{"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace bts { namespace rpc { \n\n namespace detail \n {\n class rpc_client_impl : public bts::rpc_stubs::common_api_rpc_client\n {\n public:\n fc::rpc::json_connection_ptr _json_connection;\n fc::future _json_exec_loop_complete;\n\n virtual fc::rpc::json_connection_ptr get_json_connection() const override { return _json_connection; }\n void connect_to(const fc::ip::endpoint& remote_endpoint, const blockchain::public_key_type& remote_public_key);\n bool login(const std::string& username, const std::string& password);\n };\n\n void rpc_client_impl::connect_to(const fc::ip::endpoint& remote_endpoint,\n const bts::blockchain::public_key_type& remote_public_key)\n {\n fc::buffered_istream_ptr buffered_istream;\n fc::buffered_ostream_ptr buffered_ostream;\n\n if( remote_public_key != bts::blockchain::public_key_type() )\n {\n net::stcp_socket_ptr socket = std::make_shared();\n\n try\n {\n socket->connect_to(remote_endpoint);\n }\n catch ( const fc::exception& e )\n {\n elog( \"fatal: error opening RPC socket to endpoint ${endpoint}: ${e}\", (\"endpoint\", remote_endpoint)(\"e\", e.to_detail_string() ) );\n throw;\n }\n\n fc::ecc::compact_signature signature;\n fc::raw::unpack(*socket, signature);\n wdump((signature));\n FC_ASSERT(blockchain::public_key_type(fc::ecc::public_key(signature, fc::digest(socket->get_shared_secret())))\n == remote_public_key,\n \"Unable to establish secure connection with server.\");\n\n buffered_istream = std::make_shared(socket);\n buffered_ostream = std::make_shared>(socket);\n } else {\n fc::tcp_socket_ptr socket = std::make_shared();\n\n try\n {\n socket->connect_to(remote_endpoint);\n }\n catch ( const fc::exception& e )\n {\n elog( \"fatal: error opening RPC socket to endpoint ${endpoint}: ${e}\", (\"endpoint\", remote_endpoint)(\"e\", e.to_detail_string() ) );\n throw;\n }\n\n buffered_istream = std::make_shared(socket);\n buffered_ostream = std::make_shared(socket);\n }\n\n _json_connection = std::make_shared(std::move(buffered_istream),\n std::move(buffered_ostream));\n _json_exec_loop_complete = fc::async([=](){ _json_connection->exec(); }, \"json exec loop\");\n }\n bool rpc_client_impl::login(const std::string& username, const std::string& password)\n {\n return _json_connection->call(\"login\", username, password);\n }\n\n } \/\/ end namespace detail\n\n\n rpc_client::rpc_client() :\n my(new detail::rpc_client_impl)\n {\n }\n\n rpc_client::~rpc_client()\n {\n }\n\n void rpc_client::connect_to(const fc::ip::endpoint& remote_endpoint,\n const bts::blockchain::public_key_type& remote_public_key)\n {\n my->connect_to(remote_endpoint, remote_public_key);\n }\n\n bool rpc_client::login(const std::string& username, const std::string& password)\n {\n return my->login(username, password);\n }\n \n fc::rpc::json_connection_ptr rpc_client::get_json_connection() const\n {\n return my->_json_connection;\n }\n\n} } \/\/ bts::rpc\nAttempt to fix crash on exit#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace bts { namespace rpc { \n\n namespace detail \n {\n class rpc_client_impl : public bts::rpc_stubs::common_api_rpc_client\n {\n public:\n fc::rpc::json_connection_ptr _json_connection;\n fc::future _json_exec_loop_complete;\n\n virtual fc::rpc::json_connection_ptr get_json_connection() const override { return _json_connection; }\n void connect_to(const fc::ip::endpoint& remote_endpoint, const blockchain::public_key_type& remote_public_key);\n bool login(const std::string& username, const std::string& password);\n };\n\n void rpc_client_impl::connect_to(const fc::ip::endpoint& remote_endpoint,\n const bts::blockchain::public_key_type& remote_public_key)\n {\n fc::buffered_istream_ptr buffered_istream;\n fc::buffered_ostream_ptr buffered_ostream;\n\n if( remote_public_key != bts::blockchain::public_key_type() )\n {\n net::stcp_socket_ptr socket = std::make_shared();\n\n try\n {\n socket->connect_to(remote_endpoint);\n }\n catch ( const fc::exception& e )\n {\n elog( \"fatal: error opening RPC socket to endpoint ${endpoint}: ${e}\", (\"endpoint\", remote_endpoint)(\"e\", e.to_detail_string() ) );\n throw;\n }\n\n fc::ecc::compact_signature signature;\n fc::raw::unpack(*socket, signature);\n wdump((signature));\n FC_ASSERT(blockchain::public_key_type(fc::ecc::public_key(signature, fc::digest(socket->get_shared_secret())))\n == remote_public_key,\n \"Unable to establish secure connection with server.\");\n\n buffered_istream = std::make_shared(socket);\n buffered_ostream = std::make_shared>(socket);\n } else {\n fc::tcp_socket_ptr socket = std::make_shared();\n\n try\n {\n socket->connect_to(remote_endpoint);\n }\n catch ( const fc::exception& e )\n {\n elog( \"fatal: error opening RPC socket to endpoint ${endpoint}: ${e}\", (\"endpoint\", remote_endpoint)(\"e\", e.to_detail_string() ) );\n throw;\n }\n\n buffered_istream = std::make_shared(socket);\n buffered_ostream = std::make_shared(socket);\n }\n\n _json_connection = std::make_shared(std::move(buffered_istream),\n std::move(buffered_ostream));\n _json_exec_loop_complete = fc::async([=](){ _json_connection->exec(); }, \"json exec loop\");\n }\n bool rpc_client_impl::login(const std::string& username, const std::string& password)\n {\n return _json_connection->call(\"login\", username, password);\n }\n\n } \/\/ end namespace detail\n\n\n rpc_client::rpc_client() :\n my(new detail::rpc_client_impl)\n {\n }\n\n rpc_client::~rpc_client()\n {\n try\n {\n my->_json_exec_loop_complete.cancel_and_wait(\"~rpc_client()\");\n } catch (const fc::exception& e) {\n wlog(\"Caught exception ${e} while canceling json_connection exec loop\", (\"e\", e));\n }\n }\n\n void rpc_client::connect_to(const fc::ip::endpoint& remote_endpoint,\n const bts::blockchain::public_key_type& remote_public_key)\n {\n my->connect_to(remote_endpoint, remote_public_key);\n }\n\n bool rpc_client::login(const std::string& username, const std::string& password)\n {\n return my->login(username, password);\n }\n \n fc::rpc::json_connection_ptr rpc_client::get_json_connection() const\n {\n return my->_json_connection;\n }\n\n} } \/\/ bts::rpc\n<|endoftext|>"} {"text":"Replace the NOTIMPLEMENTED() in NPN_ForceRedraw with a comment<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"webkit\/glue\/plugins\/plugin_list.h\"\n\n#include \n\n#include \"base\/command_line.h\"\n#include \"base\/lazy_instance.h\"\n#include \"base\/logging.h\"\n#include \"base\/string_split.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/time.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"net\/base\/mime_util.h\"\n#include \"webkit\/glue\/plugins\/plugin_constants_win.h\"\n#include \"webkit\/glue\/plugins\/plugin_lib.h\"\n#include \"webkit\/glue\/plugins\/plugin_switches.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n\nnamespace NPAPI {\n\nbase::LazyInstance g_singleton(base::LINKER_INITIALIZED);\n\n\/\/ static\nPluginList* PluginList::Singleton() {\n return g_singleton.Pointer();\n}\n\n\/\/ static\nbool PluginList::DebugPluginLoading() {\n return CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kDebugPluginLoading);\n}\n\nbool PluginList::PluginsLoaded() {\n AutoLock lock(lock_);\n return plugins_loaded_;\n}\n\nvoid PluginList::RefreshPlugins() {\n AutoLock lock(lock_);\n plugins_need_refresh_ = true;\n}\n\nvoid PluginList::AddExtraPluginPath(const FilePath& plugin_path) {\n \/\/ Chrome OS only loads plugins from \/opt\/google\/chrome\/plugins.\n#if !defined(OS_CHROMEOS)\n AutoLock lock(lock_);\n extra_plugin_paths_.push_back(plugin_path);\n#endif\n}\n\nvoid PluginList::RemoveExtraPluginPath(const FilePath& plugin_path) {\n AutoLock lock(lock_);\n std::vector::iterator it =\n std::find(extra_plugin_paths_.begin(), extra_plugin_paths_.end(),\n plugin_path);\n if (it != extra_plugin_paths_.end())\n extra_plugin_paths_.erase(it);\n}\n\nvoid PluginList::AddExtraPluginDir(const FilePath& plugin_dir) {\n \/\/ Chrome OS only loads plugins from \/opt\/google\/chrome\/plugins.\n#if !defined(OS_CHROMEOS)\n AutoLock lock(lock_);\n extra_plugin_dirs_.push_back(plugin_dir);\n#endif\n}\n\nvoid PluginList::RegisterInternalPlugin(const PluginVersionInfo& info) {\n AutoLock lock(lock_);\n internal_plugins_.push_back(info);\n}\n\nvoid PluginList::UnregisterInternalPlugin(const FilePath& path) {\n AutoLock lock(lock_);\n for (size_t i = 0; i < internal_plugins_.size(); i++) {\n if (internal_plugins_[i].path == path) {\n internal_plugins_.erase(internal_plugins_.begin() + i);\n return;\n }\n }\n NOTREACHED();\n}\n\nbool PluginList::ReadPluginInfo(const FilePath& filename,\n WebPluginInfo* info,\n const PluginEntryPoints** entry_points) {\n {\n AutoLock lock(lock_);\n for (size_t i = 0; i < internal_plugins_.size(); ++i) {\n if (filename == internal_plugins_[i].path) {\n *entry_points = &internal_plugins_[i].entry_points;\n return CreateWebPluginInfo(internal_plugins_[i], info);\n }\n }\n }\n\n \/\/ Not an internal plugin.\n *entry_points = NULL;\n\n return PluginLib::ReadWebPluginInfo(filename, info);\n}\n\nbool PluginList::CreateWebPluginInfo(const PluginVersionInfo& pvi,\n WebPluginInfo* info) {\n std::vector mime_types, file_extensions;\n std::vector descriptions;\n SplitString(WideToUTF8(pvi.mime_types), '|', &mime_types);\n SplitString(WideToUTF8(pvi.file_extensions), '|', &file_extensions);\n SplitString(WideToUTF16(pvi.type_descriptions), '|', &descriptions);\n\n info->mime_types.clear();\n\n if (mime_types.empty()) {\n LOG_IF(ERROR, PluginList::DebugPluginLoading())\n << \"Plugin \" << pvi.product_name << \" has no MIME types, skipping\";\n return false;\n }\n\n info->name = WideToUTF16(pvi.product_name);\n info->desc = WideToUTF16(pvi.file_description);\n info->version = WideToUTF16(pvi.file_version);\n info->path = pvi.path;\n info->enabled = true;\n\n for (size_t i = 0; i < mime_types.size(); ++i) {\n WebPluginMimeType mime_type;\n mime_type.mime_type = StringToLowerASCII(mime_types[i]);\n if (file_extensions.size() > i)\n SplitString(file_extensions[i], ',', &mime_type.file_extensions);\n\n if (descriptions.size() > i) {\n mime_type.description = descriptions[i];\n\n \/\/ On Windows, the description likely has a list of file extensions\n \/\/ embedded in it (e.g. \"SurfWriter file (*.swr)\"). Remove an extension\n \/\/ list from the description if it is present.\n size_t ext = mime_type.description.find(ASCIIToUTF16(\"(*\"));\n if (ext != string16::npos) {\n if (ext > 1 && mime_type.description[ext -1] == ' ')\n ext--;\n\n mime_type.description.erase(ext);\n }\n }\n\n info->mime_types.push_back(mime_type);\n }\n\n return true;\n}\n\nPluginList::PluginList()\n : plugins_loaded_(false), plugins_need_refresh_(false) {\n PlatformInit();\n}\n\nvoid PluginList::LoadPlugins(bool refresh) {\n \/\/ Don't want to hold the lock while loading new plugins, so we don't block\n \/\/ other methods if they're called on other threads.\n std::vector extra_plugin_paths;\n std::vector extra_plugin_dirs;\n std::vector internal_plugins;\n {\n AutoLock lock(lock_);\n if (plugins_loaded_ && !refresh && !plugins_need_refresh_)\n return;\n\n \/\/ Clear the refresh bit now, because it might get set again before we\n \/\/ reach the end of the method.\n plugins_need_refresh_ = false;\n extra_plugin_paths = extra_plugin_paths_;\n extra_plugin_dirs = extra_plugin_dirs_;\n internal_plugins = internal_plugins_;\n }\n\n base::TimeTicks start_time = base::TimeTicks::Now();\n\n std::vector new_plugins;\n std::set visited_plugins;\n\n std::vector directories_to_scan;\n GetPluginDirectories(&directories_to_scan);\n\n \/\/ Load internal plugins first so that, if both an internal plugin and a\n \/\/ \"discovered\" plugin want to handle the same type, the internal plugin\n \/\/ will have precedence.\n for (size_t i = 0; i < internal_plugins.size(); ++i) {\n if (internal_plugins[i].path.value() == kDefaultPluginLibraryName)\n continue;\n LoadPlugin(internal_plugins[i].path, &new_plugins);\n }\n\n for (size_t i = 0; i < extra_plugin_paths.size(); ++i) {\n const FilePath& path = extra_plugin_paths[i];\n if (visited_plugins.find(path) != visited_plugins.end())\n continue;\n LoadPlugin(path, &new_plugins);\n visited_plugins.insert(path);\n }\n\n for (size_t i = 0; i < extra_plugin_dirs.size(); ++i) {\n LoadPluginsFromDir(extra_plugin_dirs[i], &new_plugins, &visited_plugins);\n }\n\n for (size_t i = 0; i < directories_to_scan.size(); ++i) {\n LoadPluginsFromDir(directories_to_scan[i], &new_plugins, &visited_plugins);\n }\n\n#if defined OS_WIN\n LoadPluginsFromRegistry(&new_plugins, &visited_plugins);\n#endif\n\n \/\/ Load the default plugin last.\n if (webkit_glue::IsDefaultPluginEnabled())\n LoadPlugin(FilePath(kDefaultPluginLibraryName), &new_plugins);\n\n base::TimeTicks end_time = base::TimeTicks::Now();\n base::TimeDelta elapsed = end_time - start_time;\n DLOG(INFO) << \"Loaded plugin list in \" << elapsed.InMilliseconds() << \" ms.\";\n\n \/\/ Only update the data now since loading plugins can take a while.\n AutoLock lock(lock_);\n\n \/\/ Go through and mark new plugins in the disabled list as, well, disabled.\n for (std::vector::iterator it = new_plugins.begin();\n it != new_plugins.end();\n ++it) {\n if (disabled_plugins_.find(it->path) != disabled_plugins_.end())\n it->enabled = false;\n }\n\n plugins_ = new_plugins;\n plugins_loaded_ = true;\n}\n\nvoid PluginList::LoadPlugin(const FilePath& path,\n std::vector* plugins) {\n LOG_IF(ERROR, PluginList::DebugPluginLoading())\n << \"Loading plugin \" << path.value();\n\n WebPluginInfo plugin_info;\n const PluginEntryPoints* entry_points;\n\n if (!ReadPluginInfo(path, &plugin_info, &entry_points))\n return;\n\n if (!ShouldLoadPlugin(plugin_info, plugins))\n return;\n\n if (path.value() != kDefaultPluginLibraryName\n#if defined(OS_WIN) && !defined(NDEBUG)\n && path.BaseName().value() != L\"npspy.dll\" \/\/ Make an exception for NPSPY\n#endif\n ) {\n for (size_t i = 0; i < plugin_info.mime_types.size(); ++i) {\n \/\/ TODO: don't load global handlers for now.\n \/\/ WebKit hands to the Plugin before it tries\n \/\/ to handle mimeTypes on its own.\n const std::string &mime_type = plugin_info.mime_types[i].mime_type;\n if (mime_type == \"*\" )\n return;\n }\n }\n\n plugins->push_back(plugin_info);\n}\n\nbool PluginList::FindPlugin(const std::string& mime_type,\n bool allow_wildcard,\n WebPluginInfo* info) {\n DCHECK(mime_type == StringToLowerASCII(mime_type));\n\n LoadPlugins(false);\n AutoLock lock(lock_);\n for (size_t i = 0; i < plugins_.size(); ++i) {\n if (plugins_[i].enabled &&\n SupportsType(plugins_[i], mime_type, allow_wildcard)) {\n *info = plugins_[i];\n return true;\n }\n }\n\n return false;\n}\n\nbool PluginList::FindDisabledPlugin(const std::string& mime_type,\n bool allow_wildcard,\n WebPluginInfo* info) {\n DCHECK(mime_type == StringToLowerASCII(mime_type));\n\n LoadPlugins(false);\n AutoLock lock(lock_);\n for (size_t i = 0; i < plugins_.size(); ++i) {\n if (!plugins_[i].enabled &&\n SupportsType(plugins_[i], mime_type, allow_wildcard)) {\n *info = plugins_[i];\n return true;\n }\n }\n\n return false;\n}\n\nbool PluginList::FindPlugin(const GURL &url,\n std::string* actual_mime_type,\n WebPluginInfo* info) {\n LoadPlugins(false);\n AutoLock lock(lock_);\n std::string path = url.path();\n std::string::size_type last_dot = path.rfind('.');\n if (last_dot == std::string::npos)\n return false;\n\n std::string extension = StringToLowerASCII(std::string(path, last_dot+1));\n\n for (size_t i = 0; i < plugins_.size(); ++i) {\n if (plugins_[i].enabled &&\n SupportsExtension(plugins_[i], extension, actual_mime_type)) {\n *info = plugins_[i];\n return true;\n }\n }\n\n return false;\n}\n\nbool PluginList::SupportsType(const WebPluginInfo& info,\n const std::string &mime_type,\n bool allow_wildcard) {\n \/\/ Webkit will ask for a plugin to handle empty mime types.\n if (mime_type.empty())\n return false;\n\n for (size_t i = 0; i < info.mime_types.size(); ++i) {\n const WebPluginMimeType& mime_info = info.mime_types[i];\n if (net::MatchesMimeType(mime_info.mime_type, mime_type)) {\n if (!allow_wildcard && mime_info.mime_type == \"*\") {\n continue;\n }\n return true;\n }\n }\n return false;\n}\n\nbool PluginList::SupportsExtension(const WebPluginInfo& info,\n const std::string &extension,\n std::string* actual_mime_type) {\n for (size_t i = 0; i < info.mime_types.size(); ++i) {\n const WebPluginMimeType& mime_type = info.mime_types[i];\n for (size_t j = 0; j < mime_type.file_extensions.size(); ++j) {\n if (mime_type.file_extensions[j] == extension) {\n if (actual_mime_type)\n *actual_mime_type = mime_type.mime_type;\n return true;\n }\n }\n }\n\n return false;\n}\n\n\nvoid PluginList::GetPlugins(bool refresh, std::vector* plugins) {\n LoadPlugins(refresh);\n\n AutoLock lock(lock_);\n *plugins = plugins_;\n}\n\nvoid PluginList::GetEnabledPlugins(bool refresh,\n std::vector* plugins) {\n LoadPlugins(refresh);\n\n plugins->clear();\n AutoLock lock(lock_);\n for (std::vector::const_iterator it = plugins_.begin();\n it != plugins_.end();\n ++it) {\n if (it->enabled)\n plugins->push_back(*it);\n }\n}\n\nbool PluginList::GetPluginInfo(const GURL& url,\n const std::string& mime_type,\n bool allow_wildcard,\n WebPluginInfo* info,\n std::string* actual_mime_type) {\n bool found = FindPlugin(mime_type, allow_wildcard, info);\n if (!found || (info->path.value() == kDefaultPluginLibraryName)) {\n if (FindPlugin(url, actual_mime_type, info) ||\n FindDisabledPlugin(mime_type, allow_wildcard, info)) {\n found = true;\n }\n }\n\n return found;\n}\n\nbool PluginList::GetPluginInfoByPath(const FilePath& plugin_path,\n WebPluginInfo* info) {\n LoadPlugins(false);\n AutoLock lock(lock_);\n for (size_t i = 0; i < plugins_.size(); ++i) {\n if (plugins_[i].path == plugin_path) {\n *info = plugins_[i];\n return true;\n }\n }\n\n return false;\n}\n\nbool PluginList::EnablePlugin(const FilePath& filename) {\n AutoLock lock(lock_);\n\n bool did_enable = false;\n\n std::set::iterator entry = disabled_plugins_.find(filename);\n if (entry == disabled_plugins_.end())\n return did_enable; \/\/ Early exit if plugin not in disabled list.\n\n disabled_plugins_.erase(entry); \/\/ Remove from disabled list.\n\n \/\/ Set enabled flags if necessary.\n for (std::vector::iterator it = plugins_.begin();\n it != plugins_.end();\n ++it) {\n if (it->path == filename) {\n DCHECK(!it->enabled); \/\/ Should have been disabled.\n it->enabled = true;\n did_enable = true;\n }\n }\n\n return did_enable;\n}\n\nbool PluginList::DisablePlugin(const FilePath& filename) {\n AutoLock lock(lock_);\n\n bool did_disable = false;\n\n if (disabled_plugins_.find(filename) != disabled_plugins_.end())\n return did_disable; \/\/ Early exit if plugin already in disabled list.\n\n disabled_plugins_.insert(filename); \/\/ Add to disabled list.\n\n \/\/ Unset enabled flags if necessary.\n for (std::vector::iterator it = plugins_.begin();\n it != plugins_.end();\n ++it) {\n if (it->path == filename) {\n DCHECK(it->enabled); \/\/ Should have been enabled.\n it->enabled = false;\n did_disable = true;\n }\n }\n\n return did_disable;\n}\n\nvoid PluginList::Shutdown() {\n \/\/ TODO\n}\n\n} \/\/ namespace NPAPI\nReduce console DLOG(INFO) spam in plugin_list\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"webkit\/glue\/plugins\/plugin_list.h\"\n\n#include \n\n#include \"base\/command_line.h\"\n#include \"base\/lazy_instance.h\"\n#include \"base\/logging.h\"\n#include \"base\/string_split.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"net\/base\/mime_util.h\"\n#include \"webkit\/glue\/plugins\/plugin_constants_win.h\"\n#include \"webkit\/glue\/plugins\/plugin_lib.h\"\n#include \"webkit\/glue\/plugins\/plugin_switches.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n\nnamespace NPAPI {\n\nbase::LazyInstance g_singleton(base::LINKER_INITIALIZED);\n\n\/\/ static\nPluginList* PluginList::Singleton() {\n return g_singleton.Pointer();\n}\n\n\/\/ static\nbool PluginList::DebugPluginLoading() {\n return CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kDebugPluginLoading);\n}\n\nbool PluginList::PluginsLoaded() {\n AutoLock lock(lock_);\n return plugins_loaded_;\n}\n\nvoid PluginList::RefreshPlugins() {\n AutoLock lock(lock_);\n plugins_need_refresh_ = true;\n}\n\nvoid PluginList::AddExtraPluginPath(const FilePath& plugin_path) {\n \/\/ Chrome OS only loads plugins from \/opt\/google\/chrome\/plugins.\n#if !defined(OS_CHROMEOS)\n AutoLock lock(lock_);\n extra_plugin_paths_.push_back(plugin_path);\n#endif\n}\n\nvoid PluginList::RemoveExtraPluginPath(const FilePath& plugin_path) {\n AutoLock lock(lock_);\n std::vector::iterator it =\n std::find(extra_plugin_paths_.begin(), extra_plugin_paths_.end(),\n plugin_path);\n if (it != extra_plugin_paths_.end())\n extra_plugin_paths_.erase(it);\n}\n\nvoid PluginList::AddExtraPluginDir(const FilePath& plugin_dir) {\n \/\/ Chrome OS only loads plugins from \/opt\/google\/chrome\/plugins.\n#if !defined(OS_CHROMEOS)\n AutoLock lock(lock_);\n extra_plugin_dirs_.push_back(plugin_dir);\n#endif\n}\n\nvoid PluginList::RegisterInternalPlugin(const PluginVersionInfo& info) {\n AutoLock lock(lock_);\n internal_plugins_.push_back(info);\n}\n\nvoid PluginList::UnregisterInternalPlugin(const FilePath& path) {\n AutoLock lock(lock_);\n for (size_t i = 0; i < internal_plugins_.size(); i++) {\n if (internal_plugins_[i].path == path) {\n internal_plugins_.erase(internal_plugins_.begin() + i);\n return;\n }\n }\n NOTREACHED();\n}\n\nbool PluginList::ReadPluginInfo(const FilePath& filename,\n WebPluginInfo* info,\n const PluginEntryPoints** entry_points) {\n {\n AutoLock lock(lock_);\n for (size_t i = 0; i < internal_plugins_.size(); ++i) {\n if (filename == internal_plugins_[i].path) {\n *entry_points = &internal_plugins_[i].entry_points;\n return CreateWebPluginInfo(internal_plugins_[i], info);\n }\n }\n }\n\n \/\/ Not an internal plugin.\n *entry_points = NULL;\n\n return PluginLib::ReadWebPluginInfo(filename, info);\n}\n\nbool PluginList::CreateWebPluginInfo(const PluginVersionInfo& pvi,\n WebPluginInfo* info) {\n std::vector mime_types, file_extensions;\n std::vector descriptions;\n SplitString(WideToUTF8(pvi.mime_types), '|', &mime_types);\n SplitString(WideToUTF8(pvi.file_extensions), '|', &file_extensions);\n SplitString(WideToUTF16(pvi.type_descriptions), '|', &descriptions);\n\n info->mime_types.clear();\n\n if (mime_types.empty()) {\n LOG_IF(ERROR, PluginList::DebugPluginLoading())\n << \"Plugin \" << pvi.product_name << \" has no MIME types, skipping\";\n return false;\n }\n\n info->name = WideToUTF16(pvi.product_name);\n info->desc = WideToUTF16(pvi.file_description);\n info->version = WideToUTF16(pvi.file_version);\n info->path = pvi.path;\n info->enabled = true;\n\n for (size_t i = 0; i < mime_types.size(); ++i) {\n WebPluginMimeType mime_type;\n mime_type.mime_type = StringToLowerASCII(mime_types[i]);\n if (file_extensions.size() > i)\n SplitString(file_extensions[i], ',', &mime_type.file_extensions);\n\n if (descriptions.size() > i) {\n mime_type.description = descriptions[i];\n\n \/\/ On Windows, the description likely has a list of file extensions\n \/\/ embedded in it (e.g. \"SurfWriter file (*.swr)\"). Remove an extension\n \/\/ list from the description if it is present.\n size_t ext = mime_type.description.find(ASCIIToUTF16(\"(*\"));\n if (ext != string16::npos) {\n if (ext > 1 && mime_type.description[ext -1] == ' ')\n ext--;\n\n mime_type.description.erase(ext);\n }\n }\n\n info->mime_types.push_back(mime_type);\n }\n\n return true;\n}\n\nPluginList::PluginList()\n : plugins_loaded_(false), plugins_need_refresh_(false) {\n PlatformInit();\n}\n\nvoid PluginList::LoadPlugins(bool refresh) {\n \/\/ Don't want to hold the lock while loading new plugins, so we don't block\n \/\/ other methods if they're called on other threads.\n std::vector extra_plugin_paths;\n std::vector extra_plugin_dirs;\n std::vector internal_plugins;\n {\n AutoLock lock(lock_);\n if (plugins_loaded_ && !refresh && !plugins_need_refresh_)\n return;\n\n \/\/ Clear the refresh bit now, because it might get set again before we\n \/\/ reach the end of the method.\n plugins_need_refresh_ = false;\n extra_plugin_paths = extra_plugin_paths_;\n extra_plugin_dirs = extra_plugin_dirs_;\n internal_plugins = internal_plugins_;\n }\n\n std::vector new_plugins;\n std::set visited_plugins;\n\n std::vector directories_to_scan;\n GetPluginDirectories(&directories_to_scan);\n\n \/\/ Load internal plugins first so that, if both an internal plugin and a\n \/\/ \"discovered\" plugin want to handle the same type, the internal plugin\n \/\/ will have precedence.\n for (size_t i = 0; i < internal_plugins.size(); ++i) {\n if (internal_plugins[i].path.value() == kDefaultPluginLibraryName)\n continue;\n LoadPlugin(internal_plugins[i].path, &new_plugins);\n }\n\n for (size_t i = 0; i < extra_plugin_paths.size(); ++i) {\n const FilePath& path = extra_plugin_paths[i];\n if (visited_plugins.find(path) != visited_plugins.end())\n continue;\n LoadPlugin(path, &new_plugins);\n visited_plugins.insert(path);\n }\n\n for (size_t i = 0; i < extra_plugin_dirs.size(); ++i) {\n LoadPluginsFromDir(extra_plugin_dirs[i], &new_plugins, &visited_plugins);\n }\n\n for (size_t i = 0; i < directories_to_scan.size(); ++i) {\n LoadPluginsFromDir(directories_to_scan[i], &new_plugins, &visited_plugins);\n }\n\n#if defined OS_WIN\n LoadPluginsFromRegistry(&new_plugins, &visited_plugins);\n#endif\n\n \/\/ Load the default plugin last.\n if (webkit_glue::IsDefaultPluginEnabled())\n LoadPlugin(FilePath(kDefaultPluginLibraryName), &new_plugins);\n\n \/\/ Only update the data now since loading plugins can take a while.\n AutoLock lock(lock_);\n\n \/\/ Go through and mark new plugins in the disabled list as, well, disabled.\n for (std::vector::iterator it = new_plugins.begin();\n it != new_plugins.end();\n ++it) {\n if (disabled_plugins_.find(it->path) != disabled_plugins_.end())\n it->enabled = false;\n }\n\n plugins_ = new_plugins;\n plugins_loaded_ = true;\n}\n\nvoid PluginList::LoadPlugin(const FilePath& path,\n std::vector* plugins) {\n LOG_IF(ERROR, PluginList::DebugPluginLoading())\n << \"Loading plugin \" << path.value();\n\n WebPluginInfo plugin_info;\n const PluginEntryPoints* entry_points;\n\n if (!ReadPluginInfo(path, &plugin_info, &entry_points))\n return;\n\n if (!ShouldLoadPlugin(plugin_info, plugins))\n return;\n\n if (path.value() != kDefaultPluginLibraryName\n#if defined(OS_WIN) && !defined(NDEBUG)\n && path.BaseName().value() != L\"npspy.dll\" \/\/ Make an exception for NPSPY\n#endif\n ) {\n for (size_t i = 0; i < plugin_info.mime_types.size(); ++i) {\n \/\/ TODO: don't load global handlers for now.\n \/\/ WebKit hands to the Plugin before it tries\n \/\/ to handle mimeTypes on its own.\n const std::string &mime_type = plugin_info.mime_types[i].mime_type;\n if (mime_type == \"*\" )\n return;\n }\n }\n\n plugins->push_back(plugin_info);\n}\n\nbool PluginList::FindPlugin(const std::string& mime_type,\n bool allow_wildcard,\n WebPluginInfo* info) {\n DCHECK(mime_type == StringToLowerASCII(mime_type));\n\n LoadPlugins(false);\n AutoLock lock(lock_);\n for (size_t i = 0; i < plugins_.size(); ++i) {\n if (plugins_[i].enabled &&\n SupportsType(plugins_[i], mime_type, allow_wildcard)) {\n *info = plugins_[i];\n return true;\n }\n }\n\n return false;\n}\n\nbool PluginList::FindDisabledPlugin(const std::string& mime_type,\n bool allow_wildcard,\n WebPluginInfo* info) {\n DCHECK(mime_type == StringToLowerASCII(mime_type));\n\n LoadPlugins(false);\n AutoLock lock(lock_);\n for (size_t i = 0; i < plugins_.size(); ++i) {\n if (!plugins_[i].enabled &&\n SupportsType(plugins_[i], mime_type, allow_wildcard)) {\n *info = plugins_[i];\n return true;\n }\n }\n\n return false;\n}\n\nbool PluginList::FindPlugin(const GURL &url,\n std::string* actual_mime_type,\n WebPluginInfo* info) {\n LoadPlugins(false);\n AutoLock lock(lock_);\n std::string path = url.path();\n std::string::size_type last_dot = path.rfind('.');\n if (last_dot == std::string::npos)\n return false;\n\n std::string extension = StringToLowerASCII(std::string(path, last_dot+1));\n\n for (size_t i = 0; i < plugins_.size(); ++i) {\n if (plugins_[i].enabled &&\n SupportsExtension(plugins_[i], extension, actual_mime_type)) {\n *info = plugins_[i];\n return true;\n }\n }\n\n return false;\n}\n\nbool PluginList::SupportsType(const WebPluginInfo& info,\n const std::string &mime_type,\n bool allow_wildcard) {\n \/\/ Webkit will ask for a plugin to handle empty mime types.\n if (mime_type.empty())\n return false;\n\n for (size_t i = 0; i < info.mime_types.size(); ++i) {\n const WebPluginMimeType& mime_info = info.mime_types[i];\n if (net::MatchesMimeType(mime_info.mime_type, mime_type)) {\n if (!allow_wildcard && mime_info.mime_type == \"*\") {\n continue;\n }\n return true;\n }\n }\n return false;\n}\n\nbool PluginList::SupportsExtension(const WebPluginInfo& info,\n const std::string &extension,\n std::string* actual_mime_type) {\n for (size_t i = 0; i < info.mime_types.size(); ++i) {\n const WebPluginMimeType& mime_type = info.mime_types[i];\n for (size_t j = 0; j < mime_type.file_extensions.size(); ++j) {\n if (mime_type.file_extensions[j] == extension) {\n if (actual_mime_type)\n *actual_mime_type = mime_type.mime_type;\n return true;\n }\n }\n }\n\n return false;\n}\n\n\nvoid PluginList::GetPlugins(bool refresh, std::vector* plugins) {\n LoadPlugins(refresh);\n\n AutoLock lock(lock_);\n *plugins = plugins_;\n}\n\nvoid PluginList::GetEnabledPlugins(bool refresh,\n std::vector* plugins) {\n LoadPlugins(refresh);\n\n plugins->clear();\n AutoLock lock(lock_);\n for (std::vector::const_iterator it = plugins_.begin();\n it != plugins_.end();\n ++it) {\n if (it->enabled)\n plugins->push_back(*it);\n }\n}\n\nbool PluginList::GetPluginInfo(const GURL& url,\n const std::string& mime_type,\n bool allow_wildcard,\n WebPluginInfo* info,\n std::string* actual_mime_type) {\n bool found = FindPlugin(mime_type, allow_wildcard, info);\n if (!found || (info->path.value() == kDefaultPluginLibraryName)) {\n if (FindPlugin(url, actual_mime_type, info) ||\n FindDisabledPlugin(mime_type, allow_wildcard, info)) {\n found = true;\n }\n }\n\n return found;\n}\n\nbool PluginList::GetPluginInfoByPath(const FilePath& plugin_path,\n WebPluginInfo* info) {\n LoadPlugins(false);\n AutoLock lock(lock_);\n for (size_t i = 0; i < plugins_.size(); ++i) {\n if (plugins_[i].path == plugin_path) {\n *info = plugins_[i];\n return true;\n }\n }\n\n return false;\n}\n\nbool PluginList::EnablePlugin(const FilePath& filename) {\n AutoLock lock(lock_);\n\n bool did_enable = false;\n\n std::set::iterator entry = disabled_plugins_.find(filename);\n if (entry == disabled_plugins_.end())\n return did_enable; \/\/ Early exit if plugin not in disabled list.\n\n disabled_plugins_.erase(entry); \/\/ Remove from disabled list.\n\n \/\/ Set enabled flags if necessary.\n for (std::vector::iterator it = plugins_.begin();\n it != plugins_.end();\n ++it) {\n if (it->path == filename) {\n DCHECK(!it->enabled); \/\/ Should have been disabled.\n it->enabled = true;\n did_enable = true;\n }\n }\n\n return did_enable;\n}\n\nbool PluginList::DisablePlugin(const FilePath& filename) {\n AutoLock lock(lock_);\n\n bool did_disable = false;\n\n if (disabled_plugins_.find(filename) != disabled_plugins_.end())\n return did_disable; \/\/ Early exit if plugin already in disabled list.\n\n disabled_plugins_.insert(filename); \/\/ Add to disabled list.\n\n \/\/ Unset enabled flags if necessary.\n for (std::vector::iterator it = plugins_.begin();\n it != plugins_.end();\n ++it) {\n if (it->path == filename) {\n DCHECK(it->enabled); \/\/ Should have been enabled.\n it->enabled = false;\n did_disable = true;\n }\n }\n\n return did_disable;\n}\n\nvoid PluginList::Shutdown() {\n \/\/ TODO\n}\n\n} \/\/ namespace NPAPI\n<|endoftext|>"} {"text":"#include \"scanner.hpp\"\n#include \"compiler_error.hpp\"\n#include \n\n\nnamespace p0\n{\n\tnamespace\n\t{\n\t\tbool is_whitespace(char c)\n\t\t{\n\t\t\tswitch (c)\n\t\t\t{\n\t\t\tcase ' ':\n\t\t\tcase '\\t':\n\t\t\tcase '\\n':\n\t\t\tcase '\\r':\n\t\t\t\treturn true;\n\n\t\t\tdefault:\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tbool is_identifer_first(char c)\n\t\t{\n\t\t\tc = std::tolower(c);\n\t\t\treturn\n\t\t\t\t((c >= 'a') && (c <= 'z')) ||\n\t\t\t\t(c == '_');\n\t\t}\n\n\t\tbool is_digit_10(char c)\n\t\t{\n\t\t\treturn ((c >= '0') && (c <= '9'));\n\t\t}\n\n\t\tbool is_identifier_tail(char c)\n\t\t{\n\t\t\treturn\n\t\t\t\tis_identifer_first(c) ||\n\t\t\t\tis_digit_10(c);\n\t\t}\n\n\t\tbool is_keyword(source_range content, char const *keyword)\n\t\t{\n\t\t\tfor (auto i = content.begin(); i != content.end(); ++i, ++keyword)\n\t\t\t{\n\t\t\t\tif (*i != *keyword)\n\t\t\t\t{\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn (*keyword == '\\0');\n\t\t}\n\n\t\tstruct keyword\n\t\t{\n\t\t\tchar const *content;\n\t\t\ttoken_type::Enum token;\n\t\t};\n\n\t\ttoken_type::Enum find_keyword(source_range content)\n\t\t{\n\t\t\t\/\/a rather simple (= slow) approach of finding keywords\n\t\t\tstatic std::array const keywords =\n\t\t\t{{\n\t\t\t\t{\"var\", token_type::var},\n\t\t\t\t{\"function\", token_type::function},\n\t\t\t\t{\"return\", token_type::return_},\n\t\t\t\t{\"null\", token_type::null},\n\t\t\t\t{\"if\", token_type::if_},\n\t\t\t\t{\"else\", token_type::else_},\n\t\t\t\t{\"while\", token_type::while_},\n\t\t\t\t{\"break\", token_type::break_},\n\t\t\t\t{\"continue\", token_type::continue_},\n\t\t\t}};\n\n\t\t\tusing namespace std;\n\n\t\t\tfor (auto k = begin(keywords); k != end(keywords); ++k)\n\t\t\t{\n\t\t\t\tif (is_keyword(content, k->content))\n\t\t\t\t{\n\t\t\t\t\treturn k->token;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn token_type::identifier;\n\t\t}\n\t}\n\n\n\tscanner::scanner(\n\t\tsource_range source\n\t\t)\n\t\t: m_pos(source.begin())\n\t\t, m_end(source.end())\n\t\t, m_was_integer(false)\n\t{\n\t}\n\n\ttoken scanner::next_token()\n\t{\n\t\tskip_whitespace();\n\n\t\tif (m_pos == m_end)\n\t\t{\n\t\t\treturn token(\n\t\t\t\ttoken_type::end_of_file,\n\t\t\t\tsource_range(m_end, m_end)\n\t\t\t\t);\n\t\t}\n\n\t\tswitch (*m_pos)\n\t\t{\n\t\tcase '(': return eat_single_char_token(token_type::parenthesis_left);\n\t\tcase ')': return eat_single_char_token(token_type::parenthesis_right);\n\t\tcase '{': return eat_single_char_token(token_type::brace_left);\n\t\tcase '}': return eat_single_char_token(token_type::brace_right);\n\t\tcase '[': return eat_single_char_token(token_type::bracket_left);\n\t\tcase ']': return eat_single_char_token(token_type::bracket_right);\n\t\tcase '=': return eat_single_or_double_token(token_type::assign, '=', token_type::equal);\n\t\tcase ',': return eat_single_char_token(token_type::comma);\n\t\tcase '+': return eat_single_char_token(token_type::plus);\n\t\tcase '-': return eat_single_char_token(token_type::minus);\n\t\tcase '*': return eat_single_char_token(token_type::star);\n\t\tcase '\/': return eat_single_char_token(token_type::slash);\n\t\tcase '%': return eat_single_char_token(token_type::modulo);\n\t\tcase '&': return eat_single_or_double_token(token_type::ampersand, '&', token_type::ampersands);\n\t\tcase '|': return eat_single_or_double_token(token_type::pipe, '|', token_type::pipes);\n\t\tcase '<': return eat_single_or_triple_token(token_type::less, '<', token_type::shift_left, '=', token_type::less_equal);\n\t\tcase '>': return eat_single_or_triple_token(token_type::greater, '>', token_type::shift_right, '=', token_type::greater_equal);\n\t\tcase '!': return eat_single_or_double_token(token_type::exclamation_mark, '=', token_type::not_equal);\n\t\tcase '.': return eat_single_char_token(token_type::dot);\n\t\tcase '~': return eat_single_char_token(token_type::tilde);\n\t\tcase '^': return eat_single_char_token(token_type::caret);\n\t\tcase '\"':\n\t\t\t{\n\t\t\t\t++m_pos;\n\t\t\t\tauto const string_begin = m_pos;\n\n\t\t\t\tfor (;;)\n\t\t\t\t{\n\t\t\t\t\tauto const on_unexpected_eof = [this]()\n\t\t\t\t\t{\n\t\t\t\t\t\tthrow compiler_error(\n\t\t\t\t\t\t\t\"Unexpected end of file in string literal\",\n\t\t\t\t\t\t\tsource_range(m_end, m_end)\n\t\t\t\t\t\t\t);\n\t\t\t\t\t};\n\n\t\t\t\t\tif (m_pos == m_end)\n\t\t\t\t\t{\n\t\t\t\t\t\ton_unexpected_eof();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (((*m_pos < 0x20) ||\n\t\t\t\t\t\t(*m_pos > 0x7e)) &&\n\t\t\t\t\t\t(*m_pos != '\\t'))\n\t\t\t\t\t{\n\t\t\t\t\t\tthrow compiler_error(\n\t\t\t\t\t\t\t\"This character has to be hex-encoded in a string literal\",\n\t\t\t\t\t\t\tsource_range(m_pos, m_pos + 1)\n\t\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (*m_pos == '\\\\')\n\t\t\t\t\t{\n\t\t\t\t\t\t++m_pos;\n\t\t\t\t\t\tif (m_pos == m_end)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ton_unexpected_eof();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t++m_pos;\n\t\t\t\t\t}\n\n\t\t\t\t\telse if (*m_pos == '\"')\n\t\t\t\t\t{\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t++m_pos;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tauto const string_end = m_pos;\n\t\t\t\t++m_pos;\n\n\t\t\t\treturn token(\n\t\t\t\t\ttoken_type::string,\n\t\t\t\t\tsource_range(string_begin, string_end)\n\t\t\t\t\t);\n\t\t\t}\n\n\t\tdefault:\n\t\t\tif (is_identifer_first(*m_pos))\n\t\t\t{\n\t\t\t\tif (m_was_integer)\n\t\t\t\t{\n\t\t\t\t\tthrow compiler_error(\n\t\t\t\t\t\t\"An integer may not be directly followed by an identifier or a keyword\", \n\t\t\t\t\t\tsource_range(m_pos, m_pos + 1)\n\t\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tauto const identifier_begin = m_pos;\n\t\t\t\tdo\n\t\t\t\t{\n\t\t\t\t\t++m_pos;\n\t\t\t\t}\n\t\t\t\twhile (\n\t\t\t\t\t(m_pos != m_end) &&\n\t\t\t\t\tis_identifier_tail(*m_pos));\n\t\t\t\tauto const identifier_end = m_pos;\n\n\t\t\t\tsource_range const range(\n\t\t\t\t\tidentifier_begin,\n\t\t\t\t\tidentifier_end\n\t\t\t\t\t);\n\n\t\t\t\tauto const type = find_keyword(range);\n\n\t\t\t\treturn token(\n\t\t\t\t\ttype,\n\t\t\t\t\trange\n\t\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (is_digit_10(*m_pos))\n\t\t\t{\n\t\t\t\tauto const integer_begin = m_pos;\n\t\t\t\tdo\n\t\t\t\t{\n\t\t\t\t\t++m_pos;\n\t\t\t\t}\n\t\t\t\twhile (\n\t\t\t\t\t(m_pos != m_end) &&\n\t\t\t\t\tis_digit_10(*m_pos));\n\t\t\t\tauto const integer_end = m_pos;\n\n\t\t\t\tm_was_integer = true;\n\t\t\t\treturn token(\n\t\t\t\t\ttoken_type::integer_10,\n\t\t\t\t\tsource_range(integer_begin, integer_end)\n\t\t\t\t\t);\n\t\t\t}\n\n\t\t\tthrow compiler_error(\n\t\t\t\t\"Unexpected character\",\n\t\t\t\tsource_range(m_pos, m_pos + 1)\n\t\t\t\t);\n\t\t}\n\t}\n\n\tvoid scanner::skip_line()\n\t{\n\t\twhile (\n\t\t\t(m_pos != m_end) &&\n\t\t\t(*m_pos != '\\n'))\n\t\t{\n\t\t\t++m_pos;\n\t\t}\n\t}\n\n\tsource_range scanner::rest() const\n\t{\n\t\treturn source_range(\n\t\t\tm_pos,\n\t\t\tm_end\n\t\t\t);\n\t}\n\n\n\tvoid scanner::skip_whitespace()\n\t{\n\t\twhile (m_pos != m_end)\n\t\t{\n\t\t\tif (is_whitespace(*m_pos))\n\t\t\t{\n\t\t\t\t++m_pos;\n\t\t\t\tm_was_integer = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t\/\/a comment starts with a semicolon and ends after the current line\n\t\t\tif (*m_pos == ';')\n\t\t\t{\n\t\t\t\tdo\n\t\t\t\t{\n\t\t\t\t\t++m_pos;\n\t\t\t\t}\n\t\t\t\twhile (\n\t\t\t\t\t(m_pos != m_end) &&\n\t\t\t\t\t(*m_pos != '\\n')\n\t\t\t\t\t);\n\t\t\t\tm_was_integer = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t}\n\n\ttoken scanner::eat_single_char_token(token_type::Enum type)\n\t{\n\t\t++m_pos;\n\t\treturn token(\n\t\t\ttype,\n\t\t\tsource_range((m_pos - 1), m_pos)\n\t\t\t);\n\t}\n\n\ttoken scanner::eat_single_or_double_token(\n\t\ttoken_type::Enum single_token,\n\t\tchar second_char,\n\t\ttoken_type::Enum double_token\n\t\t)\n\t{\n\t\t++m_pos;\n\n\t\tif ((m_pos != m_end) &&\n\t\t\t(*m_pos == second_char))\n\t\t{\n\t\t\t++m_pos;\n\t\t\treturn token(double_token, source_range(m_pos - 2, m_pos));\n\t\t}\n\n\t\treturn token(single_token, source_range(m_pos - 1, m_pos));\n\t}\n\n\ttoken scanner::eat_single_or_triple_token(\n\t\ttoken_type::Enum single_token,\n\t\tchar second_char_0,\n\t\ttoken_type::Enum double_token_0,\n\t\tchar second_char_1,\n\t\ttoken_type::Enum double_token_1\n\t\t)\n\t{\n\t\t++m_pos;\n\n\t\tif (m_pos != m_end)\n\t\t{\n\t\t\tif (*m_pos == second_char_0)\n\t\t\t{\n\t\t\t\t++m_pos;\n\t\t\t\treturn token(double_token_0, source_range(m_pos - 2, m_pos));\n\t\t\t}\n\t\t\tif (*m_pos == second_char_1)\n\t\t\t{\n\t\t\t\t++m_pos;\n\t\t\t\treturn token(double_token_1, source_range(m_pos - 2, m_pos));\n\t\t\t}\n\t\t}\n\n\t\treturn token(single_token, source_range(m_pos - 1, m_pos));\n\t}\n}\ninteger followed by identifier\/keyword fixed#include \"scanner.hpp\"\n#include \"compiler_error.hpp\"\n#include \n\n\nnamespace p0\n{\n\tnamespace\n\t{\n\t\tbool is_whitespace(char c)\n\t\t{\n\t\t\tswitch (c)\n\t\t\t{\n\t\t\tcase ' ':\n\t\t\tcase '\\t':\n\t\t\tcase '\\n':\n\t\t\tcase '\\r':\n\t\t\t\treturn true;\n\n\t\t\tdefault:\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tbool is_identifer_first(char c)\n\t\t{\n\t\t\tc = std::tolower(c);\n\t\t\treturn\n\t\t\t\t((c >= 'a') && (c <= 'z')) ||\n\t\t\t\t(c == '_');\n\t\t}\n\n\t\tbool is_digit_10(char c)\n\t\t{\n\t\t\treturn ((c >= '0') && (c <= '9'));\n\t\t}\n\n\t\tbool is_identifier_tail(char c)\n\t\t{\n\t\t\treturn\n\t\t\t\tis_identifer_first(c) ||\n\t\t\t\tis_digit_10(c);\n\t\t}\n\n\t\tbool is_keyword(source_range content, char const *keyword)\n\t\t{\n\t\t\tfor (auto i = content.begin(); i != content.end(); ++i, ++keyword)\n\t\t\t{\n\t\t\t\tif (*i != *keyword)\n\t\t\t\t{\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn (*keyword == '\\0');\n\t\t}\n\n\t\tstruct keyword\n\t\t{\n\t\t\tchar const *content;\n\t\t\ttoken_type::Enum token;\n\t\t};\n\n\t\ttoken_type::Enum find_keyword(source_range content)\n\t\t{\n\t\t\t\/\/a rather simple (= slow) approach of finding keywords\n\t\t\tstatic std::array const keywords =\n\t\t\t{{\n\t\t\t\t{\"var\", token_type::var},\n\t\t\t\t{\"function\", token_type::function},\n\t\t\t\t{\"return\", token_type::return_},\n\t\t\t\t{\"null\", token_type::null},\n\t\t\t\t{\"if\", token_type::if_},\n\t\t\t\t{\"else\", token_type::else_},\n\t\t\t\t{\"while\", token_type::while_},\n\t\t\t\t{\"break\", token_type::break_},\n\t\t\t\t{\"continue\", token_type::continue_},\n\t\t\t}};\n\n\t\t\tusing namespace std;\n\n\t\t\tfor (auto k = begin(keywords); k != end(keywords); ++k)\n\t\t\t{\n\t\t\t\tif (is_keyword(content, k->content))\n\t\t\t\t{\n\t\t\t\t\treturn k->token;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn token_type::identifier;\n\t\t}\n\t}\n\n\n\tscanner::scanner(\n\t\tsource_range source\n\t\t)\n\t\t: m_pos(source.begin())\n\t\t, m_end(source.end())\n\t\t, m_was_integer(false)\n\t{\n\t}\n\n\ttoken scanner::next_token()\n\t{\n\t\tskip_whitespace();\n\n\t\tif (m_pos == m_end)\n\t\t{\n\t\t\treturn token(\n\t\t\t\ttoken_type::end_of_file,\n\t\t\t\tsource_range(m_end, m_end)\n\t\t\t\t);\n\t\t}\n\n\t\tbool const was_integer = m_was_integer;\n\t\tm_was_integer = false;\n\n\t\tswitch (*m_pos)\n\t\t{\n\t\tcase '(': return eat_single_char_token(token_type::parenthesis_left);\n\t\tcase ')': return eat_single_char_token(token_type::parenthesis_right);\n\t\tcase '{': return eat_single_char_token(token_type::brace_left);\n\t\tcase '}': return eat_single_char_token(token_type::brace_right);\n\t\tcase '[': return eat_single_char_token(token_type::bracket_left);\n\t\tcase ']': return eat_single_char_token(token_type::bracket_right);\n\t\tcase '=': return eat_single_or_double_token(token_type::assign, '=', token_type::equal);\n\t\tcase ',': return eat_single_char_token(token_type::comma);\n\t\tcase '+': return eat_single_char_token(token_type::plus);\n\t\tcase '-': return eat_single_char_token(token_type::minus);\n\t\tcase '*': return eat_single_char_token(token_type::star);\n\t\tcase '\/': return eat_single_char_token(token_type::slash);\n\t\tcase '%': return eat_single_char_token(token_type::modulo);\n\t\tcase '&': return eat_single_or_double_token(token_type::ampersand, '&', token_type::ampersands);\n\t\tcase '|': return eat_single_or_double_token(token_type::pipe, '|', token_type::pipes);\n\t\tcase '<': return eat_single_or_triple_token(token_type::less, '<', token_type::shift_left, '=', token_type::less_equal);\n\t\tcase '>': return eat_single_or_triple_token(token_type::greater, '>', token_type::shift_right, '=', token_type::greater_equal);\n\t\tcase '!': return eat_single_or_double_token(token_type::exclamation_mark, '=', token_type::not_equal);\n\t\tcase '.': return eat_single_char_token(token_type::dot);\n\t\tcase '~': return eat_single_char_token(token_type::tilde);\n\t\tcase '^': return eat_single_char_token(token_type::caret);\n\t\tcase '\"':\n\t\t\t{\n\t\t\t\t++m_pos;\n\t\t\t\tauto const string_begin = m_pos;\n\n\t\t\t\tfor (;;)\n\t\t\t\t{\n\t\t\t\t\tauto const on_unexpected_eof = [this]()\n\t\t\t\t\t{\n\t\t\t\t\t\tthrow compiler_error(\n\t\t\t\t\t\t\t\"Unexpected end of file in string literal\",\n\t\t\t\t\t\t\tsource_range(m_end, m_end)\n\t\t\t\t\t\t\t);\n\t\t\t\t\t};\n\n\t\t\t\t\tif (m_pos == m_end)\n\t\t\t\t\t{\n\t\t\t\t\t\ton_unexpected_eof();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (((*m_pos < 0x20) ||\n\t\t\t\t\t\t(*m_pos > 0x7e)) &&\n\t\t\t\t\t\t(*m_pos != '\\t'))\n\t\t\t\t\t{\n\t\t\t\t\t\tthrow compiler_error(\n\t\t\t\t\t\t\t\"This character has to be hex-encoded in a string literal\",\n\t\t\t\t\t\t\tsource_range(m_pos, m_pos + 1)\n\t\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (*m_pos == '\\\\')\n\t\t\t\t\t{\n\t\t\t\t\t\t++m_pos;\n\t\t\t\t\t\tif (m_pos == m_end)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ton_unexpected_eof();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t++m_pos;\n\t\t\t\t\t}\n\n\t\t\t\t\telse if (*m_pos == '\"')\n\t\t\t\t\t{\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t++m_pos;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tauto const string_end = m_pos;\n\t\t\t\t++m_pos;\n\n\t\t\t\treturn token(\n\t\t\t\t\ttoken_type::string,\n\t\t\t\t\tsource_range(string_begin, string_end)\n\t\t\t\t\t);\n\t\t\t}\n\n\t\tdefault:\n\t\t\tif (is_identifer_first(*m_pos))\n\t\t\t{\n\t\t\t\tif (was_integer)\n\t\t\t\t{\n\t\t\t\t\tthrow compiler_error(\n\t\t\t\t\t\t\"An integer may not be directly followed by an identifier or a keyword\", \n\t\t\t\t\t\tsource_range(m_pos, m_pos + 1)\n\t\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tauto const identifier_begin = m_pos;\n\t\t\t\tdo\n\t\t\t\t{\n\t\t\t\t\t++m_pos;\n\t\t\t\t}\n\t\t\t\twhile (\n\t\t\t\t\t(m_pos != m_end) &&\n\t\t\t\t\tis_identifier_tail(*m_pos));\n\t\t\t\tauto const identifier_end = m_pos;\n\n\t\t\t\tsource_range const range(\n\t\t\t\t\tidentifier_begin,\n\t\t\t\t\tidentifier_end\n\t\t\t\t\t);\n\n\t\t\t\tauto const type = find_keyword(range);\n\n\t\t\t\treturn token(\n\t\t\t\t\ttype,\n\t\t\t\t\trange\n\t\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (is_digit_10(*m_pos))\n\t\t\t{\n\t\t\t\tauto const integer_begin = m_pos;\n\t\t\t\tdo\n\t\t\t\t{\n\t\t\t\t\t++m_pos;\n\t\t\t\t}\n\t\t\t\twhile (\n\t\t\t\t\t(m_pos != m_end) &&\n\t\t\t\t\tis_digit_10(*m_pos));\n\t\t\t\tauto const integer_end = m_pos;\n\n\t\t\t\tm_was_integer = true;\n\n\t\t\t\treturn token(\n\t\t\t\t\ttoken_type::integer_10,\n\t\t\t\t\tsource_range(integer_begin, integer_end)\n\t\t\t\t\t);\n\t\t\t}\n\n\t\t\tthrow compiler_error(\n\t\t\t\t\"Unexpected character\",\n\t\t\t\tsource_range(m_pos, m_pos + 1)\n\t\t\t\t);\n\t\t}\n\t}\n\n\tvoid scanner::skip_line()\n\t{\n\t\twhile (\n\t\t\t(m_pos != m_end) &&\n\t\t\t(*m_pos != '\\n'))\n\t\t{\n\t\t\t++m_pos;\n\t\t}\n\t}\n\n\tsource_range scanner::rest() const\n\t{\n\t\treturn source_range(\n\t\t\tm_pos,\n\t\t\tm_end\n\t\t\t);\n\t}\n\n\n\tvoid scanner::skip_whitespace()\n\t{\n\t\twhile (m_pos != m_end)\n\t\t{\n\t\t\tif (is_whitespace(*m_pos))\n\t\t\t{\n\t\t\t\t++m_pos;\n\n\t\t\t\tm_was_integer = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t\/\/a comment starts with a semicolon and ends after the current line\n\t\t\tif (*m_pos == ';')\n\t\t\t{\n\t\t\t\tdo\n\t\t\t\t{\n\t\t\t\t\t++m_pos;\n\t\t\t\t}\n\t\t\t\twhile (\n\t\t\t\t\t(m_pos != m_end) &&\n\t\t\t\t\t(*m_pos != '\\n')\n\t\t\t\t\t);\n\n\t\t\t\tm_was_integer = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t}\n\n\ttoken scanner::eat_single_char_token(token_type::Enum type)\n\t{\n\t\t++m_pos;\n\t\treturn token(\n\t\t\ttype,\n\t\t\tsource_range((m_pos - 1), m_pos)\n\t\t\t);\n\t}\n\n\ttoken scanner::eat_single_or_double_token(\n\t\ttoken_type::Enum single_token,\n\t\tchar second_char,\n\t\ttoken_type::Enum double_token\n\t\t)\n\t{\n\t\t++m_pos;\n\n\t\tif ((m_pos != m_end) &&\n\t\t\t(*m_pos == second_char))\n\t\t{\n\t\t\t++m_pos;\n\t\t\treturn token(double_token, source_range(m_pos - 2, m_pos));\n\t\t}\n\n\t\treturn token(single_token, source_range(m_pos - 1, m_pos));\n\t}\n\n\ttoken scanner::eat_single_or_triple_token(\n\t\ttoken_type::Enum single_token,\n\t\tchar second_char_0,\n\t\ttoken_type::Enum double_token_0,\n\t\tchar second_char_1,\n\t\ttoken_type::Enum double_token_1\n\t\t)\n\t{\n\t\t++m_pos;\n\n\t\tif (m_pos != m_end)\n\t\t{\n\t\t\tif (*m_pos == second_char_0)\n\t\t\t{\n\t\t\t\t++m_pos;\n\t\t\t\treturn token(double_token_0, source_range(m_pos - 2, m_pos));\n\t\t\t}\n\t\t\tif (*m_pos == second_char_1)\n\t\t\t{\n\t\t\t\t++m_pos;\n\t\t\t\treturn token(double_token_1, source_range(m_pos - 2, m_pos));\n\t\t\t}\n\t\t}\n\n\t\treturn token(single_token, source_range(m_pos - 1, m_pos));\n\t}\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include \"ReadMaybeMapped.h\"\n\n#include \n#include \n#include \n\n#ifdef __linux__\n#include \/\/ For madvise\n#endif\n\n#include \"Debug.h\"\n#include \"Macros.h\"\n\nnamespace redex {\nnamespace {\n\nstd::string strerror_str(int no) { return std::string(strerror(no)); };\n\n\/\/ Implementation based on posix read. Avoids heap allocation when data\n\/\/ is small enough.\ntemplate \nstruct ReadFileContents final {\n size_t size;\n std::unique_ptr content;\n char inline_data[kDataSize];\n\n explicit ReadFileContents(const std::string& file) {\n int fd = open(file.c_str(), O_RDONLY | O_BINARY);\n if (fd < 0) {\n throw std::runtime_error(std::string(\"Failed to open \") + file + \": \" +\n strerror_str(errno));\n }\n struct stat st = {};\n if (fstat(fd, &st) == -1) {\n auto saved_errno = errno;\n close(fd);\n throw std::runtime_error(std::string(\"Failed to get file length of \") +\n file + \": \" + strerror_str(saved_errno));\n }\n read_data(file, fd, static_cast(st.st_size));\n }\n ReadFileContents(const std::string& file, int fd, size_t size) {\n read_data(file, fd, size);\n }\n\n void read_data(const std::string& file, int fd, size_t size_in) {\n size = size_in;\n if (size == 0) {\n close(fd);\n return;\n }\n char* data;\n if (size > kDataSize) {\n content = std::make_unique(size);\n data = content.get();\n } else {\n data = inline_data;\n }\n\n \/\/ Now read.\n size_t remaining = size;\n while (remaining > 0) {\n ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));\n if (n <= 0) {\n auto saved_errno = errno;\n close(fd);\n throw std::runtime_error(std::string(\"Failed reading \") + file + \": \" +\n strerror_str(saved_errno));\n }\n data += n;\n remaining -= n;\n }\n close(fd);\n }\n\n const char* get_content() const {\n return size > kDataSize ? content.get() : inline_data;\n }\n size_t get_content_size() const { return size; }\n};\nusing PageSizeReadFileContents = ReadFileContents<4080>;\n\nstatic_assert(sizeof(PageSizeReadFileContents) == 4096 || sizeof(void*) != 8,\n \"Unexpected size\");\n\n\/\/ Mmap: just map file contents and wrap the mapping, avoiding allocation\n\/\/ and explicit I\/O.\n\/\/\n\/\/ Note: using boost for Windows compat.\ntemplate \nstruct MmapFileContents final {\n boost::iostreams::mapped_file_source mapped_file{};\n\n explicit MmapFileContents(const std::string& file) {\n mapped_file.open(file);\n if (!mapped_file.is_open()) {\n throw std::runtime_error(std::string(\"Could not open \") + file);\n }\n#ifdef __linux__\n if (mapped_file.size() > 0) {\n madvise(const_cast(mapped_file.data()),\n mapped_file.size(),\n kMadviseFlags);\n }\n#endif\n }\n\n const char* get_content() const { return mapped_file.data(); }\n size_t get_content_size() const { return mapped_file.size(); }\n};\n\n} \/\/ namespace\n\n\/\/ Mmaps may not amortize for small files. Split between `read` and `mmap`.\nvoid read_file_with_contents(const std::string& file,\n const std::function& fn,\n size_t threshold) {\n int fd = open(file.c_str(), O_RDONLY | O_BINARY);\n if (fd < 0) {\n throw std::runtime_error(std::string(\"Failed to open \") + file + \": \" +\n strerror_str(errno));\n }\n struct stat st = {};\n if (fstat(fd, &st) == -1) {\n auto saved_errno = errno;\n close(fd);\n throw std::runtime_error(std::string(\"Failed to get file length of \") +\n file + \": \" + strerror_str(saved_errno));\n }\n size_t size = static_cast(st.st_size);\n\n if (size <= threshold) {\n auto content = PageSizeReadFileContents(file, fd, size);\n fn(content.get_content(), content.get_content_size());\n } else {\n close(fd);\n constexpr int kAdvFlags =\n#ifdef __linux__\n MADV_SEQUENTIAL | MADV_WILLNEED;\n#else\n 0;\n#endif\n auto content = MmapFileContents(file);\n fn(content.get_content(), content.get_content_size());\n }\n}\n\n} \/\/ namespace redex\nAdd missing include\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include \"ReadMaybeMapped.h\"\n\n#include \n#include \n#include \n\n#ifdef __linux__\n#include \/\/ For madvise\n#endif\n\n#include \"utils\/Compat.h\" \/\/ TEMP_FAILURE_RETRY, if necessary.\n\n#include \"Debug.h\"\n#include \"Macros.h\"\n\nnamespace redex {\nnamespace {\n\nstd::string strerror_str(int no) { return std::string(strerror(no)); };\n\n\/\/ Implementation based on posix read. Avoids heap allocation when data\n\/\/ is small enough.\ntemplate \nstruct ReadFileContents final {\n size_t size;\n std::unique_ptr content;\n char inline_data[kDataSize];\n\n explicit ReadFileContents(const std::string& file) {\n int fd = open(file.c_str(), O_RDONLY | O_BINARY);\n if (fd < 0) {\n throw std::runtime_error(std::string(\"Failed to open \") + file + \": \" +\n strerror_str(errno));\n }\n struct stat st = {};\n if (fstat(fd, &st) == -1) {\n auto saved_errno = errno;\n close(fd);\n throw std::runtime_error(std::string(\"Failed to get file length of \") +\n file + \": \" + strerror_str(saved_errno));\n }\n read_data(file, fd, static_cast(st.st_size));\n }\n ReadFileContents(const std::string& file, int fd, size_t size) {\n read_data(file, fd, size);\n }\n\n void read_data(const std::string& file, int fd, size_t size_in) {\n size = size_in;\n if (size == 0) {\n close(fd);\n return;\n }\n char* data;\n if (size > kDataSize) {\n content = std::make_unique(size);\n data = content.get();\n } else {\n data = inline_data;\n }\n\n \/\/ Now read.\n size_t remaining = size;\n while (remaining > 0) {\n ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));\n if (n <= 0) {\n auto saved_errno = errno;\n close(fd);\n throw std::runtime_error(std::string(\"Failed reading \") + file + \": \" +\n strerror_str(saved_errno));\n }\n data += n;\n remaining -= n;\n }\n close(fd);\n }\n\n const char* get_content() const {\n return size > kDataSize ? content.get() : inline_data;\n }\n size_t get_content_size() const { return size; }\n};\nusing PageSizeReadFileContents = ReadFileContents<4080>;\n\nstatic_assert(sizeof(PageSizeReadFileContents) == 4096 || sizeof(void*) != 8,\n \"Unexpected size\");\n\n\/\/ Mmap: just map file contents and wrap the mapping, avoiding allocation\n\/\/ and explicit I\/O.\n\/\/\n\/\/ Note: using boost for Windows compat.\ntemplate \nstruct MmapFileContents final {\n boost::iostreams::mapped_file_source mapped_file{};\n\n explicit MmapFileContents(const std::string& file) {\n mapped_file.open(file);\n if (!mapped_file.is_open()) {\n throw std::runtime_error(std::string(\"Could not open \") + file);\n }\n#ifdef __linux__\n if (mapped_file.size() > 0) {\n madvise(const_cast(mapped_file.data()),\n mapped_file.size(),\n kMadviseFlags);\n }\n#endif\n }\n\n const char* get_content() const { return mapped_file.data(); }\n size_t get_content_size() const { return mapped_file.size(); }\n};\n\n} \/\/ namespace\n\n\/\/ Mmaps may not amortize for small files. Split between `read` and `mmap`.\nvoid read_file_with_contents(const std::string& file,\n const std::function& fn,\n size_t threshold) {\n int fd = open(file.c_str(), O_RDONLY | O_BINARY);\n if (fd < 0) {\n throw std::runtime_error(std::string(\"Failed to open \") + file + \": \" +\n strerror_str(errno));\n }\n struct stat st = {};\n if (fstat(fd, &st) == -1) {\n auto saved_errno = errno;\n close(fd);\n throw std::runtime_error(std::string(\"Failed to get file length of \") +\n file + \": \" + strerror_str(saved_errno));\n }\n size_t size = static_cast(st.st_size);\n\n if (size <= threshold) {\n auto content = PageSizeReadFileContents(file, fd, size);\n fn(content.get_content(), content.get_content_size());\n } else {\n close(fd);\n constexpr int kAdvFlags =\n#ifdef __linux__\n MADV_SEQUENTIAL | MADV_WILLNEED;\n#else\n 0;\n#endif\n auto content = MmapFileContents(file);\n fn(content.get_content(), content.get_content_size());\n }\n}\n\n} \/\/ namespace redex\n<|endoftext|>"} {"text":"\/******************************************************************************\n * _ _____ __________ *\n * | | \/ \/ _ | \/ __\/_ __\/ Visibility *\n * | |\/ \/ __ |_\\ \\ \/ \/ Across *\n * |___\/_\/ |_\/___\/ \/_\/ Space and Time *\n * *\n * This file is part of VAST. It is subject to the license terms in the *\n * LICENSE file found in the top-level directory of this distribution and at *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file. *\n ******************************************************************************\/\n\n#pragma once\n\n#include \"vast\/concept\/parseable\/vast\/json.hpp\"\n#include \"vast\/concept\/printable\/vast\/json.hpp\"\n#include \"vast\/detail\/line_range.hpp\"\n#include \"vast\/error.hpp\"\n#include \"vast\/event.hpp\"\n#include \"vast\/expected.hpp\"\n#include \"vast\/format\/multi_layout_reader.hpp\"\n#include \"vast\/format\/printer_writer.hpp\"\n#include \"vast\/fwd.hpp\"\n#include \"vast\/json.hpp\"\n#include \"vast\/schema.hpp\"\n\nnamespace vast::format::json {\n\nstruct event_printer : printer {\n using attribute = event;\n\n template \n bool print(Iterator& out, const event& e) const {\n vast::json j;\n if (!convert(e.data(), j, e.type()))\n return false;\n return printers::json(out, j);\n }\n};\n\nclass writer : public printer_writer {\npublic:\n using printer_writer::printer_writer;\n\n const char* name() const {\n return \"json-writer\";\n }\n};\n\n\/\/\/ Adds a JSON object to a table slice builder according to a given layout.\n\/\/\/ @param builder The builder to add the JSON object to.\n\/\/\/ @param xs The JSON object to add to *builder.\n\/\/\/ @param layout The record type describing *xs*.\n\/\/\/ @param name The name of the reader used for logging.\n\/\/\/ @returns An error iff the operation failed.\ncaf::error add(table_slice_builder& builder, const vast::json::object& xs,\n const record_type& layout, const std::string_view name);\n\n\/\/\/ @relates reader\nstruct default_selector {\n caf::optional operator()(const vast::json::object&) {\n return layout;\n }\n\n caf::error schema(vast::schema sch) {\n auto entry = *sch.begin();\n if (!caf::holds_alternative(entry))\n return make_error(ec::invalid_configuration,\n \"only record_types supported for json schema\");\n layout = flatten(caf::get(entry));\n return caf::none;\n }\n\n vast::schema schema() const {\n vast::schema result;\n if (layout)\n result.add(*layout);\n return result;\n }\n\n static const char* name() {\n return \"json-reader\";\n }\n\n caf::optional layout = caf::none;\n};\n\n\/\/\/ A reader for JSON data. It operates with a *selector* to determine the\n\/\/\/ mapping of JSON object to the appropriate record type in the schema.\ntemplate \nclass reader final : public multi_layout_reader {\npublic:\n using super = multi_layout_reader;\n\n \/\/\/ Constructs a JSON reader.\n \/\/\/ @param table_slice_type The ID for table slice type to build.\n \/\/\/ @param in The stream of JSON objects.\n explicit reader(caf::atom_value table_slice_type,\n std::unique_ptr in = nullptr);\n\n void reset(std::unique_ptr in);\n\n caf::error schema(vast::schema sch) override;\n\n caf::error schema(vast::type, vast::schema);\n\n vast::schema schema() const override;\n\n const char* name() const override;\n\nprotected:\n caf::error read_impl(size_t max_events, size_t max_slice_size,\n consumer& f) override;\n\nprivate:\n using iterator_type = std::string_view::const_iterator;\n\n Selector selector_;\n std::unique_ptr input_;\n std::unique_ptr lines_;\n caf::optional proto_field_;\n std::vector port_fields_;\n};\n\n\/\/ -- implementation ----------------------------------------------------------\n\ntemplate \nreader::reader(caf::atom_value table_slice_type,\n std::unique_ptr in)\n : super(table_slice_type) {\n if (in != nullptr)\n reset(std::move(in));\n}\n\ntemplate \nvoid reader::reset(std::unique_ptr in) {\n VAST_ASSERT(in != nullptr);\n input_ = std::move(in);\n lines_ = std::make_unique(*input_);\n}\n\ntemplate \ncaf::error reader::schema(vast::schema s) {\n return selector_.schema(std::move(s));\n}\n\ntemplate \nvast::schema reader::schema() const {\n return selector_.schema();\n}\n\ntemplate \nconst char* reader::name() const {\n return Selector::name();\n}\n\ntemplate \ncaf::error reader::read_impl(size_t max_events, size_t max_slice_size,\n consumer& cons) {\n VAST_ASSERT(max_events > 0);\n VAST_ASSERT(max_slice_size > 0);\n size_t produced = 0;\n while (produced < max_events) {\n \/\/ EOF check.\n if (lines_->done())\n return finish(cons, make_error(ec::end_of_input, \"input exhausted\"));\n auto& line = lines_->get();\n vast::json j;\n if (!parsers::json(line, j))\n return make_error(ec::parse_error, \"unable to parse json\");\n auto xs = caf::get_if(&j);\n if (!xs)\n return make_error(ec::type_clash, \"not a json object\");\n auto layout = selector_(*xs);\n if (!layout)\n return make_error(ec::parse_error, \"unable to get a layout\");\n auto bptr = builder(*layout);\n if (bptr == nullptr)\n return make_error(ec::parse_error, \"unable to get a builder\");\n if (auto err = add(*bptr, *xs, *layout, selector_.name())) {\n err.context() += caf::make_message(\"line\", lines_->line_number());\n return finish(cons, err);\n }\n produced++;\n if (bptr->rows() == max_slice_size)\n if (auto err = finish(cons, bptr))\n return err;\n lines_->next();\n }\n return finish(cons);\n}\n\n} \/\/ namespace vast::format::json\nDon't abort on unrecognized events\/******************************************************************************\n * _ _____ __________ *\n * | | \/ \/ _ | \/ __\/_ __\/ Visibility *\n * | |\/ \/ __ |_\\ \\ \/ \/ Across *\n * |___\/_\/ |_\/___\/ \/_\/ Space and Time *\n * *\n * This file is part of VAST. It is subject to the license terms in the *\n * LICENSE file found in the top-level directory of this distribution and at *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file. *\n ******************************************************************************\/\n\n#pragma once\n\n#include \"vast\/concept\/parseable\/vast\/json.hpp\"\n#include \"vast\/concept\/printable\/vast\/json.hpp\"\n#include \"vast\/detail\/line_range.hpp\"\n#include \"vast\/error.hpp\"\n#include \"vast\/event.hpp\"\n#include \"vast\/expected.hpp\"\n#include \"vast\/format\/multi_layout_reader.hpp\"\n#include \"vast\/format\/printer_writer.hpp\"\n#include \"vast\/fwd.hpp\"\n#include \"vast\/json.hpp\"\n#include \"vast\/logger.hpp\"\n#include \"vast\/schema.hpp\"\n\nnamespace vast::format::json {\n\nstruct event_printer : printer {\n using attribute = event;\n\n template \n bool print(Iterator& out, const event& e) const {\n vast::json j;\n if (!convert(e.data(), j, e.type()))\n return false;\n return printers::json(out, j);\n }\n};\n\nclass writer : public printer_writer {\npublic:\n using printer_writer::printer_writer;\n\n const char* name() const {\n return \"json-writer\";\n }\n};\n\n\/\/\/ Adds a JSON object to a table slice builder according to a given layout.\n\/\/\/ @param builder The builder to add the JSON object to.\n\/\/\/ @param xs The JSON object to add to *builder.\n\/\/\/ @param layout The record type describing *xs*.\n\/\/\/ @param name The name of the reader used for logging.\n\/\/\/ @returns An error iff the operation failed.\ncaf::error add(table_slice_builder& builder, const vast::json::object& xs,\n const record_type& layout, const std::string_view name);\n\n\/\/\/ @relates reader\nstruct default_selector {\n caf::optional operator()(const vast::json::object&) {\n return layout;\n }\n\n caf::error schema(vast::schema sch) {\n auto entry = *sch.begin();\n if (!caf::holds_alternative(entry))\n return make_error(ec::invalid_configuration,\n \"only record_types supported for json schema\");\n layout = flatten(caf::get(entry));\n return caf::none;\n }\n\n vast::schema schema() const {\n vast::schema result;\n if (layout)\n result.add(*layout);\n return result;\n }\n\n static const char* name() {\n return \"json-reader\";\n }\n\n caf::optional layout = caf::none;\n};\n\n\/\/\/ A reader for JSON data. It operates with a *selector* to determine the\n\/\/\/ mapping of JSON object to the appropriate record type in the schema.\ntemplate \nclass reader final : public multi_layout_reader {\npublic:\n using super = multi_layout_reader;\n\n \/\/\/ Constructs a JSON reader.\n \/\/\/ @param table_slice_type The ID for table slice type to build.\n \/\/\/ @param in The stream of JSON objects.\n explicit reader(caf::atom_value table_slice_type,\n std::unique_ptr in = nullptr);\n\n void reset(std::unique_ptr in);\n\n caf::error schema(vast::schema sch) override;\n\n caf::error schema(vast::type, vast::schema);\n\n vast::schema schema() const override;\n\n const char* name() const override;\n\nprotected:\n caf::error read_impl(size_t max_events, size_t max_slice_size,\n consumer& f) override;\n\nprivate:\n using iterator_type = std::string_view::const_iterator;\n\n Selector selector_;\n std::unique_ptr input_;\n std::unique_ptr lines_;\n caf::optional proto_field_;\n std::vector port_fields_;\n};\n\n\/\/ -- implementation ----------------------------------------------------------\n\ntemplate \nreader::reader(caf::atom_value table_slice_type,\n std::unique_ptr in)\n : super(table_slice_type) {\n if (in != nullptr)\n reset(std::move(in));\n}\n\ntemplate \nvoid reader::reset(std::unique_ptr in) {\n VAST_ASSERT(in != nullptr);\n input_ = std::move(in);\n lines_ = std::make_unique(*input_);\n}\n\ntemplate \ncaf::error reader::schema(vast::schema s) {\n return selector_.schema(std::move(s));\n}\n\ntemplate \nvast::schema reader::schema() const {\n return selector_.schema();\n}\n\ntemplate \nconst char* reader::name() const {\n return Selector::name();\n}\n\ntemplate \ncaf::error reader::read_impl(size_t max_events, size_t max_slice_size,\n consumer& cons) {\n VAST_ASSERT(max_events > 0);\n VAST_ASSERT(max_slice_size > 0);\n size_t produced = 0;\n for (; produced < max_events; lines_->next()) {\n \/\/ EOF check.\n if (lines_->done())\n return finish(cons, make_error(ec::end_of_input, \"input exhausted\"));\n auto& line = lines_->get();\n vast::json j;\n if (!parsers::json(line, j))\n return make_error(ec::parse_error, \"unable to parse json\");\n auto xs = caf::get_if(&j);\n if (!xs)\n return make_error(ec::type_clash, \"not a json object\");\n auto layout = selector_(*xs);\n if (!layout) {\n VAST_INFO(this, \"unable to get a layout\");\n continue;\n }\n VAST_INFO(this, \"got layout\", *layout);\n auto bptr = builder(*layout);\n if (bptr == nullptr)\n return make_error(ec::parse_error, \"unable to get a builder\");\n if (auto err = add(*bptr, *xs, *layout, selector_.name())) {\n err.context() += caf::make_message(\"line\", lines_->line_number());\n return finish(cons, err);\n }\n produced++;\n if (bptr->rows() == max_slice_size)\n if (auto err = finish(cons, bptr))\n return err;\n }\n return finish(cons);\n}\n\n} \/\/ namespace vast::format::json\n<|endoftext|>"} {"text":"\/**\n * @file\n *\/\n#pragma once\n\n#include \"libbirch\/FiberState.hpp\"\n\nnamespace libbirch {\n\/**\n * Fiber.\n *\n * @ingroup libbirch\n *\n * @tparam YieldType Yield type.\n *\/\ntemplate\nclass Fiber {\npublic:\n \/**\n * Default constructor.\n *\/\n Fiber(Label* context) {\n \/\/\n }\n\n \/**\n * Constructor.\n *\/\n Fiber(Label* context, const Shared>& state) :\n state(context, state) {\n \/\/\n }\n\n \/**\n * Copy constructor.\n *\/\n Fiber(Label* context, const Fiber& o) :\n state(context, o.state) {\n \/\/\n }\n\n \/**\n * Deep copy constructor.\n *\/\n Fiber(Label* context, Label* label, const Fiber& o) :\n state(context, label, o.state) {\n \/\/\n }\n\n \/**\n * Clone the fiber.\n *\/\n Fiber clone() const {\n return Fiber(state.clone());\n }\n\n \/**\n * Freeze the fiber.\n *\/\n void freeze() const {\n state.freeze();\n }\n\n \/**\n * Thaw the fiber.\n *\/\n void thaw(LazyLabel* label) const {\n state.thaw(label);\n }\n\n \/**\n * Finish the fiber.\n *\/\n void finish() const {\n state.finish();\n }\n\n \/**\n * Run to next yield point.\n *\n * @return Was a value yielded?\n *\/\n bool query() const {\n bool result = false;\n if (state.query()) {\n result = state->query();\n if (!result) {\n const_cast*>(this)->state.release();\n \/\/ ^ fiber has finished, delete the state\n }\n }\n return result;\n }\n\n\n \/**\n * Get the last yield value.\n *\/\n YieldType get() const {\n libbirch_assert_msg_(state.query(), \"fiber handle undefined\");\n return state->get();\n }\n\n\nprivate:\n \/**\n * Fiber state.\n *\/\n Shared> state;\n};\n\ntemplate\nstruct is_value> {\n static const bool value = false;\n};\n}\nUpdates to Fiber constructors, copy and move constructors.\/**\n * @file\n *\/\n#pragma once\n\n#include \"libbirch\/FiberState.hpp\"\n\nnamespace libbirch {\n\/**\n * Fiber.\n *\n * @ingroup libbirch\n *\n * @tparam YieldType Yield type.\n *\/\ntemplate\nclass Fiber {\npublic:\n \/**\n * Constructor.\n *\/\n Fiber() {\n \/\/\n }\n\n \/**\n * Constructor.\n *\/\n Fiber(Label* context, const Shared>& state) :\n state(context, state) {\n \/\/\n }\n\n \/**\n * Copy constructor.\n *\/\n Fiber(Label* context, const Fiber& o) :\n state(context, o.state) {\n \/\/\n }\n\n \/**\n * Move constructor.\n *\/\n Fiber(Label* context, Fiber&& o) :\n state(context, std::move(o.state)) {\n \/\/\n }\n\n \/**\n * Deep copy constructor.\n *\/\n Fiber(Label* context, Label* label, const Fiber& o) :\n state(context, label, o.state) {\n \/\/\n }\n\n \/**\n * Copy assignment.\n *\/\n Fiber& assign(Label* context, const Fiber& o) {\n state.assign(context, o.state);\n return *this;\n }\n\n \/**\n * Move assignment.\n *\/\n Fiber& assign(Label* context, Fiber&& o) {\n state.assign(context, std::move(o.state));\n return *this;\n }\n\n \/**\n * Clone the fiber.\n *\/\n Fiber clone() const {\n return Fiber(state.clone());\n }\n\n \/**\n * Freeze the fiber.\n *\/\n void freeze() const {\n state.freeze();\n }\n\n \/**\n * Thaw the fiber.\n *\/\n void thaw(LazyLabel* label) const {\n state.thaw(label);\n }\n\n \/**\n * Finish the fiber.\n *\/\n void finish() const {\n state.finish();\n }\n\n \/**\n * Run to next yield point.\n *\n * @return Was a value yielded?\n *\/\n bool query() const {\n bool result = false;\n if (state.query()) {\n result = state->query();\n if (!result) {\n const_cast*>(this)->state.release();\n \/\/ ^ fiber has finished, delete the state\n }\n }\n return result;\n }\n\n\n \/**\n * Get the last yield value.\n *\/\n YieldType get() const {\n libbirch_assert_msg_(state.query(), \"fiber handle undefined\");\n return state->get();\n }\n\n\nprivate:\n \/**\n * Fiber state.\n *\/\n Shared> state;\n};\n\ntemplate\nstruct is_value> {\n static const bool value = false;\n};\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/host_zoom_map.h\"\n\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/pref_service.h\"\n\nHostZoomMap::HostZoomMap(Profile* profile) : profile_(profile) {\n const DictionaryValue* host_zoom_dictionary =\n profile_->GetPrefs()->GetDictionary(prefs::kPerHostZoomLevels);\n \/\/ Careful: The returned value could be NULL if the pref has never been set.\n if (host_zoom_dictionary != NULL) {\n for (DictionaryValue::key_iterator i(host_zoom_dictionary->begin_keys());\n i != host_zoom_dictionary->end_keys(); ++i) {\n std::wstring wide_host(*i);\n int zoom_level = 0;\n bool success = host_zoom_dictionary->GetIntegerWithoutPathExpansion(\n wide_host, &zoom_level);\n DCHECK(success);\n host_zoom_levels_[WideToUTF8(wide_host)] = zoom_level;\n }\n }\n}\n\n\/\/ static\nvoid HostZoomMap::RegisterUserPrefs(PrefService* prefs) {\n prefs->RegisterDictionaryPref(prefs::kPerHostZoomLevels);\n}\n\nint HostZoomMap::GetZoomLevel(const std::string& host) const {\n AutoLock auto_lock(lock_);\n HostZoomLevels::const_iterator i(host_zoom_levels_.find(host));\n return (i == host_zoom_levels_.end()) ? 0 : i->second;\n}\n\nvoid HostZoomMap::SetZoomLevel(const std::string& host, int level) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n if (host.empty())\n return;\n\n {\n AutoLock auto_lock(lock_);\n if (level == 0)\n host_zoom_levels_.erase(host);\n else\n host_zoom_levels_[host] = level;\n }\n\n DictionaryValue* host_zoom_dictionary =\n profile_->GetPrefs()->GetMutableDictionary(prefs::kPerHostZoomLevels);\n std::wstring wide_host(UTF8ToWide(host));\n if (level == 0) {\n host_zoom_dictionary->RemoveWithoutPathExpansion(wide_host, NULL);\n } else {\n host_zoom_dictionary->SetWithoutPathExpansion(wide_host,\n Value::CreateIntegerValue(level));\n }\n}\n\nvoid HostZoomMap::ResetToDefaults() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n\n host_zoom_levels_.clear();\n profile_->GetPrefs()->ClearPref(prefs::kPerHostZoomLevels);\n}\n\nHostZoomMap::~HostZoomMap() {\n}\nOne more place I forgot to lock.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/host_zoom_map.h\"\n\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/pref_service.h\"\n\nHostZoomMap::HostZoomMap(Profile* profile) : profile_(profile) {\n const DictionaryValue* host_zoom_dictionary =\n profile_->GetPrefs()->GetDictionary(prefs::kPerHostZoomLevels);\n \/\/ Careful: The returned value could be NULL if the pref has never been set.\n if (host_zoom_dictionary != NULL) {\n for (DictionaryValue::key_iterator i(host_zoom_dictionary->begin_keys());\n i != host_zoom_dictionary->end_keys(); ++i) {\n std::wstring wide_host(*i);\n int zoom_level = 0;\n bool success = host_zoom_dictionary->GetIntegerWithoutPathExpansion(\n wide_host, &zoom_level);\n DCHECK(success);\n host_zoom_levels_[WideToUTF8(wide_host)] = zoom_level;\n }\n }\n}\n\n\/\/ static\nvoid HostZoomMap::RegisterUserPrefs(PrefService* prefs) {\n prefs->RegisterDictionaryPref(prefs::kPerHostZoomLevels);\n}\n\nint HostZoomMap::GetZoomLevel(const std::string& host) const {\n AutoLock auto_lock(lock_);\n HostZoomLevels::const_iterator i(host_zoom_levels_.find(host));\n return (i == host_zoom_levels_.end()) ? 0 : i->second;\n}\n\nvoid HostZoomMap::SetZoomLevel(const std::string& host, int level) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n if (host.empty())\n return;\n\n {\n AutoLock auto_lock(lock_);\n if (level == 0)\n host_zoom_levels_.erase(host);\n else\n host_zoom_levels_[host] = level;\n }\n\n DictionaryValue* host_zoom_dictionary =\n profile_->GetPrefs()->GetMutableDictionary(prefs::kPerHostZoomLevels);\n std::wstring wide_host(UTF8ToWide(host));\n if (level == 0) {\n host_zoom_dictionary->RemoveWithoutPathExpansion(wide_host, NULL);\n } else {\n host_zoom_dictionary->SetWithoutPathExpansion(wide_host,\n Value::CreateIntegerValue(level));\n }\n}\n\nvoid HostZoomMap::ResetToDefaults() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n\n {\n AutoLock auto_lock(lock_);\n host_zoom_levels_.clear();\n }\n\n profile_->GetPrefs()->ClearPref(prefs::kPerHostZoomLevels);\n}\n\nHostZoomMap::~HostZoomMap() {\n}\n<|endoftext|>"} {"text":"Invoke the right method (invokeDefault) if a plugin calls NPN_InvokeDefault on its own object.<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ Description of the life cycle of a instance of MetricsService.\n\/\/\n\/\/ OVERVIEW\n\/\/\n\/\/ A MetricsService instance is created at ChromeFrame startup in\n\/\/ the IE process. It is the central controller for the UMA log data.\n\/\/ Its major job is to manage logs, prepare them for transmission.\n\/\/ Currently only histogram data is tracked in log. When MetricsService\n\/\/ prepares log for submission it snapshots the current stats of histograms,\n\/\/ translates log to XML. Transmission includes submitting a compressed log\n\/\/ as data in a URL-get, and is performed using functionality provided by\n\/\/ Urlmon\n\/\/ The actual transmission is performed using a windows timer procedure which\n\/\/ basically means that the thread on which the MetricsService object is\n\/\/ instantiated needs a message pump. Also on IE7 where every tab is created\n\/\/ on its own thread we would have a case where the timer procedures can\n\/\/ compete for sending histograms.\n\/\/\n\/\/ When preparing log for submission we acquire a list of all local histograms\n\/\/ that have been flagged for upload to the UMA server.\n\/\/\n\/\/ When ChromeFrame shuts down, there will typically be a fragment of an ongoing\n\/\/ log that has not yet been transmitted. Currently this data is ignored.\n\/\/\n\/\/ With the above overview, we can now describe the state machine's various\n\/\/ stats, based on the State enum specified in the state_ member. Those states\n\/\/ are:\n\/\/\n\/\/ INITIALIZED, \/\/ Constructor was called.\n\/\/ ACTIVE, \/\/ Accumalating log data.\n\/\/ STOPPED, \/\/ Service has stopped.\n\/\/\n\/\/-----------------------------------------------------------------------------\n\n#include \"chrome_frame\/metrics_service.h\"\n\n#include \n#include \n\n#if defined(USE_SYSTEM_LIBBZ2)\n#include \n#else\n#include \"third_party\/bzip2\/bzlib.h\"\n#endif\n\n#include \"base\/file_version_info.h\"\n#include \"base\/string_util.h\"\n#include \"base\/thread.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/common\/chrome_version_info.h\"\n#include \"chrome\/installer\/util\/browser_distribution.h\"\n#include \"chrome\/installer\/util\/chrome_frame_distribution.h\"\n#include \"chrome\/installer\/util\/google_update_settings.h\"\n#include \"chrome_frame\/bind_status_callback_impl.h\"\n#include \"chrome_frame\/crash_reporting\/crash_metrics.h\"\n#include \"chrome_frame\/utils.h\"\n#include \"net\/base\/upload_data.h\"\n#include \"chrome_frame\/urlmon_bind_status_callback.h\"\n\nusing base::Time;\nusing base::TimeDelta;\n\nstatic const char kMetricsType[] =\n \"Content-Type: application\/vnd.mozilla.metrics.bz2\\r\\n\";\n\n\/\/ The first UMA upload occurs after this interval.\nstatic const int kInitialUMAUploadTimeoutMilliSeconds = 30000;\n\n\/\/ Default to one UMA upload per 10 mins.\nstatic const int kMinMilliSecondsPerUMAUpload = 600000;\n\nbase::LazyInstance >\n MetricsService::g_metrics_instance_(base::LINKER_INITIALIZED);\n\nextern base::LazyInstance g_statistics_recorder_;\n\n\/\/ This class provides functionality to upload the ChromeFrame UMA data to the\n\/\/ server. An instance of this class is created whenever we have data to be\n\/\/ uploaded to the server.\nclass ChromeFrameMetricsDataUploader : public BSCBImpl {\n public:\n ChromeFrameMetricsDataUploader()\n : cache_stream_(NULL),\n upload_data_size_(0) {\n DLOG(INFO) << __FUNCTION__;\n }\n\n ~ChromeFrameMetricsDataUploader() {\n DLOG(INFO) << __FUNCTION__;\n }\n\n static HRESULT ChromeFrameMetricsDataUploader::UploadDataHelper(\n const std::string& upload_data) {\n CComObject* data_uploader = NULL;\n CComObject::CreateInstance(&data_uploader);\n DCHECK(data_uploader != NULL);\n\n data_uploader->AddRef();\n HRESULT hr = data_uploader->UploadData(upload_data);\n if (FAILED(hr)) {\n DLOG(ERROR) << \"Failed to initialize ChromeFrame UMA data uploader: Err\"\n << hr;\n }\n data_uploader->Release();\n return hr;\n }\n\n HRESULT UploadData(const std::string& upload_data) {\n if (upload_data.empty()) {\n NOTREACHED() << \"Invalid upload data\";\n return E_INVALIDARG;\n }\n\n DCHECK(cache_stream_.get() == NULL);\n\n upload_data_size_ = upload_data.size() + 1;\n\n HRESULT hr = CreateStreamOnHGlobal(NULL, TRUE, cache_stream_.Receive());\n if (FAILED(hr)) {\n NOTREACHED() << \"Failed to create stream. Error:\"\n << hr;\n return hr;\n }\n\n DCHECK(cache_stream_.get());\n\n unsigned long written = 0;\n cache_stream_->Write(upload_data.c_str(), upload_data_size_, &written);\n DCHECK(written == upload_data_size_);\n\n RewindStream(cache_stream_);\n\n BrowserDistribution* dist = ChromeFrameDistribution::GetDistribution();\n server_url_ = dist->GetStatsServerURL();\n DCHECK(!server_url_.empty());\n\n hr = CreateURLMoniker(NULL, server_url_.c_str(),\n upload_moniker_.Receive());\n if (FAILED(hr)) {\n DLOG(ERROR) << \"Failed to create url moniker for url:\"\n << server_url_.c_str()\n << \" Error:\"\n << hr;\n } else {\n ScopedComPtr context;\n hr = CreateAsyncBindCtx(0, this, NULL, context.Receive());\n DCHECK(SUCCEEDED(hr));\n DCHECK(context);\n\n ScopedComPtr stream;\n hr = upload_moniker_->BindToStorage(\n context, NULL, IID_IStream,\n reinterpret_cast(stream.Receive()));\n if (FAILED(hr)) {\n NOTREACHED();\n DLOG(ERROR) << \"Failed to bind to upload data moniker. Error:\"\n << hr;\n }\n }\n return hr;\n }\n\n STDMETHOD(BeginningTransaction)(LPCWSTR url, LPCWSTR headers, DWORD reserved,\n LPWSTR* additional_headers) {\n std::string new_headers;\n new_headers = StringPrintf(\"Content-Length: %s\\r\\n\",\n base::Int64ToString(upload_data_size_).c_str());\n new_headers += kMetricsType;\n\n *additional_headers = reinterpret_cast(\n CoTaskMemAlloc((new_headers.size() + 1) * sizeof(wchar_t)));\n\n lstrcpynW(*additional_headers, ASCIIToWide(new_headers).c_str(),\n new_headers.size());\n return BSCBImpl::BeginningTransaction(url, headers, reserved,\n additional_headers);\n }\n\n STDMETHOD(GetBindInfo)(DWORD* bind_flags, BINDINFO* bind_info) {\n if ((bind_info == NULL) || (bind_info->cbSize == 0) ||\n (bind_flags == NULL))\n return E_INVALIDARG;\n\n *bind_flags = BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE | BINDF_PULLDATA;\n \/\/ Bypass caching proxies on POSTs and PUTs and avoid writing responses to\n \/\/ these requests to the browser's cache\n *bind_flags |= BINDF_GETNEWESTVERSION | BINDF_PRAGMA_NO_CACHE;\n\n DCHECK(cache_stream_.get());\n\n \/\/ Initialize the STGMEDIUM.\n memset(&bind_info->stgmedData, 0, sizeof(STGMEDIUM));\n bind_info->grfBindInfoF = 0;\n bind_info->szCustomVerb = NULL;\n bind_info->dwBindVerb = BINDVERB_POST;\n bind_info->stgmedData.tymed = TYMED_ISTREAM;\n bind_info->stgmedData.pstm = cache_stream_.get();\n bind_info->stgmedData.pstm->AddRef();\n return BSCBImpl::GetBindInfo(bind_flags, bind_info);\n }\n\n STDMETHOD(OnResponse)(DWORD response_code, LPCWSTR response_headers,\n LPCWSTR request_headers, LPWSTR* additional_headers) {\n DLOG(INFO) << __FUNCTION__ << \" headers: \\n\" << response_headers;\n return BSCBImpl::OnResponse(response_code, response_headers,\n request_headers, additional_headers);\n }\n\n private:\n std::wstring server_url_;\n size_t upload_data_size_;\n ScopedComPtr cache_stream_;\n ScopedComPtr upload_moniker_;\n};\n\nMetricsService* MetricsService::GetInstance() {\n if (g_metrics_instance_.Pointer()->Get())\n return g_metrics_instance_.Pointer()->Get();\n\n g_metrics_instance_.Pointer()->Set(new MetricsService);\n return g_metrics_instance_.Pointer()->Get();\n}\n\nMetricsService::MetricsService()\n : recording_active_(false),\n reporting_active_(false),\n user_permits_upload_(false),\n state_(INITIALIZED),\n thread_(NULL),\n initial_uma_upload_(true),\n transmission_timer_id_(0) {\n}\n\nMetricsService::~MetricsService() {\n SetRecording(false);\n if (pending_log_) {\n delete pending_log_;\n pending_log_ = NULL;\n }\n if (current_log_) {\n delete current_log_;\n current_log_ = NULL;\n }\n}\n\nvoid MetricsService::InitializeMetricsState() {\n DCHECK(state_ == INITIALIZED);\n\n thread_ = PlatformThread::CurrentId();\n\n user_permits_upload_ = GoogleUpdateSettings::GetCollectStatsConsent();\n \/\/ Update session ID\n session_id_ = CrashMetricsReporter::GetInstance()->IncrementMetric(\n CrashMetricsReporter::SESSION_ID);\n\n \/\/ Ensure that an instance of the StatisticsRecorder object is created.\n g_statistics_recorder_.Get();\n\n CrashMetricsReporter::GetInstance()->set_active(true);\n}\n\n\/\/ static\nvoid MetricsService::Start() {\n if (GetInstance()->state_ == ACTIVE)\n return;\n\n GetInstance()->InitializeMetricsState();\n GetInstance()->SetRecording(true);\n GetInstance()->SetReporting(true);\n}\n\n\/\/ static\nvoid MetricsService::Stop() {\n GetInstance()->SetReporting(false);\n GetInstance()->SetRecording(false);\n}\n\nvoid MetricsService::SetRecording(bool enabled) {\n DCHECK_EQ(thread_, PlatformThread::CurrentId());\n if (enabled == recording_active_)\n return;\n\n if (enabled) {\n if (client_id_.empty()) {\n client_id_ = GenerateClientID();\n \/\/ Save client id somewhere.\n }\n StartRecording();\n\n } else {\n state_ = STOPPED;\n }\n recording_active_ = enabled;\n}\n\n\/\/ static\nstd::string MetricsService::GenerateClientID() {\n const int kGUIDSize = 39;\n\n GUID guid;\n HRESULT guid_result = CoCreateGuid(&guid);\n DCHECK(SUCCEEDED(guid_result));\n\n std::wstring guid_string;\n int result = StringFromGUID2(guid,\n WriteInto(&guid_string, kGUIDSize), kGUIDSize);\n DCHECK(result == kGUIDSize);\n return WideToUTF8(guid_string.substr(1, guid_string.length() - 2));\n}\n\n\/\/ static\nvoid CALLBACK MetricsService::TransmissionTimerProc(HWND window,\n unsigned int message,\n unsigned int event_id,\n unsigned int time) {\n DLOG(INFO) << \"Transmission timer notified\";\n DCHECK(GetInstance() != NULL);\n GetInstance()->UploadData();\n if (GetInstance()->initial_uma_upload_) {\n \/\/ If this is the first uma upload by this process then subsequent uma\n \/\/ uploads should occur once every 10 minutes(default).\n GetInstance()->initial_uma_upload_ = false;\n DCHECK(GetInstance()->transmission_timer_id_ != 0);\n SetTimer(NULL, GetInstance()->transmission_timer_id_,\n kMinMilliSecondsPerUMAUpload,\n reinterpret_cast(TransmissionTimerProc));\n }\n}\n\nvoid MetricsService::SetReporting(bool enable) {\n static const int kChromeFrameMetricsTimerId = 0xFFFFFFFF;\n\n DCHECK_EQ(thread_, PlatformThread::CurrentId());\n if (reporting_active_ != enable) {\n reporting_active_ = enable;\n if (reporting_active_) {\n transmission_timer_id_ =\n SetTimer(NULL, kChromeFrameMetricsTimerId,\n kInitialUMAUploadTimeoutMilliSeconds,\n reinterpret_cast(TransmissionTimerProc));\n }\n }\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ Recording control methods\n\nvoid MetricsService::StartRecording() {\n DCHECK_EQ(thread_, PlatformThread::CurrentId());\n if (current_log_)\n return;\n\n current_log_ = new MetricsLogBase(client_id_, session_id_,\n GetVersionString());\n if (state_ == INITIALIZED)\n state_ = ACTIVE;\n}\n\nvoid MetricsService::StopRecording(bool save_log) {\n DCHECK_EQ(thread_, PlatformThread::CurrentId());\n if (!current_log_)\n return;\n\n \/\/ Put incremental histogram deltas at the end of all log transmissions.\n \/\/ Don't bother if we're going to discard current_log_.\n if (save_log) {\n CrashMetricsReporter::GetInstance()->RecordCrashMetrics();\n RecordCurrentHistograms();\n }\n\n if (save_log) {\n pending_log_ = current_log_;\n }\n current_log_ = NULL;\n}\n\nvoid MetricsService::MakePendingLog() {\n DCHECK_EQ(thread_, PlatformThread::CurrentId());\n if (pending_log())\n return;\n\n switch (state_) {\n case INITIALIZED: \/\/ We should be further along by now.\n DCHECK(false);\n return;\n\n case ACTIVE:\n StopRecording(true);\n StartRecording();\n break;\n\n default:\n DCHECK(false);\n return;\n }\n\n DCHECK(pending_log());\n}\n\nbool MetricsService::TransmissionPermitted() const {\n \/\/ If the user forbids uploading that's their business, and we don't upload\n \/\/ anything.\n return user_permits_upload_;\n}\n\nstd::string MetricsService::PrepareLogSubmissionString() {\n DCHECK_EQ(thread_, PlatformThread::CurrentId());\n\n MakePendingLog();\n DCHECK(pending_log());\n if (pending_log_== NULL) {\n return std::string();\n }\n\n pending_log_->CloseLog();\n std::string pending_log_text = pending_log_->GetEncodedLogString();\n DCHECK(!pending_log_text.empty());\n DiscardPendingLog();\n return pending_log_text;\n}\n\nbool MetricsService::UploadData() {\n DCHECK_EQ(thread_, PlatformThread::CurrentId());\n\n if (!GetInstance()->TransmissionPermitted())\n return false;\n\n static long currently_uploading = 0;\n if (InterlockedCompareExchange(¤tly_uploading, 1, 0)) {\n DLOG(INFO) << \"Contention for uploading metrics data. Backing off\";\n return false;\n }\n\n std::string pending_log_text = PrepareLogSubmissionString();\n DCHECK(!pending_log_text.empty());\n\n \/\/ Allow security conscious users to see all metrics logs that we send.\n LOG(INFO) << \"METRICS LOG: \" << pending_log_text;\n\n bool ret = true;\n\n if (!Bzip2Compress(pending_log_text, &compressed_log_)) {\n NOTREACHED() << \"Failed to compress log for transmission.\";\n ret = false;\n } else {\n HRESULT hr = ChromeFrameMetricsDataUploader::UploadDataHelper(\n compressed_log_);\n DCHECK(SUCCEEDED(hr));\n }\n DiscardPendingLog();\n\n currently_uploading = 0;\n return ret;\n}\n\n\/\/ static\nstd::string MetricsService::GetVersionString() {\n chrome::VersionInfo version_info;\n if (version_info.is_valid()) {\n std::string version = version_info.Version();\n \/\/ Add the -F extensions to ensure that UMA data uploaded by ChromeFrame\n \/\/ lands in the ChromeFrame bucket.\n version += \"-F\";\n if (!version_info.IsOfficialBuild())\n version.append(\"-devel\");\n return version;\n } else {\n NOTREACHED() << \"Unable to retrieve version string.\";\n }\n\n return std::string();\n}\nAdd ChromeFrame to the useragent string in outgoing UMA requests from ChromeFrame.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ Description of the life cycle of a instance of MetricsService.\n\/\/\n\/\/ OVERVIEW\n\/\/\n\/\/ A MetricsService instance is created at ChromeFrame startup in\n\/\/ the IE process. It is the central controller for the UMA log data.\n\/\/ Its major job is to manage logs, prepare them for transmission.\n\/\/ Currently only histogram data is tracked in log. When MetricsService\n\/\/ prepares log for submission it snapshots the current stats of histograms,\n\/\/ translates log to XML. Transmission includes submitting a compressed log\n\/\/ as data in a URL-get, and is performed using functionality provided by\n\/\/ Urlmon\n\/\/ The actual transmission is performed using a windows timer procedure which\n\/\/ basically means that the thread on which the MetricsService object is\n\/\/ instantiated needs a message pump. Also on IE7 where every tab is created\n\/\/ on its own thread we would have a case where the timer procedures can\n\/\/ compete for sending histograms.\n\/\/\n\/\/ When preparing log for submission we acquire a list of all local histograms\n\/\/ that have been flagged for upload to the UMA server.\n\/\/\n\/\/ When ChromeFrame shuts down, there will typically be a fragment of an ongoing\n\/\/ log that has not yet been transmitted. Currently this data is ignored.\n\/\/\n\/\/ With the above overview, we can now describe the state machine's various\n\/\/ stats, based on the State enum specified in the state_ member. Those states\n\/\/ are:\n\/\/\n\/\/ INITIALIZED, \/\/ Constructor was called.\n\/\/ ACTIVE, \/\/ Accumalating log data.\n\/\/ STOPPED, \/\/ Service has stopped.\n\/\/\n\/\/-----------------------------------------------------------------------------\n\n#include \"chrome_frame\/metrics_service.h\"\n\n#include \n#include \n\n#if defined(USE_SYSTEM_LIBBZ2)\n#include \n#else\n#include \"third_party\/bzip2\/bzlib.h\"\n#endif\n\n#include \"base\/file_version_info.h\"\n#include \"base\/string_util.h\"\n#include \"base\/thread.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/common\/chrome_version_info.h\"\n#include \"chrome\/installer\/util\/browser_distribution.h\"\n#include \"chrome\/installer\/util\/chrome_frame_distribution.h\"\n#include \"chrome\/installer\/util\/google_update_settings.h\"\n#include \"chrome_frame\/bind_status_callback_impl.h\"\n#include \"chrome_frame\/crash_reporting\/crash_metrics.h\"\n#include \"chrome_frame\/html_utils.h\"\n#include \"chrome_frame\/http_negotiate.h\"\n#include \"chrome_frame\/utils.h\"\n#include \"net\/base\/upload_data.h\"\n#include \"chrome_frame\/urlmon_bind_status_callback.h\"\n\nusing base::Time;\nusing base::TimeDelta;\n\nstatic const char kMetricsType[] =\n \"Content-Type: application\/vnd.mozilla.metrics.bz2\\r\\n\";\n\n\/\/ The first UMA upload occurs after this interval.\nstatic const int kInitialUMAUploadTimeoutMilliSeconds = 30000;\n\n\/\/ Default to one UMA upload per 10 mins.\nstatic const int kMinMilliSecondsPerUMAUpload = 600000;\n\nbase::LazyInstance >\n MetricsService::g_metrics_instance_(base::LINKER_INITIALIZED);\n\nextern base::LazyInstance g_statistics_recorder_;\n\n\/\/ This class provides functionality to upload the ChromeFrame UMA data to the\n\/\/ server. An instance of this class is created whenever we have data to be\n\/\/ uploaded to the server.\nclass ChromeFrameMetricsDataUploader : public BSCBImpl {\n public:\n ChromeFrameMetricsDataUploader()\n : cache_stream_(NULL),\n upload_data_size_(0) {\n DLOG(INFO) << __FUNCTION__;\n }\n\n ~ChromeFrameMetricsDataUploader() {\n DLOG(INFO) << __FUNCTION__;\n }\n\n static HRESULT ChromeFrameMetricsDataUploader::UploadDataHelper(\n const std::string& upload_data) {\n CComObject* data_uploader = NULL;\n CComObject::CreateInstance(&data_uploader);\n DCHECK(data_uploader != NULL);\n\n data_uploader->AddRef();\n HRESULT hr = data_uploader->UploadData(upload_data);\n if (FAILED(hr)) {\n DLOG(ERROR) << \"Failed to initialize ChromeFrame UMA data uploader: Err\"\n << hr;\n }\n data_uploader->Release();\n return hr;\n }\n\n HRESULT UploadData(const std::string& upload_data) {\n if (upload_data.empty()) {\n NOTREACHED() << \"Invalid upload data\";\n return E_INVALIDARG;\n }\n\n DCHECK(cache_stream_.get() == NULL);\n\n upload_data_size_ = upload_data.size() + 1;\n\n HRESULT hr = CreateStreamOnHGlobal(NULL, TRUE, cache_stream_.Receive());\n if (FAILED(hr)) {\n NOTREACHED() << \"Failed to create stream. Error:\"\n << hr;\n return hr;\n }\n\n DCHECK(cache_stream_.get());\n\n unsigned long written = 0;\n cache_stream_->Write(upload_data.c_str(), upload_data_size_, &written);\n DCHECK(written == upload_data_size_);\n\n RewindStream(cache_stream_);\n\n BrowserDistribution* dist = ChromeFrameDistribution::GetDistribution();\n server_url_ = dist->GetStatsServerURL();\n DCHECK(!server_url_.empty());\n\n hr = CreateURLMoniker(NULL, server_url_.c_str(),\n upload_moniker_.Receive());\n if (FAILED(hr)) {\n DLOG(ERROR) << \"Failed to create url moniker for url:\"\n << server_url_.c_str()\n << \" Error:\"\n << hr;\n } else {\n ScopedComPtr context;\n hr = CreateAsyncBindCtx(0, this, NULL, context.Receive());\n DCHECK(SUCCEEDED(hr));\n DCHECK(context);\n\n ScopedComPtr stream;\n hr = upload_moniker_->BindToStorage(\n context, NULL, IID_IStream,\n reinterpret_cast(stream.Receive()));\n if (FAILED(hr)) {\n NOTREACHED();\n DLOG(ERROR) << \"Failed to bind to upload data moniker. Error:\"\n << hr;\n }\n }\n return hr;\n }\n\n STDMETHOD(BeginningTransaction)(LPCWSTR url, LPCWSTR headers, DWORD reserved,\n LPWSTR* additional_headers) {\n std::string new_headers;\n new_headers = StringPrintf(\"Content-Length: %s\\r\\n\",\n base::Int64ToString(upload_data_size_).c_str());\n new_headers += kMetricsType;\n\n std::string user_agent_value = http_utils::GetDefaultUserAgent();\n user_agent_value = http_utils::AddChromeFrameToUserAgentValue(\n user_agent_value);\n\n new_headers += \"User-Agent: \" + user_agent_value;\n new_headers += \"\\r\\n\";\n\n *additional_headers = reinterpret_cast(\n CoTaskMemAlloc((new_headers.size() + 1) * sizeof(wchar_t)));\n\n lstrcpynW(*additional_headers, ASCIIToWide(new_headers).c_str(),\n new_headers.size());\n\n return BSCBImpl::BeginningTransaction(url, headers, reserved,\n additional_headers);\n }\n\n STDMETHOD(GetBindInfo)(DWORD* bind_flags, BINDINFO* bind_info) {\n if ((bind_info == NULL) || (bind_info->cbSize == 0) ||\n (bind_flags == NULL))\n return E_INVALIDARG;\n\n *bind_flags = BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE | BINDF_PULLDATA;\n \/\/ Bypass caching proxies on POSTs and PUTs and avoid writing responses to\n \/\/ these requests to the browser's cache\n *bind_flags |= BINDF_GETNEWESTVERSION | BINDF_PRAGMA_NO_CACHE;\n\n DCHECK(cache_stream_.get());\n\n \/\/ Initialize the STGMEDIUM.\n memset(&bind_info->stgmedData, 0, sizeof(STGMEDIUM));\n bind_info->grfBindInfoF = 0;\n bind_info->szCustomVerb = NULL;\n bind_info->dwBindVerb = BINDVERB_POST;\n bind_info->stgmedData.tymed = TYMED_ISTREAM;\n bind_info->stgmedData.pstm = cache_stream_.get();\n bind_info->stgmedData.pstm->AddRef();\n return BSCBImpl::GetBindInfo(bind_flags, bind_info);\n }\n\n STDMETHOD(OnResponse)(DWORD response_code, LPCWSTR response_headers,\n LPCWSTR request_headers, LPWSTR* additional_headers) {\n DLOG(INFO) << __FUNCTION__ << \" headers: \\n\" << response_headers;\n return BSCBImpl::OnResponse(response_code, response_headers,\n request_headers, additional_headers);\n }\n\n private:\n std::wstring server_url_;\n size_t upload_data_size_;\n ScopedComPtr cache_stream_;\n ScopedComPtr upload_moniker_;\n};\n\nMetricsService* MetricsService::GetInstance() {\n if (g_metrics_instance_.Pointer()->Get())\n return g_metrics_instance_.Pointer()->Get();\n\n g_metrics_instance_.Pointer()->Set(new MetricsService);\n return g_metrics_instance_.Pointer()->Get();\n}\n\nMetricsService::MetricsService()\n : recording_active_(false),\n reporting_active_(false),\n user_permits_upload_(false),\n state_(INITIALIZED),\n thread_(NULL),\n initial_uma_upload_(true),\n transmission_timer_id_(0) {\n}\n\nMetricsService::~MetricsService() {\n SetRecording(false);\n if (pending_log_) {\n delete pending_log_;\n pending_log_ = NULL;\n }\n if (current_log_) {\n delete current_log_;\n current_log_ = NULL;\n }\n}\n\nvoid MetricsService::InitializeMetricsState() {\n DCHECK(state_ == INITIALIZED);\n\n thread_ = PlatformThread::CurrentId();\n\n user_permits_upload_ = GoogleUpdateSettings::GetCollectStatsConsent();\n \/\/ Update session ID\n session_id_ = CrashMetricsReporter::GetInstance()->IncrementMetric(\n CrashMetricsReporter::SESSION_ID);\n\n \/\/ Ensure that an instance of the StatisticsRecorder object is created.\n g_statistics_recorder_.Get();\n\n CrashMetricsReporter::GetInstance()->set_active(true);\n}\n\n\/\/ static\nvoid MetricsService::Start() {\n if (GetInstance()->state_ == ACTIVE)\n return;\n\n GetInstance()->InitializeMetricsState();\n GetInstance()->SetRecording(true);\n GetInstance()->SetReporting(true);\n}\n\n\/\/ static\nvoid MetricsService::Stop() {\n GetInstance()->SetReporting(false);\n GetInstance()->SetRecording(false);\n}\n\nvoid MetricsService::SetRecording(bool enabled) {\n DCHECK_EQ(thread_, PlatformThread::CurrentId());\n if (enabled == recording_active_)\n return;\n\n if (enabled) {\n if (client_id_.empty()) {\n client_id_ = GenerateClientID();\n \/\/ Save client id somewhere.\n }\n StartRecording();\n\n } else {\n state_ = STOPPED;\n }\n recording_active_ = enabled;\n}\n\n\/\/ static\nstd::string MetricsService::GenerateClientID() {\n const int kGUIDSize = 39;\n\n GUID guid;\n HRESULT guid_result = CoCreateGuid(&guid);\n DCHECK(SUCCEEDED(guid_result));\n\n std::wstring guid_string;\n int result = StringFromGUID2(guid,\n WriteInto(&guid_string, kGUIDSize), kGUIDSize);\n DCHECK(result == kGUIDSize);\n return WideToUTF8(guid_string.substr(1, guid_string.length() - 2));\n}\n\n\/\/ static\nvoid CALLBACK MetricsService::TransmissionTimerProc(HWND window,\n unsigned int message,\n unsigned int event_id,\n unsigned int time) {\n DLOG(INFO) << \"Transmission timer notified\";\n DCHECK(GetInstance() != NULL);\n GetInstance()->UploadData();\n if (GetInstance()->initial_uma_upload_) {\n \/\/ If this is the first uma upload by this process then subsequent uma\n \/\/ uploads should occur once every 10 minutes(default).\n GetInstance()->initial_uma_upload_ = false;\n DCHECK(GetInstance()->transmission_timer_id_ != 0);\n SetTimer(NULL, GetInstance()->transmission_timer_id_,\n kMinMilliSecondsPerUMAUpload,\n reinterpret_cast(TransmissionTimerProc));\n }\n}\n\nvoid MetricsService::SetReporting(bool enable) {\n static const int kChromeFrameMetricsTimerId = 0xFFFFFFFF;\n\n DCHECK_EQ(thread_, PlatformThread::CurrentId());\n if (reporting_active_ != enable) {\n reporting_active_ = enable;\n if (reporting_active_) {\n transmission_timer_id_ =\n SetTimer(NULL, kChromeFrameMetricsTimerId,\n kInitialUMAUploadTimeoutMilliSeconds,\n reinterpret_cast(TransmissionTimerProc));\n }\n }\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ Recording control methods\n\nvoid MetricsService::StartRecording() {\n DCHECK_EQ(thread_, PlatformThread::CurrentId());\n if (current_log_)\n return;\n\n current_log_ = new MetricsLogBase(client_id_, session_id_,\n GetVersionString());\n if (state_ == INITIALIZED)\n state_ = ACTIVE;\n}\n\nvoid MetricsService::StopRecording(bool save_log) {\n DCHECK_EQ(thread_, PlatformThread::CurrentId());\n if (!current_log_)\n return;\n\n \/\/ Put incremental histogram deltas at the end of all log transmissions.\n \/\/ Don't bother if we're going to discard current_log_.\n if (save_log) {\n CrashMetricsReporter::GetInstance()->RecordCrashMetrics();\n RecordCurrentHistograms();\n }\n\n if (save_log) {\n pending_log_ = current_log_;\n }\n current_log_ = NULL;\n}\n\nvoid MetricsService::MakePendingLog() {\n DCHECK_EQ(thread_, PlatformThread::CurrentId());\n if (pending_log())\n return;\n\n switch (state_) {\n case INITIALIZED: \/\/ We should be further along by now.\n DCHECK(false);\n return;\n\n case ACTIVE:\n StopRecording(true);\n StartRecording();\n break;\n\n default:\n DCHECK(false);\n return;\n }\n\n DCHECK(pending_log());\n}\n\nbool MetricsService::TransmissionPermitted() const {\n \/\/ If the user forbids uploading that's their business, and we don't upload\n \/\/ anything.\n return user_permits_upload_;\n}\n\nstd::string MetricsService::PrepareLogSubmissionString() {\n DCHECK_EQ(thread_, PlatformThread::CurrentId());\n\n MakePendingLog();\n DCHECK(pending_log());\n if (pending_log_== NULL) {\n return std::string();\n }\n\n pending_log_->CloseLog();\n std::string pending_log_text = pending_log_->GetEncodedLogString();\n DCHECK(!pending_log_text.empty());\n DiscardPendingLog();\n return pending_log_text;\n}\n\nbool MetricsService::UploadData() {\n DCHECK_EQ(thread_, PlatformThread::CurrentId());\n\n if (!GetInstance()->TransmissionPermitted())\n return false;\n\n static long currently_uploading = 0;\n if (InterlockedCompareExchange(¤tly_uploading, 1, 0)) {\n DLOG(INFO) << \"Contention for uploading metrics data. Backing off\";\n return false;\n }\n\n std::string pending_log_text = PrepareLogSubmissionString();\n DCHECK(!pending_log_text.empty());\n\n \/\/ Allow security conscious users to see all metrics logs that we send.\n LOG(INFO) << \"METRICS LOG: \" << pending_log_text;\n\n bool ret = true;\n\n if (!Bzip2Compress(pending_log_text, &compressed_log_)) {\n NOTREACHED() << \"Failed to compress log for transmission.\";\n ret = false;\n } else {\n HRESULT hr = ChromeFrameMetricsDataUploader::UploadDataHelper(\n compressed_log_);\n DCHECK(SUCCEEDED(hr));\n }\n DiscardPendingLog();\n\n currently_uploading = 0;\n return ret;\n}\n\n\/\/ static\nstd::string MetricsService::GetVersionString() {\n chrome::VersionInfo version_info;\n if (version_info.is_valid()) {\n std::string version = version_info.Version();\n \/\/ Add the -F extensions to ensure that UMA data uploaded by ChromeFrame\n \/\/ lands in the ChromeFrame bucket.\n version += \"-F\";\n if (!version_info.IsOfficialBuild())\n version.append(\"-devel\");\n return version;\n } else {\n NOTREACHED() << \"Unable to retrieve version string.\";\n }\n\n return std::string();\n}\n<|endoftext|>"} {"text":"#include \n#include \n\ntypedef int player_id;\n\nclass TBT_game_core;\n\nstruct TBT_game_player\n{\n TBT_game_player(player_id p_id,TBT_game_core * core)\n {\n this->p_id = p_id;\n this->game_core = core;\n }\n\n void do_turn(int hand);\n \n player_id p_id;\n TBT_game_core * game_core;\n};\n\nclass TBT_game_core\n{\n public:\n TBT_game_core()\n {\n initial_stage = true;\n last_player_id = -1;\n }\n\n TBT_game_player& generate_new_player()\n { \n players.push_back(new TBT_game_player(++last_player_id,this));\n return &(players[last_player_id]);\n }\n\n void end_initial_stage()\n {\n initial_stage = false;\n current_turn_no = 0;\n score = std::vector (last_player_id,0);\n current_turn = new std::vector(last_player_id,0);\n current_turn_done = std::vector(last_player_id,false);\n }\n\n void inform_turn_done(player_id id,int hand)\n {\n current_turn->at(id) = hand;\n current_turn_done[id] = true;\n check_next_turn();\n }\n\n player_id get_winner()\n {\n if (current_turn_no < 10)\n return -1;\n player_id maxi = 0;\n for (int i = 0; i < last_player_id; i++)\n if (score[i] > score[maxi])\n maxi = i;\n return maxi;\n }\n private:\n void check_next_turn()\n {\n player_id i;\n for (i=0;i(last_player_id,false);\n old_turns.push_back(*current_turn);\n current_turn = new std::vector (last_player_id,0); \n }\n\n \/*\n All the logic is in here.\n *\n *\/\n void do_next_turn()\n {\n for (player_id i = 0;iat(i) == (current_turn->at(j)+1)%3)\n score[i]++;\n }\n\n bool initial_stage;\n player_id last_player_id;\n int current_turn_no;\n std::vector players;\n std::vector score; \n std::vector * current_turn;\n std::vector current_turn_done;\n std::vector< std::vector > old_turns;\n};\n\nvoid TBT_game_player::do_turn(int hand)\n {\n this->game_core->inform_turn_done(this->p_id,hand);\n }\n\nusing namespace boost::python;\n\nBOOST_PYTHON_MODULE(libtbtg)\n{\n class_(\"TBT_game_core\")\n .def(\"end_initial_stage\", &TBT_game_core::end_initial_stage)\n .def(\"inform_turn_done\", &TBT_game_core::inform_turn_done)\n .def(\"get_winner\", &TBT_game_core::get_winner)\n .def(\"generate_new_player\", &TBT_game_core::generate_new_player)\n ;\n\n class_(\"TBT_game_player\", init())\n .def(\"do_turn\", &TBT_game_player::do_turn)\n ;\n\n}\nfixing shivs bugs#include \n#include \n\nusing namespace boost::python;\n\ntypedef int player_id;\n\nclass TBT_game_core;\n\nstruct TBT_game_player\n{\n TBT_game_player(player_id p_id,TBT_game_core * core)\n {\n this->p_id = p_id;\n this->game_core = core;\n }\n\n void do_turn(int hand);\n \n player_id p_id;\n TBT_game_core * game_core;\n};\n\nstruct TBT_game_player_python\n{\n\tstatic PyObject* convert(TBT_game_player const& p)\n\t{\n\t\treturn boost::python::incref(boost::python::object(p).ptr());\n }\n};\n\nclass TBT_game_core\n{\n public:\n TBT_game_core()\n {\n initial_stage = true;\n last_player_id = -1;\n }\n\n PyObject * generate_new_player()\n { \n players.push_back(*(new TBT_game_player(++last_player_id, this)));\n return TBT_game_player_python::convert(players[last_player_id]);\n } \n\n void end_initial_stage()\n {\n initial_stage = false;\n current_turn_no = 0;\n score = std::vector (last_player_id + 1, 0);\n current_turn = new std::vector(last_player_id + 1, 0);\n current_turn_done = std::vector(last_player_id + 1,false);\n }\n\n void inform_turn_done(player_id id,int hand)\n {\n current_turn->at(id) = hand;\n current_turn_done[id] = true;\n check_next_turn();\n }\n\n player_id get_winner()\n {\n if (current_turn_no < 10)\n return -1;\n player_id maxi = 0;\n for (int i = 0; i < last_player_id; i++)\n if (score[i] > score[maxi])\n maxi = i;\n return maxi;\n }\n private:\n\n void check_next_turn()\n {\n player_id i;\n for (i=0;i(last_player_id,false);\n old_turns.push_back(*current_turn);\n current_turn = new std::vector (last_player_id,0); \n }\n\n \/*\n All the logic is in here.\n *\n *\/\n void do_next_turn()\n {\n for (player_id i = 0;iat(i) == (current_turn->at(j)+1)%3)\n score[i]++;\n }\n\n bool initial_stage;\n player_id last_player_id;\n int current_turn_no;\n std::vector players;\n std::vector score; \n std::vector * current_turn;\n std::vector current_turn_done;\n std::vector< std::vector > old_turns;\n};\n\nvoid TBT_game_player::do_turn(int hand)\n{\n this->game_core->inform_turn_done(this->p_id, hand);\n}\n\nBOOST_PYTHON_MODULE(libtbtg)\n{\n\n\tboost::python::to_python_converter<\n\t TBT_game_player,\n\t TBT_game_player_python>();\n\n class_(\"TBT_game_core\")\n .def(\"end_initial_stage\", &TBT_game_core::end_initial_stage)\n .def(\"inform_turn_done\", &TBT_game_core::inform_turn_done)\n .def(\"get_winner\", &TBT_game_core::get_winner)\n .def(\"generate_new_player\", &TBT_game_core::generate_new_player)\n ;\n\n class_(\"TBT_game_player\", init())\n .def(\"do_turn\", &TBT_game_player::do_turn)\n ;\n\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 Sean McKenna\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\n\/\/ light sub-classes (e.g. generic, ambient, direct, point)\n\/\/ originally adapted from code provided by Cem Yuksel\n\n\n\/\/ namespace\nusing namespace scene;\nnamespace scene{\n\n\n\/\/ generic light definition (from main light class)\nclass GenericLight: public Light{\n public:\n \n \/\/ calculate a shadow for any light (never call from ambient!)\n float shadow(Cone ray, float z = FLOAT_MAX){\n \n \/\/ set initial hit info\n HitInfo h = HitInfo();\n h.z = z;\n \n \/\/ check ray from point to light, is it occluded?\n bool occlude = traceRay(ray, h);\n \n \/\/ return 0 if in shadow, 1 if lit directly\n if(occlude)\n return 0.0;\n else\n return 1.0;\n }\n};\n\n\n\/\/ ambient light definition\nclass AmbientLight: public GenericLight{\n public:\n \n \/\/ constructor\n AmbientLight(){\n intensity.Set(0, 0, 0);\n }\n \n \/\/ get color of ambient light\n Color illuminate(Point p){\n return intensity;\n }\n \n \/\/ get direction of ambient light (non-sensical)\n Point direction(Point p){\n return Point(0, 0, 0);\n }\n \n \/\/ return true, since light is ambient\n bool isAmbient(){\n return true;\n }\n \n \/\/ set color of ambient light\n void setIntensity(Color c){\n intensity = c;\n }\n \n private:\n \n \/\/ intensity (or color) of light\n Color intensity;\n};\n\n\n\/\/ direct light definition\nclass DirectLight: public GenericLight{\n public:\n \n \/\/ constructor\n DirectLight(){\n intensity.Set(0, 0, 0);\n dir.Set(0, 0, 1);\n }\n \n \/\/ get color of direct light (check for shadows)\n Color illuminate(Point p){\n Cone r = Cone();\n r.pos = p;\n r.dir = -dir;\n return shadow(r) * intensity;\n }\n \n \/\/ get direction of direct light (constant)\n Point direction(Point p){\n return dir;\n }\n \n \/\/ set color of direct light\n void setIntensity(Color c){\n intensity = c;\n }\n \n \/\/ set direction of direct light\n void setDirection(Point d){\n dir = d.GetNormalized();\n }\n \n private:\n \n \/\/ intensity (or color) of light\n Color intensity;\n \n \/\/ direction of light\n Point dir;\n};\n\n\n\/\/ point light definition\nclass PointLight: public GenericLight{\n public:\n \n \/\/ constructor\n PointLight(){\n intensity.Set(0, 0, 0);\n position.Set(0, 0, 0);\n size = 0.0;\n }\n \n \/\/ get color of point light (check for shadows)\n Color illuminate(Point p){\n if(size == 0.0){\n Cone r = Cone();\n r.pos = p;\n r.dir = position - p;\n return shadow(r, 1.0) * intensity;\n \n \/\/ otherwise, we have a spherical light, cast multiple shadow rays\n }else{\n \n \/\/ to detect if we are in the penumbra\n bool penumbra = false;\n \n \/\/ keep track of running shadow variables\n int count;\n float mean = 0.0;\n \n \/\/ calculate random rotation for Halton sequence on our sphere of confusion\n float rotate = dist(rnd) * 2.0 * M_PI;\n \n \/\/ cast our minmum number of shadow rays\n for(count = 0; count < shadowMin; count++){\n \n \/\/ calculate (partially) randomized shadow ray\n Cone r = getShadowRay(p, count, rotate);\n \n \/\/ cast shadow ray\n int val = shadow(r, 1.0);\n \n \/\/ update our mean shadow value\n mean = ((float) (mean * count + val)) \/ ((float) (count + 1));\n \n \/\/ check if we are in penumbra\n if(mean != 0.0 && mean != 1.0)\n penumbra = true;\n }\n \n \/\/ continue casting more shadow rays, if in penumbra\n if(penumbra){\n \n \/\/ continue casting shadow rays\n for(count = shadowMin; count < shadowMax; count++){\n \n \/\/ calculate (partially) randomized shadow ray\n Cone r = getShadowRay(p, count, rotate);\n \n \/\/ cast shadow ray\n int val = shadow(r, 1.0);\n \n \/\/ update our mean shadow value\n mean = ((float) (mean * count + val)) \/ ((float) (count + 1));\n }\n }\n \n \/\/ return our final shaded intensity\n return mean * intensity;\n }\n }\n \n \/\/ get direction of point light (calculated)\n Point direction(Point p){\n return (p - position).GetNormalized();\n }\n \n \/\/ set color of point light\n void setIntensity(Color c){\n intensity = c;\n }\n \n \/\/ set the location of the point light\n void setPosition(Point pos){\n position = pos;\n }\n \n \/\/ set the size of the point light (now a sphere)\n void setSize(float s){\n size = s;\n }\n \n \/\/ set shadow ray samples (min & max)\n void setShadowRays(int min, int max){\n shadowMin = min;\n shadowMax = max;\n }\n \n private:\n \n \/\/ intensity (or color) of light\n Color intensity;\n \n \/\/ location of light\n Point position;\n \n \/\/ size of point light (sphere if not zero)\n float size;\n \n \/\/ how many shadow rays to cast\n int shadowMin;\n int shadowMax;\n \n \/\/ random number generation for light disk rotation\n mt19937 rnd;\n uniform_real_distribution dist{0.0, 1.0};\n \n \/\/ calculate a randomized light position on a spherical light\n Cone getShadowRay(Point p, int c, float r){\n \n \/\/ get original direction\n Point dir = (position - p).GetNormalized();\n \n \/\/ get two vectors for spanning our light disk\n Point v0 = Point(0.0, 1.0, 0.0);\n if(v0 % dir < 0.1 && v0 % dir > -0.1)\n v0 = Point(0.0, 0.0, 1.0);\n Point v1 = (v0 ^ dir).GetNormalized();\n \n \/\/ grab Halton sequence to shift point along light disk\n \/\/ first four points on the perimeter of the disk\n float diskRad;\n if(c < 4)\n diskRad = 1.0 * size;\n else\n diskRad = sqrt(Halton(c - 4, 2)) * size;\n \n \/\/ grab Halton sequence to shift point around light disk\n \/\/ first four points will be distributed about the perimeter\n float diskRot;\n if(c == 0)\n diskRot = 0.0;\n else if(c == 1)\n diskRot = 1.0 * M_PI;\n else if(c == 2)\n diskRot = 0.5 * M_PI;\n else if(c == 3)\n diskRot = 1.5 * M_PI;\n else\n diskRot = Halton(c - 4, 3) * 2.0 * M_PI;\n \n \/\/ compute our semi-random position inside the disk\n Point pos = position + (v0 * diskRad * cos(diskRot + r)) + (v1 * diskRad * sin(diskRot + r));\n \n \/\/ shadow ray to return\n Cone ray = Cone();\n ray.pos = p;\n ray.dir = pos - p;\n return ray;\n }\n};\n}\nupdate shadow ray calculation, better vectors to span light disk\/\/ Copyright 2013 Sean McKenna\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\n\/\/ light sub-classes (e.g. generic, ambient, direct, point)\n\/\/ originally adapted from code provided by Cem Yuksel\n\n\n\/\/ namespace\nusing namespace scene;\nnamespace scene{\n\n\n\/\/ generic light definition (from main light class)\nclass GenericLight: public Light{\n public:\n \n \/\/ calculate a shadow for any light (never call from ambient!)\n float shadow(Cone ray, float z = FLOAT_MAX){\n \n \/\/ set initial hit info\n HitInfo h = HitInfo();\n h.z = z;\n \n \/\/ check ray from point to light, is it occluded?\n bool occlude = traceRay(ray, h);\n \n \/\/ return 0 if in shadow, 1 if lit directly\n if(occlude)\n return 0.0;\n else\n return 1.0;\n }\n};\n\n\n\/\/ ambient light definition\nclass AmbientLight: public GenericLight{\n public:\n \n \/\/ constructor\n AmbientLight(){\n intensity.Set(0, 0, 0);\n }\n \n \/\/ get color of ambient light\n Color illuminate(Point p){\n return intensity;\n }\n \n \/\/ get direction of ambient light (non-sensical)\n Point direction(Point p){\n return Point(0, 0, 0);\n }\n \n \/\/ return true, since light is ambient\n bool isAmbient(){\n return true;\n }\n \n \/\/ set color of ambient light\n void setIntensity(Color c){\n intensity = c;\n }\n \n private:\n \n \/\/ intensity (or color) of light\n Color intensity;\n};\n\n\n\/\/ direct light definition\nclass DirectLight: public GenericLight{\n public:\n \n \/\/ constructor\n DirectLight(){\n intensity.Set(0, 0, 0);\n dir.Set(0, 0, 1);\n }\n \n \/\/ get color of direct light (check for shadows)\n Color illuminate(Point p){\n Cone r = Cone();\n r.pos = p;\n r.dir = -dir;\n return shadow(r) * intensity;\n }\n \n \/\/ get direction of direct light (constant)\n Point direction(Point p){\n return dir;\n }\n \n \/\/ set color of direct light\n void setIntensity(Color c){\n intensity = c;\n }\n \n \/\/ set direction of direct light\n void setDirection(Point d){\n dir = d.GetNormalized();\n }\n \n private:\n \n \/\/ intensity (or color) of light\n Color intensity;\n \n \/\/ direction of light\n Point dir;\n};\n\n\n\/\/ point light definition\nclass PointLight: public GenericLight{\n public:\n \n \/\/ constructor\n PointLight(){\n intensity.Set(0, 0, 0);\n position.Set(0, 0, 0);\n size = 0.0;\n }\n \n \/\/ get color of point light (check for shadows)\n Color illuminate(Point p){\n if(size == 0.0){\n Cone r = Cone();\n r.pos = p;\n r.dir = position - p;\n return shadow(r, 1.0) * intensity;\n \n \/\/ otherwise, we have a spherical light, cast multiple shadow rays\n }else{\n \n \/\/ to detect if we are in the penumbra\n bool penumbra = false;\n \n \/\/ keep track of running shadow variables\n int count;\n float mean = 0.0;\n \n \/\/ calculate random rotation for Halton sequence on our sphere of confusion\n float rotate = dist(rnd) * 2.0 * M_PI;\n \n \/\/ cast our minmum number of shadow rays\n for(count = 0; count < shadowMin; count++){\n \n \/\/ calculate (partially) randomized shadow ray\n Cone r = getShadowRay(p, count, rotate);\n \n \/\/ cast shadow ray\n int val = shadow(r, 1.0);\n \n \/\/ update our mean shadow value\n mean = ((float) (mean * count + val)) \/ ((float) (count + 1));\n \n \/\/ check if we are in penumbra\n if(mean != 0.0 && mean != 1.0)\n penumbra = true;\n }\n \n \/\/ continue casting more shadow rays, if in penumbra\n if(penumbra){\n \n \/\/ continue casting shadow rays\n for(count = shadowMin; count < shadowMax; count++){\n \n \/\/ calculate (partially) randomized shadow ray\n Cone r = getShadowRay(p, count, rotate);\n \n \/\/ cast shadow ray\n int val = shadow(r, 1.0);\n \n \/\/ update our mean shadow value\n mean = ((float) (mean * count + val)) \/ ((float) (count + 1));\n }\n }\n \n \/\/ return our final shaded intensity\n return mean * intensity;\n }\n }\n \n \/\/ get direction of point light (calculated)\n Point direction(Point p){\n return (p - position).GetNormalized();\n }\n \n \/\/ set color of point light\n void setIntensity(Color c){\n intensity = c;\n }\n \n \/\/ set the location of the point light\n void setPosition(Point pos){\n position = pos;\n }\n \n \/\/ set the size of the point light (now a sphere)\n void setSize(float s){\n size = s;\n }\n \n \/\/ set shadow ray samples (min & max)\n void setShadowRays(int min, int max){\n shadowMin = min;\n shadowMax = max;\n }\n \n private:\n \n \/\/ intensity (or color) of light\n Color intensity;\n \n \/\/ location of light\n Point position;\n \n \/\/ size of point light (sphere if not zero)\n float size;\n \n \/\/ how many shadow rays to cast\n int shadowMin;\n int shadowMax;\n \n \/\/ random number generation for light disk rotation\n mt19937 rnd;\n uniform_real_distribution dist{0.0, 1.0};\n \n \/\/ calculate a randomized light position on a spherical light\n Cone getShadowRay(Point p, int c, float r){\n \n \/\/ get original direction\n Point dir = (position - p).GetNormalized();\n \n \/\/ get two vectors for spanning our light disk\n Point v0 = Point(0.0, 1.0, 0.0);\n if(v0 % dir < 0.5 && v0 % dir > -0.5)\n v0 = Point(0.0, 0.0, 1.0);\n Point v1 = (v0 ^ dir).GetNormalized();\n \n \/\/ grab Halton sequence to shift point along light disk\n \/\/ first four points on the perimeter of the disk\n float diskRad;\n if(c < 4)\n diskRad = 1.0 * size;\n else\n diskRad = sqrt(Halton(c - 4, 2)) * size;\n \n \/\/ grab Halton sequence to shift point around light disk\n \/\/ first four points will be distributed about the perimeter\n float diskRot;\n if(c == 0)\n diskRot = 0.0;\n else if(c == 1)\n diskRot = 1.0 * M_PI;\n else if(c == 2)\n diskRot = 0.5 * M_PI;\n else if(c == 3)\n diskRot = 1.5 * M_PI;\n else\n diskRot = Halton(c - 4, 3) * 2.0 * M_PI;\n \n \/\/ compute our semi-random position inside the disk\n Point pos = position + (v0 * diskRad * cos(diskRot + r)) + (v1 * diskRad * sin(diskRot + r));\n \n \/\/ shadow ray to return\n Cone ray = Cone();\n ray.pos = p;\n ray.dir = pos - p;\n return ray;\n }\n};\n}\n<|endoftext|>"} {"text":"#include \n#include \/\/ exit()\n#include \/\/ printf()\n#include \/\/ strcmp()\n#include \n#include \n#include \n#include \n#include \"alphabet.h\"\n\nusing namespace std;\n\nstring pwd;\n\nchar pwdHash[SHA256_DIGEST_LENGTH];\nchar bruteHash[SHA256_DIGEST_LENGTH];\n\nstatic const unsigned char MaxChars = 3;\n\nvoid printSHAHash(unsigned int* pbuf)\n{\n \/\/ byteswap the integer pointed to, to display hex dump in correct order\n \/\/ TODO: how to deal with big endian machines\n printf(\"%X%X%X%X%X%X%X%X\\n\",\n bswap_32(*(pbuf)),\n bswap_32(*(pbuf+1)),\n bswap_32(*(pbuf+2)),\n bswap_32(*(pbuf+3)),\n bswap_32(*(pbuf+4)),\n bswap_32(*(pbuf+5)),\n bswap_32(*(pbuf+6)),\n bswap_32(*(pbuf+7))\n );\n}\n\nbool generateSHA256(const void *const inputStr, const size_t &length, char *const hashStr)\n{\n SHA256_CTX hash;\n if(!SHA256_Init(&hash))\n {\n return false;\n }\n\n if(!SHA256_Update(&hash, inputStr, length))\n {\n return false;\n }\n\n if(!SHA256_Final(reinterpret_cast(hashStr), &hash))\n {\n return false;\n }\n\n return true;\n}\n\nvoid checkPassword(const string &password)\n{\n\/\/#ifdef VERBOSE\n cout << \"checking \" << password << endl;\n\/\/#endif \/\/ VERBOSE\n\n \/\/ generate sha hash from entered string and write it to pwdHash\n if(!generateSHA256(password.c_str(), password.length(), bruteHash))\n {\n cerr << \"Error when generating SHA256 from \\\"\" << password << \"\\\"\" << endl;\n \/\/return;\n }\n\n if (!memcmp(bruteHash, pwdHash, SHA256_DIGEST_LENGTH))\n {\n cout << \"match [\" << password << \"]\" << endl << \"hash: \" << endl;\n printSHAHash((unsigned int*)bruteHash);\n exit(0);\n }\n}\n\nvoid bruteRecursive(const string baseString, const unsigned int width)\n{\n for(int i=0; i myStack;\n\n \/\/ myStack must contain at least one element when entering loop\n \/\/ else: SIGSEGV\n \/\/ hence, start checking with an empty string\n myStack.push(\"\");\n\n do\n {\n string baseString = myStack.top();\n myStack.pop();\n cout << \"checking passwords with \" << baseString.length()+1 << \" characters...\" << endl;\n for(int i=0; i> pwd;\n\n \/\/ generate sha hash from entered string and write it to pwdHash\n if(!generateSHA256(pwd.c_str(), pwd.length(), pwdHash))\n {\n cerr << \"Error when generating SHA256 from \\\"\" << pwd << \"\\\"\" << endl;\n return -2;\n }\n else\n {\n printf(\"SHA256 Hash for your string is:\\n\");\n printSHAHash((unsigned int*)pwdHash);\n\n }\n\n cout << \"checking using Recusive Method\" << endl;\n for(int i=1; i<=MaxChars; i++)\n {\n cout << \"checking passwords with \" << i << \" characters...\" << endl;\n bruteRecursive(string(\"\"),i);\n }\n\n cout << \"checking using Iterative Method\" << endl;\n bruteIterative(MaxChars);\n\n return -1;\n}\nadded lots of comments#include \n#include \/\/ exit()\n#include \/\/ printf()\n#include \/\/ memcmp()\n#include \n#include \n#include \n#include \n#include \"alphabet.h\"\n\nusing namespace std;\n\n\/\/ clear text password entered by user\nstring pwd;\n\n\/\/ contains the hash of the unknown password\nchar pwdHash[SHA256_DIGEST_LENGTH];\n\n\/\/ contains the hash of a bruteforced string\nchar bruteHash[SHA256_DIGEST_LENGTH];\n\n\/\/ the maximum number of characters bruteforce shall check\nstatic const unsigned char MaxChars = 3;\n\n\/**\n * @brief prints 32 bytes of memory\n *\n * prints a hex dump of 32 bytes of memory pointed to\n *\n * @param[in] pbuf: pointer to some memory, usually containing an SHA256 hash\n *\/\nvoid printSHAHash(const unsigned int *const pbuf)\n{\n \/\/ byteswap the integer pointed to, to display hex dump in correct order\n \/\/ TODO: how to deal with big endian machines\n printf(\"%X%X%X%X%X%X%X%X\\n\",\n bswap_32(*(pbuf)),\n bswap_32(*(pbuf+1)),\n bswap_32(*(pbuf+2)),\n bswap_32(*(pbuf+3)),\n bswap_32(*(pbuf+4)),\n bswap_32(*(pbuf+5)),\n bswap_32(*(pbuf+6)),\n bswap_32(*(pbuf+7))\n );\n}\n\n\/**\n * @brief generates an SHA256 hash\n *\n * generates an SHA256 hash using openSSL\n *\n * @param[in] input: a const pointer to const block of data, usually a char array of which the hash is being generated\n * @param[in] length: the number of bytes the that input points to holds\n * @param[in,out] hashStr: const pointer to an array of SHA256_DIGEST_LENGTH bytes that will receive the hash\n *\n * @return returns true if the hash has been generated successfully; returns false if input or hashStr is NULL or length==0; else: false\n *\/\nbool generateSHA256(const void *const input, const size_t &length, char *const hashStr)\n{\n if(!hashStr || !input || length==0)\n {\n return false;\n }\n\n SHA256_CTX hash;\n if(!SHA256_Init(&hash))\n {\n return false;\n }\n\n if(!SHA256_Update(&hash, input, length))\n {\n return false;\n }\n\n if(!SHA256_Final(reinterpret_cast(hashStr), &hash))\n {\n return false;\n }\n\n return true;\n}\n\n\/**\n * @brief checks equality of two hashes\n *\n * calculates the SHA256 hash of 'password' and compares it\n * with the initial password hash\n *\n * @param[in] password: a const string containing a guessed password\n *\/\nvoid checkPassword(const string &password)\n{\n\/\/#ifdef VERBOSE\n cout << \"checking \" << password << endl;\n\/\/#endif \/\/ VERBOSE\n\n \/\/ generate sha hash from entered string and write it to pwdHash\n if(!generateSHA256(password.c_str(), password.length(), bruteHash))\n {\n cerr << \"Error when generating SHA256 from \\\"\" << password << \"\\\"\" << endl;\n \/\/return;\n }\n\n if (!memcmp(bruteHash, pwdHash, SHA256_DIGEST_LENGTH))\n {\n cout << \"match [\" << password << \"]\" << endl << \"hash: \" << endl;\n printSHAHash((unsigned int*)bruteHash);\n exit(0);\n }\n}\n\n\/**\n * @brief recursive implementation of bruteforce\n *\n * recursive implementation of bruteforce attack\n * call it as follows: bruteRecursive(string(\"\"), width);\n *\n * @param[in] baseString: a const string indicates the prefix of a string to be checked\n * @param[in] width: the maximum number of characters you wish to be checked\n *\/\nvoid bruteRecursive(const string baseString, const unsigned int width)\n{\n for(int i=0; i myStack;\n\n \/\/ myStack must contain at least one element when entering loop\n \/\/ else: SIGSEGV\n \/\/ hence, start checking with an empty string\n myStack.push(\"\");\n\n do\n {\n string baseString = myStack.top();\n myStack.pop();\n cout << \"checking passwords with \" << baseString.length()+1 << \" characters...\" << endl;\n for(int i=0; i> pwd;\n\n \/\/ generate sha hash from entered string and write it to pwdHash\n if(!generateSHA256(pwd.c_str(), pwd.length(), pwdHash))\n {\n cerr << \"Error when generating SHA256 from \\\"\" << pwd << \"\\\"\" << endl;\n return -2;\n }\n else\n {\n printf(\"SHA256 Hash for your string is:\\n\");\n printSHAHash((unsigned int*)pwdHash);\n\n }\n\n cout << \"checking using Recusive Method\" << endl;\n for(int i=1; i<=MaxChars; i++)\n {\n cout << \"checking passwords with \" << i << \" characters...\" << endl;\n bruteRecursive(string(\"\"),i);\n }\n\n cout << \"checking using Iterative Method\" << endl;\n bruteIterative(MaxChars);\n\n return -1;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \"simd_util.h\"\n#include \"pauli_string.h\"\n#include \n#include \n#include \n\nPauliStringPtr::PauliStringPtr(\n size_t init_size,\n BitPtr init_sign,\n uint64_t *init_x,\n uint64_t *init_z,\n size_t init_stride256) :\n size(init_size),\n bit_ptr_sign(init_sign),\n _x(init_x),\n _z(init_z),\n stride256(init_stride256) {\n}\n\nPauliStringVal::PauliStringVal(size_t init_size) :\n val_sign(false),\n x_data(init_size),\n z_data(init_size) {\n}\n\nPauliStringVal::PauliStringVal(const PauliStringPtr &other) :\n val_sign(other.bit_ptr_sign.get()),\n x_data(other.size, other._x),\n z_data(other.size, other._z) {\n}\n\nPauliStringPtr PauliStringVal::ptr() const {\n return PauliStringPtr(*this);\n}\n\nstd::string PauliStringVal::str() const {\n return ptr().str();\n}\n\nvoid PauliStringPtr::swap_with(PauliStringPtr &other) {\n assert(size == other.size);\n bit_ptr_sign.swap(other.bit_ptr_sign);\n auto x256 = (__m256i *)_x;\n auto z256 = (__m256i *)_z;\n auto ox256 = (__m256i *)other._x;\n auto oz256 = (__m256i *)other._z;\n auto end = &x256[num_words256() * stride256];\n while (x256 != end) {\n std::swap(*x256, *ox256);\n std::swap(*z256, *oz256);\n x256 += stride256;\n z256 += stride256;\n ox256 += other.stride256;\n oz256 += other.stride256;\n }\n}\n\nvoid PauliStringPtr::overwrite_with(const PauliStringPtr &other) {\n assert(size == other.size);\n bit_ptr_sign.set(other.bit_ptr_sign.get());\n auto x256 = (__m256i *)_x;\n auto z256 = (__m256i *)_z;\n auto ox256 = (__m256i *)other._x;\n auto oz256 = (__m256i *)other._z;\n auto end = &x256[num_words256() * stride256];\n while (x256 != end) {\n *x256 = *ox256;\n *z256 = *oz256;\n x256 += stride256;\n z256 += stride256;\n ox256 += other.stride256;\n oz256 += other.stride256;\n }\n}\n\nPauliStringVal& PauliStringVal::operator=(const PauliStringPtr &other) noexcept {\n (*this).~PauliStringVal();\n new(this) PauliStringVal(other);\n return *this;\n}\n\nPauliStringPtr::PauliStringPtr(const PauliStringVal &other) :\n size(other.x_data.num_bits),\n bit_ptr_sign(BitPtr((void *)&other.val_sign, 0)),\n _x(other.x_data.u64),\n _z(other.z_data.u64),\n stride256(1) {\n}\n\nuint8_t PauliStringPtr::log_i_scalar_byproduct(const PauliStringPtr &other) const {\n assert(size == other.size);\n union {__m256i u256; uint64_t u64[4]; } cnt1 {};\n union {__m256i u256; uint64_t u64[4]; } cnt2 {};\n auto x256 = (__m256i *)_x;\n auto z256 = (__m256i *)_z;\n auto ox256 = (__m256i *)other._x;\n auto oz256 = (__m256i *)other._z;\n auto end = &x256[num_words256() * stride256];\n while (x256 != end) {\n auto x1 = *x256;\n auto z2 = *oz256;\n auto z1 = *z256;\n auto x2 = *ox256;\n auto t1 = x1 & z2;\n auto t2 = x2 & z1;\n auto f = t1 ^ t2;\n auto b = ((x1 ^ z2) & t2) ^ _mm256_andnot_si256(z1, _mm256_andnot_si256(x2, t1));\n cnt1.u256 ^= b;\n cnt2.u256 ^= cnt1.u256 & f;\n cnt1.u256 ^= f ^ b;\n x256 += stride256;\n z256 += stride256;\n ox256 += other.stride256;\n oz256 += other.stride256;\n }\n size_t s = 0;\n for (size_t k = 0; k < 4; k++) {\n s += (uint8_t) std::popcount(cnt1.u64[k]);\n s ^= (uint8_t) std::popcount(cnt2.u64[k]) << 1;\n }\n return s & 3;\n}\n\nstd::string PauliStringPtr::str() const {\n std::stringstream ss;\n ss << *this;\n return ss.str();\n}\n\nbool PauliStringPtr::operator==(const PauliStringPtr &other) const {\n if (size != other.size || bit_ptr_sign.get() != other.bit_ptr_sign.get()) {\n return false;\n }\n __m256i acc {};\n auto x256 = (__m256i *)_x;\n auto z256 = (__m256i *)_z;\n auto ox256 = (__m256i *)other._x;\n auto oz256 = (__m256i *)other._z;\n auto end = &x256[num_words256() * stride256];\n while (x256 != end) {\n acc |= *x256 ^ *ox256;\n acc |= *z256 ^ *oz256;\n x256 += stride256;\n z256 += stride256;\n ox256 += other.stride256;\n oz256 += other.stride256;\n }\n\n auto acc64 = (uint64_t *)&acc;\n for (size_t k = 0; k < 4; k++) {\n if (acc64[k]) {\n return false;\n }\n }\n\n return true;\n}\n\nbool PauliStringPtr::operator!=(const PauliStringPtr &other) const {\n return !(*this == other);\n}\n\nstd::ostream &operator<<(std::ostream &out, const PauliStringVal &ps) {\n return out << ps.ptr();\n}\n\nsize_t PauliStringPtr::num_words256() const {\n return ceil256(size) >> 8;\n}\n\nstd::ostream &operator<<(std::ostream &out, const PauliStringPtr &ps) {\n out << (ps.bit_ptr_sign.get() ? '-' : '+');\n auto x256 = (__m256i *)ps._x;\n auto z256 = (__m256i *)ps._z;\n auto end = &x256[ps.num_words256() * ps.stride256];\n size_t remaining = ps.size;\n while (x256 != end) {\n auto xs = m256i_to_bits(*x256);\n auto zs = m256i_to_bits(*z256);\n for (int j = 0; j < 256 && remaining; j++) {\n out << \"_XZY\"[xs[j] + 2 * zs[j]];\n remaining--;\n }\n x256 += ps.stride256;\n z256 += ps.stride256;\n }\n return out;\n}\n\nPauliStringVal PauliStringVal::from_pattern(bool sign, size_t size, const std::function &func) {\n PauliStringVal result(size);\n result.val_sign = sign;\n for (size_t i = 0; i < size; i++) {\n char c = func(i);\n bool x;\n bool z;\n if (c == 'X') {\n x = true;\n z = false;\n } else if (c == 'Y') {\n x = true;\n z = true;\n } else if (c == 'Z') {\n x = false;\n z = true;\n } else if (c == '_' || c == 'I') {\n x = false;\n z = false;\n } else {\n throw std::runtime_error(\"Unrecognized pauli character. \" + std::to_string(c));\n }\n result.x_data.u64[i \/ 64] ^= (uint64_t)x << (i & 63);\n result.z_data.u64[i \/ 64] ^= (uint64_t)z << (i & 63);\n }\n return result;\n}\n\nPauliStringVal PauliStringVal::from_str(const char *text) {\n auto sign = text[0] == '-';\n if (text[0] == '+' || text[0] == '-') {\n text++;\n }\n return PauliStringVal::from_pattern(sign, strlen(text), [&](size_t i){ return text[i]; });\n}\n\nPauliStringVal PauliStringVal::identity(size_t size) {\n return PauliStringVal(size);\n}\n\nPauliStringPtr& PauliStringPtr::operator*=(const PauliStringPtr& rhs) {\n uint8_t log_i = inplace_right_mul_with_scalar_output(rhs);\n assert((log_i & 1) == 0);\n bit_ptr_sign.toggle_if(log_i & 2);\n return *this;\n}\n\nuint8_t PauliStringPtr::inplace_right_mul_with_scalar_output(const PauliStringPtr& rhs) {\n uint8_t result = log_i_scalar_byproduct(rhs);\n result ^= (uint8_t)rhs.bit_ptr_sign.get() << 1;\n auto x256 = (__m256i *)_x;\n auto z256 = (__m256i *)_z;\n auto ox256 = (__m256i *)rhs._x;\n auto oz256 = (__m256i *)rhs._z;\n auto end = &x256[num_words256() * stride256];\n while (x256 != end) {\n *x256 ^= *ox256;\n x256 += stride256;\n ox256 += rhs.stride256;\n }\n end = &z256[num_words256() * stride256];\n while (z256 != end) {\n *z256 ^= *oz256;\n z256 += stride256;\n oz256 += rhs.stride256;\n }\n return result;\n}\n\nbool PauliStringPtr::get_x_bit(size_t k) const {\n k = (k & ~0xFF)*stride256 | (k & 0xFF);\n size_t i0 = k >> 6;\n size_t i1 = k & 63;\n return ((_x[i0] >> i1) & 1) != 0;\n}\n\nbool PauliStringPtr::get_z_bit(size_t k) const {\n k = (k & ~0xFF)*stride256 | (k & 0xFF);\n size_t i0 = k >> 6;\n size_t i1 = k & 63;\n return ((_z[i0] >> i1) & 1) != 0;\n}\n\nvoid PauliStringPtr::toggle_x_bit(size_t k) {\n k = (k & ~0xFF)*stride256 | (k & 0xFF);\n size_t i0 = k >> 6;\n size_t i1 = k & 63;\n _x[i0] ^= 1ull << i1;\n}\n\nvoid PauliStringPtr::toggle_z_bit(size_t k) {\n k = (k & ~0xFF)*stride256 | (k & 0xFF);\n size_t i0 = k >> 6;\n size_t i1 = k & 63;\n _z[i0] ^= 1ull << i1;\n}\n\nvoid PauliStringPtr::set_x_bit(size_t k, bool val) {\n k = (k & ~0xFF)*stride256 | (k & 0xFF);\n size_t i0 = k >> 6;\n size_t i1 = k & 63;\n _x[i0] &= ~(1ull << i1);\n _x[i0] ^= (uint64_t)val << i1;\n}\n\nvoid PauliStringPtr::set_z_bit(size_t k, bool val) {\n k = (k & ~0xFF)*stride256 | (k & 0xFF);\n size_t i0 = k >> 6;\n size_t i1 = k & 63;\n _z[i0] &= ~(1ull << i1);\n _z[i0] ^= (uint64_t)val << i1;\n}\n\nvoid PauliStringPtr::gather_into(PauliStringPtr &out, const std::vector &in_indices) const {\n assert(in_indices.size() == out.size);\n for (size_t k_out = 0; k_out < out.size; k_out++) {\n size_t k_in = in_indices[k_out];\n out.set_x_bit(k_out, get_x_bit(k_in));\n out.set_z_bit(k_out, get_z_bit(k_in));\n }\n}\n\nvoid PauliStringPtr::scatter_into(PauliStringPtr &out, const std::vector &out_indices) const {\n assert(size == out_indices.size());\n for (size_t k_in = 0; k_in < size; k_in++) {\n size_t k_out = out_indices[k_in];\n out.set_x_bit(k_out, get_x_bit(k_in));\n out.set_z_bit(k_out, get_z_bit(k_in));\n }\n out.bit_ptr_sign.toggle_if(bit_ptr_sign.get());\n}\n\nbool PauliStringVal::operator==(const PauliStringPtr &other) const {\n return ptr() == other;\n}\nbool PauliStringVal::operator!=(const PauliStringPtr &other) const {\n return ptr() != other;\n}\nCommenting#include \n#include \n#include \n#include \n#include \n#include \"simd_util.h\"\n#include \"pauli_string.h\"\n#include \n#include \n#include \n\nPauliStringPtr::PauliStringPtr(\n size_t init_size,\n BitPtr init_sign,\n uint64_t *init_x,\n uint64_t *init_z,\n size_t init_stride256) :\n size(init_size),\n bit_ptr_sign(init_sign),\n _x(init_x),\n _z(init_z),\n stride256(init_stride256) {\n}\n\nPauliStringVal::PauliStringVal(size_t init_size) :\n val_sign(false),\n x_data(init_size),\n z_data(init_size) {\n}\n\nPauliStringVal::PauliStringVal(const PauliStringPtr &other) :\n val_sign(other.bit_ptr_sign.get()),\n x_data(other.size, other._x),\n z_data(other.size, other._z) {\n}\n\nPauliStringPtr PauliStringVal::ptr() const {\n return PauliStringPtr(*this);\n}\n\nstd::string PauliStringVal::str() const {\n return ptr().str();\n}\n\nvoid PauliStringPtr::swap_with(PauliStringPtr &other) {\n assert(size == other.size);\n bit_ptr_sign.swap(other.bit_ptr_sign);\n auto x256 = (__m256i *)_x;\n auto z256 = (__m256i *)_z;\n auto ox256 = (__m256i *)other._x;\n auto oz256 = (__m256i *)other._z;\n auto end = &x256[num_words256() * stride256];\n while (x256 != end) {\n std::swap(*x256, *ox256);\n std::swap(*z256, *oz256);\n x256 += stride256;\n z256 += stride256;\n ox256 += other.stride256;\n oz256 += other.stride256;\n }\n}\n\nvoid PauliStringPtr::overwrite_with(const PauliStringPtr &other) {\n assert(size == other.size);\n bit_ptr_sign.set(other.bit_ptr_sign.get());\n auto x256 = (__m256i *)_x;\n auto z256 = (__m256i *)_z;\n auto ox256 = (__m256i *)other._x;\n auto oz256 = (__m256i *)other._z;\n auto end = &x256[num_words256() * stride256];\n while (x256 != end) {\n *x256 = *ox256;\n *z256 = *oz256;\n x256 += stride256;\n z256 += stride256;\n ox256 += other.stride256;\n oz256 += other.stride256;\n }\n}\n\nPauliStringVal& PauliStringVal::operator=(const PauliStringPtr &other) noexcept {\n (*this).~PauliStringVal();\n new(this) PauliStringVal(other);\n return *this;\n}\n\nPauliStringPtr::PauliStringPtr(const PauliStringVal &other) :\n size(other.x_data.num_bits),\n bit_ptr_sign(BitPtr((void *)&other.val_sign, 0)),\n _x(other.x_data.u64),\n _z(other.z_data.u64),\n stride256(1) {\n}\n\nuint8_t PauliStringPtr::log_i_scalar_byproduct(const PauliStringPtr &other) const {\n assert(size == other.size);\n union {__m256i u256; uint64_t u64[4]; } cnt1 {};\n union {__m256i u256; uint64_t u64[4]; } cnt2 {};\n auto x256 = (__m256i *)_x;\n auto z256 = (__m256i *)_z;\n auto ox256 = (__m256i *)other._x;\n auto oz256 = (__m256i *)other._z;\n auto end = &x256[num_words256() * stride256];\n while (x256 != end) {\n \/\/ Load into registers.\n auto x1 = *x256;\n auto z2 = *oz256;\n auto z1 = *z256;\n auto x2 = *ox256;\n\n auto t1 = x1 & z2;\n auto t2 = x2 & z1;\n \/\/ At each bit position: do the Paulis anti-commute?\n auto a = t1 ^ t2;\n \/\/ At each bit position: do the Paulis anti-commute and produce a -i instead of a +i?\n auto b = ((x1 ^ z2) & t2) ^ _mm256_andnot_si256(z1, _mm256_andnot_si256(x2, t1));\n \/\/ At each bit position: `count += forward - backward` where `backward=b`, `forward=a^b`, `count=cnt1 + 2*cnt2`.\n cnt1.u256 ^= b;\n cnt2.u256 ^= cnt1.u256 & a;\n cnt1.u256 ^= a ^ b;\n\n \/\/ Move along.\n x256 += stride256;\n z256 += stride256;\n ox256 += other.stride256;\n oz256 += other.stride256;\n }\n\n \/\/ Combine final anti-commutation phase tally (mod 4).\n size_t s = 0;\n for (size_t k = 0; k < 4; k++) {\n s += (uint8_t) std::popcount(cnt1.u64[k]);\n s ^= (uint8_t) std::popcount(cnt2.u64[k]) << 1;\n }\n return s & 3;\n}\n\nstd::string PauliStringPtr::str() const {\n std::stringstream ss;\n ss << *this;\n return ss.str();\n}\n\nbool PauliStringPtr::operator==(const PauliStringPtr &other) const {\n if (size != other.size || bit_ptr_sign.get() != other.bit_ptr_sign.get()) {\n return false;\n }\n __m256i acc {};\n auto x256 = (__m256i *)_x;\n auto z256 = (__m256i *)_z;\n auto ox256 = (__m256i *)other._x;\n auto oz256 = (__m256i *)other._z;\n auto end = &x256[num_words256() * stride256];\n while (x256 != end) {\n acc |= *x256 ^ *ox256;\n acc |= *z256 ^ *oz256;\n x256 += stride256;\n z256 += stride256;\n ox256 += other.stride256;\n oz256 += other.stride256;\n }\n\n auto acc64 = (uint64_t *)&acc;\n for (size_t k = 0; k < 4; k++) {\n if (acc64[k]) {\n return false;\n }\n }\n\n return true;\n}\n\nbool PauliStringPtr::operator!=(const PauliStringPtr &other) const {\n return !(*this == other);\n}\n\nstd::ostream &operator<<(std::ostream &out, const PauliStringVal &ps) {\n return out << ps.ptr();\n}\n\nsize_t PauliStringPtr::num_words256() const {\n return ceil256(size) >> 8;\n}\n\nstd::ostream &operator<<(std::ostream &out, const PauliStringPtr &ps) {\n out << (ps.bit_ptr_sign.get() ? '-' : '+');\n auto x256 = (__m256i *)ps._x;\n auto z256 = (__m256i *)ps._z;\n auto end = &x256[ps.num_words256() * ps.stride256];\n size_t remaining = ps.size;\n while (x256 != end) {\n auto xs = m256i_to_bits(*x256);\n auto zs = m256i_to_bits(*z256);\n for (int j = 0; j < 256 && remaining; j++) {\n out << \"_XZY\"[xs[j] + 2 * zs[j]];\n remaining--;\n }\n x256 += ps.stride256;\n z256 += ps.stride256;\n }\n return out;\n}\n\nPauliStringVal PauliStringVal::from_pattern(bool sign, size_t size, const std::function &func) {\n PauliStringVal result(size);\n result.val_sign = sign;\n for (size_t i = 0; i < size; i++) {\n char c = func(i);\n bool x;\n bool z;\n if (c == 'X') {\n x = true;\n z = false;\n } else if (c == 'Y') {\n x = true;\n z = true;\n } else if (c == 'Z') {\n x = false;\n z = true;\n } else if (c == '_' || c == 'I') {\n x = false;\n z = false;\n } else {\n throw std::runtime_error(\"Unrecognized pauli character. \" + std::to_string(c));\n }\n result.x_data.u64[i \/ 64] ^= (uint64_t)x << (i & 63);\n result.z_data.u64[i \/ 64] ^= (uint64_t)z << (i & 63);\n }\n return result;\n}\n\nPauliStringVal PauliStringVal::from_str(const char *text) {\n auto sign = text[0] == '-';\n if (text[0] == '+' || text[0] == '-') {\n text++;\n }\n return PauliStringVal::from_pattern(sign, strlen(text), [&](size_t i){ return text[i]; });\n}\n\nPauliStringVal PauliStringVal::identity(size_t size) {\n return PauliStringVal(size);\n}\n\nPauliStringPtr& PauliStringPtr::operator*=(const PauliStringPtr& rhs) {\n uint8_t log_i = inplace_right_mul_with_scalar_output(rhs);\n assert((log_i & 1) == 0);\n bit_ptr_sign.toggle_if(log_i & 2);\n return *this;\n}\n\nuint8_t PauliStringPtr::inplace_right_mul_with_scalar_output(const PauliStringPtr& rhs) {\n uint8_t result = log_i_scalar_byproduct(rhs);\n result ^= (uint8_t)rhs.bit_ptr_sign.get() << 1;\n auto x256 = (__m256i *)_x;\n auto z256 = (__m256i *)_z;\n auto ox256 = (__m256i *)rhs._x;\n auto oz256 = (__m256i *)rhs._z;\n auto end = &x256[num_words256() * stride256];\n while (x256 != end) {\n *x256 ^= *ox256;\n x256 += stride256;\n ox256 += rhs.stride256;\n }\n end = &z256[num_words256() * stride256];\n while (z256 != end) {\n *z256 ^= *oz256;\n z256 += stride256;\n oz256 += rhs.stride256;\n }\n return result;\n}\n\nbool PauliStringPtr::get_x_bit(size_t k) const {\n k = (k & ~0xFF)*stride256 | (k & 0xFF);\n size_t i0 = k >> 6;\n size_t i1 = k & 63;\n return ((_x[i0] >> i1) & 1) != 0;\n}\n\nbool PauliStringPtr::get_z_bit(size_t k) const {\n k = (k & ~0xFF)*stride256 | (k & 0xFF);\n size_t i0 = k >> 6;\n size_t i1 = k & 63;\n return ((_z[i0] >> i1) & 1) != 0;\n}\n\nvoid PauliStringPtr::toggle_x_bit(size_t k) {\n k = (k & ~0xFF)*stride256 | (k & 0xFF);\n size_t i0 = k >> 6;\n size_t i1 = k & 63;\n _x[i0] ^= 1ull << i1;\n}\n\nvoid PauliStringPtr::toggle_z_bit(size_t k) {\n k = (k & ~0xFF)*stride256 | (k & 0xFF);\n size_t i0 = k >> 6;\n size_t i1 = k & 63;\n _z[i0] ^= 1ull << i1;\n}\n\nvoid PauliStringPtr::set_x_bit(size_t k, bool val) {\n k = (k & ~0xFF)*stride256 | (k & 0xFF);\n size_t i0 = k >> 6;\n size_t i1 = k & 63;\n _x[i0] &= ~(1ull << i1);\n _x[i0] ^= (uint64_t)val << i1;\n}\n\nvoid PauliStringPtr::set_z_bit(size_t k, bool val) {\n k = (k & ~0xFF)*stride256 | (k & 0xFF);\n size_t i0 = k >> 6;\n size_t i1 = k & 63;\n _z[i0] &= ~(1ull << i1);\n _z[i0] ^= (uint64_t)val << i1;\n}\n\nvoid PauliStringPtr::gather_into(PauliStringPtr &out, const std::vector &in_indices) const {\n assert(in_indices.size() == out.size);\n for (size_t k_out = 0; k_out < out.size; k_out++) {\n size_t k_in = in_indices[k_out];\n out.set_x_bit(k_out, get_x_bit(k_in));\n out.set_z_bit(k_out, get_z_bit(k_in));\n }\n}\n\nvoid PauliStringPtr::scatter_into(PauliStringPtr &out, const std::vector &out_indices) const {\n assert(size == out_indices.size());\n for (size_t k_in = 0; k_in < size; k_in++) {\n size_t k_out = out_indices[k_in];\n out.set_x_bit(k_out, get_x_bit(k_in));\n out.set_z_bit(k_out, get_z_bit(k_in));\n }\n out.bit_ptr_sign.toggle_if(bit_ptr_sign.get());\n}\n\nbool PauliStringVal::operator==(const PauliStringPtr &other) const {\n return ptr() == other;\n}\nbool PauliStringVal::operator!=(const PauliStringPtr &other) const {\n return ptr() != other;\n}\n<|endoftext|>"} {"text":"\/*\n * Adplug - Replayer for many OPL2\/OPL3 audio file formats.\n * Copyright (C) 1999, 2000, 2001 Simon Peter, , et al.\n * \n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n *\n * sa2.cpp - SAdT2 Loader by Simon Peter (dn.tlp@gmx.net)\n *\n * NOTES:\n * SAdT2 version 7 files are unimplemented (i don't have any).\n *\/\n\n#include \n\n#include \"sa2.h\"\n\nbool Csa2Loader::load(istream &f)\n{\n\tstruct {\n\t\tunsigned char data[11],arpstart,arpspeed,arppos,arpspdcnt;\n\t} insts[31];\n\tunsigned char buf;\n\tint i,j;\n\tconst unsigned char convfx[16] = {0,1,2,3,4,5,6,255,8,255,10,11,12,13,255,15};\n\n\t\/\/ file validation section\n\tf.read((char *)&header,sizeof(sa2header));\n\tif(strncmp(header.sadt,\"SAdT\",4) || (header.version != 9 && header.version != 8))\n\t\treturn false;\n\n\t\/\/ load section\n\tf.read((char *)insts,31*15);\t\t\t\t\/\/ instruments\n\tf.read((char *)instname,29*17);\t\t\t\t\/\/ instrument names\n\tf.ignore(3);\t\t\t\t\t\t\t\t\/\/ dummy bytes\n\tf.read(order,sizeof(order));\t\t\t\t\/\/ pattern orders\n\tf.read((char *)&nop,2); f.read(&length,1); f.read(&restartpos,1); f.read((char *)&bpm,2);\t\/\/ infos\n\tf.read(arplist,sizeof(arplist));\t\t\t\/\/ arpeggio list\n\tf.read(arpcmd,sizeof(arpcmd));\t\t\t\t\/\/ arpeggio commands\n\tfor(i=0;i<64*9;i++)\t\t\t\t\t\t\t\/\/ track orders\n\t\tf.read((char *)&trackord[i\/9][i%9],1);\n\tif(header.version == 9)\n\t\tf.read((char *)&activechan,2);\t\t\t\/\/ active channels\n\telse\n\t\tactivechan = 0xffff;\t\/\/ v8 files have always all channels active\n\n\t\/\/ track data\n\ti = 0;\n\twhile(f.peek() != EOF) {\n\t\tfor(j=0;j<64;j++) {\n\t\t\tbuf = f.get();\n\t\t\ttracks[i][j].note = buf >> 1;\n\t\t\ttracks[i][j].inst = (buf & 1) << 4;\n\t\t\tbuf = f.get();\n\t\t\ttracks[i][j].inst += buf >> 4;\n\t\t\ttracks[i][j].command = convfx[buf & 0x0f];\n\t\t\tbuf = f.get();\n\t\t\ttracks[i][j].param1 = buf >> 4;\n\t\t\ttracks[i][j].param2 = buf & 0x0f;\n\t\t}\n\t\ti++;\n\t}\n\n\t\/\/ convert instruments\n\tfor(i=0;i<31;i++) {\n\t\tfor(j=0;j<11;j++)\n\t\t\tinst[i].data[j] = insts[i].data[j];\n\t\tinst[i].arpstart = insts[i].arpstart;\n\t\tinst[i].arpspeed = insts[i].arpspeed;\n\t\tinst[i].arppos = insts[i].arppos;\n\t\tinst[i].arpspdcnt = insts[i].arpspdcnt;\n\t\tinst[i].misc = 0;\n\t\tinst[i].slide = 0;\n\t}\n\n\t\/\/ fix instrument names\n\tfor(i=0;i<29;i++)\n\t\tfor(j=0;j<17;j++)\n\t\t\tif(!instname[i][j])\n\t\t\t\tinstname[i][j] = ' ';\n\n\trewind(0);\t\t\/\/ rewind module\n\treturn true;\n}\n\nstd::string Csa2Loader::gettype()\n{\n\tchar tmpstr[40];\n\n\tsprintf(tmpstr,\"Surprise! Adlib Tracker 2 (version %d)\",header.version);\n\treturn std::string(tmpstr);\n}\n\nstd::string Csa2Loader::gettitle()\n{\n\tchar bufinst[29*17],buf[18];\n\tint i,ptr;\n\n\t\/\/ parse instrument names for song name\n\tmemset(bufinst,'\\0',29*17);\n\tfor(i=0;i<29;i++) {\n\t\tbuf[16] = ' '; buf[17] = '\\0';\n\t\tmemcpy(buf,instname[i]+1,16);\n\t\tfor(ptr=16;ptr>0;ptr--)\n\t\t\tif(buf[ptr] == ' ')\n\t\t\t\tbuf[ptr] = '\\0';\n\t\t\telse {\n\t\t\t\tif(ptr<16)\n\t\t\t\t\tbuf[ptr+1] = ' ';\n\t\t\t\tbreak;\n\t\t\t}\n\t\tstrcat(bufinst,buf);\n\t}\n\n\tif(strchr(bufinst,'\"'))\n\t\treturn std::string(bufinst,strchr(bufinst,'\"')-bufinst+1,strrchr(bufinst,'\"')-strchr(bufinst,'\"')-1);\n\telse\n\t\treturn std::string();\n}\n.SAT support added to sa2.cpp - thanks mamiya\/*\n * Adplug - Replayer for many OPL2\/OPL3 audio file formats.\n * Copyright (C) 1999, 2000, 2001 Simon Peter, , et al.\n * \n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n *\n * sa2.cpp - SAdT2 Loader by Simon Peter (dn.tlp@gmx.net)\n * SAdT Loader by Mamiya(mamiya@users.sourceforge.net)\n *\n *\/\n\n#include \n\n#include \"sa2.h\"\n\nbool Csa2Loader::load(istream &f)\n{\n\tstruct {\n\t\tunsigned char data[11],arpstart,arpspeed,arppos,arpspdcnt;\n\t} insts;\n\tunsigned char buf;\n\tint i,j, k, notedis = 0;\n\tconst unsigned char convfx[16] = {0,1,2,3,4,5,6,255,8,255,10,11,12,13,255,15};\n\tunsigned sat_type;\n\tenum SAT_TYPE {\n\t\tHAS_ARPEGIOLIST = (1 << 7),\n\t\tHAS_V7PATTERNS = (1 << 6),\n\t\tHAS_ACTIVECHANNELS = (1 << 5),\n\t\tHAS_TRACKORDER = (1 << 4),\n\t\tHAS_ARPEGIO = (1 << 3),\n\t\tHAS_OLDBPM = (1 << 2),\n\t\tHAS_OLDPATTERNS = (1 << 1),\n\t\tHAS_UNKNOWN127 = (1 << 0)\n\t};\n\n\t\/\/ file validation section\n\tf.read((char *)&header,sizeof(sa2header));\n\tif(strncmp(header.sadt,\"SAdT\",4))\n\t\treturn false;\n\tswitch(header.version) {\n\tcase 1:\n\t\tnotedis = +0x18;\n\t\tsat_type = HAS_UNKNOWN127 | HAS_OLDPATTERNS | HAS_OLDBPM;\n\t\tbreak;\n\tcase 2:\n\t\tnotedis = +0x18;\n\t\tsat_type = HAS_OLDPATTERNS | HAS_OLDBPM;\n\t\tbreak;\n\tcase 3:\n\t\tnotedis = +0x0c;\n\t\tsat_type = HAS_OLDPATTERNS | HAS_OLDBPM;\n\t\tbreak;\n\tcase 4:\n\t\tnotedis = +0x0c;\n\t\tsat_type = HAS_ARPEGIO | HAS_OLDPATTERNS | HAS_OLDBPM;\n\t\tbreak;\n\tcase 5:\n\t\tnotedis = +0x0c;\n\t\tsat_type = HAS_ARPEGIO | HAS_ARPEGIOLIST | HAS_OLDPATTERNS | HAS_OLDBPM;\n\t\tbreak;\n\tcase 6:\n\t\tsat_type = HAS_ARPEGIO | HAS_ARPEGIOLIST | HAS_OLDPATTERNS | HAS_OLDBPM;\n\t\tbreak;\n\tcase 7:\n\t\tsat_type = HAS_ARPEGIO | HAS_ARPEGIOLIST | HAS_V7PATTERNS;\n\t\tbreak;\n\tcase 8:\n\t\tsat_type = HAS_ARPEGIO | HAS_ARPEGIOLIST | HAS_TRACKORDER;\n\t\tbreak;\n\tcase 9:\n\t\tsat_type = HAS_ARPEGIO | HAS_ARPEGIOLIST | HAS_TRACKORDER | HAS_ACTIVECHANNELS;\n\t\tbreak;\n\tdefault:\t\/* unknown *\/\n\t\treturn false;\n\t}\n\n\t\/\/ load section\n\tfor(i = 0; i < 31; i++) {\n\t\tif(sat_type & HAS_ARPEGIO) {\n\t\t\tf.read((char *)&insts,15);\t\t\t\/\/ instruments\n\t\t\tinst[i].arpstart = insts.arpstart;\n\t\t\tinst[i].arpspeed = insts.arpspeed;\n\t\t\tinst[i].arppos = insts.arppos;\n\t\t\tinst[i].arpspdcnt = insts.arpspdcnt;\n\t\t} else {\n\t\t\tf.read((char *)&insts,11);\t\t\t\/\/ instruments\n\t\t\tinst[i].arpstart = 0;\n\t\t\tinst[i].arpspeed = 0;\n\t\t\tinst[i].arppos = 0;\n\t\t\tinst[i].arpspdcnt = 0;\n\t\t}\n\t\tfor(j=0;j<11;j++)\n\t\t\tinst[i].data[j] = insts.data[j];\n\t\tinst[i].misc = 0;\n\t\tinst[i].slide = 0;\n\t}\n\tf.read((char *)instname,29*17);\t\t\t\t\/\/ instrument names\n\tf.ignore(3);\t\t\t\t\t\t\t\t\/\/ dummy bytes\n\tf.read(order,128);\t\t\t\t\t\t\t\/\/ pattern orders\n\tif (sat_type & HAS_UNKNOWN127) f.ignore(127);\n\n\t\/\/ infos\n\tf.read((char *)&nop,2); f.read(&length,1); f.read(&restartpos,1);\n\n\t\/\/ bpm\n\tf.read((char *)&bpm,2);\n\tif(sat_type & HAS_OLDBPM) {\n\t\tbpm = bpm * 125 \/ 50;\t\t\t\t\t\/\/ cps -> bpm\n\t}\n\n\tif(sat_type & HAS_ARPEGIOLIST) {\n\t\tf.read(arplist,sizeof(arplist));\t\t\/\/ arpeggio list\n\t\tf.read(arpcmd,sizeof(arpcmd));\t\t\t\/\/ arpeggio commands\n\t}\n\n\tfor(i=0;i<64;i++) {\t\t\t\t\t\t\t\/\/ track orders\n\t\tfor(j=0;j<9;j++) {\n\t\t\tif(sat_type & HAS_TRACKORDER)\n\t\t\t\tf.read((char *)&trackord[i][j],1);\n\t\t\telse\n\t\t\t{\n\t\t\t\ttrackord[i][j] = i * 9 + j;\n\t\t\t}\n\t\t}\n\t}\n\n\tif(sat_type & HAS_ACTIVECHANNELS)\n\t\tf.read((char *)&activechan,2);\t\t\t\/\/ active channels\n\telse\n\t\tactivechan = 0xffff;\n\n\t\/\/ track data\n\tif(sat_type & HAS_OLDPATTERNS) {\n\t\ti = 0;\n\t\twhile(f.peek() != EOF) {\n\t\t\tfor(j=0;j<64;j++) {\n\t\t\t\tfor(k=0;k<9;k++) {\n\t\t\t\t\tbuf = f.get();\n\t\t\t\t\ttracks[i+k][j].note = buf ? (buf + notedis) : 0;\n\t\t\t\t\ttracks[i+k][j].inst = f.get();\n\t\t\t\t\ttracks[i+k][j].command = convfx[f.get() & 0xf];\n\t\t\t\t\ttracks[i+k][j].param1 = f.get();\n\t\t\t\t\ttracks[i+k][j].param2 = f.get();\n\t\t\t\t}\n\t\t\t}\n\t\t\ti+=9;\n\t\t}\n\t} else if(sat_type & HAS_V7PATTERNS) {\n\t\ti = 0;\n\t\twhile(f.peek() != EOF) {\n\t\t\tfor(j=0;j<64;j++) {\n\t\t\t\tfor(k=0;k<9;k++) {\n\t\t\t\t\tbuf = f.get();\n\t\t\t\t\ttracks[i+k][j].note = buf >> 1;\n\t\t\t\t\ttracks[i+k][j].inst = (buf & 1) << 4;\n\t\t\t\t\tbuf = f.get();\n\t\t\t\t\ttracks[i+k][j].inst += buf >> 4;\n\t\t\t\t\ttracks[i+k][j].command = convfx[buf & 0x0f];\n\t\t\t\t\tbuf = f.get();\n\t\t\t\t\ttracks[i+k][j].param1 = buf >> 4;\n\t\t\t\t\ttracks[i+k][j].param2 = buf & 0x0f;\n\t\t\t\t}\n\t\t\t}\n\t\t\ti+=9;\n\t\t}\n\t} else {\n\t\ti = 0;\n\t\twhile(f.peek() != EOF) {\n\t\t\tfor(j=0;j<64;j++) {\n\t\t\t\tbuf = f.get();\n\t\t\t\ttracks[i][j].note = buf >> 1;\n\t\t\t\ttracks[i][j].inst = (buf & 1) << 4;\n\t\t\t\tbuf = f.get();\n\t\t\t\ttracks[i][j].inst += buf >> 4;\n\t\t\t\ttracks[i][j].command = convfx[buf & 0x0f];\n\t\t\t\tbuf = f.get();\n\t\t\t\ttracks[i][j].param1 = buf >> 4;\n\t\t\t\ttracks[i][j].param2 = buf & 0x0f;\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\t}\n\n\t\/\/ fix instrument names\n\tfor(i=0;i<29;i++)\n\t\tfor(j=0;j<17;j++)\n\t\t\tif(!instname[i][j])\n\t\t\t\tinstname[i][j] = ' ';\n\n\trewind(0);\t\t\/\/ rewind module\n\treturn true;\n}\n\nstd::string Csa2Loader::gettype()\n{\n\tchar tmpstr[40];\n\n\tsprintf(tmpstr,\"Surprise! Adlib Tracker 2 (version %d)\",header.version);\n\treturn std::string(tmpstr);\n}\n\nstd::string Csa2Loader::gettitle()\n{\n\tchar bufinst[29*17],buf[18];\n\tint i,ptr;\n\n\t\/\/ parse instrument names for song name\n\tmemset(bufinst,'\\0',29*17);\n\tfor(i=0;i<29;i++) {\n\t\tbuf[16] = ' '; buf[17] = '\\0';\n\t\tmemcpy(buf,instname[i]+1,16);\n\t\tfor(ptr=16;ptr>0;ptr--)\n\t\t\tif(buf[ptr] == ' ')\n\t\t\t\tbuf[ptr] = '\\0';\n\t\t\telse {\n\t\t\t\tif(ptr<16)\n\t\t\t\t\tbuf[ptr+1] = ' ';\n\t\t\t\tbreak;\n\t\t\t}\n\t\tstrcat(bufinst,buf);\n\t}\n\n\tif(strchr(bufinst,'\"'))\n\t\treturn std::string(bufinst,strchr(bufinst,'\"')-bufinst+1,strrchr(bufinst,'\"')-strchr(bufinst,'\"')-1);\n\telse\n\t\treturn std::string();\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ ExecutorImplementation.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 01\/05\/2022.\n\/\/ Copyright © 2022 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef InstructionSets_M68k_ExecutorImplementation_hpp\n#define InstructionSets_M68k_ExecutorImplementation_hpp\n\n#include \"..\/Perform.hpp\"\n#include \n\nnamespace InstructionSet {\nnamespace M68k {\n\ntemplate \nExecutor::Executor(BusHandler &handler) : bus_handler_(handler) {\n\treset();\n}\n\ntemplate \nvoid Executor::reset() {\n\t\/\/ Establish: supervisor state, all interrupts blocked.\n\tstatus_.set_status(0b0010'0011'1000'0000);\n\n\t\/\/ Seed stack pointer and program counter.\n\tdata_[7] = bus_handler_.template read(0);\n\tprogram_counter_.l = bus_handler_.template read(4);\n}\n\ntemplate \nvoid Executor::read(DataSize size, uint32_t address, CPU::SlicedInt32 &value) {\n\tswitch(size) {\n\t\tcase DataSize::Byte:\n\t\t\tvalue.b = bus_handler_.template read(address);\n\t\tbreak;\n\t\tcase DataSize::Word:\n\t\t\tvalue.w = bus_handler_.template read(address);\n\t\tbreak;\n\t\tcase DataSize::LongWord:\n\t\t\tvalue.l = bus_handler_.template read(address);\n\t\tbreak;\n\t}\n}\n\ntemplate \nvoid Executor::write(DataSize size, uint32_t address, CPU::SlicedInt32 value) {\n\tswitch(size) {\n\t\tcase DataSize::Byte:\n\t\t\t bus_handler_.template write(address, value.b);\n\t\tbreak;\n\t\tcase DataSize::Word:\n\t\t\tbus_handler_.template write(address, value.w);\n\t\tbreak;\n\t\tcase DataSize::LongWord:\n\t\t\tbus_handler_.template write(address, value.l);\n\t\tbreak;\n\t}\n}\n\ntemplate \ntemplate IntT Executor::read_pc() {\n\tconst IntT result = bus_handler_.template read(program_counter_.l);\n\n\tif constexpr (sizeof(IntT) == 4) {\n\t\tprogram_counter_.l += 4;\n\t} else {\n\t\tprogram_counter_.l += 2;\n\t}\n\n\treturn result;\n}\n\ntemplate \nuint32_t Executor::index_8bitdisplacement() {\n\t\/\/ TODO: if not a 68000, check bit 8 for whether this should be a full extension word;\n\t\/\/ also include the scale field even if not.\n\tconst auto extension = read_pc();\n\tconst auto offset = int8_t(extension);\n\tconst int register_index = (extension >> 11) & 7;\n\tconst uint32_t displacement = (extension & 0x8000) ? address_[register_index].l : data_[register_index].l;\n\treturn offset + (extension & 0x800) ? displacement : uint16_t(displacement);\n}\n\ntemplate \ntypename Executor::EffectiveAddress Executor::calculate_effective_address(Preinstruction instruction, uint16_t opcode, int index) {\n\tEffectiveAddress ea;\n\n\tswitch(instruction.mode(index)) {\n\t\tcase AddressingMode::None:\n\t\t\t\/\/ Permit an uninitialised effective address to be returned;\n\t\t\t\/\/ this value shouldn't be used.\n\t\tbreak;\n\n\t\t\/\/\n\t\t\/\/ Operands that don't have effective addresses, which are returned as values.\n\t\t\/\/\n\t\tcase AddressingMode::DataRegisterDirect:\n\t\t\tea.value = data_[instruction.reg(index)];\n\t\t\tea.requires_fetch = false;\n\t\tbreak;\n\t\tcase AddressingMode::AddressRegisterDirect:\n\t\t\tea.value = address_[instruction.reg(index)];\n\t\t\tea.requires_fetch = false;\n\t\tbreak;\n\t\tcase AddressingMode::Quick:\n\t\t\tea.value.l = quick(instruction.operation, opcode);\n\t\t\tea.requires_fetch = false;\n\t\tbreak;\n\t\tcase AddressingMode::ImmediateData:\n\t\t\tread(instruction.size(), program_counter_.l, ea.value.l);\n\t\t\tprogram_counter_.l += (instruction.size() == DataSize::LongWord) ? 4 : 2;\n\t\t\tea.requires_fetch = false;\n\t\tbreak;\n\n\t\t\/\/\n\t\t\/\/ Absolute addresses.\n\t\t\/\/\n\t\tcase AddressingMode::AbsoluteShort:\n\t\t\tea.value.l = int16_t(read_pc());\n\t\t\tea.requires_fetch = true;\n\t\tbreak;\n\t\tcase AddressingMode::AbsoluteLong:\n\t\t\tea.value.l = read_pc();\n\t\t\tea.requires_fetch = true;\n\t\tbreak;\n\n\t\t\/\/\n\t\t\/\/ Address register indirects.\n\t\t\/\/\n\t\tcase AddressingMode::AddressRegisterIndirect:\n\t\t\tea.value.l = address_[instruction.reg(index)];\n\t\t\tea.requires_fetch = true;\n\t\tbreak;\n\t\tcase AddressingMode::AddressRegisterIndirectWithPostincrement: {\n\t\t\tconst auto reg = instruction.reg(index);\n\n\t\t\tea.value.l = address_[reg];\n\t\t\tea.requires_fetch = true;\n\n\t\t\tswitch(instruction.size()) {\n\t\t\t\tcase DataSize::Byte:\t\taddress_[reg].l += byte_increments[reg];\tbreak;\n\t\t\t\tcase DataSize::Word:\t\taddress_[reg].l += 2;\t\t\t\t\t\tbreak;\n\t\t\t\tcase DataSize::LongWord:\taddress_[reg].l += 4;\t\t\t\t\t\tbreak;\n\t\t\t}\n\t\t} break;\n\t\tcase AddressingMode::AddressRegisterIndirectWithPredecrement: {\n\t\t\tconst auto reg = instruction.reg(index);\n\n\t\t\tswitch(instruction.size()) {\n\t\t\t\tcase DataSize::Byte:\t\taddress_[reg].l -= byte_increments[reg];\tbreak;\n\t\t\t\tcase DataSize::Word:\t\taddress_[reg].l -= 2;\t\t\t\t\t\tbreak;\n\t\t\t\tcase DataSize::LongWord:\taddress_[reg].l -= 4;\t\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tea.value.l = address_[reg];\n\t\t\tea.requires_fetch = true;\n\t\t} break;\n\t\tcase AddressingMode::AddressRegisterIndirectWithDisplacement:\n\t\t\tea.value.l = address_[instruction.reg(index)].l + int16_t(read_pc());\n\t\t\tea.requires_fetch = true;\n\t\tbreak;\n\t\tcase AddressingMode::AddressRegisterIndirectWithIndex8bitDisplacement:\n\t\t\tea.value.l = address_[instruction.reg(index)].l + index_8bitdisplacement();\n\t\t\tea.requires_fetch = true;\n\t\tbreak;\n\n\t\t\/\/\n\t\t\/\/ PC-relative addresses.\n\t\t\/\/\n\t\t\/\/ TODO: rephrase these in terms of instruction_address_. Just for security\n\t\t\/\/ against whatever mutations the PC has been through already to get to here.\n\t\t\/\/\n\t\tcase AddressingMode::ProgramCounterIndirectWithDisplacement:\n\t\t\tea.value.l = program_counter_.l + int16_t(read_pc());\n\t\t\tea.requires_fetch = true;\n\t\tbreak;\n\t\tcase AddressingMode::ProgramCounterIndirectWithIndex8bitDisplacement:\n\t\t\tea.value.l = program_counter_.l + index_8bitdisplacement();\n\t\t\tea.requires_fetch = true;\n\t\tbreak;\n\n\t\tdefault:\n\t\t\t\/\/ TODO.\n\t\t\tassert(false);\n\t\tbreak;\n\t}\n\n\treturn ea;\n}\n\n\ntemplate \nvoid Executor::run_for_instructions(int count) {\n\twhile(count--) {\n\t\t\/\/ TODO: check interrupt level, trace flag.\n\n\t\t\/\/ Read the next instruction.\n\t\tinstruction_address_ = program_counter_.l;\n\t\tconst auto opcode = read_pc();\n\t\tconst Preinstruction instruction = decoder_.decode(opcode);\n\t\tprogram_counter_.l += 2;\n\n\t\t\/\/ TODO: check privilege level.\n\n\t\t\/\/ Temporary storage.\n\t\tCPU::SlicedInt32 operand_[2];\n\t\tEffectiveAddress effective_address_[2];\n\n\t\t\/\/ Calculate effective addresses; copy 'addresses' into the\n\t\t\/\/ operands by default both: (i) because they might be values,\n\t\t\/\/ rather than addresses; and (ii) then they'll be there for use\n\t\t\/\/ by LEA and PEA.\n\t\t\/\/\n\t\t\/\/ TODO: this work should be performed by a full Decoder, so that it can be cached.\n\t\teffective_address_[0] = calculate_effective_address(instruction, opcode, 0);\n\t\teffective_address_[1] = calculate_effective_address(instruction, opcode, 1);\n\t\toperand_[0] = effective_address_[0].value;\n\t\toperand_[1] = effective_address_[1].value;\n\n\t\t\/\/ Obtain the appropriate sequence.\n\t\t\/\/\n\t\t\/\/ TODO: make a decision about whether this goes into a fully-decoded Instruction.\n\t\tSequence sequence(instruction.operation);\n\n\t\t\/\/ Perform it.\n\t\twhile(!sequence.empty()) {\n\t\t\tconst auto step = sequence.pop_front();\n\n\t\t\tswitch(step) {\n\t\t\t\tdefault: assert(false);\t\/\/ i.e. TODO\n\n\t\t\t\tcase Step::FetchOp1:\n\t\t\t\tcase Step::FetchOp2: {\n\t\t\t\t\tconst auto index = int(step) & 1;\n\n\t\t\t\t\t\/\/ If the operand wasn't indirect, it's already fetched.\n\t\t\t\t\tif(!effective_address_[index].requires_fetch) continue;\n\n\t\t\t\t\t\/\/ TODO: potential bus alignment exception.\n\t\t\t\t\tread(instruction.size(), effective_address_[index].value, operand_[index]);\n\t\t\t\t} break;\n\n\t\t\t\tcase Step::Perform:\n\t\t\t\t\tperform(instruction, operand_[0], operand_[1], status_, this);\n\t\t\t\tbreak;\n\n\t\t\t\tcase Step::StoreOp1:\n\t\t\t\tcase Step::StoreOp2: {\n\t\t\t\t\tconst auto index = int(step) & 1;\n\n\t\t\t\t\t\/\/ If the operand wasn't indirect, store directly to Dn or An.\n\t\t\t\t\tif(!effective_address_[index].requires_fetch) {\n\t\t\t\t\t\t\/\/ This must be either address or data register indirect.\n\t\t\t\t\t\tassert(\n\t\t\t\t\t\t\tinstruction.mode(index) == AddressingMode::DataRegisterDirect ||\n\t\t\t\t\t\t\tinstruction.mode(index) == AddressingMode::AddressRegisterDirect);\n\n\t\t\t\t\t\t\/\/ TODO: is it worth holding registers as a single block to avoid this conditional?\n\t\t\t\t\t\tif(instruction.mode(index) == AddressingMode::DataRegisterDirect) {\n\t\t\t\t\t\t\tdata_[instruction.reg(index)] = operand_[index];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\taddress_[instruction.reg(index)] = operand_[index];\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ TODO: potential bus alignment exception.\n\t\t\t\t\twrite(instruction.size(), effective_address_[index].value, operand_[index]);\n\t\t\t\t} break;\n\t\t\t}\n\t\t}\n\t}\n}\n\n}\n}\n\n#endif \/* InstructionSets_M68k_ExecutorImplementation_hpp *\/\nEquivocate.\/\/\n\/\/ ExecutorImplementation.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 01\/05\/2022.\n\/\/ Copyright © 2022 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef InstructionSets_M68k_ExecutorImplementation_hpp\n#define InstructionSets_M68k_ExecutorImplementation_hpp\n\n#include \"..\/Perform.hpp\"\n#include \n\nnamespace InstructionSet {\nnamespace M68k {\n\ntemplate \nExecutor::Executor(BusHandler &handler) : bus_handler_(handler) {\n\treset();\n}\n\ntemplate \nvoid Executor::reset() {\n\t\/\/ Establish: supervisor state, all interrupts blocked.\n\tstatus_.set_status(0b0010'0011'1000'0000);\n\n\t\/\/ Seed stack pointer and program counter.\n\tdata_[7] = bus_handler_.template read(0);\n\tprogram_counter_.l = bus_handler_.template read(4);\n}\n\ntemplate \nvoid Executor::read(DataSize size, uint32_t address, CPU::SlicedInt32 &value) {\n\tswitch(size) {\n\t\tcase DataSize::Byte:\n\t\t\tvalue.b = bus_handler_.template read(address);\n\t\tbreak;\n\t\tcase DataSize::Word:\n\t\t\tvalue.w = bus_handler_.template read(address);\n\t\tbreak;\n\t\tcase DataSize::LongWord:\n\t\t\tvalue.l = bus_handler_.template read(address);\n\t\tbreak;\n\t}\n}\n\ntemplate \nvoid Executor::write(DataSize size, uint32_t address, CPU::SlicedInt32 value) {\n\tswitch(size) {\n\t\tcase DataSize::Byte:\n\t\t\t bus_handler_.template write(address, value.b);\n\t\tbreak;\n\t\tcase DataSize::Word:\n\t\t\tbus_handler_.template write(address, value.w);\n\t\tbreak;\n\t\tcase DataSize::LongWord:\n\t\t\tbus_handler_.template write(address, value.l);\n\t\tbreak;\n\t}\n}\n\ntemplate \ntemplate IntT Executor::read_pc() {\n\tconst IntT result = bus_handler_.template read(program_counter_.l);\n\n\tif constexpr (sizeof(IntT) == 4) {\n\t\tprogram_counter_.l += 4;\n\t} else {\n\t\tprogram_counter_.l += 2;\n\t}\n\n\treturn result;\n}\n\ntemplate \nuint32_t Executor::index_8bitdisplacement() {\n\t\/\/ TODO: if not a 68000, check bit 8 for whether this should be a full extension word;\n\t\/\/ also include the scale field even if not.\n\tconst auto extension = read_pc();\n\tconst auto offset = int8_t(extension);\n\tconst int register_index = (extension >> 11) & 7;\n\tconst uint32_t displacement = (extension & 0x8000) ? address_[register_index].l : data_[register_index].l;\n\treturn offset + (extension & 0x800) ? displacement : uint16_t(displacement);\n}\n\ntemplate \ntypename Executor::EffectiveAddress Executor::calculate_effective_address(Preinstruction instruction, uint16_t opcode, int index) {\n\tEffectiveAddress ea;\n\n\tswitch(instruction.mode(index)) {\n\t\tcase AddressingMode::None:\n\t\t\t\/\/ Permit an uninitialised effective address to be returned;\n\t\t\t\/\/ this value shouldn't be used.\n\t\tbreak;\n\n\t\t\/\/\n\t\t\/\/ Operands that don't have effective addresses, which are returned as values.\n\t\t\/\/\n\t\tcase AddressingMode::DataRegisterDirect:\n\t\t\tea.value = data_[instruction.reg(index)];\n\t\t\tea.requires_fetch = false;\n\t\tbreak;\n\t\tcase AddressingMode::AddressRegisterDirect:\n\t\t\tea.value = address_[instruction.reg(index)];\n\t\t\tea.requires_fetch = false;\n\t\tbreak;\n\t\tcase AddressingMode::Quick:\n\t\t\tea.value.l = quick(instruction.operation, opcode);\n\t\t\tea.requires_fetch = false;\n\t\tbreak;\n\t\tcase AddressingMode::ImmediateData:\n\t\t\tread(instruction.size(), program_counter_.l, ea.value.l);\n\t\t\tprogram_counter_.l += (instruction.size() == DataSize::LongWord) ? 4 : 2;\n\t\t\tea.requires_fetch = false;\n\t\tbreak;\n\n\t\t\/\/\n\t\t\/\/ Absolute addresses.\n\t\t\/\/\n\t\tcase AddressingMode::AbsoluteShort:\n\t\t\tea.value.l = int16_t(read_pc());\n\t\t\tea.requires_fetch = true;\n\t\tbreak;\n\t\tcase AddressingMode::AbsoluteLong:\n\t\t\tea.value.l = read_pc();\n\t\t\tea.requires_fetch = true;\n\t\tbreak;\n\n\t\t\/\/\n\t\t\/\/ Address register indirects.\n\t\t\/\/\n\t\tcase AddressingMode::AddressRegisterIndirect:\n\t\t\tea.value.l = address_[instruction.reg(index)];\n\t\t\tea.requires_fetch = true;\n\t\tbreak;\n\t\tcase AddressingMode::AddressRegisterIndirectWithPostincrement: {\n\t\t\tconst auto reg = instruction.reg(index);\n\n\t\t\tea.value.l = address_[reg];\n\t\t\tea.requires_fetch = true;\n\n\t\t\tswitch(instruction.size()) {\n\t\t\t\tcase DataSize::Byte:\t\taddress_[reg].l += byte_increments[reg];\tbreak;\n\t\t\t\tcase DataSize::Word:\t\taddress_[reg].l += 2;\t\t\t\t\t\tbreak;\n\t\t\t\tcase DataSize::LongWord:\taddress_[reg].l += 4;\t\t\t\t\t\tbreak;\n\t\t\t}\n\t\t} break;\n\t\tcase AddressingMode::AddressRegisterIndirectWithPredecrement: {\n\t\t\tconst auto reg = instruction.reg(index);\n\n\t\t\tswitch(instruction.size()) {\n\t\t\t\tcase DataSize::Byte:\t\taddress_[reg].l -= byte_increments[reg];\tbreak;\n\t\t\t\tcase DataSize::Word:\t\taddress_[reg].l -= 2;\t\t\t\t\t\tbreak;\n\t\t\t\tcase DataSize::LongWord:\taddress_[reg].l -= 4;\t\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tea.value.l = address_[reg];\n\t\t\tea.requires_fetch = true;\n\t\t} break;\n\t\tcase AddressingMode::AddressRegisterIndirectWithDisplacement:\n\t\t\tea.value.l = address_[instruction.reg(index)].l + int16_t(read_pc());\n\t\t\tea.requires_fetch = true;\n\t\tbreak;\n\t\tcase AddressingMode::AddressRegisterIndirectWithIndex8bitDisplacement:\n\t\t\tea.value.l = address_[instruction.reg(index)].l + index_8bitdisplacement();\n\t\t\tea.requires_fetch = true;\n\t\tbreak;\n\n\t\t\/\/\n\t\t\/\/ PC-relative addresses.\n\t\t\/\/\n\t\t\/\/ TODO: rephrase these in terms of instruction_address_. Just for security\n\t\t\/\/ against whatever mutations the PC has been through already to get to here.\n\t\t\/\/\n\t\tcase AddressingMode::ProgramCounterIndirectWithDisplacement:\n\t\t\tea.value.l = program_counter_.l + int16_t(read_pc());\n\t\t\tea.requires_fetch = true;\n\t\tbreak;\n\t\tcase AddressingMode::ProgramCounterIndirectWithIndex8bitDisplacement:\n\t\t\tea.value.l = program_counter_.l + index_8bitdisplacement();\n\t\t\tea.requires_fetch = true;\n\t\tbreak;\n\n\t\tdefault:\n\t\t\t\/\/ TODO.\n\t\t\tassert(false);\n\t\tbreak;\n\t}\n\n\treturn ea;\n}\n\n\ntemplate \nvoid Executor::run_for_instructions(int count) {\n\twhile(count--) {\n\t\t\/\/ TODO: check interrupt level, trace flag.\n\n\t\t\/\/ Read the next instruction.\n\t\tinstruction_address_ = program_counter_.l;\n\t\tconst auto opcode = read_pc();\n\t\tconst Preinstruction instruction = decoder_.decode(opcode);\n\t\tprogram_counter_.l += 2;\n\n\t\t\/\/ TODO: check privilege level.\n\n\t\t\/\/ Temporary storage.\n\t\tCPU::SlicedInt32 operand_[2];\n\t\tEffectiveAddress effective_address_[2];\n\n\t\t\/\/ Calculate effective addresses; copy 'addresses' into the\n\t\t\/\/ operands by default both: (i) because they might be values,\n\t\t\/\/ rather than addresses; and (ii) then they'll be there for use\n\t\t\/\/ by LEA and PEA.\n\t\t\/\/\n\t\t\/\/ TODO: much of this work should be performed by a full Decoder,\n\t\t\/\/ so that it can be cached.\n\t\teffective_address_[0] = calculate_effective_address(instruction, opcode, 0);\n\t\teffective_address_[1] = calculate_effective_address(instruction, opcode, 1);\n\t\toperand_[0] = effective_address_[0].value;\n\t\toperand_[1] = effective_address_[1].value;\n\n\t\t\/\/ Obtain the appropriate sequence.\n\t\t\/\/\n\t\t\/\/ TODO: make a decision about whether this goes into a fully-decoded Instruction.\n\t\tSequence sequence(instruction.operation);\n\n\t\t\/\/ Perform it.\n\t\twhile(!sequence.empty()) {\n\t\t\tconst auto step = sequence.pop_front();\n\n\t\t\tswitch(step) {\n\t\t\t\tdefault: assert(false);\t\/\/ i.e. TODO\n\n\t\t\t\tcase Step::FetchOp1:\n\t\t\t\tcase Step::FetchOp2: {\n\t\t\t\t\tconst auto index = int(step) & 1;\n\n\t\t\t\t\t\/\/ If the operand wasn't indirect, it's already fetched.\n\t\t\t\t\tif(!effective_address_[index].requires_fetch) continue;\n\n\t\t\t\t\t\/\/ TODO: potential bus alignment exception.\n\t\t\t\t\tread(instruction.size(), effective_address_[index].value, operand_[index]);\n\t\t\t\t} break;\n\n\t\t\t\tcase Step::Perform:\n\t\t\t\t\tperform(instruction, operand_[0], operand_[1], status_, this);\n\t\t\t\tbreak;\n\n\t\t\t\tcase Step::StoreOp1:\n\t\t\t\tcase Step::StoreOp2: {\n\t\t\t\t\tconst auto index = int(step) & 1;\n\n\t\t\t\t\t\/\/ If the operand wasn't indirect, store directly to Dn or An.\n\t\t\t\t\tif(!effective_address_[index].requires_fetch) {\n\t\t\t\t\t\t\/\/ This must be either address or data register indirect.\n\t\t\t\t\t\tassert(\n\t\t\t\t\t\t\tinstruction.mode(index) == AddressingMode::DataRegisterDirect ||\n\t\t\t\t\t\t\tinstruction.mode(index) == AddressingMode::AddressRegisterDirect);\n\n\t\t\t\t\t\t\/\/ TODO: is it worth holding registers as a single block to avoid this conditional?\n\t\t\t\t\t\tif(instruction.mode(index) == AddressingMode::DataRegisterDirect) {\n\t\t\t\t\t\t\tdata_[instruction.reg(index)] = operand_[index];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\taddress_[instruction.reg(index)] = operand_[index];\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ TODO: potential bus alignment exception.\n\t\t\t\t\twrite(instruction.size(), effective_address_[index].value, operand_[index]);\n\t\t\t\t} break;\n\t\t\t}\n\t\t}\n\t}\n}\n\n}\n}\n\n#endif \/* InstructionSets_M68k_ExecutorImplementation_hpp *\/\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n#include \n\n#include \"acsncReconnectionCallback.h\"\n\nusing namespace nc;\n\nReconnectionCallback::ReconnectionCallback(nc::Helper *sub):\n sub_(sub),\n id_is_valid_(false),\n root_poa_(0),\n services_(0)\n{\n if (::maci::ContainerImpl::getContainer() != NULL)\n services_ = ::maci::ContainerImpl::getContainer()->getContainerServices();\n}\n\nbool ReconnectionCallback::is_alive()\n{\n return true;\n}\n\nvoid ReconnectionCallback::reconnect(::CORBA::Object_ptr new_connection)\n{\n ecf_ = NotifyMonitoringExt::EventChannelFactory::_narrow(new_connection);\n if(!::CORBA::is_nil(ecf_))\n sub_->reconnect(ecf_);\n}\n\nvoid ReconnectionCallback::init( CORBA::ORB_ptr orb_mp,\n NotifyMonitoringExt::EventChannelFactory_ptr ecf)\n{\n if (::CORBA::is_nil(ecf)){\n\t std::cout << \"-- ECF is nil :( --\" << std::endl;\n return;\n }\n\n ecf_ = NotifyMonitoringExt::EventChannelFactory::_duplicate(ecf);\n NotifyExt::ReconnectionCallback_var callback;\n\n if (!::CORBA::is_nil(orb_mp)){\n ::CORBA::Object_ptr poa = orb_mp->resolve_initial_references(\"RootPOA\");\n root_poa_ = PortableServer::POA::_narrow (poa);\n callback_obj_id_ = root_poa_->activate_object(this);\n\n CORBA::Object_var obj =\n root_poa_->id_to_reference(callback_obj_id_.in());\n callback = NotifyExt::ReconnectionCallback::_narrow(obj);\n }\n else if (services_ != NULL){\n callback = NotifyExt::ReconnectionCallback::_narrow(\n services_->activateOffShoot(this));\n }\n else\n return;\n\n if (::CORBA::is_nil(callback))\n std::cout << \"Callback not initializated\" << std::endl;\n\n NotifyExt::ReconnectionRegistry_var registry =\n NotifyExt::ReconnectionRegistry::_narrow(ecf_);\n\n callback_id_ = registry->register_callback(callback);\n id_is_valid_ = true;\n\n}\n\nvoid ReconnectionCallback::disconnect()\n{\n if (id_is_valid_){\n NotifyExt::ReconnectionRegistry_var registry =\n NotifyExt::ReconnectionRegistry::_narrow(ecf_);\n registry->unregister_callback(callback_id_);\n if (!::CORBA::is_nil(root_poa_))\n root_poa_->deactivate_object(callback_obj_id_);\n else\n services_->deactivateOffShoot(this);\n id_is_valid_ = false;\n }\n}\n\nReconnectionCallback::~ReconnectionCallback()\n{\n}\nICTJ:ICT-4935: Fix memory leak in C++ callback#include \n#include \n\n#include \n#include \n\n#include \"acsncReconnectionCallback.h\"\n\nusing namespace nc;\n\nReconnectionCallback::ReconnectionCallback(nc::Helper *sub):\n sub_(sub),\n id_is_valid_(false),\n root_poa_(0),\n services_(0)\n{\n if (::maci::ContainerImpl::getContainer() != NULL)\n services_ = ::maci::ContainerImpl::getContainer()->getContainerServices();\n}\n\nbool ReconnectionCallback::is_alive()\n{\n return true;\n}\n\nvoid ReconnectionCallback::reconnect(::CORBA::Object_ptr new_connection)\n{\n ecf_ = NotifyMonitoringExt::EventChannelFactory::_narrow(new_connection);\n if(!::CORBA::is_nil(ecf_))\n sub_->reconnect(ecf_);\n}\n\nvoid ReconnectionCallback::init( CORBA::ORB_ptr orb_mp,\n NotifyMonitoringExt::EventChannelFactory_ptr ecf)\n{\n if (::CORBA::is_nil(ecf)){\n\t std::cout << \"-- ECF is nil :( --\" << std::endl;\n return;\n }\n\n ecf_ = NotifyMonitoringExt::EventChannelFactory::_duplicate(ecf);\n NotifyExt::ReconnectionCallback_var callback;\n\n if (!::CORBA::is_nil(orb_mp)){\n ::CORBA::Object_ptr poa = orb_mp->resolve_initial_references(\"RootPOA\");\n root_poa_ = PortableServer::POA::_narrow (poa);\n callback_obj_id_ = root_poa_->activate_object(this);\n\n CORBA::Object_var obj =\n root_poa_->id_to_reference(callback_obj_id_.in());\n callback = NotifyExt::ReconnectionCallback::_narrow(obj);\n }\n else if (services_ != NULL){\n ACS::OffShoot_var shoot = services_->activateOffShoot(this);\n callback = NotifyExt::ReconnectionCallback::_narrow(shoot.in());\n }\n else\n return;\n\n if (::CORBA::is_nil(callback))\n std::cout << \"Callback not initializated\" << std::endl;\n\n NotifyExt::ReconnectionRegistry_var registry =\n NotifyExt::ReconnectionRegistry::_narrow(ecf_);\n\n callback_id_ = registry->register_callback(callback);\n id_is_valid_ = true;\n\n}\n\nvoid ReconnectionCallback::disconnect()\n{\n if (id_is_valid_){\n NotifyExt::ReconnectionRegistry_var registry =\n NotifyExt::ReconnectionRegistry::_narrow(ecf_);\n registry->unregister_callback(callback_id_);\n if (!::CORBA::is_nil(root_poa_))\n root_poa_->deactivate_object(callback_obj_id_);\n else\n services_->deactivateOffShoot(this);\n id_is_valid_ = false;\n }\n}\n\nReconnectionCallback::~ReconnectionCallback()\n{\n}\n<|endoftext|>"} {"text":"\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"QmitkTrackingDeviceConfigurationWidget.h\"\n\n#include \"mitkNDIPolarisTypeInformation.h\"\n\n#include \n\nconst std::string QmitkTrackingDeviceConfigurationWidget::VIEW_ID = \"org.mitk.views.trackingdeviceconfigurationwidget\";\n\nQmitkTrackingDeviceConfigurationWidget::QmitkTrackingDeviceConfigurationWidget(QWidget* parent, Qt::WindowFlags f)\n : QWidget(parent, f)\n , m_Controls(nullptr)\n , m_TrackingDevice(nullptr)\n , m_DeviceToWidgetIndexMap()\n{\n \/\/initializations\n CreateQtPartControl(this);\n CreateConnections();\n\n RefreshTrackingDeviceCollection();\n\n \/\/initialize a few UI elements\n AddOutput(\"
First Element selected\"); \/\/Order from Collection List\n\n \/\/reset a few things\n ResetOutput();\n\n \/\/restore old UI settings\n LoadUISettings();\n}\n\nQmitkTrackingDeviceConfigurationWidget::~QmitkTrackingDeviceConfigurationWidget()\n{\n StoreUISettings();\n delete m_Controls;\n m_TrackingDevice = nullptr;\n}\n\nvoid QmitkTrackingDeviceConfigurationWidget::CreateQtPartControl(QWidget *parent)\n{\n if (!m_Controls)\n {\n \/\/ create GUI widgets\n m_Controls = new Ui::QmitkTrackingDeviceConfigurationWidgetControls;\n m_Controls->setupUi(parent);\n }\n}\n\nvoid QmitkTrackingDeviceConfigurationWidget::CreateConnections()\n{\n if (m_Controls)\n {\n connect((QObject*)(m_Controls->m_TrackingDeviceChooser), SIGNAL(currentIndexChanged(int)), this, SLOT(TrackingDeviceChanged()));\n }\n}\n\nvoid QmitkTrackingDeviceConfigurationWidget::TrackingDeviceChanged()\n{\n const std::string currentDevice = this->GetCurrentDeviceName();\n\n \/\/show the correspondig widget\n m_Controls->m_TrackingSystemWidget->setCurrentIndex(m_DeviceToWidgetIndexMap[currentDevice]);\n\n \/\/reset output\n ResetOutput();\n\n AddOutput(\"
\");\n AddOutput(currentDevice);\n AddOutput(\" selected\");\n\n QmitkAbstractTrackingDeviceWidget* widget = GetWidget(currentDevice);\n\n if (widget == nullptr || !widget->IsDeviceInstalled())\n {\n AddOutput(\"
ERROR: not installed!\");\n }\n\n emit TrackingDeviceSelectionChanged();\n}\n\nvoid QmitkTrackingDeviceConfigurationWidget::RefreshTrackingDeviceCollection()\n{\n \/\/ clean-up of stacked widget, drop-down box and map\n for (auto& item : m_DeviceToWidgetIndexMap)\n {\n m_Controls->m_TrackingSystemWidget->removeWidget(m_Controls->m_TrackingSystemWidget->widget(item.second));\n MITK_INFO << \"removing widget for device '\" << item.first << \"'\";\n }\n\n m_Controls->m_TrackingDeviceChooser->clear();\n\n m_DeviceToWidgetIndexMap.clear();\n\n \/\/ get tracking device type service references\n us::ModuleContext* context = us::GetModuleContext();\n std::vector > deviceRefs =\n context->GetServiceReferences();\n\n if (deviceRefs.empty())\n {\n MITK_ERROR << \"No tracking device type service found!\";\n return;\n }\n\n \/\/ get tracking device configuration widget service references\n std::vector > widgetRefs =\n context->GetServiceReferences();\n\n if (widgetRefs.empty())\n {\n MITK_ERROR << \"No tracking device configuration widget service found!\";\n return;\n }\n\n const us::ServiceReference& deviceServiceReference = deviceRefs.front();\n const us::ServiceReference& widgetServiceReference = widgetRefs.front();\n\n mitk::TrackingDeviceTypeCollection* deviceTypeCollection =\n context->GetService(deviceServiceReference);\n\n mitk::TrackingDeviceWidgetCollection* deviceWidgetCollection =\n context->GetService(widgetServiceReference);\n\n for (auto name : deviceTypeCollection->GetTrackingDeviceTypeNames())\n {\n \/\/ if the device is not included yet, add name to comboBox and widget to stackedWidget\n if (m_Controls->m_TrackingDeviceChooser->findText(QString::fromStdString(name)) == -1)\n {\n m_Controls->m_TrackingDeviceChooser->addItem(QString::fromStdString(name));\n QWidget* current = deviceWidgetCollection->GetTrackingDeviceWidgetClone(name);\n if (current == nullptr)\n {\n MITK_WARN << \"No widget for tracking device type \" << name << \" available. Please implement and register it!\";\n current = new QWidget();\n }\n\n m_DeviceToWidgetIndexMap[name] = m_Controls->m_TrackingSystemWidget->addWidget(current);\n }\n }\n\n if (!m_DeviceToWidgetIndexMap.empty())\n {\n m_Controls->m_TrackingDeviceChooser->setCurrentIndex(0);\n m_Controls->m_TrackingSystemWidget->setCurrentIndex(0);\n }\n\n context->UngetService(deviceServiceReference);\n context->UngetService(widgetServiceReference);\n}\n\n\/\/######################### internal help methods #######################################\nvoid QmitkTrackingDeviceConfigurationWidget::ResetOutput()\n{\n QmitkAbstractTrackingDeviceWidget* currentWidget = this->GetWidget(this->GetCurrentDeviceName());\n\n if (currentWidget == nullptr)\n {\n return;\n }\n\n currentWidget->ResetOutput();\n currentWidget->repaint();\n}\n\nvoid QmitkTrackingDeviceConfigurationWidget::AddOutput(std::string s)\n{\n QmitkAbstractTrackingDeviceWidget* currentWidget = this->GetWidget(this->GetCurrentDeviceName());\n\n if (currentWidget == nullptr)\n {\n return;\n }\n\n currentWidget->AddOutput(s);\n currentWidget->repaint();\n}\n\nmitk::TrackingDevice::Pointer QmitkTrackingDeviceConfigurationWidget::ConstructTrackingDevice()\n{\n QmitkAbstractTrackingDeviceWidget* currentWidget = this->GetWidget(this->GetCurrentDeviceName());\n\n if (currentWidget == nullptr)\n {\n return nullptr;\n }\n\n return currentWidget->ConstructTrackingDevice();\n}\n\nmitk::TrackingDevice::Pointer QmitkTrackingDeviceConfigurationWidget::GetTrackingDevice()\n{\n m_TrackingDevice = ConstructTrackingDevice();\n if (m_TrackingDevice.IsNull() || !m_TrackingDevice->IsDeviceInstalled()) return nullptr;\n else return this->m_TrackingDevice;\n}\n\nvoid QmitkTrackingDeviceConfigurationWidget::StoreUISettings()\n{\n std::string id = \"org.mitk.modules.igt.ui.trackingdeviceconfigurationwidget\";\n\n std::string selectedDevice = this->GetCurrentDeviceName();\n\n \/\/Save settings for every widget\n \/\/Don't use m_DeviceTypeCollection here, it's already unregistered, when deconstructor is called...\n for (int index = 0; index < m_Controls->m_TrackingSystemWidget->count(); index++)\n {\n QmitkAbstractTrackingDeviceWidget* widget = dynamic_cast(m_Controls->m_TrackingSystemWidget->widget(index));\n\n if (widget != nullptr)\n {\n widget->StoreUISettings();\n }\n }\n\n if (this->GetPersistenceService()) \/\/ now save the settings using the persistence service\n {\n mitk::PropertyList::Pointer propList = this->GetPersistenceService()->GetPropertyList(id);\n propList->Set(\"SelectedDevice\", selectedDevice);\n }\n else \/\/ QSettings as a fallback if the persistence service is not available\n {\n QSettings settings;\n settings.beginGroup(QString::fromStdString(id));\n settings.setValue(\"trackingDeviceChooser\", QVariant(QString::fromStdString(selectedDevice)));\n settings.endGroup();\n }\n}\n\n\/**\n * @brief QmitkTrackingDeviceConfigurationWidget::LoadUISettings\n *\n * Precondition:\n * Make sure that QStackedWidget is already initialized,\n * e.g. by calling RefreshTrackingDeviceCollection() before.\n *\/\nvoid QmitkTrackingDeviceConfigurationWidget::LoadUISettings()\n{\n \/\/Load settings for every widget\n for (int index = 0; index < m_Controls->m_TrackingSystemWidget->count(); index++)\n {\n QmitkAbstractTrackingDeviceWidget* widget = dynamic_cast(m_Controls->m_TrackingSystemWidget->widget(index));\n\n if (widget != nullptr)\n {\n widget->LoadUISettings();\n }\n }\n\n std::string id = \"org.mitk.modules.igt.ui.trackingdeviceconfigurationwidget\";\n std::string selectedDevice;\n if (this->GetPersistenceService())\n {\n mitk::PropertyList::Pointer propList = this->GetPersistenceService()->GetPropertyList(id);\n if (propList.IsNull())\n {\n MITK_ERROR << \"Property list for this UI (\" << id << \") is not available, could not load UI settings!\"; return;\n }\n\n propList->Get(\"SelectedDevice\", selectedDevice);\n\n if (selectedDevice.empty())\n {\n MITK_ERROR << \"Loaded data from persistence service is invalid (SelectedDevice:\" << selectedDevice << \"): aborted to restore data!\";\n return;\n }\n\n MITK_INFO << \"Successfully restored UI settings\";\n }\n else\n {\n \/\/ QSettings as a fallback if the persistence service is not available\n QSettings settings;\n settings.beginGroup(QString::fromStdString(id));\n\n selectedDevice = settings.value(\"trackingDeviceChooser\", \"\").toString().toStdString();\n\n settings.endGroup();\n }\n\n \/\/ The selected device requires some checks because a device that is not installed should not be restored to avoid bugs.\n \/\/ Use NDI Polaris as default if there's no widget registered for selected device or there's a widget for it but no device installed.\n\n const auto& deviceIterator = m_DeviceToWidgetIndexMap.find(selectedDevice);\n\n if (deviceIterator != m_DeviceToWidgetIndexMap.end())\n {\n QmitkAbstractTrackingDeviceWidget* widget =\n dynamic_cast(m_Controls->m_TrackingSystemWidget->widget(deviceIterator->second));\n\n if (widget == nullptr || (widget != nullptr && !widget->IsDeviceInstalled()))\n {\n selectedDevice = mitk::NDIPolarisTypeInformation::GetTrackingDeviceName();\n }\n }\n else\n {\n selectedDevice = mitk::NDIPolarisTypeInformation::GetTrackingDeviceName();\n }\n\n const int index = m_Controls->m_TrackingDeviceChooser->findText(QString::fromStdString(selectedDevice));\n\n if (index >= 0)\n {\n m_Controls->m_TrackingDeviceChooser->setCurrentIndex(index);\n }\n else\n {\n MITK_ERROR << \"Failed to load UI setting for tracking device configuration\";\n return;\n }\n\n m_Controls->m_TrackingSystemWidget->setCurrentIndex(m_DeviceToWidgetIndexMap[selectedDevice]);\n}\n\nstd::string QmitkTrackingDeviceConfigurationWidget::GetCurrentDeviceName(void) const\n{\n return m_Controls->m_TrackingDeviceChooser->currentText().toStdString();\n}\n\nQmitkAbstractTrackingDeviceWidget* QmitkTrackingDeviceConfigurationWidget::GetWidget(const std::string& deviceName) const\n{\n const auto& deviceIterator = m_DeviceToWidgetIndexMap.find(deviceName);\n\n if (deviceIterator != m_DeviceToWidgetIndexMap.end())\n {\n QWidget* widget = m_Controls->m_TrackingSystemWidget->widget(deviceIterator->second);\n\n return dynamic_cast(widget);\n }\n\n return nullptr;\n}\nOnly construct TrackingDevices if necessary!\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"QmitkTrackingDeviceConfigurationWidget.h\"\n\n#include \"mitkNDIPolarisTypeInformation.h\"\n\n#include \n\nconst std::string QmitkTrackingDeviceConfigurationWidget::VIEW_ID = \"org.mitk.views.trackingdeviceconfigurationwidget\";\n\nQmitkTrackingDeviceConfigurationWidget::QmitkTrackingDeviceConfigurationWidget(QWidget* parent, Qt::WindowFlags f)\n : QWidget(parent, f)\n , m_Controls(nullptr)\n , m_TrackingDevice(nullptr)\n , m_DeviceToWidgetIndexMap()\n{\n \/\/initializations\n CreateQtPartControl(this);\n CreateConnections();\n\n RefreshTrackingDeviceCollection();\n\n \/\/initialize a few UI elements\n AddOutput(\"
First Element selected\"); \/\/Order from Collection List\n\n \/\/reset a few things\n ResetOutput();\n\n \/\/restore old UI settings\n LoadUISettings();\n}\n\nQmitkTrackingDeviceConfigurationWidget::~QmitkTrackingDeviceConfigurationWidget()\n{\n StoreUISettings();\n delete m_Controls;\n m_TrackingDevice = nullptr;\n}\n\nvoid QmitkTrackingDeviceConfigurationWidget::CreateQtPartControl(QWidget *parent)\n{\n if (!m_Controls)\n {\n \/\/ create GUI widgets\n m_Controls = new Ui::QmitkTrackingDeviceConfigurationWidgetControls;\n m_Controls->setupUi(parent);\n }\n}\n\nvoid QmitkTrackingDeviceConfigurationWidget::CreateConnections()\n{\n if (m_Controls)\n {\n connect((QObject*)(m_Controls->m_TrackingDeviceChooser), SIGNAL(currentIndexChanged(int)), this, SLOT(TrackingDeviceChanged()));\n }\n}\n\nvoid QmitkTrackingDeviceConfigurationWidget::TrackingDeviceChanged()\n{\n const std::string currentDevice = this->GetCurrentDeviceName();\n\n \/\/show the correspondig widget\n m_Controls->m_TrackingSystemWidget->setCurrentIndex(m_DeviceToWidgetIndexMap[currentDevice]);\n\n \/\/reset output\n ResetOutput();\n\n AddOutput(\"
\");\n AddOutput(currentDevice);\n AddOutput(\" selected\");\n\n QmitkAbstractTrackingDeviceWidget* widget = GetWidget(currentDevice);\n\n if (widget == nullptr || !widget->IsDeviceInstalled())\n {\n AddOutput(\"
ERROR: not installed!\");\n }\n\n emit TrackingDeviceSelectionChanged();\n}\n\nvoid QmitkTrackingDeviceConfigurationWidget::RefreshTrackingDeviceCollection()\n{\n \/\/ clean-up of stacked widget, drop-down box and map\n for (auto& item : m_DeviceToWidgetIndexMap)\n {\n m_Controls->m_TrackingSystemWidget->removeWidget(m_Controls->m_TrackingSystemWidget->widget(item.second));\n MITK_INFO << \"removing widget for device '\" << item.first << \"'\";\n }\n\n m_Controls->m_TrackingDeviceChooser->clear();\n\n m_DeviceToWidgetIndexMap.clear();\n\n \/\/ get tracking device type service references\n us::ModuleContext* context = us::GetModuleContext();\n std::vector > deviceRefs =\n context->GetServiceReferences();\n\n if (deviceRefs.empty())\n {\n MITK_ERROR << \"No tracking device type service found!\";\n return;\n }\n\n \/\/ get tracking device configuration widget service references\n std::vector > widgetRefs =\n context->GetServiceReferences();\n\n if (widgetRefs.empty())\n {\n MITK_ERROR << \"No tracking device configuration widget service found!\";\n return;\n }\n\n const us::ServiceReference& deviceServiceReference = deviceRefs.front();\n const us::ServiceReference& widgetServiceReference = widgetRefs.front();\n\n mitk::TrackingDeviceTypeCollection* deviceTypeCollection =\n context->GetService(deviceServiceReference);\n\n mitk::TrackingDeviceWidgetCollection* deviceWidgetCollection =\n context->GetService(widgetServiceReference);\n\n for (auto name : deviceTypeCollection->GetTrackingDeviceTypeNames())\n {\n \/\/ if the device is not included yet, add name to comboBox and widget to stackedWidget\n if (m_Controls->m_TrackingDeviceChooser->findText(QString::fromStdString(name)) == -1)\n {\n m_Controls->m_TrackingDeviceChooser->addItem(QString::fromStdString(name));\n QWidget* current = deviceWidgetCollection->GetTrackingDeviceWidgetClone(name);\n if (current == nullptr)\n {\n MITK_WARN << \"No widget for tracking device type \" << name << \" available. Please implement and register it!\";\n current = new QWidget();\n }\n\n m_DeviceToWidgetIndexMap[name] = m_Controls->m_TrackingSystemWidget->addWidget(current);\n }\n }\n\n if (!m_DeviceToWidgetIndexMap.empty())\n {\n m_Controls->m_TrackingDeviceChooser->setCurrentIndex(0);\n m_Controls->m_TrackingSystemWidget->setCurrentIndex(0);\n }\n\n context->UngetService(deviceServiceReference);\n context->UngetService(widgetServiceReference);\n}\n\n\/\/######################### internal help methods #######################################\nvoid QmitkTrackingDeviceConfigurationWidget::ResetOutput()\n{\n QmitkAbstractTrackingDeviceWidget* currentWidget = this->GetWidget(this->GetCurrentDeviceName());\n\n if (currentWidget == nullptr)\n {\n return;\n }\n\n currentWidget->ResetOutput();\n currentWidget->repaint();\n}\n\nvoid QmitkTrackingDeviceConfigurationWidget::AddOutput(std::string s)\n{\n QmitkAbstractTrackingDeviceWidget* currentWidget = this->GetWidget(this->GetCurrentDeviceName());\n\n if (currentWidget == nullptr)\n {\n return;\n }\n\n currentWidget->AddOutput(s);\n currentWidget->repaint();\n}\n\nmitk::TrackingDevice::Pointer QmitkTrackingDeviceConfigurationWidget::ConstructTrackingDevice()\n{\n QmitkAbstractTrackingDeviceWidget* currentWidget = this->GetWidget(this->GetCurrentDeviceName());\n\n if (currentWidget == nullptr)\n {\n return nullptr;\n }\n\n return currentWidget->ConstructTrackingDevice();\n}\n\nmitk::TrackingDevice::Pointer QmitkTrackingDeviceConfigurationWidget::GetTrackingDevice()\n{\n \/\/Only create a new device, if we don't have one yet or if the device selection in the widget has changed.\n \/\/otherwise, hundered of devices will be created each time someone calls Get...\n if (m_TrackingDevice.IsNull() || m_TrackingDevice->GetTrackingDeviceName() != this->GetCurrentDeviceName())\n m_TrackingDevice = ConstructTrackingDevice();\n\n if (m_TrackingDevice.IsNull() || !m_TrackingDevice->IsDeviceInstalled()) return nullptr;\n else return this->m_TrackingDevice;\n}\n\nvoid QmitkTrackingDeviceConfigurationWidget::StoreUISettings()\n{\n std::string id = \"org.mitk.modules.igt.ui.trackingdeviceconfigurationwidget\";\n\n std::string selectedDevice = this->GetCurrentDeviceName();\n\n \/\/Save settings for every widget\n \/\/Don't use m_DeviceTypeCollection here, it's already unregistered, when deconstructor is called...\n for (int index = 0; index < m_Controls->m_TrackingSystemWidget->count(); index++)\n {\n QmitkAbstractTrackingDeviceWidget* widget = dynamic_cast(m_Controls->m_TrackingSystemWidget->widget(index));\n\n if (widget != nullptr)\n {\n widget->StoreUISettings();\n }\n }\n\n if (this->GetPersistenceService()) \/\/ now save the settings using the persistence service\n {\n mitk::PropertyList::Pointer propList = this->GetPersistenceService()->GetPropertyList(id);\n propList->Set(\"SelectedDevice\", selectedDevice);\n }\n else \/\/ QSettings as a fallback if the persistence service is not available\n {\n QSettings settings;\n settings.beginGroup(QString::fromStdString(id));\n settings.setValue(\"trackingDeviceChooser\", QVariant(QString::fromStdString(selectedDevice)));\n settings.endGroup();\n }\n}\n\n\/**\n * @brief QmitkTrackingDeviceConfigurationWidget::LoadUISettings\n *\n * Precondition:\n * Make sure that QStackedWidget is already initialized,\n * e.g. by calling RefreshTrackingDeviceCollection() before.\n *\/\nvoid QmitkTrackingDeviceConfigurationWidget::LoadUISettings()\n{\n \/\/Load settings for every widget\n for (int index = 0; index < m_Controls->m_TrackingSystemWidget->count(); index++)\n {\n QmitkAbstractTrackingDeviceWidget* widget = dynamic_cast(m_Controls->m_TrackingSystemWidget->widget(index));\n\n if (widget != nullptr)\n {\n widget->LoadUISettings();\n }\n }\n\n std::string id = \"org.mitk.modules.igt.ui.trackingdeviceconfigurationwidget\";\n std::string selectedDevice;\n if (this->GetPersistenceService())\n {\n mitk::PropertyList::Pointer propList = this->GetPersistenceService()->GetPropertyList(id);\n if (propList.IsNull())\n {\n MITK_ERROR << \"Property list for this UI (\" << id << \") is not available, could not load UI settings!\"; return;\n }\n\n propList->Get(\"SelectedDevice\", selectedDevice);\n\n if (selectedDevice.empty())\n {\n MITK_ERROR << \"Loaded data from persistence service is invalid (SelectedDevice:\" << selectedDevice << \"): aborted to restore data!\";\n return;\n }\n\n MITK_INFO << \"Successfully restored UI settings\";\n }\n else\n {\n \/\/ QSettings as a fallback if the persistence service is not available\n QSettings settings;\n settings.beginGroup(QString::fromStdString(id));\n\n selectedDevice = settings.value(\"trackingDeviceChooser\", \"\").toString().toStdString();\n\n settings.endGroup();\n }\n\n \/\/ The selected device requires some checks because a device that is not installed should not be restored to avoid bugs.\n \/\/ Use NDI Polaris as default if there's no widget registered for selected device or there's a widget for it but no device installed.\n\n const auto& deviceIterator = m_DeviceToWidgetIndexMap.find(selectedDevice);\n\n if (deviceIterator != m_DeviceToWidgetIndexMap.end())\n {\n QmitkAbstractTrackingDeviceWidget* widget =\n dynamic_cast(m_Controls->m_TrackingSystemWidget->widget(deviceIterator->second));\n\n if (widget == nullptr || (widget != nullptr && !widget->IsDeviceInstalled()))\n {\n selectedDevice = mitk::NDIPolarisTypeInformation::GetTrackingDeviceName();\n }\n }\n else\n {\n selectedDevice = mitk::NDIPolarisTypeInformation::GetTrackingDeviceName();\n }\n\n const int index = m_Controls->m_TrackingDeviceChooser->findText(QString::fromStdString(selectedDevice));\n\n if (index >= 0)\n {\n m_Controls->m_TrackingDeviceChooser->setCurrentIndex(index);\n }\n else\n {\n MITK_ERROR << \"Failed to load UI setting for tracking device configuration\";\n return;\n }\n\n m_Controls->m_TrackingSystemWidget->setCurrentIndex(m_DeviceToWidgetIndexMap[selectedDevice]);\n}\n\nstd::string QmitkTrackingDeviceConfigurationWidget::GetCurrentDeviceName(void) const\n{\n return m_Controls->m_TrackingDeviceChooser->currentText().toStdString();\n}\n\nQmitkAbstractTrackingDeviceWidget* QmitkTrackingDeviceConfigurationWidget::GetWidget(const std::string& deviceName) const\n{\n const auto& deviceIterator = m_DeviceToWidgetIndexMap.find(deviceName);\n\n if (deviceIterator != m_DeviceToWidgetIndexMap.end())\n {\n QWidget* widget = m_Controls->m_TrackingSystemWidget->widget(deviceIterator->second);\n\n return dynamic_cast(widget);\n }\n\n return nullptr;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"CppUTest\/TestHarness.h\"\n#include \"CppUTest\/TestOutput.h\"\n#include \"CppUTest\/TestTestingFixture.h\"\n#include \"CppUTest\/PlatformSpecificFunctions.h\"\n\nTEST_GROUP(UtestShell)\n{\n TestTestingFixture fixture;\n};\n\nstatic void _failMethod()\n{\n FAIL(\"This test fails\");\n}\n\nstatic void _passingTestMethod()\n{\n CHECK(true);\n}\n\nstatic void _passingCheckEqualTestMethod()\n{\n CHECK_EQUAL(1, 1);\n}\n\nstatic void _exitTestMethod()\n{\n TEST_EXIT;\n FAIL(\"Should not get here\");\n}\n\nstatic volatile double zero = 0.0;\n\nTEST(UtestShell, compareDoubles)\n{\n double not_a_number = zero \/ zero;\n double infinity = 1 \/ zero;\n CHECK(doubles_equal(1.0, 1.001, 0.01));\n CHECK(!doubles_equal(not_a_number, 1.001, 0.01));\n CHECK(!doubles_equal(1.0, not_a_number, 0.01));\n CHECK(!doubles_equal(1.0, 1.001, not_a_number));\n CHECK(!doubles_equal(1.0, 1.1, 0.05));\n CHECK(!doubles_equal(infinity, 1.0, 0.01));\n CHECK(!doubles_equal(1.0, infinity, 0.01));\n CHECK(doubles_equal(1.0, -1.0, infinity));\n CHECK(doubles_equal(infinity, infinity, 0.01));\n CHECK(doubles_equal(infinity, infinity, infinity));\n double a = 1.2345678;\n CHECK(doubles_equal(a, a, 0.000000001));\n}\n\nTEST(UtestShell, FailWillIncreaseTheAmountOfChecks)\n{\n fixture.setTestFunction(_failMethod);\n fixture.runAllTests();\n LONGS_EQUAL(1, fixture.getCheckCount());\n}\n\nTEST(UtestShell, PassedCheckEqualWillIncreaseTheAmountOfChecks)\n{\n fixture.setTestFunction(_passingCheckEqualTestMethod);\n fixture.runAllTests();\n LONGS_EQUAL(1, fixture.getCheckCount());\n}\n\nIGNORE_TEST(UtestShell, IgnoreTestAccessingFixture)\n{\n CHECK(&fixture != NULLPTR);\n}\n\nTEST(UtestShell, MacrosUsedInSetup)\n{\n IGNORE_ALL_LEAKS_IN_TEST();\n fixture.setSetup(_failMethod);\n fixture.setTestFunction(_passingTestMethod);\n fixture.runAllTests();\n LONGS_EQUAL(1, fixture.getFailureCount());\n}\n\nTEST(UtestShell, MacrosUsedInTearDown)\n{\n IGNORE_ALL_LEAKS_IN_TEST();\n fixture.setTeardown(_failMethod);\n fixture.setTestFunction(_passingTestMethod);\n fixture.runAllTests();\n LONGS_EQUAL(1, fixture.getFailureCount());\n}\n\nTEST(UtestShell, ExitLeavesQuietly)\n{\n fixture.setTestFunction(_exitTestMethod);\n fixture.runAllTests();\n LONGS_EQUAL(0, fixture.getFailureCount());\n}\n\n\n\nstatic int teardownCalled = 0;\n\nstatic void _teardownMethod()\n{\n teardownCalled++;\n}\n\nTEST(UtestShell, TeardownCalledAfterTestFailure)\n{\n teardownCalled = 0;\n IGNORE_ALL_LEAKS_IN_TEST();\n fixture.setTeardown(_teardownMethod);\n fixture.setTestFunction(_failMethod);\n fixture.runAllTests();\n LONGS_EQUAL(1, fixture.getFailureCount());\n LONGS_EQUAL(1, teardownCalled);\n}\n\nstatic int stopAfterFailure = 0;\nstatic void _stopAfterFailureMethod()\n{\n FAIL(\"fail\");\n stopAfterFailure++;\n}\n\nTEST(UtestShell, TestStopsAfterTestFailure)\n{\n IGNORE_ALL_LEAKS_IN_TEST();\n stopAfterFailure = 0;\n fixture.setTestFunction(_stopAfterFailureMethod);\n fixture.runAllTests();\n CHECK(fixture.hasTestFailed());\n LONGS_EQUAL(1, fixture.getFailureCount());\n LONGS_EQUAL(0, stopAfterFailure);\n}\n\nTEST(UtestShell, TestStopsAfterSetupFailure)\n{\n stopAfterFailure = 0;\n fixture.setSetup(_stopAfterFailureMethod);\n fixture.setTeardown(_stopAfterFailureMethod);\n fixture.setTestFunction(_failMethod);\n fixture.runAllTests();\n LONGS_EQUAL(2, fixture.getFailureCount());\n LONGS_EQUAL(0, stopAfterFailure);\n}\n\nclass defaultUtestShell: public UtestShell\n{\n};\n\nTEST(UtestShell, this_test_covers_the_UtestShell_createTest_and_Utest_testBody_methods)\n{\n defaultUtestShell shell;\n fixture.addTest(&shell);\n fixture.runAllTests();\n LONGS_EQUAL(2, fixture.result_->getTestCount());\n}\n\nstatic void StubPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, TestResult* result)\n{\n result->addFailure(TestFailure(shell, \"Failed in separate process\"));\n}\n\nTEST(UtestShell, RunInSeparateProcessTest)\n{\n UT_PTR_SET(PlatformSpecificRunTestInASeperateProcess, StubPlatformSpecificRunTestInASeperateProcess);\n fixture.registry_->setRunTestsInSeperateProcess();\n fixture.runAllTests();\n fixture.assertPrintContains(\"Failed in separate process\");\n}\n\n#ifndef CPPUTEST_HAVE_FORK\n\nIGNORE_TEST(UtestShell, TestDefaultCrashMethodInSeparateProcessTest) {}\n\n#else\n\nTEST(UtestShell, TestDefaultCrashMethodInSeparateProcessTest)\n{\n fixture.setTestFunction(UtestShell::crash);\n fixture.registry_->setRunTestsInSeperateProcess();\n fixture.runAllTests();\n fixture.assertPrintContains(\"Failed in separate process - killed by signal\");\n\n \/* Signal 11 usually happens, but with clang3.7 on Linux, it produced signal 4 *\/\n CHECK(fixture.getOutput().contains(\"signal 11\") || fixture.getOutput().contains(\"signal 4\"));\n}\n\n#endif\n\n#if CPPUTEST_USE_STD_CPP_LIB\n\nstatic bool destructorWasCalledOnFailedTest = false;\n\nstatic void _destructorCalledForLocalObjects()\n{\n SetBooleanOnDestructorCall pleaseCallTheDestructor(destructorWasCalledOnFailedTest);\n destructorWasCalledOnFailedTest = false;\n FAIL(\"fail\");\n}\n\nTEST(UtestShell, DestructorIsCalledForLocalObjectsWhenTheTestFails)\n{\n fixture.setTestFunction(_destructorCalledForLocalObjects);\n fixture.runAllTests();\n CHECK(destructorWasCalledOnFailedTest);\n}\n\n#endif\n\nTEST_GROUP(IgnoredUtestShell)\n{\n TestTestingFixture fixture;\n IgnoredUtestShell ignoredTest;\n ExecFunctionTestShell normalUtestShell;\n\n void setup() _override\n {\n fixture.addTest(&ignoredTest);\n fixture.addTest(&normalUtestShell);\n }\n};\n\nTEST(IgnoredUtestShell, doesIgnoreCount)\n{\n fixture.runAllTests();\n LONGS_EQUAL(1, fixture.getIgnoreCount());\n}\n\nTEST(IgnoredUtestShell, printsIGNORE_TESTwhenVerbose)\n{\n fixture.output_->verbose();\n fixture.runAllTests();\n fixture.assertPrintContains(\"IGNORE_TEST\");\n}\n\nTEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenIncreaseRunCount)\n{\n ignoredTest.setRunIgnored();\n fixture.runAllTests();\n LONGS_EQUAL(3, fixture.getRunCount());\n LONGS_EQUAL(0, fixture.getIgnoreCount());\n}\n\nTEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenIncreaseIgnoredCount)\n{\n fixture.runAllTests();\n LONGS_EQUAL(2, fixture.getRunCount());\n LONGS_EQUAL(1, fixture.getIgnoreCount());\n}\n\nTEST(IgnoredUtestShell, runIgnoredOptionSpecifiedWillNotInfluenceNormalTestCount)\n{\n normalUtestShell.setRunIgnored();\n fixture.runAllTests();\n LONGS_EQUAL(2, fixture.getRunCount());\n LONGS_EQUAL(1, fixture.getIgnoreCount());\n}\n\nTEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenReturnTESTInFormattedName)\n{\n ignoredTest.setGroupName(\"TestGroup\");\n ignoredTest.setTestName(\"TestName\");\n ignoredTest.setRunIgnored();\n fixture.runAllTests();\n STRCMP_EQUAL(\"TEST(TestGroup, TestName)\", ignoredTest.getFormattedName().asCharString());\n}\n\nTEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenReturnIGNORETESTInFormattedName)\n{\n ignoredTest.setGroupName(\"TestGroup\");\n ignoredTest.setTestName(\"TestName\");\n fixture.runAllTests();\n STRCMP_EQUAL(\"IGNORE_TEST(TestGroup, TestName)\", ignoredTest.getFormattedName().asCharString());\n}\n\nTEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenWillRunReturnFalse)\n{\n CHECK_FALSE(ignoredTest.willRun());\n}\n\nTEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenWillRunReturnTrue)\n{\n ignoredTest.setRunIgnored();\n CHECK_TRUE(ignoredTest.willRun());\n}\n\nTEST_BASE(MyOwnTest)\n{\n MyOwnTest() :\n inTest(false)\n {\n }\n bool inTest;\n\n void setup()\n {\n CHECK(!inTest);\n inTest = true;\n }\n void teardown()\n {\n CHECK(inTest);\n inTest = false;\n }\n};\n\nTEST_GROUP_BASE(UtestMyOwn, MyOwnTest)\n{\n};\n\nTEST(UtestMyOwn, test)\n{\n CHECK(inTest);\n}\n\nclass NullParameterTest: public UtestShell\n{\n};\n\nTEST(UtestMyOwn, NullParameters)\n{\n NullParameterTest nullTest; \/* Bug fix tests for creating a test without a name, fix in SimpleString *\/\n TestFilter emptyFilter;\n CHECK(nullTest.shouldRun(&emptyFilter, &emptyFilter));\n}\n\nclass AllocateAndDeallocateInConstructorAndDestructor\n{\n char* memory_;\n char* morememory_;\npublic:\n AllocateAndDeallocateInConstructorAndDestructor()\n {\n memory_ = new char[100];\n morememory_ = NULLPTR;\n }\n void allocateMoreMemory()\n {\n morememory_ = new char[123];\n }\n\n ~AllocateAndDeallocateInConstructorAndDestructor()\n {\n delete [] memory_;\n delete [] morememory_;\n }\n};\n\nTEST_GROUP(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks)\n{\n AllocateAndDeallocateInConstructorAndDestructor dummy;\n};\n\nTEST(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks, testInTestGroupName)\n{\n dummy.allocateMoreMemory();\n}\n\nstatic int getZero()\n{\n return 0;\n}\n\nstatic int getOne()\n{\n return 1;\n}\n\nTEST_GROUP(UtestShellPointerArrayTest)\n{\n UtestShell* test0;\n UtestShell* test1;\n UtestShell* test2;\n\n void setup()\n {\n test0 = new IgnoredUtestShell();\n test1 = new IgnoredUtestShell();\n test2 = new IgnoredUtestShell();\n\n test0->addTest(test1);\n test1->addTest(test2);\n }\n\n void teardown()\n {\n delete test0;\n delete test1;\n delete test2;\n }\n};\n\n\nTEST(UtestShellPointerArrayTest, empty)\n{\n UtestShellPointerArray tests(NULLPTR);\n tests.shuffle(0);\n CHECK(NULL == tests.getFirstTest());\n}\n\nTEST(UtestShellPointerArrayTest, testsAreInOrder)\n{\n UtestShellPointerArray tests(test0);\n CHECK(tests.get(0) == test0);\n CHECK(tests.get(1) == test1);\n CHECK(tests.get(2) == test2);\n}\n\nTEST(UtestShellPointerArrayTest, relinkingTestsWillKeepThemTheSameWhenNothingWasDone)\n{\n UtestShellPointerArray tests(test0);\n tests.relinkTestsInOrder();\n CHECK(tests.get(0) == test0);\n CHECK(tests.get(1) == test1);\n CHECK(tests.get(2) == test2);\n}\n\n\nTEST(UtestShellPointerArrayTest, firstTestisNotTheFirstTestWithSeed1234)\n{\n UtestShellPointerArray tests(test0);\n tests.shuffle(1234);\n CHECK(tests.getFirstTest() != test0);\n}\n\nTEST(UtestShellPointerArrayTest, ShuffleListTestWithRandomAlwaysReturningZero)\n{\n UT_PTR_SET(PlatformSpecificRand, getZero);\n\n UtestShellPointerArray tests(test0);\n tests.shuffle(3);\n CHECK(tests.get(0) == test1);\n CHECK(tests.get(1) == test2);\n CHECK(tests.get(2) == test0);\n}\n\n\/\/ swaps with 4 mod 3 (1) then 4 mod 2 (0): 1, [2], [0] --> [1], [0], 2 --> 0, 1, 2\nTEST(UtestShellPointerArrayTest, ShuffleListTestWithRandomAlwaysReturningOne)\n{\n UT_PTR_SET(PlatformSpecificRand, getOne);\n\n UtestShellPointerArray tests(test0);\n tests.shuffle(3);\n CHECK(tests.get(0) == test0);\n CHECK(tests.get(1) == test2);\n CHECK(tests.get(2) == test1);\n}\n\nTEST(UtestShellPointerArrayTest, reverse)\n{\n UT_PTR_SET(PlatformSpecificRand, getOne);\n\n UtestShellPointerArray tests(test0);\n tests.reverse();\n CHECK(tests.get(0) == test2);\n CHECK(tests.get(1) == test1);\n CHECK(tests.get(2) == test0);\n}\n\nNot use ifndef but use if\/*\n * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"CppUTest\/TestHarness.h\"\n#include \"CppUTest\/TestOutput.h\"\n#include \"CppUTest\/TestTestingFixture.h\"\n#include \"CppUTest\/PlatformSpecificFunctions.h\"\n\nTEST_GROUP(UtestShell)\n{\n TestTestingFixture fixture;\n};\n\nstatic void _failMethod()\n{\n FAIL(\"This test fails\");\n}\n\nstatic void _passingTestMethod()\n{\n CHECK(true);\n}\n\nstatic void _passingCheckEqualTestMethod()\n{\n CHECK_EQUAL(1, 1);\n}\n\nstatic void _exitTestMethod()\n{\n TEST_EXIT;\n FAIL(\"Should not get here\");\n}\n\nstatic volatile double zero = 0.0;\n\nTEST(UtestShell, compareDoubles)\n{\n double not_a_number = zero \/ zero;\n double infinity = 1 \/ zero;\n CHECK(doubles_equal(1.0, 1.001, 0.01));\n CHECK(!doubles_equal(not_a_number, 1.001, 0.01));\n CHECK(!doubles_equal(1.0, not_a_number, 0.01));\n CHECK(!doubles_equal(1.0, 1.001, not_a_number));\n CHECK(!doubles_equal(1.0, 1.1, 0.05));\n CHECK(!doubles_equal(infinity, 1.0, 0.01));\n CHECK(!doubles_equal(1.0, infinity, 0.01));\n CHECK(doubles_equal(1.0, -1.0, infinity));\n CHECK(doubles_equal(infinity, infinity, 0.01));\n CHECK(doubles_equal(infinity, infinity, infinity));\n double a = 1.2345678;\n CHECK(doubles_equal(a, a, 0.000000001));\n}\n\nTEST(UtestShell, FailWillIncreaseTheAmountOfChecks)\n{\n fixture.setTestFunction(_failMethod);\n fixture.runAllTests();\n LONGS_EQUAL(1, fixture.getCheckCount());\n}\n\nTEST(UtestShell, PassedCheckEqualWillIncreaseTheAmountOfChecks)\n{\n fixture.setTestFunction(_passingCheckEqualTestMethod);\n fixture.runAllTests();\n LONGS_EQUAL(1, fixture.getCheckCount());\n}\n\nIGNORE_TEST(UtestShell, IgnoreTestAccessingFixture)\n{\n CHECK(&fixture != NULLPTR);\n}\n\nTEST(UtestShell, MacrosUsedInSetup)\n{\n IGNORE_ALL_LEAKS_IN_TEST();\n fixture.setSetup(_failMethod);\n fixture.setTestFunction(_passingTestMethod);\n fixture.runAllTests();\n LONGS_EQUAL(1, fixture.getFailureCount());\n}\n\nTEST(UtestShell, MacrosUsedInTearDown)\n{\n IGNORE_ALL_LEAKS_IN_TEST();\n fixture.setTeardown(_failMethod);\n fixture.setTestFunction(_passingTestMethod);\n fixture.runAllTests();\n LONGS_EQUAL(1, fixture.getFailureCount());\n}\n\nTEST(UtestShell, ExitLeavesQuietly)\n{\n fixture.setTestFunction(_exitTestMethod);\n fixture.runAllTests();\n LONGS_EQUAL(0, fixture.getFailureCount());\n}\n\n\n\nstatic int teardownCalled = 0;\n\nstatic void _teardownMethod()\n{\n teardownCalled++;\n}\n\nTEST(UtestShell, TeardownCalledAfterTestFailure)\n{\n teardownCalled = 0;\n IGNORE_ALL_LEAKS_IN_TEST();\n fixture.setTeardown(_teardownMethod);\n fixture.setTestFunction(_failMethod);\n fixture.runAllTests();\n LONGS_EQUAL(1, fixture.getFailureCount());\n LONGS_EQUAL(1, teardownCalled);\n}\n\nstatic int stopAfterFailure = 0;\nstatic void _stopAfterFailureMethod()\n{\n FAIL(\"fail\");\n stopAfterFailure++;\n}\n\nTEST(UtestShell, TestStopsAfterTestFailure)\n{\n IGNORE_ALL_LEAKS_IN_TEST();\n stopAfterFailure = 0;\n fixture.setTestFunction(_stopAfterFailureMethod);\n fixture.runAllTests();\n CHECK(fixture.hasTestFailed());\n LONGS_EQUAL(1, fixture.getFailureCount());\n LONGS_EQUAL(0, stopAfterFailure);\n}\n\nTEST(UtestShell, TestStopsAfterSetupFailure)\n{\n stopAfterFailure = 0;\n fixture.setSetup(_stopAfterFailureMethod);\n fixture.setTeardown(_stopAfterFailureMethod);\n fixture.setTestFunction(_failMethod);\n fixture.runAllTests();\n LONGS_EQUAL(2, fixture.getFailureCount());\n LONGS_EQUAL(0, stopAfterFailure);\n}\n\nclass defaultUtestShell: public UtestShell\n{\n};\n\nTEST(UtestShell, this_test_covers_the_UtestShell_createTest_and_Utest_testBody_methods)\n{\n defaultUtestShell shell;\n fixture.addTest(&shell);\n fixture.runAllTests();\n LONGS_EQUAL(2, fixture.result_->getTestCount());\n}\n\nstatic void StubPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, TestResult* result)\n{\n result->addFailure(TestFailure(shell, \"Failed in separate process\"));\n}\n\nTEST(UtestShell, RunInSeparateProcessTest)\n{\n UT_PTR_SET(PlatformSpecificRunTestInASeperateProcess, StubPlatformSpecificRunTestInASeperateProcess);\n fixture.registry_->setRunTestsInSeperateProcess();\n fixture.runAllTests();\n fixture.assertPrintContains(\"Failed in separate process\");\n}\n\n#if !CPPUTEST_HAVE_FORK\n\nIGNORE_TEST(UtestShell, TestDefaultCrashMethodInSeparateProcessTest) {}\n\n#else\n\nTEST(UtestShell, TestDefaultCrashMethodInSeparateProcessTest)\n{\n fixture.setTestFunction(UtestShell::crash);\n fixture.registry_->setRunTestsInSeperateProcess();\n fixture.runAllTests();\n fixture.assertPrintContains(\"Failed in separate process - killed by signal\");\n\n \/* Signal 11 usually happens, but with clang3.7 on Linux, it produced signal 4 *\/\n CHECK(fixture.getOutput().contains(\"signal 11\") || fixture.getOutput().contains(\"signal 4\"));\n}\n\n#endif\n\n#if CPPUTEST_USE_STD_CPP_LIB\n\nstatic bool destructorWasCalledOnFailedTest = false;\n\nstatic void _destructorCalledForLocalObjects()\n{\n SetBooleanOnDestructorCall pleaseCallTheDestructor(destructorWasCalledOnFailedTest);\n destructorWasCalledOnFailedTest = false;\n FAIL(\"fail\");\n}\n\nTEST(UtestShell, DestructorIsCalledForLocalObjectsWhenTheTestFails)\n{\n fixture.setTestFunction(_destructorCalledForLocalObjects);\n fixture.runAllTests();\n CHECK(destructorWasCalledOnFailedTest);\n}\n\n#endif\n\nTEST_GROUP(IgnoredUtestShell)\n{\n TestTestingFixture fixture;\n IgnoredUtestShell ignoredTest;\n ExecFunctionTestShell normalUtestShell;\n\n void setup() _override\n {\n fixture.addTest(&ignoredTest);\n fixture.addTest(&normalUtestShell);\n }\n};\n\nTEST(IgnoredUtestShell, doesIgnoreCount)\n{\n fixture.runAllTests();\n LONGS_EQUAL(1, fixture.getIgnoreCount());\n}\n\nTEST(IgnoredUtestShell, printsIGNORE_TESTwhenVerbose)\n{\n fixture.output_->verbose();\n fixture.runAllTests();\n fixture.assertPrintContains(\"IGNORE_TEST\");\n}\n\nTEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenIncreaseRunCount)\n{\n ignoredTest.setRunIgnored();\n fixture.runAllTests();\n LONGS_EQUAL(3, fixture.getRunCount());\n LONGS_EQUAL(0, fixture.getIgnoreCount());\n}\n\nTEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenIncreaseIgnoredCount)\n{\n fixture.runAllTests();\n LONGS_EQUAL(2, fixture.getRunCount());\n LONGS_EQUAL(1, fixture.getIgnoreCount());\n}\n\nTEST(IgnoredUtestShell, runIgnoredOptionSpecifiedWillNotInfluenceNormalTestCount)\n{\n normalUtestShell.setRunIgnored();\n fixture.runAllTests();\n LONGS_EQUAL(2, fixture.getRunCount());\n LONGS_EQUAL(1, fixture.getIgnoreCount());\n}\n\nTEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenReturnTESTInFormattedName)\n{\n ignoredTest.setGroupName(\"TestGroup\");\n ignoredTest.setTestName(\"TestName\");\n ignoredTest.setRunIgnored();\n fixture.runAllTests();\n STRCMP_EQUAL(\"TEST(TestGroup, TestName)\", ignoredTest.getFormattedName().asCharString());\n}\n\nTEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenReturnIGNORETESTInFormattedName)\n{\n ignoredTest.setGroupName(\"TestGroup\");\n ignoredTest.setTestName(\"TestName\");\n fixture.runAllTests();\n STRCMP_EQUAL(\"IGNORE_TEST(TestGroup, TestName)\", ignoredTest.getFormattedName().asCharString());\n}\n\nTEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenWillRunReturnFalse)\n{\n CHECK_FALSE(ignoredTest.willRun());\n}\n\nTEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenWillRunReturnTrue)\n{\n ignoredTest.setRunIgnored();\n CHECK_TRUE(ignoredTest.willRun());\n}\n\nTEST_BASE(MyOwnTest)\n{\n MyOwnTest() :\n inTest(false)\n {\n }\n bool inTest;\n\n void setup()\n {\n CHECK(!inTest);\n inTest = true;\n }\n void teardown()\n {\n CHECK(inTest);\n inTest = false;\n }\n};\n\nTEST_GROUP_BASE(UtestMyOwn, MyOwnTest)\n{\n};\n\nTEST(UtestMyOwn, test)\n{\n CHECK(inTest);\n}\n\nclass NullParameterTest: public UtestShell\n{\n};\n\nTEST(UtestMyOwn, NullParameters)\n{\n NullParameterTest nullTest; \/* Bug fix tests for creating a test without a name, fix in SimpleString *\/\n TestFilter emptyFilter;\n CHECK(nullTest.shouldRun(&emptyFilter, &emptyFilter));\n}\n\nclass AllocateAndDeallocateInConstructorAndDestructor\n{\n char* memory_;\n char* morememory_;\npublic:\n AllocateAndDeallocateInConstructorAndDestructor()\n {\n memory_ = new char[100];\n morememory_ = NULLPTR;\n }\n void allocateMoreMemory()\n {\n morememory_ = new char[123];\n }\n\n ~AllocateAndDeallocateInConstructorAndDestructor()\n {\n delete [] memory_;\n delete [] morememory_;\n }\n};\n\nTEST_GROUP(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks)\n{\n AllocateAndDeallocateInConstructorAndDestructor dummy;\n};\n\nTEST(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks, testInTestGroupName)\n{\n dummy.allocateMoreMemory();\n}\n\nstatic int getZero()\n{\n return 0;\n}\n\nstatic int getOne()\n{\n return 1;\n}\n\nTEST_GROUP(UtestShellPointerArrayTest)\n{\n UtestShell* test0;\n UtestShell* test1;\n UtestShell* test2;\n\n void setup()\n {\n test0 = new IgnoredUtestShell();\n test1 = new IgnoredUtestShell();\n test2 = new IgnoredUtestShell();\n\n test0->addTest(test1);\n test1->addTest(test2);\n }\n\n void teardown()\n {\n delete test0;\n delete test1;\n delete test2;\n }\n};\n\n\nTEST(UtestShellPointerArrayTest, empty)\n{\n UtestShellPointerArray tests(NULLPTR);\n tests.shuffle(0);\n CHECK(NULL == tests.getFirstTest());\n}\n\nTEST(UtestShellPointerArrayTest, testsAreInOrder)\n{\n UtestShellPointerArray tests(test0);\n CHECK(tests.get(0) == test0);\n CHECK(tests.get(1) == test1);\n CHECK(tests.get(2) == test2);\n}\n\nTEST(UtestShellPointerArrayTest, relinkingTestsWillKeepThemTheSameWhenNothingWasDone)\n{\n UtestShellPointerArray tests(test0);\n tests.relinkTestsInOrder();\n CHECK(tests.get(0) == test0);\n CHECK(tests.get(1) == test1);\n CHECK(tests.get(2) == test2);\n}\n\n\nTEST(UtestShellPointerArrayTest, firstTestisNotTheFirstTestWithSeed1234)\n{\n UtestShellPointerArray tests(test0);\n tests.shuffle(1234);\n CHECK(tests.getFirstTest() != test0);\n}\n\nTEST(UtestShellPointerArrayTest, ShuffleListTestWithRandomAlwaysReturningZero)\n{\n UT_PTR_SET(PlatformSpecificRand, getZero);\n\n UtestShellPointerArray tests(test0);\n tests.shuffle(3);\n CHECK(tests.get(0) == test1);\n CHECK(tests.get(1) == test2);\n CHECK(tests.get(2) == test0);\n}\n\n\/\/ swaps with 4 mod 3 (1) then 4 mod 2 (0): 1, [2], [0] --> [1], [0], 2 --> 0, 1, 2\nTEST(UtestShellPointerArrayTest, ShuffleListTestWithRandomAlwaysReturningOne)\n{\n UT_PTR_SET(PlatformSpecificRand, getOne);\n\n UtestShellPointerArray tests(test0);\n tests.shuffle(3);\n CHECK(tests.get(0) == test0);\n CHECK(tests.get(1) == test2);\n CHECK(tests.get(2) == test1);\n}\n\nTEST(UtestShellPointerArrayTest, reverse)\n{\n UT_PTR_SET(PlatformSpecificRand, getOne);\n\n UtestShellPointerArray tests(test0);\n tests.reverse();\n CHECK(tests.get(0) == test2);\n CHECK(tests.get(1) == test1);\n CHECK(tests.get(2) == test0);\n}\n\n<|endoftext|>"} {"text":"\/*===================================================================\nAPM_PLANNER Open Source Ground Control Station\n\n(c) 2014 APM_PLANNER PROJECT \n\nThis file is part of the APM_PLANNER project\n\n APM_PLANNER is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n APM_PLANNER is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with APM_PLANNER. If not, see .\n\n======================================================================*\/\n\n\/**\n * @file\n * @brief MAVLinkProtocol\n * This class handles incoming mavlink_message_t packets.\n * It will create a UAS class if one does not exist for a particular heartbeat systemid\n * It will pass mavlink_message_t on to the UAS class for further parsing\n *\n * @author Michael Carpenter \n * @author QGROUNDCONTROL PROJECT - This code has GPLv3+ snippets from QGROUNDCONTROL, (c) 2009, 2010 QGROUNDCONTROL PROJECT \n *\n *\/\n\n\n#include \"MAVLinkProtocol.h\"\n#include \"LinkManager.h\"\n\nMAVLinkProtocol::MAVLinkProtocol():\n m_loggingEnabled(false),\n m_logfile(NULL),\n m_connectionManager(NULL),\n m_isOnline(true)\n{\n}\n\nMAVLinkProtocol::~MAVLinkProtocol()\n{\n stopLogging();\n m_connectionManager = NULL;\n}\n\nvoid MAVLinkProtocol::sendMessage(mavlink_message_t msg)\n{\n Q_UNUSED(msg);\n}\n\nvoid MAVLinkProtocol::receiveBytes(LinkInterface* link, QByteArray b)\n{\n mavlink_message_t message;\n mavlink_status_t status;\n\n \/\/ Cache the link ID for common use.\n int linkId = link->getId();\n\n static int mavlink09Count = 0;\n static int nonmavlinkCount = 0;\n static bool decodedFirstPacket = false;\n static bool warnedUser = false;\n static bool checkedUserNonMavlink = false;\n static bool warnedUserNonMavlink = false;\n\n \/\/ FIXME: Add check for if link->getId() >= MAVLINK_COMM_NUM_BUFFERS\n for (int position = 0; position < b.size(); position++) {\n unsigned int decodeState = mavlink_parse_char(linkId, (uint8_t)(b[position]), &message, &status);\n\n if ((uint8_t)b[position] == 0x55) mavlink09Count++;\n if ((mavlink09Count > 100) && !decodedFirstPacket && !warnedUser)\n {\n warnedUser = true;\n \/\/ Obviously the user tries to use a 0.9 autopilot\n \/\/ with QGroundControl built for version 1.0\n emit protocolStatusMessage(\"MAVLink Version or Baud Rate Mismatch\", \"Your MAVLink device seems to use the deprecated version 0.9, while APM Planner only supports version 1.0+. Please upgrade the MAVLink version of your autopilot. If your autopilot is using version 1.0, check if the baud rates of APM Planner and your autopilot are the same.\");\n }\n\n if (decodeState == 0 && !decodedFirstPacket)\n {\n nonmavlinkCount++;\n if (nonmavlinkCount > 2000 && !warnedUserNonMavlink)\n {\n \/\/500 bytes with no mavlink message. Are we connected to a mavlink capable device?\n if (!checkedUserNonMavlink)\n {\n link->requestReset();\n nonmavlinkCount=0;\n checkedUserNonMavlink = true;\n }\n else\n {\n warnedUserNonMavlink = true;\n emit protocolStatusMessage(\"MAVLink Baud Rate Mismatch\", \"Please check if the baud rates of APM Planner and your autopilot are the same.\");\n }\n }\n }\n if (decodeState == 1)\n {\n decodedFirstPacket = true;\n\n if(message.msgid == MAVLINK_MSG_ID_PING)\n {\n \/\/ process ping requests (tgt_system and tgt_comp must be zero)\n mavlink_ping_t ping;\n mavlink_msg_ping_decode(&message, &ping);\n if(!ping.target_system && !ping.target_component && m_isOnline)\n {\n mavlink_message_t msg;\n mavlink_msg_ping_pack(getSystemId(), getComponentId(), &msg, ping.time_usec, ping.seq, message.sysid, message.compid);\n sendMessage(msg);\n }\n }\n\n#if defined(QGC_PROTOBUF_ENABLED)\n\n if (message.msgid == MAVLINK_MSG_ID_EXTENDED_MESSAGE)\n {\n mavlink_extended_message_t extended_message;\n\n extended_message.base_msg = message;\n\n \/\/ read extended header\n uint8_t* payload = reinterpret_cast(message.payload64);\n\n memcpy(&extended_message.extended_payload_len, payload + 3, 4);\n\n \/\/ Check if message is valid\n if\n (b.size() != MAVLINK_NUM_NON_PAYLOAD_BYTES+MAVLINK_EXTENDED_HEADER_LEN+ extended_message.extended_payload_len)\n {\n \/\/invalid message\n QLOG_DEBUG() << \"GOT INVALID EXTENDED MESSAGE, ABORTING\";\n return;\n }\n\n const uint8_t* extended_payload = reinterpret_cast(b.constData()) + MAVLINK_NUM_NON_PAYLOAD_BYTES + MAVLINK_EXTENDED_HEADER_LEN;\n\n \/\/ copy extended payload data\n memcpy(extended_message.extended_payload, extended_payload, extended_message.extended_payload_len);\n\n#if defined(QGC_USE_PIXHAWK_MESSAGES)\n\n if (protobufManager.cacheFragment(extended_message))\n {\n std::tr1::shared_ptr protobuf_msg;\n\n if (protobufManager.getMessage(protobuf_msg))\n {\n const google::protobuf::Descriptor* descriptor = protobuf_msg->GetDescriptor();\n if (!descriptor)\n {\n continue;\n }\n\n const google::protobuf::FieldDescriptor* headerField = descriptor->FindFieldByName(\"header\");\n if (!headerField)\n {\n continue;\n }\n\n const google::protobuf::Descriptor* headerDescriptor = headerField->message_type();\n if (!headerDescriptor)\n {\n continue;\n }\n\n const google::protobuf::FieldDescriptor* sourceSysIdField = headerDescriptor->FindFieldByName(\"source_sysid\");\n if (!sourceSysIdField)\n {\n continue;\n }\n\n const google::protobuf::Reflection* reflection = protobuf_msg->GetReflection();\n const google::protobuf::Message& headerMsg = reflection->GetMessage(*protobuf_msg, headerField);\n const google::protobuf::Reflection* headerReflection = headerMsg.GetReflection();\n\n int source_sysid = headerReflection->GetInt32(headerMsg, sourceSysIdField);\n\n UASInterface* uas = UASManager::instance()->getUASForId(source_sysid);\n\n if (uas != NULL)\n {\n emit extendedMessageReceived(link, protobuf_msg);\n }\n }\n }\n#endif\n\n position += extended_message.extended_payload_len;\n\n continue;\n }\n#endif\n\n \/\/ Log data\n if (m_loggingEnabled && m_logfile)\n {\n quint64 time = QGC::groundTimeUsecs();\n\n QDataStream outStream(m_logfile);\n outStream.setByteOrder(QDataStream::BigEndian);\n outStream << time; \/\/ write time stamp\n \/\/ write headers, payload (incs CRC)\n int bytesWritten = outStream.writeRawData((const char*)&message.magic,\n static_cast(MAVLINK_NUM_NON_PAYLOAD_BYTES + message.len));\n\n if(bytesWritten != (MAVLINK_NUM_NON_PAYLOAD_BYTES + message.len))\n {\n emit protocolStatusMessage(tr(\"MAVLink Logging failed\"),\n tr(\"Could not write to file %1, disabling logging.\")\n .arg(m_logfile->fileName()));\n \/\/ Stop logging\n stopLogging();\n }\n }\n quint64 time = QGC::groundTimeUsecs();\n m_mavlinkMsgBuffer[time] = message;\n if (m_isOnline)\n {\n handleMessage(time,link);\n }\n }\n }\n}\nvoid MAVLinkProtocol::handleMessage(quint64 timeid,LinkInterface *link)\n{\n mavlink_message_t message = m_mavlinkMsgBuffer.value(timeid);\n unsigned int linkId = link->getId();\n \/\/ ORDER MATTERS HERE!\n \/\/ If the matching UAS object does not yet exist, it has to be created\n \/\/ before emitting the packetReceived signal\n\n \/\/UASInterface* uas = UASManager::instance()->getUASForId(message.sysid);\n Q_ASSERT_X(m_connectionManager != NULL, \"MAVLinkProtocol::receiveBytes\", \" error:m_connectionManager == NULL\");\n UASInterface* uas = m_connectionManager->getUas(message.sysid);\n \/\/qDebug() << \"MAVLinkProtocol::receiveBytes\" << uas;\n\n \/\/ Check and (if necessary) create UAS object\n if (uas == NULL && message.msgid == MAVLINK_MSG_ID_HEARTBEAT)\n {\n \/\/ ORDER MATTERS HERE!\n \/\/ The UAS object has first to be created and connected,\n \/\/ only then the rest of the application can be made aware\n \/\/ of its existence, as it only then can send and receive\n \/\/ it's first messages.\n\n \/\/ Check if the UAS has the same id like this system\n if (message.sysid == getSystemId())\n {\n if (m_throwAwayGCSPackets)\n {\n \/\/If replaying, we have to assume that it's just hearing ground control traffic\n return;\n }\n emit protocolStatusMessage(tr(\"SYSTEM ID CONFLICT!\"), tr(\"Warning: A second system is using the same system id (%1)\").arg(getSystemId()));\n }\n\n \/\/ Create a new UAS based on the heartbeat received\n \/\/ Todo dynamically load plugin at run-time for MAV\n \/\/ WIKISEARCH:AUTOPILOT_TYPE_INSTANTIATION\n\n \/\/ First create new UAS object\n \/\/ Decode heartbeat message\n mavlink_heartbeat_t heartbeat;\n \/\/ Reset version field to 0\n heartbeat.mavlink_version = 0;\n mavlink_msg_heartbeat_decode(&message, &heartbeat);\n\n \/\/ Check if the UAS has a different protocol version\n if (m_enable_version_check && (heartbeat.mavlink_version != MAVLINK_VERSION))\n {\n \/\/ Bring up dialog to inform user\n if (!versionMismatchIgnore)\n {\n emit protocolStatusMessage(tr(\"The MAVLink protocol version on the MAV and APM Planner mismatch!\"),\n tr(\"It is unsafe to use different MAVLink versions. APM Planner therefore refuses to connect to system %1, which sends MAVLink version %2 (APM Planner uses version %3).\").arg(message.sysid).arg(heartbeat.mavlink_version).arg(MAVLINK_VERSION));\n versionMismatchIgnore = true;\n }\n\n \/\/ Ignore this message and continue gracefully\n return;\n }\n\n \/\/ Create a new UAS object\n uas = m_connectionManager->createUAS(this,link,message.sysid,&heartbeat); \/\/QGCMAVLinkUASFactory::createUAS(this, link, message.sysid, &heartbeat);\n }\n\n \/\/ Only count message if UAS exists for this message\n if (uas != NULL)\n {\n\n \/\/ Increase receive counter\n totalReceiveCounter[linkId]++;\n currReceiveCounter[linkId]++;\n\n \/\/ Update last message sequence ID\n uint8_t expectedIndex;\n if (lastIndex.contains(message.sysid))\n {\n if (lastIndex.value(message.sysid).contains(message.compid))\n {\n if (lastIndex.value(message.sysid).value(message.compid) == -1)\n {\n lastIndex[message.sysid][message.compid] = message.seq;\n expectedIndex = message.seq;\n }\n else\n {\n expectedIndex = lastIndex[message.sysid][message.compid] + 1;\n }\n }\n else\n {\n lastIndex[message.sysid].insert(message.compid,message.seq);\n expectedIndex = message.seq;\n }\n }\n else\n {\n lastIndex.insert(message.sysid,QMap());\n lastIndex[message.sysid].insert(message.compid,message.seq);\n expectedIndex = message.seq;\n }\n\n \/\/ Make some noise if a message was skipped\n \/\/QLOG_DEBUG() << \"SYSID\" << message.sysid << \"COMPID\" << message.compid << \"MSGID\" << message.msgid << \"EXPECTED INDEX:\" << expectedIndex << \"SEQ\" << message.seq;\n if (message.seq != expectedIndex)\n {\n \/\/ Determine how many messages were skipped accounting for 0-wraparound\n int16_t lostMessages = message.seq - expectedIndex;\n if (lostMessages < 0)\n {\n \/\/ Usually, this happens in the case of an out-of order packet\n lostMessages = 0;\n }\n else\n {\n \/\/ Console generates excessive load at high loss rates, needs better GUI visualization\n \/\/QLOG_DEBUG() << QString(\"Lost %1 messages for comp %4: expected sequence ID %2 but received %3.\").arg(lostMessages).arg(expectedIndex).arg(message.seq).arg(message.compid);\n }\n totalLossCounter[linkId] += lostMessages;\n currLossCounter[linkId] += lostMessages;\n }\n\n \/\/ Update the last sequence ID\n lastIndex[message.sysid][message.compid] = message.seq;\n\n \/\/ Update on every 32th packet\n if (totalReceiveCounter[linkId] % 32 == 0)\n {\n \/\/ Calculate new loss ratio\n \/\/ Receive loss\n float receiveLoss = (double)currLossCounter[linkId]\/(double)(currReceiveCounter[linkId]+currLossCounter[linkId]);\n receiveLoss *= 100.0f;\n currLossCounter[linkId] = 0;\n currReceiveCounter[linkId] = 0;\n emit receiveLossChanged(message.sysid, receiveLoss);\n }\n\n \/\/ The packet is emitted as a whole, as it is only 255 - 261 bytes short\n \/\/ kind of inefficient, but no issue for a groundstation pc.\n \/\/ It buys as reentrancy for the whole code over all threads\n emit messageReceived(link, message);\n\n \/\/ Multiplex message if enabled\n \/\/if (m_multiplexingEnabled)\n \/\/{\n \/\/ Get all links connected to this unit\n \/\/QList links = LinkManager::instance()->getLinksForProtocol(this);\n\n \/\/ Emit message on all links that are currently connected\n \/\/foreach (LinkInterface* currLink, links)\n \/\/{\n \/\/ Only forward this message to the other links,\n \/\/ not the link the message was received on\n \/\/ if (currLink != link) sendMessage(currLink, message, message.sysid, message.compid);\n \/\/}\n \/\/}\n }\n}\n\nvoid MAVLinkProtocol::stopLogging()\n{\n if (m_logfile && m_logfile->isOpen()){\n QLOG_DEBUG() << \"Stop MAVLink logging\" << m_logfile->fileName();\n \/\/ Close the current open file\n m_logfile->close();\n delete m_logfile;\n m_logfile = NULL;\n }\n m_loggingEnabled = false;\n}\n\nbool MAVLinkProtocol::startLogging(const QString& filename)\n{\n if (m_logfile && m_logfile->isOpen())\n {\n return true;\n }\n stopLogging();\n QLOG_DEBUG() << \"Start MAVLink logging\" << filename;\n\n Q_ASSERT_X(m_logfile == NULL, \"startLogging\", \"m_logFile == NULL\");\n\n m_logfile = new QFile(filename);\n if (m_logfile->open(QIODevice::WriteOnly | QIODevice::Append)){\n m_loggingEnabled = true;\n\n } else {\n emit protocolStatusMessage(tr(\"Started MAVLink logging\"),\n tr(\"FAILED: MAVLink cannot start logging to.\").arg(m_logfile->fileName()));\n m_loggingEnabled = false;\n delete m_logfile;\n m_logfile = NULL;\n }\n \/\/emit loggingChanged(m_loggingEnabled);\n return m_loggingEnabled; \/\/ reflects if logging started or not.\n}\nMAVLink: Fix comparison to use correct type.\/*===================================================================\nAPM_PLANNER Open Source Ground Control Station\n\n(c) 2014 APM_PLANNER PROJECT \n\nThis file is part of the APM_PLANNER project\n\n APM_PLANNER is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n APM_PLANNER is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with APM_PLANNER. If not, see .\n\n======================================================================*\/\n\n\/**\n * @file\n * @brief MAVLinkProtocol\n * This class handles incoming mavlink_message_t packets.\n * It will create a UAS class if one does not exist for a particular heartbeat systemid\n * It will pass mavlink_message_t on to the UAS class for further parsing\n *\n * @author Michael Carpenter \n * @author QGROUNDCONTROL PROJECT - This code has GPLv3+ snippets from QGROUNDCONTROL, (c) 2009, 2010 QGROUNDCONTROL PROJECT \n *\n *\/\n\n\n#include \"MAVLinkProtocol.h\"\n#include \"LinkManager.h\"\n\nMAVLinkProtocol::MAVLinkProtocol():\n m_isOnline(true),\n m_loggingEnabled(false),\n m_logfile(NULL),\n m_connectionManager(NULL)\n{\n}\n\nMAVLinkProtocol::~MAVLinkProtocol()\n{\n stopLogging();\n m_connectionManager = NULL;\n}\n\nvoid MAVLinkProtocol::sendMessage(mavlink_message_t msg)\n{\n Q_UNUSED(msg);\n}\n\nvoid MAVLinkProtocol::receiveBytes(LinkInterface* link, QByteArray b)\n{\n mavlink_message_t message;\n mavlink_status_t status;\n\n \/\/ Cache the link ID for common use.\n int linkId = link->getId();\n\n static int mavlink09Count = 0;\n static int nonmavlinkCount = 0;\n static bool decodedFirstPacket = false;\n static bool warnedUser = false;\n static bool checkedUserNonMavlink = false;\n static bool warnedUserNonMavlink = false;\n\n \/\/ FIXME: Add check for if link->getId() >= MAVLINK_COMM_NUM_BUFFERS\n for (int position = 0; position < b.size(); position++) {\n unsigned int decodeState = mavlink_parse_char(linkId, (uint8_t)(b[position]), &message, &status);\n\n if ((uint8_t)b[position] == 0x55) mavlink09Count++;\n if ((mavlink09Count > 100) && !decodedFirstPacket && !warnedUser)\n {\n warnedUser = true;\n \/\/ Obviously the user tries to use a 0.9 autopilot\n \/\/ with QGroundControl built for version 1.0\n emit protocolStatusMessage(\"MAVLink Version or Baud Rate Mismatch\", \"Your MAVLink device seems to use the deprecated version 0.9, while APM Planner only supports version 1.0+. Please upgrade the MAVLink version of your autopilot. If your autopilot is using version 1.0, check if the baud rates of APM Planner and your autopilot are the same.\");\n }\n\n if (decodeState == 0 && !decodedFirstPacket)\n {\n nonmavlinkCount++;\n if (nonmavlinkCount > 2000 && !warnedUserNonMavlink)\n {\n \/\/500 bytes with no mavlink message. Are we connected to a mavlink capable device?\n if (!checkedUserNonMavlink)\n {\n link->requestReset();\n nonmavlinkCount=0;\n checkedUserNonMavlink = true;\n }\n else\n {\n warnedUserNonMavlink = true;\n emit protocolStatusMessage(\"MAVLink Baud Rate Mismatch\", \"Please check if the baud rates of APM Planner and your autopilot are the same.\");\n }\n }\n }\n if (decodeState == 1)\n {\n decodedFirstPacket = true;\n\n if(message.msgid == MAVLINK_MSG_ID_PING)\n {\n \/\/ process ping requests (tgt_system and tgt_comp must be zero)\n mavlink_ping_t ping;\n mavlink_msg_ping_decode(&message, &ping);\n if(!ping.target_system && !ping.target_component && m_isOnline)\n {\n mavlink_message_t msg;\n mavlink_msg_ping_pack(getSystemId(), getComponentId(), &msg, ping.time_usec, ping.seq, message.sysid, message.compid);\n sendMessage(msg);\n }\n }\n\n#if defined(QGC_PROTOBUF_ENABLED)\n\n if (message.msgid == MAVLINK_MSG_ID_EXTENDED_MESSAGE)\n {\n mavlink_extended_message_t extended_message;\n\n extended_message.base_msg = message;\n\n \/\/ read extended header\n uint8_t* payload = reinterpret_cast(message.payload64);\n\n memcpy(&extended_message.extended_payload_len, payload + 3, 4);\n\n \/\/ Check if message is valid\n if\n (b.size() != MAVLINK_NUM_NON_PAYLOAD_BYTES+MAVLINK_EXTENDED_HEADER_LEN+ extended_message.extended_payload_len)\n {\n \/\/invalid message\n QLOG_DEBUG() << \"GOT INVALID EXTENDED MESSAGE, ABORTING\";\n return;\n }\n\n const uint8_t* extended_payload = reinterpret_cast(b.constData()) + MAVLINK_NUM_NON_PAYLOAD_BYTES + MAVLINK_EXTENDED_HEADER_LEN;\n\n \/\/ copy extended payload data\n memcpy(extended_message.extended_payload, extended_payload, extended_message.extended_payload_len);\n\n#if defined(QGC_USE_PIXHAWK_MESSAGES)\n\n if (protobufManager.cacheFragment(extended_message))\n {\n std::tr1::shared_ptr protobuf_msg;\n\n if (protobufManager.getMessage(protobuf_msg))\n {\n const google::protobuf::Descriptor* descriptor = protobuf_msg->GetDescriptor();\n if (!descriptor)\n {\n continue;\n }\n\n const google::protobuf::FieldDescriptor* headerField = descriptor->FindFieldByName(\"header\");\n if (!headerField)\n {\n continue;\n }\n\n const google::protobuf::Descriptor* headerDescriptor = headerField->message_type();\n if (!headerDescriptor)\n {\n continue;\n }\n\n const google::protobuf::FieldDescriptor* sourceSysIdField = headerDescriptor->FindFieldByName(\"source_sysid\");\n if (!sourceSysIdField)\n {\n continue;\n }\n\n const google::protobuf::Reflection* reflection = protobuf_msg->GetReflection();\n const google::protobuf::Message& headerMsg = reflection->GetMessage(*protobuf_msg, headerField);\n const google::protobuf::Reflection* headerReflection = headerMsg.GetReflection();\n\n int source_sysid = headerReflection->GetInt32(headerMsg, sourceSysIdField);\n\n UASInterface* uas = UASManager::instance()->getUASForId(source_sysid);\n\n if (uas != NULL)\n {\n emit extendedMessageReceived(link, protobuf_msg);\n }\n }\n }\n#endif\n\n position += extended_message.extended_payload_len;\n\n continue;\n }\n#endif\n\n \/\/ Log data\n if (m_loggingEnabled && m_logfile)\n {\n quint64 time = QGC::groundTimeUsecs();\n\n QDataStream outStream(m_logfile);\n outStream.setByteOrder(QDataStream::BigEndian);\n outStream << time; \/\/ write time stamp\n \/\/ write headers, payload (incs CRC)\n int bytesWritten = outStream.writeRawData((const char*)&message.magic,\n static_cast(MAVLINK_NUM_NON_PAYLOAD_BYTES + message.len));\n\n if(bytesWritten != (MAVLINK_NUM_NON_PAYLOAD_BYTES + message.len))\n {\n emit protocolStatusMessage(tr(\"MAVLink Logging failed\"),\n tr(\"Could not write to file %1, disabling logging.\")\n .arg(m_logfile->fileName()));\n \/\/ Stop logging\n stopLogging();\n }\n }\n quint64 time = QGC::groundTimeUsecs();\n m_mavlinkMsgBuffer[time] = message;\n if (m_isOnline)\n {\n handleMessage(time,link);\n }\n }\n }\n}\nvoid MAVLinkProtocol::handleMessage(quint64 timeid,LinkInterface *link)\n{\n mavlink_message_t message = m_mavlinkMsgBuffer.value(timeid);\n unsigned int linkId = link->getId();\n \/\/ ORDER MATTERS HERE!\n \/\/ If the matching UAS object does not yet exist, it has to be created\n \/\/ before emitting the packetReceived signal\n\n \/\/UASInterface* uas = UASManager::instance()->getUASForId(message.sysid);\n Q_ASSERT_X(m_connectionManager != NULL, \"MAVLinkProtocol::receiveBytes\", \" error:m_connectionManager == NULL\");\n UASInterface* uas = m_connectionManager->getUas(message.sysid);\n \/\/qDebug() << \"MAVLinkProtocol::receiveBytes\" << uas;\n\n \/\/ Check and (if necessary) create UAS object\n if (uas == NULL && message.msgid == MAVLINK_MSG_ID_HEARTBEAT)\n {\n \/\/ ORDER MATTERS HERE!\n \/\/ The UAS object has first to be created and connected,\n \/\/ only then the rest of the application can be made aware\n \/\/ of its existence, as it only then can send and receive\n \/\/ it's first messages.\n\n \/\/ Check if the UAS has the same id like this system\n if (message.sysid == getSystemId())\n {\n if (m_throwAwayGCSPackets)\n {\n \/\/If replaying, we have to assume that it's just hearing ground control traffic\n return;\n }\n emit protocolStatusMessage(tr(\"SYSTEM ID CONFLICT!\"), tr(\"Warning: A second system is using the same system id (%1)\").arg(getSystemId()));\n }\n\n \/\/ Create a new UAS based on the heartbeat received\n \/\/ Todo dynamically load plugin at run-time for MAV\n \/\/ WIKISEARCH:AUTOPILOT_TYPE_INSTANTIATION\n\n \/\/ First create new UAS object\n \/\/ Decode heartbeat message\n mavlink_heartbeat_t heartbeat;\n \/\/ Reset version field to 0\n heartbeat.mavlink_version = 0;\n mavlink_msg_heartbeat_decode(&message, &heartbeat);\n\n \/\/ Check if the UAS has a different protocol version\n if (m_enable_version_check && (heartbeat.mavlink_version != MAVLINK_VERSION))\n {\n \/\/ Bring up dialog to inform user\n if (!versionMismatchIgnore)\n {\n emit protocolStatusMessage(tr(\"The MAVLink protocol version on the MAV and APM Planner mismatch!\"),\n tr(\"It is unsafe to use different MAVLink versions. APM Planner therefore refuses to connect to system %1, which sends MAVLink version %2 (APM Planner uses version %3).\").arg(message.sysid).arg(heartbeat.mavlink_version).arg(MAVLINK_VERSION));\n versionMismatchIgnore = true;\n }\n\n \/\/ Ignore this message and continue gracefully\n return;\n }\n\n \/\/ Create a new UAS object\n uas = m_connectionManager->createUAS(this,link,message.sysid,&heartbeat); \/\/QGCMAVLinkUASFactory::createUAS(this, link, message.sysid, &heartbeat);\n }\n\n \/\/ Only count message if UAS exists for this message\n if (uas != NULL)\n {\n\n \/\/ Increase receive counter\n totalReceiveCounter[linkId]++;\n currReceiveCounter[linkId]++;\n\n \/\/ Update last message sequence ID\n uint8_t expectedIndex;\n if (lastIndex.contains(message.sysid))\n {\n if (lastIndex.value(message.sysid).contains(message.compid))\n {\n if (lastIndex.value(message.sysid).value(message.compid) == static_cast(-1))\n {\n lastIndex[message.sysid][message.compid] = message.seq;\n expectedIndex = message.seq;\n }\n else\n {\n expectedIndex = lastIndex[message.sysid][message.compid] + 1;\n }\n }\n else\n {\n lastIndex[message.sysid].insert(message.compid,message.seq);\n expectedIndex = message.seq;\n }\n }\n else\n {\n lastIndex.insert(message.sysid,QMap());\n lastIndex[message.sysid].insert(message.compid,message.seq);\n expectedIndex = message.seq;\n }\n\n \/\/ Make some noise if a message was skipped\n \/\/QLOG_DEBUG() << \"SYSID\" << message.sysid << \"COMPID\" << message.compid << \"MSGID\" << message.msgid << \"EXPECTED INDEX:\" << expectedIndex << \"SEQ\" << message.seq;\n if (message.seq != expectedIndex)\n {\n \/\/ Determine how many messages were skipped accounting for 0-wraparound\n int16_t lostMessages = message.seq - expectedIndex;\n if (lostMessages < 0)\n {\n \/\/ Usually, this happens in the case of an out-of order packet\n lostMessages = 0;\n }\n else\n {\n \/\/ Console generates excessive load at high loss rates, needs better GUI visualization\n \/\/QLOG_DEBUG() << QString(\"Lost %1 messages for comp %4: expected sequence ID %2 but received %3.\").arg(lostMessages).arg(expectedIndex).arg(message.seq).arg(message.compid);\n }\n totalLossCounter[linkId] += lostMessages;\n currLossCounter[linkId] += lostMessages;\n }\n\n \/\/ Update the last sequence ID\n lastIndex[message.sysid][message.compid] = message.seq;\n\n \/\/ Update on every 32th packet\n if (totalReceiveCounter[linkId] % 32 == 0)\n {\n \/\/ Calculate new loss ratio\n \/\/ Receive loss\n float receiveLoss = (double)currLossCounter[linkId]\/(double)(currReceiveCounter[linkId]+currLossCounter[linkId]);\n receiveLoss *= 100.0f;\n currLossCounter[linkId] = 0;\n currReceiveCounter[linkId] = 0;\n emit receiveLossChanged(message.sysid, receiveLoss);\n }\n\n \/\/ The packet is emitted as a whole, as it is only 255 - 261 bytes short\n \/\/ kind of inefficient, but no issue for a groundstation pc.\n \/\/ It buys as reentrancy for the whole code over all threads\n emit messageReceived(link, message);\n\n \/\/ Multiplex message if enabled\n \/\/if (m_multiplexingEnabled)\n \/\/{\n \/\/ Get all links connected to this unit\n \/\/QList links = LinkManager::instance()->getLinksForProtocol(this);\n\n \/\/ Emit message on all links that are currently connected\n \/\/foreach (LinkInterface* currLink, links)\n \/\/{\n \/\/ Only forward this message to the other links,\n \/\/ not the link the message was received on\n \/\/ if (currLink != link) sendMessage(currLink, message, message.sysid, message.compid);\n \/\/}\n \/\/}\n }\n}\n\nvoid MAVLinkProtocol::stopLogging()\n{\n if (m_logfile && m_logfile->isOpen()){\n QLOG_DEBUG() << \"Stop MAVLink logging\" << m_logfile->fileName();\n \/\/ Close the current open file\n m_logfile->close();\n delete m_logfile;\n m_logfile = NULL;\n }\n m_loggingEnabled = false;\n}\n\nbool MAVLinkProtocol::startLogging(const QString& filename)\n{\n if (m_logfile && m_logfile->isOpen())\n {\n return true;\n }\n stopLogging();\n QLOG_DEBUG() << \"Start MAVLink logging\" << filename;\n\n Q_ASSERT_X(m_logfile == NULL, \"startLogging\", \"m_logFile == NULL\");\n\n m_logfile = new QFile(filename);\n if (m_logfile->open(QIODevice::WriteOnly | QIODevice::Append)){\n m_loggingEnabled = true;\n\n } else {\n emit protocolStatusMessage(tr(\"Started MAVLink logging\"),\n tr(\"FAILED: MAVLink cannot start logging to.\").arg(m_logfile->fileName()));\n m_loggingEnabled = false;\n delete m_logfile;\n m_logfile = NULL;\n }\n \/\/emit loggingChanged(m_loggingEnabled);\n return m_loggingEnabled; \/\/ reflects if logging started or not.\n}\n<|endoftext|>"} {"text":"\/*===================================================================\nAPM_PLANNER Open Source Ground Control Station\n\n(c) 2014 APM_PLANNER PROJECT \n\nThis file is part of the APM_PLANNER project\n\n APM_PLANNER is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n APM_PLANNER is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with APM_PLANNER. If not, see .\n\n======================================================================*\/\n\n\/**\n * @file\n * @brief MAVLinkProtocol\n * This class handles incoming mavlink_message_t packets.\n * It will create a UAS class if one does not exist for a particular heartbeat systemid\n * It will pass mavlink_message_t on to the UAS class for further parsing\n *\n * @author Michael Carpenter \n * @author QGROUNDCONTROL PROJECT - This code has GPLv3+ snippets from QGROUNDCONTROL, (c) 2009, 2010 QGROUNDCONTROL PROJECT \n *\n *\/\n\n\n#include \"MAVLinkProtocol.h\"\n#include \"LinkManager.h\"\n\nMAVLinkProtocol::MAVLinkProtocol(QObject *parent)\n{\n m_loggingEnabled = false;\n m_logfile=NULL;\n}\nvoid MAVLinkProtocol::receiveBytes(LinkInterface* link, QByteArray b)\n{\n mavlink_message_t message;\n mavlink_status_t status;\n\n \/\/ Cache the link ID for common use.\n int linkId = link->getId();\n\n static int mavlink09Count = 0;\n static int nonmavlinkCount = 0;\n static bool decodedFirstPacket = false;\n static bool warnedUser = false;\n static bool checkedUserNonMavlink = false;\n static bool warnedUserNonMavlink = false;\n\n \/\/ FIXME: Add check for if link->getId() >= MAVLINK_COMM_NUM_BUFFERS\n for (int position = 0; position < b.size(); position++) {\n unsigned int decodeState = mavlink_parse_char(linkId, (uint8_t)(b[position]), &message, &status);\n\n if ((uint8_t)b[position] == 0x55) mavlink09Count++;\n if ((mavlink09Count > 100) && !decodedFirstPacket && !warnedUser)\n {\n warnedUser = true;\n \/\/ Obviously the user tries to use a 0.9 autopilot\n \/\/ with QGroundControl built for version 1.0\n emit protocolStatusMessage(\"MAVLink Version or Baud Rate Mismatch\", \"Your MAVLink device seems to use the deprecated version 0.9, while APM Planner only supports version 1.0+. Please upgrade the MAVLink version of your autopilot. If your autopilot is using version 1.0, check if the baud rates of APM Planner and your autopilot are the same.\");\n }\n\n if (decodeState == 0 && !decodedFirstPacket)\n {\n nonmavlinkCount++;\n if (nonmavlinkCount > 2000 && !warnedUserNonMavlink)\n {\n \/\/500 bytes with no mavlink message. Are we connected to a mavlink capable device?\n if (!checkedUserNonMavlink)\n {\n link->requestReset();\n nonmavlinkCount=0;\n checkedUserNonMavlink = true;\n }\n else\n {\n warnedUserNonMavlink = true;\n emit protocolStatusMessage(\"MAVLink Baud Rate Mismatch\", \"Please check if the baud rates of APM Planner and your autopilot are the same.\");\n }\n }\n }\n if (decodeState == 1)\n {\n decodedFirstPacket = true;\n\n if(message.msgid == MAVLINK_MSG_ID_PING)\n {\n \/\/ process ping requests (tgt_system and tgt_comp must be zero)\n mavlink_ping_t ping;\n mavlink_msg_ping_decode(&message, &ping);\n if(!ping.target_system && !ping.target_component)\n {\n mavlink_message_t msg;\n mavlink_msg_ping_pack(getSystemId(), getComponentId(), &msg, ping.time_usec, ping.seq, message.sysid, message.compid);\n sendMessage(msg);\n }\n }\n\n#if defined(QGC_PROTOBUF_ENABLED)\n\n if (message.msgid == MAVLINK_MSG_ID_EXTENDED_MESSAGE)\n {\n mavlink_extended_message_t extended_message;\n\n extended_message.base_msg = message;\n\n \/\/ read extended header\n uint8_t* payload = reinterpret_cast(message.payload64);\n\n memcpy(&extended_message.extended_payload_len, payload + 3, 4);\n\n \/\/ Check if message is valid\n if\n (b.size() != MAVLINK_NUM_NON_PAYLOAD_BYTES+MAVLINK_EXTENDED_HEADER_LEN+ extended_message.extended_payload_len)\n {\n \/\/invalid message\n QLOG_DEBUG() << \"GOT INVALID EXTENDED MESSAGE, ABORTING\";\n return;\n }\n\n const uint8_t* extended_payload = reinterpret_cast(b.constData()) + MAVLINK_NUM_NON_PAYLOAD_BYTES + MAVLINK_EXTENDED_HEADER_LEN;\n\n \/\/ copy extended payload data\n memcpy(extended_message.extended_payload, extended_payload, extended_message.extended_payload_len);\n\n#if defined(QGC_USE_PIXHAWK_MESSAGES)\n\n if (protobufManager.cacheFragment(extended_message))\n {\n std::tr1::shared_ptr protobuf_msg;\n\n if (protobufManager.getMessage(protobuf_msg))\n {\n const google::protobuf::Descriptor* descriptor = protobuf_msg->GetDescriptor();\n if (!descriptor)\n {\n continue;\n }\n\n const google::protobuf::FieldDescriptor* headerField = descriptor->FindFieldByName(\"header\");\n if (!headerField)\n {\n continue;\n }\n\n const google::protobuf::Descriptor* headerDescriptor = headerField->message_type();\n if (!headerDescriptor)\n {\n continue;\n }\n\n const google::protobuf::FieldDescriptor* sourceSysIdField = headerDescriptor->FindFieldByName(\"source_sysid\");\n if (!sourceSysIdField)\n {\n continue;\n }\n\n const google::protobuf::Reflection* reflection = protobuf_msg->GetReflection();\n const google::protobuf::Message& headerMsg = reflection->GetMessage(*protobuf_msg, headerField);\n const google::protobuf::Reflection* headerReflection = headerMsg.GetReflection();\n\n int source_sysid = headerReflection->GetInt32(headerMsg, sourceSysIdField);\n\n UASInterface* uas = UASManager::instance()->getUASForId(source_sysid);\n\n if (uas != NULL)\n {\n emit extendedMessageReceived(link, protobuf_msg);\n }\n }\n }\n#endif\n\n position += extended_message.extended_payload_len;\n\n continue;\n }\n#endif\n\n \/\/ Log data\n if (m_loggingEnabled && m_logfile)\n {\n quint64 time = QGC::groundTimeUsecs();\n\n QDataStream outStream(m_logfile);\n outStream.setByteOrder(QDataStream::BigEndian);\n outStream << time; \/\/ write time stamp\n \/\/ write headers, payload (incs CRC)\n int bytesWritten = outStream.writeRawData((const char*)&message.magic,\n static_cast(MAVLINK_NUM_NON_PAYLOAD_BYTES + message.len));\n\n if(bytesWritten != (MAVLINK_NUM_NON_PAYLOAD_BYTES + message.len))\n {\n emit protocolStatusMessage(tr(\"MAVLink Logging failed\"),\n tr(\"Could not write to file %1, disabling logging.\")\n .arg(m_logfile->fileName()));\n \/\/ Stop logging\n stopLogging();\n }\n }\n\n \/\/ ORDER MATTERS HERE!\n \/\/ If the matching UAS object does not yet exist, it has to be created\n \/\/ before emitting the packetReceived signal\n\n \/\/UASInterface* uas = UASManager::instance()->getUASForId(message.sysid);\n UASInterface* uas = m_connectionManager->getUas(message.sysid);\n \/\/qDebug() << \"MAVLinkProtocol::receiveBytes\" << uas;\n\n \/\/ Check and (if necessary) create UAS object\n if (uas == NULL && message.msgid == MAVLINK_MSG_ID_HEARTBEAT)\n {\n \/\/ ORDER MATTERS HERE!\n \/\/ The UAS object has first to be created and connected,\n \/\/ only then the rest of the application can be made aware\n \/\/ of its existence, as it only then can send and receive\n \/\/ it's first messages.\n\n \/\/ Check if the UAS has the same id like this system\n if (message.sysid == getSystemId())\n {\n if (m_throwAwayGCSPackets)\n {\n \/\/If replaying, we have to assume that it's just hearing ground control traffic\n return;\n }\n emit protocolStatusMessage(tr(\"SYSTEM ID CONFLICT!\"), tr(\"Warning: A second system is using the same system id (%1)\").arg(getSystemId()));\n }\n\n \/\/ Create a new UAS based on the heartbeat received\n \/\/ Todo dynamically load plugin at run-time for MAV\n \/\/ WIKISEARCH:AUTOPILOT_TYPE_INSTANTIATION\n\n \/\/ First create new UAS object\n \/\/ Decode heartbeat message\n mavlink_heartbeat_t heartbeat;\n \/\/ Reset version field to 0\n heartbeat.mavlink_version = 0;\n mavlink_msg_heartbeat_decode(&message, &heartbeat);\n\n \/\/ Check if the UAS has a different protocol version\n if (m_enable_version_check && (heartbeat.mavlink_version != MAVLINK_VERSION))\n {\n \/\/ Bring up dialog to inform user\n if (!versionMismatchIgnore)\n {\n emit protocolStatusMessage(tr(\"The MAVLink protocol version on the MAV and APM Planner mismatch!\"),\n tr(\"It is unsafe to use different MAVLink versions. APM Planner therefore refuses to connect to system %1, which sends MAVLink version %2 (APM Planner uses version %3).\").arg(message.sysid).arg(heartbeat.mavlink_version).arg(MAVLINK_VERSION));\n versionMismatchIgnore = true;\n }\n\n \/\/ Ignore this message and continue gracefully\n continue;\n }\n\n \/\/ Create a new UAS object\n uas = m_connectionManager->createUAS(this,link,message.sysid,&heartbeat); \/\/QGCMAVLinkUASFactory::createUAS(this, link, message.sysid, &heartbeat);\n }\n\n \/\/ Only count message if UAS exists for this message\n if (uas != NULL)\n {\n\n \/\/ Increase receive counter\n totalReceiveCounter[linkId]++;\n currReceiveCounter[linkId]++;\n\n \/\/ Update last message sequence ID\n uint8_t expectedIndex;\n if (lastIndex.contains(message.sysid))\n {\n if (lastIndex.value(message.sysid).contains(message.compid))\n {\n if (lastIndex.value(message.sysid).value(message.compid) == -1)\n {\n lastIndex[message.sysid][message.compid] = message.seq;\n expectedIndex = message.seq;\n }\n else\n {\n expectedIndex = lastIndex[message.sysid][message.compid] + 1;\n }\n }\n else\n {\n lastIndex[message.sysid].insert(message.compid,message.seq);\n expectedIndex = message.seq;\n }\n }\n else\n {\n lastIndex.insert(message.sysid,QMap());\n lastIndex[message.sysid].insert(message.compid,message.seq);\n expectedIndex = message.seq;\n }\n\n \/\/ Make some noise if a message was skipped\n \/\/QLOG_DEBUG() << \"SYSID\" << message.sysid << \"COMPID\" << message.compid << \"MSGID\" << message.msgid << \"EXPECTED INDEX:\" << expectedIndex << \"SEQ\" << message.seq;\n if (message.seq != expectedIndex)\n {\n \/\/ Determine how many messages were skipped accounting for 0-wraparound\n int16_t lostMessages = message.seq - expectedIndex;\n if (lostMessages < 0)\n {\n \/\/ Usually, this happens in the case of an out-of order packet\n lostMessages = 0;\n }\n else\n {\n \/\/ Console generates excessive load at high loss rates, needs better GUI visualization\n \/\/QLOG_DEBUG() << QString(\"Lost %1 messages for comp %4: expected sequence ID %2 but received %3.\").arg(lostMessages).arg(expectedIndex).arg(message.seq).arg(message.compid);\n }\n totalLossCounter[linkId] += lostMessages;\n currLossCounter[linkId] += lostMessages;\n }\n\n \/\/ Update the last sequence ID\n lastIndex[message.sysid][message.compid] = message.seq;\n\n \/\/ Update on every 32th packet\n if (totalReceiveCounter[linkId] % 32 == 0)\n {\n \/\/ Calculate new loss ratio\n \/\/ Receive loss\n float receiveLoss = (double)currLossCounter[linkId]\/(double)(currReceiveCounter[linkId]+currLossCounter[linkId]);\n receiveLoss *= 100.0f;\n currLossCounter[linkId] = 0;\n currReceiveCounter[linkId] = 0;\n emit receiveLossChanged(message.sysid, receiveLoss);\n }\n\n \/\/ The packet is emitted as a whole, as it is only 255 - 261 bytes short\n \/\/ kind of inefficient, but no issue for a groundstation pc.\n \/\/ It buys as reentrancy for the whole code over all threads\n emit messageReceived(link, message);\n\n \/\/ Multiplex message if enabled\n \/\/if (m_multiplexingEnabled)\n \/\/{\n \/\/ Get all links connected to this unit\n \/\/QList links = LinkManager::instance()->getLinksForProtocol(this);\n\n \/\/ Emit message on all links that are currently connected\n \/\/foreach (LinkInterface* currLink, links)\n \/\/{\n \/\/ Only forward this message to the other links,\n \/\/ not the link the message was received on\n \/\/ if (currLink != link) sendMessage(currLink, message, message.sysid, message.compid);\n \/\/}\n \/\/}\n }\n }\n }\n}\nvoid MAVLinkProtocol::stopLogging()\n{\n if (m_logfile && m_logfile->isOpen()){\n QLOG_DEBUG() << \"Stop MAVLink logging\" << m_logfile->fileName();\n \/\/ Close the current open file\n m_logfile->close();\n delete m_logfile;\n m_logfile = NULL;\n }\n m_loggingEnabled = false;\n}\n\nbool MAVLinkProtocol::startLogging(const QString& filename)\n{\n if (m_logfile && m_logfile->isOpen())\n {\n return true;\n }\n stopLogging();\n QLOG_DEBUG() << \"Start MAVLink logging\" << filename;\n\n Q_ASSERT_X(m_logfile == NULL, \"startLogging\", \"m_logFile == NULL\");\n\n m_logfile = new QFile(filename);\n if (m_logfile->open(QIODevice::WriteOnly | QIODevice::Append)){\n m_loggingEnabled = true;\n\n } else {\n emit protocolStatusMessage(tr(\"Started MAVLink logging\"),\n tr(\"FAILED: MAVLink cannot start logging to.\").arg(m_logfile->fileName()));\n m_loggingEnabled = false;\n delete m_logfile;\n m_logfile = NULL;\n }\n \/\/emit loggingChanged(m_loggingEnabled);\n return m_loggingEnabled; \/\/ reflects if logging started or not.\n}\nComms: Fix to undo tautological code\/*===================================================================\nAPM_PLANNER Open Source Ground Control Station\n\n(c) 2014 APM_PLANNER PROJECT \n\nThis file is part of the APM_PLANNER project\n\n APM_PLANNER is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n APM_PLANNER is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with APM_PLANNER. If not, see .\n\n======================================================================*\/\n\n\/**\n * @file\n * @brief MAVLinkProtocol\n * This class handles incoming mavlink_message_t packets.\n * It will create a UAS class if one does not exist for a particular heartbeat systemid\n * It will pass mavlink_message_t on to the UAS class for further parsing\n *\n * @author Michael Carpenter \n * @author QGROUNDCONTROL PROJECT - This code has GPLv3+ snippets from QGROUNDCONTROL, (c) 2009, 2010 QGROUNDCONTROL PROJECT \n *\n *\/\n\n\n#include \"MAVLinkProtocol.h\"\n#include \"LinkManager.h\"\n\nMAVLinkProtocol::MAVLinkProtocol(QObject *parent)\n{\n m_loggingEnabled = false;\n m_logfile=NULL;\n}\nvoid MAVLinkProtocol::receiveBytes(LinkInterface* link, QByteArray b)\n{\n mavlink_message_t message;\n mavlink_status_t status;\n\n \/\/ Cache the link ID for common use.\n int linkId = link->getId();\n\n static int mavlink09Count = 0;\n static int nonmavlinkCount = 0;\n static bool decodedFirstPacket = false;\n static bool warnedUser = false;\n static bool checkedUserNonMavlink = false;\n static bool warnedUserNonMavlink = false;\n\n \/\/ FIXME: Add check for if link->getId() >= MAVLINK_COMM_NUM_BUFFERS\n for (int position = 0; position < b.size(); position++) {\n unsigned int decodeState = mavlink_parse_char(linkId, (uint8_t)(b[position]), &message, &status);\n\n if ((uint8_t)b[position] == 0x55) mavlink09Count++;\n if ((mavlink09Count > 100) && !decodedFirstPacket && !warnedUser)\n {\n warnedUser = true;\n \/\/ Obviously the user tries to use a 0.9 autopilot\n \/\/ with QGroundControl built for version 1.0\n emit protocolStatusMessage(\"MAVLink Version or Baud Rate Mismatch\", \"Your MAVLink device seems to use the deprecated version 0.9, while APM Planner only supports version 1.0+. Please upgrade the MAVLink version of your autopilot. If your autopilot is using version 1.0, check if the baud rates of APM Planner and your autopilot are the same.\");\n }\n\n if (decodeState == 0 && !decodedFirstPacket)\n {\n nonmavlinkCount++;\n if (nonmavlinkCount > 2000 && !warnedUserNonMavlink)\n {\n \/\/500 bytes with no mavlink message. Are we connected to a mavlink capable device?\n if (!checkedUserNonMavlink)\n {\n link->requestReset();\n nonmavlinkCount=0;\n checkedUserNonMavlink = true;\n }\n else\n {\n warnedUserNonMavlink = true;\n emit protocolStatusMessage(\"MAVLink Baud Rate Mismatch\", \"Please check if the baud rates of APM Planner and your autopilot are the same.\");\n }\n }\n }\n if (decodeState == 1)\n {\n decodedFirstPacket = true;\n\n if(message.msgid == MAVLINK_MSG_ID_PING)\n {\n \/\/ process ping requests (tgt_system and tgt_comp must be zero)\n mavlink_ping_t ping;\n mavlink_msg_ping_decode(&message, &ping);\n if(!ping.target_system && !ping.target_component)\n {\n mavlink_message_t msg;\n mavlink_msg_ping_pack(getSystemId(), getComponentId(), &msg, ping.time_usec, ping.seq, message.sysid, message.compid);\n sendMessage(msg);\n }\n }\n\n#if defined(QGC_PROTOBUF_ENABLED)\n\n if (message.msgid == MAVLINK_MSG_ID_EXTENDED_MESSAGE)\n {\n mavlink_extended_message_t extended_message;\n\n extended_message.base_msg = message;\n\n \/\/ read extended header\n uint8_t* payload = reinterpret_cast(message.payload64);\n\n memcpy(&extended_message.extended_payload_len, payload + 3, 4);\n\n \/\/ Check if message is valid\n if\n (b.size() != MAVLINK_NUM_NON_PAYLOAD_BYTES+MAVLINK_EXTENDED_HEADER_LEN+ extended_message.extended_payload_len)\n {\n \/\/invalid message\n QLOG_DEBUG() << \"GOT INVALID EXTENDED MESSAGE, ABORTING\";\n return;\n }\n\n const uint8_t* extended_payload = reinterpret_cast(b.constData()) + MAVLINK_NUM_NON_PAYLOAD_BYTES + MAVLINK_EXTENDED_HEADER_LEN;\n\n \/\/ copy extended payload data\n memcpy(extended_message.extended_payload, extended_payload, extended_message.extended_payload_len);\n\n#if defined(QGC_USE_PIXHAWK_MESSAGES)\n\n if (protobufManager.cacheFragment(extended_message))\n {\n std::tr1::shared_ptr protobuf_msg;\n\n if (protobufManager.getMessage(protobuf_msg))\n {\n const google::protobuf::Descriptor* descriptor = protobuf_msg->GetDescriptor();\n if (!descriptor)\n {\n continue;\n }\n\n const google::protobuf::FieldDescriptor* headerField = descriptor->FindFieldByName(\"header\");\n if (!headerField)\n {\n continue;\n }\n\n const google::protobuf::Descriptor* headerDescriptor = headerField->message_type();\n if (!headerDescriptor)\n {\n continue;\n }\n\n const google::protobuf::FieldDescriptor* sourceSysIdField = headerDescriptor->FindFieldByName(\"source_sysid\");\n if (!sourceSysIdField)\n {\n continue;\n }\n\n const google::protobuf::Reflection* reflection = protobuf_msg->GetReflection();\n const google::protobuf::Message& headerMsg = reflection->GetMessage(*protobuf_msg, headerField);\n const google::protobuf::Reflection* headerReflection = headerMsg.GetReflection();\n\n int source_sysid = headerReflection->GetInt32(headerMsg, sourceSysIdField);\n\n UASInterface* uas = UASManager::instance()->getUASForId(source_sysid);\n\n if (uas != NULL)\n {\n emit extendedMessageReceived(link, protobuf_msg);\n }\n }\n }\n#endif\n\n position += extended_message.extended_payload_len;\n\n continue;\n }\n#endif\n\n \/\/ Log data\n if (m_loggingEnabled && m_logfile)\n {\n quint64 time = QGC::groundTimeUsecs();\n\n QDataStream outStream(m_logfile);\n outStream.setByteOrder(QDataStream::BigEndian);\n outStream << time; \/\/ write time stamp\n \/\/ write headers, payload (incs CRC)\n int bytesWritten = outStream.writeRawData((const char*)&message.magic,\n static_cast(MAVLINK_NUM_NON_PAYLOAD_BYTES + message.len));\n\n if(bytesWritten != (MAVLINK_NUM_NON_PAYLOAD_BYTES + message.len))\n {\n emit protocolStatusMessage(tr(\"MAVLink Logging failed\"),\n tr(\"Could not write to file %1, disabling logging.\")\n .arg(m_logfile->fileName()));\n \/\/ Stop logging\n stopLogging();\n }\n }\n\n \/\/ ORDER MATTERS HERE!\n \/\/ If the matching UAS object does not yet exist, it has to be created\n \/\/ before emitting the packetReceived signal\n\n \/\/UASInterface* uas = UASManager::instance()->getUASForId(message.sysid);\n UASInterface* uas = m_connectionManager->getUas(message.sysid);\n \/\/qDebug() << \"MAVLinkProtocol::receiveBytes\" << uas;\n\n \/\/ Check and (if necessary) create UAS object\n if (uas == NULL && message.msgid == MAVLINK_MSG_ID_HEARTBEAT)\n {\n \/\/ ORDER MATTERS HERE!\n \/\/ The UAS object has first to be created and connected,\n \/\/ only then the rest of the application can be made aware\n \/\/ of its existence, as it only then can send and receive\n \/\/ it's first messages.\n\n \/\/ Check if the UAS has the same id like this system\n if (message.sysid == getSystemId())\n {\n if (m_throwAwayGCSPackets)\n {\n \/\/If replaying, we have to assume that it's just hearing ground control traffic\n return;\n }\n emit protocolStatusMessage(tr(\"SYSTEM ID CONFLICT!\"), tr(\"Warning: A second system is using the same system id (%1)\").arg(getSystemId()));\n }\n\n \/\/ Create a new UAS based on the heartbeat received\n \/\/ Todo dynamically load plugin at run-time for MAV\n \/\/ WIKISEARCH:AUTOPILOT_TYPE_INSTANTIATION\n\n \/\/ First create new UAS object\n \/\/ Decode heartbeat message\n mavlink_heartbeat_t heartbeat;\n \/\/ Reset version field to 0\n heartbeat.mavlink_version = 0;\n mavlink_msg_heartbeat_decode(&message, &heartbeat);\n\n \/\/ Check if the UAS has a different protocol version\n if (m_enable_version_check && (heartbeat.mavlink_version != MAVLINK_VERSION))\n {\n \/\/ Bring up dialog to inform user\n if (!versionMismatchIgnore)\n {\n emit protocolStatusMessage(tr(\"The MAVLink protocol version on the MAV and APM Planner mismatch!\"),\n tr(\"It is unsafe to use different MAVLink versions. APM Planner therefore refuses to connect to system %1, which sends MAVLink version %2 (APM Planner uses version %3).\").arg(message.sysid).arg(heartbeat.mavlink_version).arg(MAVLINK_VERSION));\n versionMismatchIgnore = true;\n }\n\n \/\/ Ignore this message and continue gracefully\n continue;\n }\n\n \/\/ Create a new UAS object\n uas = m_connectionManager->createUAS(this,link,message.sysid,&heartbeat); \/\/QGCMAVLinkUASFactory::createUAS(this, link, message.sysid, &heartbeat);\n }\n\n \/\/ Only count message if UAS exists for this message\n if (uas != NULL)\n {\n\n \/\/ Increase receive counter\n totalReceiveCounter[linkId]++;\n currReceiveCounter[linkId]++;\n\n \/\/ Update last message sequence ID\n uint8_t expectedIndex;\n if (lastIndex.contains(message.sysid))\n {\n if (lastIndex.value(message.sysid).contains(message.compid))\n {\n if (lastIndex.value(message.sysid).value(message.compid) == static_cast(-1))\n {\n lastIndex[message.sysid][message.compid] = message.seq;\n expectedIndex = message.seq;\n }\n else\n {\n expectedIndex = lastIndex[message.sysid][message.compid] + 1;\n }\n }\n else\n {\n lastIndex[message.sysid].insert(message.compid,message.seq);\n expectedIndex = message.seq;\n }\n }\n else\n {\n lastIndex.insert(message.sysid,QMap());\n lastIndex[message.sysid].insert(message.compid,message.seq);\n expectedIndex = message.seq;\n }\n\n \/\/ Make some noise if a message was skipped\n \/\/QLOG_DEBUG() << \"SYSID\" << message.sysid << \"COMPID\" << message.compid << \"MSGID\" << message.msgid << \"EXPECTED INDEX:\" << expectedIndex << \"SEQ\" << message.seq;\n if (message.seq != expectedIndex)\n {\n \/\/ Determine how many messages were skipped accounting for 0-wraparound\n int16_t lostMessages = message.seq - expectedIndex;\n if (lostMessages < 0)\n {\n \/\/ Usually, this happens in the case of an out-of order packet\n lostMessages = 0;\n }\n else\n {\n \/\/ Console generates excessive load at high loss rates, needs better GUI visualization\n \/\/QLOG_DEBUG() << QString(\"Lost %1 messages for comp %4: expected sequence ID %2 but received %3.\").arg(lostMessages).arg(expectedIndex).arg(message.seq).arg(message.compid);\n }\n totalLossCounter[linkId] += lostMessages;\n currLossCounter[linkId] += lostMessages;\n }\n\n \/\/ Update the last sequence ID\n lastIndex[message.sysid][message.compid] = message.seq;\n\n \/\/ Update on every 32th packet\n if (totalReceiveCounter[linkId] % 32 == 0)\n {\n \/\/ Calculate new loss ratio\n \/\/ Receive loss\n float receiveLoss = (double)currLossCounter[linkId]\/(double)(currReceiveCounter[linkId]+currLossCounter[linkId]);\n receiveLoss *= 100.0f;\n currLossCounter[linkId] = 0;\n currReceiveCounter[linkId] = 0;\n emit receiveLossChanged(message.sysid, receiveLoss);\n }\n\n \/\/ The packet is emitted as a whole, as it is only 255 - 261 bytes short\n \/\/ kind of inefficient, but no issue for a groundstation pc.\n \/\/ It buys as reentrancy for the whole code over all threads\n emit messageReceived(link, message);\n\n \/\/ Multiplex message if enabled\n \/\/if (m_multiplexingEnabled)\n \/\/{\n \/\/ Get all links connected to this unit\n \/\/QList links = LinkManager::instance()->getLinksForProtocol(this);\n\n \/\/ Emit message on all links that are currently connected\n \/\/foreach (LinkInterface* currLink, links)\n \/\/{\n \/\/ Only forward this message to the other links,\n \/\/ not the link the message was received on\n \/\/ if (currLink != link) sendMessage(currLink, message, message.sysid, message.compid);\n \/\/}\n \/\/}\n }\n }\n }\n}\nvoid MAVLinkProtocol::stopLogging()\n{\n if (m_logfile && m_logfile->isOpen()){\n QLOG_DEBUG() << \"Stop MAVLink logging\" << m_logfile->fileName();\n \/\/ Close the current open file\n m_logfile->close();\n delete m_logfile;\n m_logfile = NULL;\n }\n m_loggingEnabled = false;\n}\n\nbool MAVLinkProtocol::startLogging(const QString& filename)\n{\n if (m_logfile && m_logfile->isOpen())\n {\n return true;\n }\n stopLogging();\n QLOG_DEBUG() << \"Start MAVLink logging\" << filename;\n\n Q_ASSERT_X(m_logfile == NULL, \"startLogging\", \"m_logFile == NULL\");\n\n m_logfile = new QFile(filename);\n if (m_logfile->open(QIODevice::WriteOnly | QIODevice::Append)){\n m_loggingEnabled = true;\n\n } else {\n emit protocolStatusMessage(tr(\"Started MAVLink logging\"),\n tr(\"FAILED: MAVLink cannot start logging to.\").arg(m_logfile->fileName()));\n m_loggingEnabled = false;\n delete m_logfile;\n m_logfile = NULL;\n }\n \/\/emit loggingChanged(m_loggingEnabled);\n return m_loggingEnabled; \/\/ reflects if logging started or not.\n}\n<|endoftext|>"} {"text":"\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/\/ \\file\n\/\/\/ Tests for the FilteredDevice class.\n\n#include \n#include \n#include \n#include \"SurgSim\/DataStructures\/DataGroup.h\"\n#include \"SurgSim\/DataStructures\/DataGroupBuilder.h\"\n#include \"SurgSim\/Devices\/Devices.h\"\n#include \"SurgSim\/Framework\/Runtime.h\"\n#include \"SurgSim\/Testing\/MockInputOutput.h\"\n\nusing SurgSim::DataStructures::DataGroup;\nusing SurgSim::DataStructures::DataGroupBuilder;\nusing SurgSim::Devices::FilteredDevice;\nusing SurgSim::Testing::MockInputOutput;\n\nTEST(FilteredDeviceTest, ByHand)\n{\n\tauto filteredDevice = std::make_shared(\"device\");\n\tASSERT_FALSE(filteredDevice->initialize());\n\n\tASSERT_ANY_THROW(filteredDevice->setDevice(nullptr));\n\tASSERT_NO_THROW(filteredDevice->setDevice(std::make_shared(\"identity\")));\n\n\tfilteredDevice->addFilter(std::make_shared(\"filter1\"));\n\tfilteredDevice->addFilter(std::make_shared(\"filter2\"));\n\tEXPECT_TRUE(filteredDevice->initialize());\n\tEXPECT_ANY_THROW(filteredDevice->initialize());\n\n\tauto inputOutput = std::make_shared();\n\tEXPECT_TRUE(filteredDevice->addInputConsumer(inputOutput));\n\tEXPECT_TRUE(filteredDevice->removeInputConsumer(inputOutput));\n\n\tEXPECT_TRUE(filteredDevice->setOutputProducer(inputOutput));\n\tEXPECT_TRUE(filteredDevice->hasOutputProducer());\n\tEXPECT_TRUE(filteredDevice->removeOutputProducer(inputOutput));\n\tEXPECT_FALSE(filteredDevice->hasOutputProducer());\n}\n\nTEST(FilteredDeviceTest, Serialization)\n{\n\tauto runtime = std::make_shared(\"config.txt\");\n\tstd::shared_ptr device;\n\tASSERT_NO_THROW(device = SurgSim::Devices::loadDevice(\"FilteredDevice.yaml\"));\n\tASSERT_NE(nullptr, device);\n\tauto typedDevice = std::dynamic_pointer_cast(device);\n\tASSERT_NE(nullptr, typedDevice);\n\t\n\tauto input = std::make_shared();\n\tASSERT_TRUE(device->addInputConsumer(input));\n\tSurgSim::Math::RigidTransform3d pose;\n\tASSERT_TRUE(input->m_lastReceivedInput.poses().get(SurgSim::DataStructures::Names::POSE, &pose));\n\n\tEigen::AngleAxisd angleAxis;\n\tangleAxis.angle() = 12.3;\n\tangleAxis.axis() = SurgSim::Math::Vector3d(0.5, 0.5, 0.0);\n\tSurgSim::Math::Vector3d translation = SurgSim::Math::Vector3d(7.8, 8.9, 9.0);\n\tSurgSim::Math::RigidTransform3d expectedTransform =\n\t\tSurgSim::Math::makeRigidTransform(SurgSim::Math::Quaterniond(angleAxis), translation);\n\tEXPECT_TRUE(pose.isApprox(expectedTransform));\n\n\tASSERT_NO_THROW(device = SurgSim::Devices::loadDevice(\"BadFilteredDevice.yaml\"));\n\tEXPECT_EQ(nullptr, device);\n}FilteredDevice whitespace fix.\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/\/ \\file\n\/\/\/ Tests for the FilteredDevice class.\n\n#include \n#include \n#include \n#include \"SurgSim\/DataStructures\/DataGroup.h\"\n#include \"SurgSim\/DataStructures\/DataGroupBuilder.h\"\n#include \"SurgSim\/Devices\/Devices.h\"\n#include \"SurgSim\/Framework\/Runtime.h\"\n#include \"SurgSim\/Testing\/MockInputOutput.h\"\n\nusing SurgSim::DataStructures::DataGroup;\nusing SurgSim::DataStructures::DataGroupBuilder;\nusing SurgSim::Devices::FilteredDevice;\nusing SurgSim::Testing::MockInputOutput;\n\nTEST(FilteredDeviceTest, ByHand)\n{\n\tauto filteredDevice = std::make_shared(\"device\");\n\tASSERT_FALSE(filteredDevice->initialize());\n\n\tASSERT_ANY_THROW(filteredDevice->setDevice(nullptr));\n\tASSERT_NO_THROW(filteredDevice->setDevice(std::make_shared(\"identity\")));\n\n\tfilteredDevice->addFilter(std::make_shared(\"filter1\"));\n\tfilteredDevice->addFilter(std::make_shared(\"filter2\"));\n\tEXPECT_TRUE(filteredDevice->initialize());\n\tEXPECT_ANY_THROW(filteredDevice->initialize());\n\n\tauto inputOutput = std::make_shared();\n\tEXPECT_TRUE(filteredDevice->addInputConsumer(inputOutput));\n\tEXPECT_TRUE(filteredDevice->removeInputConsumer(inputOutput));\n\n\tEXPECT_TRUE(filteredDevice->setOutputProducer(inputOutput));\n\tEXPECT_TRUE(filteredDevice->hasOutputProducer());\n\tEXPECT_TRUE(filteredDevice->removeOutputProducer(inputOutput));\n\tEXPECT_FALSE(filteredDevice->hasOutputProducer());\n}\n\nTEST(FilteredDeviceTest, Serialization)\n{\n\tauto runtime = std::make_shared(\"config.txt\");\n\tstd::shared_ptr device;\n\tASSERT_NO_THROW(device = SurgSim::Devices::loadDevice(\"FilteredDevice.yaml\"));\n\tASSERT_NE(nullptr, device);\n\tauto typedDevice = std::dynamic_pointer_cast(device);\n\tASSERT_NE(nullptr, typedDevice);\n\n\tauto input = std::make_shared();\n\tASSERT_TRUE(device->addInputConsumer(input));\n\tSurgSim::Math::RigidTransform3d pose;\n\tASSERT_TRUE(input->m_lastReceivedInput.poses().get(SurgSim::DataStructures::Names::POSE, &pose));\n\n\tEigen::AngleAxisd angleAxis;\n\tangleAxis.angle() = 12.3;\n\tangleAxis.axis() = SurgSim::Math::Vector3d(0.5, 0.5, 0.0);\n\tSurgSim::Math::Vector3d translation = SurgSim::Math::Vector3d(7.8, 8.9, 9.0);\n\tSurgSim::Math::RigidTransform3d expectedTransform =\n\t\tSurgSim::Math::makeRigidTransform(SurgSim::Math::Quaterniond(angleAxis), translation);\n\tEXPECT_TRUE(pose.isApprox(expectedTransform));\n\n\tASSERT_NO_THROW(device = SurgSim::Devices::loadDevice(\"BadFilteredDevice.yaml\"));\n\tEXPECT_EQ(nullptr, device);\n}<|endoftext|>"} {"text":"\/*\n* Copyright (c) 2012 Fredrik Mellbin\n*\n* This file is part of VapourSynth.\n*\n* VapourSynth is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n*\n* VapourSynth is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with VapourSynth; if not, write to the Free Software\n* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \n#include \"vscore.h\"\n#include \"cachefilter.h\"\n\nVSCache::CacheAction VSCache::recommendSize() {\n \/\/ fixme, constants pulled out of my ass\n int total = hits + nearMiss + farMiss;\n\n if (total == 0)\n return caClear;\n\n if (total < 30)\n return caNoChange; \/\/ not enough requests to know what to do so keep it this way\n\n if ((float)nearMiss \/ total > 0.2) \/\/ growing the cache would be beneficial\n return caGrow;\n else if ((float)farMiss \/ total > 0.9) \/\/ probably a linear scan, no reason to waste space here\n return caShrink;\n\n return caNoChange; \/\/ probably fine the way it is\n}\n\ninline VSCache::VSCache(int maxSize, int maxHistorySize)\n : maxSize(maxSize), maxHistorySize(maxHistorySize) {\n clear();\n}\n\ninline void VSCache::clear() {\n hash.clear();\n first = NULL;\n last = NULL;\n weakpoint = NULL;\n currentSize = 0;\n historySize = 0;\n clearStats();\n}\n\ninline void VSCache::clearStats() {\n hits = 0;\n nearMiss = 0;\n farMiss = 0;\n}\n\n\ninline PVideoFrame VSCache::object(const int key) const {\n return const_cast(this)->relink(key);\n}\n\n\ninline PVideoFrame VSCache::operator[](const int key) const {\n return object(key);\n}\n\n\ninline bool VSCache::remove(const int key) {\n QHash::iterator i = hash.find(key);\n\n if (QHash::const_iterator(i) == hash.constEnd()) {\n return false;\n } else {\n unlink(*i);\n return true;\n }\n}\n\n\nbool VSCache::insert(const int akey, const PVideoFrame &aobject) {\n Q_ASSERT(aobject);\n Q_ASSERT(akey >= 0);\n remove(akey);\n trim(maxSize - 1, maxHistorySize);\n QHash::iterator i = hash.insert(akey, Node(akey, aobject));\n currentSize++;\n Node *n = &i.value();\n\n if (first)\n first->prevNode = n;\n\n n->nextNode = first;\n first = n;\n\n if (!last)\n last = first;\n\t\n\ttrim(maxSize, maxHistorySize);\n\n return true;\n}\n\n\nvoid VSCache::trim(int max, int maxHistory) {\n \/\/ first adjust the number of cached frames and extra history length\n while (currentSize > max) {\n if (!weakpoint)\n weakpoint = last;\n else\n weakpoint = weakpoint->prevNode;\n\n if (weakpoint)\n weakpoint->frame.clear();\n\n currentSize--;\n historySize++;\n }\n\n \/\/ remove history until the tail is small enough\n while (last && historySize > maxHistory) {\n unlink(*last);\n }\n}\n\n\/\/ cache filter start\n\nclass CacheInstance {\npublic:\n VSCache cache;\n VSNodeRef *clip;\n VSNode *node;\n VSCore *core;\n bool fixedsize;\n CacheInstance(VSNodeRef *clip, VSNode *node, VSCore *core) : cache(20, 20), clip(clip), node(node), core(core), fixedsize(false) { }\n void addCache() { QMutexLocker lock(&core->cacheLock); core->caches.append(node); }\n void removeCache() { QMutexLocker lock(&core->cacheLock); core->caches.removeOne(node); }\n};\n\nstatic void VS_CC cacheInit(VSMap *in, VSMap *out, void **instanceData, VSNode *node, VSCore *core, const VSAPI *vsapi) {\n VSNodeRef *video = vsapi->propGetNode(in, \"clip\", 0, 0);\n CacheInstance *c = new CacheInstance(video, node, core);\n int err;\n int fixed = vsapi->propGetInt(in, \"fixed\", 0, &err);\n\n if (!err)\n c->fixedsize = (bool)fixed;\n\n int size = vsapi->propGetInt(in, \"size\", 0, &err);\n\n if (!err && size > 0)\n c->cache.setMaxFrames(size);\n\n *instanceData = c;\n vsapi->setVideoInfo(vsapi->getVideoInfo(video), 1, node);\n\n c->addCache();\n}\n\nstatic const VSFrameRef *VS_CC cacheGetframe(int n, int activationReason, void **instanceData, void **frameData, VSFrameContext *frameCtx, VSCore *core, const VSAPI *vsapi) {\n CacheInstance *c = (CacheInstance *) * instanceData;\n\n if (activationReason == arInitial) {\n if (n == cCacheTick) {\n if (!c->fixedsize)\n switch (c->cache.recommendSize()) {\n case VSCache::caClear:\n c->cache.clear();\n case VSCache::caNoChange:\n return NULL;\n case VSCache::caGrow:\n c->cache.setMaxFrames(c->cache.getMaxFrames() + 2);\n return NULL;\n case VSCache::caShrink:\n c->cache.setMaxFrames(qMax(c->cache.getMaxFrames() - 1, 1));\n return NULL;\n }\n } else if (n == cNeedMemory) {\n if (!c->fixedsize)\n switch (c->cache.recommendSize()) {\n case VSCache::caClear:\n c->cache.clear();\n return NULL;\n case VSCache::caGrow:\n return NULL;\n case VSCache::caShrink:\n\t\t\t\t\tif (c->cache.getMaxFrames() <= 2)\n\t\t\t\t\t\tc->cache.clear();\n c->cache.setMaxFrames(qMax(c->cache.getMaxFrames() - 2, 1));\n return NULL;\n case VSCache::caNoChange:\n\t\t\t\t\tif (c->cache.getMaxFrames() <= 1)\n\t\t\t\t\t\tc->cache.clear();\n c->cache.setMaxFrames(qMax(c->cache.getMaxFrames() - 1, 1));\n return NULL;\n }\n } else {\n PVideoFrame f(c->cache[n]);\n\n if (f)\n return new VSFrameRef(f);\n\n vsapi->requestFrameFilter(n, c->clip, frameCtx);\n return NULL;\n }\n } else if (activationReason == arAllFramesReady) {\n const VSFrameRef *r = vsapi->getFrameFilter(n, c->clip, frameCtx);\n c->cache.insert(n, r->frame);\n return r;\n }\n\n return NULL;\n}\n\nstatic void VS_CC cacheFree(void *instanceData, VSCore *core, const VSAPI *vsapi) {\n CacheInstance *c = (CacheInstance *)instanceData;\n c->removeCache();\n vsapi->freeNode(c->clip);\n delete c;\n}\n\nstatic QAtomicInt cacheId(1);\n\nstatic void VS_CC createCacheFilter(const VSMap *in, VSMap *out, void *userData, VSCore *core, const VSAPI *vsapi) {\n vsapi->createFilter(in, out, (\"Cache\" + QString::number(cacheId.fetchAndAddAcquire(1))).toUtf8(), cacheInit, cacheGetframe, cacheFree, fmUnordered, nfNoCache, userData, core);\n}\n\nvoid VS_CC cacheInitialize(VSConfigPlugin configFunc, VSRegisterFunction registerFunc, VSPlugin *plugin) {\n registerFunc(\"Cache\", \"clip:clip;size:int:opt;fixed:int:opt;\", &createCacheFilter, NULL, plugin);\n}\nProperly reset cache stats after a decision\/*\n* Copyright (c) 2012 Fredrik Mellbin\n*\n* This file is part of VapourSynth.\n*\n* VapourSynth is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n*\n* VapourSynth is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with VapourSynth; if not, write to the Free Software\n* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \n#include \"vscore.h\"\n#include \"cachefilter.h\"\n\nVSCache::CacheAction VSCache::recommendSize() {\n \/\/ fixme, constants pulled out of my ass\n int total = hits + nearMiss + farMiss;\n\n if (total == 0)\n return caClear;\n\n if (total < 30)\n return caNoChange; \/\/ not enough requests to know what to do so keep it this way\n\n if ((float)nearMiss \/ total > 0.2) { \/\/ growing the cache would be beneficial\n clearStats();\n return caGrow;\n } else if ((float)farMiss \/ total > 0.9) { \/\/ probably a linear scan, no reason to waste space here\n clearStats();\n return caShrink;\n } else {\n clearStats();\n return caNoChange; \/\/ probably fine the way it is\n }\n}\n\ninline VSCache::VSCache(int maxSize, int maxHistorySize)\n : maxSize(maxSize), maxHistorySize(maxHistorySize) {\n clear();\n}\n\ninline void VSCache::clear() {\n hash.clear();\n first = NULL;\n last = NULL;\n weakpoint = NULL;\n currentSize = 0;\n historySize = 0;\n clearStats();\n}\n\ninline void VSCache::clearStats() {\n hits = 0;\n nearMiss = 0;\n farMiss = 0;\n}\n\n\ninline PVideoFrame VSCache::object(const int key) const {\n return const_cast(this)->relink(key);\n}\n\n\ninline PVideoFrame VSCache::operator[](const int key) const {\n return object(key);\n}\n\n\ninline bool VSCache::remove(const int key) {\n QHash::iterator i = hash.find(key);\n\n if (QHash::const_iterator(i) == hash.constEnd()) {\n return false;\n } else {\n unlink(*i);\n return true;\n }\n}\n\n\nbool VSCache::insert(const int akey, const PVideoFrame &aobject) {\n Q_ASSERT(aobject);\n Q_ASSERT(akey >= 0);\n remove(akey);\n trim(maxSize - 1, maxHistorySize);\n QHash::iterator i = hash.insert(akey, Node(akey, aobject));\n currentSize++;\n Node *n = &i.value();\n\n if (first)\n first->prevNode = n;\n\n n->nextNode = first;\n first = n;\n\n if (!last)\n last = first;\n\t\n\ttrim(maxSize, maxHistorySize);\n\n return true;\n}\n\n\nvoid VSCache::trim(int max, int maxHistory) {\n \/\/ first adjust the number of cached frames and extra history length\n while (currentSize > max) {\n if (!weakpoint)\n weakpoint = last;\n else\n weakpoint = weakpoint->prevNode;\n\n if (weakpoint)\n weakpoint->frame.clear();\n\n currentSize--;\n historySize++;\n }\n\n \/\/ remove history until the tail is small enough\n while (last && historySize > maxHistory) {\n unlink(*last);\n }\n}\n\n\/\/ cache filter start\n\nclass CacheInstance {\npublic:\n VSCache cache;\n VSNodeRef *clip;\n VSNode *node;\n VSCore *core;\n bool fixedsize;\n CacheInstance(VSNodeRef *clip, VSNode *node, VSCore *core) : cache(20, 20), clip(clip), node(node), core(core), fixedsize(false) { }\n void addCache() { QMutexLocker lock(&core->cacheLock); core->caches.append(node); }\n void removeCache() { QMutexLocker lock(&core->cacheLock); core->caches.removeOne(node); }\n};\n\nstatic void VS_CC cacheInit(VSMap *in, VSMap *out, void **instanceData, VSNode *node, VSCore *core, const VSAPI *vsapi) {\n VSNodeRef *video = vsapi->propGetNode(in, \"clip\", 0, 0);\n CacheInstance *c = new CacheInstance(video, node, core);\n int err;\n int fixed = vsapi->propGetInt(in, \"fixed\", 0, &err);\n\n if (!err)\n c->fixedsize = (bool)fixed;\n\n int size = vsapi->propGetInt(in, \"size\", 0, &err);\n\n if (!err && size > 0)\n c->cache.setMaxFrames(size);\n\n *instanceData = c;\n vsapi->setVideoInfo(vsapi->getVideoInfo(video), 1, node);\n\n c->addCache();\n}\n\nstatic const VSFrameRef *VS_CC cacheGetframe(int n, int activationReason, void **instanceData, void **frameData, VSFrameContext *frameCtx, VSCore *core, const VSAPI *vsapi) {\n CacheInstance *c = (CacheInstance *) * instanceData;\n\n if (activationReason == arInitial) {\n if (n == cCacheTick) {\n if (!c->fixedsize)\n switch (c->cache.recommendSize()) {\n case VSCache::caClear:\n c->cache.clear();\n case VSCache::caNoChange:\n return NULL;\n case VSCache::caGrow:\n c->cache.setMaxFrames(c->cache.getMaxFrames() + 2);\n return NULL;\n case VSCache::caShrink:\n c->cache.setMaxFrames(qMax(c->cache.getMaxFrames() - 1, 1));\n return NULL;\n }\n } else if (n == cNeedMemory) {\n if (!c->fixedsize)\n switch (c->cache.recommendSize()) {\n case VSCache::caClear:\n c->cache.clear();\n return NULL;\n case VSCache::caGrow:\n return NULL;\n case VSCache::caShrink:\n\t\t\t\t\tif (c->cache.getMaxFrames() <= 2)\n\t\t\t\t\t\tc->cache.clear();\n c->cache.setMaxFrames(qMax(c->cache.getMaxFrames() - 2, 1));\n return NULL;\n case VSCache::caNoChange:\n\t\t\t\t\tif (c->cache.getMaxFrames() <= 1)\n\t\t\t\t\t\tc->cache.clear();\n c->cache.setMaxFrames(qMax(c->cache.getMaxFrames() - 1, 1));\n return NULL;\n }\n } else {\n PVideoFrame f(c->cache[n]);\n\n if (f)\n return new VSFrameRef(f);\n\n vsapi->requestFrameFilter(n, c->clip, frameCtx);\n return NULL;\n }\n } else if (activationReason == arAllFramesReady) {\n const VSFrameRef *r = vsapi->getFrameFilter(n, c->clip, frameCtx);\n c->cache.insert(n, r->frame);\n return r;\n }\n\n return NULL;\n}\n\nstatic void VS_CC cacheFree(void *instanceData, VSCore *core, const VSAPI *vsapi) {\n CacheInstance *c = (CacheInstance *)instanceData;\n c->removeCache();\n vsapi->freeNode(c->clip);\n delete c;\n}\n\nstatic QAtomicInt cacheId(1);\n\nstatic void VS_CC createCacheFilter(const VSMap *in, VSMap *out, void *userData, VSCore *core, const VSAPI *vsapi) {\n vsapi->createFilter(in, out, (\"Cache\" + QString::number(cacheId.fetchAndAddAcquire(1))).toUtf8(), cacheInit, cacheGetframe, cacheFree, fmUnordered, nfNoCache, userData, core);\n}\n\nvoid VS_CC cacheInitialize(VSConfigPlugin configFunc, VSRegisterFunction registerFunc, VSPlugin *plugin) {\n registerFunc(\"Cache\", \"clip:clip;size:int:opt;fixed:int:opt;\", &createCacheFilter, NULL, plugin);\n}\n<|endoftext|>"} {"text":"#include \"include\/geom.h\"\n#include \n\nConstructor::Constructor(MoveListener listener) :\n Scope(listener), angles() {}\n\nConstructor::~Constructor()\n{\n for (auto *a : angles)\n delete a;\n Scope::~Scope();\n}\n\nbool Constructor::contains(const Angle *a) const\n{\n return a != nullptr &&\n std::count_if(angles.begin(), angles.end(), [a](const Angle *p) {return *p == *a; });\n}\n\nvoid Constructor::add(const Angle *a)\n{\n if (!contains(a))\n angles.push_back(a);\n}\n\n#define _make_move(movetype, arg1, arg1type, arg2, arg2type, res, restype) do { \\\n if (res != nullptr) { \\\n Scope::add(res); \\\n Scope::listener(Move(MoveType::movetype, arg1, arg2, res)); \\\n }} while (0)\n\nconst LineSegment *Constructor::join_segment(const Point &a, const Point &b)\n{\n if (!Scope::contains(&a) || !Scope::contains(&b))\n return nullptr;\n\n const LineSegment *res = new LineSegment(a, b);\n Scope::add(res);\n _make_move(straightedge, &a, Point, &b, Point, res, Line);\n return res;\n}\n\nconst Angle *Constructor::join_angle(const Point &end1, const Point &vertex, const Point &end2)\n{\n if (!Scope::contains(&end1) || !Scope::contains(&vertex) || !Scope::contains(&end2))\n return nullptr;\n\n const Angle *res = new Angle(end1, vertex, end2);\n add(res);\n if (!Scope::contains(&res->l1)) {\n Scope::add(&res->l1);\n _make_move(straightedge, &vertex, Point, &end1, Point, &res->l1, Line);\n }\n if (!Scope::contains(&res->l2)) {\n Scope::add(&res->l2);\n _make_move(straightedge, &vertex, Point, &end2, Point, &res->l2, Line);\n }\n return res;\n}\n\n#undef _make_move\n\nconst Line *Constructor::perpendicular(const Line &l, const Point &p)\n{\n const Point *o1, *o2;\n const Circle *c, *c1, *c2;\n const Line &l1 (l); \/\/ ensure containment for line segments\n\n if (!Scope::contains(&p) || !Scope::contains(&l))\n return nullptr;\n\n \/\/ generate two points on the line equidistant from p\n\n o1 = nullptr;\n for (auto *p2 : points)\n if (l1.contains(*p2) && *p2 != p) { o1 = p2; break; }\n assert(o1 != nullptr);\n\n c = join_circle(p, *o1);\n assert(c != nullptr);\n\n auto pair = meet(l1, *c); \/\/ the copy constructor works well with Scope::contains\n o2 = pair.first == o1 ? pair.second : pair.first;\n assert(o2 != nullptr);\n\n \/\/ create circles from o1 to o2 and from o2 to o1\n\n c1 = join_circle(*o1, *o2);\n c2 = join_circle(*o2, *o1);\n assert(c1 != nullptr);\n assert(c2 != nullptr);\n assert(*c1 != *c2); \/\/ o1 and o2 are different\n\n pair = meet(*c1, *c2);\n assert(pair.first != nullptr);\n assert(pair.second != nullptr);\n assert(*pair.first != *pair.second); \/\/ c1 and c2 are different\n\n return join_line(*pair.first, *pair.second);\n\n \/\/ the deletion of all these items are to be handled by ~Scope()\n}\n\nconst Line *Constructor::parallel(const Line &l, const Point &p)\n{\n if (l.contains(p))\n return &l;\n\n auto perp = perpendicular(l, p);\n if (perp == nullptr)\n return nullptr;\n\n return perpendicular(*perp, p);\n}\n\nconst LineSegment *Constructor::translate(const LineSegment &l, const Point &start)\n{\n const Line *par, *diff, *diff1;\n const Point *end;\n const LineSegment *res;\n\n par = parallel(l, start);\n if (par == nullptr) \/\/ l or start isn't added\n return nullptr;\n\n diff = join_line(l.start, start);\n assert(diff != nullptr);\n\n diff1 = parallel(*diff, l.end);\n assert(diff1 != nullptr);\n\n end = meet(*par, *diff1);\n assert(end != nullptr); \/\/ TODO move these assertions to Scope\n\n res = new LineSegment(start, *end);\n Scope::add(res);\n return res;\n}\n\n#define _ratio(l1, l2) ((l1).x_coeff == 0) ? sgn((l1).y_coeff * (l2).y_coeff) : sgn((l1).x_coeff * (l2).x_coeff)\n\nconst Angle *Constructor::translate(const Angle &a, const Point &p)\n{\n const Line *l1 = parallel(a.l1, p),\n *l2 = parallel(a.l2, p);\n \/\/ the sign of the ratio of nonconstant coefficients for l1 and l2\n int r1 = _ratio(a.l1, *l1),\n r2 = _ratio(a.l2, *l2);\n\n const Angle *res = new Angle(*l1, *l2, r1 * a.region1, r2 * a.region2);\n add(res);\n return res;\n}\n\n#undef _ratio\n\nconst Line *Constructor::bisect(const Point &a, const Point &b)\n{\n const Circle *c1 = join_circle(a, b),\n *c2 = join_circle(b, a);\n\n if (c1 == nullptr || c2 == nullptr || c1 == c2)\n return nullptr;\n auto _meet = meet(*c1, *c2);\n assert(_meet.first != nullptr);\n assert(_meet.second != nullptr);\n\n return join_line(*_meet.first, *_meet.second);\n}\n\nconst Line *Constructor::bisect(const LineSegment &l)\n{\n return bisect(l.start, l.end);\n}\n\nconst Line *Constructor::bisect(const Angle &a)\n{\n if (a.l1 == a.l2)\n return &a.l1;\n\n \/\/ find point on l1 other than vertex\n const Point *p1 = nullptr;\n for (auto *p : points)\n if (a.l1.contains(*p) && *p != a.vertex) { p1 = p; break; }\n assert(p1 != nullptr);\n\n \/\/ find point on l2 with same region as p1\n const Circle *c = join_circle(a.vertex, *p1);\n auto _meet = meet(a.l2, *c);\n assert(_meet.first != nullptr);\n assert(_meet.second != nullptr);\n\n const Point *p2 = a.l1.precedes(a.vertex, *p1) == a.l1.precedes(a.vertex, *_meet.first) ? _meet.first : _meet.second;\n return join_line(*p1, *p2);\n}\n\nconst Point *Constructor::midpoint(const Point &a, const Point &b)\n{\n const Line *l1 = join_line(a, b),\n *l2 = bisect(a, b);\n if (l1 == nullptr || l2 == nullptr)\n return nullptr;\n return meet(*l1, *l2);\n}\n\nconst Point *Constructor::midpoint(const LineSegment &a)\n{\n return midpoint(a.start, a.end);\n}\n\nconst Point *Constructor::reflect(const Point &a, const Point &pivot)\n{\n const Line *l = join_line(a, pivot);\n const Circle *c = join_circle(pivot, a);\n auto _meet = meet(*l, *c);\n\n if (_meet.first == nullptr || _meet.second == nullptr)\n return nullptr;\n\n return *_meet.first == a ? _meet.second : _meet.first;\n}\n\nconst Point *Constructor::reflect(const Point &a, const Line &pivot)\n{\n const Line &p (pivot), \/\/ override within_boundary\n *l = perpendicular(p, a);\n\n if (l == nullptr)\n return nullptr;\n const Point *c = meet(p, *l);\n\n if (c == nullptr)\n return nullptr;\n return reflect(a, *c);\n}\n\nconst Line *Constructor::reflect(const Line &a, const Point &pivot)\n{\n const Line &l (a),\n *p = perpendicular(l, pivot);\n\n if (p == nullptr)\n return nullptr;\n const Point *b = reflect(*meet(l, *p), pivot);\n\n if (b == nullptr)\n return nullptr;\n return perpendicular(*p, *b);\n}\n\nconst Line *Constructor::reflect(const Line &a, const Line &pivot)\n{\n \/\/ different cases for a and pivot being parallel or not\n const Point *vertex = meet(a, pivot), *p1 = nullptr;\n\n if (vertex == nullptr) { \/\/ parallel\n \/\/ find point on pivot\n for (auto *p : points)\n if (pivot.contains(*p)) { p1 = p; break; }\n assert(p1 != nullptr);\n\n \/\/ reflect a by p1\n return reflect(a, *p1);\n }\n \/\/ not parallel\n\n \/\/ find point on a\n for (auto *p : points)\n if (a.contains(*p) && *p != *vertex) { p1 = p; break; }\n assert(p1 != nullptr);\n\n \/\/ reflect p1 around pivot\n const Point *p = reflect(*p1, pivot);\n\n if (p == nullptr)\n return nullptr;\n return join_line(*vertex, *p);\n}\n\nconst Line *Constructor::rotate(const Line &l, const Angle &a, const Point &pivot)\n{\n \/\/ find bisector of angle\n const Line *l1 = bisect(a);\n assert(l1 != nullptr);\n\n \/\/ get parallel of bisector at pivot\n l1 = parallel(*l1, pivot);\n assert(l1 != nullptr);\n\n \/\/ reflect line around parallel\n return reflect(l, *l1);\n}\n\nconst LineSegment *Constructor::rotate(const LineSegment &l, const Angle &a)\n{\n \/\/ find bisector of angle\n const Line *l1 = bisect(a);\n if (l1 == nullptr) return nullptr;\n\n \/\/ get parallel of bisector at l.start\n l1 = parallel(*l1, l.start);\n if (l1 == nullptr) return nullptr;\n\n \/\/ reflect end around parallel\n const Point *end = reflect(l.end, *l1);\n if (end == nullptr) return nullptr;\n\n \/\/ connect start and end\n return join_segment(l.start, *end);\n\n \/* Awful previous algorithm:\n \/\/ - Translate l to the vertex of a, call the new segment l1\n const LineSegment *l1 = translate(l, a.vertex);\n\n \/\/ - Draw circle with center l1.start and touching l1.end\n if (l1 == nullptr)\n return nullptr;\n const Circle *c = join_circle(l1->start, l1->end);\n\n \/\/ - Pick the meets p1 and p2 of the circle with a.l1 and a.l2 that lie in a.region1 and a.region2\n auto meet1 = meet(a.l1, *c),\n meet2 = meet(a.l2, *c);\n assert(meet1.second != nullptr);\n assert(meet2.second != nullptr);\n const Point *p1 = a.l1.precedes(a.vertex, *meet1.first) == (a.region1 > 0) ? meet1.first : meet1.second,\n *p2 = a.l2.precedes(a.vertex, *meet2.first) == (a.region2 > 0) ? meet2.first : meet2.second;\n\n \/\/ - Find perpendicular bisector to l1.end and p2\n const Line *l2 = bisect(l1->end, *p2);\n assert(l2 != nullptr);\n\n \/\/ - Reflect p1 around the bisector\n const Point *p = reflect(*p1, *l2);\n assert(p != nullptr);\n\n \/\/ - Connect l1.start with p1 and translate the new line segment back to l.start\n const LineSegment *l3 = join_segment(l1->start, *p);\n assert(l3 != nullptr);\n\n return translate(*l3, l.start);\n *\/\n}\nAdded destructor for Constructor#include \"include\/geom.h\"\n#include \n\nConstructor::Constructor(MoveListener listener) :\n Scope(listener), angles() {}\n\nConstructor::~Constructor()\n{\n for (auto *a : angles)\n delete a;\n}\n\nbool Constructor::contains(const Angle *a) const\n{\n return a != nullptr &&\n std::count_if(angles.begin(), angles.end(), [a](const Angle *p) {return *p == *a; });\n}\n\nvoid Constructor::add(const Angle *a)\n{\n if (!contains(a))\n angles.push_back(a);\n}\n\n#define _make_move(movetype, arg1, arg1type, arg2, arg2type, res, restype) do { \\\n if (res != nullptr) { \\\n Scope::add(res); \\\n Scope::listener(Move(MoveType::movetype, arg1, arg2, res)); \\\n }} while (0)\n\nconst LineSegment *Constructor::join_segment(const Point &a, const Point &b)\n{\n if (!Scope::contains(&a) || !Scope::contains(&b))\n return nullptr;\n\n const LineSegment *res = new LineSegment(a, b);\n Scope::add(res);\n _make_move(straightedge, &a, Point, &b, Point, res, Line);\n return res;\n}\n\nconst Angle *Constructor::join_angle(const Point &end1, const Point &vertex, const Point &end2)\n{\n if (!Scope::contains(&end1) || !Scope::contains(&vertex) || !Scope::contains(&end2))\n return nullptr;\n\n const Angle *res = new Angle(end1, vertex, end2);\n add(res);\n if (!Scope::contains(&res->l1)) {\n Scope::add(&res->l1);\n _make_move(straightedge, &vertex, Point, &end1, Point, &res->l1, Line);\n }\n if (!Scope::contains(&res->l2)) {\n Scope::add(&res->l2);\n _make_move(straightedge, &vertex, Point, &end2, Point, &res->l2, Line);\n }\n return res;\n}\n\n#undef _make_move\n\nconst Line *Constructor::perpendicular(const Line &l, const Point &p)\n{\n const Point *o1, *o2;\n const Circle *c, *c1, *c2;\n const Line &l1 (l); \/\/ ensure containment for line segments\n\n if (!Scope::contains(&p) || !Scope::contains(&l))\n return nullptr;\n\n \/\/ generate two points on the line equidistant from p\n\n o1 = nullptr;\n for (auto *p2 : points)\n if (l1.contains(*p2) && *p2 != p) { o1 = p2; break; }\n assert(o1 != nullptr);\n\n c = join_circle(p, *o1);\n assert(c != nullptr);\n\n auto pair = meet(l1, *c); \/\/ the copy constructor works well with Scope::contains\n o2 = pair.first == o1 ? pair.second : pair.first;\n assert(o2 != nullptr);\n\n \/\/ create circles from o1 to o2 and from o2 to o1\n\n c1 = join_circle(*o1, *o2);\n c2 = join_circle(*o2, *o1);\n assert(c1 != nullptr);\n assert(c2 != nullptr);\n assert(*c1 != *c2); \/\/ o1 and o2 are different\n\n pair = meet(*c1, *c2);\n assert(pair.first != nullptr);\n assert(pair.second != nullptr);\n assert(*pair.first != *pair.second); \/\/ c1 and c2 are different\n\n return join_line(*pair.first, *pair.second);\n\n \/\/ the deletion of all these items are to be handled by ~Scope()\n}\n\nconst Line *Constructor::parallel(const Line &l, const Point &p)\n{\n if (l.contains(p))\n return &l;\n\n auto perp = perpendicular(l, p);\n if (perp == nullptr)\n return nullptr;\n\n return perpendicular(*perp, p);\n}\n\nconst LineSegment *Constructor::translate(const LineSegment &l, const Point &start)\n{\n const Line *par, *diff, *diff1;\n const Point *end;\n const LineSegment *res;\n\n par = parallel(l, start);\n if (par == nullptr) \/\/ l or start isn't added\n return nullptr;\n\n diff = join_line(l.start, start);\n assert(diff != nullptr);\n\n diff1 = parallel(*diff, l.end);\n assert(diff1 != nullptr);\n\n end = meet(*par, *diff1);\n assert(end != nullptr); \/\/ TODO move these assertions to Scope\n\n res = new LineSegment(start, *end);\n Scope::add(res);\n return res;\n}\n\n#define _ratio(l1, l2) ((l1).x_coeff == 0) ? sgn((l1).y_coeff * (l2).y_coeff) : sgn((l1).x_coeff * (l2).x_coeff)\n\nconst Angle *Constructor::translate(const Angle &a, const Point &p)\n{\n const Line *l1 = parallel(a.l1, p),\n *l2 = parallel(a.l2, p);\n \/\/ the sign of the ratio of nonconstant coefficients for l1 and l2\n int r1 = _ratio(a.l1, *l1),\n r2 = _ratio(a.l2, *l2);\n\n const Angle *res = new Angle(*l1, *l2, r1 * a.region1, r2 * a.region2);\n add(res);\n return res;\n}\n\n#undef _ratio\n\nconst Line *Constructor::bisect(const Point &a, const Point &b)\n{\n const Circle *c1 = join_circle(a, b),\n *c2 = join_circle(b, a);\n\n if (c1 == nullptr || c2 == nullptr || c1 == c2)\n return nullptr;\n auto _meet = meet(*c1, *c2);\n assert(_meet.first != nullptr);\n assert(_meet.second != nullptr);\n\n return join_line(*_meet.first, *_meet.second);\n}\n\nconst Line *Constructor::bisect(const LineSegment &l)\n{\n return bisect(l.start, l.end);\n}\n\nconst Line *Constructor::bisect(const Angle &a)\n{\n if (a.l1 == a.l2)\n return &a.l1;\n\n \/\/ find point on l1 other than vertex\n const Point *p1 = nullptr;\n for (auto *p : points)\n if (a.l1.contains(*p) && *p != a.vertex) { p1 = p; break; }\n assert(p1 != nullptr);\n\n \/\/ find point on l2 with same region as p1\n const Circle *c = join_circle(a.vertex, *p1);\n auto _meet = meet(a.l2, *c);\n assert(_meet.first != nullptr);\n assert(_meet.second != nullptr);\n\n const Point *p2 = a.l1.precedes(a.vertex, *p1) == a.l1.precedes(a.vertex, *_meet.first) ? _meet.first : _meet.second;\n return join_line(*p1, *p2);\n}\n\nconst Point *Constructor::midpoint(const Point &a, const Point &b)\n{\n const Line *l1 = join_line(a, b),\n *l2 = bisect(a, b);\n if (l1 == nullptr || l2 == nullptr)\n return nullptr;\n return meet(*l1, *l2);\n}\n\nconst Point *Constructor::midpoint(const LineSegment &a)\n{\n return midpoint(a.start, a.end);\n}\n\nconst Point *Constructor::reflect(const Point &a, const Point &pivot)\n{\n const Line *l = join_line(a, pivot);\n const Circle *c = join_circle(pivot, a);\n auto _meet = meet(*l, *c);\n\n if (_meet.first == nullptr || _meet.second == nullptr)\n return nullptr;\n\n return *_meet.first == a ? _meet.second : _meet.first;\n}\n\nconst Point *Constructor::reflect(const Point &a, const Line &pivot)\n{\n const Line &p (pivot), \/\/ override within_boundary\n *l = perpendicular(p, a);\n\n if (l == nullptr)\n return nullptr;\n const Point *c = meet(p, *l);\n\n if (c == nullptr)\n return nullptr;\n return reflect(a, *c);\n}\n\nconst Line *Constructor::reflect(const Line &a, const Point &pivot)\n{\n const Line &l (a),\n *p = perpendicular(l, pivot);\n\n if (p == nullptr)\n return nullptr;\n const Point *b = reflect(*meet(l, *p), pivot);\n\n if (b == nullptr)\n return nullptr;\n return perpendicular(*p, *b);\n}\n\nconst Line *Constructor::reflect(const Line &a, const Line &pivot)\n{\n \/\/ different cases for a and pivot being parallel or not\n const Point *vertex = meet(a, pivot), *p1 = nullptr;\n\n if (vertex == nullptr) { \/\/ parallel\n \/\/ find point on pivot\n for (auto *p : points)\n if (pivot.contains(*p)) { p1 = p; break; }\n assert(p1 != nullptr);\n\n \/\/ reflect a by p1\n return reflect(a, *p1);\n }\n \/\/ not parallel\n\n \/\/ find point on a\n for (auto *p : points)\n if (a.contains(*p) && *p != *vertex) { p1 = p; break; }\n assert(p1 != nullptr);\n\n \/\/ reflect p1 around pivot\n const Point *p = reflect(*p1, pivot);\n\n if (p == nullptr)\n return nullptr;\n return join_line(*vertex, *p);\n}\n\nconst Line *Constructor::rotate(const Line &l, const Angle &a, const Point &pivot)\n{\n \/\/ find bisector of angle\n const Line *l1 = bisect(a);\n assert(l1 != nullptr);\n\n \/\/ get parallel of bisector at pivot\n l1 = parallel(*l1, pivot);\n assert(l1 != nullptr);\n\n \/\/ reflect line around parallel\n return reflect(l, *l1);\n}\n\nconst LineSegment *Constructor::rotate(const LineSegment &l, const Angle &a)\n{\n \/\/ find bisector of angle\n const Line *l1 = bisect(a);\n if (l1 == nullptr) return nullptr;\n\n \/\/ get parallel of bisector at l.start\n l1 = parallel(*l1, l.start);\n if (l1 == nullptr) return nullptr;\n\n \/\/ reflect end around parallel\n const Point *end = reflect(l.end, *l1);\n if (end == nullptr) return nullptr;\n\n \/\/ connect start and end\n return join_segment(l.start, *end);\n\n \/* Awful previous algorithm:\n \/\/ - Translate l to the vertex of a, call the new segment l1\n const LineSegment *l1 = translate(l, a.vertex);\n\n \/\/ - Draw circle with center l1.start and touching l1.end\n if (l1 == nullptr)\n return nullptr;\n const Circle *c = join_circle(l1->start, l1->end);\n\n \/\/ - Pick the meets p1 and p2 of the circle with a.l1 and a.l2 that lie in a.region1 and a.region2\n auto meet1 = meet(a.l1, *c),\n meet2 = meet(a.l2, *c);\n assert(meet1.second != nullptr);\n assert(meet2.second != nullptr);\n const Point *p1 = a.l1.precedes(a.vertex, *meet1.first) == (a.region1 > 0) ? meet1.first : meet1.second,\n *p2 = a.l2.precedes(a.vertex, *meet2.first) == (a.region2 > 0) ? meet2.first : meet2.second;\n\n \/\/ - Find perpendicular bisector to l1.end and p2\n const Line *l2 = bisect(l1->end, *p2);\n assert(l2 != nullptr);\n\n \/\/ - Reflect p1 around the bisector\n const Point *p = reflect(*p1, *l2);\n assert(p != nullptr);\n\n \/\/ - Connect l1.start with p1 and translate the new line segment back to l.start\n const LineSegment *l3 = join_segment(l1->start, *p);\n assert(l3 != nullptr);\n\n return translate(*l3, l.start);\n *\/\n}\n<|endoftext|>"} {"text":"\/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Microsoft Corporation\n * \n * -=- Robust Distributed System Nucleus (rDSN) -=- \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n# include \n# include \"task_engine.h\"\n# include \n# include \n\n# ifdef _WIN32\n\n# else\n# include \n\n# ifdef __FreeBSD__\n# include \n# endif\n\n# ifdef __APPLE__\n# include \n# endif\n\n# endif\n\n\n# ifdef __TITLE__\n# undef __TITLE__\n# endif\n# define __TITLE__ \"task.worker\"\n\nnamespace dsn {\n\njoin_point task_worker::on_start(\"task_worker::on_start\");\njoin_point task_worker::on_create(\"task_worker::on_create\");\n\ntask_worker::task_worker(task_worker_pool* pool, task_queue* q, int index, task_worker* inner_provider)\n{\n _owner_pool = pool;\n _input_queue = q;\n _index = index;\n _native_tid = ::dsn::utils::get_invalid_tid();\n\n char name[256];\n sprintf(name, \"%5s.%s.%u\", pool->node()->name(), pool->spec().name.c_str(), index);\n _name = std::string(name);\n _is_running = false;\n\n _thread = nullptr;\n}\n\ntask_worker::~task_worker()\n{\n stop();\n}\n\nvoid task_worker::start()\n{ \n if (_is_running)\n return;\n\n _is_running = true;\n\n _thread = new std::thread(std::bind(&task_worker::run_internal, this));\n\n _started.wait();\n}\n\nvoid task_worker::stop()\n{\n if (!_is_running)\n return;\n\n _is_running = false;\n\n _thread->join();\n delete _thread;\n _thread = nullptr;\n\n _is_running = false;\n}\n\nvoid task_worker::set_name()\n{\n# ifdef _WIN32\n\n #ifndef MS_VC_EXCEPTION\n #define MS_VC_EXCEPTION 0x406D1388\n #endif\n\n typedef struct tagTHREADNAME_INFO\n {\n uint32_t dwType; \/\/ Must be 0x1000.\n LPCSTR szName; \/\/ Pointer to name (in user addr space).\n uint32_t dwThreadID; \/\/ Thread ID (-1=caller thread).\n uint32_t dwFlags; \/\/ Reserved for future use, must be zero.\n }THREADNAME_INFO;\n\n THREADNAME_INFO info;\n info.dwType = 0x1000;\n info.szName = name().c_str();\n info.dwThreadID = (uint32_t)-1;\n info.dwFlags = 0;\n\n __try\n {\n ::RaiseException (MS_VC_EXCEPTION, 0, sizeof(info)\/sizeof(uint32_t), (ULONG_PTR*)&info);\n }\n __except(EXCEPTION_CONTINUE_EXECUTION)\n {\n }\n\n# else\n auto thread_name = name()\n # ifdef __linux__\n .substr(0, (16 - 1))\n # endif\n ;\n auto tid = _thread->native_handle();\n int err = 0;\n # ifdef __FreeBSD__\n pthread_set_name_np(tid, thread_name.c_str());\n # elif defined(__linux__)\n err = pthread_setname_np(tid, thread_name.c_str());\n # elif defined(__APPLE__)\n err = pthread_setname_np(thread_name.c_str());\n # endif\n if (err != 0)\n {\n dwarn(\"Fail to set pthread name. ret = %d\", err);\n }\n# endif\n}\n\nvoid task_worker::set_priority(worker_priority_t pri)\n{\n# ifndef _WIN32\n static int policy = SCHED_OTHER;\n static int prio_max =\n #ifdef __linux__\n -20;\n #else\n sched_get_priority_max(policy);\n #endif\n static int prio_min =\n #ifdef __linux__\n 19;\n #else\n sched_get_priority_min(policy);\n #endif\n static int prio_middle = ((prio_min + prio_max + 1) \/ 2);\n#endif\n\n static int g_thread_priority_map[] = \n {\n# ifdef _WIN32\n THREAD_PRIORITY_LOWEST,\n THREAD_PRIORITY_BELOW_NORMAL,\n THREAD_PRIORITY_NORMAL,\n THREAD_PRIORITY_ABOVE_NORMAL,\n THREAD_PRIORITY_HIGHEST\n# else\n prio_min,\n (prio_min + prio_middle) \/ 2,\n prio_middle,\n (prio_middle + prio_max) \/ 2,\n prio_max\n# endif\n };\n\n static_assert(ARRAYSIZE(g_thread_priority_map) == THREAD_xPRIORITY_COUNT,\n \"ARRAYSIZE(g_thread_priority_map) != THREAD_xPRIORITY_COUNT\");\n\n int prio = g_thread_priority_map[static_cast(pri)];\n bool succ = true;\n# if !defined(_WIN32) && !defined(__linux__)\n struct sched_param param;\n memset(¶m, 0, sizeof(struct sched_param));\n param.sched_priority = prio;\n# endif\n\n# ifdef _WIN32\n succ = (::SetThreadPriority(_thread->native_handle(), prio) == TRUE);\n# elif defined(__linux__)\n if ((nice(prio) == -1) && (errno != 0))\n {\n succ = false;\n }\n# else\n succ = (pthread_setschedparam(_thread->native_handle(), policy, ¶m) == 0);\n\/\/# error \"not implemented\"\n# endif\n\n if (!succ)\n {\n dwarn(\"You may need priviledge to set thread priority. errno = %d.\\n\", errno);\n }\n}\n\nvoid task_worker::set_affinity(uint64_t affinity)\n{\n dassert(affinity > 0, \"affinity cannot be 0.\");\n\n int nr_cpu = static_cast(std::thread::hardware_concurrency());\n dassert(affinity <= (((uint64_t)1 << nr_cpu) - 1),\n \"There are %d cpus in total, while setting thread affinity to a nonexistent one.\", nr_cpu);\n\n auto tid = _thread->native_handle();\n int err;\n# ifdef _WIN32\n if (::SetThreadAffinityMask(tid, static_cast(affinity)) == 0)\n {\n err = static_cast::GetLastError();\n }\n# elif defined(__APPLE__)\n thread_affinity_policy_data_t policy;\n policy.affinity_tag = static_cast(affinity);\n err = static_cast(thread_policy_set(\n static_cast(::dsn::utils::get_current_tid()),\n THREAD_AFFINITY_POLICY,\n (thread_policy_t)&policy,\n THREAD_AFFINITY_POLICY_COUNT\n ));\n# else\n # ifdef __FreeBSD__\n # ifndef cpu_set_t\n # define cpu_set_t cpuset_t\n # endif\n # endif\n cpu_set_t cpuset;\n int nr_bits = std::min(nr_cpu, static_cast(sizeof(affinity) * 8));\n\n CPU_ZERO(&cpuset);\n for (int i = 0; i < nr_bits; i++)\n {\n if ((affinity & ((uint64_t)1 << i)) != 0)\n {\n CPU_SET(i, &cpuset);\n }\n }\n err = pthread_setaffinity_np(tid, sizeof(cpuset), &cpuset);\n# endif\n\n if (err != 0)\n {\n dwarn(\"Fail to set thread affinity. err = %d\", err);\n }\n}\n\nvoid task_worker::run_internal()\n{\n while (_thread == nullptr)\n {\n std::this_thread::sleep_for(std::chrono::milliseconds(1));\n }\n\n task::set_current_worker(this);\n \n _native_tid = ::dsn::utils::get_current_tid();\n set_name();\n set_priority(pool_spec().worker_priority);\n \n if (true == pool_spec().worker_share_core)\n {\n if (pool_spec().worker_affinity_mask > 0) \n {\n set_affinity(pool_spec().worker_affinity_mask);\n }\n }\n else\n {\n uint64_t current_mask = pool_spec().worker_affinity_mask;\n for (int i = 0; i < _index; ++i)\n { \n current_mask &= (current_mask - 1);\n if (0 == current_mask)\n {\n current_mask = pool_spec().worker_affinity_mask;\n }\n }\n current_mask -= (current_mask & (current_mask - 1));\n\n set_affinity(current_mask);\n }\n\n _started.notify();\n\n on_start.execute(this);\n\n loop();\n}\n\nvoid task_worker::loop()\n{\n task_queue* q = queue();\n\n \/\/try {\n while (_is_running)\n {\n task_ptr task = q->dequeue();\n if (task != nullptr)\n {\n task->exec_internal();\n }\n }\n \/*}\n catch (std::exception& ex)\n {\n dassert (false, \"%s: unhandled exception '%s'\", name().c_str(), ex.what());\n }*\/\n}\n\nconst threadpool_spec& task_worker::pool_spec() const\n{\n return pool()->spec();\n}\n\n} \/\/ end namespace\nFix a typo.\/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Microsoft Corporation\n * \n * -=- Robust Distributed System Nucleus (rDSN) -=- \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n# include \n# include \"task_engine.h\"\n# include \n# include \n\n# ifdef _WIN32\n\n# else\n# include \n\n# ifdef __FreeBSD__\n# include \n# endif\n\n# ifdef __APPLE__\n# include \n# endif\n\n# endif\n\n\n# ifdef __TITLE__\n# undef __TITLE__\n# endif\n# define __TITLE__ \"task.worker\"\n\nnamespace dsn {\n\njoin_point task_worker::on_start(\"task_worker::on_start\");\njoin_point task_worker::on_create(\"task_worker::on_create\");\n\ntask_worker::task_worker(task_worker_pool* pool, task_queue* q, int index, task_worker* inner_provider)\n{\n _owner_pool = pool;\n _input_queue = q;\n _index = index;\n _native_tid = ::dsn::utils::get_invalid_tid();\n\n char name[256];\n sprintf(name, \"%5s.%s.%u\", pool->node()->name(), pool->spec().name.c_str(), index);\n _name = std::string(name);\n _is_running = false;\n\n _thread = nullptr;\n}\n\ntask_worker::~task_worker()\n{\n stop();\n}\n\nvoid task_worker::start()\n{ \n if (_is_running)\n return;\n\n _is_running = true;\n\n _thread = new std::thread(std::bind(&task_worker::run_internal, this));\n\n _started.wait();\n}\n\nvoid task_worker::stop()\n{\n if (!_is_running)\n return;\n\n _is_running = false;\n\n _thread->join();\n delete _thread;\n _thread = nullptr;\n\n _is_running = false;\n}\n\nvoid task_worker::set_name()\n{\n# ifdef _WIN32\n\n #ifndef MS_VC_EXCEPTION\n #define MS_VC_EXCEPTION 0x406D1388\n #endif\n\n typedef struct tagTHREADNAME_INFO\n {\n uint32_t dwType; \/\/ Must be 0x1000.\n LPCSTR szName; \/\/ Pointer to name (in user addr space).\n uint32_t dwThreadID; \/\/ Thread ID (-1=caller thread).\n uint32_t dwFlags; \/\/ Reserved for future use, must be zero.\n }THREADNAME_INFO;\n\n THREADNAME_INFO info;\n info.dwType = 0x1000;\n info.szName = name().c_str();\n info.dwThreadID = (uint32_t)-1;\n info.dwFlags = 0;\n\n __try\n {\n ::RaiseException (MS_VC_EXCEPTION, 0, sizeof(info)\/sizeof(uint32_t), (ULONG_PTR*)&info);\n }\n __except(EXCEPTION_CONTINUE_EXECUTION)\n {\n }\n\n# else\n auto thread_name = name()\n # ifdef __linux__\n .substr(0, (16 - 1))\n # endif\n ;\n auto tid = _thread->native_handle();\n int err = 0;\n # ifdef __FreeBSD__\n pthread_set_name_np(tid, thread_name.c_str());\n # elif defined(__linux__)\n err = pthread_setname_np(tid, thread_name.c_str());\n # elif defined(__APPLE__)\n err = pthread_setname_np(thread_name.c_str());\n # endif\n if (err != 0)\n {\n dwarn(\"Fail to set pthread name. err = %d\", err);\n }\n# endif\n}\n\nvoid task_worker::set_priority(worker_priority_t pri)\n{\n# ifndef _WIN32\n static int policy = SCHED_OTHER;\n static int prio_max =\n #ifdef __linux__\n -20;\n #else\n sched_get_priority_max(policy);\n #endif\n static int prio_min =\n #ifdef __linux__\n 19;\n #else\n sched_get_priority_min(policy);\n #endif\n static int prio_middle = ((prio_min + prio_max + 1) \/ 2);\n#endif\n\n static int g_thread_priority_map[] = \n {\n# ifdef _WIN32\n THREAD_PRIORITY_LOWEST,\n THREAD_PRIORITY_BELOW_NORMAL,\n THREAD_PRIORITY_NORMAL,\n THREAD_PRIORITY_ABOVE_NORMAL,\n THREAD_PRIORITY_HIGHEST\n# else\n prio_min,\n (prio_min + prio_middle) \/ 2,\n prio_middle,\n (prio_middle + prio_max) \/ 2,\n prio_max\n# endif\n };\n\n static_assert(ARRAYSIZE(g_thread_priority_map) == THREAD_xPRIORITY_COUNT,\n \"ARRAYSIZE(g_thread_priority_map) != THREAD_xPRIORITY_COUNT\");\n\n int prio = g_thread_priority_map[static_cast(pri)];\n bool succ = true;\n# if !defined(_WIN32) && !defined(__linux__)\n struct sched_param param;\n memset(¶m, 0, sizeof(struct sched_param));\n param.sched_priority = prio;\n# endif\n\n# ifdef _WIN32\n succ = (::SetThreadPriority(_thread->native_handle(), prio) == TRUE);\n# elif defined(__linux__)\n if ((nice(prio) == -1) && (errno != 0))\n {\n succ = false;\n }\n# else\n succ = (pthread_setschedparam(_thread->native_handle(), policy, ¶m) == 0);\n\/\/# error \"not implemented\"\n# endif\n\n if (!succ)\n {\n dwarn(\"You may need priviledge to set thread priority. errno = %d.\\n\", errno);\n }\n}\n\nvoid task_worker::set_affinity(uint64_t affinity)\n{\n dassert(affinity > 0, \"affinity cannot be 0.\");\n\n int nr_cpu = static_cast(std::thread::hardware_concurrency());\n dassert(affinity <= (((uint64_t)1 << nr_cpu) - 1),\n \"There are %d cpus in total, while setting thread affinity to a nonexistent one.\", nr_cpu);\n\n auto tid = _thread->native_handle();\n int err;\n# ifdef _WIN32\n if (::SetThreadAffinityMask(tid, static_cast(affinity)) == 0)\n {\n err = static_cast::GetLastError();\n }\n# elif defined(__APPLE__)\n thread_affinity_policy_data_t policy;\n policy.affinity_tag = static_cast(affinity);\n err = static_cast(thread_policy_set(\n static_cast(::dsn::utils::get_current_tid()),\n THREAD_AFFINITY_POLICY,\n (thread_policy_t)&policy,\n THREAD_AFFINITY_POLICY_COUNT\n ));\n# else\n # ifdef __FreeBSD__\n # ifndef cpu_set_t\n # define cpu_set_t cpuset_t\n # endif\n # endif\n cpu_set_t cpuset;\n int nr_bits = std::min(nr_cpu, static_cast(sizeof(affinity) * 8));\n\n CPU_ZERO(&cpuset);\n for (int i = 0; i < nr_bits; i++)\n {\n if ((affinity & ((uint64_t)1 << i)) != 0)\n {\n CPU_SET(i, &cpuset);\n }\n }\n err = pthread_setaffinity_np(tid, sizeof(cpuset), &cpuset);\n# endif\n\n if (err != 0)\n {\n dwarn(\"Fail to set thread affinity. err = %d\", err);\n }\n}\n\nvoid task_worker::run_internal()\n{\n while (_thread == nullptr)\n {\n std::this_thread::sleep_for(std::chrono::milliseconds(1));\n }\n\n task::set_current_worker(this);\n \n _native_tid = ::dsn::utils::get_current_tid();\n set_name();\n set_priority(pool_spec().worker_priority);\n \n if (true == pool_spec().worker_share_core)\n {\n if (pool_spec().worker_affinity_mask > 0) \n {\n set_affinity(pool_spec().worker_affinity_mask);\n }\n }\n else\n {\n uint64_t current_mask = pool_spec().worker_affinity_mask;\n for (int i = 0; i < _index; ++i)\n { \n current_mask &= (current_mask - 1);\n if (0 == current_mask)\n {\n current_mask = pool_spec().worker_affinity_mask;\n }\n }\n current_mask -= (current_mask & (current_mask - 1));\n\n set_affinity(current_mask);\n }\n\n _started.notify();\n\n on_start.execute(this);\n\n loop();\n}\n\nvoid task_worker::loop()\n{\n task_queue* q = queue();\n\n \/\/try {\n while (_is_running)\n {\n task_ptr task = q->dequeue();\n if (task != nullptr)\n {\n task->exec_internal();\n }\n }\n \/*}\n catch (std::exception& ex)\n {\n dassert (false, \"%s: unhandled exception '%s'\", name().c_str(), ex.what());\n }*\/\n}\n\nconst threadpool_spec& task_worker::pool_spec() const\n{\n return pool()->spec();\n}\n\n} \/\/ end namespace\n<|endoftext|>"} {"text":"VariantAnnotateFrequency: fixed indel handling (uses normalized variant notation)<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Steve Reinhardt\n *\/\n\n#ifndef __CPU_SIMPLE_TIMING_HH__\n#define __CPU_SIMPLE_TIMING_HH__\n\n#include \"cpu\/simple\/base.hh\"\n#include \"cpu\/translation.hh\"\n#include \"params\/TimingSimpleCPU.hh\"\n\nclass TimingSimpleCPU : public BaseSimpleCPU\n{\n public:\n\n TimingSimpleCPU(TimingSimpleCPUParams * params);\n virtual ~TimingSimpleCPU();\n\n virtual void init();\n\n public:\n Event *drainEvent;\n\n private:\n\n \/*\n * If an access needs to be broken into fragments, currently at most two,\n * the the following two classes are used as the sender state of the\n * packets so the CPU can keep track of everything. In the main packet\n * sender state, there's an array with a spot for each fragment. If a\n * fragment has already been accepted by the CPU, aka isn't waiting for\n * a retry, it's pointer is NULL. After each fragment has successfully\n * been processed, the \"outstanding\" counter is decremented. Once the\n * count is zero, the entire larger access is complete.\n *\/\n class SplitMainSenderState : public Packet::SenderState\n {\n public:\n int outstanding;\n PacketPtr fragments[2];\n\n int\n getPendingFragment()\n {\n if (fragments[0]) {\n return 0;\n } else if (fragments[1]) {\n return 1;\n } else {\n return -1;\n }\n }\n };\n\n class SplitFragmentSenderState : public Packet::SenderState\n {\n public:\n SplitFragmentSenderState(PacketPtr _bigPkt, int _index) :\n bigPkt(_bigPkt), index(_index)\n {}\n PacketPtr bigPkt;\n int index;\n\n void\n clearFromParent()\n {\n SplitMainSenderState * main_send_state =\n dynamic_cast(bigPkt->senderState);\n main_send_state->fragments[index] = NULL;\n }\n };\n\n class FetchTranslation : public BaseTLB::Translation\n {\n protected:\n TimingSimpleCPU *cpu;\n\n public:\n FetchTranslation(TimingSimpleCPU *_cpu)\n : cpu(_cpu)\n {}\n\n void\n markDelayed()\n {\n assert(cpu->_status == Running);\n cpu->_status = ITBWaitResponse;\n }\n\n void\n finish(Fault fault, RequestPtr req, ThreadContext *tc,\n BaseTLB::Mode mode)\n {\n cpu->sendFetch(fault, req, tc);\n }\n };\n FetchTranslation fetchTranslation;\n\n void sendData(RequestPtr req, uint8_t *data, uint64_t *res, bool read);\n void sendSplitData(RequestPtr req1, RequestPtr req2, RequestPtr req,\n uint8_t *data, bool read);\n\n void translationFault(Fault fault);\n\n void buildPacket(PacketPtr &pkt, RequestPtr req, bool read);\n void buildSplitPacket(PacketPtr &pkt1, PacketPtr &pkt2,\n RequestPtr req1, RequestPtr req2, RequestPtr req,\n uint8_t *data, bool read);\n\n bool handleReadPacket(PacketPtr pkt);\n \/\/ This function always implicitly uses dcache_pkt.\n bool handleWritePacket();\n\n \/**\n * A TimingCPUPort overrides the default behaviour of the\n * recvTiming and recvRetry and implements events for the\n * scheduling of handling of incoming packets in the following\n * cycle.\n *\/\n class TimingCPUPort : public CpuPort\n {\n public:\n\n TimingCPUPort(const std::string& _name, TimingSimpleCPU* _cpu)\n : CpuPort(_name, _cpu), cpu(_cpu), retryEvent(this)\n { }\n\n protected:\n\n \/**\n * Snooping a coherence request, do nothing.\n *\/\n virtual void recvTimingSnoopReq(PacketPtr pkt) { }\n\n TimingSimpleCPU* cpu;\n\n struct TickEvent : public Event\n {\n PacketPtr pkt;\n TimingSimpleCPU *cpu;\n CpuPort *port;\n\n TickEvent(TimingSimpleCPU *_cpu) : pkt(NULL), cpu(_cpu) {}\n const char *description() const { return \"Timing CPU tick\"; }\n void schedule(PacketPtr _pkt, Tick t);\n };\n\n EventWrapper retryEvent;\n };\n\n class IcachePort : public TimingCPUPort\n {\n public:\n\n IcachePort(TimingSimpleCPU *_cpu)\n : TimingCPUPort(_cpu->name() + \"-iport\", _cpu),\n tickEvent(_cpu)\n { }\n\n protected:\n\n virtual bool recvTimingResp(PacketPtr pkt);\n\n virtual void recvRetry();\n\n struct ITickEvent : public TickEvent\n {\n\n ITickEvent(TimingSimpleCPU *_cpu)\n : TickEvent(_cpu) {}\n void process();\n const char *description() const { return \"Timing CPU icache tick\"; }\n };\n\n ITickEvent tickEvent;\n\n };\n\n class DcachePort : public TimingCPUPort\n {\n public:\n\n DcachePort(TimingSimpleCPU *_cpu)\n : TimingCPUPort(_cpu->name() + \"-dport\", _cpu), tickEvent(_cpu)\n { }\n\n protected:\n\n virtual bool recvTimingResp(PacketPtr pkt);\n\n virtual void recvRetry();\n\n struct DTickEvent : public TickEvent\n {\n DTickEvent(TimingSimpleCPU *_cpu)\n : TickEvent(_cpu) {}\n void process();\n const char *description() const { return \"Timing CPU dcache tick\"; }\n };\n\n DTickEvent tickEvent;\n\n };\n\n IcachePort icachePort;\n DcachePort dcachePort;\n\n PacketPtr ifetch_pkt;\n PacketPtr dcache_pkt;\n\n Tick previousTick;\n\n protected:\n\n \/** Return a reference to the data port. *\/\n virtual CpuPort &getDataPort() { return dcachePort; }\n\n \/** Return a reference to the instruction port. *\/\n virtual CpuPort &getInstPort() { return icachePort; }\n\n public:\n\n virtual void serialize(std::ostream &os);\n virtual void unserialize(Checkpoint *cp, const std::string §ion);\n\n virtual unsigned int drain(Event *drain_event);\n virtual void resume();\n\n void switchOut();\n void takeOverFrom(BaseCPU *oldCPU);\n\n virtual void activateContext(ThreadID thread_num, int delay);\n virtual void suspendContext(ThreadID thread_num);\n\n Fault readMem(Addr addr, uint8_t *data, unsigned size, unsigned flags);\n\n Fault writeMem(uint8_t *data, unsigned size,\n Addr addr, unsigned flags, uint64_t *res);\n\n void fetch();\n void sendFetch(Fault fault, RequestPtr req, ThreadContext *tc);\n void completeIfetch(PacketPtr );\n void completeDataAccess(PacketPtr pkt);\n void advanceInst(Fault fault);\n\n \/**\n * Print state of address in memory system via PrintReq (for\n * debugging).\n *\/\n void printAddr(Addr a);\n\n \/**\n * Finish a DTB translation.\n * @param state The DTB translation state.\n *\/\n void finishTranslation(WholeTranslationState *state);\n\n private:\n\n typedef EventWrapper FetchEvent;\n FetchEvent fetchEvent;\n\n struct IprEvent : Event {\n Packet *pkt;\n TimingSimpleCPU *cpu;\n IprEvent(Packet *_pkt, TimingSimpleCPU *_cpu, Tick t);\n virtual void process();\n virtual const char *description() const;\n };\n\n void completeDrain();\n};\n\n#endif \/\/ __CPU_SIMPLE_TIMING_HH__\nTiming CPU: Remove a redundant port pointer\/*\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Steve Reinhardt\n *\/\n\n#ifndef __CPU_SIMPLE_TIMING_HH__\n#define __CPU_SIMPLE_TIMING_HH__\n\n#include \"cpu\/simple\/base.hh\"\n#include \"cpu\/translation.hh\"\n#include \"params\/TimingSimpleCPU.hh\"\n\nclass TimingSimpleCPU : public BaseSimpleCPU\n{\n public:\n\n TimingSimpleCPU(TimingSimpleCPUParams * params);\n virtual ~TimingSimpleCPU();\n\n virtual void init();\n\n public:\n Event *drainEvent;\n\n private:\n\n \/*\n * If an access needs to be broken into fragments, currently at most two,\n * the the following two classes are used as the sender state of the\n * packets so the CPU can keep track of everything. In the main packet\n * sender state, there's an array with a spot for each fragment. If a\n * fragment has already been accepted by the CPU, aka isn't waiting for\n * a retry, it's pointer is NULL. After each fragment has successfully\n * been processed, the \"outstanding\" counter is decremented. Once the\n * count is zero, the entire larger access is complete.\n *\/\n class SplitMainSenderState : public Packet::SenderState\n {\n public:\n int outstanding;\n PacketPtr fragments[2];\n\n int\n getPendingFragment()\n {\n if (fragments[0]) {\n return 0;\n } else if (fragments[1]) {\n return 1;\n } else {\n return -1;\n }\n }\n };\n\n class SplitFragmentSenderState : public Packet::SenderState\n {\n public:\n SplitFragmentSenderState(PacketPtr _bigPkt, int _index) :\n bigPkt(_bigPkt), index(_index)\n {}\n PacketPtr bigPkt;\n int index;\n\n void\n clearFromParent()\n {\n SplitMainSenderState * main_send_state =\n dynamic_cast(bigPkt->senderState);\n main_send_state->fragments[index] = NULL;\n }\n };\n\n class FetchTranslation : public BaseTLB::Translation\n {\n protected:\n TimingSimpleCPU *cpu;\n\n public:\n FetchTranslation(TimingSimpleCPU *_cpu)\n : cpu(_cpu)\n {}\n\n void\n markDelayed()\n {\n assert(cpu->_status == Running);\n cpu->_status = ITBWaitResponse;\n }\n\n void\n finish(Fault fault, RequestPtr req, ThreadContext *tc,\n BaseTLB::Mode mode)\n {\n cpu->sendFetch(fault, req, tc);\n }\n };\n FetchTranslation fetchTranslation;\n\n void sendData(RequestPtr req, uint8_t *data, uint64_t *res, bool read);\n void sendSplitData(RequestPtr req1, RequestPtr req2, RequestPtr req,\n uint8_t *data, bool read);\n\n void translationFault(Fault fault);\n\n void buildPacket(PacketPtr &pkt, RequestPtr req, bool read);\n void buildSplitPacket(PacketPtr &pkt1, PacketPtr &pkt2,\n RequestPtr req1, RequestPtr req2, RequestPtr req,\n uint8_t *data, bool read);\n\n bool handleReadPacket(PacketPtr pkt);\n \/\/ This function always implicitly uses dcache_pkt.\n bool handleWritePacket();\n\n \/**\n * A TimingCPUPort overrides the default behaviour of the\n * recvTiming and recvRetry and implements events for the\n * scheduling of handling of incoming packets in the following\n * cycle.\n *\/\n class TimingCPUPort : public CpuPort\n {\n public:\n\n TimingCPUPort(const std::string& _name, TimingSimpleCPU* _cpu)\n : CpuPort(_name, _cpu), cpu(_cpu), retryEvent(this)\n { }\n\n protected:\n\n \/**\n * Snooping a coherence request, do nothing.\n *\/\n virtual void recvTimingSnoopReq(PacketPtr pkt) { }\n\n TimingSimpleCPU* cpu;\n\n struct TickEvent : public Event\n {\n PacketPtr pkt;\n TimingSimpleCPU *cpu;\n\n TickEvent(TimingSimpleCPU *_cpu) : pkt(NULL), cpu(_cpu) {}\n const char *description() const { return \"Timing CPU tick\"; }\n void schedule(PacketPtr _pkt, Tick t);\n };\n\n EventWrapper retryEvent;\n };\n\n class IcachePort : public TimingCPUPort\n {\n public:\n\n IcachePort(TimingSimpleCPU *_cpu)\n : TimingCPUPort(_cpu->name() + \"-iport\", _cpu),\n tickEvent(_cpu)\n { }\n\n protected:\n\n virtual bool recvTimingResp(PacketPtr pkt);\n\n virtual void recvRetry();\n\n struct ITickEvent : public TickEvent\n {\n\n ITickEvent(TimingSimpleCPU *_cpu)\n : TickEvent(_cpu) {}\n void process();\n const char *description() const { return \"Timing CPU icache tick\"; }\n };\n\n ITickEvent tickEvent;\n\n };\n\n class DcachePort : public TimingCPUPort\n {\n public:\n\n DcachePort(TimingSimpleCPU *_cpu)\n : TimingCPUPort(_cpu->name() + \"-dport\", _cpu), tickEvent(_cpu)\n { }\n\n protected:\n\n virtual bool recvTimingResp(PacketPtr pkt);\n\n virtual void recvRetry();\n\n struct DTickEvent : public TickEvent\n {\n DTickEvent(TimingSimpleCPU *_cpu)\n : TickEvent(_cpu) {}\n void process();\n const char *description() const { return \"Timing CPU dcache tick\"; }\n };\n\n DTickEvent tickEvent;\n\n };\n\n IcachePort icachePort;\n DcachePort dcachePort;\n\n PacketPtr ifetch_pkt;\n PacketPtr dcache_pkt;\n\n Tick previousTick;\n\n protected:\n\n \/** Return a reference to the data port. *\/\n virtual CpuPort &getDataPort() { return dcachePort; }\n\n \/** Return a reference to the instruction port. *\/\n virtual CpuPort &getInstPort() { return icachePort; }\n\n public:\n\n virtual void serialize(std::ostream &os);\n virtual void unserialize(Checkpoint *cp, const std::string §ion);\n\n virtual unsigned int drain(Event *drain_event);\n virtual void resume();\n\n void switchOut();\n void takeOverFrom(BaseCPU *oldCPU);\n\n virtual void activateContext(ThreadID thread_num, int delay);\n virtual void suspendContext(ThreadID thread_num);\n\n Fault readMem(Addr addr, uint8_t *data, unsigned size, unsigned flags);\n\n Fault writeMem(uint8_t *data, unsigned size,\n Addr addr, unsigned flags, uint64_t *res);\n\n void fetch();\n void sendFetch(Fault fault, RequestPtr req, ThreadContext *tc);\n void completeIfetch(PacketPtr );\n void completeDataAccess(PacketPtr pkt);\n void advanceInst(Fault fault);\n\n \/**\n * Print state of address in memory system via PrintReq (for\n * debugging).\n *\/\n void printAddr(Addr a);\n\n \/**\n * Finish a DTB translation.\n * @param state The DTB translation state.\n *\/\n void finishTranslation(WholeTranslationState *state);\n\n private:\n\n typedef EventWrapper FetchEvent;\n FetchEvent fetchEvent;\n\n struct IprEvent : Event {\n Packet *pkt;\n TimingSimpleCPU *cpu;\n IprEvent(Packet *_pkt, TimingSimpleCPU *_cpu, Tick t);\n virtual void process();\n virtual const char *description() const;\n };\n\n void completeDrain();\n};\n\n#endif \/\/ __CPU_SIMPLE_TIMING_HH__\n<|endoftext|>"} {"text":"\/\/\n\/\/ Created by Dawid Drozd aka Gelldur on 7\/19\/16.\n\/\/\n\n#include \"Preferences.h\"\n\n#include\n\n#include \n#include \n\n#include \n#include \n\nPreferences::Preferences(const std::string& databaseName, const std::string& tableName)\n\t\t: TABLE_NAME(tableName)\n\t\t, DATABSE_FILE_NAME(databaseName)\n{\n\tPoco::Data::SQLite::Connector::registerConnector();\n\n\trecreate();\n}\n\nPreferences::~Preferences()\n{\n\t_session->close();\n\tPoco::Data::SQLite::Connector::unregisterConnector();\n}\n\nvoid Preferences::setValue(const std::string& key, const std::string& value)\n{\n\t_cache[key] = value;\n\n\tif (_session == nullptr)\n\t{\n\t\tELOG(\"Session not created\\nNo storage\");\n\t\treturn;\n\t}\n\n\tPoco::Data::Session& session = *_session;\n\n\tPoco::Data::Statement insert(session);\n\tinsert << \"INSERT OR REPLACE INTO \" << TABLE_NAME << \" VALUES(?, ?)\",\n\t\t\tPoco::Data::Keywords::useRef(key),\n\t\t\tPoco::Data::Keywords::useRef(value);\n\tDLOG(\"Preferences: %s\\n(%s)=(%s)\", insert.toString().c_str(), key.c_str(), value.c_str());\n\n\tinsert.execute();\n}\n\nstd::string Preferences::getValue(const std::string& key, const std::string& defaultValue)\n{\n\tauto found = _cache.find(key);\n\tif (found != _cache.end())\n\t{\n\t\treturn found->second;\n\t}\n\n\tif (_session == nullptr)\n\t{\n\t\tELOG(\"Session not created\\nNo storage\");\n\t\t_cache[key] = defaultValue;\n\t\treturn defaultValue;\n\t}\n\n\tstd::string returnedValue = defaultValue;\n\n\tPoco::Data::Session& session = *_session;\n\n\n\t\/\/ a simple query\n\tPoco::Data::Statement select(session);\n\tselect << \"SELECT value FROM \" << TABLE_NAME << \" WHERE key=?\",\n\t\t\tPoco::Data::Keywords::useRef(key),\n\t\t\tPoco::Data::Keywords::into(returnedValue); \/\/ iterate over result set one row at a time\n\n\tDLOG(\"Select: %s\\nkey:%s\", select.toString().c_str(), key.c_str());\n\tselect.execute();\n\n\t_cache[key] = returnedValue;\n\treturn returnedValue;\n}\n\nvoid Preferences::clean()\n{\n\t_cache.clear();\n\tif (_session == nullptr)\n\t{\n\t\tELOG(\"Session not created\\nNo storage\");\n\t\treturn;\n\t}\n\n\t_session->close();\n\n\tif (std::remove(DATABSE_FILE_NAME.c_str()) != 0)\n\t{\n\t\tELOG(\"Can't remove database: %s\", DATABSE_FILE_NAME.c_str());\n\t}\n\trecreate();\n}\n\nvoid Preferences::recreate()\n{\n\t_session = std::make_unique(\"SQLite\", DATABSE_FILE_NAME.c_str());\n\n\tif (_session == nullptr)\n\t{\n\t\tELOG(\"Session not created\\nNo storage\");\n\t\treturn;\n\t}\n\n\tPoco::Data::Session& session = *_session;\n\n\tsession << \"CREATE TABLE IF NOT EXISTS `\" << TABLE_NAME << \"`(\"\n\t\t\t\"`key` TEXT NOT NULL UNIQUE,\"\n\t\t\t\"`value` TEXT,\"\n\t\t\t\"PRIMARY KEY(key)\"\n\t\t\t\");\", Poco::Data::Keywords::now;\n}\nFix NPE\/\/\n\/\/ Created by Dawid Drozd aka Gelldur on 7\/19\/16.\n\/\/\n\n#include \"Preferences.h\"\n\n#include\n\n#include \n#include \n\n#include \n#include \n\nPreferences::Preferences(const std::string& databaseName, const std::string& tableName)\n\t\t: TABLE_NAME(tableName)\n\t\t, DATABSE_FILE_NAME(databaseName)\n{\n\tPoco::Data::SQLite::Connector::registerConnector();\n\n\trecreate();\n}\n\nPreferences::~Preferences()\n{\n\tif (_session != nullptr)\n\t{\n\t\t_session->close();\n\t}\n\tPoco::Data::SQLite::Connector::unregisterConnector();\n}\n\nvoid Preferences::setValue(const std::string& key, const std::string& value)\n{\n\t_cache[key] = value;\n\n\tif (_session == nullptr)\n\t{\n\t\tELOG(\"Session not created\\nNo storage\");\n\t\treturn;\n\t}\n\n\tPoco::Data::Session& session = *_session;\n\n\tPoco::Data::Statement insert(session);\n\tinsert << \"INSERT OR REPLACE INTO \" << TABLE_NAME << \" VALUES(?, ?)\",\n\t\t\tPoco::Data::Keywords::useRef(key),\n\t\t\tPoco::Data::Keywords::useRef(value);\n\tDLOG(\"Preferences: %s\\n(%s)=(%s)\", insert.toString().c_str(), key.c_str(), value.c_str());\n\n\tinsert.execute();\n}\n\nstd::string Preferences::getValue(const std::string& key, const std::string& defaultValue)\n{\n\tauto found = _cache.find(key);\n\tif (found != _cache.end())\n\t{\n\t\treturn found->second;\n\t}\n\n\tif (_session == nullptr)\n\t{\n\t\tELOG(\"Session not created\\nNo storage\");\n\t\t_cache[key] = defaultValue;\n\t\treturn defaultValue;\n\t}\n\n\tstd::string returnedValue = defaultValue;\n\n\tPoco::Data::Session& session = *_session;\n\n\n\t\/\/ a simple query\n\tPoco::Data::Statement select(session);\n\tselect << \"SELECT value FROM \" << TABLE_NAME << \" WHERE key=?\",\n\t\t\tPoco::Data::Keywords::useRef(key),\n\t\t\tPoco::Data::Keywords::into(returnedValue); \/\/ iterate over result set one row at a time\n\n\tDLOG(\"Select: %s\\nkey:%s\", select.toString().c_str(), key.c_str());\n\tselect.execute();\n\n\t_cache[key] = returnedValue;\n\treturn returnedValue;\n}\n\nvoid Preferences::clean()\n{\n\t_cache.clear();\n\tif (_session == nullptr)\n\t{\n\t\tELOG(\"Session not created\\nNo storage\");\n\t\treturn;\n\t}\n\n\t_session->close();\n\n\tif (std::remove(DATABSE_FILE_NAME.c_str()) != 0)\n\t{\n\t\tELOG(\"Can't remove database: %s\", DATABSE_FILE_NAME.c_str());\n\t}\n\trecreate();\n}\n\nvoid Preferences::recreate()\n{\n\t_session = std::make_unique(\"SQLite\", DATABSE_FILE_NAME.c_str());\n\n\tif (_session == nullptr)\n\t{\n\t\tELOG(\"Session not created\\nNo storage\");\n\t\treturn;\n\t}\n\n\tPoco::Data::Session& session = *_session;\n\n\tsession << \"CREATE TABLE IF NOT EXISTS `\" << TABLE_NAME << \"`(\"\n\t\t\t\"`key` TEXT NOT NULL UNIQUE,\"\n\t\t\t\"`value` TEXT,\"\n\t\t\t\"PRIMARY KEY(key)\"\n\t\t\t\");\", Poco::Data::Keywords::now;\n}\n<|endoftext|>"} {"text":"#include \n\n#include \"python_api.h\"\n\nstatic int python_count=0;\n\nPython::Python()\n{\n this->_init(-1, NULL);\n}\n\nPython::Python(int argc, char* argv[])\n{\n this->_init(argc, argv);\n}\n\nvoid Python::_init(int argc, char* argv[])\n{\n python_count++;\n if (python_count == 1) {\n \/\/ This is a hack, so that we can load hermes_common below. Some better\n \/\/ mechanism should be used instead, once we figure out how to do it:\n putenv((char *)\"PYTHONPATH=.:..\/..:..\/..\/..\/python\");\n Py_Initialize();\n if (argc >= 0)\n PySys_SetArgv(argc, argv);\n if (import__hermes_common())\n throw std::runtime_error(\"hermes_common failed to import.\");\n }\n this->_namespace = namespace_create();\n}\n\nPython::~Python()\n{\n \/\/ Free the namespace. This frees all the dictionary items, so if there\n \/\/ are some numpy arrays (or your classes) in the namespace, they will be\n \/\/ deallocated at this time.\n Py_DECREF(this->_namespace);\n\n \/\/ free the interpreter if this was the last instance using it:\n python_count--;\n if (python_count == 0) {\n \/\/ don't finalize python, because the numpy package segfaults when\n \/\/ imported again:\n \/\/Py_Finalize();\n }\n}\n\nvoid Python::print()\n{\n namespace_print(_namespace);\n}\n\nvoid Python::exec(const char *text)\n{\n run_cmd(text, this->_namespace);\n}\n\nvoid Python::push(const char *name, PyObject *o)\n{\n namespace_push(this->_namespace, name, o);\n \/\/ namespace_push() is a regular Cython function and\n \/\/ as such, it increfs the object \"o\" before storing it in the namespace,\n \/\/ but we want to steal the reference, so we decref it here (there is still\n \/\/ at least one reference stored in the dictionary this->_namespace, so\n \/\/ it's safe). This is so that\n \/\/ this->push(\"i\", c2py_int(5));\n \/\/ doesn't leak (c2py_int() creates a python reference and push() destroys\n \/\/ this python reference)\n Py_DECREF(o);\n}\n\nPyObject *Python::pull(const char *name)\n{\n PyObject *tmp = namespace_pull(this->_namespace, name);\n \/\/ namespace_pull() is a regular Cython function and\n \/\/ as such, it increfs the result before returning it, but we only want to\n \/\/ borrow a reference, so we decref it here (there is still at least one\n \/\/ reference stored in the dictionary this->_namespace, so it's safe)\n \/\/ This is so that\n \/\/ int i = py2c_int(this->pull(\"i\"));\n \/\/ doesn't leak (pull() borrows the reference, py2c_int() doesn't do\n \/\/ anything with the reference, so no leak nor segfault happens)\n Py_DECREF(tmp);\n return tmp;\n}\nrefactor setting up PYTHONPATH#include \n\n#include \"python_api.h\"\n#include \"matrix.h\"\n\nstatic int python_count=0;\n\nPython::Python()\n{\n this->_init(-1, NULL);\n}\n\nPython::Python(int argc, char* argv[])\n{\n this->_init(argc, argv);\n}\n\nvoid Python::_init(int argc, char* argv[])\n{\n python_count++;\n if (python_count == 1) {\n char *PYTHONPATH = getenv(\"PYTHONPATH\");\n if (PYTHONPATH == NULL)\n _error(\"internal error in hermes_common: PYTHONPATH not defined\");\n int max_len = 10000;\n char new_path[max_len];\n \/\/ This is a hack, so that we can load hermes_common below. Some better\n \/\/ mechanism should be used instead, once we figure out how to do it:\n int nchars = snprintf(new_path, max_len, \"PYTHONPATH=.:..\/..:..\/..\/..\/python:..\/hermes_common\/:..\/..\/hermes_common\/:%s\", PYTHONPATH);\n if (nchars >= max_len)\n _error(\"internal error in hermes_common: PYTHONPATH too long.\");\n \/\/ We have to make a copy of the string, because new_path[] will get\n \/\/ deallocated:\n putenv(strdup(new_path));\n Py_Initialize();\n if (argc >= 0)\n PySys_SetArgv(argc, argv);\n if (import__hermes_common())\n throw std::runtime_error(\"hermes_common failed to import.\");\n }\n this->_namespace = namespace_create();\n}\n\nPython::~Python()\n{\n \/\/ Free the namespace. This frees all the dictionary items, so if there\n \/\/ are some numpy arrays (or your classes) in the namespace, they will be\n \/\/ deallocated at this time.\n Py_DECREF(this->_namespace);\n\n \/\/ The code below would free the interpreter if this was the last instance\n \/\/ using it. However, it is currently disabled, because the numpy package\n \/\/ segfaults when imported again; also the PYTHONPATH is set only once if\n \/\/ python_count is never decreased (which is what we want).\n \/*python_count--;\n if (python_count == 0) {\n Py_Finalize();\n }\n *\/\n}\n\nvoid Python::print()\n{\n namespace_print(_namespace);\n}\n\nvoid Python::exec(const char *text)\n{\n run_cmd(text, this->_namespace);\n}\n\nvoid Python::push(const char *name, PyObject *o)\n{\n namespace_push(this->_namespace, name, o);\n \/\/ namespace_push() is a regular Cython function and\n \/\/ as such, it increfs the object \"o\" before storing it in the namespace,\n \/\/ but we want to steal the reference, so we decref it here (there is still\n \/\/ at least one reference stored in the dictionary this->_namespace, so\n \/\/ it's safe). This is so that\n \/\/ this->push(\"i\", c2py_int(5));\n \/\/ doesn't leak (c2py_int() creates a python reference and push() destroys\n \/\/ this python reference)\n Py_DECREF(o);\n}\n\nPyObject *Python::pull(const char *name)\n{\n PyObject *tmp = namespace_pull(this->_namespace, name);\n \/\/ namespace_pull() is a regular Cython function and\n \/\/ as such, it increfs the result before returning it, but we only want to\n \/\/ borrow a reference, so we decref it here (there is still at least one\n \/\/ reference stored in the dictionary this->_namespace, so it's safe)\n \/\/ This is so that\n \/\/ int i = py2c_int(this->pull(\"i\"));\n \/\/ doesn't leak (pull() borrows the reference, py2c_int() doesn't do\n \/\/ anything with the reference, so no leak nor segfault happens)\n Py_DECREF(tmp);\n return tmp;\n}\n<|endoftext|>"} {"text":"\/*\n Copyright (c) 2016 Genome Research Ltd.\n\n Author: Jouni Siren \n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*\/\n\n#include \"gcsa.h\"\n\nusing namespace gcsa;\n\n\/\/------------------------------------------------------------------------------\n\nint\nmain(int argc, char** argv)\n{\n if(argc < 3)\n {\n std::cerr << \"usage: query_gcsa base_name patterns\" << std::endl;\n std::cerr << std::endl;\n std::exit(EXIT_SUCCESS);\n }\n\n std::string base_name = argv[1];\n std::string pattern_name = argv[2];\n std::cout << \"GCSA2 query benchmark\" << std::endl;\n std::cout << std::endl;\n printHeader(\"Base name\"); std::cout << base_name << std::endl;\n printHeader(\"Pattern file\"); std::cout << pattern_name << std::endl;\n std::cout << std::endl;\n\n GCSA index;\n std::string gcsa_name = base_name + GCSA::EXTENSION;\n sdsl::load_from_file(index, gcsa_name);\n printHeader(\"GCSA\"); std::cout << inMegabytes(sdsl::size_in_bytes(index)) << \" MB\" << std::endl;\n\n std::vector patterns;\n size_type pattern_total = readRows(pattern_name, patterns, true);\n printHeader(\"Patterns\");\n std::cout << patterns.size() << \" (total \" << inMegabytes(pattern_total) << \" MB)\" << std::endl;\n std::cout << std::endl;\n\n std::vector ranges; ranges.reserve(patterns.size());\n {\n double start = readTimer();\n for(size_type i = 0; i < patterns.size(); i++)\n {\n range_type temp = index.find(patterns[i]);\n if(!Range::empty(temp)) { ranges.push_back(temp); }\n }\n double seconds = readTimer() - start;\n printTime(\"find()\", patterns.size(), seconds);\n printHeader(\"find()\");\n std::cout << \"Found \" << ranges.size() << \" patterns (\"\n << (inMegabytes(pattern_total) \/ seconds) << \" MB\/s)\" << std::endl;\n std::cout << std::endl;\n }\n\n std::vector counts(ranges.size());\n {\n double start = readTimer();\n for(size_type i = 0; i < ranges.size(); i++)\n {\n counts[i] = index.count(ranges[i]);\n }\n double seconds = readTimer() - start;\n printTime(\"count()\", ranges.size(), seconds);\n std::cout << std::endl;\n }\n\n {\n double start = readTimer();\n std::vector results;\n size_type total = 0;\n for(size_type i = 0; i < ranges.size(); i++)\n {\n index.locate(ranges[i], results);\n counts[i] -= results.size();\n total += results.size();\n }\n double seconds = readTimer() - start;\n printTime(\"locate()\", ranges.size(), seconds);\n printHeader(\"locate()\");\n std::cout << \"Found \" << total << \" occurrences (\" <<\n (total \/ seconds) << \" \/ second)\" << std::endl;\n std::cout << std::endl;\n }\n\n bool ok = true;\n for(size_type i = 0; i < counts.size(); i++)\n {\n if(counts[i] != 0) { ok = false; }\n }\n if(!ok)\n {\n std::cout << \"Warning: count() and locate() returned inconsistent results\" << std::endl;\n std::cout << std::endl;\n }\n\n return 0;\n}\n\n\/\/------------------------------------------------------------------------------\nFilter patterns of Ns in the benchmark\/*\n Copyright (c) 2016 Genome Research Ltd.\n\n Author: Jouni Siren \n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*\/\n\n#include \"gcsa.h\"\n\nusing namespace gcsa;\n\n\/\/------------------------------------------------------------------------------\n\nvoid filter(std::vector& patterns);\n\nint\nmain(int argc, char** argv)\n{\n if(argc < 3)\n {\n std::cerr << \"usage: query_gcsa base_name patterns\" << std::endl;\n std::cerr << std::endl;\n std::exit(EXIT_SUCCESS);\n }\n\n std::string base_name = argv[1];\n std::string pattern_name = argv[2];\n std::cout << \"GCSA2 query benchmark\" << std::endl;\n std::cout << std::endl;\n printHeader(\"Base name\"); std::cout << base_name << std::endl;\n printHeader(\"Pattern file\"); std::cout << pattern_name << std::endl;\n std::cout << std::endl;\n\n GCSA index;\n std::string gcsa_name = base_name + GCSA::EXTENSION;\n sdsl::load_from_file(index, gcsa_name);\n printHeader(\"GCSA\"); std::cout << inMegabytes(sdsl::size_in_bytes(index)) << \" MB\" << std::endl;\n\n std::vector patterns;\n size_type pattern_total = readRows(pattern_name, patterns, true);\n filter(patterns);\n printHeader(\"Patterns\");\n std::cout << patterns.size() << \" (total \" << inMegabytes(pattern_total) << \" MB)\" << std::endl;\n std::cout << std::endl;\n\n std::vector ranges; ranges.reserve(patterns.size());\n {\n double start = readTimer();\n for(size_type i = 0; i < patterns.size(); i++)\n {\n range_type temp = index.find(patterns[i]);\n if(!Range::empty(temp)) { ranges.push_back(temp); }\n }\n double seconds = readTimer() - start;\n printTime(\"find()\", patterns.size(), seconds);\n printHeader(\"find()\");\n std::cout << \"Found \" << ranges.size() << \" patterns (\"\n << (inMegabytes(pattern_total) \/ seconds) << \" MB\/s)\" << std::endl;\n std::cout << std::endl;\n }\n\n std::vector counts(ranges.size());\n {\n double start = readTimer();\n for(size_type i = 0; i < ranges.size(); i++)\n {\n counts[i] = index.count(ranges[i]);\n }\n double seconds = readTimer() - start;\n printTime(\"count()\", ranges.size(), seconds);\n std::cout << std::endl;\n }\n\n {\n double start = readTimer();\n std::vector results;\n size_type total = 0;\n for(size_type i = 0; i < ranges.size(); i++)\n {\n index.locate(ranges[i], results);\n counts[i] -= results.size();\n total += results.size();\n }\n double seconds = readTimer() - start;\n printTime(\"locate()\", ranges.size(), seconds);\n printHeader(\"locate()\");\n std::cout << \"Found \" << total << \" occurrences (\" <<\n (total \/ seconds) << \" \/ second)\" << std::endl;\n std::cout << std::endl;\n }\n\n bool ok = true;\n for(size_type i = 0; i < counts.size(); i++)\n {\n if(counts[i] != 0) { ok = false; }\n }\n if(!ok)\n {\n std::cout << \"Warning: count() and locate() returned inconsistent results\" << std::endl;\n std::cout << std::endl;\n }\n\n return 0;\n}\n\n\/\/------------------------------------------------------------------------------\n\nvoid\nfilter(std::vector& patterns)\n{\n size_type tail = 0;\n for(size_type i = 0; i < patterns.size(); i++)\n {\n const std::string& curr = patterns[i];\n for(size_type j = 0; j < curr.length(); j++)\n {\n if(curr[j] != 'N') { patterns[tail] = curr; tail++; break; }\n }\n }\n patterns.resize(tail);\n}\n\n\/\/------------------------------------------------------------------------------\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 Sean McKenna\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\n\/\/ a ray tracer in C++\n\n\n\/\/ libraries, namespace\n#include \n#include \n#include \"xmlload.cpp\"\n#include \"scene.cpp\"\nusing namespace std;\n\n\n\/\/ variables for ray tracing\nint w;\nint h;\nint size;\nColor24 white = {233, 233, 233};\nColor24 black = {33, 33, 33};\nColor24* img;\nfloat* zImg;\n\n\n\/\/ variables for threading\nstatic const int numThreads = 8;\nvoid rayTracing(int i);\n\n\n\/\/ variables for camera ray generation\nvoid cameraRayVars();\nPoint3 *imageTopLeftV;\nPoint3 *dXV;\nPoint3 *dYV;\nPoint3 firstPixel;\nPoint3 cameraPos;\nPoint3 cameraDir;\nTransformation* c;\nPoint3 cameraRay(int pX, int pY);\n\n\n\/\/ trace a ray against all objects\nvoid objectIntersection(Node &n, Ray r, int pixel);\n\n\n\/\/ ray tracer\nint main(){\n \n \/\/ load scene: root node, camera, image\n LoadScene(\"scenes\/prj1.xml\");\n \n \/\/ set up background image color\n renderImage.setBackground(black);\n \n \/\/ variables for ray tracing\n w = renderImage.GetWidth();\n h = renderImage.GetHeight();\n size = w * h; \n img = renderImage.GetPixels();\n zImg = renderImage.GetZBuffer();\n \n \/\/ variables for generating camera rays\n cameraRayVars();\n \n \/\/ ray tracing loop (in parallel with threads)\n std::thread t[numThreads];\n for(int i = 0; i < numThreads; i++)\n t[i] = std::thread(rayTracing, i);\n \n \/\/ join threads back to main\n for(int i = 0; i < numThreads; i++)\n t[i].join();\n \n \/\/ output ray-traced image & z-buffer\n renderImage.SaveImage(\"images\/image.ppm\");\n renderImage.ComputeZBufferImage();\n renderImage.SaveZImage(\"images\/imageZ.ppm\");\n}\n\n\n\/\/ ray tracing loop (for an individual pixel)\nvoid rayTracing(int i){\n \n \/\/ initial starting pixel\n int pixel = i;\n \n \/\/ thread continuation condition\n while(pixel < size){\n \n \/\/ establish pixel location\n int pX = pixel % w;\n int pY = pixel \/ w;\n \n \/\/ transform ray into world space\n Point3 rayDir = cameraRay(pX, pY);\n Ray *ray = new Ray();\n ray->p = cameraPos;\n ray->dir = c->TransformFrom(rayDir);\n \n \/\/ traverse through scene DOM\n \/\/ transform rays into model space\n \/\/ detect ray intersections & update pixel\n objectIntersection(rootNode, *ray, pixel);\n \n \/\/ re-assign next pixel\n pixel += numThreads;\n }\n}\n\n\n\/\/ create variables for camera ray generation\nvoid cameraRayVars(){\n float fov = camera.fov * M_PI \/ 180.0;\n float aspectRatio = (float) w \/ (float) h;\n float imageDistance = 1.0;\n float imageTipY = imageDistance * tan(fov \/ 2.0);\n float imageTipX = imageTipY * aspectRatio;\n float dX = (2.0 * imageTipX) \/ (float) w;\n float dY = (2.0 * imageTipY) \/ (float) h;\n imageTopLeftV = new Point3(-imageTipX, imageTipY, -imageDistance);\n dXV = new Point3(dX, 0.0, 0.0);\n dYV = new Point3(0.0, -dY, 0.0);\n firstPixel = *imageTopLeftV + (*dXV * 0.5) + (*dYV * 0.5);\n \n \/\/ set up camera transformation (translation + rotation)\n Point3 cameraPos = camera.pos;\n c = new Transformation();\n c->Translate(cameraPos);\n Matrix3 *rotate = new cyMatrix3f();\n Point3 cameraDir = camera.dir;\n Point3 cameraUp = camera.up;\n cameraDir.Normalize();\n cameraUp.Normalize();\n Point3 cameraCross = cameraDir ^ cameraUp;\n cameraCross.Normalize();\n rotate->Set(cameraCross, cameraUp, -cameraDir);\n c->Transform(*rotate);\n}\n\n\n\/\/ compute camera rays\nPoint3 cameraRay(int pX, int pY){\n Point3 ray = firstPixel + (*dXV * pX) + (*dYV * pY);\n ray.Normalize();\n return ray;\n}\n\n\n\/\/ recursive object intersection through all scene objects\nvoid objectIntersection(Node &n, Ray r, int pixel){\n \n \/\/ loop on child nodes\n int j = 0;\n int numChild = n.GetNumChild();\n while(j < numChild){\n \n \/\/ grab child node\n Node *child = n.GetChild(j);\n Object *obj = child->GetObject();\n \n \/\/ transform rays into model space (or local space)\n Ray r2 = child->ToNodeCoords(r);\n \n \/\/ compute ray intersections\n HitInfo h = HitInfo();\n bool hit = obj->IntersectRay(r2, h);\n \n \/\/ check the ray computation, update pixel & z-buffer\n if(hit){\n img[pixel] = white;\n if(h.z < zImg[pixel])\n zImg[pixel] = h.z;\n }\n \n \/\/ recursively check this child's children\n objectIntersection(*child, r2, pixel);\n j++;\n }\n}\nrefactor ray-tracer to clean up and better comments\/\/ Copyright 2013 Sean McKenna\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\n\/\/ a ray tracer in C++\n\n\n\/\/ libraries, namespace\n#include \n#include \n#include \"xmlload.cpp\"\n#include \"scene.cpp\"\nusing namespace std;\n\n\n\/\/ for ray tracing\nint w;\nint h;\nint size;\nColor24 white = {233, 233, 233};\nColor24 black = {33, 33, 33};\nColor24* img;\nfloat* zImg;\n\n\n\/\/ for threading\nstatic const int numThreads = 8;\nvoid rayTracing(int i);\n\n\n\/\/ for camera ray generation\nvoid cameraRayVars();\nPoint3 *imageTopLeftV;\nPoint3 *dXV;\nPoint3 *dYV;\nPoint3 firstPixel;\nPoint3 cameraPos;\nPoint3 cameraDir;\nTransformation* c;\nPoint3 cameraRay(int pX, int pY);\n\n\n\/\/ for tracing rays to objects\nvoid objectIntersection(Node &n, Ray r, int pixel);\n\n\n\/\/ ray tracer\nint main(){\n \n \/\/ load scene: root node, camera, image\n LoadScene(\"scenes\/prj1.xml\");\n \n \/\/ set up background image color\n renderImage.setBackground(black);\n \n \/\/ set variables for ray tracing\n w = renderImage.GetWidth();\n h = renderImage.GetHeight();\n size = w * h; \n img = renderImage.GetPixels();\n zImg = renderImage.GetZBuffer();\n \n \/\/ set variables for generating camera rays\n cameraRayVars();\n \n \/\/ start ray tracing loop (in parallel with threads)\n thread t[numThreads];\n for(int i = 0; i < numThreads; i++)\n t[i] = thread(rayTracing, i);\n \n \/\/ when finished, join all threads back to main\n for(int i = 0; i < numThreads; i++)\n t[i].join();\n \n \/\/ output ray-traced image & z-buffer\n renderImage.SaveImage(\"images\/image.ppm\");\n renderImage.ComputeZBufferImage();\n renderImage.SaveZImage(\"images\/imageZ.ppm\");\n}\n\n\n\/\/ ray tracing loop (for an individual pixel)\nvoid rayTracing(int i){\n \n \/\/ initial starting pixel\n int pixel = i;\n \n \/\/ thread continuation condition\n while(pixel < size){\n \n \/\/ establish pixel location\n int pX = pixel % w;\n int pY = pixel \/ w;\n \n \/\/ transform ray into world space\n Point3 rayDir = cameraRay(pX, pY);\n Ray *ray = new Ray();\n ray->p = cameraPos;\n ray->dir = c->TransformFrom(rayDir);\n \n \/\/ traverse through scene DOM\n \/\/ transform rays into model space\n \/\/ detect ray intersections & update pixel\n objectIntersection(rootNode, *ray, pixel);\n \n \/\/ re-assign next pixel (naive, but works)\n pixel += numThreads;\n }\n}\n\n\n\/\/ create variables for camera ray generation\nvoid cameraRayVars(){\n float fov = camera.fov * M_PI \/ 180.0;\n float aspectRatio = (float) w \/ (float) h;\n float imageDistance = 1.0;\n float imageTipY = imageDistance * tan(fov \/ 2.0);\n float imageTipX = imageTipY * aspectRatio;\n float dX = (2.0 * imageTipX) \/ (float) w;\n float dY = (2.0 * imageTipY) \/ (float) h;\n imageTopLeftV = new Point3(-imageTipX, imageTipY, -imageDistance);\n dXV = new Point3(dX, 0.0, 0.0);\n dYV = new Point3(0.0, -dY, 0.0);\n firstPixel = *imageTopLeftV + (*dXV * 0.5) + (*dYV * 0.5);\n \n \/\/ set up camera transformation (translation + rotation)\n Point3 cameraPos = camera.pos;\n c = new Transformation();\n c->Translate(cameraPos);\n Matrix3 *rotate = new cyMatrix3f();\n Point3 cameraDir = camera.dir;\n Point3 cameraUp = camera.up;\n cameraDir.Normalize();\n cameraUp.Normalize();\n Point3 cameraCross = cameraDir ^ cameraUp;\n cameraCross.Normalize();\n rotate->Set(cameraCross, cameraUp, -cameraDir);\n c->Transform(*rotate);\n}\n\n\n\/\/ compute camera rays\nPoint3 cameraRay(int pX, int pY){\n Point3 ray = firstPixel + (*dXV * pX) + (*dYV * pY);\n ray.Normalize();\n return ray;\n}\n\n\n\/\/ recursive object intersection through all scene objects\nvoid objectIntersection(Node &n, Ray r, int pixel){\n \n \/\/ loop on child nodes\n int j = 0;\n int numChild = n.GetNumChild();\n while(j < numChild){\n \n \/\/ grab child node\n Node *child = n.GetChild(j);\n Object *obj = child->GetObject();\n \n \/\/ transform rays into model space (or local space)\n Ray r2 = child->ToNodeCoords(r);\n \n \/\/ compute ray intersections\n HitInfo h = HitInfo();\n bool hit = obj->IntersectRay(r2, h);\n \n \/\/ check the ray computation, update pixel & z-buffer\n if(hit){\n img[pixel] = white;\n if(h.z < zImg[pixel])\n zImg[pixel] = h.z;\n }\n \n \/\/ recursively check this child's children\n objectIntersection(*child, r2, pixel);\n j++;\n }\n}\n<|endoftext|>"} {"text":"\/**@addtogroup Probe Test whether a given port on a host is connectable.\r\n * @{@file\r\n *\r\n * This application attempts to connect to a server and port, and just returns\r\n * the status as a result to the invoker.\r\n *\r\n * @author Nigel Bree \r\n *\r\n * Copyright (C) 2011 Nigel Bree; All Rights Reserved.\r\n * \r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions\r\n * are met:\r\n * \r\n * Redistributions of source code must retain the above copyright notice,\r\n * this list of conditions and the following disclaimer.\r\n * \r\n * Redistributions in binary form must reproduce the above copyright notice,\r\n * this list of conditions and the following disclaimer in the documentation\r\n * and\/or other materials provided with the distribution.\r\n * \r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,INDIRECT, INCIDENTAL,\r\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\r\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\r\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\r\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\/\r\n\r\n#include \r\n#include \r\n\r\n\/**\r\n * Cliche for returning array lengths.\r\n *\/\r\n\r\n#define ARRAY_LENGTH(a) (sizeof (a) \/ sizeof ((a) [0]))\r\n\r\n\/**\r\n * Simple command-line argument extraction, about as unsophisticated as it can\r\n * possibly get.\r\n *\/\r\n\r\nwchar_t * split (wchar_t * args) {\r\n if (args == 0)\r\n return args;\r\n\r\n \/*\r\n * The argument is quoted (which is typical of the first argument, the\r\n * program name, because of the need to avoid problems with spaces in\r\n * the path), in which case we skip to the ending quote first.\r\n *\/\r\n\r\n if (* args == '\"') {\r\n for (;;) {\r\n ++ args;\r\n wchar_t ch = * args;\r\n if (ch == '\"')\r\n break;\r\n\r\n if (ch == 0)\r\n return 0;\r\n }\r\n }\r\n\r\n \/*\r\n * Split at the next space.\r\n *\/\r\n\r\n for (;;) {\r\n wchar_t ch = * args;\r\n if (ch == ' ')\r\n break;\r\n\r\n if (ch == 0)\r\n return 0;\r\n ++ args;\r\n }\r\n\r\n * args = 0;\r\n ++ args;\r\n\r\n \/*\r\n * If there are additional spaces, consume them.\r\n *\/\r\n\r\n while (* args == ' ')\r\n ++ args;\r\n\r\n return args;\r\n}\r\n\r\n\/**\r\n * If we're asked to probe for an NTTP port, then sometimes we have to deal\r\n * with local proxies.\r\n *\r\n * In this case, we actually try and read from the socket to at least get the\r\n * server's initial hello. For the annoying Avast! proxy, that at least does\r\n * not get sent until the real target responds to the proxy, and if the proxy\r\n * connection doesn't work (after 5-6 seconds, since it tries the TLS version\r\n * of the port even if we connected plain-text) then it spits a 400 out.\r\n *\/\r\n\r\nint checkNntp (SOCKET s) {\r\n char buf [128];\r\n int result;\r\n result = recv (s, buf, sizeof (buf), 0);\r\n if (result < 5)\r\n return 1;\r\n\r\n \/*\r\n * Various tedious socket-isms can apply, such as the bytes for the\r\n * initial response code trickling in over time. Let's not worry\r\n * about that, just deal with the basics.\r\n *\/\r\n\r\n void * end = memchr (buf, ' ', result);\r\n if (end == 0)\r\n return 1;\r\n\r\n return memcmp (buf, \"400\", 3) == 0 ? 1 : 0;\r\n}\r\n\r\n\/**\r\n * If we're asked to probe for an HTTP port, then we need to avoid problems\r\n * with local proxies.\r\n *\r\n * Unlike NNTP, the HTTP protocol is client-driven; as it turns out the way the\r\n * crappy Avast! proxy works is that it'll unilaterally close the connection if\r\n * it can't reach the real intended target, but in order to have this work for\r\n * real targets it pays to request a resource. The safest thing to ask for seems\r\n * to be favicon.ico - it's something lots of browsers request anyway and it's\r\n * almost always a small image, so we shouldn't clog up logs with requests for\r\n * 404 resources or get elaborate 404 response pages back.\r\n *\r\n * It turns out that the Avast! proxy has some other exciting misbehaviours; it\r\n * will sometimes (but not always) when a connection fails return an \"HTTP\/1.1\r\n * 200 OK\" status with some fixed bogus fields, one of which is a \"Refresh: 1;\"\r\n * to re-fetch the target URL.\r\n *\/\r\n\r\nint checkHttp (SOCKET s, HANDLE show) {\r\nstatic char head [] = \"HEAD \/favicon.ico HTTP\/1.0\\n\\n\";\r\n int result;\r\n int length = strlen (head);\r\n result = send (s, head, length, 0);\r\n if (result < length)\r\n return 1;\r\n\r\n char buf [1024];\r\n result = recv (s, buf, sizeof (buf) - 1, 0);\r\n\r\n#if 1\r\n \/*\r\n * Show the HTTP response, for debugging. I'll keep this in as long as\r\n * it doesn't cost me any compile-time space.\r\n *\/\r\n\r\n if (result > 0 && show > 0) {\r\n HANDLE err = GetStdHandle (STD_ERROR_HANDLE);\r\n unsigned long written = 0;\r\n WriteFile (err, buf, result, & written, 0);\r\n }\r\n#endif\r\n\r\n \/*\r\n * Normally we wouldn't care what the actual response text was, but to\r\n * deal with the fake response sometimes returned from Avast! I have to\r\n * recognize and suppress it.\r\n *\/\r\n\r\n if (result > 0) {\r\n buf [result] = 0;\r\n if (strstr (buf, \"\\nRefresh: 1;\") != 0)\r\n return 1;\r\n }\r\n\r\n return result < 5 ? 1 : 0;\r\n}\r\n\r\n\/**\r\n * Probe for the indicated port at the given host.\r\n *\/\r\n\r\nint probe (wchar_t * host, wchar_t * port, HANDLE show) {\r\n \/*\r\n * Detect the presence of the Avast! virus scanner; it includes a set\r\n * of proxy-type firewalls that are somewhat tedious to deal with, and\r\n * in the case of NNTP mean that NNTP connections go through their\r\n * proxy; so, our connect will succeed (being locally looped back) and\r\n * send us nothing while the proxy module slowly decides whether it can\r\n * or can't connect to the real target over TLS or plain-text NNTP.\r\n *\r\n * So, if Avast! is present we can choose to either try and read from\r\n * the socket once it connects (so we can get the response code, which\r\n * will generally be 400 once the Avast proxy fails), or we can forget\r\n * the whole probing process because that introduces too much delay.\r\n *\/\r\n\r\n HMODULE avast = GetModuleHandle (L\"snxhk.dll\");\r\n\r\n SOCKET s;\r\n s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);\r\n if (s == SOCKET_ERROR)\r\n return 2;\r\n\r\n sockaddr_in any;\r\n any.sin_family = AF_INET;\r\n any.sin_port = 0;\r\n any.sin_addr.S_un.S_addr = INADDR_ANY;\r\n if (bind (s, (sockaddr *) & any, sizeof (any)) != 0)\r\n return 2;\r\n\r\n \/*\r\n * Look up the hostname and convert the port number into numeric form,\r\n * all handily in one function.\r\n *\/\r\n\r\n ADDRINFOW * address;\r\n if (GetAddrInfoW (host, port, 0, & address) != 0)\r\n return 2;\r\n\r\n \/*\r\n * Ensure that we only connect via IPv4, having made an IPv4 socket\r\n * already (yes, I could do things in a different order, but for my\r\n * purposes here with Steam I care about IPv4 only for now since they\r\n * are IPv4-only).\r\n *\/\r\n\r\n while (address->ai_addr->sa_family != AF_INET)\r\n if ((address = address->ai_next) == 0)\r\n return 2;\r\n\r\n \/*\r\n * Just test whether the port is open or not.\r\n *\/\r\n\r\n int result;\r\n result = connect (s, address->ai_addr, address->ai_addrlen) ? 1 : 0;\r\n\r\n \/*\r\n * Decide whether to actually wait for data, if we're dealing with the\r\n * Avast! proxy being present on a system.\r\n *\/\r\n\r\n sockaddr_in * addr = (sockaddr_in *) address->ai_addr;\r\n switch (htons (addr->sin_port)) {\r\n case 119:\r\n if (avast && result == 0)\r\n result = checkNntp (s);\r\n break;\r\n\r\n case 80:\r\n if (avast && result == 0)\r\n result = checkHttp (s, show);\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n\r\n return result;\r\n}\r\n\r\n#include \r\n#include \r\n#include \"..\/steamfilter\/glob.h\"\r\n\r\n\/*\r\n * As an alternative to probing for a host, do a traceroute and permit glob\r\n * matches against the hostnames.\r\n *\r\n * In principle one could just script a traceroute, but that's a bit slow and\r\n * rather than writing a regex against the output it seems better to have a\r\n * more direct match available.\r\n *\/\r\n\r\nint trace (wchar_t * host, wchar_t * pattern, HANDLE err) {\r\n HANDLE icmp = IcmpCreateFile ();\r\n if (icmp == INVALID_HANDLE_VALUE)\r\n return 2;\r\n\r\n \/*\r\n * Resolve an IPv4 hostname.\r\n *\/\r\n\r\n ADDRINFOW * address;\r\n if (GetAddrInfoW (host, 0, 0, & address) != 0)\r\n return 2;\r\n\r\n \/*\r\n * Ensure that we only connect via IPv4, having made an IPv4 socket\r\n * already (yes, I could do things in a different order, but for my\r\n * purposes here with Steam I care about IPv4 only for now since they\r\n * are IPv4-only).\r\n *\/\r\n\r\n while (address->ai_addr->sa_family != AF_INET)\r\n if ((address = address->ai_next) == 0)\r\n return 2;\r\n\r\n sockaddr_in * addr = (sockaddr_in *) address->ai_addr;\r\n IPAddr dest = addr->sin_addr.s_addr;\r\n\r\n \/*\r\n * The timeouts in this loop are tighter than they are in general kinds\r\n * of traceroute applications since we are generally probing for things\r\n * near to the origin system and with latencies in the <50ms bracket.\r\n *\/\r\n\r\n unsigned short ttl = 1;\r\n for (; ttl < 5 ; ++ ttl) {\r\n unsigned char buf [128];\r\n\r\n \/*\r\n * Part the first; send an echo request.\r\n *\/\r\n\r\n IP_OPTION_INFORMATION info = { ttl };\r\n\r\n DWORD echo;\r\n echo = IcmpSendEcho (icmp, dest, 0, 0, & info, buf, sizeof (buf), 50);\r\n if (echo < 1)\r\n continue;\r\n\r\n \/*\r\n * We expect to see IP_TTL_EXPIRED_TRANSIT since we set the TTL\r\n * to find the intermediate systems.\r\n *\/\r\n\r\n ICMP_ECHO_REPLY * reply = (ICMP_ECHO_REPLY *) buf;\r\n if (reply->Status != IP_TTL_EXPIRED_TRANSIT && reply->Status != 0)\r\n return 1;\r\n\r\n \/* \r\n * Part the second; protocol-independent reverse name lookup.\r\n *\/\r\n\r\n sockaddr_in find = { AF_INET };\r\n find.sin_addr.s_addr = reply->Address;\r\n find.sin_port = 0;\r\n\r\n char name [128];\r\n char port [20];\r\n unsigned long error;\r\n error = getnameinfo ((SOCKADDR *) & find, sizeof (find),\r\n name, ARRAY_LENGTH (name),\r\n 0, 0, NI_NAMEREQD);\r\n\r\n if (error != 0)\r\n continue;\r\n\r\n \/*\r\n * We have a name, now we can glob-match it. If we see the\r\n * desired pattern, we win. If we don't, we bail; the first\r\n * name we resolve wins.\r\n *\/\r\n\r\n return globMatch (name, pattern) ? 0 : 1;\r\n }\r\n\r\n return 1;\r\n}\r\n\r\n\/**\r\n * This is intended as a \"naked\" WinMain without the Visual C++ run-time\r\n * at all (not just avoiding the broken locale machinery).\r\n *\/\r\n\r\nint CALLBACK myWinMain (void) {\r\n HANDLE err = GetStdHandle (STD_ERROR_HANDLE);\r\n unsigned long written = 0;\r\n\r\n \/*\r\n * Since we're not using the regular C machinery, get and split the\r\n * command line by hand. The CommandLineToArgvW () routine would do the\r\n * normal conversion to C style for us, but that depends on SHELL32.DLL\r\n * and we shouldn't need it.\r\n *\/\r\n\r\n wchar_t * base = GetCommandLineW ();\r\n wchar_t * name = split (base);\r\n wchar_t * port = split (name);\r\n wchar_t * extra = split (port);\r\n if (port == 0)\r\n return 2;\r\n WSADATA wsaData;\r\n if (WSAStartup (MAKEWORD (2, 2), & wsaData) != 0)\r\n return 2;\r\n\r\n\r\n int result;\r\n if (wcscmp (port, L\"icmp\") == 0) {\r\n result = trace (name, extra, err);\r\n } else {\r\n result = probe (name, port, err);\r\n }\r\n\r\n if (extra == 0)\r\n ExitProcess (result);\r\n\r\nstatic const char text [] = \"Probe result: \";\r\n WriteFile (err, text, strlen (text), & written, 0);\r\n\r\n char buf [2] = { '0' + result };\r\n WriteFile (err, buf, 1, & written, 0);\r\n\r\n ExitProcess (result);\r\n}\r\nAdd some more polish to the probe utility to prepare for a v0.5.4.0 release\/**@addtogroup Probe Test whether a given port on a host is connectable.\r\n * @{@file\r\n *\r\n * This application attempts to connect to a server and port, and just returns\r\n * the status as a result to the invoker.\r\n *\r\n * @author Nigel Bree \r\n *\r\n * Copyright (C) 2011 Nigel Bree; All Rights Reserved.\r\n * \r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions\r\n * are met:\r\n * \r\n * Redistributions of source code must retain the above copyright notice,\r\n * this list of conditions and the following disclaimer.\r\n * \r\n * Redistributions in binary form must reproduce the above copyright notice,\r\n * this list of conditions and the following disclaimer in the documentation\r\n * and\/or other materials provided with the distribution.\r\n * \r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,INDIRECT, INCIDENTAL,\r\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\r\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\r\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\r\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\/\r\n\r\n#include \r\n#include \r\n\r\n\/**\r\n * Cliche for returning array lengths.\r\n *\/\r\n\r\n#define ARRAY_LENGTH(a) (sizeof (a) \/ sizeof ((a) [0]))\r\n\r\n\/**\r\n * Simple command-line argument extraction, about as unsophisticated as it can\r\n * possibly get.\r\n *\/\r\n\r\nwchar_t * split (wchar_t * args) {\r\n if (args == 0)\r\n return args;\r\n\r\n \/*\r\n * The argument is quoted (which is typical of the first argument, the\r\n * program name, because of the need to avoid problems with spaces in\r\n * the path), in which case we skip to the ending quote first.\r\n *\/\r\n\r\n wchar_t * quoted = 0;\r\n if (* args == '\"') {\r\n quoted = args;\r\n for (;;) {\r\n ++ args;\r\n wchar_t ch = * args;\r\n if (ch == '\"')\r\n break;\r\n\r\n if (ch == 0)\r\n return 0;\r\n }\r\n }\r\n\r\n \/*\r\n * Split at the next space.\r\n *\/\r\n\r\n for (;;) {\r\n wchar_t ch = * args;\r\n if (ch == ' ')\r\n break;\r\n\r\n if (ch == 0)\r\n return 0;\r\n ++ args;\r\n }\r\n\r\n * args = 0;\r\n ++ args;\r\n\r\n \/*\r\n * If the arguments start with quotes, strip the quotes (this isn't a\r\n * completely generic thing to do, but it fits our purposes).\r\n *\/\r\n\r\n if (quoted) {\r\n wchar_t * from = quoted;\r\n wchar_t ch;\r\n while ((ch = * ++ quoted) != '\"')\r\n * from ++ = ch;\r\n\r\n while (ch != 0) {\r\n ch = * ++ quoted;\r\n * from ++ = ch;\r\n }\r\n\r\n * from = ch;\r\n }\r\n\r\n \/*\r\n * If there are additional spaces, consume them.\r\n *\/\r\n\r\n while (* args == ' ')\r\n ++ args;\r\n\r\n return args;\r\n}\r\n\r\n\/**\r\n * If we're asked to probe for an NTTP port, then sometimes we have to deal\r\n * with local proxies.\r\n *\r\n * In this case, we actually try and read from the socket to at least get the\r\n * server's initial hello. For the annoying Avast! proxy, that at least does\r\n * not get sent until the real target responds to the proxy, and if the proxy\r\n * connection doesn't work (after 5-6 seconds, since it tries the TLS version\r\n * of the port even if we connected plain-text) then it spits a 400 out.\r\n *\/\r\n\r\nint checkNntp (SOCKET s) {\r\n char buf [128];\r\n int result;\r\n result = recv (s, buf, sizeof (buf), 0);\r\n if (result < 5)\r\n return 1;\r\n\r\n \/*\r\n * Various tedious socket-isms can apply, such as the bytes for the\r\n * initial response code trickling in over time. Let's not worry\r\n * about that, just deal with the basics.\r\n *\/\r\n\r\n void * end = memchr (buf, ' ', result);\r\n if (end == 0)\r\n return 1;\r\n\r\n return memcmp (buf, \"400\", 3) == 0 ? 1 : 0;\r\n}\r\n\r\n\/**\r\n * If we're asked to probe for an HTTP port, then we need to avoid problems\r\n * with local proxies.\r\n *\r\n * Unlike NNTP, the HTTP protocol is client-driven; as it turns out the way the\r\n * crappy Avast! proxy works is that it'll unilaterally close the connection if\r\n * it can't reach the real intended target, but in order to have this work for\r\n * real targets it pays to request a resource. The safest thing to ask for seems\r\n * to be favicon.ico - it's something lots of browsers request anyway and it's\r\n * almost always a small image, so we shouldn't clog up logs with requests for\r\n * 404 resources or get elaborate 404 response pages back.\r\n *\r\n * It turns out that the Avast! proxy has some other exciting misbehaviours; it\r\n * will sometimes (but not always) when a connection fails return an \"HTTP\/1.1\r\n * 200 OK\" status with some fixed bogus fields, one of which is a \"Refresh: 1;\"\r\n * to re-fetch the target URL.\r\n *\/\r\n\r\nint checkHttp (SOCKET s, HANDLE show) {\r\nstatic char head [] = \"HEAD \/favicon.ico HTTP\/1.0\\n\\n\";\r\n int result;\r\n int length = strlen (head);\r\n result = send (s, head, length, 0);\r\n if (result < length)\r\n return 1;\r\n\r\n char buf [1024];\r\n result = recv (s, buf, sizeof (buf) - 1, 0);\r\n\r\n \/*\r\n * Show the HTTP response, for debugging. I'll keep this in as long as\r\n * it doesn't cost me any compile-time space. I started out aiming to\r\n * keep this around 4kb, and now that the traceroute code is in the\r\n * aim is to keep it below 8kb.\r\n *\/\r\n\r\n if (result > 0 && show > 0) {\r\n unsigned long written = 0;\r\n WriteFile (show, buf, result, & written, 0);\r\n }\r\n\r\n \/*\r\n * Normally we wouldn't care what the actual response text was, but to\r\n * deal with the fake response sometimes returned from Avast! I have to\r\n * recognize and suppress it.\r\n *\/\r\n\r\n if (result > 0) {\r\n buf [result] = 0;\r\n if (strstr (buf, \"\\nRefresh: 1;\") != 0)\r\n return 1;\r\n }\r\n\r\n return result < 5 ? 1 : 0;\r\n}\r\n\r\n\/**\r\n * Probe for the indicated port at the given host.\r\n *\/\r\n\r\nint probe (wchar_t * host, wchar_t * port, HANDLE show) {\r\n \/*\r\n * Detect the presence of the Avast! virus scanner; it includes a set\r\n * of proxy-type firewalls that are somewhat tedious to deal with, and\r\n * in the case of NNTP mean that NNTP connections go through their\r\n * proxy; so, our connect will succeed (being locally looped back) and\r\n * send us nothing while the proxy module slowly decides whether it can\r\n * or can't connect to the real target over TLS or plain-text NNTP.\r\n *\r\n * So, if Avast! is present we can choose to either try and read from\r\n * the socket once it connects (so we can get the response code, which\r\n * will generally be 400 once the Avast proxy fails), or we can forget\r\n * the whole probing process because that introduces too much delay.\r\n *\/\r\n\r\n HMODULE avast = GetModuleHandle (L\"snxhk.dll\");\r\n\r\n SOCKET s;\r\n s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);\r\n if (s == SOCKET_ERROR)\r\n return 2;\r\n\r\n sockaddr_in any;\r\n any.sin_family = AF_INET;\r\n any.sin_port = 0;\r\n any.sin_addr.S_un.S_addr = INADDR_ANY;\r\n if (bind (s, (sockaddr *) & any, sizeof (any)) != 0)\r\n return 2;\r\n\r\n \/*\r\n * Look up the hostname and convert the port number into numeric form,\r\n * all handily in one function.\r\n *\/\r\n\r\n ADDRINFOW * address;\r\n if (GetAddrInfoW (host, port, 0, & address) != 0)\r\n return 2;\r\n\r\n \/*\r\n * Ensure that we only connect via IPv4, having made an IPv4 socket\r\n * already (yes, I could do things in a different order, but for my\r\n * purposes here with Steam I care about IPv4 only for now since they\r\n * are IPv4-only).\r\n *\/\r\n\r\n while (address->ai_addr->sa_family != AF_INET)\r\n if ((address = address->ai_next) == 0)\r\n return 2;\r\n\r\n \/*\r\n * Just test whether the port is open or not.\r\n *\/\r\n\r\n int result;\r\n result = connect (s, address->ai_addr, address->ai_addrlen) ? 1 : 0;\r\n\r\n \/*\r\n * Decide whether to actually wait for data, if we're dealing with the\r\n * Avast! proxy being present on a system.\r\n *\/\r\n\r\n sockaddr_in * addr = (sockaddr_in *) address->ai_addr;\r\n switch (htons (addr->sin_port)) {\r\n case 119:\r\n if (avast && result == 0)\r\n result = checkNntp (s);\r\n break;\r\n\r\n case 80:\r\n if (avast && result == 0)\r\n result = checkHttp (s, show);\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n\r\n return result;\r\n}\r\n\r\n#include \r\n#include \r\n#include \"..\/steamfilter\/glob.h\"\r\n\r\n\/*\r\n * As an alternative to probing for a host, do a traceroute and permit glob\r\n * matches against the hostnames.\r\n *\r\n * In principle one could just script a traceroute, but that's a bit slow and\r\n * rather than writing a regex against the output it seems better to have a\r\n * more direct match available.\r\n *\/\r\n\r\nint trace (wchar_t * host, wchar_t * pattern, HANDLE err) {\r\n HANDLE icmp = IcmpCreateFile ();\r\n if (icmp == INVALID_HANDLE_VALUE)\r\n return 2;\r\n\r\n \/*\r\n * Resolve an IPv4 hostname.\r\n *\/\r\n\r\n ADDRINFOW * address;\r\n if (GetAddrInfoW (host, 0, 0, & address) != 0)\r\n return 2;\r\n\r\n \/*\r\n * Ensure that we only connect via IPv4, having made an IPv4 socket\r\n * already (yes, I could do things in a different order, but for my\r\n * purposes here with Steam I care about IPv4 only for now since they\r\n * are IPv4-only).\r\n *\/\r\n\r\n while (address->ai_addr->sa_family != AF_INET)\r\n if ((address = address->ai_next) == 0)\r\n return 2;\r\n\r\n sockaddr_in * addr = (sockaddr_in *) address->ai_addr;\r\n IPAddr dest = addr->sin_addr.s_addr;\r\n\r\n \/*\r\n * The timeouts in this loop are tighter than they are in general kinds\r\n * of traceroute applications since we are generally probing for things\r\n * near to the origin system and with latencies in the <50ms bracket.\r\n *\r\n * We'll also only use a relatively short TTL for the echo requests as\r\n * we're matching the first host with a DNS name. Also, some ISPs block\r\n * ICMP echo on their Steam servers (e.g. TelstraClear, who also keep\r\n * port 80 firewalled) so there's no point searching too hard since the\r\n * route will stall after only 2 or so hops.\r\n *\/\r\n\r\n unsigned short ttl = 1;\r\n for (; ttl < 8 ; ++ ttl) {\r\n unsigned char buf [128];\r\n\r\n \/*\r\n * Part the first; send an echo request.\r\n *\/\r\n\r\n IP_OPTION_INFORMATION info = { ttl };\r\n\r\n DWORD echo;\r\n echo = IcmpSendEcho (icmp, dest, 0, 0, & info, buf,\r\n sizeof (buf), 50);\r\n if (echo < 1) {\r\n \/*\r\n * Allow one retry, \"just in case\".\r\n *\/\r\n\r\n echo = IcmpSendEcho (icmp, dest, 0, 0, & info, buf,\r\n sizeof (buf), 50);\r\n if (echo < 1)\r\n continue;\r\n }\r\n\r\n \/*\r\n * We expect to see IP_TTL_EXPIRED_TRANSIT since we set the TTL\r\n * to find the intermediate systems.\r\n *\/\r\n\r\n ICMP_ECHO_REPLY * reply = (ICMP_ECHO_REPLY *) buf;\r\n if (reply->Status != IP_TTL_EXPIRED_TRANSIT && reply->Status != 0)\r\n return 1;\r\n\r\n \/* \r\n * Part the second; protocol-independent reverse name lookup.\r\n *\/\r\n\r\n sockaddr_in find = { AF_INET };\r\n find.sin_addr.s_addr = reply->Address;\r\n find.sin_port = 0;\r\n\r\n char name [128];\r\n char port [20];\r\n unsigned long error;\r\n error = getnameinfo ((SOCKADDR *) & find, sizeof (find),\r\n name, ARRAY_LENGTH (name),\r\n 0, 0, NI_NAMEREQD);\r\n\r\n if (error != 0)\r\n continue;\r\n\r\n \/*\r\n * If we're given a handle to write to, print the name we found.\r\n *\/\r\n\r\n unsigned long written = 0;\r\n WriteFile (err, name, strlen (name), & written, 0);\r\n WriteFile (err, \"\\r\\n\", 2, & written, 0);\r\n\r\n \/*\r\n * If the status is 0, then we've hit the target host and that\r\n * means we should stop and return 1.\r\n *\/\r\n\r\n if (reply->Status == 0 || reply->Address == dest)\r\n break;\r\n\r\n \/*\r\n * If the pattern is empty, we're just printing results.\r\n *\/\r\n\r\n if (pattern == 0 || * pattern == 0)\r\n continue;\r\n\r\n \/*\r\n * We have a name, now we can glob-match it. If we see the\r\n * desired pattern, we win. If we don't, we bail; the first\r\n * name we resolve wins.\r\n *\/\r\n\r\n return globMatch (name, pattern) ? 0 : 1;\r\n }\r\n\r\n return 1;\r\n}\r\n\r\n\/**\r\n * This is intended as a \"naked\" WinMain without the Visual C++ run-time\r\n * at all (not just avoiding the broken locale machinery).\r\n *\/\r\n\r\nint CALLBACK myWinMain (void) {\r\n HANDLE err = GetStdHandle (STD_ERROR_HANDLE);\r\n unsigned long written = 0;\r\n\r\n \/*\r\n * Since we're not using the regular C machinery, get and split the\r\n * command line by hand. The CommandLineToArgvW () routine would do the\r\n * normal conversion to C style for us, but that depends on SHELL32.DLL\r\n * and we shouldn't need it.\r\n *\/\r\n\r\n wchar_t * base = GetCommandLineW ();\r\n wchar_t * name = split (base);\r\n wchar_t * port = split (name);\r\n wchar_t * extra = split (port);\r\n if (port == 0)\r\n return 2;\r\n\r\n WSADATA wsaData;\r\n if (WSAStartup (MAKEWORD (2, 2), & wsaData) != 0)\r\n return 2;\r\n\r\n int result;\r\n if (wcscmp (port, L\"icmp\") == 0) {\r\n wchar_t * find = extra;\r\n extra = split (find);\r\n if (find == 0 || * find == 0) {\r\n \/*\r\n * If there is no third argument, just print the names\r\n * of the first few systems we find.\r\n *\/\r\n\r\n find = 0;\r\n } else if (extra == 0)\r\n err = INVALID_HANDLE_VALUE;\r\n\r\n result = trace (name, find, err);\r\n } else {\r\n if (extra == 0)\r\n err = INVALID_HANDLE_VALUE;\r\n\r\n result = probe (name, port, err);\r\n }\r\n\r\n if (extra == 0)\r\n ExitProcess (result);\r\n\r\nstatic const char text [] = \"Probe result: \";\r\n WriteFile (err, text, strlen (text), & written, 0);\r\n\r\n char buf [2] = { '0' + result };\r\n WriteFile (err, buf, 1, & written, 0);\r\n\r\n ExitProcess (result);\r\n}\r\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/gtk\/content_blocked_bubble_gtk.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"base\/i18n\/rtl.h\"\n#include \"chrome\/browser\/blocked_popup_container.h\"\n#include \"chrome\/browser\/content_setting_bubble_model.h\"\n#include \"chrome\/browser\/gtk\/gtk_chrome_link_button.h\"\n#include \"chrome\/browser\/gtk\/gtk_theme_provider.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n#include \"chrome\/browser\/gtk\/options\/content_settings_window_gtk.h\"\n#include \"chrome\/browser\/host_content_settings_map.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/content_settings.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"gfx\/gtk_util.h\"\n#include \"grit\/app_resources.h\"\n#include \"grit\/generated_resources.h\"\n\n\/\/ Padding between content and edge of info bubble.\nstatic const int kContentBorder = 7;\n\nContentSettingBubbleGtk::ContentSettingBubbleGtk(\n GtkWindow* toplevel_window,\n const gfx::Rect& bounds,\n InfoBubbleGtkDelegate* delegate,\n ContentSettingBubbleModel* content_setting_bubble_model,\n Profile* profile,\n TabContents* tab_contents)\n : toplevel_window_(toplevel_window),\n bounds_(bounds),\n profile_(profile),\n tab_contents_(tab_contents),\n delegate_(delegate),\n content_setting_bubble_model_(content_setting_bubble_model),\n info_bubble_(NULL) {\n registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED,\n Source(tab_contents));\n BuildBubble();\n}\n\nContentSettingBubbleGtk::~ContentSettingBubbleGtk() {\n}\n\nvoid ContentSettingBubbleGtk::Close() {\n if (info_bubble_)\n info_bubble_->Close();\n}\n\nvoid ContentSettingBubbleGtk::InfoBubbleClosing(InfoBubbleGtk* info_bubble,\n bool closed_by_escape) {\n delegate_->InfoBubbleClosing(info_bubble, closed_by_escape);\n delete this;\n}\n\nvoid ContentSettingBubbleGtk::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n DCHECK(type == NotificationType::TAB_CONTENTS_DESTROYED);\n DCHECK(source == Source(tab_contents_));\n tab_contents_ = NULL;\n}\n\nvoid ContentSettingBubbleGtk::BuildBubble() {\n GtkThemeProvider* theme_provider = GtkThemeProvider::GetFrom(profile_);\n\n GtkWidget* bubble_content = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);\n gtk_container_set_border_width(GTK_CONTAINER(bubble_content), kContentBorder);\n\n const ContentSettingBubbleModel::BubbleContent& content =\n content_setting_bubble_model_->bubble_content();\n if (!content.title.empty()) {\n \/\/ Add the content label.\n GtkWidget* label = gtk_label_new(content.title.c_str());\n gtk_box_pack_start(GTK_BOX(bubble_content), label, FALSE, FALSE, 0);\n }\n\n if (content_setting_bubble_model_->content_type() ==\n CONTENT_SETTINGS_TYPE_POPUPS) {\n const std::vector& popup_items =\n content.popup_items;\n GtkWidget* table = gtk_table_new(popup_items.size(), 2, FALSE);\n int row = 0;\n for (std::vector::const_iterator\n i(popup_items.begin()); i != popup_items.end(); ++i, ++row) {\n GtkWidget* image = gtk_image_new();\n if (!i->bitmap.empty()) {\n GdkPixbuf* icon_pixbuf = gfx::GdkPixbufFromSkBitmap(&i->bitmap);\n gtk_image_set_from_pixbuf(GTK_IMAGE(image), icon_pixbuf);\n g_object_unref(icon_pixbuf);\n\n \/\/ We stuff the image in an event box so we can trap mouse clicks on the\n \/\/ image (and launch the popup).\n GtkWidget* event_box = gtk_event_box_new();\n gtk_container_add(GTK_CONTAINER(event_box), image);\n\n popup_icons_[event_box] = i -popup_items.begin();\n g_signal_connect(event_box, \"button_press_event\",\n G_CALLBACK(OnPopupIconButtonPress), this);\n gtk_table_attach(GTK_TABLE(table), event_box, 0, 1, row, row + 1,\n GTK_FILL, GTK_FILL, gtk_util::kControlSpacing \/ 2,\n gtk_util::kControlSpacing \/ 2);\n }\n\n GtkWidget* button = gtk_chrome_link_button_new(i->title.c_str());\n popup_links_[button] = i -popup_items.begin();\n g_signal_connect(button, \"clicked\", G_CALLBACK(OnPopupLinkClicked),\n this);\n gtk_table_attach(GTK_TABLE(table), button, 1, 2, row, row + 1,\n GTK_FILL, GTK_FILL, gtk_util::kControlSpacing \/ 2,\n gtk_util::kControlSpacing \/ 2);\n }\n\n gtk_box_pack_start(GTK_BOX(bubble_content), table, FALSE, FALSE, 0);\n }\n\n if (content_setting_bubble_model_->content_type() !=\n CONTENT_SETTINGS_TYPE_COOKIES) {\n const ContentSettingBubbleModel::RadioGroups& radio_groups =\n content.radio_groups;\n for (ContentSettingBubbleModel::RadioGroups::const_iterator i =\n radio_groups.begin(); i != radio_groups.end(); ++i) {\n const ContentSettingBubbleModel::RadioItems& radio_items = i->radio_items;\n RadioGroupGtk radio_group_gtk;\n for (ContentSettingBubbleModel::RadioItems::const_iterator j =\n radio_items.begin(); j != radio_items.end(); ++j) {\n GtkWidget* radio =\n radio_group_gtk.empty() ?\n gtk_radio_button_new_with_label(NULL, j->c_str()) :\n gtk_radio_button_new_with_label_from_widget(\n GTK_RADIO_BUTTON(radio_group_gtk[0]),\n j->c_str());\n gtk_box_pack_start(GTK_BOX(bubble_content), radio, FALSE, FALSE, 0);\n if (j - radio_items.begin() == i->default_item) {\n \/\/ We must set the default value before we attach the signal handlers\n \/\/ or pain occurs.\n gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(radio), TRUE);\n }\n radio_group_gtk.push_back(radio);\n }\n for (std::vector::const_iterator j = radio_group_gtk.begin();\n j != radio_group_gtk.end(); ++j) {\n g_signal_connect(*j, \"toggled\", G_CALLBACK(OnRadioToggled), this);\n }\n radio_groups_gtk_.push_back(radio_group_gtk);\n gtk_box_pack_start(GTK_BOX(bubble_content), gtk_hseparator_new(), FALSE,\n FALSE, 0);\n }\n }\n\n for (std::vector::const_iterator i =\n content.domain_lists.begin();\n i != content.domain_lists.end(); ++i) {\n \/\/ Put each list into its own vbox to allow spacing between lists.\n GtkWidget* list_content = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);\n\n GtkWidget* label = gtk_label_new(i->title.c_str());\n gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);\n GtkWidget* label_box = gtk_hbox_new(FALSE, 0);\n gtk_box_pack_start(GTK_BOX(label_box), label, FALSE, FALSE, 0);\n gtk_box_pack_start(GTK_BOX(list_content), label_box, FALSE, FALSE, 0);\n for (std::set::const_iterator j = i->hosts.begin();\n j != i->hosts.end(); ++j) {\n gtk_box_pack_start(GTK_BOX(list_content),\n gtk_util::IndentWidget(gtk_util::CreateBoldLabel(*j)),\n FALSE, FALSE, 0);\n }\n gtk_box_pack_start(GTK_BOX(bubble_content), list_content, FALSE, FALSE,\n gtk_util::kControlSpacing);\n }\n\n if (!content.clear_link.empty()) {\n GtkWidget* clear_link_box = gtk_hbox_new(FALSE, 0);\n GtkWidget* clear_link = gtk_chrome_link_button_new(\n content.clear_link.c_str());\n g_signal_connect(clear_link, \"clicked\", G_CALLBACK(OnClearLinkClicked),\n this);\n gtk_box_pack_start(GTK_BOX(clear_link_box), clear_link, FALSE, FALSE, 0);\n gtk_box_pack_start(GTK_BOX(bubble_content), clear_link_box,\n FALSE, FALSE, 0);\n gtk_box_pack_start(GTK_BOX(bubble_content), gtk_hseparator_new(),\n FALSE, FALSE, 0);\n }\n\n GtkWidget* bottom_box = gtk_hbox_new(FALSE, 0);\n\n GtkWidget* manage_link =\n gtk_chrome_link_button_new(content.manage_link.c_str());\n g_signal_connect(manage_link, \"clicked\", G_CALLBACK(OnManageLinkClicked),\n this);\n gtk_box_pack_start(GTK_BOX(bottom_box), manage_link, FALSE, FALSE, 0);\n\n GtkWidget* button = gtk_button_new_with_label(\n l10n_util::GetStringUTF8(IDS_DONE).c_str());\n g_signal_connect(button, \"clicked\", G_CALLBACK(OnCloseButtonClicked), this);\n gtk_box_pack_end(GTK_BOX(bottom_box), button, FALSE, FALSE, 0);\n\n gtk_box_pack_start(GTK_BOX(bubble_content), bottom_box, FALSE, FALSE, 0);\n gtk_widget_grab_focus(bottom_box);\n gtk_widget_grab_focus(button);\n\n InfoBubbleGtk::ArrowLocationGtk arrow_location =\n !base::i18n::IsRTL() ?\n InfoBubbleGtk::ARROW_LOCATION_TOP_RIGHT :\n InfoBubbleGtk::ARROW_LOCATION_TOP_LEFT;\n info_bubble_ = InfoBubbleGtk::Show(\n toplevel_window_,\n bounds_,\n bubble_content,\n arrow_location,\n true, \/\/ match_system_theme\n true, \/\/ grab_input\n theme_provider,\n this);\n}\n\n\/\/ static\nvoid ContentSettingBubbleGtk::OnPopupIconButtonPress(\n GtkWidget* icon_event_box,\n GdkEventButton* event,\n ContentSettingBubbleGtk* bubble) {\n PopupMap::iterator i(bubble->popup_icons_.find(icon_event_box));\n DCHECK(i != bubble->popup_icons_.end());\n bubble->content_setting_bubble_model_->OnPopupClicked(i->second);\n \/\/ The views interface implicitly closes because of the launching of a new\n \/\/ window; we need to do that explicitly.\n bubble->Close();\n\n}\n\n\/\/ static\nvoid ContentSettingBubbleGtk::OnPopupLinkClicked(\n GtkWidget* button,\n ContentSettingBubbleGtk* bubble) {\n PopupMap::iterator i(bubble->popup_links_.find(button));\n DCHECK(i != bubble->popup_links_.end());\n bubble->content_setting_bubble_model_->OnPopupClicked(i->second);\n \/\/ The views interface implicitly closes because of the launching of a new\n \/\/ window; we need to do that explicitly.\n bubble->Close();\n}\n\n\/\/ static\nvoid ContentSettingBubbleGtk::OnRadioToggled(\n GtkWidget* widget,\n ContentSettingBubbleGtk* bubble) {\n for (std::vector::const_iterator i =\n bubble->radio_groups_gtk_.begin();\n i != bubble->radio_groups_gtk_.end(); ++i) {\n for (RadioGroupGtk::const_iterator j = i->begin(); j != i->end(); j++) {\n if (widget == *j) {\n bubble->content_setting_bubble_model_->OnRadioClicked(\n i - bubble->radio_groups_gtk_.begin(),\n j - i->begin());\n return;\n }\n }\n }\n NOTREACHED() << \"unknown radio toggled\";\n}\n\n\/\/ static\nvoid ContentSettingBubbleGtk::OnCloseButtonClicked(\n GtkButton *button,\n ContentSettingBubbleGtk* bubble) {\n bubble->Close();\n}\n\n\/\/ static\nvoid ContentSettingBubbleGtk::OnManageLinkClicked(\n GtkButton* button,\n ContentSettingBubbleGtk* bubble) {\n bubble->content_setting_bubble_model_->OnManageLinkClicked();\n bubble->Close();\n}\n\nvoid ContentSettingBubbleGtk::OnClearLinkClicked(\n GtkButton* button,\n ContentSettingBubbleGtk* bubble) {\n bubble->content_setting_bubble_model_->OnClearLinkClicked();\n bubble->Close();\n}\nGTK: Left justify label in content blocking bubble.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/gtk\/content_blocked_bubble_gtk.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"base\/i18n\/rtl.h\"\n#include \"chrome\/browser\/blocked_popup_container.h\"\n#include \"chrome\/browser\/content_setting_bubble_model.h\"\n#include \"chrome\/browser\/gtk\/gtk_chrome_link_button.h\"\n#include \"chrome\/browser\/gtk\/gtk_theme_provider.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n#include \"chrome\/browser\/gtk\/options\/content_settings_window_gtk.h\"\n#include \"chrome\/browser\/host_content_settings_map.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/content_settings.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"gfx\/gtk_util.h\"\n#include \"grit\/app_resources.h\"\n#include \"grit\/generated_resources.h\"\n\n\/\/ Padding between content and edge of info bubble.\nstatic const int kContentBorder = 7;\n\nContentSettingBubbleGtk::ContentSettingBubbleGtk(\n GtkWindow* toplevel_window,\n const gfx::Rect& bounds,\n InfoBubbleGtkDelegate* delegate,\n ContentSettingBubbleModel* content_setting_bubble_model,\n Profile* profile,\n TabContents* tab_contents)\n : toplevel_window_(toplevel_window),\n bounds_(bounds),\n profile_(profile),\n tab_contents_(tab_contents),\n delegate_(delegate),\n content_setting_bubble_model_(content_setting_bubble_model),\n info_bubble_(NULL) {\n registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED,\n Source(tab_contents));\n BuildBubble();\n}\n\nContentSettingBubbleGtk::~ContentSettingBubbleGtk() {\n}\n\nvoid ContentSettingBubbleGtk::Close() {\n if (info_bubble_)\n info_bubble_->Close();\n}\n\nvoid ContentSettingBubbleGtk::InfoBubbleClosing(InfoBubbleGtk* info_bubble,\n bool closed_by_escape) {\n delegate_->InfoBubbleClosing(info_bubble, closed_by_escape);\n delete this;\n}\n\nvoid ContentSettingBubbleGtk::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n DCHECK(type == NotificationType::TAB_CONTENTS_DESTROYED);\n DCHECK(source == Source(tab_contents_));\n tab_contents_ = NULL;\n}\n\nvoid ContentSettingBubbleGtk::BuildBubble() {\n GtkThemeProvider* theme_provider = GtkThemeProvider::GetFrom(profile_);\n\n GtkWidget* bubble_content = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);\n gtk_container_set_border_width(GTK_CONTAINER(bubble_content), kContentBorder);\n\n const ContentSettingBubbleModel::BubbleContent& content =\n content_setting_bubble_model_->bubble_content();\n if (!content.title.empty()) {\n \/\/ Add the content label.\n GtkWidget* label = gtk_label_new(content.title.c_str());\n gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);\n gtk_box_pack_start(GTK_BOX(bubble_content), label, FALSE, FALSE, 0);\n }\n\n if (content_setting_bubble_model_->content_type() ==\n CONTENT_SETTINGS_TYPE_POPUPS) {\n const std::vector& popup_items =\n content.popup_items;\n GtkWidget* table = gtk_table_new(popup_items.size(), 2, FALSE);\n int row = 0;\n for (std::vector::const_iterator\n i(popup_items.begin()); i != popup_items.end(); ++i, ++row) {\n GtkWidget* image = gtk_image_new();\n if (!i->bitmap.empty()) {\n GdkPixbuf* icon_pixbuf = gfx::GdkPixbufFromSkBitmap(&i->bitmap);\n gtk_image_set_from_pixbuf(GTK_IMAGE(image), icon_pixbuf);\n g_object_unref(icon_pixbuf);\n\n \/\/ We stuff the image in an event box so we can trap mouse clicks on the\n \/\/ image (and launch the popup).\n GtkWidget* event_box = gtk_event_box_new();\n gtk_container_add(GTK_CONTAINER(event_box), image);\n\n popup_icons_[event_box] = i -popup_items.begin();\n g_signal_connect(event_box, \"button_press_event\",\n G_CALLBACK(OnPopupIconButtonPress), this);\n gtk_table_attach(GTK_TABLE(table), event_box, 0, 1, row, row + 1,\n GTK_FILL, GTK_FILL, gtk_util::kControlSpacing \/ 2,\n gtk_util::kControlSpacing \/ 2);\n }\n\n GtkWidget* button = gtk_chrome_link_button_new(i->title.c_str());\n popup_links_[button] = i -popup_items.begin();\n g_signal_connect(button, \"clicked\", G_CALLBACK(OnPopupLinkClicked),\n this);\n gtk_table_attach(GTK_TABLE(table), button, 1, 2, row, row + 1,\n GTK_FILL, GTK_FILL, gtk_util::kControlSpacing \/ 2,\n gtk_util::kControlSpacing \/ 2);\n }\n\n gtk_box_pack_start(GTK_BOX(bubble_content), table, FALSE, FALSE, 0);\n }\n\n if (content_setting_bubble_model_->content_type() !=\n CONTENT_SETTINGS_TYPE_COOKIES) {\n const ContentSettingBubbleModel::RadioGroups& radio_groups =\n content.radio_groups;\n for (ContentSettingBubbleModel::RadioGroups::const_iterator i =\n radio_groups.begin(); i != radio_groups.end(); ++i) {\n const ContentSettingBubbleModel::RadioItems& radio_items = i->radio_items;\n RadioGroupGtk radio_group_gtk;\n for (ContentSettingBubbleModel::RadioItems::const_iterator j =\n radio_items.begin(); j != radio_items.end(); ++j) {\n GtkWidget* radio =\n radio_group_gtk.empty() ?\n gtk_radio_button_new_with_label(NULL, j->c_str()) :\n gtk_radio_button_new_with_label_from_widget(\n GTK_RADIO_BUTTON(radio_group_gtk[0]),\n j->c_str());\n gtk_box_pack_start(GTK_BOX(bubble_content), radio, FALSE, FALSE, 0);\n if (j - radio_items.begin() == i->default_item) {\n \/\/ We must set the default value before we attach the signal handlers\n \/\/ or pain occurs.\n gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(radio), TRUE);\n }\n radio_group_gtk.push_back(radio);\n }\n for (std::vector::const_iterator j = radio_group_gtk.begin();\n j != radio_group_gtk.end(); ++j) {\n g_signal_connect(*j, \"toggled\", G_CALLBACK(OnRadioToggled), this);\n }\n radio_groups_gtk_.push_back(radio_group_gtk);\n gtk_box_pack_start(GTK_BOX(bubble_content), gtk_hseparator_new(), FALSE,\n FALSE, 0);\n }\n }\n\n for (std::vector::const_iterator i =\n content.domain_lists.begin();\n i != content.domain_lists.end(); ++i) {\n \/\/ Put each list into its own vbox to allow spacing between lists.\n GtkWidget* list_content = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);\n\n GtkWidget* label = gtk_label_new(i->title.c_str());\n gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);\n GtkWidget* label_box = gtk_hbox_new(FALSE, 0);\n gtk_box_pack_start(GTK_BOX(label_box), label, FALSE, FALSE, 0);\n gtk_box_pack_start(GTK_BOX(list_content), label_box, FALSE, FALSE, 0);\n for (std::set::const_iterator j = i->hosts.begin();\n j != i->hosts.end(); ++j) {\n gtk_box_pack_start(GTK_BOX(list_content),\n gtk_util::IndentWidget(gtk_util::CreateBoldLabel(*j)),\n FALSE, FALSE, 0);\n }\n gtk_box_pack_start(GTK_BOX(bubble_content), list_content, FALSE, FALSE,\n gtk_util::kControlSpacing);\n }\n\n if (!content.clear_link.empty()) {\n GtkWidget* clear_link_box = gtk_hbox_new(FALSE, 0);\n GtkWidget* clear_link = gtk_chrome_link_button_new(\n content.clear_link.c_str());\n g_signal_connect(clear_link, \"clicked\", G_CALLBACK(OnClearLinkClicked),\n this);\n gtk_box_pack_start(GTK_BOX(clear_link_box), clear_link, FALSE, FALSE, 0);\n gtk_box_pack_start(GTK_BOX(bubble_content), clear_link_box,\n FALSE, FALSE, 0);\n gtk_box_pack_start(GTK_BOX(bubble_content), gtk_hseparator_new(),\n FALSE, FALSE, 0);\n }\n\n GtkWidget* bottom_box = gtk_hbox_new(FALSE, 0);\n\n GtkWidget* manage_link =\n gtk_chrome_link_button_new(content.manage_link.c_str());\n g_signal_connect(manage_link, \"clicked\", G_CALLBACK(OnManageLinkClicked),\n this);\n gtk_box_pack_start(GTK_BOX(bottom_box), manage_link, FALSE, FALSE, 0);\n\n GtkWidget* button = gtk_button_new_with_label(\n l10n_util::GetStringUTF8(IDS_DONE).c_str());\n g_signal_connect(button, \"clicked\", G_CALLBACK(OnCloseButtonClicked), this);\n gtk_box_pack_end(GTK_BOX(bottom_box), button, FALSE, FALSE, 0);\n\n gtk_box_pack_start(GTK_BOX(bubble_content), bottom_box, FALSE, FALSE, 0);\n gtk_widget_grab_focus(bottom_box);\n gtk_widget_grab_focus(button);\n\n InfoBubbleGtk::ArrowLocationGtk arrow_location =\n !base::i18n::IsRTL() ?\n InfoBubbleGtk::ARROW_LOCATION_TOP_RIGHT :\n InfoBubbleGtk::ARROW_LOCATION_TOP_LEFT;\n info_bubble_ = InfoBubbleGtk::Show(\n toplevel_window_,\n bounds_,\n bubble_content,\n arrow_location,\n true, \/\/ match_system_theme\n true, \/\/ grab_input\n theme_provider,\n this);\n}\n\n\/\/ static\nvoid ContentSettingBubbleGtk::OnPopupIconButtonPress(\n GtkWidget* icon_event_box,\n GdkEventButton* event,\n ContentSettingBubbleGtk* bubble) {\n PopupMap::iterator i(bubble->popup_icons_.find(icon_event_box));\n DCHECK(i != bubble->popup_icons_.end());\n bubble->content_setting_bubble_model_->OnPopupClicked(i->second);\n \/\/ The views interface implicitly closes because of the launching of a new\n \/\/ window; we need to do that explicitly.\n bubble->Close();\n\n}\n\n\/\/ static\nvoid ContentSettingBubbleGtk::OnPopupLinkClicked(\n GtkWidget* button,\n ContentSettingBubbleGtk* bubble) {\n PopupMap::iterator i(bubble->popup_links_.find(button));\n DCHECK(i != bubble->popup_links_.end());\n bubble->content_setting_bubble_model_->OnPopupClicked(i->second);\n \/\/ The views interface implicitly closes because of the launching of a new\n \/\/ window; we need to do that explicitly.\n bubble->Close();\n}\n\n\/\/ static\nvoid ContentSettingBubbleGtk::OnRadioToggled(\n GtkWidget* widget,\n ContentSettingBubbleGtk* bubble) {\n for (std::vector::const_iterator i =\n bubble->radio_groups_gtk_.begin();\n i != bubble->radio_groups_gtk_.end(); ++i) {\n for (RadioGroupGtk::const_iterator j = i->begin(); j != i->end(); j++) {\n if (widget == *j) {\n bubble->content_setting_bubble_model_->OnRadioClicked(\n i - bubble->radio_groups_gtk_.begin(),\n j - i->begin());\n return;\n }\n }\n }\n NOTREACHED() << \"unknown radio toggled\";\n}\n\n\/\/ static\nvoid ContentSettingBubbleGtk::OnCloseButtonClicked(\n GtkButton *button,\n ContentSettingBubbleGtk* bubble) {\n bubble->Close();\n}\n\n\/\/ static\nvoid ContentSettingBubbleGtk::OnManageLinkClicked(\n GtkButton* button,\n ContentSettingBubbleGtk* bubble) {\n bubble->content_setting_bubble_model_->OnManageLinkClicked();\n bubble->Close();\n}\n\nvoid ContentSettingBubbleGtk::OnClearLinkClicked(\n GtkButton* button,\n ContentSettingBubbleGtk* bubble) {\n bubble->content_setting_bubble_model_->OnClearLinkClicked();\n bubble->Close();\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011-2018 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n\n#include \n\n#include \n\nTransactionDescDialog::TransactionDescDialog(const QModelIndex &idx, QWidget *parent) :\n QDialog(parent),\n ui(new Ui::TransactionDescDialog)\n{\n ui->setupUi(this);\n setWindowTitle(tr(\"Details for %1\").arg(idx.data(TransactionTableModel::TxHashRole).toString()));\n QString desc = idx.data(TransactionTableModel::LongDescriptionRole).toString();\n ui->detailText->setHtml(desc);\n}\n\nTransactionDescDialog::~TransactionDescDialog()\n{\n delete ui;\n}\nPort transaction description dialog\/\/ Copyright (c) 2011-2018 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n\n#include \n#include \n\n#include \n\nTransactionDescDialog::TransactionDescDialog(const QModelIndex &idx, QWidget *parent) :\n QDialog(parent),\n ui(new Ui::TransactionDescDialog)\n{\n ui->setupUi(this);\n\n \/\/ Set stylesheet\n SetObjectStyleSheet(this, StyleSheetNames::ScrollBarDark);\n\n setWindowTitle(tr(\"Details for %1\").arg(idx.data(TransactionTableModel::TxHashRole).toString()));\n QString desc = idx.data(TransactionTableModel::LongDescriptionRole).toString();\n ui->detailText->setHtml(desc);\n}\n\nTransactionDescDialog::~TransactionDescDialog()\n{\n delete ui;\n}\n<|endoftext|>"} {"text":"\/*\n * moneyServerClient2.cpp\n *\n * Created on: 20. 7. 2017\n * Author: ondra\n *\/\n\n\n\n\n#include \"moneyServerClient2.h\"\n\n#include \n#include \n\n#include \"..\/common\/runtime_error.h\"\n\n#include \"error.h\"\n\n\n#include \"logfile.h\"\n#include \"orderBudget.h\"\n\nnamespace quark {\n\n\n\n\nMoneyServerClient2::MoneyServerClient2(PMoneySvcSupport support,\n\t\tString addr, String signature, String asset, String currency, String firstTradeId, bool logTrafic)\n\t:support(support)\n\t,addr(addr)\n\t,signature(signature)\n\t,asset(asset)\n\t,currency(currency)\n\t,firstTradeId(firstTradeId)\n\t,client(new MyClient(addr,*this))\n\t,inited(false)\n{\n\tclient->enableLogTrafic(logTrafic);\n}\n\nMoneyServerClient2::~MoneyServerClient2() {\n\tclient->close();\n}\n\nvoid MoneyServerClient2::adjustBudget(json::Value ,\n\t\tOrderBudget& ) {\n\t\/\/emoty\n}\n\ntemplate\nvoid MoneyServerClient2::callWithRetry(RefCntPtr client,PMoneySvcSupport supp, String methodName, Value params, Fn callback) {\n\n\t(*client)(methodName, params) >>\n\t\t\t[=](RpcResult res) {\n\t\tif (res.isError()) {\n\t\t\tif (res.defined()) {\n\t\t\t\thandleError(client,methodName,res);\n\t\t\t}\n\t\t\tif (!client->isClosed()) {\n\t\t\t\tsupp->dispatch([=]{callWithRetry(client,supp,methodName,params,callback);});\n\t\t\t} else {\n\t\t\t\tcallback(res);\n\t\t\t}\n\t\t} else {\n\t\t\tcallback(res);\n\t\t}\n\t};\n\n}\n\nbool MoneyServerClient2::allocBudget(json::Value user, OrderBudget total,\n\t\tCallback callback) {\n\n\tconnectIfNeed();\n\tRefCntPtr c(client);\n\tValue params = Object\n\t\t\t(\"user_id\",user)\n\t\t\t(\"currency\",total.currency)\n\t\t\t(\"asset\",total.asset)\n\t\t\t(\"marginLong\",total.marginLong)\n\t\t\t(\"marginShort\",total.marginShort)\n\t\t\t(\"posLong\",total.posLong)\n\t\t\t(\"posShort\",total.posShort);\n\n\n\t(*client)(\"CurrencyBalance.block_money\", params)\n\t\t\t>> [c,callback](const RpcResult &res) {\n\n\n\t\tif (res.isError()) {\n\t\t\tif (res.defined())\n\t\t\t\thandleError(c,\"CurrencyBalance.block_money\", res);\n\t\t\tcallback(allocTryAgain);\n\t\t} else {\n\t\t\tif (Value(res)[\"success\"].getBool()) {\n\t\t\t\tcallback(allocOk);\n\t\t\t} else {\n\t\t\t\tcallback(allocReject);\n\t\t\t}\n\t\t}\n\n\n\t};\n\treturn false;\n\n\n\n}\n\nvoid MoneyServerClient2::reportTrade(Value prevTrade, const TradeData& data) {\n\n\t connectIfNeed();\n\t reportTrade2(prevTrade, data);\n\n}\nvoid MoneyServerClient2::reportTrade2(Value prevTrade, const TradeData& data) {\n\n\tRefCntPtr c(client);\n\t(*c)(\"CurrencyBalance.trade\", Object(\"trade_id\",data.id)\n\t\t\t\t\t\t\t\t\t\t(\"prev_trade_id\", prevTrade)\n\t\t\t\t\t\t\t\t\t\t(\"timestamp\",data.timestamp)\n\t\t\t\t\t\t\t\t\t\t(\"asset\",data.size)\n\t\t\t\t\t\t\t\t\t\t(\"currency\",data.price)\n\t\t\t\t\t\t\t\t\t\t(\"buyer\",Object(\"user_id\",data.buyer.userId)\n\t\t\t\t\t\t\t\t\t\t\t\t\t (\"context\",data.buyer.context))\n\t\t\t\t\t\t\t\t\t\t(\"seller\",Object(\"user_id\",data.seller.userId)\n\t\t\t\t\t\t\t\t\t\t\t\t\t (\"context\",data.seller.context))\n\t\t\t\t\t\t\t\t\t\t(\"taker\",data.dir == OrderDir::buy?\"buyer\":\"seller\"))\n\n\t>> [c](const RpcResult &res){\n\t\tif (res.isError()) {\n\t\t\thandleError(c, \"CurrencyBalance.trade\", res);\n\t\t}\n\t};\n\tlastReportedTrade = data.id;\n}\n\n\nMoneyServerClient2::MyClient::MyClient(String addr,\n\t\tMoneyServerClient2& owner):owner(owner),closed(false) {\n}\n\nvoid MoneyServerClient2::MyClient::onInit() {\n\towner.onInit();\n}\n\nvoid MoneyServerClient2::MyClient::onNotify(const Notify& ntf) {\n\towner.onNotify(ntf);\n}\n\nvoid MoneyServerClient2::onInit() {\n\t\/\/empty\n}\n\nvoid MoneyServerClient2::onNotify(const Notify& ntf) {\n\t\/\/empty\n}\n\nclass MoneyServerClient2::ResyncStream: public ITradeStream {\npublic:\n\tMoneyServerClient2 &owner;\n\tResyncStream(MoneyServerClient2 &owner):owner(owner) {}\n\tvirtual void reportTrade(Value prevTrade, const TradeData &data) {\n\t\towner.reportTrade2(prevTrade, data);\n\t}\n};\n\n\n\nvoid MoneyServerClient2::connectIfNeed() {\n\tif (!client->isConnected()) {\n\t\tif (client->connect(addr)) {\n\n\t\t\tRpcResult initres = (*client)(\"CurrencyBalance.init\", Object\n\t\t\t\t\t(\"signature\",signature)\n\t\t\t\t\t(\"asset\",asset)\n\t\t\t\t\t(\"currency\",currency));\n\t\t\tif (initres.isError()) {\n\t\t\t\tif (initres.defined()) {\n\t\t\t\t\thandleError(client,\"CurrencyBalance.init\", initres);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tValue r(initres);\n\t\t\t\tValue lastSyncId = r[\"last_trade_id\"];\n\t\t\t\tValue version = r[\"version\"];\n\n\n\t\t\t\tif (lastSyncId.getString() == \"\" && firstTradeId != \"\") {\n\t\t\t\t\tlastSyncId = firstTradeId;\n\t\t\t\t}\n\n\t\t\t\tlogInfo({\"Initialized RPC client, version, lastId\", version, lastSyncId});\n\n\t\t\t\tResyncStream resyncStream(*this);\n\t\t\t\tsupport->resync(resyncStream, lastSyncId, lastReportedTrade);\n\t\t\t}\n\n\t\t} else {\n\t\t\t\/\/failed connect\n\t\t\t\/\/nothing here - commands send to disconnected client are rejected through callback\n\t\t}\n\t}\n}\n\nvoid MoneyServerClient2::handleError(MyClient *c, StrViewA method, const RpcResult& res)\n{\n\tlogError({method, \"Money server error, dropping connection\", c->getAddr(), Value(res)});\n\tc->disconnect(false);\n}\n\n}\nerror during sync -> unhandled exception\/*\n * moneyServerClient2.cpp\n *\n * Created on: 20. 7. 2017\n * Author: ondra\n *\/\n\n\n\n\n#include \"moneyServerClient2.h\"\n\n#include \n#include \n\n#include \"..\/common\/runtime_error.h\"\n\n#include \"error.h\"\n\n\n#include \"logfile.h\"\n#include \"orderBudget.h\"\n\nnamespace quark {\n\n\n\n\nMoneyServerClient2::MoneyServerClient2(PMoneySvcSupport support,\n\t\tString addr, String signature, String asset, String currency, String firstTradeId, bool logTrafic)\n\t:support(support)\n\t,addr(addr)\n\t,signature(signature)\n\t,asset(asset)\n\t,currency(currency)\n\t,firstTradeId(firstTradeId)\n\t,client(new MyClient(addr,*this))\n\t,inited(false)\n{\n\tclient->enableLogTrafic(logTrafic);\n}\n\nMoneyServerClient2::~MoneyServerClient2() {\n\tclient->close();\n}\n\nvoid MoneyServerClient2::adjustBudget(json::Value ,\n\t\tOrderBudget& ) {\n\t\/\/emoty\n}\n\ntemplate\nvoid MoneyServerClient2::callWithRetry(RefCntPtr client,PMoneySvcSupport supp, String methodName, Value params, Fn callback) {\n\n\t(*client)(methodName, params) >>\n\t\t\t[=](RpcResult res) {\n\t\tif (res.isError()) {\n\t\t\tif (res.defined()) {\n\t\t\t\thandleError(client,methodName,res);\n\t\t\t}\n\t\t\tif (!client->isClosed()) {\n\t\t\t\tsupp->dispatch([=]{callWithRetry(client,supp,methodName,params,callback);});\n\t\t\t} else {\n\t\t\t\tcallback(res);\n\t\t\t}\n\t\t} else {\n\t\t\tcallback(res);\n\t\t}\n\t};\n\n}\n\nbool MoneyServerClient2::allocBudget(json::Value user, OrderBudget total,\n\t\tCallback callback) {\n\n\tconnectIfNeed();\n\tRefCntPtr c(client);\n\tValue params = Object\n\t\t\t(\"user_id\",user)\n\t\t\t(\"currency\",total.currency)\n\t\t\t(\"asset\",total.asset)\n\t\t\t(\"marginLong\",total.marginLong)\n\t\t\t(\"marginShort\",total.marginShort)\n\t\t\t(\"posLong\",total.posLong)\n\t\t\t(\"posShort\",total.posShort);\n\n\n\t(*client)(\"CurrencyBalance.block_money\", params)\n\t\t\t>> [c,callback](const RpcResult &res) {\n\n\n\t\tif (res.isError()) {\n\t\t\tif (res.defined())\n\t\t\t\thandleError(c,\"CurrencyBalance.block_money\", res);\n\t\t\tcallback(allocTryAgain);\n\t\t} else {\n\t\t\tif (Value(res)[\"success\"].getBool()) {\n\t\t\t\tcallback(allocOk);\n\t\t\t} else {\n\t\t\t\tcallback(allocReject);\n\t\t\t}\n\t\t}\n\n\n\t};\n\treturn false;\n\n\n\n}\n\nvoid MoneyServerClient2::reportTrade(Value prevTrade, const TradeData& data) {\n\n\t connectIfNeed();\n\t reportTrade2(prevTrade, data);\n\n}\nvoid MoneyServerClient2::reportTrade2(Value prevTrade, const TradeData& data) {\n\n\tRefCntPtr c(client);\n\t(*c)(\"CurrencyBalance.trade\", Object(\"trade_id\",data.id)\n\t\t\t\t\t\t\t\t\t\t(\"prev_trade_id\", prevTrade)\n\t\t\t\t\t\t\t\t\t\t(\"timestamp\",data.timestamp)\n\t\t\t\t\t\t\t\t\t\t(\"asset\",data.size)\n\t\t\t\t\t\t\t\t\t\t(\"currency\",data.price)\n\t\t\t\t\t\t\t\t\t\t(\"buyer\",Object(\"user_id\",data.buyer.userId)\n\t\t\t\t\t\t\t\t\t\t\t\t\t (\"context\",data.buyer.context))\n\t\t\t\t\t\t\t\t\t\t(\"seller\",Object(\"user_id\",data.seller.userId)\n\t\t\t\t\t\t\t\t\t\t\t\t\t (\"context\",data.seller.context))\n\t\t\t\t\t\t\t\t\t\t(\"taker\",data.dir == OrderDir::buy?\"buyer\":\"seller\"))\n\n\t>> [c](const RpcResult &res){\n\t\tif (res.isError()) {\n\t\t\thandleError(c, \"CurrencyBalance.trade\", res);\n\t\t}\n\t};\n\tlastReportedTrade = data.id;\n}\n\n\nMoneyServerClient2::MyClient::MyClient(String addr,\n\t\tMoneyServerClient2& owner):owner(owner),closed(false) {\n}\n\nvoid MoneyServerClient2::MyClient::onInit() {\n\towner.onInit();\n}\n\nvoid MoneyServerClient2::MyClient::onNotify(const Notify& ntf) {\n\towner.onNotify(ntf);\n}\n\nvoid MoneyServerClient2::onInit() {\n\t\/\/empty\n}\n\nvoid MoneyServerClient2::onNotify(const Notify& ntf) {\n\t\/\/empty\n}\n\nclass MoneyServerClient2::ResyncStream: public ITradeStream {\npublic:\n\tMoneyServerClient2 &owner;\n\tResyncStream(MoneyServerClient2 &owner):owner(owner) {}\n\tvirtual void reportTrade(Value prevTrade, const TradeData &data) {\n\t\towner.reportTrade2(prevTrade, data);\n\t}\n};\n\n\n\nvoid MoneyServerClient2::connectIfNeed() {\n\tif (!client->isConnected()) {\n\t\tif (client->connect(addr)) {\n\n\t\t\tRpcResult initres = (*client)(\"CurrencyBalance.init\", Object\n\t\t\t\t\t(\"signature\",signature)\n\t\t\t\t\t(\"asset\",asset)\n\t\t\t\t\t(\"currency\",currency));\n\t\t\tif (initres.isError()) {\n\t\t\t\tif (initres.defined()) {\n\t\t\t\t\thandleError(client,\"CurrencyBalance.init\", initres);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tValue r(initres);\n\t\t\t\tValue lastSyncId = r[\"last_trade_id\"];\n\t\t\t\tValue version = r[\"version\"];\n\n\n\t\t\t\tif (lastSyncId.getString() == \"\" && firstTradeId != \"\") {\n\t\t\t\t\tlastSyncId = firstTradeId;\n\t\t\t\t}\n\n\t\t\t\tlogInfo({\"Initialized RPC client, version, lastId\", version, lastSyncId});\n\n\t\t\t\ttry {\n\t\t\t\t\tResyncStream resyncStream(*this);\n\t\t\t\t\tsupport->resync(resyncStream, lastSyncId, lastReportedTrade);\n\t\t\t\t} catch (...) {\n\t\t\t\t\tunhandledException();\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else {\n\t\t\t\/\/failed connect\n\t\t\t\/\/nothing here - commands send to disconnected client are rejected through callback\n\t\t}\n\t}\n}\n\nvoid MoneyServerClient2::handleError(MyClient *c, StrViewA method, const RpcResult& res)\n{\n\tlogError({method, \"Money server error, dropping connection\", c->getAddr(), Value(res)});\n\tc->disconnect(false);\n}\n\n}\n<|endoftext|>"} {"text":"#include \"audio\/playback.h\"\n\nnamespace loftili {\n\nnamespace audio {\n\nvoid Playback::Start() {\n if(m_state == PLAYBACK_STATE_PLAYING) return;\n spdlog::get(LOFTILI_SPDLOG_ID)->info(\"playback starting, opening playback thread\");\n m_state = PLAYBACK_STATE_PLAYING;\n m_stateclient.Update(\"playback\", 1);\n m_thread = std::unique_ptr(new std::thread(std::bind(&Playback::Run, this)));\n}\n\nvoid Playback::Skip() {\n Stop();\n m_queue.Pop();\n Start();\n}\n\nvoid Playback::Stop() {\n spdlog::get(LOFTILI_SPDLOG_ID)->info(\"stopping player and playback run thread\");\n m_state = PLAYBACK_STATE_STOPPED;\n m_player.Stop();\n m_thread->join();\n}\n\nvoid Playback::Run() {\n m_state = PLAYBACK_STATE_PLAYING;\n\n while(m_queue >> m_player && m_state == PLAYBACK_STATE_PLAYING) { \n spdlog::get(LOFTILI_SPDLOG_ID)->info(\"player finished, getting next track from queue\");\n }\n\n spdlog::get(LOFTILI_SPDLOG_ID)->info(\"playback run thread finishing\");\n m_state = PLAYBACK_STATE_STOPPED;\n m_stateclient.Update(\"playback\", 0);\n}\n\n}\n\n}\n[LFTCE-36] checking that device state playing before attempting to stop in playback skip#include \"audio\/playback.h\"\n\nnamespace loftili {\n\nnamespace audio {\n\nvoid Playback::Start() {\n if(m_state == PLAYBACK_STATE_PLAYING) return;\n spdlog::get(LOFTILI_SPDLOG_ID)->info(\"playback starting, opening playback thread\");\n m_state = PLAYBACK_STATE_PLAYING;\n m_stateclient.Update(\"playback\", 1);\n m_thread = std::unique_ptr(new std::thread(std::bind(&Playback::Run, this)));\n}\n\nvoid Playback::Skip() {\n if(m_state == PLAYBACK_STATE_PLAYING) Stop();\n m_queue.Pop();\n Start();\n}\n\nvoid Playback::Stop() {\n spdlog::get(LOFTILI_SPDLOG_ID)->info(\"stopping player and playback run thread\");\n m_state = PLAYBACK_STATE_STOPPED;\n m_player.Stop();\n m_thread->join();\n}\n\nvoid Playback::Run() {\n m_state = PLAYBACK_STATE_PLAYING;\n\n while(m_queue >> m_player && m_state == PLAYBACK_STATE_PLAYING) { \n spdlog::get(LOFTILI_SPDLOG_ID)->info(\"player finished, getting next track from queue\");\n }\n\n spdlog::get(LOFTILI_SPDLOG_ID)->info(\"playback run thread finishing\");\n m_state = PLAYBACK_STATE_STOPPED;\n m_stateclient.Update(\"playback\", 0);\n}\n\n}\n\n}\n<|endoftext|>"} {"text":"\/*******************************************************************************\n * c7a\/core\/stage_builder.hpp\n *\n * Part of Project c7a.\n *\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#pragma once\n#ifndef C7A_CORE_STAGE_BUILDER_HEADER\n#define C7A_CORE_STAGE_BUILDER_HEADER\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace c7a {\nnamespace core {\n\nusing c7a::api::DIABase;\n\nclass Stage\n{\npublic:\n explicit Stage(DIABase* node) : node_(node) {\n LOG << \"CREATING stage\" << node_->ToString() << \"node\" << node_;\n }\n\n void Execute() {\n LOG << \"EXECUTING stage \" << node_->ToString() << \"node\" << node_;\n node_->Execute();\n node_->UnregisterChilds();\n node_->set_state(c7a::api::EXECUTED);\n }\n\n void PushData() {\n LOG << \"PUSHING stage \" << node_->ToString() << \"node\" << node_;\n node_->PushData();\n }\n\n void Dispose() {\n LOG << \"DISPOSING stage \" << node_->ToString() << \"node\" << node_;\n node_->Dispose();\n node_->set_state(c7a::api::DISPOSED);\n }\n\n DIABase * node() {\n return node_;\n }\n\nprivate:\n static const bool debug = false;\n DIABase* node_;\n};\n\nclass StageBuilder\n{\npublic:\n void FindStages(DIABase* action, std::vector& stages_result) {\n LOG << \"FINDING stages:\";\n \/\/ std::set stages_found;\n std::vector stages_found;\n \/\/ Do a reverse DFS and find all stages\n std::stack dia_stack;\n dia_stack.push(action);\n \/\/ stages_found.insert(action);\n stages_found.push_back(action);\n while (!dia_stack.empty()) {\n DIABase* curr = dia_stack.top();\n dia_stack.pop();\n const auto parents = curr->parents();\n for (size_t i = 0; i < parents.size(); ++i) {\n auto p = parents[i].get();\n stages_found.push_back(p);\n if (p->state() != c7a::api::EXECUTED) {\n dia_stack.push(p);\n }\n }\n }\n for (auto stage : stages_found) {\n stages_result.emplace_back(stage);\n }\n std::reverse(stages_result.begin(), stages_result.end());\n }\n\n void RunScope(DIABase* action) {\n std::vector result;\n FindStages(action, result);\n for (auto s : result)\n {\n \/\/ TODO(sl): This is nonsense -tb, fix it:\n if (s.node()->state() == c7a::api::EXECUTED) s.Execute();\n if (s.node()->state() == c7a::api::EXECUTED) s.PushData();\n }\n }\n\n static const bool debug = false;\n};\n\n} \/\/ namespace core\n} \/\/ namespace c7a\n\n#endif \/\/ !C7A_CORE_STAGE_BUILDER_HEADER\n\n\/******************************************************************************\/\nFixed all except Zip.\/*******************************************************************************\n * c7a\/core\/stage_builder.hpp\n *\n * Part of Project c7a.\n *\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#pragma once\n#ifndef C7A_CORE_STAGE_BUILDER_HEADER\n#define C7A_CORE_STAGE_BUILDER_HEADER\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace c7a {\nnamespace core {\n\nusing c7a::api::DIABase;\n\nclass Stage\n{\npublic:\n explicit Stage(DIABase* node) : node_(node) {\n LOG << \"CREATING stage\" << node_->ToString() << \"node\" << node_;\n }\n\n void Execute() {\n LOG << \"EXECUTING stage \" << node_->ToString() << \"node\" << node_;\n node_->Execute();\n node_->PushData();\n node_->UnregisterChilds();\n node_->set_state(c7a::api::EXECUTED);\n }\n\n void PushData() {\n LOG << \"PUSHING stage \" << node_->ToString() << \"node\" << node_;\n node_->PushData();\n }\n\n void Dispose() {\n LOG << \"DISPOSING stage \" << node_->ToString() << \"node\" << node_;\n node_->Dispose();\n node_->set_state(c7a::api::DISPOSED);\n }\n\n DIABase * node() {\n return node_;\n }\n\nprivate:\n static const bool debug = false;\n DIABase* node_;\n};\n\nclass StageBuilder\n{\npublic:\n void FindStages(DIABase* action, std::vector& stages_result) {\n LOG << \"FINDING stages:\";\n \/\/ std::set stages_found;\n std::vector stages_found;\n \/\/ Do a reverse DFS and find all stages\n std::stack dia_stack;\n dia_stack.push(action);\n \/\/ stages_found.insert(action);\n stages_found.push_back(action);\n while (!dia_stack.empty()) {\n DIABase* curr = dia_stack.top();\n dia_stack.pop();\n const auto parents = curr->parents();\n for (size_t i = 0; i < parents.size(); ++i) {\n auto p = parents[i].get();\n stages_found.push_back(p);\n if (p->state() != c7a::api::EXECUTED) {\n dia_stack.push(p);\n }\n }\n }\n for (auto stage : stages_found) {\n stages_result.emplace_back(stage);\n }\n std::reverse(stages_result.begin(), stages_result.end());\n }\n\n void RunScope(DIABase* action) {\n std::vector result;\n FindStages(action, result);\n for (auto s : result)\n {\n \/\/ TODO(sl): This is nonsense -tb, fix it:\n if (s.node()->state() == c7a::api::EXECUTED) s.PushData();\n if (s.node()->state() == c7a::api::NEW) s.Execute();\n }\n }\n\n static const bool debug = false;\n};\n\n} \/\/ namespace core\n} \/\/ namespace c7a\n\n#endif \/\/ !C7A_CORE_STAGE_BUILDER_HEADER\n\n\/******************************************************************************\/\n<|endoftext|>"} {"text":"\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2011 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"Exception.h\"\n#include \"Backtrace.h\"\n#include \"Logger.h\"\n#include \"OSHelper.h\"\n\n#include \n#include \n\nusing namespace std;\n\nnamespace avg {\n\nException::Exception(int code, const string& sErr)\n : std::exception(),\n m_Code (code),\n m_sErr (sErr)\n{\n}\n\nException::Exception(const Exception& ex)\n : std::exception(),\n m_Code (ex.getCode()),\n m_sErr (ex.getStr())\n{\n}\n\nException::~Exception() throw()\n{\n}\n\nint Exception::getCode() const\n{\n return m_Code;\n}\n\nconst string& Exception::getStr() const\n{\n return m_sErr;\n}\n\nconst char* Exception::what() const throw()\n{\n return m_sErr.c_str();\n}\n\nvoid fatalError(const string& sMsg, int type)\n{\n AVG_LOG_ERROR(\"Internal error: \"+sMsg+\" Aborting.\");\n throw(Exception(type, sMsg));\n}\n\nvoid debugBreak()\n{\n#ifdef _WIN32\n __asm int 3;\n#else\n __builtin_trap();\n#endif\n}\n\nvoid avgAssert(bool b, const char * pszFile, int line, const char * pszReason)\n{\n if (!b) {\n string sDummy;\n static bool bBreak = getEnv(\"AVG_BREAK_ON_ASSERT\", sDummy);\n if (bBreak) {\n debugBreak();\n } else {\n stringstream ss;\n ss << \"Assertion failed in \" << pszFile << \": \" << line << endl;\n if (pszReason) {\n ss << \"Reason: \" << pszReason << endl;\n }\n dumpBacktrace();\n throw(Exception(AVG_ERR_ASSERT_FAILED, ss.str()));\n }\n }\n}\n\n}\nReplaced __asm with __debugbreak, work on #384\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2011 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"Exception.h\"\n#include \"Backtrace.h\"\n#include \"Logger.h\"\n#include \"OSHelper.h\"\n\n#include \n#include \n\n#ifdef WIN32\n#include \n#endif\n\nusing namespace std;\n\nnamespace avg {\n\nException::Exception(int code, const string& sErr)\n : std::exception(),\n m_Code (code),\n m_sErr (sErr)\n{\n}\n\nException::Exception(const Exception& ex)\n : std::exception(),\n m_Code (ex.getCode()),\n m_sErr (ex.getStr())\n{\n}\n\nException::~Exception() throw()\n{\n}\n\nint Exception::getCode() const\n{\n return m_Code;\n}\n\nconst string& Exception::getStr() const\n{\n return m_sErr;\n}\n\nconst char* Exception::what() const throw()\n{\n return m_sErr.c_str();\n}\n\nvoid fatalError(const string& sMsg, int type)\n{\n AVG_LOG_ERROR(\"Internal error: \"+sMsg+\" Aborting.\");\n throw(Exception(type, sMsg));\n}\n\nvoid debugBreak()\n{\n#ifdef _WIN32\n __debugbreak();\n#else\n __builtin_trap();\n#endif\n}\n\nvoid avgAssert(bool b, const char * pszFile, int line, const char * pszReason)\n{\n if (!b) {\n string sDummy;\n static bool bBreak = getEnv(\"AVG_BREAK_ON_ASSERT\", sDummy);\n if (bBreak) {\n debugBreak();\n } else {\n stringstream ss;\n ss << \"Assertion failed in \" << pszFile << \": \" << line << endl;\n if (pszReason) {\n ss << \"Reason: \" << pszReason << endl;\n }\n dumpBacktrace();\n throw(Exception(AVG_ERR_ASSERT_FAILED, ss.str()));\n }\n }\n}\n\n}\n<|endoftext|>"} {"text":"#ifndef AMGCL_SOLVERS_CG_HPP\n#define AMGCL_SOLVERS_CG_HPP\n\n\/*\nThe MIT License\n\nCopyright (c) 2012-2015 Denis Demidov \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/**\n * \\file amgcl\/solver\/cg.hpp\n * \\author Denis Demidov \n * \\brief Conjugate Gradient method.\n *\/\n\n#include \n#include \n#include \n#include \n\nnamespace amgcl {\n\n\/\/\/ Iterative solvers\nnamespace solver {\n\n\/**\n * \\defgroup solvers\n * \\brief Iterative solvers\n *\n * AMGCL provides several iterative solvers, but it should be easy to use it as\n * a preconditioner with a user-provided solver. Each solver in AMGCL is a\n * class template. Its single template parameter specifies the backend to use.\n * This allows to preallocate necessary resources at class construction.\n * Obviously, the solver backend has to coincide with the AMG backend.\n *\/\n\n\n\/\/\/ Conjugate Gradients iterative solver.\n\/**\n * \\param Backend Backend for temporary structures allocation.\n * \\ingroup solvers\n * \\sa \\cite Barrett1994\n *\/\ntemplate <\n class Backend,\n class InnerProduct = detail::default_inner_product\n >\nclass cg {\n public:\n typedef Backend backend_type;\n\n typedef typename Backend::vector vector;\n typedef typename Backend::value_type value_type;\n typedef typename Backend::params backend_params;\n\n typedef typename math::scalar_of::type scalar_type;\n\n typedef typename math::inner_product_impl<\n typename math::rhs_of::type\n >::return_type coef_type;\n\n \/\/\/ Solver parameters.\n struct params {\n \/\/\/ Maximum number of iterations.\n size_t maxiter;\n\n \/\/\/ Target residual error.\n scalar_type tol;\n\n params(size_t maxiter = 100, scalar_type tol = 1e-8)\n : maxiter(maxiter), tol(tol)\n {}\n\n params(const boost::property_tree::ptree &p)\n : AMGCL_PARAMS_IMPORT_VALUE(p, maxiter),\n AMGCL_PARAMS_IMPORT_VALUE(p, tol)\n {}\n\n void get(boost::property_tree::ptree &p, const std::string &path) const {\n AMGCL_PARAMS_EXPORT_VALUE(p, path, maxiter);\n AMGCL_PARAMS_EXPORT_VALUE(p, path, tol);\n }\n };\n\n \/\/\/ Preallocates necessary data structures\n \/**\n * \\param n The system size.\n * \\param prm Solver parameters.\n * \\param backend_prm Backend parameters.\n *\/\n cg(\n size_t n,\n const params &prm = params(),\n const backend_params &backend_prm = backend_params(),\n const InnerProduct &inner_product = InnerProduct()\n ) : prm(prm), n(n),\n r(Backend::create_vector(n, backend_prm)),\n s(Backend::create_vector(n, backend_prm)),\n p(Backend::create_vector(n, backend_prm)),\n q(Backend::create_vector(n, backend_prm)),\n inner_product(inner_product)\n { }\n\n \/\/\/ Solves the linear system for the given system matrix.\n \/**\n * \\param A System matrix.\n * \\param P Preconditioner.\n * \\param rhs Right-hand side.\n * \\param x Solution vector.\n *\n * The system matrix may differ from the matrix used for the AMG\n * preconditioner construction. This may be used for the solution of\n * non-stationary problems with slowly changing coefficients. There is\n * a strong chance that AMG built for one time step will act as a\n * reasonably good preconditioner for several subsequent time steps\n * \\cite Demidov2012.\n *\/\n template \n boost::tuple operator()(\n Matrix const &A,\n Precond const &P,\n Vec1 const &rhs,\n#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES\n Vec2 &x\n#else\n Vec2 &&x\n#endif\n ) const\n {\n static const coef_type one = math::identity();\n static const coef_type zero = math::zero();\n\n backend::residual(rhs, A, x, *r);\n scalar_type norm_rhs = norm(rhs);\n if (norm_rhs < amgcl::detail::eps(n)) {\n backend::clear(x);\n return boost::make_tuple(0, norm_rhs);\n }\n\n scalar_type eps = prm.tol * norm_rhs;\n scalar_type eps2 = eps * eps;\n\n coef_type rho1 = 2 * eps2 * one;\n coef_type rho2 = zero;\n scalar_type res_norm = norm(*r);\n\n size_t iter = 0;\n for(; iter < prm.maxiter && math::norm(rho1) > eps2; ++iter) {\n P.apply(*r, *s);\n\n rho2 = rho1;\n rho1 = inner_product(*r, *s);\n\n if (iter)\n backend::axpby(one, *s, rho1 \/ rho2, *p);\n else\n backend::copy(*s, *p);\n\n backend::spmv(one, A, *p, zero, *q);\n\n coef_type alpha = rho1 \/ inner_product(*q, *p);\n\n backend::axpby( alpha, *p, one, x);\n backend::axpby(-alpha, *q, one, *r);\n }\n\n backend::residual(rhs, A, x, *r);\n res_norm = norm(*r);\n\n return boost::make_tuple(iter, res_norm \/ norm_rhs);\n }\n\n \/\/\/ Solves the linear system for the same matrix that was used for the AMG preconditioner construction.\n \/**\n * \\param P AMG preconditioner.\n * \\param rhs Right-hand side.\n * \\param x Solution vector.\n *\/\n template \n boost::tuple operator()(\n Precond const &P,\n Vec1 const &rhs,\n#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES\n Vec2 &x\n#else\n Vec2 &&x\n#endif\n ) const\n {\n return (*this)(P.system_matrix(), P, rhs, x);\n }\n\n public:\n params prm;\n\n private:\n size_t n;\n\n boost::shared_ptr r;\n boost::shared_ptr s;\n boost::shared_ptr p;\n boost::shared_ptr q;\n\n InnerProduct inner_product;\n\n template \n scalar_type norm(const Vec &x) const {\n return sqrt(math::norm(inner_product(x, x)));\n }\n};\n\n} \/\/ namespace solver\n} \/\/ namespace amgcl\n\n\n#endif\nMore robust exit condition in solver::cg#ifndef AMGCL_SOLVERS_CG_HPP\n#define AMGCL_SOLVERS_CG_HPP\n\n\/*\nThe MIT License\n\nCopyright (c) 2012-2015 Denis Demidov \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/**\n * \\file amgcl\/solver\/cg.hpp\n * \\author Denis Demidov \n * \\brief Conjugate Gradient method.\n *\/\n\n#include \n#include \n#include \n#include \n\nnamespace amgcl {\n\n\/\/\/ Iterative solvers\nnamespace solver {\n\n\/**\n * \\defgroup solvers\n * \\brief Iterative solvers\n *\n * AMGCL provides several iterative solvers, but it should be easy to use it as\n * a preconditioner with a user-provided solver. Each solver in AMGCL is a\n * class template. Its single template parameter specifies the backend to use.\n * This allows to preallocate necessary resources at class construction.\n * Obviously, the solver backend has to coincide with the AMG backend.\n *\/\n\n\n\/\/\/ Conjugate Gradients iterative solver.\n\/**\n * \\param Backend Backend for temporary structures allocation.\n * \\ingroup solvers\n * \\sa \\cite Barrett1994\n *\/\ntemplate <\n class Backend,\n class InnerProduct = detail::default_inner_product\n >\nclass cg {\n public:\n typedef Backend backend_type;\n\n typedef typename Backend::vector vector;\n typedef typename Backend::value_type value_type;\n typedef typename Backend::params backend_params;\n\n typedef typename math::scalar_of::type scalar_type;\n\n typedef typename math::inner_product_impl<\n typename math::rhs_of::type\n >::return_type coef_type;\n\n \/\/\/ Solver parameters.\n struct params {\n \/\/\/ Maximum number of iterations.\n size_t maxiter;\n\n \/\/\/ Target residual error.\n scalar_type tol;\n\n params(size_t maxiter = 100, scalar_type tol = 1e-8)\n : maxiter(maxiter), tol(tol)\n {}\n\n params(const boost::property_tree::ptree &p)\n : AMGCL_PARAMS_IMPORT_VALUE(p, maxiter),\n AMGCL_PARAMS_IMPORT_VALUE(p, tol)\n {}\n\n void get(boost::property_tree::ptree &p, const std::string &path) const {\n AMGCL_PARAMS_EXPORT_VALUE(p, path, maxiter);\n AMGCL_PARAMS_EXPORT_VALUE(p, path, tol);\n }\n };\n\n \/\/\/ Preallocates necessary data structures\n \/**\n * \\param n The system size.\n * \\param prm Solver parameters.\n * \\param backend_prm Backend parameters.\n *\/\n cg(\n size_t n,\n const params &prm = params(),\n const backend_params &backend_prm = backend_params(),\n const InnerProduct &inner_product = InnerProduct()\n ) : prm(prm), n(n),\n r(Backend::create_vector(n, backend_prm)),\n s(Backend::create_vector(n, backend_prm)),\n p(Backend::create_vector(n, backend_prm)),\n q(Backend::create_vector(n, backend_prm)),\n inner_product(inner_product)\n { }\n\n \/\/\/ Solves the linear system for the given system matrix.\n \/**\n * \\param A System matrix.\n * \\param P Preconditioner.\n * \\param rhs Right-hand side.\n * \\param x Solution vector.\n *\n * The system matrix may differ from the matrix used for the AMG\n * preconditioner construction. This may be used for the solution of\n * non-stationary problems with slowly changing coefficients. There is\n * a strong chance that AMG built for one time step will act as a\n * reasonably good preconditioner for several subsequent time steps\n * \\cite Demidov2012.\n *\/\n template \n boost::tuple operator()(\n Matrix const &A,\n Precond const &P,\n Vec1 const &rhs,\n#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES\n Vec2 &x\n#else\n Vec2 &&x\n#endif\n ) const\n {\n static const coef_type one = math::identity();\n static const coef_type zero = math::zero();\n\n backend::residual(rhs, A, x, *r);\n scalar_type norm_rhs = norm(rhs);\n if (norm_rhs < amgcl::detail::eps(n)) {\n backend::clear(x);\n return boost::make_tuple(0, norm_rhs);\n }\n\n scalar_type eps = prm.tol * norm_rhs;\n scalar_type eps2 = eps * eps;\n\n coef_type rho1 = 2 * eps2 * one;\n coef_type rho2 = zero;\n scalar_type res_norm = norm(*r);\n\n size_t iter = 0;\n for(; iter < prm.maxiter && math::norm(res_norm) > eps2; ++iter) {\n P.apply(*r, *s);\n\n rho2 = rho1;\n rho1 = inner_product(*r, *s);\n\n if (iter)\n backend::axpby(one, *s, rho1 \/ rho2, *p);\n else\n backend::copy(*s, *p);\n\n backend::spmv(one, A, *p, zero, *q);\n\n coef_type alpha = rho1 \/ inner_product(*q, *p);\n\n backend::axpby( alpha, *p, one, x);\n backend::axpby(-alpha, *q, one, *r);\n\n res_norm = norm(*r);\n }\n\n backend::residual(rhs, A, x, *r);\n res_norm = norm(*r);\n\n return boost::make_tuple(iter, res_norm \/ norm_rhs);\n }\n\n \/\/\/ Solves the linear system for the same matrix that was used for the AMG preconditioner construction.\n \/**\n * \\param P AMG preconditioner.\n * \\param rhs Right-hand side.\n * \\param x Solution vector.\n *\/\n template \n boost::tuple operator()(\n Precond const &P,\n Vec1 const &rhs,\n#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES\n Vec2 &x\n#else\n Vec2 &&x\n#endif\n ) const\n {\n return (*this)(P.system_matrix(), P, rhs, x);\n }\n\n public:\n params prm;\n\n private:\n size_t n;\n\n boost::shared_ptr r;\n boost::shared_ptr s;\n boost::shared_ptr p;\n boost::shared_ptr q;\n\n InnerProduct inner_product;\n\n template \n scalar_type norm(const Vec &x) const {\n return sqrt(math::norm(inner_product(x, x)));\n }\n};\n\n} \/\/ namespace solver\n} \/\/ namespace amgcl\n\n\n#endif\n<|endoftext|>"} {"text":"\/*\n * This file is part of the IAN project - https:\/\/github.com\/Meoo\/IAN\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"ClusterConnection.hpp\"\n#include \"ClusterInternal.hpp\"\n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n\nnamespace asio = boost::asio;\n\n\n#define LOG_SOCKET_TUPLE \\\n socket_.remote_endpoint().address().to_string(), socket_.remote_endpoint().port()\n\nnamespace\n{\n\nconst size_t read_chunk_size = 16 * 1024; \/\/ 16k\n\nbool is_connection_reset_error(const boost::system::error_code & ec)\n{\n if (ec.category() == asio::error::get_system_category() &&\n (ec == asio::error::connection_aborted || ec == asio::error::connection_reset))\n {\n return true;\n }\n\n if (ec.category() == asio::ssl::error::get_stream_category() &&\n ec == asio::ssl::error::stream_truncated)\n {\n return true;\n }\n\n return false;\n}\n\nbool is_connection_canceled_error(const boost::system::error_code & ec)\n{\n if (ec.category() == asio::error::get_ssl_category() &&\n ERR_GET_REASON(ec.value()) == SSL_R_PROTOCOL_IS_SHUTDOWN)\n {\n return true;\n }\n\n return false;\n}\n\n} \/\/ namespace\n\n\nClusterConnection::ClusterConnection(const std::shared_ptr & logger,\n TcpSocket && socket)\n : logger_(logger), stream_(std::move(socket), cluster::internal::get_ssl()),\n socket_(stream_.next_layer()), strand_(socket_.get_io_context()),\n timer_(socket_.get_io_context())\n{\n}\n\nClusterConnection::~ClusterConnection()\n{\n \/\/ Close must be called last or using LOG_SOCKET_TUPLE will throw\n boost::system::error_code ec;\n socket_.close(ec);\n}\n\nvoid ClusterConnection::run(SslRole role, bool safe_link)\n{\n safe_link_ = safe_link;\n\n \/\/ Force peer verification\n boost::system::error_code ec;\n stream_.set_verify_mode(asio::ssl::verify_peer | asio::ssl::verify_fail_if_no_peer_cert, ec);\n if (ec)\n IAN_ERROR(logger_, \"Failed to force peer verification for cluster connection: : {}:{} : {}\",\n LOG_SOCKET_TUPLE, ec.message());\n\n \/\/ SSL handshake\n stream_.async_handshake(\n role == Client ? asio::ssl::stream_base::client : asio::ssl::stream_base::server,\n asio::bind_executor(strand_, std::bind(&ClusterConnection::on_ssl_handshake,\n shared_from_this(), std::placeholders::_1)));\n}\n\nvoid ClusterConnection::abort()\n{\n if (dropped_)\n return;\n\n boost::system::error_code ec;\n\n \/\/ Ignore errors\n timer_.cancel(ec);\n \/\/ TODO state_timer_.cancel(ec);\n\n \/\/ TODO message_queue_.clear();\n\n IAN_INFO(logger_, \"Peer disconnected: {}:{}\", LOG_SOCKET_TUPLE);\n\n \/\/ Abort stream at socket level\n socket_.shutdown(socket_.shutdown_both, ec);\n dropped_ = true;\n}\n\nvoid ClusterConnection::shutdown()\n{\n if (dropped_ || shutting_down_)\n return;\n\n boost::system::error_code ec;\n\n \/\/ Ignore errors\n timer_.cancel(ec);\n \/\/ TODO state_timer_.cancel(ec);\n\n \/\/ TODO message_queue_.clear();\n\n if (!socket_.is_open())\n return;\n\n \/\/ Shutdown stream at SSL level\n stream_.async_shutdown(\n asio::bind_executor(strand_, std::bind(&ClusterConnection::on_shutdown, shared_from_this(),\n std::placeholders::_1)));\n shutting_down_ = true;\n}\n\nvoid ClusterConnection::on_shutdown(boost::system::error_code ec)\n{\n if (dropped_)\n return;\n\n if (ec)\n {\n if (!is_connection_reset_error(ec) && !is_connection_canceled_error(ec))\n IAN_WARN(logger_, \"Shutdown error for peer: {}:{} : {} {}\", LOG_SOCKET_TUPLE, ec.message(),\n ec.value());\n }\n\n IAN_INFO(logger_, \"Peer disconnected: {}:{}\", LOG_SOCKET_TUPLE);\n\n \/\/ Abort stream at socket level\n socket_.shutdown(socket_.shutdown_both, ec);\n dropped_ = true;\n}\n\nvoid ClusterConnection::on_ssl_handshake(boost::system::error_code ec)\n{\n if (dropped_)\n return;\n\n if (ec)\n {\n IAN_WARN(logger_, \"SSL handshake failed for peer: {}:{} : {} {}\", LOG_SOCKET_TUPLE,\n ec.message(), ec.value());\n this->abort();\n return;\n }\n\n IAN_TRACE(logger_, \"SSL handshake complete for peer: {}:{}\", LOG_SOCKET_TUPLE);\n\n \/\/ Read IAN handshake\n stream_.async_read_some(\n read_buffer_.prepare(read_chunk_size),\n asio::bind_executor(strand_,\n std::bind(&ClusterConnection::on_ian_handshake, shared_from_this(),\n std::placeholders::_1, std::placeholders::_2)));\n}\n\nvoid ClusterConnection::on_ian_handshake(boost::system::error_code ec, std::size_t readlen)\n{\n if (ec)\n {\n handle_read_error(ec);\n return;\n }\n\n read_buffer_.commit(readlen);\n\n if (message_len_ == -1U)\n {\n \/\/ Read handshake length\n if (read_buffer_.size() < sizeof(message_len_))\n {\n \/\/ If first packet contains less than 4 bytes something is really wrong\n IAN_ERROR(logger_, \"Not enough data to read handshake length : {}:{} : {}\", LOG_SOCKET_TUPLE,\n read_buffer_.size());\n shutdown();\n return;\n }\n\n \/\/ Extract message length (little endian)\n read_buffer_.consume(asio::buffer_copy(\n asio::buffer((void *)&message_len_, sizeof(message_len_)), read_buffer_.data()));\n boost::endian::little_to_native_inplace(message_len_);\n }\n\n if (read_buffer_.size() < message_len_)\n {\n IAN_DEBUG(logger_, \"Not enough data to parse handshake : {}:{} : {} < {}\", LOG_SOCKET_TUPLE,\n read_buffer_.size(), message_len_);\n \/\/ Not enough data (somehow), read again\n stream_.async_read_some(\n read_buffer_.prepare(read_chunk_size),\n asio::bind_executor(strand_,\n std::bind(&ClusterConnection::on_ian_handshake, shared_from_this(),\n std::placeholders::_1, std::placeholders::_2)));\n return;\n }\n\n \/\/ Flatten\n boost::beast::flat_buffer buf;\n buf.commit(asio::buffer_copy(buf.prepare(read_buffer_.size()), read_buffer_.data()));\n\n \/\/ Verify handshake\n if (!proto::VerifyClusterHandshakeBuffer(\n flatbuffers::Verifier((const uint8_t *)buf.data().data(), buf.size())))\n {\n IAN_ERROR(logger_, \"Cluster handshake verification failed : {}:{}\", LOG_SOCKET_TUPLE);\n shutdown();\n return;\n }\n\n const proto::ClusterHandshake * handshake = proto::GetClusterHandshake(buf.data().data());\n\n auto major = handshake->version_major();\n auto minor = handshake->version_minor();\n\n IAN_DEBUG(logger_, \"Proto version for peer : {}:{} : {}.{}\", LOG_SOCKET_TUPLE, major, minor);\n\n safe_link_ = safe_link_ && handshake->safe_link();\n\n if (safe_link_)\n {\n \/\/ TODO Downgrade to clear messages\n }\n else\n {\n \/\/ TODO Start reading messages over SSL\n }\n}\n\nvoid ClusterConnection::handle_read_error(boost::system::error_code ec)\n{\n if (dropped_)\n return;\n\n if (is_connection_reset_error(ec))\n {\n this->abort();\n return;\n }\n\n if (is_connection_canceled_error(ec))\n return;\n\n IAN_WARN(logger_, \"Read failed for peer: {}:{} : {} {}\", LOG_SOCKET_TUPLE, ec.message(),\n ec.value());\n\n shutdown();\n}\n\nvoid ClusterConnection::handle_write_error(boost::system::error_code ec)\n{\n if (dropped_)\n return;\n\n if (is_connection_reset_error(ec))\n {\n this->abort();\n return;\n }\n\n if (is_connection_canceled_error(ec))\n return;\n\n IAN_WARN(logger_, \"Write failed for peer: {}:{} : {} {}\", LOG_SOCKET_TUPLE, ec.message(),\n ec.value());\n\n shutdown();\n}\nFix build\/*\n * This file is part of the IAN project - https:\/\/github.com\/Meoo\/IAN\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"ClusterConnection.hpp\"\n#include \"ClusterInternal.hpp\"\n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n\nnamespace asio = boost::asio;\n\n\n#define LOG_SOCKET_TUPLE \\\n socket_.remote_endpoint().address().to_string(), socket_.remote_endpoint().port()\n\nnamespace\n{\n\nconst size_t read_chunk_size = 16 * 1024; \/\/ 16k\n\nbool is_connection_reset_error(const boost::system::error_code & ec)\n{\n if (ec.category() == asio::error::get_system_category() &&\n (ec == asio::error::connection_aborted || ec == asio::error::connection_reset))\n {\n return true;\n }\n\n if (ec.category() == asio::ssl::error::get_stream_category() &&\n ec == asio::ssl::error::stream_truncated)\n {\n return true;\n }\n\n return false;\n}\n\nbool is_connection_canceled_error(const boost::system::error_code & ec)\n{\n if (ec.category() == asio::error::get_ssl_category() &&\n ERR_GET_REASON(ec.value()) == SSL_R_PROTOCOL_IS_SHUTDOWN)\n {\n return true;\n }\n\n return false;\n}\n\n} \/\/ namespace\n\n\nClusterConnection::ClusterConnection(const std::shared_ptr & logger,\n TcpSocket && socket)\n : logger_(logger), stream_(std::move(socket), cluster::internal::get_ssl()),\n socket_(stream_.next_layer()), strand_(socket_.get_io_context()),\n timer_(socket_.get_io_context())\n{\n}\n\nClusterConnection::~ClusterConnection()\n{\n \/\/ Close must be called last or using LOG_SOCKET_TUPLE will throw\n boost::system::error_code ec;\n socket_.close(ec);\n}\n\nvoid ClusterConnection::run(SslRole role, bool safe_link)\n{\n safe_link_ = safe_link;\n\n \/\/ Force peer verification\n boost::system::error_code ec;\n stream_.set_verify_mode(asio::ssl::verify_peer | asio::ssl::verify_fail_if_no_peer_cert, ec);\n if (ec)\n IAN_ERROR(logger_, \"Failed to force peer verification for cluster connection: : {}:{} : {}\",\n LOG_SOCKET_TUPLE, ec.message());\n\n \/\/ SSL handshake\n stream_.async_handshake(\n role == Client ? asio::ssl::stream_base::client : asio::ssl::stream_base::server,\n asio::bind_executor(strand_, std::bind(&ClusterConnection::on_ssl_handshake,\n shared_from_this(), std::placeholders::_1)));\n}\n\nvoid ClusterConnection::abort()\n{\n if (dropped_)\n return;\n\n boost::system::error_code ec;\n\n \/\/ Ignore errors\n timer_.cancel(ec);\n \/\/ TODO state_timer_.cancel(ec);\n\n \/\/ TODO message_queue_.clear();\n\n IAN_INFO(logger_, \"Peer disconnected: {}:{}\", LOG_SOCKET_TUPLE);\n\n \/\/ Abort stream at socket level\n socket_.shutdown(socket_.shutdown_both, ec);\n dropped_ = true;\n}\n\nvoid ClusterConnection::shutdown()\n{\n if (dropped_ || shutting_down_)\n return;\n\n boost::system::error_code ec;\n\n \/\/ Ignore errors\n timer_.cancel(ec);\n \/\/ TODO state_timer_.cancel(ec);\n\n \/\/ TODO message_queue_.clear();\n\n if (!socket_.is_open())\n return;\n\n \/\/ Shutdown stream at SSL level\n stream_.async_shutdown(\n asio::bind_executor(strand_, std::bind(&ClusterConnection::on_shutdown, shared_from_this(),\n std::placeholders::_1)));\n shutting_down_ = true;\n}\n\nvoid ClusterConnection::on_shutdown(boost::system::error_code ec)\n{\n if (dropped_)\n return;\n\n if (ec)\n {\n if (!is_connection_reset_error(ec) && !is_connection_canceled_error(ec))\n IAN_WARN(logger_, \"Shutdown error for peer: {}:{} : {} {}\", LOG_SOCKET_TUPLE, ec.message(),\n ec.value());\n }\n\n IAN_INFO(logger_, \"Peer disconnected: {}:{}\", LOG_SOCKET_TUPLE);\n\n \/\/ Abort stream at socket level\n socket_.shutdown(socket_.shutdown_both, ec);\n dropped_ = true;\n}\n\nvoid ClusterConnection::on_ssl_handshake(boost::system::error_code ec)\n{\n if (dropped_)\n return;\n\n if (ec)\n {\n IAN_WARN(logger_, \"SSL handshake failed for peer: {}:{} : {} {}\", LOG_SOCKET_TUPLE,\n ec.message(), ec.value());\n this->abort();\n return;\n }\n\n IAN_TRACE(logger_, \"SSL handshake complete for peer: {}:{}\", LOG_SOCKET_TUPLE);\n\n \/\/ Read IAN handshake\n stream_.async_read_some(\n read_buffer_.prepare(read_chunk_size),\n asio::bind_executor(strand_,\n std::bind(&ClusterConnection::on_ian_handshake, shared_from_this(),\n std::placeholders::_1, std::placeholders::_2)));\n}\n\nvoid ClusterConnection::on_ian_handshake(boost::system::error_code ec, std::size_t readlen)\n{\n if (ec)\n {\n handle_read_error(ec);\n return;\n }\n\n read_buffer_.commit(readlen);\n\n if (message_len_ == -1U)\n {\n \/\/ Read handshake length\n if (read_buffer_.size() < sizeof(message_len_))\n {\n \/\/ If first packet contains less than 4 bytes something is really wrong\n IAN_ERROR(logger_, \"Not enough data to read handshake length : {}:{} : {}\", LOG_SOCKET_TUPLE,\n read_buffer_.size());\n shutdown();\n return;\n }\n\n \/\/ Extract message length (little endian)\n read_buffer_.consume(asio::buffer_copy(\n asio::buffer((void *)&message_len_, sizeof(message_len_)), read_buffer_.data()));\n boost::endian::little_to_native_inplace(message_len_);\n }\n\n if (read_buffer_.size() < message_len_)\n {\n IAN_DEBUG(logger_, \"Not enough data to parse handshake : {}:{} : {} < {}\", LOG_SOCKET_TUPLE,\n read_buffer_.size(), message_len_);\n \/\/ Not enough data (somehow), read again\n stream_.async_read_some(\n read_buffer_.prepare(read_chunk_size),\n asio::bind_executor(strand_,\n std::bind(&ClusterConnection::on_ian_handshake, shared_from_this(),\n std::placeholders::_1, std::placeholders::_2)));\n return;\n }\n\n \/\/ Flatten\n boost::beast::flat_buffer buf;\n buf.commit(asio::buffer_copy(buf.prepare(read_buffer_.size()), read_buffer_.data()));\n\n \/\/ Verify handshake\n {\n flatbuffers::Verifier verifier((const uint8_t *)buf.data().data(), buf.size());\n if (!proto::VerifyClusterHandshakeBuffer(verifier))\n {\n IAN_ERROR(logger_, \"Cluster handshake verification failed : {}:{}\", LOG_SOCKET_TUPLE);\n shutdown();\n return;\n }\n }\n\n const proto::ClusterHandshake * handshake = proto::GetClusterHandshake(buf.data().data());\n\n auto major = handshake->version_major();\n auto minor = handshake->version_minor();\n\n IAN_DEBUG(logger_, \"Proto version for peer : {}:{} : {}.{}\", LOG_SOCKET_TUPLE, major, minor);\n\n safe_link_ = safe_link_ && handshake->safe_link();\n\n if (safe_link_)\n {\n \/\/ TODO Downgrade to clear messages\n }\n else\n {\n \/\/ TODO Start reading messages over SSL\n }\n}\n\nvoid ClusterConnection::handle_read_error(boost::system::error_code ec)\n{\n if (dropped_)\n return;\n\n if (is_connection_reset_error(ec))\n {\n this->abort();\n return;\n }\n\n if (is_connection_canceled_error(ec))\n return;\n\n IAN_WARN(logger_, \"Read failed for peer: {}:{} : {} {}\", LOG_SOCKET_TUPLE, ec.message(),\n ec.value());\n\n shutdown();\n}\n\nvoid ClusterConnection::handle_write_error(boost::system::error_code ec)\n{\n if (dropped_)\n return;\n\n if (is_connection_reset_error(ec))\n {\n this->abort();\n return;\n }\n\n if (is_connection_canceled_error(ec))\n return;\n\n IAN_WARN(logger_, \"Write failed for peer: {}:{} : {} {}\", LOG_SOCKET_TUPLE, ec.message(),\n ec.value());\n\n shutdown();\n}\n<|endoftext|>"} {"text":"#include \n\n#include \"helpers.hpp\"\n\n#include \n#include \n#include \n\n#include \"catch.hpp\"\n\nusing iter::product;\nusing Vec = const std::vector;\n\nTEST_CASE(\"product: basic test, two sequences\", \"[product]\") {\n using TP = std::tuple;\n using ResType = std::vector;\n\n Vec n1 = {0, 1};\n const std::string s{\"abc\"};\n\n auto p = product(n1, s);\n ResType v(std::begin(p), std::end(p));\n ResType vc = {TP{0,'a'}, TP{0,'b'}, TP{0,'c'},\n TP{1,'a'}, TP{1,'b'}, TP{1,'c'}};\n\n REQUIRE( v == vc );\n}\n\nTEST_CASE(\"product: three sequences\", \"[product]\") {\n using TP = std::tuple ;\n using ResType = const std::vector;\n\n Vec n1 = {0, 1};\n const std::string s{\"ab\"};\n Vec n2 = {2};\n\n auto p = product(n1, s, n2);\n ResType v(std::begin(p), std::end(p));\n\n ResType vc = {\n TP{0, 'a', 2},\n TP{0, 'b', 2},\n TP{1, 'a', 2},\n TP{1, 'b', 2}\n };\n\n REQUIRE( v == vc );\n}\n\n\nTEST_CASE(\"product: empty when any iterable is empty\", \"[product]\") {\n Vec n1 = {0, 1};\n Vec n2 = {0, 1, 2};\n Vec emp = {};\n\n SECTION(\"first iterable is empty\") {\n auto p = product(emp, n1, n2);\n REQUIRE( std::begin(p) == std::end(p) );\n }\n\n SECTION(\"middle iterable is empty\") {\n auto p = product(n1, emp, n2);\n REQUIRE( std::begin(p) == std::end(p) );\n }\n\n SECTION(\"last iterable is empty\") {\n auto p = product(n1, n2, emp);\n REQUIRE( std::begin(p) == std::end(p) );\n }\n}\n\nTEST_CASE(\"product: single iterable\", \"[product]\") {\n const std::string s{\"ab\"};\n using TP = std::tuple;\n using ResType = const std::vector;\n\n auto p = product(s);\n ResType v(std::begin(p), std::end(p));\n ResType vc = {TP{'a'}, TP{'b'}};\n\n REQUIRE( v == vc );\n}\n\nTEST_CASE(\"product: binds to lvalues and moves rvalues\", \"[product]\") {\n itertest::BasicIterable bi{'x', 'y'};\n itertest::BasicIterable bi2{0, 1};\n \n SECTION(\"First ref'd, second moved\") {\n product(bi, std::move(bi2));\n REQUIRE_FALSE( bi.was_moved_from() );\n REQUIRE( bi2.was_moved_from() );\n }\n\n SECTION(\"First moved, second ref'd\") {\n product(std::move(bi), bi2);\n REQUIRE( bi.was_moved_from() );\n REQUIRE_FALSE( bi2.was_moved_from() );\n }\n}\n\nTEST_CASE(\"product: doesn't move or copy elements of iterable\", \"[product]\") {\n constexpr itertest::SolidInt arr[] = {{1}, {0}, {2}};\n for (auto&& t : product(arr)) {\n (void)std::get<0>(t);\n }\n}\ntests empty product()#include \n\n#include \"helpers.hpp\"\n\n#include \n#include \n#include \n\n#include \"catch.hpp\"\n\nusing iter::product;\nusing Vec = const std::vector;\n\nTEST_CASE(\"product: basic test, two sequences\", \"[product]\") {\n using TP = std::tuple;\n using ResType = std::vector;\n\n Vec n1 = {0, 1};\n const std::string s{\"abc\"};\n\n auto p = product(n1, s);\n ResType v(std::begin(p), std::end(p));\n ResType vc = {TP{0,'a'}, TP{0,'b'}, TP{0,'c'},\n TP{1,'a'}, TP{1,'b'}, TP{1,'c'}};\n\n REQUIRE( v == vc );\n}\n\nTEST_CASE(\"product: three sequences\", \"[product]\") {\n using TP = std::tuple ;\n using ResType = const std::vector;\n\n Vec n1 = {0, 1};\n const std::string s{\"ab\"};\n Vec n2 = {2};\n\n auto p = product(n1, s, n2);\n ResType v(std::begin(p), std::end(p));\n\n ResType vc = {\n TP{0, 'a', 2},\n TP{0, 'b', 2},\n TP{1, 'a', 2},\n TP{1, 'b', 2}\n };\n\n REQUIRE( v == vc );\n}\n\n\nTEST_CASE(\"product: empty when any iterable is empty\", \"[product]\") {\n Vec n1 = {0, 1};\n Vec n2 = {0, 1, 2};\n Vec emp = {};\n\n SECTION(\"first iterable is empty\") {\n auto p = product(emp, n1, n2);\n REQUIRE( std::begin(p) == std::end(p) );\n }\n\n SECTION(\"middle iterable is empty\") {\n auto p = product(n1, emp, n2);\n REQUIRE( std::begin(p) == std::end(p) );\n }\n\n SECTION(\"last iterable is empty\") {\n auto p = product(n1, n2, emp);\n REQUIRE( std::begin(p) == std::end(p) );\n }\n}\n\nTEST_CASE(\"product: single iterable\", \"[product]\") {\n const std::string s{\"ab\"};\n using TP = std::tuple;\n using ResType = const std::vector;\n\n auto p = product(s);\n ResType v(std::begin(p), std::end(p));\n ResType vc = {TP{'a'}, TP{'b'}};\n\n REQUIRE( v == vc );\n}\n\nTEST_CASE(\"product: no arguments gives one empty tuple\", \"[product\") {\n auto p = product();\n auto it = std::begin(p);\n REQUIRE( it != std::end(p) );\n REQUIRE( *it == std::make_tuple() );\n ++it;\n REQUIRE( it == std::end(p) );\n}\n\nTEST_CASE(\"product: binds to lvalues and moves rvalues\", \"[product]\") {\n itertest::BasicIterable bi{'x', 'y'};\n itertest::BasicIterable bi2{0, 1};\n \n SECTION(\"First ref'd, second moved\") {\n product(bi, std::move(bi2));\n REQUIRE_FALSE( bi.was_moved_from() );\n REQUIRE( bi2.was_moved_from() );\n }\n\n SECTION(\"First moved, second ref'd\") {\n product(std::move(bi), bi2);\n REQUIRE( bi.was_moved_from() );\n REQUIRE_FALSE( bi2.was_moved_from() );\n }\n}\n\nTEST_CASE(\"product: doesn't move or copy elements of iterable\", \"[product]\") {\n constexpr itertest::SolidInt arr[] = {{1}, {0}, {2}};\n for (auto&& t : product(arr)) {\n (void)std::get<0>(t);\n }\n}\n<|endoftext|>"} {"text":"\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"tink\/util\/validation.h\"\n\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n#include \"tink\/util\/test_matchers.h\"\n\nnamespace crypto {\nnamespace tink {\n\nnamespace {\n\nusing crypto::tink::test::IsOk;\nusing crypto::tink::test::StatusIs;\n\nTEST(ValidateKey, ValidKey) {\n google::crypto::tink::Keyset::Key key;\n key.set_key_id(100);\n key.mutable_key_data()->set_value(\"some value\");\n key.set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);\n key.set_status(google::crypto::tink::KeyStatusType::ENABLED);\n EXPECT_THAT(crypto::tink::ValidateKey(key), IsOk());\n}\n\nTEST(ValidateKey, MissingOutputPrefixType) {\n google::crypto::tink::Keyset::Key key;\n key.set_key_id(100);\n key.mutable_key_data()->set_value(\"some value\");\n key.set_status(google::crypto::tink::KeyStatusType::ENABLED);\n EXPECT_THAT(crypto::tink::ValidateKey(key),\n StatusIs(util::error::INVALID_ARGUMENT));\n}\n\nTEST(ValidateKey, MissingKeyData) {\n google::crypto::tink::Keyset::Key key;\n key.set_key_id(100);\n key.set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);\n key.set_status(google::crypto::tink::KeyStatusType::ENABLED);\n EXPECT_THAT(crypto::tink::ValidateKey(key),\n StatusIs(util::error::INVALID_ARGUMENT));\n}\n\nTEST(ValidateKey, MissingStatus) {\n google::crypto::tink::Keyset::Key key;\n key.set_key_id(100);\n key.mutable_key_data()->set_value(\"some value\");\n key.set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);\n EXPECT_THAT(crypto::tink::ValidateKey(key),\n StatusIs(util::error::INVALID_ARGUMENT));\n}\n\nTEST(ValidateKeyset, Valid) {\n google::crypto::tink::Keyset keyset;\n google::crypto::tink::Keyset::Key* key = keyset.add_key();\n key->set_key_id(100);\n key->mutable_key_data()->set_value(\"some value\");\n key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);\n key->set_status(google::crypto::tink::KeyStatusType::ENABLED);\n keyset.set_primary_key_id(100);\n EXPECT_THAT(crypto::tink::ValidateKeyset(keyset), IsOk());\n}\n\nTEST(ValidateKeyset, ValidMultipleKeys) {\n google::crypto::tink::Keyset keyset;\n google::crypto::tink::Keyset::Key* key = keyset.add_key();\n key->set_key_id(32);\n key->mutable_key_data()->set_value(\"some value\");\n key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);\n key->set_status(google::crypto::tink::KeyStatusType::ENABLED);\n key = keyset.add_key();\n key->set_key_id(100);\n key->mutable_key_data()->set_value(\"some other value\");\n key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);\n key->set_status(google::crypto::tink::KeyStatusType::ENABLED);\n key = keyset.add_key();\n key->set_key_id(18);\n key->mutable_key_data()->set_value(\"some third value\");\n key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);\n key->set_status(google::crypto::tink::KeyStatusType::ENABLED);\n keyset.set_primary_key_id(100);\n EXPECT_THAT(crypto::tink::ValidateKeyset(keyset), IsOk());\n}\n\nTEST(ValidateKeyset, PrimaryIdNonExistent) {\n google::crypto::tink::Keyset keyset;\n google::crypto::tink::Keyset::Key* key = keyset.add_key();\n key->set_key_id(100);\n key->mutable_key_data()->set_value(\"some value\");\n key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);\n key->set_status(google::crypto::tink::KeyStatusType::ENABLED);\n keyset.set_primary_key_id(99);\n EXPECT_THAT(crypto::tink::ValidateKeyset(keyset),\n StatusIs(util::error::INVALID_ARGUMENT));\n}\n\n\nTEST(ValidateKeyset, ValidHighId) {\n google::crypto::tink::Keyset keyset;\n google::crypto::tink::Keyset::Key* key = keyset.add_key();\n key->set_key_id(std::numeric_limits::max());\n key->mutable_key_data()->set_value(\"some value\");\n key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);\n key->set_status(google::crypto::tink::KeyStatusType::ENABLED);\n keyset.set_primary_key_id(std::numeric_limits::max());\n EXPECT_THAT(crypto::tink::ValidateKeyset(keyset), IsOk());\n}\n\n} \/\/ namespace\n\n} \/\/ namespace tink\n} \/\/ namespace crypto\nAdd some tests to validation_test\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"tink\/util\/validation.h\"\n\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n#include \"tink\/util\/test_matchers.h\"\n\nnamespace crypto {\nnamespace tink {\n\nnamespace {\n\nusing crypto::tink::test::IsOk;\nusing crypto::tink::test::StatusIs;\nusing google::crypto::tink::KeyData;\nusing testing::Not;\n\nTEST(ValidateKey, ValidKey) {\n google::crypto::tink::Keyset::Key key;\n key.set_key_id(100);\n key.mutable_key_data()->set_value(\"some value\");\n key.set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);\n key.set_status(google::crypto::tink::KeyStatusType::ENABLED);\n EXPECT_THAT(crypto::tink::ValidateKey(key), IsOk());\n}\n\nTEST(ValidateKey, MissingOutputPrefixType) {\n google::crypto::tink::Keyset::Key key;\n key.set_key_id(100);\n key.mutable_key_data()->set_value(\"some value\");\n key.set_status(google::crypto::tink::KeyStatusType::ENABLED);\n EXPECT_THAT(crypto::tink::ValidateKey(key),\n StatusIs(util::error::INVALID_ARGUMENT));\n}\n\nTEST(ValidateKey, MissingKeyData) {\n google::crypto::tink::Keyset::Key key;\n key.set_key_id(100);\n key.set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);\n key.set_status(google::crypto::tink::KeyStatusType::ENABLED);\n EXPECT_THAT(crypto::tink::ValidateKey(key),\n StatusIs(util::error::INVALID_ARGUMENT));\n}\n\nTEST(ValidateKey, MissingStatus) {\n google::crypto::tink::Keyset::Key key;\n key.set_key_id(100);\n key.mutable_key_data()->set_value(\"some value\");\n key.set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);\n EXPECT_THAT(crypto::tink::ValidateKey(key),\n StatusIs(util::error::INVALID_ARGUMENT));\n}\n\nTEST(ValidateKeyset, Valid) {\n google::crypto::tink::Keyset keyset;\n google::crypto::tink::Keyset::Key* key = keyset.add_key();\n key->set_key_id(100);\n key->mutable_key_data()->set_value(\"some value\");\n key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);\n key->set_status(google::crypto::tink::KeyStatusType::ENABLED);\n keyset.set_primary_key_id(100);\n EXPECT_THAT(crypto::tink::ValidateKeyset(keyset), IsOk());\n}\n\nTEST(ValidateKeyset, ValidMultipleKeys) {\n google::crypto::tink::Keyset keyset;\n google::crypto::tink::Keyset::Key* key = keyset.add_key();\n key->set_key_id(32);\n key->mutable_key_data()->set_value(\"some value\");\n key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);\n key->set_status(google::crypto::tink::KeyStatusType::ENABLED);\n key = keyset.add_key();\n key->set_key_id(100);\n key->mutable_key_data()->set_value(\"some other value\");\n key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);\n key->set_status(google::crypto::tink::KeyStatusType::ENABLED);\n key = keyset.add_key();\n key->set_key_id(18);\n key->mutable_key_data()->set_value(\"some third value\");\n key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);\n key->set_status(google::crypto::tink::KeyStatusType::ENABLED);\n keyset.set_primary_key_id(100);\n EXPECT_THAT(crypto::tink::ValidateKeyset(keyset), IsOk());\n}\n\n\/\/ Tests that a keyset with duplicate primary id is rejected\nTEST(ValidateKeyset, DuplicatePrimaryId) {\n google::crypto::tink::Keyset keyset;\n google::crypto::tink::Keyset::Key* key = keyset.add_key();\n key->set_key_id(100);\n key->mutable_key_data()->set_value(\"some value\");\n key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);\n key->set_status(google::crypto::tink::KeyStatusType::ENABLED);\n key = keyset.add_key();\n key->set_key_id(100);\n key->mutable_key_data()->set_value(\"some other value\");\n key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);\n key->set_status(google::crypto::tink::KeyStatusType::ENABLED);\n keyset.set_primary_key_id(100);\n EXPECT_THAT(crypto::tink::ValidateKeyset(keyset), Not(IsOk()));\n}\n\n\/\/ Tests that a keyset with public keys only doesn't need a primary id\nTEST(ValidateKeyset, OnlyPublicKeys) {\n google::crypto::tink::Keyset keyset;\n google::crypto::tink::Keyset::Key* key = keyset.add_key();\n key->set_key_id(32);\n key->mutable_key_data()->set_value(\"some value\");\n key->mutable_key_data()->set_key_material_type(KeyData::ASYMMETRIC_PUBLIC);\n key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);\n key->set_status(google::crypto::tink::KeyStatusType::ENABLED);\n key = keyset.add_key();\n key->set_key_id(100);\n key->mutable_key_data()->set_value(\"some other value\");\n key->mutable_key_data()->set_key_material_type(KeyData::ASYMMETRIC_PUBLIC);\n key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);\n key->set_status(google::crypto::tink::KeyStatusType::ENABLED);\n key = keyset.add_key();\n key->set_key_id(18);\n key->mutable_key_data()->set_value(\"some third value\");\n key->mutable_key_data()->set_key_material_type(KeyData::ASYMMETRIC_PUBLIC);\n key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);\n key->set_status(google::crypto::tink::KeyStatusType::ENABLED);\n EXPECT_THAT(crypto::tink::ValidateKeyset(keyset), IsOk());\n}\n\nTEST(ValidateKeyset, PrimaryIdNonExistent) {\n google::crypto::tink::Keyset keyset;\n google::crypto::tink::Keyset::Key* key = keyset.add_key();\n key->set_key_id(100);\n key->mutable_key_data()->set_value(\"some value\");\n key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);\n key->set_status(google::crypto::tink::KeyStatusType::ENABLED);\n keyset.set_primary_key_id(99);\n EXPECT_THAT(crypto::tink::ValidateKeyset(keyset),\n StatusIs(util::error::INVALID_ARGUMENT));\n}\n\nTEST(ValidateKeyset, ValidHighId) {\n google::crypto::tink::Keyset keyset;\n google::crypto::tink::Keyset::Key* key = keyset.add_key();\n key->set_key_id(std::numeric_limits::max());\n key->mutable_key_data()->set_value(\"some value\");\n key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);\n key->set_status(google::crypto::tink::KeyStatusType::ENABLED);\n keyset.set_primary_key_id(std::numeric_limits::max());\n EXPECT_THAT(crypto::tink::ValidateKeyset(keyset), IsOk());\n}\n\n} \/\/ namespace\n\n} \/\/ namespace tink\n} \/\/ namespace crypto\n<|endoftext|>"} {"text":"#include \"oddlib\/compressiontype3.hpp\"\n#include \"oddlib\/stream.hpp\"\n#include \"logger.hpp\"\n#include \n\nnamespace Oddlib\n{\n static int Next6Bits(signed int& bitCounter, unsigned int& src_data, IStream& stream)\n {\n int ret = 0;\n if (bitCounter > 0)\n {\n if (bitCounter == 14)\n {\n bitCounter = 30;\n src_data = (ReadUint16(stream) << 14) | src_data;\n ret = 2;\n }\n }\n else\n {\n bitCounter = 32;\n src_data = ReadUint32(stream);\n ret = 4;\n }\n bitCounter -= 6;\n return ret;\n }\n\n \/\/ Function 0x004031E0 in AO\n std::vector CompressionType3::Decompress(IStream& stream, Uint32 finalW, Uint32 \/*w*\/, Uint32 h, Uint32 dataSize)\n {\n size_t dstPos = 0;\n std::vector buffer;\n buffer.resize(finalW*h*4);\n\n \/\/ const unsigned int whSize = w*h;\n int numBytesInFrameCnt = dataSize;\/\/ whSize & 0xFFFFFFFC;\n if (numBytesInFrameCnt > 0)\n {\n\n \/\/ unsigned int frame_data_index = 0;\n unsigned int src_data = 0;\n signed int bitCounter = 0;\n do\n {\n\n \/*numBytesInFrameCnt -=*\/ Next6Bits(bitCounter, src_data, stream);\n unsigned char bits = src_data & 0x3F;\n src_data = src_data >> 6;\n --numBytesInFrameCnt;\n if (bits & 0x20)\n {\n \/\/ 0x20= 0b100000\n \/\/ 0x3F= 0b111111\n int numberOfBytes = (bits & 0x1F) + 1;\n if (numberOfBytes)\n {\n do\n {\n if (numBytesInFrameCnt && dstPos < buffer.size())\n {\n \/*numBytesInFrameCnt -=*\/ Next6Bits(bitCounter, src_data, stream);\n bits = src_data & 0x3F;\n src_data = src_data >> 6;\n --numBytesInFrameCnt;\n }\n else\n {\n \/\/ 6 bits from \"other\" source\n bits = 0;\/\/ *srcPtr++ & 0x3F;\n \/\/--for_counter;\n }\n \/\/ if (dstPos < buffer.size())\n {\n buffer[dstPos++] = bits;\n }\n } while (--numberOfBytes != 0);\n }\n }\n else\n {\n \/\/ literal flag isn't set, so we have up to 5 bits of \"black\" pixels\n dstPos += bits + 1;\n }\n\n } while (numBytesInFrameCnt);\n }\n\n return buffer;\n }\n}\nfinal bit of tidy up#include \"oddlib\/compressiontype3.hpp\"\n#include \"oddlib\/stream.hpp\"\n#include \"logger.hpp\"\n#include \n\nnamespace Oddlib\n{\n static void NextBits(signed int& bitCounter, unsigned int& src_data, IStream& stream)\n {\n if (bitCounter > 0)\n {\n if (bitCounter == 14)\n {\n bitCounter = 30;\n src_data = (ReadUint16(stream) << 14) | src_data;\n }\n }\n else\n {\n bitCounter = 32;\n src_data = ReadUint32(stream);\n }\n bitCounter -= 6;\n }\n\n \/\/ Function 0x004031E0 in AO\n \/\/ NOTE: A lot of the code in AbeWin.exe for this algorithm is dead, it attempts to gain some \"other\" buffer at the end of the\n \/\/ animation data which actually doesn't exist. Thus all this \"extra\" code does is write black pixels to an already black canvas.\n std::vector CompressionType3::Decompress(IStream& stream, Uint32 finalW, Uint32 \/*w*\/, Uint32 h, Uint32 dataSize)\n {\n size_t dstPos = 0;\n std::vector buffer;\n buffer.resize(finalW*h);\n\n int numBytesInFrameCnt = dataSize & 0xFFFFFFFC;\n if (numBytesInFrameCnt > 0)\n {\n unsigned int src_data = 0;\n signed int bitCounter = 0;\n do\n {\n NextBits(bitCounter, src_data, stream);\n unsigned char bits = src_data & 0x3F;\n src_data = src_data >> 6;\n --numBytesInFrameCnt;\n if (bits & 0x20)\n {\n \/\/ 0x20 = 0b100000\n \/\/ 0x3F = 0b111111\n int numberOfBytes = (bits & 0x1F) + 1;\n if (numberOfBytes)\n {\n do\n {\n if (numBytesInFrameCnt && dstPos < buffer.size())\n {\n NextBits(bitCounter, src_data, stream);\n bits = src_data & 0x3F;\n src_data = src_data >> 6;\n --numBytesInFrameCnt;\n }\n else\n {\n bits = 0;\n }\n buffer[dstPos++] = bits;\n } while (--numberOfBytes != 0);\n }\n }\n else\n {\n \/\/ literal flag isn't set, so we have up to 5 bits of \"black\" pixels\n dstPos += bits + 1;\n }\n\n } while (numBytesInFrameCnt);\n }\n\n return buffer;\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved\n *\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#if qPlatform_Linux\n#include \n#include \n#include \n#elif qPlatform_Windows\n#include \n#include \n#endif\n\n#include \"..\/..\/Characters\/CString\/Utilities.h\"\n#include \"..\/..\/Characters\/Format.h\"\n#include \"..\/..\/Characters\/String.h\"\n#include \"..\/..\/Characters\/StringBuilder.h\"\n#include \"..\/..\/Characters\/String_Constant.h\"\n#include \"..\/..\/Characters\/ToString.h\"\n#include \"..\/..\/DataExchange\/Variant\/CharacterDelimitedLines\/Reader.h\"\n#include \"..\/..\/Execution\/Finally.h\"\n#include \"..\/..\/Execution\/Synchronized.h\"\n#include \"..\/..\/Memory\/SmallStackBuffer.h\"\n\n#include \"FileInputStream.h\"\n#include \"FileSystem.h\"\n\n#include \"MountedFilesystem.h\"\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::Containers;\nusing namespace Stroika::Foundation::IO;\nusing namespace Stroika::Foundation::IO::FileSystem;\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n#if qPlatform_Linux\nnamespace {\n \/\/ This is quirky, and only works for Linux, and \/proc\/mounts\n struct Watcher_Proc_Mounts_ {\n int mfd;\n Watcher_Proc_Mounts_ (const String& fn)\n : mfd (::open (fn.AsNarrowSDKString ().c_str (), O_RDONLY, 0))\n {\n }\n ~Watcher_Proc_Mounts_ ()\n {\n ::close (mfd);\n }\n bool IsNewAvail () const\n {\n \/\/ according to http:\/\/stackoverflow.com\/questions\/5070801\/monitoring-mount-point-changes-via-proc-mounts\n \/\/ have to use poll with POLLPRI | POLLERR flags\n \/\/\n \/\/ and from https:\/\/linux.die.net\/man\/5\/proc\n \/\/ \/proc\/[pid]\/mounts (since Linux 2.4.19)...\n \/\/ Since kernel version 2.6.15, this file is pollable: after opening the file for reading, a change in this file\n \/\/ (i.e., a file system mount or unmount) causes select(2) to mark the file descriptor as readable, and poll(2)\n \/\/ and epoll_wait(2) mark the file as having an error condition.\n struct pollfd pfd;\n int rv;\n int changes = 0;\n pfd.fd = mfd;\n pfd.events = POLLERR | POLLPRI;\n pfd.revents = 0;\n if ((rv = poll (&pfd, 1, 0)) >= 0) {\n if (pfd.revents & POLLERR) {\n return true;\n }\n }\n return false;\n }\n };\n}\n#endif\n\nnamespace {\n \/* \n * Something like this is used on many unix systems.\n *\/\n Collection ReadMountInfo_MTabLikeFile_ (const Streams::InputStream& readStream)\n {\n \/*\n * I haven't found this clearly documented yet, but it appears that a filesystem can be over-mounted.\n * See https:\/\/www.kernel.org\/doc\/Documentation\/filesystems\/ramfs-rootfs-initramfs.txt\n *\n * So the last one with a given mount point in the file wins.\n *\/\n Collection results;\n DataExchange::Variant::CharacterDelimitedLines::Reader reader{{' ', '\\t'}};\n for (Sequence line : reader.ReadMatrix (readStream)) {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"in IO::FileSystem::{}::ReadMountInfo_MTabLikeFile_ linesize=%d, line[0]=%s\", line.size (), line.empty () ? L\"\" : line[0].c_str ());\n#endif\n \/\/\n \/\/ https:\/\/www.centos.org\/docs\/5\/html\/5.2\/Deployment_Guide\/s2-proc-mounts.html\n \/\/\n \/\/ 1 - device name\n \/\/ 2 - mounted on\n \/\/ 3 - fstype\n \/\/\n if (line.size () >= 3) {\n String devName = line[0];\n \/\/ procfs\/mounts often contains symbolic links to device files\n \/\/ e.g. \/dev\/disk\/by-uuid\/e1d70192-1bb0-461d-b89f-b054e45bfa00\n if (devName.StartsWith (L\"\/\")) {\n IgnoreExceptionsExceptThreadAbortForCall (devName = IO::FileSystem::FileSystem::Default ().CanonicalizeName (devName));\n }\n String mountedAt = line[1];\n String fstype = line[2];\n static const String_Constant kNone_{L\"none\"};\n results.Add (MountedFilesystemType{mountedAt, devName == kNone_ ? Set{} : Set{devName}, fstype}); \/\/ special name none often used when there is no name\n }\n }\n return results;\n }\n}\n#if qPlatform_Linux\nnamespace {\n Collection ReadMountInfo_FromProcFSMounts_ ()\n {\n \/\/ Note - \/procfs files always unseekable\n static const String_Constant kUseFile2List_{L\"\/proc\/mounts\"};\n constexpr bool kUseWatcher_{true}; \/\/ seems safe and much faster\n if (kUseWatcher_) {\n static const Watcher_Proc_Mounts_ sWatcher_{kUseFile2List_};\n static Execution::Synchronized> sLastResult_;\n static bool sFirstTime_{true};\n if (sFirstTime_ or sWatcher_.IsNewAvail ()) {\n sLastResult_ = ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));\n sFirstTime_ = false;\n }\n return sLastResult_;\n }\n else {\n return ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));\n }\n }\n}\n#endif\n#if qPlatform_Linux\nnamespace {\n Collection ReadMountInfo_ETC_MTAB_ ()\n {\n \/\/ Note - \/procfs files always unseekable and this is sklink to \/procfs\n static const String_Constant kUseFile2List_{L\"\/etc\/mtab\"};\n return ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));\n }\n}\n#endif\n#if qPlatform_Windows\nnamespace {\n using DynamicDiskIDType = String;\n String GetPhysNameForDriveNumber_ (unsigned int i)\n {\n \/\/ This format is NOT super well documented, and was mostly derived from reading the remarks section\n \/\/ of https:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/aa363216%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396\n \/\/ (DeviceIoControl function)\n return Characters::Format (L\"\\\\\\\\.\\\\PhysicalDrive%d\", i);\n }\n Optional> GetDisksForVolume_ (String volumeName)\n {\n wchar_t volPathsBuf[10 * 1024]; \/\/ intentionally uninitialized since we dont use it if GetVolumePathNamesForVolumeNameW () returns error, and its an OUT only parameter\n DWORD retLen = 0;\n DWORD x = ::GetVolumePathNamesForVolumeNameW (volumeName.c_str (), volPathsBuf, static_cast (NEltsOf (volPathsBuf)), &retLen);\n if (x == 0) {\n return {}; \/\/ missing - no known - not empty - answer\n }\n else if (retLen <= 1) {\n return Set{};\n }\n Assert (1 <= Characters::CString::Length (volPathsBuf) and Characters::CString::Length (volPathsBuf) < NEltsOf (volPathsBuf));\n volumeName = L\"\\\\\\\\.\\\\\" + String::FromSDKString (volPathsBuf).CircularSubString (0, -1);\n\n \/\/ @todo - rewrite this - must somehow otherwise callocate this to be large enuf (dynamic alloc) - if we want more disk exents, but not sure when that happens...\n VOLUME_DISK_EXTENTS volumeDiskExtents;\n {\n \/*\n * For reasons I don't understand (maybe a hit at http:\/\/superuser.com\/questions\/733687\/give-regular-user-permission-to-access-physical-drive-on-windows)\n * this only works with admin privilges\n *\/\n HANDLE hHandle = ::CreateFileW (volumeName.c_str (), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);\n if (hHandle == INVALID_HANDLE_VALUE) {\n return {};\n }\n DWORD dwBytesReturned = 0;\n BOOL bResult = ::DeviceIoControl (hHandle, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, nullptr, 0, &volumeDiskExtents, sizeof (volumeDiskExtents), &dwBytesReturned, NULL);\n ::CloseHandle (hHandle);\n if (not bResult) {\n return {};\n }\n }\n Set result;\n for (DWORD n = 0; n < volumeDiskExtents.NumberOfDiskExtents; ++n) {\n result.Add (GetPhysNameForDriveNumber_ (volumeDiskExtents.Extents[n].DiskNumber));\n }\n return result;\n }\n\n Collection GetMountedFilesystems_Windows_ ()\n {\n Collection results{};\n TCHAR volumeNameBuf[1024]; \/\/ intentionally uninitialized since OUT parameter and not used unless FindFirstVolume success\n\n HANDLE hVol = INVALID_HANDLE_VALUE;\n auto&& cleanup = Execution::Finally ([&]() noexcept { if (hVol != INVALID_HANDLE_VALUE) { ::CloseHandle (hVol); } });\n\n for (HANDLE hVol = ::FindFirstVolume (volumeNameBuf, static_cast (NEltsOf (volumeNameBuf))); hVol != INVALID_HANDLE_VALUE;) {\n DWORD lpMaximumComponentLength;\n DWORD dwSysFlags;\n TCHAR fileSysNameBuf[1024];\n if (::GetVolumeInformation (volumeNameBuf, nullptr, static_cast (NEltsOf (volumeNameBuf)), nullptr, &lpMaximumComponentLength, &dwSysFlags, fileSysNameBuf, static_cast (NEltsOf (fileSysNameBuf)))) {\n MountedFilesystemType v;\n v.fFileSystemType = String::FromSDKString (fileSysNameBuf);\n v.fVolumeID = String::FromSDKString (volumeNameBuf);\n v.fDevicePaths = GetDisksForVolume_ (volumeNameBuf);\n\n TCHAR volPathsBuf[10 * 1024]; \/\/ intentionally uninitialized\n DWORD retLen = 0;\n DWORD x = ::GetVolumePathNamesForVolumeName (volumeNameBuf, volPathsBuf, static_cast (NEltsOf (volPathsBuf)), &retLen);\n if (x == 0) {\n DbgTrace (SDKSTR (\"Ignoring error getting paths (volume='%s')\"), volumeNameBuf);\n }\n else if (volPathsBuf[0] == 0) {\n \/\/ Ignore - unmounted!\n DbgTrace (SDKSTR (\"Ignoring unmounted filesystem (volume='%s')\"), volumeNameBuf);\n }\n else {\n for (const TCHAR* NameIdx = volPathsBuf; NameIdx[0] != L'\\0'; NameIdx += Characters::CString::Length (NameIdx) + 1) {\n v.fMountedOn = String::FromSDKString (NameIdx);\n results.Add (v);\n }\n }\n }\n\n \/\/ find next\n if (not::FindNextVolume (hVol, volumeNameBuf, static_cast (NEltsOf (volumeNameBuf)))) {\n ::FindVolumeClose (hVol);\n hVol = INVALID_HANDLE_VALUE;\n }\n }\n return results;\n }\n}\n#endif\n\n\/*\n ********************************************************************************\n ******************** IO::FileSystem::MountedFilesystemType *********************\n ********************************************************************************\n *\/\nString MountedFilesystemType::ToString () const\n{\n StringBuilder sb;\n sb += L\"{\";\n sb += L\"Mounted-On: '\" + fMountedOn + L\"', \";\n if (fDevicePaths) {\n sb += L\"Device-Paths: \" + Characters::ToString (*fDevicePaths) + L\", \";\n }\n if (fFileSystemType) {\n sb += L\"FileSystem-Type: '\" + *fFileSystemType + L\"', \";\n }\n if (fVolumeID) {\n sb += L\"Volume-ID: '\" + *fVolumeID + L\"', \";\n }\n sb += L\"}\";\n return sb.str ();\n}\n\n\/*\n ********************************************************************************\n ******************** IO::FileSystem::GetMountedFilesystems *********************\n ********************************************************************************\n *\/\nContainers::Collection IO::FileSystem::GetMountedFilesystems ()\n{\n#if qPlatform_Linux\n return ReadMountInfo_FromProcFSMounts_ ();\n#elif qPlatform_Windows\n return GetMountedFilesystems_Windows_ ();\n#else\n AssertNotImplemented ();\n return {};\n#endif\n}\nfor macos - use IO::FileSystem::GetMountedFilesystems () WeakAssert\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved\n *\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#if qPlatform_Linux\n#include \n#include \n#include \n#elif qPlatform_Windows\n#include \n#include \n#endif\n\n#include \"..\/..\/Characters\/CString\/Utilities.h\"\n#include \"..\/..\/Characters\/Format.h\"\n#include \"..\/..\/Characters\/String.h\"\n#include \"..\/..\/Characters\/StringBuilder.h\"\n#include \"..\/..\/Characters\/String_Constant.h\"\n#include \"..\/..\/Characters\/ToString.h\"\n#include \"..\/..\/DataExchange\/Variant\/CharacterDelimitedLines\/Reader.h\"\n#include \"..\/..\/Execution\/Finally.h\"\n#include \"..\/..\/Execution\/Synchronized.h\"\n#include \"..\/..\/Memory\/SmallStackBuffer.h\"\n\n#include \"FileInputStream.h\"\n#include \"FileSystem.h\"\n\n#include \"MountedFilesystem.h\"\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::Containers;\nusing namespace Stroika::Foundation::IO;\nusing namespace Stroika::Foundation::IO::FileSystem;\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n#if qPlatform_Linux\nnamespace {\n \/\/ This is quirky, and only works for Linux, and \/proc\/mounts\n struct Watcher_Proc_Mounts_ {\n int mfd;\n Watcher_Proc_Mounts_ (const String& fn)\n : mfd (::open (fn.AsNarrowSDKString ().c_str (), O_RDONLY, 0))\n {\n }\n ~Watcher_Proc_Mounts_ ()\n {\n ::close (mfd);\n }\n bool IsNewAvail () const\n {\n \/\/ according to http:\/\/stackoverflow.com\/questions\/5070801\/monitoring-mount-point-changes-via-proc-mounts\n \/\/ have to use poll with POLLPRI | POLLERR flags\n \/\/\n \/\/ and from https:\/\/linux.die.net\/man\/5\/proc\n \/\/ \/proc\/[pid]\/mounts (since Linux 2.4.19)...\n \/\/ Since kernel version 2.6.15, this file is pollable: after opening the file for reading, a change in this file\n \/\/ (i.e., a file system mount or unmount) causes select(2) to mark the file descriptor as readable, and poll(2)\n \/\/ and epoll_wait(2) mark the file as having an error condition.\n struct pollfd pfd;\n int rv;\n int changes = 0;\n pfd.fd = mfd;\n pfd.events = POLLERR | POLLPRI;\n pfd.revents = 0;\n if ((rv = poll (&pfd, 1, 0)) >= 0) {\n if (pfd.revents & POLLERR) {\n return true;\n }\n }\n return false;\n }\n };\n}\n#endif\n\nnamespace {\n \/* \n * Something like this is used on many unix systems.\n *\/\n Collection ReadMountInfo_MTabLikeFile_ (const Streams::InputStream& readStream)\n {\n \/*\n * I haven't found this clearly documented yet, but it appears that a filesystem can be over-mounted.\n * See https:\/\/www.kernel.org\/doc\/Documentation\/filesystems\/ramfs-rootfs-initramfs.txt\n *\n * So the last one with a given mount point in the file wins.\n *\/\n Collection results;\n DataExchange::Variant::CharacterDelimitedLines::Reader reader{{' ', '\\t'}};\n for (Sequence line : reader.ReadMatrix (readStream)) {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"in IO::FileSystem::{}::ReadMountInfo_MTabLikeFile_ linesize=%d, line[0]=%s\", line.size (), line.empty () ? L\"\" : line[0].c_str ());\n#endif\n \/\/\n \/\/ https:\/\/www.centos.org\/docs\/5\/html\/5.2\/Deployment_Guide\/s2-proc-mounts.html\n \/\/\n \/\/ 1 - device name\n \/\/ 2 - mounted on\n \/\/ 3 - fstype\n \/\/\n if (line.size () >= 3) {\n String devName = line[0];\n \/\/ procfs\/mounts often contains symbolic links to device files\n \/\/ e.g. \/dev\/disk\/by-uuid\/e1d70192-1bb0-461d-b89f-b054e45bfa00\n if (devName.StartsWith (L\"\/\")) {\n IgnoreExceptionsExceptThreadAbortForCall (devName = IO::FileSystem::FileSystem::Default ().CanonicalizeName (devName));\n }\n String mountedAt = line[1];\n String fstype = line[2];\n static const String_Constant kNone_{L\"none\"};\n results.Add (MountedFilesystemType{mountedAt, devName == kNone_ ? Set{} : Set{devName}, fstype}); \/\/ special name none often used when there is no name\n }\n }\n return results;\n }\n}\n#if qPlatform_Linux\nnamespace {\n Collection ReadMountInfo_FromProcFSMounts_ ()\n {\n \/\/ Note - \/procfs files always unseekable\n static const String_Constant kUseFile2List_{L\"\/proc\/mounts\"};\n constexpr bool kUseWatcher_{true}; \/\/ seems safe and much faster\n if (kUseWatcher_) {\n static const Watcher_Proc_Mounts_ sWatcher_{kUseFile2List_};\n static Execution::Synchronized> sLastResult_;\n static bool sFirstTime_{true};\n if (sFirstTime_ or sWatcher_.IsNewAvail ()) {\n sLastResult_ = ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));\n sFirstTime_ = false;\n }\n return sLastResult_;\n }\n else {\n return ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));\n }\n }\n}\n#endif\n#if qPlatform_Linux\nnamespace {\n Collection ReadMountInfo_ETC_MTAB_ ()\n {\n \/\/ Note - \/procfs files always unseekable and this is sklink to \/procfs\n static const String_Constant kUseFile2List_{L\"\/etc\/mtab\"};\n return ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));\n }\n}\n#endif\n#if qPlatform_Windows\nnamespace {\n using DynamicDiskIDType = String;\n String GetPhysNameForDriveNumber_ (unsigned int i)\n {\n \/\/ This format is NOT super well documented, and was mostly derived from reading the remarks section\n \/\/ of https:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/aa363216%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396\n \/\/ (DeviceIoControl function)\n return Characters::Format (L\"\\\\\\\\.\\\\PhysicalDrive%d\", i);\n }\n Optional> GetDisksForVolume_ (String volumeName)\n {\n wchar_t volPathsBuf[10 * 1024]; \/\/ intentionally uninitialized since we dont use it if GetVolumePathNamesForVolumeNameW () returns error, and its an OUT only parameter\n DWORD retLen = 0;\n DWORD x = ::GetVolumePathNamesForVolumeNameW (volumeName.c_str (), volPathsBuf, static_cast (NEltsOf (volPathsBuf)), &retLen);\n if (x == 0) {\n return {}; \/\/ missing - no known - not empty - answer\n }\n else if (retLen <= 1) {\n return Set{};\n }\n Assert (1 <= Characters::CString::Length (volPathsBuf) and Characters::CString::Length (volPathsBuf) < NEltsOf (volPathsBuf));\n volumeName = L\"\\\\\\\\.\\\\\" + String::FromSDKString (volPathsBuf).CircularSubString (0, -1);\n\n \/\/ @todo - rewrite this - must somehow otherwise callocate this to be large enuf (dynamic alloc) - if we want more disk exents, but not sure when that happens...\n VOLUME_DISK_EXTENTS volumeDiskExtents;\n {\n \/*\n * For reasons I don't understand (maybe a hit at http:\/\/superuser.com\/questions\/733687\/give-regular-user-permission-to-access-physical-drive-on-windows)\n * this only works with admin privilges\n *\/\n HANDLE hHandle = ::CreateFileW (volumeName.c_str (), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);\n if (hHandle == INVALID_HANDLE_VALUE) {\n return {};\n }\n DWORD dwBytesReturned = 0;\n BOOL bResult = ::DeviceIoControl (hHandle, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, nullptr, 0, &volumeDiskExtents, sizeof (volumeDiskExtents), &dwBytesReturned, NULL);\n ::CloseHandle (hHandle);\n if (not bResult) {\n return {};\n }\n }\n Set result;\n for (DWORD n = 0; n < volumeDiskExtents.NumberOfDiskExtents; ++n) {\n result.Add (GetPhysNameForDriveNumber_ (volumeDiskExtents.Extents[n].DiskNumber));\n }\n return result;\n }\n\n Collection GetMountedFilesystems_Windows_ ()\n {\n Collection results{};\n TCHAR volumeNameBuf[1024]; \/\/ intentionally uninitialized since OUT parameter and not used unless FindFirstVolume success\n\n HANDLE hVol = INVALID_HANDLE_VALUE;\n auto&& cleanup = Execution::Finally ([&]() noexcept { if (hVol != INVALID_HANDLE_VALUE) { ::CloseHandle (hVol); } });\n\n for (HANDLE hVol = ::FindFirstVolume (volumeNameBuf, static_cast (NEltsOf (volumeNameBuf))); hVol != INVALID_HANDLE_VALUE;) {\n DWORD lpMaximumComponentLength;\n DWORD dwSysFlags;\n TCHAR fileSysNameBuf[1024];\n if (::GetVolumeInformation (volumeNameBuf, nullptr, static_cast (NEltsOf (volumeNameBuf)), nullptr, &lpMaximumComponentLength, &dwSysFlags, fileSysNameBuf, static_cast (NEltsOf (fileSysNameBuf)))) {\n MountedFilesystemType v;\n v.fFileSystemType = String::FromSDKString (fileSysNameBuf);\n v.fVolumeID = String::FromSDKString (volumeNameBuf);\n v.fDevicePaths = GetDisksForVolume_ (volumeNameBuf);\n\n TCHAR volPathsBuf[10 * 1024]; \/\/ intentionally uninitialized\n DWORD retLen = 0;\n DWORD x = ::GetVolumePathNamesForVolumeName (volumeNameBuf, volPathsBuf, static_cast (NEltsOf (volPathsBuf)), &retLen);\n if (x == 0) {\n DbgTrace (SDKSTR (\"Ignoring error getting paths (volume='%s')\"), volumeNameBuf);\n }\n else if (volPathsBuf[0] == 0) {\n \/\/ Ignore - unmounted!\n DbgTrace (SDKSTR (\"Ignoring unmounted filesystem (volume='%s')\"), volumeNameBuf);\n }\n else {\n for (const TCHAR* NameIdx = volPathsBuf; NameIdx[0] != L'\\0'; NameIdx += Characters::CString::Length (NameIdx) + 1) {\n v.fMountedOn = String::FromSDKString (NameIdx);\n results.Add (v);\n }\n }\n }\n\n \/\/ find next\n if (not::FindNextVolume (hVol, volumeNameBuf, static_cast (NEltsOf (volumeNameBuf)))) {\n ::FindVolumeClose (hVol);\n hVol = INVALID_HANDLE_VALUE;\n }\n }\n return results;\n }\n}\n#endif\n\n\/*\n ********************************************************************************\n ******************** IO::FileSystem::MountedFilesystemType *********************\n ********************************************************************************\n *\/\nString MountedFilesystemType::ToString () const\n{\n StringBuilder sb;\n sb += L\"{\";\n sb += L\"Mounted-On: '\" + fMountedOn + L\"', \";\n if (fDevicePaths) {\n sb += L\"Device-Paths: \" + Characters::ToString (*fDevicePaths) + L\", \";\n }\n if (fFileSystemType) {\n sb += L\"FileSystem-Type: '\" + *fFileSystemType + L\"', \";\n }\n if (fVolumeID) {\n sb += L\"Volume-ID: '\" + *fVolumeID + L\"', \";\n }\n sb += L\"}\";\n return sb.str ();\n}\n\n\/*\n ********************************************************************************\n ******************** IO::FileSystem::GetMountedFilesystems *********************\n ********************************************************************************\n *\/\nContainers::Collection IO::FileSystem::GetMountedFilesystems ()\n{\n#if qPlatform_Linux\n return ReadMountInfo_FromProcFSMounts_ ();\n#elif qPlatform_Windows\n return GetMountedFilesystems_Windows_ ();\n#else\n\t\/\/ @todo - maybe a start on macos would be to walk the directory \/Volumes\n WeakAssertNotImplemented ();\n return {};\n#endif\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved\n *\/\n#include\t\"..\/..\/StroikaPreComp.h\"\n\n#include\t\"..\/..\/Execution\/Exceptions.h\"\n#include\t\"..\/..\/Execution\/ErrNoException.h\"\n\n#include\t\"FStreamSupport.h\"\n\n\n\n\nusing\tnamespace\tStroika::Foundation;\nusing\tnamespace\tStroika::Foundation::Streams;\nusing\tnamespace\tStroika::Foundation::Streams::iostream;\n\n\n\n\n\n\n\/*\n ********************************************************************************\n ********************** iostream::OpenInputFileStream ***************************\n ********************************************************************************\n *\/\nvoid\tStreams::iostream::OpenInputFileStream (ifstream* ifStream, const TString& fileName, ios_base::openmode _Mode)\n{\n\tRequireNotNull (ifStream);\n\tifStream->open (fileName.c_str (), _Mode);\n\tif (!(*ifStream)) {\n\t\t#if\t\tqPlatform_Windows\n\t\t\tExecution::ThrowIfNotERROR_SUCCESS (::GetLastError ());\n\t\t#elif\tqPlatform_POSIX\n\t\t\tExecution::ThrowIfError_errno_t ();\n\t\t\tAssertNotReached ();\/\/ errno sb set\n\t\t#else\n\t\t\tAssertNotImplemented ();\n\t\t#endif\n\t}\n}\n\n\n\n\n\n\n\/*\n ********************************************************************************\n ****************** StreamUtils::OpenOutputFileStream ***************************\n ********************************************************************************\n *\/\nvoid\tStreams::iostream::OpenOutputFileStream (ofstream* ofStream, const TString& fileName, ios_base::openmode _Mode)\n{\n\tRequireNotNull (ofStream);\n\tofStream->open (fileName.c_str (), _Mode);\n\tif (!(*ofStream)) {\n\t\t#if\t\tqPlatform_Windows\n\t\t\tExecution::ThrowIfNotERROR_SUCCESS (::GetLastError ());\n\t\t#elif\tqPlatform_POSIX\n\t\t\tExecution::ThrowIfError_errno_t ();\n\t\t\tAssertNotReached ();\/\/ errno sb set\n\t\t#else\n\t\t\tAssertNotImplemented ();\n\t\t#endif\n\t}\n}\n\n\nfix Streams::iostream::Open-READ\/WRITE Streams now use CATCH_REBIND_FILENAMES_HELPER_() to include filename in exceptions\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved\n *\/\n#include\t\"..\/..\/StroikaPreComp.h\"\n\n#include\t\"..\/..\/Execution\/Exceptions.h\"\n#include\t\"..\/..\/Execution\/ErrNoException.h\"\n#include\t\"..\/..\/IO\/FileAccessException.h\"\n#include\t\"..\/..\/IO\/FileBusyException.h\"\n#include\t\"..\/..\/IO\/FileFormatException.h\"\n\n#include\t\"FStreamSupport.h\"\n\n\n\n\nusing\tnamespace\tStroika::Foundation;\nusing\tnamespace\tStroika::Foundation::Streams;\nusing\tnamespace\tStroika::Foundation::Streams::iostream;\nusing\tnamespace\tStroika::Foundation::IO;\n\n\n\n\n\/*\n * Stuff INSIDE try section raises exceptions. Catch and rethow SOME binding in a new filename (if none was known).\n * Otehr exceptions just ignore (so they auto-propagate)\n *\/\n#define\t\tCATCH_REBIND_FILENAMES_HELPER_(USEFILENAME)\t\\\n\tcatch (const FileBusyException& e) {\t\\\n\t\tif (e.fFileName.empty ()) {\\\n\t\t\tExecution::DoThrow (FileBusyException (USEFILENAME));\\\n\t\t}\\\n\t\tExecution::DoReThrow ();\\\n\t}\\\n\tcatch (const FileAccessException& e) {\t\\\n\t\tif (e.fFileName.empty ()) {\\\n\t\t\tExecution::DoThrow (FileAccessException (USEFILENAME, e.fFileAccessMode));\\\n\t\t}\\\n\t\tExecution::DoReThrow ();\\\n\t}\\\n\tcatch (const FileFormatException& e) {\t\\\n\t\tif (e.fFileName.empty ()) {\\\n\t\t\tExecution::DoThrow (FileFormatException (USEFILENAME));\\\n\t\t}\\\n\t\tExecution::DoReThrow ();\\\n\t}\\\n\n\n\n\n\n\/*\n ********************************************************************************\n ********************** iostream::OpenInputFileStream ***************************\n ********************************************************************************\n *\/\nvoid\tStreams::iostream::OpenInputFileStream (ifstream* ifStream, const TString& fileName, ios_base::openmode _Mode)\n{\n\tRequireNotNull (ifStream);\n\ttry {\n\t\tifStream->open (fileName.c_str (), _Mode);\n\t\tif (!(*ifStream)) {\n\t\t\t#if\t\tqPlatform_Windows\n\t\t\t\tExecution::ThrowIfNotERROR_SUCCESS (::GetLastError ());\n\t\t\t#elif\tqPlatform_POSIX\n\t\t\t\tExecution::ThrowIfError_errno_t ();\n\t\t\t\tAssertNotReached ();\/\/ errno sb set\n\t\t\t#else\n\t\t\t\tAssertNotImplemented ();\n\t\t\t#endif\n\t\t}\n\t}\n\tCATCH_REBIND_FILENAMES_HELPER_(fileName);\n}\n\n\n\n\n\n\n\/*\n ********************************************************************************\n ****************** StreamUtils::OpenOutputFileStream ***************************\n ********************************************************************************\n *\/\nvoid\tStreams::iostream::OpenOutputFileStream (ofstream* ofStream, const TString& fileName, ios_base::openmode _Mode)\n{\n\tRequireNotNull (ofStream);\n\ttry {\n\t\tofStream->open (fileName.c_str (), _Mode);\n\t\tif (!(*ofStream)) {\n\t\t\t#if\t\tqPlatform_Windows\n\t\t\t\tExecution::ThrowIfNotERROR_SUCCESS (::GetLastError ());\n\t\t\t#elif\tqPlatform_POSIX\n\t\t\t\tExecution::ThrowIfError_errno_t ();\n\t\t\t\tAssertNotReached ();\/\/ errno sb set\n\t\t\t#else\n\t\t\t\tAssertNotImplemented ();\n\t\t\t#endif\n\t\t}\n\t}\n\tCATCH_REBIND_FILENAMES_HELPER_(fileName);\n}\n\n\n<|endoftext|>"} {"text":"\/*\n * LootManagerImplementation.cpp\n *\n * Created on: Jun 20, 2011\n * Author: Kyle\n *\/\n\n#include \"engine\/engine.h\"\n\n#include \"LootManager.h\"\n#include \"server\/zone\/objects\/scene\/SceneObject.h\"\n#include \"server\/zone\/objects\/creature\/CreatureObject.h\"\n#include \"server\/zone\/objects\/creature\/AiAgent.h\"\n#include \"server\/zone\/managers\/crafting\/CraftingManager.h\"\n#include \"server\/zone\/managers\/templates\/TemplateManager.h\"\n#include \"server\/zone\/templates\/LootItemTemplate.h\"\n#include \"server\/zone\/templates\/LootGroupTemplate.h\"\n#include \"server\/zone\/ZoneServer.h\"\n#include \"server\/zone\/managers\/stringid\/StringIdManager.h\"\n#include \"LootGroupMap.h\"\n\nvoid LootManagerImplementation::initialize() {\n\tlua = new Lua();\n\tlua->init();\n\n\tinfo(\"Loading configuration.\");\n\n\tif(!loadConfigData()) {\n\n\t\tloadDefaultConfig();\n\n\t\tinfo(\"Failed to load configuration values. Using default.\");\n\t}\n\n\tlootGroupMap = LootGroupMap::instance();\n\tlootGroupMap->initialize();\n\n\tinfo(\"Loaded \" + String::valueOf(lootableMods.size()) + \" lootable stat mods.\", true);\n\tinfo(\"Loaded \" + String::valueOf(lootGroupMap->countLootItemTemplates()) + \" loot items.\", true);\n\tinfo(\"Loaded \" + String::valueOf(lootGroupMap->countLootGroupTemplates()) + \" loot groups.\", true);\n\n\tinfo(\"Initialized.\");\n}\n\nbool LootManagerImplementation::loadConfigFile() {\n\treturn lua->runFile(\"scripts\/managers\/loot_manager.lua\");\n}\n\nbool LootManagerImplementation::loadConfigData() {\n\tif (!loadConfigFile())\n\t\treturn false;\n\n\texceptionalChance = lua->getGlobalFloat(\"exceptionalChance\");\n\texceptionalModifier = lua->getGlobalFloat(\"exceptionalModifier\");\n\tlegendaryChance = lua->getGlobalFloat(\"legendaryChance\");\n\tlegendaryModifier = lua->getGlobalFloat(\"legendaryModifier\");\n\n\tLuaObject lootableModsTable = lua->getGlobalObject(\"lootableStatMods\");\n\n\tif (!lootableModsTable.isValidTable())\n\t\treturn false;\n\n\tfor (int i = 1; i <= lootableModsTable.getTableSize(); ++i) {\n\t\tString mod = lootableModsTable.getStringAt(i);\n\t\tlootableMods.put(mod);\n\t}\n\n\tlootableModsTable.pop();\n\n\treturn true;\n}\n\nvoid LootManagerImplementation::loadDefaultConfig() {\n\n}\n\nvoid LootManagerImplementation::setInitialObjectStats(LootItemTemplate* templateObject, CraftingValues* craftingValues, TangibleObject* prototype) {\n\tSharedTangibleObjectTemplate* tanoTemplate = dynamic_cast(prototype->getObjectTemplate());\n\n\tif (tanoTemplate != NULL) {\n\t\tVector* titles = tanoTemplate->getExperimentalGroupTitles();\n\t\tVector* props = tanoTemplate->getExperimentalSubGroupTitles();\n\t\tVector* mins = tanoTemplate->getExperimentalMin();\n\t\tVector* maxs = tanoTemplate->getExperimentalMax();\n\t\tVector* prec = tanoTemplate->getExperimentalPrecision();\n\n\t\tfor (int i = 0; i < props->size(); ++i) {\n\t\t\tString title = titles->get(i);\n\t\t\tString property = props->get(i);\n\n\t\t\tif (craftingValues->hasProperty(property))\n\t\t\t\tcontinue;\n\n\t\t\tcraftingValues->addExperimentalProperty(property, property, mins->get(i), maxs->get(i), prec->get(i), false);\n\t\t\tif(title == \"null\")\n\t\t\t\tcraftingValues->setHidden(property);\n\t\t}\n\t}\n\n\tVector* customizationData = templateObject->getCustomizationStringNames();\n\tVector >* customizationValues = templateObject->getCustomizationValues();\n\n\tfor (int i = 0; i < customizationData->size(); ++i) {\n\t\tString customizationString = customizationData->get(i);\n\t\tVector* values = &customizationValues->get(i);\n\n\t\tint idx = customizationString.lastIndexOf(\"\/\");\n\n\t\tif (idx != -1)\n\t\t\tcustomizationString = customizationString.subString(idx + 1);\n\n\t\tif (values->size() > 0) {\n\t\t\tint randomValue = values->get(System::random(values->size() - 1));\n\n\t\t\tprototype->setCustomizationVariable(customizationString, randomValue, false);\n\t\t}\n\t}\n}\n\nvoid LootManagerImplementation::setCustomObjectName(TangibleObject* object, LootItemTemplate* templateObject) {\n\tString customName = templateObject->getCustomObjectName();\n\n\tif (!customName.isEmpty()) {\n\t\tif (customName.charAt(0) == '@') {\n\t\t\tStringId stringId(customName);\n\n\t\t\tobject->setObjectName(stringId);\n\t\t} else {\n\t\t\tobject->setCustomObjectName(customName, false);\n\t\t}\n\t}\n}\n\nint LootManagerImplementation::calculateLootCredits(int level) {\n\tint maxcredits = (int) round((.03f * level * level) + (3 * level) + 50);\n\tint mincredits = (int) round((((float) maxcredits) * .5f) + (2.0f * level));\n\n\tint credits = mincredits + System::random(maxcredits - mincredits);\n\n\treturn credits;\n}\n\nTangibleObject* LootManagerImplementation::createLootObject(LootItemTemplate* templateObject, int level) {\n\n\tif(level > 300)\n\t\tlevel = 300;\n\n\tString directTemplateObject = templateObject->getDirectObjectTemplate();\n\n\tManagedReference prototype = dynamic_cast (zoneServer->createObject(directTemplateObject.hashCode(), 2));\n\n\tif (prototype == NULL)\n\t\treturn NULL;\n\n\tprototype->createChildObjects();\n\n\tString serial = craftingManager->generateSerial();\n\tprototype->setSerialNumber(serial);\n\n\tCraftingValues craftingValues = templateObject->getCraftingValuesCopy();\n\n\tsetInitialObjectStats(templateObject, &craftingValues, prototype);\n\n\tsetCustomObjectName(prototype, templateObject);\n\n\tfloat excMod = 1.0;\n\n\tif (System::random(exceptionalChance) == exceptionalChance) {\n\t\tUnicodeString objectName = prototype->getCustomObjectName();\n\t\tuint32 bitmask = prototype->getOptionsBitmask() | OptionBitmask::YELLOW;\n\n\t\tif (objectName.isEmpty())\n\t\t\tobjectName = StringIdManager::instance()->getStringId(prototype->getObjectName()->getFullPath().hashCode());\n\n\t\tUnicodeString newName = objectName + \" (Exceptional)\";\n\t\tprototype->setCustomObjectName(newName, false);\n\n\t\texcMod = exceptionalModifier;\n\n\t\tprototype->setOptionsBitmask(bitmask, false);\n\t} else if (System::random(legendaryChance) == legendaryChance) {\n\t\tUnicodeString objectName = prototype->getCustomObjectName();\n\t\tuint32 bitmask = prototype->getOptionsBitmask() | OptionBitmask::YELLOW;\n\n\t\tif (objectName.isEmpty())\n\t\t\tobjectName = StringIdManager::instance()->getStringId(prototype->getObjectName()->getFullPath().hashCode());\n\n\t\tUnicodeString newName = objectName + \" (Legendary)\";\n\t\tprototype->setCustomObjectName(newName, false);\n\n\t\texcMod = legendaryModifier;\n\n\t\tprototype->setOptionsBitmask(bitmask, false);\n\t}\n\n\tString subtitle;\n\n\tfloat percentage = System::random(10000) \/ 10000.f; \/\/Generate a base percentage. We will deviate slightly from this on each stat.\n\n\tfor (int i = 0; i < craftingValues.getExperimentalPropertySubtitleSize(); ++i) {\n\t\tsubtitle = craftingValues.getExperimentalPropertySubtitle(i);\n\n\t\tif (subtitle == \"hitpoints\")\n\t\t\tcontinue;\n\n\t\tfloat min = craftingValues.getMinValue(subtitle);\n\t\tfloat max = craftingValues.getMaxValue(subtitle);\n\n\t\tif(min == max)\n\t\t\tcontinue;\n\n\t\tif (subtitle != \"useCount\" &&\n\t\t\t\tsubtitle != \"quantity\" &&\n\t\t\t\tsubtitle != \"charges\" &&\n\t\t\t\tsubtitle != \"uses\" &&\n\t\t\t\tsubtitle != \"charge\") {\n\n\t\t\tfloat minMod = (max >= min) ? 2000.f : -2000.f;\n\t\t\tfloat maxMod = (max >= min) ? 500.f : -500.f;\n\n\t\t\tmin = (min * level \/ minMod) + min;\n\t\t\tmax = (max * level \/ maxMod) + max;\n\n\t\t\tif (max >= min) {\n\t\t\t\tmin *= excMod;\n\t\t\t\tmax *= excMod;\n\t\t\t} else {\n\t\t\t\tmin \/= excMod;\n\t\t\t\tmax \/= excMod;\n\t\t\t}\n\n\t\t\tcraftingValues.setMinValue(subtitle, min);\n\t\t\tcraftingValues.setMaxValue(subtitle, max);\n\t\t}\n\n\t\tfloat deviation = (((float) System::random(400)) - 200) \/ 1000.f; \/\/Deviate up to 2%\n\n\t\tcraftingValues.setCurrentPercentage(subtitle, percentage + deviation);\n\t}\n\n\t\/\/ Use percentages to recalculate the values\n\tcraftingValues.recalculateValues(false);\n\n\tcraftingValues.addExperimentalProperty(\"creatureLevel\", \"creatureLevel\", level, level, 0, false);\n\tcraftingValues.setHidden(\"creatureLevel\");\n\n\t\/\/ Update the Tano with new values\n\tprototype->updateCraftingValues(&craftingValues, true);\n\n\treturn prototype;\n}\n\nbool LootManagerImplementation::createLoot(SceneObject* container, AiAgent* creature) {\n\tLootGroupCollection* lootCollection = creature->getLootGroups();\n\n\tif (lootCollection == NULL)\n\t\treturn false;\n\n\tfor (int i = 0; i < lootCollection->count(); ++i) {\n\t\tLootGroupCollectionEntry* entry = lootCollection->get(i);\n\t\tint lootChance = entry->getLootChance();\n\n\t\tif (lootChance <= 0)\n\t\t\tcontinue;\n\n\t\tint roll = System::random(10000000);\n\n\t\tif (roll > lootChance)\n\t\t\tcontinue;\n\n\t\tint tempChance = 0; \/\/Start at 0.\n\n\t\tLootGroups* lootGroups = entry->getLootGroups();\n\n\t\t\/\/Select the loot group to use.\n\t\tfor (int i = 0; i < lootGroups->count(); ++i) {\n\t\t\tLootGroupEntry* entry = lootGroups->get(i);\n\n\t\t\ttempChance += entry->getLootChance();\n\n\t\t\t\/\/Is this entry lower than the roll? If yes, then we want to try the next entry.\n\t\t\tif (tempChance < roll)\n\t\t\t\tcontinue;\n\n\t\t\tcreateLoot(container, entry->getLootGroupName(), creature->getLevel());\n\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn true;\n}\n\nbool LootManagerImplementation::createLoot(SceneObject* container, const String& lootGroup, int level) {\n\tif (container->hasFullContainerObjects())\n\t\treturn false;\n\n\tReference group = lootGroupMap->getLootGroupTemplate(lootGroup);\n\n\tif (group == NULL) {\n\t\twarning(\"Loot group template requested does not exist: \" + lootGroup);\n\t\treturn false;\n\t}\n\n\t\/\/Now we do the second roll for the item out of the group.\n\tint roll = System::random(10000000);\n\n\tReference itemTemplate = lootGroupMap->getLootItemTemplate(group->getLootItemTemplateForRoll(roll));\n\n\tif (itemTemplate == NULL) {\n\t\twarning(\"Loot item template requested does not exist: \" + group->getLootItemTemplateForRoll(roll) + \" for templateName: \" + group->getTemplateName());\n\t\treturn false;\n\t}\n\n\tTangibleObject* obj = createLootObject(itemTemplate, level);\n\n\tif (obj == NULL)\n\t\treturn false;\n\n\tif (container->transferObject(obj, -1, false))\n\t\tcontainer->broadcastObject(obj, true);\n\n\n\treturn true;\n}\n[added] debug message when creating unexistent loot\/*\n * LootManagerImplementation.cpp\n *\n * Created on: Jun 20, 2011\n * Author: Kyle\n *\/\n\n#include \"engine\/engine.h\"\n\n#include \"LootManager.h\"\n#include \"server\/zone\/objects\/scene\/SceneObject.h\"\n#include \"server\/zone\/objects\/creature\/CreatureObject.h\"\n#include \"server\/zone\/objects\/creature\/AiAgent.h\"\n#include \"server\/zone\/managers\/crafting\/CraftingManager.h\"\n#include \"server\/zone\/managers\/templates\/TemplateManager.h\"\n#include \"server\/zone\/templates\/LootItemTemplate.h\"\n#include \"server\/zone\/templates\/LootGroupTemplate.h\"\n#include \"server\/zone\/ZoneServer.h\"\n#include \"server\/zone\/managers\/stringid\/StringIdManager.h\"\n#include \"LootGroupMap.h\"\n\nvoid LootManagerImplementation::initialize() {\n\tlua = new Lua();\n\tlua->init();\n\n\tinfo(\"Loading configuration.\");\n\n\tif(!loadConfigData()) {\n\n\t\tloadDefaultConfig();\n\n\t\tinfo(\"Failed to load configuration values. Using default.\");\n\t}\n\n\tlootGroupMap = LootGroupMap::instance();\n\tlootGroupMap->initialize();\n\n\tinfo(\"Loaded \" + String::valueOf(lootableMods.size()) + \" lootable stat mods.\", true);\n\tinfo(\"Loaded \" + String::valueOf(lootGroupMap->countLootItemTemplates()) + \" loot items.\", true);\n\tinfo(\"Loaded \" + String::valueOf(lootGroupMap->countLootGroupTemplates()) + \" loot groups.\", true);\n\n\tinfo(\"Initialized.\");\n}\n\nbool LootManagerImplementation::loadConfigFile() {\n\treturn lua->runFile(\"scripts\/managers\/loot_manager.lua\");\n}\n\nbool LootManagerImplementation::loadConfigData() {\n\tif (!loadConfigFile())\n\t\treturn false;\n\n\texceptionalChance = lua->getGlobalFloat(\"exceptionalChance\");\n\texceptionalModifier = lua->getGlobalFloat(\"exceptionalModifier\");\n\tlegendaryChance = lua->getGlobalFloat(\"legendaryChance\");\n\tlegendaryModifier = lua->getGlobalFloat(\"legendaryModifier\");\n\n\tLuaObject lootableModsTable = lua->getGlobalObject(\"lootableStatMods\");\n\n\tif (!lootableModsTable.isValidTable())\n\t\treturn false;\n\n\tfor (int i = 1; i <= lootableModsTable.getTableSize(); ++i) {\n\t\tString mod = lootableModsTable.getStringAt(i);\n\t\tlootableMods.put(mod);\n\t}\n\n\tlootableModsTable.pop();\n\n\treturn true;\n}\n\nvoid LootManagerImplementation::loadDefaultConfig() {\n\n}\n\nvoid LootManagerImplementation::setInitialObjectStats(LootItemTemplate* templateObject, CraftingValues* craftingValues, TangibleObject* prototype) {\n\tSharedTangibleObjectTemplate* tanoTemplate = dynamic_cast(prototype->getObjectTemplate());\n\n\tif (tanoTemplate != NULL) {\n\t\tVector* titles = tanoTemplate->getExperimentalGroupTitles();\n\t\tVector* props = tanoTemplate->getExperimentalSubGroupTitles();\n\t\tVector* mins = tanoTemplate->getExperimentalMin();\n\t\tVector* maxs = tanoTemplate->getExperimentalMax();\n\t\tVector* prec = tanoTemplate->getExperimentalPrecision();\n\n\t\tfor (int i = 0; i < props->size(); ++i) {\n\t\t\tString title = titles->get(i);\n\t\t\tString property = props->get(i);\n\n\t\t\tif (craftingValues->hasProperty(property))\n\t\t\t\tcontinue;\n\n\t\t\tcraftingValues->addExperimentalProperty(property, property, mins->get(i), maxs->get(i), prec->get(i), false);\n\t\t\tif(title == \"null\")\n\t\t\t\tcraftingValues->setHidden(property);\n\t\t}\n\t}\n\n\tVector* customizationData = templateObject->getCustomizationStringNames();\n\tVector >* customizationValues = templateObject->getCustomizationValues();\n\n\tfor (int i = 0; i < customizationData->size(); ++i) {\n\t\tString customizationString = customizationData->get(i);\n\t\tVector* values = &customizationValues->get(i);\n\n\t\tint idx = customizationString.lastIndexOf(\"\/\");\n\n\t\tif (idx != -1)\n\t\t\tcustomizationString = customizationString.subString(idx + 1);\n\n\t\tif (values->size() > 0) {\n\t\t\tint randomValue = values->get(System::random(values->size() - 1));\n\n\t\t\tprototype->setCustomizationVariable(customizationString, randomValue, false);\n\t\t}\n\t}\n}\n\nvoid LootManagerImplementation::setCustomObjectName(TangibleObject* object, LootItemTemplate* templateObject) {\n\tString customName = templateObject->getCustomObjectName();\n\n\tif (!customName.isEmpty()) {\n\t\tif (customName.charAt(0) == '@') {\n\t\t\tStringId stringId(customName);\n\n\t\t\tobject->setObjectName(stringId);\n\t\t} else {\n\t\t\tobject->setCustomObjectName(customName, false);\n\t\t}\n\t}\n}\n\nint LootManagerImplementation::calculateLootCredits(int level) {\n\tint maxcredits = (int) round((.03f * level * level) + (3 * level) + 50);\n\tint mincredits = (int) round((((float) maxcredits) * .5f) + (2.0f * level));\n\n\tint credits = mincredits + System::random(maxcredits - mincredits);\n\n\treturn credits;\n}\n\nTangibleObject* LootManagerImplementation::createLootObject(LootItemTemplate* templateObject, int level) {\n\n\tif(level > 300)\n\t\tlevel = 300;\n\n\tString directTemplateObject = templateObject->getDirectObjectTemplate();\n\n\tManagedReference prototype = dynamic_cast (zoneServer->createObject(directTemplateObject.hashCode(), 2));\n\n\tif (prototype == NULL) {\n\t\terror(\"could not create loot object: \" + directTemplateObject);\n\t\treturn NULL;\n\t}\n\n\tprototype->createChildObjects();\n\n\tString serial = craftingManager->generateSerial();\n\tprototype->setSerialNumber(serial);\n\n\tCraftingValues craftingValues = templateObject->getCraftingValuesCopy();\n\n\tsetInitialObjectStats(templateObject, &craftingValues, prototype);\n\n\tsetCustomObjectName(prototype, templateObject);\n\n\tfloat excMod = 1.0;\n\n\tif (System::random(exceptionalChance) == exceptionalChance) {\n\t\tUnicodeString objectName = prototype->getCustomObjectName();\n\t\tuint32 bitmask = prototype->getOptionsBitmask() | OptionBitmask::YELLOW;\n\n\t\tif (objectName.isEmpty())\n\t\t\tobjectName = StringIdManager::instance()->getStringId(prototype->getObjectName()->getFullPath().hashCode());\n\n\t\tUnicodeString newName = objectName + \" (Exceptional)\";\n\t\tprototype->setCustomObjectName(newName, false);\n\n\t\texcMod = exceptionalModifier;\n\n\t\tprototype->setOptionsBitmask(bitmask, false);\n\t} else if (System::random(legendaryChance) == legendaryChance) {\n\t\tUnicodeString objectName = prototype->getCustomObjectName();\n\t\tuint32 bitmask = prototype->getOptionsBitmask() | OptionBitmask::YELLOW;\n\n\t\tif (objectName.isEmpty())\n\t\t\tobjectName = StringIdManager::instance()->getStringId(prototype->getObjectName()->getFullPath().hashCode());\n\n\t\tUnicodeString newName = objectName + \" (Legendary)\";\n\t\tprototype->setCustomObjectName(newName, false);\n\n\t\texcMod = legendaryModifier;\n\n\t\tprototype->setOptionsBitmask(bitmask, false);\n\t}\n\n\tString subtitle;\n\n\tfloat percentage = System::random(10000) \/ 10000.f; \/\/Generate a base percentage. We will deviate slightly from this on each stat.\n\n\tfor (int i = 0; i < craftingValues.getExperimentalPropertySubtitleSize(); ++i) {\n\t\tsubtitle = craftingValues.getExperimentalPropertySubtitle(i);\n\n\t\tif (subtitle == \"hitpoints\")\n\t\t\tcontinue;\n\n\t\tfloat min = craftingValues.getMinValue(subtitle);\n\t\tfloat max = craftingValues.getMaxValue(subtitle);\n\n\t\tif(min == max)\n\t\t\tcontinue;\n\n\t\tif (subtitle != \"useCount\" &&\n\t\t\t\tsubtitle != \"quantity\" &&\n\t\t\t\tsubtitle != \"charges\" &&\n\t\t\t\tsubtitle != \"uses\" &&\n\t\t\t\tsubtitle != \"charge\") {\n\n\t\t\tfloat minMod = (max >= min) ? 2000.f : -2000.f;\n\t\t\tfloat maxMod = (max >= min) ? 500.f : -500.f;\n\n\t\t\tmin = (min * level \/ minMod) + min;\n\t\t\tmax = (max * level \/ maxMod) + max;\n\n\t\t\tif (max >= min) {\n\t\t\t\tmin *= excMod;\n\t\t\t\tmax *= excMod;\n\t\t\t} else {\n\t\t\t\tmin \/= excMod;\n\t\t\t\tmax \/= excMod;\n\t\t\t}\n\n\t\t\tcraftingValues.setMinValue(subtitle, min);\n\t\t\tcraftingValues.setMaxValue(subtitle, max);\n\t\t}\n\n\t\tfloat deviation = (((float) System::random(400)) - 200) \/ 1000.f; \/\/Deviate up to 2%\n\n\t\tcraftingValues.setCurrentPercentage(subtitle, percentage + deviation);\n\t}\n\n\t\/\/ Use percentages to recalculate the values\n\tcraftingValues.recalculateValues(false);\n\n\tcraftingValues.addExperimentalProperty(\"creatureLevel\", \"creatureLevel\", level, level, 0, false);\n\tcraftingValues.setHidden(\"creatureLevel\");\n\n\t\/\/ Update the Tano with new values\n\tprototype->updateCraftingValues(&craftingValues, true);\n\n\treturn prototype;\n}\n\nbool LootManagerImplementation::createLoot(SceneObject* container, AiAgent* creature) {\n\tLootGroupCollection* lootCollection = creature->getLootGroups();\n\n\tif (lootCollection == NULL)\n\t\treturn false;\n\n\tfor (int i = 0; i < lootCollection->count(); ++i) {\n\t\tLootGroupCollectionEntry* entry = lootCollection->get(i);\n\t\tint lootChance = entry->getLootChance();\n\n\t\tif (lootChance <= 0)\n\t\t\tcontinue;\n\n\t\tint roll = System::random(10000000);\n\n\t\tif (roll > lootChance)\n\t\t\tcontinue;\n\n\t\tint tempChance = 0; \/\/Start at 0.\n\n\t\tLootGroups* lootGroups = entry->getLootGroups();\n\n\t\t\/\/Select the loot group to use.\n\t\tfor (int i = 0; i < lootGroups->count(); ++i) {\n\t\t\tLootGroupEntry* entry = lootGroups->get(i);\n\n\t\t\ttempChance += entry->getLootChance();\n\n\t\t\t\/\/Is this entry lower than the roll? If yes, then we want to try the next entry.\n\t\t\tif (tempChance < roll)\n\t\t\t\tcontinue;\n\n\t\t\tcreateLoot(container, entry->getLootGroupName(), creature->getLevel());\n\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn true;\n}\n\nbool LootManagerImplementation::createLoot(SceneObject* container, const String& lootGroup, int level) {\n\tif (container->hasFullContainerObjects())\n\t\treturn false;\n\n\tReference group = lootGroupMap->getLootGroupTemplate(lootGroup);\n\n\tif (group == NULL) {\n\t\twarning(\"Loot group template requested does not exist: \" + lootGroup);\n\t\treturn false;\n\t}\n\n\t\/\/Now we do the second roll for the item out of the group.\n\tint roll = System::random(10000000);\n\n\tReference itemTemplate = lootGroupMap->getLootItemTemplate(group->getLootItemTemplateForRoll(roll));\n\n\tif (itemTemplate == NULL) {\n\t\twarning(\"Loot item template requested does not exist: \" + group->getLootItemTemplateForRoll(roll) + \" for templateName: \" + group->getTemplateName());\n\t\treturn false;\n\t}\n\n\tTangibleObject* obj = createLootObject(itemTemplate, level);\n\n\tif (obj == NULL)\n\t\treturn false;\n\n\tif (container->transferObject(obj, -1, false))\n\t\tcontainer->broadcastObject(obj, true);\n\n\n\treturn true;\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n\n#include \"otbWrapperCommandLineLauncher.h\"\n#include \"otb_tinyxml.h\"\n#include \n\n#ifdef OTB_USE_MPI\n#include \"otbMPIConfig.h\"\n#endif\n\nconst std::string GetChildNodeTextOf(TiXmlElement *parentElement, std::string key);\nstd::string PrepareExpressionFromXML(std::string filename);\nstd::vector PrepareVectorExpressionFromXML(std::string filename);\nstd::string CleanWord(const std::string & word);\n\n\nstd::string PrepareExpressionFromXML(std::string filename)\n{\n std::string expression;\n\n if(filename.empty())\n {\n std::cerr <<\"Input XML Filename is empty\" << std::endl;\n return expression;\n }\n std::string ext = filename.substr(filename.size()-4,filename.size());\n if(ext != \".xml\" )\n std::cerr << ext << \" is a wrong extension: Expected .xml \" << __FILE__ << std::endl;\n\n \/\/ Open the xml file\n TiXmlDocument doc;\n\n \/\/Use itksys::SystemTools::FOpen() and close it below because\n \/\/TiXmlDocument::TiXmlFileOpen( ) is not exposed from tinyXML library. Even\n \/\/though its available in the TiXmlDocument::SaveFile().\n FILE* fp = itksys::SystemTools::Fopen(filename.c_str(), \"rb\");\n\n if (!doc.LoadFile(fp , TIXML_ENCODING_UTF8))\n {\n std::cerr << \"Can't open file \" << filename << std::endl;\n fclose(fp);\n exit(1);\n\n }\n\n TiXmlHandle handle(&doc);\n\n TiXmlElement *n_OTB;\n n_OTB = handle.FirstChild(\"OTB\").Element();\n\n if(!n_OTB)\n {\n std::string info = \"Input XML file \" + filename + \" is invalid.\";\n std::cerr << info << std::endl;\n fclose(fp);\n exit(1);\n }\n\n TiXmlElement *n_AppNode = n_OTB->FirstChildElement(\"application\");\n\n std::string moduleName;\n moduleName = GetChildNodeTextOf(n_AppNode, \"name\");\n \/*\n AddMetaData(\"appname\", app_Name);\n\n app_Descr = this_->GetChildNodeTextOf(n_AppNode, \"descr\");\n AddMetaData(\"appdescr\", app_Descr);\n\n TiXmlElement* n_Doc = n_AppNode->FirstChildElement(\"doc\");\n\n std::string doc_Name, doc_Descr, doc_Author, doc_Limitation, doc_SeeAlso;\n\n doc_Name = this_->GetChildNodeTextOf(n_Doc, \"name\");\n AddMetaData(\"docname\", doc_Name);\n\n doc_Descr = this_->GetChildNodeTextOf(n_Doc, \"longdescr\");\n AddMetaData(\"doclongdescr\", doc_Descr);\n\n doc_Author = this_->GetChildNodeTextOf(n_Doc, \"authors\");\n AddMetaData(\"docauthors\", doc_Author);\n\n doc_Limitation = this_->GetChildNodeTextOf(n_Doc, \"limitations\");\n AddMetaData(\"doclimitations\", doc_Limitation);\n\n doc_SeeAlso = this_->GetChildNodeTextOf(n_Doc, \"seealso\");\n AddMetaData(\"docseealso\", doc_SeeAlso);\n *\/\n\n expression.append(moduleName);\n\n for( TiXmlElement* n_Parameter = n_AppNode->FirstChildElement(\"parameter\"); n_Parameter != ITK_NULLPTR;\n n_Parameter = n_Parameter->NextSiblingElement() )\n {\n std::string key=\"-\";\n key.append(GetChildNodeTextOf(n_Parameter, \"key\"));\n\n TiXmlElement* n_Values = ITK_NULLPTR;\n n_Values = n_Parameter->FirstChildElement(\"values\");\n if(n_Values)\n {\n std::string values;\n for(TiXmlElement* n_Value = n_Values->FirstChildElement(\"value\"); n_Value != ITK_NULLPTR;\n n_Value = n_Value->NextSiblingElement())\n {\n values.append(n_Value->GetText());\n values.append(\" \");\n }\n values = values.substr(0,values.size()-1);\n expression.append(\" \");\n expression.append(key);\n expression.append(\" \");\n expression.append(values);\n }\n else\n {\n std::string value;\n value = GetChildNodeTextOf(n_Parameter, \"value\");\n\n expression.append(\" \");\n expression.append(key);\n expression.append(\" \");\n expression.append(value);\n\n std::string type = GetChildNodeTextOf(n_Parameter, \"type\");\n if (type == \"OutputImage\")\n {\n std::string t = GetChildNodeTextOf(n_Parameter, \"pixtype\");\n expression.append(\" \");\n expression.append(t);\n }\n }\n }\n\n fclose(fp);\n\n return expression;\n}\n\nstd::vector PrepareVectorExpressionFromXML(std::string filename)\n{\n std::vector expression;\n\n if(filename.empty())\n {\n std::cerr <<\"Input XML Filename is empty\" << std::endl;\n return expression;\n }\n std::string ext = filename.substr(filename.size()-4,filename.size());\n if(ext != \".xml\" )\n std::cerr << ext << \" is a wrong extension: Expected .xml \" << __FILE__ << std::endl;\n\n \/\/ Open the xml file\n TiXmlDocument doc;\n\n \/\/Use itksys::SystemTools::FOpen() and close it below because\n \/\/TiXmlDocument::TiXmlFileOpen( ) is not exposed from tinyXML library. Even\n \/\/though its available in the TiXmlDocument::SaveFile().\n FILE* fp = itksys::SystemTools::Fopen(filename.c_str(), \"rb\");\n\n if (!doc.LoadFile(fp , TIXML_ENCODING_UTF8))\n {\n std::cerr << \"Can't open file \" << filename << std::endl;\n fclose(fp);\n exit(1);\n\n }\n\n TiXmlHandle handle(&doc);\n\n TiXmlElement *n_OTB;\n n_OTB = handle.FirstChild(\"OTB\").Element();\n\n if(!n_OTB)\n {\n std::string info = \"Input XML file \" + filename + \" is invalid.\";\n std::cerr << info << std::endl;\n fclose(fp);\n exit(1);\n }\n\n TiXmlElement *n_AppNode = n_OTB->FirstChildElement(\"application\");\n\n std::string moduleName;\n moduleName = GetChildNodeTextOf(n_AppNode, \"name\");\n\n expression.push_back(CleanWord(moduleName));\n\n for( TiXmlElement* n_Parameter = n_AppNode->FirstChildElement(\"parameter\"); n_Parameter != ITK_NULLPTR;\n n_Parameter = n_Parameter->NextSiblingElement() )\n {\n std::string key=\"-\";\n key.append(GetChildNodeTextOf(n_Parameter, \"key\"));\n expression.push_back(CleanWord(key));\n\n TiXmlElement* n_Values = ITK_NULLPTR;\n n_Values = n_Parameter->FirstChildElement(\"values\");\n if(n_Values)\n {\n std::string values;\n for(TiXmlElement* n_Value = n_Values->FirstChildElement(\"value\"); n_Value != ITK_NULLPTR;\n n_Value = n_Value->NextSiblingElement())\n {\n expression.push_back(CleanWord(n_Value->GetText()));\n }\n }\n else\n {\n std::string value;\n value = GetChildNodeTextOf(n_Parameter, \"value\");\n expression.push_back(CleanWord(value));\n\n std::string type = GetChildNodeTextOf(n_Parameter, \"type\");\n if (type == \"OutputImage\")\n {\n std::string t = GetChildNodeTextOf(n_Parameter, \"pixtype\");\n expression.push_back(CleanWord(t));\n }\n }\n }\n\n fclose(fp);\n\n return expression;\n}\n\nstd::string CleanWord(const std::string & word)\n{\n std::string res(\"\");\n \/\/ Suppress whitespace characters at the beginning and ending of the string\n std::string::size_type cleanStart = word.find_first_not_of(\" \\t\");\n std::string::size_type cleanEnd = word.find_last_not_of(\" \\t\\f\\v\\n\\r\");\n if (cleanEnd != std::string::npos)\n {\n res = word.substr(cleanStart,cleanEnd+1);\n }\n return res;\n}\n\nint main(int argc, char* argv[])\n{\n #ifdef OTB_USE_MPI\n otb::MPIConfig::Instance()->Init(argc,argv);\n #endif\n \n if (argc < 2)\n {\n std::cerr << \"Usage : \" << argv[0] << \" module_name [MODULEPATH] [arguments]\" << std::endl;\n return EXIT_FAILURE;\n }\n\n std::vector vexp;\n \n std::string exp;\n if (strcmp(argv[1], \"-inxml\") == 0)\n {\n \/\/exp = PrepareExpressionFromXML(argv[2]);\n vexp = PrepareVectorExpressionFromXML(argv[2]);\n }\n else\n {\n \/\/ Construct the string expression\n for (int i = 1; i < argc; i++)\n {\n \/*if (i != argc - 1)\n {\n exp.append(argv[i]);\n exp.append(\" \");\n }\n else\n {\n exp.append(argv[i]);\n }*\/\n std::string strarg(argv[i]);\n std::string cleanArg = CleanWord(strarg);\n if (cleanArg.empty())\n {\n \/\/ Empty argument !\n continue;\n }\n vexp.push_back(cleanArg);\n }\n }\n \/\/ std::cerr << exp << \":\\n\";\n\n typedef otb::Wrapper::CommandLineLauncher LauncherType;\n LauncherType::Pointer launcher = LauncherType::New();\n\n \/\/if (launcher->Load(exp) == true)\n if (launcher->Load(vexp) == true)\n {\n if (launcher->ExecuteAndWriteOutput() == false)\n {\n return EXIT_FAILURE;\n }\n }\n else\n {\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n\nconst std::string GetChildNodeTextOf(TiXmlElement *parentElement, std::string key)\n{\n std::string value=\"\";\n\n if(parentElement)\n {\n TiXmlElement* childElement = ITK_NULLPTR;\n childElement = parentElement->FirstChildElement(key.c_str());\n\n \/\/same as childElement->GetText() does but that call is failing if there is\n \/\/no such node.\n \/\/but the below code works and is a replacement for GetText()\n if(childElement)\n {\n const TiXmlNode* child = childElement->FirstChild();\n if ( child )\n {\n const TiXmlText* childText = child->ToText();\n if ( childText )\n {\n value = childText->Value();\n }\n }\n }\n }\n return value;\n}\nBUG: Fix trailing whitespace trimming in otbApplicationLauncherCommandLine (kindly provided by Laurentiu Nicola)\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n\n#include \"otbWrapperCommandLineLauncher.h\"\n#include \"otb_tinyxml.h\"\n#include \n\n#ifdef OTB_USE_MPI\n#include \"otbMPIConfig.h\"\n#endif\n\nconst std::string GetChildNodeTextOf(TiXmlElement *parentElement, std::string key);\nstd::string PrepareExpressionFromXML(std::string filename);\nstd::vector PrepareVectorExpressionFromXML(std::string filename);\nstd::string CleanWord(const std::string & word);\n\n\nstd::string PrepareExpressionFromXML(std::string filename)\n{\n std::string expression;\n\n if(filename.empty())\n {\n std::cerr <<\"Input XML Filename is empty\" << std::endl;\n return expression;\n }\n std::string ext = filename.substr(filename.size()-4,filename.size());\n if(ext != \".xml\" )\n std::cerr << ext << \" is a wrong extension: Expected .xml \" << __FILE__ << std::endl;\n\n \/\/ Open the xml file\n TiXmlDocument doc;\n\n \/\/Use itksys::SystemTools::FOpen() and close it below because\n \/\/TiXmlDocument::TiXmlFileOpen( ) is not exposed from tinyXML library. Even\n \/\/though its available in the TiXmlDocument::SaveFile().\n FILE* fp = itksys::SystemTools::Fopen(filename.c_str(), \"rb\");\n\n if (!doc.LoadFile(fp , TIXML_ENCODING_UTF8))\n {\n std::cerr << \"Can't open file \" << filename << std::endl;\n fclose(fp);\n exit(1);\n\n }\n\n TiXmlHandle handle(&doc);\n\n TiXmlElement *n_OTB;\n n_OTB = handle.FirstChild(\"OTB\").Element();\n\n if(!n_OTB)\n {\n std::string info = \"Input XML file \" + filename + \" is invalid.\";\n std::cerr << info << std::endl;\n fclose(fp);\n exit(1);\n }\n\n TiXmlElement *n_AppNode = n_OTB->FirstChildElement(\"application\");\n\n std::string moduleName;\n moduleName = GetChildNodeTextOf(n_AppNode, \"name\");\n \/*\n AddMetaData(\"appname\", app_Name);\n\n app_Descr = this_->GetChildNodeTextOf(n_AppNode, \"descr\");\n AddMetaData(\"appdescr\", app_Descr);\n\n TiXmlElement* n_Doc = n_AppNode->FirstChildElement(\"doc\");\n\n std::string doc_Name, doc_Descr, doc_Author, doc_Limitation, doc_SeeAlso;\n\n doc_Name = this_->GetChildNodeTextOf(n_Doc, \"name\");\n AddMetaData(\"docname\", doc_Name);\n\n doc_Descr = this_->GetChildNodeTextOf(n_Doc, \"longdescr\");\n AddMetaData(\"doclongdescr\", doc_Descr);\n\n doc_Author = this_->GetChildNodeTextOf(n_Doc, \"authors\");\n AddMetaData(\"docauthors\", doc_Author);\n\n doc_Limitation = this_->GetChildNodeTextOf(n_Doc, \"limitations\");\n AddMetaData(\"doclimitations\", doc_Limitation);\n\n doc_SeeAlso = this_->GetChildNodeTextOf(n_Doc, \"seealso\");\n AddMetaData(\"docseealso\", doc_SeeAlso);\n *\/\n\n expression.append(moduleName);\n\n for( TiXmlElement* n_Parameter = n_AppNode->FirstChildElement(\"parameter\"); n_Parameter != ITK_NULLPTR;\n n_Parameter = n_Parameter->NextSiblingElement() )\n {\n std::string key=\"-\";\n key.append(GetChildNodeTextOf(n_Parameter, \"key\"));\n\n TiXmlElement* n_Values = ITK_NULLPTR;\n n_Values = n_Parameter->FirstChildElement(\"values\");\n if(n_Values)\n {\n std::string values;\n for(TiXmlElement* n_Value = n_Values->FirstChildElement(\"value\"); n_Value != ITK_NULLPTR;\n n_Value = n_Value->NextSiblingElement())\n {\n values.append(n_Value->GetText());\n values.append(\" \");\n }\n values = values.substr(0,values.size()-1);\n expression.append(\" \");\n expression.append(key);\n expression.append(\" \");\n expression.append(values);\n }\n else\n {\n std::string value;\n value = GetChildNodeTextOf(n_Parameter, \"value\");\n\n expression.append(\" \");\n expression.append(key);\n expression.append(\" \");\n expression.append(value);\n\n std::string type = GetChildNodeTextOf(n_Parameter, \"type\");\n if (type == \"OutputImage\")\n {\n std::string t = GetChildNodeTextOf(n_Parameter, \"pixtype\");\n expression.append(\" \");\n expression.append(t);\n }\n }\n }\n\n fclose(fp);\n\n return expression;\n}\n\nstd::vector PrepareVectorExpressionFromXML(std::string filename)\n{\n std::vector expression;\n\n if(filename.empty())\n {\n std::cerr <<\"Input XML Filename is empty\" << std::endl;\n return expression;\n }\n std::string ext = filename.substr(filename.size()-4,filename.size());\n if(ext != \".xml\" )\n std::cerr << ext << \" is a wrong extension: Expected .xml \" << __FILE__ << std::endl;\n\n \/\/ Open the xml file\n TiXmlDocument doc;\n\n \/\/Use itksys::SystemTools::FOpen() and close it below because\n \/\/TiXmlDocument::TiXmlFileOpen( ) is not exposed from tinyXML library. Even\n \/\/though its available in the TiXmlDocument::SaveFile().\n FILE* fp = itksys::SystemTools::Fopen(filename.c_str(), \"rb\");\n\n if (!doc.LoadFile(fp , TIXML_ENCODING_UTF8))\n {\n std::cerr << \"Can't open file \" << filename << std::endl;\n fclose(fp);\n exit(1);\n\n }\n\n TiXmlHandle handle(&doc);\n\n TiXmlElement *n_OTB;\n n_OTB = handle.FirstChild(\"OTB\").Element();\n\n if(!n_OTB)\n {\n std::string info = \"Input XML file \" + filename + \" is invalid.\";\n std::cerr << info << std::endl;\n fclose(fp);\n exit(1);\n }\n\n TiXmlElement *n_AppNode = n_OTB->FirstChildElement(\"application\");\n\n std::string moduleName;\n moduleName = GetChildNodeTextOf(n_AppNode, \"name\");\n\n expression.push_back(CleanWord(moduleName));\n\n for( TiXmlElement* n_Parameter = n_AppNode->FirstChildElement(\"parameter\"); n_Parameter != ITK_NULLPTR;\n n_Parameter = n_Parameter->NextSiblingElement() )\n {\n std::string key=\"-\";\n key.append(GetChildNodeTextOf(n_Parameter, \"key\"));\n expression.push_back(CleanWord(key));\n\n TiXmlElement* n_Values = ITK_NULLPTR;\n n_Values = n_Parameter->FirstChildElement(\"values\");\n if(n_Values)\n {\n std::string values;\n for(TiXmlElement* n_Value = n_Values->FirstChildElement(\"value\"); n_Value != ITK_NULLPTR;\n n_Value = n_Value->NextSiblingElement())\n {\n expression.push_back(CleanWord(n_Value->GetText()));\n }\n }\n else\n {\n std::string value;\n value = GetChildNodeTextOf(n_Parameter, \"value\");\n expression.push_back(CleanWord(value));\n\n std::string type = GetChildNodeTextOf(n_Parameter, \"type\");\n if (type == \"OutputImage\")\n {\n std::string t = GetChildNodeTextOf(n_Parameter, \"pixtype\");\n expression.push_back(CleanWord(t));\n }\n }\n }\n\n fclose(fp);\n\n return expression;\n}\n\nstd::string CleanWord(const std::string & word)\n{\n std::string res(\"\");\n \/\/ Suppress whitespace characters at the beginning and ending of the string\n std::string::size_type cleanStart = word.find_first_not_of(\" \\t\");\n std::string::size_type cleanEnd = word.find_last_not_of(\" \\t\\f\\v\\n\\r\");\n \/\/ cleanStart == npos implies cleanEnd == npos\n if (cleanEnd != std::string::npos)\n {\n res = word.substr(cleanStart, cleanEnd - cleanStart + 1);\n }\n return res;\n}\n\nint main(int argc, char* argv[])\n{\n #ifdef OTB_USE_MPI\n otb::MPIConfig::Instance()->Init(argc,argv);\n #endif\n \n if (argc < 2)\n {\n std::cerr << \"Usage : \" << argv[0] << \" module_name [MODULEPATH] [arguments]\" << std::endl;\n return EXIT_FAILURE;\n }\n\n std::vector vexp;\n\n std::string exp;\n if (strcmp(argv[1], \"-inxml\") == 0)\n {\n \/\/exp = PrepareExpressionFromXML(argv[2]);\n vexp = PrepareVectorExpressionFromXML(argv[2]);\n }\n else\n {\n \/\/ Construct the string expression\n for (int i = 1; i < argc; i++)\n {\n \/*if (i != argc - 1)\n {\n exp.append(argv[i]);\n exp.append(\" \");\n }\n else\n {\n exp.append(argv[i]);\n }*\/\n std::string strarg(argv[i]);\n std::string cleanArg = CleanWord(strarg);\n if (cleanArg.empty())\n {\n \/\/ Empty argument !\n continue;\n }\n vexp.push_back(cleanArg);\n }\n }\n \/\/ std::cerr << exp << \":\\n\";\n\n typedef otb::Wrapper::CommandLineLauncher LauncherType;\n LauncherType::Pointer launcher = LauncherType::New();\n\n \/\/if (launcher->Load(exp) == true)\n if (launcher->Load(vexp) == true)\n {\n if (launcher->ExecuteAndWriteOutput() == false)\n {\n return EXIT_FAILURE;\n }\n }\n else\n {\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n\nconst std::string GetChildNodeTextOf(TiXmlElement *parentElement, std::string key)\n{\n std::string value=\"\";\n\n if(parentElement)\n {\n TiXmlElement* childElement = ITK_NULLPTR;\n childElement = parentElement->FirstChildElement(key.c_str());\n\n \/\/same as childElement->GetText() does but that call is failing if there is\n \/\/no such node.\n \/\/but the below code works and is a replacement for GetText()\n if(childElement)\n {\n const TiXmlNode* child = childElement->FirstChild();\n if ( child )\n {\n const TiXmlText* childText = child->ToText();\n if ( childText )\n {\n value = childText->Value();\n }\n }\n }\n }\n return value;\n}\n<|endoftext|>"} {"text":"\/* -*- mode: c++; c-default-style: \"google\"; indent-tabs-mode: nil -*- *\/\n\n\/* -------------------------------------------------------------------------\nATS\n\nLicense: see $ATS_DIR\/COPYRIGHT\nAuthor: Ethan Coon\n\nStandard base for most PKs, this combines both domains\/meshes of\nPKPhysicalBase and BDF methods of PKBDFBase.\n------------------------------------------------------------------------- *\/\n\n#include \"boost\/math\/special_functions\/fpclassify.hpp\"\n\n#include \"pk_physical_bdf_base.hh\"\n\nnamespace Amanzi {\n\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Setup\n\/\/ -----------------------------------------------------------------------------\nvoid PKPhysicalBDFBase::setup(const Teuchos::Ptr& S) {\n\n \/\/ call the meat of the base constructurs via Setup methods\n PKPhysicalBase::setup(S);\n PKBDFBase::setup(S);\n\n \/\/ convergence criteria\n atol_ = plist_.get(\"absolute error tolerance\",1.0);\n rtol_ = plist_.get(\"relative error tolerance\",1.0);\n atol0_ = atol_;\n rtol0_ = rtol_;\n\n \/\/ adapt the tolerances to fit the timestep\n adapt_tols_to_h_ = plist_.get(\"adapt tolerances to timestep\", \"false\");\n if (adapt_tols_to_h_) {\n min_tol_h_ = plist_.get(\"cutoff timestep for adaptive tolerance\", 100.0);\n }\n\n \/\/ continuation to steady state enables a gradually shrinking atol\/rtol\n continuation_to_ss_ = plist_.get(\"continuation to steady state\", false);\n\n};\n\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ initialize. Note both BDFBase and PhysicalBase have initialize()\n\/\/ methods, so we need a unique overrider.\n\/\/ -----------------------------------------------------------------------------\nvoid PKPhysicalBDFBase::initialize(const Teuchos::Ptr& S) {\n \/\/ Just calls both subclass's initialize. NOTE - order is important here --\n \/\/ PhysicalBase grabs the primary variable and stuffs it into the solution,\n \/\/ which must be done prior to BDFBase initializing the timestepper.\n PKPhysicalBase::initialize(S);\n PKBDFBase::initialize(S);\n}\n\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Default enorm that uses an abs and rel tolerance to monitor convergence.\n\/\/ -----------------------------------------------------------------------------\ndouble PKPhysicalBDFBase::enorm(Teuchos::RCP u,\n Teuchos::RCP du) {\n \/\/ VerboseObject stuff.\n Teuchos::OSTab tab = getOSTab();\n if (out_.get() && includesVerbLevel(verbosity_, Teuchos::VERB_HIGH, true)) {\n *out_ << \"ENorm (Infnorm) of: \" << name_ << \": \";\n }\n\n \/\/ adapt tolerances if needed\n if (adapt_tols_to_h_) {\n double h = S_next_->time() - S_inter_->time();\n atol_ = atol0_ \/ h;\n rtol_ = rtol0_ \/ h;\n }\n\n \/\/ continue tolerances if needed\n if (continuation_to_ss_) {\n atol_ = atol0_ + 1.e5*atol0_\/(1.0 + S_next_->time());\n rtol_ = rtol0_ + 1.e5*rtol0_\/(1.0 + S_next_->time());\n }\n\n Teuchos::RCP vec = u->data();\n Teuchos::RCP dvec = du->data();\n\n\n double enorm_val = 0.0;\n for (CompositeVector::name_iterator comp=vec->begin();\n comp!=vec->end(); ++comp) {\n double enorm_comp = 0.0;\n double infnorm_comp = 0.0;\n for (int id=0; id!=vec->size(*comp,false); ++id) {\n if (boost::math::isnan((*dvec)(*comp,id))) {\n std::cout << \"Cutting time step due to NaN in correction.\" << std::endl;\n Errors::Message m(\"Cut time step\");\n Exceptions::amanzi_throw(m);\n }\n\n double tmp = abs((*dvec)(*comp,id)) \/ (atol_+rtol_*abs((*vec)(*comp,id)));\n enorm_comp = std::max(enorm_comp, tmp);\n infnorm_comp = std::max(infnorm_comp, abs((*dvec)(*comp,id)));\n }\n\n if (out_.get() && includesVerbLevel(verbosity_, Teuchos::VERB_HIGH, true)) {\n *out_ << *comp << \" = \" << enorm_comp << \" (\" << infnorm_comp << \") \";\n }\n enorm_val = std::max(enorm_val, enorm_comp);\n }\n\n if (out_.get() && includesVerbLevel(verbosity_, Teuchos::VERB_HIGH, true)) {\n *out_ << std::endl;\n }\n\n#ifdef HAVE_MPI\n double buf = enorm_val;\n MPI_Allreduce(&buf, &enorm_val, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);\n#endif\n return enorm_val;\n};\n\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Experimental approach -- we must pull out S_next_'s solution_evaluator_ to\n\/\/ stay current for changed_solution()\n\/\/ -----------------------------------------------------------------------------\nvoid PKPhysicalBDFBase::set_states(const Teuchos::RCP& S,\n const Teuchos::RCP& S_inter,\n const Teuchos::RCP& S_next) {\n PKDefaultBase::set_states(S, S_inter, S_next);\n\n Teuchos::RCP fm = S_next->GetFieldEvaluator(key_);\n\n#if ENABLE_DBC\n solution_evaluator_ = Teuchos::rcp_dynamic_cast(fm);\n ASSERT(solution_evaluator_ != Teuchos::null);\n#else\n solution_evaluator_ = Teuchos::rcp_static_cast(fm);\n#endif\n\n changed_solution();\n};\n\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Experimental approach -- calling this indicates that the time\n\/\/ integration scheme is changing the value of the solution in\n\/\/ state.\n\/\/ -----------------------------------------------------------------------------\nvoid PKPhysicalBDFBase::changed_solution() {\n solution_evaluator_->SetFieldAsChanged();\n};\n\n} \/\/ namespace\ncleanup for reporting norms in parallel case\/* -*- mode: c++; c-default-style: \"google\"; indent-tabs-mode: nil -*- *\/\n\n\/* -------------------------------------------------------------------------\nATS\n\nLicense: see $ATS_DIR\/COPYRIGHT\nAuthor: Ethan Coon\n\nStandard base for most PKs, this combines both domains\/meshes of\nPKPhysicalBase and BDF methods of PKBDFBase.\n------------------------------------------------------------------------- *\/\n\n#include \"boost\/math\/special_functions\/fpclassify.hpp\"\n\n#include \"pk_physical_bdf_base.hh\"\n\nnamespace Amanzi {\n\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Setup\n\/\/ -----------------------------------------------------------------------------\nvoid PKPhysicalBDFBase::setup(const Teuchos::Ptr& S) {\n\n \/\/ call the meat of the base constructurs via Setup methods\n PKPhysicalBase::setup(S);\n PKBDFBase::setup(S);\n\n \/\/ convergence criteria\n atol_ = plist_.get(\"absolute error tolerance\",1.0);\n rtol_ = plist_.get(\"relative error tolerance\",1.0);\n atol0_ = atol_;\n rtol0_ = rtol_;\n\n \/\/ adapt the tolerances to fit the timestep\n adapt_tols_to_h_ = plist_.get(\"adapt tolerances to timestep\", \"false\");\n if (adapt_tols_to_h_) {\n min_tol_h_ = plist_.get(\"cutoff timestep for adaptive tolerance\", 100.0);\n }\n\n \/\/ continuation to steady state enables a gradually shrinking atol\/rtol\n continuation_to_ss_ = plist_.get(\"continuation to steady state\", false);\n\n};\n\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ initialize. Note both BDFBase and PhysicalBase have initialize()\n\/\/ methods, so we need a unique overrider.\n\/\/ -----------------------------------------------------------------------------\nvoid PKPhysicalBDFBase::initialize(const Teuchos::Ptr& S) {\n \/\/ Just calls both subclass's initialize. NOTE - order is important here --\n \/\/ PhysicalBase grabs the primary variable and stuffs it into the solution,\n \/\/ which must be done prior to BDFBase initializing the timestepper.\n PKPhysicalBase::initialize(S);\n PKBDFBase::initialize(S);\n}\n\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Default enorm that uses an abs and rel tolerance to monitor convergence.\n\/\/ -----------------------------------------------------------------------------\ndouble PKPhysicalBDFBase::enorm(Teuchos::RCP u,\n Teuchos::RCP du) {\n \/\/ VerboseObject stuff.\n Teuchos::OSTab tab = getOSTab();\n if (out_.get() && includesVerbLevel(verbosity_, Teuchos::VERB_HIGH, true)) {\n *out_ << \"ENorm (Infnorm) of: \" << name_ << \": \";\n }\n\n \/\/ adapt tolerances if needed\n if (adapt_tols_to_h_) {\n double h = S_next_->time() - S_inter_->time();\n atol_ = atol0_ \/ h;\n rtol_ = rtol0_ \/ h;\n }\n\n \/\/ continue tolerances if needed\n if (continuation_to_ss_) {\n atol_ = atol0_ + 1.e5*atol0_\/(1.0 + S_next_->time());\n rtol_ = rtol0_ + 1.e5*rtol0_\/(1.0 + S_next_->time());\n }\n\n Teuchos::RCP vec = u->data();\n Teuchos::RCP dvec = du->data();\n\n\n double enorm_val = 0.0;\n for (CompositeVector::name_iterator comp=vec->begin();\n comp!=vec->end(); ++comp) {\n double enorm_comp = 0.0;\n for (int id=0; id!=vec->size(*comp,false); ++id) {\n if (boost::math::isnan((*dvec)(*comp,id))) {\n std::cout << \"Cutting time step due to NaN in correction.\" << std::endl;\n Errors::Message m(\"Cut time step\");\n Exceptions::amanzi_throw(m);\n }\n\n double tmp = abs((*dvec)(*comp,id)) \/ (atol_+rtol_*abs((*vec)(*comp,id)));\n enorm_comp = std::max(enorm_comp, tmp);\n }\n\n if (out_.get() && includesVerbLevel(verbosity_, Teuchos::VERB_HIGH, true)) {\n double buf(0.);\n MPI_Allreduce(&enorm_comp, &buf, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);\n\n double infnorm_comp;\n dvec->ViewComponent(*comp,false)->NormInf(&infnorm_comp);\n\n *out_ << *comp << \" = \" << buf << \" (\" << infnorm_comp << \") \";\n }\n enorm_val = std::max(enorm_val, enorm_comp);\n }\n\n if (out_.get() && includesVerbLevel(verbosity_, Teuchos::VERB_HIGH, true)) {\n *out_ << std::endl;\n }\n\n#ifdef HAVE_MPI\n double buf = enorm_val;\n MPI_Allreduce(&buf, &enorm_val, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);\n#endif\n return enorm_val;\n};\n\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Experimental approach -- we must pull out S_next_'s solution_evaluator_ to\n\/\/ stay current for changed_solution()\n\/\/ -----------------------------------------------------------------------------\nvoid PKPhysicalBDFBase::set_states(const Teuchos::RCP& S,\n const Teuchos::RCP& S_inter,\n const Teuchos::RCP& S_next) {\n PKDefaultBase::set_states(S, S_inter, S_next);\n\n Teuchos::RCP fm = S_next->GetFieldEvaluator(key_);\n\n#if ENABLE_DBC\n solution_evaluator_ = Teuchos::rcp_dynamic_cast(fm);\n ASSERT(solution_evaluator_ != Teuchos::null);\n#else\n solution_evaluator_ = Teuchos::rcp_static_cast(fm);\n#endif\n\n changed_solution();\n};\n\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Experimental approach -- calling this indicates that the time\n\/\/ integration scheme is changing the value of the solution in\n\/\/ state.\n\/\/ -----------------------------------------------------------------------------\nvoid PKPhysicalBDFBase::changed_solution() {\n solution_evaluator_->SetFieldAsChanged();\n};\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"#include \"stdafx.h\"\n#include \"LocalTables.h\"\n\nusing namespace std;\n\n\nvoid LocalTables::init(std::function fn, double LB)\n{\n\tfnGetNParents = fn;\n\tlowerBound = LB;\n\tcandidateTables.reserve(16);\n\tnActLevel.reserve(16);\n\tnActLevelTotal.reserve(16);\n}\n\nvoid LocalTables::update(const Motif & m, const double newUB, const int num)\n{\n\tint l = m.getnEdge();\n\tlock_guard lg(mct);\n\t\/\/ add new level\n\tif(static_cast(candidateTables.size()) <= l ) {\n\t\tsize_t len = max(candidateTables.size(), nActLevel.size());\n\t\tlen = max(len, l + 1);\n\t\tcandidateTables.resize(len);\n\t\tlock_guard lga(mat);\n\t\tnActLevel.resize(len);\n\t\tnActLevelTotal.resize(len);\n\t}\n\t\/\/ update the num. left for activation\n\tCT_t& ct = candidateTables[l];\n\tauto it = ct.find(m);\n\tif(it == ct.end()) {\n\t\t\/\/ the max(0,...) here is for the special case where fnGetNParents(m)-num < 0\n\t\tint np = max(0, fnGetNParents(m) - num);\n\t\tit = ct.insert(make_pair(move(m), make_pair(newUB, np))).first;\n\t} else {\n\t\tit->second.first = min(it->second.first, newUB);\n\t\tit->second.second -= num;\n\t}\n\t\/\/ move a motif from candiate to active\n\tif(it->second.second == 0) {\n\t\tif(it->second.first >= lowerBound) {\n\t\t\tlock_guard lga(mat);\n\t\t\tactivatedTable.push_back(make_pair(move(it->first), it->second.first));\n\t\t\t++nActLevel[l];\n\t\t\t++nActLevelTotal[l];\n\t\t}\n\t\t\/\/ Special Case: when using estimated num. parents algorithm:\n\t\t\/\/ #-left may be negative. If remove it the first time, it may be activated again.\n\t\t\/\/ Therefore, instead of remove it, I set its #-left to a very large number.\n\t\t\/\/ TODO: distinguish the method for calculating num. partents, exact type & estimated type\n\t\t\/\/ct.erase(it);\n\t\tit->second.second = numeric_limits::max();\n\t}\n\n}\n\nvoid LocalTables::addToActivated(const Motif & m, const double newUB)\n{\n\tint l = m.getnEdge();\n\tlock_guard lga(mat);\n\t\/\/ add new level\n\tif(static_cast(nActLevel.size()) <= l) {\n\t\tsize_t len = max(nActLevel.size(), l + 1);\n\t\tnActLevel.resize(len);\n\t\tnActLevelTotal.resize(len);\n\t}\n\tactivatedTable.push_back(make_pair(m, newUB));\n\t++nActLevel[l];\n\t++nActLevelTotal[l];\n}\n\nvoid LocalTables::sortUp(const int l)\n{\n\tlock_guard lg(mct);\n\tsize_t end = min(static_cast(l + 1 + 1), candidateTables.size());\n\t\/\/ first +1 : clear the CT of level l+1 ; second +1 : loop in [x,x) manner\n\tfor(size_t i = 1; i < end; ++i) {\n\t\tcandidateTables[i].clear();\n\t}\n}\n\nint LocalTables::updateLowerBound(double newLB)\n{\n\tif(lowerBound >= newLB)\n\t\treturn 0;\n\tlowerBound = newLB;\n\tlock_guard lg(mat);\n\tsize_t s0 = activatedTable.size();\n\tauto it = activatedTable.begin();\n\twhile(it != activatedTable.end()) {\n\t\tif(it->second < lowerBound) {\n\t\t\t--nActLevel[it->first.getnEdge()];\n\t\t\tit = activatedTable.erase(it);\n\t\t} else {\n\t\t\t++it;\n\t\t}\n\t}\n\treturn s0 - activatedTable.size();\n}\n\nstd::pair> LocalTables::getOne()\n{\n\tif(activatedTable.empty()) {\n\t\treturn make_pair(false, make_pair(Motif(), 0.0));\n\t}\n\tlock_guard lg(mat);\n\tif(activatedTable.empty()) {\n\t\treturn make_pair(false, make_pair(Motif(), 0.0));\n\t}\n\tauto mu = move(activatedTable.front());\n\t--nActLevel[mu.first.getnEdge()];\n\tactivatedTable.pop_front();\n\treturn make_pair(true, move(mu));\n}\n\nint LocalTables::mostRecentLevel() const\n{\n\treturn candidateTables.size() - 1;\n}\n\nbool LocalTables::emptyCandidate() const\n{\n\tfor(size_t i = 0; i < candidateTables.size(); ++i) {\n\t\tif(emptyCandidate(i))\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool LocalTables::emptyCandidate(const int level) const\n{\n\treturn static_cast(candidateTables.size()) > level\n\t\t&& candidateTables[level].empty();\n}\n\nbool LocalTables::emptyActivated() const\n{\n\treturn activatedTable.empty();\n}\n\nbool LocalTables::emptyActivated(const int level) const\n{\n\treturn static_cast(nActLevel.size()) > level\n\t\t&& nActLevel[level] == 0;\n}\n\nint LocalTables::getNumCandidate() const\n{\n\tint res = 0;\n\tsize_t n = candidateTables.size();\n\tfor(size_t i = 0; i < n; ++i)\n\t\tres += candidateTables[i].size();\n\treturn res;\n}\n\nstd::vector LocalTables::getNumCandidates() const\n{\n\tsize_t n = candidateTables.size();\n\tstd::vector res(n);\n\tfor(size_t i = 0; i < n; ++i)\n\t\tres[i] = candidateTables[i].size();\n\treturn res;\n}\n\nint LocalTables::getNumCandidate(const int level) const\n{\n\treturn static_cast(candidateTables.size()) > level\n\t\t? candidateTables[level].size() : 0;\n}\n\nint LocalTables::getNumActive() const\n{\n\treturn activatedTable.size();\n}\n\nstd::vector LocalTables::getNumActives() const\n{\n\treturn nActLevel;\n}\n\nint LocalTables::getNumActive(const int level) const\n{\n\treturn static_cast(nActLevel.size()) > level\n\t\t? nActLevel[level] : 0;\n}\n\nint LocalTables::getNumEverActive(const int level) const\n{\n\treturn static_cast(nActLevelTotal.size()) > level ?\n\t\tnActLevelTotal[level] : 0;\n}\n\nbool LocalTables::empty() const\n{\n\tunique_lock ulc(mct, defer_lock);\n\tunique_lock ula(mat, defer_lock);\n\tlock(ulc, ula);\n\tif(activatedTable.empty()) {\n\t\tfor(auto& ct : candidateTables)\n\t\t\tif(!ct.empty())\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool LocalTables::empty(const int level) const\n{\n\tunique_lock ulc(mct, defer_lock);\n\tunique_lock ula(mat, defer_lock);\n\tlock(ulc, ula);\n\treturn candidateTables[level].empty() && nActLevel[level] == 0;\n}\n\nfix an over optimization in local table#include \"stdafx.h\"\n#include \"LocalTables.h\"\n\nusing namespace std;\n\n\nvoid LocalTables::init(std::function fn, double LB)\n{\n\tfnGetNParents = fn;\n\tlowerBound = LB;\n\tcandidateTables.reserve(16);\n\tnActLevel.reserve(16);\n\tnActLevelTotal.reserve(16);\n}\n\nvoid LocalTables::update(const Motif & m, const double newUB, const int num)\n{\n\tint l = m.getnEdge();\n\tlock_guard lg(mct);\n\t\/\/ add new level\n\tif(static_cast(candidateTables.size()) <= l ) {\n\t\tsize_t len = max(candidateTables.size(), nActLevel.size());\n\t\tlen = max(len, l + 1);\n\t\tcandidateTables.resize(len);\n\t\tlock_guard lga(mat);\n\t\tnActLevel.resize(len);\n\t\tnActLevelTotal.resize(len);\n\t}\n\t\/\/ update the num. left for activation\n\tCT_t& ct = candidateTables[l];\n\tauto it = ct.find(m);\n\tif(it == ct.end()) {\n\t\t\/\/ the max(0,...) here is for the special case where fnGetNParents(m)-num < 0\n\t\tint np = max(0, fnGetNParents(m) - num);\n\t\tit = ct.insert(make_pair(move(m), make_pair(newUB, np))).first;\n\t} else {\n\t\tit->second.first = min(it->second.first, newUB);\n\t\tit->second.second -= num;\n\t}\n\t\/\/ move a motif from candiate to active\n\tif(it->second.second == 0) {\n\t\tif(it->second.first >= lowerBound) {\n\t\t\tlock_guard lga(mat);\n\t\t\tactivatedTable.push_back(make_pair(move(it->first), it->second.first));\n\t\t\t++nActLevel[l];\n\t\t\t++nActLevelTotal[l];\n\t\t}\n\t\t\/\/ Special Case: when using estimated num. parents algorithm:\n\t\t\/\/ #-left may be negative. If remove it the first time, it may be activated again.\n\t\t\/\/ Therefore, instead of remove it, I set its #-left to a very large number.\n\t\t\/\/ TODO: distinguish the method for calculating num. partents, exact type & estimated type\n\t\t\/\/ct.erase(it);\n\t\tit->second.second = numeric_limits::max();\n\t}\n\n}\n\nvoid LocalTables::addToActivated(const Motif & m, const double newUB)\n{\n\tint l = m.getnEdge();\n\tlock_guard lga(mat);\n\t\/\/ add new level\n\tif(static_cast(nActLevel.size()) <= l) {\n\t\tsize_t len = max(nActLevel.size(), l + 1);\n\t\tnActLevel.resize(len);\n\t\tnActLevelTotal.resize(len);\n\t}\n\tactivatedTable.push_back(make_pair(m, newUB));\n\t++nActLevel[l];\n\t++nActLevelTotal[l];\n}\n\nvoid LocalTables::sortUp(const int l)\n{\n\tlock_guard lg(mct);\n\tsize_t end = min(static_cast(l + 1), candidateTables.size());\n\t\/\/ l+1 : loop in [x,x) manner\n\tfor(size_t i = 1; i < end; ++i) {\n\t\tcandidateTables[i].clear();\n\t}\n}\n\nint LocalTables::updateLowerBound(double newLB)\n{\n\tif(lowerBound >= newLB)\n\t\treturn 0;\n\tlowerBound = newLB;\n\tlock_guard lg(mat);\n\tsize_t s0 = activatedTable.size();\n\tauto it = activatedTable.begin();\n\twhile(it != activatedTable.end()) {\n\t\tif(it->second < lowerBound) {\n\t\t\t--nActLevel[it->first.getnEdge()];\n\t\t\tit = activatedTable.erase(it);\n\t\t} else {\n\t\t\t++it;\n\t\t}\n\t}\n\treturn s0 - activatedTable.size();\n}\n\nstd::pair> LocalTables::getOne()\n{\n\tif(activatedTable.empty()) {\n\t\treturn make_pair(false, make_pair(Motif(), 0.0));\n\t}\n\tlock_guard lg(mat);\n\tif(activatedTable.empty()) {\n\t\treturn make_pair(false, make_pair(Motif(), 0.0));\n\t}\n\tauto mu = move(activatedTable.front());\n\t--nActLevel[mu.first.getnEdge()];\n\tactivatedTable.pop_front();\n\treturn make_pair(true, move(mu));\n}\n\nint LocalTables::mostRecentLevel() const\n{\n\treturn candidateTables.size() - 1;\n}\n\nbool LocalTables::emptyCandidate() const\n{\n\tfor(size_t i = 0; i < candidateTables.size(); ++i) {\n\t\tif(emptyCandidate(i))\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool LocalTables::emptyCandidate(const int level) const\n{\n\treturn static_cast(candidateTables.size()) > level\n\t\t&& candidateTables[level].empty();\n}\n\nbool LocalTables::emptyActivated() const\n{\n\treturn activatedTable.empty();\n}\n\nbool LocalTables::emptyActivated(const int level) const\n{\n\treturn static_cast(nActLevel.size()) > level\n\t\t&& nActLevel[level] == 0;\n}\n\nint LocalTables::getNumCandidate() const\n{\n\tint res = 0;\n\tsize_t n = candidateTables.size();\n\tfor(size_t i = 0; i < n; ++i)\n\t\tres += candidateTables[i].size();\n\treturn res;\n}\n\nstd::vector LocalTables::getNumCandidates() const\n{\n\tsize_t n = candidateTables.size();\n\tstd::vector res(n);\n\tfor(size_t i = 0; i < n; ++i)\n\t\tres[i] = candidateTables[i].size();\n\treturn res;\n}\n\nint LocalTables::getNumCandidate(const int level) const\n{\n\treturn static_cast(candidateTables.size()) > level\n\t\t? candidateTables[level].size() : 0;\n}\n\nint LocalTables::getNumActive() const\n{\n\treturn activatedTable.size();\n}\n\nstd::vector LocalTables::getNumActives() const\n{\n\treturn nActLevel;\n}\n\nint LocalTables::getNumActive(const int level) const\n{\n\treturn static_cast(nActLevel.size()) > level\n\t\t? nActLevel[level] : 0;\n}\n\nint LocalTables::getNumEverActive(const int level) const\n{\n\treturn static_cast(nActLevelTotal.size()) > level ?\n\t\tnActLevelTotal[level] : 0;\n}\n\nbool LocalTables::empty() const\n{\n\tunique_lock ulc(mct, defer_lock);\n\tunique_lock ula(mat, defer_lock);\n\tlock(ulc, ula);\n\tif(activatedTable.empty()) {\n\t\tfor(auto& ct : candidateTables)\n\t\t\tif(!ct.empty())\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool LocalTables::empty(const int level) const\n{\n\tunique_lock ulc(mct, defer_lock);\n\tunique_lock ula(mat, defer_lock);\n\tlock(ulc, ula);\n\treturn candidateTables[level].empty() && nActLevel[level] == 0;\n}\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: syshelp.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: hr $ $Date: 2007-11-02 12:55:32 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#include \n\n\n\/\/ NOT FULLY DEFINED SERVICES\n#include \n#include \"sistr.hxx\"\n#include \"list.hxx\"\n\n#ifdef WNT\n#include \n#elif defined(UNX) || defined(OS2)\n#include \n#include \n#include \n#define stricmp strcasecmp\n#else\n#error Must run under unix or windows, please define UNX or WNT.\n#endif\n\n\nchar C_sSpaceInName[] = \"   \";\n\nvoid\nWriteName( std::ostream & o_rFile,\n const Simstr & i_rIdlDocuBaseDir,\n const Simstr & i_rName,\n E_LinkType i_eLinkType )\n{\n if (i_rName.l() == 0)\n return;\n\n\n const char * pNameEnd = strstr( i_rName.str(), \" in \" );\n\n \/\/ No link:\n if ( i_eLinkType == lt_nolink )\n {\n if ( pNameEnd != 0 )\n {\n const char * pStart = i_rName.str();\n o_rFile.write( pStart, pNameEnd - pStart );\n WriteStr( o_rFile, C_sSpaceInName );\n WriteStr( o_rFile, pNameEnd );\n }\n else\n {\n WriteStr( o_rFile, i_rName );\n }\n return;\n }\n\n if ( i_eLinkType == lt_idl )\n {\n Simstr sPath(i_rName);\n sPath.replace_all('.','\/');\n int nNameEnd = sPath.pos_first(' ');\n int nPathStart = sPath.pos_last(' ');\n WriteStr( o_rFile, \" -1 )\n {\n WriteStr( o_rFile, \"file:\/\/\/\" );\n WriteStr( o_rFile, i_rIdlDocuBaseDir );\n WriteStr( o_rFile, \"\/\" );\n WriteStr( o_rFile, sPath.str() + 1 + nPathStart );\n WriteStr( o_rFile, \"\/\" );\n o_rFile.write( sPath.str(), nNameEnd );\n WriteStr( o_rFile, \".html\\\">\" );\n }\n else\n { \/\/ Should not be reached:\n WriteStr(o_rFile, i_rName);\n return;\n }\n }\n else if ( i_eLinkType == lt_html )\n {\n int nKomma = i_rName.pos_first(',');\n int nEnd = i_rName.pos_first(' ');\n if ( nKomma > -1 )\n {\n o_rFile.write( i_rName.str(), nKomma );\n WriteStr( o_rFile, \": \" );\n\n WriteStr( o_rFile, \" -1 )\n o_rFile.write( i_rName.str() + nKomma + 1, nEnd - nKomma );\n else\n WriteStr( o_rFile, i_rName.str() + nKomma + 1 );\n WriteStr( o_rFile, \"\\\">\" );\n\n o_rFile.write( i_rName.str() + nKomma + 1, nEnd - nKomma );\n }\n else\n {\n WriteStr( o_rFile, \"\" );\n\n WriteStr( o_rFile, i_rName );\n }\n WriteStr( o_rFile, \"<\/A>\" );\n return;\n }\n\n if ( pNameEnd != 0 )\n {\n const char * pStart = i_rName.str();\n if ( pNameEnd > pStart )\n o_rFile.write( pStart, pNameEnd - pStart );\n WriteStr( o_rFile, \"<\/A>\" );\n\n WriteStr( o_rFile, C_sSpaceInName );\n WriteStr( o_rFile, pNameEnd );\n }\n else\n {\n WriteStr( o_rFile, i_rName );\n WriteStr( o_rFile, \"<\/A>\" );\n }\n}\n\n\nvoid\nWriteStr( std::ostream & o_rFile,\n const char * i_sStr )\n{\n o_rFile.write( i_sStr, (int) strlen(i_sStr) );\n}\n\nvoid\nWriteStr( std::ostream & o_rFile,\n const Simstr & i_sStr )\n{\n o_rFile.write( i_sStr.str(), i_sStr.l() );\n}\n\n\nconst char C_sXML_END[] = \"\\\\*.xml\";\n\nvoid\nGatherFileNames( List & o_sFiles,\n const char * i_sSrcDirectory )\n{\n static int nAliveCounter = 0;\n\n char * sNextDir = 0;\n Simstr sNew = 0;\n\n#ifdef WNT\n struct _finddata_t aEntry;\n long hFile = 0;\n int bFindMore = 0;\n char * sFilter = new char[ strlen(i_sSrcDirectory) + sizeof C_sXML_END ];\n\n \/\/ Stayingalive sign\n if (++nAliveCounter % 100 == 1)\n std::cout << \".\" << std::flush;\n\n strcpy(sFilter, i_sSrcDirectory); \/\/ STRCPY SAFE HERE\n strcat(sFilter,C_sXML_END); \/\/ STRCAT SAFE HERE\n\n hFile = _findfirst( sFilter, &aEntry );\n for ( bFindMore = hFile == -1;\n bFindMore == 0;\n bFindMore = _findnext( hFile, &aEntry ) )\n {\n sNew = i_sSrcDirectory;\n sNew += \"\\\\\";\n sNew += aEntry.name;\n o_sFiles.push_back(sNew);\n } \/\/ end for\n\n _findclose(hFile);\n delete [] sFilter;\n#elif defined(UNX) || defined(OS2)\n DIR * pDir = opendir( i_sSrcDirectory );\n dirent * pEntry = 0;\n char * sEnding;\n\n \/\/ Stayingalive sign\n if (++nAliveCounter % 100 == 1)\n std::cout << \".\" << std::flush;\n\n while ( (pEntry = readdir(pDir)) != 0 )\n {\n sEnding = strrchr(pEntry->d_name,'.');\n if (sEnding != 0 ? stricmp(sEnding,\".xml\") == 0 : 0 )\n {\n sNew = i_sSrcDirectory;\n sNew += \"\/\";\n sNew += pEntry->d_name;\n o_sFiles.push_back(sNew);\n }\n } \/\/ end while\n\n closedir( pDir );\n#else\n#error Must run on unix or windows, please define UNX or WNT.\n#endif\n\n \/\/ gathering from subdirectories:\n List aSubDirectories;\n GatherSubDirectories( aSubDirectories, i_sSrcDirectory );\n\n unsigned d_max = aSubDirectories.size();\n for ( unsigned d = 0; d < d_max; ++d )\n {\n sNextDir = new char[ strlen(i_sSrcDirectory) + 2 + aSubDirectories[d].l() ];\n\n strcpy(sNextDir, i_sSrcDirectory);\n strcat(sNextDir, C_sSLASH);\n strcat(sNextDir, aSubDirectories[d].str());\n GatherFileNames(o_sFiles, sNextDir);\n\n delete [] sNextDir;\n }\n}\n\n\nconst char * C_sANYDIR = \"\\\\*.*\";\n\nvoid\nGatherSubDirectories( List & o_sSubDirectories,\n const char * i_sParentdDirectory )\n{\n Simstr sNew;\n\n#ifdef WNT\n struct _finddata_t aEntry;\n long hFile = 0;\n int bFindMore = 0;\n char * sFilter = new char[strlen(i_sParentdDirectory) + sizeof C_sANYDIR];\n\n strcpy(sFilter, i_sParentdDirectory);\n strcat(sFilter,C_sANYDIR);\n\n hFile = _findfirst( sFilter, &aEntry );\n for ( bFindMore = hFile == -1;\n bFindMore == 0;\n bFindMore = _findnext( hFile, &aEntry ) )\n {\n if (aEntry.attrib == _A_SUBDIR)\n {\n \/\/ Do not gather . .. and outputtree directories\n if ( strchr(aEntry.name,'.') == 0\n && strncmp(aEntry.name, \"wnt\", 3) != 0\n && strncmp(aEntry.name, \"unx\", 3) != 0 )\n {\n sNew = aEntry.name;\n o_sSubDirectories.push_back(sNew);\n }\n } \/\/ endif (aEntry.attrib == _A_SUBDIR)\n } \/\/ end for\n _findclose(hFile);\n delete [] sFilter;\n\n#elif defined(UNX) || defined(OS2)\n DIR * pDir = opendir( i_sParentdDirectory );\n dirent * pEntry = 0;\n struct stat aEntryStatus;\n\n while ( ( pEntry = readdir(pDir) ) != 0 )\n {\n stat(pEntry->d_name, &aEntryStatus);\n if ( ( aEntryStatus.st_mode & S_IFDIR ) == S_IFDIR )\n {\n \/\/ Do not gather . .. and outputtree directories\n if ( strchr(pEntry->d_name,'.') == 0\n && strncmp(pEntry->d_name, \"wnt\", 3) != 0\n && strncmp(pEntry->d_name, \"unx\", 3) != 0 )\n {\n sNew = pEntry->d_name;\n o_sSubDirectories.push_back(sNew);\n }\n } \/\/ endif (aEntry.attrib == _A_SUBDIR)\n } \/\/ end while\n closedir( pDir );\n#else\n#error Must run on unix or windows, please define UNX or WNT.\n#endif\n}\n\nINTEGRATION: CWS changefileheader (1.12.12); FILE MERGED 2008\/03\/31 13:06:36 rt 1.12.12.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: syshelp.cxx,v $\n * $Revision: 1.13 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\n#include \n\n\n\/\/ NOT FULLY DEFINED SERVICES\n#include \n#include \"sistr.hxx\"\n#include \"list.hxx\"\n\n#ifdef WNT\n#include \n#elif defined(UNX) || defined(OS2)\n#include \n#include \n#include \n#define stricmp strcasecmp\n#else\n#error Must run under unix or windows, please define UNX or WNT.\n#endif\n\n\nchar C_sSpaceInName[] = \"   \";\n\nvoid\nWriteName( std::ostream & o_rFile,\n const Simstr & i_rIdlDocuBaseDir,\n const Simstr & i_rName,\n E_LinkType i_eLinkType )\n{\n if (i_rName.l() == 0)\n return;\n\n\n const char * pNameEnd = strstr( i_rName.str(), \" in \" );\n\n \/\/ No link:\n if ( i_eLinkType == lt_nolink )\n {\n if ( pNameEnd != 0 )\n {\n const char * pStart = i_rName.str();\n o_rFile.write( pStart, pNameEnd - pStart );\n WriteStr( o_rFile, C_sSpaceInName );\n WriteStr( o_rFile, pNameEnd );\n }\n else\n {\n WriteStr( o_rFile, i_rName );\n }\n return;\n }\n\n if ( i_eLinkType == lt_idl )\n {\n Simstr sPath(i_rName);\n sPath.replace_all('.','\/');\n int nNameEnd = sPath.pos_first(' ');\n int nPathStart = sPath.pos_last(' ');\n WriteStr( o_rFile, \" -1 )\n {\n WriteStr( o_rFile, \"file:\/\/\/\" );\n WriteStr( o_rFile, i_rIdlDocuBaseDir );\n WriteStr( o_rFile, \"\/\" );\n WriteStr( o_rFile, sPath.str() + 1 + nPathStart );\n WriteStr( o_rFile, \"\/\" );\n o_rFile.write( sPath.str(), nNameEnd );\n WriteStr( o_rFile, \".html\\\">\" );\n }\n else\n { \/\/ Should not be reached:\n WriteStr(o_rFile, i_rName);\n return;\n }\n }\n else if ( i_eLinkType == lt_html )\n {\n int nKomma = i_rName.pos_first(',');\n int nEnd = i_rName.pos_first(' ');\n if ( nKomma > -1 )\n {\n o_rFile.write( i_rName.str(), nKomma );\n WriteStr( o_rFile, \": \" );\n\n WriteStr( o_rFile, \" -1 )\n o_rFile.write( i_rName.str() + nKomma + 1, nEnd - nKomma );\n else\n WriteStr( o_rFile, i_rName.str() + nKomma + 1 );\n WriteStr( o_rFile, \"\\\">\" );\n\n o_rFile.write( i_rName.str() + nKomma + 1, nEnd - nKomma );\n }\n else\n {\n WriteStr( o_rFile, \"\" );\n\n WriteStr( o_rFile, i_rName );\n }\n WriteStr( o_rFile, \"<\/A>\" );\n return;\n }\n\n if ( pNameEnd != 0 )\n {\n const char * pStart = i_rName.str();\n if ( pNameEnd > pStart )\n o_rFile.write( pStart, pNameEnd - pStart );\n WriteStr( o_rFile, \"<\/A>\" );\n\n WriteStr( o_rFile, C_sSpaceInName );\n WriteStr( o_rFile, pNameEnd );\n }\n else\n {\n WriteStr( o_rFile, i_rName );\n WriteStr( o_rFile, \"<\/A>\" );\n }\n}\n\n\nvoid\nWriteStr( std::ostream & o_rFile,\n const char * i_sStr )\n{\n o_rFile.write( i_sStr, (int) strlen(i_sStr) );\n}\n\nvoid\nWriteStr( std::ostream & o_rFile,\n const Simstr & i_sStr )\n{\n o_rFile.write( i_sStr.str(), i_sStr.l() );\n}\n\n\nconst char C_sXML_END[] = \"\\\\*.xml\";\n\nvoid\nGatherFileNames( List & o_sFiles,\n const char * i_sSrcDirectory )\n{\n static int nAliveCounter = 0;\n\n char * sNextDir = 0;\n Simstr sNew = 0;\n\n#ifdef WNT\n struct _finddata_t aEntry;\n long hFile = 0;\n int bFindMore = 0;\n char * sFilter = new char[ strlen(i_sSrcDirectory) + sizeof C_sXML_END ];\n\n \/\/ Stayingalive sign\n if (++nAliveCounter % 100 == 1)\n std::cout << \".\" << std::flush;\n\n strcpy(sFilter, i_sSrcDirectory); \/\/ STRCPY SAFE HERE\n strcat(sFilter,C_sXML_END); \/\/ STRCAT SAFE HERE\n\n hFile = _findfirst( sFilter, &aEntry );\n for ( bFindMore = hFile == -1;\n bFindMore == 0;\n bFindMore = _findnext( hFile, &aEntry ) )\n {\n sNew = i_sSrcDirectory;\n sNew += \"\\\\\";\n sNew += aEntry.name;\n o_sFiles.push_back(sNew);\n } \/\/ end for\n\n _findclose(hFile);\n delete [] sFilter;\n#elif defined(UNX) || defined(OS2)\n DIR * pDir = opendir( i_sSrcDirectory );\n dirent * pEntry = 0;\n char * sEnding;\n\n \/\/ Stayingalive sign\n if (++nAliveCounter % 100 == 1)\n std::cout << \".\" << std::flush;\n\n while ( (pEntry = readdir(pDir)) != 0 )\n {\n sEnding = strrchr(pEntry->d_name,'.');\n if (sEnding != 0 ? stricmp(sEnding,\".xml\") == 0 : 0 )\n {\n sNew = i_sSrcDirectory;\n sNew += \"\/\";\n sNew += pEntry->d_name;\n o_sFiles.push_back(sNew);\n }\n } \/\/ end while\n\n closedir( pDir );\n#else\n#error Must run on unix or windows, please define UNX or WNT.\n#endif\n\n \/\/ gathering from subdirectories:\n List aSubDirectories;\n GatherSubDirectories( aSubDirectories, i_sSrcDirectory );\n\n unsigned d_max = aSubDirectories.size();\n for ( unsigned d = 0; d < d_max; ++d )\n {\n sNextDir = new char[ strlen(i_sSrcDirectory) + 2 + aSubDirectories[d].l() ];\n\n strcpy(sNextDir, i_sSrcDirectory);\n strcat(sNextDir, C_sSLASH);\n strcat(sNextDir, aSubDirectories[d].str());\n GatherFileNames(o_sFiles, sNextDir);\n\n delete [] sNextDir;\n }\n}\n\n\nconst char * C_sANYDIR = \"\\\\*.*\";\n\nvoid\nGatherSubDirectories( List & o_sSubDirectories,\n const char * i_sParentdDirectory )\n{\n Simstr sNew;\n\n#ifdef WNT\n struct _finddata_t aEntry;\n long hFile = 0;\n int bFindMore = 0;\n char * sFilter = new char[strlen(i_sParentdDirectory) + sizeof C_sANYDIR];\n\n strcpy(sFilter, i_sParentdDirectory);\n strcat(sFilter,C_sANYDIR);\n\n hFile = _findfirst( sFilter, &aEntry );\n for ( bFindMore = hFile == -1;\n bFindMore == 0;\n bFindMore = _findnext( hFile, &aEntry ) )\n {\n if (aEntry.attrib == _A_SUBDIR)\n {\n \/\/ Do not gather . .. and outputtree directories\n if ( strchr(aEntry.name,'.') == 0\n && strncmp(aEntry.name, \"wnt\", 3) != 0\n && strncmp(aEntry.name, \"unx\", 3) != 0 )\n {\n sNew = aEntry.name;\n o_sSubDirectories.push_back(sNew);\n }\n } \/\/ endif (aEntry.attrib == _A_SUBDIR)\n } \/\/ end for\n _findclose(hFile);\n delete [] sFilter;\n\n#elif defined(UNX) || defined(OS2)\n DIR * pDir = opendir( i_sParentdDirectory );\n dirent * pEntry = 0;\n struct stat aEntryStatus;\n\n while ( ( pEntry = readdir(pDir) ) != 0 )\n {\n stat(pEntry->d_name, &aEntryStatus);\n if ( ( aEntryStatus.st_mode & S_IFDIR ) == S_IFDIR )\n {\n \/\/ Do not gather . .. and outputtree directories\n if ( strchr(pEntry->d_name,'.') == 0\n && strncmp(pEntry->d_name, \"wnt\", 3) != 0\n && strncmp(pEntry->d_name, \"unx\", 3) != 0 )\n {\n sNew = pEntry->d_name;\n o_sSubDirectories.push_back(sNew);\n }\n } \/\/ endif (aEntry.attrib == _A_SUBDIR)\n } \/\/ end while\n closedir( pDir );\n#else\n#error Must run on unix or windows, please define UNX or WNT.\n#endif\n}\n\n<|endoftext|>"} {"text":"\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/kernels\/work_group_picking.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"tensorflow\/lite\/delegates\/gpu\/common\/util.h\"\n\nnamespace tflite {\nnamespace gpu {\nnamespace cl {\n\nnamespace {\n\nstd::vector Get2DWorkgroupsEqualTo128() {\n return {{128, 1}, {64, 2}, {32, 4}, {16, 8},\n {8, 16}, {4, 32}, {2, 64}, {1, 128}};\n}\n\nstd::vector GenerateWorkGroupSizesXY128(\n int3 grid, int max_work_group_size, WorkGroupSizeAlignment z_alignment) {\n std::vector work_groups;\n work_groups.reserve(32);\n\n std::vector possible_z_sizes = GetPossibleSizes(grid.z, z_alignment);\n\n for (int x = 1; x <= max_work_group_size; x *= 2) {\n for (int y = 1; y <= max_work_group_size; y *= 2) {\n int work_group_size_xy = x * y;\n if (work_group_size_xy % 128 != 0 ||\n work_group_size_xy > max_work_group_size) {\n continue;\n }\n for (auto z : possible_z_sizes) {\n if (work_group_size_xy * z > max_work_group_size) {\n continue;\n }\n work_groups.push_back({x, y, z});\n }\n }\n }\n return work_groups;\n}\n\nstd::vector GenerateWorkGroupSizesXY128Linear(\n int3 grid, int max_work_group_size, WorkGroupSizeAlignment z_alignment) {\n std::vector work_groups;\n work_groups.reserve(32);\n\n std::vector possible_z_sizes = GetPossibleSizes(grid.z, z_alignment);\n\n for (int x = 128; x <= max_work_group_size && x < grid.x + 128; x += 128) {\n for (auto z : possible_z_sizes) {\n if (x * z <= max_work_group_size) {\n work_groups.push_back({x, 1, z});\n }\n }\n }\n return work_groups;\n}\n\nStatus GetBestWorkGroupAlignedToGrid(const TuningParameters& params,\n const CLKernel& kernel, const int3& grid,\n int3* best_work_group) {\n std::vector work_groups;\n RETURN_IF_ERROR(GenerateWorkGroupSizesAlignedToGrid(\n grid, params.info->max_work_group_sizes, kernel.GetMaxWorkGroupSize(),\n &work_groups));\n int best_work_group_index;\n RETURN_IF_ERROR(params.queue->GetBestWorkGroupIndex(\n kernel, *params.info, grid, work_groups, &best_work_group_index));\n *best_work_group = work_groups[best_work_group_index];\n return OkStatus();\n}\n\nint GetPenalty(int grid_size, int group_size) {\n const int reminder = grid_size % group_size;\n return reminder == 0 ? 0 : group_size - reminder;\n}\n\nint GetPenalty(int2 grid_size, int2 group_size) {\n const int p_x = GetPenalty(grid_size.x, group_size.x);\n const int p_y = GetPenalty(grid_size.y, group_size.y);\n return p_x * grid_size.y + p_y * grid_size.x + p_x * p_y;\n}\n\nint GetMaxSizeWithMinPenalty(int size, int max_size) {\n int best_size = 128;\n int min_penalty = GetPenalty(size, best_size);\n for (int i = 2; i * 128 <= max_size; ++i) {\n if (GetPenalty(size, i * 128) == min_penalty) {\n best_size = i * 128;\n }\n }\n return best_size;\n}\n\nint2 GetMaxSizeWithMinPenalty(int2 size, int max_size) {\n std::vector base_groups = Get2DWorkgroupsEqualTo128();\n int min_penalty = std::numeric_limits::max();\n for (auto group : base_groups) {\n min_penalty = std::min(GetPenalty(size, group), min_penalty);\n }\n for (auto group : base_groups) {\n for (int y = 1; y * group.y <= max_size; ++y) {\n int new_group_y = y * group.y;\n for (int x = 1; x * group.x <= max_size; ++x) {\n int new_group_x = x * group.x;\n if (new_group_x * new_group_y > max_size) {\n break;\n }\n if (GetPenalty(size, int2(new_group_x, new_group_y)) == min_penalty) {\n return int2(new_group_x, new_group_y);\n }\n }\n }\n }\n return int2(0, 0);\n}\n\nint GetBiggestDividerWithPriority(int number, int max_divider) {\n if (number % 8 == 0 && 8 <= max_divider) {\n return 8;\n }\n if (number % 4 == 0 && 4 <= max_divider) {\n return 4;\n }\n if (number % 2 == 0 && 2 <= max_divider) {\n return 2;\n }\n for (int i = max_divider; i != 0; i--) {\n if (number % i == 0) {\n return i;\n }\n }\n return 1;\n}\n\nint GetBiggestDivider(int number, int max_divider) {\n for (int i = max_divider; i != 0; i--) {\n if (number % i == 0) {\n return i;\n }\n }\n return 1;\n}\n\n} \/\/ namespace\n\nint3 GetWorkGroupXY128ConvLinear(const int3& grid) {\n int grid_z = GetBiggestDividerWithPriority(grid.z, 4);\n if (grid.x <= 128) {\n return int3(128, 1, grid_z);\n }\n int grid_x = GetMaxSizeWithMinPenalty(grid.x, 512 \/ grid_z);\n return {grid_x, 1, grid_z};\n}\n\nint3 GetWorkGroupXY128Conv(const int3& grid) {\n int grid_z = GetBiggestDividerWithPriority(grid.z, 4);\n if (grid.x <= 16 && grid.y <= 8) {\n return int3(16, 8, grid_z);\n }\n int2 grid_xy = GetMaxSizeWithMinPenalty(int2(grid.x, grid.y), 512 \/ grid_z);\n return int3(grid_xy.x, grid_xy.y, grid_z);\n}\n\nint3 GetWorkGroupXY128Simple(const int3& grid) { return int3(16, 8, 1); }\n\nint3 GetWorkGroup(const int3& grid, int max_size) {\n int wg_z = GetBiggestDividerWithPriority(grid.z, 8);\n int wg_xy_size = max_size \/ wg_z;\n int wg_x = std::min(IntegralDivideRoundUp(grid.x, 2), wg_xy_size);\n int wg_y = std::min(wg_xy_size \/ wg_x, grid.y);\n return int3(wg_x, wg_y, wg_z);\n}\n\nint3 GetWorkGroupConv(const int3& grid, int max_size, int max_z_size) {\n int wg_z = GetBiggestDivider(grid.z, max_z_size);\n int wg_xy_size = std::min(256, max_size) \/ wg_z;\n int wg_x = std::min(grid.x, wg_xy_size);\n int wg_y = std::min(wg_xy_size \/ wg_x, grid.y);\n if (wg_y == grid.y && grid.y % 2 == 0) {\n wg_y = grid.y \/ 2;\n }\n return int3(wg_x, wg_y, wg_z);\n}\n\nStatus GetBestWorkGroupXY128(const TuningParameters& params,\n const CLKernel& kernel, const int3& grid,\n WorkGroupSizeAlignment z_alignment,\n int3* best_work_group) {\n std::vector work_groups = GenerateWorkGroupSizesXY128(\n grid, kernel.GetMaxWorkGroupSize(), z_alignment);\n int best_work_group_index;\n RETURN_IF_ERROR(params.queue->GetBestWorkGroupIndex(\n kernel, *params.info, grid, work_groups, &best_work_group_index));\n *best_work_group = work_groups[best_work_group_index];\n return OkStatus();\n}\n\nStatus GetBestWorkGroupXY128Linear(const TuningParameters& params,\n const CLKernel& kernel, const int3& grid,\n WorkGroupSizeAlignment z_alignment,\n int3* best_work_group) {\n std::vector work_groups = GenerateWorkGroupSizesXY128Linear(\n grid, kernel.GetMaxWorkGroupSize(), z_alignment);\n int best_work_group_index;\n RETURN_IF_ERROR(params.queue->GetBestWorkGroupIndex(\n kernel, *params.info, grid, work_groups, &best_work_group_index));\n *best_work_group = work_groups[best_work_group_index];\n return OkStatus();\n}\n\nbool XY128RequiresMoreWorkGroupsThenXY128Linear(int width, int height) {\n int planar_work_groups = IntegralDivideRoundUp(width * height, 128);\n auto base_work_groups = Get2DWorkgroupsEqualTo128();\n bool have_equal_work_groups = false;\n for (auto& work_group : base_work_groups) {\n int x_groups = IntegralDivideRoundUp(width, work_group.x);\n int y_groups = IntegralDivideRoundUp(height, work_group.y);\n int xy_groups = x_groups * y_groups;\n if (xy_groups == planar_work_groups) {\n have_equal_work_groups = true;\n break;\n }\n }\n return !have_equal_work_groups;\n}\n\nStatus GetBestWorkGroup(const TuningParameters& params, const CLKernel& kernel,\n const int3& grid, int3* best_work_group) {\n switch (params.tuning_type) {\n case TuningType::FAST:\n if (params.info->vendor != Vendor::QUALCOMM) {\n *best_work_group = int3(8, 4, 1);\n return OkStatus();\n } else {\n *best_work_group = GetWorkGroup(grid, kernel.GetMaxWorkGroupSize());\n return OkStatus();\n }\n case TuningType::EXHAUSTIVE:\n return GetBestWorkGroupAlignedToGrid(params, kernel, grid,\n best_work_group);\n default:\n *best_work_group = {8, 4, 1};\n return OkStatus();\n }\n}\n\nStatus GetBestWorkGroupConv(const TuningParameters& params,\n const CLKernel& kernel, const int3& grid,\n int3* best_work_group) {\n switch (params.tuning_type) {\n case TuningType::FAST:\n if (params.info->vendor != Vendor::QUALCOMM) {\n *best_work_group = int3(8, 4, 1);\n return OkStatus();\n } else {\n int max_z_size = params.info->adreno_info.gpu_version < 400 ? 16 : 64;\n *best_work_group =\n GetWorkGroupConv(grid, kernel.GetMaxWorkGroupSize(), max_z_size);\n return OkStatus();\n }\n case TuningType::EXHAUSTIVE:\n return GetBestWorkGroupAlignedToGrid(params, kernel, grid,\n best_work_group);\n default:\n *best_work_group = {8, 4, 1};\n return OkStatus();\n }\n}\n\n} \/\/ namespace cl\n} \/\/ namespace gpu\n} \/\/ namespace tflite\nEnabling non trivial fast tuning for all vendors.\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/kernels\/work_group_picking.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"tensorflow\/lite\/delegates\/gpu\/common\/util.h\"\n\nnamespace tflite {\nnamespace gpu {\nnamespace cl {\n\nnamespace {\n\nstd::vector Get2DWorkgroupsEqualTo128() {\n return {{128, 1}, {64, 2}, {32, 4}, {16, 8},\n {8, 16}, {4, 32}, {2, 64}, {1, 128}};\n}\n\nstd::vector GenerateWorkGroupSizesXY128(\n int3 grid, int max_work_group_size, WorkGroupSizeAlignment z_alignment) {\n std::vector work_groups;\n work_groups.reserve(32);\n\n std::vector possible_z_sizes = GetPossibleSizes(grid.z, z_alignment);\n\n for (int x = 1; x <= max_work_group_size; x *= 2) {\n for (int y = 1; y <= max_work_group_size; y *= 2) {\n int work_group_size_xy = x * y;\n if (work_group_size_xy % 128 != 0 ||\n work_group_size_xy > max_work_group_size) {\n continue;\n }\n for (auto z : possible_z_sizes) {\n if (work_group_size_xy * z > max_work_group_size) {\n continue;\n }\n work_groups.push_back({x, y, z});\n }\n }\n }\n return work_groups;\n}\n\nstd::vector GenerateWorkGroupSizesXY128Linear(\n int3 grid, int max_work_group_size, WorkGroupSizeAlignment z_alignment) {\n std::vector work_groups;\n work_groups.reserve(32);\n\n std::vector possible_z_sizes = GetPossibleSizes(grid.z, z_alignment);\n\n for (int x = 128; x <= max_work_group_size && x < grid.x + 128; x += 128) {\n for (auto z : possible_z_sizes) {\n if (x * z <= max_work_group_size) {\n work_groups.push_back({x, 1, z});\n }\n }\n }\n return work_groups;\n}\n\nStatus GetBestWorkGroupAlignedToGrid(const TuningParameters& params,\n const CLKernel& kernel, const int3& grid,\n int3* best_work_group) {\n std::vector work_groups;\n RETURN_IF_ERROR(GenerateWorkGroupSizesAlignedToGrid(\n grid, params.info->max_work_group_sizes, kernel.GetMaxWorkGroupSize(),\n &work_groups));\n int best_work_group_index;\n RETURN_IF_ERROR(params.queue->GetBestWorkGroupIndex(\n kernel, *params.info, grid, work_groups, &best_work_group_index));\n *best_work_group = work_groups[best_work_group_index];\n return OkStatus();\n}\n\nint GetPenalty(int grid_size, int group_size) {\n const int reminder = grid_size % group_size;\n return reminder == 0 ? 0 : group_size - reminder;\n}\n\nint GetPenalty(int2 grid_size, int2 group_size) {\n const int p_x = GetPenalty(grid_size.x, group_size.x);\n const int p_y = GetPenalty(grid_size.y, group_size.y);\n return p_x * grid_size.y + p_y * grid_size.x + p_x * p_y;\n}\n\nint GetMaxSizeWithMinPenalty(int size, int max_size) {\n int best_size = 128;\n int min_penalty = GetPenalty(size, best_size);\n for (int i = 2; i * 128 <= max_size; ++i) {\n if (GetPenalty(size, i * 128) == min_penalty) {\n best_size = i * 128;\n }\n }\n return best_size;\n}\n\nint2 GetMaxSizeWithMinPenalty(int2 size, int max_size) {\n std::vector base_groups = Get2DWorkgroupsEqualTo128();\n int min_penalty = std::numeric_limits::max();\n for (auto group : base_groups) {\n min_penalty = std::min(GetPenalty(size, group), min_penalty);\n }\n for (auto group : base_groups) {\n for (int y = 1; y * group.y <= max_size; ++y) {\n int new_group_y = y * group.y;\n for (int x = 1; x * group.x <= max_size; ++x) {\n int new_group_x = x * group.x;\n if (new_group_x * new_group_y > max_size) {\n break;\n }\n if (GetPenalty(size, int2(new_group_x, new_group_y)) == min_penalty) {\n return int2(new_group_x, new_group_y);\n }\n }\n }\n }\n return int2(0, 0);\n}\n\nint GetBiggestDividerWithPriority(int number, int max_divider) {\n if (number % 8 == 0 && 8 <= max_divider) {\n return 8;\n }\n if (number % 4 == 0 && 4 <= max_divider) {\n return 4;\n }\n if (number % 2 == 0 && 2 <= max_divider) {\n return 2;\n }\n for (int i = max_divider; i != 0; i--) {\n if (number % i == 0) {\n return i;\n }\n }\n return 1;\n}\n\nint GetBiggestDivider(int number, int max_divider) {\n for (int i = max_divider; i != 0; i--) {\n if (number % i == 0) {\n return i;\n }\n }\n return 1;\n}\n\n} \/\/ namespace\n\nint3 GetWorkGroupXY128ConvLinear(const int3& grid) {\n int grid_z = GetBiggestDividerWithPriority(grid.z, 4);\n if (grid.x <= 128) {\n return int3(128, 1, grid_z);\n }\n int grid_x = GetMaxSizeWithMinPenalty(grid.x, 512 \/ grid_z);\n return {grid_x, 1, grid_z};\n}\n\nint3 GetWorkGroupXY128Conv(const int3& grid) {\n int grid_z = GetBiggestDividerWithPriority(grid.z, 4);\n if (grid.x <= 16 && grid.y <= 8) {\n return int3(16, 8, grid_z);\n }\n int2 grid_xy = GetMaxSizeWithMinPenalty(int2(grid.x, grid.y), 512 \/ grid_z);\n return int3(grid_xy.x, grid_xy.y, grid_z);\n}\n\nint3 GetWorkGroupXY128Simple(const int3& grid) { return int3(16, 8, 1); }\n\nint3 GetWorkGroup(const int3& grid, int max_size) {\n int wg_z = GetBiggestDividerWithPriority(grid.z, 8);\n int wg_xy_size = max_size \/ wg_z;\n int wg_x = std::min(IntegralDivideRoundUp(grid.x, 2), wg_xy_size);\n int wg_y = std::min(wg_xy_size \/ wg_x, grid.y);\n return int3(wg_x, wg_y, wg_z);\n}\n\nint3 GetWorkGroupConv(const int3& grid, int max_size, int max_z_size) {\n int wg_z = GetBiggestDivider(grid.z, max_z_size);\n int wg_xy_size = std::min(256, max_size) \/ wg_z;\n int wg_x = std::min(grid.x, wg_xy_size);\n int wg_y = std::min(wg_xy_size \/ wg_x, grid.y);\n if (wg_y == grid.y && grid.y % 2 == 0) {\n wg_y = grid.y \/ 2;\n }\n return int3(wg_x, wg_y, wg_z);\n}\n\nStatus GetBestWorkGroupXY128(const TuningParameters& params,\n const CLKernel& kernel, const int3& grid,\n WorkGroupSizeAlignment z_alignment,\n int3* best_work_group) {\n std::vector work_groups = GenerateWorkGroupSizesXY128(\n grid, kernel.GetMaxWorkGroupSize(), z_alignment);\n int best_work_group_index;\n RETURN_IF_ERROR(params.queue->GetBestWorkGroupIndex(\n kernel, *params.info, grid, work_groups, &best_work_group_index));\n *best_work_group = work_groups[best_work_group_index];\n return OkStatus();\n}\n\nStatus GetBestWorkGroupXY128Linear(const TuningParameters& params,\n const CLKernel& kernel, const int3& grid,\n WorkGroupSizeAlignment z_alignment,\n int3* best_work_group) {\n std::vector work_groups = GenerateWorkGroupSizesXY128Linear(\n grid, kernel.GetMaxWorkGroupSize(), z_alignment);\n int best_work_group_index;\n RETURN_IF_ERROR(params.queue->GetBestWorkGroupIndex(\n kernel, *params.info, grid, work_groups, &best_work_group_index));\n *best_work_group = work_groups[best_work_group_index];\n return OkStatus();\n}\n\nbool XY128RequiresMoreWorkGroupsThenXY128Linear(int width, int height) {\n int planar_work_groups = IntegralDivideRoundUp(width * height, 128);\n auto base_work_groups = Get2DWorkgroupsEqualTo128();\n bool have_equal_work_groups = false;\n for (auto& work_group : base_work_groups) {\n int x_groups = IntegralDivideRoundUp(width, work_group.x);\n int y_groups = IntegralDivideRoundUp(height, work_group.y);\n int xy_groups = x_groups * y_groups;\n if (xy_groups == planar_work_groups) {\n have_equal_work_groups = true;\n break;\n }\n }\n return !have_equal_work_groups;\n}\n\nStatus GetBestWorkGroup(const TuningParameters& params, const CLKernel& kernel,\n const int3& grid, int3* best_work_group) {\n switch (params.tuning_type) {\n case TuningType::FAST:\n *best_work_group = GetWorkGroup(grid, kernel.GetMaxWorkGroupSize());\n return OkStatus();\n case TuningType::EXHAUSTIVE:\n return GetBestWorkGroupAlignedToGrid(params, kernel, grid,\n best_work_group);\n default:\n *best_work_group = {8, 4, 1};\n return OkStatus();\n }\n}\n\nStatus GetBestWorkGroupConv(const TuningParameters& params,\n const CLKernel& kernel, const int3& grid,\n int3* best_work_group) {\n switch (params.tuning_type) {\n case TuningType::FAST: {\n int max_z_size = 16;\n if (params.info->vendor == Vendor::QUALCOMM) {\n max_z_size = params.info->adreno_info.gpu_version < 400 ? 16 : 64;\n }\n max_z_size = std::min(max_z_size, params.info->max_work_group_sizes.z);\n *best_work_group =\n GetWorkGroupConv(grid, kernel.GetMaxWorkGroupSize(), max_z_size);\n return OkStatus();\n }\n case TuningType::EXHAUSTIVE:\n return GetBestWorkGroupAlignedToGrid(params, kernel, grid,\n best_work_group);\n default:\n *best_work_group = {8, 4, 1};\n return OkStatus();\n }\n}\n\n} \/\/ namespace cl\n} \/\/ namespace gpu\n} \/\/ namespace tflite\n<|endoftext|>"} {"text":"#include \n#include \/* heap operations, std::sort *\/\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace shogun;\n\n#ifdef HAVE_EIGEN3\n\nstruct index_and_distance_struct\n{\n\tfloat64_t distance;\n\tindex_t neighbor_index;\n} ;\n\nstruct heap_comparator\n{\n\tbool operator() (const index_and_distance_struct& first, const index_and_distance_struct& second)\n\t{\n\t\treturn first.distance > second.distance;\n\t}\n} comparator;\n\nstd::vector get_neighbors_indices(CDistance* distance_object, index_t feature_vector_index, index_t n_neighbors);\n\nTEST(LocallyLinearEmbeddingTest,neighbors_preserving)\n{\n\tconst index_t n_samples = 100;\n\tconst index_t n_gaussians = 1;\n\tconst index_t n_dimensions = 4;\n\tconst index_t n_target_dimensions = 3;\n\tconst index_t n_neighbors = 30;\n\tCDenseFeatures* high_dimensional_features = \n\t\tnew CDenseFeatures(CDataGenerator::generate_gaussians(n_samples, n_gaussians, n_dimensions)); \n\t\n\tCDistance* high_dimensional_dist = \n\t\tnew CEuclideanDistance(high_dimensional_features, high_dimensional_features);\n\n\tstd::vector > neighbors_for_vectors;\n\t\/* Find n_neighbors nearest eighbours for each vector *\/\n\tfor (index_t i=0; iset_k(n_neighbors);\n\n\tlleEmbedder->set_target_dim(n_target_dimensions);\n\tEXPECT_EQ(n_target_dimensions, lleEmbedder->get_target_dim());\n\n\tCDenseFeatures* low_dimensional_features = \n\t\tlleEmbedder->embed(high_dimensional_features);\n\n\tEXPECT_EQ(n_target_dimensions,low_dimensional_features->get_dim_feature_space());\n\tEXPECT_EQ(high_dimensional_features->get_num_vectors(),low_dimensional_features->get_num_vectors());\n\n\tCDistance* low_dimensional_dist =\n\t\tnew CEuclideanDistance(low_dimensional_features, low_dimensional_features);\n\t\n\tfor (index_t i=0; i get_neighbors_indices(CDistance* distance_object, index_t feature_vector_index, index_t n_neighbors)\n{\n\tindex_t n_vectors = distance_object->get_num_vec_lhs();\n\tEXPECT_EQ(n_vectors, distance_object->get_num_vec_rhs());\n\tEXPECT_LE(n_neighbors, n_vectors - 1) << \"Number of neigbors can not be greater than total number of vectors minus 1\";\n\tEXPECT_LE(feature_vector_index, n_vectors - 1);\n\n\tstd::vector distances_and_indices;\n\n\tfor (index_t j = 0; jdistance(feature_vector_index, j);\n\t\tcurrent.neighbor_index = j;\n\t\tdistances_and_indices.push_back(current);\n\t}\n\n\t\/* Heapify, and then extract n_neighbors nearest neighbors*\/\n\tstd::make_heap(distances_and_indices.begin(), distances_and_indices.end(), comparator);\n\tstd::vector neighbors_for_current_vector;\n\tfor (index_t j = 0; j < n_neighbors; ++j)\n\t{\n\t\tneighbors_for_current_vector.push_back(distances_and_indices[0].neighbor_index);\n\t\tstd::pop_heap(distances_and_indices.begin(), distances_and_indices.end(), comparator);\n\t\tdistances_and_indices.pop_back();\n\t}\n\tstd::sort(neighbors_for_current_vector.begin(), neighbors_for_current_vector.end());\n\treturn neighbors_for_current_vector;\n}\n\n#endif\nModified unit test for Locally Linear Embedding, so that it allows 'misses' of neighbors before and after the dimensionality reduction.#include \n#include \n#include \/* heap operations, std::sort *\/\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace shogun;\n\n#ifdef HAVE_EIGEN3\n\nstruct index_and_distance_struct\n{\n\tfloat64_t distance;\n\tindex_t neighbor_index;\n} ;\n\nstruct heap_comparator\n{\n\tbool operator() (const index_and_distance_struct& first, const index_and_distance_struct& second)\n\t{\n\t\treturn first.distance > second.distance;\n\t}\n} comparator;\n\nstd::set get_neighbors_indices(CDistance* distance_object, index_t feature_vector_index, index_t n_neighbors);\n\nvoid check_similarity_of_sets(const std::set& first_set,const std::set& second_set, float min_similarity_level);\n\nTEST(LocallyLinearEmbeddingTest,neighbors_preserving)\n{\n\tconst index_t n_samples = 100;\n\tconst index_t n_gaussians = 1;\n\tconst index_t n_dimensions = 4;\n\tconst index_t n_target_dimensions = 3;\n\tconst index_t n_neighbors = 40;\n\tconst float required_similarity_level = 0.5; \/*hope we will get rid of this*\/\n\tCDenseFeatures* high_dimensional_features = \n\t\tnew CDenseFeatures(CDataGenerator::generate_gaussians(n_samples, n_gaussians, n_dimensions)); \n\t\n\tCDistance* high_dimensional_dist = \n\t\tnew CEuclideanDistance(high_dimensional_features, high_dimensional_features);\n\n\tstd::vector > high_dimensional_neighbors_for_vectors;\n\t\/* Find n_neighbors nearest eighbours for each vector *\/\n\tfor (index_t i=0; iset_k(n_neighbors);\n\n\tlleEmbedder->set_target_dim(n_target_dimensions);\n\tEXPECT_EQ(n_target_dimensions, lleEmbedder->get_target_dim());\n\n\tCDenseFeatures* low_dimensional_features = \n\t\tlleEmbedder->embed(high_dimensional_features);\n\n\tEXPECT_EQ(n_target_dimensions,low_dimensional_features->get_dim_feature_space());\n\tEXPECT_EQ(high_dimensional_features->get_num_vectors(),low_dimensional_features->get_num_vectors());\n\n\tCDistance* low_dimensional_dist =\n\t\tnew CEuclideanDistance(low_dimensional_features, low_dimensional_features);\n\t\n\tfor (index_t i=0; i low_dimensional_neighbors = get_neighbors_indices(low_dimensional_dist, i, n_neighbors);\n\t\tcheck_similarity_of_sets(high_dimensional_neighbors_for_vectors[i], low_dimensional_neighbors, required_similarity_level);\n\t}\n\n\tSG_UNREF(lleEmbedder);\n\tSG_UNREF(high_dimensional_dist);\n\tSG_UNREF(low_dimensional_dist);\n}\n\nstd::set get_neighbors_indices(CDistance* distance_object, index_t feature_vector_index, index_t n_neighbors)\n{\n\tindex_t n_vectors = distance_object->get_num_vec_lhs();\n\tEXPECT_EQ(n_vectors, distance_object->get_num_vec_rhs());\n\tEXPECT_LE(n_neighbors, n_vectors - 1) << \"Number of neigbors can not be greater than total number of vectors minus 1\";\n\tEXPECT_LE(feature_vector_index, n_vectors - 1);\n\n\tstd::vector distances_and_indices;\n\n\tfor (index_t j = 0; jdistance(feature_vector_index, j);\n\t\tcurrent.neighbor_index = j;\n\t\tdistances_and_indices.push_back(current);\n\t}\n\n\t\/* Heapify, and then extract n_neighbors nearest neighbors*\/\n\tstd::make_heap(distances_and_indices.begin(), distances_and_indices.end(), comparator);\n\tstd::set neighbors_for_current_vector;\n\tfor (index_t j = 0; j < n_neighbors; ++j)\n\t{\n\t\tneighbors_for_current_vector.insert(distances_and_indices[0].neighbor_index);\n\t\tstd::pop_heap(distances_and_indices.begin(), distances_and_indices.end(), comparator);\n\t\tdistances_and_indices.pop_back();\n\t}\n\treturn neighbors_for_current_vector;\n}\n\nvoid check_similarity_of_sets(const std::set& first_set,const std::set& second_set, float min_similarity_level)\n{\n\tindex_t total_elements_count = first_set.size();\n\tASSERT_EQ(total_elements_count, second_set.size()) << \"Can not compare sets of different size.\";\n\tASSERT_LE(min_similarity_level, 1.0) << \"Similarity level can not be greater than 1.\";\n\tASSERT_GE(min_similarity_level, 0) << \"Similarity level can not be less than 0.\";\n\tif (min_similarity_level == 0)\n\t\t\/*Nothing to do*\/\n\t\treturn;\n\tindex_t similar_elements_count = 0;\n\tstd::set::iterator first_iter = first_set.begin(), second_iter = second_set.begin();\n\twhile (first_iter != first_set.end() && second_iter != second_set.end())\n\t{\n\t\tif (*first_iter < *second_iter)\n\t\t\t++first_iter;\n\t\telse if (*second_iter < *first_iter)\n\t\t\t++second_iter;\n\t\telse\n\t\t{\n\t\t\t++similar_elements_count; ++first_iter; ++second_iter;\n\t\t}\n\t}\n\tEXPECT_GE((float) similar_elements_count \/(float) total_elements_count, min_similarity_level)<<\"#similarElements\/#total < minimal similarity level.\";\n}\n#endif\n<|endoftext|>"} {"text":"\/*\n * Copyright 2007-2021 CM4all GmbH\n * All rights reserved.\n *\n * author: Max Kellermann \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"CommandLine.hxx\"\n#include \"Config.hxx\"\n#include \"net\/Parser.hxx\"\n#include \"io\/Logger.hxx\"\n#include \"util\/StringView.hxx\"\n#include \"util\/IterableSplitString.hxx\"\n#include \"version.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nstatic void\nPrintUsage()\n{\n\tputs(\"usage: cm4all-beng-proxy [options]\\n\\n\"\n\t \"valid options:\\n\"\n#ifdef __GLIBC__\n\t \" --help\\n\"\n#endif\n\t \" -h help (this text)\\n\"\n#ifdef __GLIBC__\n\t \" --version\\n\"\n#endif\n\t \" -V show cm4all-beng-proxy version\\n\"\n#ifdef __GLIBC__\n\t \" --verbose\\n\"\n#endif\n\t \" -v be more verbose\\n\"\n#ifdef __GLIBC__\n\t \" --quiet\\n\"\n#endif\n\t \" -q be quiet\\n\"\n#ifdef __GLIBC__\n\t \" --config-file file\\n\"\n#endif\n\t \" -f file load this configuration file\\n\"\n#ifdef __GLIBC__\n\t \" --logger-user name\\n\"\n#endif\n\t \" -U name execute the error logger program with this user id\\n\"\n#ifdef __GLIBC__\n\t \" --document-root DIR\\n\"\n#endif\n\t \" -r DIR set the document root\\n\"\n#ifdef __GLIBC__\n\t \" --translation-socket PATH\\n\"\n#endif\n\t \" -t PATH set the path to the translation server socket\\n\"\n#ifdef __GLIBC__\n\t \" --cluster-size N\\n\"\n#endif\n\t \" -C N set the size of the beng-lb cluster\\n\"\n#ifdef __GLIBC__\n\t \" --cluster-node N\\n\"\n#endif\n\t \" -N N set the index of this node in the beng-lb cluster\\n\"\n#ifdef __GLIBC__\n\t \" --ua-classes PATH\\n\"\n#endif\n\t \" -a PATH load the User-Agent classification rules from this file\\n\"\n#ifdef __GLIBC__\n\t \" --set NAME=VALUE tweak an internal variable, see manual for details\\n\"\n#endif\n\t \" -s NAME=VALUE \\n\"\n\t \"\\n\"\n\t );\n}\n\nstatic void arg_error(const char *argv0, const char *fmt, ...)\n\t__attribute__ ((noreturn))\n\t__attribute__((format(printf,2,3)));\nstatic void arg_error(const char *argv0, const char *fmt, ...) {\n\tif (fmt != nullptr) {\n\t\tva_list ap;\n\n\t\tfputs(argv0, stderr);\n\t\tfputs(\": \", stderr);\n\n\t\tva_start(ap, fmt);\n\t\tvfprintf(stderr, fmt, ap);\n\t\tva_end(ap);\n\n\t\tputc('\\n', stderr);\n\t}\n\n\tfprintf(stderr, \"Try '%s --help' for more information.\\n\",\n\t\targv0);\n\texit(1);\n}\n\ntemplate\nstatic void\nSplitForEach(const char *p, char separator, F &&f)\n{\n\tfor (auto value : IterableSplitString(p, separator))\n\t\tif (!value.empty())\n\t\t\tf(std::string(value.data, value.size).c_str());\n}\n\nstatic void\nHandleSet(BpConfig &config,\n\t const char *argv0, const char *p)\n{\n\tconst char *eq;\n\n\teq = strchr(p, '=');\n\tif (eq == nullptr)\n\t\targ_error(argv0, \"No '=' found in --set argument\");\n\n\tif (eq == p)\n\t\targ_error(argv0, \"No name found in --set argument\");\n\n\tconst StringView name(p, eq - p);\n\tconst char *const value = eq + 1;\n\n\ttry {\n\t\tconfig.HandleSet(name, value);\n\t} catch (const std::runtime_error &e) {\n\t\targ_error(argv0, \"Error while parsing \\\"--set %.*s\\\": %s\",\n\t\t\t (int)name.size, name.data, e.what());\n\t}\n}\n\n\/** read configuration options from the command line *\/\nvoid\nParseCommandLine(BpCmdLine &cmdline, BpConfig &config, int argc, char **argv)\n{\n\tint ret;\n\tchar *endptr;\n#ifdef __GLIBC__\n\tstatic constexpr struct option long_options[] = {\n\t\t{\"help\", 0, nullptr, 'h'},\n\t\t{\"version\", 0, nullptr, 'V'},\n\t\t{\"verbose\", 0, nullptr, 'v'},\n\t\t{\"quiet\", 0, nullptr, 'q'},\n\t\t{\"config-file\", 1, nullptr, 'f'},\n\t\t{\"user\", 1, nullptr, 'u'},\n\t\t{\"logger-user\", 1, nullptr, 'U'},\n\t\t{\"translation-socket\", 1, nullptr, 't'},\n\t\t{\"cluster-size\", 1, nullptr, 'C'},\n\t\t{\"cluster-node\", 1, nullptr, 'N'},\n\t\t{\"ua-classes\", 1, nullptr, 'a'},\n\t\t{\"set\", 1, nullptr, 's'},\n\t\t{\"debug-listener-tag\", 1, nullptr, 'L'},\n\t\t{nullptr, 0, nullptr, 0}\n\t};\n#endif\n\tunsigned verbose = 1;\n\n\twhile (1) {\n#ifdef __GLIBC__\n\t\tint option_index = 0;\n\n\t\tret = getopt_long(argc, argv,\n\t\t\t\t \"hVvqf:U:t:B:C:N:s:\",\n\t\t\t\t long_options, &option_index);\n#else\n\t\tret = getopt(argc, argv,\n\t\t\t \"hVvqf:U:t:B:C:N:s:\");\n#endif\n\t\tif (ret == -1)\n\t\t\tbreak;\n\n\t\tswitch (ret) {\n\t\tcase 'h':\n\t\t\tPrintUsage();\n\t\t\texit(0);\n\n\t\tcase 'V':\n\t\t\tprintf(\"cm4all-beng-proxy v%s\\n\", VERSION);\n\t\t\texit(0);\n\n\t\tcase 'v':\n\t\t\t++verbose;\n\t\t\tbreak;\n\n\t\tcase 'q':\n\t\t\tverbose = 0;\n\t\t\tbreak;\n\n\t\tcase 'f':\n\t\t\tcmdline.config_file = optarg;\n\t\t\tbreak;\n\n\t\tcase 'U':\n\t\t\tcmdline.logger_user.Lookup(optarg);\n\t\t\tbreak;\n\n\t\tcase 't':\n\t\t\tconfig.translation_sockets.emplace_front(ParseSocketAddress(optarg, 0, false));\n\t\t\tbreak;\n\n\t\tcase 'C':\n\t\t\tconfig.cluster_size = strtoul(optarg, &endptr, 10);\n\t\t\tif (endptr == optarg || *endptr != 0 ||\n\t\t\t config.cluster_size > 1024)\n\t\t\t\targ_error(argv[0], \"Invalid cluster size number\");\n\n\t\t\tif (config.cluster_node >= config.cluster_size)\n\t\t\t\tconfig.cluster_node = 0;\n\t\t\tbreak;\n\n\t\tcase 'N':\n\t\t\tconfig.cluster_node = strtoul(optarg, &endptr, 10);\n\t\t\tif (endptr == optarg || *endptr != 0)\n\t\t\t\targ_error(argv[0], \"Invalid cluster size number\");\n\n\t\t\tif ((config.cluster_node != 0 || config.cluster_size != 0) &&\n\t\t\t config.cluster_node >= config.cluster_size)\n\t\t\t\targ_error(argv[0], \"Cluster node too large\");\n\t\t\tbreak;\n\n\t\tcase 'a':\n\t\t\tcmdline.ua_classification_file = optarg;\n\t\t\tbreak;\n\n\t\tcase 's':\n\t\t\tHandleSet(config, argv[0], optarg);\n\t\t\tbreak;\n\n\t\tcase 'L':\n\t\t\tcmdline.debug_listener_tag = optarg;\n\t\t\tbreak;\n\n\t\tcase '?':\n\t\t\targ_error(argv[0], nullptr);\n\n\t\tdefault:\n\t\t\texit(1);\n\t\t}\n\t}\n\n\tSetLogLevel(verbose);\n\n\t\/* check non-option arguments *\/\n\n\tif (optind < argc)\n\t\targ_error(argv[0], \"unrecognized argument: %s\", argv[optind]);\n}\nbp\/CommandLine: remove obsolete --user option\/*\n * Copyright 2007-2021 CM4all GmbH\n * All rights reserved.\n *\n * author: Max Kellermann \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"CommandLine.hxx\"\n#include \"Config.hxx\"\n#include \"net\/Parser.hxx\"\n#include \"io\/Logger.hxx\"\n#include \"util\/StringView.hxx\"\n#include \"util\/IterableSplitString.hxx\"\n#include \"version.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nstatic void\nPrintUsage()\n{\n\tputs(\"usage: cm4all-beng-proxy [options]\\n\\n\"\n\t \"valid options:\\n\"\n#ifdef __GLIBC__\n\t \" --help\\n\"\n#endif\n\t \" -h help (this text)\\n\"\n#ifdef __GLIBC__\n\t \" --version\\n\"\n#endif\n\t \" -V show cm4all-beng-proxy version\\n\"\n#ifdef __GLIBC__\n\t \" --verbose\\n\"\n#endif\n\t \" -v be more verbose\\n\"\n#ifdef __GLIBC__\n\t \" --quiet\\n\"\n#endif\n\t \" -q be quiet\\n\"\n#ifdef __GLIBC__\n\t \" --config-file file\\n\"\n#endif\n\t \" -f file load this configuration file\\n\"\n#ifdef __GLIBC__\n\t \" --logger-user name\\n\"\n#endif\n\t \" -U name execute the error logger program with this user id\\n\"\n#ifdef __GLIBC__\n\t \" --document-root DIR\\n\"\n#endif\n\t \" -r DIR set the document root\\n\"\n#ifdef __GLIBC__\n\t \" --translation-socket PATH\\n\"\n#endif\n\t \" -t PATH set the path to the translation server socket\\n\"\n#ifdef __GLIBC__\n\t \" --cluster-size N\\n\"\n#endif\n\t \" -C N set the size of the beng-lb cluster\\n\"\n#ifdef __GLIBC__\n\t \" --cluster-node N\\n\"\n#endif\n\t \" -N N set the index of this node in the beng-lb cluster\\n\"\n#ifdef __GLIBC__\n\t \" --ua-classes PATH\\n\"\n#endif\n\t \" -a PATH load the User-Agent classification rules from this file\\n\"\n#ifdef __GLIBC__\n\t \" --set NAME=VALUE tweak an internal variable, see manual for details\\n\"\n#endif\n\t \" -s NAME=VALUE \\n\"\n\t \"\\n\"\n\t );\n}\n\nstatic void arg_error(const char *argv0, const char *fmt, ...)\n\t__attribute__ ((noreturn))\n\t__attribute__((format(printf,2,3)));\nstatic void arg_error(const char *argv0, const char *fmt, ...) {\n\tif (fmt != nullptr) {\n\t\tva_list ap;\n\n\t\tfputs(argv0, stderr);\n\t\tfputs(\": \", stderr);\n\n\t\tva_start(ap, fmt);\n\t\tvfprintf(stderr, fmt, ap);\n\t\tva_end(ap);\n\n\t\tputc('\\n', stderr);\n\t}\n\n\tfprintf(stderr, \"Try '%s --help' for more information.\\n\",\n\t\targv0);\n\texit(1);\n}\n\ntemplate\nstatic void\nSplitForEach(const char *p, char separator, F &&f)\n{\n\tfor (auto value : IterableSplitString(p, separator))\n\t\tif (!value.empty())\n\t\t\tf(std::string(value.data, value.size).c_str());\n}\n\nstatic void\nHandleSet(BpConfig &config,\n\t const char *argv0, const char *p)\n{\n\tconst char *eq;\n\n\teq = strchr(p, '=');\n\tif (eq == nullptr)\n\t\targ_error(argv0, \"No '=' found in --set argument\");\n\n\tif (eq == p)\n\t\targ_error(argv0, \"No name found in --set argument\");\n\n\tconst StringView name(p, eq - p);\n\tconst char *const value = eq + 1;\n\n\ttry {\n\t\tconfig.HandleSet(name, value);\n\t} catch (const std::runtime_error &e) {\n\t\targ_error(argv0, \"Error while parsing \\\"--set %.*s\\\": %s\",\n\t\t\t (int)name.size, name.data, e.what());\n\t}\n}\n\n\/** read configuration options from the command line *\/\nvoid\nParseCommandLine(BpCmdLine &cmdline, BpConfig &config, int argc, char **argv)\n{\n\tint ret;\n\tchar *endptr;\n#ifdef __GLIBC__\n\tstatic constexpr struct option long_options[] = {\n\t\t{\"help\", 0, nullptr, 'h'},\n\t\t{\"version\", 0, nullptr, 'V'},\n\t\t{\"verbose\", 0, nullptr, 'v'},\n\t\t{\"quiet\", 0, nullptr, 'q'},\n\t\t{\"config-file\", 1, nullptr, 'f'},\n\t\t{\"logger-user\", 1, nullptr, 'U'},\n\t\t{\"translation-socket\", 1, nullptr, 't'},\n\t\t{\"cluster-size\", 1, nullptr, 'C'},\n\t\t{\"cluster-node\", 1, nullptr, 'N'},\n\t\t{\"ua-classes\", 1, nullptr, 'a'},\n\t\t{\"set\", 1, nullptr, 's'},\n\t\t{\"debug-listener-tag\", 1, nullptr, 'L'},\n\t\t{nullptr, 0, nullptr, 0}\n\t};\n#endif\n\tunsigned verbose = 1;\n\n\twhile (1) {\n#ifdef __GLIBC__\n\t\tint option_index = 0;\n\n\t\tret = getopt_long(argc, argv,\n\t\t\t\t \"hVvqf:U:t:B:C:N:s:\",\n\t\t\t\t long_options, &option_index);\n#else\n\t\tret = getopt(argc, argv,\n\t\t\t \"hVvqf:U:t:B:C:N:s:\");\n#endif\n\t\tif (ret == -1)\n\t\t\tbreak;\n\n\t\tswitch (ret) {\n\t\tcase 'h':\n\t\t\tPrintUsage();\n\t\t\texit(0);\n\n\t\tcase 'V':\n\t\t\tprintf(\"cm4all-beng-proxy v%s\\n\", VERSION);\n\t\t\texit(0);\n\n\t\tcase 'v':\n\t\t\t++verbose;\n\t\t\tbreak;\n\n\t\tcase 'q':\n\t\t\tverbose = 0;\n\t\t\tbreak;\n\n\t\tcase 'f':\n\t\t\tcmdline.config_file = optarg;\n\t\t\tbreak;\n\n\t\tcase 'U':\n\t\t\tcmdline.logger_user.Lookup(optarg);\n\t\t\tbreak;\n\n\t\tcase 't':\n\t\t\tconfig.translation_sockets.emplace_front(ParseSocketAddress(optarg, 0, false));\n\t\t\tbreak;\n\n\t\tcase 'C':\n\t\t\tconfig.cluster_size = strtoul(optarg, &endptr, 10);\n\t\t\tif (endptr == optarg || *endptr != 0 ||\n\t\t\t config.cluster_size > 1024)\n\t\t\t\targ_error(argv[0], \"Invalid cluster size number\");\n\n\t\t\tif (config.cluster_node >= config.cluster_size)\n\t\t\t\tconfig.cluster_node = 0;\n\t\t\tbreak;\n\n\t\tcase 'N':\n\t\t\tconfig.cluster_node = strtoul(optarg, &endptr, 10);\n\t\t\tif (endptr == optarg || *endptr != 0)\n\t\t\t\targ_error(argv[0], \"Invalid cluster size number\");\n\n\t\t\tif ((config.cluster_node != 0 || config.cluster_size != 0) &&\n\t\t\t config.cluster_node >= config.cluster_size)\n\t\t\t\targ_error(argv[0], \"Cluster node too large\");\n\t\t\tbreak;\n\n\t\tcase 'a':\n\t\t\tcmdline.ua_classification_file = optarg;\n\t\t\tbreak;\n\n\t\tcase 's':\n\t\t\tHandleSet(config, argv[0], optarg);\n\t\t\tbreak;\n\n\t\tcase 'L':\n\t\t\tcmdline.debug_listener_tag = optarg;\n\t\t\tbreak;\n\n\t\tcase '?':\n\t\t\targ_error(argv[0], nullptr);\n\n\t\tdefault:\n\t\t\texit(1);\n\t\t}\n\t}\n\n\tSetLogLevel(verbose);\n\n\t\/* check non-option arguments *\/\n\n\tif (optind < argc)\n\t\targ_error(argv[0], \"unrecognized argument: %s\", argv[optind]);\n}\n<|endoftext|>"} {"text":"11995 - I Can Guess the Data Structure!<|endoftext|>"} {"text":"#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace Tp;\n\nclass TestContactsInfo : public Test\n{\n Q_OBJECT\n\npublic:\n TestContactsInfo(QObject *parent = 0)\n : Test(parent), mConn(0), mContactsInfoFieldsUpdated(0)\n { }\n\nprotected Q_SLOTS:\n void onContactInfoFieldsChanged(const Tp::Contact::InfoFields &);\n\nprivate Q_SLOTS:\n void initTestCase();\n void init();\n\n void testInfo();\n\n void cleanup();\n void cleanupTestCase();\n\nprivate:\n TestConnHelper *mConn;\n int mContactsInfoFieldsUpdated;\n};\n\nvoid TestContactsInfo::onContactInfoFieldsChanged(const Tp::Contact::InfoFields &info)\n{\n Q_UNUSED(info);\n mContactsInfoFieldsUpdated++;\n mLoop->exit(0);\n}\n\nvoid TestContactsInfo::initTestCase()\n{\n initTestCaseImpl();\n\n g_type_init();\n g_set_prgname(\"contacts-info\");\n tp_debug_set_flags(\"all\");\n dbus_g_bus_get(DBUS_BUS_STARTER, 0);\n\n mConn = new TestConnHelper(this,\n TP_TESTS_TYPE_CONTACTS_CONNECTION,\n \"account\", \"me@example.com\",\n \"protocol\", \"foo\",\n NULL);\n QCOMPARE(mConn->connect(), true);\n}\n\nvoid TestContactsInfo::init()\n{\n initImpl();\n mContactsInfoFieldsUpdated = 0;\n}\n\nvoid TestContactsInfo::testInfo()\n{\n ContactManagerPtr contactManager = mConn->client()->contactManager();\n\n QVERIFY(contactManager->supportedFeatures().contains(Contact::FeatureInfo));\n\n QStringList validIDs = QStringList() << QLatin1String(\"foo\")\n << QLatin1String(\"bar\");\n QList contacts = mConn->contacts(validIDs, Contact::FeatureInfo);\n QCOMPARE(contacts.size(), validIDs.size());\n for (int i = 0; i < contacts.size(); i++) {\n ContactPtr contact = contacts[i];\n\n QCOMPARE(contact->requestedFeatures().contains(Contact::FeatureInfo), true);\n QCOMPARE(contact->actualFeatures().contains(Contact::FeatureInfo), true);\n\n QVERIFY(contact->infoFields().allFields().isEmpty());\n\n QVERIFY(connect(contact.data(),\n SIGNAL(infoFieldsChanged(const Tp::Contact::InfoFields &)),\n SLOT(onContactInfoFieldsChanged(const Tp::Contact::InfoFields &))));\n }\n\n GPtrArray *info_default = (GPtrArray *) dbus_g_type_specialized_construct (\n TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST);\n {\n const gchar * const field_values[2] = {\n \"FooBar\", NULL\n };\n g_ptr_array_add (info_default, tp_value_array_build (3,\n G_TYPE_STRING, \"n\",\n G_TYPE_STRV, NULL,\n G_TYPE_STRV, field_values,\n G_TYPE_INVALID));\n }\n tp_tests_contacts_connection_set_default_contact_info(TP_TESTS_CONTACTS_CONNECTION(mConn->service()),\n info_default);\n\n GPtrArray *info_1 = (GPtrArray *) dbus_g_type_specialized_construct (\n TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST);\n {\n const gchar * const field_values[2] = {\n \"Foo\", NULL\n };\n g_ptr_array_add (info_1, tp_value_array_build (3,\n G_TYPE_STRING, \"n\",\n G_TYPE_STRV, NULL,\n G_TYPE_STRV, field_values,\n G_TYPE_INVALID));\n }\n GPtrArray *info_2 = (GPtrArray *) dbus_g_type_specialized_construct (\n TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST);\n {\n const gchar * const field_values[2] = {\n \"Bar\", NULL\n };\n g_ptr_array_add (info_2, tp_value_array_build (3,\n G_TYPE_STRING, \"n\",\n G_TYPE_STRV, NULL,\n G_TYPE_STRV, field_values,\n G_TYPE_INVALID));\n }\n\n TpHandle handles[] = { 0, 0 };\n TpHandleRepoIface *serviceRepo = tp_base_connection_get_handles(\n TP_BASE_CONNECTION(mConn->service()), TP_HANDLE_TYPE_CONTACT);\n\n for (unsigned i = 0; i < 2; i++) {\n handles[i] = tp_handle_ensure(serviceRepo, qPrintable(validIDs[i]),\n NULL, NULL);\n }\n\n tp_tests_contacts_connection_change_contact_info(TP_TESTS_CONTACTS_CONNECTION(mConn->service()),\n handles[0], info_1);\n tp_tests_contacts_connection_change_contact_info(TP_TESTS_CONTACTS_CONNECTION(mConn->service()),\n handles[1], info_2);\n\n while (mContactsInfoFieldsUpdated != 2) {\n QCOMPARE(mLoop->exec(), 0);\n }\n\n QCOMPARE(mContactsInfoFieldsUpdated, 2);\n\n mContactsInfoFieldsUpdated = 0;\n ContactPtr contactFoo = contacts[0];\n ContactPtr contactBar = contacts[1];\n\n QCOMPARE(contactFoo->infoFields().isValid(), true);\n QCOMPARE(contactFoo->infoFields().allFields().size(), 1);\n QCOMPARE(contactFoo->infoFields().allFields()[0].fieldName, QLatin1String(\"n\"));\n QCOMPARE(contactFoo->infoFields().allFields()[0].fieldValue[0], QLatin1String(\"Foo\"));\n QCOMPARE(contactBar->infoFields().isValid(), true);\n QCOMPARE(contactBar->infoFields().allFields().size(), 1);\n QCOMPARE(contactBar->infoFields().allFields()[0].fieldName, QLatin1String(\"n\"));\n QCOMPARE(contactBar->infoFields().allFields()[0].fieldValue[0], QLatin1String(\"Bar\"));\n\n mContactsInfoFieldsUpdated = 0;\n Q_FOREACH (const ContactPtr &contact, contacts) {\n PendingOperation *op = contact->refreshInfo();\n QVERIFY(connect(op,\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n QCOMPARE(mLoop->exec(), 0);\n }\n\n while (mContactsInfoFieldsUpdated != contacts.size()) {\n mLoop->processEvents();\n }\n\n QCOMPARE(mContactsInfoFieldsUpdated, contacts.size());\n\n for (int i = 0; i < contacts.size(); i++) {\n ContactPtr contact = contacts[i];\n QVERIFY(disconnect(contact.data(),\n SIGNAL(infoFieldsChanged(const Tp::Contact::InfoFields &)),\n this,\n SLOT(onContactInfoFieldsChanged(const Tp::Contact::InfoFields &))));\n }\n\n PendingContactInfo *pci = contactFoo->requestInfo();\n QVERIFY(connect(pci,\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n while (!pci->isFinished()) {\n QCOMPARE(mLoop->exec(), 0);\n }\n\n QCOMPARE(pci->infoFields().isValid(), true);\n QCOMPARE(pci->infoFields().allFields().size(), 1);\n QCOMPARE(pci->infoFields().allFields()[0].fieldName, QLatin1String(\"n\"));\n QCOMPARE(pci->infoFields().allFields()[0].fieldValue[0], QLatin1String(\"FooBar\"));\n\n g_boxed_free(TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST, info_default);\n g_boxed_free(TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST, info_1);\n g_boxed_free(TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST, info_2);\n}\n\nvoid TestContactsInfo::cleanup()\n{\n cleanupImpl();\n}\n\nvoid TestContactsInfo::cleanupTestCase()\n{\n QCOMPARE(mConn->disconnect(), true);\n delete mConn;\n\n cleanupTestCaseImpl();\n}\n\nQTEST_MAIN(TestContactsInfo)\n#include \"_gen\/contacts-info.cpp.moc.hpp\"\ncontacts-info test: Add test to check how many times RefreshContactInfo is called.#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace Tp;\n\nclass TestContactsInfo : public Test\n{\n Q_OBJECT\n\npublic:\n TestContactsInfo(QObject *parent = 0)\n : Test(parent), mConn(0), mContactsInfoFieldsUpdated(0)\n { }\n\nprotected Q_SLOTS:\n void onContactInfoFieldsChanged(const Tp::Contact::InfoFields &);\n\nprivate Q_SLOTS:\n void initTestCase();\n void init();\n\n void testInfo();\n\n void cleanup();\n void cleanupTestCase();\n\nprivate:\n TestConnHelper *mConn;\n int mContactsInfoFieldsUpdated;\n};\n\nvoid TestContactsInfo::onContactInfoFieldsChanged(const Tp::Contact::InfoFields &info)\n{\n Q_UNUSED(info);\n mContactsInfoFieldsUpdated++;\n}\n\nvoid TestContactsInfo::initTestCase()\n{\n initTestCaseImpl();\n\n g_type_init();\n g_set_prgname(\"contacts-info\");\n tp_debug_set_flags(\"all\");\n dbus_g_bus_get(DBUS_BUS_STARTER, 0);\n\n mConn = new TestConnHelper(this,\n TP_TESTS_TYPE_CONTACTS_CONNECTION,\n \"account\", \"me@example.com\",\n \"protocol\", \"foo\",\n NULL);\n QCOMPARE(mConn->connect(), true);\n}\n\nvoid TestContactsInfo::init()\n{\n initImpl();\n mContactsInfoFieldsUpdated = 0;\n}\n\nvoid TestContactsInfo::testInfo()\n{\n ContactManagerPtr contactManager = mConn->client()->contactManager();\n\n QVERIFY(contactManager->supportedFeatures().contains(Contact::FeatureInfo));\n\n QStringList validIDs = QStringList() << QLatin1String(\"foo\")\n << QLatin1String(\"bar\");\n QList contacts = mConn->contacts(validIDs, Contact::FeatureInfo);\n QCOMPARE(contacts.size(), validIDs.size());\n for (int i = 0; i < contacts.size(); i++) {\n ContactPtr contact = contacts[i];\n\n QCOMPARE(contact->requestedFeatures().contains(Contact::FeatureInfo), true);\n QCOMPARE(contact->actualFeatures().contains(Contact::FeatureInfo), true);\n\n QVERIFY(contact->infoFields().allFields().isEmpty());\n\n QVERIFY(connect(contact.data(),\n SIGNAL(infoFieldsChanged(const Tp::Contact::InfoFields &)),\n SLOT(onContactInfoFieldsChanged(const Tp::Contact::InfoFields &))));\n }\n\n GPtrArray *info_default = (GPtrArray *) dbus_g_type_specialized_construct (\n TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST);\n {\n const gchar * const field_values[2] = {\n \"FooBar\", NULL\n };\n g_ptr_array_add (info_default, tp_value_array_build (3,\n G_TYPE_STRING, \"n\",\n G_TYPE_STRV, NULL,\n G_TYPE_STRV, field_values,\n G_TYPE_INVALID));\n }\n tp_tests_contacts_connection_set_default_contact_info(TP_TESTS_CONTACTS_CONNECTION(mConn->service()),\n info_default);\n\n GPtrArray *info_1 = (GPtrArray *) dbus_g_type_specialized_construct (\n TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST);\n {\n const gchar * const field_values[2] = {\n \"Foo\", NULL\n };\n g_ptr_array_add (info_1, tp_value_array_build (3,\n G_TYPE_STRING, \"n\",\n G_TYPE_STRV, NULL,\n G_TYPE_STRV, field_values,\n G_TYPE_INVALID));\n }\n GPtrArray *info_2 = (GPtrArray *) dbus_g_type_specialized_construct (\n TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST);\n {\n const gchar * const field_values[2] = {\n \"Bar\", NULL\n };\n g_ptr_array_add (info_2, tp_value_array_build (3,\n G_TYPE_STRING, \"n\",\n G_TYPE_STRV, NULL,\n G_TYPE_STRV, field_values,\n G_TYPE_INVALID));\n }\n\n TpHandle handles[] = { 0, 0 };\n TpHandleRepoIface *serviceRepo = tp_base_connection_get_handles(\n TP_BASE_CONNECTION(mConn->service()), TP_HANDLE_TYPE_CONTACT);\n\n for (unsigned i = 0; i < 2; i++) {\n handles[i] = tp_handle_ensure(serviceRepo, qPrintable(validIDs[i]),\n NULL, NULL);\n }\n\n tp_tests_contacts_connection_change_contact_info(TP_TESTS_CONTACTS_CONNECTION(mConn->service()),\n handles[0], info_1);\n tp_tests_contacts_connection_change_contact_info(TP_TESTS_CONTACTS_CONNECTION(mConn->service()),\n handles[1], info_2);\n\n while (mContactsInfoFieldsUpdated != 2) {\n mLoop->processEvents();\n }\n\n QCOMPARE(mContactsInfoFieldsUpdated, 2);\n\n mContactsInfoFieldsUpdated = 0;\n ContactPtr contactFoo = contacts[0];\n ContactPtr contactBar = contacts[1];\n\n QCOMPARE(contactFoo->infoFields().isValid(), true);\n QCOMPARE(contactFoo->infoFields().allFields().size(), 1);\n QCOMPARE(contactFoo->infoFields().allFields()[0].fieldName, QLatin1String(\"n\"));\n QCOMPARE(contactFoo->infoFields().allFields()[0].fieldValue[0], QLatin1String(\"Foo\"));\n QCOMPARE(contactBar->infoFields().isValid(), true);\n QCOMPARE(contactBar->infoFields().allFields().size(), 1);\n QCOMPARE(contactBar->infoFields().allFields()[0].fieldName, QLatin1String(\"n\"));\n QCOMPARE(contactBar->infoFields().allFields()[0].fieldValue[0], QLatin1String(\"Bar\"));\n\n TpTestsContactsConnection *serviceConn = TP_TESTS_CONTACTS_CONNECTION(mConn->service());\n QCOMPARE(serviceConn->refresh_contact_info_called, static_cast(0));\n\n mContactsInfoFieldsUpdated = 0;\n Q_FOREACH (const ContactPtr &contact, contacts) {\n QVERIFY(contact->refreshInfo());\n }\n while (mContactsInfoFieldsUpdated != contacts.size()) {\n mLoop->processEvents();\n }\n\n QCOMPARE(mContactsInfoFieldsUpdated, contacts.size());\n\n QCOMPARE(serviceConn->refresh_contact_info_called, static_cast(contacts.size()));\n\n for (int i = 0; i < contacts.size(); i++) {\n ContactPtr contact = contacts[i];\n QVERIFY(disconnect(contact.data(),\n SIGNAL(infoFieldsChanged(const Tp::Contact::InfoFields &)),\n this,\n SLOT(onContactInfoFieldsChanged(const Tp::Contact::InfoFields &))));\n }\n\n PendingContactInfo *pci = contactFoo->requestInfo();\n QVERIFY(connect(pci,\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n while (!pci->isFinished()) {\n QCOMPARE(mLoop->exec(), 0);\n }\n\n QCOMPARE(pci->infoFields().isValid(), true);\n QCOMPARE(pci->infoFields().allFields().size(), 1);\n QCOMPARE(pci->infoFields().allFields()[0].fieldName, QLatin1String(\"n\"));\n QCOMPARE(pci->infoFields().allFields()[0].fieldValue[0], QLatin1String(\"FooBar\"));\n\n g_boxed_free(TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST, info_default);\n g_boxed_free(TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST, info_1);\n g_boxed_free(TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST, info_2);\n}\n\nvoid TestContactsInfo::cleanup()\n{\n cleanupImpl();\n}\n\nvoid TestContactsInfo::cleanupTestCase()\n{\n QCOMPARE(mConn->disconnect(), true);\n delete mConn;\n\n cleanupTestCaseImpl();\n}\n\nQTEST_MAIN(TestContactsInfo)\n#include \"_gen\/contacts-info.cpp.moc.hpp\"\n<|endoftext|>"} {"text":"\/\/ Copyright 2018 The Crashpad Authors. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"client\/crashpad_client.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"base\/logging.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"client\/client_argv_handling.h\"\n#include \"util\/file\/file_io.h\"\n#include \"util\/linux\/exception_handler_client.h\"\n#include \"util\/linux\/exception_information.h\"\n#include \"util\/linux\/scoped_pr_set_dumpable.h\"\n#include \"util\/linux\/scoped_pr_set_ptracer.h\"\n#include \"util\/misc\/from_pointer_cast.h\"\n#include \"util\/posix\/double_fork_and_exec.h\"\n#include \"util\/posix\/signals.h\"\n\nnamespace crashpad {\n\nnamespace {\n\nstd::string FormatArgumentInt(const std::string& name, int value) {\n return base::StringPrintf(\"--%s=%d\", name.c_str(), value);\n}\n\nstd::string FormatArgumentAddress(const std::string& name, void* addr) {\n return base::StringPrintf(\"--%s=%p\", name.c_str(), addr);\n}\n\n#if defined(OS_ANDROID)\n\nstd::vector BuildAppProcessArgs(\n const std::string& class_name,\n const base::FilePath& database,\n const base::FilePath& metrics_dir,\n const std::string& url,\n const std::map& annotations,\n const std::vector& arguments,\n int socket) {\n std::vector argv;\n#if defined(ARCH_CPU_64_BITS)\n argv.push_back(\"\/system\/bin\/app_process64\");\n#else\n argv.push_back(\"\/system\/bin\/app_process32\");\n#endif\n argv.push_back(\"\/system\/bin\");\n argv.push_back(\"--application\");\n argv.push_back(class_name);\n\n std::vector handler_argv = BuildHandlerArgvStrings(\n base::FilePath(), database, metrics_dir, url, annotations, arguments);\n\n if (socket != kInvalidFileHandle) {\n handler_argv.push_back(FormatArgumentInt(\"initial-client-fd\", socket));\n }\n\n argv.insert(argv.end(), handler_argv.begin() + 1, handler_argv.end());\n return argv;\n}\n\nstd::vector BuildArgsToLaunchWithLinker(\n const std::string& handler_trampoline,\n const std::string& handler_library,\n bool is_64_bit,\n const base::FilePath& database,\n const base::FilePath& metrics_dir,\n const std::string& url,\n const std::map& annotations,\n const std::vector& arguments,\n int socket) {\n std::vector argv;\n if (is_64_bit) {\n argv.push_back(\"\/system\/bin\/linker64\");\n } else {\n argv.push_back(\"\/system\/bin\/linker\");\n }\n argv.push_back(handler_trampoline);\n argv.push_back(handler_library);\n\n std::vector handler_argv = BuildHandlerArgvStrings(\n base::FilePath(), database, metrics_dir, url, annotations, arguments);\n\n if (socket != kInvalidFileHandle) {\n handler_argv.push_back(FormatArgumentInt(\"initial-client-fd\", socket));\n }\n\n argv.insert(argv.end(), handler_argv.begin() + 1, handler_argv.end());\n return argv;\n}\n\n#endif \/\/ OS_ANDROID\n\n\/\/ Launches a single use handler to snapshot this process.\nclass LaunchAtCrashHandler {\n public:\n static LaunchAtCrashHandler* Get() {\n static LaunchAtCrashHandler* instance = new LaunchAtCrashHandler();\n return instance;\n }\n\n bool Initialize(std::vector* argv_in,\n const std::vector* envp) {\n argv_strings_.swap(*argv_in);\n\n if (envp) {\n envp_strings_ = *envp;\n StringVectorToCStringVector(envp_strings_, &envp_);\n set_envp_ = true;\n }\n\n argv_strings_.push_back(FormatArgumentAddress(\"trace-parent-with-exception\",\n &exception_information_));\n\n StringVectorToCStringVector(argv_strings_, &argv_);\n return Signals::InstallCrashHandlers(HandleCrash, 0, &old_actions_);\n }\n\n bool HandleCrashNonFatal(int signo, siginfo_t* siginfo, void* context) {\n if (first_chance_handler_ &&\n first_chance_handler_(\n signo, siginfo, static_cast(context))) {\n return true;\n }\n\n exception_information_.siginfo_address =\n FromPointerCast(\n siginfo);\n exception_information_.context_address =\n FromPointerCast(\n context);\n exception_information_.thread_id = syscall(SYS_gettid);\n\n ScopedPrSetPtracer set_ptracer(getpid(), \/* may_log= *\/ false);\n ScopedPrSetDumpable set_dumpable(\/* may_log= *\/ false);\n\n pid_t pid = fork();\n if (pid < 0) {\n return false;\n }\n if (pid == 0) {\n if (set_envp_) {\n execve(argv_[0],\n const_cast(argv_.data()),\n const_cast(envp_.data()));\n } else {\n execv(argv_[0], const_cast(argv_.data()));\n }\n _exit(EXIT_FAILURE);\n }\n\n int status;\n waitpid(pid, &status, 0);\n return false;\n }\n\n void HandleCrashFatal(int signo, siginfo_t* siginfo, void* context) {\n if (enabled_ && HandleCrashNonFatal(signo, siginfo, context)) {\n return;\n }\n Signals::RestoreHandlerAndReraiseSignalOnReturn(\n siginfo, old_actions_.ActionForSignal(signo));\n }\n\n void SetFirstChanceHandler(CrashpadClient::FirstChanceHandler handler) {\n first_chance_handler_ = handler;\n }\n\n static void Disable() { enabled_ = false; }\n\n private:\n LaunchAtCrashHandler() = default;\n\n ~LaunchAtCrashHandler() = delete;\n\n static void HandleCrash(int signo, siginfo_t* siginfo, void* context) {\n auto state = Get();\n state->HandleCrashFatal(signo, siginfo, context);\n }\n\n Signals::OldActions old_actions_ = {};\n std::vector argv_strings_;\n std::vector argv_;\n std::vector envp_strings_;\n std::vector envp_;\n ExceptionInformation exception_information_;\n CrashpadClient::FirstChanceHandler first_chance_handler_ = nullptr;\n bool set_envp_ = false;\n\n static thread_local bool enabled_;\n\n DISALLOW_COPY_AND_ASSIGN(LaunchAtCrashHandler);\n};\nthread_local bool LaunchAtCrashHandler::enabled_ = true;\n\n\/\/ A pointer to the currently installed crash signal handler. This allows\n\/\/ the static method CrashpadClient::DumpWithoutCrashing to simulate a crash\n\/\/ using the currently configured crash handling strategy.\nstatic LaunchAtCrashHandler* g_crash_handler;\n\n} \/\/ namespace\n\nCrashpadClient::CrashpadClient() {}\n\nCrashpadClient::~CrashpadClient() {}\n\nbool CrashpadClient::StartHandler(\n const base::FilePath& handler,\n const base::FilePath& database,\n const base::FilePath& metrics_dir,\n const std::string& url,\n const std::map& annotations,\n const std::vector& arguments,\n bool restartable,\n bool asynchronous_start) {\n \/\/ TODO(jperaza): Implement this after the Android\/Linux ExceptionHandlerSever\n \/\/ supports accepting new connections.\n \/\/ https:\/\/crashpad.chromium.org\/bug\/30\n NOTREACHED();\n return false;\n}\n\n#if defined(OS_ANDROID)\n\n\/\/ static\nbool CrashpadClient::StartJavaHandlerAtCrash(\n const std::string& class_name,\n const std::vector* env,\n const base::FilePath& database,\n const base::FilePath& metrics_dir,\n const std::string& url,\n const std::map& annotations,\n const std::vector& arguments) {\n std::vector argv = BuildAppProcessArgs(class_name,\n database,\n metrics_dir,\n url,\n annotations,\n arguments,\n kInvalidFileHandle);\n\n auto signal_handler = LaunchAtCrashHandler::Get();\n if (signal_handler->Initialize(&argv, env)) {\n DCHECK(!g_crash_handler);\n g_crash_handler = signal_handler;\n return true;\n }\n return false;\n}\n\n\/\/ static\nbool CrashpadClient::StartJavaHandlerForClient(\n const std::string& class_name,\n const std::vector* env,\n const base::FilePath& database,\n const base::FilePath& metrics_dir,\n const std::string& url,\n const std::map& annotations,\n const std::vector& arguments,\n int socket) {\n std::vector argv = BuildAppProcessArgs(\n class_name, database, metrics_dir, url, annotations, arguments, socket);\n return DoubleForkAndExec(argv, env, socket, false, nullptr);\n}\n\n\/\/ static\nbool CrashpadClient::StartHandlerWithLinkerAtCrash(\n const std::string& handler_trampoline,\n const std::string& handler_library,\n bool is_64_bit,\n const std::vector* env,\n const base::FilePath& database,\n const base::FilePath& metrics_dir,\n const std::string& url,\n const std::map& annotations,\n const std::vector& arguments) {\n std::vector argv =\n BuildArgsToLaunchWithLinker(handler_trampoline,\n handler_library,\n is_64_bit,\n database,\n metrics_dir,\n url,\n annotations,\n arguments,\n kInvalidFileHandle);\n auto signal_handler = LaunchAtCrashHandler::Get();\n if (signal_handler->Initialize(&argv, env)) {\n DCHECK(!g_crash_handler);\n g_crash_handler = signal_handler;\n return true;\n }\n return false;\n}\n\n\/\/ static\nbool CrashpadClient::StartHandlerWithLinkerForClient(\n const std::string& handler_trampoline,\n const std::string& handler_library,\n bool is_64_bit,\n const std::vector* env,\n const base::FilePath& database,\n const base::FilePath& metrics_dir,\n const std::string& url,\n const std::map& annotations,\n const std::vector& arguments,\n int socket) {\n std::vector argv =\n BuildArgsToLaunchWithLinker(handler_trampoline,\n handler_library,\n is_64_bit,\n database,\n metrics_dir,\n url,\n annotations,\n arguments,\n socket);\n return DoubleForkAndExec(argv, env, socket, false, nullptr);\n}\n\n#endif\n\n\/\/ static\nbool CrashpadClient::StartHandlerAtCrash(\n const base::FilePath& handler,\n const base::FilePath& database,\n const base::FilePath& metrics_dir,\n const std::string& url,\n const std::map& annotations,\n const std::vector& arguments) {\n std::vector argv = BuildHandlerArgvStrings(\n handler, database, metrics_dir, url, annotations, arguments);\n\n auto signal_handler = LaunchAtCrashHandler::Get();\n if (signal_handler->Initialize(&argv, nullptr)) {\n DCHECK(!g_crash_handler);\n g_crash_handler = signal_handler;\n return true;\n }\n return false;\n}\n\n\/\/ static\nbool CrashpadClient::StartHandlerForClient(\n const base::FilePath& handler,\n const base::FilePath& database,\n const base::FilePath& metrics_dir,\n const std::string& url,\n const std::map& annotations,\n const std::vector& arguments,\n int socket) {\n std::vector argv = BuildHandlerArgvStrings(\n handler, database, metrics_dir, url, annotations, arguments);\n\n argv.push_back(FormatArgumentInt(\"initial-client-fd\", socket));\n\n return DoubleForkAndExec(argv, nullptr, socket, true, nullptr);\n}\n\n\/\/ static\nvoid CrashpadClient::DumpWithoutCrash(NativeCPUContext* context) {\n DCHECK(g_crash_handler);\n\n#if defined(ARCH_CPU_ARMEL)\n memset(context->uc_regspace, 0, sizeof(context->uc_regspace));\n#elif defined(ARCH_CPU_ARM64)\n memset(context->uc_mcontext.__reserved,\n 0,\n sizeof(context->uc_mcontext.__reserved));\n#endif\n\n siginfo_t siginfo;\n siginfo.si_signo = Signals::kSimulatedSigno;\n siginfo.si_errno = 0;\n siginfo.si_code = 0;\n g_crash_handler->HandleCrashNonFatal(\n siginfo.si_signo, &siginfo, reinterpret_cast(context));\n}\n\n\/\/ static\nvoid CrashpadClient::CrashWithoutDump(const std::string& message) {\n LaunchAtCrashHandler::Disable();\n LOG(FATAL) << message;\n}\n\n\/\/ static\nvoid CrashpadClient::SetFirstChanceExceptionHandler(\n FirstChanceHandler handler) {\n DCHECK(g_crash_handler);\n g_crash_handler->SetFirstChanceHandler(handler);\n}\n\n} \/\/ namespace crashpad\nlinux: Disable DumpWithoutCrash() if Crashpad isn't initialized\/\/ Copyright 2018 The Crashpad Authors. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"client\/crashpad_client.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"base\/logging.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"client\/client_argv_handling.h\"\n#include \"util\/file\/file_io.h\"\n#include \"util\/linux\/exception_handler_client.h\"\n#include \"util\/linux\/exception_information.h\"\n#include \"util\/linux\/scoped_pr_set_dumpable.h\"\n#include \"util\/linux\/scoped_pr_set_ptracer.h\"\n#include \"util\/misc\/from_pointer_cast.h\"\n#include \"util\/posix\/double_fork_and_exec.h\"\n#include \"util\/posix\/signals.h\"\n\nnamespace crashpad {\n\nnamespace {\n\nstd::string FormatArgumentInt(const std::string& name, int value) {\n return base::StringPrintf(\"--%s=%d\", name.c_str(), value);\n}\n\nstd::string FormatArgumentAddress(const std::string& name, void* addr) {\n return base::StringPrintf(\"--%s=%p\", name.c_str(), addr);\n}\n\n#if defined(OS_ANDROID)\n\nstd::vector BuildAppProcessArgs(\n const std::string& class_name,\n const base::FilePath& database,\n const base::FilePath& metrics_dir,\n const std::string& url,\n const std::map& annotations,\n const std::vector& arguments,\n int socket) {\n std::vector argv;\n#if defined(ARCH_CPU_64_BITS)\n argv.push_back(\"\/system\/bin\/app_process64\");\n#else\n argv.push_back(\"\/system\/bin\/app_process32\");\n#endif\n argv.push_back(\"\/system\/bin\");\n argv.push_back(\"--application\");\n argv.push_back(class_name);\n\n std::vector handler_argv = BuildHandlerArgvStrings(\n base::FilePath(), database, metrics_dir, url, annotations, arguments);\n\n if (socket != kInvalidFileHandle) {\n handler_argv.push_back(FormatArgumentInt(\"initial-client-fd\", socket));\n }\n\n argv.insert(argv.end(), handler_argv.begin() + 1, handler_argv.end());\n return argv;\n}\n\nstd::vector BuildArgsToLaunchWithLinker(\n const std::string& handler_trampoline,\n const std::string& handler_library,\n bool is_64_bit,\n const base::FilePath& database,\n const base::FilePath& metrics_dir,\n const std::string& url,\n const std::map& annotations,\n const std::vector& arguments,\n int socket) {\n std::vector argv;\n if (is_64_bit) {\n argv.push_back(\"\/system\/bin\/linker64\");\n } else {\n argv.push_back(\"\/system\/bin\/linker\");\n }\n argv.push_back(handler_trampoline);\n argv.push_back(handler_library);\n\n std::vector handler_argv = BuildHandlerArgvStrings(\n base::FilePath(), database, metrics_dir, url, annotations, arguments);\n\n if (socket != kInvalidFileHandle) {\n handler_argv.push_back(FormatArgumentInt(\"initial-client-fd\", socket));\n }\n\n argv.insert(argv.end(), handler_argv.begin() + 1, handler_argv.end());\n return argv;\n}\n\n#endif \/\/ OS_ANDROID\n\n\/\/ Launches a single use handler to snapshot this process.\nclass LaunchAtCrashHandler {\n public:\n static LaunchAtCrashHandler* Get() {\n static LaunchAtCrashHandler* instance = new LaunchAtCrashHandler();\n return instance;\n }\n\n bool Initialize(std::vector* argv_in,\n const std::vector* envp) {\n argv_strings_.swap(*argv_in);\n\n if (envp) {\n envp_strings_ = *envp;\n StringVectorToCStringVector(envp_strings_, &envp_);\n set_envp_ = true;\n }\n\n argv_strings_.push_back(FormatArgumentAddress(\"trace-parent-with-exception\",\n &exception_information_));\n\n StringVectorToCStringVector(argv_strings_, &argv_);\n return Signals::InstallCrashHandlers(HandleCrash, 0, &old_actions_);\n }\n\n bool HandleCrashNonFatal(int signo, siginfo_t* siginfo, void* context) {\n if (first_chance_handler_ &&\n first_chance_handler_(\n signo, siginfo, static_cast(context))) {\n return true;\n }\n\n exception_information_.siginfo_address =\n FromPointerCast(\n siginfo);\n exception_information_.context_address =\n FromPointerCast(\n context);\n exception_information_.thread_id = syscall(SYS_gettid);\n\n ScopedPrSetPtracer set_ptracer(getpid(), \/* may_log= *\/ false);\n ScopedPrSetDumpable set_dumpable(\/* may_log= *\/ false);\n\n pid_t pid = fork();\n if (pid < 0) {\n return false;\n }\n if (pid == 0) {\n if (set_envp_) {\n execve(argv_[0],\n const_cast(argv_.data()),\n const_cast(envp_.data()));\n } else {\n execv(argv_[0], const_cast(argv_.data()));\n }\n _exit(EXIT_FAILURE);\n }\n\n int status;\n waitpid(pid, &status, 0);\n return false;\n }\n\n void HandleCrashFatal(int signo, siginfo_t* siginfo, void* context) {\n if (enabled_ && HandleCrashNonFatal(signo, siginfo, context)) {\n return;\n }\n Signals::RestoreHandlerAndReraiseSignalOnReturn(\n siginfo, old_actions_.ActionForSignal(signo));\n }\n\n void SetFirstChanceHandler(CrashpadClient::FirstChanceHandler handler) {\n first_chance_handler_ = handler;\n }\n\n static void Disable() { enabled_ = false; }\n\n private:\n LaunchAtCrashHandler() = default;\n\n ~LaunchAtCrashHandler() = delete;\n\n static void HandleCrash(int signo, siginfo_t* siginfo, void* context) {\n auto state = Get();\n state->HandleCrashFatal(signo, siginfo, context);\n }\n\n Signals::OldActions old_actions_ = {};\n std::vector argv_strings_;\n std::vector argv_;\n std::vector envp_strings_;\n std::vector envp_;\n ExceptionInformation exception_information_;\n CrashpadClient::FirstChanceHandler first_chance_handler_ = nullptr;\n bool set_envp_ = false;\n\n static thread_local bool enabled_;\n\n DISALLOW_COPY_AND_ASSIGN(LaunchAtCrashHandler);\n};\nthread_local bool LaunchAtCrashHandler::enabled_ = true;\n\n\/\/ A pointer to the currently installed crash signal handler. This allows\n\/\/ the static method CrashpadClient::DumpWithoutCrashing to simulate a crash\n\/\/ using the currently configured crash handling strategy.\nstatic LaunchAtCrashHandler* g_crash_handler;\n\n} \/\/ namespace\n\nCrashpadClient::CrashpadClient() {}\n\nCrashpadClient::~CrashpadClient() {}\n\nbool CrashpadClient::StartHandler(\n const base::FilePath& handler,\n const base::FilePath& database,\n const base::FilePath& metrics_dir,\n const std::string& url,\n const std::map& annotations,\n const std::vector& arguments,\n bool restartable,\n bool asynchronous_start) {\n \/\/ TODO(jperaza): Implement this after the Android\/Linux ExceptionHandlerSever\n \/\/ supports accepting new connections.\n \/\/ https:\/\/crashpad.chromium.org\/bug\/30\n NOTREACHED();\n return false;\n}\n\n#if defined(OS_ANDROID)\n\n\/\/ static\nbool CrashpadClient::StartJavaHandlerAtCrash(\n const std::string& class_name,\n const std::vector* env,\n const base::FilePath& database,\n const base::FilePath& metrics_dir,\n const std::string& url,\n const std::map& annotations,\n const std::vector& arguments) {\n std::vector argv = BuildAppProcessArgs(class_name,\n database,\n metrics_dir,\n url,\n annotations,\n arguments,\n kInvalidFileHandle);\n\n auto signal_handler = LaunchAtCrashHandler::Get();\n if (signal_handler->Initialize(&argv, env)) {\n DCHECK(!g_crash_handler);\n g_crash_handler = signal_handler;\n return true;\n }\n return false;\n}\n\n\/\/ static\nbool CrashpadClient::StartJavaHandlerForClient(\n const std::string& class_name,\n const std::vector* env,\n const base::FilePath& database,\n const base::FilePath& metrics_dir,\n const std::string& url,\n const std::map& annotations,\n const std::vector& arguments,\n int socket) {\n std::vector argv = BuildAppProcessArgs(\n class_name, database, metrics_dir, url, annotations, arguments, socket);\n return DoubleForkAndExec(argv, env, socket, false, nullptr);\n}\n\n\/\/ static\nbool CrashpadClient::StartHandlerWithLinkerAtCrash(\n const std::string& handler_trampoline,\n const std::string& handler_library,\n bool is_64_bit,\n const std::vector* env,\n const base::FilePath& database,\n const base::FilePath& metrics_dir,\n const std::string& url,\n const std::map& annotations,\n const std::vector& arguments) {\n std::vector argv =\n BuildArgsToLaunchWithLinker(handler_trampoline,\n handler_library,\n is_64_bit,\n database,\n metrics_dir,\n url,\n annotations,\n arguments,\n kInvalidFileHandle);\n auto signal_handler = LaunchAtCrashHandler::Get();\n if (signal_handler->Initialize(&argv, env)) {\n DCHECK(!g_crash_handler);\n g_crash_handler = signal_handler;\n return true;\n }\n return false;\n}\n\n\/\/ static\nbool CrashpadClient::StartHandlerWithLinkerForClient(\n const std::string& handler_trampoline,\n const std::string& handler_library,\n bool is_64_bit,\n const std::vector* env,\n const base::FilePath& database,\n const base::FilePath& metrics_dir,\n const std::string& url,\n const std::map& annotations,\n const std::vector& arguments,\n int socket) {\n std::vector argv =\n BuildArgsToLaunchWithLinker(handler_trampoline,\n handler_library,\n is_64_bit,\n database,\n metrics_dir,\n url,\n annotations,\n arguments,\n socket);\n return DoubleForkAndExec(argv, env, socket, false, nullptr);\n}\n\n#endif\n\n\/\/ static\nbool CrashpadClient::StartHandlerAtCrash(\n const base::FilePath& handler,\n const base::FilePath& database,\n const base::FilePath& metrics_dir,\n const std::string& url,\n const std::map& annotations,\n const std::vector& arguments) {\n std::vector argv = BuildHandlerArgvStrings(\n handler, database, metrics_dir, url, annotations, arguments);\n\n auto signal_handler = LaunchAtCrashHandler::Get();\n if (signal_handler->Initialize(&argv, nullptr)) {\n DCHECK(!g_crash_handler);\n g_crash_handler = signal_handler;\n return true;\n }\n return false;\n}\n\n\/\/ static\nbool CrashpadClient::StartHandlerForClient(\n const base::FilePath& handler,\n const base::FilePath& database,\n const base::FilePath& metrics_dir,\n const std::string& url,\n const std::map& annotations,\n const std::vector& arguments,\n int socket) {\n std::vector argv = BuildHandlerArgvStrings(\n handler, database, metrics_dir, url, annotations, arguments);\n\n argv.push_back(FormatArgumentInt(\"initial-client-fd\", socket));\n\n return DoubleForkAndExec(argv, nullptr, socket, true, nullptr);\n}\n\n\/\/ static\nvoid CrashpadClient::DumpWithoutCrash(NativeCPUContext* context) {\n if (!g_crash_handler) {\n DLOG(ERROR) << \"Crashpad isn't enabled\";\n return;\n }\n\n#if defined(ARCH_CPU_ARMEL)\n memset(context->uc_regspace, 0, sizeof(context->uc_regspace));\n#elif defined(ARCH_CPU_ARM64)\n memset(context->uc_mcontext.__reserved,\n 0,\n sizeof(context->uc_mcontext.__reserved));\n#endif\n\n siginfo_t siginfo;\n siginfo.si_signo = Signals::kSimulatedSigno;\n siginfo.si_errno = 0;\n siginfo.si_code = 0;\n g_crash_handler->HandleCrashNonFatal(\n siginfo.si_signo, &siginfo, reinterpret_cast(context));\n}\n\n\/\/ static\nvoid CrashpadClient::CrashWithoutDump(const std::string& message) {\n LaunchAtCrashHandler::Disable();\n LOG(FATAL) << message;\n}\n\n\/\/ static\nvoid CrashpadClient::SetFirstChanceExceptionHandler(\n FirstChanceHandler handler) {\n DCHECK(g_crash_handler);\n g_crash_handler->SetFirstChanceHandler(handler);\n}\n\n} \/\/ namespace crashpad\n<|endoftext|>"} {"text":"#ifndef ENTT_CORE_MEMORY_HPP\n#define ENTT_CORE_MEMORY_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \"..\/config\/config.h\"\n\nnamespace entt {\n\n\/**\n * @brief Unwraps fancy pointers, does nothing otherwise (waiting for C++20).\n * @tparam Type Pointer type.\n * @param ptr Fancy or raw pointer.\n * @return A raw pointer that represents the address of the original pointer.\n *\/\ntemplate\n[[nodiscard]] constexpr auto to_address(Type &&ptr) ENTT_NOEXCEPT {\n if constexpr(std::is_pointer_v>>) {\n return ptr;\n } else {\n return to_address(std::forward(ptr).operator->());\n }\n}\n\n\/**\n * @brief Utility function to design allocation-aware containers.\n * @tparam Allocator Type of allocator.\n * @param lhs A valid allocator.\n * @param rhs Another valid allocator.\n *\/\ntemplate\nconstexpr void propagate_on_container_copy_assignment([[maybe_unused]] Allocator &lhs, [[maybe_unused]] Allocator &rhs) ENTT_NOEXCEPT {\n if constexpr(std::allocator_traits::propagate_on_container_copy_assignment::value) {\n lhs = rhs;\n }\n}\n\n\/**\n * @brief Utility function to design allocation-aware containers.\n * @tparam Allocator Type of allocator.\n * @param lhs A valid allocator.\n * @param rhs Another valid allocator.\n *\/\ntemplate\nconstexpr void propagate_on_container_move_assignment([[maybe_unused]] Allocator &lhs, [[maybe_unused]] Allocator &rhs) ENTT_NOEXCEPT {\n if constexpr(std::allocator_traits::propagate_on_container_move_assignment::value) {\n lhs = std::move(rhs);\n }\n}\n\n\/**\n * @brief Utility function to design allocation-aware containers.\n * @tparam Allocator Type of allocator.\n * @param lhs A valid allocator.\n * @param rhs Another valid allocator.\n *\/\ntemplate\nconstexpr void propagate_on_container_swap([[maybe_unused]] Allocator &lhs, [[maybe_unused]] Allocator &rhs) ENTT_NOEXCEPT {\n ENTT_ASSERT(std::allocator_traits::propagate_on_container_swap::value || lhs == rhs, \"Cannot swap the containers\");\n\n if constexpr(std::allocator_traits::propagate_on_container_swap::value) {\n using std::swap;\n swap(lhs, rhs);\n }\n}\n\n\/**\n * @brief Checks whether a value is a power of two or not.\n * @param value A value that may or may not be a power of two.\n * @return True if the value is a power of two, false otherwise.\n *\/\n[[nodiscard]] inline constexpr bool is_power_of_two(const std::size_t value) ENTT_NOEXCEPT {\n return value && ((value & (value - 1)) == 0);\n}\n\n\/**\n * @brief Computes the smallest power of two greater than or equal to a value.\n * @param value The value to use.\n * @return The smallest power of two greater than or equal to the given value.\n *\/\n[[nodiscard]] inline constexpr std::size_t next_power_of_two(const std::size_t value) ENTT_NOEXCEPT {\n ENTT_ASSERT(value < (std::size_t{1u} << (std::numeric_limits::digits - 1)), \"Numeric limits exceeded\");\n std::size_t curr = value - (value != 0u);\n\n for(int next = 1; next < std::numeric_limits::digits; next = next * 2) {\n curr |= curr >> next;\n }\n\n return ++curr;\n}\n\n\/**\n * @brief Fast module utility function (powers of two only).\n * @param value A value for which to calculate the modulus.\n * @param mod _Modulus_, it must be a power of two.\n * @return The common remainder.\n *\/\n[[nodiscard]] inline constexpr std::size_t fast_mod(const std::size_t value, const std::size_t mod) ENTT_NOEXCEPT {\n ENTT_ASSERT(is_power_of_two(mod), \"Value must be a power of two\");\n return value & (mod - 1u);\n}\n\n\/**\n * @brief General purpose deleter for allocator-aware unique pointers.\n * @tparam Args Types of arguments to use to construct the object.\n *\/\ntemplate\nstruct allocation_deleter: private Allocator {\n \/*! @brief Allocator type. *\/\n using allocator_type = Allocator;\n \/*! @brief Pointer type. *\/\n using pointer = typename std::allocator_traits::pointer;\n\n \/**\n * @brief Inherited constructors.\n * @param allocator The allocator to use.\n *\/\n allocation_deleter(const allocator_type &allocator)\n : Allocator{allocator} {}\n\n \/**\n * @brief Destroys the pointed object and deallocates its memory.\n * @param ptr A valid pointer to an object of the given type.\n *\/\n void operator()(pointer ptr) {\n using alloc_traits = typename std::allocator_traits;\n alloc_traits::destroy(*this, to_address(ptr));\n alloc_traits::deallocate(*this, ptr, 1u);\n }\n};\n\n\/**\n * @brief Allows `std::unique_ptr` to use allocators.\n * @tparam Type Type of object to allocate for and to construct.\n * @tparam Allocator Type of allocator used to manage memory and elements.\n * @tparam Args Types of arguments to use to construct the object.\n * @param allocator The allocator to use.\n * @param args Parameters to use to construct an object for the entity.\n * @return A properly initialized unique pointer with a custom deleter.\n *\/\ntemplate\nauto allocate_unique(Allocator &allocator, Args &&...args) {\n using alloc = typename std::allocator_traits::template rebind_alloc;\n using alloc_traits = typename std::allocator_traits;\n\n alloc type_allocator{allocator};\n auto ptr = alloc_traits::allocate(type_allocator, 1u);\n\n ENTT_TRY {\n alloc_traits::construct(type_allocator, to_address(ptr), std::forward(args)...);\n }\n ENTT_CATCH {\n alloc_traits::deallocate(type_allocator, ptr, 1u);\n ENTT_THROW;\n }\n\n return std::unique_ptr>{ptr, type_allocator};\n}\n\n} \/\/ namespace entt\n\n#endif\nmemory: suppress a (shadow) warning from gcc#ifndef ENTT_CORE_MEMORY_HPP\n#define ENTT_CORE_MEMORY_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \"..\/config\/config.h\"\n\nnamespace entt {\n\n\/**\n * @brief Unwraps fancy pointers, does nothing otherwise (waiting for C++20).\n * @tparam Type Pointer type.\n * @param ptr Fancy or raw pointer.\n * @return A raw pointer that represents the address of the original pointer.\n *\/\ntemplate\n[[nodiscard]] constexpr auto to_address(Type &&ptr) ENTT_NOEXCEPT {\n if constexpr(std::is_pointer_v>>) {\n return ptr;\n } else {\n return to_address(std::forward(ptr).operator->());\n }\n}\n\n\/**\n * @brief Utility function to design allocation-aware containers.\n * @tparam Allocator Type of allocator.\n * @param lhs A valid allocator.\n * @param rhs Another valid allocator.\n *\/\ntemplate\nconstexpr void propagate_on_container_copy_assignment([[maybe_unused]] Allocator &lhs, [[maybe_unused]] Allocator &rhs) ENTT_NOEXCEPT {\n if constexpr(std::allocator_traits::propagate_on_container_copy_assignment::value) {\n lhs = rhs;\n }\n}\n\n\/**\n * @brief Utility function to design allocation-aware containers.\n * @tparam Allocator Type of allocator.\n * @param lhs A valid allocator.\n * @param rhs Another valid allocator.\n *\/\ntemplate\nconstexpr void propagate_on_container_move_assignment([[maybe_unused]] Allocator &lhs, [[maybe_unused]] Allocator &rhs) ENTT_NOEXCEPT {\n if constexpr(std::allocator_traits::propagate_on_container_move_assignment::value) {\n lhs = std::move(rhs);\n }\n}\n\n\/**\n * @brief Utility function to design allocation-aware containers.\n * @tparam Allocator Type of allocator.\n * @param lhs A valid allocator.\n * @param rhs Another valid allocator.\n *\/\ntemplate\nconstexpr void propagate_on_container_swap([[maybe_unused]] Allocator &lhs, [[maybe_unused]] Allocator &rhs) ENTT_NOEXCEPT {\n ENTT_ASSERT(std::allocator_traits::propagate_on_container_swap::value || lhs == rhs, \"Cannot swap the containers\");\n\n if constexpr(std::allocator_traits::propagate_on_container_swap::value) {\n using std::swap;\n swap(lhs, rhs);\n }\n}\n\n\/**\n * @brief Checks whether a value is a power of two or not.\n * @param value A value that may or may not be a power of two.\n * @return True if the value is a power of two, false otherwise.\n *\/\n[[nodiscard]] inline constexpr bool is_power_of_two(const std::size_t value) ENTT_NOEXCEPT {\n return value && ((value & (value - 1)) == 0);\n}\n\n\/**\n * @brief Computes the smallest power of two greater than or equal to a value.\n * @param value The value to use.\n * @return The smallest power of two greater than or equal to the given value.\n *\/\n[[nodiscard]] inline constexpr std::size_t next_power_of_two(const std::size_t value) ENTT_NOEXCEPT {\n ENTT_ASSERT(value < (std::size_t{1u} << (std::numeric_limits::digits - 1)), \"Numeric limits exceeded\");\n std::size_t curr = value - (value != 0u);\n\n for(int next = 1; next < std::numeric_limits::digits; next = next * 2) {\n curr |= curr >> next;\n }\n\n return ++curr;\n}\n\n\/**\n * @brief Fast module utility function (powers of two only).\n * @param value A value for which to calculate the modulus.\n * @param mod _Modulus_, it must be a power of two.\n * @return The common remainder.\n *\/\n[[nodiscard]] inline constexpr std::size_t fast_mod(const std::size_t value, const std::size_t mod) ENTT_NOEXCEPT {\n ENTT_ASSERT(is_power_of_two(mod), \"Value must be a power of two\");\n return value & (mod - 1u);\n}\n\n\/**\n * @brief General purpose deleter for allocator-aware unique pointers.\n * @tparam Args Types of arguments to use to construct the object.\n *\/\ntemplate\nstruct allocation_deleter: private Allocator {\n \/*! @brief Allocator type. *\/\n using allocator_type = Allocator;\n \/*! @brief Pointer type. *\/\n using pointer = typename std::allocator_traits::pointer;\n\n \/**\n * @brief Inherited constructors.\n * @param alloc The allocator to use.\n *\/\n allocation_deleter(const allocator_type &alloc)\n : Allocator{alloc} {}\n\n \/**\n * @brief Destroys the pointed object and deallocates its memory.\n * @param ptr A valid pointer to an object of the given type.\n *\/\n void operator()(pointer ptr) {\n using alloc_traits = typename std::allocator_traits;\n alloc_traits::destroy(*this, to_address(ptr));\n alloc_traits::deallocate(*this, ptr, 1u);\n }\n};\n\n\/**\n * @brief Allows `std::unique_ptr` to use allocators.\n * @tparam Type Type of object to allocate for and to construct.\n * @tparam Allocator Type of allocator used to manage memory and elements.\n * @tparam Args Types of arguments to use to construct the object.\n * @param allocator The allocator to use.\n * @param args Parameters to use to construct an object for the entity.\n * @return A properly initialized unique pointer with a custom deleter.\n *\/\ntemplate\nauto allocate_unique(Allocator &allocator, Args &&...args) {\n using alloc = typename std::allocator_traits::template rebind_alloc;\n using alloc_traits = typename std::allocator_traits;\n\n alloc type_allocator{allocator};\n auto ptr = alloc_traits::allocate(type_allocator, 1u);\n\n ENTT_TRY {\n alloc_traits::construct(type_allocator, to_address(ptr), std::forward(args)...);\n }\n ENTT_CATCH {\n alloc_traits::deallocate(type_allocator, ptr, 1u);\n ENTT_THROW;\n }\n\n return std::unique_ptr>{ptr, type_allocator};\n}\n\n} \/\/ namespace entt\n\n#endif\n<|endoftext|>"} {"text":"#include \"stdafx.h\"\r\n\/*\r\n* Copyright (c) 2007-2009 SlimDX Group\r\n* \r\n* Permission is hereby granted, free of charge, to any person obtaining a copy\r\n* of this software and associated documentation files (the \"Software\"), to deal\r\n* in the Software without restriction, including without limitation the rights\r\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n* copies of the Software, and to permit persons to whom the Software is\r\n* furnished to do so, subject to the following conditions:\r\n* \r\n* The above copyright notice and this permission notice shall be included in\r\n* all copies or substantial portions of the Software.\r\n* \r\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n* THE SOFTWARE.\r\n*\/\r\n\r\n#include \r\n#include \r\n\r\n#include \"..\/stack_array.h\"\r\n\r\n#include \"BlendState.h\"\r\n#include \"DepthStencilState.h\"\r\n#include \"DepthStencilView.h\"\r\n#include \"OutputMergerWrapper.h\"\r\n#include \"RenderTargetView.h\"\r\n\r\nusing namespace System;\r\n\r\nnamespace SlimDX\r\n{\r\nnamespace Direct3D10\r\n{ \r\n\tOutputMergerWrapper::OutputMergerWrapper( ID3D10Device* device )\r\n\t{\r\n\t\tif( device == 0 )\r\n\t\t\tthrow gcnew ArgumentNullException( \"device\" );\r\n\t\tm_Device = device;\r\n\t}\r\n\t\r\n\tvoid OutputMergerWrapper::DepthStencilState::set( SlimDX::Direct3D10::DepthStencilState^ value )\r\n\t{\r\n\t\tID3D10DepthStencilState* oldState;\r\n\t\tint oldReference;\r\n\t\tm_Device->OMGetDepthStencilState( &oldState, reinterpret_cast( &oldReference ) );\r\n\t\toldState->Release();\r\n\t\r\n\t\tif( value == nullptr )\r\n\t\t\tm_Device->OMSetDepthStencilState( 0, oldReference );\r\n\t\telse\r\n\t\t\tm_Device->OMSetDepthStencilState( value->InternalPointer, oldReference );\r\n\t}\r\n\t\r\n\tSlimDX::Direct3D10::DepthStencilState^ OutputMergerWrapper::DepthStencilState::get()\r\n\t{\r\n\t\tID3D10DepthStencilState* oldState = 0;\r\n\t\tint oldReference = 0;\r\n\t\tm_Device->OMGetDepthStencilState( &oldState, reinterpret_cast( &oldReference ) );\r\n\t\t\r\n\t\treturn SlimDX::Direct3D10::DepthStencilState::FromPointer( oldState );\r\n\t}\r\n\t\r\n\tvoid OutputMergerWrapper::DepthStencilReference::set( int value )\r\n\t{\r\n\t\tID3D10DepthStencilState* oldState = 0;\r\n\t\tint oldReference = 0;\r\n\t\tm_Device->OMGetDepthStencilState( &oldState, reinterpret_cast( &oldReference ) );\r\n\t\r\n\t\tm_Device->OMSetDepthStencilState( oldState, value );\r\n\t\toldState->Release();\r\n\t}\r\n\t\r\n\tint OutputMergerWrapper::DepthStencilReference::get()\r\n\t{\r\n\t\tID3D10DepthStencilState* oldState = 0;\r\n\t\tint oldReference = 0;\r\n\t\tm_Device->OMGetDepthStencilState( &oldState, reinterpret_cast( &oldReference ) );\r\n\t\toldState->Release();\r\n\t\t\r\n\t\treturn oldReference;\r\n\t}\r\n\t\r\n\tvoid OutputMergerWrapper::BlendState::set( SlimDX::Direct3D10::BlendState^ value )\r\n\t{\r\n\t\tID3D10BlendState* oldState = 0;\r\n\t\tfloat oldFactor[4];\r\n\t\tint oldMask = 0;\r\n\t\tm_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast( &oldMask ) );\r\n\t\toldState->Release();\r\n\t\t\r\n\t\tif( value == nullptr )\r\n\t\t\tm_Device->OMSetBlendState( 0, oldFactor, oldMask );\r\n\t\telse \r\n\t\t\tm_Device->OMSetBlendState( value->InternalPointer, oldFactor, oldMask );\r\n\t}\r\n\t\r\n\tSlimDX::Direct3D10::BlendState^ OutputMergerWrapper::BlendState::get()\r\n\t{\r\n\t\tID3D10BlendState* oldState = 0;\r\n\t\tfloat oldFactor[4];\r\n\t\tint oldMask = 0;\r\n\t\tm_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast( &oldMask ) );\r\n\t\t\r\n\t\treturn SlimDX::Direct3D10::BlendState::FromPointer( oldState );\r\n\t}\r\n\t\r\n\tvoid OutputMergerWrapper::BlendFactor::set( Color4 value )\r\n\t{\r\n\t\tID3D10BlendState* oldState = 0;\r\n\t\tfloat oldFactor[4];\r\n\t\tint oldMask = 0;\r\n\t\tm_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast( &oldMask ) );\r\n\t\t\r\n\t\tfloat newFactor[4] = { value.Red, value.Green, value.Blue, value.Alpha };\r\n\t\tm_Device->OMSetBlendState( oldState, newFactor, oldMask );\r\n\t\toldState->Release();\r\n\t}\r\n\t\r\n\tColor4 OutputMergerWrapper::BlendFactor::get()\r\n\t{\r\n\t\tID3D10BlendState* oldState = 0;\r\n\t\tfloat oldFactor[4];\r\n\t\tint oldMask = 0;\r\n\t\tm_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast( &oldMask ) );\r\n\t\toldState->Release();\r\n\t\t\r\n\t\treturn Color4( oldFactor[3], oldFactor[0], oldFactor[1], oldFactor[2] );\r\n\t}\r\n\t\r\n\tvoid OutputMergerWrapper::BlendSampleMask::set( int value )\r\n\t{\r\n\t\tID3D10BlendState* oldState = 0;\r\n\t\tfloat oldFactor[4];\r\n\t\tint oldMask = 0;\r\n\t\tm_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast( &oldMask ) );\r\n\t\r\n\t\tm_Device->OMSetBlendState( oldState, oldFactor, value );\r\n\t\toldState->Release();\r\n\t}\r\n\t\r\n\tint OutputMergerWrapper::BlendSampleMask::get()\r\n\t{\r\n\t\tID3D10BlendState* oldState = 0;\r\n\t\tfloat oldFactor[4];\r\n\t\tint oldMask = 0;\r\n\t\tm_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast( &oldMask ) );\r\n\t\toldState->Release();\r\n\t\t\r\n\t\treturn oldMask;\r\n\t}\r\n\t\r\n\tvoid OutputMergerWrapper::SetTargets( RenderTargetView^ renderTargetView )\r\n\t{\r\n\t\tSetTargets( nullptr, renderTargetView );\r\n\t}\r\n\t\r\n\tvoid OutputMergerWrapper::SetTargets( DepthStencilView^ depthStencilView, RenderTargetView^ renderTargetView )\r\n\t{\r\n\t\tID3D10DepthStencilView *nativeDSV = depthStencilView == nullptr ? 0 : static_cast( depthStencilView->InternalPointer );\r\n\t\tID3D10RenderTargetView *nativeRTV[] = { renderTargetView == nullptr ? 0 : static_cast( renderTargetView->InternalPointer ) };\r\n\t\t\r\n\t\tm_Device->OMSetRenderTargets( 1, nativeRTV, nativeDSV );\r\n\t}\r\n\r\n\tvoid OutputMergerWrapper::SetTargets( ... array^ renderTargets )\r\n\t{\r\n\t\tSetTargets( nullptr, renderTargets );\r\n\t}\r\n\r\n\tvoid OutputMergerWrapper::SetTargets( DepthStencilView^ depthStencilView, ... array^ renderTargets )\r\n\t{\r\n\t\tID3D10DepthStencilView *nativeDSV = depthStencilView == nullptr ? 0 : static_cast( depthStencilView->InternalPointer );\r\n\t\tID3D10RenderTargetView* nativeRTVs[D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT];\r\n\t\t\r\n\t\tif( renderTargets == nullptr )\r\n\t\t{\r\n\t\t\tm_Device->OMSetRenderTargets( 0, 0, nativeDSV );\r\n\t\t}\r\n\t\telse \r\n\t\t{\r\n\t\t\tfor( int i = 0; i < renderTargets->Length; ++i )\r\n\t\t\t\tnativeRTVs[ i ] = renderTargets[ i ] == nullptr ? 0 : static_cast( renderTargets[ i ]->InternalPointer );\r\n\t\t\tm_Device->OMSetRenderTargets( renderTargets->Length, nativeRTVs, nativeDSV );\r\n\t\t}\r\n\t}\r\n\t\r\n\tDepthStencilView^ OutputMergerWrapper::GetDepthStencilView()\r\n\t{\r\n\t\tID3D10DepthStencilView *view;\r\n\r\n\t\tm_Device->OMGetRenderTargets( 0, 0, &view );\r\n\t\treturn DepthStencilView::FromPointer( view );\r\n\t}\r\n\r\n\tarray^ OutputMergerWrapper::GetRenderTargets( int count )\r\n\t{\r\n\t\tstack_array targets = stackalloc( ID3D10RenderTargetView*, count );\r\n\t\tarray^ results = gcnew array( count );\r\n\r\n\t\tm_Device->OMGetRenderTargets( count, &targets[0], 0 );\r\n\r\n\t\tfor( int i = 0; i < count; i++ )\r\n\t\t\tresults[i] = RenderTargetView::FromPointer( targets[i] );\r\n\r\n\t\treturn results;\r\n\t}\r\n}\r\n}\r\nAdded null checks to oldState->Release in OutputMergerWrapper. Fixes issue 536.#include \"stdafx.h\"\r\n\/*\r\n* Copyright (c) 2007-2009 SlimDX Group\r\n* \r\n* Permission is hereby granted, free of charge, to any person obtaining a copy\r\n* of this software and associated documentation files (the \"Software\"), to deal\r\n* in the Software without restriction, including without limitation the rights\r\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n* copies of the Software, and to permit persons to whom the Software is\r\n* furnished to do so, subject to the following conditions:\r\n* \r\n* The above copyright notice and this permission notice shall be included in\r\n* all copies or substantial portions of the Software.\r\n* \r\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n* THE SOFTWARE.\r\n*\/\r\n\r\n#include \r\n#include \r\n\r\n#include \"..\/stack_array.h\"\r\n\r\n#include \"BlendState.h\"\r\n#include \"DepthStencilState.h\"\r\n#include \"DepthStencilView.h\"\r\n#include \"OutputMergerWrapper.h\"\r\n#include \"RenderTargetView.h\"\r\n\r\nusing namespace System;\r\n\r\nnamespace SlimDX\r\n{\r\nnamespace Direct3D10\r\n{ \r\n\tOutputMergerWrapper::OutputMergerWrapper( ID3D10Device* device )\r\n\t{\r\n\t\tif( device == 0 )\r\n\t\t\tthrow gcnew ArgumentNullException( \"device\" );\r\n\t\tm_Device = device;\r\n\t}\r\n\t\r\n\tvoid OutputMergerWrapper::DepthStencilState::set( SlimDX::Direct3D10::DepthStencilState^ value )\r\n\t{\r\n\t\tID3D10DepthStencilState* oldState;\r\n\t\tint oldReference;\r\n\t\tm_Device->OMGetDepthStencilState( &oldState, reinterpret_cast( &oldReference ) );\r\n\t\tif( oldState != NULL )\r\n\t\t\toldState->Release();\r\n\t\r\n\t\tif( value == nullptr )\r\n\t\t\tm_Device->OMSetDepthStencilState( 0, oldReference );\r\n\t\telse\r\n\t\t\tm_Device->OMSetDepthStencilState( value->InternalPointer, oldReference );\r\n\t}\r\n\t\r\n\tSlimDX::Direct3D10::DepthStencilState^ OutputMergerWrapper::DepthStencilState::get()\r\n\t{\r\n\t\tID3D10DepthStencilState* oldState = 0;\r\n\t\tint oldReference = 0;\r\n\t\tm_Device->OMGetDepthStencilState( &oldState, reinterpret_cast( &oldReference ) );\r\n\t\t\r\n\t\treturn SlimDX::Direct3D10::DepthStencilState::FromPointer( oldState );\r\n\t}\r\n\t\r\n\tvoid OutputMergerWrapper::DepthStencilReference::set( int value )\r\n\t{\r\n\t\tID3D10DepthStencilState* oldState = 0;\r\n\t\tint oldReference = 0;\r\n\t\tm_Device->OMGetDepthStencilState( &oldState, reinterpret_cast( &oldReference ) );\r\n\t\r\n\t\tm_Device->OMSetDepthStencilState( oldState, value );\r\n\t\tif( oldState != NULL )\r\n\t\t\toldState->Release();\r\n\t}\r\n\t\r\n\tint OutputMergerWrapper::DepthStencilReference::get()\r\n\t{\r\n\t\tID3D10DepthStencilState* oldState = 0;\r\n\t\tint oldReference = 0;\r\n\t\tm_Device->OMGetDepthStencilState( &oldState, reinterpret_cast( &oldReference ) );\r\n\t\tif( oldState != NULL )\r\n\t\t\toldState->Release();\r\n\t\t\r\n\t\treturn oldReference;\r\n\t}\r\n\t\r\n\tvoid OutputMergerWrapper::BlendState::set( SlimDX::Direct3D10::BlendState^ value )\r\n\t{\r\n\t\tID3D10BlendState* oldState = 0;\r\n\t\tfloat oldFactor[4];\r\n\t\tint oldMask = 0;\r\n\t\tm_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast( &oldMask ) );\r\n\t\tif( oldState != NULL )\r\n\t\t\toldState->Release();\r\n\t\t\r\n\t\tif( value == nullptr )\r\n\t\t\tm_Device->OMSetBlendState( 0, oldFactor, oldMask );\r\n\t\telse \r\n\t\t\tm_Device->OMSetBlendState( value->InternalPointer, oldFactor, oldMask );\r\n\t}\r\n\t\r\n\tSlimDX::Direct3D10::BlendState^ OutputMergerWrapper::BlendState::get()\r\n\t{\r\n\t\tID3D10BlendState* oldState = 0;\r\n\t\tfloat oldFactor[4];\r\n\t\tint oldMask = 0;\r\n\t\tm_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast( &oldMask ) );\r\n\t\t\r\n\t\treturn SlimDX::Direct3D10::BlendState::FromPointer( oldState );\r\n\t}\r\n\t\r\n\tvoid OutputMergerWrapper::BlendFactor::set( Color4 value )\r\n\t{\r\n\t\tID3D10BlendState* oldState = 0;\r\n\t\tfloat oldFactor[4];\r\n\t\tint oldMask = 0;\r\n\t\tm_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast( &oldMask ) );\r\n\t\t\r\n\t\tfloat newFactor[4] = { value.Red, value.Green, value.Blue, value.Alpha };\r\n\t\tm_Device->OMSetBlendState( oldState, newFactor, oldMask );\r\n\t\tif( oldState != NULL )\r\n\t\t\toldState->Release();\r\n\t}\r\n\t\r\n\tColor4 OutputMergerWrapper::BlendFactor::get()\r\n\t{\r\n\t\tID3D10BlendState* oldState = 0;\r\n\t\tfloat oldFactor[4];\r\n\t\tint oldMask = 0;\r\n\t\tm_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast( &oldMask ) );\r\n\t\tif( oldState != NULL )\r\n\t\t\toldState->Release();\r\n\t\t\r\n\t\treturn Color4( oldFactor[3], oldFactor[0], oldFactor[1], oldFactor[2] );\r\n\t}\r\n\t\r\n\tvoid OutputMergerWrapper::BlendSampleMask::set( int value )\r\n\t{\r\n\t\tID3D10BlendState* oldState = 0;\r\n\t\tfloat oldFactor[4];\r\n\t\tint oldMask = 0;\r\n\t\tm_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast( &oldMask ) );\r\n\t\r\n\t\tm_Device->OMSetBlendState( oldState, oldFactor, value );\r\n\t\tif( oldState != NULL )\r\n\t\t\toldState->Release();\r\n\t}\r\n\t\r\n\tint OutputMergerWrapper::BlendSampleMask::get()\r\n\t{\r\n\t\tID3D10BlendState* oldState = 0;\r\n\t\tfloat oldFactor[4];\r\n\t\tint oldMask = 0;\r\n\t\tm_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast( &oldMask ) );\r\n\t\tif( oldState != NULL )\r\n\t\t\toldState->Release();\r\n\t\t\r\n\t\treturn oldMask;\r\n\t}\r\n\t\r\n\tvoid OutputMergerWrapper::SetTargets( RenderTargetView^ renderTargetView )\r\n\t{\r\n\t\tSetTargets( nullptr, renderTargetView );\r\n\t}\r\n\t\r\n\tvoid OutputMergerWrapper::SetTargets( DepthStencilView^ depthStencilView, RenderTargetView^ renderTargetView )\r\n\t{\r\n\t\tID3D10DepthStencilView *nativeDSV = depthStencilView == nullptr ? 0 : static_cast( depthStencilView->InternalPointer );\r\n\t\tID3D10RenderTargetView *nativeRTV[] = { renderTargetView == nullptr ? 0 : static_cast( renderTargetView->InternalPointer ) };\r\n\t\t\r\n\t\tm_Device->OMSetRenderTargets( 1, nativeRTV, nativeDSV );\r\n\t}\r\n\r\n\tvoid OutputMergerWrapper::SetTargets( ... array^ renderTargets )\r\n\t{\r\n\t\tSetTargets( nullptr, renderTargets );\r\n\t}\r\n\r\n\tvoid OutputMergerWrapper::SetTargets( DepthStencilView^ depthStencilView, ... array^ renderTargets )\r\n\t{\r\n\t\tID3D10DepthStencilView *nativeDSV = depthStencilView == nullptr ? 0 : static_cast( depthStencilView->InternalPointer );\r\n\t\tID3D10RenderTargetView* nativeRTVs[D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT];\r\n\t\t\r\n\t\tif( renderTargets == nullptr )\r\n\t\t{\r\n\t\t\tm_Device->OMSetRenderTargets( 0, 0, nativeDSV );\r\n\t\t}\r\n\t\telse \r\n\t\t{\r\n\t\t\tfor( int i = 0; i < renderTargets->Length; ++i )\r\n\t\t\t\tnativeRTVs[ i ] = renderTargets[ i ] == nullptr ? 0 : static_cast( renderTargets[ i ]->InternalPointer );\r\n\t\t\tm_Device->OMSetRenderTargets( renderTargets->Length, nativeRTVs, nativeDSV );\r\n\t\t}\r\n\t}\r\n\t\r\n\tDepthStencilView^ OutputMergerWrapper::GetDepthStencilView()\r\n\t{\r\n\t\tID3D10DepthStencilView *view;\r\n\r\n\t\tm_Device->OMGetRenderTargets( 0, 0, &view );\r\n\t\treturn DepthStencilView::FromPointer( view );\r\n\t}\r\n\r\n\tarray^ OutputMergerWrapper::GetRenderTargets( int count )\r\n\t{\r\n\t\tstack_array targets = stackalloc( ID3D10RenderTargetView*, count );\r\n\t\tarray^ results = gcnew array( count );\r\n\r\n\t\tm_Device->OMGetRenderTargets( count, &targets[0], 0 );\r\n\r\n\t\tfor( int i = 0; i < count; i++ )\r\n\t\t\tresults[i] = RenderTargetView::FromPointer( targets[i] );\r\n\r\n\t\treturn results;\r\n\t}\r\n}\r\n}\r\n<|endoftext|>"} {"text":"\/\/\n\/\/ poNodeContainer.cpp\n\/\/ BasicScene\n\/\/\n\/\/ Created by Stephen Varga on 3\/22\/14.\n\/\/\n\/\/\n\n#include \"poNodeContainer.h\"\n\nnamespace po {\n NodeContainerRef NodeContainer::create(std::string name)\n {\n return std::shared_ptr(new NodeContainer(name));\n }\n\n NodeContainer::NodeContainer(std::string name)\n : Node(name)\n {\n }\n \n \n \/\/------------------------------------------------------\n #pragma mark - Scene -\n \n void NodeContainer::setScene(SceneRef scene)\n {\n Node::setScene(scene);\n for(NodeRef &childNode : mChildren) {\n childNode->setScene(scene);\n }\n }\n \n void NodeContainer::removeScene()\n {\n Node::removeScene();\n for(NodeRef &childNode : mChildren) {\n childNode->removeScene();\n }\n }\n \n \n \/\/------------------------------------------------------\n #pragma mark - Add Children -\n\n void NodeContainer::addChild(NodeRef node)\n {\n setParentAndScene(node);\n mChildren.push_back(node);\n }\n \n void NodeContainer::addChildAt(int index, NodeRef node)\n {\n setParentAndScene(node);\n mChildren.insert(mChildren.begin()+index, node);\n }\n \n void NodeContainer::addChildBefore(NodeRef before, NodeRef node)\n {\n setParentAndScene(node);\n mChildren.insert(mChildren.begin() + getChildIndex(before), node);\n }\n \n void NodeContainer::addChildAfter(NodeRef after, NodeRef node)\n {\n setParentAndScene(node);\n mChildren.insert(mChildren.begin() + getChildIndex(after)+1, node);\n }\n \n \n \/\/------------------------------------------------------\n #pragma mark - Get Children -\n \n std::vector NodeContainer::getChildren()\n {\n return mChildren;\n };\n \n std::vector& NodeContainer::getChildrenByReference()\n {\n return mChildren;\n }\n \n int NodeContainer::getChildIndex(const NodeRef& child)\n {\n std::vector::iterator iter = std::find(mChildren.begin(), mChildren.end(), child);\n if(iter != mChildren.end())\n return (int)std::distance(mChildren.begin(), iter);\n return INVALID_INDEX;\n }\n \n NodeRef NodeContainer::getChildByIndex(int index)\n {\n if(index < 0 || index >= mChildren.size())\n return NodeRef();\n return *(mChildren.begin() + index);\n }\n \n NodeRef NodeContainer::getChildByUID(uint32_t uid)\n {\n \/\/Go through our tree to find any node with UID\n for(NodeRef& node : mChildren) {\n NodeContainerRef container = std::dynamic_pointer_cast(node);\n if(container) {\n NodeRef foundNode = container->getChildByUID(uid);\n if(foundNode) return foundNode;\n }\n \n else {\n if(node->getUID() == uid) return node;\n }\n }\n \n \/\/See if it is us\n if(mUid == uid) return shared_from_this();\n \n \/\/Not found\n return NodeRef();\n }\n \n NodeRef NodeContainer::getChildByName(const std::string &name)\n {\n for(NodeRef& node : mChildren) {\n if(node->getName() == name) return node;\n }\n \n return NodeRef();\n }\n \n NodeRef NodeContainer::getFirstChild()\n {\n if(mChildren.empty())\n return NodeRef();\n \n return mChildren.front();\n }\n \n NodeRef NodeContainer::getLastChild()\n {\n if(mChildren.empty())\n return NodeRef();\n \n return mChildren.back();\n }\n \n \n \/\/------------------------------------------------------\n #pragma mark - Remove Children -\n \n bool NodeContainer::removeChild(NodeRef node)\n {\n std::vector::iterator iter = std::find(mChildren.begin(), mChildren.end(), node);\n if(iter != mChildren.end()) {\n (*iter)->removeParent();\n (*iter)->removeScene();\n \n #pragma message \"This is not safe in recursion...\"\n mChildren.erase(iter);\n \n return true;\n }\n \n return false;\n }\n \n bool NodeContainer::removeChildAt(int index)\n {\n if(index <= 0 || index >= mChildren.size())\n return false;\n \n mChildren[index]->removeParent();\n mChildren[index]->removeScene();\n \n mChildren.erase(mChildren.begin() + index);\n \n return true;\n }\n \n void NodeContainer::removeAllChildren()\n {\n for(NodeRef& node : mChildren) {\n node->removeParent();\n node->removeScene();\n }\n \n mChildren.clear();\n }\n \n \n \/\/------------------------------------------------------\n #pragma mark - Move Children -\n \n void NodeContainer::moveChildToFront(NodeRef& node)\n {\n if(removeChild(node))\n addChild(node);\n }\n \n void NodeContainer::moveChildForward(NodeRef& node)\n {\n int idx = getChildIndex(node);\n if(removeChild(node))\n #pragma message \"Does this work with a vector, or would this be out of bounds?\"\n addChildAt(std::min(idx+1, getNumChildren()), node);\n }\n \n void NodeContainer::moveChildToBack(NodeRef& node)\n {\n if(removeChild(node))\n addChildAt(0, node);\n }\n \n void NodeContainer::moveChildBackward(NodeRef& node)\n {\n int idx = getChildIndex(node);\n if(removeChild(node))\n addChildAt(std::max(idx-1, 0), node);\n }\n \n void NodeContainer::setParentAndScene(NodeRef node)\n {\n \/\/See if the node is already a child of another node.\n if(node->getParent())\n node->getParent()->removeChild(node);\n \n \/\/Assign ourselves as the parent\n node->setParent(std::dynamic_pointer_cast(shared_from_this()));\n node->setScene(mScene.lock());\n }\n \n \n \/\/------------------------------------------------------\n #pragma mark - Update and Draw Trees -\n\n void NodeContainer::updateTree()\n {\n update();\n for(NodeRef &childNode : mChildren)\n childNode->updateTree();\n }\n\n void NodeContainer::drawTree()\n {\n #pragma message \"Need to implement matrix order\"\n ci::gl::pushMatrices();\n setTransformation();\n \n draw();\n for(NodeRef &childNode : mChildren) {\n childNode->drawTree();\n \n #pragma message \"For testing, should be removed\"\n ci::gl::color(0,255,0);\n ci::gl::drawStrokedRect(childNode->getFrame());\n }\n \n if(mDrawBounds)\n drawBounds();\n \n ci::gl::popMatrices();\n }\n \n \n \/\/------------------------------------------------------\n #pragma mark - Dimensions -\n\n ci::Rectf NodeContainer::getBounds()\n {\n \/\/Reset Bounds\n ci::Rectf bounds = ci::Rectf(0,0,0,0);\n \n for(NodeRef &childNode : mChildren)\n bounds.include(childNode->getFrame());\n \n return bounds;\n }\n \n bool NodeContainer::pointInside(const ci::Vec2f &point)\n {\n for (NodeRef node : mChildren) {\n if (node->pointInside(point)) {\n return true;\n }\n }\n \n return false;\n }\n}Checking objects for visibility before including frame in bounds\/\/\n\/\/ poNodeContainer.cpp\n\/\/ BasicScene\n\/\/\n\/\/ Created by Stephen Varga on 3\/22\/14.\n\/\/\n\/\/\n\n#include \"poNodeContainer.h\"\n\nnamespace po {\n NodeContainerRef NodeContainer::create(std::string name)\n {\n return std::shared_ptr(new NodeContainer(name));\n }\n\n NodeContainer::NodeContainer(std::string name)\n : Node(name)\n {\n }\n \n \n \/\/------------------------------------------------------\n #pragma mark - Scene -\n \n void NodeContainer::setScene(SceneRef scene)\n {\n Node::setScene(scene);\n for(NodeRef &childNode : mChildren) {\n childNode->setScene(scene);\n }\n }\n \n void NodeContainer::removeScene()\n {\n Node::removeScene();\n for(NodeRef &childNode : mChildren) {\n childNode->removeScene();\n }\n }\n \n \n \/\/------------------------------------------------------\n #pragma mark - Add Children -\n\n void NodeContainer::addChild(NodeRef node)\n {\n setParentAndScene(node);\n mChildren.push_back(node);\n }\n \n void NodeContainer::addChildAt(int index, NodeRef node)\n {\n setParentAndScene(node);\n mChildren.insert(mChildren.begin()+index, node);\n }\n \n void NodeContainer::addChildBefore(NodeRef before, NodeRef node)\n {\n setParentAndScene(node);\n mChildren.insert(mChildren.begin() + getChildIndex(before), node);\n }\n \n void NodeContainer::addChildAfter(NodeRef after, NodeRef node)\n {\n setParentAndScene(node);\n mChildren.insert(mChildren.begin() + getChildIndex(after)+1, node);\n }\n \n \n \/\/------------------------------------------------------\n #pragma mark - Get Children -\n \n std::vector NodeContainer::getChildren()\n {\n return mChildren;\n };\n \n std::vector& NodeContainer::getChildrenByReference()\n {\n return mChildren;\n }\n \n int NodeContainer::getChildIndex(const NodeRef& child)\n {\n std::vector::iterator iter = std::find(mChildren.begin(), mChildren.end(), child);\n if(iter != mChildren.end())\n return (int)std::distance(mChildren.begin(), iter);\n return INVALID_INDEX;\n }\n \n NodeRef NodeContainer::getChildByIndex(int index)\n {\n if(index < 0 || index >= mChildren.size())\n return NodeRef();\n return *(mChildren.begin() + index);\n }\n \n NodeRef NodeContainer::getChildByUID(uint32_t uid)\n {\n \/\/Go through our tree to find any node with UID\n for(NodeRef& node : mChildren) {\n NodeContainerRef container = std::dynamic_pointer_cast(node);\n if(container) {\n NodeRef foundNode = container->getChildByUID(uid);\n if(foundNode) return foundNode;\n }\n \n else {\n if(node->getUID() == uid) return node;\n }\n }\n \n \/\/See if it is us\n if(mUid == uid) return shared_from_this();\n \n \/\/Not found\n return NodeRef();\n }\n \n NodeRef NodeContainer::getChildByName(const std::string &name)\n {\n for(NodeRef& node : mChildren) {\n if(node->getName() == name) return node;\n }\n \n return NodeRef();\n }\n \n NodeRef NodeContainer::getFirstChild()\n {\n if(mChildren.empty())\n return NodeRef();\n \n return mChildren.front();\n }\n \n NodeRef NodeContainer::getLastChild()\n {\n if(mChildren.empty())\n return NodeRef();\n \n return mChildren.back();\n }\n \n \n \/\/------------------------------------------------------\n #pragma mark - Remove Children -\n \n bool NodeContainer::removeChild(NodeRef node)\n {\n std::vector::iterator iter = std::find(mChildren.begin(), mChildren.end(), node);\n if(iter != mChildren.end()) {\n (*iter)->removeParent();\n (*iter)->removeScene();\n \n #pragma message \"This is not safe in recursion...\"\n mChildren.erase(iter);\n \n return true;\n }\n \n return false;\n }\n \n bool NodeContainer::removeChildAt(int index)\n {\n if(index <= 0 || index >= mChildren.size())\n return false;\n \n mChildren[index]->removeParent();\n mChildren[index]->removeScene();\n \n mChildren.erase(mChildren.begin() + index);\n \n return true;\n }\n \n void NodeContainer::removeAllChildren()\n {\n for(NodeRef& node : mChildren) {\n node->removeParent();\n node->removeScene();\n }\n \n mChildren.clear();\n }\n \n \n \/\/------------------------------------------------------\n #pragma mark - Move Children -\n \n void NodeContainer::moveChildToFront(NodeRef& node)\n {\n if(removeChild(node))\n addChild(node);\n }\n \n void NodeContainer::moveChildForward(NodeRef& node)\n {\n int idx = getChildIndex(node);\n if(removeChild(node))\n #pragma message \"Does this work with a vector, or would this be out of bounds?\"\n addChildAt(std::min(idx+1, getNumChildren()), node);\n }\n \n void NodeContainer::moveChildToBack(NodeRef& node)\n {\n if(removeChild(node))\n addChildAt(0, node);\n }\n \n void NodeContainer::moveChildBackward(NodeRef& node)\n {\n int idx = getChildIndex(node);\n if(removeChild(node))\n addChildAt(std::max(idx-1, 0), node);\n }\n \n void NodeContainer::setParentAndScene(NodeRef node)\n {\n \/\/See if the node is already a child of another node.\n if(node->getParent())\n node->getParent()->removeChild(node);\n \n \/\/Assign ourselves as the parent\n node->setParent(std::dynamic_pointer_cast(shared_from_this()));\n node->setScene(mScene.lock());\n }\n \n \n \/\/------------------------------------------------------\n #pragma mark - Update and Draw Trees -\n\n void NodeContainer::updateTree()\n {\n update();\n for(NodeRef &childNode : mChildren)\n childNode->updateTree();\n }\n\n void NodeContainer::drawTree()\n {\n #pragma message \"Need to implement matrix order\"\n ci::gl::pushMatrices();\n setTransformation();\n \n draw();\n for(NodeRef &childNode : mChildren) {\n childNode->drawTree();\n \n #pragma message \"For testing, should be removed\"\n \/\/ci::gl::color(0,255,0);\n \/\/ci::gl::drawStrokedRect(childNode->getFrame());\n }\n \n if(mDrawBounds)\n drawBounds();\n \n ci::gl::popMatrices();\n }\n \n \n \/\/------------------------------------------------------\n #pragma mark - Dimensions -\n\n ci::Rectf NodeContainer::getBounds()\n {\n \/\/Reset Bounds\n ci::Rectf bounds = ci::Rectf(0,0,0,0);\n \n for(NodeRef &childNode : mChildren) {\n\t\t\tif(childNode->isVisible())\n\t\t\t\tbounds.include(childNode->getFrame());\n\t\t}\n \n \n return bounds;\n }\n \n bool NodeContainer::pointInside(const ci::Vec2f &point)\n {\n for (NodeRef node : mChildren) {\n if (node->pointInside(point)) {\n return true;\n }\n }\n \n return false;\n }\n}<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved\n *\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#include \"..\/..\/Characters\/String_Constant.h\"\n#include \"..\/..\/Debug\/Trace.h\"\n#include \"..\/..\/Execution\/ErrNoException.h\"\n\n#include \"InternetAddress.h\"\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::Memory;\nusing namespace Stroika::Foundation::IO;\nusing namespace Stroika::Foundation::IO::Network;\n\n\n#define qSupportPTONAndPTON_ (qPlatform_POSIX || (qPlatformWindows && (NTDDI_VERSION >= NTDDI_VISTA)))\n\n#if qCompilerAndStdLib_constexpr_union_variants_Buggy\nconst InternetAddress V4::kAddrAny = InternetAddress (in_addr {});\nconst InternetAddress V6::kAddrAny = InternetAddress (in6_addr {});\n#if qPlatform_POSIX\nconst InternetAddress V4::kLocalhost = InternetAddress (in_addr { INADDR_LOOPBACK } );\n#elif qPlatform_Windows\nconst InternetAddress V4::kLocalhost = InternetAddress (in_addr { { { 0x1, 0x0, 0x0, 0x7f } } } );\n#endif\nconst InternetAddress V6::kLocalhost = InternetAddress (in6_addr { { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 } } } );\n#endif\n\n\n\n#if qPlatform_Windows\n\/\/ Not sure why this is necessary, but we get link errors sometimes without it... Maybe a windows makefile issue on regtest apps?\n\/\/ -- LGP 2014-11-06\n#pragma comment(lib, \"Ws2_32.lib\")\n#endif\n\n\n\n\n\/*\n ********************************************************************************\n ********************* IO::Network::InternetAddress *****************************\n ********************************************************************************\n *\/\nInternetAddress::InternetAddress (const string& s, AddressFamily af)\n : fAddressFamily_ (AddressFamily::UNKNOWN)\n{\n if (not s.empty ()) {\n if (af == AddressFamily::UNKNOWN) {\n \/\/ guess format - based on '.' versus ':' in name\n if (s.find ('.') != string::npos) {\n af = AddressFamily::V4;\n }\n else if (s.find (':') != string::npos) {\n af = AddressFamily::V6;\n }\n }\n switch (af) {\n case AddressFamily::V4: {\n#if qSupportPTONAndPTON_\n Execution::ThrowErrNoIfNegative (inet_pton (AF_INET, s.c_str (), &fV4_));\n#elif qPlatform_Windows\n DISABLE_COMPILER_MSC_WARNING_START(4996) \/\/ msft doesnt have this on old platforms but still warns!\n fV4_.s_addr = ::inet_addr (s.c_str ());\n DISABLE_COMPILER_MSC_WARNING_END(4996)\n#else\n AssertNotImplemented ();\n#endif\n fAddressFamily_ = af;\n }\n break;\n case AddressFamily::V6: {\n#if qSupportPTONAndPTON_\n Execution::ThrowErrNoIfNegative (inet_pton (AF_INET6, s.c_str (), &fV6_));\n#else\n AssertNotImplemented ();\n#endif\n fAddressFamily_ = af;\n }\n break;\n default: {\n \/\/ @todo need better exception\n Execution::DoThrow (Execution::StringException (String_Constant (L\"Unrecognized address family\")));\n }\n break;\n }\n }\n}\n\nInternetAddress::InternetAddress (const String& s, AddressFamily af)\n : InternetAddress (s.AsUTF8 (), af)\n{\n}\n\nnamespace Stroika {\n namespace Foundation {\n namespace IO {\n namespace Network {\n template <>\n String InternetAddress::As () const\n {\n switch (fAddressFamily_) {\n case AddressFamily::UNKNOWN: {\n return String ();\n }\n break;\n case AddressFamily::V4: {\n#if qSupportPTONAndPTON_\n char buf[INET_ADDRSTRLEN + 1];\n const char* result = ::inet_ntop (AF_INET, &fV4_, buf, sizeof (buf));\n return result == nullptr ? String () : String::FromUTF8 (result);\n#else\n DISABLE_COMPILER_MSC_WARNING_START(4996) \/\/ msft doesnt have this on old platforms but still warns!\n return String::FromUTF8 (::inet_ntoa (fV4_));\n DISABLE_COMPILER_MSC_WARNING_END(4996)\n#endif\n }\n break;\n case AddressFamily::V6: {\n#if qSupportPTONAndPTON_\n char buf[INET6_ADDRSTRLEN + 1];\n const char* result = ::inet_ntop (AF_INET6, &fV6_, buf, sizeof (buf));\n return result == nullptr ? String () : String::FromUTF8 (result);\n#else\n AssertNotImplemented ();\n return String ();\n#endif\n }\n break;\n default: {\n RequireNotReached ();\n return String ();\n }\n break;\n }\n }\n }\n }\n }\n}\n\nbool InternetAddress::IsLocalhostAddress () const\n{\n Require (not empty ());\n switch (fAddressFamily_) {\n case AddressFamily::V4: {\n \/\/ 127.0.0.x\n \/\/return (::ntohl (fV4_.s_addr) & 0xffffff00) == 0x7f000000;\n return (ntohl (fV4_.s_addr) & 0x00ffffff) == 0x00007f;\n }\n break;\n case AddressFamily::V6: {\n return\n fV6_.s6_addr[0] == 0 and\n fV6_.s6_addr[1] == 0 and\n fV6_.s6_addr[2] == 0 and\n fV6_.s6_addr[3] == 0 and\n fV6_.s6_addr[4] == 0 and\n fV6_.s6_addr[5] == 0 and\n fV6_.s6_addr[6] == 0 and\n fV6_.s6_addr[7] == 0 and\n fV6_.s6_addr[8] == 0 and\n fV6_.s6_addr[9] == 0 and\n fV6_.s6_addr[10] == 0 and\n fV6_.s6_addr[11] == 0 and\n fV6_.s6_addr[12] == 0 and\n fV6_.s6_addr[13] == 0 and\n fV6_.s6_addr[14] == 0 and\n fV6_.s6_addr[15] == 1\n ;\n }\n break;\n }\n AssertNotReached ();\n return false;\n}\n\nbool InternetAddress::IsLinkLocalAddress () const\n{\n Require (not empty ());\n switch (fAddressFamily_) {\n case AddressFamily::V4: {\n static const InternetAddress kMinLinkLocal_ { \"169.254.0.1\" };\n static const InternetAddress kMaxLinkLocal_ { \"169.254.255.254\" };\n return kMinLinkLocal_ <= *this and * this <= kMaxLinkLocal_;\n }\n break;\n case AddressFamily::V6: {\n return\n fV6_.s6_addr[0] == 0xfe and fV6_.s6_addr[1] == 0x80 and\n fV6_.s6_addr[2] == 0x0 and fV6_.s6_addr[3] == 0x0 and\n fV6_.s6_addr[4] == 0x0 and fV6_.s6_addr[5] == 0x0 and\n fV6_.s6_addr[6] == 0x0 and fV6_.s6_addr[7] == 0x0\n ;\n }\n break;\n }\n AssertNotReached ();\n return false;\n}\n\nbool InternetAddress::IsPrivateAddress () const\n{\n#if qDebug && defined (s_net)\n auto ipv4Checker = [](in_addr n) -> bool {\n if (n.s_net == 10)\n {\n return true;\n }\n else if (n.s_net == 172 and (16 <= n.s_host and n.s_host == 31))\n {\n return true;\n }\n else if (n.s_net == 192 and n.s_host == 168)\n {\n return true;\n }\n return false;\n };\n#endif\n#if qDebug && defined (s6_words)\n auto ipv6Checker = [](in6_addr n) -> bool {\n return n.s6_words[0] == 0xfc00;\n };\n#endif\n switch (fAddressFamily_) {\n case AddressFamily::V4: {\n \/*\n * http:\/\/www.faqs.org\/rfcs\/rfc1918.html\n *\n * 3. Private Address Space\n *\n * The Internet Assigned Numbers Authority (IANA) has reserved the\n * following three blocks of the IP address space for private internets:\n *\n * 10.0.0.0 - 10.255.255.255 (10\/8 prefix)\n * 172.16.0.0 - 172.31.255.255 (172.16\/12 prefix)\n * 192.168.0.0 - 192.168.255.255 (192.168\/16 prefix)\n *\/\n uint32_t hostByteOrderAddr = ntohl (fV4_.s_addr);\n uint8_t net = (hostByteOrderAddr >> 24);\n uint8_t host = ((hostByteOrderAddr >> 16) & 0xff);\n if (net == 10) {\n#if defined (s_net)\n Assert (ipv4Checker (fV4_));\n#endif\n return true;\n }\n else if (net == 172 and (16 <= host and host == 31)) {\n#if defined (s_net)\n Assert (ipv4Checker (fV4_));\n#endif\n return true;\n }\n else if (net == 192 and host == 168) {\n#if defined (s_net)\n Assert (ipv4Checker (fV4_));\n#endif\n return true;\n }\n#if defined (s_net)\n Assert (not ipv4Checker (fV4_));\n#endif\n return false;\n }\n break;\n case AddressFamily::V6: {\n \/*\n * From http:\/\/en.wikipedia.org\/wiki\/Private_network\n *\n * The concept of private networks and special address reservation for such networks\n * has been carried over to the next generation of the Internet Protocol, IPv6.\n * The address block fc00:: \/ 7 has been reserved by IANA as described in RFC 4193.\n * These addresses are called Unique Local Addresses (ULA).They are defined as being\n * unicast in character and contain a 40 - bit random number in the routing prefix.\n *\/\n bool result = fV6_.s6_addr[0] == 0xfc and fV6_.s6_addr[1] == 0x0;\n#if defined (s6_words)\n Assert (ipv6Checker (fV6_) == result);\n#endif\n return result;\n }\n break;\n }\n AssertNotReached ();\n return false;\n}\n\nbool InternetAddress::IsMulticastAddress () const\n{\n Require (not empty ());\n switch (fAddressFamily_) {\n case AddressFamily::V4: {\n \/\/ Not sure - might have byte order backwards??? or totally wrong - a bit of a guess?\n return (ntohl (fV4_.s_addr) & 0xf0000000) == 0xe0000000;\n }\n break;\n case AddressFamily::V6: {\n return (fV6_.s6_addr[0] == 0xff);\n }\n break;\n }\n AssertNotReached ();\n return false;\n}\n\nint InternetAddress::Compare (const InternetAddress& rhs) const\n{\n if (fAddressFamily_ != rhs.fAddressFamily_) {\n return fAddressFamily_ < rhs.fAddressFamily_ ? -1 : 1;\n }\n switch (fAddressFamily_) {\n case AddressFamily::UNKNOWN: {\n return 0;\n }\n break;\n case AddressFamily::V4: {\n \/\/ if not equal, compare by net\/host before other things so we get sensible intuitive ordering\n if (memcmp (&fV4_, &rhs.fV4_, sizeof (fV4_)) == 0) {\n return 0;\n }\n#if qPlatform_POSIX\n if (inet_netof (fV4_) != inet_netof (rhs.fV4_)) {\n return inet_netof (fV4_) - inet_netof (rhs.fV4_);\n }\n if (inet_lnaof (fV4_) != inet_lnaof (rhs.fV4_)) {\n return inet_lnaof (fV4_) - inet_lnaof (rhs.fV4_);\n }\n#elif qPlatform_Windows\n if (fV4_.s_net != rhs.fV4_.s_net) {\n return static_cast (fV4_.s_net) - static_cast (rhs.fV4_.s_net);\n }\n if (fV4_.s_host != rhs.fV4_.s_host) {\n return static_cast (fV4_.s_host) - static_cast (rhs.fV4_.s_host);\n }\n if (fV4_.s_lh != rhs.fV4_.s_lh) {\n return static_cast (fV4_.s_lh) - static_cast (rhs.fV4_.s_lh);\n }\n if (fV4_.s_impno != rhs.fV4_.s_impno) {\n return static_cast (fV4_.s_impno) - static_cast (rhs.fV4_.s_impno);\n }\n#endif\n AssertNotReached ();\n return 0;\n \/\/return memcmp (&fV4_, &rhs.fV4_, sizeof (fV4_));\n }\n break;\n case AddressFamily::V6: {\n return memcmp (&fV6_, &fV6_, sizeof (fV6_));\n }\n break;\n }\n AssertNotReached ();\n return false;\n}\ncast to int for better compare in InternetAddress::Compare () for POSIX\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved\n *\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#include \"..\/..\/Characters\/String_Constant.h\"\n#include \"..\/..\/Debug\/Trace.h\"\n#include \"..\/..\/Execution\/ErrNoException.h\"\n\n#include \"InternetAddress.h\"\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::Memory;\nusing namespace Stroika::Foundation::IO;\nusing namespace Stroika::Foundation::IO::Network;\n\n\n#define qSupportPTONAndPTON_ (qPlatform_POSIX || (qPlatformWindows && (NTDDI_VERSION >= NTDDI_VISTA)))\n\n#if qCompilerAndStdLib_constexpr_union_variants_Buggy\nconst InternetAddress V4::kAddrAny = InternetAddress (in_addr {});\nconst InternetAddress V6::kAddrAny = InternetAddress (in6_addr {});\n#if qPlatform_POSIX\nconst InternetAddress V4::kLocalhost = InternetAddress (in_addr { INADDR_LOOPBACK } );\n#elif qPlatform_Windows\nconst InternetAddress V4::kLocalhost = InternetAddress (in_addr { { { 0x1, 0x0, 0x0, 0x7f } } } );\n#endif\nconst InternetAddress V6::kLocalhost = InternetAddress (in6_addr { { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 } } } );\n#endif\n\n\n\n#if qPlatform_Windows\n\/\/ Not sure why this is necessary, but we get link errors sometimes without it... Maybe a windows makefile issue on regtest apps?\n\/\/ -- LGP 2014-11-06\n#pragma comment(lib, \"Ws2_32.lib\")\n#endif\n\n\n\n\n\/*\n ********************************************************************************\n ********************* IO::Network::InternetAddress *****************************\n ********************************************************************************\n *\/\nInternetAddress::InternetAddress (const string& s, AddressFamily af)\n : fAddressFamily_ (AddressFamily::UNKNOWN)\n{\n if (not s.empty ()) {\n if (af == AddressFamily::UNKNOWN) {\n \/\/ guess format - based on '.' versus ':' in name\n if (s.find ('.') != string::npos) {\n af = AddressFamily::V4;\n }\n else if (s.find (':') != string::npos) {\n af = AddressFamily::V6;\n }\n }\n switch (af) {\n case AddressFamily::V4: {\n#if qSupportPTONAndPTON_\n Execution::ThrowErrNoIfNegative (inet_pton (AF_INET, s.c_str (), &fV4_));\n#elif qPlatform_Windows\n DISABLE_COMPILER_MSC_WARNING_START(4996) \/\/ msft doesnt have this on old platforms but still warns!\n fV4_.s_addr = ::inet_addr (s.c_str ());\n DISABLE_COMPILER_MSC_WARNING_END(4996)\n#else\n AssertNotImplemented ();\n#endif\n fAddressFamily_ = af;\n }\n break;\n case AddressFamily::V6: {\n#if qSupportPTONAndPTON_\n Execution::ThrowErrNoIfNegative (inet_pton (AF_INET6, s.c_str (), &fV6_));\n#else\n AssertNotImplemented ();\n#endif\n fAddressFamily_ = af;\n }\n break;\n default: {\n \/\/ @todo need better exception\n Execution::DoThrow (Execution::StringException (String_Constant (L\"Unrecognized address family\")));\n }\n break;\n }\n }\n}\n\nInternetAddress::InternetAddress (const String& s, AddressFamily af)\n : InternetAddress (s.AsUTF8 (), af)\n{\n}\n\nnamespace Stroika {\n namespace Foundation {\n namespace IO {\n namespace Network {\n template <>\n String InternetAddress::As () const\n {\n switch (fAddressFamily_) {\n case AddressFamily::UNKNOWN: {\n return String ();\n }\n break;\n case AddressFamily::V4: {\n#if qSupportPTONAndPTON_\n char buf[INET_ADDRSTRLEN + 1];\n const char* result = ::inet_ntop (AF_INET, &fV4_, buf, sizeof (buf));\n return result == nullptr ? String () : String::FromUTF8 (result);\n#else\n DISABLE_COMPILER_MSC_WARNING_START(4996) \/\/ msft doesnt have this on old platforms but still warns!\n return String::FromUTF8 (::inet_ntoa (fV4_));\n DISABLE_COMPILER_MSC_WARNING_END(4996)\n#endif\n }\n break;\n case AddressFamily::V6: {\n#if qSupportPTONAndPTON_\n char buf[INET6_ADDRSTRLEN + 1];\n const char* result = ::inet_ntop (AF_INET6, &fV6_, buf, sizeof (buf));\n return result == nullptr ? String () : String::FromUTF8 (result);\n#else\n AssertNotImplemented ();\n return String ();\n#endif\n }\n break;\n default: {\n RequireNotReached ();\n return String ();\n }\n break;\n }\n }\n }\n }\n }\n}\n\nbool InternetAddress::IsLocalhostAddress () const\n{\n Require (not empty ());\n switch (fAddressFamily_) {\n case AddressFamily::V4: {\n \/\/ 127.0.0.x\n \/\/return (::ntohl (fV4_.s_addr) & 0xffffff00) == 0x7f000000;\n return (ntohl (fV4_.s_addr) & 0x00ffffff) == 0x00007f;\n }\n break;\n case AddressFamily::V6: {\n return\n fV6_.s6_addr[0] == 0 and\n fV6_.s6_addr[1] == 0 and\n fV6_.s6_addr[2] == 0 and\n fV6_.s6_addr[3] == 0 and\n fV6_.s6_addr[4] == 0 and\n fV6_.s6_addr[5] == 0 and\n fV6_.s6_addr[6] == 0 and\n fV6_.s6_addr[7] == 0 and\n fV6_.s6_addr[8] == 0 and\n fV6_.s6_addr[9] == 0 and\n fV6_.s6_addr[10] == 0 and\n fV6_.s6_addr[11] == 0 and\n fV6_.s6_addr[12] == 0 and\n fV6_.s6_addr[13] == 0 and\n fV6_.s6_addr[14] == 0 and\n fV6_.s6_addr[15] == 1\n ;\n }\n break;\n }\n AssertNotReached ();\n return false;\n}\n\nbool InternetAddress::IsLinkLocalAddress () const\n{\n Require (not empty ());\n switch (fAddressFamily_) {\n case AddressFamily::V4: {\n static const InternetAddress kMinLinkLocal_ { \"169.254.0.1\" };\n static const InternetAddress kMaxLinkLocal_ { \"169.254.255.254\" };\n return kMinLinkLocal_ <= *this and * this <= kMaxLinkLocal_;\n }\n break;\n case AddressFamily::V6: {\n return\n fV6_.s6_addr[0] == 0xfe and fV6_.s6_addr[1] == 0x80 and\n fV6_.s6_addr[2] == 0x0 and fV6_.s6_addr[3] == 0x0 and\n fV6_.s6_addr[4] == 0x0 and fV6_.s6_addr[5] == 0x0 and\n fV6_.s6_addr[6] == 0x0 and fV6_.s6_addr[7] == 0x0\n ;\n }\n break;\n }\n AssertNotReached ();\n return false;\n}\n\nbool InternetAddress::IsPrivateAddress () const\n{\n#if qDebug && defined (s_net)\n auto ipv4Checker = [](in_addr n) -> bool {\n if (n.s_net == 10)\n {\n return true;\n }\n else if (n.s_net == 172 and (16 <= n.s_host and n.s_host == 31))\n {\n return true;\n }\n else if (n.s_net == 192 and n.s_host == 168)\n {\n return true;\n }\n return false;\n };\n#endif\n#if qDebug && defined (s6_words)\n auto ipv6Checker = [](in6_addr n) -> bool {\n return n.s6_words[0] == 0xfc00;\n };\n#endif\n switch (fAddressFamily_) {\n case AddressFamily::V4: {\n \/*\n * http:\/\/www.faqs.org\/rfcs\/rfc1918.html\n *\n * 3. Private Address Space\n *\n * The Internet Assigned Numbers Authority (IANA) has reserved the\n * following three blocks of the IP address space for private internets:\n *\n * 10.0.0.0 - 10.255.255.255 (10\/8 prefix)\n * 172.16.0.0 - 172.31.255.255 (172.16\/12 prefix)\n * 192.168.0.0 - 192.168.255.255 (192.168\/16 prefix)\n *\/\n uint32_t hostByteOrderAddr = ntohl (fV4_.s_addr);\n uint8_t net = (hostByteOrderAddr >> 24);\n uint8_t host = ((hostByteOrderAddr >> 16) & 0xff);\n if (net == 10) {\n#if defined (s_net)\n Assert (ipv4Checker (fV4_));\n#endif\n return true;\n }\n else if (net == 172 and (16 <= host and host == 31)) {\n#if defined (s_net)\n Assert (ipv4Checker (fV4_));\n#endif\n return true;\n }\n else if (net == 192 and host == 168) {\n#if defined (s_net)\n Assert (ipv4Checker (fV4_));\n#endif\n return true;\n }\n#if defined (s_net)\n Assert (not ipv4Checker (fV4_));\n#endif\n return false;\n }\n break;\n case AddressFamily::V6: {\n \/*\n * From http:\/\/en.wikipedia.org\/wiki\/Private_network\n *\n * The concept of private networks and special address reservation for such networks\n * has been carried over to the next generation of the Internet Protocol, IPv6.\n * The address block fc00:: \/ 7 has been reserved by IANA as described in RFC 4193.\n * These addresses are called Unique Local Addresses (ULA).They are defined as being\n * unicast in character and contain a 40 - bit random number in the routing prefix.\n *\/\n bool result = fV6_.s6_addr[0] == 0xfc and fV6_.s6_addr[1] == 0x0;\n#if defined (s6_words)\n Assert (ipv6Checker (fV6_) == result);\n#endif\n return result;\n }\n break;\n }\n AssertNotReached ();\n return false;\n}\n\nbool InternetAddress::IsMulticastAddress () const\n{\n Require (not empty ());\n switch (fAddressFamily_) {\n case AddressFamily::V4: {\n \/\/ Not sure - might have byte order backwards??? or totally wrong - a bit of a guess?\n return (ntohl (fV4_.s_addr) & 0xf0000000) == 0xe0000000;\n }\n break;\n case AddressFamily::V6: {\n return (fV6_.s6_addr[0] == 0xff);\n }\n break;\n }\n AssertNotReached ();\n return false;\n}\n\nint InternetAddress::Compare (const InternetAddress& rhs) const\n{\n if (fAddressFamily_ != rhs.fAddressFamily_) {\n return fAddressFamily_ < rhs.fAddressFamily_ ? -1 : 1;\n }\n switch (fAddressFamily_) {\n case AddressFamily::UNKNOWN: {\n return 0;\n }\n break;\n case AddressFamily::V4: {\n \/\/ if not equal, compare by net\/host before other things so we get sensible intuitive ordering\n if (memcmp (&fV4_, &rhs.fV4_, sizeof (fV4_)) == 0) {\n return 0;\n }\n#if qPlatform_POSIX\n if (inet_netof (fV4_) != inet_netof (rhs.fV4_)) {\n return static_cast (inet_netof (fV4_)) - static_cast (inet_netof (rhs.fV4_));\n }\n if (inet_lnaof (fV4_) != inet_lnaof (rhs.fV4_)) {\n return static_cast (inet_lnaof (fV4_)) - static_cast (inet_lnaof (rhs.fV4_));\n }\n#elif qPlatform_Windows\n if (fV4_.s_net != rhs.fV4_.s_net) {\n return static_cast (fV4_.s_net) - static_cast (rhs.fV4_.s_net);\n }\n if (fV4_.s_host != rhs.fV4_.s_host) {\n return static_cast (fV4_.s_host) - static_cast (rhs.fV4_.s_host);\n }\n if (fV4_.s_lh != rhs.fV4_.s_lh) {\n return static_cast (fV4_.s_lh) - static_cast (rhs.fV4_.s_lh);\n }\n if (fV4_.s_impno != rhs.fV4_.s_impno) {\n return static_cast (fV4_.s_impno) - static_cast (rhs.fV4_.s_impno);\n }\n#endif\n AssertNotReached ();\n return 0;\n \/\/return memcmp (&fV4_, &rhs.fV4_, sizeof (fV4_));\n }\n break;\n case AddressFamily::V6: {\n return memcmp (&fV6_, &fV6_, sizeof (fV6_));\n }\n break;\n }\n AssertNotReached ();\n return false;\n}\n<|endoftext|>"} {"text":"#include \"Threading.hpp\"\r\n#include \"ThreadData.hpp\"\r\n#include \r\n#include \r\n\r\nnamespace Cpp {\r\n\/\/------------------------------------------------------------------------------\r\nclass Win32_ThreadData\r\n{\r\npublic:\r\n\tWin32_ThreadData()\r\n\t{\r\n\t\tInitializeCriticalSection(&cs_);\r\n\t}\r\n\r\n\t~Win32_ThreadData()\r\n\t{\r\n\t\tassert(ref_.isNull());\r\n\t\tDeleteCriticalSection(&cs_);\r\n\t}\r\n\r\n\tvoid lock()\r\n\t{\r\n\t\tEnterCriticalSection(&cs);\r\n\t}\r\n\r\n\tvoid unlock()\r\n\t{\r\n\t\tLeaveCriticalSection(&cs);\r\n\t}\r\n\r\n\tvoid retain()\r\n\t{\r\n\t\tref_.retain();\r\n\t}\r\n\r\n\tvoid release()\r\n\t{\r\n\t\tif(ref_.release())\r\n\t\t{\r\n\t\t\tdelete this;\r\n\t\t}\r\n\t}\r\nprivate:\r\n\tAtomicReferenceCounter ref_;\r\n\tCRITICAL_SECTION cs_;\r\n};\r\n\/\/------------------------------------------------------------------------------\r\nstatic DWORD dwTlsIndex = 0;\r\n\/\/------------------------------------------------------------------------------\r\nvoid Threading::constructProcessData()\r\n{\r\n\tassert(!dwTlsIndex);\r\n\tdwTlsIndex = TlsAlloc();\r\n\tconstructThreadData();\r\n}\r\n\/\/------------------------------------------------------------------------------\r\nvoid Threading::destructProcessData()\r\n{\r\n\tdestructThreadData();\r\n\tassert(dwTlsIndex);\r\n\tTlsFree(dwTlsIndex);\r\n}\r\n\/\/------------------------------------------------------------------------------\r\nvoid Threading::constructThreadData()\r\n{\r\n\tassert(dwTlsIndex);\r\n\tassert(!TlsGetValue(dwTlsIndex));\r\n\tWin32_ThreadData * data = new Win32_ThreadData();\r\n\tdata->retain();\r\n\tLPVOID pvTlsData = reinterpret_cast(data);\r\n\tTlsSetValue(dwTlsIndex, pvTlsData);\r\n}\r\n\/\/------------------------------------------------------------------------------\r\nvoid Threading::destructThreadData()\r\n{\r\n\tassert(dwTlsIndex);\r\n\tLPVOID pvTlsData = TlsGetValue(dwTlsIndex);\r\n\tassert(pvTlsData);\r\n\tWin32_ThreadData * data = reinterpret_cast(pvTlsData);\r\n\tdata->release();\r\n\tTlsSetValue(dwTlsIndex, NULL);\r\n}\r\n\/\/------------------------------------------------------------------------------\r\nThreading::ThreadData * Threading::currentThreadData()\r\n{\r\n\tassert(dwTlsIndex);\r\n\tLPVOID pvTlsData = TlsGetValue(dwTlsIndex);\r\n\tassert(pvTlsData);\r\n\tWin32_ThreadData * data = reinterpret_cast(pvTlsData);\r\n\treturn reinterpret_cast(data);\r\n}\r\n\/\/------------------------------------------------------------------------------\r\nvoid Threading::ThreadData::lock()\r\n{\r\n\treinterpret_cast(this)->lock();\r\n}\r\n\/\/------------------------------------------------------------------------------\r\nvoid Threading::ThreadData::unlock()\r\n{\r\n\treinterpret_cast(this)->lock();\r\n}\r\n\/\/------------------------------------------------------------------------------\r\nvoid Threading::ThreadData::retain()\r\n{\r\n\treinterpret_cast(this)->retain();\r\n}\r\n\/\/------------------------------------------------------------------------------\r\nvoid Threading::ThreadData::release()\r\n{\r\n\treinterpret_cast(this)->release();\r\n}\r\n\/\/------------------------------------------------------------------------------\r\n} \/\/namespace Cpp-: Fix for commit 91#include \"Threading.hpp\"\r\n#include \"ThreadData.hpp\"\r\n#include \r\n#include \r\n\r\nnamespace Cpp {\r\n\/\/------------------------------------------------------------------------------\r\nclass Win32_ThreadData\r\n{\r\npublic:\r\n\tWin32_ThreadData()\r\n\t{\r\n\t\tInitializeCriticalSection(&cs_);\r\n\t}\r\n\r\n\t~Win32_ThreadData()\r\n\t{\r\n\t\tassert(ref_.isNull());\r\n\t\tDeleteCriticalSection(&cs_);\r\n\t}\r\n\r\n\tvoid lock()\r\n\t{\r\n\t\tEnterCriticalSection(&cs_);\r\n\t}\r\n\r\n\tvoid unlock()\r\n\t{\r\n\t\tLeaveCriticalSection(&cs_);\r\n\t}\r\n\r\n\tvoid retain()\r\n\t{\r\n\t\tref_.retain();\r\n\t}\r\n\r\n\tvoid release()\r\n\t{\r\n\t\tif(ref_.release())\r\n\t\t{\r\n\t\t\tdelete this;\r\n\t\t}\r\n\t}\r\nprivate:\r\n\tAtomicReferenceCounter ref_;\r\n\tCRITICAL_SECTION cs_;\r\n};\r\n\/\/------------------------------------------------------------------------------\r\nstatic DWORD dwTlsIndex = 0;\r\n\/\/------------------------------------------------------------------------------\r\nvoid Threading::constructProcessData()\r\n{\r\n\tassert(!dwTlsIndex);\r\n\tdwTlsIndex = TlsAlloc();\r\n\tconstructThreadData();\r\n}\r\n\/\/------------------------------------------------------------------------------\r\nvoid Threading::destructProcessData()\r\n{\r\n\tdestructThreadData();\r\n\tassert(dwTlsIndex);\r\n\tTlsFree(dwTlsIndex);\r\n}\r\n\/\/------------------------------------------------------------------------------\r\nvoid Threading::constructThreadData()\r\n{\r\n\tassert(dwTlsIndex);\r\n\tassert(!TlsGetValue(dwTlsIndex));\r\n\tWin32_ThreadData * data = new Win32_ThreadData();\r\n\tdata->retain();\r\n\tLPVOID pvTlsData = reinterpret_cast(data);\r\n\tTlsSetValue(dwTlsIndex, pvTlsData);\r\n}\r\n\/\/------------------------------------------------------------------------------\r\nvoid Threading::destructThreadData()\r\n{\r\n\tassert(dwTlsIndex);\r\n\tLPVOID pvTlsData = TlsGetValue(dwTlsIndex);\r\n\tassert(pvTlsData);\r\n\tWin32_ThreadData * data = reinterpret_cast(pvTlsData);\r\n\tdata->release();\r\n\tTlsSetValue(dwTlsIndex, NULL);\r\n}\r\n\/\/------------------------------------------------------------------------------\r\nThreading::ThreadData * Threading::currentThreadData()\r\n{\r\n\tassert(dwTlsIndex);\r\n\tLPVOID pvTlsData = TlsGetValue(dwTlsIndex);\r\n\tassert(pvTlsData);\r\n\tWin32_ThreadData * data = reinterpret_cast(pvTlsData);\r\n\treturn reinterpret_cast(data);\r\n}\r\n\/\/------------------------------------------------------------------------------\r\nvoid Threading::ThreadData::lock()\r\n{\r\n\treinterpret_cast(this)->lock();\r\n}\r\n\/\/------------------------------------------------------------------------------\r\nvoid Threading::ThreadData::unlock()\r\n{\r\n\treinterpret_cast(this)->lock();\r\n}\r\n\/\/------------------------------------------------------------------------------\r\nvoid Threading::ThreadData::retain()\r\n{\r\n\treinterpret_cast(this)->retain();\r\n}\r\n\/\/------------------------------------------------------------------------------\r\nvoid Threading::ThreadData::release()\r\n{\r\n\treinterpret_cast(this)->release();\r\n}\r\n\/\/------------------------------------------------------------------------------\r\n} \/\/namespace Cpp<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#define USER_MATRIX\n\nint main(int, char *[])\n{\n\tvtkSmartPointer colors =\n\t\tvtkSmartPointer::New();\n\n\t\/\/ Set the background color.\n\tstd::array bkg{ { 26, 51, 77, 255 } };\n\tcolors->SetColor(\"BkgColor\", bkg.data());\n\n\n\t\/\/ Create a cylinder.\n\t\/\/ Cylinder height vector is (0,1,0).\n\t\/\/ Cylinder center is in the middle of the cylinder\n\tvtkSmartPointer cylinderSource =\n\t\tvtkSmartPointer::New();\n\tcylinderSource->SetResolution(15);\n\n\t\/\/ Generate a random start and end point\n\tdouble startPoint[3];\n\tdouble endPoint[3];\n\tvtkSmartPointer rng =\n\t\tvtkSmartPointer::New();\n\trng->SetSeed(8775070); \/\/ For testing.\n\tfor (auto i = 0; i < 3; ++i)\n\t{\n\t\trng->Next();\n\t\tstartPoint[i] = rng->GetRangeValue(-10, 10);\n\t\trng->Next();\n\t\tendPoint[i] = rng->GetRangeValue(-10, 10);\n\t}\n\n\t\/\/ Compute a basis\n\tdouble normalizedX[3];\n\tdouble normalizedY[3];\n\tdouble normalizedZ[3];\n\n\t\/\/ The X axis is a vector from start to end\n\tvtkMath::Subtract(endPoint, startPoint, normalizedX);\n\tdouble length = vtkMath::Norm(normalizedX);\n\tvtkMath::Normalize(normalizedX);\n\n\t\/\/ The Z axis is an arbitrary vector cross X\n\tdouble arbitrary[3];\n\tfor (auto i = 0; i < 3; ++i)\n\t{\n\t\trng->Next();\n\t\tarbitrary[i] = rng->GetRangeValue(-10, 10);\n\t}\n\tvtkMath::Cross(normalizedX, arbitrary, normalizedZ);\n\tvtkMath::Normalize(normalizedZ);\n\n\t\/\/ The Y axis is Z cross X\n\tvtkMath::Cross(normalizedZ, normalizedX, normalizedY);\n\tvtkSmartPointer matrix =\n\t\tvtkSmartPointer::New();\n\n\t\/\/ Create the direction cosine matrix\n\tmatrix->Identity();\n\tfor (unsigned int i = 0; i < 3; i++)\n\t{\n\t\tmatrix->SetElement(i, 0, normalizedX[i]);\n\t\tmatrix->SetElement(i, 1, normalizedY[i]);\n\t\tmatrix->SetElement(i, 2, normalizedZ[i]);\n\t}\n\n\t\/\/ Apply the transforms\n\tvtkSmartPointer transform =\n\t\tvtkSmartPointer::New();\n\ttransform->Translate(startPoint); \/\/ translate to starting point\n\ttransform->Concatenate(matrix); \/\/ apply direction cosines\n\ttransform->RotateZ(-90.0); \/\/ align cylinder to x axis\n\ttransform->Scale(1.0, length, 1.0); \/\/ scale along the height vector\n\ttransform->Translate(0, .5, 0); \/\/ translate to start of cylinder\n\n\t\t\t\t\t\t\t\t\t\t\/\/ Transform the polydata\n\tvtkSmartPointer transformPD =\n\t\tvtkSmartPointer::New();\n\ttransformPD->SetTransform(transform);\n\ttransformPD->SetInputConnection(cylinderSource->GetOutputPort());\n\n\t\/\/Create a mapper and actor for the cylinder\n\tvtkSmartPointer mapper =\n\t\tvtkSmartPointer::New();\n\tvtkSmartPointer actor =\n\t\tvtkSmartPointer::New();\n#ifdef USER_MATRIX\n\tmapper->SetInputConnection(cylinderSource->GetOutputPort());\n\tactor->SetUserMatrix(transform->GetMatrix());\n#else\n\tmapper->SetInputConnection(transformPD->GetOutputPort());\n#endif\n\tactor->SetMapper(mapper);\n\tactor->GetProperty()->SetColor(colors->GetColor3d(\"Cyan\").GetData());\n\n\t\/\/ Create spheres for start and end point\n\tvtkSmartPointer sphereStartSource =\n\t\tvtkSmartPointer::New();\n\tsphereStartSource->SetCenter(startPoint);\n\tsphereStartSource->SetRadius(0.8);\n\tvtkSmartPointer sphereStartMapper =\n\t\tvtkSmartPointer::New();\n\tsphereStartMapper->SetInputConnection(sphereStartSource->GetOutputPort());\n\tvtkSmartPointer sphereStart =\n\t\tvtkSmartPointer::New();\n\tsphereStart->SetMapper(sphereStartMapper);\n\tsphereStart->GetProperty()->SetColor(colors->GetColor3d(\"Yellow\").GetData());\n\n\tvtkSmartPointer sphereEndSource =\n\t\tvtkSmartPointer::New();\n\tsphereEndSource->SetCenter(endPoint);\n\tsphereEndSource->SetRadius(0.8);\n\tvtkSmartPointer sphereEndMapper =\n\t\tvtkSmartPointer::New();\n\tsphereEndMapper->SetInputConnection(sphereEndSource->GetOutputPort());\n\tvtkSmartPointer sphereEnd =\n\t\tvtkSmartPointer::New();\n\tsphereEnd->SetMapper(sphereEndMapper);\n\tsphereEnd->GetProperty()->SetColor(colors->GetColor3d(\"Magenta\").GetData());\n\n\t\/\/Create a renderer, render window, and interactor\n\tvtkSmartPointer renderer =\n\t\tvtkSmartPointer::New();\n\tvtkSmartPointer renderWindow =\n\t\tvtkSmartPointer::New();\n\trenderWindow->AddRenderer(renderer);\n\tvtkSmartPointer renderWindowInteractor =\n\t\tvtkSmartPointer::New();\n\trenderWindowInteractor->SetRenderWindow(renderWindow);\n\n\t\/\/Add the actor to the scene\n\trenderer->AddActor(actor);\n\trenderer->AddActor(sphereStart);\n\trenderer->AddActor(sphereEnd);\n\trenderer->SetBackground(colors->GetColor3d(\"BkgColor\").GetData());\n\n\t\/\/Render and interact\n\trenderWindow->Render();\n\trenderWindowInteractor->Start();\n\n\treturn EXIT_SUCCESS;\n}\nUpdate OpenVROrientedCylinder.cxx#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#define USER_MATRIX\n\nint main(int, char *[])\n{\n vtkSmartPointer colors =\n \tvtkSmartPointer::New();\n \n \/\/ Set the background color.\n std::array bkg{ { 26, 51, 77, 255 } };\n colors->SetColor(\"BkgColor\", bkg.data());\n \n \n \/\/ Create a cylinder.\n \/\/ Cylinder height vector is (0,1,0).\n \/\/ Cylinder center is in the middle of the cylinder\n vtkSmartPointer cylinderSource =\n \tvtkSmartPointer::New();\n cylinderSource->SetResolution(15);\n \n \/\/ Generate a random start and end point\n double startPoint[3];\n double endPoint[3];\n vtkSmartPointer rng =\n \tvtkSmartPointer::New();\n rng->SetSeed(8775070); \/\/ For testing.\n for (auto i = 0; i < 3; ++i)\n {\n \trng->Next();\n \tstartPoint[i] = rng->GetRangeValue(-10, 10);\n \trng->Next();\n \tendPoint[i] = rng->GetRangeValue(-10, 10);\n }\n \n \/\/ Compute a basis\n double normalizedX[3];\n double normalizedY[3];\n double normalizedZ[3];\n \n \/\/ The X axis is a vector from start to end\n vtkMath::Subtract(endPoint, startPoint, normalizedX);\n double length = vtkMath::Norm(normalizedX);\n vtkMath::Normalize(normalizedX);\n \n \/\/ The Z axis is an arbitrary vector cross X\n double arbitrary[3];\n for (auto i = 0; i < 3; ++i)\n {\n \trng->Next();\n \tarbitrary[i] = rng->GetRangeValue(-10, 10);\n }\n vtkMath::Cross(normalizedX, arbitrary, normalizedZ);\n vtkMath::Normalize(normalizedZ);\n \n \/\/ The Y axis is Z cross X\n vtkMath::Cross(normalizedZ, normalizedX, normalizedY);\n vtkSmartPointer matrix =\n \tvtkSmartPointer::New();\n \n \/\/ Create the direction cosine matrix\n matrix->Identity();\n for (unsigned int i = 0; i < 3; i++)\n {\n \tmatrix->SetElement(i, 0, normalizedX[i]);\n \tmatrix->SetElement(i, 1, normalizedY[i]);\n \tmatrix->SetElement(i, 2, normalizedZ[i]);\n }\n \n \/\/ Apply the transforms\n vtkSmartPointer transform =\n \tvtkSmartPointer::New();\n transform->Translate(startPoint); \/\/ translate to starting point\n transform->Concatenate(matrix); \/\/ apply direction cosines\n transform->RotateZ(-90.0); \/\/ align cylinder to x axis\n transform->Scale(1.0, length, 1.0); \/\/ scale along the height vector\n transform->Translate(0, .5, 0); \/\/ translate to start of cylinder\n \n \t\t\t\t\t\t\t\t\t\/\/ Transform the polydata\n vtkSmartPointer transformPD =\n \tvtkSmartPointer::New();\n transformPD->SetTransform(transform);\n transformPD->SetInputConnection(cylinderSource->GetOutputPort());\n \n \/\/Create a mapper and actor for the cylinder\n vtkSmartPointer mapper =\n \tvtkSmartPointer::New();\n vtkSmartPointer actor =\n \tvtkSmartPointer::New();\n#ifdef USER_MATRIX\n mapper->SetInputConnection(cylinderSource->GetOutputPort());\n actor->SetUserMatrix(transform->GetMatrix());\n#else\n mapper->SetInputConnection(transformPD->GetOutputPort());\n#endif\n actor->SetMapper(mapper);\n actor->GetProperty()->SetColor(colors->GetColor3d(\"Cyan\").GetData());\n \n \/\/ Create spheres for start and end point\n vtkSmartPointer sphereStartSource =\n \tvtkSmartPointer::New();\n sphereStartSource->SetCenter(startPoint);\n sphereStartSource->SetRadius(0.8);\n vtkSmartPointer sphereStartMapper =\n \tvtkSmartPointer::New();\n sphereStartMapper->SetInputConnection(sphereStartSource->GetOutputPort());\n vtkSmartPointer sphereStart =\n \tvtkSmartPointer::New();\n sphereStart->SetMapper(sphereStartMapper);\n sphereStart->GetProperty()->SetColor(colors->GetColor3d(\"Yellow\").GetData());\n \n vtkSmartPointer sphereEndSource =\n \tvtkSmartPointer::New();\n sphereEndSource->SetCenter(endPoint);\n sphereEndSource->SetRadius(0.8);\n vtkSmartPointer sphereEndMapper =\n \tvtkSmartPointer::New();\n sphereEndMapper->SetInputConnection(sphereEndSource->GetOutputPort());\n vtkSmartPointer sphereEnd =\n \tvtkSmartPointer::New();\n sphereEnd->SetMapper(sphereEndMapper);\n sphereEnd->GetProperty()->SetColor(colors->GetColor3d(\"Magenta\").GetData());\n \n \/\/Create a renderer, render window, and interactor\n vtkSmartPointer renderer =\n \tvtkSmartPointer::New();\n vtkSmartPointer renderWindow =\n \tvtkSmartPointer::New();\n renderWindow->AddRenderer(renderer);\n vtkSmartPointer renderWindowInteractor =\n \tvtkSmartPointer::New();\n renderWindowInteractor->SetRenderWindow(renderWindow);\n \n \/\/Add the actor to the scene\n renderer->AddActor(actor);\n renderer->AddActor(sphereStart);\n renderer->AddActor(sphereEnd);\n renderer->SetBackground(colors->GetColor3d(\"BkgColor\").GetData());\n \n \/\/Render and interact\n renderWindow->Render();\n renderWindowInteractor->Start();\n \n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ AliFemtoModelCorrFctn3DSpherical: a class to calculate 3D correlation \/\/\n\/\/ for pairs of identical particles, binned in spherical coordinates. \/\/\n\/\/ In analysis the function should be first created in a macro, then \/\/\n\/\/ added to the analysis, and at the end of the macro the procedure to \/\/\n\/\/ write out histograms should be called. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"AliFemtoModelCorrFctn3DSpherical.h\"\n#include \"AliFemtoModelManager.h\"\n#include \n#include \n\n#ifdef __ROOT__ \nClassImp(AliFemtoModelCorrFctn3DSpherical)\n#endif\n\n\/\/____________________________\nAliFemtoModelCorrFctn3DSpherical::AliFemtoModelCorrFctn3DSpherical(char* title, const int& nqbins, const float& QLo, const float& QHi, const int& nphibins, const int& ncthetabins):\n AliFemtoModelCorrFctn(),\n fTrueNumeratorSph(0),\n fFakeNumeratorSph(0),\n fDenominatorSph(0),\n fPairCut(0x0)\n{\n \/\/ set up numerator\n char tTitNum[100] = \"NumTrue\";\n strcat(tTitNum,title);\n fTrueNumeratorSph = new TH3D(tTitNum,title,nqbins,QLo,QHi,nphibins,-TMath::Pi(),TMath::Pi(),ncthetabins,-1.0,1.0);\n \/\/ set up numerator\n char tTitNumF[100] = \"NumFake\";\n strcat(tTitNumF,title);\n fFakeNumeratorSph = new TH3D(tTitNumF,title,nqbins,QLo,QHi,nphibins,-TMath::Pi(),TMath::Pi(),ncthetabins,-1.0,1.0);\n \/\/ set up denominator\n char tTitDen[100] = \"Den\";\n strcat(tTitDen,title);\n fDenominatorSph = new TH3D(tTitDen,title,nqbins,QLo,QHi,nphibins,-TMath::Pi(),TMath::Pi(),ncthetabins,-1.0,1.0);\n\n \/\/ to enable error bar calculation...\n fTrueNumeratorSph->Sumw2();\n fFakeNumeratorSph->Sumw2();\n fDenominatorSph->Sumw2();\n}\n\nAliFemtoModelCorrFctn3DSpherical::AliFemtoModelCorrFctn3DSpherical(const AliFemtoModelCorrFctn3DSpherical& aCorrFctn) :\n AliFemtoModelCorrFctn(aCorrFctn),\n fTrueNumeratorSph(0),\n fFakeNumeratorSph(0),\n fDenominatorSph(0),\n fPairCut(0x0)\n{\n \/\/ Copy constructor\n fTrueNumeratorSph = new TH3D(*aCorrFctn.fTrueNumeratorSph);\n fFakeNumeratorSph = new TH3D(*aCorrFctn.fFakeNumeratorSph);\n fDenominatorSph = new TH3D(*aCorrFctn.fDenominatorSph);\n fPairCut = aCorrFctn.fPairCut;\n}\n\/\/____________________________\nAliFemtoModelCorrFctn3DSpherical::~AliFemtoModelCorrFctn3DSpherical(){\n \/\/ Destructor\n delete fTrueNumeratorSph;\n delete fFakeNumeratorSph;\n delete fDenominatorSph;\n}\n\/\/_________________________\nAliFemtoModelCorrFctn3DSpherical& AliFemtoModelCorrFctn3DSpherical::operator=(const AliFemtoModelCorrFctn3DSpherical& aCorrFctn)\n{\n \/\/ assignment operator\n if (this == &aCorrFctn)\n return *this;\n\n if (fTrueNumeratorSph) delete fTrueNumeratorSph;\n fTrueNumeratorSph = new TH3D(*aCorrFctn.fTrueNumeratorSph);\n if (fFakeNumeratorSph) delete fFakeNumeratorSph;\n fFakeNumeratorSph = new TH3D(*aCorrFctn.fFakeNumeratorSph);\n if (fDenominatorSph) delete fDenominatorSph;\n fDenominatorSph = new TH3D(*aCorrFctn.fDenominatorSph);\n \n fPairCut = aCorrFctn.fPairCut;\n \n return *this;\n}\n\n\/\/_________________________\nvoid AliFemtoModelCorrFctn3DSpherical::WriteOutHistos(){\n \/\/ Write out all histograms to file\n fTrueNumeratorSph->Write();\n fFakeNumeratorSph->Write();\n fDenominatorSph->Write();\n}\n\/\/______________________________\nTList* AliFemtoModelCorrFctn3DSpherical::GetOutputList()\n{\n \/\/ Prepare the list of objects to be written to the output\n TList *tOutputList = new TList();\n\n tOutputList->Add(fTrueNumeratorSph); \n tOutputList->Add(fFakeNumeratorSph); \n tOutputList->Add(fDenominatorSph); \n\n return tOutputList;\n}\n\n\/\/_________________________\nvoid AliFemtoModelCorrFctn3DSpherical::Finish(){\n \/\/ here is where we should normalize, fit, etc...\n}\n\n\/\/____________________________\nAliFemtoString AliFemtoModelCorrFctn3DSpherical::Report(){\n \/\/ Construct the report\n string stemp = \"PRF Frame Spherical 3D Model Correlation Function Report:\\n\";\n char ctemp[100];\n sprintf(ctemp,\"Number of entries in numerator:\\t%E\\n\",fTrueNumeratorSph->GetEntries());\n stemp += ctemp;\n sprintf(ctemp,\"Number of entries in denominator:\\t%E\\n\",fDenominatorSph->GetEntries());\n stemp += ctemp;\n\n if (fPairCut){\n sprintf(ctemp,\"Here is the PairCut specific to this CorrFctn\\n\");\n stemp += ctemp;\n stemp += fPairCut->Report();\n }\n else{\n sprintf(ctemp,\"No PairCut specific to this CorrFctn\\n\");\n stemp += ctemp;\n }\n\n \/\/ \n AliFemtoString returnThis = stemp;\n return returnThis;\n}\n\/\/____________________________\nvoid AliFemtoModelCorrFctn3DSpherical::AddRealPair( AliFemtoPair* pair){\n \/\/ perform operations on real pairs\n if (fPairCut){\n if (!(fPairCut->Pass(pair))) return;\n }\n\n Double_t weight = fManager->GetWeight(pair);\n\n double tKO = pair->KOut();\n double tKS = pair->KSide();\n double tKL = pair->KLong();\n\n double tKR = sqrt(tKO*tKO + tKS*tKS + tKL*tKL);\n double tKC;\n if ( fabs(tKR) < 1e-10 ) tKC = 0.0;\n else tKC=tKL\/tKR;\n double tKP=atan2(tKS,tKO);\n\n fTrueNumeratorSph->Fill(tKR,tKP,tKC,weight);\n}\n\/\/____________________________\nvoid AliFemtoModelCorrFctn3DSpherical::AddMixedPair( AliFemtoPair* pair){\n \/\/ perform operations on mixed pairs\n if (fPairCut){\n if (!(fPairCut->Pass(pair))) return;\n }\n\n Double_t weight = fManager->GetWeight(pair);\n\n double tKO = pair->KOut();\n double tKS = pair->KSide();\n double tKL = pair->KLong();\n\n double tKR = sqrt(tKO*tKO + tKS*tKS + tKL*tKL);\n double tKC;\n if ( fabs(tKR) < 1e-10 ) tKC = 0.0;\n else tKC=tKL\/tKR;\n double tKP=atan2(tKS,tKO);\n\n fFakeNumeratorSph->Fill(tKR,tKP,tKC,weight);\n fDenominatorSph->Fill(tKR,tKP,tKC);\n}\n\n\nRemove dependence\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ AliFemtoModelCorrFctn3DSpherical: a class to calculate 3D correlation \/\/\n\/\/ for pairs of identical particles, binned in spherical coordinates. \/\/\n\/\/ In analysis the function should be first created in a macro, then \/\/\n\/\/ added to the analysis, and at the end of the macro the procedure to \/\/\n\/\/ write out histograms should be called. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"AliFemtoModelCorrFctn3DSpherical.h\"\n#include \"AliFemtoModelManager.h\"\n#include \n#include \n\/\/#include \n\n#ifdef __ROOT__ \nClassImp(AliFemtoModelCorrFctn3DSpherical)\n#endif\n\n\/\/____________________________\nAliFemtoModelCorrFctn3DSpherical::AliFemtoModelCorrFctn3DSpherical(char* title, const int& nqbins, const float& QLo, const float& QHi, const int& nphibins, const int& ncthetabins):\n AliFemtoModelCorrFctn(),\n fTrueNumeratorSph(0),\n fFakeNumeratorSph(0),\n fDenominatorSph(0),\n fPairCut(0x0)\n{\n \/\/ set up numerator\n char tTitNum[100] = \"NumTrue\";\n strcat(tTitNum,title);\n fTrueNumeratorSph = new TH3D(tTitNum,title,nqbins,QLo,QHi,nphibins,-TMath::Pi(),TMath::Pi(),ncthetabins,-1.0,1.0);\n \/\/ set up numerator\n char tTitNumF[100] = \"NumFake\";\n strcat(tTitNumF,title);\n fFakeNumeratorSph = new TH3D(tTitNumF,title,nqbins,QLo,QHi,nphibins,-TMath::Pi(),TMath::Pi(),ncthetabins,-1.0,1.0);\n \/\/ set up denominator\n char tTitDen[100] = \"Den\";\n strcat(tTitDen,title);\n fDenominatorSph = new TH3D(tTitDen,title,nqbins,QLo,QHi,nphibins,-TMath::Pi(),TMath::Pi(),ncthetabins,-1.0,1.0);\n\n \/\/ to enable error bar calculation...\n fTrueNumeratorSph->Sumw2();\n fFakeNumeratorSph->Sumw2();\n fDenominatorSph->Sumw2();\n}\n\nAliFemtoModelCorrFctn3DSpherical::AliFemtoModelCorrFctn3DSpherical(const AliFemtoModelCorrFctn3DSpherical& aCorrFctn) :\n AliFemtoModelCorrFctn(aCorrFctn),\n fTrueNumeratorSph(0),\n fFakeNumeratorSph(0),\n fDenominatorSph(0),\n fPairCut(0x0)\n{\n \/\/ Copy constructor\n fTrueNumeratorSph = new TH3D(*aCorrFctn.fTrueNumeratorSph);\n fFakeNumeratorSph = new TH3D(*aCorrFctn.fFakeNumeratorSph);\n fDenominatorSph = new TH3D(*aCorrFctn.fDenominatorSph);\n fPairCut = aCorrFctn.fPairCut;\n}\n\/\/____________________________\nAliFemtoModelCorrFctn3DSpherical::~AliFemtoModelCorrFctn3DSpherical(){\n \/\/ Destructor\n delete fTrueNumeratorSph;\n delete fFakeNumeratorSph;\n delete fDenominatorSph;\n}\n\/\/_________________________\nAliFemtoModelCorrFctn3DSpherical& AliFemtoModelCorrFctn3DSpherical::operator=(const AliFemtoModelCorrFctn3DSpherical& aCorrFctn)\n{\n \/\/ assignment operator\n if (this == &aCorrFctn)\n return *this;\n\n if (fTrueNumeratorSph) delete fTrueNumeratorSph;\n fTrueNumeratorSph = new TH3D(*aCorrFctn.fTrueNumeratorSph);\n if (fFakeNumeratorSph) delete fFakeNumeratorSph;\n fFakeNumeratorSph = new TH3D(*aCorrFctn.fFakeNumeratorSph);\n if (fDenominatorSph) delete fDenominatorSph;\n fDenominatorSph = new TH3D(*aCorrFctn.fDenominatorSph);\n \n fPairCut = aCorrFctn.fPairCut;\n \n return *this;\n}\n\n\/\/_________________________\nvoid AliFemtoModelCorrFctn3DSpherical::WriteOutHistos(){\n \/\/ Write out all histograms to file\n fTrueNumeratorSph->Write();\n fFakeNumeratorSph->Write();\n fDenominatorSph->Write();\n}\n\/\/______________________________\nTList* AliFemtoModelCorrFctn3DSpherical::GetOutputList()\n{\n \/\/ Prepare the list of objects to be written to the output\n TList *tOutputList = new TList();\n\n tOutputList->Add(fTrueNumeratorSph); \n tOutputList->Add(fFakeNumeratorSph); \n tOutputList->Add(fDenominatorSph); \n\n return tOutputList;\n}\n\n\/\/_________________________\nvoid AliFemtoModelCorrFctn3DSpherical::Finish(){\n \/\/ here is where we should normalize, fit, etc...\n}\n\n\/\/____________________________\nAliFemtoString AliFemtoModelCorrFctn3DSpherical::Report(){\n \/\/ Construct the report\n string stemp = \"PRF Frame Spherical 3D Model Correlation Function Report:\\n\";\n char ctemp[100];\n sprintf(ctemp,\"Number of entries in numerator:\\t%E\\n\",fTrueNumeratorSph->GetEntries());\n stemp += ctemp;\n sprintf(ctemp,\"Number of entries in denominator:\\t%E\\n\",fDenominatorSph->GetEntries());\n stemp += ctemp;\n\n if (fPairCut){\n sprintf(ctemp,\"Here is the PairCut specific to this CorrFctn\\n\");\n stemp += ctemp;\n stemp += fPairCut->Report();\n }\n else{\n sprintf(ctemp,\"No PairCut specific to this CorrFctn\\n\");\n stemp += ctemp;\n }\n\n \/\/ \n AliFemtoString returnThis = stemp;\n return returnThis;\n}\n\/\/____________________________\nvoid AliFemtoModelCorrFctn3DSpherical::AddRealPair( AliFemtoPair* pair){\n \/\/ perform operations on real pairs\n if (fPairCut){\n if (!(fPairCut->Pass(pair))) return;\n }\n\n Double_t weight = fManager->GetWeight(pair);\n\n double tKO = pair->KOut();\n double tKS = pair->KSide();\n double tKL = pair->KLong();\n\n double tKR = sqrt(tKO*tKO + tKS*tKS + tKL*tKL);\n double tKC;\n if ( fabs(tKR) < 1e-10 ) tKC = 0.0;\n else tKC=tKL\/tKR;\n double tKP=atan2(tKS,tKO);\n\n fTrueNumeratorSph->Fill(tKR,tKP,tKC,weight);\n}\n\/\/____________________________\nvoid AliFemtoModelCorrFctn3DSpherical::AddMixedPair( AliFemtoPair* pair){\n \/\/ perform operations on mixed pairs\n if (fPairCut){\n if (!(fPairCut->Pass(pair))) return;\n }\n\n Double_t weight = fManager->GetWeight(pair);\n\n double tKO = pair->KOut();\n double tKS = pair->KSide();\n double tKL = pair->KLong();\n\n double tKR = sqrt(tKO*tKO + tKS*tKS + tKL*tKL);\n double tKC;\n if ( fabs(tKR) < 1e-10 ) tKC = 0.0;\n else tKC=tKL\/tKR;\n double tKP=atan2(tKS,tKO);\n\n fFakeNumeratorSph->Fill(tKR,tKP,tKC,weight);\n fDenominatorSph->Fill(tKR,tKP,tKC);\n}\n\n\n<|endoftext|>"} {"text":"\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/log.h\"\n#include \"kernel\/register.h\"\n#include \"kernel\/sigtools.h\"\n#include \"kernel\/consteval.h\"\n#include \"kernel\/celltypes.h\"\n#include \"fsmdata.h\"\n#include \n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nstruct FsmOpt\n{\n\tFsmData fsm_data;\n\tRTLIL::Cell *cell;\n\tRTLIL::Module *module;\n\n\tvoid opt_unreachable_states()\n\t{\n\t\twhile (1)\n\t\t{\n\t\t\tstd::set unreachable_states;\n\t\t\tstd::vector new_transition_table;\n\t\t\tstd::vector new_state_table;\n\t\t\tstd::map old_to_new_state;\n\n\t\t\tfor (int i = 0; i < GetSize(fsm_data.state_table); i++)\n\t\t\t\tif (i != fsm_data.reset_state)\n\t\t\t\t\tunreachable_states.insert(i);\n\n\t\t\tfor (auto &trans : fsm_data.transition_table)\n\t\t\t\tunreachable_states.erase(trans.state_out);\n\n\t\t\tif (unreachable_states.empty())\n\t\t\t\tbreak;\n\n\t\t\tfor (int i = 0; i < GetSize(fsm_data.state_table); i++) {\n\t\t\t\tif (unreachable_states.count(i)) {\n\t\t\t\t\tlog(\" Removing unreachable state %s.\\n\", log_signal(fsm_data.state_table[i]));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\told_to_new_state[i] = GetSize(new_state_table);\n\t\t\t\tnew_state_table.push_back(fsm_data.state_table[i]);\n\t\t\t}\n\n\t\t\tfor (auto trans : fsm_data.transition_table) {\n\t\t\t\tif (unreachable_states.count(trans.state_in))\n\t\t\t\t\tcontinue;\n\t\t\t\ttrans.state_in = old_to_new_state.at(trans.state_in);\n\t\t\t\ttrans.state_out = old_to_new_state.at(trans.state_out);\n\t\t\t\tnew_transition_table.push_back(trans);\n\t\t\t}\n\n\t\t\tnew_transition_table.swap(fsm_data.transition_table);\n\t\t\tnew_state_table.swap(fsm_data.state_table);\n\t\t\tfsm_data.reset_state = old_to_new_state.at(fsm_data.reset_state);\n\t\t}\n\t}\n\n\tbool signal_is_unused(RTLIL::SigSpec sig)\n\t{\n\t\tRTLIL::SigBit bit = sig.as_bit();\n\n\t\tif (bit.wire == NULL || bit.wire->attributes.count(\"\\\\unused_bits\") == 0)\n\t\t\treturn false;\n\n\t\tchar *str = strdup(bit.wire->attributes[\"\\\\unused_bits\"].decode_string().c_str());\n\t\tfor (char *tok = strtok(str, \" \"); tok != NULL; tok = strtok(NULL, \" \")) {\n\t\t\tif (tok[0] && bit.offset == atoi(tok)) {\n\t\t\t\tfree(str);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\tfree(str);\n\n\t\treturn false;\n\t}\n\n\tvoid opt_const_and_unused_inputs()\n\t{\n\t\tRTLIL::SigSpec ctrl_in = cell->getPort(\"\\\\CTRL_IN\");\n\t\tstd::vector ctrl_in_used(ctrl_in.size());\n\n\t\tstd::vector new_transition_table;\n\t\tfor (auto &tr : fsm_data.transition_table) {\n\t\t\tfor (int i = 0; i < ctrl_in.size(); i++) {\n\t\t\t\tRTLIL::SigSpec ctrl_bit = ctrl_in.extract(i, 1);\n\t\t\t\tif (ctrl_bit.is_fully_const()) {\n\t\t\t\t\tif (tr.ctrl_in.bits[i] <= RTLIL::State::S1 && RTLIL::SigSpec(tr.ctrl_in.bits[i]) != ctrl_bit)\n\t\t\t\t\t\tgoto delete_this_transition;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (tr.ctrl_in.bits[i] <= RTLIL::State::S1)\n\t\t\t\t\tctrl_in_used[i] = true;\n\t\t\t}\n\t\t\tnew_transition_table.push_back(tr);\n\t\tdelete_this_transition:;\n\t\t}\n\n\t\tfor (int i = int(ctrl_in_used.size())-1; i >= 0; i--) {\n\t\t\tif (!ctrl_in_used[i]) {\n\t\t\t\tlog(\" Removing unused input signal %s.\\n\", log_signal(cell->getPort(\"\\\\CTRL_IN\").extract(i, 1)));\n\t\t\t\tfor (auto &tr : new_transition_table) {\n\t\t\t\t\tRTLIL::SigSpec tmp(tr.ctrl_in);\n\t\t\t\t\ttmp.remove(i, 1);\n\t\t\t\t\ttr.ctrl_in = tmp.as_const();\n\t\t\t\t}\n\t\t\t\tRTLIL::SigSpec new_ctrl_in = cell->getPort(\"\\\\CTRL_IN\");\n\t\t\t\tnew_ctrl_in.remove(i, 1);\n\t\t\t\tcell->setPort(\"\\\\CTRL_IN\", new_ctrl_in);\n\t\t\t\tfsm_data.num_inputs--;\n\t\t\t}\n\t\t}\n\n\t\tfsm_data.transition_table.swap(new_transition_table);\n\t\tnew_transition_table.clear();\n\t}\n\n\tvoid opt_unused_outputs()\n\t{\n\t\tfor (int i = 0; i < fsm_data.num_outputs; i++) {\n\t\t\tRTLIL::SigSpec sig = cell->getPort(\"\\\\CTRL_OUT\").extract(i, 1);\n\t\t\tif (signal_is_unused(sig)) {\n\t\t\t\tlog(\" Removing unused output signal %s.\\n\", log_signal(sig));\n\t\t\t\tRTLIL::SigSpec new_ctrl_out = cell->getPort(\"\\\\CTRL_OUT\");\n\t\t\t\tnew_ctrl_out.remove(i, 1);\n\t\t\t\tcell->setPort(\"\\\\CTRL_OUT\", new_ctrl_out);\n\t\t\t\tfor (auto &tr : fsm_data.transition_table) {\n\t\t\t\t\tRTLIL::SigSpec tmp(tr.ctrl_out);\n\t\t\t\t\ttmp.remove(i, 1);\n\t\t\t\t\ttr.ctrl_out = tmp.as_const();\n\t\t\t\t}\n\t\t\t\tfsm_data.num_outputs--;\n\t\t\t\ti--;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid opt_alias_inputs()\n\t{\n\t\tRTLIL::SigSpec &ctrl_in = cell->connections_[\"\\\\CTRL_IN\"];\n\n\t\tfor (int i = 0; i < ctrl_in.size(); i++)\n\t\tfor (int j = i+1; j < ctrl_in.size(); j++)\n\t\t\tif (ctrl_in.extract(i, 1) == ctrl_in.extract(j, 1))\n\t\t\t{\n\t\t\t\tlog(\" Optimize handling of signal %s that is connected to inputs %d and %d.\\n\", log_signal(ctrl_in.extract(i, 1)), i, j);\n\t\t\t\tstd::vector new_transition_table;\n\n\t\t\t\tfor (auto tr : fsm_data.transition_table)\n\t\t\t\t{\n\t\t\t\t\tRTLIL::State &si = tr.ctrl_in.bits[i];\n\t\t\t\t\tRTLIL::State &sj = tr.ctrl_in.bits[j];\n\n\t\t\t\t\tif (si > RTLIL::State::S1)\n\t\t\t\t\t\tsi = sj;\n\t\t\t\t\telse if (sj > RTLIL::State::S1)\n\t\t\t\t\t\tsj = si;\n\n\t\t\t\t\tif (si == sj) {\n\t\t\t\t\t\tRTLIL::SigSpec tmp(tr.ctrl_in);\n\t\t\t\t\t\ttmp.remove(j, 1);\n\t\t\t\t\t\ttr.ctrl_in = tmp.as_const();\n\t\t\t\t\t\tnew_transition_table.push_back(tr);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tctrl_in.remove(j--, 1);\n\t\t\t\tfsm_data.num_inputs--;\n\n\t\t\t\tfsm_data.transition_table.swap(new_transition_table);\n\t\t\t\tnew_transition_table.clear();\n\t\t\t}\n\t}\n\n\tvoid opt_feedback_inputs()\n\t{\n\t\tRTLIL::SigSpec &ctrl_in = cell->connections_[\"\\\\CTRL_IN\"];\n\t\tRTLIL::SigSpec &ctrl_out = cell->connections_[\"\\\\CTRL_OUT\"];\n\n\t\tfor (int j = 0; j < ctrl_out.size(); j++)\n\t\tfor (int i = 0; i < ctrl_in.size(); i++)\n\t\t\tif (ctrl_in.extract(i, 1) == ctrl_out.extract(j, 1))\n\t\t\t{\n\t\t\t\tlog(\" Optimize handling of signal %s that is connected to input %d and output %d.\\n\", log_signal(ctrl_in.extract(i, 1)), i, j);\n\t\t\t\tstd::vector new_transition_table;\n\n\t\t\t\tfor (auto tr : fsm_data.transition_table)\n\t\t\t\t{\n\t\t\t\t\tRTLIL::State &si = tr.ctrl_in.bits[i];\n\t\t\t\t\tRTLIL::State &sj = tr.ctrl_out.bits[j];\n\n\t\t\t\t\tif (si > RTLIL::State::S1 || si == sj) {\n\t\t\t\t\t\tRTLIL::SigSpec tmp(tr.ctrl_in);\n\t\t\t\t\t\ttmp.remove(i, 1);\n\t\t\t\t\t\ttr.ctrl_in = tmp.as_const();\n\t\t\t\t\t\tnew_transition_table.push_back(tr);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tctrl_in.remove(i--, 1);\n\t\t\t\tfsm_data.num_inputs--;\n\n\t\t\t\tfsm_data.transition_table.swap(new_transition_table);\n\t\t\t\tnew_transition_table.clear();\n\t\t\t}\n\t}\n\n\tvoid opt_find_dont_care_worker(std::set &set, int bit, FsmData::transition_t &tr, bool &did_something)\n\t{\n\t\tstd::set new_set;\n\n\t\tfor (auto &pattern : set)\n\t\t{\n\t\t\tif (pattern.bits[bit] > RTLIL::State::S1) {\n\t\t\t\tnew_set.insert(pattern);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tRTLIL::Const other_pattern = pattern;\n\n\t\t\tif (pattern.bits[bit] == RTLIL::State::S1)\n\t\t\t\tother_pattern.bits[bit] = RTLIL::State::S0;\n\t\t\telse\n\t\t\t\tother_pattern.bits[bit] = RTLIL::State::S1;\n\n\t\t\tif (set.count(other_pattern) > 0) {\n\t\t\t\tlog(\" Merging pattern %s and %s from group (%d %d %s).\\n\", log_signal(pattern), log_signal(other_pattern),\n\t\t\t\t\t\ttr.state_in, tr.state_out, log_signal(tr.ctrl_out));\n\t\t\t\tother_pattern.bits[bit] = RTLIL::State::Sa;\n\t\t\t\tnew_set.insert(other_pattern);\n\t\t\t\tdid_something = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnew_set.insert(pattern);\n\t\t}\n\n\t\tset.swap(new_set);\n\t}\n\n\tvoid opt_find_dont_care()\n\t{\n\t\ttypedef std::pair, RTLIL::Const> group_t;\n\t\tstd::map> transitions_by_group;\n\n\t\tfor (auto &tr : fsm_data.transition_table) {\n\t\t\tgroup_t group(std::pair(tr.state_in, tr.state_out), tr.ctrl_out);\n\t\t\ttransitions_by_group[group].insert(tr.ctrl_in);\n\t\t}\n\n\t\tfsm_data.transition_table.clear();\n\t\tfor (auto &it : transitions_by_group)\n\t\t{\n\t\t\tFsmData::transition_t tr;\n\t\t\ttr.state_in = it.first.first.first;\n\t\t\ttr.state_out = it.first.first.second;\n\t\t\ttr.ctrl_out = it.first.second;\n\n\t\t\tbool did_something = true;\n\t\t\twhile (did_something) {\n\t\t\t\tdid_something = false;\n\t\t\t\tfor (int i = 0; i < fsm_data.num_inputs; i++)\n\t\t\t\t\topt_find_dont_care_worker(it.second, i, tr, did_something);\n\t\t\t}\n\n\t\t\tfor (auto &ci : it.second) {\n\t\t\t\ttr.ctrl_in = ci;\n\t\t\t\tfsm_data.transition_table.push_back(tr);\n\t\t\t}\n\t\t}\n\t}\n\n\tFsmOpt(RTLIL::Cell *cell, RTLIL::Module *module)\n\t{\n\t\tlog(\"Optimizing FSM `%s' from module `%s'.\\n\", cell->name.c_str(), module->name.c_str());\n\n\t\tfsm_data.copy_from_cell(cell);\n\t\tthis->cell = cell;\n\t\tthis->module = module;\n\n\t\topt_unreachable_states();\n\n\t\topt_unused_outputs();\n\n\t\topt_alias_inputs();\n\t\topt_feedback_inputs();\n\t\topt_find_dont_care();\n\n\t\topt_const_and_unused_inputs();\n\n\t\tfsm_data.copy_to_cell(cell);\n\t}\n};\n\nPRIVATE_NAMESPACE_END\n\nvoid YOSYS_NAMESPACE_PREFIX FsmData::optimize_fsm(RTLIL::Cell *cell, RTLIL::Module *module)\n{\n\tFsmOpt fsmopt(cell, module);\n}\n\nPRIVATE_NAMESPACE_BEGIN\n\nstruct FsmOptPass : public Pass {\n\tFsmOptPass() : Pass(\"fsm_opt\", \"optimize finite state machines\") { }\n\tvoid help() YS_OVERRIDE\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" fsm_opt [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This pass optimizes FSM cells. It detects which output signals are actually\\n\");\n\t\tlog(\"not used and removes them from the FSM. This pass is usually used in\\n\");\n\t\tlog(\"combination with the 'opt_clean' pass (see also 'help fsm').\\n\");\n\t\tlog(\"\\n\");\n\t}\n\tvoid execute(std::vector args, RTLIL::Design *design) YS_OVERRIDE\n\t{\n\t\tlog_header(design, \"Executing FSM_OPT pass (simple optimizations of FSMs).\\n\");\n\t\textra_args(args, 1, design);\n\n\t\tfor (auto &mod_it : design->modules_) {\n\t\t\tif (design->selected(mod_it.second))\n\t\t\t\tfor (auto &cell_it : mod_it.second->cells_)\n\t\t\t\t\tif (cell_it.second->type == \"$fsm\" && design->selected(mod_it.second, cell_it.second))\n\t\t\t\t\t\tFsmData::optimize_fsm(cell_it.second, mod_it.second);\n\t\t}\n\t}\n} FsmOptPass;\n\nPRIVATE_NAMESPACE_END\nfsm_opt: Fix runtime error for FSMs without a reset state\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/log.h\"\n#include \"kernel\/register.h\"\n#include \"kernel\/sigtools.h\"\n#include \"kernel\/consteval.h\"\n#include \"kernel\/celltypes.h\"\n#include \"fsmdata.h\"\n#include \n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nstruct FsmOpt\n{\n\tFsmData fsm_data;\n\tRTLIL::Cell *cell;\n\tRTLIL::Module *module;\n\n\tvoid opt_unreachable_states()\n\t{\n\t\twhile (1)\n\t\t{\n\t\t\tstd::set unreachable_states;\n\t\t\tstd::vector new_transition_table;\n\t\t\tstd::vector new_state_table;\n\t\t\tstd::map old_to_new_state;\n\n\t\t\tfor (int i = 0; i < GetSize(fsm_data.state_table); i++)\n\t\t\t\tif (i != fsm_data.reset_state)\n\t\t\t\t\tunreachable_states.insert(i);\n\n\t\t\tfor (auto &trans : fsm_data.transition_table)\n\t\t\t\tunreachable_states.erase(trans.state_out);\n\n\t\t\tif (unreachable_states.empty())\n\t\t\t\tbreak;\n\n\t\t\tfor (int i = 0; i < GetSize(fsm_data.state_table); i++) {\n\t\t\t\tif (unreachable_states.count(i)) {\n\t\t\t\t\tlog(\" Removing unreachable state %s.\\n\", log_signal(fsm_data.state_table[i]));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\told_to_new_state[i] = GetSize(new_state_table);\n\t\t\t\tnew_state_table.push_back(fsm_data.state_table[i]);\n\t\t\t}\n\n\t\t\tfor (auto trans : fsm_data.transition_table) {\n\t\t\t\tif (unreachable_states.count(trans.state_in))\n\t\t\t\t\tcontinue;\n\t\t\t\ttrans.state_in = old_to_new_state.at(trans.state_in);\n\t\t\t\ttrans.state_out = old_to_new_state.at(trans.state_out);\n\t\t\t\tnew_transition_table.push_back(trans);\n\t\t\t}\n\n\t\t\tnew_transition_table.swap(fsm_data.transition_table);\n\t\t\tnew_state_table.swap(fsm_data.state_table);\n\t\t\tif (fsm_data.reset_state != -1)\n\t\t\t\tfsm_data.reset_state = old_to_new_state.at(fsm_data.reset_state);\n\t\t}\n\t}\n\n\tbool signal_is_unused(RTLIL::SigSpec sig)\n\t{\n\t\tRTLIL::SigBit bit = sig.as_bit();\n\n\t\tif (bit.wire == NULL || bit.wire->attributes.count(\"\\\\unused_bits\") == 0)\n\t\t\treturn false;\n\n\t\tchar *str = strdup(bit.wire->attributes[\"\\\\unused_bits\"].decode_string().c_str());\n\t\tfor (char *tok = strtok(str, \" \"); tok != NULL; tok = strtok(NULL, \" \")) {\n\t\t\tif (tok[0] && bit.offset == atoi(tok)) {\n\t\t\t\tfree(str);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\tfree(str);\n\n\t\treturn false;\n\t}\n\n\tvoid opt_const_and_unused_inputs()\n\t{\n\t\tRTLIL::SigSpec ctrl_in = cell->getPort(\"\\\\CTRL_IN\");\n\t\tstd::vector ctrl_in_used(ctrl_in.size());\n\n\t\tstd::vector new_transition_table;\n\t\tfor (auto &tr : fsm_data.transition_table) {\n\t\t\tfor (int i = 0; i < ctrl_in.size(); i++) {\n\t\t\t\tRTLIL::SigSpec ctrl_bit = ctrl_in.extract(i, 1);\n\t\t\t\tif (ctrl_bit.is_fully_const()) {\n\t\t\t\t\tif (tr.ctrl_in.bits[i] <= RTLIL::State::S1 && RTLIL::SigSpec(tr.ctrl_in.bits[i]) != ctrl_bit)\n\t\t\t\t\t\tgoto delete_this_transition;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (tr.ctrl_in.bits[i] <= RTLIL::State::S1)\n\t\t\t\t\tctrl_in_used[i] = true;\n\t\t\t}\n\t\t\tnew_transition_table.push_back(tr);\n\t\tdelete_this_transition:;\n\t\t}\n\n\t\tfor (int i = int(ctrl_in_used.size())-1; i >= 0; i--) {\n\t\t\tif (!ctrl_in_used[i]) {\n\t\t\t\tlog(\" Removing unused input signal %s.\\n\", log_signal(cell->getPort(\"\\\\CTRL_IN\").extract(i, 1)));\n\t\t\t\tfor (auto &tr : new_transition_table) {\n\t\t\t\t\tRTLIL::SigSpec tmp(tr.ctrl_in);\n\t\t\t\t\ttmp.remove(i, 1);\n\t\t\t\t\ttr.ctrl_in = tmp.as_const();\n\t\t\t\t}\n\t\t\t\tRTLIL::SigSpec new_ctrl_in = cell->getPort(\"\\\\CTRL_IN\");\n\t\t\t\tnew_ctrl_in.remove(i, 1);\n\t\t\t\tcell->setPort(\"\\\\CTRL_IN\", new_ctrl_in);\n\t\t\t\tfsm_data.num_inputs--;\n\t\t\t}\n\t\t}\n\n\t\tfsm_data.transition_table.swap(new_transition_table);\n\t\tnew_transition_table.clear();\n\t}\n\n\tvoid opt_unused_outputs()\n\t{\n\t\tfor (int i = 0; i < fsm_data.num_outputs; i++) {\n\t\t\tRTLIL::SigSpec sig = cell->getPort(\"\\\\CTRL_OUT\").extract(i, 1);\n\t\t\tif (signal_is_unused(sig)) {\n\t\t\t\tlog(\" Removing unused output signal %s.\\n\", log_signal(sig));\n\t\t\t\tRTLIL::SigSpec new_ctrl_out = cell->getPort(\"\\\\CTRL_OUT\");\n\t\t\t\tnew_ctrl_out.remove(i, 1);\n\t\t\t\tcell->setPort(\"\\\\CTRL_OUT\", new_ctrl_out);\n\t\t\t\tfor (auto &tr : fsm_data.transition_table) {\n\t\t\t\t\tRTLIL::SigSpec tmp(tr.ctrl_out);\n\t\t\t\t\ttmp.remove(i, 1);\n\t\t\t\t\ttr.ctrl_out = tmp.as_const();\n\t\t\t\t}\n\t\t\t\tfsm_data.num_outputs--;\n\t\t\t\ti--;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid opt_alias_inputs()\n\t{\n\t\tRTLIL::SigSpec &ctrl_in = cell->connections_[\"\\\\CTRL_IN\"];\n\n\t\tfor (int i = 0; i < ctrl_in.size(); i++)\n\t\tfor (int j = i+1; j < ctrl_in.size(); j++)\n\t\t\tif (ctrl_in.extract(i, 1) == ctrl_in.extract(j, 1))\n\t\t\t{\n\t\t\t\tlog(\" Optimize handling of signal %s that is connected to inputs %d and %d.\\n\", log_signal(ctrl_in.extract(i, 1)), i, j);\n\t\t\t\tstd::vector new_transition_table;\n\n\t\t\t\tfor (auto tr : fsm_data.transition_table)\n\t\t\t\t{\n\t\t\t\t\tRTLIL::State &si = tr.ctrl_in.bits[i];\n\t\t\t\t\tRTLIL::State &sj = tr.ctrl_in.bits[j];\n\n\t\t\t\t\tif (si > RTLIL::State::S1)\n\t\t\t\t\t\tsi = sj;\n\t\t\t\t\telse if (sj > RTLIL::State::S1)\n\t\t\t\t\t\tsj = si;\n\n\t\t\t\t\tif (si == sj) {\n\t\t\t\t\t\tRTLIL::SigSpec tmp(tr.ctrl_in);\n\t\t\t\t\t\ttmp.remove(j, 1);\n\t\t\t\t\t\ttr.ctrl_in = tmp.as_const();\n\t\t\t\t\t\tnew_transition_table.push_back(tr);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tctrl_in.remove(j--, 1);\n\t\t\t\tfsm_data.num_inputs--;\n\n\t\t\t\tfsm_data.transition_table.swap(new_transition_table);\n\t\t\t\tnew_transition_table.clear();\n\t\t\t}\n\t}\n\n\tvoid opt_feedback_inputs()\n\t{\n\t\tRTLIL::SigSpec &ctrl_in = cell->connections_[\"\\\\CTRL_IN\"];\n\t\tRTLIL::SigSpec &ctrl_out = cell->connections_[\"\\\\CTRL_OUT\"];\n\n\t\tfor (int j = 0; j < ctrl_out.size(); j++)\n\t\tfor (int i = 0; i < ctrl_in.size(); i++)\n\t\t\tif (ctrl_in.extract(i, 1) == ctrl_out.extract(j, 1))\n\t\t\t{\n\t\t\t\tlog(\" Optimize handling of signal %s that is connected to input %d and output %d.\\n\", log_signal(ctrl_in.extract(i, 1)), i, j);\n\t\t\t\tstd::vector new_transition_table;\n\n\t\t\t\tfor (auto tr : fsm_data.transition_table)\n\t\t\t\t{\n\t\t\t\t\tRTLIL::State &si = tr.ctrl_in.bits[i];\n\t\t\t\t\tRTLIL::State &sj = tr.ctrl_out.bits[j];\n\n\t\t\t\t\tif (si > RTLIL::State::S1 || si == sj) {\n\t\t\t\t\t\tRTLIL::SigSpec tmp(tr.ctrl_in);\n\t\t\t\t\t\ttmp.remove(i, 1);\n\t\t\t\t\t\ttr.ctrl_in = tmp.as_const();\n\t\t\t\t\t\tnew_transition_table.push_back(tr);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tctrl_in.remove(i--, 1);\n\t\t\t\tfsm_data.num_inputs--;\n\n\t\t\t\tfsm_data.transition_table.swap(new_transition_table);\n\t\t\t\tnew_transition_table.clear();\n\t\t\t}\n\t}\n\n\tvoid opt_find_dont_care_worker(std::set &set, int bit, FsmData::transition_t &tr, bool &did_something)\n\t{\n\t\tstd::set new_set;\n\n\t\tfor (auto &pattern : set)\n\t\t{\n\t\t\tif (pattern.bits[bit] > RTLIL::State::S1) {\n\t\t\t\tnew_set.insert(pattern);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tRTLIL::Const other_pattern = pattern;\n\n\t\t\tif (pattern.bits[bit] == RTLIL::State::S1)\n\t\t\t\tother_pattern.bits[bit] = RTLIL::State::S0;\n\t\t\telse\n\t\t\t\tother_pattern.bits[bit] = RTLIL::State::S1;\n\n\t\t\tif (set.count(other_pattern) > 0) {\n\t\t\t\tlog(\" Merging pattern %s and %s from group (%d %d %s).\\n\", log_signal(pattern), log_signal(other_pattern),\n\t\t\t\t\t\ttr.state_in, tr.state_out, log_signal(tr.ctrl_out));\n\t\t\t\tother_pattern.bits[bit] = RTLIL::State::Sa;\n\t\t\t\tnew_set.insert(other_pattern);\n\t\t\t\tdid_something = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnew_set.insert(pattern);\n\t\t}\n\n\t\tset.swap(new_set);\n\t}\n\n\tvoid opt_find_dont_care()\n\t{\n\t\ttypedef std::pair, RTLIL::Const> group_t;\n\t\tstd::map> transitions_by_group;\n\n\t\tfor (auto &tr : fsm_data.transition_table) {\n\t\t\tgroup_t group(std::pair(tr.state_in, tr.state_out), tr.ctrl_out);\n\t\t\ttransitions_by_group[group].insert(tr.ctrl_in);\n\t\t}\n\n\t\tfsm_data.transition_table.clear();\n\t\tfor (auto &it : transitions_by_group)\n\t\t{\n\t\t\tFsmData::transition_t tr;\n\t\t\ttr.state_in = it.first.first.first;\n\t\t\ttr.state_out = it.first.first.second;\n\t\t\ttr.ctrl_out = it.first.second;\n\n\t\t\tbool did_something = true;\n\t\t\twhile (did_something) {\n\t\t\t\tdid_something = false;\n\t\t\t\tfor (int i = 0; i < fsm_data.num_inputs; i++)\n\t\t\t\t\topt_find_dont_care_worker(it.second, i, tr, did_something);\n\t\t\t}\n\n\t\t\tfor (auto &ci : it.second) {\n\t\t\t\ttr.ctrl_in = ci;\n\t\t\t\tfsm_data.transition_table.push_back(tr);\n\t\t\t}\n\t\t}\n\t}\n\n\tFsmOpt(RTLIL::Cell *cell, RTLIL::Module *module)\n\t{\n\t\tlog(\"Optimizing FSM `%s' from module `%s'.\\n\", cell->name.c_str(), module->name.c_str());\n\n\t\tfsm_data.copy_from_cell(cell);\n\t\tthis->cell = cell;\n\t\tthis->module = module;\n\n\t\topt_unreachable_states();\n\n\t\topt_unused_outputs();\n\n\t\topt_alias_inputs();\n\t\topt_feedback_inputs();\n\t\topt_find_dont_care();\n\n\t\topt_const_and_unused_inputs();\n\n\t\tfsm_data.copy_to_cell(cell);\n\t}\n};\n\nPRIVATE_NAMESPACE_END\n\nvoid YOSYS_NAMESPACE_PREFIX FsmData::optimize_fsm(RTLIL::Cell *cell, RTLIL::Module *module)\n{\n\tFsmOpt fsmopt(cell, module);\n}\n\nPRIVATE_NAMESPACE_BEGIN\n\nstruct FsmOptPass : public Pass {\n\tFsmOptPass() : Pass(\"fsm_opt\", \"optimize finite state machines\") { }\n\tvoid help() YS_OVERRIDE\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" fsm_opt [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This pass optimizes FSM cells. It detects which output signals are actually\\n\");\n\t\tlog(\"not used and removes them from the FSM. This pass is usually used in\\n\");\n\t\tlog(\"combination with the 'opt_clean' pass (see also 'help fsm').\\n\");\n\t\tlog(\"\\n\");\n\t}\n\tvoid execute(std::vector args, RTLIL::Design *design) YS_OVERRIDE\n\t{\n\t\tlog_header(design, \"Executing FSM_OPT pass (simple optimizations of FSMs).\\n\");\n\t\textra_args(args, 1, design);\n\n\t\tfor (auto &mod_it : design->modules_) {\n\t\t\tif (design->selected(mod_it.second))\n\t\t\t\tfor (auto &cell_it : mod_it.second->cells_)\n\t\t\t\t\tif (cell_it.second->type == \"$fsm\" && design->selected(mod_it.second, cell_it.second))\n\t\t\t\t\t\tFsmData::optimize_fsm(cell_it.second, mod_it.second);\n\t\t}\n\t}\n} FsmOptPass;\n\nPRIVATE_NAMESPACE_END\n<|endoftext|>"} {"text":"\/*!\n\t@file\n\t@author\t\tGeorge Evmenov\n\t@date\t\t07\/2009\n*\/\n\n#include \"MyGUI_OpenGLRenderManager.h\"\n#include \"MyGUI_OpenGLTexture.h\"\n#include \"MyGUI_OpenGLVertexBuffer.h\"\n#include \"MyGUI_OpenGLDiagnostic.h\"\n#include \"MyGUI_VertexData.h\"\n#include \"MyGUI_Gui.h\"\n#include \"MyGUI_Timer.h\"\n\n#include \"GL\/glew.h\"\n\nnamespace MyGUI\n{\n\n\tOpenGLRenderManager::OpenGLRenderManager() :\n\t\tmUpdate(false),\n\t\tmImageLoader(nullptr),\n\t\tmPboIsSupported(false),\n\t\tmIsInitialise(false)\n\t{\n\t}\n\n\tvoid OpenGLRenderManager::initialise(OpenGLImageLoader* _loader)\n\t{\n\t\tMYGUI_ASSERT(!mIsInitialise, getClassTypeName() << \" initialised twice\");\n\t\tMYGUI_LOG(Info, \"* Initialise: \" << getClassTypeName());\n\n\t\tmVertexFormat = VertexColourType::ColourABGR;\n\n\t\tmUpdate = false;\n\t\tmImageLoader = _loader;\n\n\t\tglewInit();\n\n\t\tmPboIsSupported = glewIsExtensionSupported(\"GL_EXT_pixel_buffer_object\") != 0;\n\n\t\tMYGUI_LOG(Info, getClassTypeName() << \" successfully initialized\");\n\t\tmIsInitialise = true;\n\t}\n\n\tvoid OpenGLRenderManager::shutdown()\n\t{\n\t\tMYGUI_ASSERT(mIsInitialise, getClassTypeName() << \" is not initialised\");\n\t\tMYGUI_LOG(Info, \"* Shutdown: \" << getClassTypeName());\n\n\t\tdestroyAllResources();\n\n\t\tMYGUI_LOG(Info, getClassTypeName() << \" successfully shutdown\");\n\t\tmIsInitialise = false;\n\t}\n\n\tIVertexBuffer* OpenGLRenderManager::createVertexBuffer()\n\t{\n\t\treturn new OpenGLVertexBuffer();\n\t}\n\n\tvoid OpenGLRenderManager::destroyVertexBuffer(IVertexBuffer* _buffer)\n\t{\n\t\tdelete _buffer;\n\t}\n\n\tvoid OpenGLRenderManager::doRender(IVertexBuffer* _buffer, ITexture* _texture, size_t _count)\n\t{\n\t\tOpenGLVertexBuffer* buffer = static_cast(_buffer);\n\t\tunsigned int buffer_id = buffer->getBufferID();\n\t\tMYGUI_PLATFORM_ASSERT(buffer_id, \"Vertex buffer is not created\");\n\n\t\tunsigned int texture_id = 0;\n\t\tif (_texture)\n\t\t{\n\t\t\tOpenGLTexture* texture = static_cast(_texture);\n\t\t\ttexture_id = texture->getTextureID();\n\t\t\t\/\/MYGUI_PLATFORM_ASSERT(texture_id, \"Texture is not created\");\n\t\t}\n\n\t\tglBindTexture(GL_TEXTURE_2D, texture_id);\n\n\t\tglBindBufferARB(GL_ARRAY_BUFFER_ARB, buffer_id);\n\n\t\t\/\/ enable vertex arrays\n\t\tglEnableClientState(GL_VERTEX_ARRAY);\n\t\tglEnableClientState(GL_COLOR_ARRAY);\n\t\tglEnableClientState(GL_TEXTURE_COORD_ARRAY);\n\n\t\t\/\/ before draw, specify vertex and index arrays with their offsets\n\t\tsize_t offset = 0;\n\t\tglVertexPointer(3, GL_FLOAT, sizeof(Vertex), (void*)offset);\n\t\toffset += (sizeof(float) * 3);\n\t\tglColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex), (void*)offset);\n\t\toffset += (4);\n\t\tglTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), (void*)offset);\n\n\t\tglDrawArrays(GL_TRIANGLES, 0, _count);\n\n\t\tglDisableClientState(GL_TEXTURE_COORD_ARRAY);\n\t\tglDisableClientState(GL_COLOR_ARRAY);\n\t\tglDisableClientState(GL_VERTEX_ARRAY);\n\n\t\tglBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);\n\t\tglBindTexture(GL_TEXTURE_2D, 0);\n\t}\n\n\tvoid OpenGLRenderManager::begin()\n\t{\n\t\t\/\/save current attributes\n\t\tglPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS);\n\t\tglPushAttrib(GL_ALL_ATTRIB_BITS);\n\n\t\tglPolygonMode(GL_FRONT, GL_FILL);\n\t\tglMatrixMode(GL_PROJECTION);\n\t\tglPushMatrix();\n\t\tglLoadIdentity();\n\t\tglOrtho(-1, 1, -1, 1, -1, 1);\n\n\t\tglMatrixMode(GL_MODELVIEW);\n\t\tglPushMatrix();\n\t\tglLoadIdentity();\n\n\t\tglDisable(GL_LIGHTING);\n\t\tglDisable(GL_DEPTH_TEST);\n\t\tglDisable(GL_FOG);\n\t\tglDisable(GL_TEXTURE_GEN_S);\n\t\tglDisable(GL_TEXTURE_GEN_T);\n\t\tglDisable(GL_TEXTURE_GEN_R);\n\n\t\t\/\/glFrontFace(GL_CW);\n\t\t\/\/glCullFace(GL_BACK);\n\t\t\/\/glEnable(GL_CULL_FACE);\n\n\t\tglEnable(GL_BLEND);\n\t\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n\t\tglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);\n\t\tglEnable(GL_TEXTURE_2D);\n\t}\n\n\tvoid OpenGLRenderManager::end()\n\t{\n\t\tglPopMatrix();\n\t\tglMatrixMode(GL_PROJECTION);\n\t\tglPopMatrix();\n\t\tglMatrixMode(GL_MODELVIEW);\n\n\t\t\/\/restore former attributes\n\t\tglPopAttrib();\n\t\tglPopClientAttrib();\n\t}\n\n\tconst RenderTargetInfo& OpenGLRenderManager::getInfo()\n\t{\n\t\treturn mInfo;\n\t}\n\n\tconst IntSize& OpenGLRenderManager::getViewSize() const\n\t{\n\t\treturn mViewSize;\n\t}\n\n\tVertexColourType OpenGLRenderManager::getVertexFormat()\n\t{\n\t\treturn mVertexFormat;\n\t}\n\n\tvoid OpenGLRenderManager::drawOneFrame()\n\t{\n\t\tGui* gui = Gui::getInstancePtr();\n\t\tif (gui == nullptr)\n\t\t\treturn;\n\n\t\tstatic Timer timer;\n\t\tstatic unsigned long last_time = timer.getMilliseconds();\n\t\tunsigned long now_time = timer.getMilliseconds();\n\t\tunsigned long time = now_time - last_time;\n\n\t\tgui->_injectFrameEntered((float)((double)(time) \/ (double)1000));\n\n\t\tlast_time = now_time;\n\n\t\tbegin();\n\t\tLayerManager::getInstance().renderToTarget(this, mUpdate);\n\t\tend();\n\n\t\tmUpdate = false;\n\t}\n\n\tvoid OpenGLRenderManager::setViewSize(int _width, int _height)\n\t{\n\t\tif (_height == 0)\n\t\t\t_height = 1;\n\t\tif (_width == 0)\n\t\t\t_width = 1;\n\n\t\tmViewSize.set(_width, _height);\n\n\t\tmInfo.maximumDepth = 1;\n\t\tmInfo.hOffset = 0;\n\t\tmInfo.vOffset = 0;\n\t\tmInfo.aspectCoef = float(mViewSize.height) \/ float(mViewSize.width);\n\t\tmInfo.pixScaleX = 1.0f \/ float(mViewSize.width);\n\t\tmInfo.pixScaleY = 1.0f \/ float(mViewSize.height);\n\n\t\tGui* gui = Gui::getInstancePtr();\n\t\tif (gui != nullptr)\n\t\t{\n\t\t\tgui->_resizeWindow(mViewSize);\n\t\t\tmUpdate = true;\n\t\t}\n\t}\n\n\tbool OpenGLRenderManager::isPixelBufferObjectSupported()\n\t{\n\t\treturn mPboIsSupported;\n\t}\n\n\tITexture* OpenGLRenderManager::createTexture(const std::string& _name)\n\t{\n\t\tMapTexture::const_iterator item = mTextures.find(_name);\n\t\tMYGUI_PLATFORM_ASSERT(item == mTextures.end(), \"Texture '\" << _name << \"' already exist\");\n\n\t\tOpenGLTexture* texture = new OpenGLTexture(_name, mImageLoader);\n\t\tmTextures[_name] = texture;\n\t\treturn texture;\n\t}\n\n\tvoid OpenGLRenderManager::destroyTexture(ITexture* _texture)\n\t{\n\t\tif (_texture == nullptr) return;\n\n\t\tMapTexture::iterator item = mTextures.find(_texture->getName());\n\t\tMYGUI_PLATFORM_ASSERT(item != mTextures.end(), \"Texture '\" << _texture->getName() << \"' not found\");\n\n\t\tmTextures.erase(item);\n\t\tdelete _texture;\n\t}\n\n\tITexture* OpenGLRenderManager::getTexture(const std::string& _name)\n\t{\n\t\tMapTexture::const_iterator item = mTextures.find(_name);\n\t\tif (item == mTextures.end()) return nullptr;\n\t\treturn item->second;\n\t}\n\n\tvoid OpenGLRenderManager::destroyAllResources()\n\t{\n\t\tfor (MapTexture::const_iterator item = mTextures.begin(); item != mTextures.end(); ++item)\n\t\t{\n\t\t\tdelete item->second;\n\t\t}\n\t\tmTextures.clear();\n\t}\n\n} \/\/ namespace MyGUI\nrefactoring OpenGL platform\/*!\n\t@file\n\t@author\t\tGeorge Evmenov\n\t@date\t\t07\/2009\n*\/\n\n#include \"MyGUI_OpenGLRenderManager.h\"\n#include \"MyGUI_OpenGLTexture.h\"\n#include \"MyGUI_OpenGLVertexBuffer.h\"\n#include \"MyGUI_OpenGLDiagnostic.h\"\n#include \"MyGUI_VertexData.h\"\n#include \"MyGUI_Gui.h\"\n#include \"MyGUI_Timer.h\"\n\n#include \"GL\/glew.h\"\n\nnamespace MyGUI\n{\n\n\tOpenGLRenderManager::OpenGLRenderManager() :\n\t\tmUpdate(false),\n\t\tmImageLoader(nullptr),\n\t\tmPboIsSupported(false),\n\t\tmIsInitialise(false)\n\t{\n\t}\n\n\tvoid OpenGLRenderManager::initialise(OpenGLImageLoader* _loader)\n\t{\n\t\tMYGUI_ASSERT(!mIsInitialise, getClassTypeName() << \" initialised twice\");\n\t\tMYGUI_LOG(Info, \"* Initialise: \" << getClassTypeName());\n\n\t\tmVertexFormat = VertexColourType::ColourABGR;\n\n\t\tmUpdate = false;\n\t\tmImageLoader = _loader;\n\n\t\tglewInit();\n\n\t\tmPboIsSupported = glewIsExtensionSupported(\"GL_EXT_pixel_buffer_object\") != 0;\n\n\t\tMYGUI_LOG(Info, getClassTypeName() << \" successfully initialized\");\n\t\tmIsInitialise = true;\n\t}\n\n\tvoid OpenGLRenderManager::shutdown()\n\t{\n\t\tMYGUI_ASSERT(mIsInitialise, getClassTypeName() << \" is not initialised\");\n\t\tMYGUI_LOG(Info, \"* Shutdown: \" << getClassTypeName());\n\n\t\tdestroyAllResources();\n\n\t\tMYGUI_LOG(Info, getClassTypeName() << \" successfully shutdown\");\n\t\tmIsInitialise = false;\n\t}\n\n\tIVertexBuffer* OpenGLRenderManager::createVertexBuffer()\n\t{\n\t\treturn new OpenGLVertexBuffer();\n\t}\n\n\tvoid OpenGLRenderManager::destroyVertexBuffer(IVertexBuffer* _buffer)\n\t{\n\t\tdelete _buffer;\n\t}\n\n\tvoid OpenGLRenderManager::doRender(IVertexBuffer* _buffer, ITexture* _texture, size_t _count)\n\t{\n\t\tOpenGLVertexBuffer* buffer = static_cast(_buffer);\n\t\tunsigned int buffer_id = buffer->getBufferID();\n\t\tMYGUI_PLATFORM_ASSERT(buffer_id, \"Vertex buffer is not created\");\n\n\t\tunsigned int texture_id = 0;\n\t\tif (_texture)\n\t\t{\n\t\t\tOpenGLTexture* texture = static_cast(_texture);\n\t\t\ttexture_id = texture->getTextureID();\n\t\t\t\/\/MYGUI_PLATFORM_ASSERT(texture_id, \"Texture is not created\");\n\t\t}\n\n\t\tglBindTexture(GL_TEXTURE_2D, texture_id);\n\n\t\tglBindBufferARB(GL_ARRAY_BUFFER_ARB, buffer_id);\n\n\t\t\/\/ enable vertex arrays\n\t\tglEnableClientState(GL_VERTEX_ARRAY);\n\t\tglEnableClientState(GL_COLOR_ARRAY);\n\t\tglEnableClientState(GL_TEXTURE_COORD_ARRAY);\n\n\t\t\/\/ before draw, specify vertex and index arrays with their offsets\n\t\tsize_t offset = 0;\n\t\tglVertexPointer(3, GL_FLOAT, sizeof(Vertex), (void*)offset);\n\t\toffset += (sizeof(float) * 3);\n\t\tglColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex), (void*)offset);\n\t\toffset += (4);\n\t\tglTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), (void*)offset);\n\n\t\tglDrawArrays(GL_TRIANGLES, 0, _count);\n\n\t\tglDisableClientState(GL_TEXTURE_COORD_ARRAY);\n\t\tglDisableClientState(GL_COLOR_ARRAY);\n\t\tglDisableClientState(GL_VERTEX_ARRAY);\n\n\t\tglBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);\n\t\tglBindTexture(GL_TEXTURE_2D, 0);\n\t}\n\n\tvoid OpenGLRenderManager::begin()\n\t{\n\t\t\/\/save current attributes\n\t\tglPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS);\n\t\tglPushAttrib(GL_ALL_ATTRIB_BITS);\n\n\t\tglPolygonMode(GL_FRONT, GL_FILL);\n\t\tglMatrixMode(GL_PROJECTION);\n\t\tglPushMatrix();\n\t\tglLoadIdentity();\n\t\tglOrtho(-1, 1, -1, 1, -1, 1);\n\n\t\tglMatrixMode(GL_MODELVIEW);\n\t\tglPushMatrix();\n\t\tglLoadIdentity();\n\n\t\tglDisable(GL_LIGHTING);\n\t\tglDisable(GL_DEPTH_TEST);\n\t\tglDisable(GL_FOG);\n\t\tglDisable(GL_TEXTURE_GEN_S);\n\t\tglDisable(GL_TEXTURE_GEN_T);\n\t\tglDisable(GL_TEXTURE_GEN_R);\n\n\t\t\/\/glFrontFace(GL_CW);\n\t\t\/\/glCullFace(GL_BACK);\n\t\t\/\/glEnable(GL_CULL_FACE);\n\n\t\tglEnable(GL_BLEND);\n\t\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n\t\tglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);\n\t\tglEnable(GL_TEXTURE_2D);\n\t}\n\n\tvoid OpenGLRenderManager::end()\n\t{\n\t\tglPopMatrix();\n\t\tglMatrixMode(GL_PROJECTION);\n\t\tglPopMatrix();\n\t\tglMatrixMode(GL_MODELVIEW);\n\n\t\t\/\/restore former attributes\n\t\tglPopAttrib();\n\t\tglPopClientAttrib();\n\t}\n\n\tconst RenderTargetInfo& OpenGLRenderManager::getInfo()\n\t{\n\t\treturn mInfo;\n\t}\n\n\tconst IntSize& OpenGLRenderManager::getViewSize() const\n\t{\n\t\treturn mViewSize;\n\t}\n\n\tVertexColourType OpenGLRenderManager::getVertexFormat()\n\t{\n\t\treturn mVertexFormat;\n\t}\n\n\tvoid OpenGLRenderManager::drawOneFrame()\n\t{\n\t\tGui* gui = Gui::getInstancePtr();\n\t\tif (gui == nullptr)\n\t\t\treturn;\n\n\t\tstatic Timer timer;\n\t\tstatic unsigned long last_time = timer.getMilliseconds();\n\t\tunsigned long now_time = timer.getMilliseconds();\n\t\tunsigned long time = now_time - last_time;\n\n\t\tonFrameEvent((float)((double)(time) \/ (double)1000));\n\n\t\tlast_time = now_time;\n\n\t\tbegin();\n\t\tonRenderToTarget(this, mUpdate);\n\t\tend();\n\n\t\tmUpdate = false;\n\t}\n\n\tvoid OpenGLRenderManager::setViewSize(int _width, int _height)\n\t{\n\t\tif (_height == 0)\n\t\t\t_height = 1;\n\t\tif (_width == 0)\n\t\t\t_width = 1;\n\n\t\tmViewSize.set(_width, _height);\n\n\t\tmInfo.maximumDepth = 1;\n\t\tmInfo.hOffset = 0;\n\t\tmInfo.vOffset = 0;\n\t\tmInfo.aspectCoef = float(mViewSize.height) \/ float(mViewSize.width);\n\t\tmInfo.pixScaleX = 1.0f \/ float(mViewSize.width);\n\t\tmInfo.pixScaleY = 1.0f \/ float(mViewSize.height);\n\n\t\tonResizeView(mViewSize);\n\t\tmUpdate = true;\n\t}\n\n\tbool OpenGLRenderManager::isPixelBufferObjectSupported()\n\t{\n\t\treturn mPboIsSupported;\n\t}\n\n\tITexture* OpenGLRenderManager::createTexture(const std::string& _name)\n\t{\n\t\tMapTexture::const_iterator item = mTextures.find(_name);\n\t\tMYGUI_PLATFORM_ASSERT(item == mTextures.end(), \"Texture '\" << _name << \"' already exist\");\n\n\t\tOpenGLTexture* texture = new OpenGLTexture(_name, mImageLoader);\n\t\tmTextures[_name] = texture;\n\t\treturn texture;\n\t}\n\n\tvoid OpenGLRenderManager::destroyTexture(ITexture* _texture)\n\t{\n\t\tif (_texture == nullptr)\n\t\t\treturn;\n\n\t\tMapTexture::iterator item = mTextures.find(_texture->getName());\n\t\tMYGUI_PLATFORM_ASSERT(item != mTextures.end(), \"Texture '\" << _texture->getName() << \"' not found\");\n\n\t\tmTextures.erase(item);\n\t\tdelete _texture;\n\t}\n\n\tITexture* OpenGLRenderManager::getTexture(const std::string& _name)\n\t{\n\t\tMapTexture::const_iterator item = mTextures.find(_name);\n\t\tif (item == mTextures.end())\n\t\t\treturn nullptr;\n\t\treturn item->second;\n\t}\n\n\tvoid OpenGLRenderManager::destroyAllResources()\n\t{\n\t\tfor (MapTexture::const_iterator item = mTextures.begin(); item != mTextures.end(); ++item)\n\t\t{\n\t\t\tdelete item->second;\n\t\t}\n\t\tmTextures.clear();\n\t}\n\n} \/\/ namespace MyGUI\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nint main(int argc, char *argv[]) {\n namespace aif = affine_invariant_features;\n\n if (argc != 4) {\n std::cout << \"Usage: extract_features \"\n << std::endl;\n std::cout << \"Note: use generate_*_file to generate parameter or target files\" << std::endl;\n return 0;\n }\n\n const std::string param_path(argv[1]);\n const std::string target_path(argv[2]);\n const std::string result_path(argv[3]);\n\n const cv::FileStorage param_file(param_path, cv::FileStorage::READ);\n const cv::Ptr< const aif::FeatureParameters > params(\n aif::readFeatureParameters(param_file.root()));\n if (!params) {\n std::cerr << \"Could not load a parameter set from \" << param_path << std::endl;\n return 1;\n }\n\n const cv::FileStorage target_file(target_path, cv::FileStorage::READ);\n aif::TargetDescription target_desc;\n target_file[target_desc.getDefaultName()] >> target_desc;\n if (target_desc.imagePath.empty()) {\n std::cerr << \"Could not load an image path from \" << target_path << std::endl;\n return 1;\n }\n\n const aif::TargetData target_data(target_desc.toData());\n if (target_data.image.empty()) {\n std::cerr << \"Could not load a target image described in \" << target_path << std::endl;\n return 1;\n }\n\n cv::Mat target_image;\n if (target_data.mask.empty()) {\n target_image = target_data.image.clone();\n } else {\n target_image = target_data.image \/ 4;\n target_data.image.copyTo(target_image, target_data.mask);\n }\n std::cout << \"Showing the target image with mask. Press any key to continue.\" << std::endl;\n cv::imshow(\"Target\", target_image);\n cv::waitKey(0);\n\n std::cout << \"Extracting features. This may take seconds or minutes.\" << std::endl;\n const cv::Ptr< cv::Feature2D > feature(\n aif::AffineInvariantFeature::create(params->createFeature()));\n aif::Results results;\n feature->detectAndCompute(target_data.image, target_data.mask, results.keypoints,\n results.descriptors);\n results.normType = feature->defaultNorm();\n\n cv::Mat result_image;\n cv::drawKeypoints(target_image, results.keypoints, result_image);\n std::cout << \"Showing a result image with keypoints. Press any key to continue.\" << std::endl;\n cv::imshow(\"Resutls\", result_image);\n cv::waitKey(0);\n\n cv::FileStorage result_file(result_path, cv::FileStorage::WRITE);\n result_file << params->getDefaultName() << *params;\n result_file << target_desc.getDefaultName() << target_desc;\n result_file << results.getDefaultName() << results;\n\n std::cout << \"Wrote context and results of feature extraction to \" << result_path << std::endl;\n\n return 0;\n}\nrefactor extract_features#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nint main(int argc, char *argv[]) {\n namespace aif = affine_invariant_features;\n\n const cv::CommandLineParser args(\n argc, argv, \"{ help | | }\"\n \"{ use-simple-feature | | will not use affine invariant sampling }\"\n \"{ @parameter-file | | can be generated by generate_parameter_file }\"\n \"{ @target-file | | can be generated by generate_target_file }\"\n \"{ @result-file | | }\");\n\n if (args.has(\"help\")) {\n args.printMessage();\n return 0;\n }\n\n const bool use_simple_feature(args.has(\"use-simple-feature\"));\n const std::string param_path(args.get< std::string >(\"@parameter-file\"));\n const std::string target_path(args.get< std::string >(\"@target-file\"));\n const std::string result_path(args.get< std::string >(\"@result-file\"));\n if (!args.check()) {\n args.printErrors();\n return 1;\n }\n\n const cv::FileStorage param_file(param_path, cv::FileStorage::READ);\n if (!param_file.isOpened()) {\n std::cerr << \"Could not open \" << param_path << std::endl;\n return 1;\n }\n\n const cv::Ptr< const aif::FeatureParameters > params(\n aif::readFeatureParameters(param_file.root()));\n if (!params) {\n std::cerr << \"Could not load a parameter set from \" << param_path << std::endl;\n return 1;\n }\n\n const cv::FileStorage target_file(target_path, cv::FileStorage::READ);\n if (!target_file.isOpened()) {\n std::cerr << \"Could not open \" << target_path << std::endl;\n return 1;\n }\n\n aif::TargetDescription target_desc;\n target_file[target_desc.getDefaultName()] >> target_desc;\n if (target_desc.imagePath.empty()) {\n std::cerr << \"Could not load an image path from \" << target_path << std::endl;\n return 1;\n }\n\n const aif::TargetData target_data(target_desc.toData());\n if (target_data.image.empty()) {\n std::cerr << \"Could not load a target image described in \" << target_path << std::endl;\n return 1;\n }\n\n cv::Mat target_image;\n if (target_data.mask.empty()) {\n target_image = target_data.image.clone();\n } else {\n target_image = target_data.image \/ 4;\n target_data.image.copyTo(target_image, target_data.mask);\n }\n std::cout << \"Showing the target image with mask. Press any key to continue.\" << std::endl;\n cv::imshow(\"Target\", target_image);\n cv::waitKey(0);\n\n std::cout << \"Extracting features. This may take seconds or minutes.\" << std::endl;\n cv::Ptr< cv::Feature2D > feature;\n if (use_simple_feature) {\n feature = params->createFeature();\n } else {\n feature = aif::AffineInvariantFeature::create(params->createFeature());\n }\n aif::Results results;\n feature->detectAndCompute(target_data.image, target_data.mask, results.keypoints,\n results.descriptors);\n results.normType = feature->defaultNorm();\n\n cv::Mat result_image;\n cv::drawKeypoints(target_image, results.keypoints, result_image);\n std::cout << \"Showing a result image with keypoints. Press any key to continue.\" << std::endl;\n cv::imshow(\"Resutls\", result_image);\n cv::waitKey(0);\n\n cv::FileStorage result_file(result_path, cv::FileStorage::WRITE);\n if(!result_file.isOpened()){\n std::cerr << \"Could not open or create \" << result_path << std::endl;\n return 1;\n }\n\n result_file << params->getDefaultName() << *params;\n result_file << target_desc.getDefaultName() << target_desc;\n result_file << results.getDefaultName() << results;\n std::cout << \"Wrote context and results of feature extraction to \" << result_path << std::endl;\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: syshelp.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 11:58:53 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef X2C_SYSHELP_HXX\n#define X2C_SYSHELP_HXX\n\n\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n \/\/ COMPONENTS\n \/\/ PARAMETERS\n#include \n\nclass Simstr;\ntemplate class List;\n\n\n#ifdef WNT\nconst char C_sSLASH[] = \"\\\\\";\nconst char C_cSLASH = '\\\\';\n#elif defined(UNX)\nconst char C_sSLASH[] = \"\/\";\nconst char C_cSLASH = '\/';\n#else\n#error Must run under unix or windows, please define UNX or WNT.\n#endif\n\nenum E_LinkType\n{\n lt_nolink = 0,\n lt_idl,\n lt_html\n};\n\n\nvoid WriteName(\n std::ostream & o_rFile,\n const Simstr & i_rIdlDocuBaseDir,\n const Simstr & i_rName,\n E_LinkType i_eLinkType );\n\n\nvoid WriteStr(\n std::ostream & o_rFile,\n const char * i_sStr );\nvoid WriteStr(\n std::ostream & o_rFile,\n const Simstr & i_sStr );\n\nvoid GatherFileNames(\n List & o_sFiles,\n const char * i_sSrcDirectory );\nvoid GatherSubDirectories(\n List & o_sSubDirectories,\n const char * i_sParentdDirectory );\n\n\n\n#endif\n\nINTEGRATION: CWS os2port02 (1.7.40); FILE MERGED 2007\/10\/04 19:45:25 ydario 1.7.40.1: Issue number: i82034 Submitted by: ydario Reviewed by: ydario Commit of changes for OS\/2 CWS source code integration.\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: syshelp.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: hr $ $Date: 2007-11-02 12:55:47 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef X2C_SYSHELP_HXX\n#define X2C_SYSHELP_HXX\n\n\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n \/\/ COMPONENTS\n \/\/ PARAMETERS\n#include \n\nclass Simstr;\ntemplate class List;\n\n\n#if defined(WNT) || defined(OS2)\nconst char C_sSLASH[] = \"\\\\\";\nconst char C_cSLASH = '\\\\';\n#elif defined(UNX)\nconst char C_sSLASH[] = \"\/\";\nconst char C_cSLASH = '\/';\n#else\n#error Must run under unix or windows, please define UNX or WNT.\n#endif\n\nenum E_LinkType\n{\n lt_nolink = 0,\n lt_idl,\n lt_html\n};\n\n\nvoid WriteName(\n std::ostream & o_rFile,\n const Simstr & i_rIdlDocuBaseDir,\n const Simstr & i_rName,\n E_LinkType i_eLinkType );\n\n\nvoid WriteStr(\n std::ostream & o_rFile,\n const char * i_sStr );\nvoid WriteStr(\n std::ostream & o_rFile,\n const Simstr & i_sStr );\n\nvoid GatherFileNames(\n List & o_sFiles,\n const char * i_sSrcDirectory );\nvoid GatherSubDirectories(\n List & o_sSubDirectories,\n const char * i_sParentdDirectory );\n\n\n\n#endif\n\n<|endoftext|>"} {"text":"coverity#704111: Unchecked return value<|endoftext|>"} {"text":"\/\/ Copyright (c) 2013 - 2015, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\n#include \n\nusing namespace std;\nusing namespace nix::base;\n\nnamespace nix {\nnamespace file {\n\nDimensionType dimensionTypeFromStr(const string &str) {\n if (str == \"set\") {\n return DimensionType::Set;\n } else if (str == \"range\") {\n return DimensionType::Range;\n } else if (str == \"sample\") {\n return DimensionType::Sample;\n } else {\n throw runtime_error(\"Not a valid dimension name\");\n }\n}\n\n\nstd::string dimensionTypeToStr(DimensionType dim) {\n\n \/\/The way this switch + string.empty() checking is\n \/\/ done here might seem a bit convoluted, but the\n \/\/ idea behind it is:\n \/\/ a) have no default case in the switch to get a\n \/\/ compile warning in case a new element is\n \/\/ added to the enum\n \/\/ b) still be safe and throw an exception in case\n \/\/ not all enum cases are handled properly\n\n std::string dimType;\n\n switch (dim) {\n case DimensionType::Set:\n dimType = \"set\";\n break;\n case DimensionType::Range:\n dimType = \"range\";\n break;\n case DimensionType::Sample:\n dimType = \"sample\";\n break;\n }\n\n if (dimType.empty()) {\n throw runtime_error(\"Not a valid dimension type\");\n }\n\n return dimType;\n}\n\n\nshared_ptr openDimensionFS(const string &loc, size_t index, FileMode mode) {\n AttributesFS attr(loc, mode);\n string type_name;\n attr.get(\"dimension_type\", type_name);\n\n DimensionType type = dimensionTypeFromStr(type_name);\n shared_ptr dim;\n\n switch (type) {\n case DimensionType::Set:\n dim = make_shared(loc, index, mode);\n break;\n case DimensionType::Range:\n dim = make_shared(loc, index, mode);\n break;\n case DimensionType::Sample:\n dim = make_shared(loc, index, mode);\n break;\n }\n return dim;\n}\n\n\n\/\/ Implementation of Dimension\n\nDimensionFS::DimensionFS(const string &loc, size_t index, FileMode mode)\n : DirectoryWithAttributes(loc + boost::filesystem::path::preferred_separator + util::numToStr(index), mode)\n{\n this->index(index);\n}\n\nvoid DimensionFS::index(size_t index) {\n setAttr(\"index\", index);\n}\n\nsize_t DimensionFS::index() const {\n size_t idx;\n if (hasAttr(\"index\"))\n getAttr(\"index\", idx);\n return idx;\n}\n\nvoid DimensionFS::setType() {\n if (!hasAttr(\"dimension_type\"))\n setAttr(\"dimension_type\", dimensionTypeToStr(dimensionType()));\n}\n\n\nbool DimensionFS::operator==(const DimensionFS &other) const {\n return location() == other.location();\n}\n\n\nbool DimensionFS::operator!=(const DimensionFS &other) const {\n return !(*this == other);\n}\n\n\nDimensionFS::~DimensionFS() {}\n\n\/\/--------------------------------------------------------------\n\/\/ Implementation of SampledDimension\n\/\/--------------------------------------------------------------\n\nSampledDimensionFS::SampledDimensionFS(const string &loc, size_t index, FileMode mode)\n : DimensionFS(loc, index, mode)\n{\n}\n\nSampledDimensionFS::SampledDimensionFS(const string &loc, size_t index, double sampling_interval, FileMode mode)\n : SampledDimensionFS(loc, index, mode)\n{\n setType();\n this->samplingInterval(sampling_interval);\n}\n\n\nDimensionType SampledDimensionFS::dimensionType() const {\n return DimensionType::Sample;\n}\n\n\nboost::optional SampledDimensionFS::label() const {\n boost::optional ret;\n string label;\n if (hasAttr(\"label\")) {\n getAttr(\"label\", label);\n ret = label;\n }\n return ret;\n}\n\n\nvoid SampledDimensionFS::label(const string &label) {\n if (label.empty()) {\n throw EmptyString(\"label\");\n } else {\n setAttr(\"label\", label);\n \/\/ NOTE: forceUpdatedAt() not possible since not reachable from here\n }\n}\n\n\nvoid SampledDimensionFS::label(const none_t t) {\n if (hasAttr(\"label\")) {\n removeAttr(\"label\");\n }\n \/\/ NOTE: forceUpdatedAt() not possible since not reachable from here\n}\n\n\nboost::optional SampledDimensionFS::unit() const {\n boost::optional ret;\n string unit;\n if (hasAttr(\"unit\")) {\n getAttr(\"unit\", unit);\n ret = unit;\n }\n return ret;\n}\n\n\nvoid SampledDimensionFS::unit(const string &unit) {\n if (unit.empty()) {\n throw EmptyString(\"unit\");\n } else {\n setAttr(\"unit\", unit);\n \/\/ NOTE: forceUpdatedAt() not possible since not reachable from here\n }\n}\n\n\nvoid SampledDimensionFS::unit(const none_t t) {\n if (hasAttr(\"unit\")) {\n removeAttr(\"unit\");\n }\n \/\/ NOTE: forceUpdatedAt() not possible since not reachable from here\n}\n\n\ndouble SampledDimensionFS::samplingInterval() const {\n double sampling_interval;\n if (hasAttr(\"sampling_interval\")) {\n getAttr(\"sampling_interval\", sampling_interval);\n return sampling_interval;\n } else {\n throw MissingAttr(\"sampling_interval\");\n }\n}\n\n\nvoid SampledDimensionFS::samplingInterval(double sampling_interval) {\n setAttr(\"sampling_interval\", sampling_interval);\n}\n\n\nboost::optional SampledDimensionFS::offset() const {\n boost::optional ret;\n double offset = 0;\n if (hasAttr(\"offset\")) {\n getAttr(\"offset\", offset);\n ret = offset;\n }\n return ret;\n}\n\n\nvoid SampledDimensionFS::offset(double offset) {\n setAttr(\"offset\", offset);\n}\n\n\nvoid SampledDimensionFS::offset(const none_t t) {\n if (hasAttr(\"offset\")) {\n removeAttr(\"offset\");\n }\n}\n\n\nSampledDimensionFS::~SampledDimensionFS() {}\n\n\/\/--------------------------------------------------------------\n\/\/ Implementation of SetDimensionHDF5\n\/\/--------------------------------------------------------------\n\nSetDimensionFS::SetDimensionFS(const string &loc, size_t index, FileMode mode)\n : DimensionFS(loc, index, mode)\n{\n setType();\n}\n\n\nDimensionType SetDimensionFS::dimensionType() const {\n return DimensionType::Set;\n}\n\n\nvector SetDimensionFS::labels() const {\n vector labels;\n getAttr(\"labels\", labels);\n return labels;\n}\n\n\nvoid SetDimensionFS::labels(const vector &labels) {\n setAttr(\"labels\", labels);\n}\n\nvoid SetDimensionFS::labels(const none_t t) {\n if (hasAttr(\"labels\")) {\n removeAttr(\"labels\");\n }\n}\n\nSetDimensionFS::~SetDimensionFS() {}\n\n\/\/--------------------------------------------------------------\n\/\/ Implementation of RangeDimensionHDF5\n\/\/--------------------------------------------------------------\n\nRangeDimensionFS::RangeDimensionFS(const string &loc, size_t index, FileMode mode)\n : DimensionFS(loc, index, mode)\n{\n}\n\n\nRangeDimensionFS::RangeDimensionFS(const string &loc, size_t index, vector ticks, FileMode mode)\n : RangeDimensionFS(loc, index, mode)\n{\n setType();\n this->ticks(ticks);\n}\n\n\nRangeDimensionFS::RangeDimensionFS(const string &loc, size_t index, const DataArrayFS &array, FileMode mode)\n :RangeDimensionFS(loc, index, mode)\n{\n setType();\n \/\/ this->group.createLink(array.group(), array.id()); FIXME\n}\n\n\nDimensionType RangeDimensionFS::dimensionType() const {\n return DimensionType::Range;\n}\n\n\nstring RangeDimensionFS::redirectGroup() const {\n \/*\n Group g;\n if (alias()) {\n string group_name = group.objectName(0);\n g = group.openGroup(group_name, false);\n } else {\n g = group;\n }\n return g;\n *\/\n return \"\";\n}\n\n\nboost::optional RangeDimensionFS::label() const {\n boost::optional ret;\n string label;\n \/*\n Group g = redirectGroup();\n bool have_attr = g.getAttr(\"label\", label);\n if (have_attr) {\n ret = label;\n }\n *\/\n return ret;\n}\n\n\nvoid RangeDimensionFS::label(const string &label) {\n if (label.empty()) {\n throw EmptyString(\"label\");\n }\n \/*\n Group g = redirectGroup();\n g.setAttr(\"label\", label);\n \/\/ NOTE: forceUpdatedAt() not possible since not reachable from here\n *\/\n \/\/ FIXME\n}\n\n\nvoid RangeDimensionFS::label(const none_t t) {\n \/*\n Group g = redirectGroup();\n if (g.hasAttr(\"label\")) {\n g.removeAttr(\"label\");\n }\n *\/\n \/\/ FIXME\n \/\/ NOTE: forceUpdatedAt() not possible since not reachable from here\n}\n\n\nboost::optional RangeDimensionFS::unit() const {\n boost::optional ret;\n string unit;\n \/*\n Group g = redirectGroup();\n bool have_attr = g.getAttr(\"unit\", unit);\n if (have_attr) {\n ret = unit;\n }\n *\/ \/\/ FIXME\n return ret;\n}\n\n\nvoid RangeDimensionFS::unit(const string &unit) {\n if (unit.empty()) {\n throw EmptyString(\"unit\");\n } else {\n \/\/ Group g = redirectGroup(); FIXME\n \/\/ g.setAttr(\"unit\", unit);\n \/\/ NOTE: forceUpdatedAt() not possible since not reachable from here\n }\n}\n\n\nvoid RangeDimensionFS::unit(const none_t t) {\n \/\/ Group g = redirectGroup();\n \/\/ if (g.hasAttr(\"unit\")) {\n \/\/ g.removeAttr(\"unit\");\n \/\/ } FIXME\n \/\/ NOTE: forceUpdatedAt() not possible since not reachable from here\n}\n\n\nbool RangeDimensionFS::alias() const {\n return false;\n \/\/ return group.objectCount() > 0 && !group.hasData(\"ticks\");FIXME\n}\n\n\nvector RangeDimensionFS::ticks() const {\n vector ticks;\n \/*\n Group g = redirectGroup();\n if (g.hasData(\"ticks\")) {\n g.getData(\"ticks\", ticks);\n return ticks;\n } else if (g.hasData(\"data\")) {\n g.getData(\"data\", ticks);\n return ticks;\n } else {\n throw MissingAttr(\"ticks\");\n }\n *\/ \/\/ FIXME\n return ticks;\n}\n\n\nvoid RangeDimensionFS::ticks(const vector &ticks) {\n \/*\n Group g = redirectGroup();\n if (!alias()) {\n g.setData(\"ticks\", ticks);\n } else if (g.hasData(\"data\")) {\n NDSize extent(1, ticks.size());\n DataSet ds = g.openData(\"data\");\n ds.setExtent(extent);\n ds.write(nix::DataType::Double, extent, ticks.data());\n } else {\n throw MissingAttr(\"ticks\");\n }\n *\/ \/\/FIXME\n}\n\nRangeDimensionFS::~RangeDimensionFS() {}\n\n} \/\/ ns nix::file\n} \/\/ ns nix\n\n[file_backend\/Dimensions] setType always(!) resets the dime type\/\/ Copyright (c) 2013 - 2015, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\n#include \n\nusing namespace std;\nusing namespace nix::base;\n\nnamespace nix {\nnamespace file {\n\nDimensionType dimensionTypeFromStr(const string &str) {\n if (str == \"set\") {\n return DimensionType::Set;\n } else if (str == \"range\") {\n return DimensionType::Range;\n } else if (str == \"sample\") {\n return DimensionType::Sample;\n } else {\n throw runtime_error(\"Not a valid dimension name\");\n }\n}\n\n\nstd::string dimensionTypeToStr(DimensionType dim) {\n\n \/\/The way this switch + string.empty() checking is\n \/\/ done here might seem a bit convoluted, but the\n \/\/ idea behind it is:\n \/\/ a) have no default case in the switch to get a\n \/\/ compile warning in case a new element is\n \/\/ added to the enum\n \/\/ b) still be safe and throw an exception in case\n \/\/ not all enum cases are handled properly\n\n std::string dimType;\n\n switch (dim) {\n case DimensionType::Set:\n dimType = \"set\";\n break;\n case DimensionType::Range:\n dimType = \"range\";\n break;\n case DimensionType::Sample:\n dimType = \"sample\";\n break;\n }\n\n if (dimType.empty()) {\n throw runtime_error(\"Not a valid dimension type\");\n }\n\n return dimType;\n}\n\n\nshared_ptr openDimensionFS(const string &loc, size_t index, FileMode mode) {\n AttributesFS attr(loc, mode);\n string type_name;\n attr.get(\"dimension_type\", type_name);\n\n DimensionType type = dimensionTypeFromStr(type_name);\n shared_ptr dim;\n\n switch (type) {\n case DimensionType::Set:\n dim = make_shared(loc, index, mode);\n break;\n case DimensionType::Range:\n dim = make_shared(loc, index, mode);\n break;\n case DimensionType::Sample:\n dim = make_shared(loc, index, mode);\n break;\n }\n return dim;\n}\n\n\n\/\/ Implementation of Dimension\n\nDimensionFS::DimensionFS(const string &loc, size_t index, FileMode mode)\n : DirectoryWithAttributes(loc + boost::filesystem::path::preferred_separator + util::numToStr(index), mode)\n{\n this->index(index);\n}\n\nvoid DimensionFS::index(size_t index) {\n setAttr(\"index\", index);\n}\n\nsize_t DimensionFS::index() const {\n size_t idx;\n if (hasAttr(\"index\"))\n getAttr(\"index\", idx);\n return idx;\n}\n\nvoid DimensionFS::setType() {\n setAttr(\"dimension_type\", dimensionTypeToStr(dimensionType()));\n}\n\n\nbool DimensionFS::operator==(const DimensionFS &other) const {\n return location() == other.location();\n}\n\n\nbool DimensionFS::operator!=(const DimensionFS &other) const {\n return !(*this == other);\n}\n\n\nDimensionFS::~DimensionFS() {}\n\n\/\/--------------------------------------------------------------\n\/\/ Implementation of SampledDimension\n\/\/--------------------------------------------------------------\n\nSampledDimensionFS::SampledDimensionFS(const string &loc, size_t index, FileMode mode)\n : DimensionFS(loc, index, mode)\n{\n}\n\nSampledDimensionFS::SampledDimensionFS(const string &loc, size_t index, double sampling_interval, FileMode mode)\n : SampledDimensionFS(loc, index, mode)\n{\n setType();\n this->samplingInterval(sampling_interval);\n}\n\n\nDimensionType SampledDimensionFS::dimensionType() const {\n return DimensionType::Sample;\n}\n\n\nboost::optional SampledDimensionFS::label() const {\n boost::optional ret;\n string label;\n if (hasAttr(\"label\")) {\n getAttr(\"label\", label);\n ret = label;\n }\n return ret;\n}\n\n\nvoid SampledDimensionFS::label(const string &label) {\n if (label.empty()) {\n throw EmptyString(\"label\");\n } else {\n setAttr(\"label\", label);\n \/\/ NOTE: forceUpdatedAt() not possible since not reachable from here\n }\n}\n\n\nvoid SampledDimensionFS::label(const none_t t) {\n if (hasAttr(\"label\")) {\n removeAttr(\"label\");\n }\n \/\/ NOTE: forceUpdatedAt() not possible since not reachable from here\n}\n\n\nboost::optional SampledDimensionFS::unit() const {\n boost::optional ret;\n string unit;\n if (hasAttr(\"unit\")) {\n getAttr(\"unit\", unit);\n ret = unit;\n }\n return ret;\n}\n\n\nvoid SampledDimensionFS::unit(const string &unit) {\n if (unit.empty()) {\n throw EmptyString(\"unit\");\n } else {\n setAttr(\"unit\", unit);\n \/\/ NOTE: forceUpdatedAt() not possible since not reachable from here\n }\n}\n\n\nvoid SampledDimensionFS::unit(const none_t t) {\n if (hasAttr(\"unit\")) {\n removeAttr(\"unit\");\n }\n \/\/ NOTE: forceUpdatedAt() not possible since not reachable from here\n}\n\n\ndouble SampledDimensionFS::samplingInterval() const {\n double sampling_interval;\n if (hasAttr(\"sampling_interval\")) {\n getAttr(\"sampling_interval\", sampling_interval);\n return sampling_interval;\n } else {\n throw MissingAttr(\"sampling_interval\");\n }\n}\n\n\nvoid SampledDimensionFS::samplingInterval(double sampling_interval) {\n setAttr(\"sampling_interval\", sampling_interval);\n}\n\n\nboost::optional SampledDimensionFS::offset() const {\n boost::optional ret;\n double offset = 0;\n if (hasAttr(\"offset\")) {\n getAttr(\"offset\", offset);\n ret = offset;\n }\n return ret;\n}\n\n\nvoid SampledDimensionFS::offset(double offset) {\n setAttr(\"offset\", offset);\n}\n\n\nvoid SampledDimensionFS::offset(const none_t t) {\n if (hasAttr(\"offset\")) {\n removeAttr(\"offset\");\n }\n}\n\n\nSampledDimensionFS::~SampledDimensionFS() {}\n\n\/\/--------------------------------------------------------------\n\/\/ Implementation of SetDimensionHDF5\n\/\/--------------------------------------------------------------\n\nSetDimensionFS::SetDimensionFS(const string &loc, size_t index, FileMode mode)\n : DimensionFS(loc, index, mode)\n{\n setType();\n}\n\n\nDimensionType SetDimensionFS::dimensionType() const {\n return DimensionType::Set;\n}\n\n\nvector SetDimensionFS::labels() const {\n vector labels;\n getAttr(\"labels\", labels);\n return labels;\n}\n\n\nvoid SetDimensionFS::labels(const vector &labels) {\n setAttr(\"labels\", labels);\n}\n\nvoid SetDimensionFS::labels(const none_t t) {\n if (hasAttr(\"labels\")) {\n removeAttr(\"labels\");\n }\n}\n\nSetDimensionFS::~SetDimensionFS() {}\n\n\/\/--------------------------------------------------------------\n\/\/ Implementation of RangeDimensionHDF5\n\/\/--------------------------------------------------------------\n\nRangeDimensionFS::RangeDimensionFS(const string &loc, size_t index, FileMode mode)\n : DimensionFS(loc, index, mode)\n{\n}\n\n\nRangeDimensionFS::RangeDimensionFS(const string &loc, size_t index, vector ticks, FileMode mode)\n : RangeDimensionFS(loc, index, mode)\n{\n setType();\n this->ticks(ticks);\n}\n\n\nRangeDimensionFS::RangeDimensionFS(const string &loc, size_t index, const DataArrayFS &array, FileMode mode)\n :RangeDimensionFS(loc, index, mode)\n{\n setType();\n \/\/ this->group.createLink(array.group(), array.id()); FIXME\n}\n\n\nDimensionType RangeDimensionFS::dimensionType() const {\n return DimensionType::Range;\n}\n\n\nstring RangeDimensionFS::redirectGroup() const {\n \/*\n Group g;\n if (alias()) {\n string group_name = group.objectName(0);\n g = group.openGroup(group_name, false);\n } else {\n g = group;\n }\n return g;\n *\/\n return \"\";\n}\n\n\nboost::optional RangeDimensionFS::label() const {\n boost::optional ret;\n string label;\n \/*\n Group g = redirectGroup();\n bool have_attr = g.getAttr(\"label\", label);\n if (have_attr) {\n ret = label;\n }\n *\/\n return ret;\n}\n\n\nvoid RangeDimensionFS::label(const string &label) {\n if (label.empty()) {\n throw EmptyString(\"label\");\n }\n \/*\n Group g = redirectGroup();\n g.setAttr(\"label\", label);\n \/\/ NOTE: forceUpdatedAt() not possible since not reachable from here\n *\/\n \/\/ FIXME\n}\n\n\nvoid RangeDimensionFS::label(const none_t t) {\n \/*\n Group g = redirectGroup();\n if (g.hasAttr(\"label\")) {\n g.removeAttr(\"label\");\n }\n *\/\n \/\/ FIXME\n \/\/ NOTE: forceUpdatedAt() not possible since not reachable from here\n}\n\n\nboost::optional RangeDimensionFS::unit() const {\n boost::optional ret;\n string unit;\n \/*\n Group g = redirectGroup();\n bool have_attr = g.getAttr(\"unit\", unit);\n if (have_attr) {\n ret = unit;\n }\n *\/ \/\/ FIXME\n return ret;\n}\n\n\nvoid RangeDimensionFS::unit(const string &unit) {\n if (unit.empty()) {\n throw EmptyString(\"unit\");\n } else {\n \/\/ Group g = redirectGroup(); FIXME\n \/\/ g.setAttr(\"unit\", unit);\n \/\/ NOTE: forceUpdatedAt() not possible since not reachable from here\n }\n}\n\n\nvoid RangeDimensionFS::unit(const none_t t) {\n \/\/ Group g = redirectGroup();\n \/\/ if (g.hasAttr(\"unit\")) {\n \/\/ g.removeAttr(\"unit\");\n \/\/ } FIXME\n \/\/ NOTE: forceUpdatedAt() not possible since not reachable from here\n}\n\n\nbool RangeDimensionFS::alias() const {\n return false;\n \/\/ return group.objectCount() > 0 && !group.hasData(\"ticks\");FIXME\n}\n\n\nvector RangeDimensionFS::ticks() const {\n vector ticks;\n \/*\n Group g = redirectGroup();\n if (g.hasData(\"ticks\")) {\n g.getData(\"ticks\", ticks);\n return ticks;\n } else if (g.hasData(\"data\")) {\n g.getData(\"data\", ticks);\n return ticks;\n } else {\n throw MissingAttr(\"ticks\");\n }\n *\/ \/\/ FIXME\n return ticks;\n}\n\n\nvoid RangeDimensionFS::ticks(const vector &ticks) {\n \/*\n Group g = redirectGroup();\n if (!alias()) {\n g.setData(\"ticks\", ticks);\n } else if (g.hasData(\"data\")) {\n NDSize extent(1, ticks.size());\n DataSet ds = g.openData(\"data\");\n ds.setExtent(extent);\n ds.write(nix::DataType::Double, extent, ticks.data());\n } else {\n throw MissingAttr(\"ticks\");\n }\n *\/ \/\/FIXME\n}\n\nRangeDimensionFS::~RangeDimensionFS() {}\n\n} \/\/ ns nix::file\n} \/\/ ns nix\n\n<|endoftext|>"} {"text":"#include \"ngraph.h\"\n#include \n#include \n#include \n#include \n#include \"Iterators\/PinIterator.h\"\n#include \"Iterators\/GraphIterator.h\"\n\nnamespace agi {\n\n void Ngraph::getResidence(GraphEdge* e, Peers& residence) const {\n agi::PinIterator* pitr = pins(e);\n agi::GraphVertex* vtx;\n lid_t deg = degree(e);\n for (lid_t i=0;ie) \n found=true;\n else if (degree_list[t][index]<=e)\n bound_low=index;\n else\n bound_high=index;\n\n }\n return index;\n }\n GraphVertex* Ngraph::u(GraphEdge* edge) const {\n lid_t lid = (uintptr_t)(edge)-1;\n etype type = lid%num_types;\n lid\/=num_types;\n lid_t vid = u(lid,type);\n return reinterpret_cast(vid+1);\n }\n\n GraphVertex* Ngraph::v(GraphEdge* edge) const {\n if (isHyperGraph) {\n fprintf(stderr,\"v(edge) not supported in hypergraph mode\");\n return NULL;\n }\n if (edge==NULL) \n return NULL;\n uintptr_t id = (uintptr_t)(edge)-1;\n etype type = id%num_types;\n id\/=num_types;\n return reinterpret_cast(edge_list[type][id]+1);\n }\n\n lid_t Ngraph::degree(GraphEdge* edge) const {\n if (!isHyperGraph)\n return 2;\n uintptr_t id = (uintptr_t)(edge)-1;\n etype type = id%num_types;\n id\/=num_types;\n return pin_degree_list[type][id+1]-pin_degree_list[type][id];\n }\n\n PinIterator* Ngraph::pins(GraphEdge* edge) const {\n uintptr_t id = (uintptr_t)(edge)-1;\n etype type = id%num_types;\n id\/=num_types;\n if (!isHyperGraph) {\n return new PinIterator(reinterpret_cast(u(edge)),\n reinterpret_cast((char*)(edge_list[type]\n [id]+1)));\n }\n return new PinIterator((pin_list[type]+pin_degree_list[type][id]),\n pin_list[type]+pin_degree_list[type][id+1]);\n }\n\n void Ngraph::setEdgeWeights(std::vector& wgts, etype t) {\n assert(!edge_weights[t]);\n if (wgts.size()==0) {\n edge_weights[t] = new wgt_t[num_local_edges[t]];\n for (gid_t i=0;iWhoops... Deleted something that was needed#include \"ngraph.h\"\n#include \n#include \n#include \n#include \n#include \"Iterators\/PinIterator.h\"\n#include \"Iterators\/GraphIterator.h\"\n\nnamespace agi {\n\n void Ngraph::getResidence(GraphEdge* e, Peers& residence) const {\n agi::PinIterator* pitr = pins(e);\n agi::GraphVertex* vtx;\n lid_t deg = degree(e);\n for (lid_t i=0;ie) \n found=true;\n else if (degree_list[t][index]<=e)\n bound_low=index;\n else\n bound_high=index;\n\n }\n return index;\n }\n GraphVertex* Ngraph::u(GraphEdge* edge) const {\n lid_t lid = (uintptr_t)(edge)-1;\n etype type = lid%num_types;\n lid\/=num_types;\n lid_t vid = u(lid,type);\n return reinterpret_cast(vid+1);\n }\n\n GraphVertex* Ngraph::v(GraphEdge* edge) const {\n if (isHyperGraph) {\n fprintf(stderr,\"v(edge) not supported in hypergraph mode\");\n return NULL;\n }\n if (edge==NULL) \n return NULL;\n uintptr_t id = (uintptr_t)(edge)-1;\n etype type = id%num_types;\n id\/=num_types;\n return reinterpret_cast(edge_list[type][id]+1);\n }\n\n lid_t Ngraph::degree(GraphEdge* edge) const {\n if (!isHyperGraph)\n return 2;\n if (edge==NULL)\n return 0;\n uintptr_t id = (uintptr_t)(edge)-1;\n etype type = id%num_types;\n id\/=num_types;\n return pin_degree_list[type][id+1]-pin_degree_list[type][id];\n }\n\n PinIterator* Ngraph::pins(GraphEdge* edge) const {\n uintptr_t id = (uintptr_t)(edge)-1;\n etype type = id%num_types;\n id\/=num_types;\n if (!isHyperGraph) {\n return new PinIterator(reinterpret_cast(u(edge)),\n reinterpret_cast((char*)(edge_list[type][id]+1)));\n }\n return new PinIterator((pin_list[type]+pin_degree_list[type][id]),\n pin_list[type]+pin_degree_list[type][id+1]);\n }\n\n void Ngraph::setEdgeWeights(std::vector& wgts, etype t) {\n assert(!edge_weights[t]);\n if (wgts.size()==0) {\n edge_weights[t] = new wgt_t[num_local_edges[t]];\n for (gid_t i=0;i"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: shapetransitionfactory.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2005-10-11 08:45:36 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifndef BOOST_BIND_HPP_INCLUDED\n#include \n#endif\n\n\nusing namespace ::com::sun::star;\n\nnamespace presentation {\nnamespace internal {\n\n\/***************************************************\n *** ***\n *** Shape Transition Effects ***\n *** ***\n ***************************************************\/\n\nnamespace {\n\nclass ClippingAnimation : public NumberAnimation\n{\npublic:\n ClippingAnimation(\n const ParametricPolyPolygonSharedPtr& rPolygon,\n const LayerManagerSharedPtr& rLayerManager,\n const TransitionInfo& rTransitionInfo,\n bool bDirectionForward,\n bool bModeIn );\n\n ~ClippingAnimation();\n\n \/\/ Animation interface\n \/\/ -------------------\n virtual void start( const AnimatableShapeSharedPtr& rShape,\n const ShapeAttributeLayerSharedPtr& rAttrLayer );\n virtual void end();\n\n \/\/ NumberAnimation interface\n \/\/ -----------------------\n virtual bool operator()( double nValue );\n virtual double getUnderlyingValue() const;\n\nprivate:\n void end_();\n\n AnimatableShapeSharedPtr mpShape;\n ShapeAttributeLayerSharedPtr mpAttrLayer;\n LayerManagerSharedPtr mpLayerManager;\n ClippingFunctor maClippingFunctor;\n bool mbSpriteActive;\n};\n\nClippingAnimation::ClippingAnimation(\n const ParametricPolyPolygonSharedPtr& rPolygon,\n const LayerManagerSharedPtr& rLayerManager,\n const TransitionInfo& rTransitionInfo,\n bool bDirectionForward,\n bool bModeIn ) :\n mpShape(),\n mpAttrLayer(),\n mpLayerManager( rLayerManager ),\n maClippingFunctor( rPolygon,\n rTransitionInfo,\n bDirectionForward,\n bModeIn ),\n mbSpriteActive(false)\n{\n ENSURE_AND_THROW(\n rLayerManager.get(),\n \"ClippingAnimation::ClippingAnimation(): Invalid LayerManager\" );\n}\n\nClippingAnimation::~ClippingAnimation()\n{\n end_();\n}\n\nvoid ClippingAnimation::start( const AnimatableShapeSharedPtr& rShape,\n const ShapeAttributeLayerSharedPtr& rAttrLayer )\n{\n OSL_ENSURE( !mpShape.get(),\n \"ClippingAnimation::start(): Shape already set\" );\n OSL_ENSURE( !mpAttrLayer.get(),\n \"ClippingAnimation::start(): Attribute layer already set\" );\n\n mpShape = rShape;\n mpAttrLayer = rAttrLayer;\n\n ENSURE_AND_THROW( rShape.get(),\n \"ClippingAnimation::start(): Invalid shape\" );\n ENSURE_AND_THROW( rAttrLayer.get(),\n \"ClippingAnimation::start(): Invalid attribute layer\" );\n\n mpShape = rShape;\n mpAttrLayer = rAttrLayer;\n\n if( !mbSpriteActive )\n {\n mpLayerManager->enterAnimationMode( mpShape );\n mbSpriteActive = true;\n }\n}\n\nvoid ClippingAnimation::end()\n{\n end_();\n}\n\nvoid ClippingAnimation::end_()\n{\n if( mbSpriteActive )\n {\n mbSpriteActive = false;\n mpLayerManager->leaveAnimationMode( mpShape );\n\n if( mpShape->isUpdateNecessary() )\n mpLayerManager->notifyShapeUpdate( mpShape );\n }\n}\n\nbool ClippingAnimation::operator()( double nValue )\n{\n ENSURE_AND_RETURN(\n mpAttrLayer.get() && mpShape.get(),\n \"ClippingAnimation::operator(): Invalid ShapeAttributeLayer\" );\n\n \/\/ set new clip\n mpAttrLayer->setClip( maClippingFunctor( nValue,\n mpShape->getUpdateArea().getRange() ) );\n\n if( mpShape->isUpdateNecessary() )\n mpLayerManager->notifyShapeUpdate( mpShape );\n\n return true;\n}\n\ndouble ClippingAnimation::getUnderlyingValue() const\n{\n ENSURE_AND_THROW(\n mpAttrLayer.get(),\n \"ClippingAnimation::getUnderlyingValue(): Invalid ShapeAttributeLayer\" );\n\n return 0.0; \/\/ though this should be used in concert with\n \/\/ ActivitiesFactory::createSimpleActivity, better\n \/\/ explicitely name our start value.\n \/\/ Permissible range for operator() above is [0,1]\n}\n\n} \/\/ anon namespace\n\n\nAnimationActivitySharedPtr TransitionFactory::createShapeTransition(\n const ActivitiesFactory::CommonParameters& rParms,\n const AnimatableShapeSharedPtr& rShape,\n const LayerManagerSharedPtr& rLayerManager,\n uno::Reference< animations::XTransitionFilter > const& xTransition )\n{\n return createShapeTransition( rParms,\n rShape,\n rLayerManager,\n xTransition,\n xTransition->getTransition(),\n xTransition->getSubtype() );\n}\n\nAnimationActivitySharedPtr TransitionFactory::createShapeTransition(\n const ActivitiesFactory::CommonParameters& rParms,\n const AnimatableShapeSharedPtr& rShape,\n const LayerManagerSharedPtr& rLayerManager,\n ::com::sun::star::uno::Reference<\n ::com::sun::star::animations::XTransitionFilter > const& xTransition,\n sal_Int16 nType,\n sal_Int16 nSubType )\n{\n ENSURE_AND_THROW(\n xTransition.is(),\n \"TransitionFactory::createShapeTransition(): Invalid XTransition\" );\n\n const TransitionInfo* pTransitionInfo(\n getTransitionInfo( nType, nSubType ) );\n\n AnimationActivitySharedPtr pGeneratedActivity;\n if( pTransitionInfo != NULL )\n {\n switch( pTransitionInfo->meTransitionClass )\n {\n default:\n case TransitionInfo::TRANSITION_INVALID:\n OSL_ENSURE( false,\n \"TransitionFactory::createShapeTransition(): Invalid transition type. \"\n \"Don't ask me for a 0 TransitionType, have no XTransitionFilter node instead!\" );\n return AnimationActivitySharedPtr();\n\n\n case TransitionInfo::TRANSITION_CLIP_POLYPOLYGON:\n {\n \/\/ generate parametric poly-polygon\n ParametricPolyPolygonSharedPtr pPoly(\n ParametricPolyPolygonFactory::createClipPolyPolygon(\n nType, nSubType ) );\n\n \/\/ create a clip activity from that\n pGeneratedActivity = ActivitiesFactory::createSimpleActivity(\n rParms,\n NumberAnimationSharedPtr(\n new ClippingAnimation(\n pPoly,\n rLayerManager,\n *pTransitionInfo,\n xTransition->getDirection(),\n xTransition->getMode() ) ),\n true );\n }\n break;\n\n case TransitionInfo::TRANSITION_SPECIAL:\n {\n switch( nType )\n {\n case animations::TransitionType::RANDOM:\n {\n \/\/ select randomly one of the effects from the\n \/\/ TransitionFactoryTable\n\n const TransitionInfo* pRandomTransitionInfo( getRandomTransitionInfo() );\n\n ENSURE_AND_THROW( pRandomTransitionInfo != NULL,\n \"TransitionFactory::createShapeTransition(): Got invalid random transition info\" );\n\n ENSURE_AND_THROW( pRandomTransitionInfo->mnTransitionType != animations::TransitionType::RANDOM,\n \"TransitionFactory::createShapeTransition(): Got random again for random input!\" );\n\n \/\/ and recurse\n pGeneratedActivity = createShapeTransition( rParms,\n rShape,\n rLayerManager,\n xTransition,\n pRandomTransitionInfo->mnTransitionType,\n pRandomTransitionInfo->mnTransitionSubType );\n }\n break;\n\n \/\/ TODO(F3): Implement slidewipe for shape\n case animations::TransitionType::SLIDEWIPE:\n {\n sal_Int16 nBarWipeSubType(0);\n bool bDirectionForward(true);\n\n \/\/ map slidewipe to BARWIPE, for now\n switch( nSubType )\n {\n case animations::TransitionSubType::FROMLEFT:\n nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;\n bDirectionForward = true;\n break;\n\n case animations::TransitionSubType::FROMRIGHT:\n nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;\n bDirectionForward = false;\n break;\n\n case animations::TransitionSubType::FROMTOP:\n nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;\n bDirectionForward = true;\n break;\n\n case animations::TransitionSubType::FROMBOTTOM:\n nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;\n bDirectionForward = false;\n break;\n\n default:\n ENSURE_AND_THROW( false,\n \"TransitionFactory::createShapeTransition(): Unexpected subtype for SLIDEWIPE\" );\n break;\n }\n\n \/\/ generate parametric poly-polygon\n ParametricPolyPolygonSharedPtr pPoly(\n ParametricPolyPolygonFactory::createClipPolyPolygon(\n animations::TransitionType::BARWIPE,\n nBarWipeSubType ) );\n\n \/\/ create a clip activity from that\n pGeneratedActivity = ActivitiesFactory::createSimpleActivity(\n rParms,\n NumberAnimationSharedPtr(\n new ClippingAnimation(\n pPoly,\n rLayerManager,\n *getTransitionInfo( animations::TransitionType::BARWIPE,\n nBarWipeSubType ),\n bDirectionForward,\n xTransition->getMode() ) ),\n true );\n }\n break;\n\n default:\n {\n \/\/ TODO(F1): Check whether there's anything left, anyway,\n \/\/ for _shape_ transitions. AFAIK, there are no special\n \/\/ effects for shapes...\n\n \/\/ for now, map all to fade effect\n pGeneratedActivity = ActivitiesFactory::createSimpleActivity(\n rParms,\n AnimationFactory::createNumberPropertyAnimation(\n ::rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM(\"Opacity\") ),\n rShape,\n rLayerManager ),\n xTransition->getMode() );\n }\n break;\n }\n }\n break;\n }\n }\n\n if( !pGeneratedActivity.get() )\n {\n \/\/ No animation generated, maybe no table entry for given\n \/\/ transition?\n OSL_TRACE(\n \"TransitionFactory::createShapeTransition(): Unknown type\/subtype (%d\/%d) \"\n \"combination encountered\",\n xTransition->getTransition(),\n xTransition->getSubtype() );\n OSL_ENSURE(\n false,\n \"TransitionFactory::createShapeTransition(): Unknown type\/subtype \"\n \"combination encountered\" );\n }\n\n return pGeneratedActivity;\n}\n\n}\n}\nINTEGRATION: CWS canvas02 (1.2.34); FILE MERGED 2005\/10\/17 12:21:07 thb 1.2.34.3: RESYNC: (1.3-1.4); FILE MERGED 2005\/10\/09 04:21:18 thb 1.2.34.2: RESYNC: (1.2-1.3); FILE MERGED 2005\/09\/01 14:01:29 thb 1.2.34.1: #122302# Using new Shape::getDOMBounds() method to determine size of the clip polygon, instead of the former getUpdateArea(). This is because, the sprite clip is transformed by the sprite transformation, which in turn contains the _full_ shape transform, relative to the DOM values\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: shapetransitionfactory.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: kz $ $Date: 2005-11-02 14:04:54 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifndef BOOST_BIND_HPP_INCLUDED\n#include \n#endif\n\n\nusing namespace ::com::sun::star;\n\nnamespace presentation {\nnamespace internal {\n\n\/***************************************************\n *** ***\n *** Shape Transition Effects ***\n *** ***\n ***************************************************\/\n\nnamespace {\n\nclass ClippingAnimation : public NumberAnimation\n{\npublic:\n ClippingAnimation(\n const ParametricPolyPolygonSharedPtr& rPolygon,\n const LayerManagerSharedPtr& rLayerManager,\n const TransitionInfo& rTransitionInfo,\n bool bDirectionForward,\n bool bModeIn );\n\n ~ClippingAnimation();\n\n \/\/ Animation interface\n \/\/ -------------------\n virtual void start( const AnimatableShapeSharedPtr& rShape,\n const ShapeAttributeLayerSharedPtr& rAttrLayer );\n virtual void end();\n\n \/\/ NumberAnimation interface\n \/\/ -----------------------\n virtual bool operator()( double nValue );\n virtual double getUnderlyingValue() const;\n\nprivate:\n void end_();\n\n AnimatableShapeSharedPtr mpShape;\n ShapeAttributeLayerSharedPtr mpAttrLayer;\n LayerManagerSharedPtr mpLayerManager;\n ClippingFunctor maClippingFunctor;\n bool mbSpriteActive;\n};\n\nClippingAnimation::ClippingAnimation(\n const ParametricPolyPolygonSharedPtr& rPolygon,\n const LayerManagerSharedPtr& rLayerManager,\n const TransitionInfo& rTransitionInfo,\n bool bDirectionForward,\n bool bModeIn ) :\n mpShape(),\n mpAttrLayer(),\n mpLayerManager( rLayerManager ),\n maClippingFunctor( rPolygon,\n rTransitionInfo,\n bDirectionForward,\n bModeIn ),\n mbSpriteActive(false)\n{\n ENSURE_AND_THROW(\n rLayerManager.get(),\n \"ClippingAnimation::ClippingAnimation(): Invalid LayerManager\" );\n}\n\nClippingAnimation::~ClippingAnimation()\n{\n end_();\n}\n\nvoid ClippingAnimation::start( const AnimatableShapeSharedPtr& rShape,\n const ShapeAttributeLayerSharedPtr& rAttrLayer )\n{\n OSL_ENSURE( !mpShape.get(),\n \"ClippingAnimation::start(): Shape already set\" );\n OSL_ENSURE( !mpAttrLayer.get(),\n \"ClippingAnimation::start(): Attribute layer already set\" );\n\n mpShape = rShape;\n mpAttrLayer = rAttrLayer;\n\n ENSURE_AND_THROW( rShape.get(),\n \"ClippingAnimation::start(): Invalid shape\" );\n ENSURE_AND_THROW( rAttrLayer.get(),\n \"ClippingAnimation::start(): Invalid attribute layer\" );\n\n mpShape = rShape;\n mpAttrLayer = rAttrLayer;\n\n if( !mbSpriteActive )\n {\n mpLayerManager->enterAnimationMode( mpShape );\n mbSpriteActive = true;\n }\n}\n\nvoid ClippingAnimation::end()\n{\n end_();\n}\n\nvoid ClippingAnimation::end_()\n{\n if( mbSpriteActive )\n {\n mbSpriteActive = false;\n mpLayerManager->leaveAnimationMode( mpShape );\n\n if( mpShape->isUpdateNecessary() )\n mpLayerManager->notifyShapeUpdate( mpShape );\n }\n}\n\nbool ClippingAnimation::operator()( double nValue )\n{\n ENSURE_AND_RETURN(\n mpAttrLayer.get() && mpShape.get(),\n \"ClippingAnimation::operator(): Invalid ShapeAttributeLayer\" );\n\n \/\/ set new clip\n mpAttrLayer->setClip( maClippingFunctor( nValue,\n mpShape->getDOMBounds().getRange() ) );\n\n if( mpShape->isUpdateNecessary() )\n mpLayerManager->notifyShapeUpdate( mpShape );\n\n return true;\n}\n\ndouble ClippingAnimation::getUnderlyingValue() const\n{\n ENSURE_AND_THROW(\n mpAttrLayer.get(),\n \"ClippingAnimation::getUnderlyingValue(): Invalid ShapeAttributeLayer\" );\n\n return 0.0; \/\/ though this should be used in concert with\n \/\/ ActivitiesFactory::createSimpleActivity, better\n \/\/ explicitely name our start value.\n \/\/ Permissible range for operator() above is [0,1]\n}\n\n} \/\/ anon namespace\n\n\nAnimationActivitySharedPtr TransitionFactory::createShapeTransition(\n const ActivitiesFactory::CommonParameters& rParms,\n const AnimatableShapeSharedPtr& rShape,\n const LayerManagerSharedPtr& rLayerManager,\n uno::Reference< animations::XTransitionFilter > const& xTransition )\n{\n return createShapeTransition( rParms,\n rShape,\n rLayerManager,\n xTransition,\n xTransition->getTransition(),\n xTransition->getSubtype() );\n}\n\nAnimationActivitySharedPtr TransitionFactory::createShapeTransition(\n const ActivitiesFactory::CommonParameters& rParms,\n const AnimatableShapeSharedPtr& rShape,\n const LayerManagerSharedPtr& rLayerManager,\n ::com::sun::star::uno::Reference<\n ::com::sun::star::animations::XTransitionFilter > const& xTransition,\n sal_Int16 nType,\n sal_Int16 nSubType )\n{\n ENSURE_AND_THROW(\n xTransition.is(),\n \"TransitionFactory::createShapeTransition(): Invalid XTransition\" );\n\n const TransitionInfo* pTransitionInfo(\n getTransitionInfo( nType, nSubType ) );\n\n AnimationActivitySharedPtr pGeneratedActivity;\n if( pTransitionInfo != NULL )\n {\n switch( pTransitionInfo->meTransitionClass )\n {\n default:\n case TransitionInfo::TRANSITION_INVALID:\n OSL_ENSURE( false,\n \"TransitionFactory::createShapeTransition(): Invalid transition type. \"\n \"Don't ask me for a 0 TransitionType, have no XTransitionFilter node instead!\" );\n return AnimationActivitySharedPtr();\n\n\n case TransitionInfo::TRANSITION_CLIP_POLYPOLYGON:\n {\n \/\/ generate parametric poly-polygon\n ParametricPolyPolygonSharedPtr pPoly(\n ParametricPolyPolygonFactory::createClipPolyPolygon(\n nType, nSubType ) );\n\n \/\/ create a clip activity from that\n pGeneratedActivity = ActivitiesFactory::createSimpleActivity(\n rParms,\n NumberAnimationSharedPtr(\n new ClippingAnimation(\n pPoly,\n rLayerManager,\n *pTransitionInfo,\n xTransition->getDirection(),\n xTransition->getMode() ) ),\n true );\n }\n break;\n\n case TransitionInfo::TRANSITION_SPECIAL:\n {\n switch( nType )\n {\n case animations::TransitionType::RANDOM:\n {\n \/\/ select randomly one of the effects from the\n \/\/ TransitionFactoryTable\n\n const TransitionInfo* pRandomTransitionInfo( getRandomTransitionInfo() );\n\n ENSURE_AND_THROW( pRandomTransitionInfo != NULL,\n \"TransitionFactory::createShapeTransition(): Got invalid random transition info\" );\n\n ENSURE_AND_THROW( pRandomTransitionInfo->mnTransitionType != animations::TransitionType::RANDOM,\n \"TransitionFactory::createShapeTransition(): Got random again for random input!\" );\n\n \/\/ and recurse\n pGeneratedActivity = createShapeTransition( rParms,\n rShape,\n rLayerManager,\n xTransition,\n pRandomTransitionInfo->mnTransitionType,\n pRandomTransitionInfo->mnTransitionSubType );\n }\n break;\n\n \/\/ TODO(F3): Implement slidewipe for shape\n case animations::TransitionType::SLIDEWIPE:\n {\n sal_Int16 nBarWipeSubType(0);\n bool bDirectionForward(true);\n\n \/\/ map slidewipe to BARWIPE, for now\n switch( nSubType )\n {\n case animations::TransitionSubType::FROMLEFT:\n nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;\n bDirectionForward = true;\n break;\n\n case animations::TransitionSubType::FROMRIGHT:\n nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;\n bDirectionForward = false;\n break;\n\n case animations::TransitionSubType::FROMTOP:\n nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;\n bDirectionForward = true;\n break;\n\n case animations::TransitionSubType::FROMBOTTOM:\n nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;\n bDirectionForward = false;\n break;\n\n default:\n ENSURE_AND_THROW( false,\n \"TransitionFactory::createShapeTransition(): Unexpected subtype for SLIDEWIPE\" );\n break;\n }\n\n \/\/ generate parametric poly-polygon\n ParametricPolyPolygonSharedPtr pPoly(\n ParametricPolyPolygonFactory::createClipPolyPolygon(\n animations::TransitionType::BARWIPE,\n nBarWipeSubType ) );\n\n \/\/ create a clip activity from that\n pGeneratedActivity = ActivitiesFactory::createSimpleActivity(\n rParms,\n NumberAnimationSharedPtr(\n new ClippingAnimation(\n pPoly,\n rLayerManager,\n *getTransitionInfo( animations::TransitionType::BARWIPE,\n nBarWipeSubType ),\n bDirectionForward,\n xTransition->getMode() ) ),\n true );\n }\n break;\n\n default:\n {\n \/\/ TODO(F1): Check whether there's anything left, anyway,\n \/\/ for _shape_ transitions. AFAIK, there are no special\n \/\/ effects for shapes...\n\n \/\/ for now, map all to fade effect\n pGeneratedActivity = ActivitiesFactory::createSimpleActivity(\n rParms,\n AnimationFactory::createNumberPropertyAnimation(\n ::rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM(\"Opacity\") ),\n rShape,\n rLayerManager ),\n xTransition->getMode() );\n }\n break;\n }\n }\n break;\n }\n }\n\n if( !pGeneratedActivity.get() )\n {\n \/\/ No animation generated, maybe no table entry for given\n \/\/ transition?\n OSL_TRACE(\n \"TransitionFactory::createShapeTransition(): Unknown type\/subtype (%d\/%d) \"\n \"combination encountered\",\n xTransition->getTransition(),\n xTransition->getSubtype() );\n OSL_ENSURE(\n false,\n \"TransitionFactory::createShapeTransition(): Unknown type\/subtype \"\n \"combination encountered\" );\n }\n\n return pGeneratedActivity;\n}\n\n}\n}\n<|endoftext|>"} {"text":"Update mongoUnsubscribeContext.cpp<|endoftext|>"} {"text":"added allreduct for testing<|endoftext|>"} {"text":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#pragma once\n\n\n#include \"begin_native.hpp\"\n#include \n#include \n#include \"end_native.hpp\"\n\nnamespace Apache\n{\n namespace Geode\n {\n namespace Client\n {\n using namespace System;\n using namespace apache::geode::util::chrono::duration;\n\n using ticks = std::chrono::duration>;\n \n class TimeUtils\n {\n public:\n template \n inline static _Duration TimeSpanToDurationCeil(TimeSpan timeSpan)\n {\n return _ceil<_Duration>(TimeSpanToDuration(timeSpan));\n }\n \n inline static ticks TimeSpanToDuration(TimeSpan timespan)\n {\n return ticks(timespan.Ticks);\n }\n\n inline static TimeSpan DurationToTimeSpan(ticks duration)\n {\n return TimeSpan::FromTicks(duration.count());\n } \n\n inline static DateTime TimePointToDateTime(std::chrono::system_clock::time_point timePoint) {\n using namespace std::chrono;\n auto t = duration_cast(timePoint.time_since_epoch());\n t += epochDifference;\n return DateTime(t.count());\n }\n\n inline static std::chrono::system_clock::time_point DateTimeToTimePoint(DateTime dateTime) {\n using namespace std::chrono;\n auto t = ticks(dateTime.Ticks);\n t -= epochDifference;\n return system_clock::time_point(t);\n }\n\n private:\n static constexpr auto epochDifference = ticks(621355968000000000);\n };\n } \/\/ namespace Client\n } \/\/ namespace Geode\n} \/\/ namespace Apache\n\nGEODE-4188: Fixes CLI inlude of internal duration header.\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#pragma once\n\n\n#include \"begin_native.hpp\"\n#include \n#include \n#include \"end_native.hpp\"\n\nnamespace Apache\n{\n namespace Geode\n {\n namespace Client\n {\n using namespace System;\n using namespace apache::geode::internal::chrono::duration;\n\n using ticks = std::chrono::duration>;\n \n class TimeUtils\n {\n public:\n template \n inline static _Duration TimeSpanToDurationCeil(TimeSpan timeSpan)\n {\n return _ceil<_Duration>(TimeSpanToDuration(timeSpan));\n }\n \n inline static ticks TimeSpanToDuration(TimeSpan timespan)\n {\n return ticks(timespan.Ticks);\n }\n\n inline static TimeSpan DurationToTimeSpan(ticks duration)\n {\n return TimeSpan::FromTicks(duration.count());\n } \n\n inline static DateTime TimePointToDateTime(std::chrono::system_clock::time_point timePoint) {\n using namespace std::chrono;\n auto t = duration_cast(timePoint.time_since_epoch());\n t += epochDifference;\n return DateTime(t.count());\n }\n\n inline static std::chrono::system_clock::time_point DateTimeToTimePoint(DateTime dateTime) {\n using namespace std::chrono;\n auto t = ticks(dateTime.Ticks);\n t -= epochDifference;\n return system_clock::time_point(t);\n }\n\n private:\n static constexpr auto epochDifference = ticks(621355968000000000);\n };\n } \/\/ namespace Client\n } \/\/ namespace Geode\n} \/\/ namespace Apache\n\n<|endoftext|>"} {"text":"\/\/ Copyright eeGeo Ltd (2012-2015), All Rights Reserved\r\n\r\n#include \"Search.h\"\r\n#include \"ICallback.h\"\r\n#include \"SearchResultModel.h\"\r\n#include \"YelpSearchQueryFactory.h\"\r\n#include \"YelpSearchQuery.h\"\r\n#include \"YelpSearchConstants.h\"\r\n#include \"YelpCategoryModel.h\"\n#include \"IAppCameraController.h\"\r\n#include \"CameraState.h\"\r\n#include \"RenderCamera.h\"\r\n#include \"urlencode.h\"\r\n#include \r\n#include \r\n\r\nnamespace ExampleApp\r\n{\r\n namespace Search\r\n {\r\n namespace Yelp\r\n {\r\n namespace SdkModel\r\n {\r\n namespace\r\n {\r\n \r\n std::string UrlGetParamsEncoder(const std::map& params)\r\n {\r\n std::string url;\r\n \r\n for (std::map::const_iterator it = params.begin();\r\n it != params.end();\r\n ++it)\r\n {\r\n url += it->first + \"=\" + urlencode(it->second, URLEncodeType::URLEncode_Everything) + \"&\";\r\n }\r\n \r\n \/\/remove trailing &\r\n url[url.length() - 1] = '\\0';\r\n \r\n return url;\r\n }\n \n int GetSearchRadius(ExampleApp::AppCamera::SdkModel::IAppCameraController& cameraController)\n {\n const float SearchRadiusMin = 50.0f;\n const float SearchRadiusMax = 40000.0f;\n double distanceToInterest = (cameraController.GetCameraState().InterestPointEcef() - cameraController.GetCameraState().LocationEcef()).Length();\n float radius = (distanceToInterest * Eegeo::Math::Tan(cameraController.GetRenderCamera().GetFOV()));\n return static_cast(Eegeo::Clamp(radius, SearchRadiusMin, SearchRadiusMax));\n }\r\n \r\n \r\n }\r\n YelpSearchQueryFactory::YelpSearchQueryFactory(\r\n const std::string& yelpApiKey,\r\n SdkModel::SearchTagToYelpCategoryMapper& searchTagToYelpCategoryMap,\r\n Eegeo::Web::IWebLoadRequestFactory& webRequestFactory,\n ExampleApp::AppCamera::SdkModel::IAppCameraController& cameraController)\r\n : m_webRequestFactory(webRequestFactory)\n , m_cameraController(cameraController)\r\n , m_yelpApiKey(yelpApiKey)\r\n , m_searchTagToYelpCategoryMap(searchTagToYelpCategoryMap)\r\n , m_apiUrl(\"https:\/\/api.yelp.com\/v3\/businesses\/search\")\r\n {\r\n\r\n }\r\n\r\n YelpSearchQueryFactory::~YelpSearchQueryFactory()\r\n {\r\n }\r\n\r\n SdkModel::IYelpSearchQuery* YelpSearchQueryFactory::CreateYelpSearchForQuery(const Search::SdkModel::SearchQuery& searchQuery,\r\n Eegeo::Helpers::ICallback0 &completionCallback)\r\n {\r\n std::string searchTerm = \"\";\r\n YelpCategoryModel categoryFilter { \"\", true };\r\n std::string searchLimit(\"20\");\r\n \r\n if (searchQuery.IsTag())\r\n {\r\n m_searchTagToYelpCategoryMap.TryGetBestYelpCategoryForSearchTag(searchQuery.Query(), categoryFilter);\r\n if(categoryFilter.skipYelpSearch == true)\r\n {\r\n searchLimit = \"0\";\r\n }\r\n }\r\n else\r\n {\r\n searchTerm = searchQuery.Query();\r\n }\r\n \r\n std::map params;\r\n std::stringstream conversionStream;\r\n \r\n conversionStream.setf(std::ios::fixed);\r\n conversionStream << std::setprecision(17)\r\n << searchQuery.Location().GetLatitudeInDegrees();\r\n std::string latitude = conversionStream.str();\r\n \r\n conversionStream.clear();\r\n conversionStream.str(\"\");\r\n conversionStream << std::setprecision(17)\r\n << searchQuery.Location().GetLongitudeInDegrees();\r\n std::string longitude = conversionStream.str();\r\n \r\n if (searchTerm.length() > 0)\r\n {\r\n params[\"term\"] = searchTerm;\r\n }\r\n\r\n if (categoryFilter.yelpCategoryFilter.length() > 0)\r\n {\r\n params[\"categories\"] = categoryFilter.yelpCategoryFilter;\r\n }\r\n params[\"latitude\"] = latitude;\r\n params[\"longitude\"] = longitude;\r\n params[\"limit\"] = searchLimit;\n \n int radius = GetSearchRadius(m_cameraController);\n conversionStream.clear();\n conversionStream.str(\"\");\n conversionStream << radius;\n params[\"radius\"] = conversionStream.str();\r\n \r\n std::stringstream requestUrl;\r\n requestUrl << m_apiUrl << \"?\" << UrlGetParamsEncoder(params);\r\n \r\n return Eegeo_NEW(YelpSearchQuery)(\r\n requestUrl.str(),\r\n m_yelpApiKey,\r\n completionCallback,\r\n m_webRequestFactory);\r\n }\r\n\r\n\r\n }\r\n }\r\n }\r\n}\r\nfix MPLY-10022 'Yelp searches only return results in the viewport rather than via radius'\/\/ Copyright eeGeo Ltd (2012-2015), All Rights Reserved\r\n\r\n#include \"Search.h\"\r\n#include \"ICallback.h\"\r\n#include \"SearchResultModel.h\"\r\n#include \"YelpSearchQueryFactory.h\"\r\n#include \"YelpSearchQuery.h\"\r\n#include \"YelpSearchConstants.h\"\r\n#include \"YelpCategoryModel.h\"\r\n#include \"IAppCameraController.h\"\r\n#include \"CameraState.h\"\r\n#include \"RenderCamera.h\"\r\n#include \"urlencode.h\"\r\n#include \r\n#include \r\n\r\nnamespace ExampleApp\r\n{\r\n namespace Search\r\n {\r\n namespace Yelp\r\n {\r\n namespace SdkModel\r\n {\r\n namespace\r\n {\r\n \r\n std::string UrlGetParamsEncoder(const std::map& params)\r\n {\r\n std::string url;\r\n \r\n for (std::map::const_iterator it = params.begin();\r\n it != params.end();\r\n ++it)\r\n {\r\n url += it->first + \"=\" + urlencode(it->second, URLEncodeType::URLEncode_Everything) + \"&\";\r\n }\r\n \r\n \/\/remove trailing &\r\n url[url.length() - 1] = '\\0';\r\n \r\n return url;\r\n }\r\n \r\n int GetSearchRadius(ExampleApp::AppCamera::SdkModel::IAppCameraController& cameraController)\r\n {\r\n const float SearchRadiusMin = 250.0f;\r\n const float SearchRadiusMax = 40000.0f;\r\n double distanceToInterest = (cameraController.GetCameraState().InterestPointEcef() - cameraController.GetCameraState().LocationEcef()).Length();\r\n float radius = (distanceToInterest * Eegeo::Math::Tan(cameraController.GetRenderCamera().GetFOV()));\r\n return static_cast(Eegeo::Clamp(radius, SearchRadiusMin, SearchRadiusMax));\r\n }\r\n \r\n \r\n }\r\n YelpSearchQueryFactory::YelpSearchQueryFactory(\r\n const std::string& yelpApiKey,\r\n SdkModel::SearchTagToYelpCategoryMapper& searchTagToYelpCategoryMap,\r\n Eegeo::Web::IWebLoadRequestFactory& webRequestFactory,\r\n ExampleApp::AppCamera::SdkModel::IAppCameraController& cameraController)\r\n : m_webRequestFactory(webRequestFactory)\r\n , m_cameraController(cameraController)\r\n , m_yelpApiKey(yelpApiKey)\r\n , m_searchTagToYelpCategoryMap(searchTagToYelpCategoryMap)\r\n , m_apiUrl(\"https:\/\/api.yelp.com\/v3\/businesses\/search\")\r\n {\r\n\r\n }\r\n\r\n YelpSearchQueryFactory::~YelpSearchQueryFactory()\r\n {\r\n }\r\n\r\n SdkModel::IYelpSearchQuery* YelpSearchQueryFactory::CreateYelpSearchForQuery(const Search::SdkModel::SearchQuery& searchQuery,\r\n Eegeo::Helpers::ICallback0 &completionCallback)\r\n {\r\n std::string searchTerm = \"\";\r\n YelpCategoryModel categoryFilter { \"\", true };\r\n std::string searchLimit(\"20\");\r\n \r\n if (searchQuery.IsTag())\r\n {\r\n m_searchTagToYelpCategoryMap.TryGetBestYelpCategoryForSearchTag(searchQuery.Query(), categoryFilter);\r\n if(categoryFilter.skipYelpSearch == true)\r\n {\r\n searchLimit = \"0\";\r\n }\r\n }\r\n else\r\n {\r\n searchTerm = searchQuery.Query();\r\n }\r\n \r\n std::map params;\r\n std::stringstream conversionStream;\r\n \r\n conversionStream.setf(std::ios::fixed);\r\n conversionStream << std::setprecision(17)\r\n << searchQuery.Location().GetLatitudeInDegrees();\r\n std::string latitude = conversionStream.str();\r\n \r\n conversionStream.clear();\r\n conversionStream.str(\"\");\r\n conversionStream << std::setprecision(17)\r\n << searchQuery.Location().GetLongitudeInDegrees();\r\n std::string longitude = conversionStream.str();\r\n \r\n if (searchTerm.length() > 0)\r\n {\r\n params[\"term\"] = searchTerm;\r\n }\r\n\r\n if (categoryFilter.yelpCategoryFilter.length() > 0)\r\n {\r\n params[\"categories\"] = categoryFilter.yelpCategoryFilter;\r\n }\r\n params[\"latitude\"] = latitude;\r\n params[\"longitude\"] = longitude;\r\n params[\"limit\"] = searchLimit;\r\n \r\n int radius = GetSearchRadius(m_cameraController);\r\n conversionStream.clear();\r\n conversionStream.str(\"\");\r\n conversionStream << radius;\r\n params[\"radius\"] = conversionStream.str();\r\n \r\n std::stringstream requestUrl;\r\n requestUrl << m_apiUrl << \"?\" << UrlGetParamsEncoder(params);\r\n \r\n return Eegeo_NEW(YelpSearchQuery)(\r\n requestUrl.str(),\r\n m_yelpApiKey,\r\n completionCallback,\r\n m_webRequestFactory);\r\n }\r\n\r\n\r\n }\r\n }\r\n }\r\n}\r\n<|endoftext|>"} {"text":"#ifndef STAN_MATH_PRIM_PROB_INV_WISHART_CHOLESKY_RNG_HPP\n#define STAN_MATH_PRIM_PROB_INV_WISHART_CHOLESKY_RNG_HPP\n\n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/** \\ingroup multivar_dists\n * Return a random Cholesky factor of a covariance matrix\n * of the specified dimensionality drawn\n * from the inverse Wishart distribution with the specified degrees of freedom\n * using the specified random number generator.\n *\n * @tparam RNG Random number generator type\n * @param[in] nu scalar degrees of freedom\n * @param[in] L_S lower Cholesky factor of the scale matrix\n * @param[in, out] rng random-number generator\n * @return random lower Cholesky factor drawn from the given inverse Wishart\n * distribution\n * @throw std::domain_error if the scale matrix is not a Cholesky factor\n * @throw std::domain_error if the degrees of freedom is greater than k - 1\n * where k is the dimension of L\n *\/\ntemplate \ninline Eigen::MatrixXd inv_wishart_cholesky_rng(double nu,\n const Eigen::MatrixXd& L_S,\n RNG& rng) {\n using Eigen::MatrixXd;\n static const char* function = \"inv_wishart_cholesky_rng\";\n index_type_t k = L_S.rows();\n check_greater(function, \"degrees of freedom > dims - 1\", nu, k - 1);\n check_positive(function, \"Cholesky Scale matrix\", L_S.diagonal());\n check_positive(function, \"columns of Cholesky Scale matrix\", L_S.cols());\n\n MatrixXd L_Sinv = mdivide_left_tri(L_S);\n return mdivide_left_tri(wishart_cholesky_rng(nu, L_Sinv, rng));\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\nUpdate inv_wishart_cholesky_rng.hpp#ifndef STAN_MATH_PRIM_PROB_INV_WISHART_CHOLESKY_RNG_HPP\n#define STAN_MATH_PRIM_PROB_INV_WISHART_CHOLESKY_RNG_HPP\n\n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/** \\ingroup multivar_dists\n * Return a random Cholesky factor of a covariance matrix\n * of the specified dimensionality drawn\n * from the inverse Wishart distribution with the specified degrees of freedom\n * using the specified random number generator.\n *\n * @tparam RNG Random number generator type\n * @param[in] nu scalar degrees of freedom\n * @param[in] L_S lower Cholesky factor of the scale matrix\n * @param[in, out] rng random-number generator\n * @return random lower Cholesky factor drawn from the given inverse Wishart\n * distribution\n * @throw std::domain_error if the scale matrix is not a Cholesky factor\n * @throw std::domain_error if the degrees of freedom is greater than k - 1\n * where k is the dimension of L\n *\/\ntemplate \ninline Eigen::MatrixXd inv_wishart_cholesky_rng(double nu,\n const Eigen::MatrixXd& L_S,\n RNG& rng) {\n using Eigen::MatrixXd;\n static const char* function = \"inv_wishart_cholesky_rng\";\n index_type_t k = L_S.rows();\n check_greater(function, \"degrees of freedom > dims - 1\", nu, k - 1);\n check_positive(function, \"Cholesky Scale matrix\", L_S.diagonal());\n check_positive(function, \"columns of Cholesky Scale matrix\", L_S.cols());\n\n MatrixXd L_Sinv = stan::math::mdivide_left_tri(L_S);\n return stan::math::mdivide_left_tri(wishart_cholesky_rng(nu, L_Sinv, rng));\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<|endoftext|>"} {"text":"#include \"regex.h\"\n\n#include \n#include \n#include \n\n#include \"document.h\"\n#include \"prolog.h\"\n#include \"pi.h\"\n#include \"doctype.h\"\n#include \"attribute.h\"\n#include \"element.h\"\n#include \"composite_element.h\"\n#include \"content.h\"\n\nstatic std::string schema_to_regex(CompositeElement *, std::map &);\nstatic std::string element_to_regex(Element *, std::map &);\nstatic std::string simple_element_to_regex(Element *, std::map &);\nstatic std::string complexe_type_to_regex(CompositeElement *, std::map &);\nstatic std::string choice_to_regex(CompositeElement *, std::map &);\nstatic std::string sequence_to_regex(CompositeElement *, std::map &, bool mixed=false);\n\nstatic const std::string re_string(\"[^<]*\");\nstatic const std::string re_date(\"[0-9]{4}-[0-9]{2}-[0-9]{2}(((\\\\+|-)[0-2][0-9]:[0-5][0-9])|Z)?\");\nstatic const std::string re_mixed(\"[^<]*\");\nstatic const std::string re_blank(\"\\\\s*\");\nstatic const std::string re_S(\"(\\\\s+)\");\nstatic const std::string re_Eq(re_S + \"?=\" + re_S + \"?\");\nstatic const std::string re_Name(\"[:A-Za-z\\\\200-\\\\377_][:A-Za-z\\\\200-\\\\377_0-9.-]*\");\nstatic const std::string re_AttValue(\"(\\\"[^<&\\\"]*\\\"|\\'[^<&\\\"]*\\')\");\nstatic const std::string re_Attr(re_Name + re_Eq + re_AttValue);\nstatic const std::string re_version_info(re_S + \"version\" + re_Eq + \"(\\\"1\\\\.[0-9]+\\\"|'1\\\\.[0-9]+')\");\nstatic const std::string re_encoding_decl(re_S + \"encoding\" + re_Eq + re_AttValue);\nstatic const std::string re_sd_decl(re_S + re_Attr);\nstatic const std::string re_xml_decl(\"<\\\\?xml(\" +\n re_version_info + \")?(\" +\n re_encoding_decl + \")?(\" +\n re_sd_decl + \")? ?\\\\?>\");\nstatic const std::string re_comment(\"\");\nstatic const std::string re_PI(\"<\\\\?\" + re_Name + \"(\" + re_S + re_Attr + \")*\\\\?>\");\nstatic const std::string re_Misc(\"(\" + re_comment + \"|\" + re_PI + \"|\" + re_S + \")\");\nstatic const std::string re_doctype_decl(\"\");\nstatic const std::string re_prolog(\"(\" + re_xml_decl + \")?\" + re_Misc + \"*(\" + re_doctype_decl + re_Misc + \"*)?\");\n\nstd::string xsd_to_regex(Document * doc)\n{\n \/\/ std::cout << \"xml : \" << re_xml_decl << std::endl;\n \/\/ std::cout << \"doc : \" << re_doctype_decl << std::endl;\n \/\/ std::cout << \"com : \" << re_comment << std::endl;\n \/\/ std::cout << \"pi : \" << re_PI << std::endl;\n \/\/ std::cout << \"pro : \" << re_prolog << std::endl;\n CompositeElement * root = dynamic_cast(doc->root());\n if (root == nullptr)\n return \"^$\";\n if (root->begin_tag() == \"xsd:schema\")\n {\n std::map refs;\n std::string re(\"^\" + re_prolog + schema_to_regex(root, refs) + re_Misc + \"*$\");\n std::cout << re << std::endl; \/\/ Mais oui c'est clair\n return re;\n }\n return \"^$\";\n}\n\nstd::string schema_to_regex(CompositeElement * s,\n std::map & refs)\n{\n std::string r;\n for (auto c : s->content())\n {\n auto e = dynamic_cast(c);\n if (e != nullptr && e->name() == \"xsd:element\")\n r += element_to_regex(e, refs) + \"|\";\n }\n r = r.substr(0, r.length() - 1);\n return \"(\" + r + \")\";\n}\n\nstd::string element_to_regex(Element * e,\n std::map & refs)\n{\n auto it_name = std::find_if(e->attributes().begin(), e->attributes().end(),\n [](Attribute * a) { return a->name() == \"name\"; });\n if (it_name == e->attributes().end())\n {\n auto it_ref = std::find_if(e->attributes().begin(), e->attributes().end(),\n [](Attribute * a) { return a->name() == \"ref\"; });\n if (it_ref == e->attributes().end())\n return \"\";\n\n auto ref = (*it_ref)->value();\n auto r = refs.find(ref);\n if (r == refs.end())\n return \"\";\n return r->second;\n }\n\n auto name = (*it_name)->value();\n const std::string begin(\"<\" + name + \"(\" + re_S + re_Attr + \")*\" + re_blank + \">\");\n const std::string end(\"<\/\" + name + re_blank + \">\");\n\n auto ce = dynamic_cast(e);\n if (ce != nullptr)\n {\n CompositeElement * cce = nullptr;\n if (ce->content().size() >= 1\n && (cce = dynamic_cast(ce->content().front())) != nullptr\n && cce->begin_tag() == \"xsd:complexType\")\n {\n std::string r(begin + complexe_type_to_regex(cce, refs) + end);\n refs[name] = r;\n return r;\n }\n }\n else\n {\n std::string r( begin + simple_element_to_regex(e, refs) + end);\n refs[name] = r;\n return r;\n }\n return \"\";\n}\n\nstd::string simple_element_to_regex(Element * e,\n std::map &)\n{\n auto it_type = std::find_if(e->attributes().begin(), e->attributes().end(),\n [](Attribute * a) { return a->name() == \"type\"; });\n if (it_type == e->attributes().end())\n return \"\";\n\n auto type = (*it_type)->value();\n if (type == \"xsd:string\")\n return re_string;\n else if (type == \"xsd:date\")\n return re_date;\n return \"\";\n}\n\nstd::string complexe_type_to_regex(CompositeElement * e,\n std::map & refs)\n{\n if (e->content().size() < 1)\n return \"\";\n\n CompositeElement * ce = dynamic_cast(e->content().front());\n if (ce == nullptr)\n return \"\";\n\n bool mixed = false;\n auto it_mixed = std::find_if(e->attributes().begin(), e->attributes().end(),\n [](Attribute * a) { return a->name() == \"mixed\"; });\n if (it_mixed != e->attributes().end()\n && (*it_mixed)->value() == \"true\")\n mixed = true;\n\n std::string s;\n if (ce->begin_tag() == \"xsd:choice\")\n {\n if (mixed)\n s += re_mixed;\n s += choice_to_regex(ce, refs);\n if (mixed)\n s += re_mixed;\n }\n else if (ce->begin_tag() == \"xsd:sequence\")\n {\n s += sequence_to_regex(ce, refs, mixed);\n }\n return s;\n}\n\nstd::string choice_to_regex(CompositeElement * e,\n std::map & refs)\n{\n std::string s;\n for (auto c : e->content())\n {\n auto ce = dynamic_cast(c);\n if (ce)\n {\n s += element_to_regex(ce, refs);\n if (c != e->content().back())\n s += \"|\";\n }\n }\n return re_blank + \"(\" + s + \")\" + re_blank;\n}\n\nstd::string sequence_to_regex(CompositeElement * e,\n std::map & refs, bool mixed)\n{\n std::string s;\n std::string space = mixed ? re_mixed : re_blank;\n for (auto c : e->content())\n {\n auto ce = dynamic_cast(c);\n if (ce)\n {\n auto it_maxOccurs = std::find_if(ce->attributes().begin(),\n ce->attributes().end(),\n [](Attribute * a) { return a->name() == \"maxOccurs\"; });\n std::string maxOccurs(\"1\");\n if (it_maxOccurs != ce->attributes().end())\n maxOccurs = (*it_maxOccurs)->value();\n s += \"(\" + element_to_regex(ce, refs) + \"){1,\" + maxOccurs + \"}\" + space;\n }\n }\n return space + s;\n}\n\nTous les tests passe pour p et v#include \"regex.h\"\n\n#include \n#include \n#include \n\n#include \"document.h\"\n#include \"prolog.h\"\n#include \"pi.h\"\n#include \"doctype.h\"\n#include \"attribute.h\"\n#include \"element.h\"\n#include \"composite_element.h\"\n#include \"content.h\"\n\nstatic std::string schema_to_regex(CompositeElement *, std::map &);\nstatic std::string element_to_regex(Element *, std::map &);\nstatic std::string simple_element_to_regex(Element *, std::map &);\nstatic std::string complexe_type_to_regex(CompositeElement *, std::map &);\nstatic std::string choice_to_regex(CompositeElement *, std::map &);\nstatic std::string sequence_to_regex(CompositeElement *, std::map &, bool mixed=false);\n\nstatic const std::string re_string(\"[^<]*\");\nstatic const std::string re_date(\"[0-9]{4}-[0-9]{2}-[0-9]{2}(((\\\\+|-)[0-2][0-9]:[0-5][0-9])|Z)?\");\nstatic const std::string re_mixed(\"[^<]*\");\nstatic const std::string re_blank(\"\\\\s*\");\nstatic const std::string re_S(\"(\\\\s+)\");\nstatic const std::string re_Eq(re_S + \"?=\" + re_S + \"?\");\nstatic const std::string re_Name(\"[:A-Za-z\\\\200-\\\\377_][:A-Za-z\\\\200-\\\\377_0-9.-]*\");\nstatic const std::string re_AttValue(\"(\\\"[^<&\\\"]*\\\"|\\'[^<&\\\"]*\\')\");\nstatic const std::string re_Attr(re_Name + re_Eq + re_AttValue);\nstatic const std::string re_version_info(re_S + \"version\" + re_Eq + \"(\\\"1\\\\.[0-9]+\\\"|'1\\\\.[0-9]+')\");\nstatic const std::string re_encoding_decl(re_S + \"encoding\" + re_Eq + re_AttValue);\nstatic const std::string re_sd_decl(re_S + re_Attr);\nstatic const std::string re_xml_decl(\"<\\\\?xml(\" +\n re_version_info + \")?(\" +\n re_encoding_decl + \")?(\" +\n re_sd_decl + \")? ?\\\\?>\");\nstatic const std::string re_comment(\"\");\nstatic const std::string re_PI(\"<\\\\?\" + re_Name + \"(\" + re_S + re_Attr + \")*\\\\?>\");\nstatic const std::string re_Misc(\"(\" + re_comment + \"|\" + re_PI + \"|\" + re_S + \")\");\nstatic const std::string re_doctype_decl(\"\");\nstatic const std::string re_prolog(\"(\" + re_xml_decl + \")?\" + re_Misc + \"*(\" + re_doctype_decl + re_Misc + \"*)?\");\n\nstd::string xsd_to_regex(Document * doc)\n{\n \/\/ std::cout << \"xml : \" << re_xml_decl << std::endl;\n \/\/ std::cout << \"doc : \" << re_doctype_decl << std::endl;\n \/\/ std::cout << \"com : \" << re_comment << std::endl;\n \/\/ std::cout << \"pi : \" << re_PI << std::endl;\n \/\/ std::cout << \"pro : \" << re_prolog << std::endl;\n CompositeElement * root = dynamic_cast(doc->root());\n if (root == nullptr)\n return \"^$\";\n if (root->begin_tag() == \"xsd:schema\")\n {\n std::map refs;\n std::string re(\"^\" + re_prolog + schema_to_regex(root, refs) + re_Misc + \"*$\");\n \/\/ std::cout << re << std::endl; \/\/ Mais oui c'est clair\n return re;\n }\n return \"^$\";\n}\n\nstd::string schema_to_regex(CompositeElement * s,\n std::map & refs)\n{\n std::string r;\n for (auto c : s->content())\n {\n auto e = dynamic_cast(c);\n if (e != nullptr && e->name() == \"xsd:element\")\n r += element_to_regex(e, refs) + \"|\";\n }\n r = r.substr(0, r.length() - 1);\n return \"(\" + r + \")\";\n}\n\nstd::string element_to_regex(Element * e,\n std::map & refs)\n{\n auto it_name = std::find_if(e->attributes().begin(), e->attributes().end(),\n [](Attribute * a) { return a->name() == \"name\"; });\n if (it_name == e->attributes().end())\n {\n auto it_ref = std::find_if(e->attributes().begin(), e->attributes().end(),\n [](Attribute * a) { return a->name() == \"ref\"; });\n if (it_ref == e->attributes().end())\n return \"\";\n\n auto ref = (*it_ref)->value();\n auto r = refs.find(ref);\n if (r == refs.end())\n return \"\";\n return r->second;\n }\n\n auto name = (*it_name)->value();\n const std::string begin(\"<\" + name + \"(\" + re_S + re_Attr + \")*\" + re_blank + \">\");\n const std::string end(\"<\/\" + name + re_blank + \">\");\n\n auto ce = dynamic_cast(e);\n if (ce != nullptr)\n {\n CompositeElement * cce = nullptr;\n if (ce->content().size() >= 1\n && (cce = dynamic_cast(ce->content().front())) != nullptr\n && cce->begin_tag() == \"xsd:complexType\")\n {\n std::string r(begin + complexe_type_to_regex(cce, refs) + end);\n refs[name] = r;\n return r;\n }\n }\n else\n {\n std::string r( begin + simple_element_to_regex(e, refs) + end);\n refs[name] = r;\n return r;\n }\n return \"\";\n}\n\nstd::string simple_element_to_regex(Element * e,\n std::map &)\n{\n auto it_type = std::find_if(e->attributes().begin(), e->attributes().end(),\n [](Attribute * a) { return a->name() == \"type\"; });\n if (it_type == e->attributes().end())\n return \"\";\n\n auto type = (*it_type)->value();\n if (type == \"xsd:string\")\n return re_string;\n else if (type == \"xsd:date\")\n return re_date;\n return \"\";\n}\n\nstd::string complexe_type_to_regex(CompositeElement * e,\n std::map & refs)\n{\n if (e->content().size() < 1)\n return \"\";\n\n CompositeElement * ce = dynamic_cast(e->content().front());\n if (ce == nullptr)\n return \"\";\n\n bool mixed = false;\n auto it_mixed = std::find_if(e->attributes().begin(), e->attributes().end(),\n [](Attribute * a) { return a->name() == \"mixed\"; });\n if (it_mixed != e->attributes().end()\n && (*it_mixed)->value() == \"true\")\n mixed = true;\n\n std::string s;\n if (ce->begin_tag() == \"xsd:choice\")\n {\n if (mixed)\n s += re_mixed;\n s += choice_to_regex(ce, refs);\n if (mixed)\n s += re_mixed;\n }\n else if (ce->begin_tag() == \"xsd:sequence\")\n {\n s += sequence_to_regex(ce, refs, mixed);\n }\n return s;\n}\n\nstd::string choice_to_regex(CompositeElement * e,\n std::map & refs)\n{\n std::string s;\n for (auto c : e->content())\n {\n auto ce = dynamic_cast(c);\n if (ce)\n {\n s += element_to_regex(ce, refs);\n if (c != e->content().back())\n s += \"|\";\n }\n }\n return re_blank + \"(\" + s + \")\" + re_blank;\n}\n\nstd::string sequence_to_regex(CompositeElement * e,\n std::map & refs, bool mixed)\n{\n std::string s;\n std::string space = mixed ? re_mixed : re_blank;\n for (auto c : e->content())\n {\n auto ce = dynamic_cast(c);\n if (ce)\n {\n auto it_maxOccurs = std::find_if(ce->attributes().begin(),\n ce->attributes().end(),\n [](Attribute * a) { return a->name() == \"maxOccurs\"; });\n std::string reg = element_to_regex(ce, refs) + space;\n if (it_maxOccurs != ce->attributes().end())\n {\n int maxOccurs = atoi((*it_maxOccurs)->value().c_str());\n for (int i(0); i < maxOccurs; i++) {\n s += reg;\n }\n }\n else\n {\n s += reg;\n }\n }\n }\n return space + s;\n}\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2017 deipi.com LLC and contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"test_serialise_list.h\"\n\n#include \"..\/src\/serialise_list.h\"\n#include \"utils.h\"\n\n\ninline int testing(const std::vector& strs) {\n\tauto serialised = StringList::serialise(strs.begin(), strs.end());\n\n\tint cont = 0;\n\n\tStringList s(serialised);\n\tif (s.size() != strs.size()) {\n\t\tL_ERR(nullptr, \"StringList is not working. Size: %zu Expected: %zu\", s.size(), strs.size());\n\t\t++cont;\n\t}\n\n\tstd::vector res;\n\tStringList::unserialise(serialised, std::back_inserter(res));\n\tif (res.size() != strs.size()) {\n\t\tL_ERR(nullptr, \"StringList::unserialise is not working. Size: %zu Expected: %zu\", res.size(), strs.size());\n\t\t++cont;\n\t}\n\n\tauto it_s = s.begin();\n\tauto it_r = res.begin();\n\tfor (const auto& elem : strs) {\n\t\tif (*it_s != elem || *it_r != elem) {\n\t\t\tL_ERR(nullptr, \"StringList is not working. Result: [%s, %s] Expected: %s\", it_s->c_str(), it_r->c_str(), elem.c_str());\n\t\t\t++cont;\n\t\t}\n\t\t++it_s;\n\t\t++it_r;\n\t}\n\n\treturn cont;\n}\n\n\ninline int testing(const std::vector& ptos) {\n\tauto serialised = CartesianList::serialise(ptos.begin(), ptos.end());\n\n\tint cont = 0;\n\n\tCartesianList s(serialised);\n\tif (s.size() != ptos.size()) {\n\t\tL_ERR(nullptr, \"CartesianList is not working. Size: %zu Expected: %zu\", s.size(), ptos.size());\n\t\t++cont;\n\t}\n\n\tstd::vector res;\n\tCartesianList::unserialise(serialised, std::back_inserter(res));\n\tif (res.size() != ptos.size()) {\n\t\tL_ERR(nullptr, \"CartesianList::unserialise is not working. Size: %zu Expected: %zu\", res.size(), ptos.size());\n\t\t++cont;\n\t}\n\n\tauto it_s = s.begin();\n\tauto it_r = res.begin();\n\tfor (const auto& elem : ptos) {\n\t\tif (*it_s != elem || *it_r != elem) {\n\t\t\tL_ERR(nullptr, \"CartesianList is not working. Result: [%s, %s] Expected: %s\", it_s->to_string().c_str(), it_r->to_string().c_str(), elem.to_string().c_str());\n\t\t\t++cont;\n\t\t}\n\t\t++it_s;\n\t\t++it_r;\n\t}\n\n\treturn cont;\n}\n\n\ninline int testing(const std::vector& ranges) {\n\tauto serialised = RangeList::serialise(ranges.begin(), ranges.end());\n\n\tint cont = 0;\n\n\tRangeList s(serialised);\n\tif (s.size() != ranges.size()) {\n\t\tL_ERR(nullptr, \"RangeList is not working. Size: %zu Expected: %zu\", s.size(), ranges.size());\n\t\t++cont;\n\t}\n\n\tstd::vector res;\n\tRangeList::unserialise(serialised, std::back_inserter(res));\n\tif (res.size() != ranges.size()) {\n\t\tL_ERR(nullptr, \"RangeList::unserialise is not working. Size: %zu Expected: %zu\", res.size(), ranges.size());\n\t\t++cont;\n\t}\n\n\tauto it_s = s.begin();\n\tauto it_r = res.begin();\n\tfor (const auto& elem : ranges) {\n\t\tif (*it_s != elem || *it_r != elem) {\n\t\t\tL_ERR(nullptr, \"RangeList is not working. Result: [%s, %s] Expected: %s\", it_s->to_string().c_str(), it_r->to_string().c_str(), elem.to_string().c_str());\n\t\t\t++cont;\n\t\t}\n\t\t++it_s;\n\t\t++it_r;\n\t}\n\n\treturn cont;\n}\n\n\nint test_StringList() {\n\tstd::vector strs;\n\n\tint cont = testing(strs);\n\n\tstrs.emplace_back(\"a\");\n\tcont += testing(strs);\n\n\tstrs.emplace_back(\"b\");\n\tstrs.emplace_back(\"c\");\n\tstrs.emplace_back(\"d\");\n\tstrs.emplace_back(\"e\");\n\tstrs.emplace_back(\"f\");\n\tstrs.emplace_back(\"g\");\n\tstrs.emplace_back(\"h\");\n\tstrs.emplace_back(\"i\");\n\tstrs.emplace_back(\"j\");\n\tcont += testing(strs);\n\n\tRETURN(cont);\n}\n\n\nint test_CartesianList() {\n\tstd::vector ptos;\n\n\tint cont = testing(ptos);\n\n\tptos.emplace_back(-1, 0, 0);\n\tcont += testing(ptos);\n\n\tptos.emplace_back(0.267261, 0.534522, 0.801784);\n\tptos.emplace_back(0.455842, 0.569803, 0.683763);\n\tptos.emplace_back(0.502571, 0.574367, 0.646162);\n\tptos.emplace_back(0.523424, 0.575766, 0.628109);\n\tptos.emplace_back(-0.267261, 0.534522, 0.801784);\n\tptos.emplace_back(0.455842, -0.569803, 0.683763);\n\tptos.emplace_back(0.502571, 0.574367, -0.646162);\n\tptos.emplace_back(-0.523424, -0.575766, -0.628109);\n\tcont += testing(ptos);\n\n\tRETURN(cont);\n}\n\n\nint test_RangeList() {\n\tstd::vector ranges;\n\n\tint cont = testing(ranges);\n\n\tranges.emplace_back(1, 10);\n\tcont += testing(ranges);\n\n\tranges.emplace_back(20, 30);\n\tranges.emplace_back(40, 50);\n\tranges.emplace_back(60, 70);\n\tranges.emplace_back(80, 90);\n\tranges.emplace_back(100, 110);\n\tranges.emplace_back(120, 130);\n\tranges.emplace_back(140, 150);\n\tcont += testing(ranges);\n\n\tRETURN(cont);\n}\nSerialise::range works for HTM with level 25\/*\n * Copyright (C) 2017 deipi.com LLC and contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"test_serialise_list.h\"\n\n#include \"..\/src\/serialise_list.h\"\n#include \"utils.h\"\n\n\ninline int testing(const std::vector& strs) {\n\tauto serialised = StringList::serialise(strs.begin(), strs.end());\n\n\tint cont = 0;\n\n\tStringList s(serialised);\n\tif (s.size() != strs.size()) {\n\t\tL_ERR(nullptr, \"StringList is not working. Size: %zu Expected: %zu\", s.size(), strs.size());\n\t\t++cont;\n\t}\n\n\tstd::vector res;\n\tStringList::unserialise(serialised, std::back_inserter(res));\n\tif (res.size() != strs.size()) {\n\t\tL_ERR(nullptr, \"StringList::unserialise is not working. Size: %zu Expected: %zu\", res.size(), strs.size());\n\t\t++cont;\n\t}\n\n\tauto it_s = s.begin();\n\tauto it_r = res.begin();\n\tfor (const auto& elem : strs) {\n\t\tif (*it_s != elem || *it_r != elem) {\n\t\t\tL_ERR(nullptr, \"StringList is not working. Result: [%s, %s] Expected: %s\", it_s->c_str(), it_r->c_str(), elem.c_str());\n\t\t\t++cont;\n\t\t}\n\t\t++it_s;\n\t\t++it_r;\n\t}\n\n\treturn cont;\n}\n\n\ninline int testing(const std::vector& ptos) {\n\tauto serialised = CartesianList::serialise(ptos.begin(), ptos.end());\n\n\tint cont = 0;\n\n\tCartesianList s(serialised);\n\tif (s.size() != ptos.size()) {\n\t\tL_ERR(nullptr, \"CartesianList is not working. Size: %zu Expected: %zu\", s.size(), ptos.size());\n\t\t++cont;\n\t}\n\n\tstd::vector res;\n\tCartesianList::unserialise(serialised, std::back_inserter(res));\n\tif (res.size() != ptos.size()) {\n\t\tL_ERR(nullptr, \"CartesianList::unserialise is not working. Size: %zu Expected: %zu\", res.size(), ptos.size());\n\t\t++cont;\n\t}\n\n\tauto it_s = s.begin();\n\tauto it_r = res.begin();\n\tfor (const auto& elem : ptos) {\n\t\tif (*it_s != elem || *it_r != elem) {\n\t\t\tL_ERR(nullptr, \"CartesianList is not working. Result: [%s, %s] Expected: %s\", it_s->to_string().c_str(), it_r->to_string().c_str(), elem.to_string().c_str());\n\t\t\t++cont;\n\t\t}\n\t\t++it_s;\n\t\t++it_r;\n\t}\n\n\treturn cont;\n}\n\n\ninline int testing(const std::vector& ranges) {\n\tauto serialised = RangeList::serialise(ranges.begin(), ranges.end());\n\n\tint cont = 0;\n\n\tRangeList s(serialised);\n\tif (s.size() != ranges.size()) {\n\t\tL_ERR(nullptr, \"RangeList is not working. Size: %zu Expected: %zu\", s.size(), ranges.size());\n\t\t++cont;\n\t}\n\n\tstd::vector res;\n\tRangeList::unserialise(serialised, std::back_inserter(res));\n\tif (res.size() != ranges.size()) {\n\t\tL_ERR(nullptr, \"RangeList::unserialise is not working. Size: %zu Expected: %zu\", res.size(), ranges.size());\n\t\t++cont;\n\t}\n\n\tauto it_s = s.begin();\n\tauto it_r = res.begin();\n\tfor (const auto& elem : ranges) {\n\t\tif (*it_s != elem || *it_r != elem) {\n\t\t\tL_ERR(nullptr, \"RangeList is not working. Result: [%s, %s] Expected: %s\", it_s->to_string().c_str(), it_r->to_string().c_str(), elem.to_string().c_str());\n\t\t\t++cont;\n\t\t}\n\t\t++it_s;\n\t\t++it_r;\n\t}\n\n\treturn cont;\n}\n\n\nint test_StringList() {\n\tstd::vector strs;\n\n\tint cont = testing(strs);\n\n\tstrs.emplace_back(\"a\");\n\tcont += testing(strs);\n\n\tstrs.emplace_back(\"b\");\n\tstrs.emplace_back(\"c\");\n\tstrs.emplace_back(\"d\");\n\tstrs.emplace_back(\"e\");\n\tstrs.emplace_back(\"f\");\n\tstrs.emplace_back(\"g\");\n\tstrs.emplace_back(\"h\");\n\tstrs.emplace_back(\"i\");\n\tstrs.emplace_back(\"j\");\n\tcont += testing(strs);\n\n\tRETURN(cont);\n}\n\n\nint test_CartesianList() {\n\tstd::vector ptos;\n\n\tint cont = testing(ptos);\n\n\tptos.emplace_back(-1, 0, 0);\n\tcont += testing(ptos);\n\n\tptos.emplace_back(0.267261, 0.534522, 0.801784);\n\tptos.emplace_back(0.455842, 0.569803, 0.683763);\n\tptos.emplace_back(0.502571, 0.574367, 0.646162);\n\tptos.emplace_back(0.523424, 0.575766, 0.628109);\n\tptos.emplace_back(-0.267261, 0.534522, 0.801784);\n\tptos.emplace_back(0.455842, -0.569803, 0.683763);\n\tptos.emplace_back(0.502571, 0.574367, -0.646162);\n\tptos.emplace_back(-0.523424, -0.575766, -0.628109);\n\tcont += testing(ptos);\n\n\tRETURN(cont);\n}\n\n\nint test_RangeList() {\n\tstd::vector ranges;\n\n\tint cont = testing(ranges);\n\n\t\/\/ Small level range.\n\tranges.emplace_back(14363263991021568, 14363298350759935);\n\tcont += testing(ranges);\n\n\tranges.emplace_back(14363315530629120, 14363332710498303);\n\tranges.emplace_back(14363367070236672, 14363384250105855);\n\tranges.emplace_back(14363401429975040, 14363418609844223);\n\tranges.emplace_back(14363607588405248, 14363624768274431);\n\tranges.emplace_back(14363641948143616, 14363676307881983);\n\tranges.emplace_back(14363745027358720, 14363813746835455);\n\tranges.emplace_back(14363899646181376, 14363916826050559);\n\tranges.emplace_back(14363968365658112, 14364019905265663);\n\tcont += testing(ranges);\n\n\tRETURN(cont);\n}\n<|endoftext|>"} {"text":"#include \"sipclienttransaction.h\"\n\n#include \"siptransactionuser.h\"\n\n#include \n\n\/\/ 2 seconds for a SIP reply\nconst unsigned int TIMEOUT = 2000;\n\/\/ 1 minute for the user to react\nconst unsigned int INVITE_TIMEOUT = 60000;\n\nSIPClientTransaction::SIPClientTransaction():\n ongoingTransactionType_(SIP_UNKNOWN_REQUEST),\n connected_(false),\n sessionID_(0),\n state_(INACTIVE),\n pendingRequest_(SIP_UNKNOWN_REQUEST),\n transactionUser_(NULL)\n{}\n\nvoid SIPClientTransaction::init(SIPTransactionUser* tu, uint32_t sessionID)\n{\n Q_ASSERT(sessionID != 0);\n Q_ASSERT(tu);\n transactionUser_ = tu;\n sessionID_ = sessionID;\n requestTimer_.setSingleShot(true);\n connect(&requestTimer_, SIGNAL(timeout()), this, SLOT(requestTimeOut()));\n}\n\n\n\/\/processes incoming response\nbool SIPClientTransaction::processResponse(SIPResponse &response)\n{\n Q_ASSERT(sessionID_ != 0);\n Q_ASSERT(transactionUser_ != NULL);\n\n qDebug() << \"Client starts processing response\";\n if(!sessionID_ || transactionUser_ == NULL)\n {\n qWarning() << \"WARNING: SIP Client Transaction not initialized.\";\n return true;\n }\n\n int responseCode = response.type;\n\n if(responseCode >= 300 && responseCode <= 399)\n {\n \/\/ TODO: 8.1.3.4 Processing 3xx Responses in RFC 3261\n qDebug() << \"Got a redirection response Code. Not implemented!\";\n return false;\n }\n\n if(responseCode >= 400 && responseCode <= 499)\n {\n \/\/ TODO: 8.1.3.5 Processing 4xx Responses in RFC 3261\n qDebug() << \"Got a Client Failure Response Code. Not implemented!\";\n\n \/\/ TODO: if the response is 481 or 408, terminate dialog\n return false;\n }\n\n if(responseCode >= 500 && responseCode <= 599)\n {\n qDebug() << \"Got a Server Failure Response Code. Not implemented!\";\n return false;\n }\n\n\n if(ongoingTransactionType_ == INVITE)\n {\n if(responseCode >= 600 && responseCode <= 699)\n {\n qDebug() << \"Got a Global Failure Response Code for INVITE\";\n transactionUser_->callRejected(sessionID_);\n return false;\n }\n else\n {\n switch (response.type) {\n case SIP_RINGING:\n transactionUser_->callRinging(sessionID_);\n break;\n case SIP_OK:\n \/\/ the sdp has been check by transaction layer before this.\n requestSender(ACK);\n transactionUser_->callNegotiated(sessionID_);\n break;\n default:\n break;\n }\n }\n }\n if(responseCode >= 200)\n {\n ongoingTransactionType_ = SIP_UNKNOWN_REQUEST;\n }\n\n return true;\n}\n\n\nbool SIPClientTransaction::startCall()\n{\n qDebug() << \"Starting a call and sending an INVITE in session\";\n Q_ASSERT(sessionID_ != 0);\n if(!sessionID_)\n {\n qWarning() << \"WARNING: SIP Client Transaction not initialized\";\n return false;\n }\n\n if(state_ == INACTIVE)\n {\n requestSender(INVITE);\n }\n else\n {\n qWarning() << \"WARNING: Trying to start a call, when it is already running or negotiating:\" << state_;\n return false;\n }\n\n return true;\n}\n\nvoid SIPClientTransaction::endCall()\n{\n if(state_ != RUNNNING)\n {\n qDebug() << \"WARNING: Trying to end a non-active call!\";\n return;\n }\n\n requestSender(BYE);\n}\n\nvoid SIPClientTransaction::registerToServer()\n{\n requestSender(REGISTER);\n}\n\nvoid SIPClientTransaction::connectionReady(bool ready)\n{\n connected_ = ready;\n if(pendingRequest_ != SIP_UNKNOWN_REQUEST)\n {\n requestSender(pendingRequest_);\n pendingRequest_ = SIP_UNKNOWN_REQUEST;\n }\n}\n\nvoid SIPClientTransaction::getRequestMessageInfo(RequestType type,\n std::shared_ptr& outMessage)\n{\n outMessage = std::shared_ptr (new SIPMessageInfo);\n\n if(type == ACK)\n {\n outMessage->transactionRequest = INVITE;\n }\n else if(type == CANCEL)\n {\n outMessage->transactionRequest = ongoingTransactionType_;\n }\n else\n {\n outMessage->transactionRequest = type;\n }\n\n outMessage->dialog = NULL;\n outMessage->maxForwards = 71;\n outMessage->version = \"2.0\";\n outMessage->cSeq = 0; \/\/ invalid, should be set in dialog\n}\n\nvoid SIPClientTransaction::requestSender(RequestType type)\n{\n if(!connected_)\n {\n qDebug() << \"Added a pending request:\" << type;\n pendingRequest_ = type;\n }\n else\n {\n qDebug() << \"Client starts sending a request:\" << type;\n ongoingTransactionType_ = type;\n emit sendRequest(sessionID_, type);\n\n if(type != INVITE)\n {\n qDebug() << \"Request timeout set to: \" << TIMEOUT;\n requestTimer_.start(TIMEOUT);\n }\n else\n {\n qDebug() << \"INVITE timeout set to: \" << INVITE_TIMEOUT;\n requestTimer_.start(INVITE_TIMEOUT);\n }\n }\n}\n\nvoid SIPClientTransaction::requestTimeOut()\n{\n qDebug() << \"No response. Request timed out\";\n\n if(ongoingTransactionType_ == INVITE)\n {\n sendRequest(sessionID_, BYE);\n \/\/ TODO tell user we have failed\n }\n\n requestSender(CANCEL);\n transactionUser_->callRejected(sessionID_);\n ongoingTransactionType_ = SIP_UNKNOWN_REQUEST;\n}\nFixed bunch of issues with timeout triggering too soon or needlessly.#include \"sipclienttransaction.h\"\n\n#include \"siptransactionuser.h\"\n\n#include \n\n\/\/ 2 seconds for a SIP reply\nconst unsigned int TIMEOUT = 2000;\n\/\/ 1 minute for the user to react\nconst unsigned int INVITE_TIMEOUT = 60000;\n\nSIPClientTransaction::SIPClientTransaction():\n ongoingTransactionType_(SIP_UNKNOWN_REQUEST),\n connected_(false),\n sessionID_(0),\n state_(INACTIVE),\n pendingRequest_(SIP_UNKNOWN_REQUEST),\n transactionUser_(NULL)\n{}\n\nvoid SIPClientTransaction::init(SIPTransactionUser* tu, uint32_t sessionID)\n{\n Q_ASSERT(sessionID != 0);\n Q_ASSERT(tu);\n transactionUser_ = tu;\n sessionID_ = sessionID;\n requestTimer_.setSingleShot(true);\n connect(&requestTimer_, SIGNAL(timeout()), this, SLOT(requestTimeOut()));\n}\n\n\n\/\/processes incoming response\nbool SIPClientTransaction::processResponse(SIPResponse &response)\n{\n Q_ASSERT(sessionID_ != 0);\n Q_ASSERT(transactionUser_ != NULL);\n\n qDebug() << \"Client starts processing response\";\n if(!sessionID_ || transactionUser_ == NULL)\n {\n qWarning() << \"WARNING: SIP Client Transaction not initialized.\";\n return true;\n }\n\n int responseCode = response.type;\n\n if(responseCode >= 100 && responseCode <= 199)\n {\n qDebug() << \"Got provisional response. Restarting timer.\";\n if(response.message->transactionRequest == INVITE)\n {\n requestTimer_.start(INVITE_TIMEOUT);\n }\n else\n {\n requestTimer_.start(TIMEOUT);\n }\n }\n else\n {\n qDebug() << \"Got response. Stopping timout.\";\n requestTimer_.stop();\n }\n\n if(responseCode >= 300 && responseCode <= 399)\n {\n \/\/ TODO: 8.1.3.4 Processing 3xx Responses in RFC 3261\n qDebug() << \"Got a redirection response Code. Not implemented!\";\n return false;\n }\n\n if(responseCode >= 400 && responseCode <= 499)\n {\n \/\/ TODO: 8.1.3.5 Processing 4xx Responses in RFC 3261\n qDebug() << \"Got a Client Failure Response Code. Not implemented!\";\n\n \/\/ TODO: if the response is 481 or 408, terminate dialog\n return false;\n }\n\n if(responseCode >= 500 && responseCode <= 599)\n {\n qDebug() << \"Got a Server Failure Response Code. Not implemented!\";\n return false;\n }\n\n\n if(ongoingTransactionType_ == INVITE)\n {\n if(responseCode >= 600 && responseCode <= 699)\n {\n qDebug() << \"Got a Global Failure Response Code for INVITE\";\n transactionUser_->callRejected(sessionID_);\n return false;\n }\n else\n {\n switch (response.type) {\n case SIP_RINGING:\n transactionUser_->callRinging(sessionID_);\n break;\n case SIP_OK:\n \/\/ the sdp has been check by transaction layer before this.\n requestSender(ACK);\n transactionUser_->callNegotiated(sessionID_);\n break;\n default:\n break;\n }\n }\n }\n if(responseCode >= 200)\n {\n ongoingTransactionType_ = SIP_UNKNOWN_REQUEST;\n }\n\n return true;\n}\n\n\nbool SIPClientTransaction::startCall()\n{\n qDebug() << \"Starting a call and sending an INVITE in session\";\n Q_ASSERT(sessionID_ != 0);\n if(!sessionID_)\n {\n qWarning() << \"WARNING: SIP Client Transaction not initialized\";\n return false;\n }\n\n if(state_ == INACTIVE)\n {\n requestSender(INVITE);\n }\n else\n {\n qWarning() << \"WARNING: Trying to start a call, when it is already running or negotiating:\" << state_;\n return false;\n }\n\n return true;\n}\n\nvoid SIPClientTransaction::endCall()\n{\n if(state_ != RUNNNING)\n {\n qDebug() << \"WARNING: Trying to end a non-active call!\";\n return;\n }\n\n requestSender(BYE);\n}\n\nvoid SIPClientTransaction::registerToServer()\n{\n requestSender(REGISTER);\n}\n\nvoid SIPClientTransaction::connectionReady(bool ready)\n{\n connected_ = ready;\n if(pendingRequest_ != SIP_UNKNOWN_REQUEST)\n {\n requestSender(pendingRequest_);\n pendingRequest_ = SIP_UNKNOWN_REQUEST;\n }\n}\n\nvoid SIPClientTransaction::getRequestMessageInfo(RequestType type,\n std::shared_ptr& outMessage)\n{\n outMessage = std::shared_ptr (new SIPMessageInfo);\n\n if(type == ACK)\n {\n outMessage->transactionRequest = INVITE;\n }\n else if(type == CANCEL)\n {\n outMessage->transactionRequest = ongoingTransactionType_;\n }\n else\n {\n outMessage->transactionRequest = type;\n }\n\n outMessage->dialog = NULL;\n outMessage->maxForwards = 71;\n outMessage->version = \"2.0\";\n outMessage->cSeq = 0; \/\/ invalid, should be set in dialog\n}\n\nvoid SIPClientTransaction::requestSender(RequestType type)\n{\n if(!connected_)\n {\n qDebug() << \"Added a pending request:\" << type;\n pendingRequest_ = type;\n }\n else\n {\n qDebug() << \"Client starts sending a request:\" << type;\n ongoingTransactionType_ = type;\n emit sendRequest(sessionID_, type);\n\n if(type != INVITE && type != CANCEL && type != ACK)\n {\n qDebug() << \"Request timeout set to: \" << TIMEOUT;\n requestTimer_.start(TIMEOUT);\n }\n else if(type == INVITE)\n {\n qDebug() << \"INVITE timeout set to: \" << INVITE_TIMEOUT;\n requestTimer_.start(INVITE_TIMEOUT);\n }\n else\n {\n requestTimer_.stop();\n }\n }\n}\n\nvoid SIPClientTransaction::requestTimeOut()\n{\n qDebug() << \"No response. Request timed out\";\n\n if(ongoingTransactionType_ == INVITE)\n {\n sendRequest(sessionID_, BYE);\n \/\/ TODO tell user we have failed\n }\n\n requestSender(CANCEL);\n requestTimer_.stop();\n transactionUser_->callRejected(sessionID_);\n ongoingTransactionType_ = SIP_UNKNOWN_REQUEST;\n}\n<|endoftext|>"} {"text":"\/*-------------------------------------------------------------------------\n * Vulkan Conformance Tests\n * ------------------------\n *\n * Copyright (c) 2016 The Khronos Group Inc.\n * Copyright (c) 2016 Samsung Electronics Co., Ltd.\n * Copyright (c) 2014 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\/*!\n * \\file\n * \\brief Compressed texture tests.\n *\/\/*--------------------------------------------------------------------*\/\n\n#include \"vktTextureCompressedFormatTests.hpp\"\n\n#include \"deString.h\"\n#include \"deStringUtil.hpp\"\n#include \"tcuCompressedTexture.hpp\"\n#include \"tcuTexture.hpp\"\n#include \"tcuTextureUtil.hpp\"\n#include \"vkImageUtil.hpp\"\n#include \"vktTestGroupUtil.hpp\"\n#include \"vktTextureTestUtil.hpp\"\n#include \n#include \n\nnamespace vkt\n{\nnamespace texture\n{\nnamespace\n{\n\nusing namespace vk;\nusing namespace glu::TextureTestUtil;\nusing namespace texture::util;\n\nusing std::string;\nusing std::vector;\nusing tcu::Sampler;\nusing tcu::TestLog;\n\nstruct Compressed2DTestParameters : public Texture2DTestCaseParameters\n{\n};\n\nclass Compressed2DTestInstance : public TestInstance\n{\npublic:\n\ttypedef Compressed2DTestParameters\tParameterType;\n\n\t\t\t\t\t\t\t\t\t\tCompressed2DTestInstance\t(Context&\t\t\t\tcontext,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t const ParameterType&\ttestParameters);\n\ttcu::TestStatus\t\t\t\t\t\titerate\t\t\t\t\t\t(void);\n\nprivate:\n\t\t\t\t\t\t\t\t\t\tCompressed2DTestInstance\t(const Compressed2DTestInstance& other);\n\tCompressed2DTestInstance&\t\t\toperator=\t\t\t\t\t(const Compressed2DTestInstance& other);\n\n\tconst ParameterType&\t\t\t\tm_testParameters;\n\tconst tcu::CompressedTexFormat\t\tm_compressedFormat;\n\tTestTexture2DSp\t\t\t\t\t\tm_texture;\n\tTextureRenderer\t\t\t\t\t\tm_renderer;\n};\n\nCompressed2DTestInstance::Compressed2DTestInstance (Context&\t\t\t\tcontext,\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst ParameterType&\ttestParameters)\n\t: TestInstance\t\t\t(context)\n\t, m_testParameters\t\t(testParameters)\n\t, m_compressedFormat\t(mapVkCompressedFormat(testParameters.format))\n\t, m_texture\t\t\t\t(TestTexture2DSp(new pipeline::TestTexture2D(m_compressedFormat, testParameters.width, testParameters.height)))\n\t, m_renderer\t\t\t(context, testParameters.sampleCount, testParameters.width, testParameters.height)\n{\n\tm_renderer.add2DTexture(m_texture);\n}\n\ntcu::TestStatus Compressed2DTestInstance::iterate (void)\n{\n\ttcu::TestLog&\t\t\t\t\tlog\t\t\t\t= m_context.getTestContext().getLog();\n\tconst pipeline::TestTexture2D&\ttexture\t\t\t= m_renderer.get2DTexture(0);\n\tconst tcu::TextureFormat\t\ttextureFormat\t= texture.getTextureFormat();\n\tconst tcu::TextureFormatInfo\tformatInfo\t\t= tcu::getTextureFormatInfo(textureFormat);\n\n\tReferenceParams\t\t\t\t\tsampleParams\t(TEXTURETYPE_2D);\n\ttcu::Surface\t\t\t\t\trendered\t\t(m_renderer.getRenderWidth(), m_renderer.getRenderHeight());\n\tvector\t\t\t\t\ttexCoord;\n\n\t\/\/ Setup params for reference.\n\tsampleParams.sampler\t\t\t= util::createSampler(m_testParameters.wrapS, m_testParameters.wrapT, m_testParameters.minFilter, m_testParameters.magFilter);\n\tsampleParams.samplerType\t\t= SAMPLERTYPE_FLOAT;\n\tsampleParams.lodMode\t\t\t= LODMODE_EXACT;\n\tsampleParams.colorBias\t\t\t= formatInfo.lookupBias;\n\tsampleParams.colorScale\t\t\t= formatInfo.lookupScale;\n\n\tlog << TestLog::Message << \"Compare reference value = \" << sampleParams.ref << TestLog::EndMessage;\n\n\t\/\/ Compute texture coordinates.\n\tcomputeQuadTexCoord2D(texCoord, tcu::Vec2(0.0f, 0.0f), tcu::Vec2(1.0f, 1.0f));\n\n\tm_renderer.renderQuad(rendered, 0, &texCoord[0], sampleParams);\n\n\t\/\/ Compute reference.\n\tconst tcu::IVec4\t\tformatBitDepth\t= getTextureFormatBitDepth(vk::mapVkFormat(VK_FORMAT_R8G8B8A8_UNORM));\n\tconst tcu::PixelFormat\tpixelFormat\t\t(formatBitDepth[0], formatBitDepth[1], formatBitDepth[2], formatBitDepth[3]);\n\ttcu::Surface\t\t\treferenceFrame\t(m_renderer.getRenderWidth(), m_renderer.getRenderHeight());\n\tsampleTexture(tcu::SurfaceAccess(referenceFrame, pixelFormat), m_texture->getTexture(), &texCoord[0], sampleParams);\n\n\t\/\/ Compare and log.\n\tconst bool isOk = compareImages(log, referenceFrame, rendered, pixelFormat.getColorThreshold() + tcu::RGBA(1, 1, 1, 1));\n\n\treturn isOk ? tcu::TestStatus::pass(\"Pass\") : tcu::TestStatus::fail(\"Image verification failed\");\n}\n\nvoid populateTextureCompressedFormatTests (tcu::TestCaseGroup* compressedTextureTests)\n{\n\ttcu::TestContext&\ttestCtx\t= compressedTextureTests->getTestContext();\n\n\t\/\/ ETC2 and EAC compressed formats.\n\tconst struct {\n\t\tconst VkFormat\tformat;\n\t} etc2Formats[] =\n\t{\n\t\t{ VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK\t\t},\n\t\t{ VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK\t\t},\n\t\t{ VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK\t},\n\t\t{ VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK\t},\n\t\t{ VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK\t},\n\t\t{ VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK\t},\n\n\t\t{ VK_FORMAT_EAC_R11_UNORM_BLOCK\t\t\t},\n\t\t{ VK_FORMAT_EAC_R11_SNORM_BLOCK\t\t\t},\n\t\t{ VK_FORMAT_EAC_R11G11_UNORM_BLOCK\t\t},\n\t\t{ VK_FORMAT_EAC_R11G11_SNORM_BLOCK\t\t},\n\t};\n\n\tconst struct {\n\t\tconst int\twidth;\n\t\tconst int\theight;\n\t\tconst char*\tname;\n\t} sizes[] =\n\t{\n\t\t{ 128, 64, \"pot\" },\n\t\t{ 51, 65, \"npot\" },\n\t};\n\n\tfor (int sizeNdx = 0; sizeNdx < DE_LENGTH_OF_ARRAY(sizes); sizeNdx++)\n\tfor (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(etc2Formats); formatNdx++)\n\t{\n\t\tconst string\tformatStr\t= de::toString(getFormatStr(etc2Formats[formatNdx].format));\n\t\tconst string\tnameBase\t= de::toLower(formatStr.substr(10));\n\n\t\tCompressed2DTestParameters\ttestParameters;\n\t\ttestParameters.format\t\t= etc2Formats[formatNdx].format;\n\t\ttestParameters.width\t\t= sizes[sizeNdx].width;\n\t\ttestParameters.height\t\t= sizes[sizeNdx].height;\n\t\ttestParameters.programs.push_back(PROGRAM_2D_FLOAT);\n\n\t\tcompressedTextureTests->addChild(new TextureTestCase(testCtx, (nameBase + \"_2d_\" + sizes[sizeNdx].name).c_str(), (formatStr + \", TEXTURETYPE_2D\").c_str(), testParameters));\n\t}\n}\n\n} \/\/ anonymous\n\ntcu::TestCaseGroup* createTextureCompressedFormatTests (tcu::TestContext& testCtx)\n{\n\treturn createTestGroup(testCtx, \"compressed\", \"Texture compressed format tests.\", populateTextureCompressedFormatTests);\n}\n\n} \/\/ texture\n} \/\/ vkt\nProperly initialize minFilter\/magFilter when setting up test cases\/*-------------------------------------------------------------------------\n * Vulkan Conformance Tests\n * ------------------------\n *\n * Copyright (c) 2016 The Khronos Group Inc.\n * Copyright (c) 2016 Samsung Electronics Co., Ltd.\n * Copyright (c) 2014 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\/*!\n * \\file\n * \\brief Compressed texture tests.\n *\/\/*--------------------------------------------------------------------*\/\n\n#include \"vktTextureCompressedFormatTests.hpp\"\n\n#include \"deString.h\"\n#include \"deStringUtil.hpp\"\n#include \"tcuCompressedTexture.hpp\"\n#include \"tcuTexture.hpp\"\n#include \"tcuTextureUtil.hpp\"\n#include \"vkImageUtil.hpp\"\n#include \"vktTestGroupUtil.hpp\"\n#include \"vktTextureTestUtil.hpp\"\n#include \n#include \n\nnamespace vkt\n{\nnamespace texture\n{\nnamespace\n{\n\nusing namespace vk;\nusing namespace glu::TextureTestUtil;\nusing namespace texture::util;\n\nusing std::string;\nusing std::vector;\nusing tcu::Sampler;\nusing tcu::TestLog;\n\nstruct Compressed2DTestParameters : public Texture2DTestCaseParameters\n{\n};\n\nclass Compressed2DTestInstance : public TestInstance\n{\npublic:\n\ttypedef Compressed2DTestParameters\tParameterType;\n\n\t\t\t\t\t\t\t\t\t\tCompressed2DTestInstance\t(Context&\t\t\t\tcontext,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t const ParameterType&\ttestParameters);\n\ttcu::TestStatus\t\t\t\t\t\titerate\t\t\t\t\t\t(void);\n\nprivate:\n\t\t\t\t\t\t\t\t\t\tCompressed2DTestInstance\t(const Compressed2DTestInstance& other);\n\tCompressed2DTestInstance&\t\t\toperator=\t\t\t\t\t(const Compressed2DTestInstance& other);\n\n\tconst ParameterType&\t\t\t\tm_testParameters;\n\tconst tcu::CompressedTexFormat\t\tm_compressedFormat;\n\tTestTexture2DSp\t\t\t\t\t\tm_texture;\n\tTextureRenderer\t\t\t\t\t\tm_renderer;\n};\n\nCompressed2DTestInstance::Compressed2DTestInstance (Context&\t\t\t\tcontext,\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst ParameterType&\ttestParameters)\n\t: TestInstance\t\t\t(context)\n\t, m_testParameters\t\t(testParameters)\n\t, m_compressedFormat\t(mapVkCompressedFormat(testParameters.format))\n\t, m_texture\t\t\t\t(TestTexture2DSp(new pipeline::TestTexture2D(m_compressedFormat, testParameters.width, testParameters.height)))\n\t, m_renderer\t\t\t(context, testParameters.sampleCount, testParameters.width, testParameters.height)\n{\n\tm_renderer.add2DTexture(m_texture);\n}\n\ntcu::TestStatus Compressed2DTestInstance::iterate (void)\n{\n\ttcu::TestLog&\t\t\t\t\tlog\t\t\t\t= m_context.getTestContext().getLog();\n\tconst pipeline::TestTexture2D&\ttexture\t\t\t= m_renderer.get2DTexture(0);\n\tconst tcu::TextureFormat\t\ttextureFormat\t= texture.getTextureFormat();\n\tconst tcu::TextureFormatInfo\tformatInfo\t\t= tcu::getTextureFormatInfo(textureFormat);\n\n\tReferenceParams\t\t\t\t\tsampleParams\t(TEXTURETYPE_2D);\n\ttcu::Surface\t\t\t\t\trendered\t\t(m_renderer.getRenderWidth(), m_renderer.getRenderHeight());\n\tvector\t\t\t\t\ttexCoord;\n\n\t\/\/ Setup params for reference.\n\tsampleParams.sampler\t\t\t= util::createSampler(m_testParameters.wrapS, m_testParameters.wrapT, m_testParameters.minFilter, m_testParameters.magFilter);\n\tsampleParams.samplerType\t\t= SAMPLERTYPE_FLOAT;\n\tsampleParams.lodMode\t\t\t= LODMODE_EXACT;\n\tsampleParams.colorBias\t\t\t= formatInfo.lookupBias;\n\tsampleParams.colorScale\t\t\t= formatInfo.lookupScale;\n\n\tlog << TestLog::Message << \"Compare reference value = \" << sampleParams.ref << TestLog::EndMessage;\n\n\t\/\/ Compute texture coordinates.\n\tcomputeQuadTexCoord2D(texCoord, tcu::Vec2(0.0f, 0.0f), tcu::Vec2(1.0f, 1.0f));\n\n\tm_renderer.renderQuad(rendered, 0, &texCoord[0], sampleParams);\n\n\t\/\/ Compute reference.\n\tconst tcu::IVec4\t\tformatBitDepth\t= getTextureFormatBitDepth(vk::mapVkFormat(VK_FORMAT_R8G8B8A8_UNORM));\n\tconst tcu::PixelFormat\tpixelFormat\t\t(formatBitDepth[0], formatBitDepth[1], formatBitDepth[2], formatBitDepth[3]);\n\ttcu::Surface\t\t\treferenceFrame\t(m_renderer.getRenderWidth(), m_renderer.getRenderHeight());\n\tsampleTexture(tcu::SurfaceAccess(referenceFrame, pixelFormat), m_texture->getTexture(), &texCoord[0], sampleParams);\n\n\t\/\/ Compare and log.\n\tconst bool isOk = compareImages(log, referenceFrame, rendered, pixelFormat.getColorThreshold() + tcu::RGBA(1, 1, 1, 1));\n\n\treturn isOk ? tcu::TestStatus::pass(\"Pass\") : tcu::TestStatus::fail(\"Image verification failed\");\n}\n\nvoid populateTextureCompressedFormatTests (tcu::TestCaseGroup* compressedTextureTests)\n{\n\ttcu::TestContext&\ttestCtx\t= compressedTextureTests->getTestContext();\n\n\t\/\/ ETC2 and EAC compressed formats.\n\tconst struct {\n\t\tconst VkFormat\tformat;\n\t} etc2Formats[] =\n\t{\n\t\t{ VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK\t\t},\n\t\t{ VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK\t\t},\n\t\t{ VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK\t},\n\t\t{ VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK\t},\n\t\t{ VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK\t},\n\t\t{ VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK\t},\n\n\t\t{ VK_FORMAT_EAC_R11_UNORM_BLOCK\t\t\t},\n\t\t{ VK_FORMAT_EAC_R11_SNORM_BLOCK\t\t\t},\n\t\t{ VK_FORMAT_EAC_R11G11_UNORM_BLOCK\t\t},\n\t\t{ VK_FORMAT_EAC_R11G11_SNORM_BLOCK\t\t},\n\t};\n\n\tconst struct {\n\t\tconst int\twidth;\n\t\tconst int\theight;\n\t\tconst char*\tname;\n\t} sizes[] =\n\t{\n\t\t{ 128, 64, \"pot\" },\n\t\t{ 51, 65, \"npot\" },\n\t};\n\n\tfor (int sizeNdx = 0; sizeNdx < DE_LENGTH_OF_ARRAY(sizes); sizeNdx++)\n\tfor (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(etc2Formats); formatNdx++)\n\t{\n\t\tconst string\tformatStr\t= de::toString(getFormatStr(etc2Formats[formatNdx].format));\n\t\tconst string\tnameBase\t= de::toLower(formatStr.substr(10));\n\n\t\tCompressed2DTestParameters\ttestParameters;\n\t\ttestParameters.format\t\t= etc2Formats[formatNdx].format;\n\t\ttestParameters.width\t\t= sizes[sizeNdx].width;\n\t\ttestParameters.height\t\t= sizes[sizeNdx].height;\n\t\ttestParameters.minFilter\t= tcu::Sampler::NEAREST;\n\t\ttestParameters.magFilter\t= tcu::Sampler::NEAREST;\n\t\ttestParameters.programs.push_back(PROGRAM_2D_FLOAT);\n\n\t\tcompressedTextureTests->addChild(new TextureTestCase(testCtx, (nameBase + \"_2d_\" + sizes[sizeNdx].name).c_str(), (formatStr + \", TEXTURETYPE_2D\").c_str(), testParameters));\n\t}\n}\n\n} \/\/ anonymous\n\ntcu::TestCaseGroup* createTextureCompressedFormatTests (tcu::TestContext& testCtx)\n{\n\treturn createTestGroup(testCtx, \"compressed\", \"Texture compressed format tests.\", populateTextureCompressedFormatTests);\n}\n\n} \/\/ texture\n} \/\/ vkt\n<|endoftext|>"} {"text":"static void\nshow_type(Vec &t, FILE *fp) {\n fprintf(fp, \"( \");\n forv_CreationSet(cs, t) if (cs) {\n if (cs->sym->name)\n fprintf(fp, \"%s \", cs->sym->name);\n else if (cs->sym->constant)\n fprintf(fp, \"\\\"%s\\\" \", cs->sym->constant);\n else\n fprintf(fp, \"%d \", cs->sym->id);\n }\n fprintf(fp, \") \");\n}\n\nstatic void\nshow_sym(Sym *s, FILE *fp) {\n if (s->is_pattern) {\n fprintf(fp, \"( \");\n forv_Sym(ss, s->has) {\n if (ss != s->has.v[0])\n\tfprintf(fp, \", \");\n show_sym(ss, fp);\n }\n fprintf(fp, \") \");\n } else if (s->name)\n fprintf(fp, \"%s \", s->name);\n else if (s->constant)\n fprintf(fp, \"\\\"%s\\\" \", s->constant);\n if (s->type && s->type->name)\n fprintf(fp, \"= %s\", s->type->name);\n else if (s->must_implement && \n\t s->must_implement == s->must_specialize)\n fprintf(fp, \": %s\", s->must_implement->name);\n else if (s->must_implement)\n fprintf(fp, \"< %s\", s->must_implement->name);\n else if (s->must_specialize)\n fprintf(fp, \"@ %s\", s->must_specialize->name);\n}\n\nstatic void\nshow_fun(Fun *f, FILE *fp) {\n fprintf(fp, \"%s:%d: \", f->filename(), f->line());\n forv_Sym(s, f->sym->has)\n show_sym(s, fp);\n}\n\nvoid\nfa_print_backward(AVar *v, FILE *fp) {\n Vec done, todo;\n todo.add(v);\n done.set_add(v);\n for (int i = 0; i < todo.n; i++) {\n v = todo.v[i];\n if (v->var) {\n if (v->var->sym) {\n\tif (v->var->sym->name)\n\t fprintf(fp, \"%s %d\\n\", v->var->sym->name, v->var->sym->id);\n\telse\n\t fprintf(fp, \"%d\\n\", v->var->sym->id);\n } else\n\tfprintf(fp, \"VAR %p\\n\", v->var);\n } else\n fprintf(fp, \"AVAR %p\\n\", v);\n show_type(*v->out, fp); fprintf(fp, \"\\n\");\n forv_AVar(vv, v->backward) if (vv) {\n if (!done.set_in(vv)) {\n\ttodo.add(vv);\n\tdone.set_add(vv);\n }\n }\n }\n}\n\nvoid\nfa_dump_var_types(AVar *av, FILE *fp, int verbose = verbose_level) {\n Var *v = av->var;\n if (verbose < 2 && (!v->sym->name || v->sym->is_symbol))\n return;\n if (!v->sym->in)\n fprintf(fp, \"::\");\n else if (v->sym->in->name)\n fprintf(fp, \"%s::\", v->sym->in->name);\n else\n fprintf(fp, \"%d::\", v->sym->in->id);\n if (v->sym->name)\n fprintf(fp, \"%s(%d) \", v->sym->name, v->sym->id);\n else\n fprintf(fp, \"(%d) \", v->sym->id);\n if (v->sym->constant)\n fprintf(fp, \"\\\"%s\\\" \", v->sym->constant);\n else {\n fprintf(fp, \"\\\"\");\n print(fp, v->sym->imm, v->sym->type);\n fprintf(fp, \"\\\" \");\n }\n show_type(*av->out, fp);\n fprintf(fp, \"\\n\");\n}\n\nvoid\nfa_dump_types(FA *fa, FILE *fp) {\n Vec gvars;\n forv_Fun(f, fa->funs) {\n forv_EntrySet(es, f->ess) {\n if (f->sym->name)\n\tfprintf(fp, \"function %s (%d) \", f->sym->name, f->sym->id);\n else\n\tfprintf(fp, \"function %d \", f->sym->id);\n fprintf(fp, \"entry set with %d edges\\n\", es->edges.count());\n Vec vars;\n f->collect_Vars(vars);\n forv_Var(v, vars) {\n\tif (v->sym->global_scope) {\n\t gvars.set_add(v);\n\t continue;\n\t}\n\tfa_dump_var_types(make_AVar(v, es), fp);\n }\n }\n }\n gvars.set_to_vec();\n fprintf(fp, \"globals\\n\");\n forv_Var(v, gvars)\n if (!v->sym->is_constant && !v->sym->is_symbol)\n fa_dump_var_types(unique_AVar(v, GLOBAL_CONTOUR), fp);\n}\n\nstatic void\nshow_illegal_type(FILE *fp, ATypeViolation *v) {\n AVar *av = v->av;\n if (av->var->sym->name)\n fprintf(stderr, \"'%s' \", av->var->sym->name);\n else if (verbose_level)\n fprintf(stderr, \"expr:%d \", av->var->sym->id);\n else\n fprintf(stderr, \"expression \");\n if (verbose_level) {\n fprintf(stderr, \"id:%d \", av->var->sym->id);\n if (av->out->n) {\n fprintf(stderr, \": \");\n show_type(*av->out, fp);\n }\n }\n fprintf(stderr, \"illegal: \");\n show_type(*v->type, fp);\n fprintf(stderr, \"\\n\");\n}\n\nstatic void\nshow_call_tree(FILE *fp, PNode *p, EntrySet *es, int depth = 0) {\n depth++;\n if (depth > print_call_depth || !p->code)\n return;\n if (depth > 1 && p->code->filename()) {\n for (int x = 0; x < depth; x++)\n fprintf(stderr, \" \");\n fprintf(stderr, \"called from %s:%d\\n\", p->code->filename(), p->code->line());\n }\n AEdge **last = es->edges.last();\n for (AEdge **x = es->edges.first(); x < last; x++) if (*x)\n show_call_tree(fp, (*x)->pnode, (*x)->from, depth);\n}\n\nstatic void\nshow_call_tree(FILE *fp, AVar *av) {\n EntrySet *es = (EntrySet*)av->contour;\n AEdge **last = es->edges.last();\n for (AEdge **x = es->edges.first(); x < last; x++) if (*x)\n show_call_tree(fp, (*x)->pnode, (*x)->from, 1);\n}\n\nstatic int\ncompar_tv_pos(const void *aa, const void *bb) {\n ATypeViolation *a = (*(ATypeViolation**)aa);\n ATypeViolation *b = (*(ATypeViolation**)bb);\n AST *aast = a->send ? a->send->var->def->code->ast : 0;\n if (!aast) aast = a->av->var->sym->ast;\n AST *bast = b->send ? b->send->var->def->code->ast : 0;\n if (!bast) bast = b->av->var->sym->ast;\n if (!aast || !bast) {\n if (bast) return -1;\n if (aast) return 1;\n return 0;\n }\n if (!aast->pathname() || !bast->pathname()) {\n if (bast->pathname()) return -1;\n if (aast->pathname()) return 1;\n } else {\n int x = strcmp(aast->pathname(), bast->pathname());\n if (x) return x;\n }\n int i = aast->line();\n int j = bast->line();\n return (i > j) ? 1 : ((i < j) ? -1 : 0);\n}\n\nstatic void\nshow_violations(FA *fa, FILE *fp) {\n Vec vv;\n forv_ATypeViolation(v, type_violations) if (v)\n vv.add(v);\n qsort(vv.v, vv.n, sizeof(vv.v[0]), compar_tv_pos);\n forv_ATypeViolation(v, vv) if (v) {\n if (!verbose_level && !v->av->var->sym->name)\n continue;\n if (v->send)\n fprintf(stderr, \"%s:%d: \", v->send->var->def->code->filename(), \n\t v->send->var->def->code->line());\n else if (v->av->var->sym->ast)\n fprintf(stderr, \"%s:%d: \", v->av->var->sym->filename(), \n\t v->av->var->sym->line());\n else\n fprintf(stderr, \"error: \");\n switch (v->kind) {\n default: assert(0);\n case ATypeViolation_PRIMITIVE_ARGUMENT:\n\tfprintf(stderr, \"illegal primitive argument type \");\n\tshow_illegal_type(fp, v);\n\tbreak;\n case ATypeViolation_SEND_ARGUMENT:\n\tif (v->av->var->sym->is_symbol &&\n\t v->send->var->def->rvals.v[0] == v->av->var)\n\t fprintf(stderr, \"unresolved call '%s'\\n\", v->av->var->sym->name);\n\telse {\n\t fprintf(stderr, \"illegal call argument type \");\n\t show_illegal_type(fp, v);\n\t}\n\tbreak;\n case ATypeViolation_DISPATCH_AMBIGUITY:\n\tfprintf(stderr, \"ambiguous call '%s'\\n\", v->av->var->sym->name);\n\tfprintf(stderr, \" candidate functions:\\n\");\n\tforv_Fun(f, *v->funs) {\n\t fprintf(stderr, \" \");\n\t show_fun(f, stderr);\n\t fprintf(stderr, \"\\n\");\n\t}\n\tbreak;\n case ATypeViolation_MEMBER:\n\tif (v->av->out->n == 1)\n\t fprintf(stderr, \"unresolved member '%s'\", v->av->out->v[0]->sym->name);\n\telse {\n\t fprintf(stderr, \"unresolved member\\n\");\n\t forv_CreationSet(selector, *v->av->out)\n\t fprintf(stderr, \" selector '%s'\\n\", selector->sym->name);\n\t}\n\tif (v->type->n == 1)\n\t fprintf(stderr, \" class '%s'\\n\", v->type->v[0]->sym->name ? v->type->v[0]->sym->name : \n\t\t \"\");\n\telse {\n\t fprintf(stderr, \" classes\\n\");\n\t forv_CreationSet(cs, *v->type)\n\t fprintf(stderr, \" class '%s'\\n\", cs->sym->name);\n\t}\n\tbreak;\n case ATypeViolation_MATCH:\n\tif (v->type->n == 1)\n\t fprintf(stderr, \"near '%s' unmatched type '%s'\\n\", \n\t\t v->av->var->sym->name ? v->av->var->sym->name : \"\", \n\t\t v->type->v[0]->sym->name);\n\telse {\n\t fprintf(stderr, \"near '%s' unmatched type\\n\");\n\t forv_CreationSet(cs, *v->type)\n\t fprintf(stderr, \" type '%s'\\n\", cs->sym->name);\n\t}\n\tbreak;\n case ATypeViolation_NOTYPE:\n\tif (v->av->var->sym->name)\n\t fprintf(stderr, \"'%s' \", v->av->var->sym->name);\n\telse\n\t fprintf(stderr, \"expression \");\n\tfprintf(stderr, \"has no type\\n\");\n\tbreak;\n }\n if (v->send)\n show_call_tree(fp, v->send->var->def, (EntrySet*)v->send->contour);\n else if (v->av->contour_is_entry_set)\n show_call_tree(fp, v->av);\n }\n}\n\nstatic char *fn(char *s) {\n if (!s)\n return \"\";\n char *filename = strrchr(s, '\/');\n if (filename)\n return filename + 1;\t\n return s;\n}\n\nvoid\nlog_var_types(Var *v, Fun *f) {\n if (!v->sym->name || v->sym->is_symbol)\n return;\n if (!v->sym->in)\n log(LOG_TEST_FA, \"::\");\n else if (v->sym->in->name)\n log(LOG_TEST_FA, \"%s::\", v->sym->in->name);\n else\n log(LOG_TEST_FA, \"%d::\", v->sym->in->id);\n if (v->sym->name)\n log(LOG_TEST_FA, \"%s(%s:%d) \", v->sym->name, fn(v->sym->filename()), v->sym->line());\n else\n log(LOG_TEST_FA, \"(%s:%d) \", fn(v->sym->filename()), v->sym->line());\n Vec css;\n for (int i = 0; i < v->avars.n; i++) if (v->avars.v[i].key) {\n AVar *av = v->avars.v[i].value;\n if (!f || f->ess.in(((EntrySet*)av->contour)))\n css.set_union(*av->out);\n }\n assert(css.n);\n log(LOG_TEST_FA, \"( \");\n Vec syms;\n forv_CreationSet(cs, css) if (cs)\n syms.set_add(cs->sym);\n syms.set_to_vec();\n qsort(syms.v, syms.n, sizeof(syms.v[0]), compar_syms);\n forv_Sym(s, syms) {\n if (s->name)\n log(LOG_TEST_FA, \"%s \", s->name);\n else if (s->constant)\n log(LOG_TEST_FA, \"\\\"%s\\\" \", s->constant);\n log(LOG_TEST_FA, \"(%s:%d) \", fn(s->filename()), s->line());\n }\n log(LOG_TEST_FA, \")\\n\");\n}\n\n\nSEGV in debug output of some constantsstatic void\nshow_type(Vec &t, FILE *fp) {\n fprintf(fp, \"( \");\n forv_CreationSet(cs, t) if (cs) {\n if (cs->sym->name)\n fprintf(fp, \"%s \", cs->sym->name);\n else if (cs->sym->constant)\n fprintf(fp, \"\\\"%s\\\" \", cs->sym->constant);\n else\n fprintf(fp, \"%d \", cs->sym->id);\n }\n fprintf(fp, \") \");\n}\n\nstatic void\nshow_sym(Sym *s, FILE *fp) {\n if (s->is_pattern) {\n fprintf(fp, \"( \");\n forv_Sym(ss, s->has) {\n if (ss != s->has.v[0])\n\tfprintf(fp, \", \");\n show_sym(ss, fp);\n }\n fprintf(fp, \") \");\n } else if (s->name)\n fprintf(fp, \"%s \", s->name);\n else if (s->constant)\n fprintf(fp, \"\\\"%s\\\" \", s->constant);\n if (s->type && s->type->name)\n fprintf(fp, \"= %s\", s->type->name);\n else if (s->must_implement && \n\t s->must_implement == s->must_specialize)\n fprintf(fp, \": %s\", s->must_implement->name);\n else if (s->must_implement)\n fprintf(fp, \"< %s\", s->must_implement->name);\n else if (s->must_specialize)\n fprintf(fp, \"@ %s\", s->must_specialize->name);\n}\n\nstatic void\nshow_fun(Fun *f, FILE *fp) {\n fprintf(fp, \"%s:%d: \", f->filename(), f->line());\n forv_Sym(s, f->sym->has)\n show_sym(s, fp);\n}\n\nvoid\nfa_print_backward(AVar *v, FILE *fp) {\n Vec done, todo;\n todo.add(v);\n done.set_add(v);\n for (int i = 0; i < todo.n; i++) {\n v = todo.v[i];\n if (v->var) {\n if (v->var->sym) {\n\tif (v->var->sym->name)\n\t fprintf(fp, \"%s %d\\n\", v->var->sym->name, v->var->sym->id);\n\telse\n\t fprintf(fp, \"%d\\n\", v->var->sym->id);\n } else\n\tfprintf(fp, \"VAR %p\\n\", v->var);\n } else\n fprintf(fp, \"AVAR %p\\n\", v);\n show_type(*v->out, fp); fprintf(fp, \"\\n\");\n forv_AVar(vv, v->backward) if (vv) {\n if (!done.set_in(vv)) {\n\ttodo.add(vv);\n\tdone.set_add(vv);\n }\n }\n }\n}\n\nvoid\nfa_dump_var_types(AVar *av, FILE *fp, int verbose = verbose_level) {\n Var *v = av->var;\n if (verbose < 2 && (!v->sym->name || v->sym->is_symbol))\n return;\n if (!v->sym->in)\n fprintf(fp, \"::\");\n else if (v->sym->in->name)\n fprintf(fp, \"%s::\", v->sym->in->name);\n else\n fprintf(fp, \"%d::\", v->sym->in->id);\n if (v->sym->name)\n fprintf(fp, \"%s(%d) \", v->sym->name, v->sym->id);\n else\n fprintf(fp, \"(%d) \", v->sym->id);\n if (v->sym->is_constant) {\n if (v->sym->constant)\n fprintf(fp, \"\\\"%s\\\" \", v->sym->constant);\n else {\n fprintf(fp, \"\\\"\");\n print(fp, v->sym->imm, v->sym->type);\n fprintf(fp, \"\\\" \");\n }\n }\n show_type(*av->out, fp);\n fprintf(fp, \"\\n\");\n}\n\nvoid\nfa_dump_types(FA *fa, FILE *fp) {\n Vec gvars;\n forv_Fun(f, fa->funs) {\n forv_EntrySet(es, f->ess) {\n if (f->sym->name)\n\tfprintf(fp, \"function %s (%d) \", f->sym->name, f->sym->id);\n else\n\tfprintf(fp, \"function %d \", f->sym->id);\n fprintf(fp, \"entry set with %d edges\\n\", es->edges.count());\n Vec vars;\n f->collect_Vars(vars);\n forv_Var(v, vars) {\n\tif (v->sym->global_scope) {\n\t gvars.set_add(v);\n\t continue;\n\t}\n\tfa_dump_var_types(make_AVar(v, es), fp);\n }\n }\n }\n gvars.set_to_vec();\n fprintf(fp, \"globals\\n\");\n forv_Var(v, gvars)\n if (!v->sym->is_constant && !v->sym->is_symbol)\n fa_dump_var_types(unique_AVar(v, GLOBAL_CONTOUR), fp);\n}\n\nstatic void\nshow_illegal_type(FILE *fp, ATypeViolation *v) {\n AVar *av = v->av;\n if (av->var->sym->name)\n fprintf(stderr, \"'%s' \", av->var->sym->name);\n else if (verbose_level)\n fprintf(stderr, \"expr:%d \", av->var->sym->id);\n else\n fprintf(stderr, \"expression \");\n if (verbose_level) {\n fprintf(stderr, \"id:%d \", av->var->sym->id);\n if (av->out->n) {\n fprintf(stderr, \": \");\n show_type(*av->out, fp);\n }\n }\n fprintf(stderr, \"illegal: \");\n show_type(*v->type, fp);\n fprintf(stderr, \"\\n\");\n}\n\nstatic void\nshow_call_tree(FILE *fp, PNode *p, EntrySet *es, int depth = 0) {\n depth++;\n if (depth > print_call_depth || !p->code)\n return;\n if (depth > 1 && p->code->filename()) {\n for (int x = 0; x < depth; x++)\n fprintf(stderr, \" \");\n fprintf(stderr, \"called from %s:%d\\n\", p->code->filename(), p->code->line());\n }\n AEdge **last = es->edges.last();\n for (AEdge **x = es->edges.first(); x < last; x++) if (*x)\n show_call_tree(fp, (*x)->pnode, (*x)->from, depth);\n}\n\nstatic void\nshow_call_tree(FILE *fp, AVar *av) {\n EntrySet *es = (EntrySet*)av->contour;\n AEdge **last = es->edges.last();\n for (AEdge **x = es->edges.first(); x < last; x++) if (*x)\n show_call_tree(fp, (*x)->pnode, (*x)->from, 1);\n}\n\nstatic int\ncompar_tv_pos(const void *aa, const void *bb) {\n ATypeViolation *a = (*(ATypeViolation**)aa);\n ATypeViolation *b = (*(ATypeViolation**)bb);\n AST *aast = a->send ? a->send->var->def->code->ast : 0;\n if (!aast) aast = a->av->var->sym->ast;\n AST *bast = b->send ? b->send->var->def->code->ast : 0;\n if (!bast) bast = b->av->var->sym->ast;\n if (!aast || !bast) {\n if (bast) return -1;\n if (aast) return 1;\n return 0;\n }\n if (!aast->pathname() || !bast->pathname()) {\n if (bast->pathname()) return -1;\n if (aast->pathname()) return 1;\n } else {\n int x = strcmp(aast->pathname(), bast->pathname());\n if (x) return x;\n }\n int i = aast->line();\n int j = bast->line();\n return (i > j) ? 1 : ((i < j) ? -1 : 0);\n}\n\nstatic void\nshow_violations(FA *fa, FILE *fp) {\n Vec vv;\n forv_ATypeViolation(v, type_violations) if (v)\n vv.add(v);\n qsort(vv.v, vv.n, sizeof(vv.v[0]), compar_tv_pos);\n forv_ATypeViolation(v, vv) if (v) {\n if (!verbose_level && !v->av->var->sym->name)\n continue;\n if (v->send)\n fprintf(stderr, \"%s:%d: \", v->send->var->def->code->filename(), \n\t v->send->var->def->code->line());\n else if (v->av->var->sym->ast)\n fprintf(stderr, \"%s:%d: \", v->av->var->sym->filename(), \n\t v->av->var->sym->line());\n else\n fprintf(stderr, \"error: \");\n switch (v->kind) {\n default: assert(0);\n case ATypeViolation_PRIMITIVE_ARGUMENT:\n\tfprintf(stderr, \"illegal primitive argument type \");\n\tshow_illegal_type(fp, v);\n\tbreak;\n case ATypeViolation_SEND_ARGUMENT:\n\tif (v->av->var->sym->is_symbol &&\n\t v->send->var->def->rvals.v[0] == v->av->var)\n\t fprintf(stderr, \"unresolved call '%s'\\n\", v->av->var->sym->name);\n\telse {\n\t fprintf(stderr, \"illegal call argument type \");\n\t show_illegal_type(fp, v);\n\t}\n\tbreak;\n case ATypeViolation_DISPATCH_AMBIGUITY:\n\tfprintf(stderr, \"ambiguous call '%s'\\n\", v->av->var->sym->name);\n\tfprintf(stderr, \" candidate functions:\\n\");\n\tforv_Fun(f, *v->funs) {\n\t fprintf(stderr, \" \");\n\t show_fun(f, stderr);\n\t fprintf(stderr, \"\\n\");\n\t}\n\tbreak;\n case ATypeViolation_MEMBER:\n\tif (v->av->out->n == 1)\n\t fprintf(stderr, \"unresolved member '%s'\", v->av->out->v[0]->sym->name);\n\telse {\n\t fprintf(stderr, \"unresolved member\\n\");\n\t forv_CreationSet(selector, *v->av->out)\n\t fprintf(stderr, \" selector '%s'\\n\", selector->sym->name);\n\t}\n\tif (v->type->n == 1)\n\t fprintf(stderr, \" class '%s'\\n\", v->type->v[0]->sym->name ? v->type->v[0]->sym->name : \n\t\t \"\");\n\telse {\n\t fprintf(stderr, \" classes\\n\");\n\t forv_CreationSet(cs, *v->type)\n\t fprintf(stderr, \" class '%s'\\n\", cs->sym->name);\n\t}\n\tbreak;\n case ATypeViolation_MATCH:\n\tif (v->type->n == 1)\n\t fprintf(stderr, \"near '%s' unmatched type '%s'\\n\", \n\t\t v->av->var->sym->name ? v->av->var->sym->name : \"\", \n\t\t v->type->v[0]->sym->name);\n\telse {\n\t fprintf(stderr, \"near '%s' unmatched type\\n\");\n\t forv_CreationSet(cs, *v->type)\n\t fprintf(stderr, \" type '%s'\\n\", cs->sym->name);\n\t}\n\tbreak;\n case ATypeViolation_NOTYPE:\n\tif (v->av->var->sym->name)\n\t fprintf(stderr, \"'%s' \", v->av->var->sym->name);\n\telse\n\t fprintf(stderr, \"expression \");\n\tfprintf(stderr, \"has no type\\n\");\n\tbreak;\n }\n if (v->send)\n show_call_tree(fp, v->send->var->def, (EntrySet*)v->send->contour);\n else if (v->av->contour_is_entry_set)\n show_call_tree(fp, v->av);\n }\n}\n\nstatic char *fn(char *s) {\n if (!s)\n return \"\";\n char *filename = strrchr(s, '\/');\n if (filename)\n return filename + 1;\t\n return s;\n}\n\nvoid\nlog_var_types(Var *v, Fun *f) {\n if (!v->sym->name || v->sym->is_symbol)\n return;\n if (!v->sym->in)\n log(LOG_TEST_FA, \"::\");\n else if (v->sym->in->name)\n log(LOG_TEST_FA, \"%s::\", v->sym->in->name);\n else\n log(LOG_TEST_FA, \"%d::\", v->sym->in->id);\n if (v->sym->name)\n log(LOG_TEST_FA, \"%s(%s:%d) \", v->sym->name, fn(v->sym->filename()), v->sym->line());\n else\n log(LOG_TEST_FA, \"(%s:%d) \", fn(v->sym->filename()), v->sym->line());\n Vec css;\n for (int i = 0; i < v->avars.n; i++) if (v->avars.v[i].key) {\n AVar *av = v->avars.v[i].value;\n if (!f || f->ess.in(((EntrySet*)av->contour)))\n css.set_union(*av->out);\n }\n assert(css.n);\n log(LOG_TEST_FA, \"( \");\n Vec syms;\n forv_CreationSet(cs, css) if (cs)\n syms.set_add(cs->sym);\n syms.set_to_vec();\n qsort(syms.v, syms.n, sizeof(syms.v[0]), compar_syms);\n forv_Sym(s, syms) {\n if (s->name)\n log(LOG_TEST_FA, \"%s \", s->name);\n else if (s->constant)\n log(LOG_TEST_FA, \"\\\"%s\\\" \", s->constant);\n log(LOG_TEST_FA, \"(%s:%d) \", fn(s->filename()), s->line());\n }\n log(LOG_TEST_FA, \")\\n\");\n}\n\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#include \"core\/do_with.hh\"\n#include \"cql_test_env.hh\"\n#include \"cql3\/query_processor.hh\"\n#include \"cql3\/query_options.hh\"\n#include \"core\/distributed.hh\"\n#include \"core\/shared_ptr.hh\"\n#include \"utils\/UUID_gen.hh\"\n#include \"message\/messaging_service.hh\"\n#include \"service\/storage_service.hh\"\n\nclass in_memory_cql_env : public cql_test_env {\npublic:\n static auto constexpr ks_name = \"ks\";\nprivate:\n ::shared_ptr> _db;\n ::shared_ptr> _qp;\n ::shared_ptr> _proxy;\nprivate:\n struct core_local_state {\n service::client_state client_state;\n\n core_local_state()\n : client_state(service::client_state::for_internal_calls()) {\n client_state.set_keyspace(ks_name);\n }\n\n future<> stop() {\n return make_ready_future<>();\n }\n };\n distributed _core_local;\nprivate:\n auto make_query_state() {\n return ::make_shared(_core_local.local().client_state);\n }\npublic:\n in_memory_cql_env(\n ::shared_ptr> db,\n ::shared_ptr> qp,\n ::shared_ptr> proxy)\n : _db(db)\n , _qp(qp)\n , _proxy(proxy)\n { }\n\n virtual future<::shared_ptr> execute_cql(const sstring& text) override {\n auto qs = make_query_state();\n return _qp->local().process(text, *qs, cql3::query_options::DEFAULT).finally([qs] {});\n }\n\n virtual future<::shared_ptr> execute_cql(\n const sstring& text,\n std::unique_ptr qo) override\n {\n auto qs = make_query_state();\n auto& lqo = *qo;\n return _qp->local().process(text, *qs, lqo).finally([qs, qo = std::move(qo)] {});\n }\n\n virtual future prepare(sstring query) override {\n return _qp->invoke_on_all([query, this] (auto& local_qp) {\n auto qs = this->make_query_state();\n return local_qp.prepare(query, *qs).finally([qs] {}).discard_result();\n }).then([query, this] {\n return _qp->local().compute_id(query, ks_name);\n });\n }\n\n virtual future<::shared_ptr> execute_prepared(\n bytes id,\n std::vector values) override\n {\n auto prepared = _qp->local().get_prepared(id);\n assert(bool(prepared));\n auto stmt = prepared->statement;\n assert(stmt->get_bound_terms() == values.size());\n\n int32_t protocol_version = 3;\n auto options = ::make_shared(db::consistency_level::ONE, std::experimental::nullopt, std::move(values), false,\n cql3::query_options::specific_options::DEFAULT, protocol_version, serialization_format::use_32_bit());\n options->prepare(prepared->bound_names);\n\n auto qs = make_query_state();\n return _qp->local().process_statement(stmt, *qs, *options)\n .finally([options, qs] {});\n }\n\n virtual future<> create_table(std::function schema_maker) override {\n auto id = utils::UUID_gen::get_time_UUID();\n return _db->invoke_on_all([schema_maker, id, this] (database& db) {\n auto cf_schema = make_lw_shared(schema_maker(ks_name));\n cf_schema->set_id(id);\n auto& ks = db.find_keyspace(ks_name);\n auto cfg = ks.make_column_family_config(*cf_schema);\n db.add_column_family(std::move(cf_schema), std::move(cfg));\n });\n }\n\n virtual future<> require_keyspace_exists(const sstring& ks_name) override {\n auto& db = _db->local();\n assert(db.has_keyspace(ks_name));\n return make_ready_future<>();\n }\n\n virtual future<> require_table_exists(const sstring& ks_name, const sstring& table_name) override {\n auto& db = _db->local();\n assert(db.has_schema(ks_name, table_name));\n return make_ready_future<>();\n }\n\n virtual future<> require_column_has_value(const sstring& table_name,\n std::vector pk,\n std::vector ck,\n const sstring& column_name,\n boost::any expected) override {\n auto& db = _db->local();\n auto& cf = db.find_column_family(ks_name, table_name);\n auto schema = cf.schema();\n auto pkey = partition_key::from_deeply_exploded(*schema, pk);\n auto dk = dht::global_partitioner().decorate_key(*schema, pkey);\n auto shard = db.shard_of(dk._token);\n return _db->invoke_on(shard, [pkey = std::move(pkey),\n ck = std::move(ck),\n ks_name = std::move(ks_name),\n column_name = std::move(column_name),\n expected = std::move(expected),\n table_name = std::move(table_name)] (database& db) mutable {\n auto& cf = db.find_column_family(ks_name, table_name);\n auto schema = cf.schema();\n return cf.find_partition_slow(pkey).then([schema, ck, column_name, expected] (column_family::const_mutation_partition_ptr p) {\n assert(p != nullptr);\n auto row = p->find_row(clustering_key::from_deeply_exploded(*schema, ck));\n assert(row != nullptr);\n auto col_def = schema->get_column_definition(utf8_type->decompose(column_name));\n assert(col_def != nullptr);\n const atomic_cell_or_collection* cell = row->find_cell(col_def->id);\n if (!cell) {\n assert(((void)\"column not set\", 0));\n }\n bytes actual;\n if (!col_def->type->is_multi_cell()) {\n auto c = cell->as_atomic_cell();\n assert(c.is_live());\n actual = { c.value().begin(), c.value().end() };\n } else {\n auto c = cell->as_collection_mutation();\n auto type = dynamic_pointer_cast(col_def->type);\n actual = type->to_value(type->deserialize_mutation_form(c),\n serialization_format::internal());\n }\n assert(col_def->type->equal(actual, col_def->type->decompose(expected)));\n });\n });\n }\n\n virtual database& local_db() override {\n return _db->local();\n }\n\n future<> start() {\n return _core_local.start().then([this] () {\n auto query = sprint(\"create keyspace %s with replication = { 'class' : 'org.apache.cassandra.locator.SimpleStrategy', 'replication_factor' : 1 };\", sstring{ks_name});\n return execute_cql(query).discard_result().then([] {\n return make_ready_future<>();\n });\n });\n }\n\n virtual future<> stop() override {\n return _core_local.stop().then([this] {\n return _qp->stop().then([this] {\n return _proxy->stop().then([this] {\n return _db->stop().then([] {\n return locator::i_endpoint_snitch::stop_snitch();\n });\n });\n });\n });\n }\n};\n\nfuture<> init_once() {\n static bool done = false;\n if (!done) {\n done = true;\n return service::init_storage_service().then([] {\n return net::init_messaging_service(\"127.0.0.1\", db::config::seed_provider_type()).then([] {\n });\n });\n } else {\n return make_ready_future();\n }\n}\n\nfuture<::shared_ptr> make_env_for_test() {\n return init_once().then([] {\n using namespace locator;\n return i_endpoint_snitch::create_snitch(\"org.apache.cassandra.locator.SimpleSnitch\").then([] {\n auto db = ::make_shared>();\n auto cfg = make_lw_shared();\n cfg->data_file_directories() = {};\n return db->start(std::move(*cfg)).then([db] {\n auto proxy = ::make_shared>();\n auto qp = ::make_shared>();\n return proxy->start(std::ref(*db)).then([qp, db, proxy] {\n return qp->start(std::ref(*proxy), std::ref(*db)).then([db, proxy, qp] {\n auto env = ::make_shared(db, qp, proxy);\n return env->start().then([env] () -> ::shared_ptr {\n return env;\n });\n });\n });\n });\n });\n });\n}\n\nfuture<> do_with_cql_env(std::function(cql_test_env&)> func) {\n return make_env_for_test().then([func = std::move(func)] (auto e) mutable {\n return do_with(std::move(func), [e] (auto& f) {\n return f(*e);\n }).finally([e] {\n return e->stop().finally([e] {});\n });\n });\n}\ncql_test_env: Start the global snitch before storage service\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#include \"core\/do_with.hh\"\n#include \"cql_test_env.hh\"\n#include \"cql3\/query_processor.hh\"\n#include \"cql3\/query_options.hh\"\n#include \"core\/distributed.hh\"\n#include \"core\/shared_ptr.hh\"\n#include \"utils\/UUID_gen.hh\"\n#include \"message\/messaging_service.hh\"\n#include \"service\/storage_service.hh\"\n\nclass in_memory_cql_env : public cql_test_env {\npublic:\n static auto constexpr ks_name = \"ks\";\nprivate:\n ::shared_ptr> _db;\n ::shared_ptr> _qp;\n ::shared_ptr> _proxy;\nprivate:\n struct core_local_state {\n service::client_state client_state;\n\n core_local_state()\n : client_state(service::client_state::for_internal_calls()) {\n client_state.set_keyspace(ks_name);\n }\n\n future<> stop() {\n return make_ready_future<>();\n }\n };\n distributed _core_local;\nprivate:\n auto make_query_state() {\n return ::make_shared(_core_local.local().client_state);\n }\npublic:\n in_memory_cql_env(\n ::shared_ptr> db,\n ::shared_ptr> qp,\n ::shared_ptr> proxy)\n : _db(db)\n , _qp(qp)\n , _proxy(proxy)\n { }\n\n virtual future<::shared_ptr> execute_cql(const sstring& text) override {\n auto qs = make_query_state();\n return _qp->local().process(text, *qs, cql3::query_options::DEFAULT).finally([qs] {});\n }\n\n virtual future<::shared_ptr> execute_cql(\n const sstring& text,\n std::unique_ptr qo) override\n {\n auto qs = make_query_state();\n auto& lqo = *qo;\n return _qp->local().process(text, *qs, lqo).finally([qs, qo = std::move(qo)] {});\n }\n\n virtual future prepare(sstring query) override {\n return _qp->invoke_on_all([query, this] (auto& local_qp) {\n auto qs = this->make_query_state();\n return local_qp.prepare(query, *qs).finally([qs] {}).discard_result();\n }).then([query, this] {\n return _qp->local().compute_id(query, ks_name);\n });\n }\n\n virtual future<::shared_ptr> execute_prepared(\n bytes id,\n std::vector values) override\n {\n auto prepared = _qp->local().get_prepared(id);\n assert(bool(prepared));\n auto stmt = prepared->statement;\n assert(stmt->get_bound_terms() == values.size());\n\n int32_t protocol_version = 3;\n auto options = ::make_shared(db::consistency_level::ONE, std::experimental::nullopt, std::move(values), false,\n cql3::query_options::specific_options::DEFAULT, protocol_version, serialization_format::use_32_bit());\n options->prepare(prepared->bound_names);\n\n auto qs = make_query_state();\n return _qp->local().process_statement(stmt, *qs, *options)\n .finally([options, qs] {});\n }\n\n virtual future<> create_table(std::function schema_maker) override {\n auto id = utils::UUID_gen::get_time_UUID();\n return _db->invoke_on_all([schema_maker, id, this] (database& db) {\n auto cf_schema = make_lw_shared(schema_maker(ks_name));\n cf_schema->set_id(id);\n auto& ks = db.find_keyspace(ks_name);\n auto cfg = ks.make_column_family_config(*cf_schema);\n db.add_column_family(std::move(cf_schema), std::move(cfg));\n });\n }\n\n virtual future<> require_keyspace_exists(const sstring& ks_name) override {\n auto& db = _db->local();\n assert(db.has_keyspace(ks_name));\n return make_ready_future<>();\n }\n\n virtual future<> require_table_exists(const sstring& ks_name, const sstring& table_name) override {\n auto& db = _db->local();\n assert(db.has_schema(ks_name, table_name));\n return make_ready_future<>();\n }\n\n virtual future<> require_column_has_value(const sstring& table_name,\n std::vector pk,\n std::vector ck,\n const sstring& column_name,\n boost::any expected) override {\n auto& db = _db->local();\n auto& cf = db.find_column_family(ks_name, table_name);\n auto schema = cf.schema();\n auto pkey = partition_key::from_deeply_exploded(*schema, pk);\n auto dk = dht::global_partitioner().decorate_key(*schema, pkey);\n auto shard = db.shard_of(dk._token);\n return _db->invoke_on(shard, [pkey = std::move(pkey),\n ck = std::move(ck),\n ks_name = std::move(ks_name),\n column_name = std::move(column_name),\n expected = std::move(expected),\n table_name = std::move(table_name)] (database& db) mutable {\n auto& cf = db.find_column_family(ks_name, table_name);\n auto schema = cf.schema();\n return cf.find_partition_slow(pkey).then([schema, ck, column_name, expected] (column_family::const_mutation_partition_ptr p) {\n assert(p != nullptr);\n auto row = p->find_row(clustering_key::from_deeply_exploded(*schema, ck));\n assert(row != nullptr);\n auto col_def = schema->get_column_definition(utf8_type->decompose(column_name));\n assert(col_def != nullptr);\n const atomic_cell_or_collection* cell = row->find_cell(col_def->id);\n if (!cell) {\n assert(((void)\"column not set\", 0));\n }\n bytes actual;\n if (!col_def->type->is_multi_cell()) {\n auto c = cell->as_atomic_cell();\n assert(c.is_live());\n actual = { c.value().begin(), c.value().end() };\n } else {\n auto c = cell->as_collection_mutation();\n auto type = dynamic_pointer_cast(col_def->type);\n actual = type->to_value(type->deserialize_mutation_form(c),\n serialization_format::internal());\n }\n assert(col_def->type->equal(actual, col_def->type->decompose(expected)));\n });\n });\n }\n\n virtual database& local_db() override {\n return _db->local();\n }\n\n future<> start() {\n return _core_local.start().then([this] () {\n auto query = sprint(\"create keyspace %s with replication = { 'class' : 'org.apache.cassandra.locator.SimpleStrategy', 'replication_factor' : 1 };\", sstring{ks_name});\n return execute_cql(query).discard_result().then([] {\n return make_ready_future<>();\n });\n });\n }\n\n virtual future<> stop() override {\n return _core_local.stop().then([this] {\n return _qp->stop().then([this] {\n return _proxy->stop().then([this] {\n return _db->stop().then([] {\n return locator::i_endpoint_snitch::stop_snitch();\n });\n });\n });\n });\n }\n};\n\nfuture<> init_once() {\n static bool done = false;\n if (!done) {\n done = true;\n return service::init_storage_service().then([] {\n return net::init_messaging_service(\"127.0.0.1\", db::config::seed_provider_type()).then([] {\n });\n });\n } else {\n return make_ready_future();\n }\n}\n\nfuture<::shared_ptr> make_env_for_test() {\n return locator::i_endpoint_snitch::create_snitch(\"SimpleSnitch\").then([] {\n return init_once().then([] {\n auto db = ::make_shared>();\n auto cfg = make_lw_shared();\n cfg->data_file_directories() = {};\n return db->start(std::move(*cfg)).then([db] {\n auto proxy = ::make_shared>();\n auto qp = ::make_shared>();\n return proxy->start(std::ref(*db)).then([qp, db, proxy] {\n return qp->start(std::ref(*proxy), std::ref(*db)).then([db, proxy, qp] {\n auto env = ::make_shared(db, qp, proxy);\n return env->start().then([env] () -> ::shared_ptr {\n return env;\n });\n });\n });\n });\n });\n });\n}\n\nfuture<> do_with_cql_env(std::function(cql_test_env&)> func) {\n return make_env_for_test().then([func = std::move(func)] (auto e) mutable {\n return do_with(std::move(func), [e] (auto& f) {\n return f(*e);\n }).finally([e] {\n return e->stop().finally([e] {});\n });\n });\n}\n<|endoftext|>"} {"text":"\/\/===--- TypeSerialization.cpp - Serialization of Decls ---------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by Ted Kremenek and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This files defines methods that implement bitcode serialization for Types.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/AST\/Type.h\"\n#include \"llvm\/Bitcode\/Serialize.h\"\n#include \"llvm\/Bitcode\/Deserialize.h\"\n\nusing namespace clang;\n\nvoid QualType::Emit(llvm::Serializer& S) const {\n S.EmitPtr(getAsOpaquePtr());\n S.EmitInt(getQualifiers());\n}\n\nvoid QualType::Read(llvm::Deserializer& D) {\n D.ReadPtr(ThePtr);\n ThePtr |= D.ReadInt();\n}\n\n\/* FIXME: Either remove this method or complete it.\n\nvoid Type::Emit(llvm::Serializer& S) {\n switch (getTypeClass()) {\n default:\n assert (false && \"Serialization for type class not implemented.\");\n break;\n \n case Type::Builtin:\n cast(this)->Emit(S);\n break;\n }\n}\n *\/\n\nvoid Type::EmitTypeInternal(llvm::Serializer& S) const {\n S.Emit(CanonicalType);\n}\n\nvoid Type::ReadTypeInternal(llvm::Deserializer& D) {\n D.Read(CanonicalType);\n}\n\nvoid ComplexType::Emit(llvm::Serializer& S) const {\n EmitTypeInternal(S);\n S.Emit(ElementType);\n}\n\nComplexType* ComplexType::Materialize(llvm::Deserializer& D) {\n ComplexType* T = new ComplexType(QualType(),QualType());\n T->ReadTypeInternal(D);\n D.Read(T->ElementType);\n return T;\n}\n\nvoid PointerType::Emit(llvm::Serializer& S) const {\n EmitTypeInternal(S);\n S.Emit(PointeeType);\n}\n\nPointerType* PointerType::Materialize(llvm::Deserializer& D) {\n PointerType* T = new PointerType(QualType(),QualType());\n T->ReadTypeInternal(D);\n D.Read(T->PointeeType);\n return T;\n}\n\nvoid ReferenceType::Emit(llvm::Serializer& S) const {\n EmitTypeInternal(S);\n S.Emit(ReferenceeType);\n}\n\nReferenceType* ReferenceType::Materialize(llvm::Deserializer& D) {\n ReferenceType* T = new ReferenceType(QualType(),QualType());\n T->ReadTypeInternal(D);\n D.Read(T->ReferenceeType);\n return T;\n}\n\nvoid ArrayType::EmitArrayTypeInternal(llvm::Serializer& S) const {\n EmitTypeInternal(S);\n S.Emit(ElementType);\n S.EmitInt(SizeModifier);\n S.EmitInt(IndexTypeQuals);\n}\n\nvoid ArrayType::ReadArrayTypeInternal(llvm::Deserializer& D) {\n ReadTypeInternal(D);\n D.Read(ElementType);\n SizeModifier = static_cast(D.ReadInt());\n IndexTypeQuals = D.ReadInt();\n}\n\nvoid ConstantArrayType::Emit(llvm::Serializer& S) const {\n#if 0\n \/\/ FIXME: APInt serialization\n S.Emit(Size);\n#endif\n EmitArrayTypeInternal(S);\n}\n\nConstantArrayType* ConstantArrayType::Materialize(llvm::Deserializer& D) {\n#if 0\n llvm::APInt x = S.ReadVal(D);\n \n \/\/ \"Default\" construct the array.\n ConstantArrayType* T =\n new ConstantArrayType(QualType(), QualType(), x, ArrayType::Normal, 0);\n \n \/\/ Deserialize the internal values.\n T->ReadArrayTypeInternal(D);\n\n return T;\n#else\n return NULL;\n#endif\n\n}\nCompleted serialization of ConstantArrayTypes (now that APInt serialization is in place).\/\/===--- TypeSerialization.cpp - Serialization of Decls ---------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by Ted Kremenek and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This files defines methods that implement bitcode serialization for Types.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/AST\/Type.h\"\n#include \"llvm\/Bitcode\/Serialize.h\"\n#include \"llvm\/Bitcode\/Deserialize.h\"\n\nusing namespace clang;\n\nvoid QualType::Emit(llvm::Serializer& S) const {\n S.EmitPtr(getAsOpaquePtr());\n S.EmitInt(getQualifiers());\n}\n\nvoid QualType::Read(llvm::Deserializer& D) {\n D.ReadPtr(ThePtr);\n ThePtr |= D.ReadInt();\n}\n\n\/* FIXME: Either remove this method or complete it.\n\nvoid Type::Emit(llvm::Serializer& S) {\n switch (getTypeClass()) {\n default:\n assert (false && \"Serialization for type class not implemented.\");\n break;\n \n case Type::Builtin:\n cast(this)->Emit(S);\n break;\n }\n}\n *\/\n\nvoid Type::EmitTypeInternal(llvm::Serializer& S) const {\n S.Emit(CanonicalType);\n}\n\nvoid Type::ReadTypeInternal(llvm::Deserializer& D) {\n D.Read(CanonicalType);\n}\n\nvoid ComplexType::Emit(llvm::Serializer& S) const {\n EmitTypeInternal(S);\n S.Emit(ElementType);\n}\n\nComplexType* ComplexType::Materialize(llvm::Deserializer& D) {\n ComplexType* T = new ComplexType(QualType(),QualType());\n T->ReadTypeInternal(D);\n D.Read(T->ElementType);\n return T;\n}\n\nvoid PointerType::Emit(llvm::Serializer& S) const {\n EmitTypeInternal(S);\n S.Emit(PointeeType);\n}\n\nPointerType* PointerType::Materialize(llvm::Deserializer& D) {\n PointerType* T = new PointerType(QualType(),QualType());\n T->ReadTypeInternal(D);\n D.Read(T->PointeeType);\n return T;\n}\n\nvoid ReferenceType::Emit(llvm::Serializer& S) const {\n EmitTypeInternal(S);\n S.Emit(ReferenceeType);\n}\n\nReferenceType* ReferenceType::Materialize(llvm::Deserializer& D) {\n ReferenceType* T = new ReferenceType(QualType(),QualType());\n T->ReadTypeInternal(D);\n D.Read(T->ReferenceeType);\n return T;\n}\n\nvoid ArrayType::EmitArrayTypeInternal(llvm::Serializer& S) const {\n EmitTypeInternal(S);\n S.Emit(ElementType);\n S.EmitInt(SizeModifier);\n S.EmitInt(IndexTypeQuals);\n}\n\nvoid ArrayType::ReadArrayTypeInternal(llvm::Deserializer& D) {\n ReadTypeInternal(D);\n D.Read(ElementType);\n SizeModifier = static_cast(D.ReadInt());\n IndexTypeQuals = D.ReadInt();\n}\n\nvoid ConstantArrayType::Emit(llvm::Serializer& S) const {\n EmitArrayTypeInternal(S);\n S.Emit(Size);\n}\n\nConstantArrayType* ConstantArrayType::Materialize(llvm::Deserializer& D) {\n \/\/ \"Default\" construct the array.\n ConstantArrayType* T =\n new ConstantArrayType(QualType(), QualType(), llvm::APInt(), \n ArrayType::Normal, 0);\n \n \/\/ Deserialize the internal values.\n T->ReadArrayTypeInternal(D); \n D.Read(T->Size);\n\n return T;\n}\n<|endoftext|>"} {"text":"\/\/ Blink.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"ConnectionService.h\"\n#include \"TreehopperUsb.h\"\n#include \n#include \n#include \n\nusing namespace Treehopper;\n\nint main()\n{\n\tauto service = ConnectionService::instance();\n TreehopperUsb& board = service.getFirstDevice();\n \n\tboard.connect();\n\n board.pins[2].makeAnalogInput();\n \n for(int i=0;i<20;i++)\n\t{\n\t\tboard.led(!board.led());\n\t\t\/\/board.pins[1].toggleOutput();\n cout << board.pins[2].adcValue() << endl;\n this_thread::sleep_for(chrono::milliseconds(100));\n\t}\n\tboard.disconnect();\n \n while(true)\n {\n std:this_thread::sleep_for(chrono::seconds(5));\n }\n \n return 0;\n}\n\nDon't hang after blink is finished\/\/ Blink.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"ConnectionService.h\"\n#include \"TreehopperUsb.h\"\n#include \n#include \n#include \n\nusing namespace Treehopper;\n\nint main()\n{\n\tauto service = ConnectionService::instance();\n TreehopperUsb& board = service.getFirstDevice();\n \n\tboard.connect();\n\n board.pins[2].makeAnalogInput();\n \n for(int i=0;i<20;i++)\n\t{\n\t\tboard.led(!board.led());\n\t\t\/\/board.pins[1].toggleOutput();\n cout << board.pins[2].adcValue() << endl;\n this_thread::sleep_for(chrono::milliseconds(100));\n\t}\n\tboard.disconnect();\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/*\n * Mediator\n * Author: reimen\n * Data: Oct.15.2014\n *\n *\/\n#include \n#include \nusing std::cout;\nusing std::endl;\nclass Colleague;\nclass Mediator;\nclass ConcreteMediator;\n\nclass Mediator\n{\nprotected:\n Colleague* _colleague;\npublic:\n virtual ~Mediator() {}\n virtual void createColleague() = 0;\n virtual void colleagueChanged() = 0;\n};\n\nclass Colleague\n{\nprotected:\n Mediator* _mediator;\npublic:\n virtual ~Colleague() {}\n virtual void setMediator(Mediator* mediator) = 0;\n virtual void controlColleague() = 0;\n};\n\nclass ConcreteColleague : public Colleague\n{\nprivate:\n\npublic:\n ConcreteColleague() {}\n virtual ~ConcreteColleague() {}\n void setMediator(Mediator* mediator)\n {\n _mediator = mediator;\n }\n void controlColleague()\n {\n cout << \"Hello This is Colleague\" << endl;\n if(_mediator != NULL)\n {\n _mediator -> colleagueChanged();\n }\n else\n {\n cout << \"There is no mediator\" << endl;\n }\n }\n};\n\nclass ConcreteMediator : Mediator\n{\npublic:\n virtual ~ConcreteMediator() { delete _colleague; }\n void createColleague()\n {\n if(_colleague == NULL)\n {\n _colleague = new ConcreteColleague;\n _colleague -> setMediator(this);\n }\n\n }\n void colleagueChanged()\n {\n cout << \"Hello I am mediator!!\" << endl;\n }\n void zap()\n {\n if(_colleague != NULL)\n {\n _colleague->controlColleague();\n }\n else\n {\n cout << \"No colleague\" << endl;\n }\n }\n};\n\n\nint main()\n{\n ConcreteMediator mediator;\n mediator.createColleague();\n mediator.zap();\n return EXIT_SUCCESS;\n}\nAdd Comments to Mediator.cpp\/*\n * Mediator\n * Author: reimen\n * Date: Oct.15.2014\n * Define an object that encapsulates how a set of objects interact.\n * Mediator promotes loose coupling by keeping objects from\n * referring to each other explicitly, and it lets you vary their\n * interaction independently.\n *\/\n#include \n#include \nusing std::cout;\nusing std::endl;\nclass Colleague;\nclass Mediator;\nclass ConcreteMediator;\n\nclass Mediator\n{\nprotected:\n Colleague* _colleague;\npublic:\n virtual ~Mediator() {}\n virtual void createColleague() = 0;\n virtual void colleagueChanged() = 0;\n};\n\nclass Colleague\n{\nprotected:\n Mediator* _mediator;\npublic:\n virtual ~Colleague() {}\n virtual void setMediator(Mediator* mediator) = 0;\n virtual void controlColleague() = 0;\n};\n\nclass ConcreteColleague : public Colleague\n{\nprivate:\n\npublic:\n ConcreteColleague() {}\n virtual ~ConcreteColleague() {}\n void setMediator(Mediator* mediator)\n {\n _mediator = mediator;\n }\n void controlColleague()\n {\n cout << \"Hello This is Colleague\" << endl;\n if(_mediator != NULL)\n {\n _mediator -> colleagueChanged();\n }\n else\n {\n cout << \"There is no mediator\" << endl;\n }\n }\n};\n\nclass ConcreteMediator : Mediator\n{\npublic:\n virtual ~ConcreteMediator()\n {\n delete _colleague;\n }\n void createColleague()\n {\n if(_colleague == NULL)\n {\n _colleague = new ConcreteColleague;\n _colleague -> setMediator(this);\n }\n\n }\n void colleagueChanged()\n {\n cout << \"Hello I am mediator!!\" << endl;\n }\n void zap()\n {\n if(_colleague != NULL)\n {\n _colleague->controlColleague();\n }\n else\n {\n cout << \"No colleague\" << endl;\n }\n }\n};\n\n\nint main()\n{\n ConcreteMediator mediator;\n mediator.createColleague();\n mediator.zap();\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"gtest\/gtest.h\"\n\n\/\/ redefine class, private & protected to get access to\n\/\/ private and protected members of rbtree & rbnode.\n#define class struct\n#define private public\n#define protected public\n\n#include \"..\/rbtree.hpp\"\n#include \"..\/rbnode.hpp\"\n\n#undef class\n#undef private\n#undef protected\n\nusing namespace std;\n\n\/\/ Redirect the cout to a string\nstruct cout_redirect {\n cout_redirect(std::streambuf* new_buffer) \n : old( std::cout.rdbuf(new_buffer))\n {\n }\n\n ~cout_redirect() {\n std::cout.rdbuf(old);\n }\n\nprivate:\n std::streambuf* old;\n};\n\nclass rbtree_tests : public ::testing::Test {\npublic:\n \/\/ red black trees\n rbtree* rbt;\n \n rbtree_tests() {\n rbt = new rbtree();\n }\n \n ~rbtree_tests() {\n delete rbt;\n }\n};\n\nTEST_F(rbtree_tests, test_empty) {\n EXPECT_TRUE(rbt->root == nullptr) << \"root should be null\";\n}\n\nTEST_F(rbtree_tests, test_rbtree_invalid) {\n rbt->root = new rbnode(56, rbcolor::red);\n EXPECT_FALSE(rbt->is_valid_rbtree()) << \"tree with red root is invalid\";\n}\n\nTEST_F(rbtree_tests, test_rbtree_valid_1) {\n \/\/ build a red black tree.\n auto root = new rbnode(45, rbcolor::black);\n \n auto r1 = new rbnode(25);\n r1->parent = root;\n \n auto r2 = new rbnode(60);\n r2->parent = root;\n \n root->left = r1;\n root->right = r2;\n \n rbt->root = root;\n EXPECT_TRUE(rbt->is_valid_rbtree());\n}\n\nTEST_F(rbtree_tests, test_rbtree_valid_2) {\n auto root = new rbnode(10, rbcolor::black);\n auto n7 = new rbnode(7, rbcolor::black, root);\n auto n19 = new rbnode(19, rbcolor::red, root);\n auto n13 = new rbnode(13, rbcolor::black, n19);\n auto n23 = new rbnode(23, rbcolor::black, n19);\n \n root->left = n7;\n root->right = n19;\n n19->left = n13;\n n19->right = n23;\n \n rbt->root = root;\n EXPECT_TRUE(rbt->is_valid_rbtree());\n}\n\nTEST_F(rbtree_tests, test_rbtree_insert) {\n \n}\n\nTEST_F(rbtree_tests, test_rbtree_remove) {\n \n}\n\nTEST_F(rbtree_tests, test_rbtree_remove_all) {\n \n}\nadded test cases for rb insert, rotate#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"gtest\/gtest.h\"\n\n\/\/ redefine class, private & protected to get access to\n\/\/ private and protected members of rbtree & rbnode.\n#define class struct\n#define private public\n#define protected public\n\n#include \"..\/rbtree.hpp\"\n#include \"..\/rbnode.hpp\"\n\n#undef class\n#undef private\n#undef protected\n\nusing namespace std;\n\n\/\/ Redirect the cout to a string\nstruct cout_redirect {\n cout_redirect(std::streambuf* new_buffer) \n : old( std::cout.rdbuf(new_buffer))\n {\n }\n\n ~cout_redirect() {\n std::cout.rdbuf(old);\n }\n\nprivate:\n std::streambuf* old;\n};\n\nclass rbtree_tests : public ::testing::Test {\npublic:\n \/\/ red black trees\n rbtree* rbt;\n \n rbtree_tests() {\n rbt = new rbtree();\n }\n \n ~rbtree_tests() {\n delete rbt;\n }\n};\n\nTEST_F(rbtree_tests, test_empty) {\n EXPECT_TRUE(rbt->root == nullptr) << \"root should be null!\";\n}\n\nTEST_F(rbtree_tests, test_rbtree_invalid_1) {\n rbt->root = new rbnode(56, rbcolor::red);\n EXPECT_FALSE(rbt->is_valid_rbtree()) << \"tree with red root should be invalid!\";\n}\n\nTEST_F(rbtree_tests, test_rbtree_invalid_2) {\n auto root = new rbnode(7, rbcolor::black);\n auto n3 = new rbnode(3, rbcolor::red, root);\n auto n18 = new rbnode(18, rbcolor::black, root);\n auto n1 = new rbnode(1, rbcolor::black, n3);\n auto n45 = new rbnode(45, rbcolor::black, n18);\n auto n2 = new rbnode(2, rbcolor::black, n1);\n \n root->left = n3;\n root->right = n18;\n n18->right = n45;\n n3->left = n1;\n n1->right = n2;\n \n rbt->root = root;\n EXPECT_FALSE(rbt->is_valid_rbtree());\n}\n\nTEST_F(rbtree_tests, test_rbtree_valid_1) {\n \/\/ build a red black tree.\n auto root = new rbnode(45, rbcolor::black);\n \n auto r1 = new rbnode(25);\n r1->parent = root;\n \n auto r2 = new rbnode(60);\n r2->parent = root;\n \n root->left = r1;\n root->right = r2;\n \n rbt->root = root;\n EXPECT_TRUE(rbt->is_valid_rbtree());\n}\n\nTEST_F(rbtree_tests, test_rbtree_valid_2) {\n auto root = new rbnode(10, rbcolor::black);\n auto n7 = new rbnode(7, rbcolor::black, root);\n auto n19 = new rbnode(19, rbcolor::red, root);\n auto n13 = new rbnode(13, rbcolor::black, n19);\n auto n23 = new rbnode(23, rbcolor::black, n19);\n \n root->left = n7;\n root->right = n19;\n n19->left = n13;\n n19->right = n23;\n \n rbt->root = root;\n EXPECT_TRUE(rbt->is_valid_rbtree());\n}\n\nTEST_F(rbtree_tests, test_rbtree_insert) {\n \/\/ generated using visualization tool: https:\/\/www.cs.usfca.edu\/~galles\/visualization\/RedBlack.html\n vector expected = {\n \"0(black)\\n\",\n \"0(black)\\n1(red)\\n\",\n \"0(red)\\n1(black)\\n2(red)\\n\",\n \"0(black)\\n1(black)\\n2(black)\\n3(red)\\n\",\n \"0(black)\\n1(black)\\n2(red)\\n3(black)\\n4(red)\\n\",\n \"0(black)\\n1(black)\\n2(black)\\n3(red)\\n4(black)\\n5(red)\\n\",\n \"0(black)\\n1(black)\\n2(black)\\n3(red)\\n4(red)\\n5(black)\\n6(red)\\n\",\n \"0(black)\\n1(red)\\n2(black)\\n3(black)\\n4(black)\\n5(red)\\n6(black)\\n7(red)\\n\",\n \"0(black)\\n1(red)\\n2(black)\\n3(black)\\n4(black)\\n5(red)\\n6(red)\\n7(black)\\n8(red)\\n\",\n \"0(black)\\n1(black)\\n2(black)\\n3(black)\\n4(black)\\n5(black)\\n6(black)\\n7(red)\\n8(black)\\n9(red)\\n\"\n };\n \n for (int i = 0; i < expected.size(); i++) {\n auto n = i+1;\n rbt->insert(i);\n \n stringstream buffer; {\n cout_redirect activate(buffer.rdbuf());\n rbt->inorder();\n }\n string got = buffer.str();\n \n EXPECT_TRUE(expected[i] == got) << \"insert of \" << i << \" is incorrect!\";\n \n \/\/ max heigth of rb tree <= 2 * log(n+1)\n EXPECT_TRUE(rbt->depth() < 2 * ceil(log2(n+1))) << \"depth of rb tree is incorrect!\";\n \n }\n}\n\nTEST_F(rbtree_tests, test_rbtree_remove) {\n \n}\n\nTEST_F(rbtree_tests, test_rbtree_remove_all) {\n rbt->remove_all(rbt->root);\n EXPECT_TRUE(rbt->root == nullptr);\n EXPECT_TRUE(rbt->depth() == 0) << \"depth of empty rb tree should be zero!\";\n}\n\nTEST_F(rbtree_tests, test_left_rotate) {\n \/*\n x y\n \/ \\ left rotate around x \/ \\\n a y ------------------------> x c\n \/ \\ \/ \\\n b c a b\n *\/\n \n auto x = new rbnode(50, rbcolor::black);\n auto y = new rbnode(60, rbcolor::red, x);\n auto a = new rbnode(25, rbcolor::black, x);\n auto b = new rbnode(55, rbcolor::black, y);\n auto c = new rbnode(70, rbcolor::black, y);\n \n x->left = a;\n x->right = y;\n y->right = c;\n y->left = b;\n \n rbt->root = x;\n rbt->left_rotate(x);\n \n stringstream buffer; {\n cout_redirect activate(buffer.rdbuf());\n rbt->inorder();\n }\n \n string expected = \"25(black)\\n50(black)\\n55(black)\\n60(red)\\n70(black)\\n\";\n string got = buffer.str();\n \n EXPECT_TRUE(expected == got) << \"left rotation is incorrect!\";\n EXPECT_TRUE(rbt->depth() == 3) << \"left rotation is of incorrect depth!\";\n}\n\nTEST_F(rbtree_tests, test_right_rotate) {\n \/*\n y x\n \/ \\ right rotate around y \/ \\\n x c -----------------------> a y\n \/ \\ \/ \\\n a b b c\n \n *\/\n \n auto y = new rbnode(50, rbcolor::black);\n auto x = new rbnode(25, rbcolor::red, y);\n auto a = new rbnode(10, rbcolor::black, x);\n auto b = new rbnode(30, rbcolor::black, x);\n auto c = new rbnode(60, rbcolor::black);\n \n x->left = a;\n x->right = b;\n y->right = c;\n y->left = x;\n \n rbt->root = y;\n rbt->right_rotate(y);\n \n stringstream buffer; {\n cout_redirect activate(buffer.rdbuf());\n rbt->inorder();\n }\n \n string expected = \"10(black)\\n25(red)\\n30(black)\\n50(black)\\n60(black)\\n\";\n string got = buffer.str();\n \n EXPECT_TRUE(expected == got) << \"right rotation is incorrect.\";\n EXPECT_TRUE(rbt->depth() == 3) << \"right rotation is of incorrect depth\";\n}\n<|endoftext|>"} {"text":"using namespace System;\nusing namespace System::Reflection;\nusing namespace System::Runtime::CompilerServices;\nusing namespace System::Runtime::InteropServices;\nusing namespace System::Security::Permissions;\n\n\/\/\n\/\/ Les informations gnrales relatives un assembly dpendent de\n\/\/ l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations\n\/\/ associes un assembly.\n\/\/\n[assembly:AssemblyTitleAttribute(L\"ClrPhlib\")];\n[assembly:AssemblyDescriptionAttribute(L\"\")];\n[assembly:AssemblyConfigurationAttribute(L\"\")];\n[assembly:AssemblyCompanyAttribute(L\"\")];\n[assembly:AssemblyProductAttribute(L\"ClrPhlib\")];\n[assembly:AssemblyCopyrightAttribute(L\"Copyright (c) 2017\")];\n[assembly:AssemblyTrademarkAttribute(L\"\")];\n[assembly:AssemblyCultureAttribute(L\"\")];\n\n\/\/\n\/\/ Les informations de version pour un assembly se composent des quatre valeurs suivantes:\n\/\/\n\/\/ Version principale\n\/\/ Version secondaire\n\/\/ Numro de build\n\/\/ Rvision\n\/\/\n\/\/ Vous pouvez spcifier toutes les valeurs ou indiquer les numros de rvision et de build par dfaut\n\/\/ en utilisant '*', comme indiqu ci-dessous:\n\n[assembly:AssemblyVersionAttribute(\"1.9.*\")];\n\n[assembly:ComVisible(false)];\n\n[assembly:CLSCompliantAttribute(true)];Save encoding of AssemblyInfo.cpp to UTF-8 because of the diacritics of comment may cause compile error (we treat compile warning as error).using namespace System;\nusing namespace System::Reflection;\nusing namespace System::Runtime::CompilerServices;\nusing namespace System::Runtime::InteropServices;\nusing namespace System::Security::Permissions;\n\n\/\/\n\/\/ Les informations générales relatives à un assembly dépendent de\n\/\/ l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations\n\/\/ associées à un assembly.\n\/\/\n[assembly:AssemblyTitleAttribute(L\"ClrPhlib\")];\n[assembly:AssemblyDescriptionAttribute(L\"\")];\n[assembly:AssemblyConfigurationAttribute(L\"\")];\n[assembly:AssemblyCompanyAttribute(L\"\")];\n[assembly:AssemblyProductAttribute(L\"ClrPhlib\")];\n[assembly:AssemblyCopyrightAttribute(L\"Copyright (c) 2017\")];\n[assembly:AssemblyTrademarkAttribute(L\"\")];\n[assembly:AssemblyCultureAttribute(L\"\")];\n\n\/\/\n\/\/ Les informations de version pour un assembly se composent des quatre valeurs suivantes :\n\/\/\n\/\/ Version principale\n\/\/ Version secondaire\n\/\/ Numéro de build\n\/\/ Révision\n\/\/\n\/\/ Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de révision et de build par défaut\n\/\/ en utilisant '*', comme indiqué ci-dessous :\n\n[assembly:AssemblyVersionAttribute(\"1.9.*\")];\n\n[assembly:ComVisible(false)];\n\n[assembly:CLSCompliantAttribute(true)];<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Monteverdi2\n Language: C++\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See Copyright.txt for details.\n\n Monteverdi2 is distributed under the CeCILL licence version 2. See\n Licence_CeCILL_V2-en.txt or\n http:\/\/www.cecill.info\/licences\/Licence_CeCILL_V2-en.txt for more details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\/\/\n\/\/ Configuration include.\n\/\/\/\/ Included at first position before any other ones.\n#include \"ConfigureMonteverdi2.h\"\n\n\/\/\n\/\/ Qt includes (sorted by alphabetic order)\n\/\/\/\/ Must be included before system\/custom includes.\n\n\/\/\n\/\/ System includes (sorted by alphabetic order)\n\n\/\/ Monteverdi includes (sorted by alphabetic order)\n#include \"mvdApplication.h\"\n#include \"mvdMainWindow.h\"\n#include \"mvdDatasetModel.h\"\n\n\/\/\n\/\/ OTB includes (sorted by alphabetic order)\n\n\/\/\n\/\/ MAIN\n\/\/\nint\nmain( int argc, char* argv[] )\n{\n mvd::Application application( argc, argv );\n\n \/\/\n \/\/ Force numeric options of locale to \"C\"\n \/\/ See issue #635\n \/\/\n \/\/ TODO: Move into I18nApplication.\n setlocale( LC_NUMERIC, \"C\" );\n\n \/\/ Check if the application have a settings file already available\n bool appHasSettingsFile = application.HasSettingsFile();\n bool appHasIncorrectCacheDir(false);\n if (appHasSettingsFile)\n {\n \/\/ Read cache dir from settings\n application.ReadCacheDirFromSettings();\n \/\/ Check the cache dir\n if (!application.CheckCacheDirIsCorrect() )\n {\n appHasIncorrectCacheDir = true;\n }\n }\n else \/\/ TODO MSD: should be removed\n {\n std::cout << \"Application has no settings file\";\n }\n\n mvd::MainWindow mainWindow;\n\n if (!appHasSettingsFile || appHasIncorrectCacheDir)\n {\n \/\/ Loop until the directory will be correct\n while (true)\n {\n \/\/ Select a new location for the cache director\n try\n {\n \/\/ Create the cache directory\n application.MakeCacheDir(mainWindow.SelectCacheDir(appHasIncorrectCacheDir));\n break;\n }\n catch (...)\n {\n appHasIncorrectCacheDir = true;\n }\n }\n \/\/ Save the cache directory into the settings file\n application.WriteCacheDirIntoSettings();\n }\n\n\n\n#if defined( _DEBUG )\n \/\/ Usefull when developping\/debugging to avoid overlapping other windows.\n mainWindow.show();\n#else\n \/\/ TODO: Correctly manage main-window state via application settings.\n mainWindow.showMaximized();\n#endif\n\n \/\/ This code is here to propagate events from maximization to child\n \/\/ widgets, so that an image loaded from command-line will get the\n \/\/ appropriate widget size and occupy as much space as possible on screen.\n application.processEvents();\n\n \/\/ TODO: Move into mvd::Application.\n \/\/ Handle passing image filename from command-line\n if(argc>1)\n {\n mainWindow.OpenImage( QString(argv[1]) );\n }\n \n return application.exec();\n}\n\n\/\/\n\/\/ Main functions implementations.\n\/\/\nBUG: fix resource loading on Windows\/*=========================================================================\n\n Program: Monteverdi2\n Language: C++\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See Copyright.txt for details.\n\n Monteverdi2 is distributed under the CeCILL licence version 2. See\n Licence_CeCILL_V2-en.txt or\n http:\/\/www.cecill.info\/licences\/Licence_CeCILL_V2-en.txt for more details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\/\/\n\/\/ Configuration include.\n\/\/\/\/ Included at first position before any other ones.\n#include \"ConfigureMonteverdi2.h\"\n\n\/\/\n\/\/ Qt includes (sorted by alphabetic order)\n\/\/\/\/ Must be included before system\/custom includes.\n\n\/\/\n\/\/ System includes (sorted by alphabetic order)\n\n\/\/ Monteverdi includes (sorted by alphabetic order)\n#include \"mvdApplication.h\"\n#include \"mvdMainWindow.h\"\n#include \"mvdDatasetModel.h\"\n\n\/\/\n\/\/ OTB includes (sorted by alphabetic order)\n\n\/\/\n\/\/ MAIN\n\/\/\nint\nmain( int argc, char* argv[] )\n{\n Q_INIT_RESOURCE(mvdMainWindow);\n\n mvd::Application application( argc, argv );\n\n \/\/\n \/\/ Force numeric options of locale to \"C\"\n \/\/ See issue #635\n \/\/\n \/\/ TODO: Move into I18nApplication.\n setlocale( LC_NUMERIC, \"C\" );\n\n \/\/ Check if the application have a settings file already available\n bool appHasSettingsFile = application.HasSettingsFile();\n bool appHasIncorrectCacheDir(false);\n if (appHasSettingsFile)\n {\n \/\/ Read cache dir from settings\n application.ReadCacheDirFromSettings();\n \/\/ Check the cache dir\n if (!application.CheckCacheDirIsCorrect() )\n {\n appHasIncorrectCacheDir = true;\n }\n }\n else \/\/ TODO MSD: should be removed\n {\n std::cout << \"Application has no settings file\";\n }\n\n mvd::MainWindow mainWindow;\n\n if (!appHasSettingsFile || appHasIncorrectCacheDir)\n {\n \/\/ Loop until the directory will be correct\n while (true)\n {\n \/\/ Select a new location for the cache director\n try\n {\n \/\/ Create the cache directory\n application.MakeCacheDir(mainWindow.SelectCacheDir(appHasIncorrectCacheDir));\n break;\n }\n catch (...)\n {\n appHasIncorrectCacheDir = true;\n }\n }\n \/\/ Save the cache directory into the settings file\n application.WriteCacheDirIntoSettings();\n }\n\n\n\n#if defined( _DEBUG )\n \/\/ Usefull when developping\/debugging to avoid overlapping other windows.\n mainWindow.show();\n#else\n \/\/ TODO: Correctly manage main-window state via application settings.\n mainWindow.showMaximized();\n#endif\n\n \/\/ This code is here to propagate events from maximization to child\n \/\/ widgets, so that an image loaded from command-line will get the\n \/\/ appropriate widget size and occupy as much space as possible on screen.\n application.processEvents();\n\n \/\/ TODO: Move into mvd::Application.\n \/\/ Handle passing image filename from command-line\n if(argc>1)\n {\n mainWindow.OpenImage( QString(argv[1]) );\n }\n \n return application.exec();\n}\n\n\/\/\n\/\/ Main functions implementations.\n\/\/\n<|endoftext|>"} {"text":"\/*=========================================================================\n\nProgram: ORFEO Toolbox\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\n\nCopyright (c) Centre National d'Etudes Spatiales. All rights reserved.\nSee OTBCopyright.txt for details.\n\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"otbMsgReporter.h\"\n#include \n\nnamespace otb\n{\n \/** Initialize the singleton *\/\n MsgReporter::Pointer MsgReporter::m_Instance = NULL;\n\n \/\/\/ Constructor\n MsgReporter\n ::MsgReporter()\n {\n this->Build();\n wMainWindow->show();\n Fl_Text_Buffer * buffer = new Fl_Text_Buffer();\n this->textArea->buffer(buffer);\n }\n\n\n \/** Manage the singleton *\/\n MsgReporter::Pointer\n MsgReporter\n ::GetInstance()\n {\n if(!m_Instance)\n {\n\tm_Instance = MsgReporter::New();\n }\n return m_Instance;\n }\n \/\/Show\n void\n MsgReporter\n ::Show()\n {\n this->wMainWindow->show();\n }\n \/\/Hide\n void\n MsgReporter\n ::Hide()\n {\n this->wMainWindow->hide();\n }\n \/\/Set title\n void\n MsgReporter\n ::SetTitle(const std::string & title)\n {\n std::string str(title);\n str = str + \" message reporter window\";\n this->wMainWindow->label(str.c_str());\n }\n \/\/Send Msg\n void\n MsgReporter\n ::SendMsg(const std::string & msg)\n {\n this->textArea->insert(msg.c_str());\n this->textArea->insert(\"\\n\");\n this->textArea->show_insert_position();\n Fl::check();\n }\n\n \/\/Send Error\n void\n MsgReporter\n ::SendError(const std::string & msg)\n {\n this->textArea->insert(\"ERROR: \");\n this->textArea->insert(msg.c_str());\n this->textArea->insert(\"\\n\");\n this->textArea->show_insert_position();\n this->Show();\n Fl::check();\n }\n\n}\nSTYLE: tab replaced by 2 spaces\/*=========================================================================\n\nProgram: ORFEO Toolbox\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\n\nCopyright (c) Centre National d'Etudes Spatiales. All rights reserved.\nSee OTBCopyright.txt for details.\n\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"otbMsgReporter.h\"\n#include \n\nnamespace otb\n{\n \/** Initialize the singleton *\/\n MsgReporter::Pointer MsgReporter::m_Instance = NULL;\n\n \/\/\/ Constructor\n MsgReporter\n ::MsgReporter()\n {\n this->Build();\n wMainWindow->show();\n Fl_Text_Buffer * buffer = new Fl_Text_Buffer();\n this->textArea->buffer(buffer);\n }\n\n\n \/** Manage the singleton *\/\n MsgReporter::Pointer\n MsgReporter\n ::GetInstance()\n {\n if(!m_Instance)\n {\n m_Instance = MsgReporter::New();\n }\n return m_Instance;\n }\n \/\/Show\n void\n MsgReporter\n ::Show()\n {\n this->wMainWindow->show();\n }\n \/\/Hide\n void\n MsgReporter\n ::Hide()\n {\n this->wMainWindow->hide();\n }\n \/\/Set title\n void\n MsgReporter\n ::SetTitle(const std::string & title)\n {\n std::string str(title);\n str = str + \" message reporter window\";\n this->wMainWindow->label(str.c_str());\n }\n \/\/Send Msg\n void\n MsgReporter\n ::SendMsg(const std::string & msg)\n {\n this->textArea->insert(msg.c_str());\n this->textArea->insert(\"\\n\");\n this->textArea->show_insert_position();\n Fl::check();\n }\n\n \/\/Send Error\n void\n MsgReporter\n ::SendError(const std::string & msg)\n {\n this->textArea->insert(\"ERROR: \");\n this->textArea->insert(msg.c_str());\n this->textArea->insert(\"\\n\");\n this->textArea->show_insert_position();\n this->Show();\n Fl::check();\n }\n\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n\n This source file is part of the TEM tomography project.\n\n Copyright Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n#include \"Behaviors.h\"\n\n#include \"pqAlwaysConnectedBehavior.h\"\n#include \"pqApplicationCore.h\"\n#include \"pqDefaultViewBehavior.h\"\n#include \"pqInterfaceTracker.h\"\n#include \"pqPersistentMainWindowStateBehavior.h\"\n#include \"pqQtMessageHandlerBehavior.h\"\n#include \"pqStandardPropertyWidgetInterface.h\"\n#include \"pqStandardViewModules.h\"\n#include \"pqViewFrameActionsBehavior.h\"\n#include \"ProgressBehavior.h\"\n\n#include \n\nnamespace TEM\n{\n\/\/-----------------------------------------------------------------------------\nBehaviors::Behaviors(QMainWindow* mainWindow)\n{\n Q_ASSERT(mainWindow);\n\n \/\/ Register ParaView interfaces.\n pqInterfaceTracker* pgm = pqApplicationCore::instance()->interfaceTracker();\n\n \/\/ * adds support for standard paraview views.\n pgm->addInterface(new pqStandardViewModules(pgm));\n\n \/\/ * add support for ParaView properties panel widgets.\n pgm->addInterface(new pqStandardPropertyWidgetInterface(pgm));\n\n \/\/ Load plugins distributed with application.\n pqApplicationCore::instance()->loadDistributedPlugins();\n\n new pqQtMessageHandlerBehavior(this);\n new pqViewFrameActionsBehavior(this);\n new pqDefaultViewBehavior(this);\n new pqAlwaysConnectedBehavior(this);\n new pqPersistentMainWindowStateBehavior(mainWindow);\n new TEM::ProgressBehavior(mainWindow);\n\n \/\/ this will trigger the logic to setup reader\/writer factories, etc.\n pqApplicationCore::instance()->loadConfigurationXML(\"\");\n}\n\n\/\/-----------------------------------------------------------------------------\nBehaviors::~Behaviors()\n{\n}\n\n} \/\/ end of namespace TEM\nUpdates to build with ParaView\/master.\/******************************************************************************\n\n This source file is part of the TEM tomography project.\n\n Copyright Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n#include \"Behaviors.h\"\n\n#include \"pqAlwaysConnectedBehavior.h\"\n#include \"pqApplicationCore.h\"\n#include \"pqDefaultViewBehavior.h\"\n#include \"pqInterfaceTracker.h\"\n#include \"pqPersistentMainWindowStateBehavior.h\"\n#include \"pqQtMessageHandlerBehavior.h\"\n#include \"pqStandardPropertyWidgetInterface.h\"\n#include \"pqStandardViewFrameActionsImplementation.h\"\n#include \"ProgressBehavior.h\"\n\n#include \n\nnamespace TEM\n{\n\/\/-----------------------------------------------------------------------------\nBehaviors::Behaviors(QMainWindow* mainWindow)\n{\n Q_ASSERT(mainWindow);\n\n \/\/ Register ParaView interfaces.\n pqInterfaceTracker* pgm = pqApplicationCore::instance()->interfaceTracker();\n\n \/\/ * add support for ParaView properties panel widgets.\n pgm->addInterface(new pqStandardPropertyWidgetInterface(pgm));\n\n \/\/ * register standard types of view-frame actions.\n pgm->addInterface(new pqStandardViewFrameActionsImplementation(pgm));\n\n \/\/ Load plugins distributed with application.\n pqApplicationCore::instance()->loadDistributedPlugins();\n\n new pqQtMessageHandlerBehavior(this);\n new pqDefaultViewBehavior(this);\n new pqAlwaysConnectedBehavior(this);\n new pqPersistentMainWindowStateBehavior(mainWindow);\n new TEM::ProgressBehavior(mainWindow);\n\n \/\/ this will trigger the logic to setup reader\/writer factories, etc.\n pqApplicationCore::instance()->loadConfigurationXML(\"\");\n}\n\n\/\/-----------------------------------------------------------------------------\nBehaviors::~Behaviors()\n{\n}\n\n} \/\/ end of namespace TEM\n<|endoftext|>"} {"text":"\/*\n* Copyright (C) 2004-2019 ZNC, see the NOTICE file for details.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n* \n* \n* ==================================================\n* BotStatus module by QueenElsa • Version 1.0\n* --------------------------------------------------\n* Designed for use by the Undernet User-Committee\n* --------------------------------------------------\n* Channel: #development @ irc.undernet.org\n* Contact: QueenElsa@undernet.org\n* --------------------------------------------------\n* Announces the status of an attached bot. Based \n* of ClientNotify module.\n* ==================================================\n*\/\n\n\n#include \n#include \n#include \n\nusing std::set;\n\nclass CBotStatus : public CModule {\nprotected:\n\tCString m_sMethod;\n\tbool m_bOnDisconnect{};\n\tbool m_bOnConnect{};\n\n\tset m_sBotsSeen;\n\n\tvoid SaveSettings() {\n\t\tSetNV(\"method\", m_sMethod);\n\t\tSetNV(\"ondisconnect\", m_bOnDisconnect ? \"1\" : \"0\");\n\t\tSetNV(\"onconnect\", m_bOnConnect ? \"1\" : \"0\");\n\t}\n\n\tvoid SendNotification(const CString& sMessage) {\n\t\tif(m_sMethod == \"message\") {\n\t\t\tPutIRC(\"PRIVMSG #Arendelle :\" +sMessage);\n\t\t\tPutIRC(\"PRIVMSG #Uback :\" +sMessage);\n\t\t}\n\t\telse if(m_sMethod == \"notice\") {\n\t\t\tPutIRC(\"NOTICE #Arendelle :\" +sMessage);\n\t\t\tPutIRC(\"NOTICE #Uback :\" +sMessage);\n\t\t}\n\t}\n\npublic:\n\tMODCONSTRUCTOR(CBotStatus) {\n\t\tAddHelpCommand();\n\t\tAddCommand(\"Method\", static_cast(&CBotStatus::OnMethodCommand), \"\", \"Sets the notify method\");\n\t\tAddCommand(\"OnDisconnect\", static_cast(&CBotStatus::OnDisconnectCommand), \"\", \"Turns notifications on disconnect only.\");\n\t\tAddCommand(\"OnConnect\", static_cast(&CBotStatus::OnConnectCommand), \"\", \"Turns notifications on connect only.\");\n\t\tAddCommand(\"Show\", static_cast(&CBotStatus::OnShowCommand), \"\", \"Show the current settings\");\n\t}\n\n\tbool OnLoad(const CString& sArgs, CString& sMessage) override {\n\t\tm_sMethod = GetNV(\"method\");\n\n\t\tif(m_sMethod != \"notice\" && m_sMethod != \"message\" && m_sMethod != \"off\") {\n\t\t\tm_sMethod = \"message\";\n\t\t}\n\n\t\t\/\/ default = off for these:\n\n\t\tm_bOnDisconnect = (GetNV(\"ondisconnect\") == \"0\");\n\t\tm_bOnConnect = (GetNV(\"onconnect\") == \"0\");\n\n\t\treturn true;\n\t}\n\n\tvoid OnClientLogin() override {\n\t\tif(m_bOnConnect) {\n\t\t\tSendNotification(\"[ONLINE] Bot services have been restored. I will respond to commands I receive from ops.\");\n\t\t}\n\t}\n\n\tvoid OnClientDisconnect() override {\n\t\tif(m_bOnDisconnect) {\n\t\t\tSendNotification(\"[OFFLINE] Bot services are unavailable. I will not respond to any commands received. Please contact a User-Com Administrator.\");\n\t\t}\n\t}\n\n\tvoid OnMethodCommand(const CString& sCommand) {\n\t\tconst CString& sArg = sCommand.Token(1, true).AsLower();\n\n\t\tif (sArg != \"notice\" && sArg != \"message\" && sArg != \"off\") {\n\t\t\tPutModule(\"Usage: Method \");\n\t\t\treturn;\n\t\t}\n\n\t\tif (sArg == \"off\") {\n\t\t\tPutModule(\"MESSAGE METHOD CHANGED: Off - You will not be informed if your bot goes offline.\");\n\t\t\tPutModule(\"WARNING: Status updates will remain turned off until you change the method to NOTICE or MESSAGE.\");\n\t\t}\n\n\t\tif (sArg == \"notice\") {\n\t\t\tPutModule(\"MESSAGE METHOD CHANGED: Notice - You will be informed if your bot has gone offline via a channel notice.\");\n\t\t}\n\n\t\tif (sArg == \"message\") {\n\t\t\tPutModule(\"MESSAGE METHOD CHANGED: Message - You will be informed if your bot has gone offline via a channel message.\");\n\t\t}\n\n\t\tm_sMethod = sArg;\n\t\tSaveSettings();\n\t}\n\n\tvoid OnDisconnectCommand(const CString& sCommand) {\n\t\tconst CString& sArg = sCommand.Token(1, true).AsLower();\n\n\t\tif (sArg.empty()) {\n\t\t\tPutModule(\"Usage: OnDisconnect \");\n\t\t\treturn;\n\t\t}\n\n\t\tif (sArg == \"off\") {\n\t\t\tPutModule(\"DISCONNECT NOTIFICATION CHANGED: Off - You will not be informed if your bot goes offline.\");\n\t\t\tPutModule(\"WARNING: This setting will remain turned off until you manually turn it back on.\");\n\t\t}\n\n\t\tif (sArg == \"on\") {\n\t\t\tPutModule(\"DISCONNECT NOTIFICATION CHANGED: On - You will be informed if your bot goes offline.\");\n\t\t}\n\n\t\tm_bOnDisconnect = sArg.ToBool();\n\t\tSaveSettings();\n\t\tPutModule(\"Saved.\");\n\t}\n\n\t\tvoid OnConnectCommand(const CString& sCommand) {\n\t\tconst CString& sArg = sCommand.Token(1, true).AsLower();\n\n\t\tif (sArg.empty()) {\n\t\t\tPutModule(\"Usage: OnConnect \");\n\t\t\treturn;\n\t\t}\n\n\t\tif (sArg == \"off\") {\n\t\t\tPutModule(\"CONNECT NOTIFICATION CHANGED: Off - You will not be informed if your bot comes online.\");\n\t\t\tPutModule(\"WARNING: This setting will remain turned off until you manually turn it back on.\");\n\t\t}\n\n\t\tif (sArg == \"on\") {\n\t\t\tPutModule(\"CONNECT NOTIFICATION CHANGED: On - You will be informed if your bot comes online.\");\n\t\t}\n\n\t\tm_bOnConnect = sArg.ToBool();\n\t\tSaveSettings();\n\t\tPutModule(\"Saved.\");\n\t}\n\n\tvoid OnShowCommand(const CString& sLine) {\n\t\tPutModule(\"Current settings: Message Method: \" + m_sMethod + \", Notify if bot disconnected: \" + CString(m_bOnDisconnect) + \", Notify if bot reconnects: \" + CString(m_bOnConnect));\n\t}\n};\n\ntemplate<> void TModInfo(CModInfo& Info) {\n\tInfo.SetWikiPage(\"BotStatus\");\n}\n\nUSERMODULEDEFS(CBotStatus, \"Notifies you when your bot has come online or gone offline. Configurable.\")\n\nDelete BotStatus.cpp<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: inspagob.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 05:44:50 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SD_INSPAGOB_HXX\n#define _SD_INSPAGOB_HXX\n\n#ifndef _SV_BUTTON_HXX \/\/autogen\n#include \n#endif\n#ifndef _SV_DIALOG_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _SDTREELB_HXX\n#include \"sdtreelb.hxx\"\n#endif\n\nclass SdDrawDocument;\n\n\/\/------------------------------------------------------------------------\n\nclass SdInsertPagesObjsDlg : public ModalDialog\n{\nprivate:\n SdPageObjsTLB aLbTree;\n CheckBox aCbxLink;\n CheckBox aCbxMasters;\n OKButton aBtnOk;\n CancelButton aBtnCancel;\n HelpButton aBtnHelp;\n\n SfxMedium* pMedium;\n const SdDrawDocument* pDoc;\n const String& rName;\n\n void Reset();\n DECL_LINK( SelectObjectHdl, void * );\n\npublic:\n SdInsertPagesObjsDlg( Window* pParent,\n const SdDrawDocument* pDoc,\n SfxMedium* pSfxMedium,\n const String& rFileName );\n ~SdInsertPagesObjsDlg();\n\n List* GetList( USHORT nType );\n BOOL IsLink();\n BOOL IsRemoveUnnessesaryMasterPages() const;\n};\n\n\n#endif \/\/ _SD_INSPAGOB_HXX\nINTEGRATION: CWS sdwarningsbegone (1.3.316); FILE MERGED 2006\/11\/22 12:42:04 cl 1.3.316.1: #i69285# warning free code changes for unxlngi6.pro\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: inspagob.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: kz $ $Date: 2006-12-12 17:44:08 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SD_INSPAGOB_HXX\n#define _SD_INSPAGOB_HXX\n\n#ifndef _SV_BUTTON_HXX \/\/autogen\n#include \n#endif\n#ifndef _SV_DIALOG_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _SDTREELB_HXX\n#include \"sdtreelb.hxx\"\n#endif\n\nclass SdDrawDocument;\n\n\/\/------------------------------------------------------------------------\n\nclass SdInsertPagesObjsDlg : public ModalDialog\n{\nprivate:\n SdPageObjsTLB aLbTree;\n CheckBox aCbxLink;\n CheckBox aCbxMasters;\n OKButton aBtnOk;\n CancelButton aBtnCancel;\n HelpButton aBtnHelp;\n\n SfxMedium* pMedium;\n const SdDrawDocument* mpDoc;\n const String& rName;\n\n void Reset();\n DECL_LINK( SelectObjectHdl, void * );\n\npublic:\n SdInsertPagesObjsDlg( Window* pParent,\n const SdDrawDocument* pDoc,\n SfxMedium* pSfxMedium,\n const String& rFileName );\n ~SdInsertPagesObjsDlg();\n\n List* GetList( USHORT nType );\n BOOL IsLink();\n BOOL IsRemoveUnnessesaryMasterPages() const;\n};\n\n\n#endif \/\/ _SD_INSPAGOB_HXX\n<|endoftext|>"} {"text":"\/\/*****************************************************************************\n\/\/\n\/\/ Window.cpp\n\/\/\n\/\/ Class responsible for spawning, managing, and closing the OpenGL context.\n\/\/\n\/\/ Copyright (c) 2015 Brandon To, Minh Mai, and Yuzhou Liu\n\/\/ This code is licensed under BSD license (see LICENSE.txt for details)\n\/\/\n\/\/ Created:\n\/\/ December 27, 2015\n\/\/\n\/\/ Modified:\n\/\/ December 28, 2015\n\/\/\n\/\/*****************************************************************************\n#include \"Window.h\"\n\n#include \n\n#include \n\n\/\/*****************************************************************************\n\/\/\n\/\/! Constructor for Window. Acquires resources for window and renderer.\n\/\/!\n\/\/! \\param None.\n\/\/!\n\/\/! \\return None.\n\/\/\n\/\/*****************************************************************************\nWindow::Window()\n : _window(NULL), _renderer(NULL), _width(_DEFAULT_WIDTH),\n _height(_DEFAULT_HEIGHT)\n{\n \/\/\n \/\/ Initialize window\n \/\/\n if (!_initialize())\n {\n std::cerr << \"[ERROR] Window::Window(): Failed to initialize.\" <<\n std::endl;\n return;\n }\n\n \/\/\n \/\/ Creates base hand image\n \/\/\n _baseImage = std::unique_ptr(new Image(_renderer, \"data\/gfx\/hand_base.png\"));\n\n \/\/\n \/\/ Creates and add images to finger image list\n \/\/\n _fingerImageList.push_back(std::unique_ptr(new Image(_renderer, \"data\/gfx\/hand_right_thumb.png\")));\n _fingerImageList.push_back(std::unique_ptr(new Image(_renderer, \"data\/gfx\/hand_right_index.png\")));\n _fingerImageList.push_back(std::unique_ptr(new Image(_renderer, \"data\/gfx\/hand_right_middle.png\")));\n _fingerImageList.push_back(std::unique_ptr(new Image(_renderer, \"data\/gfx\/hand_right_ring.png\")));\n _fingerImageList.push_back(std::unique_ptr(new Image(_renderer, \"data\/gfx\/hand_right_pinky.png\")));\n\n \/\/\n \/\/ Centre all images for aesthetic purposes\n \/\/\n _centreImage(_baseImage);\n for (auto it = _fingerImageList.begin(); it != _fingerImageList.end(); it++)\n {\n _centreImage(*it);\n }\n}\n\n\/\/*****************************************************************************\n\/\/\n\/\/! Destructor for Window. Releases resources used by window and renderer.\n\/\/!\n\/\/! \\param None.\n\/\/!\n\/\/! \\return None.\n\/\/\n\/\/*****************************************************************************\nWindow::~Window()\n{\n _terminate();\n}\n\n\/\/*****************************************************************************\n\/\/\n\/\/! Updates the window. Called once every frame.\n\/\/!\n\/\/! \\param None.\n\/\/!\n\/\/! \\return None.\n\/\/\n\/\/*****************************************************************************\nvoid Window::update()\n{\n _processInput();\n _update();\n _render();\n}\n\n\/\/*****************************************************************************\n\/\/\n\/\/! Initializes the window.\n\/\/!\n\/\/! \\param None.\n\/\/!\n\/\/! \\return Returns \\b true if the window was initialized successfully and\n\/\/! \\b false otherwise.\n\/\/\n\/\/*****************************************************************************\nbool Window::_initialize()\n{\n int iRetVal = 0;\n\n \/\/\n \/\/ Creates OpenGL context\n \/\/\n _window = SDL_CreateWindow(\"Human Interface for Robotic Control\",\n SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, _width, _height,\n SDL_WINDOW_SHOWN);\n if (_window == NULL)\n {\n std::cerr << \"[ERROR] Window::_initialize(): SDL_CreateWindow() \"\\\n \"failed. SDL Error \" << SDL_GetError() << std::endl;\n return false;\n }\n\n \/\/\n \/\/ Creates renderer\n \/\/\n _renderer = SDL_CreateRenderer(_window, -1, SDL_RENDERER_ACCELERATED |\n SDL_RENDERER_TARGETTEXTURE);\n if (_renderer == NULL)\n {\n std::cerr << \"[ERROR] Window::_initialize(): SDL_CreateRenderer() \"\\\n \"failed. SDL Error \" << SDL_GetError() << std::endl;\n return false;\n }\n\n \/\/\n \/\/ Sets renderer to default to an Opqaue White color on screen clear\n \/\/\n iRetVal = SDL_SetRenderDrawColor(_renderer, 0xFF, 0xFF, 0xFF,\n SDL_ALPHA_OPAQUE);\n if (iRetVal < 0)\n {\n std::cerr << \"[ERROR] Window::_initialize(): SDL_SetRenderDrawColor()\"\\\n \" failed. SDL Error \" << SDL_GetError() << std::endl;\n return false;\n }\n\n \/\/\n \/\/ Sets a device independent resolution for rendering\n \/\/\n iRetVal = SDL_RenderSetLogicalSize(_renderer, _width, _height);\n if (iRetVal < 0)\n {\n std::cerr << \"[ERROR] Window::_initialize(): \"\\\n \"SDL_RenderSetLogicalSize() failed. SDL Error \" << SDL_GetError()\n << std::endl;\n return false;\n }\n\n return true;\n}\n\n\/\/*****************************************************************************\n\/\/\n\/\/! Terminates the window.\n\/\/!\n\/\/! \\param None.\n\/\/!\n\/\/! \\return None.\n\/\/\n\/\/*****************************************************************************\nvoid Window::_terminate()\n{\n if (_renderer != NULL)\n {\n SDL_DestroyRenderer(_renderer);\n }\n\n if (_window != NULL)\n {\n SDL_DestroyWindow(_window);\n }\n}\n\n\/\/*****************************************************************************\n\/\/\n\/\/! Processes user input. Called once per frame by update().\n\/\/!\n\/\/! \\param None.\n\/\/!\n\/\/! \\return None.\n\/\/\n\/\/*****************************************************************************\nvoid Window::_processInput()\n{\n SDL_Event event;\n\n \/\/\n \/\/ Polls the event queue for pending events\n \/\/\n while (SDL_PollEvent(&event))\n {\n \/\/\n \/\/ Notifies the Application class that the user wants to quit\n \/\/\n if (event.type == SDL_QUIT)\n {\n notify(SDL_QUIT);\n }\n }\n}\n\n\/\/*****************************************************************************\n\/\/\n\/\/! Updates program logic. Called once per frame by update().\n\/\/!\n\/\/! \\param None.\n\/\/!\n\/\/! \\return None.\n\/\/\n\/\/*****************************************************************************\nvoid Window::_update()\n{\n \/\/ TODO (Brandon): Implement\n}\n\n\/\/*****************************************************************************\n\/\/\n\/\/! Renders frame. Called once per frame by update().\n\/\/!\n\/\/! \\param None.\n\/\/!\n\/\/! \\return None.\n\/\/\n\/\/*****************************************************************************\nvoid Window::_render()\n{\n \/\/\n \/\/ Clears screen\n \/\/\n SDL_RenderClear(_renderer);\n\n \/\/\n \/\/ Renders all images to screen\n \/\/\n _baseImage->onRender();\n for (auto it = _fingerImageList.begin(); it != _fingerImageList.end();\n it++)\n {\n (*it)->onRender();\n }\n\n \/\/\n \/\/ Updates screen (swaps screen buffers)\n \/\/\n SDL_RenderPresent(_renderer);\n}\n\n\/\/*****************************************************************************\n\/\/\n\/\/! Centre the image on the screen.\n\/\/!\n\/\/! \\param image the image to be centred.\n\/\/!\n\/\/! \\return None.\n\/\/\n\/\/*****************************************************************************\nvoid Window::_centreImage(const std::unique_ptr &image)\n{\n SDL_Rect centredRect;\n centredRect.w = image->getWidth();\n centredRect.h = image->getHeight();\n centredRect.x = (_width - centredRect.w) \/ 2;\n centredRect.y = (_height - centredRect.h) \/ 2;\n image->setRenderRect(¢redRect);\n}\nChanged occurrences of NULL to nullptr when dealing with pointers.\/\/*****************************************************************************\n\/\/\n\/\/ Window.cpp\n\/\/\n\/\/ Class responsible for spawning, managing, and closing the OpenGL context.\n\/\/\n\/\/ Copyright (c) 2015 Brandon To, Minh Mai, and Yuzhou Liu\n\/\/ This code is licensed under BSD license (see LICENSE.txt for details)\n\/\/\n\/\/ Created:\n\/\/ December 27, 2015\n\/\/\n\/\/ Modified:\n\/\/ December 28, 2015\n\/\/\n\/\/*****************************************************************************\n#include \"Window.h\"\n\n#include \n\n#include \n\n\/\/*****************************************************************************\n\/\/\n\/\/! Constructor for Window. Acquires resources for window and renderer.\n\/\/!\n\/\/! \\param None.\n\/\/!\n\/\/! \\return None.\n\/\/\n\/\/*****************************************************************************\nWindow::Window()\n : _window(nullptr), _renderer(nullptr), _width(_DEFAULT_WIDTH),\n _height(_DEFAULT_HEIGHT)\n{\n \/\/\n \/\/ Initialize window\n \/\/\n if (!_initialize())\n {\n std::cerr << \"[ERROR] Window::Window(): Failed to initialize.\" <<\n std::endl;\n return;\n }\n\n \/\/\n \/\/ Creates base hand image\n \/\/\n _baseImage = std::unique_ptr(new Image(_renderer, \"data\/gfx\/hand_base.png\"));\n\n \/\/\n \/\/ Creates and add images to finger image list\n \/\/\n _fingerImageList.push_back(std::unique_ptr(new Image(_renderer, \"data\/gfx\/hand_right_thumb.png\")));\n _fingerImageList.push_back(std::unique_ptr(new Image(_renderer, \"data\/gfx\/hand_right_index.png\")));\n _fingerImageList.push_back(std::unique_ptr(new Image(_renderer, \"data\/gfx\/hand_right_middle.png\")));\n _fingerImageList.push_back(std::unique_ptr(new Image(_renderer, \"data\/gfx\/hand_right_ring.png\")));\n _fingerImageList.push_back(std::unique_ptr(new Image(_renderer, \"data\/gfx\/hand_right_pinky.png\")));\n\n \/\/\n \/\/ Centre all images for aesthetic purposes\n \/\/\n _centreImage(_baseImage);\n for (auto it = _fingerImageList.begin(); it != _fingerImageList.end(); it++)\n {\n _centreImage(*it);\n }\n}\n\n\/\/*****************************************************************************\n\/\/\n\/\/! Destructor for Window. Releases resources used by window and renderer.\n\/\/!\n\/\/! \\param None.\n\/\/!\n\/\/! \\return None.\n\/\/\n\/\/*****************************************************************************\nWindow::~Window()\n{\n _terminate();\n}\n\n\/\/*****************************************************************************\n\/\/\n\/\/! Updates the window. Called once every frame.\n\/\/!\n\/\/! \\param None.\n\/\/!\n\/\/! \\return None.\n\/\/\n\/\/*****************************************************************************\nvoid Window::update()\n{\n _processInput();\n _update();\n _render();\n}\n\n\/\/*****************************************************************************\n\/\/\n\/\/! Initializes the window.\n\/\/!\n\/\/! \\param None.\n\/\/!\n\/\/! \\return Returns \\b true if the window was initialized successfully and\n\/\/! \\b false otherwise.\n\/\/\n\/\/*****************************************************************************\nbool Window::_initialize()\n{\n int iRetVal = 0;\n\n \/\/\n \/\/ Creates OpenGL context\n \/\/\n _window = SDL_CreateWindow(\"Human Interface for Robotic Control\",\n SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, _width, _height,\n SDL_WINDOW_SHOWN);\n if (_window == nullptr)\n {\n std::cerr << \"[ERROR] Window::_initialize(): SDL_CreateWindow() \"\\\n \"failed. SDL Error \" << SDL_GetError() << std::endl;\n return false;\n }\n\n \/\/\n \/\/ Creates renderer\n \/\/\n _renderer = SDL_CreateRenderer(_window, -1, SDL_RENDERER_ACCELERATED |\n SDL_RENDERER_TARGETTEXTURE);\n if (_renderer == nullptr)\n {\n std::cerr << \"[ERROR] Window::_initialize(): SDL_CreateRenderer() \"\\\n \"failed. SDL Error \" << SDL_GetError() << std::endl;\n return false;\n }\n\n \/\/\n \/\/ Sets renderer to default to an Opqaue White color on screen clear\n \/\/\n iRetVal = SDL_SetRenderDrawColor(_renderer, 0xFF, 0xFF, 0xFF,\n SDL_ALPHA_OPAQUE);\n if (iRetVal < 0)\n {\n std::cerr << \"[ERROR] Window::_initialize(): SDL_SetRenderDrawColor()\"\\\n \" failed. SDL Error \" << SDL_GetError() << std::endl;\n return false;\n }\n\n \/\/\n \/\/ Sets a device independent resolution for rendering\n \/\/\n iRetVal = SDL_RenderSetLogicalSize(_renderer, _width, _height);\n if (iRetVal < 0)\n {\n std::cerr << \"[ERROR] Window::_initialize(): \"\\\n \"SDL_RenderSetLogicalSize() failed. SDL Error \" << SDL_GetError()\n << std::endl;\n return false;\n }\n\n return true;\n}\n\n\/\/*****************************************************************************\n\/\/\n\/\/! Terminates the window.\n\/\/!\n\/\/! \\param None.\n\/\/!\n\/\/! \\return None.\n\/\/\n\/\/*****************************************************************************\nvoid Window::_terminate()\n{\n if (_renderer != nullptr)\n {\n SDL_DestroyRenderer(_renderer);\n }\n\n if (_window != nullptr)\n {\n SDL_DestroyWindow(_window);\n }\n}\n\n\/\/*****************************************************************************\n\/\/\n\/\/! Processes user input. Called once per frame by update().\n\/\/!\n\/\/! \\param None.\n\/\/!\n\/\/! \\return None.\n\/\/\n\/\/*****************************************************************************\nvoid Window::_processInput()\n{\n SDL_Event event;\n\n \/\/\n \/\/ Polls the event queue for pending events\n \/\/\n while (SDL_PollEvent(&event))\n {\n \/\/\n \/\/ Notifies the Application class that the user wants to quit\n \/\/\n if (event.type == SDL_QUIT)\n {\n notify(SDL_QUIT);\n }\n }\n}\n\n\/\/*****************************************************************************\n\/\/\n\/\/! Updates program logic. Called once per frame by update().\n\/\/!\n\/\/! \\param None.\n\/\/!\n\/\/! \\return None.\n\/\/\n\/\/*****************************************************************************\nvoid Window::_update()\n{\n \/\/ TODO (Brandon): Implement\n}\n\n\/\/*****************************************************************************\n\/\/\n\/\/! Renders frame. Called once per frame by update().\n\/\/!\n\/\/! \\param None.\n\/\/!\n\/\/! \\return None.\n\/\/\n\/\/*****************************************************************************\nvoid Window::_render()\n{\n \/\/\n \/\/ Clears screen\n \/\/\n SDL_RenderClear(_renderer);\n\n \/\/\n \/\/ Renders all images to screen\n \/\/\n _baseImage->onRender();\n for (auto it = _fingerImageList.begin(); it != _fingerImageList.end();\n it++)\n {\n (*it)->onRender();\n }\n\n \/\/\n \/\/ Updates screen (swaps screen buffers)\n \/\/\n SDL_RenderPresent(_renderer);\n}\n\n\/\/*****************************************************************************\n\/\/\n\/\/! Centre the image on the screen.\n\/\/!\n\/\/! \\param image the image to be centred.\n\/\/!\n\/\/! \\return None.\n\/\/\n\/\/*****************************************************************************\nvoid Window::_centreImage(const std::unique_ptr &image)\n{\n SDL_Rect centredRect;\n centredRect.w = image->getWidth();\n centredRect.h = image->getHeight();\n centredRect.x = (_width - centredRect.w) \/ 2;\n centredRect.y = (_height - centredRect.h) \/ 2;\n image->setRenderRect(¢redRect);\n}\n<|endoftext|>"} {"text":"\/\/ OfficeXlsFile.cpp : Implementation of COfficeXlsFile\r\n\r\n#include \"stdafx.h\"\r\n\r\n#include \r\n#include \r\n\r\n#include \r\n#pragma warning(push)\r\n#pragma warning(disable : 4244)\r\n#include \r\n#pragma warning(pop)\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \"source\\ConvertXls2Xlsx.h\"\r\n\r\n#include \"..\\Common\\XmlUtils.h\"\r\n#include \"..\\Common\\ASCATLError.h\"\r\n\r\n\r\n#include \"OfficeXlsFile.h\"\r\n\r\n\/\/ : 1 , xlsx docx\r\n\/\/ 0 , package\r\n#ifndef STANDALONE_USE\r\n\t#define STANDALONE_USE 0\/\/ : (1) (0)\r\n#endif\r\n\r\n\/\/ - uuid\r\nboost::filesystem::wpath MakeTempDirectoryName(const std::wstring & Dst)\r\n{\r\n boost::uuids::random_generator gen;\r\n boost::uuids::uuid u = gen();\r\n boost::filesystem::wpath path = boost::filesystem::wpath(Dst) \/ boost::lexical_cast(u);\r\n return path;\r\n}\r\n\r\nstd::wstring bstr2wstring(BSTR str)\r\n{\r\n return str ? std::wstring(&str[0], &str[::SysStringLen(str)]) : L\"\";\r\n}\r\n\r\nboost::filesystem::wpath MakeTempDirectoryName(BSTR Dst)\r\n{\r\n return MakeTempDirectoryName(bstr2wstring(Dst));\r\n}\r\n\/\/\/------------------------------------------------------------------------------------\r\n\r\n\/\/ COfficeXlsFile\r\nCOfficeXlsFile::COfficeXlsFile()\r\n{\r\n#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)\r\n office_utils_.CoCreateInstance(__uuidof(ASCOfficeUtils::COfficeUtils)); \r\n#endif\r\n}\r\n\r\nHRESULT COfficeXlsFile::SaveToFile(BSTR sDstFileName, BSTR sSrcPath, BSTR sXMLOptions)\r\n{\r\n return E_NOTIMPL;\r\n}\r\n\r\nHRESULT COfficeXlsFile::LoadFromFile(BSTR sSrcFileName, BSTR sDstPath, BSTR sXMLOptions)\r\n{\r\n HRESULT hr;\r\n if (!initialized())\r\n return E_FAIL;\r\n\r\n if (!sDstPath)\r\n {\r\n _ASSERTE(!!sDstPath);\r\n return E_FAIL;\r\n }\r\n\r\n#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)\r\n boost::filesystem::wpath outputDir = boost::filesystem::wpath(bstr2wstring(sDstPath)).parent_path();\r\n#else\r\n boost::filesystem::wpath outputDir = boost::filesystem::wpath(bstr2wstring(sDstPath));\r\n#endif\r\n\r\n \r\n\r\n#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)\r\n boost::filesystem::wpath dstTempPath = MakeTempDirectoryName(BOOST_STRING_PATH(outputDir));\r\n#else\r\n boost::filesystem::wpath dstTempPath = outputDir.string();\r\n#endif\r\n\r\n try\r\n {\r\n#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)\r\n \/\/ \r\n boost::filesystem::create_directory(dstTempPath);\r\n#endif\r\n hr = LoadFromFileImpl(bstr2wstring(sSrcFileName), BOOST_STRING_PATH(dstTempPath), bstr2wstring(sDstPath));\r\n \r\n }\r\n catch(...)\r\n {\r\n hr = E_FAIL;\r\n }\r\n\r\n\r\n\r\n#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)\r\n \/\/ ( )\r\n try \r\n {\r\n boost::filesystem::remove_all(dstTempPath);\r\n }\r\n catch(...)\r\n {\r\n }\r\n#endif\r\n \r\n return hr;\r\n}\r\n\r\n\r\n\r\nHRESULT COfficeXlsFile::LoadFromFileImpl(const std::wstring & srcFileName,\r\n const std::wstring & dstTempPath,\r\n const std::wstring & dstPath)\r\n{\r\n HRESULT hr = AVS_ERROR_UNEXPECTED; \r\n \r\n\tProgressCallback ffCallBack;\r\n\r\n\tffCallBack.OnProgress\t=\tOnProgressFunc;\r\n\tffCallBack.OnProgressEx\t=\tOnProgressExFunc;\r\n\tffCallBack.caller\t\t=\tthis;\r\n\r\n\thr = ConvertXls2Xlsx(srcFileName, dstTempPath, &ffCallBack);\r\n\r\n\tif (hr != S_OK) return hr;\r\n \r\n#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)\r\n if FAILED(hr = office_utils_->CompressFileOrDirectory(ATL::CComBSTR(dstTempPath.c_str()), ATL::CComBSTR(dstPath.c_str()), (-1)))\r\n return hr;\r\n#endif\r\n\r\n return S_OK;\r\n}\r\n\r\nbool COfficeXlsFile::initialized()\r\n{\r\n#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)\r\n return (!!office_utils_);\r\n#endif\r\n return true;\r\n}\r\n\r\nvoid COfficeXlsFile::OnProgressFunc (LPVOID lpParam, long nID, long nPercent)\r\n{\r\n\t\/\/g_oCriticalSection.Enter();\r\n\r\n\tCOfficeXlsFile* pXlsFile = reinterpret_cast(lpParam);\r\n\tif (pXlsFile != NULL)\r\n\t{\r\n\t\tpXlsFile->OnProgress(nID, nPercent);\r\n\t}\r\n\r\n\t\/\/g_oCriticalSection.Leave();\r\n}\r\n\r\nvoid COfficeXlsFile::OnProgressExFunc (LPVOID lpParam, long nID, long nPercent, short* pStop)\r\n{\r\n\t\/\/g_oCriticalSection.Enter();\r\n\r\n\tCOfficeXlsFile* pXlsFile = reinterpret_cast(lpParam);\r\n\tif (pXlsFile != NULL)\r\n\t{\r\n\t\tpXlsFile->OnProgressEx(nID, nPercent, pStop);\r\n\t}\r\n\r\n\t\/\/g_oCriticalSection.Leave();\r\n}\r\n \/\/ OfficeXlsFile.cpp : Implementation of COfficeXlsFile\r\n\r\n#include \"stdafx.h\"\r\n\r\n#include \r\n#include \r\n\r\n#include \r\n#pragma warning(push)\r\n#pragma warning(disable : 4244)\r\n#include \r\n#pragma warning(pop)\r\n\r\n#include \r\n#include \r\n#include \r\n#include \"..\/Common\/boost_filesystem_version.h\"\r\n\r\n#include \"source\/ConvertXls2Xlsx.h\"\r\n\r\n#include \"..\/Common\/XmlUtils.h\"\r\n#include \"..\/Common\/ASCATLError.h\"\r\n\r\n\r\n#include \"OfficeXlsFile.h\"\r\n\r\n\/\/ : 1 , xlsx docx\r\n\/\/ 0 , package\r\n#ifndef STANDALONE_USE\r\n\t#define STANDALONE_USE 0\/\/ : (1) (0)\r\n#endif\r\n\r\n\/\/ - uuid\r\nboost::filesystem::wpath MakeTempDirectoryName(const std::wstring & Dst)\r\n{\r\n boost::uuids::random_generator gen;\r\n boost::uuids::uuid u = gen();\r\n boost::filesystem::wpath path = boost::filesystem::wpath(Dst) \/ boost::lexical_cast(u);\r\n return path;\r\n}\r\n\r\nstd::wstring bstr2wstring(BSTR str)\r\n{\r\n return str ? std::wstring(&str[0], &str[::SysStringLen(str)]) : L\"\";\r\n}\r\n\r\nboost::filesystem::wpath MakeTempDirectoryName(BSTR Dst)\r\n{\r\n return MakeTempDirectoryName(bstr2wstring(Dst));\r\n}\r\n\/\/\/------------------------------------------------------------------------------------\r\n\r\n\/\/ COfficeXlsFile\r\nCOfficeXlsFile::COfficeXlsFile()\r\n{\r\n#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)\r\n office_utils_.CoCreateInstance(__uuidof(ASCOfficeUtils::COfficeUtils)); \r\n#endif\r\n}\r\n\r\nHRESULT COfficeXlsFile::SaveToFile(BSTR sDstFileName, BSTR sSrcPath, BSTR sXMLOptions)\r\n{\r\n return E_NOTIMPL;\r\n}\r\n\r\nHRESULT COfficeXlsFile::LoadFromFile(BSTR sSrcFileName, BSTR sDstPath, BSTR sXMLOptions)\r\n{\r\n HRESULT hr;\r\n if (!initialized())\r\n return E_FAIL;\r\n\r\n if (!sDstPath)\r\n {\r\n _ASSERTE(!!sDstPath);\r\n return E_FAIL;\r\n }\r\n\r\n#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)\r\n boost::filesystem::wpath outputDir = boost::filesystem::wpath(bstr2wstring(sDstPath)).parent_path();\r\n#else\r\n boost::filesystem::wpath outputDir = boost::filesystem::wpath(bstr2wstring(sDstPath));\r\n#endif\r\n\r\n \r\n\r\n#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)\r\n boost::filesystem::wpath dstTempPath = MakeTempDirectoryName(BOOST_STRING_PATH(outputDir));\r\n#else\r\n boost::filesystem::wpath dstTempPath = outputDir.string();\r\n#endif\r\n\r\n try\r\n {\r\n#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)\r\n \/\/ \r\n boost::filesystem::create_directory(dstTempPath);\r\n#endif\r\n hr = LoadFromFileImpl(bstr2wstring(sSrcFileName), BOOST_STRING_PATH(dstTempPath), bstr2wstring(sDstPath));\r\n \r\n }\r\n catch(...)\r\n {\r\n hr = E_FAIL;\r\n }\r\n\r\n\r\n\r\n#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)\r\n \/\/ ( )\r\n try \r\n {\r\n boost::filesystem::remove_all(dstTempPath);\r\n }\r\n catch(...)\r\n {\r\n }\r\n#endif\r\n \r\n return hr;\r\n}\r\n\r\n\r\n\r\nHRESULT COfficeXlsFile::LoadFromFileImpl(const std::wstring & srcFileName,\r\n const std::wstring & dstTempPath,\r\n const std::wstring & dstPath)\r\n{\r\n HRESULT hr = AVS_ERROR_UNEXPECTED; \r\n \r\n\tProgressCallback ffCallBack;\r\n\r\n\tffCallBack.OnProgress\t=\tOnProgressFunc;\r\n\tffCallBack.OnProgressEx\t=\tOnProgressExFunc;\r\n\tffCallBack.caller\t\t=\tthis;\r\n\r\n\thr = ConvertXls2Xlsx(srcFileName, dstTempPath, &ffCallBack);\r\n\r\n\tif (hr != S_OK) return hr;\r\n \r\n#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)\r\n if FAILED(hr = office_utils_->CompressFileOrDirectory(ATL::CComBSTR(dstTempPath.c_str()), ATL::CComBSTR(dstPath.c_str()), (-1)))\r\n return hr;\r\n#endif\r\n\r\n return S_OK;\r\n}\r\n\r\nbool COfficeXlsFile::initialized()\r\n{\r\n#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)\r\n return (!!office_utils_);\r\n#endif\r\n return true;\r\n}\r\n\r\nvoid COfficeXlsFile::OnProgressFunc (LPVOID lpParam, long nID, long nPercent)\r\n{\r\n\t\/\/g_oCriticalSection.Enter();\r\n\r\n\tCOfficeXlsFile* pXlsFile = reinterpret_cast(lpParam);\r\n\tif (pXlsFile != NULL)\r\n\t{\r\n\t\tpXlsFile->OnProgress(nID, nPercent);\r\n\t}\r\n\r\n\t\/\/g_oCriticalSection.Leave();\r\n}\r\n\r\nvoid COfficeXlsFile::OnProgressExFunc (LPVOID lpParam, long nID, long nPercent, short* pStop)\r\n{\r\n\t\/\/g_oCriticalSection.Enter();\r\n\r\n\tCOfficeXlsFile* pXlsFile = reinterpret_cast(lpParam);\r\n\tif (pXlsFile != NULL)\r\n\t{\r\n\t\tpXlsFile->OnProgressEx(nID, nPercent, pStop);\r\n\t}\r\n\r\n\t\/\/g_oCriticalSection.Leave();\r\n}\r\n<|endoftext|>"} {"text":"\/* * * * * * * * * * * * * * * * * * * * * * * * * * * * *\r\n* BSD 3-Clause License\r\n\/* * * * * * * * * * * * * * * * * * * * * * * * * * * * *\r\nCode by Cassius Fiorin - cafiorin@gmail.com\r\nhttp:\/\/pinballhomemade.blogspot.com.br\r\n* * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\r\n\r\n#include \"Utils.h\"\r\n\r\nvoid myStrcpy(char *str1, const char *str2)\r\n{\r\n\tint bufsize = sizeof(str1);\r\n\tint len = (int) strlen(str2);\r\n\tif (len < bufsize)\r\n\t{\r\n\t\tstrcpy(str1, str2);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tstrncpy(str1, str2, bufsize);\r\n\t\tstr1[bufsize - 1] = 0;\r\n\t}\r\n\r\n}\r\n\r\n#ifdef ARDUINO\r\nlong Millis()\r\n{\r\n\treturn millis();\r\n}\r\n\r\n#endif\r\n\r\n#ifdef DOS\r\nclock_t Millis()\r\n{\r\n\treturn clock();\r\n}\r\n\r\nlong timediff(clock_t t2, clock_t t1) \r\n{\r\n\tlong elapsed;\r\n\telapsed = ((double)t2 - t1) \/ CLOCKS_PER_SEC * 1000;\r\n\treturn elapsed;\r\n}\r\n\r\nvoid gotoxy(int x, int y)\r\n{\r\n\tCOORD coord;\r\n\tcoord.X = x;\r\n\tcoord.Y = y;\r\n\tSetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);\r\n}\r\n\r\nvoid getCursorXY(int &x, int&y)\r\n{\r\n\tCONSOLE_SCREEN_BUFFER_INFO csbi;\r\n\r\n\tif (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))\r\n\t{\r\n\t\tx = csbi.dwCursorPosition.X;\r\n\t\ty = csbi.dwCursorPosition.Y;\r\n\t}\r\n}\r\n\r\nvoid setcolor(WORD color)\r\n{\r\n\tSetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);\r\n\treturn;\r\n}\r\n\r\nvoid clrscr()\r\n{\r\n\tCOORD coordScreen = { 0, 0 };\r\n\tDWORD cCharsWritten;\r\n\tCONSOLE_SCREEN_BUFFER_INFO csbi;\r\n\tDWORD dwConSize;\r\n\tHANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);\r\n\r\n\tGetConsoleScreenBufferInfo(hConsole, &csbi);\r\n\tdwConSize = csbi.dwSize.X * csbi.dwSize.Y;\r\n\tFillConsoleOutputCharacter(hConsole, TEXT(' '), dwConSize, coordScreen, &cCharsWritten);\r\n\tGetConsoleScreenBufferInfo(hConsole, &csbi);\r\n\tFillConsoleOutputAttribute(hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten);\r\n\tSetConsoleCursorPosition(hConsole, coordScreen);\r\n\treturn;\r\n}\r\n\r\nvoid box(unsigned x, unsigned y, unsigned sx, unsigned sy, unsigned char col, unsigned char col2, char text_[])\r\n{\r\n\tunsigned i, j, m;\r\n\t{\r\n\r\n\t\tm = (sx - x); \/\/differential\r\n\t\tj = m \/ 8; \/\/adjust\r\n\t\tj = j - 1; \/\/more adjustment\r\n\t\tgotoxy(x, y); cprintf(\"┌\"); \/\/Top left corner of box\r\n\t\tgotoxy(sx, y); cprintf(\"¬\"); \/\/Top right corner of box\r\n\t\tgotoxy(x, sy); cprintf(\"└\"); \/\/Bottom left corner of box\r\n\t\tgotoxy(sx, sy); cprintf(\"┌\"); \/\/Bottom right corner of box\r\n\r\n\t\tfor (i = x + 1; iFixed square\/* * * * * * * * * * * * * * * * * * * * * * * * * * * * *\r\n* BSD 3-Clause License\r\n\/* * * * * * * * * * * * * * * * * * * * * * * * * * * * *\r\nCode by Cassius Fiorin - cafiorin@gmail.com\r\nhttp:\/\/pinballhomemade.blogspot.com.br\r\n* * * * * * * * * * * * * * * * * * * * * * * * * * * * *\/\r\n\r\n#include \"Utils.h\"\r\n\r\n#pragma execution_character_set(\"utf-8\") \r\n\r\nvoid myStrcpy(char *str1, const char *str2)\r\n{\r\n\tint bufsize = sizeof(str1);\r\n\tint len = (int) strlen(str2);\r\n\tif (len < bufsize)\r\n\t{\r\n\t\tstrcpy(str1, str2);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tstrncpy(str1, str2, bufsize);\r\n\t\tstr1[bufsize - 1] = 0;\r\n\t}\r\n\r\n}\r\n\r\n#ifdef ARDUINO\r\nlong Millis()\r\n{\r\n\treturn millis();\r\n}\r\n\r\n#endif\r\n\r\n#ifdef DOS\r\nclock_t Millis()\r\n{\r\n\treturn clock();\r\n}\r\n\r\nlong timediff(clock_t t2, clock_t t1) \r\n{\r\n\tlong elapsed;\r\n\telapsed = (long) ((double)t2 - t1) \/ CLOCKS_PER_SEC * 1000;\r\n\treturn elapsed;\r\n}\r\n\r\nvoid gotoxy(int x, int y)\r\n{\r\n\tCOORD coord;\r\n\tcoord.X = x;\r\n\tcoord.Y = y;\r\n\tSetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);\r\n}\r\n\r\nvoid getCursorXY(int &x, int&y)\r\n{\r\n\tCONSOLE_SCREEN_BUFFER_INFO csbi;\r\n\r\n\tif (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))\r\n\t{\r\n\t\tx = csbi.dwCursorPosition.X;\r\n\t\ty = csbi.dwCursorPosition.Y;\r\n\t}\r\n}\r\n\r\nvoid setcolor(WORD color)\r\n{\r\n\tSetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);\r\n\treturn;\r\n}\r\n\r\nvoid clrscr()\r\n{\r\n\tCOORD coordScreen = { 0, 0 };\r\n\tDWORD cCharsWritten;\r\n\tCONSOLE_SCREEN_BUFFER_INFO csbi;\r\n\tDWORD dwConSize;\r\n\tHANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);\r\n\r\n\tGetConsoleScreenBufferInfo(hConsole, &csbi);\r\n\tdwConSize = csbi.dwSize.X * csbi.dwSize.Y;\r\n\tFillConsoleOutputCharacter(hConsole, TEXT(' '), dwConSize, coordScreen, &cCharsWritten);\r\n\tGetConsoleScreenBufferInfo(hConsole, &csbi);\r\n\tFillConsoleOutputAttribute(hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten);\r\n\tSetConsoleCursorPosition(hConsole, coordScreen);\r\n\treturn;\r\n}\r\n\r\nvoid box(unsigned x, unsigned y, unsigned sx, unsigned sy, unsigned char col, unsigned char col2, char text_[])\r\n{\r\n\tunsigned i, j, m;\r\n\t{\r\n\r\n\t\tm = (sx - x); \/\/differential\r\n\t\tj = m \/ 8; \/\/adjust\r\n\t\tj = j - 1; \/\/more adjustment\r\n\t\tgotoxy(x, y); cprintf(\"*\"); \/\/ ┌ \/\/Top left corner of box\r\n\t\tgotoxy(sx, y); cprintf(\"*\"); \/\/ ┐ \/\/Top right corner of box\r\n\t\tgotoxy(x, sy); cprintf(\"*\"); \/\/ └ \/\/Bottom left corner of box\r\n\t\tgotoxy(sx, sy); cprintf(\"*\"); \/\/ ┘ \/\/Bottom right corner of box\r\n\r\n\t\tfor (i = x + 1; i"} {"text":"\/\/ For conditions of distribution and use, see copyright notice in license.txt\n\n#include \"StableHeaders.h\"\n#include \"QtHttpAssetProvider.h\"\n#include \"ConfigurationManager.h\"\n#include \"EventManager.h\"\n#include \"AssetModule.h\"\n\n#include \"RexAsset.h\"\n#include \"AssetMetadataInterface.h\"\n#include \"AssetServiceInterface.h\"\n#include \"AssetEvents.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n\n#define MAX_HTTP_CONNECTIONS 10000 \/\/ Basically means no limit to parallel connections\n\nnamespace Asset\n{\n QtHttpAssetProvider::QtHttpAssetProvider(Foundation::Framework *framework) :\n QObject(),\n framework_(framework),\n event_manager_(framework->GetEventManager().get()),\n name_(\"QtHttpAssetProvider\"),\n network_manager_(new QNetworkAccessManager()),\n filling_stack_(false),\n get_texture_cap_(QUrl())\n {\n\t\tasset_timeout_ = framework_->GetDefaultConfig().DeclareSetting(\"AssetSystem\", \"http_timeout\", 120.0);\n if (event_manager_)\n asset_event_category_ = event_manager_->QueryEventCategory(\"Asset\");\n if (!asset_event_category_)\n AssetModule::LogWarning(\"QtHttpAssetProvider >> Could not get event category for Asset events\");\n\n connect(network_manager_, SIGNAL(finished(QNetworkReply*)), SLOT(TranferCompleted(QNetworkReply*)));\n\n AssetModule::LogWarning(QString(\"QtHttpAssetProvider >> Initialized with max %1 parallel HTTP connections\").arg(QString::number(MAX_HTTP_CONNECTIONS)).toStdString());\n }\n\n QtHttpAssetProvider::~QtHttpAssetProvider()\n {\n SAFE_DELETE(network_manager_);\n }\n\n void QtHttpAssetProvider::SetGetTextureCap(std::string url)\n {\n get_texture_cap_ = QUrl(QString::fromStdString(url));\n }\n\n \/\/ Interface implementation\n\n void QtHttpAssetProvider::Update(f64 frametime)\n {\n StartTransferFromQueue();\n }\n\n const std::string& QtHttpAssetProvider::Name()\n {\n return name_;\n }\n\n bool QtHttpAssetProvider::IsValidId(const std::string& asset_id, const std::string& asset_type)\n {\n \/\/ Textures over http with the GetTexture cap\n if (IsAcceptableAssetType(asset_type))\n if (RexUUID::IsValid(asset_id) && get_texture_cap_.isValid())\n return true;\n\n QString id(asset_id.c_str());\n if (!id.startsWith(\"http:\/\/\"))\n return false;\n\n QUrl asset_url(id);\n if (asset_url.isValid())\n return true;\n else\n return false;\n }\n \n bool QtHttpAssetProvider::RequestAsset(const std::string& asset_id, const std::string& asset_type, request_tag_t tag)\n {\n if (!IsValidId(asset_id, asset_type))\n return false;\n\n QString asset_id_qstring = QString::fromStdString(asset_id);\n if (assetid_to_transfer_map_.contains(asset_id_qstring))\n {\n assetid_to_transfer_map_[asset_id_qstring]->GetTranferInfo().AddTag(tag);\n }\n else\n {\n asset_type_t asset_type_int = RexTypes::GetAssetTypeFromTypeName(asset_type);\n QtHttpAssetTransfer *transfer = 0;\n \n if (IsAcceptableAssetType(asset_type))\n {\n \/\/ Http texture via cap url\n QString texture_url_string = get_texture_cap_.toString() + \"?texture_id=\" + asset_id_qstring;\n QUrl texture_url(texture_url_string);\n transfer = new QtHttpAssetTransfer(texture_url, asset_id_qstring, asset_type_int, tag);\n }\n else\n {\n \/\/ Normal http get\n QUrl asset_url = CreateUrl(asset_id_qstring);\n transfer = new QtHttpAssetTransfer(asset_url, asset_id_qstring, asset_type_int, tag);\n }\n\n if (!transfer)\n return false;\n\n transfer->setOriginatingObject(transfer);\n if (assetid_to_transfer_map_.count() <= MAX_HTTP_CONNECTIONS)\n {\n assetid_to_transfer_map_[asset_id_qstring] = transfer;\n network_manager_->get(*transfer);\n AssetModule::LogDebug(\"New HTTP asset request: \" + asset_id + \" type: \" + asset_type);\n }\n else\n pending_request_queue_.append(transfer);\n }\n return true;\n }\n\n bool QtHttpAssetProvider::InProgress(const std::string& asset_id)\n {\n QString qt_asset_id = QString::fromStdString(asset_id);\n if (assetid_to_transfer_map_.contains(qt_asset_id) || CheckRequestQueue(qt_asset_id))\n return true;\n else\n return false;\n }\n\n bool QtHttpAssetProvider::QueryAssetStatus(const std::string& asset_id, uint& size, uint& received, uint& received_continuous)\n {\n if (InProgress(asset_id))\n {\n \/\/ We dont know, QNetworkAccessManager handles these\n size = 0;\n received = 0;\n received_continuous = 0;\n return true;\n }\n else\n return false;\n }\n\n Foundation::AssetPtr QtHttpAssetProvider::GetIncompleteAsset(const std::string& asset_id, const std::string& asset_type, uint received) \n {\n return Foundation::AssetPtr();\n }\n\n Foundation::AssetTransferInfoVector QtHttpAssetProvider::GetTransferInfo()\n {\n Foundation::AssetTransferInfoVector info_vector;\n foreach (QtHttpAssetTransfer *transfer, assetid_to_transfer_map_.values())\n {\n HttpAssetTransferInfo iter_info = transfer->GetTranferInfo();\n \/\/ What we know\n Foundation::AssetTransferInfo info;\n info.id_ = iter_info.id.toStdString();\n info.type_ = RexTypes::GetAssetTypeString(iter_info.type);\n info.provider_ = Name();\n \/\/ The following we dont know, QNetworkAccessManager handles these\n info.size_ = 0;\n info.received_ = 0;\n info.received_continuous_ = 0;\n info_vector.push_back(info);\n }\n return info_vector;\n }\n\n \/\/ Private\n\n QUrl QtHttpAssetProvider::CreateUrl(QString assed_id)\n {\n if (!assed_id.startsWith(\"http:\/\/\") && !assed_id.startsWith(\"https:\/\/\"))\n assed_id = \"http:\/\/\" + assed_id;\n return QUrl(assed_id);\n }\n\n void QtHttpAssetProvider::TranferCompleted(QNetworkReply *reply)\n {\n fake_metadata_fetch_ = false;\n QtHttpAssetTransfer *transfer = dynamic_cast(reply->request().originatingObject());\n\n \/**** THIS IS A DATA REQUEST REPLY AND IT FAILED ****\/\n if (reply->error() != QNetworkReply::NoError && transfer)\n {\n \/\/ Send asset canceled events\n HttpAssetTransferInfo error_transfer_data = transfer->GetTranferInfo();\n Events::AssetCanceled *data = new Events::AssetCanceled(error_transfer_data.id.toStdString(), RexTypes::GetAssetTypeString(error_transfer_data.type));\n Foundation::EventDataPtr data_ptr(data);\n event_manager_->SendDelayedEvent(asset_event_category_, Events::ASSET_CANCELED, data_ptr, 0);\n\n \/\/ Clean up\n RemoveFinishedTransfers(error_transfer_data.id, reply->url());\n StartTransferFromQueue();\n\n AssetModule::LogDebug(\"HTTP asset \" + error_transfer_data.id.toStdString() + \" canceled\");\n reply->deleteLater();\n return;\n }\n\n \/**** THIS IS A \/data REQUEST REPLY ****\/\n if (transfer)\n {\n \/\/ Create asset pointer\n HttpAssetTransferInfo tranfer_info = transfer->GetTranferInfo();\n std::string id = tranfer_info.id.toStdString();\n std::string type = RexTypes::GetTypeNameFromAssetType(tranfer_info.type);\n Foundation::AssetPtr asset_ptr = Foundation::AssetPtr(new RexAsset(id, type));\n\n \/\/ Fill asset data with reply data\n RexAsset::AssetDataVector& data_vector = checked_static_cast(asset_ptr.get())->GetDataInternal();\n QByteArray data_array = reply->readAll();\n for (int index = 0; index < data_array.count(); ++index)\n data_vector.push_back(data_array.at(index));\n\n \/\/ Get metadata if available\n QString url_path = tranfer_info.url.path();\n if (url_path.endsWith(\"\/data\") || url_path.endsWith(\"\/data\/\"))\n {\n \/\/ Generate metada url\n int clip_count;\n if (url_path.endsWith(\"\/data\"))\n clip_count = 5;\n else if (url_path.endsWith(\"\/data\/\"))\n clip_count = 6;\n else\n {\n reply->deleteLater();\n return;\n }\n\n QUrl metadata_url = tranfer_info.url;\n url_path = url_path.left(url_path.count()-clip_count);\n url_path = url_path + \"\/metadata\";\n metadata_url.setPath(url_path);\n tranfer_info.url = metadata_url;\n\n QNetworkRequest *metada_request = new QNetworkRequest(metadata_url);\n\n \/\/ Store tranfer data and asset data pointer internally\n QPair data_pair;\n data_pair.first = tranfer_info;\n data_pair.second = asset_ptr;\n metadata_to_assetptr_[metada_request->url()] = data_pair;\n \n \/\/ Send metadata network request\n \/\/network_manager_->get(*metada_request);\n \n \/\/ HACK to avoid metadata fetch for now\n fake_metadata_url_ = metada_request->url();\n fake_metadata_fetch_ = true;\n }\n \/\/ Asset data feched, lets store\n else\n {\n \/\/ Store asset\n boost::shared_ptr asset_service = framework_->GetServiceManager()->GetService(Foundation::Service::ST_Asset).lock();\n if (asset_service)\n asset_service->StoreAsset(asset_ptr);\n\n \/\/ Send asset ready events\n foreach (request_tag_t tag, tranfer_info.tags)\n {\n Events::AssetReady event_data(asset_ptr.get()->GetId(), asset_ptr.get()->GetType(), asset_ptr, tag);\n event_manager_->SendEvent(asset_event_category_, Events::ASSET_READY, &event_data);\n }\n\n RemoveFinishedTransfers(tranfer_info.id, QUrl());\n StartTransferFromQueue();\n AssetModule::LogDebug(\"HTTP asset \" + tranfer_info.id.toStdString() + \" completed\");\n }\n }\n\n \/\/ Complete \/data and \/metadata sequence, fake is here as long as we dont have xml parser for metadata\n \/\/ or actually we dont use metadata in naali so thats the main reason its not fetched\n if (fake_metadata_fetch_)\n {\n \/**** THIS IS A \/metadata REQUEST REPLY ****\/\n if (metadata_to_assetptr_.contains(fake_metadata_url_))\n {\n \/\/ Pull out transfer data and asset pointer assosiated with this reply url\n QUrl metadata_transfer_url = fake_metadata_url_;\n HttpAssetTransferInfo transfer_data = metadata_to_assetptr_[metadata_transfer_url].first;\n Foundation::AssetPtr ready_asset_ptr = metadata_to_assetptr_[metadata_transfer_url].second;\n if (!ready_asset_ptr)\n {\n reply->deleteLater();\n return;\n }\n\n \/\/ Fill metadata\n \/*\n const QByteArray &inbound_metadata = reply->readAll();\n QString decoded_metadata = QString::fromUtf8(inbound_metadata.data());\n #if defined(__GNUC__)\n RexAssetMetadata *m = dynamic_cast(ready_asset_ptr.get()->GetMetadata());\n #else\t \n Foundation::AssetMetadataInterface *metadata = ready_asset_ptr.get()->GetMetadata();\n RexAssetMetadata *m = static_cast(metadata);\n #endif\n std::string std_md(decoded_metadata.toStdString());\n \n m->DesesrializeFromJSON(std_md); \/\/ TODO: implement a xml based metadata parser.\n *\/\n\n \/\/ Store asset\n boost::shared_ptr asset_service = framework_->GetServiceManager()->GetService(Foundation::Service::ST_Asset).lock();\n if (asset_service)\n asset_service->StoreAsset(ready_asset_ptr);\n\n \/\/ Send asset ready events\n foreach (request_tag_t tag, transfer_data.tags)\n {\n Events::AssetReady event_data(ready_asset_ptr.get()->GetId(), ready_asset_ptr.get()->GetType(), ready_asset_ptr, tag);\n event_manager_->SendEvent(asset_event_category_, Events::ASSET_READY, &event_data);\n }\n\n RemoveFinishedTransfers(transfer_data.id, metadata_transfer_url);\n StartTransferFromQueue();\n AssetModule::LogDebug(\"HTTP asset \" + transfer_data.id.toStdString() + \" completed with metadata\");\n }\n }\n reply->deleteLater();\n }\n\n void QtHttpAssetProvider::RemoveFinishedTransfers(QString asset_transfer_key, QUrl metadata_transfer_key)\n {\n QtHttpAssetTransfer *remove_transfer = assetid_to_transfer_map_[asset_transfer_key];\n assetid_to_transfer_map_.remove(asset_transfer_key);\n if (metadata_transfer_key.isValid())\n metadata_to_assetptr_.remove(metadata_transfer_key);\n SAFE_DELETE(remove_transfer);\n }\n\n void QtHttpAssetProvider::ClearAllTransfers()\n {\n foreach (QtHttpAssetTransfer *transfer, assetid_to_transfer_map_.values())\n SAFE_DELETE(transfer);\n assetid_to_transfer_map_.clear();\n\n foreach (QtHttpAssetTransfer *transfer, pending_request_queue_)\n SAFE_DELETE(transfer);\n pending_request_queue_.clear();\n }\n\n void QtHttpAssetProvider::StartTransferFromQueue()\n {\n if (pending_request_queue_.count() == 0)\n return;\n\n \/\/ If the whole map is empty then go and start new MAX_HTTP_CONNECTIONS amount of http gets\n if (assetid_to_transfer_map_.count() == 0)\n filling_stack_ = true;\n\n if (!filling_stack_)\n return;\n\n if (assetid_to_transfer_map_.count() <= MAX_HTTP_CONNECTIONS && pending_request_queue_.count() > 0)\n {\n if (assetid_to_transfer_map_.count() == MAX_HTTP_CONNECTIONS || pending_request_queue_.count() == 0)\n filling_stack_ = false; \n else\n {\n QtHttpAssetTransfer *new_transfer = pending_request_queue_.takeAt(0);\n assetid_to_transfer_map_[new_transfer->GetTranferInfo().id] = new_transfer;\n network_manager_->get(*new_transfer);\n\n AssetModule::LogDebug(\"New HTTP asset request from queue: \" + new_transfer->GetTranferInfo().id.toStdString() + \" type: \" + RexTypes::GetAssetTypeString(new_transfer->GetTranferInfo().type));\n StartTransferFromQueue(); \/\/ Recursivly fill the transfer map\n }\n }\n }\n\n bool QtHttpAssetProvider::CheckRequestQueue(QString assed_id)\n {\n foreach (QtHttpAssetTransfer *transfer, pending_request_queue_)\n if (transfer->GetTranferInfo().id == assed_id)\n return true;\n return false;\n }\n\n bool QtHttpAssetProvider::IsAcceptableAssetType(const std::string& asset_type)\n {\n using namespace RexTypes;\n \n bool accepted = false;\n switch (GetAssetTypeFromTypeName(asset_type))\n {\n case RexAT_Texture:\n case RexAT_Mesh:\n accepted = true;\n break;\n default:\n accepted = false;\n break;\n }\n return accepted;\n }\n}Bug fix to handle urls properly if caps url not set (modrex addurls etc). Printing a info line to console if server has http assets enabled.\/\/ For conditions of distribution and use, see copyright notice in license.txt\n\n#include \"StableHeaders.h\"\n#include \"QtHttpAssetProvider.h\"\n#include \"ConfigurationManager.h\"\n#include \"EventManager.h\"\n#include \"AssetModule.h\"\n\n#include \"RexAsset.h\"\n#include \"AssetMetadataInterface.h\"\n#include \"AssetServiceInterface.h\"\n#include \"AssetEvents.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n\n#define MAX_HTTP_CONNECTIONS 10000 \/\/ Basically means no limit to parallel connections\n\nnamespace Asset\n{\n QtHttpAssetProvider::QtHttpAssetProvider(Foundation::Framework *framework) :\n QObject(),\n framework_(framework),\n event_manager_(framework->GetEventManager().get()),\n name_(\"QtHttpAssetProvider\"),\n network_manager_(new QNetworkAccessManager()),\n filling_stack_(false),\n get_texture_cap_(QUrl())\n {\n\t\tasset_timeout_ = framework_->GetDefaultConfig().DeclareSetting(\"AssetSystem\", \"http_timeout\", 120.0);\n if (event_manager_)\n asset_event_category_ = event_manager_->QueryEventCategory(\"Asset\");\n if (!asset_event_category_)\n AssetModule::LogWarning(\"QtHttpAssetProvider >> Could not get event category for Asset events\");\n\n connect(network_manager_, SIGNAL(finished(QNetworkReply*)), SLOT(TranferCompleted(QNetworkReply*)));\n\n AssetModule::LogWarning(QString(\"QtHttpAssetProvider >> Initialized with max %1 parallel HTTP connections\").arg(QString::number(MAX_HTTP_CONNECTIONS)).toStdString());\n }\n\n QtHttpAssetProvider::~QtHttpAssetProvider()\n {\n SAFE_DELETE(network_manager_);\n }\n\n void QtHttpAssetProvider::SetGetTextureCap(std::string url)\n {\n get_texture_cap_ = QUrl(QString::fromStdString(url));\n if (get_texture_cap_.isValid())\n AssetModule::LogInfo(\"Server supports HTTP assets: using HTTP to fetch textures and meshes.\");\n }\n\n \/\/ Interface implementation\n\n void QtHttpAssetProvider::Update(f64 frametime)\n {\n StartTransferFromQueue();\n }\n\n const std::string& QtHttpAssetProvider::Name()\n {\n return name_;\n }\n\n bool QtHttpAssetProvider::IsValidId(const std::string& asset_id, const std::string& asset_type)\n {\n \/\/ Textures over http with the GetTexture cap\n if (IsAcceptableAssetType(asset_type))\n if (RexUUID::IsValid(asset_id) && get_texture_cap_.isValid())\n return true;\n\n QString id(asset_id.c_str());\n if (!id.startsWith(\"http:\/\/\"))\n return false;\n\n QUrl asset_url(id);\n if (asset_url.isValid())\n return true;\n else\n return false;\n }\n \n bool QtHttpAssetProvider::RequestAsset(const std::string& asset_id, const std::string& asset_type, request_tag_t tag)\n {\n if (!IsValidId(asset_id, asset_type))\n return false;\n\n QString asset_id_qstring = QString::fromStdString(asset_id);\n if (assetid_to_transfer_map_.contains(asset_id_qstring))\n {\n assetid_to_transfer_map_[asset_id_qstring]->GetTranferInfo().AddTag(tag);\n }\n else\n {\n asset_type_t asset_type_int = RexTypes::GetAssetTypeFromTypeName(asset_type);\n QtHttpAssetTransfer *transfer = 0;\n \n if (IsAcceptableAssetType(asset_type) && RexUUID::IsValid(asset_id) && get_texture_cap_.isValid())\n {\n \/\/ Http texture\/meshes via cap url\n QString texture_url_string = get_texture_cap_.toString() + \"?texture_id=\" + asset_id_qstring;\n QUrl texture_url(texture_url_string);\n transfer = new QtHttpAssetTransfer(texture_url, asset_id_qstring, asset_type_int, tag);\n }\n else\n {\n \/\/ Normal http get\n QUrl asset_url = CreateUrl(asset_id_qstring);\n transfer = new QtHttpAssetTransfer(asset_url, asset_id_qstring, asset_type_int, tag);\n }\n\n if (!transfer)\n return false;\n\n transfer->setOriginatingObject(transfer);\n if (assetid_to_transfer_map_.count() <= MAX_HTTP_CONNECTIONS)\n {\n assetid_to_transfer_map_[asset_id_qstring] = transfer;\n network_manager_->get(*transfer);\n AssetModule::LogDebug(\"New HTTP asset request: \" + asset_id + \" type: \" + asset_type);\n }\n else\n pending_request_queue_.append(transfer);\n }\n return true;\n }\n\n bool QtHttpAssetProvider::InProgress(const std::string& asset_id)\n {\n QString qt_asset_id = QString::fromStdString(asset_id);\n if (assetid_to_transfer_map_.contains(qt_asset_id) || CheckRequestQueue(qt_asset_id))\n return true;\n else\n return false;\n }\n\n bool QtHttpAssetProvider::QueryAssetStatus(const std::string& asset_id, uint& size, uint& received, uint& received_continuous)\n {\n if (InProgress(asset_id))\n {\n \/\/ We dont know, QNetworkAccessManager handles these\n size = 0;\n received = 0;\n received_continuous = 0;\n return true;\n }\n else\n return false;\n }\n\n Foundation::AssetPtr QtHttpAssetProvider::GetIncompleteAsset(const std::string& asset_id, const std::string& asset_type, uint received) \n {\n return Foundation::AssetPtr();\n }\n\n Foundation::AssetTransferInfoVector QtHttpAssetProvider::GetTransferInfo()\n {\n Foundation::AssetTransferInfoVector info_vector;\n foreach (QtHttpAssetTransfer *transfer, assetid_to_transfer_map_.values())\n {\n HttpAssetTransferInfo iter_info = transfer->GetTranferInfo();\n \/\/ What we know\n Foundation::AssetTransferInfo info;\n info.id_ = iter_info.id.toStdString();\n info.type_ = RexTypes::GetAssetTypeString(iter_info.type);\n info.provider_ = Name();\n \/\/ The following we dont know, QNetworkAccessManager handles these\n info.size_ = 0;\n info.received_ = 0;\n info.received_continuous_ = 0;\n info_vector.push_back(info);\n }\n return info_vector;\n }\n\n \/\/ Private\n\n QUrl QtHttpAssetProvider::CreateUrl(QString assed_id)\n {\n if (!assed_id.startsWith(\"http:\/\/\") && !assed_id.startsWith(\"https:\/\/\"))\n assed_id = \"http:\/\/\" + assed_id;\n return QUrl(assed_id);\n }\n\n void QtHttpAssetProvider::TranferCompleted(QNetworkReply *reply)\n {\n fake_metadata_fetch_ = false;\n QtHttpAssetTransfer *transfer = dynamic_cast(reply->request().originatingObject());\n\n \/**** THIS IS A DATA REQUEST REPLY AND IT FAILED ****\/\n if (reply->error() != QNetworkReply::NoError && transfer)\n {\n \/\/ Send asset canceled events\n HttpAssetTransferInfo error_transfer_data = transfer->GetTranferInfo();\n Events::AssetCanceled *data = new Events::AssetCanceled(error_transfer_data.id.toStdString(), RexTypes::GetAssetTypeString(error_transfer_data.type));\n Foundation::EventDataPtr data_ptr(data);\n event_manager_->SendDelayedEvent(asset_event_category_, Events::ASSET_CANCELED, data_ptr, 0);\n\n \/\/ Clean up\n RemoveFinishedTransfers(error_transfer_data.id, reply->url());\n StartTransferFromQueue();\n\n AssetModule::LogDebug(\"HTTP asset \" + error_transfer_data.id.toStdString() + \" canceled\");\n reply->deleteLater();\n return;\n }\n\n \/**** THIS IS A \/data REQUEST REPLY ****\/\n if (transfer)\n {\n \/\/ Create asset pointer\n HttpAssetTransferInfo tranfer_info = transfer->GetTranferInfo();\n std::string id = tranfer_info.id.toStdString();\n std::string type = RexTypes::GetTypeNameFromAssetType(tranfer_info.type);\n Foundation::AssetPtr asset_ptr = Foundation::AssetPtr(new RexAsset(id, type));\n\n \/\/ Fill asset data with reply data\n RexAsset::AssetDataVector& data_vector = checked_static_cast(asset_ptr.get())->GetDataInternal();\n QByteArray data_array = reply->readAll();\n for (int index = 0; index < data_array.count(); ++index)\n data_vector.push_back(data_array.at(index));\n\n \/\/ Get metadata if available\n QString url_path = tranfer_info.url.path();\n if (url_path.endsWith(\"\/data\") || url_path.endsWith(\"\/data\/\"))\n {\n \/\/ Generate metada url\n int clip_count;\n if (url_path.endsWith(\"\/data\"))\n clip_count = 5;\n else if (url_path.endsWith(\"\/data\/\"))\n clip_count = 6;\n else\n {\n reply->deleteLater();\n return;\n }\n\n QUrl metadata_url = tranfer_info.url;\n url_path = url_path.left(url_path.count()-clip_count);\n url_path = url_path + \"\/metadata\";\n metadata_url.setPath(url_path);\n tranfer_info.url = metadata_url;\n\n QNetworkRequest *metada_request = new QNetworkRequest(metadata_url);\n\n \/\/ Store tranfer data and asset data pointer internally\n QPair data_pair;\n data_pair.first = tranfer_info;\n data_pair.second = asset_ptr;\n metadata_to_assetptr_[metada_request->url()] = data_pair;\n \n \/\/ Send metadata network request\n \/\/network_manager_->get(*metada_request);\n \n \/\/ HACK to avoid metadata fetch for now\n fake_metadata_url_ = metada_request->url();\n fake_metadata_fetch_ = true;\n }\n \/\/ Asset data feched, lets store\n else\n {\n \/\/ Store asset\n boost::shared_ptr asset_service = framework_->GetServiceManager()->GetService(Foundation::Service::ST_Asset).lock();\n if (asset_service)\n asset_service->StoreAsset(asset_ptr);\n\n \/\/ Send asset ready events\n foreach (request_tag_t tag, tranfer_info.tags)\n {\n Events::AssetReady event_data(asset_ptr.get()->GetId(), asset_ptr.get()->GetType(), asset_ptr, tag);\n event_manager_->SendEvent(asset_event_category_, Events::ASSET_READY, &event_data);\n }\n\n RemoveFinishedTransfers(tranfer_info.id, QUrl());\n StartTransferFromQueue();\n AssetModule::LogDebug(\"HTTP asset \" + tranfer_info.id.toStdString() + \" completed\");\n }\n }\n\n \/\/ Complete \/data and \/metadata sequence, fake is here as long as we dont have xml parser for metadata\n \/\/ or actually we dont use metadata in naali so thats the main reason its not fetched\n if (fake_metadata_fetch_)\n {\n \/**** THIS IS A \/metadata REQUEST REPLY ****\/\n if (metadata_to_assetptr_.contains(fake_metadata_url_))\n {\n \/\/ Pull out transfer data and asset pointer assosiated with this reply url\n QUrl metadata_transfer_url = fake_metadata_url_;\n HttpAssetTransferInfo transfer_data = metadata_to_assetptr_[metadata_transfer_url].first;\n Foundation::AssetPtr ready_asset_ptr = metadata_to_assetptr_[metadata_transfer_url].second;\n if (!ready_asset_ptr)\n {\n reply->deleteLater();\n return;\n }\n\n \/\/ Fill metadata\n \/*\n const QByteArray &inbound_metadata = reply->readAll();\n QString decoded_metadata = QString::fromUtf8(inbound_metadata.data());\n #if defined(__GNUC__)\n RexAssetMetadata *m = dynamic_cast(ready_asset_ptr.get()->GetMetadata());\n #else\t \n Foundation::AssetMetadataInterface *metadata = ready_asset_ptr.get()->GetMetadata();\n RexAssetMetadata *m = static_cast(metadata);\n #endif\n std::string std_md(decoded_metadata.toStdString());\n \n m->DesesrializeFromJSON(std_md); \/\/ TODO: implement a xml based metadata parser.\n *\/\n\n \/\/ Store asset\n boost::shared_ptr asset_service = framework_->GetServiceManager()->GetService(Foundation::Service::ST_Asset).lock();\n if (asset_service)\n asset_service->StoreAsset(ready_asset_ptr);\n\n \/\/ Send asset ready events\n foreach (request_tag_t tag, transfer_data.tags)\n {\n Events::AssetReady event_data(ready_asset_ptr.get()->GetId(), ready_asset_ptr.get()->GetType(), ready_asset_ptr, tag);\n event_manager_->SendEvent(asset_event_category_, Events::ASSET_READY, &event_data);\n }\n\n RemoveFinishedTransfers(transfer_data.id, metadata_transfer_url);\n StartTransferFromQueue();\n AssetModule::LogDebug(\"HTTP asset \" + transfer_data.id.toStdString() + \" completed with metadata\");\n }\n }\n reply->deleteLater();\n }\n\n void QtHttpAssetProvider::RemoveFinishedTransfers(QString asset_transfer_key, QUrl metadata_transfer_key)\n {\n QtHttpAssetTransfer *remove_transfer = assetid_to_transfer_map_[asset_transfer_key];\n assetid_to_transfer_map_.remove(asset_transfer_key);\n if (metadata_transfer_key.isValid())\n metadata_to_assetptr_.remove(metadata_transfer_key);\n SAFE_DELETE(remove_transfer);\n }\n\n void QtHttpAssetProvider::ClearAllTransfers()\n {\n foreach (QtHttpAssetTransfer *transfer, assetid_to_transfer_map_.values())\n SAFE_DELETE(transfer);\n assetid_to_transfer_map_.clear();\n\n foreach (QtHttpAssetTransfer *transfer, pending_request_queue_)\n SAFE_DELETE(transfer);\n pending_request_queue_.clear();\n }\n\n void QtHttpAssetProvider::StartTransferFromQueue()\n {\n if (pending_request_queue_.count() == 0)\n return;\n\n \/\/ If the whole map is empty then go and start new MAX_HTTP_CONNECTIONS amount of http gets\n if (assetid_to_transfer_map_.count() == 0)\n filling_stack_ = true;\n\n if (!filling_stack_)\n return;\n\n if (assetid_to_transfer_map_.count() <= MAX_HTTP_CONNECTIONS && pending_request_queue_.count() > 0)\n {\n if (assetid_to_transfer_map_.count() == MAX_HTTP_CONNECTIONS || pending_request_queue_.count() == 0)\n filling_stack_ = false; \n else\n {\n QtHttpAssetTransfer *new_transfer = pending_request_queue_.takeAt(0);\n assetid_to_transfer_map_[new_transfer->GetTranferInfo().id] = new_transfer;\n network_manager_->get(*new_transfer);\n\n AssetModule::LogDebug(\"New HTTP asset request from queue: \" + new_transfer->GetTranferInfo().id.toStdString() + \" type: \" + RexTypes::GetAssetTypeString(new_transfer->GetTranferInfo().type));\n StartTransferFromQueue(); \/\/ Recursivly fill the transfer map\n }\n }\n }\n\n bool QtHttpAssetProvider::CheckRequestQueue(QString assed_id)\n {\n foreach (QtHttpAssetTransfer *transfer, pending_request_queue_)\n if (transfer->GetTranferInfo().id == assed_id)\n return true;\n return false;\n }\n\n bool QtHttpAssetProvider::IsAcceptableAssetType(const std::string& asset_type)\n {\n using namespace RexTypes;\n \n bool accepted = false;\n switch (GetAssetTypeFromTypeName(asset_type))\n {\n case RexAT_Texture:\n case RexAT_Mesh:\n accepted = true;\n break;\n default:\n accepted = false;\n break;\n }\n return accepted;\n }\n}<|endoftext|>"} {"text":"\/*\n * IcarusFitnessCalculator.cpp\n *\n * Created on: 26\/03\/2015\n * Author: Vitor\n *\/\n\n#include \"IcarusFitnessCalculator.h\"\n\ndouble IcarusFitnessCalculator::fitness() {\n\tgerar_arquivo_top();\n\tif (system(\"iverilog top.v genetico.v -o individuo\") == -1) {\n\t\tstd::cerr << \"Erro na chamada iverilog.\\n\";\n\t\texit(1);\n\t}\n\tFILE* simulador = popen(\"vvp individuo\", \"r\");\n\tif (simulador == nullptr) {\n\t\tstd::cerr << \"Nao consegui executar o simulador vvp.\\n\";\n\t\tstd::exit(1);\n\t}\n\n\tauto parsed_output = parse_output(simulador);\n\n\tpclose(simulador);\n\n\treturn fitness_calculator(parsed_output);\n}\n\nvoid IcarusFitnessCalculator::gerar_arquivo_top() {\n\tstd::ofstream top;\n\ttop.open(\"top.v\");\n\n\ttop << \"module top();\\n\\n\";\n\ttop << \"\\tinteger i;\\n\";\n\ttop << \"\\treg [\" << num_inputs - 1 << \":0] in;\\n\";\n\ttop << \"\\twire [\" << num_outputs - 1 << \":0] out;\\n\\n\";\n\ttop << \"initial begin\\n\";\n\ttop << \"\\t$monitor(\\\"\";\n\tfor (int i = 0; i < num_inputs; i++) {\n\t\ttop << \"%b\";\n\t}\n\ttop << \" \";\n\tfor (int i = 0; i < num_outputs; i++) {\n\t\ttop << \"%b\";\n\t}\n\ttop << \"\\\", \";\n\tfor (int i = num_inputs - 1; i >= 0; i--) {\n\t\ttop << \"in[\" << i << \"], \";\n\t}\n\tfor (int i = num_outputs - 1; i >= 1; i--) {\n\t\ttop << \"out[\" << i << \"], \";\n\t}\n\ttop << \"out);\\n\";\n\ttop << \"\\tfor (i = 0; i < \" << (int) pow(2, num_inputs)\n\t\t\t<< \"; i = i + 1) begin\\n\";\n\ttop << \"\\t\\t#5 in = i;\\n\";\n\ttop << \"\\tend\\n\";\n\ttop << \"end\\n\\n\";\n\ttop << \"genetico genetico(\\n\";\n\ttop << \"\\t.in(in),\\n\";\n\ttop << \"\\t.out(out)\\n\";\n\ttop << \");\\n\\n\";\n\ttop << \"endmodule\";\n}\n\nstd::vector>>\n\tIcarusFitnessCalculator::parse_output(FILE* simulador) {\n\tstd::vector>> results;\n\tchar entrada[100];\n\tchar saida[100];\n\n\t\/\/ Ignorando os x's\n\tfscanf(simulador, \"%s\", entrada);\n\tfscanf(simulador, \"%s\", saida);\n\n\tfor (int i = 0; i < (int) pow(2, num_inputs); i++) {\n\t\tfscanf(simulador, \"%s\", entrada);\n\t\tfscanf(simulador, \"%s\", saida);\n\t\tresults.push_back(std::vector>());\n\t\tresults[i].push_back(std::bitset<8>(saida));\n\t}\n\treturn results;\n}\nAdicionado logic_e.v na linha de compilacao do individuo.\/*\n * IcarusFitnessCalculator.cpp\n *\n * Created on: 26\/03\/2015\n * Author: Vitor\n *\/\n\n#include \"IcarusFitnessCalculator.h\"\n\ndouble IcarusFitnessCalculator::fitness() {\n\tgerar_arquivo_top();\n\tif (system(\"iverilog top.v genetico.v logic_e.v -o individuo\") == -1) {\n\t\tstd::cerr << \"Erro na chamada iverilog.\\n\";\n\t\texit(1);\n\t}\n\tFILE* simulador = popen(\"vvp individuo\", \"r\");\n\tif (simulador == nullptr) {\n\t\tstd::cerr << \"Nao consegui executar o simulador vvp.\\n\";\n\t\tstd::exit(1);\n\t}\n\n\tauto parsed_output = parse_output(simulador);\n\n\tpclose(simulador);\n\n\treturn fitness_calculator(parsed_output);\n}\n\nvoid IcarusFitnessCalculator::gerar_arquivo_top() {\n\tstd::ofstream top;\n\ttop.open(\"top.v\");\n\n\ttop << \"module top();\\n\\n\";\n\ttop << \"\\tinteger i;\\n\";\n\ttop << \"\\treg [\" << num_inputs - 1 << \":0] in;\\n\";\n\ttop << \"\\twire [\" << num_outputs - 1 << \":0] out;\\n\\n\";\n\ttop << \"initial begin\\n\";\n\ttop << \"\\t$monitor(\\\"\";\n\tfor (int i = 0; i < num_inputs; i++) {\n\t\ttop << \"%b\";\n\t}\n\ttop << \" \";\n\tfor (int i = 0; i < num_outputs; i++) {\n\t\ttop << \"%b\";\n\t}\n\ttop << \"\\\", \";\n\tfor (int i = num_inputs - 1; i >= 0; i--) {\n\t\ttop << \"in[\" << i << \"], \";\n\t}\n\tfor (int i = num_outputs - 1; i >= 1; i--) {\n\t\ttop << \"out[\" << i << \"], \";\n\t}\n\ttop << \"out);\\n\";\n\ttop << \"\\tfor (i = 0; i < \" << (int) pow(2, num_inputs)\n\t\t\t<< \"; i = i + 1) begin\\n\";\n\ttop << \"\\t\\t#5 in = i;\\n\";\n\ttop << \"\\tend\\n\";\n\ttop << \"end\\n\\n\";\n\ttop << \"genetico genetico(\\n\";\n\ttop << \"\\t.in(in),\\n\";\n\ttop << \"\\t.out(out)\\n\";\n\ttop << \");\\n\\n\";\n\ttop << \"endmodule\";\n}\n\nstd::vector>>\n\tIcarusFitnessCalculator::parse_output(FILE* simulador) {\n\tstd::vector>> results;\n\tchar entrada[100];\n\tchar saida[100];\n\n\t\/\/ Ignorando os x's\n\tfscanf(simulador, \"%s\", entrada);\n\tfscanf(simulador, \"%s\", saida);\n\n\tfor (int i = 0; i < (int) pow(2, num_inputs); i++) {\n\t\tfscanf(simulador, \"%s\", entrada);\n\t\tfscanf(simulador, \"%s\", saida);\n\t\tresults.push_back(std::vector>());\n\t\tresults[i].push_back(std::bitset<8>(saida));\n\t}\n\treturn results;\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2007-2010, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n\n#include \"IECoreGL\/IECoreGL.h\"\n\n#include \"IECoreGL\/bindings\/RendererBinding.h\"\n#include \"IECoreGL\/bindings\/BindableBinding.h\"\n#include \"IECoreGL\/bindings\/ShaderBinding.h\"\n#include \"IECoreGL\/bindings\/TextureBinding.h\"\n#include \"IECoreGL\/bindings\/WindowBinding.h\"\n#include \"IECoreGL\/bindings\/StateBinding.h\"\n#include \"IECoreGL\/bindings\/RenderableBinding.h\"\n#include \"IECoreGL\/bindings\/SceneBinding.h\"\n#include \"IECoreGL\/bindings\/SceneViewerBinding.h\"\n#include \"IECoreGL\/bindings\/ShaderManagerBinding.h\"\n#include \"IECoreGL\/bindings\/TextureLoaderBinding.h\"\n#include \"IECoreGL\/bindings\/GroupBinding.h\"\n#include \"IECoreGL\/bindings\/FrameBufferBinding.h\"\n#include \"IECoreGL\/bindings\/ColorTextureBinding.h\"\n#include \"IECoreGL\/bindings\/DepthTextureBinding.h\"\n#include \"IECoreGL\/bindings\/CameraBinding.h\"\n#include \"IECoreGL\/bindings\/OrthographicCameraBinding.h\"\n#include \"IECoreGL\/bindings\/PerspectiveCameraBinding.h\"\n#include \"IECoreGL\/bindings\/CameraControllerBinding.h\"\n#include \"IECoreGL\/bindings\/StateComponentBinding.h\"\n#include \"IECoreGL\/bindings\/TypedStateComponentBinding.h\"\n#include \"IECoreGL\/bindings\/NameStateComponentBinding.h\"\n#include \"IECoreGL\/bindings\/HitRecordBinding.h\"\n#include \"IECoreGL\/bindings\/ToGLConverterBinding.h\"\n#include \"IECoreGL\/bindings\/ToGLCameraConverterBinding.h\"\n#include \"IECoreGL\/bindings\/AlphaTextureBinding.h\"\n#include \"IECoreGL\/bindings\/LuminanceTextureBinding.h\"\n#include \"IECoreGL\/bindings\/ToGLTextureConverterBinding.h\"\n#include \"IECoreGL\/bindings\/PrimitiveBinding.h\"\n#include \"IECoreGL\/bindings\/PointsPrimitiveBinding.h\"\n\n\nusing namespace IECoreGL;\nusing namespace boost::python;\n\nBOOST_PYTHON_MODULE( _IECoreGL )\n{\n\tbindRenderer();\n\tbindBindable();\n\tbindShader();\n\tbindTexture();\n\tbindWindow();\n\tbindState();\n\tbindRenderable();\n\tbindScene();\n\tbindSceneViewer();\n\tbindShaderManager();\n\tbindTextureLoader();\n\tbindGroup();\n\tbindFrameBuffer();\n\tbindColorTexture();\n\tbindDepthTexture();\n\tbindCamera();\n\tbindOrthographicCamera();\n\tbindPerspectiveCamera();\n\tbindCameraController();\n\tbindStateComponent();\n\tbindTypedStateComponents();\n\tbindNameStateComponent();\n\tbindHitRecord();\n\tbindToGLConverter();\n\tbindToGLCameraConverter();\n\tbindAlphaTexture();\n\tbindLuminanceTexture();\n\tbindToGLTextureConverter();\n\tbindPrimitive();\n\tbindPointsPrimitive();\n\n\tdef( \"init\", &IECoreGL::init );\n}\nAdding missing changes which should have been in revision 4552.\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2007-2012, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n\n#include \"IECoreGL\/IECoreGL.h\"\n\n#include \"IECoreGL\/bindings\/RendererBinding.h\"\n#include \"IECoreGL\/bindings\/BindableBinding.h\"\n#include \"IECoreGL\/bindings\/ShaderBinding.h\"\n#include \"IECoreGL\/bindings\/TextureBinding.h\"\n#include \"IECoreGL\/bindings\/WindowBinding.h\"\n#include \"IECoreGL\/bindings\/StateBinding.h\"\n#include \"IECoreGL\/bindings\/RenderableBinding.h\"\n#include \"IECoreGL\/bindings\/SceneBinding.h\"\n#include \"IECoreGL\/bindings\/SceneViewerBinding.h\"\n#include \"IECoreGL\/bindings\/ShaderManagerBinding.h\"\n#include \"IECoreGL\/bindings\/TextureLoaderBinding.h\"\n#include \"IECoreGL\/bindings\/GroupBinding.h\"\n#include \"IECoreGL\/bindings\/FrameBufferBinding.h\"\n#include \"IECoreGL\/bindings\/ColorTextureBinding.h\"\n#include \"IECoreGL\/bindings\/DepthTextureBinding.h\"\n#include \"IECoreGL\/bindings\/CameraBinding.h\"\n#include \"IECoreGL\/bindings\/OrthographicCameraBinding.h\"\n#include \"IECoreGL\/bindings\/PerspectiveCameraBinding.h\"\n#include \"IECoreGL\/bindings\/CameraControllerBinding.h\"\n#include \"IECoreGL\/bindings\/StateComponentBinding.h\"\n#include \"IECoreGL\/bindings\/TypedStateComponentBinding.h\"\n#include \"IECoreGL\/bindings\/NameStateComponentBinding.h\"\n#include \"IECoreGL\/bindings\/HitRecordBinding.h\"\n#include \"IECoreGL\/bindings\/ToGLConverterBinding.h\"\n#include \"IECoreGL\/bindings\/ToGLCameraConverterBinding.h\"\n#include \"IECoreGL\/bindings\/AlphaTextureBinding.h\"\n#include \"IECoreGL\/bindings\/LuminanceTextureBinding.h\"\n#include \"IECoreGL\/bindings\/ToGLTextureConverterBinding.h\"\n#include \"IECoreGL\/bindings\/PrimitiveBinding.h\"\n#include \"IECoreGL\/bindings\/PointsPrimitiveBinding.h\"\n#include \"IECoreGL\/bindings\/SelectorBinding.h\"\n\n\nusing namespace IECoreGL;\nusing namespace boost::python;\n\nBOOST_PYTHON_MODULE( _IECoreGL )\n{\n\tbindRenderer();\n\tbindBindable();\n\tbindShader();\n\tbindTexture();\n\tbindWindow();\n\tbindState();\n\tbindRenderable();\n\tbindScene();\n\tbindSceneViewer();\n\tbindShaderManager();\n\tbindTextureLoader();\n\tbindGroup();\n\tbindFrameBuffer();\n\tbindColorTexture();\n\tbindDepthTexture();\n\tbindCamera();\n\tbindOrthographicCamera();\n\tbindPerspectiveCamera();\n\tbindCameraController();\n\tbindStateComponent();\n\tbindTypedStateComponents();\n\tbindNameStateComponent();\n\tbindHitRecord();\n\tbindToGLConverter();\n\tbindToGLCameraConverter();\n\tbindAlphaTexture();\n\tbindLuminanceTexture();\n\tbindToGLTextureConverter();\n\tbindPrimitive();\n\tbindPointsPrimitive();\n\tbindSelector();\n\n\tdef( \"init\", &IECoreGL::init );\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n\nnamespace orm\n{\n Sqlite3Query::Sqlite3Query(Bdd* bdd,const std::string& query) : Query(bdd,query), statement(0)\n {\n int result = sqlite3_prepare_v2(static_cast(bdd)->dbConn,query.c_str(),query.size()+1, &statement, NULL);\n\n #if ORM_VERBOSITY & ORM_ERROR\n if (result != SQLITE_OK)\n {\n ORM_PRINT_ERROR(\"Sqlite3Query::Sqlite3Query(bdd,string&) Failed to make the statment\")\n \/\/\/ \\todo <(bdd)->dbConn,query.c_str(),query.size()+1, &statement, NULL);\n\n #if ORM_VERBOSITY & ORM_ERROR\n if (result != SQLITE_OK)\n {\n ORM_PRINT_ERROR(\"Sqlite3Query::Sqlite3Query(bdd,string&&) Failed to make the statment\")\n \/\/\/ \\todo <fix bug with sqlite string#include \n#include \n\n\nnamespace orm\n{\n Sqlite3Query::Sqlite3Query(Bdd* bdd,const std::string& query) : Query(bdd,query), statement(0)\n {\n int result = sqlite3_prepare_v2(static_cast(bdd)->dbConn,query.c_str(),query.size()+1, &statement, NULL);\n\n #if ORM_VERBOSITY & ORM_ERROR\n if (result != SQLITE_OK)\n {\n ORM_PRINT_ERROR(\"Sqlite3Query::Sqlite3Query(bdd,string&) Failed to make the statment\")\n \/\/\/ \\todo <(bdd)->dbConn,query.c_str(),query.size()+1, &statement, NULL);\n\n #if ORM_VERBOSITY & ORM_ERROR\n if (result != SQLITE_OK)\n {\n ORM_PRINT_ERROR(\"Sqlite3Query::Sqlite3Query(bdd,string&&) Failed to make the statment\")\n \/\/\/ \\todo <"} {"text":"#include \"BathRoomMirrorHeatingCtrl.h\"\r\n\r\n#include \r\n#include \r\n\r\n#include \"C:\/eclipseArduino\/sloeber\/arduinoPlugin\/packages\/arduino\/hardware\/avr\/1.6.18\/variants\/standard\/pins_arduino.h\"\r\n#include \"D:\/HomeAutomation\/ArduinoLibs\/DHT\/DHT.h\"\r\n#include \"D:\/HomeAutomation\/ArduinoLibs\/Timer\/Timer.h\"\r\n\r\nTimer resetAnalogPinTimer;\r\nTimer offTimer;\r\nTimer humiditySensorReadTimer;\r\nDHT dhtSensor(DHT_PIN, DHT22);\r\nvolatile DhtSensorData sensorData;\r\nvolatile boolean isHeatingAndLightDesired;\r\nvolatile int analogSensorReading;\r\n\r\nbool debug = true;\r\nbool ignoreHumiditySensor = true;\r\n\r\n\/\/The setup function is called once at startup of the sketch\r\nvoid setup() {\r\n\tSerial.begin(115200);\r\n\tSerial.println(\"Setup starts here...\");\r\n\r\n\tisHeatingAndLightDesired = false;\r\n\tsensorData.temperature = 25;\r\n\tsensorData.humidity = 55;\r\n\r\n\tpinMode(INPUT_PIN_IR_TRIGGER, INPUT);\r\n\tanalogReadInputPin();\r\n\tresetAnalogPinTimer.every(RESET_ANALOG_SENSOR_READING, resetReadingAndUpdateDecision);\r\n\r\n\tpinMode(LIGHTS_PIN, OUTPUT);\r\n\tsetRelay(LIGHTS_PIN, OFF);\r\n\r\n\tpinMode(HEAT_PIN, OUTPUT);\r\n\tsetRelay(HEAT_PIN, OFF);\r\n\r\n\tdhtSensor.begin();\r\n\treadDhtInfo();\r\n\thumiditySensorReadTimer.every(DHT_TIMER_EVERY, readDhtInfo);\r\n\tSerial.println(\"Setup ends here...\");\r\n}\r\n\r\n\/\/ The loop function is called in an endless loop\r\nvoid loop() {\r\n\toffTimer.update();\r\n\thumiditySensorReadTimer.update();\r\n\tresetAnalogPinTimer.update();\r\n\tdecisionMaker();\r\n\tanalogReadInputPin();\r\n}\r\n\r\nvoid resetReadingAndUpdateDecision() {\r\n\tif(analogSensorReading > ANALOG_TRESHOLD) {\r\n\t\tisHeatingAndLightDesired = !isHeatingAndLightDesired;\r\n\t}\r\n\tSerial.print(\"AnalogSensor last value:\");\r\n\tSerial.println(analogSensorReading);\r\n\tanalogSensorReading = 0;\r\n\tSerial.print(\"AnalogSensor new value:\");\r\n\tSerial.println(analogSensorReading);\r\n}\r\n\r\nvoid offTimerExpired() {\r\n\tisHeatingAndLightDesired = false;;\r\n}\r\n\r\nvoid reattachInterrupt() {\r\n\tif(debug) {\r\n\t\tSerial.println(\"ReattachInterrupt triggered\");\r\n\t}\r\n\tattachInterrupt(digitalPinToInterrupt(INPUT_PIN_IR_TRIGGER), userInputDetected, RISING);\r\n\tresetAnalogPinTimer.stop(millis());\r\n}\r\n\r\nvoid readDhtInfo() {\r\n\tfloat humidity = dhtSensor.readHumidity();\r\n\tfloat temperature = dhtSensor.readTemperature();\r\n\r\n\t\/\/ simple error check. Do not update data if sensor reading is wrong.\r\n\tif(humidity > 0 && temperature > -30) {\r\n\t\tsensorData.humidity = humidity;\r\n\t\tsensorData.temperature = temperature;\r\n\t\tignoreHumiditySensor = false;\r\n\t} else {\r\n\t\tignoreHumiditySensor = true;\r\n\t\tif(debug) {\r\n\t\t\tSerial.println(\"DHT wrong data received...\");\r\n\t\t\tSerial.print(\"Humidity:\"); Serial.println(humidity);\r\n\t\t\tSerial.print(\"Temperature:\"); Serial.println(temperature);\r\n\t\t}\r\n\t}\r\n\tif(debug) {\r\n\/\/\t\tsensorData.humidity = random(100);\r\n\/\/\t\tsensorData.temperature = random(30);\r\n\t\tSerial.print(\"Humidity:\");Serial.println(sensorData.humidity);\r\n\t\tSerial.print(\"Temperature:\");Serial.println(sensorData.temperature);\r\n\t\treturn;\r\n\t}\r\n}\r\n\r\nvoid decisionMaker() {\r\n\tif(isHeatingAndLightDesired) {\r\n\t\tif(!lightIsOn()) {\r\n\t\t\tsetRelay(LIGHTS_PIN, ON);\r\n\t\t}\r\n\t\tif((sensorData.humidity > HUMIDITY_TRESHOLD || ignoreHumiditySensor) && !heatingIsOn()) {\r\n\t\t\tsetRelay(HEAT_PIN, ON);\r\n\t\t}\r\n\t} else {\r\n\t\tif(lightIsOn()) {\r\n\t\t\tsetRelay(LIGHTS_PIN, OFF);\r\n\t\t}\r\n\t\tif(heatingIsOn()) {\r\n\t\t\tsetRelay(HEAT_PIN, OFF);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid setRelay(byte pin, byte state) {\r\n\tdigitalWrite(pin, state);\r\n\tif (debug) {\r\n\t\tSerial.print(\"Pin \");Serial.print(pin);Serial.print(\" state changed to \");Serial.println(state);\r\n\t}\r\n}\r\n\r\nboolean lightIsOn() {\r\n\treturn digitalRead(LIGHTS_PIN);\r\n}\r\n\r\nboolean heatingIsOn() {\r\n\treturn digitalRead(HEAT_PIN);\r\n}\r\n\r\nvoid analogReadInputPin() {\r\n\tint sensorReading = analogRead(INPUT_PIN_IR_TRIGGER);\r\n\tif(sensorReading > 100 && sensorReading > analogSensorReading) {\r\n\t\tanalogSensorReading = sensorReading;\r\n\t}\r\n}\r\nAdded off-timer 15 mins#include \"BathRoomMirrorHeatingCtrl.h\"\r\n\r\n#include \r\n#include \r\n\r\n#include \"C:\/eclipseArduino\/sloeber\/arduinoPlugin\/packages\/arduino\/hardware\/avr\/1.6.18\/variants\/standard\/pins_arduino.h\"\r\n#include \"D:\/HomeAutomation\/ArduinoLibs\/DHT\/DHT.h\"\r\n#include \"D:\/HomeAutomation\/ArduinoLibs\/Timer\/Timer.h\"\r\n\r\nTimer resetAnalogPinTimer;\r\nTimer offTimer;\r\nTimer humiditySensorReadTimer;\r\nDHT dhtSensor(DHT_PIN, DHT22);\r\nvolatile DhtSensorData sensorData;\r\nvolatile boolean isHeatingAndLightDesired;\r\nvolatile int analogSensorReading;\r\n\r\nbool debug = true;\r\nbool ignoreHumiditySensor = true;\r\n\r\n\/\/The setup function is called once at startup of the sketch\r\nvoid setup() {\r\n\tSerial.begin(115200);\r\n\tSerial.println(\"Setup starts here...\");\r\n\r\n\tisHeatingAndLightDesired = false;\r\n\tsensorData.temperature = 25;\r\n\tsensorData.humidity = 55;\r\n\r\n\tpinMode(INPUT_PIN_IR_TRIGGER, INPUT);\r\n\tanalogReadInputPin();\r\n\tresetAnalogPinTimer.every(RESET_ANALOG_SENSOR_READING, resetReadingAndUpdateDecision);\r\n\r\n\tpinMode(LIGHTS_PIN, OUTPUT);\r\n\tsetRelay(LIGHTS_PIN, OFF);\r\n\r\n\tpinMode(HEAT_PIN, OUTPUT);\r\n\tsetRelay(HEAT_PIN, OFF);\r\n\r\n\tdhtSensor.begin();\r\n\treadDhtInfo();\r\n\thumiditySensorReadTimer.every(DHT_TIMER_EVERY, readDhtInfo);\r\n\tSerial.println(\"Setup ends here...\");\r\n}\r\n\r\n\/\/ The loop function is called in an endless loop\r\nvoid loop() {\r\n\toffTimer.update();\r\n\thumiditySensorReadTimer.update();\r\n\tresetAnalogPinTimer.update();\r\n\tdecisionMaker();\r\n\tanalogReadInputPin();\r\n}\r\n\r\nvoid resetReadingAndUpdateDecision() {\r\n\tif(analogSensorReading > ANALOG_TRESHOLD) {\r\n\t\tisHeatingAndLightDesired = !isHeatingAndLightDesired;\r\n\t\tif(isHeatingAndLightDesired) {\r\n\t\t\toffTimer.after(OFF_TIME_TIMER_OFFSET, offTimerExpired);\r\n\t\t} else {\r\n\t\t\toffTimer.stop(0);\r\n\t\t}\r\n\t}\r\n\r\n\tif(debug) {\r\n\t\tSerial.print(\"AnalogSensor last value:\");\r\n\t\tSerial.println(analogSensorReading);\r\n\t}\r\n\r\n\tanalogSensorReading = 0;\r\n}\r\n\r\nvoid offTimerExpired() {\r\n\tisHeatingAndLightDesired = false;;\r\n}\r\n\r\nvoid reattachInterrupt() {\r\n\tif(debug) {\r\n\t\tSerial.println(\"ReattachInterrupt triggered\");\r\n\t}\r\n\tattachInterrupt(digitalPinToInterrupt(INPUT_PIN_IR_TRIGGER), userInputDetected, RISING);\r\n\tresetAnalogPinTimer.stop(millis());\r\n}\r\n\r\nvoid readDhtInfo() {\r\n\tfloat humidity = dhtSensor.readHumidity();\r\n\tfloat temperature = dhtSensor.readTemperature();\r\n\r\n\t\/\/ simple error check. Do not update data if sensor reading is wrong.\r\n\tif(humidity > 0 && temperature > -30) {\r\n\t\tsensorData.humidity = humidity;\r\n\t\tsensorData.temperature = temperature;\r\n\t\tignoreHumiditySensor = false;\r\n\t} else {\r\n\t\tignoreHumiditySensor = true;\r\n\t\tif(debug) {\r\n\t\t\tSerial.println(\"DHT wrong data received...\");\r\n\t\t\tSerial.print(\"Humidity:\"); Serial.println(humidity);\r\n\t\t\tSerial.print(\"Temperature:\"); Serial.println(temperature);\r\n\t\t}\r\n\t}\r\n\tif(debug) {\r\n\/\/\t\tsensorData.humidity = random(100);\r\n\/\/\t\tsensorData.temperature = random(30);\r\n\t\tSerial.print(\"Humidity:\");Serial.println(sensorData.humidity);\r\n\t\tSerial.print(\"Temperature:\");Serial.println(sensorData.temperature);\r\n\t\treturn;\r\n\t}\r\n}\r\n\r\nvoid decisionMaker() {\r\n\tif(isHeatingAndLightDesired) {\r\n\t\tif(!lightIsOn()) {\r\n\t\t\tsetRelay(LIGHTS_PIN, ON);\r\n\t\t}\r\n\t\tif((sensorData.humidity > HUMIDITY_TRESHOLD || ignoreHumiditySensor) && !heatingIsOn()) {\r\n\t\t\tsetRelay(HEAT_PIN, ON);\r\n\t\t}\r\n\t} else {\r\n\t\tif(lightIsOn()) {\r\n\t\t\tsetRelay(LIGHTS_PIN, OFF);\r\n\t\t}\r\n\t\tif(heatingIsOn()) {\r\n\t\t\tsetRelay(HEAT_PIN, OFF);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid setRelay(byte pin, byte state) {\r\n\tdigitalWrite(pin, state);\r\n\tif (debug) {\r\n\t\tSerial.print(\"Pin \");Serial.print(pin);Serial.print(\" state changed to \");Serial.println(state);\r\n\t}\r\n}\r\n\r\nboolean lightIsOn() {\r\n\treturn digitalRead(LIGHTS_PIN);\r\n}\r\n\r\nboolean heatingIsOn() {\r\n\treturn digitalRead(HEAT_PIN);\r\n}\r\n\r\nvoid analogReadInputPin() {\r\n\tint sensorReading = analogRead(INPUT_PIN_IR_TRIGGER);\r\n\tif(sensorReading > 100 && sensorReading > analogSensorReading) {\r\n\t\tanalogSensorReading = sensorReading;\r\n\t}\r\n}\r\n<|endoftext|>"} {"text":"\/****************************************************************************\nCopyright (c) 2016 Yuji Toki(tokineco)\n- MIT license\n****************************************************************************\/\n\n#pragma execution_character_set(\"utf-8\")\n\n#include \"Converter.h\"\n\nUSING_NS_CC;\n\n\/\/ \"0xARGB\"の文字列からアルファ付きのColor4Bを返す\ncocos2d::Color4B Converter::fromARGB(std::string code) {\n\n \/\/ 0xARGBコードが見つかったら\n if (code.find(\"0x\") == 0 && code.length() == 10) {\n\n try {\n \/\/ A\n int a = (int)strtol(code.substr(2, 2).c_str(), nullptr, 16);\n \/\/ R\n int r = (int)strtol(code.substr(4, 2).c_str(), nullptr, 16);\n \/\/ G\n int g = (int)strtol(code.substr(6, 2).c_str(), nullptr, 16);\n \/\/ B\n int b = (int)strtol(code.substr(8, 2).c_str(), nullptr, 16);\n\n\n return cocos2d::Color4B(r, g, b, a);\n\n } catch (...) {\n \/\/ Error\n CCLOG(\"illegal color code : %s\", code.c_str());\n }\n } else {\n \/\/ Error\n CCLOG(\"not supeert format : %s\", code.c_str());\n }\n\n return cocos2d::Color4B::BLACK;\n}\n\n\/\/ 文字列の \"true\" or \"false\" を bool型の true or false に変換する\n\/\/ \"1\"もtrueとして扱う\nbool Converter::stringToBool(std::string strBool, bool def) {\n\n if (strBool == \"true\" || strBool == \"1\") {\n return true;\n } else if (strBool == \"false\" || strBool == \"0\") {\n return false;\n }\n\n return def;\n}\n\nbool Converter::stringToBool(std::string strBool) {\n return stringToBool(strBool, false);\n}\n\n\/\/ 文字列のSplit\nstd::vector Converter::split(std::string str, char delim) {\n\n std::vector result;\n std::string::size_type current = 0, delimIdx;\n\n while ((delimIdx = str.find_first_of(delim, current)) != std::string::npos) {\n result.push_back(std::string(str, current, delimIdx - current));\n current = delimIdx + 1;\n }\n result.push_back(std::string(str, current, str.size() - current));\n\n return result;\n}\n\n\/\/ 文字列の全置換\nstd::string Converter::replaceAll(std::string str, std::string before, std::string after) {\n\n std::string::size_type pos(str.find(before));\n\n while (pos != std::string::npos) {\n str.replace(pos, before.length(), after);\n pos = str.find(before, pos + after.length());\n }\n\n return str;\n}\n\n\/\/ 文字列の先頭と末尾にあるホワイトスペースを取り除く\nstd::string Converter::trim(const std::string& str, const char* trimChars \/* = \" \\t\\v\\r\\n\" *\/) {\n\n std::string result;\n std::string::size_type left = str.find_first_not_of(trimChars);\n\n if (left != std::string::npos) {\n std::string::size_type right = str.find_last_not_of(trimChars);\n result = str.substr(left, right - left + 1);\n }\n\n return result;\n}\nFixed error message typo\/****************************************************************************\nCopyright (c) 2016 Yuji Toki(tokineco)\n- MIT license\n****************************************************************************\/\n\n#pragma execution_character_set(\"utf-8\")\n\n#include \"Converter.h\"\n\nUSING_NS_CC;\n\n\/\/ \"0xARGB\"の文字列からアルファ付きのColor4Bを返す\ncocos2d::Color4B Converter::fromARGB(std::string code) {\n\n \/\/ 0xARGBコードが見つかったら\n if (code.find(\"0x\") == 0 && code.length() == 10) {\n\n try {\n \/\/ A\n int a = (int)strtol(code.substr(2, 2).c_str(), nullptr, 16);\n \/\/ R\n int r = (int)strtol(code.substr(4, 2).c_str(), nullptr, 16);\n \/\/ G\n int g = (int)strtol(code.substr(6, 2).c_str(), nullptr, 16);\n \/\/ B\n int b = (int)strtol(code.substr(8, 2).c_str(), nullptr, 16);\n\n\n return cocos2d::Color4B(r, g, b, a);\n\n } catch (...) {\n \/\/ Error\n CCLOG(\"illegal color code : %s\", code.c_str());\n }\n } else {\n \/\/ Error\n CCLOG(\"not support format : %s\", code.c_str());\n }\n\n return cocos2d::Color4B::BLACK;\n}\n\n\/\/ 文字列の \"true\" or \"false\" を bool型の true or false に変換する\n\/\/ \"1\"もtrueとして扱う\nbool Converter::stringToBool(std::string strBool, bool def) {\n\n if (strBool == \"true\" || strBool == \"1\") {\n return true;\n } else if (strBool == \"false\" || strBool == \"0\") {\n return false;\n }\n\n return def;\n}\n\nbool Converter::stringToBool(std::string strBool) {\n return stringToBool(strBool, false);\n}\n\n\/\/ 文字列のSplit\nstd::vector Converter::split(std::string str, char delim) {\n\n std::vector result;\n std::string::size_type current = 0, delimIdx;\n\n while ((delimIdx = str.find_first_of(delim, current)) != std::string::npos) {\n result.push_back(std::string(str, current, delimIdx - current));\n current = delimIdx + 1;\n }\n result.push_back(std::string(str, current, str.size() - current));\n\n return result;\n}\n\n\/\/ 文字列の全置換\nstd::string Converter::replaceAll(std::string str, std::string before, std::string after) {\n\n std::string::size_type pos(str.find(before));\n\n while (pos != std::string::npos) {\n str.replace(pos, before.length(), after);\n pos = str.find(before, pos + after.length());\n }\n\n return str;\n}\n\n\/\/ 文字列の先頭と末尾にあるホワイトスペースを取り除く\nstd::string Converter::trim(const std::string& str, const char* trimChars \/* = \" \\t\\v\\r\\n\" *\/) {\n\n std::string result;\n std::string::size_type left = str.find_first_not_of(trimChars);\n\n if (left != std::string::npos) {\n std::string::size_type right = str.find_last_not_of(trimChars);\n result = str.substr(left, right - left + 1);\n }\n\n return result;\n}\n<|endoftext|>"} {"text":"void Draw(string s_Exo, string s_Run)\n{\ngStyle->SetOptStat(0);\n\nstring s_TFile_Cyclus = s_Exo + \"\/\" + s_Run + \"\/cyclus.root\";\nstring s_TFile_Class = s_Exo + \"\/\" + s_Run + \"\/Scenario.root\";\n\ncout<Get(\"TT\");\nTTree *TCl = (TTree *) FCl->Get(\"TreeScenario\");\n\nTCy->SetLineColor(kRed); TCy->SetMarkerColor(kRed); TCy->SetLineWidth(3);\nTCl->SetLineColor(kBlue); TCl->SetMarkerColor(kBlue); TCl->SetLineWidth(3);\n\n\/\/ ################################################################################\n\/\/ Legend\n\/\/ ################################################################################\n \n TLegend *L01 = new TLegend(0.75,0.10,0.90,0.25);\n L01->AddEntry(TCy, \"Cyclus\", \"L\");\n L01->AddEntry(TCl, \"CLASS\", \"L\");\n\n\/\/ ################################################################################\n\/\/ ENERGY\n\/\/ ################################################################################\n\n TCanvas *C00 = new TCanvas(\"C00\",\"C00\",700,500);\n TCy->Draw(\"P:T\",\"\",\"L\");\n TCl->Draw(\"P:T\",\"\",\"Lsame\");\n TH1F *tmp0 = (TH1F*)gPad->GetPrimitive(\"htemp\"); tmp0->SetTitle(\"Thermal Power\");\n tmp0->GetXaxis()->SetTitle(\"Time (y)\"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);\n tmp0->GetYaxis()->SetTitle(\"Power (W)\"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);\n gPad->Update();\n L01->Draw();\n\n\/\/ ################################################################################\n\/\/ Plutonium\n\/\/ ################################################################################\n\n TCanvas *C0 = new TCanvas(\"C0\",\"Pu\",1400,900);\n C0->Divide(2,2,0.01,0.01);\n \n C0->cd(1);\n TCy->Draw(\"B93\/1000:T\",\"\",\"L\");\n TCl->Draw(\"B93:T\",\"\",\"Lsame\");\n tmp0 = (TH1F*)gPad->GetPrimitive(\"htemp\"); tmp0->SetTitle(\"Total Pu\");\n tmp0->GetXaxis()->SetTitle(\"Time (y)\"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);\n tmp0->GetYaxis()->SetTitle(\"Mass (tons)\"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);\n gPad->Update();\n L01->Draw();\n \n C0->cd(2);\n TCy->Draw(\"B3\/1000:T\",\"\",\"L\");\n TCl->Draw(\"B3:T\",\"\",\"Lsame\");\n tmp0 = (TH1F*)gPad->GetPrimitive(\"htemp\"); tmp0->SetTitle(\"Pu in Stock\");\n tmp0->GetXaxis()->SetTitle(\"Time (y)\"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);\n tmp0->GetYaxis()->SetTitle(\"Mass (tons)\"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);\n gPad->Update();\n L01->Draw();\n\n C0->cd(3);\n TCy->Draw(\"B98\/1000:T\",\"\",\"L\");\n TCl->Draw(\"B98:T\",\"\",\"Lsame\");\n tmp0 = (TH1F*)gPad->GetPrimitive(\"htemp\"); tmp0->SetTitle(\"Total Pu9\");\n tmp0->GetXaxis()->SetTitle(\"Time (y)\"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);\n tmp0->GetYaxis()->SetTitle(\"Mass (tons)\"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);\n gPad->Update();\n L01->Draw();\n \n C0->cd(4);\n TCy->Draw(\"B8\/1000:T\",\"\",\"L\");\n TCl->Draw(\"B8:T\",\"\",\"Lsame\");\n tmp0 = (TH1F*)gPad->GetPrimitive(\"htemp\"); tmp0->SetTitle(\"Pu9 in Stock\");\n tmp0->GetXaxis()->SetTitle(\"Time (y)\"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);\n tmp0->GetYaxis()->SetTitle(\"Mass (tons)\"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);\n gPad->Update();\n L01->Draw();\n\n\/\/ ################################################################################\n\/\/ MA\n\/\/ ################################################################################\n\n TCanvas *C1 = new TCanvas(\"C1\",\"MA\",1400,900);\n C1->Divide(2,2,0.01,0.01);\n \n C1->cd(1);\n TCy->Draw(\"B96\/1000:T\",\"\",\"L\");\n TCl->Draw(\"B96:T\",\"\",\"Lsame\");\n tmp0 = (TH1F*)gPad->GetPrimitive(\"htemp\"); tmp0->SetTitle(\"Total MA\");\n tmp0->GetXaxis()->SetTitle(\"Time (y)\"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);\n tmp0->GetYaxis()->SetTitle(\"Mass (tons)\"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);\n gPad->Update();\n L01->Draw();\n \n C1->cd(2);\n TCy->Draw(\"B94\/1000:T\",\"\",\"L\");\n TCl->Draw(\"B94:T\",\"\",\"Lsame\");\n tmp0 = (TH1F*)gPad->GetPrimitive(\"htemp\"); tmp0->SetTitle(\"Total Am\");\n tmp0->GetXaxis()->SetTitle(\"Time (y)\"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);\n tmp0->GetYaxis()->SetTitle(\"Mass (tons)\"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);\n gPad->Update();\n L01->Draw();\n \n C1->cd(3);\n TCy->Draw(\"B92\/1000:T\",\"\",\"L\");\n TCl->Draw(\"B92:T\",\"\",\"Lsame\");\n tmp0 = (TH1F*)gPad->GetPrimitive(\"htemp\"); tmp0->SetTitle(\"Total Np\");\n tmp0->GetXaxis()->SetTitle(\"Time (y)\"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);\n tmp0->GetYaxis()->SetTitle(\"Mass (tons)\"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);\n gPad->Update();\n L01->Draw();\n \n C1->cd(4);\n TCy->Draw(\"B95\/1000:T\",\"\",\"L\");\n TCl->Draw(\"B95:T\",\"\",\"Lsame\");\n tmp0 = (TH1F*)gPad->GetPrimitive(\"htemp\"); tmp0->SetTitle(\"Total Cm\");\n tmp0->GetXaxis()->SetTitle(\"Time (y)\"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);\n tmp0->GetYaxis()->SetTitle(\"Mass (tons)\"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);\n gPad->Update();\n L01->Draw();\n}\nUpdate general Draw scriptvoid Draw(string s_Exo, string s_Run)\n{\ngStyle->SetOptStat(0);\n\nstring s_TFile_Cyclus = s_Exo + \"\/\" + s_Run + \"\/cyclus.root\";\nstring s_TFile_Class = s_Exo + \"\/\" + s_Run + \"\/Scenario.root\";\n\ncout<Get(\"TT\");\nTTree *TCl = (TTree *) FCl->Get(\"TreeScenario\");\n\nTCy->SetLineColor(kRed); TCy->SetMarkerColor(kRed); TCy->SetLineWidth(3);\nTCl->SetLineColor(kBlue); TCl->SetMarkerColor(kBlue); TCl->SetLineWidth(3);\n\n\/\/ ################################################################################\n\/\/ Legend\n\/\/ ################################################################################\n \n TLegend *L01 = new TLegend(0.75,0.10,0.90,0.25);\n L01->AddEntry(TCy, \"Cyclus\", \"L\");\n L01->AddEntry(TCl, \"CLASS\", \"L\");\n\n\/\/ ################################################################################\n\/\/ ENERGY\n\/\/ ################################################################################\n\n TCanvas *C00 = new TCanvas(\"C00\",\"C00\",700,500);\n TCy->Draw(\"P:T\",\"\",\"L\");\n TCl->Draw(\"P:T\",\"\",\"Lsame\");\n TH1F *tmp0 = (TH1F*)gPad->GetPrimitive(\"htemp\"); tmp0->SetTitle(\"Thermal Power\");\n tmp0->GetXaxis()->SetTitle(\"Time (y)\"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);\n tmp0->GetYaxis()->SetTitle(\"Power (W)\"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);\n gPad->Update();\n L01->Draw();\n\n\/\/ ################################################################################\n\/\/ Plutonium\n\/\/ ################################################################################\n\n TCanvas *C0 = new TCanvas(\"C0\",\"Pu\",1500,900);\n C0->Divide(2,2,0.01,0.01);\n \n C0->cd(1);\n TCy->Draw(\"B93\/1000:T\",\"\",\"L\");\n TCl->Draw(\"B93:T\",\"\",\"Lsame\");\n tmp0 = (TH1F*)gPad->GetPrimitive(\"htemp\"); tmp0->SetTitle(\"Total Pu\");\n tmp0->GetXaxis()->SetTitle(\"Time (y)\"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);\n tmp0->GetYaxis()->SetTitle(\"Mass (tons)\"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);\n gPad->Update();\n L01->Draw();\n \n C0->cd(2);\n TCy->Draw(\"B3\/1000:T\",\"\",\"L\");\n TCl->Draw(\"B3:T\",\"\",\"Lsame\");\n tmp0 = (TH1F*)gPad->GetPrimitive(\"htemp\"); tmp0->SetTitle(\"Pu in Stock\");\n tmp0->GetXaxis()->SetTitle(\"Time (y)\"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);\n tmp0->GetYaxis()->SetTitle(\"Mass (tons)\"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);\n gPad->Update();\n L01->Draw();\n\n C0->cd(3);\n TCy->Draw(\"B98\/1000:T\",\"\",\"L\");\n TCl->Draw(\"B98:T\",\"\",\"Lsame\");\n tmp0 = (TH1F*)gPad->GetPrimitive(\"htemp\"); tmp0->SetTitle(\"Total Pu9\");\n tmp0->GetXaxis()->SetTitle(\"Time (y)\"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);\n tmp0->GetYaxis()->SetTitle(\"Mass (tons)\"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);\n gPad->Update();\n L01->Draw();\n \n C0->cd(4);\n TCy->Draw(\"B8\/1000:T\",\"\",\"L\");\n TCl->Draw(\"B8:T\",\"\",\"Lsame\");\n tmp0 = (TH1F*)gPad->GetPrimitive(\"htemp\"); tmp0->SetTitle(\"Pu9 in Stock\");\n tmp0->GetXaxis()->SetTitle(\"Time (y)\"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);\n tmp0->GetYaxis()->SetTitle(\"Mass (tons)\"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);\n gPad->Update();\n L01->Draw();\n\n\/\/ ################################################################################\n\/\/ MA\n\/\/ ################################################################################\n\n TCanvas *C1 = new TCanvas(\"C1\",\"MA\",1500,900);\n C1->Divide(2,2,0.01,0.01);\n \n C1->cd(1);\n TCy->Draw(\"B96\/1000:T\",\"\",\"L\");\n TCl->Draw(\"B96:T\",\"\",\"Lsame\");\n tmp0 = (TH1F*)gPad->GetPrimitive(\"htemp\"); tmp0->SetTitle(\"Total MA\");\n tmp0->GetXaxis()->SetTitle(\"Time (y)\"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);\n tmp0->GetYaxis()->SetTitle(\"Mass (tons)\"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);\n gPad->Update();\n L01->Draw();\n \n C1->cd(2);\n TCy->Draw(\"B94\/1000:T\",\"\",\"L\");\n TCl->Draw(\"B94:T\",\"\",\"Lsame\");\n tmp0 = (TH1F*)gPad->GetPrimitive(\"htemp\"); tmp0->SetTitle(\"Total Am\");\n tmp0->GetXaxis()->SetTitle(\"Time (y)\"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);\n tmp0->GetYaxis()->SetTitle(\"Mass (tons)\"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);\n gPad->Update();\n L01->Draw();\n \n C1->cd(3);\n TCy->Draw(\"B92\/1000:T\",\"\",\"L\");\n TCl->Draw(\"B92:T\",\"\",\"Lsame\");\n tmp0 = (TH1F*)gPad->GetPrimitive(\"htemp\"); tmp0->SetTitle(\"Total Np\");\n tmp0->GetXaxis()->SetTitle(\"Time (y)\"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);\n tmp0->GetYaxis()->SetTitle(\"Mass (tons)\"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);\n gPad->Update();\n L01->Draw();\n \n C1->cd(4);\n TCy->Draw(\"B95\/1000:T\",\"\",\"L\");\n TCl->Draw(\"B95:T\",\"\",\"Lsame\");\n tmp0 = (TH1F*)gPad->GetPrimitive(\"htemp\"); tmp0->SetTitle(\"Total Cm\");\n tmp0->GetXaxis()->SetTitle(\"Time (y)\"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);\n tmp0->GetYaxis()->SetTitle(\"Mass (tons)\"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);\n gPad->Update();\n L01->Draw();\n}\n<|endoftext|>"} {"text":"\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkNavigationToolStorage.h\"\n\n\/\/Microservices\n#include \n#include \n#include \n\nconst std::string mitk::NavigationToolStorage::US_INTERFACE_NAME = \"org.mitk.services.NavigationToolStorage\"; \/\/ Name of the interface\nconst std::string mitk::NavigationToolStorage::US_PROPKEY_SOURCE_ID = US_INTERFACE_NAME + \".sourceID\";\nconst std::string mitk::NavigationToolStorage::US_PROPKEY_STORAGE_NAME = US_INTERFACE_NAME + \".name\";\n\nmitk::NavigationToolStorage::NavigationToolStorage()\n : m_ToolCollection(std::vector()),\n m_DataStorage(NULL),\n m_storageLocked(false)\n {\n this->SetName(\"ToolStorage (no name given)\");\n }\n\nmitk::NavigationToolStorage::NavigationToolStorage(mitk::DataStorage::Pointer ds)\n : m_storageLocked(false)\n {\n m_ToolCollection = std::vector();\n this->m_DataStorage = ds;\n this->SetName(\"Tool Storage (no name given)\");\n }\n\nvoid mitk::NavigationToolStorage::SetName(std::string n)\n {\n m_Name = n;\n m_props[ US_PROPKEY_STORAGE_NAME ] = m_Name;\n }\n\nstd::string mitk::NavigationToolStorage::GetName() const\n{\n return m_Name;\n}\n\n void mitk::NavigationToolStorage::UpdateMicroservice()\n {\n if (m_ServiceRegistration) {m_ServiceRegistration.SetProperties(m_props);}\n }\n\n\nmitk::NavigationToolStorage::~NavigationToolStorage()\n {\n if (m_DataStorage.IsNotNull()) \/\/remove all nodes from the data storage\n {\n for(std::vector::iterator it = m_ToolCollection.begin(); it != m_ToolCollection.end(); it++)\n m_DataStorage->Remove((*it)->GetDataNode());\n }\n }\n\n\nvoid mitk::NavigationToolStorage::RegisterAsMicroservice(std::string sourceID){\n\n if ( sourceID.empty() ) mitkThrow() << \"Empty or null string passed to NavigationToolStorage::registerAsMicroservice().\";\n\n \/\/ Get Context\n us::ModuleContext* context = us::GetModuleContext();\n\n \/\/ Define ServiceProps\n m_props[ US_PROPKEY_SOURCE_ID ] = sourceID;\n m_ServiceRegistration = context->RegisterService(this, m_props);\n}\n\n\nvoid mitk::NavigationToolStorage::UnRegisterMicroservice(){\n if ( ! m_ServiceRegistration )\n {\n MITK_WARN(\"NavigationToolStorage\")\n << \"Cannot unregister microservice as it wasn't registered before.\";\n return;\n }\n\n m_ServiceRegistration.Unregister();\n m_ServiceRegistration = 0;\n}\n\n\nbool mitk::NavigationToolStorage::DeleteTool(int number)\n {\n if (m_storageLocked)\n {\n MITK_WARN << \"Storage is locked, cannot modify it!\";\n return false;\n }\n\n else if ((unsigned int)number > m_ToolCollection.size())\n {\n MITK_WARN << \"Tool no \" << number << \"doesn't exist, can't delete it!\";\n return false;\n }\n std::vector::iterator it = m_ToolCollection.begin() + number;\n if(m_DataStorage.IsNotNull())\n m_DataStorage->Remove((*it)->GetDataNode());\n m_ToolCollection.erase(it);\n\n return true;\n }\n\nbool mitk::NavigationToolStorage::DeleteAllTools()\n {\n if (m_storageLocked)\n {\n MITK_WARN << \"Storage is locked, cannot modify it!\";\n return false;\n }\n\n while(m_ToolCollection.size() > 0) if (!DeleteTool(0)) return false;\n return true;\n }\n\nbool mitk::NavigationToolStorage::AddTool(mitk::NavigationTool::Pointer tool)\n {\n if (m_storageLocked)\n {\n MITK_WARN << \"Storage is locked, cannot modify it!\";\n return false;\n }\n else if (GetTool(tool->GetIdentifier()).IsNotNull())\n {\n MITK_WARN << \"Tool ID already exists in storage, can't add!\";\n return false;\n }\n else\n {\n m_ToolCollection.push_back(tool);\n if(m_DataStorage.IsNotNull())\n {\n if (!m_DataStorage->Exists(tool->GetDataNode()))\n m_DataStorage->Add(tool->GetDataNode());\n }\n return true;\n }\n }\n\nmitk::NavigationTool::Pointer mitk::NavigationToolStorage::GetTool(int number)\n {\n return m_ToolCollection.at(number);\n }\n\nmitk::NavigationTool::Pointer mitk::NavigationToolStorage::GetTool(std::string identifier)\n {\n for (int i=0; iGetIdentifier())==identifier) return GetTool(i);\n return NULL;\n }\n\nmitk::NavigationTool::Pointer mitk::NavigationToolStorage::GetToolByName(std::string name)\n {\n for (int i=0; iGetToolName())==name) return GetTool(i);\n return NULL;\n }\n\nint mitk::NavigationToolStorage::GetToolCount()\n {\n return m_ToolCollection.size();\n }\n\nbool mitk::NavigationToolStorage::isEmpty()\n {\n return m_ToolCollection.empty();\n }\n\nvoid mitk::NavigationToolStorage::LockStorage()\n {\n m_storageLocked = true;\n }\n\nvoid mitk::NavigationToolStorage::UnLockStorage()\n {\n m_storageLocked = false;\n }\n\nbool mitk::NavigationToolStorage::isLocked()\n {\n return m_storageLocked;\n }\n\nbool mitk::NavigationToolStorage::AssignToolNumber(std::string identifier1, int number2)\n {\n if (this->GetTool(identifier1).IsNull())\n {\n MITK_WARN << \"Identifier does not exist, cannot assign new number\";\n return false;\n }\n\n if ((number2 >= m_ToolCollection.size()) || (number2 < 0))\n {\n MITK_WARN << \"Invalid number, cannot assign new number\";\n return false;\n }\n\n mitk::NavigationTool::Pointer tool2 = m_ToolCollection.at(number2);\n\n int number1 = -1;\n\n for(int i = 0; iGetIdentifier() == identifier1) {number1=i;}\n }\n\n m_ToolCollection[number2] = m_ToolCollection.at(number1);\n\n m_ToolCollection[number1] = tool2;\n\n MITK_DEBUG << \"Swapped tool \" << number2 << \" with tool \" << number1;\n\n return true;\n}\nCode format for better reading. White space changes only.\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkNavigationToolStorage.h\"\n\n\/\/Microservices\n#include \n#include \n#include \n\nconst std::string mitk::NavigationToolStorage::US_INTERFACE_NAME = \"org.mitk.services.NavigationToolStorage\"; \/\/ Name of the interface\nconst std::string mitk::NavigationToolStorage::US_PROPKEY_SOURCE_ID = US_INTERFACE_NAME + \".sourceID\";\nconst std::string mitk::NavigationToolStorage::US_PROPKEY_STORAGE_NAME = US_INTERFACE_NAME + \".name\";\n\nmitk::NavigationToolStorage::NavigationToolStorage()\n : m_ToolCollection(std::vector()),\n m_DataStorage(NULL),\n m_storageLocked(false)\n{\n this->SetName(\"ToolStorage (no name given)\");\n}\n\nmitk::NavigationToolStorage::NavigationToolStorage(mitk::DataStorage::Pointer ds)\n : m_storageLocked(false)\n{\n m_ToolCollection = std::vector();\n this->m_DataStorage = ds;\n this->SetName(\"Tool Storage (no name given)\");\n}\n\nvoid mitk::NavigationToolStorage::SetName(std::string n)\n{\n m_Name = n;\n m_props[US_PROPKEY_STORAGE_NAME] = m_Name;\n}\n\nstd::string mitk::NavigationToolStorage::GetName() const\n{\n return m_Name;\n}\n\nvoid mitk::NavigationToolStorage::UpdateMicroservice()\n{\n if (m_ServiceRegistration) { m_ServiceRegistration.SetProperties(m_props); }\n}\n\nmitk::NavigationToolStorage::~NavigationToolStorage()\n{\n if (m_DataStorage.IsNotNull()) \/\/remove all nodes from the data storage\n {\n for (std::vector::iterator it = m_ToolCollection.begin(); it != m_ToolCollection.end(); it++)\n m_DataStorage->Remove((*it)->GetDataNode());\n }\n}\n\nvoid mitk::NavigationToolStorage::RegisterAsMicroservice(std::string sourceID){\n if (sourceID.empty()) mitkThrow() << \"Empty or null string passed to NavigationToolStorage::registerAsMicroservice().\";\n\n \/\/ Get Context\n us::ModuleContext* context = us::GetModuleContext();\n\n \/\/ Define ServiceProps\n m_props[US_PROPKEY_SOURCE_ID] = sourceID;\n m_ServiceRegistration = context->RegisterService(this, m_props);\n}\n\nvoid mitk::NavigationToolStorage::UnRegisterMicroservice(){\n if (!m_ServiceRegistration)\n {\n MITK_WARN(\"NavigationToolStorage\")\n << \"Cannot unregister microservice as it wasn't registered before.\";\n return;\n }\n\n m_ServiceRegistration.Unregister();\n m_ServiceRegistration = 0;\n}\n\nbool mitk::NavigationToolStorage::DeleteTool(int number)\n{\n if (m_storageLocked)\n {\n MITK_WARN << \"Storage is locked, cannot modify it!\";\n return false;\n }\n\n else if ((unsigned int)number > m_ToolCollection.size())\n {\n MITK_WARN << \"Tool no \" << number << \"doesn't exist, can't delete it!\";\n return false;\n }\n std::vector::iterator it = m_ToolCollection.begin() + number;\n if (m_DataStorage.IsNotNull())\n m_DataStorage->Remove((*it)->GetDataNode());\n m_ToolCollection.erase(it);\n\n return true;\n}\n\nbool mitk::NavigationToolStorage::DeleteAllTools()\n{\n if (m_storageLocked)\n {\n MITK_WARN << \"Storage is locked, cannot modify it!\";\n return false;\n }\n\n while (m_ToolCollection.size() > 0) if (!DeleteTool(0)) return false;\n return true;\n}\n\nbool mitk::NavigationToolStorage::AddTool(mitk::NavigationTool::Pointer tool)\n{\n if (m_storageLocked)\n {\n MITK_WARN << \"Storage is locked, cannot modify it!\";\n return false;\n }\n else if (GetTool(tool->GetIdentifier()).IsNotNull())\n {\n MITK_WARN << \"Tool ID already exists in storage, can't add!\";\n return false;\n }\n else\n {\n m_ToolCollection.push_back(tool);\n if (m_DataStorage.IsNotNull())\n {\n if (!m_DataStorage->Exists(tool->GetDataNode()))\n m_DataStorage->Add(tool->GetDataNode());\n }\n return true;\n }\n}\n\nmitk::NavigationTool::Pointer mitk::NavigationToolStorage::GetTool(int number)\n{\n return m_ToolCollection.at(number);\n}\n\nmitk::NavigationTool::Pointer mitk::NavigationToolStorage::GetTool(std::string identifier)\n{\n for (int i = 0; i < GetToolCount(); i++) if ((GetTool(i)->GetIdentifier()) == identifier) return GetTool(i);\n return NULL;\n}\n\nmitk::NavigationTool::Pointer mitk::NavigationToolStorage::GetToolByName(std::string name)\n{\n for (int i = 0; i < GetToolCount(); i++) if ((GetTool(i)->GetToolName()) == name) return GetTool(i);\n return NULL;\n}\n\nint mitk::NavigationToolStorage::GetToolCount()\n{\n return m_ToolCollection.size();\n}\n\nbool mitk::NavigationToolStorage::isEmpty()\n{\n return m_ToolCollection.empty();\n}\n\nvoid mitk::NavigationToolStorage::LockStorage()\n{\n m_storageLocked = true;\n}\n\nvoid mitk::NavigationToolStorage::UnLockStorage()\n{\n m_storageLocked = false;\n}\n\nbool mitk::NavigationToolStorage::isLocked()\n{\n return m_storageLocked;\n}\n\nbool mitk::NavigationToolStorage::AssignToolNumber(std::string identifier1, int number2)\n{\n if (this->GetTool(identifier1).IsNull())\n {\n MITK_WARN << \"Identifier does not exist, cannot assign new number\";\n return false;\n }\n\n if ((number2 >= m_ToolCollection.size()) || (number2 < 0))\n {\n MITK_WARN << \"Invalid number, cannot assign new number\";\n return false;\n }\n\n mitk::NavigationTool::Pointer tool2 = m_ToolCollection.at(number2);\n\n int number1 = -1;\n\n for (int i = 0; i < m_ToolCollection.size(); i++)\n {\n if (m_ToolCollection.at(i)->GetIdentifier() == identifier1) { number1 = i; }\n }\n\n m_ToolCollection[number2] = m_ToolCollection.at(number1);\n\n m_ToolCollection[number1] = tool2;\n\n MITK_DEBUG << \"Swapped tool \" << number2 << \" with tool \" << number1;\n\n return true;\n}<|endoftext|>"} {"text":"\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n\/\/Poco headers\n#include \"Poco\/Zip\/Decompress.h\"\n#include \"Poco\/Path.h\"\n#include \"Poco\/File.h\"\n\n#include \"mitkNavigationToolStorageDeserializer.h\"\n#include \n#include \n#include \"mitkNavigationToolReader.h\"\n\n\/\/POCO\n#include \n\n\n#include \"mitkIGTException.h\"\n#include \"mitkIGTIOException.h\"\n\n\nmitk::NavigationToolStorageDeserializer::NavigationToolStorageDeserializer(mitk::DataStorage::Pointer dataStorage)\n {\n m_DataStorage = dataStorage;\n \/\/create temp directory for this reader\n m_tempDirectory = mitk::IOUtil::CreateTemporaryDirectory(\"NavigationToolStorageDeserializerTmp_XXXXXX\",mitk::IOUtil::GetTempPath());\n }\n\nmitk::NavigationToolStorageDeserializer::~NavigationToolStorageDeserializer()\n {\n \/\/remove temp directory\n Poco::File myFile(m_tempDirectory);\n try\n {\n if (myFile.exists()) myFile.remove();\n }\n catch(...)\n {\n MITK_ERROR << \"Can't remove temp directory \" << m_tempDirectory << \"!\";\n }\n }\n\nmitk::NavigationToolStorage::Pointer mitk::NavigationToolStorageDeserializer::Deserialize(std::string filename)\n {\n \/\/decomress zip file into temporary directory\n decomressFiles(filename,m_tempDirectory);\n\n \/\/now read all files and convert them to navigation tools\n mitk::NavigationToolStorage::Pointer returnValue = mitk::NavigationToolStorage::New(m_DataStorage);\n bool cont = true;\n int i;\n for (i=0; cont==true; i++)\n {\n std::string fileName = m_tempDirectory + Poco::Path::separator() + \"NavigationTool\" + convertIntToString(i) + \".tool\";\n mitk::NavigationToolReader::Pointer myReader = mitk::NavigationToolReader::New();\n mitk::NavigationTool::Pointer readTool = myReader->DoRead(fileName);\n if (readTool.IsNull()) cont = false;\n else returnValue->AddTool(readTool);\n \/\/delete file\n std::remove(fileName.c_str());\n }\n if(i==1)\n {\n \/\/throw an exception here in case of not finding any tool\n m_ErrorMessage = \"Error: did not find any tool. \\n Is this a tool storage file?\";\n mitkThrowException(mitk::IGTException)<<\"Error: did not find any tool. \\n Is this a tool storage file?\";\n }\n return returnValue;\n }\n\nstd::string mitk::NavigationToolStorageDeserializer::convertIntToString(int i)\n{\nstd::string s;\nstd::stringstream out;\nout << i;\ns = out.str();\nreturn s;\n}\n\nvoid mitk::NavigationToolStorageDeserializer::decomressFiles(std::string filename,std::string path)\n{\n std::ifstream file( filename.c_str(), std::ios::binary );\n if (!file.good())\n {\n m_ErrorMessage = \"Cannot open '\" + filename + \"' for reading\";\n mitkThrowException(mitk::IGTException)<<\"Cannot open\"+filename+\" for reading\";\n }\n\n try\n {\n Poco::Zip::Decompress unzipper( file, Poco::Path( path ) );\n unzipper.decompressAllFiles();\n file.close();\n }\n\n catch(Poco::IllegalStateException e) \/\/temporary solution: replace this by defined exception handling later!\n {\n m_ErrorMessage = \"Error: wrong file format! \\n (please only load tool storage files)\";\n MITK_ERROR << m_ErrorMessage;\n mitkThrowException(mitk::IGTException) << m_ErrorMessage;\n }\n\n }\nRemove logging of error message\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n\/\/Poco headers\n#include \"Poco\/Zip\/Decompress.h\"\n#include \"Poco\/Path.h\"\n#include \"Poco\/File.h\"\n\n#include \"mitkNavigationToolStorageDeserializer.h\"\n#include \n#include \n#include \"mitkNavigationToolReader.h\"\n\n\/\/POCO\n#include \n\n\n#include \"mitkIGTException.h\"\n#include \"mitkIGTIOException.h\"\n\n\nmitk::NavigationToolStorageDeserializer::NavigationToolStorageDeserializer(mitk::DataStorage::Pointer dataStorage)\n {\n m_DataStorage = dataStorage;\n \/\/create temp directory for this reader\n m_tempDirectory = mitk::IOUtil::CreateTemporaryDirectory(\"NavigationToolStorageDeserializerTmp_XXXXXX\",mitk::IOUtil::GetTempPath());\n }\n\nmitk::NavigationToolStorageDeserializer::~NavigationToolStorageDeserializer()\n {\n \/\/remove temp directory\n Poco::File myFile(m_tempDirectory);\n try\n {\n if (myFile.exists()) myFile.remove();\n }\n catch(...)\n {\n MITK_ERROR << \"Can't remove temp directory \" << m_tempDirectory << \"!\";\n }\n }\n\nmitk::NavigationToolStorage::Pointer mitk::NavigationToolStorageDeserializer::Deserialize(std::string filename)\n {\n \/\/decomress zip file into temporary directory\n decomressFiles(filename,m_tempDirectory);\n\n \/\/now read all files and convert them to navigation tools\n mitk::NavigationToolStorage::Pointer returnValue = mitk::NavigationToolStorage::New(m_DataStorage);\n bool cont = true;\n int i;\n for (i=0; cont==true; i++)\n {\n std::string fileName = m_tempDirectory + Poco::Path::separator() + \"NavigationTool\" + convertIntToString(i) + \".tool\";\n mitk::NavigationToolReader::Pointer myReader = mitk::NavigationToolReader::New();\n mitk::NavigationTool::Pointer readTool = myReader->DoRead(fileName);\n if (readTool.IsNull()) cont = false;\n else returnValue->AddTool(readTool);\n \/\/delete file\n std::remove(fileName.c_str());\n }\n if(i==1)\n {\n \/\/throw an exception here in case of not finding any tool\n m_ErrorMessage = \"Error: did not find any tool. \\n Is this a tool storage file?\";\n mitkThrowException(mitk::IGTException)<<\"Error: did not find any tool. \\n Is this a tool storage file?\";\n }\n return returnValue;\n }\n\nstd::string mitk::NavigationToolStorageDeserializer::convertIntToString(int i)\n{\nstd::string s;\nstd::stringstream out;\nout << i;\ns = out.str();\nreturn s;\n}\n\nvoid mitk::NavigationToolStorageDeserializer::decomressFiles(std::string filename,std::string path)\n{\n std::ifstream file( filename.c_str(), std::ios::binary );\n if (!file.good())\n {\n m_ErrorMessage = \"Cannot open '\" + filename + \"' for reading\";\n mitkThrowException(mitk::IGTException)<<\"Cannot open\"+filename+\" for reading\";\n }\n\n try\n {\n Poco::Zip::Decompress unzipper( file, Poco::Path( path ) );\n unzipper.decompressAllFiles();\n file.close();\n }\n\n catch(Poco::IllegalStateException e) \/\/temporary solution: replace this by defined exception handling later!\n {\n m_ErrorMessage = \"Error: wrong file format! \\n (please only load tool storage files)\";\n mitkThrowException(mitk::IGTException) << m_ErrorMessage;\n }\n\n }\n<|endoftext|>"} {"text":"\/*\nOpen Asset Import Library (assimp)\n----------------------------------------------------------------------\n\nCopyright (c) 2006-2016, assimp team\nAll rights reserved.\n\nRedistribution and use of this software in source and binary forms,\nwith or without modification, are permitted provided that the\nfollowing conditions are met:\n\n* Redistributions of source code must retain the above\n copyright notice, this list of conditions and the\n following disclaimer.\n\n* Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the\n following disclaimer in the documentation and\/or other\n materials provided with the distribution.\n\n* Neither the name of the assimp team, nor the names of its\n contributors may be used to endorse or promote products\n derived from this software without specific prior\n written permission of the assimp team.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n----------------------------------------------------------------------\n*\/\n\n#include \"D3MFImporter.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \"irrXMLWrapper.h\"\n#include \"StringComparison.h\"\n#include \"StringUtils.h\"\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"D3MFOpcPackage.h\"\n\n#ifndef ASSIMP_BUILD_NO_3MF_IMPORTER\n\nnamespace Assimp {\n\nnamespace D3MF {\n\n\nnamespace XmlTag {\n\n const std::string model = \"model\";\n const std::string metadata = \"metadata\";\n const std::string resources = \"resources\";\n const std::string object = \"object\";\n const std::string mesh = \"mesh\";\n const std::string vertices = \"vertices\";\n const std::string vertex = \"vertex\";\n const std::string triangles = \"triangles\";\n const std::string triangle = \"triangle\";\n const std::string x = \"x\";\n const std::string y = \"y\";\n const std::string z = \"z\";\n const std::string v1 = \"v1\";\n const std::string v2 = \"v2\";\n const std::string v3 = \"v3\";\n const std::string id = \"id\";\n const std::string name = \"name\";\n const std::string type = \"type\";\n const std::string build = \"build\";\n const std::string item = \"item\";\n const std::string objectid = \"objectid\";\n const std::string transform = \"transform\";\n\n}\n\n\nclass XmlSerializer\n{\npublic:\n XmlSerializer(XmlReader* xmlReader)\n : xmlReader(xmlReader)\n {\n\n }\n\n void ImportXml(aiScene* scene)\n {\n\n scene->mFlags |= AI_SCENE_FLAGS_NON_VERBOSE_FORMAT;\n\n scene->mRootNode = new aiNode();\n std::vector children;\n\n while(ReadToEndElement(D3MF::XmlTag::model))\n { \n\n if(xmlReader->getNodeName() == D3MF::XmlTag::object)\n {\n children.push_back(ReadObject(scene));\n }\n else if(xmlReader->getNodeName() == D3MF::XmlTag::build)\n {\n\n }\n } \n\n if(scene->mRootNode->mName.length == 0)\n scene->mRootNode->mName.Set(\"3MF\");\n\n\n scene->mNumMeshes = static_cast(meshes.size());\n scene->mMeshes = new aiMesh*[scene->mNumMeshes]();\n\n std::copy(meshes.begin(), meshes.end(), scene->mMeshes);\n\n scene->mRootNode->mNumChildren = static_cast(children.size());\n scene->mRootNode->mChildren = new aiNode*[scene->mRootNode->mNumChildren]();\n\n std::copy(children.begin(), children.end(), scene->mRootNode->mChildren);\n\n }\n\nprivate:\n aiNode* ReadObject(aiScene* scene)\n { \n ScopeGuard node(new aiNode());\n\n std::vector meshIds;\n\n int id = std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::id.c_str()));\n std::string name(xmlReader->getAttributeValue(D3MF::XmlTag::name.c_str()));\n std::string type(xmlReader->getAttributeValue(D3MF::XmlTag::type.c_str()));\n\n node->mParent = scene->mRootNode;\n node->mName.Set(name); \n\n unsigned long meshIdx = meshes.size();\n\n while(ReadToEndElement(D3MF::XmlTag::object))\n {\n if(xmlReader->getNodeName() == D3MF::XmlTag::mesh)\n { \n auto mesh = ReadMesh();\n\n mesh->mName.Set(name);\n meshes.push_back(mesh);\n meshIds.push_back(meshIdx);\n meshIdx++;\n\n }\n }\n\n node->mNumMeshes = static_cast(meshIds.size());\n\n node->mMeshes = new unsigned int[node->mNumMeshes];\n\n std::copy(meshIds.begin(), meshIds.end(), node->mMeshes);\n\n return node.dismiss();\n\n }\n\n aiMesh* ReadMesh()\n {\n aiMesh* mesh = new aiMesh();\n\n while(ReadToEndElement(D3MF::XmlTag::mesh))\n { \n if(xmlReader->getNodeName() == D3MF::XmlTag::vertices)\n {\n ImportVertices(mesh);\n }\n else if(xmlReader->getNodeName() == D3MF::XmlTag::triangles)\n {\n ImportTriangles(mesh);\n }\n\n }\n\n\n return mesh;\n }\n\n void ImportVertices(aiMesh* mesh)\n {\n std::vector vertices; \n\n while(ReadToEndElement(D3MF::XmlTag::vertices))\n { \n if(xmlReader->getNodeName() == D3MF::XmlTag::vertex)\n { \n vertices.push_back(ReadVertex());\n }\n }\n mesh->mNumVertices = static_cast(vertices.size());\n mesh->mVertices = new aiVector3D[mesh->mNumVertices];\n\n std::copy(vertices.begin(), vertices.end(), mesh->mVertices);\n\n }\n aiVector3D ReadVertex()\n { \n aiVector3D vertex;\n vertex.x = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::x.c_str()), nullptr);\n vertex.y = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::y.c_str()), nullptr);\n vertex.z = ai_strtof>(xmlReader->getAttributeValue(D3MF::XmlTag::z.c_str()), nullptr);\n\n return vertex;\n }\n\n void ImportTriangles(aiMesh* mesh)\n {\n std::vector faces; \n\n\n while(ReadToEndElement(D3MF::XmlTag::triangles))\n {\n if(xmlReader->getNodeName() == D3MF::XmlTag::triangle)\n {\n faces.push_back(ReadTriangle());\n }\n }\n\n mesh->mNumFaces = static_cast(faces.size());\n mesh->mFaces = new aiFace[mesh->mNumFaces];\n mesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;\n\n\n std::copy(faces.begin(), faces.end(), mesh->mFaces);\n\n }\n\n aiFace ReadTriangle()\n {\n aiFace face;\n\n face.mNumIndices = 3;\n face.mIndices = new unsigned int[face.mNumIndices];\n face.mIndices[0] = static_cast(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v1.c_str())));\n face.mIndices[1] = static_cast(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v2.c_str())));\n face.mIndices[2] = static_cast(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v3.c_str())));\n\n return face;\n }\n\nprivate:\n\n bool ReadToStartElement(const std::string& startTag)\n {\n while(xmlReader->read())\n {\n if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT && xmlReader->getNodeName() == startTag)\n {\n return true;\n }\n else if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT_END &&\n xmlReader->getNodeName() == startTag)\n {\n return false;\n }\n }\n \/\/DefaultLogger::get()->error(\"unexpected EOF, expected closing <\" + closeTag + \"> tag\");\n return false;\n }\n\n bool ReadToEndElement(const std::string& closeTag)\n {\n while(xmlReader->read())\n {\n if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT) {\n return true;\n }\n else if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT_END\n && xmlReader->getNodeName() == closeTag)\n {\n return false;\n }\n }\n DefaultLogger::get()->error(\"unexpected EOF, expected closing <\" + closeTag + \"> tag\");\n return false;\n }\n\n\nprivate:\n std::vector meshes;\n XmlReader* xmlReader;\n\n\n};\n\n} \/\/namespace D3MF\n\n\nstatic const aiImporterDesc desc = {\n \"3mf Importer\",\n \"\",\n \"\",\n \"http:\/\/3mf.io\/\",\n aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_SupportCompressedFlavour,\n 0,\n 0,\n 0,\n 0,\n \"3mf\"\n};\n\n\nD3MFImporter::D3MFImporter()\n{\n\n}\n\nD3MFImporter::~D3MFImporter()\n{\n\n}\n\nbool D3MFImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool checkSig) const\n{ \n const std::string extension = GetExtension(pFile);\n\n if(extension == \"3mf\")\n {\n return true;\n }\n else if(!extension.length() || checkSig)\n {\n if(!pIOHandler)\n return true;\n }\n\n return false;\n}\n\nvoid D3MFImporter::SetupProperties(const Importer *pImp)\n{\n\n}\n\nconst aiImporterDesc *D3MFImporter::GetInfo() const\n{\n return &desc;\n}\n\nvoid D3MFImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler)\n{\n\n\n D3MF::D3MFOpcPackage opcPackage(pIOHandler, pFile);\n\n std::unique_ptr xmlStream(new CIrrXML_IOStreamReader(opcPackage.RootStream()));\n std::unique_ptr xmlReader(irr::io::createIrrXMLReader(xmlStream.get()));\n\n D3MF::XmlSerializer xmlSerializer(xmlReader.get());\n\n\n xmlSerializer.ImportXml(pScene);\n\n\n}\n\n}\n\n#endif \/\/ ASSIMP_BUILD_NO_3MF_IMPORTER\nFixed type in the assimp codebase (this is already fixed in more recent releases of assimp)\/*\nOpen Asset Import Library (assimp)\n----------------------------------------------------------------------\n\nCopyright (c) 2006-2016, assimp team\nAll rights reserved.\n\nRedistribution and use of this software in source and binary forms,\nwith or without modification, are permitted provided that the\nfollowing conditions are met:\n\n* Redistributions of source code must retain the above\n copyright notice, this list of conditions and the\n following disclaimer.\n\n* Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the\n following disclaimer in the documentation and\/or other\n materials provided with the distribution.\n\n* Neither the name of the assimp team, nor the names of its\n contributors may be used to endorse or promote products\n derived from this software without specific prior\n written permission of the assimp team.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n----------------------------------------------------------------------\n*\/\n\n#include \"D3MFImporter.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \"irrXMLWrapper.h\"\n#include \"StringComparison.h\"\n#include \"StringUtils.h\"\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"D3MFOpcPackage.h\"\n\n#ifndef ASSIMP_BUILD_NO_3MF_IMPORTER\n\nnamespace Assimp {\n\nnamespace D3MF {\n\n\nnamespace XmlTag {\n\n const std::string model = \"model\";\n const std::string metadata = \"metadata\";\n const std::string resources = \"resources\";\n const std::string object = \"object\";\n const std::string mesh = \"mesh\";\n const std::string vertices = \"vertices\";\n const std::string vertex = \"vertex\";\n const std::string triangles = \"triangles\";\n const std::string triangle = \"triangle\";\n const std::string x = \"x\";\n const std::string y = \"y\";\n const std::string z = \"z\";\n const std::string v1 = \"v1\";\n const std::string v2 = \"v2\";\n const std::string v3 = \"v3\";\n const std::string id = \"id\";\n const std::string name = \"name\";\n const std::string type = \"type\";\n const std::string build = \"build\";\n const std::string item = \"item\";\n const std::string objectid = \"objectid\";\n const std::string transform = \"transform\";\n\n}\n\n\nclass XmlSerializer\n{\npublic:\n XmlSerializer(XmlReader* xmlReader)\n : xmlReader(xmlReader)\n {\n\n }\n\n void ImportXml(aiScene* scene)\n {\n\n scene->mFlags |= AI_SCENE_FLAGS_NON_VERBOSE_FORMAT;\n\n scene->mRootNode = new aiNode();\n std::vector children;\n\n while(ReadToEndElement(D3MF::XmlTag::model))\n { \n\n if(xmlReader->getNodeName() == D3MF::XmlTag::object)\n {\n children.push_back(ReadObject(scene));\n }\n else if(xmlReader->getNodeName() == D3MF::XmlTag::build)\n {\n\n }\n } \n\n if(scene->mRootNode->mName.length == 0)\n scene->mRootNode->mName.Set(\"3MF\");\n\n\n scene->mNumMeshes = static_cast(meshes.size());\n scene->mMeshes = new aiMesh*[scene->mNumMeshes]();\n\n std::copy(meshes.begin(), meshes.end(), scene->mMeshes);\n\n scene->mRootNode->mNumChildren = static_cast(children.size());\n scene->mRootNode->mChildren = new aiNode*[scene->mRootNode->mNumChildren]();\n\n std::copy(children.begin(), children.end(), scene->mRootNode->mChildren);\n\n }\n\nprivate:\n aiNode* ReadObject(aiScene* scene)\n { \n ScopeGuard node(new aiNode());\n\n std::vector meshIds;\n\n int id = std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::id.c_str()));\n std::string name(xmlReader->getAttributeValue(D3MF::XmlTag::name.c_str()));\n std::string type(xmlReader->getAttributeValue(D3MF::XmlTag::type.c_str()));\n\n node->mParent = scene->mRootNode;\n node->mName.Set(name); \n\n unsigned long meshIdx = meshes.size();\n\n while(ReadToEndElement(D3MF::XmlTag::object))\n {\n if(xmlReader->getNodeName() == D3MF::XmlTag::mesh)\n { \n auto mesh = ReadMesh();\n\n mesh->mName.Set(name);\n meshes.push_back(mesh);\n meshIds.push_back(meshIdx);\n meshIdx++;\n\n }\n }\n\n node->mNumMeshes = static_cast(meshIds.size());\n\n node->mMeshes = new unsigned int[node->mNumMeshes];\n\n std::copy(meshIds.begin(), meshIds.end(), node->mMeshes);\n\n return node.dismiss();\n\n }\n\n aiMesh* ReadMesh()\n {\n aiMesh* mesh = new aiMesh();\n\n while(ReadToEndElement(D3MF::XmlTag::mesh))\n { \n if(xmlReader->getNodeName() == D3MF::XmlTag::vertices)\n {\n ImportVertices(mesh);\n }\n else if(xmlReader->getNodeName() == D3MF::XmlTag::triangles)\n {\n ImportTriangles(mesh);\n }\n\n }\n\n\n return mesh;\n }\n\n void ImportVertices(aiMesh* mesh)\n {\n std::vector vertices; \n\n while(ReadToEndElement(D3MF::XmlTag::vertices))\n { \n if(xmlReader->getNodeName() == D3MF::XmlTag::vertex)\n { \n vertices.push_back(ReadVertex());\n }\n }\n mesh->mNumVertices = static_cast(vertices.size());\n mesh->mVertices = new aiVector3D[mesh->mNumVertices];\n\n std::copy(vertices.begin(), vertices.end(), mesh->mVertices);\n\n }\n aiVector3D ReadVertex()\n { \n aiVector3D vertex;\n vertex.x = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::x.c_str()), nullptr);\n vertex.y = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::y.c_str()), nullptr);\n vertex.z = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::z.c_str()), nullptr);\n\n return vertex;\n }\n\n void ImportTriangles(aiMesh* mesh)\n {\n std::vector faces; \n\n\n while(ReadToEndElement(D3MF::XmlTag::triangles))\n {\n if(xmlReader->getNodeName() == D3MF::XmlTag::triangle)\n {\n faces.push_back(ReadTriangle());\n }\n }\n\n mesh->mNumFaces = static_cast(faces.size());\n mesh->mFaces = new aiFace[mesh->mNumFaces];\n mesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;\n\n\n std::copy(faces.begin(), faces.end(), mesh->mFaces);\n\n }\n\n aiFace ReadTriangle()\n {\n aiFace face;\n\n face.mNumIndices = 3;\n face.mIndices = new unsigned int[face.mNumIndices];\n face.mIndices[0] = static_cast(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v1.c_str())));\n face.mIndices[1] = static_cast(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v2.c_str())));\n face.mIndices[2] = static_cast(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v3.c_str())));\n\n return face;\n }\n\nprivate:\n\n bool ReadToStartElement(const std::string& startTag)\n {\n while(xmlReader->read())\n {\n if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT && xmlReader->getNodeName() == startTag)\n {\n return true;\n }\n else if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT_END &&\n xmlReader->getNodeName() == startTag)\n {\n return false;\n }\n }\n \/\/DefaultLogger::get()->error(\"unexpected EOF, expected closing <\" + closeTag + \"> tag\");\n return false;\n }\n\n bool ReadToEndElement(const std::string& closeTag)\n {\n while(xmlReader->read())\n {\n if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT) {\n return true;\n }\n else if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT_END\n && xmlReader->getNodeName() == closeTag)\n {\n return false;\n }\n }\n DefaultLogger::get()->error(\"unexpected EOF, expected closing <\" + closeTag + \"> tag\");\n return false;\n }\n\n\nprivate:\n std::vector meshes;\n XmlReader* xmlReader;\n\n\n};\n\n} \/\/namespace D3MF\n\n\nstatic const aiImporterDesc desc = {\n \"3mf Importer\",\n \"\",\n \"\",\n \"http:\/\/3mf.io\/\",\n aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_SupportCompressedFlavour,\n 0,\n 0,\n 0,\n 0,\n \"3mf\"\n};\n\n\nD3MFImporter::D3MFImporter()\n{\n\n}\n\nD3MFImporter::~D3MFImporter()\n{\n\n}\n\nbool D3MFImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool checkSig) const\n{ \n const std::string extension = GetExtension(pFile);\n\n if(extension == \"3mf\")\n {\n return true;\n }\n else if(!extension.length() || checkSig)\n {\n if(!pIOHandler)\n return true;\n }\n\n return false;\n}\n\nvoid D3MFImporter::SetupProperties(const Importer *pImp)\n{\n\n}\n\nconst aiImporterDesc *D3MFImporter::GetInfo() const\n{\n return &desc;\n}\n\nvoid D3MFImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler)\n{\n\n\n D3MF::D3MFOpcPackage opcPackage(pIOHandler, pFile);\n\n std::unique_ptr xmlStream(new CIrrXML_IOStreamReader(opcPackage.RootStream()));\n std::unique_ptr xmlReader(irr::io::createIrrXMLReader(xmlStream.get()));\n\n D3MF::XmlSerializer xmlSerializer(xmlReader.get());\n\n\n xmlSerializer.ImportXml(pScene);\n\n\n}\n\n}\n\n#endif \/\/ ASSIMP_BUILD_NO_3MF_IMPORTER\n<|endoftext|>"} {"text":"\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * .\n *\n * $ Id: $\n *\n *\n * @author David N. Bertoni<\/a>\n *\/\n#include \"StdBinInputStream.hpp\"\n\n\n\n#include \n\n#if !defined(XALAN_OLD_STREAMS)\n#if defined(XALAN_OLD_STREAM_HEADERS)\n#include \n#else\n#include \n#endif\n#endif\n\n\n\n#if defined(XALAN_NO_NAMESPACES)\nStdBinInputStream::StdBinInputStream(istream&\t\ttheStream) :\n#else\nStdBinInputStream::StdBinInputStream(std::istream&\ttheStream) :\n#endif\n\tBinInputStream(),\n\tm_stream(theStream)\n{\n}\n\n\n\nStdBinInputStream::~StdBinInputStream()\n{\n}\n\n\n\nunsigned int\nStdBinInputStream::curPos() const\n{\n\treturn m_stream.tellg();\n}\n\n\n\nunsigned int\nStdBinInputStream::readBytes(\n\t\t\tXMLByte* const toFill,\n\t\t\tconst unsigned int\tmaxToRead)\n{\n\tassert(sizeof(XMLByte) == sizeof(char));\n\n\tif (!m_stream)\n\t{\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\tunsigned int\ti = 0;\n\n\t\twhile(i < maxToRead)\n\t\t{\n\t\t\tconst int\tch = m_stream.get();\n\n\t\t\tif (ch == EOF)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ttoFill[i] = XMLByte(ch);\n\n\t\t\t\t++i;\n\t\t\t}\n\t\t}\n\n\t\treturn i;\n\t}\n}\nRead bytes from the stream all at once.\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * .\n *\n * $ Id: $\n *\n *\n * @author David N. Bertoni<\/a>\n *\/\n#include \"StdBinInputStream.hpp\"\n\n\n\n#include \n\n#if !defined(XALAN_OLD_STREAMS)\n#if defined(XALAN_OLD_STREAM_HEADERS)\n#include \n#else\n#include \n#endif\n#endif\n\n\n\n#if defined(XALAN_NO_NAMESPACES)\nStdBinInputStream::StdBinInputStream(istream&\t\ttheStream) :\n#else\nStdBinInputStream::StdBinInputStream(std::istream&\ttheStream) :\n#endif\n\tBinInputStream(),\n\tm_stream(theStream)\n{\n}\n\n\n\nStdBinInputStream::~StdBinInputStream()\n{\n}\n\n\n\nunsigned int\nStdBinInputStream::curPos() const\n{\n\treturn m_stream.tellg();\n}\n\n\n\nunsigned int\nStdBinInputStream::readBytes(\n\t\t\tXMLByte* const toFill,\n\t\t\tconst unsigned int\tmaxToRead)\n{\n\tassert(sizeof(XMLByte) == sizeof(char));\n\n\tif (!m_stream)\n\t{\n\t\treturn 0;\n\t}\n\telse\n\t{\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\treturn m_stream.readsome((char*)toFill, maxToRead);\n#else\n\t\treturn m_stream.readsome(reinterpret_cast(toFill), maxToRead);\n#endif\n\t}\n}\n<|endoftext|>"} {"text":"\/*\n * mitkFiberBundleMapper2D.cpp\n * mitk-all\n *\n * Created by HAL9000 on 1\/17\/11.\n * Copyright 2011 __MyCompanyName__. All rights reserved.\n *\n *\/\n\n#include \"mitkFiberBundleXMapper2D.h\"\n#include \n\n\n#include \n#include \n#include \n#include \n\/\/#include \n\n\/\/#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\nmitk::FiberBundleXMapper2D::FiberBundleXMapper2D()\n{\n m_lut = vtkLookupTable::New();\n m_lut->Build();\n\n}\n\nmitk::FiberBundleXMapper2D::~FiberBundleXMapper2D()\n{\n}\n\n\nmitk::FiberBundleX* mitk::FiberBundleXMapper2D::GetInput()\n{\n return dynamic_cast< mitk::FiberBundleX * > ( GetData() );\n}\n\n\n\nvoid mitk::FiberBundleXMapper2D::Update(mitk::BaseRenderer * renderer)\n{\n\n if ( !this->IsVisible( renderer ) )\n {\n return;\n }\n\n MITK_INFO << \"MapperFBX 2D update: \";\n \/\/ Calculate time step of the input data for the specified renderer (integer value)\n \/\/ this method is implemented in mitkMapper\n this->CalculateTimeStep( renderer );\n\n \/\/check if updates occured in the node or on the display\n FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);\n const DataNode *node = this->GetDataNode();\n if ( (localStorage->m_LastUpdateTime < node->GetMTime())\n || (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) \/\/was a property modified?\n || (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) )\n {\n \/\/ MITK_INFO << \"UPDATE NEEDED FOR _ \" << renderer->GetName();\n this->GenerateDataForRenderer( renderer );\n }\n\n if ((localStorage->m_LastUpdateTime < renderer->GetDisplayGeometry()->GetMTime()) ) \/\/was the display geometry modified? e.g. zooming, panning)\n {\n\n this->UpdateShaderParameter(renderer);\n\n }\n\n}\n\nvoid mitk::FiberBundleXMapper2D::UpdateShaderParameter(mitk::BaseRenderer * renderer)\n{\n FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);\n\n \/\/get information about current position of views\n mitk::SliceNavigationController::Pointer sliceContr = renderer->GetSliceNavigationController();\n mitk::PlaneGeometry::ConstPointer planeGeo = sliceContr->GetCurrentPlaneGeometry();\n\n \/\/generate according cutting planes based on the view position\n float sliceN[3], planeOrigin[3];\n\n\n \/\/ since shader uses camera coordinates, transform origin and normal from worldcoordinates to cameracoordinates\n\n\n planeOrigin[0] = (float) planeGeo->GetOrigin()[0];\n planeOrigin[1] = (float) planeGeo->GetOrigin()[1];\n planeOrigin[2] = (float) planeGeo->GetOrigin()[2];\n\n sliceN[0] = planeGeo->GetNormal()[0];\n sliceN[1] = planeGeo->GetNormal()[1];\n sliceN[2] = planeGeo->GetNormal()[2];\n\n\n float tmp1 = planeOrigin[0] * sliceN[0];\n float tmp2 = planeOrigin[1] * sliceN[1];\n float tmp3 = planeOrigin[2] * sliceN[2];\n float d1 = tmp1 + tmp2 + tmp3; \/\/attention, correct normalvector\n\n\n float plane1[4];\n plane1[0] = sliceN[0];\n plane1[1] = sliceN[1];\n plane1[2] = sliceN[2];\n plane1[3] = d1;\n\n float thickness = 2.0;\n if(!this->GetDataNode()->GetPropertyValue(\"Fiber2DSliceThickness\",thickness))\n MITK_INFO << \"FIBER2D SLICE THICKNESS PROPERTY ERROR\";\n\n\n bool fiberfading = false;\n if(!this->GetDataNode()->GetPropertyValue(\"Fiber2DfadeEFX\",fiberfading))\n MITK_INFO << \"FIBER2D SLICE FADE EFX PROPERTY ERROR\";\n\n\n int fiberfading_i = 1;\n if (!fiberfading)\n fiberfading_i = 0;\n\n \/\/ set Opacity\n float fiberOpacity;\n this->GetDataNode()->GetOpacity(fiberOpacity, NULL);\n\n localStorage->m_PointActor->GetProperty()->AddShaderVariable(\"slicingPlane\",4, plane1);\n localStorage->m_PointActor->GetProperty()->AddShaderVariable(\"fiberThickness\",1, &thickness);\n localStorage->m_PointActor->GetProperty()->AddShaderVariable(\"fiberFadingON\",1, &fiberfading_i);\n localStorage->m_PointActor->GetProperty()->AddShaderVariable(\"fiberOpacity\", 1, &fiberOpacity);\n\n\n}\n\n\/\/ ALL RAW DATA FOR VISUALIZATION IS GENERATED HERE.\n\/\/ vtkActors and Mappers are feeded here\nvoid mitk::FiberBundleXMapper2D::GenerateDataForRenderer(mitk::BaseRenderer *renderer)\n{\n\n \/\/the handler of local storage gets feeded in this method with requested data for related renderwindow\n FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);\n\n \/\/this procedure is depricated,\n \/\/not needed after initializaton anymore\n mitk::DataNode* node = this->GetDataNode();\n if ( node == NULL )\n {\n MITK_INFO << \"check DATANODE: ....[Fail] \";\n return;\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/\/THIS GET INPUT\n mitk::FiberBundleX* fbx = this->GetInput();\n\n localStorage->m_PointMapper->ScalarVisibilityOn();\n localStorage->m_PointMapper->SetScalarModeToUsePointFieldData();\n localStorage->m_PointMapper->SetLookupTable(m_lut); \/\/apply the properties after the slice was set\n localStorage->m_PointActor->GetProperty()->SetOpacity(0.999);\n\n \/\/ set color\n if (fbx->GetCurrentColorCoding() != NULL){\n\/\/ localStorage->m_PointMapper->SelectColorArray(\"\");\n localStorage->m_PointMapper->SelectColorArray(fbx->GetCurrentColorCoding());\n MITK_DEBUG << \"MapperFBX 2D: \" << fbx->GetCurrentColorCoding();\n\n if(fbx->GetCurrentColorCoding() == fbx->COLORCODING_CUSTOM){\n float temprgb[3];\n this->GetDataNode()->GetColor( temprgb, NULL );\n double trgb[3] = { (double) temprgb[0], (double) temprgb[1], (double) temprgb[2] };\n localStorage->m_PointActor->GetProperty()->SetColor(trgb);\n }\n }\n\n\n\n localStorage->m_PointMapper->SetInput(fbx->GetFiberPolyData());\n localStorage->m_PointActor->SetMapper(localStorage->m_PointMapper);\n localStorage->m_PointActor->GetProperty()->ShadingOn();\n\n \/\/ Applying shading properties\n {\n mitk::ShaderRepository::GetGlobalShaderRepository()->ApplyProperties(this->GetDataNode(),localStorage->m_PointActor,renderer, localStorage->m_LastUpdateTime);\n }\n\n\n\n this->UpdateShaderParameter(renderer);\n\n\n \/\/ We have been modified => save this for next Update()\n localStorage->m_LastUpdateTime.Modified();\n\n\n}\n\n\nvtkProp* mitk::FiberBundleXMapper2D::GetVtkProp(mitk::BaseRenderer *renderer)\n{\n\n \/\/MITK_INFO << \"FiberBundleMapper2D GetVtkProp(renderer)\";\n this->Update(renderer);\n return m_LSH.GetLocalStorage(renderer)->m_PointActor;\n\n}\n\n\nvoid mitk::FiberBundleXMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite)\n{ \/\/add shader to datano\n\n\n \/\/####### load shader from file #########\n QString applicationDir = QCoreApplication::applicationDirPath();\n\n if (applicationDir.endsWith(\"bin\"))\n applicationDir.append(\"\/\");\n else if (applicationDir.endsWith(\"MacOS\"))\n {\n \/\/on osx, check if path for installer or MITK development is needed\n applicationDir.append(\"\/\");\n QFile f( applicationDir+\"FiberTrackingLUTBaryCoords.bin\" );\n if( !f.exists() ) \/\/ if file does not exist, then look in MITK development build directory\n applicationDir.append(\"..\/..\/..\/\");\n }else\n applicationDir.append(\"\\\\..\\\\\");\n\n mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch( applicationDir.toStdString().c_str(), false );\n mitk::ShaderRepository::Pointer shaderRepository = mitk::ShaderRepository::GetGlobalShaderRepository();\n shaderRepository->LoadShader(mitk::StandardFileLocations::GetInstance()->FindFile(\"mitkShaderFiberClipping.xml\"));\n\n\n\n \/\/####################################################################\n node->SetProperty(\"shader\",mitk::ShaderProperty::New(\"mitkShaderFiberClipping\"));\n mitk::ShaderRepository::GetGlobalShaderRepository()->AddDefaultProperties(node,renderer,overwrite);\n\n\n \/\/add other parameters to propertylist\n node->AddProperty( \"Fiber2DSliceThickness\", mitk::FloatProperty::New(2.0f), renderer, overwrite );\n node->AddProperty( \"Fiber2DfadeEFX\", mitk::BoolProperty::New(true), renderer, overwrite );\n\n\n Superclass::SetDefaultProperties(node, renderer, overwrite);\n}\n\n\n\n\n\n\/\/ following methods are essential, they actually call the GetVtkProp() method\n\/\/ which returns the desired actors\nvoid mitk::FiberBundleXMapper2D::MitkRenderOverlay(BaseRenderer* renderer)\n{\n \/\/ MITK_INFO << \"FiberBundleMapper2D MitkRenderOVerlay(renderer)\";\n if ( this->IsVisible(renderer)==false )\n return;\n\n if ( this->GetVtkProp(renderer)->GetVisibility() )\n {\n this->GetVtkProp(renderer)->RenderOverlay(renderer->GetVtkRenderer());\n }\n}\n\nvoid mitk::FiberBundleXMapper2D::MitkRenderOpaqueGeometry(BaseRenderer* renderer)\n{\n \/\/ MITK_INFO << \"FiberBundleMapper2D MitkRenderOpaqueGeometry(renderer)\";\n if ( this->IsVisible( renderer )==false )\n return;\n\n if ( this->GetVtkProp(renderer)->GetVisibility() )\n this->GetVtkProp(renderer)->RenderOpaqueGeometry( renderer->GetVtkRenderer() );\n}\nvoid mitk::FiberBundleXMapper2D::MitkRenderTranslucentGeometry(BaseRenderer* renderer)\n{\n \/\/ MITK_INFO << \"FiberBundleMapper2D MitkRenderTranslucentGeometry(renderer)\";\n if ( this->IsVisible(renderer)==false )\n return;\n\n \/\/TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer???\n if ( this->GetVtkProp(renderer)->GetVisibility() )\n this->GetVtkProp(renderer)->RenderTranslucentPolygonalGeometry(renderer->GetVtkRenderer());\n\n}\nvoid mitk::FiberBundleXMapper2D::MitkRenderVolumetricGeometry(BaseRenderer* renderer)\n{\n \/\/ MITK_INFO << \"FiberBundleMapper2D MitkRenderVolumentricGeometry(renderer)\";\n if(IsVisible(renderer)==false)\n return;\n\n \/\/TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer???\n if ( GetVtkProp(renderer)->GetVisibility() )\n this->GetVtkProp(renderer)->RenderVolumetricGeometry(renderer->GetVtkRenderer());\n\n}\n\nmitk::FiberBundleXMapper2D::FBXLocalStorage::FBXLocalStorage()\n{\n m_PointActor = vtkSmartPointer::New();\n m_PointMapper = vtkSmartPointer::New();\n\n}\nMissed output in a separate branch\/*\n * mitkFiberBundleMapper2D.cpp\n * mitk-all\n *\n * Created by HAL9000 on 1\/17\/11.\n * Copyright 2011 __MyCompanyName__. All rights reserved.\n *\n *\/\n\n#include \"mitkFiberBundleXMapper2D.h\"\n#include \n\n\n#include \n#include \n#include \n#include \n\/\/#include \n\n\/\/#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\nmitk::FiberBundleXMapper2D::FiberBundleXMapper2D()\n{\n m_lut = vtkLookupTable::New();\n m_lut->Build();\n\n}\n\nmitk::FiberBundleXMapper2D::~FiberBundleXMapper2D()\n{\n}\n\n\nmitk::FiberBundleX* mitk::FiberBundleXMapper2D::GetInput()\n{\n return dynamic_cast< mitk::FiberBundleX * > ( GetData() );\n}\n\n\n\nvoid mitk::FiberBundleXMapper2D::Update(mitk::BaseRenderer * renderer)\n{\n\n if ( !this->IsVisible( renderer ) )\n {\n return;\n }\n\n MITK_DEBUG << \"MapperFBX 2D update: \";\n \/\/ Calculate time step of the input data for the specified renderer (integer value)\n \/\/ this method is implemented in mitkMapper\n this->CalculateTimeStep( renderer );\n\n \/\/check if updates occured in the node or on the display\n FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);\n const DataNode *node = this->GetDataNode();\n if ( (localStorage->m_LastUpdateTime < node->GetMTime())\n || (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) \/\/was a property modified?\n || (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) )\n {\n \/\/ MITK_INFO << \"UPDATE NEEDED FOR _ \" << renderer->GetName();\n this->GenerateDataForRenderer( renderer );\n }\n\n if ((localStorage->m_LastUpdateTime < renderer->GetDisplayGeometry()->GetMTime()) ) \/\/was the display geometry modified? e.g. zooming, panning)\n {\n\n this->UpdateShaderParameter(renderer);\n\n }\n\n}\n\nvoid mitk::FiberBundleXMapper2D::UpdateShaderParameter(mitk::BaseRenderer * renderer)\n{\n FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);\n\n \/\/get information about current position of views\n mitk::SliceNavigationController::Pointer sliceContr = renderer->GetSliceNavigationController();\n mitk::PlaneGeometry::ConstPointer planeGeo = sliceContr->GetCurrentPlaneGeometry();\n\n \/\/generate according cutting planes based on the view position\n float sliceN[3], planeOrigin[3];\n\n\n \/\/ since shader uses camera coordinates, transform origin and normal from worldcoordinates to cameracoordinates\n\n\n planeOrigin[0] = (float) planeGeo->GetOrigin()[0];\n planeOrigin[1] = (float) planeGeo->GetOrigin()[1];\n planeOrigin[2] = (float) planeGeo->GetOrigin()[2];\n\n sliceN[0] = planeGeo->GetNormal()[0];\n sliceN[1] = planeGeo->GetNormal()[1];\n sliceN[2] = planeGeo->GetNormal()[2];\n\n\n float tmp1 = planeOrigin[0] * sliceN[0];\n float tmp2 = planeOrigin[1] * sliceN[1];\n float tmp3 = planeOrigin[2] * sliceN[2];\n float d1 = tmp1 + tmp2 + tmp3; \/\/attention, correct normalvector\n\n\n float plane1[4];\n plane1[0] = sliceN[0];\n plane1[1] = sliceN[1];\n plane1[2] = sliceN[2];\n plane1[3] = d1;\n\n float thickness = 2.0;\n if(!this->GetDataNode()->GetPropertyValue(\"Fiber2DSliceThickness\",thickness))\n MITK_INFO << \"FIBER2D SLICE THICKNESS PROPERTY ERROR\";\n\n\n bool fiberfading = false;\n if(!this->GetDataNode()->GetPropertyValue(\"Fiber2DfadeEFX\",fiberfading))\n MITK_INFO << \"FIBER2D SLICE FADE EFX PROPERTY ERROR\";\n\n\n int fiberfading_i = 1;\n if (!fiberfading)\n fiberfading_i = 0;\n\n \/\/ set Opacity\n float fiberOpacity;\n this->GetDataNode()->GetOpacity(fiberOpacity, NULL);\n\n localStorage->m_PointActor->GetProperty()->AddShaderVariable(\"slicingPlane\",4, plane1);\n localStorage->m_PointActor->GetProperty()->AddShaderVariable(\"fiberThickness\",1, &thickness);\n localStorage->m_PointActor->GetProperty()->AddShaderVariable(\"fiberFadingON\",1, &fiberfading_i);\n localStorage->m_PointActor->GetProperty()->AddShaderVariable(\"fiberOpacity\", 1, &fiberOpacity);\n\n\n}\n\n\/\/ ALL RAW DATA FOR VISUALIZATION IS GENERATED HERE.\n\/\/ vtkActors and Mappers are feeded here\nvoid mitk::FiberBundleXMapper2D::GenerateDataForRenderer(mitk::BaseRenderer *renderer)\n{\n\n \/\/the handler of local storage gets feeded in this method with requested data for related renderwindow\n FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);\n\n \/\/this procedure is depricated,\n \/\/not needed after initializaton anymore\n mitk::DataNode* node = this->GetDataNode();\n if ( node == NULL )\n {\n MITK_INFO << \"check DATANODE: ....[Fail] \";\n return;\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/\/THIS GET INPUT\n mitk::FiberBundleX* fbx = this->GetInput();\n\n localStorage->m_PointMapper->ScalarVisibilityOn();\n localStorage->m_PointMapper->SetScalarModeToUsePointFieldData();\n localStorage->m_PointMapper->SetLookupTable(m_lut); \/\/apply the properties after the slice was set\n localStorage->m_PointActor->GetProperty()->SetOpacity(0.999);\n\n \/\/ set color\n if (fbx->GetCurrentColorCoding() != NULL){\n\/\/ localStorage->m_PointMapper->SelectColorArray(\"\");\n localStorage->m_PointMapper->SelectColorArray(fbx->GetCurrentColorCoding());\n MITK_DEBUG << \"MapperFBX 2D: \" << fbx->GetCurrentColorCoding();\n\n if(fbx->GetCurrentColorCoding() == fbx->COLORCODING_CUSTOM){\n float temprgb[3];\n this->GetDataNode()->GetColor( temprgb, NULL );\n double trgb[3] = { (double) temprgb[0], (double) temprgb[1], (double) temprgb[2] };\n localStorage->m_PointActor->GetProperty()->SetColor(trgb);\n }\n }\n\n\n\n localStorage->m_PointMapper->SetInput(fbx->GetFiberPolyData());\n localStorage->m_PointActor->SetMapper(localStorage->m_PointMapper);\n localStorage->m_PointActor->GetProperty()->ShadingOn();\n\n \/\/ Applying shading properties\n {\n mitk::ShaderRepository::GetGlobalShaderRepository()->ApplyProperties(this->GetDataNode(),localStorage->m_PointActor,renderer, localStorage->m_LastUpdateTime);\n }\n\n\n\n this->UpdateShaderParameter(renderer);\n\n\n \/\/ We have been modified => save this for next Update()\n localStorage->m_LastUpdateTime.Modified();\n\n\n}\n\n\nvtkProp* mitk::FiberBundleXMapper2D::GetVtkProp(mitk::BaseRenderer *renderer)\n{\n\n \/\/MITK_INFO << \"FiberBundleMapper2D GetVtkProp(renderer)\";\n this->Update(renderer);\n return m_LSH.GetLocalStorage(renderer)->m_PointActor;\n\n}\n\n\nvoid mitk::FiberBundleXMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite)\n{ \/\/add shader to datano\n\n\n \/\/####### load shader from file #########\n QString applicationDir = QCoreApplication::applicationDirPath();\n\n if (applicationDir.endsWith(\"bin\"))\n applicationDir.append(\"\/\");\n else if (applicationDir.endsWith(\"MacOS\"))\n {\n \/\/on osx, check if path for installer or MITK development is needed\n applicationDir.append(\"\/\");\n QFile f( applicationDir+\"FiberTrackingLUTBaryCoords.bin\" );\n if( !f.exists() ) \/\/ if file does not exist, then look in MITK development build directory\n applicationDir.append(\"..\/..\/..\/\");\n }else\n applicationDir.append(\"\\\\..\\\\\");\n\n mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch( applicationDir.toStdString().c_str(), false );\n mitk::ShaderRepository::Pointer shaderRepository = mitk::ShaderRepository::GetGlobalShaderRepository();\n shaderRepository->LoadShader(mitk::StandardFileLocations::GetInstance()->FindFile(\"mitkShaderFiberClipping.xml\"));\n\n\n\n \/\/####################################################################\n node->SetProperty(\"shader\",mitk::ShaderProperty::New(\"mitkShaderFiberClipping\"));\n mitk::ShaderRepository::GetGlobalShaderRepository()->AddDefaultProperties(node,renderer,overwrite);\n\n\n \/\/add other parameters to propertylist\n node->AddProperty( \"Fiber2DSliceThickness\", mitk::FloatProperty::New(2.0f), renderer, overwrite );\n node->AddProperty( \"Fiber2DfadeEFX\", mitk::BoolProperty::New(true), renderer, overwrite );\n\n\n Superclass::SetDefaultProperties(node, renderer, overwrite);\n}\n\n\n\n\n\n\/\/ following methods are essential, they actually call the GetVtkProp() method\n\/\/ which returns the desired actors\nvoid mitk::FiberBundleXMapper2D::MitkRenderOverlay(BaseRenderer* renderer)\n{\n \/\/ MITK_INFO << \"FiberBundleMapper2D MitkRenderOVerlay(renderer)\";\n if ( this->IsVisible(renderer)==false )\n return;\n\n if ( this->GetVtkProp(renderer)->GetVisibility() )\n {\n this->GetVtkProp(renderer)->RenderOverlay(renderer->GetVtkRenderer());\n }\n}\n\nvoid mitk::FiberBundleXMapper2D::MitkRenderOpaqueGeometry(BaseRenderer* renderer)\n{\n \/\/ MITK_INFO << \"FiberBundleMapper2D MitkRenderOpaqueGeometry(renderer)\";\n if ( this->IsVisible( renderer )==false )\n return;\n\n if ( this->GetVtkProp(renderer)->GetVisibility() )\n this->GetVtkProp(renderer)->RenderOpaqueGeometry( renderer->GetVtkRenderer() );\n}\nvoid mitk::FiberBundleXMapper2D::MitkRenderTranslucentGeometry(BaseRenderer* renderer)\n{\n \/\/ MITK_INFO << \"FiberBundleMapper2D MitkRenderTranslucentGeometry(renderer)\";\n if ( this->IsVisible(renderer)==false )\n return;\n\n \/\/TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer???\n if ( this->GetVtkProp(renderer)->GetVisibility() )\n this->GetVtkProp(renderer)->RenderTranslucentPolygonalGeometry(renderer->GetVtkRenderer());\n\n}\nvoid mitk::FiberBundleXMapper2D::MitkRenderVolumetricGeometry(BaseRenderer* renderer)\n{\n \/\/ MITK_INFO << \"FiberBundleMapper2D MitkRenderVolumentricGeometry(renderer)\";\n if(IsVisible(renderer)==false)\n return;\n\n \/\/TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer???\n if ( GetVtkProp(renderer)->GetVisibility() )\n this->GetVtkProp(renderer)->RenderVolumetricGeometry(renderer->GetVtkRenderer());\n\n}\n\nmitk::FiberBundleXMapper2D::FBXLocalStorage::FBXLocalStorage()\n{\n m_PointActor = vtkSmartPointer::New();\n m_PointMapper = vtkSmartPointer::New();\n\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ RemotePhotoTool - remote camera control software\n\/\/ Copyright (C) 2008-2014 Michael Fink\n\/\/\n\/\/\/ \\file CmdlineApp.cpp Command line app\n\/\/\n\n\/\/ includes\n#include \"stdafx.h\"\n#include \"CmdlineApp.hpp\"\n#include \"Exception.hpp\"\n#include \"CameraException.hpp\"\n#include \"AppCommand.hpp\"\n#include \"AppOptions.hpp\"\n#include \"Event.hpp\"\n#include \"CameraScriptProcessor.hpp\"\n#include \"Instance.hpp\"\n#include \"SourceInfo.hpp\"\n#include \"SourceDevice.hpp\"\n#include \"RemoteReleaseControl.hpp\"\n#include \"ShutterReleaseSettings.hpp\"\n#include \"Filesystem.hpp\"\n#include \"CrashReporter.hpp\"\n#include \"..\\version.h\"\n#include \n\nCmdlineApp::CmdlineApp()\n{\n _tprintf(_T(\"RemotePhotoTool Command-Line %s\\n%s\\n\\n\"),\n _T(VERSIONINFO_FILEVERSION_DISPLAYSTRING),\n _T(VERSIONINFO_COPYRIGHT));\n}\n\nvoid CmdlineApp::InitCrashReporter()\n{\n CString cszFolder = App_GetAppDataFolder(appDataUserNonRoaming) + _T(\"\\\\RemotePhotoToolCmdline\\\\\");\n\n if (!Directory_Exists(cszFolder))\n CreateDirectory(cszFolder, NULL);\n\n cszFolder += _T(\"crashdumps\\\\\");\n\n if (!Directory_Exists(cszFolder))\n CreateDirectory(cszFolder, NULL);\n\n CrashReporter::Init(cszFolder);\n}\n\nvoid CmdlineApp::Run(int argc, TCHAR* argv[])\n{\n \/\/ parse options\n AppOptions options(m_vecCommandList);\n options.Parse(argc, argv);\n\n if (m_vecCommandList.empty())\n {\n options.OutputHelp();\n return;\n }\n\n if (options.IsSelectedHelpOption())\n return;\n\n \/\/ run command list\n std::for_each(m_vecCommandList.begin(), m_vecCommandList.end(), [&](const AppCommand& cmd)\n {\n try\n {\n Exec(cmd);\n }\n catch(const CameraException& ex)\n {\n _tprintf(_T(\"CameraException was thrown: \\\"%s\\\"\\n\"), ex.Message().GetString());\n }\n catch(const Exception& ex)\n {\n _tprintf(_T(\"Exception was thrown: \\\"%s\\\"\\n\"), ex.Message().GetString());\n }\n });\n}\n\nvoid CmdlineApp::Exec(const AppCommand& cmd)\n{\n switch (cmd.m_enCommand)\n {\n case AppCommand::showVersion: PrintVersionInfo(); break;\n case AppCommand::listDevices: ListDevices(); break;\n case AppCommand::openDevice: OpenByName(cmd.m_cszData); break;\n case AppCommand::closeDevice:\n m_spSourceDevice.reset();\n m_spReleaseControl.reset();\n break;\n case AppCommand::deviceInfo: OutputDeviceInfo(); break;\n case AppCommand::deviceProperties: ListDeviceProperties(); break;\n case AppCommand::imageProperties: ListImageProperties(); break;\n case AppCommand::listenEvents: ListenToEvents(); break;\n case AppCommand::releaseShutter: ReleaseShutter(); break;\n case AppCommand::runScript: RunScript(cmd.m_cszData); break;\n default:\n ATLASSERT(false);\n break;\n }\n}\n\nvoid CmdlineApp::PrintVersionInfo()\n{\n _tprintf(_T(\"CanonControl version info\\n\\n\"));\n\n Instance inst = Instance::Get();\n\n CString cszVersionInfo = inst.Version();\n\n _tprintf(_T(\"%s\\n\"), cszVersionInfo.GetString());\n}\n\nvoid CmdlineApp::ListDevices()\n{\n _tprintf(_T(\"Devices list\\n\"));\n\n Instance inst = Instance::Get();\n\n std::vector> vecSourceDevices;\n inst.EnumerateDevices(vecSourceDevices);\n\n if (vecSourceDevices.empty())\n {\n _tprintf(_T(\"No device found.\\n\"));\n }\n else\n {\n for (size_t i=0,iMax=vecSourceDevices.size(); i spSourceInfo = vecSourceDevices[i];\n _tprintf(_T(\"Device %lu: \\\"%s\\\"\\n\"), i+1, spSourceInfo->Name().GetString());\n }\n }\n\n _tprintf(_T(\"\\n\"));\n}\n\nvoid CmdlineApp::OpenByName(const CString& cszName)\n{\n Instance inst = Instance::Get();\n\n std::vector> vecSourceDevices;\n inst.EnumerateDevices(vecSourceDevices);\n\n int iPosOpen = cszName.Find(_T('{'));\n int iPosClose = cszName.Find(_T('}'), iPosOpen + 1);\n if (iPosOpen != -1 && iPosClose != -1)\n {\n CString cszIndex = cszName.Mid(iPosOpen + 1, iPosClose - iPosOpen - 1);\n\n size_t iIndex = _tcstoul(cszIndex, nullptr, 10);\n\n if (iIndex >= vecSourceDevices.size())\n throw Exception(_T(\"Invalid index for camera\"), __FILE__, __LINE__);\n\n std::shared_ptr spSourceInfo = vecSourceDevices[iIndex];\n\n _tprintf(_T(\"Opening camera: %s\\n\"), spSourceInfo->Name().GetString());\n\n m_spSourceDevice = spSourceInfo->Open();\n return;\n }\n\n for (size_t i=0,iMax=vecSourceDevices.size(); i spSourceInfo = vecSourceDevices[i];\n if (spSourceInfo->Name() == cszName)\n {\n _tprintf(_T(\"Opening camera: %s\\n\"), spSourceInfo->Name().GetString());\n\n m_spSourceDevice = spSourceInfo->Open();\n return;\n }\n }\n\n throw Exception(_T(\"Couldn't find camera model: \") + cszName, __FILE__, __LINE__);\n}\n\nvoid CmdlineApp::OutputDeviceInfo()\n{\n _tprintf(_T(\"Device info about \\\"%s\\\"\\n\"), m_spSourceDevice->ModelName().GetString());\n _tprintf(_T(\"Serial number \\\"%s\\\"\\n\"), m_spSourceDevice->SerialNumber().GetString());\n\n \/\/ output capabilities\n _tprintf(_T(\"Device capabilities\\n\"));\n bool bCanRelease = m_spSourceDevice->GetDeviceCapability(SourceDevice::capRemoteReleaseControl);\n bool bCanUseViewfinder = m_spSourceDevice->GetDeviceCapability(SourceDevice::capRemoteViewfinder);\n\n _tprintf(_T(\"can release shutter: %s\\n\"), bCanRelease ? _T(\"yes\") : _T(\"no\"));\n _tprintf(_T(\"can use remote viewfinder: %s\\n\"), bCanUseViewfinder ? _T(\"yes\") : _T(\"no\"));\n _tprintf(_T(\"\\n\"));\n}\n\nvoid CmdlineApp::ListDeviceProperties()\n{\n \/\/ output device properties\n _tprintf(_T(\"Device properties\\n\"));\n\n std::vector vecProperties = m_spSourceDevice->EnumDeviceProperties();\n\n for (size_t i=0, iMax=vecProperties.size(); iGetDeviceProperty(uiPropertyId);\n\n _tprintf(_T(\"Property \\\"%s\\\" (%04x)%s: %s (%s)\\n\"),\n dp.Name().GetString(),\n uiPropertyId,\n dp.IsReadOnly() ? _T(\" [read-only]\") : _T(\"\"),\n dp.Value().ToString().GetString(),\n dp.AsString().GetString());\n\n std::vector vecValidValues = dp.ValidValues();\n for (size_t j=0, jMax=vecValidValues.size(); j vecImageProperties = m_spReleaseControl->EnumImageProperties();\n if (vecImageProperties.empty())\n {\n _tprintf(_T(\"no image properties found.\\n\"));\n }\n else\n for (size_t i=0,iMax=vecImageProperties.size(); iGetImageProperty(uiPropertyId);\n\n _tprintf(_T(\"Image property \\\"%s\\\" (%04x)%s: %s (%s)\\n\"),\n ip.Name().GetString(),\n uiPropertyId,\n ip.IsReadOnly() ? _T(\" [read-only]\") : _T(\"\"),\n ip.Value().ToString().GetString(),\n ip.AsString().GetString());\n\n std::vector vecValues;\n m_spReleaseControl->EnumImagePropertyValues(vecImageProperties[i], vecValues);\n\n for (size_t j=0, jMax=vecValues.size(); jAddPropertyEventHandler(\n [&](RemoteReleaseControl::T_enPropertyEvent enPropertyEvent, unsigned int uiValue)\n {\n ImageProperty prop = m_spReleaseControl->GetImageProperty(uiValue);\n\n _tprintf(_T(\"Property%s changed: Id=%04x Name=%s Value=%s\\n\"),\n enPropertyEvent == RemoteReleaseControl::propEventPropertyChanged ? _T(\"\") : _T(\" desc.\"),\n uiValue,\n prop.Name().GetString(),\n prop.AsString().GetString());\n });\n\n int iStateEvent = m_spReleaseControl->AddStateEventHandler(\n [&](RemoteReleaseControl::T_enStateEvent enStateEvent, unsigned int uiValue)\n {\n _tprintf(_T(\"State changed: State=%s Value=%u\\n\"),\n enStateEvent == RemoteReleaseControl::stateEventCameraShutdown ? _T(\"CameraShutdown\") :\n enStateEvent == RemoteReleaseControl::stateEventRotationAngle ? _T(\"RotationAngle\") :\n enStateEvent == RemoteReleaseControl::stateEventMemoryCardSlotOpen ? _T(\"MemoryCardSlotOpen\") :\n enStateEvent == RemoteReleaseControl::stateEventReleaseError ? _T(\"ReleaseError\") :\n enStateEvent == RemoteReleaseControl::stateEventBulbExposureTime ? _T(\"BulbExposureTime\") :\n enStateEvent == RemoteReleaseControl::stateEventInternalError ? _T(\"InternalError\") :\n _T(\"???\"),\n uiValue);\n });\n\n _tprintf(_T(\"Press any key to exit listening for events...\\n\\n\"));\n\n \/\/ wait for key and run OnIdle() in the meantime\n Event evtStop(true, false);\n std::thread idleThread([&evtStop]()\n {\n (void)fgetc(stdin);\n evtStop.Set();\n });\n\n while (!evtStop.Wait(10))\n Instance::OnIdle();\n\n idleThread.join();\n\n m_spReleaseControl->RemovePropertyEventHandler(iPropertyEvent);\n m_spReleaseControl->RemoveStateEventHandler(iStateEvent);\n}\n\nvoid CmdlineApp::EnsureReleaseControl()\n{\n if (m_spReleaseControl != nullptr)\n return;\n\n if (m_spSourceDevice == nullptr)\n throw Exception(_T(\"Source device not opened.\"), __FILE__, __LINE__);\n\n _tprintf(_T(\"Starting Remote Release Control\\n\"));\n\n m_spReleaseControl = m_spSourceDevice->EnterReleaseControl();\n}\n\nvoid CmdlineApp::ReleaseShutter()\n{\n _tprintf(_T(\"Release shutter\\n\"));\n\n EnsureReleaseControl();\n\n unsigned int uiNumAvailShot = m_spReleaseControl->NumAvailableShots();\n _tprintf(_T(\"Memory for %u images available\\n\"), uiNumAvailShot);\n\n Event evtPictureTaken(true, false);\n ShutterReleaseSettings settings(\n ShutterReleaseSettings::saveToHost,\n std::bind(&Event::Set, &evtPictureTaken));\n\n m_spReleaseControl->SetReleaseSettings(settings);\n\n m_spReleaseControl->Release();\n\n evtPictureTaken.Wait();\n}\n\nvoid CmdlineApp::RunScript(const CString& cszFilename)\n{\n _tprintf(_T(\"Loading script: %s\\n\"), cszFilename.GetString());\n\n CameraScriptProcessor proc;\n\n proc.SetOutputDebugStringHandler(\n [&](const CString& cszText){\n _tprintf(_T(\"%s\"), cszText.GetString());\n });\n\n proc.LoadScript(cszFilename);\n\n proc.Run();\n\n _tprintf(_T(\"Press any key to abort running script.\\n\\n\"));\n\n (void)fgetc(stdin);\n\n proc.Stop();\n}\nfixed cppcheck message, formatting size_t with wrong format specifier\/\/\n\/\/ RemotePhotoTool - remote camera control software\n\/\/ Copyright (C) 2008-2014 Michael Fink\n\/\/\n\/\/\/ \\file CmdlineApp.cpp Command line app\n\/\/\n\n\/\/ includes\n#include \"stdafx.h\"\n#include \"CmdlineApp.hpp\"\n#include \"Exception.hpp\"\n#include \"CameraException.hpp\"\n#include \"AppCommand.hpp\"\n#include \"AppOptions.hpp\"\n#include \"Event.hpp\"\n#include \"CameraScriptProcessor.hpp\"\n#include \"Instance.hpp\"\n#include \"SourceInfo.hpp\"\n#include \"SourceDevice.hpp\"\n#include \"RemoteReleaseControl.hpp\"\n#include \"ShutterReleaseSettings.hpp\"\n#include \"Filesystem.hpp\"\n#include \"CrashReporter.hpp\"\n#include \"..\\version.h\"\n#include \n\nCmdlineApp::CmdlineApp()\n{\n _tprintf(_T(\"RemotePhotoTool Command-Line %s\\n%s\\n\\n\"),\n _T(VERSIONINFO_FILEVERSION_DISPLAYSTRING),\n _T(VERSIONINFO_COPYRIGHT));\n}\n\nvoid CmdlineApp::InitCrashReporter()\n{\n CString cszFolder = App_GetAppDataFolder(appDataUserNonRoaming) + _T(\"\\\\RemotePhotoToolCmdline\\\\\");\n\n if (!Directory_Exists(cszFolder))\n CreateDirectory(cszFolder, NULL);\n\n cszFolder += _T(\"crashdumps\\\\\");\n\n if (!Directory_Exists(cszFolder))\n CreateDirectory(cszFolder, NULL);\n\n CrashReporter::Init(cszFolder);\n}\n\nvoid CmdlineApp::Run(int argc, TCHAR* argv[])\n{\n \/\/ parse options\n AppOptions options(m_vecCommandList);\n options.Parse(argc, argv);\n\n if (m_vecCommandList.empty())\n {\n options.OutputHelp();\n return;\n }\n\n if (options.IsSelectedHelpOption())\n return;\n\n \/\/ run command list\n std::for_each(m_vecCommandList.begin(), m_vecCommandList.end(), [&](const AppCommand& cmd)\n {\n try\n {\n Exec(cmd);\n }\n catch(const CameraException& ex)\n {\n _tprintf(_T(\"CameraException was thrown: \\\"%s\\\"\\n\"), ex.Message().GetString());\n }\n catch(const Exception& ex)\n {\n _tprintf(_T(\"Exception was thrown: \\\"%s\\\"\\n\"), ex.Message().GetString());\n }\n });\n}\n\nvoid CmdlineApp::Exec(const AppCommand& cmd)\n{\n switch (cmd.m_enCommand)\n {\n case AppCommand::showVersion: PrintVersionInfo(); break;\n case AppCommand::listDevices: ListDevices(); break;\n case AppCommand::openDevice: OpenByName(cmd.m_cszData); break;\n case AppCommand::closeDevice:\n m_spSourceDevice.reset();\n m_spReleaseControl.reset();\n break;\n case AppCommand::deviceInfo: OutputDeviceInfo(); break;\n case AppCommand::deviceProperties: ListDeviceProperties(); break;\n case AppCommand::imageProperties: ListImageProperties(); break;\n case AppCommand::listenEvents: ListenToEvents(); break;\n case AppCommand::releaseShutter: ReleaseShutter(); break;\n case AppCommand::runScript: RunScript(cmd.m_cszData); break;\n default:\n ATLASSERT(false);\n break;\n }\n}\n\nvoid CmdlineApp::PrintVersionInfo()\n{\n _tprintf(_T(\"CanonControl version info\\n\\n\"));\n\n Instance inst = Instance::Get();\n\n CString cszVersionInfo = inst.Version();\n\n _tprintf(_T(\"%s\\n\"), cszVersionInfo.GetString());\n}\n\nvoid CmdlineApp::ListDevices()\n{\n _tprintf(_T(\"Devices list\\n\"));\n\n Instance inst = Instance::Get();\n\n std::vector> vecSourceDevices;\n inst.EnumerateDevices(vecSourceDevices);\n\n if (vecSourceDevices.empty())\n {\n _tprintf(_T(\"No device found.\\n\"));\n }\n else\n {\n for (size_t i=0,iMax=vecSourceDevices.size(); i spSourceInfo = vecSourceDevices[i];\n _tprintf(_T(\"Device %Iu: \\\"%s\\\"\\n\"), i+1, spSourceInfo->Name().GetString());\n }\n }\n\n _tprintf(_T(\"\\n\"));\n}\n\nvoid CmdlineApp::OpenByName(const CString& cszName)\n{\n Instance inst = Instance::Get();\n\n std::vector> vecSourceDevices;\n inst.EnumerateDevices(vecSourceDevices);\n\n int iPosOpen = cszName.Find(_T('{'));\n int iPosClose = cszName.Find(_T('}'), iPosOpen + 1);\n if (iPosOpen != -1 && iPosClose != -1)\n {\n CString cszIndex = cszName.Mid(iPosOpen + 1, iPosClose - iPosOpen - 1);\n\n size_t iIndex = _tcstoul(cszIndex, nullptr, 10);\n\n if (iIndex >= vecSourceDevices.size())\n throw Exception(_T(\"Invalid index for camera\"), __FILE__, __LINE__);\n\n std::shared_ptr spSourceInfo = vecSourceDevices[iIndex];\n\n _tprintf(_T(\"Opening camera: %s\\n\"), spSourceInfo->Name().GetString());\n\n m_spSourceDevice = spSourceInfo->Open();\n return;\n }\n\n for (size_t i=0,iMax=vecSourceDevices.size(); i spSourceInfo = vecSourceDevices[i];\n if (spSourceInfo->Name() == cszName)\n {\n _tprintf(_T(\"Opening camera: %s\\n\"), spSourceInfo->Name().GetString());\n\n m_spSourceDevice = spSourceInfo->Open();\n return;\n }\n }\n\n throw Exception(_T(\"Couldn't find camera model: \") + cszName, __FILE__, __LINE__);\n}\n\nvoid CmdlineApp::OutputDeviceInfo()\n{\n _tprintf(_T(\"Device info about \\\"%s\\\"\\n\"), m_spSourceDevice->ModelName().GetString());\n _tprintf(_T(\"Serial number \\\"%s\\\"\\n\"), m_spSourceDevice->SerialNumber().GetString());\n\n \/\/ output capabilities\n _tprintf(_T(\"Device capabilities\\n\"));\n bool bCanRelease = m_spSourceDevice->GetDeviceCapability(SourceDevice::capRemoteReleaseControl);\n bool bCanUseViewfinder = m_spSourceDevice->GetDeviceCapability(SourceDevice::capRemoteViewfinder);\n\n _tprintf(_T(\"can release shutter: %s\\n\"), bCanRelease ? _T(\"yes\") : _T(\"no\"));\n _tprintf(_T(\"can use remote viewfinder: %s\\n\"), bCanUseViewfinder ? _T(\"yes\") : _T(\"no\"));\n _tprintf(_T(\"\\n\"));\n}\n\nvoid CmdlineApp::ListDeviceProperties()\n{\n \/\/ output device properties\n _tprintf(_T(\"Device properties\\n\"));\n\n std::vector vecProperties = m_spSourceDevice->EnumDeviceProperties();\n\n for (size_t i=0, iMax=vecProperties.size(); iGetDeviceProperty(uiPropertyId);\n\n _tprintf(_T(\"Property \\\"%s\\\" (%04x)%s: %s (%s)\\n\"),\n dp.Name().GetString(),\n uiPropertyId,\n dp.IsReadOnly() ? _T(\" [read-only]\") : _T(\"\"),\n dp.Value().ToString().GetString(),\n dp.AsString().GetString());\n\n std::vector vecValidValues = dp.ValidValues();\n for (size_t j=0, jMax=vecValidValues.size(); j vecImageProperties = m_spReleaseControl->EnumImageProperties();\n if (vecImageProperties.empty())\n {\n _tprintf(_T(\"no image properties found.\\n\"));\n }\n else\n for (size_t i=0,iMax=vecImageProperties.size(); iGetImageProperty(uiPropertyId);\n\n _tprintf(_T(\"Image property \\\"%s\\\" (%04x)%s: %s (%s)\\n\"),\n ip.Name().GetString(),\n uiPropertyId,\n ip.IsReadOnly() ? _T(\" [read-only]\") : _T(\"\"),\n ip.Value().ToString().GetString(),\n ip.AsString().GetString());\n\n std::vector vecValues;\n m_spReleaseControl->EnumImagePropertyValues(vecImageProperties[i], vecValues);\n\n for (size_t j=0, jMax=vecValues.size(); jAddPropertyEventHandler(\n [&](RemoteReleaseControl::T_enPropertyEvent enPropertyEvent, unsigned int uiValue)\n {\n ImageProperty prop = m_spReleaseControl->GetImageProperty(uiValue);\n\n _tprintf(_T(\"Property%s changed: Id=%04x Name=%s Value=%s\\n\"),\n enPropertyEvent == RemoteReleaseControl::propEventPropertyChanged ? _T(\"\") : _T(\" desc.\"),\n uiValue,\n prop.Name().GetString(),\n prop.AsString().GetString());\n });\n\n int iStateEvent = m_spReleaseControl->AddStateEventHandler(\n [&](RemoteReleaseControl::T_enStateEvent enStateEvent, unsigned int uiValue)\n {\n _tprintf(_T(\"State changed: State=%s Value=%u\\n\"),\n enStateEvent == RemoteReleaseControl::stateEventCameraShutdown ? _T(\"CameraShutdown\") :\n enStateEvent == RemoteReleaseControl::stateEventRotationAngle ? _T(\"RotationAngle\") :\n enStateEvent == RemoteReleaseControl::stateEventMemoryCardSlotOpen ? _T(\"MemoryCardSlotOpen\") :\n enStateEvent == RemoteReleaseControl::stateEventReleaseError ? _T(\"ReleaseError\") :\n enStateEvent == RemoteReleaseControl::stateEventBulbExposureTime ? _T(\"BulbExposureTime\") :\n enStateEvent == RemoteReleaseControl::stateEventInternalError ? _T(\"InternalError\") :\n _T(\"???\"),\n uiValue);\n });\n\n _tprintf(_T(\"Press any key to exit listening for events...\\n\\n\"));\n\n \/\/ wait for key and run OnIdle() in the meantime\n Event evtStop(true, false);\n std::thread idleThread([&evtStop]()\n {\n (void)fgetc(stdin);\n evtStop.Set();\n });\n\n while (!evtStop.Wait(10))\n Instance::OnIdle();\n\n idleThread.join();\n\n m_spReleaseControl->RemovePropertyEventHandler(iPropertyEvent);\n m_spReleaseControl->RemoveStateEventHandler(iStateEvent);\n}\n\nvoid CmdlineApp::EnsureReleaseControl()\n{\n if (m_spReleaseControl != nullptr)\n return;\n\n if (m_spSourceDevice == nullptr)\n throw Exception(_T(\"Source device not opened.\"), __FILE__, __LINE__);\n\n _tprintf(_T(\"Starting Remote Release Control\\n\"));\n\n m_spReleaseControl = m_spSourceDevice->EnterReleaseControl();\n}\n\nvoid CmdlineApp::ReleaseShutter()\n{\n _tprintf(_T(\"Release shutter\\n\"));\n\n EnsureReleaseControl();\n\n unsigned int uiNumAvailShot = m_spReleaseControl->NumAvailableShots();\n _tprintf(_T(\"Memory for %u images available\\n\"), uiNumAvailShot);\n\n Event evtPictureTaken(true, false);\n ShutterReleaseSettings settings(\n ShutterReleaseSettings::saveToHost,\n std::bind(&Event::Set, &evtPictureTaken));\n\n m_spReleaseControl->SetReleaseSettings(settings);\n\n m_spReleaseControl->Release();\n\n evtPictureTaken.Wait();\n}\n\nvoid CmdlineApp::RunScript(const CString& cszFilename)\n{\n _tprintf(_T(\"Loading script: %s\\n\"), cszFilename.GetString());\n\n CameraScriptProcessor proc;\n\n proc.SetOutputDebugStringHandler(\n [&](const CString& cszText){\n _tprintf(_T(\"%s\"), cszText.GetString());\n });\n\n proc.LoadScript(cszFilename);\n\n proc.Run();\n\n _tprintf(_T(\"Press any key to abort running script.\\n\\n\"));\n\n (void)fgetc(stdin);\n\n proc.Stop();\n}\n<|endoftext|>"} {"text":"Fix BMC 21651 - [REG] New tab on wrench menu is not working when bookmark manager or download manager is open<|endoftext|>"} {"text":"Looks like the fix I did last time did work. According to the flakiness dashboard this hasn't failed since the day I checked in the fix (Jan 26th).<|endoftext|>"} {"text":"Disable test while investigating. TBR=amit<|endoftext|>"} {"text":"\n#include \n#include \n\n\nnamespace {\n\nclass OpenMeshReadWriteSTL : public OpenMeshBase {\n\n protected:\n\n \/\/ This function is called before each test is run\n virtual void SetUp() {\n\n \/\/ Do some initial stuff with the member data here...\n }\n\n \/\/ This function is called after all tests are through\n virtual void TearDown() {\n\n \/\/ Do some final stuff with the member data here...\n }\n\n \/\/ Member already defined in OpenMeshBase\n \/\/Mesh mesh_;\n};\n\n\/*\n * ====================================================================\n * Define tests below\n * ====================================================================\n *\/\n\n\/*\n * Just load a simple mesh file in stla format and count whether\n * the right number of entities has been loaded.\n *\/\nTEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLFile) {\n\n mesh_.clear();\n\n bool ok = OpenMesh::IO::read_mesh(mesh_, \"cube1.stl\");\n\n EXPECT_TRUE(ok);\n\n EXPECT_EQ(7526u , mesh_.n_vertices()) << \"The number of loaded vertices is not correct!\";\n EXPECT_EQ(22572u , mesh_.n_edges()) << \"The number of loaded edges is not correct!\";\n EXPECT_EQ(15048u , mesh_.n_faces()) << \"The number of loaded faces is not correct!\";\n}\n\n\n\/*\n * Just load a simple mesh file in stla format and count whether\n * the right number of entities has been loaded. Also check facet normals.\n *\/\nTEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLFileWithNormals) {\n\n mesh_.clear();\n mesh_.request_face_normals();\n\n OpenMesh::IO::Options opt;\n opt += OpenMesh::IO::Options::FaceNormal;\n\n bool ok = OpenMesh::IO::read_mesh(mesh_, \"cube1.stl\", opt);\n\n EXPECT_TRUE(ok);\n\n EXPECT_TRUE(opt.face_has_normal());\n EXPECT_FALSE(opt.vertex_has_normal());\n\n EXPECT_NEAR(-0.038545f, mesh_.normal(mesh_.face_handle(0))[0], 0.0001 ) << \"Wrong face normal at face 0 component 0\";\n EXPECT_NEAR(-0.004330f, mesh_.normal(mesh_.face_handle(0))[1], 0.0001 ) << \"Wrong face normal at face 0 component 1\";\n EXPECT_NEAR(0.999247f, mesh_.normal(mesh_.face_handle(0))[2], 0.0001 ) << \"Wrong face normal at face 0 component 2\";\n\n EXPECT_EQ(7526u , mesh_.n_vertices()) << \"The number of loaded vertices is not correct!\";\n EXPECT_EQ(22572u , mesh_.n_edges()) << \"The number of loaded edges is not correct!\";\n EXPECT_EQ(15048u , mesh_.n_faces()) << \"The number of loaded faces is not correct!\";\n\n mesh_.release_face_normals();\n}\n\n\n\/*\n * Just load a simple mesh file in stlb format and count whether\n * the right number of entities has been loaded.\n *\/\nTEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLBinaryFile) {\n\n mesh_.clear();\n\n bool ok = OpenMesh::IO::read_mesh(mesh_, \"cube1Binary.stl\");\n\n EXPECT_TRUE(ok);\n\n EXPECT_EQ(7526u , mesh_.n_vertices()) << \"The number of loaded vertices is not correct!\";\n EXPECT_EQ(22572u , mesh_.n_edges()) << \"The number of loaded edges is not correct!\";\n EXPECT_EQ(15048u , mesh_.n_faces()) << \"The number of loaded faces is not correct!\";\n}\n\n\n\/*\n * Just load a simple mesh file in stlb format and count whether\n * the right number of entities has been loaded. Also check facet normals.\n *\/\nTEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLBinaryFileWithNormals) {\n\n mesh_.clear();\n mesh_.request_face_normals();\n\n OpenMesh::IO::Options opt;\n opt += OpenMesh::IO::Options::FaceNormal;\n opt += OpenMesh::IO::Options::Binary;\n\n bool ok = OpenMesh::IO::read_mesh(mesh_, \"cube1Binary.stl\", opt);\n\n EXPECT_TRUE(ok);\n\n EXPECT_TRUE(opt.is_binary());\n EXPECT_TRUE(opt.face_has_normal());\n EXPECT_FALSE(opt.vertex_has_normal());\n\n EXPECT_NEAR(-0.038545f, mesh_.normal(mesh_.face_handle(0))[0], 0.0001 ) << \"Wrong face normal at face 0 component 0\";\n EXPECT_NEAR(-0.004330f, mesh_.normal(mesh_.face_handle(0))[1], 0.0001 ) << \"Wrong face normal at face 0 component 1\";\n EXPECT_NEAR(0.999247f, mesh_.normal(mesh_.face_handle(0))[2], 0.0001 ) << \"Wrong face normal at face 0 component 2\";\n\n EXPECT_EQ(7526u , mesh_.n_vertices()) << \"The number of loaded vertices is not correct!\";\n EXPECT_EQ(22572u , mesh_.n_edges()) << \"The number of loaded edges is not correct!\";\n EXPECT_EQ(15048u , mesh_.n_faces()) << \"The number of loaded faces is not correct!\";\n\n mesh_.release_face_normals();\n}\n\n}\nadd write unittest for binary files\n#include \n#include \n\n\nnamespace {\n\nclass OpenMeshReadWriteSTL : public OpenMeshBase {\n\n protected:\n\n \/\/ This function is called before each test is run\n virtual void SetUp() {\n\n \/\/ Do some initial stuff with the member data here...\n }\n\n \/\/ This function is called after all tests are through\n virtual void TearDown() {\n\n \/\/ Do some final stuff with the member data here...\n }\n\n \/\/ Member already defined in OpenMeshBase\n \/\/Mesh mesh_;\n};\n\n\/*\n * ====================================================================\n * Define tests below\n * ====================================================================\n *\/\n\n\/*\n * Just load a simple mesh file in stla format and count whether\n * the right number of entities has been loaded.\n *\/\nTEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLFile) {\n\n mesh_.clear();\n\n bool ok = OpenMesh::IO::read_mesh(mesh_, \"cube1.stl\");\n\n EXPECT_TRUE(ok);\n\n EXPECT_EQ(7526u , mesh_.n_vertices()) << \"The number of loaded vertices is not correct!\";\n EXPECT_EQ(22572u , mesh_.n_edges()) << \"The number of loaded edges is not correct!\";\n EXPECT_EQ(15048u , mesh_.n_faces()) << \"The number of loaded faces is not correct!\";\n}\n\n\n\/*\n * Just load a simple mesh file in stla format and count whether\n * the right number of entities has been loaded. Also check facet normals.\n *\/\nTEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLFileWithNormals) {\n\n mesh_.clear();\n mesh_.request_face_normals();\n\n OpenMesh::IO::Options opt;\n opt += OpenMesh::IO::Options::FaceNormal;\n\n bool ok = OpenMesh::IO::read_mesh(mesh_, \"cube1.stl\", opt);\n\n EXPECT_TRUE(ok);\n\n EXPECT_TRUE(opt.face_has_normal());\n EXPECT_FALSE(opt.vertex_has_normal());\n\n EXPECT_NEAR(-0.038545f, mesh_.normal(mesh_.face_handle(0))[0], 0.0001 ) << \"Wrong face normal at face 0 component 0\";\n EXPECT_NEAR(-0.004330f, mesh_.normal(mesh_.face_handle(0))[1], 0.0001 ) << \"Wrong face normal at face 0 component 1\";\n EXPECT_NEAR(0.999247f, mesh_.normal(mesh_.face_handle(0))[2], 0.0001 ) << \"Wrong face normal at face 0 component 2\";\n\n EXPECT_EQ(7526u , mesh_.n_vertices()) << \"The number of loaded vertices is not correct!\";\n EXPECT_EQ(22572u , mesh_.n_edges()) << \"The number of loaded edges is not correct!\";\n EXPECT_EQ(15048u , mesh_.n_faces()) << \"The number of loaded faces is not correct!\";\n\n mesh_.release_face_normals();\n}\n\n\n\/*\n * Just load a simple mesh file in stlb format and count whether\n * the right number of entities has been loaded.\n *\/\nTEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLBinaryFile) {\n\n mesh_.clear();\n\n bool ok = OpenMesh::IO::read_mesh(mesh_, \"cube1Binary.stl\");\n\n EXPECT_TRUE(ok);\n\n EXPECT_EQ(7526u , mesh_.n_vertices()) << \"The number of loaded vertices is not correct!\";\n EXPECT_EQ(22572u , mesh_.n_edges()) << \"The number of loaded edges is not correct!\";\n EXPECT_EQ(15048u , mesh_.n_faces()) << \"The number of loaded faces is not correct!\";\n}\n\n\n\/*\n * Just load a simple mesh file in stlb format and count whether\n * the right number of entities has been loaded. Also check facet normals.\n *\/\nTEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLBinaryFileWithNormals) {\n\n mesh_.clear();\n mesh_.request_face_normals();\n\n OpenMesh::IO::Options opt;\n opt += OpenMesh::IO::Options::FaceNormal;\n opt += OpenMesh::IO::Options::Binary;\n\n bool ok = OpenMesh::IO::read_mesh(mesh_, \"cube1Binary.stl\", opt);\n\n EXPECT_TRUE(ok);\n\n EXPECT_TRUE(opt.is_binary());\n EXPECT_TRUE(opt.face_has_normal());\n EXPECT_FALSE(opt.vertex_has_normal());\n\n EXPECT_NEAR(-0.038545f, mesh_.normal(mesh_.face_handle(0))[0], 0.0001 ) << \"Wrong face normal at face 0 component 0\";\n EXPECT_NEAR(-0.004330f, mesh_.normal(mesh_.face_handle(0))[1], 0.0001 ) << \"Wrong face normal at face 0 component 1\";\n EXPECT_NEAR(0.999247f, mesh_.normal(mesh_.face_handle(0))[2], 0.0001 ) << \"Wrong face normal at face 0 component 2\";\n\n EXPECT_EQ(7526u , mesh_.n_vertices()) << \"The number of loaded vertices is not correct!\";\n EXPECT_EQ(22572u , mesh_.n_edges()) << \"The number of loaded edges is not correct!\";\n EXPECT_EQ(15048u , mesh_.n_faces()) << \"The number of loaded faces is not correct!\";\n\n mesh_.release_face_normals();\n}\n\n\/*\n * Read and Write stl binary file\n *\/\nTEST_F(OpenMeshReadWriteSTL, ReadWriteSimpleSTLBinaryFile) {\n\n mesh_.clear();\n\n OpenMesh::IO::Options opt;\n opt += OpenMesh::IO::Options::Binary;\n\n bool ok = OpenMesh::IO::read_mesh(mesh_, \"cube1Binary.stl\");\n\n EXPECT_TRUE(ok);\n\n const char* filename = \"cube1Binary_openmeshWriteTestFile.stl\";\n\n ok = OpenMesh::IO::write_mesh(mesh_, filename, opt);\n\n EXPECT_TRUE(ok);\n\n ok = OpenMesh::IO::read_mesh(mesh_, filename, opt);\n\n EXPECT_TRUE(ok);\n\n EXPECT_EQ(7526u , mesh_.n_vertices()) << \"The number of loaded vertices is not correct!\";\n EXPECT_EQ(22572u , mesh_.n_edges()) << \"The number of loaded edges is not correct!\";\n EXPECT_EQ(15048u , mesh_.n_faces()) << \"The number of loaded faces is not correct!\";\n\n remove(filename);\n}\n\n\/*\n * Just load a simple mesh file in stlb format and count whether\n * the right number of entities has been loaded. Also check facet normals.\n *\/\nTEST_F(OpenMeshReadWriteSTL, ReadWriteSimpleSTLBinaryFileWithNormals) {\n\n mesh_.clear();\n mesh_.request_face_normals();\n\n OpenMesh::IO::Options opt;\n opt += OpenMesh::IO::Options::FaceNormal;\n opt += OpenMesh::IO::Options::Binary;\n\n bool ok = OpenMesh::IO::read_mesh(mesh_, \"cube1Binary.stl\", opt);\n\n EXPECT_TRUE(ok);\n\n const char* filename = \"cube1BinaryNormal_openmeshWriteTestFile.stl\";\n\n ok = OpenMesh::IO::write_mesh(mesh_, filename, opt);\n\n EXPECT_TRUE(ok);\n\n ok = OpenMesh::IO::read_mesh(mesh_, filename, opt);\n\n EXPECT_TRUE(ok);\n\n EXPECT_TRUE(opt.is_binary());\n EXPECT_TRUE(opt.face_has_normal());\n EXPECT_FALSE(opt.vertex_has_normal());\n\n EXPECT_NEAR(-0.038545f, mesh_.normal(mesh_.face_handle(0))[0], 0.0001 ) << \"Wrong face normal at face 0 component 0\";\n EXPECT_NEAR(-0.004330f, mesh_.normal(mesh_.face_handle(0))[1], 0.0001 ) << \"Wrong face normal at face 0 component 1\";\n EXPECT_NEAR(0.999247f, mesh_.normal(mesh_.face_handle(0))[2], 0.0001 ) << \"Wrong face normal at face 0 component 2\";\n\n EXPECT_EQ(7526u , mesh_.n_vertices()) << \"The number of loaded vertices is not correct!\";\n EXPECT_EQ(22572u , mesh_.n_edges()) << \"The number of loaded edges is not correct!\";\n EXPECT_EQ(15048u , mesh_.n_faces()) << \"The number of loaded faces is not correct!\";\n\n mesh_.release_face_normals();\n remove(filename);\n}\n\n\n}\n<|endoftext|>"} {"text":"nit: spacing<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkShiftScaleLabelMapFilterTest1.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n Portions of this code are covered under the VTK copyright.\n See VTKCopyright.txt or http:\/\/www.kitware.com\/VTKCopyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkSimpleFilterWatcher.h\"\n\n#include \"itkLabelObject.h\"\n#include \"itkLabelMap.h\"\n#include \"itkLabelImageToLabelMapFilter.h\"\n#include \"itkShiftScaleLabelMapFilter.h\"\n#include \"itkLabelMapToLabelImageFilter.h\"\n\n#include \"itkTestingMacros.h\"\n\n\nint itkShiftScaleLabelMapFilterTest1(int argc, char * argv[])\n{\n\n if( argc != 6 )\n {\n std::cerr << \"usage: \" << argv[0] << \" input output shift scale change_bg\" << std::endl;\n return EXIT_FAILURE; \n }\n\n const unsigned int dim = 2;\n \n typedef itk::Image< unsigned char, dim > ImageType;\n\n typedef itk::LabelObject< unsigned char, dim > LabelObjectType;\n typedef itk::LabelMap< LabelObjectType > LabelMapType;\n \n typedef itk::ImageFileReader< ImageType > ReaderType;\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName( argv[1] );\n \n typedef itk::LabelImageToLabelMapFilter< ImageType, LabelMapType> I2LType;\n I2LType::Pointer i2l = I2LType::New();\n i2l->SetInput( reader->GetOutput() );\n\n typedef itk::ShiftScaleLabelMapFilter< LabelMapType > ChangeType;\n ChangeType::Pointer change = ChangeType::New();\n change->SetInput( i2l->GetOutput() );\n change->SetShift( atof(argv[3]) );\n change->SetScale( atof(argv[4]) );\n change->SetChangeBackgroundValue( atoi(argv[5]) );\n itk::SimpleFilterWatcher watcher6(change, \"filter\");\n\n typedef itk::LabelMapToLabelImageFilter< LabelMapType, ImageType> L2IType;\n L2IType::Pointer l2i = L2IType::New();\n l2i->SetInput( change->GetOutput() );\n\n typedef itk::ImageFileWriter< ImageType > WriterType;\n WriterType::Pointer writer = WriterType::New();\n writer->SetInput( l2i->GetOutput() );\n writer->SetFileName( argv[2] );\n writer->UseCompressionOn();\n\n TRY_EXPECT_NO_EXCEPTION( writer->Update() );\n\n return EXIT_SUCCESS;\n}\nBUG: Clarified use of ChangeBackgroundValue as a boolean.\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkShiftScaleLabelMapFilterTest1.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n Portions of this code are covered under the VTK copyright.\n See VTKCopyright.txt or http:\/\/www.kitware.com\/VTKCopyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkSimpleFilterWatcher.h\"\n\n#include \"itkLabelObject.h\"\n#include \"itkLabelMap.h\"\n#include \"itkLabelImageToLabelMapFilter.h\"\n#include \"itkShiftScaleLabelMapFilter.h\"\n#include \"itkLabelMapToLabelImageFilter.h\"\n\n#include \"itkTestingMacros.h\"\n\n\nint itkShiftScaleLabelMapFilterTest1(int argc, char * argv[])\n{\n\n if( argc != 6 )\n {\n std::cerr << \"usage: \" << argv[0] << \" input output shift scale change_bg\" << std::endl;\n return EXIT_FAILURE; \n }\n\n const unsigned int dim = 2;\n \n typedef itk::Image< unsigned char, dim > ImageType;\n\n typedef itk::LabelObject< unsigned char, dim > LabelObjectType;\n typedef itk::LabelMap< LabelObjectType > LabelMapType;\n \n typedef itk::ImageFileReader< ImageType > ReaderType;\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName( argv[1] );\n \n typedef itk::LabelImageToLabelMapFilter< ImageType, LabelMapType> I2LType;\n I2LType::Pointer i2l = I2LType::New();\n i2l->SetInput( reader->GetOutput() );\n\n typedef itk::ShiftScaleLabelMapFilter< LabelMapType > ChangeType;\n ChangeType::Pointer change = ChangeType::New();\n change->SetInput( i2l->GetOutput() );\n change->SetShift( atof(argv[3]) );\n change->SetScale( atof(argv[4]) );\n bool changeBackground = atoi(argv[5]);\n change->SetChangeBackgroundValue( changeBackground ); \n itk::SimpleFilterWatcher watcher6(change, \"filter\");\n\n typedef itk::LabelMapToLabelImageFilter< LabelMapType, ImageType> L2IType;\n L2IType::Pointer l2i = L2IType::New();\n l2i->SetInput( change->GetOutput() );\n\n typedef itk::ImageFileWriter< ImageType > WriterType;\n WriterType::Pointer writer = WriterType::New();\n writer->SetInput( l2i->GetOutput() );\n writer->SetFileName( argv[2] );\n writer->UseCompressionOn();\n\n TRY_EXPECT_NO_EXCEPTION( writer->Update() );\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"Revert -r47806 which had negative consequences (failing to handle properly #ifdef at the beginning of an unnamed script and making it much harder to update roottest to work around missing feature in cling)<|endoftext|>"} {"text":"\/*\n * itkVectorImageRepresenterTest.cpp\n *\n * Created on: May 3, 2012\n * Author: luethi\n *\/\n\n#include \"itkVectorImageRepresenter.h\"\n#include \"genericRepresenterTest.hxx\"\n\n\n\ntypedef itk::Image< itk::Vector ,2 > VectorImageType;\ntypedef itk::VectorImageRepresenter RepresenterType;\n\ntypedef GenericRepresenterTest RepresenterTestType;\n\nVectorImageType::Pointer loadVectorImage(const std::string& filename) {\n\titk::ImageFileReader::Pointer reader = itk::ImageFileReader::New();\n\treader->SetFileName(filename);\n\treader->Update();\n\tVectorImageType::Pointer img = reader->GetOutput();\n\timg->DisconnectPipeline();\n\treturn img;\n}\n\nint main(int argc, char** argv) {\n\tif (argc < 2) {\n\t\tstd::cout << \"Usage: \" << argv[0] << \" datadir\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\tstd::string datadir = std::string(argv[1]);\n\n\tconst std::string referenceFilename = datadir + \"\/hand_dfs\/df-hand-1.vtk\";\n\tconst std::string testDatasetFilename = datadir + \"\/hand_dfs\/df-hand-2.vtk\";\n\n\tRepresenterType::Pointer representer = RepresenterType::New();\n\tVectorImageType::Pointer reference = loadVectorImage(referenceFilename);\n\trepresenter->SetReference(reference);\n\n\t\/\/ choose a test dataset, a point and its associate pixel value\n\n\tVectorImageType::Pointer testDataset = loadVectorImage(testDatasetFilename);\n\tVectorImageType::IndexType idx;\n\tidx.Fill(0);\n\tVectorImageType::PointType testPt;\n\ttestDataset->TransformIndexToPhysicalPoint(idx, testPt);\n\tVectorImageType::PixelType testValue = testDataset->GetPixel(idx);\n\n\tRepresenterTestType representerTest(representer, testDataset, std::make_pair(testPt, testValue));\n\n\tif (representerTest.runAllTests() == true) {\n\t\treturn EXIT_SUCCESS;\n\t}\n\telse {\n\t\treturn EXIT_FAILURE;\n\t}\n\n}\n\n\nfixed bug: testPoint must be taken from reference and not from testData\/*\n * itkVectorImageRepresenterTest.cpp\n *\n * Created on: May 3, 2012\n * Author: luethi\n *\/\n\n#include \"itkVectorImageRepresenter.h\"\n#include \"genericRepresenterTest.hxx\"\n\n\n\ntypedef itk::Image< itk::Vector ,2 > VectorImageType;\ntypedef itk::VectorImageRepresenter RepresenterType;\n\ntypedef GenericRepresenterTest RepresenterTestType;\n\nVectorImageType::Pointer loadVectorImage(const std::string& filename) {\n\titk::ImageFileReader::Pointer reader = itk::ImageFileReader::New();\n\treader->SetFileName(filename);\n\treader->Update();\n\tVectorImageType::Pointer img = reader->GetOutput();\n\timg->DisconnectPipeline();\n\treturn img;\n}\n\nint main(int argc, char** argv) {\n\tif (argc < 2) {\n\t\tstd::cout << \"Usage: \" << argv[0] << \" datadir\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\tstd::string datadir = std::string(argv[1]);\n\n\tconst std::string referenceFilename = datadir + \"\/hand_dfs\/df-hand-1.vtk\";\n\tconst std::string testDatasetFilename = datadir + \"\/hand_dfs\/df-hand-2.vtk\";\n\n\tRepresenterType::Pointer representer = RepresenterType::New();\n\tVectorImageType::Pointer reference = loadVectorImage(referenceFilename);\n\trepresenter->SetReference(reference);\n\n\t\/\/ choose a test dataset, a point and its associate pixel value\n\n\tVectorImageType::Pointer testDataset = loadVectorImage(testDatasetFilename);\n\tVectorImageType::IndexType idx;\n\tidx.Fill(0);\n\tVectorImageType::PointType testPt;\n\treference->TransformIndexToPhysicalPoint(idx, testPt);\n\tVectorImageType::PixelType testValue = testDataset->GetPixel(idx);\n\n\tRepresenterTestType representerTest(representer, testDataset, std::make_pair(testPt, testValue));\n\n\tif (representerTest.runAllTests() == true) {\n\t\treturn EXIT_SUCCESS;\n\t}\n\telse {\n\t\treturn EXIT_FAILURE;\n\t}\n\n}\n\n\n<|endoftext|>"} {"text":"#include \"decafs_barista.h\"\n\nint main (int argc, char *argv[]) {\n barista_core_init (argc, argv);\n printf (\"Barista is initialized.\\n\");\n printf (\"\\tstripe_size: %d\\n\\tchunk_size: %d\\n\\n\", get_stripe_size(),\n get_chunk_size());\n\n int port = 0;\n if (argc >= MIN_ARGS) {\n port = atoi(argv[PORT]); \n printf(\"got port: %d\\n\", port);\n } else {\n fprintf(stderr, \"port number not specified\\n\");\n exit(-1);\n }\n\n BaristaServer *barista_server = BaristaServer::init(port);\n barista_server->run();\n\n \/* TEST CODE *\/\n \/*struct ip_address ip;\n struct client default_client = {ip, 1, 1};\n int count, fd = open_file (\"new_file.txt\", O_RDWR, default_client);\n char buf[] = \"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100\";\n char *read_buf = (char *)malloc (1000);\n memset (read_buf, '\\0', 1000);\n printf (\"\\n\\n ------------------------------FIRST WRITE------------------------------\\n\");\n count = write_file (fd, buf, strlen (buf), default_client);\n printf (\"(\\n(BARISTA) wrote %d bytes.\\n\", count);\n \n close_file (fd, default_client);\n fd = open_file (\"new_file.txt\", O_RDONLY, default_client);\n\n printf (\"\\n\\n ------------------------------FIRST READ--------------------------------\\n\");\n count = read_file (fd, read_buf, strlen (buf), default_client);\n printf (\"\\n(BARISTA) Read %d bytes.\\n\", count);\n printf (\"(BARISTA) Buf is:\\n%s\\n\", read_buf);\n \n close_file (fd, default_client);\n fd = open_file (\"new_file.txt\", O_RDWR | O_APPEND, default_client);\n\n printf (\"\\n\\n ------------------------------SECOND WRITE------------------------------\\n\");\n write_file (fd, buf, strlen (buf), default_client);\n \n close_file (fd, default_client);\n fd = open_file (\"new_file.txt\", O_RDONLY, default_client);\n \n printf (\"\\n\\n ------------------------------SECOND READ--------------------------------\\n\");\n count = read_file (fd, read_buf, 2*strlen (buf), default_client);\n printf (\"\\n(BARISTA) Read %d bytes.\\n\", count);\n printf (\"(BARISTA) Buf is:\\n%s\\n\", read_buf);*\/\n return 0;\n}\n\nadded logging to decafs_barista main#include \"decafs_barista.h\"\n\nint main (int argc, char *argv[]) {\n\n printf(\"DecafsBarista: initializing barista_core\\n\");\n barista_core_init (argc, argv);\n printf (\"Barista is initialized.\\n\");\n printf (\"\\tstripe_size: %d\\n\\tchunk_size: %d\\n\\n\", get_stripe_size(),\n get_chunk_size());\n printf(\"DecafsBarista: barista_core initialized\\n\");\n\n int port = 0;\n if (argc >= MIN_ARGS) {\n port = atoi(argv[PORT]); \n printf(\"got port: %d\\n\", port);\n } else {\n fprintf(stderr, \"port number not specified\\n\");\n exit(-1);\n }\n\n printf(\"DecafsBarista: initializing BaristaServer\\n\");\n BaristaServer *barista_server = BaristaServer::init(port);\n printf(\"DecafsBarista: BaristaServer initialized, running BaristaServer\\n\");\n barista_server->run();\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"Export ShapeRec symbols<|endoftext|>"} {"text":"#include \"HPACK.h\"\n#include \"gtest\/gtest.h\"\n#include \n\nTEST(encode_intTest, NormalTest) {\n uint8_t dst[10];\n uint8_t expect[][5] = {\n {0x01, 0x00},\n {0x0f, 0x01},\n \/\/{0x1f, 0xa1, 0x8d, 0xb7, 0x01},\n };\n uint64_t len = encode_int(dst, 1, 1);\n EXPECT_EQ(2, len);\n EXPECT_TRUE(0 == std::memcmp(dst, expect[0], len));\n len = encode_int(dst, 16, 4);\n EXPECT_EQ(2, len);\n EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len));\n \/*\n len = encode_int(dst, 3000000, 5);\n EXPECT_EQ(5, len);\n EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len));\n *\/\n}\n\nTEST(decode_intTest, NormalTest) {\n uint32_t dst = 0;\n uint8_t data[][5] = {\n {0x01, 0x00},\n {0x0f, 0x01},\n };\n EXPECT_EQ(1, decode_int(data[0], 1));\n EXPECT_EQ(16, decode_int(data[1], 4));\n}\n\nint main(int argc, char **argv) {\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\nimplement json parser#include \"HPACK.h\"\n#include \"hpack_table.h\"\n#include \"gtest\/gtest.h\"\n#include \n#include \"picojson\/picojson.h\"\n#include \n#include \n#include \n\n\nTEST(encode_intTest, NormalTest) {\n uint8_t dst[10];\n uint8_t expect[][5] = {\n {0x01, 0x00},\n {0x0f, 0x01},\n \/\/{0x1f, 0xa1, 0x8d, 0xb7, 0x01},\n };\n uint64_t len = encode_int(dst, 1, 1);\n EXPECT_EQ(2, len);\n EXPECT_TRUE(0 == std::memcmp(dst, expect[0], len));\n len = encode_int(dst, 16, 4);\n EXPECT_EQ(2, len);\n EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len));\n \/*\n len = encode_int(dst, 3000000, 5);\n EXPECT_EQ(5, len);\n EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len));\n *\/\n}\n\nTEST(decode_intTest, NormalTest) {\n uint32_t dst = 0;\n uint8_t data[][5] = {\n {0x01, 0x00},\n {0x0f, 0x01},\n };\n EXPECT_EQ(1, decode_int(data[0], 1));\n EXPECT_EQ(16, decode_int(data[1], 4));\n}\n\nTEST(encodeTest, NormalTest) {\n std::ifstream ifs(\"hpack-test-case\/haskell-http2-naive\/story_00.json\");\n if (ifs.fail()) {\n std::cerr << \"fail to open\" << std::endl;\n }\n std::string str((std::istreambuf_iterator(ifs)), std::istreambuf_iterator());\n\n picojson::value v;\n std::string err = picojson::parse(v, str);\n if (! err.empty()) {\n std::cerr << err << std::endl;\n }\n\n picojson::object obj = v.get();\n picojson::array arr = obj[\"cases\"].get();\n picojson::array::iterator it_seqno;\n for (it_seqno = arr.begin(); it_seqno != arr.end(); it_seqno++) {\n picojson::object obj_in = it_seqno->get();\n std::string wire = obj_in[\"wire\"].to_str();\n picojson::array json_headers = obj_in[\"headers\"].get();\n picojson::array::iterator it_headers;\n std::vector
ans_headers;\n\n for (it_headers = json_headers.begin(); it_headers != json_headers.end(); it_headers++) {\n picojson::object content = it_headers->get();\n picojson::object::iterator it = content.begin();\n ans_headers.push_back(header(it->first, it->second.to_str()));\n }\n Table* table = new Table();\n uint8_t dst[2000];\n int64_t len = hpack_encode(dst, ans_headers, false, false, false, table, -1);\n \/\/EXPECT_TRUE(0 == std::memcmp(dst, wire, len));\n }\n}\n\nint main(int argc, char **argv) {\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nModule: $RCSfile$\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n#include \"mitkRenderWindow.h\"\n#include \"mitkVtkRenderWindow.h\"\n#include \"mitkOpenGLRenderer.h\"\n#include \n\nstd::set mitk::RenderWindow::instances;\n\nmitk::RenderWindow::RenderWindow(const char *name, mitk::BaseRenderer* renderer) \n : m_MitkVtkRenderWindow(NULL), m_Name(name), m_Renderer(renderer)\n{\n instances.insert(this);\n m_MitkVtkRenderWindow = mitk::VtkRenderWindow::New();\n}\n\nmitk::RenderWindow::~RenderWindow()\n{\n instances.erase(this);\n m_Renderer = NULL;\n m_MitkVtkRenderWindow->Delete(); \/\/xxx\n}\n\nvoid mitk::RenderWindow::MakeCurrent() \n{\n m_MitkVtkRenderWindow->MakeCurrent();\n};\n\nvoid mitk::RenderWindow::SwapBuffers() \n{\n m_MitkVtkRenderWindow->Frame();\n};\n\nbool mitk::RenderWindow::IsSharing () const\n{\n return false;\n}\n\nvoid mitk::RenderWindow::Update()\n{\n m_MitkVtkRenderWindow->MakeCurrent();\n m_MitkVtkRenderWindow->Render();\n}\n\nvoid mitk::RenderWindow::Repaint()\n{\n m_MitkVtkRenderWindow->MakeCurrent();\n m_MitkVtkRenderWindow->Render();\n}\n\nvoid mitk::RenderWindow::SetSize(int w, int h)\n{\n m_MitkVtkRenderWindow->SetSize(w,h);\n}\n\nvoid mitk::RenderWindow::InitRenderer()\n{\n if(m_Renderer.IsNull())\n m_Renderer = mitk::OpenGLRenderer::New();\n\n m_MitkVtkRenderWindow->SetMitkRenderer(m_Renderer);\n\n m_Renderer->InitRenderer(this);\n\n int * size = m_MitkVtkRenderWindow->GetSize();\n if((size[0]>10) && (size[1]>10))\n m_Renderer->InitSize(size[0], size[1]);\n}\n\nvoid mitk::RenderWindow::SetWindowId(void * id)\n{\n m_MitkVtkRenderWindow->SetWindowId( id );\n}\n\nvoid mitk::RenderWindow::SetVtkRenderWindow(VtkRenderWindow* renWin)\n{\n if (renWin != NULL)\n {\n m_MitkVtkRenderWindow = renWin;\n InitRenderer();\n }\n}\n\nFIX: accept NULL as name\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nModule: $RCSfile$\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n#include \"mitkRenderWindow.h\"\n#include \"mitkVtkRenderWindow.h\"\n#include \"mitkOpenGLRenderer.h\"\n#include \n\nstd::set mitk::RenderWindow::instances;\n\nmitk::RenderWindow::RenderWindow(const char *name, mitk::BaseRenderer* renderer) \n : m_MitkVtkRenderWindow(NULL), m_Renderer(renderer)\n{\n if(name == NULL)\n m_Name = \"renderwindow\";\n else\n m_Name = name;\n instances.insert(this);\n m_MitkVtkRenderWindow = mitk::VtkRenderWindow::New();\n}\n\nmitk::RenderWindow::~RenderWindow()\n{\n instances.erase(this);\n m_Renderer = NULL;\n m_MitkVtkRenderWindow->Delete(); \/\/xxx\n}\n\nvoid mitk::RenderWindow::MakeCurrent() \n{\n m_MitkVtkRenderWindow->MakeCurrent();\n};\n\nvoid mitk::RenderWindow::SwapBuffers() \n{\n m_MitkVtkRenderWindow->Frame();\n};\n\nbool mitk::RenderWindow::IsSharing () const\n{\n return false;\n}\n\nvoid mitk::RenderWindow::Update()\n{\n m_MitkVtkRenderWindow->MakeCurrent();\n m_MitkVtkRenderWindow->Render();\n}\n\nvoid mitk::RenderWindow::Repaint()\n{\n m_MitkVtkRenderWindow->MakeCurrent();\n m_MitkVtkRenderWindow->Render();\n}\n\nvoid mitk::RenderWindow::SetSize(int w, int h)\n{\n m_MitkVtkRenderWindow->SetSize(w,h);\n}\n\nvoid mitk::RenderWindow::InitRenderer()\n{\n if(m_Renderer.IsNull())\n m_Renderer = mitk::OpenGLRenderer::New();\n\n m_MitkVtkRenderWindow->SetMitkRenderer(m_Renderer);\n\n m_Renderer->InitRenderer(this);\n\n int * size = m_MitkVtkRenderWindow->GetSize();\n if((size[0]>10) && (size[1]>10))\n m_Renderer->InitSize(size[0], size[1]);\n}\n\nvoid mitk::RenderWindow::SetWindowId(void * id)\n{\n m_MitkVtkRenderWindow->SetWindowId( id );\n}\n\nvoid mitk::RenderWindow::SetVtkRenderWindow(VtkRenderWindow* renWin)\n{\n if (renWin != NULL)\n {\n m_MitkVtkRenderWindow = renWin;\n InitRenderer();\n }\n}\n\n<|endoftext|>"} {"text":"\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"localplaingdbadapter.h\"\n\n#include \"gdbengine.h\"\n#include \"procinterrupt.h\"\n#include \"debuggerstringutils.h\"\n\n#include \n\n#include \n#include \n#include \n\nnamespace Debugger {\nnamespace Internal {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PlainGdbAdapter\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nLocalPlainGdbAdapter::LocalPlainGdbAdapter(GdbEngine *engine, QObject *parent)\n : AbstractPlainGdbAdapter(engine, parent)\n{\n \/\/ Output\n connect(&m_outputCollector, SIGNAL(byteDelivery(QByteArray)),\n engine, SLOT(readDebugeeOutput(QByteArray)));\n}\n\nAbstractGdbAdapter::DumperHandling LocalPlainGdbAdapter::dumperHandling() const\n{\n \/\/ LD_PRELOAD fails for System-Qt on Mac.\n#if defined(Q_OS_WIN) || defined(Q_OS_MAC)\n return DumperLoadedByGdb;\n#else\n return DumperLoadedByGdbPreload;\n#endif\n}\n\nvoid LocalPlainGdbAdapter::startAdapter()\n{\n QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());\n showMessage(_(\"TRYING TO START ADAPTER\"));\n\n QStringList gdbArgs;\n\n if (!m_outputCollector.listen()) {\n m_engine->handleAdapterStartFailed(tr(\"Cannot set up communication with child process: %1\")\n .arg(m_outputCollector.errorString()), QString());\n return;\n }\n gdbArgs.append(_(\"--tty=\") + m_outputCollector.serverName());\n\n if (!startParameters().workingDirectory.isEmpty())\n m_gdbProc.setWorkingDirectory(startParameters().workingDirectory);\n if (!startParameters().environment.isEmpty())\n m_gdbProc.setEnvironment(startParameters().environment);\n\n if (!m_engine->startGdb(gdbArgs)) {\n m_outputCollector.shutdown();\n return;\n }\n\n checkForReleaseBuild();\n m_engine->handleAdapterStarted();\n}\n\nvoid LocalPlainGdbAdapter::setupInferior()\n{\n AbstractPlainGdbAdapter::setupInferior();\n}\n\nvoid LocalPlainGdbAdapter::runEngine()\n{\n AbstractPlainGdbAdapter::runEngine();\n}\n\nvoid LocalPlainGdbAdapter::shutdownInferior()\n{\n m_engine->defaultInferiorShutdown(\"kill\");\n}\n\nvoid LocalPlainGdbAdapter::shutdownAdapter()\n{\n showMessage(_(\"PLAIN ADAPTER SHUTDOWN %1\").arg(state()));\n m_outputCollector.shutdown();\n m_engine->notifyAdapterShutdownOk();\n}\n\nvoid LocalPlainGdbAdapter::checkForReleaseBuild()\n{\n \/\/ Quick check for a \"release\" build\n QProcess proc;\n QStringList args;\n args.append(_(\"-h\"));\n args.append(_(\"-j\"));\n args.append(_(\".debug_info\"));\n args.append(startParameters().executable);\n proc.start(_(\"objdump\"), args);\n proc.closeWriteChannel();\n QTC_ASSERT(proc.waitForStarted(), qDebug() << \"UNABLE TO RUN OBJDUMP\");\n proc.waitForFinished();\n QByteArray ba = proc.readAllStandardOutput();\n \/\/ This should yield something like\n \/\/ \"debuggertest: file format elf32-i386\\n\\n\"\n \/\/ \"Sections:\\nIdx Name Size VMA LMA File off Algn\\n\"\n \/\/ \"30 .debug_info 00087d36 00000000 00000000 0006bbd5 2**0\\n\"\n \/\/ \" CONTENTS, READONLY, DEBUGGING\"\n if (ba.contains(\"Sections:\") && !ba.contains(\".debug_info\")) {\n m_engine->showMessageBox(QMessageBox::Information, \"Warning\",\n tr(\"This does not seem to be a \\\"Debug\\\" build.\\n\"\n \"Setting breakpoints by file name and line number may fail.\"));\n }\n}\n\nvoid LocalPlainGdbAdapter::interruptInferior()\n{\n const qint64 attachedPID = m_engine->inferiorPid();\n if (attachedPID <= 0) {\n showMessage(_(\"TRYING TO INTERRUPT INFERIOR BEFORE PID WAS OBTAINED\"));\n return;\n }\n\n if (!interruptProcess(attachedPID)) {\n showMessage(_(\"CANNOT INTERRUPT %1\").arg(attachedPID));\n m_engine->notifyInferiorStopFailed();\n }\n}\n\nQByteArray LocalPlainGdbAdapter::execFilePath() const\n{\n return QFileInfo(startParameters().executable)\n .absoluteFilePath().toLocal8Bit();\n}\n\nbool LocalPlainGdbAdapter::infoTargetNecessary() const\n{\n#ifdef Q_OS_LINUX\n return true;\n#else\n return false;\n#endif\n}\n\nQByteArray LocalPlainGdbAdapter::toLocalEncoding(const QString &s) const\n{\n return s.toLocal8Bit();\n}\n\nQString LocalPlainGdbAdapter::fromLocalEncoding(const QByteArray &b) const\n{\n return QString::fromLocal8Bit(b);\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Debugger\ndebugger: skip \"release build\" check if objdump could not be started\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"localplaingdbadapter.h\"\n\n#include \"gdbengine.h\"\n#include \"procinterrupt.h\"\n#include \"debuggerstringutils.h\"\n\n#include \n\n#include \n#include \n#include \n\nnamespace Debugger {\nnamespace Internal {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PlainGdbAdapter\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nLocalPlainGdbAdapter::LocalPlainGdbAdapter(GdbEngine *engine, QObject *parent)\n : AbstractPlainGdbAdapter(engine, parent)\n{\n \/\/ Output\n connect(&m_outputCollector, SIGNAL(byteDelivery(QByteArray)),\n engine, SLOT(readDebugeeOutput(QByteArray)));\n}\n\nAbstractGdbAdapter::DumperHandling LocalPlainGdbAdapter::dumperHandling() const\n{\n \/\/ LD_PRELOAD fails for System-Qt on Mac.\n#if defined(Q_OS_WIN) || defined(Q_OS_MAC)\n return DumperLoadedByGdb;\n#else\n return DumperLoadedByGdbPreload;\n#endif\n}\n\nvoid LocalPlainGdbAdapter::startAdapter()\n{\n QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());\n showMessage(_(\"TRYING TO START ADAPTER\"));\n\n QStringList gdbArgs;\n\n if (!m_outputCollector.listen()) {\n m_engine->handleAdapterStartFailed(tr(\"Cannot set up communication with child process: %1\")\n .arg(m_outputCollector.errorString()), QString());\n return;\n }\n gdbArgs.append(_(\"--tty=\") + m_outputCollector.serverName());\n\n if (!startParameters().workingDirectory.isEmpty())\n m_gdbProc.setWorkingDirectory(startParameters().workingDirectory);\n if (!startParameters().environment.isEmpty())\n m_gdbProc.setEnvironment(startParameters().environment);\n\n if (!m_engine->startGdb(gdbArgs)) {\n m_outputCollector.shutdown();\n return;\n }\n\n checkForReleaseBuild();\n m_engine->handleAdapterStarted();\n}\n\nvoid LocalPlainGdbAdapter::setupInferior()\n{\n AbstractPlainGdbAdapter::setupInferior();\n}\n\nvoid LocalPlainGdbAdapter::runEngine()\n{\n AbstractPlainGdbAdapter::runEngine();\n}\n\nvoid LocalPlainGdbAdapter::shutdownInferior()\n{\n m_engine->defaultInferiorShutdown(\"kill\");\n}\n\nvoid LocalPlainGdbAdapter::shutdownAdapter()\n{\n showMessage(_(\"PLAIN ADAPTER SHUTDOWN %1\").arg(state()));\n m_outputCollector.shutdown();\n m_engine->notifyAdapterShutdownOk();\n}\n\nvoid LocalPlainGdbAdapter::checkForReleaseBuild()\n{\n \/\/ Quick check for a \"release\" build\n QProcess proc;\n QStringList args;\n args.append(_(\"-h\"));\n args.append(_(\"-j\"));\n args.append(_(\".debug_info\"));\n args.append(startParameters().executable);\n proc.start(_(\"objdump\"), args);\n proc.closeWriteChannel();\n if (!proc.waitForStarted()) {\n showMessage(_(\"OBJDUMP PROCESS COULD NOT BE STARTED. \"\n \"RELEASE BUILD CHECK WILL FAIL\"));\n return;\n }\n proc.waitForFinished();\n QByteArray ba = proc.readAllStandardOutput();\n \/\/ This should yield something like\n \/\/ \"debuggertest: file format elf32-i386\\n\\n\"\n \/\/ \"Sections:\\nIdx Name Size VMA LMA File off Algn\\n\"\n \/\/ \"30 .debug_info 00087d36 00000000 00000000 0006bbd5 2**0\\n\"\n \/\/ \" CONTENTS, READONLY, DEBUGGING\"\n if (ba.contains(\"Sections:\") && !ba.contains(\".debug_info\")) {\n m_engine->showMessageBox(QMessageBox::Information, \"Warning\",\n tr(\"This does not seem to be a \\\"Debug\\\" build.\\n\"\n \"Setting breakpoints by file name and line number may fail.\"));\n }\n}\n\nvoid LocalPlainGdbAdapter::interruptInferior()\n{\n const qint64 attachedPID = m_engine->inferiorPid();\n if (attachedPID <= 0) {\n showMessage(_(\"TRYING TO INTERRUPT INFERIOR BEFORE PID WAS OBTAINED\"));\n return;\n }\n\n if (!interruptProcess(attachedPID)) {\n showMessage(_(\"CANNOT INTERRUPT %1\").arg(attachedPID));\n m_engine->notifyInferiorStopFailed();\n }\n}\n\nQByteArray LocalPlainGdbAdapter::execFilePath() const\n{\n return QFileInfo(startParameters().executable)\n .absoluteFilePath().toLocal8Bit();\n}\n\nbool LocalPlainGdbAdapter::infoTargetNecessary() const\n{\n#ifdef Q_OS_LINUX\n return true;\n#else\n return false;\n#endif\n}\n\nQByteArray LocalPlainGdbAdapter::toLocalEncoding(const QString &s) const\n{\n return s.toLocal8Bit();\n}\n\nQString LocalPlainGdbAdapter::fromLocalEncoding(const QByteArray &b) const\n{\n return QString::fromLocal8Bit(b);\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Debugger\n<|endoftext|>"} {"text":"\/*ckwg +5\n * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include \"multiplication_process.h\"\n\n#include \n\n#include \n#include \n#include \n\n#include \n\nnamespace vistk\n{\n\nclass multiplication_process::priv\n{\n public:\n typedef uint32_t number_t;\n\n priv();\n ~priv();\n\n edge_ref_t input_edge_factor1;\n edge_ref_t input_edge_factor2;\n edge_group_t output_edges;\n\n port_info_t factor1_port_info;\n port_info_t factor2_port_info;\n port_info_t output_port_info;\n\n static port_t const INPUT_FACTOR1_PORT_NAME;\n static port_t const INPUT_FACTOR2_PORT_NAME;\n static port_t const OUTPUT_PORT_NAME;\n};\n\nprocess::port_t const multiplication_process::priv::INPUT_FACTOR1_PORT_NAME = process::port_t(\"factor1\");\nprocess::port_t const multiplication_process::priv::INPUT_FACTOR2_PORT_NAME = process::port_t(\"factor2\");\nprocess::port_t const multiplication_process::priv::OUTPUT_PORT_NAME = process::port_t(\"product\");\n\nmultiplication_process\n::multiplication_process(config_t const& config)\n : process(config)\n{\n d = boost::shared_ptr(new priv);\n}\n\nmultiplication_process\n::~multiplication_process()\n{\n}\n\nvoid\nmultiplication_process\n::_step()\n{\n datum_t dat;\n stamp_t st;\n\n edge_group_t input_edges;\n\n input_edges.push_back(d->input_edge_factor1);\n input_edges.push_back(d->input_edge_factor2);\n\n bool const colored = same_colored_edges(input_edges);\n bool const syncd = syncd_edges(input_edges);\n\n if (!colored)\n {\n st = heartbeat_stamp();\n\n dat = datum::error_datum(\"The input edges are not colored the same.\");\n }\n else if (!syncd)\n {\n st = heartbeat_stamp();\n\n dat = datum::error_datum(\"The input edges are not synchronized.\");\n }\n else\n {\n edge_datum_t const factor1_dat = grab_from_edge_ref(d->input_edge_factor1);\n edge_datum_t const factor2_dat = grab_from_edge_ref(d->input_edge_factor2);\n\n edge_data_t input_dats;\n\n input_dats.push_back(factor1_dat);\n input_dats.push_back(factor2_dat);\n\n st = factor1_dat.get<1>();\n\n datum::datum_type_t const max_type = max_status(input_dats);\n\n switch (max_type)\n {\n case datum::DATUM_DATA:\n {\n priv::number_t const factor1 = factor1_dat.get<0>()->get_datum();\n priv::number_t const factor2 = factor2_dat.get<0>()->get_datum();\n\n priv::number_t const product = factor1 * factor2;\n\n dat = datum::new_datum(product);\n break;\n }\n case datum::DATUM_EMPTY:\n dat = datum::empty_datum();\n break;\n case datum::DATUM_COMPLETE:\n mark_as_complete();\n dat = datum::complete_datum();\n break;\n case datum::DATUM_ERROR:\n dat = datum::error_datum(\"Error on the input edges.\");\n break;\n case datum::DATUM_INVALID:\n default:\n dat = datum::error_datum(\"Unrecognized datum type.\");\n break;\n }\n }\n\n edge_datum_t const edat = edge_datum_t(dat, st);\n\n push_to_edges(d->output_edges, edat);\n\n process::_step();\n}\n\nvoid\nmultiplication_process\n::_connect_input_port(port_t const& port, edge_t edge)\n{\n if (port == priv::INPUT_FACTOR1_PORT_NAME)\n {\n if (d->input_edge_factor1.use_count())\n {\n throw port_reconnect_exception(name(), port);\n }\n\n d->input_edge_factor1 = edge_ref_t(edge);\n\n return;\n }\n if (port == priv::INPUT_FACTOR2_PORT_NAME)\n {\n if (d->input_edge_factor2.use_count())\n {\n throw port_reconnect_exception(name(), port);\n }\n\n d->input_edge_factor2 = edge_ref_t(edge);\n\n return;\n }\n\n process::_connect_input_port(port, edge);\n}\n\nprocess::port_info_t\nmultiplication_process\n::_input_port_info(port_t const& port) const\n{\n if (port == priv::INPUT_FACTOR1_PORT_NAME)\n {\n return d->factor1_port_info;\n }\n if (port == priv::INPUT_FACTOR2_PORT_NAME)\n {\n return d->factor2_port_info;\n }\n\n return process::_input_port_info(port);\n}\n\nvoid\nmultiplication_process\n::_connect_output_port(port_t const& port, edge_t edge)\n{\n if (port == priv::OUTPUT_PORT_NAME)\n {\n d->output_edges.push_back(edge_ref_t(edge));\n\n return;\n }\n\n process::_connect_output_port(port, edge);\n}\n\nprocess::port_info_t\nmultiplication_process\n::_output_port_info(port_t const& port) const\n{\n if (port == priv::OUTPUT_PORT_NAME)\n {\n return d->output_port_info;\n }\n\n return process::_output_port_info(port);\n}\n\nprocess::ports_t\nmultiplication_process\n::_input_ports() const\n{\n ports_t ports;\n\n ports.push_back(priv::INPUT_FACTOR1_PORT_NAME);\n ports.push_back(priv::INPUT_FACTOR2_PORT_NAME);\n\n return ports;\n}\n\nprocess::ports_t\nmultiplication_process\n::_output_ports() const\n{\n ports_t ports;\n\n ports.push_back(priv::OUTPUT_PORT_NAME);\n\n return ports;\n}\n\nmultiplication_process::priv\n::priv()\n{\n port_flags_t required;\n\n required.insert(flag_required);\n\n factor1_port_info = port_info_t(new port_info(\n port_types::t_integer,\n required,\n port_description_t(\"The first factor to multiply.\")));\n factor2_port_info = port_info_t(new port_info(\n port_types::t_integer,\n required,\n port_description_t(\"The second factor to multiply.\")));\n output_port_info = port_info_t(new port_info(\n port_types::t_integer,\n required,\n port_description_t(\"Where the product will be available.\")));\n}\n\nmultiplication_process::priv\n::~priv()\n{\n}\n\n}\nCollect all input edges as received\/*ckwg +5\n * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include \"multiplication_process.h\"\n\n#include \n\n#include \n#include \n#include \n\n#include \n\nnamespace vistk\n{\n\nclass multiplication_process::priv\n{\n public:\n typedef uint32_t number_t;\n\n priv();\n ~priv();\n\n edge_ref_t input_edge_factor1;\n edge_ref_t input_edge_factor2;\n\n edge_group_t input_edges;\n edge_group_t output_edges;\n\n port_info_t factor1_port_info;\n port_info_t factor2_port_info;\n port_info_t output_port_info;\n\n static port_t const INPUT_FACTOR1_PORT_NAME;\n static port_t const INPUT_FACTOR2_PORT_NAME;\n static port_t const OUTPUT_PORT_NAME;\n};\n\nprocess::port_t const multiplication_process::priv::INPUT_FACTOR1_PORT_NAME = process::port_t(\"factor1\");\nprocess::port_t const multiplication_process::priv::INPUT_FACTOR2_PORT_NAME = process::port_t(\"factor2\");\nprocess::port_t const multiplication_process::priv::OUTPUT_PORT_NAME = process::port_t(\"product\");\n\nmultiplication_process\n::multiplication_process(config_t const& config)\n : process(config)\n{\n d = boost::shared_ptr(new priv);\n}\n\nmultiplication_process\n::~multiplication_process()\n{\n}\n\nvoid\nmultiplication_process\n::_step()\n{\n datum_t dat;\n stamp_t st;\n\n bool const colored = same_colored_edges(d->input_edges);\n bool const syncd = syncd_edges(d->input_edges);\n\n if (!colored)\n {\n st = heartbeat_stamp();\n\n dat = datum::error_datum(\"The input edges are not colored the same.\");\n }\n else if (!syncd)\n {\n st = heartbeat_stamp();\n\n dat = datum::error_datum(\"The input edges are not synchronized.\");\n }\n else\n {\n edge_datum_t const factor1_dat = grab_from_edge_ref(d->input_edge_factor1);\n edge_datum_t const factor2_dat = grab_from_edge_ref(d->input_edge_factor2);\n\n edge_data_t input_dats;\n\n input_dats.push_back(factor1_dat);\n input_dats.push_back(factor2_dat);\n\n st = factor1_dat.get<1>();\n\n datum::datum_type_t const max_type = max_status(input_dats);\n\n switch (max_type)\n {\n case datum::DATUM_DATA:\n {\n priv::number_t const factor1 = factor1_dat.get<0>()->get_datum();\n priv::number_t const factor2 = factor2_dat.get<0>()->get_datum();\n\n priv::number_t const product = factor1 * factor2;\n\n dat = datum::new_datum(product);\n break;\n }\n case datum::DATUM_EMPTY:\n dat = datum::empty_datum();\n break;\n case datum::DATUM_COMPLETE:\n mark_as_complete();\n dat = datum::complete_datum();\n break;\n case datum::DATUM_ERROR:\n dat = datum::error_datum(\"Error on the input edges.\");\n break;\n case datum::DATUM_INVALID:\n default:\n dat = datum::error_datum(\"Unrecognized datum type.\");\n break;\n }\n }\n\n edge_datum_t const edat = edge_datum_t(dat, st);\n\n push_to_edges(d->output_edges, edat);\n\n process::_step();\n}\n\nvoid\nmultiplication_process\n::_connect_input_port(port_t const& port, edge_t edge)\n{\n if (port == priv::INPUT_FACTOR1_PORT_NAME)\n {\n if (d->input_edge_factor1.use_count())\n {\n throw port_reconnect_exception(name(), port);\n }\n\n d->input_edge_factor1 = edge_ref_t(edge);\n d->input_edges.push_back(d->input_edge_factor1);\n\n return;\n }\n if (port == priv::INPUT_FACTOR2_PORT_NAME)\n {\n if (d->input_edge_factor2.use_count())\n {\n throw port_reconnect_exception(name(), port);\n }\n\n d->input_edge_factor2 = edge_ref_t(edge);\n d->input_edges.push_back(d->input_edge_factor2);\n\n return;\n }\n\n process::_connect_input_port(port, edge);\n}\n\nprocess::port_info_t\nmultiplication_process\n::_input_port_info(port_t const& port) const\n{\n if (port == priv::INPUT_FACTOR1_PORT_NAME)\n {\n return d->factor1_port_info;\n }\n if (port == priv::INPUT_FACTOR2_PORT_NAME)\n {\n return d->factor2_port_info;\n }\n\n return process::_input_port_info(port);\n}\n\nvoid\nmultiplication_process\n::_connect_output_port(port_t const& port, edge_t edge)\n{\n if (port == priv::OUTPUT_PORT_NAME)\n {\n d->output_edges.push_back(edge_ref_t(edge));\n\n return;\n }\n\n process::_connect_output_port(port, edge);\n}\n\nprocess::port_info_t\nmultiplication_process\n::_output_port_info(port_t const& port) const\n{\n if (port == priv::OUTPUT_PORT_NAME)\n {\n return d->output_port_info;\n }\n\n return process::_output_port_info(port);\n}\n\nprocess::ports_t\nmultiplication_process\n::_input_ports() const\n{\n ports_t ports;\n\n ports.push_back(priv::INPUT_FACTOR1_PORT_NAME);\n ports.push_back(priv::INPUT_FACTOR2_PORT_NAME);\n\n return ports;\n}\n\nprocess::ports_t\nmultiplication_process\n::_output_ports() const\n{\n ports_t ports;\n\n ports.push_back(priv::OUTPUT_PORT_NAME);\n\n return ports;\n}\n\nmultiplication_process::priv\n::priv()\n{\n port_flags_t required;\n\n required.insert(flag_required);\n\n factor1_port_info = port_info_t(new port_info(\n port_types::t_integer,\n required,\n port_description_t(\"The first factor to multiply.\")));\n factor2_port_info = port_info_t(new port_info(\n port_types::t_integer,\n required,\n port_description_t(\"The second factor to multiply.\")));\n output_port_info = port_info_t(new port_info(\n port_types::t_integer,\n required,\n port_description_t(\"Where the product will be available.\")));\n}\n\nmultiplication_process::priv\n::~priv()\n{\n}\n\n}\n<|endoftext|>"} {"text":"\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 2001 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 2001, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * .\n *\/\n\n\/*\n * $Id$\n *\/\n\n#if !defined(COMPLEXTYPEINFO_HPP)\n#define COMPLEXTYPEINFO_HPP\n\n\n\/**\n * The class act as a place holder to store complex type information.\n *\n * The class is intended for internal use.\n *\/\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nXERCES_CPP_NAMESPACE_BEGIN\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Forward Declarations\n\/\/ ---------------------------------------------------------------------------\nclass DatatypeValidator;\nclass ContentSpecNode;\nclass SchemaAttDefList;\nclass SchemaElementDecl;\nclass XSDLocator;\n\n\nclass VALIDATORS_EXPORT ComplexTypeInfo\n{\npublic:\n \/\/ -----------------------------------------------------------------------\n \/\/ Public Constructors\/Destructor\n \/\/ -----------------------------------------------------------------------\n ComplexTypeInfo();\n ~ComplexTypeInfo();\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Getter methods\n \/\/ -----------------------------------------------------------------------\n bool getAbstract() const;\n bool getAdoptContentSpec() const;\n bool containsAttWithTypeId() const;\n bool getPreprocessed() const;\n int getDerivedBy() const;\n int getBlockSet() const;\n int getFinalSet() const;\n int getScopeDefined() const;\n unsigned int getElementId() const;\n int getContentType() const;\n unsigned int elementCount() const;\n XMLCh* getTypeName() const;\n DatatypeValidator* getBaseDatatypeValidator() const;\n DatatypeValidator* getDatatypeValidator() const;\n ComplexTypeInfo* getBaseComplexTypeInfo() const;\n ContentSpecNode* getContentSpec() const;\n const SchemaAttDef* getAttWildCard() const;\n SchemaAttDef* getAttWildCard();\n const SchemaAttDef* getAttDef(const XMLCh* const baseName,\n const int uriId) const;\n SchemaAttDef* getAttDef(const XMLCh* const baseName,\n const int uriId);\n XMLAttDefList& getAttDefList() const;\n const SchemaElementDecl* elementAt(const unsigned int index) const;\n SchemaElementDecl* elementAt(const unsigned int index);\n XMLContentModel* getContentModel(const bool checkUPA = false);\n const XMLCh* getFormattedContentModel () const;\n XSDLocator* getLocator() const;\n\n \/**\n * returns true if this type is anonymous\n **\/\n bool getAnonymous() const;\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Setter methods\n \/\/ -----------------------------------------------------------------------\n void setAbstract(const bool isAbstract);\n void setAdoptContentSpec(const bool toAdopt);\n void setAttWithTypeId(const bool value);\n void setPreprocessed(const bool aValue = true);\n void setDerivedBy(const int derivedBy);\n void setBlockSet(const int blockSet);\n void setFinalSet(const int finalSet);\n void setScopeDefined(const int scopeDefined);\n void setElementId(const unsigned int elemId);\n void setTypeName(const XMLCh* const typeName);\n void setContentType(const int contentType);\n void setBaseDatatypeValidator(DatatypeValidator* const baseValidator);\n void setDatatypeValidator(DatatypeValidator* const validator);\n void setBaseComplexTypeInfo(ComplexTypeInfo* const typeInfo);\n void setContentSpec(ContentSpecNode* const toAdopt);\n void setAttWildCard(SchemaAttDef* const toAdopt);\n void addAttDef(SchemaAttDef* const toAdd);\n void addElement(SchemaElementDecl* const toAdd);\n void setContentModel(XMLContentModel* const newModelToAdopt);\n void setLocator(XSDLocator* const aLocator);\n\n \/**\n * sets this type to be anonymous\n **\/\n void setAnonymous(); \n\n \/\/ -----------------------------------------------------------------------\n \/\/ Helper methods\n \/\/ -----------------------------------------------------------------------\n bool hasAttDefs() const;\n bool contains(const XMLCh* const attName);\n XMLAttDef* findAttr\n (\n const XMLCh* const qName\n , const unsigned int uriId\n , const XMLCh* const baseName\n , const XMLCh* const prefix\n , const XMLElementDecl::LookupOpts options\n , bool& wasAdded\n ) const;\n bool resetDefs();\n void checkUniqueParticleAttribution\n (\n SchemaGrammar* const pGrammar\n , GrammarResolver* const pGrammarResolver\n , XMLStringPool* const pStringPool\n , XMLValidator* const pValidator\n ) ;\n\nprivate:\n \/\/ -----------------------------------------------------------------------\n \/\/ Unimplemented contstructors and operators\n \/\/ -----------------------------------------------------------------------\n ComplexTypeInfo(const ComplexTypeInfo& elemInfo);\n ComplexTypeInfo& operator= (const ComplexTypeInfo& other);\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Private helper methods\n \/\/ -----------------------------------------------------------------------\n void faultInAttDefList() const;\n XMLContentModel* createChildModel(ContentSpecNode* specNode, const bool isMixed);\n XMLContentModel* makeContentModel(const bool checkUPA = false, ContentSpecNode* const specNode = 0);\n XMLCh* formatContentModel () const ;\n ContentSpecNode* expandContentModel(ContentSpecNode* const curNode, const int minOccurs, const int maxOccurs);\n ContentSpecNode* convertContentSpecTree(ContentSpecNode* const curNode, const bool checkUPA = false);\n void resizeContentSpecOrgURI();\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Private data members\n \/\/ -----------------------------------------------------------------------\n bool fAbstract;\n bool fAdoptContentSpec;\n bool fAttWithTypeId;\n bool fPreprocessed;\n int fDerivedBy;\n int fBlockSet;\n int fFinalSet;\n int fScopeDefined;\n unsigned int fElementId;\n int fContentType;\n XMLCh* fTypeName;\n DatatypeValidator* fBaseDatatypeValidator;\n DatatypeValidator* fDatatypeValidator;\n ComplexTypeInfo* fBaseComplexTypeInfo;\n ContentSpecNode* fContentSpec;\n SchemaAttDef* fAttWildCard;\n RefHash2KeysTableOf* fAttDefs;\n SchemaAttDefList* fAttList;\n RefVectorOf* fElements;\n XMLContentModel* fContentModel;\n XMLCh* fFormattedModel;\n unsigned int* fContentSpecOrgURI;\n unsigned int fUniqueURI;\n unsigned int fContentSpecOrgURISize;\n RefVectorOf* fSpecNodesToDelete;\n XSDLocator* fLocator;\n bool fAnonymous; \n};\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ ComplexTypeInfo: Getter methods\n\/\/ ---------------------------------------------------------------------------\ninline bool ComplexTypeInfo::getAbstract() const {\n\n return fAbstract;\n}\n\ninline bool ComplexTypeInfo::getAdoptContentSpec() const {\n\n return fAdoptContentSpec;\n}\n\ninline bool ComplexTypeInfo::containsAttWithTypeId() const {\n\n return fAttWithTypeId;\n}\n\ninline bool ComplexTypeInfo::getPreprocessed() const {\n\n return fPreprocessed;\n}\n\ninline int ComplexTypeInfo::getDerivedBy() const {\n\n return fDerivedBy;\n}\n\ninline int ComplexTypeInfo::getBlockSet() const {\n\n return fBlockSet;\n}\n\ninline int ComplexTypeInfo::getFinalSet() const {\n\n return fFinalSet;\n}\n\ninline int ComplexTypeInfo::getScopeDefined() const {\n\n return fScopeDefined;\n}\n\ninline unsigned int ComplexTypeInfo::getElementId() const {\n\n return fElementId;\n}\n\ninline int ComplexTypeInfo::getContentType() const {\n\n return fContentType;\n}\n\ninline unsigned int ComplexTypeInfo::elementCount() const {\n\n if (fElements) {\n return fElements->size();\n }\n\n return 0;\n}\n\ninline XMLCh* ComplexTypeInfo::getTypeName() const {\n\n return fTypeName;\n}\n\ninline DatatypeValidator* ComplexTypeInfo::getBaseDatatypeValidator() const {\n\n return fBaseDatatypeValidator;\n}\n\ninline DatatypeValidator* ComplexTypeInfo::getDatatypeValidator() const {\n\n return fDatatypeValidator;\n}\n\ninline ComplexTypeInfo* ComplexTypeInfo::getBaseComplexTypeInfo() const {\n\n return fBaseComplexTypeInfo;\n}\n\ninline ContentSpecNode* ComplexTypeInfo::getContentSpec() const {\n\n return fContentSpec;\n}\n\ninline const SchemaAttDef* ComplexTypeInfo::getAttWildCard() const {\n\n return fAttWildCard;\n}\n\ninline SchemaAttDef* ComplexTypeInfo::getAttWildCard() {\n\n return fAttWildCard;\n}\n\ninline const SchemaAttDef* ComplexTypeInfo::getAttDef(const XMLCh* const baseName,\n const int uriId) const {\n\n \/\/ If no list, then return a null\n if (!fAttDefs)\n return 0;\n\n return fAttDefs->get(baseName, uriId);\n}\n\ninline SchemaAttDef* ComplexTypeInfo::getAttDef(const XMLCh* const baseName,\n const int uriId)\n{\n \/\/ If no list, then return a null\n if (!fAttDefs)\n return 0;\n\n return fAttDefs->get(baseName, uriId);\n}\n\ninline SchemaElementDecl*\nComplexTypeInfo::elementAt(const unsigned int index) {\n\n if (!fElements) {\n return 0; \/\/ REVISIT - need to throw an exception\n }\n\n return fElements->elementAt(index);\n}\n\ninline const SchemaElementDecl*\nComplexTypeInfo::elementAt(const unsigned int index) const {\n\n if (!fElements) {\n return 0; \/\/ REVISIT - need to throw an exception\n }\n\n return fElements->elementAt(index);\n}\n\ninline XMLContentModel* ComplexTypeInfo::getContentModel(const bool checkUPA)\n{\n if (!fContentModel)\n fContentModel = makeContentModel(checkUPA);\n\n return fContentModel;\n}\n\ninline XSDLocator* ComplexTypeInfo::getLocator() const\n{\n return fLocator;\n}\n\ninline bool ComplexTypeInfo::getAnonymous() const {\n return fAnonymous;\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ ComplexTypeInfo: Setter methods\n\/\/ ---------------------------------------------------------------------------\ninline void ComplexTypeInfo::setAbstract(const bool isAbstract) {\n\n fAbstract = isAbstract;\n}\n\ninline void ComplexTypeInfo::setAdoptContentSpec(const bool toAdopt) {\n\n fAdoptContentSpec = toAdopt;\n}\n\ninline void ComplexTypeInfo::setAttWithTypeId(const bool value) {\n\n fAttWithTypeId = value;\n}\n\ninline void ComplexTypeInfo::setPreprocessed(const bool aValue) {\n\n fPreprocessed = aValue;\n}\n\ninline void ComplexTypeInfo::setDerivedBy(const int derivedBy) {\n\n fDerivedBy = derivedBy;\n}\n\ninline void ComplexTypeInfo::setBlockSet(const int blockSet) {\n\n fBlockSet = blockSet;\n}\n\ninline void ComplexTypeInfo::setFinalSet(const int finalSet) {\n\n fFinalSet = finalSet;\n}\n\ninline void ComplexTypeInfo::setScopeDefined(const int scopeDefined) {\n\n fScopeDefined = scopeDefined;\n}\n\ninline void ComplexTypeInfo::setElementId(const unsigned int elemId) {\n\n fElementId = elemId;\n}\n\ninline void\nComplexTypeInfo::setContentType(const int contentType) {\n\n fContentType = contentType;\n}\n\ninline void ComplexTypeInfo::setTypeName(const XMLCh* const typeName) {\n\n if (fTypeName != 0) {\n delete [] fTypeName;\n }\n\n fTypeName = XMLString::replicate(typeName);\n}\n\ninline void\nComplexTypeInfo::setBaseDatatypeValidator(DatatypeValidator* const validator) {\n\n fBaseDatatypeValidator = validator;\n}\n\ninline void\nComplexTypeInfo::setDatatypeValidator(DatatypeValidator* const validator) {\n\n fDatatypeValidator = validator;\n}\n\ninline void\nComplexTypeInfo::setBaseComplexTypeInfo(ComplexTypeInfo* const typeInfo) {\n\n fBaseComplexTypeInfo = typeInfo;\n}\n\ninline void ComplexTypeInfo::addElement(SchemaElementDecl* const elem) {\n\n if (!fElements) {\n fElements = new RefVectorOf(8, false);\n }\n else if (fElements->containsElement(elem)) {\n return;\n }\n\n fElements->addElement(elem);\n}\n\ninline void ComplexTypeInfo::setAttWildCard(SchemaAttDef* const toAdopt) {\n\n if (fAttWildCard) {\n delete fAttWildCard;\n }\n\n fAttWildCard = toAdopt;\n}\n\ninline void\nComplexTypeInfo::setContentModel(XMLContentModel* const newModelToAdopt)\n{\n delete fContentModel;\n fContentModel = newModelToAdopt;\n}\n\n\n\ninline void ComplexTypeInfo::setAnonymous() {\n fAnonymous = true;\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ ComplexTypeInfo: Helper methods\n\/\/ ---------------------------------------------------------------------------\ninline bool ComplexTypeInfo::hasAttDefs() const\n{\n \/\/ If the collection hasn't been faulted in, then no att defs\n if (!fAttDefs)\n return false;\n\n return !fAttDefs->isEmpty();\n}\n\ninline bool ComplexTypeInfo::contains(const XMLCh* const attName) {\n\n if (!fAttDefs) {\n return false;\n }\n\n RefHash2KeysTableOfEnumerator enumDefs(fAttDefs);\n\n while (enumDefs.hasMoreElements()) {\n\n if (XMLString::equals(attName, enumDefs.nextElement().getAttName()->getLocalPart())) {\n return true;\n }\n }\n\n return false;\n}\n\nXERCES_CPP_NAMESPACE_END\n\n#endif\n\n\/**\n * End of file ComplexTypeInfo.hpp\n *\/\n\nPerformance: move declaration around can help optimization\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 2001 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 2001, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * .\n *\/\n\n\/*\n * $Id$\n *\/\n\n#if !defined(COMPLEXTYPEINFO_HPP)\n#define COMPLEXTYPEINFO_HPP\n\n\n\/**\n * The class act as a place holder to store complex type information.\n *\n * The class is intended for internal use.\n *\/\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nXERCES_CPP_NAMESPACE_BEGIN\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Forward Declarations\n\/\/ ---------------------------------------------------------------------------\nclass DatatypeValidator;\nclass ContentSpecNode;\nclass SchemaAttDefList;\nclass SchemaElementDecl;\nclass XSDLocator;\n\n\nclass VALIDATORS_EXPORT ComplexTypeInfo\n{\npublic:\n \/\/ -----------------------------------------------------------------------\n \/\/ Public Constructors\/Destructor\n \/\/ -----------------------------------------------------------------------\n ComplexTypeInfo();\n ~ComplexTypeInfo();\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Getter methods\n \/\/ -----------------------------------------------------------------------\n bool getAbstract() const;\n bool getAdoptContentSpec() const;\n bool containsAttWithTypeId() const;\n bool getPreprocessed() const;\n int getDerivedBy() const;\n int getBlockSet() const;\n int getFinalSet() const;\n int getScopeDefined() const;\n unsigned int getElementId() const;\n int getContentType() const;\n unsigned int elementCount() const;\n XMLCh* getTypeName() const;\n DatatypeValidator* getBaseDatatypeValidator() const;\n DatatypeValidator* getDatatypeValidator() const;\n ComplexTypeInfo* getBaseComplexTypeInfo() const;\n ContentSpecNode* getContentSpec() const;\n const SchemaAttDef* getAttWildCard() const;\n SchemaAttDef* getAttWildCard();\n const SchemaAttDef* getAttDef(const XMLCh* const baseName,\n const int uriId) const;\n SchemaAttDef* getAttDef(const XMLCh* const baseName,\n const int uriId);\n XMLAttDefList& getAttDefList() const;\n const SchemaElementDecl* elementAt(const unsigned int index) const;\n SchemaElementDecl* elementAt(const unsigned int index);\n XMLContentModel* getContentModel(const bool checkUPA = false);\n const XMLCh* getFormattedContentModel () const;\n XSDLocator* getLocator() const;\n\n \/**\n * returns true if this type is anonymous\n **\/\n bool getAnonymous() const;\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Setter methods\n \/\/ -----------------------------------------------------------------------\n void setAbstract(const bool isAbstract);\n void setAdoptContentSpec(const bool toAdopt);\n void setAttWithTypeId(const bool value);\n void setPreprocessed(const bool aValue = true);\n void setDerivedBy(const int derivedBy);\n void setBlockSet(const int blockSet);\n void setFinalSet(const int finalSet);\n void setScopeDefined(const int scopeDefined);\n void setElementId(const unsigned int elemId);\n void setTypeName(const XMLCh* const typeName);\n void setContentType(const int contentType);\n void setBaseDatatypeValidator(DatatypeValidator* const baseValidator);\n void setDatatypeValidator(DatatypeValidator* const validator);\n void setBaseComplexTypeInfo(ComplexTypeInfo* const typeInfo);\n void setContentSpec(ContentSpecNode* const toAdopt);\n void setAttWildCard(SchemaAttDef* const toAdopt);\n void addAttDef(SchemaAttDef* const toAdd);\n void addElement(SchemaElementDecl* const toAdd);\n void setContentModel(XMLContentModel* const newModelToAdopt);\n void setLocator(XSDLocator* const aLocator);\n\n \/**\n * sets this type to be anonymous\n **\/\n void setAnonymous();\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Helper methods\n \/\/ -----------------------------------------------------------------------\n bool hasAttDefs() const;\n bool contains(const XMLCh* const attName);\n XMLAttDef* findAttr\n (\n const XMLCh* const qName\n , const unsigned int uriId\n , const XMLCh* const baseName\n , const XMLCh* const prefix\n , const XMLElementDecl::LookupOpts options\n , bool& wasAdded\n ) const;\n bool resetDefs();\n void checkUniqueParticleAttribution\n (\n SchemaGrammar* const pGrammar\n , GrammarResolver* const pGrammarResolver\n , XMLStringPool* const pStringPool\n , XMLValidator* const pValidator\n ) ;\n\nprivate:\n \/\/ -----------------------------------------------------------------------\n \/\/ Unimplemented contstructors and operators\n \/\/ -----------------------------------------------------------------------\n ComplexTypeInfo(const ComplexTypeInfo& elemInfo);\n ComplexTypeInfo& operator= (const ComplexTypeInfo& other);\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Private helper methods\n \/\/ -----------------------------------------------------------------------\n void faultInAttDefList() const;\n XMLContentModel* createChildModel(ContentSpecNode* specNode, const bool isMixed);\n XMLContentModel* makeContentModel(const bool checkUPA = false, ContentSpecNode* const specNode = 0);\n XMLCh* formatContentModel () const ;\n ContentSpecNode* expandContentModel(ContentSpecNode* const curNode, const int minOccurs, const int maxOccurs);\n ContentSpecNode* convertContentSpecTree(ContentSpecNode* const curNode, const bool checkUPA = false);\n void resizeContentSpecOrgURI();\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Private data members\n \/\/ -----------------------------------------------------------------------\n bool fAbstract;\n bool fAdoptContentSpec;\n bool fAttWithTypeId;\n bool fPreprocessed;\n int fDerivedBy;\n int fBlockSet;\n int fFinalSet;\n int fScopeDefined;\n unsigned int fElementId;\n int fContentType;\n XMLCh* fTypeName;\n DatatypeValidator* fBaseDatatypeValidator;\n DatatypeValidator* fDatatypeValidator;\n ComplexTypeInfo* fBaseComplexTypeInfo;\n ContentSpecNode* fContentSpec;\n SchemaAttDef* fAttWildCard;\n SchemaAttDefList* fAttList;\n RefVectorOf* fElements;\n RefVectorOf* fSpecNodesToDelete;\n RefHash2KeysTableOf* fAttDefs;\n XMLContentModel* fContentModel;\n XMLCh* fFormattedModel;\n unsigned int* fContentSpecOrgURI;\n unsigned int fUniqueURI;\n unsigned int fContentSpecOrgURISize;\n XSDLocator* fLocator;\n bool fAnonymous;\n};\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ ComplexTypeInfo: Getter methods\n\/\/ ---------------------------------------------------------------------------\ninline bool ComplexTypeInfo::getAbstract() const {\n\n return fAbstract;\n}\n\ninline bool ComplexTypeInfo::getAdoptContentSpec() const {\n\n return fAdoptContentSpec;\n}\n\ninline bool ComplexTypeInfo::containsAttWithTypeId() const {\n\n return fAttWithTypeId;\n}\n\ninline bool ComplexTypeInfo::getPreprocessed() const {\n\n return fPreprocessed;\n}\n\ninline int ComplexTypeInfo::getDerivedBy() const {\n\n return fDerivedBy;\n}\n\ninline int ComplexTypeInfo::getBlockSet() const {\n\n return fBlockSet;\n}\n\ninline int ComplexTypeInfo::getFinalSet() const {\n\n return fFinalSet;\n}\n\ninline int ComplexTypeInfo::getScopeDefined() const {\n\n return fScopeDefined;\n}\n\ninline unsigned int ComplexTypeInfo::getElementId() const {\n\n return fElementId;\n}\n\ninline int ComplexTypeInfo::getContentType() const {\n\n return fContentType;\n}\n\ninline unsigned int ComplexTypeInfo::elementCount() const {\n\n if (fElements) {\n return fElements->size();\n }\n\n return 0;\n}\n\ninline XMLCh* ComplexTypeInfo::getTypeName() const {\n\n return fTypeName;\n}\n\ninline DatatypeValidator* ComplexTypeInfo::getBaseDatatypeValidator() const {\n\n return fBaseDatatypeValidator;\n}\n\ninline DatatypeValidator* ComplexTypeInfo::getDatatypeValidator() const {\n\n return fDatatypeValidator;\n}\n\ninline ComplexTypeInfo* ComplexTypeInfo::getBaseComplexTypeInfo() const {\n\n return fBaseComplexTypeInfo;\n}\n\ninline ContentSpecNode* ComplexTypeInfo::getContentSpec() const {\n\n return fContentSpec;\n}\n\ninline const SchemaAttDef* ComplexTypeInfo::getAttWildCard() const {\n\n return fAttWildCard;\n}\n\ninline SchemaAttDef* ComplexTypeInfo::getAttWildCard() {\n\n return fAttWildCard;\n}\n\ninline const SchemaAttDef* ComplexTypeInfo::getAttDef(const XMLCh* const baseName,\n const int uriId) const {\n\n \/\/ If no list, then return a null\n if (!fAttDefs)\n return 0;\n\n return fAttDefs->get(baseName, uriId);\n}\n\ninline SchemaAttDef* ComplexTypeInfo::getAttDef(const XMLCh* const baseName,\n const int uriId)\n{\n \/\/ If no list, then return a null\n if (!fAttDefs)\n return 0;\n\n return fAttDefs->get(baseName, uriId);\n}\n\ninline SchemaElementDecl*\nComplexTypeInfo::elementAt(const unsigned int index) {\n\n if (!fElements) {\n return 0; \/\/ REVISIT - need to throw an exception\n }\n\n return fElements->elementAt(index);\n}\n\ninline const SchemaElementDecl*\nComplexTypeInfo::elementAt(const unsigned int index) const {\n\n if (!fElements) {\n return 0; \/\/ REVISIT - need to throw an exception\n }\n\n return fElements->elementAt(index);\n}\n\ninline XMLContentModel* ComplexTypeInfo::getContentModel(const bool checkUPA)\n{\n if (!fContentModel)\n fContentModel = makeContentModel(checkUPA);\n\n return fContentModel;\n}\n\ninline XSDLocator* ComplexTypeInfo::getLocator() const\n{\n return fLocator;\n}\n\ninline bool ComplexTypeInfo::getAnonymous() const {\n return fAnonymous;\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ ComplexTypeInfo: Setter methods\n\/\/ ---------------------------------------------------------------------------\ninline void ComplexTypeInfo::setAbstract(const bool isAbstract) {\n\n fAbstract = isAbstract;\n}\n\ninline void ComplexTypeInfo::setAdoptContentSpec(const bool toAdopt) {\n\n fAdoptContentSpec = toAdopt;\n}\n\ninline void ComplexTypeInfo::setAttWithTypeId(const bool value) {\n\n fAttWithTypeId = value;\n}\n\ninline void ComplexTypeInfo::setPreprocessed(const bool aValue) {\n\n fPreprocessed = aValue;\n}\n\ninline void ComplexTypeInfo::setDerivedBy(const int derivedBy) {\n\n fDerivedBy = derivedBy;\n}\n\ninline void ComplexTypeInfo::setBlockSet(const int blockSet) {\n\n fBlockSet = blockSet;\n}\n\ninline void ComplexTypeInfo::setFinalSet(const int finalSet) {\n\n fFinalSet = finalSet;\n}\n\ninline void ComplexTypeInfo::setScopeDefined(const int scopeDefined) {\n\n fScopeDefined = scopeDefined;\n}\n\ninline void ComplexTypeInfo::setElementId(const unsigned int elemId) {\n\n fElementId = elemId;\n}\n\ninline void\nComplexTypeInfo::setContentType(const int contentType) {\n\n fContentType = contentType;\n}\n\ninline void ComplexTypeInfo::setTypeName(const XMLCh* const typeName) {\n\n if (fTypeName != 0) {\n delete [] fTypeName;\n }\n\n fTypeName = XMLString::replicate(typeName);\n}\n\ninline void\nComplexTypeInfo::setBaseDatatypeValidator(DatatypeValidator* const validator) {\n\n fBaseDatatypeValidator = validator;\n}\n\ninline void\nComplexTypeInfo::setDatatypeValidator(DatatypeValidator* const validator) {\n\n fDatatypeValidator = validator;\n}\n\ninline void\nComplexTypeInfo::setBaseComplexTypeInfo(ComplexTypeInfo* const typeInfo) {\n\n fBaseComplexTypeInfo = typeInfo;\n}\n\ninline void ComplexTypeInfo::addElement(SchemaElementDecl* const elem) {\n\n if (!fElements) {\n fElements = new RefVectorOf(8, false);\n }\n else if (fElements->containsElement(elem)) {\n return;\n }\n\n fElements->addElement(elem);\n}\n\ninline void ComplexTypeInfo::setAttWildCard(SchemaAttDef* const toAdopt) {\n\n if (fAttWildCard) {\n delete fAttWildCard;\n }\n\n fAttWildCard = toAdopt;\n}\n\ninline void\nComplexTypeInfo::setContentModel(XMLContentModel* const newModelToAdopt)\n{\n delete fContentModel;\n fContentModel = newModelToAdopt;\n}\n\n\n\ninline void ComplexTypeInfo::setAnonymous() {\n fAnonymous = true;\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ ComplexTypeInfo: Helper methods\n\/\/ ---------------------------------------------------------------------------\ninline bool ComplexTypeInfo::hasAttDefs() const\n{\n \/\/ If the collection hasn't been faulted in, then no att defs\n if (!fAttDefs)\n return false;\n\n return !fAttDefs->isEmpty();\n}\n\ninline bool ComplexTypeInfo::contains(const XMLCh* const attName) {\n\n if (!fAttDefs) {\n return false;\n }\n\n RefHash2KeysTableOfEnumerator enumDefs(fAttDefs);\n\n while (enumDefs.hasMoreElements()) {\n\n if (XMLString::equals(attName, enumDefs.nextElement().getAttName()->getLocalPart())) {\n return true;\n }\n }\n\n return false;\n}\n\nXERCES_CPP_NAMESPACE_END\n\n#endif\n\n\/**\n * End of file ComplexTypeInfo.hpp\n *\/\n\n<|endoftext|>"} {"text":"\/**\n * @file mixGasTransport.cpp\n * test problem for mixture transport\n *\/\n\n\/\/ Example \n\/\/\n\/\/ Test case for mixture transport in a gas\n\/\/ The basic idea is to set up a gradient of some kind.\n\/\/ Then the resulting transport coefficients out.\n\/\/ Essentially all of the interface routines should be\n\/\/ exercised and the results dumped out.\n\/\/\n\/\/ A blessed solution test will make sure that the actual\n\/\/ solution doesn't change as a function of time or \n\/\/ further development. \n\n\/\/ perhaps, later, an analytical solution could be added\n\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\n#define MAX(x,y) (( (x) > (y) ) ? (x) : (y)) \n\n\/*****************************************************************\/\n\/*****************************************************************\/\n\n#include \"Cantera.h\"\n#include \"transport.h\"\n#include \"IdealGasMix.h\"\n\n#include \"kernel\/TransportFactory.h\"\n\nusing namespace Cantera;\n\nvoid printDbl(double val) {\n if (fabs(val) < 5.0E-17) {\n cout << \" nil\";\n } else {\n cout << val;\n }\n}\n\nint main(int argc, char** argv) {\n int k;\n string infile = \"diamond.xml\";\n \n try {\n\n \n IdealGasMix g(\"gri30.xml\", \"gri30_mix\");\n int nsp = g.nSpecies();\n double pres = 1.0E5;\n vector_fp Xset(nsp, 0.0);\n Xset[0] = 0.269205 ;\n Xset[1] = 0.000107082;\n Xset[2] = 1.36377e-09 ;\n Xset[3] = 4.35475e-10; \n Xset[4] = 4.34036e-06 ;\n Xset[5] = 0.192249; \n Xset[6] = 3.59356e-13; \n Xset[7] = 2.78061e-12 ; \n Xset[8] = 4.7406e-18 ; \n Xset[9] = 4.12955e-17 ;\n Xset[10] = 2.58549e-14 ; \n Xset[11] = 8.96502e-16 ; \n Xset[12] = 6.09056e-11 ;\n Xset[13] = 7.56752e-09 ;\n Xset[14] = 0.192253;\n Xset[15] = 0.0385036; \n Xset[16] = 1.49596e-08 ;\n Xset[17] = 2.22378e-08 ;\n Xset[18] = 1.43096e-13 ;\n Xset[19] = 1.45312e-15 ;\n Xset[20] = 1.96948e-12 ;\n Xset[21] = 8.41937e-19;\n Xset[22] = 3.18852e-13 ;\n Xset[23] = 7.93625e-18 ;\n Xset[24] = 3.20653e-15 ;\n Xset[25] = 1.15149e-19 ;\n Xset[26] = 1.61189e-18 ;\n Xset[27] = 1.4719e-15 ;\n Xset[28] = 5.24728e-13 ;\n Xset[29] = 6.90582e-17 ;\n Xset[30] = 6.37248e-12 ;\n Xset[31] =5.93728e-11 ;\n Xset[32] = 2.71219e-09 ;\n Xset[33] = 2.66645e-06 ;\n Xset[34] = 6.57142e-11 ;\n Xset[35] = 9.52453e-08 ;\n Xset[36] = 1.26006e-14; \n Xset[37] = 3.49802e-12;\n Xset[38] = 1.19232e-11 ;\n Xset[39] = 7.17782e-13 ; \n Xset[40] = 1.85347e-07 ;\n Xset[41] = 8.25325e-14 ;\n Xset[42] = 5.00914e-20 ;\n Xset[43] = 1.54407e-16 ;\n Xset[44] =3.07176e-11 ;\n Xset[45] =4.93198e-08 ;\n Xset[46] =4.84792e-12 ;\n Xset[47] = 0.307675 ;\n Xset[48] =0;\n Xset[49] =6.21649e-29;\n Xset[50] = 8.42393e-28 ;\n Xset[51] = 6.77865e-18;\n Xset[52] = 2.19225e-16;\n double T1 = 1500.;\n\n double sum = 0.0;\n for (k = 0; k < nsp; k++) {\n sum += Xset[k];\n }\n for (k = 0; k < nsp; k++) {\n Xset[k] \/= sum;\n }\n\n vector_fp X2set(nsp, 0.0);\n X2set[0] = 0.25 ; \n X2set[5] = 0.17; \n X2set[14] = 0.15;\n X2set[15] = 0.05; \n X2set[47] = 0.38 ;\n double T2 = 1200.;\n \n double dist = 0.1;\n\n vector_fp X3set(nsp, 0.0);\n X3set[0] = 0.27 ; \n X3set[5] = 0.15; \n X3set[14] = 0.18;\n X3set[15] = 0.06; \n X3set[47] = 0.36 ;\n double T3 = 1400.;\n \n vector_fp grad_T(3, 0.0);\n\n Array2D grad_X(nsp, 2, 0.0);\n\n\n for( k = 0; k < nsp; k++) {\n grad_X(k,0) = (X2set[k] - Xset[k])\/dist; \n grad_X(k,1) = (X3set[k] - Xset[k])\/dist; \n }\n\n grad_T[0] = (T2 - T1) \/ dist;\n grad_T[1] = (T3 - T1) \/ dist;\n\n int log_level = 0;\n Transport * tran = newTransportMgr(\"Mix\", &g, log_level=0);\n\n MixTransport * tranMix = dynamic_cast(tran);\n\n\n g.setState_TPX(1500.0, pres, DATA_PTR(Xset));\n \n \n vector_fp mixDiffs(nsp, 0.0);\n \n tranMix->getMixDiffCoeffs(DATA_PTR(mixDiffs));\n printf(\" Dump of the mixture Diffusivities:\\n\");\n for (k = 0; k < nsp; k++) {\n string sss = g.speciesName(k);\n printf(\" %15s %13.5g\\n\", sss.c_str(), mixDiffs[k]);\n }\n \n\n vector_fp specVisc(nsp, 0.0);\n \n tranMix->getSpeciesViscosities(DATA_PTR(specVisc));\n printf(\" Dump of the species viscosities:\\n\");\n for (k = 0; k < nsp; k++) {\n string sss = g.speciesName(k);\n printf(\" %15s %13.5g\\n\", sss.c_str(), specVisc[k]);\n }\n\n vector_fp thermDiff(nsp, 0.0);\n tranMix->getThermalDiffCoeffs(DATA_PTR(thermDiff));\n printf(\" Dump of the Thermal Diffusivities :\\n\");\n for (k = 0; k < nsp; k++) {\n string sss = g.speciesName(k);\n printf(\" %15s %13.5g\\n\", sss.c_str(), thermDiff[k]);\n }\n\n printf(\"Viscoscity and thermal Cond vs. T\\n\");\n for (k = 0; k < 10; k++) {\n T1 = 400. + 100. * k;\n g.setState_TPX(T1, pres, DATA_PTR(Xset));\n double visc = tran->viscosity();\n double cond = tran->thermalConductivity();\n printf(\" %13g %13.5g %13.5g\\n\", T1, visc, cond);\n }\n\n g.setState_TPX(T1, pres, DATA_PTR(Xset));\n\n Array2D Bdiff(nsp, nsp, 0.0);\n printf(\"Binary Diffusion Coefficients H2 vs species\\n\");\n\n tranMix->getBinaryDiffCoeffs(nsp, Bdiff.ptrColumn(0));\n for (k = 0; k < nsp; k++) {\n string sss = g.speciesName(k);\n printf(\" H2 - %15s %13.5g %13.5g\\n\", sss.c_str(), Bdiff(0,k), Bdiff(k,0));\n }\n\n\n vector_fp specMob(nsp, 0.0);\n \n tranMix->getMobilities(DATA_PTR(specMob));\n printf(\" Dump of the species mobilities:\\n\");\n for (k = 0; k < nsp; k++) {\n string sss = g.speciesName(k);\n printf(\" %15s %13.5g\\n\", sss.c_str(), specMob[k]);\n }\n\n Array2D fluxes(nsp, 2, 0.0);\n \n tranMix->getSpeciesFluxes(2, DATA_PTR(grad_T), nsp,\n\t\t\t grad_X.ptrColumn(0), nsp, fluxes.ptrColumn(0));\n printf(\" Dump of the species fluxes:\\n\");\n double sum1 = 0.0;\n double sum2 = 0.0;\n double max1 = 0.0;\n double max2 = 0.0;\n for (k = 0; k < nsp; k++) {\n string sss = g.speciesName(k);\n printf(\" %15s %13.5g %13.5g\\n\", sss.c_str(), fluxes(k,0), fluxes(k,1));\n sum1 += fluxes(k,0);\n if (fabs(fluxes(k,0)) > max1) {\n\tmax1 = fabs(fluxes(k,0));\n } \n sum2 += fluxes(k,1);\n if (fabs(fluxes(k,1)) > max2) {\n\tmax2 = fabs(fluxes(k,0));\n } \n }\n \n \/\/ Make sure roundoff error doesn't interfere with the printout.\n \/\/ these should be zero.\n if (fabs(sum1) * 1.0E14 > max1) {\n printf(\"sum in x direction = %13.5g\\n\", sum1);\n } else {\n printf(\"sum in x direction = 0\\n\");\n }\n if (fabs(sum2) * 1.0E14 > max2) {\n printf(\"sum in y direction = %13.5g\\n\", sum1);\n } else {\n printf(\"sum in y direction = 0\\n\");\n }\n \n\n }\n catch (CanteraError) {\n showErrors(cout);\n }\n\n return 0;\n}\n\/***********************************************************\/\nusing namespace Cantera_CXX addition\/**\n * @file mixGasTransport.cpp\n * test problem for mixture transport\n *\/\n\n\/\/ Example \n\/\/\n\/\/ Test case for mixture transport in a gas\n\/\/ The basic idea is to set up a gradient of some kind.\n\/\/ Then the resulting transport coefficients out.\n\/\/ Essentially all of the interface routines should be\n\/\/ exercised and the results dumped out.\n\/\/\n\/\/ A blessed solution test will make sure that the actual\n\/\/ solution doesn't change as a function of time or \n\/\/ further development. \n\n\/\/ perhaps, later, an analytical solution could be added\n\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\n#define MAX(x,y) (( (x) > (y) ) ? (x) : (y)) \n\n\/*****************************************************************\/\n\/*****************************************************************\/\n\n#include \"Cantera.h\"\n#include \"transport.h\"\n#include \"IdealGasMix.h\"\n\n#include \"kernel\/TransportFactory.h\"\n\nusing namespace Cantera;\nusing namespace Cantera_CXX;\n\nvoid printDbl(double val) {\n if (fabs(val) < 5.0E-17) {\n cout << \" nil\";\n } else {\n cout << val;\n }\n}\n\nint main(int argc, char** argv) {\n int k;\n string infile = \"diamond.xml\";\n \n try {\n\n \n IdealGasMix g(\"gri30.xml\", \"gri30_mix\");\n int nsp = g.nSpecies();\n double pres = 1.0E5;\n vector_fp Xset(nsp, 0.0);\n Xset[0] = 0.269205 ;\n Xset[1] = 0.000107082;\n Xset[2] = 1.36377e-09 ;\n Xset[3] = 4.35475e-10; \n Xset[4] = 4.34036e-06 ;\n Xset[5] = 0.192249; \n Xset[6] = 3.59356e-13; \n Xset[7] = 2.78061e-12 ; \n Xset[8] = 4.7406e-18 ; \n Xset[9] = 4.12955e-17 ;\n Xset[10] = 2.58549e-14 ; \n Xset[11] = 8.96502e-16 ; \n Xset[12] = 6.09056e-11 ;\n Xset[13] = 7.56752e-09 ;\n Xset[14] = 0.192253;\n Xset[15] = 0.0385036; \n Xset[16] = 1.49596e-08 ;\n Xset[17] = 2.22378e-08 ;\n Xset[18] = 1.43096e-13 ;\n Xset[19] = 1.45312e-15 ;\n Xset[20] = 1.96948e-12 ;\n Xset[21] = 8.41937e-19;\n Xset[22] = 3.18852e-13 ;\n Xset[23] = 7.93625e-18 ;\n Xset[24] = 3.20653e-15 ;\n Xset[25] = 1.15149e-19 ;\n Xset[26] = 1.61189e-18 ;\n Xset[27] = 1.4719e-15 ;\n Xset[28] = 5.24728e-13 ;\n Xset[29] = 6.90582e-17 ;\n Xset[30] = 6.37248e-12 ;\n Xset[31] =5.93728e-11 ;\n Xset[32] = 2.71219e-09 ;\n Xset[33] = 2.66645e-06 ;\n Xset[34] = 6.57142e-11 ;\n Xset[35] = 9.52453e-08 ;\n Xset[36] = 1.26006e-14; \n Xset[37] = 3.49802e-12;\n Xset[38] = 1.19232e-11 ;\n Xset[39] = 7.17782e-13 ; \n Xset[40] = 1.85347e-07 ;\n Xset[41] = 8.25325e-14 ;\n Xset[42] = 5.00914e-20 ;\n Xset[43] = 1.54407e-16 ;\n Xset[44] =3.07176e-11 ;\n Xset[45] =4.93198e-08 ;\n Xset[46] =4.84792e-12 ;\n Xset[47] = 0.307675 ;\n Xset[48] =0;\n Xset[49] =6.21649e-29;\n Xset[50] = 8.42393e-28 ;\n Xset[51] = 6.77865e-18;\n Xset[52] = 2.19225e-16;\n double T1 = 1500.;\n\n double sum = 0.0;\n for (k = 0; k < nsp; k++) {\n sum += Xset[k];\n }\n for (k = 0; k < nsp; k++) {\n Xset[k] \/= sum;\n }\n\n vector_fp X2set(nsp, 0.0);\n X2set[0] = 0.25 ; \n X2set[5] = 0.17; \n X2set[14] = 0.15;\n X2set[15] = 0.05; \n X2set[47] = 0.38 ;\n double T2 = 1200.;\n \n double dist = 0.1;\n\n vector_fp X3set(nsp, 0.0);\n X3set[0] = 0.27 ; \n X3set[5] = 0.15; \n X3set[14] = 0.18;\n X3set[15] = 0.06; \n X3set[47] = 0.36 ;\n double T3 = 1400.;\n \n vector_fp grad_T(3, 0.0);\n\n Array2D grad_X(nsp, 2, 0.0);\n\n\n for( k = 0; k < nsp; k++) {\n grad_X(k,0) = (X2set[k] - Xset[k])\/dist; \n grad_X(k,1) = (X3set[k] - Xset[k])\/dist; \n }\n\n grad_T[0] = (T2 - T1) \/ dist;\n grad_T[1] = (T3 - T1) \/ dist;\n\n int log_level = 0;\n Transport * tran = newTransportMgr(\"Mix\", &g, log_level=0);\n\n MixTransport * tranMix = dynamic_cast(tran);\n\n\n g.setState_TPX(1500.0, pres, DATA_PTR(Xset));\n \n \n vector_fp mixDiffs(nsp, 0.0);\n \n tranMix->getMixDiffCoeffs(DATA_PTR(mixDiffs));\n printf(\" Dump of the mixture Diffusivities:\\n\");\n for (k = 0; k < nsp; k++) {\n string sss = g.speciesName(k);\n printf(\" %15s %13.5g\\n\", sss.c_str(), mixDiffs[k]);\n }\n \n\n vector_fp specVisc(nsp, 0.0);\n \n tranMix->getSpeciesViscosities(DATA_PTR(specVisc));\n printf(\" Dump of the species viscosities:\\n\");\n for (k = 0; k < nsp; k++) {\n string sss = g.speciesName(k);\n printf(\" %15s %13.5g\\n\", sss.c_str(), specVisc[k]);\n }\n\n vector_fp thermDiff(nsp, 0.0);\n tranMix->getThermalDiffCoeffs(DATA_PTR(thermDiff));\n printf(\" Dump of the Thermal Diffusivities :\\n\");\n for (k = 0; k < nsp; k++) {\n string sss = g.speciesName(k);\n printf(\" %15s %13.5g\\n\", sss.c_str(), thermDiff[k]);\n }\n\n printf(\"Viscoscity and thermal Cond vs. T\\n\");\n for (k = 0; k < 10; k++) {\n T1 = 400. + 100. * k;\n g.setState_TPX(T1, pres, DATA_PTR(Xset));\n double visc = tran->viscosity();\n double cond = tran->thermalConductivity();\n printf(\" %13g %13.5g %13.5g\\n\", T1, visc, cond);\n }\n\n g.setState_TPX(T1, pres, DATA_PTR(Xset));\n\n Array2D Bdiff(nsp, nsp, 0.0);\n printf(\"Binary Diffusion Coefficients H2 vs species\\n\");\n\n tranMix->getBinaryDiffCoeffs(nsp, Bdiff.ptrColumn(0));\n for (k = 0; k < nsp; k++) {\n string sss = g.speciesName(k);\n printf(\" H2 - %15s %13.5g %13.5g\\n\", sss.c_str(), Bdiff(0,k), Bdiff(k,0));\n }\n\n\n vector_fp specMob(nsp, 0.0);\n \n tranMix->getMobilities(DATA_PTR(specMob));\n printf(\" Dump of the species mobilities:\\n\");\n for (k = 0; k < nsp; k++) {\n string sss = g.speciesName(k);\n printf(\" %15s %13.5g\\n\", sss.c_str(), specMob[k]);\n }\n\n Array2D fluxes(nsp, 2, 0.0);\n \n tranMix->getSpeciesFluxes(2, DATA_PTR(grad_T), nsp,\n\t\t\t grad_X.ptrColumn(0), nsp, fluxes.ptrColumn(0));\n printf(\" Dump of the species fluxes:\\n\");\n double sum1 = 0.0;\n double sum2 = 0.0;\n double max1 = 0.0;\n double max2 = 0.0;\n for (k = 0; k < nsp; k++) {\n string sss = g.speciesName(k);\n printf(\" %15s %13.5g %13.5g\\n\", sss.c_str(), fluxes(k,0), fluxes(k,1));\n sum1 += fluxes(k,0);\n if (fabs(fluxes(k,0)) > max1) {\n\tmax1 = fabs(fluxes(k,0));\n } \n sum2 += fluxes(k,1);\n if (fabs(fluxes(k,1)) > max2) {\n\tmax2 = fabs(fluxes(k,0));\n } \n }\n \n \/\/ Make sure roundoff error doesn't interfere with the printout.\n \/\/ these should be zero.\n if (fabs(sum1) * 1.0E14 > max1) {\n printf(\"sum in x direction = %13.5g\\n\", sum1);\n } else {\n printf(\"sum in x direction = 0\\n\");\n }\n if (fabs(sum2) * 1.0E14 > max2) {\n printf(\"sum in y direction = %13.5g\\n\", sum1);\n } else {\n printf(\"sum in y direction = 0\\n\");\n }\n \n\n }\n catch (CanteraError) {\n showErrors(cout);\n }\n\n return 0;\n}\n\/***********************************************************\/\n<|endoftext|>"} {"text":"Don't consider as danger obstacles moving a least than 2 m\/s<|endoftext|>"} {"text":"\/\/ Copyright (c) 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/browser\/web_contents\/aura\/window_slider.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/callback.h\"\n#include \"content\/browser\/web_contents\/aura\/shadow_layer_delegate.h\"\n#include \"content\/public\/browser\/overscroll_configuration.h\"\n#include \"ui\/aura\/window.h\"\n#include \"ui\/base\/events\/event.h\"\n#include \"ui\/compositor\/layer_animation_observer.h\"\n#include \"ui\/compositor\/scoped_layer_animation_settings.h\"\n\nnamespace content {\n\nnamespace {\n\n\/\/ An animation observer that runs a callback at the end of the animation, and\n\/\/ destroys itself.\nclass CallbackAnimationObserver : public ui::ImplicitAnimationObserver {\n public:\n CallbackAnimationObserver(const base::Closure& closure)\n : closure_(closure) {\n }\n\n virtual ~CallbackAnimationObserver() {}\n\n private:\n \/\/ Overridden from ui::ImplicitAnimationObserver:\n virtual void OnImplicitAnimationsCompleted() OVERRIDE {\n if (!closure_.is_null())\n closure_.Run();\n base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);\n }\n\n const base::Closure closure_;\n\n DISALLOW_COPY_AND_ASSIGN(CallbackAnimationObserver);\n};\n\n} \/\/ namespace\n\nWindowSlider::WindowSlider(Delegate* delegate,\n aura::Window* event_window,\n aura::Window* owner)\n : delegate_(delegate),\n event_window_(event_window),\n owner_(owner),\n delta_x_(0.f),\n weak_factory_(this),\n min_start_threshold_(content::GetOverscrollConfig(\n content::OVERSCROLL_CONFIG_MIN_THRESHOLD_START)),\n complete_threshold_(content::GetOverscrollConfig(\n content::OVERSCROLL_CONFIG_HORIZ_THRESHOLD_COMPLETE)) {\n event_window_->AddPreTargetHandler(this);\n\n event_window_->AddObserver(this);\n owner_->AddObserver(this);\n}\n\nWindowSlider::~WindowSlider() {\n delegate_->OnWindowSliderDestroyed();\n if (event_window_) {\n event_window_->RemovePreTargetHandler(this);\n event_window_->RemoveObserver(this);\n }\n if (owner_)\n owner_->RemoveObserver(this);\n}\n\nvoid WindowSlider::ChangeOwner(aura::Window* new_owner) {\n if (owner_)\n owner_->RemoveObserver(this);\n owner_ = new_owner;\n if (owner_) {\n owner_->AddObserver(this);\n UpdateForScroll(0.f, 0.f);\n }\n}\n\nvoid WindowSlider::SetupSliderLayer() {\n ui::Layer* parent = owner_->layer()->parent();\n parent->Add(slider_.get());\n if (delta_x_ < 0)\n parent->StackAbove(slider_.get(), owner_->layer());\n else\n parent->StackBelow(slider_.get(), owner_->layer());\n slider_->SetBounds(owner_->layer()->bounds());\n slider_->SetVisible(true);\n}\n\nvoid WindowSlider::UpdateForScroll(float x_offset, float y_offset) {\n float old_delta = delta_x_;\n delta_x_ += x_offset;\n if (fabs(delta_x_) < min_start_threshold_) {\n ResetScroll();\n return;\n }\n\n if ((old_delta < 0 && delta_x_ > 0) ||\n (old_delta > 0 && delta_x_ < 0)) {\n slider_.reset();\n shadow_.reset();\n }\n\n float translate = 0.f;\n ui::Layer* translate_layer = NULL;\n\n if (delta_x_ <= -min_start_threshold_) {\n if (!slider_.get()) {\n slider_.reset(delegate_->CreateFrontLayer());\n SetupSliderLayer();\n }\n translate = event_window_->bounds().width() -\n fabs(delta_x_ - min_start_threshold_);\n translate_layer = slider_.get();\n } else if (delta_x_ >= min_start_threshold_) {\n if (!slider_.get()) {\n slider_.reset(delegate_->CreateBackLayer());\n SetupSliderLayer();\n }\n translate = delta_x_ - min_start_threshold_;\n translate_layer = owner_->layer();\n } else {\n NOTREACHED();\n }\n\n if (!shadow_.get())\n shadow_.reset(new ShadowLayerDelegate(translate_layer));\n\n gfx::Transform transform;\n transform.Translate(translate, 0);\n translate_layer->SetTransform(transform);\n}\n\nvoid WindowSlider::UpdateForFling(float x_velocity, float y_velocity) {\n if (fabs(delta_x_) < min_start_threshold_)\n return;\n\n int width = owner_->bounds().width();\n float ratio = (fabs(delta_x_) - min_start_threshold_) \/ width;\n if (ratio < complete_threshold_) {\n ResetScroll();\n return;\n }\n\n ui::Layer* sliding = delta_x_ < 0 ? slider_.get() : owner_->layer();\n ui::ScopedLayerAnimationSettings settings(sliding->GetAnimator());\n settings.SetPreemptionStrategy(\n ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);\n settings.SetTweenType(ui::Tween::EASE_OUT);\n settings.AddObserver(new CallbackAnimationObserver(\n base::Bind(&WindowSlider::CompleteWindowSlideAfterAnimation,\n weak_factory_.GetWeakPtr())));\n\n gfx::Transform transform;\n transform.Translate(delta_x_ < 0 ? 0 : width, 0);\n sliding->SetTransform(transform);\n}\n\nvoid WindowSlider::ResetScroll() {\n if (!slider_.get())\n return;\n\n \/\/ Do not trigger any callbacks if this animation replaces any in-progress\n \/\/ animation.\n weak_factory_.InvalidateWeakPtrs();\n\n \/\/ Reset the state of the sliding layer.\n if (slider_.get()) {\n ui::Layer* layer = slider_.release();\n ui::ScopedLayerAnimationSettings settings(layer->GetAnimator());\n settings.SetPreemptionStrategy(\n ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);\n settings.SetTweenType(ui::Tween::EASE_OUT);\n settings.AddObserver(new CallbackAnimationObserver(\n base::Bind(&base::DeletePointer,\n base::Unretained(layer))));\n settings.AddObserver(new CallbackAnimationObserver(\n base::Bind(&base::DeletePointer,\n base::Unretained(shadow_.release()))));\n\n gfx::Transform transform;\n transform.Translate(delta_x_ < 0 ? layer->bounds().width() : 0, 0);\n layer->SetTransform(transform);\n }\n\n \/\/ Reset the state of the main layer.\n {\n ui::ScopedLayerAnimationSettings settings(owner_->layer()->GetAnimator());\n settings.SetPreemptionStrategy(\n ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);\n settings.SetTweenType(ui::Tween::EASE_OUT);\n settings.AddObserver(new CallbackAnimationObserver(\n base::Bind(&WindowSlider::AbortWindowSlideAfterAnimation,\n weak_factory_.GetWeakPtr())));\n owner_->layer()->SetTransform(gfx::Transform());\n owner_->layer()->SetLayerBrightness(0.f);\n }\n\n delta_x_ = 0.f;\n}\n\nvoid WindowSlider::CancelScroll() {\n ResetScroll();\n}\n\nvoid WindowSlider::CompleteWindowSlideAfterAnimation() {\n delegate_->OnWindowSlideComplete();\n delete this;\n}\n\nvoid WindowSlider::AbortWindowSlideAfterAnimation() {\n delegate_->OnWindowSlideAborted();\n}\n\nvoid WindowSlider::OnKeyEvent(ui::KeyEvent* event) {\n CancelScroll();\n}\n\nvoid WindowSlider::OnMouseEvent(ui::MouseEvent* event) {\n if (!(event->flags() & ui::EF_IS_SYNTHESIZED))\n CancelScroll();\n}\n\nvoid WindowSlider::OnScrollEvent(ui::ScrollEvent* event) {\n if (event->type() == ui::ET_SCROLL)\n UpdateForScroll(event->x_offset_ordinal(), event->y_offset_ordinal());\n else if (event->type() == ui::ET_SCROLL_FLING_START)\n UpdateForFling(event->x_offset_ordinal(), event->y_offset_ordinal());\n else\n CancelScroll();\n event->SetHandled();\n}\n\nvoid WindowSlider::OnGestureEvent(ui::GestureEvent* event) {\n const ui::GestureEventDetails& details = event->details();\n switch (event->type()) {\n case ui::ET_GESTURE_SCROLL_BEGIN:\n ResetScroll();\n break;\n\n case ui::ET_GESTURE_SCROLL_UPDATE:\n UpdateForScroll(details.scroll_x(), details.scroll_y());\n break;\n\n case ui::ET_GESTURE_SCROLL_END:\n UpdateForFling(0.f, 0.f);\n break;\n\n case ui::ET_SCROLL_FLING_START:\n UpdateForFling(details.velocity_x(), details.velocity_y());\n break;\n\n case ui::ET_GESTURE_PINCH_BEGIN:\n case ui::ET_GESTURE_PINCH_UPDATE:\n case ui::ET_GESTURE_PINCH_END:\n CancelScroll();\n break;\n\n default:\n break;\n }\n\n event->SetHandled();\n}\n\nvoid WindowSlider::OnWindowRemovingFromRootWindow(aura::Window* window) {\n if (window == event_window_) {\n window->RemoveObserver(this);\n window->RemovePreTargetHandler(this);\n event_window_ = NULL;\n } else if (window == owner_) {\n window->RemoveObserver(this);\n owner_ = NULL;\n if (!slider_.get())\n delete this;\n } else {\n NOTREACHED();\n }\n}\n\n} \/\/ namespace content\naura: Fix a valgrind error in WindowSlider.\/\/ Copyright (c) 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/browser\/web_contents\/aura\/window_slider.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/callback.h\"\n#include \"content\/browser\/web_contents\/aura\/shadow_layer_delegate.h\"\n#include \"content\/public\/browser\/overscroll_configuration.h\"\n#include \"ui\/aura\/window.h\"\n#include \"ui\/base\/events\/event.h\"\n#include \"ui\/compositor\/layer_animation_observer.h\"\n#include \"ui\/compositor\/scoped_layer_animation_settings.h\"\n\nnamespace content {\n\nnamespace {\n\nvoid DeleteLayerAndShadow(ui::Layer* layer,\n ShadowLayerDelegate* shadow) {\n delete shadow;\n delete layer;\n}\n\n\/\/ An animation observer that runs a callback at the end of the animation, and\n\/\/ destroys itself.\nclass CallbackAnimationObserver : public ui::ImplicitAnimationObserver {\n public:\n CallbackAnimationObserver(const base::Closure& closure)\n : closure_(closure) {\n }\n\n virtual ~CallbackAnimationObserver() {}\n\n private:\n \/\/ Overridden from ui::ImplicitAnimationObserver:\n virtual void OnImplicitAnimationsCompleted() OVERRIDE {\n if (!closure_.is_null())\n closure_.Run();\n base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);\n }\n\n const base::Closure closure_;\n\n DISALLOW_COPY_AND_ASSIGN(CallbackAnimationObserver);\n};\n\n} \/\/ namespace\n\nWindowSlider::WindowSlider(Delegate* delegate,\n aura::Window* event_window,\n aura::Window* owner)\n : delegate_(delegate),\n event_window_(event_window),\n owner_(owner),\n delta_x_(0.f),\n weak_factory_(this),\n min_start_threshold_(content::GetOverscrollConfig(\n content::OVERSCROLL_CONFIG_MIN_THRESHOLD_START)),\n complete_threshold_(content::GetOverscrollConfig(\n content::OVERSCROLL_CONFIG_HORIZ_THRESHOLD_COMPLETE)) {\n event_window_->AddPreTargetHandler(this);\n\n event_window_->AddObserver(this);\n owner_->AddObserver(this);\n}\n\nWindowSlider::~WindowSlider() {\n delegate_->OnWindowSliderDestroyed();\n if (event_window_) {\n event_window_->RemovePreTargetHandler(this);\n event_window_->RemoveObserver(this);\n }\n if (owner_)\n owner_->RemoveObserver(this);\n}\n\nvoid WindowSlider::ChangeOwner(aura::Window* new_owner) {\n if (owner_)\n owner_->RemoveObserver(this);\n owner_ = new_owner;\n if (owner_) {\n owner_->AddObserver(this);\n UpdateForScroll(0.f, 0.f);\n }\n}\n\nvoid WindowSlider::SetupSliderLayer() {\n ui::Layer* parent = owner_->layer()->parent();\n parent->Add(slider_.get());\n if (delta_x_ < 0)\n parent->StackAbove(slider_.get(), owner_->layer());\n else\n parent->StackBelow(slider_.get(), owner_->layer());\n slider_->SetBounds(owner_->layer()->bounds());\n slider_->SetVisible(true);\n}\n\nvoid WindowSlider::UpdateForScroll(float x_offset, float y_offset) {\n float old_delta = delta_x_;\n delta_x_ += x_offset;\n if (fabs(delta_x_) < min_start_threshold_) {\n ResetScroll();\n return;\n }\n\n if ((old_delta < 0 && delta_x_ > 0) ||\n (old_delta > 0 && delta_x_ < 0)) {\n slider_.reset();\n shadow_.reset();\n }\n\n float translate = 0.f;\n ui::Layer* translate_layer = NULL;\n\n if (delta_x_ <= -min_start_threshold_) {\n if (!slider_.get()) {\n slider_.reset(delegate_->CreateFrontLayer());\n SetupSliderLayer();\n }\n translate = event_window_->bounds().width() -\n fabs(delta_x_ - min_start_threshold_);\n translate_layer = slider_.get();\n } else if (delta_x_ >= min_start_threshold_) {\n if (!slider_.get()) {\n slider_.reset(delegate_->CreateBackLayer());\n SetupSliderLayer();\n }\n translate = delta_x_ - min_start_threshold_;\n translate_layer = owner_->layer();\n } else {\n NOTREACHED();\n }\n\n if (!shadow_.get())\n shadow_.reset(new ShadowLayerDelegate(translate_layer));\n\n gfx::Transform transform;\n transform.Translate(translate, 0);\n translate_layer->SetTransform(transform);\n}\n\nvoid WindowSlider::UpdateForFling(float x_velocity, float y_velocity) {\n if (fabs(delta_x_) < min_start_threshold_)\n return;\n\n int width = owner_->bounds().width();\n float ratio = (fabs(delta_x_) - min_start_threshold_) \/ width;\n if (ratio < complete_threshold_) {\n ResetScroll();\n return;\n }\n\n ui::Layer* sliding = delta_x_ < 0 ? slider_.get() : owner_->layer();\n ui::ScopedLayerAnimationSettings settings(sliding->GetAnimator());\n settings.SetPreemptionStrategy(\n ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);\n settings.SetTweenType(ui::Tween::EASE_OUT);\n settings.AddObserver(new CallbackAnimationObserver(\n base::Bind(&WindowSlider::CompleteWindowSlideAfterAnimation,\n weak_factory_.GetWeakPtr())));\n\n gfx::Transform transform;\n transform.Translate(delta_x_ < 0 ? 0 : width, 0);\n sliding->SetTransform(transform);\n}\n\nvoid WindowSlider::ResetScroll() {\n if (!slider_.get())\n return;\n\n \/\/ Do not trigger any callbacks if this animation replaces any in-progress\n \/\/ animation.\n weak_factory_.InvalidateWeakPtrs();\n\n \/\/ Reset the state of the sliding layer.\n if (slider_.get()) {\n ui::Layer* layer = slider_.release();\n ui::ScopedLayerAnimationSettings settings(layer->GetAnimator());\n settings.SetPreemptionStrategy(\n ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);\n settings.SetTweenType(ui::Tween::EASE_OUT);\n\n \/\/ Delete the layer and the shadow at the end of the animation.\n settings.AddObserver(new CallbackAnimationObserver(\n base::Bind(&DeleteLayerAndShadow,\n base::Unretained(layer),\n base::Unretained(shadow_.release()))));\n\n gfx::Transform transform;\n transform.Translate(delta_x_ < 0 ? layer->bounds().width() : 0, 0);\n layer->SetTransform(transform);\n }\n\n \/\/ Reset the state of the main layer.\n {\n ui::ScopedLayerAnimationSettings settings(owner_->layer()->GetAnimator());\n settings.SetPreemptionStrategy(\n ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);\n settings.SetTweenType(ui::Tween::EASE_OUT);\n settings.AddObserver(new CallbackAnimationObserver(\n base::Bind(&WindowSlider::AbortWindowSlideAfterAnimation,\n weak_factory_.GetWeakPtr())));\n owner_->layer()->SetTransform(gfx::Transform());\n owner_->layer()->SetLayerBrightness(0.f);\n }\n\n delta_x_ = 0.f;\n}\n\nvoid WindowSlider::CancelScroll() {\n ResetScroll();\n}\n\nvoid WindowSlider::CompleteWindowSlideAfterAnimation() {\n delegate_->OnWindowSlideComplete();\n delete this;\n}\n\nvoid WindowSlider::AbortWindowSlideAfterAnimation() {\n delegate_->OnWindowSlideAborted();\n}\n\nvoid WindowSlider::OnKeyEvent(ui::KeyEvent* event) {\n CancelScroll();\n}\n\nvoid WindowSlider::OnMouseEvent(ui::MouseEvent* event) {\n if (!(event->flags() & ui::EF_IS_SYNTHESIZED))\n CancelScroll();\n}\n\nvoid WindowSlider::OnScrollEvent(ui::ScrollEvent* event) {\n if (event->type() == ui::ET_SCROLL)\n UpdateForScroll(event->x_offset_ordinal(), event->y_offset_ordinal());\n else if (event->type() == ui::ET_SCROLL_FLING_START)\n UpdateForFling(event->x_offset_ordinal(), event->y_offset_ordinal());\n else\n CancelScroll();\n event->SetHandled();\n}\n\nvoid WindowSlider::OnGestureEvent(ui::GestureEvent* event) {\n const ui::GestureEventDetails& details = event->details();\n switch (event->type()) {\n case ui::ET_GESTURE_SCROLL_BEGIN:\n ResetScroll();\n break;\n\n case ui::ET_GESTURE_SCROLL_UPDATE:\n UpdateForScroll(details.scroll_x(), details.scroll_y());\n break;\n\n case ui::ET_GESTURE_SCROLL_END:\n UpdateForFling(0.f, 0.f);\n break;\n\n case ui::ET_SCROLL_FLING_START:\n UpdateForFling(details.velocity_x(), details.velocity_y());\n break;\n\n case ui::ET_GESTURE_PINCH_BEGIN:\n case ui::ET_GESTURE_PINCH_UPDATE:\n case ui::ET_GESTURE_PINCH_END:\n CancelScroll();\n break;\n\n default:\n break;\n }\n\n event->SetHandled();\n}\n\nvoid WindowSlider::OnWindowRemovingFromRootWindow(aura::Window* window) {\n if (window == event_window_) {\n window->RemoveObserver(this);\n window->RemovePreTargetHandler(this);\n event_window_ = NULL;\n } else if (window == owner_) {\n window->RemoveObserver(this);\n owner_ = NULL;\n if (!slider_.get())\n delete this;\n } else {\n NOTREACHED();\n }\n}\n\n} \/\/ namespace content\n<|endoftext|>"} {"text":"\/* Siconos-Kernel, Copyright INRIA 2005-2011.\n * Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n * Siconos is a free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * Siconos is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Siconos; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr\n *\/\n\n\/*! \\file DynamicalSystem.hpp\n \\brief Abstract class - General interface for all Dynamical Systems.\n*\/\n\n#ifndef PLUGIN_HPP\n#define PLUGIN_HPP\n\n#include \"SiconosSharedLibrary.hpp\"\n\nclass Plugin\n{\n\npublic:\n\n static bool setFunction(void* f, const std::string& pluginPath, const std::string& functionName, std::string& name)\n {\n SSL::setFunction(f, pluginPath, functionName);\n name = pluginPath.substr(0, pluginPath.length() - 3) + \":\" + functionName;\n return true;\n }\n\n static bool setFunction(void* f, const std::string& pluginPath, const std::string& functionName)\n {\n SSL::setFunction(f, pluginPath, functionName);\n return true;\n }\n static bool setFunction(void* f, const std::string& Name)\n {\n SSL::setFunction(f, SSL::getPluginName(Name), SSL::getPluginFunctionName(Name));\n return true;\n }\n\n\n};\n\n#endif\n\n\nPlugin: update doc\/* Siconos-Kernel, Copyright INRIA 2005-2011.\n * Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n * Siconos is a free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * Siconos is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Siconos; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr\n *\/\n\n\/*! \\file Plugin.hpp\n \\brief Class to deal with functions given as C functions\n*\/\n\n#ifndef PLUGIN_HPP\n#define PLUGIN_HPP\n\n#include \"SiconosSharedLibrary.hpp\"\n\nclass Plugin\n{\n\npublic:\n\n static bool setFunction(void* f, const std::string& pluginPath, const std::string& functionName, std::string& name)\n {\n SSL::setFunction(f, pluginPath, functionName);\n name = pluginPath.substr(0, pluginPath.length() - 3) + \":\" + functionName;\n return true;\n }\n\n static bool setFunction(void* f, const std::string& pluginPath, const std::string& functionName)\n {\n SSL::setFunction(f, pluginPath, functionName);\n return true;\n }\n static bool setFunction(void* f, const std::string& Name)\n {\n SSL::setFunction(f, SSL::getPluginName(Name), SSL::getPluginFunctionName(Name));\n return true;\n }\n\n\n};\n\n#endif\n\n\n<|endoftext|>"} {"text":"\/\/ Do not remove the include below\r\n#include \"LCD_Experiments.h\"\r\n\r\n\/*\r\n\r\nSainSmart GL_ST7735 LCD\/microSD module\r\nwww.sainsmart.com\r\n\r\n\r\nSignal Definition TFT LCD):\r\n\tGND \t : Power Ground\r\n\tVCC \t : 5V power input (3.3V might work)\r\n\tCS \t : Chipselect for LCD, (use pin 10)\r\n\tSDA \t : LCD Data for SPI (use MOSI, pin 11)\r\n\tSCL \t : SCLK for TFT Clock (use SCLK, pin 13)\r\n\tRS\/DC \t : Command\/Data Selection (use pin 9)\r\n\tRESET \t : LCD controller reset, active low (use pin 8)\r\nSignal Definition micro-SD):\r\n\tCS (SD-CS) \t : Chipselect for TF Card,\r\n\tCLK (SD-Clock)\t: SPI Clock\r\n\tMOSI (SD-DI) \t: SPI Master out Slave in\r\n\tMISO (SD-DO) \t: SPI Master in Slave out\r\n\r\nMethods that may be called:\r\n\r\nCreate an instance:\r\n GL_ST7735(uint8_t CS, uint8_t RS, uint8_t SID,\r\n\t uint8_t SCLK, uint8_t RST);\r\n GL_ST7735(uint8_t CS, uint8_t RS, uint8_t RST);\r\n\r\n Description\r\n\r\n The base class for drawing to the GL_ST7735. Use this to create a named\r\n instance of the GL_ST7735 class to refer to in your sketch.\r\n\r\n Syntax\r\n\r\n GL_ST7735(cs, dc, rst); for using hardware SPI\r\n GL_ST7735(cs, dc, mosi, sclk, rst); for use on any pins\r\n\r\n Parameters\r\n\r\n cs : int, pin for chip select\r\n dc : int, pin used for data\/command\r\n rst : int, pin used for reset\r\n mosi : int, pin used for MOSI communication when not using hardware SPI\r\n sclk : int, pin used for the shared clock, when not using hardware SPI\r\n\r\n Returns\r\n\r\n none\r\n\r\n\r\n The screen can be configured for use in two ways. One is to use an Arduino's\r\n hardware SPI interface. The other is to declare all the pins manually. There\r\n is no difference in the functionality of the screen between the two methods,\r\n but using hardware SPI is significantly faster.\r\n\r\n If you plan on using the SD card on the TFT module, you must use hardware SPI.\r\n All examples in the library are written for hardware SPI use.\r\n\r\n If using hardware SPI with the Uno, you only need to declare the\r\n CS, DC, and RESET pins,\r\n as MOSI (pin 11) and SCLK (pin 13) are already defined.\r\n\r\n #define CS 10\r\n #define DC 9\r\n #define RESET 8\r\n\r\n GL_ST7735 myScreen = GL_ST7735(CS, DC, RESET);\r\n\r\n\r\nInitialize an ST7735B:\r\n void initB(void);\r\n\r\nInitialize an ST7735R:\r\n void initR(void);\r\n\r\n Drawing primitives:\r\n void pushColor(uint16_t color);\r\n void drawPixel(uint8_t x, uint8_t y, uint16_t color);\r\n void drawLine(int16_t x, int16_t y, int16_t x1, int16_t y1, uint16_t color);\r\n void fillScreen(uint16_t color);\r\n void drawVerticalLine(uint8_t x0, uint8_t y0,\r\n\t\t\tuint8_t length, uint16_t color);\r\n void drawHorizontalLine(uint8_t x0, uint8_t y0,\r\n\t\t\t uint8_t length, uint16_t color);\r\n void drawRect(uint8_t x, uint8_t y, uint8_t w, uint8_t h,\r\n\t\tuint16_t color);\r\n void fillRect(uint8_t x, uint8_t y, uint8_t w, uint8_t h,\r\n\t\tuint16_t color);\r\n void drawCircle(uint8_t x0, uint8_t y0, uint8_t r,\r\n\t\t uint16_t color);\r\n void fillCircle(uint8_t x0, uint8_t y0, uint8_t r,\r\n\t\t uint16_t color);\r\n\r\n void drawString(uint8_t x, uint8_t y, char *c,\r\n\t\t uint16_t color, uint8_t size=1);\r\n void drawChar(uint8_t x, uint8_t y, char c,\r\n\t\t uint16_t color, uint8_t size=1);\r\n\r\n static const uint8_t width = 128;\r\n static const uint8_t height = 160;\r\n\r\nLow level:\r\n void setAddrWindow(uint8_t x0, uint8_t y0, uint8_t x1, uint8_t y1);\r\n void writecommand(uint8_t);\r\n void writedata(uint8_t);\r\n void setRotation(uint8_t);\r\n uint8_t getRotation(void);\r\n void drawFastLine(uint8_t x0, uint8_t y0, uint8_t l,\r\n\t\t uint16_t color, uint8_t flag);\r\n\r\nCommented out:\r\n void dummyclock(void);\r\n\r\n x starts on the left and increases to the right.\r\n x goes from 0 to .width - 1\r\n\r\n y starts at the top and increases downward.\r\n y goes from 0 to .height - 1\r\n\r\n strings are drawn with the stated position being the upper left corner.\r\n circles are drawn with the stated position being the center of the circle.\r\n\r\n\r\n *\/\r\n\r\nconst byte CS = 10 ;\r\nconst byte DC = 9 ;\r\nconst byte RESET = 8 ;\r\n\r\nGL_ST7735 lcd = GL_ST7735(CS, DC, RESET);\r\nGLBall ball[] = {GLBall(&lcd), GLBall(&lcd), GLBall(&lcd)} ;\r\n\r\nconst unsigned int xBouncesToRepeat = 33 ;\r\nunsigned int xBouncesRemaining = xBouncesToRepeat ;\r\n\r\n\/\/\r\n\/\/ This program displays a test pattern on the LCD screen,\r\n\/\/ waits two seconds,\r\n\/\/ then clears the screen and displays a \"ball\" that bounces around\r\n\/\/ the LCD screen. The ball leaves a trail as it goes.\r\n\/\/\r\nvoid setup()\r\n{\r\n\tenum States {\r\n\t\tred1, red2, red3,\r\n\t\tgreen1, green2, green3,\r\n\t\tblue1, blue2, blue3\r\n\t} ;\r\n\tStates state = red1 ;\r\n\tchar strResult[17] ;\r\n\tint offset = 0 ;\r\n\tunsigned int color = RED ;\r\n\tlcd.initR() ;\r\n\tclearScreen(lcd) ; \/\/ Clear screen.\r\n\tSerial.begin(115200) ;\r\n\t\/\/\r\n\t\/\/ Draw test pattern including string for line number.\r\n\t\/\/\r\n\tfor (unsigned int i=1; i<=lcd.height; i++) {\r\n\t\tconst int size = 1 ; \/\/ size may be 1, 2, 3, 4, 5, 6, or 7.\r\n\t\t \/\/ size of 1 is smallest, size of 7 is largest.\r\n\t\t\/\/\r\n\t\t\/\/ Clear space for new data.\r\n\t\t\/\/ Provides space for 3 digits.\r\n\t\t\/\/\r\n\t\tlcd.fillRect( 10, 51, 18*size, 8*size, BLACK) ;\r\n\t\t\/\/\r\n\t\t\/\/ Write line number.\r\n\t\t\/\/\r\n\t\tlcd.drawString(10, 51, itoa(i, strResult, 10), WHITE, size) ;\r\n\t\t\/\/\r\n\t\t\/\/ Draw the line.\r\n\t\t\/\/\r\n\t\tlcd.drawHorizontalLine(offset, i-1, lcd.width-offset, color) ;\r\n\/\/\t\tdelay(10) ;\r\n\t\tif (i0) {\r\n\t\t\tlcd.drawEllipse(60, 80, 54, iPrevious, 20, BLACK);\/\/ Erase previous.\r\n\t\t}\r\n\t\tiPrevious = i ;\r\n\t}\r\n\tfor (int i = 46 ; i >= 6 ; i-=delta) {\r\n\t\tlcd.drawEllipse(60, 80, 54, i, 20, GREEN) ; \/\/ Draw new.\r\n\t\tlcd.drawEllipse(60, 80, 54, iPrevious, 20, BLACK) ; \/\/ Erase previous.\r\n\t\tiPrevious = i ;\r\n\t}\r\n\tdelay(2000) ;\r\n\tclearScreen(lcd) ;\r\n\t\/\/\r\n\t\/\/ Set up ball parameters\r\n\t\/\/\r\n\tball[0].setBallColor(YELLOW)\r\n\t\t\t\t\t.setTrailColor(RED)\r\n\t\t\t\t\t.setRadius(2)\r\n\t\t\t\t\t.setXCurrent(50)\r\n\t\t\t\t\t.setYCurrent(50)\r\n\t\t\t\t\t.setYVel(-ball[0].getYVel())\r\n\t\t\t\t\t.begin() ;\r\n\tball[1].setBallColor(CYAN)\r\n\t \t\t.setTrailColor(YELLOW)\r\n\t \t\t.begin() ;\r\n\tball[2].setBallColor(MAGENTA)\r\n\t\t\t\t\t.setTrailColor(GREEN)\r\n\t\t\t\t\t.setRadius(8)\r\n\t\t\t\t\t.setXCurrent(50)\r\n\t\t\t\t\t.setYCurrent(ball[2].getRadius())\r\n\t\t\t\t\t.setXVel(-ball[2].getXVel())\r\n\t\t\t\t\t.begin() ;\r\n}\r\nvoid loop() {\r\n\t\/\/\r\n\t\/\/ Knowing when it is time to switch trail colors\r\n\t\/\/\r\n\tint xVelPrevious = ball[1].getXVel();\r\n\tfor (int i = 0; i <= 2; i++) {\r\n\t\tif (i != 1) {\r\n\t\t\tball[i].update();\r\n\t\t} else {\r\n\t\t\tif (ball[i].update()) {\r\n\t\t\t\tint xVelCurrent = ball[i].getXVel();\r\n\t\t\t\tif (xVelCurrent == -xVelPrevious) {\r\n\t\t\t\t\txBouncesRemaining--;\r\n\t\t\t\t}\r\n\t\t\t\tif (xBouncesRemaining == 0) {\r\n\t\t\t\t\tfor (int j = 0; j <= 2; j++) {\r\n\t\t\t\t\t\tball[j].setTrailColor(~ball[j].getTrailColor());\r\n\t\t\t\t\t\tball[j].setBallColor(~ball[j].getBallColor());\r\n\t\t\t\t\t}\r\n\t\t\t\t\txBouncesRemaining = xBouncesToRepeat;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid clearScreen(GL_ST7735 obj) {\r\n\tobj.fillRect(0, 0, lcd.width, lcd.height, BLACK); \/\/ Clear screen.\r\n}\r\n\r\nMake use of new method setInverted(...) to inveert and then non-invert display color of final ellipse.\/\/ Do not remove the include below\r\n#include \"LCD_Experiments.h\"\r\n\r\n\/*\r\n\r\nSainSmart GL_ST7735 LCD\/microSD module\r\nwww.sainsmart.com\r\n\r\n\r\nSignal Definition TFT LCD):\r\n\tGND \t : Power Ground\r\n\tVCC \t : 5V power input (3.3V might work)\r\n\tCS \t : Chipselect for LCD, (use pin 10)\r\n\tSDA \t : LCD Data for SPI (use MOSI, pin 11)\r\n\tSCL \t : SCLK for TFT Clock (use SCLK, pin 13)\r\n\tRS\/DC \t : Command\/Data Selection (use pin 9)\r\n\tRESET \t : LCD controller reset, active low (use pin 8)\r\nSignal Definition micro-SD):\r\n\tCS (SD-CS) \t : Chipselect for TF Card,\r\n\tCLK (SD-Clock)\t: SPI Clock\r\n\tMOSI (SD-DI) \t: SPI Master out Slave in\r\n\tMISO (SD-DO) \t: SPI Master in Slave out\r\n\r\nMethods that may be called:\r\n\r\nCreate an instance:\r\n GL_ST7735(uint8_t CS, uint8_t RS, uint8_t SID,\r\n\t uint8_t SCLK, uint8_t RST);\r\n GL_ST7735(uint8_t CS, uint8_t RS, uint8_t RST);\r\n\r\n Description\r\n\r\n The base class for drawing to the GL_ST7735. Use this to create a named\r\n instance of the GL_ST7735 class to refer to in your sketch.\r\n\r\n Syntax\r\n\r\n GL_ST7735(cs, dc, rst); for using hardware SPI\r\n GL_ST7735(cs, dc, mosi, sclk, rst); for use on any pins\r\n\r\n Parameters\r\n\r\n cs : int, pin for chip select\r\n dc : int, pin used for data\/command\r\n rst : int, pin used for reset\r\n mosi : int, pin used for MOSI communication when not using hardware SPI\r\n sclk : int, pin used for the shared clock, when not using hardware SPI\r\n\r\n Returns\r\n\r\n none\r\n\r\n\r\n The screen can be configured for use in two ways. One is to use an Arduino's\r\n hardware SPI interface. The other is to declare all the pins manually. There\r\n is no difference in the functionality of the screen between the two methods,\r\n but using hardware SPI is significantly faster.\r\n\r\n If you plan on using the SD card on the TFT module, you must use hardware SPI.\r\n All examples in the library are written for hardware SPI use.\r\n\r\n If using hardware SPI with the Uno, you only need to declare the\r\n CS, DC, and RESET pins,\r\n as MOSI (pin 11) and SCLK (pin 13) are already defined.\r\n\r\n #define CS 10\r\n #define DC 9\r\n #define RESET 8\r\n\r\n GL_ST7735 myScreen = GL_ST7735(CS, DC, RESET);\r\n\r\n\r\nInitialize an ST7735B:\r\n void initB(void);\r\n\r\nInitialize an ST7735R:\r\n void initR(void);\r\n\r\n Drawing primitives:\r\n void pushColor(uint16_t color);\r\n void drawPixel(uint8_t x, uint8_t y, uint16_t color);\r\n void drawLine(int16_t x, int16_t y, int16_t x1, int16_t y1, uint16_t color);\r\n void fillScreen(uint16_t color);\r\n void drawVerticalLine(uint8_t x0, uint8_t y0,\r\n\t\t\tuint8_t length, uint16_t color);\r\n void drawHorizontalLine(uint8_t x0, uint8_t y0,\r\n\t\t\t uint8_t length, uint16_t color);\r\n void drawRect(uint8_t x, uint8_t y, uint8_t w, uint8_t h,\r\n\t\tuint16_t color);\r\n void fillRect(uint8_t x, uint8_t y, uint8_t w, uint8_t h,\r\n\t\tuint16_t color);\r\n void drawCircle(uint8_t x0, uint8_t y0, uint8_t r,\r\n\t\t uint16_t color);\r\n void fillCircle(uint8_t x0, uint8_t y0, uint8_t r,\r\n\t\t uint16_t color);\r\n\r\n void drawString(uint8_t x, uint8_t y, char *c,\r\n\t\t uint16_t color, uint8_t size=1);\r\n void drawChar(uint8_t x, uint8_t y, char c,\r\n\t\t uint16_t color, uint8_t size=1);\r\n\r\n static const uint8_t width = 128;\r\n static const uint8_t height = 160;\r\n\r\nLow level:\r\n void setAddrWindow(uint8_t x0, uint8_t y0, uint8_t x1, uint8_t y1);\r\n void writecommand(uint8_t);\r\n void writedata(uint8_t);\r\n void setRotation(uint8_t);\r\n uint8_t getRotation(void);\r\n void drawFastLine(uint8_t x0, uint8_t y0, uint8_t l,\r\n\t\t uint16_t color, uint8_t flag);\r\n\r\nCommented out:\r\n void dummyclock(void);\r\n\r\n x starts on the left and increases to the right.\r\n x goes from 0 to .width - 1\r\n\r\n y starts at the top and increases downward.\r\n y goes from 0 to .height - 1\r\n\r\n strings are drawn with the stated position being the upper left corner.\r\n circles are drawn with the stated position being the center of the circle.\r\n\r\n\r\n *\/\r\n\r\nconst byte CS = 10 ;\r\nconst byte DC = 9 ;\r\nconst byte RESET = 8 ;\r\n\r\nGL_ST7735 lcd = GL_ST7735(CS, DC, RESET);\r\nGLBall ball[] = {GLBall(&lcd), GLBall(&lcd), GLBall(&lcd)} ;\r\n\r\nconst unsigned int xBouncesToRepeat = 33 ;\r\nunsigned int xBouncesRemaining = xBouncesToRepeat ;\r\n\r\n\/\/\r\n\/\/ This program displays a test pattern on the LCD screen,\r\n\/\/ waits two seconds,\r\n\/\/ then clears the screen and displays a \"ball\" that bounces around\r\n\/\/ the LCD screen. The ball leaves a trail as it goes.\r\n\/\/\r\nvoid setup()\r\n{\r\n\tenum States {\r\n\t\tred1, red2, red3,\r\n\t\tgreen1, green2, green3,\r\n\t\tblue1, blue2, blue3\r\n\t} ;\r\n\tStates state = red1 ;\r\n\tchar strResult[17] ;\r\n\tint offset = 0 ;\r\n\tunsigned int color = RED ;\r\n\tlcd.initR() ;\r\n\tclearScreen(lcd) ; \/\/ Clear screen.\r\n\tSerial.begin(115200) ;\r\n\t\/\/\r\n\t\/\/ Draw test pattern including string for line number.\r\n\t\/\/\r\n\tfor (unsigned int i=1; i<=lcd.height; i++) {\r\n\t\tconst int size = 1 ; \/\/ size may be 1, 2, 3, 4, 5, 6, or 7.\r\n\t\t \/\/ size of 1 is smallest, size of 7 is largest.\r\n\t\t\/\/\r\n\t\t\/\/ Clear space for new data.\r\n\t\t\/\/ Provides space for 3 digits.\r\n\t\t\/\/\r\n\t\tlcd.fillRect( 10, 51, 18*size, 8*size, BLACK) ;\r\n\t\t\/\/\r\n\t\t\/\/ Write line number.\r\n\t\t\/\/\r\n\t\tlcd.drawString(10, 51, itoa(i, strResult, 10), WHITE, size) ;\r\n\t\t\/\/\r\n\t\t\/\/ Draw the line.\r\n\t\t\/\/\r\n\t\tlcd.drawHorizontalLine(offset, i-1, lcd.width-offset, color) ;\r\n\/\/\t\tdelay(10) ;\r\n\t\tif (i0) {\r\n\t\t\tlcd.drawEllipse(60, 80, 54, iPrevious, 20, BLACK);\/\/ Erase previous.\r\n\t\t}\r\n\t\tiPrevious = i ;\r\n\t}\r\n\tfor (int i = 46 ; i >= 6 ; i-=delta) {\r\n\t\tlcd.drawEllipse(60, 80, 54, i, 20, GREEN) ; \/\/ Draw new.\r\n\t\tlcd.drawEllipse(60, 80, 54, iPrevious, 20, BLACK) ; \/\/ Erase previous.\r\n\t\tiPrevious = i ;\r\n\t}\r\n\tdelay(2000) ;\r\n\tlcd.setInverted(true) ;\r\n\tdelay(2000) ;\r\n\tlcd.setInverted(false) ;\r\n\tdelay(2000) ;\r\n\tclearScreen(lcd) ;\r\n\t\/\/\r\n\t\/\/ Set up ball parameters\r\n\t\/\/\r\n\tball[0].setBallColor(YELLOW)\r\n\t\t\t\t\t.setTrailColor(RED)\r\n\t\t\t\t\t.setRadius(2)\r\n\t\t\t\t\t.setXCurrent(50)\r\n\t\t\t\t\t.setYCurrent(50)\r\n\t\t\t\t\t.setYVel(-ball[0].getYVel())\r\n\t\t\t\t\t.begin() ;\r\n\tball[1].setBallColor(CYAN)\r\n\t \t\t.setTrailColor(YELLOW)\r\n\t \t\t.begin() ;\r\n\tball[2].setBallColor(MAGENTA)\r\n\t\t\t\t\t.setTrailColor(GREEN)\r\n\t\t\t\t\t.setRadius(8)\r\n\t\t\t\t\t.setXCurrent(50)\r\n\t\t\t\t\t.setYCurrent(ball[2].getRadius())\r\n\t\t\t\t\t.setXVel(-ball[2].getXVel())\r\n\t\t\t\t\t.begin() ;\r\n}\r\nvoid loop() {\r\n\t\/\/\r\n\t\/\/ Knowing when it is time to switch trail colors\r\n\t\/\/\r\n\tint xVelPrevious = ball[1].getXVel();\r\n\tfor (int i = 0; i <= 2; i++) {\r\n\t\tif (i != 1) {\r\n\t\t\tball[i].update();\r\n\t\t} else {\r\n\t\t\tif (ball[i].update()) {\r\n\t\t\t\tint xVelCurrent = ball[i].getXVel();\r\n\t\t\t\tif (xVelCurrent == -xVelPrevious) {\r\n\t\t\t\t\txBouncesRemaining--;\r\n\t\t\t\t}\r\n\t\t\t\tif (xBouncesRemaining == 0) {\r\n\t\t\t\t\tfor (int j = 0; j <= 2; j++) {\r\n\t\t\t\t\t\tball[j].setTrailColor(~ball[j].getTrailColor());\r\n\t\t\t\t\t\tball[j].setBallColor(~ball[j].getBallColor());\r\n\t\t\t\t\t}\r\n\t\t\t\t\txBouncesRemaining = xBouncesToRepeat;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid clearScreen(GL_ST7735 obj) {\r\n\tobj.fillRect(0, 0, lcd.width, lcd.height, BLACK); \/\/ Clear screen.\r\n}\r\n\r\n<|endoftext|>"} {"text":"\/** @file\n *\n * @ingroup modularLibrary\n *\n * @brief A Viewer Object.\n *\n * @details\n *\n * @authors Théo de la Hogue\n *\n * @copyright © 2010, Théo de la Hogue @n\n * This code is licensed under the terms of the \"New BSD License\" @n\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\n\n#include \"TTViewer.h\"\n\n#define thisTTClass\t\t\tTTViewer\n#define thisTTClassName\t\t\"Viewer\"\n#define thisTTClassTags\t\t\"viewer\"\n\nTTObjectBasePtr TTViewer::instantiate (TTSymbol name, TTValue arguments)\n{\n\treturn new TTViewer(arguments);\n}\n\nextern \"C\" void TTViewer::registerClass()\n{\n\tTTClassRegister(TTSymbol(\"Viewer\"), thisTTClassTags, TTViewer::instantiate);\n}\n\nTTViewer::TTViewer(const TTValue& arguments) :\nTTCallback(arguments),\nmAddress(kTTAdrsEmpty),\nmDescription(kTTSym_none),\nmType(kTTSym_generic),\nmTags(kTTSym_none),\nmHighlight(NO),\nmFreeze(NO),\nmDataspace(kTTSym_none),\nmDataspaceUnit(kTTSym_none),\nmDataspaceConverter(\"dataspace\"),\nmActive(YES)\n{\n\taddAttributeWithSetter(Address, kTypeSymbol);\n\taddAttribute(Description, kTypeSymbol);\n\taddAttribute(Type, kTypeSymbol);\n\taddAttribute(Tags, kTypeSymbol);\n\taddAttributeWithSetter(Highlight, kTypeBoolean);\n\taddAttributeWithSetter(Freeze, kTypeBoolean);\n\t\n\taddAttribute(Dataspace, kTypeSymbol);\n\taddAttributeProperty(Dataspace, readOnly, YES);\n addAttributeProperty(Dataspace, hidden, YES);\n\taddAttributeWithSetter(DataspaceUnit, kTypeSymbol);\n\t\n\taddAttributeWithSetter(Active, kTypeBoolean);\n\t\n\taddAttributeWithSetter(ReturnedValue, kTypeLocalValue);\n\taddAttributeProperty(ReturnedValue, readOnly, YES);\n\taddAttributeProperty(ReturnedValue, hidden, YES);\n\t\n\taddMessageWithArguments(Send);\n\taddMessageProperty(Send, hidden, YES);\n \n addMessageWithArguments(Grab);\n\taddMessageProperty(Grab, hidden, YES);\n}\n\nTTViewer::~TTViewer()\n{\n \/\/ disable reception to avoid crash\n mActive = NO;\n}\n\nTTErr TTViewer::setAddress(const TTValue& value)\n{\n TTBoolean memoActive = mActive;\n \n\tmAddress = value[0];\n \n \/\/ disable reception to avoid crash\n mActive = NO;\n\t\n \/\/ if no address : delete sender, receiver and observers\n\tif (mAddress == kTTAdrsEmpty) {\n \n if (mSender.valid()) {\n mSender.set(kTTSym_address, kTTAdrsEmpty);\n mSender = TTObject();\n }\n \n if (mReceiver.valid()) {\n mReceiver.set(kTTSym_address, kTTAdrsEmpty);\n mReceiver = TTObject();\n }\n \n if (mDataspaceObserver.valid()) {\n mDataspaceObserver.set(kTTSym_address, kTTAdrsEmpty);\n mDataspaceObserver = TTObject();\n }\n \n if (mDataspaceUnitObserver.valid()) {\n mDataspaceUnitObserver.set(kTTSym_address, kTTAdrsEmpty);\n mDataspaceUnitObserver = TTObject();\n }\n \n\t\treturn kTTErrGeneric;\n }\n\t\n\t\/\/ the default attribute to bind is value\n\tif (mAddress.getAttribute() == NO_ATTRIBUTE)\n\t\tmAddress.appendAttribute(kTTSym_value);\n \n \/\/ create sender if needed\n if (!mSender.valid())\n mSender = TTObject(kTTSym_Sender);\n \n\t\/\/ change sender address\n\tmSender.set(kTTSym_address, mAddress);\n \n \/\/ create receiver if needed\n if (!mReceiver.valid()) {\n \n TTValue args;\n \n TTObject returnAddressCallback = TTObject(\"callback\");\n returnAddressCallback.set(kTTSym_baton, TTObject(this));\n returnAddressCallback.set(kTTSym_function, TTPtr(&TTViewerReceiveAddressCallback));\n args.append(returnAddressCallback);\n\t\n TTObject returnValueCallback = TTObject(\"callback\");\n returnValueCallback.set(kTTSym_baton, TTObject(this));\n returnValueCallback.set(kTTSym_function, TTPtr(&TTViewerReceiveValueCallback));\n args.append(returnValueCallback);\n \n mReceiver = TTObject(kTTSym_Receiver, args);\n }\n\t\n\t\/\/ change receiver address\n\tmReceiver.set(kTTSym_address, mAddress);\n \n \/\/ create dataspace observer if needed\n if (!mDataspaceObserver.valid()) {\n \n TTValue args;\n TTObject empty;\n \n args.append(empty);\n\t\n TTObject returnDataspaceCallback = TTObject(\"callback\");\n returnDataspaceCallback.set(kTTSym_baton, TTObject(this));\n returnDataspaceCallback.set(kTTSym_function, TTPtr(&TTViewerDataspaceCallback));\n args.append(returnDataspaceCallback);\n\t\n mDataspaceObserver = TTObject(kTTSym_Receiver, args);\n }\n\t\n \/\/ change dataspace observer address and get the value\n mDataspaceObserver.set(kTTSym_address, mAddress.appendAttribute(kTTSym_dataspace));\n\tmDataspaceObserver.send(kTTSym_Get);\n \n \/\/ create dataspace unit observer if needed\n if (!mDataspaceUnitObserver.valid()) {\n \n TTValue args;\n TTObject empty;\n \n args.append(empty);\n\t\n TTObject returnDataspaceUnitCallback = TTObject(\"callback\");\n returnDataspaceUnitCallback.set(kTTSym_baton, TTObject(this));\n returnDataspaceUnitCallback.set(kTTSym_function, TTPtr(&TTViewerDataspaceUnitCallback));\n args.append(returnDataspaceUnitCallback);\n\t\n mDataspaceUnitObserver = TTObject(kTTSym_Receiver, args);\n }\n \n \/\/ change dataspace unit observer address and get the value\n mDataspaceUnitObserver.set(kTTSym_address, mAddress.appendAttribute(kTTSym_dataspaceUnit));\n\tmDataspaceUnitObserver.send(kTTSym_Get);\n \n \/\/ enable reception\n mActive = memoActive;\n \n \/\/ refresh\n return mReceiver.send(kTTSym_Get);\n}\n\nTTErr TTViewer::setActive(const TTValue& value)\n{\n\tmActive = value;\n\t\n if (mReceiver.valid()) {\n \n mReceiver.set(kTTSym_active, mActive);\n \n if (mActive)\n return mReceiver.send(kTTSym_Get);\n else\n return kTTErrNone;\n }\n \n\treturn kTTErrGeneric;\n}\n\nTTErr TTViewer::setHighlight(const TTValue& value)\n{\n TTAttributePtr\tanAttribute = NULL;\n\tTTErr\t\t\terr;\n\t\n\tmHighlight = value;\n\t\n\terr = this->findAttribute(kTTSym_highlight, &anAttribute);\n\t\n\tif (!err)\n\t\tanAttribute->sendNotification(kTTSym_notify, mHighlight);\t\/\/ we use kTTSym_notify because we know that observers are TTCallback\n\t\n\treturn kTTErrNone;\n}\n\nTTErr TTViewer::setFreeze(const TTValue& value)\n{\n\tmFreeze = value;\n \n if (mReceiver.valid()) {\n \n \/\/ update the value if the Viewer is unfreezed\n if (!mFreeze)\n return mReceiver.send(kTTSym_Get);\n else\n return kTTErrNone;\n }\n\t\n\treturn kTTErrGeneric;\n}\n\nTTErr TTViewer::setReturnedValue(const TTValue& value)\n{\n\tTTAttributePtr\tanAttribute = NULL;\n\tTTErr\t\t\terr;\n\t\n\tmReturnedValue = value;\n\t\n\terr = this->findAttribute(kTTSym_returnedValue, &anAttribute);\n\t\n\tif (!err)\n\t\tanAttribute->sendNotification(kTTSym_notify, mReturnedValue);\t\/\/ we use kTTSym_notify because we know that observers are TTCallback\n\t\n\treturn kTTErrNone;\n}\n\nTTErr TTViewer::Send(const TTValue& inputValue, TTValue& outputValue)\n{\n if (!mActive)\n return kTTErrNone;\n \n TTValue none, valueToSend;\n \n \/\/ insert view unit before \"ramp\" (except for empty value)\n if (inputValue.size() > 0 &&\n mDataspaceUnit != kTTSym_none &&\n mAddress.getAttribute() == kTTSym_value)\n {\n TTBoolean ramp = false;\n \n for (TTInt32 i = 0; i < inputValue.size(); i++)\n {\n if (inputValue[i].type() == kTypeSymbol)\n {\n TTSymbol s = inputValue[i];\n if (s == kTTSym_ramp)\n {\n ramp = true;\n valueToSend.append(mDataspaceUnit);\n }\n }\n \n valueToSend.append(inputValue[i]);\n }\n \n if (!ramp)\n valueToSend.append(mDataspaceUnit);\n }\n else\n valueToSend = inputValue;\n \n if (mSender.valid())\n return mSender.send(kTTSym_Send, valueToSend);\n else\n return kTTErrGeneric;\n}\n\nTTErr TTViewer::Grab(const TTValue& inputValue, TTValue& outputValue)\n{\n if (mReceiver.valid()) {\n \n return mReceiver.send(kTTSym_Grab, inputValue, outputValue);\n }\n \n return kTTErrGeneric;\n}\n\nTTErr TTViewer::setDataspaceUnit(const TTValue& value)\n{\n\tTTValue n = value;\t\t\t\t\/\/ use new value to protect the attribute\n\tmDataspaceUnit = value;\n\t\n\treturn mDataspaceConverter.set(\"outputUnit\", mDataspaceUnit);\n\t\n\t\/\/ TODO : notifyObservers(kTTSym_dataspaceUnit, n);\n}\n\n#if 0\n#pragma mark -\n#pragma mark Some Methods\n#endif\n\nTTErr TTViewerReceiveAddressCallback(const TTValue& baton, const TTValue& data)\n{\n return kTTErrNone;\n}\n\nTTErr TTViewerReceiveValueCallback(const TTValue& baton, const TTValue& data)\n{\n TTObject o;\n\tTTViewerPtr aViewer;\n\tTTValue\t\tconverted;\n\t\n\t\/\/ unpack baton (a #TTViewer)\n o = baton[0];\n\taViewer = (TTViewerPtr)o.instance();\n\t\n\tif (aViewer->mActive) {\n\t\t\n\t\tif (!aViewer->mFreeze)\n\t\t\t\/\/ convert data\n\t\t\taViewer->mDataspaceConverter.send(\"convert\", data, converted);\n\t\t\n\t\telse\n\t\t\t\/\/ use last data\n\t\t\tconverted = aViewer->mReturnedValue;\n\t\t\t\n\t\t\/\/ return value\n aViewer->deliver(converted);\n aViewer->setReturnedValue(converted);\n\t}\n\t\n\treturn kTTErrNone;\n}\n\nTTErr TTViewerDataspaceCallback(const TTValue& baton, const TTValue& data)\n{\n TTObject o;\n\tTTViewerPtr aViewer;\n\tTTValue\t\tv;\n TTSymbol dataspace;\n\t\n\t\/\/ unpack baton (a #TTViewer)\n o = baton[0];\n\taViewer = (TTViewerPtr)o.instance();\n\t\n dataspace = data;\n \n \/\/ filter repetitions\n if (dataspace != aViewer->mDataspace) {\n \n aViewer->mDataspace = data;\n\t\n return aViewer->mDataspaceConverter.set(kTTSym_dataspace, aViewer->mDataspace);\n }\n\t\n\treturn kTTErrNone;\n}\n\nTTErr TTViewerDataspaceUnitCallback(const TTValue& baton, const TTValue& data)\n{\n TTObject o;\n\tTTViewerPtr aViewer;\n\tTTValue\t\tv;\n\tTTErr\t\terr;\n\t\n\t\/\/ unpack baton (a #TTViewer)\n o = baton[0];\n\taViewer = (TTViewerPtr)o.instance();\n\t\n \/\/ set input unit like the data unit\n aViewer->mDataspaceConverter.set(\"inputUnit\", data);\n \n \/\/ if no unit : set the output unit like the data unit\n if (aViewer->mDataspaceUnit == kTTSym_none)\n aViewer->mDataspaceUnit = data;\n \n \/\/ if the unit is wrong : use the default unit\n err = aViewer->mDataspaceConverter.set(\"outputUnit\", aViewer->mDataspaceUnit);\n if (err) {\n aViewer->mDataspaceConverter.get(\"outputUnit\", v);\n aViewer->mDataspaceUnit = v[0];\n aViewer->mDataspaceConverter.set(\"outputUnit\", aViewer->mDataspaceUnit);\n }\n\t\n\treturn kTTErrNone;\n}\nFixing #827 even when attibute is kTTSymEmpty\/** @file\n *\n * @ingroup modularLibrary\n *\n * @brief A Viewer Object.\n *\n * @details\n *\n * @authors Théo de la Hogue\n *\n * @copyright © 2010, Théo de la Hogue @n\n * This code is licensed under the terms of the \"New BSD License\" @n\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\n\n#include \"TTViewer.h\"\n\n#define thisTTClass\t\t\tTTViewer\n#define thisTTClassName\t\t\"Viewer\"\n#define thisTTClassTags\t\t\"viewer\"\n\nTTObjectBasePtr TTViewer::instantiate (TTSymbol name, TTValue arguments)\n{\n\treturn new TTViewer(arguments);\n}\n\nextern \"C\" void TTViewer::registerClass()\n{\n\tTTClassRegister(TTSymbol(\"Viewer\"), thisTTClassTags, TTViewer::instantiate);\n}\n\nTTViewer::TTViewer(const TTValue& arguments) :\nTTCallback(arguments),\nmAddress(kTTAdrsEmpty),\nmDescription(kTTSym_none),\nmType(kTTSym_generic),\nmTags(kTTSym_none),\nmHighlight(NO),\nmFreeze(NO),\nmDataspace(kTTSym_none),\nmDataspaceUnit(kTTSym_none),\nmDataspaceConverter(\"dataspace\"),\nmActive(YES)\n{\n\taddAttributeWithSetter(Address, kTypeSymbol);\n\taddAttribute(Description, kTypeSymbol);\n\taddAttribute(Type, kTypeSymbol);\n\taddAttribute(Tags, kTypeSymbol);\n\taddAttributeWithSetter(Highlight, kTypeBoolean);\n\taddAttributeWithSetter(Freeze, kTypeBoolean);\n\t\n\taddAttribute(Dataspace, kTypeSymbol);\n\taddAttributeProperty(Dataspace, readOnly, YES);\n addAttributeProperty(Dataspace, hidden, YES);\n\taddAttributeWithSetter(DataspaceUnit, kTypeSymbol);\n\t\n\taddAttributeWithSetter(Active, kTypeBoolean);\n\t\n\taddAttributeWithSetter(ReturnedValue, kTypeLocalValue);\n\taddAttributeProperty(ReturnedValue, readOnly, YES);\n\taddAttributeProperty(ReturnedValue, hidden, YES);\n\t\n\taddMessageWithArguments(Send);\n\taddMessageProperty(Send, hidden, YES);\n \n addMessageWithArguments(Grab);\n\taddMessageProperty(Grab, hidden, YES);\n}\n\nTTViewer::~TTViewer()\n{\n \/\/ disable reception to avoid crash\n mActive = NO;\n}\n\nTTErr TTViewer::setAddress(const TTValue& value)\n{\n TTBoolean memoActive = mActive;\n \n\tmAddress = value[0];\n \n \/\/ disable reception to avoid crash\n mActive = NO;\n\t\n \/\/ if no address : delete sender, receiver and observers\n\tif (mAddress == kTTAdrsEmpty) {\n \n if (mSender.valid()) {\n mSender.set(kTTSym_address, kTTAdrsEmpty);\n mSender = TTObject();\n }\n \n if (mReceiver.valid()) {\n mReceiver.set(kTTSym_address, kTTAdrsEmpty);\n mReceiver = TTObject();\n }\n \n if (mDataspaceObserver.valid()) {\n mDataspaceObserver.set(kTTSym_address, kTTAdrsEmpty);\n mDataspaceObserver = TTObject();\n }\n \n if (mDataspaceUnitObserver.valid()) {\n mDataspaceUnitObserver.set(kTTSym_address, kTTAdrsEmpty);\n mDataspaceUnitObserver = TTObject();\n }\n \n\t\treturn kTTErrGeneric;\n }\n\t\n\t\/\/ the default attribute to bind is value\n\tif (mAddress.getAttribute() == NO_ATTRIBUTE)\n\t\tmAddress.appendAttribute(kTTSym_value);\n \n \/\/ create sender if needed\n if (!mSender.valid())\n mSender = TTObject(kTTSym_Sender);\n \n\t\/\/ change sender address\n\tmSender.set(kTTSym_address, mAddress);\n \n \/\/ create receiver if needed\n if (!mReceiver.valid()) {\n \n TTValue args;\n \n TTObject returnAddressCallback = TTObject(\"callback\");\n returnAddressCallback.set(kTTSym_baton, TTObject(this));\n returnAddressCallback.set(kTTSym_function, TTPtr(&TTViewerReceiveAddressCallback));\n args.append(returnAddressCallback);\n\t\n TTObject returnValueCallback = TTObject(\"callback\");\n returnValueCallback.set(kTTSym_baton, TTObject(this));\n returnValueCallback.set(kTTSym_function, TTPtr(&TTViewerReceiveValueCallback));\n args.append(returnValueCallback);\n \n mReceiver = TTObject(kTTSym_Receiver, args);\n }\n\t\n\t\/\/ change receiver address\n\tmReceiver.set(kTTSym_address, mAddress);\n \n \/\/ create dataspace observer if needed\n if (!mDataspaceObserver.valid()) {\n \n TTValue args;\n TTObject empty;\n \n args.append(empty);\n\t\n TTObject returnDataspaceCallback = TTObject(\"callback\");\n returnDataspaceCallback.set(kTTSym_baton, TTObject(this));\n returnDataspaceCallback.set(kTTSym_function, TTPtr(&TTViewerDataspaceCallback));\n args.append(returnDataspaceCallback);\n\t\n mDataspaceObserver = TTObject(kTTSym_Receiver, args);\n }\n\t\n \/\/ change dataspace observer address and get the value\n mDataspaceObserver.set(kTTSym_address, mAddress.appendAttribute(kTTSym_dataspace));\n\tmDataspaceObserver.send(kTTSym_Get);\n \n \/\/ create dataspace unit observer if needed\n if (!mDataspaceUnitObserver.valid()) {\n \n TTValue args;\n TTObject empty;\n \n args.append(empty);\n\t\n TTObject returnDataspaceUnitCallback = TTObject(\"callback\");\n returnDataspaceUnitCallback.set(kTTSym_baton, TTObject(this));\n returnDataspaceUnitCallback.set(kTTSym_function, TTPtr(&TTViewerDataspaceUnitCallback));\n args.append(returnDataspaceUnitCallback);\n\t\n mDataspaceUnitObserver = TTObject(kTTSym_Receiver, args);\n }\n \n \/\/ change dataspace unit observer address and get the value\n mDataspaceUnitObserver.set(kTTSym_address, mAddress.appendAttribute(kTTSym_dataspaceUnit));\n\tmDataspaceUnitObserver.send(kTTSym_Get);\n \n \/\/ enable reception\n mActive = memoActive;\n \n \/\/ refresh\n return mReceiver.send(kTTSym_Get);\n}\n\nTTErr TTViewer::setActive(const TTValue& value)\n{\n\tmActive = value;\n\t\n if (mReceiver.valid()) {\n \n mReceiver.set(kTTSym_active, mActive);\n \n if (mActive)\n return mReceiver.send(kTTSym_Get);\n else\n return kTTErrNone;\n }\n \n\treturn kTTErrGeneric;\n}\n\nTTErr TTViewer::setHighlight(const TTValue& value)\n{\n TTAttributePtr\tanAttribute = NULL;\n\tTTErr\t\t\terr;\n\t\n\tmHighlight = value;\n\t\n\terr = this->findAttribute(kTTSym_highlight, &anAttribute);\n\t\n\tif (!err)\n\t\tanAttribute->sendNotification(kTTSym_notify, mHighlight);\t\/\/ we use kTTSym_notify because we know that observers are TTCallback\n\t\n\treturn kTTErrNone;\n}\n\nTTErr TTViewer::setFreeze(const TTValue& value)\n{\n\tmFreeze = value;\n \n if (mReceiver.valid()) {\n \n \/\/ update the value if the Viewer is unfreezed\n if (!mFreeze)\n return mReceiver.send(kTTSym_Get);\n else\n return kTTErrNone;\n }\n\t\n\treturn kTTErrGeneric;\n}\n\nTTErr TTViewer::setReturnedValue(const TTValue& value)\n{\n\tTTAttributePtr\tanAttribute = NULL;\n\tTTErr\t\t\terr;\n\t\n\tmReturnedValue = value;\n\t\n\terr = this->findAttribute(kTTSym_returnedValue, &anAttribute);\n\t\n\tif (!err)\n\t\tanAttribute->sendNotification(kTTSym_notify, mReturnedValue);\t\/\/ we use kTTSym_notify because we know that observers are TTCallback\n\t\n\treturn kTTErrNone;\n}\n\nTTErr TTViewer::Send(const TTValue& inputValue, TTValue& outputValue)\n{\n if (!mActive)\n return kTTErrNone;\n \n TTValue none, valueToSend;\n\n \/\/ insert view unit before \"ramp\" (except for empty value)\n if (inputValue.size() > 0 &&\n mDataspaceUnit != kTTSym_none &&\n (mAddress.getAttribute() == kTTSym_value || mAddress.getAttribute() == kTTSymEmpty))\n {\n TTBoolean ramp = false;\n \n for (TTInt32 i = 0; i < inputValue.size(); i++)\n {\n if (inputValue[i].type() == kTypeSymbol)\n {\n TTSymbol s = inputValue[i];\n if (s == kTTSym_ramp)\n {\n ramp = true;\n valueToSend.append(mDataspaceUnit);\n }\n }\n \n valueToSend.append(inputValue[i]);\n }\n \n if (!ramp)\n valueToSend.append(mDataspaceUnit);\n }\n else\n valueToSend = inputValue;\n \n if (mSender.valid())\n return mSender.send(kTTSym_Send, valueToSend);\n else\n return kTTErrGeneric;\n}\n\nTTErr TTViewer::Grab(const TTValue& inputValue, TTValue& outputValue)\n{\n if (mReceiver.valid()) {\n \n return mReceiver.send(kTTSym_Grab, inputValue, outputValue);\n }\n \n return kTTErrGeneric;\n}\n\nTTErr TTViewer::setDataspaceUnit(const TTValue& value)\n{\n\tTTValue n = value;\t\t\t\t\/\/ use new value to protect the attribute\n\tmDataspaceUnit = value;\n\t\n\treturn mDataspaceConverter.set(\"outputUnit\", mDataspaceUnit);\n\t\n\t\/\/ TODO : notifyObservers(kTTSym_dataspaceUnit, n);\n}\n\n#if 0\n#pragma mark -\n#pragma mark Some Methods\n#endif\n\nTTErr TTViewerReceiveAddressCallback(const TTValue& baton, const TTValue& data)\n{\n return kTTErrNone;\n}\n\nTTErr TTViewerReceiveValueCallback(const TTValue& baton, const TTValue& data)\n{\n TTObject o;\n\tTTViewerPtr aViewer;\n\tTTValue\t\tconverted;\n\t\n\t\/\/ unpack baton (a #TTViewer)\n o = baton[0];\n\taViewer = (TTViewerPtr)o.instance();\n\t\n\tif (aViewer->mActive) {\n\t\t\n\t\tif (!aViewer->mFreeze)\n\t\t\t\/\/ convert data\n\t\t\taViewer->mDataspaceConverter.send(\"convert\", data, converted);\n\t\t\n\t\telse\n\t\t\t\/\/ use last data\n\t\t\tconverted = aViewer->mReturnedValue;\n\t\t\t\n\t\t\/\/ return value\n aViewer->deliver(converted);\n aViewer->setReturnedValue(converted);\n\t}\n\t\n\treturn kTTErrNone;\n}\n\nTTErr TTViewerDataspaceCallback(const TTValue& baton, const TTValue& data)\n{\n TTObject o;\n\tTTViewerPtr aViewer;\n\tTTValue\t\tv;\n TTSymbol dataspace;\n\t\n\t\/\/ unpack baton (a #TTViewer)\n o = baton[0];\n\taViewer = (TTViewerPtr)o.instance();\n\t\n dataspace = data;\n \n \/\/ filter repetitions\n if (dataspace != aViewer->mDataspace) {\n \n aViewer->mDataspace = data;\n\t\n return aViewer->mDataspaceConverter.set(kTTSym_dataspace, aViewer->mDataspace);\n }\n\t\n\treturn kTTErrNone;\n}\n\nTTErr TTViewerDataspaceUnitCallback(const TTValue& baton, const TTValue& data)\n{\n TTObject o;\n\tTTViewerPtr aViewer;\n\tTTValue\t\tv;\n\tTTErr\t\terr;\n\t\n\t\/\/ unpack baton (a #TTViewer)\n o = baton[0];\n\taViewer = (TTViewerPtr)o.instance();\n\t\n \/\/ set input unit like the data unit\n aViewer->mDataspaceConverter.set(\"inputUnit\", data);\n \n \/\/ if no unit : set the output unit like the data unit\n if (aViewer->mDataspaceUnit == kTTSym_none)\n aViewer->mDataspaceUnit = data;\n \n \/\/ if the unit is wrong : use the default unit\n err = aViewer->mDataspaceConverter.set(\"outputUnit\", aViewer->mDataspaceUnit);\n if (err) {\n aViewer->mDataspaceConverter.get(\"outputUnit\", v);\n aViewer->mDataspaceUnit = v[0];\n aViewer->mDataspaceConverter.set(\"outputUnit\", aViewer->mDataspaceUnit);\n }\n\t\n\treturn kTTErrNone;\n}\n<|endoftext|>"} {"text":"\/\/ -------------------------------------------------------------------------\r\n\/\/ @FileName\t\t\t: NFCLogModule.cpp\r\n\/\/ @Author : LvSheng.Huang\r\n\/\/ @Date : 2012-12-15\r\n\/\/ @Module : NFCLogModule\r\n\/\/ @Desc :\r\n\/\/ -------------------------------------------------------------------------\r\n\r\n#define GLOG_NO_ABBREVIATED_SEVERITIES\r\n#include \r\n#include \"NFCLogModule.h\"\r\n#include \"easylogging++.h\"\r\n\r\nINITIALIZE_EASYLOGGINGPP\r\n\r\nunsigned int NFCLogModule::idx = 0;\r\n\r\nbool NFCLogModule::CheckLogFileExist(const char* filename)\r\n{\r\n std::stringstream stream;\r\n stream << filename << \".\" << ++idx;\r\n std::fstream file;\r\n file.open(stream.str(), std::ios::in);\r\n if (file)\r\n {\r\n return CheckLogFileExist(filename);\r\n }\r\n\r\n return false;\r\n}\r\n\r\nvoid NFCLogModule::rolloutHandler(const char* filename, std::size_t size)\r\n{\r\n std::stringstream stream;\r\n if (!CheckLogFileExist(filename))\r\n {\r\n stream << filename << \".\" << idx;\r\n rename(filename, stream.str().c_str());\r\n }\r\n}\r\n\r\nNFCLogModule::NFCLogModule(NFIPluginManager* p)\r\n{\r\n pPluginManager = p;\r\n}\r\n\r\nbool NFCLogModule::Init()\r\n{\r\n mnLogCountTotal = 0;\r\n\r\n el::Loggers::addFlag(el::LoggingFlag::StrictLogFileSizeCheck);\r\n el::Loggers::addFlag(el::LoggingFlag::DisableApplicationAbortOnFatalLog);\r\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n el::Configurations conf(\"log_win.conf\");\r\n#else\r\n el::Configurations conf(\"log.conf\");\r\n#endif\r\n el::Loggers::reconfigureAllLoggers(conf);\r\n el::Helpers::installPreRollOutCallback(rolloutHandler);\r\n\r\n return true;\r\n}\r\n\r\nbool NFCLogModule::Shut()\r\n{\r\n el::Helpers::uninstallPreRollOutCallback();\r\n\r\n return true;\r\n}\r\n\r\nbool NFCLogModule::BeforeShut()\r\n{\r\n return true;\r\n\r\n}\r\n\r\nbool NFCLogModule::AfterInit()\r\n{\r\n return true;\r\n\r\n}\r\n\r\nbool NFCLogModule::Execute()\r\n{\r\n return true;\r\n\r\n}\r\n\r\nbool NFCLogModule::Log(const NF_LOG_LEVEL nll, const char* format, ...)\r\n{\r\n mnLogCountTotal++;\r\n\r\n char szBuffer[1024 * 10] = {0};\r\n\r\n va_list args;\r\n va_start(args, format);\r\n vsnprintf(szBuffer, sizeof(szBuffer) - 1, format, args);\r\n va_end(args);\r\n\r\n switch (nll)\r\n {\r\n case NFILogModule::NLL_DEBUG_NORMAL:\r\n LOG(DEBUG) << mnLogCountTotal << \" \" << szBuffer;\r\n break;\r\n case NFILogModule::NLL_INFO_NORMAL:\r\n LOG(INFO) << mnLogCountTotal << \" \" << szBuffer;\r\n break;\r\n case NFILogModule::NLL_WARING_NORMAL:\r\n LOG(WARNING) << mnLogCountTotal << \" \" << szBuffer;\r\n break;\r\n case NFILogModule::NLL_ERROR_NORMAL:\r\n {\r\n LOG(ERROR) << mnLogCountTotal << \" \" << szBuffer;\r\n \/\/LogStack();\r\n }\r\n break;\r\n case NFILogModule::NLL_FATAL_NORMAL:\r\n LOG(FATAL) << mnLogCountTotal << \" \" << szBuffer;\r\n break;\r\n default:\r\n LOG(INFO) << mnLogCountTotal << \" \" << szBuffer;\r\n break;\r\n }\r\n\r\n return true;\r\n}\r\n\r\nbool NFCLogModule::LogElement(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strElement, const std::string& strDesc, const char* func, int line)\r\n{\r\n if (line > 0)\r\n {\r\n Log(nll, \"[ELEMENT] Indent[%s] Element[%s] %s %s %d\", ident.ToString().c_str(), strElement.c_str(), strDesc.c_str(), func, line);\r\n }\r\n else\r\n {\r\n Log(nll, \"[ELEMENT] Indent[%s] Element[%s] %s\", ident.ToString().c_str(), strElement.c_str(), strDesc.c_str());\r\n }\r\n\r\n return true;\r\n}\r\n\r\nbool NFCLogModule::LogProperty(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strProperty, const std::string& strDesc, const char* func, int line)\r\n{\r\n if (line > 0)\r\n {\r\n Log(nll, \"[PROPERTY] Indent[%s] Property[%s] %s %s %d\", ident.ToString().c_str(), strProperty.c_str(), strDesc.c_str(), func, line);\r\n }\r\n else\r\n {\r\n Log(nll, \"[PROPERTY] Indent[%s] Property[%s] %s\", ident.ToString().c_str(), strProperty.c_str(), strDesc.c_str());\r\n }\r\n\r\n return true;\r\n\r\n}\r\n\r\nbool NFCLogModule::LogRecord(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strRecord, const std::string& strDesc, const int nRow, const int nCol, const char* func, int line)\r\n{\r\n if (line > 0)\r\n {\r\n Log(nll, \"[RECORD] Indent[%s] Record[%s] Row[%d] Col[%d] %s %s %d\", ident.ToString().c_str(), strRecord.c_str(), nRow, nCol, strDesc.c_str(), func, line);\r\n }\r\n else\r\n {\r\n Log(nll, \"[RECORD] Indent[%s] Record[%s] Row[%d] Col[%d] %s\", ident.ToString().c_str(), strRecord.c_str(), nRow, nCol, strDesc.c_str());\r\n }\r\n\r\n return true;\r\n\r\n}\r\n\r\nbool NFCLogModule::LogRecord(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strRecord, const std::string& strDesc, const char* func, int line)\r\n{\r\n if (line > 0)\r\n {\r\n Log(nll, \"[RECORD] Indent[%s] Record[%s] %s %s %d\", ident.ToString().c_str(), strRecord.c_str(), strDesc.c_str(), func, line);\r\n }\r\n else\r\n {\r\n Log(nll, \"[RECORD] Indent[%s] Record[%s] %s\", ident.ToString().c_str(), strRecord.c_str(), strDesc.c_str());\r\n }\r\n\r\n return true;\r\n}\r\n\r\nbool NFCLogModule::LogObject(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strDesc, const char* func, int line)\r\n{\r\n if (line > 0)\r\n {\r\n Log(nll, \"[OBJECT] Indent[%s] %s %s %d\", ident.ToString().c_str(), strDesc.c_str(), func, line);\r\n }\r\n else\r\n {\r\n Log(nll, \"[OBJECT] Indent[%s] %s\", ident.ToString().c_str(), strDesc.c_str());\r\n }\r\n\r\n return true;\r\n\r\n}\r\n\r\nvoid NFCLogModule::LogStack()\r\n{\r\n\r\n \/\/To Add\r\n \/*\r\n #ifdef NF_DEBUG_MODE\r\n time_t t = time(0);\r\n char szDmupName[MAX_PATH];\r\n tm* ptm = localtime(&t);\r\n\r\n sprintf(szDmupName, \"%d_%d_%d_%d_%d_%d.dmp\", ptm->tm_year + 1900, ptm->tm_mon, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);\r\n \/\/ 创建Dump文件\r\n HANDLE hDumpFile = CreateFile(szDmupName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\r\n\r\n \/\/ Dump信息\r\n MINIDUMP_EXCEPTION_INFORMATION dumpInfo;\r\n \/\/dumpInfo.ExceptionPointers = pException;\r\n dumpInfo.ThreadId = GetCurrentThreadId();\r\n dumpInfo.ClientPointers = TRUE;\r\n\r\n \/\/ 写入Dump文件内容\r\n MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);\r\n\r\n CloseHandle(hDumpFile);\r\n\r\n #endif\r\n *\/\r\n}\r\n\r\nbool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strInfo, const std::string& strDesc, const char* func, int line)\r\n{\r\n if (line > 0)\r\n {\r\n Log(nll, \"Indent[%s] %s %s %s %d\", ident.ToString().c_str(), strInfo.c_str(), strDesc.c_str(), func, line);\r\n }\r\n else\r\n {\r\n Log(nll, \"Indent[%s] %s %s\", ident.ToString().c_str(), strInfo.c_str(), strDesc.c_str());\r\n }\r\n\r\n return true;\r\n}\r\n\r\nbool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strInfo, const int nDesc, const char* func, int line)\r\n{\r\n if (line > 0)\r\n {\r\n Log(nll, \"Indent[%s] %s %d %s %d\", ident.ToString().c_str(), strInfo.c_str(), nDesc, func, line);\r\n }\r\n else\r\n {\r\n Log(nll, \"Indent[%s] %s %d\", ident.ToString().c_str(), strInfo.c_str(), nDesc);\r\n }\r\n\r\n return true;\r\n}\r\n\r\nbool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFGUID ident, const std::ostringstream& stream, const char* func, int line)\r\n{\r\n if (line > 0)\r\n {\r\n Log(nll, \"Indent[%s] %s %s %d\", ident.ToString().c_str(), strInfo.c_str(), func, line);\r\n }\r\n else\r\n {\r\n Log(nll, \"Indent[%s] %s\", ident.ToString().c_str(), strInfo.c_str());\r\n }\r\n\r\n return true;\r\n}\r\n\r\nbool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strInfo, const char* func \/*= \"\"*\/, int line \/*= 0*\/)\r\n{\r\n if (line > 0)\r\n {\r\n Log(nll, \"Indent[%s] %s %s %d\", ident.ToString().c_str(), strInfo.c_str(), func, line);\r\n }\r\n else\r\n {\r\n Log(nll, \"Indent[%s] %s\", ident.ToString().c_str(), strInfo.c_str());\r\n }\r\n\r\n return true;\r\n}\r\n\r\nbool NFCLogModule::LogDebugFunctionDump(const NFGUID ident, const int nMsg, const std::string& strArg, const char* func \/*= \"\"*\/, const int line \/*= 0*\/)\r\n{\r\n \/\/#ifdef NF_DEBUG_MODE\r\n LogNormal(NFILogModule::NLL_WARING_NORMAL, ident, strArg + \"MsgID:\", nMsg, func, line);\r\n \/\/#endif\r\n return true;\r\n}\r\n\r\nbool NFCLogModule::ChangeLogLevel(const std::string& strLevel)\r\n{\r\n el::Level logLevel = el::LevelHelper::convertFromString(strLevel.c_str());\r\n el::Logger* pLogger = el::Loggers::getLogger(\"default\");\r\n if (NULL == pLogger)\r\n {\r\n return false;\r\n }\r\n\r\n el::Configurations* pConfigurations = pLogger->configurations();\r\n el::base::TypedConfigurations* pTypeConfigurations = pLogger->typedConfigurations();\r\n if (NULL == pConfigurations)\r\n {\r\n return false;\r\n }\r\n\r\n \/\/ log级别为debug, info, warning, error, fatal(级别逐渐提高)\r\n \/\/ 当传入为info时,则高于(包含)info的级别会输出\r\n \/\/ !!!!!! NOTICE:故意没有break,请千万注意 !!!!!!\r\n switch (logLevel)\r\n {\r\n case el::Level::Fatal:\r\n {\r\n el::Configuration errorConfiguration(el::Level::Error, el::ConfigurationType::Enabled, \"false\");\r\n pConfigurations->set(&errorConfiguration);\r\n }\r\n case el::Level::Error:\r\n {\r\n el::Configuration warnConfiguration(el::Level::Warning, el::ConfigurationType::Enabled, \"false\");\r\n pConfigurations->set(&warnConfiguration);\r\n }\r\n case el::Level::Warning:\r\n {\r\n el::Configuration infoConfiguration(el::Level::Info, el::ConfigurationType::Enabled, \"false\");\r\n pConfigurations->set(&infoConfiguration);\r\n }\r\n case el::Level::Info:\r\n {\r\n el::Configuration debugConfiguration(el::Level::Debug, el::ConfigurationType::Enabled, \"false\");\r\n pConfigurations->set(&debugConfiguration);\r\n\r\n }\r\n case el::Level::Debug:\r\n break;\r\n default:\r\n break;\r\n }\r\n\r\n el::Loggers::reconfigureAllLoggers(*pConfigurations);\r\n LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(), \"[Log] Change log level\", strLevel, __FUNCTION__, __LINE__);\r\n return true;\r\n}\r\nfixed for log module\/\/ -------------------------------------------------------------------------\r\n\/\/ @FileName\t\t\t: NFCLogModule.cpp\r\n\/\/ @Author : LvSheng.Huang\r\n\/\/ @Date : 2012-12-15\r\n\/\/ @Module : NFCLogModule\r\n\/\/ @Desc :\r\n\/\/ -------------------------------------------------------------------------\r\n\r\n#define GLOG_NO_ABBREVIATED_SEVERITIES\r\n#include \r\n#include \"NFCLogModule.h\"\r\n#include \"easylogging++.h\"\r\n\r\nINITIALIZE_EASYLOGGINGPP\r\n\r\nunsigned int NFCLogModule::idx = 0;\r\n\r\nbool NFCLogModule::CheckLogFileExist(const char* filename)\r\n{\r\n std::stringstream stream;\r\n stream << filename << \".\" << ++idx;\r\n std::fstream file;\r\n file.open(stream.str(), std::ios::in);\r\n if (file)\r\n {\r\n return CheckLogFileExist(filename);\r\n }\r\n\r\n return false;\r\n}\r\n\r\nvoid NFCLogModule::rolloutHandler(const char* filename, std::size_t size)\r\n{\r\n std::stringstream stream;\r\n if (!CheckLogFileExist(filename))\r\n {\r\n stream << filename << \".\" << idx;\r\n rename(filename, stream.str().c_str());\r\n }\r\n}\r\n\r\nNFCLogModule::NFCLogModule(NFIPluginManager* p)\r\n{\r\n pPluginManager = p;\r\n}\r\n\r\nbool NFCLogModule::Init()\r\n{\r\n mnLogCountTotal = 0;\r\n\r\n el::Loggers::addFlag(el::LoggingFlag::StrictLogFileSizeCheck);\r\n el::Loggers::addFlag(el::LoggingFlag::DisableApplicationAbortOnFatalLog);\r\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n el::Configurations conf(\"log_win.conf\");\r\n#else\r\n el::Configurations conf(\"log.conf\");\r\n#endif\r\n el::Loggers::reconfigureAllLoggers(conf);\r\n el::Helpers::installPreRollOutCallback(rolloutHandler);\r\n\r\n return true;\r\n}\r\n\r\nbool NFCLogModule::Shut()\r\n{\r\n el::Helpers::uninstallPreRollOutCallback();\r\n\r\n return true;\r\n}\r\n\r\nbool NFCLogModule::BeforeShut()\r\n{\r\n return true;\r\n\r\n}\r\n\r\nbool NFCLogModule::AfterInit()\r\n{\r\n return true;\r\n\r\n}\r\n\r\nbool NFCLogModule::Execute()\r\n{\r\n return true;\r\n\r\n}\r\n\r\nbool NFCLogModule::Log(const NF_LOG_LEVEL nll, const char* format, ...)\r\n{\r\n mnLogCountTotal++;\r\n\r\n char szBuffer[1024 * 10] = {0};\r\n\r\n va_list args;\r\n va_start(args, format);\r\n vsnprintf(szBuffer, sizeof(szBuffer) - 1, format, args);\r\n va_end(args);\r\n\r\n switch (nll)\r\n {\r\n case NFILogModule::NLL_DEBUG_NORMAL:\r\n LOG(DEBUG) << mnLogCountTotal << \" \" << szBuffer;\r\n break;\r\n case NFILogModule::NLL_INFO_NORMAL:\r\n LOG(INFO) << mnLogCountTotal << \" \" << szBuffer;\r\n break;\r\n case NFILogModule::NLL_WARING_NORMAL:\r\n LOG(WARNING) << mnLogCountTotal << \" \" << szBuffer;\r\n break;\r\n case NFILogModule::NLL_ERROR_NORMAL:\r\n {\r\n LOG(ERROR) << mnLogCountTotal << \" \" << szBuffer;\r\n \/\/LogStack();\r\n }\r\n break;\r\n case NFILogModule::NLL_FATAL_NORMAL:\r\n LOG(FATAL) << mnLogCountTotal << \" \" << szBuffer;\r\n break;\r\n default:\r\n LOG(INFO) << mnLogCountTotal << \" \" << szBuffer;\r\n break;\r\n }\r\n\r\n return true;\r\n}\r\n\r\nbool NFCLogModule::LogElement(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strElement, const std::string& strDesc, const char* func, int line)\r\n{\r\n if (line > 0)\r\n {\r\n Log(nll, \"[ELEMENT] Indent[%s] Element[%s] %s %s %d\", ident.ToString().c_str(), strElement.c_str(), strDesc.c_str(), func, line);\r\n }\r\n else\r\n {\r\n Log(nll, \"[ELEMENT] Indent[%s] Element[%s] %s\", ident.ToString().c_str(), strElement.c_str(), strDesc.c_str());\r\n }\r\n\r\n return true;\r\n}\r\n\r\nbool NFCLogModule::LogProperty(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strProperty, const std::string& strDesc, const char* func, int line)\r\n{\r\n if (line > 0)\r\n {\r\n Log(nll, \"[PROPERTY] Indent[%s] Property[%s] %s %s %d\", ident.ToString().c_str(), strProperty.c_str(), strDesc.c_str(), func, line);\r\n }\r\n else\r\n {\r\n Log(nll, \"[PROPERTY] Indent[%s] Property[%s] %s\", ident.ToString().c_str(), strProperty.c_str(), strDesc.c_str());\r\n }\r\n\r\n return true;\r\n\r\n}\r\n\r\nbool NFCLogModule::LogRecord(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strRecord, const std::string& strDesc, const int nRow, const int nCol, const char* func, int line)\r\n{\r\n if (line > 0)\r\n {\r\n Log(nll, \"[RECORD] Indent[%s] Record[%s] Row[%d] Col[%d] %s %s %d\", ident.ToString().c_str(), strRecord.c_str(), nRow, nCol, strDesc.c_str(), func, line);\r\n }\r\n else\r\n {\r\n Log(nll, \"[RECORD] Indent[%s] Record[%s] Row[%d] Col[%d] %s\", ident.ToString().c_str(), strRecord.c_str(), nRow, nCol, strDesc.c_str());\r\n }\r\n\r\n return true;\r\n\r\n}\r\n\r\nbool NFCLogModule::LogRecord(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strRecord, const std::string& strDesc, const char* func, int line)\r\n{\r\n if (line > 0)\r\n {\r\n Log(nll, \"[RECORD] Indent[%s] Record[%s] %s %s %d\", ident.ToString().c_str(), strRecord.c_str(), strDesc.c_str(), func, line);\r\n }\r\n else\r\n {\r\n Log(nll, \"[RECORD] Indent[%s] Record[%s] %s\", ident.ToString().c_str(), strRecord.c_str(), strDesc.c_str());\r\n }\r\n\r\n return true;\r\n}\r\n\r\nbool NFCLogModule::LogObject(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strDesc, const char* func, int line)\r\n{\r\n if (line > 0)\r\n {\r\n Log(nll, \"[OBJECT] Indent[%s] %s %s %d\", ident.ToString().c_str(), strDesc.c_str(), func, line);\r\n }\r\n else\r\n {\r\n Log(nll, \"[OBJECT] Indent[%s] %s\", ident.ToString().c_str(), strDesc.c_str());\r\n }\r\n\r\n return true;\r\n\r\n}\r\n\r\nvoid NFCLogModule::LogStack()\r\n{\r\n\r\n \/\/To Add\r\n \/*\r\n #ifdef NF_DEBUG_MODE\r\n time_t t = time(0);\r\n char szDmupName[MAX_PATH];\r\n tm* ptm = localtime(&t);\r\n\r\n sprintf(szDmupName, \"%d_%d_%d_%d_%d_%d.dmp\", ptm->tm_year + 1900, ptm->tm_mon, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);\r\n \/\/ 创建Dump文件\r\n HANDLE hDumpFile = CreateFile(szDmupName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\r\n\r\n \/\/ Dump信息\r\n MINIDUMP_EXCEPTION_INFORMATION dumpInfo;\r\n \/\/dumpInfo.ExceptionPointers = pException;\r\n dumpInfo.ThreadId = GetCurrentThreadId();\r\n dumpInfo.ClientPointers = TRUE;\r\n\r\n \/\/ 写入Dump文件内容\r\n MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);\r\n\r\n CloseHandle(hDumpFile);\r\n\r\n #endif\r\n *\/\r\n}\r\n\r\nbool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strInfo, const std::string& strDesc, const char* func, int line)\r\n{\r\n if (line > 0)\r\n {\r\n Log(nll, \"Indent[%s] %s %s %s %d\", ident.ToString().c_str(), strInfo.c_str(), strDesc.c_str(), func, line);\r\n }\r\n else\r\n {\r\n Log(nll, \"Indent[%s] %s %s\", ident.ToString().c_str(), strInfo.c_str(), strDesc.c_str());\r\n }\r\n\r\n return true;\r\n}\r\n\r\nbool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strInfo, const int nDesc, const char* func, int line)\r\n{\r\n if (line > 0)\r\n {\r\n Log(nll, \"Indent[%s] %s %d %s %d\", ident.ToString().c_str(), strInfo.c_str(), nDesc, func, line);\r\n }\r\n else\r\n {\r\n Log(nll, \"Indent[%s] %s %d\", ident.ToString().c_str(), strInfo.c_str(), nDesc);\r\n }\r\n\r\n return true;\r\n}\r\n\r\nbool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFGUID ident, const std::ostringstream& stream, const char* func, int line)\r\n{\r\n if (line > 0)\r\n {\r\n Log(nll, \"Indent[%s] %s %d\", ident.ToString().c_str(), func, line);\r\n }\r\n else\r\n {\r\n Log(nll, \"Indent[%s] %s\", ident.ToString().c_str());\r\n }\r\n\r\n return true;\r\n}\r\n\r\nbool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strInfo, const char* func \/*= \"\"*\/, int line \/*= 0*\/)\r\n{\r\n if (line > 0)\r\n {\r\n Log(nll, \"Indent[%s] %s %s %d\", ident.ToString().c_str(), strInfo.c_str(), func, line);\r\n }\r\n else\r\n {\r\n Log(nll, \"Indent[%s] %s\", ident.ToString().c_str(), strInfo.c_str());\r\n }\r\n\r\n return true;\r\n}\r\n\r\nbool NFCLogModule::LogDebugFunctionDump(const NFGUID ident, const int nMsg, const std::string& strArg, const char* func \/*= \"\"*\/, const int line \/*= 0*\/)\r\n{\r\n \/\/#ifdef NF_DEBUG_MODE\r\n LogNormal(NFILogModule::NLL_WARING_NORMAL, ident, strArg + \"MsgID:\", nMsg, func, line);\r\n \/\/#endif\r\n return true;\r\n}\r\n\r\nbool NFCLogModule::ChangeLogLevel(const std::string& strLevel)\r\n{\r\n el::Level logLevel = el::LevelHelper::convertFromString(strLevel.c_str());\r\n el::Logger* pLogger = el::Loggers::getLogger(\"default\");\r\n if (NULL == pLogger)\r\n {\r\n return false;\r\n }\r\n\r\n el::Configurations* pConfigurations = pLogger->configurations();\r\n el::base::TypedConfigurations* pTypeConfigurations = pLogger->typedConfigurations();\r\n if (NULL == pConfigurations)\r\n {\r\n return false;\r\n }\r\n\r\n \/\/ log级别为debug, info, warning, error, fatal(级别逐渐提高)\r\n \/\/ 当传入为info时,则高于(包含)info的级别会输出\r\n \/\/ !!!!!! NOTICE:故意没有break,请千万注意 !!!!!!\r\n switch (logLevel)\r\n {\r\n case el::Level::Fatal:\r\n {\r\n el::Configuration errorConfiguration(el::Level::Error, el::ConfigurationType::Enabled, \"false\");\r\n pConfigurations->set(&errorConfiguration);\r\n }\r\n case el::Level::Error:\r\n {\r\n el::Configuration warnConfiguration(el::Level::Warning, el::ConfigurationType::Enabled, \"false\");\r\n pConfigurations->set(&warnConfiguration);\r\n }\r\n case el::Level::Warning:\r\n {\r\n el::Configuration infoConfiguration(el::Level::Info, el::ConfigurationType::Enabled, \"false\");\r\n pConfigurations->set(&infoConfiguration);\r\n }\r\n case el::Level::Info:\r\n {\r\n el::Configuration debugConfiguration(el::Level::Debug, el::ConfigurationType::Enabled, \"false\");\r\n pConfigurations->set(&debugConfiguration);\r\n\r\n }\r\n case el::Level::Debug:\r\n break;\r\n default:\r\n break;\r\n }\r\n\r\n el::Loggers::reconfigureAllLoggers(*pConfigurations);\r\n LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(), \"[Log] Change log level\", strLevel, __FUNCTION__, __LINE__);\r\n return true;\r\n}\r\n<|endoftext|>"} {"text":"\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2008 Torus Knot Software Ltd\nAlso see acknowledgements in Readme.html\n\nThis program is free software; you can redistribute it and\/or modify it under\nthe terms of the GNU Lesser General Public License as published by the Free Software\nFoundation; either version 2 of the License, or (at your option) any later\nversion.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License along with\nthis program; if not, write to the Free Software Foundation, Inc., 59 Temple\nPlace - Suite 330, Boston, MA 02111-1307, USA, or go to\nhttp:\/\/www.gnu.org\/copyleft\/lesser.txt.\n\nYou may alternatively use this source under the terms of a specific version of\nthe OGRE Unrestricted License provided you have obtained such a license from\nTorus Knot Software Ltd.\n-----------------------------------------------------------------------------\n*\/\n#include \"OgreStableHeaders.h\"\n#include \"OgrePrerequisites.h\"\n#include \"OgreMemoryNedAlloc.h\"\n#include \"OgrePlatformInformation.h\"\n#include \"OgreMemoryTracker.h\"\n\n#if OGRE_MEMORY_ALLOCATOR == OGRE_MEMORY_ALLOCATOR_NED\n\n\/\/ include ned implementation\n#include \n\nnamespace Ogre\n{\n\n\t\/\/---------------------------------------------------------------------\n\tvoid* NedAllocImpl::allocBytes(size_t count, \n\t\tconst char* file, int line, const char* func)\n\t{\n\t\tvoid* ptr = nedalloc::nedmalloc(count);\n\t#if OGRE_MEMORY_TRACKER\n\t\t\/\/ this alloc policy doesn't do pools (yet, ned can do it)\n\t\tMemoryTracker::get()._recordAlloc(ptr, count, 0, file, line, func);\n\t#else\n\t\t\/\/ avoid unused params warning\n\t\tfile;line;func;\n\t#endif\n\t\treturn ptr;\n\t}\n\t\/\/---------------------------------------------------------------------\n\tvoid NedAllocImpl::deallocBytes(void* ptr)\n\t{\n#if OGRE_MEMORY_TRACKER\n\t\tMemoryTracker::get()._recordDealloc(ptr);\n#endif\n\t\tnedalloc::nedfree(ptr);\n\t}\n\t\/\/---------------------------------------------------------------------\n\tvoid* NedAllocImpl::allocBytesAligned(size_t align, size_t count, \n\t\tconst char* file, int line, const char* func)\n\t{\n\t\t\/\/ default to platform SIMD alignment if none specified\n\t\tvoid* ptr = align ? nedalloc::nedmemalign(align, count)\n\t\t\t: nedalloc::nedmemalign(OGRE_SIMD_ALIGNMENT, count);\n#if OGRE_MEMORY_TRACKER\n\t\t\/\/ this alloc policy doesn't do pools (yet, ned can do it)\n\t\tMemoryTracker::get()._recordAlloc(ptr, count, 0, file, line, func);\n#else\n\t\t\/\/ avoid unused params warning\n\t\tfile;line;func;\n#endif\n\t\treturn ptr;\n\t}\n\t\/\/---------------------------------------------------------------------\n\tvoid NedAllocImpl::deallocBytesAligned(size_t align, void* ptr)\n\t{\n#if OGRE_MEMORY_TRACKER\n\t\t\/\/ this alloc policy doesn't do pools (yet, ned can do it)\n\t\tMemoryTracker::get()._recordDealloc(ptr);\n#endif\n\t\tnedalloc::nedfree(ptr);\n\t}\n\n\n}\n\n\n#endif\n\nNed deallocator should deal with null pointers\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2008 Torus Knot Software Ltd\nAlso see acknowledgements in Readme.html\n\nThis program is free software; you can redistribute it and\/or modify it under\nthe terms of the GNU Lesser General Public License as published by the Free Software\nFoundation; either version 2 of the License, or (at your option) any later\nversion.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License along with\nthis program; if not, write to the Free Software Foundation, Inc., 59 Temple\nPlace - Suite 330, Boston, MA 02111-1307, USA, or go to\nhttp:\/\/www.gnu.org\/copyleft\/lesser.txt.\n\nYou may alternatively use this source under the terms of a specific version of\nthe OGRE Unrestricted License provided you have obtained such a license from\nTorus Knot Software Ltd.\n-----------------------------------------------------------------------------\n*\/\n#include \"OgreStableHeaders.h\"\n#include \"OgrePrerequisites.h\"\n#include \"OgreMemoryNedAlloc.h\"\n#include \"OgrePlatformInformation.h\"\n#include \"OgreMemoryTracker.h\"\n\n#if OGRE_MEMORY_ALLOCATOR == OGRE_MEMORY_ALLOCATOR_NED\n\n\/\/ include ned implementation\n#include \n\nnamespace Ogre\n{\n\n\t\/\/---------------------------------------------------------------------\n\tvoid* NedAllocImpl::allocBytes(size_t count, \n\t\tconst char* file, int line, const char* func)\n\t{\n\t\tvoid* ptr = nedalloc::nedmalloc(count);\n\t#if OGRE_MEMORY_TRACKER\n\t\t\/\/ this alloc policy doesn't do pools (yet, ned can do it)\n\t\tMemoryTracker::get()._recordAlloc(ptr, count, 0, file, line, func);\n\t#else\n\t\t\/\/ avoid unused params warning\n\t\tfile;line;func;\n\t#endif\n\t\treturn ptr;\n\t}\n\t\/\/---------------------------------------------------------------------\n\tvoid NedAllocImpl::deallocBytes(void* ptr)\n\t{\n\t\t\/\/ deal with null\n\t\tif (!ptr)\n\t\t\treturn;\n#if OGRE_MEMORY_TRACKER\n\t\tMemoryTracker::get()._recordDealloc(ptr);\n#endif\n\t\tnedalloc::nedfree(ptr);\n\t}\n\t\/\/---------------------------------------------------------------------\n\tvoid* NedAllocImpl::allocBytesAligned(size_t align, size_t count, \n\t\tconst char* file, int line, const char* func)\n\t{\n\t\t\/\/ default to platform SIMD alignment if none specified\n\t\tvoid* ptr = align ? nedalloc::nedmemalign(align, count)\n\t\t\t: nedalloc::nedmemalign(OGRE_SIMD_ALIGNMENT, count);\n#if OGRE_MEMORY_TRACKER\n\t\t\/\/ this alloc policy doesn't do pools (yet, ned can do it)\n\t\tMemoryTracker::get()._recordAlloc(ptr, count, 0, file, line, func);\n#else\n\t\t\/\/ avoid unused params warning\n\t\tfile;line;func;\n#endif\n\t\treturn ptr;\n\t}\n\t\/\/---------------------------------------------------------------------\n\tvoid NedAllocImpl::deallocBytesAligned(size_t align, void* ptr)\n\t{\n\t\t\/\/ deal with null\n\t\tif (!ptr)\n\t\t\treturn;\n#if OGRE_MEMORY_TRACKER\n\t\t\/\/ this alloc policy doesn't do pools (yet, ned can do it)\n\t\tMemoryTracker::get()._recordDealloc(ptr);\n#endif\n\t\tnedalloc::nedfree(ptr);\n\t}\n\n\n}\n\n\n#endif\n\n<|endoftext|>"} {"text":"Adding the possibility to select the POI based on pdg (ALICE3 LoI)<|endoftext|>"} {"text":"#include \"transactionrecord.h\"\n#include \"wallet\/wallet.h\"\n#include \"base58.h\"\n\nstd::string GetTxProject(uint256 hash, int& out_blocknumber, int& out_blocktype, double& out_rac);\n\n\n\/* Return positive answer if transaction should be shown in list. *\/\nbool TransactionRecord::showTransaction(const CWalletTx &wtx, bool datetime_limit_flag, const int64_t &datetime_limit)\n{\n\n \/\/ Do not show transactions earlier than the datetime_limit if the flag is set.\n if (datetime_limit_flag && (int64_t) wtx.nTime < datetime_limit)\n {\n return false;\n }\n\n std::string ShowOrphans = GetArg(\"-showorphans\", \"false\");\n\n\t\/\/R Halford - POS Transactions - If Orphaned follow showorphans directive:\n\tif (wtx.IsCoinStake() && !wtx.IsInMainChain())\n\t{\n\t \/\/Orphaned tx\n\t\t return (ShowOrphans==\"true\" ? true : false);\n }\n\n if (wtx.IsCoinBase())\n {\n \/\/ Ensures we show generated coins \/ mined transactions at depth 1\n if (!wtx.IsInMainChain())\n {\n return false;\n }\n }\n\n \/\/ Suppress OP_RETURN transactions if they did not originate from you.\n \/\/ This is not \"very\" taxing but necessary since the transaction is in the wallet already.\n if (!wtx.IsFromMe())\n {\n for (auto const& txout : wtx.vout)\n {\n if (txout.scriptPubKey == (CScript() << OP_RETURN))\n return false;\n }\n }\n return true;\n}\n\n\/*\n * Decompose CWallet transaction to model transaction records.\n *\/\nQList TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx)\n{\n QList parts;\n int64_t nTime = wtx.GetTxTime();\n int64_t nCredit = wtx.GetCredit(true);\n int64_t nDebit = wtx.GetDebit();\n int64_t nNet = nCredit - nDebit;\n size_t wtx_size = wtx.vout.size();\n uint256 hash = wtx.GetHash();\n\n std::map mapValue = wtx.mapValue;\n\n bool fContractPresent = false;\n NN::ContractType ContractType;\n\n if (!wtx.GetContracts().empty())\n {\n const auto& contract = wtx.GetContracts().begin();\n fContractPresent = true;\n ContractType = contract->m_type.Value();\n }\n\n \/\/ This is legacy CoinBase for PoW, no longer used.\n if (wtx.IsCoinBase())\n {\n for (const auto& txout :wtx.vout)\n {\n if (wallet->IsMine(txout) != ISMINE_NO)\n {\n TransactionRecord sub(hash, nTime);\n CTxDestination address;\n sub.idx = parts.size(); \/\/ sequence number\n\n if (ExtractDestination(txout.scriptPubKey, address))\n {\n sub.address = CBitcoinAddress(address).ToString();\n }\n\n \/\/ Generated (proof-of-work)\n sub.type = TransactionRecord::Generated;\n sub.credit = txout.nValue;\n\n parts.append(sub);\n }\n }\n }\n \/\/ Since we are now separating out the sent sidestake info\n \/\/ into a separate subtransaction, we need to include the entire\n \/\/ value of the coinstake transaction here, rather than the previous\n \/\/ counting of only IsMine outputs.\n else if (wtx.IsCoinStake())\n {\n \/\/ We check the first coinstake output (zero is empty) for IsMine to\n \/\/ determine how to characterize the entire coinstake transaction. The\n \/\/ sidestakes to other (not mine) addresses are accounted for as negatives\n \/\/ in a separate subtransaction. The first output is ALWAYS guaranteed to be\n \/\/ the stake return to the original owner, and so matches the input.\n if (wallet->IsMine(wtx.vout[1]) != ISMINE_NO)\n {\n TransactionRecord sub(hash, nTime);\n CTxDestination address;\n sub.idx = parts.size();\n sub.vout = 1;\n\n sub.type = TransactionRecord::Generated;\n \/\/ The coinstake HAS to be from an address.\n if(ExtractDestination(wtx.vout[1].scriptPubKey, address))\n {\n sub.address = CBitcoinAddress(address).ToString();\n }\n\n \/\/ Here we add up all of the outputs, whether they are ours (the stake return with\n \/\/ apportioned reward, or not (sidestake), because the part that is not ours\n \/\/ will be accounted in the separated sidestake send transaction.\n sub.credit = 0;\n for (const auto& txout : wtx.vout)\n {\n sub.credit += txout.nValue;\n }\n\n sub.debit = -nDebit;\n\n \/\/ Append the subtransaction to the parts QList (transaction record).\n parts.append(sub);\n }\n\n \/\/ We only want outputs > 1 because the zeroth output is always empty,\n \/\/ and the first output is always the staker's. Output 2 onwards may or\n \/\/ may not be a sidestake, depending on whether stakesplitting is active,\n \/\/ or whether sidestaking is even turned on.\n \/\/ There is no coalescing here. A separate subtransaction is created for each\n \/\/ sidestake.\n for (unsigned int t = 2; t < wtx_size; t++)\n {\n \/\/ If this is not a stake split AND either vout[1] is mine OR\n \/\/ vout[t] is mine\n if (wtx.vout[t].scriptPubKey != wtx.vout[1].scriptPubKey &&\n (wallet->IsMine(wtx.vout[1]) != ISMINE_NO ||\n wallet->IsMine(wtx.vout[t]) != ISMINE_NO))\n {\n TransactionRecord sub(hash, nTime);\n CTxDestination address;\n sub.idx = parts.size(); \/\/ sequence number\n sub.vout = t;\n\n sub.type = TransactionRecord::Generated;\n\n if (ExtractDestination(wtx.vout[t].scriptPubKey, address))\n {\n sub.address = CBitcoinAddress(address).ToString();\n }\n\n int64_t nValue = wtx.vout[t].nValue;\n\n if (wallet->IsMine(wtx.vout[t]) != ISMINE_NO)\n {\n sub.credit = nValue;\n }\n else\n {\n sub.debit = -nValue;\n }\n\n parts.append(sub);\n }\n }\n }\n else if (nNet > 0)\n {\n for (const auto& txout : wtx.vout)\n {\n if (wallet->IsMine(txout) != ISMINE_NO)\n {\n TransactionRecord sub(hash, nTime);\n CTxDestination address;\n sub.idx = parts.size(); \/\/ sequence number\n\n if (ExtractDestination(txout.scriptPubKey, address))\n {\n \/\/ Received by Bitcoin Address\n sub.type = TransactionRecord::RecvWithAddress;\n sub.address = CBitcoinAddress(address).ToString();\n }\n else\n {\n \/\/ Received by IP connection (deprecated features), or a multisignature or other non-simple transaction\n sub.type = TransactionRecord::RecvFromOther;\n sub.address = mapValue[\"from\"];\n }\n\n sub.credit = txout.nValue;\n\n parts.append(sub);\n }\n }\n }\n else \/\/ Everything else\n {\n bool fAllFromMe = true;\n for (auto const& txin : wtx.vin)\n fAllFromMe = fAllFromMe && (wallet->IsMine(txin) != ISMINE_NO);\n\n bool fAllToMe = true;\n for (auto const& txout : wtx.vout)\n fAllToMe = fAllToMe && (wallet->IsMine(txout) != ISMINE_NO);\n\n if (fAllFromMe && fAllToMe)\n {\n \/\/ Payment to self\n int64_t nChange = wtx.GetChange();\n\n parts.append(TransactionRecord(hash, nTime, TransactionRecord::SendToSelf, \"\",\n -(nDebit - nChange), nCredit - nChange, 0));\n }\n else if (fAllFromMe)\n {\n \/\/\n \/\/ Debit\n \/\/\n int64_t nTxFee = nDebit - wtx.GetValueOut();\n\n \/\/ for tracking message type display\n bool fMessageDisplayed = false;\n\n for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++)\n {\n const CTxOut& txout = wtx.vout[nOut];\n TransactionRecord sub(hash, nTime);\n sub.idx = parts.size();\n\n if(wallet->IsMine(txout) != ISMINE_NO)\n {\n \/\/ Ignore parts sent to self, as this is usually the change\n \/\/ from a transaction sent back to our own address.\n continue;\n }\n\n CTxDestination address;\n if (ExtractDestination(txout.scriptPubKey, address))\n {\n \/\/ Sent to Bitcoin Address\n sub.type = TransactionRecord::SendToAddress;\n sub.address = CBitcoinAddress(address).ToString();\n }\n else\n {\n \/\/ Sent to IP, or other non-address transaction like OP_EVAL\n sub.type = TransactionRecord::SendToOther;\n sub.address = mapValue[\"to\"];\n }\n\n int64_t nValue = txout.nValue;\n \/* Add fee to first output *\/\n if (nTxFee > 0)\n {\n nValue += nTxFee;\n nTxFee = 0;\n }\n sub.debit = -nValue;\n\n \/\/ Determine if the transaction is a beacon advertisement or a vote.\n \/\/ For right now, there should only be one contract in a transaction.\n \/\/ We will simply select the first and only one. Note that we are\n \/\/ looping through the outputs one by one in the for loop above this,\n \/\/ So if we get here, we are not a coinbase or coinstake, and we are on\n \/\/ an ouput that isn't ours. The worst that can happen from this\n \/\/ simple approach is to label more than one output with the\n \/\/ first found contract type. For right now, this is sufficient, because\n \/\/ the contracts that are sent right now only contain two outputs,\n \/\/ the burn and the change. We will have to get more sophisticated\n \/\/ when we allow more than one contract per transaction.\n\n \/\/ Notice this doesn't mess with the value or debit, it simply\n \/\/ overrides the TransactionRecord enum type.\n if (fContractPresent)\n {\n switch (ContractType)\n {\n case NN::ContractType::BEACON:\n sub.type = TransactionRecord::BeaconAdvertisement;\n break;\n case NN::ContractType::POLL:\n sub.type = TransactionRecord::Poll;\n break;\n case NN::ContractType::VOTE:\n sub.type = TransactionRecord::Vote;\n break;\n case NN::ContractType::MESSAGE:\n \/\/ Only display the message type for the first not is mine output\n if (!fMessageDisplayed && wallet->IsMine(txout) == ISMINE_NO)\n {\n sub.type = TransactionRecord::Message;\n fMessageDisplayed = true;\n }\n \/\/ Do not display the op return output for a send message contract separately.\n else if (txout.scriptPubKey[0] == OP_RETURN)\n {\n continue;\n }\n break;\n default:\n break; \/\/ Suppress warning\n }\n }\n\n parts.append(sub);\n }\n }\n else\n {\n \/\/\n \/\/ Mixed debit transaction, can't break down payees\n \/\/\n parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, \"\", nNet, 0, 0));\n }\n }\n\n return parts;\n}\n\nvoid TransactionRecord::updateStatus(const CWalletTx &wtx)\n{\n AssertLockHeld(cs_main);\n \/\/ Determine transaction status\n\n \/\/ Find the block the tx is in\n CBlockIndex* pindex = NULL;\n BlockMap::iterator mi = mapBlockIndex.find(wtx.hashBlock);\n if (mi != mapBlockIndex.end())\n pindex = (*mi).second;\n\n \/\/ Sort order, unrecorded transactions sort to the top\n status.sortKey = strprintf(\"%010d-%01d-%010u-%03d\",\n (pindex ? pindex->nHeight : std::numeric_limits::max()),\n (wtx.IsCoinBase() ? 1 : 0),\n wtx.nTimeReceived,\n idx);\n status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0);\n status.depth = wtx.GetDepthInMainChain();\n status.cur_num_blocks = nBestHeight;\n\n if (!IsFinalTx(wtx, nBestHeight + 1))\n {\n if (wtx.nLockTime < LOCKTIME_THRESHOLD)\n {\n status.status = TransactionStatus::OpenUntilBlock;\n status.open_for = wtx.nLockTime - nBestHeight;\n }\n else\n {\n status.status = TransactionStatus::OpenUntilDate;\n status.open_for = wtx.nLockTime;\n }\n }\n\n \/\/ For generated transactions, determine maturity\n else if(type == TransactionRecord::Generated)\n {\n if (wtx.GetBlocksToMaturity() > 0)\n {\n status.status = TransactionStatus::Immature;\n\n if (wtx.IsInMainChain())\n {\n status.matures_in = wtx.GetBlocksToMaturity();\n\n \/\/ Check if the block was requested by anyone\n if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)\n status.status = TransactionStatus::MaturesWarning;\n }\n else\n {\n status.status = TransactionStatus::NotAccepted;\n }\n }\n else\n {\n status.status = TransactionStatus::Confirmed;\n }\n }\n else\n {\n if (status.depth < 0)\n {\n status.status = TransactionStatus::Conflicted;\n }\n else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)\n {\n status.status = TransactionStatus::Offline;\n }\n else if (status.depth == 0)\n {\n status.status = TransactionStatus::Unconfirmed;\n }\n else if (status.depth < RecommendedNumConfirmations)\n {\n status.status = TransactionStatus::Confirming;\n }\n else\n {\n status.status = TransactionStatus::Confirmed;\n }\n }\n}\n\nbool TransactionRecord::statusUpdateNeeded()\n{\n AssertLockHeld(cs_main);\n return status.cur_num_blocks != nBestHeight;\n}\n\nstd::string TransactionRecord::getTxID()\n{\n return hash.ToString();\n}\n\n\nAdjust OP_RETURN filter to only filter version 1 transactions#include \"transactionrecord.h\"\n#include \"wallet\/wallet.h\"\n#include \"base58.h\"\n\nstd::string GetTxProject(uint256 hash, int& out_blocknumber, int& out_blocktype, double& out_rac);\n\n\n\/* Return positive answer if transaction should be shown in list. *\/\nbool TransactionRecord::showTransaction(const CWalletTx &wtx, bool datetime_limit_flag, const int64_t &datetime_limit)\n{\n\n \/\/ Do not show transactions earlier than the datetime_limit if the flag is set.\n if (datetime_limit_flag && (int64_t) wtx.nTime < datetime_limit)\n {\n return false;\n }\n\n std::string ShowOrphans = GetArg(\"-showorphans\", \"false\");\n\n\t\/\/R Halford - POS Transactions - If Orphaned follow showorphans directive:\n\tif (wtx.IsCoinStake() && !wtx.IsInMainChain())\n\t{\n\t \/\/Orphaned tx\n\t\t return (ShowOrphans==\"true\" ? true : false);\n }\n\n if (wtx.IsCoinBase())\n {\n \/\/ Ensures we show generated coins \/ mined transactions at depth 1\n if (!wtx.IsInMainChain())\n {\n return false;\n }\n }\n\n \/\/ Suppress OP_RETURN transactions if they did not originate from you.\n \/\/ This is not \"very\" taxing but necessary since the transaction is in the wallet already.\n \/\/ We only do this for version 1 transactions, because this legacy error does not occur\n \/\/ anymore, and we can't filter entire transactions that have OP_RETURNs, since\n \/\/ some outputs are relevent with the new contract types, such as messages.\n if (wtx.nVersion == 1 && !wtx.IsFromMe())\n {\n for (auto const& txout : wtx.vout)\n {\n if (txout.scriptPubKey == (CScript() << OP_RETURN))\n return false;\n }\n }\n return true;\n}\n\n\/*\n * Decompose CWallet transaction to model transaction records.\n *\/\nQList TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx)\n{\n QList parts;\n int64_t nTime = wtx.GetTxTime();\n int64_t nCredit = wtx.GetCredit(true);\n int64_t nDebit = wtx.GetDebit();\n int64_t nNet = nCredit - nDebit;\n size_t wtx_size = wtx.vout.size();\n uint256 hash = wtx.GetHash();\n\n std::map mapValue = wtx.mapValue;\n\n bool fContractPresent = false;\n NN::ContractType ContractType;\n\n if (!wtx.GetContracts().empty())\n {\n const auto& contract = wtx.GetContracts().begin();\n fContractPresent = true;\n ContractType = contract->m_type.Value();\n }\n\n \/\/ This is legacy CoinBase for PoW, no longer used.\n if (wtx.IsCoinBase())\n {\n for (const auto& txout :wtx.vout)\n {\n if (wallet->IsMine(txout) != ISMINE_NO)\n {\n TransactionRecord sub(hash, nTime);\n CTxDestination address;\n sub.idx = parts.size(); \/\/ sequence number\n\n if (ExtractDestination(txout.scriptPubKey, address))\n {\n sub.address = CBitcoinAddress(address).ToString();\n }\n\n \/\/ Generated (proof-of-work)\n sub.type = TransactionRecord::Generated;\n sub.credit = txout.nValue;\n\n parts.append(sub);\n }\n }\n }\n \/\/ Since we are now separating out the sent sidestake info\n \/\/ into a separate subtransaction, we need to include the entire\n \/\/ value of the coinstake transaction here, rather than the previous\n \/\/ counting of only IsMine outputs.\n else if (wtx.IsCoinStake())\n {\n \/\/ We check the first coinstake output (zero is empty) for IsMine to\n \/\/ determine how to characterize the entire coinstake transaction. The\n \/\/ sidestakes to other (not mine) addresses are accounted for as negatives\n \/\/ in a separate subtransaction. The first output is ALWAYS guaranteed to be\n \/\/ the stake return to the original owner, and so matches the input.\n if (wallet->IsMine(wtx.vout[1]) != ISMINE_NO)\n {\n TransactionRecord sub(hash, nTime);\n CTxDestination address;\n sub.idx = parts.size();\n sub.vout = 1;\n\n sub.type = TransactionRecord::Generated;\n \/\/ The coinstake HAS to be from an address.\n if(ExtractDestination(wtx.vout[1].scriptPubKey, address))\n {\n sub.address = CBitcoinAddress(address).ToString();\n }\n\n \/\/ Here we add up all of the outputs, whether they are ours (the stake return with\n \/\/ apportioned reward, or not (sidestake), because the part that is not ours\n \/\/ will be accounted in the separated sidestake send transaction.\n sub.credit = 0;\n for (const auto& txout : wtx.vout)\n {\n sub.credit += txout.nValue;\n }\n\n sub.debit = -nDebit;\n\n \/\/ Append the subtransaction to the parts QList (transaction record).\n parts.append(sub);\n }\n\n \/\/ We only want outputs > 1 because the zeroth output is always empty,\n \/\/ and the first output is always the staker's. Output 2 onwards may or\n \/\/ may not be a sidestake, depending on whether stakesplitting is active,\n \/\/ or whether sidestaking is even turned on.\n \/\/ There is no coalescing here. A separate subtransaction is created for each\n \/\/ sidestake.\n for (unsigned int t = 2; t < wtx_size; t++)\n {\n \/\/ If this is not a stake split AND either vout[1] is mine OR\n \/\/ vout[t] is mine\n if (wtx.vout[t].scriptPubKey != wtx.vout[1].scriptPubKey &&\n (wallet->IsMine(wtx.vout[1]) != ISMINE_NO ||\n wallet->IsMine(wtx.vout[t]) != ISMINE_NO))\n {\n TransactionRecord sub(hash, nTime);\n CTxDestination address;\n sub.idx = parts.size(); \/\/ sequence number\n sub.vout = t;\n\n sub.type = TransactionRecord::Generated;\n\n if (ExtractDestination(wtx.vout[t].scriptPubKey, address))\n {\n sub.address = CBitcoinAddress(address).ToString();\n }\n\n int64_t nValue = wtx.vout[t].nValue;\n\n if (wallet->IsMine(wtx.vout[t]) != ISMINE_NO)\n {\n sub.credit = nValue;\n }\n else\n {\n sub.debit = -nValue;\n }\n\n parts.append(sub);\n }\n }\n }\n else if (nNet > 0)\n {\n for (const auto& txout : wtx.vout)\n {\n if (wallet->IsMine(txout) != ISMINE_NO)\n {\n TransactionRecord sub(hash, nTime);\n CTxDestination address;\n sub.idx = parts.size(); \/\/ sequence number\n\n if (ExtractDestination(txout.scriptPubKey, address))\n {\n \/\/ Received by Bitcoin Address\n sub.type = TransactionRecord::RecvWithAddress;\n sub.address = CBitcoinAddress(address).ToString();\n }\n else\n {\n \/\/ Received by IP connection (deprecated features), or a multisignature or other non-simple transaction\n sub.type = TransactionRecord::RecvFromOther;\n sub.address = mapValue[\"from\"];\n }\n\n if (fContractPresent && ContractType == NN::ContractType::MESSAGE)\n {\n sub.type = TransactionRecord::Message;\n }\n\n sub.credit = txout.nValue;\n\n parts.append(sub);\n }\n }\n }\n else \/\/ Everything else\n {\n bool fAllFromMe = true;\n for (auto const& txin : wtx.vin)\n fAllFromMe = fAllFromMe && (wallet->IsMine(txin) != ISMINE_NO);\n\n bool fAllToMe = true;\n for (auto const& txout : wtx.vout)\n fAllToMe = fAllToMe && (wallet->IsMine(txout) != ISMINE_NO);\n\n if (fAllFromMe && fAllToMe)\n {\n \/\/ Payment to self\n int64_t nChange = wtx.GetChange();\n\n parts.append(TransactionRecord(hash, nTime, TransactionRecord::SendToSelf, \"\",\n -(nDebit - nChange), nCredit - nChange, 0));\n }\n else if (fAllFromMe)\n {\n \/\/\n \/\/ Debit\n \/\/\n int64_t nTxFee = nDebit - wtx.GetValueOut();\n\n \/\/ for tracking message type display\n bool fMessageDisplayed = false;\n\n for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++)\n {\n const CTxOut& txout = wtx.vout[nOut];\n TransactionRecord sub(hash, nTime);\n sub.idx = parts.size();\n\n if(wallet->IsMine(txout) != ISMINE_NO)\n {\n \/\/ Ignore parts sent to self, as this is usually the change\n \/\/ from a transaction sent back to our own address.\n continue;\n }\n\n CTxDestination address;\n if (ExtractDestination(txout.scriptPubKey, address))\n {\n \/\/ Sent to Bitcoin Address\n sub.type = TransactionRecord::SendToAddress;\n sub.address = CBitcoinAddress(address).ToString();\n }\n else\n {\n \/\/ Sent to IP, or other non-address transaction like OP_EVAL\n sub.type = TransactionRecord::SendToOther;\n sub.address = mapValue[\"to\"];\n }\n\n int64_t nValue = txout.nValue;\n \/* Add fee to first output *\/\n if (nTxFee > 0)\n {\n nValue += nTxFee;\n nTxFee = 0;\n }\n sub.debit = -nValue;\n\n \/\/ Determine if the transaction is a beacon advertisement or a vote.\n \/\/ For right now, there should only be one contract in a transaction.\n \/\/ We will simply select the first and only one. Note that we are\n \/\/ looping through the outputs one by one in the for loop above this,\n \/\/ So if we get here, we are not a coinbase or coinstake, and we are on\n \/\/ an ouput that isn't ours. The worst that can happen from this\n \/\/ simple approach is to label more than one output with the\n \/\/ first found contract type. For right now, this is sufficient, because\n \/\/ the contracts that are sent right now only contain two outputs,\n \/\/ the burn and the change. We will have to get more sophisticated\n \/\/ when we allow more than one contract per transaction.\n\n \/\/ Notice this doesn't mess with the value or debit, it simply\n \/\/ overrides the TransactionRecord enum type.\n if (fContractPresent)\n {\n switch (ContractType)\n {\n case NN::ContractType::BEACON:\n sub.type = TransactionRecord::BeaconAdvertisement;\n break;\n case NN::ContractType::POLL:\n sub.type = TransactionRecord::Poll;\n break;\n case NN::ContractType::VOTE:\n sub.type = TransactionRecord::Vote;\n break;\n case NN::ContractType::MESSAGE:\n \/\/ Only display the message type for the first not is mine output\n if (!fMessageDisplayed && wallet->IsMine(txout) == ISMINE_NO)\n {\n sub.type = TransactionRecord::Message;\n fMessageDisplayed = true;\n }\n \/\/ Do not display the op return output for a send message contract separately.\n else if (txout.scriptPubKey[0] == OP_RETURN)\n {\n continue;\n }\n break;\n default:\n break; \/\/ Suppress warning\n }\n }\n\n parts.append(sub);\n }\n }\n else\n {\n \/\/\n \/\/ Mixed debit transaction, can't break down payees\n \/\/\n parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, \"\", nNet, 0, 0));\n }\n }\n\n return parts;\n}\n\nvoid TransactionRecord::updateStatus(const CWalletTx &wtx)\n{\n AssertLockHeld(cs_main);\n \/\/ Determine transaction status\n\n \/\/ Find the block the tx is in\n CBlockIndex* pindex = NULL;\n BlockMap::iterator mi = mapBlockIndex.find(wtx.hashBlock);\n if (mi != mapBlockIndex.end())\n pindex = (*mi).second;\n\n \/\/ Sort order, unrecorded transactions sort to the top\n status.sortKey = strprintf(\"%010d-%01d-%010u-%03d\",\n (pindex ? pindex->nHeight : std::numeric_limits::max()),\n (wtx.IsCoinBase() ? 1 : 0),\n wtx.nTimeReceived,\n idx);\n status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0);\n status.depth = wtx.GetDepthInMainChain();\n status.cur_num_blocks = nBestHeight;\n\n if (!IsFinalTx(wtx, nBestHeight + 1))\n {\n if (wtx.nLockTime < LOCKTIME_THRESHOLD)\n {\n status.status = TransactionStatus::OpenUntilBlock;\n status.open_for = wtx.nLockTime - nBestHeight;\n }\n else\n {\n status.status = TransactionStatus::OpenUntilDate;\n status.open_for = wtx.nLockTime;\n }\n }\n\n \/\/ For generated transactions, determine maturity\n else if(type == TransactionRecord::Generated)\n {\n if (wtx.GetBlocksToMaturity() > 0)\n {\n status.status = TransactionStatus::Immature;\n\n if (wtx.IsInMainChain())\n {\n status.matures_in = wtx.GetBlocksToMaturity();\n\n \/\/ Check if the block was requested by anyone\n if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)\n status.status = TransactionStatus::MaturesWarning;\n }\n else\n {\n status.status = TransactionStatus::NotAccepted;\n }\n }\n else\n {\n status.status = TransactionStatus::Confirmed;\n }\n }\n else\n {\n if (status.depth < 0)\n {\n status.status = TransactionStatus::Conflicted;\n }\n else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)\n {\n status.status = TransactionStatus::Offline;\n }\n else if (status.depth == 0)\n {\n status.status = TransactionStatus::Unconfirmed;\n }\n else if (status.depth < RecommendedNumConfirmations)\n {\n status.status = TransactionStatus::Confirming;\n }\n else\n {\n status.status = TransactionStatus::Confirmed;\n }\n }\n}\n\nbool TransactionRecord::statusUpdateNeeded()\n{\n AssertLockHeld(cs_main);\n return status.cur_num_blocks != nBestHeight;\n}\n\nstd::string TransactionRecord::getTxID()\n{\n return hash.ToString();\n}\n\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/task_manager.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"base\/file_path.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/extensions\/crashed_extension_infobar.h\"\n#include \"chrome\/browser\/extensions\/extension_browsertest.h\"\n#include \"chrome\/browser\/tab_contents\/infobar_delegate.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/page_transition_types.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"grit\/generated_resources.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\nconst FilePath::CharType* kTitle1File = FILE_PATH_LITERAL(\"title1.html\");\n\nclass ResourceChangeObserver : public TaskManagerModelObserver {\n public:\n ResourceChangeObserver(const TaskManagerModel* model,\n int target_resource_count)\n : model_(model),\n target_resource_count_(target_resource_count) {\n }\n\n virtual void OnModelChanged() {\n OnResourceChange();\n }\n\n virtual void OnItemsChanged(int start, int length) {\n OnResourceChange();\n }\n\n virtual void OnItemsAdded(int start, int length) {\n OnResourceChange();\n }\n\n virtual void OnItemsRemoved(int start, int length) {\n OnResourceChange();\n }\n\n private:\n void OnResourceChange() {\n if (model_->ResourceCount() == target_resource_count_)\n MessageLoopForUI::current()->Quit();\n }\n\n const TaskManagerModel* model_;\n const int target_resource_count_;\n};\n\n} \/\/ namespace\n\nclass TaskManagerBrowserTest : public ExtensionBrowserTest {\n public:\n TaskManagerModel* model() const {\n return TaskManager::GetInstance()->model();\n }\n\n void WaitForResourceChange(int target_count) {\n if (model()->ResourceCount() == target_count)\n return;\n ResourceChangeObserver observer(model(), target_count);\n model()->AddObserver(&observer);\n ui_test_utils::RunMessageLoop();\n model()->RemoveObserver(&observer);\n }\n};\n\n\/\/ Regression test for http:\/\/crbug.com\/13361\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, ShutdownWhileOpen) {\n browser()->window()->ShowTaskManager();\n}\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeTabContentsChanges) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Open a new tab and make sure we notice that.\n GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),\n FilePath(kTitle1File)));\n browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,\n true, 0, false, NULL);\n WaitForResourceChange(3);\n\n \/\/ Close the tab and verify that we notice.\n TabContents* first_tab = browser()->GetTabContentsAt(0);\n ASSERT_TRUE(first_tab);\n browser()->CloseTabContents(first_tab);\n WaitForResourceChange(2);\n}\n\n#if defined(OS_WIN)\n\/\/ http:\/\/crbug.com\/31663\n#define NoticeExtensionChanges DISABLED_NoticeExtensionChanges\n#endif\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeExtensionChanges) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Loading an extension should result in a new resource being\n \/\/ created for it.\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"one_in_shelf\")));\n WaitForResourceChange(3);\n\n \/\/ Make sure we also recognize extensions with just background pages.\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n WaitForResourceChange(4);\n}\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtension) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n \/\/ Kill the extension process and make sure we notice it.\n TaskManager::GetInstance()->KillProcess(2);\n WaitForResourceChange(2);\n}\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtensionAndReload) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n \/\/ Kill the extension process and make sure we notice it.\n TaskManager::GetInstance()->KillProcess(2);\n WaitForResourceChange(2);\n\n \/\/ Reload the extension using the \"crashed extension\" infobar while the task\n \/\/ manager is still visible. Make sure we don't crash and the extension\n \/\/ gets reloaded and noticed in the task manager.\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_EQ(1, current_tab->infobar_delegate_count());\n InfoBarDelegate* delegate = current_tab->GetInfoBarDelegateAt(0);\n CrashedExtensionInfoBarDelegate* crashed_delegate =\n delegate->AsCrashedExtensionInfoBarDelegate();\n ASSERT_TRUE(crashed_delegate);\n crashed_delegate->Accept();\n WaitForResourceChange(3);\n}\n\n\/\/ Regression test for http:\/\/crbug.com\/18693.\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, ReloadExtension) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n const Extension* extension = model()->GetResourceExtension(2);\n\n \/\/ Reload the extension a few times and make sure our resource count\n \/\/ doesn't increase.\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n extension = model()->GetResourceExtension(2);\n\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n extension = model()->GetResourceExtension(2);\n\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n}\n\n\/\/ Crashy, http:\/\/crbug.com\/42301.\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest,\n DISABLED_PopulateWebCacheFields) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Open a new tab and make sure we notice that.\n GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),\n FilePath(kTitle1File)));\n browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,\n true, 0, false, NULL);\n WaitForResourceChange(3);\n\n \/\/ Check that we get some value for the cache columns.\n DCHECK_NE(model()->GetResourceWebCoreImageCacheSize(2),\n l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));\n DCHECK_NE(model()->GetResourceWebCoreScriptsCacheSize(2),\n l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));\n DCHECK_NE(model()->GetResourceWebCoreCSSCacheSize(2),\n l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));\n}\nDisable crashy TaskManagerBrowserTest.ReloadExtension on Windows.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/task_manager.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"base\/file_path.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/extensions\/crashed_extension_infobar.h\"\n#include \"chrome\/browser\/extensions\/extension_browsertest.h\"\n#include \"chrome\/browser\/tab_contents\/infobar_delegate.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/page_transition_types.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"grit\/generated_resources.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\nconst FilePath::CharType* kTitle1File = FILE_PATH_LITERAL(\"title1.html\");\n\nclass ResourceChangeObserver : public TaskManagerModelObserver {\n public:\n ResourceChangeObserver(const TaskManagerModel* model,\n int target_resource_count)\n : model_(model),\n target_resource_count_(target_resource_count) {\n }\n\n virtual void OnModelChanged() {\n OnResourceChange();\n }\n\n virtual void OnItemsChanged(int start, int length) {\n OnResourceChange();\n }\n\n virtual void OnItemsAdded(int start, int length) {\n OnResourceChange();\n }\n\n virtual void OnItemsRemoved(int start, int length) {\n OnResourceChange();\n }\n\n private:\n void OnResourceChange() {\n if (model_->ResourceCount() == target_resource_count_)\n MessageLoopForUI::current()->Quit();\n }\n\n const TaskManagerModel* model_;\n const int target_resource_count_;\n};\n\n} \/\/ namespace\n\nclass TaskManagerBrowserTest : public ExtensionBrowserTest {\n public:\n TaskManagerModel* model() const {\n return TaskManager::GetInstance()->model();\n }\n\n void WaitForResourceChange(int target_count) {\n if (model()->ResourceCount() == target_count)\n return;\n ResourceChangeObserver observer(model(), target_count);\n model()->AddObserver(&observer);\n ui_test_utils::RunMessageLoop();\n model()->RemoveObserver(&observer);\n }\n};\n\n\/\/ Regression test for http:\/\/crbug.com\/13361\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, ShutdownWhileOpen) {\n browser()->window()->ShowTaskManager();\n}\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeTabContentsChanges) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Open a new tab and make sure we notice that.\n GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),\n FilePath(kTitle1File)));\n browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,\n true, 0, false, NULL);\n WaitForResourceChange(3);\n\n \/\/ Close the tab and verify that we notice.\n TabContents* first_tab = browser()->GetTabContentsAt(0);\n ASSERT_TRUE(first_tab);\n browser()->CloseTabContents(first_tab);\n WaitForResourceChange(2);\n}\n\n#if defined(OS_WIN)\n\/\/ http:\/\/crbug.com\/31663\n#define NoticeExtensionChanges DISABLED_NoticeExtensionChanges\n#endif\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeExtensionChanges) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Loading an extension should result in a new resource being\n \/\/ created for it.\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"one_in_shelf\")));\n WaitForResourceChange(3);\n\n \/\/ Make sure we also recognize extensions with just background pages.\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n WaitForResourceChange(4);\n}\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtension) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n \/\/ Kill the extension process and make sure we notice it.\n TaskManager::GetInstance()->KillProcess(2);\n WaitForResourceChange(2);\n}\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtensionAndReload) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n \/\/ Kill the extension process and make sure we notice it.\n TaskManager::GetInstance()->KillProcess(2);\n WaitForResourceChange(2);\n\n \/\/ Reload the extension using the \"crashed extension\" infobar while the task\n \/\/ manager is still visible. Make sure we don't crash and the extension\n \/\/ gets reloaded and noticed in the task manager.\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_EQ(1, current_tab->infobar_delegate_count());\n InfoBarDelegate* delegate = current_tab->GetInfoBarDelegateAt(0);\n CrashedExtensionInfoBarDelegate* crashed_delegate =\n delegate->AsCrashedExtensionInfoBarDelegate();\n ASSERT_TRUE(crashed_delegate);\n crashed_delegate->Accept();\n WaitForResourceChange(3);\n}\n\n\/\/ Regression test for http:\/\/crbug.com\/18693.\n#if defined(OS_WIN)\n\/\/ Crashy, http:\/\/crbug.com\/42315.\n#define MAYBE_ReloadExtension DISABLED_ReloadExtension\n#else\n#define MAYBE_ReloadExtension ReloadExtension\n#endif\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, MAYBE_ReloadExtension) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n const Extension* extension = model()->GetResourceExtension(2);\n\n \/\/ Reload the extension a few times and make sure our resource count\n \/\/ doesn't increase.\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n extension = model()->GetResourceExtension(2);\n\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n extension = model()->GetResourceExtension(2);\n\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n}\n\n\/\/ Crashy, http:\/\/crbug.com\/42301.\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest,\n DISABLED_PopulateWebCacheFields) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Open a new tab and make sure we notice that.\n GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),\n FilePath(kTitle1File)));\n browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,\n true, 0, false, NULL);\n WaitForResourceChange(3);\n\n \/\/ Check that we get some value for the cache columns.\n DCHECK_NE(model()->GetResourceWebCoreImageCacheSize(2),\n l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));\n DCHECK_NE(model()->GetResourceWebCoreScriptsCacheSize(2),\n l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));\n DCHECK_NE(model()->GetResourceWebCoreCSSCacheSize(2),\n l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/test_suite.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n\nint main(int argc, char** argv) {\n TestSuite test_suite(argc, argv);\n\n \/\/ Register Chrome Path provider so that we can get test data dir.\n chrome::RegisterPathProvider();\n\n return test_suite.Run();\n}\nFix include.\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/test\/test_suite.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n\nint main(int argc, char** argv) {\n TestSuite test_suite(argc, argv);\n\n \/\/ Register Chrome Path provider so that we can get test data dir.\n chrome::RegisterPathProvider();\n\n return test_suite.Run();\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_util.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/path_service.h\"\n#include \"base\/test\/trace_event_analyzer.h\"\n#include \"base\/version.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/tracing.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/browser\/gpu\/gpu_blacklist.h\"\n#include \"content\/browser\/gpu\/gpu_data_manager.h\"\n#include \"net\/base\/net_util.h\"\n\nnamespace {\n\nclass GpuFeatureTest : public InProcessBrowserTest {\n public:\n GpuFeatureTest() {}\n\n virtual void SetUpCommandLine(CommandLine* command_line) {\n \/\/ This enables DOM automation for tab contents.\n EnableDOMAutomation();\n }\n\n void SetupBlacklist(const std::string& json_blacklist) {\n scoped_ptr os_version(Version::GetVersionFromString(\"1.0\"));\n GpuBlacklist* blacklist = new GpuBlacklist(\"1.0 unknown\");\n\n ASSERT_TRUE(blacklist->LoadGpuBlacklist(\n json_blacklist, GpuBlacklist::kAllOs));\n GpuDataManager::GetInstance()->SetBuiltInGpuBlacklist(blacklist);\n }\n\n void RunTest(const FilePath& url, bool expect_gpu_process) {\n using namespace trace_analyzer;\n\n FilePath test_path;\n PathService::Get(chrome::DIR_TEST_DATA, &test_path);\n test_path = test_path.Append(FILE_PATH_LITERAL(\"gpu\"));\n test_path = test_path.Append(url);\n\n ASSERT_TRUE(file_util::PathExists(test_path))\n << \"Missing test file: \" << test_path.value();\n\n ASSERT_TRUE(tracing::BeginTracing(\"test_gpu\"));\n\n ui_test_utils::DOMMessageQueue message_queue;\n \/\/ Have to use a new tab for the blacklist to work.\n ui_test_utils::NavigateToURLWithDisposition(\n browser(), net::FilePathToFileURL(test_path), NEW_FOREGROUND_TAB,\n ui_test_utils::BROWSER_TEST_NONE);\n \/\/ Wait for message indicating the test has finished running.\n ASSERT_TRUE(message_queue.WaitForMessage(NULL));\n\n std::string json_events;\n ASSERT_TRUE(tracing::EndTracing(&json_events));\n\n scoped_ptr analyzer(TraceAnalyzer::Create(json_events));\n EXPECT_EQ(expect_gpu_process, analyzer->FindOneEvent(\n Query(EVENT_NAME) == Query::String(\"GpuProcessLaunched\")) != NULL);\n }\n};\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, AcceleratedCompositingAllowed) {\n GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();\n EXPECT_EQ(flags.flags(), 0u);\n\n const bool expect_gpu_process = true;\n const FilePath url(FILE_PATH_LITERAL(\"feature_compositing.html\"));\n RunTest(url, expect_gpu_process);\n}\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, AcceleratedCompositingBlocked) {\n const std::string json_blacklist =\n \"{\\n\"\n \" \\\"name\\\": \\\"gpu blacklist\\\",\\n\"\n \" \\\"version\\\": \\\"1.0\\\",\\n\"\n \" \\\"entries\\\": [\\n\"\n \" {\\n\"\n \" \\\"id\\\": 1,\\n\"\n \" \\\"blacklist\\\": [\\n\"\n \" \\\"accelerated_compositing\\\"\\n\"\n \" ]\\n\"\n \" }\\n\"\n \" ]\\n\"\n \"}\";\n SetupBlacklist(json_blacklist);\n GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();\n EXPECT_EQ(\n flags.flags(),\n static_cast(GpuFeatureFlags::kGpuFeatureAcceleratedCompositing));\n\n const bool expect_gpu_process = false;\n const FilePath url(FILE_PATH_LITERAL(\"feature_compositing.html\"));\n RunTest(url, expect_gpu_process);\n}\n\n#if defined(OS_LINUX)\n\/\/ http:\/\/crbug.com\/104142\n#define WebGLAllowed FLAKY_WebGLAllowed\n#endif\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, WebGLAllowed) {\n GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();\n EXPECT_EQ(flags.flags(), 0u);\n\n const bool expect_gpu_process = true;\n const FilePath url(FILE_PATH_LITERAL(\"feature_webgl.html\"));\n RunTest(url, expect_gpu_process);\n}\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, WebGLBlocked) {\n const std::string json_blacklist =\n \"{\\n\"\n \" \\\"name\\\": \\\"gpu blacklist\\\",\\n\"\n \" \\\"version\\\": \\\"1.0\\\",\\n\"\n \" \\\"entries\\\": [\\n\"\n \" {\\n\"\n \" \\\"id\\\": 1,\\n\"\n \" \\\"blacklist\\\": [\\n\"\n \" \\\"webgl\\\"\\n\"\n \" ]\\n\"\n \" }\\n\"\n \" ]\\n\"\n \"}\";\n SetupBlacklist(json_blacklist);\n GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();\n EXPECT_EQ(\n flags.flags(),\n static_cast(GpuFeatureFlags::kGpuFeatureWebgl));\n\n const bool expect_gpu_process = false;\n const FilePath url(FILE_PATH_LITERAL(\"feature_webgl.html\"));\n RunTest(url, expect_gpu_process);\n}\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, Canvas2DAllowed) {\n GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();\n EXPECT_EQ(flags.flags(), 0u);\n\n#if defined(OS_MACOSX)\n \/\/ TODO(zmo): enabling Mac when skia backend is enabled.\n const bool expect_gpu_process = false;\n#else\n const bool expect_gpu_process = true;\n#endif\n const FilePath url(FILE_PATH_LITERAL(\"feature_canvas2d.html\"));\n RunTest(url, expect_gpu_process);\n}\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, Canvas2DBlocked) {\n const std::string json_blacklist =\n \"{\\n\"\n \" \\\"name\\\": \\\"gpu blacklist\\\",\\n\"\n \" \\\"version\\\": \\\"1.0\\\",\\n\"\n \" \\\"entries\\\": [\\n\"\n \" {\\n\"\n \" \\\"id\\\": 1,\\n\"\n \" \\\"blacklist\\\": [\\n\"\n \" \\\"accelerated_2d_canvas\\\"\\n\"\n \" ]\\n\"\n \" }\\n\"\n \" ]\\n\"\n \"}\";\n SetupBlacklist(json_blacklist);\n GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();\n EXPECT_EQ(\n flags.flags(),\n static_cast(GpuFeatureFlags::kGpuFeatureAccelerated2dCanvas));\n\n const bool expect_gpu_process = false;\n const FilePath url(FILE_PATH_LITERAL(\"feature_canvas2d.html\"));\n RunTest(url, expect_gpu_process);\n}\n\n} \/\/ namespace anonymous\n\nMarking GpuFeatureTest.Canvas2DAllowed flaky on Linux.\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_util.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/path_service.h\"\n#include \"base\/test\/trace_event_analyzer.h\"\n#include \"base\/version.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/tracing.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/browser\/gpu\/gpu_blacklist.h\"\n#include \"content\/browser\/gpu\/gpu_data_manager.h\"\n#include \"net\/base\/net_util.h\"\n\nnamespace {\n\nclass GpuFeatureTest : public InProcessBrowserTest {\n public:\n GpuFeatureTest() {}\n\n virtual void SetUpCommandLine(CommandLine* command_line) {\n \/\/ This enables DOM automation for tab contents.\n EnableDOMAutomation();\n }\n\n void SetupBlacklist(const std::string& json_blacklist) {\n scoped_ptr os_version(Version::GetVersionFromString(\"1.0\"));\n GpuBlacklist* blacklist = new GpuBlacklist(\"1.0 unknown\");\n\n ASSERT_TRUE(blacklist->LoadGpuBlacklist(\n json_blacklist, GpuBlacklist::kAllOs));\n GpuDataManager::GetInstance()->SetBuiltInGpuBlacklist(blacklist);\n }\n\n void RunTest(const FilePath& url, bool expect_gpu_process) {\n using namespace trace_analyzer;\n\n FilePath test_path;\n PathService::Get(chrome::DIR_TEST_DATA, &test_path);\n test_path = test_path.Append(FILE_PATH_LITERAL(\"gpu\"));\n test_path = test_path.Append(url);\n\n ASSERT_TRUE(file_util::PathExists(test_path))\n << \"Missing test file: \" << test_path.value();\n\n ASSERT_TRUE(tracing::BeginTracing(\"test_gpu\"));\n\n ui_test_utils::DOMMessageQueue message_queue;\n \/\/ Have to use a new tab for the blacklist to work.\n ui_test_utils::NavigateToURLWithDisposition(\n browser(), net::FilePathToFileURL(test_path), NEW_FOREGROUND_TAB,\n ui_test_utils::BROWSER_TEST_NONE);\n \/\/ Wait for message indicating the test has finished running.\n ASSERT_TRUE(message_queue.WaitForMessage(NULL));\n\n std::string json_events;\n ASSERT_TRUE(tracing::EndTracing(&json_events));\n\n scoped_ptr analyzer(TraceAnalyzer::Create(json_events));\n EXPECT_EQ(expect_gpu_process, analyzer->FindOneEvent(\n Query(EVENT_NAME) == Query::String(\"GpuProcessLaunched\")) != NULL);\n }\n};\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, AcceleratedCompositingAllowed) {\n GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();\n EXPECT_EQ(flags.flags(), 0u);\n\n const bool expect_gpu_process = true;\n const FilePath url(FILE_PATH_LITERAL(\"feature_compositing.html\"));\n RunTest(url, expect_gpu_process);\n}\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, AcceleratedCompositingBlocked) {\n const std::string json_blacklist =\n \"{\\n\"\n \" \\\"name\\\": \\\"gpu blacklist\\\",\\n\"\n \" \\\"version\\\": \\\"1.0\\\",\\n\"\n \" \\\"entries\\\": [\\n\"\n \" {\\n\"\n \" \\\"id\\\": 1,\\n\"\n \" \\\"blacklist\\\": [\\n\"\n \" \\\"accelerated_compositing\\\"\\n\"\n \" ]\\n\"\n \" }\\n\"\n \" ]\\n\"\n \"}\";\n SetupBlacklist(json_blacklist);\n GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();\n EXPECT_EQ(\n flags.flags(),\n static_cast(GpuFeatureFlags::kGpuFeatureAcceleratedCompositing));\n\n const bool expect_gpu_process = false;\n const FilePath url(FILE_PATH_LITERAL(\"feature_compositing.html\"));\n RunTest(url, expect_gpu_process);\n}\n\n#if defined(OS_LINUX)\n\/\/ http:\/\/crbug.com\/104142\n#define WebGLAllowed FLAKY_WebGLAllowed\n#endif\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, WebGLAllowed) {\n GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();\n EXPECT_EQ(flags.flags(), 0u);\n\n const bool expect_gpu_process = true;\n const FilePath url(FILE_PATH_LITERAL(\"feature_webgl.html\"));\n RunTest(url, expect_gpu_process);\n}\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, WebGLBlocked) {\n const std::string json_blacklist =\n \"{\\n\"\n \" \\\"name\\\": \\\"gpu blacklist\\\",\\n\"\n \" \\\"version\\\": \\\"1.0\\\",\\n\"\n \" \\\"entries\\\": [\\n\"\n \" {\\n\"\n \" \\\"id\\\": 1,\\n\"\n \" \\\"blacklist\\\": [\\n\"\n \" \\\"webgl\\\"\\n\"\n \" ]\\n\"\n \" }\\n\"\n \" ]\\n\"\n \"}\";\n SetupBlacklist(json_blacklist);\n GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();\n EXPECT_EQ(\n flags.flags(),\n static_cast(GpuFeatureFlags::kGpuFeatureWebgl));\n\n const bool expect_gpu_process = false;\n const FilePath url(FILE_PATH_LITERAL(\"feature_webgl.html\"));\n RunTest(url, expect_gpu_process);\n}\n\n#if defined(OS_LINUX)\n\/\/ http:\/\/crbug.com\/104142\n#define Canvas2DAllowed FLAKY_Canvas2DAllowed\n#endif\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, Canvas2DAllowed) {\n GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();\n EXPECT_EQ(flags.flags(), 0u);\n\n#if defined(OS_MACOSX)\n \/\/ TODO(zmo): enabling Mac when skia backend is enabled.\n const bool expect_gpu_process = false;\n#else\n const bool expect_gpu_process = true;\n#endif\n const FilePath url(FILE_PATH_LITERAL(\"feature_canvas2d.html\"));\n RunTest(url, expect_gpu_process);\n}\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, Canvas2DBlocked) {\n const std::string json_blacklist =\n \"{\\n\"\n \" \\\"name\\\": \\\"gpu blacklist\\\",\\n\"\n \" \\\"version\\\": \\\"1.0\\\",\\n\"\n \" \\\"entries\\\": [\\n\"\n \" {\\n\"\n \" \\\"id\\\": 1,\\n\"\n \" \\\"blacklist\\\": [\\n\"\n \" \\\"accelerated_2d_canvas\\\"\\n\"\n \" ]\\n\"\n \" }\\n\"\n \" ]\\n\"\n \"}\";\n SetupBlacklist(json_blacklist);\n GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();\n EXPECT_EQ(\n flags.flags(),\n static_cast(GpuFeatureFlags::kGpuFeatureAccelerated2dCanvas));\n\n const bool expect_gpu_process = false;\n const FilePath url(FILE_PATH_LITERAL(\"feature_canvas2d.html\"));\n RunTest(url, expect_gpu_process);\n}\n\n} \/\/ namespace anonymous\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome_frame\/test\/net\/fake_external_tab.h\"\n\n#include \n\n#include \"app\/app_paths.h\"\n#include \"app\/resource_bundle.h\"\n#include \"app\/win_util.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/i18n\/icu_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_bstr_win.h\"\n#include \"base\/scoped_comptr_win.h\"\n#include \"base\/scoped_variant_win.h\"\n\n#include \"chrome\/browser\/browser_prefs.h\"\n#include \"chrome\/browser\/plugin_service.h\"\n#include \"chrome\/browser\/process_singleton.h\"\n#include \"chrome\/browser\/profile_manager.h\"\n#include \"chrome\/browser\/renderer_host\/render_process_host.h\"\n#include \"chrome\/browser\/renderer_host\/web_cache_manager.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_paths_internal.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/pref_service.h\"\n#include \"chrome_frame\/utils.h\"\n#include \"chrome_frame\/test\/chrome_frame_test_utils.h\"\n#include \"chrome_frame\/test\/net\/dialog_watchdog.h\"\n#include \"chrome_frame\/test\/net\/test_automation_resource_message_filter.h\"\n\nnamespace {\n\n\/\/ A special command line switch to allow developers to manually launch the\n\/\/ browser and debug CF inside the browser.\nconst wchar_t kManualBrowserLaunch[] = L\"manual-browser\";\n\n\/\/ Pops up a message box after the test environment has been set up\n\/\/ and before tearing it down. Useful for when debugging tests and not\n\/\/ the test environment that's been set up.\nconst wchar_t kPromptAfterSetup[] = L\"prompt-after-setup\";\n\nconst int kTestServerPort = 4666;\n\/\/ The test HTML we use to initialize Chrome Frame.\n\/\/ Note that there's a little trick in there to avoid an extra URL request\n\/\/ that the browser will otherwise make for the site's favicon.\n\/\/ If we don't do this the browser will create a new URL request after\n\/\/ the CF page has been initialized and that URL request will confuse the\n\/\/ global URL instance counter in the unit tests and subsequently trip\n\/\/ some DCHECKs.\nconst char kChromeFrameHtml[] = \"\"\n \"\"\n \"\"\n \"<\/head>Chrome Frame should now be loaded<\/body><\/html>\";\n\nbool ShouldLaunchBrowser() {\n return !CommandLine::ForCurrentProcess()->HasSwitch(kManualBrowserLaunch);\n}\n\nbool PromptAfterSetup() {\n return CommandLine::ForCurrentProcess()->HasSwitch(kPromptAfterSetup);\n}\n\n} \/\/ end namespace\n\nFakeExternalTab::FakeExternalTab() {\n PathService::Get(chrome::DIR_USER_DATA, &overridden_user_dir_);\n GetProfilePath(&user_data_dir_);\n PathService::Override(chrome::DIR_USER_DATA, user_data_dir_);\n process_singleton_.reset(new ProcessSingleton(user_data_dir_));\n}\n\nFakeExternalTab::~FakeExternalTab() {\n if (!overridden_user_dir_.empty()) {\n PathService::Override(chrome::DIR_USER_DATA, overridden_user_dir_);\n }\n}\n\nstd::wstring FakeExternalTab::GetProfileName() {\n return L\"iexplore\";\n}\n\nbool FakeExternalTab::GetProfilePath(FilePath* path) {\n if (!chrome::GetChromeFrameUserDataDirectory(path))\n return false;\n *path = path->Append(GetProfileName());\n return true;\n}\n\nvoid FakeExternalTab::Initialize() {\n DCHECK(g_browser_process == NULL);\n SystemMonitor system_monitor;\n\n \/\/ The gears plugin causes the PluginRequestInterceptor to kick in and it\n \/\/ will cause problems when it tries to intercept URL requests.\n PathService::Override(chrome::FILE_GEARS_PLUGIN, FilePath());\n\n icu_util::Initialize();\n\n chrome::RegisterPathProvider();\n app::RegisterPathProvider();\n\n \/\/ Load Chrome.dll as our resource dll.\n FilePath dll;\n PathService::Get(base::DIR_MODULE, &dll);\n dll = dll.Append(chrome::kBrowserResourcesDll);\n HMODULE res_mod = ::LoadLibraryExW(dll.value().c_str(),\n NULL, LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE);\n DCHECK(res_mod);\n _AtlBaseModule.SetResourceInstance(res_mod);\n\n ResourceBundle::InitSharedInstance(L\"en-US\");\n\n CommandLine* cmd = CommandLine::ForCurrentProcess();\n cmd->AppendSwitch(switches::kDisableWebResources);\n cmd->AppendSwitch(switches::kSingleProcess);\n\n browser_process_.reset(new BrowserProcessImpl(*cmd));\n \/\/ BrowserProcessImpl's constructor should set g_browser_process.\n DCHECK(g_browser_process);\n \/\/ Set the app locale and create the child threads.\n g_browser_process->set_application_locale(\"en-US\");\n g_browser_process->db_thread();\n g_browser_process->file_thread();\n g_browser_process->io_thread();\n\n RenderProcessHost::set_run_renderer_in_process(true);\n\n Profile* profile = g_browser_process->profile_manager()->\n GetDefaultProfile(FilePath(user_data()));\n PrefService* prefs = profile->GetPrefs();\n DCHECK(prefs != NULL);\n\n WebCacheManager::RegisterPrefs(prefs);\n PrefService* local_state = browser_process_->local_state();\n local_state->RegisterStringPref(prefs::kApplicationLocale, L\"\");\n local_state->RegisterBooleanPref(prefs::kMetricsReportingEnabled, false);\n\n browser::RegisterLocalState(local_state);\n\n \/\/ Override some settings to avoid hitting some preferences that have not\n \/\/ been registered.\n prefs->SetBoolean(prefs::kPasswordManagerEnabled, false);\n prefs->SetBoolean(prefs::kAlternateErrorPagesEnabled, false);\n prefs->SetBoolean(prefs::kSafeBrowsingEnabled, false);\n\n profile->InitExtensions();\n}\n\nvoid FakeExternalTab::Shutdown() {\n browser_process_.reset();\n g_browser_process = NULL;\n process_singleton_.reset();\n\n ResourceBundle::CleanupSharedInstance();\n}\n\nCFUrlRequestUnittestRunner::CFUrlRequestUnittestRunner(int argc, char** argv)\n : NetTestSuite(argc, argv),\n chrome_frame_html_(\"\/chrome_frame\", kChromeFrameHtml) {\n \/\/ Register the main thread by instantiating it, but don't call any methods.\n main_thread_.reset(new ChromeThread(ChromeThread::UI,\n MessageLoop::current()));\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n fake_chrome_.Initialize();\n pss_subclass_.reset(new ProcessSingletonSubclass(this));\n EXPECT_TRUE(pss_subclass_->Subclass(fake_chrome_.user_data()));\n StartChromeFrameInHostBrowser();\n}\n\nCFUrlRequestUnittestRunner::~CFUrlRequestUnittestRunner() {\n fake_chrome_.Shutdown();\n}\n\nvoid CFUrlRequestUnittestRunner::StartChromeFrameInHostBrowser() {\n if (!ShouldLaunchBrowser())\n return;\n\n win_util::ScopedCOMInitializer com;\n chrome_frame_test::CloseAllIEWindows();\n\n test_http_server_.reset(new test_server::SimpleWebServer(kTestServerPort));\n test_http_server_->AddResponse(&chrome_frame_html_);\n std::wstring url(StringPrintf(L\"http:\/\/localhost:%i\/chrome_frame\",\n kTestServerPort).c_str());\n\n \/\/ Launch IE. This launches IE correctly on Vista too.\n ScopedHandle ie_process(chrome_frame_test::LaunchIE(url));\n EXPECT_TRUE(ie_process.IsValid());\n\n \/\/ NOTE: If you're running IE8 and CF is not being loaded, you need to\n \/\/ disable IE8's prebinding until CF properly handles that situation.\n \/\/\n \/\/ HKCU\\Software\\Microsoft\\Internet Explorer\\Main\n \/\/ Value name: EnablePreBinding (REG_DWORD)\n \/\/ Value: 0\n}\n\nvoid CFUrlRequestUnittestRunner::ShutDownHostBrowser() {\n if (ShouldLaunchBrowser()) {\n win_util::ScopedCOMInitializer com;\n chrome_frame_test::CloseAllIEWindows();\n }\n}\n\n\/\/ Override virtual void Initialize to not call icu initialize\nvoid CFUrlRequestUnittestRunner::Initialize() {\n DCHECK(::GetCurrentThreadId() == test_thread_id_);\n\n \/\/ Start by replicating some of the steps that would otherwise be\n \/\/ done by TestSuite::Initialize. We can't call the base class\n \/\/ directly because it will attempt to initialize some things such as\n \/\/ ICU that have already been initialized for this process.\n InitializeLogging();\n base::Time::UseHighResolutionTimer(true);\n\n#if !defined(PURIFY) && defined(OS_WIN)\n logging::SetLogAssertHandler(UnitTestAssertHandler);\n#endif \/\/ !defined(PURIFY)\n\n \/\/ Next, do some initialization for NetTestSuite.\n NetTestSuite::InitializeTestThread();\n}\n\nvoid CFUrlRequestUnittestRunner::Shutdown() {\n DCHECK(::GetCurrentThreadId() == test_thread_id_);\n NetTestSuite::Shutdown();\n}\n\nvoid CFUrlRequestUnittestRunner::OnConnectAutomationProviderToChannel(\n const std::string& channel_id) {\n Profile* profile = g_browser_process->profile_manager()->\n GetDefaultProfile(fake_chrome_.user_data());\n\n AutomationProviderList* list =\n g_browser_process->InitAutomationProviderList();\n DCHECK(list);\n list->AddProvider(TestAutomationProvider::NewAutomationProvider(profile,\n channel_id, this));\n}\n\nvoid CFUrlRequestUnittestRunner::OnInitialTabLoaded() {\n test_http_server_.reset();\n StartTests();\n}\n\nvoid CFUrlRequestUnittestRunner::RunMainUIThread() {\n DCHECK(MessageLoop::current());\n DCHECK(MessageLoop::current()->type() == MessageLoop::TYPE_UI);\n MessageLoop::current()->Run();\n}\n\nvoid CFUrlRequestUnittestRunner::StartTests() {\n if (PromptAfterSetup())\n MessageBoxA(NULL, \"click ok to run\", \"\", MB_OK);\n\n DCHECK_EQ(test_thread_.IsValid(), false);\n test_thread_.Set(::CreateThread(NULL, 0, RunAllUnittests, this, 0,\n &test_thread_id_));\n DCHECK(test_thread_.IsValid());\n}\n\n\/\/ static\nDWORD CFUrlRequestUnittestRunner::RunAllUnittests(void* param) {\n PlatformThread::SetName(\"CFUrlRequestUnittestRunner\");\n \/\/ Needed for some url request tests like the intercept job tests, etc.\n NotificationService service;\n CFUrlRequestUnittestRunner* me =\n reinterpret_cast(param);\n me->Run();\n me->fake_chrome_.ui_loop()->PostTask(FROM_HERE,\n NewRunnableFunction(TakeDownBrowser, me));\n return 0;\n}\n\n\/\/ static\nvoid CFUrlRequestUnittestRunner::TakeDownBrowser(\n CFUrlRequestUnittestRunner* me) {\n if (PromptAfterSetup())\n MessageBoxA(NULL, \"click ok to exit\", \"\", MB_OK);\n\n me->ShutDownHostBrowser();\n}\n\nvoid CFUrlRequestUnittestRunner::InitializeLogging() {\n FilePath exe;\n PathService::Get(base::FILE_EXE, &exe);\n FilePath log_filename = exe.ReplaceExtension(FILE_PATH_LITERAL(\"log\"));\n logging::InitLogging(log_filename.value().c_str(),\n logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG,\n logging::LOCK_LOG_FILE,\n logging::DELETE_OLD_LOG_FILE);\n \/\/ We want process and thread IDs because we may have multiple processes.\n \/\/ Note: temporarily enabled timestamps in an effort to catch bug 6361.\n logging::SetLogItems(true, true, true, true);\n}\n\nvoid FilterDisabledTests() {\n if (::testing::FLAGS_gtest_filter.length() &&\n ::testing::FLAGS_gtest_filter.Compare(\"*\") != 0) {\n \/\/ Don't override user specified filters.\n return;\n }\n\n const char* disabled_tests[] = {\n \/\/ Tests disabled since they're testing the same functionality used\n \/\/ by the TestAutomationProvider.\n \"URLRequestTest.Intercept\",\n \"URLRequestTest.InterceptNetworkError\",\n \"URLRequestTest.InterceptRestartRequired\",\n \"URLRequestTest.InterceptRespectsCancelMain\",\n \"URLRequestTest.InterceptRespectsCancelRedirect\",\n \"URLRequestTest.InterceptRespectsCancelFinal\",\n \"URLRequestTest.InterceptRespectsCancelInRestart\",\n \"URLRequestTest.InterceptRedirect\",\n \"URLRequestTest.InterceptServerError\",\n \"URLRequestTestFTP.*\",\n\n \/\/ Tests that are currently not working:\n\n \/\/ Temporarily disabled because they needs user input (login dialog).\n \"URLRequestTestHTTP.BasicAuth\",\n \"URLRequestTestHTTP.BasicAuthWithCookies\",\n\n \/\/ HTTPS tests temporarily disabled due to the certificate error dialog.\n \/\/ TODO(tommi): The tests currently fail though, so need to fix.\n \"HTTPSRequestTest.HTTPSMismatchedTest\",\n \"HTTPSRequestTest.HTTPSExpiredTest\",\n\n \/\/ Tests chrome's network stack's cache (might not apply to CF).\n \"URLRequestTestHTTP.VaryHeader\",\n\n \/\/ I suspect we can only get this one to work (if at all) on IE8 and\n \/\/ later by using the new INTERNET_OPTION_SUPPRESS_BEHAVIOR flags\n \/\/ See http:\/\/msdn.microsoft.com\/en-us\/library\/aa385328(VS.85).aspx\n \"URLRequestTest.DoNotSaveCookies\",\n\n \/\/ TODO(ananta): This test has been consistently failing. Disabling it for\n \/\/ now.\n \"URLRequestTestHTTP.GetTest_NoCache\",\n\n \/\/ These tests have been disabled as the Chrome cookie policies don't make\n \/\/ sense for the host network stack.\n \"URLRequestTest.DoNotSaveCookies_ViaPolicy\",\n \"URLRequestTest.DoNotSendCookies_ViaPolicy\",\n \"URLRequestTest.DoNotSaveCookies_ViaPolicy_Async\",\n \"URLRequestTest.CookiePolicy_ForceSession\",\n };\n\n std::string filter(\"-\"); \/\/ All following filters will be negative.\n for (int i = 0; i < arraysize(disabled_tests); ++i) {\n if (i > 0)\n filter += \":\";\n filter += disabled_tests[i];\n }\n\n ::testing::FLAGS_gtest_filter = filter;\n}\n\nint main(int argc, char** argv) {\n DialogWatchdog watchdog;\n \/\/ See url_request_unittest.cc for these credentials.\n SupplyProxyCredentials credentials(\"user\", \"secret\");\n watchdog.AddObserver(&credentials);\n testing::InitGoogleTest(&argc, argv);\n FilterDisabledTests();\n PluginService::EnableChromePlugins(false);\n CFUrlRequestUnittestRunner test_suite(argc, argv);\n test_suite.RunMainUIThread();\n return 0;\n}\nDisabling the following net tests for ChromeFrame as this functionality does not exist there.\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome_frame\/test\/net\/fake_external_tab.h\"\n\n#include \n\n#include \"app\/app_paths.h\"\n#include \"app\/resource_bundle.h\"\n#include \"app\/win_util.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/i18n\/icu_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_bstr_win.h\"\n#include \"base\/scoped_comptr_win.h\"\n#include \"base\/scoped_variant_win.h\"\n\n#include \"chrome\/browser\/browser_prefs.h\"\n#include \"chrome\/browser\/plugin_service.h\"\n#include \"chrome\/browser\/process_singleton.h\"\n#include \"chrome\/browser\/profile_manager.h\"\n#include \"chrome\/browser\/renderer_host\/render_process_host.h\"\n#include \"chrome\/browser\/renderer_host\/web_cache_manager.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_paths_internal.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/pref_service.h\"\n#include \"chrome_frame\/utils.h\"\n#include \"chrome_frame\/test\/chrome_frame_test_utils.h\"\n#include \"chrome_frame\/test\/net\/dialog_watchdog.h\"\n#include \"chrome_frame\/test\/net\/test_automation_resource_message_filter.h\"\n\nnamespace {\n\n\/\/ A special command line switch to allow developers to manually launch the\n\/\/ browser and debug CF inside the browser.\nconst wchar_t kManualBrowserLaunch[] = L\"manual-browser\";\n\n\/\/ Pops up a message box after the test environment has been set up\n\/\/ and before tearing it down. Useful for when debugging tests and not\n\/\/ the test environment that's been set up.\nconst wchar_t kPromptAfterSetup[] = L\"prompt-after-setup\";\n\nconst int kTestServerPort = 4666;\n\/\/ The test HTML we use to initialize Chrome Frame.\n\/\/ Note that there's a little trick in there to avoid an extra URL request\n\/\/ that the browser will otherwise make for the site's favicon.\n\/\/ If we don't do this the browser will create a new URL request after\n\/\/ the CF page has been initialized and that URL request will confuse the\n\/\/ global URL instance counter in the unit tests and subsequently trip\n\/\/ some DCHECKs.\nconst char kChromeFrameHtml[] = \"\"\n \"\"\n \"\"\n \"<\/head>Chrome Frame should now be loaded<\/body><\/html>\";\n\nbool ShouldLaunchBrowser() {\n return !CommandLine::ForCurrentProcess()->HasSwitch(kManualBrowserLaunch);\n}\n\nbool PromptAfterSetup() {\n return CommandLine::ForCurrentProcess()->HasSwitch(kPromptAfterSetup);\n}\n\n} \/\/ end namespace\n\nFakeExternalTab::FakeExternalTab() {\n PathService::Get(chrome::DIR_USER_DATA, &overridden_user_dir_);\n GetProfilePath(&user_data_dir_);\n PathService::Override(chrome::DIR_USER_DATA, user_data_dir_);\n process_singleton_.reset(new ProcessSingleton(user_data_dir_));\n}\n\nFakeExternalTab::~FakeExternalTab() {\n if (!overridden_user_dir_.empty()) {\n PathService::Override(chrome::DIR_USER_DATA, overridden_user_dir_);\n }\n}\n\nstd::wstring FakeExternalTab::GetProfileName() {\n return L\"iexplore\";\n}\n\nbool FakeExternalTab::GetProfilePath(FilePath* path) {\n if (!chrome::GetChromeFrameUserDataDirectory(path))\n return false;\n *path = path->Append(GetProfileName());\n return true;\n}\n\nvoid FakeExternalTab::Initialize() {\n DCHECK(g_browser_process == NULL);\n SystemMonitor system_monitor;\n\n \/\/ The gears plugin causes the PluginRequestInterceptor to kick in and it\n \/\/ will cause problems when it tries to intercept URL requests.\n PathService::Override(chrome::FILE_GEARS_PLUGIN, FilePath());\n\n icu_util::Initialize();\n\n chrome::RegisterPathProvider();\n app::RegisterPathProvider();\n\n \/\/ Load Chrome.dll as our resource dll.\n FilePath dll;\n PathService::Get(base::DIR_MODULE, &dll);\n dll = dll.Append(chrome::kBrowserResourcesDll);\n HMODULE res_mod = ::LoadLibraryExW(dll.value().c_str(),\n NULL, LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE);\n DCHECK(res_mod);\n _AtlBaseModule.SetResourceInstance(res_mod);\n\n ResourceBundle::InitSharedInstance(L\"en-US\");\n\n CommandLine* cmd = CommandLine::ForCurrentProcess();\n cmd->AppendSwitch(switches::kDisableWebResources);\n cmd->AppendSwitch(switches::kSingleProcess);\n\n browser_process_.reset(new BrowserProcessImpl(*cmd));\n \/\/ BrowserProcessImpl's constructor should set g_browser_process.\n DCHECK(g_browser_process);\n \/\/ Set the app locale and create the child threads.\n g_browser_process->set_application_locale(\"en-US\");\n g_browser_process->db_thread();\n g_browser_process->file_thread();\n g_browser_process->io_thread();\n\n RenderProcessHost::set_run_renderer_in_process(true);\n\n Profile* profile = g_browser_process->profile_manager()->\n GetDefaultProfile(FilePath(user_data()));\n PrefService* prefs = profile->GetPrefs();\n DCHECK(prefs != NULL);\n\n WebCacheManager::RegisterPrefs(prefs);\n PrefService* local_state = browser_process_->local_state();\n local_state->RegisterStringPref(prefs::kApplicationLocale, L\"\");\n local_state->RegisterBooleanPref(prefs::kMetricsReportingEnabled, false);\n\n browser::RegisterLocalState(local_state);\n\n \/\/ Override some settings to avoid hitting some preferences that have not\n \/\/ been registered.\n prefs->SetBoolean(prefs::kPasswordManagerEnabled, false);\n prefs->SetBoolean(prefs::kAlternateErrorPagesEnabled, false);\n prefs->SetBoolean(prefs::kSafeBrowsingEnabled, false);\n\n profile->InitExtensions();\n}\n\nvoid FakeExternalTab::Shutdown() {\n browser_process_.reset();\n g_browser_process = NULL;\n process_singleton_.reset();\n\n ResourceBundle::CleanupSharedInstance();\n}\n\nCFUrlRequestUnittestRunner::CFUrlRequestUnittestRunner(int argc, char** argv)\n : NetTestSuite(argc, argv),\n chrome_frame_html_(\"\/chrome_frame\", kChromeFrameHtml) {\n \/\/ Register the main thread by instantiating it, but don't call any methods.\n main_thread_.reset(new ChromeThread(ChromeThread::UI,\n MessageLoop::current()));\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n fake_chrome_.Initialize();\n pss_subclass_.reset(new ProcessSingletonSubclass(this));\n EXPECT_TRUE(pss_subclass_->Subclass(fake_chrome_.user_data()));\n StartChromeFrameInHostBrowser();\n}\n\nCFUrlRequestUnittestRunner::~CFUrlRequestUnittestRunner() {\n fake_chrome_.Shutdown();\n}\n\nvoid CFUrlRequestUnittestRunner::StartChromeFrameInHostBrowser() {\n if (!ShouldLaunchBrowser())\n return;\n\n win_util::ScopedCOMInitializer com;\n chrome_frame_test::CloseAllIEWindows();\n\n test_http_server_.reset(new test_server::SimpleWebServer(kTestServerPort));\n test_http_server_->AddResponse(&chrome_frame_html_);\n std::wstring url(StringPrintf(L\"http:\/\/localhost:%i\/chrome_frame\",\n kTestServerPort).c_str());\n\n \/\/ Launch IE. This launches IE correctly on Vista too.\n ScopedHandle ie_process(chrome_frame_test::LaunchIE(url));\n EXPECT_TRUE(ie_process.IsValid());\n\n \/\/ NOTE: If you're running IE8 and CF is not being loaded, you need to\n \/\/ disable IE8's prebinding until CF properly handles that situation.\n \/\/\n \/\/ HKCU\\Software\\Microsoft\\Internet Explorer\\Main\n \/\/ Value name: EnablePreBinding (REG_DWORD)\n \/\/ Value: 0\n}\n\nvoid CFUrlRequestUnittestRunner::ShutDownHostBrowser() {\n if (ShouldLaunchBrowser()) {\n win_util::ScopedCOMInitializer com;\n chrome_frame_test::CloseAllIEWindows();\n }\n}\n\n\/\/ Override virtual void Initialize to not call icu initialize\nvoid CFUrlRequestUnittestRunner::Initialize() {\n DCHECK(::GetCurrentThreadId() == test_thread_id_);\n\n \/\/ Start by replicating some of the steps that would otherwise be\n \/\/ done by TestSuite::Initialize. We can't call the base class\n \/\/ directly because it will attempt to initialize some things such as\n \/\/ ICU that have already been initialized for this process.\n InitializeLogging();\n base::Time::UseHighResolutionTimer(true);\n\n#if !defined(PURIFY) && defined(OS_WIN)\n logging::SetLogAssertHandler(UnitTestAssertHandler);\n#endif \/\/ !defined(PURIFY)\n\n \/\/ Next, do some initialization for NetTestSuite.\n NetTestSuite::InitializeTestThread();\n}\n\nvoid CFUrlRequestUnittestRunner::Shutdown() {\n DCHECK(::GetCurrentThreadId() == test_thread_id_);\n NetTestSuite::Shutdown();\n}\n\nvoid CFUrlRequestUnittestRunner::OnConnectAutomationProviderToChannel(\n const std::string& channel_id) {\n Profile* profile = g_browser_process->profile_manager()->\n GetDefaultProfile(fake_chrome_.user_data());\n\n AutomationProviderList* list =\n g_browser_process->InitAutomationProviderList();\n DCHECK(list);\n list->AddProvider(TestAutomationProvider::NewAutomationProvider(profile,\n channel_id, this));\n}\n\nvoid CFUrlRequestUnittestRunner::OnInitialTabLoaded() {\n test_http_server_.reset();\n StartTests();\n}\n\nvoid CFUrlRequestUnittestRunner::RunMainUIThread() {\n DCHECK(MessageLoop::current());\n DCHECK(MessageLoop::current()->type() == MessageLoop::TYPE_UI);\n MessageLoop::current()->Run();\n}\n\nvoid CFUrlRequestUnittestRunner::StartTests() {\n if (PromptAfterSetup())\n MessageBoxA(NULL, \"click ok to run\", \"\", MB_OK);\n\n DCHECK_EQ(test_thread_.IsValid(), false);\n test_thread_.Set(::CreateThread(NULL, 0, RunAllUnittests, this, 0,\n &test_thread_id_));\n DCHECK(test_thread_.IsValid());\n}\n\n\/\/ static\nDWORD CFUrlRequestUnittestRunner::RunAllUnittests(void* param) {\n PlatformThread::SetName(\"CFUrlRequestUnittestRunner\");\n \/\/ Needed for some url request tests like the intercept job tests, etc.\n NotificationService service;\n CFUrlRequestUnittestRunner* me =\n reinterpret_cast(param);\n me->Run();\n me->fake_chrome_.ui_loop()->PostTask(FROM_HERE,\n NewRunnableFunction(TakeDownBrowser, me));\n return 0;\n}\n\n\/\/ static\nvoid CFUrlRequestUnittestRunner::TakeDownBrowser(\n CFUrlRequestUnittestRunner* me) {\n if (PromptAfterSetup())\n MessageBoxA(NULL, \"click ok to exit\", \"\", MB_OK);\n\n me->ShutDownHostBrowser();\n}\n\nvoid CFUrlRequestUnittestRunner::InitializeLogging() {\n FilePath exe;\n PathService::Get(base::FILE_EXE, &exe);\n FilePath log_filename = exe.ReplaceExtension(FILE_PATH_LITERAL(\"log\"));\n logging::InitLogging(log_filename.value().c_str(),\n logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG,\n logging::LOCK_LOG_FILE,\n logging::DELETE_OLD_LOG_FILE);\n \/\/ We want process and thread IDs because we may have multiple processes.\n \/\/ Note: temporarily enabled timestamps in an effort to catch bug 6361.\n logging::SetLogItems(true, true, true, true);\n}\n\nvoid FilterDisabledTests() {\n if (::testing::FLAGS_gtest_filter.length() &&\n ::testing::FLAGS_gtest_filter.Compare(\"*\") != 0) {\n \/\/ Don't override user specified filters.\n return;\n }\n\n const char* disabled_tests[] = {\n \/\/ Tests disabled since they're testing the same functionality used\n \/\/ by the TestAutomationProvider.\n \"URLRequestTest.Intercept\",\n \"URLRequestTest.InterceptNetworkError\",\n \"URLRequestTest.InterceptRestartRequired\",\n \"URLRequestTest.InterceptRespectsCancelMain\",\n \"URLRequestTest.InterceptRespectsCancelRedirect\",\n \"URLRequestTest.InterceptRespectsCancelFinal\",\n \"URLRequestTest.InterceptRespectsCancelInRestart\",\n \"URLRequestTest.InterceptRedirect\",\n \"URLRequestTest.InterceptServerError\",\n \"URLRequestTestFTP.*\",\n\n \/\/ Tests that are currently not working:\n\n \/\/ Temporarily disabled because they needs user input (login dialog).\n \"URLRequestTestHTTP.BasicAuth\",\n \"URLRequestTestHTTP.BasicAuthWithCookies\",\n\n \/\/ HTTPS tests temporarily disabled due to the certificate error dialog.\n \/\/ TODO(tommi): The tests currently fail though, so need to fix.\n \"HTTPSRequestTest.HTTPSMismatchedTest\",\n \"HTTPSRequestTest.HTTPSExpiredTest\",\n\n \/\/ Tests chrome's network stack's cache (might not apply to CF).\n \"URLRequestTestHTTP.VaryHeader\",\n\n \/\/ I suspect we can only get this one to work (if at all) on IE8 and\n \/\/ later by using the new INTERNET_OPTION_SUPPRESS_BEHAVIOR flags\n \/\/ See http:\/\/msdn.microsoft.com\/en-us\/library\/aa385328(VS.85).aspx\n \"URLRequestTest.DoNotSaveCookies\",\n\n \/\/ TODO(ananta): This test has been consistently failing. Disabling it for\n \/\/ now.\n \"URLRequestTestHTTP.GetTest_NoCache\",\n\n \/\/ These tests have been disabled as the Chrome cookie policies don't make\n \/\/ sense or have not been implemented for the host network stack.\n \"URLRequestTest.DoNotSaveCookies_ViaPolicy\",\n \"URLRequestTest.DoNotSendCookies_ViaPolicy\",\n \"URLRequestTest.DoNotSaveCookies_ViaPolicy_Async\",\n \"URLRequestTest.CookiePolicy_ForceSession\",\n \"URLRequestTest.DoNotSendCookies\",\n \"URLRequestTest.DoNotSendCookies_ViaPolicy_Async\",\n \"URLRequestTest.CancelTest_During_OnGetCookiesBlocked\",\n \"URLRequestTest.CancelTest_During_OnSetCookieBlocked\",\n };\n\n std::string filter(\"-\"); \/\/ All following filters will be negative.\n for (int i = 0; i < arraysize(disabled_tests); ++i) {\n if (i > 0)\n filter += \":\";\n filter += disabled_tests[i];\n }\n\n ::testing::FLAGS_gtest_filter = filter;\n}\n\nint main(int argc, char** argv) {\n DialogWatchdog watchdog;\n \/\/ See url_request_unittest.cc for these credentials.\n SupplyProxyCredentials credentials(\"user\", \"secret\");\n watchdog.AddObserver(&credentials);\n testing::InitGoogleTest(&argc, argv);\n FilterDisabledTests();\n PluginService::EnableChromePlugins(false);\n CFUrlRequestUnittestRunner test_suite(argc, argv);\n test_suite.RunMainUIThread();\n return 0;\n}\n<|endoftext|>"} {"text":"\/* ---------------------------------------------------------------------------\n** This software is in the public domain, furnished \"as is\", without technical\n** support, and with no warranty, express or implied, as to its usefulness for\n** any purpose.\n**\n** rtspconnectionclient.cpp\n** \n** Interface to an RTSP client connection\n** \n** -------------------------------------------------------------------------*\/\n\n\n#include \"rtspconnectionclient.h\"\n\nRTSPConnection::SessionSink::SessionSink(UsageEnvironment& env, Callback* callback) \n\t: MediaSink(env)\n\t, m_buffer(NULL)\n\t, m_bufferSize(0)\n\t, m_callback(callback) \n\t, m_markerSize(0)\n{\n\tallocate(1024*1024);\n}\n\nRTSPConnection::SessionSink::~SessionSink()\n{\n\tdelete [] m_buffer;\n}\n\nvoid RTSPConnection::SessionSink::allocate(ssize_t bufferSize)\n{\n\tm_bufferSize = bufferSize;\n\tm_buffer = new u_int8_t[m_bufferSize];\n\tif (m_callback)\n\t{\n\t\tm_markerSize = m_callback->onNewBuffer(m_buffer, m_bufferSize);\n\t\tenvir() << \"markerSize:\" << (int)m_markerSize << \"\\n\";\n\t}\n}\n\n\nvoid RTSPConnection::SessionSink::afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds)\n{\n\tif (numTruncatedBytes != 0)\n\t{\n\t\tdelete [] m_buffer;\n\t\tenvir() << \"buffer too small \" << (int)m_bufferSize << \" allocate bigger one\\n\";\n\t\tallocate(m_bufferSize*2);\n\t}\n\telse if (m_callback)\n\t{\n\t\tif (!m_callback->onData(this->name(), m_buffer, frameSize+m_markerSize, presentationTime))\n\t\t{\n\t\t\tenvir() << \"NOTIFY failed\\n\";\n\t\t}\n\t}\n\tthis->continuePlaying();\n}\n\nBoolean RTSPConnection::SessionSink::continuePlaying()\n{\n\tBoolean ret = False;\n\tif (source() != NULL)\n\t{\n\t\tsource()->getNextFrame(m_buffer+m_markerSize, m_bufferSize-m_markerSize,\n\t\t\t\tafterGettingFrame, this,\n\t\t\t\tonSourceClosure, this);\n\t\tret = True;\n\t}\n\treturn ret;\t\n}\n\n\nRTSPConnection::RTSPConnection(Environment& env, Callback* callback, const char* rtspURL, int timeout, bool rtpovertcp, int verbosityLevel) \n\t\t\t\t: m_startCallbackTask(NULL)\n\t\t\t\t, m_env(env)\n\t\t\t\t, m_callback(callback)\n\t\t\t\t, m_url(rtspURL)\n\t\t\t\t, m_timeout(timeout)\n\t\t\t\t, m_rtpovertcp(rtpovertcp)\n\t\t\t\t, m_verbosity(verbosityLevel)\n\t\t\t\t, m_rtspClient(NULL)\n{\n\tthis->start();\n}\n\nvoid RTSPConnection::start(unsigned int delay)\n{\n\tm_startCallbackTask = m_env.taskScheduler().scheduleDelayedTask(delay*1000000, TaskstartCallback, this);\n}\t\n\nvoid RTSPConnection::TaskstartCallback() \n{\n\tif (m_rtspClient)\n\t{\n\t\t\n\t\tMedium::close(m_rtspClient);\n\t}\n\t\n\tm_rtspClient = new RTSPClientConnection(*this, m_env, m_callback, m_url.c_str(), m_timeout, m_rtpovertcp, m_verbosity);\t\n}\n\nRTSPConnection::~RTSPConnection()\n{\n\tm_env.taskScheduler().unscheduleDelayedTask(m_startCallbackTask);\n\tMedium::close(m_rtspClient);\n}\n\n\t\t\nRTSPConnection::RTSPClientConnection::RTSPClientConnection(RTSPConnection& connection, Environment& env, Callback* callback, const char* rtspURL, int timeout, bool rtpovertcp, int verbosityLevel) \n\t\t\t\t: RTSPClientConstrutor(env, rtspURL, verbosityLevel, NULL, 0)\n\t\t\t\t, m_connection(connection)\n\t\t\t\t, m_timeout(timeout)\n\t\t\t\t, m_rtpovertcp(rtpovertcp)\n\t\t\t\t, m_session(NULL)\n\t\t\t\t, m_subSessionIter(NULL)\n\t\t\t\t, m_callback(callback)\n\t\t\t\t, m_nbPacket(0)\n{\n\t\/\/ start tasks\n\tm_ConnectionTimeoutTask = envir().taskScheduler().scheduleDelayedTask(m_timeout*1000000, TaskConnectionTimeout, this);\n\t\n\t\/\/ initiate connection process\n\tthis->sendNextCommand();\n}\n\nRTSPConnection::RTSPClientConnection::~RTSPClientConnection()\n{\n\tenvir().taskScheduler().unscheduleDelayedTask(m_ConnectionTimeoutTask);\n\tenvir().taskScheduler().unscheduleDelayedTask(m_DataArrivalTimeoutTask);\n\t\n\tdelete m_subSessionIter;\n\t\n\t\/\/ free subsession\n\tif (m_session != NULL) \n\t{\n\t\tMediaSubsessionIterator iter(*m_session);\n\t\tMediaSubsession* subsession;\n\t\twhile ((subsession = iter.next()) != NULL) \n\t\t{\n\t\t\tif (subsession->sink) \n\t\t\t{\n\t\t\t\tenvir() << \"Close session: \" << subsession->mediumName() << \"\/\" << subsession->codecName() << \"\\n\";\n\t\t\t\tMedium::close(subsession->sink);\n\t\t\t\tsubsession->sink = NULL;\n\t\t\t}\n\t\t}\t\n\t\tMedium::close(m_session);\n\t}\n}\n\t\t\nvoid RTSPConnection::RTSPClientConnection::sendNextCommand() \n{\n\tif (m_subSessionIter == NULL)\n\t{\n\t\t\/\/ no SDP, send DESCRIBE\n\t\tthis->sendDescribeCommand(continueAfterDESCRIBE); \n\t}\n\telse\n\t{\n\t\tm_subSession = m_subSessionIter->next();\n\t\tif (m_subSession != NULL) \n\t\t{\n\t\t\t\/\/ still subsession to SETUP\n\t\t\tif (!m_subSession->initiate()) \n\t\t\t{\n\t\t\t\tenvir() << \"Failed to initiate \" << m_subSession->mediumName() << \"\/\" << m_subSession->codecName() << \" subsession: \" << envir().getResultMsg() << \"\\n\";\n\t\t\t\tthis->sendNextCommand();\n\t\t\t} \n\t\t\telse \n\t\t\t{\n\t\t\t\tif (fVerbosityLevel > 1) \n\t\t\t\t{\t\t\t\t\n\t\t\t\t\tenvir() << \"Initiated \" << m_subSession->mediumName() << \"\/\" << m_subSession->codecName() << \" subsession\" << \"\\n\";\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis->sendSetupCommand(*m_subSession, continueAfterSETUP, false, m_rtpovertcp);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ no more subsession to SETUP, send PLAY\n\t\t\tthis->sendPlayCommand(*m_session, continueAfterPLAY);\n\t\t}\n\t}\n}\n\nvoid RTSPConnection::RTSPClientConnection::continueAfterDESCRIBE(int resultCode, char* resultString)\n{\n\tif (resultCode != 0) \n\t{\n\t\tenvir() << \"Failed to DESCRIBE: \" << resultString << \"\\n\";\n\t\tm_callback->onError(m_connection, resultString);\n\t}\n\telse\n\t{\n\t\tif (fVerbosityLevel > 1) \n\t\t{\n\t\t\tenvir() << \"Got SDP:\\n\" << resultString << \"\\n\";\n\t\t}\n\t\tm_session = MediaSession::createNew(envir(), resultString);\n\t\tm_subSessionIter = new MediaSubsessionIterator(*m_session);\n\t\tthis->sendNextCommand(); \n\t}\n\tdelete[] resultString;\n}\n\nvoid RTSPConnection::RTSPClientConnection::continueAfterSETUP(int resultCode, char* resultString)\n{\n\tif (resultCode != 0) \n\t{\n\t\tenvir() << \"Failed to SETUP: \" << resultString << \"\\n\";\n\t\tm_callback->onError(m_connection, resultString);\n\t}\n\telse\n\t{\t\t\t\t\n\t\tm_subSession->sink = SessionSink::createNew(envir(), m_callback);\n\t\tif (m_subSession->sink == NULL) \n\t\t{\n\t\t\tenvir() << \"Failed to create a data sink for \" << m_subSession->mediumName() << \"\/\" << m_subSession->codecName() << \" subsession: \" << envir().getResultMsg() << \"\\n\";\n\t\t}\n\t\telse if (m_callback->onNewSession(m_subSession->sink->name(), m_subSession->mediumName(), m_subSession->codecName(), m_subSession->savedSDPLines()))\n\t\t{\n\t\t\tenvir() << \"Created a data sink for the \\\"\" << m_subSession->mediumName() << \"\/\" << m_subSession->codecName() << \"\\\" subsession\" << \"\\n\";\n\t\t\tm_subSession->sink->startPlaying(*(m_subSession->readSource()), NULL, NULL);\n\t\t}\n\t}\n\tdelete[] resultString;\n\tthis->sendNextCommand(); \n}\t\n\nvoid RTSPConnection::RTSPClientConnection::continueAfterPLAY(int resultCode, char* resultString)\n{\n\tif (resultCode != 0) \n\t{\n\t\tenvir() << \"Failed to PLAY: \" << resultString << \"\\n\";\n\t\tm_callback->onError(m_connection, resultString);\n\t}\n\telse\n\t{\n\t\tif (fVerbosityLevel > 1) \n\t\t{\n\t\t\tenvir() << \"PLAY OK\" << \"\\n\";\n\t\t}\n\t\tm_DataArrivalTimeoutTask = envir().taskScheduler().scheduleDelayedTask(m_timeout*1000000, TaskDataArrivalTimeout, this);\n\n\t}\n\tenvir().taskScheduler().unscheduleDelayedTask(m_ConnectionTimeoutTask);\n\tdelete[] resultString;\n}\n\nvoid RTSPConnection::RTSPClientConnection::TaskConnectionTimeout()\n{\n\tm_callback->onConnectionTimeout(m_connection);\n}\n\t\t\nvoid RTSPConnection::RTSPClientConnection::TaskDataArrivalTimeout()\n{\n\tunsigned int newTotNumPacketsReceived = 0;\n\n\tMediaSubsessionIterator iter(*m_session);\n\tMediaSubsession* subsession;\n\twhile ((subsession = iter.next()) != NULL) \n\t{\n\t\tRTPSource* src = subsession->rtpSource();\n\t\tif (src != NULL) \n\t\t{\n\t\t\tnewTotNumPacketsReceived += src->receptionStatsDB().totNumPacketsReceived();\n\t\t}\n\t}\n\t\n\tif (newTotNumPacketsReceived == m_nbPacket) \n\t{\n\t\tm_callback->onDataTimeout(m_connection);\n\t} \n\telse \n\t{\n\t\tm_nbPacket = newTotNumPacketsReceived;\n\t\tm_DataArrivalTimeoutTask = envir().taskScheduler().scheduleDelayedTask(m_timeout*1000000, TaskDataArrivalTimeout, this);\n\t}\t\n}\nrun onNewSession callback, before onNewBuffer\/* ---------------------------------------------------------------------------\n** This software is in the public domain, furnished \"as is\", without technical\n** support, and with no warranty, express or implied, as to its usefulness for\n** any purpose.\n**\n** rtspconnectionclient.cpp\n** \n** Interface to an RTSP client connection\n** \n** -------------------------------------------------------------------------*\/\n\n\n#include \"rtspconnectionclient.h\"\n\nRTSPConnection::SessionSink::SessionSink(UsageEnvironment& env, Callback* callback) \n\t: MediaSink(env)\n\t, m_buffer(NULL)\n\t, m_bufferSize(0)\n\t, m_callback(callback) \n\t, m_markerSize(0)\n{\n\tallocate(1024*1024);\n}\n\nRTSPConnection::SessionSink::~SessionSink()\n{\n\tdelete [] m_buffer;\n}\n\nvoid RTSPConnection::SessionSink::allocate(ssize_t bufferSize)\n{\n\tm_bufferSize = bufferSize;\n\tm_buffer = new u_int8_t[m_bufferSize];\n\tif (m_callback)\n\t{\n\t\tm_markerSize = m_callback->onNewBuffer(m_buffer, m_bufferSize);\n\t\tenvir() << \"markerSize:\" << (int)m_markerSize << \"\\n\";\n\t}\n}\n\n\nvoid RTSPConnection::SessionSink::afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds)\n{\n\tif (numTruncatedBytes != 0)\n\t{\n\t\tdelete [] m_buffer;\n\t\tenvir() << \"buffer too small \" << (int)m_bufferSize << \" allocate bigger one\\n\";\n\t\tallocate(m_bufferSize*2);\n\t}\n\telse if (m_callback)\n\t{\n\t\tif (!m_callback->onData(this->name(), m_buffer, frameSize+m_markerSize, presentationTime))\n\t\t{\n\t\t\tenvir() << \"NOTIFY failed\\n\";\n\t\t}\n\t}\n\tthis->continuePlaying();\n}\n\nBoolean RTSPConnection::SessionSink::continuePlaying()\n{\n\tBoolean ret = False;\n\tif (source() != NULL)\n\t{\n\t\tsource()->getNextFrame(m_buffer+m_markerSize, m_bufferSize-m_markerSize,\n\t\t\t\tafterGettingFrame, this,\n\t\t\t\tonSourceClosure, this);\n\t\tret = True;\n\t}\n\treturn ret;\t\n}\n\n\nRTSPConnection::RTSPConnection(Environment& env, Callback* callback, const char* rtspURL, int timeout, bool rtpovertcp, int verbosityLevel) \n\t\t\t\t: m_startCallbackTask(NULL)\n\t\t\t\t, m_env(env)\n\t\t\t\t, m_callback(callback)\n\t\t\t\t, m_url(rtspURL)\n\t\t\t\t, m_timeout(timeout)\n\t\t\t\t, m_rtpovertcp(rtpovertcp)\n\t\t\t\t, m_verbosity(verbosityLevel)\n\t\t\t\t, m_rtspClient(NULL)\n{\n\tthis->start();\n}\n\nvoid RTSPConnection::start(unsigned int delay)\n{\n\tm_startCallbackTask = m_env.taskScheduler().scheduleDelayedTask(delay*1000000, TaskstartCallback, this);\n}\t\n\nvoid RTSPConnection::TaskstartCallback() \n{\n\tif (m_rtspClient)\n\t{\n\t\t\n\t\tMedium::close(m_rtspClient);\n\t}\n\t\n\tm_rtspClient = new RTSPClientConnection(*this, m_env, m_callback, m_url.c_str(), m_timeout, m_rtpovertcp, m_verbosity);\t\n}\n\nRTSPConnection::~RTSPConnection()\n{\n\tm_env.taskScheduler().unscheduleDelayedTask(m_startCallbackTask);\n\tMedium::close(m_rtspClient);\n}\n\n\t\t\nRTSPConnection::RTSPClientConnection::RTSPClientConnection(RTSPConnection& connection, Environment& env, Callback* callback, const char* rtspURL, int timeout, bool rtpovertcp, int verbosityLevel) \n\t\t\t\t: RTSPClientConstrutor(env, rtspURL, verbosityLevel, NULL, 0)\n\t\t\t\t, m_connection(connection)\n\t\t\t\t, m_timeout(timeout)\n\t\t\t\t, m_rtpovertcp(rtpovertcp)\n\t\t\t\t, m_session(NULL)\n\t\t\t\t, m_subSessionIter(NULL)\n\t\t\t\t, m_callback(callback)\n\t\t\t\t, m_nbPacket(0)\n{\n\t\/\/ start tasks\n\tm_ConnectionTimeoutTask = envir().taskScheduler().scheduleDelayedTask(m_timeout*1000000, TaskConnectionTimeout, this);\n\t\n\t\/\/ initiate connection process\n\tthis->sendNextCommand();\n}\n\nRTSPConnection::RTSPClientConnection::~RTSPClientConnection()\n{\n\tenvir().taskScheduler().unscheduleDelayedTask(m_ConnectionTimeoutTask);\n\tenvir().taskScheduler().unscheduleDelayedTask(m_DataArrivalTimeoutTask);\n\t\n\tdelete m_subSessionIter;\n\t\n\t\/\/ free subsession\n\tif (m_session != NULL) \n\t{\n\t\tMediaSubsessionIterator iter(*m_session);\n\t\tMediaSubsession* subsession;\n\t\twhile ((subsession = iter.next()) != NULL) \n\t\t{\n\t\t\tif (subsession->sink) \n\t\t\t{\n\t\t\t\tenvir() << \"Close session: \" << subsession->mediumName() << \"\/\" << subsession->codecName() << \"\\n\";\n\t\t\t\tMedium::close(subsession->sink);\n\t\t\t\tsubsession->sink = NULL;\n\t\t\t}\n\t\t}\t\n\t\tMedium::close(m_session);\n\t}\n}\n\t\t\nvoid RTSPConnection::RTSPClientConnection::sendNextCommand() \n{\n\tif (m_subSessionIter == NULL)\n\t{\n\t\t\/\/ no SDP, send DESCRIBE\n\t\tthis->sendDescribeCommand(continueAfterDESCRIBE); \n\t}\n\telse\n\t{\n\t\tm_subSession = m_subSessionIter->next();\n\t\tif (m_subSession != NULL) \n\t\t{\n\t\t\t\/\/ still subsession to SETUP\n\t\t\tif (!m_subSession->initiate()) \n\t\t\t{\n\t\t\t\tenvir() << \"Failed to initiate \" << m_subSession->mediumName() << \"\/\" << m_subSession->codecName() << \" subsession: \" << envir().getResultMsg() << \"\\n\";\n\t\t\t\tthis->sendNextCommand();\n\t\t\t} \n\t\t\telse \n\t\t\t{\n\t\t\t\tif (fVerbosityLevel > 1) \n\t\t\t\t{\t\t\t\t\n\t\t\t\t\tenvir() << \"Initiated \" << m_subSession->mediumName() << \"\/\" << m_subSession->codecName() << \" subsession\" << \"\\n\";\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis->sendSetupCommand(*m_subSession, continueAfterSETUP, false, m_rtpovertcp);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ no more subsession to SETUP, send PLAY\n\t\t\tthis->sendPlayCommand(*m_session, continueAfterPLAY);\n\t\t}\n\t}\n}\n\nvoid RTSPConnection::RTSPClientConnection::continueAfterDESCRIBE(int resultCode, char* resultString)\n{\n\tif (resultCode != 0) \n\t{\n\t\tenvir() << \"Failed to DESCRIBE: \" << resultString << \"\\n\";\n\t\tm_callback->onError(m_connection, resultString);\n\t}\n\telse\n\t{\n\t\tif (fVerbosityLevel > 1) \n\t\t{\n\t\t\tenvir() << \"Got SDP:\\n\" << resultString << \"\\n\";\n\t\t}\n\t\tm_session = MediaSession::createNew(envir(), resultString);\n\t\tm_subSessionIter = new MediaSubsessionIterator(*m_session);\n\t\tthis->sendNextCommand(); \n\t}\n\tdelete[] resultString;\n}\n\nvoid RTSPConnection::RTSPClientConnection::continueAfterSETUP(int resultCode, char* resultString)\n{\n\tif (resultCode != 0) \n\t{\n\t\tenvir() << \"Failed to SETUP: \" << resultString << \"\\n\";\n\t\tm_callback->onError(m_connection, resultString);\n\t}\n\telse\n\t{\t\t\t\t\n\t\tif (m_callback->onNewSession(m_subSession->sink->name(), m_subSession->mediumName(), m_subSession->codecName(), m_subSession->savedSDPLines()))\n\t\t{\n\t\t\tenvir() << \"Created a data sink for the \\\"\" << m_subSession->mediumName() << \"\/\" << m_subSession->codecName() << \"\\\" subsession\" << \"\\n\";\n\t\t\tm_subSession->sink = SessionSink::createNew(envir(), m_callback);\n\t\t\tif (m_subSession->sink == NULL) \n\t\t\t{\n\t\t\t\tenvir() << \"Failed to create a data sink for \" << m_subSession->mediumName() << \"\/\" << m_subSession->codecName() << \" subsession: \" << envir().getResultMsg() << \"\\n\";\n\t\t\t} else {\n\t\t\t\tm_subSession->sink->startPlaying(*(m_subSession->readSource()), NULL, NULL);\n\t\t\t}\n\t\t}\n\t}\n\tdelete[] resultString;\n\tthis->sendNextCommand(); \n}\t\n\nvoid RTSPConnection::RTSPClientConnection::continueAfterPLAY(int resultCode, char* resultString)\n{\n\tif (resultCode != 0) \n\t{\n\t\tenvir() << \"Failed to PLAY: \" << resultString << \"\\n\";\n\t\tm_callback->onError(m_connection, resultString);\n\t}\n\telse\n\t{\n\t\tif (fVerbosityLevel > 1) \n\t\t{\n\t\t\tenvir() << \"PLAY OK\" << \"\\n\";\n\t\t}\n\t\tm_DataArrivalTimeoutTask = envir().taskScheduler().scheduleDelayedTask(m_timeout*1000000, TaskDataArrivalTimeout, this);\n\n\t}\n\tenvir().taskScheduler().unscheduleDelayedTask(m_ConnectionTimeoutTask);\n\tdelete[] resultString;\n}\n\nvoid RTSPConnection::RTSPClientConnection::TaskConnectionTimeout()\n{\n\tm_callback->onConnectionTimeout(m_connection);\n}\n\t\t\nvoid RTSPConnection::RTSPClientConnection::TaskDataArrivalTimeout()\n{\n\tunsigned int newTotNumPacketsReceived = 0;\n\n\tMediaSubsessionIterator iter(*m_session);\n\tMediaSubsession* subsession;\n\twhile ((subsession = iter.next()) != NULL) \n\t{\n\t\tRTPSource* src = subsession->rtpSource();\n\t\tif (src != NULL) \n\t\t{\n\t\t\tnewTotNumPacketsReceived += src->receptionStatsDB().totNumPacketsReceived();\n\t\t}\n\t}\n\t\n\tif (newTotNumPacketsReceived == m_nbPacket) \n\t{\n\t\tm_callback->onDataTimeout(m_connection);\n\t} \n\telse \n\t{\n\t\tm_nbPacket = newTotNumPacketsReceived;\n\t\tm_DataArrivalTimeoutTask = envir().taskScheduler().scheduleDelayedTask(m_timeout*1000000, TaskDataArrivalTimeout, this);\n\t}\t\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ webcam.cpp --a part of libdecodeqr\n\/\/\n\/\/ Copyright(C) 2007 NISHI Takao \n\/\/ JMA (Japan Medical Association)\n\/\/ NaCl (Network Applied Communication Laboratory Ltd.)\n\/\/\n\/\/ This is free software with ABSOLUTELY NO WARRANTY.\n\/\/ You can redistribute and\/or modify it under the terms of LGPL.\n\/\/\n\/\/ $Id$\n\/\/\n#include \n#include \n#include \"..\/..\/libdecodeqr\/decodeqr.h\"\n\nint main(int argc,char *argv[])\n{\n \/\/\n \/\/ start camera\n \/\/\n CvCapture *capture=cvCaptureFromCAM(0);\n if(!capture)\n return(-1);\n\n \/\/\n \/\/ initialize qr decoder\n \/\/\n QrDecoderHandle decoder=qr_decoder_open();\n printf(\"libdecodeqr version %s\\n\",qr_decoder_version());\n\n \n cvNamedWindow(\"src\",1);\n cvNamedWindow(\"bin\",1);\n\n puts(\"Hit [SPACE] key to grab, or any key to end.\");\n puts(\"\");\n\n \/\/\n \/\/ 1 shot grabing\n \/\/\n \/\/\n \/\/ allocate grabed buffer to decoder\n \/\/\n int key=-1;\n\n IplImage *camera=cvQueryFrame(capture);\n IplImage *src=NULL;\n if(camera){\n src=cvCloneImage(camera);\n qr_decoder_set_image_buffer(decoder,src);\n }\n else\n key=1;\n\n unsigned char *text=NULL;\n int text_size=0;\n\n while(key<=0){\n cvShowImage(\"src\",camera);\n key=cvWaitKey(150);\n\n \/\/\n \/\/ when [SPACE] key pressed, do decode.\n \/\/\n if(key==0x20&&!qr_decoder_is_busy(decoder)){\n key=-1;\n\n \/\/\n \/\/ if left-bottom origin (MS-Windows style) format,\n \/\/ it must be converted to left-top origin.\n \/\/\n if(camera->origin)\n cvConvertImage(camera,src,CV_CVTIMG_FLIP);\n else\n cvCopy(camera,src);\n\n \/\/\n \/\/ While decoding is a failure, decrease the\n \/\/ adaptive_th_size parameter.\n \/\/ Note that the adaptive_th_size must be odd.\n \/\/\n short sz,stat;\n for(sz=25,stat=0;\n (sz>=3)&&((stat&QR_IMAGEREADER_DECODED)==0);\n sz-=2)\n stat=qr_decoder_decode(decoder,sz);\n\n \/\/\n \/\/ for debug, show binarized image.\n \/\/\n cvShowImage(\"bin\",\n qr_decoder_get_binarized_image_buffer(decoder));\n printf(\"adaptive_th_size=%d, status=%04x\\n\",sz,stat);\n\n \/\/\n \/\/ on suceed decoding, print decoded text.\n \/\/\n QrCodeHeader header;\n if(qr_decoder_get_header(decoder,&header)){\n if(text_sizeorigin)\n cvConvertImage(src,src,CV_CVTIMG_FLIP);\n\n cvShowImage(\"src\",src);\n\n \/\/\n \/\/ wait 1500msec.\n \/\/\n key=cvWaitKey(1500);\n }\n }\n\n camera=cvQueryFrame(capture);\n if(!camera)\n break;\n }\n \n if(text)\n delete text;\n\n qr_decoder_close(decoder);\n if(src)\n cvReleaseImage(&src);\n cvReleaseCapture(&capture);\n\n return(0);\n}\nsrc\/sample\/webcam\/webcam.cpp: * dumps core bug fixed?\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ webcam.cpp --a part of libdecodeqr\n\/\/\n\/\/ Copyright(C) 2007 NISHI Takao \n\/\/ JMA (Japan Medical Association)\n\/\/ NaCl (Network Applied Communication Laboratory Ltd.)\n\/\/\n\/\/ This is free software with ABSOLUTELY NO WARRANTY.\n\/\/ You can redistribute and\/or modify it under the terms of LGPL.\n\/\/\n\/\/ $Id$\n\/\/\n#include \n#include \n#include \"..\/..\/libdecodeqr\/decodeqr.h\"\n\nint main(int argc,char *argv[])\n{\n \/\/\n \/\/ start camera\n \/\/\n CvCapture *capture=cvCaptureFromCAM(0);\n if(!capture)\n return(-1);\n\n \/\/\n \/\/ initialize qr decoder\n \/\/\n QrDecoderHandle decoder=qr_decoder_open();\n printf(\"libdecodeqr version %s\\n\",qr_decoder_version());\n\n \n cvNamedWindow(\"src\",1);\n cvNamedWindow(\"bin\",1);\n\n puts(\"Hit [SPACE] key to grab, or any key to end.\");\n puts(\"\");\n\n \/\/\n \/\/ 1 shot grabing\n \/\/\n \/\/\n \/\/ allocate grabed buffer to decoder\n \/\/\n int key=-1;\n\n IplImage *camera=cvQueryFrame(capture);\n IplImage *src=NULL,*bin=NULL;\n if(camera){\n src=cvCloneImage(camera);\n qr_decoder_set_image_buffer(decoder,src);\n }\n else\n key=1;\n\n unsigned char *text=NULL;\n int text_size=0;\n\n while(key<=0){\n cvShowImage(\"src\",camera);\n key=cvWaitKey(150);\n\n \/\/\n \/\/ when [SPACE] key pressed, do decode.\n \/\/\n if(key==0x20&&!qr_decoder_is_busy(decoder)){\n key=-1;\n\n \/\/\n \/\/ if left-bottom origin (MS-Windows style) format,\n \/\/ it must be converted to left-top origin.\n \/\/\n if(camera->origin)\n cvConvertImage(camera,src,CV_CVTIMG_FLIP);\n else\n cvCopy(camera,src);\n\n \/\/\n \/\/ While decoding is a failure, decrease the\n \/\/ adaptive_th_size parameter.\n \/\/ Note that the adaptive_th_size must be odd.\n \/\/\n short sz,stat;\n for(sz=25,stat=0;\n (sz>=3)&&((stat&QR_IMAGEREADER_DECODED)==0);\n sz-=2)\n stat=qr_decoder_decode(decoder,sz);\n\n \/\/\n \/\/ for debug, show binarized image.\n \/\/\n if(bin)\n cvReleaseImage(&bin);\n bin=cvCloneImage(qr_decoder_get_binarized_image_buffer(decoder));\n cvShowImage(\"bin\",bin);\n printf(\"adaptive_th_size=%d, status=%04x\\n\",sz,stat);\n\n \/\/\n \/\/ on suceed decoding, print decoded text.\n \/\/\n QrCodeHeader header;\n if(qr_decoder_get_header(decoder,&header)){\n if(text_sizeorigin)\n cvConvertImage(src,src,CV_CVTIMG_FLIP);\n\n cvShowImage(\"src\",src);\n\n \/\/\n \/\/ wait 1500msec.\n \/\/\n key=cvWaitKey(1500);\n }\n }\n\n camera=cvQueryFrame(capture);\n if(!camera)\n break;\n }\n \n if(text)\n delete text;\n\n qr_decoder_close(decoder);\n if(bin)\n cvReleaseImage(&bin);\n if(src)\n cvReleaseImage(&src);\n \n cvReleaseCapture(&capture);\n\n return(0);\n}\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2013, Project OSRM, Dennis Luxen, others\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"..\/Util\/GitDescription.h\"\n#include \"..\/Util\/OSRMException.h\"\n#include \"..\/Util\/SimpleLogger.h\"\n#include \"..\/Util\/TimingUtil.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#ifdef __linux__\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n\nconst unsigned number_of_elements = 268435456;\n\nstruct Statistics\n{\n double min, max, med, mean, dev;\n};\n\nvoid RunStatistics(std::vector &timings_vector, Statistics &stats)\n{\n std::sort(timings_vector.begin(), timings_vector.end());\n stats.min = timings_vector.front();\n stats.max = timings_vector.back();\n stats.med = timings_vector[timings_vector.size() \/ 2];\n double primary_sum = std::accumulate(timings_vector.begin(), timings_vector.end(), 0.0);\n stats.mean = primary_sum \/ timings_vector.size();\n\n double primary_sq_sum = std::inner_product(\n timings_vector.begin(), timings_vector.end(), timings_vector.begin(), 0.0);\n stats.dev = std::sqrt(primary_sq_sum \/ timings_vector.size() - (stats.mean * stats.mean));\n}\n\nint main(int argc, char *argv[])\n{\n LogPolicy::GetInstance().Unmute();\n\n SimpleLogger().Write() << \"starting up engines, \" << g_GIT_DESCRIPTION << \", \"\n << \"compiled at \" << __DATE__ << \", \" __TIME__;\n\n#ifdef __FreeBSD__\n SimpleLogger().Write() << \"Not supported on FreeBSD\";\n return 0;\n#endif\n\n if (1 == argc)\n {\n SimpleLogger().Write(logWARNING) << \"usage: \" << argv[0] << \" \/path\/on\/device\";\n return -1;\n }\n\n boost::filesystem::path test_path = boost::filesystem::path(argv[1]);\n test_path \/= \"osrm.tst\";\n SimpleLogger().Write(logDEBUG) << \"temporary file: \" << test_path.string();\n\n try\n {\n \/\/ create files for testing\n if (2 == argc)\n {\n \/\/ create file to test\n if (boost::filesystem::exists(test_path))\n {\n throw OSRMException(\"Data file already exists\");\n }\n\n int *random_array = new int[number_of_elements];\n std::generate(random_array, random_array + number_of_elements, std::rand);\n#ifdef __APPLE__\n FILE *fd = fopen(test_path.string().c_str(), \"w\");\n fcntl(fileno(fd), F_NOCACHE, 1);\n fcntl(fileno(fd), F_RDAHEAD, 0);\n TIMER_START(write_1gb);\n write(fileno(fd), (char *)random_array, number_of_elements * sizeof(unsigned));\n TIMER_STOP(write_1gb);\n fclose(fd);\n#endif\n#ifdef __linux__\n int f =\n open(test_path.string().c_str(), O_CREAT | O_TRUNC | O_WRONLY | O_SYNC, S_IRWXU);\n if (-1 == f)\n {\n throw OSRMException(\"Could not open random data file\");\n }\n TIMER_START(write_1gb);\n int ret = write(f, random_array, number_of_elements * sizeof(unsigned));\n if (0 > ret)\n {\n throw OSRMException(\"could not write random data file\");\n }\n TIMER_STOP(write_1gb);\n close(f);\n#endif\n delete[] random_array;\n SimpleLogger().Write(logDEBUG) << \"writing raw 1GB took \" << TIMER_SEC(write_1gb)\n << \"s\";\n SimpleLogger().Write() << \"raw write performance: \" << std::setprecision(5)\n << std::fixed << 1024 * 1024 \/ TIMER_SEC(write_1gb)\n << \"MB\/sec\";\n\n SimpleLogger().Write(logDEBUG)\n << \"finished creation of random data. Flush disk cache now!\";\n }\n else\n {\n \/\/ Run Non-Cached I\/O benchmarks\n if (!boost::filesystem::exists(test_path))\n {\n throw OSRMException(\"data file does not exist\");\n }\n\n \/\/ volatiles do not get optimized\n Statistics stats;\n\n#ifdef __APPLE__\n volatile unsigned single_block[1024];\n char *raw_array = new char[number_of_elements * sizeof(unsigned)];\n FILE *fd = fopen(test_path.string().c_str(), \"r\");\n fcntl(fileno(fd), F_NOCACHE, 1);\n fcntl(fileno(fd), F_RDAHEAD, 0);\n#endif\n#ifdef __linux__\n char *single_block = (char *)memalign(512, 1024 * sizeof(unsigned));\n\n int f = open(test_path.string().c_str(), O_RDONLY | O_DIRECT | O_SYNC);\n if (-1 == f)\n {\n SimpleLogger().Write(logDEBUG) << \"opened, error: \" << strerror(errno);\n return -1;\n }\n char *raw_array = (char *)memalign(512, number_of_elements * sizeof(unsigned));\n#endif\n TIMER_START(read_1gb);\n#ifdef __APPLE__\n read(fileno(fd), raw_array, number_of_elements * sizeof(unsigned));\n close(fileno(fd));\n fd = fopen(test_path.string().c_str(), \"r\");\n#endif\n#ifdef __linux__\n int ret = read(f, raw_array, number_of_elements * sizeof(unsigned));\n SimpleLogger().Write(logDEBUG) << \"read \" << ret\n << \" bytes, error: \" << strerror(errno);\n close(f);\n f = open(test_path.string().c_str(), O_RDONLY | O_DIRECT | O_SYNC);\n SimpleLogger().Write(logDEBUG) << \"opened, error: \" << strerror(errno);\n#endif\n TIMER_STOP(read_1gb);\n\n SimpleLogger().Write(logDEBUG) << \"reading raw 1GB took \" << TIMER_SEC(read_1gb)\n << \"s\";\n SimpleLogger().Write() << \"raw read performance: \" << std::setprecision(5) << std::fixed\n << 1024 * 1024 \/ TIMER_SEC(read_1gb) << \"MB\/sec\";\n\n std::vector timing_results_raw_random;\n SimpleLogger().Write(logDEBUG) << \"running 1000 random I\/Os of 4KB\";\n\n#ifdef __APPLE__\n fseek(fd, 0, SEEK_SET);\n#endif\n#ifdef __linux__\n lseek(f, 0, SEEK_SET);\n#endif\n \/\/ make 1000 random access, time each I\/O seperately\n unsigned number_of_blocks = (number_of_elements * sizeof(unsigned) - 1) \/ 4096;\n for (unsigned i = 0; i < 1000; ++i)\n {\n unsigned block_to_read = std::rand() % number_of_blocks;\n off_t current_offset = block_to_read * 4096;\n TIMER_START(random_access);\n#ifdef __APPLE__\n int ret1 = fseek(fd, current_offset, SEEK_SET);\n int ret2 = read(fileno(fd), (char *)&single_block[0], 4096);\n#endif\n\n#ifdef __FreeBSD__\n int ret1 = 0;\n int ret2 = 0;\n#endif\n\n#ifdef __linux__\n int ret1 = lseek(f, current_offset, SEEK_SET);\n int ret2 = read(f, (char *)single_block, 4096);\n#endif\n TIMER_STOP(random_access);\n if (((off_t) - 1) == ret1)\n {\n SimpleLogger().Write(logWARNING) << \"offset: \" << current_offset;\n SimpleLogger().Write(logWARNING) << \"seek error \" << strerror(errno);\n throw OSRMException(\"seek error\");\n }\n if (-1 == ret2)\n {\n SimpleLogger().Write(logWARNING) << \"offset: \" << current_offset;\n SimpleLogger().Write(logWARNING) << \"read error \" << strerror(errno);\n throw OSRMException(\"read error\");\n }\n timing_results_raw_random.push_back(TIMER_SEC(random_access));\n }\n\n \/\/ Do statistics\n SimpleLogger().Write(logDEBUG) << \"running raw random I\/O statistics\";\n std::ofstream random_csv(\"random.csv\", std::ios::trunc);\n for (unsigned i = 0; i < timing_results_raw_random.size(); ++i)\n {\n random_csv << i << \", \" << timing_results_raw_random[i] << std::endl;\n }\n random_csv.close();\n RunStatistics(timing_results_raw_random, stats);\n\n SimpleLogger().Write() << \"raw random I\/O: \" << std::setprecision(5) << std::fixed\n << \"min: \" << stats.min << \"ms, \"\n << \"mean: \" << stats.mean << \"ms, \"\n << \"med: \" << stats.med << \"ms, \"\n << \"max: \" << stats.max << \"ms, \"\n << \"dev: \" << stats.dev << \"ms\";\n\n std::vector timing_results_raw_seq;\n#ifdef __APPLE__\n fseek(fd, 0, SEEK_SET);\n#endif\n#ifdef __linux__\n lseek(f, 0, SEEK_SET);\n#endif\n\n \/\/ read every 100th block\n for (unsigned i = 0; i < 1000; ++i)\n {\n off_t current_offset = i * 4096;\n TIMER_START(read_every_100);\n#ifdef __APPLE__\n int ret1 = fseek(fd, current_offset, SEEK_SET);\n int ret2 = read(fileno(fd), (char *)&single_block, 4096);\n#endif\n\n#ifdef __FreeBSD__\n int ret1 = 0;\n int ret2 = 0;\n#endif\n\n#ifdef __linux__\n int ret1 = lseek(f, current_offset, SEEK_SET);\n\n int ret2 = read(f, (char *)single_block, 4096);\n#endif\n TIMER_STOP(read_every_100);\n if (((off_t) - 1) == ret1)\n {\n SimpleLogger().Write(logWARNING) << \"offset: \" << current_offset;\n SimpleLogger().Write(logWARNING) << \"seek error \" << strerror(errno);\n throw OSRMException(\"seek error\");\n }\n if (-1 == ret2)\n {\n SimpleLogger().Write(logWARNING) << \"offset: \" << current_offset;\n SimpleLogger().Write(logWARNING) << \"read error \" << strerror(errno);\n throw OSRMException(\"read error\");\n }\n timing_results_raw_seq.push_back(TIMER_SEC(read_every_100));\n }\n#ifdef __APPLE__\n fclose(fd);\n \/\/ free(single_element);\n free(raw_array);\n\/\/ free(single_block);\n#endif\n#ifdef __linux__\n close(f);\n#endif\n \/\/ Do statistics\n SimpleLogger().Write(logDEBUG) << \"running sequential I\/O statistics\";\n \/\/ print simple statistics: min, max, median, variance\n std::ofstream seq_csv(\"sequential.csv\", std::ios::trunc);\n for (unsigned i = 0; i < timing_results_raw_seq.size(); ++i)\n {\n seq_csv << i << \", \" << timing_results_raw_seq[i] << std::endl;\n }\n seq_csv.close();\n RunStatistics(timing_results_raw_seq, stats);\n SimpleLogger().Write() << \"raw sequential I\/O: \" << std::setprecision(5) << std::fixed\n << \"min: \" << stats.min << \"ms, \"\n << \"mean: \" << stats.mean << \"ms, \"\n << \"med: \" << stats.med << \"ms, \"\n << \"max: \" << stats.max << \"ms, \"\n << \"dev: \" << stats.dev << \"ms\";\n\n if (boost::filesystem::exists(test_path))\n {\n boost::filesystem::remove(test_path);\n SimpleLogger().Write(logDEBUG) << \"removing temporary files\";\n }\n }\n }\n catch (const std::exception &e)\n {\n SimpleLogger().Write(logWARNING) << \"caught exception: \" << e.what();\n SimpleLogger().Write(logWARNING) << \"cleaning up, and exiting\";\n if (boost::filesystem::exists(test_path))\n {\n boost::filesystem::remove(test_path);\n SimpleLogger().Write(logWARNING) << \"removing temporary files\";\n }\n return -1;\n }\n return 0;\n}\ndisable io-benchmark on Windows\/*\n\nCopyright (c) 2013, Project OSRM, Dennis Luxen, others\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"..\/Util\/GitDescription.h\"\n#include \"..\/Util\/OSRMException.h\"\n#include \"..\/Util\/SimpleLogger.h\"\n#include \"..\/Util\/TimingUtil.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#ifdef __linux__\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n\nconst unsigned number_of_elements = 268435456;\n\nstruct Statistics\n{\n double min, max, med, mean, dev;\n};\n\nvoid RunStatistics(std::vector &timings_vector, Statistics &stats)\n{\n std::sort(timings_vector.begin(), timings_vector.end());\n stats.min = timings_vector.front();\n stats.max = timings_vector.back();\n stats.med = timings_vector[timings_vector.size() \/ 2];\n double primary_sum = std::accumulate(timings_vector.begin(), timings_vector.end(), 0.0);\n stats.mean = primary_sum \/ timings_vector.size();\n\n double primary_sq_sum = std::inner_product(\n timings_vector.begin(), timings_vector.end(), timings_vector.begin(), 0.0);\n stats.dev = std::sqrt(primary_sq_sum \/ timings_vector.size() - (stats.mean * stats.mean));\n}\n\nint main(int argc, char *argv[])\n{\n LogPolicy::GetInstance().Unmute();\n\n SimpleLogger().Write() << \"starting up engines, \" << g_GIT_DESCRIPTION << \", \"\n << \"compiled at \" << __DATE__ << \", \" __TIME__;\n\n#ifdef __FreeBSD__\n SimpleLogger().Write() << \"Not supported on FreeBSD\";\n return 0;\n#endif\n#ifdef WIN32\n SimpleLogger().Write() << \"Not supported on Windows\";\n return 0;\n#else\n\n\n if (1 == argc)\n {\n SimpleLogger().Write(logWARNING) << \"usage: \" << argv[0] << \" \/path\/on\/device\";\n return -1;\n }\n\n boost::filesystem::path test_path = boost::filesystem::path(argv[1]);\n test_path \/= \"osrm.tst\";\n SimpleLogger().Write(logDEBUG) << \"temporary file: \" << test_path.string();\n\n try\n {\n \/\/ create files for testing\n if (2 == argc)\n {\n \/\/ create file to test\n if (boost::filesystem::exists(test_path))\n {\n throw OSRMException(\"Data file already exists\");\n }\n\n int *random_array = new int[number_of_elements];\n std::generate(random_array, random_array + number_of_elements, std::rand);\n#ifdef __APPLE__\n FILE *fd = fopen(test_path.string().c_str(), \"w\");\n fcntl(fileno(fd), F_NOCACHE, 1);\n fcntl(fileno(fd), F_RDAHEAD, 0);\n TIMER_START(write_1gb);\n write(fileno(fd), (char *)random_array, number_of_elements * sizeof(unsigned));\n TIMER_STOP(write_1gb);\n fclose(fd);\n#endif\n#ifdef __linux__\n int f =\n open(test_path.string().c_str(), O_CREAT | O_TRUNC | O_WRONLY | O_SYNC, S_IRWXU);\n if (-1 == f)\n {\n throw OSRMException(\"Could not open random data file\");\n }\n TIMER_START(write_1gb);\n int ret = write(f, random_array, number_of_elements * sizeof(unsigned));\n if (0 > ret)\n {\n throw OSRMException(\"could not write random data file\");\n }\n TIMER_STOP(write_1gb);\n close(f);\n#endif\n delete[] random_array;\n SimpleLogger().Write(logDEBUG) << \"writing raw 1GB took \" << TIMER_SEC(write_1gb)\n << \"s\";\n SimpleLogger().Write() << \"raw write performance: \" << std::setprecision(5)\n << std::fixed << 1024 * 1024 \/ TIMER_SEC(write_1gb)\n << \"MB\/sec\";\n\n SimpleLogger().Write(logDEBUG)\n << \"finished creation of random data. Flush disk cache now!\";\n }\n else\n {\n \/\/ Run Non-Cached I\/O benchmarks\n if (!boost::filesystem::exists(test_path))\n {\n throw OSRMException(\"data file does not exist\");\n }\n\n \/\/ volatiles do not get optimized\n Statistics stats;\n\n#ifdef __APPLE__\n volatile unsigned single_block[1024];\n char *raw_array = new char[number_of_elements * sizeof(unsigned)];\n FILE *fd = fopen(test_path.string().c_str(), \"r\");\n fcntl(fileno(fd), F_NOCACHE, 1);\n fcntl(fileno(fd), F_RDAHEAD, 0);\n#endif\n#ifdef __linux__\n char *single_block = (char *)memalign(512, 1024 * sizeof(unsigned));\n\n int f = open(test_path.string().c_str(), O_RDONLY | O_DIRECT | O_SYNC);\n if (-1 == f)\n {\n SimpleLogger().Write(logDEBUG) << \"opened, error: \" << strerror(errno);\n return -1;\n }\n char *raw_array = (char *)memalign(512, number_of_elements * sizeof(unsigned));\n#endif\n TIMER_START(read_1gb);\n#ifdef __APPLE__\n read(fileno(fd), raw_array, number_of_elements * sizeof(unsigned));\n close(fileno(fd));\n fd = fopen(test_path.string().c_str(), \"r\");\n#endif\n#ifdef __linux__\n int ret = read(f, raw_array, number_of_elements * sizeof(unsigned));\n SimpleLogger().Write(logDEBUG) << \"read \" << ret\n << \" bytes, error: \" << strerror(errno);\n close(f);\n f = open(test_path.string().c_str(), O_RDONLY | O_DIRECT | O_SYNC);\n SimpleLogger().Write(logDEBUG) << \"opened, error: \" << strerror(errno);\n#endif\n TIMER_STOP(read_1gb);\n\n SimpleLogger().Write(logDEBUG) << \"reading raw 1GB took \" << TIMER_SEC(read_1gb)\n << \"s\";\n SimpleLogger().Write() << \"raw read performance: \" << std::setprecision(5) << std::fixed\n << 1024 * 1024 \/ TIMER_SEC(read_1gb) << \"MB\/sec\";\n\n std::vector timing_results_raw_random;\n SimpleLogger().Write(logDEBUG) << \"running 1000 random I\/Os of 4KB\";\n\n#ifdef __APPLE__\n fseek(fd, 0, SEEK_SET);\n#endif\n#ifdef __linux__\n lseek(f, 0, SEEK_SET);\n#endif\n \/\/ make 1000 random access, time each I\/O seperately\n unsigned number_of_blocks = (number_of_elements * sizeof(unsigned) - 1) \/ 4096;\n for (unsigned i = 0; i < 1000; ++i)\n {\n unsigned block_to_read = std::rand() % number_of_blocks;\n off_t current_offset = block_to_read * 4096;\n TIMER_START(random_access);\n#ifdef __APPLE__\n int ret1 = fseek(fd, current_offset, SEEK_SET);\n int ret2 = read(fileno(fd), (char *)&single_block[0], 4096);\n#endif\n\n#ifdef __FreeBSD__\n int ret1 = 0;\n int ret2 = 0;\n#endif\n\n#ifdef __linux__\n int ret1 = lseek(f, current_offset, SEEK_SET);\n int ret2 = read(f, (char *)single_block, 4096);\n#endif\n TIMER_STOP(random_access);\n if (((off_t) - 1) == ret1)\n {\n SimpleLogger().Write(logWARNING) << \"offset: \" << current_offset;\n SimpleLogger().Write(logWARNING) << \"seek error \" << strerror(errno);\n throw OSRMException(\"seek error\");\n }\n if (-1 == ret2)\n {\n SimpleLogger().Write(logWARNING) << \"offset: \" << current_offset;\n SimpleLogger().Write(logWARNING) << \"read error \" << strerror(errno);\n throw OSRMException(\"read error\");\n }\n timing_results_raw_random.push_back(TIMER_SEC(random_access));\n }\n\n \/\/ Do statistics\n SimpleLogger().Write(logDEBUG) << \"running raw random I\/O statistics\";\n std::ofstream random_csv(\"random.csv\", std::ios::trunc);\n for (unsigned i = 0; i < timing_results_raw_random.size(); ++i)\n {\n random_csv << i << \", \" << timing_results_raw_random[i] << std::endl;\n }\n random_csv.close();\n RunStatistics(timing_results_raw_random, stats);\n\n SimpleLogger().Write() << \"raw random I\/O: \" << std::setprecision(5) << std::fixed\n << \"min: \" << stats.min << \"ms, \"\n << \"mean: \" << stats.mean << \"ms, \"\n << \"med: \" << stats.med << \"ms, \"\n << \"max: \" << stats.max << \"ms, \"\n << \"dev: \" << stats.dev << \"ms\";\n\n std::vector timing_results_raw_seq;\n#ifdef __APPLE__\n fseek(fd, 0, SEEK_SET);\n#endif\n#ifdef __linux__\n lseek(f, 0, SEEK_SET);\n#endif\n\n \/\/ read every 100th block\n for (unsigned i = 0; i < 1000; ++i)\n {\n off_t current_offset = i * 4096;\n TIMER_START(read_every_100);\n#ifdef __APPLE__\n int ret1 = fseek(fd, current_offset, SEEK_SET);\n int ret2 = read(fileno(fd), (char *)&single_block, 4096);\n#endif\n\n#ifdef __FreeBSD__\n int ret1 = 0;\n int ret2 = 0;\n#endif\n\n#ifdef __linux__\n int ret1 = lseek(f, current_offset, SEEK_SET);\n\n int ret2 = read(f, (char *)single_block, 4096);\n#endif\n TIMER_STOP(read_every_100);\n if (((off_t) - 1) == ret1)\n {\n SimpleLogger().Write(logWARNING) << \"offset: \" << current_offset;\n SimpleLogger().Write(logWARNING) << \"seek error \" << strerror(errno);\n throw OSRMException(\"seek error\");\n }\n if (-1 == ret2)\n {\n SimpleLogger().Write(logWARNING) << \"offset: \" << current_offset;\n SimpleLogger().Write(logWARNING) << \"read error \" << strerror(errno);\n throw OSRMException(\"read error\");\n }\n timing_results_raw_seq.push_back(TIMER_SEC(read_every_100));\n }\n#ifdef __APPLE__\n fclose(fd);\n \/\/ free(single_element);\n free(raw_array);\n\/\/ free(single_block);\n#endif\n#ifdef __linux__\n close(f);\n#endif\n \/\/ Do statistics\n SimpleLogger().Write(logDEBUG) << \"running sequential I\/O statistics\";\n \/\/ print simple statistics: min, max, median, variance\n std::ofstream seq_csv(\"sequential.csv\", std::ios::trunc);\n for (unsigned i = 0; i < timing_results_raw_seq.size(); ++i)\n {\n seq_csv << i << \", \" << timing_results_raw_seq[i] << std::endl;\n }\n seq_csv.close();\n RunStatistics(timing_results_raw_seq, stats);\n SimpleLogger().Write() << \"raw sequential I\/O: \" << std::setprecision(5) << std::fixed\n << \"min: \" << stats.min << \"ms, \"\n << \"mean: \" << stats.mean << \"ms, \"\n << \"med: \" << stats.med << \"ms, \"\n << \"max: \" << stats.max << \"ms, \"\n << \"dev: \" << stats.dev << \"ms\";\n\n if (boost::filesystem::exists(test_path))\n {\n boost::filesystem::remove(test_path);\n SimpleLogger().Write(logDEBUG) << \"removing temporary files\";\n }\n }\n }\n catch (const std::exception &e)\n {\n SimpleLogger().Write(logWARNING) << \"caught exception: \" << e.what();\n SimpleLogger().Write(logWARNING) << \"cleaning up, and exiting\";\n if (boost::filesystem::exists(test_path))\n {\n boost::filesystem::remove(test_path);\n SimpleLogger().Write(logWARNING) << \"removing temporary files\";\n }\n return -1;\n }\n return 0;\n#endif\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkLog10ImageFilterAndAdaptorTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n#include \n#include \n#include \n#include \n#include \n\n\nint itkLog10ImageFilterAndAdaptorTest(int, char* [] ) \n{\n\n \/\/ Define the dimension of the images\n const unsigned int ImageDimension = 3;\n\n \/\/ Declare the types of the images\n typedef itk::Image InputImageType;\n typedef itk::Image OutputImageType;\n\n \n \n \/\/ Declare Iterator types apropriated for each image \n typedef itk::ImageRegionIteratorWithIndex<\n InputImageType> InputIteratorType;\n\n typedef itk::ImageRegionIteratorWithIndex<\n OutputImageType> OutputIteratorType;\n\n\n\n \/\/ Declare the type of the index to access images\n typedef itk::Index IndexType;\n\n \/\/ Declare the type of the size \n typedef itk::Size SizeType;\n\n \/\/ Declare the type of the Region\n typedef itk::ImageRegion RegionType;\n\n \/\/ Create two images\n InputImageType::Pointer inputImage = InputImageType::New();\n \n \/\/ Define their size, and start index\n SizeType size;\n size[0] = 2;\n size[1] = 2;\n size[2] = 2;\n\n IndexType start;\n start[0] = 0;\n start[1] = 0;\n start[2] = 0;\n\n RegionType region;\n region.SetIndex( start );\n region.SetSize( size );\n\n \/\/ Initialize Image A\n inputImage->SetLargestPossibleRegion( region );\n inputImage->SetBufferedRegion( region );\n inputImage->SetRequestedRegion( region );\n inputImage->Allocate();\n \/\/ Create one iterator for the Input Image (this is a light object)\n InputIteratorType it( inputImage, inputImage->GetBufferedRegion() );\n\n \/\/ Initialize the content of Image A\n const double value = vnl_math::pi \/ 6.0;\n std::cout << \"Content of the Input \" << std::endl;\n it.GoToBegin();\n while( !it.IsAtEnd() ) \n {\n it.Set( value );\n std::cout << it.Get() << std::endl;\n ++it;\n }\n\n \/\/ Declare the type for the Log10 filter\n typedef itk::Log10ImageFilter< InputImageType,\n OutputImageType > FilterType;\n \n\n \/\/ Create an ADD Filter \n FilterType::Pointer filter = FilterType::New();\n\n\n \/\/ Connect the input images\n filter->SetInput( inputImage ); \n\n \/\/ Get the Smart Pointer to the Filter Output \n OutputImageType::Pointer outputImage = filter->GetOutput();\n\n \n \/\/ Execute the filter\n filter->Update();\n filter->SetFunctor(filter->GetFunctor());\n\n \/\/ Create an iterator for going through the image output\n OutputIteratorType ot(outputImage, outputImage->GetRequestedRegion());\n \n \/\/ Check the content of the result image\n std::cout << \"Verification of the output \" << std::endl;\n const OutputImageType::PixelType epsilon = 1e-6;\n ot.GoToBegin();\n it.GoToBegin();\n while( !ot.IsAtEnd() ) \n {\n std::cout << ot.Get() << \" = \";\n std::cout << log10( it.Get() ) << std::endl; \n const InputImageType::PixelType input = it.Get();\n const OutputImageType::PixelType output = ot.Get();\n const OutputImageType::PixelType naturallog = log10(input);\n if( vcl_fabs( naturallog - output ) > epsilon )\n {\n std::cerr << \"Error in itkLog10ImageFilterTest \" << std::endl;\n std::cerr << \" log10( \" << input << \") = \" << naturallog << std::endl;\n std::cerr << \" differs from \" << output;\n std::cerr << \" by more than \" << epsilon << std::endl;\n return EXIT_FAILURE;\n }\n ++ot;\n ++it;\n }\n\n\n \/\/---------------------------------------\n \/\/ This section tests for Log10ImageAdaptor\n \/\/---------------------------------------\n\n typedef itk::Log10ImageAdaptor AdaptorType;\n\n AdaptorType::Pointer log10Adaptor = AdaptorType::New();\n\n log10Adaptor->SetImage( inputImage );\n\n typedef itk::SubtractImageFilter<\n OutputImageType,\n AdaptorType,\n OutputImageType > DiffFilterType;\n\n DiffFilterType::Pointer diffFilter = DiffFilterType::New();\n\n diffFilter->SetInput1( outputImage );\n diffFilter->SetInput2( log10Adaptor );\n\n diffFilter->Update();\n\n \/\/ Get the Smart Pointer to the Diff filter Output\n OutputImageType::Pointer diffImage = diffFilter->GetOutput();\n\n \/\/ Check the content of the diff image\n std::cout << \"Comparing the results with those of an Adaptor\" << std::endl;\n std::cout << \"Verification of the output \" << std::endl;\n\n \/\/ Create an iterator for going through the image output\n OutputIteratorType dt(diffImage, diffImage->GetRequestedRegion());\n \n dt.GoToBegin();\n while( !dt.IsAtEnd() ) \n {\n std::cout << dt.Get() << std::endl;\n const OutputImageType::PixelType diff = dt.Get();\n if( vcl_fabs( diff ) > epsilon )\n {\n std::cerr << \"Error in itkLog10ImageFilterTest \" << std::endl;\n std::cerr << \"Comparing results with Adaptors\" << std::endl;\n std::cerr << \" difference = \" << diff << std::endl;\n std::cerr << \" differs from 0 \";\n std::cerr << \" by more than \" << epsilon << std::endl;\n return EXIT_FAILURE;\n }\n ++dt;\n }\n\n \n return EXIT_SUCCESS;\n}\nCOMP: Replacing \"log10\" with \"vcl_log10\" in order to support Sun-CC and -stlport4.\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkLog10ImageFilterAndAdaptorTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \"itkImage.h\"\n#include \"itkLog10ImageFilter.h\"\n#include \"itkLog10ImageAdaptor.h\"\n#include \"itkImageRegionIteratorWithIndex.h\"\n#include \"itkSubtractImageFilter.h\"\n\n\nint itkLog10ImageFilterAndAdaptorTest(int, char* [] ) \n{\n\n \/\/ Define the dimension of the images\n const unsigned int ImageDimension = 3;\n\n \/\/ Declare the types of the images\n typedef itk::Image InputImageType;\n typedef itk::Image OutputImageType;\n\n \n \n \/\/ Declare Iterator types apropriated for each image \n typedef itk::ImageRegionIteratorWithIndex<\n InputImageType> InputIteratorType;\n\n typedef itk::ImageRegionIteratorWithIndex<\n OutputImageType> OutputIteratorType;\n\n\n\n \/\/ Declare the type of the index to access images\n typedef itk::Index IndexType;\n\n \/\/ Declare the type of the size \n typedef itk::Size SizeType;\n\n \/\/ Declare the type of the Region\n typedef itk::ImageRegion RegionType;\n\n \/\/ Create two images\n InputImageType::Pointer inputImage = InputImageType::New();\n \n \/\/ Define their size, and start index\n SizeType size;\n size[0] = 2;\n size[1] = 2;\n size[2] = 2;\n\n IndexType start;\n start[0] = 0;\n start[1] = 0;\n start[2] = 0;\n\n RegionType region;\n region.SetIndex( start );\n region.SetSize( size );\n\n \/\/ Initialize Image A\n inputImage->SetLargestPossibleRegion( region );\n inputImage->SetBufferedRegion( region );\n inputImage->SetRequestedRegion( region );\n inputImage->Allocate();\n \/\/ Create one iterator for the Input Image (this is a light object)\n InputIteratorType it( inputImage, inputImage->GetBufferedRegion() );\n\n \/\/ Initialize the content of Image A\n const double value = vnl_math::pi \/ 6.0;\n std::cout << \"Content of the Input \" << std::endl;\n it.GoToBegin();\n while( !it.IsAtEnd() ) \n {\n it.Set( value );\n std::cout << it.Get() << std::endl;\n ++it;\n }\n\n \/\/ Declare the type for the Log10 filter\n typedef itk::Log10ImageFilter< InputImageType,\n OutputImageType > FilterType;\n \n\n \/\/ Create an ADD Filter \n FilterType::Pointer filter = FilterType::New();\n\n\n \/\/ Connect the input images\n filter->SetInput( inputImage ); \n\n \/\/ Get the Smart Pointer to the Filter Output \n OutputImageType::Pointer outputImage = filter->GetOutput();\n\n \n \/\/ Execute the filter\n filter->Update();\n filter->SetFunctor(filter->GetFunctor());\n\n \/\/ Create an iterator for going through the image output\n OutputIteratorType ot(outputImage, outputImage->GetRequestedRegion());\n \n \/\/ Check the content of the result image\n std::cout << \"Verification of the output \" << std::endl;\n const OutputImageType::PixelType epsilon = 1e-6;\n ot.GoToBegin();\n it.GoToBegin();\n while( !ot.IsAtEnd() ) \n {\n std::cout << ot.Get() << \" = \";\n std::cout << vcl_log10( it.Get() ) << std::endl; \n const InputImageType::PixelType input = it.Get();\n const OutputImageType::PixelType output = ot.Get();\n const OutputImageType::PixelType naturallog = vcl_log10(input);\n if( vcl_fabs( naturallog - output ) > epsilon )\n {\n std::cerr << \"Error in itkLog10ImageFilterTest \" << std::endl;\n std::cerr << \" vcl_log10( \" << input << \") = \" << naturallog << std::endl;\n std::cerr << \" differs from \" << output;\n std::cerr << \" by more than \" << epsilon << std::endl;\n return EXIT_FAILURE;\n }\n ++ot;\n ++it;\n }\n\n\n \/\/---------------------------------------\n \/\/ This section tests for Log10ImageAdaptor\n \/\/---------------------------------------\n\n typedef itk::Log10ImageAdaptor AdaptorType;\n\n AdaptorType::Pointer log10Adaptor = AdaptorType::New();\n\n log10Adaptor->SetImage( inputImage );\n\n typedef itk::SubtractImageFilter<\n OutputImageType,\n AdaptorType,\n OutputImageType > DiffFilterType;\n\n DiffFilterType::Pointer diffFilter = DiffFilterType::New();\n\n diffFilter->SetInput1( outputImage );\n diffFilter->SetInput2( log10Adaptor );\n\n diffFilter->Update();\n\n \/\/ Get the Smart Pointer to the Diff filter Output\n OutputImageType::Pointer diffImage = diffFilter->GetOutput();\n\n \/\/ Check the content of the diff image\n std::cout << \"Comparing the results with those of an Adaptor\" << std::endl;\n std::cout << \"Verification of the output \" << std::endl;\n\n \/\/ Create an iterator for going through the image output\n OutputIteratorType dt(diffImage, diffImage->GetRequestedRegion());\n \n dt.GoToBegin();\n while( !dt.IsAtEnd() ) \n {\n std::cout << dt.Get() << std::endl;\n const OutputImageType::PixelType diff = dt.Get();\n if( vcl_fabs( diff ) > epsilon )\n {\n std::cerr << \"Error in itkLog10ImageFilterTest \" << std::endl;\n std::cerr << \"Comparing results with Adaptors\" << std::endl;\n std::cerr << \" difference = \" << diff << std::endl;\n std::cerr << \" differs from 0 \";\n std::cerr << \" by more than \" << epsilon << std::endl;\n return EXIT_FAILURE;\n }\n ++dt;\n }\n\n \n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2014, Ӱ\n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/ \n\/\/ * Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/ \n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\/\/ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"stdafx.h\"\n#include \"IkhWinLib2\/COpenGLWnd.h\"\n\nBEGIN_IKHWINLIB2()\n\nBEGIN_MSGMAP(COpenGLWnd, CWindow)\n\tMSGMAP_WM_CREATE(OnCreate)\n\tMSGMAP_WM_SIZE(OnSize)\n\tMSGMAP_WM_DESTROY(OnDestroy)\nEND_MSGMAP(COpenGLWnd, CWindow)\n\nCOpenGLWnd::COpenGLWnd(BYTE cDepthBits \/* = 24 *\/, BYTE cStencilBits \/* = 8 *\/)\n\t: m_cDepthBits(cDepthBits), m_cStencilBits(cStencilBits),\n\t, m_fps(0), m_hdc(nullptr)\n\t, m_count(0), m_gap(0), m_PrevTime(0), m_bCalced(false)\n{\n}\n\nBOOL COpenGLWnd::OnCreate(LPCREATESTRUCT lpcs)\n{\n\tif (!MSG_FORWARD_WM_CREATE(CWindow, lpcs))\n\t\treturn FALSE;\n\n\tPIXELFORMATDESCRIPTOR pfd;\n\tint nPixelFormat;\n\n\tm_hdc = GetDC(*this);\n\n\tRECT rt;\n\tGetClientRect(*this, &rt);\n\tm_cx = rt.right;\n\tm_cy = rt.bottom;\n\n\tmemset(&pfd, 0, sizeof(pfd));\n\tpfd.nSize = sizeof(pfd);\n\tpfd.nVersion = 1;\n\tpfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;\n\tpfd.iPixelType = PFD_TYPE_RGBA;\n\tpfd.cColorBits = 32;\n\tpfd.cDepthBits = m_cDepthBits;\n\tpfd.cStencilBits = m_cStencilBits;\n\tpfd.iLayerType = PFD_MAIN_PLANE;\n\n\tnPixelFormat = ChoosePixelFormat(m_hdc, &pfd);\n\tif (nPixelFormat != 0)\n\t{\n\t\tif (SetPixelFormat(m_hdc, nPixelFormat, &pfd))\n\t\t{\n\t\t\treturn TRUE;\n\t\t}\n\t}\n\n\treturn FALSE;\n}\n\nvoid COpenGLWnd::OnSize(UINT state, int cx, int cy)\n{\n\tMSG_FORWARD_WM_SIZE(CWindow, state, cx, cy);\n\n\tm_cx = cx;\n\tm_cy = cy;\n}\n\nvoid COpenGLWnd::OnDestroy()\n{\n\twglMakeCurrent(m_hdc, nullptr);\n\n\tMSG_FORWARD_WM_DESTROY(CWindow);\n}\n\nHGLRC COpenGLWnd::InitGL()\n{\n\tassert(this != nullptr);\n\n\tHGLRC hrc = wglCreateContext(m_hdc);\n\twglMakeCurrent(m_hdc, hrc);\n\n\treturn hrc;\n}\n\nvoid COpenGLWnd::DestroyGL(HGLRC hrc)\n{\n\tassert(this != nullptr);\n\n\twglDeleteContext(hrc);\n}\n\nvoid COpenGLWnd::SizeChangeProc()\n{\n\tglViewport(0, 0, m_cx, m_cy);\n}\n\nunsigned COpenGLWnd::CalcFPS()\n{\n\tassert(this != nullptr);\n\n\tDWORD now = GetTickCount();\n\n\tif (!m_bCalced)\n\t{\n\t\tm_PrevTime = now;\n\t\tm_bCalced = true;\n\t}\n\n\tm_gap = now - m_PrevTime;\n\n\tm_count++;\n\n\tif (m_gap >= 1000)\n\t{\n\t\tm_PrevTime = now;\n\n\t\tm_gap -= 1000;\n\t\tm_fps = m_count;\n\t\tm_count = 0;\n\t}\n\n\treturn m_fps;\n}\n\nEND_IKHWINLIB2()\nminor change (fix) (#9) (#10)\/\/ Copyright (c) 2014, Ӱ\n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/ \n\/\/ * Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/ \n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\/\/ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"stdafx.h\"\n#include \"IkhWinLib2\/COpenGLWnd.h\"\n\nBEGIN_IKHWINLIB2()\n\nBEGIN_MSGMAP(COpenGLWnd, CWindow)\n\tMSGMAP_WM_CREATE(OnCreate)\n\tMSGMAP_WM_SIZE(OnSize)\n\tMSGMAP_WM_DESTROY(OnDestroy)\nEND_MSGMAP(COpenGLWnd, CWindow)\n\nCOpenGLWnd::COpenGLWnd(BYTE cDepthBits \/* = 24 *\/, BYTE cStencilBits \/* = 8 *\/)\n\t: m_cDepthBits(cDepthBits), m_cStencilBits(cStencilBits)\n\t, m_fps(0), m_hdc(nullptr)\n\t, m_count(0), m_gap(0), m_PrevTime(0), m_bCalced(false)\n{\n}\n\nBOOL COpenGLWnd::OnCreate(LPCREATESTRUCT lpcs)\n{\n\tif (!MSG_FORWARD_WM_CREATE(CWindow, lpcs))\n\t\treturn FALSE;\n\n\tPIXELFORMATDESCRIPTOR pfd;\n\tint nPixelFormat;\n\n\tm_hdc = GetDC(*this);\n\n\tRECT rt;\n\tGetClientRect(*this, &rt);\n\tm_cx = rt.right;\n\tm_cy = rt.bottom;\n\n\tmemset(&pfd, 0, sizeof(pfd));\n\tpfd.nSize = sizeof(pfd);\n\tpfd.nVersion = 1;\n\tpfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;\n\tpfd.iPixelType = PFD_TYPE_RGBA;\n\tpfd.cColorBits = 32;\n\tpfd.cDepthBits = m_cDepthBits;\n\tpfd.cStencilBits = m_cStencilBits;\n\tpfd.iLayerType = PFD_MAIN_PLANE;\n\n\tnPixelFormat = ChoosePixelFormat(m_hdc, &pfd);\n\tif (nPixelFormat != 0)\n\t{\n\t\tif (SetPixelFormat(m_hdc, nPixelFormat, &pfd))\n\t\t{\n\t\t\treturn TRUE;\n\t\t}\n\t}\n\n\treturn FALSE;\n}\n\nvoid COpenGLWnd::OnSize(UINT state, int cx, int cy)\n{\n\tMSG_FORWARD_WM_SIZE(CWindow, state, cx, cy);\n\n\tm_cx = cx;\n\tm_cy = cy;\n}\n\nvoid COpenGLWnd::OnDestroy()\n{\n\twglMakeCurrent(m_hdc, nullptr);\n\n\tMSG_FORWARD_WM_DESTROY(CWindow);\n}\n\nHGLRC COpenGLWnd::InitGL()\n{\n\tassert(this != nullptr);\n\n\tHGLRC hrc = wglCreateContext(m_hdc);\n\twglMakeCurrent(m_hdc, hrc);\n\n\treturn hrc;\n}\n\nvoid COpenGLWnd::DestroyGL(HGLRC hrc)\n{\n\tassert(this != nullptr);\n\n\twglDeleteContext(hrc);\n}\n\nvoid COpenGLWnd::SizeChangeProc()\n{\n\tglViewport(0, 0, m_cx, m_cy);\n}\n\nunsigned COpenGLWnd::CalcFPS()\n{\n\tassert(this != nullptr);\n\n\tDWORD now = GetTickCount();\n\n\tif (!m_bCalced)\n\t{\n\t\tm_PrevTime = now;\n\t\tm_bCalced = true;\n\t}\n\n\tm_gap = now - m_PrevTime;\n\n\tm_count++;\n\n\tif (m_gap >= 1000)\n\t{\n\t\tm_PrevTime = now;\n\n\t\tm_gap -= 1000;\n\t\tm_fps = m_count;\n\t\tm_count = 0;\n\t}\n\n\treturn m_fps;\n}\n\nEND_IKHWINLIB2()\n<|endoftext|>"} {"text":"#include \"sp\/sp.h\"\n#include \"sp\/system\/FileSystem.h\"\n\n#include \"sp\/system\/Memory.h\"\n\n#include \n\nnamespace sp {\n\n\tstatic int64 GetFileSizeInternal(HANDLE file)\n\t{\n\t\tLARGE_INTEGER size;\n\t\tGetFileSizeEx(file, &size);\n\t\treturn size.QuadPart;\n\t}\n\n\tvoid CALLBACK FileIOCompletionRoutine(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped)\n\t{\n\t}\n\n\tbool FileSystem::FileExists(const String& path)\n\t{\n\t\tDWORD result = GetFileAttributes(path.c_str());\n\t\treturn !(result == INVALID_FILE_ATTRIBUTES && GetLastError() == ERROR_FILE_NOT_FOUND);\n\t}\n\n\tint64 FileSystem::GetFileSize(const String& path)\n\t{\n\t\tHANDLE file = CreateFile(path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);\n\t\tif (file == INVALID_HANDLE_VALUE)\n\t\t\treturn -1;\n\t\treturn GetFileSizeInternal(file);\n\t}\n\n\tbool FileSystem::ReadFile(const String& path, void* buffer, int64 size)\n\t{\n\t\tHANDLE file = CreateFile(path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);\n\t\tif (file == INVALID_HANDLE_VALUE)\n\t\t\treturn false;\n\n\t\tif (size < 0)\n\t\t\tsize = GetFileSizeInternal(file);\n\n\t\tOVERLAPPED ol = { 0 };\n\t\tbool result = ReadFileEx(file, buffer, size, &ol, FileIOCompletionRoutine);\n\t\tCloseHandle(file);\n\t\treturn result;\n\t}\n\n\tbyte* FileSystem::ReadFile(const String& path)\n\t{\n\t\tint64 size = GetFileSize(path);\n\t\tbyte* buffer = spnew byte[size];\n\t\tif (!ReadFile(path, buffer, size))\n\t\t{\n\t\t\tspdel buffer;\n\t\t\treturn nullptr;\n\t\t}\n\t\treturn buffer;\n\t}\n\n\tString FileSystem::ReadTextFile(const String& path)\n\t{\n\t\tint64 size = GetFileSize(path);\n\t\tString result(size, 0);\n\t\tif (!ReadFile(path, &result[0]))\n\t\t\treturn String();\n\n\t\t\/\/ Strip carriage returns\n\t\tresult.erase(std::remove(result.begin(), result.end(), '\\r'), result.end());\n\t\treturn result;\n\t}\n\n\tbool FileSystem::WriteFile(const String& path, byte* buffer)\n\t{\n\t\tHANDLE file = CreateFile(path.c_str(), GENERIC_WRITE, NULL, NULL, CREATE_NEW | OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);\n\t\tif (file == INVALID_HANDLE_VALUE)\n\t\t\treturn false;\n\n\t\tint64 size = GetFileSizeInternal(file);\n\t\tDWORD written;\n\t\tbool result = ::WriteFile(file, buffer, size, &written, NULL);\n\t\tCloseHandle(file);\n\t\treturn result;\n\t}\n\n\tbool FileSystem::WriteTextFile(const String& path, const String& text)\n\t{\n\t\treturn WriteFile(path, (byte*)&text[0]);\n\t}\n}Fixed Win32FileSystem file handle not being closed.#include \"sp\/sp.h\"\n#include \"sp\/system\/FileSystem.h\"\n\n#include \"sp\/system\/Memory.h\"\n\n#include \n\nnamespace sp {\n\n\tstatic int64 GetFileSizeInternal(HANDLE file)\n\t{\n\t\tLARGE_INTEGER size;\n\t\tGetFileSizeEx(file, &size);\n\t\treturn size.QuadPart;\n\t}\n\n\tvoid CALLBACK FileIOCompletionRoutine(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped)\n\t{\n\t}\n\n\tbool FileSystem::FileExists(const String& path)\n\t{\n\t\tDWORD result = GetFileAttributes(path.c_str());\n\t\treturn !(result == INVALID_FILE_ATTRIBUTES && GetLastError() == ERROR_FILE_NOT_FOUND);\n\t}\n\n\tint64 FileSystem::GetFileSize(const String& path)\n\t{\n\t\tHANDLE file = CreateFile(path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);\n\t\tif (file == INVALID_HANDLE_VALUE)\n\t\t\treturn -1;\n\t\tint64 result = GetFileSizeInternal(file);\n\t\tCloseHandle(file);\n\t\treturn result;\n\t}\n\n\tbool FileSystem::ReadFile(const String& path, void* buffer, int64 size)\n\t{\n\t\tHANDLE file = CreateFile(path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);\n\t\tif (file == INVALID_HANDLE_VALUE)\n\t\t\treturn false;\n\n\t\tif (size < 0)\n\t\t\tsize = GetFileSizeInternal(file);\n\n\t\tOVERLAPPED ol = { 0 };\n\t\tbool result = ReadFileEx(file, buffer, size, &ol, FileIOCompletionRoutine);\n\t\tCloseHandle(file);\n\t\treturn result;\n\t}\n\n\tbyte* FileSystem::ReadFile(const String& path)\n\t{\n\t\tint64 size = GetFileSize(path);\n\t\tbyte* buffer = spnew byte[size];\n\t\tif (!ReadFile(path, buffer, size))\n\t\t{\n\t\t\tspdel buffer;\n\t\t\treturn nullptr;\n\t\t}\n\t\treturn buffer;\n\t}\n\n\tString FileSystem::ReadTextFile(const String& path)\n\t{\n\t\tint64 size = GetFileSize(path);\n\t\tString result(size, 0);\n\t\tif (!ReadFile(path, &result[0]))\n\t\t\treturn String();\n\n\t\t\/\/ Strip carriage returns\n\t\tresult.erase(std::remove(result.begin(), result.end(), '\\r'), result.end());\n\t\treturn result;\n\t}\n\n\tbool FileSystem::WriteFile(const String& path, byte* buffer)\n\t{\n\t\tHANDLE file = CreateFile(path.c_str(), GENERIC_WRITE, NULL, NULL, CREATE_NEW | OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);\n\t\tif (file == INVALID_HANDLE_VALUE)\n\t\t\treturn false;\n\n\t\tint64 size = GetFileSizeInternal(file);\n\t\tDWORD written;\n\t\tbool result = ::WriteFile(file, buffer, size, &written, NULL);\n\t\tCloseHandle(file);\n\t\treturn result;\n\t}\n\n\tbool FileSystem::WriteTextFile(const String& path, const String& text)\n\t{\n\t\treturn WriteFile(path, (byte*)&text[0]);\n\t}\n}<|endoftext|>"} {"text":"#include \"ColorGradientLabel.h\"\n\n#include \n\n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \"ColorGradientModel.h\"\n\n#include \"util.hpp\"\n\nnamespace\n{\n\nconst QBrush TransparencyBackgroundBrush()\n{\n const int size = 12;\n QImage backgroundImage(size, size, QImage::Format_ARGB32);\n unsigned char *bits = backgroundImage.bits();\n \n int color, i;\n for(unsigned short x = 0; x < size; ++x)\n for(unsigned short y = 0; y < size; ++y)\n {\n i = (x * size + y) * 4;\n \n color = (x <= 5 && y <= 5) || (x > 5 && y > 5) ? 255 : 224;\n \n bits[i + 2] = color;\n bits[i + 1] = color;\n bits[i + 0] = color;\n bits[i + 3] = 255;\n }\n \n return QBrush(backgroundImage);\n};\n\n} \/\/ namespace\n\nnamespace widgetzeug\n{\n\nColorGradientLabel::ColorGradientLabel(QWidget * parent)\n: QGLWidget{parent}\n, m_model{nullptr}\n, m_backgroundBrush{TransparencyBackgroundBrush()}\n{\n setMinimumSize(1u, 30);\n}\n\nColorGradientLabel::ColorGradientLabel(\n ColorGradientModel * model,\n QWidget * parent)\n: ColorGradientLabel{parent}\n{\n setModel(model);\n}\n\nColorGradientLabel::~ColorGradientLabel()\n{\n if (m_model)\n m_model->disconnect(m_modelConnection);\n}\n\nvoid ColorGradientLabel::setModel(widgetzeug::ColorGradientModel * model)\n{\n if (m_model)\n m_model->disconnect(m_modelConnection);\n \n m_model = model;\n updatePixmap();\n update();\n \n m_modelConnection = connect(model, &ColorGradientModel::changed,\n [this] ()\n {\n updatePixmap();\n update();\n });\n}\n\nvoid ColorGradientLabel::setHistogram(const QList & histogram)\n{\n m_histogram = histogram;\n\n updateHistogram();\n update();\n}\n\nvoid ColorGradientLabel::resizeEvent(QResizeEvent * event)\n{\n if (!m_model)\n return;\n \n updateHistogram();\n updatePixmap();\n \n update();\n}\n\nvoid ColorGradientLabel::paintEvent(QPaintEvent * event)\n{\n QPainter painter{this};\n \n paintGradient(event->rect(), painter);\n paintHistogram(painter);\n}\n\nvoid ColorGradientLabel::paintGradient(const QRect & paintRect, QPainter & painter)\n{\n painter.save();\n\n painter.setPen(Qt::NoPen);\n painter.setBrush(m_backgroundBrush);\n painter.drawRect(paintRect);\n \n painter.drawPixmap(paintRect, m_gradientPixmap);\n\n painter.restore();\n}\n\nvoid ColorGradientLabel::paintHistogram(QPainter & painter)\n{\n if (m_histogram.empty())\n return;\n\n const auto width = this->width();\n const auto widthScale = width \/ static_cast(m_numBuckets * m_actualBucketSize);\n\n painter.save();\n\n auto pen = QPen{QColor{0, 0, 0, 100}};\n pen.setWidthF(1.0 \/ devicePixelRatio());\n painter.setPen(pen);\n painter.setBrush(QColor{255, 255, 255, 70});\n\n painter.scale(widthScale, 1.0);\n painter.drawPath(m_histogramPath);\n\n painter.restore();\n}\n\nQList ColorGradientLabel::generateBuckets(uint numBuckets)\n{\n auto buckets = QList{};\n \n if (numBuckets < m_histogram.size())\n {\n const auto invNumBuckets = 1.0 \/ numBuckets;\n \n auto histogram_index = 0;\n for (auto bucket_i = 0u; bucket_i < numBuckets; ++bucket_i)\n {\n const auto norm_bucket_i = static_cast(bucket_i) \/ numBuckets;\n auto value = 0u, count = 0u;\n \n while (static_cast(histogram_index) \/ m_histogram.size() < (norm_bucket_i + invNumBuckets))\n {\n count += 1;\n value += m_histogram[histogram_index++];\n }\n \n buckets << value \/ count;\n }\n \n assert(histogram_index == m_histogram.size());\n }\n else\n {\n std::copy(\n m_histogram.begin(),\n m_histogram.end(),\n std::back_inserter(buckets));\n }\n \n auto min = std::numeric_limits::max(), max = 0.0;\n for (const auto & value : buckets)\n {\n min = std::min(min, value);\n max = std::max(max, value);\n }\n \n const auto diff = (max - min);\n \n for (auto & value : buckets)\n {\n value = static_cast(value - min) \/ diff;\n assert(value >= 0.0 && value <= 1.0);\n }\n \n for (auto i = 0; i < buckets.size(); ++i)\n {\n const auto prev = std::max(0, i - 1);\n const auto next = std::min(buckets.size() - 1, i + 1);\n \n buckets[i] = (buckets[prev] + buckets[i] + buckets[next]) \/ 3.0;\n }\n \n return buckets;\n}\n\nvoid ColorGradientLabel::updateHistogram()\n{\n if (m_histogram.empty())\n {\n m_histogramPath = QPainterPath{};\n return;\n }\n\n const auto buckets = generateBuckets(width() \/ s_bucketSize);\n \n m_numBuckets = buckets.size();\n m_actualBucketSize = width() \/ m_numBuckets;\n \n static const auto offset = 2u;\n \n const auto height = this->height();\n const auto paddingTop = static_cast(height * 0.2);\n const auto maxRange = static_cast(height * 0.7);\n \n const auto initialX = 0.0;\n auto currentX = initialX;\n \n m_histogramPath = QPainterPath{};\n m_histogramPath.moveTo(currentX, height + offset);\n \n for (const auto & value : buckets)\n {\n const auto y = paddingTop + (1.0 - value) * maxRange;\n \n m_histogramPath.lineTo(currentX, y);\n currentX += m_actualBucketSize;\n m_histogramPath.lineTo(currentX, y);\n }\n \n m_histogramPath.lineTo(currentX, height + offset);\n m_histogramPath.lineTo(initialX, height + offset);\n}\n\nvoid ColorGradientLabel::updatePixmap()\n{\n auto image = m_model->image(width() * devicePixelRatio());\n m_gradientPixmap = QPixmap::fromImage(image);\n m_gradientPixmap.setDevicePixelRatio(devicePixelRatio());\n}\n\n} \/\/ namespace widgetzeug\nFix unsigned warning#include \"ColorGradientLabel.h\"\n\n#include \n\n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \"ColorGradientModel.h\"\n\n#include \"util.hpp\"\n\nnamespace\n{\n\nconst QBrush TransparencyBackgroundBrush()\n{\n const int size = 12;\n QImage backgroundImage(size, size, QImage::Format_ARGB32);\n unsigned char *bits = backgroundImage.bits();\n \n int color, i;\n for(unsigned short x = 0; x < size; ++x)\n for(unsigned short y = 0; y < size; ++y)\n {\n i = (x * size + y) * 4;\n \n color = (x <= 5 && y <= 5) || (x > 5 && y > 5) ? 255 : 224;\n \n bits[i + 2] = color;\n bits[i + 1] = color;\n bits[i + 0] = color;\n bits[i + 3] = 255;\n }\n \n return QBrush(backgroundImage);\n};\n\n} \/\/ namespace\n\nnamespace widgetzeug\n{\n\nColorGradientLabel::ColorGradientLabel(QWidget * parent)\n: QGLWidget{parent}\n, m_model{nullptr}\n, m_backgroundBrush{TransparencyBackgroundBrush()}\n{\n setMinimumSize(1u, 30);\n}\n\nColorGradientLabel::ColorGradientLabel(\n ColorGradientModel * model,\n QWidget * parent)\n: ColorGradientLabel{parent}\n{\n setModel(model);\n}\n\nColorGradientLabel::~ColorGradientLabel()\n{\n if (m_model)\n m_model->disconnect(m_modelConnection);\n}\n\nvoid ColorGradientLabel::setModel(widgetzeug::ColorGradientModel * model)\n{\n if (m_model)\n m_model->disconnect(m_modelConnection);\n \n m_model = model;\n updatePixmap();\n update();\n \n m_modelConnection = connect(model, &ColorGradientModel::changed,\n [this] ()\n {\n updatePixmap();\n update();\n });\n}\n\nvoid ColorGradientLabel::setHistogram(const QList & histogram)\n{\n m_histogram = histogram;\n\n updateHistogram();\n update();\n}\n\nvoid ColorGradientLabel::resizeEvent(QResizeEvent * event)\n{\n if (!m_model)\n return;\n \n updateHistogram();\n updatePixmap();\n \n update();\n}\n\nvoid ColorGradientLabel::paintEvent(QPaintEvent * event)\n{\n QPainter painter{this};\n \n paintGradient(event->rect(), painter);\n paintHistogram(painter);\n}\n\nvoid ColorGradientLabel::paintGradient(const QRect & paintRect, QPainter & painter)\n{\n painter.save();\n\n painter.setPen(Qt::NoPen);\n painter.setBrush(m_backgroundBrush);\n painter.drawRect(paintRect);\n \n painter.drawPixmap(paintRect, m_gradientPixmap);\n\n painter.restore();\n}\n\nvoid ColorGradientLabel::paintHistogram(QPainter & painter)\n{\n if (m_histogram.empty())\n return;\n\n const auto width = this->width();\n const auto widthScale = width \/ static_cast(m_numBuckets * m_actualBucketSize);\n\n painter.save();\n\n auto pen = QPen{QColor{0, 0, 0, 100}};\n pen.setWidthF(1.0 \/ devicePixelRatio());\n painter.setPen(pen);\n painter.setBrush(QColor{255, 255, 255, 70});\n\n painter.scale(widthScale, 1.0);\n painter.drawPath(m_histogramPath);\n\n painter.restore();\n}\n\nQList ColorGradientLabel::generateBuckets(uint numBuckets)\n{\n auto buckets = QList{};\n \n if (numBuckets < static_cast(m_histogram.size()))\n {\n const auto invNumBuckets = 1.0 \/ numBuckets;\n \n auto histogram_index = 0;\n for (auto bucket_i = 0u; bucket_i < numBuckets; ++bucket_i)\n {\n const auto norm_bucket_i = static_cast(bucket_i) \/ numBuckets;\n auto value = 0u, count = 0u;\n \n while (static_cast(histogram_index) \/ m_histogram.size() < (norm_bucket_i + invNumBuckets))\n {\n count += 1;\n value += m_histogram[histogram_index++];\n }\n \n buckets << value \/ count;\n }\n \n assert(histogram_index == m_histogram.size());\n }\n else\n {\n std::copy(\n m_histogram.begin(),\n m_histogram.end(),\n std::back_inserter(buckets));\n }\n \n auto min = std::numeric_limits::max(), max = 0.0;\n for (const auto & value : buckets)\n {\n min = std::min(min, value);\n max = std::max(max, value);\n }\n \n const auto diff = (max - min);\n \n for (auto & value : buckets)\n {\n value = static_cast(value - min) \/ diff;\n assert(value >= 0.0 && value <= 1.0);\n }\n \n for (auto i = 0; i < buckets.size(); ++i)\n {\n const auto prev = std::max(0, i - 1);\n const auto next = std::min(buckets.size() - 1, i + 1);\n \n buckets[i] = (buckets[prev] + buckets[i] + buckets[next]) \/ 3.0;\n }\n \n return buckets;\n}\n\nvoid ColorGradientLabel::updateHistogram()\n{\n if (m_histogram.empty())\n {\n m_histogramPath = QPainterPath{};\n return;\n }\n\n const auto buckets = generateBuckets(width() \/ s_bucketSize);\n \n m_numBuckets = buckets.size();\n m_actualBucketSize = width() \/ m_numBuckets;\n \n static const auto offset = 2u;\n \n const auto height = this->height();\n const auto paddingTop = static_cast(height * 0.2);\n const auto maxRange = static_cast(height * 0.7);\n \n const auto initialX = 0.0;\n auto currentX = initialX;\n \n m_histogramPath = QPainterPath{};\n m_histogramPath.moveTo(currentX, height + offset);\n \n for (const auto & value : buckets)\n {\n const auto y = paddingTop + (1.0 - value) * maxRange;\n \n m_histogramPath.lineTo(currentX, y);\n currentX += m_actualBucketSize;\n m_histogramPath.lineTo(currentX, y);\n }\n \n m_histogramPath.lineTo(currentX, height + offset);\n m_histogramPath.lineTo(initialX, height + offset);\n}\n\nvoid ColorGradientLabel::updatePixmap()\n{\n auto image = m_model->image(width() * devicePixelRatio());\n m_gradientPixmap = QPixmap::fromImage(image);\n m_gradientPixmap.setDevicePixelRatio(devicePixelRatio());\n}\n\n} \/\/ namespace widgetzeug\n<|endoftext|>"} {"text":"\/********************************** SIGNATURE *********************************\\\n| ,, |\n| db `7MM |\n| ;MM: MM |\n| ,V^MM. ,pP\"Ybd MMpMMMb. .gP\"Ya `7Mb,od8 |\n| ,M `MM 8I `\" MM MM ,M' Yb MM' \"' |\n| AbmmmqMA `YMMMa. MM MM 8M\"\"\"\"\"\" MM |\n| A' VML L. I8 MM MM YM. , MM |\n| .AMA. .AMMA.M9mmmP'.JMML JMML.`Mbmmd'.JMML. |\n| |\n| |\n| ,, ,, |\n| .g8\"\"\"bgd `7MM db `7MM |\n| .dP' `M MM MM |\n| dM' ` MM `7MM ,p6\"bo MM ,MP' |\n| MM MM MM 6M' OO MM ;Y |\n| MM. `7MMF' MM MM 8M MM;Mm |\n| `Mb. MM MM MM YM. , MM `Mb. |\n| `\"bmmmdPY .JMML..JMML.YMbmd'.JMML. YA. |\n| |\n\\******************************************************************************\/\n\/*********************************** LICENSE **********************************\\\n| Copyright (c) 2013, Asher Glick |\n| All rights reserved. |\n| |\n| Redistribution and use in source and binary forms, with or without |\n| modification, are permitted provided that the following conditions are met: |\n| |\n| * Redistributions of source code must retain the above copyright notice, |\n| this list of conditions and the following disclaimer. |\n| * Redistributions in binary form must reproduce the above copyright notice, |\n| this list of conditions and the following disclaimer in the documentation |\n| and\/or other materials provided with the distribution. |\n| |\n| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" |\n| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |\n| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |\n| ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE |\n| LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |\n| CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |\n| SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |\n| INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |\n| CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |\n| ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |\n| POSSIBILITY OF SUCH DAMAGE. |\n\\******************************************************************************\/\n\n#include \n#include \n#include \n#include \n #include \n #include \n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n#define HASHSIZE 32\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ BASE MODIFICATION FUNCTIONS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ \nint calculateNewBaseLength(int oldBase, int oldBaseLength, int newBase) {\n double logOldBase = log(oldBase);\n double logNewBase = log(newBase);\n double newBaseLength = oldBaseLength * (logOldBase\/logNewBase);\n int intNewBaseLength = newBaseLength;\n if (newBaseLength > intNewBaseLength) intNewBaseLength += 1; \/\/ round up\n return intNewBaseLength;\n}\n\/\/ Trims all of the preceding zeros off a function\nvector trimNumber(vector v) {\n vector::iterator i = v.begin();\n while (i != v.end()-1) {\n if (*i != 0) {\n break;\n }\n i++;\n }\n\n return vector(i, v.end());\n}\n\n\/\/ creats a new base number of the old base value of 10\nvector tenInOldBase(int oldBase, int newBase) {\n \/\/ int ten[] = {1,0};\n int newBaseLength = calculateNewBaseLength(oldBase, 2, newBase);\n int maxLength = newBaseLength>2?newBaseLength:2;\n\n vector newNumber(maxLength, 0);\n\n int currentNumber = oldBase;\n for (int i = maxLength-1; i >=0; i--) {\n newNumber[i] = currentNumber % newBase;\n currentNumber = currentNumber \/ newBase;\n }\n\n newNumber = trimNumber(newNumber);\n\n \/\/ return calculateNewBase(oldBase, 2, newBase, ten);\n return newNumber;\n}\n\n\/\/ Multiplies two base n numbers together\nvector multiply(int base, vector firstNumber, vector secondNumber) {\n int resultLength = firstNumber.size() + secondNumber.size();\n vector resultNumber(resultLength, 0);\n for (int i = firstNumber.size() - 1 ; i >= 0; i--) {\n for (int j = secondNumber.size() - 1; j >= 0; j--) {\n resultNumber[i+j + 1] += firstNumber[i] * secondNumber[j];\n }\n }\n\n for (int i = resultNumber.size() -1; i > 0; i--) {\n if (resultNumber[i] >= base) {\n resultNumber[i-1] += resultNumber[i]\/base;\n resultNumber[i] = resultNumber[i] % base;\n }\n }\n return trimNumber(resultNumber);\n}\n\n\n\nvector calculateNewBase(int oldBase, int newBase, vector oldNumber) {\n int newNumberLength = calculateNewBaseLength(oldBase, oldNumber.size(), newBase);\n vector newNumber(newNumberLength, 0);\n vector conversionFactor(1, 1); \/\/ a single digit of 1\n for (int i = oldNumber.size()-1; i >= 0; i--) {\n vector difference(conversionFactor);\n \/\/ size the vector\n for (unsigned int j = 0; j < difference.size(); j++) {\n difference[j] *= oldNumber[i];\n }\n \/\/ add the vector\n for (unsigned int j = 0; j < difference.size(); j++) {\n int newNumberIndex = j + newNumberLength - difference.size();\n newNumber[newNumberIndex] += difference[j];\n }\n \/\/ increment the conversion factor by oldbase 10\n conversionFactor = multiply(newBase, conversionFactor, tenInOldBase(oldBase,newBase));\n }\n\n \/\/ Flatten number to base\n for (int i = newNumber.size()-1; i >=0; i--) {\n if (newNumber[i] >= newBase) {\n newNumber[i-1] += newNumber[i]\/newBase;\n newNumber[i] = newNumber[i]%newBase;\n }\n }\n\n return trimNumber(newNumber);\n}\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ READ SETTINGS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ \nstruct settingWrapper {\n string domain;\n string allowedCharacters;\n uint maxCharacters;\n string regex;\n};\n\n \n\nsettingWrapper getSettings(string domain) {\n string hexCharacters = \"0123456789abcdef\";\n\n settingWrapper settings;\n\n \/\/ open ~\/.passcodes\/config\n ifstream configFile;\n struct passwd *pw = getpwuid(getuid());\n const char *homedir = pw->pw_dir;\n string configPath = string(homedir) + \"\/.passcodes\/\";\n string subscriptionPath = string(homedir) + \"\/.passcodes\/subscriptions\";\n\n\n configFile.open(subscriptionPath.c_str());\n\n if (!configFile.is_open()) {\n cout << \"File does not exist\" << endl;\n #if defined(_WIN32)\n _mkdir(strPath.c_str());\n #else\n mkdir(configPath.c_str(), 0777); \/\/ notice that 777 is different than 0777\n #endif\n\n ofstream testFile;\n testFile.open(subscriptionPath.c_str());\n testFile << \"http:\/\/passcod.es\/global.chanel\" << endl;\n testFile << \"http:\/\/asherglick.github.io\/Passcodes\" << endl;\n testFile.close();\n\n configFile.open(subscriptionPath.c_str());\n }\n\n cout << \"opening file\" << endl;\n \/\/configFile.open(subscriptionPath.c_str());\n string subscription = \"\";\n if (configFile.is_open()) {\n cout << \"File is open\" << endl;\n while (getline(configFile, subscription)) {\n cout << \"LINE\" << endl;\n unsigned char hash[20];\n SHA1((unsigned char*)subscription.c_str(), subscription.size(), hash);\n string cashedSubscriptionName = \"\";\n for (int i = 0; i < 4; i++) {\n cashedSubscriptionName += hexCharacters[hash[i]&0x0F];\n cashedSubscriptionName += hexCharacters[(hash[i]>>4)&0x0F];\n }\n cout << cashedSubscriptionName << endl;\n \n }\n }\n \/\/ look for 'subscriptions' section\n \/\/ open each file in the subscriptions list in order\n \/\/ ~\/.passcodes\/\/\n \/\/ add any non-blank entry to the settings, latter entries overriding former\n\n return settings;\n}\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ GENERATE PASSWORD FUNCTIONS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ \n#define ITERATIONCOUNT 100000\n\/****************************** GENERATE PASSWORD *****************************\\\n| The generate password function takes in the domain and the master password |\n| then returns the 16 character long base64 password based off of the sha256 |\n| hash |\n\\******************************************************************************\/\nstring generatePassword(string masterpass, string domain) {\n settingWrapper settings = getSettings(domain);\n\n string prehash = masterpass+domain;\n unsigned char hash[HASHSIZE];\n\n string output = \"\";\n\n for (int i = 0; i < ITERATIONCOUNT; i++) {\n SHA256((unsigned char*)prehash.c_str(), prehash.size(), hash);\n\n prehash = \"\";\n for (int j = 0; j < HASHSIZE; j++) {\n prehash += hash[j];\n }\n }\n\n vector hashedValues(32);\n for (int j = 0; j < HASHSIZE; j++) {\n hashedValues[j] = static_cast(hash[j]);\n }\n vector newValues = calculateNewBase(256, 64, hashedValues);\n\n for (int val : newValues) {\n cout << val << \", \";\n }\n return \"Failed\";\n}\n\n\/************************************ HELP ************************************\\\n| The help fucntion displays the help text to the user, it is called if the |\n| help flag is present or if the user has used the program incorrectly |\n\\******************************************************************************\/\nvoid help() {\n cout <<\n \"Welcome to the command line application for passcod.es\\n\"\n \"written by Asher Glick (aglick@aglick.com)\\n\"\n \"\\n\"\n \"Usage\\n\"\n \" passcodes [-s] [-h] [-d] [-p] \\n\"\n \"\\n\"\n \"Commands\\n\"\n \" -d Any text that comes after this flag is set as the domain\\n\"\n \" If no domain is given it is prompted for\\n\"\n \" -p Any text that comes after this flag is set as the password\\n\"\n \" If this flag is set a warning will be displayed\\n\"\n \" If this flag is not set the user is prompted for a password\\n\"\n \" -h Display the help menu\\n\"\n \" No other functions will be run if this flag is present\\n\"\n \" -s Suppress warnings\\n\"\n \" No warning messages will appear from using the -p flag\\n\"\n << endl;\n}\n\n\/************************************ MAIN ************************************\\\n| The main function handles all of the arguments, parsing them into the |\n| correct locations. Then prompts the user to enter the domain and password |\n| if they have not been specified in the arguments. Finaly it outputs the |\n| generated password to the user |\n\\******************************************************************************\/\nint main(int argc, char* argv[]) {\n bool silent = false;\n string domain = \"\";\n string password = \"\";\n string *pointer = NULL;\n\n \/\/ Parse the arguments\n for (int i = 1; i < argc; i++) {\n if (string(argv[i]) == \"-p\") { \/\/ password flag\n pointer = &password;\n } else if (string(argv[i]) == \"-d\") { \/\/ domain flag\n pointer = &domain;\n } else if (string(argv[i]) == \"-s\") { \/\/ silent flag\n silent = true;\n } else if (string(argv[i]) == \"-h\") { \/\/ help flag\n help();\n return 0;\n } else {\n if (pointer == NULL) {\n help();\n return 0;\n } else {\n *pointer += argv[i];\n }\n }\n }\n\n \/\/ If there is no domain given, prompt the user for a domain\n if (domain == \"\") {\n cout << \"Enter Domain: \";\n getline(cin, domain);\n }\n \/\/ If there is a password given and the silent flag is not present\n \/\/ give the user a warning telling them that the password flag is insecure\n if (password != \"\" && !silent) {\n cout <<\"WARNING: you should not use the -p flag as it may be insecure\" << endl;\n }\n \/\/ If there is not a password given, prompt the user for a password securly\n else if (password == \"\") {\n password = string(getpass(\"Enter Password: \"));\n }\n\n \/\/ Output the generated Password to the user\n cout << generatePassword(domain, password) << endl;\n}\nfixed a bug with password and updated config reading\/********************************** SIGNATURE *********************************\\\n| ,, |\n| db `7MM |\n| ;MM: MM |\n| ,V^MM. ,pP\"Ybd MMpMMMb. .gP\"Ya `7Mb,od8 |\n| ,M `MM 8I `\" MM MM ,M' Yb MM' \"' |\n| AbmmmqMA `YMMMa. MM MM 8M\"\"\"\"\"\" MM |\n| A' VML L. I8 MM MM YM. , MM |\n| .AMA. .AMMA.M9mmmP'.JMML JMML.`Mbmmd'.JMML. |\n| |\n| |\n| ,, ,, |\n| .g8\"\"\"bgd `7MM db `7MM |\n| .dP' `M MM MM |\n| dM' ` MM `7MM ,p6\"bo MM ,MP' |\n| MM MM MM 6M' OO MM ;Y |\n| MM. `7MMF' MM MM 8M MM;Mm |\n| `Mb. MM MM MM YM. , MM `Mb. |\n| `\"bmmmdPY .JMML..JMML.YMbmd'.JMML. YA. |\n| |\n\\******************************************************************************\/\n\/*********************************** LICENSE **********************************\\\n| Copyright (c) 2013, Asher Glick |\n| All rights reserved. |\n| |\n| Redistribution and use in source and binary forms, with or without |\n| modification, are permitted provided that the following conditions are met: |\n| |\n| * Redistributions of source code must retain the above copyright notice, |\n| this list of conditions and the following disclaimer. |\n| * Redistributions in binary form must reproduce the above copyright notice, |\n| this list of conditions and the following disclaimer in the documentation |\n| and\/or other materials provided with the distribution. |\n| |\n| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" |\n| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |\n| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |\n| ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE |\n| LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |\n| CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |\n| SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |\n| INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |\n| CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |\n| ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |\n| POSSIBILITY OF SUCH DAMAGE. |\n\\******************************************************************************\/\n\n#include \n#include \n#include \n#include \n #include \n #include \n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n#define HASHSIZE 32\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ BASE MODIFICATION FUNCTIONS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ \nint calculateNewBaseLength(int oldBase, int oldBaseLength, int newBase) {\n double logOldBase = log(oldBase);\n double logNewBase = log(newBase);\n double newBaseLength = oldBaseLength * (logOldBase\/logNewBase);\n int intNewBaseLength = newBaseLength;\n if (newBaseLength > intNewBaseLength) intNewBaseLength += 1; \/\/ round up\n return intNewBaseLength;\n}\n\/\/ Trims all of the preceding zeros off a function\nvector trimNumber(vector v) {\n vector::iterator i = v.begin();\n while (i != v.end()-1) {\n if (*i != 0) {\n break;\n }\n i++;\n }\n\n return vector(i, v.end());\n}\n\n\/\/ creats a new base number of the old base value of 10\nvector tenInOldBase(int oldBase, int newBase) {\n \/\/ int ten[] = {1,0};\n int newBaseLength = calculateNewBaseLength(oldBase, 2, newBase);\n int maxLength = newBaseLength>2?newBaseLength:2;\n\n vector newNumber(maxLength, 0);\n\n int currentNumber = oldBase;\n for (int i = maxLength-1; i >=0; i--) {\n newNumber[i] = currentNumber % newBase;\n currentNumber = currentNumber \/ newBase;\n }\n\n newNumber = trimNumber(newNumber);\n\n \/\/ return calculateNewBase(oldBase, 2, newBase, ten);\n return newNumber;\n}\n\n\/\/ Multiplies two base n numbers together\nvector multiply(int base, vector firstNumber, vector secondNumber) {\n int resultLength = firstNumber.size() + secondNumber.size();\n vector resultNumber(resultLength, 0);\n for (int i = firstNumber.size() - 1 ; i >= 0; i--) {\n for (int j = secondNumber.size() - 1; j >= 0; j--) {\n resultNumber[i+j + 1] += firstNumber[i] * secondNumber[j];\n }\n }\n\n for (int i = resultNumber.size() -1; i > 0; i--) {\n if (resultNumber[i] >= base) {\n resultNumber[i-1] += resultNumber[i]\/base;\n resultNumber[i] = resultNumber[i] % base;\n }\n }\n return trimNumber(resultNumber);\n}\n\n\n\nvector calculateNewBase(int oldBase, int newBase, vector oldNumber) {\n int newNumberLength = calculateNewBaseLength(oldBase, oldNumber.size(), newBase);\n vector newNumber(newNumberLength, 0);\n vector conversionFactor(1, 1); \/\/ a single digit of 1\n for (int i = oldNumber.size()-1; i >= 0; i--) {\n vector difference(conversionFactor);\n \/\/ size the vector\n for (unsigned int j = 0; j < difference.size(); j++) {\n difference[j] *= oldNumber[i];\n }\n \/\/ add the vector\n for (unsigned int j = 0; j < difference.size(); j++) {\n int newNumberIndex = j + newNumberLength - difference.size();\n newNumber[newNumberIndex] += difference[j];\n }\n \/\/ increment the conversion factor by oldbase 10\n conversionFactor = multiply(newBase, conversionFactor, tenInOldBase(oldBase,newBase));\n }\n\n \/\/ Flatten number to base\n for (int i = newNumber.size()-1; i >=0; i--) {\n if (newNumber[i] >= newBase) {\n newNumber[i-1] += newNumber[i]\/newBase;\n newNumber[i] = newNumber[i]%newBase;\n }\n }\n\n return trimNumber(newNumber);\n}\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ READ SETTINGS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ \nstruct settingWrapper {\n string domain;\n string allowedCharacters;\n uint maxCharacters;\n string regex;\n};\n\n \n\nsettingWrapper getSettings(string domain) {\n string hexCharacters = \"0123456789abcdef\";\n\n settingWrapper settings;\n\n \/\/ open ~\/.passcodes\/config\n ifstream configFile;\n struct passwd *pw = getpwuid(getuid());\n const char *homedir = pw->pw_dir;\n string configPath = string(homedir) + \"\/.passcodes\/\";\n string subscriptionPath = string(homedir) + \"\/.passcodes\/subscriptions\";\n\n\n configFile.open(subscriptionPath.c_str());\n\n if (!configFile.is_open()) {\n cout << \"File does not exist\" << endl;\n #if defined(_WIN32)\n _mkdir(strPath.c_str());\n #else\n mkdir(configPath.c_str(), 0777); \/\/ notice that 777 is different than 0777\n #endif\n\n ofstream testFile;\n testFile.open(subscriptionPath.c_str());\n testFile << \"http:\/\/passcod.es\/global.chanel\" << endl;\n testFile << \"http:\/\/asherglick.github.io\/Passcodes\" << endl;\n testFile.close();\n\n configFile.open(subscriptionPath.c_str());\n }\n\n cout << \"opening file\" << endl;\n \/\/configFile.open(subscriptionPath.c_str());\n string subscription = \"\";\n if (configFile.is_open()) {\n cout << \"File is open\" << endl;\n while (getline(configFile, subscription)) {\n unsigned char hash[20];\n SHA1((unsigned char*)subscription.c_str(), subscription.size(), hash);\n string cashedSubscriptionName = \"\";\n for (int i = 0; i < 4; i++) {\n cashedSubscriptionName += hexCharacters[hash[i]&0x0F];\n cashedSubscriptionName += hexCharacters[(hash[i]>>4)&0x0F];\n }\n ifstream subscription;\n string subscriptionPath = configPath + \"cashe\/\" + cashedSubscriptionName + \"\/\" + domain;\n subscription.open(subscriptionPath);\n string maxLength\n cout << subscriptionPath << endl;\n }\n }\n \/\/ look for 'subscriptions' section\n \/\/ open each file in the subscriptions list in order\n \/\/ ~\/.passcodes\/\/\n \/\/ add any non-blank entry to the settings, latter entries overriding former\n\n return settings;\n}\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ GENERATE PASSWORD FUNCTIONS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ \n#define ITERATIONCOUNT 100000\n\/****************************** GENERATE PASSWORD *****************************\\\n| The generate password function takes in the domain and the master password |\n| then returns the 16 character long base64 password based off of the sha256 |\n| hash |\n\\******************************************************************************\/\nstring generatePassword(string domain, string masterpass ) {\n settingWrapper settings = getSettings(domain);\n\n string prehash = domain+masterpass;\n unsigned char hash[HASHSIZE];\n\n string output = \"\";\n\n for (int i = 0; i < ITERATIONCOUNT; i++) {\n SHA256((unsigned char*)prehash.c_str(), prehash.size(), hash);\n\n prehash = \"\";\n for (int j = 0; j < HASHSIZE; j++) {\n prehash += hash[j];\n }\n }\n\n vector hashedValues(32);\n for (int j = 0; j < HASHSIZE; j++) {\n hashedValues[j] = static_cast(hash[j]);\n }\n vector newValues = calculateNewBase(256, 64, hashedValues);\n\n for (int val : newValues) {\n cout << val << \", \";\n }\n return \"Failed\";\n}\n\n\/************************************ HELP ************************************\\\n| The help fucntion displays the help text to the user, it is called if the |\n| help flag is present or if the user has used the program incorrectly |\n\\******************************************************************************\/\nvoid help() {\n cout <<\n \"Welcome to the command line application for passcod.es\\n\"\n \"written by Asher Glick (aglick@aglick.com)\\n\"\n \"\\n\"\n \"Usage\\n\"\n \" passcodes [-s] [-h] [-d] [-p] \\n\"\n \"\\n\"\n \"Commands\\n\"\n \" -d Any text that comes after this flag is set as the domain\\n\"\n \" If no domain is given it is prompted for\\n\"\n \" -p Any text that comes after this flag is set as the password\\n\"\n \" If this flag is set a warning will be displayed\\n\"\n \" If this flag is not set the user is prompted for a password\\n\"\n \" -h Display the help menu\\n\"\n \" No other functions will be run if this flag is present\\n\"\n \" -s Suppress warnings\\n\"\n \" No warning messages will appear from using the -p flag\\n\"\n << endl;\n}\n\n\/************************************ MAIN ************************************\\\n| The main function handles all of the arguments, parsing them into the |\n| correct locations. Then prompts the user to enter the domain and password |\n| if they have not been specified in the arguments. Finaly it outputs the |\n| generated password to the user |\n\\******************************************************************************\/\nint main(int argc, char* argv[]) {\n bool silent = false;\n string domain = \"\";\n string password = \"\";\n string *pointer = NULL;\n\n \/\/ Parse the arguments\n for (int i = 1; i < argc; i++) {\n if (string(argv[i]) == \"-p\") { \/\/ password flag\n pointer = &password;\n } else if (string(argv[i]) == \"-d\") { \/\/ domain flag\n pointer = &domain;\n } else if (string(argv[i]) == \"-s\") { \/\/ silent flag\n silent = true;\n } else if (string(argv[i]) == \"-h\") { \/\/ help flag\n help();\n return 0;\n } else {\n if (pointer == NULL) {\n help();\n return 0;\n } else {\n *pointer += argv[i];\n }\n }\n }\n\n \/\/ If there is no domain given, prompt the user for a domain\n if (domain == \"\") {\n cout << \"Enter Domain: \";\n getline(cin, domain);\n }\n \/\/ If there is a password given and the silent flag is not present\n \/\/ give the user a warning telling them that the password flag is insecure\n if (password != \"\" && !silent) {\n cout <<\"WARNING: you should not use the -p flag as it may be insecure\" << endl;\n }\n \/\/ If there is not a password given, prompt the user for a password securly\n else if (password == \"\") {\n password = string(getpass(\"Enter Password: \"));\n }\n\n \/\/ Output the generated Password to the user\n cout << generatePassword(domain, password) << endl;\n}\n<|endoftext|>"} {"text":"\/**\n \\file innerintegral.hh\n **\/\n\n#ifndef DUNE_DETAILED_DISCRETIZATIONS_DISCRETEOPERATOR_LOCAL_CODIM1_INNERINTEGRAL_HH\n#define DUNE_DETAILED_DISCRETIZATIONS_DISCRETEOPERATOR_LOCAL_CODIM1_INNERINTEGRAL_HH\n\n\/\/ dune-common\n#include \n\n\/\/ dune-geometry\n#include \n\n\/\/ dune-stuff\n#include \n\nnamespace Dune {\n\nnamespace Detailed {\n\nnamespace Discretizations {\n\nnamespace DiscreteOperator {\n\nnamespace Local {\n\nnamespace Codim1 {\n\n\/**\n \\brief Local operator for inner intersections, i.e. those who have an inner codim 0 entity (Entity or En) and an\n outer codim 0 Neighboring entity (Neighbor or Ne).\n **\/\ntemplate \nclass InnerIntegral\n{\npublic:\n typedef LocalEvaluationImp LocalEvaluationType;\n\n typedef InnerIntegral ThisType;\n\n typedef typename LocalEvaluationType::FunctionSpaceType FunctionSpaceType;\n\n typedef typename FunctionSpaceType::RangeFieldType RangeFieldType;\n\n typedef typename FunctionSpaceType::DomainType DomainType;\n\n typedef typename FunctionSpaceType::DomainFieldType DomainFieldType;\n\n \/\/ template< class InducingDiscreteFunctionType >\n \/\/ class LocalFunctional\n \/\/ {\n \/\/ public:\n \/\/ typedef Dune::Functionals::DiscreteFunctional::Local::Codim0::IntegralInduced< ThisType,\n \/\/ InducingDiscreteFunctionType >\n \/\/ Type;\n \/\/ };\n\n InnerIntegral(const LocalEvaluationType& localEvaluation)\n : localEvaluation_(localEvaluation)\n {\n }\n\n const LocalEvaluationType& localEvaluation() const\n {\n return localEvaluation_;\n }\n\n \/\/ template< class InducingDiscreteFunctionType >\n \/\/ typename LocalFunctional< InducingDiscreteFunctionType >::Type\n \/\/ localFunctional( const InducingDiscreteFunctionType& inducingDiscreteFunction ) const\n \/\/ {\n \/\/ typedef Dune::Functionals::DiscreteFunctional::Local::Codim0::IntegralInduced< ThisType,\n \/\/ InducingDiscreteFunctionType >\n \/\/ LocalFunctionalType;\n\n \/\/ return LocalFunctionalType( *this, inducingDiscreteFunction );\n \/\/ } \/\/ end method localFunctional\n\n unsigned int numTmpObjectsRequired() const\n {\n return 4;\n }\n\n \/**\n \\todo Rename Entity -> En, Neighbor -> Ne\n **\/\n template \n void applyLocal(const LocalAnsatzBaseFunctionSetEntityType& localAnsatzBaseFunctionSetEntity,\n const LocalAnsatzBaseFunctionSetNeighborType& localAnsatzBaseFunctionSetNeighbor,\n const LocalTestBaseFunctionSetEntityType& localTestBaseFunctionSetEntity,\n const LocalTestBaseFunctionSetNeighborType& localTestBaseFunctionSetNeighbor,\n const IntersectionType& intersection, LocalMatrixType& localMatrixEnEn,\n LocalMatrixType& localMatrixEnNe, LocalMatrixType& localMatrixNeEn, LocalMatrixType& localMatrixNeNe,\n std::vector& tmpLocalMatrices) const\n {\n \/\/ preparations\n const unsigned int rowsEn = localAnsatzBaseFunctionSetEntity.size();\n const unsigned int rowsNe = localAnsatzBaseFunctionSetNeighbor.size();\n const unsigned int colsEn = localTestBaseFunctionSetEntity.size();\n const unsigned int colsNe = localTestBaseFunctionSetNeighbor.size();\n\n \/\/ make sure, that the target matrices are big enough\n assert(localMatrixEnEn.rows() >= rowsEn);\n assert(localMatrixEnEn.cols() >= colsEn);\n assert(localMatrixEnNe.rows() >= rowsEn);\n assert(localMatrixEnNe.cols() >= colsNe);\n assert(localMatrixNeEn.rows() >= rowsNe);\n assert(localMatrixNeEn.cols() >= colsEn);\n assert(localMatrixNeNe.rows() >= rowsNe);\n assert(localMatrixNeNe.cols() >= colsNe);\n\n \/\/ clear target matrices\n Dune::Stuff::Common::Matrix::clear(localMatrixEnEn);\n Dune::Stuff::Common::Matrix::clear(localMatrixEnNe);\n Dune::Stuff::Common::Matrix::clear(localMatrixNeEn);\n Dune::Stuff::Common::Matrix::clear(localMatrixNeNe);\n\n \/\/ check tmp local matrices\n if (tmpLocalMatrices.size() < numTmpObjectsRequired()) {\n tmpLocalMatrices.resize(\n numTmpObjectsRequired(),\n LocalMatrixType(std::max(localAnsatzBaseFunctionSetEntity.baseFunctionSet().space().map().maxLocalSize(),\n localAnsatzBaseFunctionSetNeighbor.baseFunctionSet().space().map().maxLocalSize()),\n std::max(localTestBaseFunctionSetEntity.baseFunctionSet().space().map().maxLocalSize(),\n localTestBaseFunctionSetNeighbor.baseFunctionSet().space().map().maxLocalSize()),\n RangeFieldType(0.0)));\n } \/\/ check tmp local matrices\n\n \/\/ quadrature\n const unsigned int quadratureOrder =\n localEvaluation_.order()\n + std::max(localAnsatzBaseFunctionSetEntity.order(), localAnsatzBaseFunctionSetNeighbor.order())\n + std::max(localTestBaseFunctionSetEntity.order(), localTestBaseFunctionSetNeighbor.order());\n typedef Dune::QuadratureRules FaceQuadratureRules;\n typedef Dune::QuadratureRule FaceQuadratureType;\n const FaceQuadratureType& faceQuadrature = FaceQuadratureRules::rule(intersection.type(), 2 * quadratureOrder + 1);\n\n \/\/ do loop over all quadrature points\n const typename FaceQuadratureType::const_iterator quadratureEnd = faceQuadrature.end();\n for (typename FaceQuadratureType::const_iterator quadPoint = faceQuadrature.begin(); quadPoint != quadratureEnd;\n ++quadPoint) {\n \/\/ local coordinates\n typedef typename IntersectionType::LocalCoordinate LocalCoordinateType;\n const LocalCoordinateType x = quadPoint->position();\n\n \/\/ integration factors\n const double integrationFactor = intersection.geometry().integrationElement(x);\n const double quadratureWeight = quadPoint->weight();\n\n \/\/ evaluate the local operation\n localEvaluation_.evaluateLocal(localAnsatzBaseFunctionSetEntity,\n localTestBaseFunctionSetEntity,\n localAnsatzBaseFunctionSetNeighbor,\n localTestBaseFunctionSetNeighbor,\n intersection,\n x,\n tmpLocalMatrices[0], \/*EnEn*\/\n tmpLocalMatrices[1], \/*EnNe*\/\n tmpLocalMatrices[2], \/*NeEn*\/\n tmpLocalMatrices[3]); \/*NeNe*\/\n\n \/\/ compute integral (see below)\n addToIntegral(tmpLocalMatrices[0], integrationFactor, quadratureWeight, rowsEn, colsEn, localMatrixEnEn);\n addToIntegral(tmpLocalMatrices[1], integrationFactor, quadratureWeight, rowsEn, colsNe, localMatrixEnNe);\n addToIntegral(tmpLocalMatrices[2], integrationFactor, quadratureWeight, rowsNe, colsEn, localMatrixNeEn);\n addToIntegral(tmpLocalMatrices[3], integrationFactor, quadratureWeight, rowsNe, colsNe, localMatrixNeNe);\n } \/\/ done loop over all quadrature points\n } \/\/ void applyLocal\n\nprivate:\n InnerIntegral(const ThisType& other);\n ThisType& operator=(const ThisType&);\n\n template \n void addToIntegral(const Dune::DenseMatrix& localMatrix, const RangeFieldType& integrationFactor,\n const RangeFieldType& quadratureWeight, const unsigned int rows, const unsigned int cols,\n Dune::DenseMatrix& ret) const\n {\n \/\/ loop over all rows\n for (unsigned int i = 0; i < rows; ++i) {\n \/\/ get row\n const typename Dune::DenseMatrix::const_row_reference localMatrixRow = localMatrix[i];\n typename Dune::DenseMatrix::row_reference retRow = ret[i];\n \/\/ loop over all cols\n for (unsigned int j = 0; j < cols; ++j) {\n retRow[j] += localMatrixRow[j] * integrationFactor * quadratureWeight;\n } \/\/ loop over all cols\n } \/\/ loop over all rows\n } \/\/ end method addToIntegral\n\n const LocalEvaluationType& localEvaluation_;\n}; \/\/ end class InnerIntegral\n\n} \/\/ end namespace Codim1\n\n} \/\/ end namespace Local\n\n} \/\/ end namespace DiscreteOperator\n\n} \/\/ namespace Discretizations\n\n} \/\/ namespace Detailed\n\n} \/\/ end namespace Dune\n\n#endif \/\/ end DUNE_DETAILED_DISCRETIZATIONS_DISCRETEOPERATOR_LOCAL_CODIM1_INNERINTEGRAL_HH\n[discreteoperator.local.codim1.innerintegral] minor change in argument reordering\/**\n \\file innerintegral.hh\n **\/\n\n#ifndef DUNE_DETAILED_DISCRETIZATIONS_DISCRETEOPERATOR_LOCAL_CODIM1_INNERINTEGRAL_HH\n#define DUNE_DETAILED_DISCRETIZATIONS_DISCRETEOPERATOR_LOCAL_CODIM1_INNERINTEGRAL_HH\n\n\/\/ dune-common\n#include \n\n\/\/ dune-geometry\n#include \n\n\/\/ dune-stuff\n#include \n\nnamespace Dune {\n\nnamespace Detailed {\n\nnamespace Discretizations {\n\nnamespace DiscreteOperator {\n\nnamespace Local {\n\nnamespace Codim1 {\n\n\/**\n \\brief Local operator for inner intersections, i.e. those who have an inner codim 0 entity (Entity or En) and an\n outer codim 0 Neighboring entity (Neighbor or Ne).\n **\/\ntemplate \nclass InnerIntegral\n{\npublic:\n typedef LocalEvaluationImp LocalEvaluationType;\n\n typedef InnerIntegral ThisType;\n\n typedef typename LocalEvaluationType::FunctionSpaceType FunctionSpaceType;\n\n typedef typename FunctionSpaceType::RangeFieldType RangeFieldType;\n\n typedef typename FunctionSpaceType::DomainType DomainType;\n\n typedef typename FunctionSpaceType::DomainFieldType DomainFieldType;\n\n \/\/ template< class InducingDiscreteFunctionType >\n \/\/ class LocalFunctional\n \/\/ {\n \/\/ public:\n \/\/ typedef Dune::Functionals::DiscreteFunctional::Local::Codim0::IntegralInduced< ThisType,\n \/\/ InducingDiscreteFunctionType >\n \/\/ Type;\n \/\/ };\n\n InnerIntegral(const LocalEvaluationType& localEvaluation)\n : localEvaluation_(localEvaluation)\n {\n }\n\n const LocalEvaluationType& localEvaluation() const\n {\n return localEvaluation_;\n }\n\n \/\/ template< class InducingDiscreteFunctionType >\n \/\/ typename LocalFunctional< InducingDiscreteFunctionType >::Type\n \/\/ localFunctional( const InducingDiscreteFunctionType& inducingDiscreteFunction ) const\n \/\/ {\n \/\/ typedef Dune::Functionals::DiscreteFunctional::Local::Codim0::IntegralInduced< ThisType,\n \/\/ InducingDiscreteFunctionType >\n \/\/ LocalFunctionalType;\n\n \/\/ return LocalFunctionalType( *this, inducingDiscreteFunction );\n \/\/ } \/\/ end method localFunctional\n\n unsigned int numTmpObjectsRequired() const\n {\n return 4;\n }\n\n \/**\n \\todo Rename Entity -> En, Neighbor -> Ne\n **\/\n template \n void applyLocal(const LocalAnsatzBaseFunctionSetEntityType& localAnsatzBaseFunctionSetEntity,\n const LocalTestBaseFunctionSetEntityType& localTestBaseFunctionSetEntity,\n const LocalAnsatzBaseFunctionSetNeighborType& localAnsatzBaseFunctionSetNeighbor,\n const LocalTestBaseFunctionSetNeighborType& localTestBaseFunctionSetNeighbor,\n const IntersectionType& intersection, LocalMatrixType& localMatrixEnEn,\n LocalMatrixType& localMatrixEnNe, LocalMatrixType& localMatrixNeEn, LocalMatrixType& localMatrixNeNe,\n std::vector& tmpLocalMatrices) const\n {\n \/\/ preparations\n const unsigned int rowsEn = localAnsatzBaseFunctionSetEntity.size();\n const unsigned int rowsNe = localAnsatzBaseFunctionSetNeighbor.size();\n const unsigned int colsEn = localTestBaseFunctionSetEntity.size();\n const unsigned int colsNe = localTestBaseFunctionSetNeighbor.size();\n\n \/\/ make sure, that the target matrices are big enough\n assert(localMatrixEnEn.rows() >= rowsEn);\n assert(localMatrixEnEn.cols() >= colsEn);\n assert(localMatrixEnNe.rows() >= rowsEn);\n assert(localMatrixEnNe.cols() >= colsNe);\n assert(localMatrixNeEn.rows() >= rowsNe);\n assert(localMatrixNeEn.cols() >= colsEn);\n assert(localMatrixNeNe.rows() >= rowsNe);\n assert(localMatrixNeNe.cols() >= colsNe);\n\n \/\/ clear target matrices\n Dune::Stuff::Common::Matrix::clear(localMatrixEnEn);\n Dune::Stuff::Common::Matrix::clear(localMatrixEnNe);\n Dune::Stuff::Common::Matrix::clear(localMatrixNeEn);\n Dune::Stuff::Common::Matrix::clear(localMatrixNeNe);\n\n \/\/ check tmp local matrices\n if (tmpLocalMatrices.size() < numTmpObjectsRequired()) {\n tmpLocalMatrices.resize(\n numTmpObjectsRequired(),\n LocalMatrixType(std::max(localAnsatzBaseFunctionSetEntity.baseFunctionSet().space().map().maxLocalSize(),\n localAnsatzBaseFunctionSetNeighbor.baseFunctionSet().space().map().maxLocalSize()),\n std::max(localTestBaseFunctionSetEntity.baseFunctionSet().space().map().maxLocalSize(),\n localTestBaseFunctionSetNeighbor.baseFunctionSet().space().map().maxLocalSize()),\n RangeFieldType(0.0)));\n } \/\/ check tmp local matrices\n\n \/\/ quadrature\n const unsigned int quadratureOrder =\n localEvaluation_.order()\n + std::max(localAnsatzBaseFunctionSetEntity.order(), localAnsatzBaseFunctionSetNeighbor.order())\n + std::max(localTestBaseFunctionSetEntity.order(), localTestBaseFunctionSetNeighbor.order());\n typedef Dune::QuadratureRules FaceQuadratureRules;\n typedef Dune::QuadratureRule FaceQuadratureType;\n const FaceQuadratureType& faceQuadrature = FaceQuadratureRules::rule(intersection.type(), 2 * quadratureOrder + 1);\n\n \/\/ do loop over all quadrature points\n for (typename FaceQuadratureType::const_iterator quadPoint = faceQuadrature.begin();\n quadPoint != faceQuadrature.end();\n ++quadPoint) {\n \/\/ local coordinates\n typedef typename IntersectionType::LocalCoordinate LocalCoordinateType;\n const LocalCoordinateType x = quadPoint->position();\n\n \/\/ integration factors\n const double integrationFactor = intersection.geometry().integrationElement(x);\n const double quadratureWeight = quadPoint->weight();\n\n \/\/ evaluate the local operation\n localEvaluation_.evaluateLocal(localAnsatzBaseFunctionSetEntity,\n localTestBaseFunctionSetEntity,\n localAnsatzBaseFunctionSetNeighbor,\n localTestBaseFunctionSetNeighbor,\n intersection,\n x,\n tmpLocalMatrices[0], \/*EnEn*\/\n tmpLocalMatrices[1], \/*EnNe*\/\n tmpLocalMatrices[2], \/*NeEn*\/\n tmpLocalMatrices[3]); \/*NeNe*\/\n\n \/\/ compute integral (see below)\n addToIntegral(tmpLocalMatrices[0], integrationFactor, quadratureWeight, rowsEn, colsEn, localMatrixEnEn);\n addToIntegral(tmpLocalMatrices[1], integrationFactor, quadratureWeight, rowsEn, colsNe, localMatrixEnNe);\n addToIntegral(tmpLocalMatrices[2], integrationFactor, quadratureWeight, rowsNe, colsEn, localMatrixNeEn);\n addToIntegral(tmpLocalMatrices[3], integrationFactor, quadratureWeight, rowsNe, colsNe, localMatrixNeNe);\n } \/\/ done loop over all quadrature points\n } \/\/ void applyLocal\n\nprivate:\n InnerIntegral(const ThisType& other);\n ThisType& operator=(const ThisType&);\n\n template \n void addToIntegral(const Dune::DenseMatrix& localMatrix, const RangeFieldType& integrationFactor,\n const RangeFieldType& quadratureWeight, const unsigned int rows, const unsigned int cols,\n Dune::DenseMatrix& ret) const\n {\n \/\/ loop over all rows\n for (unsigned int i = 0; i < rows; ++i) {\n \/\/ get row\n const typename Dune::DenseMatrix::const_row_reference localMatrixRow = localMatrix[i];\n typename Dune::DenseMatrix::row_reference retRow = ret[i];\n \/\/ loop over all cols\n for (unsigned int j = 0; j < cols; ++j) {\n retRow[j] += localMatrixRow[j] * integrationFactor * quadratureWeight;\n } \/\/ loop over all cols\n } \/\/ loop over all rows\n } \/\/ end method addToIntegral\n\n const LocalEvaluationType& localEvaluation_;\n}; \/\/ end class InnerIntegral\n\n} \/\/ end namespace Codim1\n\n} \/\/ end namespace Local\n\n} \/\/ end namespace DiscreteOperator\n\n} \/\/ namespace Discretizations\n\n} \/\/ namespace Detailed\n\n} \/\/ end namespace Dune\n\n#endif \/\/ end DUNE_DETAILED_DISCRETIZATIONS_DISCRETEOPERATOR_LOCAL_CODIM1_INNERINTEGRAL_HH\n<|endoftext|>"} {"text":"\/\/ NoteTrainer (c) 2016 Andrey Fidrya. MIT license. See LICENSE for more information.\n\n#include \n#include \"Note.h\"\n#include \"Utils\/Utils.h\"\n\nNote::Note(Note::Pitch pitch, int octave)\n : pitch_(pitch)\n , octave_(octave)\n{\n\n}\n\nNote Note::noteFromKey(int key)\n{\n Note note;\n note.setPitch((Note::Pitch)(key % 12));\n note.setOctave(-1 + key \/ 12);\n return note;\n}\n\nQString Note::pitchName(Note::Pitch pitch)\n{\n switch (pitch) {\n case Pitch::C: return \"do\";\n case Pitch::Cis: return \"di\";\n case Pitch::D: return \"re\";\n case Pitch::Ees: return \"me\";\n case Pitch::E: return \"mi\";\n case Pitch::F: return \"fa\";\n case Pitch::Fis: return \"fi\";\n case Pitch::G: return \"so\";\n case Pitch::Aes: return \"lu\";\n case Pitch::A: return \"la\";\n case Pitch::Bes: return \"se\";\n case Pitch::B: return \"si\";\n default: break;\n }\n return \"?\";\n}\n\nQString Note::pitchName() const\n{\n return pitchName(pitch_);\n}\n\nbool Note::isFilled() const\n{\n switch (pitch_) {\n case Pitch::C:\n case Pitch::D:\n case Pitch::E:\n case Pitch::Fis:\n case Pitch::Aes:\n case Pitch::Bes:\n return true;\n default:\n break;\n }\n return false;\n}\n\nNote::Pitch Note::pitch() const\n{\n return pitch_;\n}\n\nvoid Note::setPitch(const Pitch &pitch)\n{\n pitch_ = pitch;\n}\n\nint Note::octave() const\n{\n return octave_;\n}\n\nvoid Note::setOctave(int octave)\n{\n octave_ = octave;\n}\n\nbool Note::operator==(const Note &other) const\n{\n return pitch_ == other.pitch_ && octave_ == other.octave_;\n}\n\nbool Note::operator<(const Note &other) const\n{\n return octave_ < other.octave_ ||\n (octave_ == other.octave_ && pitch_ < other.pitch_);\n}\n\nuint qHash(Note note)\n{\n return ::qHash((int)note.pitch()) ^ ::qHash(note.octave());\n}\n\n\nQTextStream &operator<<(QTextStream &s, const Note ¬e)\n{\n return s << \"{ octave: \" << (int)note.octave() << \", pitch: \" << (int)note.pitch() << \" }\";\n}\nChange QHashFunctions include to backwards-compatible QHash\/\/ NoteTrainer (c) 2016 Andrey Fidrya. MIT license. See LICENSE for more information.\n\n#include \n#include \"Note.h\"\n#include \"Utils\/Utils.h\"\n\nNote::Note(Note::Pitch pitch, int octave)\n : pitch_(pitch)\n , octave_(octave)\n{\n\n}\n\nNote Note::noteFromKey(int key)\n{\n Note note;\n note.setPitch((Note::Pitch)(key % 12));\n note.setOctave(-1 + key \/ 12);\n return note;\n}\n\nQString Note::pitchName(Note::Pitch pitch)\n{\n switch (pitch) {\n case Pitch::C: return \"do\";\n case Pitch::Cis: return \"di\";\n case Pitch::D: return \"re\";\n case Pitch::Ees: return \"me\";\n case Pitch::E: return \"mi\";\n case Pitch::F: return \"fa\";\n case Pitch::Fis: return \"fi\";\n case Pitch::G: return \"so\";\n case Pitch::Aes: return \"lu\";\n case Pitch::A: return \"la\";\n case Pitch::Bes: return \"se\";\n case Pitch::B: return \"si\";\n default: break;\n }\n return \"?\";\n}\n\nQString Note::pitchName() const\n{\n return pitchName(pitch_);\n}\n\nbool Note::isFilled() const\n{\n switch (pitch_) {\n case Pitch::C:\n case Pitch::D:\n case Pitch::E:\n case Pitch::Fis:\n case Pitch::Aes:\n case Pitch::Bes:\n return true;\n default:\n break;\n }\n return false;\n}\n\nNote::Pitch Note::pitch() const\n{\n return pitch_;\n}\n\nvoid Note::setPitch(const Pitch &pitch)\n{\n pitch_ = pitch;\n}\n\nint Note::octave() const\n{\n return octave_;\n}\n\nvoid Note::setOctave(int octave)\n{\n octave_ = octave;\n}\n\nbool Note::operator==(const Note &other) const\n{\n return pitch_ == other.pitch_ && octave_ == other.octave_;\n}\n\nbool Note::operator<(const Note &other) const\n{\n return octave_ < other.octave_ ||\n (octave_ == other.octave_ && pitch_ < other.pitch_);\n}\n\nuint qHash(Note note)\n{\n return ::qHash((int)note.pitch()) ^ ::qHash(note.octave());\n}\n\n\nQTextStream &operator<<(QTextStream &s, const Note ¬e)\n{\n return s << \"{ octave: \" << (int)note.octave() << \", pitch: \" << (int)note.pitch() << \" }\";\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"wrapping_paper_functions.hpp\"\n\nvoid run_part_one() {\n unsigned int area_sum = 0;\n std::string dimensions;\n while (std::cin >> dimensions) {\n Present present(dimensions);\n unsigned int area = calculate_wrapping_paper_area(present);\n std::cout << area << std::endl;\n area_sum += area;\n }\n std::cout << area_sum << std::endl;\n\n}\nvoid run_part_two() {\n}\n\nint main(int argc, char* argv[]) {\n if (argc > 1) {\n if (std::string(argv[1]) == \"--part_two\") {\n run_part_two();\n } else {\n std::cout << \"Usage: day2 [--part_two]\" << std::endl;\n return -1;\n }\n } else {\n run_part_one();\n }\n}\nadded calculation of ribbon length to main function#include \n#include \n\n#include \"wrapping_paper_functions.hpp\"\n\nvoid run_part_one() {\n unsigned int area_sum = 0;\n std::string dimensions;\n while (std::cin >> dimensions) {\n Present present(dimensions);\n unsigned int area = calculate_wrapping_paper_area(present);\n std::cout << area << std::endl;\n area_sum += area;\n }\n std::cout << area_sum << std::endl;\n\n}\nvoid run_part_two() {\n unsigned int total_length = 0;\n std::string dimensions;\n while (std::cin >> dimensions) {\n Present present(dimensions);\n unsigned int length = calculate_ribbon_length(present);\n std::cout << length << std::endl;\n total_length += length;\n }\n std::cout << total_length << std::endl;\n}\n\n\nint main(int argc, char* argv[]) {\n if (argc > 1) {\n if (std::string(argv[1]) == \"--part_two\") {\n run_part_two();\n } else {\n std::cout << \"Usage: day2 [--part_two]\" << std::endl;\n return -1;\n }\n } else {\n run_part_one();\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) , Arm Limited and affiliates.\n * SPDX-License-Identifier: Apache-2.0\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \"nsapi_types.h\"\n#include \"ATHandler.h\"\n#include \"EventQueue.h\"\n#include \"ATHandler_stub.h\"\n\nusing namespace mbed;\nusing namespace events;\n\n#include \"CellularLog.h\"\n\nconst int DEFAULT_AT_TIMEOUT = 1000; \/\/ at default timeout in milliseconds\n\nnsapi_error_t ATHandler_stub::nsapi_error_value = 0;\nuint8_t ATHandler_stub::nsapi_error_ok_counter = 0;\nint ATHandler_stub::int_value = -1;\nint ATHandler_stub::ref_count = 0;\nint ATHandler_stub::timeout = 0;\nbool ATHandler_stub::default_timeout = 0;\nbool ATHandler_stub::debug_on = 0;\nssize_t ATHandler_stub::ssize_value = 0;\nconst char *ATHandler_stub::read_string_value = NULL;\nsize_t ATHandler_stub::size_value = 0;\nsize_t ATHandler_stub::return_given_size = false;\nbool ATHandler_stub::bool_value = false;\nuint8_t ATHandler_stub::uint8_value = 0;\nFileHandle_stub *ATHandler_stub::fh_value = NULL;\ndevice_err_t ATHandler_stub::device_err_value;\nbool ATHandler_stub::call_immediately = false;\nuint8_t ATHandler_stub::resp_info_true_counter = false;\nuint8_t ATHandler_stub::info_elem_true_counter = false;\nint ATHandler_stub::int_valid_count_table[kRead_int_table_size];\nint ATHandler_stub::int_count = kRead_int_table_size;\nbool ATHandler_stub::process_oob_urc = false;\n\nint ATHandler_stub::read_string_index = kRead_string_table_size;\nconst char *ATHandler_stub::read_string_table[kRead_string_table_size];\nint ATHandler_stub::resp_stop_success_count = kResp_stop_count_default;\nint ATHandler_stub::urc_amount = 0;\nmbed::Callback ATHandler_stub::callback[kATHandler_urc_table_max_size];\nchar *ATHandler_stub::urc_string_table[kATHandler_urc_table_max_size];\n\nATHandler::ATHandler(FileHandle *fh, EventQueue &queue, int timeout, const char *output_delimiter, uint16_t send_delay) :\n _nextATHandler(0),\n _fileHandle(fh),\n _queue(queue)\n{\n ATHandler_stub::ref_count = 1;\n\n ATHandler_stub::process_oob_urc = false;\n ATHandler_stub::urc_amount = 0;\n int i=0;\n while (i < kATHandler_urc_table_max_size) {\n ATHandler_stub::callback[i] = NULL;\n ATHandler_stub::urc_string_table[i++] = NULL;\n }\n}\n\nvoid ATHandler::set_debug(bool debug_on)\n{\n ATHandler_stub::debug_on = debug_on;\n}\n\nATHandler::~ATHandler()\n{\n ATHandler_stub::ref_count = kATHandler_destructor_ref_ount;\n\n int i=0;\n while (i < kATHandler_urc_table_max_size) {\n if (ATHandler_stub::urc_string_table[i]) {\n delete [] ATHandler_stub::urc_string_table[i];\n i++;\n } else {\n break;\n }\n }\n}\n\nvoid ATHandler::inc_ref_count()\n{\n ATHandler_stub::ref_count++;\n}\n\nvoid ATHandler::dec_ref_count()\n{\n ATHandler_stub::ref_count--;\n}\n\nint ATHandler::get_ref_count()\n{\n return ATHandler_stub::ref_count;\n}\n\nFileHandle *ATHandler::get_file_handle()\n{\n return ATHandler_stub::fh_value;\n}\n\nvoid ATHandler::set_file_handle(FileHandle *fh)\n{\n}\n\nnsapi_error_t ATHandler::set_urc_handler(const char *urc, mbed::Callback cb)\n{\n if (ATHandler_stub::urc_amount < kATHandler_urc_table_max_size) {\n ATHandler_stub::callback[ATHandler_stub::urc_amount] = cb;\n ATHandler_stub::urc_string_table[ATHandler_stub::urc_amount] = new char[kATHandler_urc_string_max_size];\n if (urc) {\n int bytes_to_copy = strlen(urc) < kATHandler_urc_string_max_size ? strlen(urc) : kATHandler_urc_string_max_size;\n memcpy(ATHandler_stub::urc_string_table[ATHandler_stub::urc_amount], urc, bytes_to_copy);\n }\n ATHandler_stub::urc_amount++;\n } else {\n ATHandler_stub::callback[0] = cb;\n MBED_ASSERT(\"ATHandler URC amount limit reached\");\n }\n if (ATHandler_stub::call_immediately) {\n cb();\n }\n return ATHandler_stub::nsapi_error_value;\n}\n\nvoid ATHandler::remove_urc_handler(const char *prefix)\n{\n}\n\nnsapi_error_t ATHandler::get_last_error() const\n{\n if (ATHandler_stub::nsapi_error_ok_counter) {\n ATHandler_stub::nsapi_error_ok_counter--;\n return NSAPI_ERROR_OK;\n }\n return ATHandler_stub::nsapi_error_value;\n}\n\nvoid ATHandler::lock()\n{\n}\n\nvoid ATHandler::unlock()\n{\n}\n\nnsapi_error_t ATHandler::unlock_return_error()\n{\n return ATHandler_stub::nsapi_error_value;\n}\n\nvoid ATHandler::set_at_timeout(uint32_t timeout_milliseconds, bool default_timeout)\n{\n ATHandler_stub::timeout = timeout_milliseconds;\n ATHandler_stub::default_timeout = default_timeout;\n}\n\nvoid ATHandler::restore_at_timeout()\n{\n}\n\nvoid ATHandler::process_oob()\n{\n if (ATHandler_stub::process_oob_urc) {\n int i = 0;\n while (i < ATHandler_stub::urc_amount) {\n if (ATHandler_stub::read_string_index >= 0) {\n if (!memcmp(ATHandler_stub::urc_string_table[i],\n ATHandler_stub::read_string_table[ATHandler_stub::read_string_index],\n strlen(ATHandler_stub::urc_string_table[i]))) {\n ATHandler_stub::callback[i]();\n break;\n }\n }\n i++;\n }\n }\n}\n\nvoid ATHandler::clear_error()\n{\n ATHandler_stub::nsapi_error_ok_counter++;\n}\n\nvoid ATHandler::skip_param(uint32_t count)\n{\n\n}\n\nvoid ATHandler::skip_param(ssize_t len, uint32_t count)\n{\n}\n\nssize_t ATHandler::read_bytes(uint8_t *buf, size_t len)\n{\n return ATHandler_stub::ssize_value;\n}\n\nssize_t ATHandler::read_string(char *buf, size_t size, bool read_even_stop_tag)\n{\n\n if (ATHandler_stub::read_string_index == kRead_string_table_size) {\n if (ATHandler_stub::read_string_value && ATHandler_stub::ssize_value >= 0) {\n memcpy(buf, ATHandler_stub::read_string_value, ATHandler_stub::ssize_value + 1);\n buf[ATHandler_stub::ssize_value] = '\\0';\n }\n return ATHandler_stub::ssize_value;\n }\n\n ATHandler_stub::read_string_index--;\n if (ATHandler_stub::read_string_index >= 0) {\n const char *tmp = ATHandler_stub::read_string_table[ATHandler_stub::read_string_index];\n ssize_t len = strlen(tmp);\n memcpy(buf, tmp, len + 1);\n buf[len] = '\\0';\n return len;\n }\n\n ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR;\n return -1;\n}\n\nint32_t ATHandler::read_int()\n{\n if (ATHandler_stub::nsapi_error_value != NSAPI_ERROR_OK) {\n return -1;\n }\n\n if (ATHandler_stub::int_count == kRead_int_table_size) {\n return ATHandler_stub::int_value;\n }\n\n \/\/printf(\"ATHandler_stub::int_count: %d\", ATHandler_stub::int_count);\n ATHandler_stub::int_count--;\n if (ATHandler_stub::int_count < kRead_int_table_size && ATHandler_stub::int_count >= 0) {\n return ATHandler_stub::int_valid_count_table[ATHandler_stub::int_count];\n }\n\n ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR;\n return -1;\n}\n\nvoid ATHandler::set_delimiter(char delimiter)\n{\n}\n\nvoid ATHandler::set_default_delimiter()\n{\n}\n\nvoid ATHandler::set_stop_tag(const char *stop_tag_seq)\n{\n}\n\nint ATHandler::get_3gpp_error()\n{\n return ATHandler_stub::int_value;\n}\n\nvoid ATHandler::resp_start(const char *prefix, bool stop)\n{\n}\n\nbool ATHandler::info_resp()\n{\n if (ATHandler_stub::resp_info_true_counter) {\n ATHandler_stub::resp_info_true_counter--;\n return true;\n }\n return ATHandler_stub::bool_value;\n}\n\nbool ATHandler::info_elem(char start_tag)\n{\n if (ATHandler_stub::info_elem_true_counter) {\n ATHandler_stub::info_elem_true_counter--;\n return true;\n }\n return ATHandler_stub::bool_value;\n}\n\nbool ATHandler::consume_to_stop_tag()\n{\n return ATHandler_stub::bool_value;\n}\n\nvoid ATHandler::resp_stop()\n{\n if (ATHandler_stub::resp_stop_success_count > 0) {\n ATHandler_stub::resp_stop_success_count--;\n return;\n }\n ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR;\n}\n\nvoid ATHandler::cmd_start(const char *cmd)\n{\n}\n\nvoid ATHandler::write_int(int32_t param)\n{\n}\n\nvoid ATHandler::write_string(const char *param, bool useQuotations)\n{\n}\n\nsize_t ATHandler::write_bytes(const uint8_t *param, size_t len)\n{\n if (ATHandler_stub::return_given_size) {\n return len;\n }\n return ATHandler_stub::size_value;\n}\n\nvoid ATHandler::cmd_stop()\n{\n}\n\nvoid ATHandler::cmd_stop_read_resp()\n{\n cmd_stop();\n resp_start();\n resp_stop();\n}\n\ndevice_err_t ATHandler::get_last_device_error() const\n{\n return ATHandler_stub::device_err_value;\n}\n\nvoid ATHandler::flush()\n{\n\n}\ncellular: registration status change astyle fix\/*\n * Copyright (c) , Arm Limited and affiliates.\n * SPDX-License-Identifier: Apache-2.0\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \"nsapi_types.h\"\n#include \"ATHandler.h\"\n#include \"EventQueue.h\"\n#include \"ATHandler_stub.h\"\n\nusing namespace mbed;\nusing namespace events;\n\n#include \"CellularLog.h\"\n\nconst int DEFAULT_AT_TIMEOUT = 1000; \/\/ at default timeout in milliseconds\n\nnsapi_error_t ATHandler_stub::nsapi_error_value = 0;\nuint8_t ATHandler_stub::nsapi_error_ok_counter = 0;\nint ATHandler_stub::int_value = -1;\nint ATHandler_stub::ref_count = 0;\nint ATHandler_stub::timeout = 0;\nbool ATHandler_stub::default_timeout = 0;\nbool ATHandler_stub::debug_on = 0;\nssize_t ATHandler_stub::ssize_value = 0;\nconst char *ATHandler_stub::read_string_value = NULL;\nsize_t ATHandler_stub::size_value = 0;\nsize_t ATHandler_stub::return_given_size = false;\nbool ATHandler_stub::bool_value = false;\nuint8_t ATHandler_stub::uint8_value = 0;\nFileHandle_stub *ATHandler_stub::fh_value = NULL;\ndevice_err_t ATHandler_stub::device_err_value;\nbool ATHandler_stub::call_immediately = false;\nuint8_t ATHandler_stub::resp_info_true_counter = false;\nuint8_t ATHandler_stub::info_elem_true_counter = false;\nint ATHandler_stub::int_valid_count_table[kRead_int_table_size];\nint ATHandler_stub::int_count = kRead_int_table_size;\nbool ATHandler_stub::process_oob_urc = false;\n\nint ATHandler_stub::read_string_index = kRead_string_table_size;\nconst char *ATHandler_stub::read_string_table[kRead_string_table_size];\nint ATHandler_stub::resp_stop_success_count = kResp_stop_count_default;\nint ATHandler_stub::urc_amount = 0;\nmbed::Callback ATHandler_stub::callback[kATHandler_urc_table_max_size];\nchar *ATHandler_stub::urc_string_table[kATHandler_urc_table_max_size];\n\nATHandler::ATHandler(FileHandle *fh, EventQueue &queue, int timeout, const char *output_delimiter, uint16_t send_delay) :\n _nextATHandler(0),\n _fileHandle(fh),\n _queue(queue)\n{\n ATHandler_stub::ref_count = 1;\n\n ATHandler_stub::process_oob_urc = false;\n ATHandler_stub::urc_amount = 0;\n int i = 0;\n while (i < kATHandler_urc_table_max_size) {\n ATHandler_stub::callback[i] = NULL;\n ATHandler_stub::urc_string_table[i++] = NULL;\n }\n}\n\nvoid ATHandler::set_debug(bool debug_on)\n{\n ATHandler_stub::debug_on = debug_on;\n}\n\nATHandler::~ATHandler()\n{\n ATHandler_stub::ref_count = kATHandler_destructor_ref_ount;\n\n int i = 0;\n while (i < kATHandler_urc_table_max_size) {\n if (ATHandler_stub::urc_string_table[i]) {\n delete [] ATHandler_stub::urc_string_table[i];\n i++;\n } else {\n break;\n }\n }\n}\n\nvoid ATHandler::inc_ref_count()\n{\n ATHandler_stub::ref_count++;\n}\n\nvoid ATHandler::dec_ref_count()\n{\n ATHandler_stub::ref_count--;\n}\n\nint ATHandler::get_ref_count()\n{\n return ATHandler_stub::ref_count;\n}\n\nFileHandle *ATHandler::get_file_handle()\n{\n return ATHandler_stub::fh_value;\n}\n\nvoid ATHandler::set_file_handle(FileHandle *fh)\n{\n}\n\nnsapi_error_t ATHandler::set_urc_handler(const char *urc, mbed::Callback cb)\n{\n if (ATHandler_stub::urc_amount < kATHandler_urc_table_max_size) {\n ATHandler_stub::callback[ATHandler_stub::urc_amount] = cb;\n ATHandler_stub::urc_string_table[ATHandler_stub::urc_amount] = new char[kATHandler_urc_string_max_size];\n if (urc) {\n int bytes_to_copy = strlen(urc) < kATHandler_urc_string_max_size ? strlen(urc) : kATHandler_urc_string_max_size;\n memcpy(ATHandler_stub::urc_string_table[ATHandler_stub::urc_amount], urc, bytes_to_copy);\n }\n ATHandler_stub::urc_amount++;\n } else {\n ATHandler_stub::callback[0] = cb;\n MBED_ASSERT(\"ATHandler URC amount limit reached\");\n }\n if (ATHandler_stub::call_immediately) {\n cb();\n }\n return ATHandler_stub::nsapi_error_value;\n}\n\nvoid ATHandler::remove_urc_handler(const char *prefix)\n{\n}\n\nnsapi_error_t ATHandler::get_last_error() const\n{\n if (ATHandler_stub::nsapi_error_ok_counter) {\n ATHandler_stub::nsapi_error_ok_counter--;\n return NSAPI_ERROR_OK;\n }\n return ATHandler_stub::nsapi_error_value;\n}\n\nvoid ATHandler::lock()\n{\n}\n\nvoid ATHandler::unlock()\n{\n}\n\nnsapi_error_t ATHandler::unlock_return_error()\n{\n return ATHandler_stub::nsapi_error_value;\n}\n\nvoid ATHandler::set_at_timeout(uint32_t timeout_milliseconds, bool default_timeout)\n{\n ATHandler_stub::timeout = timeout_milliseconds;\n ATHandler_stub::default_timeout = default_timeout;\n}\n\nvoid ATHandler::restore_at_timeout()\n{\n}\n\nvoid ATHandler::process_oob()\n{\n if (ATHandler_stub::process_oob_urc) {\n int i = 0;\n while (i < ATHandler_stub::urc_amount) {\n if (ATHandler_stub::read_string_index >= 0) {\n if (!memcmp(ATHandler_stub::urc_string_table[i],\n ATHandler_stub::read_string_table[ATHandler_stub::read_string_index],\n strlen(ATHandler_stub::urc_string_table[i]))) {\n ATHandler_stub::callback[i]();\n break;\n }\n }\n i++;\n }\n }\n}\n\nvoid ATHandler::clear_error()\n{\n ATHandler_stub::nsapi_error_ok_counter++;\n}\n\nvoid ATHandler::skip_param(uint32_t count)\n{\n\n}\n\nvoid ATHandler::skip_param(ssize_t len, uint32_t count)\n{\n}\n\nssize_t ATHandler::read_bytes(uint8_t *buf, size_t len)\n{\n return ATHandler_stub::ssize_value;\n}\n\nssize_t ATHandler::read_string(char *buf, size_t size, bool read_even_stop_tag)\n{\n\n if (ATHandler_stub::read_string_index == kRead_string_table_size) {\n if (ATHandler_stub::read_string_value && ATHandler_stub::ssize_value >= 0) {\n memcpy(buf, ATHandler_stub::read_string_value, ATHandler_stub::ssize_value + 1);\n buf[ATHandler_stub::ssize_value] = '\\0';\n }\n return ATHandler_stub::ssize_value;\n }\n\n ATHandler_stub::read_string_index--;\n if (ATHandler_stub::read_string_index >= 0) {\n const char *tmp = ATHandler_stub::read_string_table[ATHandler_stub::read_string_index];\n ssize_t len = strlen(tmp);\n memcpy(buf, tmp, len + 1);\n buf[len] = '\\0';\n return len;\n }\n\n ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR;\n return -1;\n}\n\nint32_t ATHandler::read_int()\n{\n if (ATHandler_stub::nsapi_error_value != NSAPI_ERROR_OK) {\n return -1;\n }\n\n if (ATHandler_stub::int_count == kRead_int_table_size) {\n return ATHandler_stub::int_value;\n }\n\n \/\/printf(\"ATHandler_stub::int_count: %d\", ATHandler_stub::int_count);\n ATHandler_stub::int_count--;\n if (ATHandler_stub::int_count < kRead_int_table_size && ATHandler_stub::int_count >= 0) {\n return ATHandler_stub::int_valid_count_table[ATHandler_stub::int_count];\n }\n\n ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR;\n return -1;\n}\n\nvoid ATHandler::set_delimiter(char delimiter)\n{\n}\n\nvoid ATHandler::set_default_delimiter()\n{\n}\n\nvoid ATHandler::set_stop_tag(const char *stop_tag_seq)\n{\n}\n\nint ATHandler::get_3gpp_error()\n{\n return ATHandler_stub::int_value;\n}\n\nvoid ATHandler::resp_start(const char *prefix, bool stop)\n{\n}\n\nbool ATHandler::info_resp()\n{\n if (ATHandler_stub::resp_info_true_counter) {\n ATHandler_stub::resp_info_true_counter--;\n return true;\n }\n return ATHandler_stub::bool_value;\n}\n\nbool ATHandler::info_elem(char start_tag)\n{\n if (ATHandler_stub::info_elem_true_counter) {\n ATHandler_stub::info_elem_true_counter--;\n return true;\n }\n return ATHandler_stub::bool_value;\n}\n\nbool ATHandler::consume_to_stop_tag()\n{\n return ATHandler_stub::bool_value;\n}\n\nvoid ATHandler::resp_stop()\n{\n if (ATHandler_stub::resp_stop_success_count > 0) {\n ATHandler_stub::resp_stop_success_count--;\n return;\n }\n ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR;\n}\n\nvoid ATHandler::cmd_start(const char *cmd)\n{\n}\n\nvoid ATHandler::write_int(int32_t param)\n{\n}\n\nvoid ATHandler::write_string(const char *param, bool useQuotations)\n{\n}\n\nsize_t ATHandler::write_bytes(const uint8_t *param, size_t len)\n{\n if (ATHandler_stub::return_given_size) {\n return len;\n }\n return ATHandler_stub::size_value;\n}\n\nvoid ATHandler::cmd_stop()\n{\n}\n\nvoid ATHandler::cmd_stop_read_resp()\n{\n cmd_stop();\n resp_start();\n resp_stop();\n}\n\ndevice_err_t ATHandler::get_last_device_error() const\n{\n return ATHandler_stub::device_err_value;\n}\n\nvoid ATHandler::flush()\n{\n\n}\n<|endoftext|>"} {"text":"#ifndef ITER_ACCUMULATE_H_\n#define ITER_ACCUMULATE_H_\n\n#include \"internal\/iterbase.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace iter {\n namespace impl {\n template \n class Accumulator;\n }\n\n template \n impl::Accumulator accumulate(\n Container&&, AccumulateFunc);\n\n template \n impl::Accumulator, AccumulateFunc> accumulate(\n std::initializer_list, AccumulateFunc);\n}\n\ntemplate \nclass iter::impl::Accumulator {\n private:\n Container container;\n AccumulateFunc accumulate_func;\n\n friend Accumulator iter::accumulate(\n Container&&, AccumulateFunc);\n\n template \n friend Accumulator, AF> iter::accumulate(\n std::initializer_list, AF);\n\n using AccumVal = std::remove_reference_t, iterator_deref)>>;\n\n Accumulator(Container&& in_container, AccumulateFunc in_accumulate_func)\n : container(std::forward(in_container)),\n accumulate_func(in_accumulate_func) {}\n\n public:\n Accumulator(Accumulator&&) = default;\n\n class Iterator : public std::iterator {\n private:\n iterator_type sub_iter;\n iterator_type sub_end;\n AccumulateFunc* accumulate_func;\n std::unique_ptr acc_val;\n\n public:\n Iterator(iterator_type&& iter, iterator_type&& end,\n AccumulateFunc& in_accumulate_fun)\n : sub_iter{std::move(iter)},\n sub_end{std::move(end)},\n accumulate_func(&in_accumulate_fun),\n \/\/ only get first value if not an end iterator\n acc_val{!(iter != end) ? nullptr : new AccumVal(*iter)} {}\n\n Iterator(const Iterator& other)\n : sub_iter{other.sub_iter},\n sub_end{other.sub_end},\n accumulate_func{other.accumulate_func},\n acc_val{other.acc_val ? new AccumVal(*other.acc_val) : nullptr} {}\n\n Iterator& operator=(const Iterator& other) {\n if (this == &other) { return *this; }\n this->sub_iter = other.sub_iter;\n this->sub_end = other.sub_end;\n this->accumulate_func = other.accumulate_func;\n this->acc_val.reset(\n other.acc_val ? new AccumVal(*other.acc_val) : nullptr);\n return *this;\n }\n\n Iterator(Iterator&&) = default;\n Iterator& operator=(Iterator&&) = default;\n\n const AccumVal& operator*() const {\n return *this->acc_val;\n }\n\n const AccumVal* operator->() const {\n return this->acc_val.get();\n }\n\n Iterator& operator++() {\n ++this->sub_iter;\n if (this->sub_iter != this->sub_end) {\n *this->acc_val = (*accumulate_func)(*this->acc_val, *this->sub_iter);\n }\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->sub_iter != other.sub_iter;\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n };\n\n Iterator begin() {\n return {std::begin(this->container), std::end(this->container),\n this->accumulate_func};\n }\n\n Iterator end() {\n return {std::end(this->container), std::end(this->container),\n this->accumulate_func};\n }\n};\n\ntemplate \niter::impl::Accumulator iter::accumulate(\n Container&& container, AccumulateFunc accumulate_func) {\n return {std::forward(container), accumulate_func};\n}\n\ntemplate \niter::impl::Accumulator, AccumulateFunc>\niter::accumulate(std::initializer_list il, AccumulateFunc accumulate_func) {\n return {std::move(il), accumulate_func};\n}\n\nnamespace iter {\n template \n auto accumulate(Container&& container) -> decltype(accumulate(\n std::forward(container),\n std::plus>>{})) {\n return accumulate(std::forward(container),\n std::plus>>{});\n }\n\n template \n auto accumulate(std::initializer_list il)\n -> decltype(accumulate(std::move(il), std::plus{})) {\n return accumulate(std::move(il), std::plus{});\n }\n}\n\n#endif\ndrops init list support from accumulate#ifndef ITER_ACCUMULATE_H_\n#define ITER_ACCUMULATE_H_\n\n#include \"internal\/iterbase.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace iter {\n namespace impl {\n template \n class Accumulator;\n }\n\n template \n impl::Accumulator accumulate(\n Container&&, AccumulateFunc);\n\n}\n\ntemplate \nclass iter::impl::Accumulator {\n private:\n Container container;\n AccumulateFunc accumulate_func;\n\n friend Accumulator iter::accumulate(\n Container&&, AccumulateFunc);\n\n using AccumVal = std::remove_reference_t, iterator_deref)>>;\n\n Accumulator(Container&& in_container, AccumulateFunc in_accumulate_func)\n : container(std::forward(in_container)),\n accumulate_func(in_accumulate_func) {}\n\n public:\n Accumulator(Accumulator&&) = default;\n\n class Iterator : public std::iterator {\n private:\n iterator_type sub_iter;\n iterator_type sub_end;\n AccumulateFunc* accumulate_func;\n std::unique_ptr acc_val;\n\n public:\n Iterator(iterator_type&& iter, iterator_type&& end,\n AccumulateFunc& in_accumulate_fun)\n : sub_iter{std::move(iter)},\n sub_end{std::move(end)},\n accumulate_func(&in_accumulate_fun),\n \/\/ only get first value if not an end iterator\n acc_val{!(iter != end) ? nullptr : new AccumVal(*iter)} {}\n\n Iterator(const Iterator& other)\n : sub_iter{other.sub_iter},\n sub_end{other.sub_end},\n accumulate_func{other.accumulate_func},\n acc_val{other.acc_val ? new AccumVal(*other.acc_val) : nullptr} {}\n\n Iterator& operator=(const Iterator& other) {\n if (this == &other) { return *this; }\n this->sub_iter = other.sub_iter;\n this->sub_end = other.sub_end;\n this->accumulate_func = other.accumulate_func;\n this->acc_val.reset(\n other.acc_val ? new AccumVal(*other.acc_val) : nullptr);\n return *this;\n }\n\n Iterator(Iterator&&) = default;\n Iterator& operator=(Iterator&&) = default;\n\n const AccumVal& operator*() const {\n return *this->acc_val;\n }\n\n const AccumVal* operator->() const {\n return this->acc_val.get();\n }\n\n Iterator& operator++() {\n ++this->sub_iter;\n if (this->sub_iter != this->sub_end) {\n *this->acc_val = (*accumulate_func)(*this->acc_val, *this->sub_iter);\n }\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->sub_iter != other.sub_iter;\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n };\n\n Iterator begin() {\n return {std::begin(this->container), std::end(this->container),\n this->accumulate_func};\n }\n\n Iterator end() {\n return {std::end(this->container), std::end(this->container),\n this->accumulate_func};\n }\n};\n\ntemplate \niter::impl::Accumulator iter::accumulate(\n Container&& container, AccumulateFunc accumulate_func) {\n return {std::forward(container), accumulate_func};\n}\n\nnamespace iter {\n template \n auto accumulate(Container&& container) -> decltype(accumulate(\n std::forward(container),\n std::plus>>{})) {\n return accumulate(std::forward(container),\n std::plus>>{});\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/MIT License\n\/\/Copyright(c) 2017 Patrick Laughrea\n#include \"parser.h\"\n\n\/\/#define DISABLE_IMPORT\n#ifndef DISABLE_IMPORT\n#include \"curl.h\"\n#endif\n#include \"errors.h\"\n#include \"patternsContainers.h\"\n#include \"WebssonUtils\/constants.h\"\n#include \"WebssonUtils\/utilsWebss.h\"\n\nusing namespace std;\nusing namespace webss;\n\nconst char ERROR_INPUT_DICTIONARY[] = \"dictionary can only have key-values\";\nconst char ERROR_INPUT_LIST[] = \"list can only have concrete value-onlys\";\nconst char ERROR_INPUT_TUPLE[] = \"tuple can only have concrete value-onlys or key-values\";\nconst char ERROR_INPUT_NAMESPACE[] = \"namespace can only have entity definitions\";\nconst char ERROR_INPUT_ENUM[] = \"enum can only have key-onlys\";\nconst char ERROR_INPUT_DOCUMENT[] = \"document can only have concrete value-onlys or key-values\";\n\nstring getItPosition(SmartIterator& it)\n{\n\treturn \"[ln \" + to_string(it.getLine()) + \", ch \" + to_string(it.getCharCount()) + \"]\";\n}\n\nstring getItCurrentChar(SmartIterator& it)\n{\n\tif (!it)\n\t\treturn string(\"\");\n\n\tstring out;\n\tout += \" '\";\n\tif (*it == '\\'' || *it == '\\\\')\n\t\tout += '\\\\';\n\tout = out + *it + \"' \";\n\n\tswitch (*it)\n\t{\n\tcase '~': out += \"(using namespace)\"; break;\n\tcase '!': out += \"(entity declaration)\"; break;\n\tcase '@': out += \"(import)\"; break;\n\tcase '#': out += \"(option)\"; break;\n\tcase '&': out += \"(self)\"; break;\n\tcase ':': out += \"(line string)\"; break;\n\tcase '\"': out += \"(cstring)\"; break;\n\tcase '?': out += \"(entity declaration)\"; break;\n\tcase '.': out += \"(scope)\"; break;\n\tcase '(': case ')':out += \"(parenthesis \/ round bracket)\"; break;\n\tcase '{': case '}': out += \"(brace \/ curly bracket)\"; break;\n\tcase '[': case ']': out += \"(square bracket)\"; break;\n\tcase '<': case '>': out += \"(angle bracket \/ chevron)\"; break;\n\tdefault:\n\t\tbreak;\n\t}\n\treturn out;\n}\n\nDictionary Parser::parseDictionary()\n{\n\treturn parseContainer(Dictionary(), [&](Dictionary& dict)\n\t{\n\t\tif (nextTag == Tag::C_STRING)\n\t\t\taddJsonKeyvalue(dict);\n\t\telse\n\t\t\tparseOtherValue(\n\t\t\t\tCaseKeyValue{ dict.addSafe(move(key), move(value)); },\n\t\t\t\tErrorKeyOnly(ERROR_INPUT_DICTIONARY),\n\t\t\t\tErrorValueOnly(ERROR_INPUT_DICTIONARY),\n\t\t\t\tErrorAbstractEntity(ERROR_INPUT_DICTIONARY));\n\t});\n}\n\nList Parser::parseList()\n{\n\treturn parseContainer(List(), [&](List& list)\n\t{\n\t\tlist.add(parseValueOnly());\n\t});\n}\n\nTuple Parser::parseTuple()\n{\n\treturn parseContainer(Tuple(), [&](Tuple& tuple)\n\t{\n\t\tparseOtherValue(\n\t\t\tCaseKeyValue{ tuple.addSafe(move(key), move(value)); },\n\t\t\tErrorKeyOnly(ERROR_INPUT_TUPLE),\n\t\t\tCaseValueOnly{ tuple.add(move(value)); },\n\t\t\tErrorAbstractEntity(ERROR_INPUT_TUPLE));\n\t});\n}\n\nList Parser::parseListText()\n{\n\treturn parseContainer(List(), [&](List& list)\n\t{\n\t\tlist.add(parseLineString());\n\t});\n}\nTuple Parser::parseTupleText()\n{\n\treturn parseContainer(Tuple(), [&](Tuple& tuple)\n\t{\n\t\ttuple.add(parseLineString());\n\t});\n}\n\nNamespace Parser::parseNamespace(const string& name, const Namespace& previousNamespace)\n{\n\treturn parseContainer(Namespace(name, previousNamespace), [&](Namespace& nspace)\n\t{\n\t\tswitch (*it)\n\t\t{\n\t\tcase CHAR_ABSTRACT_ENTITY:\n\t\t\t++it;\n\t\t\tnspace.addSafe(parseAbstractEntity(nspace));\n\t\t\tbreak;\n\t\tcase CHAR_CONCRETE_ENTITY:\n\t\t\t++it;\n\t\t\tnspace.addSafe(parseConcreteEntity());\n\t\t\tbreak;\n\t\tcase CHAR_SELF:\n\t\t\tskipJunkToTag(++it, Tag::START_TEMPLATE);\n\t\t\tnspace.addSafe(Entity(string(name), parseTemplateHead()));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow runtime_error(ERROR_INPUT_NAMESPACE);\n\t\t}\n\t});\n}\n\nEnum Parser::parseEnum(const string& name)\n{\n\treturn parseContainer(Enum(name), [&](Enum& tEnum)\n\t{\n\t\tparseOtherValue(\n\t\t\tErrorKeyValue(ERROR_INPUT_ENUM),\n\t\t\tCaseKeyOnly{ tEnum.add(move(key)); },\n\t\t\tErrorValueOnly(ERROR_INPUT_ENUM),\n\t\t\tErrorAbstractEntity(ERROR_INPUT_ENUM));\n\t});\n}\n\nDocument Parser::parseDocument()\n{\n\ttry\n\t{\n\t\tDocument doc;\n\t\tif (!containerEmpty() && !parseDocumentHead(doc.getHead(), Namespace::getEmptyInstance()))\n\t\t{\n\t\t\tdo\n\t\t\t\tparseOtherValue(\n\t\t\t\t\tCaseKeyValue{ doc.addSafe(move(key), move(value)); },\n\t\t\t\t\tErrorKeyOnly(ERROR_INPUT_DOCUMENT),\n\t\t\t\t\tCaseValueOnly{ doc.add(move(value)); },\n\t\t\t\t\tErrorAbstractEntity(ERROR_INPUT_DOCUMENT));\n\t\t\twhile (checkNextElement());\n\t\t}\n\t\treturn doc;\n\t}\n\tcatch (const exception& e)\n\t{\n\t\tthrow runtime_error(string(getItPosition(it) + ' ' + e.what() + getItCurrentChar(it)).c_str());\n\t}\n}\n\nbool Parser::parseDocumentHead(vector& docHead, const Namespace& nspace)\n{\n\tassert(it);\n\tdo\n\t{\n\t\tswitch (*it)\n\t\t{\n\t\tcase CHAR_ABSTRACT_ENTITY:\n\t\t{\n\t\t\t++it;\n\t\t\tauto ent = parseAbstractEntity(nspace);\n\t\t\tdocHead.push_back(ParamDocument::makeEntityAbstract(ent));\n\t\t\tents.addLocalSafe(move(ent));\n\t\t\tbreak;\n\t\t}\n\t\tcase CHAR_CONCRETE_ENTITY:\n\t\t{\n\t\t\t++it;\n\t\t\tauto ent = parseConcreteEntity();\n\t\t\tdocHead.push_back(ParamDocument::makeEntityConcrete(ent));\n\t\t\tents.addLocalSafe(move(ent));\n\t\t\tbreak;\n\t\t}\n\t\tcase CHAR_IMPORT:\n\t\t{\n\t\t\t++it;\n\t\t\tauto import = parseImport();\n\t\t\tdocHead.push_back(move(import));\n\t\t\tbreak;\n\t\t}\n\t\tcase CHAR_SCOPED_DOCUMENT:\n\t\t\t++it;\n\t\t\tparseScopedDocument(docHead);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn false;\n\t\t}\n\t} while (checkNextElement());\n\treturn true;\n}\n\nvoid Parser::parseScopedDocument(vector& docHead)\n{\n\tif (*skipJunkToValid(it) == OPEN_TEMPLATE)\n\t{\n\t\tContainerSwitcher switcher1(*this, ConType::TEMPLATE_HEAD, false);\n\t\tif (containerEmpty())\n\t\t\tthrow runtime_error(\"can't have empty scoped document head\");\n\n\t\tauto head = parseTemplateHeadScoped();\n\n\t\tskipJunkToTag(it, Tag::START_DICTIONARY);\n\t\tDocumentHead body;\n\n\t\tContainerSwitcher switcher2(*this, ConType::DICTIONARY, false);\n\t\tif (!containerEmpty())\n\t\t{\n\t\t\tParamDocumentIncluder includer(ents, head.getParameters());\n\t\t\tif (!parseDocumentHead(body, Namespace::getEmptyInstance()))\n\t\t\t\tthrow runtime_error(ERROR_UNEXPECTED);\n\t\t}\n\t\tdocHead.push_back(ScopedDocument{ move(head), move(body) });\n\t}\n\telse\n\t{\n\t\tconst auto& nspace = parseUsingNamespaceStatic();\n\n\t\t\/\/first check the namespace entity is accessible; if so it has to be removed since\n\t\t\/\/it'll no longer be necessary and an entity with the same name could be inside\n\t\tif (ParamDocumentIncluder::namespacePresentScope(ents, nspace))\n\t\t\tents.removeLocal(ents[nspace.getName()]);\n\n\t\tfor (const auto& ent : nspace)\n\t\t\tents.addLocalSafe(ent);\n\t}\n}\n\nImportedDocument Parser::parseImport()\n{\n#ifdef DISABLE_IMPORT\n\tthrow runtime_error(\"this parser cannot import documents\");\n#else\n\tnextTag = getTag(it);\n\tauto importName = parseValueOnly();\n\tif (!importName.isString())\n\t\tthrow runtime_error(\"import must reference a string\");\n\tImportedDocument import(move(importName));\n\tconst auto& link = import.getLink();\n\tif (!importedDocuments.hasEntity(link))\n\t{\n\t\ttry\n\t\t{\n\t\t\timportedDocuments.addLocalSafe(link, 0);\n\t\t\tImportSwitcher switcher(*this, SmartIterator(Curl().readWebDocument(link)));\n\t\t\tDocumentHead docHead;\n\t\t\tif (!containerEmpty() && !parseDocumentHead(docHead, Namespace::getEmptyInstance()))\n\t\t\t\tthrow runtime_error(ERROR_UNEXPECTED);\n\t\t}\n\t\tcatch (const exception& e)\n\t\t\t{ throw runtime_error(string(\"while parsing import, \") + e.what()); }\n\t}\n\treturn import;\n#endif\n}\n\nconst Namespace& Parser::parseUsingNamespaceStatic()\n{\n\tskipJunkToTag(it, Tag::NAME_START);\n\tauto nameType = parseNameType();\n\tif (nameType.type != NameType::ENTITY_ABSTRACT || !nameType.entity.getContent().isNamespace())\n\t\tthrow runtime_error(\"expected namespace\");\n\treturn nameType.entity.getContent().getNamespaceSafe();\n}Scoped names for namespace and enum\/\/MIT License\n\/\/Copyright(c) 2017 Patrick Laughrea\n#include \"parser.h\"\n\n\/\/#define DISABLE_IMPORT\n#ifndef DISABLE_IMPORT\n#include \"curl.h\"\n#endif\n#include \"errors.h\"\n#include \"patternsContainers.h\"\n#include \"WebssonUtils\/constants.h\"\n#include \"WebssonUtils\/utilsWebss.h\"\n\nusing namespace std;\nusing namespace webss;\n\nconst char ERROR_INPUT_DICTIONARY[] = \"dictionary can only have key-values\";\nconst char ERROR_INPUT_LIST[] = \"list can only have concrete value-onlys\";\nconst char ERROR_INPUT_TUPLE[] = \"tuple can only have concrete value-onlys or key-values\";\nconst char ERROR_INPUT_NAMESPACE[] = \"namespace can only have entity definitions\";\nconst char ERROR_INPUT_ENUM[] = \"enum can only have key-onlys\";\nconst char ERROR_INPUT_DOCUMENT[] = \"document can only have concrete value-onlys or key-values\";\n\nstring getItPosition(SmartIterator& it)\n{\n\treturn \"[ln \" + to_string(it.getLine()) + \", ch \" + to_string(it.getCharCount()) + \"]\";\n}\n\nstring getItCurrentChar(SmartIterator& it)\n{\n\tif (!it)\n\t\treturn string(\"\");\n\n\tstring out;\n\tout += \" '\";\n\tif (*it == '\\'' || *it == '\\\\')\n\t\tout += '\\\\';\n\tout = out + *it + \"' \";\n\n\tswitch (*it)\n\t{\n\tcase '~': out += \"(using namespace)\"; break;\n\tcase '!': out += \"(entity declaration)\"; break;\n\tcase '@': out += \"(import)\"; break;\n\tcase '#': out += \"(option)\"; break;\n\tcase '&': out += \"(self)\"; break;\n\tcase ':': out += \"(line string)\"; break;\n\tcase '\"': out += \"(cstring)\"; break;\n\tcase '?': out += \"(entity declaration)\"; break;\n\tcase '.': out += \"(scope)\"; break;\n\tcase '(': case ')':out += \"(parenthesis \/ round bracket)\"; break;\n\tcase '{': case '}': out += \"(brace \/ curly bracket)\"; break;\n\tcase '[': case ']': out += \"(square bracket)\"; break;\n\tcase '<': case '>': out += \"(angle bracket \/ chevron)\"; break;\n\tdefault:\n\t\tbreak;\n\t}\n\treturn out;\n}\n\nDictionary Parser::parseDictionary()\n{\n\treturn parseContainer(Dictionary(), [&](Dictionary& dict)\n\t{\n\t\tif (nextTag == Tag::C_STRING)\n\t\t\taddJsonKeyvalue(dict);\n\t\telse\n\t\t\tparseOtherValue(\n\t\t\t\tCaseKeyValue{ dict.addSafe(move(key), move(value)); },\n\t\t\t\tErrorKeyOnly(ERROR_INPUT_DICTIONARY),\n\t\t\t\tErrorValueOnly(ERROR_INPUT_DICTIONARY),\n\t\t\t\tErrorAbstractEntity(ERROR_INPUT_DICTIONARY));\n\t});\n}\n\nList Parser::parseList()\n{\n\treturn parseContainer(List(), [&](List& list)\n\t{\n\t\tlist.add(parseValueOnly());\n\t});\n}\n\nTuple Parser::parseTuple()\n{\n\treturn parseContainer(Tuple(), [&](Tuple& tuple)\n\t{\n\t\tparseOtherValue(\n\t\t\tCaseKeyValue{ tuple.addSafe(move(key), move(value)); },\n\t\t\tErrorKeyOnly(ERROR_INPUT_TUPLE),\n\t\t\tCaseValueOnly{ tuple.add(move(value)); },\n\t\t\tErrorAbstractEntity(ERROR_INPUT_TUPLE));\n\t});\n}\n\nList Parser::parseListText()\n{\n\treturn parseContainer(List(), [&](List& list)\n\t{\n\t\tlist.add(parseLineString());\n\t});\n}\nTuple Parser::parseTupleText()\n{\n\treturn parseContainer(Tuple(), [&](Tuple& tuple)\n\t{\n\t\ttuple.add(parseLineString());\n\t});\n}\n\nNamespace Parser::parseNamespace(const string& name, const Namespace& previousNamespace)\n{\n\treturn parseContainer(Namespace(name, previousNamespace), [&](Namespace& nspace)\n\t{\n\t\tswitch (*it)\n\t\t{\n\t\tcase CHAR_ABSTRACT_ENTITY:\n\t\t\t++it;\n\t\t\tnspace.addSafe(parseAbstractEntity(nspace));\n\t\t\tbreak;\n\t\tcase CHAR_CONCRETE_ENTITY:\n\t\t\t++it;\n\t\t\tnspace.addSafe(parseConcreteEntity());\n\t\t\tbreak;\n\t\tcase CHAR_SELF:\n\t\t\tskipJunkToTag(++it, Tag::START_TEMPLATE);\n\t\t\tnspace.addSafe(Entity(string(name), parseTemplateHead()));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow runtime_error(ERROR_INPUT_NAMESPACE);\n\t\t}\n\t});\n}\n\nEnum Parser::parseEnum(const string& name)\n{\n\treturn parseContainer(Enum(name), [&](Enum& tEnum)\n\t{\n\t\tif (nextTag != Tag::NAME_START)\n\t\t\tthrow runtime_error(ERROR_UNEXPECTED);\n\t\tauto name = parseName(it);\n\t\tif (isKeyword(name))\n\t\t\tthrow runtime_error(\"enum name can't be a keyword\");\n\t\ttEnum.addSafe(move(name));\n\t});\n}\n\nDocument Parser::parseDocument()\n{\n\ttry\n\t{\n\t\tDocument doc;\n\t\tif (!containerEmpty() && !parseDocumentHead(doc.getHead(), Namespace::getEmptyInstance()))\n\t\t{\n\t\t\tdo\n\t\t\t\tparseOtherValue(\n\t\t\t\t\tCaseKeyValue{ doc.addSafe(move(key), move(value)); },\n\t\t\t\t\tErrorKeyOnly(ERROR_INPUT_DOCUMENT),\n\t\t\t\t\tCaseValueOnly{ doc.add(move(value)); },\n\t\t\t\t\tErrorAbstractEntity(ERROR_INPUT_DOCUMENT));\n\t\t\twhile (checkNextElement());\n\t\t}\n\t\treturn doc;\n\t}\n\tcatch (const exception& e)\n\t{\n\t\tthrow runtime_error(string(getItPosition(it) + ' ' + e.what() + getItCurrentChar(it)).c_str());\n\t}\n}\n\nbool Parser::parseDocumentHead(vector& docHead, const Namespace& nspace)\n{\n\tassert(it);\n\tdo\n\t{\n\t\tswitch (*it)\n\t\t{\n\t\tcase CHAR_ABSTRACT_ENTITY:\n\t\t{\n\t\t\t++it;\n\t\t\tauto ent = parseAbstractEntity(nspace);\n\t\t\tdocHead.push_back(ParamDocument::makeEntityAbstract(ent));\n\t\t\tents.addLocalSafe(move(ent));\n\t\t\tbreak;\n\t\t}\n\t\tcase CHAR_CONCRETE_ENTITY:\n\t\t{\n\t\t\t++it;\n\t\t\tauto ent = parseConcreteEntity();\n\t\t\tdocHead.push_back(ParamDocument::makeEntityConcrete(ent));\n\t\t\tents.addLocalSafe(move(ent));\n\t\t\tbreak;\n\t\t}\n\t\tcase CHAR_IMPORT:\n\t\t{\n\t\t\t++it;\n\t\t\tauto import = parseImport();\n\t\t\tdocHead.push_back(move(import));\n\t\t\tbreak;\n\t\t}\n\t\tcase CHAR_SCOPED_DOCUMENT:\n\t\t\t++it;\n\t\t\tparseScopedDocument(docHead);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn false;\n\t\t}\n\t} while (checkNextElement());\n\treturn true;\n}\n\nvoid Parser::parseScopedDocument(vector& docHead)\n{\n\tif (*skipJunkToValid(it) == OPEN_TEMPLATE)\n\t{\n\t\tContainerSwitcher switcher1(*this, ConType::TEMPLATE_HEAD, false);\n\t\tif (containerEmpty())\n\t\t\tthrow runtime_error(\"can't have empty scoped document head\");\n\n\t\tauto head = parseTemplateHeadScoped();\n\n\t\tskipJunkToTag(it, Tag::START_DICTIONARY);\n\t\tDocumentHead body;\n\n\t\tContainerSwitcher switcher2(*this, ConType::DICTIONARY, false);\n\t\tif (!containerEmpty())\n\t\t{\n\t\t\tParamDocumentIncluder includer(ents, head.getParameters());\n\t\t\tif (!parseDocumentHead(body, Namespace::getEmptyInstance()))\n\t\t\t\tthrow runtime_error(ERROR_UNEXPECTED);\n\t\t}\n\t\tdocHead.push_back(ScopedDocument{ move(head), move(body) });\n\t}\n\telse\n\t{\n\t\tconst auto& nspace = parseUsingNamespaceStatic();\n\n\t\t\/\/first check the namespace entity is accessible; if so it has to be removed since\n\t\t\/\/it'll no longer be necessary and an entity with the same name could be inside\n\t\tif (ParamDocumentIncluder::namespacePresentScope(ents, nspace))\n\t\t\tents.removeLocal(ents[nspace.getName()]);\n\n\t\tfor (const auto& ent : nspace)\n\t\t\tents.addLocalSafe(ent);\n\t}\n}\n\nImportedDocument Parser::parseImport()\n{\n#ifdef DISABLE_IMPORT\n\tthrow runtime_error(\"this parser cannot import documents\");\n#else\n\tnextTag = getTag(it);\n\tauto importName = parseValueOnly();\n\tif (!importName.isString())\n\t\tthrow runtime_error(\"import must reference a string\");\n\tImportedDocument import(move(importName));\n\tconst auto& link = import.getLink();\n\tif (!importedDocuments.hasEntity(link))\n\t{\n\t\ttry\n\t\t{\n\t\t\timportedDocuments.addLocalSafe(link, 0);\n\t\t\tImportSwitcher switcher(*this, SmartIterator(Curl().readWebDocument(link)));\n\t\t\tDocumentHead docHead;\n\t\t\tif (!containerEmpty() && !parseDocumentHead(docHead, Namespace::getEmptyInstance()))\n\t\t\t\tthrow runtime_error(ERROR_UNEXPECTED);\n\t\t}\n\t\tcatch (const exception& e)\n\t\t\t{ throw runtime_error(string(\"while parsing import, \") + e.what()); }\n\t}\n\treturn import;\n#endif\n}\n\nconst Namespace& Parser::parseUsingNamespaceStatic()\n{\n\tskipJunkToTag(it, Tag::NAME_START);\n\tauto nameType = parseNameType();\n\tif (nameType.type != NameType::ENTITY_ABSTRACT || !nameType.entity.getContent().isNamespace())\n\t\tthrow runtime_error(\"expected namespace\");\n\treturn nameType.entity.getContent().getNamespaceSafe();\n}<|endoftext|>"} {"text":"Fixing a possible error source<|endoftext|>"} {"text":"#include \"pch.h\"\r\n#include \"WASAPIDevice.h\"\r\n\r\nusing namespace LibAudio;\r\n\r\nWASAPIDevice::WASAPIDevice() : m_initialized(false)\r\n{\r\n}\r\n\r\nvoid WASAPIDevice::StopAsync()\r\n{\r\n\tif (Capture != nullptr)\r\n\t{\r\n\t\tCapture->StopCaptureAsync();\r\n\t}\r\n}\r\n\r\nvoid WASAPIDevice::InitCaptureDevice(size_t id, DataCollector^ collector)\r\n{\r\n\tNumber = id;\r\n\tif (Capture)\r\n\t{\r\n\t\tCapture = nullptr;\r\n\t}\r\n\r\n\tCapture = Make();\r\n\r\n\tStateChangedEvent = Capture->GetDeviceStateEvent();\r\n\tDeviceStateChangeToken = StateChangedEvent->StateChangedEvent += ref new DeviceStateChangedHandler(this, &WASAPIDevice::OnDeviceStateChange);\r\n\r\n\tCapture->InitializeAudioDeviceAsync(ID, Number, collector);\r\n\tm_initialized = true;\r\n}\r\n\r\nvoid WASAPIDevice::InitRendererDevice(size_t id, DataCollector^ collector)\r\n{\r\n HRESULT hr = S_OK;\r\n\r\n if (Renderer)\r\n {\r\n\t\tRenderer = nullptr;\r\n\t}\r\n\t\r\n Renderer = Make();\r\n\t\r\n StateChangedEvent = Renderer->GetDeviceStateEvent();\r\n\tDeviceStateChangeToken = StateChangedEvent->StateChangedEvent += ref new DeviceStateChangedHandler(this, &WASAPIDevice::OnDeviceStateChange);\r\n\r\n\t\r\n\tDEVICEPROPS props;\r\n\tprops.IsTonePlayback = true;\r\n\tprops.Frequency = static_cast(440);\r\n\t\/*\r\n\tswitch (m_ContentType)\r\n\t{\r\n\tcase ContentType::ContentTypeTone:\r\n\t\tprops.IsTonePlayback = true;\r\n\t\tprops.Frequency = static_cast(sliderFrequency->Value);\r\n\t\tbreak;\r\n\r\n\tcase ContentType::ContentTypeFile:\r\n\t\tprops.IsTonePlayback = false;\r\n\t\tprops.ContentStream = m_ContentStream;\r\n\t\tbreak;\r\n\t}\r\n\r\n\tm_IsMinimumLatency = static_cast(toggleMinimumLatency->IsOn);\r\n\t\r\n\tprops.IsLowLatency = m_IsMinimumLatency;\r\n\tprops.IsHWOffload = false;\r\n\tprops.IsBackground = false;\r\n\tprops.IsRawChosen = static_cast(toggleRawAudio->IsOn);\r\n\tprops.IsRawSupported = m_deviceSupportsRawMode;\r\n\t*\/\r\n\tRenderer->SetProperties(props);\r\n\t\r\n\tRenderer->InitializeAudioDeviceAsync(ID, Number, collector);\r\n\tm_initialized = true;\r\n}\r\n\r\nvoid WASAPIDevice::OnDeviceStateChange(Object^ sender, DeviceStateChangedEventArgs^ e)\r\n{\r\n\t\/\/ Get the current time for messages\r\n\tauto t = Windows::Globalization::DateTimeFormatting::DateTimeFormatter::LongTime;\r\n\tWindows::Globalization::Calendar^ calendar = ref new Windows::Globalization::Calendar();\r\n\tcalendar->SetToNow();\r\n\r\n\t\/\/ Handle state specific messages\r\n\tswitch (e->State)\r\n\t{\r\n\t\tcase DeviceState::DeviceStateInitialized:\r\n\t\t{\r\n\t\t\tString^ str = String::Concat(ID, \"-DeviceStateInitialized\\n\");\r\n\t\t\tOutputDebugString(str->Data());\r\n\t\t\tif (Capture != nullptr)\r\n\t\t\t{\r\n\t\t\t\tCapture->StartCaptureAsync();\r\n\t\t\t}\r\n\t\t\tif (Renderer != nullptr)\r\n\t\t\t{\r\n\t\t\t\tRenderer->StartPlaybackAsync();\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcase DeviceState::DeviceStateCapturing:\r\n\t\t{\r\n\t\t\tString^ str = String::Concat(ID, \"-DeviceStateCapturing\\n\");\r\n\t\t\tOutputDebugString(str->Data());\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcase DeviceState::DeviceStateDiscontinuity:\r\n\t\t{\r\n\t\t\tString^ str = String::Concat(ID, \"-DeviceStateDiscontinuity\\n\");\r\n\t\t\tOutputDebugString(str->Data());\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcase DeviceState::DeviceStateInError:\r\n\t\t{\r\n\t\t\tString^ str = String::Concat(ID, \"-DeviceStateInError\\n\");\r\n\t\t\tOutputDebugString(str->Data());\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n}\r\n12052016 - 12:53#include \"pch.h\"\r\n#include \"WASAPIDevice.h\"\r\n\r\nusing namespace LibAudio;\r\n\r\nWASAPIDevice::WASAPIDevice() : m_initialized(false)\r\n{\r\n}\r\n\r\nvoid WASAPIDevice::StopAsync()\r\n{\r\n\tif (Capture != nullptr)\r\n\t{\r\n\t\tCapture->StopCaptureAsync();\r\n\t}\r\n}\r\n\r\nvoid WASAPIDevice::InitCaptureDevice(size_t id, DataCollector^ collector)\r\n{\r\n\tNumber = id;\r\n\tif (Capture)\r\n\t{\r\n\t\tCapture = nullptr;\r\n\t}\r\n\r\n\tCapture = Make();\r\n\r\n\tStateChangedEvent = Capture->GetDeviceStateEvent();\r\n\tDeviceStateChangeToken = StateChangedEvent->StateChangedEvent += ref new DeviceStateChangedHandler(this, &WASAPIDevice::OnDeviceStateChange);\r\n\r\n\tCapture->InitializeAudioDeviceAsync(ID, Number, collector);\r\n\tm_initialized = true;\r\n}\r\n\r\nvoid WASAPIDevice::InitRendererDevice(size_t id, DataCollector^ collector)\r\n{\r\n HRESULT hr = S_OK;\r\n\r\n if (Renderer)\r\n {\r\n\t\tRenderer = nullptr;\r\n\t}\r\n\t\r\n Renderer = Make();\r\n\t\r\n StateChangedEvent = Renderer->GetDeviceStateEvent();\r\n\tDeviceStateChangeToken = StateChangedEvent->StateChangedEvent += ref new DeviceStateChangedHandler(this, &WASAPIDevice::OnDeviceStateChange);\r\n\r\n\t\r\n\tDEVICEPROPS props;\r\n\tprops.IsTonePlayback = true;\r\n\tprops.Frequency = static_cast(440);\r\n\t\/*\r\n\tswitch (m_ContentType)\r\n\t{\r\n\tcase ContentType::ContentTypeTone:\r\n\t\tprops.IsTonePlayback = true;\r\n\t\tprops.Frequency = static_cast(sliderFrequency->Value);\r\n\t\tbreak;\r\n\r\n\tcase ContentType::ContentTypeFile:\r\n\t\tprops.IsTonePlayback = false;\r\n\t\tprops.ContentStream = m_ContentStream;\r\n\t\tbreak;\r\n\t}\r\n\r\n\tm_IsMinimumLatency = static_cast(toggleMinimumLatency->IsOn);\r\n\t\r\n\tprops.IsLowLatency = m_IsMinimumLatency;\r\n\tprops.IsHWOffload = false;\r\n\tprops.IsBackground = false;\r\n\tprops.IsRawChosen = static_cast(toggleRawAudio->IsOn);\r\n\tprops.IsRawSupported = m_deviceSupportsRawMode;\r\n\t*\/\r\n\tRenderer->SetProperties(props);\r\n\t\r\n\tRenderer->InitializeAudioDeviceAsync(ID, Number, collector);\r\n\tm_initialized = true;\r\n}\r\n\r\nvoid WASAPIDevice::OnDeviceStateChange(Object^ sender, DeviceStateChangedEventArgs^ e)\r\n{\r\n\t\/\/ Get the current time for messages\r\n\tauto t = Windows::Globalization::DateTimeFormatting::DateTimeFormatter::LongTime;\r\n\tWindows::Globalization::Calendar^ calendar = ref new Windows::Globalization::Calendar();\r\n\tcalendar->SetToNow();\r\n\r\n\t\/\/ Handle state specific messages\r\n\tswitch (e->State)\r\n\t{\r\n\t\tcase DeviceState::DeviceStateActivated:\r\n\t\t{\r\n\t\t\tString^ str = String::Concat(ID, \"-DeviceStateActivated\\n\");\r\n\t\t\tOutputDebugString(str->Data());\r\n\t\t\tif (Renderer != nullptr)\r\n\t\t\t{\r\n\t\t\t\tRenderer->StartPlaybackAsync();\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcase DeviceState::DeviceStateInitialized:\r\n\t\t{\r\n\t\t\tString^ str = String::Concat(ID, \"-DeviceStateInitialized\\n\");\r\n\t\t\tOutputDebugString(str->Data());\r\n\t\t\tif (Capture != nullptr)\r\n\t\t\t{\r\n\t\t\t\tCapture->StartCaptureAsync();\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcase DeviceState::DeviceStateCapturing:\r\n\t\t{\r\n\t\t\tString^ str = String::Concat(ID, \"-DeviceStateCapturing\\n\");\r\n\t\t\tOutputDebugString(str->Data());\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcase DeviceState::DeviceStateDiscontinuity:\r\n\t\t{\r\n\t\t\tString^ str = String::Concat(ID, \"-DeviceStateDiscontinuity\\n\");\r\n\t\t\tOutputDebugString(str->Data());\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcase DeviceState::DeviceStateInError:\r\n\t\t{\r\n\t\t\tString^ str = String::Concat(ID, \"-DeviceStateInError\\n\");\r\n\t\t\tOutputDebugString(str->Data());\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n}\r\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/policy\/network_configuration_updater.h\"\n\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_network_library.h\"\n#include \"chrome\/browser\/policy\/mock_configuration_policy_provider.h\"\n#include \"chrome\/browser\/policy\/policy_map.h\"\n#include \"chrome\/browser\/policy\/policy_service_impl.h\"\n#include \"policy\/policy_constants.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nusing testing::Mock;\nusing testing::Return;\nusing testing::_;\n\nnamespace policy {\n\nstatic const char kFakeONC[] = \"{ \\\"GUID\\\": \\\"1234\\\" }\";\n\nclass NetworkConfigurationUpdaterTest\n : public testing::TestWithParam {\n protected:\n virtual void SetUp() OVERRIDE {\n EXPECT_CALL(network_library_, LoadOncNetworks(_, \"\", _, _, _))\n .WillRepeatedly(Return(true));\n EXPECT_CALL(provider_, IsInitializationComplete())\n .WillRepeatedly(Return(true));\n PolicyServiceImpl::Providers providers;\n providers.push_back(&provider_);\n policy_service_.reset(new PolicyServiceImpl(providers));\n }\n\n \/\/ Maps configuration policy name to corresponding ONC source.\n static chromeos::NetworkUIData::ONCSource NameToONCSource(\n const std::string& name) {\n if (name == key::kDeviceOpenNetworkConfiguration)\n return chromeos::NetworkUIData::ONC_SOURCE_DEVICE_POLICY;\n if (name == key::kOpenNetworkConfiguration)\n return chromeos::NetworkUIData::ONC_SOURCE_USER_POLICY;\n return chromeos::NetworkUIData::ONC_SOURCE_NONE;\n }\n\n chromeos::MockNetworkLibrary network_library_;\n MockConfigurationPolicyProvider provider_;\n scoped_ptr policy_service_;\n};\n\nTEST_P(NetworkConfigurationUpdaterTest, InitialUpdate) {\n PolicyMap policy;\n policy.Set(GetParam(), POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,\n Value::CreateStringValue(kFakeONC));\n provider_.UpdateChromePolicy(policy);\n\n EXPECT_CALL(network_library_,\n LoadOncNetworks(kFakeONC, \"\", NameToONCSource(GetParam()),\n false, _))\n .WillOnce(Return(true));\n\n NetworkConfigurationUpdater updater(policy_service_.get(), &network_library_);\n Mock::VerifyAndClearExpectations(&network_library_);\n}\n\nTEST_P(NetworkConfigurationUpdaterTest, AllowWebTrust) {\n NetworkConfigurationUpdater updater(policy_service_.get(), &network_library_);\n updater.set_allow_web_trust(true);\n\n EXPECT_CALL(network_library_,\n LoadOncNetworks(kFakeONC, \"\", NameToONCSource(GetParam()),\n true, _))\n .WillOnce(Return(true));\n\n PolicyMap policy;\n policy.Set(GetParam(), POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,\n Value::CreateStringValue(kFakeONC));\n provider_.UpdateChromePolicy(policy);\n Mock::VerifyAndClearExpectations(&network_library_);\n}\n\nTEST_P(NetworkConfigurationUpdaterTest, PolicyChange) {\n NetworkConfigurationUpdater updater(policy_service_.get(), &network_library_);\n\n \/\/ We should update if policy changes.\n EXPECT_CALL(network_library_,\n LoadOncNetworks(kFakeONC, \"\", NameToONCSource(GetParam()),\n false, _))\n .WillOnce(Return(true));\n PolicyMap policy;\n policy.Set(GetParam(), POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,\n Value::CreateStringValue(kFakeONC));\n provider_.UpdateChromePolicy(policy);\n Mock::VerifyAndClearExpectations(&network_library_);\n\n \/\/ No update if the set the same value again.\n EXPECT_CALL(network_library_,\n LoadOncNetworks(kFakeONC, \"\", NameToONCSource(GetParam()),\n false, _))\n .Times(0);\n provider_.UpdateChromePolicy(policy);\n Mock::VerifyAndClearExpectations(&network_library_);\n\n \/\/ Another update is expected if the policy goes away.\n EXPECT_CALL(network_library_,\n LoadOncNetworks(NetworkConfigurationUpdater::kEmptyConfiguration,\n \"\", NameToONCSource(GetParam()), false, _))\n .WillOnce(Return(true));\n policy.Erase(GetParam());\n provider_.UpdateChromePolicy(policy);\n Mock::VerifyAndClearExpectations(&network_library_);\n}\n\nINSTANTIATE_TEST_CASE_P(\n NetworkConfigurationUpdaterTestInstance,\n NetworkConfigurationUpdaterTest,\n testing::Values(key::kDeviceOpenNetworkConfiguration,\n key::kOpenNetworkConfiguration));\n\n} \/\/ namespace policy\nUpdate unit_test that broke after http:\/\/crrev.com\/162481\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/policy\/network_configuration_updater.h\"\n\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_network_library.h\"\n#include \"chrome\/browser\/policy\/mock_configuration_policy_provider.h\"\n#include \"chrome\/browser\/policy\/policy_map.h\"\n#include \"chrome\/browser\/policy\/policy_service_impl.h\"\n#include \"policy\/policy_constants.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nusing testing::Mock;\nusing testing::Return;\nusing testing::_;\n\nnamespace policy {\n\nstatic const char kFakeONC[] = \"{ \\\"GUID\\\": \\\"1234\\\" }\";\n\nclass NetworkConfigurationUpdaterTest\n : public testing::TestWithParam {\n protected:\n virtual void SetUp() OVERRIDE {\n EXPECT_CALL(network_library_, LoadOncNetworks(_, \"\", _, _, _))\n .WillRepeatedly(Return(true));\n EXPECT_CALL(provider_, IsInitializationComplete())\n .WillRepeatedly(Return(true));\n provider_.Init();\n PolicyServiceImpl::Providers providers;\n providers.push_back(&provider_);\n policy_service_.reset(new PolicyServiceImpl(providers));\n }\n\n virtual void TearDown() OVERRIDE {\n provider_.Shutdown();\n }\n\n \/\/ Maps configuration policy name to corresponding ONC source.\n static chromeos::NetworkUIData::ONCSource NameToONCSource(\n const std::string& name) {\n if (name == key::kDeviceOpenNetworkConfiguration)\n return chromeos::NetworkUIData::ONC_SOURCE_DEVICE_POLICY;\n if (name == key::kOpenNetworkConfiguration)\n return chromeos::NetworkUIData::ONC_SOURCE_USER_POLICY;\n return chromeos::NetworkUIData::ONC_SOURCE_NONE;\n }\n\n chromeos::MockNetworkLibrary network_library_;\n MockConfigurationPolicyProvider provider_;\n scoped_ptr policy_service_;\n};\n\nTEST_P(NetworkConfigurationUpdaterTest, InitialUpdate) {\n PolicyMap policy;\n policy.Set(GetParam(), POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,\n Value::CreateStringValue(kFakeONC));\n provider_.UpdateChromePolicy(policy);\n\n EXPECT_CALL(network_library_,\n LoadOncNetworks(kFakeONC, \"\", NameToONCSource(GetParam()),\n false, _))\n .WillOnce(Return(true));\n\n NetworkConfigurationUpdater updater(policy_service_.get(), &network_library_);\n Mock::VerifyAndClearExpectations(&network_library_);\n}\n\nTEST_P(NetworkConfigurationUpdaterTest, AllowWebTrust) {\n NetworkConfigurationUpdater updater(policy_service_.get(), &network_library_);\n updater.set_allow_web_trust(true);\n\n EXPECT_CALL(network_library_,\n LoadOncNetworks(kFakeONC, \"\", NameToONCSource(GetParam()),\n true, _))\n .WillOnce(Return(true));\n\n PolicyMap policy;\n policy.Set(GetParam(), POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,\n Value::CreateStringValue(kFakeONC));\n provider_.UpdateChromePolicy(policy);\n Mock::VerifyAndClearExpectations(&network_library_);\n}\n\nTEST_P(NetworkConfigurationUpdaterTest, PolicyChange) {\n NetworkConfigurationUpdater updater(policy_service_.get(), &network_library_);\n\n \/\/ We should update if policy changes.\n EXPECT_CALL(network_library_,\n LoadOncNetworks(kFakeONC, \"\", NameToONCSource(GetParam()),\n false, _))\n .WillOnce(Return(true));\n PolicyMap policy;\n policy.Set(GetParam(), POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,\n Value::CreateStringValue(kFakeONC));\n provider_.UpdateChromePolicy(policy);\n Mock::VerifyAndClearExpectations(&network_library_);\n\n \/\/ No update if the set the same value again.\n EXPECT_CALL(network_library_,\n LoadOncNetworks(kFakeONC, \"\", NameToONCSource(GetParam()),\n false, _))\n .Times(0);\n provider_.UpdateChromePolicy(policy);\n Mock::VerifyAndClearExpectations(&network_library_);\n\n \/\/ Another update is expected if the policy goes away.\n EXPECT_CALL(network_library_,\n LoadOncNetworks(NetworkConfigurationUpdater::kEmptyConfiguration,\n \"\", NameToONCSource(GetParam()), false, _))\n .WillOnce(Return(true));\n policy.Erase(GetParam());\n provider_.UpdateChromePolicy(policy);\n Mock::VerifyAndClearExpectations(&network_library_);\n}\n\nINSTANTIATE_TEST_CASE_P(\n NetworkConfigurationUpdaterTestInstance,\n NetworkConfigurationUpdaterTest,\n testing::Values(key::kDeviceOpenNetworkConfiguration,\n key::kOpenNetworkConfiguration));\n\n} \/\/ namespace policy\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/tab_contents\/render_view_host_delegate_helper.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/background_contents_service.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/character_encoding.h\"\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n#include \"chrome\/browser\/pref_service.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/renderer_host\/render_process_host.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host_view.h\"\n#include \"chrome\/browser\/renderer_host\/site_instance.h\"\n#include \"chrome\/browser\/tab_contents\/background_contents.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents_view.h\"\n#include \"chrome\/browser\/user_style_sheet_watcher.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/pref_names.h\"\n\nBackgroundContents*\nRenderViewHostDelegateViewHelper::MaybeCreateBackgroundContents(\n int route_id,\n Profile* profile,\n SiteInstance* site,\n GURL opener_url,\n const string16& frame_name) {\n ExtensionsService* extensions_service = profile->GetExtensionsService();\n\n if (!opener_url.is_valid() ||\n frame_name.empty() ||\n !extensions_service ||\n !extensions_service->is_ready())\n return NULL;\n\n Extension* extension = extensions_service->GetExtensionByURL(opener_url);\n if (!extension)\n extension = extensions_service->GetExtensionByWebExtent(opener_url);\n if (!extension ||\n !extension->HasApiPermission(Extension::kBackgroundPermission))\n return NULL;\n\n \/\/ Only allow a single background contents per app.\n if (!profile->GetBackgroundContentsService() ||\n profile->GetBackgroundContentsService()->GetAppBackgroundContents(\n ASCIIToUTF16(extension->id())))\n return NULL;\n\n \/\/ Ensure that we're trying to open this from the extension's process.\n ExtensionProcessManager* process_manager =\n profile->GetExtensionProcessManager();\n if (!site->GetProcess() || !process_manager ||\n site->GetProcess() != process_manager->GetExtensionProcess(opener_url))\n return NULL;\n\n \/\/ Passed all the checks, so this should be created as a BackgroundContents.\n BackgroundContents* contents = new BackgroundContents(site, route_id);\n string16 appid = ASCIIToUTF16(extension->id());\n BackgroundContentsOpenedDetails details = { contents, frame_name, appid };\n NotificationService::current()->Notify(\n NotificationType::BACKGROUND_CONTENTS_OPENED,\n Source(profile),\n Details(&details));\n\n return contents;\n}\n\nTabContents* RenderViewHostDelegateViewHelper::CreateNewWindow(\n int route_id,\n Profile* profile,\n SiteInstance* site,\n DOMUITypeID domui_type,\n RenderViewHostDelegate* opener,\n WindowContainerType window_container_type,\n const string16& frame_name) {\n if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {\n BackgroundContents* contents = MaybeCreateBackgroundContents(\n route_id,\n profile,\n site,\n opener->GetURL(),\n frame_name);\n if (contents) {\n pending_contents_[route_id] = contents->render_view_host();\n return NULL;\n }\n }\n\n \/\/ Create the new web contents. This will automatically create the new\n \/\/ TabContentsView. In the future, we may want to create the view separately.\n TabContents* new_contents =\n new TabContents(profile,\n site,\n route_id,\n opener->GetAsTabContents());\n new_contents->set_opener_dom_ui_type(domui_type);\n TabContentsView* new_view = new_contents->view();\n\n \/\/ TODO(brettw) it seems bogus that we have to call this function on the\n \/\/ newly created object and give it one of its own member variables.\n new_view->CreateViewForWidget(new_contents->render_view_host());\n\n \/\/ Save the created window associated with the route so we can show it later.\n pending_contents_[route_id] = new_contents->render_view_host();\n return new_contents;\n}\n\nRenderWidgetHostView* RenderViewHostDelegateViewHelper::CreateNewWidget(\n int route_id, WebKit::WebPopupType popup_type, RenderProcessHost* process) {\n RenderWidgetHost* widget_host =\n new RenderWidgetHost(process, route_id);\n RenderWidgetHostView* widget_view =\n RenderWidgetHostView::CreateViewForWidget(widget_host);\n \/\/ Popups should not get activated.\n widget_view->set_popup_type(popup_type);\n \/\/ Save the created widget associated with the route so we can show it later.\n pending_widget_views_[route_id] = widget_view;\n return widget_view;\n}\n\nTabContents* RenderViewHostDelegateViewHelper::GetCreatedWindow(int route_id) {\n PendingContents::iterator iter = pending_contents_.find(route_id);\n if (iter == pending_contents_.end()) {\n DCHECK(false);\n return NULL;\n }\n\n RenderViewHost* new_rvh = iter->second;\n pending_contents_.erase(route_id);\n\n \/\/ The renderer crashed or it is a TabContents and has no view.\n if (!new_rvh->process()->HasConnection() ||\n (new_rvh->delegate()->GetAsTabContents() && !new_rvh->view()))\n return NULL;\n\n \/\/ TODO(brettw) this seems bogus to reach into here and initialize the host.\n new_rvh->Init();\n return new_rvh->delegate()->GetAsTabContents();\n}\n\nRenderWidgetHostView* RenderViewHostDelegateViewHelper::GetCreatedWidget(\n int route_id) {\n PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id);\n if (iter == pending_widget_views_.end()) {\n DCHECK(false);\n return NULL;\n }\n\n RenderWidgetHostView* widget_host_view = iter->second;\n pending_widget_views_.erase(route_id);\n\n RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();\n if (!widget_host->process()->HasConnection()) {\n \/\/ The view has gone away or the renderer crashed. Nothing to do.\n return NULL;\n }\n\n return widget_host_view;\n}\n\nvoid RenderViewHostDelegateViewHelper::RenderWidgetHostDestroyed(\n RenderWidgetHost* host) {\n for (PendingWidgetViews::iterator i = pending_widget_views_.begin();\n i != pending_widget_views_.end(); ++i) {\n if (host->view() == i->second) {\n pending_widget_views_.erase(i);\n return;\n }\n }\n}\n\n\/\/ static\nWebPreferences RenderViewHostDelegateHelper::GetWebkitPrefs(\n Profile* profile, bool is_dom_ui) {\n PrefService* prefs = profile->GetPrefs();\n WebPreferences web_prefs;\n\n web_prefs.fixed_font_family =\n UTF8ToWide(prefs->GetString(prefs::kWebKitFixedFontFamily));\n web_prefs.serif_font_family =\n UTF8ToWide(prefs->GetString(prefs::kWebKitSerifFontFamily));\n web_prefs.sans_serif_font_family =\n UTF8ToWide(prefs->GetString(prefs::kWebKitSansSerifFontFamily));\n if (prefs->GetBoolean(prefs::kWebKitStandardFontIsSerif))\n web_prefs.standard_font_family = web_prefs.serif_font_family;\n else\n web_prefs.standard_font_family = web_prefs.sans_serif_font_family;\n web_prefs.cursive_font_family =\n UTF8ToWide(prefs->GetString(prefs::kWebKitCursiveFontFamily));\n web_prefs.fantasy_font_family =\n UTF8ToWide(prefs->GetString(prefs::kWebKitFantasyFontFamily));\n\n web_prefs.default_font_size =\n prefs->GetInteger(prefs::kWebKitDefaultFontSize);\n web_prefs.default_fixed_font_size =\n prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);\n web_prefs.minimum_font_size =\n prefs->GetInteger(prefs::kWebKitMinimumFontSize);\n web_prefs.minimum_logical_font_size =\n prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);\n\n web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset);\n\n web_prefs.javascript_can_open_windows_automatically =\n prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically);\n web_prefs.dom_paste_enabled =\n prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);\n web_prefs.shrinks_standalone_images_to_fit =\n prefs->GetBoolean(prefs::kWebKitShrinksStandaloneImagesToFit);\n const DictionaryValue* inspector_settings =\n prefs->GetDictionary(prefs::kWebKitInspectorSettings);\n if (inspector_settings) {\n for (DictionaryValue::key_iterator iter(inspector_settings->begin_keys());\n iter != inspector_settings->end_keys(); ++iter) {\n std::string value;\n if (inspector_settings->GetStringWithoutPathExpansion(*iter, &value))\n web_prefs.inspector_settings.push_back(\n std::make_pair(WideToUTF8(*iter), value));\n }\n }\n web_prefs.tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);\n\n { \/\/ Command line switches are used for preferences with no user interface.\n const CommandLine& command_line = *CommandLine::ForCurrentProcess();\n web_prefs.developer_extras_enabled =\n !command_line.HasSwitch(switches::kDisableDevTools);\n web_prefs.javascript_enabled =\n !command_line.HasSwitch(switches::kDisableJavaScript) &&\n prefs->GetBoolean(prefs::kWebKitJavascriptEnabled);\n web_prefs.web_security_enabled =\n !command_line.HasSwitch(switches::kDisableWebSecurity) &&\n prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled);\n web_prefs.plugins_enabled =\n !command_line.HasSwitch(switches::kDisablePlugins) &&\n prefs->GetBoolean(prefs::kWebKitPluginsEnabled);\n web_prefs.java_enabled =\n !command_line.HasSwitch(switches::kDisableJava) &&\n prefs->GetBoolean(prefs::kWebKitJavaEnabled);\n web_prefs.loads_images_automatically =\n prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);\n web_prefs.uses_page_cache =\n command_line.HasSwitch(switches::kEnableFastback);\n web_prefs.remote_fonts_enabled =\n !command_line.HasSwitch(switches::kDisableRemoteFonts);\n web_prefs.xss_auditor_enabled =\n command_line.HasSwitch(switches::kEnableXSSAuditor);\n web_prefs.application_cache_enabled =\n !command_line.HasSwitch(switches::kDisableApplicationCache);\n\n web_prefs.local_storage_enabled =\n !command_line.HasSwitch(switches::kDisableLocalStorage);\n web_prefs.databases_enabled =\n !command_line.HasSwitch(switches::kDisableDatabases);\n web_prefs.experimental_webgl_enabled =\n command_line.HasSwitch(switches::kEnableExperimentalWebGL);\n web_prefs.site_specific_quirks_enabled =\n !command_line.HasSwitch(switches::kDisableSiteSpecificQuirks);\n web_prefs.allow_file_access_from_file_urls =\n command_line.HasSwitch(switches::kAllowFileAccessFromFiles);\n web_prefs.show_composited_layer_borders =\n command_line.HasSwitch(switches::kShowCompositedLayerBorders);\n web_prefs.accelerated_compositing_enabled =\n command_line.HasSwitch(switches::kEnableAcceleratedCompositing);\n web_prefs.accelerated_2d_canvas_enabled =\n command_line.HasSwitch(switches::kEnableAccelerated2dCanvas);\n web_prefs.memory_info_enabled =\n command_line.HasSwitch(switches::kEnableMemoryInfo);\n \/\/ The user stylesheet watcher may not exist in a testing profile.\n if (profile->GetUserStyleSheetWatcher()) {\n web_prefs.user_style_sheet_enabled = true;\n web_prefs.user_style_sheet_location =\n profile->GetUserStyleSheetWatcher()->user_style_sheet();\n } else {\n web_prefs.user_style_sheet_enabled = false;\n }\n }\n\n web_prefs.uses_universal_detector =\n prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector);\n web_prefs.text_areas_are_resizable =\n prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);\n\n \/\/ Make sure we will set the default_encoding with canonical encoding name.\n web_prefs.default_encoding =\n CharacterEncoding::GetCanonicalEncodingNameByAliasName(\n web_prefs.default_encoding);\n if (web_prefs.default_encoding.empty()) {\n prefs->ClearPref(prefs::kDefaultCharset);\n web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset);\n }\n DCHECK(!web_prefs.default_encoding.empty());\n\n if (is_dom_ui) {\n web_prefs.loads_images_automatically = true;\n web_prefs.javascript_enabled = true;\n }\n\n return web_prefs;\n}\nRemove unneeded browser.h include from RVHDelegateHelper.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/tab_contents\/render_view_host_delegate_helper.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/background_contents_service.h\"\n#include \"chrome\/browser\/character_encoding.h\"\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n#include \"chrome\/browser\/pref_service.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/renderer_host\/render_process_host.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host_view.h\"\n#include \"chrome\/browser\/renderer_host\/site_instance.h\"\n#include \"chrome\/browser\/tab_contents\/background_contents.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents_view.h\"\n#include \"chrome\/browser\/user_style_sheet_watcher.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/pref_names.h\"\n\nBackgroundContents*\nRenderViewHostDelegateViewHelper::MaybeCreateBackgroundContents(\n int route_id,\n Profile* profile,\n SiteInstance* site,\n GURL opener_url,\n const string16& frame_name) {\n ExtensionsService* extensions_service = profile->GetExtensionsService();\n\n if (!opener_url.is_valid() ||\n frame_name.empty() ||\n !extensions_service ||\n !extensions_service->is_ready())\n return NULL;\n\n Extension* extension = extensions_service->GetExtensionByURL(opener_url);\n if (!extension)\n extension = extensions_service->GetExtensionByWebExtent(opener_url);\n if (!extension ||\n !extension->HasApiPermission(Extension::kBackgroundPermission))\n return NULL;\n\n \/\/ Only allow a single background contents per app.\n if (!profile->GetBackgroundContentsService() ||\n profile->GetBackgroundContentsService()->GetAppBackgroundContents(\n ASCIIToUTF16(extension->id())))\n return NULL;\n\n \/\/ Ensure that we're trying to open this from the extension's process.\n ExtensionProcessManager* process_manager =\n profile->GetExtensionProcessManager();\n if (!site->GetProcess() || !process_manager ||\n site->GetProcess() != process_manager->GetExtensionProcess(opener_url))\n return NULL;\n\n \/\/ Passed all the checks, so this should be created as a BackgroundContents.\n BackgroundContents* contents = new BackgroundContents(site, route_id);\n string16 appid = ASCIIToUTF16(extension->id());\n BackgroundContentsOpenedDetails details = { contents, frame_name, appid };\n NotificationService::current()->Notify(\n NotificationType::BACKGROUND_CONTENTS_OPENED,\n Source(profile),\n Details(&details));\n\n return contents;\n}\n\nTabContents* RenderViewHostDelegateViewHelper::CreateNewWindow(\n int route_id,\n Profile* profile,\n SiteInstance* site,\n DOMUITypeID domui_type,\n RenderViewHostDelegate* opener,\n WindowContainerType window_container_type,\n const string16& frame_name) {\n if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {\n BackgroundContents* contents = MaybeCreateBackgroundContents(\n route_id,\n profile,\n site,\n opener->GetURL(),\n frame_name);\n if (contents) {\n pending_contents_[route_id] = contents->render_view_host();\n return NULL;\n }\n }\n\n \/\/ Create the new web contents. This will automatically create the new\n \/\/ TabContentsView. In the future, we may want to create the view separately.\n TabContents* new_contents =\n new TabContents(profile,\n site,\n route_id,\n opener->GetAsTabContents());\n new_contents->set_opener_dom_ui_type(domui_type);\n TabContentsView* new_view = new_contents->view();\n\n \/\/ TODO(brettw) it seems bogus that we have to call this function on the\n \/\/ newly created object and give it one of its own member variables.\n new_view->CreateViewForWidget(new_contents->render_view_host());\n\n \/\/ Save the created window associated with the route so we can show it later.\n pending_contents_[route_id] = new_contents->render_view_host();\n return new_contents;\n}\n\nRenderWidgetHostView* RenderViewHostDelegateViewHelper::CreateNewWidget(\n int route_id, WebKit::WebPopupType popup_type, RenderProcessHost* process) {\n RenderWidgetHost* widget_host =\n new RenderWidgetHost(process, route_id);\n RenderWidgetHostView* widget_view =\n RenderWidgetHostView::CreateViewForWidget(widget_host);\n \/\/ Popups should not get activated.\n widget_view->set_popup_type(popup_type);\n \/\/ Save the created widget associated with the route so we can show it later.\n pending_widget_views_[route_id] = widget_view;\n return widget_view;\n}\n\nTabContents* RenderViewHostDelegateViewHelper::GetCreatedWindow(int route_id) {\n PendingContents::iterator iter = pending_contents_.find(route_id);\n if (iter == pending_contents_.end()) {\n DCHECK(false);\n return NULL;\n }\n\n RenderViewHost* new_rvh = iter->second;\n pending_contents_.erase(route_id);\n\n \/\/ The renderer crashed or it is a TabContents and has no view.\n if (!new_rvh->process()->HasConnection() ||\n (new_rvh->delegate()->GetAsTabContents() && !new_rvh->view()))\n return NULL;\n\n \/\/ TODO(brettw) this seems bogus to reach into here and initialize the host.\n new_rvh->Init();\n return new_rvh->delegate()->GetAsTabContents();\n}\n\nRenderWidgetHostView* RenderViewHostDelegateViewHelper::GetCreatedWidget(\n int route_id) {\n PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id);\n if (iter == pending_widget_views_.end()) {\n DCHECK(false);\n return NULL;\n }\n\n RenderWidgetHostView* widget_host_view = iter->second;\n pending_widget_views_.erase(route_id);\n\n RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();\n if (!widget_host->process()->HasConnection()) {\n \/\/ The view has gone away or the renderer crashed. Nothing to do.\n return NULL;\n }\n\n return widget_host_view;\n}\n\nvoid RenderViewHostDelegateViewHelper::RenderWidgetHostDestroyed(\n RenderWidgetHost* host) {\n for (PendingWidgetViews::iterator i = pending_widget_views_.begin();\n i != pending_widget_views_.end(); ++i) {\n if (host->view() == i->second) {\n pending_widget_views_.erase(i);\n return;\n }\n }\n}\n\n\/\/ static\nWebPreferences RenderViewHostDelegateHelper::GetWebkitPrefs(\n Profile* profile, bool is_dom_ui) {\n PrefService* prefs = profile->GetPrefs();\n WebPreferences web_prefs;\n\n web_prefs.fixed_font_family =\n UTF8ToWide(prefs->GetString(prefs::kWebKitFixedFontFamily));\n web_prefs.serif_font_family =\n UTF8ToWide(prefs->GetString(prefs::kWebKitSerifFontFamily));\n web_prefs.sans_serif_font_family =\n UTF8ToWide(prefs->GetString(prefs::kWebKitSansSerifFontFamily));\n if (prefs->GetBoolean(prefs::kWebKitStandardFontIsSerif))\n web_prefs.standard_font_family = web_prefs.serif_font_family;\n else\n web_prefs.standard_font_family = web_prefs.sans_serif_font_family;\n web_prefs.cursive_font_family =\n UTF8ToWide(prefs->GetString(prefs::kWebKitCursiveFontFamily));\n web_prefs.fantasy_font_family =\n UTF8ToWide(prefs->GetString(prefs::kWebKitFantasyFontFamily));\n\n web_prefs.default_font_size =\n prefs->GetInteger(prefs::kWebKitDefaultFontSize);\n web_prefs.default_fixed_font_size =\n prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);\n web_prefs.minimum_font_size =\n prefs->GetInteger(prefs::kWebKitMinimumFontSize);\n web_prefs.minimum_logical_font_size =\n prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);\n\n web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset);\n\n web_prefs.javascript_can_open_windows_automatically =\n prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically);\n web_prefs.dom_paste_enabled =\n prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);\n web_prefs.shrinks_standalone_images_to_fit =\n prefs->GetBoolean(prefs::kWebKitShrinksStandaloneImagesToFit);\n const DictionaryValue* inspector_settings =\n prefs->GetDictionary(prefs::kWebKitInspectorSettings);\n if (inspector_settings) {\n for (DictionaryValue::key_iterator iter(inspector_settings->begin_keys());\n iter != inspector_settings->end_keys(); ++iter) {\n std::string value;\n if (inspector_settings->GetStringWithoutPathExpansion(*iter, &value))\n web_prefs.inspector_settings.push_back(\n std::make_pair(WideToUTF8(*iter), value));\n }\n }\n web_prefs.tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);\n\n { \/\/ Command line switches are used for preferences with no user interface.\n const CommandLine& command_line = *CommandLine::ForCurrentProcess();\n web_prefs.developer_extras_enabled =\n !command_line.HasSwitch(switches::kDisableDevTools);\n web_prefs.javascript_enabled =\n !command_line.HasSwitch(switches::kDisableJavaScript) &&\n prefs->GetBoolean(prefs::kWebKitJavascriptEnabled);\n web_prefs.web_security_enabled =\n !command_line.HasSwitch(switches::kDisableWebSecurity) &&\n prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled);\n web_prefs.plugins_enabled =\n !command_line.HasSwitch(switches::kDisablePlugins) &&\n prefs->GetBoolean(prefs::kWebKitPluginsEnabled);\n web_prefs.java_enabled =\n !command_line.HasSwitch(switches::kDisableJava) &&\n prefs->GetBoolean(prefs::kWebKitJavaEnabled);\n web_prefs.loads_images_automatically =\n prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);\n web_prefs.uses_page_cache =\n command_line.HasSwitch(switches::kEnableFastback);\n web_prefs.remote_fonts_enabled =\n !command_line.HasSwitch(switches::kDisableRemoteFonts);\n web_prefs.xss_auditor_enabled =\n command_line.HasSwitch(switches::kEnableXSSAuditor);\n web_prefs.application_cache_enabled =\n !command_line.HasSwitch(switches::kDisableApplicationCache);\n\n web_prefs.local_storage_enabled =\n !command_line.HasSwitch(switches::kDisableLocalStorage);\n web_prefs.databases_enabled =\n !command_line.HasSwitch(switches::kDisableDatabases);\n web_prefs.experimental_webgl_enabled =\n command_line.HasSwitch(switches::kEnableExperimentalWebGL);\n web_prefs.site_specific_quirks_enabled =\n !command_line.HasSwitch(switches::kDisableSiteSpecificQuirks);\n web_prefs.allow_file_access_from_file_urls =\n command_line.HasSwitch(switches::kAllowFileAccessFromFiles);\n web_prefs.show_composited_layer_borders =\n command_line.HasSwitch(switches::kShowCompositedLayerBorders);\n web_prefs.accelerated_compositing_enabled =\n command_line.HasSwitch(switches::kEnableAcceleratedCompositing);\n web_prefs.accelerated_2d_canvas_enabled =\n command_line.HasSwitch(switches::kEnableAccelerated2dCanvas);\n web_prefs.memory_info_enabled =\n command_line.HasSwitch(switches::kEnableMemoryInfo);\n \/\/ The user stylesheet watcher may not exist in a testing profile.\n if (profile->GetUserStyleSheetWatcher()) {\n web_prefs.user_style_sheet_enabled = true;\n web_prefs.user_style_sheet_location =\n profile->GetUserStyleSheetWatcher()->user_style_sheet();\n } else {\n web_prefs.user_style_sheet_enabled = false;\n }\n }\n\n web_prefs.uses_universal_detector =\n prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector);\n web_prefs.text_areas_are_resizable =\n prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);\n\n \/\/ Make sure we will set the default_encoding with canonical encoding name.\n web_prefs.default_encoding =\n CharacterEncoding::GetCanonicalEncodingNameByAliasName(\n web_prefs.default_encoding);\n if (web_prefs.default_encoding.empty()) {\n prefs->ClearPref(prefs::kDefaultCharset);\n web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset);\n }\n DCHECK(!web_prefs.default_encoding.empty());\n\n if (is_dom_ui) {\n web_prefs.loads_images_automatically = true;\n web_prefs.javascript_enabled = true;\n }\n\n return web_prefs;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"ImageUtils.h\"\n#include \"PaletteWindow.h\"\n#include \"SummaryView.h\"\n\nSummaryView::SummaryView(int size, int tileCount, int offsetX, int offsetY, int visibleSideCount, int reductionFactor)\n : isAlive(false), size(size), tileId(tileCount), selectedTile(2955),\n topographicSummarizer(size, tileCount, offsetX, offsetY, visibleSideCount, reductionFactor, \"..\/ContourTiler\/rasters\/summary\/\", \"summary.png\"),\n overlaySummarizer(size, tileCount, offsetX, offsetY, visibleSideCount, reductionFactor, \"..\/ContourTiler\/rasters\/summary\/\", \"overlay.png\"),\n windowSelf(nullptr), offsetX(offsetX), offsetY(offsetY), visibleSideCount(visibleSideCount)\n{\n}\n\nvoid SummaryView::RemapToTile(double* x, double* y)\n{\n int tileX, tileY;\n tileId.GetPositionFromId(selectedTile, &tileX, &tileY);\n\n (*x) *= ((double)1000 * tileId.GetTileCount());\n (*y) *= ((double)1000 * tileId.GetTileCount());\n\n (*x) -= (tileX * 1000);\n (*y) -= (tileY * 1000);\n}\n\nvoid SummaryView::MoveSelectedTile(Direction direction)\n{\n int x, y;\n tileId.GetPositionFromId(selectedTile, &x, &y);\n\n switch (direction)\n {\n case UP: ++y; break;\n case DOWN: --y; break;\n case LEFT: --x; break;\n case RIGHT: ++x; break;\n }\n\n if (topographicSummarizer.IsTileValid(x, y))\n {\n selectedTile = tileId.GetTileId(x, y);\n UpdateSelectedTileRectangle();\n\n \/\/ TODO this doesn't apply on startup, and should be fixed to not pass around the window pointer.\n if (windowSelf != nullptr)\n {\n std::stringstream titleString;\n titleString << \"Summary (\" << x << \", \" << y << \")\" << std::endl;\n windowSelf->setTitle(titleString.str());\n }\n }\n}\n\nvoid SummaryView::LoadSelectedTile(unsigned char** data, int offsetX, int offsetY)\n{\n if (*data != nullptr)\n {\n \/\/ We could also do topographic, but we (for now) don't support elevation changes with this program.\n\n ImageUtils::FreeImage(*data);\n *data = nullptr;\n }\n\n int x, y;\n tileId.GetPositionFromId(selectedTile, &x, &y);\n\n x += offsetX;\n y += offsetY;\n\n \/\/ Ensure we read a valid image.\n x = std::max(0, x);\n y = std::max(0, y);\n x = std::min(x, tileId.GetTileCount() - 1);\n y = std::min(y, tileId.GetTileCount() - 1);\n\n std::stringstream imageTile;\n imageTile << \"..\/ContourTiler\/rasters\/\" << y << \"\/\" << x << \".png\";\n\n int width, height;\n if (!ImageUtils::LoadImage(imageTile.str().c_str(), &width, &height, data))\n {\n std::cout << \"Failed to load \" << imageTile.str() << std::endl;\n }\n}\n\nvoid SummaryView::LoadSelectedTile(bool loadEdges, unsigned char** centerData, unsigned char** leftData, unsigned char** rightData, unsigned char** topData, unsigned char** bottomData)\n{\n LoadSelectedTile(centerData, 0, 0);\n \n \/\/ Don't reload the edges if we aren't saving when moving to speed up drawing\n if (loadEdges)\n {\n LoadSelectedTile(leftData, -1, 0);\n LoadSelectedTile(rightData, 1, 0);\n LoadSelectedTile(topData, 0, 1);\n LoadSelectedTile(bottomData, 0, -1);\n }\n}\n\n\/\/ We know that only the topographic data is what really matters. We do need to indicate a reload to both topographic and overlay layers though.\nvoid SummaryView::UpdateSelectedTile(unsigned char* newData)\n{\n int x, y;\n tileId.GetPositionFromId(selectedTile, &x, &y);\n topographicSummarizer.UpdateSummaryForTile(newData, x, y, true);\n overlaySummarizer.UpdateSummaryForTile(newData, x, y, false);\n}\n\nvoid SummaryView::UpdateSelectedTileRectangle()\n{\n int motionScale = size \/ visibleSideCount;\n int x, y;\n tileId.GetPositionFromId(selectedTile, &x, &y);\n selectedTileRectangle.setPosition(sf::Vector2f((float)((x - offsetX) * motionScale), (float)(size - (y - offsetY + 1) * motionScale)));\n}\n\nvoid SummaryView::HandleEvents(sf::RenderWindow& window)\n{\n \/\/ Handle all events.\n sf::Event event;\n while (window.pollEvent(event))\n {\n if (event.type == sf::Event::Closed)\n {\n \/\/ Ignore -- we only close if the main map editor closes.\n }\n }\n}\n\nvoid SummaryView::Render(sf::RenderWindow& window)\n{\n window.draw(topographicSummarizer.GetSummarizedSprite());\n window.draw(overlaySummarizer.GetSummarizedSprite());\n window.draw(selectedTileRectangle);\n}\n\nvoid SummaryView::ThreadStart()\n{\n topographicSummarizer.Initialize(\n [](unsigned char r, unsigned char g, unsigned char b, unsigned char a) -> float\n {\n return ((float)((unsigned short)r + (((unsigned short)g) << 8))) \/ (float)std::numeric_limits::max();\n },\n [](float value, unsigned char* r, unsigned char* g, unsigned char* b, unsigned char* a) -> void\n {\n unsigned short averageValue = (unsigned short)(value * (float)std::numeric_limits::max());\n unsigned char actualValue = (unsigned char)(averageValue \/ 256);\n *r = actualValue;\n *g = actualValue;\n *b = actualValue;\n *a = 255;\n });\n\n overlaySummarizer.Initialize(\n [](unsigned char r, unsigned char g, unsigned char b, unsigned char a) -> float\n {\n return (float)b;\n },\n [](float value, unsigned char* r, unsigned char* g, unsigned char* b, unsigned char* a) -> void\n {\n \/\/ This will probably look odd but it's the best I can do.\n unsigned char averageValue = (unsigned char)value;\n PaletteWindow::TerrainType type = PaletteWindow::GetNearestTerrainType(averageValue);\n sf::Color color = PaletteWindow::GetTerrainColor(type);\n *r = color.r;\n *g = color.g;\n *b = color.b;\n *a = 110;\n });\n\n selectedTileRectangle = sf::RectangleShape(sf::Vector2f((float)(size \/ visibleSideCount), (float)(size \/ visibleSideCount)));\n selectedTileRectangle.setFillColor(sf::Color(0, 0, 0, 0));\n selectedTileRectangle.setOutlineThickness(1.0f);\n selectedTileRectangle.setOutlineColor(sf::Color::Green);\n UpdateSelectedTileRectangle();\n\n \/\/ 24 depth bits, 8 stencil bits, 8x AA, major version 4.\n sf::ContextSettings contextSettings = sf::ContextSettings(24, 8, 8, 4, 0);\n\n sf::Uint32 style = sf::Style::Titlebar;\n sf::RenderWindow window(sf::VideoMode(size, size), \"Summary\", style, contextSettings);\n window.setFramerateLimit(60);\n \n \/\/ TODO\n windowSelf = &window;\n\n \/\/ Start the main loop\n isAlive = true;\n while (isAlive)\n {\n HandleEvents(window);\n Render(window);\n\n \/\/ Display what we rendered.\n window.display();\n }\n}\n\nvoid SummaryView::Start()\n{\n executionThread = new std::thread(&SummaryView::ThreadStart, this);\n while (!isAlive)\n {\n sf::sleep(sf::milliseconds(50));\n }\n}\n\nvoid SummaryView::Stop()\n{\n isAlive = false;\n executionThread->join();\n delete executionThread;\n}Fudge factor necessary for the summary to be correct. Going to take a whil e to draw in all the tiles.#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"ImageUtils.h\"\n#include \"PaletteWindow.h\"\n#include \"SummaryView.h\"\n\nSummaryView::SummaryView(int size, int tileCount, int offsetX, int offsetY, int visibleSideCount, int reductionFactor)\n : isAlive(false), size(size), tileId(tileCount), selectedTile(2955),\n topographicSummarizer(size, tileCount, offsetX, offsetY, visibleSideCount, reductionFactor, \"..\/ContourTiler\/rasters\/summary\/\", \"summary.png\"),\n overlaySummarizer(size, tileCount, offsetX, offsetY, visibleSideCount, reductionFactor, \"..\/ContourTiler\/rasters\/summary\/\", \"overlay.png\"),\n windowSelf(nullptr), offsetX(offsetX), offsetY(offsetY), visibleSideCount(visibleSideCount)\n{\n}\n\nvoid SummaryView::RemapToTile(double* x, double* y)\n{\n int tileX, tileY;\n tileId.GetPositionFromId(selectedTile, &tileX, &tileY);\n\n (*x) *= ((double)1000 * tileId.GetTileCount());\n (*y) *= ((double)1000 * tileId.GetTileCount());\n\n (*x) -= (tileX * 1000);\n (*y) -= (tileY * 1000);\n}\n\nvoid SummaryView::MoveSelectedTile(Direction direction)\n{\n int x, y;\n tileId.GetPositionFromId(selectedTile, &x, &y);\n\n switch (direction)\n {\n case UP: ++y; break;\n case DOWN: --y; break;\n case LEFT: --x; break;\n case RIGHT: ++x; break;\n }\n\n if (topographicSummarizer.IsTileValid(x, y))\n {\n selectedTile = tileId.GetTileId(x, y);\n UpdateSelectedTileRectangle();\n\n \/\/ TODO this doesn't apply on startup, and should be fixed to not pass around the window pointer.\n if (windowSelf != nullptr)\n {\n std::stringstream titleString;\n titleString << \"Summary (\" << x << \", \" << y << \")\" << std::endl;\n windowSelf->setTitle(titleString.str());\n }\n }\n}\n\nvoid SummaryView::LoadSelectedTile(unsigned char** data, int offsetX, int offsetY)\n{\n if (*data != nullptr)\n {\n \/\/ We could also do topographic, but we (for now) don't support elevation changes with this program.\n\n ImageUtils::FreeImage(*data);\n *data = nullptr;\n }\n\n int x, y;\n tileId.GetPositionFromId(selectedTile, &x, &y);\n\n x += offsetX;\n y += offsetY;\n\n \/\/ Ensure we read a valid image.\n x = std::max(0, x);\n y = std::max(0, y);\n x = std::min(x, tileId.GetTileCount() - 1);\n y = std::min(y, tileId.GetTileCount() - 1);\n\n std::stringstream imageTile;\n imageTile << \"..\/ContourTiler\/rasters\/\" << y << \"\/\" << x << \".png\";\n\n int width, height;\n if (!ImageUtils::LoadImage(imageTile.str().c_str(), &width, &height, data))\n {\n std::cout << \"Failed to load \" << imageTile.str() << std::endl;\n }\n}\n\nvoid SummaryView::LoadSelectedTile(bool loadEdges, unsigned char** centerData, unsigned char** leftData, unsigned char** rightData, unsigned char** topData, unsigned char** bottomData)\n{\n LoadSelectedTile(centerData, 0, 0);\n \n \/\/ Don't reload the edges if we aren't saving when moving to speed up drawing\n if (loadEdges)\n {\n LoadSelectedTile(leftData, -1, 0);\n LoadSelectedTile(rightData, 1, 0);\n LoadSelectedTile(topData, 0, 1);\n LoadSelectedTile(bottomData, 0, -1);\n }\n}\n\n\/\/ We know that only the topographic data is what really matters. We do need to indicate a reload to both topographic and overlay layers though.\nvoid SummaryView::UpdateSelectedTile(unsigned char* newData)\n{\n int x, y;\n tileId.GetPositionFromId(selectedTile, &x, &y);\n topographicSummarizer.UpdateSummaryForTile(newData, x, y, true);\n overlaySummarizer.UpdateSummaryForTile(newData, x, y, false);\n}\n\nvoid SummaryView::UpdateSelectedTileRectangle()\n{\n int motionScale = size \/ visibleSideCount;\n int x, y;\n tileId.GetPositionFromId(selectedTile, &x, &y);\n selectedTileRectangle.setPosition(sf::Vector2f((float)((x - offsetX) * motionScale), (float)(size - (y - offsetY + 1) * motionScale)));\n}\n\nvoid SummaryView::HandleEvents(sf::RenderWindow& window)\n{\n \/\/ Handle all events.\n sf::Event event;\n while (window.pollEvent(event))\n {\n if (event.type == sf::Event::Closed)\n {\n \/\/ Ignore -- we only close if the main map editor closes.\n }\n }\n}\n\nvoid SummaryView::Render(sf::RenderWindow& window)\n{\n window.draw(topographicSummarizer.GetSummarizedSprite());\n window.draw(overlaySummarizer.GetSummarizedSprite());\n window.draw(selectedTileRectangle);\n}\n\nvoid SummaryView::ThreadStart()\n{\n topographicSummarizer.Initialize(\n [](unsigned char r, unsigned char g, unsigned char b, unsigned char a) -> float\n {\n return ((float)((unsigned short)r + (((unsigned short)g) << 8))) \/ (float)std::numeric_limits::max();\n },\n [](float value, unsigned char* r, unsigned char* g, unsigned char* b, unsigned char* a) -> void\n {\n unsigned short averageValue = (unsigned short)(value * (float)std::numeric_limits::max());\n unsigned char actualValue = (unsigned char)(averageValue \/ 256);\n *r = actualValue;\n *g = actualValue;\n *b = actualValue;\n *a = 255;\n });\n\n overlaySummarizer.Initialize(\n [](unsigned char r, unsigned char g, unsigned char b, unsigned char a) -> float\n {\n return (float)b;\n },\n [](float value, unsigned char* r, unsigned char* g, unsigned char* b, unsigned char* a) -> void\n {\n \/\/ This will probably look odd but it's the best I can do.\n unsigned char averageValue = (unsigned char)value;\n PaletteWindow::TerrainType type = PaletteWindow::GetNearestTerrainType(averageValue > 250 ? averageValue : averageValue + 10);\n sf::Color color = PaletteWindow::GetTerrainColor(type);\n *r = color.r;\n *g = color.g;\n *b = color.b;\n *a = 110;\n });\n\n selectedTileRectangle = sf::RectangleShape(sf::Vector2f((float)(size \/ visibleSideCount), (float)(size \/ visibleSideCount)));\n selectedTileRectangle.setFillColor(sf::Color(0, 0, 0, 0));\n selectedTileRectangle.setOutlineThickness(1.0f);\n selectedTileRectangle.setOutlineColor(sf::Color::Green);\n UpdateSelectedTileRectangle();\n\n \/\/ 24 depth bits, 8 stencil bits, 8x AA, major version 4.\n sf::ContextSettings contextSettings = sf::ContextSettings(24, 8, 8, 4, 0);\n\n sf::Uint32 style = sf::Style::Titlebar;\n sf::RenderWindow window(sf::VideoMode(size, size), \"Summary\", style, contextSettings);\n window.setFramerateLimit(60);\n \n \/\/ TODO\n windowSelf = &window;\n\n \/\/ Start the main loop\n isAlive = true;\n while (isAlive)\n {\n HandleEvents(window);\n Render(window);\n\n \/\/ Display what we rendered.\n window.display();\n }\n}\n\nvoid SummaryView::Start()\n{\n executionThread = new std::thread(&SummaryView::ThreadStart, this);\n while (!isAlive)\n {\n sf::sleep(sf::milliseconds(50));\n }\n}\n\nvoid SummaryView::Stop()\n{\n isAlive = false;\n executionThread->join();\n delete executionThread;\n}<|endoftext|>"} {"text":"\/*\n\tThis file is part of the E_Rendering library.\n\tCopyright (C) 2018 Sascha Brandt \n\t\n\tThis library is subject to the terms of the Mozilla Public License, v. 2.0.\n\tYou should have received a copy of the MPL along with this library; see the\n\tfile LICENSE. If not, you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n*\/\n#include \"E_VertexAccessor.h\"\n#include \"E_Mesh.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace E_Rendering{\nusing namespace Rendering;\n\n\/\/ ----------------------------------------\n\/\/ E_VertexAccessor\n\n\/\/! (static)\nEScript::Type * E_VertexAccessor::getTypeObject() {\n\t\/\/ E_VertexAccessor ---|> Object\n\tstatic EScript::ERef typeObject = new EScript::Type(EScript::Object::getTypeObject());\n\treturn typeObject.get();\n}\n\n\/\/! (static) init members\nvoid E_VertexAccessor::init(EScript::Namespace & lib) {\n\tEScript::Type * typeObject = E_VertexAccessor::getTypeObject();\n\tdeclareConstant(&lib,getClassName(),typeObject);\n\t\n\t\/\/!\t[ESMF] new Rendering.VertexAccessor( Mesh )\n\tES_CTOR(typeObject, 1, 1, new VertexAccessor(parameter[0].to(rt)->openVertexData()))\n\t\n\t\/\/! [ESMF] Geometry.Vec3 VertexAccessor.getPosition(Number index, [String attribute])\n\tES_MFUN(typeObject,const VertexAccessor,\"getPosition\",1,2,thisObj->getPosition(parameter[0].to(rt), parameter[1].toString(VertexAttributeIds::POSITION.toString())))\n\n\t\/\/! [ESMF] thisEObj VertexAccessor.setPosition(Number index, Geometry.Vec3, [String attribute])\n\tES_MFUN(typeObject,VertexAccessor,\"setPosition\",2,3,(thisObj->setPosition(parameter[0].to(rt), parameter[1].to(rt), parameter[2].toString(VertexAttributeIds::POSITION.toString())),thisEObj))\n\t\n\t\/\/! [ESMF] Geometry.Vec3 VertexAccessor.getNormal(Number index, [String attribute])\n\tES_MFUN(typeObject,const VertexAccessor,\"getNormal\",1,2,thisObj->getNormal(parameter[0].to(rt), parameter[1].toString(VertexAttributeIds::NORMAL.toString())))\n\n\t\/\/! [ESMF] thisEObj VertexAccessor.setNormal(Number index, Geometry.Vec3, [String attribute])\n\tES_MFUN(typeObject,VertexAccessor,\"setNormal\",2,3,(thisObj->setPosition(parameter[0].to(rt), parameter[1].to(rt), parameter[2].toString(VertexAttributeIds::NORMAL.toString())),thisEObj))\n\t\n\t\/\/! [ESMF] Util.Color4f VertexAccessor.getColor4f(Number index, [String attribute])\n\tES_MFUN(typeObject,const VertexAccessor,\"getColor4f\",1,2,thisObj->getColor4f(parameter[0].to(rt), parameter[1].toString(VertexAttributeIds::COLOR.toString())))\n\n\t\/\/! [ESMF] thisEObj VertexAccessor.setColor(Number index, Util.Color, [String attribute])\n\tES_MFUN(typeObject,VertexAccessor,\"setColor\",2,3,(thisObj->setColor(parameter[0].to(rt), parameter[1].to(rt), parameter[2].toString(VertexAttributeIds::COLOR.toString())),thisEObj))\n\t\n\t\/\/! [ESMF] Geometry.Vec2 VertexAccessor.getTexCoord(Number index, [String attribute])\n\tES_MFUN(typeObject,const VertexAccessor,\"getTexCoord\",1,2,thisObj->getTexCoord(parameter[0].to(rt), parameter[1].toString(VertexAttributeIds::TEXCOORD0.toString())))\n\n\t\/\/! [ESMF] thisEObj VertexAccessor.setTexCoord(Number index, Geometry.Vec2, [String attribute])\n\tES_MFUN(typeObject,VertexAccessor,\"setTexCoord\",2,3,(thisObj->setTexCoord(parameter[0].to(rt), parameter[1].to(rt), parameter[2].toString(VertexAttributeIds::TEXCOORD0.toString())),thisEObj))\n\t\n\t\/\/! [ESMF] Geometry.Vec4 VertexAccessor.getVec4(Number index, String attribute)\n\tES_MFUN(typeObject,const VertexAccessor,\"getVec4\",2,2,thisObj->getVec4(parameter[0].to(rt), parameter[1].toString()))\n\n\t\/\/! [ESMF] thisEObj VertexAccessor.setVec4(Number index, Geometry.Vec4, String attribute)\n\tES_MFUN(typeObject,VertexAccessor,\"setVec4\",3,3,(thisObj->setVec4(parameter[0].to(rt), parameter[1].to(rt), parameter[2].toString()),thisEObj))\n\n\t\/\/! [ESMF] Number VertexAccessor.getFloat(Number index, String attribute)\n\tES_MFUN(typeObject,const VertexAccessor,\"getFloat\",2,2,thisObj->getFloat(parameter[0].to(rt), parameter[1].toString()))\n\n\t\/\/! [ESMF] Array VertexAccessor.getFloats(Number index, String attribute)\n\tES_MFUN(typeObject,const VertexAccessor,\"getFloats\",2,2,EScript::Array::create(thisObj->getFloats(parameter[0].to(rt), parameter[1].toString())))\n\t\n\t\/\/! [ESMF] thisEObj VertexAccessor.setFloat(Number index, Number value, String attribute)\n\tES_MFUN(typeObject,VertexAccessor,\"setFloat\",3,3,(thisObj->setFloat(parameter[0].to(rt), parameter[1].toFloat(), parameter[2].toString()),thisEObj))\n\t\n\t\/\/! [ESMF] thisEObj VertexAccessor.setFloats(Number index, Array values, String attribute)\n\tES_MFUNCTION(typeObject,VertexAccessor,\"setFloats\",3,3,{\n\t\tEScript::Array * a=parameter[1].to(rt);\n\t\tstd::vector values;\n\t\tfor(auto v : *a)\n\t\t\tvalues.push_back(v.toFloat());\n\t\tthisObj->setFloats(parameter[0].to(rt), values, parameter[2].toString());\n\t\treturn thisEObj;\n\t})\n\t\n\t\/\/! [ESMF] Number VertexAccessor.getUInt(Number index, String attribute)\n\tES_MFUN(typeObject,const VertexAccessor,\"getUInt\",2,2,thisObj->getUInt(parameter[0].to(rt), parameter[1].toString()))\n\n\t\/\/! [ESMF] Array VertexAccessor.getUInts(Number index, String attribute)\n\tES_MFUN(typeObject,const VertexAccessor,\"getUInts\",2,2,EScript::Array::create(thisObj->getUInts(parameter[0].to(rt), parameter[1].toString())))\n\t\n\t\/\/! [ESMF] thisEObj VertexAccessor.setUInt(Number index, Number value, String attribute)\n\tES_MFUN(typeObject,VertexAccessor,\"setUInt\",3,3,(thisObj->setUInt(parameter[0].to(rt), parameter[1].toUInt(), parameter[2].toString()),thisEObj))\n\t\n\t\/\/! [ESMF] thisEObj VertexAccessor.setUInts(Number index, Array values, String attribute)\n\tES_MFUNCTION(typeObject,VertexAccessor,\"setUInts\",3,3,{\n\t\tEScript::Array * a=parameter[1].to(rt);\n\t\tstd::vector values;\n\t\tfor(auto v : *a)\n\t\t\tvalues.push_back(v.toUInt());\n\t\tthisObj->setUInts(parameter[0].to(rt), values, parameter[2].toString());\n\t\treturn thisEObj;\n\t})\n}\n\n}\nChanged bindings for VertexAccessor\/*\n\tThis file is part of the E_Rendering library.\n\tCopyright (C) 2018 Sascha Brandt \n\t\n\tThis library is subject to the terms of the Mozilla Public License, v. 2.0.\n\tYou should have received a copy of the MPL along with this library; see the\n\tfile LICENSE. If not, you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n*\/\n#include \"E_VertexAccessor.h\"\n#include \"E_Mesh.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace E_Rendering{\nusing namespace Rendering;\n\n\/\/ ----------------------------------------\n\/\/ E_VertexAccessor\n\n\/\/! (static)\nEScript::Type * E_VertexAccessor::getTypeObject() {\n\t\/\/ E_VertexAccessor ---|> Object\n\tstatic EScript::ERef typeObject = new EScript::Type(EScript::Object::getTypeObject());\n\treturn typeObject.get();\n}\n\n\/\/! (static) init members\nvoid E_VertexAccessor::init(EScript::Namespace & lib) {\n\tEScript::Type * typeObject = E_VertexAccessor::getTypeObject();\n\tdeclareConstant(&lib,getClassName(),typeObject);\n\t\n\t\/\/!\t[ESMF] new Rendering.VertexAccessor( Mesh )\n\tES_CTOR(typeObject, 1, 1, VertexAccessor::create(parameter[0].to(rt)))\n\t\n\t\/\/! [ESMF] Number VertexAccessor.getAttributeLocation(String attribute)\n\tES_MFUN(typeObject,const VertexAccessor,\"getAttributeLocation\",1,1,thisObj->getAttributeLocation(parameter[0].toString()))\n\t\n\t\/\/! [ESMF] Geometry.Vec3 VertexAccessor.getPosition(Number index, [String attribute | Number location])\n\tES_MFUN(typeObject,const VertexAccessor,\"getPosition\",1,2,\n\t\tparameter[1].isNull() || parameter[1]->isA(EScript::String::getTypeObject()) ? \n\t\tthisObj->getPosition(parameter[0].toUInt(), parameter[1].toString(VertexAttributeIds::POSITION.toString())) :\n\t\tthisObj->getPosition(parameter[0].toUInt(), parameter[1].to(rt))\n\t)\n\n\t\/\/! [ESMF] thisEObj VertexAccessor.setPosition(Number index, Geometry.Vec3, [String attribute | Number location])\n\tES_MFUN(typeObject,VertexAccessor,\"setPosition\",2,3,(\n\t\tparameter[2].isNull() || parameter[2]->isA(EScript::String::getTypeObject()) ? \n\t\tthisObj->setPosition(parameter[0].toUInt(), parameter[1].to(rt), parameter[2].toString(VertexAttributeIds::POSITION.toString())) :\t\t\n\t\tthisObj->setPosition(parameter[0].toUInt(), parameter[1].to(rt), parameter[2].to(rt))\n\t,thisEObj))\n\t\n\t\/\/! [ESMF] Geometry.Vec3 VertexAccessor.getNormal(Number index, [String attribute | Number location])\n\tES_MFUN(typeObject,const VertexAccessor,\"getNormal\",1,2,\n\t\tparameter[1].isNull() || parameter[1]->isA(EScript::String::getTypeObject()) ? \n\t\tthisObj->getNormal(parameter[0].toUInt(), parameter[1].toString(VertexAttributeIds::NORMAL.toString())) :\n\t\tthisObj->getNormal(parameter[0].toUInt(), parameter[1].to(rt))\n\t)\n\n\t\/\/! [ESMF] thisEObj VertexAccessor.setNormal(Number index, Geometry.Vec3, [String attribute | Number location])\n\tES_MFUN(typeObject,VertexAccessor,\"setNormal\",2,3,(\n\t\tparameter[2].isNull() || parameter[2]->isA(EScript::String::getTypeObject()) ? \n\t\tthisObj->setNormal(parameter[0].toUInt(), parameter[1].to(rt), parameter[2].toString(VertexAttributeIds::NORMAL.toString())) :\t\t\n\t\tthisObj->setNormal(parameter[0].toUInt(), parameter[1].to(rt), parameter[2].to(rt))\n\t,thisEObj))\n\t\n\t\/\/! [ESMF] Util.Color4f VertexAccessor.getColor4f(Number index, [String attribute | Number location])\n\tES_MFUN(typeObject,const VertexAccessor,\"getColor4f\",1,2,\n\t\tparameter[1].isNull() || parameter[1]->isA(EScript::String::getTypeObject()) ? \n\t\tthisObj->getColor4f(parameter[0].toUInt(), parameter[1].toString(VertexAttributeIds::COLOR.toString())) :\n\t\tthisObj->getColor4f(parameter[0].toUInt(), parameter[1].to(rt))\n\t)\n\n\t\/\/! [ESMF] thisEObj VertexAccessor.setColor(Number index, Util.Color4f, [String attribute | Number location])\n\tES_MFUN(typeObject,VertexAccessor,\"setColor\",2,3,(\n\t\tparameter[2].isNull() || parameter[2]->isA(EScript::String::getTypeObject()) ? \n\t\tthisObj->setColor(parameter[0].toUInt(), parameter[1].to(rt), parameter[2].toString(VertexAttributeIds::COLOR.toString())) :\t\t\n\t\tthisObj->setColor(parameter[0].toUInt(), parameter[1].to(rt), parameter[2].to(rt))\n\t,thisEObj))\n\t\n\t\/\/! [ESMF] Geometry.Vec2 VertexAccessor.getTexCoord(Number index, [String attribute | Number location])\n\tES_MFUN(typeObject,const VertexAccessor,\"getTexCoord\",1,2,\n\t\tparameter[1].isNull() || parameter[1]->isA(EScript::String::getTypeObject()) ? \n\t\tthisObj->getTexCoord(parameter[0].toUInt(), parameter[1].toString(VertexAttributeIds::TEXCOORD0.toString())) :\n\t\tthisObj->getTexCoord(parameter[0].toUInt(), parameter[1].to(rt))\n\t)\n\n\t\/\/! [ESMF] thisEObj VertexAccessor.setTexCoord(Number index, Geometry.Vec2, [String attribute | Number location])\n\tES_MFUN(typeObject,VertexAccessor,\"setTexCoord\",2,3,(\n\t\tparameter[2].isNull() || parameter[2]->isA(EScript::String::getTypeObject()) ? \n\t\tthisObj->setTexCoord(parameter[0].toUInt(), parameter[1].to(rt), parameter[2].toString(VertexAttributeIds::TEXCOORD0.toString())) :\t\t\n\t\tthisObj->setTexCoord(parameter[0].toUInt(), parameter[1].to(rt), parameter[2].to(rt))\n\t,thisEObj))\n\t\n\t\/\/! [ESMF] Geometry.Vec4 VertexAccessor.getVec4(Number index, String attribute | Number location)\n\tES_MFUN(typeObject,const VertexAccessor,\"getVec4\",2,2,\n\t\tparameter[1]->isA(EScript::String::getTypeObject()) ? \n\t\tthisObj->getVec4(parameter[0].toUInt(), parameter[1].toString()) :\n\t\tthisObj->getVec4(parameter[0].toUInt(), parameter[1].to(rt))\n\t)\n\n\t\/\/! [ESMF] thisEObj VertexAccessor.setVec4(Number index, Geometry.Vec4, String attribute | Number location)\n\tES_MFUN(typeObject,VertexAccessor,\"setVec4\",3,3,(\n\t\tparameter[2]->isA(EScript::String::getTypeObject()) ? \n\t\tthisObj->setVec4(parameter[0].toUInt(), parameter[1].to(rt), parameter[2].toString()) :\t\t\n\t\tthisObj->setVec4(parameter[0].toUInt(), parameter[1].to(rt), parameter[2].to(rt))\n\t,thisEObj))\n\t\t\n\t\/\/! [ESMF] Number VertexAccessor.getFloat(Number index, String attribute | Number location)\n\tES_MFUN(typeObject,const VertexAccessor,\"getFloat\",2,2,\n\t\tparameter[1]->isA(EScript::String::getTypeObject()) ? \n\t\tthisObj->readValue(parameter[0].toUInt(), parameter[1].toString()) :\n\t\tthisObj->readValue(parameter[0].toUInt(), parameter[1].to(rt))\n\t)\n\t\n\t\/\/! [ESMF] Number VertexAccessor.getFloats(Number index, String attribute | Number location, Number count)\n\tES_MFUN(typeObject,const VertexAccessor,\"getFloats\",3,3,\n\t\tEScript::Array::create(parameter[1]->isA(EScript::String::getTypeObject()) ? \n\t\tthisObj->readValues(parameter[0].toUInt(), parameter[1].toString(), parameter[2].toUInt()) :\n\t\tthisObj->readValues(parameter[0].toUInt(), parameter[1].to(rt), parameter[2].toUInt()))\n\t)\n\n\t\/\/! [ESMF] thisEObj VertexAccessor.setFloat(Number index, String attribute | Number location, Number value)\n\tES_MFUN(typeObject,VertexAccessor,\"setFloat\",3,3,(\n\t\tparameter[1]->isA(EScript::String::getTypeObject()) ? \n\t\tthisObj->writeValue(parameter[0].toUInt(), parameter[1].toString(), parameter[2].toFloat()) :\t\t\n\t\tthisObj->writeValue(parameter[0].toUInt(), parameter[1].to(rt), parameter[2].toFloat())\n\t,thisEObj))\n\n\t\/\/! [ESMF] thisEObj VertexAccessor.setFloats(Number index, String attribute, Array values)\n\tES_MFUNCTION(typeObject,VertexAccessor,\"setFloats\",3,3,{\n\t\tEScript::Array * a=parameter[2].to(rt);\n\t\tstd::vector values;\n\t\tfor(auto v : *a)\n\t\t\tvalues.push_back(v.toFloat());\n\t\tif(parameter[1]->isA(EScript::String::getTypeObject()))\n\t\t\tthisObj->writeValues(parameter[0].toUInt(), parameter[1].toString(), values);\n\t\telse\n\t\t\tthisObj->writeValues(parameter[0].toUInt(), parameter[1].to(rt), values);\n\t\treturn thisEObj;\n\t})\n\t\t\n\t\/\/! [ESMF] Number VertexAccessor.getUInt(Number index, String attribute | Number location)\n\tES_MFUN(typeObject,const VertexAccessor,\"getUInt\",2,2,\n\t\tparameter[1]->isA(EScript::String::getTypeObject()) ? \n\t\tthisObj->readValue(parameter[0].toUInt(), parameter[1].toString()) :\n\t\tthisObj->readValue(parameter[0].toUInt(), parameter[1].to(rt))\n\t)\n\t\n\t\/\/! [ESMF] Number VertexAccessor.getUInts(Number index, String attribute | Number location, Number count)\n\tES_MFUN(typeObject,const VertexAccessor,\"getUInts\",3,3,\n\t\tEScript::Array::create(parameter[1]->isA(EScript::String::getTypeObject()) ? \n\t\tthisObj->readValues(parameter[0].toUInt(), parameter[1].toString(), parameter[2].toUInt()) :\n\t\tthisObj->readValues(parameter[0].toUInt(), parameter[1].to(rt), parameter[2].toUInt()))\n\t)\n\n\t\/\/! [ESMF] thisEObj VertexAccessor.setUInt(Number index, String attribute | Number location, Number value)\n\tES_MFUN(typeObject,VertexAccessor,\"setUInt\",3,3,(\n\t\tparameter[1]->isA(EScript::String::getTypeObject()) ? \n\t\tthisObj->writeValue(parameter[0].toUInt(), parameter[1].toString(), parameter[2].toUInt()) :\t\t\n\t\tthisObj->writeValue(parameter[0].toUInt(), parameter[1].to(rt), parameter[2].toUInt())\n\t,thisEObj))\n\n\t\/\/! [ESMF] thisEObj VertexAccessor.setUInts(Number index, String attribute, Array values)\n\tES_MFUNCTION(typeObject,VertexAccessor,\"setUInts\",3,3,{\n\t\tEScript::Array * a=parameter[2].to(rt);\n\t\tstd::vector values;\n\t\tfor(auto v : *a)\n\t\t\tvalues.push_back(v.toUInt());\n\t\tif(parameter[1]->isA(EScript::String::getTypeObject()))\n\t\t\tthisObj->writeValues(parameter[0].toUInt(), parameter[1].toString(), values);\n\t\telse\n\t\t\tthisObj->writeValues(parameter[0].toUInt(), parameter[1].to(rt), values);\n\t\treturn thisEObj;\n\t})\n}\n\n}\n<|endoftext|>"} {"text":"\/\/-----------------------------------\n\/\/ Copyright Pierric Gimmig 2013-2017\n\/\/-----------------------------------\n\n#include \"Core.h\"\n#include \"OrbitModule.h\"\n#include \"Serialization.h\"\n#include \"Pdb.h\"\n#include \n\n#ifndef WIN32\n#include \"LinuxUtils.h\"\n#include \"Capture.h\"\n#include \"ScopeTimer.h\"\n#include \"OrbitUnreal.h\"\n#include \"Params.h\"\n#include \"OrbitProcess.h\"\n#include \"Path.h\"\n#endif\n\n\/\/-----------------------------------------------------------------------------\nModule::Module()\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nstd::wstring Module::GetPrettyName()\n{\n if( m_PrettyName.size() == 0 )\n {\n #ifdef WIN32\n m_PrettyName = Format( \"%s [%I64x - %I64x] %s\\r\\n\", m_Name.c_str(), m_AddressStart, m_AddressEnd, m_FullName.c_str() );\n m_AddressRange = Format( \"[%I64x - %I64x]\", m_AddressStart, m_AddressEnd );\n #else\n m_PrettyName = m_FullName;\n m_AddressRange = Format( \"[%016llx - %016llx]\", m_AddressStart, m_AddressEnd );\n m_PdbName = m_FullName;\n m_FoundPdb = true;\n #endif\n }\n\n return s2ws(m_PrettyName);\n}\n\n\/\/-----------------------------------------------------------------------------\nbool Module::IsDll() const\n{\n return ToLower( Path::GetExtension( s2ws(m_FullName) ) ) == std::wstring( L\".dll\" ) ||\n Contains(m_Name, \".so\" );\n}\n\n\/\/-----------------------------------------------------------------------------\nbool Module::LoadDebugInfo()\n{\n std::wstring pdbName = s2ws(m_PdbName);\n m_Pdb = std::make_shared( pdbName.c_str() );\n m_Pdb->SetMainModule( (HMODULE)m_AddressStart );\n\n PRINT_VAR(m_FoundPdb);\n if( m_FoundPdb )\n {\n return m_Pdb->LoadDataFromPdb();\n }\n\n return false;\n}\n\n\/\/-----------------------------------------------------------------------------\nuint64_t Module::ValidateAddress( uint64_t a_Address )\n{\n if( ContainsAddress(a_Address ) )\n return a_Address;\n\n \/\/ Treat input address as RVA\n uint64_t newAddress = m_AddressStart + a_Address;\n if( ContainsAddress(newAddress) )\n return newAddress;\n\n return 0xbadadd;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Module::SetLoaded(bool a_Value)\n{\n m_Loaded = a_Value;\n}\n\n\/\/-----------------------------------------------------------------------------\nORBIT_SERIALIZE( Module, 0 )\n{\n ORBIT_NVP_VAL( 0, m_Name );\n ORBIT_NVP_VAL( 0, m_FullName );\n ORBIT_NVP_VAL( 0, m_PdbName );\n ORBIT_NVP_VAL( 0, m_Directory );\n ORBIT_NVP_VAL( 0, m_PrettyName );\n ORBIT_NVP_VAL( 0, m_AddressRange );\n ORBIT_NVP_VAL( 0, m_DebugSignature );\n ORBIT_NVP_VAL( 0, m_AddressStart );\n ORBIT_NVP_VAL( 0, m_AddressEnd );\n ORBIT_NVP_VAL( 0, m_EntryPoint );\n ORBIT_NVP_VAL( 0, m_FoundPdb );\n ORBIT_NVP_VAL( 0, m_Selected );\n ORBIT_NVP_VAL( 0, m_Loaded );\n ORBIT_NVP_VAL( 0, m_PdbSize );\n}\n\n#ifndef WIN32\n\n\/\/-----------------------------------------------------------------------------\nFunction* Pdb::FunctionFromName( const std::string& a_Name )\n{\n uint64_t hash = StringHash(a_Name);\n auto iter = m_StringFunctionMap.find(hash);\n return (iter == m_StringFunctionMap.end()) ? nullptr : iter->second;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Pdb::LoadPdb( const wchar_t* a_PdbName )\n{\n m_FileName = a_PdbName;\n m_Name = Path::GetFileName(m_FileName);\n\n {\n SCOPE_TIMER_LOG(L\"nm\");\n \/\/ nm\n std::string nmCommand = std::string(\"nm \") + ws2s(a_PdbName) + std::string(\" -n -l\");\n std::string nmResult = LinuxUtils::ExecuteCommand(nmCommand.c_str());\n std::stringstream nmStream(nmResult);\n std::string line;\n while (std::getline(nmStream, line, '\\n'))\n {\n std::vector tokens = Tokenize(line, \" \\t\");\n if (tokens.size() > 2) \/\/ nm\n {\n Function func;\n func.m_Name = tokens[2];\n func.m_Address = std::stoull(tokens[0], nullptr, 16);\n func.m_PrettyName = LinuxUtils::Demangle(tokens[2].c_str());\n func.m_Module = ws2s(Path::GetFileName(a_PdbName));\n func.m_Pdb = this;\n this->AddFunction(func);\n\n \/\/ Debug - Temporary\n if (Contains(func.m_PrettyName, \"btCollisionDispatcher::needsCollision\"))\n {\n PRINT_VAR(func.m_PrettyName);\n }\n }\n }\n }\n ProcessData();\n\n {\n SCOPE_TIMER_LOG(L\"bpftrace -l\");\n \/\/ find functions that can receive bpftrace uprobes\n std::string bpfCommand = std::string(\"bpftrace -l 'uprobe: \") + ws2s(a_PdbName) + std::string(\"'\");\n std::string bpfResult = LinuxUtils::ExecuteCommand(bpfCommand.c_str());\n std::stringstream bpfStream(bpfResult);\n std::string line;\n while (std::getline(bpfStream, line, '\\n'))\n {\n std::vector tokens = Tokenize(line);\n if (tokens.size() == 2) \/\/ bpftrace\n {\n Function func;\n auto probeTokens = Tokenize(tokens[1], \":\");\n if (probeTokens.size() == 2)\n {\n std::string mangled = probeTokens[1];\n std::string demangled = LinuxUtils::Demangle(probeTokens[1].c_str());\n\n \/\/ Debug - Temporary\n if (Contains(demangled, \"btCollisionDispatcher::needsCollision\"))\n PRINT_VAR(demangled);\n Function* func = FunctionFromName(demangled);\n if (func && func->m_Probe.empty())\n {\n std::string probe = Replace(tokens[1], \".\", \"*\");\n func->m_Probe = probe;\n }\n }\n }\n }\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Pdb::LoadPdbAsync( const wchar_t* a_PdbName, std::function a_CompletionCallback )\n{\n m_LoadingCompleteCallback = a_CompletionCallback;\n LoadPdb(a_PdbName);\n a_CompletionCallback();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Pdb::ProcessData()\n{\n SCOPE_TIMER_LOG( L\"ProcessData\" );\n ScopeLock lock( Capture::GTargetProcess->GetDataMutex() );\n\n auto & functions = Capture::GTargetProcess->GetFunctions();\n auto & globals = Capture::GTargetProcess->GetGlobals();\n\n functions.reserve( functions.size() + m_Functions.size() );\n\n for( Function & func : m_Functions )\n {\n func.m_Pdb = this;\n functions.push_back( &func );\n GOrbitUnreal.OnFunctionAdded( &func );\n }\n\n if( GParams.m_FindFileAndLineInfo )\n {\n SCOPE_TIMER_LOG(L\"Find File and Line info\");\n for( Function & func : m_Functions )\n {\n func.FindFile();\n }\n }\n\n for( Type & type : m_Types )\n {\n type.m_Pdb = this;\n Capture::GTargetProcess->AddType( type );\n GOrbitUnreal.OnTypeAdded( &type );\n }\n\n for( Variable & var : m_Globals )\n {\n var.m_Pdb = this;\n globals.push_back( &var );\n }\n\n for( auto & it : m_TypeMap )\n {\n it.second.m_Pdb = this;\n }\n\n PopulateFunctionMap();\n PopulateStringFunctionMap();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Pdb::PopulateFunctionMap()\n{\n m_IsPopulatingFunctionMap = true;\n \n SCOPE_TIMER_LOG( L\"Pdb::PopulateFunctionMap\" );\n\n uint64_t baseAddress = (uint64_t)GetHModule();\n bool rvaAddresses = false;\n\n \/\/ It seems nm can return addresses as VA or RVA\n \/\/ TODO: investigate, use simple test to detect RVA\n for( Function & function : m_Functions )\n {\n if( function.m_Address > 0 && function.m_Address < baseAddress )\n {\n rvaAddresses = true;\n break;\n }\n }\n\n for( Function & Function : m_Functions )\n {\n uint64_t RVA = rvaAddresses ? Function.m_Address : Function.m_Address - (uint64_t)GetHModule();\n m_FunctionMap.insert( std::make_pair( RVA, &Function ) );\n }\n\n m_IsPopulatingFunctionMap = false;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Pdb::PopulateStringFunctionMap()\n{\n m_IsPopulatingFunctionStringMap = true;\n\n {\n \/\/SCOPE_TIMER_LOG( L\"Reserving map\" );\n m_StringFunctionMap.reserve( unsigned ( 1.5f * (float)m_Functions.size() ) );\n }\n\n {\n \/\/SCOPE_TIMER_LOG( L\"Hash\" );\n for( Function & Function : m_Functions )\n {\n Function.Hash();\n }\n }\n\n {\n \/\/SCOPE_TIMER_LOG( L\"Map inserts\" );\n\n for( Function & Function : m_Functions )\n {\n m_StringFunctionMap[Function.m_NameHash] = &Function;\n }\n }\n\n m_IsPopulatingFunctionStringMap = false;\n}\n\n\/\/-----------------------------------------------------------------------------\nFunction* Pdb::GetFunctionFromExactAddress( uint64_t a_Address )\n{\n uint64_t RVA = a_Address - (uint64_t)GetHModule();\n auto iter = m_FunctionMap.find(RVA);\n return (iter != m_FunctionMap.end()) ? iter->second : nullptr;\n}\n\n\/\/-----------------------------------------------------------------------------\nFunction* Pdb::GetFunctionFromProgramCounter( uint64_t a_Address )\n{\n uint64_t RVA = a_Address - (uint64_t)GetHModule();\n\n auto it = m_FunctionMap.upper_bound( RVA );\n if (!m_FunctionMap.empty() && it != m_FunctionMap.begin())\n {\n --it;\n Function* func = it->second;\n return func;\n }\n\n return nullptr;\n}\n\n#endif\n\n\/\/-----------------------------------------------------------------------------\nORBIT_SERIALIZE(ModuleDebugInfo, 0)\n{\n ORBIT_NVP_VAL(0, m_Pid);\n ORBIT_NVP_VAL(0, m_Name);\n ORBIT_NVP_VAL(0, m_Functions);\n}Fix Linux build.\/\/-----------------------------------\n\/\/ Copyright Pierric Gimmig 2013-2017\n\/\/-----------------------------------\n\n#include \"Core.h\"\n#include \"OrbitModule.h\"\n#include \"Serialization.h\"\n#include \"Pdb.h\"\n#include \n\n#ifndef WIN32\n#include \"LinuxUtils.h\"\n#include \"Capture.h\"\n#include \"ScopeTimer.h\"\n#include \"OrbitUnreal.h\"\n#include \"Params.h\"\n#include \"OrbitProcess.h\"\n#include \"Path.h\"\n#endif\n\n\/\/-----------------------------------------------------------------------------\nModule::Module()\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nstd::wstring Module::GetPrettyName()\n{\n if( m_PrettyName.size() == 0 )\n {\n #ifdef WIN32\n m_PrettyName = Format( \"%s [%I64x - %I64x] %s\\r\\n\", m_Name.c_str(), m_AddressStart, m_AddressEnd, m_FullName.c_str() );\n m_AddressRange = Format( \"[%I64x - %I64x]\", m_AddressStart, m_AddressEnd );\n #else\n m_PrettyName = m_FullName;\n m_AddressRange = Format( \"[%016llx - %016llx]\", m_AddressStart, m_AddressEnd );\n m_PdbName = m_FullName;\n m_FoundPdb = true;\n #endif\n }\n\n return s2ws(m_PrettyName);\n}\n\n\/\/-----------------------------------------------------------------------------\nbool Module::IsDll() const\n{\n return ToLower( Path::GetExtension( s2ws(m_FullName) ) ) == std::wstring( L\".dll\" ) ||\n Contains(m_Name, \".so\" );\n}\n\n\/\/-----------------------------------------------------------------------------\nbool Module::LoadDebugInfo()\n{\n std::wstring pdbName = s2ws(m_PdbName);\n m_Pdb = std::make_shared( pdbName.c_str() );\n m_Pdb->SetMainModule( (HMODULE)m_AddressStart );\n\n PRINT_VAR(m_FoundPdb);\n if( m_FoundPdb )\n {\n return m_Pdb->LoadDataFromPdb();\n }\n\n return false;\n}\n\n\/\/-----------------------------------------------------------------------------\nuint64_t Module::ValidateAddress( uint64_t a_Address )\n{\n if( ContainsAddress(a_Address ) )\n return a_Address;\n\n \/\/ Treat input address as RVA\n uint64_t newAddress = m_AddressStart + a_Address;\n if( ContainsAddress(newAddress) )\n return newAddress;\n\n return 0xbadadd;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Module::SetLoaded(bool a_Value)\n{\n m_Loaded = a_Value;\n}\n\n\/\/-----------------------------------------------------------------------------\nORBIT_SERIALIZE( Module, 0 )\n{\n ORBIT_NVP_VAL( 0, m_Name );\n ORBIT_NVP_VAL( 0, m_FullName );\n ORBIT_NVP_VAL( 0, m_PdbName );\n ORBIT_NVP_VAL( 0, m_Directory );\n ORBIT_NVP_VAL( 0, m_PrettyName );\n ORBIT_NVP_VAL( 0, m_AddressRange );\n ORBIT_NVP_VAL( 0, m_DebugSignature );\n ORBIT_NVP_VAL( 0, m_AddressStart );\n ORBIT_NVP_VAL( 0, m_AddressEnd );\n ORBIT_NVP_VAL( 0, m_EntryPoint );\n ORBIT_NVP_VAL( 0, m_FoundPdb );\n ORBIT_NVP_VAL( 0, m_Selected );\n ORBIT_NVP_VAL( 0, m_Loaded );\n ORBIT_NVP_VAL( 0, m_PdbSize );\n}\n\n#ifndef WIN32\n\n\/\/-----------------------------------------------------------------------------\nFunction* Pdb::FunctionFromName( const std::string& a_Name )\n{\n uint64_t hash = StringHash(a_Name);\n auto iter = m_StringFunctionMap.find(hash);\n return (iter == m_StringFunctionMap.end()) ? nullptr : iter->second;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool Pdb::LoadPdb( const wchar_t* a_PdbName )\n{\n m_FileName = a_PdbName;\n m_Name = Path::GetFileName(m_FileName);\n\n {\n SCOPE_TIMER_LOG(L\"nm\");\n \/\/ nm\n std::string nmCommand = std::string(\"nm \") + ws2s(a_PdbName) + std::string(\" -n -l\");\n std::string nmResult = LinuxUtils::ExecuteCommand(nmCommand.c_str());\n std::stringstream nmStream(nmResult);\n std::string line;\n while (std::getline(nmStream, line, '\\n'))\n {\n std::vector tokens = Tokenize(line, \" \\t\");\n if (tokens.size() > 2) \/\/ nm\n {\n Function func;\n func.m_Name = tokens[2];\n func.m_Address = std::stoull(tokens[0], nullptr, 16);\n func.m_PrettyName = LinuxUtils::Demangle(tokens[2].c_str());\n func.m_Module = ws2s(Path::GetFileName(a_PdbName));\n func.m_Pdb = this;\n this->AddFunction(func);\n\n \/\/ Debug - Temporary\n if (Contains(func.m_PrettyName, \"btCollisionDispatcher::needsCollision\"))\n {\n PRINT_VAR(func.m_PrettyName);\n }\n }\n }\n }\n ProcessData();\n\n {\n SCOPE_TIMER_LOG(L\"bpftrace -l\");\n \/\/ find functions that can receive bpftrace uprobes\n std::string bpfCommand = std::string(\"bpftrace -l 'uprobe: \") + ws2s(a_PdbName) + std::string(\"'\");\n std::string bpfResult = LinuxUtils::ExecuteCommand(bpfCommand.c_str());\n std::stringstream bpfStream(bpfResult);\n std::string line;\n while (std::getline(bpfStream, line, '\\n'))\n {\n std::vector tokens = Tokenize(line);\n if (tokens.size() == 2) \/\/ bpftrace\n {\n Function func;\n auto probeTokens = Tokenize(tokens[1], \":\");\n if (probeTokens.size() == 2)\n {\n std::string mangled = probeTokens[1];\n std::string demangled = LinuxUtils::Demangle(probeTokens[1].c_str());\n\n \/\/ Debug - Temporary\n if (Contains(demangled, \"btCollisionDispatcher::needsCollision\"))\n PRINT_VAR(demangled);\n Function* func = FunctionFromName(demangled);\n if (func && func->m_Probe.empty())\n {\n std::string probe = Replace(tokens[1], \".\", \"*\");\n func->m_Probe = probe;\n }\n }\n }\n }\n }\n\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Pdb::LoadPdbAsync( const wchar_t* a_PdbName, std::function a_CompletionCallback )\n{\n m_LoadingCompleteCallback = a_CompletionCallback;\n LoadPdb(a_PdbName);\n a_CompletionCallback();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Pdb::ProcessData()\n{\n SCOPE_TIMER_LOG( L\"ProcessData\" );\n ScopeLock lock( Capture::GTargetProcess->GetDataMutex() );\n\n auto & functions = Capture::GTargetProcess->GetFunctions();\n auto & globals = Capture::GTargetProcess->GetGlobals();\n\n functions.reserve( functions.size() + m_Functions.size() );\n\n for( Function & func : m_Functions )\n {\n func.m_Pdb = this;\n functions.push_back( &func );\n GOrbitUnreal.OnFunctionAdded( &func );\n }\n\n if( GParams.m_FindFileAndLineInfo )\n {\n SCOPE_TIMER_LOG(L\"Find File and Line info\");\n for( Function & func : m_Functions )\n {\n func.FindFile();\n }\n }\n\n for( Type & type : m_Types )\n {\n type.m_Pdb = this;\n Capture::GTargetProcess->AddType( type );\n GOrbitUnreal.OnTypeAdded( &type );\n }\n\n for( Variable & var : m_Globals )\n {\n var.m_Pdb = this;\n globals.push_back( &var );\n }\n\n for( auto & it : m_TypeMap )\n {\n it.second.m_Pdb = this;\n }\n\n PopulateFunctionMap();\n PopulateStringFunctionMap();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Pdb::PopulateFunctionMap()\n{\n m_IsPopulatingFunctionMap = true;\n \n SCOPE_TIMER_LOG( L\"Pdb::PopulateFunctionMap\" );\n\n uint64_t baseAddress = (uint64_t)GetHModule();\n bool rvaAddresses = false;\n\n \/\/ It seems nm can return addresses as VA or RVA\n \/\/ TODO: investigate, use simple test to detect RVA\n for( Function & function : m_Functions )\n {\n if( function.m_Address > 0 && function.m_Address < baseAddress )\n {\n rvaAddresses = true;\n break;\n }\n }\n\n for( Function & Function : m_Functions )\n {\n uint64_t RVA = rvaAddresses ? Function.m_Address : Function.m_Address - (uint64_t)GetHModule();\n m_FunctionMap.insert( std::make_pair( RVA, &Function ) );\n }\n\n m_IsPopulatingFunctionMap = false;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Pdb::PopulateStringFunctionMap()\n{\n m_IsPopulatingFunctionStringMap = true;\n\n {\n \/\/SCOPE_TIMER_LOG( L\"Reserving map\" );\n m_StringFunctionMap.reserve( unsigned ( 1.5f * (float)m_Functions.size() ) );\n }\n\n {\n \/\/SCOPE_TIMER_LOG( L\"Hash\" );\n for( Function & Function : m_Functions )\n {\n Function.Hash();\n }\n }\n\n {\n \/\/SCOPE_TIMER_LOG( L\"Map inserts\" );\n\n for( Function & Function : m_Functions )\n {\n m_StringFunctionMap[Function.m_NameHash] = &Function;\n }\n }\n\n m_IsPopulatingFunctionStringMap = false;\n}\n\n\/\/-----------------------------------------------------------------------------\nFunction* Pdb::GetFunctionFromExactAddress( uint64_t a_Address )\n{\n uint64_t RVA = a_Address - (uint64_t)GetHModule();\n auto iter = m_FunctionMap.find(RVA);\n return (iter != m_FunctionMap.end()) ? iter->second : nullptr;\n}\n\n\/\/-----------------------------------------------------------------------------\nFunction* Pdb::GetFunctionFromProgramCounter( uint64_t a_Address )\n{\n uint64_t RVA = a_Address - (uint64_t)GetHModule();\n\n auto it = m_FunctionMap.upper_bound( RVA );\n if (!m_FunctionMap.empty() && it != m_FunctionMap.begin())\n {\n --it;\n Function* func = it->second;\n return func;\n }\n\n return nullptr;\n}\n\n#endif\n\n\/\/-----------------------------------------------------------------------------\nORBIT_SERIALIZE(ModuleDebugInfo, 0)\n{\n ORBIT_NVP_VAL(0, m_Pid);\n ORBIT_NVP_VAL(0, m_Name);\n ORBIT_NVP_VAL(0, m_Functions);\n}<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\nint main(int argc, char * argv[])\n{\n return 0;\n}\nadded basic adobe example on which i will begin working#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n#if 0\nclass object_t\n{\n public:\n virtual ~object_t() {}\n virtual void draw(ostream&, size_t) const = 0;\n};\n\nusing document_t = vector>;\n\nvoid draw(const document_t& x, ostream& out, size_t position)\n{\n out << string(position, ' ') << \"\" << endl;\n for (const auto& e : x )\n e->draw(out, position + 2);\n out << string(position, ' ') << \"<\/document>\" << endl;\n}\n\nclass my_class_t : public object_t\n{\n public:\n void draw(ostream &out, size_t position) const\n {\n out << string(position, ' ') << \"my_class_t\" << endl;\n }\n};\n\nint main(int argc, char * argv[])\n{\n document_t document;\n document.emplace_back(new my_class_t{});\n draw(document,cout, 1);\n return 0;\n}\n#else\nclass object_t\n{\n public:\n template \n object_t(T x) : self_(make_shared>(move(x))) {}\n void draw(ostream& out, size_t position) const\n {\n self_->draw_(out,position);\n }\n\n private:\n struct concept_t\n {\n virtual ~concept_t() = default;\n virtual void draw_(ostream&, size_t) const = 0;\n };\n\n template\n struct model : concept_t\n {\n model(T x) : data_(move(x)) {}\n void draw_(ostream& out, size_t position) const\n {\n data_.draw(out,position);\n }\n T data_;\n };\n\n shared_ptr self_;\n};\n\nusing document_t = vector;\n\nvoid draw(const document_t& x, ostream& out, size_t position)\n{\n out << string(position, ' ') << \"\" << endl;\n for (const auto& e : x )\n e.draw(out, position + 2);\n out << string(position, ' ') << \"<\/document>\" << endl;\n}\n\nclass my_class_t\n{\n public:\n void draw(ostream& out, size_t position) const\n {\n out << string(position, ' ') << \"my_class_t\" << endl;\n }\n};\n\nint main()\n{\n document_t document;\n document.emplace_back(my_class_t{});\n draw(document,cout,0);\n}\n#endif\n<|endoftext|>"} {"text":"\/\/ SmallGames.cpp : Definiert die exportierten Funktionen fr die DLL-Anwendung.\n\/\/ @author Florian Dahlitz\n\n#include \"stdafx.h\"\n\n#include \"SmallGames.h\"\n\nvoid ISmallGames::HangingMan::setupGame()\n{\n\twordlist = getWordlist();\n\tword = getRandomWord(wordlist);\n\tboost::to_upper(word);\n\tuserWord = \"_\";\n\n\tfor (unsigned int i = 0; i < word.size() - 1; ++i)\n\t\tuserWord += \"_\";\n\n\treturn;\n}\n\nvoid ISmallGames::HangingMan::buildWindow()\n{\n\tsystem(\"cls\");\n\n\tstd::cout << \"THE HANGING MAN\" << std::endl;\n\n\tfor (it = hangingManParts.begin(); it != hangingManParts.end(); ++it)\n\t\tif (it->first == m_efforts)\n\t\t\tstd::cout << it->second << std::endl << std::endl;\n\n\tfor (int i = 0; i < (m_hangingMan - manHeight[m_efforts]); ++i)\n\t\tstd::cout << \"\\n\";\n\n\tstd::cout << \"\" << std::endl << std::endl;\t\/\/ clean buffer + better overview\n\n\tfor (int i = 0; i < userWord.length(); i++)\n\t\tstd::cout << userWord[i] << \" \";\n\n\tstd::cout << std::endl; \/\/ clean buffer\n\n\treturn;\n}\n\nstd::map ISmallGames::HangingMan::getWordlist()\n{\n\tunsigned int i = 0;\n\tstd::string strWord;\n\tstd::map wordlist;\n\tstd::ifstream worldlistFile(m_path);\n\tif (worldlistFile.fail())\n\t\tstd::cout << m_path << std::endl;\n\t\/\/ TODO: change reading file w\/ vectors -> read something about\n\twhile (std::getline(worldlistFile, strWord))\n\t{\n\t\twordlist[i] = strWord;\n\t\tstd::cout << ++i << \" - \" << strWord << std::endl;\n\t}\n\n\treturn wordlist;\n}\n\nstd::string ISmallGames::HangingMan::getRandomWord(std::map wordlist)\n{\n\tstd::string randomWord;\n\tauto iter = wordlist.begin();\n\n\tsrand(time(NULL));\n\tstd::advance(iter, rand() % wordlist.size());\n\trandomWord = iter->second;\n\n\twordlist.erase(iter);\n\t\n\treturn randomWord;\n}\n\nvoid ISmallGames::HangingMan::playGame()\n{\n\tdo {\n\t\tbuildWindow();\n\n\t\tchar userChar = getUserChar();\n\t\taddToUserWord(userChar);\n\n\t} while (userWord.compare(word) && (m_efforts != 6));\n\n\treturn;\n}\n\nchar ISmallGames::HangingMan::getUserChar()\n{\n\tchar userChar;\n\n\tdo {\n\t\tstd::cout << \"Type in a character: \";\n\t\tstd::cin >> userChar;\n\t\tuserChar = toupper(userChar);\n\t} while ((usedChars.count(userChar) == 1) || (allowedChars.count(userChar) != 1));\n\n\tusedChars[userChar] = userChar;\n\n\treturn userChar;\n}\n\nvoid ISmallGames::HangingMan::addToUserWord(char userChar)\n{\n\tsize_t found = word.find(userChar);\n\t\n\tif (found == std::string::npos)\n\t\tm_efforts++;\n\n\twhile (found != std::string::npos)\n\t{\n\t\tuserWord[found] = userChar;\n\t\tfound = word.find(userChar, found+1);\n\t}\n\n\treturn;\n}\nfixed issue #2 -> multiple chars at one input\/\/ SmallGames.cpp : Definiert die exportierten Funktionen fr die DLL-Anwendung.\n\/\/ @author Florian Dahlitz\n\n#include \"stdafx.h\"\n\n#include \"SmallGames.h\"\n\nvoid ISmallGames::HangingMan::setupGame()\n{\n\twordlist = getWordlist();\n\tword = getRandomWord(wordlist);\n\tboost::to_upper(word);\n\tuserWord = \"_\";\n\n\tfor (unsigned int i = 0; i < word.size() - 1; ++i)\n\t\tuserWord += \"_\";\n\n\treturn;\n}\n\nvoid ISmallGames::HangingMan::buildWindow()\n{\n\tsystem(\"cls\");\n\n\tstd::cout << \"THE HANGING MAN\" << std::endl;\n\n\tfor (it = hangingManParts.begin(); it != hangingManParts.end(); ++it)\n\t\tif (it->first == m_efforts)\n\t\t\tstd::cout << it->second << std::endl << std::endl;\n\n\tfor (int i = 0; i < (m_hangingMan - manHeight[m_efforts]); ++i)\n\t\tstd::cout << \"\\n\";\n\n\tstd::cout << \"\" << std::endl << std::endl;\t\/\/ clean buffer + better overview\n\n\tfor (int i = 0; i < userWord.length(); i++)\n\t\tstd::cout << userWord[i] << \" \";\n\n\tstd::cout << std::endl; \/\/ clean buffer\n\n\treturn;\n}\n\nstd::map ISmallGames::HangingMan::getWordlist()\n{\n\tunsigned int i = 0;\n\tstd::string strWord;\n\tstd::map wordlist;\n\tstd::ifstream worldlistFile(m_path);\n\tif (worldlistFile.fail())\n\t\tstd::cout << m_path << std::endl;\n\t\/\/ TODO: change reading file w\/ vectors -> read something about\n\twhile (std::getline(worldlistFile, strWord))\n\t{\n\t\twordlist[i] = strWord;\n\t\tstd::cout << ++i << \" - \" << strWord << std::endl;\n\t}\n\n\treturn wordlist;\n}\n\nstd::string ISmallGames::HangingMan::getRandomWord(std::map wordlist)\n{\n\tstd::string randomWord;\n\tauto iter = wordlist.begin();\n\n\tsrand(time(NULL));\n\tstd::advance(iter, rand() % wordlist.size());\n\trandomWord = iter->second;\n\n\twordlist.erase(iter);\n\t\n\treturn randomWord;\n}\n\nvoid ISmallGames::HangingMan::playGame()\n{\n\tdo {\n\t\tbuildWindow();\n\n\t\tchar userChar = getUserChar();\n\t\taddToUserWord(userChar);\n\n\t} while (userWord.compare(word) && (m_efforts != 6));\n\n\treturn;\n}\n\nchar ISmallGames::HangingMan::getUserChar()\n{\n\tstd::string userInput;\n\tchar userChar;\n\n\tdo {\n\t\tstd::cout << \"Type in a character: \";\n\t\tstd::cin >> userInput;\n\t\tuserChar = userInput[0];\n\t\tuserChar = toupper(userChar);\n\t} while ((usedChars.count(userChar) == 1) || (allowedChars.count(userChar) != 1));\n\n\tusedChars[userChar] = userChar;\n\n\treturn userChar;\n}\n\nvoid ISmallGames::HangingMan::addToUserWord(char userChar)\n{\n\tsize_t found = word.find(userChar);\n\t\n\tif (found == std::string::npos)\n\t\tm_efforts++;\n\n\twhile (found != std::string::npos)\n\t{\n\t\tuserWord[found] = userChar;\n\t\tfound = word.find(userChar, found+1);\n\t}\n\n\treturn;\n}\n<|endoftext|>"} {"text":"#include \"Iop_Sysmem.h\"\r\n#include \"..\/Log.h\"\r\n#include \"Iop_SifMan.h\"\r\n\r\nusing namespace Iop;\r\n\r\n#define LOG_NAME (\"iop_sysmem\")\r\n\r\n#define FUNCTION_ALLOCATEMEMORY\t\t\t\"AllocateMemory\"\r\n#define FUNCTION_FREEMEMORY\t\t\t\t\"FreeMemory\"\r\n#define FUNCTION_PRINTF\t\t\t\t\t\"printf\"\r\n#define FUNCTION_QUERYMEMSIZE\t\t\t\"QueryMemSize\"\r\n#define FUNCTION_QUERYMAXFREEMEMSIZE\t\"QueryMaxFreeMemSize\"\r\n\r\n#define MIN_BLOCK_SIZE 0x20\r\n\r\nCSysmem::CSysmem(uint8* ram, uint32 memoryBegin, uint32 memoryEnd, uint32 blockBase, CStdio& stdio, CIoman& ioman, CSifMan& sifMan)\r\n: m_iopRam(ram)\r\n, m_memoryBegin(memoryBegin)\r\n, m_memoryEnd(memoryEnd)\r\n, m_stdio(stdio)\r\n, m_ioman(ioman)\r\n, m_memorySize(memoryEnd - memoryBegin)\r\n, m_blocks(reinterpret_cast(&ram[blockBase]), 1, MAX_BLOCKS)\r\n{\r\n\t\/\/Initialize block map\r\n\tm_headBlockId = m_blocks.Allocate();\r\n\tBLOCK* block = m_blocks[m_headBlockId];\r\n\tblock->address\t\t= m_memorySize;\r\n\tblock->size\t\t\t= 0;\r\n\tblock->nextBlock\t= 0;\r\n\r\n\t\/\/Register sif module\r\n\tsifMan.RegisterModule(MODULE_ID, this);\r\n}\r\n\r\nCSysmem::~CSysmem()\r\n{\r\n\r\n}\r\n\r\nstd::string CSysmem::GetId() const\r\n{\r\n\treturn \"sysmem\";\r\n}\r\n\r\nstd::string CSysmem::GetFunctionName(unsigned int functionId) const\r\n{\r\n\tswitch(functionId)\r\n\t{\r\n\tcase 4:\r\n\t\treturn FUNCTION_ALLOCATEMEMORY;\r\n\t\tbreak;\r\n\tcase 5:\r\n\t\treturn FUNCTION_FREEMEMORY;\r\n\t\tbreak;\r\n\tcase 6:\r\n\t\treturn FUNCTION_QUERYMEMSIZE;\r\n\t\tbreak;\r\n\tcase 7:\r\n\t\treturn FUNCTION_QUERYMAXFREEMEMSIZE;\r\n\t\tbreak;\r\n\tcase 14:\r\n\t\treturn FUNCTION_PRINTF;\r\n\t\tbreak;\r\n\tdefault:\r\n\t\treturn \"unknown\";\r\n\t\tbreak;\r\n\t}\r\n}\r\n\r\nvoid CSysmem::Invoke(CMIPS& context, unsigned int functionId)\r\n{\r\n\tswitch(functionId)\r\n\t{\r\n\tcase 4:\r\n\t\tcontext.m_State.nGPR[CMIPS::V0].nD0 = static_cast(AllocateMemory(\r\n\t\t\tcontext.m_State.nGPR[CMIPS::A1].nV[0],\r\n\t\t\tcontext.m_State.nGPR[CMIPS::A0].nV[0],\r\n\t\t\tcontext.m_State.nGPR[CMIPS::A2].nV[0]\r\n\t\t\t));\r\n\t\tbreak;\r\n\tcase 5:\r\n\t\tcontext.m_State.nGPR[CMIPS::V0].nD0 = static_cast(FreeMemory(\r\n\t\t\tcontext.m_State.nGPR[CMIPS::A0].nV[0]\r\n\t\t\t));\r\n\t\tbreak;\r\n\tcase 6:\r\n\t\tcontext.m_State.nGPR[CMIPS::V0].nD0 = m_memorySize;\r\n\t\tbreak;\r\n\tcase 7:\r\n\t\tcontext.m_State.nGPR[CMIPS::V0].nD0 = QueryMaxFreeMemSize();\r\n\t\tbreak;\r\n\tcase 14:\r\n\t\tm_stdio.__printf(context);\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tCLog::GetInstance().Print(LOG_NAME, \"%s(%0.8X): Unknown function (%d) called.\\r\\n\", __FUNCTION__, context.m_State.nPC, functionId);\r\n\t\tbreak;\r\n\t}\r\n}\r\n\r\nbool CSysmem::Invoke(uint32 method, uint32* args, uint32 argsSize, uint32* ret, uint32 retSize, uint8* ram)\r\n{\r\n\tswitch(method)\r\n\t{\r\n\tcase 0x01:\r\n\t\tassert(retSize == 4);\r\n\t\tret[0] = SifAllocate(args[0]);\r\n\t\tbreak;\r\n\tcase 0x02:\r\n\t\tassert(argsSize == 4);\r\n\t\tret[0] = SifFreeMemory(args[0]);\r\n\t\tbreak;\r\n\tcase 0x03:\r\n\t\tassert(argsSize >= 4);\r\n\t\tassert(retSize == 4);\r\n\t\tret[0] = SifLoadMemory(args[0], reinterpret_cast(args) + 4);\r\n\t\tbreak;\r\n\tcase 0x04:\r\n\t\tassert(retSize == 4);\r\n\t\tret[0] = SifAllocateSystemMemory(args[0], args[1], args[2]);\r\n\t\tbreak;\r\n\tcase 0x06:\r\n\t\tret[0] = m_memorySize;\r\n\t\tbreak;\r\n\tcase 0x07:\r\n\t\tret[0] = QueryMaxFreeMemSize();\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tCLog::GetInstance().Print(LOG_NAME, \"Unknown method invoked (0x%0.8X).\\r\\n\", method);\r\n\t\tbreak;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nuint32 CSysmem::QueryMaxFreeMemSize()\r\n{\r\n\tuint32 maxSize = 0;\r\n\tuint32 begin = 0;\r\n\tuint32* nextBlockId = &m_headBlockId;\r\n\tBLOCK* nextBlock = m_blocks[*nextBlockId];\r\n\twhile (nextBlock != NULL)\r\n\t{\r\n\t\tuint32 end = nextBlock->address;\r\n\t\tif ((end - begin) >= maxSize)\r\n\t\t{\r\n\t\t\tmaxSize = end - begin;\r\n\t\t}\r\n\t\tbegin = nextBlock->address + nextBlock->size;\r\n\t\tnextBlockId = &nextBlock->nextBlock;\r\n\t\tnextBlock = m_blocks[*nextBlockId];\r\n\t}\r\n\treturn maxSize;\r\n}\r\n\r\nuint32 CSysmem::AllocateMemory(uint32 size, uint32 flags, uint32 wantedAddress)\r\n{\r\n\tCLog::GetInstance().Print(LOG_NAME, \"AllocateMemory(size = 0x%0.8X, flags = 0x%0.8X, wantedAddress = 0x%0.8X);\\r\\n\",\r\n\t\tsize, flags, wantedAddress);\r\n\r\n\tconst uint32 blockSize = MIN_BLOCK_SIZE;\r\n\tsize = ((size + (blockSize - 1)) \/ blockSize) * blockSize;\r\n\r\n\tif(flags == 0 || flags == 1)\r\n\t{\r\n\t\tuint32 begin = 0;\r\n\t\tuint32* nextBlockId = &m_headBlockId;\r\n\t\tBLOCK* nextBlock = m_blocks[*nextBlockId];\r\n\t\twhile(nextBlock != NULL)\r\n\t\t{\r\n\t\t\tuint32 end = nextBlock->address;\r\n\t\t\tif((end - begin) >= size)\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tbegin = nextBlock->address + nextBlock->size;\r\n\t\t\tnextBlockId = &nextBlock->nextBlock;\r\n\t\t\tnextBlock = m_blocks[*nextBlockId];\r\n\t\t}\r\n\t\t\r\n\t\tif(nextBlock != NULL)\r\n\t\t{\r\n\t\t\tuint32 newBlockId = m_blocks.Allocate();\r\n\t\t\tassert(newBlockId != 0);\r\n\t\t\tif(newBlockId == 0)\r\n\t\t\t{\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\t\t\tBLOCK* newBlock = m_blocks[newBlockId];\r\n\t\t\tnewBlock->address\t= begin;\r\n\t\t\tnewBlock->size\t\t= size;\r\n\t\t\tnewBlock->nextBlock\t= *nextBlockId;\r\n\t\t\t*nextBlockId = newBlockId;\r\n\t\t\treturn begin + m_memoryBegin;\r\n\t\t}\r\n\t}\r\n\telse if(flags == 2)\r\n\t{\r\n\t\tassert(wantedAddress != 0);\r\n\t\twantedAddress -= m_memoryBegin;\r\n\r\n\t\tuint32 begin = 0;\r\n\t\tuint32* nextBlockId = &m_headBlockId;\r\n\t\tBLOCK* nextBlock = m_blocks[*nextBlockId];\r\n\t\twhile(nextBlock != NULL)\r\n\t\t{\r\n\t\t\tuint32 end = nextBlock->address;\r\n\t\t\tif(begin > wantedAddress)\r\n\t\t\t{\r\n\t\t\t\t\/\/Couldn't find suitable space\r\n\t\t\t\tnextBlock = NULL;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif(\r\n\t\t\t\t(begin <= wantedAddress) && \r\n\t\t\t\t((end - begin) >= size)\r\n\t\t\t\t)\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tbegin = nextBlock->address + nextBlock->size;\r\n\t\t\tnextBlockId = &nextBlock->nextBlock;\r\n\t\t\tnextBlock = m_blocks[*nextBlockId];\r\n\t\t}\r\n\t\t\r\n\t\tif(nextBlock != NULL)\r\n\t\t{\r\n\t\t\tuint32 newBlockId = m_blocks.Allocate();\r\n\t\t\tassert(newBlockId != 0);\r\n\t\t\tif(newBlockId == 0)\r\n\t\t\t{\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\t\t\tBLOCK* newBlock = m_blocks[newBlockId];\r\n\t\t\tnewBlock->address\t= wantedAddress;\r\n\t\t\tnewBlock->size\t\t= size;\r\n\t\t\tnewBlock->nextBlock\t= *nextBlockId;\r\n\t\t\t*nextBlockId = newBlockId;\r\n\t\t\treturn wantedAddress + m_memoryBegin;\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\tassert(0);\r\n\t}\r\n\r\n\tassert(0);\r\n\treturn NULL;\r\n}\r\n\r\nuint32 CSysmem::FreeMemory(uint32 address)\r\n{\r\n\tCLog::GetInstance().Print(LOG_NAME, \"FreeMemory(address = 0x%0.8X);\\r\\n\", address);\r\n\r\n\taddress -= m_memoryBegin;\r\n\t\/\/Search for block pointing at the address\r\n\tuint32* nextBlockId = &m_headBlockId;\r\n\tBLOCK* nextBlock = m_blocks[*nextBlockId];\r\n\twhile(nextBlock != NULL)\r\n\t{\r\n\t\tif(nextBlock->address == address)\r\n\t\t{\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tnextBlockId = &nextBlock->nextBlock;\r\n\t\tnextBlock = m_blocks[*nextBlockId];\r\n\t}\r\n\r\n\tif(nextBlock != NULL)\r\n\t{\r\n\t\tm_blocks.Free(*nextBlockId);\r\n\t\t*nextBlockId = nextBlock->nextBlock;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tCLog::GetInstance().Print(LOG_NAME, \"%s: Trying to unallocate an unexisting memory block (0x%0.8X).\\r\\n\", __FUNCTION__, address);\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nuint32 CSysmem::SifAllocate(uint32 nSize)\r\n{\r\n\tuint32 result = AllocateMemory(nSize, 0, 0); \r\n\tCLog::GetInstance().Print(LOG_NAME, \"result = 0x%0.8X = Allocate(size = 0x%0.8X);\\r\\n\", \r\n\t\tresult, nSize);\r\n\treturn result;\r\n}\r\n\r\nuint32 CSysmem::SifAllocateSystemMemory(uint32 nSize, uint32 nFlags, uint32 nPtr)\r\n{\r\n\tuint32 result = AllocateMemory(nSize, nFlags, nPtr);\r\n\tCLog::GetInstance().Print(LOG_NAME, \"result = 0x%0.8X = AllocateSystemMemory(flags = 0x%0.8X, size = 0x%0.8X, ptr = 0x%0.8X);\\r\\n\", \r\n\t\tresult, nFlags, nSize, nPtr);\r\n\treturn result;\r\n}\r\n\r\nuint32 CSysmem::SifLoadMemory(uint32 address, const char* filePath)\r\n{\r\n\tCLog::GetInstance().Print(LOG_NAME, \"LoadMemory(address = 0x%0.8X, filePath = '%s');\\r\\n\",\r\n\t\taddress, filePath);\r\n\r\n\tauto fd = m_ioman.Open(Ioman::CDevice::OPEN_FLAG_RDONLY, filePath);\r\n\tif(static_cast(fd) < 0)\r\n\t{\r\n\t\treturn fd;\r\n\t}\r\n\tuint32 fileSize = m_ioman.Seek(fd, 0, CIoman::SEEK_DIR_END);\r\n\tm_ioman.Seek(fd, 0, CIoman::SEEK_DIR_SET);\r\n\tm_ioman.Read(fd, fileSize, m_iopRam + address);\r\n\tm_ioman.Close(fd);\r\n\treturn 0;\r\n}\r\n\r\nuint32 CSysmem::SifFreeMemory(uint32 address)\r\n{\r\n\tCLog::GetInstance().Print(LOG_NAME, \"FreeMemory(address = 0x%0.8X);\\r\\n\", address);\r\n\tFreeMemory(address);\r\n\treturn 0;\r\n}\r\nChanged minimum memory alloc block size to 256 bytes.#include \"Iop_Sysmem.h\"\r\n#include \"..\/Log.h\"\r\n#include \"Iop_SifMan.h\"\r\n\r\nusing namespace Iop;\r\n\r\n#define LOG_NAME (\"iop_sysmem\")\r\n\r\n#define FUNCTION_ALLOCATEMEMORY\t\t\t\"AllocateMemory\"\r\n#define FUNCTION_FREEMEMORY\t\t\t\t\"FreeMemory\"\r\n#define FUNCTION_PRINTF\t\t\t\t\t\"printf\"\r\n#define FUNCTION_QUERYMEMSIZE\t\t\t\"QueryMemSize\"\r\n#define FUNCTION_QUERYMAXFREEMEMSIZE\t\"QueryMaxFreeMemSize\"\r\n\r\n#define MIN_BLOCK_SIZE 0x100\r\n\r\nCSysmem::CSysmem(uint8* ram, uint32 memoryBegin, uint32 memoryEnd, uint32 blockBase, CStdio& stdio, CIoman& ioman, CSifMan& sifMan)\r\n: m_iopRam(ram)\r\n, m_memoryBegin(memoryBegin)\r\n, m_memoryEnd(memoryEnd)\r\n, m_stdio(stdio)\r\n, m_ioman(ioman)\r\n, m_memorySize(memoryEnd - memoryBegin)\r\n, m_blocks(reinterpret_cast(&ram[blockBase]), 1, MAX_BLOCKS)\r\n{\r\n\t\/\/Initialize block map\r\n\tm_headBlockId = m_blocks.Allocate();\r\n\tBLOCK* block = m_blocks[m_headBlockId];\r\n\tblock->address\t\t= m_memorySize;\r\n\tblock->size\t\t\t= 0;\r\n\tblock->nextBlock\t= 0;\r\n\r\n\t\/\/Register sif module\r\n\tsifMan.RegisterModule(MODULE_ID, this);\r\n}\r\n\r\nCSysmem::~CSysmem()\r\n{\r\n\r\n}\r\n\r\nstd::string CSysmem::GetId() const\r\n{\r\n\treturn \"sysmem\";\r\n}\r\n\r\nstd::string CSysmem::GetFunctionName(unsigned int functionId) const\r\n{\r\n\tswitch(functionId)\r\n\t{\r\n\tcase 4:\r\n\t\treturn FUNCTION_ALLOCATEMEMORY;\r\n\t\tbreak;\r\n\tcase 5:\r\n\t\treturn FUNCTION_FREEMEMORY;\r\n\t\tbreak;\r\n\tcase 6:\r\n\t\treturn FUNCTION_QUERYMEMSIZE;\r\n\t\tbreak;\r\n\tcase 7:\r\n\t\treturn FUNCTION_QUERYMAXFREEMEMSIZE;\r\n\t\tbreak;\r\n\tcase 14:\r\n\t\treturn FUNCTION_PRINTF;\r\n\t\tbreak;\r\n\tdefault:\r\n\t\treturn \"unknown\";\r\n\t\tbreak;\r\n\t}\r\n}\r\n\r\nvoid CSysmem::Invoke(CMIPS& context, unsigned int functionId)\r\n{\r\n\tswitch(functionId)\r\n\t{\r\n\tcase 4:\r\n\t\tcontext.m_State.nGPR[CMIPS::V0].nD0 = static_cast(AllocateMemory(\r\n\t\t\tcontext.m_State.nGPR[CMIPS::A1].nV[0],\r\n\t\t\tcontext.m_State.nGPR[CMIPS::A0].nV[0],\r\n\t\t\tcontext.m_State.nGPR[CMIPS::A2].nV[0]\r\n\t\t\t));\r\n\t\tbreak;\r\n\tcase 5:\r\n\t\tcontext.m_State.nGPR[CMIPS::V0].nD0 = static_cast(FreeMemory(\r\n\t\t\tcontext.m_State.nGPR[CMIPS::A0].nV[0]\r\n\t\t\t));\r\n\t\tbreak;\r\n\tcase 6:\r\n\t\tcontext.m_State.nGPR[CMIPS::V0].nD0 = m_memorySize;\r\n\t\tbreak;\r\n\tcase 7:\r\n\t\tcontext.m_State.nGPR[CMIPS::V0].nD0 = QueryMaxFreeMemSize();\r\n\t\tbreak;\r\n\tcase 14:\r\n\t\tm_stdio.__printf(context);\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tCLog::GetInstance().Print(LOG_NAME, \"%s(%0.8X): Unknown function (%d) called.\\r\\n\", __FUNCTION__, context.m_State.nPC, functionId);\r\n\t\tbreak;\r\n\t}\r\n}\r\n\r\nbool CSysmem::Invoke(uint32 method, uint32* args, uint32 argsSize, uint32* ret, uint32 retSize, uint8* ram)\r\n{\r\n\tswitch(method)\r\n\t{\r\n\tcase 0x01:\r\n\t\tassert(retSize == 4);\r\n\t\tret[0] = SifAllocate(args[0]);\r\n\t\tbreak;\r\n\tcase 0x02:\r\n\t\tassert(argsSize == 4);\r\n\t\tret[0] = SifFreeMemory(args[0]);\r\n\t\tbreak;\r\n\tcase 0x03:\r\n\t\tassert(argsSize >= 4);\r\n\t\tassert(retSize == 4);\r\n\t\tret[0] = SifLoadMemory(args[0], reinterpret_cast(args) + 4);\r\n\t\tbreak;\r\n\tcase 0x04:\r\n\t\tassert(retSize == 4);\r\n\t\tret[0] = SifAllocateSystemMemory(args[0], args[1], args[2]);\r\n\t\tbreak;\r\n\tcase 0x06:\r\n\t\tret[0] = m_memorySize;\r\n\t\tbreak;\r\n\tcase 0x07:\r\n\t\tret[0] = QueryMaxFreeMemSize();\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tCLog::GetInstance().Print(LOG_NAME, \"Unknown method invoked (0x%0.8X).\\r\\n\", method);\r\n\t\tbreak;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nuint32 CSysmem::QueryMaxFreeMemSize()\r\n{\r\n\tuint32 maxSize = 0;\r\n\tuint32 begin = 0;\r\n\tuint32* nextBlockId = &m_headBlockId;\r\n\tBLOCK* nextBlock = m_blocks[*nextBlockId];\r\n\twhile (nextBlock != NULL)\r\n\t{\r\n\t\tuint32 end = nextBlock->address;\r\n\t\tif ((end - begin) >= maxSize)\r\n\t\t{\r\n\t\t\tmaxSize = end - begin;\r\n\t\t}\r\n\t\tbegin = nextBlock->address + nextBlock->size;\r\n\t\tnextBlockId = &nextBlock->nextBlock;\r\n\t\tnextBlock = m_blocks[*nextBlockId];\r\n\t}\r\n\treturn maxSize;\r\n}\r\n\r\nuint32 CSysmem::AllocateMemory(uint32 size, uint32 flags, uint32 wantedAddress)\r\n{\r\n\tCLog::GetInstance().Print(LOG_NAME, \"AllocateMemory(size = 0x%0.8X, flags = 0x%0.8X, wantedAddress = 0x%0.8X);\\r\\n\",\r\n\t\tsize, flags, wantedAddress);\r\n\r\n\tconst uint32 blockSize = MIN_BLOCK_SIZE;\r\n\tsize = ((size + (blockSize - 1)) \/ blockSize) * blockSize;\r\n\r\n\tif(flags == 0 || flags == 1)\r\n\t{\r\n\t\tuint32 begin = 0;\r\n\t\tuint32* nextBlockId = &m_headBlockId;\r\n\t\tBLOCK* nextBlock = m_blocks[*nextBlockId];\r\n\t\twhile(nextBlock != NULL)\r\n\t\t{\r\n\t\t\tuint32 end = nextBlock->address;\r\n\t\t\tif((end - begin) >= size)\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tbegin = nextBlock->address + nextBlock->size;\r\n\t\t\tnextBlockId = &nextBlock->nextBlock;\r\n\t\t\tnextBlock = m_blocks[*nextBlockId];\r\n\t\t}\r\n\t\t\r\n\t\tif(nextBlock != NULL)\r\n\t\t{\r\n\t\t\tuint32 newBlockId = m_blocks.Allocate();\r\n\t\t\tassert(newBlockId != 0);\r\n\t\t\tif(newBlockId == 0)\r\n\t\t\t{\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\t\t\tBLOCK* newBlock = m_blocks[newBlockId];\r\n\t\t\tnewBlock->address\t= begin;\r\n\t\t\tnewBlock->size\t\t= size;\r\n\t\t\tnewBlock->nextBlock\t= *nextBlockId;\r\n\t\t\t*nextBlockId = newBlockId;\r\n\t\t\treturn begin + m_memoryBegin;\r\n\t\t}\r\n\t}\r\n\telse if(flags == 2)\r\n\t{\r\n\t\tassert(wantedAddress != 0);\r\n\t\twantedAddress -= m_memoryBegin;\r\n\r\n\t\tuint32 begin = 0;\r\n\t\tuint32* nextBlockId = &m_headBlockId;\r\n\t\tBLOCK* nextBlock = m_blocks[*nextBlockId];\r\n\t\twhile(nextBlock != NULL)\r\n\t\t{\r\n\t\t\tuint32 end = nextBlock->address;\r\n\t\t\tif(begin > wantedAddress)\r\n\t\t\t{\r\n\t\t\t\t\/\/Couldn't find suitable space\r\n\t\t\t\tnextBlock = NULL;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif(\r\n\t\t\t\t(begin <= wantedAddress) && \r\n\t\t\t\t((end - begin) >= size)\r\n\t\t\t\t)\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tbegin = nextBlock->address + nextBlock->size;\r\n\t\t\tnextBlockId = &nextBlock->nextBlock;\r\n\t\t\tnextBlock = m_blocks[*nextBlockId];\r\n\t\t}\r\n\t\t\r\n\t\tif(nextBlock != NULL)\r\n\t\t{\r\n\t\t\tuint32 newBlockId = m_blocks.Allocate();\r\n\t\t\tassert(newBlockId != 0);\r\n\t\t\tif(newBlockId == 0)\r\n\t\t\t{\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\t\t\tBLOCK* newBlock = m_blocks[newBlockId];\r\n\t\t\tnewBlock->address\t= wantedAddress;\r\n\t\t\tnewBlock->size\t\t= size;\r\n\t\t\tnewBlock->nextBlock\t= *nextBlockId;\r\n\t\t\t*nextBlockId = newBlockId;\r\n\t\t\treturn wantedAddress + m_memoryBegin;\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\tassert(0);\r\n\t}\r\n\r\n\tassert(0);\r\n\treturn NULL;\r\n}\r\n\r\nuint32 CSysmem::FreeMemory(uint32 address)\r\n{\r\n\tCLog::GetInstance().Print(LOG_NAME, \"FreeMemory(address = 0x%0.8X);\\r\\n\", address);\r\n\r\n\taddress -= m_memoryBegin;\r\n\t\/\/Search for block pointing at the address\r\n\tuint32* nextBlockId = &m_headBlockId;\r\n\tBLOCK* nextBlock = m_blocks[*nextBlockId];\r\n\twhile(nextBlock != NULL)\r\n\t{\r\n\t\tif(nextBlock->address == address)\r\n\t\t{\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tnextBlockId = &nextBlock->nextBlock;\r\n\t\tnextBlock = m_blocks[*nextBlockId];\r\n\t}\r\n\r\n\tif(nextBlock != NULL)\r\n\t{\r\n\t\tm_blocks.Free(*nextBlockId);\r\n\t\t*nextBlockId = nextBlock->nextBlock;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tCLog::GetInstance().Print(LOG_NAME, \"%s: Trying to unallocate an unexisting memory block (0x%0.8X).\\r\\n\", __FUNCTION__, address);\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nuint32 CSysmem::SifAllocate(uint32 nSize)\r\n{\r\n\tuint32 result = AllocateMemory(nSize, 0, 0); \r\n\tCLog::GetInstance().Print(LOG_NAME, \"result = 0x%0.8X = Allocate(size = 0x%0.8X);\\r\\n\", \r\n\t\tresult, nSize);\r\n\treturn result;\r\n}\r\n\r\nuint32 CSysmem::SifAllocateSystemMemory(uint32 nSize, uint32 nFlags, uint32 nPtr)\r\n{\r\n\tuint32 result = AllocateMemory(nSize, nFlags, nPtr);\r\n\tCLog::GetInstance().Print(LOG_NAME, \"result = 0x%0.8X = AllocateSystemMemory(flags = 0x%0.8X, size = 0x%0.8X, ptr = 0x%0.8X);\\r\\n\", \r\n\t\tresult, nFlags, nSize, nPtr);\r\n\treturn result;\r\n}\r\n\r\nuint32 CSysmem::SifLoadMemory(uint32 address, const char* filePath)\r\n{\r\n\tCLog::GetInstance().Print(LOG_NAME, \"LoadMemory(address = 0x%0.8X, filePath = '%s');\\r\\n\",\r\n\t\taddress, filePath);\r\n\r\n\tauto fd = m_ioman.Open(Ioman::CDevice::OPEN_FLAG_RDONLY, filePath);\r\n\tif(static_cast(fd) < 0)\r\n\t{\r\n\t\treturn fd;\r\n\t}\r\n\tuint32 fileSize = m_ioman.Seek(fd, 0, CIoman::SEEK_DIR_END);\r\n\tm_ioman.Seek(fd, 0, CIoman::SEEK_DIR_SET);\r\n\tm_ioman.Read(fd, fileSize, m_iopRam + address);\r\n\tm_ioman.Close(fd);\r\n\treturn 0;\r\n}\r\n\r\nuint32 CSysmem::SifFreeMemory(uint32 address)\r\n{\r\n\tCLog::GetInstance().Print(LOG_NAME, \"FreeMemory(address = 0x%0.8X);\\r\\n\", address);\r\n\tFreeMemory(address);\r\n\treturn 0;\r\n}\r\n<|endoftext|>"} {"text":"\/******************************************************************************\r\nFile: KeyMappings.cpp\r\nCreated: 10\/3\/2017 11:57:46 AM\r\nCopyright (c) 2017 Turn Tactics\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in\r\nall copies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n\r\nPurpose: Contains all of the key mapping functions and data for keyboard input\r\nfrom SDL\r\n\r\nAuthor: James Womack\r\n\r\n********************************************************************************\/\r\n#include \"KeyMappings.h\"\r\n#include \"..\/Math\/Common.h\"\r\n#include \r\n\r\nnamespace lse {\r\n \r\n \/\/ A map that maps KeyType to a string.\r\n const containers::UnorderedMap gc_keyTextMappings{\r\n { KeyType::Key0, \"0\" },{ KeyType::Key1, \"1\" },\r\n { KeyType::Key2, \"2\" },{ KeyType::Key3, \"3\" },\r\n { KeyType::Key4, \"4\" },{ KeyType::Key5, \"5\" },\r\n { KeyType::Key6, \"6\" },{ KeyType::Key7, \"7\" },\r\n { KeyType::Key8, \"8\" },{ KeyType::Key9, \"9\" },\r\n { KeyType::KeyA, \"a\" },{ KeyType::KeyB, \"b\" },\r\n { KeyType::KeyC, \"c\" },{ KeyType::KeyD, \"d\" },\r\n { KeyType::KeyE, \"e\" },{ KeyType::KeyF, \"f\" },\r\n { KeyType::KeyG, \"g\" },{ KeyType::KeyH, \"h\" },\r\n { KeyType::KeyI, \"i\" },{ KeyType::KeyJ, \"j\" },\r\n { KeyType::KeyL, \"l\" },{ KeyType::KeyK, \"k\" },\r\n { KeyType::KeyN, \"n\" },{ KeyType::KeyM, \"m\" },\r\n { KeyType::KeyP, \"p\" },{ KeyType::KeyO, \"o\" },\r\n { KeyType::KeyR, \"r\" },{ KeyType::KeyQ, \"q\" },\r\n { KeyType::KeyT, \"t\" },{ KeyType::KeyS, \"s\" },\r\n { KeyType::KeyV, \"v\" },{ KeyType::KeyU, \"u\" },\r\n { KeyType::KeyW, \"w\" },{ KeyType::KeyX, \"x\" },\r\n { KeyType::KeyY, \"y\" },{ KeyType::KeyZ, \"z\" },\r\n { KeyType::KeyTab, \"\\t\" },{ KeyType::KeyEnter, \"\\n\" },\r\n { KeyType::KeyBracketLeft, \"[\" },{ KeyType::KeyBracketRight, \"]\" },\r\n { KeyType::KeyLeftParenthesis, \"(\" },{ KeyType::KeyRightParenthesis, \")\" },\r\n { KeyType::KeyCurlyBracketLeft, \"{\" },{ KeyType::KeyCurlyBracketRight, \"}\" },\r\n { KeyType::KeyAngleBracketLeft, \"{\" },{ KeyType::KeyAngleBracketRight, \"}\" },\r\n { KeyType::KeyColon, \":\" },{ KeyType::KeySemicolon, \";\" },\r\n { KeyType::KeyComma, \",\" },{ KeyType::KeyEnter, \"\\n\" },\r\n { KeyType::KeySlash, \"\/\" },{ KeyType::KeyBackslash, \"\\\\\" },\r\n { KeyType::KeyExclamation, \"!\" },{ KeyType::KeyAt, \"@\" },\r\n { KeyType::KeyHash, \"#\" },{ KeyType::KeyPercent, \"%\" },\r\n { KeyType::KeyHat, \"^\" },{ KeyType::KeyAmpersand, \"&\" },\r\n { KeyType::KeyStar, \"*\" },{ KeyType::KeyMinus, \"-\" },\r\n { KeyType::KeyUnderscore, \"_\" },{ KeyType::KeyEquals, \"=\" },\r\n { KeyType::KeyPlus, \"+\" },\r\n { KeyType::KeyApostrophe, \"'\" },{ KeyType::KeyQuotes, \"\\\"\" },\r\n { KeyType::KeyBacktick, \"`\" },{ KeyType::KeyQuestion, \"?\" },\r\n { KeyType::KeyBackspace, \"\\\\backspace\\\\\" },{ KeyType::KeyDelete, \"\\\\delete\\\\\" },\r\n { KeyType::KeyDollar, \"$\" },{ KeyType::KeyHome, \"\\\\home\\\\\" },\r\n { KeyType::KeyPageDown, \"\\\\pg-down\\\\\" },{ KeyType::KeyPageUp, \"\\\\pg-up\\\\\" },\r\n { KeyType::KeyEnd, \"\\\\end\\\\\" },{ KeyType::KeyInsert, \"\\\\insert\\\\\" },\r\n { KeyType::KeyF1, \"\\\\f1\\\\\" },{ KeyType::KeyF2, \"\\\\f2\\\\\" },\r\n { KeyType::KeyF3, \"\\\\f3\\\\\" },{ KeyType::KeyF4, \"\\\\f4\\\\\" },\r\n { KeyType::KeyF5, \"\\\\f5\\\\\" },{ KeyType::KeyF6, \"\\\\f6\\\\\" },\r\n { KeyType::KeyF7, \"\\\\f7\\\\\" },{ KeyType::KeyF8, \"\\\\f8\\\\\" },\r\n { KeyType::KeyF9, \"\\\\f9\\\\\" },{ KeyType::KeyF10, \"\\\\f10\\\\\" },\r\n { KeyType::KeyF11, \"\\\\f11\\\\\" },{ KeyType::KeyF12, \"\\\\f12\\\\\" },\r\n { KeyType::KeyArrowUp, \"\\\\^\\\\\" },{ KeyType::KeyArrowDown, \"\\\\v\\\\\" },\r\n { KeyType::KeyArrowLeft, \"\\\\<\\\\\" },{ KeyType::KeyArrowRight, \"\\\\>\\\\\" },\r\n { KeyType::KeyPeriod, \".\" },{KeyType::KeyPipe, \"|\" },\r\n { KeyType::KeyNone, \"\" }\r\n };\r\n\r\n const containers::UnorderedMap gc_keyModiferTextMappings {\r\n { KeyModiferType::KeyNone, \"\" }, { KeyModiferType::KeyAlt, \"Alt\" },\r\n { KeyModiferType::KeyCtrl, \"Ctrl\" }, { KeyModiferType::KeyCtrlAlt, \"Ctrl+Alt\"},\r\n { KeyModiferType::KeyCtrlShift, \"Ctrl+Shift\" }, { KeyModiferType::KeyCtrlShiftAlt, \"Ctrl+Shift+Alt\"},\r\n { KeyModiferType::KeyShift, \"Shift\" }, { KeyModiferType::KeyShiftAlt, \"Shift+Alt\" }\r\n };\r\n\r\n const containers::UnorderedMap gc_sdlKeyMapping {\r\n { SDLK_0, KeyType::Key0 },{ SDLK_1, KeyType::Key1 },\r\n { SDLK_2, KeyType::Key2 },{ SDLK_3, KeyType::Key3 },\r\n { SDLK_4, KeyType::Key4 },{ SDLK_5, KeyType::Key5 },\r\n { SDLK_6, KeyType::Key6 },{ SDLK_7, KeyType::Key7 },\r\n { SDLK_8, KeyType::Key8 },{ SDLK_9, KeyType::Key9 },\r\n { SDLK_a, KeyType::KeyA },{ SDLK_b, KeyType::KeyB },\r\n { SDLK_c, KeyType::KeyC },{ SDLK_d, KeyType::KeyD },\r\n { SDLK_e, KeyType::KeyE },{ SDLK_f, KeyType::KeyF },\r\n { SDLK_g, KeyType::KeyG },{ SDLK_h, KeyType::KeyH },\r\n { SDLK_i, KeyType::KeyI },{ SDLK_j, KeyType::KeyJ },\r\n { SDLK_k, KeyType::KeyK },{ SDLK_l, KeyType::KeyL },\r\n { SDLK_m, KeyType::KeyM },{ SDLK_n, KeyType::KeyN },\r\n { SDLK_o, KeyType::KeyO },{ SDLK_p, KeyType::KeyP },\r\n { SDLK_q, KeyType::KeyQ },{ SDLK_r, KeyType::KeyR },\r\n { SDLK_s, KeyType::KeyS },{ SDLK_t, KeyType::KeyT },\r\n { SDLK_u, KeyType::KeyU },{ SDLK_v, KeyType::KeyV },\r\n { SDLK_w, KeyType::KeyW },{ SDLK_x, KeyType::KeyX },\r\n { SDLK_y, KeyType::KeyY },{ SDLK_z, KeyType::KeyZ },\r\n { SDLK_y, KeyType::KeyY },{ SDLK_z, KeyType::KeyAccent },\r\n };\r\n\r\n \/\/ Maps SDL_Event type to a KeyState type if applicable\r\n inline KeyState get_sdl_key_state(SDL_Event& e)\r\n {\r\n return e.type == SDL_KEYDOWN ? KeyState::KeyDown \r\n : e.type == SDL_KEYUP ? KeyState::KeyUp : KeyState::KeyNone;\r\n }\r\n\r\n inline \r\n\r\n inline String get_text_character(KeyEvent& keyEvent)\r\n {\r\n auto keyStr = gc_keyTextMappings.at(keyEvent.key());\r\n\r\n if (is_alpha_keystroke(keyEvent) && keyEvent.modifier() == KeyModiferType::KeyShift)\r\n {\r\n return to_upper(keyStr);\r\n }\r\n\r\n return keyStr;\r\n }\r\n\r\n inline String get_key_event_string(KeyEvent& keyEvent)\r\n {\r\n auto keyStr = to_upper(gc_keyTextMappings.at(keyEvent.key()));\r\n auto modiferStr = to_upper(gc_keyModiferTextMappings.at(keyEvent.modifier()));\r\n\r\n if (keyStr.length() > 0 && modiferStr.length() > 0)\r\n {\r\n return modiferStr + \"+\" + keyStr;\r\n } else if (keyStr.length() > 0)\r\n {\r\n return keyStr;\r\n } else if (modiferStr.length() > 0)\r\n {\r\n return modiferStr;\r\n } else\r\n {\r\n return \"\\\\none\\\\\";\r\n }\r\n }\r\n}\r\nRevert \"i dont know\"\/******************************************************************************\r\nFile: KeyMappings.cpp\r\nCreated: 10\/3\/2017 11:57:46 AM\r\nCopyright (c) 2017 Turn Tactics\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\nThe above copyright notice and this permission notice shall be included in\r\nall copies or substantial portions of the Software.\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\nPurpose: Contains all of the key mapping functions and data for keyboard input\r\nfrom SDL\r\nAuthor: James Womack\r\n********************************************************************************\/\r\n#include \"KeyMappings.h\"\r\n#include \"..\/Math\/Common.h\"\r\n#include \r\n\r\nnamespace lse {\r\n\r\n\t\/\/ A map that maps KeyType to a string.\r\n\tconst containers::UnorderedMap gc_keyTextMappings {\r\n\t\t{ KeyType::Key0, \"0\" }, { KeyType::Key1, \"1\" },\r\n\t\t{ KeyType::Key2, \"2\" }, { KeyType::Key3, \"3\" },\r\n\t\t{ KeyType::Key4, \"4\" }, { KeyType::Key5, \"5\" },\r\n\t\t{ KeyType::Key6, \"6\" }, { KeyType::Key7, \"7\" },\r\n\t\t{ KeyType::Key8, \"8\" }, { KeyType::Key9, \"9\" },\r\n\t\t{ KeyType::KeyA, \"a\" }, { KeyType::KeyB, \"b\" },\r\n\t\t{ KeyType::KeyC, \"c\" }, { KeyType::KeyD, \"d\" },\r\n\t\t{ KeyType::KeyE, \"e\" }, { KeyType::KeyF, \"f\" },\r\n\t\t{ KeyType::KeyG, \"g\" }, { KeyType::KeyH, \"h\" },\r\n\t\t{ KeyType::KeyI, \"i\" }, { KeyType::KeyJ, \"j\" },\r\n\t\t{ KeyType::KeyL, \"l\" }, { KeyType::KeyK, \"k\" },\r\n\t\t{ KeyType::KeyN, \"n\" }, { KeyType::KeyM, \"m\" },\r\n\t\t{ KeyType::KeyP, \"p\" }, { KeyType::KeyO, \"o\" },\r\n\t\t{ KeyType::KeyR, \"r\" }, { KeyType::KeyQ, \"q\" },\r\n\t\t{ KeyType::KeyT, \"t\" }, { KeyType::KeyS, \"s\" },\r\n\t\t{ KeyType::KeyV, \"v\" }, { KeyType::KeyU, \"u\" },\r\n\t\t{ KeyType::KeyW, \"w\" }, { KeyType::KeyX, \"x\" },\r\n\t\t{ KeyType::KeyY, \"y\" }, { KeyType::KeyZ, \"z\" },\r\n\t\t{ KeyType::KeyTab, \"\\t\" }, { KeyType::KeyEnter, \"\\n\" },\r\n\t\t{ KeyType::KeyBracketLeft, \"[\" }, { KeyType::KeyBracketRight, \"]\" },\r\n\t\t{ KeyType::KeyLeftParenthesis, \"(\" }, { KeyType::KeyRightParenthesis, \")\" },\r\n\t\t{ KeyType::KeyCurlyBracketLeft, \"{\" }, { KeyType::KeyCurlyBracketRight, \"}\" },\r\n\t\t{ KeyType::KeyAngleBracketLeft, \"{\" }, { KeyType::KeyAngleBracketRight, \"}\" },\r\n\t\t{ KeyType::KeyColon, \":\" }, { KeyType::KeySemicolon, \";\" },\r\n\t\t{ KeyType::KeyComma, \",\" }, { KeyType::KeyEnter, \"\\n\" },\r\n\t\t{ KeyType::KeySlash, \"\/\" }, { KeyType::KeyBackslash, \"\\\\\" },\r\n\t\t{ KeyType::KeyExclamation, \"!\" }, { KeyType::KeyAt, \"@\" },\r\n\t\t{ KeyType::KeyHash, \"#\" }, { KeyType::KeyPercent, \"%\" },\r\n\t\t{ KeyType::KeyHat, \"^\" }, { KeyType::KeyAmpersand, \"&\" },\r\n\t\t{ KeyType::KeyStar, \"*\" }, { KeyType::KeyMinus, \"-\" },\r\n\t\t{ KeyType::KeyUnderscore, \"_\" }, { KeyType::KeyEquals, \"=\" },\r\n\t\t{ KeyType::KeyPlus, \"+\" },\r\n\t\t{ KeyType::KeyApostrophe, \"'\" }, { KeyType::KeyQuotes, \"\\\"\" },\r\n\t\t{ KeyType::KeyBacktick, \"`\" }, { KeyType::KeyQuestion, \"?\" },\r\n\t\t{ KeyType::KeyBackspace, \"\\\\backspace\\\\\" }, { KeyType::KeyDelete, \"\\\\delete\\\\\" },\r\n\t\t{ KeyType::KeyDollar, \"$\" }, { KeyType::KeyHome, \"\\\\home\\\\\" },\r\n\t\t{ KeyType::KeyPageDown, \"\\\\pg-down\\\\\" }, { KeyType::KeyPageUp, \"\\\\pg-up\\\\\" },\r\n\t\t{ KeyType::KeyEnd, \"\\\\end\\\\\" }, { KeyType::KeyInsert, \"\\\\insert\\\\\" },\r\n\t\t{ KeyType::KeyF1, \"\\\\f1\\\\\" }, { KeyType::KeyF2, \"\\\\f2\\\\\" },\r\n\t\t{ KeyType::KeyF3, \"\\\\f3\\\\\" }, { KeyType::KeyF4, \"\\\\f4\\\\\" },\r\n\t\t{ KeyType::KeyF5, \"\\\\f5\\\\\" }, { KeyType::KeyF6, \"\\\\f6\\\\\" },\r\n\t\t{ KeyType::KeyF7, \"\\\\f7\\\\\" }, { KeyType::KeyF8, \"\\\\f8\\\\\" },\r\n\t\t{ KeyType::KeyF9, \"\\\\f9\\\\\" }, { KeyType::KeyF10, \"\\\\f10\\\\\" },\r\n\t\t{ KeyType::KeyF11, \"\\\\f11\\\\\" }, { KeyType::KeyF12, \"\\\\f12\\\\\" },\r\n\t\t{ KeyType::KeyArrowUp, \"\\\\^\\\\\" }, { KeyType::KeyArrowDown, \"\\\\v\\\\\" },\r\n\t\t{ KeyType::KeyArrowLeft, \"\\\\<\\\\\" }, { KeyType::KeyArrowRight, \"\\\\>\\\\\" },\r\n\t\t{ KeyType::KeyPeriod, \".\" }, { KeyType::KeyPipe, \"|\" },\r\n\t\t{ KeyType::KeyNone, \"\" }\r\n\t};\r\n\r\n\tconst containers::UnorderedMap gc_keyModiferTextMappings {\r\n\t\t{ KeyModiferType::KeyNone, \"\" }, { KeyModiferType::KeyAlt, \"Alt\" },\r\n\t\t{ KeyModiferType::KeyCtrl, \"Ctrl\" }, { KeyModiferType::KeyCtrlAlt, \"Ctrl+Alt\" },\r\n\t\t{ KeyModiferType::KeyCtrlShift, \"Ctrl+Shift\" }, { KeyModiferType::KeyCtrlShiftAlt, \"Ctrl+Shift+Alt\" },\r\n\t\t{ KeyModiferType::KeyShift, \"Shift\" }, { KeyModiferType::KeyShiftAlt, \"Shift+Alt\" }\r\n\t};\r\n\r\n\tconst containers::UnorderedMap gc_sdlKeyMapping {\r\n\t\t{ SDLK_0, KeyType::Key0 }, { SDLK_1, KeyType::Key1 },\r\n\t\t{ SDLK_2, KeyType::Key2 }, { SDLK_3, KeyType::Key3 },\r\n\t\t{ SDLK_4, KeyType::Key4 }, { SDLK_5, KeyType::Key5 },\r\n\t\t{ SDLK_6, KeyType::Key6 }, { SDLK_7, KeyType::Key7 },\r\n\t\t{ SDLK_8, KeyType::Key8 }, { SDLK_9, KeyType::Key9 },\r\n\t\t{ SDLK_a, KeyType::KeyA }, { SDLK_b, KeyType::KeyB },\r\n\t\t{ SDLK_c, KeyType::KeyC }, { SDLK_d, KeyType::KeyD },\r\n\t\t{ SDLK_e, KeyType::KeyE }, { SDLK_f, KeyType::KeyF },\r\n\t\t{ SDLK_g, KeyType::KeyG }, { SDLK_h, KeyType::KeyH },\r\n\t\t{ SDLK_i, KeyType::KeyI }, { SDLK_j, KeyType::KeyJ },\r\n\t\t{ SDLK_k, KeyType::KeyK }, { SDLK_l, KeyType::KeyL },\r\n\t\t{ SDLK_m, KeyType::KeyM }, { SDLK_n, KeyType::KeyN },\r\n\t\t{ SDLK_o, KeyType::KeyO }, { SDLK_p, KeyType::KeyP },\r\n\t\t{ SDLK_q, KeyType::KeyQ }, { SDLK_r, KeyType::KeyR },\r\n\t\t{ SDLK_s, KeyType::KeyS }, { SDLK_t, KeyType::KeyT },\r\n\t\t{ SDLK_u, KeyType::KeyU }, { SDLK_v, KeyType::KeyV },\r\n\t\t{ SDLK_w, KeyType::KeyW }, { SDLK_x, KeyType::KeyX },\r\n\t\t{ SDLK_y, KeyType::KeyY }, { SDLK_z, KeyType::KeyZ },\r\n\t\t{ SDLK_y, KeyType::KeyY }, { SDLK_z, KeyType::KeyAccent },\r\n\t};\r\n\r\n\t\/\/ Maps SDL_Event type to a KeyState type if applicable\r\n\tinline KeyState get_sdl_key_state(SDL_Event& e) {\r\n\t\treturn e.type == SDL_KEYDOWN ? KeyState::KeyDown\r\n\t\t\t: e.type == SDL_KEYUP ? KeyState::KeyUp : KeyState::KeyNone;\r\n\t}\r\n\r\n\tinline\r\n\r\n\t\tinline String get_text_character(KeyEvent& keyEvent) {\r\n\t\tauto keyStr = gc_keyTextMappings.at(keyEvent.key());\r\n\r\n\t\tif(is_alpha_keystroke(keyEvent) && keyEvent.modifier() == KeyModiferType::KeyShift) {\r\n\t\t\treturn to_upper(keyStr);\r\n\t\t}\r\n\r\n\t\treturn keyStr;\r\n\t}\r\n\r\n\tinline String get_key_event_string(KeyEvent& keyEvent) {\r\n\t\tauto keyStr = to_upper(gc_keyTextMappings.at(keyEvent.key()));\r\n\t\tauto modiferStr = to_upper(gc_keyModiferTextMappings.at(keyEvent.modifier()));\r\n\r\n\t\tif(keyStr.length() > 0 && modiferStr.length() > 0) {\r\n\t\t\treturn modiferStr + \"+\" + keyStr;\r\n\t\t} else if(keyStr.length() > 0) {\r\n\t\t\treturn keyStr;\r\n\t\t} else if(modiferStr.length() > 0) {\r\n\t\t\treturn modiferStr;\r\n\t\t} else {\r\n\t\t\treturn \"\\\\none\\\\\";\r\n\t\t}\r\n\t}\r\n}<|endoftext|>"} {"text":"#include \"TableToTreeProxyModel.h\"\n\n#include \n#include \n#include \n#include \n\nstruct TreeNode {\n TreeNode(int row=-1, int column=-1, TreeNode *parent=0)\n : row(row), column(column), parent(parent)\n {\n if (parent)\n parent->children.append(this);\n };\n int row;\n int column;\n TreeNode *parent;\n QList children;\n QString text;\n};\n\nTableToTreeProxyModel::TableToTreeProxyModel(QObject *parent)\n : QAbstractProxyModel(parent)\n{\n}\n\nQModelIndex\tTableToTreeProxyModel::mapFromSource(const QModelIndex &sourceIndex) const\n{\n TreeNode *node = tableNodes.at(sourceIndex.column()).at(sourceIndex.row());\n Q_ASSERT(node);\n if (!node)\n return QModelIndex();\n\n Q_ASSERT(false);\n return index(sourceIndex.row(), 0);\n}\n\nQModelIndex\tTableToTreeProxyModel::mapToSource(const QModelIndex &proxyIndex) const\n{\n if (!proxyIndex.isValid())\n return QModelIndex();\n\n const TreeNode *node = static_cast(proxyIndex.internalPointer());\n Q_ASSERT(node);\n if (!node)\n return QModelIndex();\n\n return sourceModel()->index(node->row, node->column);\n}\n\nQVariant TableToTreeProxyModel::data(const QModelIndex &proxyIndex, int role) const\n{\n if (!proxyIndex.isValid())\n return QVariant();\n\n const TreeNode *node = static_cast(proxyIndex.internalPointer());\n Q_ASSERT(node);\n if (!node)\n return QVariant();\n\n const QModelIndex index = sourceModel()->index(node->row, node->column);\n return sourceModel()->data(index, role);\n}\n\nQModelIndex TableToTreeProxyModel::index(int row, int column, const QModelIndex &parent) const\n{\n if (!hasIndex(row, column, parent))\n return QModelIndex();\n\n const TreeNode *parentNode = static_cast(parent.internalPointer());\n if (!parentNode)\n parentNode = rootNode;\n\n TreeNode *node = parentNode->children.at(row);\n Q_ASSERT(node);\n if (!node)\n return QModelIndex();\n\n return createIndex(row, column, node);\n}\n\nQModelIndex TableToTreeProxyModel::parent(const QModelIndex &child) const\n{\n if (!child.isValid())\n return QModelIndex();\n\n const TreeNode *childNode = static_cast(child.internalPointer());\n Q_ASSERT(childNode);\n if (!childNode)\n return QModelIndex();\n\n TreeNode *parentNode = childNode->parent;\n Q_ASSERT(parentNode);\n if (!parentNode)\n return QModelIndex();\n\n return createIndex(parentNode->row, parentNode->column, parentNode);\n}\n\nint TableToTreeProxyModel::rowCount(const QModelIndex &parent) const\n{\n const TreeNode *node = static_cast(parent.internalPointer());\n if (!node)\n node = rootNode;\n\n return node->children.size();\n}\n\nint TableToTreeProxyModel::columnCount(const QModelIndex &) const\n{\n return 1;\n}\n\nbool TableToTreeProxyModel::hasChildren(const QModelIndex &parent) const\n{\n const TreeNode *node = static_cast(parent.internalPointer());\n if (!node)\n node = rootNode;\n\n return node->children.size() > 0;\n}\n\nvoid TableToTreeProxyModel::setSourceModel(QAbstractItemModel *sourceModel)\n{\n \/\/ TODO: cleanup on already existing\n tableNodes.clear();\n rootNode = new TreeNode;\n\n for (int row=0; row < sourceModel->rowCount(); ++row) {\n QList rowNodes;\n TreeNode *previousNode = rootNode;\n for (int column=0; column < sourceModel->columnCount(); ++column) {\n const QString &nodeText = sourceModel->data(sourceModel->index(row, column)).toString();\n TreeNode *node = 0;\n foreach (TreeNode *siblingNode, previousNode->children) {\n Q_ASSERT(siblingNode);\n if (!siblingNode)\n continue;\n if (siblingNode->text == nodeText) {\n node = siblingNode;\n break;\n }\n }\n\n if (!node) {\n node = new TreeNode(row, column, previousNode);\n node->text = nodeText;\n }\n rowNodes.insert(column, node);\n previousNode = node;\n }\n tableNodes.insert(row, rowNodes);\n }\n\n QAbstractProxyModel::setSourceModel(sourceModel);\n}\nRemove ugly tabs.#include \"TableToTreeProxyModel.h\"\n\n#include \n#include \n#include \n#include \n\nstruct TreeNode {\n TreeNode(int row=-1, int column=-1, TreeNode *parent=0)\n : row(row), column(column), parent(parent)\n {\n if (parent)\n parent->children.append(this);\n };\n int row;\n int column;\n TreeNode *parent;\n QList children;\n QString text;\n};\n\nTableToTreeProxyModel::TableToTreeProxyModel(QObject *parent)\n : QAbstractProxyModel(parent)\n{\n}\n\nQModelIndex TableToTreeProxyModel::mapFromSource(const QModelIndex &sourceIndex) const\n{\n TreeNode *node = tableNodes.at(sourceIndex.column()).at(sourceIndex.row());\n Q_ASSERT(node);\n if (!node)\n return QModelIndex();\n\n Q_ASSERT(false);\n return index(sourceIndex.row(), 0);\n}\n\nQModelIndex TableToTreeProxyModel::mapToSource(const QModelIndex &proxyIndex) const\n{\n if (!proxyIndex.isValid())\n return QModelIndex();\n\n const TreeNode *node = static_cast(proxyIndex.internalPointer());\n Q_ASSERT(node);\n if (!node)\n return QModelIndex();\n\n return sourceModel()->index(node->row, node->column);\n}\n\nQVariant TableToTreeProxyModel::data(const QModelIndex &proxyIndex, int role) const\n{\n if (!proxyIndex.isValid())\n return QVariant();\n\n const TreeNode *node = static_cast(proxyIndex.internalPointer());\n Q_ASSERT(node);\n if (!node)\n return QVariant();\n\n const QModelIndex index = sourceModel()->index(node->row, node->column);\n return sourceModel()->data(index, role);\n}\n\nQModelIndex TableToTreeProxyModel::index(int row, int column, const QModelIndex &parent) const\n{\n if (!hasIndex(row, column, parent))\n return QModelIndex();\n\n const TreeNode *parentNode = static_cast(parent.internalPointer());\n if (!parentNode)\n parentNode = rootNode;\n\n TreeNode *node = parentNode->children.at(row);\n Q_ASSERT(node);\n if (!node)\n return QModelIndex();\n\n return createIndex(row, column, node);\n}\n\nQModelIndex TableToTreeProxyModel::parent(const QModelIndex &child) const\n{\n if (!child.isValid())\n return QModelIndex();\n\n const TreeNode *childNode = static_cast(child.internalPointer());\n Q_ASSERT(childNode);\n if (!childNode)\n return QModelIndex();\n\n TreeNode *parentNode = childNode->parent;\n Q_ASSERT(parentNode);\n if (!parentNode)\n return QModelIndex();\n\n return createIndex(parentNode->row, parentNode->column, parentNode);\n}\n\nint TableToTreeProxyModel::rowCount(const QModelIndex &parent) const\n{\n const TreeNode *node = static_cast(parent.internalPointer());\n if (!node)\n node = rootNode;\n\n return node->children.size();\n}\n\nint TableToTreeProxyModel::columnCount(const QModelIndex &) const\n{\n return 1;\n}\n\nbool TableToTreeProxyModel::hasChildren(const QModelIndex &parent) const\n{\n const TreeNode *node = static_cast(parent.internalPointer());\n if (!node)\n node = rootNode;\n\n return node->children.size() > 0;\n}\n\nvoid TableToTreeProxyModel::setSourceModel(QAbstractItemModel *sourceModel)\n{\n \/\/ TODO: cleanup on already existing\n tableNodes.clear();\n rootNode = new TreeNode;\n\n for (int row=0; row < sourceModel->rowCount(); ++row) {\n QList rowNodes;\n TreeNode *previousNode = rootNode;\n for (int column=0; column < sourceModel->columnCount(); ++column) {\n const QString &nodeText = sourceModel->data(sourceModel->index(row, column)).toString();\n TreeNode *node = 0;\n foreach (TreeNode *siblingNode, previousNode->children) {\n Q_ASSERT(siblingNode);\n if (!siblingNode)\n continue;\n if (siblingNode->text == nodeText) {\n node = siblingNode;\n break;\n }\n }\n\n if (!node) {\n node = new TreeNode(row, column, previousNode);\n node->text = nodeText;\n }\n rowNodes.insert(column, node);\n previousNode = node;\n }\n tableNodes.insert(row, rowNodes);\n }\n\n QAbstractProxyModel::setSourceModel(sourceModel);\n}\n<|endoftext|>"} {"text":"\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * .\n *\/\n\n#include \n#include \n#include \n#include \n\n#if !defined(XALAN_NO_NAMESPACES)\n\tusing std::cerr;\n\tusing std::cout;\n\tusing std::cin;\n\tusing std::endl;\n\tusing std::ifstream;\n\tusing std::ios_base;\n\tusing std::ostrstream;\n\tusing std::string;\n#endif\n\n\/\/ XERCES HEADERS...\n\/\/\tAre included by HarnessInit.hpp\n\n\/\/ XALAN HEADERS...\n\/\/\tAre included by FileUtility.hpp\n\n\/\/ HARNESS HEADERS...\n#include \n#include \n#include \n\n#if defined(XALAN_NO_NAMESPACES)\n\ttypedef map >\tHashtable;\n#else\n\ttypedef std::map Hashtable;\n#endif\n\n\/\/ This is here for memory leak testing.\n#if !defined(NDEBUG) && defined(_MSC_VER)\n#include \n#endif\n\nFileUtility\t\th;\n\nvoid\nsetHelp()\n{\n\th.args.help << endl\n\t\t << \"compare dirname [-out -gold]\"\n\t\t << endl\n\t\t << endl\n\t\t << \"dirname\t\t(base directory for testcases)\"\n\t\t << endl\n\t\t << \"-out dirname\t(base directory for output)\"\n\t\t << endl\n\t\t << \"-gold dirname\t(base directory for gold files)\"\n\t\t << endl;\n}\n\nint\nmain(int\t\t\targc,\n\t const char*\targv[])\n{\n#if !defined(NDEBUG) && defined(_MSC_VER)\n\t_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);\n\t_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);\n\t_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);\n#endif\n\n\tHarnessInit xmlPlatformUtils;\n\tXalanTransformer::initialize();\n\n\t{\n\t\tint transResult = 0;\n\t\tbool setGold = true;\n\t\tXalanDOMString fileName;\n\n\t\t\/\/ Set the program help string, then get the command line parameters.\n\t\t\/\/\n\t\tsetHelp();\n\n\t\tif (h.getParams(argc, argv, \"DOMCOM-RESULTS\", setGold) == true)\n\t\t{\n\t\t\t\/\/\n\t\t\t\/\/ Call the static initializers for xerces and xalan, and create a transformer\n\t\t\t\/\/\n\t\t\tXalanTransformer xalan;\n\n\t\t\tXalanSourceTreeDOMSupport domSupport;\n\t\t\tXalanSourceTreeParserLiaison parserLiaison(domSupport);\n\t\t\tdomSupport.setParserLiaison(&parserLiaison);\n\n\n\t\t\t\/\/ Generate Unique Run id and processor info\n\t\t\tconst XalanDOMString UniqRunid = h.generateUniqRunid();\n\t\t\tconst XalanDOMString resultFilePrefix(\"cpp\");\n\t\t\tconst XalanDOMString resultsFile(h.args.output + resultFilePrefix + UniqRunid + XMLSuffix);\n\n\n\t\t\tXMLFileReporter\tlogFile(resultsFile);\n\t\t\tlogFile.logTestFileInit(\"Comparison Testing:\");\n\t\t\t\t\n\t\t\t\/\/ Specify the \"test\" directory for both input and output.\n\t\t\t\/\/\n\t\t\tconst XalanDOMString currentDir(\"domcomtests\");\n\t\t\tconst XalanDOMString theOutputDir = h.args.output + currentDir;\n\t\t\th.checkAndCreateDir(theOutputDir);\n\n\t\t\t\/\/ Get the files found in the test directory\n\t\t\t\/\/\n\t\t\tlogFile.logTestCaseInit(currentDir);\n\t\t\tconst FileNameVectorType files = h.getTestFileNames(h.args.base, currentDir, true);\n\n\t\t\tfor(FileNameVectorType::size_type i = 0; i < files.size(); i++)\n\t\t\t{\n\t\t\t\tfileName = files[i];\n\t\t\t\th.data.reset();\n\t\t\t\th.data.testOrFile = fileName;\n\n\t\t\t\tconst XalanDOMString theXSLFile= h.args.base + currentDir + pathSep + fileName;\n\t\t\t\tconst XalanDOMString theXMLFile = h.generateFileName(theXSLFile,\"xml\");\n\t\t\t\tXalanDOMString theGoldFile = h.args.gold + currentDir + pathSep + fileName;\n\t\t\t\ttheGoldFile = h.generateFileName(theGoldFile, \"out\");\n\n\t\t\t\tconst XalanDOMString outbase = h.args.output + currentDir + pathSep + fileName; \n\t\t\t\tconst XalanDOMString theOutputFile = h.generateFileName(outbase, \"out\");\n\n\t\t\t\tconst XSLTInputSource\txslInputSource(c_wstr(theXSLFile));\n\t\t\t\tconst XSLTInputSource\txmlInputSource(c_wstr(theXMLFile));\n\t\t\t\tconst XSLTInputSource\tgoldInputSource(c_wstr(theGoldFile));\n\n\t\t\t\t\/\/ Use a XalanSourceTreeDocument to create the XSLTResultTarget. \n\t\t\t\t\/\/\n\t\t\t\tXalanSourceTreeDocument* dom = parserLiaison.createXalanSourceTreeDocument();\n\t\t\t\tFormatterToSourceTree domOut(dom); \n\t\t\t\tXSLTResultTarget domResultTarget;\n\t\t\t\tdomResultTarget.setDocumentHandler(&domOut);\n\n\t\t\t\t\/\/ Parsing(compile) the XSL stylesheet and report the results..\n\t\t\t\t\/\/\n\t\t\t\tconst XalanCompiledStylesheet*\tcompiledSS = 0;\n\t\t\t\txalan.compileStylesheet(xslInputSource, compiledSS);\n\t\t\t\tif (compiledSS == 0 )\n\t\t\t\t{ \n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t\/\/ Parsing the input XML and report the results..\n\t\t\t\t\/\/\n\t\t\t\tconst XalanParsedSource* parsedSource = 0;\n\t\t\t\txalan.parseSource(xmlInputSource, parsedSource);\n\t\t\t\tif (parsedSource == 0)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t\/\/ Perform One transform using parsed stylesheet and unparsed xml source, report results...\n\t\t\t\t\/\/ \n\t\t\t\txalan.transform(*parsedSource, compiledSS, domResultTarget);\n\t\t\t\th.checkDOMResults(theOutputFile, compiledSS, dom, goldInputSource, logFile);\n\n\t\t\t\tparserLiaison.reset();\n\t\t\t\txalan.destroyParsedSource(parsedSource);\n\t\t\t\txalan.destroyStylesheet(compiledSS);\n\t\t\t}\n\n\t\tlogFile.logTestCaseClose(\"Done\", \"Pass\");\n\t\th.reportPassFail(logFile, UniqRunid);\n\t\tlogFile.logTestFileClose(\"DomCom \", \"Done\");\n\t\tlogFile.close();\n\n\t\th.analyzeResults(xalan, resultsFile);\n\t\t}\n\t}\n\n\tXalanTransformer::terminate();\n\n\n\treturn 0;\n}\nClean of includes.\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * .\n *\/\n\n#include \n#include \n#include \n#include \n\n#if !defined(XALAN_NO_NAMESPACES)\n\tusing std::cerr;\n\tusing std::cout;\n\tusing std::cin;\n\tusing std::endl;\n\tusing std::ifstream;\n\tusing std::ios_base;\n\tusing std::ostrstream;\n\tusing std::string;\n#endif\n\n\/\/ XERCES HEADERS...\n\/\/\tAre included by HarnessInit.hpp\n\n\/\/ XALAN HEADERS...\n#include \n#include \n#include \n\n#include \n\n\/\/ HARNESS HEADERS...\n#include \n#include \n#include \n\n#if defined(XALAN_NO_NAMESPACES)\n\ttypedef map >\tHashtable;\n#else\n\ttypedef std::map Hashtable;\n#endif\n\n\/\/ This is here for memory leak testing.\n#if !defined(NDEBUG) && defined(_MSC_VER)\n#include \n#endif\n\n\n\nvoid\nsetHelp(FileUtility&\th)\n{\n\th.args.getHelpStream() << endl\n\t\t << \"compare dirname [-out -gold]\"\n\t\t << endl\n\t\t << endl\n\t\t << \"dirname\t\t(base directory for testcases)\"\n\t\t << endl\n\t\t << \"-out dirname\t(base directory for output)\"\n\t\t << endl\n\t\t << \"-gold dirname\t(base directory for gold files)\"\n\t\t << endl;\n}\n\nint\nmain(int\t\t\targc,\n\t const char*\targv[])\n{\n#if !defined(NDEBUG) && defined(_MSC_VER)\n\t_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);\n\t_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);\n\t_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);\n#endif\n\n\tHarnessInit xmlPlatformUtils;\n\n\t{\n\t\tFileUtility\t\th;\n\n\t\tint transResult = 0;\n\t\tbool setGold = true;\n\t\tXalanDOMString fileName;\n\n\t\t\/\/ Set the program help string, then get the command line parameters.\n\t\t\/\/\n\t\tsetHelp(h);\n\n\t\tif (h.getParams(argc, argv, \"DOMCOM-RESULTS\", setGold) == true)\n\t\t{\n\t\t\tXalanTransformer::initialize();\n\n\t\t\t{\n\t\t\t\t\/\/\n\t\t\t\t\/\/ Call the static initializers for xerces and xalan, and create a transformer\n\t\t\t\t\/\/\n\t\t\t\tXalanTransformer xalan;\n\n\t\t\t\tXalanSourceTreeDOMSupport domSupport;\n\t\t\t\tXalanSourceTreeParserLiaison parserLiaison(domSupport);\n\t\t\t\tdomSupport.setParserLiaison(&parserLiaison);\n\n\n\t\t\t\t\/\/ Generate Unique Run id and processor info\n\t\t\t\tconst XalanDOMString UniqRunid = h.generateUniqRunid();\n\t\t\t\tconst XalanDOMString resultFilePrefix(\"cpp\");\n\t\t\t\tconst XalanDOMString resultsFile(h.args.output + resultFilePrefix + UniqRunid + FileUtility::s_xmlSuffix);\n\n\n\t\t\t\tXMLFileReporter\tlogFile(resultsFile);\n\t\t\t\tlogFile.logTestFileInit(\"Comparison Testing:\");\n\t\t\t\t\t\n\t\t\t\t\/\/ Specify the \"test\" directory for both input and output.\n\t\t\t\t\/\/\n\t\t\t\tconst XalanDOMString currentDir(\"domcomtests\");\n\t\t\t\tconst XalanDOMString theOutputDir = h.args.output + currentDir;\n\t\t\t\th.checkAndCreateDir(theOutputDir);\n\n\t\t\t\t\/\/ Get the files found in the test directory\n\t\t\t\t\/\/\n\t\t\t\tlogFile.logTestCaseInit(currentDir);\n\t\t\t\tconst FileNameVectorType files = h.getTestFileNames(h.args.base, currentDir, true);\n\n\t\t\t\tfor(FileNameVectorType::size_type i = 0; i < files.size(); i++)\n\t\t\t\t{\n\t\t\t\t\tfileName = files[i];\n\t\t\t\t\th.data.reset();\n\t\t\t\t\th.data.testOrFile = fileName;\n\n\t\t\t\t\tconst XalanDOMString theXSLFile= h.args.base + currentDir + FileUtility::s_pathSep + fileName;\n\t\t\t\t\tconst XalanDOMString theXMLFile = h.generateFileName(theXSLFile,\"xml\");\n\t\t\t\t\tXalanDOMString theGoldFile = h.args.gold + currentDir + FileUtility::s_pathSep + fileName;\n\t\t\t\t\ttheGoldFile = h.generateFileName(theGoldFile, \"out\");\n\n\t\t\t\t\tconst XalanDOMString outbase = h.args.output + currentDir + FileUtility::s_pathSep + fileName; \n\t\t\t\t\tconst XalanDOMString theOutputFile = h.generateFileName(outbase, \"out\");\n\n\t\t\t\t\tconst XSLTInputSource\txslInputSource(c_wstr(theXSLFile));\n\t\t\t\t\tconst XSLTInputSource\txmlInputSource(c_wstr(theXMLFile));\n\t\t\t\t\tconst XSLTInputSource\tgoldInputSource(c_wstr(theGoldFile));\n\n\t\t\t\t\t\/\/ Use a XalanSourceTreeDocument to create the XSLTResultTarget. \n\t\t\t\t\t\/\/\n\t\t\t\t\tXalanSourceTreeDocument* dom = parserLiaison.createXalanSourceTreeDocument();\n\t\t\t\t\tFormatterToSourceTree domOut(dom); \n\t\t\t\t\tXSLTResultTarget domResultTarget;\n\t\t\t\t\tdomResultTarget.setDocumentHandler(&domOut);\n\n\t\t\t\t\t\/\/ Parsing(compile) the XSL stylesheet and report the results..\n\t\t\t\t\t\/\/\n\t\t\t\t\tconst XalanCompiledStylesheet*\tcompiledSS = 0;\n\t\t\t\t\txalan.compileStylesheet(xslInputSource, compiledSS);\n\t\t\t\t\tif (compiledSS == 0 )\n\t\t\t\t\t{ \n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Parsing the input XML and report the results..\n\t\t\t\t\t\/\/\n\t\t\t\t\tconst XalanParsedSource* parsedSource = 0;\n\t\t\t\t\txalan.parseSource(xmlInputSource, parsedSource);\n\t\t\t\t\tif (parsedSource == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Perform One transform using parsed stylesheet and unparsed xml source, report results...\n\t\t\t\t\t\/\/ \n\t\t\t\t\txalan.transform(*parsedSource, compiledSS, domResultTarget);\n\t\t\t\t\th.checkDOMResults(theOutputFile, compiledSS, dom, goldInputSource, logFile);\n\n\t\t\t\t\tparserLiaison.reset();\n\t\t\t\t\txalan.destroyParsedSource(parsedSource);\n\t\t\t\t\txalan.destroyStylesheet(compiledSS);\n\t\t\t\t}\n\n\t\t\t\tlogFile.logTestCaseClose(\"Done\", \"Pass\");\n\t\t\t\th.reportPassFail(logFile, UniqRunid);\n\t\t\t\tlogFile.logTestFileClose(\"DomCom \", \"Done\");\n\t\t\t\tlogFile.close();\n\n\t\t\t\th.analyzeResults(xalan, resultsFile);\n\t\t\t}\n\n\t\t\tXalanTransformer::terminate();\n\t\t}\n\t}\n\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\n#include \"AliVZERODataDCS.h\"\n\n#include \"AliDCSValue.h\"\n#include \"AliLog.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nclass TH2;\nclass AliCDBMetaData;\nclass TDatime;\n\n\/\/ AliVZERODataDCS class\n\/\/ main aim to introduce the aliases for the VZERO DCS\n\/\/ data points to be then\n\/\/ stored in the OCDB, and to process them. \n\/\/ ProcessData() method called by VZEROPreprocessor\n\nClassImp(AliVZERODataDCS)\n\n\/\/_____________________________________________________________________________\nAliVZERODataDCS::AliVZERODataDCS():\n\tTObject(),\n\tfRun(0),\n\tfStartTime(0),\n\tfEndTime(0),\n fGraphs(\"TGraph\",kNGraphs),\n\tfIsProcessed(kFALSE)\n{\n \/\/ Default constructor\n for(int i=0;iGetEntries()<2){\n AliError(Form(\"Alias %s has just %d entries!\",\n\t\t fAliasNames[iAlias].Data(),aliasArr->GetEntries()));\n continue;\n }\n \n TIter iterarray(aliasArr);\n \n Int_t nentries = aliasArr->GetEntries();\n \n Double_t *times = new Double_t[nentries];\n Double_t *values = new Double_t[nentries];\n\n UInt_t iValue=0;\n while((aValue = (AliDCSValue*) iterarray.Next())) {\n \t\tvalues[iValue] = aValue->GetFloat();\n\t\tif(iValue>0) {\n\t\t\tFloat_t variation ;\n\t\t\tif(values[iValue-1]>0.) variation = TMath::Abs(values[iValue]-values[iValue-1])\/values[iValue-1];\n\t\t\tif(variation > 0.10) fDeadChannel[GetOfflineChannel(iAlias)] = kTRUE;\n\t\t}\n \t\ttimes[iValue] = (Double_t) (aValue->GetTimeStamp());\n\t\tfHv[iAlias]->Fill(values[iValue]);\n\t\tprintf(\"%s %f Dead=%d\\n\",fAliasNames[iAlias].Data(),values[iValue],fDeadChannel[GetOfflineChannel(iAlias)]);\n \t\tiValue++;\n } \n CreateGraph(iAlias, aliasArr->GetEntries(), times, values); \/\/ fill graphs \n \n delete[] values;\n delete[] times;\t \n }\n \n \t\/\/ calculate mean and rms of the first two histos\n\t\/\/ and convert index to aliroot channel\n\tfor(int i=0;iGetMean();\n\t\tfWidthHV[iChannel] = fHv[i]->GetRMS();\n\t}\n \n fIsProcessed=kTRUE;\n}\n\n\/\/_____________________________________________________________________________\nvoid AliVZERODataDCS::Init(){\n\n \/\/ initialization of aliases and DCS data\n\n TString sindex;\n int iAlias = 0;\n \n for(int iSide = 0; iSide<2 ; iSide++){\n \tfor(int iRing = 0; iRing<4 ; iRing++){\n \t\tfor(int iSector = 0; iSector<8 ; iSector++){\n \t\t\tif(iSide == 0) fAliasNames[iAlias] = \"V00\/HV\/V0A\/SECTOR\";\n \t\t\telse fAliasNames[iAlias] = \"V00\/HV\/V0C\/SECTOR\";\n\t\t\tsindex.Form(\"%d\/RING%d\",iSector,iRing);\n\t\t\tfAliasNames[iAlias] += sindex;\n\t\t\t\n\t\t\tfHv[iAlias] = new TH1F(fAliasNames[iAlias].Data(),fAliasNames[iAlias].Data(), 2000, kHvMin, kHvMax);\n\t\t\tfHv[iAlias]->GetXaxis()->SetTitle(\"Hv\");\n\t\t\tiAlias++;\n \t\t}\n \t}\n }\n if(iAlias!=kNAliases) \n \t AliError(Form(\"Number of DCS Aliases defined not correct\"));\n\n}\n\n\/\/_____________________________________________________________________________\nvoid AliVZERODataDCS::Introduce(UInt_t numAlias, const TObjArray* aliasArr)const\n{\n\n \/\/ method to introduce new aliases\n\n int entries=aliasArr->GetEntries();\n AliInfo(Form(\"************ Alias: %s **********\",fAliasNames[numAlias].Data()));\n AliInfo(Form(\" \t%d DP values collected\",entries));\n\n}\n\n\/\/_____________________________________________________________________________\nvoid AliVZERODataDCS::CreateGraph(int i, int dim, const Double_t *x, const Double_t *y)\n{\n\n \/\/ Create graphics\n \n TGraph *gr = new(fGraphs[fGraphs.GetEntriesFast()]) TGraph(dim, x, y);\n\n gr->GetXaxis()->SetTimeDisplay(1);\n gr->SetTitle(fAliasNames[i].Data());\n\n AliInfo(Form(\"Array entries: %d\",fGraphs.GetEntriesFast()));\n\n}\n\n\n\/\/_____________________________________________________________________________\nvoid AliVZERODataDCS::Draw(const Option_t* \/*option*\/)\n{\n\/\/ Draw all histos and graphs\n\n if(!fIsProcessed) return;\n\n if(fGraphs.GetEntries()==0) return;\n \n TString canvasName;\n TCanvas *cHV[8];\n \n for(int iSide = 0 ;iSide<2;iSide++){\n \tfor(int iRing=0;iRing<4;iRing++){\n \t\tif(iSide == 0) canvasName = \"V0A_Ring\";\n \t\telse canvasName = \"V0C_Ring\";\n \t\tcanvasName += iRing;\n \t\tint iCanvas = iSide*4 + iRing;\n \t\tcHV[iCanvas] = new TCanvas(canvasName,canvasName);\n \t\tcHV[iCanvas]->Divide(3,3);\n \t\tfor(int iSector=0;iSector<8;iSector++){\n \t\t\tcHV[iCanvas]->cd(iSector+1);\n \t\t\tint iChannel = iSide*32 + iRing*8 + iSector; \n \t\t\t((TGraph*) fGraphs.UncheckedAt(iChannel))->SetMarkerStyle(20);\n \t\t\t((TGraph*) fGraphs.UncheckedAt(iChannel))->Draw(\"ALP\");\n\n \t\t}\n \t\t \t\t\n \t}\n }\n\n}\n\nWarning fixed\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\n#include \"AliVZERODataDCS.h\"\n\n#include \"AliDCSValue.h\"\n#include \"AliLog.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nclass TH2;\nclass AliCDBMetaData;\nclass TDatime;\n\n\/\/ AliVZERODataDCS class\n\/\/ main aim to introduce the aliases for the VZERO DCS\n\/\/ data points to be then\n\/\/ stored in the OCDB, and to process them. \n\/\/ ProcessData() method called by VZEROPreprocessor\n\nClassImp(AliVZERODataDCS)\n\n\/\/_____________________________________________________________________________\nAliVZERODataDCS::AliVZERODataDCS():\n\tTObject(),\n\tfRun(0),\n\tfStartTime(0),\n\tfEndTime(0),\n fGraphs(\"TGraph\",kNGraphs),\n\tfIsProcessed(kFALSE)\n{\n \/\/ Default constructor\n for(int i=0;iGetEntries()<2){\n AliError(Form(\"Alias %s has just %d entries!\",\n\t\t fAliasNames[iAlias].Data(),aliasArr->GetEntries()));\n continue;\n }\n \n TIter iterarray(aliasArr);\n \n Int_t nentries = aliasArr->GetEntries();\n \n Double_t *times = new Double_t[nentries];\n Double_t *values = new Double_t[nentries];\n\n UInt_t iValue=0;\n Float_t variation = 0.0;\n \n while((aValue = (AliDCSValue*) iterarray.Next())) {\n \t\tvalues[iValue] = aValue->GetFloat();\n\t\tif(iValue>0) {\n\t\t\tif(values[iValue-1]>0.) variation = TMath::Abs(values[iValue]-values[iValue-1])\/values[iValue-1];\n\t\t\tif(variation > 0.10) fDeadChannel[GetOfflineChannel(iAlias)] = kTRUE;\n\t\t}\n \t\ttimes[iValue] = (Double_t) (aValue->GetTimeStamp());\n\t\tfHv[iAlias]->Fill(values[iValue]);\n\t\tprintf(\"%s %f Dead=%d\\n\",fAliasNames[iAlias].Data(),values[iValue],fDeadChannel[GetOfflineChannel(iAlias)]);\n \t\tiValue++;\n } \n CreateGraph(iAlias, aliasArr->GetEntries(), times, values); \/\/ fill graphs \n \n delete[] values;\n delete[] times;\t \n }\n \n \t\/\/ calculate mean and rms of the first two histos\n\t\/\/ and convert index to aliroot channel\n\tfor(int i=0;iGetMean();\n\t\tfWidthHV[iChannel] = fHv[i]->GetRMS();\n\t}\n \n fIsProcessed=kTRUE;\n}\n\n\/\/_____________________________________________________________________________\nvoid AliVZERODataDCS::Init(){\n\n \/\/ initialization of aliases and DCS data\n\n TString sindex;\n int iAlias = 0;\n \n for(int iSide = 0; iSide<2 ; iSide++){\n \tfor(int iRing = 0; iRing<4 ; iRing++){\n \t\tfor(int iSector = 0; iSector<8 ; iSector++){\n \t\t\tif(iSide == 0) fAliasNames[iAlias] = \"V00\/HV\/V0A\/SECTOR\";\n \t\t\telse fAliasNames[iAlias] = \"V00\/HV\/V0C\/SECTOR\";\n\t\t\tsindex.Form(\"%d\/RING%d\",iSector,iRing);\n\t\t\tfAliasNames[iAlias] += sindex;\n\t\t\t\n\t\t\tfHv[iAlias] = new TH1F(fAliasNames[iAlias].Data(),fAliasNames[iAlias].Data(), 2000, kHvMin, kHvMax);\n\t\t\tfHv[iAlias]->GetXaxis()->SetTitle(\"Hv\");\n\t\t\tiAlias++;\n \t\t}\n \t}\n }\n if(iAlias!=kNAliases) \n \t AliError(Form(\"Number of DCS Aliases defined not correct\"));\n\n}\n\n\/\/_____________________________________________________________________________\nvoid AliVZERODataDCS::Introduce(UInt_t numAlias, const TObjArray* aliasArr)const\n{\n\n \/\/ method to introduce new aliases\n\n int entries=aliasArr->GetEntries();\n AliInfo(Form(\"************ Alias: %s **********\",fAliasNames[numAlias].Data()));\n AliInfo(Form(\" \t%d DP values collected\",entries));\n\n}\n\n\/\/_____________________________________________________________________________\nvoid AliVZERODataDCS::CreateGraph(int i, int dim, const Double_t *x, const Double_t *y)\n{\n\n \/\/ Create graphics\n \n TGraph *gr = new(fGraphs[fGraphs.GetEntriesFast()]) TGraph(dim, x, y);\n\n gr->GetXaxis()->SetTimeDisplay(1);\n gr->SetTitle(fAliasNames[i].Data());\n\n AliInfo(Form(\"Array entries: %d\",fGraphs.GetEntriesFast()));\n\n}\n\n\n\/\/_____________________________________________________________________________\nvoid AliVZERODataDCS::Draw(const Option_t* \/*option*\/)\n{\n\/\/ Draw all histos and graphs\n\n if(!fIsProcessed) return;\n\n if(fGraphs.GetEntries()==0) return;\n \n TString canvasName;\n TCanvas *cHV[8];\n \n for(int iSide = 0 ;iSide<2;iSide++){\n \tfor(int iRing=0;iRing<4;iRing++){\n \t\tif(iSide == 0) canvasName = \"V0A_Ring\";\n \t\telse canvasName = \"V0C_Ring\";\n \t\tcanvasName += iRing;\n \t\tint iCanvas = iSide*4 + iRing;\n \t\tcHV[iCanvas] = new TCanvas(canvasName,canvasName);\n \t\tcHV[iCanvas]->Divide(3,3);\n \t\tfor(int iSector=0;iSector<8;iSector++){\n \t\t\tcHV[iCanvas]->cd(iSector+1);\n \t\t\tint iChannel = iSide*32 + iRing*8 + iSector; \n \t\t\t((TGraph*) fGraphs.UncheckedAt(iChannel))->SetMarkerStyle(20);\n \t\t\t((TGraph*) fGraphs.UncheckedAt(iChannel))->Draw(\"ALP\");\n\n \t\t}\n \t\t \t\t\n \t}\n }\n\n}\n\n<|endoftext|>"} {"text":"#include \"stdafx.h\"\r\n#include \"DropDownPane.h\"\r\n#include \"String.h\"\r\n#include \"InterpretProp2.h\"\r\n#include \r\n\r\nstatic wstring CLASS = L\"DropDownPane\";\r\n\r\nViewPane* CreateDropDownPane(UINT uidLabel, ULONG ulDropList, _In_opt_count_(ulDropList) UINT* lpuidDropList, bool bReadOnly)\r\n{\r\n\treturn new DropDownPane(uidLabel, bReadOnly, ulDropList, lpuidDropList, nullptr, false);\r\n}\r\n\r\nViewPane* CreateDropDownArrayPane(UINT uidLabel, ULONG ulDropList, _In_opt_count_(ulDropList) LPNAME_ARRAY_ENTRY lpnaeDropList, bool bReadOnly)\r\n{\r\n\treturn new DropDownPane(uidLabel, bReadOnly, ulDropList, nullptr, lpnaeDropList, false);\r\n}\r\n\r\nViewPane* CreateDropDownGuidPane(UINT uidLabel, bool bReadOnly)\r\n{\r\n\treturn new DropDownPane(uidLabel, bReadOnly, 0, nullptr, nullptr, true);\r\n}\r\n\r\nDropDownPane::DropDownPane(UINT uidLabel, bool bReadOnly, ULONG ulDropList, _In_opt_count_(ulDropList) UINT* lpuidDropList, _In_opt_count_(ulDropList) LPNAME_ARRAY_ENTRY lpnaeDropList, bool bGUID) :ViewPane(uidLabel, bReadOnly)\r\n{\r\n\tm_ulDropList = ulDropList;\r\n\tm_lpuidDropList = lpuidDropList;\r\n\tm_iDropSelection = CB_ERR;\r\n\tm_iDropSelectionValue = 0;\r\n\tm_lpnaeDropList = lpnaeDropList;\r\n\tm_bGUID = bGUID;\r\n}\r\n\r\nbool DropDownPane::IsType(__ViewTypes vType)\r\n{\r\n\treturn CTRL_DROPDOWNPANE == vType;\r\n}\r\n\r\nULONG DropDownPane::GetFlags()\r\n{\r\n\tULONG ulFlags = vpNone;\r\n\tif (m_bReadOnly) ulFlags |= vpReadonly;\r\n\treturn ulFlags;\r\n}\r\n\r\nwstring GetLBText(CComboBox& box, int nIndex)\r\n{\r\n\tauto len = box.GetLBTextLen(nIndex);\r\n\tauto buffer = new TCHAR[len];\r\n\tmemset(buffer, 0, sizeof(TCHAR)* len);\r\n\tbox.GetLBText(nIndex, buffer);\r\n\tauto szOut = LPCTSTRToWstring(buffer);\r\n\tdelete[] buffer;\r\n\treturn szOut;\r\n}\r\n\r\nint DropDownPane::GetMinWidth(_In_ HDC hdc)\r\n{\r\n\tauto cxDropDown = 0;\r\n\tfor (auto iDropString = 0; iDropString < m_DropDown.GetCount(); iDropString++)\r\n\t{\r\n\t\tSIZE sizeDrop = { 0 };\r\n\t\tauto szDropString = GetLBText(m_DropDown, iDropString);\r\n\t\t::GetTextExtentPoint32W(hdc, szDropString.c_str(), szDropString.length(), &sizeDrop);\r\n\t\tcxDropDown = max(cxDropDown, sizeDrop.cx);\r\n\t}\r\n\r\n\t\/\/ Add scroll bar and margins for our frame\r\n\tcxDropDown += ::GetSystemMetrics(SM_CXVSCROLL) + 2 * GetSystemMetrics(SM_CXFIXEDFRAME);\r\n\r\n\treturn max(ViewPane::GetMinWidth(hdc), cxDropDown);\r\n}\r\n\r\nint DropDownPane::GetFixedHeight()\r\n{\r\n\tauto iHeight = 0;\r\n\r\n\tif (0 != m_iControl) iHeight += m_iSmallHeightMargin; \/\/ Top margin\r\n\r\n\tif (m_bUseLabelControl)\r\n\t{\r\n\t\tiHeight += m_iLabelHeight;\r\n\t}\r\n\r\n\tiHeight += m_iEditHeight; \/\/ Height of the dropdown\r\n\r\n\t\/\/ No bottom margin on the DropDown as it's usually tied to the following control\r\n\treturn iHeight;\r\n}\r\n\r\nint DropDownPane::GetLines()\r\n{\r\n\treturn 0;\r\n}\r\n\r\nvoid DropDownPane::SetWindowPos(int x, int y, int width, int \/*height*\/)\r\n{\r\n\tauto hRes = S_OK;\r\n\tif (0 != m_iControl)\r\n\t{\r\n\t\ty += m_iSmallHeightMargin;\r\n\t\t\/\/ height -= m_iSmallHeightMargin;\r\n\t}\r\n\r\n\tif (m_bUseLabelControl)\r\n\t{\r\n\t\tEC_B(m_Label.SetWindowPos(\r\n\t\t\tnullptr,\r\n\t\t\tx,\r\n\t\t\ty,\r\n\t\t\twidth,\r\n\t\t\tm_iLabelHeight,\r\n\t\t\tSWP_NOZORDER));\r\n\t\ty += m_iLabelHeight;\r\n\t\t\/\/ height -= m_iLabelHeight;\r\n\t}\r\n\r\n\tEC_B(m_DropDown.SetWindowPos(NULL, x, y, width, m_iEditHeight, SWP_NOZORDER));\r\n}\r\n\r\nvoid DropDownPane::DoInit(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)\r\n{\r\n\tauto hRes = S_OK;\r\n\r\n\tViewPane::Initialize(iControl, pParent, hdc);\r\n\r\n\tauto ulDrops = 1 + (m_ulDropList ? min(m_ulDropList, 4) : 4);\r\n\tauto dropHeight = ulDrops * (pParent ? GetEditHeight(pParent->m_hWnd) : 0x1e);\r\n\r\n\t\/\/ m_bReadOnly means you can't type...\r\n\tDWORD dwDropStyle;\r\n\tif (m_bReadOnly)\r\n\t{\r\n\t\tdwDropStyle = CBS_DROPDOWNLIST; \/\/ does not allow typing\r\n\t}\r\n\telse\r\n\t{\r\n\t\tdwDropStyle = CBS_DROPDOWN; \/\/ allows typing\r\n\t}\r\n\r\n\tEC_B(m_DropDown.Create(\r\n\t\tWS_TABSTOP\r\n\t\t| WS_CHILD\r\n\t\t| WS_CLIPSIBLINGS\r\n\t\t| WS_BORDER\r\n\t\t| WS_VISIBLE\r\n\t\t| WS_VSCROLL\r\n\t\t| CBS_OWNERDRAWFIXED\r\n\t\t| CBS_HASSTRINGS\r\n\t\t| CBS_AUTOHSCROLL\r\n\t\t| CBS_DISABLENOSCROLL\r\n\t\t| dwDropStyle,\r\n\t\tCRect(0, 0, 0, dropHeight),\r\n\t\tpParent,\r\n\t\tm_nID));\r\n}\r\n\r\nvoid DropDownPane::Initialize(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)\r\n{\r\n\tDoInit(iControl, pParent, hdc);\r\n\r\n\tif (m_lpuidDropList)\r\n\t{\r\n\t\tfor (ULONG iDropNum = 0; iDropNum < m_ulDropList; iDropNum++)\r\n\t\t{\r\n\t\t\tauto szDropString = loadstring(m_lpuidDropList[iDropNum]);\r\n\t\t\tInsertDropString(iDropNum, szDropString, m_lpuidDropList[iDropNum]);\r\n\t\t}\r\n\t}\r\n\telse if (m_lpnaeDropList)\r\n\t{\r\n\t\tfor (ULONG iDropNum = 0; iDropNum < m_ulDropList; iDropNum++)\r\n\t\t{\r\n\t\t\tauto szDropString = wstring(m_lpnaeDropList[iDropNum].lpszName);\r\n\t\t\tInsertDropString(iDropNum, szDropString, m_lpnaeDropList[iDropNum].ulValue);\r\n\t\t}\r\n\t}\r\n\r\n\t\/\/ If this is a GUID list, load up our list of guids\r\n\tif (m_bGUID)\r\n\t{\r\n\t\tfor (ULONG iDropNum = 0; iDropNum < ulPropGuidArray; iDropNum++)\r\n\t\t{\r\n\t\t\tInsertDropString(iDropNum, GUIDToStringAndName(PropGuidArray[iDropNum].lpGuid), iDropNum);\r\n\t\t}\r\n\t}\r\n\r\n\tm_DropDown.SetCurSel(static_cast(m_iDropSelectionValue));\r\n\r\n\tm_bInitialized = true;\r\n}\r\n\r\nvoid DropDownPane::InsertDropString(int iRow, _In_ wstring szText, ULONG ulValue)\r\n{\r\n\tm_DropDown.InsertString(iRow, wstringToCString(szText));\r\n\tm_DropDown.SetItemData(iRow, ulValue);\r\n}\r\n\r\nvoid DropDownPane::CommitUIValues()\r\n{\r\n\tm_iDropSelection = GetDropDownSelection();\r\n\tm_iDropSelectionValue = GetDropDownSelectionValue();\r\n\tm_lpszSelectionString = GetDropStringUseControl();\r\n\tm_bInitialized = false; \/\/ must be last\r\n}\r\n\r\n_Check_return_ wstring DropDownPane::GetDropStringUseControl() const\r\n{\r\n\tCString szText;\r\n\tm_DropDown.GetWindowText(szText);\r\n\r\n\treturn LPCTSTRToWstring(szText);\r\n}\r\n\r\n\/\/ This should work whether the editor is active\/displayed or not\r\n_Check_return_ int DropDownPane::GetDropDownSelection() const\r\n{\r\n\tif (m_bInitialized) return m_DropDown.GetCurSel();\r\n\r\n\t\/\/ In case we're being called after we're done displaying, use the stored value\r\n\treturn m_iDropSelection;\r\n}\r\n\r\n_Check_return_ DWORD_PTR DropDownPane::GetDropDownSelectionValue() const\r\n{\r\n\tif (m_bInitialized)\r\n\t{\r\n\t\tauto iSel = m_DropDown.GetCurSel();\r\n\r\n\t\tif (CB_ERR != iSel)\r\n\t\t{\r\n\t\t\treturn m_DropDown.GetItemData(iSel);\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn m_iDropSelectionValue;\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n\r\n_Check_return_ int DropDownPane::GetDropDown() const\r\n{\r\n\treturn m_iDropSelection;\r\n}\r\n\r\n_Check_return_ DWORD_PTR DropDownPane::GetDropDownValue() const\r\n{\r\n\treturn m_iDropSelectionValue;\r\n}\r\n\r\n\/\/ This should work whether the editor is active\/displayed or not\r\n_Check_return_ bool DropDownPane::GetSelectedGUID(bool bByteSwapped, _In_ LPGUID lpSelectedGUID) const\r\n{\r\n\tif (!lpSelectedGUID) return NULL;\r\n\r\n\tauto iCurSel = GetDropDownSelection();\r\n\tif (iCurSel != CB_ERR)\r\n\t{\r\n\t\tmemcpy(lpSelectedGUID, PropGuidArray[iCurSel].lpGuid, sizeof(GUID));\r\n\t\treturn true;\r\n\t}\r\n\r\n\t\/\/ no match - need to do a lookup\r\n\twstring szText;\r\n\tif (m_bInitialized)\r\n\t{\r\n\t\tszText = GetDropStringUseControl();\r\n\t}\r\n\r\n\tif (szText.empty())\r\n\t{\r\n\t\tszText = m_lpszSelectionString;\r\n\t}\r\n\r\n\tauto lpGUID = GUIDNameToGUID(szText, bByteSwapped);\r\n\tif (lpGUID)\r\n\t{\r\n\t\tmemcpy(lpSelectedGUID, lpGUID, sizeof(GUID));\r\n\t\tdelete[] lpGUID;\r\n\t\treturn true;\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n\r\nvoid DropDownPane::SetDropDownSelection(_In_ wstring szText)\r\n{\r\n\tauto hRes = S_OK;\r\n\tauto text = wstringToCString(szText);\r\n\tauto iSelect = m_DropDown.SelectString(0, text);\r\n\r\n\t\/\/ if we can't select, try pushing the text in there\r\n\t\/\/ not all dropdowns will support this!\r\n\tif (CB_ERR == iSelect)\r\n\t{\r\n\t\tEC_B(::SendMessage(\r\n\t\t\tm_DropDown.m_hWnd,\r\n\t\t\tWM_SETTEXT,\r\n\t\t\tNULL,\r\n\t\t\treinterpret_cast(static_cast(text))));\r\n\t}\r\n}\r\n\r\nvoid DropDownPane::SetSelection(DWORD_PTR iSelection)\r\n{\r\n\tif (!m_bInitialized)\r\n\t{\r\n\t\tm_iDropSelectionValue = iSelection;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tm_DropDown.SetCurSel(static_cast(iSelection));\r\n\t}\r\n}kill final CString variable#include \"stdafx.h\"\r\n#include \"DropDownPane.h\"\r\n#include \"String.h\"\r\n#include \"InterpretProp2.h\"\r\n#include \r\n\r\nstatic wstring CLASS = L\"DropDownPane\";\r\n\r\nViewPane* CreateDropDownPane(UINT uidLabel, ULONG ulDropList, _In_opt_count_(ulDropList) UINT* lpuidDropList, bool bReadOnly)\r\n{\r\n\treturn new DropDownPane(uidLabel, bReadOnly, ulDropList, lpuidDropList, nullptr, false);\r\n}\r\n\r\nViewPane* CreateDropDownArrayPane(UINT uidLabel, ULONG ulDropList, _In_opt_count_(ulDropList) LPNAME_ARRAY_ENTRY lpnaeDropList, bool bReadOnly)\r\n{\r\n\treturn new DropDownPane(uidLabel, bReadOnly, ulDropList, nullptr, lpnaeDropList, false);\r\n}\r\n\r\nViewPane* CreateDropDownGuidPane(UINT uidLabel, bool bReadOnly)\r\n{\r\n\treturn new DropDownPane(uidLabel, bReadOnly, 0, nullptr, nullptr, true);\r\n}\r\n\r\nDropDownPane::DropDownPane(UINT uidLabel, bool bReadOnly, ULONG ulDropList, _In_opt_count_(ulDropList) UINT* lpuidDropList, _In_opt_count_(ulDropList) LPNAME_ARRAY_ENTRY lpnaeDropList, bool bGUID) :ViewPane(uidLabel, bReadOnly)\r\n{\r\n\tm_ulDropList = ulDropList;\r\n\tm_lpuidDropList = lpuidDropList;\r\n\tm_iDropSelection = CB_ERR;\r\n\tm_iDropSelectionValue = 0;\r\n\tm_lpnaeDropList = lpnaeDropList;\r\n\tm_bGUID = bGUID;\r\n}\r\n\r\nbool DropDownPane::IsType(__ViewTypes vType)\r\n{\r\n\treturn CTRL_DROPDOWNPANE == vType;\r\n}\r\n\r\nULONG DropDownPane::GetFlags()\r\n{\r\n\tULONG ulFlags = vpNone;\r\n\tif (m_bReadOnly) ulFlags |= vpReadonly;\r\n\treturn ulFlags;\r\n}\r\n\r\nwstring GetLBText(const CComboBox& box, int nIndex)\r\n{\r\n\tauto len = box.GetLBTextLen(nIndex) + 1;\r\n\tauto buffer = new TCHAR[len];\r\n\tmemset(buffer, 0, sizeof(TCHAR)* len);\r\n\tbox.GetLBText(nIndex, buffer);\r\n\tauto szOut = LPCTSTRToWstring(buffer);\r\n\tdelete[] buffer;\r\n\treturn szOut;\r\n}\r\n\r\nint DropDownPane::GetMinWidth(_In_ HDC hdc)\r\n{\r\n\tauto cxDropDown = 0;\r\n\tfor (auto iDropString = 0; iDropString < m_DropDown.GetCount(); iDropString++)\r\n\t{\r\n\t\tSIZE sizeDrop = { 0 };\r\n\t\tauto szDropString = GetLBText(m_DropDown, iDropString);\r\n\t\t::GetTextExtentPoint32W(hdc, szDropString.c_str(), szDropString.length(), &sizeDrop);\r\n\t\tcxDropDown = max(cxDropDown, sizeDrop.cx);\r\n\t}\r\n\r\n\t\/\/ Add scroll bar and margins for our frame\r\n\tcxDropDown += ::GetSystemMetrics(SM_CXVSCROLL) + 2 * GetSystemMetrics(SM_CXFIXEDFRAME);\r\n\r\n\treturn max(ViewPane::GetMinWidth(hdc), cxDropDown);\r\n}\r\n\r\nint DropDownPane::GetFixedHeight()\r\n{\r\n\tauto iHeight = 0;\r\n\r\n\tif (0 != m_iControl) iHeight += m_iSmallHeightMargin; \/\/ Top margin\r\n\r\n\tif (m_bUseLabelControl)\r\n\t{\r\n\t\tiHeight += m_iLabelHeight;\r\n\t}\r\n\r\n\tiHeight += m_iEditHeight; \/\/ Height of the dropdown\r\n\r\n\t\/\/ No bottom margin on the DropDown as it's usually tied to the following control\r\n\treturn iHeight;\r\n}\r\n\r\nint DropDownPane::GetLines()\r\n{\r\n\treturn 0;\r\n}\r\n\r\nvoid DropDownPane::SetWindowPos(int x, int y, int width, int \/*height*\/)\r\n{\r\n\tauto hRes = S_OK;\r\n\tif (0 != m_iControl)\r\n\t{\r\n\t\ty += m_iSmallHeightMargin;\r\n\t\t\/\/ height -= m_iSmallHeightMargin;\r\n\t}\r\n\r\n\tif (m_bUseLabelControl)\r\n\t{\r\n\t\tEC_B(m_Label.SetWindowPos(\r\n\t\t\tnullptr,\r\n\t\t\tx,\r\n\t\t\ty,\r\n\t\t\twidth,\r\n\t\t\tm_iLabelHeight,\r\n\t\t\tSWP_NOZORDER));\r\n\t\ty += m_iLabelHeight;\r\n\t\t\/\/ height -= m_iLabelHeight;\r\n\t}\r\n\r\n\tEC_B(m_DropDown.SetWindowPos(NULL, x, y, width, m_iEditHeight, SWP_NOZORDER));\r\n}\r\n\r\nvoid DropDownPane::DoInit(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)\r\n{\r\n\tauto hRes = S_OK;\r\n\r\n\tViewPane::Initialize(iControl, pParent, hdc);\r\n\r\n\tauto ulDrops = 1 + (m_ulDropList ? min(m_ulDropList, 4) : 4);\r\n\tauto dropHeight = ulDrops * (pParent ? GetEditHeight(pParent->m_hWnd) : 0x1e);\r\n\r\n\t\/\/ m_bReadOnly means you can't type...\r\n\tDWORD dwDropStyle;\r\n\tif (m_bReadOnly)\r\n\t{\r\n\t\tdwDropStyle = CBS_DROPDOWNLIST; \/\/ does not allow typing\r\n\t}\r\n\telse\r\n\t{\r\n\t\tdwDropStyle = CBS_DROPDOWN; \/\/ allows typing\r\n\t}\r\n\r\n\tEC_B(m_DropDown.Create(\r\n\t\tWS_TABSTOP\r\n\t\t| WS_CHILD\r\n\t\t| WS_CLIPSIBLINGS\r\n\t\t| WS_BORDER\r\n\t\t| WS_VISIBLE\r\n\t\t| WS_VSCROLL\r\n\t\t| CBS_OWNERDRAWFIXED\r\n\t\t| CBS_HASSTRINGS\r\n\t\t| CBS_AUTOHSCROLL\r\n\t\t| CBS_DISABLENOSCROLL\r\n\t\t| dwDropStyle,\r\n\t\tCRect(0, 0, 0, dropHeight),\r\n\t\tpParent,\r\n\t\tm_nID));\r\n}\r\n\r\nvoid DropDownPane::Initialize(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)\r\n{\r\n\tDoInit(iControl, pParent, hdc);\r\n\r\n\tif (m_lpuidDropList)\r\n\t{\r\n\t\tfor (ULONG iDropNum = 0; iDropNum < m_ulDropList; iDropNum++)\r\n\t\t{\r\n\t\t\tauto szDropString = loadstring(m_lpuidDropList[iDropNum]);\r\n\t\t\tInsertDropString(iDropNum, szDropString, m_lpuidDropList[iDropNum]);\r\n\t\t}\r\n\t}\r\n\telse if (m_lpnaeDropList)\r\n\t{\r\n\t\tfor (ULONG iDropNum = 0; iDropNum < m_ulDropList; iDropNum++)\r\n\t\t{\r\n\t\t\tauto szDropString = wstring(m_lpnaeDropList[iDropNum].lpszName);\r\n\t\t\tInsertDropString(iDropNum, szDropString, m_lpnaeDropList[iDropNum].ulValue);\r\n\t\t}\r\n\t}\r\n\r\n\t\/\/ If this is a GUID list, load up our list of guids\r\n\tif (m_bGUID)\r\n\t{\r\n\t\tfor (ULONG iDropNum = 0; iDropNum < ulPropGuidArray; iDropNum++)\r\n\t\t{\r\n\t\t\tInsertDropString(iDropNum, GUIDToStringAndName(PropGuidArray[iDropNum].lpGuid), iDropNum);\r\n\t\t}\r\n\t}\r\n\r\n\tm_DropDown.SetCurSel(static_cast(m_iDropSelectionValue));\r\n\r\n\tm_bInitialized = true;\r\n}\r\n\r\nvoid DropDownPane::InsertDropString(int iRow, _In_ wstring szText, ULONG ulValue)\r\n{\r\n\tm_DropDown.InsertString(iRow, wstringToCString(szText));\r\n\tm_DropDown.SetItemData(iRow, ulValue);\r\n}\r\n\r\nvoid DropDownPane::CommitUIValues()\r\n{\r\n\tm_iDropSelection = GetDropDownSelection();\r\n\tm_iDropSelectionValue = GetDropDownSelectionValue();\r\n\tm_lpszSelectionString = GetDropStringUseControl();\r\n\tm_bInitialized = false; \/\/ must be last\r\n}\r\n\r\n_Check_return_ wstring DropDownPane::GetDropStringUseControl() const\r\n{\r\n\tauto len = m_DropDown.GetWindowTextLength() + 1;\r\n\tauto buffer = new WCHAR[len];\r\n\tmemset(buffer, 0, sizeof(WCHAR)* len);\r\n\t::GetWindowTextW(m_DropDown.m_hWnd, buffer, len);\r\n\twstring szOut = buffer;\r\n\tdelete[] buffer;\r\n\treturn szOut;\r\n}\r\n\r\n\/\/ This should work whether the editor is active\/displayed or not\r\n_Check_return_ int DropDownPane::GetDropDownSelection() const\r\n{\r\n\tif (m_bInitialized) return m_DropDown.GetCurSel();\r\n\r\n\t\/\/ In case we're being called after we're done displaying, use the stored value\r\n\treturn m_iDropSelection;\r\n}\r\n\r\n_Check_return_ DWORD_PTR DropDownPane::GetDropDownSelectionValue() const\r\n{\r\n\tif (m_bInitialized)\r\n\t{\r\n\t\tauto iSel = m_DropDown.GetCurSel();\r\n\r\n\t\tif (CB_ERR != iSel)\r\n\t\t{\r\n\t\t\treturn m_DropDown.GetItemData(iSel);\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn m_iDropSelectionValue;\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n\r\n_Check_return_ int DropDownPane::GetDropDown() const\r\n{\r\n\treturn m_iDropSelection;\r\n}\r\n\r\n_Check_return_ DWORD_PTR DropDownPane::GetDropDownValue() const\r\n{\r\n\treturn m_iDropSelectionValue;\r\n}\r\n\r\n\/\/ This should work whether the editor is active\/displayed or not\r\n_Check_return_ bool DropDownPane::GetSelectedGUID(bool bByteSwapped, _In_ LPGUID lpSelectedGUID) const\r\n{\r\n\tif (!lpSelectedGUID) return NULL;\r\n\r\n\tauto iCurSel = GetDropDownSelection();\r\n\tif (iCurSel != CB_ERR)\r\n\t{\r\n\t\tmemcpy(lpSelectedGUID, PropGuidArray[iCurSel].lpGuid, sizeof(GUID));\r\n\t\treturn true;\r\n\t}\r\n\r\n\t\/\/ no match - need to do a lookup\r\n\twstring szText;\r\n\tif (m_bInitialized)\r\n\t{\r\n\t\tszText = GetDropStringUseControl();\r\n\t}\r\n\r\n\tif (szText.empty())\r\n\t{\r\n\t\tszText = m_lpszSelectionString;\r\n\t}\r\n\r\n\tauto lpGUID = GUIDNameToGUID(szText, bByteSwapped);\r\n\tif (lpGUID)\r\n\t{\r\n\t\tmemcpy(lpSelectedGUID, lpGUID, sizeof(GUID));\r\n\t\tdelete[] lpGUID;\r\n\t\treturn true;\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n\r\nvoid DropDownPane::SetDropDownSelection(_In_ wstring szText)\r\n{\r\n\tauto hRes = S_OK;\r\n\tauto text = wstringToCString(szText);\r\n\tauto iSelect = m_DropDown.SelectString(0, text);\r\n\r\n\t\/\/ if we can't select, try pushing the text in there\r\n\t\/\/ not all dropdowns will support this!\r\n\tif (CB_ERR == iSelect)\r\n\t{\r\n\t\tEC_B(::SendMessage(\r\n\t\t\tm_DropDown.m_hWnd,\r\n\t\t\tWM_SETTEXT,\r\n\t\t\tNULL,\r\n\t\t\treinterpret_cast(static_cast(text))));\r\n\t}\r\n}\r\n\r\nvoid DropDownPane::SetSelection(DWORD_PTR iSelection)\r\n{\r\n\tif (!m_bInitialized)\r\n\t{\r\n\t\tm_iDropSelectionValue = iSelection;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tm_DropDown.SetCurSel(static_cast(iSelection));\r\n\t}\r\n}<|endoftext|>"} {"text":"#include \"stdafx.h\"\r\n#include \"DropDownPane.h\"\r\n#include \"String.h\"\r\n#include \"InterpretProp2.h\"\r\n#include \r\n\r\nstatic wstring CLASS = L\"DropDownPane\";\r\n\r\nDropDownPane* DropDownPane::Create(UINT uidLabel, ULONG ulDropList, _In_opt_count_(ulDropList) UINT* lpuidDropList, bool bReadOnly)\r\n{\r\n\tauto pane = new DropDownPane();\r\n\tif (pane && lpuidDropList)\r\n\t{\r\n\t\tfor (ULONG iDropNum = 0; iDropNum < ulDropList; iDropNum++)\r\n\t\t{\r\n\t\t\tpane->InsertDropString(loadstring(lpuidDropList[iDropNum]), lpuidDropList[iDropNum]);\r\n\t\t}\r\n\r\n\t\tpane->SetLabel(uidLabel, bReadOnly);\r\n\t}\r\n\r\n\treturn pane;\r\n}\r\n\r\nDropDownPane* DropDownPane::CreateGuid(UINT uidLabel, bool bReadOnly)\r\n{\r\n\tauto pane = new DropDownPane();\r\n\tif (pane)\r\n\t{\r\n\t\tfor (ULONG iDropNum = 0; iDropNum < PropGuidArray.size(); iDropNum++)\r\n\t\t{\r\n\t\t\tpane->InsertDropString(GUIDToStringAndName(PropGuidArray[iDropNum].lpGuid), iDropNum);\r\n\t\t}\r\n\r\n\t\tpane->SetLabel(uidLabel, bReadOnly);\r\n\t}\r\n\r\n\treturn pane;\r\n}\r\n\r\nDropDownPane::DropDownPane()\r\n{\r\n\tm_iDropSelection = CB_ERR;\r\n\tm_iDropSelectionValue = 0;\r\n}\r\n\r\nint DropDownPane::GetMinWidth(_In_ HDC hdc)\r\n{\r\n\tauto cxDropDown = 0;\r\n\tfor (auto iDropString = 0; iDropString < m_DropDown.GetCount(); iDropString++)\r\n\t{\r\n\t\tauto szDropString = GetLBText(m_DropDown.m_hWnd, iDropString);\r\n\t\tauto sizeDrop = GetTextExtentPoint32(hdc, szDropString);\r\n\t\tcxDropDown = max(cxDropDown, sizeDrop.cx);\r\n\t}\r\n\r\n\t\/\/ Add scroll bar and margins for our frame\r\n\tcxDropDown += GetSystemMetrics(SM_CXVSCROLL) + 2 * GetSystemMetrics(SM_CXFIXEDFRAME);\r\n\r\n\treturn max(ViewPane::GetMinWidth(hdc), cxDropDown);\r\n}\r\n\r\nint DropDownPane::GetFixedHeight()\r\n{\r\n\tauto iHeight = 0;\r\n\r\n\tif (0 != m_iControl) iHeight += m_iSmallHeightMargin; \/\/ Top margin\r\n\r\n\tif (!m_szLabel.empty())\r\n\t{\r\n\t\tiHeight += m_iLabelHeight;\r\n\t}\r\n\r\n\tiHeight += m_iEditHeight; \/\/ Height of the dropdown\r\n\r\n\tiHeight += m_iLargeHeightMargin; \/\/ Bottom margin\r\n\r\n\treturn iHeight;\r\n}\r\n\r\nvoid DropDownPane::SetWindowPos(int x, int y, int width, int \/*height*\/)\r\n{\r\n\tauto hRes = S_OK;\r\n\tif (0 != m_iControl)\r\n\t{\r\n\t\ty += m_iSmallHeightMargin;\r\n\t}\r\n\r\n\tif (!m_szLabel.empty())\r\n\t{\r\n\t\tEC_B(m_Label.SetWindowPos(\r\n\t\t\tnullptr,\r\n\t\t\tx,\r\n\t\t\ty,\r\n\t\t\twidth,\r\n\t\t\tm_iLabelHeight,\r\n\t\t\tSWP_NOZORDER));\r\n\t\ty += m_iLabelHeight;\r\n\t}\r\n\r\n\t\/\/ Note - Real height of a combo box is fixed at m_iEditHeight\r\n\t\/\/ Height we set here influences the amount of dropdown entries we see\r\n\t\/\/ This will give us something between 4 and 10 entries\r\n\tULONG ulDrops = min(10, 1 + max(m_DropList.size(), 4));\r\n\r\n\tEC_B(m_DropDown.SetWindowPos(NULL, x, y, width, m_iEditHeight * ulDrops, SWP_NOZORDER));\r\n}\r\n\r\nvoid DropDownPane::CreateControl(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)\r\n{\r\n\tauto hRes = S_OK;\r\n\r\n\tViewPane::Initialize(iControl, pParent, hdc);\r\n\r\n\tauto ulDrops = 1 + (m_DropList.size() ? min(m_DropList.size(), 4) : 4);\r\n\tauto dropHeight = ulDrops * (pParent ? GetEditHeight(pParent->m_hWnd) : 0x1e);\r\n\r\n\t\/\/ m_bReadOnly means you can't type...\r\n\tDWORD dwDropStyle;\r\n\tif (m_bReadOnly)\r\n\t{\r\n\t\tdwDropStyle = CBS_DROPDOWNLIST; \/\/ does not allow typing\r\n\t}\r\n\telse\r\n\t{\r\n\t\tdwDropStyle = CBS_DROPDOWN; \/\/ allows typing\r\n\t}\r\n\r\n\tEC_B(m_DropDown.Create(\r\n\t\tWS_TABSTOP\r\n\t\t| WS_CHILD\r\n\t\t| WS_CLIPSIBLINGS\r\n\t\t| WS_BORDER\r\n\t\t| WS_VISIBLE\r\n\t\t| WS_VSCROLL\r\n\t\t| CBS_OWNERDRAWFIXED\r\n\t\t| CBS_HASSTRINGS\r\n\t\t| CBS_AUTOHSCROLL\r\n\t\t| CBS_DISABLENOSCROLL\r\n\t\t| CBS_NOINTEGRALHEIGHT\r\n\t\t| dwDropStyle,\r\n\t\tCRect(0, 0, 0, static_cast(dropHeight)),\r\n\t\tpParent,\r\n\t\tm_nID));\r\n\r\n\tSendMessage(m_DropDown.m_hWnd, WM_SETFONT, reinterpret_cast(GetSegoeFont()), false);\r\n}\r\n\r\nvoid DropDownPane::Initialize(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)\r\n{\r\n\tCreateControl(iControl, pParent, hdc);\r\n\r\n\tauto iDropNum = 0;\r\n\tfor (const auto& drop : m_DropList)\r\n\t{\r\n\t\tm_DropDown.InsertString(iDropNum, wstringTotstring(drop.first).c_str());\r\n\t\tm_DropDown.SetItemData(iDropNum, drop.second);\r\n\t\tiDropNum++;\r\n\t}\r\n\r\n\tm_DropDown.SetCurSel(static_cast(m_iDropSelectionValue));\r\n\r\n\tm_bInitialized = true;\r\n\tSetDropDownSelection(m_lpszSelectionString);\r\n}\r\n\r\nvoid DropDownPane::InsertDropString(_In_ const wstring& szText, ULONG ulValue)\r\n{\r\n\tm_DropList.push_back({ szText, ulValue });\r\n}\r\n\r\nvoid DropDownPane::CommitUIValues()\r\n{\r\n\tm_iDropSelection = GetDropDownSelection();\r\n\tm_iDropSelectionValue = GetDropDownSelectionValue();\r\n\tm_lpszSelectionString = GetDropStringUseControl();\r\n\tm_bInitialized = false; \/\/ must be last\r\n}\r\n\r\n_Check_return_ wstring DropDownPane::GetDropStringUseControl() const\r\n{\r\n\tauto len = m_DropDown.GetWindowTextLength() + 1;\r\n\tauto buffer = new WCHAR[len];\r\n\tmemset(buffer, 0, sizeof(WCHAR)* len);\r\n\tGetWindowTextW(m_DropDown.m_hWnd, buffer, len);\r\n\twstring szOut = buffer;\r\n\tdelete[] buffer;\r\n\treturn szOut;\r\n}\r\n\r\n\/\/ This should work whether the editor is active\/displayed or not\r\n_Check_return_ int DropDownPane::GetDropDownSelection() const\r\n{\r\n\tif (m_bInitialized) return m_DropDown.GetCurSel();\r\n\r\n\t\/\/ In case we're being called after we're done displaying, use the stored value\r\n\treturn m_iDropSelection;\r\n}\r\n\r\n_Check_return_ DWORD_PTR DropDownPane::GetDropDownSelectionValue() const\r\n{\r\n\tif (m_bInitialized)\r\n\t{\r\n\t\tauto iSel = m_DropDown.GetCurSel();\r\n\r\n\t\tif (CB_ERR != iSel)\r\n\t\t{\r\n\t\t\treturn m_DropDown.GetItemData(iSel);\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn m_iDropSelectionValue;\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n\r\n_Check_return_ int DropDownPane::GetDropDown() const\r\n{\r\n\treturn m_iDropSelection;\r\n}\r\n\r\n_Check_return_ DWORD_PTR DropDownPane::GetDropDownValue() const\r\n{\r\n\treturn m_iDropSelectionValue;\r\n}\r\n\r\n\/\/ This should work whether the editor is active\/displayed or not\r\n_Check_return_ GUID DropDownPane::GetSelectedGUID(bool bByteSwapped) const\r\n{\r\n\tauto iCurSel = GetDropDownSelection();\r\n\tif (iCurSel != CB_ERR)\r\n\t{\r\n\t\treturn *PropGuidArray[iCurSel].lpGuid;\r\n\t}\r\n\r\n\t\/\/ no match - need to do a lookup\r\n\twstring szText;\r\n\tif (m_bInitialized)\r\n\t{\r\n\t\tszText = GetDropStringUseControl();\r\n\t}\r\n\r\n\tif (szText.empty())\r\n\t{\r\n\t\tszText = m_lpszSelectionString;\r\n\t}\r\n\r\n\tauto lpGUID = GUIDNameToGUID(szText, bByteSwapped);\r\n\tif (lpGUID)\r\n\t{\r\n\t\tauto guid = *lpGUID;\r\n\t\tdelete[] lpGUID;\r\n\t\treturn guid;\r\n\t}\r\n\r\n\treturn{ 0 };\r\n}\r\n\r\nvoid DropDownPane::SetDropDownSelection(_In_ const wstring& szText)\r\n{\r\n\tm_lpszSelectionString = szText;\r\n\tif (!m_bInitialized) return;\r\n\r\n\tauto hRes = S_OK;\r\n\tauto text = wstringTotstring(m_lpszSelectionString);\r\n\tauto iSelect = m_DropDown.SelectString(0, text.c_str());\r\n\r\n\t\/\/ if we can't select, try pushing the text in there\r\n\t\/\/ not all dropdowns will support this!\r\n\tif (CB_ERR == iSelect)\r\n\t{\r\n\t\tEC_B(::SendMessage(\r\n\t\t\tm_DropDown.m_hWnd,\r\n\t\t\tWM_SETTEXT,\r\n\t\t\tNULL,\r\n\t\t\treinterpret_cast(static_cast(text.c_str()))));\r\n\t}\r\n}\r\n\r\nvoid DropDownPane::SetSelection(DWORD_PTR iSelection)\r\n{\r\n\tif (!m_bInitialized)\r\n\t{\r\n\t\tm_iDropSelectionValue = iSelection;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tm_DropDown.SetCurSel(static_cast(iSelection));\r\n\t}\r\n}Use better type for unicode#include \"stdafx.h\"\r\n#include \"DropDownPane.h\"\r\n#include \"String.h\"\r\n#include \"InterpretProp2.h\"\r\n#include \r\n\r\nstatic wstring CLASS = L\"DropDownPane\";\r\n\r\nDropDownPane* DropDownPane::Create(UINT uidLabel, ULONG ulDropList, _In_opt_count_(ulDropList) UINT* lpuidDropList, bool bReadOnly)\r\n{\r\n\tauto pane = new DropDownPane();\r\n\tif (pane && lpuidDropList)\r\n\t{\r\n\t\tfor (ULONG iDropNum = 0; iDropNum < ulDropList; iDropNum++)\r\n\t\t{\r\n\t\t\tpane->InsertDropString(loadstring(lpuidDropList[iDropNum]), lpuidDropList[iDropNum]);\r\n\t\t}\r\n\r\n\t\tpane->SetLabel(uidLabel, bReadOnly);\r\n\t}\r\n\r\n\treturn pane;\r\n}\r\n\r\nDropDownPane* DropDownPane::CreateGuid(UINT uidLabel, bool bReadOnly)\r\n{\r\n\tauto pane = new DropDownPane();\r\n\tif (pane)\r\n\t{\r\n\t\tfor (ULONG iDropNum = 0; iDropNum < PropGuidArray.size(); iDropNum++)\r\n\t\t{\r\n\t\t\tpane->InsertDropString(GUIDToStringAndName(PropGuidArray[iDropNum].lpGuid), iDropNum);\r\n\t\t}\r\n\r\n\t\tpane->SetLabel(uidLabel, bReadOnly);\r\n\t}\r\n\r\n\treturn pane;\r\n}\r\n\r\nDropDownPane::DropDownPane()\r\n{\r\n\tm_iDropSelection = CB_ERR;\r\n\tm_iDropSelectionValue = 0;\r\n}\r\n\r\nint DropDownPane::GetMinWidth(_In_ HDC hdc)\r\n{\r\n\tauto cxDropDown = 0;\r\n\tfor (auto iDropString = 0; iDropString < m_DropDown.GetCount(); iDropString++)\r\n\t{\r\n\t\tauto szDropString = GetLBText(m_DropDown.m_hWnd, iDropString);\r\n\t\tauto sizeDrop = GetTextExtentPoint32(hdc, szDropString);\r\n\t\tcxDropDown = max(cxDropDown, sizeDrop.cx);\r\n\t}\r\n\r\n\t\/\/ Add scroll bar and margins for our frame\r\n\tcxDropDown += GetSystemMetrics(SM_CXVSCROLL) + 2 * GetSystemMetrics(SM_CXFIXEDFRAME);\r\n\r\n\treturn max(ViewPane::GetMinWidth(hdc), cxDropDown);\r\n}\r\n\r\nint DropDownPane::GetFixedHeight()\r\n{\r\n\tauto iHeight = 0;\r\n\r\n\tif (0 != m_iControl) iHeight += m_iSmallHeightMargin; \/\/ Top margin\r\n\r\n\tif (!m_szLabel.empty())\r\n\t{\r\n\t\tiHeight += m_iLabelHeight;\r\n\t}\r\n\r\n\tiHeight += m_iEditHeight; \/\/ Height of the dropdown\r\n\r\n\tiHeight += m_iLargeHeightMargin; \/\/ Bottom margin\r\n\r\n\treturn iHeight;\r\n}\r\n\r\nvoid DropDownPane::SetWindowPos(int x, int y, int width, int \/*height*\/)\r\n{\r\n\tauto hRes = S_OK;\r\n\tif (0 != m_iControl)\r\n\t{\r\n\t\ty += m_iSmallHeightMargin;\r\n\t}\r\n\r\n\tif (!m_szLabel.empty())\r\n\t{\r\n\t\tEC_B(m_Label.SetWindowPos(\r\n\t\t\tnullptr,\r\n\t\t\tx,\r\n\t\t\ty,\r\n\t\t\twidth,\r\n\t\t\tm_iLabelHeight,\r\n\t\t\tSWP_NOZORDER));\r\n\t\ty += m_iLabelHeight;\r\n\t}\r\n\r\n\t\/\/ Note - Real height of a combo box is fixed at m_iEditHeight\r\n\t\/\/ Height we set here influences the amount of dropdown entries we see\r\n\t\/\/ This will give us something between 4 and 10 entries\r\n\tauto ulDrops = static_cast(min(10, 1 + max(m_DropList.size(), 4)));\r\n\r\n\tEC_B(m_DropDown.SetWindowPos(NULL, x, y, width, m_iEditHeight * ulDrops, SWP_NOZORDER));\r\n}\r\n\r\nvoid DropDownPane::CreateControl(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)\r\n{\r\n\tauto hRes = S_OK;\r\n\r\n\tViewPane::Initialize(iControl, pParent, hdc);\r\n\r\n\tauto ulDrops = 1 + (m_DropList.size() ? min(m_DropList.size(), 4) : 4);\r\n\tauto dropHeight = ulDrops * (pParent ? GetEditHeight(pParent->m_hWnd) : 0x1e);\r\n\r\n\t\/\/ m_bReadOnly means you can't type...\r\n\tDWORD dwDropStyle;\r\n\tif (m_bReadOnly)\r\n\t{\r\n\t\tdwDropStyle = CBS_DROPDOWNLIST; \/\/ does not allow typing\r\n\t}\r\n\telse\r\n\t{\r\n\t\tdwDropStyle = CBS_DROPDOWN; \/\/ allows typing\r\n\t}\r\n\r\n\tEC_B(m_DropDown.Create(\r\n\t\tWS_TABSTOP\r\n\t\t| WS_CHILD\r\n\t\t| WS_CLIPSIBLINGS\r\n\t\t| WS_BORDER\r\n\t\t| WS_VISIBLE\r\n\t\t| WS_VSCROLL\r\n\t\t| CBS_OWNERDRAWFIXED\r\n\t\t| CBS_HASSTRINGS\r\n\t\t| CBS_AUTOHSCROLL\r\n\t\t| CBS_DISABLENOSCROLL\r\n\t\t| CBS_NOINTEGRALHEIGHT\r\n\t\t| dwDropStyle,\r\n\t\tCRect(0, 0, 0, static_cast(dropHeight)),\r\n\t\tpParent,\r\n\t\tm_nID));\r\n\r\n\tSendMessage(m_DropDown.m_hWnd, WM_SETFONT, reinterpret_cast(GetSegoeFont()), false);\r\n}\r\n\r\nvoid DropDownPane::Initialize(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)\r\n{\r\n\tCreateControl(iControl, pParent, hdc);\r\n\r\n\tauto iDropNum = 0;\r\n\tfor (const auto& drop : m_DropList)\r\n\t{\r\n\t\tm_DropDown.InsertString(iDropNum, wstringTotstring(drop.first).c_str());\r\n\t\tm_DropDown.SetItemData(iDropNum, drop.second);\r\n\t\tiDropNum++;\r\n\t}\r\n\r\n\tm_DropDown.SetCurSel(static_cast(m_iDropSelectionValue));\r\n\r\n\tm_bInitialized = true;\r\n\tSetDropDownSelection(m_lpszSelectionString);\r\n}\r\n\r\nvoid DropDownPane::InsertDropString(_In_ const wstring& szText, ULONG ulValue)\r\n{\r\n\tm_DropList.push_back({ szText, ulValue });\r\n}\r\n\r\nvoid DropDownPane::CommitUIValues()\r\n{\r\n\tm_iDropSelection = GetDropDownSelection();\r\n\tm_iDropSelectionValue = GetDropDownSelectionValue();\r\n\tm_lpszSelectionString = GetDropStringUseControl();\r\n\tm_bInitialized = false; \/\/ must be last\r\n}\r\n\r\n_Check_return_ wstring DropDownPane::GetDropStringUseControl() const\r\n{\r\n\tauto len = m_DropDown.GetWindowTextLength() + 1;\r\n\tauto buffer = new WCHAR[len];\r\n\tmemset(buffer, 0, sizeof(WCHAR)* len);\r\n\tGetWindowTextW(m_DropDown.m_hWnd, buffer, len);\r\n\twstring szOut = buffer;\r\n\tdelete[] buffer;\r\n\treturn szOut;\r\n}\r\n\r\n\/\/ This should work whether the editor is active\/displayed or not\r\n_Check_return_ int DropDownPane::GetDropDownSelection() const\r\n{\r\n\tif (m_bInitialized) return m_DropDown.GetCurSel();\r\n\r\n\t\/\/ In case we're being called after we're done displaying, use the stored value\r\n\treturn m_iDropSelection;\r\n}\r\n\r\n_Check_return_ DWORD_PTR DropDownPane::GetDropDownSelectionValue() const\r\n{\r\n\tif (m_bInitialized)\r\n\t{\r\n\t\tauto iSel = m_DropDown.GetCurSel();\r\n\r\n\t\tif (CB_ERR != iSel)\r\n\t\t{\r\n\t\t\treturn m_DropDown.GetItemData(iSel);\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn m_iDropSelectionValue;\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n\r\n_Check_return_ int DropDownPane::GetDropDown() const\r\n{\r\n\treturn m_iDropSelection;\r\n}\r\n\r\n_Check_return_ DWORD_PTR DropDownPane::GetDropDownValue() const\r\n{\r\n\treturn m_iDropSelectionValue;\r\n}\r\n\r\n\/\/ This should work whether the editor is active\/displayed or not\r\n_Check_return_ GUID DropDownPane::GetSelectedGUID(bool bByteSwapped) const\r\n{\r\n\tauto iCurSel = GetDropDownSelection();\r\n\tif (iCurSel != CB_ERR)\r\n\t{\r\n\t\treturn *PropGuidArray[iCurSel].lpGuid;\r\n\t}\r\n\r\n\t\/\/ no match - need to do a lookup\r\n\twstring szText;\r\n\tif (m_bInitialized)\r\n\t{\r\n\t\tszText = GetDropStringUseControl();\r\n\t}\r\n\r\n\tif (szText.empty())\r\n\t{\r\n\t\tszText = m_lpszSelectionString;\r\n\t}\r\n\r\n\tauto lpGUID = GUIDNameToGUID(szText, bByteSwapped);\r\n\tif (lpGUID)\r\n\t{\r\n\t\tauto guid = *lpGUID;\r\n\t\tdelete[] lpGUID;\r\n\t\treturn guid;\r\n\t}\r\n\r\n\treturn{ 0 };\r\n}\r\n\r\nvoid DropDownPane::SetDropDownSelection(_In_ const wstring& szText)\r\n{\r\n\tm_lpszSelectionString = szText;\r\n\tif (!m_bInitialized) return;\r\n\r\n\tauto hRes = S_OK;\r\n\tauto text = wstringTotstring(m_lpszSelectionString);\r\n\tauto iSelect = m_DropDown.SelectString(0, text.c_str());\r\n\r\n\t\/\/ if we can't select, try pushing the text in there\r\n\t\/\/ not all dropdowns will support this!\r\n\tif (CB_ERR == iSelect)\r\n\t{\r\n\t\tEC_B(::SendMessage(\r\n\t\t\tm_DropDown.m_hWnd,\r\n\t\t\tWM_SETTEXT,\r\n\t\t\tNULL,\r\n\t\t\treinterpret_cast(static_cast(text.c_str()))));\r\n\t}\r\n}\r\n\r\nvoid DropDownPane::SetSelection(DWORD_PTR iSelection)\r\n{\r\n\tif (!m_bInitialized)\r\n\t{\r\n\t\tm_iDropSelectionValue = iSelection;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tm_DropDown.SetCurSel(static_cast(iSelection));\r\n\t}\r\n}<|endoftext|>"} {"text":"#include \"stdafx.h\"\r\n#include \"DropDownPane.h\"\r\n#include \"String.h\"\r\n#include \"InterpretProp2.h\"\r\n#include \r\n\r\nstatic wstring CLASS = L\"DropDownPane\";\r\n\r\nDropDownPane* DropDownPane::Create(UINT uidLabel, ULONG ulDropList, _In_opt_count_(ulDropList) UINT* lpuidDropList, bool bReadOnly)\r\n{\r\n\tauto pane = new DropDownPane();\r\n\tif (pane)\r\n\t{\r\n\t\tfor (ULONG iDropNum = 0; iDropNum < ulDropList; iDropNum++)\r\n\t\t{\r\n\t\t\tpane->InsertDropString(loadstring(lpuidDropList[iDropNum]), lpuidDropList[iDropNum]);\r\n\t\t}\r\n\r\n\t\tpane->SetLabel(uidLabel, bReadOnly);\r\n\t}\r\n\r\n\treturn pane;\r\n}\r\n\r\nDropDownPane* DropDownPane::CreateGuid(UINT uidLabel, bool bReadOnly)\r\n{\r\n\tauto pane = new DropDownPane();\r\n\tif (pane)\r\n\t{\r\n\t\tfor (ULONG iDropNum = 0; iDropNum < PropGuidArray.size(); iDropNum++)\r\n\t\t{\r\n\t\t\tpane->InsertDropString(GUIDToStringAndName(PropGuidArray[iDropNum].lpGuid), iDropNum);\r\n\t\t}\r\n\r\n\t\tpane->SetLabel(uidLabel, bReadOnly);\r\n\t}\r\n\r\n\treturn pane;\r\n}\r\n\r\nDropDownPane::DropDownPane()\r\n{\r\n\tm_iDropSelection = CB_ERR;\r\n\tm_iDropSelectionValue = 0;\r\n}\r\n\r\nbool DropDownPane::IsType(__ViewTypes vType)\r\n{\r\n\treturn CTRL_DROPDOWNPANE == vType;\r\n}\r\n\r\nULONG DropDownPane::GetFlags()\r\n{\r\n\tULONG ulFlags = vpNone;\r\n\tif (m_bReadOnly) ulFlags |= vpReadonly;\r\n\treturn ulFlags;\r\n}\r\n\r\nint DropDownPane::GetMinWidth(_In_ HDC hdc)\r\n{\r\n\tauto cxDropDown = 0;\r\n\tfor (auto iDropString = 0; iDropString < m_DropDown.GetCount(); iDropString++)\r\n\t{\r\n\t\tauto szDropString = GetLBText(m_DropDown.m_hWnd, iDropString);\r\n\t\tauto sizeDrop = GetTextExtentPoint32(hdc, szDropString);\r\n\t\tcxDropDown = max(cxDropDown, sizeDrop.cx);\r\n\t}\r\n\r\n\t\/\/ Add scroll bar and margins for our frame\r\n\tcxDropDown += ::GetSystemMetrics(SM_CXVSCROLL) + 2 * GetSystemMetrics(SM_CXFIXEDFRAME);\r\n\r\n\treturn max(ViewPane::GetMinWidth(hdc), cxDropDown);\r\n}\r\n\r\nint DropDownPane::GetFixedHeight()\r\n{\r\n\tauto iHeight = 0;\r\n\r\n\tif (0 != m_iControl) iHeight += m_iSmallHeightMargin; \/\/ Top margin\r\n\r\n\tif (m_bUseLabelControl)\r\n\t{\r\n\t\tiHeight += m_iLabelHeight;\r\n\t}\r\n\r\n\tiHeight += m_iEditHeight; \/\/ Height of the dropdown\r\n\r\n\t\/\/ No bottom margin on the DropDown as it's usually tied to the following control\r\n\treturn iHeight;\r\n}\r\n\r\nint DropDownPane::GetLines()\r\n{\r\n\treturn 0;\r\n}\r\n\r\nvoid DropDownPane::SetWindowPos(int x, int y, int width, int \/*height*\/)\r\n{\r\n\tauto hRes = S_OK;\r\n\tif (0 != m_iControl)\r\n\t{\r\n\t\ty += m_iSmallHeightMargin;\r\n\t\t\/\/ height -= m_iSmallHeightMargin;\r\n\t}\r\n\r\n\tif (m_bUseLabelControl)\r\n\t{\r\n\t\tEC_B(m_Label.SetWindowPos(\r\n\t\t\tnullptr,\r\n\t\t\tx,\r\n\t\t\ty,\r\n\t\t\twidth,\r\n\t\t\tm_iLabelHeight,\r\n\t\t\tSWP_NOZORDER));\r\n\t\ty += m_iLabelHeight;\r\n\t\t\/\/ height -= m_iLabelHeight;\r\n\t}\r\n\r\n\tEC_B(m_DropDown.SetWindowPos(NULL, x, y, width, m_iEditHeight, SWP_NOZORDER));\r\n}\r\n\r\nvoid DropDownPane::CreateControl(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)\r\n{\r\n\tauto hRes = S_OK;\r\n\r\n\tViewPane::Initialize(iControl, pParent, hdc);\r\n\r\n\tauto ulDrops = 1 + (m_DropList.size() ? min(m_DropList.size(), 4) : 4);\r\n\tauto dropHeight = ulDrops * (pParent ? GetEditHeight(pParent->m_hWnd) : 0x1e);\r\n\r\n\t\/\/ m_bReadOnly means you can't type...\r\n\tDWORD dwDropStyle;\r\n\tif (m_bReadOnly)\r\n\t{\r\n\t\tdwDropStyle = CBS_DROPDOWNLIST; \/\/ does not allow typing\r\n\t}\r\n\telse\r\n\t{\r\n\t\tdwDropStyle = CBS_DROPDOWN; \/\/ allows typing\r\n\t}\r\n\r\n\tEC_B(m_DropDown.Create(\r\n\t\tWS_TABSTOP\r\n\t\t| WS_CHILD\r\n\t\t| WS_CLIPSIBLINGS\r\n\t\t| WS_BORDER\r\n\t\t| WS_VISIBLE\r\n\t\t| WS_VSCROLL\r\n\t\t| CBS_OWNERDRAWFIXED\r\n\t\t| CBS_HASSTRINGS\r\n\t\t| CBS_AUTOHSCROLL\r\n\t\t| CBS_DISABLENOSCROLL\r\n\t\t| dwDropStyle,\r\n\t\tCRect(0, 0, 0, dropHeight),\r\n\t\tpParent,\r\n\t\tm_nID));\r\n}\r\n\r\nvoid DropDownPane::Initialize(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)\r\n{\r\n\tCreateControl(iControl, pParent, hdc);\r\n\r\n\tauto iDropNum = 0;\r\n\tfor (auto drop : m_DropList)\r\n\t{\r\n\t\tm_DropDown.InsertString(iDropNum, wstringTotstring(drop.first).c_str());\r\n\t\tm_DropDown.SetItemData(iDropNum, drop.second);\r\n\t\tiDropNum++;\r\n\t}\r\n\r\n\tm_DropDown.SetCurSel(static_cast(m_iDropSelectionValue));\r\n\r\n\tm_bInitialized = true;\r\n}\r\n\r\nvoid DropDownPane::InsertDropString(_In_ const wstring& szText, ULONG ulValue)\r\n{\r\n\tm_DropList.push_back({ szText, ulValue });\r\n}\r\n\r\nvoid DropDownPane::CommitUIValues()\r\n{\r\n\tm_iDropSelection = GetDropDownSelection();\r\n\tm_iDropSelectionValue = GetDropDownSelectionValue();\r\n\tm_lpszSelectionString = GetDropStringUseControl();\r\n\tm_bInitialized = false; \/\/ must be last\r\n}\r\n\r\n_Check_return_ wstring DropDownPane::GetDropStringUseControl() const\r\n{\r\n\tauto len = m_DropDown.GetWindowTextLength() + 1;\r\n\tauto buffer = new WCHAR[len];\r\n\tmemset(buffer, 0, sizeof(WCHAR)* len);\r\n\t::GetWindowTextW(m_DropDown.m_hWnd, buffer, len);\r\n\twstring szOut = buffer;\r\n\tdelete[] buffer;\r\n\treturn szOut;\r\n}\r\n\r\n\/\/ This should work whether the editor is active\/displayed or not\r\n_Check_return_ int DropDownPane::GetDropDownSelection() const\r\n{\r\n\tif (m_bInitialized) return m_DropDown.GetCurSel();\r\n\r\n\t\/\/ In case we're being called after we're done displaying, use the stored value\r\n\treturn m_iDropSelection;\r\n}\r\n\r\n_Check_return_ DWORD_PTR DropDownPane::GetDropDownSelectionValue() const\r\n{\r\n\tif (m_bInitialized)\r\n\t{\r\n\t\tauto iSel = m_DropDown.GetCurSel();\r\n\r\n\t\tif (CB_ERR != iSel)\r\n\t\t{\r\n\t\t\treturn m_DropDown.GetItemData(iSel);\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn m_iDropSelectionValue;\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n\r\n_Check_return_ int DropDownPane::GetDropDown() const\r\n{\r\n\treturn m_iDropSelection;\r\n}\r\n\r\n_Check_return_ DWORD_PTR DropDownPane::GetDropDownValue() const\r\n{\r\n\treturn m_iDropSelectionValue;\r\n}\r\n\r\n\/\/ This should work whether the editor is active\/displayed or not\r\n_Check_return_ GUID DropDownPane::GetSelectedGUID(bool bByteSwapped) const\r\n{\r\n\tauto iCurSel = GetDropDownSelection();\r\n\tif (iCurSel != CB_ERR)\r\n\t{\r\n\t\treturn *PropGuidArray[iCurSel].lpGuid;\r\n\t}\r\n\r\n\t\/\/ no match - need to do a lookup\r\n\twstring szText;\r\n\tif (m_bInitialized)\r\n\t{\r\n\t\tszText = GetDropStringUseControl();\r\n\t}\r\n\r\n\tif (szText.empty())\r\n\t{\r\n\t\tszText = m_lpszSelectionString;\r\n\t}\r\n\r\n\tauto lpGUID = GUIDNameToGUID(szText, bByteSwapped);\r\n\tif (lpGUID)\r\n\t{\r\n\t\tauto guid = *lpGUID;\r\n\t\tdelete[] lpGUID;\r\n\t\treturn guid;\r\n\t}\r\n\r\n\treturn{ 0 };\r\n}\r\n\r\nvoid DropDownPane::SetDropDownSelection(_In_ const wstring& szText)\r\n{\r\n\tauto hRes = S_OK;\r\n\tauto text = wstringTotstring(szText);\r\n\tauto iSelect = m_DropDown.SelectString(0, text.c_str());\r\n\r\n\t\/\/ if we can't select, try pushing the text in there\r\n\t\/\/ not all dropdowns will support this!\r\n\tif (CB_ERR == iSelect)\r\n\t{\r\n\t\tEC_B(::SendMessage(\r\n\t\t\tm_DropDown.m_hWnd,\r\n\t\t\tWM_SETTEXT,\r\n\t\t\tNULL,\r\n\t\t\treinterpret_cast(static_cast(text.c_str()))));\r\n\t}\r\n}\r\n\r\nvoid DropDownPane::SetSelection(DWORD_PTR iSelection)\r\n{\r\n\tif (!m_bInitialized)\r\n\t{\r\n\t\tm_iDropSelectionValue = iSelection;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tm_DropDown.SetCurSel(static_cast(iSelection));\r\n\t}\r\n}Casting issue#include \"stdafx.h\"\r\n#include \"DropDownPane.h\"\r\n#include \"String.h\"\r\n#include \"InterpretProp2.h\"\r\n#include \r\n\r\nstatic wstring CLASS = L\"DropDownPane\";\r\n\r\nDropDownPane* DropDownPane::Create(UINT uidLabel, ULONG ulDropList, _In_opt_count_(ulDropList) UINT* lpuidDropList, bool bReadOnly)\r\n{\r\n\tauto pane = new DropDownPane();\r\n\tif (pane)\r\n\t{\r\n\t\tfor (ULONG iDropNum = 0; iDropNum < ulDropList; iDropNum++)\r\n\t\t{\r\n\t\t\tpane->InsertDropString(loadstring(lpuidDropList[iDropNum]), lpuidDropList[iDropNum]);\r\n\t\t}\r\n\r\n\t\tpane->SetLabel(uidLabel, bReadOnly);\r\n\t}\r\n\r\n\treturn pane;\r\n}\r\n\r\nDropDownPane* DropDownPane::CreateGuid(UINT uidLabel, bool bReadOnly)\r\n{\r\n\tauto pane = new DropDownPane();\r\n\tif (pane)\r\n\t{\r\n\t\tfor (ULONG iDropNum = 0; iDropNum < PropGuidArray.size(); iDropNum++)\r\n\t\t{\r\n\t\t\tpane->InsertDropString(GUIDToStringAndName(PropGuidArray[iDropNum].lpGuid), iDropNum);\r\n\t\t}\r\n\r\n\t\tpane->SetLabel(uidLabel, bReadOnly);\r\n\t}\r\n\r\n\treturn pane;\r\n}\r\n\r\nDropDownPane::DropDownPane()\r\n{\r\n\tm_iDropSelection = CB_ERR;\r\n\tm_iDropSelectionValue = 0;\r\n}\r\n\r\nbool DropDownPane::IsType(__ViewTypes vType)\r\n{\r\n\treturn CTRL_DROPDOWNPANE == vType;\r\n}\r\n\r\nULONG DropDownPane::GetFlags()\r\n{\r\n\tULONG ulFlags = vpNone;\r\n\tif (m_bReadOnly) ulFlags |= vpReadonly;\r\n\treturn ulFlags;\r\n}\r\n\r\nint DropDownPane::GetMinWidth(_In_ HDC hdc)\r\n{\r\n\tauto cxDropDown = 0;\r\n\tfor (auto iDropString = 0; iDropString < m_DropDown.GetCount(); iDropString++)\r\n\t{\r\n\t\tauto szDropString = GetLBText(m_DropDown.m_hWnd, iDropString);\r\n\t\tauto sizeDrop = GetTextExtentPoint32(hdc, szDropString);\r\n\t\tcxDropDown = max(cxDropDown, sizeDrop.cx);\r\n\t}\r\n\r\n\t\/\/ Add scroll bar and margins for our frame\r\n\tcxDropDown += ::GetSystemMetrics(SM_CXVSCROLL) + 2 * GetSystemMetrics(SM_CXFIXEDFRAME);\r\n\r\n\treturn max(ViewPane::GetMinWidth(hdc), cxDropDown);\r\n}\r\n\r\nint DropDownPane::GetFixedHeight()\r\n{\r\n\tauto iHeight = 0;\r\n\r\n\tif (0 != m_iControl) iHeight += m_iSmallHeightMargin; \/\/ Top margin\r\n\r\n\tif (m_bUseLabelControl)\r\n\t{\r\n\t\tiHeight += m_iLabelHeight;\r\n\t}\r\n\r\n\tiHeight += m_iEditHeight; \/\/ Height of the dropdown\r\n\r\n\t\/\/ No bottom margin on the DropDown as it's usually tied to the following control\r\n\treturn iHeight;\r\n}\r\n\r\nint DropDownPane::GetLines()\r\n{\r\n\treturn 0;\r\n}\r\n\r\nvoid DropDownPane::SetWindowPos(int x, int y, int width, int \/*height*\/)\r\n{\r\n\tauto hRes = S_OK;\r\n\tif (0 != m_iControl)\r\n\t{\r\n\t\ty += m_iSmallHeightMargin;\r\n\t\t\/\/ height -= m_iSmallHeightMargin;\r\n\t}\r\n\r\n\tif (m_bUseLabelControl)\r\n\t{\r\n\t\tEC_B(m_Label.SetWindowPos(\r\n\t\t\tnullptr,\r\n\t\t\tx,\r\n\t\t\ty,\r\n\t\t\twidth,\r\n\t\t\tm_iLabelHeight,\r\n\t\t\tSWP_NOZORDER));\r\n\t\ty += m_iLabelHeight;\r\n\t\t\/\/ height -= m_iLabelHeight;\r\n\t}\r\n\r\n\tEC_B(m_DropDown.SetWindowPos(NULL, x, y, width, m_iEditHeight, SWP_NOZORDER));\r\n}\r\n\r\nvoid DropDownPane::CreateControl(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)\r\n{\r\n\tauto hRes = S_OK;\r\n\r\n\tViewPane::Initialize(iControl, pParent, hdc);\r\n\r\n\tauto ulDrops = 1 + (m_DropList.size() ? min(m_DropList.size(), 4) : 4);\r\n\tauto dropHeight = ulDrops * (pParent ? GetEditHeight(pParent->m_hWnd) : 0x1e);\r\n\r\n\t\/\/ m_bReadOnly means you can't type...\r\n\tDWORD dwDropStyle;\r\n\tif (m_bReadOnly)\r\n\t{\r\n\t\tdwDropStyle = CBS_DROPDOWNLIST; \/\/ does not allow typing\r\n\t}\r\n\telse\r\n\t{\r\n\t\tdwDropStyle = CBS_DROPDOWN; \/\/ allows typing\r\n\t}\r\n\r\n\tEC_B(m_DropDown.Create(\r\n\t\tWS_TABSTOP\r\n\t\t| WS_CHILD\r\n\t\t| WS_CLIPSIBLINGS\r\n\t\t| WS_BORDER\r\n\t\t| WS_VISIBLE\r\n\t\t| WS_VSCROLL\r\n\t\t| CBS_OWNERDRAWFIXED\r\n\t\t| CBS_HASSTRINGS\r\n\t\t| CBS_AUTOHSCROLL\r\n\t\t| CBS_DISABLENOSCROLL\r\n\t\t| dwDropStyle,\r\n\t\tCRect(0, 0, 0, static_cast(dropHeight)),\r\n\t\tpParent,\r\n\t\tm_nID));\r\n}\r\n\r\nvoid DropDownPane::Initialize(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)\r\n{\r\n\tCreateControl(iControl, pParent, hdc);\r\n\r\n\tauto iDropNum = 0;\r\n\tfor (auto drop : m_DropList)\r\n\t{\r\n\t\tm_DropDown.InsertString(iDropNum, wstringTotstring(drop.first).c_str());\r\n\t\tm_DropDown.SetItemData(iDropNum, drop.second);\r\n\t\tiDropNum++;\r\n\t}\r\n\r\n\tm_DropDown.SetCurSel(static_cast(m_iDropSelectionValue));\r\n\r\n\tm_bInitialized = true;\r\n}\r\n\r\nvoid DropDownPane::InsertDropString(_In_ const wstring& szText, ULONG ulValue)\r\n{\r\n\tm_DropList.push_back({ szText, ulValue });\r\n}\r\n\r\nvoid DropDownPane::CommitUIValues()\r\n{\r\n\tm_iDropSelection = GetDropDownSelection();\r\n\tm_iDropSelectionValue = GetDropDownSelectionValue();\r\n\tm_lpszSelectionString = GetDropStringUseControl();\r\n\tm_bInitialized = false; \/\/ must be last\r\n}\r\n\r\n_Check_return_ wstring DropDownPane::GetDropStringUseControl() const\r\n{\r\n\tauto len = m_DropDown.GetWindowTextLength() + 1;\r\n\tauto buffer = new WCHAR[len];\r\n\tmemset(buffer, 0, sizeof(WCHAR)* len);\r\n\t::GetWindowTextW(m_DropDown.m_hWnd, buffer, len);\r\n\twstring szOut = buffer;\r\n\tdelete[] buffer;\r\n\treturn szOut;\r\n}\r\n\r\n\/\/ This should work whether the editor is active\/displayed or not\r\n_Check_return_ int DropDownPane::GetDropDownSelection() const\r\n{\r\n\tif (m_bInitialized) return m_DropDown.GetCurSel();\r\n\r\n\t\/\/ In case we're being called after we're done displaying, use the stored value\r\n\treturn m_iDropSelection;\r\n}\r\n\r\n_Check_return_ DWORD_PTR DropDownPane::GetDropDownSelectionValue() const\r\n{\r\n\tif (m_bInitialized)\r\n\t{\r\n\t\tauto iSel = m_DropDown.GetCurSel();\r\n\r\n\t\tif (CB_ERR != iSel)\r\n\t\t{\r\n\t\t\treturn m_DropDown.GetItemData(iSel);\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn m_iDropSelectionValue;\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n\r\n_Check_return_ int DropDownPane::GetDropDown() const\r\n{\r\n\treturn m_iDropSelection;\r\n}\r\n\r\n_Check_return_ DWORD_PTR DropDownPane::GetDropDownValue() const\r\n{\r\n\treturn m_iDropSelectionValue;\r\n}\r\n\r\n\/\/ This should work whether the editor is active\/displayed or not\r\n_Check_return_ GUID DropDownPane::GetSelectedGUID(bool bByteSwapped) const\r\n{\r\n\tauto iCurSel = GetDropDownSelection();\r\n\tif (iCurSel != CB_ERR)\r\n\t{\r\n\t\treturn *PropGuidArray[iCurSel].lpGuid;\r\n\t}\r\n\r\n\t\/\/ no match - need to do a lookup\r\n\twstring szText;\r\n\tif (m_bInitialized)\r\n\t{\r\n\t\tszText = GetDropStringUseControl();\r\n\t}\r\n\r\n\tif (szText.empty())\r\n\t{\r\n\t\tszText = m_lpszSelectionString;\r\n\t}\r\n\r\n\tauto lpGUID = GUIDNameToGUID(szText, bByteSwapped);\r\n\tif (lpGUID)\r\n\t{\r\n\t\tauto guid = *lpGUID;\r\n\t\tdelete[] lpGUID;\r\n\t\treturn guid;\r\n\t}\r\n\r\n\treturn{ 0 };\r\n}\r\n\r\nvoid DropDownPane::SetDropDownSelection(_In_ const wstring& szText)\r\n{\r\n\tauto hRes = S_OK;\r\n\tauto text = wstringTotstring(szText);\r\n\tauto iSelect = m_DropDown.SelectString(0, text.c_str());\r\n\r\n\t\/\/ if we can't select, try pushing the text in there\r\n\t\/\/ not all dropdowns will support this!\r\n\tif (CB_ERR == iSelect)\r\n\t{\r\n\t\tEC_B(::SendMessage(\r\n\t\t\tm_DropDown.m_hWnd,\r\n\t\t\tWM_SETTEXT,\r\n\t\t\tNULL,\r\n\t\t\treinterpret_cast(static_cast(text.c_str()))));\r\n\t}\r\n}\r\n\r\nvoid DropDownPane::SetSelection(DWORD_PTR iSelection)\r\n{\r\n\tif (!m_bInitialized)\r\n\t{\r\n\t\tm_iDropSelectionValue = iSelection;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tm_DropDown.SetCurSel(static_cast(iSelection));\r\n\t}\r\n}<|endoftext|>"} {"text":"\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n#include \n\n#include \n#include \"flatbuffers\/flatbuffers.h\" \/\/ from @flatbuffers\n#include \"tensorflow\/lite\/c\/common.h\"\n#include \"tensorflow\/lite\/delegates\/nnapi\/nnapi_delegate.h\"\n#include \"tensorflow\/lite\/delegates\/nnapi\/nnapi_delegate_kernel.h\"\n#include \"tensorflow\/lite\/delegates\/nnapi\/nnapi_delegate_mock_test.h\"\n#include \"tensorflow\/lite\/experimental\/acceleration\/configuration\/configuration_generated.h\"\n#include \"tensorflow\/lite\/experimental\/acceleration\/configuration\/delegate_registry.h\"\n#include \"tensorflow\/lite\/interpreter.h\"\n#include \"tensorflow\/lite\/kernels\/test_util.h\"\n\n\/\/ Tests for checking that the NNAPI Delegate plugin correctly handles all the\n\/\/ options from the flatbuffer.\n\/\/\n\/\/ Checking done at NNAPI call level, as that is where we have a mockable\n\/\/ layer.\nnamespace tflite {\nnamespace {\n\nusing delegate::nnapi::NnApiMock;\n\nclass SingleAddOpModel : tflite::SingleOpModel {\n public:\n void Build() {\n int input = AddInput({tflite::TensorType_FLOAT32, {1, 2, 2}});\n int constant = AddConstInput({tflite::TensorType_FLOAT32, {1, 2, 2}},\n {1.0f, 1.0f, 1.0f, 1.0f});\n AddOutput({tflite::TensorType_FLOAT32, {}});\n\n SetBuiltinOp(tflite::BuiltinOperator_ADD, tflite::BuiltinOptions_AddOptions,\n tflite::CreateAddOptions(builder_).Union());\n BuildInterpreter({GetShape(input), GetShape(constant)});\n }\n\n tflite::Interpreter* Interpreter() const { return interpreter_.get(); }\n};\n\nclass NNAPIPluginTest : public ::testing::Test {\n protected:\n NNAPIPluginTest() : delegate_(nullptr, [](TfLiteDelegate*) {}) {}\n void SetUp() override {\n nnapi_ = const_cast(NnApiImplementation());\n nnapi_mock_ = absl::make_unique(nnapi_);\n nnapi_->ANeuralNetworksModel_getSupportedOperationsForDevices =\n [](const ANeuralNetworksModel* model,\n const ANeuralNetworksDevice* const* devices, uint32_t numDevices,\n bool* supportedOps) -> int {\n supportedOps[0] = true;\n return 0;\n };\n model_.Build();\n }\n template \n void CheckExecutionPreference() {\n \/\/ Note - this uses a template since the NNAPI functions are C function\n \/\/ pointers rather than lambdas so can't capture variables.\n nnapi_->ANeuralNetworksCompilation_setPreference =\n [](ANeuralNetworksCompilation* compilation, int32_t preference) {\n return preference - output;\n };\n CreateDelegate(CreateNNAPISettings(fbb_, 0, 0, 0, input));\n \/\/ Since delegation succeeds, the model becomes immutable and hence can't\n \/\/ reuse it.\n SingleAddOpModel model;\n model.Build();\n EXPECT_EQ(model.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),\n kTfLiteOk)\n << \" given input: \" << input << \" expected output: \" << output;\n }\n template \n void CheckExecutionPriority() {\n \/\/ Note - this uses a template since the NNAPI functions are C function\n \/\/ pointers rather than lambdas so can't capture variables.\n nnapi_->ANeuralNetworksCompilation_setPriority =\n [](ANeuralNetworksCompilation* compilation, int32_t priority) {\n return priority - output;\n };\n CreateDelegate(CreateNNAPISettings(fbb_, 0, 0, 0,\n NNAPIExecutionPreference_UNDEFINED, 0, 0,\n \/*allow CPU=*\/true, input));\n \/\/ Since delegation succeeds, the model becomes immutable and hence can't\n \/\/ reuse it.\n SingleAddOpModel model;\n model.Build();\n EXPECT_EQ(model.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),\n kTfLiteOk)\n << \" given input: \" << input << \" expected output: \" << output;\n }\n\n void CreateDelegate(flatbuffers::Offset settings) {\n settings_ = flatbuffers::GetTemporaryPointer(\n fbb_, CreateTFLiteSettings(fbb_, tflite::Delegate_NNAPI, settings));\n\n plugin_ = delegates::DelegatePluginRegistry::CreateByName(\"NnapiPlugin\",\n *settings_);\n delegate_ = plugin_->Create();\n }\n\n NnApi* nnapi_;\n std::unique_ptr nnapi_mock_;\n SingleAddOpModel model_;\n flatbuffers::FlatBufferBuilder fbb_;\n const TFLiteSettings* settings_ = nullptr;\n delegates::TfLiteDelegatePtr delegate_;\n std::unique_ptr plugin_;\n};\n\nTEST_F(NNAPIPluginTest, PassesAcceleratorName) {\n \/\/ Fails with non-existent \"foo\".\n CreateDelegate(CreateNNAPISettings(fbb_, fbb_.CreateString(\"foo\")));\n EXPECT_EQ(model_.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),\n kTfLiteDelegateError);\n\n \/\/ Succeeds with \"test-device\" supported by the mock.\n CreateDelegate(CreateNNAPISettings(fbb_, fbb_.CreateString(\"test-device\")));\n EXPECT_EQ(model_.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),\n kTfLiteOk);\n}\n\nTEST_F(NNAPIPluginTest, PassesExecutionPreference) {\n CheckExecutionPreference();\n CheckExecutionPreference();\n CheckExecutionPreference();\n CheckExecutionPreference();\n}\n\nTEST_F(NNAPIPluginTest, PassesExecutionPriority) {\n nnapi_->android_sdk_version =\n tflite::delegate::nnapi::kMinSdkVersionForNNAPI13;\n CheckExecutionPriority();\n CheckExecutionPriority();\n CheckExecutionPriority();\n CheckExecutionPriority();\n}\n\nTEST_F(NNAPIPluginTest, PassesCachingParameters) {\n nnapi_->ANeuralNetworksCompilation_setCaching =\n [](ANeuralNetworksCompilation* compilation, const char* cacheDir,\n const uint8_t* token) -> int {\n if (std::string(cacheDir) != \"d\") return 1;\n \/\/ Token is hashed with other bits, just check that it's not empty.\n if (std::string(reinterpret_cast(token)).empty()) return 2;\n return 0;\n };\n CreateDelegate(CreateNNAPISettings(fbb_, 0, fbb_.CreateString(\"d\"),\n fbb_.CreateString(\"t\")));\n EXPECT_EQ(model_.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),\n kTfLiteOk);\n}\n\nTEST_F(NNAPIPluginTest, PassesFalseNNAPICpuFlag) {\n CreateDelegate(CreateNNAPISettings(fbb_, 0, 0, 0,\n NNAPIExecutionPreference_UNDEFINED, 0, 0,\n \/* allow CPU *\/ false));\n nnapi_->ANeuralNetworksModel_getSupportedOperationsForDevices =\n [](const ANeuralNetworksModel* model,\n const ANeuralNetworksDevice* const* devices, uint32_t numDevices,\n bool* supportedOps) -> int {\n supportedOps[0] = true;\n \/\/ Since no CPU, should only pass one device.\n return numDevices - 1;\n };\n EXPECT_EQ(model_.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),\n kTfLiteOk);\n}\n\nTEST_F(NNAPIPluginTest, PassesTrueNNAPICpuFlag) {\n CreateDelegate(CreateNNAPISettings(fbb_, 0, 0, 0,\n NNAPIExecutionPreference_UNDEFINED, 0, 0,\n \/* allow CPU *\/ true));\n nnapi_->ANeuralNetworksModel_getSupportedOperationsForDevices =\n [](const ANeuralNetworksModel* model,\n const ANeuralNetworksDevice* const* devices, uint32_t numDevices,\n bool* supportedOps) -> int {\n supportedOps[0] = true;\n \/\/ With CPU allowed, should pass two devices.\n return numDevices - 2;\n };\n EXPECT_EQ(model_.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),\n kTfLiteOk);\n}\n\n} \/\/ namespace\n} \/\/ namespace tflite\nSkip applying TfLite default delegates for the nnapi_plugin_test.\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n#include \n\n#include \n#include \"flatbuffers\/flatbuffers.h\" \/\/ from @flatbuffers\n#include \"tensorflow\/lite\/c\/common.h\"\n#include \"tensorflow\/lite\/delegates\/nnapi\/nnapi_delegate.h\"\n#include \"tensorflow\/lite\/delegates\/nnapi\/nnapi_delegate_kernel.h\"\n#include \"tensorflow\/lite\/delegates\/nnapi\/nnapi_delegate_mock_test.h\"\n#include \"tensorflow\/lite\/experimental\/acceleration\/configuration\/configuration_generated.h\"\n#include \"tensorflow\/lite\/experimental\/acceleration\/configuration\/delegate_registry.h\"\n#include \"tensorflow\/lite\/interpreter.h\"\n#include \"tensorflow\/lite\/kernels\/test_util.h\"\n\n\/\/ Tests for checking that the NNAPI Delegate plugin correctly handles all the\n\/\/ options from the flatbuffer.\n\/\/\n\/\/ Checking done at NNAPI call level, as that is where we have a mockable\n\/\/ layer.\nnamespace tflite {\nnamespace {\n\nusing delegate::nnapi::NnApiMock;\n\nclass SingleAddOpModel : tflite::SingleOpModel {\n public:\n void Build() {\n int input = AddInput({tflite::TensorType_FLOAT32, {1, 2, 2}});\n int constant = AddConstInput({tflite::TensorType_FLOAT32, {1, 2, 2}},\n {1.0f, 1.0f, 1.0f, 1.0f});\n AddOutput({tflite::TensorType_FLOAT32, {}});\n\n SetBuiltinOp(tflite::BuiltinOperator_ADD, tflite::BuiltinOptions_AddOptions,\n tflite::CreateAddOptions(builder_).Union());\n \/\/ Set apply_delegate to false to skip applying TfLite default delegates.\n BuildInterpreter({GetShape(input), GetShape(constant)},\n \/*num_threads=*\/-1,\n \/*allow_fp32_relax_to_fp16=*\/false,\n \/*apply_delegate=*\/false,\n \/*allocate_and_delegate=*\/true);\n }\n\n tflite::Interpreter* Interpreter() const { return interpreter_.get(); }\n};\n\nclass NNAPIPluginTest : public ::testing::Test {\n protected:\n NNAPIPluginTest() : delegate_(nullptr, [](TfLiteDelegate*) {}) {}\n void SetUp() override {\n nnapi_ = const_cast(NnApiImplementation());\n nnapi_mock_ = absl::make_unique(nnapi_);\n nnapi_->ANeuralNetworksModel_getSupportedOperationsForDevices =\n [](const ANeuralNetworksModel* model,\n const ANeuralNetworksDevice* const* devices, uint32_t numDevices,\n bool* supportedOps) -> int {\n supportedOps[0] = true;\n return 0;\n };\n model_.Build();\n }\n template \n void CheckExecutionPreference() {\n \/\/ Note - this uses a template since the NNAPI functions are C function\n \/\/ pointers rather than lambdas so can't capture variables.\n nnapi_->ANeuralNetworksCompilation_setPreference =\n [](ANeuralNetworksCompilation* compilation, int32_t preference) {\n return preference - output;\n };\n CreateDelegate(CreateNNAPISettings(fbb_, 0, 0, 0, input));\n \/\/ Since delegation succeeds, the model becomes immutable and hence can't\n \/\/ reuse it.\n SingleAddOpModel model;\n model.Build();\n EXPECT_EQ(model.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),\n kTfLiteOk)\n << \" given input: \" << input << \" expected output: \" << output;\n }\n template \n void CheckExecutionPriority() {\n \/\/ Note - this uses a template since the NNAPI functions are C function\n \/\/ pointers rather than lambdas so can't capture variables.\n nnapi_->ANeuralNetworksCompilation_setPriority =\n [](ANeuralNetworksCompilation* compilation, int32_t priority) {\n return priority - output;\n };\n CreateDelegate(CreateNNAPISettings(fbb_, 0, 0, 0,\n NNAPIExecutionPreference_UNDEFINED, 0, 0,\n \/*allow CPU=*\/true, input));\n \/\/ Since delegation succeeds, the model becomes immutable and hence can't\n \/\/ reuse it.\n SingleAddOpModel model;\n model.Build();\n EXPECT_EQ(model.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),\n kTfLiteOk)\n << \" given input: \" << input << \" expected output: \" << output;\n }\n\n void CreateDelegate(flatbuffers::Offset settings) {\n settings_ = flatbuffers::GetTemporaryPointer(\n fbb_, CreateTFLiteSettings(fbb_, tflite::Delegate_NNAPI, settings));\n\n plugin_ = delegates::DelegatePluginRegistry::CreateByName(\"NnapiPlugin\",\n *settings_);\n delegate_ = plugin_->Create();\n }\n\n NnApi* nnapi_;\n std::unique_ptr nnapi_mock_;\n SingleAddOpModel model_;\n flatbuffers::FlatBufferBuilder fbb_;\n const TFLiteSettings* settings_ = nullptr;\n delegates::TfLiteDelegatePtr delegate_;\n std::unique_ptr plugin_;\n};\n\nTEST_F(NNAPIPluginTest, PassesAcceleratorName) {\n \/\/ Fails with non-existent \"foo\".\n CreateDelegate(CreateNNAPISettings(fbb_, fbb_.CreateString(\"foo\")));\n EXPECT_EQ(model_.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),\n kTfLiteDelegateError);\n\n \/\/ Succeeds with \"test-device\" supported by the mock.\n CreateDelegate(CreateNNAPISettings(fbb_, fbb_.CreateString(\"test-device\")));\n EXPECT_EQ(model_.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),\n kTfLiteOk);\n}\n\nTEST_F(NNAPIPluginTest, PassesExecutionPreference) {\n CheckExecutionPreference();\n CheckExecutionPreference();\n CheckExecutionPreference();\n CheckExecutionPreference();\n}\n\nTEST_F(NNAPIPluginTest, PassesExecutionPriority) {\n nnapi_->android_sdk_version =\n tflite::delegate::nnapi::kMinSdkVersionForNNAPI13;\n CheckExecutionPriority();\n CheckExecutionPriority();\n CheckExecutionPriority();\n CheckExecutionPriority();\n}\n\nTEST_F(NNAPIPluginTest, PassesCachingParameters) {\n nnapi_->ANeuralNetworksCompilation_setCaching =\n [](ANeuralNetworksCompilation* compilation, const char* cacheDir,\n const uint8_t* token) -> int {\n if (std::string(cacheDir) != \"d\") return 1;\n \/\/ Token is hashed with other bits, just check that it's not empty.\n if (std::string(reinterpret_cast(token)).empty()) return 2;\n return 0;\n };\n CreateDelegate(CreateNNAPISettings(fbb_, 0, fbb_.CreateString(\"d\"),\n fbb_.CreateString(\"t\")));\n EXPECT_EQ(model_.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),\n kTfLiteOk);\n}\n\nTEST_F(NNAPIPluginTest, PassesFalseNNAPICpuFlag) {\n CreateDelegate(CreateNNAPISettings(fbb_, 0, 0, 0,\n NNAPIExecutionPreference_UNDEFINED, 0, 0,\n \/* allow CPU *\/ false));\n nnapi_->ANeuralNetworksModel_getSupportedOperationsForDevices =\n [](const ANeuralNetworksModel* model,\n const ANeuralNetworksDevice* const* devices, uint32_t numDevices,\n bool* supportedOps) -> int {\n supportedOps[0] = true;\n \/\/ Since no CPU, should only pass one device.\n return numDevices - 1;\n };\n EXPECT_EQ(model_.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),\n kTfLiteOk);\n}\n\nTEST_F(NNAPIPluginTest, PassesTrueNNAPICpuFlag) {\n CreateDelegate(CreateNNAPISettings(fbb_, 0, 0, 0,\n NNAPIExecutionPreference_UNDEFINED, 0, 0,\n \/* allow CPU *\/ true));\n nnapi_->ANeuralNetworksModel_getSupportedOperationsForDevices =\n [](const ANeuralNetworksModel* model,\n const ANeuralNetworksDevice* const* devices, uint32_t numDevices,\n bool* supportedOps) -> int {\n supportedOps[0] = true;\n \/\/ With CPU allowed, should pass two devices.\n return numDevices - 2;\n };\n EXPECT_EQ(model_.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),\n kTfLiteOk);\n}\n\n} \/\/ namespace\n} \/\/ namespace tflite\n<|endoftext|>"} {"text":"\/*! \\file unitTestCoefficientGenerator.cpp\r\n * This file contains the unit test of the hypersonic local inclination\r\n * analysis.\r\n *\r\n * Path : \/Astrodynamics\/ForceModels\/Aerothermodynamics\/\r\n * Version : 1\r\n * Check status : Checked\r\n *\r\n * Author : Dominic Dirkx\r\n * Affiliation : Delft University of Technology\r\n * E-mail address : D.Dirkx@student.tudelft.nl\r\n *\r\n * Checker : Bart Romgens\r\n * Affiliation : Delft University of Technology\r\n * E-mail address : B.Romgens@student.tudelft.nl\r\n *\r\n * Date created : 25 November, 2010\r\n * Last modified : 9 February, 2011\r\n *\r\n * References\r\n * Gentry, A., Smyth, D., and Oliver, W. . The Mark IV Supersonic-Hypersonic\r\n * Arbitrary Body Program, Volume II - Program Formulation, Douglas Aircraft\r\n * Aircraft Company, 1973.\r\n *\r\n * Notes\r\n *\r\n * Copyright (c) 2010 Delft University of Technology.\r\n *\r\n * This software is protected by national and international copyright.\r\n * Any unauthorized use, reproduction or modification is unlawful and\r\n * will be prosecuted. Commercial and non-private application of the\r\n * software in any form is strictly prohibited unless otherwise granted\r\n * by the authors.\r\n *\r\n * The code is provided without any warranty; without even the implied\r\n * warranty of merchantibility or fitness for a particular purpose.\r\n *\r\n * Changelog\r\n * YYMMDD Author Comment\r\n * 102511 D. Dirkx First version of file.\r\n *\/\r\n\r\n\/\/ Include statements.\r\n#include \"unitTestCoefficientGenerator.h\"\r\n#include \"writingOutputToFile.h\"\r\n\r\nbool unit_tests::testCoefficientGenerator( )\r\n{\r\n\r\n \/\/ Declare test variable.\r\n bool isCoefficientGeneratorBad_ = 0;\r\n\r\n \/\/ Create test sphere.\r\n SphereSegment sphere = SphereSegment( );\r\n sphere.setRadius( 1.0 );\r\n sphere.setMinimumAzimuthAngle( 0.0 );\r\n sphere.setMaximumAzimuthAngle( 2.0 * M_PI);\r\n sphere.setMinimumZenithAngle( 0.0 );\r\n sphere.setMaximumZenithAngle( M_PI );\r\n VehicleExternalModel externalModel = VehicleExternalModel();\r\n externalModel.setVehicleGeometry( sphere );\r\n Vehicle vehicle = Vehicle();\r\n vehicle.setExternalModel( externalModel );\r\n\r\n \/\/ Create analysis object.\r\n HypersonicLocalInclinationAnalysis analysis =\r\n HypersonicLocalInclinationAnalysis( );\r\n\r\n \/\/ Set vehicle in analysis with 10,000 panels.\r\n int* numberOfLines = new int[ 1 ];\r\n int* numberOfPoints = new int[ 1 ];\r\n bool* invertOrder = new bool[ 1 ];\r\n numberOfLines[ 0 ] = 101;\r\n numberOfPoints[ 0 ] = 101;\r\n invertOrder[ 0 ] = 0;\r\n analysis.setVehicle( vehicle, numberOfLines, numberOfPoints, invertOrder );\r\n\r\n \/\/ Set reference quantities.\r\n analysis.setReferenceArea( M_PI );\r\n analysis.setReferenceLength( 1.0 );\r\n analysis.setMomentReferencePoint( Vector3d( 0, 0, 0) );\r\n\r\n \/\/ Set pure Newtonian compression method for test purposes.\r\n analysis.setSelectedMethod( 0, 0, 0 );\r\n\r\n \/\/ Generate sphere database.\r\n analysis.generateDatabase( );\r\n\r\n \/\/ Allocate memory for independent variables\r\n \/\/ to pass to analysis for retrieval.\r\n int* independentVariables = new int[ 3 ];\r\n independentVariables[ 0 ] = 0;\r\n independentVariables[ 1 ] = 0;\r\n independentVariables[ 2 ] = 0;\r\n\r\n \/\/ Declare local test variables.\r\n VectorXd aerodynamicCoefficients_;\r\n double forceCoefficient_;\r\n\r\n \/\/ Iterate over all angles of attack to verify sphere coefficients.\r\n for( int i = 0; i < analysis.getNumberOfMachPoints(); i++ )\r\n {\r\n independentVariables[ 0 ] = i;\r\n\r\n for( int j = 0; j < analysis.getNumberOfAngleOfAttackPoints( ); j++ )\r\n {\r\n independentVariables[ 1 ] = j;\r\n\r\n for( int k = 0; k < analysis.getNumberOfAngleOfSideslipPoints( ); k++ )\r\n {\r\n independentVariables[ 2 ] = k;\r\n\r\n \/\/ Retrieve aerodynamic coefficients.\r\n aerodynamicCoefficients_ = analysis.getAerodynamicCoefficients(\r\n independentVariables );\r\n forceCoefficient_ = sqrt( aerodynamicCoefficients_.x( )\r\n * aerodynamicCoefficients_.x( )\r\n + aerodynamicCoefficients_.y( )\r\n * aerodynamicCoefficients_.y( )\r\n + aerodynamicCoefficients_.z( )\r\n * aerodynamicCoefficients_.z( ) );\r\n\r\n \/\/ Check if 'total' aerodynamic coefficient is always\r\n \/\/ sufficiently close to zero.\r\n if( fabs( forceCoefficient_ - 1.0 ) > 1.0E-3 )\r\n {\r\n std::cout<<\"Total magnitude of aerodynamic force wrong in \"\r\n <<\"sphere.\"< 1.0E-5 )\r\n {\r\n std::cerr<<\" Error, sphere roll moment coefficient not zero. \"\r\n < 1.0E-3 )\r\n {\r\n std::cerr<<\" Error, sphere pitch moment coefficient not zero. \"\r\n < 1.0E-5 )\r\n {\r\n std::cerr<<\" Error, sphere yaw moment coefficient not zero. \"\r\n <( i - 6 )\r\n * 5.0 * M_PI \/ 180.0 );\r\n }\r\n\r\n \/\/ Generate database.\r\n analysis2.generateDatabase( );\r\n\r\n \/\/ Retrieve coefficients at zero angle of attack for comparison.\r\n independentVariables[ 0 ] = analysis2.getNumberOfMachPoints( ) - 1;\r\n independentVariables[ 1 ] = analysis2.getNumberOfMachPoints( ) - 1;\r\n independentVariables[ 2 ] = 0;\r\n aerodynamicCoefficients_ = analysis2.getAerodynamicCoefficients( independentVariables );\r\n\r\n \/\/ Compare values to database values.\r\n if( fabs( aerodynamicCoefficients_[ 0 ] - 1.51 ) > 0.1 )\r\n {\r\n std::cerr<<\" Error in Apollo drag coefficient \"< 1.0E-15 )\r\n {\r\n std::cerr<<\" Error in Apollo side force coefficient \"< 1.0E-15 )\r\n {\r\n std::cerr<<\" Error in Apollo normal force coefficient \"< 1.0E-15 )\r\n {\r\n std::cerr<<\" Error in Apollo roll moment coefficient \"< 0.01 )\r\n {\r\n std::cerr<<\" Error in Apollo pitch moment coefficient \"< 1.0E-15 )\r\n {\r\n std::cerr<<\" Error in Apollo yaw moment coefficient \"<Commit of update to unit test of aerodynamics coefficient generator.\/*! \\file unitTestCoefficientGenerator.cpp\r\n * This file contains the unit test of the hypersonic local inclination\r\n * analysis.\r\n *\r\n * Path : \/Astrodynamics\/ForceModels\/Aerothermodynamics\/\r\n * Version : 1\r\n * Check status : Checked\r\n *\r\n * Author : Dominic Dirkx\r\n * Affiliation : Delft University of Technology\r\n * E-mail address : D.Dirkx@student.tudelft.nl\r\n *\r\n * Checker : Bart Romgens\r\n * Affiliation : Delft University of Technology\r\n * E-mail address : B.Romgens@student.tudelft.nl\r\n *\r\n * Date created : 25 November, 2010\r\n * Last modified : 9 February, 2011\r\n *\r\n * References\r\n * Gentry, A., Smyth, D., and Oliver, W. . The Mark IV Supersonic-Hypersonic\r\n * Arbitrary Body Program, Volume II - Program Formulation, Douglas Aircraft\r\n * Aircraft Company, 1973.\r\n *\r\n * Notes\r\n *\r\n * Copyright (c) 2010 Delft University of Technology.\r\n *\r\n * This software is protected by national and international copyright.\r\n * Any unauthorized use, reproduction or modification is unlawful and\r\n * will be prosecuted. Commercial and non-private application of the\r\n * software in any form is strictly prohibited unless otherwise granted\r\n * by the authors.\r\n *\r\n * The code is provided without any warranty; without even the implied\r\n * warranty of merchantibility or fitness for a particular purpose.\r\n *\r\n * Changelog\r\n * YYMMDD Author Comment\r\n * 102511 D. Dirkx First version of file.\r\n *\/\r\n\r\n\/\/ Include statements.\r\n#include \"unitTestCoefficientGenerator.h\"\r\n#include \"writingOutputToFile.h\"\r\n\r\nbool unit_tests::testCoefficientGenerator( )\r\n{\r\n\r\n \/\/ Declare test variable.\r\n bool isCoefficientGeneratorBad_ = 0;\r\n\r\n \/\/ Create test sphere.\r\n SphereSegment sphere = SphereSegment( );\r\n sphere.setRadius( 1.0 );\r\n sphere.setMinimumAzimuthAngle( 0.0 );\r\n sphere.setMaximumAzimuthAngle( 2.0 * M_PI);\r\n sphere.setMinimumZenithAngle( 0.0 );\r\n sphere.setMaximumZenithAngle( M_PI );\r\n VehicleExternalModel externalModel = VehicleExternalModel();\r\n externalModel.setVehicleGeometry( sphere );\r\n Vehicle vehicle = Vehicle();\r\n vehicle.setExternalModel( externalModel );\r\n\r\n \/\/ Create analysis object.\r\n HypersonicLocalInclinationAnalysis analysis =\r\n HypersonicLocalInclinationAnalysis( );\r\n\r\n \/\/ Set vehicle in analysis with 10,000 panels.\r\n int* numberOfLines = new int[ 1 ];\r\n int* numberOfPoints = new int[ 1 ];\r\n bool* invertOrder = new bool[ 1 ];\r\n numberOfLines[ 0 ] = 31;\r\n numberOfPoints[ 0 ] = 31;\r\n invertOrder[ 0 ] = 0;\r\n analysis.setVehicle( vehicle, numberOfLines, numberOfPoints, invertOrder );\r\n\r\n \/\/ Set reference quantities.\r\n analysis.setReferenceArea( M_PI );\r\n analysis.setReferenceLength( 1.0 );\r\n analysis.setMomentReferencePoint( Vector3d( 0, 0, 0) );\r\n\r\n \/\/ Set pure Newtonian compression method for test purposes.\r\n analysis.setSelectedMethod( 0, 0, 0 );\r\n\r\n \/\/ Generate sphere database.\r\n analysis.generateDatabase( );\r\n\r\n \/\/ Allocate memory for independent variables\r\n \/\/ to pass to analysis for retrieval.\r\n int* independentVariables = new int[ 3 ];\r\n independentVariables[ 0 ] = 0;\r\n independentVariables[ 1 ] = 0;\r\n independentVariables[ 2 ] = 0;\r\n\r\n \/\/ Declare local test variables.\r\n VectorXd aerodynamicCoefficients_;\r\n double forceCoefficient_;\r\n\r\n \/\/ Iterate over all angles of attack to verify sphere coefficients.\r\n for( int i = 0; i < analysis.getNumberOfMachPoints(); i++ )\r\n {\r\n independentVariables[ 0 ] = i;\r\n\r\n for( int j = 0; j < analysis.getNumberOfAngleOfAttackPoints( ); j++ )\r\n {\r\n independentVariables[ 1 ] = j;\r\n\r\n for( int k = 0; k < analysis.getNumberOfAngleOfSideslipPoints( ); k++ )\r\n {\r\n independentVariables[ 2 ] = k;\r\n\r\n \/\/ Retrieve aerodynamic coefficients.\r\n aerodynamicCoefficients_ = analysis.getAerodynamicCoefficients(\r\n independentVariables );\r\n forceCoefficient_ = sqrt( aerodynamicCoefficients_.x( )\r\n * aerodynamicCoefficients_.x( )\r\n + aerodynamicCoefficients_.y( )\r\n * aerodynamicCoefficients_.y( )\r\n + aerodynamicCoefficients_.z( )\r\n * aerodynamicCoefficients_.z( ) );\r\n\r\n \/\/ Check if 'total' aerodynamic coefficient is always\r\n \/\/ sufficiently close to zero.\r\n if( fabs( forceCoefficient_ - 1.0 ) > 1.0E-2 )\r\n {\r\n std::cout<<\"Total magnitude of aerodynamic force wrong in \"\r\n <<\"sphere.\"< 1.0E-4 )\r\n {\r\n std::cerr<<\" Error, sphere roll moment coefficient not zero. \"\r\n < 1.0E-2 )\r\n {\r\n std::cerr<<\" Error, sphere pitch moment coefficient not zero. \"\r\n < 1.0E-2 )\r\n {\r\n std::cerr<<\" Error, sphere yaw moment coefficient not zero. \"\r\n <( i - 6 )\r\n * 5.0 * M_PI \/ 180.0 );\r\n }\r\n\r\n \/\/ Generate database.\r\n analysis2.generateDatabase( );\r\n\r\n \/\/ Retrieve coefficients at zero angle of attack for comparison.\r\n independentVariables[ 0 ] = analysis2.getNumberOfMachPoints( ) - 1;\r\n independentVariables[ 1 ] = analysis2.getNumberOfMachPoints( ) - 1;\r\n independentVariables[ 2 ] = 0;\r\n aerodynamicCoefficients_ = analysis2.getAerodynamicCoefficients( independentVariables );\r\n\r\n \/\/ Compare values to database values.\r\n if( fabs( aerodynamicCoefficients_[ 0 ] - 1.51 ) > 0.1 )\r\n {\r\n std::cerr<<\" Error in Apollo drag coefficient \"< 1.0E-15 )\r\n {\r\n std::cerr<<\" Error in Apollo side force coefficient \"< 1.0E-15 )\r\n {\r\n std::cerr<<\" Error in Apollo normal force coefficient \"< 1.0E-15 )\r\n {\r\n std::cerr<<\" Error in Apollo roll moment coefficient \"< 0.01 )\r\n {\r\n std::cerr<<\" Error in Apollo pitch moment coefficient \"< 1.0E-15 )\r\n {\r\n std::cerr<<\" Error in Apollo yaw moment coefficient \"<"} {"text":"\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \"mitkCommandLineParser.h\"\n#include \n#include \n#include \n#include \n\n\nmitk::FiberBundle::Pointer LoadFib(std::string filename)\n{\n std::vector fibInfile = mitk::IOUtil::Load(filename);\n if( fibInfile.empty() )\n std::cout << \"File \" << filename << \" could not be read!\";\n mitk::BaseData::Pointer baseData = fibInfile.at(0);\n return dynamic_cast(baseData.GetPointer());\n}\n\n\/*!\n\\brief Modify input tractogram: fiber resampling, compression, pruning and transformation.\n*\/\nint main(int argc, char* argv[])\n{\n mitkCommandLineParser parser;\n\n parser.setTitle(\"Fiber Processing\");\n parser.setCategory(\"Fiber Tracking and Processing Methods\");\n parser.setDescription(\"Modify input tractogram: fiber resampling, compression, pruning and transformation.\");\n parser.setContributor(\"MIC\");\n\n parser.setArgumentPrefix(\"--\", \"-\");\n\n parser.beginGroup(\"1. Mandatory arguments:\");\n parser.addArgument(\"\", \"i\", mitkCommandLineParser::String, \"Input:\", \"Input fiber bundle (.fib, .trk, .tck)\", us::Any(), false, false, false, mitkCommandLineParser::Input);\n parser.addArgument(\"\", \"o\", mitkCommandLineParser::String, \"Output:\", \"Output fiber bundle (.fib, .trk)\", us::Any(), false, false, false, mitkCommandLineParser::Output);\n parser.endGroup();\n\n parser.beginGroup(\"2. Resampling:\");\n parser.addArgument(\"spline_resampling\", \"\", mitkCommandLineParser::Float, \"Spline resampling:\", \"Resample fiber using splines with the given point distance (in mm)\");\n parser.addArgument(\"linear_resampling\", \"\", mitkCommandLineParser::Float, \"Linear resampling:\", \"Resample fiber linearly with the given point distance (in mm)\");\n parser.addArgument(\"num_resampling\", \"\", mitkCommandLineParser::Int, \"Num. fiber points resampling:\", \"Resample all fibers to the given number of points\");\n parser.addArgument(\"compress\", \"\", mitkCommandLineParser::Float, \"Compress:\", \"Compress fiber using the given error threshold (in mm)\");\n parser.endGroup();\n\n parser.beginGroup(\"3. Filtering:\");\n parser.addArgument(\"min_length\", \"\", mitkCommandLineParser::Float, \"Minimum length:\", \"Minimum fiber length (in mm)\");\n parser.addArgument(\"max_length\", \"\", mitkCommandLineParser::Float, \"Maximum length:\", \"Maximum fiber length (in mm)\");\n parser.addArgument(\"max_angle\", \"\", mitkCommandLineParser::Float, \"Maximum angle:\", \"Maximum angular STDEV (in degree) over given distance\");\n parser.addArgument(\"max_angle_dist\", \"\", mitkCommandLineParser::Float, \"Distance:\", \"Distance in mm\", 10);\n parser.addArgument(\"remove\", \"\", mitkCommandLineParser::Bool, \"Remove fibers exceeding curvature threshold:\", \"If false, only the high curvature parts are removed\");\n parser.addArgument(\"subsample\", \"\", mitkCommandLineParser::Float, \"Randomly select fraction of streamlines:\", \"Randomly select the specified fraction of streamlines from the input tractogram\");\n parser.addArgument(\"random_subsample\", \"\", mitkCommandLineParser::Bool, \"Randomly seed subsampling:\", \"Randomly seed subsampling. Else, use seed 0.\");\n parser.endGroup();\n\n parser.beginGroup(\"4. Transformation:\");\n parser.addArgument(\"mirror\", \"\", mitkCommandLineParser::Int, \"Invert coordinates:\", \"Invert fiber coordinates XYZ (e.g. 010 to invert y-coordinate of each fiber point)\");\n\n parser.addArgument(\"rotate_x\", \"\", mitkCommandLineParser::Float, \"Rotate x-axis:\", \"Rotate around x-axis (in deg)\");\n parser.addArgument(\"rotate_y\", \"\", mitkCommandLineParser::Float, \"Rotate y-axis:\", \"Rotate around y-axis (in deg)\");\n parser.addArgument(\"rotate_z\", \"\", mitkCommandLineParser::Float, \"Rotate z-axis:\", \"Rotate around z-axis (in deg)\");\n\n parser.addArgument(\"scale_x\", \"\", mitkCommandLineParser::Float, \"Scale x-axis:\", \"Scale in direction of x-axis\");\n parser.addArgument(\"scale_y\", \"\", mitkCommandLineParser::Float, \"Scale y-axis:\", \"Scale in direction of y-axis\");\n parser.addArgument(\"scale_z\", \"\", mitkCommandLineParser::Float, \"Scale z-axis\", \"Scale in direction of z-axis\");\n\n parser.addArgument(\"translate_x\", \"\", mitkCommandLineParser::Float, \"Translate x-axis:\", \"Translate in direction of x-axis (in mm)\");\n parser.addArgument(\"translate_y\", \"\", mitkCommandLineParser::Float, \"Translate y-axis:\", \"Translate in direction of y-axis (in mm)\");\n parser.addArgument(\"translate_z\", \"\", mitkCommandLineParser::Float, \"Translate z-axis:\", \"Translate in direction of z-axis (in mm)\");\n parser.endGroup();\n\n\n std::map parsedArgs = parser.parseArguments(argc, argv);\n if (parsedArgs.size()==0)\n return EXIT_FAILURE;\n\n bool remove = false;\n if (parsedArgs.count(\"remove\"))\n remove = us::any_cast(parsedArgs[\"remove\"]);\n\n bool random_subsample = false;\n if (parsedArgs.count(\"random_subsample\"))\n random_subsample = us::any_cast(parsedArgs[\"random_subsample\"]);\n\n float spline_resampling = -1;\n if (parsedArgs.count(\"spline_resampling\"))\n spline_resampling = us::any_cast(parsedArgs[\"spline_resampling\"]);\n\n float linear_resampling = -1;\n if (parsedArgs.count(\"linear_resampling\"))\n linear_resampling = us::any_cast(parsedArgs[\"linear_resampling\"]);\n\n int num_resampling = -1;\n if (parsedArgs.count(\"num_resampling\"))\n num_resampling = us::any_cast(parsedArgs[\"num_resampling\"]);\n\n float subsample = -1;\n if (parsedArgs.count(\"subsample\"))\n subsample = us::any_cast(parsedArgs[\"subsample\"]);\n\n float compress = -1;\n if (parsedArgs.count(\"compress\"))\n compress = us::any_cast(parsedArgs[\"compress\"]);\n\n float minFiberLength = -1;\n if (parsedArgs.count(\"min_length\"))\n minFiberLength = us::any_cast(parsedArgs[\"min_length\"]);\n\n float maxFiberLength = -1;\n if (parsedArgs.count(\"max_length\"))\n maxFiberLength = us::any_cast(parsedArgs[\"max_length\"]);\n\n float max_angle_dist = 10;\n if (parsedArgs.count(\"max_angle_dist\"))\n max_angle_dist = us::any_cast(parsedArgs[\"max_angle_dist\"]);\n\n float maxAngularDev = -1;\n if (parsedArgs.count(\"max_angle\"))\n maxAngularDev = us::any_cast(parsedArgs[\"max_angle\"]);\n\n int axis = 0;\n if (parsedArgs.count(\"mirror\"))\n axis = us::any_cast(parsedArgs[\"mirror\"]);\n\n float rotateX = 0;\n if (parsedArgs.count(\"rotate_x\"))\n rotateX = us::any_cast(parsedArgs[\"rotate_x\"]);\n\n float rotateY = 0;\n if (parsedArgs.count(\"rotate_y\"))\n rotateY = us::any_cast(parsedArgs[\"rotate_y\"]);\n\n float rotateZ = 0;\n if (parsedArgs.count(\"rotate_z\"))\n rotateZ = us::any_cast(parsedArgs[\"rotate_z\"]);\n\n float scaleX = 0;\n if (parsedArgs.count(\"scale_x\"))\n scaleX = us::any_cast(parsedArgs[\"scale_x\"]);\n\n float scaleY = 0;\n if (parsedArgs.count(\"scale_y\"))\n scaleY = us::any_cast(parsedArgs[\"scale_y\"]);\n\n float scaleZ = 0;\n if (parsedArgs.count(\"scale_z\"))\n scaleZ = us::any_cast(parsedArgs[\"scale_z\"]);\n\n float translateX = 0;\n if (parsedArgs.count(\"translate_x\"))\n translateX = us::any_cast(parsedArgs[\"translate_x\"]);\n\n float translateY = 0;\n if (parsedArgs.count(\"translate_y\"))\n translateY = us::any_cast(parsedArgs[\"translate_y\"]);\n\n float translateZ = 0;\n if (parsedArgs.count(\"translate_z\"))\n translateZ = us::any_cast(parsedArgs[\"translate_z\"]);\n\n\n std::string inFileName = us::any_cast(parsedArgs[\"i\"]);\n std::string outFileName = us::any_cast(parsedArgs[\"o\"]);\n\n try\n {\n mitk::FiberBundle::Pointer fib = LoadFib(inFileName);\n\n if (subsample>0)\n fib = fib->SubsampleFibers(subsample, random_subsample);\n\n if (maxAngularDev>0)\n {\n auto filter = itk::FiberCurvatureFilter::New();\n filter->SetInputFiberBundle(fib);\n filter->SetAngularDeviation(maxAngularDev);\n filter->SetDistance(max_angle_dist);\n filter->SetRemoveFibers(remove);\n filter->Update();\n fib = filter->GetOutputFiberBundle();\n }\n\n if (minFiberLength>0)\n fib->RemoveShortFibers(minFiberLength);\n\n if (maxFiberLength>0)\n fib->RemoveLongFibers(maxFiberLength);\n\n if (spline_resampling>0)\n fib->ResampleSpline(spline_resampling);\n\n if (linear_resampling>0)\n fib->ResampleLinear(linear_resampling);\n\n if (num_resampling>0)\n fib->ResampleToNumPoints(num_resampling);\n\n if (compress>0)\n fib->Compress(compress);\n\n if (axis\/100==1)\n fib->MirrorFibers(0);\n\n if ((axis%100)\/10==1)\n fib->MirrorFibers(1);\n\n if (axis%10==1)\n fib->MirrorFibers(2);\n\n\n if (rotateX > 0 || rotateY > 0 || rotateZ > 0){\n std::cout << \"Rotate \" << rotateX << \" \" << rotateY << \" \" << rotateZ;\n fib->RotateAroundAxis(rotateX, rotateY, rotateZ);\n }\n if (translateX > 0 || translateY > 0 || translateZ > 0){\n fib->TranslateFibers(translateX, translateY, translateZ);\n }\n if (scaleX > 0 || scaleY > 0 || scaleZ > 0)\n fib->ScaleFibers(scaleX, scaleY, scaleZ);\n\n mitk::IOUtil::Save(fib.GetPointer(), outFileName );\n\n }\n catch (itk::ExceptionObject e)\n {\n std::cout << e;\n return EXIT_FAILURE;\n }\n catch (std::exception e)\n {\n std::cout << e.what();\n return EXIT_FAILURE;\n }\n catch (...)\n {\n std::cout << \"ERROR!?!\";\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\nFiber cutting\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \"mitkCommandLineParser.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\n\nmitk::FiberBundle::Pointer LoadFib(std::string filename)\n{\n std::vector fibInfile = mitk::IOUtil::Load(filename);\n if( fibInfile.empty() )\n std::cout << \"File \" << filename << \" could not be read!\";\n mitk::BaseData::Pointer baseData = fibInfile.at(0);\n return dynamic_cast(baseData.GetPointer());\n}\n\n\/*!\n\\brief Modify input tractogram: fiber resampling, compression, pruning and transformation.\n*\/\nint main(int argc, char* argv[])\n{\n mitkCommandLineParser parser;\n\n parser.setTitle(\"Fiber Processing\");\n parser.setCategory(\"Fiber Tracking and Processing Methods\");\n parser.setDescription(\"Modify input tractogram: fiber resampling, compression, pruning and transformation.\");\n parser.setContributor(\"MIC\");\n\n parser.setArgumentPrefix(\"--\", \"-\");\n\n parser.beginGroup(\"1. Mandatory arguments:\");\n parser.addArgument(\"\", \"i\", mitkCommandLineParser::String, \"Input:\", \"Input fiber bundle (.fib, .trk, .tck)\", us::Any(), false, false, false, mitkCommandLineParser::Input);\n parser.addArgument(\"\", \"o\", mitkCommandLineParser::String, \"Output:\", \"Output fiber bundle (.fib, .trk)\", us::Any(), false, false, false, mitkCommandLineParser::Output);\n parser.endGroup();\n\n parser.beginGroup(\"2. Resampling:\");\n parser.addArgument(\"spline_resampling\", \"\", mitkCommandLineParser::Float, \"Spline resampling:\", \"Resample fiber using splines with the given point distance (in mm)\");\n parser.addArgument(\"linear_resampling\", \"\", mitkCommandLineParser::Float, \"Linear resampling:\", \"Resample fiber linearly with the given point distance (in mm)\");\n parser.addArgument(\"num_resampling\", \"\", mitkCommandLineParser::Int, \"Num. fiber points resampling:\", \"Resample all fibers to the given number of points\");\n parser.addArgument(\"compress\", \"\", mitkCommandLineParser::Float, \"Compress:\", \"Compress fiber using the given error threshold (in mm)\");\n parser.endGroup();\n\n parser.beginGroup(\"3. Filtering:\");\n parser.addArgument(\"min_length\", \"\", mitkCommandLineParser::Float, \"Minimum length:\", \"Minimum fiber length (in mm)\");\n parser.addArgument(\"max_length\", \"\", mitkCommandLineParser::Float, \"Maximum length:\", \"Maximum fiber length (in mm)\");\n parser.addArgument(\"max_angle\", \"\", mitkCommandLineParser::Float, \"Maximum angle:\", \"Maximum angular STDEV (in degree) over given distance\");\n parser.addArgument(\"max_angle_dist\", \"\", mitkCommandLineParser::Float, \"Distance:\", \"Distance in mm\", 10);\n parser.addArgument(\"remove\", \"\", mitkCommandLineParser::Bool, \"Remove fibers exceeding curvature threshold:\", \"If false, only the high curvature parts are removed\");\n parser.addArgument(\"subsample\", \"\", mitkCommandLineParser::Float, \"Randomly select fraction of streamlines:\", \"Randomly select the specified fraction of streamlines from the input tractogram\");\n parser.addArgument(\"random_subsample\", \"\", mitkCommandLineParser::Bool, \"Randomly seed subsampling:\", \"Randomly seed subsampling. Else, use seed 0.\");\n parser.endGroup();\n\n parser.beginGroup(\"4. Transformation:\");\n parser.addArgument(\"mirror\", \"\", mitkCommandLineParser::Int, \"Invert coordinates:\", \"Invert fiber coordinates XYZ (e.g. 010 to invert y-coordinate of each fiber point)\");\n\n parser.addArgument(\"rotate_x\", \"\", mitkCommandLineParser::Float, \"Rotate x-axis:\", \"Rotate around x-axis (in deg)\");\n parser.addArgument(\"rotate_y\", \"\", mitkCommandLineParser::Float, \"Rotate y-axis:\", \"Rotate around y-axis (in deg)\");\n parser.addArgument(\"rotate_z\", \"\", mitkCommandLineParser::Float, \"Rotate z-axis:\", \"Rotate around z-axis (in deg)\");\n\n parser.addArgument(\"scale_x\", \"\", mitkCommandLineParser::Float, \"Scale x-axis:\", \"Scale in direction of x-axis\");\n parser.addArgument(\"scale_y\", \"\", mitkCommandLineParser::Float, \"Scale y-axis:\", \"Scale in direction of y-axis\");\n parser.addArgument(\"scale_z\", \"\", mitkCommandLineParser::Float, \"Scale z-axis\", \"Scale in direction of z-axis\");\n\n parser.addArgument(\"translate_x\", \"\", mitkCommandLineParser::Float, \"Translate x-axis:\", \"Translate in direction of x-axis (in mm)\");\n parser.addArgument(\"translate_y\", \"\", mitkCommandLineParser::Float, \"Translate y-axis:\", \"Translate in direction of y-axis (in mm)\");\n parser.addArgument(\"translate_z\", \"\", mitkCommandLineParser::Float, \"Translate z-axis:\", \"Translate in direction of z-axis (in mm)\");\n\n parser.endGroup();\n\n parser.beginGroup(\"5. Remove fiber parts:\");\n parser.addArgument(\"remove_inside\", \"\", mitkCommandLineParser::Bool, \"Remove fibers inside mask:\", \"remove fibers inside mask\");\n parser.addArgument(\"remove_outside\", \"\", mitkCommandLineParser::Bool, \"Remove fibers outside mask:\", \"remove fibers outside mask\");\n parser.addArgument(\"mask\", \"\", mitkCommandLineParser::String, \"Mask image:\", \"mask image\", us::Any(), true, false, false, mitkCommandLineParser::Input);\n parser.endGroup();\n\n\n std::map parsedArgs = parser.parseArguments(argc, argv);\n if (parsedArgs.size()==0)\n return EXIT_FAILURE;\n\n bool remove_outside = false;\n if (parsedArgs.count(\"remove_outside\"))\n remove_outside = us::any_cast(parsedArgs[\"remove_outside\"]);\n\n bool remove_inside = false;\n if (!remove_outside && parsedArgs.count(\"remove_inside\"))\n remove_inside = us::any_cast(parsedArgs[\"remove_inside\"]);\n\n typedef itk::Image< unsigned char, 3 > UcharImageType;\n UcharImageType::Pointer mask = nullptr;\n if (remove_inside || remove_outside)\n {\n if (parsedArgs.count(\"mask\"))\n mask = mitk::DiffusionDataIOHelper::load_itk_image< UcharImageType >(us::any_cast(parsedArgs[\"mask\"]));\n else {\n MITK_INFO << \"Mask needed to remove fibers inside or outside mask!\";\n return EXIT_FAILURE;\n }\n }\n\n bool remove = false;\n if (parsedArgs.count(\"remove\"))\n remove = us::any_cast(parsedArgs[\"remove\"]);\n\n bool random_subsample = false;\n if (parsedArgs.count(\"random_subsample\"))\n random_subsample = us::any_cast(parsedArgs[\"random_subsample\"]);\n\n float spline_resampling = -1;\n if (parsedArgs.count(\"spline_resampling\"))\n spline_resampling = us::any_cast(parsedArgs[\"spline_resampling\"]);\n\n float linear_resampling = -1;\n if (parsedArgs.count(\"linear_resampling\"))\n linear_resampling = us::any_cast(parsedArgs[\"linear_resampling\"]);\n\n int num_resampling = -1;\n if (parsedArgs.count(\"num_resampling\"))\n num_resampling = us::any_cast(parsedArgs[\"num_resampling\"]);\n\n float subsample = -1;\n if (parsedArgs.count(\"subsample\"))\n subsample = us::any_cast(parsedArgs[\"subsample\"]);\n\n float compress = -1;\n if (parsedArgs.count(\"compress\"))\n compress = us::any_cast(parsedArgs[\"compress\"]);\n\n float minFiberLength = -1;\n if (parsedArgs.count(\"min_length\"))\n minFiberLength = us::any_cast(parsedArgs[\"min_length\"]);\n\n float maxFiberLength = -1;\n if (parsedArgs.count(\"max_length\"))\n maxFiberLength = us::any_cast(parsedArgs[\"max_length\"]);\n\n float max_angle_dist = 10;\n if (parsedArgs.count(\"max_angle_dist\"))\n max_angle_dist = us::any_cast(parsedArgs[\"max_angle_dist\"]);\n\n float maxAngularDev = -1;\n if (parsedArgs.count(\"max_angle\"))\n maxAngularDev = us::any_cast(parsedArgs[\"max_angle\"]);\n\n int axis = 0;\n if (parsedArgs.count(\"mirror\"))\n axis = us::any_cast(parsedArgs[\"mirror\"]);\n\n float rotateX = 0;\n if (parsedArgs.count(\"rotate_x\"))\n rotateX = us::any_cast(parsedArgs[\"rotate_x\"]);\n\n float rotateY = 0;\n if (parsedArgs.count(\"rotate_y\"))\n rotateY = us::any_cast(parsedArgs[\"rotate_y\"]);\n\n float rotateZ = 0;\n if (parsedArgs.count(\"rotate_z\"))\n rotateZ = us::any_cast(parsedArgs[\"rotate_z\"]);\n\n float scaleX = 0;\n if (parsedArgs.count(\"scale_x\"))\n scaleX = us::any_cast(parsedArgs[\"scale_x\"]);\n\n float scaleY = 0;\n if (parsedArgs.count(\"scale_y\"))\n scaleY = us::any_cast(parsedArgs[\"scale_y\"]);\n\n float scaleZ = 0;\n if (parsedArgs.count(\"scale_z\"))\n scaleZ = us::any_cast(parsedArgs[\"scale_z\"]);\n\n float translateX = 0;\n if (parsedArgs.count(\"translate_x\"))\n translateX = us::any_cast(parsedArgs[\"translate_x\"]);\n\n float translateY = 0;\n if (parsedArgs.count(\"translate_y\"))\n translateY = us::any_cast(parsedArgs[\"translate_y\"]);\n\n float translateZ = 0;\n if (parsedArgs.count(\"translate_z\"))\n translateZ = us::any_cast(parsedArgs[\"translate_z\"]);\n\n\n std::string inFileName = us::any_cast(parsedArgs[\"i\"]);\n std::string outFileName = us::any_cast(parsedArgs[\"o\"]);\n\n try\n {\n mitk::FiberBundle::Pointer fib = LoadFib(inFileName);\n\n if (subsample>0)\n fib = fib->SubsampleFibers(subsample, random_subsample);\n\n if (maxAngularDev>0)\n {\n auto filter = itk::FiberCurvatureFilter::New();\n filter->SetInputFiberBundle(fib);\n filter->SetAngularDeviation(maxAngularDev);\n filter->SetDistance(max_angle_dist);\n filter->SetRemoveFibers(remove);\n filter->Update();\n fib = filter->GetOutputFiberBundle();\n }\n\n if (minFiberLength>0)\n fib->RemoveShortFibers(minFiberLength);\n\n if (maxFiberLength>0)\n fib->RemoveLongFibers(maxFiberLength);\n\n if (spline_resampling>0)\n fib->ResampleSpline(spline_resampling);\n\n if (linear_resampling>0)\n fib->ResampleLinear(linear_resampling);\n\n if (num_resampling>0)\n fib->ResampleToNumPoints(num_resampling);\n\n if (compress>0)\n fib->Compress(compress);\n\n if ( mask.IsNotNull() )\n {\n if (remove_outside)\n fib = fib->RemoveFibersOutside(mask, false);\n else if (remove_inside)\n fib = fib->RemoveFibersOutside(mask, true);\n }\n\n if (axis\/100==1)\n fib->MirrorFibers(0);\n\n if ((axis%100)\/10==1)\n fib->MirrorFibers(1);\n\n if (axis%10==1)\n fib->MirrorFibers(2);\n\n\n if (rotateX > 0 || rotateY > 0 || rotateZ > 0){\n std::cout << \"Rotate \" << rotateX << \" \" << rotateY << \" \" << rotateZ;\n fib->RotateAroundAxis(rotateX, rotateY, rotateZ);\n }\n if (translateX > 0 || translateY > 0 || translateZ > 0){\n fib->TranslateFibers(translateX, translateY, translateZ);\n }\n if (scaleX > 0 || scaleY > 0 || scaleZ > 0)\n fib->ScaleFibers(scaleX, scaleY, scaleZ);\n\n mitk::IOUtil::Save(fib.GetPointer(), outFileName );\n\n }\n catch (itk::ExceptionObject e)\n {\n std::cout << e;\n return EXIT_FAILURE;\n }\n catch (std::exception e)\n {\n std::cout << e.what();\n return EXIT_FAILURE;\n }\n catch (...)\n {\n std::cout << \"ERROR!?!\";\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"AliAnalysisTaskSEpPbCorrelationsJetV2Kine_dev *AddTaskSEpPbCorrelationsJetV2Kine(TString sMode = \"TPCTPCFMDA\")\n{\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskKineAmpt.C::AddTaskKineAmpt\", \"No analysis manager to connect to\");\n return nullptr;\n }\n\/\/=============================================================================\n\n AliAnalysisTaskSEpPbCorrelationsJetV2Kine_dev *task = new AliAnalysisTaskSEpPbCorrelationsJetV2Kine_dev(\"AliAnalysisTaskSEpPbCorrelationsJetV2Kine_dev\");\n\n Double_t trigPtLimits[] = {0.5, 1.0, 1.5, 2.0, 3.0, 5.0, 8.0};\n const Int_t nBinTrigPt = sizeof(trigPtLimits) \/ sizeof(Double_t) - 1;\n task->SetTrigPtBinning(nBinTrigPt, trigPtLimits);\n\n Double_t assocPtLimits[] = {0.5, 1., 1.5, 50.};\n const Int_t nBinAssocPt = sizeof(assocPtLimits) \/ sizeof(Double_t) - 1;\n task->SetAssocPtBinning(nBinAssocPt, assocPtLimits);\n\n task->SetAnaMode(sMode);\n task->SetAssoCut(1.0);\n \n task->SetPtMin(0.5);\n task->SetPtMax(50.);\n\n task->SetCen1(0);\n task->SetCen2(10);\n\n\n \/\/ Input File\n TGrid::Connect(\"alien:\/\/\");\n TFile *file = TFile::Open(\"alien:\/\/\/alice\/cern.ch\/user\/s\/sitang\/AMPT_Centrality_Calibration\/Centrality.root\");\n\n \/\/TFile *file = TFile::Open(\".\/Centrality\/Centrality.root\");\n TH1D *h_Charge = (TH1D*)file->Get(\"hChargeV0A\"); h_Charge->SetDirectory(0);\n file->Close();\n\n \/\/ create input container\n AliAnalysisDataContainer *cinput1 = mgr->CreateContainer(\"h_centrality\",\n TH1D::Class(),\n AliAnalysisManager::kInputContainer);\n cinput1->SetData(h_Charge);\n\n mgr->AddTask(task);\n mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer());\n mgr->ConnectInput(task, 1, cinput1);\n mgr->ConnectOutput(task, 1, mgr->CreateContainer(Form(\"listKineAmpt_%s\",sMode.Data()),\n TList::Class(),\n AliAnalysisManager::kOutputContainer,\n AliAnalysisManager::GetCommonFileName()));\n\/\/=============================================================================\n\n return task;\n}\nUpdate Jet particle v2 MCAliAnalysisTaskSEpPbCorrelationsJetV2Kine *AddTaskSEpPbCorrelationsJetV2Kine(TString sMode = \"TPCTPCFMDA\")\n{\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskKineAmpt.C::AddTaskKineAmpt\", \"No analysis manager to connect to\");\n return nullptr;\n }\n\/\/=============================================================================\n\n AliAnalysisTaskSEpPbCorrelationsJetV2Kine *task = new AliAnalysisTaskSEpPbCorrelationsJetV2Kine(\"AliAnalysisTaskSEpPbCorrelationsJetV2Kine\");\n\n Double_t trigPtLimits[] = {0.5, 1.0, 1.5, 2.0, 3.0, 5.0, 8.0};\n const Int_t nBinTrigPt = sizeof(trigPtLimits) \/ sizeof(Double_t) - 1;\n task->SetTrigPtBinning(nBinTrigPt, trigPtLimits);\n\n Double_t assocPtLimits[] = {0.5, 1., 1.5, 50.};\n const Int_t nBinAssocPt = sizeof(assocPtLimits) \/ sizeof(Double_t) - 1;\n task->SetAssocPtBinning(nBinAssocPt, assocPtLimits);\n\n task->SetAnaMode(sMode);\n task->SetAssoCut(1.0);\n \n task->SetPtMin(0.5);\n task->SetPtMax(50.);\n\n task->SetCen1(0);\n task->SetCen2(10);\n\n\n \/\/ Input File\n TGrid::Connect(\"alien:\/\/\");\n TFile *file = TFile::Open(\"alien:\/\/\/alice\/cern.ch\/user\/s\/sitang\/AMPT_Centrality_Calibration\/Centrality.root\");\n\n \/\/TFile *file = TFile::Open(\".\/Centrality\/Centrality.root\");\n TH1D *h_Charge = (TH1D*)file->Get(\"hChargeV0A\"); h_Charge->SetDirectory(0);\n file->Close();\n\n \/\/ create input container\n AliAnalysisDataContainer *cinput1 = mgr->CreateContainer(\"h_centrality\",\n TH1D::Class(),\n AliAnalysisManager::kInputContainer);\n cinput1->SetData(h_Charge);\n\n mgr->AddTask(task);\n mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer());\n mgr->ConnectInput(task, 1, cinput1);\n mgr->ConnectOutput(task, 1, mgr->CreateContainer(Form(\"listKineAmpt_%s\",sMode.Data()),\n TList::Class(),\n AliAnalysisManager::kOutputContainer,\n AliAnalysisManager::GetCommonFileName()));\n\/\/=============================================================================\n\n return task;\n}\n<|endoftext|>"} {"text":"\/\/------------------------------------------------------------------------------------------------\r\n\/\/ File: LineFollower.cpp\r\n\/\/ Project: LG Exec Ed Program\r\n\/\/ Versions:\r\n\/\/ 1.0 April 2017 - initial version\r\n\/\/ Main line follower Program. This is the main program follows a line. \r\n\/\/ To invoke LineFollower . This program will send the processed camera image \r\n\/\/ via UDP to the RecvImage_UDP program that will display the image\r\n\/\/ \r\n\/\/ Use the following keys\r\n\/\/ r key - run mode (starts the robot following the line\r\n\/\/ s key - disables run mode and stops the robot\r\n\/\/ j key - moves the camera pan servo left\r\n\/\/ l key - moves the camera pan servo right\r\n\/\/ i key - moves the camera tilt servo up\r\n\/\/ m key - moves the camera tilt servo down\r\n\/\/ k key - moves the camera pan and tilt servos to center\r\n\/\/ q key - descreases the speed of the robot (manual control only both wheels move at the same speed)\r\n\/\/ w key - stops the robot (manual control only)\r\n\/\/ e key - increases the speed of the robot (manual control only both wheels move at the same speed)\r\n\/\/----------------------------------------------------------------------------------------------\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \"ImageProcessing.h\"\r\n#include \"PI3OpencvCompat.h\"\r\n#include \"PID.h\"\r\n#include \"Servos.h\"\r\n#include \"NetworkUDP.h\"\r\n#include \"UdpSendJpeg.h\"\r\n#include \"UdpSendMap.h\"\r\n#include \"KeyboardSetup.h\"\r\n\r\n#ifndef UBUNTU\t\t\/\/ For building in ubuntu. Below code sould be built in raspberry pi.\r\n#include \r\n#endif \/\/UBUNTU\r\n\r\n#include \"sensor_manager.h\"\r\n#include \"servos_manager.h\"\r\n\r\n\r\n\r\n#define INIT 0\r\n#define STOP 1\r\n#define FOWARD 2\r\n#define LEFT 3\r\n#define RIGHT 4\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nusing namespace cv;\r\nusing namespace std;\r\n\r\n\r\n#define WIDTH 640\r\n#define HEIGHT 480\r\n\r\n\r\n\r\nstatic int AWidth;\r\nstatic int AHeight;\r\nstatic int Pan;\r\nstatic int Tilt;\r\nstatic CvCapture * capture=NULL;\r\nstatic UdpSendJpeg VideoSender;\r\nstatic UdpSendMap\t MapSender;\r\nstatic TPID PID; \r\nstatic int Run=INIT;\r\n\r\nfloat\t offset;\t\t \/\/ computed robot deviation from the line \r\n\r\n\r\n\r\n\r\n\r\n\r\nstatic void Setup_Control_C_Signal_Handler_And_Keyboard_No_Enter(void);\r\nstatic void CleanUp(void);\r\nstatic void Control_C_Handler(int s);\r\nstatic void HandleInputChar(void);\r\n\r\n\/\/----------------------------------------------------------------\r\n\/\/ main - This is the main program for the line follower and \r\n\/\/ contains the control loop\r\n\/\/-----------------------------------------------------------------\r\nint main(int argc, const char** argv)\r\n{\r\n IplImage * iplCameraImage; \/\/ camera image in IplImage format \r\n Mat image; \/\/ camera image in Mat format \r\n\r\n\r\n\r\n if (argc !=3) {\r\n fprintf(stderr,\"usage %s hostname port\\n\", argv[0]);\r\n exit(0);\r\n }\r\n\r\n Setup_Control_C_Signal_Handler_And_Keyboard_No_Enter(); \/\/ Set Control-c handler to properly exit cleanly \r\n\r\n\r\n\r\n\r\n if (VideoSender.OpenUdp(argv[1],argv[2]) == 0) \/\/ Setup remote network destination to send images\r\n {\r\n\t printf(\"VideoSender.OpenUdp Failed\\n\");\r\n\t CleanUp();\r\n\t return(-1);\r\n }\r\n\r\n if (MapSender.OpenUdp(argv[1], \"30002\") == 0) \/\/ Setup remote network destination to send images\r\n {\r\n\t printf(\"MapSender.OpenUdp Failed\\n\");\r\n\t CleanUp();\r\n\t return(-1);\r\n }\r\n\r\n printf(\"cvCreateCameraCapture()\\n\");\r\n\r\n capture =cvCreateCameraCapture(0); \/\/ Open default Camera\r\n if(!capture)\r\n {\r\n printf(\"Camera Not Initialized\\n\");\r\n CleanUp();\r\n return 0;\r\n }\r\n\r\n if (cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH,WIDTH)==0) \/\/ Set camera width \r\n {\r\n printf(\"cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH,WIDTH) Failed)\\n\");\r\n }\r\n\r\n if (cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT,HEIGHT)==0) \/\/ Set camera height\r\n {\r\n printf(\"cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT,HEIGHT) Failed)\\n\");\r\n }\r\n\r\n AWidth=cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);\r\n AHeight=cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);\r\n\r\n printf(\"Width = %d\\n\",AWidth );\r\n printf(\"Height = %d\\n\", AHeight);\r\n\r\n if (!IsPi3) namedWindow( \"camera\", CV_WINDOW_AUTOSIZE ); \/\/ If not running on PI3 open local Window\r\n \r\n \/\/if (!IsPi3) namedWindow( \"processed\", CV_WINDOW_AUTOSIZE ); \/\/ If not running on PI3 open local Window\r\n do\r\n {\r\n\tsensor_manager_main();\r\n\tservos_manager_main();\r\n\r\n iplCameraImage = cvQueryFrame(capture); \/\/ Get Camera image\r\n image= cv::cvarrToMat(iplCameraImage); \/\/ Convert Camera image to Mat format\r\n if (IsPi3) flip(image, image,-1); \/\/ if running on PI3 flip(-1)=180 degrees\r\n\r\n offset=FindLineInImageAndComputeOffset(image); \/\/ Process camera image \/ locat line and compute offset from line\r\n\r\n\tVideoSender.UdpSendImageAsJpeg(image);\r\n \r\n if (!IsPi3) imshow(\"camera\", image ); \/\/ Show image locally if not running on PI 3\r\n HandleInputChar(); \/\/ Handle Keyboard Input\r\n if (!IsPi3) cv::waitKey(1); \/\/ must be call show image locally work with imshow\r\n\r\n } while (1);\r\n\r\n\r\n return 0;\r\n}\r\n\/\/-----------------------------------------------------------------\r\n\/\/ END main\r\n\/\/-----------------------------------------------------------------\r\n\/\/----------------------------------------------------------------\r\n\/\/ Setup_Control_C_Signal_Handler_And_Keyboard_No_Enter - This \r\n\/\/ sets uo the Control-c Handler and put the keyboard in a mode\r\n\/\/ where it will not\r\n\/\/ 1. echo input\r\n\/\/ 2. need enter hit to get a character \r\n\/\/ 3. block waiting for input\r\n\/\/-----------------------------------------------------------------\r\nstatic void Setup_Control_C_Signal_Handler_And_Keyboard_No_Enter(void)\r\n{\r\n struct sigaction sigIntHandler;\r\n sigIntHandler.sa_handler = Control_C_Handler; \/\/ Setup control-c callback \r\n sigemptyset(&sigIntHandler.sa_mask);\r\n sigIntHandler.sa_flags = 0;\r\n sigaction(SIGINT, &sigIntHandler, NULL);\r\n ConfigKeyboardNoEnterBlockEcho(); \/\/ set keyboard configuration\r\n}\r\n\/\/-----------------------------------------------------------------\r\n\/\/ END Setup_Control_C_Signal_Handler_And_Keyboard_No_Enter\r\n\/\/-----------------------------------------------------------------\r\n\/\/----------------------------------------------------------------\r\n\/\/ CleanUp - Performs cleanup processing before exiting the\r\n\/\/ the program\r\n\/\/-----------------------------------------------------------------\r\nstatic void CleanUp(void)\r\n{\r\n RestoreKeyboard(); \/\/ restore Keyboard\r\n \r\n if (capture!=NULL) \r\n {\r\n cvReleaseCapture(&capture); \/\/ Close camera\r\n capture=NULL;\r\n }\r\n\r\n VideoSender.CloseUdp();\r\n MapSender.CloseUdp();\r\n ResetServos(); \/\/ Reset servos to center or stopped\r\n CloseServos(); \/\/ Close servo device driver\r\n printf(\"restored\\n\");\r\n}\r\n\/\/-----------------------------------------------------------------\r\n\/\/ END CleanUp\r\n\/\/-----------------------------------------------------------------\r\n\/\/----------------------------------------------------------------\r\n\/\/ Control_C_Handler - called when control-c pressed\r\n\/\/-----------------------------------------------------------------\r\nstatic void Control_C_Handler(int s)\r\n{\r\n CleanUp();\r\n printf(\"Caught signal %d\\n\",s);\r\n printf(\"exiting\\n\");\r\n exit(1);\r\n}\r\n\/\/-----------------------------------------------------------------\r\n\/\/ END Control_C_Handler\r\n\/\/-----------------------------------------------------------------\r\n\/\/----------------------------------------------------------------\r\n\/\/ HandleInputChar - check if keys are press and proccess keys of\r\n\/\/ interest.\r\n\/\/-----------------------------------------------------------------\r\nstatic void HandleInputChar(void)\r\n{\r\n int ch;\r\n static int speed=0;\r\n if ((ch=getchar())==EOF) \/\/ no key pressed return\r\n {\r\n return;\r\n }\r\n\r\n\tif (ch=='w')\r\n\t{\r\n\t\trobot_mode_setting(ROBOT_FOWARD_MOVING,offset);\r\n }\r\n\telse if (ch=='x')\r\n {\r\n\t\trobot_mode_setting(ROBOT_BACKWARD_MOVING,offset);\r\n }\r\n\telse if (ch=='d')\r\n {\r\n\t\trobot_mode_setting(ROBOT_RIGHT_ROTATING,offset);\r\n }\r\n\telse if (ch=='a')\r\n {\r\n\t\trobot_mode_setting(ROBOT_LEFT_ROTATING,offset);\r\n }\r\n\telse\r\n\t{\r\n\t\trobot_mode_setting(ROBOT_STOP,offset);\r\n\t}\r\n\t\r\n\r\n}\r\n\r\n\/\/-----------------------------------------------------------------\r\n\/\/ END HandleInputChar\r\n\/\/-----------------------------------------------------------------\r\n\/\/-----------------------------------------------------------------\r\n\/\/ END of File\r\n\/\/-----------------------------------------------------------------\r\n\r\nadd map_port to command line!\/\/------------------------------------------------------------------------------------------------\r\n\/\/ File: LineFollower.cpp\r\n\/\/ Project: LG Exec Ed Program\r\n\/\/ Versions:\r\n\/\/ 1.0 April 2017 - initial version\r\n\/\/ Main line follower Program. This is the main program follows a line. \r\n\/\/ To invoke LineFollower . This program will send the processed camera image \r\n\/\/ via UDP to the RecvImage_UDP program that will display the image\r\n\/\/ \r\n\/\/ Use the following keys\r\n\/\/ r key - run mode (starts the robot following the line\r\n\/\/ s key - disables run mode and stops the robot\r\n\/\/ j key - moves the camera pan servo left\r\n\/\/ l key - moves the camera pan servo right\r\n\/\/ i key - moves the camera tilt servo up\r\n\/\/ m key - moves the camera tilt servo down\r\n\/\/ k key - moves the camera pan and tilt servos to center\r\n\/\/ q key - descreases the speed of the robot (manual control only both wheels move at the same speed)\r\n\/\/ w key - stops the robot (manual control only)\r\n\/\/ e key - increases the speed of the robot (manual control only both wheels move at the same speed)\r\n\/\/----------------------------------------------------------------------------------------------\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \"ImageProcessing.h\"\r\n#include \"PI3OpencvCompat.h\"\r\n#include \"PID.h\"\r\n#include \"Servos.h\"\r\n#include \"NetworkUDP.h\"\r\n#include \"UdpSendJpeg.h\"\r\n#include \"UdpSendMap.h\"\r\n#include \"KeyboardSetup.h\"\r\n\r\n#ifndef UBUNTU\t\t\/\/ For building in ubuntu. Below code sould be built in raspberry pi.\r\n#include \r\n#endif \/\/UBUNTU\r\n\r\n#include \"sensor_manager.h\"\r\n#include \"servos_manager.h\"\r\n\r\n\r\n\r\n#define INIT 0\r\n#define STOP 1\r\n#define FOWARD 2\r\n#define LEFT 3\r\n#define RIGHT 4\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nusing namespace cv;\r\nusing namespace std;\r\n\r\n\r\n#define WIDTH 640\r\n#define HEIGHT 480\r\n\r\n\r\n\r\nstatic int AWidth;\r\nstatic int AHeight;\r\nstatic int Pan;\r\nstatic int Tilt;\r\nstatic CvCapture * capture=NULL;\r\nstatic UdpSendJpeg VideoSender;\r\nstatic UdpSendMap\t MapSender;\r\nstatic TPID PID; \r\nstatic int Run=INIT;\r\n\r\nfloat\t offset;\t\t \/\/ computed robot deviation from the line \r\n\r\n\r\n\r\n\r\n\r\n\r\nstatic void Setup_Control_C_Signal_Handler_And_Keyboard_No_Enter(void);\r\nstatic void CleanUp(void);\r\nstatic void Control_C_Handler(int s);\r\nstatic void HandleInputChar(void);\r\n\r\n\/\/----------------------------------------------------------------\r\n\/\/ main - This is the main program for the line follower and \r\n\/\/ contains the control loop\r\n\/\/-----------------------------------------------------------------\r\nint main(int argc, const char** argv)\r\n{\r\n IplImage * iplCameraImage; \/\/ camera image in IplImage format \r\n Mat image; \/\/ camera image in Mat format \r\n\r\n\r\n\r\n if (argc !=4) {\r\n fprintf(stderr,\"usage %s hostname video_port map_port\\n\", argv[0]);\r\n exit(0);\r\n }\r\n\r\n Setup_Control_C_Signal_Handler_And_Keyboard_No_Enter(); \/\/ Set Control-c handler to properly exit cleanly \r\n\r\n\r\n\r\n\r\n if (VideoSender.OpenUdp(argv[1],argv[2]) == 0) \/\/ Setup remote network destination to send images\r\n {\r\n\t printf(\"VideoSender.OpenUdp Failed\\n\");\r\n\t CleanUp();\r\n\t return(-1);\r\n }\r\n\r\n if (MapSender.OpenUdp(argv[1], argv[3]) == 0) \/\/ Setup remote network destination to send images\r\n {\r\n\t printf(\"MapSender.OpenUdp Failed\\n\");\r\n\t CleanUp();\r\n\t return(-1);\r\n }\r\n\r\n printf(\"cvCreateCameraCapture()\\n\");\r\n\r\n capture =cvCreateCameraCapture(0); \/\/ Open default Camera\r\n if(!capture)\r\n {\r\n printf(\"Camera Not Initialized\\n\");\r\n CleanUp();\r\n return 0;\r\n }\r\n\r\n if (cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH,WIDTH)==0) \/\/ Set camera width \r\n {\r\n printf(\"cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH,WIDTH) Failed)\\n\");\r\n }\r\n\r\n if (cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT,HEIGHT)==0) \/\/ Set camera height\r\n {\r\n printf(\"cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT,HEIGHT) Failed)\\n\");\r\n }\r\n\r\n AWidth=cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);\r\n AHeight=cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);\r\n\r\n printf(\"Width = %d\\n\",AWidth );\r\n printf(\"Height = %d\\n\", AHeight);\r\n\r\n if (!IsPi3) namedWindow( \"camera\", CV_WINDOW_AUTOSIZE ); \/\/ If not running on PI3 open local Window\r\n \r\n \/\/if (!IsPi3) namedWindow( \"processed\", CV_WINDOW_AUTOSIZE ); \/\/ If not running on PI3 open local Window\r\n do\r\n {\r\n\tsensor_manager_main();\r\n\tservos_manager_main();\r\n\r\n iplCameraImage = cvQueryFrame(capture); \/\/ Get Camera image\r\n image= cv::cvarrToMat(iplCameraImage); \/\/ Convert Camera image to Mat format\r\n if (IsPi3) flip(image, image,-1); \/\/ if running on PI3 flip(-1)=180 degrees\r\n\r\n offset=FindLineInImageAndComputeOffset(image); \/\/ Process camera image \/ locat line and compute offset from line\r\n\r\n\tVideoSender.UdpSendImageAsJpeg(image);\r\n \r\n if (!IsPi3) imshow(\"camera\", image ); \/\/ Show image locally if not running on PI 3\r\n HandleInputChar(); \/\/ Handle Keyboard Input\r\n if (!IsPi3) cv::waitKey(1); \/\/ must be call show image locally work with imshow\r\n\r\n } while (1);\r\n\r\n\r\n return 0;\r\n}\r\n\/\/-----------------------------------------------------------------\r\n\/\/ END main\r\n\/\/-----------------------------------------------------------------\r\n\/\/----------------------------------------------------------------\r\n\/\/ Setup_Control_C_Signal_Handler_And_Keyboard_No_Enter - This \r\n\/\/ sets uo the Control-c Handler and put the keyboard in a mode\r\n\/\/ where it will not\r\n\/\/ 1. echo input\r\n\/\/ 2. need enter hit to get a character \r\n\/\/ 3. block waiting for input\r\n\/\/-----------------------------------------------------------------\r\nstatic void Setup_Control_C_Signal_Handler_And_Keyboard_No_Enter(void)\r\n{\r\n struct sigaction sigIntHandler;\r\n sigIntHandler.sa_handler = Control_C_Handler; \/\/ Setup control-c callback \r\n sigemptyset(&sigIntHandler.sa_mask);\r\n sigIntHandler.sa_flags = 0;\r\n sigaction(SIGINT, &sigIntHandler, NULL);\r\n ConfigKeyboardNoEnterBlockEcho(); \/\/ set keyboard configuration\r\n}\r\n\/\/-----------------------------------------------------------------\r\n\/\/ END Setup_Control_C_Signal_Handler_And_Keyboard_No_Enter\r\n\/\/-----------------------------------------------------------------\r\n\/\/----------------------------------------------------------------\r\n\/\/ CleanUp - Performs cleanup processing before exiting the\r\n\/\/ the program\r\n\/\/-----------------------------------------------------------------\r\nstatic void CleanUp(void)\r\n{\r\n RestoreKeyboard(); \/\/ restore Keyboard\r\n \r\n if (capture!=NULL) \r\n {\r\n cvReleaseCapture(&capture); \/\/ Close camera\r\n capture=NULL;\r\n }\r\n\r\n VideoSender.CloseUdp();\r\n MapSender.CloseUdp();\r\n ResetServos(); \/\/ Reset servos to center or stopped\r\n CloseServos(); \/\/ Close servo device driver\r\n printf(\"restored\\n\");\r\n}\r\n\/\/-----------------------------------------------------------------\r\n\/\/ END CleanUp\r\n\/\/-----------------------------------------------------------------\r\n\/\/----------------------------------------------------------------\r\n\/\/ Control_C_Handler - called when control-c pressed\r\n\/\/-----------------------------------------------------------------\r\nstatic void Control_C_Handler(int s)\r\n{\r\n CleanUp();\r\n printf(\"Caught signal %d\\n\",s);\r\n printf(\"exiting\\n\");\r\n exit(1);\r\n}\r\n\/\/-----------------------------------------------------------------\r\n\/\/ END Control_C_Handler\r\n\/\/-----------------------------------------------------------------\r\n\/\/----------------------------------------------------------------\r\n\/\/ HandleInputChar - check if keys are press and proccess keys of\r\n\/\/ interest.\r\n\/\/-----------------------------------------------------------------\r\nstatic void HandleInputChar(void)\r\n{\r\n int ch;\r\n static int speed=0;\r\n if ((ch=getchar())==EOF) \/\/ no key pressed return\r\n {\r\n return;\r\n }\r\n\r\n\tif (ch=='w')\r\n\t{\r\n\t\trobot_mode_setting(ROBOT_FOWARD_MOVING,offset);\r\n }\r\n\telse if (ch=='x')\r\n {\r\n\t\trobot_mode_setting(ROBOT_BACKWARD_MOVING,offset);\r\n }\r\n\telse if (ch=='d')\r\n {\r\n\t\trobot_mode_setting(ROBOT_RIGHT_ROTATING,offset);\r\n }\r\n\telse if (ch=='a')\r\n {\r\n\t\trobot_mode_setting(ROBOT_LEFT_ROTATING,offset);\r\n }\r\n\telse\r\n\t{\r\n\t\trobot_mode_setting(ROBOT_STOP,offset);\r\n\t}\r\n\t\r\n\r\n}\r\n\r\n\/\/-----------------------------------------------------------------\r\n\/\/ END HandleInputChar\r\n\/\/-----------------------------------------------------------------\r\n\/\/-----------------------------------------------------------------\r\n\/\/ END of File\r\n\/\/-----------------------------------------------------------------\r\n\r\n<|endoftext|>"} {"text":"\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2016 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\/\/ C++ includes\n\n\/\/ Local includes\n#include \"libmesh\/side.h\"\n#include \"libmesh\/cell_pyramid5.h\"\n#include \"libmesh\/edge_edge2.h\"\n#include \"libmesh\/face_tri3.h\"\n#include \"libmesh\/face_quad4.h\"\n\nnamespace libMesh\n{\n\n\n\n\n\/\/ ------------------------------------------------------------\n\/\/ Pyramid5 class static member initializations\nconst unsigned int Pyramid5::side_nodes_map[5][4] =\n {\n {0, 1, 4, 99}, \/\/ Side 0\n {1, 2, 4, 99}, \/\/ Side 1\n {2, 3, 4, 99}, \/\/ Side 2\n {3, 0, 4, 99}, \/\/ Side 3\n {0, 3, 2, 1} \/\/ Side 4\n };\n\nconst unsigned int Pyramid5::edge_nodes_map[8][2] =\n {\n {0, 1}, \/\/ Side 0\n {1, 2}, \/\/ Side 1\n {2, 3}, \/\/ Side 2\n {0, 3}, \/\/ Side 3\n {0, 4}, \/\/ Side 4\n {1, 4}, \/\/ Side 5\n {2, 4}, \/\/ Side 6\n {3, 4} \/\/ Side 7\n };\n\n\n\n\/\/ ------------------------------------------------------------\n\/\/ Pyramid5 class member functions\n\nbool Pyramid5::is_vertex(const unsigned int) const\n{\n return true;\n}\n\nbool Pyramid5::is_edge(const unsigned int) const\n{\n return false;\n}\n\nbool Pyramid5::is_face(const unsigned int) const\n{\n return false;\n}\n\nbool Pyramid5::is_node_on_side(const unsigned int n,\n const unsigned int s) const\n{\n libmesh_assert_less (s, n_sides());\n for (unsigned int i = 0; i != 4; ++i)\n if (side_nodes_map[s][i] == n)\n return true;\n return false;\n}\n\nbool Pyramid5::is_node_on_edge(const unsigned int n,\n const unsigned int e) const\n{\n libmesh_assert_less (e, n_edges());\n for (unsigned int i = 0; i != 2; ++i)\n if (edge_nodes_map[e][i] == n)\n return true;\n return false;\n}\n\n\n\nbool Pyramid5::has_affine_map() const\n{\n \/\/ Point v = this->point(3) - this->point(0);\n \/\/ return (v.relative_fuzzy_equals(this->point(2) - this->point(1)));\n return false;\n}\n\n\n\nUniquePtr Pyramid5::build_side (const unsigned int i,\n bool proxy) const\n{\n libmesh_assert_less (i, this->n_sides());\n\n if (proxy)\n {\n switch (i)\n {\n case 0:\n case 1:\n case 2:\n case 3:\n return UniquePtr(new Side(this,i));\n\n case 4:\n return UniquePtr(new Side(this,i));\n\n default:\n libmesh_error_msg(\"Invalid side i = \" << i);\n }\n }\n\n else\n {\n \/\/ Create NULL pointer to be initialized, returned later.\n Elem * face = libmesh_nullptr;\n\n switch (i)\n {\n case 0: \/\/ triangular face 1\n case 1: \/\/ triangular face 2\n case 2: \/\/ triangular face 3\n case 3: \/\/ triangular face 4\n {\n face = new Tri3;\n break;\n }\n case 4: \/\/ the quad face at z=0\n {\n face = new Quad4;\n break;\n }\n default:\n libmesh_error_msg(\"Invalid side i = \" << i);\n }\n\n face->subdomain_id() = this->subdomain_id();\n\n \/\/ Set the nodes\n for (unsigned n=0; nn_nodes(); ++n)\n face->set_node(n) = this->get_node(Pyramid5::side_nodes_map[i][n]);\n\n return UniquePtr(face);\n }\n\n libmesh_error_msg(\"We'll never get here!\");\n return UniquePtr();\n}\n\n\n\nUniquePtr Pyramid5::build_edge (const unsigned int i) const\n{\n libmesh_assert_less (i, this->n_edges());\n\n return UniquePtr(new SideEdge(this,i));\n}\n\n\n\nvoid Pyramid5::connectivity(const unsigned int libmesh_dbg_var(sc),\n const IOPackage iop,\n std::vector & conn) const\n{\n libmesh_assert(_nodes);\n libmesh_assert_less (sc, this->n_sub_elem());\n libmesh_assert_not_equal_to (iop, INVALID_IO_PACKAGE);\n\n switch (iop)\n {\n case TECPLOT:\n {\n conn.resize(8);\n conn[0] = this->node(0)+1;\n conn[1] = this->node(1)+1;\n conn[2] = this->node(2)+1;\n conn[3] = this->node(3)+1;\n conn[4] = this->node(4)+1;\n conn[5] = this->node(4)+1;\n conn[6] = this->node(4)+1;\n conn[7] = this->node(4)+1;\n return;\n }\n\n case VTK:\n {\n conn.resize(5);\n conn[0] = this->node(3);\n conn[1] = this->node(2);\n conn[2] = this->node(1);\n conn[3] = this->node(0);\n conn[4] = this->node(4);\n return;\n }\n\n default:\n libmesh_error_msg(\"Unsupported IO package \" << iop);\n }\n}\n\n\nReal Pyramid5::volume () const\n{\n \/\/ Make copies of our points. It makes the subsequent calculations a bit\n \/\/ shorter and avoids dereferencing the same pointer multiple times.\n Point\n x0 = point(0), x1 = point(1), x2 = point(2), x3 = point(3), x4 = point(4);\n\n \/\/ The number of components in the dx_dxi, dx_deta, and dx_dzeta arrays.\n const int n_components = 4;\n\n Point dx_dxi[n_components] =\n {\n -x0\/4 + x1\/4 + x2\/4 - x3\/4, \/\/ const\n x0\/4 - x1\/4 - x2\/4 + x3\/4, \/\/ zeta\n x0\/4 - x1\/4 + x2\/4 - x3\/4 \/\/ eta\n };\n\n Point dx_deta[n_components] =\n {\n -x0\/4 - x1\/4 + x2\/4 + x3\/4, \/\/ const\n x0\/4 + x1\/4 - x2\/4 - x3\/4, \/\/ zeta\n x0\/4 - x1\/4 + x2\/4 - x3\/4, \/\/ xi\n };\n\n Point dx_dzeta[n_components] =\n {\n -x0\/4 - x1\/4 - x2\/4 - x3\/4 + x4, \/\/ const\n x0\/2 + x1\/2 + x2\/2 + x3\/2 - 2*x4, \/\/ zeta\n -x0\/4 - x1\/4 - x2\/4 - x3\/4 + x4, \/\/ zeta**2\n x0\/4 - x1\/4 + x2\/4 - x3\/4 \/\/ xi*eta\n };\n\n \/\/ Number of points in the 2D quadrature rule\n const int N = 8;\n\n \/\/ Parameters of the quadrature rule\n static const Real\n a1 = -5.0661630334978742377431469429037e-01L,\n a2 = -2.6318405556971359557121701304557e-01L,\n b1 = 1.2251482265544137786674043037115e-01L,\n b2 = 5.4415184401122528879992623629551e-01L,\n w1 = 2.3254745125350790274997694884235e-01L,\n w2 = 1.0078588207982543058335638449098e-01L;\n\n \/\/ The points and weights of the 2x2x2 quadrature rule\n static const Real xi[8] = {a1, a2, a1, a2, -a1, -a2, -a1, -a2};\n static const Real eta[8] = {a1, a2, -a1, -a2, a1, a2, -a1, -a2};\n static const Real zeta[8] = {b1, b2, b1, b2, b1, b2, b1, b2};\n static const Real w[8] = {w1, w2, w1, w2, w1, w2, w1, w2};\n\n Real vol = 0.;\n for (int q=0; qRevert \"Add quadrature-based volume() implementation for Pyramid5.\"\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2016 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\/\/ C++ includes\n\n\/\/ Local includes\n#include \"libmesh\/side.h\"\n#include \"libmesh\/cell_pyramid5.h\"\n#include \"libmesh\/edge_edge2.h\"\n#include \"libmesh\/face_tri3.h\"\n#include \"libmesh\/face_quad4.h\"\n\nnamespace libMesh\n{\n\n\n\n\n\/\/ ------------------------------------------------------------\n\/\/ Pyramid5 class static member initializations\nconst unsigned int Pyramid5::side_nodes_map[5][4] =\n {\n {0, 1, 4, 99}, \/\/ Side 0\n {1, 2, 4, 99}, \/\/ Side 1\n {2, 3, 4, 99}, \/\/ Side 2\n {3, 0, 4, 99}, \/\/ Side 3\n {0, 3, 2, 1} \/\/ Side 4\n };\n\nconst unsigned int Pyramid5::edge_nodes_map[8][2] =\n {\n {0, 1}, \/\/ Side 0\n {1, 2}, \/\/ Side 1\n {2, 3}, \/\/ Side 2\n {0, 3}, \/\/ Side 3\n {0, 4}, \/\/ Side 4\n {1, 4}, \/\/ Side 5\n {2, 4}, \/\/ Side 6\n {3, 4} \/\/ Side 7\n };\n\n\n\n\/\/ ------------------------------------------------------------\n\/\/ Pyramid5 class member functions\n\nbool Pyramid5::is_vertex(const unsigned int) const\n{\n return true;\n}\n\nbool Pyramid5::is_edge(const unsigned int) const\n{\n return false;\n}\n\nbool Pyramid5::is_face(const unsigned int) const\n{\n return false;\n}\n\nbool Pyramid5::is_node_on_side(const unsigned int n,\n const unsigned int s) const\n{\n libmesh_assert_less (s, n_sides());\n for (unsigned int i = 0; i != 4; ++i)\n if (side_nodes_map[s][i] == n)\n return true;\n return false;\n}\n\nbool Pyramid5::is_node_on_edge(const unsigned int n,\n const unsigned int e) const\n{\n libmesh_assert_less (e, n_edges());\n for (unsigned int i = 0; i != 2; ++i)\n if (edge_nodes_map[e][i] == n)\n return true;\n return false;\n}\n\n\n\nbool Pyramid5::has_affine_map() const\n{\n \/\/ Point v = this->point(3) - this->point(0);\n \/\/ return (v.relative_fuzzy_equals(this->point(2) - this->point(1)));\n return false;\n}\n\n\n\nUniquePtr Pyramid5::build_side (const unsigned int i,\n bool proxy) const\n{\n libmesh_assert_less (i, this->n_sides());\n\n if (proxy)\n {\n switch (i)\n {\n case 0:\n case 1:\n case 2:\n case 3:\n return UniquePtr(new Side(this,i));\n\n case 4:\n return UniquePtr(new Side(this,i));\n\n default:\n libmesh_error_msg(\"Invalid side i = \" << i);\n }\n }\n\n else\n {\n \/\/ Create NULL pointer to be initialized, returned later.\n Elem * face = libmesh_nullptr;\n\n switch (i)\n {\n case 0: \/\/ triangular face 1\n case 1: \/\/ triangular face 2\n case 2: \/\/ triangular face 3\n case 3: \/\/ triangular face 4\n {\n face = new Tri3;\n break;\n }\n case 4: \/\/ the quad face at z=0\n {\n face = new Quad4;\n break;\n }\n default:\n libmesh_error_msg(\"Invalid side i = \" << i);\n }\n\n face->subdomain_id() = this->subdomain_id();\n\n \/\/ Set the nodes\n for (unsigned n=0; nn_nodes(); ++n)\n face->set_node(n) = this->get_node(Pyramid5::side_nodes_map[i][n]);\n\n return UniquePtr(face);\n }\n\n libmesh_error_msg(\"We'll never get here!\");\n return UniquePtr();\n}\n\n\n\nUniquePtr Pyramid5::build_edge (const unsigned int i) const\n{\n libmesh_assert_less (i, this->n_edges());\n\n return UniquePtr(new SideEdge(this,i));\n}\n\n\n\nvoid Pyramid5::connectivity(const unsigned int libmesh_dbg_var(sc),\n const IOPackage iop,\n std::vector & conn) const\n{\n libmesh_assert(_nodes);\n libmesh_assert_less (sc, this->n_sub_elem());\n libmesh_assert_not_equal_to (iop, INVALID_IO_PACKAGE);\n\n switch (iop)\n {\n case TECPLOT:\n {\n conn.resize(8);\n conn[0] = this->node(0)+1;\n conn[1] = this->node(1)+1;\n conn[2] = this->node(2)+1;\n conn[3] = this->node(3)+1;\n conn[4] = this->node(4)+1;\n conn[5] = this->node(4)+1;\n conn[6] = this->node(4)+1;\n conn[7] = this->node(4)+1;\n return;\n }\n\n case VTK:\n {\n conn.resize(5);\n conn[0] = this->node(3);\n conn[1] = this->node(2);\n conn[2] = this->node(1);\n conn[3] = this->node(0);\n conn[4] = this->node(4);\n return;\n }\n\n default:\n libmesh_error_msg(\"Unsupported IO package \" << iop);\n }\n}\n\n\nReal Pyramid5::volume () const\n{\n \/\/ The pyramid with a bilinear base has volume given by the\n \/\/ formula in: \"Calculation of the Volume of a General Hexahedron\n \/\/ for Flow Predictions\", AIAA Journal v.23, no.6, 1984, p.954-\n Node * node0 = this->get_node(0);\n Node * node1 = this->get_node(1);\n Node * node2 = this->get_node(2);\n Node * node3 = this->get_node(3);\n Node * node4 = this->get_node(4);\n\n \/\/ Construct Various edge and diagonal vectors\n Point v40 ( *node0 - *node4 );\n Point v13 ( *node3 - *node1 );\n Point v02 ( *node2 - *node0 );\n Point v03 ( *node3 - *node0 );\n Point v01 ( *node1 - *node0 );\n\n \/\/ Finally, ready to return the volume!\n return (1.\/6.)*(v40*(v13.cross(v02))) + (1.\/12.)*(v02*(v01.cross(v03)));\n}\n\n} \/\/ namespace libMesh\n<|endoftext|>"} {"text":"\/*\n * Copyright © 2010 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n\/**\n * \\file ir_validate.cpp\n *\n * Attempts to verify that various invariants of the IR tree are true.\n *\n * In particular, at the moment it makes sure that no single\n * ir_instruction node except for ir_variable appears multiple times\n * in the ir tree. ir_variable does appear multiple times: Once as a\n * declaration in an exec_list, and multiple times as the endpoint of\n * a dereference chain.\n *\/\n\n#include \n#include \"ir.h\"\n#include \"ir_hierarchical_visitor.h\"\n#include \"hash_table.h\"\n\n\nclass ir_validate : public ir_hierarchical_visitor {\npublic:\n ir_validate()\n {\n this->ht = hash_table_ctor(0, hash_table_pointer_hash,\n\t\t\t\t hash_table_pointer_compare);\n\n this->current_function = NULL;\n\n this->callback = ir_validate::validate_ir;\n this->data = ht;\n }\n\n ~ir_validate()\n {\n hash_table_dtor(this->ht);\n }\n\n virtual ir_visitor_status visit(ir_variable *v);\n virtual ir_visitor_status visit(ir_dereference_variable *ir);\n\n virtual ir_visitor_status visit_enter(ir_function *ir);\n virtual ir_visitor_status visit_leave(ir_function *ir);\n virtual ir_visitor_status visit_enter(ir_function_signature *ir);\n\n static void validate_ir(ir_instruction *ir, void *data);\n\n ir_function *current_function;\n\n struct hash_table *ht;\n};\n\n\nir_visitor_status\nir_validate::visit(ir_dereference_variable *ir)\n{\n if ((ir->var == NULL) || (ir->var->as_variable() == NULL)) {\n printf(\"ir_dereference_variable @ %p does not specify a variable %p\\n\",\n\t ir, ir->var);\n abort();\n }\n\n if (hash_table_find(ht, ir->var) == NULL) {\n printf(\"ir_dereference_variable @ %p specifies undeclared variable \"\n\t \"`%s' @ %p\\n\",\n\t ir, ir->var->name, ir->var);\n abort();\n }\n\n this->validate_ir(ir, this->data);\n\n return visit_continue;\n}\n\n\nir_visitor_status\nir_validate::visit_enter(ir_function *ir)\n{\n \/* Function definitions cannot be nested.\n *\/\n if (this->current_function != NULL) {\n printf(\"Function definition nested inside another function \"\n\t \"definition:\\n\");\n printf(\"%s %p inside %s %p\\n\",\n\t ir->name, ir,\n\t this->current_function->name, this->current_function);\n abort();\n }\n\n \/* Store the current function hierarchy being traversed. This is used\n * by the function signature visitor to ensure that the signatures are\n * linked with the correct functions.\n *\/\n this->current_function = ir;\n\n this->validate_ir(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_validate::visit_leave(ir_function *ir)\n{\n (void) ir;\n\n this->current_function = NULL;\n return visit_continue;\n}\n\nir_visitor_status\nir_validate::visit_enter(ir_function_signature *ir)\n{\n if (this->current_function != ir->function()) {\n printf(\"Function signature nested inside wrong function \"\n\t \"definition:\\n\");\n printf(\"%p inside %s %p instead of %s %p\\n\",\n\t ir,\n\t this->current_function->name, this->current_function,\n\t ir->function_name(), ir->function());\n abort();\n }\n\n this->validate_ir(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_validate::visit(ir_variable *ir)\n{\n \/* An ir_variable is the one thing that can (and will) appear multiple times\n * in an IR tree. It is added to the hashtable so that it can be used\n * in the ir_dereference_variable handler to ensure that a variable is\n * declared before it is dereferenced.\n *\/\n hash_table_insert(ht, ir, ir);\n return visit_continue;\n}\n\nvoid\nir_validate::validate_ir(ir_instruction *ir, void *data)\n{\n struct hash_table *ht = (struct hash_table *) data;\n\n if (hash_table_find(ht, ir)) {\n printf(\"Instruction node present twice in ir tree:\\n\");\n ir->print();\n printf(\"\\n\");\n abort();\n }\n hash_table_insert(ht, ir, ir);\n}\n\nvoid\ncheck_node_type(ir_instruction *ir, void *data)\n{\n if (ir->ir_type <= ir_type_unset || ir->ir_type >= ir_type_max) {\n printf(\"Instruction node with unset type\\n\");\n ir->print(); printf(\"\\n\");\n }\n}\n\nvoid\nvalidate_ir_tree(exec_list *instructions)\n{\n ir_validate v;\n\n v.run(instructions);\n\n foreach_iter(exec_list_iterator, iter, *instructions) {\n ir_instruction *ir = (ir_instruction *)iter.get();\n\n visit_tree(ir, check_node_type, NULL);\n }\n}\nglsl2: Check that nodes in a valid tree aren't error-type.\/*\n * Copyright © 2010 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n\/**\n * \\file ir_validate.cpp\n *\n * Attempts to verify that various invariants of the IR tree are true.\n *\n * In particular, at the moment it makes sure that no single\n * ir_instruction node except for ir_variable appears multiple times\n * in the ir tree. ir_variable does appear multiple times: Once as a\n * declaration in an exec_list, and multiple times as the endpoint of\n * a dereference chain.\n *\/\n\n#include \n#include \"ir.h\"\n#include \"ir_hierarchical_visitor.h\"\n#include \"hash_table.h\"\n#include \"glsl_types.h\"\n\nclass ir_validate : public ir_hierarchical_visitor {\npublic:\n ir_validate()\n {\n this->ht = hash_table_ctor(0, hash_table_pointer_hash,\n\t\t\t\t hash_table_pointer_compare);\n\n this->current_function = NULL;\n\n this->callback = ir_validate::validate_ir;\n this->data = ht;\n }\n\n ~ir_validate()\n {\n hash_table_dtor(this->ht);\n }\n\n virtual ir_visitor_status visit(ir_variable *v);\n virtual ir_visitor_status visit(ir_dereference_variable *ir);\n\n virtual ir_visitor_status visit_enter(ir_function *ir);\n virtual ir_visitor_status visit_leave(ir_function *ir);\n virtual ir_visitor_status visit_enter(ir_function_signature *ir);\n\n static void validate_ir(ir_instruction *ir, void *data);\n\n ir_function *current_function;\n\n struct hash_table *ht;\n};\n\n\nir_visitor_status\nir_validate::visit(ir_dereference_variable *ir)\n{\n if ((ir->var == NULL) || (ir->var->as_variable() == NULL)) {\n printf(\"ir_dereference_variable @ %p does not specify a variable %p\\n\",\n\t ir, ir->var);\n abort();\n }\n\n if (hash_table_find(ht, ir->var) == NULL) {\n printf(\"ir_dereference_variable @ %p specifies undeclared variable \"\n\t \"`%s' @ %p\\n\",\n\t ir, ir->var->name, ir->var);\n abort();\n }\n\n this->validate_ir(ir, this->data);\n\n return visit_continue;\n}\n\n\nir_visitor_status\nir_validate::visit_enter(ir_function *ir)\n{\n \/* Function definitions cannot be nested.\n *\/\n if (this->current_function != NULL) {\n printf(\"Function definition nested inside another function \"\n\t \"definition:\\n\");\n printf(\"%s %p inside %s %p\\n\",\n\t ir->name, ir,\n\t this->current_function->name, this->current_function);\n abort();\n }\n\n \/* Store the current function hierarchy being traversed. This is used\n * by the function signature visitor to ensure that the signatures are\n * linked with the correct functions.\n *\/\n this->current_function = ir;\n\n this->validate_ir(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_validate::visit_leave(ir_function *ir)\n{\n (void) ir;\n\n this->current_function = NULL;\n return visit_continue;\n}\n\nir_visitor_status\nir_validate::visit_enter(ir_function_signature *ir)\n{\n if (this->current_function != ir->function()) {\n printf(\"Function signature nested inside wrong function \"\n\t \"definition:\\n\");\n printf(\"%p inside %s %p instead of %s %p\\n\",\n\t ir,\n\t this->current_function->name, this->current_function,\n\t ir->function_name(), ir->function());\n abort();\n }\n\n this->validate_ir(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_validate::visit(ir_variable *ir)\n{\n \/* An ir_variable is the one thing that can (and will) appear multiple times\n * in an IR tree. It is added to the hashtable so that it can be used\n * in the ir_dereference_variable handler to ensure that a variable is\n * declared before it is dereferenced.\n *\/\n hash_table_insert(ht, ir, ir);\n return visit_continue;\n}\n\nvoid\nir_validate::validate_ir(ir_instruction *ir, void *data)\n{\n struct hash_table *ht = (struct hash_table *) data;\n\n if (hash_table_find(ht, ir)) {\n printf(\"Instruction node present twice in ir tree:\\n\");\n ir->print();\n printf(\"\\n\");\n abort();\n }\n hash_table_insert(ht, ir, ir);\n}\n\nvoid\ncheck_node_type(ir_instruction *ir, void *data)\n{\n if (ir->ir_type <= ir_type_unset || ir->ir_type >= ir_type_max) {\n printf(\"Instruction node with unset type\\n\");\n ir->print(); printf(\"\\n\");\n }\n assert(ir->type != glsl_type::error_type);\n}\n\nvoid\nvalidate_ir_tree(exec_list *instructions)\n{\n ir_validate v;\n\n v.run(instructions);\n\n foreach_iter(exec_list_iterator, iter, *instructions) {\n ir_instruction *ir = (ir_instruction *)iter.get();\n\n visit_tree(ir, check_node_type, NULL);\n }\n}\n<|endoftext|>"} {"text":"\/*****************************************************************************\/\n\/* Sockets.cpp Copyright (c) Ladislav Zezula 2021 *\/\n\/*---------------------------------------------------------------------------*\/\n\/* Don't call this module \"Socket.cpp\", otherwise VS 2019 will not link it *\/\n\/* Socket functions for CascLib. *\/\n\/*---------------------------------------------------------------------------*\/\n\/* Date Ver Who Comment *\/\n\/* -------- ---- --- ------- *\/\n\/* 13.02.21 1.00 Lad Created *\/\n\/*****************************************************************************\/\n\n#define __CASCLIB_SELF__\n#include \"..\/CascLib.h\"\n#include \"..\/CascCommon.h\"\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Local variables\n\nCASC_SOCKET_CACHE SocketCache;\n\n\/\/-----------------------------------------------------------------------------\n\/\/ CASC_SOCKET functions\n\n\/\/ Guarantees that there is zero terminator after the response\nchar * CASC_SOCKET::ReadResponse(const char * request, size_t request_length, size_t * PtrLength)\n{\n CASC_MIME_HTTP HttpInfo;\n char * server_response = NULL;\n size_t total_received = 0;\n size_t block_increment = 0x8000;\n size_t buffer_size = block_increment;\n int bytes_received = 0;\n\n \/\/ Pre-set the result length\n if(PtrLength != NULL)\n PtrLength[0] = 0;\n if(request_length == 0)\n request_length = strlen(request);\n\n \/\/ Lock the socket\n CascLock(Lock);\n\n \/\/ Send the request to the remote host. On Linux, this call may send signal(SIGPIPE),\n \/\/ we need to prevend that by using the MSG_NOSIGNAL flag. On Windows, it fails normally.\n while(send(sock, request, (int)request_length, MSG_NOSIGNAL) == SOCKET_ERROR)\n {\n \/\/ If the connection was closed by the remote host, we try to reconnect\n if(ReconnectAfterShutdown(sock, remoteItem) == INVALID_SOCKET)\n {\n SetCascError(ERROR_NETWORK_NOT_AVAILABLE);\n CascUnlock(Lock);\n return NULL;\n }\n }\n\n \/\/ Allocate buffer for server response. Allocate one extra byte for zero terminator\n if((server_response = CASC_ALLOC(buffer_size + 1)) != NULL)\n {\n for(;;)\n {\n \/\/ Reallocate the buffer size, if needed\n if(total_received == buffer_size)\n {\n if((server_response = CASC_REALLOC(char, server_response, buffer_size + block_increment + 1)) == NULL)\n {\n SetCascError(ERROR_NOT_ENOUGH_MEMORY);\n CascUnlock(Lock);\n return NULL;\n }\n buffer_size += block_increment;\n }\n\n \/\/ Receive the next part of the response, up to buffer size\n \/\/ Return value 0 means \"connection closed\", -1 means an error\n bytes_received = recv(sock, server_response + total_received, (int)(buffer_size - total_received), 0);\n if(bytes_received <= 0)\n break;\n\n \/\/ Append the number of bytes received. Also terminate response with zero\n total_received += bytes_received;\n server_response[total_received] = 0;\n\n \/\/ On a HTTP protocol, we need to check whether we received all data\n if(HttpInfo.IsDataComplete(server_response, total_received))\n break;\n }\n }\n\n \/\/ Unlock the socket\n CascUnlock(Lock);\n\n \/\/ Give the result to the caller\n if(PtrLength != NULL)\n PtrLength[0] = total_received;\n return server_response;\n}\n\nDWORD CASC_SOCKET::AddRef()\n{\n return CascInterlockedIncrement(&dwRefCount);\n}\n\nvoid CASC_SOCKET::Release()\n{\n \/\/ Note: If this is a cached socket, there will be extra reference from the cache\n if(CascInterlockedDecrement(&dwRefCount) == 0)\n {\n Delete();\n }\n}\n\nint CASC_SOCKET::GetSockError()\n{\n#ifdef CASCLIB_PLATFORM_WINDOWS\n return WSAGetLastError();\n#else\n return errno;\n#endif\n}\n\nDWORD CASC_SOCKET::GetAddrInfoWrapper(const char * hostName, unsigned portNum, PADDRINFO hints, PADDRINFO * ppResult)\n{\n char portNumString[16];\n\n \/\/ Prepare the port number\n CascStrPrintf(portNumString, _countof(portNumString), \"%d\", portNum);\n\n \/\/ Attempt to connect\n for(;;)\n {\n \/\/ Attempt to call the addrinfo\n DWORD dwErrCode = getaddrinfo(hostName, portNumString, hints, ppResult);\n\n \/\/ Error-specific handling\n switch(dwErrCode)\n {\n#ifdef CASCLIB_PLATFORM_WINDOWS\n case WSANOTINITIALISED: \/\/ Windows-specific: WSAStartup not called\n {\n WSADATA wsd;\n\n WSAStartup(MAKEWORD(2, 2), &wsd);\n continue;\n }\n#endif\n case EAI_AGAIN: \/\/ Temporary error, try again\n continue;\n\n default: \/\/ Any other result, incl. ERROR_SUCCESS\n return dwErrCode;\n }\n }\n}\n\nSOCKET CASC_SOCKET::CreateAndConnect(addrinfo * remoteItem)\n{\n SOCKET sock;\n\n \/\/ Create new socket\n \/\/ On error, returns returns INVALID_SOCKET (-1) on Windows, -1 on Linux\n if((sock = socket(remoteItem->ai_family, remoteItem->ai_socktype, remoteItem->ai_protocol)) > 0)\n {\n \/\/ Connect to the remote host\n \/\/ On error, returns SOCKET_ERROR (-1) on Windows, -1 on Linux\n if(connect(sock, remoteItem->ai_addr, (int)remoteItem->ai_addrlen) == 0)\n return sock;\n\n \/\/ Failed. Close the socket and return 0\n closesocket(sock);\n sock = INVALID_SOCKET;\n }\n\n return sock;\n}\n\nSOCKET CASC_SOCKET::ReconnectAfterShutdown(SOCKET & sock, addrinfo * remoteItem)\n{\n \/\/ Retrieve the error code related to previous socket operation\n switch(GetSockError())\n {\n case EPIPE: \/\/ Non-Windows\n case WSAECONNRESET: \/\/ Windows\n {\n \/\/ Close the old socket\n if(sock != INVALID_SOCKET)\n closesocket(sock);\n\n \/\/ Attempt to reconnect\n sock = CreateAndConnect(remoteItem);\n return sock;\n }\n }\n\n \/\/ Another problem\n return INVALID_SOCKET;\n}\n\nPCASC_SOCKET CASC_SOCKET::New(addrinfo * remoteList, addrinfo * remoteItem, const char * hostName, unsigned portNum, SOCKET sock)\n{\n PCASC_SOCKET pSocket;\n size_t length = strlen(hostName);\n\n \/\/ Allocate enough bytes\n pSocket = (PCASC_SOCKET)CASC_ALLOC(sizeof(CASC_SOCKET) + length);\n if(pSocket != NULL)\n {\n \/\/ Fill the entire object with zero\n memset(pSocket, 0, sizeof(CASC_SOCKET) + length);\n pSocket->remoteList = remoteList;\n pSocket->remoteItem = remoteItem;\n pSocket->dwRefCount = 1;\n pSocket->portNum = portNum;\n pSocket->sock = sock;\n\n \/\/ Init the remote host name\n CascStrCopy((char *)pSocket->hostName, length + 1, hostName);\n\n \/\/ Init the socket lock\n CascInitLock(pSocket->Lock);\n }\n\n return pSocket;\n}\n\nPCASC_SOCKET CASC_SOCKET::Connect(const char * hostName, unsigned portNum)\n{\n PCASC_SOCKET pSocket;\n addrinfo * remoteList;\n addrinfo * remoteItem;\n addrinfo hints = {0};\n SOCKET sock;\n int nErrCode;\n\n \/\/ Retrieve the information about the remote host\n \/\/ This will fail immediately if there is no connection to the internet\n hints.ai_family = AF_INET;\n hints.ai_socktype = SOCK_STREAM;\n nErrCode = GetAddrInfoWrapper(hostName, portNum, &hints, &remoteList);\n\n \/\/ Handle error code\n if(nErrCode == 0)\n {\n \/\/ Try to connect to any address provided by the getaddrinfo()\n for(remoteItem = remoteList; remoteItem != NULL; remoteItem = remoteItem->ai_next)\n {\n \/\/ Create new socket and connect to the remote host\n if((sock = CreateAndConnect(remoteItem)) != 0)\n {\n \/\/ Create new instance of the CASC_SOCKET structure\n if((pSocket = CASC_SOCKET::New(remoteList, remoteItem, hostName, portNum, sock)) != NULL)\n {\n return pSocket;\n }\n\n \/\/ Close the socket\n closesocket(sock);\n }\n }\n\n \/\/ Couldn't find a network\n nErrCode = ERROR_NETWORK_NOT_AVAILABLE;\n }\n\n SetCascError(nErrCode);\n return NULL;\n}\n\nvoid CASC_SOCKET::Delete()\n{\n PCASC_SOCKET pThis = this;\n\n \/\/ Remove the socket from the cache\n if(pCache != NULL)\n pCache->UnlinkSocket(this);\n pCache = NULL;\n\n \/\/ Close the socket, if any\n if(sock != 0)\n closesocket(sock);\n sock = 0;\n\n \/\/ Free the lock\n CascFreeLock(Lock);\n\n \/\/ Free the socket itself\n CASC_FREE(pThis);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ The CASC_SOCKET_CACHE class\n\nCASC_SOCKET_CACHE::CASC_SOCKET_CACHE()\n{\n pFirst = pLast = NULL;\n dwRefCount = 0;\n}\n\nCASC_SOCKET_CACHE::~CASC_SOCKET_CACHE()\n{\n PurgeAll();\n}\n\nPCASC_SOCKET CASC_SOCKET_CACHE::Find(const char * hostName, unsigned portNum)\n{\n PCASC_SOCKET pSocket;\n\n for(pSocket = pFirst; pSocket != NULL; pSocket = pSocket->pNext)\n {\n if(!_stricmp(pSocket->hostName, hostName) && (pSocket->portNum == portNum))\n break;\n }\n\n return pSocket;\n}\n\nPCASC_SOCKET CASC_SOCKET_CACHE::InsertSocket(PCASC_SOCKET pSocket)\n{\n if(pSocket != NULL && pSocket->pCache == NULL)\n {\n \/\/ Do we have caching turned on?\n if(dwRefCount > 0)\n {\n \/\/ Insert one reference to the socket to mark it as cached\n pSocket->AddRef();\n\n \/\/ Insert the socket to the chain\n if(pFirst == NULL && pLast == NULL)\n {\n pFirst = pLast = pSocket;\n }\n else\n {\n pSocket->pPrev = pLast;\n pLast->pNext = pSocket;\n pLast = pSocket;\n }\n\n \/\/ Mark the socket as cached\n pSocket->pCache = this;\n }\n }\n\n return pSocket;\n}\n\nvoid CASC_SOCKET_CACHE::UnlinkSocket(PCASC_SOCKET pSocket)\n{\n \/\/ Only if it's a valid socket\n if(pSocket != NULL)\n {\n \/\/ Check the first and the last items\n if(pSocket == pFirst)\n pFirst = pSocket->pNext;\n if(pSocket == pLast)\n pLast = pSocket->pPrev;\n\n \/\/ Disconnect the socket from the chain\n if(pSocket->pPrev != NULL)\n pSocket->pPrev->pNext = pSocket->pNext;\n if(pSocket->pNext != NULL)\n pSocket->pNext->pPrev = pSocket->pPrev;\n }\n}\n\nvoid CASC_SOCKET_CACHE::SetCaching(bool bAddRef)\n{\n PCASC_SOCKET pSocket;\n PCASC_SOCKET pNext;\n\n \/\/ We need to increment reference count for each enabled caching\n if(bAddRef)\n {\n \/\/ Add one reference to all currently held sockets\n if(dwRefCount == 0)\n {\n for(pSocket = pFirst; pSocket != NULL; pSocket = pSocket->pNext)\n pSocket->AddRef();\n }\n\n \/\/ Increment of references for the future sockets\n CascInterlockedIncrement(&dwRefCount);\n }\n else\n {\n \/\/ Sanity check for multiple calls to dereference\n assert(dwRefCount > 0);\n\n \/\/ Dereference the reference count. If drops to zero, dereference all sockets as well\n if(CascInterlockedDecrement(&dwRefCount) == 0)\n {\n for(pSocket = pFirst; pSocket != NULL; pSocket = pNext)\n {\n pNext = pSocket->pNext;\n pSocket->Release();\n }\n }\n }\n}\n\nvoid CASC_SOCKET_CACHE::PurgeAll()\n{\n PCASC_SOCKET pSocket;\n PCASC_SOCKET pNext;\n\n \/\/ Dereference all current sockets\n for(pSocket = pFirst; pSocket != NULL; pSocket = pNext)\n {\n pNext = pSocket->pNext;\n pSocket->Delete();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Public functions\n\nPCASC_SOCKET sockets_connect(const char * hostName, unsigned portNum)\n{\n PCASC_SOCKET pSocket;\n\n \/\/ Try to find the item in the cache\n if((pSocket = SocketCache.Find(hostName, portNum)) != NULL)\n {\n pSocket->AddRef();\n }\n else\n {\n \/\/ Create new socket and connect it to the remote host\n pSocket = CASC_SOCKET::Connect(hostName, portNum);\n\n \/\/ Insert it to the cache, if it's a HTTP connection\n if(pSocket->portNum == CASC_PORT_HTTP)\n pSocket = SocketCache.InsertSocket(pSocket);\n }\n\n return pSocket;\n}\n\nvoid sockets_set_caching(bool caching)\n{\n SocketCache.SetCaching(caching);\n}\nFix build with clang\/*****************************************************************************\/\n\/* Sockets.cpp Copyright (c) Ladislav Zezula 2021 *\/\n\/*---------------------------------------------------------------------------*\/\n\/* Don't call this module \"Socket.cpp\", otherwise VS 2019 will not link it *\/\n\/* Socket functions for CascLib. *\/\n\/*---------------------------------------------------------------------------*\/\n\/* Date Ver Who Comment *\/\n\/* -------- ---- --- ------- *\/\n\/* 13.02.21 1.00 Lad Created *\/\n\/*****************************************************************************\/\n\n#define __CASCLIB_SELF__\n#include \"..\/CascLib.h\"\n#include \"..\/CascCommon.h\"\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Local variables\n\nCASC_SOCKET_CACHE SocketCache;\n\n\/\/-----------------------------------------------------------------------------\n\/\/ CASC_SOCKET functions\n\n\/\/ Guarantees that there is zero terminator after the response\nchar * CASC_SOCKET::ReadResponse(const char * request, size_t request_length, size_t * PtrLength)\n{\n CASC_MIME_HTTP HttpInfo;\n char * server_response = NULL;\n size_t total_received = 0;\n size_t block_increment = 0x8000;\n size_t buffer_size = block_increment;\n int bytes_received = 0;\n\n \/\/ Pre-set the result length\n if(PtrLength != NULL)\n PtrLength[0] = 0;\n if(request_length == 0)\n request_length = strlen(request);\n\n \/\/ Lock the socket\n CascLock(Lock);\n\n \/\/ Send the request to the remote host. On Linux, this call may send signal(SIGPIPE),\n \/\/ we need to prevend that by using the MSG_NOSIGNAL flag. On Windows, it fails normally.\n while(send(sock, request, (int)request_length, MSG_NOSIGNAL) == SOCKET_ERROR)\n {\n \/\/ If the connection was closed by the remote host, we try to reconnect\n if(ReconnectAfterShutdown(sock, remoteItem) == INVALID_SOCKET)\n {\n SetCascError(ERROR_NETWORK_NOT_AVAILABLE);\n CascUnlock(Lock);\n return NULL;\n }\n }\n\n \/\/ Allocate buffer for server response. Allocate one extra byte for zero terminator\n if((server_response = CASC_ALLOC(buffer_size + 1)) != NULL)\n {\n for(;;)\n {\n \/\/ Reallocate the buffer size, if needed\n if(total_received == buffer_size)\n {\n if((server_response = CASC_REALLOC(char, server_response, buffer_size + block_increment + 1)) == NULL)\n {\n SetCascError(ERROR_NOT_ENOUGH_MEMORY);\n CascUnlock(Lock);\n return NULL;\n }\n buffer_size += block_increment;\n }\n\n \/\/ Receive the next part of the response, up to buffer size\n \/\/ Return value 0 means \"connection closed\", -1 means an error\n bytes_received = recv(sock, server_response + total_received, (int)(buffer_size - total_received), 0);\n if(bytes_received <= 0)\n break;\n\n \/\/ Append the number of bytes received. Also terminate response with zero\n total_received += bytes_received;\n server_response[total_received] = 0;\n\n \/\/ On a HTTP protocol, we need to check whether we received all data\n if(HttpInfo.IsDataComplete(server_response, total_received))\n break;\n }\n }\n\n \/\/ Unlock the socket\n CascUnlock(Lock);\n\n \/\/ Give the result to the caller\n if(PtrLength != NULL)\n PtrLength[0] = total_received;\n return server_response;\n}\n\nDWORD CASC_SOCKET::AddRef()\n{\n return CascInterlockedIncrement(&dwRefCount);\n}\n\nvoid CASC_SOCKET::Release()\n{\n \/\/ Note: If this is a cached socket, there will be extra reference from the cache\n if(CascInterlockedDecrement(&dwRefCount) == 0)\n {\n Delete();\n }\n}\n\nint CASC_SOCKET::GetSockError()\n{\n#ifdef CASCLIB_PLATFORM_WINDOWS\n return WSAGetLastError();\n#else\n return errno;\n#endif\n}\n\nDWORD CASC_SOCKET::GetAddrInfoWrapper(const char * hostName, unsigned portNum, PADDRINFO hints, PADDRINFO * ppResult)\n{\n char portNumString[16];\n\n \/\/ Prepare the port number\n CascStrPrintf(portNumString, _countof(portNumString), \"%d\", portNum);\n\n \/\/ Attempt to connect\n for(;;)\n {\n \/\/ Attempt to call the addrinfo\n DWORD dwErrCode = getaddrinfo(hostName, portNumString, hints, ppResult);\n\n \/\/ Error-specific handling\n switch(dwErrCode)\n {\n#ifdef CASCLIB_PLATFORM_WINDOWS\n case WSANOTINITIALISED: \/\/ Windows-specific: WSAStartup not called\n {\n WSADATA wsd;\n\n WSAStartup(MAKEWORD(2, 2), &wsd);\n continue;\n }\n#endif\n case (DWORD)EAI_AGAIN: \/\/ Temporary error, try again\n continue;\n\n default: \/\/ Any other result, incl. ERROR_SUCCESS\n return dwErrCode;\n }\n }\n}\n\nSOCKET CASC_SOCKET::CreateAndConnect(addrinfo * remoteItem)\n{\n SOCKET sock;\n\n \/\/ Create new socket\n \/\/ On error, returns returns INVALID_SOCKET (-1) on Windows, -1 on Linux\n if((sock = socket(remoteItem->ai_family, remoteItem->ai_socktype, remoteItem->ai_protocol)) > 0)\n {\n \/\/ Connect to the remote host\n \/\/ On error, returns SOCKET_ERROR (-1) on Windows, -1 on Linux\n if(connect(sock, remoteItem->ai_addr, (int)remoteItem->ai_addrlen) == 0)\n return sock;\n\n \/\/ Failed. Close the socket and return 0\n closesocket(sock);\n sock = INVALID_SOCKET;\n }\n\n return sock;\n}\n\nSOCKET CASC_SOCKET::ReconnectAfterShutdown(SOCKET & sock, addrinfo * remoteItem)\n{\n \/\/ Retrieve the error code related to previous socket operation\n switch(GetSockError())\n {\n case EPIPE: \/\/ Non-Windows\n case WSAECONNRESET: \/\/ Windows\n {\n \/\/ Close the old socket\n if(sock != INVALID_SOCKET)\n closesocket(sock);\n\n \/\/ Attempt to reconnect\n sock = CreateAndConnect(remoteItem);\n return sock;\n }\n }\n\n \/\/ Another problem\n return INVALID_SOCKET;\n}\n\nPCASC_SOCKET CASC_SOCKET::New(addrinfo * remoteList, addrinfo * remoteItem, const char * hostName, unsigned portNum, SOCKET sock)\n{\n PCASC_SOCKET pSocket;\n size_t length = strlen(hostName);\n\n \/\/ Allocate enough bytes\n pSocket = (PCASC_SOCKET)CASC_ALLOC(sizeof(CASC_SOCKET) + length);\n if(pSocket != NULL)\n {\n \/\/ Fill the entire object with zero\n memset(pSocket, 0, sizeof(CASC_SOCKET) + length);\n pSocket->remoteList = remoteList;\n pSocket->remoteItem = remoteItem;\n pSocket->dwRefCount = 1;\n pSocket->portNum = portNum;\n pSocket->sock = sock;\n\n \/\/ Init the remote host name\n CascStrCopy((char *)pSocket->hostName, length + 1, hostName);\n\n \/\/ Init the socket lock\n CascInitLock(pSocket->Lock);\n }\n\n return pSocket;\n}\n\nPCASC_SOCKET CASC_SOCKET::Connect(const char * hostName, unsigned portNum)\n{\n PCASC_SOCKET pSocket;\n addrinfo * remoteList;\n addrinfo * remoteItem;\n addrinfo hints = {0};\n SOCKET sock;\n int nErrCode;\n\n \/\/ Retrieve the information about the remote host\n \/\/ This will fail immediately if there is no connection to the internet\n hints.ai_family = AF_INET;\n hints.ai_socktype = SOCK_STREAM;\n nErrCode = GetAddrInfoWrapper(hostName, portNum, &hints, &remoteList);\n\n \/\/ Handle error code\n if(nErrCode == 0)\n {\n \/\/ Try to connect to any address provided by the getaddrinfo()\n for(remoteItem = remoteList; remoteItem != NULL; remoteItem = remoteItem->ai_next)\n {\n \/\/ Create new socket and connect to the remote host\n if((sock = CreateAndConnect(remoteItem)) != 0)\n {\n \/\/ Create new instance of the CASC_SOCKET structure\n if((pSocket = CASC_SOCKET::New(remoteList, remoteItem, hostName, portNum, sock)) != NULL)\n {\n return pSocket;\n }\n\n \/\/ Close the socket\n closesocket(sock);\n }\n }\n\n \/\/ Couldn't find a network\n nErrCode = ERROR_NETWORK_NOT_AVAILABLE;\n }\n\n SetCascError(nErrCode);\n return NULL;\n}\n\nvoid CASC_SOCKET::Delete()\n{\n PCASC_SOCKET pThis = this;\n\n \/\/ Remove the socket from the cache\n if(pCache != NULL)\n pCache->UnlinkSocket(this);\n pCache = NULL;\n\n \/\/ Close the socket, if any\n if(sock != 0)\n closesocket(sock);\n sock = 0;\n\n \/\/ Free the lock\n CascFreeLock(Lock);\n\n \/\/ Free the socket itself\n CASC_FREE(pThis);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ The CASC_SOCKET_CACHE class\n\nCASC_SOCKET_CACHE::CASC_SOCKET_CACHE()\n{\n pFirst = pLast = NULL;\n dwRefCount = 0;\n}\n\nCASC_SOCKET_CACHE::~CASC_SOCKET_CACHE()\n{\n PurgeAll();\n}\n\nPCASC_SOCKET CASC_SOCKET_CACHE::Find(const char * hostName, unsigned portNum)\n{\n PCASC_SOCKET pSocket;\n\n for(pSocket = pFirst; pSocket != NULL; pSocket = pSocket->pNext)\n {\n if(!_stricmp(pSocket->hostName, hostName) && (pSocket->portNum == portNum))\n break;\n }\n\n return pSocket;\n}\n\nPCASC_SOCKET CASC_SOCKET_CACHE::InsertSocket(PCASC_SOCKET pSocket)\n{\n if(pSocket != NULL && pSocket->pCache == NULL)\n {\n \/\/ Do we have caching turned on?\n if(dwRefCount > 0)\n {\n \/\/ Insert one reference to the socket to mark it as cached\n pSocket->AddRef();\n\n \/\/ Insert the socket to the chain\n if(pFirst == NULL && pLast == NULL)\n {\n pFirst = pLast = pSocket;\n }\n else\n {\n pSocket->pPrev = pLast;\n pLast->pNext = pSocket;\n pLast = pSocket;\n }\n\n \/\/ Mark the socket as cached\n pSocket->pCache = this;\n }\n }\n\n return pSocket;\n}\n\nvoid CASC_SOCKET_CACHE::UnlinkSocket(PCASC_SOCKET pSocket)\n{\n \/\/ Only if it's a valid socket\n if(pSocket != NULL)\n {\n \/\/ Check the first and the last items\n if(pSocket == pFirst)\n pFirst = pSocket->pNext;\n if(pSocket == pLast)\n pLast = pSocket->pPrev;\n\n \/\/ Disconnect the socket from the chain\n if(pSocket->pPrev != NULL)\n pSocket->pPrev->pNext = pSocket->pNext;\n if(pSocket->pNext != NULL)\n pSocket->pNext->pPrev = pSocket->pPrev;\n }\n}\n\nvoid CASC_SOCKET_CACHE::SetCaching(bool bAddRef)\n{\n PCASC_SOCKET pSocket;\n PCASC_SOCKET pNext;\n\n \/\/ We need to increment reference count for each enabled caching\n if(bAddRef)\n {\n \/\/ Add one reference to all currently held sockets\n if(dwRefCount == 0)\n {\n for(pSocket = pFirst; pSocket != NULL; pSocket = pSocket->pNext)\n pSocket->AddRef();\n }\n\n \/\/ Increment of references for the future sockets\n CascInterlockedIncrement(&dwRefCount);\n }\n else\n {\n \/\/ Sanity check for multiple calls to dereference\n assert(dwRefCount > 0);\n\n \/\/ Dereference the reference count. If drops to zero, dereference all sockets as well\n if(CascInterlockedDecrement(&dwRefCount) == 0)\n {\n for(pSocket = pFirst; pSocket != NULL; pSocket = pNext)\n {\n pNext = pSocket->pNext;\n pSocket->Release();\n }\n }\n }\n}\n\nvoid CASC_SOCKET_CACHE::PurgeAll()\n{\n PCASC_SOCKET pSocket;\n PCASC_SOCKET pNext;\n\n \/\/ Dereference all current sockets\n for(pSocket = pFirst; pSocket != NULL; pSocket = pNext)\n {\n pNext = pSocket->pNext;\n pSocket->Delete();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Public functions\n\nPCASC_SOCKET sockets_connect(const char * hostName, unsigned portNum)\n{\n PCASC_SOCKET pSocket;\n\n \/\/ Try to find the item in the cache\n if((pSocket = SocketCache.Find(hostName, portNum)) != NULL)\n {\n pSocket->AddRef();\n }\n else\n {\n \/\/ Create new socket and connect it to the remote host\n pSocket = CASC_SOCKET::Connect(hostName, portNum);\n\n \/\/ Insert it to the cache, if it's a HTTP connection\n if(pSocket->portNum == CASC_PORT_HTTP)\n pSocket = SocketCache.InsertSocket(pSocket);\n }\n\n return pSocket;\n}\n\nvoid sockets_set_caching(bool caching)\n{\n SocketCache.SetCaching(caching);\n}\n<|endoftext|>"} {"text":"\/*\n* Copyright (c) 2003-2016 Rony Shapiro .\n* All rights reserved. Use of the code is allowed under the\n* Artistic License 2.0 terms, as specified in the LICENSE file\n* distributed with this code, or available from\n* http:\/\/www.opensource.org\/licenses\/artistic-license-2.0.php\n*\/\n\/\/ OptionsSystem.cpp : implementation file\n\/\/\n\n#include \"stdafx.h\"\n#include \"passwordsafe.h\"\n#include \"ThisMfcApp.h\" \/\/ For Help\n#include \"Options_PropertySheet.h\"\n#include \"GeneralMsgBox.h\"\n\n#include \"core\/PwsPlatform.h\"\n#include \"core\/PWSprefs.h\"\n\n#include \"resource.h\"\n#include \"resource2.h\" \/\/ Menu, Toolbar & Accelerator resources\n#include \"resource3.h\" \/\/ String resources\n\n#include \"OptionsSystem.h\" \/\/ Must be after resource.h\n\nextern bool OfferConfigMigration();\nextern bool PerformConfigMigration();\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#undef THIS_FILE\nstatic char THIS_FILE[] = __FILE__;\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ COptionsSystem property page\n\nbool COptionsSystem::m_bShowConfigFile = false;\n\nIMPLEMENT_DYNAMIC(COptionsSystem, COptions_PropertyPage)\n\nCOptionsSystem::COptionsSystem(CWnd *pParent, st_Opt_master_data *pOPTMD) \n: COptions_PropertyPage(pParent,\n COptionsSystem::IDD, COptionsSystem::IDD_SHORT,\n pOPTMD),\n m_DeleteRegistry(FALSE), m_saveDeleteRegistry(FALSE),\n m_Migrate2Appdata(FALSE), m_saveMigrate2Appdata(FALSE)\n{\n#ifdef _DEBUG\n m_bShowConfigFile = true;\n#endif\n\n m_UseSystemTray = M_UseSystemTray();\n m_HideSystemTray = M_HideSystemTray();\n m_Startup = M_Startup();\n m_MRUOnFileMenu = M_MRUOnFileMenu();\n m_DefaultOpenRO = M_DefaultOpenRO();\n m_MultipleInstances = M_MultipleInstances();\n m_MaxREItems = M_MaxREItems();\n m_MaxMRUItems = M_MaxMRUItems();\n m_InitialHotkeyState = M_AppHotKeyEnabled();\n}\n\nvoid COptionsSystem::DoDataExchange(CDataExchange *pDX)\n{\n CPWPropertyPage::DoDataExchange(pDX);\n\n \/\/{{AFX_DATA_MAP(COptionsSystem)\n DDX_Text(pDX, IDC_MAXREITEMS, m_MaxREItems);\n DDV_MinMaxInt(pDX, m_MaxREItems, 0, ID_TRAYRECENT_ENTRYMAX - ID_TRAYRECENT_ENTRY1 + 1);\n DDX_Check(pDX, IDC_DEFPWUSESYSTRAY, m_UseSystemTray);\n DDX_Check(pDX, IDC_DEFPWHIDESYSTRAY, m_HideSystemTray);\n DDX_Check(pDX, IDC_STARTUP, m_Startup);\n DDX_Text(pDX, IDC_MAXMRUITEMS, m_MaxMRUItems);\n DDV_MinMaxInt(pDX, m_MaxMRUItems, 0, ID_FILE_MRU_ENTRYMAX - ID_FILE_MRU_ENTRY1 + 1);\n DDX_Check(pDX, IDC_MRU_ONFILEMENU, m_MRUOnFileMenu);\n DDX_Check(pDX, IDC_REGDEL, m_DeleteRegistry);\n DDX_Check(pDX, IDC_MIGRATETOAPPDATA, m_Migrate2Appdata);\n DDX_Check(pDX, IDC_DEFAULTOPENRO, m_DefaultOpenRO);\n DDX_Check(pDX, IDC_MULTIPLEINSTANCES, m_MultipleInstances);\n\n DDX_Control(pDX, IDC_REGDELHELP, m_Help1);\n DDX_Control(pDX, IDC_MIGRATETOAPPDATAHELP, m_Help2);\n \/\/}}AFX_DATA_MAP\n}\n\nBEGIN_MESSAGE_MAP(COptionsSystem, CPWPropertyPage)\n \/\/{{AFX_MSG_MAP(COptionsSystem)\n ON_BN_CLICKED(ID_HELP, OnHelp)\n\n ON_BN_CLICKED(IDC_DEFPWUSESYSTRAY, OnUseSystemTray)\n ON_BN_CLICKED(IDC_STARTUP, OnStartup)\n ON_BN_CLICKED(IDC_REGDEL, OnSetDeleteRegistry)\n ON_BN_CLICKED(IDC_MIGRATETOAPPDATA, OnSetMigrate2Appdata)\n ON_BN_CLICKED(IDC_APPLYCONFIGCHANGES, OnApplyConfigChanges)\n ON_MESSAGE(PSM_QUERYSIBLINGS, OnQuerySiblings)\n \/\/}}AFX_MSG_MAP\nEND_MESSAGE_MAP()\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ COptionsSystem message handlers\n\n\nBOOL COptionsSystem::OnInitDialog() \n{\n COptions_PropertyPage::OnInitDialog();\n\n PWSprefs *prefs = PWSprefs::GetInstance();\n if (!m_bShowConfigFile) {\n GetDlgItem(IDC_STATIC_CONFIGFILE)->ShowWindow(SW_HIDE);\n GetDlgItem(IDC_STATIC_RWSTATUS)->ShowWindow(SW_HIDE);\n GetDlgItem(IDC_CONFIGFILE)->ShowWindow(SW_HIDE);\n } else {\n PWSprefs::ConfigOption configoption;\n std::wstring wsCF = prefs->GetConfigFile(configoption);\n std::wstring wsCO(L\"\");\n switch (configoption) {\n case PWSprefs::CF_NONE:\n LoadAString(wsCF, IDS_NONE);\n break;\n case PWSprefs::CF_REGISTRY:\n LoadAString(wsCF, IDS_REGISTRY);\n break;\n case PWSprefs::CF_FILE_RO:\n LoadAString(wsCO, IDS_READ_ONLY);\n break;\n case PWSprefs::CF_FILE_RW:\n case PWSprefs::CF_FILE_RW_NEW:\n LoadAString(wsCO, IDS_READ_WRITE);\n break;\n default:\n ASSERT(0);\n }\n GetDlgItem(IDC_CONFIGFILE)->SetWindowText(wsCF.c_str());\n GetDlgItem(IDC_STATIC_RWSTATUS)->SetWindowText(wsCO.c_str());\n }\n\n bool bofferdeleteregistry = prefs->OfferDeleteRegistry();\n\n bool boffermigrate2appdata = OfferConfigMigration();\n\n if (!bofferdeleteregistry) {\n GetDlgItem(IDC_REGDEL)->ShowWindow(SW_HIDE);\n GetDlgItem(IDC_REGDEL)->EnableWindow(FALSE);\n }\n\n if (!boffermigrate2appdata) {\n GetDlgItem(IDC_MIGRATETOAPPDATA)->ShowWindow(SW_HIDE);\n GetDlgItem(IDC_MIGRATETOAPPDATA)->EnableWindow(FALSE);\n }\n\n if (!bofferdeleteregistry && !boffermigrate2appdata) {\n GetDlgItem(IDC_CONFIG_GRP)->ShowWindow(SW_HIDE);\n GetDlgItem(IDC_APPLYCONFIGCHANGES)->ShowWindow(SW_HIDE);\n } else {\n GetDlgItem(IDC_APPLYCONFIGCHANGES)->ShowWindow(SW_SHOW);\n }\n\n GetDlgItem(IDC_APPLYCONFIGCHANGES)->EnableWindow(FALSE);\n\n CSpinButtonCtrl *pspin = (CSpinButtonCtrl *)GetDlgItem(IDC_RESPIN);\n\n pspin->SetBuddy(GetDlgItem(IDC_MAXREITEMS));\n pspin->SetRange(0, ID_TRAYRECENT_ENTRYMAX - ID_TRAYRECENT_ENTRY1 + 1);\n pspin->SetBase(10);\n pspin->SetPos(m_MaxREItems);\n\n pspin = (CSpinButtonCtrl *)GetDlgItem(IDC_MRUSPIN);\n\n pspin->SetBuddy(GetDlgItem(IDC_MAXMRUITEMS));\n pspin->SetRange(0, ID_FILE_MRU_ENTRYMAX - ID_FILE_MRU_ENTRY1 + 1);\n pspin->SetBase(10);\n pspin->SetPos(m_MaxMRUItems);\n\n OnUseSystemTray();\n\n if (InitToolTip(TTS_BALLOON | TTS_NOPREFIX, 0)) {\n m_Help1.Init(IDB_QUESTIONMARK);\n m_Help2.Init(IDB_QUESTIONMARK);\n\n \/\/ Note naming convention: string IDS_xxx corresponds to control IDC_xxx_HELP\n AddTool(IDC_REGDELHELP, IDS_REGDEL);\n AddTool(IDC_MIGRATETOAPPDATAHELP, IDS_MIGRATETOAPPDATA);\n ActivateToolTip();\n } else {\n m_Help1.EnableWindow(FALSE);\n m_Help1.ShowWindow(SW_HIDE);\n m_Help2.EnableWindow(FALSE);\n m_Help2.ShowWindow(SW_HIDE);\n }\n\n if (!boffermigrate2appdata) {\n m_Help2.EnableWindow(FALSE);\n m_Help2.ShowWindow(SW_HIDE);\n }\n\n return TRUE; \/\/ return TRUE unless you set the focus to a control\n \/\/ EXCEPTION: OCX Property Pages should return FALSE\n}\n\nLRESULT COptionsSystem::OnQuerySiblings(WPARAM wParam, LPARAM )\n{\n UpdateData(TRUE);\n\n \/\/ Have any of my fields been changed?\n switch (wParam) {\n case PP_DATA_CHANGED:\n if (M_UseSystemTray() != m_UseSystemTray ||\n M_HideSystemTray() != m_HideSystemTray ||\n (m_UseSystemTray == TRUE &&\n M_MaxREItems() != m_MaxREItems) ||\n M_Startup() != m_Startup ||\n M_MaxMRUItems() != m_MaxMRUItems ||\n M_MRUOnFileMenu() != m_MRUOnFileMenu ||\n M_DefaultOpenRO() != m_DefaultOpenRO ||\n M_MultipleInstances() != m_MultipleInstances ||\n m_saveDeleteRegistry != m_DeleteRegistry ||\n m_saveMigrate2Appdata != m_Migrate2Appdata)\n return 1L;\n break;\n case PP_UPDATE_VARIABLES:\n \/\/ Since OnOK calls OnApply after we need to verify and\/or\n \/\/ copy data into the entry - we do it ourselves here first\n if (OnApply() == FALSE)\n return 1L;\n }\n return 0L;\n}\n\nBOOL COptionsSystem::OnApply()\n{\n UpdateData(TRUE);\n\n M_UseSystemTray() = m_UseSystemTray;\n M_HideSystemTray() = m_HideSystemTray;\n M_Startup() = m_Startup;\n M_MRUOnFileMenu() = m_MRUOnFileMenu;\n M_DefaultOpenRO() = m_DefaultOpenRO;\n M_MultipleInstances() = m_MultipleInstances;\n M_MaxREItems() = m_MaxREItems;\n M_MaxMRUItems() = m_MaxMRUItems;\n M_AppHotKeyEnabled() = m_InitialHotkeyState;\n\n return COptions_PropertyPage::OnApply();\n}\n\nBOOL COptionsSystem::PreTranslateMessage(MSG* pMsg)\n{\n RelayToolTipEvent(pMsg);\n\n if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_F1) {\n PostMessage(WM_COMMAND, MAKELONG(ID_HELP, BN_CLICKED), NULL);\n return TRUE;\n }\n\n return COptions_PropertyPage::PreTranslateMessage(pMsg);\n}\n\nBOOL COptionsSystem::OnKillActive()\n{\n \/\/ Needed as we have DDV routines.\n return CPWPropertyPage::OnKillActive();\n}\n\nvoid COptionsSystem::OnHelp()\n{\n ShowHelp(L\"::\/html\/system_tab.html\");\n}\n\nvoid COptionsSystem::OnUseSystemTray() \n{\n BOOL enable = (((CButton*)GetDlgItem(IDC_DEFPWUSESYSTRAY))->GetCheck() ==\n BST_CHECKED) ? TRUE : FALSE;\n\n GetDlgItem(IDC_STATIC_MAXREITEMS)->EnableWindow(enable);\n GetDlgItem(IDC_MAXREITEMS)->EnableWindow(enable);\n GetDlgItem(IDC_RESPIN)->EnableWindow(enable);\n\n if (enable == TRUE) {\n \/\/ Check if user has the Misc PP open and hot key set\n if (QuerySiblings(PPOPT_HOTKEY_SET, 0L) == 1L) {\n \/\/ Yes - open and hot key is set\n GetDlgItem(IDC_DEFPWHIDESYSTRAY)->EnableWindow(TRUE);\n } else {\n \/\/ No - Not open - then take initial value as the answer\n GetDlgItem(IDC_DEFPWHIDESYSTRAY)->EnableWindow(m_InitialHotkeyState);\n }\n }\n}\n\nvoid COptionsSystem::OnStartup() \n{\n \/\/ Startup implies System tray\n bool enable = ((CButton*)GetDlgItem(IDC_STARTUP))->GetCheck() == BST_CHECKED;\n\n if (enable) {\n ((CButton*)GetDlgItem(IDC_DEFPWUSESYSTRAY))->SetCheck(BST_CHECKED);\n GetDlgItem(IDC_STATIC_MAXREITEMS)->EnableWindow(TRUE);\n GetDlgItem(IDC_MAXREITEMS)->EnableWindow(TRUE);\n GetDlgItem(IDC_RESPIN)->EnableWindow(TRUE);\n }\n}\n\nvoid COptionsSystem::OnSetDeleteRegistry() \n{\n BOOL enable = (((CButton*)GetDlgItem(IDC_REGDEL))->GetCheck() == 1) ? TRUE : FALSE;\n\n GetDlgItem(IDC_APPLYCONFIGCHANGES)->EnableWindow(enable);\n}\n\nvoid COptionsSystem::OnSetMigrate2Appdata()\n{\n BOOL enable = (((CButton*)GetDlgItem(IDC_MIGRATETOAPPDATA))->GetCheck() == 1) ? TRUE : FALSE;\n\n GetDlgItem(IDC_APPLYCONFIGCHANGES)->EnableWindow(enable);\n}\n\nvoid COptionsSystem::OnApplyConfigChanges()\n{\n UpdateData(TRUE);\n\n CGeneralMsgBox gmb;\n if (m_DeleteRegistry == TRUE) {\n if (gmb.AfxMessageBox(IDS_CONFIRMDELETEREG, MB_YESNO | MB_ICONSTOP) == IDYES) {\n PWSprefs::GetInstance()->DeleteRegistryEntries();\n GetDlgItem(IDC_REGDEL)->EnableWindow(FALSE);\n }\n }\n\n if (m_Migrate2Appdata == TRUE) {\n GetDlgItem(IDC_MIGRATETOAPPDATA)->EnableWindow(FALSE);\n PerformConfigMigration();\n }\n\n if (!GetDlgItem(IDC_REGDEL)->IsWindowEnabled() && \n !GetDlgItem(IDC_MIGRATETOAPPDATA)->IsWindowEnabled())\n GetDlgItem(IDC_APPLYCONFIGCHANGES)->EnableWindow(FALSE);\n\n UpdateData(FALSE);\n}\n\nBOOL COptionsSystem::OnSetActive()\n{\n BOOL enable = (((CButton*)GetDlgItem(IDC_DEFPWUSESYSTRAY))->GetCheck() ==\n BST_CHECKED) ? TRUE : FALSE;\n\n if (enable == TRUE) {\n \/\/ Check if user has the Misc PP open and hot key set\n if (QuerySiblings(PPOPT_HOTKEY_SET, 0L) == 1L) {\n \/\/ Yes - open and hot key is set\n GetDlgItem(IDC_DEFPWHIDESYSTRAY)->EnableWindow(TRUE);\n } else {\n \/\/ No - Not open - then take initial value as the answer\n GetDlgItem(IDC_DEFPWHIDESYSTRAY)->EnableWindow(m_InitialHotkeyState);\n }\n }\n\n return CPWPropertyPage::OnSetActive();\n}\nBR1357: Hide Options->System Reg cleanup tooltip button\/*\n* Copyright (c) 2003-2016 Rony Shapiro .\n* All rights reserved. Use of the code is allowed under the\n* Artistic License 2.0 terms, as specified in the LICENSE file\n* distributed with this code, or available from\n* http:\/\/www.opensource.org\/licenses\/artistic-license-2.0.php\n*\/\n\/\/ OptionsSystem.cpp : implementation file\n\/\/\n\n#include \"stdafx.h\"\n#include \"passwordsafe.h\"\n#include \"ThisMfcApp.h\" \/\/ For Help\n#include \"Options_PropertySheet.h\"\n#include \"GeneralMsgBox.h\"\n\n#include \"core\/PwsPlatform.h\"\n#include \"core\/PWSprefs.h\"\n\n#include \"resource.h\"\n#include \"resource2.h\" \/\/ Menu, Toolbar & Accelerator resources\n#include \"resource3.h\" \/\/ String resources\n\n#include \"OptionsSystem.h\" \/\/ Must be after resource.h\n\nextern bool OfferConfigMigration();\nextern bool PerformConfigMigration();\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#undef THIS_FILE\nstatic char THIS_FILE[] = __FILE__;\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ COptionsSystem property page\n\nbool COptionsSystem::m_bShowConfigFile = false;\n\nIMPLEMENT_DYNAMIC(COptionsSystem, COptions_PropertyPage)\n\nCOptionsSystem::COptionsSystem(CWnd *pParent, st_Opt_master_data *pOPTMD) \n: COptions_PropertyPage(pParent,\n COptionsSystem::IDD, COptionsSystem::IDD_SHORT,\n pOPTMD),\n m_DeleteRegistry(FALSE), m_saveDeleteRegistry(FALSE),\n m_Migrate2Appdata(FALSE), m_saveMigrate2Appdata(FALSE)\n{\n#ifdef _DEBUG\n m_bShowConfigFile = true;\n#endif\n\n m_UseSystemTray = M_UseSystemTray();\n m_HideSystemTray = M_HideSystemTray();\n m_Startup = M_Startup();\n m_MRUOnFileMenu = M_MRUOnFileMenu();\n m_DefaultOpenRO = M_DefaultOpenRO();\n m_MultipleInstances = M_MultipleInstances();\n m_MaxREItems = M_MaxREItems();\n m_MaxMRUItems = M_MaxMRUItems();\n m_InitialHotkeyState = M_AppHotKeyEnabled();\n}\n\nvoid COptionsSystem::DoDataExchange(CDataExchange *pDX)\n{\n CPWPropertyPage::DoDataExchange(pDX);\n\n \/\/{{AFX_DATA_MAP(COptionsSystem)\n DDX_Text(pDX, IDC_MAXREITEMS, m_MaxREItems);\n DDV_MinMaxInt(pDX, m_MaxREItems, 0, ID_TRAYRECENT_ENTRYMAX - ID_TRAYRECENT_ENTRY1 + 1);\n DDX_Check(pDX, IDC_DEFPWUSESYSTRAY, m_UseSystemTray);\n DDX_Check(pDX, IDC_DEFPWHIDESYSTRAY, m_HideSystemTray);\n DDX_Check(pDX, IDC_STARTUP, m_Startup);\n DDX_Text(pDX, IDC_MAXMRUITEMS, m_MaxMRUItems);\n DDV_MinMaxInt(pDX, m_MaxMRUItems, 0, ID_FILE_MRU_ENTRYMAX - ID_FILE_MRU_ENTRY1 + 1);\n DDX_Check(pDX, IDC_MRU_ONFILEMENU, m_MRUOnFileMenu);\n DDX_Check(pDX, IDC_REGDEL, m_DeleteRegistry);\n DDX_Check(pDX, IDC_MIGRATETOAPPDATA, m_Migrate2Appdata);\n DDX_Check(pDX, IDC_DEFAULTOPENRO, m_DefaultOpenRO);\n DDX_Check(pDX, IDC_MULTIPLEINSTANCES, m_MultipleInstances);\n\n DDX_Control(pDX, IDC_REGDELHELP, m_Help1);\n DDX_Control(pDX, IDC_MIGRATETOAPPDATAHELP, m_Help2);\n \/\/}}AFX_DATA_MAP\n}\n\nBEGIN_MESSAGE_MAP(COptionsSystem, CPWPropertyPage)\n \/\/{{AFX_MSG_MAP(COptionsSystem)\n ON_BN_CLICKED(ID_HELP, OnHelp)\n\n ON_BN_CLICKED(IDC_DEFPWUSESYSTRAY, OnUseSystemTray)\n ON_BN_CLICKED(IDC_STARTUP, OnStartup)\n ON_BN_CLICKED(IDC_REGDEL, OnSetDeleteRegistry)\n ON_BN_CLICKED(IDC_MIGRATETOAPPDATA, OnSetMigrate2Appdata)\n ON_BN_CLICKED(IDC_APPLYCONFIGCHANGES, OnApplyConfigChanges)\n ON_MESSAGE(PSM_QUERYSIBLINGS, OnQuerySiblings)\n \/\/}}AFX_MSG_MAP\nEND_MESSAGE_MAP()\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ COptionsSystem message handlers\n\n\nBOOL COptionsSystem::OnInitDialog() \n{\n COptions_PropertyPage::OnInitDialog();\n\n PWSprefs *prefs = PWSprefs::GetInstance();\n if (!m_bShowConfigFile) {\n GetDlgItem(IDC_STATIC_CONFIGFILE)->ShowWindow(SW_HIDE);\n GetDlgItem(IDC_STATIC_RWSTATUS)->ShowWindow(SW_HIDE);\n GetDlgItem(IDC_CONFIGFILE)->ShowWindow(SW_HIDE);\n } else {\n PWSprefs::ConfigOption configoption;\n std::wstring wsCF = prefs->GetConfigFile(configoption);\n std::wstring wsCO(L\"\");\n switch (configoption) {\n case PWSprefs::CF_NONE:\n LoadAString(wsCF, IDS_NONE);\n break;\n case PWSprefs::CF_REGISTRY:\n LoadAString(wsCF, IDS_REGISTRY);\n break;\n case PWSprefs::CF_FILE_RO:\n LoadAString(wsCO, IDS_READ_ONLY);\n break;\n case PWSprefs::CF_FILE_RW:\n case PWSprefs::CF_FILE_RW_NEW:\n LoadAString(wsCO, IDS_READ_WRITE);\n break;\n default:\n ASSERT(0);\n }\n GetDlgItem(IDC_CONFIGFILE)->SetWindowText(wsCF.c_str());\n GetDlgItem(IDC_STATIC_RWSTATUS)->SetWindowText(wsCO.c_str());\n }\n\n bool bofferdeleteregistry = prefs->OfferDeleteRegistry();\n\n bool boffermigrate2appdata = OfferConfigMigration();\n\n if (!bofferdeleteregistry) {\n GetDlgItem(IDC_REGDEL)->ShowWindow(SW_HIDE);\n GetDlgItem(IDC_REGDEL)->EnableWindow(FALSE);\n }\n\n if (!boffermigrate2appdata) {\n GetDlgItem(IDC_MIGRATETOAPPDATA)->ShowWindow(SW_HIDE);\n GetDlgItem(IDC_MIGRATETOAPPDATA)->EnableWindow(FALSE);\n }\n\n if (!bofferdeleteregistry && !boffermigrate2appdata) {\n GetDlgItem(IDC_CONFIG_GRP)->ShowWindow(SW_HIDE);\n GetDlgItem(IDC_APPLYCONFIGCHANGES)->ShowWindow(SW_HIDE);\n } else {\n GetDlgItem(IDC_APPLYCONFIGCHANGES)->ShowWindow(SW_SHOW);\n }\n\n GetDlgItem(IDC_APPLYCONFIGCHANGES)->EnableWindow(FALSE);\n\n CSpinButtonCtrl *pspin = (CSpinButtonCtrl *)GetDlgItem(IDC_RESPIN);\n\n pspin->SetBuddy(GetDlgItem(IDC_MAXREITEMS));\n pspin->SetRange(0, ID_TRAYRECENT_ENTRYMAX - ID_TRAYRECENT_ENTRY1 + 1);\n pspin->SetBase(10);\n pspin->SetPos(m_MaxREItems);\n\n pspin = (CSpinButtonCtrl *)GetDlgItem(IDC_MRUSPIN);\n\n pspin->SetBuddy(GetDlgItem(IDC_MAXMRUITEMS));\n pspin->SetRange(0, ID_FILE_MRU_ENTRYMAX - ID_FILE_MRU_ENTRY1 + 1);\n pspin->SetBase(10);\n pspin->SetPos(m_MaxMRUItems);\n\n OnUseSystemTray();\n\n if (InitToolTip(TTS_BALLOON | TTS_NOPREFIX, 0)) {\n m_Help1.Init(IDB_QUESTIONMARK);\n m_Help2.Init(IDB_QUESTIONMARK);\n\n \/\/ Note naming convention: string IDS_xxx corresponds to control IDC_xxx_HELP\n AddTool(IDC_REGDELHELP, IDS_REGDEL);\n AddTool(IDC_MIGRATETOAPPDATAHELP, IDS_MIGRATETOAPPDATA);\n ActivateToolTip();\n } else {\n m_Help1.EnableWindow(FALSE);\n m_Help1.ShowWindow(SW_HIDE);\n m_Help2.EnableWindow(FALSE);\n m_Help2.ShowWindow(SW_HIDE);\n }\n\n if (!bofferdeleteregistry) {\n m_Help1.EnableWindow(FALSE);\n m_Help1.ShowWindow(SW_HIDE);\n }\n\n if (!boffermigrate2appdata) {\n m_Help2.EnableWindow(FALSE);\n m_Help2.ShowWindow(SW_HIDE);\n }\n\n return TRUE; \/\/ return TRUE unless you set the focus to a control\n \/\/ EXCEPTION: OCX Property Pages should return FALSE\n}\n\nLRESULT COptionsSystem::OnQuerySiblings(WPARAM wParam, LPARAM )\n{\n UpdateData(TRUE);\n\n \/\/ Have any of my fields been changed?\n switch (wParam) {\n case PP_DATA_CHANGED:\n if (M_UseSystemTray() != m_UseSystemTray ||\n M_HideSystemTray() != m_HideSystemTray ||\n (m_UseSystemTray == TRUE &&\n M_MaxREItems() != m_MaxREItems) ||\n M_Startup() != m_Startup ||\n M_MaxMRUItems() != m_MaxMRUItems ||\n M_MRUOnFileMenu() != m_MRUOnFileMenu ||\n M_DefaultOpenRO() != m_DefaultOpenRO ||\n M_MultipleInstances() != m_MultipleInstances ||\n m_saveDeleteRegistry != m_DeleteRegistry ||\n m_saveMigrate2Appdata != m_Migrate2Appdata)\n return 1L;\n break;\n case PP_UPDATE_VARIABLES:\n \/\/ Since OnOK calls OnApply after we need to verify and\/or\n \/\/ copy data into the entry - we do it ourselves here first\n if (OnApply() == FALSE)\n return 1L;\n }\n return 0L;\n}\n\nBOOL COptionsSystem::OnApply()\n{\n UpdateData(TRUE);\n\n M_UseSystemTray() = m_UseSystemTray;\n M_HideSystemTray() = m_HideSystemTray;\n M_Startup() = m_Startup;\n M_MRUOnFileMenu() = m_MRUOnFileMenu;\n M_DefaultOpenRO() = m_DefaultOpenRO;\n M_MultipleInstances() = m_MultipleInstances;\n M_MaxREItems() = m_MaxREItems;\n M_MaxMRUItems() = m_MaxMRUItems;\n M_AppHotKeyEnabled() = m_InitialHotkeyState;\n\n return COptions_PropertyPage::OnApply();\n}\n\nBOOL COptionsSystem::PreTranslateMessage(MSG* pMsg)\n{\n RelayToolTipEvent(pMsg);\n\n if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_F1) {\n PostMessage(WM_COMMAND, MAKELONG(ID_HELP, BN_CLICKED), NULL);\n return TRUE;\n }\n\n return COptions_PropertyPage::PreTranslateMessage(pMsg);\n}\n\nBOOL COptionsSystem::OnKillActive()\n{\n \/\/ Needed as we have DDV routines.\n return CPWPropertyPage::OnKillActive();\n}\n\nvoid COptionsSystem::OnHelp()\n{\n ShowHelp(L\"::\/html\/system_tab.html\");\n}\n\nvoid COptionsSystem::OnUseSystemTray() \n{\n BOOL enable = (((CButton*)GetDlgItem(IDC_DEFPWUSESYSTRAY))->GetCheck() ==\n BST_CHECKED) ? TRUE : FALSE;\n\n GetDlgItem(IDC_STATIC_MAXREITEMS)->EnableWindow(enable);\n GetDlgItem(IDC_MAXREITEMS)->EnableWindow(enable);\n GetDlgItem(IDC_RESPIN)->EnableWindow(enable);\n\n if (enable == TRUE) {\n \/\/ Check if user has the Misc PP open and hot key set\n if (QuerySiblings(PPOPT_HOTKEY_SET, 0L) == 1L) {\n \/\/ Yes - open and hot key is set\n GetDlgItem(IDC_DEFPWHIDESYSTRAY)->EnableWindow(TRUE);\n } else {\n \/\/ No - Not open - then take initial value as the answer\n GetDlgItem(IDC_DEFPWHIDESYSTRAY)->EnableWindow(m_InitialHotkeyState);\n }\n }\n}\n\nvoid COptionsSystem::OnStartup() \n{\n \/\/ Startup implies System tray\n bool enable = ((CButton*)GetDlgItem(IDC_STARTUP))->GetCheck() == BST_CHECKED;\n\n if (enable) {\n ((CButton*)GetDlgItem(IDC_DEFPWUSESYSTRAY))->SetCheck(BST_CHECKED);\n GetDlgItem(IDC_STATIC_MAXREITEMS)->EnableWindow(TRUE);\n GetDlgItem(IDC_MAXREITEMS)->EnableWindow(TRUE);\n GetDlgItem(IDC_RESPIN)->EnableWindow(TRUE);\n }\n}\n\nvoid COptionsSystem::OnSetDeleteRegistry() \n{\n BOOL enable = (((CButton*)GetDlgItem(IDC_REGDEL))->GetCheck() == 1) ? TRUE : FALSE;\n\n GetDlgItem(IDC_APPLYCONFIGCHANGES)->EnableWindow(enable);\n}\n\nvoid COptionsSystem::OnSetMigrate2Appdata()\n{\n BOOL enable = (((CButton*)GetDlgItem(IDC_MIGRATETOAPPDATA))->GetCheck() == 1) ? TRUE : FALSE;\n\n GetDlgItem(IDC_APPLYCONFIGCHANGES)->EnableWindow(enable);\n}\n\nvoid COptionsSystem::OnApplyConfigChanges()\n{\n UpdateData(TRUE);\n\n CGeneralMsgBox gmb;\n if (m_DeleteRegistry == TRUE) {\n if (gmb.AfxMessageBox(IDS_CONFIRMDELETEREG, MB_YESNO | MB_ICONSTOP) == IDYES) {\n PWSprefs::GetInstance()->DeleteRegistryEntries();\n GetDlgItem(IDC_REGDEL)->EnableWindow(FALSE);\n }\n }\n\n if (m_Migrate2Appdata == TRUE) {\n GetDlgItem(IDC_MIGRATETOAPPDATA)->EnableWindow(FALSE);\n PerformConfigMigration();\n }\n\n if (!GetDlgItem(IDC_REGDEL)->IsWindowEnabled() && \n !GetDlgItem(IDC_MIGRATETOAPPDATA)->IsWindowEnabled())\n GetDlgItem(IDC_APPLYCONFIGCHANGES)->EnableWindow(FALSE);\n\n UpdateData(FALSE);\n}\n\nBOOL COptionsSystem::OnSetActive()\n{\n BOOL enable = (((CButton*)GetDlgItem(IDC_DEFPWUSESYSTRAY))->GetCheck() ==\n BST_CHECKED) ? TRUE : FALSE;\n\n if (enable == TRUE) {\n \/\/ Check if user has the Misc PP open and hot key set\n if (QuerySiblings(PPOPT_HOTKEY_SET, 0L) == 1L) {\n \/\/ Yes - open and hot key is set\n GetDlgItem(IDC_DEFPWHIDESYSTRAY)->EnableWindow(TRUE);\n } else {\n \/\/ No - Not open - then take initial value as the answer\n GetDlgItem(IDC_DEFPWHIDESYSTRAY)->EnableWindow(m_InitialHotkeyState);\n }\n }\n\n return CPWPropertyPage::OnSetActive();\n}\n<|endoftext|>"} {"text":"#include \"vector3.h\"\n#include \"catch.hpp\"\n\ntemplate void vectorTestSuite() {\n\tauto REQUIRE_VECS_EQ = [](V a, V b) {\n\t\tREQUIRE(a.x() == Approx(b.x()));\n\t\tREQUIRE(a.y() == Approx(b.y()));\n\t\tREQUIRE(a.z() == Approx(b.z()));\n\t};\n\tSECTION(\"Vector magSq is correct\") {\n\t\tREQUIRE(V(2, 3, 6).magSq() == Approx(49));\n\t}\n\tSECTION(\"Vector mag is correct\") {\n\t\tREQUIRE(V(2, 3, 6).mag() == Approx(7));\n\t}\n SECTION(\"Vector negation is correct\") {\n REQUIRE_VECS_EQ(-V(2.0, -3.0, 1.5), V(-2.0, 3.0, -1.5));\n }\n SECTION(\"Vector normalization is correct\") {\n \tREQUIRE_VECS_EQ(V(2.0, 3.0, 6.0).norm(), V(2.0\/7.0, 3.0\/7.0, 6.0\/7.0));\n }\n SECTION(\"Vector scaling is correct\") {\n REQUIRE_VECS_EQ(V(2.0, -3.0, 1.5)*4, V(8.0, -12.0, 6.0));\n }\n SECTION(\"Vector scaling (by division) is correct\") {\n \tREQUIRE_VECS_EQ(V(2.0, -3.0, 4.0)\/4.0, V(0.5, -0.75, 1.0));\n }\n SECTION(\"Vector addition is correct\") {\n REQUIRE_VECS_EQ(V(2.0, -3.0, 1.5)+V(-1.5, 1.5, 0.5), V(0.5, -1.5, 2.0));\n }\n SECTION(\"Vector subtraction is correct\") {\n REQUIRE_VECS_EQ(V(2.0, -3.0, 1.5)-V(-1.5, 1.5, 0.5), V(3.5, -4.5, 1.0));\n }\n SECTION(\"Vector dot product is correct\") {\n \tREQUIRE(V(5, 3, 2).dot(V(-2, 3, 4)) == Approx(7));\n }\n SECTION(\"Vector cross product is correct\") {\n \tREQUIRE_VECS_EQ(V(1, 2, 3).cross(V(2, 3, 4)), V(-1, 2, -1));\n }\n SECTION(\"Vector scalar projection is correct\") {\n \tREQUIRE(V(3, 4, 5).scalarProj(V(2, 0, 0)) == Approx(3));\n \tREQUIRE(V(3, 4, 5).scalarProj(V(0, 2, 0)) == Approx(4));\n \tREQUIRE(V(3, 4, 5).scalarProj(V(2, 6, 9)) == Approx(75.0\/11.0));\n }\n SECTION(\"Vector project is correct\") {\n \tREQUIRE_VECS_EQ(V(3, 1, 4).proj(V(6, 0, 8)), V(3, 0, 4));\n }\n SECTION(\"Vector distance is correct\") {\n \tREQUIRE(V(2, 1, 3).distance(V(6, 2, -5)) == Approx(9.0));\n }\n}\n\nTEST_CASE(\"Vector3f math operations are accurate\", \"[vector3]\") {\n\tvectorTestSuite();\n}\nTEST_CASE(\"Vector3d math operations are accurate\", \"[vector3]\") {\n\tvectorTestSuite();\n}Add license\/* The MIT License (MIT)\n *\n * Copyright (c) 2014 Colin Wallace\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include \"vector3.h\"\n#include \"catch.hpp\"\n\ntemplate void vectorTestSuite() {\n\tauto REQUIRE_VECS_EQ = [](V a, V b) {\n\t\tREQUIRE(a.x() == Approx(b.x()));\n\t\tREQUIRE(a.y() == Approx(b.y()));\n\t\tREQUIRE(a.z() == Approx(b.z()));\n\t};\n\tSECTION(\"Vector magSq is correct\") {\n\t\tREQUIRE(V(2, 3, 6).magSq() == Approx(49));\n\t}\n\tSECTION(\"Vector mag is correct\") {\n\t\tREQUIRE(V(2, 3, 6).mag() == Approx(7));\n\t}\n SECTION(\"Vector negation is correct\") {\n REQUIRE_VECS_EQ(-V(2.0, -3.0, 1.5), V(-2.0, 3.0, -1.5));\n }\n SECTION(\"Vector normalization is correct\") {\n \tREQUIRE_VECS_EQ(V(2.0, 3.0, 6.0).norm(), V(2.0\/7.0, 3.0\/7.0, 6.0\/7.0));\n }\n SECTION(\"Vector scaling is correct\") {\n REQUIRE_VECS_EQ(V(2.0, -3.0, 1.5)*4, V(8.0, -12.0, 6.0));\n }\n SECTION(\"Vector scaling (by division) is correct\") {\n \tREQUIRE_VECS_EQ(V(2.0, -3.0, 4.0)\/4.0, V(0.5, -0.75, 1.0));\n }\n SECTION(\"Vector addition is correct\") {\n REQUIRE_VECS_EQ(V(2.0, -3.0, 1.5)+V(-1.5, 1.5, 0.5), V(0.5, -1.5, 2.0));\n }\n SECTION(\"Vector subtraction is correct\") {\n REQUIRE_VECS_EQ(V(2.0, -3.0, 1.5)-V(-1.5, 1.5, 0.5), V(3.5, -4.5, 1.0));\n }\n SECTION(\"Vector dot product is correct\") {\n \tREQUIRE(V(5, 3, 2).dot(V(-2, 3, 4)) == Approx(7));\n }\n SECTION(\"Vector cross product is correct\") {\n \tREQUIRE_VECS_EQ(V(1, 2, 3).cross(V(2, 3, 4)), V(-1, 2, -1));\n }\n SECTION(\"Vector scalar projection is correct\") {\n \tREQUIRE(V(3, 4, 5).scalarProj(V(2, 0, 0)) == Approx(3));\n \tREQUIRE(V(3, 4, 5).scalarProj(V(0, 2, 0)) == Approx(4));\n \tREQUIRE(V(3, 4, 5).scalarProj(V(2, 6, 9)) == Approx(75.0\/11.0));\n }\n SECTION(\"Vector project is correct\") {\n \tREQUIRE_VECS_EQ(V(3, 1, 4).proj(V(6, 0, 8)), V(3, 0, 4));\n }\n SECTION(\"Vector distance is correct\") {\n \tREQUIRE(V(2, 1, 3).distance(V(6, 2, -5)) == Approx(9.0));\n }\n}\n\nTEST_CASE(\"Vector3f math operations are accurate\", \"[vector3]\") {\n\tvectorTestSuite();\n}\nTEST_CASE(\"Vector3d math operations are accurate\", \"[vector3]\") {\n\tvectorTestSuite();\n}<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/lib\/mcbist\/address.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file address.H\n\/\/\/ @brief Class for mcbist related addresses (addresses below the hash translation)\n\/\/\/\n\/\/ *HWP HWP Owner: Brian Silver \n\/\/ *HWP HWP Backup: Andre Marin \n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: HB:FSP\n\n#ifndef _MSS_MCBIST_ADDRESS_H_\n#define _MSS_MCBIST_ADDRESS_H_\n\n#include \n#include \n\nnamespace mss\n{\nnamespace mcbist\n{\n\n\/\/\/\n\/\/\/ @class address\n\/\/\/ @brief Represents a physical address in memory\n\/\/\/ @note\n\/\/\/ 0:1 port select\n\/\/\/ 2 dimm select\n\/\/\/ 3:4 mrank(0 to 1)\n\/\/\/ 5:7 srank(0 to 2)\n\/\/\/ 8:25 row(0 to 17)\n\/\/\/ 26:32 col(3 to 9)\n\/\/\/ 33:35 bank(0 to 2)\n\/\/\/ 36:37 bank_group(0 to 1)\n\/\/\/\nclass address\n{\n private:\n \/\/ How far over we shift to align the address in either the register or a buffer\n enum { MAGIC_PAD = 26 };\n\n public:\n\n \/\/ first is the start bit of the field, second is the length\n typedef std::pair field;\n\n constexpr static field PORT = {0, 2};\n constexpr static field DIMM = {2, 1};\n constexpr static field MRANK = {3, 2};\n constexpr static field SRANK = {5, 3};\n constexpr static field ROW = {8, 18};\n constexpr static field COL = {26, 7};\n constexpr static field BANK = {33, 3};\n constexpr static field BANK_GROUP = {36, 2};\n constexpr static field LAST_VALID = BANK_GROUP;\n\n address() = default;\n\n \/\/\/\n \/\/\/ @brief Construct an address from a uint64_t (scom'ed value)\n \/\/\/ @param[in] i_value representing an address; say from a trap register\n \/\/\/\n \/\/\/ @note This assumes input has the same bit layout as this address\n \/\/\/ structure, and this is presently not the case for the trap registers (3\/16).\n \/\/\/ These are presently unused, however. There is an open defect against the\n \/\/\/ design team to correct this.\n \/\/\/ @warn Assumes right-aligned value; bit 63 is shifted to represent the Bank Group\n address( const uint64_t i_value ):\n iv_address(i_value << MAGIC_PAD)\n {\n }\n\n \/\/\/\n \/\/\/ @brief Conversion operator to uint64_t\n \/\/\/ @warn Right-aligns the address\n \/\/\/\n inline operator uint64_t() const\n {\n return iv_address >> MAGIC_PAD;\n }\n\n \/\/\/\n \/\/\/ @brief Set a field for an address\n \/\/\/ @tparam F the field to set\n \/\/\/ @param[in] i_value the value to set\n \/\/\/ @return address& for method chaining\n \/\/\/\n template< const field& F >\n inline address& set_field( const uint64_t i_value )\n {\n iv_address.insertFromRight(i_value);\n return *this;\n }\n\n \/\/\/\n \/\/\/ @brief Get a field from an address\n \/\/\/ @tparam F the field to get\n \/\/\/ @return right-aligned uint64_t representing the value\n \/\/\/\n template< const field& F >\n inline uint64_t get_field() const\n {\n uint64_t l_value = 0;\n iv_address.extractToRight(l_value);\n return l_value;\n }\n\n \/\/\/\n \/\/\/ @brief Get a range of addresses.\n \/\/\/ @tparam[in] F the left-most valid field. So, if the address was for master rank,\n \/\/\/ the left-most valid field would be MRANK\n \/\/\/ @param[out] o_end representing an address to end at\n \/\/\/ @note this pointer is the start address\n \/\/\/\n template< const field& F >\n inline void get_range( address& o_end ) const\n {\n constexpr uint64_t START = F.first + F.second;\n constexpr uint64_t LEN = (LAST_VALID.first + LAST_VALID.second) - START;\n\n \/\/ All we need to do is fill in the bits to the right of the last valid field\n o_end.iv_address = iv_address;\n o_end.iv_address.setBit();\n }\n\n \/\/\/\n \/\/\/ @brief Get a range of addresses given a master rank\n \/\/\/ @param[in] i_start representing an address to start from\n \/\/\/ @param[out] o_end representing an address to end at\n \/\/\/\n inline static void get_mrank_range( const address& i_start, address& o_end )\n {\n i_start.get_range(o_end);\n }\n\n \/\/\/\n \/\/\/ @brief Get a range of addresses given a master rank\n \/\/\/ @param[in] i_port representing the port for the starting address\n \/\/\/ @param[in] i_dimm representing the dimm for the starting address\n \/\/\/ @param[in] i_mrank representing the master rank for the starting address\n \/\/\/ @param[out] o_start representing an address to start from\n \/\/\/ @param[out] o_end representing an address to end at\n \/\/\/\n inline static void get_mrank_range( const uint64_t i_port, const uint64_t i_dimm, const uint64_t i_mrank,\n address& o_start, address& o_end )\n {\n o_start.set_port(i_port).set_dimm(i_dimm).set_master_rank(i_mrank);\n get_mrank_range(o_start, o_end);\n }\n\n \/\/\/\n \/\/\/ @brief Get a range of addresses given a slave rank\n \/\/\/ @param[in] i_start representing an address to start from\n \/\/\/ @param[out] o_end representing an address to end at\n \/\/\/\n inline static void get_srank_range( const address& i_start, address& o_end )\n {\n i_start.get_range(o_end);\n }\n\n \/\/\/\n \/\/\/ @brief Get a range of addresses given a slave rank\n \/\/\/ @param[in] i_port representing the port for the starting address\n \/\/\/ @param[in] i_dimm representing the dimm for the starting address\n \/\/\/ @param[in] i_mrank representing the master rank for the starting address\n \/\/\/ @param[in] i_srank representing the slave rank for the starting address\n \/\/\/ @param[out] o_start representing an address to start from\n \/\/\/ @param[out] o_end representing an address to end at\n \/\/\/\n inline static void get_srank_range( const uint64_t i_port, const uint64_t i_dimm,\n const uint64_t i_mrank, const uint64_t i_srank,\n address& o_start, address& o_end )\n {\n o_start.set_port(i_port).set_dimm(i_dimm).set_master_rank(i_mrank).set_slave_rank(i_srank);\n get_srank_range(o_start, o_end);\n }\n\n \/\/\/\n \/\/\/ @brief Set the port value for an address\n \/\/\/ @param[in] i_value the value to set\n \/\/\/ @return address& for method chaining\n \/\/\/\n inline address& set_port( const uint64_t i_value )\n {\n return set_field(i_value);\n }\n\n \/\/\/\n \/\/\/ @brief Get the port value for an address\n \/\/\/ @return right-aligned uint64_t representing the value\n \/\/\/\n inline uint64_t get_port() const\n {\n return get_field();\n }\n\n \/\/\/\n \/\/\/ @brief Set the DIMM value for an address\n \/\/\/ @param[in] i_value the value to set\n \/\/\/ @note 0 is the DIMM[0] != 0 is DIMM[1]\n \/\/\/ @return address& for method chaining\n \/\/\/\n inline address& set_dimm( const uint64_t i_value )\n {\n return set_field(i_value);\n }\n\n \/\/\/\n \/\/\/ @brief Get the DIMM value for an address\n \/\/\/ @return right-aligned uint64_t representing the vaule\n \/\/\/\n inline uint64_t get_dimm() const\n {\n return (get_field() == true ? 1 : 0);\n }\n\n \/\/\/\n \/\/\/ @brief Set the master rank value for an address\n \/\/\/ @param[in] i_value the value to set\n \/\/\/ @return address& for method chaining\n \/\/\/\n inline address& set_master_rank( const uint64_t i_value )\n {\n return set_field(i_value);\n }\n\n \/\/\/\n \/\/\/ @brief Get the master rank value for an address\n \/\/\/ @return right-aligned uint64_t representing the value\n \/\/\/\n inline uint64_t get_master_rank() const\n {\n return get_field();\n }\n\n\n \/\/\/\n \/\/\/ @brief Set the slave rank value for an address\n \/\/\/ @param[in] i_value the value to set\n \/\/\/\n inline void set_slave_rank( const uint64_t i_value )\n {\n set_field(i_value);\n }\n\n \/\/\/\n \/\/\/ @brief Get the slave rank value for an address\n \/\/\/ @return right-aligned uint64_t representing the value\n \/\/\/\n inline uint64_t get_slave_rank() const\n {\n return get_field();\n }\n\n\n \/\/\/\n \/\/\/ @brief Set the row value for an address\n \/\/\/ @param[in] i_value the value to set\n \/\/\/ @return address& for method chaining\n \/\/\/\n inline address& set_row( const uint64_t i_value )\n {\n return set_field(i_value);\n }\n\n \/\/\/\n \/\/\/ @brief Get the row value for an address\n \/\/\/ @return right-aligned uint64_t representing the value\n \/\/\/\n inline uint64_t get_row() const\n {\n return get_field();\n }\n\n\n \/\/\/\n \/\/\/ @brief Set the column value for an address\n \/\/\/ @param[in] i_value the value to set\n \/\/\/ @return address& for method chaining\n \/\/\/\n inline address& set_column( const uint64_t i_value )\n {\n return set_field(i_value);\n }\n\n \/\/\/\n \/\/\/ @brief Get the column value for an address\n \/\/\/ @return right-aligned uint64_t representing the value\n \/\/\/\n inline uint64_t get_column() const\n {\n return get_field();\n }\n\n\n \/\/\/\n \/\/\/ @brief Set the bank value for an address\n \/\/\/ @param[in] i_value the value to set\n \/\/\/ @return address& for method chaining\n \/\/\/\n inline address& set_bank( const uint64_t i_value )\n {\n return set_field(i_value);\n }\n\n \/\/\/\n \/\/\/ @brief Get the bank value for an address\n \/\/\/ @return right-aligned uint64_t representing the value\n \/\/\/\n inline uint64_t get_bank() const\n {\n return get_field();\n }\n\n \/\/\/\n \/\/\/ @brief Set the bank group value for an address\n \/\/\/ @param[in] i_value the value to set\n \/\/\/ @return address& for method chaining\n \/\/\/\n inline address& set_bank_group( const uint64_t i_value )\n {\n return set_field(i_value);\n }\n\n \/\/\/\n \/\/\/ @brief Get the bank group value for an address\n \/\/\/ @return right-aligned uint64_t representing the value\n \/\/\/\n inline uint64_t get_bank_group() const\n {\n return get_field();\n }\n\n private:\n \/\/ We use a fapi2 buffer as it has static compile-time support\n fapi2::buffer iv_address;\n};\n\n} \/\/ namespace\n\n} \/\/ namespace\n\n#endif\nAdd memdiags scrub capability\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/lib\/mcbist\/address.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file address.H\n\/\/\/ @brief Class for mcbist related addresses (addresses below the hash translation)\n\/\/\/\n\/\/ *HWP HWP Owner: Brian Silver \n\/\/ *HWP HWP Backup: Andre Marin \n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: HB:FSP\n\n#ifndef _MSS_MCBIST_ADDRESS_H_\n#define _MSS_MCBIST_ADDRESS_H_\n\n#include \n#include \n\nnamespace mss\n{\nnamespace mcbist\n{\n\n\/\/\/\n\/\/\/ @class address\n\/\/\/ @brief Represents a physical address in memory\n\/\/\/ @note\n\/\/\/ 0:1 port select\n\/\/\/ 2 dimm select\n\/\/\/ 3:4 mrank(0 to 1)\n\/\/\/ 5:7 srank(0 to 2)\n\/\/\/ 8:25 row(0 to 17)\n\/\/\/ 26:32 col(3 to 9)\n\/\/\/ 33:35 bank(0 to 2)\n\/\/\/ 36:37 bank_group(0 to 1)\n\/\/\/\nclass address\n{\n private:\n \/\/ How far over we shift to align the address in either the register or a buffer\n enum { MAGIC_PAD = 26 };\n\n public:\n\n \/\/ first is the start bit of the field, second is the length\n typedef std::pair field;\n\n constexpr static field PORT = {0, 2};\n constexpr static field DIMM = {2, 1};\n constexpr static field MRANK = {3, 2};\n constexpr static field SRANK = {5, 3};\n constexpr static field ROW = {8, 18};\n constexpr static field COL = {26, 7};\n constexpr static field BANK = {33, 3};\n constexpr static field BANK_GROUP = {36, 2};\n constexpr static field LAST_VALID = BANK_GROUP;\n\n address() = default;\n\n \/\/\/\n \/\/\/ @brief Construct an address from a uint64_t (scom'ed value)\n \/\/\/ @param[in] i_value representing an address; say from a trap register\n \/\/\/\n \/\/\/ @note This assumes input has the same bit layout as this address\n \/\/\/ structure, and this is presently not the case for the trap registers (3\/16).\n \/\/\/ These are presently unused, however. There is an open defect against the\n \/\/\/ design team to correct this.\n \/\/\/ @warn Assumes right-aligned value; bit 63 is shifted to represent the Bank Group\n address( const uint64_t i_value ):\n iv_address(i_value << MAGIC_PAD)\n {\n }\n\n \/\/\/\n \/\/\/ @brief Conversion operator to uint64_t\n \/\/\/ @warn Right-aligns the address\n \/\/\/\n inline operator uint64_t() const\n {\n return iv_address >> MAGIC_PAD;\n }\n\n \/\/\/\n \/\/\/ @brief Set a field for an address\n \/\/\/ @tparam F the field to set\n \/\/\/ @param[in] i_value the value to set\n \/\/\/ @return address& for method chaining\n \/\/\/\n template< const field& F >\n inline address& set_field( const uint64_t i_value )\n {\n iv_address.insertFromRight(i_value);\n return *this;\n }\n\n \/\/\/\n \/\/\/ @brief Get a field from an address\n \/\/\/ @tparam F the field to get\n \/\/\/ @return right-aligned uint64_t representing the value\n \/\/\/\n template< const field& F >\n inline uint64_t get_field() const\n {\n uint64_t l_value = 0;\n iv_address.extractToRight(l_value);\n return l_value;\n }\n\n \/\/\/\n \/\/\/ @brief Get a range of addresses.\n \/\/\/ @tparam[in] F the left-most valid field. So, if the address was for master rank,\n \/\/\/ the left-most valid field would be MRANK\n \/\/\/ @param[out] o_end representing an address to end at\n \/\/\/ @note this pointer is the start address\n \/\/\/\n template< const field& F >\n inline void get_range( address& o_end ) const\n {\n constexpr uint64_t START = F.first + F.second;\n constexpr uint64_t LEN = (LAST_VALID.first + LAST_VALID.second) - START;\n\n \/\/ All we need to do is fill in the bits to the right of the last valid field\n o_end.iv_address = iv_address;\n o_end.iv_address.setBit();\n }\n\n\n \/\/\/\n \/\/\/ @brief Get an end address for sim mode\n \/\/\/ @param[out] o_end representing an address to end at\n \/\/\/ @note this pointer is the start address\n \/\/\/\n inline void get_sim_end_address( address& o_end ) const\n {\n \/\/ This magic number represents a range of addresses which cover all\n \/\/ cache lines the training algorithms touch. By effecting 0 - this end\n \/\/ address you'll effect everything which has bad ECC in the sim.\n constexpr uint64_t l_magic_sim_number = 0b1000000;\n\n get_range(o_end);\n o_end.set_column(l_magic_sim_number);\n return;\n }\n\n \/\/\/\n \/\/\/ @brief Get a range of addresses given a master rank\n \/\/\/ @param[in] i_start representing an address to start from\n \/\/\/ @param[out] o_end representing an address to end at\n \/\/\/\n inline static void get_mrank_range( const address& i_start, address& o_end )\n {\n i_start.get_range(o_end);\n }\n\n \/\/\/\n \/\/\/ @brief Get a range of addresses given a master rank\n \/\/\/ @param[in] i_port representing the port for the starting address\n \/\/\/ @param[in] i_dimm representing the dimm for the starting address\n \/\/\/ @param[in] i_mrank representing the master rank for the starting address\n \/\/\/ @param[out] o_start representing an address to start from\n \/\/\/ @param[out] o_end representing an address to end at\n \/\/\/\n inline static void get_mrank_range( const uint64_t i_port, const uint64_t i_dimm, const uint64_t i_mrank,\n address& o_start, address& o_end )\n {\n o_start.set_port(i_port).set_dimm(i_dimm).set_master_rank(i_mrank);\n get_mrank_range(o_start, o_end);\n }\n\n \/\/\/\n \/\/\/ @brief Get a range of addresses given a slave rank\n \/\/\/ @param[in] i_start representing an address to start from\n \/\/\/ @param[out] o_end representing an address to end at\n \/\/\/\n inline static void get_srank_range( const address& i_start, address& o_end )\n {\n i_start.get_range(o_end);\n }\n\n \/\/\/\n \/\/\/ @brief Get a range of addresses given a slave rank\n \/\/\/ @param[in] i_port representing the port for the starting address\n \/\/\/ @param[in] i_dimm representing the dimm for the starting address\n \/\/\/ @param[in] i_mrank representing the master rank for the starting address\n \/\/\/ @param[in] i_srank representing the slave rank for the starting address\n \/\/\/ @param[out] o_start representing an address to start from\n \/\/\/ @param[out] o_end representing an address to end at\n \/\/\/\n inline static void get_srank_range( const uint64_t i_port, const uint64_t i_dimm,\n const uint64_t i_mrank, const uint64_t i_srank,\n address& o_start, address& o_end )\n {\n o_start.set_port(i_port).set_dimm(i_dimm).set_master_rank(i_mrank).set_slave_rank(i_srank);\n get_srank_range(o_start, o_end);\n }\n\n \/\/\/\n \/\/\/ @brief Set the port value for an address\n \/\/\/ @param[in] i_value the value to set\n \/\/\/ @return address& for method chaining\n \/\/\/\n inline address& set_port( const uint64_t i_value )\n {\n return set_field(i_value);\n }\n\n \/\/\/\n \/\/\/ @brief Get the port value for an address\n \/\/\/ @return right-aligned uint64_t representing the value\n \/\/\/\n inline uint64_t get_port() const\n {\n return get_field();\n }\n\n \/\/\/\n \/\/\/ @brief Set the DIMM value for an address\n \/\/\/ @param[in] i_value the value to set\n \/\/\/ @note 0 is the DIMM[0] != 0 is DIMM[1]\n \/\/\/ @return address& for method chaining\n \/\/\/\n inline address& set_dimm( const uint64_t i_value )\n {\n return set_field(i_value);\n }\n\n \/\/\/\n \/\/\/ @brief Get the DIMM value for an address\n \/\/\/ @return right-aligned uint64_t representing the vaule\n \/\/\/\n inline uint64_t get_dimm() const\n {\n return (get_field() == true ? 1 : 0);\n }\n\n \/\/\/\n \/\/\/ @brief Set the master rank value for an address\n \/\/\/ @param[in] i_value the value to set\n \/\/\/ @return address& for method chaining\n \/\/\/\n inline address& set_master_rank( const uint64_t i_value )\n {\n return set_field(i_value);\n }\n\n \/\/\/\n \/\/\/ @brief Get the master rank value for an address\n \/\/\/ @return right-aligned uint64_t representing the value\n \/\/\/\n inline uint64_t get_master_rank() const\n {\n return get_field();\n }\n\n\n \/\/\/\n \/\/\/ @brief Set the slave rank value for an address\n \/\/\/ @param[in] i_value the value to set\n \/\/\/\n inline void set_slave_rank( const uint64_t i_value )\n {\n set_field(i_value);\n }\n\n \/\/\/\n \/\/\/ @brief Get the slave rank value for an address\n \/\/\/ @return right-aligned uint64_t representing the value\n \/\/\/\n inline uint64_t get_slave_rank() const\n {\n return get_field();\n }\n\n\n \/\/\/\n \/\/\/ @brief Set the row value for an address\n \/\/\/ @param[in] i_value the value to set\n \/\/\/ @return address& for method chaining\n \/\/\/\n inline address& set_row( const uint64_t i_value )\n {\n return set_field(i_value);\n }\n\n \/\/\/\n \/\/\/ @brief Get the row value for an address\n \/\/\/ @return right-aligned uint64_t representing the value\n \/\/\/\n inline uint64_t get_row() const\n {\n return get_field();\n }\n\n\n \/\/\/\n \/\/\/ @brief Set the column value for an address\n \/\/\/ @param[in] i_value the value to set\n \/\/\/ @return address& for method chaining\n \/\/\/\n inline address& set_column( const uint64_t i_value )\n {\n return set_field(i_value);\n }\n\n \/\/\/\n \/\/\/ @brief Get the column value for an address\n \/\/\/ @return right-aligned uint64_t representing the value\n \/\/\/\n inline uint64_t get_column() const\n {\n return get_field();\n }\n\n\n \/\/\/\n \/\/\/ @brief Set the bank value for an address\n \/\/\/ @param[in] i_value the value to set\n \/\/\/ @return address& for method chaining\n \/\/\/\n inline address& set_bank( const uint64_t i_value )\n {\n return set_field(i_value);\n }\n\n \/\/\/\n \/\/\/ @brief Get the bank value for an address\n \/\/\/ @return right-aligned uint64_t representing the value\n \/\/\/\n inline uint64_t get_bank() const\n {\n return get_field();\n }\n\n \/\/\/\n \/\/\/ @brief Set the bank group value for an address\n \/\/\/ @param[in] i_value the value to set\n \/\/\/ @return address& for method chaining\n \/\/\/\n inline address& set_bank_group( const uint64_t i_value )\n {\n return set_field(i_value);\n }\n\n \/\/\/\n \/\/\/ @brief Get the bank group value for an address\n \/\/\/ @return right-aligned uint64_t representing the value\n \/\/\/\n inline uint64_t get_bank_group() const\n {\n return get_field();\n }\n\n private:\n \/\/ We use a fapi2 buffer as it has static compile-time support\n fapi2::buffer iv_address;\n};\n\n} \/\/ namespace\n\n} \/\/ namespace\n\n#endif\n<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/perv\/p9_sbe_chiplet_reset.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/------------------------------------------------------------------------------\n\/\/\/ @file p9_sbe_chiplet_reset.H\n\/\/\/\n\/\/\/ @brief Steps:-\n\/\/\/ 1) Identify Partical good chiplet and configure Multicasting register\n\/\/\/ 2) Similar way, Configure hang pulse counter for Nest\/MC\/OBus\/XBus\/PCIe\n\/\/\/ 3) Similar way, set fence for Nest and MC chiplet\n\/\/\/ 4) Similar way, Reset sys.config and OPCG setting for Nest and MC chiplet in sync mode\n\/\/\/\n\/\/\/ Done\n\/\/------------------------------------------------------------------------------\n\/\/ *HWP HW Owner : Abhishek Agarwal \n\/\/ *HWP HW Backup Owner : Srinivas V. Naga \n\/\/ *HWP FW Owner : Brian Silver \n\/\/ *HWP Team : Perv\n\/\/ *HWP Level : 2\n\/\/ *HWP Consumed by : SBE\n\/\/------------------------------------------------------------------------------\n\n\n#ifndef _P9_SBE_CHIPLET_RESET_H_\n#define _P9_SBE_CHIPLET_RESET_H_\n\n\n#include \n\n\nnamespace p9SbeChipletReset\n{\nenum P9_SBE_CHIPLET_RESET_Public_Constants\n{\n MCGR0_CNFG_SETTINGS = 0xE0001C0000000000ull,\n MCGR1_CNFG_SETTINGS = 0xE4001C0000000000ull,\n MCGR2_CNFG_SETTINGS = 0xE8001C0000000000ull,\n MCGR3_CNFG_SETTINGS = 0xEC001C0000000000ull,\n NET_CNTL0_HW_INIT_VALUE = 0x7C16222000000000ull,\n HANG_PULSE_0X10 = 0x10,\n HANG_PULSE_0X0F = 0x0F,\n HANG_PULSE_0X06 = 0x06,\n HANG_PULSE_0X17 = 0x17,\n HANG_PULSE_0X18 = 0x18,\n HANG_PULSE_0X22 = 0x22,\n HANG_PULSE_0X13 = 0x13,\n HANG_PULSE_0X03 = 0x03,\n OPCG_ALIGN_SETTING = 0x5000000000003020ull,\n INOP_ALIGN_SETTING_0X5 = 0x5,\n OPCG_WAIT_CYCLE_0X020 = 0x020,\n SCAN_RATIO_0X3 = 0x3,\n SYNC_PULSE_DELAY_0X0 = 0X00,\n SYNC_CONFIG_DEFAULT = 0X0000000000000000,\n HANG_PULSE_0X00 = 0x00,\n HANG_PULSE_0X01 = 0x01,\n HANG_PULSE_0X04 = 0x04,\n HANG_PULSE_0X1A = 0x1A,\n NET_CNTL1_HW_INIT_VALUE = 0x7200000000000000ull,\n MCGR2_CACHE_CNFG_SETTINGS = 0xF0001C0000000000ull,\n MCGR3_CACHE_CNFG_SETTINGS = 0xF4001C0000000000ull,\n MCGR4_CACHE_CNFG_SETTINGS = 0xF8001C0000000000ull,\n REGIONS_EXCEPT_VITAL = 0x7FF,\n SCAN_TYPES_EXCEPT_TIME_GPTR_REPR = 0xDCE,\n SCAN_TYPES_TIME_GPTR_REPR = 0x230,\n SCAN_RATIO_0X0 = 0x0,\n SYNC_CONFIG_4TO1 = 0X0800000000000000,\n HW_NS_DELAY = 200000, \/\/ unit is nano seconds\n SIM_CYCLE_DELAY = 10000, \/\/ unit is cycles\n HANG_PULSE_0X12 = 0x12,\n HANG_PULSE_0X1C = 0x1C,\n HANG_PULSE_0X05 = 0x05\n};\n}\n\ntypedef fapi2::ReturnCode (*p9_sbe_chiplet_reset_FP_t)(const\n fapi2::Target&);\n\n\/\/\/ @brief Identify all good chiplets excluding EQ\/EC\n\/\/\/ -- All chiplets will be reset and PLLs started\n\/\/\/ -- Partial bad - All nest Chiplets must be good, MC, IO can be partial bad\n\/\/\/ Setup multicast groups for all chiplets\n\/\/\/ -- Can't use the multicast for all non-nest chiplets\n\/\/\/ -- This is intended to be the eventual product setting\n\/\/\/ -- This includes the core\/cache chiplets\n\/\/\/ For all good chiplets excluding EQ\/EC\n\/\/\/ -- Setup Chiplet GP3 regs\n\/\/\/ -- Reset to default state\n\/\/\/ -- Set chiplet enable on all all good chiplets excluding EQ\/EC\n\/\/\/ For all enabled chiplets excluding EQ\/EC\/Buses\n\/\/\/ -- Start vital clocks and release endpoint reset\n\/\/\/ -- PCB Slave error register Reset\n\/\/\/\n\/\/\/\n\/\/\/ @param[in] i_target_chip Reference to TARGET_TYPE_PROC_CHIP target\n\/\/\/ @return FAPI2_RC_SUCCESS if success, else error code.\nextern \"C\"\n{\n fapi2::ReturnCode p9_sbe_chiplet_reset(const\n fapi2::Target& i_target_chip);\n}\n\n#endif\nLevel 2 HWP for p9_sbe_chiplet_reset\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/perv\/p9_sbe_chiplet_reset.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/------------------------------------------------------------------------------\n\/\/\/ @file p9_sbe_chiplet_reset.H\n\/\/\/\n\/\/\/ @brief Steps:-\n\/\/\/ 1) Identify Partical good chiplet and configure Multicasting register\n\/\/\/ 2) Similar way, Configure hang pulse counter for Nest\/MC\/OBus\/XBus\/PCIe\n\/\/\/ 3) Similar way, set fence for Nest and MC chiplet\n\/\/\/ 4) Similar way, Reset sys.config and OPCG setting for Nest and MC chiplet in sync mode\n\/\/\/\n\/\/\/ Done\n\/\/------------------------------------------------------------------------------\n\/\/ *HWP HW Owner : Abhishek Agarwal \n\/\/ *HWP HW Backup Owner : Srinivas V. Naga \n\/\/ *HWP FW Owner : Brian Silver \n\/\/ *HWP Team : Perv\n\/\/ *HWP Level : 2\n\/\/ *HWP Consumed by : SBE\n\/\/------------------------------------------------------------------------------\n\n\n#ifndef _P9_SBE_CHIPLET_RESET_H_\n#define _P9_SBE_CHIPLET_RESET_H_\n\n\n#include \n\n\nnamespace p9SbeChipletReset\n{\nenum P9_SBE_CHIPLET_RESET_Public_Constants\n{\n MCGR0_CNFG_SETTINGS = 0xE0001C0000000000ull,\n MCGR1_CNFG_SETTINGS = 0xE4001C0000000000ull,\n MCGR2_CNFG_SETTINGS = 0xE8001C0000000000ull,\n MCGR3_CNFG_SETTINGS = 0xEC001C0000000000ull,\n NET_CNTL0_HW_INIT_VALUE = 0x7C16222000000000ull,\n HANG_PULSE_0X10 = 0x10,\n HANG_PULSE_0X0F = 0x0F,\n HANG_PULSE_0X06 = 0x06,\n HANG_PULSE_0X17 = 0x17,\n HANG_PULSE_0X18 = 0x18,\n HANG_PULSE_0X22 = 0x22,\n HANG_PULSE_0X13 = 0x13,\n HANG_PULSE_0X03 = 0x03,\n OPCG_ALIGN_SETTING = 0x5000000000003020ull,\n INOP_ALIGN_SETTING_0X5 = 0x5,\n OPCG_WAIT_CYCLE_0X020 = 0x020,\n SCAN_RATIO_0X3 = 0x3,\n SYNC_PULSE_DELAY_0X0 = 0X00,\n SYNC_CONFIG_DEFAULT = 0X0000000000000000,\n HANG_PULSE_0X00 = 0x00,\n HANG_PULSE_0X01 = 0x01,\n HANG_PULSE_0X04 = 0x04,\n HANG_PULSE_0X1A = 0x1A,\n NET_CNTL1_HW_INIT_VALUE = 0x7200000000000000ull,\n MCGR2_CACHE_CNFG_SETTINGS = 0xF0001C0000000000ull,\n MCGR3_CACHE_CNFG_SETTINGS = 0xF4001C0000000000ull,\n MCGR4_CACHE_CNFG_SETTINGS = 0xF8001C0000000000ull,\n REGIONS_EXCEPT_VITAL = 0x7FF,\n SCAN_TYPES_EXCEPT_TIME_GPTR_REPR = 0xDCE,\n SCAN_TYPES_TIME_GPTR_REPR = 0x230,\n SCAN_RATIO_0X0 = 0x0,\n SYNC_CONFIG_4TO1 = 0X0800000000000000,\n HW_NS_DELAY = 200000, \/\/ unit is nano seconds\n SIM_CYCLE_DELAY = 10000, \/\/ unit is cycles\n HANG_PULSE_0X12 = 0x12,\n HANG_PULSE_0X1C = 0x1C,\n HANG_PULSE_0X05 = 0x05,\n HANG_PULSE_0X08 = 0x08\n};\n}\n\ntypedef fapi2::ReturnCode (*p9_sbe_chiplet_reset_FP_t)(const\n fapi2::Target&);\n\n\/\/\/ @brief Identify all good chiplets excluding EQ\/EC\n\/\/\/ -- All chiplets will be reset and PLLs started\n\/\/\/ -- Partial bad - All nest Chiplets must be good, MC, IO can be partial bad\n\/\/\/ Setup multicast groups for all chiplets\n\/\/\/ -- Can't use the multicast for all non-nest chiplets\n\/\/\/ -- This is intended to be the eventual product setting\n\/\/\/ -- This includes the core\/cache chiplets\n\/\/\/ For all good chiplets excluding EQ\/EC\n\/\/\/ -- Setup Chiplet GP3 regs\n\/\/\/ -- Reset to default state\n\/\/\/ -- Set chiplet enable on all all good chiplets excluding EQ\/EC\n\/\/\/ For all enabled chiplets excluding EQ\/EC\/Buses\n\/\/\/ -- Start vital clocks and release endpoint reset\n\/\/\/ -- PCB Slave error register Reset\n\/\/\/\n\/\/\/\n\/\/\/ @param[in] i_target_chip Reference to TARGET_TYPE_PROC_CHIP target\n\/\/\/ @return FAPI2_RC_SUCCESS if success, else error code.\nextern \"C\"\n{\n fapi2::ReturnCode p9_sbe_chiplet_reset(const\n fapi2::Target& i_target_chip);\n}\n\n#endif\n<|endoftext|>"} {"text":"\/*\n * Copyright 2011-2015 Blender Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"util_aligned_malloc.h\"\n\n#include \n\n\/* Adopted from Libmv. *\/\n\n#if !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__NetBSD__)\n\/* Needed for memalign on Linux and _aligned_alloc on Windows. *\/\n# ifdef FREE_WINDOWS\n\/* Make sure _aligned_malloc is included. *\/\n# ifdef __MSVCRT_VERSION__\n# undef __MSVCRT_VERSION__\n# endif\n# define __MSVCRT_VERSION__ 0x0700\n# endif \/* FREE_WINDOWS *\/\n# include \n#else\n\/* Apple's malloc is 16-byte aligned, and does not have malloc.h, so include\n * stdilb instead.\n *\/\n# include \n#endif\n\nCCL_NAMESPACE_BEGIN\n\nvoid *util_aligned_malloc(int size, int alignment)\n{\n#ifdef _WIN32\n\treturn _aligned_malloc(size, alignment);\n#elif defined(__APPLE__)\n\t\/* On Mac OS X, both the heap and the stack are guaranteed 16-byte aligned so\n\t * they work natively with SSE types with no further work.\n\t *\/\n\tassert(alignment == 16);\n\treturn malloc(size);\n#elif defined(__FreeBSD__) || defined(__NetBSD__)\n\tvoid *result;\n\tif (posix_memalign(&result, alignment, size)) {\n\t\t\/* Non-zero means allocation error\n\t\t * either no allocation or bad alignment value.\n\t\t *\/\n\t\treturn NULL;\n\t}\n\treturn result;\n#else \/* This is for Linux. *\/\n\treturn memalign(alignment, size);\n#endif\n}\n\nvoid util_aligned_free(void *ptr)\n{\n#ifdef _WIN32\n\t_aligned_free(ptr);\n#else\n\tfree(ptr);\n#endif\n}\n\nCCL_NAMESPACE_END\nMake aligned allocation to respect WITH_BLENDER_GUARDEDALLOC\/*\n * Copyright 2011-2015 Blender Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"util_aligned_malloc.h\"\n#include \"util_guarded_allocator.h\"\n\n#include \n\n\/* Adopted from Libmv. *\/\n\n#if !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__NetBSD__)\n\/* Needed for memalign on Linux and _aligned_alloc on Windows. *\/\n# ifdef FREE_WINDOWS\n\/* Make sure _aligned_malloc is included. *\/\n# ifdef __MSVCRT_VERSION__\n# undef __MSVCRT_VERSION__\n# endif\n# define __MSVCRT_VERSION__ 0x0700\n# endif \/* FREE_WINDOWS *\/\n# include \n#else\n\/* Apple's malloc is 16-byte aligned, and does not have malloc.h, so include\n * stdilb instead.\n *\/\n# include \n#endif\n\nCCL_NAMESPACE_BEGIN\n\nvoid *util_aligned_malloc(int size, int alignment)\n{\n#ifdef WITH_BLENDER_GUARDEDALLOC\n\treturn MEM_mallocN_aligned(size, alignment, \"Cycles Aligned Alloc\");\n#endif\n#ifdef _WIN32\n\treturn _aligned_malloc(size, alignment);\n#elif defined(__APPLE__)\n\t\/* On Mac OS X, both the heap and the stack are guaranteed 16-byte aligned so\n\t * they work natively with SSE types with no further work.\n\t *\/\n\tassert(alignment == 16);\n\treturn malloc(size);\n#elif defined(__FreeBSD__) || defined(__NetBSD__)\n\tvoid *result;\n\tif (posix_memalign(&result, alignment, size)) {\n\t\t\/* Non-zero means allocation error\n\t\t * either no allocation or bad alignment value.\n\t\t *\/\n\t\treturn NULL;\n\t}\n\treturn result;\n#else \/* This is for Linux. *\/\n\treturn memalign(alignment, size);\n#endif\n}\n\nvoid util_aligned_free(void *ptr)\n{\n#if defined(WITH_BLENDER_GUARDEDALLOC)\n\tif(ptr != NULL) {\n\t\tMEM_freeN(ptr);\n\t}\n#elif defined(_WIN32)\n\t_aligned_free(ptr);\n#else\n\tfree(ptr);\n#endif\n}\n\nCCL_NAMESPACE_END\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright © 2020 Arm Ltd and Contributors. All rights reserved.\n\/\/ SPDX-License-Identifier: MIT\n\/\/\n\n#include \"ClContextDeserializer.hpp\"\n#include \"ClContextSchema_generated.h\"\n\n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\nnamespace armnn\n{\n\nvoid ClContextDeserializer::Deserialize(arm_compute::CLCompileContext& clCompileContext,\n cl::Context& context,\n cl::Device& device,\n const std::string& filePath)\n{\n std::ifstream inputFileStream(filePath, std::ios::binary);\n std::vector binaryContent;\n while (inputFileStream)\n {\n char input;\n inputFileStream.get(input);\n if (inputFileStream)\n {\n binaryContent.push_back(static_cast(input));\n }\n }\n inputFileStream.close();\n DeserializeFromBinary(clCompileContext, context, device, binaryContent);\n}\n\nvoid ClContextDeserializer::DeserializeFromBinary(arm_compute::CLCompileContext& clCompileContext,\n cl::Context& context,\n cl::Device& device,\n const std::vector& binaryContent)\n{\n if (binaryContent.data() == nullptr)\n {\n throw InvalidArgumentException(fmt::format(\"Invalid (null) binary content {}\",\n CHECK_LOCATION().AsString()));\n }\n\n size_t binaryContentSize = binaryContent.size();\n flatbuffers::Verifier verifier(binaryContent.data(), binaryContentSize);\n if (verifier.VerifyBuffer() == false)\n {\n throw ParseException(fmt::format(\"Buffer doesn't conform to the expected Armnn \"\n \"flatbuffers format. size:{0} {1}\",\n binaryContentSize,\n CHECK_LOCATION().AsString()));\n }\n auto clContext = GetClContext(binaryContent.data());\n\n for (Program const* program : *clContext->programs())\n {\n const char* volatile programName = program->name()->c_str();\n auto programBinary = program->binary();\n std::vector binary(programBinary->begin(), programBinary->begin() + programBinary->size());\n\n cl::Program::Binaries binaries{ binary };\n std::vector devices {device};\n cl::Program theProgram(context, devices, binaries);\n theProgram.build();\n clCompileContext.add_built_program(programName, theProgram);\n }\n}\n\n} \/\/ namespace armnn\nUse mmap to load the clcache file\/\/\n\/\/ Copyright © 2020 Arm Ltd and Contributors. All rights reserved.\n\/\/ SPDX-License-Identifier: MIT\n\/\/\n\n#include \"ClContextDeserializer.hpp\"\n#include \"ClContextSchema_generated.h\"\n\n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n\n#if defined(__linux__)\n#define SERIALIZER_USE_MMAP 1\n#if SERIALIZER_USE_MMAP\n#include \n#include \n#include \n#include \n#endif\n#endif\n\nnamespace armnn\n{\n\nvoid ClContextDeserializer::Deserialize(arm_compute::CLCompileContext& clCompileContext,\n cl::Context& context,\n cl::Device& device,\n const std::string& filePath)\n{\n std::vector binaryContent;\n#if !SERIALIZER_USE_MMAP\n std::ifstream inputFileStream(filePath, std::ios::binary);\n while (inputFileStream)\n {\n char input;\n inputFileStream.get(input);\n if (inputFileStream)\n {\n binaryContent.push_back(static_cast(input));\n }\n }\n inputFileStream.close();\n#else\n struct stat statbuf;\n int fp = open(filePath.c_str(),O_RDONLY);\n if (!fp)\n {\n ARMNN_LOG(error) << (std::string(\"Cannot open file \") + filePath);\n return;\n }\n fstat(fp,&statbuf);\n const unsigned long dataSize = static_cast(statbuf.st_size);\n binaryContent.resize(static_cast(dataSize));\n void* ptrmem = mmap(NULL, dataSize,PROT_READ,MAP_PRIVATE,fp,0);\n if(ptrmem!=MAP_FAILED)\n {\n memcpy (binaryContent.data(), ptrmem, dataSize);\n }\n close(fp);\n if(ptrmem == MAP_FAILED)\n {\n ARMNN_LOG(error) << (std::string(\"Cannot map file \") + filePath);\n return;\n }\n#endif\n\n DeserializeFromBinary(clCompileContext, context, device, binaryContent);\n}\n\nvoid ClContextDeserializer::DeserializeFromBinary(arm_compute::CLCompileContext& clCompileContext,\n cl::Context& context,\n cl::Device& device,\n const std::vector& binaryContent)\n{\n if (binaryContent.data() == nullptr)\n {\n throw InvalidArgumentException(fmt::format(\"Invalid (null) binary content {}\",\n CHECK_LOCATION().AsString()));\n }\n\n size_t binaryContentSize = binaryContent.size();\n flatbuffers::Verifier verifier(binaryContent.data(), binaryContentSize);\n if (verifier.VerifyBuffer() == false)\n {\n throw ParseException(fmt::format(\"Buffer doesn't conform to the expected Armnn \"\n \"flatbuffers format. size:{0} {1}\",\n binaryContentSize,\n CHECK_LOCATION().AsString()));\n }\n auto clContext = GetClContext(binaryContent.data());\n\n for (Program const* program : *clContext->programs())\n {\n const char* volatile programName = program->name()->c_str();\n auto programBinary = program->binary();\n std::vector binary(programBinary->begin(), programBinary->begin() + programBinary->size());\n\n cl::Program::Binaries binaries{ binary };\n std::vector devices {device};\n cl::Program theProgram(context, devices, binaries);\n theProgram.build();\n clCompileContext.add_built_program(programName, theProgram);\n }\n}\n\n} \/\/ namespace armnn\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nclass ShowImage {\npublic:\n ShowImage()\n : m_gamma(2048),\n RGB_WINDOW_NAME {\"RGB image\"},\n DEPTH_WINDOW_NAME {\"Depth image\"},\n BINARY_WINDOW_NAME {\"Binary image\"}\n {\n for(int i = 0; i < 2048; i++) {\n float v = i \/ 2048.0;\n v = std::pow(v, 3) * 6;\n m_gamma[i] = v * 6 * 256;\n }\n\n cv::namedWindow(RGB_WINDOW_NAME);\n cv::namedWindow(DEPTH_WINDOW_NAME);\n cv::namedWindow(BINARY_WINDOW_NAME);\n }\n\n ~ShowImage() {\n cv::destroyWindow(RGB_WINDOW_NAME);\n cv::destroyWindow(DEPTH_WINDOW_NAME);\n cv::destroyWindow(BINARY_WINDOW_NAME);\n }\n\n void showRGB(const cv::Mat& rgb) {\n imshow(RGB_WINDOW_NAME, rgb);\n }\n\n void showBinary(const cv::Mat& binary) {\n imshow(BINARY_WINDOW_NAME, binary);\n }\n\n void showDepth(const cv::Mat& depth) {\n cv::Mat buf = cv::Mat::zeros(depth.size(), CV_16UC1);\n cv::Mat output = cv::Mat::zeros(depth.size(), CV_8UC3);\n cv::normalize(depth, buf, 0, 2013, cv::NORM_MINMAX);\n\n for (int i = 0; i < depth.rows * depth.cols; i++) {\n int y = (int)(i \/ depth.cols);\n int x = (int)(i % depth.cols);\n int pval = m_gamma[buf.at(i)];\n int lb = pval & 0xff;\n\n switch(pval >> 8) {\n case 0:\n output.at(y,x)[2] = 255;\n output.at(y,x)[1] = 255-lb;\n output.at(y,x)[0] = 255-lb;\n break;\n case 1:\n output.at(y,x)[2] = 255;\n output.at(y,x)[1] = lb;\n output.at(y,x)[0] = 0;\n break;\n case 2:\n output.at(y,x)[2] = 255-lb;\n output.at(y,x)[1] = 255;\n output.at(y,x)[0] = 0;\n break;\n case 3:\n output.at(y,x)[2] = 0;\n output.at(y,x)[1] = 255;\n output.at(y,x)[0] = lb;\n break;\n case 4:\n output.at(y,x)[2] = 0;\n output.at(y,x)[1] = 255-lb;\n output.at(y,x)[0] = 255;\n break;\n case 5:\n output.at(y,x)[2] = 0;\n output.at(y,x)[1] = 0;\n output.at(y,x)[0] = 255-lb;\n break;\n default:\n output.at(y,x)[2] = 0;\n output.at(y,x)[1] = 0;\n output.at(y,x)[0] = 0;\n break;\n }\n }\n imshow(DEPTH_WINDOW_NAME, output);\n }\n\nprivate:\n std::vector m_gamma;\n const std::string RGB_WINDOW_NAME;\n const std::string DEPTH_WINDOW_NAME;\n const std::string BINARY_WINDOW_NAME;\n};\n\n\nclass SearchTomato\n{\npublic:\n SearchTomato()\n : tomato_contours {},\n siObj {},\n server {},\n f(std::bind(&dynamic_reconfigure_callback, std::placeholders::_1, std::placeholders::_2))\n {\n server.setCallback(f);\n }\n\n void update(const cv::Mat& capture_rgb) {\n siObj.showRGB(capture_rgb);\n cv::Mat binary_mat = cv::Mat::zeros(capture_rgb.size(), CV_8UC1);\n imageProsessing(capture_rgb, binary_mat);\n siObj.showBinary(binary_mat);\n searchTomatoContours(binary_mat, tomato_contours);\n }\n\n bool searchTomato(const cv::Mat& capture_depth, geometry_msgs::Point& tomato_point) {\n siObj.showDepth(capture_depth);\n cv::Mat maskedDepth = cv::Mat::zeros(capture_depth.size(), CV_16UC1);\n cv::Mat mask = cv::Mat::zeros(capture_depth.size(), CV_8UC1);\n cv::drawContours(mask, tomato_contours, -1, cv::Scalar(255), CV_FILLED, 8);\n siObj.showBinary(mask);\n\n capture_depth.copyTo(maskedDepth, mask);\n return findClosePoint(maskedDepth, tomato_point);\n }\n\n bool searchTomato(const cv::Mat& capture_depth, geometry_msgs::PoseArray& tomato_poses) {\n tomato_poses.poses.clear();\n siObj.showDepth(capture_depth);\n cv::Mat maskedDepth = cv::Mat::zeros(capture_depth.size(), CV_16UC1);\n cv::Mat mask = cv::Mat::zeros(capture_depth.size(), CV_8UC1);\n for (std::size_t i {0}; i < tomato_contours.size(); ++i) {\n cv::drawContours(mask, tomato_contours, i, cv::Scalar(255), CV_FILLED, 8);\n siObj.showBinary(mask);\n\n capture_depth.copyTo(maskedDepth, mask);\n findClosePoint(maskedDepth, tomato_poses);\n }\n return tomato_poses.poses.empty() ? false : true;\n }\n\nprivate:\n static void dynamic_reconfigure_callback(kinect_tomato_searcher::SearchConfig& config, uint32_t level)\n {\n h_min_ = config.h_min;\n h_max_ = config.h_max;\n s_min_ = config.s_min;\n s_max_ = config.s_max;\n v_min_ = config.v_min;\n v_max_ = config.v_max;\n }\n\n void imageProsessing(const cv::Mat& rgb, cv::Mat& binary) {\n cv::Mat blur, hsv;\n cv::GaussianBlur(rgb, blur, cv::Size(5, 5), 4.0, 4.0);\n cv::cvtColor(blur, hsv, CV_BGR2HSV);\n redFilter(hsv, binary);\n cv::dilate(binary, binary, cv::Mat(), cv::Point(-1, -1), 2);\n cv::erode(binary, binary, cv::Mat(), cv::Point(-1, -1), 4);\n cv::dilate(binary, binary, cv::Mat(), cv::Point(-1, -1), 1);\n }\n\n void searchTomatoContours(const cv::Mat& binary, std::vector >& tomato_contours) {\n std::vector > contours;\n std::vector contour;\n cv::Rect bounding_box;\n float ratio_balance;\n\n cv::findContours(binary, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);\n\n tomato_contours.clear();\n while (!contours.empty()) {\n contour = contours.back();\n contours.pop_back();\n\n bounding_box = cv::boundingRect(contour);\n ratio_balance = (float)bounding_box.width \/ (float)bounding_box.height;\n if (ratio_balance > 1.0f) ratio_balance = 1.0f \/ ratio_balance;\n\n \/\/ delete mismach. that is smaller or spier or empty\n if (bounding_box.area() >= 400 && bounding_box.area() < cv::contourArea(contour)*2 && ratio_balance > 0.4f)\n tomato_contours.push_back(contour);\n }\n }\n\n void redFilter(const cv::Mat& hsv, cv::Mat& binary) {\n int a, x, y;\n for(y = 0; y < hsv.rows; y++) {\n for(x = 0; x < hsv.cols; x++) {\n a = hsv.step*y+(x*3);\n if((hsv.data[a] <= h_min_ || hsv.data[a] >= h_max_) &&\n (hsv.data[a+1] >= s_min_ && hsv.data[a+1] <= s_max_) &&\n (hsv.data[a+2] >= v_min_ && hsv.data[a+2] <= v_max_))\n binary.at(y,x) = 255;\n else\n binary.at(y,x) = 0;\n }\n }\n }\n\n bool findClosePoint(const cv::Mat& maskedDepth, geometry_msgs::Point& tomato_point) {\n uint16_t depth;\n constexpr uint16_t OVER_RANGE = 3000;\n uint16_t close_depth = OVER_RANGE;\n\n for (int y = 0; y < maskedDepth.rows; y++) {\n const uint16_t* line_point = maskedDepth.ptr(y);\n for (int x = 0; x < maskedDepth.cols; x++) {\n depth = line_point[x];\n if (512 < depth && depth < close_depth) {\n tomato_point.x = depth; \/\/ for ros coordinate system\n tomato_point.y = x - maskedDepth.cols \/ 2; \/\/ for ros coordinate system\n tomato_point.z = -(y - maskedDepth.rows \/ 2); \/\/ for ros coordinate system\n close_depth = depth;\n }\n }\n }\n return (close_depth != OVER_RANGE ? true : false);\n }\n\n bool findClosePoint(const cv::Mat& maskedDepth, geometry_msgs::PoseArray& tomato_poses) {\n geometry_msgs::Point tomato_point {};\n if (findClosePoint(maskedDepth, tomato_point)) {\n geometry_msgs::Pose tomato_pose {};\n tomato_pose.position = tomato_point;\n tomato_pose.orientation.w = 1.0;\n tomato_poses.poses.push_back(tomato_pose);\n return true;\n }\n return false;\n }\n\n static uint16_t h_min_;\n static uint16_t h_max_;\n static uint16_t s_min_;\n static uint16_t s_max_;\n static uint16_t v_min_;\n static uint16_t v_max_;\n\n std::vector > tomato_contours;\n ShowImage siObj;\n dynamic_reconfigure::Server server;\n dynamic_reconfigure::Server::CallbackType f;\n};\nuint16_t SearchTomato::h_min_;\nuint16_t SearchTomato::h_max_;\nuint16_t SearchTomato::s_min_;\nuint16_t SearchTomato::s_max_;\nuint16_t SearchTomato::v_min_;\nuint16_t SearchTomato::v_max_;\n\n\nclass ImageConverter {\nprivate:\n ros::NodeHandle nh;\n ros::NodeHandle tomapo_nh;\n ros::Publisher poses_pub;\n geometry_msgs::PoseArray pub_msg;\n image_transport::ImageTransport it;\n image_transport::Subscriber rgb_sub;\n image_transport::Subscriber depth_sub;\n cv_bridge::CvImageConstPtr rgb_ptr;\n cv_bridge::CvImageConstPtr depth_ptr;\n SearchTomato stObj;\n const std::size_t height_;\n const double angle_x_per_piccell_;\n const double angle_y_per_piccell_;\n static constexpr double PI {3.141592653589793};\n\npublic:\n ImageConverter(const std::size_t width, const std::size_t height, const double angle_of_view_x, const double angle_of_view_y)\n : nh {},\n tomapo_nh {nh, \"tomato_point\"},\n poses_pub {tomapo_nh.advertise(\"array\", 1)},\n it {nh},\n rgb_sub {it.subscribe(\"color\", 1, &ImageConverter::rgbCb, this)},\n depth_sub {it.subscribe(\"depth\", 1, &ImageConverter::depthCb, this)},\n stObj {},\n height_ {height},\n angle_x_per_piccell_ {(angle_of_view_x * PI \/ 180.0) \/ width},\n angle_y_per_piccell_ {(angle_of_view_y * PI \/ 180.0) \/ height}\n {\n pub_msg.header.frame_id = \"kinect\";\n }\n\n \/**\n * search tomato function.\n * get rgb image, and search tomato.\n * will tomato_point have data.\n *\n * @author Yusuke Doi\n *\/\n void rgbCb(const sensor_msgs::ImageConstPtr& msg) {\n \/\/ get rgb image on kinect\n try {\n rgb_ptr = cv_bridge::toCvShare(msg, \"bgr8\");\n } catch (cv_bridge::Exception& e) {\n ROS_ERROR(\"cv_bridge exception by rgb: %s\", e.what());\n }\n\n stObj.update(rgb_ptr->image);\n\n cv::waitKey(100);\n }\n\n void depthCb(const sensor_msgs::ImageConstPtr& msg) {\n try {\n depth_ptr = cv_bridge::toCvShare(msg, sensor_msgs::image_encodings::TYPE_16UC1);\n } catch (cv_bridge::Exception& e) {\n ROS_ERROR(\"cv_bridge exception by depth: %s\", e.what());\n }\n\n if (stObj.searchTomato(depth_ptr->image, pub_msg)) {\n pub_msg.header.stamp = ros::Time::now();\n for (auto& tomato_pose : pub_msg.poses) {\n tomato_pose.position.y = tomato_pose.position.x * tan(angle_x_per_piccell_ * tomato_pose.position.y) \/ 1000.0; \/\/ convert to m\n tomato_pose.position.z = tomato_pose.position.x * tan(angle_y_per_piccell_ * tomato_pose.position.z) \/ 1000.0; \/\/ convert to m\n tomato_pose.position.x = tomato_pose.position.x \/ 1000.0; \/\/ convert to m\n }\n poses_pub.publish(pub_msg);\n }\n\n cv::waitKey(100);\n }\n};\n\nint main(int argc, char** argv) {\n ros::init(argc, argv, \"kinect_tomato_searcher_node\");\n ImageConverter ic {512, 424, 70, 60};\n ros::spin();\n return 0;\n}\nRemove max; unkown max value#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nclass ShowImage {\npublic:\n ShowImage()\n : m_gamma(2048),\n RGB_WINDOW_NAME {\"RGB image\"},\n DEPTH_WINDOW_NAME {\"Depth image\"},\n BINARY_WINDOW_NAME {\"Binary image\"}\n {\n for(int i = 0; i < 2048; i++) {\n float v = i \/ 2048.0;\n v = std::pow(v, 3) * 6;\n m_gamma[i] = v * 6 * 256;\n }\n\n cv::namedWindow(RGB_WINDOW_NAME);\n cv::namedWindow(DEPTH_WINDOW_NAME);\n cv::namedWindow(BINARY_WINDOW_NAME);\n }\n\n ~ShowImage() {\n cv::destroyWindow(RGB_WINDOW_NAME);\n cv::destroyWindow(DEPTH_WINDOW_NAME);\n cv::destroyWindow(BINARY_WINDOW_NAME);\n }\n\n void showRGB(const cv::Mat& rgb) {\n imshow(RGB_WINDOW_NAME, rgb);\n }\n\n void showBinary(const cv::Mat& binary) {\n imshow(BINARY_WINDOW_NAME, binary);\n }\n\n void showDepth(const cv::Mat& depth) {\n cv::Mat buf = cv::Mat::zeros(depth.size(), CV_16UC1);\n cv::Mat output = cv::Mat::zeros(depth.size(), CV_8UC3);\n cv::normalize(depth, buf, 0, 2013, cv::NORM_MINMAX);\n\n for (int i = 0; i < depth.rows * depth.cols; i++) {\n int y = (int)(i \/ depth.cols);\n int x = (int)(i % depth.cols);\n int pval = m_gamma[buf.at(i)];\n int lb = pval & 0xff;\n\n switch(pval >> 8) {\n case 0:\n output.at(y,x)[2] = 255;\n output.at(y,x)[1] = 255-lb;\n output.at(y,x)[0] = 255-lb;\n break;\n case 1:\n output.at(y,x)[2] = 255;\n output.at(y,x)[1] = lb;\n output.at(y,x)[0] = 0;\n break;\n case 2:\n output.at(y,x)[2] = 255-lb;\n output.at(y,x)[1] = 255;\n output.at(y,x)[0] = 0;\n break;\n case 3:\n output.at(y,x)[2] = 0;\n output.at(y,x)[1] = 255;\n output.at(y,x)[0] = lb;\n break;\n case 4:\n output.at(y,x)[2] = 0;\n output.at(y,x)[1] = 255-lb;\n output.at(y,x)[0] = 255;\n break;\n case 5:\n output.at(y,x)[2] = 0;\n output.at(y,x)[1] = 0;\n output.at(y,x)[0] = 255-lb;\n break;\n default:\n output.at(y,x)[2] = 0;\n output.at(y,x)[1] = 0;\n output.at(y,x)[0] = 0;\n break;\n }\n }\n imshow(DEPTH_WINDOW_NAME, output);\n }\n\nprivate:\n std::vector m_gamma;\n const std::string RGB_WINDOW_NAME;\n const std::string DEPTH_WINDOW_NAME;\n const std::string BINARY_WINDOW_NAME;\n};\n\n\nclass SearchTomato\n{\npublic:\n SearchTomato()\n : tomato_contours {},\n siObj {},\n server {},\n f(std::bind(&dynamic_reconfigure_callback, std::placeholders::_1, std::placeholders::_2))\n {\n server.setCallback(f);\n }\n\n void update(const cv::Mat& capture_rgb) {\n siObj.showRGB(capture_rgb);\n cv::Mat binary_mat = cv::Mat::zeros(capture_rgb.size(), CV_8UC1);\n imageProsessing(capture_rgb, binary_mat);\n siObj.showBinary(binary_mat);\n searchTomatoContours(binary_mat, tomato_contours);\n }\n\n bool searchTomato(const cv::Mat& capture_depth, geometry_msgs::Point& tomato_point) {\n siObj.showDepth(capture_depth);\n cv::Mat maskedDepth = cv::Mat::zeros(capture_depth.size(), CV_16UC1);\n cv::Mat mask = cv::Mat::zeros(capture_depth.size(), CV_8UC1);\n cv::drawContours(mask, tomato_contours, -1, cv::Scalar(255), CV_FILLED, 8);\n siObj.showBinary(mask);\n\n capture_depth.copyTo(maskedDepth, mask);\n return findClosePoint(maskedDepth, tomato_point);\n }\n\n bool searchTomato(const cv::Mat& capture_depth, geometry_msgs::PoseArray& tomato_poses) {\n tomato_poses.poses.clear();\n siObj.showDepth(capture_depth);\n cv::Mat maskedDepth = cv::Mat::zeros(capture_depth.size(), CV_16UC1);\n cv::Mat mask = cv::Mat::zeros(capture_depth.size(), CV_8UC1);\n for (std::size_t i {0}; i < tomato_contours.size(); ++i) {\n cv::drawContours(mask, tomato_contours, i, cv::Scalar(255), CV_FILLED, 8);\n siObj.showBinary(mask);\n\n capture_depth.copyTo(maskedDepth, mask);\n findClosePoint(maskedDepth, tomato_poses);\n }\n return tomato_poses.poses.empty() ? false : true;\n }\n\nprivate:\n static void dynamic_reconfigure_callback(kinect_tomato_searcher::SearchConfig& config, uint32_t level)\n {\n h_min_ = config.h_min;\n h_max_ = config.h_max;\n s_min_ = config.s_min;\n s_max_ = config.s_max;\n v_min_ = config.v_min;\n v_max_ = config.v_max;\n }\n\n void imageProsessing(const cv::Mat& rgb, cv::Mat& binary) {\n cv::Mat blur, hsv;\n cv::GaussianBlur(rgb, blur, cv::Size(5, 5), 4.0, 4.0);\n cv::cvtColor(blur, hsv, CV_BGR2HSV);\n redFilter(hsv, binary);\n cv::dilate(binary, binary, cv::Mat(), cv::Point(-1, -1), 2);\n cv::erode(binary, binary, cv::Mat(), cv::Point(-1, -1), 4);\n cv::dilate(binary, binary, cv::Mat(), cv::Point(-1, -1), 1);\n }\n\n void searchTomatoContours(const cv::Mat& binary, std::vector >& tomato_contours) {\n std::vector > contours;\n std::vector contour;\n cv::Rect bounding_box;\n float ratio_balance;\n\n cv::findContours(binary, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);\n\n tomato_contours.clear();\n while (!contours.empty()) {\n contour = contours.back();\n contours.pop_back();\n\n bounding_box = cv::boundingRect(contour);\n ratio_balance = (float)bounding_box.width \/ (float)bounding_box.height;\n if (ratio_balance > 1.0f) ratio_balance = 1.0f \/ ratio_balance;\n\n \/\/ delete mismach. that is smaller or spier or empty\n if (bounding_box.area() >= 400 && bounding_box.area() < cv::contourArea(contour)*2 && ratio_balance > 0.4f)\n tomato_contours.push_back(contour);\n }\n }\n\n void redFilter(const cv::Mat& hsv, cv::Mat& binary) {\n int a, x, y;\n for(y = 0; y < hsv.rows; y++) {\n for(x = 0; x < hsv.cols; x++) {\n a = hsv.step*y+(x*3);\n if((hsv.data[a] <= h_min_ || hsv.data[a] >= h_max_) &&\n (hsv.data[a+1] >= s_min_) &&\n (hsv.data[a+2] >= v_min_))\n binary.at(y,x) = 255;\n else\n binary.at(y,x) = 0;\n }\n }\n }\n\n bool findClosePoint(const cv::Mat& maskedDepth, geometry_msgs::Point& tomato_point) {\n uint16_t depth;\n constexpr uint16_t OVER_RANGE = 3000;\n uint16_t close_depth = OVER_RANGE;\n\n for (int y = 0; y < maskedDepth.rows; y++) {\n const uint16_t* line_point = maskedDepth.ptr(y);\n for (int x = 0; x < maskedDepth.cols; x++) {\n depth = line_point[x];\n if (512 < depth && depth < close_depth) {\n tomato_point.x = depth; \/\/ for ros coordinate system\n tomato_point.y = x - maskedDepth.cols \/ 2; \/\/ for ros coordinate system\n tomato_point.z = -(y - maskedDepth.rows \/ 2); \/\/ for ros coordinate system\n close_depth = depth;\n }\n }\n }\n return (close_depth != OVER_RANGE ? true : false);\n }\n\n bool findClosePoint(const cv::Mat& maskedDepth, geometry_msgs::PoseArray& tomato_poses) {\n geometry_msgs::Point tomato_point {};\n if (findClosePoint(maskedDepth, tomato_point)) {\n geometry_msgs::Pose tomato_pose {};\n tomato_pose.position = tomato_point;\n tomato_pose.orientation.w = 1.0;\n tomato_poses.poses.push_back(tomato_pose);\n return true;\n }\n return false;\n }\n\n static uint16_t h_min_;\n static uint16_t h_max_;\n static uint16_t s_min_;\n static uint16_t s_max_;\n static uint16_t v_min_;\n static uint16_t v_max_;\n\n std::vector > tomato_contours;\n ShowImage siObj;\n dynamic_reconfigure::Server server;\n dynamic_reconfigure::Server::CallbackType f;\n};\nuint16_t SearchTomato::h_min_;\nuint16_t SearchTomato::h_max_;\nuint16_t SearchTomato::s_min_;\nuint16_t SearchTomato::s_max_;\nuint16_t SearchTomato::v_min_;\nuint16_t SearchTomato::v_max_;\n\n\nclass ImageConverter {\nprivate:\n ros::NodeHandle nh;\n ros::NodeHandle tomapo_nh;\n ros::Publisher poses_pub;\n geometry_msgs::PoseArray pub_msg;\n image_transport::ImageTransport it;\n image_transport::Subscriber rgb_sub;\n image_transport::Subscriber depth_sub;\n cv_bridge::CvImageConstPtr rgb_ptr;\n cv_bridge::CvImageConstPtr depth_ptr;\n SearchTomato stObj;\n const std::size_t height_;\n const double angle_x_per_piccell_;\n const double angle_y_per_piccell_;\n static constexpr double PI {3.141592653589793};\n\npublic:\n ImageConverter(const std::size_t width, const std::size_t height, const double angle_of_view_x, const double angle_of_view_y)\n : nh {},\n tomapo_nh {nh, \"tomato_point\"},\n poses_pub {tomapo_nh.advertise(\"array\", 1)},\n it {nh},\n rgb_sub {it.subscribe(\"color\", 1, &ImageConverter::rgbCb, this)},\n depth_sub {it.subscribe(\"depth\", 1, &ImageConverter::depthCb, this)},\n stObj {},\n height_ {height},\n angle_x_per_piccell_ {(angle_of_view_x * PI \/ 180.0) \/ width},\n angle_y_per_piccell_ {(angle_of_view_y * PI \/ 180.0) \/ height}\n {\n pub_msg.header.frame_id = \"kinect\";\n }\n\n \/**\n * search tomato function.\n * get rgb image, and search tomato.\n * will tomato_point have data.\n *\n * @author Yusuke Doi\n *\/\n void rgbCb(const sensor_msgs::ImageConstPtr& msg) {\n \/\/ get rgb image on kinect\n try {\n rgb_ptr = cv_bridge::toCvShare(msg, \"bgr8\");\n } catch (cv_bridge::Exception& e) {\n ROS_ERROR(\"cv_bridge exception by rgb: %s\", e.what());\n }\n\n stObj.update(rgb_ptr->image);\n\n cv::waitKey(100);\n }\n\n void depthCb(const sensor_msgs::ImageConstPtr& msg) {\n try {\n depth_ptr = cv_bridge::toCvShare(msg, sensor_msgs::image_encodings::TYPE_16UC1);\n } catch (cv_bridge::Exception& e) {\n ROS_ERROR(\"cv_bridge exception by depth: %s\", e.what());\n }\n\n if (stObj.searchTomato(depth_ptr->image, pub_msg)) {\n pub_msg.header.stamp = ros::Time::now();\n for (auto& tomato_pose : pub_msg.poses) {\n tomato_pose.position.y = tomato_pose.position.x * tan(angle_x_per_piccell_ * tomato_pose.position.y) \/ 1000.0; \/\/ convert to m\n tomato_pose.position.z = tomato_pose.position.x * tan(angle_y_per_piccell_ * tomato_pose.position.z) \/ 1000.0; \/\/ convert to m\n tomato_pose.position.x = tomato_pose.position.x \/ 1000.0; \/\/ convert to m\n }\n poses_pub.publish(pub_msg);\n }\n\n cv::waitKey(100);\n }\n};\n\nint main(int argc, char** argv) {\n ros::init(argc, argv, \"kinect_tomato_searcher_node\");\n ImageConverter ic {512, 424, 70, 60};\n ros::spin();\n return 0;\n}\n<|endoftext|>"} {"text":"#ifndef FUNCTIONS_HPP\n#define FUNCTIONS_HPP\n\n#include \"constants.hpp\"\n\nnamespace cutehmi {\n\n\/**\n * Epsilon for a number. Get epsilon for real number @a r, that means smallest number which added to @a r changes value of @a r.\n * @param r real number.\n * @return smallest number, which added to @a r changes value of @a r. If @a r is positive number, then returned number is also\n * positive. Otherwise negative number is returned.\n *\n * @see absEps().\n *\/\ninline\nqreal eps(qreal r)\n{\n\tstatic constexpr qreal MACHINE_EPS = std::numeric_limits::epsilon() * 0.5;\n\n\tint exp;\n\tstd::frexp(r, & exp);\n\treturn std::ldexp(std::signbit(r) ? -MACHINE_EPS : MACHINE_EPS, exp);\n}\n\n\/**\n * Absolute epsilon for a number. Works in similar way to eps() function, except that absolute value is returned instead of signed\n * one.\n * @param r real number.\n * @return smallest number which added to @a r changes value of @a r. Always non-negative value is returned.\n *\n * @see eps().\n *\/\ninline\nqreal absEps(qreal r)\n{\n\tstatic constexpr qreal MACHINE_EPS = std::numeric_limits::epsilon() * 0.5;\n\n\tint exp;\n\tstd::frexp(r, & exp);\n\treturn std::ldexp(MACHINE_EPS, exp);\n}\n\n\/**\n * Approximately equal. Compares real numbers @a r1, @a r2.\n * @param r1 first number to compare.\n * @param r2 second number to compare.\n * @param eps epsilon tolerance parameter used in comparison.\n * @return @p true when @a r1 and @a r2 are approximately equal, @p false otherwise.\n *\n * @see ale().\n *\n * @internal Donald E. Knuth \"Art of Computer Programming\" [P 4.2.2 Vol2].\n *\/\ninline\nbool ape(qreal r1, qreal r2, qreal eps = EPS)\n{\n\tint exp1, exp2;\n\tstd::frexp(r1, & exp1);\n\tstd::frexp(r2, & exp2);\n\n\t\/\/ For some reason <= is used in the book to compare both sides. There may be a reason for this, so I'll leave it for now, but\n\t\/\/ the consequence is that image of a function is a bit weird, e.g.:\n\t\/\/ ape(1.0, 1.99, 0.25) -> false, ape(1.0, 2.0, 0.25) -> true, ape(1.0, 2.01, 0.25) -> false\n\treturn std::abs(r2 - r1) <= std::ldexp(eps, std::max(exp1, exp2));\n}\n\n\/**\n * Almost equal. Compares real numbers @a r1, @a r2. Function similar to ape(), however ale() is slightly stronger than ape() (@a r1\n * and @a r2 must be slightly closer to each other to manifest equality). This function can be problematic, when one of the values\n * is exactly zero, because in such case it returns @p true only if second argument is also exactly zero.\n * @param r1 first number to compare.\n * @param r2 second number to compare.\n * @param eps epsilon tolerance parameter used in comparison.\n * @return @p true when @a r1 and @a r2 are almost equal, @p false otherwise.\n *\n * @see ape().\n *\n * @internal Donald E. Knuth \"Art of Computer Programming\" [P 4.2.2 Vol2].\n *\/\ninline\nbool ale(qreal r1, qreal r2, qreal eps = EPS)\n{\n\tint exp1, exp2;\n\tstd::frexp(r1, & exp1);\n\tstd::frexp(r2, & exp2);\n\n\treturn std::abs(r2 - r1) <= std::ldexp(eps, std::min(exp1, exp2));\n}\n\n\/**\n * Considerably less than.\n * @param r1 first number to compare.\n * @param r2 second number to compare.\n * @param eps epsilon tolerance parameter used in comparison.\n * @return @p true when @a r1 is considerably less than @a r2, @p false otherwise.\n *\n * @internal Donald E. Knuth \"Art of Computer Programming\" [P 4.2.2 Vol2].\n *\/\ninline\nbool clt(qreal r1, qreal r2, qreal eps = EPS)\n{\n\tint exp1, exp2;\n\tstd::frexp(r1, & exp1);\n\tstd::frexp(r2, & exp2);\n\n\treturn r2 - r1 > std::ldexp(eps, std::max(exp1, exp2));\n}\n\n\/**\n * Considerably greater than.\n * @param r1 first number to compare.\n * @param r2 second number to compare.\n * @param eps epsilon tolerance parameter used in comparison.\n * @return @p true when @a r1 is considerably greater than @a r2, @p false otherwise.\n *\n * @internal Donald E. Knuth \"Art of Computer Programming\" [P 4.2.2 Vol2].\n *\/\ninline\nbool cgt(qreal r1, qreal r2, qreal eps = EPS)\n{\n\tint exp1, exp2;\n\tstd::frexp(r1, & exp1);\n\tstd::frexp(r2, & exp2);\n\n\treturn r1 - r2 > std::ldexp(eps, std::max(exp1, exp2));\n}\n\n}\n\n#endif \/\/ FUNCTIONS_HPP\nRename constants.#ifndef FUNCTIONS_HPP\n#define FUNCTIONS_HPP\n\n#include \"constants.hpp\"\n\nnamespace cutehmi {\n\n\/**\n * Epsilon for a number. Get epsilon for real number @a r, that means smallest number which added to @a r changes value of @a r.\n * @param r real number.\n * @return smallest number, which added to @a r changes value of @a r. If @a r is positive number, then returned number is also\n * positive. Otherwise negative number is returned.\n *\n * @see absEps().\n *\/\ninline\nqreal eps(qreal r)\n{\n\tstatic constexpr qreal HALF_EPS = std::numeric_limits::epsilon() * 0.5;\n\n\tint exp;\n\tstd::frexp(r, & exp);\n\treturn std::ldexp(std::signbit(r) ? -HALF_EPS : HALF_EPS, exp);\n}\n\n\/**\n * Absolute epsilon for a number. Works in similar way to eps() function, except that absolute value is returned instead of signed\n * one.\n * @param r real number.\n * @return smallest number which added to @a r changes value of @a r. Always non-negative value is returned.\n *\n * @see eps().\n *\/\ninline\nqreal absEps(qreal r)\n{\n\tstatic constexpr qreal HALF_EPS = std::numeric_limits::epsilon() * 0.5;\n\n\tint exp;\n\tstd::frexp(r, & exp);\n\treturn std::ldexp(HALF_EPS, exp);\n}\n\n\/**\n * Approximately equal. Compares real numbers @a r1, @a r2.\n * @param r1 first number to compare.\n * @param r2 second number to compare.\n * @param eps epsilon tolerance parameter used in comparison.\n * @return @p true when @a r1 and @a r2 are approximately equal, @p false otherwise.\n *\n * @see ale().\n *\n * @internal Donald E. Knuth \"Art of Computer Programming\" [P 4.2.2 Vol2].\n *\/\ninline\nbool ape(qreal r1, qreal r2, qreal eps = EPS)\n{\n\tint exp1, exp2;\n\tstd::frexp(r1, & exp1);\n\tstd::frexp(r2, & exp2);\n\n\t\/\/ For some reason <= is used in the book to compare both sides. There may be a reason for this, so I'll leave it for now, but\n\t\/\/ the consequence is that image of a function is a bit weird, e.g.:\n\t\/\/ ape(1.0, 1.99, 0.25) -> false, ape(1.0, 2.0, 0.25) -> true, ape(1.0, 2.01, 0.25) -> false\n\treturn std::abs(r2 - r1) <= std::ldexp(eps, std::max(exp1, exp2));\n}\n\n\/**\n * Almost equal. Compares real numbers @a r1, @a r2. Function similar to ape(), however ale() is slightly stronger than ape() (@a r1\n * and @a r2 must be slightly closer to each other to manifest equality). This function can be problematic, when one of the values\n * is exactly zero, because in such case it returns @p true only if second argument is also exactly zero.\n * @param r1 first number to compare.\n * @param r2 second number to compare.\n * @param eps epsilon tolerance parameter used in comparison.\n * @return @p true when @a r1 and @a r2 are almost equal, @p false otherwise.\n *\n * @see ape().\n *\n * @internal Donald E. Knuth \"Art of Computer Programming\" [P 4.2.2 Vol2].\n *\/\ninline\nbool ale(qreal r1, qreal r2, qreal eps = EPS)\n{\n\tint exp1, exp2;\n\tstd::frexp(r1, & exp1);\n\tstd::frexp(r2, & exp2);\n\n\treturn std::abs(r2 - r1) <= std::ldexp(eps, std::min(exp1, exp2));\n}\n\n\/**\n * Considerably less than.\n * @param r1 first number to compare.\n * @param r2 second number to compare.\n * @param eps epsilon tolerance parameter used in comparison.\n * @return @p true when @a r1 is considerably less than @a r2, @p false otherwise.\n *\n * @internal Donald E. Knuth \"Art of Computer Programming\" [P 4.2.2 Vol2].\n *\/\ninline\nbool clt(qreal r1, qreal r2, qreal eps = EPS)\n{\n\tint exp1, exp2;\n\tstd::frexp(r1, & exp1);\n\tstd::frexp(r2, & exp2);\n\n\treturn r2 - r1 > std::ldexp(eps, std::max(exp1, exp2));\n}\n\n\/**\n * Considerably greater than.\n * @param r1 first number to compare.\n * @param r2 second number to compare.\n * @param eps epsilon tolerance parameter used in comparison.\n * @return @p true when @a r1 is considerably greater than @a r2, @p false otherwise.\n *\n * @internal Donald E. Knuth \"Art of Computer Programming\" [P 4.2.2 Vol2].\n *\/\ninline\nbool cgt(qreal r1, qreal r2, qreal eps = EPS)\n{\n\tint exp1, exp2;\n\tstd::frexp(r1, & exp1);\n\tstd::frexp(r2, & exp2);\n\n\treturn r1 - r2 > std::ldexp(eps, std::max(exp1, exp2));\n}\n\n}\n\n#endif \/\/ FUNCTIONS_HPP\n<|endoftext|>"} {"text":"\/\/ Copyright 2014 BVLC and contributors.\n\n#include \n#include \n\n#include \"gtest\/gtest.h\"\n#include \"caffe\/blob.hpp\"\n#include \"caffe\/common.hpp\"\n#include \"caffe\/filler.hpp\"\n#include \"caffe\/vision_layers.hpp\"\n#include \"caffe\/test\/test_gradient_check_util.hpp\"\n\n#include \"caffe\/test\/test_caffe_main.hpp\"\n\nnamespace caffe {\n\ntemplate \nclass ConvolutionLayerTest : public MultiDeviceTest {\n typedef typename TypeParam::Dtype Dtype;\n\n protected:\n ConvolutionLayerTest()\n : blob_bottom_(new Blob(2, 3, 6, 4)),\n blob_bottom_2_(new Blob(2, 3, 6, 4)),\n blob_top_(new Blob()),\n blob_top_2_(new Blob()) {}\n virtual void SetUp() {\n \/\/ fill the values\n FillerParameter filler_param;\n filler_param.set_value(1.);\n GaussianFiller filler(filler_param);\n filler.Fill(this->blob_bottom_);\n filler.Fill(this->blob_bottom_2_);\n blob_bottom_vec_.push_back(blob_bottom_);\n blob_top_vec_.push_back(blob_top_);\n }\n\n virtual ~ConvolutionLayerTest() {\n delete blob_bottom_;\n delete blob_bottom_2_;\n delete blob_top_;\n delete blob_top_2_;\n }\n\n Blob* const blob_bottom_;\n Blob* const blob_bottom_2_;\n Blob* const blob_top_;\n Blob* const blob_top_2_;\n vector*> blob_bottom_vec_;\n vector*> blob_top_vec_;\n};\n\nTYPED_TEST_CASE(ConvolutionLayerTest, TestDtypesAndDevices);\n\nTYPED_TEST(ConvolutionLayerTest, TestSetup) {\n typedef typename TypeParam::Dtype Dtype;\n LayerParameter layer_param;\n ConvolutionParameter* convolution_param =\n layer_param.mutable_convolution_param();\n convolution_param->set_kernel_size(3);\n convolution_param->set_stride(2);\n convolution_param->set_num_output(4);\n this->blob_bottom_vec_.push_back(this->blob_bottom_2_);\n this->blob_top_vec_.push_back(this->blob_top_2_);\n shared_ptr > layer(\n new ConvolutionLayer(layer_param));\n layer->SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n EXPECT_EQ(this->blob_top_->num(), 2);\n EXPECT_EQ(this->blob_top_->channels(), 4);\n EXPECT_EQ(this->blob_top_->height(), 2);\n EXPECT_EQ(this->blob_top_->width(), 1);\n EXPECT_EQ(this->blob_top_2_->num(), 2);\n EXPECT_EQ(this->blob_top_2_->channels(), 4);\n EXPECT_EQ(this->blob_top_2_->height(), 2);\n EXPECT_EQ(this->blob_top_2_->width(), 1);\n \/\/ setting group should not change the shape\n convolution_param->set_num_output(3);\n convolution_param->set_group(3);\n layer.reset(new ConvolutionLayer(layer_param));\n layer->SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n EXPECT_EQ(this->blob_top_->num(), 2);\n EXPECT_EQ(this->blob_top_->channels(), 3);\n EXPECT_EQ(this->blob_top_->height(), 2);\n EXPECT_EQ(this->blob_top_->width(), 1);\n EXPECT_EQ(this->blob_top_2_->num(), 2);\n EXPECT_EQ(this->blob_top_2_->channels(), 3);\n EXPECT_EQ(this->blob_top_2_->height(), 2);\n EXPECT_EQ(this->blob_top_2_->width(), 1);\n}\n\nTYPED_TEST(ConvolutionLayerTest, TestSimpleConvolution) {\n \/\/ We will simply see if the convolution layer carries out averaging well.\n typedef typename TypeParam::Dtype Dtype;\n shared_ptr > filler;\n FillerParameter filler_param;\n filler_param.set_value(1.);\n filler.reset(new ConstantFiller(filler_param));\n filler->Fill(this->blob_bottom_);\n filler_param.set_value(2.);\n filler.reset(new ConstantFiller(filler_param));\n filler->Fill(this->blob_bottom_2_);\n this->blob_bottom_vec_.push_back(this->blob_bottom_2_);\n this->blob_top_vec_.push_back(this->blob_top_2_);\n LayerParameter layer_param;\n ConvolutionParameter* convolution_param =\n layer_param.mutable_convolution_param();\n convolution_param->set_kernel_size(3);\n convolution_param->set_stride(2);\n convolution_param->set_num_output(4);\n convolution_param->mutable_weight_filler()->set_type(\"constant\");\n convolution_param->mutable_weight_filler()->set_value(1);\n convolution_param->mutable_bias_filler()->set_type(\"constant\");\n convolution_param->mutable_bias_filler()->set_value(0.1);\n shared_ptr > layer(\n new ConvolutionLayer(layer_param));\n layer->SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n layer->Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));\n \/\/ After the convolution, the output should all have output values 27.1\n const Dtype* top_data = this->blob_top_->cpu_data();\n for (int i = 0; i < this->blob_top_->count(); ++i) {\n EXPECT_NEAR(top_data[i], 27.1, 1e-4);\n }\n top_data = this->blob_top_2_->cpu_data();\n for (int i = 0; i < this->blob_top_2_->count(); ++i) {\n EXPECT_NEAR(top_data[i], 54.1, 1e-4);\n }\n}\n\nTYPED_TEST(ConvolutionLayerTest, TestSimpleConvolutionGroup) {\n \/\/ We will simply see if the convolution layer carries out averaging well.\n typedef typename TypeParam::Dtype Dtype;\n FillerParameter filler_param;\n filler_param.set_value(1.);\n ConstantFiller filler(filler_param);\n filler.Fill(this->blob_bottom_);\n Dtype* bottom_data = this->blob_bottom_->mutable_cpu_data();\n for (int n = 0; n < this->blob_bottom_->num(); ++n) {\n for (int c = 0; c < this->blob_bottom_->channels(); ++c) {\n for (int h = 0; h < this->blob_bottom_->height(); ++h) {\n for (int w = 0; w < this->blob_bottom_->width(); ++w) {\n bottom_data[this->blob_bottom_->offset(n, c, h, w)] = c;\n }\n }\n }\n }\n LayerParameter layer_param;\n ConvolutionParameter* convolution_param =\n layer_param.mutable_convolution_param();\n convolution_param->set_kernel_size(3);\n convolution_param->set_stride(2);\n convolution_param->set_num_output(3);\n convolution_param->set_group(3);\n convolution_param->mutable_weight_filler()->set_type(\"constant\");\n convolution_param->mutable_weight_filler()->set_value(1);\n convolution_param->mutable_bias_filler()->set_type(\"constant\");\n convolution_param->mutable_bias_filler()->set_value(0.1);\n shared_ptr > layer(\n new ConvolutionLayer(layer_param));\n layer->SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n layer->Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));\n \/\/ After the convolution, the output should all have output values 9.1\n const Dtype* top_data = this->blob_top_->cpu_data();\n for (int n = 0; n < this->blob_top_->num(); ++n) {\n for (int c = 0; c < this->blob_top_->channels(); ++c) {\n for (int h = 0; h < this->blob_top_->height(); ++h) {\n for (int w = 0; w < this->blob_top_->width(); ++w) {\n Dtype data = top_data[this->blob_top_->offset(n, c, h, w)];\n EXPECT_NEAR(data, c * 9 + 0.1, 1e-4);\n }\n }\n }\n }\n}\n\nTYPED_TEST(ConvolutionLayerTest, TestGradient) {\n typedef typename TypeParam::Dtype Dtype;\n LayerParameter layer_param;\n ConvolutionParameter* convolution_param =\n layer_param.mutable_convolution_param();\n this->blob_bottom_vec_.push_back(this->blob_bottom_2_);\n this->blob_top_vec_.push_back(this->blob_top_2_);\n convolution_param->set_kernel_size(3);\n convolution_param->set_stride(2);\n convolution_param->set_num_output(2);\n convolution_param->mutable_weight_filler()->set_type(\"gaussian\");\n convolution_param->mutable_bias_filler()->set_type(\"gaussian\");\n ConvolutionLayer layer(layer_param);\n GradientChecker checker(1e-2, 1e-3);\n checker.CheckGradientExhaustive(&layer, &(this->blob_bottom_vec_),\n &(this->blob_top_vec_));\n}\n\nTYPED_TEST(ConvolutionLayerTest, TestGradientGroup) {\n typedef typename TypeParam::Dtype Dtype;\n LayerParameter layer_param;\n ConvolutionParameter* convolution_param =\n layer_param.mutable_convolution_param();\n convolution_param->set_kernel_size(3);\n convolution_param->set_stride(2);\n convolution_param->set_num_output(3);\n convolution_param->set_group(3);\n convolution_param->mutable_weight_filler()->set_type(\"gaussian\");\n convolution_param->mutable_bias_filler()->set_type(\"gaussian\");\n ConvolutionLayer layer(layer_param);\n GradientChecker checker(1e-2, 1e-3);\n checker.CheckGradientExhaustive(&layer, &(this->blob_bottom_vec_),\n &(this->blob_top_vec_));\n}\n\n} \/\/ namespace caffe\ntest non-square filters by separable convolution of Sobel operator\/\/ Copyright 2014 BVLC and contributors.\n\n#include \n#include \n\n#include \"gtest\/gtest.h\"\n#include \"caffe\/blob.hpp\"\n#include \"caffe\/common.hpp\"\n#include \"caffe\/filler.hpp\"\n#include \"caffe\/vision_layers.hpp\"\n#include \"caffe\/test\/test_gradient_check_util.hpp\"\n\n#include \"caffe\/test\/test_caffe_main.hpp\"\n\nnamespace caffe {\n\ntemplate \nclass ConvolutionLayerTest : public MultiDeviceTest {\n typedef typename TypeParam::Dtype Dtype;\n\n protected:\n ConvolutionLayerTest()\n : blob_bottom_(new Blob(2, 3, 6, 4)),\n blob_bottom_2_(new Blob(2, 3, 6, 4)),\n blob_top_(new Blob()),\n blob_top_2_(new Blob()) {}\n virtual void SetUp() {\n \/\/ fill the values\n FillerParameter filler_param;\n filler_param.set_value(1.);\n GaussianFiller filler(filler_param);\n filler.Fill(this->blob_bottom_);\n filler.Fill(this->blob_bottom_2_);\n blob_bottom_vec_.push_back(blob_bottom_);\n blob_top_vec_.push_back(blob_top_);\n }\n\n virtual ~ConvolutionLayerTest() {\n delete blob_bottom_;\n delete blob_bottom_2_;\n delete blob_top_;\n delete blob_top_2_;\n }\n\n Blob* const blob_bottom_;\n Blob* const blob_bottom_2_;\n Blob* const blob_top_;\n Blob* const blob_top_2_;\n vector*> blob_bottom_vec_;\n vector*> blob_top_vec_;\n};\n\nTYPED_TEST_CASE(ConvolutionLayerTest, TestDtypesAndDevices);\n\nTYPED_TEST(ConvolutionLayerTest, TestSetup) {\n typedef typename TypeParam::Dtype Dtype;\n LayerParameter layer_param;\n ConvolutionParameter* convolution_param =\n layer_param.mutable_convolution_param();\n convolution_param->set_kernel_size(3);\n convolution_param->set_stride(2);\n convolution_param->set_num_output(4);\n this->blob_bottom_vec_.push_back(this->blob_bottom_2_);\n this->blob_top_vec_.push_back(this->blob_top_2_);\n shared_ptr > layer(\n new ConvolutionLayer(layer_param));\n layer->SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n EXPECT_EQ(this->blob_top_->num(), 2);\n EXPECT_EQ(this->blob_top_->channels(), 4);\n EXPECT_EQ(this->blob_top_->height(), 2);\n EXPECT_EQ(this->blob_top_->width(), 1);\n EXPECT_EQ(this->blob_top_2_->num(), 2);\n EXPECT_EQ(this->blob_top_2_->channels(), 4);\n EXPECT_EQ(this->blob_top_2_->height(), 2);\n EXPECT_EQ(this->blob_top_2_->width(), 1);\n \/\/ setting group should not change the shape\n convolution_param->set_num_output(3);\n convolution_param->set_group(3);\n layer.reset(new ConvolutionLayer(layer_param));\n layer->SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n EXPECT_EQ(this->blob_top_->num(), 2);\n EXPECT_EQ(this->blob_top_->channels(), 3);\n EXPECT_EQ(this->blob_top_->height(), 2);\n EXPECT_EQ(this->blob_top_->width(), 1);\n EXPECT_EQ(this->blob_top_2_->num(), 2);\n EXPECT_EQ(this->blob_top_2_->channels(), 3);\n EXPECT_EQ(this->blob_top_2_->height(), 2);\n EXPECT_EQ(this->blob_top_2_->width(), 1);\n}\n\nTYPED_TEST(ConvolutionLayerTest, TestSimpleConvolution) {\n \/\/ We will simply see if the convolution layer carries out averaging well.\n typedef typename TypeParam::Dtype Dtype;\n shared_ptr > filler;\n FillerParameter filler_param;\n filler_param.set_value(1.);\n filler.reset(new ConstantFiller(filler_param));\n filler->Fill(this->blob_bottom_);\n filler_param.set_value(2.);\n filler.reset(new ConstantFiller(filler_param));\n filler->Fill(this->blob_bottom_2_);\n this->blob_bottom_vec_.push_back(this->blob_bottom_2_);\n this->blob_top_vec_.push_back(this->blob_top_2_);\n LayerParameter layer_param;\n ConvolutionParameter* convolution_param =\n layer_param.mutable_convolution_param();\n convolution_param->set_kernel_size(3);\n convolution_param->set_stride(2);\n convolution_param->set_num_output(4);\n convolution_param->mutable_weight_filler()->set_type(\"constant\");\n convolution_param->mutable_weight_filler()->set_value(1);\n convolution_param->mutable_bias_filler()->set_type(\"constant\");\n convolution_param->mutable_bias_filler()->set_value(0.1);\n shared_ptr > layer(\n new ConvolutionLayer(layer_param));\n layer->SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n layer->Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));\n \/\/ After the convolution, the output should all have output values 27.1\n const Dtype* top_data = this->blob_top_->cpu_data();\n for (int i = 0; i < this->blob_top_->count(); ++i) {\n EXPECT_NEAR(top_data[i], 27.1, 1e-4);\n }\n top_data = this->blob_top_2_->cpu_data();\n for (int i = 0; i < this->blob_top_2_->count(); ++i) {\n EXPECT_NEAR(top_data[i], 54.1, 1e-4);\n }\n}\n\nTYPED_TEST(ConvolutionLayerTest, TestSimpleConvolutionGroup) {\n \/\/ We will simply see if the convolution layer carries out averaging well.\n typedef typename TypeParam::Dtype Dtype;\n FillerParameter filler_param;\n filler_param.set_value(1.);\n ConstantFiller filler(filler_param);\n filler.Fill(this->blob_bottom_);\n Dtype* bottom_data = this->blob_bottom_->mutable_cpu_data();\n for (int n = 0; n < this->blob_bottom_->num(); ++n) {\n for (int c = 0; c < this->blob_bottom_->channels(); ++c) {\n for (int h = 0; h < this->blob_bottom_->height(); ++h) {\n for (int w = 0; w < this->blob_bottom_->width(); ++w) {\n bottom_data[this->blob_bottom_->offset(n, c, h, w)] = c;\n }\n }\n }\n }\n LayerParameter layer_param;\n ConvolutionParameter* convolution_param =\n layer_param.mutable_convolution_param();\n convolution_param->set_kernel_size(3);\n convolution_param->set_stride(2);\n convolution_param->set_num_output(3);\n convolution_param->set_group(3);\n convolution_param->mutable_weight_filler()->set_type(\"constant\");\n convolution_param->mutable_weight_filler()->set_value(1);\n convolution_param->mutable_bias_filler()->set_type(\"constant\");\n convolution_param->mutable_bias_filler()->set_value(0.1);\n shared_ptr > layer(\n new ConvolutionLayer(layer_param));\n layer->SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n layer->Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));\n \/\/ After the convolution, the output should all have output values 9.1\n const Dtype* top_data = this->blob_top_->cpu_data();\n for (int n = 0; n < this->blob_top_->num(); ++n) {\n for (int c = 0; c < this->blob_top_->channels(); ++c) {\n for (int h = 0; h < this->blob_top_->height(); ++h) {\n for (int w = 0; w < this->blob_top_->width(); ++w) {\n Dtype data = top_data[this->blob_top_->offset(n, c, h, w)];\n EXPECT_NEAR(data, c * 9 + 0.1, 1e-4);\n }\n }\n }\n }\n}\n\nTYPED_TEST(ConvolutionLayerTest, TestSobelConvolution) {\n \/\/ Test separable convolution by computing the Sobel operator\n \/\/ as a single filter then comparing the result\n \/\/ as the convolution of two rectangular filters.\n typedef typename TypeParam::Dtype Dtype;\n \/\/ Fill bottoms with identical Gaussian noise.\n shared_ptr > filler;\n FillerParameter filler_param;\n filler_param.set_value(1.);\n filler.reset(new GaussianFiller(filler_param));\n filler->Fill(this->blob_bottom_);\n this->blob_bottom_2_->CopyFrom(*this->blob_bottom_);\n \/\/ Compute Sobel G_x operator as 3 x 3 convolution.\n LayerParameter layer_param;\n ConvolutionParameter* convolution_param =\n layer_param.mutable_convolution_param();\n convolution_param->set_kernel_size(3);\n convolution_param->set_stride(2);\n convolution_param->set_num_output(1);\n convolution_param->set_bias_term(false);\n shared_ptr > layer(\n new ConvolutionLayer(layer_param));\n layer->blobs().resize(1);\n layer->blobs()[0].reset(new Blob(1, 3, 3, 3));\n Dtype* weights = layer->blobs()[0]->mutable_cpu_data();\n for (int c = 0; c < 3; ++c) {\n int i = c * 9; \/\/ 3 x 3 filter\n weights[i + 0] = -1;\n weights[i + 1] = 0;\n weights[i + 2] = 1;\n weights[i + 3] = -2;\n weights[i + 4] = 0;\n weights[i + 5] = 2;\n weights[i + 6] = -1;\n weights[i + 7] = 0;\n weights[i + 8] = 1;\n }\n layer->SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n layer->Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));\n \/\/ Compute Sobel G_x operator as separable 3 x 1 and 1 x 3 convolutions.\n \/\/ (1) the [1 2 1] column filter\n vector*> sep_blob_bottom_vec;\n vector*> sep_blob_top_vec;\n shared_ptr > blob_sep(new Blob());\n sep_blob_bottom_vec.push_back(this->blob_bottom_2_);\n sep_blob_top_vec.push_back(this->blob_top_2_);\n convolution_param->clear_kernel_size();\n convolution_param->clear_stride();\n convolution_param->set_kernel_h(3);\n convolution_param->set_kernel_w(1);\n convolution_param->set_stride_h(2);\n convolution_param->set_stride_w(1);\n convolution_param->set_num_output(1);\n convolution_param->set_bias_term(false);\n layer.reset(new ConvolutionLayer(layer_param));\n layer->blobs().resize(1);\n layer->blobs()[0].reset(new Blob(1, 3, 3, 1));\n Dtype* weights_1 = layer->blobs()[0]->mutable_cpu_data();\n for (int c = 0; c < 3; ++c) {\n int i = c * 3; \/\/ 3 x 1 filter\n weights_1[i + 0] = 1;\n weights_1[i + 1] = 2;\n weights_1[i + 2] = 1;\n }\n layer->SetUp(sep_blob_bottom_vec, &(sep_blob_top_vec));\n layer->Forward(sep_blob_bottom_vec, &(sep_blob_top_vec));\n \/\/ (2) the [-1 0 1] row filter\n blob_sep->CopyFrom(*this->blob_top_2_, false, true);\n sep_blob_bottom_vec.clear();\n sep_blob_bottom_vec.push_back(blob_sep.get());\n convolution_param->set_kernel_h(1);\n convolution_param->set_kernel_w(3);\n convolution_param->set_stride_h(1);\n convolution_param->set_stride_w(2);\n convolution_param->set_num_output(1);\n convolution_param->set_bias_term(false);\n layer.reset(new ConvolutionLayer(layer_param));\n layer->blobs().resize(1);\n layer->blobs()[0].reset(new Blob(1, 3, 1, 3));\n Dtype* weights_2 = layer->blobs()[0]->mutable_cpu_data();\n for (int c = 0; c < 3; ++c) {\n int i = c * 3; \/\/ 1 x 3 filter\n weights_2[i + 0] = -1;\n weights_2[i + 1] = 0;\n weights_2[i + 2] = 1;\n }\n layer->SetUp(sep_blob_bottom_vec, &(sep_blob_top_vec));\n layer->Forward(sep_blob_bottom_vec, &(sep_blob_top_vec));\n \/\/ Test equivalence of full and separable filters.\n const Dtype* top_data = this->blob_top_->cpu_data();\n const Dtype* sep_top_data = this->blob_top_2_->cpu_data();\n for (int i = 0; i < this->blob_top_->count(); ++i) {\n EXPECT_NEAR(top_data[i], sep_top_data[i], 1e-4);\n }\n}\n\nTYPED_TEST(ConvolutionLayerTest, TestGradient) {\n typedef typename TypeParam::Dtype Dtype;\n LayerParameter layer_param;\n ConvolutionParameter* convolution_param =\n layer_param.mutable_convolution_param();\n this->blob_bottom_vec_.push_back(this->blob_bottom_2_);\n this->blob_top_vec_.push_back(this->blob_top_2_);\n convolution_param->set_kernel_size(3);\n convolution_param->set_stride(2);\n convolution_param->set_num_output(2);\n convolution_param->mutable_weight_filler()->set_type(\"gaussian\");\n convolution_param->mutable_bias_filler()->set_type(\"gaussian\");\n ConvolutionLayer layer(layer_param);\n GradientChecker checker(1e-2, 1e-3);\n checker.CheckGradientExhaustive(&layer, &(this->blob_bottom_vec_),\n &(this->blob_top_vec_));\n}\n\nTYPED_TEST(ConvolutionLayerTest, TestGradientGroup) {\n typedef typename TypeParam::Dtype Dtype;\n LayerParameter layer_param;\n ConvolutionParameter* convolution_param =\n layer_param.mutable_convolution_param();\n convolution_param->set_kernel_size(3);\n convolution_param->set_stride(2);\n convolution_param->set_num_output(3);\n convolution_param->set_group(3);\n convolution_param->mutable_weight_filler()->set_type(\"gaussian\");\n convolution_param->mutable_bias_filler()->set_type(\"gaussian\");\n ConvolutionLayer layer(layer_param);\n GradientChecker checker(1e-2, 1e-3);\n checker.CheckGradientExhaustive(&layer, &(this->blob_bottom_vec_),\n &(this->blob_top_vec_));\n}\n\n} \/\/ namespace caffe\n<|endoftext|>"} {"text":"\/\/\n\/\/ partlistvisitor.cpp\n\/\/ libmusicxml2\n\/\/\n\/\/ Created by Arshia Cont on 05\/01\/17.\n\/\/\n\/\/\n\n#include \n\n#include \"partlistvisitor.h\"\n\n#include \"rational.h\"\n#include \"xml_tree_browser.h\"\n#include \"tree_browser.h\"\n\nusing namespace std;\n\nnamespace MusicXML2\n{\n partlistvisitor::partlistvisitor() : fPartGroupIncrementer(0), staffCreatorCounter(1)\n {\n }\n \n \n partGroup* partlistvisitor::find_first_of_partID_inGroup(std::string partID)\n {\n \/\/ search if this part ID exists in any grouping\n \/\/ Guido Limitation: One \\accol tag per staff ONLY (for nested definitions)\n \/\/ IDEA: Treat the FIRST occurence of partID in grouping and get rid of it.\n std::map::iterator partGroupIt;\n for (partGroupIt=fPartGroups.begin();\n partGroupIt != fPartGroups.end();\n partGroupIt++)\n {\n if (partGroupIt->second.visited == false) {\n if (std::find(partGroupIt->second.partIDs.begin()\n , partGroupIt->second.partIDs.end(),\n partID) != partGroupIt->second.partIDs.end() )\n {\n \/\/ this partID is in group number partGroupIt->first\n \/\/cerr << \"\\t ID found in group \" << partGroupIt->first <<\" \"<second;\n }\n \n return NULL;\n }\n \n void partlistvisitor::partID2range(partGroup &pGroup)\n {\n std::vector staves;\n for (size_t i=0; i::iterator rangeEnd = std::max_element(staves.begin(), staves.end());\n std::vector::iterator rangeBegin = std::min_element(staves.begin(), staves.begin());\n \n stringstream rangeStream;\n rangeStream << \"\\\"\"<< (*rangeBegin)<<\"-\"<<(*rangeEnd)<<\"\\\"\";\n pGroup.guidoRange = rangeStream.str();\n pGroup.guidoRangeStart = *rangeBegin;\n pGroup.guidoRangeStop = *rangeEnd;\n }\n \n bool partlistvisitor::checkLonelyBarFormat(int staffID)\n {\n std::map::iterator partGroupIt;\n for (partGroupIt=fPartGroups.begin();\n partGroupIt != fPartGroups.end();\n partGroupIt++)\n {\n if (partGroupIt->second.barlineGrouping == true)\n {\n \/\/ see if this staff is in range\n if ( (staffID>= partGroupIt->second.guidoRangeStart)&&(staffID<=partGroupIt->second.guidoRangeStop))\n {\n return false;\n }\n }\n }\n \n return true;\n }\n \n \/\/\/ Visitors\n \n void partlistvisitor::visitStart ( S_part_group& elt )\n {\n int partGroupNumber = elt->getAttributeIntValue(\"number\", 0);\n \/\/\/ IMPORTANT NOTE: the number attribute is NOT sequential and can be repeated! So we need to do further book-keeping.\n std::string partGroupType = elt->getAttributeValue(\"type\");\n \n if (partGroupType==\"start\")\n {\n int groupIndex = fPartGroupIncrementer;\n fPartGroups[groupIndex].xmlGroupNumber = partGroupNumber;\n if (elt->getValue(k_group_symbol)==\"bracket\")\n {\n fPartGroups[groupIndex].bracket = true;\n } else\n fPartGroups[groupIndex].bracket = false;\n \n if (elt->getValue(k_group_barline)==\"yes\")\n {\n fPartGroups[groupIndex].barlineGrouping = true;\n } else\n fPartGroups[groupIndex].barlineGrouping = false;\n \n \/\/ Add optional names\n fPartGroups[groupIndex].fGroupName = elt->getValue(k_group_name);\n fPartGroups[groupIndex].visited = false;\n \n fCurrentPartGroupIndex.push_back(groupIndex);\n fPartGroupIncrementer++;\n \/\/cerr << \"Started group \" << partGroupNumber << \" index \" << groupIndex<<\" (\" << fCurrentPartGroupIndex.size() << \")\" << endl;\n }else\n if (partGroupType==\"stop\")\n {\n \/\/ Erase the INDEX whose xmlGroupNumber is equal to partGroupNumber\n std::vector::iterator ito;\n for (ito = fCurrentPartGroupIndex.begin(); ito < fCurrentPartGroupIndex.end(); ito++)\n {\n if (fPartGroups[*ito].xmlGroupNumber == partGroupNumber)\n break;\n }\n \n \/\/ calculate Guido Range and set\n partID2range(fPartGroups[*ito]);\n \n \/\/ Do Erase\n if (ito != fCurrentPartGroupIndex.end())\n {\n fCurrentPartGroupIndex.erase(ito);\n }else\n cerr << \"Something is really wrong in S_PART_GROUP visitor!\" << endl;\n }\n }\n \n void partlistvisitor::visitStart( S_score_part& elt)\n {\n std::string PartID = elt->getAttributeValue(\"id\");\n part2staffmap[PartID] = staffCreatorCounter;\n staffCreatorCounter++;\n \n fPartHeaders[PartID].fPartName = elt->getValue(k_part_name);\n fPartHeaders[PartID].fPartNameAbbr = elt->getValue(k_part_abbreviation);\n \n \/\/ add groupings if any\n if (fCurrentPartGroupIndex.size())\n {\n for (size_t ind=0; ind < fCurrentPartGroupIndex.size(); ind++)\n {\n fPartGroups[fCurrentPartGroupIndex[ind]].partIDs.push_back(PartID);\n }\n }\n }\n \n \n \n}\nfix crash bug in partID2range\/\/\n\/\/ partlistvisitor.cpp\n\/\/ libmusicxml2\n\/\/\n\/\/ Created by Arshia Cont on 05\/01\/17.\n\/\/\n\/\/\n\n#include \n\n#include \"partlistvisitor.h\"\n\n#include \"rational.h\"\n#include \"xml_tree_browser.h\"\n#include \"tree_browser.h\"\n\nusing namespace std;\n\nnamespace MusicXML2\n{\n partlistvisitor::partlistvisitor() : fPartGroupIncrementer(0), staffCreatorCounter(1)\n {\n }\n \n \n partGroup* partlistvisitor::find_first_of_partID_inGroup(std::string partID)\n {\n \/\/ search if this part ID exists in any grouping\n \/\/ Guido Limitation: One \\accol tag per staff ONLY (for nested definitions)\n \/\/ IDEA: Treat the FIRST occurence of partID in grouping and get rid of it.\n std::map::iterator partGroupIt;\n for (partGroupIt=fPartGroups.begin();\n partGroupIt != fPartGroups.end();\n partGroupIt++)\n {\n if (partGroupIt->second.visited == false) {\n if (std::find(partGroupIt->second.partIDs.begin()\n , partGroupIt->second.partIDs.end(),\n partID) != partGroupIt->second.partIDs.end() )\n {\n \/\/ this partID is in group number partGroupIt->first\n \/\/cerr << \"\\t ID found in group \" << partGroupIt->first <<\" \"<second;\n }\n \n return NULL;\n }\n \n void partlistvisitor::partID2range(partGroup &pGroup)\n {\n std::vector staves;\n for (size_t i=0; i::iterator rangeEnd = std::max_element(staves.begin(), staves.end());\n std::vector::iterator rangeBegin = std::min_element(staves.begin(), staves.begin());\n \n stringstream rangeStream;\n rangeStream << \"\\\"\" << (*rangeBegin) << \"-\" << (*rangeEnd) << \"\\\"\";\n pGroup.guidoRange = rangeStream.str();\n pGroup.guidoRangeStart = *rangeBegin;\n pGroup.guidoRangeStop = *rangeEnd;\n }\n \n bool partlistvisitor::checkLonelyBarFormat(int staffID)\n {\n std::map::iterator partGroupIt;\n for (partGroupIt=fPartGroups.begin();\n partGroupIt != fPartGroups.end();\n partGroupIt++)\n {\n if (partGroupIt->second.barlineGrouping == true)\n {\n \/\/ see if this staff is in range\n if ( (staffID>= partGroupIt->second.guidoRangeStart)&&(staffID<=partGroupIt->second.guidoRangeStop))\n {\n return false;\n }\n }\n }\n \n return true;\n }\n \n \/\/\/ Visitors\n \n void partlistvisitor::visitStart ( S_part_group& elt )\n {\n int partGroupNumber = elt->getAttributeIntValue(\"number\", 0);\n \/\/\/ IMPORTANT NOTE: the number attribute is NOT sequential and can be repeated! So we need to do further book-keeping.\n std::string partGroupType = elt->getAttributeValue(\"type\");\n \n if (partGroupType==\"start\")\n {\n int groupIndex = fPartGroupIncrementer;\n fPartGroups[groupIndex].xmlGroupNumber = partGroupNumber;\n if (elt->getValue(k_group_symbol)==\"bracket\")\n {\n fPartGroups[groupIndex].bracket = true;\n } else\n fPartGroups[groupIndex].bracket = false;\n \n if (elt->getValue(k_group_barline)==\"yes\")\n {\n fPartGroups[groupIndex].barlineGrouping = true;\n } else\n fPartGroups[groupIndex].barlineGrouping = false;\n \n \/\/ Add optional names\n fPartGroups[groupIndex].fGroupName = elt->getValue(k_group_name);\n fPartGroups[groupIndex].visited = false;\n \n fCurrentPartGroupIndex.push_back(groupIndex);\n fPartGroupIncrementer++;\n \/\/cerr << \"Started group \" << partGroupNumber << \" index \" << groupIndex<<\" (\" << fCurrentPartGroupIndex.size() << \")\" << endl;\n }else\n if (partGroupType==\"stop\")\n {\n \/\/ Erase the INDEX whose xmlGroupNumber is equal to partGroupNumber\n std::vector::iterator ito;\n for (ito = fCurrentPartGroupIndex.begin(); ito < fCurrentPartGroupIndex.end(); ito++)\n {\n if (fPartGroups[*ito].xmlGroupNumber == partGroupNumber)\n break;\n }\n \n \/\/ calculate Guido Range and set\n partID2range(fPartGroups[*ito]);\n \n \/\/ Do Erase\n if (ito != fCurrentPartGroupIndex.end())\n {\n fCurrentPartGroupIndex.erase(ito);\n }else\n cerr << \"Something is really wrong in S_PART_GROUP visitor!\" << endl;\n }\n }\n \n void partlistvisitor::visitStart( S_score_part& elt)\n {\n std::string PartID = elt->getAttributeValue(\"id\");\n part2staffmap[PartID] = staffCreatorCounter;\n staffCreatorCounter++;\n \n fPartHeaders[PartID].fPartName = elt->getValue(k_part_name);\n fPartHeaders[PartID].fPartNameAbbr = elt->getValue(k_part_abbreviation);\n \n \/\/ add groupings if any\n if (fCurrentPartGroupIndex.size())\n {\n for (size_t ind=0; ind < fCurrentPartGroupIndex.size(); ind++)\n {\n fPartGroups[fCurrentPartGroupIndex[ind]].partIDs.push_back(PartID);\n }\n }\n }\n \n \n \n}\n<|endoftext|>"} {"text":"\/*\n * VehicleExtraProperties.cpp\n *\n * Created on: Apr 25, 2015\n * Author: arman\n *\/\n\n#include \"VehicleExtraProperties.h\"\n\n\n\/\/ Arman : maybe too many includes\n#include \"core\/ChStream.h\"\n\n\/\/#include \"chrono_parallel\/lcp\/ChLcpSystemDescriptorParallel.h\"\n\/\/#include \"chrono_parallel\/collision\/ChCNarrowphaseRUtils.h\"\n#include \"chrono_vehicle\/ChVehicleModelData.h\"\n\n\n\n\nint chassisFam = 2;\nint tireFam = 3;\n\n\/\/#include \"hmmwvParams.h\"\n\nusing namespace chrono;\nusing namespace collision;\n\n\/\/ Tire Coefficient of friction\nfloat mu_t = 0.8;\n\n\/\/ Callback class for providing driver inputs.\nMyDriverInputs::MyDriverInputs(double delay) : m_delay(delay) {}\nvoid MyDriverInputs::onCallback(double time, double& throttle, double& steering, double& braking) {\n\tthrottle = 0;\n\tsteering = 0;\n\tbraking = 0;\n\n\tdouble eff_time = time - m_delay;\n\n\t\/\/ Do not generate any driver inputs for a duration equal to m_delay.\n\tif (eff_time < 0)\n\t\treturn;\n\n\tif (eff_time > 0.2)\n\t\tthrottle = 1.0;\n\telse if (eff_time > 0.1)\n\t\tthrottle = 10 * (eff_time - 0.1);\n}\n\n\/\/ Callback class for specifying rigid tire contact model.\n\/\/ This version uses cylindrical contact shapes.\nvoid MyCylindricalTire::onCallback(ChSharedPtr wheelBody, double radius, double width) {\n\twheelBody->ChangeCollisionModel(new collision::ChCollisionModelParallel);\n\n\twheelBody->GetCollisionModel()->ClearModel();\n\twheelBody->GetCollisionModel()->AddCylinder(0.46, 0.46, width \/ 2);\n\twheelBody->GetCollisionModel()->BuildModel();\n\n\twheelBody->GetMaterialSurface()->SetFriction(mu_t);\n}\n\n\/\/ Callback class for specifying rigid tire contact model.\n\/\/ This version uses a collection of convex contact shapes (meshes).\nMyLuggedTire::MyLuggedTire() {\n\tstd::string lugged_file(\"hmmwv\/lugged_wheel_section.obj\");\n\tgeometry::ChTriangleMeshConnected lugged_mesh;\n\tutils::LoadConvexMesh(vehicle::GetDataFile(lugged_file), lugged_mesh, lugged_convex);\n\tnum_hulls = lugged_convex.GetHullCount();\n}\nvoid MyLuggedTire::onCallback(ChSharedPtr wheelBody, double radius, double width) {\n\twheelBody->ChangeCollisionModel(new collision::ChCollisionModelParallel);\n\n\tChCollisionModelParallel* coll_model = (ChCollisionModelParallel*)wheelBody->GetCollisionModel();\n\tcoll_model->ClearModel();\n\n\t\/\/ Assemble the tire contact from 15 segments, properly offset.\n\t\/\/ Each segment is further decomposed in convex hulls.\n\tfor (int iseg = 0; iseg < 15; iseg++) {\n\t\tChQuaternion<> rot = Q_from_AngAxis(iseg * 24 * CH_C_DEG_TO_RAD, VECT_Y);\n\t\tfor (int ihull = 0; ihull < num_hulls; ihull++) {\n\t\t\tstd::vector > convexhull;\n\t\t\tlugged_convex.GetConvexHullResult(ihull, convexhull);\n\t\t\tcoll_model->AddConvexHull(convexhull, VNULL, rot);\n\t\t}\n\t}\n\n\t\/\/ Add a cylinder to represent the wheel hub.\n\tcoll_model->AddCylinder(0.223, 0.223, 0.126);\n\n\tcoll_model->BuildModel();\n\n\twheelBody->GetMaterialSurface()->SetFriction(mu_t);\n}\n\n\n\/\/ Callback class for specifying chassis contact model.\n\/\/ This version uses a box representing the chassis.\n\/\/ In addition, this version overrides the visualization assets of the provided\n\/\/ chassis body with the collision meshes.\nvoid MyChassisBoxModel_vis::onCallback(ChSharedPtr chassisBody) {\n \/\/ Clear any existing assets (will be overriden)\n\n chassisBody->GetCollisionModel()->ClearModel();\n ChVector<> chLoc = ChVector<>(0, 0, 0);\n \/\/ ChVector<> chLoc = chassisBody->GetFrame_REF_to_COG().GetPos();\n chassisBody->GetCollisionModel()->AddBox(size.x, size.y, size.z, chLoc, rot);\n \/\/ utils::AddBoxGeometry(\n \/\/ chassisBody.get_ptr(), ChVector<>(1, .5, .05), ChVector<>(0, 0, 0), ChQuaternion<>(1, 0, 0, 0), true);\n chassisBody->GetCollisionModel()->SetFamily(chassisFam);\n chassisBody->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(tireFam);\n chassisBody->GetCollisionModel()->BuildModel();\n chassisBody->GetMaterialSurface()->SetFriction(mu_t);\n\n chassisBody->GetAssets().clear();\n ChSharedPtr box(new ChBoxShape);\n box->GetBoxGeometry().Size = size;\n box->Rot = rot;\n chassisBody->GetAssets().push_back(box);\n}\n\nvoid MyChassisBoxModel_vis::SetAttributes(const ChVector<>& otherSize,\n const ChQuaternion<>& otherRot,\n const ChVector<>& otherLoc) {\n size = otherSize;\n rot = otherRot;\n loc = otherLoc;\n}\n\n\/\/ Callback class for specifying chassis contact model.\n\/\/ This version uses a sphere representing the chassis.\n\/\/ In addition, this version overrides the visualization assets of the provided\n\/\/ chassis body with the collision meshes.\nvoid MyChassisSphereModel_vis::onCallback(ChSharedPtr chassisBody) {\n \/\/ Clear any existing assets (will be overriden)\n\n chassisBody->GetCollisionModel()->ClearModel();\n ChVector<> chLoc = ChVector<>(0, 0, 0);\n\/\/ ChVector<> chLoc = chassisBody->GetFrame_REF_to_COG().GetPos();\n chassisBody->GetCollisionModel()->AddSphere(rad, chLoc);\n \/\/ utils::AddBoxGeometry(\n \/\/ chassisBody.get_ptr(), ChVector<>(1, .5, .05), ChVector<>(0, 0, 0), ChQuaternion<>(1, 0, 0, 0), true);\n chassisBody->GetCollisionModel()->SetFamily(chassisFam);\n chassisBody->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(tireFam);\n chassisBody->GetCollisionModel()->BuildModel();\n chassisBody->GetMaterialSurface()->SetFriction(mu_t);\n\n chassisBody->GetAssets().clear();\n ChSharedPtr sphere(new ChSphereShape);\n sphere->GetSphereGeometry().rad = rad;\n chassisBody->GetAssets().push_back(sphere);\n}\n\nvoid MyChassisSphereModel_vis::SetAttributes(double otherRad,\n const ChQuaternion<>& otherRot,\n const ChVector<>& otherLoc) {\n rad = otherRad;\n rot = otherRot;\n loc = otherLoc;\n}\n\n\/\/ Callback class for specifying chassis contact model.\n\/\/ This version uses a convex decomposition of an obj representing the chassis.\nMyChassisSimpleConvexMesh::MyChassisSimpleConvexMesh() :\n\tpos(chrono::ChVector<>(0, 0, 0)) , rot( chrono::ChQuaternion<>(1, 0, 0, 0)) {\n \/\/ std::string chassis_obj_file(\"hmmwv\/lugged_wheel_section.obj\");\n \/\/ std::string chassis_obj_file(\"hmmwv\/lugged_wheel.obj\");\n \/\/ std::string chassis_obj_file(\"hmmwv\/myHumvee.obj\");\n\/\/ chassis_obj_file = std::string(\"hmmwv\/myHumvee1.obj\");\n\tchassis_obj_file = std::string(\"hmmwv\/hmmwv_chassis_simple.obj\");\n\n utils::LoadConvexMesh(vehicle::GetDataFile(chassis_obj_file), chassis_mesh, chassis_convex);\n}\n\nvoid MyChassisSimpleConvexMesh::onCallback(ChSharedPtr chassisBody) {\n ChVector<> chLoc = ChVector<>(0, 0, 0); \/\/ chassisBody->GetFrame_REF_to_COG().GetPos();\n chassisBody->GetCollisionModel()->ClearModel();\n \/\/ utils::AddConvexCollisionModel(chassisBody, chassis_mesh, chassis_convex, chLoc, ChQuaternion<>(1, 0, 0, 0),\n \/\/ false);\n\n \/\/ **************************\n ChSharedPtr body = chassisBody;\n geometry::ChTriangleMeshConnected& convex_mesh = chassis_mesh;\n ChConvexDecompositionHACDv2& convex_shape = chassis_convex;\n ChConvexDecomposition* used_decomposition = &convex_shape;\n\n \/\/*****\n int hull_count = used_decomposition->GetHullCount();\n\n for (int c = 0; c < hull_count; c++) {\n std::vector > convexhull;\n used_decomposition->GetConvexHullResult(c, convexhull);\n\n ((collision::ChCollisionModelParallel*)body->GetCollisionModel())->AddConvexHull(convexhull, chLoc, rot);\n }\n chassisBody->GetCollisionModel()->SetFamily(chassisFam);\n\/\/ printf(\"chassis family %d \\n\", chassisBody->GetCollisionModel()->GetFamily());\n chassisBody->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(tireFam);\n chassisBody->GetCollisionModel()->BuildModel();\n\n \/\/ **************************\n\n \/\/ chassisBody->RecomputeCollisionModel();\n \/\/ chassisBody->SetCollide(false);\n\n chassisBody->GetMaterialSurface()->SetFriction(mu_t);\n}\n\n\/\/ Callback class for specifying chassis contact model.\n\/\/ This version uses a triangular given in an obj representing the chassis.\n\/\/ In addition, this version overrides the visualization assets of the provided\n\/\/ chassis body with the collision meshes.\nMyChassisSimpleTriMesh_vis::MyChassisSimpleTriMesh_vis() :\n\tpos(chrono::ChVector<>(0, 0, 0)) , rot( chrono::ChQuaternion<>(1, 0, 0, 0)) {\n\/\/\tchassis_obj_file = std::string(\"hmmwv\/myHumvee1.obj\");\n\tchassis_obj_file = std::string(\"hmmwv\/hmmwv_chassis_simple.obj\");\n}\n\nvoid MyChassisSimpleTriMesh_vis::onCallback(ChSharedPtr chassisBody) {\n \/\/ Clear any existing assets (will be overriden)\n const std::string mesh_name(\"chassis\");\n\n chassisBody->GetAssets().clear();\n \/\/ ChVector<> chLoc = ChVector<>(0,0,0);\/\/chassisBody->GetFrame_REF_to_COG().GetPos();\n\n chassisBody->GetCollisionModel()->ClearModel();\n \/\/ utils::AddTriangleMeshGeometry(chassisBody.get_ptr(), vehicle::GetDataFile(chassis_obj_file), mesh_name, pos,\n \/\/ rot, true);\n\n ChVector<> chLoc = ChVector<>(0, 0, 0); \/\/ chassisBody->GetFrame_REF_to_COG().GetPos();\n\/\/ ChVector<> chLoc = chassisBody->GetFrame_REF_to_COG().GetPos();\n\n \/\/ *** here\n std::string obj_filename = vehicle::GetDataFile(chassis_obj_file);\n const std::string& name = mesh_name;\n ChBody* body = chassisBody.get_ptr();\n geometry::ChTriangleMeshConnected trimesh;\n trimesh.LoadWavefrontMesh(obj_filename, false, false);\n\n for (int i = 0; i < trimesh.m_vertices.size(); i++)\n trimesh.m_vertices[i] = pos + rot.Rotate(trimesh.m_vertices[i]);\n\n body->GetCollisionModel()->AddTriangleMesh(trimesh, false, false, chLoc);\n\n if (true) {\n ChSharedPtr trimesh_shape(new ChTriangleMeshShape);\n trimesh_shape->SetMesh(trimesh);\n trimesh_shape->SetName(name);\n trimesh_shape->Pos = ChVector<>(0, 0, 0);\n trimesh_shape->Rot = ChQuaternion<>(1, 0, 0, 0);\n body->GetAssets().push_back(trimesh_shape);\n }\n \/\/ *** to here\n chassisBody->GetCollisionModel()->SetFamily(chassisFam);\n chassisBody->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(tireFam);\n chassisBody->GetCollisionModel()->BuildModel();\n\n chassisBody->GetMaterialSurface()->SetFriction(mu_t);\n}\n\n\n\ncollision model need to be set for contact geometries\/*\n * VehicleExtraProperties.cpp\n *\n * Created on: Apr 25, 2015\n * Author: arman\n *\/\n\n#include \"VehicleExtraProperties.h\"\n\n\n\/\/ Arman : maybe too many includes\n#include \"core\/ChStream.h\"\n\n\/\/#include \"chrono_parallel\/lcp\/ChLcpSystemDescriptorParallel.h\"\n\/\/#include \"chrono_parallel\/collision\/ChCNarrowphaseRUtils.h\"\n#include \"chrono_vehicle\/ChVehicleModelData.h\"\n\n\n\n\nint chassisFam = 2;\nint tireFam = 3;\n\n\/\/#include \"hmmwvParams.h\"\n\nusing namespace chrono;\nusing namespace collision;\n\n\/\/ Tire Coefficient of friction\nfloat mu_t = 0.8;\n\n\/\/ Callback class for providing driver inputs.\nMyDriverInputs::MyDriverInputs(double delay) : m_delay(delay) {}\nvoid MyDriverInputs::onCallback(double time, double& throttle, double& steering, double& braking) {\n\tthrottle = 0;\n\tsteering = 0;\n\tbraking = 0;\n\n\tdouble eff_time = time - m_delay;\n\n\t\/\/ Do not generate any driver inputs for a duration equal to m_delay.\n\tif (eff_time < 0)\n\t\treturn;\n\n\tif (eff_time > 0.2)\n\t\tthrottle = 1.0;\n\telse if (eff_time > 0.1)\n\t\tthrottle = 10 * (eff_time - 0.1);\n}\n\n\/\/ Callback class for specifying rigid tire contact model.\n\/\/ This version uses cylindrical contact shapes.\nvoid MyCylindricalTire::onCallback(ChSharedPtr wheelBody, double radius, double width) {\n\twheelBody->ChangeCollisionModel(new collision::ChCollisionModelParallel);\n\n\twheelBody->GetCollisionModel()->ClearModel();\n\twheelBody->GetCollisionModel()->AddCylinder(0.46, 0.46, width \/ 2);\n\twheelBody->GetCollisionModel()->BuildModel();\n\n\twheelBody->GetMaterialSurface()->SetFriction(mu_t);\n}\n\n\/\/ Callback class for specifying rigid tire contact model.\n\/\/ This version uses a collection of convex contact shapes (meshes).\nMyLuggedTire::MyLuggedTire() {\n\tstd::string lugged_file(\"hmmwv\/lugged_wheel_section.obj\");\n\tgeometry::ChTriangleMeshConnected lugged_mesh;\n\tutils::LoadConvexMesh(vehicle::GetDataFile(lugged_file), lugged_mesh, lugged_convex);\n\tnum_hulls = lugged_convex.GetHullCount();\n}\nvoid MyLuggedTire::onCallback(ChSharedPtr wheelBody, double radius, double width) {\n\twheelBody->ChangeCollisionModel(new collision::ChCollisionModelParallel);\n\n\tChCollisionModelParallel* coll_model = (ChCollisionModelParallel*)wheelBody->GetCollisionModel();\n\tcoll_model->ClearModel();\n\n\t\/\/ Assemble the tire contact from 15 segments, properly offset.\n\t\/\/ Each segment is further decomposed in convex hulls.\n\tfor (int iseg = 0; iseg < 15; iseg++) {\n\t\tChQuaternion<> rot = Q_from_AngAxis(iseg * 24 * CH_C_DEG_TO_RAD, VECT_Y);\n\t\tfor (int ihull = 0; ihull < num_hulls; ihull++) {\n\t\t\tstd::vector > convexhull;\n\t\t\tlugged_convex.GetConvexHullResult(ihull, convexhull);\n\t\t\tcoll_model->AddConvexHull(convexhull, VNULL, rot);\n\t\t}\n\t}\n\n\t\/\/ Add a cylinder to represent the wheel hub.\n\tcoll_model->AddCylinder(0.223, 0.223, 0.126);\n\n\tcoll_model->BuildModel();\n\n\twheelBody->GetMaterialSurface()->SetFriction(mu_t);\n}\n\n\n\/\/ Callback class for specifying chassis contact model.\n\/\/ This version uses a box representing the chassis.\n\/\/ In addition, this version overrides the visualization assets of the provided\n\/\/ chassis body with the collision meshes.\nvoid MyChassisBoxModel_vis::onCallback(ChSharedPtr chassisBody) {\n \/\/ Clear any existing assets (will be overriden)\n\n chassisBody->ChangeCollisionModel(new collision::ChCollisionModelParallel);\n\n chassisBody->GetCollisionModel()->ClearModel();\n ChVector<> chLoc = ChVector<>(0, 0, 0);\n \/\/ ChVector<> chLoc = chassisBody->GetFrame_REF_to_COG().GetPos();\n chassisBody->GetCollisionModel()->AddBox(size.x, size.y, size.z, chLoc, rot);\n \/\/ utils::AddBoxGeometry(\n \/\/ chassisBody.get_ptr(), ChVector<>(1, .5, .05), ChVector<>(0, 0, 0), ChQuaternion<>(1, 0, 0, 0), true);\n chassisBody->GetCollisionModel()->SetFamily(chassisFam);\n chassisBody->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(tireFam);\n chassisBody->GetCollisionModel()->BuildModel();\n chassisBody->GetMaterialSurface()->SetFriction(mu_t);\n\n chassisBody->GetAssets().clear();\n ChSharedPtr box(new ChBoxShape);\n box->GetBoxGeometry().Size = size;\n box->Rot = rot;\n chassisBody->GetAssets().push_back(box);\n}\n\nvoid MyChassisBoxModel_vis::SetAttributes(const ChVector<>& otherSize,\n const ChQuaternion<>& otherRot,\n const ChVector<>& otherLoc) {\n size = otherSize;\n rot = otherRot;\n loc = otherLoc;\n}\n\n\/\/ Callback class for specifying chassis contact model.\n\/\/ This version uses a sphere representing the chassis.\n\/\/ In addition, this version overrides the visualization assets of the provided\n\/\/ chassis body with the collision meshes.\nvoid MyChassisSphereModel_vis::onCallback(ChSharedPtr chassisBody) {\n \/\/ Clear any existing assets (will be overriden)\n\n\tchassisBody->ChangeCollisionModel(new collision::ChCollisionModelParallel);\n\n chassisBody->GetCollisionModel()->ClearModel();\n ChVector<> chLoc = ChVector<>(0, 0, 0);\n\/\/ ChVector<> chLoc = chassisBody->GetFrame_REF_to_COG().GetPos();\n chassisBody->GetCollisionModel()->AddSphere(rad, chLoc);\n \/\/ utils::AddBoxGeometry(\n \/\/ chassisBody.get_ptr(), ChVector<>(1, .5, .05), ChVector<>(0, 0, 0), ChQuaternion<>(1, 0, 0, 0), true);\n chassisBody->GetCollisionModel()->SetFamily(chassisFam);\n chassisBody->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(tireFam);\n chassisBody->GetCollisionModel()->BuildModel();\n chassisBody->GetMaterialSurface()->SetFriction(mu_t);\n\n chassisBody->GetAssets().clear();\n ChSharedPtr sphere(new ChSphereShape);\n sphere->GetSphereGeometry().rad = rad;\n chassisBody->GetAssets().push_back(sphere);\n}\n\nvoid MyChassisSphereModel_vis::SetAttributes(double otherRad,\n const ChQuaternion<>& otherRot,\n const ChVector<>& otherLoc) {\n rad = otherRad;\n rot = otherRot;\n loc = otherLoc;\n}\n\n\/\/ Callback class for specifying chassis contact model.\n\/\/ This version uses a convex decomposition of an obj representing the chassis.\nMyChassisSimpleConvexMesh::MyChassisSimpleConvexMesh() :\n\tpos(chrono::ChVector<>(0, 0, 0)) , rot( chrono::ChQuaternion<>(1, 0, 0, 0)) {\n \/\/ std::string chassis_obj_file(\"hmmwv\/lugged_wheel_section.obj\");\n \/\/ std::string chassis_obj_file(\"hmmwv\/lugged_wheel.obj\");\n \/\/ std::string chassis_obj_file(\"hmmwv\/myHumvee.obj\");\n\/\/ chassis_obj_file = std::string(\"hmmwv\/myHumvee1.obj\");\n\tchassis_obj_file = std::string(\"hmmwv\/hmmwv_chassis_simple.obj\");\n\n utils::LoadConvexMesh(vehicle::GetDataFile(chassis_obj_file), chassis_mesh, chassis_convex);\n}\n\nvoid MyChassisSimpleConvexMesh::onCallback(ChSharedPtr chassisBody) {\n\tchassisBody->ChangeCollisionModel(new collision::ChCollisionModelParallel);\n\n ChVector<> chLoc = ChVector<>(0, 0, 0); \/\/ chassisBody->GetFrame_REF_to_COG().GetPos();\n chassisBody->GetCollisionModel()->ClearModel();\n \/\/ utils::AddConvexCollisionModel(chassisBody, chassis_mesh, chassis_convex, chLoc, ChQuaternion<>(1, 0, 0, 0),\n \/\/ false);\n\n \/\/ **************************\n ChSharedPtr body = chassisBody;\n geometry::ChTriangleMeshConnected& convex_mesh = chassis_mesh;\n ChConvexDecompositionHACDv2& convex_shape = chassis_convex;\n ChConvexDecomposition* used_decomposition = &convex_shape;\n\n \/\/*****\n int hull_count = used_decomposition->GetHullCount();\n\n for (int c = 0; c < hull_count; c++) {\n std::vector > convexhull;\n used_decomposition->GetConvexHullResult(c, convexhull);\n\n ((collision::ChCollisionModelParallel*)body->GetCollisionModel())->AddConvexHull(convexhull, chLoc, rot);\n }\n chassisBody->GetCollisionModel()->SetFamily(chassisFam);\n\/\/ printf(\"chassis family %d \\n\", chassisBody->GetCollisionModel()->GetFamily());\n chassisBody->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(tireFam);\n chassisBody->GetCollisionModel()->BuildModel();\n\n \/\/ **************************\n\n \/\/ chassisBody->RecomputeCollisionModel();\n \/\/ chassisBody->SetCollide(false);\n\n chassisBody->GetMaterialSurface()->SetFriction(mu_t);\n}\n\n\/\/ Callback class for specifying chassis contact model.\n\/\/ This version uses a triangular given in an obj representing the chassis.\n\/\/ In addition, this version overrides the visualization assets of the provided\n\/\/ chassis body with the collision meshes.\nMyChassisSimpleTriMesh_vis::MyChassisSimpleTriMesh_vis() :\n\tpos(chrono::ChVector<>(0, 0, 0)) , rot( chrono::ChQuaternion<>(1, 0, 0, 0)) {\n\/\/\tchassis_obj_file = std::string(\"hmmwv\/myHumvee1.obj\");\n\tchassis_obj_file = std::string(\"hmmwv\/hmmwv_chassis_simple.obj\");\n}\n\nvoid MyChassisSimpleTriMesh_vis::onCallback(ChSharedPtr chassisBody) {\n\tchassisBody->ChangeCollisionModel(new collision::ChCollisionModelParallel);\n\n \/\/ Clear any existing assets (will be overriden)\n const std::string mesh_name(\"chassis\");\n\n chassisBody->GetAssets().clear();\n \/\/ ChVector<> chLoc = ChVector<>(0,0,0);\/\/chassisBody->GetFrame_REF_to_COG().GetPos();\n\n chassisBody->GetCollisionModel()->ClearModel();\n \/\/ utils::AddTriangleMeshGeometry(chassisBody.get_ptr(), vehicle::GetDataFile(chassis_obj_file), mesh_name, pos,\n \/\/ rot, true);\n\n ChVector<> chLoc = ChVector<>(0, 0, 0); \/\/ chassisBody->GetFrame_REF_to_COG().GetPos();\n\/\/ ChVector<> chLoc = chassisBody->GetFrame_REF_to_COG().GetPos();\n\n \/\/ *** here\n std::string obj_filename = vehicle::GetDataFile(chassis_obj_file);\n const std::string& name = mesh_name;\n ChBody* body = chassisBody.get_ptr();\n geometry::ChTriangleMeshConnected trimesh;\n trimesh.LoadWavefrontMesh(obj_filename, false, false);\n\n for (int i = 0; i < trimesh.m_vertices.size(); i++)\n trimesh.m_vertices[i] = pos + rot.Rotate(trimesh.m_vertices[i]);\n\n body->GetCollisionModel()->AddTriangleMesh(trimesh, false, false, chLoc);\n\n if (true) {\n ChSharedPtr trimesh_shape(new ChTriangleMeshShape);\n trimesh_shape->SetMesh(trimesh);\n trimesh_shape->SetName(name);\n trimesh_shape->Pos = ChVector<>(0, 0, 0);\n trimesh_shape->Rot = ChQuaternion<>(1, 0, 0, 0);\n body->GetAssets().push_back(trimesh_shape);\n }\n \/\/ *** to here\n chassisBody->GetCollisionModel()->SetFamily(chassisFam);\n chassisBody->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(tireFam);\n chassisBody->GetCollisionModel()->BuildModel();\n\n chassisBody->GetMaterialSurface()->SetFriction(mu_t);\n}\n\n\n\n<|endoftext|>"} {"text":"\/* -------------------------------------------------------------------------- *\/\n\/* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\/\n\/* not use this file except in compliance with the License. You may obtain *\/\n\/* a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\/\n\/* See the License for the specific language governing permissions and *\/\n\/* limitations under the License. *\/\n\/* -------------------------------------------------------------------------- *\/\n\n#include \"VirtualMachineTemplate.h\"\n\nusing namespace std;\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nstd::map > VirtualMachineTemplate::restricted;\nstd::map > VirtualMachineTemplate::encrypted;\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint VirtualMachineTemplate::replace_disk_image(int target_id, const string&\n target_name, const string& target_uname, const string& new_name,\n const string& new_uname)\n{\n int num_disks;\n int tmp_id;\n\n string tmp_name;\n string tmp_uname;\n\n vector disks;\n VectorAttribute * disk = 0;\n\n num_disks = get(\"DISK\", disks);\n\n for(int i=0; ivector_value(\"IMAGE_ID\", tmp_id) == 0) \/\/DISK has IMAGE_ID\n {\n if (tmp_id == target_id)\n {\n break;\n }\n }\n else \/\/IMAGE and IMAGE_UNAME\n {\n tmp_name = disk->vector_value(\"IMAGE\");\n tmp_uname = disk->vector_value(\"IMAGE_UNAME\");\n\n bool uname = tmp_uname.empty() || tmp_uname == target_uname;\n\n if ( tmp_name == target_name && uname )\n {\n break;\n }\n }\n\n disk = 0;\n }\n\n if ( disk == 0 )\n {\n return -1;\n }\n\n disk->remove(\"IMAGE_ID\");\n\n disk->replace(\"IMAGE\", new_name);\n\n disk->replace(\"IMAGE_UNAME\", new_uname);\n\n return 0;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nstring& VirtualMachineTemplate::to_xml_short(string& xml) const\n{\n ostringstream oss;\n string labels;\n\n string schd_rank, schd_ds_rank;\n string schd_req, schd_ds_req;\n\n string user_prio;\n\n vector attrs;\n\n if (attributes.empty())\n {\n oss << \"\";\n }\n else\n {\n oss << \"\";\n\n \/* ------------------------------------------------------------------ *\/\n \/* Attributes required by Sunstone *\/\n \/* - LABELS *\/\n \/* ------------------------------------------------------------------ *\/\n if (get(\"LABELS\", labels))\n {\n oss << \"\" << one_util::escape_xml(labels) << \"<\/LABELS>\";\n }\n\n \/* ------------------------------------------------------------------ *\/\n \/* Attributes required by Scheduler *\/\n \/* - SCHED_RANK (RANK - deprecated) *\/\n \/* - SCHED_DS_RANK *\/\n \/* - SCHED_REQUIREMENTS *\/\n \/* - SCHED_DS_REQUIREMENTS *\/\n \/* *\/\n \/* - SCHED_ACTION *\/\n \/* - PUBLIC_CLOUD *\/\n \/* ------------------------------------------------------------------ *\/\n if (get(\"SCHED_RANK\", schd_rank))\n {\n oss << \"\" << one_util::escape_xml(schd_rank)\n << \"<\/SCHED_RANK>\";\n }\n\n if (get(\"SCHED_DS_RANK\", schd_ds_rank))\n {\n oss << \"\" << one_util::escape_xml(schd_ds_rank)\n << \"<\/SCHED_DS_RANK>\";\n }\n\n if (get(\"SCHED_REQUIREMENTS\", schd_req))\n {\n oss << \"\" << one_util::escape_xml(schd_req)\n << \"<\/SCHED_REQUIREMENTS>\";\n }\n\n if (get(\"SCHED_DS_REQUIREMENTS\", schd_ds_req))\n {\n oss << \"\" << one_util::escape_xml(schd_ds_req)\n << \"<\/SCHED_DS_REQUIREMENTS>\";\n }\n\n if (get(\"USER_PRIORITY\", user_prio))\n {\n oss << \"\" << one_util::escape_xml(user_prio)\n << \"<\/USER_PRIORITY>\";\n }\n\n if ( get(\"PUBLIC_CLOUD\", attrs) > 0 )\n {\n for (auto vattr : attrs)\n {\n vattr->to_xml(oss);\n }\n }\n\n attrs.clear();\n\n if ( get(\"SCHED_ACTION\", attrs) > 0 )\n {\n for (auto vattr : attrs)\n {\n vattr->to_xml(oss);\n }\n }\n\n oss << \"<\/USER_TEMPLATE>\";\n }\n\n xml = oss.str();\n\n return xml;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\n\nstd::map> VirtualMachineTemplate::UPDATECONF_ATTRS = {\n { \"OS\",\n { \"ARCH\",\n \"MACHINE\",\n \"KERNEL\",\n \"INITRD\",\n \"BOOTLOADER\",\n \"BOOT\",\n \"KERNEL_CMD\",\n \"ROOT\",\n \"SD_DISK_BUS\",\n \"UUID\"}\n },\n { \"FEATURES\",\n { \"PAE\",\n \"ACPI\",\n \"APIC\",\n \"LOCALTIME\",\n \"HYPERV\",\n \"GUEST_AGENT\",\n \"VIRTIO_SCSI_QUEUES\",\n \"IOTHREADS\"}\n },\n { \"INPUT\",\n { \"TYPE\",\n \"BUS\"}\n },\n {\"GRAPHICS\",\n { \"TYPE\",\n \"LISTEN\",\n \"PASSWD\",\n \"KEYMAP\",\n \"COMMAND\"}\n },\n {\"RAW\",\n { \"TYPE\",\n \"DATA\",\n \"DATA_VMX\"}\n },\n {\"CPU_MODEL\",\n { \"MODEL\" }\n }\n};\n\n\/\/ -----------------------------------------------------------------------------\n\/**\n * returns a copy the values of a vector value\n *\/\nstatic void copy_vector_values(const Template *old_tmpl, Template *new_tmpl,\n const char * name)\n{\n string value;\n\n const VectorAttribute * old_attr = old_tmpl->get(name);\n\n if ( old_attr == 0 )\n {\n return;\n }\n\n VectorAttribute * new_vattr = new VectorAttribute(name);\n\n std::vector vnames = VirtualMachineTemplate::UPDATECONF_ATTRS[name];\n\n for (const auto& vname : vnames)\n {\n std::string vval = old_attr->vector_value(vname);\n\n if (!vval.empty())\n {\n new_vattr->replace(vname, vval);\n }\n }\n\n if ( new_vattr->empty() )\n {\n delete new_vattr;\n }\n else\n {\n new_tmpl->set(new_vattr);\n }\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nunique_ptr VirtualMachineTemplate::get_updateconf_template() const\n{\n auto conf_tmpl = make_unique();\n\n copy_vector_values(this, conf_tmpl.get(), \"OS\");\n\n copy_vector_values(this, conf_tmpl.get(), \"FEATURES\");\n\n copy_vector_values(this, conf_tmpl.get(), \"INPUT\");\n\n copy_vector_values(this, conf_tmpl.get(), \"GRAPHICS\");\n\n copy_vector_values(this, conf_tmpl.get(), \"RAW\");\n\n const VectorAttribute * context = get(\"CONTEXT\");\n\n if ( context != 0 )\n {\n conf_tmpl->set(context->clone());\n }\n\n return conf_tmpl;\n}\n\nB #5096: fix minor bug with CPU_MODEL (#979)\/* -------------------------------------------------------------------------- *\/\n\/* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\/\n\/* not use this file except in compliance with the License. You may obtain *\/\n\/* a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\/\n\/* See the License for the specific language governing permissions and *\/\n\/* limitations under the License. *\/\n\/* -------------------------------------------------------------------------- *\/\n\n#include \"VirtualMachineTemplate.h\"\n\nusing namespace std;\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nstd::map > VirtualMachineTemplate::restricted;\nstd::map > VirtualMachineTemplate::encrypted;\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint VirtualMachineTemplate::replace_disk_image(int target_id, const string&\n target_name, const string& target_uname, const string& new_name,\n const string& new_uname)\n{\n int num_disks;\n int tmp_id;\n\n string tmp_name;\n string tmp_uname;\n\n vector disks;\n VectorAttribute * disk = 0;\n\n num_disks = get(\"DISK\", disks);\n\n for(int i=0; ivector_value(\"IMAGE_ID\", tmp_id) == 0) \/\/DISK has IMAGE_ID\n {\n if (tmp_id == target_id)\n {\n break;\n }\n }\n else \/\/IMAGE and IMAGE_UNAME\n {\n tmp_name = disk->vector_value(\"IMAGE\");\n tmp_uname = disk->vector_value(\"IMAGE_UNAME\");\n\n bool uname = tmp_uname.empty() || tmp_uname == target_uname;\n\n if ( tmp_name == target_name && uname )\n {\n break;\n }\n }\n\n disk = 0;\n }\n\n if ( disk == 0 )\n {\n return -1;\n }\n\n disk->remove(\"IMAGE_ID\");\n\n disk->replace(\"IMAGE\", new_name);\n\n disk->replace(\"IMAGE_UNAME\", new_uname);\n\n return 0;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nstring& VirtualMachineTemplate::to_xml_short(string& xml) const\n{\n ostringstream oss;\n string labels;\n\n string schd_rank, schd_ds_rank;\n string schd_req, schd_ds_req;\n\n string user_prio;\n\n vector attrs;\n\n if (attributes.empty())\n {\n oss << \"\";\n }\n else\n {\n oss << \"\";\n\n \/* ------------------------------------------------------------------ *\/\n \/* Attributes required by Sunstone *\/\n \/* - LABELS *\/\n \/* ------------------------------------------------------------------ *\/\n if (get(\"LABELS\", labels))\n {\n oss << \"\" << one_util::escape_xml(labels) << \"<\/LABELS>\";\n }\n\n \/* ------------------------------------------------------------------ *\/\n \/* Attributes required by Scheduler *\/\n \/* - SCHED_RANK (RANK - deprecated) *\/\n \/* - SCHED_DS_RANK *\/\n \/* - SCHED_REQUIREMENTS *\/\n \/* - SCHED_DS_REQUIREMENTS *\/\n \/* *\/\n \/* - SCHED_ACTION *\/\n \/* - PUBLIC_CLOUD *\/\n \/* ------------------------------------------------------------------ *\/\n if (get(\"SCHED_RANK\", schd_rank))\n {\n oss << \"\" << one_util::escape_xml(schd_rank)\n << \"<\/SCHED_RANK>\";\n }\n\n if (get(\"SCHED_DS_RANK\", schd_ds_rank))\n {\n oss << \"\" << one_util::escape_xml(schd_ds_rank)\n << \"<\/SCHED_DS_RANK>\";\n }\n\n if (get(\"SCHED_REQUIREMENTS\", schd_req))\n {\n oss << \"\" << one_util::escape_xml(schd_req)\n << \"<\/SCHED_REQUIREMENTS>\";\n }\n\n if (get(\"SCHED_DS_REQUIREMENTS\", schd_ds_req))\n {\n oss << \"\" << one_util::escape_xml(schd_ds_req)\n << \"<\/SCHED_DS_REQUIREMENTS>\";\n }\n\n if (get(\"USER_PRIORITY\", user_prio))\n {\n oss << \"\" << one_util::escape_xml(user_prio)\n << \"<\/USER_PRIORITY>\";\n }\n\n if ( get(\"PUBLIC_CLOUD\", attrs) > 0 )\n {\n for (auto vattr : attrs)\n {\n vattr->to_xml(oss);\n }\n }\n\n attrs.clear();\n\n if ( get(\"SCHED_ACTION\", attrs) > 0 )\n {\n for (auto vattr : attrs)\n {\n vattr->to_xml(oss);\n }\n }\n\n oss << \"<\/USER_TEMPLATE>\";\n }\n\n xml = oss.str();\n\n return xml;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\n\nstd::map> VirtualMachineTemplate::UPDATECONF_ATTRS = {\n { \"OS\",\n { \"ARCH\",\n \"MACHINE\",\n \"KERNEL\",\n \"INITRD\",\n \"BOOTLOADER\",\n \"BOOT\",\n \"KERNEL_CMD\",\n \"ROOT\",\n \"SD_DISK_BUS\",\n \"UUID\"}\n },\n { \"FEATURES\",\n { \"PAE\",\n \"ACPI\",\n \"APIC\",\n \"LOCALTIME\",\n \"HYPERV\",\n \"GUEST_AGENT\",\n \"VIRTIO_SCSI_QUEUES\",\n \"IOTHREADS\"}\n },\n { \"INPUT\",\n { \"TYPE\",\n \"BUS\"}\n },\n {\"GRAPHICS\",\n { \"TYPE\",\n \"LISTEN\",\n \"PASSWD\",\n \"KEYMAP\",\n \"COMMAND\"}\n },\n {\"RAW\",\n { \"TYPE\",\n \"DATA\",\n \"DATA_VMX\"}\n },\n {\"CPU_MODEL\",\n { \"MODEL\" }\n }\n};\n\n\/\/ -----------------------------------------------------------------------------\n\/**\n * returns a copy the values of a vector value\n *\/\nstatic void copy_vector_values(const Template *old_tmpl, Template *new_tmpl,\n const char * name)\n{\n string value;\n\n const VectorAttribute * old_attr = old_tmpl->get(name);\n\n if ( old_attr == 0 )\n {\n return;\n }\n\n VectorAttribute * new_vattr = new VectorAttribute(name);\n\n std::vector vnames = VirtualMachineTemplate::UPDATECONF_ATTRS[name];\n\n for (const auto& vname : vnames)\n {\n std::string vval = old_attr->vector_value(vname);\n\n if (!vval.empty())\n {\n new_vattr->replace(vname, vval);\n }\n }\n\n if ( new_vattr->empty() )\n {\n delete new_vattr;\n }\n else\n {\n new_tmpl->set(new_vattr);\n }\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nunique_ptr VirtualMachineTemplate::get_updateconf_template() const\n{\n auto conf_tmpl = make_unique();\n\n copy_vector_values(this, conf_tmpl.get(), \"OS\");\n\n copy_vector_values(this, conf_tmpl.get(), \"FEATURES\");\n\n copy_vector_values(this, conf_tmpl.get(), \"INPUT\");\n\n copy_vector_values(this, conf_tmpl.get(), \"GRAPHICS\");\n\n copy_vector_values(this, conf_tmpl.get(), \"RAW\");\n\n copy_vector_values(this, conf_tmpl.get(), \"CPU_MODEL\");\n\n const VectorAttribute * context = get(\"CONTEXT\");\n\n if ( context != 0 )\n {\n conf_tmpl->set(context->clone());\n }\n\n return conf_tmpl;\n}\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: estack.hxx,v $\n *\n * $Revision: 1.1.1.1 $\n *\n * last change: $Author: np $ $Date: 2002-03-08 14:45:27 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef ARY_ESTACK_HXX\n#define ARY_ESTACK_HXX\n\n\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n#include \n \/\/ COMPONENTS\n \/\/ PARAMETERS\n\n\n\ntemplate \nclass EStack : private std::slist\n{\n private:\n typedef std::slist base;\n const base & Base() const { return *this; }\n base & Base() { return *this; }\n\n public:\n typedef ELEM value_type;\n typedef std::slist::size_type size_type;\n\n \/\/ LIFECYCLE\n EStack() {}\n EStack(\n const EStack & i_rStack )\n : base( (const base &)(i_rStack) ) {}\n ~EStack() {}\n \/\/ OPERATORS\n EStack & operator=(\n const EStack & i_rStack )\n { base::operator=( i_rStack.Base() );\n return *this; }\n bool operator==(\n const EStack &\n i_r2 ) const\n { return std::operator==( Base(), i_rStack.Base() ); }\n bool operator<(\n const EStack &\n i_r2 ) const\n { return std::operator<( Base(), i_rStack.Base() ); }\n \/\/ OPERATIONS\n void push(\n const value_type & i_rElem )\n { base::push_front(i_rElem); }\n void pop() { base::pop_front(); }\n void erase_all() { while (NOT empty()) pop(); }\n\n \/\/ INQUIRY\n const value_type & top() const { return base::front(); }\n size_type size() const { return base::size(); }\n bool empty() const { return base::empty(); }\n\n \/\/ ACCESS\n value_type & top() { return base::front(); }\n};\n\n\n\n\/\/ IMPLEMENTATION\n\n\n#endif\n\nINTEGRATION: CWS adc6 (1.1.1.1.50); FILE MERGED 2003\/06\/26 14:43:32 np 1.1.1.1.50.1: #110259# Fix differing output on Windows vs. Unix and remove broken links from output.\/*************************************************************************\n *\n * $RCSfile: estack.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: hr $ $Date: 2003-06-30 15:27:34 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef ARY_ESTACK_HXX\n#define ARY_ESTACK_HXX\n\n\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n#include \n \/\/ COMPONENTS\n \/\/ PARAMETERS\n\n\n\ntemplate \nclass EStack : private std::slist\n{\n private:\n typedef std::slist base;\n const base & Base() const { return *this; }\n base & Base() { return *this; }\n\n public:\n typedef ELEM value_type;\n typedef typename std::slist::size_type size_type;\n\n \/\/ LIFECYCLE\n EStack() {}\n EStack(\n const EStack & i_rStack )\n : base( (const base &)(i_rStack) ) {}\n ~EStack() {}\n \/\/ OPERATORS\n EStack & operator=(\n const EStack & i_rStack )\n { base::operator=( i_rStack.Base() );\n return *this; }\n bool operator==(\n const EStack &\n i_r2 ) const\n { return std::operator==( Base(), i_rStack.Base() ); }\n bool operator<(\n const EStack &\n i_r2 ) const\n { return std::operator<( Base(), i_rStack.Base() ); }\n \/\/ OPERATIONS\n void push(\n const value_type & i_rElem )\n { base::push_front(i_rElem); }\n void pop() { base::pop_front(); }\n void erase_all() { while (NOT empty()) pop(); }\n\n \/\/ INQUIRY\n const value_type & top() const { return base::front(); }\n size_type size() const { return base::size(); }\n bool empty() const { return base::empty(); }\n\n \/\/ ACCESS\n value_type & top() { return base::front(); }\n};\n\n\n\n\/\/ IMPLEMENTATION\n\n\n#endif\n\n<|endoftext|>"} {"text":"Added unit test relative displacement<|endoftext|>"} {"text":"\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/ Author: Sebastian Schaffert \n\n#include \"SourcesToolService.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"SerializerTSV.h\"\n#include \"SerializerJSON.h\"\n#include \"Persistence.h\"\n#include \"Membuf.h\"\n#include \"Version.h\"\n\n#define TIMING(message, begin, end) \\\n BOOSTER_NOTICE(\"sourcestool\") \\\n << request().remote_addr() << \": \" \\\n << (message) << \" time: \" \\\n << 1000 * (static_cast(end - begin) \/ CLOCKS_PER_SEC) \\\n << \"ms\" << std::endl;\n\n\/\/ initialise static counters for status reports\ntime_t SourcesToolService::startupTime = std::time(NULL);\nint64_t SourcesToolService::reqGetEntityCount = 0;\nint64_t SourcesToolService::reqGetRandomCount = 0;\nint64_t SourcesToolService::reqGetStatementCount = 0;\nint64_t SourcesToolService::reqUpdateStatementCount = 0;\nint64_t SourcesToolService::reqStatusCount = 0;\n\n\/\/ format a time_t using ISO8601 GMT time\ninline std::string formatGMT(time_t* time) {\n char result[128];\n std::strftime(result, 128, \"%Y-%m-%dT%H:%M:%SZ\", gmtime(time));\n return std::string(result);\n}\n\n\/\/ represent memory statistics (used for status)\nstruct memstat {\n double rss, shared_mem, private_mem;\n};\n\n\/\/ read memory statistics from \/proc (used for status)\ninline memstat getMemStat() {\n int tSize = 0, resident = 0, share = 0;\n std::ifstream buffer(\"\/proc\/self\/statm\");\n buffer >> tSize >> resident >> share;\n buffer.close();\n\n struct memstat result;\n\n long page_size_kb = sysconf(_SC_PAGE_SIZE) \/ 1024; \/\/ in case x86-64 is configured to use 2MB pages\n result.rss = resident * page_size_kb;\n result.shared_mem = share * page_size_kb;\n result.private_mem = result.rss - result.shared_mem;\n\n return result;\n}\n\n\/\/ initialise service mappings from URLs to methods\nSourcesToolService::SourcesToolService(cppcms::service &srv)\n : cppcms::application(srv), backend(settings()[\"database\"]) {\n\n dispatcher().assign(\"\/entities\/(Q\\\\d+)\",\n &SourcesToolService::getEntityByQID, this, 1);\n mapper().assign(\"entity_by_qid\", \"\/entities\/{1}\");\n\n \/\/ map request to random entity selector\n dispatcher().assign(\"\/entities\/any\",\n &SourcesToolService::getRandomEntity, this);\n mapper().assign(\"entity_by_topic_user\", \"\/entities\/any\");\n\n \/\/ map GET and POST requests to \/entities\/ to the respective handlers\n \/\/ we use a helper function to distinguish both cases, since cppcms\n \/\/ currently does not really support REST\n dispatcher().assign(\"\/statements\/(\\\\d+)\",\n &SourcesToolService::handleGetPostStatement, this, 1);\n mapper().assign(\"stmt_by_id\", \"\/statements\/{1}\");\n\n dispatcher().assign(\"\/statements\/any\",\n &SourcesToolService::getRandomStatements, this);\n mapper().assign(\"stmt_by_random\", \"\/statements\/any\");\n\n dispatcher().assign(\"\/import\",\n &SourcesToolService::importStatements, this);\n mapper().assign(\"import\", \"\/import\");\n\n dispatcher().assign(\"\/delete\",\n &SourcesToolService::deleteStatements, this);\n mapper().assign(\"delete\", \"\/delete\");\n\n dispatcher().assign(\"\/datasets\/all\",\n &SourcesToolService::getAllDatasets, this);\n mapper().assign(\"datasets_all\", \"\/datasets\/all\");\n\n dispatcher().assign(\"\/status\",\n &SourcesToolService::getStatus, this);\n mapper().assign(\"status\", \"\/status\");\n\n dispatcher().assign(\"\/dashboard\/activitylog\",\n &SourcesToolService::getActivityLog, this);\n mapper().assign(\"activitylog\", \"\/dashboard\/activitylog\");\n}\n\n\nvoid SourcesToolService::handleGetPostStatement(std::string stid) {\n if (request().request_method() == \"POST\") {\n approveStatement(std::stoll(stid));\n } else {\n getStatement(std::stoll(stid));\n }\n}\n\nvoid SourcesToolService::getEntityByQID(std::string qid) {\n clock_t begin = std::clock();\n\n std::vector statements = backend.getStatementsByQID(cache(), qid, true, request().get(\"dataset\"));\n\n addCORSHeaders();\n addVersionHeaders();\n\n if (statements.size() > 0) {\n serializeStatements(statements);\n } else {\n response().status(404, \"no statements found for entity \"+qid);\n }\n\n reqGetEntityCount++;\n\n clock_t end = std::clock();\n TIMING(\"GET \/entities\/\" + qid, begin, end);\n}\n\nvoid SourcesToolService::getRandomEntity() {\n clock_t begin = std::clock();\n\n addCORSHeaders();\n addVersionHeaders();\n\n try {\n std::vector statements = backend.getStatementsByRandomQID(cache(), true, request().get(\"dataset\"));\n serializeStatements(statements);\n } catch(PersistenceException const &e) {\n response().status(404, \"no random unapproved entity found\");\n }\n\n reqGetRandomCount++;\n\n clock_t end = std::clock();\n TIMING(\"GET \/entities\/any\", begin, end);\n}\n\nvoid SourcesToolService::approveStatement(int64_t stid) {\n clock_t begin = std::clock();\n\n ApprovalState state;\n\n addCORSHeaders();\n addVersionHeaders();\n\n \/\/ return 403 forbidden when there is no user given or the username is too\n \/\/ long for the database\n if (request().get(\"user\") == \"\" || request().get(\"user\").length() > 64) {\n response().status(403, \"Forbidden: invalid or missing user\");\n return;\n }\n\n \/\/ check if statement exists and update it with new state\n try {\n backend.updateStatement(cache(), stid, stateFromString(request().get(\"state\")), request().get(\"user\"));\n } catch(PersistenceException const &e) {\n response().status(404, \"Statement not found\");\n } catch(InvalidApprovalState const &e) {\n response().status(400, \"Bad Request: invalid or missing state parameter\");\n }\n\n reqUpdateStatementCount++;\n\n clock_t end = std::clock();\n TIMING(\"POST \/statements\/\" + std::to_string(stid), begin, end);\n}\n\nvoid SourcesToolService::getStatement(int64_t stid) {\n clock_t begin = std::clock();\n\n addCORSHeaders();\n addVersionHeaders();\n\n \/\/ query for statement, wrap it in a vector and return it\n try {\n std::vector statements = { backend.getStatementByID(cache(), stid) };\n serializeStatements(statements);\n } catch(PersistenceException const &e) {\n std::cerr << \"error: \" << e.what() << std::endl;\n response().status(404, \"Statement not found\");\n }\n\n reqGetStatementCount++;\n\n clock_t end = std::clock();\n TIMING(\"GET \/statements\/\" + std::to_string(stid), begin, end);\n}\n\nvoid SourcesToolService::getRandomStatements() {\n clock_t begin = std::clock();\n\n int count = 10;\n if (request().get(\"count\") != \"\") {\n count = std::stoi(request().get(\"count\"));\n }\n\n addCORSHeaders();\n addVersionHeaders();\n\n serializeStatements(backend.getRandomStatements(cache(), count, true));\n\n clock_t end = std::clock();\n TIMING(\"GET \/statements\/any\", begin, end);\n}\n\n\nvoid SourcesToolService::getStatus() {\n clock_t begin = std::clock();\n\n addCORSHeaders();\n addVersionHeaders();\n\n cppcms::json::value result;\n\n Status status = backend.getStatus(cache());\n\n result[\"statements\"][\"total\"] = status.getStatements();\n result[\"statements\"][\"approved\"] = status.getApproved();\n result[\"statements\"][\"unapproved\"] = status.getUnapproved();\n result[\"statements\"][\"blacklisted\"] = status.getBlacklisted();\n result[\"statements\"][\"duplicate\"] = status.getDuplicate();\n result[\"statements\"][\"wrong\"] = status.getWrong();\n\n cppcms::json::array topusers;\n for (auto entry : status.getTopUsers()) {\n cppcms::json::value v;\n v[\"name\"] = entry.first;\n v[\"activities\"] = entry.second;\n topusers.push_back(v);\n }\n result[\"topusers\"] = topusers;\n\n \/\/ system information\n result[\"system\"][\"startup\"] = formatGMT(&SourcesToolService::startupTime);\n result[\"system\"][\"version\"] = std::string(GIT_SHA1);\n result[\"system\"][\"cache_hits\"] = backend.getCacheHits();\n result[\"system\"][\"cache_misses\"] = backend.getCacheMisses();\n\n struct memstat meminfo = getMemStat();\n result[\"system\"][\"shared_mem\"] = meminfo.shared_mem;\n result[\"system\"][\"private_mem\"] = meminfo.private_mem;\n result[\"system\"][\"rss\"] = meminfo.rss;\n\n \/\/ request statistics\n result[\"requests\"][\"getentity\"] = reqGetEntityCount;\n result[\"requests\"][\"getrandom\"] = reqGetRandomCount;\n result[\"requests\"][\"getstatement\"] = reqGetStatementCount;\n result[\"requests\"][\"updatestatement\"] = reqUpdateStatementCount;\n result[\"requests\"][\"getstatus\"] = reqStatusCount;\n\n response().content_type(\"application\/json\");\n result.save(response().out(), cppcms::json::readable);\n\n reqStatusCount++;\n\n clock_t end = std::clock();\n TIMING(\"GET \/status\", begin, end);\n}\n\nvoid SourcesToolService::serializeStatements(const std::vector &statements) {\n if(request().http_accept() == \"text\/vnd.wikidata+tsv\"\n || request().http_accept() == \"text\/tsv\") {\n response().content_type(\"text\/vnd.wikidata+tsv\");\n\n Serializer::writeTSV(statements.cbegin(), statements.cend(), &response().out());\n } else if(request().http_accept() == \"application\/vnd.wikidata+json\") {\n response().content_type(\"application\/vnd.wikidata+json\");\n\n Serializer::writeWikidataJSON(statements.cbegin(), statements.cend(), &response().out());\n } else {\n response().content_type(\"application\/vnd.wikidata.envelope+json\");\n\n Serializer::writeEnvelopeJSON(statements.cbegin(), statements.cend(), &response().out());\n }\n}\n\nvoid SourcesToolService::importStatements() {\n addVersionHeaders();\n\n if (request().request_method() == \"POST\") {\n clock_t begin = std::clock();\n\n \/\/ check if token matches\n if (request().get(\"token\") != settings()[\"token\"].str()) {\n response().status(401, \"Invalid authorization token\");\n return;\n }\n\n if (request().get(\"dataset\") == \"\") {\n response().status(400, \"Missing argument: dataset\");\n return;\n }\n\n \/\/ check if content is gzipped\n bool gzip = false;\n if (request().get(\"gzip\") == \"true\") {\n gzip = true;\n }\n\n bool dedup = true;\n if (request().get(\"deduplicate\") == \"false\") {\n dedup = false;\n }\n\n \/\/ wrap raw post data into a memory stream\n Membuf body(request().raw_post_data());\n std::istream in(&body);\n\n \/\/ import statements\n int64_t count = backend.importStatements(\n cache(), in, request().get(\"dataset\"), gzip, dedup);\n\n clock_t end = std::clock();\n\n cppcms::json::value result;\n result[\"count\"] = count;\n result[\"time\"] = 1000 * (static_cast(end - begin) \/ CLOCKS_PER_SEC);\n\n response().content_type(\"application\/json\");\n result.save(response().out(), cppcms::json::readable);\n\n TIMING(\"POST \/import\", begin, end);\n } else {\n response().status(405, \"Method not allowed\");\n response().set_header(\"Allow\", \"POST\");\n }\n}\n\nvoid SourcesToolService::getAllDatasets() {\n\taddCORSHeaders();\n\taddVersionHeaders();\n\n\tstd::vector datasets = backend.getDatasets(cache());\n\n\tcppcms::json::value result;\n\tfor(std::string id : datasets) {\n result[id][\"id\"] = id;\n\t}\n\n response().content_type(\"application\/json\");\n result.save(response().out(), cppcms::json::readable);\n}\n\nvoid SourcesToolService::deleteStatements() {\n addVersionHeaders();\n\n if (request().request_method() == \"POST\") {\n\n \/\/ check if token matches\n if (request().get(\"token\") != settings()[\"token\"].str()) {\n response().status(401, \"Invalid authorization token\");\n return;\n }\n\n clock_t begin = std::clock();\n\n \/\/ check if statement exists and update it with new state\n try {\n backend.deleteStatements(cache(), stateFromString(request().get(\"state\")));\n } catch(PersistenceException const &e) {\n response().status(404, \"Could not delete statements\");\n } catch(InvalidApprovalState const &e) {\n response().status(400, \"Bad Request: invalid or missing state parameter\");\n }\n\n clock_t end = std::clock();\n\n TIMING(\"POST \/delete\", begin, end);\n } else {\n response().status(405, \"Method not allowed\");\n response().set_header(\"Allow\", \"POST\");\n }\n}\n\nvoid SourcesToolService::addCORSHeaders() {\n response().set_header(\"Access-Control-Allow-Origin\", \"*\");\n}\n\nvoid SourcesToolService::addVersionHeaders() {\n response().set_header(\"X-Powered-By\", std::string(\"Wikidata Sources Tool\/\") + GIT_SHA1);\n}\n\n\nvoid SourcesToolService::getActivityLog() {\n clock_t begin = std::clock();\n\n addCORSHeaders();\n addVersionHeaders();\n\n cppcms::json::value result;\n\n Dashboard::ActivityLog activities = backend.getActivityLog(cache());\n\n std::vector users(activities.getUsers().begin(), activities.getUsers().end());\n\n result[\"users\"] = users;\n for(int i=0; i< activities.getActivities().size(); i++) {\n Dashboard::ActivityEntry entry = activities.getActivities()[i];\n\n if (entry.date != \"\") {\n result[\"approved\"][i][0] = entry.date;\n for (int j = 0; j < users.size(); j++) {\n if (entry.approved.find(users[j]) != entry.approved.end()) {\n result[\"approved\"][i][j + 1] = entry.approved[users[j]];\n } else {\n result[\"approved\"][i][j + 1] = 0;\n }\n }\n\n result[\"rejected\"][i][0] = entry.date;\n for (int j = 0; j < users.size(); j++) {\n if (entry.rejected.find(users[j]) != entry.rejected.end()) {\n result[\"rejected\"][i][j + 1] = entry.rejected[users[j]];\n } else {\n result[\"rejected\"][i][j + 1] = 0;\n }\n }\n }\n\n }\n\n\n response().content_type(\"application\/json\");\n result.save(response().out(), cppcms::json::readable);\n\n reqStatusCount++;\n\n clock_t end = std::clock();\n TIMING(\"GET \/dashboard\/activitylog\", begin, end);\n}\nAdds dataset to the import response\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/ Author: Sebastian Schaffert \n\n#include \"SourcesToolService.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"SerializerTSV.h\"\n#include \"SerializerJSON.h\"\n#include \"Persistence.h\"\n#include \"Membuf.h\"\n#include \"Version.h\"\n\n#define TIMING(message, begin, end) \\\n BOOSTER_NOTICE(\"sourcestool\") \\\n << request().remote_addr() << \": \" \\\n << (message) << \" time: \" \\\n << 1000 * (static_cast(end - begin) \/ CLOCKS_PER_SEC) \\\n << \"ms\" << std::endl;\n\n\/\/ initialise static counters for status reports\ntime_t SourcesToolService::startupTime = std::time(NULL);\nint64_t SourcesToolService::reqGetEntityCount = 0;\nint64_t SourcesToolService::reqGetRandomCount = 0;\nint64_t SourcesToolService::reqGetStatementCount = 0;\nint64_t SourcesToolService::reqUpdateStatementCount = 0;\nint64_t SourcesToolService::reqStatusCount = 0;\n\n\/\/ format a time_t using ISO8601 GMT time\ninline std::string formatGMT(time_t* time) {\n char result[128];\n std::strftime(result, 128, \"%Y-%m-%dT%H:%M:%SZ\", gmtime(time));\n return std::string(result);\n}\n\n\/\/ represent memory statistics (used for status)\nstruct memstat {\n double rss, shared_mem, private_mem;\n};\n\n\/\/ read memory statistics from \/proc (used for status)\ninline memstat getMemStat() {\n int tSize = 0, resident = 0, share = 0;\n std::ifstream buffer(\"\/proc\/self\/statm\");\n buffer >> tSize >> resident >> share;\n buffer.close();\n\n struct memstat result;\n\n long page_size_kb = sysconf(_SC_PAGE_SIZE) \/ 1024; \/\/ in case x86-64 is configured to use 2MB pages\n result.rss = resident * page_size_kb;\n result.shared_mem = share * page_size_kb;\n result.private_mem = result.rss - result.shared_mem;\n\n return result;\n}\n\n\/\/ initialise service mappings from URLs to methods\nSourcesToolService::SourcesToolService(cppcms::service &srv)\n : cppcms::application(srv), backend(settings()[\"database\"]) {\n\n dispatcher().assign(\"\/entities\/(Q\\\\d+)\",\n &SourcesToolService::getEntityByQID, this, 1);\n mapper().assign(\"entity_by_qid\", \"\/entities\/{1}\");\n\n \/\/ map request to random entity selector\n dispatcher().assign(\"\/entities\/any\",\n &SourcesToolService::getRandomEntity, this);\n mapper().assign(\"entity_by_topic_user\", \"\/entities\/any\");\n\n \/\/ map GET and POST requests to \/entities\/ to the respective handlers\n \/\/ we use a helper function to distinguish both cases, since cppcms\n \/\/ currently does not really support REST\n dispatcher().assign(\"\/statements\/(\\\\d+)\",\n &SourcesToolService::handleGetPostStatement, this, 1);\n mapper().assign(\"stmt_by_id\", \"\/statements\/{1}\");\n\n dispatcher().assign(\"\/statements\/any\",\n &SourcesToolService::getRandomStatements, this);\n mapper().assign(\"stmt_by_random\", \"\/statements\/any\");\n\n dispatcher().assign(\"\/import\",\n &SourcesToolService::importStatements, this);\n mapper().assign(\"import\", \"\/import\");\n\n dispatcher().assign(\"\/delete\",\n &SourcesToolService::deleteStatements, this);\n mapper().assign(\"delete\", \"\/delete\");\n\n dispatcher().assign(\"\/datasets\/all\",\n &SourcesToolService::getAllDatasets, this);\n mapper().assign(\"datasets_all\", \"\/datasets\/all\");\n\n dispatcher().assign(\"\/status\",\n &SourcesToolService::getStatus, this);\n mapper().assign(\"status\", \"\/status\");\n\n dispatcher().assign(\"\/dashboard\/activitylog\",\n &SourcesToolService::getActivityLog, this);\n mapper().assign(\"activitylog\", \"\/dashboard\/activitylog\");\n}\n\n\nvoid SourcesToolService::handleGetPostStatement(std::string stid) {\n if (request().request_method() == \"POST\") {\n approveStatement(std::stoll(stid));\n } else {\n getStatement(std::stoll(stid));\n }\n}\n\nvoid SourcesToolService::getEntityByQID(std::string qid) {\n clock_t begin = std::clock();\n\n std::vector statements = backend.getStatementsByQID(cache(), qid, true, request().get(\"dataset\"));\n\n addCORSHeaders();\n addVersionHeaders();\n\n if (statements.size() > 0) {\n serializeStatements(statements);\n } else {\n response().status(404, \"no statements found for entity \"+qid);\n }\n\n reqGetEntityCount++;\n\n clock_t end = std::clock();\n TIMING(\"GET \/entities\/\" + qid, begin, end);\n}\n\nvoid SourcesToolService::getRandomEntity() {\n clock_t begin = std::clock();\n\n addCORSHeaders();\n addVersionHeaders();\n\n try {\n std::vector statements = backend.getStatementsByRandomQID(cache(), true, request().get(\"dataset\"));\n serializeStatements(statements);\n } catch(PersistenceException const &e) {\n response().status(404, \"no random unapproved entity found\");\n }\n\n reqGetRandomCount++;\n\n clock_t end = std::clock();\n TIMING(\"GET \/entities\/any\", begin, end);\n}\n\nvoid SourcesToolService::approveStatement(int64_t stid) {\n clock_t begin = std::clock();\n\n ApprovalState state;\n\n addCORSHeaders();\n addVersionHeaders();\n\n \/\/ return 403 forbidden when there is no user given or the username is too\n \/\/ long for the database\n if (request().get(\"user\") == \"\" || request().get(\"user\").length() > 64) {\n response().status(403, \"Forbidden: invalid or missing user\");\n return;\n }\n\n \/\/ check if statement exists and update it with new state\n try {\n backend.updateStatement(cache(), stid, stateFromString(request().get(\"state\")), request().get(\"user\"));\n } catch(PersistenceException const &e) {\n response().status(404, \"Statement not found\");\n } catch(InvalidApprovalState const &e) {\n response().status(400, \"Bad Request: invalid or missing state parameter\");\n }\n\n reqUpdateStatementCount++;\n\n clock_t end = std::clock();\n TIMING(\"POST \/statements\/\" + std::to_string(stid), begin, end);\n}\n\nvoid SourcesToolService::getStatement(int64_t stid) {\n clock_t begin = std::clock();\n\n addCORSHeaders();\n addVersionHeaders();\n\n \/\/ query for statement, wrap it in a vector and return it\n try {\n std::vector statements = { backend.getStatementByID(cache(), stid) };\n serializeStatements(statements);\n } catch(PersistenceException const &e) {\n std::cerr << \"error: \" << e.what() << std::endl;\n response().status(404, \"Statement not found\");\n }\n\n reqGetStatementCount++;\n\n clock_t end = std::clock();\n TIMING(\"GET \/statements\/\" + std::to_string(stid), begin, end);\n}\n\nvoid SourcesToolService::getRandomStatements() {\n clock_t begin = std::clock();\n\n int count = 10;\n if (request().get(\"count\") != \"\") {\n count = std::stoi(request().get(\"count\"));\n }\n\n addCORSHeaders();\n addVersionHeaders();\n\n serializeStatements(backend.getRandomStatements(cache(), count, true));\n\n clock_t end = std::clock();\n TIMING(\"GET \/statements\/any\", begin, end);\n}\n\n\nvoid SourcesToolService::getStatus() {\n clock_t begin = std::clock();\n\n addCORSHeaders();\n addVersionHeaders();\n\n cppcms::json::value result;\n\n Status status = backend.getStatus(cache());\n\n result[\"statements\"][\"total\"] = status.getStatements();\n result[\"statements\"][\"approved\"] = status.getApproved();\n result[\"statements\"][\"unapproved\"] = status.getUnapproved();\n result[\"statements\"][\"blacklisted\"] = status.getBlacklisted();\n result[\"statements\"][\"duplicate\"] = status.getDuplicate();\n result[\"statements\"][\"wrong\"] = status.getWrong();\n\n cppcms::json::array topusers;\n for (auto entry : status.getTopUsers()) {\n cppcms::json::value v;\n v[\"name\"] = entry.first;\n v[\"activities\"] = entry.second;\n topusers.push_back(v);\n }\n result[\"topusers\"] = topusers;\n\n \/\/ system information\n result[\"system\"][\"startup\"] = formatGMT(&SourcesToolService::startupTime);\n result[\"system\"][\"version\"] = std::string(GIT_SHA1);\n result[\"system\"][\"cache_hits\"] = backend.getCacheHits();\n result[\"system\"][\"cache_misses\"] = backend.getCacheMisses();\n\n struct memstat meminfo = getMemStat();\n result[\"system\"][\"shared_mem\"] = meminfo.shared_mem;\n result[\"system\"][\"private_mem\"] = meminfo.private_mem;\n result[\"system\"][\"rss\"] = meminfo.rss;\n\n \/\/ request statistics\n result[\"requests\"][\"getentity\"] = reqGetEntityCount;\n result[\"requests\"][\"getrandom\"] = reqGetRandomCount;\n result[\"requests\"][\"getstatement\"] = reqGetStatementCount;\n result[\"requests\"][\"updatestatement\"] = reqUpdateStatementCount;\n result[\"requests\"][\"getstatus\"] = reqStatusCount;\n\n response().content_type(\"application\/json\");\n result.save(response().out(), cppcms::json::readable);\n\n reqStatusCount++;\n\n clock_t end = std::clock();\n TIMING(\"GET \/status\", begin, end);\n}\n\nvoid SourcesToolService::serializeStatements(const std::vector &statements) {\n if(request().http_accept() == \"text\/vnd.wikidata+tsv\"\n || request().http_accept() == \"text\/tsv\") {\n response().content_type(\"text\/vnd.wikidata+tsv\");\n\n Serializer::writeTSV(statements.cbegin(), statements.cend(), &response().out());\n } else if(request().http_accept() == \"application\/vnd.wikidata+json\") {\n response().content_type(\"application\/vnd.wikidata+json\");\n\n Serializer::writeWikidataJSON(statements.cbegin(), statements.cend(), &response().out());\n } else {\n response().content_type(\"application\/vnd.wikidata.envelope+json\");\n\n Serializer::writeEnvelopeJSON(statements.cbegin(), statements.cend(), &response().out());\n }\n}\n\nvoid SourcesToolService::importStatements() {\n addVersionHeaders();\n\n if (request().request_method() == \"POST\") {\n clock_t begin = std::clock();\n\n \/\/ check if token matches\n if (request().get(\"token\") != settings()[\"token\"].str()) {\n response().status(401, \"Invalid authorization token\");\n return;\n }\n\n std::string dataset = request().get(\"dataset\");\n if (dataset == \"\") {\n response().status(400, \"Missing argument: dataset\");\n return;\n }\n\n \/\/ check if content is gzipped\n bool gzip = false;\n if (request().get(\"gzip\") == \"true\") {\n gzip = true;\n }\n\n bool dedup = true;\n if (request().get(\"deduplicate\") == \"false\") {\n dedup = false;\n }\n\n \/\/ wrap raw post data into a memory stream\n Membuf body(request().raw_post_data());\n std::istream in(&body);\n\n \/\/ import statements\n int64_t count = backend.importStatements(\n cache(), in, dataset, gzip, dedup);\n\n clock_t end = std::clock();\n\n cppcms::json::value result;\n result[\"count\"] = count;\n result[\"time\"] = 1000 * (static_cast(end - begin) \/ CLOCKS_PER_SEC);\n result[\"dataset\"] = dataset;\n\n response().content_type(\"application\/json\");\n result.save(response().out(), cppcms::json::readable);\n\n TIMING(\"POST \/import\", begin, end);\n } else {\n response().status(405, \"Method not allowed\");\n response().set_header(\"Allow\", \"POST\");\n }\n}\n\nvoid SourcesToolService::getAllDatasets() {\n\taddCORSHeaders();\n\taddVersionHeaders();\n\n\tstd::vector datasets = backend.getDatasets(cache());\n\n\tcppcms::json::value result;\n\tfor(std::string id : datasets) {\n result[id][\"id\"] = id;\n\t}\n\n response().content_type(\"application\/json\");\n result.save(response().out(), cppcms::json::readable);\n}\n\nvoid SourcesToolService::deleteStatements() {\n addVersionHeaders();\n\n if (request().request_method() == \"POST\") {\n\n \/\/ check if token matches\n if (request().get(\"token\") != settings()[\"token\"].str()) {\n response().status(401, \"Invalid authorization token\");\n return;\n }\n\n clock_t begin = std::clock();\n\n \/\/ check if statement exists and update it with new state\n try {\n backend.deleteStatements(cache(), stateFromString(request().get(\"state\")));\n } catch(PersistenceException const &e) {\n response().status(404, \"Could not delete statements\");\n } catch(InvalidApprovalState const &e) {\n response().status(400, \"Bad Request: invalid or missing state parameter\");\n }\n\n clock_t end = std::clock();\n\n TIMING(\"POST \/delete\", begin, end);\n } else {\n response().status(405, \"Method not allowed\");\n response().set_header(\"Allow\", \"POST\");\n }\n}\n\nvoid SourcesToolService::addCORSHeaders() {\n response().set_header(\"Access-Control-Allow-Origin\", \"*\");\n}\n\nvoid SourcesToolService::addVersionHeaders() {\n response().set_header(\"X-Powered-By\", std::string(\"Wikidata Sources Tool\/\") + GIT_SHA1);\n}\n\n\nvoid SourcesToolService::getActivityLog() {\n clock_t begin = std::clock();\n\n addCORSHeaders();\n addVersionHeaders();\n\n cppcms::json::value result;\n\n Dashboard::ActivityLog activities = backend.getActivityLog(cache());\n\n std::vector users(activities.getUsers().begin(), activities.getUsers().end());\n\n result[\"users\"] = users;\n for(int i=0; i< activities.getActivities().size(); i++) {\n Dashboard::ActivityEntry entry = activities.getActivities()[i];\n\n if (entry.date != \"\") {\n result[\"approved\"][i][0] = entry.date;\n for (int j = 0; j < users.size(); j++) {\n if (entry.approved.find(users[j]) != entry.approved.end()) {\n result[\"approved\"][i][j + 1] = entry.approved[users[j]];\n } else {\n result[\"approved\"][i][j + 1] = 0;\n }\n }\n\n result[\"rejected\"][i][0] = entry.date;\n for (int j = 0; j < users.size(); j++) {\n if (entry.rejected.find(users[j]) != entry.rejected.end()) {\n result[\"rejected\"][i][j + 1] = entry.rejected[users[j]];\n } else {\n result[\"rejected\"][i][j + 1] = 0;\n }\n }\n }\n\n }\n\n\n response().content_type(\"application\/json\");\n result.save(response().out(), cppcms::json::readable);\n\n reqStatusCount++;\n\n clock_t end = std::clock();\n TIMING(\"GET \/dashboard\/activitylog\", begin, end);\n}\n<|endoftext|>"} {"text":"\n#include \"config.h\"\n\n#include \"ambdec.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"compat.h\"\n\n\nnamespace {\n\nint readline(std::istream &f, std::string &output)\n{\n while(f.good() && f.peek() == '\\n')\n f.ignore();\n\n std::getline(f, output);\n return !output.empty();\n}\n\nbool read_clipped_line(std::istream &f, std::string &buffer)\n{\n while(readline(f, buffer))\n {\n std::size_t pos{0};\n while(pos < buffer.length() && std::isspace(buffer[pos]))\n pos++;\n buffer.erase(0, pos);\n\n std::size_t cmtpos{buffer.find_first_of('#')};\n if(cmtpos < buffer.length())\n buffer.resize(cmtpos);\n while(!buffer.empty() && std::isspace(buffer.back()))\n buffer.pop_back();\n\n if(!buffer.empty())\n return true;\n }\n return false;\n}\n\n\nstd::string read_word(std::istream &f)\n{\n std::string ret;\n f >> ret;\n return ret;\n}\n\nbool is_at_end(const std::string &buffer, std::size_t endpos)\n{\n while(endpos < buffer.length() && std::isspace(buffer[endpos]))\n ++endpos;\n if(endpos < buffer.length())\n return false;\n return true;\n}\n\n\nbool load_ambdec_speakers(AmbDecConf *conf, std::istream &f, std::string &buffer)\n{\n ALsizei cur = 0;\n while(cur < conf->NumSpeakers)\n {\n std::istringstream istr{buffer};\n\n std::string cmd = read_word(istr);\n if(cmd.empty())\n {\n if(!read_clipped_line(f, buffer))\n {\n ERR(\"Unexpected end of file\\n\");\n return false;\n }\n istr = std::istringstream{buffer};\n cmd = read_word(istr);\n }\n\n if(cmd == \"add_spkr\")\n {\n istr >> conf->Speakers[cur].Name;\n if(istr.fail()) WARN(\"Name not specified for speaker %u\\n\", cur+1);\n istr >> conf->Speakers[cur].Distance;\n if(istr.fail()) WARN(\"Distance not specified for speaker %u\\n\", cur+1);\n istr >> conf->Speakers[cur].Azimuth;\n if(istr.fail()) WARN(\"Azimuth not specified for speaker %u\\n\", cur+1);\n istr >> conf->Speakers[cur].Elevation;\n if(istr.fail()) WARN(\"Elevation not specified for speaker %u\\n\", cur+1);\n istr >> conf->Speakers[cur].Connection;\n if(istr.fail()) TRACE(\"Connection not specified for speaker %u\\n\", cur+1);\n\n cur++;\n }\n else\n {\n ERR(\"Unexpected speakers command: %s\\n\", cmd.c_str());\n return false;\n }\n\n istr.clear();\n std::streamsize endpos{istr.tellg()};\n if(!is_at_end(buffer, endpos))\n {\n ERR(\"Unexpected junk on line: %s\\n\", buffer.c_str()+endpos);\n return false;\n }\n buffer.clear();\n }\n\n return true;\n}\n\nbool load_ambdec_matrix(ALfloat *gains, ALfloat (*matrix)[MAX_AMBI_COEFFS], ALsizei maxrow, std::istream &f, std::string &buffer)\n{\n bool gotgains = false;\n ALsizei cur = 0;\n while(cur < maxrow)\n {\n std::istringstream istr{buffer};\n std::string cmd;\n\n istr >> cmd;\n if(cmd.empty())\n {\n if(!read_clipped_line(f, buffer))\n {\n ERR(\"Unexpected end of file\\n\");\n return false;\n }\n istr = std::istringstream{buffer};\n istr >> cmd;\n }\n\n if(cmd == \"order_gain\")\n {\n ALuint curgain = 0;\n float value;\n while(istr.good())\n {\n istr >> value;\n if(istr.fail()) break;\n if(!istr.eof() && !std::isspace(istr.peek()))\n {\n ERR(\"Extra junk on gain %u: %s\\n\", curgain+1, buffer.c_str()+istr.tellg());\n return false;\n }\n if(curgain < MAX_AMBI_ORDER+1)\n gains[curgain++] = value;\n }\n while(curgain < MAX_AMBI_ORDER+1)\n gains[curgain++] = 0.0f;\n gotgains = true;\n }\n else if(cmd == \"add_row\")\n {\n ALuint curidx = 0;\n float value;\n while(istr.good())\n {\n istr >> value;\n if(istr.fail()) break;\n if(!istr.eof() && !std::isspace(istr.peek()))\n {\n ERR(\"Extra junk on matrix element %ux%u: %s\\n\", cur, curidx,\n buffer.c_str()+istr.tellg());\n return false;\n }\n if(curidx < MAX_AMBI_COEFFS)\n matrix[cur][curidx++] = value;\n }\n while(curidx < MAX_AMBI_COEFFS)\n matrix[cur][curidx++] = 0.0f;\n cur++;\n }\n else\n {\n ERR(\"Unexpected matrix command: %s\\n\", cmd.c_str());\n return false;\n }\n\n istr.clear();\n std::streamsize endpos{istr.tellg()};\n if(!is_at_end(buffer, endpos))\n {\n ERR(\"Unexpected junk on line: %s\\n\", buffer.c_str()+endpos);\n return false;\n }\n buffer.clear();\n }\n\n if(!gotgains)\n {\n ERR(\"Matrix order_gain not specified\\n\");\n return false;\n }\n\n return true;\n}\n\n} \/\/ namespace\n\nint AmbDecConf::load(const char *fname)\n{\n al::ifstream f{fname};\n if(!f.is_open())\n {\n ERR(\"Failed to open: %s\\n\", fname);\n return 0;\n }\n\n std::string buffer;\n while(read_clipped_line(f, buffer))\n {\n std::istringstream istr{buffer};\n std::string command;\n\n istr >> command;\n if(command.empty())\n {\n ERR(\"Malformed line: %s\\n\", buffer.c_str());\n return 0;\n }\n\n if(command == \"\/description\")\n istr >> Description;\n else if(command == \"\/version\")\n {\n istr >> Version;\n if(!istr.eof() && !std::isspace(istr.peek()))\n {\n ERR(\"Extra junk after version: %s\\n\", buffer.c_str()+istr.tellg());\n return 0;\n }\n if(Version != 3)\n {\n ERR(\"Unsupported version: %u\\n\", Version);\n return 0;\n }\n }\n else if(command == \"\/dec\/chan_mask\")\n {\n istr >> std::hex >> ChanMask >> std::dec;\n if(!istr.eof() && !std::isspace(istr.peek()))\n {\n ERR(\"Extra junk after mask: %s\\n\", buffer.c_str()+istr.tellg());\n return 0;\n }\n }\n else if(command == \"\/dec\/freq_bands\")\n {\n istr >> FreqBands;\n if(!istr.eof() && !std::isspace(istr.peek()))\n {\n ERR(\"Extra junk after freq_bands: %s\\n\", buffer.c_str()+istr.tellg());\n return 0;\n }\n if(FreqBands != 1 && FreqBands != 2)\n {\n ERR(\"Invalid freq_bands value: %u\\n\", FreqBands);\n return 0;\n }\n }\n else if(command == \"\/dec\/speakers\")\n {\n istr >> NumSpeakers;\n if(!istr.eof() && !std::isspace(istr.peek()))\n {\n ERR(\"Extra junk after speakers: %s\\n\", buffer.c_str()+istr.tellg());\n return 0;\n }\n if(NumSpeakers > MAX_OUTPUT_CHANNELS)\n {\n ERR(\"Unsupported speaker count: %u\\n\", NumSpeakers);\n return 0;\n }\n }\n else if(command == \"\/dec\/coeff_scale\")\n {\n std::string scale = read_word(istr);\n if(scale == \"n3d\") CoeffScale = AmbDecScale::N3D;\n else if(scale == \"sn3d\") CoeffScale = AmbDecScale::SN3D;\n else if(scale == \"fuma\") CoeffScale = AmbDecScale::FuMa;\n else\n {\n ERR(\"Unsupported coeff scale: %s\\n\", scale.c_str());\n return 0;\n }\n }\n else if(command == \"\/opt\/xover_freq\")\n {\n istr >> XOverFreq;\n if(!istr.eof() && !std::isspace(istr.peek()))\n {\n ERR(\"Extra junk after xover_freq: %s\\n\", buffer.c_str()+istr.tellg());\n return 0;\n }\n }\n else if(command == \"\/opt\/xover_ratio\")\n {\n istr >> XOverRatio;\n if(!istr.eof() && !std::isspace(istr.peek()))\n {\n ERR(\"Extra junk after xover_ratio: %s\\n\", buffer.c_str()+istr.tellg());\n return 0;\n }\n }\n else if(command == \"\/opt\/input_scale\" || command == \"\/opt\/nfeff_comp\" ||\n command == \"\/opt\/delay_comp\" || command == \"\/opt\/level_comp\")\n {\n \/* Unused *\/\n read_word(istr);\n }\n else if(command == \"\/speakers\/{\")\n {\n std::streamsize endpos{istr.tellg()};\n if(!is_at_end(buffer, endpos))\n {\n ERR(\"Unexpected junk on line: %s\\n\", buffer.c_str()+endpos);\n return 0;\n }\n buffer.clear();\n\n if(!load_ambdec_speakers(this, f, buffer))\n return 0;\n\n if(!read_clipped_line(f, buffer))\n {\n ERR(\"Unexpected end of file\\n\");\n return 0;\n }\n istr = std::istringstream{buffer};\n std::string endmark = read_word(istr);\n if(endmark != \"\/}\")\n {\n ERR(\"Expected \/} after speaker definitions, got %s\\n\", endmark.c_str());\n return 0;\n }\n }\n else if(command == \"\/lfmatrix\/{\" || command == \"\/hfmatrix\/{\" || command == \"\/matrix\/{\")\n {\n std::streamsize endpos{istr.tellg()};\n if(!is_at_end(buffer, endpos))\n {\n ERR(\"Unexpected junk on line: %s\\n\", buffer.c_str()+endpos);\n return 0;\n }\n buffer.clear();\n\n if(FreqBands == 1)\n {\n if(command != \"\/matrix\/{\")\n {\n ERR(\"Unexpected \\\"%s\\\" type for a single-band decoder\\n\", command.c_str());\n return 0;\n }\n if(!load_ambdec_matrix(HFOrderGain, HFMatrix, NumSpeakers, f, buffer))\n return 0;\n }\n else\n {\n if(command == \"\/lfmatrix\/{\")\n {\n if(!load_ambdec_matrix(LFOrderGain, LFMatrix, NumSpeakers, f, buffer))\n return 0;\n }\n else if(command == \"\/hfmatrix\/{\")\n {\n if(!load_ambdec_matrix(HFOrderGain, HFMatrix, NumSpeakers, f, buffer))\n return 0;\n }\n else\n {\n ERR(\"Unexpected \\\"%s\\\" type for a dual-band decoder\\n\", command.c_str());\n return 0;\n }\n }\n\n if(!read_clipped_line(f, buffer))\n {\n ERR(\"Unexpected end of file\\n\");\n return 0;\n }\n istr = std::istringstream{buffer};\n std::string endmark = read_word(istr);\n if(endmark != \"\/}\")\n {\n ERR(\"Expected \/} after matrix definitions, got %s\\n\", endmark.c_str());\n return 0;\n }\n }\n else if(command == \"\/end\")\n {\n std::streamsize endpos{istr.tellg()};\n if(!is_at_end(buffer, endpos))\n {\n ERR(\"Unexpected junk on end: %s\\n\", buffer.c_str()+endpos);\n return 0;\n }\n\n return 1;\n }\n else\n {\n ERR(\"Unexpected command: %s\\n\", command.c_str());\n return 0;\n }\n\n istr.clear();\n std::streamsize endpos{istr.tellg()};\n if(!is_at_end(buffer, endpos))\n {\n ERR(\"Unexpected junk on line: %s\\n\", buffer.c_str()+endpos);\n return 0;\n }\n buffer.clear();\n }\n ERR(\"Unexpected end of file\\n\");\n\n return 0;\n}\nAvoid moving istringstreams\n#include \"config.h\"\n\n#include \"ambdec.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"compat.h\"\n\n\nnamespace {\n\nint readline(std::istream &f, std::string &output)\n{\n while(f.good() && f.peek() == '\\n')\n f.ignore();\n\n std::getline(f, output);\n return !output.empty();\n}\n\nbool read_clipped_line(std::istream &f, std::string &buffer)\n{\n while(readline(f, buffer))\n {\n std::size_t pos{0};\n while(pos < buffer.length() && std::isspace(buffer[pos]))\n pos++;\n buffer.erase(0, pos);\n\n std::size_t cmtpos{buffer.find_first_of('#')};\n if(cmtpos < buffer.length())\n buffer.resize(cmtpos);\n while(!buffer.empty() && std::isspace(buffer.back()))\n buffer.pop_back();\n\n if(!buffer.empty())\n return true;\n }\n return false;\n}\n\n\nstd::string read_word(std::istream &f)\n{\n std::string ret;\n f >> ret;\n return ret;\n}\n\nbool is_at_end(const std::string &buffer, std::size_t endpos)\n{\n while(endpos < buffer.length() && std::isspace(buffer[endpos]))\n ++endpos;\n if(endpos < buffer.length())\n return false;\n return true;\n}\n\n\nbool load_ambdec_speakers(AmbDecConf *conf, std::istream &f, std::string &buffer)\n{\n ALsizei cur = 0;\n while(cur < conf->NumSpeakers)\n {\n std::istringstream istr{buffer};\n\n std::string cmd{read_word(istr)};\n if(cmd.empty())\n {\n if(!read_clipped_line(f, buffer))\n {\n ERR(\"Unexpected end of file\\n\");\n return false;\n }\n continue;\n }\n\n if(cmd == \"add_spkr\")\n {\n istr >> conf->Speakers[cur].Name;\n if(istr.fail()) WARN(\"Name not specified for speaker %u\\n\", cur+1);\n istr >> conf->Speakers[cur].Distance;\n if(istr.fail()) WARN(\"Distance not specified for speaker %u\\n\", cur+1);\n istr >> conf->Speakers[cur].Azimuth;\n if(istr.fail()) WARN(\"Azimuth not specified for speaker %u\\n\", cur+1);\n istr >> conf->Speakers[cur].Elevation;\n if(istr.fail()) WARN(\"Elevation not specified for speaker %u\\n\", cur+1);\n istr >> conf->Speakers[cur].Connection;\n if(istr.fail()) TRACE(\"Connection not specified for speaker %u\\n\", cur+1);\n\n cur++;\n }\n else\n {\n ERR(\"Unexpected speakers command: %s\\n\", cmd.c_str());\n return false;\n }\n\n istr.clear();\n std::streamsize endpos{istr.tellg()};\n if(!is_at_end(buffer, endpos))\n {\n ERR(\"Unexpected junk on line: %s\\n\", buffer.c_str()+endpos);\n return false;\n }\n buffer.clear();\n }\n\n return true;\n}\n\nbool load_ambdec_matrix(ALfloat *gains, ALfloat (*matrix)[MAX_AMBI_COEFFS], ALsizei maxrow, std::istream &f, std::string &buffer)\n{\n bool gotgains = false;\n ALsizei cur = 0;\n while(cur < maxrow)\n {\n std::istringstream istr{buffer};\n\n std::string cmd{read_word(istr)};\n if(cmd.empty())\n {\n if(!read_clipped_line(f, buffer))\n {\n ERR(\"Unexpected end of file\\n\");\n return false;\n }\n continue;\n }\n\n if(cmd == \"order_gain\")\n {\n ALuint curgain = 0;\n float value;\n while(istr.good())\n {\n istr >> value;\n if(istr.fail()) break;\n if(!istr.eof() && !std::isspace(istr.peek()))\n {\n ERR(\"Extra junk on gain %u: %s\\n\", curgain+1, buffer.c_str()+istr.tellg());\n return false;\n }\n if(curgain < MAX_AMBI_ORDER+1)\n gains[curgain++] = value;\n }\n while(curgain < MAX_AMBI_ORDER+1)\n gains[curgain++] = 0.0f;\n gotgains = true;\n }\n else if(cmd == \"add_row\")\n {\n ALuint curidx = 0;\n float value;\n while(istr.good())\n {\n istr >> value;\n if(istr.fail()) break;\n if(!istr.eof() && !std::isspace(istr.peek()))\n {\n ERR(\"Extra junk on matrix element %ux%u: %s\\n\", cur, curidx,\n buffer.c_str()+istr.tellg());\n return false;\n }\n if(curidx < MAX_AMBI_COEFFS)\n matrix[cur][curidx++] = value;\n }\n while(curidx < MAX_AMBI_COEFFS)\n matrix[cur][curidx++] = 0.0f;\n cur++;\n }\n else\n {\n ERR(\"Unexpected matrix command: %s\\n\", cmd.c_str());\n return false;\n }\n\n istr.clear();\n std::streamsize endpos{istr.tellg()};\n if(!is_at_end(buffer, endpos))\n {\n ERR(\"Unexpected junk on line: %s\\n\", buffer.c_str()+endpos);\n return false;\n }\n buffer.clear();\n }\n\n if(!gotgains)\n {\n ERR(\"Matrix order_gain not specified\\n\");\n return false;\n }\n\n return true;\n}\n\n} \/\/ namespace\n\nint AmbDecConf::load(const char *fname)\n{\n al::ifstream f{fname};\n if(!f.is_open())\n {\n ERR(\"Failed to open: %s\\n\", fname);\n return 0;\n }\n\n std::string buffer;\n while(read_clipped_line(f, buffer))\n {\n std::istringstream istr{buffer};\n\n std::string command{read_word(istr)};\n if(command.empty())\n {\n ERR(\"Malformed line: %s\\n\", buffer.c_str());\n return 0;\n }\n\n if(command == \"\/description\")\n istr >> Description;\n else if(command == \"\/version\")\n {\n istr >> Version;\n if(!istr.eof() && !std::isspace(istr.peek()))\n {\n ERR(\"Extra junk after version: %s\\n\", buffer.c_str()+istr.tellg());\n return 0;\n }\n if(Version != 3)\n {\n ERR(\"Unsupported version: %u\\n\", Version);\n return 0;\n }\n }\n else if(command == \"\/dec\/chan_mask\")\n {\n istr >> std::hex >> ChanMask >> std::dec;\n if(!istr.eof() && !std::isspace(istr.peek()))\n {\n ERR(\"Extra junk after mask: %s\\n\", buffer.c_str()+istr.tellg());\n return 0;\n }\n }\n else if(command == \"\/dec\/freq_bands\")\n {\n istr >> FreqBands;\n if(!istr.eof() && !std::isspace(istr.peek()))\n {\n ERR(\"Extra junk after freq_bands: %s\\n\", buffer.c_str()+istr.tellg());\n return 0;\n }\n if(FreqBands != 1 && FreqBands != 2)\n {\n ERR(\"Invalid freq_bands value: %u\\n\", FreqBands);\n return 0;\n }\n }\n else if(command == \"\/dec\/speakers\")\n {\n istr >> NumSpeakers;\n if(!istr.eof() && !std::isspace(istr.peek()))\n {\n ERR(\"Extra junk after speakers: %s\\n\", buffer.c_str()+istr.tellg());\n return 0;\n }\n if(NumSpeakers > MAX_OUTPUT_CHANNELS)\n {\n ERR(\"Unsupported speaker count: %u\\n\", NumSpeakers);\n return 0;\n }\n }\n else if(command == \"\/dec\/coeff_scale\")\n {\n std::string scale = read_word(istr);\n if(scale == \"n3d\") CoeffScale = AmbDecScale::N3D;\n else if(scale == \"sn3d\") CoeffScale = AmbDecScale::SN3D;\n else if(scale == \"fuma\") CoeffScale = AmbDecScale::FuMa;\n else\n {\n ERR(\"Unsupported coeff scale: %s\\n\", scale.c_str());\n return 0;\n }\n }\n else if(command == \"\/opt\/xover_freq\")\n {\n istr >> XOverFreq;\n if(!istr.eof() && !std::isspace(istr.peek()))\n {\n ERR(\"Extra junk after xover_freq: %s\\n\", buffer.c_str()+istr.tellg());\n return 0;\n }\n }\n else if(command == \"\/opt\/xover_ratio\")\n {\n istr >> XOverRatio;\n if(!istr.eof() && !std::isspace(istr.peek()))\n {\n ERR(\"Extra junk after xover_ratio: %s\\n\", buffer.c_str()+istr.tellg());\n return 0;\n }\n }\n else if(command == \"\/opt\/input_scale\" || command == \"\/opt\/nfeff_comp\" ||\n command == \"\/opt\/delay_comp\" || command == \"\/opt\/level_comp\")\n {\n \/* Unused *\/\n read_word(istr);\n }\n else if(command == \"\/speakers\/{\")\n {\n std::streamsize endpos{istr.tellg()};\n if(!is_at_end(buffer, endpos))\n {\n ERR(\"Unexpected junk on line: %s\\n\", buffer.c_str()+endpos);\n return 0;\n }\n buffer.clear();\n\n if(!load_ambdec_speakers(this, f, buffer))\n return 0;\n\n if(!read_clipped_line(f, buffer))\n {\n ERR(\"Unexpected end of file\\n\");\n return 0;\n }\n std::istringstream istr2{buffer};\n std::string endmark{read_word(istr2)};\n if(endmark != \"\/}\")\n {\n ERR(\"Expected \/} after speaker definitions, got %s\\n\", endmark.c_str());\n return 0;\n }\n istr.swap(istr2);\n }\n else if(command == \"\/lfmatrix\/{\" || command == \"\/hfmatrix\/{\" || command == \"\/matrix\/{\")\n {\n std::streamsize endpos{istr.tellg()};\n if(!is_at_end(buffer, endpos))\n {\n ERR(\"Unexpected junk on line: %s\\n\", buffer.c_str()+endpos);\n return 0;\n }\n buffer.clear();\n\n if(FreqBands == 1)\n {\n if(command != \"\/matrix\/{\")\n {\n ERR(\"Unexpected \\\"%s\\\" type for a single-band decoder\\n\", command.c_str());\n return 0;\n }\n if(!load_ambdec_matrix(HFOrderGain, HFMatrix, NumSpeakers, f, buffer))\n return 0;\n }\n else\n {\n if(command == \"\/lfmatrix\/{\")\n {\n if(!load_ambdec_matrix(LFOrderGain, LFMatrix, NumSpeakers, f, buffer))\n return 0;\n }\n else if(command == \"\/hfmatrix\/{\")\n {\n if(!load_ambdec_matrix(HFOrderGain, HFMatrix, NumSpeakers, f, buffer))\n return 0;\n }\n else\n {\n ERR(\"Unexpected \\\"%s\\\" type for a dual-band decoder\\n\", command.c_str());\n return 0;\n }\n }\n\n if(!read_clipped_line(f, buffer))\n {\n ERR(\"Unexpected end of file\\n\");\n return 0;\n }\n std::istringstream istr2{buffer};\n std::string endmark{read_word(istr2)};\n if(endmark != \"\/}\")\n {\n ERR(\"Expected \/} after matrix definitions, got %s\\n\", endmark.c_str());\n return 0;\n }\n istr.swap(istr2);\n }\n else if(command == \"\/end\")\n {\n std::streamsize endpos{istr.tellg()};\n if(!is_at_end(buffer, endpos))\n {\n ERR(\"Unexpected junk on end: %s\\n\", buffer.c_str()+endpos);\n return 0;\n }\n\n return 1;\n }\n else\n {\n ERR(\"Unexpected command: %s\\n\", command.c_str());\n return 0;\n }\n\n istr.clear();\n std::streamsize endpos{istr.tellg()};\n if(!is_at_end(buffer, endpos))\n {\n ERR(\"Unexpected junk on line: %s\\n\", buffer.c_str()+endpos);\n return 0;\n }\n buffer.clear();\n }\n ERR(\"Unexpected end of file\\n\");\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"app\/l10n_util.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/chromeos\/login\/account_screen.h\"\n#include \"chrome\/browser\/chromeos\/login\/eula_view.h\"\n#include \"chrome\/browser\/chromeos\/login\/language_switch_menu.h\"\n#include \"chrome\/browser\/chromeos\/login\/login_screen.h\"\n#include \"chrome\/browser\/chromeos\/login\/mock_update_screen.h\"\n#include \"chrome\/browser\/chromeos\/login\/network_screen.h\"\n#include \"chrome\/browser\/chromeos\/login\/network_selection_view.h\"\n#include \"chrome\/browser\/chromeos\/login\/user_image_screen.h\"\n#include \"chrome\/browser\/chromeos\/login\/wizard_controller.h\"\n#include \"chrome\/browser\/chromeos\/login\/wizard_in_process_browser_test.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"grit\/generated_resources.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"unicode\/locid.h\"\n#include \"views\/accelerator.h\"\n\nnamespace {\n\ntemplate \nclass MockOutShowHide : public T {\n public:\n template MockOutShowHide(P p) : T(p) {}\n template MockOutShowHide(P1 p1, P2 p2) : T(p1, p2) {}\n MOCK_METHOD0(Show, void());\n MOCK_METHOD0(Hide, void());\n};\n\ntemplate \nstruct CreateMockWizardScreenHelper {\n static MockOutShowHide* Create(WizardController* wizard);\n};\n\ntemplate MockOutShowHide*\nCreateMockWizardScreenHelper::Create(WizardController* wizard) {\n return new MockOutShowHide(wizard);\n}\n\ntemplate <> MockOutShowHide*\nCreateMockWizardScreenHelper::Create(\n WizardController* wizard) {\n return new MockOutShowHide(wizard);\n}\n\n#define MOCK(mock_var, screen_name, mocked_class) \\\n mock_var = CreateMockWizardScreenHelper::Create(controller()); \\\n controller()->screen_name.reset(mock_var); \\\n EXPECT_CALL(*mock_var, Show()).Times(0); \\\n EXPECT_CALL(*mock_var, Hide()).Times(0);\n\n} \/\/ namespace\n\nclass WizardControllerTest : public chromeos::WizardInProcessBrowserTest {\n protected:\n WizardControllerTest() : chromeos::WizardInProcessBrowserTest(\n WizardController::kTestNoScreenName) {}\n virtual ~WizardControllerTest() {}\n\n private:\n DISALLOW_COPY_AND_ASSIGN(WizardControllerTest);\n};\n\nIN_PROC_BROWSER_TEST_F(WizardControllerTest, SwitchLanguage) {\n WizardController* const wizard = controller();\n ASSERT_TRUE(wizard != NULL);\n wizard->ShowFirstScreen(WizardController::kNetworkScreenName);\n views::View* current_screen = wizard->contents();\n ASSERT_TRUE(current_screen != NULL);\n\n \/\/ Checking the default locale. Provided that the profile is cleared in SetUp.\n EXPECT_EQ(\"en-US\", g_browser_process->GetApplicationLocale());\n EXPECT_STREQ(\"en\", icu::Locale::getDefault().getLanguage());\n EXPECT_FALSE(base::i18n::IsRTL());\n const std::wstring en_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE);\n\n chromeos::LanguageSwitchMenu::SwitchLanguage(\"fr\");\n EXPECT_EQ(\"fr\", g_browser_process->GetApplicationLocale());\n EXPECT_STREQ(\"fr\", icu::Locale::getDefault().getLanguage());\n EXPECT_FALSE(base::i18n::IsRTL());\n const std::wstring fr_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE);\n\n EXPECT_NE(en_str, fr_str);\n\n chromeos::LanguageSwitchMenu::SwitchLanguage(\"ar\");\n EXPECT_EQ(\"ar\", g_browser_process->GetApplicationLocale());\n EXPECT_STREQ(\"ar\", icu::Locale::getDefault().getLanguage());\n EXPECT_TRUE(base::i18n::IsRTL());\n const std::wstring ar_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE);\n\n EXPECT_NE(fr_str, ar_str);\n}\n\nclass WizardControllerFlowTest : public WizardControllerTest {\n protected:\n WizardControllerFlowTest() {}\n \/\/ Overriden from InProcessBrowserTest:\n virtual Browser* CreateBrowser(Profile* profile) {\n Browser* ret = WizardControllerTest::CreateBrowser(profile);\n\n \/\/ Make sure that OOBE is run as an \"official\" build.\n WizardController::default_controller()->is_official_build_ = true;\n\n \/\/ Set up the mocks for all screens.\n MOCK(mock_account_screen_, account_screen_, chromeos::AccountScreen);\n MOCK(mock_login_screen_, login_screen_, chromeos::LoginScreen);\n MOCK(mock_network_screen_, network_screen_, chromeos::NetworkScreen);\n MOCK(mock_update_screen_, update_screen_, MockUpdateScreen);\n MOCK(mock_eula_screen_, eula_screen_, chromeos::EulaScreen);\n\n \/\/ Switch to the initial screen.\n EXPECT_EQ(NULL, controller()->current_screen());\n EXPECT_CALL(*mock_network_screen_, Show()).Times(1);\n controller()->ShowFirstScreen(WizardController::kNetworkScreenName);\n\n return ret;\n }\n\n MockOutShowHide* mock_account_screen_;\n MockOutShowHide* mock_login_screen_;\n MockOutShowHide* mock_network_screen_;\n MockOutShowHide* mock_update_screen_;\n MockOutShowHide* mock_eula_screen_;\n\n private:\n DISALLOW_COPY_AND_ASSIGN(WizardControllerFlowTest);\n};\n\nIN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowMain) {\n EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_eula_screen_, Show()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED);\n\n EXPECT_EQ(controller()->GetEulaScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_eula_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(1);\n EXPECT_CALL(*mock_update_screen_, Show()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::EULA_ACCEPTED);\n\n EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_update_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_eula_screen_, Show()).Times(0);\n EXPECT_CALL(*mock_login_screen_, Show()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::UPDATE_INSTALLED);\n\n EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_login_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_account_screen_, Show()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::LOGIN_CREATE_ACCOUNT);\n\n EXPECT_EQ(controller()->GetAccountScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_account_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_login_screen_, Show()).Times(1);\n EXPECT_CALL(*mock_login_screen_, Hide()).Times(0); \/\/ last transition\n controller()->OnExit(chromeos::ScreenObserver::ACCOUNT_CREATED);\n\n EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen());\n}\n\nIN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowErrorUpdate) {\n EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(0);\n EXPECT_CALL(*mock_eula_screen_, Show()).Times(1);\n EXPECT_CALL(*mock_update_screen_, Show()).Times(0);\n EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED);\n\n EXPECT_EQ(controller()->GetEulaScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_eula_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(1);\n EXPECT_CALL(*mock_update_screen_, Show()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::EULA_ACCEPTED);\n\n EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_update_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_eula_screen_, Show()).Times(0);\n EXPECT_CALL(*mock_eula_screen_, Hide()).Times(0); \/\/ last transition\n EXPECT_CALL(*mock_login_screen_, Show()).Times(1);\n controller()->OnExit(\n chromeos::ScreenObserver::UPDATE_ERROR_UPDATING);\n\n EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen());\n}\n\nIN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowEulaDeclined) {\n EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(0);\n EXPECT_CALL(*mock_eula_screen_, Show()).Times(1);\n EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED);\n\n EXPECT_EQ(controller()->GetEulaScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_eula_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_network_screen_, Show()).Times(1);\n EXPECT_CALL(*mock_network_screen_, Hide()).Times(0); \/\/ last transition\n controller()->OnExit(chromeos::ScreenObserver::EULA_BACK);\n\n EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());\n}\n\nIN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowErrorNetwork) {\n EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_login_screen_, Show()).Times(1);\n EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::NETWORK_OFFLINE);\n EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen());\n}\n\n#if defined(OFFICIAL_BUILD)\n\/\/ This test is supposed to fail on official test.\n#define MAYBE_Accelerators DISABLED_Accelerators\n#else\n#define MAYBE_Accelerators Accelerators\n#endif\n\nIN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, MAYBE_Accelerators) {\n EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());\n\n views::FocusManager* focus_manager =\n controller()->contents()->GetFocusManager();\n views::Accelerator accel_account_screen(app::VKEY_A, false, true, true);\n views::Accelerator accel_login_screen(app::VKEY_L, false, true, true);\n views::Accelerator accel_network_screen(app::VKEY_N, false, true, true);\n views::Accelerator accel_update_screen(app::VKEY_U, false, true, true);\n views::Accelerator accel_image_screen(app::VKEY_I, false, true, true);\n views::Accelerator accel_eula_screen(app::VKEY_E, false, true, true);\n\n EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_account_screen_, Show()).Times(1);\n EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_account_screen));\n EXPECT_EQ(controller()->GetAccountScreen(), controller()->current_screen());\n\n focus_manager = controller()->contents()->GetFocusManager();\n EXPECT_CALL(*mock_account_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_login_screen_, Show()).Times(1);\n EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_login_screen));\n EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen());\n\n focus_manager = controller()->contents()->GetFocusManager();\n EXPECT_CALL(*mock_login_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_network_screen_, Show()).Times(1);\n EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_network_screen));\n EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());\n\n focus_manager = controller()->contents()->GetFocusManager();\n EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_update_screen_, Show()).Times(1);\n EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_update_screen));\n EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen());\n\n focus_manager = controller()->contents()->GetFocusManager();\n EXPECT_CALL(*mock_update_screen_, Hide()).Times(1);\n EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_image_screen));\n EXPECT_EQ(controller()->GetUserImageScreen(), controller()->current_screen());\n\n focus_manager = controller()->contents()->GetFocusManager();\n EXPECT_CALL(*mock_eula_screen_, Show()).Times(1);\n EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_eula_screen));\n EXPECT_EQ(controller()->GetEulaScreen(), controller()->current_screen());\n}\n\nCOMPILE_ASSERT(chromeos::ScreenObserver::EXIT_CODES_COUNT == 18,\n add_tests_for_new_control_flow_you_just_introduced);\nMark failing unittest to FAILS.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"app\/l10n_util.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/chromeos\/login\/account_screen.h\"\n#include \"chrome\/browser\/chromeos\/login\/eula_view.h\"\n#include \"chrome\/browser\/chromeos\/login\/language_switch_menu.h\"\n#include \"chrome\/browser\/chromeos\/login\/login_screen.h\"\n#include \"chrome\/browser\/chromeos\/login\/mock_update_screen.h\"\n#include \"chrome\/browser\/chromeos\/login\/network_screen.h\"\n#include \"chrome\/browser\/chromeos\/login\/network_selection_view.h\"\n#include \"chrome\/browser\/chromeos\/login\/user_image_screen.h\"\n#include \"chrome\/browser\/chromeos\/login\/wizard_controller.h\"\n#include \"chrome\/browser\/chromeos\/login\/wizard_in_process_browser_test.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"grit\/generated_resources.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"unicode\/locid.h\"\n#include \"views\/accelerator.h\"\n\nnamespace {\n\ntemplate \nclass MockOutShowHide : public T {\n public:\n template MockOutShowHide(P p) : T(p) {}\n template MockOutShowHide(P1 p1, P2 p2) : T(p1, p2) {}\n MOCK_METHOD0(Show, void());\n MOCK_METHOD0(Hide, void());\n};\n\ntemplate \nstruct CreateMockWizardScreenHelper {\n static MockOutShowHide* Create(WizardController* wizard);\n};\n\ntemplate MockOutShowHide*\nCreateMockWizardScreenHelper::Create(WizardController* wizard) {\n return new MockOutShowHide(wizard);\n}\n\ntemplate <> MockOutShowHide*\nCreateMockWizardScreenHelper::Create(\n WizardController* wizard) {\n return new MockOutShowHide(wizard);\n}\n\n#define MOCK(mock_var, screen_name, mocked_class) \\\n mock_var = CreateMockWizardScreenHelper::Create(controller()); \\\n controller()->screen_name.reset(mock_var); \\\n EXPECT_CALL(*mock_var, Show()).Times(0); \\\n EXPECT_CALL(*mock_var, Hide()).Times(0);\n\n} \/\/ namespace\n\nclass WizardControllerTest : public chromeos::WizardInProcessBrowserTest {\n protected:\n WizardControllerTest() : chromeos::WizardInProcessBrowserTest(\n WizardController::kTestNoScreenName) {}\n virtual ~WizardControllerTest() {}\n\n private:\n DISALLOW_COPY_AND_ASSIGN(WizardControllerTest);\n};\n\n\/\/ TODO(zelidrag): Need to revisit this once translation for fr and ar is\n\/\/ complete. See http:\/\/crosbug.com\/8974\nIN_PROC_BROWSER_TEST_F(WizardControllerTest, FAILS_SwitchLanguage) {\n WizardController* const wizard = controller();\n ASSERT_TRUE(wizard != NULL);\n wizard->ShowFirstScreen(WizardController::kNetworkScreenName);\n views::View* current_screen = wizard->contents();\n ASSERT_TRUE(current_screen != NULL);\n\n \/\/ Checking the default locale. Provided that the profile is cleared in SetUp.\n EXPECT_EQ(\"en-US\", g_browser_process->GetApplicationLocale());\n EXPECT_STREQ(\"en\", icu::Locale::getDefault().getLanguage());\n EXPECT_FALSE(base::i18n::IsRTL());\n const std::wstring en_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE);\n\n chromeos::LanguageSwitchMenu::SwitchLanguage(\"fr\");\n EXPECT_EQ(\"fr\", g_browser_process->GetApplicationLocale());\n EXPECT_STREQ(\"fr\", icu::Locale::getDefault().getLanguage());\n EXPECT_FALSE(base::i18n::IsRTL());\n const std::wstring fr_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE);\n\n EXPECT_NE(en_str, fr_str);\n\n chromeos::LanguageSwitchMenu::SwitchLanguage(\"ar\");\n EXPECT_EQ(\"ar\", g_browser_process->GetApplicationLocale());\n EXPECT_STREQ(\"ar\", icu::Locale::getDefault().getLanguage());\n EXPECT_TRUE(base::i18n::IsRTL());\n const std::wstring ar_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE);\n\n EXPECT_NE(fr_str, ar_str);\n}\n\nclass WizardControllerFlowTest : public WizardControllerTest {\n protected:\n WizardControllerFlowTest() {}\n \/\/ Overriden from InProcessBrowserTest:\n virtual Browser* CreateBrowser(Profile* profile) {\n Browser* ret = WizardControllerTest::CreateBrowser(profile);\n\n \/\/ Make sure that OOBE is run as an \"official\" build.\n WizardController::default_controller()->is_official_build_ = true;\n\n \/\/ Set up the mocks for all screens.\n MOCK(mock_account_screen_, account_screen_, chromeos::AccountScreen);\n MOCK(mock_login_screen_, login_screen_, chromeos::LoginScreen);\n MOCK(mock_network_screen_, network_screen_, chromeos::NetworkScreen);\n MOCK(mock_update_screen_, update_screen_, MockUpdateScreen);\n MOCK(mock_eula_screen_, eula_screen_, chromeos::EulaScreen);\n\n \/\/ Switch to the initial screen.\n EXPECT_EQ(NULL, controller()->current_screen());\n EXPECT_CALL(*mock_network_screen_, Show()).Times(1);\n controller()->ShowFirstScreen(WizardController::kNetworkScreenName);\n\n return ret;\n }\n\n MockOutShowHide* mock_account_screen_;\n MockOutShowHide* mock_login_screen_;\n MockOutShowHide* mock_network_screen_;\n MockOutShowHide* mock_update_screen_;\n MockOutShowHide* mock_eula_screen_;\n\n private:\n DISALLOW_COPY_AND_ASSIGN(WizardControllerFlowTest);\n};\n\nIN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowMain) {\n EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_eula_screen_, Show()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED);\n\n EXPECT_EQ(controller()->GetEulaScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_eula_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(1);\n EXPECT_CALL(*mock_update_screen_, Show()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::EULA_ACCEPTED);\n\n EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_update_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_eula_screen_, Show()).Times(0);\n EXPECT_CALL(*mock_login_screen_, Show()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::UPDATE_INSTALLED);\n\n EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_login_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_account_screen_, Show()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::LOGIN_CREATE_ACCOUNT);\n\n EXPECT_EQ(controller()->GetAccountScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_account_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_login_screen_, Show()).Times(1);\n EXPECT_CALL(*mock_login_screen_, Hide()).Times(0); \/\/ last transition\n controller()->OnExit(chromeos::ScreenObserver::ACCOUNT_CREATED);\n\n EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen());\n}\n\nIN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowErrorUpdate) {\n EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(0);\n EXPECT_CALL(*mock_eula_screen_, Show()).Times(1);\n EXPECT_CALL(*mock_update_screen_, Show()).Times(0);\n EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED);\n\n EXPECT_EQ(controller()->GetEulaScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_eula_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(1);\n EXPECT_CALL(*mock_update_screen_, Show()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::EULA_ACCEPTED);\n\n EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_update_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_eula_screen_, Show()).Times(0);\n EXPECT_CALL(*mock_eula_screen_, Hide()).Times(0); \/\/ last transition\n EXPECT_CALL(*mock_login_screen_, Show()).Times(1);\n controller()->OnExit(\n chromeos::ScreenObserver::UPDATE_ERROR_UPDATING);\n\n EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen());\n}\n\nIN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowEulaDeclined) {\n EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(0);\n EXPECT_CALL(*mock_eula_screen_, Show()).Times(1);\n EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED);\n\n EXPECT_EQ(controller()->GetEulaScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_eula_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_network_screen_, Show()).Times(1);\n EXPECT_CALL(*mock_network_screen_, Hide()).Times(0); \/\/ last transition\n controller()->OnExit(chromeos::ScreenObserver::EULA_BACK);\n\n EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());\n}\n\nIN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowErrorNetwork) {\n EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_login_screen_, Show()).Times(1);\n EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::NETWORK_OFFLINE);\n EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen());\n}\n\n#if defined(OFFICIAL_BUILD)\n\/\/ This test is supposed to fail on official test.\n#define MAYBE_Accelerators DISABLED_Accelerators\n#else\n#define MAYBE_Accelerators Accelerators\n#endif\n\nIN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, MAYBE_Accelerators) {\n EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());\n\n views::FocusManager* focus_manager =\n controller()->contents()->GetFocusManager();\n views::Accelerator accel_account_screen(app::VKEY_A, false, true, true);\n views::Accelerator accel_login_screen(app::VKEY_L, false, true, true);\n views::Accelerator accel_network_screen(app::VKEY_N, false, true, true);\n views::Accelerator accel_update_screen(app::VKEY_U, false, true, true);\n views::Accelerator accel_image_screen(app::VKEY_I, false, true, true);\n views::Accelerator accel_eula_screen(app::VKEY_E, false, true, true);\n\n EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_account_screen_, Show()).Times(1);\n EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_account_screen));\n EXPECT_EQ(controller()->GetAccountScreen(), controller()->current_screen());\n\n focus_manager = controller()->contents()->GetFocusManager();\n EXPECT_CALL(*mock_account_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_login_screen_, Show()).Times(1);\n EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_login_screen));\n EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen());\n\n focus_manager = controller()->contents()->GetFocusManager();\n EXPECT_CALL(*mock_login_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_network_screen_, Show()).Times(1);\n EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_network_screen));\n EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());\n\n focus_manager = controller()->contents()->GetFocusManager();\n EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_update_screen_, Show()).Times(1);\n EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_update_screen));\n EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen());\n\n focus_manager = controller()->contents()->GetFocusManager();\n EXPECT_CALL(*mock_update_screen_, Hide()).Times(1);\n EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_image_screen));\n EXPECT_EQ(controller()->GetUserImageScreen(), controller()->current_screen());\n\n focus_manager = controller()->contents()->GetFocusManager();\n EXPECT_CALL(*mock_eula_screen_, Show()).Times(1);\n EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_eula_screen));\n EXPECT_EQ(controller()->GetEulaScreen(), controller()->current_screen());\n}\n\nCOMPILE_ASSERT(chromeos::ScreenObserver::EXIT_CODES_COUNT == 18,\n add_tests_for_new_control_flow_you_just_introduced);\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/process_util.h\"\n#include \"base\/sys_string_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/extensions\/component_loader.h\"\n#include \"chrome\/browser\/extensions\/extension_browsertest.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/browser\/ui\/omnibox\/location_bar.h\"\n#include \"chrome\/browser\/ui\/omnibox\/omnibox_view.h\"\n#include \"chrome\/browser\/ui\/tabs\/tab_strip_model.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/testing_profile.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/browser\/navigation_controller.h\"\n#include \"content\/public\/browser\/navigation_entry.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"extensions\/common\/constants.h\"\n#include \"googleurl\/src\/gurl.h\"\n\nusing content::NavigationEntry;\n\nclass ExtensionURLRewriteBrowserTest : public ExtensionBrowserTest {\n public:\n virtual void SetUp() OVERRIDE {\n extensions::ComponentLoader::EnableBackgroundExtensionsForTesting();\n ExtensionBrowserTest::SetUp();\n }\n\n protected:\n std::string GetLocationBarText() const {\n return UTF16ToUTF8(\n browser()->window()->GetLocationBar()->GetLocationEntry()->GetText());\n }\n\n GURL GetLocationBarTextAsURL() const {\n return GURL(GetLocationBarText());\n }\n\n content::NavigationController* GetNavigationController() const {\n return &browser()->tab_strip_model()->GetActiveWebContents()->\n GetController();\n }\n\n NavigationEntry* GetNavigationEntry() const {\n return GetNavigationController()->GetActiveEntry();\n }\n\n base::FilePath GetTestExtensionPath(const char* extension_name) const {\n return test_data_dir_.AppendASCII(\"browsertest\/url_rewrite\/\").\n AppendASCII(extension_name);\n }\n\n \/\/ Navigates to |url| and tests that the location bar and the |virtual_url|\n \/\/ correspond to |url|, while the real URL of the navigation entry uses the\n \/\/ chrome-extension:\/\/ scheme.\n void TestExtensionURLOverride(const GURL& url) {\n ui_test_utils::NavigateToURL(browser(), url);\n EXPECT_EQ(url, GetLocationBarTextAsURL());\n EXPECT_EQ(url, GetNavigationEntry()->GetVirtualURL());\n EXPECT_TRUE(\n GetNavigationEntry()->GetURL().SchemeIs(extensions::kExtensionScheme));\n }\n\n \/\/ Navigates to |url| and tests that the location bar is empty while the\n \/\/ |virtual_url| is the same as |url|.\n void TestURLNotShown(const GURL& url) {\n ui_test_utils::NavigateToURL(browser(), url);\n EXPECT_EQ(\"\", GetLocationBarText());\n EXPECT_EQ(url, GetNavigationEntry()->GetVirtualURL());\n }\n};\n\nIN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, NewTabPageURL) {\n \/\/ Navigate to chrome:\/\/newtab and check that the location bar text is blank.\n GURL url(chrome::kChromeUINewTabURL);\n TestURLNotShown(url);\n \/\/ Check that the actual URL corresponds to chrome:\/\/newtab.\n EXPECT_EQ(url, GetNavigationEntry()->GetURL());\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, NewTabPageURLOverride) {\n \/\/ Load an extension to override the NTP and check that the location bar text\n \/\/ is blank after navigating to chrome:\/\/newtab.\n LoadExtension(GetTestExtensionPath(\"newtab\"));\n TestURLNotShown(GURL(chrome::kChromeUINewTabURL));\n \/\/ Check that the internal URL uses the chrome-extension:\/\/ scheme.\n EXPECT_TRUE(GetNavigationEntry()->GetURL().SchemeIs(\n extensions::kExtensionScheme));\n}\n\n\/\/ TODO(linux_aura) http:\/\/crbug.com\/163931\n#if defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(USE_AURA)\n#define MAYBE_BookmarksURL DISABLED_BookmarksURL\n#else\n#define MAYBE_BookmarksURL BookmarksURL\n#endif\nIN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, MAYBE_BookmarksURL) {\n \/\/ Navigate to chrome:\/\/bookmarks and check that the location bar URL is\n \/\/ what was entered and the internal URL uses the chrome-extension:\/\/ scheme.\n TestExtensionURLOverride(GURL(chrome::kChromeUIBookmarksURL));\n}\n\n#if defined(FILE_MANAGER_EXTENSION)\nIN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, FileManagerURL) {\n \/\/ Navigate to chrome:\/\/files and check that the location bar URL is\n \/\/ what was entered and the internal URL uses the chrome-extension:\/\/ scheme.\n TestExtensionURLOverride(GURL(chrome::kChromeUIFileManagerURL));\n}\n#endif\n\nIN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, BookmarksURLWithRef) {\n \/\/ Navigate to chrome:\/\/bookmarks\/#1 and check that the location bar URL is\n \/\/ what was entered and the internal URL uses the chrome-extension:\/\/ scheme.\n GURL url_with_ref(chrome::kChromeUIBookmarksURL + std::string(\"#1\"));\n TestExtensionURLOverride(url_with_ref);\n}\n\n\/\/ Disabled for flakiness: crbug.com\/176332\nIN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest,\n DISABLED_BookmarksURLOverride) {\n \/\/ Load an extension that overrides chrome:\/\/bookmarks.\n LoadExtension(GetTestExtensionPath(\"bookmarks\"));\n \/\/ Navigate to chrome:\/\/bookmarks and check that the location bar URL is what\n \/\/ was entered and the internal URL uses the chrome-extension:\/\/ scheme.\n TestExtensionURLOverride(GURL(chrome::kChromeUIBookmarksURL));\n}\nAttempt to fix flakyness of ExtensionURLRewriteBrowserTest.BookmarksURL.\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/process_util.h\"\n#include \"base\/sys_string_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/extensions\/component_loader.h\"\n#include \"chrome\/browser\/extensions\/extension_browsertest.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/browser\/ui\/omnibox\/location_bar.h\"\n#include \"chrome\/browser\/ui\/omnibox\/omnibox_view.h\"\n#include \"chrome\/browser\/ui\/tabs\/tab_strip_model.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/testing_profile.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/browser\/navigation_controller.h\"\n#include \"content\/public\/browser\/navigation_entry.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"extensions\/common\/constants.h\"\n#include \"googleurl\/src\/gurl.h\"\n\nusing content::NavigationEntry;\n\nclass ExtensionURLRewriteBrowserTest : public ExtensionBrowserTest {\n public:\n virtual void SetUp() OVERRIDE {\n extensions::ComponentLoader::EnableBackgroundExtensionsForTesting();\n ExtensionBrowserTest::SetUp();\n }\n\n protected:\n std::string GetLocationBarText() const {\n return UTF16ToUTF8(\n browser()->window()->GetLocationBar()->GetLocationEntry()->GetText());\n }\n\n GURL GetLocationBarTextAsURL() const {\n return GURL(GetLocationBarText());\n }\n\n content::NavigationController* GetNavigationController() const {\n return &browser()->tab_strip_model()->GetActiveWebContents()->\n GetController();\n }\n\n NavigationEntry* GetNavigationEntry() const {\n return GetNavigationController()->GetActiveEntry();\n }\n\n base::FilePath GetTestExtensionPath(const char* extension_name) const {\n return test_data_dir_.AppendASCII(\"browsertest\/url_rewrite\/\").\n AppendASCII(extension_name);\n }\n\n \/\/ Navigates to |url| and tests that the location bar and the |virtual_url|\n \/\/ correspond to |url|, while the real URL of the navigation entry uses the\n \/\/ chrome-extension:\/\/ scheme.\n void TestExtensionURLOverride(const GURL& url) {\n ui_test_utils::NavigateToURL(browser(), url);\n EXPECT_EQ(url, GetLocationBarTextAsURL());\n EXPECT_EQ(url, GetNavigationEntry()->GetVirtualURL());\n EXPECT_TRUE(\n GetNavigationEntry()->GetURL().SchemeIs(extensions::kExtensionScheme));\n }\n\n \/\/ Navigates to |url| and tests that the location bar is empty while the\n \/\/ |virtual_url| is the same as |url|.\n void TestURLNotShown(const GURL& url) {\n ui_test_utils::NavigateToURL(browser(), url);\n EXPECT_EQ(\"\", GetLocationBarText());\n EXPECT_EQ(url, GetNavigationEntry()->GetVirtualURL());\n }\n};\n\nIN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, NewTabPageURL) {\n \/\/ Navigate to chrome:\/\/newtab and check that the location bar text is blank.\n GURL url(chrome::kChromeUINewTabURL);\n TestURLNotShown(url);\n \/\/ Check that the actual URL corresponds to chrome:\/\/newtab.\n EXPECT_EQ(url, GetNavigationEntry()->GetURL());\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, NewTabPageURLOverride) {\n \/\/ Load an extension to override the NTP and check that the location bar text\n \/\/ is blank after navigating to chrome:\/\/newtab.\n ASSERT_TRUE(LoadExtension(GetTestExtensionPath(\"newtab\")));\n TestURLNotShown(GURL(chrome::kChromeUINewTabURL));\n \/\/ Check that the internal URL uses the chrome-extension:\/\/ scheme.\n EXPECT_TRUE(GetNavigationEntry()->GetURL().SchemeIs(\n extensions::kExtensionScheme));\n}\n\n\/\/ TODO(linux_aura) http:\/\/crbug.com\/163931\n#if defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(USE_AURA)\n#define MAYBE_BookmarksURL DISABLED_BookmarksURL\n#else\n#define MAYBE_BookmarksURL BookmarksURL\n#endif\nIN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, MAYBE_BookmarksURL) {\n \/\/ Navigate to chrome:\/\/bookmarks and check that the location bar URL is\n \/\/ what was entered and the internal URL uses the chrome-extension:\/\/ scheme.\n const GURL bookmarks_url(chrome::kChromeUIBookmarksURL);\n ui_test_utils::NavigateToURL(browser(), bookmarks_url);\n \/\/ The default chrome:\/\/bookmarks implementation will append \/#1 to the URL\n \/\/ once loaded. Use |GetWithEmptyPath()| to avoid flakyness.\n EXPECT_EQ(bookmarks_url, GetLocationBarTextAsURL().GetWithEmptyPath());\n NavigationEntry* navigation = GetNavigationEntry();\n EXPECT_EQ(bookmarks_url, navigation->GetVirtualURL().GetWithEmptyPath());\n EXPECT_TRUE(navigation->GetURL().SchemeIs(extensions::kExtensionScheme));\n}\n\n#if defined(FILE_MANAGER_EXTENSION)\nIN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, FileManagerURL) {\n \/\/ Navigate to chrome:\/\/files and check that the location bar URL is\n \/\/ what was entered and the internal URL uses the chrome-extension:\/\/ scheme.\n TestExtensionURLOverride(GURL(chrome::kChromeUIFileManagerURL));\n}\n#endif\n\nIN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, BookmarksURLWithRef) {\n \/\/ Navigate to chrome:\/\/bookmarks\/#1 and check that the location bar URL is\n \/\/ what was entered and the internal URL uses the chrome-extension:\/\/ scheme.\n GURL url_with_ref(chrome::kChromeUIBookmarksURL + std::string(\"#1\"));\n TestExtensionURLOverride(url_with_ref);\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, BookmarksURLOverride) {\n \/\/ Load an extension that overrides chrome:\/\/bookmarks.\n ASSERT_TRUE(LoadExtension(GetTestExtensionPath(\"bookmarks\")));\n \/\/ Navigate to chrome:\/\/bookmarks and check that the location bar URL is what\n \/\/ was entered and the internal URL uses the chrome-extension:\/\/ scheme.\n TestExtensionURLOverride(GURL(chrome::kChromeUIBookmarksURL));\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\nint main(int argc, char** argv) {\n\tstd::vector some_values;\n\t\n\tsome_values.push_back(10);\n\tconst char* c_str = \"Hello there!\";\n\tsome_values.push_back(c_str);\n\tsome_values.push_back(std::string(\"Wow!\"));\n\tstd::string& s = boost::any_cast(some_values.back());\n\ts += \" That is great!\\n\";\n\tstd::cout << s;\n\treturn 0;\n}'Any' example updated.#include \n#include \n#include \n#include \n#include \n\n\nint main(int argc, char** argv) {\n\n\t{\n\t\tboost::any any_value = 10;\n\t\tstd::cout << boost::any_cast(any_value) << std::endl;\n\t\tint *pointer = boost::any_cast(&any_value);\n\t\tstd::cout << *pointer << std::endl;\n\n\t\tany_value = 2.34;\n\t\tstd::cout << boost::any_cast(any_value) << std::endl;\n\n\t\tany_value = false;\n\t\tstd::cout << std::boolalpha << boost::any_cast(any_value) << std::endl;\n\t}\n\n\t{\n\t\tboost::any any_value = 10;\n\t\tassert(any_value.type() == typeid(int));\n\n\t\tboost::any empty_value;\n\t\tassert(empty_value.empty());\n\t}\n\n\treturn 0;\n}<|endoftext|>"} {"text":"#ifndef STAN_MATH_OPENCL_TRI_INVERSE_HPP\n#define STAN_MATH_OPENCL_TRI_INVERSE_HPP\n\n#ifdef STAN_OPENCL\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\/** \\ingroup opencl\n * Computes the inverse of a triangular matrix\n *\n * For a full guide to how this works and fits into Cholesky decompositions,\n * see the reference report\n * \n * here<\/a> and kernel doc\n * here<\/a>.\n *\n * @param A matrix on the OpenCL device\n * @return the inverse of A\n *\n * @throw std::invalid_argument<\/code> if the matrix\n * is not square\n *\/\ntemplate >\ninline matrix_cl tri_inverse(const matrix_cl& A) {\n \/\/ if the triangular view is not specified use the triangularity of\n \/\/ the input matrix\n matrix_cl_view tri_view = matrix_view;\n if (matrix_view == matrix_cl_view::Entire\n || matrix_view == matrix_cl_view::Diagonal) {\n tri_view = A.view();\n }\n check_triangular(\"tri_inverse (OpenCL)\", \"A\", A);\n check_square(\"tri_inverse (OpenCL)\", \"A\", A);\n\n int thread_block_2D_dim = 32;\n int max_1D_thread_block_size = opencl_context.max_thread_block_size();\n \/\/ we split the input matrix to 32 blocks\n int thread_block_size_1D\n = (((A.rows() \/ 32) + thread_block_2D_dim - 1) \/ thread_block_2D_dim)\n * thread_block_2D_dim;\n if (max_1D_thread_block_size < thread_block_size_1D) {\n thread_block_size_1D = max_1D_thread_block_size;\n }\n int max_2D_thread_block_dim = std::sqrt(max_1D_thread_block_size);\n if (max_2D_thread_block_dim < thread_block_2D_dim) {\n thread_block_2D_dim = max_2D_thread_block_dim;\n }\n \/\/ for small size split in max 2 parts\n if (thread_block_size_1D < 64) {\n thread_block_size_1D = 32;\n }\n if (A.rows() < thread_block_size_1D) {\n thread_block_size_1D = A.rows();\n }\n\n \/\/ pad the input matrix\n int A_rows_padded\n = ((A.rows() + thread_block_size_1D - 1) \/ thread_block_size_1D)\n * thread_block_size_1D;\n\n matrix_cl temp(A_rows_padded, A_rows_padded);\n matrix_cl inv_padded(A_rows_padded, A_rows_padded);\n matrix_cl inv_mat(A);\n matrix_cl zero_mat(A_rows_padded - A.rows(), A_rows_padded);\n zero_mat.template zeros();\n inv_padded.template zeros();\n if (tri_view == matrix_cl_view::Upper) {\n inv_mat = transpose(inv_mat);\n }\n int work_per_thread\n = opencl_kernels::inv_lower_tri_multiply.make_functor.get_opts().at(\n \"WORK_PER_THREAD\");\n \/\/ the number of blocks in the first step\n \/\/ each block is inverted with using the regular forward substitution\n int parts = inv_padded.rows() \/ thread_block_size_1D;\n inv_padded.sub_block(inv_mat, 0, 0, 0, 0, inv_mat.rows(), inv_mat.rows());\n try {\n \/\/ create a batch of identity matrices to be used in the first step\n opencl_kernels::batch_identity(\n cl::NDRange(parts, thread_block_size_1D, thread_block_size_1D), temp,\n thread_block_size_1D, temp.size());\n \/\/ spawn parts thread blocks, each responsible for one block\n opencl_kernels::diag_inv(cl::NDRange(parts * thread_block_size_1D),\n cl::NDRange(thread_block_size_1D), inv_padded,\n temp, inv_padded.rows());\n } catch (cl::Error& e) {\n check_opencl_error(\"inverse step1\", e);\n }\n \/\/ set the padded part of the matrix and the upper triangular to zeros\n inv_padded.sub_block(zero_mat, 0, 0, inv_mat.rows(), 0, zero_mat.rows(),\n zero_mat.cols());\n inv_padded.template zeros_strict_tri();\n if (parts == 1) {\n inv_mat.sub_block(inv_padded, 0, 0, 0, 0, inv_mat.rows(), inv_mat.rows());\n if (tri_view == matrix_cl_view::Upper) {\n inv_mat = transpose(inv_mat);\n }\n return inv_mat;\n }\n using std::ceil;\n parts = ceil(parts \/ 2.0);\n\n auto result_matrix_dim = thread_block_size_1D;\n auto thread_block_work2d_dim = thread_block_2D_dim \/ work_per_thread;\n auto ndrange_2d\n = cl::NDRange(thread_block_2D_dim, thread_block_work2d_dim, 1);\n while (parts > 0) {\n int result_matrix_dim_x = result_matrix_dim;\n \/\/ when calculating the last submatrix\n \/\/ we can reduce the size to the actual size (not the next power of 2)\n if (parts == 1 && (inv_padded.rows() - result_matrix_dim * 2) < 0) {\n result_matrix_dim_x = inv_padded.rows() - result_matrix_dim;\n }\n auto result_work_dim = result_matrix_dim \/ work_per_thread;\n auto result_ndrange\n = cl::NDRange(result_matrix_dim_x, result_work_dim, parts);\n opencl_kernels::inv_lower_tri_multiply(result_ndrange, ndrange_2d,\n inv_padded, temp, inv_padded.rows(),\n result_matrix_dim);\n opencl_kernels::neg_rect_lower_tri_multiply(\n result_ndrange, ndrange_2d, inv_padded, temp, inv_padded.rows(),\n result_matrix_dim);\n \/\/ if this is the last submatrix, end\n if (parts == 1) {\n parts = 0;\n } else {\n parts = ceil(parts \/ 2.0);\n }\n result_matrix_dim *= 2;\n \/\/ set the padded part and upper diagonal to zeros\n inv_padded.sub_block(zero_mat, 0, 0, inv_mat.rows(), 0, zero_mat.rows(),\n zero_mat.cols());\n inv_padded.template zeros_strict_tri();\n }\n \/\/ un-pad and return\n inv_mat.sub_block(inv_padded, 0, 0, 0, 0, inv_mat.rows(), inv_mat.rows());\n if (tri_view == matrix_cl_view::Upper) {\n inv_mat = transpose(inv_mat);\n }\n inv_mat.view(tri_view);\n return inv_mat;\n}\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n#endif\nfixed aliasing in tri_inverse#ifndef STAN_MATH_OPENCL_TRI_INVERSE_HPP\n#define STAN_MATH_OPENCL_TRI_INVERSE_HPP\n\n#ifdef STAN_OPENCL\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\/** \\ingroup opencl\n * Computes the inverse of a triangular matrix\n *\n * For a full guide to how this works and fits into Cholesky decompositions,\n * see the reference report\n * \n * here<\/a> and kernel doc\n * here<\/a>.\n *\n * @param A matrix on the OpenCL device\n * @return the inverse of A\n *\n * @throw std::invalid_argument<\/code> if the matrix\n * is not square\n *\/\ntemplate >\ninline matrix_cl tri_inverse(const matrix_cl& A) {\n \/\/ if the triangular view is not specified use the triangularity of\n \/\/ the input matrix\n matrix_cl_view tri_view = matrix_view;\n if (matrix_view == matrix_cl_view::Entire\n || matrix_view == matrix_cl_view::Diagonal) {\n tri_view = A.view();\n }\n check_triangular(\"tri_inverse (OpenCL)\", \"A\", A);\n check_square(\"tri_inverse (OpenCL)\", \"A\", A);\n\n int thread_block_2D_dim = 32;\n int max_1D_thread_block_size = opencl_context.max_thread_block_size();\n \/\/ we split the input matrix to 32 blocks\n int thread_block_size_1D\n = (((A.rows() \/ 32) + thread_block_2D_dim - 1) \/ thread_block_2D_dim)\n * thread_block_2D_dim;\n if (max_1D_thread_block_size < thread_block_size_1D) {\n thread_block_size_1D = max_1D_thread_block_size;\n }\n int max_2D_thread_block_dim = std::sqrt(max_1D_thread_block_size);\n if (max_2D_thread_block_dim < thread_block_2D_dim) {\n thread_block_2D_dim = max_2D_thread_block_dim;\n }\n \/\/ for small size split in max 2 parts\n if (thread_block_size_1D < 64) {\n thread_block_size_1D = 32;\n }\n if (A.rows() < thread_block_size_1D) {\n thread_block_size_1D = A.rows();\n }\n\n \/\/ pad the input matrix\n int A_rows_padded\n = ((A.rows() + thread_block_size_1D - 1) \/ thread_block_size_1D)\n * thread_block_size_1D;\n\n matrix_cl temp(A_rows_padded, A_rows_padded);\n matrix_cl inv_padded(A_rows_padded, A_rows_padded);\n matrix_cl inv_mat(A);\n matrix_cl zero_mat(A_rows_padded - A.rows(), A_rows_padded);\n zero_mat.template zeros();\n inv_padded.template zeros();\n if (tri_view == matrix_cl_view::Upper) {\n inv_mat = transpose(inv_mat).eval();\n }\n int work_per_thread\n = opencl_kernels::inv_lower_tri_multiply.make_functor.get_opts().at(\n \"WORK_PER_THREAD\");\n \/\/ the number of blocks in the first step\n \/\/ each block is inverted with using the regular forward substitution\n int parts = inv_padded.rows() \/ thread_block_size_1D;\n inv_padded.sub_block(inv_mat, 0, 0, 0, 0, inv_mat.rows(), inv_mat.rows());\n try {\n \/\/ create a batch of identity matrices to be used in the first step\n opencl_kernels::batch_identity(\n cl::NDRange(parts, thread_block_size_1D, thread_block_size_1D), temp,\n thread_block_size_1D, temp.size());\n \/\/ spawn parts thread blocks, each responsible for one block\n opencl_kernels::diag_inv(cl::NDRange(parts * thread_block_size_1D),\n cl::NDRange(thread_block_size_1D), inv_padded,\n temp, inv_padded.rows());\n } catch (cl::Error& e) {\n check_opencl_error(\"inverse step1\", e);\n }\n \/\/ set the padded part of the matrix and the upper triangular to zeros\n inv_padded.sub_block(zero_mat, 0, 0, inv_mat.rows(), 0, zero_mat.rows(),\n zero_mat.cols());\n inv_padded.template zeros_strict_tri();\n if (parts == 1) {\n inv_mat.sub_block(inv_padded, 0, 0, 0, 0, inv_mat.rows(), inv_mat.rows());\n if (tri_view == matrix_cl_view::Upper) {\n inv_mat = transpose(inv_mat).eval();\n }\n return inv_mat;\n }\n using std::ceil;\n parts = ceil(parts \/ 2.0);\n\n auto result_matrix_dim = thread_block_size_1D;\n auto thread_block_work2d_dim = thread_block_2D_dim \/ work_per_thread;\n auto ndrange_2d\n = cl::NDRange(thread_block_2D_dim, thread_block_work2d_dim, 1);\n while (parts > 0) {\n int result_matrix_dim_x = result_matrix_dim;\n \/\/ when calculating the last submatrix\n \/\/ we can reduce the size to the actual size (not the next power of 2)\n if (parts == 1 && (inv_padded.rows() - result_matrix_dim * 2) < 0) {\n result_matrix_dim_x = inv_padded.rows() - result_matrix_dim;\n }\n auto result_work_dim = result_matrix_dim \/ work_per_thread;\n auto result_ndrange\n = cl::NDRange(result_matrix_dim_x, result_work_dim, parts);\n opencl_kernels::inv_lower_tri_multiply(result_ndrange, ndrange_2d,\n inv_padded, temp, inv_padded.rows(),\n result_matrix_dim);\n opencl_kernels::neg_rect_lower_tri_multiply(\n result_ndrange, ndrange_2d, inv_padded, temp, inv_padded.rows(),\n result_matrix_dim);\n \/\/ if this is the last submatrix, end\n if (parts == 1) {\n parts = 0;\n } else {\n parts = ceil(parts \/ 2.0);\n }\n result_matrix_dim *= 2;\n \/\/ set the padded part and upper diagonal to zeros\n inv_padded.sub_block(zero_mat, 0, 0, inv_mat.rows(), 0, zero_mat.rows(),\n zero_mat.cols());\n inv_padded.template zeros_strict_tri();\n }\n \/\/ un-pad and return\n inv_mat.sub_block(inv_padded, 0, 0, 0, 0, inv_mat.rows(), inv_mat.rows());\n if (tri_view == matrix_cl_view::Upper) {\n inv_mat = transpose(inv_mat).eval();\n }\n inv_mat.view(tri_view);\n return inv_mat;\n}\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n#endif\n<|endoftext|>"} {"text":"#include \"MainFrame.h\"\n#include \n#include \n#include \n#include \n#include \"ImageViewPanel.h\"\n#include \"ZipEntry.h\"\n#include \"FileEntry.h\"\n\nenum MainFrameIds { ID_DIRECTORY_TREE = 1, ID_IMAGE_BUTTON };\n\nMainFrame::MainFrame() : wxFrame(NULL, wxID_ANY, \"ZipPicView\") {\n auto statusBar = CreateStatusBar();\n SetStatusText(\"Welcome to ZipPicView!\");\n\n auto outerSizer = new wxBoxSizer(wxVERTICAL);\n auto toolSizer = new wxBoxSizer(wxHORIZONTAL);\n onTopChk = new wxCheckBox(this, wxID_ANY, \"On Top\");\n onTopChk->Bind(wxEVT_CHECKBOX, &MainFrame::OnOnTopChecked, this);\n notebook = new wxNotebook(this, wxID_ANY);\n\n currentFileCtrl =\n new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition,\n wxDefaultSize, wxTE_READONLY);\n dirBrowseBtn = new wxButton(this, wxID_ANY, \"Directory...\");\n dirBrowseBtn->Bind(wxEVT_BUTTON, &MainFrame::OnDirBrowsePressed, this);\n zipBrowseBtn = new wxButton(this, wxID_ANY, \"Zip...\");\n zipBrowseBtn->Bind(wxEVT_BUTTON, &MainFrame::OnZipBrowsePressed, this);\n\n toolSizer->Add(currentFileCtrl, 1, wxEXPAND | wxALL);\n toolSizer->Add(dirBrowseBtn, 0, wxEXPAND | wxALL);\n toolSizer->Add(zipBrowseBtn, 0, wxEXPAND | wxALL);\n toolSizer->Add(onTopChk, 0, wxEXPAND | wxALL);\n\n outerSizer->Add(toolSizer, 0, wxEXPAND | wxALL, 5);\n outerSizer->Add(notebook, 1, wxEXPAND | wxALL, 5);\n\n splitter = new wxSplitterWindow(notebook, wxID_ANY);\n dirTree = new wxTreeCtrl(splitter, ID_DIRECTORY_TREE, wxDefaultPosition,\n wxDefaultSize, wxTR_SINGLE | wxTR_NO_LINES |\n wxTR_FULL_ROW_HIGHLIGHT);\n dirTree->Bind(wxEVT_TREE_SEL_CHANGED, &MainFrame::OnTreeSelectionChanged,\n this, ID_DIRECTORY_TREE);\n dirTree->Bind(wxEVT_TREE_ITEM_COLLAPSING,\n [=](wxTreeEvent &event) { event.Veto(); }, ID_DIRECTORY_TREE);\n dirTree->SetMinSize({250, 250});\n\n auto rightWindow = new wxScrolledWindow(splitter, wxID_ANY);\n auto grid = new wxGridSizer(5);\n rightWindow->SetSizer(grid);\n rightWindow->SetScrollRate(10, 10);\n rightWindow->SetMinSize({250, 250});\n rightWindow->Bind(wxEVT_SIZE, &MainFrame::OnGridPanelSize, this);\n splitter->SplitVertically(dirTree, rightWindow, 250);\n\n notebook->AddPage(splitter, \"Browse\");\n\n SetMinSize({640, 480});\n SetSizer(outerSizer);\n}\n\nvoid MainFrame::BuildDirectoryTree() {\n auto root = dirTree->AddRoot(entry->Name(), -1, -1, new EntryItemData(entry));\n AddTreeItemsFromEntry(root, entry);\n}\n\nvoid MainFrame::AddTreeItemsFromEntry(const wxTreeItemId &itemId,\n Entry *entry) {\n for (auto childEntry : *entry) {\n if (!childEntry->IsDirectory())\n return;\n\n auto child = dirTree->AppendItem(itemId, childEntry->Name(), -1, -1,\n new EntryItemData(childEntry));\n\n AddTreeItemsFromEntry(child, childEntry);\n }\n}\n\nvoid MainFrame::OnTreeSelectionChanged(wxTreeEvent &event) {\n wxProgressDialog progressDlg(\"Loading\", \"Please Wait\");\n\n auto treeItemId = event.GetItem();\n auto rootId = dirTree->GetRootItem();\n auto currentFileEntry =\n dynamic_cast(dirTree->GetItemData(treeItemId))->Get();\n\n progressDlg.Pulse();\n auto gridPanel = dynamic_cast(splitter->GetWindow2());\n gridPanel->Show(false);\n auto grid = gridPanel->GetSizer();\n grid->Clear(true);\n\n for (auto childEntry : *currentFileEntry) {\n if (childEntry->IsDirectory())\n return;\n\n auto name = childEntry->Name();\n if (!(name.EndsWith(\".jpg\") || name.EndsWith(\".jpeg\") ||\n name.EndsWith(\".png\") || name.EndsWith(\".gif\")))\n return;\n\n auto image = childEntry->LoadImage();\n auto button = new wxButton(gridPanel, wxID_ANY);\n button->Bind(wxEVT_BUTTON, &MainFrame::OnImageButtonClick, this);\n\n int longerSide = image.GetWidth() > image.GetHeight() ? image.GetWidth()\n : image.GetHeight();\n int width = 200 * image.GetWidth() \/ longerSide;\n int height = 200 * image.GetHeight() \/ longerSide;\n auto thumbnailImage = image.Scale(width, height, wxIMAGE_QUALITY_HIGH);\n\n button->SetBitmap(thumbnailImage, wxBOTTOM);\n button->SetClientObject(new EntryItemData(childEntry));\n button->SetMinSize({250, 250});\n\n auto btnSizer = new wxBoxSizer(wxVERTICAL);\n btnSizer->Add(button, 0, wxEXPAND);\n btnSizer->Add(new wxStaticText(gridPanel, wxID_ANY, childEntry->Name()));\n\n grid->Add(btnSizer, 0, wxALL | wxEXPAND, 5);\n progressDlg.Pulse();\n }\n\n grid->FitInside(gridPanel);\n gridPanel->Show(true);\n gridPanel->Scroll(0, 0);\n progressDlg.Update(100);\n}\n\nvoid MainFrame::OnImageButtonClick(wxCommandEvent &event) {\n auto button = dynamic_cast(event.GetEventObject());\n auto clientData =\n dynamic_cast(button->GetClientObject());\n\n auto page = notebook->GetPageCount();\n auto childEntry =\n dynamic_cast(button->GetClientObject())->Get();\n auto bitmapCtl = new ImageViewPanel(notebook, childEntry->LoadImage());\n notebook->AddPage(bitmapCtl, childEntry->Name());\n notebook->SetSelection(page);\n}\n\nvoid MainFrame::OnGridPanelSize(wxSizeEvent &event) {\n auto grid = dynamic_cast(splitter->GetWindow2()->GetSizer());\n auto size = event.GetSize();\n int col = (size.GetWidth() \/ 250);\n grid->SetCols(col > 0 ? col : 1);\n\n grid->FitInside(splitter->GetWindow2());\n}\n\nvoid MainFrame::OnOnTopChecked(wxCommandEvent &event) {\n auto style = GetWindowStyle();\n\n if (onTopChk->IsChecked()) {\n style += wxSTAY_ON_TOP;\n } else {\n style -= wxSTAY_ON_TOP;\n }\n SetWindowStyle(style);\n}\n\nvoid MainFrame::OnDirBrowsePressed(wxCommandEvent &event) {\n wxDirDialog dlg(NULL, \"Choose directory\", \"\",\n wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST);\n if (dlg.ShowModal() == wxID_CANCEL)\n return;\n auto oldEntry = entry;\n auto path = dlg.GetPath() + wxFileName::GetPathSeparator();\n\n wxFileName filename(path);\n auto entry = FileEntry::Create(filename);\n SetEntry(entry);\n currentFileCtrl->SetLabelText(filename.GetFullPath());\n}\n\nvoid MainFrame::OnZipBrowsePressed(wxCommandEvent &event) {\n wxFileDialog dialog(this, _(\"Open ZIP file\"), \"\", \"\",\n \"ZIP files (*.zip)|*.zip\",\n wxFD_OPEN | wxFD_FILE_MUST_EXIST);\n if (dialog.ShowModal() == wxID_CANCEL)\n return;\n\n auto path = dialog.GetPath();\n wxFileName filename(path);\n\n int error;\n auto zipFile = zip_open(path, ZIP_RDONLY, &error);\n\n if (zipFile == nullptr) {\n throw error;\n }\n\n auto entry = ZipEntry::Create(zipFile);\n SetEntry(entry);\n currentFileCtrl->SetLabelText(filename.GetFullPath());\n}\n\nvoid MainFrame::SetEntry(Entry *entry) {\n auto oldEntry = MainFrame::entry;\n MainFrame::entry = entry;\n\n dirTree->UnselectAll();\n dirTree->DeleteAllItems();\n\n BuildDirectoryTree();\n\n dirTree->SelectItem(dirTree->GetRootItem());\n dirTree->ExpandAll();\n\n if (oldEntry) {\n delete oldEntry;\n }\n}\nUnicode filename handling (almost) properly.#include \"MainFrame.h\"\n#include \n#include \n#include \n#include \n#include \"ImageViewPanel.h\"\n#include \"ZipEntry.h\"\n#include \"FileEntry.h\"\n\nenum MainFrameIds { ID_DIRECTORY_TREE = 1, ID_IMAGE_BUTTON };\n\nMainFrame::MainFrame() : wxFrame(NULL, wxID_ANY, \"ZipPicView\") {\n auto statusBar = CreateStatusBar();\n SetStatusText(\"Welcome to ZipPicView!\");\n\n auto outerSizer = new wxBoxSizer(wxVERTICAL);\n auto toolSizer = new wxBoxSizer(wxHORIZONTAL);\n onTopChk = new wxCheckBox(this, wxID_ANY, \"On Top\");\n onTopChk->Bind(wxEVT_CHECKBOX, &MainFrame::OnOnTopChecked, this);\n notebook = new wxNotebook(this, wxID_ANY);\n\n currentFileCtrl =\n new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition,\n wxDefaultSize, wxTE_READONLY);\n dirBrowseBtn = new wxButton(this, wxID_ANY, \"Directory...\");\n dirBrowseBtn->Bind(wxEVT_BUTTON, &MainFrame::OnDirBrowsePressed, this);\n zipBrowseBtn = new wxButton(this, wxID_ANY, \"Zip...\");\n zipBrowseBtn->Bind(wxEVT_BUTTON, &MainFrame::OnZipBrowsePressed, this);\n\n toolSizer->Add(currentFileCtrl, 1, wxEXPAND | wxALL);\n toolSizer->Add(dirBrowseBtn, 0, wxEXPAND | wxALL);\n toolSizer->Add(zipBrowseBtn, 0, wxEXPAND | wxALL);\n toolSizer->Add(onTopChk, 0, wxEXPAND | wxALL);\n\n outerSizer->Add(toolSizer, 0, wxEXPAND | wxALL, 5);\n outerSizer->Add(notebook, 1, wxEXPAND | wxALL, 5);\n\n splitter = new wxSplitterWindow(notebook, wxID_ANY);\n dirTree = new wxTreeCtrl(splitter, ID_DIRECTORY_TREE, wxDefaultPosition,\n wxDefaultSize, wxTR_SINGLE | wxTR_NO_LINES |\n wxTR_FULL_ROW_HIGHLIGHT);\n dirTree->Bind(wxEVT_TREE_SEL_CHANGED, &MainFrame::OnTreeSelectionChanged,\n this, ID_DIRECTORY_TREE);\n dirTree->Bind(wxEVT_TREE_ITEM_COLLAPSING,\n [=](wxTreeEvent &event) { event.Veto(); }, ID_DIRECTORY_TREE);\n dirTree->SetMinSize({250, 250});\n\n auto rightWindow = new wxScrolledWindow(splitter, wxID_ANY);\n auto grid = new wxGridSizer(5);\n rightWindow->SetSizer(grid);\n rightWindow->SetScrollRate(10, 10);\n rightWindow->SetMinSize({250, 250});\n rightWindow->Bind(wxEVT_SIZE, &MainFrame::OnGridPanelSize, this);\n splitter->SplitVertically(dirTree, rightWindow, 250);\n\n notebook->AddPage(splitter, \"Browse\");\n\n SetMinSize({640, 480});\n SetSizer(outerSizer);\n}\n\nvoid MainFrame::BuildDirectoryTree() {\n auto root = dirTree->AddRoot(entry->Name(), -1, -1, new EntryItemData(entry));\n AddTreeItemsFromEntry(root, entry);\n}\n\nvoid MainFrame::AddTreeItemsFromEntry(const wxTreeItemId &itemId,\n Entry *entry) {\n for (auto childEntry : *entry) {\n if (!childEntry->IsDirectory())\n return;\n\n auto child = dirTree->AppendItem(itemId, childEntry->Name(), -1, -1,\n new EntryItemData(childEntry));\n\n AddTreeItemsFromEntry(child, childEntry);\n }\n}\n\nvoid MainFrame::OnTreeSelectionChanged(wxTreeEvent &event) {\n wxProgressDialog progressDlg(\"Loading\", \"Please Wait\");\n\n auto treeItemId = event.GetItem();\n auto rootId = dirTree->GetRootItem();\n auto currentFileEntry =\n dynamic_cast(dirTree->GetItemData(treeItemId))->Get();\n\n progressDlg.Pulse();\n auto gridPanel = dynamic_cast(splitter->GetWindow2());\n gridPanel->Show(false);\n auto grid = gridPanel->GetSizer();\n grid->Clear(true);\n\n for (auto childEntry : *currentFileEntry) {\n if (childEntry->IsDirectory())\n return;\n\n auto name = childEntry->Name();\n if (!(name.EndsWith(\".jpg\") || name.EndsWith(\".jpeg\") ||\n name.EndsWith(\".png\") || name.EndsWith(\".gif\")))\n return;\n\n auto image = childEntry->LoadImage();\n auto button = new wxButton(gridPanel, wxID_ANY);\n button->Bind(wxEVT_BUTTON, &MainFrame::OnImageButtonClick, this);\n\n int longerSide = image.GetWidth() > image.GetHeight() ? image.GetWidth()\n : image.GetHeight();\n int width = 200 * image.GetWidth() \/ longerSide;\n int height = 200 * image.GetHeight() \/ longerSide;\n auto thumbnailImage = image.Scale(width, height, wxIMAGE_QUALITY_HIGH);\n\n button->SetBitmap(thumbnailImage, wxBOTTOM);\n button->SetClientObject(new EntryItemData(childEntry));\n button->SetMinSize({250, 250});\n\n auto btnSizer = new wxBoxSizer(wxVERTICAL);\n btnSizer->Add(button, 0, wxEXPAND);\n btnSizer->Add(new wxStaticText(gridPanel, wxID_ANY, childEntry->Name()));\n\n grid->Add(btnSizer, 0, wxALL | wxEXPAND, 5);\n progressDlg.Pulse();\n }\n\n grid->FitInside(gridPanel);\n gridPanel->Show(true);\n gridPanel->Scroll(0, 0);\n progressDlg.Update(100);\n}\n\nvoid MainFrame::OnImageButtonClick(wxCommandEvent &event) {\n auto button = dynamic_cast(event.GetEventObject());\n auto clientData =\n dynamic_cast(button->GetClientObject());\n\n auto page = notebook->GetPageCount();\n auto childEntry =\n dynamic_cast(button->GetClientObject())->Get();\n auto bitmapCtl = new ImageViewPanel(notebook, childEntry->LoadImage());\n notebook->AddPage(bitmapCtl, childEntry->Name());\n notebook->SetSelection(page);\n}\n\nvoid MainFrame::OnGridPanelSize(wxSizeEvent &event) {\n auto grid = dynamic_cast(splitter->GetWindow2()->GetSizer());\n auto size = event.GetSize();\n int col = (size.GetWidth() \/ 250);\n grid->SetCols(col > 0 ? col : 1);\n\n grid->FitInside(splitter->GetWindow2());\n}\n\nvoid MainFrame::OnOnTopChecked(wxCommandEvent &event) {\n auto style = GetWindowStyle();\n\n if (onTopChk->IsChecked()) {\n style += wxSTAY_ON_TOP;\n } else {\n style -= wxSTAY_ON_TOP;\n }\n SetWindowStyle(style);\n}\n\nvoid MainFrame::OnDirBrowsePressed(wxCommandEvent &event) {\n wxDirDialog dlg(NULL, \"Choose directory\", \"\",\n wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST);\n if (dlg.ShowModal() == wxID_CANCEL)\n return;\n auto oldEntry = entry;\n auto path = dlg.GetPath() + wxFileName::GetPathSeparator();\n\n wxFileName filename(path);\n auto entry = FileEntry::Create(filename);\n SetEntry(entry);\n currentFileCtrl->SetLabelText(filename.GetFullPath());\n}\n\nvoid MainFrame::OnZipBrowsePressed(wxCommandEvent &event) {\n wxFileDialog dialog(this, _(\"Open ZIP file\"), \"\", \"\",\n \"ZIP files (*.zip)|*.zip\",\n wxFD_OPEN | wxFD_FILE_MUST_EXIST);\n if (dialog.ShowModal() == wxID_CANCEL)\n return;\n\n auto path = dialog.GetPath();\n wxFileName filename(path);\n wxFile file(path);\n\n int error;\n auto zipFile = zip_fdopen(file.fd(), ZIP_RDONLY, &error);\n \/\/ auto zipFile = zip_open(path.ToUTF8(), ZIP_RDONLY, &error);\n\n if (zipFile == nullptr) {\n throw error;\n }\n\n auto entry = ZipEntry::Create(zipFile);\n SetEntry(entry);\n currentFileCtrl->SetLabelText(filename.GetFullPath());\n}\n\nvoid MainFrame::SetEntry(Entry *entry) {\n auto oldEntry = MainFrame::entry;\n MainFrame::entry = entry;\n\n dirTree->UnselectAll();\n dirTree->DeleteAllItems();\n\n BuildDirectoryTree();\n\n dirTree->SelectItem(dirTree->GetRootItem());\n dirTree->ExpandAll();\n\n if (oldEntry) {\n delete oldEntry;\n }\n}\n<|endoftext|>"} {"text":"\/***************************************************************************\n * Copyright (C) 2005-2017 by the FIFE team *\n * http:\/\/www.fifengine.net *\n * This file is part of FIFE. *\n * *\n * FIFE is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Lesser General Public *\n * License as published by the Free Software Foundation; either *\n * version 2.1 of the License, or (at your option) any later version. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public *\n * License along with this library; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *\n ***************************************************************************\/\n\n\/\/ Standard C++ library includes\n\n\/\/ 3rd party library includes\n#include \n\n\/\/ FIFE includes\n\/\/ These includes are split up in two parts, separated by one empty line\n\/\/ First block: files included from the FIFE root src directory\n\/\/ Second block: files included from the same folder\n#include \"util\/structures\/rect.h\"\n#include \"util\/time\/timemanager.h\"\n#include \"util\/log\/logger.h\"\n#include \"video\/imagemanager.h\"\n\n#include \"animation.h\"\n#include \"image.h\"\n#include \"renderbackend.h\"\n#include \"cursor.h\"\n\nnamespace FIFE {\n\t\/** Logger to use for this source file.\n\t * @relates Logger\n\t *\/\n\tstatic Logger _log(LM_CURSOR);\n\n\tCursor::Cursor(RenderBackend* renderbackend):\n\t\tm_cursor_id(NC_ARROW),\n\t\tm_cursor_type(CURSOR_NATIVE),\n\t\tm_drag_type(CURSOR_NONE),\n\t\tm_native_cursor(NULL),\n\t\tm_renderbackend(renderbackend),\n\t\tm_animtime(0),\n\t\tm_drag_animtime(0),\n\t\tm_drag_offset_x(0),\n\t\tm_drag_offset_y(0),\n\t\tm_mx(0),\n\t\tm_my(0),\n\t\tm_timemanager(TimeManager::instance()),\n\t\tm_invalidated(false),\n\t\tm_native_image_cursor_enabled(false) {\n\t\tassert(m_timemanager);\n\t\tset(m_cursor_id);\n\t}\n\n\tvoid Cursor::set(uint32_t cursor_id) {\n\t\tm_cursor_type = CURSOR_NATIVE;\n\n\t\tif (!SDL_ShowCursor(1)) {\n\t\t\tSDL_PumpEvents();\n\t\t}\n\t\tsetNativeCursor(cursor_id);\n\n\t\tm_cursor_image.reset();\n\t\tm_cursor_animation.reset();\n\t}\n\n\tvoid Cursor::set(ImagePtr image) {\n\t\tassert(image != 0);\n\n\t\tm_cursor_image = image;\n\t\tm_cursor_type = CURSOR_IMAGE;\n\n\t\tif (m_native_image_cursor_enabled) {\n\t\t\tsetNativeImageCursor(image);\n\t\t\tif (!SDL_ShowCursor(1)) {\n\t\t\t\tSDL_PumpEvents();\n\t\t\t}\n\t\t}\n\t\telse if (SDL_ShowCursor(0)) {\n\t\t\tSDL_PumpEvents();\n\t\t}\n\n\t\tm_cursor_id = NC_ARROW;\n\t\tm_cursor_animation.reset();\n\t}\n\n\tvoid Cursor::set(AnimationPtr anim) {\n\t\tassert(anim != 0);\n\n\t\tm_cursor_animation = anim;\n\t\tm_cursor_type = CURSOR_ANIMATION;\n\n\t\tif (m_native_image_cursor_enabled) {\n\t\t\tsetNativeImageCursor(anim->getFrameByTimestamp(0));\n\t\t\tif (!SDL_ShowCursor(1)) {\n\t\t\t\tSDL_PumpEvents();\n\t\t\t}\n\t\t}\n\t\telse if (SDL_ShowCursor(0)) {\n\t\t\tSDL_PumpEvents();\n\t\t}\n\t\tm_animtime = m_timemanager->getTime();\n\n\t\tm_cursor_id = NC_ARROW;\n\t\tm_cursor_image.reset();\n\t}\n\n\tvoid Cursor::setDrag(ImagePtr image, int32_t drag_offset_x, int32_t drag_offset_y) {\n\t\tassert(image != 0);\n\n\t\tm_cursor_drag_image = image;\n\t\tm_drag_type = CURSOR_IMAGE;\n\t\tm_drag_offset_x = drag_offset_x;\n\t\tm_drag_offset_y = drag_offset_y;\n\n\t\tm_cursor_drag_animation.reset();\n\t}\n\n\tvoid Cursor::setDrag(AnimationPtr anim, int32_t drag_offset_x, int32_t drag_offset_y) {\n\t\tassert(anim != 0);\n\n\t\tm_cursor_drag_animation = anim;\n\t\tm_drag_type = CURSOR_ANIMATION;\n\t\tm_drag_offset_x = drag_offset_x;\n\t\tm_drag_offset_y = drag_offset_y;\n\n\t\tm_drag_animtime = m_timemanager->getTime();\n\n\t\tm_cursor_drag_image.reset();\n\t}\n\n\tvoid Cursor::resetDrag() {\n\t\tm_drag_type = CURSOR_NONE;\n\n\t\tm_drag_animtime = 0;\n\t\tm_drag_offset_x = 0;\n\t\tm_drag_offset_y = 0;\n\n\t\tm_cursor_drag_animation.reset();\n\t\tm_cursor_drag_image.reset();\n\t}\n\n void Cursor::setPosition(uint32_t x, uint32_t y) {\n\t\tm_mx = x;\n\t\tm_my = y;\n\t\tSDL_WarpMouseInWindow(RenderBackend::instance()->getWindow(), m_mx, m_my);\n\t}\n\n void Cursor::getPosition(int32_t* x, int32_t* y) {\n *x = m_mx;\n *y = m_my;\n }\n\n\tvoid Cursor::invalidate() {\n\t\tif (m_native_cursor != NULL) {\n\t\t\tSDL_FreeCursor(m_native_cursor);\n\t\t\tm_native_cursor = NULL;\n\t\t\tm_native_cursor_image.reset();\n\n\t\t\tm_invalidated = true;\n\t\t}\n\t}\n\n\tvoid Cursor::draw() {\n\t\tif (m_invalidated) {\n\t\t\tif (m_cursor_type == CURSOR_NATIVE ) {\n\t\t\t\tset(m_cursor_id);\n\t\t\t}\n\t\t\telse if (m_native_image_cursor_enabled) {\n\t\t\t\tif (m_cursor_type == CURSOR_IMAGE ) {\n\t\t\t\t\tset(m_cursor_image);\n\t\t\t\t}\n\t\t\t\telse if (m_cursor_type == CURSOR_ANIMATION ) {\n\t\t\t\t\tset(m_cursor_animation);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tm_invalidated = false;\n\t\t}\n\n\t\tSDL_GetMouseState(&m_mx, &m_my);\n\t\tif ((m_cursor_type == CURSOR_NATIVE) && (m_drag_type == CURSOR_NONE)) {\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ render possible drag image\n\t\tImagePtr img;\n\t\tif (m_drag_type == CURSOR_IMAGE) {\n\t\t\timg = m_cursor_drag_image;\n\t\t}\n\t\telse if (m_drag_type == CURSOR_ANIMATION) {\n\t\t\tint32_t animtime = (m_timemanager->getTime() - m_drag_animtime) % m_cursor_drag_animation->getDuration();\n\t\t\timg = m_cursor_drag_animation->getFrameByTimestamp(animtime);\n\t\t}\n\n\t\tif (img != 0) {\n\t\t\tRect area(m_mx + m_drag_offset_x + img->getXShift(), m_my + m_drag_offset_y + img->getYShift(), img->getWidth(), img->getHeight());\n\t\t\tm_renderbackend->pushClipArea(area, false);\n\t\t\timg->render(area);\n\t\t\tm_renderbackend->renderVertexArrays();\n\t\t\tm_renderbackend->popClipArea();\n\t\t}\n\n\t\tImagePtr img2;\n\t\t\/\/ render possible cursor image\n\t\tif (m_cursor_type == CURSOR_IMAGE) {\n\t\t\timg2 = m_cursor_image;\n\t\t}\n\t\telse if (m_cursor_type == CURSOR_ANIMATION) {\n\t\t\tint32_t animtime = (m_timemanager->getTime() - m_animtime) % m_cursor_animation->getDuration();\n\t\t\timg2 = m_cursor_animation->getFrameByTimestamp(animtime);\n\t\t}\n\n\t\tif (img2 != 0) {\n\t\t\tif (m_native_image_cursor_enabled) {\n\t\t\t\tsetNativeImageCursor(img2);\n\t\t\t} else {\n\t\t\t\tRect area(m_mx + img2->getXShift(), m_my + img2->getYShift(), img2->getWidth(), img2->getHeight());\n\t\t\t\tm_renderbackend->pushClipArea(area, false);\n\t\t\t\timg2->render(area);\n\t\t\t\tm_renderbackend->renderVertexArrays();\n\t\t\t\tm_renderbackend->popClipArea();\n\t\t\t}\n\t\t}\n\t}\n\n\tuint32_t Cursor::getNativeId(uint32_t cursor_id) {\n\t\tswitch (cursor_id) {\n\t\t\tcase NC_ARROW:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_ARROW;\n\t\t\tcase NC_IBEAM:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_IBEAM;\n\t\t\tcase NC_WAIT:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_WAIT;\n\t\t\tcase NC_CROSS:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_CROSSHAIR;\n\t\t\tcase NC_WAITARROW:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_WAITARROW;\n\t\t\tcase NC_RESIZENWSE:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_SIZENWSE;\n\t\t\tcase NC_RESIZENESW:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_SIZENESW;\n\t\t\tcase NC_RESIZEWE:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_SIZEWE;\n\t\t\tcase NC_RESIZENS:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_SIZENS;\n\t\t\tcase NC_RESIZEALL:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_SIZEALL;\n\t\t\tcase NC_NO:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_NO;\n\t\t\tcase NC_HAND:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_HAND;\n\t\t}\n\t\treturn cursor_id;\n\t}\n\n\tvoid Cursor::setNativeCursor(uint32_t cursor_id) {\n\t\tcursor_id = getNativeId(cursor_id);\n\t\tSDL_Cursor* cursor = SDL_CreateSystemCursor(static_cast(cursor_id));\n\t\tif (!cursor) {\n\t\t\tFL_WARN(_log, \"No cursor matching cursor_id was found.\");\n\t\t\treturn;\n\t\t}\n\t\tSDL_SetCursor(cursor);\n\t\tif (m_native_cursor != NULL) {\n\t\t\tSDL_FreeCursor(m_native_cursor);\n\t\t}\n\t\tm_native_cursor = cursor;\n\t}\n\n\tvoid Cursor::setNativeImageCursor(ImagePtr image) {\n\t\tif (image == m_native_cursor_image) {\n\t\t\treturn;\n\t\t}\n\n\t\tImagePtr temp_image = image;\n\t\tif (image->isSharedImage()) {\n\t\t\ttemp_image = ImageManager::instance()->create();\n\t\t\ttemp_image->copySubimage(0, 0, image);\n\t\t}\n\n\t\tSDL_Cursor* cursor = SDL_CreateColorCursor(temp_image->getSurface(), -image->getXShift(), -image->getYShift());\n\t\tif (cursor == NULL) {\n\t\t\tFL_WARN(_log, LMsg(\"SDL_CreateColorCursor: \\\"\") << SDL_GetError();\n\t\t\tif (image->isSharedImage()) {\n\t\t\t\tImageManager::instance()->remove(temp_image);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tSDL_SetCursor(cursor);\n\t\tm_native_cursor_image = image;\n\n\t\tif (image->isSharedImage()) {\n\t\t\tImageManager::instance()->remove(temp_image);\n\t\t}\n\t\tif (m_native_cursor != NULL) {\n\t\t\tSDL_FreeCursor(m_native_cursor);\n\t\t}\n\t\tm_native_cursor = cursor;\n\t}\n\n\tvoid Cursor::setNativeImageCursorEnabled(bool native_image_cursor_enabled) {\n\t\tif (m_native_image_cursor_enabled != native_image_cursor_enabled) {\n\t\t\tm_native_image_cursor_enabled = native_image_cursor_enabled;\n\t\t\tif (m_cursor_type == CURSOR_IMAGE ) {\n\t\t\t\tset(m_cursor_image);\n\t\t\t}\n\t\t\telse if (m_cursor_type == CURSOR_ANIMATION ) {\n\t\t\t\tset(m_cursor_animation);\n\t\t\t}\n\t\t}\n\t}\n\n\tbool Cursor::isNativeImageCursorEnabled() const {\n\t\treturn m_native_image_cursor_enabled;\n\t}\n}\nFall back to software cursor if SDL_CreateColorCursor() fails\/***************************************************************************\n * Copyright (C) 2005-2017 by the FIFE team *\n * http:\/\/www.fifengine.net *\n * This file is part of FIFE. *\n * *\n * FIFE is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Lesser General Public *\n * License as published by the Free Software Foundation; either *\n * version 2.1 of the License, or (at your option) any later version. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public *\n * License along with this library; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *\n ***************************************************************************\/\n\n\/\/ Standard C++ library includes\n\n\/\/ 3rd party library includes\n#include \n\n\/\/ FIFE includes\n\/\/ These includes are split up in two parts, separated by one empty line\n\/\/ First block: files included from the FIFE root src directory\n\/\/ Second block: files included from the same folder\n#include \"util\/structures\/rect.h\"\n#include \"util\/time\/timemanager.h\"\n#include \"util\/log\/logger.h\"\n#include \"video\/imagemanager.h\"\n\n#include \"animation.h\"\n#include \"image.h\"\n#include \"renderbackend.h\"\n#include \"cursor.h\"\n\nnamespace FIFE {\n\t\/** Logger to use for this source file.\n\t * @relates Logger\n\t *\/\n\tstatic Logger _log(LM_CURSOR);\n\n\tCursor::Cursor(RenderBackend* renderbackend):\n\t\tm_cursor_id(NC_ARROW),\n\t\tm_cursor_type(CURSOR_NATIVE),\n\t\tm_drag_type(CURSOR_NONE),\n\t\tm_native_cursor(NULL),\n\t\tm_renderbackend(renderbackend),\n\t\tm_animtime(0),\n\t\tm_drag_animtime(0),\n\t\tm_drag_offset_x(0),\n\t\tm_drag_offset_y(0),\n\t\tm_mx(0),\n\t\tm_my(0),\n\t\tm_timemanager(TimeManager::instance()),\n\t\tm_invalidated(false),\n\t\tm_native_image_cursor_enabled(false) {\n\t\tassert(m_timemanager);\n\t\tset(m_cursor_id);\n\t}\n\n\tvoid Cursor::set(uint32_t cursor_id) {\n\t\tm_cursor_type = CURSOR_NATIVE;\n\n\t\tif (!SDL_ShowCursor(1)) {\n\t\t\tSDL_PumpEvents();\n\t\t}\n\t\tsetNativeCursor(cursor_id);\n\n\t\tm_cursor_image.reset();\n\t\tm_cursor_animation.reset();\n\t}\n\n\tvoid Cursor::set(ImagePtr image) {\n\t\tassert(image != 0);\n\n\t\tm_cursor_image = image;\n\t\tm_cursor_type = CURSOR_IMAGE;\n\n\t\tif (m_native_image_cursor_enabled) {\n\t\t\tsetNativeImageCursor(image);\n\t\t\tif (!SDL_ShowCursor(1)) {\n\t\t\t\tSDL_PumpEvents();\n\t\t\t}\n\t\t}\n\t\telse if (SDL_ShowCursor(0)) {\n\t\t\tSDL_PumpEvents();\n\t\t}\n\n\t\tm_cursor_id = NC_ARROW;\n\t\tm_cursor_animation.reset();\n\t}\n\n\tvoid Cursor::set(AnimationPtr anim) {\n\t\tassert(anim != 0);\n\n\t\tm_cursor_animation = anim;\n\t\tm_cursor_type = CURSOR_ANIMATION;\n\n\t\tif (m_native_image_cursor_enabled) {\n\t\t\tsetNativeImageCursor(anim->getFrameByTimestamp(0));\n\t\t\tif (!SDL_ShowCursor(1)) {\n\t\t\t\tSDL_PumpEvents();\n\t\t\t}\n\t\t}\n\t\telse if (SDL_ShowCursor(0)) {\n\t\t\tSDL_PumpEvents();\n\t\t}\n\t\tm_animtime = m_timemanager->getTime();\n\n\t\tm_cursor_id = NC_ARROW;\n\t\tm_cursor_image.reset();\n\t}\n\n\tvoid Cursor::setDrag(ImagePtr image, int32_t drag_offset_x, int32_t drag_offset_y) {\n\t\tassert(image != 0);\n\n\t\tm_cursor_drag_image = image;\n\t\tm_drag_type = CURSOR_IMAGE;\n\t\tm_drag_offset_x = drag_offset_x;\n\t\tm_drag_offset_y = drag_offset_y;\n\n\t\tm_cursor_drag_animation.reset();\n\t}\n\n\tvoid Cursor::setDrag(AnimationPtr anim, int32_t drag_offset_x, int32_t drag_offset_y) {\n\t\tassert(anim != 0);\n\n\t\tm_cursor_drag_animation = anim;\n\t\tm_drag_type = CURSOR_ANIMATION;\n\t\tm_drag_offset_x = drag_offset_x;\n\t\tm_drag_offset_y = drag_offset_y;\n\n\t\tm_drag_animtime = m_timemanager->getTime();\n\n\t\tm_cursor_drag_image.reset();\n\t}\n\n\tvoid Cursor::resetDrag() {\n\t\tm_drag_type = CURSOR_NONE;\n\n\t\tm_drag_animtime = 0;\n\t\tm_drag_offset_x = 0;\n\t\tm_drag_offset_y = 0;\n\n\t\tm_cursor_drag_animation.reset();\n\t\tm_cursor_drag_image.reset();\n\t}\n\n void Cursor::setPosition(uint32_t x, uint32_t y) {\n\t\tm_mx = x;\n\t\tm_my = y;\n\t\tSDL_WarpMouseInWindow(RenderBackend::instance()->getWindow(), m_mx, m_my);\n\t}\n\n void Cursor::getPosition(int32_t* x, int32_t* y) {\n *x = m_mx;\n *y = m_my;\n }\n\n\tvoid Cursor::invalidate() {\n\t\tif (m_native_cursor != NULL) {\n\t\t\tSDL_FreeCursor(m_native_cursor);\n\t\t\tm_native_cursor = NULL;\n\t\t\tm_native_cursor_image.reset();\n\n\t\t\tm_invalidated = true;\n\t\t}\n\t}\n\n\tvoid Cursor::draw() {\n\t\tif (m_invalidated) {\n\t\t\tif (m_cursor_type == CURSOR_NATIVE ) {\n\t\t\t\tset(m_cursor_id);\n\t\t\t}\n\t\t\telse if (m_native_image_cursor_enabled) {\n\t\t\t\tif (m_cursor_type == CURSOR_IMAGE ) {\n\t\t\t\t\tset(m_cursor_image);\n\t\t\t\t}\n\t\t\t\telse if (m_cursor_type == CURSOR_ANIMATION ) {\n\t\t\t\t\tset(m_cursor_animation);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tm_invalidated = false;\n\t\t}\n\n\t\tSDL_GetMouseState(&m_mx, &m_my);\n\t\tif ((m_cursor_type == CURSOR_NATIVE) && (m_drag_type == CURSOR_NONE)) {\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ render possible drag image\n\t\tImagePtr img;\n\t\tif (m_drag_type == CURSOR_IMAGE) {\n\t\t\timg = m_cursor_drag_image;\n\t\t}\n\t\telse if (m_drag_type == CURSOR_ANIMATION) {\n\t\t\tint32_t animtime = (m_timemanager->getTime() - m_drag_animtime) % m_cursor_drag_animation->getDuration();\n\t\t\timg = m_cursor_drag_animation->getFrameByTimestamp(animtime);\n\t\t}\n\n\t\tif (img != 0) {\n\t\t\tRect area(m_mx + m_drag_offset_x + img->getXShift(), m_my + m_drag_offset_y + img->getYShift(), img->getWidth(), img->getHeight());\n\t\t\tm_renderbackend->pushClipArea(area, false);\n\t\t\timg->render(area);\n\t\t\tm_renderbackend->renderVertexArrays();\n\t\t\tm_renderbackend->popClipArea();\n\t\t}\n\n\t\tImagePtr img2;\n\t\t\/\/ render possible cursor image\n\t\tif (m_cursor_type == CURSOR_IMAGE) {\n\t\t\timg2 = m_cursor_image;\n\t\t}\n\t\telse if (m_cursor_type == CURSOR_ANIMATION) {\n\t\t\tint32_t animtime = (m_timemanager->getTime() - m_animtime) % m_cursor_animation->getDuration();\n\t\t\timg2 = m_cursor_animation->getFrameByTimestamp(animtime);\n\t\t}\n\n\t\tif (img2 != 0) {\n\t\t\tif (m_native_image_cursor_enabled) {\n\t\t\t\tsetNativeImageCursor(img2);\n\t\t\t} else {\n\t\t\t\tRect area(m_mx + img2->getXShift(), m_my + img2->getYShift(), img2->getWidth(), img2->getHeight());\n\t\t\t\tm_renderbackend->pushClipArea(area, false);\n\t\t\t\timg2->render(area);\n\t\t\t\tm_renderbackend->renderVertexArrays();\n\t\t\t\tm_renderbackend->popClipArea();\n\t\t\t}\n\t\t}\n\t}\n\n\tuint32_t Cursor::getNativeId(uint32_t cursor_id) {\n\t\tswitch (cursor_id) {\n\t\t\tcase NC_ARROW:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_ARROW;\n\t\t\tcase NC_IBEAM:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_IBEAM;\n\t\t\tcase NC_WAIT:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_WAIT;\n\t\t\tcase NC_CROSS:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_CROSSHAIR;\n\t\t\tcase NC_WAITARROW:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_WAITARROW;\n\t\t\tcase NC_RESIZENWSE:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_SIZENWSE;\n\t\t\tcase NC_RESIZENESW:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_SIZENESW;\n\t\t\tcase NC_RESIZEWE:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_SIZEWE;\n\t\t\tcase NC_RESIZENS:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_SIZENS;\n\t\t\tcase NC_RESIZEALL:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_SIZEALL;\n\t\t\tcase NC_NO:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_NO;\n\t\t\tcase NC_HAND:\n\t\t\t\treturn SDL_SYSTEM_CURSOR_HAND;\n\t\t}\n\t\treturn cursor_id;\n\t}\n\n\tvoid Cursor::setNativeCursor(uint32_t cursor_id) {\n\t\tcursor_id = getNativeId(cursor_id);\n\t\tSDL_Cursor* cursor = SDL_CreateSystemCursor(static_cast(cursor_id));\n\t\tif (!cursor) {\n\t\t\tFL_WARN(_log, \"No cursor matching cursor_id was found.\");\n\t\t\treturn;\n\t\t}\n\t\tSDL_SetCursor(cursor);\n\t\tif (m_native_cursor != NULL) {\n\t\t\tSDL_FreeCursor(m_native_cursor);\n\t\t}\n\t\tm_native_cursor = cursor;\n\t}\n\n\tvoid Cursor::setNativeImageCursor(ImagePtr image) {\n\t\tif (image == m_native_cursor_image) {\n\t\t\treturn;\n\t\t}\n\n\t\tImagePtr temp_image = image;\n\t\tif (image->isSharedImage()) {\n\t\t\ttemp_image = ImageManager::instance()->create();\n\t\t\ttemp_image->copySubimage(0, 0, image);\n\t\t}\n\n\t\tSDL_Cursor* cursor = SDL_CreateColorCursor(temp_image->getSurface(), -image->getXShift(), -image->getYShift());\n\t\tif (cursor == NULL) {\n\t\t\tFL_WARN(_log, LMsg(\"SDL_CreateColorCursor: \\\"\") << SDL_GetError() << \"\\\". Falling back to software cursor.\");\n\t\t\tif (image->isSharedImage()) {\n\t\t\t\tImageManager::instance()->remove(temp_image);\n\t\t\t}\n\t\t\tsetNativeImageCursorEnabled(false);\n\t\t\treturn;\n\t\t}\n\t\tSDL_SetCursor(cursor);\n\t\tm_native_cursor_image = image;\n\n\t\tif (image->isSharedImage()) {\n\t\t\tImageManager::instance()->remove(temp_image);\n\t\t}\n\t\tif (m_native_cursor != NULL) {\n\t\t\tSDL_FreeCursor(m_native_cursor);\n\t\t}\n\t\tm_native_cursor = cursor;\n\t}\n\n\tvoid Cursor::setNativeImageCursorEnabled(bool native_image_cursor_enabled) {\n\t\tif (m_native_image_cursor_enabled != native_image_cursor_enabled) {\n\t\t\tm_native_image_cursor_enabled = native_image_cursor_enabled;\n\t\t\tif (m_cursor_type == CURSOR_IMAGE ) {\n\t\t\t\tset(m_cursor_image);\n\t\t\t}\n\t\t\telse if (m_cursor_type == CURSOR_ANIMATION ) {\n\t\t\t\tset(m_cursor_animation);\n\t\t\t}\n\t\t}\n\t}\n\n\tbool Cursor::isNativeImageCursorEnabled() const {\n\t\treturn m_native_image_cursor_enabled;\n\t}\n}\n<|endoftext|>"} {"text":"\/\/===- BugDriver.cpp - Top-Level BugPoint class implementation ------------===\/\/\n\/\/\n\/\/ This class contains all of the shared state and information that is used by\n\/\/ the BugPoint tool to track down errors in optimizations. This class is the\n\/\/ main driver class that invokes all sub-functionality.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"BugDriver.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Assembly\/Parser.h\"\n#include \"llvm\/Bytecode\/Reader.h\"\n#include \"llvm\/Transforms\/Utils\/Linker.h\"\n#include \"Support\/CommandLine.h\"\n#include \"Support\/FileUtilities.h\"\n#include \n\n\/\/ Anonymous namespace to define command line options for debugging.\n\/\/\nnamespace {\n \/\/ Output - The user can specify a file containing the expected output of the\n \/\/ program. If this filename is set, it is used as the reference diff source,\n \/\/ otherwise the raw input run through an interpreter is used as the reference\n \/\/ source.\n \/\/\n cl::opt \n OutputFile(\"output\", cl::desc(\"Specify a reference program output \"\n \"(for miscompilation detection)\"));\n\n enum DebugType { DebugCompile, DebugCodegen };\n cl::opt\n DebugMode(\"mode\", cl::desc(\"Debug mode for bugpoint:\"), cl::Prefix,\n cl::values(clEnumValN(DebugCompile, \"compile\", \" Compilation\"),\n clEnumValN(DebugCodegen, \"codegen\", \" Code generation\"),\n 0),\n cl::init(DebugCompile));\n}\n\n\/\/\/ getPassesString - Turn a list of passes into a string which indicates the\n\/\/\/ command line options that must be passed to add the passes.\n\/\/\/\nstd::string getPassesString(const std::vector &Passes) {\n std::string Result;\n for (unsigned i = 0, e = Passes.size(); i != e; ++i) {\n if (i) Result += \" \";\n Result += \"-\";\n Result += Passes[i]->getPassArgument();\n }\n return Result;\n}\n\n\/\/ DeleteFunctionBody - \"Remove\" the function by deleting all of its basic\n\/\/ blocks, making it external.\n\/\/\nvoid DeleteFunctionBody(Function *F) {\n \/\/ delete the body of the function...\n F->deleteBody();\n assert(F->isExternal() && \"This didn't make the function external!\");\n}\n\nBugDriver::BugDriver(const char *toolname)\n : ToolName(toolname), ReferenceOutputFile(OutputFile),\n Program(0), Interpreter(0), cbe(0), gcc(0) {}\n\n\n\/\/\/ ParseInputFile - Given a bytecode or assembly input filename, parse and\n\/\/\/ return it, or return null if not possible.\n\/\/\/\nModule *BugDriver::ParseInputFile(const std::string &InputFilename) const {\n Module *Result = 0;\n try {\n Result = ParseBytecodeFile(InputFilename);\n if (!Result && !(Result = ParseAssemblyFile(InputFilename))){\n std::cerr << ToolName << \": could not read input file '\"\n << InputFilename << \"'!\\n\";\n }\n } catch (const ParseException &E) {\n std::cerr << ToolName << \": \" << E.getMessage() << \"\\n\";\n Result = 0;\n }\n return Result;\n}\n\n\/\/ This method takes the specified list of LLVM input files, attempts to load\n\/\/ them, either as assembly or bytecode, then link them together. It returns\n\/\/ true on failure (if, for example, an input bytecode file could not be\n\/\/ parsed), and false on success.\n\/\/\nbool BugDriver::addSources(const std::vector &Filenames) {\n assert(Program == 0 && \"Cannot call addSources multiple times!\");\n assert(!Filenames.empty() && \"Must specify at least on input filename!\");\n\n \/\/ Load the first input file...\n Program = ParseInputFile(Filenames[0]);\n if (Program == 0) return true;\n std::cout << \"Read input file : '\" << Filenames[0] << \"'\\n\";\n\n for (unsigned i = 1, e = Filenames.size(); i != e; ++i) {\n std::auto_ptr M(ParseInputFile(Filenames[i]));\n if (M.get() == 0) return true;\n\n std::cout << \"Linking in input file: '\" << Filenames[i] << \"'\\n\";\n std::string ErrorMessage;\n if (LinkModules(Program, M.get(), &ErrorMessage)) {\n std::cerr << ToolName << \": error linking in '\" << Filenames[i] << \"': \"\n << ErrorMessage << \"\\n\";\n return true;\n }\n }\n\n std::cout << \"*** All input ok\\n\";\n\n \/\/ All input files read successfully!\n return false;\n}\n\n\n\n\/\/\/ run - The top level method that is invoked after all of the instance\n\/\/\/ variables are set up from command line arguments.\n\/\/\/\nbool BugDriver::run() {\n \/\/ The first thing that we must do is determine what the problem is. Does the\n \/\/ optimization series crash the compiler, or does it produce illegal code? We\n \/\/ make the top-level decision by trying to run all of the passes on the the\n \/\/ input program, which should generate a bytecode file. If it does generate\n \/\/ a bytecode file, then we know the compiler didn't crash, so try to diagnose\n \/\/ a miscompilation.\n \/\/\n std::cout << \"Running selected passes on program to test for crash: \";\n if (runPasses(PassesToRun))\n return debugCrash();\n\n std::cout << \"Checking for a miscompilation...\\n\";\n\n \/\/ Set up the execution environment, selecting a method to run LLVM bytecode.\n if (initializeExecutionEnvironment()) return true;\n\n \/\/ Run the raw input to see where we are coming from. If a reference output\n \/\/ was specified, make sure that the raw output matches it. If not, it's a\n \/\/ problem in the front-end or the code generator.\n \/\/\n bool CreatedOutput = false;\n if (ReferenceOutputFile.empty()) {\n std::cout << \"Generating reference output from raw program...\";\n if (DebugCodegen) {\n ReferenceOutputFile = executeProgramWithCBE(\"bugpoint.reference.out\");\n } else {\n ReferenceOutputFile = executeProgram(\"bugpoint.reference.out\");\n }\n CreatedOutput = true;\n std::cout << \"Reference output is: \" << ReferenceOutputFile << \"\\n\";\n } \n\n bool Result;\n switch (DebugMode) {\n default: assert(0 && \"Bad value for DebugMode!\");\n case DebugCompile:\n std::cout << \"\\n*** Debugging miscompilation!\\n\";\n Result = debugMiscompilation();\n break;\n case DebugCodegen:\n std::cout << \"Debugging code generator problem!\\n\";\n Result = debugCodeGenerator();\n }\n\n if (CreatedOutput) removeFile(ReferenceOutputFile);\n return Result;\n}\n\nvoid BugDriver::PrintFunctionList(const std::vector &Funcs)\n{\n for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {\n if (i) std::cout << \", \";\n std::cout << Funcs[i]->getName();\n }\n}\nUnbreak code generator debug mode\/\/===- BugDriver.cpp - Top-Level BugPoint class implementation ------------===\/\/\n\/\/\n\/\/ This class contains all of the shared state and information that is used by\n\/\/ the BugPoint tool to track down errors in optimizations. This class is the\n\/\/ main driver class that invokes all sub-functionality.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"BugDriver.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Assembly\/Parser.h\"\n#include \"llvm\/Bytecode\/Reader.h\"\n#include \"llvm\/Transforms\/Utils\/Linker.h\"\n#include \"Support\/CommandLine.h\"\n#include \"Support\/FileUtilities.h\"\n#include \n\n\/\/ Anonymous namespace to define command line options for debugging.\n\/\/\nnamespace {\n \/\/ Output - The user can specify a file containing the expected output of the\n \/\/ program. If this filename is set, it is used as the reference diff source,\n \/\/ otherwise the raw input run through an interpreter is used as the reference\n \/\/ source.\n \/\/\n cl::opt \n OutputFile(\"output\", cl::desc(\"Specify a reference program output \"\n \"(for miscompilation detection)\"));\n\n enum DebugType { DebugCompile, DebugCodegen };\n cl::opt\n DebugMode(\"mode\", cl::desc(\"Debug mode for bugpoint:\"), cl::Prefix,\n cl::values(clEnumValN(DebugCompile, \"compile\", \" Compilation\"),\n clEnumValN(DebugCodegen, \"codegen\", \" Code generation\"),\n 0),\n cl::init(DebugCompile));\n}\n\n\/\/\/ getPassesString - Turn a list of passes into a string which indicates the\n\/\/\/ command line options that must be passed to add the passes.\n\/\/\/\nstd::string getPassesString(const std::vector &Passes) {\n std::string Result;\n for (unsigned i = 0, e = Passes.size(); i != e; ++i) {\n if (i) Result += \" \";\n Result += \"-\";\n Result += Passes[i]->getPassArgument();\n }\n return Result;\n}\n\n\/\/ DeleteFunctionBody - \"Remove\" the function by deleting all of its basic\n\/\/ blocks, making it external.\n\/\/\nvoid DeleteFunctionBody(Function *F) {\n \/\/ delete the body of the function...\n F->deleteBody();\n assert(F->isExternal() && \"This didn't make the function external!\");\n}\n\nBugDriver::BugDriver(const char *toolname)\n : ToolName(toolname), ReferenceOutputFile(OutputFile),\n Program(0), Interpreter(0), cbe(0), gcc(0) {}\n\n\n\/\/\/ ParseInputFile - Given a bytecode or assembly input filename, parse and\n\/\/\/ return it, or return null if not possible.\n\/\/\/\nModule *BugDriver::ParseInputFile(const std::string &InputFilename) const {\n Module *Result = 0;\n try {\n Result = ParseBytecodeFile(InputFilename);\n if (!Result && !(Result = ParseAssemblyFile(InputFilename))){\n std::cerr << ToolName << \": could not read input file '\"\n << InputFilename << \"'!\\n\";\n }\n } catch (const ParseException &E) {\n std::cerr << ToolName << \": \" << E.getMessage() << \"\\n\";\n Result = 0;\n }\n return Result;\n}\n\n\/\/ This method takes the specified list of LLVM input files, attempts to load\n\/\/ them, either as assembly or bytecode, then link them together. It returns\n\/\/ true on failure (if, for example, an input bytecode file could not be\n\/\/ parsed), and false on success.\n\/\/\nbool BugDriver::addSources(const std::vector &Filenames) {\n assert(Program == 0 && \"Cannot call addSources multiple times!\");\n assert(!Filenames.empty() && \"Must specify at least on input filename!\");\n\n \/\/ Load the first input file...\n Program = ParseInputFile(Filenames[0]);\n if (Program == 0) return true;\n std::cout << \"Read input file : '\" << Filenames[0] << \"'\\n\";\n\n for (unsigned i = 1, e = Filenames.size(); i != e; ++i) {\n std::auto_ptr M(ParseInputFile(Filenames[i]));\n if (M.get() == 0) return true;\n\n std::cout << \"Linking in input file: '\" << Filenames[i] << \"'\\n\";\n std::string ErrorMessage;\n if (LinkModules(Program, M.get(), &ErrorMessage)) {\n std::cerr << ToolName << \": error linking in '\" << Filenames[i] << \"': \"\n << ErrorMessage << \"\\n\";\n return true;\n }\n }\n\n std::cout << \"*** All input ok\\n\";\n\n \/\/ All input files read successfully!\n return false;\n}\n\n\n\n\/\/\/ run - The top level method that is invoked after all of the instance\n\/\/\/ variables are set up from command line arguments.\n\/\/\/\nbool BugDriver::run() {\n \/\/ The first thing that we must do is determine what the problem is. Does the\n \/\/ optimization series crash the compiler, or does it produce illegal code? We\n \/\/ make the top-level decision by trying to run all of the passes on the the\n \/\/ input program, which should generate a bytecode file. If it does generate\n \/\/ a bytecode file, then we know the compiler didn't crash, so try to diagnose\n \/\/ a miscompilation.\n \/\/\n if (!PassesToRun.empty()) {\n std::cout << \"Running selected passes on program to test for crash: \";\n if (runPasses(PassesToRun))\n return debugCrash();\n }\n\n std::cout << \"Checking for a miscompilation...\\n\";\n\n \/\/ Set up the execution environment, selecting a method to run LLVM bytecode.\n if (initializeExecutionEnvironment()) return true;\n\n \/\/ Run the raw input to see where we are coming from. If a reference output\n \/\/ was specified, make sure that the raw output matches it. If not, it's a\n \/\/ problem in the front-end or the code generator.\n \/\/\n bool CreatedOutput = false;\n if (ReferenceOutputFile.empty()) {\n std::cout << \"Generating reference output from raw program...\";\n if (DebugCodegen) {\n ReferenceOutputFile = executeProgramWithCBE(\"bugpoint.reference.out\");\n } else {\n ReferenceOutputFile = executeProgram(\"bugpoint.reference.out\");\n }\n CreatedOutput = true;\n std::cout << \"Reference output is: \" << ReferenceOutputFile << \"\\n\";\n } \n\n bool Result;\n switch (DebugMode) {\n default: assert(0 && \"Bad value for DebugMode!\");\n case DebugCompile:\n std::cout << \"\\n*** Debugging miscompilation!\\n\";\n Result = debugMiscompilation();\n break;\n case DebugCodegen:\n std::cout << \"Debugging code generator problem!\\n\";\n Result = debugCodeGenerator();\n }\n\n if (CreatedOutput) removeFile(ReferenceOutputFile);\n return Result;\n}\n\nvoid BugDriver::PrintFunctionList(const std::vector &Funcs)\n{\n for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {\n if (i) std::cout << \", \";\n std::cout << Funcs[i]->getName();\n }\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Logarithm.cpp\n\/\/ Calculator\n\/\/\n\/\/ Created by Gavin Scheele on 3\/27\/14.\n\/\/ Copyright (c) 2014 Gavin Scheele. All rights reserved.\n\/\/\n\n#include \"Logarithm.h\"\nusing namespace std;\n#include \n\n\/\/constructor for int base with an int operand\nLogarithm::Logarithm(int base, int operand){\n if (operand == 0){\n throw runtime_error(\"Logarithms of 0 are undefined.\");\n }\n if (operand < 0) {\n throw runtime_error(\"Logarithms of negative numbers are undefined.\");\n }\n this->type = \"logarithm\";\n this->base = base;\n this->operand = operand;\n this->eOperand = new Integer(operand);\n this->eBase = new Integer(base);\n\n}\n\n\/\/constructor for expression base and or expression operand\nLogarithm::Logarithm(Expression* eBase, Expression* eOperand){\n this->type = \"logarithm\";\n this->eBase = eBase;\n this->eOperand = eOperand;\n\n}\n\/\/get-set methods below\nint Logarithm::getBase(){\n\treturn base;\n}\nint Logarithm::getOperand(){\n\treturn operand;\n}\nExpression* Logarithm::getEBase(){\n\treturn eBase;\n}\nExpression* Logarithm::getEOperand(){\n\treturn eOperand;\n}\n\nvoid Logarithm::setBase(Expression* x){\n\tthis->eBase = x;\n}\nvoid Logarithm::setOperand(Expression* x){\n\tthis->eOperand = x;\n}\n\nLogarithm::~Logarithm(){\n delete this;\n}\n\nExpression* Logarithm::simplifyOperand(){\n Expression* e = this->eOperand;\n e->exp = e->toString();\n string operand1 = e->exp;\n cout< position;\n vector symbols;\n int length = operand1.length();\n for(int i = 0; i < length; i++)\n {\n if(operand1.at(i)== (asterick) || operand1.at(i)== slash){\n position.push_back(i);\n position.push_back(operand1.at(i));\n cout< logs;\n for(int j =0; j<=position.size();j++){\n int positionofop = position.at(j);\n string number = operand1.substr(j,positionofop-2);\n Solver* s = new Solver();\n Expression* e = s->bindToExpressionType(number);\n Logarithm* simpleLog = (Logarithm*)e;\n simpleLog->simplify();\n logs.push_back(e);\n\n }\n\n Expression* endlog = new Integer(0);\n endlog->type = \"multiple\";\n stringstream endlogexp;\n for(int k = 0; kexp = endlogexp.str();\n return endlog;\n\n\n\n}\nExpression* Logarithm::simplify(){\n\n\n if(eOperand->type == \"euler\")\n {\n\n if(eBase->type == \"euler\"){\n Integer* answer = new Integer(1);\n return answer;\n }\n else{\n Logarithm* answer = new Logarithm(eBase, eOperand);\n return answer;\n }\n\n }\n\n if(eOperand->type == \"pi\")\n {\n if(eBase->type == \"pi\"){\n Integer* answer = new Integer(1);\n return answer;\n }\n else{\n Logarithm* answer = new Logarithm(eBase, eOperand);\n return answer;\n }\n\n }\n\n if(eOperand->type == \"integer\"){\n vector primefactors = primeFactorization(operand);\/\/Create a vector of all the prime factors of the operand\n size_t size1 = primefactors.size();\/\/gets the size of this vector\n vector seperatedLogs(size1);\/\/creates another vector of type expression to save all of the separated Logs has the same size of the number of prime factors\n\n\n for(int i = 0 ; i < size1; i++){\n seperatedLogs.at(i) = new Logarithm(this->eBase, new Integer(primefactors.at(i)));\/\/assigns values to each seperatedlog with the same base and operands of the prime factorization\n }\n\n for(int j= 0; j type == \"logarithm\") {\/\/checks to see if the value at seperated log is a log type\n Logarithm* a = (Logarithm *)seperatedLogs.at(j);\n Logarithm* log = new Logarithm(a->getEBase(),a->getEOperand());\n if(log->eBase->type == log->eOperand->type && log->eBase->type == \"integer\"){ \/\/makes sure the ebase and eoperand are of the same type\n Integer* b = (Integer *)(log->eBase);\n Integer* c = (Integer *)(log->eOperand);\n if (b->getValue() == c->getValue()){\/\/ checks to see if the ebase and the eOperand are the same\n Integer* inte= new Integer(1);\/\/returns one if they are the same\n seperatedLogs.at(j) = inte;\/\/assigns 1 to the value of seperated log at j\n\n\n }\n }\n \t}\n \t}\n\n\n Expression * answer;\/\/creates a new variable called answer\n if(size1 >= 2){\/\/ if the size is two or higher\n answer = seperatedLogs.at(0)->add(seperatedLogs.at(1));\/\/ add the first two together\n }\n else{\/\/if the size is just 1\n answer = seperatedLogs.at(0);\/\/the answer is the first one\n }\n\n\n for(int k = 2; kadd(seperatedLogs.at(k));\/\/keeps adding elements of seperated log to answer\n\n }\n Integer* size2 = new Integer((int)size1);\n Integer* answerint = (Integer *)answer;\n if(answerint->getValue()==size2->getValue())\n {\n return answer;\n }\n else if(size1 == 1){\n return this;\n }\n else\n {\n Expression* e = new Integer(answerint->getValue());\n e->type = \"multiple\";\n stringstream s;\n for(int l = 0; lexp = s.str();\n \/\/cout<exp;\n return e;\n }\n }\n\n throw runtime_error(\"invalid entry\");\n return this;\n}\n\n\/\/creates vector of prime factors of n to be used in the simplify method\nvector Logarithm::primeFactorization(int n) {\n int k = 0;\n vector factors;\n while (n%2 == 0) {\n factors.push_back(2);\n n = n\/2;\n }\n for (int i = 3; i <= sqrt(n); i = i + 2) {\n while (n%i == 0) {\n factors.push_back(i);\n k++;\n n = n\/i;\n }\n }\n if (n > 2) {\n factors.push_back(n);\n }\n return factors;\n}\n\nExpression* Logarithm::add(Expression* a){\n return this;\n}\nExpression* Logarithm::subtract(Expression* a){\n Logarithm* c = this;\n Logarithm* b = (Logarithm *) a;\n if(c->eBase->type == b->eBase->type && c->eOperand->type == b->eOperand->type) {\n \tif (c->getEBase() == b->getEBase() && c->getEOperand() == b->getEOperand()){\n \t\tExpression* answer = new Integer(0);\n \t\treturn answer;\n \t}\n }\n return c;\n}\n\nExpression* Logarithm::multiply(Expression* a){\n Logarithm* c = this;\n Logarithm* b = (Logarithm *) a;\n if(c->eBase->type == b->eBase->type && c->eOperand->type == b->eOperand->type) {\n \tif (c->getEBase() == b->getEBase() && c->getEOperand() == b->getEOperand()){\n \t\tExponential* answer = new Exponential(this, new Rational(2,1));\n \t\treturn answer;\n \t}\n }\n return c;\n}\nExpression* Logarithm::divide(Expression* a){\/\/this set up is \"this\" divided by a so if this = log11 and a = log3 it would be log11\/log3\n Logarithm* c = this;\n Logarithm* b = (Logarithm *) a;\n if(c->eBase->type == b->eBase->type && c->getEBase() == b->getEBase()) {\n Expression* numeratorOperand = c->getEOperand();\n Expression* denominatorOperand = b->getEOperand();\n Logarithm* answer = new Logarithm(denominatorOperand, numeratorOperand);\n return answer;\n }\n\n return c;\n}\nostream& Logarithm::print(std::ostream& output) const{\n output << \"Log_\" << *eBase << \":\" << *eOperand<< endl;\n\n return output;\n}\nstring Logarithm::toString(){\n stringstream ss;\n ss << \"Log_\" << *this->eBase << \":\" << *this->eOperand;\n\n return ss.str();\n};\nstuff\/\/\n\/\/ Logarithm.cpp\n\/\/ Calculator\n\/\/\n\/\/ Created by Gavin Scheele on 3\/27\/14.\n\/\/ Copyright (c) 2014 Gavin Scheele. All rights reserved.\n\/\/\n\n#include \"Logarithm.h\"\nusing namespace std;\n#include \n\n\/\/constructor for int base with an int operand\nLogarithm::Logarithm(int base, int operand){\n if (operand == 0){\n throw runtime_error(\"Logarithms of 0 are undefined.\");\n }\n if (operand < 0) {\n throw runtime_error(\"Logarithms of negative numbers are undefined.\");\n }\n this->type = \"logarithm\";\n this->base = base;\n this->operand = operand;\n this->eOperand = new Integer(operand);\n this->eBase = new Integer(base);\n\n}\n\n\/\/constructor for expression base and or expression operand\nLogarithm::Logarithm(Expression* eBase, Expression* eOperand){\n this->type = \"logarithm\";\n this->eBase = eBase;\n this->eOperand = eOperand;\n\n}\n\/\/get-set methods below\nint Logarithm::getBase(){\n\treturn base;\n}\nint Logarithm::getOperand(){\n\treturn operand;\n}\nExpression* Logarithm::getEBase(){\n\treturn eBase;\n}\nExpression* Logarithm::getEOperand(){\n\treturn eOperand;\n}\n\nvoid Logarithm::setBase(Expression* x){\n\tthis->eBase = x;\n}\nvoid Logarithm::setOperand(Expression* x){\n\tthis->eOperand = x;\n}\n\nLogarithm::~Logarithm(){\n delete this;\n}\n\nExpression* Logarithm::simplifyOperand(){\n Expression* e = this->eOperand;\n e->exp = e->toString();\n string operand1 = e->exp;\n cout< position;\n vector symbols;\n int length = operand1.length();\n for(int i = 0; i < length; i++)\n {\n if(operand1.at(i)== (asterick) || operand1.at(i)== slash){\n position.push_back(i);\n position.push_back(operand1.at(i));\n cout< logs;\n for(int j =0; j<=position.size();j++){\n int positionofop = position.at(j);\n string number = operand1.substr(j,positionofop-2);\n Solver* s = new Solver();\n Expression* e = s->bindToExpressionType(number);\n Logarithm* simpleLog = (Logarithm*)e;\n simpleLog->simplify();\n logs.push_back(e);\n\n }\n\n Expression* endlog = new Integer(0);\n endlog->type = \"multiple\";\n stringstream endlogexp;\n for(int k = 0; kexp = endlogexp.str();\n return endlog;\n\n\n\n}\nExpression* Logarithm::simplify(){\n\n\n if(eOperand->type == \"euler\")\n {\n\n if(eBase->type == \"euler\"){\n Integer* answer = new Integer(1);\n return answer;\n }\n else{\n Logarithm* answer = new Logarithm(eBase, eOperand);\n return answer;\n }\n\n }\n\n if(eOperand->type == \"pi\")\n {\n if(eBase->type == \"pi\"){\n Integer* answer = new Integer(1);\n return answer;\n }\n else{\n Logarithm* answer = new Logarithm(eBase, eOperand);\n return answer;\n }\n\n }\n\n if(eOperand->type == \"integer\"){\n\n vector primefactors = primeFactorization(operand);\/\/Create a vector of all the prime factors of the operand\n size_t size1 = primefactors.size();\/\/gets the size of this vector\n vector seperatedLogs(size1);\/\/creates another vector of type expression to save all of the separated Logs has the same size of the number of prime factors\n\n\n for(int i = 0 ; i < size1; i++){\n seperatedLogs.at(i) = new Logarithm(this->eBase, new Integer(primefactors.at(i)));\/\/assigns values to each seperatedlog with the same base and operands of the prime factorization\n }\n\n\n for(int j= 0; j type == \"logarithm\") {\/\/checks to see if the value at seperated log is a log type\n Logarithm* a = (Logarithm *)seperatedLogs.at(j);\n Logarithm* log = new Logarithm(a->getEBase(),a->getEOperand());\n if(log->eBase->type == log->eOperand->type && log->eBase->type == \"integer\"){ \/\/makes sure the ebase and eoperand are of the same type\n Integer* b = (Integer *)(log->eBase);\n Integer* c = (Integer *)(log->eOperand);\n if (b->getValue() == c->getValue()){\/\/ checks to see if the ebase and the eOperand are the same\n Integer* inte= new Integer(1);\/\/returns one if they are the same\n seperatedLogs.at(j) = inte;\/\/assigns 1 to the value of seperated log at j\n\n\n }\n }\n \t}\n \t}\n\n\n Expression * answer;\/\/creates a new variable called answer\n if(size1 >= 2){\/\/ if the size is two or higher\n answer = seperatedLogs.at(0)->add(seperatedLogs.at(1));\/\/ add the first two together\n }\n else{\/\/if the size is just 1\n answer = seperatedLogs.at(0);\/\/the answer is the first one\n }\n\n\n for(int k = 2; kadd(seperatedLogs.at(k));\/\/keeps adding elements of seperated log to answer\n\n }\n Integer* size2 = new Integer((int)size1);\n Integer* answerint = (Integer *)answer;\n if(answerint->getValue()==size2->getValue())\n {\n return answer;\n }\n else if(size1 == 1){\n return this;\n }\n else\n {\n Expression* e = new Integer(answerint->getValue());\n e->type = \"multiple\";\n stringstream s;\n for(int l = 0; lexp = s.str();\n cout<exp;\n return e;\n }\n }\n\n throw runtime_error(\"invalid entry\");\n return this;\n}\n\n\/\/creates vector of prime factors of n to be used in the simplify method\nvector Logarithm::primeFactorization(int n) {\n int k = 0;\n vector factors;\n while (n%2 == 0) {\n factors.push_back(2);\n n = n\/2;\n }\n for (int i = 3; i <= sqrt(n); i = i + 2) {\n while (n%i == 0) {\n factors.push_back(i);\n k++;\n n = n\/i;\n }\n }\n if (n > 2) {\n factors.push_back(n);\n }\n return factors;\n}\n\nExpression* Logarithm::add(Expression* a){\n return this;\n}\nExpression* Logarithm::subtract(Expression* a){\n Logarithm* c = this;\n Logarithm* b = (Logarithm *) a;\n if(c->eBase->type == b->eBase->type && c->eOperand->type == b->eOperand->type) {\n \tif (c->getEBase() == b->getEBase() && c->getEOperand() == b->getEOperand()){\n \t\tExpression* answer = new Integer(0);\n \t\treturn answer;\n \t}\n }\n return c;\n}\n\nExpression* Logarithm::multiply(Expression* a){\n Logarithm* c = this;\n Logarithm* b = (Logarithm *) a;\n if(c->eBase->type == b->eBase->type && c->eOperand->type == b->eOperand->type) {\n \tif (c->getEBase() == b->getEBase() && c->getEOperand() == b->getEOperand()){\n \t\tExponential* answer = new Exponential(this, new Rational(2,1));\n \t\treturn answer;\n \t}\n }\n return c;\n}\nExpression* Logarithm::divide(Expression* a){\/\/this set up is \"this\" divided by a so if this = log11 and a = log3 it would be log11\/log3\n Logarithm* c = this;\n Logarithm* b = (Logarithm *) a;\n if(c->eBase->type == b->eBase->type && c->getEBase() == b->getEBase()) {\n Expression* numeratorOperand = c->getEOperand();\n Expression* denominatorOperand = b->getEOperand();\n Logarithm* answer = new Logarithm(denominatorOperand, numeratorOperand);\n return answer;\n }\n\n return c;\n}\nostream& Logarithm::print(std::ostream& output) const{\n output << \"Log_\" << *eBase << \":\" << *eOperand<< endl;\n\n return output;\n}\nstring Logarithm::toString(){\n stringstream ss;\n ss << \"Log_\" << *this->eBase << \":\" << *this->eOperand;\n\n return ss.str();\n};\n<|endoftext|>"} {"text":"\/\/ Copyright 2014 BVLC and contributors.\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"caffe\/proto\/caffe.pb.h\"\n#include \"caffe\/util\/io.hpp\"\n\nusing caffe::Datum;\nusing caffe::BlobProto;\nusing std::max;\n\nint main(int argc, char** argv) {\n ::google::InitGoogleLogging(argv[0]);\n if (argc != 3) {\n LOG(ERROR) << \"Usage: compute_image_mean input_leveldb output_file\";\n return 1;\n }\n\n leveldb::DB* db;\n leveldb::Options options;\n options.create_if_missing = false;\n\n LOG(INFO) << \"Opening leveldb \" << argv[1];\n leveldb::Status status = leveldb::DB::Open(\n options, argv[1], &db);\n CHECK(status.ok()) << \"Failed to open leveldb \" << argv[1];\n\n leveldb::ReadOptions read_options;\n read_options.fill_cache = false;\n leveldb::Iterator* it = db->NewIterator(read_options);\n it->SeekToFirst();\n Datum datum;\n BlobProto sum_blob;\n int count = 0;\n datum.ParseFromString(it->value().ToString());\n sum_blob.set_num(1);\n sum_blob.set_channels(datum.channels());\n sum_blob.set_height(datum.height());\n sum_blob.set_width(datum.width());\n const int data_size = datum.channels() * datum.height() * datum.width();\n int size_in_datum = std::max(datum.data().size(),\n datum.float_data_size());\n for (int i = 0; i < size_in_datum; ++i) {\n sum_blob.add_data(0.);\n }\n LOG(INFO) << \"Starting Iteration\";\n for (it->SeekToFirst(); it->Valid(); it->Next()) {\n \/\/ just a dummy operation\n datum.ParseFromString(it->value().ToString());\n const string& data = datum.data();\n size_in_datum = std::max(datum.data().size(), datum.float_data_size());\n CHECK_EQ(size_in_datum, data_size) << \"Incorrect data field size \" <<\n size_in_datum;\n if (data.size() != 0) {\n for (int i = 0; i < size_in_datum; ++i) {\n sum_blob.set_data(i, sum_blob.data(i) + (uint8_t)data[i]);\n }\n } else {\n for (int i = 0; i < size_in_datum; ++i) {\n sum_blob.set_data(i, sum_blob.data(i) +\n static_cast(datum.float_data(i)));\n }\n }\n ++count;\n if (count % 10000 == 0) {\n LOG(ERROR) << \"Processed \" << count << \" files.\";\n }\n }\n if (count % 10000 != 0) {\n LOG(ERROR) << \"Processed \" << count << \" files.\";\n }\n for (int i = 0; i < sum_blob.data_size(); ++i) {\n sum_blob.set_data(i, sum_blob.data(i) \/ count);\n }\n \/\/ Write to disk\n LOG(INFO) << \"Write to \" << argv[2];\n WriteProtoToBinaryFile(sum_blob, argv[2]);\n\n delete db;\n return 0;\n}\nadd lmdb support for compute_image_mean\/\/ Copyright 2014 BVLC and contributors.\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"caffe\/proto\/caffe.pb.h\"\n#include \"caffe\/util\/io.hpp\"\n\nusing caffe::Datum;\nusing caffe::BlobProto;\nusing std::max;\n\nint main(int argc, char** argv) {\n ::google::InitGoogleLogging(argv[0]);\n if (argc < 3 || argc > 4) {\n LOG(ERROR) << \"Usage: compute_image_mean input_leveldb output_file\"\n << \" db_backend[leveldb or lmdb]\";\n return 1;\n }\n\n string db_backend = \"leveldb\";\n if (argc == 4) {\n db_backend = string(argv[3]);\n }\n\n \/\/ leveldb\n leveldb::DB* db;\n leveldb::Options options;\n options.create_if_missing = false;\n leveldb::Iterator* it;\n \/\/ lmdb\n MDB_env* mdb_env;\n MDB_dbi mdb_dbi;\n MDB_val mdb_key, mdb_value;\n MDB_txn* mdb_txn;\n MDB_cursor* mdb_cursor;\n\n \/\/ Open db\n if (db_backend == \"leveldb\") { \/\/ leveldb\n LOG(INFO) << \"Opening leveldb \" << argv[1];\n leveldb::Status status = leveldb::DB::Open(\n options, argv[1], &db);\n CHECK(status.ok()) << \"Failed to open leveldb \" << argv[1];\n leveldb::ReadOptions read_options;\n read_options.fill_cache = false;\n it = db->NewIterator(read_options);\n it->SeekToFirst();\n } else if (db_backend == \"lmdb\") { \/\/ lmdb\n LOG(INFO) << \"Opening lmdb \" << argv[1];\n CHECK_EQ(mdb_env_create(&mdb_env), MDB_SUCCESS) << \"mdb_env_create failed\";\n CHECK_EQ(mdb_env_set_mapsize(mdb_env, 1099511627776), MDB_SUCCESS); \/\/ 1TB\n CHECK_EQ(mdb_env_open(mdb_env, argv[1], MDB_RDONLY, 0664),\n MDB_SUCCESS) << \"mdb_env_open failed\";\n CHECK_EQ(mdb_txn_begin(mdb_env, NULL, MDB_RDONLY, &mdb_txn), MDB_SUCCESS)\n << \"mdb_txn_begin failed\";\n CHECK_EQ(mdb_open(mdb_txn, NULL, 0, &mdb_dbi), MDB_SUCCESS)\n << \"mdb_open failed\";\n CHECK_EQ(mdb_cursor_open(mdb_txn, mdb_dbi, &mdb_cursor), MDB_SUCCESS)\n << \"mdb_cursor_open failed\";\n CHECK_EQ(mdb_cursor_get(mdb_cursor, &mdb_key, &mdb_value, MDB_FIRST),\n MDB_SUCCESS);\n } else {\n LOG(FATAL) << \"Unknown db backend \" << db_backend;\n }\n\n Datum datum;\n BlobProto sum_blob;\n int count = 0;\n \/\/ load first datum\n if (db_backend == \"leveldb\") {\n datum.ParseFromString(it->value().ToString());\n } else if (db_backend == \"lmdb\") {\n datum.ParseFromArray(mdb_value.mv_data, mdb_value.mv_size);\n } else {\n LOG(FATAL) << \"Unknown db backend \" << db_backend;\n }\n\n sum_blob.set_num(1);\n sum_blob.set_channels(datum.channels());\n sum_blob.set_height(datum.height());\n sum_blob.set_width(datum.width());\n const int data_size = datum.channels() * datum.height() * datum.width();\n int size_in_datum = std::max(datum.data().size(),\n datum.float_data_size());\n for (int i = 0; i < size_in_datum; ++i) {\n sum_blob.add_data(0.);\n }\n LOG(INFO) << \"Starting Iteration\";\n if (db_backend == \"leveldb\") { \/\/ leveldb\n for (it->SeekToFirst(); it->Valid(); it->Next()) {\n \/\/ just a dummy operation\n datum.ParseFromString(it->value().ToString());\n const string& data = datum.data();\n size_in_datum = std::max(datum.data().size(),\n datum.float_data_size());\n CHECK_EQ(size_in_datum, data_size) << \"Incorrect data field size \" <<\n size_in_datum;\n if (data.size() != 0) {\n for (int i = 0; i < size_in_datum; ++i) {\n sum_blob.set_data(i, sum_blob.data(i) + (uint8_t)data[i]);\n }\n } else {\n for (int i = 0; i < size_in_datum; ++i) {\n sum_blob.set_data(i, sum_blob.data(i) +\n static_cast(datum.float_data(i)));\n }\n }\n ++count;\n if (count % 10000 == 0) {\n LOG(ERROR) << \"Processed \" << count << \" files.\";\n }\n }\n } else if (db_backend == \"lmdb\") { \/\/ lmdb\n CHECK_EQ(mdb_cursor_get(mdb_cursor, &mdb_key, &mdb_value, MDB_FIRST),\n MDB_SUCCESS);\n do {\n \/\/ just a dummy operation\n datum.ParseFromArray(mdb_value.mv_data, mdb_value.mv_size);\n const string& data = datum.data();\n size_in_datum = std::max(datum.data().size(),\n datum.float_data_size());\n CHECK_EQ(size_in_datum, data_size) << \"Incorrect data field size \" <<\n size_in_datum;\n if (data.size() != 0) {\n for (int i = 0; i < size_in_datum; ++i) {\n sum_blob.set_data(i, sum_blob.data(i) + (uint8_t)data[i]);\n }\n } else {\n for (int i = 0; i < size_in_datum; ++i) {\n sum_blob.set_data(i, sum_blob.data(i) +\n static_cast(datum.float_data(i)));\n }\n }\n ++count;\n if (count % 10000 == 0) {\n LOG(ERROR) << \"Processed \" << count << \" files.\";\n }\n } while (mdb_cursor_get(mdb_cursor, &mdb_key, &mdb_value, MDB_NEXT)\n == MDB_SUCCESS);\n } else {\n LOG(FATAL) << \"Unknown db backend \" << db_backend;\n }\n\n if (count % 10000 != 0) {\n LOG(ERROR) << \"Processed \" << count << \" files.\";\n }\n for (int i = 0; i < sum_blob.data_size(); ++i) {\n sum_blob.set_data(i, sum_blob.data(i) \/ count);\n }\n \/\/ Write to disk\n LOG(INFO) << \"Write to \" << argv[2];\n WriteProtoToBinaryFile(sum_blob, argv[2]);\n\n \/\/ Clean up\n if (db_backend == \"leveldb\") {\n delete db;\n } else if (db_backend == \"lmdb\") {\n mdb_cursor_close(mdb_cursor);\n mdb_close(mdb_env, mdb_dbi);\n mdb_txn_abort(mdb_txn);\n mdb_env_close(mdb_env);\n } else {\n LOG(FATAL) << \"Unknown db backend \" << db_backend;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright © 2011 Stéphane Raimbault \n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser Public License for more details.\n *\n * You should have received a copy of the GNU Lesser Public License\n * along with this program. If not, see .\n *\n *\n * This library implements the Modbus protocol.\n * http:\/\/libmodbus.org\/\n *\/\n\n#include \n\n#include \"WProgram.h\"\n#include \"Modbusino.h\"\n\n#define _MODBUS_RTU_SLAVE 0\n#define _MODBUS_RTU_FUNCTION 1\n#define _MODBUS_RTU_PRESET_REQ_LENGTH 6\n#define _MODBUS_RTU_PRESET_RSP_LENGTH 2\n\n#define _MODBUS_RTU_CHECKSUM_LENGTH 2\n\n#define _MODBUSINO_RTU_MAX_ADU_LENGTH 128\n\n\/* Supported function codes *\/\n#define _FC_READ_HOLDING_REGISTERS 0x03\n#define _FC_WRITE_MULTIPLE_REGISTERS 0x10\n\nenum {\n _STEP_FUNCTION = 0x01,\n _STEP_META,\n _STEP_DATA\n};\n\nstatic uint16_t crc16(uint8_t *req, uint8_t req_length)\n{\n uint8_t j;\n uint16_t crc;\n\n crc = 0xFFFF;\n while (req_length--) {\n\tcrc = crc ^ *req++;\n\tfor (j=0; j < 8; j++) {\n\t if (crc & 0x0001)\n\t\tcrc = (crc >> 1) ^ 0xA001;\n\t else\n\t\tcrc = crc >> 1;\n\t}\n }\n\n return (crc << 8 | crc >> 8);\n}\n\nModbusinoSlave::ModbusinoSlave(uint8_t slave) {\n _slave = slave;\n}\n\nvoid ModbusinoSlave::setup(long baud) {\n Serial.begin(baud);\n}\n\nstatic int check_integrity(uint8_t *msg, uint8_t msg_length)\n{\n uint16_t crc_calculated;\n uint16_t crc_received;\n\n if (msg_length < 2)\n\treturn -1;\n\n crc_calculated = crc16(msg, msg_length - 2);\n crc_received = (msg[msg_length - 2] << 8) | msg[msg_length - 1];\n\n \/* Check CRC of msg *\/\n if (crc_calculated == crc_received) {\n return msg_length;\n } else {\n return -1;\n }\n}\n\nstatic int build_response_basis(uint8_t slave, uint8_t function,\n\t\t\t\tuint8_t* rsp)\n{\n rsp[0] = slave;\n rsp[1] = function;\n\n return _MODBUS_RTU_PRESET_RSP_LENGTH;\n}\n\nstatic void send_msg(uint8_t *msg, uint8_t msg_length)\n{\n uint16_t crc = crc16(msg, msg_length);\n\n msg[msg_length++] = crc >> 8;\n msg[msg_length++] = crc & 0x00FF;\n\n Serial.write(msg, msg_length);\n}\n\nstatic uint8_t response_exception(uint8_t slave, uint8_t function,\n\t\t\t\t uint8_t exception_code,\n\t\t\t\t uint8_t *rsp)\n{\n uint8_t rsp_length;\n\n rsp_length = build_response_basis(slave, function + 0x80, rsp);\n\n \/* Positive exception code *\/\n rsp[rsp_length++] = exception_code;\n\n return rsp_length;\n}\n\nstatic void flush(void)\n{\n \/* Wait a moment to receive the remaining garbage *\/\n while (Serial.available()) {\n\tSerial.flush();\n\tdelay(3);\n }\n}\n\nstatic int receive(uint8_t *req, uint8_t _slave)\n{\n uint8_t i;\n uint8_t length_to_read;\n uint8_t req_index;\n uint8_t step;\n uint8_t function;\n\n \/* We need to analyse the message step by step. At the first step, we want\n * to reach the function code because all packets contain this\n * information. *\/\n step = _STEP_FUNCTION;\n length_to_read = _MODBUS_RTU_FUNCTION + 1;\n\n req_index = 0;\n while (length_to_read != 0) {\n\n\t\/* The timeout is defined to ~10 ms between each bytes. Precision is\n\t not that important so I rather to avoid millis() to apply the KISS\n\t principle (millis overflows after 50 days, etc) *\/\n if (!Serial.available()) {\n\t i = 0;\n\t while (!Serial.available()) {\n\t\tdelay(1);\n\t\tif (++i == 10) {\n\t\t \/* Too late, bye *\/\n\t\t return -1;\n\t\t}\n\t }\n }\n\n\treq[req_index] = Serial.read();\n\n \/* Moves the pointer to receive other data *\/\n\treq_index++;\n\n \/* Computes remaining bytes *\/\n length_to_read--;\n\n if (length_to_read == 0) {\n switch (step) {\n case _STEP_FUNCTION:\n \/* Function code position *\/\n\t\tfunction = req[_MODBUS_RTU_FUNCTION];\n\t\tif (function == _FC_READ_HOLDING_REGISTERS) {\n\t\t length_to_read = 4;\n\t\t} else if (function == _FC_WRITE_MULTIPLE_REGISTERS) {\n\t\t length_to_read = 5;\n\t\t} else {\n\t\t \/* Wait a moment to receive the remaining garbage *\/\n\t\t flush();\n\t\t if (_slave == req[_MODBUS_RTU_SLAVE]) {\n\t\t\t\/* It's for me so send an exception (reuse req) *\/\n\t\t\tuint8_t rsp_length = response_exception(\n\t\t\t _slave, function,\n\t\t\t MODBUS_EXCEPTION_ILLEGAL_FUNCTION,\n\t\t\t req);\n\t\t\tsend_msg(req, rsp_length);\n\t\t\treturn - 1 - MODBUS_EXCEPTION_ILLEGAL_FUNCTION;\n\t\t }\n\n\t\t return -1;\n\t\t}\n\t\tstep = _STEP_META;\n\t\tbreak;\n case _STEP_META:\n\t\tlength_to_read = _MODBUS_RTU_CHECKSUM_LENGTH;\n\n\t\tif (function == _FC_WRITE_MULTIPLE_REGISTERS)\n\t\t length_to_read += req[_MODBUS_RTU_FUNCTION + 5];\n\n if ((req_index + length_to_read) > _MODBUSINO_RTU_MAX_ADU_LENGTH) {\n\t\t flush();\n\t\t if (_slave == req[_MODBUS_RTU_SLAVE]) {\n\t\t\t\/* It's for me so send an exception (reuse req) *\/\n\t\t\tuint8_t rsp_length = response_exception(\n\t\t\t _slave, function,\n\t\t\t MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE,\n\t\t\t req);\n\t\t\tsend_msg(req, rsp_length);\n\t\t\treturn - 1 - MODBUS_EXCEPTION_ILLEGAL_FUNCTION;\n\t\t }\n\t\t return -1;\n }\n step = _STEP_DATA;\n break;\n default:\n break;\n }\n }\n }\n\n return check_integrity(req, req_index);\n}\n\n\nstatic void reply(uint16_t *tab_reg, uint8_t nb_reg,\n\t\t uint8_t *req, uint8_t req_length, uint8_t _slave)\n{\n uint8_t slave = req[_MODBUS_RTU_SLAVE];\n uint8_t function = req[_MODBUS_RTU_FUNCTION];\n uint16_t address = (req[_MODBUS_RTU_FUNCTION + 1] << 8) +\n\treq[_MODBUS_RTU_FUNCTION + 2];\n uint16_t nb = (req[_MODBUS_RTU_FUNCTION + 3] << 8) +\n\treq[_MODBUS_RTU_FUNCTION + 4];\n uint8_t rsp[_MODBUSINO_RTU_MAX_ADU_LENGTH];\n uint8_t rsp_length = 0;\n\n if (slave != _slave) {\n\treturn;\n }\n\n if (address + nb > nb_reg) {\n\trsp_length = response_exception(\n\t slave, function,\n\t MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp);\n }\n\n req_length -= _MODBUS_RTU_CHECKSUM_LENGTH;\n\n if (function == _FC_READ_HOLDING_REGISTERS) {\n\tuint8_t i;\n\trsp_length = build_response_basis(slave, function, rsp);\n\trsp[rsp_length++] = nb << 1;\n\tfor (i = address; i < address + nb; i++) {\n\t rsp[rsp_length++] = tab_reg[i] >> 8;\n\t rsp[rsp_length++] = tab_reg[i] & 0xFF;\n\t}\n } else {\n\tint i, j;\n\n\tfor (i = address, j = 6; i < address + nb; i++, j += 2) {\n\t \/* 6 and 7 = first value *\/\n\t tab_reg[i] = (req[_MODBUS_RTU_FUNCTION + j] << 8) +\n\t\treq[_MODBUS_RTU_FUNCTION + j + 1];\n\t}\n\n\trsp_length = build_response_basis(slave, function, rsp);\n\t\/* 4 to copy the address (2) and the no. of registers *\/\n\tmemcpy(rsp + rsp_length, req + rsp_length, 4);\n\trsp_length += 4;\n }\n\n send_msg(rsp, rsp_length);\n}\n\nint ModbusinoSlave::loop(uint16_t* tab_reg, uint8_t nb_reg)\n{\n int rc;\n uint8_t req[_MODBUSINO_RTU_MAX_ADU_LENGTH];\n\n if (Serial.available()) {\n\trc = receive(req, _slave);\n\tif (rc > 0) {\n\t reply(tab_reg, nb_reg, req, rc, _slave);\n\t}\n }\n\n \/* Returns a positive value if successful,\n 0 if a slave filtering has occured,\n -1 if an undefined error has occured,\n -2 for MODBUS_EXCEPTION_ILLEGAL_FUNCTION\n etc *\/\n return rc;\n}\nAvoid getting stuck on a line saturated by garbage\/*\n * Copyright © 2011 Stéphane Raimbault \n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser Public License for more details.\n *\n * You should have received a copy of the GNU Lesser Public License\n * along with this program. If not, see .\n *\n *\n * This library implements the Modbus protocol.\n * http:\/\/libmodbus.org\/\n *\/\n\n#include \n\n#include \"WProgram.h\"\n#include \"Modbusino.h\"\n\n#define _MODBUS_RTU_SLAVE 0\n#define _MODBUS_RTU_FUNCTION 1\n#define _MODBUS_RTU_PRESET_REQ_LENGTH 6\n#define _MODBUS_RTU_PRESET_RSP_LENGTH 2\n\n#define _MODBUS_RTU_CHECKSUM_LENGTH 2\n\n#define _MODBUSINO_RTU_MAX_ADU_LENGTH 128\n\n\/* Supported function codes *\/\n#define _FC_READ_HOLDING_REGISTERS 0x03\n#define _FC_WRITE_MULTIPLE_REGISTERS 0x10\n\nenum {\n _STEP_FUNCTION = 0x01,\n _STEP_META,\n _STEP_DATA\n};\n\nstatic uint16_t crc16(uint8_t *req, uint8_t req_length)\n{\n uint8_t j;\n uint16_t crc;\n\n crc = 0xFFFF;\n while (req_length--) {\n\tcrc = crc ^ *req++;\n\tfor (j=0; j < 8; j++) {\n\t if (crc & 0x0001)\n\t\tcrc = (crc >> 1) ^ 0xA001;\n\t else\n\t\tcrc = crc >> 1;\n\t}\n }\n\n return (crc << 8 | crc >> 8);\n}\n\nModbusinoSlave::ModbusinoSlave(uint8_t slave) {\n _slave = slave;\n}\n\nvoid ModbusinoSlave::setup(long baud) {\n Serial.begin(baud);\n}\n\nstatic int check_integrity(uint8_t *msg, uint8_t msg_length)\n{\n uint16_t crc_calculated;\n uint16_t crc_received;\n\n if (msg_length < 2)\n\treturn -1;\n\n crc_calculated = crc16(msg, msg_length - 2);\n crc_received = (msg[msg_length - 2] << 8) | msg[msg_length - 1];\n\n \/* Check CRC of msg *\/\n if (crc_calculated == crc_received) {\n return msg_length;\n } else {\n return -1;\n }\n}\n\nstatic int build_response_basis(uint8_t slave, uint8_t function,\n\t\t\t\tuint8_t* rsp)\n{\n rsp[0] = slave;\n rsp[1] = function;\n\n return _MODBUS_RTU_PRESET_RSP_LENGTH;\n}\n\nstatic void send_msg(uint8_t *msg, uint8_t msg_length)\n{\n uint16_t crc = crc16(msg, msg_length);\n\n msg[msg_length++] = crc >> 8;\n msg[msg_length++] = crc & 0x00FF;\n\n Serial.write(msg, msg_length);\n}\n\nstatic uint8_t response_exception(uint8_t slave, uint8_t function,\n\t\t\t\t uint8_t exception_code,\n\t\t\t\t uint8_t *rsp)\n{\n uint8_t rsp_length;\n\n rsp_length = build_response_basis(slave, function + 0x80, rsp);\n\n \/* Positive exception code *\/\n rsp[rsp_length++] = exception_code;\n\n return rsp_length;\n}\n\nstatic void flush(void)\n{\n uint8_t i = 0;\n\n \/* Wait a moment to receive the remaining garbage but avoid getting stuck\n * because the line is saturated *\/\n while (Serial.available() && i++ < 10) {\n\tSerial.flush();\n\tdelay(3);\n }\n}\n\nstatic int receive(uint8_t *req, uint8_t _slave)\n{\n uint8_t i;\n uint8_t length_to_read;\n uint8_t req_index;\n uint8_t step;\n uint8_t function;\n\n \/* We need to analyse the message step by step. At the first step, we want\n * to reach the function code because all packets contain this\n * information. *\/\n step = _STEP_FUNCTION;\n length_to_read = _MODBUS_RTU_FUNCTION + 1;\n\n req_index = 0;\n while (length_to_read != 0) {\n\n\t\/* The timeout is defined to ~10 ms between each bytes. Precision is\n\t not that important so I rather to avoid millis() to apply the KISS\n\t principle (millis overflows after 50 days, etc) *\/\n if (!Serial.available()) {\n\t i = 0;\n\t while (!Serial.available()) {\n\t\tdelay(1);\n\t\tif (++i == 10) {\n\t\t \/* Too late, bye *\/\n\t\t return -1;\n\t\t}\n\t }\n }\n\n\treq[req_index] = Serial.read();\n\n \/* Moves the pointer to receive other data *\/\n\treq_index++;\n\n \/* Computes remaining bytes *\/\n length_to_read--;\n\n if (length_to_read == 0) {\n switch (step) {\n case _STEP_FUNCTION:\n \/* Function code position *\/\n\t\tfunction = req[_MODBUS_RTU_FUNCTION];\n\t\tif (function == _FC_READ_HOLDING_REGISTERS) {\n\t\t length_to_read = 4;\n\t\t} else if (function == _FC_WRITE_MULTIPLE_REGISTERS) {\n\t\t length_to_read = 5;\n\t\t} else {\n\t\t \/* Wait a moment to receive the remaining garbage *\/\n\t\t flush();\n\t\t if (_slave == req[_MODBUS_RTU_SLAVE]) {\n\t\t\t\/* It's for me so send an exception (reuse req) *\/\n\t\t\tuint8_t rsp_length = response_exception(\n\t\t\t _slave, function,\n\t\t\t MODBUS_EXCEPTION_ILLEGAL_FUNCTION,\n\t\t\t req);\n\t\t\tsend_msg(req, rsp_length);\n\t\t\treturn - 1 - MODBUS_EXCEPTION_ILLEGAL_FUNCTION;\n\t\t }\n\n\t\t return -1;\n\t\t}\n\t\tstep = _STEP_META;\n\t\tbreak;\n case _STEP_META:\n\t\tlength_to_read = _MODBUS_RTU_CHECKSUM_LENGTH;\n\n\t\tif (function == _FC_WRITE_MULTIPLE_REGISTERS)\n\t\t length_to_read += req[_MODBUS_RTU_FUNCTION + 5];\n\n if ((req_index + length_to_read) > _MODBUSINO_RTU_MAX_ADU_LENGTH) {\n\t\t flush();\n\t\t if (_slave == req[_MODBUS_RTU_SLAVE]) {\n\t\t\t\/* It's for me so send an exception (reuse req) *\/\n\t\t\tuint8_t rsp_length = response_exception(\n\t\t\t _slave, function,\n\t\t\t MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE,\n\t\t\t req);\n\t\t\tsend_msg(req, rsp_length);\n\t\t\treturn - 1 - MODBUS_EXCEPTION_ILLEGAL_FUNCTION;\n\t\t }\n\t\t return -1;\n }\n step = _STEP_DATA;\n break;\n default:\n break;\n }\n }\n }\n\n return check_integrity(req, req_index);\n}\n\n\nstatic void reply(uint16_t *tab_reg, uint8_t nb_reg,\n\t\t uint8_t *req, uint8_t req_length, uint8_t _slave)\n{\n uint8_t slave = req[_MODBUS_RTU_SLAVE];\n uint8_t function = req[_MODBUS_RTU_FUNCTION];\n uint16_t address = (req[_MODBUS_RTU_FUNCTION + 1] << 8) +\n\treq[_MODBUS_RTU_FUNCTION + 2];\n uint16_t nb = (req[_MODBUS_RTU_FUNCTION + 3] << 8) +\n\treq[_MODBUS_RTU_FUNCTION + 4];\n uint8_t rsp[_MODBUSINO_RTU_MAX_ADU_LENGTH];\n uint8_t rsp_length = 0;\n\n if (slave != _slave) {\n\treturn;\n }\n\n if (address + nb > nb_reg) {\n\trsp_length = response_exception(\n\t slave, function,\n\t MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp);\n }\n\n req_length -= _MODBUS_RTU_CHECKSUM_LENGTH;\n\n if (function == _FC_READ_HOLDING_REGISTERS) {\n\tuint8_t i;\n\trsp_length = build_response_basis(slave, function, rsp);\n\trsp[rsp_length++] = nb << 1;\n\tfor (i = address; i < address + nb; i++) {\n\t rsp[rsp_length++] = tab_reg[i] >> 8;\n\t rsp[rsp_length++] = tab_reg[i] & 0xFF;\n\t}\n } else {\n\tint i, j;\n\n\tfor (i = address, j = 6; i < address + nb; i++, j += 2) {\n\t \/* 6 and 7 = first value *\/\n\t tab_reg[i] = (req[_MODBUS_RTU_FUNCTION + j] << 8) +\n\t\treq[_MODBUS_RTU_FUNCTION + j + 1];\n\t}\n\n\trsp_length = build_response_basis(slave, function, rsp);\n\t\/* 4 to copy the address (2) and the no. of registers *\/\n\tmemcpy(rsp + rsp_length, req + rsp_length, 4);\n\trsp_length += 4;\n }\n\n send_msg(rsp, rsp_length);\n}\n\nint ModbusinoSlave::loop(uint16_t* tab_reg, uint8_t nb_reg)\n{\n int rc;\n uint8_t req[_MODBUSINO_RTU_MAX_ADU_LENGTH];\n\n if (Serial.available()) {\n\trc = receive(req, _slave);\n\tif (rc > 0) {\n\t reply(tab_reg, nb_reg, req, rc, _slave);\n\t}\n }\n\n \/* Returns a positive value if successful,\n 0 if a slave filtering has occured,\n -1 if an undefined error has occured,\n -2 for MODBUS_EXCEPTION_ILLEGAL_FUNCTION\n etc *\/\n return rc;\n}\n<|endoftext|>"} {"text":"\/***********************************************************************************\n** MIT License **\n** **\n** Copyright (c) 2017 Victor DENIS (victordenis01@gmail.com) **\n** **\n** Permission is hereby granted, free of charge, to any person obtaining a copy **\n** of this software and associated documentation files (the \"Software\"), to deal **\n** in the Software without restriction, including without limitation the rights **\n** to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell **\n** copies of the Software, and to permit persons to whom the Software is **\n** furnished to do so, subject to the following conditions: **\n** **\n** The above copyright notice and this permission notice shall be included in all **\n** copies or substantial portions of the Software. **\n** **\n** THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR **\n** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, **\n** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE **\n** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER **\n** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, **\n** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE **\n** SOFTWARE. **\n***********************************************************************************\/\n\n#include \"AutoFill.hpp\"\n\n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n\n#include \"Password\/PasswordManager.hpp\"\n\n#include \"Web\/WebPage.hpp\"\n#include \"Web\/WebView.hpp\"\n\n#include \"Utils\/SqlDatabase.hpp\"\n\n#include \"Application.hpp\"\n#include \"AutoFillNotification.hpp\"\n\nnamespace Sn {\n\nAutoFill::AutoFill(QObject* parent) :\n\tQObject(parent),\n\tm_manager(new PasswordManager(this)),\n\tm_isStoring(false)\n{\n\tloadSettings();\n\n\tQString source = QLatin1String(\"(function() {\"\n\t\t\t\t\t\t\t\t\t \"function findUsername(inputs) {\"\n\t\t\t\t\t\t\t\t\t \" for (var i = 0; i < inputs.length; ++i)\"\n\t\t\t\t\t\t\t\t\t \" if (inputs[i].type == 'text' && inputs[i].value.length && inputs[i].name.indexOf('user') != -1)\"\n\t\t\t\t\t\t\t\t\t \" return inputs[i].value;\"\n\t\t\t\t\t\t\t\t\t \" for (var i = 0; i < inputs.length; ++i)\"\n\t\t\t\t\t\t\t\t\t \" if (inputs[i].type == 'text' && inputs[i].value.length && inputs[i].name.indexOf('name') != -1)\"\n\t\t\t\t\t\t\t\t\t \" return inputs[i].value;\"\n\t\t\t\t\t\t\t\t\t \" for (var i = 0; i < inputs.length; ++i)\"\n\t\t\t\t\t\t\t\t\t \" if (inputs[i].type == 'text' && inputs[i].value.length)\"\n\t\t\t\t\t\t\t\t\t \" return inputs[i].value;\"\n\t\t\t\t\t\t\t\t\t \" for (var i = 0; i < inputs.length; ++i)\"\n\t\t\t\t\t\t\t\t\t \" if (inputs[i].type == 'email' && inputs[i].value.length)\"\n\t\t\t\t\t\t\t\t\t \" return inputs[i].value;\"\n\t\t\t\t\t\t\t\t\t \" return '';\"\n\t\t\t\t\t\t\t\t\t \"}\"\n\t\t\t\t\t\t\t\t\t \"\"\n\t\t\t\t\t\t\t\t\t \"function registerForm(form) {\"\n\t\t\t\t\t\t\t\t\t \" form.addEventListener('submit', function() {\"\n\t\t\t\t\t\t\t\t\t \" var form = this;\"\n\t\t\t\t\t\t\t\t\t \" var data = '';\"\n\t\t\t\t\t\t\t\t\t \" var password = '';\"\n\t\t\t\t\t\t\t\t\t \" var inputs = form.getElementsByTagName('input');\"\n\t\t\t\t\t\t\t\t\t \" for (var i = 0; i < inputs.length; ++i) {\"\n\t\t\t\t\t\t\t\t\t \" var input = inputs[i];\"\n\t\t\t\t\t\t\t\t\t \" var type = input.type.toLowerCase();\"\n\t\t\t\t\t\t\t\t\t \" if (type != 'text' && type != 'password' && type != 'email')\"\n\t\t\t\t\t\t\t\t\t \" continue;\"\n\t\t\t\t\t\t\t\t\t \" if (!password && type == 'password')\"\n\t\t\t\t\t\t\t\t\t \" password = input.value;\"\n\t\t\t\t\t\t\t\t\t \" data += encodeURIComponent(input.name);\"\n\t\t\t\t\t\t\t\t\t \" data += '=';\"\n\t\t\t\t\t\t\t\t\t \" data += encodeURIComponent(input.value);\"\n\t\t\t\t\t\t\t\t\t \" data += '&';\"\n\t\t\t\t\t\t\t\t\t \" }\"\n\t\t\t\t\t\t\t\t\t \" if (!password)\"\n\t\t\t\t\t\t\t\t\t \" return;\"\n\t\t\t\t\t\t\t\t\t \" data = data.substring(0, data.length - 1);\"\n\t\t\t\t\t\t\t\t\t \" var url = window.location.href;\"\n\t\t\t\t\t\t\t\t\t \" var username = findUsername(inputs);\"\n\t\t\t\t\t\t\t\t\t \" external.autoFill.formSubmitted(url, username, password, data);\"\n\t\t\t\t\t\t\t\t\t \" }, true);\"\n\t\t\t\t\t\t\t\t\t \"}\"\n\t\t\t\t\t\t\t\t\t \"\"\n\t\t\t\t\t\t\t\t\t \"if (!document.documentElement) return;\"\n\t\t\t\t\t\t\t\t\t \"\"\n\t\t\t\t\t\t\t\t\t \"for (var i = 0; i < document.forms.length; ++i)\"\n\t\t\t\t\t\t\t\t\t \" registerForm(document.forms[i]);\"\n\t\t\t\t\t\t\t\t\t \"\"\n\t\t\t\t\t\t\t\t\t \"var observer = new MutationObserver(function(mutations) {\"\n\t\t\t\t\t\t\t\t\t \" for (var i = 0; i < mutations.length; ++i)\"\n\t\t\t\t\t\t\t\t\t \" for (var j = 0; j < mutations[i].addedNodes.length; ++j)\"\n\t\t\t\t\t\t\t\t\t \" if (mutations[i].addedNodes[j].tagName == 'form')\"\n\t\t\t\t\t\t\t\t\t \" registerForm(mutations[i].addedNodes[j]);\"\n\t\t\t\t\t\t\t\t\t \"});\"\n\t\t\t\t\t\t\t\t\t \"observer.observe(document.documentElement, { childList: true });\"\n\t\t\t\t\t\t\t\t\t \"\"\n\t\t\t\t\t\t\t\t\t \"})()\");\n\n\tQWebEngineScript script{};\n\n\tscript.setName(QStringLiteral(\"_sielo_autofill\"));\n\tscript.setInjectionPoint(QWebEngineScript::DocumentReady);\n\tscript.setWorldId(QWebEngineScript::MainWorld);\n\tscript.setRunsOnSubFrames(true);\n\tscript.setSourceCode(source);\n\n\tApplication::instance()->webProfile()->scripts()->insert(script);\n}\n\nvoid AutoFill::loadSettings()\n{\n\tQSettings settings{};\n\n\tm_isStoring = settings.value(\"Settings\/savePasswordsOnSites\", true).toBool();\n}\n\nbool AutoFill::isStored(const QUrl& url)\n{\n\tif (!isStoringEnabled(url))\n\t\treturn false;\n\n\treturn !m_manager->getEntries(url).isEmpty();\n}\n\nbool AutoFill::isStoringEnabled(const QUrl& url)\n{\n\tif (!m_isStoring)\n\t\treturn false;\n\n\tQString server{url.host()};\n\tQSqlQuery query{};\n\n\tquery.prepare(\"SELECT count(id) FROM autofill_exceptions WHERE server=?\");\n\tquery.addBindValue(server);\n\tquery.exec();\n\n\tif (!query.next())\n\t\treturn false;\n\n\treturn query.value(0).toInt() <= 0;\n}\n\nvoid AutoFill::blockStoringForUrl(const QUrl& url)\n{\n\tQString server{url.host()};\n\n\tif (server.isEmpty())\n\t\tserver = url.toString();\n\n\tQSqlQuery query{};\n\n\tquery.prepare(\"INSERT INTO autofill_exceptions (sever) VALUES (?)\");\n\tquery.addBindValue(server);\n\n\tSqlDatabase::instance()->execAsync(query);\n}\n\nQVector AutoFill::getFormData(const QUrl& url)\n{\n\treturn m_manager->getEntries(url);\n}\n\nQVector AutoFill::getAllFormData()\n{\n\treturn m_manager->getAllEntries();\n}\n\nvoid AutoFill::updateLastUsed(PasswordEntry& data)\n{\n\tm_manager->updateLastUsed(data);\n}\n\nvoid AutoFill::addEntry(const QUrl& url, const QString& name, const QString& password)\n{\n\tPasswordEntry entry{};\n\n\tentry.host = PasswordManager::createHost(url);\n\tentry.username = name;\n\tentry.password = password;\n\n\tm_manager->addEntry(entry);\n}\n\nvoid AutoFill::addEntry(const QUrl& url, const PageFormData& formData)\n{\n\tPasswordEntry entry{};\n\n\tentry.host = PasswordManager::createHost(url);\n\tentry.username = formData.username;\n\tentry.password = formData.password;\n\tentry.data = formData.postData;\n\n\tm_manager->addEntry(entry);\n}\n\nvoid AutoFill::updateEntry(const QUrl& url, const QString& name, const QString& password)\n{\n\tPasswordEntry entry{};\n\n\tentry.host = PasswordManager::createHost(url);\n\tentry.username = name;\n\tentry.password = password;\n\n\tm_manager->updateEntry(entry);\n}\n\nbool AutoFill::updateEntry(const PasswordEntry& entry)\n{\n\treturn m_manager->updateEntry(entry);\n}\n\nvoid AutoFill::removeEntry(const PasswordEntry& entry)\n{\n\tm_manager->removeEntry(entry);\n}\n\nvoid AutoFill::removeAllEntries()\n{\n\tm_manager->removeAllEntries();\n}\n\nvoid AutoFill::saveForm(WebPage* page, const QUrl& frameUrl, const PageFormData& formData)\n{\n\tif (Application::instance()->privateBrowsing() || !page)\n\t\treturn;\n\n\tif (!isStoringEnabled(frameUrl))\n\t\treturn;\n\n\tPasswordEntry updateData{};\n\n\tif (isStored(frameUrl)) {\n\t\tconst QVector& list = getFormData(frameUrl);\n\n\t\t\tforeach (const PasswordEntry& data, list) {\n\t\t\t\tif (data.username == formData.username) {\n\t\t\t\t\tupdateData = data;\n\t\t\t\t\tupdateLastUsed(updateData);\n\n\t\t\t\t\tif (data.password == formData.password) {\n\t\t\t\t\t\tupdateData.password.clear();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tupdateData.username = formData.username;\n\t\t\t\t\tupdateData.password = formData.password;\n\t\t\t\t\tupdateData.data = formData.postData;\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t}\n\n\tAutoFillNotification* notification{new AutoFillNotification(frameUrl, formData, updateData)};\n\tpage->view()->addNotification(notification);\n}\n\nQVector AutoFill::completePage(WebPage* page, const QUrl& frameUrl)\n{\n\tQVector list;\n\n\tif (!page || !isStored(frameUrl))\n\t\treturn list;\n\n\tlist = getFormData(frameUrl);\n\n\tif (!list.isEmpty()) {\n\t\tQString source = QLatin1String(\"(function() {\"\n\t\t\t\t\t\t\t\t\t\t \"var data = '%1'.split('&');\"\n\t\t\t\t\t\t\t\t\t\t \"var inputs = document.getElementsByTagName('input');\"\n\t\t\t\t\t\t\t\t\t\t \"\"\n\t\t\t\t\t\t\t\t\t\t \"for (var i = 0; i < data.length; ++i) {\"\n\t\t\t\t\t\t\t\t\t\t \" var pair = data[i].split('=');\"\n\t\t\t\t\t\t\t\t\t\t \" if (pair.length != 2)\"\n\t\t\t\t\t\t\t\t\t\t \" continue;\"\n\t\t\t\t\t\t\t\t\t\t \" var key = decodeURIComponent(pair[0]);\"\n\t\t\t\t\t\t\t\t\t\t \" var val = decodeURIComponent(pair[1]);\"\n\t\t\t\t\t\t\t\t\t\t \" for (var j = 0; j < inputs.length; ++j) {\"\n\t\t\t\t\t\t\t\t\t\t \" var input = inputs[j];\"\n\t\t\t\t\t\t\t\t\t\t \" var type = input.type.toLowerCase();\"\n\t\t\t\t\t\t\t\t\t\t \" if (type != 'text' && type != 'password' && type != 'email')\"\n\t\t\t\t\t\t\t\t\t\t \" continue;\"\n\t\t\t\t\t\t\t\t\t\t \" if (input.name == key)\"\n\t\t\t\t\t\t\t\t\t\t \" input.value = val;\"\n\t\t\t\t\t\t\t\t\t\t \" }\"\n\t\t\t\t\t\t\t\t\t\t \"}\"\n\t\t\t\t\t\t\t\t\t\t \"\"\n\t\t\t\t\t\t\t\t\t\t \"})()\");\n\t\tconst PasswordEntry entry = list[0];\n\t\tQString data{entry.data};\n\n\t\tdata.replace(QLatin1String(\"'\"), QLatin1String(\"\\\\'\"));\n\n\t\tpage->runJavaScript(source.arg(data), QWebEngineScript::ApplicationWorld);\n\t}\n\n\treturn list;\n}\n\nQByteArray AutoFill::exportPasswords()\n{\n\t\/\/TODO: do\n\tQMessageBox::critical(nullptr, tr(\"No\"), tr(\"You can't export password yet\"));\n\n\treturn QByteArray();\n}\n\nbool AutoFill::importPasswords(const QByteArray& data)\n{\n\t\/\/TODO: do\n\tQMessageBox::critical(nullptr, tr(\"No\"), tr(\"You can't import password yet\"));\n\n\treturn false;\n}\n\n}\n[Fix] mistakes in AutoFill class\/***********************************************************************************\n** MIT License **\n** **\n** Copyright (c) 2017 Victor DENIS (victordenis01@gmail.com) **\n** **\n** Permission is hereby granted, free of charge, to any person obtaining a copy **\n** of this software and associated documentation files (the \"Software\"), to deal **\n** in the Software without restriction, including without limitation the rights **\n** to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell **\n** copies of the Software, and to permit persons to whom the Software is **\n** furnished to do so, subject to the following conditions: **\n** **\n** The above copyright notice and this permission notice shall be included in all **\n** copies or substantial portions of the Software. **\n** **\n** THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR **\n** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, **\n** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE **\n** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER **\n** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, **\n** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE **\n** SOFTWARE. **\n***********************************************************************************\/\n\n#include \"AutoFill.hpp\"\n\n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n\n#include \"Password\/PasswordManager.hpp\"\n\n#include \"Web\/WebPage.hpp\"\n#include \"Web\/WebView.hpp\"\n\n#include \"Utils\/SqlDatabase.hpp\"\n\n#include \"Application.hpp\"\n#include \"AutoFillNotification.hpp\"\n\nnamespace Sn {\n\nAutoFill::AutoFill(QObject* parent) :\n\tQObject(parent),\n\tm_manager(new PasswordManager(this)),\n\tm_isStoring(false)\n{\n\tloadSettings();\n\n\tQString source = QLatin1String(\"(function() {\"\n\t\t\t\t\t\t\t\t\t \"function findUsername(inputs) {\"\n\t\t\t\t\t\t\t\t\t \" for (var i = 0; i < inputs.length; ++i)\"\n\t\t\t\t\t\t\t\t\t \" if (inputs[i].type == 'text' && inputs[i].value.length && inputs[i].name.indexOf('user') != -1)\"\n\t\t\t\t\t\t\t\t\t \" return inputs[i].value;\"\n\t\t\t\t\t\t\t\t\t \" for (var i = 0; i < inputs.length; ++i)\"\n\t\t\t\t\t\t\t\t\t \" if (inputs[i].type == 'text' && inputs[i].value.length && inputs[i].name.indexOf('name') != -1)\"\n\t\t\t\t\t\t\t\t\t \" return inputs[i].value;\"\n\t\t\t\t\t\t\t\t\t \" for (var i = 0; i < inputs.length; ++i)\"\n\t\t\t\t\t\t\t\t\t \" if (inputs[i].type == 'text' && inputs[i].value.length)\"\n\t\t\t\t\t\t\t\t\t \" return inputs[i].value;\"\n\t\t\t\t\t\t\t\t\t \" for (var i = 0; i < inputs.length; ++i)\"\n\t\t\t\t\t\t\t\t\t \" if (inputs[i].type == 'email' && inputs[i].value.length)\"\n\t\t\t\t\t\t\t\t\t \" return inputs[i].value;\"\n\t\t\t\t\t\t\t\t\t \" return '';\"\n\t\t\t\t\t\t\t\t\t \"}\"\n\t\t\t\t\t\t\t\t\t \"\"\n\t\t\t\t\t\t\t\t\t \"function registerForm(form) {\"\n\t\t\t\t\t\t\t\t\t \" form.addEventListener('submit', function() {\"\n\t\t\t\t\t\t\t\t\t \" var form = this;\"\n\t\t\t\t\t\t\t\t\t \" var data = '';\"\n\t\t\t\t\t\t\t\t\t \" var password = '';\"\n\t\t\t\t\t\t\t\t\t \" var inputs = form.getElementsByTagName('input');\"\n\t\t\t\t\t\t\t\t\t \" for (var i = 0; i < inputs.length; ++i) {\"\n\t\t\t\t\t\t\t\t\t \" var input = inputs[i];\"\n\t\t\t\t\t\t\t\t\t \" var type = input.type.toLowerCase();\"\n\t\t\t\t\t\t\t\t\t \" if (type != 'text' && type != 'password' && type != 'email')\"\n\t\t\t\t\t\t\t\t\t \" continue;\"\n\t\t\t\t\t\t\t\t\t \" if (!password && type == 'password')\"\n\t\t\t\t\t\t\t\t\t \" password = input.value;\"\n\t\t\t\t\t\t\t\t\t \" data += encodeURIComponent(input.name);\"\n\t\t\t\t\t\t\t\t\t \" data += '=';\"\n\t\t\t\t\t\t\t\t\t \" data += encodeURIComponent(input.value);\"\n\t\t\t\t\t\t\t\t\t \" data += '&';\"\n\t\t\t\t\t\t\t\t\t \" }\"\n\t\t\t\t\t\t\t\t\t \" if (!password)\"\n\t\t\t\t\t\t\t\t\t \" return;\"\n\t\t\t\t\t\t\t\t\t \" data = data.substring(0, data.length - 1);\"\n\t\t\t\t\t\t\t\t\t \" var url = window.location.href;\"\n\t\t\t\t\t\t\t\t\t \" var username = findUsername(inputs);\"\n\t\t\t\t\t\t\t\t\t \" external.autoFill.formSubmitted(url, username, password, data);\"\n\t\t\t\t\t\t\t\t\t \" }, true);\"\n\t\t\t\t\t\t\t\t\t \"}\"\n\t\t\t\t\t\t\t\t\t \"\"\n\t\t\t\t\t\t\t\t\t \"if (!document.documentElement) return;\"\n\t\t\t\t\t\t\t\t\t \"\"\n\t\t\t\t\t\t\t\t\t \"for (var i = 0; i < document.forms.length; ++i)\"\n\t\t\t\t\t\t\t\t\t \" registerForm(document.forms[i]);\"\n\t\t\t\t\t\t\t\t\t \"\"\n\t\t\t\t\t\t\t\t\t \"var observer = new MutationObserver(function(mutations) {\"\n\t\t\t\t\t\t\t\t\t \" for (var i = 0; i < mutations.length; ++i)\"\n\t\t\t\t\t\t\t\t\t \" for (var j = 0; j < mutations[i].addedNodes.length; ++j)\"\n\t\t\t\t\t\t\t\t\t \" if (mutations[i].addedNodes[j].tagName == 'form')\"\n\t\t\t\t\t\t\t\t\t \" registerForm(mutations[i].addedNodes[j]);\"\n\t\t\t\t\t\t\t\t\t \"});\"\n\t\t\t\t\t\t\t\t\t \"observer.observe(document.documentElement, { childList: true });\"\n\t\t\t\t\t\t\t\t\t \"\"\n\t\t\t\t\t\t\t\t\t \"})()\");\n\n\tQWebEngineScript script{};\n\n\tscript.setName(QStringLiteral(\"_sielo_autofill\"));\n\tscript.setInjectionPoint(QWebEngineScript::DocumentReady);\n\tscript.setWorldId(QWebEngineScript::MainWorld);\n\tscript.setRunsOnSubFrames(true);\n\tscript.setSourceCode(source);\n\n\tApplication::instance()->webProfile()->scripts()->insert(script);\n}\n\nvoid AutoFill::loadSettings()\n{\n\tQSettings settings{};\n\n\tm_isStoring = settings.value(\"Settings\/savePasswordsOnSites\", true).toBool();\n}\n\nbool AutoFill::isStored(const QUrl& url)\n{\n\tif (!isStoringEnabled(url))\n\t\treturn false;\n\n\treturn !m_manager->getEntries(url).isEmpty();\n}\n\nbool AutoFill::isStoringEnabled(const QUrl& url)\n{\n\tif (!m_isStoring)\n\t\treturn false;\n\n\tQString server{url.host()};\n\n\tif (server.isEmpty())\n\t\tserver = url.toString();\n\n\tQSqlQuery query{};\n\n\tquery.prepare(\"SELECT count(id) FROM autofill_exceptions WHERE server=?\");\n\tquery.addBindValue(server);\n\tquery.exec();\n\n\tif (!query.next())\n\t\treturn false;\n\n\treturn query.value(0).toInt() <= 0;\n}\n\nvoid AutoFill::blockStoringForUrl(const QUrl& url)\n{\n\tQString server{url.host()};\n\n\tif (server.isEmpty())\n\t\tserver = url.toString();\n\n\tQSqlQuery query{};\n\n\tquery.prepare(\"INSERT INTO autofill_exceptions (server) VALUES (?)\");\n\tquery.addBindValue(server);\n\n\tSqlDatabase::instance()->execAsync(query);\n}\n\nQVector AutoFill::getFormData(const QUrl& url)\n{\n\treturn m_manager->getEntries(url);\n}\n\nQVector AutoFill::getAllFormData()\n{\n\treturn m_manager->getAllEntries();\n}\n\nvoid AutoFill::updateLastUsed(PasswordEntry& data)\n{\n\tm_manager->updateLastUsed(data);\n}\n\nvoid AutoFill::addEntry(const QUrl& url, const QString& name, const QString& password)\n{\n\tPasswordEntry entry{};\n\n\tentry.host = PasswordManager::createHost(url);\n\tentry.username = name;\n\tentry.password = password;\n\n\tm_manager->addEntry(entry);\n}\n\nvoid AutoFill::addEntry(const QUrl& url, const PageFormData& formData)\n{\n\tPasswordEntry entry{};\n\n\tentry.host = PasswordManager::createHost(url);\n\tentry.username = formData.username;\n\tentry.password = formData.password;\n\tentry.data = formData.postData;\n\n\tm_manager->addEntry(entry);\n}\n\nvoid AutoFill::updateEntry(const QUrl& url, const QString& name, const QString& password)\n{\n\tPasswordEntry entry{};\n\n\tentry.host = PasswordManager::createHost(url);\n\tentry.username = name;\n\tentry.password = password;\n\n\tm_manager->updateEntry(entry);\n}\n\nbool AutoFill::updateEntry(const PasswordEntry& entry)\n{\n\treturn m_manager->updateEntry(entry);\n}\n\nvoid AutoFill::removeEntry(const PasswordEntry& entry)\n{\n\tm_manager->removeEntry(entry);\n}\n\nvoid AutoFill::removeAllEntries()\n{\n\tm_manager->removeAllEntries();\n}\n\nvoid AutoFill::saveForm(WebPage* page, const QUrl& frameUrl, const PageFormData& formData)\n{\n\tif (Application::instance()->privateBrowsing() || !page)\n\t\treturn;\n\n\tif (!isStoringEnabled(frameUrl))\n\t\treturn;\n\n\tPasswordEntry updateData{};\n\n\tif (isStored(frameUrl)) {\n\t\tconst QVector& list = getFormData(frameUrl);\n\n\t\t\tforeach (const PasswordEntry& data, list) {\n\t\t\t\tif (data.username == formData.username) {\n\t\t\t\t\tupdateData = data;\n\t\t\t\t\tupdateLastUsed(updateData);\n\n\t\t\t\t\tif (data.password == formData.password) {\n\t\t\t\t\t\tupdateData.password.clear();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tupdateData.username = formData.username;\n\t\t\t\t\tupdateData.password = formData.password;\n\t\t\t\t\tupdateData.data = formData.postData;\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t}\n\n\tAutoFillNotification* notification{new AutoFillNotification(frameUrl, formData, updateData)};\n\tpage->view()->addNotification(notification);\n}\n\nQVector AutoFill::completePage(WebPage* page, const QUrl& frameUrl)\n{\n\tQVector list;\n\n\tif (!page || !isStored(frameUrl))\n\t\treturn list;\n\n\tlist = getFormData(frameUrl);\n\n\tif (!list.isEmpty()) {\n\t\tQString source = QLatin1String(\"(function() {\"\n\t\t\t\t\t\t\t\t\t\t \"var data = '%1'.split('&');\"\n\t\t\t\t\t\t\t\t\t\t \"var inputs = document.getElementsByTagName('input');\"\n\t\t\t\t\t\t\t\t\t\t \"\"\n\t\t\t\t\t\t\t\t\t\t \"for (var i = 0; i < data.length; ++i) {\"\n\t\t\t\t\t\t\t\t\t\t \" var pair = data[i].split('=');\"\n\t\t\t\t\t\t\t\t\t\t \" if (pair.length != 2)\"\n\t\t\t\t\t\t\t\t\t\t \" continue;\"\n\t\t\t\t\t\t\t\t\t\t \" var key = decodeURIComponent(pair[0]);\"\n\t\t\t\t\t\t\t\t\t\t \" var val = decodeURIComponent(pair[1]);\"\n\t\t\t\t\t\t\t\t\t\t \" for (var j = 0; j < inputs.length; ++j) {\"\n\t\t\t\t\t\t\t\t\t\t \" var input = inputs[j];\"\n\t\t\t\t\t\t\t\t\t\t \" var type = input.type.toLowerCase();\"\n\t\t\t\t\t\t\t\t\t\t \" if (type != 'text' && type != 'password' && type != 'email')\"\n\t\t\t\t\t\t\t\t\t\t \" continue;\"\n\t\t\t\t\t\t\t\t\t\t \" if (input.name == key)\"\n\t\t\t\t\t\t\t\t\t\t \" input.value = val;\"\n\t\t\t\t\t\t\t\t\t\t \" }\"\n\t\t\t\t\t\t\t\t\t\t \"}\"\n\t\t\t\t\t\t\t\t\t\t \"\"\n\t\t\t\t\t\t\t\t\t\t \"})()\");\n\t\tconst PasswordEntry entry = list[0];\n\t\tQString data{entry.data};\n\n\t\tdata.replace(QLatin1String(\"'\"), QLatin1String(\"\\\\'\"));\n\n\t\tpage->runJavaScript(source.arg(data), QWebEngineScript::ApplicationWorld);\n\t}\n\n\treturn list;\n}\n\nQByteArray AutoFill::exportPasswords()\n{\n\t\/\/TODO: do\n\tQMessageBox::critical(nullptr, tr(\"No\"), tr(\"You can't export password yet\"));\n\n\treturn QByteArray();\n}\n\nbool AutoFill::importPasswords(const QByteArray& data)\n{\n\t\/\/TODO: do\n\tQMessageBox::critical(nullptr, tr(\"No\"), tr(\"You can't import password yet\"));\n\n\treturn false;\n}\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\n\/*\n\nGF(2n), to be productized\n\nvoid print(int i)\n{\n \/\/ bitset<8> x(i);\n \/\/ cout << x << \" \";\n cout << i << \" \";\n}\n\nint shift(int i)\n{\n i = i << 1;\n if ((i & (1 << 3)) != 0)\n {\n \/\/ 76543210\n \/\/ 00001011\n i = i ^ 0xb;\n }\n return i;\n}\n\nint add(int i, int j)\n{\n return i ^ j;\n}\n\nint multiply(int i, int j)\n{\n int result = 0;\n int mask = 1;\n for (int bit = 0; bit < 3; bit++)\n {\n if ((mask & j) != 0)\n {\n int temp = i;\n for (int times = 0; times < bit; times++)\n {\n temp = shift(temp);\n }\n result = add(result, temp);\n }\n mask = mask << 1;\n }\n return result;\n}\n\nint main()\n{\n for (int i = 0; i < 8; i++)\n {\n for (int j = 0; j < 8; j++)\n {\n cout << multiply(i, j) << \" \";\n }\n cout << endl;\n }\n return 0;\n}\n*\/\n\nconst int n = 64;\nconst int a = 125;\n\/\/ TODO, prime should account for largest possible overlap, good for now\nconst int prime = 193;\nconst int inverse = 190;\nint powers[64];\n\nint mod(int x, int p)\n{\n return ((x % p) + p) % p;\n}\n\nvoid number_theoretic_transform_helper(int n, int* input, int* output, int sign)\n{\n for (int f = 0; f < n; f++)\n {\n output[f] = 0;\n for (int t = 0; t < n; t++)\n {\n output[f] = mod(output[f] + mod(powers[mod(sign * t * f, n)] * input[t], prime), prime);\n }\n }\n}\n\nvoid number_theoretic_transform(int n, int* input, int* output)\n{\n number_theoretic_transform_helper(n, input, output, -1);\n}\n\nvoid inverse_number_theoretic_transform(int n, int* input, int* output)\n{\n number_theoretic_transform_helper(n, input, output, 1);\n for (int f = 0; f < n; f++)\n {\n output[f] = mod(output[f] * inverse, prime);\n }\n}\n\n\nvoid fast_number_theoretic_transform_helper(int length, int input_offset, int stride, vector& input, int output_offset, int output_stride, vector& output, int sign)\n{\n if (length == 1)\n {\n output[output_offset] = input[input_offset];\n }\n else\n {\n int half = length \/ 2;\n fast_number_theoretic_transform_helper(half, input_offset, stride * 2, input, output_offset, output_stride, output, sign);\n fast_number_theoretic_transform_helper(half, input_offset + stride, stride * 2, input, output_offset + half * output_stride, output_stride, output, sign);\n for (int i = 0; i < half; i++)\n {\n int a = output[output_offset + i * output_stride];\n int b = output[output_offset + (i + half) * output_stride];\n int c = mod(a + mod(powers[mod(-i * n \/ length * sign, n)] * b, prime), prime);\n int d = mod(a + mod(powers[mod((half - i) * n \/ length * sign, n)] * b, prime), prime);\n output[output_offset + i * output_stride] = c;\n output[output_offset + (i + half) * output_stride] = d;\n }\n }\n}\n\nvoid fast_number_theoretic_transform(int length, int input_offset, int stride, vector& input, int output_offset, int output_stride, vector& output)\n{\n fast_number_theoretic_transform_helper(length, input_offset, stride, input, output_offset, output_stride, output, 1);\n}\n\nvoid inverse_fast_number_theoretic_transform(int length, int input_offset, int stride, vector& input, int output_offset, int output_stride, vector& output)\n{\n fast_number_theoretic_transform_helper(length, input_offset, stride, input, output_offset, output_stride, output, -1);\n for (int f = 0; f < length; f++)\n {\n \/\/ TODO - What I really needed here is the multiplicative inverse of length, not the multiplicative inverse of 64\n output[output_offset + f * output_stride] = mod(output[output_offset + f * output_stride] * inverse, prime);\n }\n}\n\nvoid init_powers()\n{\n int p = 1;\n for (int i = 0; i < n; i++)\n {\n powers[i] = p;\n p = mod(p * a, prime);\n }\n}\n\n\/*\nclc;clear;\nit1 = [1 1 0;0 1 0;0 1 0];\nit2 = [1 0 0;1 1 0;0 0 0];\nIT1 = [it1 zeros(3, 3);zeros(3, 6)];\nIT2 = [it2 zeros(3, 3);zeros(3, 6)];\nIF1 = fft2(IT1);\nIF2 = fft2(IT2);\nCF = IF1 .* IF2;\nCT = ifft2(CF)\nconv2(it1,it2)\n *\/\nint main(int argc, char** argv)\n{\n init_powers();\n vector> img1(3, vector(3, 0));\n vector> img2(3, vector(3, 0));\n img1[0][0] = 1; img1[0][1] = 1; img1[0][2] = 0;\n img1[1][0] = 0; img1[1][1] = 1; img1[1][2] = 0;\n img1[2][0] = 0; img1[2][1] = 1; img1[2][2] = 0;\n\n img2[0][0] = 0; img2[0][1] = 0; img2[0][2] = 0;\n img2[1][0] = 0; img2[1][1] = 1; img2[1][2] = 1;\n img2[2][0] = 0; img2[2][1] = 0; img2[2][2] = 1;\n\n vector padded_image1(64, 0);\n vector padded_image2(64, 0);\n\n vector image1_rows(64, 0);\n vector image2_rows(64, 0);\n vector image1_rows_cols(64, 0);\n vector image2_rows_cols(64, 0);\n vector product (64, 0);\n vector product_rows(64, 0);\n vector product_rows_cols(64, 0);\n\n for (int row = 0; row < img1.size(); row++)\n {\n for (int col = 0; col < img1[0].size(); col++)\n {\n padded_image1[row * 8 + col] = img1[row][col];\n }\n }\n\n for (int row = 0; row < img2.size(); row++)\n {\n for (int col = 0; col < img2[0].size(); col++)\n {\n padded_image2[row * 8 + col] = img2[img2.size() - row - 1][img2[0].size() - col - 1];\n }\n }\n\n for (int row = 0; row < 8; row++)\n {\n fast_number_theoretic_transform(8, row * 8, 1, padded_image1, row * 8, 1, image1_rows);\n fast_number_theoretic_transform(8, row * 8, 1, padded_image2, row * 8, 1, image2_rows);\n }\n for (int col = 0; col < 8; col++)\n {\n fast_number_theoretic_transform(8, col, 8, image1_rows, col, 8, image1_rows_cols);\n fast_number_theoretic_transform(8, col, 8, image2_rows, col, 8, image2_rows_cols);\n }\n for (int i = 0; i < 64; i++)\n {\n product[i] = mod(image1_rows_cols[i] * image2_rows_cols[i], prime);\n }\n for (int row = 0; row < 8; row++)\n {\n inverse_fast_number_theoretic_transform(8, row * 8, 1, product, row * 8, 1, product_rows);\n }\n for (int col = 0; col < 8; col++)\n {\n inverse_fast_number_theoretic_transform(8, col, 8, product_rows, col, 8, product_rows_cols);\n }\n for (int row = 0; row < 8; row++)\n {\n for (int col = 0; col < 8; col++)\n {\n \/\/ TODO, eliminate this compensation\n cout << mod(product_rows_cols[row * 8 + col] * 64, prime) << \" \";\n }\n cout << endl;\n }\n\n return 0;\n}Improve Galois field implementation#include \n#include \nusing namespace std;\n\n\/\/ This code represents GF(8), a Galois field of 8 elements\n\/\/ Each element in the field is represented by a polynomial with cofficients in GF(2) [i.e. a single bit]\n\/\/ We use an integer to represent the polynomial. Therefore, 00001011 represents the polynomial x^3 + x + 1\n\/\/ Operations are done modulo a irreducible_polynomial polynomial, in this case, 00001011\n\/\/ Beyond the constants, the code can be adapted to other irreducible polynomials and thus fields of different size\n\/\/ \n\/\/ For example, this is a larger finite field of 1024 elements, this will take a while to run through the full brute-force testing\n\/\/ \n\/\/ const int degree = 10;\n\/\/ const int irreducible_polynomial = 1877;\n\/\/\n\nconst int degree = 3;\nconst int irreducible_polynomial = 11;\nconst int N = 1 << degree;\n\nint add(int i, int j)\n{\n \/\/ Adding a pair of polynomial is simply bitwise xor\n return i ^ j;\n}\n\nint additive_inverse(int i)\n{\n return i;\n}\n\nint mul(int i, int j)\n{\n \/\/ The idea of this algorithm is that when we write i to be f(x) and j to be g(x)\n \/\/ If we write g(x) as a sum of monomials, then we can write it as\n \/\/ g(x) = c2 x^2 + c1 x^1 + c0 x^0\n \/\/ \n \/\/ Then the product can be written as\n \/\/ f(x)g(x) = c2 f(x) x^2 + c_1 f(x) x^1 + c_0 f(x) x^0\n \/\/ = ((c2 f(x) x + c1 f(x))x) + c0 f(x)\n \/\/ = ((((0)x + c2 f(x)) x + c1 f(x))x) + c0 f(x)\n \/\/ \n \/\/ The formula does look complicated, but the code isn't.\n \/\/\n \/\/ The evaluation starts from the innermost bracket, every time we want to evaluate the \n \/\/ outer bracket, we multiply by x and then add f(x) if the coefficient is not zero.\n \/\/\n \/\/ That's it\n \/\/\n int result = 0;\n int mask = 1 << (degree - 1);\n for (int bit = 0; bit < degree; bit++)\n {\n \/\/ This operation multiply the current polynomial by x\n result = result << 1;\n \/\/ Assuming result was a polynomial with degree at most 2\n \/\/ After the multiply, it is at most 3, so either it is or it is not\n if ((result & (1 << degree)) != 0)\n {\n \/\/ In case it is, we compute the mod irreducible_polynomial simply by subtracting it.\n result = add(result, additive_inverse(irreducible_polynomial));\n }\n \/\/ If the coefficient is not 0\n if ((mask & j) != 0)\n {\n \/\/ Add f(x) to the result\n result = add(result, i);\n }\n \/\/ And consider the next less significant term\n mask = mask >> 1;\n }\n return result;\n}\n\n\/\/ A simple repeated squaring algorithm\nint power(int a, int n)\n{\n if (n == 0)\n {\n return 1;\n }\n else if (n == 1)\n {\n return a;\n }\n else\n {\n int half = power(a, n \/ 2);\n int answer = mul(half, half);\n if (n % 2 == 1)\n {\n answer = mul(answer, a);\n }\n return answer;\n }\n}\n\n\/\/ We know that the is multiplicative group is cyclic with order N - 1, \n\/\/ therefore a^(N-1) = 1, so a^(N-2) is the multiplicative inverse\nint multiplicative_inverse(int a)\n{\n return power(a, N - 2);\n}\n\n\/\/ The procedure test that the field we generated does satisfy the field axioms.\nint main()\n{\n \/\/ closure not tested\n for (int a = 0; a < N; a++)\n {\n \/\/ identity rule\n assert(add(a, 0) == a);\n assert(add(0, a) == a);\n assert(mul(a, 1) == a);\n assert(mul(1, a) == a);\n \/\/ additive inverse\n assert(add(a, additive_inverse(a)) == 0);\n if (a != 0)\n {\n assert(mul(a, multiplicative_inverse(a)) == 1);\n }\n for (int b = 0; b < N; b++)\n {\n \/\/ commutative\n assert(add(a, b) == add(b, a));\n assert(mul(a, b) == mul(b, a));\n for (int c = 0; c < 8; c++)\n {\n \/\/ associative\n assert(add(add(a, b), c) == add(a, add(b, c)));\n assert(mul(mul(a, b), c) == mul(a, mul(b, c)));\n\n \/\/ distributive\n assert(mul(add(a, b), c) == add(mul(a, c), mul(b, c)));\n }\n }\n }\n \/\/ TODO: Find a primitive element\n\n return 0;\n}<|endoftext|>"} {"text":"\/\/ Copyright Hugh Perkins 2014 hughperkins at gmail\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License, \n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file, You can \n\/\/ obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \n#include \n\n#include \"Timer.h\"\n#include \"ConvolutionalLayer.h\"\n#include \"LayerMaker.h\"\n#include \"ActivationFunction.h\"\n#include \"StatefulTimer.h\"\n#include \"AccuracyHelper.h\"\n#include \"NeuralNetMould.h\"\n#include \"Layer.h\"\n#include \"InputLayer.h\"\n#include \"FullyConnectedLayer.h\"\n#include \"EpochMaker.h\"\n\n\n#include \"NeuralNet.h\"\n\nusing namespace std;\n\n\/\/static std::mt19937 random;\n\nNeuralNet::NeuralNet( int numPlanes, int boardSize ) {\n cl = new OpenCLHelper();\n InputLayerMaker *maker = new InputLayerMaker( this, numPlanes, boardSize );\n maker->insert();\n}\nNeuralNet::~NeuralNet() {\n for( int i = 0; i < layers.size(); i++ ) {\n delete layers[i];\n }\n delete cl;\n}\nOpenCLHelper *NeuralNet::getCl() {\n return cl;\n}\nNeuralNetMould *NeuralNet::maker() { \/\/ [static]\n return new NeuralNetMould();\n}\nFullyConnectedMaker *NeuralNet::fullyConnectedMaker() {\n return new FullyConnectedMaker( this );\n}\nConvolutionalMaker *NeuralNet::convolutionalMaker() {\n return new ConvolutionalMaker( this );\n}\nvoid NeuralNet::initWeights( int layerIndex, float *weights, float *biasWeights ) {\n initWeights( layerIndex, weights );\n initBiasWeights( layerIndex, biasWeights );\n}\nvoid NeuralNet::initWeights( int layerIndex, float *weights ) {\n layers[layerIndex]->initWeights( weights );\n}\nvoid NeuralNet::initBiasWeights( int layerIndex, float *weights ) {\n layers[layerIndex]->initBiasWeights( weights );\n}\nvoid NeuralNet::printWeightsAsCode() {\n for( int layer = 1; layer < layers.size(); layer++ ) {\n layers[layer]->printWeightsAsCode();\n }\n}\nvoid NeuralNet::printBiasWeightsAsCode() {\n for( int layer = 1; layer < layers.size(); layer++ ) {\n layers[layer]->printBiasWeightsAsCode();\n }\n}\nfloat NeuralNet::calcLoss(float const *expectedValues ) {\n return layers[layers.size()-1]->calcLoss( expectedValues );\n}\nEpochMaker *NeuralNet::epochMaker() {\n return new EpochMaker(this);\n}\nInputLayer *NeuralNet::getFirstLayer() {\n return dynamic_cast( layers[0] );\n}\nLayer *NeuralNet::getLastLayer() {\n return layers[layers.size() - 1];\n}\nLayer *NeuralNet::addLayer( LayerMaker *maker ) {\n Layer *previousLayer = 0;\n if( layers.size() > 0 ) {\n previousLayer = layers[ layers.size() - 1 ];\n }\n maker->setPreviousLayer( previousLayer );\n Layer *layer = maker->instance();\n layers.push_back( layer );\n return layer;\n}\nvoid NeuralNet::setBatchSize( int batchSize ) {\n for( std::vector::iterator it = layers.begin(); it != layers.end(); it++ ) {\n (*it)->setBatchSize( batchSize );\n }\n}\nfloat NeuralNet::doEpoch( float learningRate, int batchSize, int numImages, float const* images, float const *expectedResults ) {\n\/\/ Timer timer;\n setBatchSize( batchSize );\n int numBatches = numImages \/ batchSize;\n float loss = 0;\n int total = 0;\n for( int batch = 0; batch < numBatches; batch++ ) {\n int batchStart = batch * batchSize;\n int thisBatchSize = batchSize;\n if( batch == numBatches - 1 ) {\n thisBatchSize = numImages - batchStart; \/\/ eg, we have 5 images, and batchsize is 3\n \/\/ so last batch size is: 2 = 5 - 3\n setBatchSize( thisBatchSize );\n }\n\/\/ std::cout << \" batch \" << batch << \" start \" << batchStart << \" inputsizeperex \" << getInputSizePerExample() <<\n\/\/ \" resultssizeperex \" << getResultsSizePerExample() << std::endl;\n learnBatch( learningRate, &(images[batchStart*getInputSizePerExample()]), &(expectedResults[batchStart*getResultsSizePerExample()]) );\n loss += calcLoss( &(expectedResults[batchStart*getResultsSizePerExample()]) );\n }\n\/\/ StatefulTimer::dump();\n\/\/ timer.timeCheck(\"epoch time\");\n return loss;\n}\nfloat NeuralNet::doEpochWithCalcTrainingAccuracy( float learningRate, int batchSize, int numImages, float const* images, float const *expectedResults, int const *labels, int *p_totalCorrect ) {\n\/\/ Timer timer;\n setBatchSize( batchSize );\n int numBatches = ( numImages + batchSize - 1 ) \/ batchSize;\n std::cout << \"numBatches: \" << numBatches << std::endl;\n float loss = 0;\n int numRight = 0;\n int total = 0;\n if( getLastLayer()->boardSize != 1 ) {\n throw std::runtime_error(\"Last layer should have board size of 1, and number of planes equal number of categories, if you want to measure training accuracy\");\n }\n for( int batch = 0; batch < numBatches; batch++ ) {\n int batchStart = batch * batchSize;\n int thisBatchSize = batchSize;\n if( batch == numBatches - 1 ) {\n thisBatchSize = numImages - batchStart; \/\/ eg, we have 5 images, and batchsize is 3\n \/\/ so last batch size is: 2 = 5 - 3\n setBatchSize( thisBatchSize );\n }\n\/\/ std::cout << \" batch \" << batch << \" start \" << batchStart << \" inputsizeperex \" << getInputSizePerExample() <<\n\/\/ \" resultssizeperex \" << getResultsSizePerExample() << std::endl;\n learnBatch( learningRate, &(images[batchStart*getInputSizePerExample()]), &(expectedResults[batchStart*getResultsSizePerExample()]) );\n StatefulTimer::timeCheck(\"after batch forward-backward prop\");\n numRight += AccuracyHelper::calcNumRight( thisBatchSize, getLastLayer()->numPlanes, &(labels[batchStart]), getResults() );\n StatefulTimer::timeCheck(\"after batch calc training num right\");\n loss += calcLoss( &(expectedResults[batchStart*getResultsSizePerExample()]) );\n StatefulTimer::timeCheck(\"after batch calc loss\");\n }\n *p_totalCorrect = numRight;\n\/\/ StatefulTimer::dump();\n\/\/ timer.timeCheck(\"epoch time\");\n return loss;\n}\n\/\/ float *propagate( int N, int batchSize, float const*images) {\n\/\/ float *results = new float[N];\n\/\/ int numBatches = N \/ batchSize;\n\/\/ for( int batch = 0; batch < numBatches; batch++ ) {\n\/\/ int batchStart = batch * batchSize;\n\/\/ int batchEndExcl = std::min( N, (batch + 1 ) * batchSize );\n\/\/ propagateBatch( &(images[batchStart]) );\n\/\/ std::cout << \" batch \" << batch << \" start \" << batchStart << \" end \" << batchEndExcl << std::endl;\n\/\/ float const *netResults = getResults();\n\/\/ for( int i = 0; i < batchSize; i++ ) {\n\/\/ results[batchStart + i ] = netResults[i];\n\/\/ }\n\/\/ }\n\/\/ return results;\n\/\/ }\nvoid NeuralNet::propagate( float const*images) {\n \/\/ forward...\n\/\/ Timer timer;\n dynamic_cast(layers[0])->in( images );\n for( int layerId = 1; layerId < layers.size(); layerId++ ) {\n layers[layerId]->propagate();\n }\n\/\/ timer.timeCheck(\"propagate time\");\n}\nvoid NeuralNet::backProp(float learningRate, float const *expectedResults) {\n \/\/ backward...\n Layer *lastLayer = getLastLayer();\n float *errors = new float[ lastLayer->getResultsSize() ];\n lastLayer->calcErrors( expectedResults, errors );\n\n float *errorsForNextLayer = 0;\n for( int layerIdx = layers.size() - 1; layerIdx >= 1; layerIdx-- ) { \/\/ no point in propagating to input layer :-P\n if( layerIdx > 1 ) {\n errorsForNextLayer = new float[ layers[layerIdx-1]->getResultsSize() ];\n }\n layers[layerIdx]->backPropErrors( learningRate, errors, errorsForNextLayer );\n delete[] errors;\n errors = 0;\n errors = errorsForNextLayer;\n errorsForNextLayer = 0;\n }\n}\nvoid NeuralNet::learnBatch( float learningRate, float const*images, float const *expectedResults ) {\n\/\/ Timer timer;\n propagate( images);\n\/\/ timer.timeCheck(\"propagate\");\n backProp(learningRate, expectedResults );\n\/\/ timer.timeCheck(\"backProp\");\n}\nint NeuralNet::getNumLayers() {\n return layers.size();\n}\nfloat const *NeuralNet::getResults( int layer ) const {\n return layers[layer]->getResults();\n}\nint NeuralNet::getInputSizePerExample() const {\n return layers[ 0 ]->getResultsSizePerExample();\n}\nint NeuralNet::getResultsSizePerExample() const {\n return layers[ layers.size() - 1 ]->getResultsSizePerExample();\n}\nfloat const *NeuralNet::getResults() const {\n return getResults( layers.size() - 1 );\n}\nvoid NeuralNet::print() {\n int i = 0; \n for( std::vector< Layer* >::iterator it = layers.begin(); it != layers.end(); it++ ) {\n std::cout << \"layer \" << i << \":\" << std::endl;\n (*it)->print();\n i++;\n }\n}\nvoid NeuralNet::printWeights() {\n int i = 0; \n for( std::vector< Layer* >::iterator it = layers.begin(); it != layers.end(); it++ ) {\n std::cout << \"layer \" << i << \":\" << std::endl;\n (*it)->printWeights();\n i++;\n }\n}\nvoid NeuralNet::printOutput() {\n int i = 0; \n for( std::vector< Layer* >::iterator it = layers.begin(); it != layers.end(); it++ ) {\n std::cout << \"layer \" << i << \":\" << std::endl;\n (*it)->printOutput();\n i++;\n }\n}\n\nmove [static] to line before method\/\/ Copyright Hugh Perkins 2014 hughperkins at gmail\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License, \n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file, You can \n\/\/ obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \n#include \n\n#include \"Timer.h\"\n#include \"ConvolutionalLayer.h\"\n#include \"LayerMaker.h\"\n#include \"ActivationFunction.h\"\n#include \"StatefulTimer.h\"\n#include \"AccuracyHelper.h\"\n#include \"NeuralNetMould.h\"\n#include \"Layer.h\"\n#include \"InputLayer.h\"\n#include \"FullyConnectedLayer.h\"\n#include \"EpochMaker.h\"\n\n\n#include \"NeuralNet.h\"\n\nusing namespace std;\n\n\/\/static std::mt19937 random;\n\nNeuralNet::NeuralNet( int numPlanes, int boardSize ) {\n cl = new OpenCLHelper();\n InputLayerMaker *maker = new InputLayerMaker( this, numPlanes, boardSize );\n maker->insert();\n}\nNeuralNet::~NeuralNet() {\n for( int i = 0; i < layers.size(); i++ ) {\n delete layers[i];\n }\n delete cl;\n}\nOpenCLHelper *NeuralNet::getCl() {\n return cl;\n}\n\/\/ [static]\nNeuralNetMould *NeuralNet::maker() {\n return new NeuralNetMould();\n}\nFullyConnectedMaker *NeuralNet::fullyConnectedMaker() {\n return new FullyConnectedMaker( this );\n}\nConvolutionalMaker *NeuralNet::convolutionalMaker() {\n return new ConvolutionalMaker( this );\n}\nvoid NeuralNet::initWeights( int layerIndex, float *weights, float *biasWeights ) {\n initWeights( layerIndex, weights );\n initBiasWeights( layerIndex, biasWeights );\n}\nvoid NeuralNet::initWeights( int layerIndex, float *weights ) {\n layers[layerIndex]->initWeights( weights );\n}\nvoid NeuralNet::initBiasWeights( int layerIndex, float *weights ) {\n layers[layerIndex]->initBiasWeights( weights );\n}\nvoid NeuralNet::printWeightsAsCode() {\n for( int layer = 1; layer < layers.size(); layer++ ) {\n layers[layer]->printWeightsAsCode();\n }\n}\nvoid NeuralNet::printBiasWeightsAsCode() {\n for( int layer = 1; layer < layers.size(); layer++ ) {\n layers[layer]->printBiasWeightsAsCode();\n }\n}\nfloat NeuralNet::calcLoss(float const *expectedValues ) {\n return layers[layers.size()-1]->calcLoss( expectedValues );\n}\nEpochMaker *NeuralNet::epochMaker() {\n return new EpochMaker(this);\n}\nInputLayer *NeuralNet::getFirstLayer() {\n return dynamic_cast( layers[0] );\n}\nLayer *NeuralNet::getLastLayer() {\n return layers[layers.size() - 1];\n}\nLayer *NeuralNet::addLayer( LayerMaker *maker ) {\n Layer *previousLayer = 0;\n if( layers.size() > 0 ) {\n previousLayer = layers[ layers.size() - 1 ];\n }\n maker->setPreviousLayer( previousLayer );\n Layer *layer = maker->instance();\n layers.push_back( layer );\n return layer;\n}\nvoid NeuralNet::setBatchSize( int batchSize ) {\n for( std::vector::iterator it = layers.begin(); it != layers.end(); it++ ) {\n (*it)->setBatchSize( batchSize );\n }\n}\nfloat NeuralNet::doEpoch( float learningRate, int batchSize, int numImages, float const* images, float const *expectedResults ) {\n\/\/ Timer timer;\n setBatchSize( batchSize );\n int numBatches = numImages \/ batchSize;\n float loss = 0;\n int total = 0;\n for( int batch = 0; batch < numBatches; batch++ ) {\n int batchStart = batch * batchSize;\n int thisBatchSize = batchSize;\n if( batch == numBatches - 1 ) {\n thisBatchSize = numImages - batchStart; \/\/ eg, we have 5 images, and batchsize is 3\n \/\/ so last batch size is: 2 = 5 - 3\n setBatchSize( thisBatchSize );\n }\n\/\/ std::cout << \" batch \" << batch << \" start \" << batchStart << \" inputsizeperex \" << getInputSizePerExample() <<\n\/\/ \" resultssizeperex \" << getResultsSizePerExample() << std::endl;\n learnBatch( learningRate, &(images[batchStart*getInputSizePerExample()]), &(expectedResults[batchStart*getResultsSizePerExample()]) );\n loss += calcLoss( &(expectedResults[batchStart*getResultsSizePerExample()]) );\n }\n\/\/ StatefulTimer::dump();\n\/\/ timer.timeCheck(\"epoch time\");\n return loss;\n}\nfloat NeuralNet::doEpochWithCalcTrainingAccuracy( float learningRate, int batchSize, int numImages, float const* images, float const *expectedResults, int const *labels, int *p_totalCorrect ) {\n\/\/ Timer timer;\n setBatchSize( batchSize );\n int numBatches = ( numImages + batchSize - 1 ) \/ batchSize;\n std::cout << \"numBatches: \" << numBatches << std::endl;\n float loss = 0;\n int numRight = 0;\n int total = 0;\n if( getLastLayer()->boardSize != 1 ) {\n throw std::runtime_error(\"Last layer should have board size of 1, and number of planes equal number of categories, if you want to measure training accuracy\");\n }\n for( int batch = 0; batch < numBatches; batch++ ) {\n int batchStart = batch * batchSize;\n int thisBatchSize = batchSize;\n if( batch == numBatches - 1 ) {\n thisBatchSize = numImages - batchStart; \/\/ eg, we have 5 images, and batchsize is 3\n \/\/ so last batch size is: 2 = 5 - 3\n setBatchSize( thisBatchSize );\n }\n\/\/ std::cout << \" batch \" << batch << \" start \" << batchStart << \" inputsizeperex \" << getInputSizePerExample() <<\n\/\/ \" resultssizeperex \" << getResultsSizePerExample() << std::endl;\n learnBatch( learningRate, &(images[batchStart*getInputSizePerExample()]), &(expectedResults[batchStart*getResultsSizePerExample()]) );\n StatefulTimer::timeCheck(\"after batch forward-backward prop\");\n numRight += AccuracyHelper::calcNumRight( thisBatchSize, getLastLayer()->numPlanes, &(labels[batchStart]), getResults() );\n StatefulTimer::timeCheck(\"after batch calc training num right\");\n loss += calcLoss( &(expectedResults[batchStart*getResultsSizePerExample()]) );\n StatefulTimer::timeCheck(\"after batch calc loss\");\n }\n *p_totalCorrect = numRight;\n\/\/ StatefulTimer::dump();\n\/\/ timer.timeCheck(\"epoch time\");\n return loss;\n}\n\/\/ float *propagate( int N, int batchSize, float const*images) {\n\/\/ float *results = new float[N];\n\/\/ int numBatches = N \/ batchSize;\n\/\/ for( int batch = 0; batch < numBatches; batch++ ) {\n\/\/ int batchStart = batch * batchSize;\n\/\/ int batchEndExcl = std::min( N, (batch + 1 ) * batchSize );\n\/\/ propagateBatch( &(images[batchStart]) );\n\/\/ std::cout << \" batch \" << batch << \" start \" << batchStart << \" end \" << batchEndExcl << std::endl;\n\/\/ float const *netResults = getResults();\n\/\/ for( int i = 0; i < batchSize; i++ ) {\n\/\/ results[batchStart + i ] = netResults[i];\n\/\/ }\n\/\/ }\n\/\/ return results;\n\/\/ }\nvoid NeuralNet::propagate( float const*images) {\n \/\/ forward...\n\/\/ Timer timer;\n dynamic_cast(layers[0])->in( images );\n for( int layerId = 1; layerId < layers.size(); layerId++ ) {\n layers[layerId]->propagate();\n }\n\/\/ timer.timeCheck(\"propagate time\");\n}\nvoid NeuralNet::backProp(float learningRate, float const *expectedResults) {\n \/\/ backward...\n Layer *lastLayer = getLastLayer();\n float *errors = new float[ lastLayer->getResultsSize() ];\n lastLayer->calcErrors( expectedResults, errors );\n\n float *errorsForNextLayer = 0;\n for( int layerIdx = layers.size() - 1; layerIdx >= 1; layerIdx-- ) { \/\/ no point in propagating to input layer :-P\n if( layerIdx > 1 ) {\n errorsForNextLayer = new float[ layers[layerIdx-1]->getResultsSize() ];\n }\n layers[layerIdx]->backPropErrors( learningRate, errors, errorsForNextLayer );\n delete[] errors;\n errors = 0;\n errors = errorsForNextLayer;\n errorsForNextLayer = 0;\n }\n}\nvoid NeuralNet::learnBatch( float learningRate, float const*images, float const *expectedResults ) {\n\/\/ Timer timer;\n propagate( images);\n\/\/ timer.timeCheck(\"propagate\");\n backProp(learningRate, expectedResults );\n\/\/ timer.timeCheck(\"backProp\");\n}\nint NeuralNet::getNumLayers() {\n return layers.size();\n}\nfloat const *NeuralNet::getResults( int layer ) const {\n return layers[layer]->getResults();\n}\nint NeuralNet::getInputSizePerExample() const {\n return layers[ 0 ]->getResultsSizePerExample();\n}\nint NeuralNet::getResultsSizePerExample() const {\n return layers[ layers.size() - 1 ]->getResultsSizePerExample();\n}\nfloat const *NeuralNet::getResults() const {\n return getResults( layers.size() - 1 );\n}\nvoid NeuralNet::print() {\n int i = 0; \n for( std::vector< Layer* >::iterator it = layers.begin(); it != layers.end(); it++ ) {\n std::cout << \"layer \" << i << \":\" << std::endl;\n (*it)->print();\n i++;\n }\n}\nvoid NeuralNet::printWeights() {\n int i = 0; \n for( std::vector< Layer* >::iterator it = layers.begin(); it != layers.end(); it++ ) {\n std::cout << \"layer \" << i << \":\" << std::endl;\n (*it)->printWeights();\n i++;\n }\n}\nvoid NeuralNet::printOutput() {\n int i = 0; \n for( std::vector< Layer* >::iterator it = layers.begin(); it != layers.end(); it++ ) {\n std::cout << \"layer \" << i << \":\" << std::endl;\n (*it)->printOutput();\n i++;\n }\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/gtk\/options\/customize_sync_window_gtk.h\"\n\n#include \n\n#include \n\n#include \"app\/gtk_signal.h\"\n#include \"app\/l10n_util.h\"\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/gtk\/accessible_widget_helper_gtk.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n#include \"chrome\/browser\/options_window.h\"\n#include \"chrome\/browser\/pref_service.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/sync\/glue\/data_type_controller.h\"\n#include \"chrome\/browser\/sync\/profile_sync_service.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/locale_settings.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomizeSyncWindowGtk\n\/\/\n\/\/ The contents of the Customize Sync dialog window.\n\nclass CustomizeSyncWindowGtk {\n public:\n explicit CustomizeSyncWindowGtk(Profile* profile);\n ~CustomizeSyncWindowGtk();\n\n void Show();\n bool ClickOk();\n void ClickCancel();\n\n private:\n \/\/ The pixel width we wrap labels at.\n static const int kWrapWidth = 475;\n\n GtkWidget* AddCheckbox(GtkWidget* parent, int label_id, bool checked);\n bool Accept();\n\n static void OnWindowDestroy(GtkWidget* widget,\n CustomizeSyncWindowGtk* window);\n\n static void OnResponse(GtkDialog* dialog, gint response_id,\n CustomizeSyncWindowGtk* customize_sync_window);\n\n CHROMEGTK_CALLBACK_0(CustomizeSyncWindowGtk, void, OnCheckboxClicked);\n\n \/\/ The customize sync dialog.\n GtkWidget *dialog_;\n\n Profile* profile_;\n\n GtkWidget* description_label_;\n GtkWidget* bookmarks_check_box_;\n GtkWidget* preferences_check_box_;\n GtkWidget* themes_check_box_;\n GtkWidget* autofill_check_box_;\n\n \/\/ Helper object to manage accessibility metadata.\n scoped_ptr accessible_widget_helper_;\n\n DISALLOW_COPY_AND_ASSIGN(CustomizeSyncWindowGtk);\n};\n\n\/\/ The singleton customize sync window object.\nstatic CustomizeSyncWindowGtk* customize_sync_window = NULL;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomizeSyncWindowGtk, public:\n\nCustomizeSyncWindowGtk::CustomizeSyncWindowGtk(Profile* profile)\n : profile_(profile),\n description_label_(NULL),\n bookmarks_check_box_(NULL),\n preferences_check_box_(NULL),\n themes_check_box_(NULL),\n autofill_check_box_(NULL) {\n syncable::ModelTypeSet registered_types;\n profile_->GetProfileSyncService()->GetRegisteredDataTypes(®istered_types);\n syncable::ModelTypeSet preferred_types;\n profile_->GetProfileSyncService()->GetPreferredDataTypes(&preferred_types);\n\n std::string dialog_name = l10n_util::GetStringUTF8(\n IDS_CUSTOMIZE_SYNC_WINDOW_TITLE);\n dialog_ = gtk_dialog_new_with_buttons(\n dialog_name.c_str(),\n \/\/ Customize sync window is shared between all browser windows.\n NULL,\n \/\/ Non-modal.\n GTK_DIALOG_NO_SEPARATOR,\n GTK_STOCK_OK,\n GTK_RESPONSE_OK,\n GTK_STOCK_CANCEL,\n GTK_RESPONSE_CANCEL,\n NULL);\n gtk_box_set_spacing(GTK_BOX(GTK_DIALOG(dialog_)->vbox),\n gtk_util::kContentAreaSpacing);\n\n accessible_widget_helper_.reset(new AccessibleWidgetHelper(\n dialog_, profile));\n accessible_widget_helper_->SendOpenWindowNotification(dialog_name);\n\n GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);\n\n description_label_ = gtk_label_new(l10n_util::GetStringUTF8(\n IDS_CUSTOMIZE_SYNC_DESCRIPTION).c_str());\n gtk_label_set_line_wrap(GTK_LABEL(description_label_), TRUE);\n gtk_widget_set_size_request(description_label_, kWrapWidth, -1);\n gtk_box_pack_start(GTK_BOX(vbox), description_label_, FALSE, FALSE, 0);\n\n accessible_widget_helper_->SetWidgetName(description_label_,\n IDS_CUSTOMIZE_SYNC_DESCRIPTION);\n\n DCHECK(registered_types.count(syncable::BOOKMARKS));\n bool bookmarks_checked = preferred_types.count(syncable::BOOKMARKS) != 0;\n bookmarks_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_BOOKMARKS,\n bookmarks_checked);\n\n if (registered_types.count(syncable::PREFERENCES)) {\n bool prefs_checked = preferred_types.count(syncable::PREFERENCES) != 0;\n preferences_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_PREFERENCES,\n prefs_checked);\n }\n\n if (registered_types.count(syncable::THEMES)) {\n bool themes_checked = preferred_types.count(syncable::THEMES) != 0;\n themes_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_THEMES,\n themes_checked);\n }\n\n if (registered_types.count(syncable::AUTOFILL)) {\n bool autofill_checked = preferred_types.count(syncable::AUTOFILL) != 0;\n autofill_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_AUTOFILL,\n autofill_checked);\n }\n\n gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog_)->vbox), vbox, FALSE, FALSE, 0);\n\n gtk_widget_realize(dialog_);\n gtk_util::SetWindowSizeFromResources(GTK_WINDOW(dialog_),\n IDS_CUSTOMIZE_SYNC_DIALOG_WIDTH_CHARS,\n IDS_CUSTOMIZE_SYNC_DIALOG_HEIGHT_LINES,\n true);\n\n g_signal_connect(dialog_, \"response\", G_CALLBACK(OnResponse), this);\n g_signal_connect(dialog_, \"destroy\", G_CALLBACK(OnWindowDestroy), this);\n\n gtk_util::ShowDialog(dialog_);\n}\n\nCustomizeSyncWindowGtk::~CustomizeSyncWindowGtk() {\n}\n\nvoid CustomizeSyncWindowGtk::Show() {\n \/\/ Bring options window to front if it already existed and isn't already\n \/\/ in front\n gtk_util::PresentWindow(dialog_, 0);\n}\n\nbool CustomizeSyncWindowGtk::ClickOk() {\n\n if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(bookmarks_check_box_)) ||\n (preferences_check_box_ &&\n gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(\n preferences_check_box_))) ||\n (themes_check_box_ &&\n gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(themes_check_box_))) ||\n (autofill_check_box_ &&\n gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(autofill_check_box_)))) {\n Accept();\n gtk_widget_destroy(GTK_WIDGET(dialog_));\n return true;\n } else {\n \/\/ show the user that something's wrong with this dialog (not perfect, but\n \/\/ a temporary fix)\n gtk_util::PresentWindow(dialog_, 0);\n return false;\n }\n}\n\nvoid CustomizeSyncWindowGtk::ClickCancel() {\n gtk_widget_destroy(GTK_WIDGET(dialog_));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomizeSyncWindowGtk, private:\n\nGtkWidget* CustomizeSyncWindowGtk::AddCheckbox(GtkWidget* parent, int label_id,\n bool checked) {\n\n GtkWidget* checkbox = gtk_check_button_new_with_label(\n l10n_util::GetStringUTF8(label_id).c_str());\n\n gtk_box_pack_start(GTK_BOX(parent), checkbox, FALSE, FALSE, 0);\n accessible_widget_helper_->SetWidgetName(checkbox, label_id);\n gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbox), checked);\n\n g_signal_connect(checkbox, \"clicked\", G_CALLBACK(OnCheckboxClickedThunk),\n this);\n\n return checkbox;\n}\n\nbool CustomizeSyncWindowGtk::Accept() {\n syncable::ModelTypeSet preferred_types;\n\n bool bookmarks_enabled = gtk_toggle_button_get_active(\n GTK_TOGGLE_BUTTON(bookmarks_check_box_));\n if (bookmarks_enabled) {\n preferred_types.insert(syncable::BOOKMARKS);\n }\n\n if (preferences_check_box_) {\n bool preferences_enabled = gtk_toggle_button_get_active(\n GTK_TOGGLE_BUTTON(preferences_check_box_));\n if (preferences_enabled) {\n preferred_types.insert(syncable::PREFERENCES);\n }\n }\n if (themes_check_box_) {\n bool themes_enabled = gtk_toggle_button_get_active(\n GTK_TOGGLE_BUTTON(themes_check_box_));\n if (themes_enabled) {\n preferred_types.insert(syncable::THEMES);\n }\n }\n if (autofill_check_box_) {\n bool autofill_enabled = gtk_toggle_button_get_active(\n GTK_TOGGLE_BUTTON(autofill_check_box_));\n if (autofill_enabled) {\n preferred_types.insert(syncable::AUTOFILL);\n }\n }\n\n profile_->GetProfileSyncService()->ChangePreferredDataTypes(preferred_types);\n return true;\n}\n\n\/\/ static\nvoid CustomizeSyncWindowGtk::OnWindowDestroy(GtkWidget* widget,\n CustomizeSyncWindowGtk* window) {\n customize_sync_window = NULL;\n MessageLoop::current()->DeleteSoon(FROM_HERE, window);\n}\n\n\/\/ static\nvoid CustomizeSyncWindowGtk::OnResponse(\n GtkDialog* dialog, gint response_id,\n CustomizeSyncWindowGtk* customize_sync_window) {\n if (response_id == GTK_RESPONSE_OK) {\n customize_sync_window->ClickOk();\n } else if (response_id == GTK_RESPONSE_CANCEL) {\n customize_sync_window->ClickCancel();\n }\n}\n\n\/\/ Deactivate the \"OK\" button if you uncheck all the data types.\nvoid CustomizeSyncWindowGtk::OnCheckboxClicked(GtkWidget* widget) {\n bool any_datatypes_selected =\n gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(bookmarks_check_box_)) ||\n (preferences_check_box_ &&\n gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(\n preferences_check_box_))) ||\n (themes_check_box_ &&\n gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(themes_check_box_))) ||\n (autofill_check_box_ &&\n gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(autofill_check_box_)));\n if (any_datatypes_selected) {\n gtk_dialog_set_response_sensitive(\n GTK_DIALOG(customize_sync_window->dialog_), GTK_RESPONSE_OK, TRUE);\n } else {\n gtk_dialog_set_response_sensitive(\n GTK_DIALOG(customize_sync_window->dialog_), GTK_RESPONSE_OK, FALSE);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Factory\/finder method:\n\nvoid ShowCustomizeSyncWindow(Profile* profile) {\n DCHECK(profile);\n \/\/ If there's already an existing window, use it.\n if (!customize_sync_window) {\n customize_sync_window = new CustomizeSyncWindowGtk(profile);\n }\n customize_sync_window->Show();\n}\n\nbool CustomizeSyncWindowOk() {\n if (customize_sync_window) {\n return customize_sync_window->ClickOk();\n } else {\n return true;\n }\n}\n\nvoid CustomizeSyncWindowCancel() {\n if (customize_sync_window) {\n customize_sync_window->ClickCancel();\n }\n}\nGTK: swap ok\/cancel button order in sync personalization dialog.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/gtk\/options\/customize_sync_window_gtk.h\"\n\n#include \n\n#include \n\n#include \"app\/gtk_signal.h\"\n#include \"app\/l10n_util.h\"\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/gtk\/accessible_widget_helper_gtk.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n#include \"chrome\/browser\/options_window.h\"\n#include \"chrome\/browser\/pref_service.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/sync\/glue\/data_type_controller.h\"\n#include \"chrome\/browser\/sync\/profile_sync_service.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/locale_settings.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomizeSyncWindowGtk\n\/\/\n\/\/ The contents of the Customize Sync dialog window.\n\nclass CustomizeSyncWindowGtk {\n public:\n explicit CustomizeSyncWindowGtk(Profile* profile);\n ~CustomizeSyncWindowGtk();\n\n void Show();\n bool ClickOk();\n void ClickCancel();\n\n private:\n \/\/ The pixel width we wrap labels at.\n static const int kWrapWidth = 475;\n\n GtkWidget* AddCheckbox(GtkWidget* parent, int label_id, bool checked);\n bool Accept();\n\n static void OnWindowDestroy(GtkWidget* widget,\n CustomizeSyncWindowGtk* window);\n\n static void OnResponse(GtkDialog* dialog, gint response_id,\n CustomizeSyncWindowGtk* customize_sync_window);\n\n CHROMEGTK_CALLBACK_0(CustomizeSyncWindowGtk, void, OnCheckboxClicked);\n\n \/\/ The customize sync dialog.\n GtkWidget *dialog_;\n\n Profile* profile_;\n\n GtkWidget* description_label_;\n GtkWidget* bookmarks_check_box_;\n GtkWidget* preferences_check_box_;\n GtkWidget* themes_check_box_;\n GtkWidget* autofill_check_box_;\n\n \/\/ Helper object to manage accessibility metadata.\n scoped_ptr accessible_widget_helper_;\n\n DISALLOW_COPY_AND_ASSIGN(CustomizeSyncWindowGtk);\n};\n\n\/\/ The singleton customize sync window object.\nstatic CustomizeSyncWindowGtk* customize_sync_window = NULL;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomizeSyncWindowGtk, public:\n\nCustomizeSyncWindowGtk::CustomizeSyncWindowGtk(Profile* profile)\n : profile_(profile),\n description_label_(NULL),\n bookmarks_check_box_(NULL),\n preferences_check_box_(NULL),\n themes_check_box_(NULL),\n autofill_check_box_(NULL) {\n syncable::ModelTypeSet registered_types;\n profile_->GetProfileSyncService()->GetRegisteredDataTypes(®istered_types);\n syncable::ModelTypeSet preferred_types;\n profile_->GetProfileSyncService()->GetPreferredDataTypes(&preferred_types);\n\n std::string dialog_name = l10n_util::GetStringUTF8(\n IDS_CUSTOMIZE_SYNC_WINDOW_TITLE);\n dialog_ = gtk_dialog_new_with_buttons(\n dialog_name.c_str(),\n \/\/ Customize sync window is shared between all browser windows.\n NULL,\n \/\/ Non-modal.\n GTK_DIALOG_NO_SEPARATOR,\n GTK_STOCK_CANCEL,\n GTK_RESPONSE_CANCEL,\n GTK_STOCK_OK,\n GTK_RESPONSE_OK,\n NULL);\n gtk_box_set_spacing(GTK_BOX(GTK_DIALOG(dialog_)->vbox),\n gtk_util::kContentAreaSpacing);\n\n accessible_widget_helper_.reset(new AccessibleWidgetHelper(\n dialog_, profile));\n accessible_widget_helper_->SendOpenWindowNotification(dialog_name);\n\n GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);\n\n description_label_ = gtk_label_new(l10n_util::GetStringUTF8(\n IDS_CUSTOMIZE_SYNC_DESCRIPTION).c_str());\n gtk_label_set_line_wrap(GTK_LABEL(description_label_), TRUE);\n gtk_widget_set_size_request(description_label_, kWrapWidth, -1);\n gtk_box_pack_start(GTK_BOX(vbox), description_label_, FALSE, FALSE, 0);\n\n accessible_widget_helper_->SetWidgetName(description_label_,\n IDS_CUSTOMIZE_SYNC_DESCRIPTION);\n\n DCHECK(registered_types.count(syncable::BOOKMARKS));\n bool bookmarks_checked = preferred_types.count(syncable::BOOKMARKS) != 0;\n bookmarks_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_BOOKMARKS,\n bookmarks_checked);\n\n if (registered_types.count(syncable::PREFERENCES)) {\n bool prefs_checked = preferred_types.count(syncable::PREFERENCES) != 0;\n preferences_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_PREFERENCES,\n prefs_checked);\n }\n\n if (registered_types.count(syncable::THEMES)) {\n bool themes_checked = preferred_types.count(syncable::THEMES) != 0;\n themes_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_THEMES,\n themes_checked);\n }\n\n if (registered_types.count(syncable::AUTOFILL)) {\n bool autofill_checked = preferred_types.count(syncable::AUTOFILL) != 0;\n autofill_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_AUTOFILL,\n autofill_checked);\n }\n\n gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog_)->vbox), vbox, FALSE, FALSE, 0);\n\n gtk_widget_realize(dialog_);\n gtk_util::SetWindowSizeFromResources(GTK_WINDOW(dialog_),\n IDS_CUSTOMIZE_SYNC_DIALOG_WIDTH_CHARS,\n IDS_CUSTOMIZE_SYNC_DIALOG_HEIGHT_LINES,\n true);\n\n g_signal_connect(dialog_, \"response\", G_CALLBACK(OnResponse), this);\n g_signal_connect(dialog_, \"destroy\", G_CALLBACK(OnWindowDestroy), this);\n\n gtk_util::ShowDialog(dialog_);\n}\n\nCustomizeSyncWindowGtk::~CustomizeSyncWindowGtk() {\n}\n\nvoid CustomizeSyncWindowGtk::Show() {\n \/\/ Bring options window to front if it already existed and isn't already\n \/\/ in front\n gtk_util::PresentWindow(dialog_, 0);\n}\n\nbool CustomizeSyncWindowGtk::ClickOk() {\n\n if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(bookmarks_check_box_)) ||\n (preferences_check_box_ &&\n gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(\n preferences_check_box_))) ||\n (themes_check_box_ &&\n gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(themes_check_box_))) ||\n (autofill_check_box_ &&\n gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(autofill_check_box_)))) {\n Accept();\n gtk_widget_destroy(GTK_WIDGET(dialog_));\n return true;\n } else {\n \/\/ show the user that something's wrong with this dialog (not perfect, but\n \/\/ a temporary fix)\n gtk_util::PresentWindow(dialog_, 0);\n return false;\n }\n}\n\nvoid CustomizeSyncWindowGtk::ClickCancel() {\n gtk_widget_destroy(GTK_WIDGET(dialog_));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomizeSyncWindowGtk, private:\n\nGtkWidget* CustomizeSyncWindowGtk::AddCheckbox(GtkWidget* parent, int label_id,\n bool checked) {\n\n GtkWidget* checkbox = gtk_check_button_new_with_label(\n l10n_util::GetStringUTF8(label_id).c_str());\n\n gtk_box_pack_start(GTK_BOX(parent), checkbox, FALSE, FALSE, 0);\n accessible_widget_helper_->SetWidgetName(checkbox, label_id);\n gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbox), checked);\n\n g_signal_connect(checkbox, \"clicked\", G_CALLBACK(OnCheckboxClickedThunk),\n this);\n\n return checkbox;\n}\n\nbool CustomizeSyncWindowGtk::Accept() {\n syncable::ModelTypeSet preferred_types;\n\n bool bookmarks_enabled = gtk_toggle_button_get_active(\n GTK_TOGGLE_BUTTON(bookmarks_check_box_));\n if (bookmarks_enabled) {\n preferred_types.insert(syncable::BOOKMARKS);\n }\n\n if (preferences_check_box_) {\n bool preferences_enabled = gtk_toggle_button_get_active(\n GTK_TOGGLE_BUTTON(preferences_check_box_));\n if (preferences_enabled) {\n preferred_types.insert(syncable::PREFERENCES);\n }\n }\n if (themes_check_box_) {\n bool themes_enabled = gtk_toggle_button_get_active(\n GTK_TOGGLE_BUTTON(themes_check_box_));\n if (themes_enabled) {\n preferred_types.insert(syncable::THEMES);\n }\n }\n if (autofill_check_box_) {\n bool autofill_enabled = gtk_toggle_button_get_active(\n GTK_TOGGLE_BUTTON(autofill_check_box_));\n if (autofill_enabled) {\n preferred_types.insert(syncable::AUTOFILL);\n }\n }\n\n profile_->GetProfileSyncService()->ChangePreferredDataTypes(preferred_types);\n return true;\n}\n\n\/\/ static\nvoid CustomizeSyncWindowGtk::OnWindowDestroy(GtkWidget* widget,\n CustomizeSyncWindowGtk* window) {\n customize_sync_window = NULL;\n MessageLoop::current()->DeleteSoon(FROM_HERE, window);\n}\n\n\/\/ static\nvoid CustomizeSyncWindowGtk::OnResponse(\n GtkDialog* dialog, gint response_id,\n CustomizeSyncWindowGtk* customize_sync_window) {\n if (response_id == GTK_RESPONSE_OK) {\n customize_sync_window->ClickOk();\n } else if (response_id == GTK_RESPONSE_CANCEL) {\n customize_sync_window->ClickCancel();\n }\n}\n\n\/\/ Deactivate the \"OK\" button if you uncheck all the data types.\nvoid CustomizeSyncWindowGtk::OnCheckboxClicked(GtkWidget* widget) {\n bool any_datatypes_selected =\n gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(bookmarks_check_box_)) ||\n (preferences_check_box_ &&\n gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(\n preferences_check_box_))) ||\n (themes_check_box_ &&\n gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(themes_check_box_))) ||\n (autofill_check_box_ &&\n gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(autofill_check_box_)));\n if (any_datatypes_selected) {\n gtk_dialog_set_response_sensitive(\n GTK_DIALOG(customize_sync_window->dialog_), GTK_RESPONSE_OK, TRUE);\n } else {\n gtk_dialog_set_response_sensitive(\n GTK_DIALOG(customize_sync_window->dialog_), GTK_RESPONSE_OK, FALSE);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Factory\/finder method:\n\nvoid ShowCustomizeSyncWindow(Profile* profile) {\n DCHECK(profile);\n \/\/ If there's already an existing window, use it.\n if (!customize_sync_window) {\n customize_sync_window = new CustomizeSyncWindowGtk(profile);\n }\n customize_sync_window->Show();\n}\n\nbool CustomizeSyncWindowOk() {\n if (customize_sync_window) {\n return customize_sync_window->ClickOk();\n } else {\n return true;\n }\n}\n\nvoid CustomizeSyncWindowCancel() {\n if (customize_sync_window) {\n customize_sync_window->ClickCancel();\n }\n}\n<|endoftext|>"} {"text":"IOSS: Remove debugging output<|endoftext|>"} {"text":"\/*\n *\n * ledger_api_blockchain_explorer_tests\n * ledger-core\n *\n * Created by Pierre Pollastri on 10\/03\/2017.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 Ledger\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \"BaseFixture.h\"\n\ntemplate \nclass LedgerApiBlockchainExplorerTests : public BaseFixture {\npublic:\n void SetUp() override {\n BaseFixture::SetUp();\n auto worker = dispatcher->getSerialExecutionContext(\"worker\");\n auto client = std::make_shared(explorerEndpoint, http, worker);\n explorer = std::make_shared(worker, client, params, api::DynamicObject::newInstance());\n logger = ledger::core::logger::create(\"test_logs\",\n dispatcher->getSerialExecutionContext(\"logger\"),\n resolver,\n printer,\n 2000000000\n );\n }\n NetworkParameters params;\n std::string explorerEndpoint;\n std::shared_ptr logger;\n std::shared_ptr explorer;\n};\n\nclass LedgerApiBitcoinLikeBlockchainExplorerTests : public LedgerApiBlockchainExplorerTests {\npublic:\n LedgerApiBitcoinLikeBlockchainExplorerTests() {\n params = networks::getNetworkParameters(\"bitcoin\");\n explorerEndpoint = \"http:\/\/api.ledgerwallet.com\";\n }\n};\n\nTEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, StartSession) {\n auto session = wait(explorer->startSession());\n EXPECT_EQ(((std::string *)session)->size(), 36);\n}\n\nTEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetRawTransaction) {\n auto transaction = wait(explorer->getRawTransaction(\"9d7945129b78e2f63a72fed93e8ebe38567bdc9318591cfe8c8a7de76c5cb1a3\"));\n auto hex = transaction.toHex();\n EXPECT_EQ(hex.str(), \"0100000001d62dad27a2bdd0c5e72a6288acb4e0acac088b4bc5588e60ff5c3861c4584d71010000006b483045022100d72a8e43c74764a18c5dfec225f1e60dceb12a9bf4931afa1093f14c471f55d202202cf4ed0956fd68dc9ba9d026a4ae04758092487cebff1618e320dcc12d736577012102b62b6c66c0d69ca3272ed3d0884a40bd4fb50ab08bec6de6d899b7389f40e9b5ffffffff026fa40200000000001976a91459fa62dab1f04b4528e5c5446f4c897b53fc983c88ace58f8b00000000001976a914b026e605bb239cf7eafb6437667f0f7f80e827f488ac00000000\");\n\n}\n\nTEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactionByHash) {\n auto transaction = wait(explorer->getTransactionByHash(\"9fdbe15a16fe282291426df15894ab1473e252bc31f244e4d923a17e11743eda\"));\n auto &tx = *transaction.get();\n EXPECT_EQ(tx.inputs.size(), 1);\n EXPECT_EQ(tx.hash, \"9fdbe15a16fe282291426df15894ab1473e252bc31f244e4d923a17e11743eda\");\n EXPECT_EQ(tx.inputs[0].value.getValue().toString(), \"1634001\");\n EXPECT_EQ(tx.inputs[0].address.getValue(), \"1Nd2kJid5fFmPks9KSRpoHQX4VpkPhuATm\");\n EXPECT_EQ(tx.fees.getValue().toString(), \"11350\");\n EXPECT_EQ(tx.outputs.size(), 2);\n EXPECT_EQ(tx.outputs[0].value.toString(), \"1000\");\n EXPECT_EQ(tx.outputs[1].value.toString(), \"1621651\");\n EXPECT_EQ(tx.outputs[0].address.getValue(), \"1QKJghDW4kLqCsH2pq3XKKsSSeYNPcL5PD\");\n EXPECT_EQ(tx.outputs[1].address.getValue(), \"19j8biFtMSy5HFRX6mXiurjz3jszg7nLN5\");\n EXPECT_EQ(tx.block.getValue().hash, \"0000000000000000026aa418ef33e0b079a42d348f35bc0a2fa4bc150a9c459d\");\n EXPECT_EQ(tx.block.getValue().height, 403912);\n \/\/ Checked that real value of 2016-03-23T11:54:21Z corresponds to 1458734061000\n EXPECT_EQ(std::chrono::duration_cast(tx.block.getValue().time.time_since_epoch()).count(), 1458734061000);\n EXPECT_EQ(std::chrono::duration_cast(tx.receivedAt.time_since_epoch()).count(), 1458734061000);\n}\n\nTEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactionByHash_2) {\n auto transaction = wait(explorer->getTransactionByHash(\"16da85a108a63ff318458be597f34f0a7f6b9f703528249056ba2f48722ae44e\"));\n auto &tx = *transaction;\n EXPECT_EQ(tx.inputs.size(), 1);\n EXPECT_EQ(tx.hash, \"16da85a108a63ff318458be597f34f0a7f6b9f703528249056ba2f48722ae44e\");\n EXPECT_EQ(tx.inputs.size(), 1);\n EXPECT_EQ(tx.outputs.size(), 1);\n EXPECT_EQ(tx.inputs[0].coinbase.getValue(), \"03070c070004ebabf05804496e151608bef5342d8b2800000a425720537570706f727420384d200a666973686572206a696e78696e092f425720506f6f6c2f\");\n EXPECT_EQ(tx.outputs[0].address.getValue(), \"1BQLNJtMDKmMZ4PyqVFfRuBNvoGhjigBKF\");\n EXPECT_EQ(tx.outputs[0].value.toString(), \"1380320309\");\n}\n\nTEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactionByHash_3) {\n auto transaction = wait(explorer->getTransactionByHash(\"8d2a0ccbe3a71f3e505be1557995c57f2a26f1951a72931f23a61f18fa4b3d2d\"));\n auto &tx = *transaction;\n EXPECT_EQ(tx.hash, \"8d2a0ccbe3a71f3e505be1557995c57f2a26f1951a72931f23a61f18fa4b3d2d\");\n EXPECT_EQ(tx.inputs.size(), 8);\n EXPECT_EQ(tx.outputs.size(), 2);\n EXPECT_EQ(tx.inputs[5].value.getValue().toString(), \"270000\");\n EXPECT_EQ(tx.inputs[5].index, 5);\n EXPECT_EQ(tx.inputs[5].address.getValue(), \"1BEG75jXGZgH7QsSNjmm9RGJ2fgWcXVbxm\");\n EXPECT_EQ(tx.inputs[5].signatureScript.getValue(), \"483045022100b21b21023b15be3d71fc660513adc4ef1aaa299ee58b9a5c1b8401015d045622022031847f047494c83b199a743d5edd5dbeb33b2dae03dcdff12485b212061d0463012102a7e1245393aa50cf6e08077ac5f4460c2db9c54858f6b0958d91b8d62f39c3bb\");\n EXPECT_EQ(tx.inputs[5].previousTxHash.getValue(), \"64717373eef15249771032b0153daae92d18ea63e997c1c70a33879698b43329\");\n EXPECT_EQ(tx.inputs[5].previousTxOutputIndex.getValue(), 9);\n EXPECT_EQ(tx.outputs[0].address.getValue(), \"14w1wdDMV5uSnBd92yf3N9LfgS6TKVzyYr\");\n EXPECT_EQ(tx.outputs[1].address.getValue(), \"1pCL4HJ3wbNXKiDde8eNmu9uMs1Tkd9hD\");\n}\n\nTEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetCurrentBlock) {\n auto block = wait(explorer->getCurrentBlock());\n EXPECT_GT(block->height, 462400);\n}\n\nTEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactions) {\n auto result = wait(explorer\n ->getTransactions(\n {\"1H6ZZpRmMnrw8ytepV3BYwMjYYnEkWDqVP\", \"1DxPxrQtUXVcebgNYETn163RQaEKxAvxqP\"},\n Option(), Option()));\n EXPECT_TRUE(result->hasNext);\n EXPECT_TRUE(result->transactions.size() > 0);\n}\n\nTEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetFees) {\n auto result = wait(explorer->getFees());\n EXPECT_NE(result.size(), 0);\n if (result.size() > 1) {\n EXPECT_GE(result[0]->intValue(), result[1]->intValue());\n }\n}\n\nTEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, EndSession) {\n auto session = wait(explorer->startSession());\n EXPECT_EQ(((std::string *) session)->size(), 36);\n auto u = wait(explorer->killSession(session));\n}\n\nclass LedgerApiEthereumLikeBlockchainExplorerTests : public LedgerApiBlockchainExplorerTests {\npublic:\n LedgerApiEthereumLikeBlockchainExplorerTests() {\n params = networks::getEthLikeNetworkParameters(\"ethereum_ropsten\");\n explorerEndpoint = \"http:\/\/eth-ropsten.explorers.dev.aws.ledger.fr\";\n }\n};\n\n\nTEST_F(LedgerApiEthereumLikeBlockchainExplorerTests, GetGasPrice) {\n auto result = wait(explorer->getGasPrice());\n EXPECT_NE(result->toUint64(), 0);\n}\n\nTEST_F(LedgerApiEthereumLikeBlockchainExplorerTests, GetEstimatedGasLimit) {\n auto result = wait(explorer->getEstimatedGasLimit(\"0x57e8ba2a915285f984988282ab9346c1336a4e11\"));\n EXPECT_GE(result->toUint64(), 10000);\n}\n\nTEST_F(LedgerApiEthereumLikeBlockchainExplorerTests, PostEstimatedGasLimit) {\n auto request = api::EthereumGasLimitRequest(\n optional(), optional(), optional(),\n optional(\"0xa9059cbb00000000000000000000000013C5d95f25688f8A\"\n \"7544582D9e311f201A56de6300000000000000000000000000\"\n \"00000000000000000000000000000000000000\"),\n optional(), optional(), 1.5);\n auto result = wait(explorer->getDryrunGasLimit(\n \"0x57e8ba2a915285f984988282ab9346c1336a4e11\", request));\n EXPECT_GE(result->toUint64(), 10000);\n}\n[review] Use implicit constructor\/*\n *\n * ledger_api_blockchain_explorer_tests\n * ledger-core\n *\n * Created by Pierre Pollastri on 10\/03\/2017.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 Ledger\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \"BaseFixture.h\"\n\ntemplate \nclass LedgerApiBlockchainExplorerTests : public BaseFixture {\npublic:\n void SetUp() override {\n BaseFixture::SetUp();\n auto worker = dispatcher->getSerialExecutionContext(\"worker\");\n auto client = std::make_shared(explorerEndpoint, http, worker);\n explorer = std::make_shared(worker, client, params, api::DynamicObject::newInstance());\n logger = ledger::core::logger::create(\"test_logs\",\n dispatcher->getSerialExecutionContext(\"logger\"),\n resolver,\n printer,\n 2000000000\n );\n }\n NetworkParameters params;\n std::string explorerEndpoint;\n std::shared_ptr logger;\n std::shared_ptr explorer;\n};\n\nclass LedgerApiBitcoinLikeBlockchainExplorerTests : public LedgerApiBlockchainExplorerTests {\npublic:\n LedgerApiBitcoinLikeBlockchainExplorerTests() {\n params = networks::getNetworkParameters(\"bitcoin\");\n explorerEndpoint = \"http:\/\/api.ledgerwallet.com\";\n }\n};\n\nTEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, StartSession) {\n auto session = wait(explorer->startSession());\n EXPECT_EQ(((std::string *)session)->size(), 36);\n}\n\nTEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetRawTransaction) {\n auto transaction = wait(explorer->getRawTransaction(\"9d7945129b78e2f63a72fed93e8ebe38567bdc9318591cfe8c8a7de76c5cb1a3\"));\n auto hex = transaction.toHex();\n EXPECT_EQ(hex.str(), \"0100000001d62dad27a2bdd0c5e72a6288acb4e0acac088b4bc5588e60ff5c3861c4584d71010000006b483045022100d72a8e43c74764a18c5dfec225f1e60dceb12a9bf4931afa1093f14c471f55d202202cf4ed0956fd68dc9ba9d026a4ae04758092487cebff1618e320dcc12d736577012102b62b6c66c0d69ca3272ed3d0884a40bd4fb50ab08bec6de6d899b7389f40e9b5ffffffff026fa40200000000001976a91459fa62dab1f04b4528e5c5446f4c897b53fc983c88ace58f8b00000000001976a914b026e605bb239cf7eafb6437667f0f7f80e827f488ac00000000\");\n\n}\n\nTEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactionByHash) {\n auto transaction = wait(explorer->getTransactionByHash(\"9fdbe15a16fe282291426df15894ab1473e252bc31f244e4d923a17e11743eda\"));\n auto &tx = *transaction.get();\n EXPECT_EQ(tx.inputs.size(), 1);\n EXPECT_EQ(tx.hash, \"9fdbe15a16fe282291426df15894ab1473e252bc31f244e4d923a17e11743eda\");\n EXPECT_EQ(tx.inputs[0].value.getValue().toString(), \"1634001\");\n EXPECT_EQ(tx.inputs[0].address.getValue(), \"1Nd2kJid5fFmPks9KSRpoHQX4VpkPhuATm\");\n EXPECT_EQ(tx.fees.getValue().toString(), \"11350\");\n EXPECT_EQ(tx.outputs.size(), 2);\n EXPECT_EQ(tx.outputs[0].value.toString(), \"1000\");\n EXPECT_EQ(tx.outputs[1].value.toString(), \"1621651\");\n EXPECT_EQ(tx.outputs[0].address.getValue(), \"1QKJghDW4kLqCsH2pq3XKKsSSeYNPcL5PD\");\n EXPECT_EQ(tx.outputs[1].address.getValue(), \"19j8biFtMSy5HFRX6mXiurjz3jszg7nLN5\");\n EXPECT_EQ(tx.block.getValue().hash, \"0000000000000000026aa418ef33e0b079a42d348f35bc0a2fa4bc150a9c459d\");\n EXPECT_EQ(tx.block.getValue().height, 403912);\n \/\/ Checked that real value of 2016-03-23T11:54:21Z corresponds to 1458734061000\n EXPECT_EQ(std::chrono::duration_cast(tx.block.getValue().time.time_since_epoch()).count(), 1458734061000);\n EXPECT_EQ(std::chrono::duration_cast(tx.receivedAt.time_since_epoch()).count(), 1458734061000);\n}\n\nTEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactionByHash_2) {\n auto transaction = wait(explorer->getTransactionByHash(\"16da85a108a63ff318458be597f34f0a7f6b9f703528249056ba2f48722ae44e\"));\n auto &tx = *transaction;\n EXPECT_EQ(tx.inputs.size(), 1);\n EXPECT_EQ(tx.hash, \"16da85a108a63ff318458be597f34f0a7f6b9f703528249056ba2f48722ae44e\");\n EXPECT_EQ(tx.inputs.size(), 1);\n EXPECT_EQ(tx.outputs.size(), 1);\n EXPECT_EQ(tx.inputs[0].coinbase.getValue(), \"03070c070004ebabf05804496e151608bef5342d8b2800000a425720537570706f727420384d200a666973686572206a696e78696e092f425720506f6f6c2f\");\n EXPECT_EQ(tx.outputs[0].address.getValue(), \"1BQLNJtMDKmMZ4PyqVFfRuBNvoGhjigBKF\");\n EXPECT_EQ(tx.outputs[0].value.toString(), \"1380320309\");\n}\n\nTEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactionByHash_3) {\n auto transaction = wait(explorer->getTransactionByHash(\"8d2a0ccbe3a71f3e505be1557995c57f2a26f1951a72931f23a61f18fa4b3d2d\"));\n auto &tx = *transaction;\n EXPECT_EQ(tx.hash, \"8d2a0ccbe3a71f3e505be1557995c57f2a26f1951a72931f23a61f18fa4b3d2d\");\n EXPECT_EQ(tx.inputs.size(), 8);\n EXPECT_EQ(tx.outputs.size(), 2);\n EXPECT_EQ(tx.inputs[5].value.getValue().toString(), \"270000\");\n EXPECT_EQ(tx.inputs[5].index, 5);\n EXPECT_EQ(tx.inputs[5].address.getValue(), \"1BEG75jXGZgH7QsSNjmm9RGJ2fgWcXVbxm\");\n EXPECT_EQ(tx.inputs[5].signatureScript.getValue(), \"483045022100b21b21023b15be3d71fc660513adc4ef1aaa299ee58b9a5c1b8401015d045622022031847f047494c83b199a743d5edd5dbeb33b2dae03dcdff12485b212061d0463012102a7e1245393aa50cf6e08077ac5f4460c2db9c54858f6b0958d91b8d62f39c3bb\");\n EXPECT_EQ(tx.inputs[5].previousTxHash.getValue(), \"64717373eef15249771032b0153daae92d18ea63e997c1c70a33879698b43329\");\n EXPECT_EQ(tx.inputs[5].previousTxOutputIndex.getValue(), 9);\n EXPECT_EQ(tx.outputs[0].address.getValue(), \"14w1wdDMV5uSnBd92yf3N9LfgS6TKVzyYr\");\n EXPECT_EQ(tx.outputs[1].address.getValue(), \"1pCL4HJ3wbNXKiDde8eNmu9uMs1Tkd9hD\");\n}\n\nTEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetCurrentBlock) {\n auto block = wait(explorer->getCurrentBlock());\n EXPECT_GT(block->height, 462400);\n}\n\nTEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactions) {\n auto result = wait(explorer\n ->getTransactions(\n {\"1H6ZZpRmMnrw8ytepV3BYwMjYYnEkWDqVP\", \"1DxPxrQtUXVcebgNYETn163RQaEKxAvxqP\"},\n Option(), Option()));\n EXPECT_TRUE(result->hasNext);\n EXPECT_TRUE(result->transactions.size() > 0);\n}\n\nTEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetFees) {\n auto result = wait(explorer->getFees());\n EXPECT_NE(result.size(), 0);\n if (result.size() > 1) {\n EXPECT_GE(result[0]->intValue(), result[1]->intValue());\n }\n}\n\nTEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, EndSession) {\n auto session = wait(explorer->startSession());\n EXPECT_EQ(((std::string *) session)->size(), 36);\n auto u = wait(explorer->killSession(session));\n}\n\nclass LedgerApiEthereumLikeBlockchainExplorerTests : public LedgerApiBlockchainExplorerTests {\npublic:\n LedgerApiEthereumLikeBlockchainExplorerTests() {\n params = networks::getEthLikeNetworkParameters(\"ethereum_ropsten\");\n explorerEndpoint = \"http:\/\/eth-ropsten.explorers.dev.aws.ledger.fr\";\n }\n};\n\n\nTEST_F(LedgerApiEthereumLikeBlockchainExplorerTests, GetGasPrice) {\n auto result = wait(explorer->getGasPrice());\n EXPECT_NE(result->toUint64(), 0);\n}\n\nTEST_F(LedgerApiEthereumLikeBlockchainExplorerTests, GetEstimatedGasLimit) {\n auto result = wait(explorer->getEstimatedGasLimit(\"0x57e8ba2a915285f984988282ab9346c1336a4e11\"));\n EXPECT_GE(result->toUint64(), 10000);\n}\n\nTEST_F(LedgerApiEthereumLikeBlockchainExplorerTests, PostEstimatedGasLimit) {\n auto request = api::EthereumGasLimitRequest(\n optional(), optional(), optional(),\n \"0xa9059cbb00000000000000000000000013C5d95f25688f8A\"\n \"7544582D9e311f201A56de6300000000000000000000000000\"\n \"00000000000000000000000000000000000000\",\n optional(), optional(), 1.5);\n auto result = wait(explorer->getDryrunGasLimit(\n \"0x57e8ba2a915285f984988282ab9346c1336a4e11\", request));\n EXPECT_GE(result->toUint64(), 10000);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/fullscreen_exit_bubble_views.h\"\n\n#include \"base\/message_loop.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/browser\/ui\/views\/bubble\/bubble.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/base\/animation\/slide_animation.h\"\n#include \"ui\/base\/keycodes\/keyboard_codes.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/gfx\/canvas_skia.h\"\n#include \"ui\/gfx\/screen.h\"\n#include \"views\/bubble\/bubble_border.h\"\n#include \"views\/controls\/button\/text_button.h\"\n#include \"views\/controls\/link.h\"\n#include \"views\/widget\/widget.h\"\n\n#if defined(OS_WIN)\n#include \"ui\/base\/l10n\/l10n_util_win.h\"\n#endif\n\n\/\/ FullscreenExitView ----------------------------------------------------------\n\nnamespace {\n\/\/ Space between the site info label and the buttons \/ link.\nconst int kMiddlePaddingPx = 30;\n} \/\/ namespace\n\nclass FullscreenExitBubbleViews::FullscreenExitView\n : public views::View,\n public views::ButtonListener {\n public:\n FullscreenExitView(FullscreenExitBubbleViews* bubble,\n const string16& accelerator,\n const GURL& url,\n bool ask_permission);\n virtual ~FullscreenExitView();\n\n \/\/ views::View\n virtual gfx::Size GetPreferredSize();\n\n \/\/ views::ButtonListener\n virtual void ButtonPressed(views::Button* sender, const views::Event& event);\n\n \/\/ Hide the accept and deny buttons, exposing the exit link.\n void HideButtons();\n\n private:\n string16 GetMessage(const GURL& url);\n\n \/\/ views::View\n virtual void Layout();\n\n FullscreenExitBubbleViews* bubble_;\n\n \/\/ Clickable hint text to show in the bubble.\n views::Link link_;\n views::Label message_label_;\n views::NativeTextButton* accept_button_;\n views::NativeTextButton* deny_button_;\n\n bool show_buttons_;\n};\n\nFullscreenExitBubbleViews::FullscreenExitView::FullscreenExitView(\n FullscreenExitBubbleViews* bubble,\n const string16& accelerator,\n const GURL& url,\n bool ask_permission)\n : bubble_(bubble),\n accept_button_(NULL),\n deny_button_(NULL),\n show_buttons_(ask_permission) {\n views::BubbleBorder* bubble_border =\n new views::BubbleBorder(views::BubbleBorder::NONE);\n bubble_border->set_background_color(Bubble::kBackgroundColor);\n set_background(new views::BubbleBackground(bubble_border));\n set_border(bubble_border);\n set_focusable(false);\n\n message_label_.set_parent_owned(false);\n message_label_.SetText(GetMessage(url));\n message_label_.SetFont(ResourceBundle::GetSharedInstance().GetFont(\n ResourceBundle::MediumFont));\n\n link_.set_parent_owned(false);\n link_.set_collapse_when_hidden(false);\n link_.set_focusable(false);\n#if !defined(OS_CHROMEOS)\n link_.SetText(\n l10n_util::GetStringFUTF16(IDS_EXIT_FULLSCREEN_MODE,\n accelerator));\n#else\n link_.SetText(l10n_util::GetStringUTF16(IDS_EXIT_FULLSCREEN_MODE));\n#endif\n link_.set_listener(bubble);\n link_.SetFont(ResourceBundle::GetSharedInstance().GetFont(\n ResourceBundle::MediumFont));\n link_.SetPressedColor(message_label_.enabled_color());\n link_.SetEnabledColor(message_label_.enabled_color());\n link_.SetVisible(false);\n\n link_.SetBackgroundColor(background()->get_color());\n message_label_.SetBackgroundColor(background()->get_color());\n AddChildView(&message_label_);\n AddChildView(&link_);\n\n accept_button_ = new views::NativeTextButton(this,\n UTF16ToWide(l10n_util::GetStringUTF16(IDS_FULLSCREEN_INFOBAR_ALLOW)));\n accept_button_->set_focusable(false);\n AddChildView(accept_button_);\n\n deny_button_ = new views::NativeTextButton(this,\n UTF16ToWide(l10n_util::GetStringUTF16(IDS_FULLSCREEN_INFOBAR_DENY)));\n deny_button_->set_focusable(false);\n AddChildView(deny_button_);\n\n if (!show_buttons_)\n HideButtons();\n}\n\nstring16 FullscreenExitBubbleViews::FullscreenExitView::GetMessage(\n const GURL& url) {\n if (url.is_empty()) {\n return l10n_util::GetStringUTF16(\n IDS_FULLSCREEN_INFOBAR_USER_ENTERED_FULLSCREEN);\n }\n if (url.SchemeIsFile())\n return l10n_util::GetStringUTF16(IDS_FULLSCREEN_INFOBAR_FILE_PAGE_NAME);\n return l10n_util::GetStringFUTF16(IDS_FULLSCREEN_INFOBAR_REQUEST_PERMISSION,\n UTF8ToUTF16(url.host()));\n}\n\nFullscreenExitBubbleViews::FullscreenExitView::~FullscreenExitView() {\n}\n\nvoid FullscreenExitBubbleViews::FullscreenExitView::ButtonPressed(\n views::Button* sender, const views::Event& event) {\n if (sender == accept_button_)\n bubble_->OnAcceptFullscreen();\n else\n bubble_->OnCancelFullscreen();\n}\n\nvoid FullscreenExitBubbleViews::FullscreenExitView::HideButtons() {\n show_buttons_ = false;\n accept_button_->SetVisible(false);\n deny_button_->SetVisible(false);\n link_.SetVisible(true);\n}\n\ngfx::Size FullscreenExitBubbleViews::FullscreenExitView::GetPreferredSize() {\n gfx::Size link_size(link_.GetPreferredSize());\n gfx::Size message_label_size(message_label_.GetPreferredSize());\n gfx::Size accept_size(accept_button_->GetPreferredSize());\n gfx::Size deny_size(deny_button_->GetPreferredSize());\n gfx::Insets insets(GetInsets());\n\n int buttons_width = accept_size.width() + kPaddingPx +\n deny_size.width();\n int button_box_width = std::max(buttons_width, link_size.width());\n int width = kPaddingPx + message_label_size.width() + kMiddlePaddingPx +\n button_box_width + kPaddingPx;\n\n gfx::Size result(width + insets.width(),\n kPaddingPx * 2 + accept_size.height() + insets.height());\n return result;\n}\n\nvoid FullscreenExitBubbleViews::FullscreenExitView::Layout() {\n gfx::Size link_size(link_.GetPreferredSize());\n gfx::Size message_label_size(message_label_.GetPreferredSize());\n gfx::Size accept_size(accept_button_->GetPreferredSize());\n gfx::Size deny_size(deny_button_->GetPreferredSize());\n gfx::Insets insets(GetInsets());\n\n int inner_height = height() - insets.height();\n int button_box_x = insets.left() + kPaddingPx +\n message_label_size.width() + kMiddlePaddingPx;\n int message_label_y = insets.top() +\n (inner_height - message_label_size.height()) \/ 2;\n int link_x = width() - insets.right() - kPaddingPx -\n link_size.width();\n int link_y = insets.top() + (inner_height - link_size.height()) \/ 2;\n\n message_label_.SetPosition(gfx::Point(insets.left() + kPaddingPx,\n message_label_y));\n link_.SetPosition(gfx::Point(link_x, link_y));\n if (show_buttons_) {\n accept_button_->SetPosition(gfx::Point(button_box_x,\n insets.top() + kPaddingPx));\n deny_button_->SetPosition(gfx::Point(\n button_box_x + accept_size.width() + kPaddingPx,\n insets.top() + kPaddingPx));\n }\n}\n\n\/\/ FullscreenExitBubbleViews ---------------------------------------------------\n\nFullscreenExitBubbleViews::FullscreenExitBubbleViews(views::Widget* frame,\n Browser* browser,\n const GURL& url,\n bool ask_permission)\n : FullscreenExitBubble(browser),\n root_view_(frame->GetRootView()),\n popup_(NULL),\n size_animation_(new ui::SlideAnimation(this)),\n url_(url) {\n size_animation_->Reset(1);\n\n \/\/ Create the contents view.\n views::Accelerator accelerator(ui::VKEY_UNKNOWN, false, false, false);\n bool got_accelerator = frame->GetAccelerator(IDC_FULLSCREEN, &accelerator);\n DCHECK(got_accelerator);\n view_ = new FullscreenExitView(this,\n accelerator.GetShortcutText(), url, ask_permission);\n\n \/\/ Initialize the popup.\n popup_ = new views::Widget;\n views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP);\n params.transparent = true;\n params.can_activate = false;\n params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;\n params.parent = frame->GetNativeView();\n params.bounds = GetPopupRect(false);\n popup_->Init(params);\n gfx::Size size = GetPopupRect(true).size();\n popup_->SetContentsView(view_);\n \/\/ We set layout manager to NULL to prevent the widget from sizing its\n \/\/ contents to the same size as itself. This prevents the widget contents from\n \/\/ shrinking while we animate the height of the popup to give the impression\n \/\/ that it is sliding off the top of the screen.\n popup_->GetRootView()->SetLayoutManager(NULL);\n view_->SetBounds(0, 0, size.width(), size.height());\n popup_->Show(); \/\/ This does not activate the popup.\n\n if (!ask_permission)\n StartWatchingMouse();\n}\n\nFullscreenExitBubbleViews::~FullscreenExitBubbleViews() {\n \/\/ This is tricky. We may be in an ATL message handler stack, in which case\n \/\/ the popup cannot be deleted yet. We also can't set the popup's ownership\n \/\/ model to NATIVE_WIDGET_OWNS_WIDGET because if the user closed the last tab\n \/\/ while in fullscreen mode, Windows has already destroyed the popup HWND by\n \/\/ the time we get here, and thus either the popup will already have been\n \/\/ deleted (if we set this in our constructor) or the popup will never get\n \/\/ another OnFinalMessage() call (if not, as currently). So instead, we tell\n \/\/ the popup to synchronously hide, and then asynchronously close and delete\n \/\/ itself.\n popup_->Close();\n MessageLoop::current()->DeleteSoon(FROM_HERE, popup_);\n}\n\nvoid FullscreenExitBubbleViews::LinkClicked(\n views::Link* source, int event_flags) {\n ToggleFullscreen();\n}\n\nvoid FullscreenExitBubbleViews::OnAcceptFullscreen() {\n AcceptFullscreen(url_);\n view_->HideButtons();\n StartWatchingMouse();\n}\n\nvoid FullscreenExitBubbleViews::OnCancelFullscreen() {\n CancelFullscreen();\n}\n\nvoid FullscreenExitBubbleViews::AnimationProgressed(\n const ui::Animation* animation) {\n gfx::Rect popup_rect(GetPopupRect(false));\n if (popup_rect.IsEmpty()) {\n popup_->Hide();\n } else {\n popup_->SetBounds(popup_rect);\n view_->SetY(popup_rect.height() - view_->height());\n popup_->Show();\n }\n}\n\nvoid FullscreenExitBubbleViews::AnimationEnded(\n const ui::Animation* animation) {\n AnimationProgressed(animation);\n}\n\nvoid FullscreenExitBubbleViews::Hide() {\n size_animation_->SetSlideDuration(kSlideOutDurationMs);\n size_animation_->Hide();\n}\n\nvoid FullscreenExitBubbleViews::Show() {\n size_animation_->SetSlideDuration(kSlideInDurationMs);\n size_animation_->Show();\n}\n\nbool FullscreenExitBubbleViews::IsAnimating() {\n return size_animation_->GetCurrentValue() != 0;\n}\n\nbool FullscreenExitBubbleViews::IsWindowActive() {\n return root_view_->GetWidget()->IsActive();\n}\n\nbool FullscreenExitBubbleViews::WindowContainsPoint(gfx::Point pos) {\n return root_view_->HitTest(pos);\n}\n\ngfx::Point FullscreenExitBubbleViews::GetCursorScreenPoint() {\n gfx::Point cursor_pos = gfx::Screen::GetCursorScreenPoint();\n gfx::Point transformed_pos(cursor_pos);\n views::View::ConvertPointToView(NULL, root_view_, &transformed_pos);\n return transformed_pos;\n}\n\ngfx::Rect FullscreenExitBubbleViews::GetPopupRect(\n bool ignore_animation_state) const {\n gfx::Size size(view_->GetPreferredSize());\n \/\/ NOTE: don't use the bounds of the root_view_. On linux changing window\n \/\/ size is async. Instead we use the size of the screen.\n gfx::Rect screen_bounds = gfx::Screen::GetMonitorAreaNearestWindow(\n root_view_->GetWidget()->GetNativeView());\n gfx::Point origin(screen_bounds.x() +\n (screen_bounds.width() - size.width()) \/ 2,\n kPopupTopPx + screen_bounds.y());\n if (!ignore_animation_state) {\n int total_height = size.height() + kPopupTopPx;\n int popup_bottom = size_animation_->CurrentValueBetween(\n static_cast(total_height), 0.0f);\n int y_offset = std::min(popup_bottom, kPopupTopPx);\n size.set_height(size.height() - popup_bottom + y_offset);\n origin.set_y(origin.y() - y_offset);\n }\n return gfx::Rect(origin, size);\n}\nChange SetPosition() to SetBounds() in FullscreenExitView::Layout().\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/fullscreen_exit_bubble_views.h\"\n\n#include \"base\/message_loop.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/browser\/ui\/views\/bubble\/bubble.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/base\/animation\/slide_animation.h\"\n#include \"ui\/base\/keycodes\/keyboard_codes.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/gfx\/canvas_skia.h\"\n#include \"ui\/gfx\/screen.h\"\n#include \"views\/bubble\/bubble_border.h\"\n#include \"views\/controls\/button\/text_button.h\"\n#include \"views\/controls\/link.h\"\n#include \"views\/widget\/widget.h\"\n\n#if defined(OS_WIN)\n#include \"ui\/base\/l10n\/l10n_util_win.h\"\n#endif\n\n\/\/ FullscreenExitView ----------------------------------------------------------\n\nnamespace {\n\/\/ Space between the site info label and the buttons \/ link.\nconst int kMiddlePaddingPx = 30;\n} \/\/ namespace\n\nclass FullscreenExitBubbleViews::FullscreenExitView\n : public views::View,\n public views::ButtonListener {\n public:\n FullscreenExitView(FullscreenExitBubbleViews* bubble,\n const string16& accelerator,\n const GURL& url,\n bool ask_permission);\n virtual ~FullscreenExitView();\n\n \/\/ views::View\n virtual gfx::Size GetPreferredSize();\n\n \/\/ views::ButtonListener\n virtual void ButtonPressed(views::Button* sender, const views::Event& event);\n\n \/\/ Hide the accept and deny buttons, exposing the exit link.\n void HideButtons();\n\n private:\n string16 GetMessage(const GURL& url);\n\n \/\/ views::View\n virtual void Layout();\n\n FullscreenExitBubbleViews* bubble_;\n\n \/\/ Clickable hint text to show in the bubble.\n views::Link link_;\n views::Label message_label_;\n views::NativeTextButton* accept_button_;\n views::NativeTextButton* deny_button_;\n\n bool show_buttons_;\n};\n\nFullscreenExitBubbleViews::FullscreenExitView::FullscreenExitView(\n FullscreenExitBubbleViews* bubble,\n const string16& accelerator,\n const GURL& url,\n bool ask_permission)\n : bubble_(bubble),\n accept_button_(NULL),\n deny_button_(NULL),\n show_buttons_(ask_permission) {\n views::BubbleBorder* bubble_border =\n new views::BubbleBorder(views::BubbleBorder::NONE);\n bubble_border->set_background_color(Bubble::kBackgroundColor);\n set_background(new views::BubbleBackground(bubble_border));\n set_border(bubble_border);\n set_focusable(false);\n\n message_label_.set_parent_owned(false);\n message_label_.SetText(GetMessage(url));\n message_label_.SetFont(ResourceBundle::GetSharedInstance().GetFont(\n ResourceBundle::MediumFont));\n\n link_.set_parent_owned(false);\n link_.set_collapse_when_hidden(false);\n link_.set_focusable(false);\n#if !defined(OS_CHROMEOS)\n link_.SetText(\n l10n_util::GetStringFUTF16(IDS_EXIT_FULLSCREEN_MODE,\n accelerator));\n#else\n link_.SetText(l10n_util::GetStringUTF16(IDS_EXIT_FULLSCREEN_MODE));\n#endif\n link_.set_listener(bubble);\n link_.SetFont(ResourceBundle::GetSharedInstance().GetFont(\n ResourceBundle::MediumFont));\n link_.SetPressedColor(message_label_.enabled_color());\n link_.SetEnabledColor(message_label_.enabled_color());\n link_.SetVisible(false);\n\n link_.SetBackgroundColor(background()->get_color());\n message_label_.SetBackgroundColor(background()->get_color());\n AddChildView(&message_label_);\n AddChildView(&link_);\n\n accept_button_ = new views::NativeTextButton(this,\n UTF16ToWide(l10n_util::GetStringUTF16(IDS_FULLSCREEN_INFOBAR_ALLOW)));\n accept_button_->set_focusable(false);\n AddChildView(accept_button_);\n\n deny_button_ = new views::NativeTextButton(this,\n UTF16ToWide(l10n_util::GetStringUTF16(IDS_FULLSCREEN_INFOBAR_DENY)));\n deny_button_->set_focusable(false);\n AddChildView(deny_button_);\n\n if (!show_buttons_)\n HideButtons();\n}\n\nstring16 FullscreenExitBubbleViews::FullscreenExitView::GetMessage(\n const GURL& url) {\n if (url.is_empty()) {\n return l10n_util::GetStringUTF16(\n IDS_FULLSCREEN_INFOBAR_USER_ENTERED_FULLSCREEN);\n }\n if (url.SchemeIsFile())\n return l10n_util::GetStringUTF16(IDS_FULLSCREEN_INFOBAR_FILE_PAGE_NAME);\n return l10n_util::GetStringFUTF16(IDS_FULLSCREEN_INFOBAR_REQUEST_PERMISSION,\n UTF8ToUTF16(url.host()));\n}\n\nFullscreenExitBubbleViews::FullscreenExitView::~FullscreenExitView() {\n}\n\nvoid FullscreenExitBubbleViews::FullscreenExitView::ButtonPressed(\n views::Button* sender, const views::Event& event) {\n if (sender == accept_button_)\n bubble_->OnAcceptFullscreen();\n else\n bubble_->OnCancelFullscreen();\n}\n\nvoid FullscreenExitBubbleViews::FullscreenExitView::HideButtons() {\n show_buttons_ = false;\n accept_button_->SetVisible(false);\n deny_button_->SetVisible(false);\n link_.SetVisible(true);\n}\n\ngfx::Size FullscreenExitBubbleViews::FullscreenExitView::GetPreferredSize() {\n gfx::Size link_size(link_.GetPreferredSize());\n gfx::Size message_label_size(message_label_.GetPreferredSize());\n gfx::Size accept_size(accept_button_->GetPreferredSize());\n gfx::Size deny_size(deny_button_->GetPreferredSize());\n gfx::Insets insets(GetInsets());\n\n int buttons_width = accept_size.width() + kPaddingPx +\n deny_size.width();\n int button_box_width = std::max(buttons_width, link_size.width());\n int width = kPaddingPx + message_label_size.width() + kMiddlePaddingPx +\n button_box_width + kPaddingPx;\n\n gfx::Size result(width + insets.width(),\n kPaddingPx * 2 + accept_size.height() + insets.height());\n return result;\n}\n\nvoid FullscreenExitBubbleViews::FullscreenExitView::Layout() {\n gfx::Size link_size(link_.GetPreferredSize());\n gfx::Size message_label_size(message_label_.GetPreferredSize());\n gfx::Size accept_size(accept_button_->GetPreferredSize());\n gfx::Size deny_size(deny_button_->GetPreferredSize());\n gfx::Insets insets(GetInsets());\n\n int inner_height = height() - insets.height();\n int button_box_x = insets.left() + kPaddingPx +\n message_label_size.width() + kMiddlePaddingPx;\n int message_label_y = insets.top() +\n (inner_height - message_label_size.height()) \/ 2;\n int link_x = width() - insets.right() - kPaddingPx -\n link_size.width();\n int link_y = insets.top() + (inner_height - link_size.height()) \/ 2;\n\n message_label_.SetBounds(insets.left() + kPaddingPx,\n message_label_y,\n message_label_size.width(),\n message_label_size.height());\n link_.SetBounds(link_x,\n link_y,\n link_size.width(),\n link_size.height());\n if (show_buttons_) {\n accept_button_->SetBounds(button_box_x,\n insets.top() + kPaddingPx,\n accept_size.width(),\n accept_size.height());\n deny_button_->SetBounds(button_box_x + accept_size.width() + kPaddingPx,\n insets.top() + kPaddingPx,\n deny_size.width(),\n deny_size.height());\n }\n}\n\n\/\/ FullscreenExitBubbleViews ---------------------------------------------------\n\nFullscreenExitBubbleViews::FullscreenExitBubbleViews(views::Widget* frame,\n Browser* browser,\n const GURL& url,\n bool ask_permission)\n : FullscreenExitBubble(browser),\n root_view_(frame->GetRootView()),\n popup_(NULL),\n size_animation_(new ui::SlideAnimation(this)),\n url_(url) {\n size_animation_->Reset(1);\n\n \/\/ Create the contents view.\n views::Accelerator accelerator(ui::VKEY_UNKNOWN, false, false, false);\n bool got_accelerator = frame->GetAccelerator(IDC_FULLSCREEN, &accelerator);\n DCHECK(got_accelerator);\n view_ = new FullscreenExitView(this,\n accelerator.GetShortcutText(), url, ask_permission);\n\n \/\/ Initialize the popup.\n popup_ = new views::Widget;\n views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP);\n params.transparent = true;\n params.can_activate = false;\n params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;\n params.parent = frame->GetNativeView();\n params.bounds = GetPopupRect(false);\n popup_->Init(params);\n gfx::Size size = GetPopupRect(true).size();\n popup_->SetContentsView(view_);\n \/\/ We set layout manager to NULL to prevent the widget from sizing its\n \/\/ contents to the same size as itself. This prevents the widget contents from\n \/\/ shrinking while we animate the height of the popup to give the impression\n \/\/ that it is sliding off the top of the screen.\n popup_->GetRootView()->SetLayoutManager(NULL);\n view_->SetBounds(0, 0, size.width(), size.height());\n popup_->Show(); \/\/ This does not activate the popup.\n\n if (!ask_permission)\n StartWatchingMouse();\n}\n\nFullscreenExitBubbleViews::~FullscreenExitBubbleViews() {\n \/\/ This is tricky. We may be in an ATL message handler stack, in which case\n \/\/ the popup cannot be deleted yet. We also can't set the popup's ownership\n \/\/ model to NATIVE_WIDGET_OWNS_WIDGET because if the user closed the last tab\n \/\/ while in fullscreen mode, Windows has already destroyed the popup HWND by\n \/\/ the time we get here, and thus either the popup will already have been\n \/\/ deleted (if we set this in our constructor) or the popup will never get\n \/\/ another OnFinalMessage() call (if not, as currently). So instead, we tell\n \/\/ the popup to synchronously hide, and then asynchronously close and delete\n \/\/ itself.\n popup_->Close();\n MessageLoop::current()->DeleteSoon(FROM_HERE, popup_);\n}\n\nvoid FullscreenExitBubbleViews::LinkClicked(\n views::Link* source, int event_flags) {\n ToggleFullscreen();\n}\n\nvoid FullscreenExitBubbleViews::OnAcceptFullscreen() {\n AcceptFullscreen(url_);\n view_->HideButtons();\n StartWatchingMouse();\n}\n\nvoid FullscreenExitBubbleViews::OnCancelFullscreen() {\n CancelFullscreen();\n}\n\nvoid FullscreenExitBubbleViews::AnimationProgressed(\n const ui::Animation* animation) {\n gfx::Rect popup_rect(GetPopupRect(false));\n if (popup_rect.IsEmpty()) {\n popup_->Hide();\n } else {\n popup_->SetBounds(popup_rect);\n view_->SetY(popup_rect.height() - view_->height());\n popup_->Show();\n }\n}\n\nvoid FullscreenExitBubbleViews::AnimationEnded(\n const ui::Animation* animation) {\n AnimationProgressed(animation);\n}\n\nvoid FullscreenExitBubbleViews::Hide() {\n size_animation_->SetSlideDuration(kSlideOutDurationMs);\n size_animation_->Hide();\n}\n\nvoid FullscreenExitBubbleViews::Show() {\n size_animation_->SetSlideDuration(kSlideInDurationMs);\n size_animation_->Show();\n}\n\nbool FullscreenExitBubbleViews::IsAnimating() {\n return size_animation_->GetCurrentValue() != 0;\n}\n\nbool FullscreenExitBubbleViews::IsWindowActive() {\n return root_view_->GetWidget()->IsActive();\n}\n\nbool FullscreenExitBubbleViews::WindowContainsPoint(gfx::Point pos) {\n return root_view_->HitTest(pos);\n}\n\ngfx::Point FullscreenExitBubbleViews::GetCursorScreenPoint() {\n gfx::Point cursor_pos = gfx::Screen::GetCursorScreenPoint();\n gfx::Point transformed_pos(cursor_pos);\n views::View::ConvertPointToView(NULL, root_view_, &transformed_pos);\n return transformed_pos;\n}\n\ngfx::Rect FullscreenExitBubbleViews::GetPopupRect(\n bool ignore_animation_state) const {\n gfx::Size size(view_->GetPreferredSize());\n \/\/ NOTE: don't use the bounds of the root_view_. On linux changing window\n \/\/ size is async. Instead we use the size of the screen.\n gfx::Rect screen_bounds = gfx::Screen::GetMonitorAreaNearestWindow(\n root_view_->GetWidget()->GetNativeView());\n gfx::Point origin(screen_bounds.x() +\n (screen_bounds.width() - size.width()) \/ 2,\n kPopupTopPx + screen_bounds.y());\n if (!ignore_animation_state) {\n int total_height = size.height() + kPopupTopPx;\n int popup_bottom = size_animation_->CurrentValueBetween(\n static_cast(total_height), 0.0f);\n int y_offset = std::min(popup_bottom, kPopupTopPx);\n size.set_height(size.height() - popup_bottom + y_offset);\n origin.set_y(origin.y() - y_offset);\n }\n return gfx::Rect(origin, size);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_temp_dir.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/extensions\/extension_constants.h\"\n#include \"chrome\/common\/extensions\/extension_unpacker.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n\nnamespace errors = extension_manifest_errors;\nnamespace keys = extension_manifest_keys;\n\nclass ExtensionUnpackerTest : public testing::Test {\npublic:\n void SetupUnpacker(const std::string& crx_name) {\n FilePath original_path;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &original_path));\n original_path = original_path.AppendASCII(\"extensions\")\n .AppendASCII(\"unpacker\")\n .AppendASCII(crx_name);\n ASSERT_TRUE(file_util::PathExists(original_path)) << original_path.value();\n\n \/\/ Try bots won't let us write into DIR_TEST_DATA, so we have to create\n \/\/ a temp folder to play in.\n ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());\n\n FilePath crx_path = temp_dir_.path().AppendASCII(crx_name);\n ASSERT_TRUE(file_util::CopyFile(original_path, crx_path)) <<\n \"Original path \" << original_path.value() <<\n \", Crx path \" << crx_path.value();\n\n unpacker_.reset(\n new ExtensionUnpacker(\n crx_path, Extension::INTERNAL, Extension::NO_FLAGS));\n }\n\n protected:\n ScopedTempDir temp_dir_;\n scoped_ptr unpacker_;\n};\n\n\/\/ Crashes intermittently on Windows, see http:\/\/crbug.com\/109238\n#if defined(OS_WIN)\n#define MAYBE_EmptyDefaultLocale DISABLED_EmptyDefaultLocale\n#else\n#define MAYBE_EmptyDefaultLocale EmptyDefaultLocale\n#endif\nTEST_F(ExtensionUnpackerTest, MAYBE_EmptyDefaultLocale) {\n SetupUnpacker(\"empty_default_locale.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kInvalidDefaultLocale),\n unpacker_->error_message());\n}\n\n\/\/ Crashes intermittently on Vista, see http:\/\/crbug.com\/109385\n#if defined(OS_WIN)\n#define MAYBE_HasDefaultLocaleMissingLocalesFolder \\\n DISABLED_HasDefaultLocaleMissingLocalesFolder\n#else\n#define MAYBE_HasDefaultLocaleMissingLocalesFolder \\\n HasDefaultLocaleMissingLocalesFolder\n#endif\nTEST_F(ExtensionUnpackerTest, MAYBE_HasDefaultLocaleMissingLocalesFolder) {\n SetupUnpacker(\"has_default_missing_locales.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kLocalesTreeMissing),\n unpacker_->error_message());\n}\n\n\/\/ Crashes intermittently on Windows, see http:\/\/crbug.com\/109238\n#if defined(OS_WIN)\n#define MAYBE_InvalidDefaultLocale DISABLED_InvalidDefaultLocale\n#else\n#define MAYBE_InvalidDefaultLocale InvalidDefaultLocale\n#endif\nTEST_F(ExtensionUnpackerTest, MAYBE_InvalidDefaultLocale) {\n SetupUnpacker(\"invalid_default_locale.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kInvalidDefaultLocale),\n unpacker_->error_message());\n}\n\nTEST_F(ExtensionUnpackerTest, InvalidMessagesFile) {\n SetupUnpacker(\"invalid_messages_file.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_TRUE(MatchPattern(unpacker_->error_message(),\n ASCIIToUTF16(\"*_locales?en_US?messages.json: Line: 2, column: 3,\"\n \" Dictionary keys must be quoted.\")));\n}\n\nTEST_F(ExtensionUnpackerTest, MissingDefaultData) {\n SetupUnpacker(\"missing_default_data.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultMessages),\n unpacker_->error_message());\n}\n\nTEST_F(ExtensionUnpackerTest, MissingDefaultLocaleHasLocalesFolder) {\n SetupUnpacker(\"missing_default_has_locales.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultLocaleSpecified),\n unpacker_->error_message());\n}\n\nTEST_F(ExtensionUnpackerTest, MissingMessagesFile) {\n SetupUnpacker(\"missing_messages_file.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_TRUE(MatchPattern(unpacker_->error_message(),\n ASCIIToUTF16(errors::kLocalesMessagesFileMissing) +\n ASCIIToUTF16(\"*_locales?en_US?messages.json\")));\n}\n\nTEST_F(ExtensionUnpackerTest, NoLocaleData) {\n SetupUnpacker(\"no_locale_data.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultMessages),\n unpacker_->error_message());\n}\n\nTEST_F(ExtensionUnpackerTest, GoodL10n) {\n SetupUnpacker(\"good_l10n.crx\");\n EXPECT_TRUE(unpacker_->Run());\n EXPECT_TRUE(unpacker_->error_message().empty());\n ASSERT_EQ(2U, unpacker_->parsed_catalogs()->size());\n}\n\nTEST_F(ExtensionUnpackerTest, NoL10n) {\n SetupUnpacker(\"no_l10n.crx\");\n EXPECT_TRUE(unpacker_->Run());\n EXPECT_TRUE(unpacker_->error_message().empty());\n EXPECT_EQ(0U, unpacker_->parsed_catalogs()->size());\n}\nExtensionUnpackerTest.InvalidMessagesFile is flaky on Windows\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_temp_dir.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/extensions\/extension_constants.h\"\n#include \"chrome\/common\/extensions\/extension_unpacker.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n\nnamespace errors = extension_manifest_errors;\nnamespace keys = extension_manifest_keys;\n\nclass ExtensionUnpackerTest : public testing::Test {\npublic:\n void SetupUnpacker(const std::string& crx_name) {\n FilePath original_path;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &original_path));\n original_path = original_path.AppendASCII(\"extensions\")\n .AppendASCII(\"unpacker\")\n .AppendASCII(crx_name);\n ASSERT_TRUE(file_util::PathExists(original_path)) << original_path.value();\n\n \/\/ Try bots won't let us write into DIR_TEST_DATA, so we have to create\n \/\/ a temp folder to play in.\n ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());\n\n FilePath crx_path = temp_dir_.path().AppendASCII(crx_name);\n ASSERT_TRUE(file_util::CopyFile(original_path, crx_path)) <<\n \"Original path \" << original_path.value() <<\n \", Crx path \" << crx_path.value();\n\n unpacker_.reset(\n new ExtensionUnpacker(\n crx_path, Extension::INTERNAL, Extension::NO_FLAGS));\n }\n\n protected:\n ScopedTempDir temp_dir_;\n scoped_ptr unpacker_;\n};\n\n\/\/ Crashes intermittently on Windows, see http:\/\/crbug.com\/109238\n#if defined(OS_WIN)\n#define MAYBE_EmptyDefaultLocale DISABLED_EmptyDefaultLocale\n#else\n#define MAYBE_EmptyDefaultLocale EmptyDefaultLocale\n#endif\nTEST_F(ExtensionUnpackerTest, MAYBE_EmptyDefaultLocale) {\n SetupUnpacker(\"empty_default_locale.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kInvalidDefaultLocale),\n unpacker_->error_message());\n}\n\n\/\/ Crashes intermittently on Vista, see http:\/\/crbug.com\/109385\n#if defined(OS_WIN)\n#define MAYBE_HasDefaultLocaleMissingLocalesFolder \\\n DISABLED_HasDefaultLocaleMissingLocalesFolder\n#else\n#define MAYBE_HasDefaultLocaleMissingLocalesFolder \\\n HasDefaultLocaleMissingLocalesFolder\n#endif\nTEST_F(ExtensionUnpackerTest, MAYBE_HasDefaultLocaleMissingLocalesFolder) {\n SetupUnpacker(\"has_default_missing_locales.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kLocalesTreeMissing),\n unpacker_->error_message());\n}\n\n\/\/ Crashes intermittently on Windows, see http:\/\/crbug.com\/109238\n#if defined(OS_WIN)\n#define MAYBE_InvalidDefaultLocale DISABLED_InvalidDefaultLocale\n#else\n#define MAYBE_InvalidDefaultLocale InvalidDefaultLocale\n#endif\nTEST_F(ExtensionUnpackerTest, MAYBE_InvalidDefaultLocale) {\n SetupUnpacker(\"invalid_default_locale.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kInvalidDefaultLocale),\n unpacker_->error_message());\n}\n\n\/\/ Crashes intermittently on Windows, see http:\/\/crbug.com\/109738\n#if defined(OS_WIN)\n#define MAYBE_InvalidMessagesFile DISABLE_InvalidMessagesFile\n#else\n#define MAYBE_InvalidMessagesFile InvalidMessagesFile\n#endif\nTEST_F(ExtensionUnpackerTest, MAYBE_InvalidMessagesFile) {\n SetupUnpacker(\"invalid_messages_file.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_TRUE(MatchPattern(unpacker_->error_message(),\n ASCIIToUTF16(\"*_locales?en_US?messages.json: Line: 2, column: 3,\"\n \" Dictionary keys must be quoted.\")));\n}\n\nTEST_F(ExtensionUnpackerTest, MissingDefaultData) {\n SetupUnpacker(\"missing_default_data.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultMessages),\n unpacker_->error_message());\n}\n\nTEST_F(ExtensionUnpackerTest, MissingDefaultLocaleHasLocalesFolder) {\n SetupUnpacker(\"missing_default_has_locales.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultLocaleSpecified),\n unpacker_->error_message());\n}\n\nTEST_F(ExtensionUnpackerTest, MissingMessagesFile) {\n SetupUnpacker(\"missing_messages_file.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_TRUE(MatchPattern(unpacker_->error_message(),\n ASCIIToUTF16(errors::kLocalesMessagesFileMissing) +\n ASCIIToUTF16(\"*_locales?en_US?messages.json\")));\n}\n\nTEST_F(ExtensionUnpackerTest, NoLocaleData) {\n SetupUnpacker(\"no_locale_data.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultMessages),\n unpacker_->error_message());\n}\n\nTEST_F(ExtensionUnpackerTest, GoodL10n) {\n SetupUnpacker(\"good_l10n.crx\");\n EXPECT_TRUE(unpacker_->Run());\n EXPECT_TRUE(unpacker_->error_message().empty());\n ASSERT_EQ(2U, unpacker_->parsed_catalogs()->size());\n}\n\nTEST_F(ExtensionUnpackerTest, NoL10n) {\n SetupUnpacker(\"no_l10n.crx\");\n EXPECT_TRUE(unpacker_->Run());\n EXPECT_TRUE(unpacker_->error_message().empty());\n EXPECT_EQ(0U, unpacker_->parsed_catalogs()->size());\n}\n<|endoftext|>"} {"text":"\/*\n * NotebookPlots.cpp\n *\n * Copyright (C) 2009-16 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \"SessionRmdNotebook.hpp\"\n#include \"NotebookPlots.hpp\"\n#include \"NotebookOutput.hpp\"\n#include \"..\/SessionPlots.hpp\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n#define kPlotPrefix \"_rs_chunk_plot_\"\n#define kGoldenRatio 1.618\n\nusing namespace rstudio::core;\n\nnamespace rstudio {\nnamespace session {\nnamespace modules {\nnamespace rmarkdown {\nnamespace notebook {\nnamespace {\n\nbool isPlotPath(const FilePath& path)\n{\n return path.hasExtensionLowerCase(\".png\") &&\n string_utils::isPrefixOf(path.stem(), kPlotPrefix);\n}\n\n} \/\/ anonymous namespace\n\nPlotCapture::PlotCapture() :\n hasPlots_(false),\n plotPending_(false),\n lastOrdinal_(0)\n{\n}\n\nPlotCapture::~PlotCapture()\n{\n}\n\nvoid PlotCapture::processPlots(bool ignoreEmpty)\n{\n \/\/ ensure plot folder exists\n if (!plotFolder_.exists())\n return;\n\n \/\/ collect plots from the folder\n std::vector folderContents;\n Error error = plotFolder_.children(&folderContents);\n if (error)\n LOG_ERROR(error);\n \n BOOST_FOREACH(const FilePath& path, folderContents)\n {\n if (isPlotPath(path))\n {\n \/\/ we might find an empty plot file if it hasn't been flushed to disk\n \/\/ yet--ignore these\n if (ignoreEmpty && path.size() == 0)\n continue;\n\n \/\/ emit the plot and the snapshot file\n events().onPlotOutput(path, snapshotFile_, lastOrdinal_);\n\n \/\/ we've consumed the snapshot file, so clear it\n snapshotFile_ = FilePath();\n lastOrdinal_ = 0;\n\n \/\/ clean up the plot so it isn't emitted twice\n error = path.removeIfExists();\n if (error)\n LOG_ERROR(error);\n }\n }\n}\n\nvoid PlotCapture::saveSnapshot()\n{\n \/\/ no work to do if we don't have a display list to write\n if (lastPlot_.isNil())\n return;\n\n \/\/ if there's a plot on the device, write its display list before it's\n \/\/ cleared for the next page\n FilePath outputFile = plotFolder_.complete(\n core::system::generateUuid(false) + kDisplayListExt);\n\n Error error = r::exec::RFunction(\".rs.saveNotebookGraphics\", \n lastPlot_.get(), outputFile.absolutePath()).call();\n if (error)\n LOG_ERROR(error);\n else\n snapshotFile_ = outputFile;\n}\n\nvoid PlotCapture::onExprComplete()\n{\n r::sexp::Protect protect;\n\n \/\/ no action if no plots were created in this chunk\n if (!hasPlots_)\n return;\n\n \/\/ no action if nothing on device list (implies no graphics output)\n if (!isGraphicsDeviceActive())\n return;\n \n \/\/ if we were expecting a new plot to be produced by the previous\n \/\/ expression, process the plot folder\n if (plotPending_)\n {\n plotPending_ = false;\n processPlots(true);\n }\n\n \/\/ check the current state of the graphics device against the last known\n \/\/ state\n SEXP plot = R_NilValue;\n Error error = r::exec::RFunction(\"recordPlot\").call(&plot, &protect);\n if (error)\n {\n LOG_ERROR(error);\n return;\n }\n\n \/\/ detect changes and save last state\n bool unchanged = false;\n if (!lastPlot_.isNil())\n r::exec::RFunction(\"identical\", plot, lastPlot_.get()).call(&unchanged);\n lastPlot_.set(plot);\n\n \/\/ if the state changed, reserve an ordinal at this position\n if (!unchanged)\n {\n OutputPair pair = lastChunkOutput(docId_, chunkId_, nbCtxId_);\n lastOrdinal_ = ++pair.ordinal;\n pair.outputType = ChunkOutputPlot;\n updateLastChunkOutput(docId_, chunkId_, pair);\n\n \/\/ notify the client so it can create a placeholder\n json::Object unit;\n unit[kChunkOutputType] = static_cast(ChunkOutputOrdinal);\n unit[kChunkOutputValue] = static_cast(lastOrdinal_);\n unit[kChunkOutputOrdinal] = static_cast(lastOrdinal_);\n json::Object placeholder;\n placeholder[kChunkId] = chunkId_;\n placeholder[kChunkDocId] = docId_;\n placeholder[kChunkOutputPath] = unit;\n\n module_context::enqueClientEvent(ClientEvent(\n client_events::kChunkOutput, placeholder));\n }\n\n}\n\nvoid PlotCapture::removeGraphicsDevice()\n{\n \/\/ take a snapshot of the last plot's display list before we turn off the\n \/\/ device (if we haven't emitted it yet)\n if (hasPlots_ && \n sizeBehavior_ == PlotSizeAutomatic &&\n snapshotFile_.empty())\n saveSnapshot();\n\n \/\/ turn off the graphics device, if it was ever turned on -- this has the\n \/\/ side effect of writing the device's remaining output to files\n if (isGraphicsDeviceActive())\n {\n Error error = r::exec::RFunction(\"dev.off\").call();\n if (error)\n LOG_ERROR(error);\n isGraphicsDeviceActive();\n\n processPlots(false);\n }\n hasPlots_ = false;\n}\n\nvoid PlotCapture::onBeforeNewPlot()\n{\n if (!lastPlot_.isNil())\n {\n \/\/ save the snapshot of the plot to disk\n if (sizeBehavior_ == PlotSizeAutomatic)\n saveSnapshot();\n }\n plotPending_ = true;\n hasPlots_ = true;\n}\n\nvoid PlotCapture::onNewPlot()\n{\n hasPlots_ = true;\n processPlots(true);\n}\n\n\/\/ begins capturing plot output\ncore::Error PlotCapture::connectPlots(const std::string& docId, \n const std::string& chunkId, const std::string& nbCtxId, \n double height, double width, PlotSizeBehavior sizeBehavior,\n const FilePath& plotFolder)\n{\n \/\/ save identifiers\n docId_ = docId;\n chunkId_ = chunkId;\n nbCtxId_ = nbCtxId;\n\n \/\/ clean up any stale plots from the folder\n plotFolder_ = plotFolder;\n std::vector folderContents;\n Error error = plotFolder.children(&folderContents);\n if (error)\n return error;\n\n BOOST_FOREACH(const core::FilePath& file, folderContents)\n {\n \/\/ remove if it looks like a plot \n if (isPlotPath(file)) \n {\n error = file.remove();\n if (error)\n {\n \/\/ this is non-fatal \n LOG_ERROR(error);\n }\n }\n }\n\n \/\/ infer height\/width if only one is given\n if (height == 0 && width > 0)\n height = width \/ kGoldenRatio;\n else if (height > 0 && width == 0)\n width = height * kGoldenRatio;\n width_ = width;\n height_ = height;\n sizeBehavior_ = sizeBehavior;\n\n \/\/ save old device option\n deviceOption_.set(r::options::getOption(\"device\"));\n\n \/\/ set option for notebook graphics device (must succeed)\n error = setGraphicsOption();\n if (error)\n return error;\n\n onBeforeNewPlot_ = plots::events().onBeforeNewPlot.connect(\n boost::bind(&PlotCapture::onBeforeNewPlot, this));\n \n onBeforeNewGridPage_ = plots::events().onBeforeNewGridPage.connect(\n boost::bind(&PlotCapture::onBeforeNewPlot, this));\n\n onNewPlot_ = plots::events().onNewPlot.connect(\n boost::bind(&PlotCapture::onNewPlot, this));\n\n NotebookCapture::connect();\n return Success();\n}\n\nvoid PlotCapture::disconnect()\n{\n if (connected())\n {\n \/\/ remove the graphics device if we created it\n removeGraphicsDevice();\n\n \/\/ restore the graphics device option\n r::options::setOption(\"device\", deviceOption_.get());\n\n onNewPlot_.disconnect();\n onBeforeNewPlot_.disconnect();\n onBeforeNewGridPage_.disconnect();\n }\n NotebookCapture::disconnect();\n}\n\ncore::Error PlotCapture::setGraphicsOption()\n{\n Error error;\n\n \/\/ create the notebook graphics device\n r::exec::RFunction setOption(\".rs.setNotebookGraphicsOption\");\n\n \/\/ the folder in which to place the rendered plots (this is a sibling of the\n \/\/ main chunk output folder)\n setOption.addParam(\n plotFolder_.absolutePath() + \"\/\" kPlotPrefix \"%03d.png\");\n\n \/\/ device dimensions\n setOption.addParam(height_);\n setOption.addParam(width_); \n\n \/\/ sizing behavior drives units -- user specified units are in inches but\n \/\/ we use pixels when scaling automatically\n setOption.addParam(sizeBehavior_ == PlotSizeManual ? \"in\" : \"px\");\n\n \/\/ device parameters\n setOption.addParam(r::session::graphics::device::devicePixelRatio());\n\n \/\/ other args (OS dependent)\n setOption.addParam(r::session::graphics::extraBitmapParams());\n\n return setOption.call();\n}\n\nbool PlotCapture::isGraphicsDeviceActive()\n{\n r::sexp::Protect protect;\n SEXP devlist = R_NilValue;\n Error error = r::exec::RFunction(\"dev.list\").call(&devlist, &protect);\n if (error)\n LOG_ERROR(error);\n if (r::sexp::isNull(devlist))\n return false;\n return true;\n}\n\ncore::Error initPlots()\n{\n ExecBlock initBlock;\n initBlock.addFunctions()\n (boost::bind(module_context::sourceModuleRFile, \"NotebookPlots.R\"));\n\n return initBlock.execute();\n}\n\n} \/\/ namespace notebook\n} \/\/ namespace rmarkdown\n} \/\/ namespace modules\n} \/\/ namespace session\n} \/\/ namespace rstudio\n\nnotebook: skip plot processing for empty graphics device\/*\n * NotebookPlots.cpp\n *\n * Copyright (C) 2009-16 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \"SessionRmdNotebook.hpp\"\n#include \"NotebookPlots.hpp\"\n#include \"NotebookOutput.hpp\"\n#include \"..\/SessionPlots.hpp\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n#define kPlotPrefix \"_rs_chunk_plot_\"\n#define kGoldenRatio 1.618\n\nusing namespace rstudio::core;\n\nnamespace rstudio {\nnamespace session {\nnamespace modules {\nnamespace rmarkdown {\nnamespace notebook {\nnamespace {\n\nbool isPlotPath(const FilePath& path)\n{\n return path.hasExtensionLowerCase(\".png\") &&\n string_utils::isPrefixOf(path.stem(), kPlotPrefix);\n}\n\n} \/\/ anonymous namespace\n\nPlotCapture::PlotCapture() :\n hasPlots_(false),\n plotPending_(false),\n lastOrdinal_(0)\n{\n}\n\nPlotCapture::~PlotCapture()\n{\n}\n\nvoid PlotCapture::processPlots(bool ignoreEmpty)\n{\n \/\/ ensure plot folder exists\n if (!plotFolder_.exists())\n return;\n\n \/\/ collect plots from the folder\n std::vector folderContents;\n Error error = plotFolder_.children(&folderContents);\n if (error)\n LOG_ERROR(error);\n \n BOOST_FOREACH(const FilePath& path, folderContents)\n {\n if (isPlotPath(path))\n {\n \/\/ we might find an empty plot file if it hasn't been flushed to disk\n \/\/ yet--ignore these\n if (ignoreEmpty && path.size() == 0)\n continue;\n\n \/\/ emit the plot and the snapshot file\n events().onPlotOutput(path, snapshotFile_, lastOrdinal_);\n\n \/\/ we've consumed the snapshot file, so clear it\n snapshotFile_ = FilePath();\n lastOrdinal_ = 0;\n\n \/\/ clean up the plot so it isn't emitted twice\n error = path.removeIfExists();\n if (error)\n LOG_ERROR(error);\n }\n }\n}\n\nvoid PlotCapture::saveSnapshot()\n{\n \/\/ no work to do if we don't have a display list to write\n if (lastPlot_.isNil())\n return;\n\n \/\/ if there's a plot on the device, write its display list before it's\n \/\/ cleared for the next page\n FilePath outputFile = plotFolder_.complete(\n core::system::generateUuid(false) + kDisplayListExt);\n\n Error error = r::exec::RFunction(\".rs.saveNotebookGraphics\", \n lastPlot_.get(), outputFile.absolutePath()).call();\n if (error)\n LOG_ERROR(error);\n else\n snapshotFile_ = outputFile;\n}\n\nvoid PlotCapture::onExprComplete()\n{\n r::sexp::Protect protect;\n\n \/\/ no action if no plots were created in this chunk\n if (!hasPlots_)\n return;\n\n \/\/ no action if nothing on device list (implies no graphics output)\n if (!isGraphicsDeviceActive())\n return;\n \n \/\/ if we were expecting a new plot to be produced by the previous\n \/\/ expression, process the plot folder\n if (plotPending_)\n {\n plotPending_ = false;\n processPlots(true);\n }\n\n \/\/ check the current state of the graphics device against the last known\n \/\/ state\n SEXP plot = R_NilValue;\n Error error = r::exec::RFunction(\"recordPlot\").call(&plot, &protect);\n if (error)\n {\n LOG_ERROR(error);\n return;\n }\n\n \/\/ detect changes and save last state\n bool unchanged = false;\n if (!lastPlot_.isNil())\n r::exec::RFunction(\"identical\", plot, lastPlot_.get()).call(&unchanged);\n lastPlot_.set(plot);\n\n \/\/ if the state changed, reserve an ordinal at this position\n if (!unchanged)\n {\n OutputPair pair = lastChunkOutput(docId_, chunkId_, nbCtxId_);\n lastOrdinal_ = ++pair.ordinal;\n pair.outputType = ChunkOutputPlot;\n updateLastChunkOutput(docId_, chunkId_, pair);\n\n \/\/ notify the client so it can create a placeholder\n json::Object unit;\n unit[kChunkOutputType] = static_cast(ChunkOutputOrdinal);\n unit[kChunkOutputValue] = static_cast(lastOrdinal_);\n unit[kChunkOutputOrdinal] = static_cast(lastOrdinal_);\n json::Object placeholder;\n placeholder[kChunkId] = chunkId_;\n placeholder[kChunkDocId] = docId_;\n placeholder[kChunkOutputPath] = unit;\n\n module_context::enqueClientEvent(ClientEvent(\n client_events::kChunkOutput, placeholder));\n }\n\n}\n\nvoid PlotCapture::removeGraphicsDevice()\n{\n \/\/ take a snapshot of the last plot's display list before we turn off the\n \/\/ device (if we haven't emitted it yet)\n if (hasPlots_ && \n sizeBehavior_ == PlotSizeAutomatic &&\n snapshotFile_.empty())\n saveSnapshot();\n\n \/\/ turn off the graphics device, if it was ever turned on -- this has the\n \/\/ side effect of writing the device's remaining output to files\n if (isGraphicsDeviceActive())\n {\n Error error = r::exec::RFunction(\"dev.off\").call();\n if (error)\n LOG_ERROR(error);\n\n \/\/ some operations may trigger the graphics device without actually\n \/\/ writing a plot; ignore these\n if (hasPlots_)\n processPlots(false);\n }\n hasPlots_ = false;\n}\n\nvoid PlotCapture::onBeforeNewPlot()\n{\n if (!lastPlot_.isNil())\n {\n \/\/ save the snapshot of the plot to disk\n if (sizeBehavior_ == PlotSizeAutomatic)\n saveSnapshot();\n }\n plotPending_ = true;\n hasPlots_ = true;\n}\n\nvoid PlotCapture::onNewPlot()\n{\n hasPlots_ = true;\n processPlots(true);\n}\n\n\/\/ begins capturing plot output\ncore::Error PlotCapture::connectPlots(const std::string& docId, \n const std::string& chunkId, const std::string& nbCtxId, \n double height, double width, PlotSizeBehavior sizeBehavior,\n const FilePath& plotFolder)\n{\n \/\/ save identifiers\n docId_ = docId;\n chunkId_ = chunkId;\n nbCtxId_ = nbCtxId;\n\n \/\/ clean up any stale plots from the folder\n plotFolder_ = plotFolder;\n std::vector folderContents;\n Error error = plotFolder.children(&folderContents);\n if (error)\n return error;\n\n BOOST_FOREACH(const core::FilePath& file, folderContents)\n {\n \/\/ remove if it looks like a plot \n if (isPlotPath(file)) \n {\n error = file.remove();\n if (error)\n {\n \/\/ this is non-fatal \n LOG_ERROR(error);\n }\n }\n }\n\n \/\/ infer height\/width if only one is given\n if (height == 0 && width > 0)\n height = width \/ kGoldenRatio;\n else if (height > 0 && width == 0)\n width = height * kGoldenRatio;\n width_ = width;\n height_ = height;\n sizeBehavior_ = sizeBehavior;\n\n \/\/ save old device option\n deviceOption_.set(r::options::getOption(\"device\"));\n\n \/\/ set option for notebook graphics device (must succeed)\n error = setGraphicsOption();\n if (error)\n return error;\n\n onBeforeNewPlot_ = plots::events().onBeforeNewPlot.connect(\n boost::bind(&PlotCapture::onBeforeNewPlot, this));\n \n onBeforeNewGridPage_ = plots::events().onBeforeNewGridPage.connect(\n boost::bind(&PlotCapture::onBeforeNewPlot, this));\n\n onNewPlot_ = plots::events().onNewPlot.connect(\n boost::bind(&PlotCapture::onNewPlot, this));\n\n NotebookCapture::connect();\n return Success();\n}\n\nvoid PlotCapture::disconnect()\n{\n if (connected())\n {\n \/\/ remove the graphics device if we created it\n removeGraphicsDevice();\n\n \/\/ restore the graphics device option\n r::options::setOption(\"device\", deviceOption_.get());\n\n onNewPlot_.disconnect();\n onBeforeNewPlot_.disconnect();\n onBeforeNewGridPage_.disconnect();\n }\n NotebookCapture::disconnect();\n}\n\ncore::Error PlotCapture::setGraphicsOption()\n{\n Error error;\n\n \/\/ create the notebook graphics device\n r::exec::RFunction setOption(\".rs.setNotebookGraphicsOption\");\n\n \/\/ the folder in which to place the rendered plots (this is a sibling of the\n \/\/ main chunk output folder)\n setOption.addParam(\n plotFolder_.absolutePath() + \"\/\" kPlotPrefix \"%03d.png\");\n\n \/\/ device dimensions\n setOption.addParam(height_);\n setOption.addParam(width_); \n\n \/\/ sizing behavior drives units -- user specified units are in inches but\n \/\/ we use pixels when scaling automatically\n setOption.addParam(sizeBehavior_ == PlotSizeManual ? \"in\" : \"px\");\n\n \/\/ device parameters\n setOption.addParam(r::session::graphics::device::devicePixelRatio());\n\n \/\/ other args (OS dependent)\n setOption.addParam(r::session::graphics::extraBitmapParams());\n\n return setOption.call();\n}\n\nbool PlotCapture::isGraphicsDeviceActive()\n{\n r::sexp::Protect protect;\n SEXP devlist = R_NilValue;\n Error error = r::exec::RFunction(\"dev.list\").call(&devlist, &protect);\n if (error)\n LOG_ERROR(error);\n if (r::sexp::isNull(devlist))\n return false;\n return true;\n}\n\ncore::Error initPlots()\n{\n ExecBlock initBlock;\n initBlock.addFunctions()\n (boost::bind(module_context::sourceModuleRFile, \"NotebookPlots.R\"));\n\n return initBlock.execute();\n}\n\n} \/\/ namespace notebook\n} \/\/ namespace rmarkdown\n} \/\/ namespace modules\n} \/\/ namespace session\n} \/\/ namespace rstudio\n\n<|endoftext|>"} {"text":"\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2011 Heiko Strathmann\n * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace shogun;\n\nvoid print_message(FILE* target, const char* str)\n{\n\tfprintf(target, \"%s\", str);\n}\n\nCModelSelectionParameters* create_param_tree()\n{\n\tCModelSelectionParameters* root=new CModelSelectionParameters();\n\n\tCModelSelectionParameters* c1=new CModelSelectionParameters(\"C1\");\n\troot->append_child(c1);\n\tc1->build_values(-15, 15, R_EXP);\n\n\tCModelSelectionParameters* c2=new CModelSelectionParameters(\"C2\");\n\troot->append_child(c2);\n\tc2->build_values(-15, 15, R_EXP);\n\n\treturn root;\n}\n\nint main(int argc, char **argv)\n{\n\tinit_shogun(&print_message, &print_message, &print_message);\n\n\tint32_t num_subsets=5;\n\tint32_t num_features=11;\n\n\t\/* create some data *\/\n\tfloat64_t* matrix=new float64_t[num_features*2];\n\tfor (int32_t i=0; i* features=new CSimpleFeatures ();\n\tfeatures->set_feature_matrix(matrix, 2, num_features);\n\n\t\/* create three labels *\/\n\tCLabels* labels=new CLabels(num_features);\n\tfor (index_t i=0; iset_label(i, i%2==0 ? 1 : -1);\n\n\t\/* create linear classifier (use -s 2 option to avoid warnings) *\/\n\tCLibLinear* classifier=new CLibLinear(L2R_L2LOSS_SVC);\n\n\t\/* splitting strategy *\/\n\tCStratifiedCrossValidationSplitting* splitting_strategy=\n\t\t\tnew CStratifiedCrossValidationSplitting(labels, num_subsets);\n\n\t\/* accuracy evaluation *\/\n\tCContingencyTableEvaluation* evaluation_criterium=\n\t\t\tnew CContingencyTableEvaluation(ACCURACY);\n\n\t\/* cross validation class for evaluation in model selection *\/\n\tCCrossValidation* cross=new CCrossValidation(classifier, features, labels,\n\t\t\tsplitting_strategy, evaluation_criterium);\n\n\t\/* model parameter selection, deletion is handled by modsel class (SG_UNREF) *\/\n\tCModelSelectionParameters* param_tree=create_param_tree();\n\n\t\/* this is on the stack and handles all of the above structures in memory *\/\n\tCGridSearchModelSelection grid_search(param_tree, cross);\n\n\tfloat64_t result;\n\tCParameterCombination* best_combination=grid_search.select_model(result);\n\tSG_SPRINT(\"best parameter(s):\\n\");\n\tbest_combination->print_tree();\n\tSG_SPRINT(\"result: %f\\n\", result);\n\n\t\/* clean up destroy result parameter *\/\n\tSG_UNREF(best_combination);\n\n\tSG_SPRINT(\"\\nEND\\n\");\n\texit_shogun();\n\n\treturn 0;\n}\n\napplied interface changes\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2011 Heiko Strathmann\n * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace shogun;\n\nvoid print_message(FILE* target, const char* str)\n{\n\tfprintf(target, \"%s\", str);\n}\n\nCModelSelectionParameters* create_param_tree()\n{\n\tCModelSelectionParameters* root=new CModelSelectionParameters();\n\n\tCModelSelectionParameters* c1=new CModelSelectionParameters(\"C1\");\n\troot->append_child(c1);\n\tc1->build_values(-15, 15, R_EXP);\n\n\tCModelSelectionParameters* c2=new CModelSelectionParameters(\"C2\");\n\troot->append_child(c2);\n\tc2->build_values(-15, 15, R_EXP);\n\n\treturn root;\n}\n\nint main(int argc, char **argv)\n{\n\tinit_shogun(&print_message, &print_message, &print_message);\n\n\tint32_t num_subsets=5;\n\tint32_t num_features=11;\n\n\t\/* create some data *\/\n\tfloat64_t* matrix=new float64_t[num_features*2];\n\tfor (int32_t i=0; i* features=new CSimpleFeatures ();\n\tfeatures->set_feature_matrix(matrix, 2, num_features);\n\n\t\/* create three labels *\/\n\tCLabels* labels=new CLabels(num_features);\n\tfor (index_t i=0; iset_label(i, i%2==0 ? 1 : -1);\n\n\t\/* create linear classifier (use -s 2 option to avoid warnings) *\/\n\tCLibLinear* classifier=new CLibLinear(L2R_L2LOSS_SVC);\n\n\t\/* splitting strategy *\/\n\tCStratifiedCrossValidationSplitting* splitting_strategy=\n\t\t\tnew CStratifiedCrossValidationSplitting(labels, num_subsets);\n\n\t\/* accuracy evaluation *\/\n\tCContingencyTableEvaluation* evaluation_criterium=\n\t\t\tnew CContingencyTableEvaluation(ACCURACY);\n\n\t\/* cross validation class for evaluation in model selection *\/\n\tCCrossValidation* cross=new CCrossValidation(classifier, features, labels,\n\t\t\tsplitting_strategy, evaluation_criterium);\n\n\t\/* model parameter selection, deletion is handled by modsel class (SG_UNREF) *\/\n\tCModelSelectionParameters* param_tree=create_param_tree();\n\n\t\/* this is on the stack and handles all of the above structures in memory *\/\n\tCGridSearchModelSelection grid_search(param_tree, cross);\n\n\tCParameterCombination* best_combination=grid_search.select_model();\n\tSG_SPRINT(\"best parameter(s):\\n\");\n\tbest_combination->print_tree();\n\n\tbest_combination->apply_to_machine(classifier);\n\tSG_SPRINT(\"result: %f\\n\", cross->evaluate());\n\n\t\/* clean up destroy result parameter *\/\n\tSG_UNREF(best_combination);\n\n\tSG_SPRINT(\"\\nEND\\n\");\n\texit_shogun();\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/ \n\/\/ GRINS - General Reacting Incompressible Navier-Stokes \n\/\/\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\/\/ This class\n#include \"grins\/error_estimation_factory.h\"\n\n\/\/ libMesh\n#include \"libmesh\/adjoint_residual_error_estimator.h\"\n#include \"libmesh\/getpot.h\"\n#include \"libmesh\/patch_recovery_error_estimator.h\"\n#include \"libmesh\/qoi_set.h\"\n\nnamespace GRINS\n{\n\n ErrorEstimatorFactory::ErrorEstimatorFactory()\n {\n return;\n }\n\n ErrorEstimatorFactory::~ErrorEstimatorFactory()\n {\n return;\n }\n\n std::tr1::shared_ptr ErrorEstimatorFactory::build( const GetPot& input,\n std::tr1::shared_ptr qoi_base )\n {\n \/\/ check if qoi_base is an empty pointer (user set no QoI), in that case return empty pointer.\n if( qoi_base == std::tr1::shared_ptr() )\n {\n return std::tr1::shared_ptr();\n }\n\n std::string estimator_type = input(\"MeshAdaptivity\/estimator_type\", \"none\");\n\n ErrorEstimatorEnum estimator_enum = this->string_to_enum( estimator_type );\n\n std::tr1::shared_ptr error_estimator;\n \n switch( estimator_enum )\n {\n case(ADJOINT_RESIDUAL):\n {\n error_estimator.reset( new libMesh::AdjointResidualErrorEstimator );\n \n libMesh::AdjointResidualErrorEstimator* adjoint_error_estimator = libmesh_cast_ptr( error_estimator.get() );\n \n libMesh::PatchRecoveryErrorEstimator *p1 = new libMesh::PatchRecoveryErrorEstimator;\n adjoint_error_estimator->primal_error_estimator().reset( p1 );\n \n libMesh::PatchRecoveryErrorEstimator *p2 = new libMesh::PatchRecoveryErrorEstimator;\n adjoint_error_estimator->dual_error_estimator().reset( p2 ); \n \n bool patch_reuse = input( \"MeshAdaptivity\/patch_reuse\", true );\n adjoint_error_estimator->primal_error_estimator()->error_norm.set_type( 0, H1_SEMINORM );\n p1->set_patch_reuse( patch_reuse );\n \n adjoint_error_estimator->dual_error_estimator()->error_norm.set_type( 0, H1_SEMINORM );\n p2->set_patch_reuse( patch_reuse );\n }\n break;\n\n case(ADJOINT_REFINEMENT):\n case(KELLY):\n case(PATCH_RECOVERY):\n case(WEIGHTED_PATCH_RECOVERY):\n case(UNIFORM_REFINEMENT):\n {\n libmesh_not_implemented();\n }\n break;\n\n default:\n {\n std::cerr << \"Error: Invalid error estimator type \" << estimator_type << std::endl;\n libmesh_error();\n }\n\n } \/\/ switch( estimator_enum )\n \n return error_estimator;\n }\n\n ErrorEstimatorFactory::ErrorEstimatorEnum ErrorEstimatorFactory::string_to_enum( const std::string& estimator_type ) const\n {\n ErrorEstimatorEnum value;\n\n if( estimator_type == std::string(\"adjoint_residual\") )\n {\n value = ADJOINT_RESIDUAL;\n }\n else if( estimator_type == std::string(\"adjoint_refinement\") )\n {\n value = ADJOINT_REFINEMENT;\n }\n else if( estimator_type == std::string(\"kelly\") )\n {\n value = KELLY;\n }\n else if( estimator_type == std::string(\"patch_recovery\") )\n {\n value = PATCH_RECOVERY;\n }\n else if( estimator_type == std::string(\"weighted_patch_recovery\") )\n {\n value = WEIGHTED_PATCH_RECOVERY;\n }\n else if( estimator_type == std::string(\"uniform_refinement\") )\n {\n value = UNIFORM_REFINEMENT;\n }\n else\n {\n std::cerr << \"Error: Invalid error estimator type \" << estimator_type << std::endl\n << \"Valid error estimator types are: adjoint_residual\" << std::endl\n << \" adjoint_refinement\" << std::endl\n << \" kelly\" << std::endl\n << \" patch_recovery\" << std::endl\n << \" weighted_patch_recovery\" << std::endl\n << \" uniform_refinement\" << std::endl;\n libmesh_error();\n }\n\n return value;\n }\n\n} \/\/ namespace GRINS\nMeh, no need for error message there because that should never happen.\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/ \n\/\/ GRINS - General Reacting Incompressible Navier-Stokes \n\/\/\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\/\/ This class\n#include \"grins\/error_estimation_factory.h\"\n\n\/\/ libMesh\n#include \"libmesh\/adjoint_residual_error_estimator.h\"\n#include \"libmesh\/getpot.h\"\n#include \"libmesh\/patch_recovery_error_estimator.h\"\n#include \"libmesh\/qoi_set.h\"\n\nnamespace GRINS\n{\n\n ErrorEstimatorFactory::ErrorEstimatorFactory()\n {\n return;\n }\n\n ErrorEstimatorFactory::~ErrorEstimatorFactory()\n {\n return;\n }\n\n std::tr1::shared_ptr ErrorEstimatorFactory::build( const GetPot& input,\n std::tr1::shared_ptr qoi_base )\n {\n \/\/ check if qoi_base is an empty pointer (user set no QoI), in that case return empty pointer.\n if( qoi_base == std::tr1::shared_ptr() )\n {\n return std::tr1::shared_ptr();\n }\n\n std::string estimator_type = input(\"MeshAdaptivity\/estimator_type\", \"none\");\n\n ErrorEstimatorEnum estimator_enum = this->string_to_enum( estimator_type );\n\n std::tr1::shared_ptr error_estimator;\n \n switch( estimator_enum )\n {\n case(ADJOINT_RESIDUAL):\n {\n error_estimator.reset( new libMesh::AdjointResidualErrorEstimator );\n \n libMesh::AdjointResidualErrorEstimator* adjoint_error_estimator = libmesh_cast_ptr( error_estimator.get() );\n \n libMesh::PatchRecoveryErrorEstimator *p1 = new libMesh::PatchRecoveryErrorEstimator;\n adjoint_error_estimator->primal_error_estimator().reset( p1 );\n \n libMesh::PatchRecoveryErrorEstimator *p2 = new libMesh::PatchRecoveryErrorEstimator;\n adjoint_error_estimator->dual_error_estimator().reset( p2 ); \n \n bool patch_reuse = input( \"MeshAdaptivity\/patch_reuse\", true );\n adjoint_error_estimator->primal_error_estimator()->error_norm.set_type( 0, H1_SEMINORM );\n p1->set_patch_reuse( patch_reuse );\n \n adjoint_error_estimator->dual_error_estimator()->error_norm.set_type( 0, H1_SEMINORM );\n p2->set_patch_reuse( patch_reuse );\n }\n break;\n\n case(ADJOINT_REFINEMENT):\n case(KELLY):\n case(PATCH_RECOVERY):\n case(WEIGHTED_PATCH_RECOVERY):\n case(UNIFORM_REFINEMENT):\n {\n libmesh_not_implemented();\n }\n break;\n\n \/\/ wat?!\n default:\n {\n libmesh_error();\n }\n\n } \/\/ switch( estimator_enum )\n \n return error_estimator;\n }\n\n ErrorEstimatorFactory::ErrorEstimatorEnum ErrorEstimatorFactory::string_to_enum( const std::string& estimator_type ) const\n {\n ErrorEstimatorEnum value;\n\n if( estimator_type == std::string(\"adjoint_residual\") )\n {\n value = ADJOINT_RESIDUAL;\n }\n else if( estimator_type == std::string(\"adjoint_refinement\") )\n {\n value = ADJOINT_REFINEMENT;\n }\n else if( estimator_type == std::string(\"kelly\") )\n {\n value = KELLY;\n }\n else if( estimator_type == std::string(\"patch_recovery\") )\n {\n value = PATCH_RECOVERY;\n }\n else if( estimator_type == std::string(\"weighted_patch_recovery\") )\n {\n value = WEIGHTED_PATCH_RECOVERY;\n }\n else if( estimator_type == std::string(\"uniform_refinement\") )\n {\n value = UNIFORM_REFINEMENT;\n }\n else\n {\n std::cerr << \"Error: Invalid error estimator type \" << estimator_type << std::endl\n << \"Valid error estimator types are: adjoint_residual\" << std::endl\n << \" adjoint_refinement\" << std::endl\n << \" kelly\" << std::endl\n << \" patch_recovery\" << std::endl\n << \" weighted_patch_recovery\" << std::endl\n << \" uniform_refinement\" << std::endl;\n libmesh_error();\n }\n\n return value;\n }\n\n} \/\/ namespace GRINS\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright 2012 Francisco Jerez\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n\/\/ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF\n\/\/ OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\n#include \"core\/resource.hpp\"\n#include \"pipe\/p_screen.h\"\n#include \"util\/u_sampler.h\"\n#include \"util\/u_format.h\"\n\nusing namespace clover;\n\nnamespace {\n class box {\n public:\n box(const resource::point &origin, const resource::point &size) :\n pipe({ (int)origin[0], (int)origin[1],\n (int)origin[2], (int)size[0],\n (int)size[1], (int)size[2] }) {\n }\n\n operator const pipe_box *() {\n return &pipe;\n }\n\n protected:\n pipe_box pipe;\n };\n}\n\nresource::resource(clover::device &dev, clover::memory_obj &obj) :\n dev(dev), obj(obj), pipe(NULL), offset{0} {\n}\n\nresource::~resource() {\n}\n\nvoid\nresource::copy(command_queue &q, const point &origin, const point ®ion,\n resource &src_res, const point &src_origin) {\n point p = offset + origin;\n\n q.pipe->resource_copy_region(q.pipe, pipe, 0, p[0], p[1], p[2],\n src_res.pipe, 0,\n box(src_res.offset + src_origin, region));\n}\n\nvoid *\nresource::add_map(command_queue &q, cl_map_flags flags, bool blocking,\n const point &origin, const point ®ion) {\n maps.emplace_back(q, *this, flags, blocking, origin, region);\n return maps.back();\n}\n\nvoid\nresource::del_map(void *p) {\n auto it = std::find(maps.begin(), maps.end(), p);\n if (it != maps.end())\n maps.erase(it);\n}\n\nunsigned\nresource::map_count() const {\n return maps.size();\n}\n\npipe_sampler_view *\nresource::bind_sampler_view(clover::command_queue &q) {\n pipe_sampler_view info;\n\n u_sampler_view_default_template(&info, pipe, pipe->format);\n return q.pipe->create_sampler_view(q.pipe, pipe, &info);\n}\n\nvoid\nresource::unbind_sampler_view(clover::command_queue &q,\n pipe_sampler_view *st) {\n q.pipe->sampler_view_destroy(q.pipe, st);\n}\n\npipe_surface *\nresource::bind_surface(clover::command_queue &q, bool rw) {\n pipe_surface info {};\n\n info.format = pipe->format;\n info.usage = pipe->bind;\n info.writable = rw;\n\n if (pipe->target == PIPE_BUFFER)\n info.u.buf.last_element = pipe->width0 - 1;\n\n return q.pipe->create_surface(q.pipe, pipe, &info);\n}\n\nvoid\nresource::unbind_surface(clover::command_queue &q, pipe_surface *st) {\n q.pipe->surface_destroy(q.pipe, st);\n}\n\nroot_resource::root_resource(clover::device &dev, clover::memory_obj &obj,\n clover::command_queue &q,\n const std::string &data) :\n resource(dev, obj) {\n pipe_resource info {};\n\n if (image *img = dynamic_cast(&obj)) {\n info.format = translate_format(img->format());\n info.width0 = img->width();\n info.height0 = img->height();\n info.depth0 = img->depth();\n } else {\n info.width0 = obj.size();\n info.height0 = 1;\n info.depth0 = 1;\n }\n\n info.target = translate_target(obj.type());\n info.bind = (PIPE_BIND_SAMPLER_VIEW |\n PIPE_BIND_COMPUTE_RESOURCE |\n PIPE_BIND_GLOBAL |\n PIPE_BIND_TRANSFER_READ |\n PIPE_BIND_TRANSFER_WRITE);\n\n pipe = dev.pipe->resource_create(dev.pipe, &info);\n if (!pipe)\n throw error(CL_OUT_OF_RESOURCES);\n\n if (!data.empty()) {\n box rect { { 0, 0, 0 }, { info.width0, info.height0, info.depth0 } };\n unsigned cpp = util_format_get_blocksize(info.format);\n\n q.pipe->transfer_inline_write(q.pipe, pipe, 0, PIPE_TRANSFER_WRITE,\n rect, data.data(), cpp * info.width0,\n cpp * info.width0 * info.height0);\n }\n}\n\nroot_resource::root_resource(clover::device &dev, clover::memory_obj &obj,\n clover::root_resource &r) :\n resource(dev, obj) {\n assert(0); \/\/ XXX -- resource shared among dev and r.dev\n}\n\nroot_resource::~root_resource() {\n dev.pipe->resource_destroy(dev.pipe, pipe);\n}\n\nsub_resource::sub_resource(clover::resource &r, point offset) :\n resource(r.dev, r.obj) {\n pipe = r.pipe;\n offset = r.offset + offset;\n}\n\nmapping::mapping(command_queue &q, resource &r,\n cl_map_flags flags, bool blocking,\n const resource::point &origin,\n const resource::point ®ion) :\n pctx(q.pipe) {\n unsigned usage = ((flags & CL_MAP_WRITE ? PIPE_TRANSFER_WRITE : 0 ) |\n (flags & CL_MAP_READ ? PIPE_TRANSFER_READ : 0 ) |\n (blocking ? PIPE_TRANSFER_UNSYNCHRONIZED : 0));\n\n p = pctx->transfer_map(pctx, r.pipe, 0, usage,\n box(origin + r.offset, region), &pxfer);\n if (!p) {\n pxfer = NULL;\n throw error(CL_OUT_OF_RESOURCES);\n }\n}\n\nmapping::mapping(mapping &&m) :\n pctx(m.pctx), pxfer(m.pxfer), p(m.p) {\n m.p = NULL;\n m.pxfer = NULL;\n}\n\nmapping::~mapping() {\n if (pxfer) {\n pctx->transfer_unmap(pctx, pxfer);\n }\n}\nclover: Fix build since removal of pipe_surface::usage\/\/\n\/\/ Copyright 2012 Francisco Jerez\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n\/\/ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF\n\/\/ OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\n#include \"core\/resource.hpp\"\n#include \"pipe\/p_screen.h\"\n#include \"util\/u_sampler.h\"\n#include \"util\/u_format.h\"\n\nusing namespace clover;\n\nnamespace {\n class box {\n public:\n box(const resource::point &origin, const resource::point &size) :\n pipe({ (int)origin[0], (int)origin[1],\n (int)origin[2], (int)size[0],\n (int)size[1], (int)size[2] }) {\n }\n\n operator const pipe_box *() {\n return &pipe;\n }\n\n protected:\n pipe_box pipe;\n };\n}\n\nresource::resource(clover::device &dev, clover::memory_obj &obj) :\n dev(dev), obj(obj), pipe(NULL), offset{0} {\n}\n\nresource::~resource() {\n}\n\nvoid\nresource::copy(command_queue &q, const point &origin, const point ®ion,\n resource &src_res, const point &src_origin) {\n point p = offset + origin;\n\n q.pipe->resource_copy_region(q.pipe, pipe, 0, p[0], p[1], p[2],\n src_res.pipe, 0,\n box(src_res.offset + src_origin, region));\n}\n\nvoid *\nresource::add_map(command_queue &q, cl_map_flags flags, bool blocking,\n const point &origin, const point ®ion) {\n maps.emplace_back(q, *this, flags, blocking, origin, region);\n return maps.back();\n}\n\nvoid\nresource::del_map(void *p) {\n auto it = std::find(maps.begin(), maps.end(), p);\n if (it != maps.end())\n maps.erase(it);\n}\n\nunsigned\nresource::map_count() const {\n return maps.size();\n}\n\npipe_sampler_view *\nresource::bind_sampler_view(clover::command_queue &q) {\n pipe_sampler_view info;\n\n u_sampler_view_default_template(&info, pipe, pipe->format);\n return q.pipe->create_sampler_view(q.pipe, pipe, &info);\n}\n\nvoid\nresource::unbind_sampler_view(clover::command_queue &q,\n pipe_sampler_view *st) {\n q.pipe->sampler_view_destroy(q.pipe, st);\n}\n\npipe_surface *\nresource::bind_surface(clover::command_queue &q, bool rw) {\n pipe_surface info {};\n\n info.format = pipe->format;\n info.writable = rw;\n\n if (pipe->target == PIPE_BUFFER)\n info.u.buf.last_element = pipe->width0 - 1;\n\n return q.pipe->create_surface(q.pipe, pipe, &info);\n}\n\nvoid\nresource::unbind_surface(clover::command_queue &q, pipe_surface *st) {\n q.pipe->surface_destroy(q.pipe, st);\n}\n\nroot_resource::root_resource(clover::device &dev, clover::memory_obj &obj,\n clover::command_queue &q,\n const std::string &data) :\n resource(dev, obj) {\n pipe_resource info {};\n\n if (image *img = dynamic_cast(&obj)) {\n info.format = translate_format(img->format());\n info.width0 = img->width();\n info.height0 = img->height();\n info.depth0 = img->depth();\n } else {\n info.width0 = obj.size();\n info.height0 = 1;\n info.depth0 = 1;\n }\n\n info.target = translate_target(obj.type());\n info.bind = (PIPE_BIND_SAMPLER_VIEW |\n PIPE_BIND_COMPUTE_RESOURCE |\n PIPE_BIND_GLOBAL |\n PIPE_BIND_TRANSFER_READ |\n PIPE_BIND_TRANSFER_WRITE);\n\n pipe = dev.pipe->resource_create(dev.pipe, &info);\n if (!pipe)\n throw error(CL_OUT_OF_RESOURCES);\n\n if (!data.empty()) {\n box rect { { 0, 0, 0 }, { info.width0, info.height0, info.depth0 } };\n unsigned cpp = util_format_get_blocksize(info.format);\n\n q.pipe->transfer_inline_write(q.pipe, pipe, 0, PIPE_TRANSFER_WRITE,\n rect, data.data(), cpp * info.width0,\n cpp * info.width0 * info.height0);\n }\n}\n\nroot_resource::root_resource(clover::device &dev, clover::memory_obj &obj,\n clover::root_resource &r) :\n resource(dev, obj) {\n assert(0); \/\/ XXX -- resource shared among dev and r.dev\n}\n\nroot_resource::~root_resource() {\n dev.pipe->resource_destroy(dev.pipe, pipe);\n}\n\nsub_resource::sub_resource(clover::resource &r, point offset) :\n resource(r.dev, r.obj) {\n pipe = r.pipe;\n offset = r.offset + offset;\n}\n\nmapping::mapping(command_queue &q, resource &r,\n cl_map_flags flags, bool blocking,\n const resource::point &origin,\n const resource::point ®ion) :\n pctx(q.pipe) {\n unsigned usage = ((flags & CL_MAP_WRITE ? PIPE_TRANSFER_WRITE : 0 ) |\n (flags & CL_MAP_READ ? PIPE_TRANSFER_READ : 0 ) |\n (blocking ? PIPE_TRANSFER_UNSYNCHRONIZED : 0));\n\n p = pctx->transfer_map(pctx, r.pipe, 0, usage,\n box(origin + r.offset, region), &pxfer);\n if (!p) {\n pxfer = NULL;\n throw error(CL_OUT_OF_RESOURCES);\n }\n}\n\nmapping::mapping(mapping &&m) :\n pctx(m.pctx), pxfer(m.pxfer), p(m.p) {\n m.p = NULL;\n m.pxfer = NULL;\n}\n\nmapping::~mapping() {\n if (pxfer) {\n pctx->transfer_unmap(pctx, pxfer);\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2017 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"referencefieldvalue.h\"\n#include \n#include \n#include \n\nusing vespalib::IllegalArgumentException;\nusing vespalib::make_string;\n\nnamespace document {\n\nIMPLEMENT_IDENTIFIABLE(ReferenceFieldValue, FieldValue);\n\nReferenceFieldValue::ReferenceFieldValue()\n : _dataType(nullptr),\n _documentId(),\n _altered(true)\n{\n}\n\nReferenceFieldValue::ReferenceFieldValue(const ReferenceDataType& dataType)\n : _dataType(&dataType),\n _documentId(),\n _altered(true)\n{\n}\n\nReferenceFieldValue::ReferenceFieldValue(\n const ReferenceDataType& dataType,\n const DocumentId& documentId)\n : _dataType(&dataType),\n _documentId(documentId),\n _altered(true)\n{\n requireIdOfMatchingType(_documentId, _dataType->getTargetType());\n}\n\nReferenceFieldValue::~ReferenceFieldValue() {\n}\n\nvoid ReferenceFieldValue::requireIdOfMatchingType(\n const DocumentId& id, const DocumentType& type)\n{\n if (id.getDocType() != type.getName()) {\n throw IllegalArgumentException(\n make_string(\"Can't assign document ID '%s' (of type '%s') to \"\n \"reference of document type '%s'\",\n id.toString().c_str(),\n id.getDocType().c_str(),\n type.getName().c_str()),\n VESPA_STRLOC);\n }\n}\n\nFieldValue& ReferenceFieldValue::assign(const FieldValue& rhs) {\n const auto* refValueRhs(dynamic_cast(&rhs));\n if (refValueRhs != nullptr) {\n if (refValueRhs == this) {\n return *this;\n }\n _documentId = refValueRhs->_documentId;\n _dataType = refValueRhs->_dataType;\n _altered = true;\n } else {\n throw IllegalArgumentException(\n make_string(\"Can't assign field value of type %s to \"\n \"a ReferenceFieldValue\",\n rhs.getDataType()->getName().c_str()),\n VESPA_STRLOC);\n }\n return *this;\n}\n\nvoid ReferenceFieldValue::setDeserializedDocumentId(const DocumentId& id) {\n assert(_dataType != nullptr);\n requireIdOfMatchingType(id, _dataType->getTargetType());\n _documentId = id;\n _altered = false;\n}\n\nReferenceFieldValue* ReferenceFieldValue::clone() const {\n assert(_dataType != nullptr);\n return new ReferenceFieldValue(*_dataType, _documentId);\n}\n\nint ReferenceFieldValue::compare(const FieldValue& rhs) const {\n const int parentCompare = FieldValue::compare(rhs);\n if (parentCompare != 0) {\n return parentCompare;\n }\n \/\/ Type equality is checked by the parent.\n const auto& refValueRhs(dynamic_cast(rhs));\n \/\/ TODO PERF: DocumentId does currently _not_ expose any methods that\n \/\/ cheaply allow an ordering to be established. Only (in)equality operators.\n \/\/ IdString::operator== is already implemented in the same way as this, so\n \/\/ don't put this code in your inner loops, kids!\n return _documentId.toString().compare(refValueRhs._documentId.toString());\n}\n\nvoid ReferenceFieldValue::print(std::ostream& os, bool verbose, const std::string& indent) const {\n (void) verbose;\n (void) indent;\n assert(_dataType != nullptr);\n os << \"ReferenceFieldValue(\" << *_dataType << \", DocumentId(\";\n _documentId.print(os, false, \"\");\n os << \"))\";\n}\n\nbool ReferenceFieldValue::hasChanged() const {\n return _altered;\n}\n\nvoid ReferenceFieldValue::accept(FieldValueVisitor& visitor) {\n visitor.visit(*this);\n}\n\nvoid ReferenceFieldValue::accept(ConstFieldValueVisitor& visitor) const {\n visitor.visit(*this);\n}\n\n} \/\/ document\nSimplify branching\/\/ Copyright 2017 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"referencefieldvalue.h\"\n#include \n#include \n#include \n\nusing vespalib::IllegalArgumentException;\nusing vespalib::make_string;\n\nnamespace document {\n\nIMPLEMENT_IDENTIFIABLE(ReferenceFieldValue, FieldValue);\n\nReferenceFieldValue::ReferenceFieldValue()\n : _dataType(nullptr),\n _documentId(),\n _altered(true)\n{\n}\n\nReferenceFieldValue::ReferenceFieldValue(const ReferenceDataType& dataType)\n : _dataType(&dataType),\n _documentId(),\n _altered(true)\n{\n}\n\nReferenceFieldValue::ReferenceFieldValue(\n const ReferenceDataType& dataType,\n const DocumentId& documentId)\n : _dataType(&dataType),\n _documentId(documentId),\n _altered(true)\n{\n requireIdOfMatchingType(_documentId, _dataType->getTargetType());\n}\n\nReferenceFieldValue::~ReferenceFieldValue() {\n}\n\nvoid ReferenceFieldValue::requireIdOfMatchingType(\n const DocumentId& id, const DocumentType& type)\n{\n if (id.getDocType() != type.getName()) {\n throw IllegalArgumentException(\n make_string(\"Can't assign document ID '%s' (of type '%s') to \"\n \"reference of document type '%s'\",\n id.toString().c_str(),\n id.getDocType().c_str(),\n type.getName().c_str()),\n VESPA_STRLOC);\n }\n}\n\nFieldValue& ReferenceFieldValue::assign(const FieldValue& rhs) {\n const auto* refValueRhs(dynamic_cast(&rhs));\n if (refValueRhs == nullptr) {\n throw IllegalArgumentException(\n make_string(\"Can't assign field value of type %s to \"\n \"a ReferenceFieldValue\",\n rhs.getDataType()->getName().c_str()),\n VESPA_STRLOC);\n }\n if (refValueRhs == this) {\n return *this;\n }\n _documentId = refValueRhs->_documentId;\n _dataType = refValueRhs->_dataType;\n _altered = true;\n return *this;\n}\n\nvoid ReferenceFieldValue::setDeserializedDocumentId(const DocumentId& id) {\n assert(_dataType != nullptr);\n requireIdOfMatchingType(id, _dataType->getTargetType());\n _documentId = id;\n _altered = false;\n}\n\nReferenceFieldValue* ReferenceFieldValue::clone() const {\n assert(_dataType != nullptr);\n return new ReferenceFieldValue(*_dataType, _documentId);\n}\n\nint ReferenceFieldValue::compare(const FieldValue& rhs) const {\n const int parentCompare = FieldValue::compare(rhs);\n if (parentCompare != 0) {\n return parentCompare;\n }\n \/\/ Type equality is checked by the parent.\n const auto& refValueRhs(dynamic_cast(rhs));\n \/\/ TODO PERF: DocumentId does currently _not_ expose any methods that\n \/\/ cheaply allow an ordering to be established. Only (in)equality operators.\n \/\/ IdString::operator== is already implemented in the same way as this, so\n \/\/ don't put this code in your inner loops, kids!\n return _documentId.toString().compare(refValueRhs._documentId.toString());\n}\n\nvoid ReferenceFieldValue::print(std::ostream& os, bool verbose, const std::string& indent) const {\n (void) verbose;\n (void) indent;\n assert(_dataType != nullptr);\n os << \"ReferenceFieldValue(\" << *_dataType << \", DocumentId(\";\n _documentId.print(os, false, \"\");\n os << \"))\";\n}\n\nbool ReferenceFieldValue::hasChanged() const {\n return _altered;\n}\n\nvoid ReferenceFieldValue::accept(FieldValueVisitor& visitor) {\n visitor.visit(*this);\n}\n\nvoid ReferenceFieldValue::accept(ConstFieldValueVisitor& visitor) const {\n visitor.visit(*this);\n}\n\n} \/\/ document\n<|endoftext|>"} {"text":"#ifndef DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_VECTOR_HH\n#define DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_VECTOR_HH\n\n\/\/ system\n#include \n\n\/\/ dune-stuff\n#include \n\nnamespace Dune\n{\n\nnamespace Detailed {\n\nnamespace Discretizations\n{\n\nnamespace Assembler\n{\n\nnamespace Local\n{\n\nnamespace Codim1\n{\n\n\/**\n \\todo Add neumann boundary treatment\n \\todo When adding neumann: think of numTmpObjectsRequired()!\n \\todo Add penalty parameter\n **\/\ntemplate< class LocalFunctionalImp >\nclass Vector\n{\npublic:\n\n typedef LocalFunctionalImp\n LocalFunctionalType;\n\n typedef Vector< LocalFunctionalType >\n ThisType;\n\n typedef typename LocalFunctionalType::RangeFieldType\n RangeFieldType;\n\n \/\/! constructor\n Vector( const LocalFunctionalType localFunctional )\n : localFunctional_( localFunctional )\n {\n }\n\nprivate:\n \/\/! copy constructor\n Vector( const ThisType& other )\n : localFunctional_( other.localFunctional() )\n {\n }\n\npublic:\n const LocalFunctionalType& localFunctional() const\n {\n return localFunctional_;\n }\n\n \/**\n \\todo Add neumann treatment here!\n **\/\n std::vector< unsigned int > numTmpObjectsRequired() const\n {\n std::vector< unsigned int > ret( 2, 0 );\n \/\/ we require 1 tmp vector in this local assembler\n ret[0] = 1;\n \/\/ the functional itself requires that much local matrices\n ret[1] = localFunctional_.numTmpObjectsRequired();\n return ret;\n }\n\n template< class TestSpaceType,\n class EntityType,\n class SystemVectorType,\n class LocalVectorType >\n void assembleLocal( const TestSpaceType& testSpace,\n const EntityType& entity,\n SystemVectorType& systemVector,\n std::vector< std::vector< LocalVectorType > >& tmpLocalVectorsContainer ) const\n {\n \/\/ get the local basefunction set\n typedef typename TestSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType\n LocalTesBaseFunctionSetType;\n\n const LocalTesBaseFunctionSetType localTestBaseFunctionSet = testSpace.baseFunctionSet().local( entity );\n\n \/\/ check tmp local vectors\n assert( tmpLocalVectorsContainer.size() > 1 );\n std::vector< LocalVectorType >& tmpLocalVectors = tmpLocalVectorsContainer[0];\n if( tmpLocalVectors.size() < 1 )\n {\n tmpLocalVectors.resize( 1, LocalVectorType( testSpace.map().maxLocalSize(), RangeFieldType( 0.0 ) ) );\n }\n\n \/\/ some types\n typedef typename TestSpaceType::GridViewType\n GridViewType;\n\n typedef typename GridViewType::IntersectionIterator\n IntersectionIteratorType;\n\n typedef typename IntersectionIteratorType::Intersection\n IntersectionType;\n\n typedef typename IntersectionType::EntityPointer\n EntityPointerType;\n\n const GridViewType& gridView = testSpace.gridView();\n\n const IntersectionIteratorType lastIntersection = gridView.iend( entity );\n\n \/\/ do loop over all intersections\n for( IntersectionIteratorType intIt = gridView.ibegin( entity ); intIt != lastIntersection; ++intIt )\n {\n const IntersectionType& intersection = *intIt;\n\n if( !intersection.neighbor() && intersection.boundary() ) \/\/ if boundary intersection\n {\n \/\/ clear target vectors\n Dune::Stuff::Common::clear(tmpLocalVectors[0]);\n\n localFunctional_.applyLocal( localTestBaseFunctionSet,\n intersection,\n tmpLocalVectors[0],\n tmpLocalVectorsContainer[1] );\n\n \/\/ write local vector to global\n addToVector( testSpace, entity, tmpLocalVectors[0], systemVector );\n\n }\/\/ end if boundary intersection\n } \/\/ done loop over all intersections\n } \/\/ end method assembleLocal\n\nprivate:\n\n \/\/! assignment operator\n ThisType& operator=( const ThisType& );\n\n template< class TestSpaceType,\n class EntityType,\n class LocalVectorType,\n class SystemVectorType >\n void addToVector( const TestSpaceType& testSpace,\n const EntityType& entity,\n const LocalVectorType& localVector,\n SystemVectorType& systemVector ) const\n {\n for( unsigned int j = 0; j < testSpace.baseFunctionSet().local( entity ).size(); ++j )\n {\n const unsigned int globalJ = testSpace.map().toGlobal( entity, j );\n\n systemVector[globalJ] += localVector[j];\n }\n } \/\/ end method addToVector\n\n const LocalFunctionalType localFunctional_;\n}; \/\/ end class Vector\n\n} \/\/ end namespace Codim1\n\n} \/\/ end namespace Local\n\n} \/\/ end namespace Assembler\n\n} \/\/ namespace Discretizations\n\n} \/\/ namespace Detailed\n\n} \/\/ end namespace Dune\n\n#endif \/\/ DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_VECTOR_HH\n[assembler.local.codim1.vector] added Neumann#ifndef DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_VECTOR_HH\n#define DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_VECTOR_HH\n\n#include \n\n#include \n\n#include \n#include \n\nnamespace Dune {\nnamespace Detailed {\nnamespace Discretizations {\nnamespace Assembler {\nnamespace Local {\nnamespace Codim1 {\nnamespace Vector {\n\ntemplate< class LocalFunctionalImp, class BoundaryInfoImp >\nclass Neumann\n{\npublic:\n typedef LocalFunctionalImp LocalFunctionalType;\n\n typedef BoundaryInfoImp BoundaryInfoType;\n\n typedef Neumann< LocalFunctionalType, BoundaryInfoType > ThisType;\n\n Neumann(const LocalFunctionalType& _localFunctional,\n const Dune::shared_ptr< const BoundaryInfoType > _boundaryInfo)\n : localFunctional_(_localFunctional)\n , boundaryInfo_(_boundaryInfo)\n {}\n\n const LocalFunctionalType& localFunctional() const\n {\n return localFunctional_;\n }\n\n const Dune::shared_ptr< const BoundaryInfoType > boundaryInfo() const\n {\n return boundaryInfo_;\n }\n\n std::vector< unsigned int > numTmpObjectsRequired() const\n {\n std::vector< unsigned int > ret(2, 0);\n \/\/ we require 1 tmp vector in this local assembler\n ret[0] = 1;\n \/\/ the functional itself requires that much local matrices\n ret[1] = localFunctional_.numTmpObjectsRequired();\n return ret;\n } \/\/ std::vector< unsigned int > numTmpObjectsRequired() const\n\n template< class TestSpaceType,\n class EntityType,\n class VectorType,\n class LocalVectorType >\n void assembleLocal(const TestSpaceType& testSpace,\n const EntityType& entity,\n VectorType& vector,\n std::vector< std::vector< LocalVectorType > >& tmpLocalVectorsContainer) const\n {\n \/\/ get the local basefunction set\n typedef typename TestSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType LocalTesBaseFunctionSetType;\n const LocalTesBaseFunctionSetType localTestBaseFunctionSet = testSpace.baseFunctionSet().local(entity);\n\n \/\/ check tmp local vectors\n typedef typename LocalFunctionalType::FunctionSpaceType::RangeFieldType RangeFieldType;\n assert(tmpLocalVectorsContainer.size() > 1);\n std::vector< LocalVectorType >& tmpLocalVectors = tmpLocalVectorsContainer[0];\n if (tmpLocalVectors.size() < numTmpObjectsRequired()[0])\n tmpLocalVectors.resize( numTmpObjectsRequired()[0],\n LocalVectorType(testSpace.map().maxLocalSize(),RangeFieldType(0)));\n\n \/\/ do loop over all intersections\n typedef typename TestSpaceType::GridViewType GridViewType;\n typedef typename GridViewType::IntersectionIterator IntersectionIteratorType;\n typedef typename IntersectionIteratorType::Intersection IntersectionType;\n typedef typename IntersectionType::EntityPointer EntityPointerType;\n const GridViewType& gridView = testSpace.gridView();\n for (IntersectionIteratorType intersectionIt = gridView.ibegin(entity);\n intersectionIt != gridView.iend(entity);\n ++intersectionIt) {\n const IntersectionType& intersection = *intersectionIt;\n if (boundaryInfo_->neumann(intersection)) {\n Dune::Stuff::Common::clear(tmpLocalVectors[0]);\n localFunctional_.applyLocal(localTestBaseFunctionSet,\n intersection,\n tmpLocalVectors[0],\n tmpLocalVectorsContainer[1]);\n addToVector(testSpace, entity, tmpLocalVectors[0], vector);\n }\n } \/\/ do loop over all intersections\n } \/\/ void assembleLocal(...)\n\nprivate:\n Neumann(const ThisType&);\n ThisType& operator=(const ThisType&);\n\n template< class TestSpaceType,\n class EntityType,\n class LocalVectorType,\n class SystemVectorType >\n void addToVector(const TestSpaceType& testSpace,\n const EntityType& entity,\n const LocalVectorType& localVector,\n SystemVectorType& systemVector) const\n {\n for (unsigned int j = 0; j < testSpace.baseFunctionSet().local(entity).size(); ++j) {\n const unsigned int globalJ = testSpace.map().toGlobal(entity, j);\n systemVector[globalJ] += localVector[j];\n }\n } \/\/ vodi addToVector(...)\n\n const LocalFunctionalType& localFunctional_;\n const Dune::shared_ptr< const BoundaryInfoType > boundaryInfo_;\n}; \/\/ class Neumann\n\n} \/\/ namespace Vector\n} \/\/ namespace Codim1\n} \/\/ namespace Local\n} \/\/ namespace Assembler\n} \/\/ namespace Discretizations\n} \/\/ namespace Detailed\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_VECTOR_HH\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n\n#include \n#include \n\nnamespace cutehmi {\nnamespace services {\n\nconstexpr int Service::INITIAL_STOP_TIMEOUT;\nconstexpr int Service::INITIAL_START_TIMEOUT;\nconstexpr int Service::INITIAL_REPAIR_TIMEOUT;\nconstexpr const char * Service::INITIAL_NAME;\n\nService::Service(QObject * parent):\n\tQObject(parent),\n\tm(new Members)\n{\n\tServiceManager::Instance().add(this);\n\tsetStatus(DefaultStatus());\n}\n\nService::~Service()\n{\n\tstop();\n\n\t\/\/ Wait till either service stops or is interrupted.\n\tif (m->stateInterface)\n\t\twhile (!m->stateInterface->stopped().active() && !m->stateInterface->interrupted().active()) {\n\t\t\t\/\/ Due to repair and start timeouts service may end up in broken state. Try to stop the service repeatedly.\n\t\t\tstop();\n\n\t\t\t\/\/ QCoreApplication::processEvents(QEventLoop::WaitForMoreEvents) slows down shutdown, so execute this loop aggressively.\n\t\t\tQCoreApplication::processEvents();\n\t\t}\n\n\tif (m->serviceable)\n\t\tServiceManager::Instance().leave(this);\n\tServiceManager::Instance().remove(this);\n\n\tif (m->stateMachine)\n\t\tm->stateMachine->stop();\n}\n\nint Service::stopTimeout() const\n{\n\treturn m->stopTimeout;\n}\n\nvoid Service::setStopTimeout(int timeout)\n{\n\tif (m->stopTimeout != timeout) {\n\t\tm->stopTimeout = timeout;\n\t\temit stopTimeoutChanged();\n\t}\n}\n\nint Service::startTimeout() const\n{\n\treturn m->startTimeout;\n}\n\nvoid Service::setStartTimeout(int startTimeout)\n{\n\tif (m->startTimeout != startTimeout) {\n\t\tm->startTimeout = startTimeout;\n\t\temit startTimeoutChanged();\n\t}\n}\n\nint Service::repairTimeout() const\n{\n\treturn m->repairTimeout;\n}\n\nvoid Service::setRepairTimeout(int repairTimeout)\n{\n\tif (m->repairTimeout != repairTimeout) {\n\t\tm->repairTimeout = repairTimeout;\n\t\temit repairTimeoutChanged();\n\t}\n}\n\nQString Service::name() const\n{\n\treturn m->name;\n}\n\nvoid Service::setName(const QString & name)\n{\n\tif (m->name != name) {\n\t\tm->name = name;\n\t\temit nameChanged();\n\t}\n}\n\nQString Service::status() const\n{\n\treturn m->status;\n}\n\nvoid Service::setServiceable(QVariant serviceable)\n{\n\tQObject * qobjectPtr = serviceable.value();\n\tServiceable * serviceablePtr = dynamic_cast(qobjectPtr);\n\tif (qobjectPtr != nullptr && serviceablePtr == nullptr)\n\t\tCUTEHMI_WARNING(\"Object assigned as serviceable to '\" << name() << \"' service does not implement 'cutehmi::services::Serviceable' interface.\");\n\n\tif (m->serviceable != serviceablePtr) {\n\t\tif (m->serviceable)\n\t\t\tServiceManager::Instance().leave(this);\n\t\tdestroyStateMachine();\n\t\tif (serviceablePtr)\n\t\t\tinitializeStateMachine(*serviceablePtr);\n\t\tm->serviceable = serviceablePtr;\n\t\tif (m->serviceable)\n\t\t\tServiceManager::Instance().manage(this);\n\t\telse\n\t\t\tsetStatus(DefaultStatus());\n\t\temit serviceableChanged();\n\t}\n}\n\nQVariant Service::serviceable() const\n{\n\treturn QVariant::fromValue(m->serviceable);\n}\n\nvoid Service::start()\n{\n\temit started();\n}\n\nvoid Service::stop()\n{\n\temit stopped();\n}\n\ninternal::StateInterface * Service::stateInterface()\n{\n\treturn m->stateInterface;\n}\n\nconst internal::StateInterface * Service::stateInterface() const\n{\n\treturn m->stateInterface;\n}\n\nvoid Service::activate()\n{\n\temit activated();\n}\n\nvoid Service::setStatus(const QString & status)\n{\n\tif (m->status != status) {\n\t\tm->status = status;\n\t\temit statusChanged();\n\t}\n}\n\nQString & Service::DefaultStatus()\n{\n\tstatic QString name = QObject::tr(\"Unmanaged\");\n\treturn name;\n}\n\nvoid Service::destroyStateMachine()\n{\n\tif (m->stateMachine) {\n\t\tm->stateMachine->stop();\n\t\tm->stateMachine->deleteLater();\n\t\tm->stateMachine = nullptr;\n\t\tm->stateInterface = nullptr;\n\t}\n}\n\nvoid Service::initializeStateMachine(Serviceable & serviceable)\n{\n\ttry {\n\t\tm->stateMachine = new QStateMachine(this);\n\t\tm->stateInterface = new internal::StateInterface(m->stateMachine);\n\n\n\t\tconnect(m->stateInterface, & internal::StateInterface::statusChanged, this, [this]() {\n\t\t\tsetStatus(m->stateInterface->status());\n\t\t} );\n\n\n\t\t\/\/ Variable m->lastNotifiableState is used to prevent notification spam, i.e. when service fails to leave notifiable state\n\t\t\/\/ through intermediate, non-notifiable state (e.g. 'broken' is a notifiable state, 'repairing' is an intermediate state;\n\t\t\/\/ without the condition \"Service 'XYZ' broke\" message would be posted after each failed repair attempt).\n\t\tconnect(& m->stateInterface->interrupted(), & QState::entered, [this]() {\n\t\t\tif (m->lastNotifiableState != & m->stateInterface->interrupted())\n\t\t\t\tNotification::Critical(tr(\"Stop sequence of '%1' service has been interrupted, because it took more than %2 [ms] to stop the service.\").arg(name()).arg(stopTimeout()));\n\t\t\tm->lastNotifiableState = & m->stateInterface->interrupted();\n\t\t});\n\t\tconnect(& m->stateInterface->started(), & QState::entered, [this]() {\n\t\t\tif (m->lastNotifiableState != & m->stateInterface->started())\n\t\t\t\tNotification::Info(tr(\"Service '%1' has started.\").arg(name()));\n\t\t\tm->lastNotifiableState = & m->stateInterface->started();\n\t\t});\n\t\tconnect(& m->stateInterface->stopped(), & QState::entered, [this]() {\n\t\t\tif (m->lastNotifiableState != & m->stateInterface->stopped())\n\t\t\t\tNotification::Info(tr(\"Service '%1' is stopped.\").arg(name()));\n\t\t\tm->lastNotifiableState = & m->stateInterface->stopped();\n\t\t});\n\t\tconnect(& m->stateInterface->broken(), & QState::entered, [this]() {\n\t\t\tif (m->lastNotifiableState != & m->stateInterface->broken())\n\t\t\t\tNotification::Warning(tr(\"Service '%1' broke.\").arg(name()));\n\t\t\tm->lastNotifiableState = & m->stateInterface->broken();\n\t\t});\n\n\n\t\t\/\/ Configure timeouts.\n\n\t\tconnect(& m->stateInterface->stopping(), & QState::entered, [this]() {\n\t\t\tif (stopTimeout() >= 0)\n\t\t\t\tm->timeoutTimer.start(stopTimeout());\n\t\t});\n\t\t\/\/ It's safer to stop timeout, so that it won't make false shot.\n\t\tconnect(& m->stateInterface->stopping(), & QState::exited, & m->timeoutTimer, & QTimer::stop);\n\n\t\tconnect(& m->stateInterface->evacuating(), & QState::entered, [this]() {\n\t\t\tif (stopTimeout() >= 0)\n\t\t\t\tm->timeoutTimer.start(stopTimeout());\n\t\t});\n\t\t\/\/ It's safer to stop timeout, so that it won't make false shot.\n\t\tconnect(& m->stateInterface->evacuating(), & QState::exited, & m->timeoutTimer, & QTimer::stop);\n\n\t\tconnect(& m->stateInterface->starting(), & QState::entered, [this]() {\n\t\t\tif (startTimeout() >= 0)\n\t\t\t\tm->timeoutTimer.start(startTimeout());\n\t\t});\n\t\t\/\/ It's safer to stop timeout, so that it won't make false shot.\n\t\tconnect(& m->stateInterface->starting(), & QState::exited, & m->timeoutTimer, & QTimer::stop);\n\n\t\tconnect(& m->stateInterface->repairing(), & QState::entered, [this]() {\n\t\t\tif (repairTimeout() >= 0)\n\t\t\t\tm->timeoutTimer.start(repairTimeout());\n\t\t});\n\t\t\/\/ It's safer to stop timeout, so that it won't make false shot.\n\t\tconnect(& m->stateInterface->repairing(), & QState::exited, & m->timeoutTimer, & QTimer::stop);\n\n\n\t\tm->stateInterface->stopped().assignProperty(m->stateInterface, \"status\", tr(\"Stopped\"));\n\t\tm->stateInterface->interrupted().assignProperty(m->stateInterface, \"status\", tr(\"Interrupted\"));\n\t\tm->stateInterface->starting().assignProperty(m->stateInterface, \"status\", tr(\"Starting\"));\n\t\tm->stateInterface->started().assignProperty(m->stateInterface, \"status\", tr(\"Started\"));\n\t\tm->stateInterface->idling().assignProperty(m->stateInterface, \"status\", tr(\"Idling\"));\n\t\tm->stateInterface->yielding().assignProperty(m->stateInterface, \"status\", tr(\"Yielding\"));\n\t\tm->stateInterface->active().assignProperty(m->stateInterface, \"status\", tr(\"Active\"));\n\t\tm->stateInterface->stopping().assignProperty(m->stateInterface, \"status\", tr(\"Stopping\"));\n\t\tm->stateInterface->broken().assignProperty(m->stateInterface, \"status\", tr(\"Broken\"));\n\t\tm->stateInterface->repairing().assignProperty(m->stateInterface, \"status\", tr(\"Repairing\"));\n\t\tm->stateInterface->evacuating().assignProperty(m->stateInterface, \"status\", tr(\"Evacuating\"));\n\n\n\t\tm->stateMachine->addState(& m->stateInterface->stopped());\n\t\tm->stateMachine->addState(& m->stateInterface->interrupted());\n\t\tm->stateMachine->addState(& m->stateInterface->starting());\n\t\tm->stateMachine->addState(& m->stateInterface->started());\n\t\tm->stateMachine->addState(& m->stateInterface->stopping());\n\t\tm->stateMachine->addState(& m->stateInterface->broken());\n\t\tm->stateMachine->addState(& m->stateInterface->repairing());\n\t\tm->stateMachine->addState(& m->stateInterface->evacuating());\n\t\tm->stateMachine->setInitialState(& m->stateInterface->stopped());\n\n\n\t\tm->stateInterface->stopped().addTransition(this, & Service::started, & m->stateInterface->starting());\n\t\tm->stateInterface->started().addTransition(this, & Service::stopped, & m->stateInterface->stopping());\n\t\tm->stateInterface->broken().addTransition(this, & Service::started, & m->stateInterface->repairing());\n\t\tm->stateInterface->broken().addTransition(this, & Service::stopped, & m->stateInterface->evacuating());\n\t\tm->stateInterface->stopping().addTransition(& m->timeoutTimer, & QTimer::timeout, & m->stateInterface->interrupted());\n\t\tm->stateInterface->starting().addTransition(& m->timeoutTimer, & QTimer::timeout, & m->stateInterface->broken());\n\t\tm->stateInterface->repairing().addTransition(& m->timeoutTimer, & QTimer::timeout, & m->stateInterface->broken());\n\t\tm->stateInterface->yielding().addTransition(this, & Service::activated, & m->stateInterface->active());\n\t\tm->stateInterface->evacuating().addTransition(& m->timeoutTimer, & QTimer::timeout, & m->stateInterface->interrupted());\n\n\n\t\taddTransition(& m->stateInterface->starting(), & m->stateInterface->started(), serviceable.transitionToStarted());\n\t\taddTransition(& m->stateInterface->repairing(), & m->stateInterface->started(), serviceable.transitionToStarted());\n\t\taddTransition(& m->stateInterface->stopping(), & m->stateInterface->stopped(), serviceable.transitionToStopped());\n\t\taddTransition(& m->stateInterface->starting(), & m->stateInterface->broken(), serviceable.transitionToBroken());\n\t\taddTransition(& m->stateInterface->started(), & m->stateInterface->broken(), serviceable.transitionToBroken());\n\t\taddTransition(& m->stateInterface->repairing(), & m->stateInterface->broken(), serviceable.transitionToBroken());\n\t\tif (serviceable.transitionToIdling())\n\t\t\taddTransition(& m->stateInterface->active(), & m->stateInterface->idling(), serviceable.transitionToIdling());\n\t\taddTransition(& m->stateInterface->idling(), & m->stateInterface->yielding(), serviceable.transitionToYielding());\n\t\taddTransition(& m->stateInterface->evacuating(), & m->stateInterface->stopped(), serviceable.transitionToStopped());\n\n\n\t\taddStatuses(serviceable.configureBroken(& m->stateInterface->broken()));\n\t\taddStatuses(serviceable.configureStarted(& m->stateInterface->active(), & m->stateInterface->idling(), & m->stateInterface->yielding()));\n\t\taddStatuses(serviceable.configureStarting(& m->stateInterface->starting()));\n\t\taddStatuses(serviceable.configureStopping(& m->stateInterface->stopping()));\n\t\taddStatuses(serviceable.configureRepairing(& m->stateInterface->repairing()));\n\t\taddStatuses(serviceable.configureEvacuating(& m->stateInterface->evacuating()));\n\n\n\t\tm->stateMachine->start();\n\t\tQCoreApplication::processEvents();\t\/\/ This is required in order to truly start state machine and prevent it from ignoring incoming events.\n\t} catch (const std::exception & e) {\n\t\tCUTEHMI_CRITICAL(\"Could not initialize new state machine, because of following exception: \" << e.what());\n\t}\n}\n\nvoid Service::addTransition(QState * source, QState * target, std::unique_ptr transition)\n{\n\tif (transition) {\n\t\ttransition->setParent(source);\n\t\ttransition->setTargetState(target);\n\t\tsource->addTransition(transition.release());\n\t} else\n\t\tsource->addTransition(target);\n}\n\nvoid Service::addStatuses(std::unique_ptr statuses)\n{\n\tif (statuses)\n\t\tfor (auto stateStatus = statuses->begin(); stateStatus != statuses->end(); ++stateStatus)\n\t\t\tstateStatus.key()->assignProperty(m->stateInterface, \"status\", stateStatus.value());\n}\n\n}\n}\n\n\/\/(c)C: Copyright © 2019-2020, Michał Policht , Yuri Chornoivan . All rights reserved.\n\/\/(c)C: This file is a part of CuteHMI.\n\/\/(c)C: CuteHMI 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 3 of the License, or (at your option) any later version.\n\/\/(c)C: CuteHMI 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.\n\/\/(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see .\nPrint service status in debug output.#include \n\n#include \n#include \n\n#include \n#include \n\nnamespace cutehmi {\nnamespace services {\n\nconstexpr int Service::INITIAL_STOP_TIMEOUT;\nconstexpr int Service::INITIAL_START_TIMEOUT;\nconstexpr int Service::INITIAL_REPAIR_TIMEOUT;\nconstexpr const char * Service::INITIAL_NAME;\n\nService::Service(QObject * parent):\n\tQObject(parent),\n\tm(new Members)\n{\n\tServiceManager::Instance().add(this);\n\tsetStatus(DefaultStatus());\n}\n\nService::~Service()\n{\n\tstop();\n\n\t\/\/ Wait till either service stops or is interrupted.\n\tif (m->stateInterface)\n\t\twhile (!m->stateInterface->stopped().active() && !m->stateInterface->interrupted().active()) {\n\t\t\t\/\/ Due to repair and start timeouts service may end up in broken state. Try to stop the service repeatedly.\n\t\t\tstop();\n\n\t\t\t\/\/ QCoreApplication::processEvents(QEventLoop::WaitForMoreEvents) slows down shutdown, so execute this loop aggressively.\n\t\t\tQCoreApplication::processEvents();\n\t\t}\n\n\tif (m->serviceable)\n\t\tServiceManager::Instance().leave(this);\n\tServiceManager::Instance().remove(this);\n\n\tif (m->stateMachine)\n\t\tm->stateMachine->stop();\n}\n\nint Service::stopTimeout() const\n{\n\treturn m->stopTimeout;\n}\n\nvoid Service::setStopTimeout(int timeout)\n{\n\tif (m->stopTimeout != timeout) {\n\t\tm->stopTimeout = timeout;\n\t\temit stopTimeoutChanged();\n\t}\n}\n\nint Service::startTimeout() const\n{\n\treturn m->startTimeout;\n}\n\nvoid Service::setStartTimeout(int startTimeout)\n{\n\tif (m->startTimeout != startTimeout) {\n\t\tm->startTimeout = startTimeout;\n\t\temit startTimeoutChanged();\n\t}\n}\n\nint Service::repairTimeout() const\n{\n\treturn m->repairTimeout;\n}\n\nvoid Service::setRepairTimeout(int repairTimeout)\n{\n\tif (m->repairTimeout != repairTimeout) {\n\t\tm->repairTimeout = repairTimeout;\n\t\temit repairTimeoutChanged();\n\t}\n}\n\nQString Service::name() const\n{\n\treturn m->name;\n}\n\nvoid Service::setName(const QString & name)\n{\n\tif (m->name != name) {\n\t\tm->name = name;\n\t\temit nameChanged();\n\t}\n}\n\nQString Service::status() const\n{\n\treturn m->status;\n}\n\nvoid Service::setServiceable(QVariant serviceable)\n{\n\tQObject * qobjectPtr = serviceable.value();\n\tServiceable * serviceablePtr = dynamic_cast(qobjectPtr);\n\tif (qobjectPtr != nullptr && serviceablePtr == nullptr)\n\t\tCUTEHMI_WARNING(\"Object assigned as serviceable to '\" << name() << \"' service does not implement 'cutehmi::services::Serviceable' interface.\");\n\n\tif (m->serviceable != serviceablePtr) {\n\t\tif (m->serviceable)\n\t\t\tServiceManager::Instance().leave(this);\n\t\tdestroyStateMachine();\n\t\tif (serviceablePtr)\n\t\t\tinitializeStateMachine(*serviceablePtr);\n\t\tm->serviceable = serviceablePtr;\n\t\tif (m->serviceable)\n\t\t\tServiceManager::Instance().manage(this);\n\t\telse\n\t\t\tsetStatus(DefaultStatus());\n\t\temit serviceableChanged();\n\t}\n}\n\nQVariant Service::serviceable() const\n{\n\treturn QVariant::fromValue(m->serviceable);\n}\n\nvoid Service::start()\n{\n\temit started();\n}\n\nvoid Service::stop()\n{\n\temit stopped();\n}\n\ninternal::StateInterface * Service::stateInterface()\n{\n\treturn m->stateInterface;\n}\n\nconst internal::StateInterface * Service::stateInterface() const\n{\n\treturn m->stateInterface;\n}\n\nvoid Service::activate()\n{\n\temit activated();\n}\n\nvoid Service::setStatus(const QString & status)\n{\n\tif (m->status != status) {\n\t\tm->status = status;\n\t\tif (m->serviceable)\n\t\t\tCUTEHMI_DEBUG(name() << \": \" << status);\n\t\temit statusChanged();\n\t}\n}\n\nQString & Service::DefaultStatus()\n{\n\tstatic QString name = QObject::tr(\"Unmanaged\");\n\treturn name;\n}\n\nvoid Service::destroyStateMachine()\n{\n\tif (m->stateMachine) {\n\t\tm->stateMachine->stop();\n\t\tm->stateMachine->deleteLater();\n\t\tm->stateMachine = nullptr;\n\t\tm->stateInterface = nullptr;\n\t}\n}\n\nvoid Service::initializeStateMachine(Serviceable & serviceable)\n{\n\ttry {\n\t\tm->stateMachine = new QStateMachine(this);\n\t\tm->stateInterface = new internal::StateInterface(m->stateMachine);\n\n\n\t\tconnect(m->stateInterface, & internal::StateInterface::statusChanged, this, [this]() {\n\t\t\tsetStatus(m->stateInterface->status());\n\t\t} );\n\n\n\t\t\/\/ Variable m->lastNotifiableState is used to prevent notification spam, i.e. when service fails to leave notifiable state\n\t\t\/\/ through intermediate, non-notifiable state (e.g. 'broken' is a notifiable state, 'repairing' is an intermediate state;\n\t\t\/\/ without the condition \"Service 'XYZ' broke\" message would be posted after each failed repair attempt).\n\t\tconnect(& m->stateInterface->interrupted(), & QState::entered, [this]() {\n\t\t\tif (m->lastNotifiableState != & m->stateInterface->interrupted())\n\t\t\t\tNotification::Critical(tr(\"Stop sequence of '%1' service has been interrupted, because it took more than %2 [ms] to stop the service.\").arg(name()).arg(stopTimeout()));\n\t\t\tm->lastNotifiableState = & m->stateInterface->interrupted();\n\t\t});\n\t\tconnect(& m->stateInterface->started(), & QState::entered, [this]() {\n\t\t\tif (m->lastNotifiableState != & m->stateInterface->started())\n\t\t\t\tNotification::Info(tr(\"Service '%1' has started.\").arg(name()));\n\t\t\tm->lastNotifiableState = & m->stateInterface->started();\n\t\t});\n\t\tconnect(& m->stateInterface->stopped(), & QState::entered, [this]() {\n\t\t\tif (m->lastNotifiableState != & m->stateInterface->stopped())\n\t\t\t\tNotification::Info(tr(\"Service '%1' is stopped.\").arg(name()));\n\t\t\tm->lastNotifiableState = & m->stateInterface->stopped();\n\t\t});\n\t\tconnect(& m->stateInterface->broken(), & QState::entered, [this]() {\n\t\t\tif (m->lastNotifiableState != & m->stateInterface->broken())\n\t\t\t\tNotification::Warning(tr(\"Service '%1' broke.\").arg(name()));\n\t\t\tm->lastNotifiableState = & m->stateInterface->broken();\n\t\t});\n\n\n\t\t\/\/ Configure timeouts.\n\n\t\tconnect(& m->stateInterface->stopping(), & QState::entered, [this]() {\n\t\t\tif (stopTimeout() >= 0)\n\t\t\t\tm->timeoutTimer.start(stopTimeout());\n\t\t});\n\t\t\/\/ It's safer to stop timeout, so that it won't make false shot.\n\t\tconnect(& m->stateInterface->stopping(), & QState::exited, & m->timeoutTimer, & QTimer::stop);\n\n\t\tconnect(& m->stateInterface->evacuating(), & QState::entered, [this]() {\n\t\t\tif (stopTimeout() >= 0)\n\t\t\t\tm->timeoutTimer.start(stopTimeout());\n\t\t});\n\t\t\/\/ It's safer to stop timeout, so that it won't make false shot.\n\t\tconnect(& m->stateInterface->evacuating(), & QState::exited, & m->timeoutTimer, & QTimer::stop);\n\n\t\tconnect(& m->stateInterface->starting(), & QState::entered, [this]() {\n\t\t\tif (startTimeout() >= 0)\n\t\t\t\tm->timeoutTimer.start(startTimeout());\n\t\t});\n\t\t\/\/ It's safer to stop timeout, so that it won't make false shot.\n\t\tconnect(& m->stateInterface->starting(), & QState::exited, & m->timeoutTimer, & QTimer::stop);\n\n\t\tconnect(& m->stateInterface->repairing(), & QState::entered, [this]() {\n\t\t\tif (repairTimeout() >= 0)\n\t\t\t\tm->timeoutTimer.start(repairTimeout());\n\t\t});\n\t\t\/\/ It's safer to stop timeout, so that it won't make false shot.\n\t\tconnect(& m->stateInterface->repairing(), & QState::exited, & m->timeoutTimer, & QTimer::stop);\n\n\n\t\tm->stateInterface->stopped().assignProperty(m->stateInterface, \"status\", tr(\"Stopped\"));\n\t\tm->stateInterface->interrupted().assignProperty(m->stateInterface, \"status\", tr(\"Interrupted\"));\n\t\tm->stateInterface->starting().assignProperty(m->stateInterface, \"status\", tr(\"Starting\"));\n\t\tm->stateInterface->started().assignProperty(m->stateInterface, \"status\", tr(\"Started\"));\n\t\tm->stateInterface->idling().assignProperty(m->stateInterface, \"status\", tr(\"Idling\"));\n\t\tm->stateInterface->yielding().assignProperty(m->stateInterface, \"status\", tr(\"Yielding\"));\n\t\tm->stateInterface->active().assignProperty(m->stateInterface, \"status\", tr(\"Active\"));\n\t\tm->stateInterface->stopping().assignProperty(m->stateInterface, \"status\", tr(\"Stopping\"));\n\t\tm->stateInterface->broken().assignProperty(m->stateInterface, \"status\", tr(\"Broken\"));\n\t\tm->stateInterface->repairing().assignProperty(m->stateInterface, \"status\", tr(\"Repairing\"));\n\t\tm->stateInterface->evacuating().assignProperty(m->stateInterface, \"status\", tr(\"Evacuating\"));\n\n\n\t\tm->stateMachine->addState(& m->stateInterface->stopped());\n\t\tm->stateMachine->addState(& m->stateInterface->interrupted());\n\t\tm->stateMachine->addState(& m->stateInterface->starting());\n\t\tm->stateMachine->addState(& m->stateInterface->started());\n\t\tm->stateMachine->addState(& m->stateInterface->stopping());\n\t\tm->stateMachine->addState(& m->stateInterface->broken());\n\t\tm->stateMachine->addState(& m->stateInterface->repairing());\n\t\tm->stateMachine->addState(& m->stateInterface->evacuating());\n\t\tm->stateMachine->setInitialState(& m->stateInterface->stopped());\n\n\n\t\tm->stateInterface->stopped().addTransition(this, & Service::started, & m->stateInterface->starting());\n\t\tm->stateInterface->started().addTransition(this, & Service::stopped, & m->stateInterface->stopping());\n\t\tm->stateInterface->broken().addTransition(this, & Service::started, & m->stateInterface->repairing());\n\t\tm->stateInterface->broken().addTransition(this, & Service::stopped, & m->stateInterface->evacuating());\n\t\tm->stateInterface->stopping().addTransition(& m->timeoutTimer, & QTimer::timeout, & m->stateInterface->interrupted());\n\t\tm->stateInterface->starting().addTransition(& m->timeoutTimer, & QTimer::timeout, & m->stateInterface->broken());\n\t\tm->stateInterface->repairing().addTransition(& m->timeoutTimer, & QTimer::timeout, & m->stateInterface->broken());\n\t\tm->stateInterface->yielding().addTransition(this, & Service::activated, & m->stateInterface->active());\n\t\tm->stateInterface->evacuating().addTransition(& m->timeoutTimer, & QTimer::timeout, & m->stateInterface->interrupted());\n\n\n\t\taddTransition(& m->stateInterface->starting(), & m->stateInterface->started(), serviceable.transitionToStarted());\n\t\taddTransition(& m->stateInterface->repairing(), & m->stateInterface->started(), serviceable.transitionToStarted());\n\t\taddTransition(& m->stateInterface->stopping(), & m->stateInterface->stopped(), serviceable.transitionToStopped());\n\t\taddTransition(& m->stateInterface->starting(), & m->stateInterface->broken(), serviceable.transitionToBroken());\n\t\taddTransition(& m->stateInterface->started(), & m->stateInterface->broken(), serviceable.transitionToBroken());\n\t\taddTransition(& m->stateInterface->repairing(), & m->stateInterface->broken(), serviceable.transitionToBroken());\n\t\tif (serviceable.transitionToIdling())\n\t\t\taddTransition(& m->stateInterface->active(), & m->stateInterface->idling(), serviceable.transitionToIdling());\n\t\taddTransition(& m->stateInterface->idling(), & m->stateInterface->yielding(), serviceable.transitionToYielding());\n\t\taddTransition(& m->stateInterface->evacuating(), & m->stateInterface->stopped(), serviceable.transitionToStopped());\n\n\n\t\taddStatuses(serviceable.configureBroken(& m->stateInterface->broken()));\n\t\taddStatuses(serviceable.configureStarted(& m->stateInterface->active(), & m->stateInterface->idling(), & m->stateInterface->yielding()));\n\t\taddStatuses(serviceable.configureStarting(& m->stateInterface->starting()));\n\t\taddStatuses(serviceable.configureStopping(& m->stateInterface->stopping()));\n\t\taddStatuses(serviceable.configureRepairing(& m->stateInterface->repairing()));\n\t\taddStatuses(serviceable.configureEvacuating(& m->stateInterface->evacuating()));\n\n\n\t\tm->stateMachine->start();\n\t\tQCoreApplication::processEvents();\t\/\/ This is required in order to truly start state machine and prevent it from ignoring incoming events.\n\t} catch (const std::exception & e) {\n\t\tCUTEHMI_CRITICAL(\"Could not initialize new state machine, because of following exception: \" << e.what());\n\t}\n}\n\nvoid Service::addTransition(QState * source, QState * target, std::unique_ptr transition)\n{\n\tif (transition) {\n\t\ttransition->setParent(source);\n\t\ttransition->setTargetState(target);\n\t\tsource->addTransition(transition.release());\n\t} else\n\t\tsource->addTransition(target);\n}\n\nvoid Service::addStatuses(std::unique_ptr statuses)\n{\n\tif (statuses)\n\t\tfor (auto stateStatus = statuses->begin(); stateStatus != statuses->end(); ++stateStatus)\n\t\t\tstateStatus.key()->assignProperty(m->stateInterface, \"status\", stateStatus.value());\n}\n\n}\n}\n\n\/\/(c)C: Copyright © 2019-2020, Michał Policht , Yuri Chornoivan . All rights reserved.\n\/\/(c)C: This file is a part of CuteHMI.\n\/\/(c)C: CuteHMI 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 3 of the License, or (at your option) any later version.\n\/\/(c)C: CuteHMI 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.\n\/\/(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see .\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) Microsoft. All rights reserved.\n\/\/ Licensed under the MIT license. See LICENSE file in the project root for full license information. \n\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ The name of the CoreCLR native runtime DLL.\nstatic const char * const coreClrDll = \"libcoreclr.so\";\n\n\/\/ Windows types used by the ExecuteAssembly function\ntypedef unsigned int DWORD;\ntypedef const char16_t* LPCWSTR;\ntypedef const char* LPCSTR;\ntypedef int32_t HRESULT;\n\n#define SUCCEEDED(Status) ((HRESULT)(Status) >= 0)\n\n\/\/ Prototype of the ExecuteAssembly function from the libcoreclr.do\ntypedef HRESULT (*ExecuteAssemblyFunction)(\n LPCSTR exePath,\n LPCSTR coreClrPath,\n LPCSTR appDomainFriendlyName,\n int propertyCount,\n LPCSTR* propertyKeys,\n LPCSTR* propertyValues,\n int argc,\n LPCSTR* argv,\n LPCSTR managedAssemblyPath,\n DWORD* exitCode);\n\n\/\/ Display the command line options\nvoid DisplayUsage()\n{\n fprintf(\n stderr,\n \"Usage: corerun [OPTIONS] assembly [ARGUMENTS]\\n\"\n \"Execute the specified managed assembly with the passed in arguments\\n\\n\"\n \"Options:\\n\"\n \"-c, --clr-path path to the libcoreclr.so and the managed CLR assemblies\\n\");\n}\n\n\/\/ Get absolute path from the specified path.\n\/\/ Return true in case of a success, false otherwise.\nbool GetAbsolutePath(const char* path, std::string& absolutePath)\n{\n bool result = false;\n \n char realPath[PATH_MAX];\n if (realpath(path, realPath) != nullptr && realPath[0] != '\\0')\n {\n absolutePath.assign(realPath);\n \/\/ The realpath should return canonicalized path without the trailing slash\n assert(absolutePath.back() != '\/');\n\n result = true;\n } \n \n return result;\n}\n\nvoid GetDirectory(const char* path, std::string& directory)\n{\n directory.assign(path);\n size_t lastSlash = directory.rfind('\/');\n directory.erase(lastSlash); \n}\n\n\/\/ Parse the command line arguments \nbool ParseArguments(\n const int argc,\n const char* argv[],\n const char** clrFilesPath,\n const char** managedAssemblyPath,\n int* managedAssemblyArgc,\n const char*** managedAssemblyArgv)\n{\n bool success = false;\n\n *clrFilesPath = nullptr;\n *managedAssemblyPath = nullptr;\n *managedAssemblyArgv = nullptr;\n *managedAssemblyArgc = 0;\n\n \/\/ The command line must contain at least the current exe name and the managed assembly path\n if (argc >= 2)\n {\n for (int i = 1; i < argc; i++)\n {\n \/\/ Check for an option\n if (argv[i][0] == '-')\n {\n \/\/ Path to the libcoreclr.so and the managed CLR assemblies\n if (strcmp(argv[i], \"-c\") == 0 || strcmp(argv[i], \"--clr-path\") == 0)\n {\n i++;\n if (i < argc)\n {\n *clrFilesPath = argv[i];\n }\n else\n {\n fprintf(stderr, \"Option %s: missing path\\n\", argv[i - 1]);\n break;\n }\n }\n else if (strcmp(argv[i], \"--help\") == 0)\n {\n DisplayUsage();\n break;\n }\n else\n {\n fprintf(stderr, \"Unknown option %s\\n\", argv[i]);\n break;\n }\n }\n else\n {\n \/\/ First argument that is not an option is the managed assembly to execute\n *managedAssemblyPath = argv[i];\n\n int managedArgvOffset = (i + 1);\n *managedAssemblyArgc = argc - managedArgvOffset;\n if (*managedAssemblyArgc != 0)\n {\n *managedAssemblyArgv = &argv[managedArgvOffset];\n }\n success = true;\n break;\n }\n }\n }\n else\n {\n DisplayUsage();\n }\n\n return success;\n}\n\n\/\/ Add all *.dll, *.ni.dll, *.exe, and *.ni.exe files from the specified directory\n\/\/ to the tpaList string;\nvoid AddFilesFromDirectoryToTpaList(const char* directory, std::string& tpaList)\n{\n const char * const tpaExtensions[] = {\n \".ni.dll\",\t\t\/\/ Probe for .ni.dll first so that it's preferred if ni and il coexist in the same dir\n \".dll\",\n \".ni.exe\",\n \".exe\",\n };\n \n DIR* dir = opendir(directory);\n if (dir == nullptr)\n {\n return;\n }\n\n std::set addedAssemblies;\n \n \/\/ Walk the directory for each extension separately so that we first get files with .ni.dll extension,\n \/\/ then files with .dll extension, etc.\n for (int extIndex = 0; extIndex < sizeof(tpaExtensions) \/ sizeof(tpaExtensions[0]); extIndex++)\n {\n const char* ext = tpaExtensions[extIndex];\n int extLength = strlen(ext);\n \n struct dirent* entry;\n \n \/\/ For all entries in the directory\n while ((entry = readdir(dir)) != nullptr)\n {\n \/\/ We are interested in files only\n if (entry->d_type != DT_REG)\n {\n continue;\n }\n\n std::string filename(entry->d_name);\n \n \/\/ Check if the extension matches the one we are looking for\n size_t extPos = filename.length() - extLength;\n if ((extPos <= 0) || (filename.compare(extPos, extLength, ext) != 0))\n {\n continue;\n }\n \n std::string filenameWithoutExt(filename.substr(0, extPos));\n\n \/\/ Make sure if we have an assembly with multiple extensions present,\n \/\/ we insert only one version of it.\n if (addedAssemblies.find(filenameWithoutExt) == addedAssemblies.end())\n {\n addedAssemblies.insert(filenameWithoutExt);\n\n tpaList.append(directory);\n tpaList.append(\"\/\");\n tpaList.append(filename);\n tpaList.append(\":\");\n }\n } \n \n \/\/ Rewind the directory stream to be able to iterate over it for the next extension\n rewinddir(dir);\n }\n \n closedir(dir); \n}\n\n\/\/\n\/\/ Execute the specified managed assembly. \n\/\/\n\/\/ Parameters:\n\/\/ currentExePath - Path of the current executable\n\/\/ clrFilesAbsolutePath - Absolute path of a folder where the libcoreclr.so and CLR managed assemblies are stored\n\/\/ managedAssemblyPath - Path to the managed assembly to execute\n\/\/ managedAssemblyArgc - Number of arguments passed to the executed assembly\n\/\/ managedAssemblyArgv - Array of arguments passed to the executed assembly\n\/\/\n\/\/ Returns:\n\/\/ ExitCode of the assembly\n\/\/\nint ExecuteManagedAssembly(\n const char* currentExeAbsolutePath,\n const char* clrFilesAbsolutePath,\n const char* managedAssemblyAbsolutePath,\n int managedAssemblyArgc,\n const char** managedAssemblyArgv)\n{\n \/\/ Indicates failure\n int exitCode = -1;\n \n std::string coreClrDllPath(clrFilesAbsolutePath);\n coreClrDllPath.append(\"\/\");\n coreClrDllPath.append(coreClrDll);\n \n if (coreClrDllPath.length() >= PATH_MAX)\n {\n fprintf(stderr, \"Absolute path to libcoreclr.so too long\\n\");\n return -1;\n }\n\n \/\/ Get just the path component of the managed assembly path\n std::string appPath;\n GetDirectory(managedAssemblyAbsolutePath, appPath);\n \n std::string nativeDllSearchDirs(appPath);\n nativeDllSearchDirs.append(\":\");\n nativeDllSearchDirs.append(clrFilesAbsolutePath);\n \n std::string tpaList;\n AddFilesFromDirectoryToTpaList(clrFilesAbsolutePath, tpaList);\n \n void* coreclrLib = dlopen(coreClrDllPath.c_str(), RTLD_NOW);\n if (coreclrLib != nullptr)\n {\n ExecuteAssemblyFunction executeAssembly = (ExecuteAssemblyFunction)dlsym(coreclrLib, \"ExecuteAssembly\");\n if (executeAssembly != nullptr)\n {\n \/\/ Allowed property names:\n \/\/ APPBASE\n \/\/ - The base path of the application from which the exe and other assemblies will be loaded\n \/\/\n \/\/ TRUSTED_PLATFORM_ASSEMBLIES\n \/\/ - The list of complete paths to each of the fully trusted assemblies\n \/\/\n \/\/ APP_PATHS\n \/\/ - The list of paths which will be probed by the assembly loader\n \/\/\n \/\/ APP_NI_PATHS\n \/\/ - The list of additional paths that the assembly loader will probe for ngen images\n \/\/\n \/\/ NATIVE_DLL_SEARCH_DIRECTORIES\n \/\/ - The list of paths that will be probed for native DLLs called by PInvoke\n \/\/\n const char *propertyKeys[] = {\n \"TRUSTED_PLATFORM_ASSEMBLIES\",\n \"APP_PATHS\",\n \"APP_NI_PATHS\",\n \"NATIVE_DLL_SEARCH_DIRECTORIES\"\n };\n const char *propertyValues[] = {\n \/\/ TRUSTED_PLATFORM_ASSEMBLIES\n tpaList.c_str(),\n \/\/ APP_PATHS\n appPath.c_str(),\n \/\/ APP_NI_PATHS\n appPath.c_str(),\n \/\/ NATIVE_DLL_SEARCH_DIRECTORIES\n nativeDllSearchDirs.c_str()\n };\n\n HRESULT st = executeAssembly(\n currentExeAbsolutePath,\n coreClrDllPath.c_str(),\n \"unixcorerun\",\n sizeof(propertyKeys) \/ sizeof(propertyKeys[0]),\n propertyKeys,\n propertyValues,\n managedAssemblyArgc,\n managedAssemblyArgv,\n managedAssemblyAbsolutePath,\n (DWORD*)&exitCode);\n\n if (!SUCCEEDED(st))\n {\n fprintf(stderr, \"ExecuteAssembly failed - status: 0x%08x\\n\", st);\n }\n }\n else\n {\n fprintf(stderr, \"Function ExecuteAssembly not found in the libcoreclr.so\\n\");\n }\n\n if (dlclose(coreclrLib) != 0)\n {\n fprintf(stderr, \"Warning - dlclose failed\\n\");\n }\n }\n else\n {\n char* error = dlerror();\n fprintf(stderr, \"dlopen failed to open the libcoreclr.so with error %s\\n\", error);\n }\n\n return exitCode;\n}\n\nint main(const int argc, const char* argv[])\n{\n const char* clrFilesPath;\n const char* managedAssemblyPath;\n const char** managedAssemblyArgv;\n int managedAssemblyArgc;\n\n if (!ParseArguments(\n argc,\n argv,\n &clrFilesPath,\n &managedAssemblyPath,\n &managedAssemblyArgc,\n &managedAssemblyArgv))\n {\n \/\/ Invalid command line\n return -1;\n }\n\n \/\/ Check if the specified managed assembly file exists\n struct stat sb;\n if (stat(managedAssemblyPath, &sb) == -1)\n {\n perror(\"Managed assembly not found\");\n return -1;\n }\n\n \/\/ Verify that the managed assembly path points to a file\n if (!S_ISREG(sb.st_mode))\n {\n fprintf(stderr, \"The specified managed assembly is not a file\\n\");\n return -1;\n }\n \n \/\/ Convert the specified path to CLR files to an absolute path since the libcoreclr.so\n \/\/ requires it.\n std::string clrFilesAbsolutePath;\n std::string clrFilesRelativePath;\n\n if (clrFilesPath == nullptr)\n {\n \/\/ There was no CLR files path specified, use the folder of the corerun\n GetDirectory(argv[0], clrFilesRelativePath);\n clrFilesPath = clrFilesRelativePath.c_str();\n \n \/\/ TODO: consider using an env variable (if defined) as a fall-back.\n \/\/ The windows version of the corerun uses core_root env variable\n }\n\n if (!GetAbsolutePath(clrFilesPath, clrFilesAbsolutePath))\n {\n perror(\"Failed to convert CLR files path to absolute path\");\n return -1;\n }\n\n std::string managedAssemblyAbsolutePath;\n if (!GetAbsolutePath(managedAssemblyPath, managedAssemblyAbsolutePath))\n {\n perror(\"Failed to convert managed assembly path to absolute path\");\n return -1;\n }\n \n int exitCode = ExecuteManagedAssembly(\n argv[0],\n clrFilesAbsolutePath.c_str(),\n managedAssemblyAbsolutePath.c_str(),\n managedAssemblyArgc,\n managedAssemblyArgv);\n return exitCode;\n}\nFix std::out_of_range exception with short filenames (Linux)\/\/\n\/\/ Copyright (c) Microsoft. All rights reserved.\n\/\/ Licensed under the MIT license. See LICENSE file in the project root for full license information. \n\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ The name of the CoreCLR native runtime DLL.\nstatic const char * const coreClrDll = \"libcoreclr.so\";\n\n\/\/ Windows types used by the ExecuteAssembly function\ntypedef unsigned int DWORD;\ntypedef const char16_t* LPCWSTR;\ntypedef const char* LPCSTR;\ntypedef int32_t HRESULT;\n\n#define SUCCEEDED(Status) ((HRESULT)(Status) >= 0)\n\n\/\/ Prototype of the ExecuteAssembly function from the libcoreclr.do\ntypedef HRESULT (*ExecuteAssemblyFunction)(\n LPCSTR exePath,\n LPCSTR coreClrPath,\n LPCSTR appDomainFriendlyName,\n int propertyCount,\n LPCSTR* propertyKeys,\n LPCSTR* propertyValues,\n int argc,\n LPCSTR* argv,\n LPCSTR managedAssemblyPath,\n DWORD* exitCode);\n\n\/\/ Display the command line options\nvoid DisplayUsage()\n{\n fprintf(\n stderr,\n \"Usage: corerun [OPTIONS] assembly [ARGUMENTS]\\n\"\n \"Execute the specified managed assembly with the passed in arguments\\n\\n\"\n \"Options:\\n\"\n \"-c, --clr-path path to the libcoreclr.so and the managed CLR assemblies\\n\");\n}\n\n\/\/ Get absolute path from the specified path.\n\/\/ Return true in case of a success, false otherwise.\nbool GetAbsolutePath(const char* path, std::string& absolutePath)\n{\n bool result = false;\n \n char realPath[PATH_MAX];\n if (realpath(path, realPath) != nullptr && realPath[0] != '\\0')\n {\n absolutePath.assign(realPath);\n \/\/ The realpath should return canonicalized path without the trailing slash\n assert(absolutePath.back() != '\/');\n\n result = true;\n } \n \n return result;\n}\n\nvoid GetDirectory(const char* path, std::string& directory)\n{\n directory.assign(path);\n size_t lastSlash = directory.rfind('\/');\n directory.erase(lastSlash); \n}\n\n\/\/ Parse the command line arguments \nbool ParseArguments(\n const int argc,\n const char* argv[],\n const char** clrFilesPath,\n const char** managedAssemblyPath,\n int* managedAssemblyArgc,\n const char*** managedAssemblyArgv)\n{\n bool success = false;\n\n *clrFilesPath = nullptr;\n *managedAssemblyPath = nullptr;\n *managedAssemblyArgv = nullptr;\n *managedAssemblyArgc = 0;\n\n \/\/ The command line must contain at least the current exe name and the managed assembly path\n if (argc >= 2)\n {\n for (int i = 1; i < argc; i++)\n {\n \/\/ Check for an option\n if (argv[i][0] == '-')\n {\n \/\/ Path to the libcoreclr.so and the managed CLR assemblies\n if (strcmp(argv[i], \"-c\") == 0 || strcmp(argv[i], \"--clr-path\") == 0)\n {\n i++;\n if (i < argc)\n {\n *clrFilesPath = argv[i];\n }\n else\n {\n fprintf(stderr, \"Option %s: missing path\\n\", argv[i - 1]);\n break;\n }\n }\n else if (strcmp(argv[i], \"--help\") == 0)\n {\n DisplayUsage();\n break;\n }\n else\n {\n fprintf(stderr, \"Unknown option %s\\n\", argv[i]);\n break;\n }\n }\n else\n {\n \/\/ First argument that is not an option is the managed assembly to execute\n *managedAssemblyPath = argv[i];\n\n int managedArgvOffset = (i + 1);\n *managedAssemblyArgc = argc - managedArgvOffset;\n if (*managedAssemblyArgc != 0)\n {\n *managedAssemblyArgv = &argv[managedArgvOffset];\n }\n success = true;\n break;\n }\n }\n }\n else\n {\n DisplayUsage();\n }\n\n return success;\n}\n\n\/\/ Add all *.dll, *.ni.dll, *.exe, and *.ni.exe files from the specified directory\n\/\/ to the tpaList string;\nvoid AddFilesFromDirectoryToTpaList(const char* directory, std::string& tpaList)\n{\n const char * const tpaExtensions[] = {\n \".ni.dll\",\t\t\/\/ Probe for .ni.dll first so that it's preferred if ni and il coexist in the same dir\n \".dll\",\n \".ni.exe\",\n \".exe\",\n };\n \n DIR* dir = opendir(directory);\n if (dir == nullptr)\n {\n return;\n }\n\n std::set addedAssemblies;\n \n \/\/ Walk the directory for each extension separately so that we first get files with .ni.dll extension,\n \/\/ then files with .dll extension, etc.\n for (int extIndex = 0; extIndex < sizeof(tpaExtensions) \/ sizeof(tpaExtensions[0]); extIndex++)\n {\n const char* ext = tpaExtensions[extIndex];\n int extLength = strlen(ext);\n \n struct dirent* entry;\n \n \/\/ For all entries in the directory\n while ((entry = readdir(dir)) != nullptr)\n {\n \/\/ We are interested in files only\n if (entry->d_type != DT_REG)\n {\n continue;\n }\n\n std::string filename(entry->d_name);\n \n \/\/ Check if the extension matches the one we are looking for\n int extPos = filename.length() - extLength;\n if ((extPos <= 0) || (filename.compare(extPos, extLength, ext) != 0))\n {\n continue;\n }\n \n std::string filenameWithoutExt(filename.substr(0, extPos));\n\n \/\/ Make sure if we have an assembly with multiple extensions present,\n \/\/ we insert only one version of it.\n if (addedAssemblies.find(filenameWithoutExt) == addedAssemblies.end())\n {\n addedAssemblies.insert(filenameWithoutExt);\n\n tpaList.append(directory);\n tpaList.append(\"\/\");\n tpaList.append(filename);\n tpaList.append(\":\");\n }\n } \n \n \/\/ Rewind the directory stream to be able to iterate over it for the next extension\n rewinddir(dir);\n }\n \n closedir(dir); \n}\n\n\/\/\n\/\/ Execute the specified managed assembly. \n\/\/\n\/\/ Parameters:\n\/\/ currentExePath - Path of the current executable\n\/\/ clrFilesAbsolutePath - Absolute path of a folder where the libcoreclr.so and CLR managed assemblies are stored\n\/\/ managedAssemblyPath - Path to the managed assembly to execute\n\/\/ managedAssemblyArgc - Number of arguments passed to the executed assembly\n\/\/ managedAssemblyArgv - Array of arguments passed to the executed assembly\n\/\/\n\/\/ Returns:\n\/\/ ExitCode of the assembly\n\/\/\nint ExecuteManagedAssembly(\n const char* currentExeAbsolutePath,\n const char* clrFilesAbsolutePath,\n const char* managedAssemblyAbsolutePath,\n int managedAssemblyArgc,\n const char** managedAssemblyArgv)\n{\n \/\/ Indicates failure\n int exitCode = -1;\n \n std::string coreClrDllPath(clrFilesAbsolutePath);\n coreClrDllPath.append(\"\/\");\n coreClrDllPath.append(coreClrDll);\n \n if (coreClrDllPath.length() >= PATH_MAX)\n {\n fprintf(stderr, \"Absolute path to libcoreclr.so too long\\n\");\n return -1;\n }\n\n \/\/ Get just the path component of the managed assembly path\n std::string appPath;\n GetDirectory(managedAssemblyAbsolutePath, appPath);\n \n std::string nativeDllSearchDirs(appPath);\n nativeDllSearchDirs.append(\":\");\n nativeDllSearchDirs.append(clrFilesAbsolutePath);\n \n std::string tpaList;\n AddFilesFromDirectoryToTpaList(clrFilesAbsolutePath, tpaList);\n \n void* coreclrLib = dlopen(coreClrDllPath.c_str(), RTLD_NOW);\n if (coreclrLib != nullptr)\n {\n ExecuteAssemblyFunction executeAssembly = (ExecuteAssemblyFunction)dlsym(coreclrLib, \"ExecuteAssembly\");\n if (executeAssembly != nullptr)\n {\n \/\/ Allowed property names:\n \/\/ APPBASE\n \/\/ - The base path of the application from which the exe and other assemblies will be loaded\n \/\/\n \/\/ TRUSTED_PLATFORM_ASSEMBLIES\n \/\/ - The list of complete paths to each of the fully trusted assemblies\n \/\/\n \/\/ APP_PATHS\n \/\/ - The list of paths which will be probed by the assembly loader\n \/\/\n \/\/ APP_NI_PATHS\n \/\/ - The list of additional paths that the assembly loader will probe for ngen images\n \/\/\n \/\/ NATIVE_DLL_SEARCH_DIRECTORIES\n \/\/ - The list of paths that will be probed for native DLLs called by PInvoke\n \/\/\n const char *propertyKeys[] = {\n \"TRUSTED_PLATFORM_ASSEMBLIES\",\n \"APP_PATHS\",\n \"APP_NI_PATHS\",\n \"NATIVE_DLL_SEARCH_DIRECTORIES\"\n };\n const char *propertyValues[] = {\n \/\/ TRUSTED_PLATFORM_ASSEMBLIES\n tpaList.c_str(),\n \/\/ APP_PATHS\n appPath.c_str(),\n \/\/ APP_NI_PATHS\n appPath.c_str(),\n \/\/ NATIVE_DLL_SEARCH_DIRECTORIES\n nativeDllSearchDirs.c_str()\n };\n\n HRESULT st = executeAssembly(\n currentExeAbsolutePath,\n coreClrDllPath.c_str(),\n \"unixcorerun\",\n sizeof(propertyKeys) \/ sizeof(propertyKeys[0]),\n propertyKeys,\n propertyValues,\n managedAssemblyArgc,\n managedAssemblyArgv,\n managedAssemblyAbsolutePath,\n (DWORD*)&exitCode);\n\n if (!SUCCEEDED(st))\n {\n fprintf(stderr, \"ExecuteAssembly failed - status: 0x%08x\\n\", st);\n }\n }\n else\n {\n fprintf(stderr, \"Function ExecuteAssembly not found in the libcoreclr.so\\n\");\n }\n\n if (dlclose(coreclrLib) != 0)\n {\n fprintf(stderr, \"Warning - dlclose failed\\n\");\n }\n }\n else\n {\n char* error = dlerror();\n fprintf(stderr, \"dlopen failed to open the libcoreclr.so with error %s\\n\", error);\n }\n\n return exitCode;\n}\n\nint main(const int argc, const char* argv[])\n{\n const char* clrFilesPath;\n const char* managedAssemblyPath;\n const char** managedAssemblyArgv;\n int managedAssemblyArgc;\n\n if (!ParseArguments(\n argc,\n argv,\n &clrFilesPath,\n &managedAssemblyPath,\n &managedAssemblyArgc,\n &managedAssemblyArgv))\n {\n \/\/ Invalid command line\n return -1;\n }\n\n \/\/ Check if the specified managed assembly file exists\n struct stat sb;\n if (stat(managedAssemblyPath, &sb) == -1)\n {\n perror(\"Managed assembly not found\");\n return -1;\n }\n\n \/\/ Verify that the managed assembly path points to a file\n if (!S_ISREG(sb.st_mode))\n {\n fprintf(stderr, \"The specified managed assembly is not a file\\n\");\n return -1;\n }\n \n \/\/ Convert the specified path to CLR files to an absolute path since the libcoreclr.so\n \/\/ requires it.\n std::string clrFilesAbsolutePath;\n std::string clrFilesRelativePath;\n\n if (clrFilesPath == nullptr)\n {\n \/\/ There was no CLR files path specified, use the folder of the corerun\n GetDirectory(argv[0], clrFilesRelativePath);\n clrFilesPath = clrFilesRelativePath.c_str();\n \n \/\/ TODO: consider using an env variable (if defined) as a fall-back.\n \/\/ The windows version of the corerun uses core_root env variable\n }\n\n if (!GetAbsolutePath(clrFilesPath, clrFilesAbsolutePath))\n {\n perror(\"Failed to convert CLR files path to absolute path\");\n return -1;\n }\n\n std::string managedAssemblyAbsolutePath;\n if (!GetAbsolutePath(managedAssemblyPath, managedAssemblyAbsolutePath))\n {\n perror(\"Failed to convert managed assembly path to absolute path\");\n return -1;\n }\n \n int exitCode = ExecuteManagedAssembly(\n argv[0],\n clrFilesAbsolutePath.c_str(),\n managedAssemblyAbsolutePath.c_str(),\n managedAssemblyArgc,\n managedAssemblyArgv);\n return exitCode;\n}\n<|endoftext|>"} {"text":"\n#include \"simple_paint_file.h\"\n#include \"simple_paint_util.h\"\n\n#include \n#include \n#include \n\n\nvoid SimplePaintFile::Close()\n{\n if (filename) \n delete[] filename;\n\n if (image) \n imImageDestroy(image);\n}\n\nvoid SimplePaintFile::SetFilename(const char* new_filename)\n{\n if (filename != new_filename)\n {\n if (filename) \n delete[] filename;\n\n filename = str_duplicate(new_filename);\n }\n}\n\nimImage* SimplePaintFile::Read(const char* new_filename) const\n{\n int error;\n imImage* image = imFileImageLoadBitmap(new_filename, 0, &error);\n if (error)\n show_file_error(error);\n return image;\n}\n\nbool SimplePaintFile::Write(const char* new_filename) const\n{\n const char* format = imImageGetAttribString(image, \"FileFormat\");\n int error = imFileImageSave(new_filename, format, image);\n if (error)\n {\n show_file_error(error);\n return false;\n }\n return true;\n}\n\nvoid SimplePaintFile::SetFormat(const char* new_filename)\n{\n const char* ext = str_fileext(new_filename);\n const char* format = \"JPEG\";\n if (str_compare(ext, \"jpg\", 0) || str_compare(ext, \"jpeg\", 0))\n format = \"JPEG\";\n else if (str_compare(ext, \"bmp\", 0))\n format = \"BMP\";\n else if (str_compare(ext, \"png\", 0))\n format = \"PNG\";\n else if (str_compare(ext, \"tga\", 0))\n format = \"TGA\";\n else if (str_compare(ext, \"tif\", 0) || str_compare(ext, \"tiff\", 0))\n format = \"TIFF\";\n imImageSetAttribString(image, \"FileFormat\", format);\n}\n\nbool SimplePaintFile::SaveCheck()\n{\n if (dirty)\n {\n switch (IupAlarm(\"Warning\", \"File not saved! Save it now?\", \"Yes\", \"No\", \"Cancel\"))\n {\n case 1: \/* save the changes and continue *\/\n SaveFile();\n break;\n case 2: \/* ignore the changes and continue *\/\n break;\n case 3: \/* cancel *\/\n return false;\n }\n }\n return true;\n}\n\nvoid SimplePaintFile::SaveFile()\n{\n if (Write(filename))\n dirty = false;\n}\n\nbool SimplePaintFile::SaveAsFile(const char* new_filename)\n{\n SetFormat(new_filename);\n\n if (Write(new_filename))\n {\n SetFilename(new_filename);\n dirty = false;\n\n return true;\n }\n\n return false;\n}\n\nstatic void image_fill_white(imImage* image)\n{\n float color[3];\n\n color[0] = 255;\r\n color[1] = 255;\r\n color[2] = 255;\n\n imProcessRenderConstant(image, color);\n}\n\nbool SimplePaintFile::New(int width, int height)\n{\n imImage* new_image = imImageCreate(width, height, IM_RGB, IM_BYTE);\n if (!new_image)\n {\n show_file_error(IM_ERR_MEM);\n return false;\n }\n\n \/* new image default contents *\/\n image_fill_white(new_image);\n\n \/* default file format *\/\n imImageSetAttribString(new_image, \"FileFormat\", \"JPEG\");\n\n SetImage(new_image);\n\n \/* set properties *\/\n SetFilename(0);\n dirty = false;\n\n return true;\n}\n\nvoid SimplePaintFile::SetImage(imImage* new_image, bool release)\n{\n \/* remove previous one if any *\/\n if (release && image)\n imImageDestroy(image);\n\n \/* set properties (leave filename as it is) *\/\n dirty = true;\n image = new_image;\n}\n\nvoid SimplePaintFile::New(imImage* new_image)\n{\n \/* this tests are necessary only for open and paste *\/\n\n \/* we are going to support only RGB images with no alpha *\/\n imImageRemoveAlpha(new_image);\n if (new_image->color_space != IM_RGB)\n {\n imImage* rgb_image = imImageCreateBased(new_image, -1, -1, IM_RGB, -1);\n imConvertColorSpace(new_image, rgb_image);\n imImageDestroy(new_image);\n\n new_image = rgb_image;\n }\n\n \/* default file format *\/\n const char* format = imImageGetAttribString(new_image, \"FileFormat\");\n if (!format)\n imImageSetAttribString(new_image, \"FileFormat\", \"JPEG\");\n\n SetImage(new_image);\n}\n\nbool SimplePaintFile::Open(const char* new_filename)\n{\n imImage* new_image = Read(new_filename);\n if (new_image)\n {\n New(new_image);\n\n \/* set properties *\/\n dirty = false;\n SetFilename(new_filename);\n\n return true;\n }\n\n return false;\n}\n\n#include \"simple_paint_file.h\"\n#include \"simple_paint_util.h\"\n\n#include \n#include \n#include \n\n\nvoid SimplePaintFile::Close()\n{\n if (filename) \n delete[] filename;\n\n if (image) \n imImageDestroy(image);\n}\n\nvoid SimplePaintFile::SetFilename(const char* new_filename)\n{\n if (filename != new_filename)\n {\n if (filename) \n delete[] filename;\n\n filename = str_duplicate(new_filename);\n }\n}\n\nimImage* SimplePaintFile::Read(const char* new_filename) const\n{\n int error;\n imImage* image = imFileImageLoadBitmap(new_filename, 0, &error);\n if (error)\n show_file_error(error);\n return image;\n}\n\nbool SimplePaintFile::Write(const char* new_filename) const\n{\n const char* format = imImageGetAttribString(image, \"FileFormat\");\n int error = imFileImageSave(new_filename, format, image);\n if (error)\n {\n show_file_error(error);\n return false;\n }\n return true;\n}\n\nvoid SimplePaintFile::SetFormat(const char* new_filename)\n{\n const char* ext = str_fileext(new_filename);\n const char* format = \"JPEG\";\n if (str_compare(ext, \"jpg\", 0) || str_compare(ext, \"jpeg\", 0))\n format = \"JPEG\";\n else if (str_compare(ext, \"bmp\", 0))\n format = \"BMP\";\n else if (str_compare(ext, \"png\", 0))\n format = \"PNG\";\n else if (str_compare(ext, \"tga\", 0))\n format = \"TGA\";\n else if (str_compare(ext, \"tif\", 0) || str_compare(ext, \"tiff\", 0))\n format = \"TIFF\";\n imImageSetAttribString(image, \"FileFormat\", format);\n}\n\nbool SimplePaintFile::SaveCheck()\n{\n if (dirty)\n {\n switch (IupAlarm(\"Warning\", \"File not saved! Save it now?\", \"Yes\", \"No\", \"Cancel\"))\n {\n case 1: \/* save the changes and continue *\/\n SaveFile();\n break;\n case 2: \/* ignore the changes and continue *\/\n break;\n case 3: \/* cancel *\/\n return false;\n }\n }\n return true;\n}\n\nvoid SimplePaintFile::SaveFile()\n{\n if (Write(filename))\n dirty = false;\n}\n\nbool SimplePaintFile::SaveAsFile(const char* new_filename)\n{\n SetFormat(new_filename);\n\n if (Write(new_filename))\n {\n SetFilename(new_filename);\n dirty = false;\n\n return true;\n }\n\n return false;\n}\n\nstatic void image_fill_white(imImage* image)\n{\n float color[3];\n\n color[0] = 255;\n color[1] = 255;\n color[2] = 255;\n\n imProcessRenderConstant(image, color);\n}\n\nbool SimplePaintFile::New(int width, int height)\n{\n imImage* new_image = imImageCreate(width, height, IM_RGB, IM_BYTE);\n if (!new_image)\n {\n show_file_error(IM_ERR_MEM);\n return false;\n }\n\n \/* new image default contents *\/\n image_fill_white(new_image);\n\n \/* default file format *\/\n imImageSetAttribString(new_image, \"FileFormat\", \"JPEG\");\n\n SetImage(new_image);\n\n \/* set properties *\/\n SetFilename(0);\n dirty = false;\n\n return true;\n}\n\nvoid SimplePaintFile::SetImage(imImage* new_image, bool release)\n{\n \/* remove previous one if any *\/\n if (release && image)\n imImageDestroy(image);\n\n \/* set properties (leave filename as it is) *\/\n dirty = true;\n image = new_image;\n}\n\nvoid SimplePaintFile::New(imImage* new_image)\n{\n \/* this tests are necessary only for open and paste *\/\n\n \/* we are going to support only RGB images with no alpha *\/\n imImageRemoveAlpha(new_image);\n if (new_image->color_space != IM_RGB)\n {\n imImage* rgb_image = imImageCreateBased(new_image, -1, -1, IM_RGB, -1);\n imConvertColorSpace(new_image, rgb_image);\n imImageDestroy(new_image);\n\n new_image = rgb_image;\n }\n\n \/* default file format *\/\n const char* format = imImageGetAttribString(new_image, \"FileFormat\");\n if (!format)\n imImageSetAttribString(new_image, \"FileFormat\", \"JPEG\");\n\n SetImage(new_image);\n}\n\nbool SimplePaintFile::Open(const char* new_filename)\n{\n imImage* new_image = Read(new_filename);\n if (new_image)\n {\n New(new_image);\n\n \/* set properties *\/\n dirty = false;\n SetFilename(new_filename);\n\n return true;\n }\n\n return false;\n}\n<|endoftext|>"} {"text":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\/**\n * @author Intel, Evgueni Brevnov\n * @version $Revision: 1.1 $\n *\/\n\n#include \n#include \n\n#include \"open\/hythread.h\"\n#include \"open\/jthread.h\"\n#include \"open\/gc.h\"\n\n#include \"jni.h\"\n#include \"jni_direct.h\"\n#include \"environment.h\"\n#include \"classloader.h\"\n#include \"compile.h\"\n#include \"nogc.h\"\n#include \"jni_utils.h\"\n#include \"vm_stats.h\"\n#include \"thread_dump.h\"\n#include \"interpreter.h\"\n#include \"finalize.h\"\n\n#define LOG_DOMAIN \"vm.core.shutdown\"\n#include \"cxxlog.h\"\n\n#define PROCESS_EXCEPTION(messageId, message) \\\n{ \\\n LECHO(messageId, message << \"Internal error: \"); \\\n\\\n if (jni_env->ExceptionCheck()== JNI_TRUE) \\\n { \\\n jni_env->ExceptionDescribe(); \\\n jni_env->ExceptionClear(); \\\n } \\\n\\\n return JNI_ERR; \\\n} \\\n\n\/**\n * Calls java.lang.System.execShutdownSequence() method.\n *\n * @param jni_env JNI environment of the current thread\n *\/\nstatic jint exec_shutdown_sequence(JNIEnv * jni_env) {\n jclass system_class;\n jmethodID shutdown_method;\n\n assert(hythread_is_suspend_enabled());\n BEGIN_RAISE_AREA;\n\n system_class = jni_env->FindClass(\"java\/lang\/System\");\n if (jni_env->ExceptionCheck() == JNI_TRUE || system_class == NULL) {\n \/\/ This is debug message only. May appear when VM is already in shutdown stage.\n PROCESS_EXCEPTION(38, \"{0}can't find java.lang.System class.\");\n }\n\n shutdown_method = jni_env->GetStaticMethodID(system_class, \"execShutdownSequence\", \"()V\");\n if (jni_env->ExceptionCheck() == JNI_TRUE || shutdown_method == NULL) {\n PROCESS_EXCEPTION(39, \"{0}can't find java.lang.System.execShutdownSequence() method.\");\n }\n\n jni_env->CallStaticVoidMethod(system_class, shutdown_method);\n\n if (jni_env->ExceptionCheck() == JNI_TRUE) {\n PROCESS_EXCEPTION(40, \"{0}java.lang.System.execShutdownSequence() method completed with an exception.\");\n }\n\n END_RAISE_AREA;\n return JNI_OK;\n}\n\nstatic void vm_shutdown_callback() {\n hythread_suspend_enable();\n set_unwindable(false);\n\n vm_thread_t vm_thread = jthread_self_vm_thread();\n assert(vm_thread);\n\n jobject java_thread = vm_thread->java_thread;\n assert(java_thread);\n\n IDATA UNUSED status = jthread_detach(java_thread);\n assert(status == TM_ERROR_NONE);\n\n hythread_exit(NULL);\n}\n\nstatic void vm_thread_cancel(vm_thread_t thread) {\n assert(thread);\n\n \/\/ grab hythread global lock\n hythread_global_lock();\n\n IDATA UNUSED status = jthread_vm_detach(thread);\n assert(status == TM_ERROR_NONE);\n\n hythread_cancel((hythread_t)thread);\n\n \/\/ release hythread global lock\n hythread_global_unlock();\n}\n\n\/**\n * Stops running java threads by throwing an exception\n * up to the first native frame.\n *\n * @param[in] vm_env a global VM environment\n *\/\nstatic void vm_shutdown_stop_java_threads(Global_Env * vm_env) {\n hythread_t self;\n hythread_t * running_threads;\n hythread_t native_thread;\n hythread_iterator_t it;\n VM_thread *vm_thread;\n\n self = hythread_self();\n\n \/\/ Collect running java threads.\n \/\/ Set callbacks to let threads exit\n TRACE2(\"shutdown\", \"stopping threads, self \" << self);\n it = hythread_iterator_create(NULL);\n running_threads = (hythread_t *)apr_palloc(vm_env->mem_pool,\n hythread_iterator_size(it) * sizeof(hythread_t));\n int size = 0;\n while(native_thread = hythread_iterator_next(&it)) {\n vm_thread = jthread_get_vm_thread(native_thread);\n if (native_thread != self && vm_thread != NULL) {\n hythread_set_safepoint_callback(native_thread,\n vm_shutdown_callback);\n running_threads[size] = native_thread;\n ++size;\n }\n }\n hythread_iterator_release(&it);\n\n TRACE2(\"shutdown\", \"joining threads\");\n \/\/ join running threads\n \/\/ blocked and waiting threads won't be joined\n for (int i = 0; i < size; i++) {\n hythread_join_timed(running_threads[i], 100\/size + 1, 0);\n }\n\n TRACE2(\"shutdown\", \"cancelling threads\");\n \/\/ forcedly kill remaining threads\n \/\/ There is a small chance that some of these threads are not in the point\n \/\/ safe for killing, e.g. in malloc()\n it = hythread_iterator_create(NULL);\n while(native_thread = hythread_iterator_next(&it)) {\n vm_thread = jthread_get_vm_thread(native_thread);\n \/\/ we should not cancel self and\n \/\/ non-java threads (i.e. vm_thread == NULL)\n if (native_thread != self && vm_thread != NULL) {\n vm_thread_cancel(vm_thread);\n TRACE2(\"shutdown\", \"cancelling \" << native_thread);\n STD_FREE(vm_thread);\n }\n }\n hythread_iterator_release(&it);\n\n TRACE2(\"shutdown\", \"shutting down threads complete\");\n}\n\n\/**\n * Waits until all non-daemon threads finish their execution,\n * initiates VM shutdown sequence and stops running threads if any.\n *\n * @param[in] java_vm JVM that should be destroyed\n * @param[in] java_thread current java thread\n *\/\njint vm_destroy(JavaVM_Internal * java_vm, jthread java_thread)\n{\n IDATA status;\n JNIEnv * jni_env;\n jobject uncaught_exception;\n\n assert(hythread_is_suspend_enabled());\n\n jni_env = jthread_get_JNI_env(java_thread);\n\n \/\/ Wait until all non-daemon threads finish their execution.\n status = jthread_wait_for_all_nondaemon_threads();\n if (status != TM_ERROR_NONE) {\n TRACE(\"Failed to wait for all non-daemon threads completion.\");\n return JNI_ERR;\n }\n\n \/\/ Print out gathered data.\n#ifdef VM_STATS\n VM_Statistics::get_vm_stats().print();\n#endif\n\n \/\/ Remember thread's uncaught exception if any.\n uncaught_exception = jni_env->ExceptionOccurred();\n jni_env->ExceptionClear();\n\n \/\/ Execute pending shutdown hooks & finalizers\n status = exec_shutdown_sequence(jni_env);\n if (status != JNI_OK) return (jint)status;\n \n if(get_native_finalizer_thread_flag())\n wait_native_fin_threads_detached();\n if(get_native_ref_enqueue_thread_flag())\n wait_native_ref_thread_detached();\n\n \/\/ Raise uncaught exception to current thread.\n \/\/ It will be properly processed in jthread_java_detach().\n if (uncaught_exception) {\n exn_raise_object(uncaught_exception);\n }\n\n \/\/ Send VM_Death event and switch to DEAD phase.\n \/\/ This should be the last event sent by VM.\n \/\/ This event should be sent before Agent_OnUnload called.\n jvmti_send_vm_death_event();\n\n \/\/ prepare thread manager to shutdown\n hythread_shutdowning();\n\n \/\/ Stop all (except current) java threads\n \/\/ before destroying VM-wide data.\n vm_shutdown_stop_java_threads(java_vm->vm_env);\n\n \/\/ TODO: ups we don't stop native threads as well :-((\n \/\/ We are lucky! Currently, there are no such threads.\n\n \/\/ Detach current main thread.\n status = jthread_detach(java_thread);\n\n \/\/ check detach status\n if (status != TM_ERROR_NONE)\n return JNI_ERR;\n\n \/\/ Shutdown signals\n extern void shutdown_signals();\n shutdown_signals();\n\n \/\/ Call Agent_OnUnload() for agents and unload agents.\n java_vm->vm_env->TI->Shutdown(java_vm);\n\n \/\/ Block thread creation.\n \/\/ TODO: investigate how to achieve that with ThreadManager\n\n \/\/ Starting this moment any exception occurred in java thread will cause\n \/\/ entire java stack unwinding to the most recent native frame.\n \/\/ JNI is not available as well.\n assert(java_vm->vm_env->vm_state == Global_Env::VM_RUNNING);\n java_vm->vm_env->vm_state = Global_Env::VM_SHUTDOWNING;\n\n TRACE2(\"shutdown\", \"vm_destroy complete\");\n return JNI_OK;\n}\n\nstatic IDATA vm_interrupt_process(void * data) {\n vm_thread_t * threadBuf;\n int i;\n\n threadBuf = (vm_thread_t *)data;\n i = 0;\n \/\/ Join all threads.\n while (threadBuf[i] != NULL) {\n hythread_join((hythread_t)threadBuf[i]);\n STD_FREE(threadBuf[i]);\n i++;\n }\n\n STD_FREE(threadBuf);\n\n \/\/ Return 130 to be compatible with RI.\n exit(130);\n}\n\n\/**\n * Initiates VM shutdown sequence.\n *\/\nstatic IDATA vm_interrupt_entry_point(void * data) {\n JNIEnv * jni_env;\n JavaVMAttachArgs args;\n JavaVM * java_vm;\n jint status;\n\n java_vm = (JavaVM *)data;\n args.version = JNI_VERSION_1_2;\n args.group = NULL;\n args.name = \"InterruptionHandler\";\n\n status = AttachCurrentThread(java_vm, (void **)&jni_env, &args);\n if (status == JNI_OK) {\n exec_shutdown_sequence(jni_env);\n DetachCurrentThread(java_vm);\n }\n return status;\n}\n\n\/**\n * Release allocated resourses.\n *\/\nstatic IDATA vm_dump_process(void * data) {\n vm_thread_t * threadBuf;\n int i;\n\n threadBuf = (vm_thread_t *)data;\n i = 0;\n \/\/ Join all threads and release allocated resources.\n while (threadBuf[i] != NULL) {\n hythread_join((hythread_t)threadBuf[i]);\n STD_FREE(threadBuf[i]);\n i++;\n }\n STD_FREE(threadBuf);\n\n return TM_ERROR_NONE;\n}\n\n\/**\n * Dumps all java stacks.\n *\/\nstatic IDATA vm_dump_entry_point(void * data) {\n JNIEnv * jni_env;\n JavaVMAttachArgs args;\n JavaVM * java_vm;\n jint status;\n\n java_vm = (JavaVM *)data;\n args.version = JNI_VERSION_1_2;\n args.group = NULL;\n args.name = \"DumpHandler\";\n\n status = AttachCurrentThread(java_vm, (void **)&jni_env, &args);\n if (status == JNI_OK) {\n \/\/ TODO: specify particular VM to notify.\n jvmti_notify_data_dump_request();\n st_print_all(stdout);\n DetachCurrentThread(java_vm);\n }\n return status;\n}\n\n\/**\n * Current process received an interruption signal (Ctrl+C pressed).\n * Shutdown all running VMs and terminate the process.\n *\/\nvoid vm_interrupt_handler(int UNREF x) {\n JavaVM ** vmBuf;\n vm_thread_t * threadBuf;\n int nVMs;\n IDATA status;\n\n status = JNI_GetCreatedJavaVMs(NULL, 0, &nVMs);\n assert(nVMs <= 1);\n if (status != JNI_OK)\n return;\n\n vmBuf = (JavaVM **) STD_MALLOC(nVMs * sizeof(JavaVM *));\n status = JNI_GetCreatedJavaVMs(vmBuf, nVMs, &nVMs);\n assert(nVMs <= 1);\n if (status != JNI_OK)\n goto cleanup;\n\n threadBuf = (vm_thread_t*) STD_MALLOC((nVMs + 1) * sizeof(vm_thread_t));\n assert(threadBuf);\n\n \/\/ Create a new thread for each VM to avoid scalability and deadlock problems.\n for (int i = 0; i < nVMs; i++) {\n threadBuf[i] = jthread_allocate_thread();\n status = hythread_create_ex((hythread_t)threadBuf[i], NULL, 0, 0, NULL,\n vm_interrupt_entry_point, (void *)vmBuf[i]);\n assert(status == TM_ERROR_NONE);\n }\n\n \/\/ spawn a new thread which will terminate the process.\n status = hythread_create(NULL, 0, 0, 0,\n vm_interrupt_process, (void *)threadBuf);\n assert(status == TM_ERROR_NONE);\n\n \/\/ set a NULL terminator\n threadBuf[nVMs] = NULL;\n\ncleanup:\n STD_FREE(vmBuf);\n}\n\n\/**\n * Current process received an ??? signal (Ctrl+Break pressed).\n * Prints java stack traces for each VM running in the current process.\n *\/\nvoid vm_dump_handler(int UNREF x) {\n int nVMs;\n vm_thread_t *threadBuf;\n\n jint status = JNI_GetCreatedJavaVMs(NULL, 0, &nVMs);\n assert(nVMs <= 1);\n if (status != JNI_OK)\n return;\n\n JavaVM ** vmBuf = (JavaVM **) STD_MALLOC(nVMs * sizeof(JavaVM *));\n status = JNI_GetCreatedJavaVMs(vmBuf, nVMs, &nVMs);\n assert(nVMs <= 1);\n if (status != JNI_OK) {\n goto cleanup;\n }\n\n threadBuf =\n (vm_thread_t*)STD_MALLOC((nVMs + 1) * sizeof(vm_thread_t));\n assert(threadBuf);\n\n \/\/ Create a new thread for each VM to avoid scalability and deadlock problems.\n IDATA UNUSED hy_status;\n for (int i = 0; i < nVMs; i++) {\n threadBuf[i] = jthread_allocate_thread();\n hy_status = hythread_create_ex((hythread_t)threadBuf[i],\n NULL, 0, 0, NULL, vm_dump_entry_point, (void *)vmBuf[i]);\n assert(hy_status == TM_ERROR_NONE);\n }\n\n \/\/ spawn a new thread which will release resources.\n hy_status = hythread_create(NULL, 0, 0, 0,\n vm_dump_process, (void *)threadBuf);\n assert(hy_status == TM_ERROR_NONE);\n\ncleanup:\n STD_FREE(vmBuf);\n}\nApplied VM side fix for HARMONY-5019 [jdktools][jpda] Agent has to ensure that all of its threads are terminated when Agent_OnUnload exits\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\/**\n * @author Intel, Evgueni Brevnov\n * @version $Revision: 1.1 $\n *\/\n\n#include \n#include \n\n#include \"open\/hythread.h\"\n#include \"open\/jthread.h\"\n#include \"open\/gc.h\"\n\n#include \"jni.h\"\n#include \"jni_direct.h\"\n#include \"environment.h\"\n#include \"classloader.h\"\n#include \"compile.h\"\n#include \"nogc.h\"\n#include \"jni_utils.h\"\n#include \"vm_stats.h\"\n#include \"thread_dump.h\"\n#include \"interpreter.h\"\n#include \"finalize.h\"\n\n#define LOG_DOMAIN \"vm.core.shutdown\"\n#include \"cxxlog.h\"\n\n#define PROCESS_EXCEPTION(messageId, message) \\\n{ \\\n LECHO(messageId, message << \"Internal error: \"); \\\n\\\n if (jni_env->ExceptionCheck()== JNI_TRUE) \\\n { \\\n jni_env->ExceptionDescribe(); \\\n jni_env->ExceptionClear(); \\\n } \\\n\\\n return JNI_ERR; \\\n} \\\n\n\/**\n * Calls java.lang.System.execShutdownSequence() method.\n *\n * @param jni_env JNI environment of the current thread\n *\/\nstatic jint exec_shutdown_sequence(JNIEnv * jni_env) {\n jclass system_class;\n jmethodID shutdown_method;\n\n assert(hythread_is_suspend_enabled());\n BEGIN_RAISE_AREA;\n\n system_class = jni_env->FindClass(\"java\/lang\/System\");\n if (jni_env->ExceptionCheck() == JNI_TRUE || system_class == NULL) {\n \/\/ This is debug message only. May appear when VM is already in shutdown stage.\n PROCESS_EXCEPTION(38, \"{0}can't find java.lang.System class.\");\n }\n\n shutdown_method = jni_env->GetStaticMethodID(system_class, \"execShutdownSequence\", \"()V\");\n if (jni_env->ExceptionCheck() == JNI_TRUE || shutdown_method == NULL) {\n PROCESS_EXCEPTION(39, \"{0}can't find java.lang.System.execShutdownSequence() method.\");\n }\n\n jni_env->CallStaticVoidMethod(system_class, shutdown_method);\n\n if (jni_env->ExceptionCheck() == JNI_TRUE) {\n PROCESS_EXCEPTION(40, \"{0}java.lang.System.execShutdownSequence() method completed with an exception.\");\n }\n\n END_RAISE_AREA;\n return JNI_OK;\n}\n\nstatic void vm_shutdown_callback() {\n hythread_suspend_enable();\n set_unwindable(false);\n\n vm_thread_t vm_thread = jthread_self_vm_thread();\n assert(vm_thread);\n\n jobject java_thread = vm_thread->java_thread;\n assert(java_thread);\n\n IDATA UNUSED status = jthread_detach(java_thread);\n assert(status == TM_ERROR_NONE);\n\n hythread_exit(NULL);\n}\n\nstatic void vm_thread_cancel(vm_thread_t thread) {\n assert(thread);\n\n \/\/ grab hythread global lock\n hythread_global_lock();\n\n IDATA UNUSED status = jthread_vm_detach(thread);\n assert(status == TM_ERROR_NONE);\n\n hythread_cancel((hythread_t)thread);\n\n \/\/ release hythread global lock\n hythread_global_unlock();\n}\n\n\/**\n * Stops running java threads by throwing an exception\n * up to the first native frame.\n *\n * @param[in] vm_env a global VM environment\n *\/\nstatic void vm_shutdown_stop_java_threads(Global_Env * vm_env) {\n hythread_t self;\n hythread_t * running_threads;\n hythread_t native_thread;\n hythread_iterator_t it;\n VM_thread *vm_thread;\n\n self = hythread_self();\n\n \/\/ Collect running java threads.\n \/\/ Set callbacks to let threads exit\n TRACE2(\"shutdown\", \"stopping threads, self \" << self);\n it = hythread_iterator_create(NULL);\n running_threads = (hythread_t *)apr_palloc(vm_env->mem_pool,\n hythread_iterator_size(it) * sizeof(hythread_t));\n int size = 0;\n while(native_thread = hythread_iterator_next(&it)) {\n vm_thread = jthread_get_vm_thread(native_thread);\n if (native_thread != self && vm_thread != NULL) {\n hythread_set_safepoint_callback(native_thread,\n vm_shutdown_callback);\n running_threads[size] = native_thread;\n ++size;\n }\n }\n hythread_iterator_release(&it);\n\n TRACE2(\"shutdown\", \"joining threads\");\n \/\/ join running threads\n \/\/ blocked and waiting threads won't be joined\n for (int i = 0; i < size; i++) {\n hythread_join_timed(running_threads[i], 100\/size + 1, 0);\n }\n\n TRACE2(\"shutdown\", \"cancelling threads\");\n \/\/ forcedly kill remaining threads\n \/\/ There is a small chance that some of these threads are not in the point\n \/\/ safe for killing, e.g. in malloc()\n it = hythread_iterator_create(NULL);\n while(native_thread = hythread_iterator_next(&it)) {\n vm_thread = jthread_get_vm_thread(native_thread);\n \/\/ we should not cancel self and\n \/\/ non-java threads (i.e. vm_thread == NULL)\n if (native_thread != self && vm_thread != NULL) {\n vm_thread_cancel(vm_thread);\n TRACE2(\"shutdown\", \"cancelling \" << native_thread);\n STD_FREE(vm_thread);\n }\n }\n hythread_iterator_release(&it);\n\n TRACE2(\"shutdown\", \"shutting down threads complete\");\n}\n\n\/**\n * Waits until all non-daemon threads finish their execution,\n * initiates VM shutdown sequence and stops running threads if any.\n *\n * @param[in] java_vm JVM that should be destroyed\n * @param[in] java_thread current java thread\n *\/\njint vm_destroy(JavaVM_Internal * java_vm, jthread java_thread)\n{\n IDATA status;\n JNIEnv * jni_env;\n jobject uncaught_exception;\n\n assert(hythread_is_suspend_enabled());\n\n jni_env = jthread_get_JNI_env(java_thread);\n\n \/\/ Wait until all non-daemon threads finish their execution.\n status = jthread_wait_for_all_nondaemon_threads();\n if (status != TM_ERROR_NONE) {\n TRACE(\"Failed to wait for all non-daemon threads completion.\");\n return JNI_ERR;\n }\n\n \/\/ Print out gathered data.\n#ifdef VM_STATS\n VM_Statistics::get_vm_stats().print();\n#endif\n\n \/\/ Remember thread's uncaught exception if any.\n uncaught_exception = jni_env->ExceptionOccurred();\n jni_env->ExceptionClear();\n\n \/\/ Execute pending shutdown hooks & finalizers\n status = exec_shutdown_sequence(jni_env);\n if (status != JNI_OK) return (jint)status;\n \n if(get_native_finalizer_thread_flag())\n wait_native_fin_threads_detached();\n if(get_native_ref_enqueue_thread_flag())\n wait_native_ref_thread_detached();\n\n \/\/ Raise uncaught exception to current thread.\n \/\/ It will be properly processed in jthread_java_detach().\n if (uncaught_exception) {\n exn_raise_object(uncaught_exception);\n }\n\n \/\/ Send VM_Death event and switch to DEAD phase.\n \/\/ This should be the last event sent by VM.\n \/\/ This event should be sent before Agent_OnUnload called.\n jvmti_send_vm_death_event();\n\n \/\/ prepare thread manager to shutdown\n hythread_shutdowning();\n\n \/\/ Call Agent_OnUnload() for agents and unload agents.\n \/\/ Gregory -\n \/\/ We cannot call this function after vm_shutdown_stop_java_threads!!!\n \/\/ In this case agent's thread won't be shutdown properly, and the\n \/\/ code of agent's thread will run in unmapped address space\n \/\/ of unloaded agent's library. This is bad and will almost certainly crash.\n java_vm->vm_env->TI->Shutdown(java_vm);\n\n \/\/ Stop all (except current) java threads\n \/\/ before destroying VM-wide data.\n vm_shutdown_stop_java_threads(java_vm->vm_env);\n\n \/\/ TODO: ups we don't stop native threads as well :-((\n \/\/ We are lucky! Currently, there are no such threads.\n\n \/\/ Detach current main thread.\n status = jthread_detach(java_thread);\n\n \/\/ check detach status\n if (status != TM_ERROR_NONE)\n return JNI_ERR;\n\n \/\/ Shutdown signals\n extern void shutdown_signals();\n shutdown_signals();\n\n \/\/ Block thread creation.\n \/\/ TODO: investigate how to achieve that with ThreadManager\n\n \/\/ Starting this moment any exception occurred in java thread will cause\n \/\/ entire java stack unwinding to the most recent native frame.\n \/\/ JNI is not available as well.\n assert(java_vm->vm_env->vm_state == Global_Env::VM_RUNNING);\n java_vm->vm_env->vm_state = Global_Env::VM_SHUTDOWNING;\n\n TRACE2(\"shutdown\", \"vm_destroy complete\");\n return JNI_OK;\n}\n\nstatic IDATA vm_interrupt_process(void * data) {\n vm_thread_t * threadBuf;\n int i;\n\n threadBuf = (vm_thread_t *)data;\n i = 0;\n \/\/ Join all threads.\n while (threadBuf[i] != NULL) {\n hythread_join((hythread_t)threadBuf[i]);\n STD_FREE(threadBuf[i]);\n i++;\n }\n\n STD_FREE(threadBuf);\n\n \/\/ Return 130 to be compatible with RI.\n exit(130);\n}\n\n\/**\n * Initiates VM shutdown sequence.\n *\/\nstatic IDATA vm_interrupt_entry_point(void * data) {\n JNIEnv * jni_env;\n JavaVMAttachArgs args;\n JavaVM * java_vm;\n jint status;\n\n java_vm = (JavaVM *)data;\n args.version = JNI_VERSION_1_2;\n args.group = NULL;\n args.name = \"InterruptionHandler\";\n\n status = AttachCurrentThread(java_vm, (void **)&jni_env, &args);\n if (status == JNI_OK) {\n exec_shutdown_sequence(jni_env);\n DetachCurrentThread(java_vm);\n }\n return status;\n}\n\n\/**\n * Release allocated resourses.\n *\/\nstatic IDATA vm_dump_process(void * data) {\n vm_thread_t * threadBuf;\n int i;\n\n threadBuf = (vm_thread_t *)data;\n i = 0;\n \/\/ Join all threads and release allocated resources.\n while (threadBuf[i] != NULL) {\n hythread_join((hythread_t)threadBuf[i]);\n STD_FREE(threadBuf[i]);\n i++;\n }\n STD_FREE(threadBuf);\n\n return TM_ERROR_NONE;\n}\n\n\/**\n * Dumps all java stacks.\n *\/\nstatic IDATA vm_dump_entry_point(void * data) {\n JNIEnv * jni_env;\n JavaVMAttachArgs args;\n JavaVM * java_vm;\n jint status;\n\n java_vm = (JavaVM *)data;\n args.version = JNI_VERSION_1_2;\n args.group = NULL;\n args.name = \"DumpHandler\";\n\n status = AttachCurrentThread(java_vm, (void **)&jni_env, &args);\n if (status == JNI_OK) {\n \/\/ TODO: specify particular VM to notify.\n jvmti_notify_data_dump_request();\n st_print_all(stdout);\n DetachCurrentThread(java_vm);\n }\n return status;\n}\n\n\/**\n * Current process received an interruption signal (Ctrl+C pressed).\n * Shutdown all running VMs and terminate the process.\n *\/\nvoid vm_interrupt_handler(int UNREF x) {\n JavaVM ** vmBuf;\n vm_thread_t * threadBuf;\n int nVMs;\n IDATA status;\n\n status = JNI_GetCreatedJavaVMs(NULL, 0, &nVMs);\n assert(nVMs <= 1);\n if (status != JNI_OK)\n return;\n\n vmBuf = (JavaVM **) STD_MALLOC(nVMs * sizeof(JavaVM *));\n status = JNI_GetCreatedJavaVMs(vmBuf, nVMs, &nVMs);\n assert(nVMs <= 1);\n if (status != JNI_OK)\n goto cleanup;\n\n threadBuf = (vm_thread_t*) STD_MALLOC((nVMs + 1) * sizeof(vm_thread_t));\n assert(threadBuf);\n\n \/\/ Create a new thread for each VM to avoid scalability and deadlock problems.\n for (int i = 0; i < nVMs; i++) {\n threadBuf[i] = jthread_allocate_thread();\n status = hythread_create_ex((hythread_t)threadBuf[i], NULL, 0, 0, NULL,\n vm_interrupt_entry_point, (void *)vmBuf[i]);\n assert(status == TM_ERROR_NONE);\n }\n\n \/\/ spawn a new thread which will terminate the process.\n status = hythread_create(NULL, 0, 0, 0,\n vm_interrupt_process, (void *)threadBuf);\n assert(status == TM_ERROR_NONE);\n\n \/\/ set a NULL terminator\n threadBuf[nVMs] = NULL;\n\ncleanup:\n STD_FREE(vmBuf);\n}\n\n\/**\n * Current process received an ??? signal (Ctrl+Break pressed).\n * Prints java stack traces for each VM running in the current process.\n *\/\nvoid vm_dump_handler(int UNREF x) {\n int nVMs;\n vm_thread_t *threadBuf;\n\n jint status = JNI_GetCreatedJavaVMs(NULL, 0, &nVMs);\n assert(nVMs <= 1);\n if (status != JNI_OK)\n return;\n\n JavaVM ** vmBuf = (JavaVM **) STD_MALLOC(nVMs * sizeof(JavaVM *));\n status = JNI_GetCreatedJavaVMs(vmBuf, nVMs, &nVMs);\n assert(nVMs <= 1);\n if (status != JNI_OK) {\n goto cleanup;\n }\n\n threadBuf =\n (vm_thread_t*)STD_MALLOC((nVMs + 1) * sizeof(vm_thread_t));\n assert(threadBuf);\n\n \/\/ Create a new thread for each VM to avoid scalability and deadlock problems.\n IDATA UNUSED hy_status;\n for (int i = 0; i < nVMs; i++) {\n threadBuf[i] = jthread_allocate_thread();\n hy_status = hythread_create_ex((hythread_t)threadBuf[i],\n NULL, 0, 0, NULL, vm_dump_entry_point, (void *)vmBuf[i]);\n assert(hy_status == TM_ERROR_NONE);\n }\n\n \/\/ spawn a new thread which will release resources.\n hy_status = hythread_create(NULL, 0, 0, 0,\n vm_dump_process, (void *)threadBuf);\n assert(hy_status == TM_ERROR_NONE);\n\ncleanup:\n STD_FREE(vmBuf);\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n *\n * Copyright (c) 2019 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file PreFlightCheck.cpp\n *\/\n\n#include \"PreFlightCheck.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace time_literals;\n\nstatic constexpr unsigned max_mandatory_gyro_count = 1;\nstatic constexpr unsigned max_optional_gyro_count = 3;\nstatic constexpr unsigned max_mandatory_accel_count = 1;\nstatic constexpr unsigned max_optional_accel_count = 3;\nstatic constexpr unsigned max_mandatory_mag_count = 1;\nstatic constexpr unsigned max_optional_mag_count = 4;\nstatic constexpr unsigned max_mandatory_baro_count = 1;\nstatic constexpr unsigned max_optional_baro_count = 1;\n\nbool PreFlightCheck::preflightCheck(orb_advert_t *mavlink_log_pub, vehicle_status_s &status,\n\t\t\t\t vehicle_status_flags_s &status_flags, const bool checkGNSS, bool reportFailures, const bool prearm,\n\t\t\t\t const hrt_abstime &time_since_boot)\n{\n\tif (time_since_boot < 2_s) {\n\t\t\/\/ the airspeed driver filter doesn't deliver the actual value yet\n\t\treportFailures = false;\n\t}\n\n\tconst bool hil_enabled = (status.hil_state == vehicle_status_s::HIL_STATE_ON);\n\n\tbool checkSensors = !hil_enabled;\n\tconst bool checkRC = (status.rc_input_mode == vehicle_status_s::RC_IN_MODE_DEFAULT);\n\tconst bool checkDynamic = !hil_enabled;\n\tconst bool checkPower = (status_flags.condition_power_input_valid && !status_flags.circuit_breaker_engaged_power_check);\n\tconst bool checkFailureDetector = true;\n\n\tbool checkAirspeed = false;\n\n\t\/* Perform airspeed check only if circuit breaker is not\n\t * engaged and it's not a rotary wing *\/\n\tif (!status_flags.circuit_breaker_engaged_airspd_check &&\n\t (status.vehicle_type == vehicle_status_s::VEHICLE_TYPE_FIXED_WING || status.is_vtol)) {\n\t\tcheckAirspeed = true;\n\t}\n\n\treportFailures = (reportFailures && status_flags.condition_system_hotplug_timeout\n\t\t\t && !status_flags.condition_calibration_enabled);\n\n\tbool failed = false;\n\n\t\/* ---- MAG ---- *\/\n\tif (checkSensors) {\n\t\tbool prime_found = false;\n\n\t\tint32_t prime_id = -1;\n\t\tparam_get(param_find(\"CAL_MAG_PRIME\"), &prime_id);\n\n\t\tint32_t sys_has_mag = 1;\n\t\tparam_get(param_find(\"SYS_HAS_MAG\"), &sys_has_mag);\n\n\t\tbool mag_fail_reported = false;\n\n\t\t\/* check all sensors individually, but fail only for mandatory ones *\/\n\t\tfor (unsigned i = 0; i < max_optional_mag_count; i++) {\n\t\t\tconst bool required = (i < max_mandatory_mag_count) && (sys_has_mag == 1);\n\t\t\tconst bool report_fail = (reportFailures && !failed && !mag_fail_reported);\n\n\t\t\tint32_t device_id = -1;\n\n\t\t\tif (magnometerCheck(mavlink_log_pub, status, i, !required, device_id, report_fail)) {\n\n\t\t\t\tif ((prime_id > 0) && (device_id == prime_id)) {\n\t\t\t\t\tprime_found = true;\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tif (required) {\n\t\t\t\t\tfailed = true;\n\t\t\t\t\tmag_fail_reported = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (sys_has_mag == 1) {\n\t\t\t\/* check if the primary device is present *\/\n\t\t\tif (!prime_found) {\n\t\t\t\tif (reportFailures && !failed) {\n\t\t\t\t\tmavlink_log_critical(mavlink_log_pub, \"Primary compass not found\");\n\t\t\t\t}\n\n\t\t\t\tset_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_MAG, false, true, false, status);\n\t\t\t\tfailed = true;\n\t\t\t}\n\n\t\t\t\/* mag consistency checks (need to be performed after the individual checks) *\/\n\t\t\tif (!magConsistencyCheck(mavlink_log_pub, status, (reportFailures && !failed))) {\n\t\t\t\tfailed = true;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/* ---- ACCEL ---- *\/\n\tif (checkSensors) {\n\t\tbool prime_found = false;\n\t\tint32_t prime_id = -1;\n\t\tparam_get(param_find(\"CAL_ACC_PRIME\"), &prime_id);\n\n\t\tbool accel_fail_reported = false;\n\n\t\t\/* check all sensors individually, but fail only for mandatory ones *\/\n\t\tfor (unsigned i = 0; i < max_optional_accel_count; i++) {\n\t\t\tconst bool required = (i < max_mandatory_accel_count);\n\t\t\tconst bool report_fail = (reportFailures && !failed && !accel_fail_reported);\n\n\t\t\tint32_t device_id = -1;\n\n\t\t\tif (accelerometerCheck(mavlink_log_pub, status, i, !required, checkDynamic, device_id, report_fail)) {\n\n\t\t\t\tif ((prime_id > 0) && (device_id == prime_id)) {\n\t\t\t\t\tprime_found = true;\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tif (required) {\n\t\t\t\t\tfailed = true;\n\t\t\t\t\taccel_fail_reported = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/* check if the primary device is present *\/\n\t\tif (!prime_found) {\n\t\t\tif (reportFailures && !failed) {\n\t\t\t\tmavlink_log_critical(mavlink_log_pub, \"Primary accelerometer not found\");\n\t\t\t}\n\n\t\t\tset_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_ACC, false, true, false, status);\n\t\t\tfailed = true;\n\t\t}\n\t}\n\n\t\/* ---- GYRO ---- *\/\n\tif (checkSensors) {\n\t\tbool prime_found = false;\n\t\tint32_t prime_id = -1;\n\t\tparam_get(param_find(\"CAL_GYRO_PRIME\"), &prime_id);\n\n\t\tbool gyro_fail_reported = false;\n\n\t\t\/* check all sensors individually, but fail only for mandatory ones *\/\n\t\tfor (unsigned i = 0; i < max_optional_gyro_count; i++) {\n\t\t\tconst bool required = (i < max_mandatory_gyro_count);\n\t\t\tconst bool report_fail = (reportFailures && !failed && !gyro_fail_reported);\n\n\t\t\tint32_t device_id = -1;\n\n\t\t\tif (gyroCheck(mavlink_log_pub, status, i, !required, device_id, report_fail)) {\n\n\t\t\t\tif ((prime_id > 0) && (device_id == prime_id)) {\n\t\t\t\t\tprime_found = true;\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tif (required) {\n\t\t\t\t\tfailed = true;\n\t\t\t\t\tgyro_fail_reported = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/* check if the primary device is present *\/\n\t\tif (!prime_found) {\n\t\t\tif (reportFailures && !failed) {\n\t\t\t\tmavlink_log_critical(mavlink_log_pub, \"Primary gyro not found\");\n\t\t\t}\n\n\t\t\tset_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_GYRO, false, true, false, status);\n\t\t\tfailed = true;\n\t\t}\n\t}\n\n\t\/* ---- BARO ---- *\/\n\tif (checkSensors) {\n\t\t\/\/bool prime_found = false;\n\n\t\tint32_t prime_id = -1;\n\t\tparam_get(param_find(\"CAL_BARO_PRIME\"), &prime_id);\n\n\t\tint32_t sys_has_baro = 1;\n\t\tparam_get(param_find(\"SYS_HAS_BARO\"), &sys_has_baro);\n\n\t\tbool baro_fail_reported = false;\n\n\t\t\/* check all sensors, but fail only for mandatory ones *\/\n\t\tfor (unsigned i = 0; i < max_optional_baro_count; i++) {\n\t\t\tconst bool required = (i < max_mandatory_baro_count) && (sys_has_baro == 1);\n\t\t\tconst bool report_fail = (reportFailures && !failed && !baro_fail_reported);\n\n\t\t\tint32_t device_id = -1;\n\n\t\t\tif (baroCheck(mavlink_log_pub, status, i, !required, device_id, report_fail)) {\n\t\t\t\tif ((prime_id > 0) && (device_id == prime_id)) {\n\t\t\t\t\t\/\/prime_found = true;\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tif (required) {\n\t\t\t\t\tfailed = true;\n\t\t\t\t\tbaro_fail_reported = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ TODO there is no logic in place to calibrate the primary baro yet\n\t\t\/\/ \/\/ check if the primary device is present\n\t\t\/\/ if (false) {\n\t\t\/\/ \tif (reportFailures && !failed) {\n\t\t\/\/ \t\tmavlink_log_critical(mavlink_log_pub, \"Primary barometer not operational\");\n\t\t\/\/ \t}\n\n\t\t\/\/ \tset_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_ABSPRESSURE, false, true, false, status);\n\t\t\/\/ \tfailed = true;\n\t\t\/\/ }\n\t}\n\n\t\/* ---- IMU CONSISTENCY ---- *\/\n\t\/\/ To be performed after the individual sensor checks have completed\n\tif (checkSensors) {\n\t\tif (!imuConsistencyCheck(mavlink_log_pub, status, (reportFailures && !failed))) {\n\t\t\tfailed = true;\n\t\t}\n\t}\n\n\t\/* ---- AIRSPEED ---- *\/\n\tif (checkAirspeed) {\n\t\tint32_t optional = 0;\n\t\tparam_get(param_find(\"FW_ARSP_MODE\"), &optional);\n\n\t\tif (!airspeedCheck(mavlink_log_pub, status, (bool)optional, reportFailures && !failed, prearm) && !(bool)optional) {\n\t\t\tfailed = true;\n\t\t}\n\t}\n\n\t\/* ---- RC CALIBRATION ---- *\/\n\tif (checkRC) {\n\t\tif (rcCalibrationCheck(mavlink_log_pub, reportFailures && !failed, status.is_vtol) != OK) {\n\t\t\tif (reportFailures) {\n\t\t\t\tmavlink_log_critical(mavlink_log_pub, \"RC calibration check failed\");\n\t\t\t}\n\n\t\t\tfailed = true;\n\n\t\t\tset_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_RCRECEIVER, status_flags.rc_signal_found_once, true, false, status);\n\t\t\tstatus_flags.rc_calibration_valid = false;\n\n\t\t} else {\n\t\t\t\/\/ The calibration is fine, but only set the overall health state to true if the signal is not currently lost\n\t\t\tstatus_flags.rc_calibration_valid = true;\n\t\t\tset_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_RCRECEIVER, status_flags.rc_signal_found_once, true,\n\t\t\t\t\t !status.rc_signal_lost, status);\n\t\t}\n\t}\n\n\t\/* ---- SYSTEM POWER ---- *\/\n\tif (checkPower) {\n\t\tif (!powerCheck(mavlink_log_pub, status, (reportFailures && !failed), prearm)) {\n\t\t\tfailed = true;\n\t\t}\n\t}\n\n\t\/* ---- Navigation EKF ---- *\/\n\t\/\/ only check EKF2 data if EKF2 is selected as the estimator and GNSS checking is enabled\n\tint32_t estimator_type = -1;\n\n\tif (status.vehicle_type == vehicle_status_s::VEHICLE_TYPE_ROTARY_WING && !status.is_vtol) {\n\t\tparam_get(param_find(\"SYS_MC_EST_GROUP\"), &estimator_type);\n\n\t} else {\n\t\t\/\/ EKF2 is currently the only supported option for FW & VTOL\n\t\testimator_type = 2;\n\t}\n\n\tif (estimator_type == 2) {\n\t\t\/\/ don't report ekf failures for the first 10 seconds to allow time for the filter to start\n\t\tbool report_ekf_fail = (time_since_boot > 10_s);\n\n\t\tif (!ekf2Check(mavlink_log_pub, status, false, reportFailures && report_ekf_fail && !failed, checkGNSS)) {\n\t\t\tfailed = true;\n\t\t}\n\t}\n\n\t\/* ---- Failure Detector ---- *\/\n\tif (checkFailureDetector) {\n\t\tif (!failureDetectorCheck(mavlink_log_pub, status, (reportFailures && !failed), prearm)) {\n\t\t\tfailed = true;\n\t\t}\n\t}\n\n\t\/* Report status *\/\n\treturn !failed;\n}\n\nbool PreFlightCheck::check_calibration(const char *param_template, const int32_t device_id)\n{\n\tbool calibration_found = false;\n\n\tchar s[20];\n\tint instance = 0;\n\n\t\/* old style transition: check param values *\/\n\twhile (!calibration_found) {\n\t\tsprintf(s, param_template, instance);\n\t\tconst param_t parm = param_find_no_notification(s);\n\n\t\t\/* if the calibration param is not present, abort *\/\n\t\tif (parm == PARAM_INVALID) {\n\t\t\tbreak;\n\t\t}\n\n\t\t\/* if param get succeeds *\/\n\t\tint32_t calibration_devid = -1;\n\n\t\tif (param_get(parm, &calibration_devid) == PX4_OK) {\n\n\t\t\t\/* if the devid matches, exit early *\/\n\t\t\tif (device_id == calibration_devid) {\n\t\t\t\tcalibration_found = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tinstance++;\n\t}\n\n\treturn calibration_found;\n}\ncommander: skip all mag checks if SYS_HAS_MAG is 0\/****************************************************************************\n *\n * Copyright (c) 2019 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file PreFlightCheck.cpp\n *\/\n\n#include \"PreFlightCheck.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace time_literals;\n\nstatic constexpr unsigned max_mandatory_gyro_count = 1;\nstatic constexpr unsigned max_optional_gyro_count = 3;\nstatic constexpr unsigned max_mandatory_accel_count = 1;\nstatic constexpr unsigned max_optional_accel_count = 3;\nstatic constexpr unsigned max_mandatory_mag_count = 1;\nstatic constexpr unsigned max_optional_mag_count = 4;\nstatic constexpr unsigned max_mandatory_baro_count = 1;\nstatic constexpr unsigned max_optional_baro_count = 1;\n\nbool PreFlightCheck::preflightCheck(orb_advert_t *mavlink_log_pub, vehicle_status_s &status,\n\t\t\t\t vehicle_status_flags_s &status_flags, const bool checkGNSS, bool reportFailures, const bool prearm,\n\t\t\t\t const hrt_abstime &time_since_boot)\n{\n\tif (time_since_boot < 2_s) {\n\t\t\/\/ the airspeed driver filter doesn't deliver the actual value yet\n\t\treportFailures = false;\n\t}\n\n\tconst bool hil_enabled = (status.hil_state == vehicle_status_s::HIL_STATE_ON);\n\n\tbool checkSensors = !hil_enabled;\n\tconst bool checkRC = (status.rc_input_mode == vehicle_status_s::RC_IN_MODE_DEFAULT);\n\tconst bool checkDynamic = !hil_enabled;\n\tconst bool checkPower = (status_flags.condition_power_input_valid && !status_flags.circuit_breaker_engaged_power_check);\n\tconst bool checkFailureDetector = true;\n\n\tbool checkAirspeed = false;\n\n\t\/* Perform airspeed check only if circuit breaker is not\n\t * engaged and it's not a rotary wing *\/\n\tif (!status_flags.circuit_breaker_engaged_airspd_check &&\n\t (status.vehicle_type == vehicle_status_s::VEHICLE_TYPE_FIXED_WING || status.is_vtol)) {\n\t\tcheckAirspeed = true;\n\t}\n\n\treportFailures = (reportFailures && status_flags.condition_system_hotplug_timeout\n\t\t\t && !status_flags.condition_calibration_enabled);\n\n\tbool failed = false;\n\n\t\/* ---- MAG ---- *\/\n\tif (checkSensors) {\n\t\tint32_t sys_has_mag = 1;\n\t\tparam_get(param_find(\"SYS_HAS_MAG\"), &sys_has_mag);\n\n\t\tif (sys_has_mag == 1) {\n\n\t\t\tbool prime_found = false;\n\n\t\t\tint32_t prime_id = -1;\n\t\t\tparam_get(param_find(\"CAL_MAG_PRIME\"), &prime_id);\n\n\t\t\tbool mag_fail_reported = false;\n\n\t\t\t\/* check all sensors individually, but fail only for mandatory ones *\/\n\t\t\tfor (unsigned i = 0; i < max_optional_mag_count; i++) {\n\t\t\t\tconst bool required = (i < max_mandatory_mag_count) && (sys_has_mag == 1);\n\t\t\t\tconst bool report_fail = (reportFailures && !failed && !mag_fail_reported);\n\n\t\t\t\tint32_t device_id = -1;\n\n\t\t\t\tif (magnometerCheck(mavlink_log_pub, status, i, !required, device_id, report_fail)) {\n\n\t\t\t\t\tif ((prime_id > 0) && (device_id == prime_id)) {\n\t\t\t\t\t\tprime_found = true;\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\tif (required) {\n\t\t\t\t\t\tfailed = true;\n\t\t\t\t\t\tmag_fail_reported = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\t\/* check if the primary device is present *\/\n\t\t\tif (!prime_found) {\n\t\t\t\tif (reportFailures && !failed) {\n\t\t\t\t\tmavlink_log_critical(mavlink_log_pub, \"Primary compass not found\");\n\t\t\t\t}\n\n\t\t\t\tset_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_MAG, false, true, false, status);\n\t\t\t\tfailed = true;\n\t\t\t}\n\n\t\t\t\/* mag consistency checks (need to be performed after the individual checks) *\/\n\t\t\tif (!magConsistencyCheck(mavlink_log_pub, status, (reportFailures && !failed))) {\n\t\t\t\tfailed = true;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/* ---- ACCEL ---- *\/\n\tif (checkSensors) {\n\t\tbool prime_found = false;\n\t\tint32_t prime_id = -1;\n\t\tparam_get(param_find(\"CAL_ACC_PRIME\"), &prime_id);\n\n\t\tbool accel_fail_reported = false;\n\n\t\t\/* check all sensors individually, but fail only for mandatory ones *\/\n\t\tfor (unsigned i = 0; i < max_optional_accel_count; i++) {\n\t\t\tconst bool required = (i < max_mandatory_accel_count);\n\t\t\tconst bool report_fail = (reportFailures && !failed && !accel_fail_reported);\n\n\t\t\tint32_t device_id = -1;\n\n\t\t\tif (accelerometerCheck(mavlink_log_pub, status, i, !required, checkDynamic, device_id, report_fail)) {\n\n\t\t\t\tif ((prime_id > 0) && (device_id == prime_id)) {\n\t\t\t\t\tprime_found = true;\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tif (required) {\n\t\t\t\t\tfailed = true;\n\t\t\t\t\taccel_fail_reported = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/* check if the primary device is present *\/\n\t\tif (!prime_found) {\n\t\t\tif (reportFailures && !failed) {\n\t\t\t\tmavlink_log_critical(mavlink_log_pub, \"Primary accelerometer not found\");\n\t\t\t}\n\n\t\t\tset_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_ACC, false, true, false, status);\n\t\t\tfailed = true;\n\t\t}\n\t}\n\n\t\/* ---- GYRO ---- *\/\n\tif (checkSensors) {\n\t\tbool prime_found = false;\n\t\tint32_t prime_id = -1;\n\t\tparam_get(param_find(\"CAL_GYRO_PRIME\"), &prime_id);\n\n\t\tbool gyro_fail_reported = false;\n\n\t\t\/* check all sensors individually, but fail only for mandatory ones *\/\n\t\tfor (unsigned i = 0; i < max_optional_gyro_count; i++) {\n\t\t\tconst bool required = (i < max_mandatory_gyro_count);\n\t\t\tconst bool report_fail = (reportFailures && !failed && !gyro_fail_reported);\n\n\t\t\tint32_t device_id = -1;\n\n\t\t\tif (gyroCheck(mavlink_log_pub, status, i, !required, device_id, report_fail)) {\n\n\t\t\t\tif ((prime_id > 0) && (device_id == prime_id)) {\n\t\t\t\t\tprime_found = true;\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tif (required) {\n\t\t\t\t\tfailed = true;\n\t\t\t\t\tgyro_fail_reported = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/* check if the primary device is present *\/\n\t\tif (!prime_found) {\n\t\t\tif (reportFailures && !failed) {\n\t\t\t\tmavlink_log_critical(mavlink_log_pub, \"Primary gyro not found\");\n\t\t\t}\n\n\t\t\tset_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_GYRO, false, true, false, status);\n\t\t\tfailed = true;\n\t\t}\n\t}\n\n\t\/* ---- BARO ---- *\/\n\tif (checkSensors) {\n\t\t\/\/bool prime_found = false;\n\n\t\tint32_t prime_id = -1;\n\t\tparam_get(param_find(\"CAL_BARO_PRIME\"), &prime_id);\n\n\t\tint32_t sys_has_baro = 1;\n\t\tparam_get(param_find(\"SYS_HAS_BARO\"), &sys_has_baro);\n\n\t\tbool baro_fail_reported = false;\n\n\t\t\/* check all sensors, but fail only for mandatory ones *\/\n\t\tfor (unsigned i = 0; i < max_optional_baro_count; i++) {\n\t\t\tconst bool required = (i < max_mandatory_baro_count) && (sys_has_baro == 1);\n\t\t\tconst bool report_fail = (reportFailures && !failed && !baro_fail_reported);\n\n\t\t\tint32_t device_id = -1;\n\n\t\t\tif (baroCheck(mavlink_log_pub, status, i, !required, device_id, report_fail)) {\n\t\t\t\tif ((prime_id > 0) && (device_id == prime_id)) {\n\t\t\t\t\t\/\/prime_found = true;\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tif (required) {\n\t\t\t\t\tfailed = true;\n\t\t\t\t\tbaro_fail_reported = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ TODO there is no logic in place to calibrate the primary baro yet\n\t\t\/\/ \/\/ check if the primary device is present\n\t\t\/\/ if (false) {\n\t\t\/\/ \tif (reportFailures && !failed) {\n\t\t\/\/ \t\tmavlink_log_critical(mavlink_log_pub, \"Primary barometer not operational\");\n\t\t\/\/ \t}\n\n\t\t\/\/ \tset_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_ABSPRESSURE, false, true, false, status);\n\t\t\/\/ \tfailed = true;\n\t\t\/\/ }\n\t}\n\n\t\/* ---- IMU CONSISTENCY ---- *\/\n\t\/\/ To be performed after the individual sensor checks have completed\n\tif (checkSensors) {\n\t\tif (!imuConsistencyCheck(mavlink_log_pub, status, (reportFailures && !failed))) {\n\t\t\tfailed = true;\n\t\t}\n\t}\n\n\t\/* ---- AIRSPEED ---- *\/\n\tif (checkAirspeed) {\n\t\tint32_t optional = 0;\n\t\tparam_get(param_find(\"FW_ARSP_MODE\"), &optional);\n\n\t\tif (!airspeedCheck(mavlink_log_pub, status, (bool)optional, reportFailures && !failed, prearm) && !(bool)optional) {\n\t\t\tfailed = true;\n\t\t}\n\t}\n\n\t\/* ---- RC CALIBRATION ---- *\/\n\tif (checkRC) {\n\t\tif (rcCalibrationCheck(mavlink_log_pub, reportFailures && !failed, status.is_vtol) != OK) {\n\t\t\tif (reportFailures) {\n\t\t\t\tmavlink_log_critical(mavlink_log_pub, \"RC calibration check failed\");\n\t\t\t}\n\n\t\t\tfailed = true;\n\n\t\t\tset_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_RCRECEIVER, status_flags.rc_signal_found_once, true, false, status);\n\t\t\tstatus_flags.rc_calibration_valid = false;\n\n\t\t} else {\n\t\t\t\/\/ The calibration is fine, but only set the overall health state to true if the signal is not currently lost\n\t\t\tstatus_flags.rc_calibration_valid = true;\n\t\t\tset_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_RCRECEIVER, status_flags.rc_signal_found_once, true,\n\t\t\t\t\t !status.rc_signal_lost, status);\n\t\t}\n\t}\n\n\t\/* ---- SYSTEM POWER ---- *\/\n\tif (checkPower) {\n\t\tif (!powerCheck(mavlink_log_pub, status, (reportFailures && !failed), prearm)) {\n\t\t\tfailed = true;\n\t\t}\n\t}\n\n\t\/* ---- Navigation EKF ---- *\/\n\t\/\/ only check EKF2 data if EKF2 is selected as the estimator and GNSS checking is enabled\n\tint32_t estimator_type = -1;\n\n\tif (status.vehicle_type == vehicle_status_s::VEHICLE_TYPE_ROTARY_WING && !status.is_vtol) {\n\t\tparam_get(param_find(\"SYS_MC_EST_GROUP\"), &estimator_type);\n\n\t} else {\n\t\t\/\/ EKF2 is currently the only supported option for FW & VTOL\n\t\testimator_type = 2;\n\t}\n\n\tif (estimator_type == 2) {\n\t\t\/\/ don't report ekf failures for the first 10 seconds to allow time for the filter to start\n\t\tbool report_ekf_fail = (time_since_boot > 10_s);\n\n\t\tif (!ekf2Check(mavlink_log_pub, status, false, reportFailures && report_ekf_fail && !failed, checkGNSS)) {\n\t\t\tfailed = true;\n\t\t}\n\t}\n\n\t\/* ---- Failure Detector ---- *\/\n\tif (checkFailureDetector) {\n\t\tif (!failureDetectorCheck(mavlink_log_pub, status, (reportFailures && !failed), prearm)) {\n\t\t\tfailed = true;\n\t\t}\n\t}\n\n\t\/* Report status *\/\n\treturn !failed;\n}\n\nbool PreFlightCheck::check_calibration(const char *param_template, const int32_t device_id)\n{\n\tbool calibration_found = false;\n\n\tchar s[20];\n\tint instance = 0;\n\n\t\/* old style transition: check param values *\/\n\twhile (!calibration_found) {\n\t\tsprintf(s, param_template, instance);\n\t\tconst param_t parm = param_find_no_notification(s);\n\n\t\t\/* if the calibration param is not present, abort *\/\n\t\tif (parm == PARAM_INVALID) {\n\t\t\tbreak;\n\t\t}\n\n\t\t\/* if param get succeeds *\/\n\t\tint32_t calibration_devid = -1;\n\n\t\tif (param_get(parm, &calibration_devid) == PX4_OK) {\n\n\t\t\t\/* if the devid matches, exit early *\/\n\t\t\tif (device_id == calibration_devid) {\n\t\t\t\tcalibration_found = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tinstance++;\n\t}\n\n\treturn calibration_found;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: rootactiontriggercontainer.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 01:14:22 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifndef _OSL_MUTEX_HXX_\n#include \n#endif\n\n#ifndef _SV_SVAPP_HXX\n#include \n#endif\n\n#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_\n#include \n#endif\n\n\nusing namespace rtl;\nusing namespace cppu;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::container;\nusing namespace com::sun::star::beans;\n\n\nnamespace framework\n{\n\nstatic Sequence< sal_Int8 > impl_getStaticIdentifier()\n{\n static sal_uInt8 pGUID[16] = { 0x17, 0x0F, 0xA2, 0xC9, 0xCA, 0x50, 0x4A, 0xD3, 0xA6, 0x3B, 0x39, 0x99, 0xC5, 0x96, 0x43, 0x27 };\n static ::com::sun::star::uno::Sequence< sal_Int8 > seqID((sal_Int8*)pGUID,16) ;\n return seqID ;\n}\n\n\nRootActionTriggerContainer::RootActionTriggerContainer( const Menu* pMenu, const Reference< XMultiServiceFactory >& rServiceManager ) :\n PropertySetContainer( rServiceManager )\n , m_pMenu( pMenu )\n , m_bContainerCreated( sal_False )\n , m_bContainerChanged( sal_False )\n , m_bInContainerCreation( sal_False )\n{\n}\n\nRootActionTriggerContainer::~RootActionTriggerContainer()\n{\n}\n\nSequence< sal_Int8 > RootActionTriggerContainer::GetUnoTunnelId() const\n{\n return impl_getStaticIdentifier();\n}\n\nconst Menu* RootActionTriggerContainer::GetMenu()\n{\n if ( !m_bContainerChanged )\n return m_pMenu;\n else\n {\n ResetableGuard aGuard( m_aLock );\n\n Menu* pNewMenu = new PopupMenu;\n\n ActionTriggerHelper::CreateMenuFromActionTriggerContainer( pNewMenu, this );\n m_pMenu = pNewMenu;\n m_bContainerChanged = sal_False;\n\n return m_pMenu;\n }\n}\n\n\n\/\/ XInterface\nAny SAL_CALL RootActionTriggerContainer::queryInterface( const Type& aType )\nthrow ( RuntimeException )\n{\n Any a = ::cppu::queryInterface(\n aType ,\n SAL_STATIC_CAST( XMultiServiceFactory* , this ),\n SAL_STATIC_CAST( XServiceInfo* , this ),\n SAL_STATIC_CAST( XUnoTunnel* , this ),\n SAL_STATIC_CAST( XTypeProvider* , this ));\n\n if( a.hasValue() )\n {\n return a;\n }\n\n return PropertySetContainer::queryInterface( aType );\n}\n\nvoid SAL_CALL RootActionTriggerContainer::acquire() throw ()\n{\n PropertySetContainer::acquire();\n}\n\nvoid SAL_CALL RootActionTriggerContainer::release() throw ()\n{\n PropertySetContainer::release();\n}\n\n\/\/ XMultiServiceFactory\nReference< XInterface > SAL_CALL RootActionTriggerContainer::createInstance( const ::rtl::OUString& aServiceSpecifier )\nthrow ( Exception, RuntimeException )\n{\n if ( aServiceSpecifier.equalsAscii( SERVICENAME_ACTIONTRIGGER ))\n return (OWeakObject *)( new ActionTriggerPropertySet( m_xServiceManager ));\n else if ( aServiceSpecifier.equalsAscii( SERVICENAME_ACTIONTRIGGERCONTAINER ))\n return (OWeakObject *)( new ActionTriggerContainer( m_xServiceManager ));\n else if ( aServiceSpecifier.equalsAscii( SERVICENAME_ACTIONTRIGGERSEPARATOR ))\n return (OWeakObject *)( new ActionTriggerSeparatorPropertySet( m_xServiceManager ));\n else\n throw com::sun::star::uno::RuntimeException( OUString( RTL_CONSTASCII_USTRINGPARAM( \"Unknown service specifier!\" )), (OWeakObject *)this );\n}\n\nReference< XInterface > SAL_CALL RootActionTriggerContainer::createInstanceWithArguments( const ::rtl::OUString& ServiceSpecifier, const Sequence< Any >& Arguments )\nthrow ( Exception, RuntimeException )\n{\n return createInstance( ServiceSpecifier );\n}\n\nSequence< ::rtl::OUString > SAL_CALL RootActionTriggerContainer::getAvailableServiceNames()\nthrow ( RuntimeException )\n{\n Sequence< ::rtl::OUString > aSeq( 3 );\n\n aSeq[0] = OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICENAME_ACTIONTRIGGER ));\n aSeq[1] = OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICENAME_ACTIONTRIGGERCONTAINER ));\n aSeq[2] = OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICENAME_ACTIONTRIGGERSEPARATOR ));\n\n return aSeq;\n}\n\n\n\/\/ XIndexContainer\nvoid SAL_CALL RootActionTriggerContainer::insertByIndex( sal_Int32 Index, const Any& Element )\nthrow ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException )\n{\n ResetableGuard aGuard( m_aLock );\n\n if ( !m_bContainerCreated )\n FillContainer();\n\n if ( !m_bInContainerCreation )\n m_bContainerChanged = sal_True;\n PropertySetContainer::insertByIndex( Index, Element );\n}\n\nvoid SAL_CALL RootActionTriggerContainer::removeByIndex( sal_Int32 Index )\nthrow ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException )\n{\n ResetableGuard aGuard( m_aLock );\n\n if ( !m_bContainerCreated )\n FillContainer();\n\n if ( !m_bInContainerCreation )\n m_bContainerChanged = sal_True;\n PropertySetContainer::removeByIndex( Index );\n}\n\n\n\/\/ XIndexReplace\nvoid SAL_CALL RootActionTriggerContainer::replaceByIndex( sal_Int32 Index, const Any& Element )\nthrow ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException )\n{\n ResetableGuard aGuard( m_aLock );\n\n if ( !m_bContainerCreated )\n FillContainer();\n\n if ( !m_bInContainerCreation )\n m_bContainerChanged = sal_True;\n PropertySetContainer::replaceByIndex( Index, Element );\n}\n\n\n\/\/ XIndexAccess\nsal_Int32 SAL_CALL RootActionTriggerContainer::getCount()\nthrow ( RuntimeException )\n{\n ResetableGuard aGuard( m_aLock );\n\n if ( !m_bContainerCreated )\n {\n if ( m_pMenu )\n {\n vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );\n return m_pMenu->GetItemCount();\n }\n else\n return 0;\n }\n else\n {\n return PropertySetContainer::getCount();\n }\n}\n\nAny SAL_CALL RootActionTriggerContainer::getByIndex( sal_Int32 Index )\nthrow ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException )\n{\n ResetableGuard aGuard( m_aLock );\n\n if ( !m_bContainerCreated )\n FillContainer();\n\n return PropertySetContainer::getByIndex( Index );\n}\n\n\n\/\/ XElementAccess\nType SAL_CALL RootActionTriggerContainer::getElementType()\n throw (::com::sun::star::uno::RuntimeException)\n{\n return ::getCppuType(( Reference< XPropertySet >*)0);\n}\n\nsal_Bool SAL_CALL RootActionTriggerContainer::hasElements()\nthrow (::com::sun::star::uno::RuntimeException)\n{\n if ( m_pMenu )\n {\n vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );\n return ( m_pMenu->GetItemCount() > 0 );\n }\n\n return sal_False;\n}\n\n\n\/\/ XServiceInfo\n::rtl::OUString SAL_CALL RootActionTriggerContainer::getImplementationName()\nthrow ( RuntimeException )\n{\n return OUString( RTL_CONSTASCII_USTRINGPARAM( IMPLEMENTATIONNAME_ROOTACTIONTRIGGERCONTAINER ));\n}\n\nsal_Bool SAL_CALL RootActionTriggerContainer::supportsService( const ::rtl::OUString& ServiceName )\nthrow ( RuntimeException )\n{\n if ( ServiceName.equalsAscii( SERVICENAME_ACTIONTRIGGERCONTAINER ))\n return sal_True;\n\n return sal_False;\n}\n\nSequence< ::rtl::OUString > SAL_CALL RootActionTriggerContainer::getSupportedServiceNames()\nthrow ( RuntimeException )\n{\n Sequence< ::rtl::OUString > seqServiceNames( 1 );\n\n seqServiceNames[0] = OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICENAME_ACTIONTRIGGERCONTAINER ));\n return seqServiceNames;\n}\n\n\/\/ XUnoTunnel\nsal_Int64 SAL_CALL RootActionTriggerContainer::getSomething( const Sequence< sal_Int8 >& aIdentifier ) throw ( RuntimeException )\n{\n if ( aIdentifier == impl_getStaticIdentifier() )\n return (sal_Int64)this;\n else\n return 0;\n}\n\n\/\/ XTypeProvider\nSequence< Type > SAL_CALL RootActionTriggerContainer::getTypes() throw ( RuntimeException )\n{\n \/\/ Optimize this method !\n \/\/ We initialize a static variable only one time. And we don't must use a mutex at every call!\n \/\/ For the first call; pTypeCollection is NULL - for the second call pTypeCollection is different from NULL!\n static ::cppu::OTypeCollection* pTypeCollection = NULL ;\n\n if ( pTypeCollection == NULL )\n {\n \/\/ Ready for multithreading; get global mutex for first call of this method only! see before\n osl::MutexGuard aGuard( osl::Mutex::getGlobalMutex() ) ;\n\n \/\/ Control these pointer again ... it can be, that another instance will be faster then these!\n if ( pTypeCollection == NULL )\n {\n \/\/ Create a static typecollection ...\n static ::cppu::OTypeCollection aTypeCollection(\n ::getCppuType(( const Reference< XMultiServiceFactory >*)NULL ) ,\n ::getCppuType(( const Reference< XIndexContainer >*)NULL ) ,\n ::getCppuType(( const Reference< XIndexAccess >*)NULL ) ,\n ::getCppuType(( const Reference< XIndexReplace >*)NULL ) ,\n ::getCppuType(( const Reference< XServiceInfo >*)NULL ) ,\n ::getCppuType(( const Reference< XTypeProvider >*)NULL ) ,\n ::getCppuType(( const Reference< XUnoTunnel >*)NULL ) ) ;\n\n \/\/ ... and set his address to static pointer!\n pTypeCollection = &aTypeCollection ;\n }\n }\n\n return pTypeCollection->getTypes() ;\n}\n\nSequence< sal_Int8 > SAL_CALL RootActionTriggerContainer::getImplementationId() throw ( RuntimeException )\n{\n \/\/ Create one Id for all instances of this class.\n \/\/ Use ethernet address to do this! (sal_True)\n\n \/\/ Optimize this method\n \/\/ We initialize a static variable only one time. And we don't must use a mutex at every call!\n \/\/ For the first call; pID is NULL - for the second call pID is different from NULL!\n static ::cppu::OImplementationId* pID = NULL ;\n\n if ( pID == NULL )\n {\n \/\/ Ready for multithreading; get global mutex for first call of this method only! see before\n osl::MutexGuard aGuard( osl::Mutex::getGlobalMutex() ) ;\n\n \/\/ Control these pointer again ... it can be, that another instance will be faster then these!\n if ( pID == NULL )\n {\n \/\/ Create a new static ID ...\n static ::cppu::OImplementationId aID( sal_False ) ;\n \/\/ ... and set his address to static pointer!\n pID = &aID ;\n }\n }\n\n return pID->getImplementationId() ;\n}\n\n\/\/ private implementation helper\nvoid RootActionTriggerContainer::FillContainer()\n{\n m_bContainerCreated = sal_True;\n m_bInContainerCreation = sal_True;\n Reference xXIndexContainer( (OWeakObject *)this, UNO_QUERY );\n ActionTriggerHelper::FillActionTriggerContainerFromMenu(\n xXIndexContainer,\n m_pMenu );\n m_bInContainerCreation = sal_False;\n}\n\n}\nINTEGRATION: CWS warnings01 (1.5.32); FILE MERGED 2005\/11\/16 13:10:33 pl 1.5.32.2: #i55991# removed warnings 2005\/10\/28 14:48:31 cd 1.5.32.1: #i55991# Warning free code changes for gcc\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: rootactiontriggercontainer.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 11:14:51 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifndef _OSL_MUTEX_HXX_\n#include \n#endif\n\n#ifndef _SV_SVAPP_HXX\n#include \n#endif\n\n#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_\n#include \n#endif\n\n\nusing namespace rtl;\nusing namespace cppu;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::container;\nusing namespace com::sun::star::beans;\n\n\nnamespace framework\n{\n\nstatic Sequence< sal_Int8 > impl_getStaticIdentifier()\n{\n static sal_uInt8 pGUID[16] = { 0x17, 0x0F, 0xA2, 0xC9, 0xCA, 0x50, 0x4A, 0xD3, 0xA6, 0x3B, 0x39, 0x99, 0xC5, 0x96, 0x43, 0x27 };\n static ::com::sun::star::uno::Sequence< sal_Int8 > seqID((sal_Int8*)pGUID,16) ;\n return seqID ;\n}\n\n\nRootActionTriggerContainer::RootActionTriggerContainer( const Menu* pMenu, const Reference< XMultiServiceFactory >& rServiceManager ) :\n PropertySetContainer( rServiceManager )\n , m_bContainerCreated( sal_False )\n , m_bContainerChanged( sal_False )\n , m_bInContainerCreation( sal_False )\n , m_pMenu( pMenu )\n{\n}\n\nRootActionTriggerContainer::~RootActionTriggerContainer()\n{\n}\n\nSequence< sal_Int8 > RootActionTriggerContainer::GetUnoTunnelId() const\n{\n return impl_getStaticIdentifier();\n}\n\nconst Menu* RootActionTriggerContainer::GetMenu()\n{\n if ( !m_bContainerChanged )\n return m_pMenu;\n else\n {\n ResetableGuard aGuard( m_aLock );\n\n Menu* pNewMenu = new PopupMenu;\n\n ActionTriggerHelper::CreateMenuFromActionTriggerContainer( pNewMenu, this );\n m_pMenu = pNewMenu;\n m_bContainerChanged = sal_False;\n\n return m_pMenu;\n }\n}\n\n\n\/\/ XInterface\nAny SAL_CALL RootActionTriggerContainer::queryInterface( const Type& aType )\nthrow ( RuntimeException )\n{\n Any a = ::cppu::queryInterface(\n aType ,\n SAL_STATIC_CAST( XMultiServiceFactory* , this ),\n SAL_STATIC_CAST( XServiceInfo* , this ),\n SAL_STATIC_CAST( XUnoTunnel* , this ),\n SAL_STATIC_CAST( XTypeProvider* , this ));\n\n if( a.hasValue() )\n {\n return a;\n }\n\n return PropertySetContainer::queryInterface( aType );\n}\n\nvoid SAL_CALL RootActionTriggerContainer::acquire() throw ()\n{\n PropertySetContainer::acquire();\n}\n\nvoid SAL_CALL RootActionTriggerContainer::release() throw ()\n{\n PropertySetContainer::release();\n}\n\n\/\/ XMultiServiceFactory\nReference< XInterface > SAL_CALL RootActionTriggerContainer::createInstance( const ::rtl::OUString& aServiceSpecifier )\nthrow ( Exception, RuntimeException )\n{\n if ( aServiceSpecifier.equalsAscii( SERVICENAME_ACTIONTRIGGER ))\n return (OWeakObject *)( new ActionTriggerPropertySet( m_xServiceManager ));\n else if ( aServiceSpecifier.equalsAscii( SERVICENAME_ACTIONTRIGGERCONTAINER ))\n return (OWeakObject *)( new ActionTriggerContainer( m_xServiceManager ));\n else if ( aServiceSpecifier.equalsAscii( SERVICENAME_ACTIONTRIGGERSEPARATOR ))\n return (OWeakObject *)( new ActionTriggerSeparatorPropertySet( m_xServiceManager ));\n else\n throw com::sun::star::uno::RuntimeException( OUString( RTL_CONSTASCII_USTRINGPARAM( \"Unknown service specifier!\" )), (OWeakObject *)this );\n}\n\nReference< XInterface > SAL_CALL RootActionTriggerContainer::createInstanceWithArguments( const ::rtl::OUString& ServiceSpecifier, const Sequence< Any >& \/*Arguments*\/ )\nthrow ( Exception, RuntimeException )\n{\n return createInstance( ServiceSpecifier );\n}\n\nSequence< ::rtl::OUString > SAL_CALL RootActionTriggerContainer::getAvailableServiceNames()\nthrow ( RuntimeException )\n{\n Sequence< ::rtl::OUString > aSeq( 3 );\n\n aSeq[0] = OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICENAME_ACTIONTRIGGER ));\n aSeq[1] = OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICENAME_ACTIONTRIGGERCONTAINER ));\n aSeq[2] = OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICENAME_ACTIONTRIGGERSEPARATOR ));\n\n return aSeq;\n}\n\n\n\/\/ XIndexContainer\nvoid SAL_CALL RootActionTriggerContainer::insertByIndex( sal_Int32 Index, const Any& Element )\nthrow ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException )\n{\n ResetableGuard aGuard( m_aLock );\n\n if ( !m_bContainerCreated )\n FillContainer();\n\n if ( !m_bInContainerCreation )\n m_bContainerChanged = sal_True;\n PropertySetContainer::insertByIndex( Index, Element );\n}\n\nvoid SAL_CALL RootActionTriggerContainer::removeByIndex( sal_Int32 Index )\nthrow ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException )\n{\n ResetableGuard aGuard( m_aLock );\n\n if ( !m_bContainerCreated )\n FillContainer();\n\n if ( !m_bInContainerCreation )\n m_bContainerChanged = sal_True;\n PropertySetContainer::removeByIndex( Index );\n}\n\n\n\/\/ XIndexReplace\nvoid SAL_CALL RootActionTriggerContainer::replaceByIndex( sal_Int32 Index, const Any& Element )\nthrow ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException )\n{\n ResetableGuard aGuard( m_aLock );\n\n if ( !m_bContainerCreated )\n FillContainer();\n\n if ( !m_bInContainerCreation )\n m_bContainerChanged = sal_True;\n PropertySetContainer::replaceByIndex( Index, Element );\n}\n\n\n\/\/ XIndexAccess\nsal_Int32 SAL_CALL RootActionTriggerContainer::getCount()\nthrow ( RuntimeException )\n{\n ResetableGuard aGuard( m_aLock );\n\n if ( !m_bContainerCreated )\n {\n if ( m_pMenu )\n {\n vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );\n return m_pMenu->GetItemCount();\n }\n else\n return 0;\n }\n else\n {\n return PropertySetContainer::getCount();\n }\n}\n\nAny SAL_CALL RootActionTriggerContainer::getByIndex( sal_Int32 Index )\nthrow ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException )\n{\n ResetableGuard aGuard( m_aLock );\n\n if ( !m_bContainerCreated )\n FillContainer();\n\n return PropertySetContainer::getByIndex( Index );\n}\n\n\n\/\/ XElementAccess\nType SAL_CALL RootActionTriggerContainer::getElementType()\n throw (::com::sun::star::uno::RuntimeException)\n{\n return ::getCppuType(( Reference< XPropertySet >*)0);\n}\n\nsal_Bool SAL_CALL RootActionTriggerContainer::hasElements()\nthrow (::com::sun::star::uno::RuntimeException)\n{\n if ( m_pMenu )\n {\n vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );\n return ( m_pMenu->GetItemCount() > 0 );\n }\n\n return sal_False;\n}\n\n\n\/\/ XServiceInfo\n::rtl::OUString SAL_CALL RootActionTriggerContainer::getImplementationName()\nthrow ( RuntimeException )\n{\n return OUString( RTL_CONSTASCII_USTRINGPARAM( IMPLEMENTATIONNAME_ROOTACTIONTRIGGERCONTAINER ));\n}\n\nsal_Bool SAL_CALL RootActionTriggerContainer::supportsService( const ::rtl::OUString& ServiceName )\nthrow ( RuntimeException )\n{\n if ( ServiceName.equalsAscii( SERVICENAME_ACTIONTRIGGERCONTAINER ))\n return sal_True;\n\n return sal_False;\n}\n\nSequence< ::rtl::OUString > SAL_CALL RootActionTriggerContainer::getSupportedServiceNames()\nthrow ( RuntimeException )\n{\n Sequence< ::rtl::OUString > seqServiceNames( 1 );\n\n seqServiceNames[0] = OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICENAME_ACTIONTRIGGERCONTAINER ));\n return seqServiceNames;\n}\n\n\/\/ XUnoTunnel\nsal_Int64 SAL_CALL RootActionTriggerContainer::getSomething( const Sequence< sal_Int8 >& aIdentifier ) throw ( RuntimeException )\n{\n if ( aIdentifier == impl_getStaticIdentifier() )\n return reinterpret_cast< sal_Int64 >( this );\n else\n return 0;\n}\n\n\/\/ XTypeProvider\nSequence< Type > SAL_CALL RootActionTriggerContainer::getTypes() throw ( RuntimeException )\n{\n \/\/ Optimize this method !\n \/\/ We initialize a static variable only one time. And we don't must use a mutex at every call!\n \/\/ For the first call; pTypeCollection is NULL - for the second call pTypeCollection is different from NULL!\n static ::cppu::OTypeCollection* pTypeCollection = NULL ;\n\n if ( pTypeCollection == NULL )\n {\n \/\/ Ready for multithreading; get global mutex for first call of this method only! see before\n osl::MutexGuard aGuard( osl::Mutex::getGlobalMutex() ) ;\n\n \/\/ Control these pointer again ... it can be, that another instance will be faster then these!\n if ( pTypeCollection == NULL )\n {\n \/\/ Create a static typecollection ...\n static ::cppu::OTypeCollection aTypeCollection(\n ::getCppuType(( const Reference< XMultiServiceFactory >*)NULL ) ,\n ::getCppuType(( const Reference< XIndexContainer >*)NULL ) ,\n ::getCppuType(( const Reference< XIndexAccess >*)NULL ) ,\n ::getCppuType(( const Reference< XIndexReplace >*)NULL ) ,\n ::getCppuType(( const Reference< XServiceInfo >*)NULL ) ,\n ::getCppuType(( const Reference< XTypeProvider >*)NULL ) ,\n ::getCppuType(( const Reference< XUnoTunnel >*)NULL ) ) ;\n\n \/\/ ... and set his address to static pointer!\n pTypeCollection = &aTypeCollection ;\n }\n }\n\n return pTypeCollection->getTypes() ;\n}\n\nSequence< sal_Int8 > SAL_CALL RootActionTriggerContainer::getImplementationId() throw ( RuntimeException )\n{\n \/\/ Create one Id for all instances of this class.\n \/\/ Use ethernet address to do this! (sal_True)\n\n \/\/ Optimize this method\n \/\/ We initialize a static variable only one time. And we don't must use a mutex at every call!\n \/\/ For the first call; pID is NULL - for the second call pID is different from NULL!\n static ::cppu::OImplementationId* pID = NULL ;\n\n if ( pID == NULL )\n {\n \/\/ Ready for multithreading; get global mutex for first call of this method only! see before\n osl::MutexGuard aGuard( osl::Mutex::getGlobalMutex() ) ;\n\n \/\/ Control these pointer again ... it can be, that another instance will be faster then these!\n if ( pID == NULL )\n {\n \/\/ Create a new static ID ...\n static ::cppu::OImplementationId aID( sal_False ) ;\n \/\/ ... and set his address to static pointer!\n pID = &aID ;\n }\n }\n\n return pID->getImplementationId() ;\n}\n\n\/\/ private implementation helper\nvoid RootActionTriggerContainer::FillContainer()\n{\n m_bContainerCreated = sal_True;\n m_bInContainerCreation = sal_True;\n Reference xXIndexContainer( (OWeakObject *)this, UNO_QUERY );\n ActionTriggerHelper::FillActionTriggerContainerFromMenu(\n xXIndexContainer,\n m_pMenu );\n m_bInContainerCreation = sal_False;\n}\n\n}\n<|endoftext|>"} {"text":"\/\/ Protocol Buffers - Google's data interchange format\n\/\/ Copyright 2008 Google Inc. All rights reserved.\n\/\/ http:\/\/code.google.com\/p\/protobuf\/\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ Author: kenton@google.com (Kenton Varda)\n\/\/ Based on original Protocol Buffers design by\n\/\/ Sanjay Ghemawat, Jeff Dean, and others.\n\n#include \n#include \n#include \n#include \n\nnamespace google {\nnamespace protobuf {\nnamespace compiler {\nnamespace cpp {\n\nServiceGenerator::ServiceGenerator(const ServiceDescriptor* descriptor,\n const string& dllexport_decl)\n : descriptor_(descriptor) {\n vars_[\"classname\"] = descriptor_->name();\n vars_[\"full_name\"] = descriptor_->full_name();\n if (dllexport_decl.empty()) {\n vars_[\"dllexport\"] = \"\";\n } else {\n vars_[\"dllexport\"] = dllexport_decl + \" \";\n }\n}\n\nServiceGenerator::~ServiceGenerator() {}\n\nvoid ServiceGenerator::GenerateDeclarations(io::Printer* printer) {\n \/\/ Forward-declare the stub type.\n printer->Print(vars_,\n \"class $classname$_Stub;\\n\"\n \"\\n\");\n\n GenerateInterface(printer);\n GenerateStubDefinition(printer);\n}\n\nvoid ServiceGenerator::GenerateInterface(io::Printer* printer) {\n printer->Print(vars_,\n \"class $dllexport$$classname$ : public ::google::protobuf::Service {\\n\"\n \" protected:\\n\"\n \" \/\/ This class should be treated as an abstract interface.\\n\"\n \" inline $classname$() {};\\n\"\n \" public:\\n\"\n \" virtual ~$classname$();\\n\");\n printer->Indent();\n\n printer->Print(vars_,\n \"\\n\"\n \"typedef $classname$_Stub Stub;\\n\"\n \"\\n\"\n \"static const ::google::protobuf::ServiceDescriptor* descriptor();\\n\"\n \"\\n\");\n\n GenerateMethodSignatures(VIRTUAL, printer);\n\n printer->Print(\n \"\\n\"\n \"\/\/ implements Service ----------------------------------------------\\n\"\n \"\\n\"\n \"const ::google::protobuf::ServiceDescriptor* GetDescriptor();\\n\"\n \"void CallMethod(const ::google::protobuf::MethodDescriptor* method,\\n\"\n \" ::google::protobuf::RpcController* controller,\\n\"\n \" const ::google::protobuf::Message* request,\\n\"\n \" ::google::protobuf::Message* response,\\n\"\n \" ::google::protobuf::Closure* done);\\n\"\n \"const ::google::protobuf::Message& GetRequestPrototype(\\n\"\n \" const ::google::protobuf::MethodDescriptor* method) const;\\n\"\n \"const ::google::protobuf::Message& GetResponsePrototype(\\n\"\n \" const ::google::protobuf::MethodDescriptor* method) const;\\n\");\n\n printer->Outdent();\n printer->Print(vars_,\n \"\\n\"\n \" private:\\n\"\n \" GOOGLE_DISALLOW_EVIL_CONSTRUCTORS($classname$);\\n\"\n \"};\\n\"\n \"\\n\");\n}\n\nvoid ServiceGenerator::GenerateStubDefinition(io::Printer* printer) {\n printer->Print(vars_,\n \"class $dllexport$$classname$_Stub : public $classname$ {\\n\"\n \" public:\\n\");\n\n printer->Indent();\n\n printer->Print(vars_,\n \"$classname$_Stub(::google::protobuf::RpcChannel* channel);\\n\"\n \"$classname$_Stub(::google::protobuf::RpcChannel* channel,\\n\"\n \" ::google::protobuf::Service::ChannelOwnership ownership);\\n\"\n \"~$classname$_Stub();\\n\"\n \"\\n\"\n \"inline ::google::protobuf::RpcChannel* channel() { return channel_; }\\n\"\n \"\\n\"\n \"\/\/ implements $classname$ ------------------------------------------\\n\"\n \"\\n\");\n\n GenerateMethodSignatures(NON_VIRTUAL, printer);\n\n printer->Outdent();\n printer->Print(vars_,\n \" private:\\n\"\n \" ::google::protobuf::RpcChannel* channel_;\\n\"\n \" bool owns_channel_;\\n\"\n \" GOOGLE_DISALLOW_EVIL_CONSTRUCTORS($classname$_Stub);\\n\"\n \"};\\n\"\n \"\\n\");\n}\n\nvoid ServiceGenerator::GenerateMethodSignatures(\n VirtualOrNon virtual_or_non, io::Printer* printer) {\n for (int i = 0; i < descriptor_->method_count(); i++) {\n const MethodDescriptor* method = descriptor_->method(i);\n map sub_vars;\n sub_vars[\"name\"] = method->name();\n sub_vars[\"input_type\"] = ClassName(method->input_type(), true);\n sub_vars[\"output_type\"] = ClassName(method->output_type(), true);\n sub_vars[\"virtual\"] = virtual_or_non == VIRTUAL ? \"virtual \" : \"\";\n\n printer->Print(sub_vars,\n \"$virtual$void $name$(::google::protobuf::RpcController* controller,\\n\"\n \" const $input_type$* request,\\n\"\n \" $output_type$* response,\\n\"\n \" ::google::protobuf::Closure* done);\\n\");\n }\n}\n\n\/\/ ===================================================================\n\nvoid ServiceGenerator::GenerateDescriptorInitializer(\n io::Printer* printer, int index) {\n map vars;\n vars[\"classname\"] = descriptor_->name();\n vars[\"index\"] = SimpleItoa(index);\n\n printer->Print(vars,\n \"$classname$_descriptor_ = file->service($index$);\\n\");\n}\n\n\/\/ ===================================================================\n\nvoid ServiceGenerator::GenerateImplementation(io::Printer* printer) {\n printer->Print(vars_,\n \"$classname$::~$classname$() {}\\n\"\n \"\\n\"\n \"const ::google::protobuf::ServiceDescriptor* $classname$::descriptor() {\\n\"\n \" return $classname$_descriptor_;\\n\"\n \"}\\n\"\n \"\\n\"\n \"const ::google::protobuf::ServiceDescriptor* $classname$::GetDescriptor() {\\n\"\n \" return $classname$_descriptor_;\\n\"\n \"}\\n\"\n \"\\n\");\n\n \/\/ Generate methods of the interface.\n GenerateNotImplementedMethods(printer);\n GenerateCallMethod(printer);\n GenerateGetPrototype(REQUEST, printer);\n GenerateGetPrototype(RESPONSE, printer);\n\n \/\/ Generate stub implementation.\n printer->Print(vars_,\n \"$classname$_Stub::$classname$_Stub(::google::protobuf::RpcChannel* channel)\\n\"\n \" : channel_(channel), owns_channel_(false) {}\\n\"\n \"$classname$_Stub::$classname$_Stub(\\n\"\n \" ::google::protobuf::RpcChannel* channel,\\n\"\n \" ::google::protobuf::Service::ChannelOwnership ownership)\\n\"\n \" : channel_(channel),\\n\"\n \" owns_channel_(ownership == ::google::protobuf::Service::STUB_OWNS_CHANNEL) {}\\n\"\n \"$classname$_Stub::~$classname$_Stub() {\\n\"\n \" if (owns_channel_) delete channel_;\\n\"\n \"}\\n\"\n \"\\n\");\n\n GenerateStubMethods(printer);\n}\n\nvoid ServiceGenerator::GenerateNotImplementedMethods(io::Printer* printer) {\n for (int i = 0; i < descriptor_->method_count(); i++) {\n const MethodDescriptor* method = descriptor_->method(i);\n map sub_vars;\n sub_vars[\"classname\"] = descriptor_->name();\n sub_vars[\"name\"] = method->name();\n sub_vars[\"index\"] = SimpleItoa(i);\n sub_vars[\"input_type\"] = ClassName(method->input_type(), true);\n sub_vars[\"output_type\"] = ClassName(method->output_type(), true);\n\n printer->Print(sub_vars,\n \"void $classname$::$name$(::google::protobuf::RpcController* controller,\\n\"\n \" const $input_type$* request,\\n\"\n \" $output_type$* response,\\n\"\n \" ::google::protobuf::Closure* done) {\\n\"\n \" controller->SetFailed(\\\"Method $name$() not implemented.\\\");\\n\"\n \" done->Run();\\n\"\n \"}\\n\"\n \"\\n\");\n }\n}\n\nvoid ServiceGenerator::GenerateCallMethod(io::Printer* printer) {\n printer->Print(vars_,\n \"void $classname$::CallMethod(const ::google::protobuf::MethodDescriptor* method,\\n\"\n \" ::google::protobuf::RpcController* controller,\\n\"\n \" const ::google::protobuf::Message* request,\\n\"\n \" ::google::protobuf::Message* response,\\n\"\n \" ::google::protobuf::Closure* done) {\\n\"\n \" GOOGLE_DCHECK_EQ(method->service(), $classname$_descriptor_);\\n\"\n \" switch(method->index()) {\\n\");\n\n for (int i = 0; i < descriptor_->method_count(); i++) {\n const MethodDescriptor* method = descriptor_->method(i);\n map sub_vars;\n sub_vars[\"name\"] = method->name();\n sub_vars[\"index\"] = SimpleItoa(i);\n sub_vars[\"input_type\"] = ClassName(method->input_type(), true);\n sub_vars[\"output_type\"] = ClassName(method->output_type(), true);\n\n \/\/ Note: ::google::protobuf::down_cast does not work here because it only works on pointers,\n \/\/ not references.\n printer->Print(sub_vars,\n \" case $index$:\\n\"\n \" $name$(controller,\\n\"\n \" ::google::protobuf::down_cast(request),\\n\"\n \" ::google::protobuf::down_cast< $output_type$*>(response),\\n\"\n \" done);\\n\"\n \" break;\\n\");\n }\n\n printer->Print(vars_,\n \" default:\\n\"\n \" GOOGLE_LOG(FATAL) << \\\"Bad method index; this should never happen.\\\";\\n\"\n \" break;\\n\"\n \" }\\n\"\n \"}\\n\"\n \"\\n\");\n}\n\nvoid ServiceGenerator::GenerateGetPrototype(RequestOrResponse which,\n io::Printer* printer) {\n if (which == REQUEST) {\n printer->Print(vars_,\n \"const ::google::protobuf::Message& $classname$::GetRequestPrototype(\\n\");\n } else {\n printer->Print(vars_,\n \"const ::google::protobuf::Message& $classname$::GetResponsePrototype(\\n\");\n }\n\n printer->Print(vars_,\n \" const ::google::protobuf::MethodDescriptor* method) const {\\n\"\n \" GOOGLE_DCHECK_EQ(method->service(), $classname$_descriptor_);\\n\"\n \" switch(method->index()) {\\n\");\n\n for (int i = 0; i < descriptor_->method_count(); i++) {\n const MethodDescriptor* method = descriptor_->method(i);\n const Descriptor* type =\n (which == REQUEST) ? method->input_type() : method->output_type();\n\n map sub_vars;\n sub_vars[\"index\"] = SimpleItoa(i);\n sub_vars[\"type\"] = ClassName(type, true);\n\n printer->Print(sub_vars,\n \" case $index$:\\n\"\n \" return $type$::default_instance();\\n\");\n }\n\n printer->Print(vars_,\n \" default:\\n\"\n \" GOOGLE_LOG(FATAL) << \\\"Bad method index; this should never happen.\\\";\\n\"\n \" return *reinterpret_cast< ::google::protobuf::Message*>(NULL);\\n\"\n \" }\\n\"\n \"}\\n\"\n \"\\n\");\n}\n\nvoid ServiceGenerator::GenerateStubMethods(io::Printer* printer) {\n for (int i = 0; i < descriptor_->method_count(); i++) {\n const MethodDescriptor* method = descriptor_->method(i);\n map sub_vars;\n sub_vars[\"classname\"] = descriptor_->name();\n sub_vars[\"name\"] = method->name();\n sub_vars[\"index\"] = SimpleItoa(i);\n sub_vars[\"input_type\"] = ClassName(method->input_type(), true);\n sub_vars[\"output_type\"] = ClassName(method->output_type(), true);\n\n printer->Print(sub_vars,\n \"void $classname$_Stub::$name$(::google::protobuf::RpcController* controller,\\n\"\n \" const $input_type$* request,\\n\"\n \" $output_type$* response,\\n\"\n \" ::google::protobuf::Closure* done) {\\n\"\n \" channel_->CallMethod($classname$_descriptor_->method($index$),\\n\"\n \" controller, request, response, done);\\n\"\n \"}\\n\");\n }\n}\n\n} \/\/ namespace cpp\n} \/\/ namespace compiler\n} \/\/ namespace protobuf\n} \/\/ namespace google\nAvoid an \"unused parameter\" warning when using high warning levels.\/\/ Protocol Buffers - Google's data interchange format\n\/\/ Copyright 2008 Google Inc. All rights reserved.\n\/\/ http:\/\/code.google.com\/p\/protobuf\/\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ Author: kenton@google.com (Kenton Varda)\n\/\/ Based on original Protocol Buffers design by\n\/\/ Sanjay Ghemawat, Jeff Dean, and others.\n\n#include \n#include \n#include \n#include \n\nnamespace google {\nnamespace protobuf {\nnamespace compiler {\nnamespace cpp {\n\nServiceGenerator::ServiceGenerator(const ServiceDescriptor* descriptor,\n const string& dllexport_decl)\n : descriptor_(descriptor) {\n vars_[\"classname\"] = descriptor_->name();\n vars_[\"full_name\"] = descriptor_->full_name();\n if (dllexport_decl.empty()) {\n vars_[\"dllexport\"] = \"\";\n } else {\n vars_[\"dllexport\"] = dllexport_decl + \" \";\n }\n}\n\nServiceGenerator::~ServiceGenerator() {}\n\nvoid ServiceGenerator::GenerateDeclarations(io::Printer* printer) {\n \/\/ Forward-declare the stub type.\n printer->Print(vars_,\n \"class $classname$_Stub;\\n\"\n \"\\n\");\n\n GenerateInterface(printer);\n GenerateStubDefinition(printer);\n}\n\nvoid ServiceGenerator::GenerateInterface(io::Printer* printer) {\n printer->Print(vars_,\n \"class $dllexport$$classname$ : public ::google::protobuf::Service {\\n\"\n \" protected:\\n\"\n \" \/\/ This class should be treated as an abstract interface.\\n\"\n \" inline $classname$() {};\\n\"\n \" public:\\n\"\n \" virtual ~$classname$();\\n\");\n printer->Indent();\n\n printer->Print(vars_,\n \"\\n\"\n \"typedef $classname$_Stub Stub;\\n\"\n \"\\n\"\n \"static const ::google::protobuf::ServiceDescriptor* descriptor();\\n\"\n \"\\n\");\n\n GenerateMethodSignatures(VIRTUAL, printer);\n\n printer->Print(\n \"\\n\"\n \"\/\/ implements Service ----------------------------------------------\\n\"\n \"\\n\"\n \"const ::google::protobuf::ServiceDescriptor* GetDescriptor();\\n\"\n \"void CallMethod(const ::google::protobuf::MethodDescriptor* method,\\n\"\n \" ::google::protobuf::RpcController* controller,\\n\"\n \" const ::google::protobuf::Message* request,\\n\"\n \" ::google::protobuf::Message* response,\\n\"\n \" ::google::protobuf::Closure* done);\\n\"\n \"const ::google::protobuf::Message& GetRequestPrototype(\\n\"\n \" const ::google::protobuf::MethodDescriptor* method) const;\\n\"\n \"const ::google::protobuf::Message& GetResponsePrototype(\\n\"\n \" const ::google::protobuf::MethodDescriptor* method) const;\\n\");\n\n printer->Outdent();\n printer->Print(vars_,\n \"\\n\"\n \" private:\\n\"\n \" GOOGLE_DISALLOW_EVIL_CONSTRUCTORS($classname$);\\n\"\n \"};\\n\"\n \"\\n\");\n}\n\nvoid ServiceGenerator::GenerateStubDefinition(io::Printer* printer) {\n printer->Print(vars_,\n \"class $dllexport$$classname$_Stub : public $classname$ {\\n\"\n \" public:\\n\");\n\n printer->Indent();\n\n printer->Print(vars_,\n \"$classname$_Stub(::google::protobuf::RpcChannel* channel);\\n\"\n \"$classname$_Stub(::google::protobuf::RpcChannel* channel,\\n\"\n \" ::google::protobuf::Service::ChannelOwnership ownership);\\n\"\n \"~$classname$_Stub();\\n\"\n \"\\n\"\n \"inline ::google::protobuf::RpcChannel* channel() { return channel_; }\\n\"\n \"\\n\"\n \"\/\/ implements $classname$ ------------------------------------------\\n\"\n \"\\n\");\n\n GenerateMethodSignatures(NON_VIRTUAL, printer);\n\n printer->Outdent();\n printer->Print(vars_,\n \" private:\\n\"\n \" ::google::protobuf::RpcChannel* channel_;\\n\"\n \" bool owns_channel_;\\n\"\n \" GOOGLE_DISALLOW_EVIL_CONSTRUCTORS($classname$_Stub);\\n\"\n \"};\\n\"\n \"\\n\");\n}\n\nvoid ServiceGenerator::GenerateMethodSignatures(\n VirtualOrNon virtual_or_non, io::Printer* printer) {\n for (int i = 0; i < descriptor_->method_count(); i++) {\n const MethodDescriptor* method = descriptor_->method(i);\n map sub_vars;\n sub_vars[\"name\"] = method->name();\n sub_vars[\"input_type\"] = ClassName(method->input_type(), true);\n sub_vars[\"output_type\"] = ClassName(method->output_type(), true);\n sub_vars[\"virtual\"] = virtual_or_non == VIRTUAL ? \"virtual \" : \"\";\n\n printer->Print(sub_vars,\n \"$virtual$void $name$(::google::protobuf::RpcController* controller,\\n\"\n \" const $input_type$* request,\\n\"\n \" $output_type$* response,\\n\"\n \" ::google::protobuf::Closure* done);\\n\");\n }\n}\n\n\/\/ ===================================================================\n\nvoid ServiceGenerator::GenerateDescriptorInitializer(\n io::Printer* printer, int index) {\n map vars;\n vars[\"classname\"] = descriptor_->name();\n vars[\"index\"] = SimpleItoa(index);\n\n printer->Print(vars,\n \"$classname$_descriptor_ = file->service($index$);\\n\");\n}\n\n\/\/ ===================================================================\n\nvoid ServiceGenerator::GenerateImplementation(io::Printer* printer) {\n printer->Print(vars_,\n \"$classname$::~$classname$() {}\\n\"\n \"\\n\"\n \"const ::google::protobuf::ServiceDescriptor* $classname$::descriptor() {\\n\"\n \" return $classname$_descriptor_;\\n\"\n \"}\\n\"\n \"\\n\"\n \"const ::google::protobuf::ServiceDescriptor* $classname$::GetDescriptor() {\\n\"\n \" return $classname$_descriptor_;\\n\"\n \"}\\n\"\n \"\\n\");\n\n \/\/ Generate methods of the interface.\n GenerateNotImplementedMethods(printer);\n GenerateCallMethod(printer);\n GenerateGetPrototype(REQUEST, printer);\n GenerateGetPrototype(RESPONSE, printer);\n\n \/\/ Generate stub implementation.\n printer->Print(vars_,\n \"$classname$_Stub::$classname$_Stub(::google::protobuf::RpcChannel* channel)\\n\"\n \" : channel_(channel), owns_channel_(false) {}\\n\"\n \"$classname$_Stub::$classname$_Stub(\\n\"\n \" ::google::protobuf::RpcChannel* channel,\\n\"\n \" ::google::protobuf::Service::ChannelOwnership ownership)\\n\"\n \" : channel_(channel),\\n\"\n \" owns_channel_(ownership == ::google::protobuf::Service::STUB_OWNS_CHANNEL) {}\\n\"\n \"$classname$_Stub::~$classname$_Stub() {\\n\"\n \" if (owns_channel_) delete channel_;\\n\"\n \"}\\n\"\n \"\\n\");\n\n GenerateStubMethods(printer);\n}\n\nvoid ServiceGenerator::GenerateNotImplementedMethods(io::Printer* printer) {\n for (int i = 0; i < descriptor_->method_count(); i++) {\n const MethodDescriptor* method = descriptor_->method(i);\n map sub_vars;\n sub_vars[\"classname\"] = descriptor_->name();\n sub_vars[\"name\"] = method->name();\n sub_vars[\"index\"] = SimpleItoa(i);\n sub_vars[\"input_type\"] = ClassName(method->input_type(), true);\n sub_vars[\"output_type\"] = ClassName(method->output_type(), true);\n\n printer->Print(sub_vars,\n \"void $classname$::$name$(::google::protobuf::RpcController* controller,\\n\"\n \" const $input_type$*,\\n\"\n \" $output_type$*,\\n\"\n \" ::google::protobuf::Closure* done) {\\n\"\n \" controller->SetFailed(\\\"Method $name$() not implemented.\\\");\\n\"\n \" done->Run();\\n\"\n \"}\\n\"\n \"\\n\");\n }\n}\n\nvoid ServiceGenerator::GenerateCallMethod(io::Printer* printer) {\n printer->Print(vars_,\n \"void $classname$::CallMethod(const ::google::protobuf::MethodDescriptor* method,\\n\"\n \" ::google::protobuf::RpcController* controller,\\n\"\n \" const ::google::protobuf::Message* request,\\n\"\n \" ::google::protobuf::Message* response,\\n\"\n \" ::google::protobuf::Closure* done) {\\n\"\n \" GOOGLE_DCHECK_EQ(method->service(), $classname$_descriptor_);\\n\"\n \" switch(method->index()) {\\n\");\n\n for (int i = 0; i < descriptor_->method_count(); i++) {\n const MethodDescriptor* method = descriptor_->method(i);\n map sub_vars;\n sub_vars[\"name\"] = method->name();\n sub_vars[\"index\"] = SimpleItoa(i);\n sub_vars[\"input_type\"] = ClassName(method->input_type(), true);\n sub_vars[\"output_type\"] = ClassName(method->output_type(), true);\n\n \/\/ Note: ::google::protobuf::down_cast does not work here because it only works on pointers,\n \/\/ not references.\n printer->Print(sub_vars,\n \" case $index$:\\n\"\n \" $name$(controller,\\n\"\n \" ::google::protobuf::down_cast(request),\\n\"\n \" ::google::protobuf::down_cast< $output_type$*>(response),\\n\"\n \" done);\\n\"\n \" break;\\n\");\n }\n\n printer->Print(vars_,\n \" default:\\n\"\n \" GOOGLE_LOG(FATAL) << \\\"Bad method index; this should never happen.\\\";\\n\"\n \" break;\\n\"\n \" }\\n\"\n \"}\\n\"\n \"\\n\");\n}\n\nvoid ServiceGenerator::GenerateGetPrototype(RequestOrResponse which,\n io::Printer* printer) {\n if (which == REQUEST) {\n printer->Print(vars_,\n \"const ::google::protobuf::Message& $classname$::GetRequestPrototype(\\n\");\n } else {\n printer->Print(vars_,\n \"const ::google::protobuf::Message& $classname$::GetResponsePrototype(\\n\");\n }\n\n printer->Print(vars_,\n \" const ::google::protobuf::MethodDescriptor* method) const {\\n\"\n \" GOOGLE_DCHECK_EQ(method->service(), $classname$_descriptor_);\\n\"\n \" switch(method->index()) {\\n\");\n\n for (int i = 0; i < descriptor_->method_count(); i++) {\n const MethodDescriptor* method = descriptor_->method(i);\n const Descriptor* type =\n (which == REQUEST) ? method->input_type() : method->output_type();\n\n map sub_vars;\n sub_vars[\"index\"] = SimpleItoa(i);\n sub_vars[\"type\"] = ClassName(type, true);\n\n printer->Print(sub_vars,\n \" case $index$:\\n\"\n \" return $type$::default_instance();\\n\");\n }\n\n printer->Print(vars_,\n \" default:\\n\"\n \" GOOGLE_LOG(FATAL) << \\\"Bad method index; this should never happen.\\\";\\n\"\n \" return *reinterpret_cast< ::google::protobuf::Message*>(NULL);\\n\"\n \" }\\n\"\n \"}\\n\"\n \"\\n\");\n}\n\nvoid ServiceGenerator::GenerateStubMethods(io::Printer* printer) {\n for (int i = 0; i < descriptor_->method_count(); i++) {\n const MethodDescriptor* method = descriptor_->method(i);\n map sub_vars;\n sub_vars[\"classname\"] = descriptor_->name();\n sub_vars[\"name\"] = method->name();\n sub_vars[\"index\"] = SimpleItoa(i);\n sub_vars[\"input_type\"] = ClassName(method->input_type(), true);\n sub_vars[\"output_type\"] = ClassName(method->output_type(), true);\n\n printer->Print(sub_vars,\n \"void $classname$_Stub::$name$(::google::protobuf::RpcController* controller,\\n\"\n \" const $input_type$* request,\\n\"\n \" $output_type$* response,\\n\"\n \" ::google::protobuf::Closure* done) {\\n\"\n \" channel_->CallMethod($classname$_descriptor_->method($index$),\\n\"\n \" controller, request, response, done);\\n\"\n \"}\\n\");\n }\n}\n\n} \/\/ namespace cpp\n} \/\/ namespace compiler\n} \/\/ namespace protobuf\n} \/\/ namespace google\n<|endoftext|>"} {"text":"\/*\n * Copyright 2014 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"GrGLShaderStringBuilder.h\"\n#include \"GrSKSLPrettyPrint.h\"\n#include \"SkAutoMalloc.h\"\n#include \"SkSLCompiler.h\"\n#include \"SkSLGLSLCodeGenerator.h\"\n#include \"SkTraceEvent.h\"\n#include \"gl\/GrGLGpu.h\"\n#include \"ir\/SkSLProgram.h\"\n\n#define GL_CALL(X) GR_GL_CALL(gpu->glInterface(), X)\n#define GL_CALL_RET(R, X) GR_GL_CALL_RET(gpu->glInterface(), R, X)\n\n\/\/ Print the source code for all shaders generated.\nstatic const bool c_PrintShaders{false};\n\nstatic void print_source_lines_with_numbers(const char* source,\n std::function println) {\n SkTArray lines;\n SkStrSplit(source, \"\\n\", kStrict_SkStrSplitMode, &lines);\n for (int i = 0; i < lines.count(); ++i) {\n SkString& line = lines[i];\n line.prependf(\"%4i\\t\", i + 1);\n println(line.c_str());\n }\n}\n\n\/\/ Prints shaders one line at the time. This ensures they don't get truncated by the adb log.\nstatic void print_sksl_line_by_line(const char** skslStrings, int* lengths, int count,\n std::function println = [](const char* ln) {\n SkDebugf(\"%s\\n\", ln);\n }) {\n SkSL::String sksl = GrSKSLPrettyPrint::PrettyPrint(skslStrings, lengths, count, false);\n println(\"SKSL:\");\n print_source_lines_with_numbers(sksl.c_str(), println);\n}\n\nstatic void print_glsl_line_by_line(const SkSL::String& glsl,\n std::function println = [](const char* ln) {\n SkDebugf(\"%s\\n\", ln);\n }) {\n println(\"GLSL:\");\n print_source_lines_with_numbers(glsl.c_str(), println);\n}\n\nstd::unique_ptr GrSkSLtoGLSL(const GrGLContext& context, GrGLenum type,\n const char** skslStrings, int* lengths, int count,\n const SkSL::Program::Settings& settings,\n SkSL::String* glsl) {\n \/\/ Trace event for shader preceding driver compilation\n bool traceShader;\n TRACE_EVENT_CATEGORY_GROUP_ENABLED(\"skia.gpu\", &traceShader);\n if (traceShader) {\n SkString shaderDebugString;\n print_sksl_line_by_line(skslStrings, lengths, count, [&](const char* ln) {\n shaderDebugString.append(ln);\n shaderDebugString.append(\"\\n\");\n });\n TRACE_EVENT_INSTANT1(\"skia.gpu\", \"skia_gpu::GLShader\",\n TRACE_EVENT_SCOPE_THREAD, \"shader\",\n TRACE_STR_COPY(shaderDebugString.c_str()));\n }\n\n SkSL::String sksl;\n#ifdef SK_DEBUG\n sksl = GrSKSLPrettyPrint::PrettyPrint(skslStrings, lengths, count, false);\n#else\n for (int i = 0; i < count; i++) {\n sksl.append(skslStrings[i], lengths[i]);\n }\n#endif\n SkSL::Compiler* compiler = context.compiler();\n std::unique_ptr program;\n SkSL::Program::Kind programKind;\n switch (type) {\n case GR_GL_VERTEX_SHADER: programKind = SkSL::Program::kVertex_Kind; break;\n case GR_GL_FRAGMENT_SHADER: programKind = SkSL::Program::kFragment_Kind; break;\n case GR_GL_GEOMETRY_SHADER: programKind = SkSL::Program::kGeometry_Kind; break;\n }\n program = compiler->convertProgram(programKind, sksl, settings);\n if (!program || !compiler->toGLSL(*program, glsl)) {\n SkDebugf(\"SKSL compilation error\\n----------------------\\n\");\n print_sksl_line_by_line(skslStrings, lengths, count);\n SkDebugf(\"\\nErrors:\\n%s\\n\", compiler->errorText().c_str());\n SkDEBUGFAIL(\"SKSL compilation failed!\\n\");\n return nullptr;\n }\n return program;\n}\n\nGrGLuint GrGLCompileAndAttachShader(const GrGLContext& glCtx,\n GrGLuint programId,\n GrGLenum type,\n const char* glsl,\n int glslLength,\n GrGpu::Stats* stats,\n const SkSL::Program::Settings& settings) {\n const GrGLInterface* gli = glCtx.interface();\n\n \/\/ Specify GLSL source to the driver.\n GrGLuint shaderId;\n GR_GL_CALL_RET(gli, shaderId, CreateShader(type));\n if (0 == shaderId) {\n return 0;\n }\n GR_GL_CALL(gli, ShaderSource(shaderId, 1, &glsl, &glslLength));\n\n stats->incShaderCompilations();\n GR_GL_CALL(gli, CompileShader(shaderId));\n\n \/\/ Calling GetShaderiv in Chromium is quite expensive. Assume success in release builds.\n bool checkCompiled = kChromium_GrGLDriver != glCtx.driver();\n#ifdef SK_DEBUG\n checkCompiled = true;\n#endif\n if (checkCompiled) {\n GrGLint compiled = GR_GL_INIT_ZERO;\n GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_COMPILE_STATUS, &compiled));\n\n if (!compiled) {\n SkDebugf(\"GLSL compilation error\\n----------------------\\n\");\n print_glsl_line_by_line(glsl);\n GrGLint infoLen = GR_GL_INIT_ZERO;\n GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_INFO_LOG_LENGTH, &infoLen));\n SkAutoMalloc log(sizeof(char)*(infoLen+1)); \/\/ outside if for debugger\n if (infoLen > 0) {\n \/\/ retrieve length even though we don't need it to workaround bug in Chromium cmd\n \/\/ buffer param validation.\n GrGLsizei length = GR_GL_INIT_ZERO;\n GR_GL_CALL(gli, GetShaderInfoLog(shaderId, infoLen+1, &length, (char*)log.get()));\n SkDebugf(\"Errors:\\n%s\\n\", (const char*) log.get());\n }\n SkDEBUGFAIL(\"GLSL compilation failed!\");\n GR_GL_CALL(gli, DeleteShader(shaderId));\n return 0;\n }\n }\n\n if (c_PrintShaders) {\n const char* typeName = \"Unknown\";\n switch (type) {\n case GR_GL_VERTEX_SHADER: typeName = \"Vertex\"; break;\n case GR_GL_GEOMETRY_SHADER: typeName = \"Geometry\"; break;\n case GR_GL_FRAGMENT_SHADER: typeName = \"Fragment\"; break;\n }\n SkDebugf(\"---- %s shader ----------------------------------------------------\\n\", typeName);\n print_glsl_line_by_line(glsl);\n }\n\n \/\/ Attach the shader, but defer deletion until after we have linked the program.\n \/\/ This works around a bug in the Android emulator's GLES2 wrapper which\n \/\/ will immediately delete the shader object and free its memory even though it's\n \/\/ attached to a program, which then causes glLinkProgram to fail.\n GR_GL_CALL(gli, AttachShader(programId, shaderId));\n return shaderId;\n}\n\nvoid GrGLPrintShader(const GrGLContext& context, GrGLenum type, const char** skslStrings,\n int* lengths, int count, const SkSL::Program::Settings& settings) {\n print_sksl_line_by_line(skslStrings, lengths, count);\n SkSL::String glsl;\n if (GrSkSLtoGLSL(context, type, skslStrings, lengths, count, settings, &glsl)) {\n print_glsl_line_by_line(glsl);\n }\n}\nRoll external\/skia 64ca6be98..06ab3836f (1 commits)\/*\n * Copyright 2014 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"GrGLShaderStringBuilder.h\"\n#include \"GrSKSLPrettyPrint.h\"\n#include \"SkAutoMalloc.h\"\n#include \"SkSLCompiler.h\"\n#include \"SkSLGLSLCodeGenerator.h\"\n#include \"SkTraceEvent.h\"\n#include \"gl\/GrGLGpu.h\"\n#include \"ir\/SkSLProgram.h\"\n\n#define GL_CALL(X) GR_GL_CALL(gpu->glInterface(), X)\n#define GL_CALL_RET(R, X) GR_GL_CALL_RET(gpu->glInterface(), R, X)\n\n\/\/ Print the source code for all shaders generated.\nstatic const bool gPrintSKSL = false;\nstatic const bool gPrintGLSL = false;\n\nstatic void print_source_lines_with_numbers(const char* source,\n std::function println) {\n SkTArray lines;\n SkStrSplit(source, \"\\n\", kStrict_SkStrSplitMode, &lines);\n for (int i = 0; i < lines.count(); ++i) {\n SkString& line = lines[i];\n line.prependf(\"%4i\\t\", i + 1);\n println(line.c_str());\n }\n}\n\n\/\/ Prints shaders one line at the time. This ensures they don't get truncated by the adb log.\nstatic void print_sksl_line_by_line(const char** skslStrings, int* lengths, int count,\n std::function println = [](const char* ln) {\n SkDebugf(\"%s\\n\", ln);\n }) {\n SkSL::String sksl = GrSKSLPrettyPrint::PrettyPrint(skslStrings, lengths, count, false);\n println(\"SKSL:\");\n print_source_lines_with_numbers(sksl.c_str(), println);\n}\n\nstatic void print_glsl_line_by_line(const SkSL::String& glsl,\n std::function println = [](const char* ln) {\n SkDebugf(\"%s\\n\", ln);\n }) {\n println(\"GLSL:\");\n print_source_lines_with_numbers(glsl.c_str(), println);\n}\n\nvoid print_shader_banner(GrGLenum type) {\n const char* typeName = \"Unknown\";\n switch (type) {\n case GR_GL_VERTEX_SHADER: typeName = \"Vertex\"; break;\n case GR_GL_GEOMETRY_SHADER: typeName = \"Geometry\"; break;\n case GR_GL_FRAGMENT_SHADER: typeName = \"Fragment\"; break;\n }\n SkDebugf(\"---- %s shader ----------------------------------------------------\\n\", typeName);\n}\n\nstd::unique_ptr GrSkSLtoGLSL(const GrGLContext& context, GrGLenum type,\n const char** skslStrings, int* lengths, int count,\n const SkSL::Program::Settings& settings,\n SkSL::String* glsl) {\n \/\/ Trace event for shader preceding driver compilation\n bool traceShader;\n TRACE_EVENT_CATEGORY_GROUP_ENABLED(\"skia.gpu\", &traceShader);\n if (traceShader) {\n SkString shaderDebugString;\n print_sksl_line_by_line(skslStrings, lengths, count, [&](const char* ln) {\n shaderDebugString.append(ln);\n shaderDebugString.append(\"\\n\");\n });\n TRACE_EVENT_INSTANT1(\"skia.gpu\", \"skia_gpu::GLShader\",\n TRACE_EVENT_SCOPE_THREAD, \"shader\",\n TRACE_STR_COPY(shaderDebugString.c_str()));\n }\n\n SkSL::String sksl;\n#ifdef SK_DEBUG\n sksl = GrSKSLPrettyPrint::PrettyPrint(skslStrings, lengths, count, false);\n#else\n for (int i = 0; i < count; i++) {\n sksl.append(skslStrings[i], lengths[i]);\n }\n#endif\n SkSL::Compiler* compiler = context.compiler();\n std::unique_ptr program;\n SkSL::Program::Kind programKind;\n switch (type) {\n case GR_GL_VERTEX_SHADER: programKind = SkSL::Program::kVertex_Kind; break;\n case GR_GL_FRAGMENT_SHADER: programKind = SkSL::Program::kFragment_Kind; break;\n case GR_GL_GEOMETRY_SHADER: programKind = SkSL::Program::kGeometry_Kind; break;\n }\n program = compiler->convertProgram(programKind, sksl, settings);\n if (!program || !compiler->toGLSL(*program, glsl)) {\n SkDebugf(\"SKSL compilation error\\n----------------------\\n\");\n print_sksl_line_by_line(skslStrings, lengths, count);\n SkDebugf(\"\\nErrors:\\n%s\\n\", compiler->errorText().c_str());\n SkDEBUGFAIL(\"SKSL compilation failed!\\n\");\n return nullptr;\n }\n if (gPrintSKSL) {\n print_shader_banner(type);\n print_sksl_line_by_line(skslStrings, lengths, count);\n }\n return program;\n}\n\nGrGLuint GrGLCompileAndAttachShader(const GrGLContext& glCtx,\n GrGLuint programId,\n GrGLenum type,\n const char* glsl,\n int glslLength,\n GrGpu::Stats* stats,\n const SkSL::Program::Settings& settings) {\n const GrGLInterface* gli = glCtx.interface();\n\n \/\/ Specify GLSL source to the driver.\n GrGLuint shaderId;\n GR_GL_CALL_RET(gli, shaderId, CreateShader(type));\n if (0 == shaderId) {\n return 0;\n }\n GR_GL_CALL(gli, ShaderSource(shaderId, 1, &glsl, &glslLength));\n\n stats->incShaderCompilations();\n GR_GL_CALL(gli, CompileShader(shaderId));\n\n \/\/ Calling GetShaderiv in Chromium is quite expensive. Assume success in release builds.\n bool checkCompiled = kChromium_GrGLDriver != glCtx.driver();\n#ifdef SK_DEBUG\n checkCompiled = true;\n#endif\n if (checkCompiled) {\n GrGLint compiled = GR_GL_INIT_ZERO;\n GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_COMPILE_STATUS, &compiled));\n\n if (!compiled) {\n SkDebugf(\"GLSL compilation error\\n----------------------\\n\");\n print_glsl_line_by_line(glsl);\n GrGLint infoLen = GR_GL_INIT_ZERO;\n GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_INFO_LOG_LENGTH, &infoLen));\n SkAutoMalloc log(sizeof(char)*(infoLen+1)); \/\/ outside if for debugger\n if (infoLen > 0) {\n \/\/ retrieve length even though we don't need it to workaround bug in Chromium cmd\n \/\/ buffer param validation.\n GrGLsizei length = GR_GL_INIT_ZERO;\n GR_GL_CALL(gli, GetShaderInfoLog(shaderId, infoLen+1, &length, (char*)log.get()));\n SkDebugf(\"Errors:\\n%s\\n\", (const char*) log.get());\n }\n SkDEBUGFAIL(\"GLSL compilation failed!\");\n GR_GL_CALL(gli, DeleteShader(shaderId));\n return 0;\n }\n }\n\n if (gPrintGLSL) {\n print_shader_banner(type);\n print_glsl_line_by_line(glsl);\n }\n\n \/\/ Attach the shader, but defer deletion until after we have linked the program.\n \/\/ This works around a bug in the Android emulator's GLES2 wrapper which\n \/\/ will immediately delete the shader object and free its memory even though it's\n \/\/ attached to a program, which then causes glLinkProgram to fail.\n GR_GL_CALL(gli, AttachShader(programId, shaderId));\n return shaderId;\n}\n\nvoid GrGLPrintShader(const GrGLContext& context, GrGLenum type, const char** skslStrings,\n int* lengths, int count, const SkSL::Program::Settings& settings) {\n print_sksl_line_by_line(skslStrings, lengths, count);\n SkSL::String glsl;\n if (GrSkSLtoGLSL(context, type, skslStrings, lengths, count, settings, &glsl)) {\n print_glsl_line_by_line(glsl);\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2014 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"GrGLShaderStringBuilder.h\"\n#include \"GrSKSLPrettyPrint.h\"\n#include \"SkAutoMalloc.h\"\n#include \"SkSLCompiler.h\"\n#include \"SkSLGLSLCodeGenerator.h\"\n#include \"SkTraceEvent.h\"\n#include \"gl\/GrGLGpu.h\"\n#include \"ir\/SkSLProgram.h\"\n\n#define GL_CALL(X) GR_GL_CALL(gpu->glInterface(), X)\n#define GL_CALL_RET(R, X) GR_GL_CALL_RET(gpu->glInterface(), R, X)\n\n\/\/ Print the source code for all shaders generated.\nstatic const bool c_PrintShaders{false};\n\nstatic SkString list_source_with_line_numbers(const char* source) {\n SkTArray lines;\n SkStrSplit(source, \"\\n\", kStrict_SkStrSplitMode, &lines);\n SkString result;\n for (int line = 0; line < lines.count(); ++line) {\n \/\/ Print the shader one line at the time so it doesn't get truncated by the adb log.\n result.appendf(\"%4i\\t%s\\n\", line + 1, lines[line].c_str());\n }\n return result;\n}\n\nSkString list_shaders(const char** skslStrings, int* lengths, int count, const SkSL::String& glsl) {\n SkString sksl = GrSKSLPrettyPrint::PrettyPrint(skslStrings, lengths, count, false);\n SkString result(\"SKSL:\\n\");\n result.append(list_source_with_line_numbers(sksl.c_str()));\n if (!glsl.isEmpty()) {\n result.append(\"GLSL:\\n\");\n result.append(list_source_with_line_numbers(glsl.c_str()));\n }\n return result;\n}\n\nstd::unique_ptr translate_to_glsl(const GrGLContext& context, GrGLenum type,\n const char** skslStrings, int* lengths, int count,\n const SkSL::Program::Settings& settings,\n SkSL::String* glsl) {\n SkString sksl;\n#ifdef SK_DEBUG\n sksl = GrSKSLPrettyPrint::PrettyPrint(skslStrings, lengths, count, false);\n#else\n for (int i = 0; i < count; i++) {\n sksl.append(skslStrings[i], lengths[i]);\n }\n#endif\n SkSL::Compiler* compiler = context.compiler();\n std::unique_ptr program;\n SkSL::Program::Kind programKind;\n switch (type) {\n case GR_GL_VERTEX_SHADER: programKind = SkSL::Program::kVertex_Kind; break;\n case GR_GL_FRAGMENT_SHADER: programKind = SkSL::Program::kFragment_Kind; break;\n case GR_GL_GEOMETRY_SHADER: programKind = SkSL::Program::kGeometry_Kind; break;\n }\n program = compiler->convertProgram(programKind, sksl, settings);\n if (!program || !compiler->toGLSL(*program, glsl)) {\n SkDebugf(\"SKSL compilation error\\n----------------------\\n\");\n SkDebugf(list_shaders(skslStrings, lengths, count, *glsl).c_str());\n SkDebugf(\"\\nErrors:\\n%s\\n\", compiler->errorText().c_str());\n SkDEBUGFAIL(\"SKSL compilation failed!\\n\");\n return nullptr;\n }\n return program;\n}\n\nGrGLuint GrGLCompileAndAttachShader(const GrGLContext& glCtx,\n GrGLuint programId,\n GrGLenum type,\n const char** skslStrings,\n int* lengths,\n int count,\n GrGpu::Stats* stats,\n const SkSL::Program::Settings& settings,\n SkSL::Program::Inputs* outInputs) {\n const GrGLInterface* gli = glCtx.interface();\n\n SkSL::String glsl;\n auto program = translate_to_glsl(glCtx, type, skslStrings, lengths, count, settings, &glsl);\n if (!program) {\n return 0;\n }\n\n \/\/ Specify GLSL source to the driver.\n GrGLuint shaderId;\n GR_GL_CALL_RET(gli, shaderId, CreateShader(type));\n if (0 == shaderId) {\n return 0;\n }\n const char* glslChars = glsl.c_str();\n GrGLint glslLength = (GrGLint) glsl.size();\n GR_GL_CALL(gli, ShaderSource(shaderId, 1, &glslChars, &glslLength));\n\n \/\/ Lazy initialized pretty-printed shaders for dumping.\n SkString shaderDebugString;\n\n \/\/ Trace event for shader preceding driver compilation\n bool traceShader;\n TRACE_EVENT_CATEGORY_GROUP_ENABLED(TRACE_DISABLED_BY_DEFAULT(\"skia.gpu\"), &traceShader);\n if (traceShader) {\n if (shaderDebugString.isEmpty()) {\n shaderDebugString = list_shaders(skslStrings, lengths, count, glsl);\n }\n TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT(\"skia.gpu\"), \"skia_gpu::GLShader\",\n TRACE_EVENT_SCOPE_THREAD, \"shader\",\n TRACE_STR_COPY(shaderDebugString.c_str()));\n }\n\n stats->incShaderCompilations();\n GR_GL_CALL(gli, CompileShader(shaderId));\n\n \/\/ Calling GetShaderiv in Chromium is quite expensive. Assume success in release builds.\n bool checkCompiled = kChromium_GrGLDriver != glCtx.driver();\n#ifdef SK_DEBUG\n checkCompiled = true;\n#endif\n if (checkCompiled) {\n GrGLint compiled = GR_GL_INIT_ZERO;\n GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_COMPILE_STATUS, &compiled));\n\n if (!compiled) {\n if (shaderDebugString.isEmpty()) {\n shaderDebugString = list_shaders(skslStrings, lengths, count, glsl);\n }\n SkDebugf(\"GLSL compilation error\\n----------------------\\n\");\n SkDebugf(shaderDebugString.c_str());\n GrGLint infoLen = GR_GL_INIT_ZERO;\n GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_INFO_LOG_LENGTH, &infoLen));\n SkAutoMalloc log(sizeof(char)*(infoLen+1)); \/\/ outside if for debugger\n if (infoLen > 0) {\n \/\/ retrieve length even though we don't need it to workaround bug in Chromium cmd\n \/\/ buffer param validation.\n GrGLsizei length = GR_GL_INIT_ZERO;\n GR_GL_CALL(gli, GetShaderInfoLog(shaderId, infoLen+1, &length, (char*)log.get()));\n SkDebugf(\"Errors:\\n%s\\n\", (const char*) log.get());\n }\n SkDEBUGFAIL(\"GLSL compilation failed!\");\n GR_GL_CALL(gli, DeleteShader(shaderId));\n return 0;\n }\n }\n\n if (c_PrintShaders) {\n const char* typeName = \"Unknown\";\n switch (type) {\n case GR_GL_VERTEX_SHADER: typeName = \"Vertex\"; break;\n case GR_GL_GEOMETRY_SHADER: typeName = \"Geometry\"; break;\n case GR_GL_FRAGMENT_SHADER: typeName = \"Fragment\"; break;\n }\n SkDebugf(\"---- %s shader ----------------------------------------------------\\n\", typeName);\n if (shaderDebugString.isEmpty()) {\n shaderDebugString = list_shaders(skslStrings, lengths, count, glsl);\n }\n SkDebugf(shaderDebugString.c_str());\n }\n\n \/\/ Attach the shader, but defer deletion until after we have linked the program.\n \/\/ This works around a bug in the Android emulator's GLES2 wrapper which\n \/\/ will immediately delete the shader object and free its memory even though it's\n \/\/ attached to a program, which then causes glLinkProgram to fail.\n GR_GL_CALL(gli, AttachShader(programId, shaderId));\n *outInputs = program->fInputs;\n return shaderId;\n}\n\nvoid GrGLPrintShader(const GrGLContext& context, GrGLenum type, const char** skslStrings,\n int* lengths, int count, const SkSL::Program::Settings& settings) {\n SkSL::String glsl;\n if (translate_to_glsl(context, type, skslStrings, lengths, count, settings, &glsl)) {\n SkDebugf(list_shaders(skslStrings, lengths, count, glsl).c_str());\n }\n}\ngl: print shader sources one line at a time\/*\n * Copyright 2014 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"GrGLShaderStringBuilder.h\"\n#include \"GrSKSLPrettyPrint.h\"\n#include \"SkAutoMalloc.h\"\n#include \"SkSLCompiler.h\"\n#include \"SkSLGLSLCodeGenerator.h\"\n#include \"SkTraceEvent.h\"\n#include \"gl\/GrGLGpu.h\"\n#include \"ir\/SkSLProgram.h\"\n\n#define GL_CALL(X) GR_GL_CALL(gpu->glInterface(), X)\n#define GL_CALL_RET(R, X) GR_GL_CALL_RET(gpu->glInterface(), R, X)\n\n\/\/ Print the source code for all shaders generated.\nstatic const bool c_PrintShaders{false};\n\nstatic void print_source_lines_with_numbers(const char* source,\n std::function println) {\n SkTArray lines;\n SkStrSplit(source, \"\\n\", kStrict_SkStrSplitMode, &lines);\n for (int i = 0; i < lines.count(); ++i) {\n SkString& line = lines[i];\n line.prependf(\"%4i\\t\", i + 1);\n println(line.c_str());\n }\n}\n\n\/\/ Prints shaders one line at the time. This ensures they don't get truncated by the adb log.\nstatic void print_shaders_line_by_line(const char** skslStrings, int* lengths,\n int count, const SkSL::String& glsl,\n std::function println = [](const char* ln) {\n SkDebugf(\"%s\\n\", ln);\n }) {\n SkString sksl = GrSKSLPrettyPrint::PrettyPrint(skslStrings, lengths, count, false);\n println(\"SKSL:\");\n print_source_lines_with_numbers(sksl.c_str(), println);\n if (!glsl.isEmpty()) {\n println(\"GLSL:\");\n print_source_lines_with_numbers(glsl.c_str(), println);\n }\n}\n\nstd::unique_ptr translate_to_glsl(const GrGLContext& context, GrGLenum type,\n const char** skslStrings, int* lengths, int count,\n const SkSL::Program::Settings& settings,\n SkSL::String* glsl) {\n SkString sksl;\n#ifdef SK_DEBUG\n sksl = GrSKSLPrettyPrint::PrettyPrint(skslStrings, lengths, count, false);\n#else\n for (int i = 0; i < count; i++) {\n sksl.append(skslStrings[i], lengths[i]);\n }\n#endif\n SkSL::Compiler* compiler = context.compiler();\n std::unique_ptr program;\n SkSL::Program::Kind programKind;\n switch (type) {\n case GR_GL_VERTEX_SHADER: programKind = SkSL::Program::kVertex_Kind; break;\n case GR_GL_FRAGMENT_SHADER: programKind = SkSL::Program::kFragment_Kind; break;\n case GR_GL_GEOMETRY_SHADER: programKind = SkSL::Program::kGeometry_Kind; break;\n }\n program = compiler->convertProgram(programKind, sksl, settings);\n if (!program || !compiler->toGLSL(*program, glsl)) {\n SkDebugf(\"SKSL compilation error\\n----------------------\\n\");\n print_shaders_line_by_line(skslStrings, lengths, count, *glsl);\n SkDebugf(\"\\nErrors:\\n%s\\n\", compiler->errorText().c_str());\n SkDEBUGFAIL(\"SKSL compilation failed!\\n\");\n return nullptr;\n }\n return program;\n}\n\nGrGLuint GrGLCompileAndAttachShader(const GrGLContext& glCtx,\n GrGLuint programId,\n GrGLenum type,\n const char** skslStrings,\n int* lengths,\n int count,\n GrGpu::Stats* stats,\n const SkSL::Program::Settings& settings,\n SkSL::Program::Inputs* outInputs) {\n const GrGLInterface* gli = glCtx.interface();\n\n SkSL::String glsl;\n auto program = translate_to_glsl(glCtx, type, skslStrings, lengths, count, settings, &glsl);\n if (!program) {\n return 0;\n }\n\n \/\/ Specify GLSL source to the driver.\n GrGLuint shaderId;\n GR_GL_CALL_RET(gli, shaderId, CreateShader(type));\n if (0 == shaderId) {\n return 0;\n }\n const char* glslChars = glsl.c_str();\n GrGLint glslLength = (GrGLint) glsl.size();\n GR_GL_CALL(gli, ShaderSource(shaderId, 1, &glslChars, &glslLength));\n\n \/\/ Trace event for shader preceding driver compilation\n bool traceShader;\n TRACE_EVENT_CATEGORY_GROUP_ENABLED(TRACE_DISABLED_BY_DEFAULT(\"skia.gpu\"), &traceShader);\n if (traceShader) {\n SkString shaderDebugString;\n print_shaders_line_by_line(skslStrings, lengths, count, glsl, [&](const char* ln) {\n shaderDebugString.append(ln);\n shaderDebugString.append(\"\\n\");\n });\n TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT(\"skia.gpu\"), \"skia_gpu::GLShader\",\n TRACE_EVENT_SCOPE_THREAD, \"shader\",\n TRACE_STR_COPY(shaderDebugString.c_str()));\n }\n\n stats->incShaderCompilations();\n GR_GL_CALL(gli, CompileShader(shaderId));\n\n \/\/ Calling GetShaderiv in Chromium is quite expensive. Assume success in release builds.\n bool checkCompiled = kChromium_GrGLDriver != glCtx.driver();\n#ifdef SK_DEBUG\n checkCompiled = true;\n#endif\n if (checkCompiled) {\n GrGLint compiled = GR_GL_INIT_ZERO;\n GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_COMPILE_STATUS, &compiled));\n\n if (!compiled) {\n SkDebugf(\"GLSL compilation error\\n----------------------\\n\");\n print_shaders_line_by_line(skslStrings, lengths, count, glsl);\n GrGLint infoLen = GR_GL_INIT_ZERO;\n GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_INFO_LOG_LENGTH, &infoLen));\n SkAutoMalloc log(sizeof(char)*(infoLen+1)); \/\/ outside if for debugger\n if (infoLen > 0) {\n \/\/ retrieve length even though we don't need it to workaround bug in Chromium cmd\n \/\/ buffer param validation.\n GrGLsizei length = GR_GL_INIT_ZERO;\n GR_GL_CALL(gli, GetShaderInfoLog(shaderId, infoLen+1, &length, (char*)log.get()));\n SkDebugf(\"Errors:\\n%s\\n\", (const char*) log.get());\n }\n SkDEBUGFAIL(\"GLSL compilation failed!\");\n GR_GL_CALL(gli, DeleteShader(shaderId));\n return 0;\n }\n }\n\n if (c_PrintShaders) {\n const char* typeName = \"Unknown\";\n switch (type) {\n case GR_GL_VERTEX_SHADER: typeName = \"Vertex\"; break;\n case GR_GL_GEOMETRY_SHADER: typeName = \"Geometry\"; break;\n case GR_GL_FRAGMENT_SHADER: typeName = \"Fragment\"; break;\n }\n SkDebugf(\"---- %s shader ----------------------------------------------------\\n\", typeName);\n print_shaders_line_by_line(skslStrings, lengths, count, glsl);\n }\n\n \/\/ Attach the shader, but defer deletion until after we have linked the program.\n \/\/ This works around a bug in the Android emulator's GLES2 wrapper which\n \/\/ will immediately delete the shader object and free its memory even though it's\n \/\/ attached to a program, which then causes glLinkProgram to fail.\n GR_GL_CALL(gli, AttachShader(programId, shaderId));\n *outInputs = program->fInputs;\n return shaderId;\n}\n\nvoid GrGLPrintShader(const GrGLContext& context, GrGLenum type, const char** skslStrings,\n int* lengths, int count, const SkSL::Program::Settings& settings) {\n SkSL::String glsl;\n if (translate_to_glsl(context, type, skslStrings, lengths, count, settings, &glsl)) {\n print_shaders_line_by_line(skslStrings, lengths, count, glsl);\n }\n}\n<|endoftext|>"} {"text":"#ifndef SIMULATE_ENGINE_BASE_HPP_\n#define SIMULATE_ENGINE_BASE_HPP_\n\n#include \"clotho\/powerset\/variable_subset.hpp\"\n#include \"clotho\/utility\/random_generator.hpp\"\n\n#include \"clotho\/classifiers\/region_classifier.hpp\"\n\n#include \n#include \n\ntemplate < class URNG, class AlleleType, class LogType, class TimerType >\nclass simulate_engine_base {\npublic:\n typedef URNG rng_type;\n typedef AlleleType allele_type;\n typedef LogType log_type;\n typedef TimerType timer_type;\n\n typedef unsigned long block_type;\n\n typedef clotho::utility::random_generator< rng_type, allele_type > allele_generator;\n\n typedef clotho::powersets::variable_subset< allele_type, block_type > sequence_type;\n typedef typename sequence_type::pointer sequence_pointer;\n typedef typename sequence_type::powerset_type allele_set_type;\n\n typedef clotho::classifiers::region_classifier< allele_type > classifier_type;\n typedef clotho::utility::random_generator< rng_type, classifier_type > classifier_generator;\n\n typedef std::pair< sequence_pointer, sequence_pointer > individual_type;\n typedef std::vector< individual_type > population_type;\n typedef typename population_type::iterator population_iterator;\n};\n\n#endif \/\/ SIMULATE_ENGINE_BASE_HPP_\nAdded compilation specific dependencies for specific types#ifndef SIMULATE_ENGINE_BASE_HPP_\n#define SIMULATE_ENGINE_BASE_HPP_\n\n#include \"qtl_config.hpp\"\n\n#include \n#include \n\ntemplate < class URNG, class AlleleType, class LogType, class TimerType >\nclass simulate_engine_base {\npublic:\n typedef URNG rng_type;\n typedef AlleleType allele_type;\n typedef LogType log_type;\n typedef TimerType timer_type;\n\n typedef BLOCK_UNIT_TYPE block_type;\n\n typedef clotho::utility::random_generator< rng_type, allele_type > allele_generator;\n\n typedef SUBSETTYPE< allele_type, block_type > sequence_type;\n typedef typename sequence_type::pointer sequence_pointer;\n typedef typename sequence_type::powerset_type allele_set_type;\n\n typedef RECOMBTYPE classifier_type;\n typedef clotho::utility::random_generator< rng_type, classifier_type > classifier_generator;\n\n typedef std::pair< sequence_pointer, sequence_pointer > individual_type;\n typedef std::vector< individual_type > population_type;\n typedef typename population_type::iterator population_iterator;\n};\n\n#endif \/\/ SIMULATE_ENGINE_BASE_HPP_\n<|endoftext|>"} {"text":"#include \"streamline.h\"\n#include \"inc_glut.h\"\n#include \"color.h\"\n#include \"svg_line.h\"\n\nnamespace INMOST\n{\n\t\n\tvoid GetVelocity(Element c, const Tag & velocity_tag, ElementType vel_adj, coord pnt, coord & ret)\n\t{\n\t\tcoord cnt;\n\t\tconst Storage::real eps = 1.0e-8;\n\t\tStorage::real dist = 0;\n\t\tret[0] = ret[1] = ret[2] = 0;\n\t\tc->Centroid(cnt.data());\n\t\tif ((cnt - pnt).length() < 1.0e-5)\n\t\t{\n\t\t\tret = coord(c->RealArray(velocity_tag).data());\n\t\t}\n\t\telse \/\/inverse distance algorithm (consider wlsqr with linear basis)\n\t\t{\n\t\t\tElementArray adj = c->BridgeAdjacencies(vel_adj == NODE ? CELL : NODE,vel_adj);\n\t\t\tadj.push_back(c);\n\t\t\tfor (ElementArray::iterator it = adj.begin(); it != adj.end(); ++it)\n\t\t\t{\n\t\t\t\tit->Centroid(cnt.data());\n\t\t\t\tcoord vel = coord(it->RealArray(velocity_tag).data());\n\t\t\t\tStorage::real l = (cnt - pnt).length() + eps;\n\t\t\t\tStorage::real omega = 1.0 \/ (l*l);\n\t\t\t\tret += vel*omega;\n\t\t\t\tdist += omega;\n\t\t\t}\n\t\t\tret \/= dist;\n\t\t}\n\t}\n\n\n\tStorage::real GetSize(Cell c)\n\t{\n\t\tStorage::real bounds[3][2] = { { 1.0e20, -1.0e20 }, { 1.0e20, -1.0e20 }, { 1.0e20, -1.0e20 } };\n\t\tElementArray nodes = c->getNodes();\n\t\tfor (ElementArray::iterator n = nodes.begin(); n != nodes.end(); ++n)\n\t\t{\n\t\t\tStorage::real_array cnt = n->Coords();\n\t\t\tfor (int k = 0; k < 3; ++k)\n\t\t\t{\n\t\t\t\tif (bounds[k][0] > cnt[k]) bounds[k][0] = cnt[k];\n\t\t\t\tif (bounds[k][1] < cnt[k]) bounds[k][1] = cnt[k];\n\t\t\t}\n\t\t}\n\t\tStorage::real ret = 1.0e+20;\n\t\tfor (int k = 0; k < 3; ++k) if (bounds[k][1] - bounds[k][0])\n\t\t\tret = std::min(ret, bounds[k][1] - bounds[k][0]);\n\t\tif (ret > 1.0e+19) std::cout << __FILE__ << \":\" << __LINE__ << \" oops\" << std::endl;\n\t\treturn ret;\n\t}\n\n\n\tStorage::real GetSize(Element n, const Tag & size_tag)\n\t{\n\t\tElementArray cells = n->getCells();\n\t\tStorage::real minsize = 1.0e+20, size;\n\t\tfor (ElementArray::iterator c = cells.begin(); c != cells.end(); ++c)\n\t\t{\n\t\t\tsize = c->RealDF(size_tag);\n\t\t\tif (minsize > size) minsize = size;\n\t\t}\n\t\tif (minsize > 1.0e+19) std::cout << __FILE__ << \":\" << __LINE__ << \" oops\" << std::endl;\n\t\treturn minsize;\n\t}\n\n\n\tvoid BuildStreamlines(Mesh *mesh, Tag vel, ElementType vel_def, std::vector & output)\n\t{\n\t\tif (!vel.isDefined(vel_def))\n\t\t{\n\t\t\tstd::cout << __FILE__ << \":\" << __LINE__ << \" Velocity was not defined on \" << ElementTypeName(vel_def) << std::endl;\n\t\t\treturn;\n\t\t}\n\t\tif (vel.GetDataType() != DATA_REAL)\n\t\t{\n\t\t\tstd::cout << __FILE__ << \":\" << __LINE__ << \" Data type for velocity is not floating point\" << std::endl;\n\t\t\treturn;\n\t\t}\n\t\tif (vel.GetSize() != 3)\n\t\t{\n\t\t\tstd::cout << __FILE__ << \":\" << __LINE__ << \" Expected 3 entries in velocity field for streamlines\" << std::endl;\n\t\t\treturn;\n\t\t}\n\t\tprintf(\"preparing octree around mesh, was sets %d\\n\", mesh->NumberOfSets());\n\t\tOctree octsearch = Octree(mesh->CreateSet(\"octsearch\").first);\n\t\toctsearch.Construct(vel_def, false); \/\/auto-detect octree or quadtree\n\t\tprintf(\"done, sets %d\\n\", mesh->NumberOfSets());\n\t\tprintf(\"building streamlines\\n\");\n\t\tTag cell_size = mesh->CreateTag(\"STREAMLINES_TEMPORARY_CELL_SIZES\", DATA_REAL, CELL, NONE, 1);\n\t\tStorage::real velmax = 0, velmin = 1.0e20, l;\n\t\tfor (Mesh::iteratorCell c = mesh->BeginCell(); c != mesh->EndCell(); ++c)\n\t\t{\n\t\t\tcoord velv(c->RealArray(vel).data());\n\t\t\tl = velv.length();\n\t\t\tif (l > velmax) velmax = l;\n\t\t\tif (l < velmin) velmin = l;\n\t\t\tc->RealDF(cell_size) = GetSize(c->self());\n\t\t}\n\t\tvelmax = log(velmax + 1.0e-25);\n\t\tvelmin = log(velmin + 1.0e-25);\n\t\t\n\t\t{\n\t\t\tMarkerType visited = mesh->CreateMarker();\n\n\t\t\tprintf(\"started building streamlines from boundary elements\\n\");\n\t\t\tint tot = 0;\n\t\t\tfor (Mesh::iteratorElement f = mesh->BeginElement(vel_def); f != mesh->EndElement(); ++f) if (f->Boundary())\n\t\t\t\ttot++;\n\n\t\t\tprintf(\"total elements: %d\\n\",tot);\n\t\t\tint k = 0;\n\t\t\tfor (Mesh::iteratorElement f = mesh->BeginElement(vel_def); f != mesh->EndElement(); ++f) if (f->Boundary())\n\t\t\t{\n\t\t\t\tcoord v(f->RealArray(vel).data());\n\t\t\t\tif (v.length() > 1.0e-4)\n\t\t\t\t{\n\t\t\t\t\tcoord nrm(0,0,0);\n\t\t\t\t\tif( f->GetElementType() == FACE )\n\t\t\t\t\t\tf->getAsFace().UnitNormal(nrm.data());\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tcoord ncur;\n\t\t\t\t\t\tint nn = 0;\n\t\t\t\t\t\tElementArray faces = f->getFaces();\n\t\t\t\t\t\tfor (ElementArray::iterator ff = faces.begin(); ff != faces.end(); ++ff) if (ff->Boundary())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tff->UnitNormal(ncur.data());\n\t\t\t\t\t\t\tnrm+=ncur;\n\t\t\t\t\t\t\tnn++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif( nn )\n\t\t\t\t\t\t\tnrm \/= (double)nn;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tstd::cout << __FILE__ << \":\" << __LINE__ << \" No boundary faces around boundary element\" << std::endl;\n\t\t\t\t\t}\n\t\t\t\t\tdouble dir = nrm^v;\n\t\t\t\t\tif( dir > 0.0 ) \/\/velocity points out of mesh\n\t\t\t\t\t\tdir = -1; \n\t\t\t\t\telse dir = 1; \/\/velocity points into mesh\n\t\t\t\t\tcoord cntf;\n\t\t\t\t\tf->Centroid(cntf.data());\n\t\t\t\t\toutput.push_back(Streamline(octsearch, cntf, vel, vel_def, cell_size, velmin, velmax, dir, visited));\n\n\t\t\t\t\tElementArray edges = f->getEdges();\n\t\t\t\t\tfor (ElementArray::iterator n = edges.begin(); n != edges.end(); ++n)\n\t\t\t\t\t{\n\t\t\t\t\t\tcoord cntn;\n\t\t\t\t\t\tn->Centroid(cntn.data());\n\t\t\t\t\t\tif (cntn[2] == cntf[2])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst Storage::real coef[4] = { 0.4, 0.8 };\n\t\t\t\t\t\t\tfor (int q = 0; q < 2; ++q)\n\t\t\t\t\t\t\t\toutput.push_back(Streamline(octsearch, cntf*coef[q] + cntn*(1 - coef[q]), vel, vel_def, cell_size, velmin, velmax, 1.0, visited));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tk++;\n\t\t\t\tif (k % 100 == 0)\n\t\t\t\t{\n\t\t\t\t\tprintf(\"%5.2f%%\\r\", (double)k \/ (double)tot*100.0);\n\t\t\t\t\tfflush(stdout);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprintf(\"done from boundary faces, total streamlines = %lu\\n\", output.size());\n\n\t\t\tprintf(\"started building streamlines from unvisited cells\\n\");\n\t\t\ttot = 0;\n\t\t\tfor (Mesh::iteratorCell it = mesh->BeginCell(); it != mesh->EndCell(); ++it)\n\t\t\t\tif (!it->GetMarker(visited)) tot++;\n\n\t\t\tprintf(\"total elements: %d\\n\", tot);\n\t\t\tk = 0;\n\t\t\tfor (Mesh::iteratorCell it = mesh->BeginCell(); it != mesh->EndCell(); ++it)\n\t\t\t{\n\t\t\t\tif (!it->GetMarker(visited))\n\t\t\t\t{\n\t\t\t\t\tcoord cntc;\n\t\t\t\t\tit->Centroid(cntc.data());\n\t\t\t\t\tif (coord(it->RealArray(vel).data()).length() > 1.0e-4)\n\t\t\t\t\t{\n\t\t\t\t\t\toutput.push_back(Streamline(octsearch, cntc, vel, vel_def, cell_size, velmin, velmax, 1.0, 0));\n\t\t\t\t\t\toutput.push_back(Streamline(octsearch, cntc, vel, vel_def, cell_size, velmin, velmax, -1.0, 0));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tk++;\n\t\t\t\tif (k % 100 == 0)\n\t\t\t\t{\n\t\t\t\t\tprintf(\"%5.2f%%\\r\", (double)k \/ (double)tot*100.0);\n\t\t\t\t\tfflush(stdout);\n\t\t\t\t}\n\t\t\t}\n\t\t\tprintf(\"done from unvisited cells, total streamlines = %lu\\n\", output.size());\n\n\t\t\tmesh->ReleaseMarker(visited,vel_def);\n\n\t\t}\n\t\tmesh->DeleteTag(cell_size);\n\t\tprintf(\"done, total streamlines = %lu\\n\", output.size());\n\t\tprintf(\"killing octree, was sets %d\\n\", mesh->NumberOfSets());\n\t\toctsearch.Destroy();\n\t\tprintf(\"done, sets %d\\n\", mesh->NumberOfSets());\n\n\t}\n\n\n\tStreamline::Streamline(const Octree & octsearch, coord pos, Tag velocity_tag, ElementType velocity_defined, Tag cell_size, Storage::real velocity_min, Storage::real velocity_max, Storage::real sign, MarkerType visited)\n\t{\n\t\tStorage::real coef, len, size;\n\t\tcoord next = pos, vel;\n\t\tElement c;\n\t\tconst int maxsteps = 250;\n\t\tpoints.reserve(maxsteps \/ 2);\n\t\tvelarr.reserve(maxsteps \/ 2);\n\t\tpoints.push_back(pos);\n\t\tvelarr.push_back(0);\n\t\twhile (points.size() < maxsteps)\n\t\t{\n\t\t\tc = octsearch.FindClosestCell(next.data());\n\t\t\tif (!c.isValid()) break;\n\t\t\t\/\/check we are inside mesh\n\t\t\t\/*\n\t\t\tElementArray cells = c->BridgeAdjacencies2Cell(NODE);\n\t\t\tbool inside = false;\n\t\t\tfor (ElementArray::iterator it = cells.begin(); it != cells.end() && !inside; ++it)\n\t\t\t\tif( it->Inside(next.data()) ) inside = true;\n\t\t\tif( !inside ) break;\n\t\t\t*\/\n\t\t\tc.SetMarker(visited);\n\t\t\tGetVelocity(c, velocity_tag, velocity_defined, next, vel);\n\t\t\tlen = vel.length();\n\t\t\tif (len < 1.0e-4) break;\n\t\t\tsize = GetSize(c, cell_size);\/\/ c->RealDF(cell_size);\n\t\t\tcoef = 0.05*size \/ len;\n\t\t\tnext += vel*coef*sign;\n\t\t\tpoints.push_back(next);\n\t\t\tvelarr.push_back((log(len + 1.0e-25) - velocity_min) \/ (velocity_max - velocity_min));\n\t\t}\n\t\t\/\/printf(\"%ld %ld\\n\",points.size(),velarr.size());\n\t}\n\n\n\tGLUquadric * cylqs = NULL;\n\tvoid drawcylinder(coord a, coord b, double width)\n\t{\n\t\tdouble matrix[16];\n\t\tif (cylqs == NULL)\n\t\t{\n\t\t\tcylqs = gluNewQuadric();\n\t\t\tgluQuadricNormals(cylqs, GLU_SMOOTH);\n\t\t\tgluQuadricOrientation(cylqs, GLU_OUTSIDE);\n\t\t\tgluQuadricDrawStyle(cylqs, GLU_FILL);\/\/GLU_SILHOUETTE\n\t\t}\n\t\tglPushMatrix();\n\t\tglTranslated(a[0], a[1], a[2]);\n\t\tget_matrix(a, b, matrix);\n\t\tglMultMatrixd(matrix);\n\t\tgluCylinder(cylqs, width, width, sqrt((b - a) ^ (b - a)), 4, 2);\n\t\tglPopMatrix();\n\t}\n\n\n\n\tvoid Streamline::Draw(int reduced)\n\t{\n\t\tif (reduced)\n\t\t{\n\t\t\tglBegin(GL_LINE_STRIP);\n\t\t\tfor (unsigned int i = 0; i < points.size() - 1; i++)\n\t\t\t{\n\t\t\t\tglColor3f(velarr[i + 1] * 0.65, 0.65*(velarr[i + 1] < 0.5 ? velarr[i] : 1.0 - velarr[i]), 0.65*(1 - velarr[i + 1]));\n\t\t\t\tglVertex3d(points[i][0], points[i][1], points[i][2]);\n\t\t\t}\n\t\t\tglEnd();\n\t\t}\n\t\telse for (unsigned int i = 0; i < points.size() - 1; i++)\n\t\t{\n\t\t\tglColor3f(velarr[i + 1] * 0.65, 0.65*(velarr[i + 1] < 0.5 ? velarr[i] : 1.0 - velarr[i]), 0.65*(1 - velarr[i + 1]));\n\t\t\tdrawcylinder(points[i], points[i + 1], 0.25*abs(points[i + 1] - points[i]));\n\t\t}\n\t}\n\n\n\tvoid Streamline::SVGDraw(std::ostream & file, double modelview[16], double projection[16], int viewport[4])\n\t{\n\t\tfor (unsigned int i = 0; i < points.size() - 1; i++)\n\t\t{\n\t\t\tdouble * v0 = points[i].data();\n\t\t\tdouble * v1 = points[i + 1].data();\n\t\t\tcolor_t c(velarr[i + 1] * 0.65, 0.65*(velarr[i + 1] < 0.5 ? velarr[i] : 1.0 - velarr[i]), 0.65*(1 - velarr[i + 1]));\n\t\t\tfile << \"\" << std::endl;\n\t\t\tsvg_line(file, v0[0], v0[1], v0[2], v1[0], v1[1], v1[2], modelview, projection, viewport);\n\t\t\tfile << \"<\/g>\" << std::endl;\n\t\t}\n\t}\n}\nStreamlines in OldDrawGrid#include \"streamline.h\"\n#include \"inc_glut.h\"\n#include \"color.h\"\n#include \"svg_line.h\"\n\nnamespace INMOST\n{\n\t\n\tvoid GetVelocity(Element c, const Tag & velocity_tag, ElementType vel_adj, coord pnt, coord & ret)\n\t{\n\t\tcoord cnt;\n\t\tconst Storage::real eps = 1.0e-8;\n\t\tStorage::real dist = 0;\n\t\tret[0] = ret[1] = ret[2] = 0;\n\t\tc->Centroid(cnt.data());\n\t\tif ((cnt - pnt).length() < 1.0e-5)\n\t\t{\n\t\t\tret = coord(c->RealArray(velocity_tag).data());\n\t\t}\n\t\telse \/\/inverse distance algorithm (consider wlsqr with linear basis)\n\t\t{\n\t\t\tElementArray adj = c->BridgeAdjacencies(vel_adj == NODE ? CELL : NODE,vel_adj);\n\t\t\tadj.push_back(c);\n\t\t\tfor (ElementArray::iterator it = adj.begin(); it != adj.end(); ++it)\n\t\t\t{\n\t\t\t\tit->Centroid(cnt.data());\n\t\t\t\tcoord vel = coord(it->RealArray(velocity_tag).data());\n\t\t\t\tStorage::real l = (cnt - pnt).length() + eps;\n\t\t\t\tStorage::real omega = 1.0 \/ (l*l);\n\t\t\t\tret += vel*omega;\n\t\t\t\tdist += omega;\n\t\t\t}\n\t\t\tret \/= dist;\n\t\t}\n\t}\n\n\n\tStorage::real GetSize(Cell c)\n\t{\n\t\tStorage::real bounds[3][2] = { { 1.0e20, -1.0e20 }, { 1.0e20, -1.0e20 }, { 1.0e20, -1.0e20 } };\n\t\tElementArray nodes = c->getNodes();\n\t\tfor (ElementArray::iterator n = nodes.begin(); n != nodes.end(); ++n)\n\t\t{\n\t\t\tStorage::real_array cnt = n->Coords();\n\t\t\tfor (int k = 0; k < 3; ++k)\n\t\t\t{\n\t\t\t\tif (bounds[k][0] > cnt[k]) bounds[k][0] = cnt[k];\n\t\t\t\tif (bounds[k][1] < cnt[k]) bounds[k][1] = cnt[k];\n\t\t\t}\n\t\t}\n\t\tStorage::real ret = 1.0e+20;\n\t\tfor (int k = 0; k < 3; ++k) if (bounds[k][1] - bounds[k][0])\n\t\t\tret = std::min(ret, bounds[k][1] - bounds[k][0]);\n\t\tif (ret > 1.0e+19) std::cout << __FILE__ << \":\" << __LINE__ << \" oops\" << std::endl;\n\t\treturn ret;\n\t}\n\t\n\tvoid GetBbox(Element c, Storage::real bounds[3][2])\n\t{\n\t\tbounds[0][0] = 1.0e20;\n\t\tbounds[0][1] = -1.0e20;\n\t\tbounds[1][0] = 1.0e20;\n\t\tbounds[1][1] = -1.0e20;\n\t\tbounds[2][0] = 1.0e20;\n\t\tbounds[2][1] = -1.0e20;\n\t\t\/\/bounds[3][2] = { { 1.0e20, -1.0e20 }, { 1.0e20, -1.0e20 }, { 1.0e20, -1.0e20 } };\n\t\tElementArray nodes = c->getNodes();\n\t\tfor (ElementArray::iterator n = nodes.begin(); n != nodes.end(); ++n)\n\t\t{\n\t\t\tStorage::real_array cnt = n->Coords();\n\t\t\tfor (int k = 0; k < 3; ++k)\n\t\t\t{\n\t\t\t\tif (bounds[k][0] > cnt[k]) bounds[k][0] = cnt[k];\n\t\t\t\tif (bounds[k][1] < cnt[k]) bounds[k][1] = cnt[k];\n\t\t\t}\n\t\t}\n\t\treturn;\n\t\t\/\/Storage::real ret = 1.0e+20;\n\t\t\/\/for (int k = 0; k < 3; ++k) if (bounds[k][1] - bounds[k][0])\n\t\t\/\/\tret = std::min(ret, bounds[k][1] - bounds[k][0]);\n\t\t\/\/if (ret > 1.0e+19) std::cout << __FILE__ << \":\" << __LINE__ << \" oops\" << std::endl;\n\t\t\/\/return ret;\n\t}\n\n\tdouble GetSizeProj(double bounds[3][2], const coord & v)\n\t{\n\t\tdouble vl = v.length();\n\t\tif( !vl ) return 0;\n\t\tcoord uv = v\/vl;\n\t\tdouble ret = 0;\n\t\tfor(int k = 0; k < 3; ++k) ret += fabs(uv[k]*(bounds[k][1]-bounds[k][0]));\n\t\treturn ret;\n\t}\n\t\n\tdouble GetSizeProj(Element c, const coord & v)\n\t{\n\t\tdouble bounds[3][2];\n\t\tGetBbox(c,bounds);\n\t\treturn GetSizeProj(bounds,v);\n\t}\n\n\n\tStorage::real GetSize(Element n, const Tag & size_tag)\n\t{\n\t\tElementArray cells = n->getCells();\n\t\tStorage::real minsize = 1.0e+20, size;\n\t\tfor (ElementArray::iterator c = cells.begin(); c != cells.end(); ++c)\n\t\t{\n\t\t\tsize = c->RealDF(size_tag);\n\t\t\tif (minsize > size) minsize = size;\n\t\t}\n\t\tif (minsize > 1.0e+19) std::cout << __FILE__ << \":\" << __LINE__ << \" oops\" << std::endl;\n\t\treturn minsize;\n\t}\n\n\n\tvoid BuildStreamlines(Mesh *mesh, Tag vel, ElementType vel_def, std::vector & output)\n\t{\n\t\tif (!vel.isDefined(vel_def))\n\t\t{\n\t\t\tstd::cout << __FILE__ << \":\" << __LINE__ << \" Velocity was not defined on \" << ElementTypeName(vel_def) << std::endl;\n\t\t\treturn;\n\t\t}\n\t\tif (vel.GetDataType() != DATA_REAL)\n\t\t{\n\t\t\tstd::cout << __FILE__ << \":\" << __LINE__ << \" Data type for velocity is not floating point\" << std::endl;\n\t\t\treturn;\n\t\t}\n\t\tif (vel.GetSize() != 3)\n\t\t{\n\t\t\tstd::cout << __FILE__ << \":\" << __LINE__ << \" Expected 3 entries in velocity field for streamlines\" << std::endl;\n\t\t\treturn;\n\t\t}\n\t\tprintf(\"preparing octree around mesh, was sets %d\\n\", mesh->NumberOfSets());\n\t\tOctree octsearch = Octree(mesh->CreateSet(\"octsearch\").first);\n\t\toctsearch.Construct(vel_def, false); \/\/auto-detect octree or quadtree\n\t\tprintf(\"done, sets %d\\n\", mesh->NumberOfSets());\n\t\tprintf(\"building streamlines\\n\");\n\t\tTag cell_size = mesh->CreateTag(\"STREAMLINES_TEMPORARY_CELL_SIZES\", DATA_REAL, CELL, NONE, 1);\n\t\tStorage::real velmax = 0, velmin = 1.0e20, l;\n\t\tfor (Mesh::iteratorCell c = mesh->BeginCell(); c != mesh->EndCell(); ++c)\n\t\t{\n\t\t\tcoord velv(c->RealArray(vel).data());\n\t\t\tl = velv.length();\n\t\t\tif (l > velmax) velmax = l;\n\t\t\tif (l < velmin) velmin = l;\n\t\t\tc->RealDF(cell_size) = GetSize(c->self());\n\t\t}\n\t\tvelmax = log(velmax + 1.0e-25);\n\t\tvelmin = log(velmin + 1.0e-25);\n\t\t\n\t\t{\n\t\t\tMarkerType visited = mesh->CreateMarker();\n\t\t\tint tot = 0;\n\t\t\tint k = 0;\n\t\t\t\/*\n\t\t\tprintf(\"started building streamlines from boundary elements\\n\");\n\t\t\t\n\t\t\tfor (Mesh::iteratorElement f = mesh->BeginElement(vel_def); f != mesh->EndElement(); ++f) if (f->Boundary())\n\t\t\t\ttot++;\n\n\t\t\tprintf(\"total elements: %d\\n\",tot);\n\t\t\t\n\t\t\tfor (Mesh::iteratorElement f = mesh->BeginElement(vel_def); f != mesh->EndElement(); ++f) if (f->Boundary())\n\t\t\t{\n\t\t\t\tcoord v(f->RealArray(vel).data());\n\t\t\t\tif (v.length() > 1.0e-4)\n\t\t\t\t{\n\t\t\t\t\tcoord nrm(0,0,0);\n\t\t\t\t\tif( f->GetElementType() == FACE )\n\t\t\t\t\t\tf->getAsFace().UnitNormal(nrm.data());\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tcoord ncur;\n\t\t\t\t\t\tint nn = 0;\n\t\t\t\t\t\tElementArray faces = f->getFaces();\n\t\t\t\t\t\tfor (ElementArray::iterator ff = faces.begin(); ff != faces.end(); ++ff) if (ff->Boundary())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tff->UnitNormal(ncur.data());\n\t\t\t\t\t\t\tnrm+=ncur;\n\t\t\t\t\t\t\tnn++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif( nn )\n\t\t\t\t\t\t\tnrm \/= (double)nn;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tstd::cout << __FILE__ << \":\" << __LINE__ << \" No boundary faces around boundary element\" << std::endl;\n\t\t\t\t\t}\n\t\t\t\t\tdouble dir = nrm^v;\n\t\t\t\t\tif( dir > 0.0 ) \/\/velocity points out of mesh\n\t\t\t\t\t\tdir = -1; \n\t\t\t\t\telse dir = 1; \/\/velocity points into mesh\n\t\t\t\t\tcoord cntf;\n\t\t\t\t\tf->Centroid(cntf.data());\n\t\t\t\t\toutput.push_back(Streamline(octsearch, cntf, vel, vel_def, cell_size, velmin, velmax, dir, visited));\n\n\t\t\t\t\tElementArray edges = f->getEdges();\n\t\t\t\t\tfor (ElementArray::iterator n = edges.begin(); n != edges.end(); ++n)\n\t\t\t\t\t{\n\t\t\t\t\t\tcoord cntn;\n\t\t\t\t\t\tn->Centroid(cntn.data());\n\t\t\t\t\t\tif (cntn[2] == cntf[2])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst Storage::real coef[4] = { 0.4, 0.8 };\n\t\t\t\t\t\t\tfor (int q = 0; q < 2; ++q)\n\t\t\t\t\t\t\t\toutput.push_back(Streamline(octsearch, cntf*coef[q] + cntn*(1 - coef[q]), vel, vel_def, cell_size, velmin, velmax, 1.0, visited));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tk++;\n\t\t\t\tif (k % 100 == 0)\n\t\t\t\t{\n\t\t\t\t\tprintf(\"%5.2f%%\\r\", (double)k \/ (double)tot*100.0);\n\t\t\t\t\tfflush(stdout);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprintf(\"done from boundary faces, total streamlines = %lu\\n\", output.size());\n\t\t\t *\/\n\n\t\t\tprintf(\"started building streamlines from unvisited cells\\n\");\n\t\t\ttot = 0;\n\t\t\tfor (Mesh::iteratorCell it = mesh->BeginCell(); it != mesh->EndCell(); ++it)\n\t\t\t\tif (!it->GetMarker(visited)) tot++;\n\n\t\t\tprintf(\"total elements: %d\\n\", tot);\n\t\t\tk = 0;\n\t\t\tfor (Mesh::iteratorCell it = mesh->BeginCell(); it != mesh->EndCell(); ++it)\n\t\t\t{\n\t\t\t\tif (!it->GetMarker(visited))\n\t\t\t\t{\n\t\t\t\t\tcoord cntc;\n\t\t\t\t\tit->Centroid(cntc.data());\n\t\t\t\t\tif (coord(it->RealArray(vel).data()).length() > 1.0e-4)\n\t\t\t\t\t{\n\t\t\t\t\t\toutput.push_back(Streamline(octsearch, cntc, vel, vel_def, cell_size, velmin, velmax, 1.0, visited));\n\t\t\t\t\t\toutput.push_back(Streamline(octsearch, cntc, vel, vel_def, cell_size, velmin, velmax, -1.0, visited));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tk++;\n\t\t\t\tif (k % 100 == 0)\n\t\t\t\t{\n\t\t\t\t\tprintf(\"%5.2f%%\\r\", (double)k \/ (double)tot*100.0);\n\t\t\t\t\tfflush(stdout);\n\t\t\t\t}\n\t\t\t}\n\t\t\tprintf(\"done from unvisited cells, total streamlines = %lu\\n\", output.size());\n\n\t\t\tmesh->ReleaseMarker(visited,vel_def);\n\n\t\t}\n\t\tmesh->DeleteTag(cell_size);\n\t\tprintf(\"done, total streamlines = %lu\\n\", output.size());\n\t\tprintf(\"killing octree, was sets %d\\n\", mesh->NumberOfSets());\n\t\toctsearch.Destroy();\n\t\tprintf(\"done, sets %d\\n\", mesh->NumberOfSets());\n\n\t}\n\n\n\tStreamline::Streamline(const Octree & octsearch, coord pos, Tag velocity_tag, ElementType velocity_defined, Tag cell_size, Storage::real velocity_min, Storage::real velocity_max, Storage::real sign, MarkerType visited)\n\t{\n\t\tStorage::real coef, len, size;\n\t\tcoord next = pos, vel;\n\t\tElement c;\n\t\tconst int maxsteps = 8000;\n\t\tpoints.reserve(maxsteps \/ 2);\n\t\tvelarr.reserve(maxsteps \/ 2);\n\t\tpoints.push_back(pos);\n\t\tvelarr.push_back(0);\n\t\twhile (points.size() < maxsteps)\n\t\t{\n\t\t\tc = octsearch.FindClosestCell(next.data());\n\t\t\tif (!c.isValid()) break;\n\t\t\t\/\/if( !c.getAsCell().Inside(next.data()) ) break;\n\t\t\t\/\/check we are inside mesh\n\t\t\t\/*\n\t\t\tElementArray cells = c->BridgeAdjacencies2Cell(NODE);\n\t\t\tbool inside = false;\n\t\t\tfor (ElementArray::iterator it = cells.begin(); it != cells.end() && !inside; ++it)\n\t\t\t\tif( it->Inside(next.data()) ) inside = true;\n\t\t\tif( !inside ) break;\n\t\t\t*\/\n\t\t\tc.SetMarker(visited);\n\t\t\tGetVelocity(c, velocity_tag, velocity_defined, next, vel);\n\t\t\tlen = vel.length();\n\t\t\tif (len < 1.0e-7) break;\n\t\t\t\/\/size = GetSize(c, cell_size);\/\/ c->RealDF(cell_size);\n\t\t\tsize = GetSizeProj(c,vel);\n\t\t\tcoef = 0.02*size \/ len;\n\t\t\tnext += vel*coef*sign;\n\t\t\tpoints.push_back(next);\n\t\t\tvelarr.push_back((log(len + 1.0e-25) - velocity_min) \/ (velocity_max - velocity_min));\n\t\t}\n\t\t\/\/printf(\"%ld %ld\\n\",points.size(),velarr.size());\n\t}\n\n\n\tGLUquadric * cylqs = NULL;\n\tvoid drawcylinder(coord a, coord b, double width)\n\t{\n\t\tdouble matrix[16];\n\t\tif (cylqs == NULL)\n\t\t{\n\t\t\tcylqs = gluNewQuadric();\n\t\t\tgluQuadricNormals(cylqs, GLU_SMOOTH);\n\t\t\tgluQuadricOrientation(cylqs, GLU_OUTSIDE);\n\t\t\tgluQuadricDrawStyle(cylqs, GLU_FILL);\/\/GLU_SILHOUETTE\n\t\t}\n\t\tglPushMatrix();\n\t\tglTranslated(a[0], a[1], a[2]);\n\t\tget_matrix(a, b, matrix);\n\t\tglMultMatrixd(matrix);\n\t\tgluCylinder(cylqs, width, width, sqrt((b - a) ^ (b - a)), 4, 2);\n\t\tglPopMatrix();\n\t}\n\n\n\n\tvoid Streamline::Draw(int reduced)\n\t{\n\t\tif (reduced)\n\t\t{\n\t\t\tglBegin(GL_LINE_STRIP);\n\t\t\tfor (unsigned int i = 0; i < points.size() - 1; i++)\n\t\t\t{\n\t\t\t\tglColor3f(velarr[i + 1] * 0.65, 0.65*(velarr[i + 1] < 0.5 ? velarr[i] : 1.0 - velarr[i]), 0.65*(1 - velarr[i + 1]));\n\t\t\t\tglVertex3d(points[i][0], points[i][1], points[i][2]);\n\t\t\t}\n\t\t\tglEnd();\n\t\t}\n\t\telse for (unsigned int i = 0; i < points.size() - 1; i++)\n\t\t{\n\t\t\tglColor3f(velarr[i + 1] * 0.65, 0.65*(velarr[i + 1] < 0.5 ? velarr[i] : 1.0 - velarr[i]), 0.65*(1 - velarr[i + 1]));\n\t\t\tdrawcylinder(points[i], points[i + 1], 0.5*abs(points[i + 1] - points[i]));\n\t\t}\n\t}\n\n\n\tvoid Streamline::SVGDraw(std::ostream & file, double modelview[16], double projection[16], int viewport[4])\n\t{\n\t\tfor (unsigned int i = 0; i < points.size() - 1; i++)\n\t\t{\n\t\t\tdouble * v0 = points[i].data();\n\t\t\tdouble * v1 = points[i + 1].data();\n\t\t\tcolor_t c(velarr[i + 1] * 0.65, 0.65*(velarr[i + 1] < 0.5 ? velarr[i] : 1.0 - velarr[i]), 0.65*(1 - velarr[i + 1]));\n\t\t\tfile << \"\" << std::endl;\n\t\t\tsvg_line(file, v0[0], v0[1], v0[2], v1[0], v1[1], v1[2], modelview, projection, viewport);\n\t\t\tfile << \"<\/g>\" << std::endl;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"#include \"inmost.h\"\n\nusing namespace INMOST;\n\n\/\/TODO:\n\/\/attach scale to rescale grid\n\/\/attach slice grid to cut cylinder\n\/\/option to set shear rate \/ pressure drop \/ maximum velocity\n\/\/setup BC\n\/\/cmake compilation\n\n\/\/setup on mesh:\n\/\/\n\/\/ FORCE - 3 entries\n\/\/\n\/\/ BOUNDARY_CONDITION_VELOCITY - 7 entries\n\/\/ r = (a5,a6,a7)\n\/\/ n.(a1*u + a2*t) = n.r\n\/\/ (I - nn.)(a3*u + a4*t) = (I-nn.)r\n\/\/\n\/\/ BOUNDARY_CONDITION_PRESSURE - 1 entry\n\/\/\n\/\/ REFERENCE_VELOCITY - 3 entries\n\/\/\n\/\/ REFERENCE_PRESSURE - 1 entry\n\/\/\n\n\n\ntypedef Storage::real real;\n\n\n\nint main(int argc, char ** argv)\n{\n\t\n\tif( argc < 2 )\n\t{\n\t\tstd::cout << \"Usage: \" << argv[0] << \" mesh [axis=2 (0:x,1:y,2:z)] [control=0 (0:shear rate,1:pressure drop,2:maximal velocity)] [control_value=10] [visc=1.0e-5] [mesh_out=grid_out.pmf]\" << std::endl;\n\t\treturn 0;\n\t}\n\t\n\tMesh * m = new Mesh;\n\tm->SetFileOption(\"VERBOSITY\",\"2\");\n\ttry\n\t{\n\t\tm->Load(argv[1]);\n\t}\n\tcatch(...)\n\t{\n\t\tstd::cout << \"Cannot load the mesh \" << argv[1] << std::endl;\n\t\treturn -1;\n\t}\n\t\n\tstd::string fout = \"grid_out.pmf\";\n\tint axis = 2;\n\tdouble visc = 1.0e-5;\n\tint control = 0;\n\tdouble control_value = 10;\n\tdouble Len = 8;\n\tdouble Diam = 1;\n\tdouble shear = 10;\/\/0; \/\/shear rate\n\tdouble dp = 0;\/\/36e-6;\n\tdouble vmax = 0;\n\n\tif( argc > 2 ) axis = atoi(argv[2]);\n\tif( argc > 3 ) control = atoi(argv[3]);\n\tif( argc > 4 ) control_value = atof(argv[4]);\n\tif( argc > 5 ) visc = atof(argv[5]);\n\tif( argc > 6 ) fout = std::string(argv[6]);\n\t\n\t\n\t\n\tif( axis < 0 || axis > 2 )\n\t{\n\t\tstd::cout << \"bad axis: \" << axis << \" should be 0 - x, 1 - y, 2 - z\" << std::endl;\n\t\treturn -1;\n\t}\n\t\n\tif( control < 0 || control > 2 )\n\t{\n\t\tstd::cout << \"bad control: \" << control << \" should be 0 - shear rate, 1 - pressure drop, 2 - maximal velocity\" << std::endl;\n\t\treturn -1;\n\t}\n\t\n\tif( visc <= 0 )\n\t{\n\t\tstd::cout << \"bad viscosity: \" << visc << std::endl;\n\t\treturn -1;\n\t}\n\t\n\tif( control == 0 )\n\t{\n\t\tshear = control_value;\n\t\tdp = vmax = 0;\n\t}\n\telse if( control == 1 )\n\t{\n\t\tdp = control_value;\n\t\tshear = vmax = 0;\n\t}\n\telse if( control == 2 )\n\t{\n\t\tvmax = control_value;\n\t\tdp = shear = 0;\n\t}\n\t\n\t\n\tdouble cmax[3] = {-1.0e20,-1.0e20,-1.0e20}, cmin[3] = {1.0e20,1.0e20,1.0e20};\n\tfor(Mesh::iteratorNode n = m->BeginNode(); n != m->EndNode(); ++n)\n\t{\n\t\tStorage::real_array c = n->Coords();\n\t\tfor(int k = 0; k < 3; ++k)\n\t\t{\n\t\t\tif( cmax[k] < c[k] ) cmax[k] = c[k];\n\t\t\tif( cmin[k] > c[k] ) cmin[k] = c[k];\n\t\t}\n\t}\n\tLen = cmax[axis] - cmin[axis];\n\tDiam = std::max(cmax[(axis+1)%3]-cmin[(axis+1)%3],cmax[(axis+2)%3]-cmin[(axis+2)%3]);\n\t\t\t\n\t\n\tif( shear )\n\t{\n\t\tdp = 4*Len\/Diam*shear*visc;\n\t\tvmax = Diam*Diam*dp\/(16*visc*Len);\n\t}\n\telse if( dp )\n\t{\n\t\tvmax = Diam*Diam*dp\/(16*visc*Len);\n\t\tshear = 4*vmax\/Diam;\n\t}\n\telse if( vmax )\n\t{\n\t\tshear = 4*vmax\/Diam;\n\t\tdp = 4*Len\/Diam*shear*visc;\n\t}\n\t\n\tstd::cout << \"viscosity \" << visc << \" shear \" << shear << \" dp \" << dp << \" vmax \" << vmax << \" length \" << Len << \" diameter \" << Diam << std::endl;\n\t\n\t\/\/TagRealArray force = m->CreateTag(\"FORCE\",DATA_REAL,CELL,NONE,3);\n\tTagRealArray bc = m->CreateTag(\"BOUNDARY_CONDITION_VELOCITY\",DATA_REAL,FACE,FACE,7);\n\tTagReal bcp = m->CreateTag(\"BOUNDARY_CONDITION_PRESSURE\",DATA_REAL,FACE,FACE,1);\n\tTagRealArray uvw = m->CreateTag(\"UVW\",DATA_REAL,CELL,NONE,3);\n\tTagRealArray uvw_ref = m->CreateTag(\"REFERENCE_VELOCITY\",DATA_REAL,CELL,NONE,3); \/\/depends on viscosity\n\tTagReal p_ref = m->CreateTag(\"REFERENCE_PRESSURE\",DATA_REAL,CELL,NONE,1);\n\tTagReal p = m->CreateTag(\"P\",DATA_REAL,CELL,NONE,1);\n\t\n\t\n\t\n\t\/\/this should not be needed?\n\tfor(Mesh::iteratorFace it = m->BeginFace(); it != m->EndFace(); ++it) if( it->Boundary() )\n\t\tit->FixNormalOrientation();\n\t\n\tdouble cnt0[3];\n\tcnt0[axis] = 0;\n\tcnt0[(axis+1)%2] = (cmax[(axis+1)%2] + cmin[(axis+1)%2])*0.5;\n\tcnt0[(axis+2)%2] = (cmax[(axis+2)%2] + cmin[(axis+2)%2])*0.5;\n\tfor(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); ++it)\n\t{\n\t\tdouble cnt[3];\n\t\tit->Barycenter(cnt);\n\t\tdouble r = sqrt(pow(cnt[(axis+1)%2]-cnt0[(axis+1)%2],2)+pow(cnt[(axis+2)%2]-cnt0[(axis+2)%2],2));\n\t\tuvw(*it,3,1).Zero();\n\t\tp[*it] = 0;\n\t\tuvw_ref(*it,3,1).Zero();\n\t\tuvw_ref(*it,3,1)(axis,0) = (Diam*Diam\/4.0-r*r)*dp\/(4.0*visc*Len);\n\t\tp_ref[*it] = dp*(cnt[axis]-cmin[axis])\/Len;\n\t}\n\t\n\t\n\t\n\tfor(Mesh::iteratorFace it = m->BeginFace(); it != m->EndFace(); ++it) if( it->Boundary() )\n\t{\n\t\tdouble n[3];\n\t\tit->UnitNormal(n);\n\t\tif( fabs(n[axis]-1) < 1.0e-3 ) \/\/ outflow\n\t\t{\n\t\t\tbcp[*it] = 0+10;\n\t\t}\n\t\telse if( fabs(n[axis]+1) < 1.0e-3 ) \/\/inflow\n\t\t{\n\t\t\tbcp[*it] = dp+10;\n\t\t}\n\t\telse \/\/no-slip walls\n\t\t{\n\t\t\tbc[*it][0] = 1;\n\t\t\tbc[*it][1] = 0;\n\t\t\tbc[*it][2] = 1;\n\t\t\tbc[*it][3] = 0;\n\t\t\tbc[*it][4] = 0;\n\t\t\tbc[*it][5] = 0;\n\t\t\tbc[*it][6] = 0;\n\t\t}\n\t}\n\t\n\tstd::cout << \"Saving output to \" << fout << std::endl;\n\t\n\tm->Save(fout);\n\t\n\treturn 0;\n}\nsync N-S pousielle test#include \"inmost.h\"\n\nusing namespace INMOST;\n\n\/\/TODO:\n\/\/attach scale to rescale grid\n\/\/attach slice grid to cut cylinder\n\/\/option to set shear rate \/ pressure drop \/ maximum velocity\n\/\/setup BC\n\/\/cmake compilation\n\n\/\/setup on mesh:\n\/\/\n\/\/ FORCE - 3 entries\n\/\/\n\/\/ BOUNDARY_CONDITION_VELOCITY - 7 entries\n\/\/ r = (a5,a6,a7)\n\/\/ n.(a1*u + a2*t) = n.r\n\/\/ (I - nn.)(a3*u + a4*t) = (I-nn.)r\n\/\/\n\/\/ BOUNDARY_CONDITION_PRESSURE - 1 entry\n\/\/\n\/\/ REFERENCE_VELOCITY - 3 entries\n\/\/\n\/\/ REFERENCE_PRESSURE - 1 entry\n\/\/\n\n\n\ntypedef Storage::real real;\n\n\n\nint main(int argc, char ** argv)\n{\n\t\n\tif( argc < 2 )\n\t{\n\t\tstd::cout << \"Usage: \" << argv[0] << \" mesh [axis=2 (0:x,1:y,2:z)] [control=0 (0:shear rate,1:pressure drop,2:maximal velocity)] [control_value=10] [visc=1.0e-5] [mesh_out=grid_out.pmf] [addsym=0]\" << std::endl;\n\t\treturn 0;\n\t}\n\t\n\tMesh * m = new Mesh;\n\tm->SetFileOption(\"VERBOSITY\",\"2\");\n\ttry\n\t{\n\t\tm->Load(argv[1]);\n\t}\n\tcatch(...)\n\t{\n\t\tstd::cout << \"Cannot load the mesh \" << argv[1] << std::endl;\n\t\treturn -1;\n\t}\n\t\n\tstd::string fout = \"grid_out.pmf\";\n\tint axis = 2;\n\tdouble visc = 1.0e-5;\n\tint control = 0;\n\tdouble control_value = 10;\n\tdouble Len = 8;\n\tdouble Diam = 1;\n\tdouble shear = 10;\/\/0; \/\/shear rate\n\tdouble dp = 0;\/\/36e-6;\n\tdouble vmax = 0;\n\tdouble addsym = 0;\n\n\tif( argc > 2 ) axis = atoi(argv[2]);\n\tif( argc > 3 ) control = atoi(argv[3]);\n\tif( argc > 4 ) control_value = atof(argv[4]);\n\tif( argc > 5 ) visc = atof(argv[5]);\n\tif( argc > 6 ) fout = std::string(argv[6]);\n\tif( argc > 7 ) addsym = atof(argv[7]);\n\t\n\t\n\t\n\tif( axis < 0 || axis > 2 )\n\t{\n\t\tstd::cout << \"bad axis: \" << axis << \" should be 0 - x, 1 - y, 2 - z\" << std::endl;\n\t\treturn -1;\n\t}\n\t\n\tif( control < 0 || control > 2 )\n\t{\n\t\tstd::cout << \"bad control: \" << control << \" should be 0 - shear rate, 1 - pressure drop, 2 - maximal velocity\" << std::endl;\n\t\treturn -1;\n\t}\n\t\n\tif( visc <= 0 )\n\t{\n\t\tstd::cout << \"bad viscosity: \" << visc << std::endl;\n\t\treturn -1;\n\t}\n\t\n\tif( control == 0 )\n\t{\n\t\tshear = control_value;\n\t\tdp = vmax = 0;\n\t}\n\telse if( control == 1 )\n\t{\n\t\tdp = control_value;\n\t\tshear = vmax = 0;\n\t}\n\telse if( control == 2 )\n\t{\n\t\tvmax = control_value;\n\t\tdp = shear = 0;\n\t}\n\t\n\t\n\tdouble cmax[3] = {-1.0e20,-1.0e20,-1.0e20}, cmin[3] = {1.0e20,1.0e20,1.0e20};\n\tfor(Mesh::iteratorNode n = m->BeginNode(); n != m->EndNode(); ++n)\n\t{\n\t\tStorage::real_array c = n->Coords();\n\t\tfor(int k = 0; k < 3; ++k)\n\t\t{\n\t\t\tif( cmax[k] < c[k] ) cmax[k] = c[k];\n\t\t\tif( cmin[k] > c[k] ) cmin[k] = c[k];\n\t\t}\n\t}\n\tLen = cmax[axis] - cmin[axis];\n\tDiam = std::max(cmax[(axis+1)%3]-cmin[(axis+1)%3],cmax[(axis+2)%3]-cmin[(axis+2)%3]);\n\t\t\t\n\t\n\tif( shear )\n\t{\n\t\tdp = 4*Len\/Diam*shear*visc;\n\t\tvmax = Diam*Diam*dp\/(16*visc*Len);\n\t}\n\telse if( dp )\n\t{\n\t\tvmax = Diam*Diam*dp\/(16*visc*Len);\n\t\tshear = 4*vmax\/Diam;\n\t}\n\telse if( vmax )\n\t{\n\t\tshear = 4*vmax\/Diam;\n\t\tdp = 4*Len\/Diam*shear*visc;\n\t}\n\t\n\tstd::cout << \"viscosity \" << visc << \" shear \" << shear << \" dp \" << dp << \" vmax \" << vmax << \" length \" << Len << \" diameter \" << Diam << std::endl;\n\t\n\t\/\/TagRealArray force = m->CreateTag(\"FORCE\",DATA_REAL,CELL,NONE,3);\n\tTagRealArray bc = m->CreateTag(\"BOUNDARY_CONDITION_VELOCITY\",DATA_REAL,FACE,FACE,7);\n\tTagReal bcp = m->CreateTag(\"BOUNDARY_CONDITION_PRESSURE\",DATA_REAL,FACE,FACE,1);\n\tTagRealArray uvw = m->CreateTag(\"UVW\",DATA_REAL,CELL,NONE,3);\n\tTagRealArray uvw_ref = m->CreateTag(\"REFERENCE_VELOCITY\",DATA_REAL,CELL,NONE,3); \/\/depends on viscosity\n\tTagReal p_ref = m->CreateTag(\"REFERENCE_PRESSURE\",DATA_REAL,CELL,NONE,1);\n\tTagReal p = m->CreateTag(\"P\",DATA_REAL,CELL,NONE,1);\n\t\n\t\n\t\n\t\/\/this should not be needed?\n\tfor(Mesh::iteratorFace it = m->BeginFace(); it != m->EndFace(); ++it) if( it->Boundary() )\n\t\tit->FixNormalOrientation();\n\t\n\tdouble cnt0[3], p0 = 10;\n\tcnt0[axis] = 0;\n\tcnt0[(axis+1)%2] = (cmax[(axis+1)%2] + cmin[(axis+1)%2])*0.5;\n\tcnt0[(axis+2)%2] = (cmax[(axis+2)%2] + cmin[(axis+2)%2])*0.5;\n\tstd::cout << \"center \" << cnt0[0] << \" \" << cnt0[1] << \" \" << cnt0[2] << std::endl;\n\t\n\tfor(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); ++it)\n\t{\n\t\tdouble cnt[3];\n\t\tit->Barycenter(cnt);\n\t\tdouble r = sqrt(pow(cnt[(axis+1)%2]-cnt0[(axis+1)%2],2)+pow(cnt[(axis+2)%2]-cnt0[(axis+2)%2],2));\n\t\tuvw(*it,3,1).Zero();\n\t\tp[*it] = 0;\n\t\tuvw_ref(*it,3,1).Zero();\n\t\tuvw_ref(*it,3,1)(axis,0) = (Diam*Diam\/4.0-r*r)*dp\/(4.0*visc*Len);\n\t\tp_ref[*it] = p0 + dp*(cmax[axis] - cnt[axis])\/Len - 0.5*addsym*uvw_ref(*it,3,1).DotProduct(uvw_ref(*it,3,1));\n\t}\n\t\n\t\n\t\n\tfor(Mesh::iteratorFace it = m->BeginFace(); it != m->EndFace(); ++it) if( it->Boundary() )\n\t{\n\t\tdouble n[3];\n\t\tit->UnitNormal(n);\n\t\tif( fabs(n[axis]-1) < 1.0e-3 ) \/\/ outflow\n\t\t{\n\t\t\tbcp[*it] = 0+p0;\n\t\t}\n\t\telse if( fabs(n[axis]+1) < 1.0e-3 ) \/\/inflow\n\t\t{\n\t\t\tbcp[*it] = dp+p0;\n\t\t}\n\t\telse \/\/no-slip walls\n\t\t{\n\t\t\tbc[*it][0] = 1;\n\t\t\tbc[*it][1] = 0;\n\t\t\tbc[*it][2] = 1;\n\t\t\tbc[*it][3] = 0;\n\t\t\tbc[*it][4] = 0;\n\t\t\tbc[*it][5] = 0;\n\t\t\tbc[*it][6] = 0;\n\t\t}\n\t}\n\t\n\tstd::cout << \"Saving output to \" << fout << std::endl;\n\t\n\tm->Save(fout);\n\t\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/** @copyright\n * Copyright (c) 2018, Stuart W Baker\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * @file TivaCanNullTx.hxx\n * This file implements a test driver for CAN on Tiva.\n *\n * @author Stuart W. Baker\n * @date 6 June 2018\n *\/\n\n#ifndef _FREERTOS_DRIVERS_TI_TIVACANNULLTX_HXX_\n#define _FREERTOS_DRIVERS_TI_TIVACANNULLTX_HXX_\n\n#include \"TivaDev.hxx\"\n\n\/** Specialization of Tiva CAN driver for testing purposes.\n *\/\nclass TivaCanNullTx : public TivaCan\n{\npublic:\n \/** Constructor.\n * @param name name of this device instance in the file system\n * @param base base address of this device\n * @param interrupt interrupt number of this device\n *\/\n TivaCanNullTx(const char *name, unsigned long base, uint32_t interrupt)\n : TivaCan(name, base, interrupt)\n , readTimeFirst_(0)\n , readTime10000_(0)\n , readCount_(0)\n {\n }\n\n \/** Destructor.\n *\/\n ~TivaCanNullTx()\n {\n }\n\n \/** Get the latest performance time stamp.\n * @param count the number of messages that have been received in total\n * @return if count < @ref MESSAGE_COUNT, the time since the first message\n * was received, else, the time between the first message received\n * and the 10,000th message received.\n *\/\n long long get_timestamp_and_count(unsigned *count)\n {\n long long result;\n\n portENTER_CRITICAL();\n *count = readCount_;\n if (readCount_ >= MESSAGE_COUNT)\n {\n result = readTime10000_ - readTimeFirst_;\n }\n else\n {\n result = OSTime::get_monotonic() - readTimeFirst_;\n }\n portEXIT_CRITICAL();\n\n return result;\n }\n\nprivate:\n static constexpr size_t MESSAGE_COUNT = 10000;\n\n \/** Read from a file or device.\n * @param file file reference for this device\n * @param buf location to place read data\n * @param count number of bytes to read\n * @return number of bytes read upon success, -1 upon failure with errno\n * containing the cause\n *\/\n ssize_t read(File *file, void *buf, size_t count) override\n {\n if (readCount_ == 0)\n {\n readTimeFirst_ = OSTime::get_monotonic();\n }\n\n ssize_t result = Can::read(file, buf, count);\n\n if (result > 0)\n {\n readCount_ += result \/ sizeof(struct can_frame);\n\n if (readCount_ >= MESSAGE_COUNT && readTime10000_ == 0)\n {\n readTime10000_ = OSTime::get_monotonic();\n }\n }\n\n return result;\n }\n\n \/** Write to a file or device.\n * @param file file reference for this device\n * @param buf location to find write data\n * @param count number of bytes to write\n * @return number of bytes written upon success, -1 upon failure with errno\n * containing the cause\n *\/\n ssize_t write(File *file, const void *buf, size_t count) override\n {\n \/* drop all the write data on the floor *\/\n return count;\n }\n\n long long readTimeFirst_; \/**< timestamp of first read in nsec *\/\n long long readTime10000_; \/**< timestamp of 10,000th read in nsec *\/\n\n size_t readCount_; \/**< running count of all the reads *\/\n\n DISALLOW_COPY_AND_ASSIGN(TivaCanNullTx);\n};\n\n#endif \/* _FREERTOS_DRIVERS_TI_TIVACANNULLTX_HXX_ *\/\nFix the logic to be more time accurate.\/** @copyright\n * Copyright (c) 2018, Stuart W Baker\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * @file TivaCanNullTx.hxx\n * This file implements a test driver for CAN on Tiva.\n *\n * @author Stuart W. Baker\n * @date 6 June 2018\n *\/\n\n#ifndef _FREERTOS_DRIVERS_TI_TIVACANNULLTX_HXX_\n#define _FREERTOS_DRIVERS_TI_TIVACANNULLTX_HXX_\n\n#include \"TivaDev.hxx\"\n\n\/** Specialization of Tiva CAN driver for testing purposes.\n *\/\nclass TivaCanNullTx : public TivaCan\n{\npublic:\n \/** Constructor.\n * @param name name of this device instance in the file system\n * @param base base address of this device\n * @param interrupt interrupt number of this device\n *\/\n TivaCanNullTx(const char *name, unsigned long base, uint32_t interrupt)\n : TivaCan(name, base, interrupt)\n , readTimeFirst_(0)\n , readTime10000_(0)\n , readCount_(0)\n {\n }\n\n \/** Destructor.\n *\/\n ~TivaCanNullTx()\n {\n }\n\n \/** Get the latest performance time stamp.\n * @param count the number of messages that have been received in total\n * @return if count < @ref MESSAGE_COUNT, the time since the first message\n * was received, else, the time between the first message received\n * and the 10,000th message received.\n *\/\n long long get_timestamp_and_count(unsigned *count)\n {\n long long result;\n\n portENTER_CRITICAL();\n *count = readCount_;\n if (readCount_ >= MESSAGE_COUNT)\n {\n result = readTime10000_ - readTimeFirst_;\n }\n else\n {\n result = OSTime::get_monotonic() - readTimeFirst_;\n }\n portEXIT_CRITICAL();\n\n return result;\n }\n\nprivate:\n static constexpr size_t MESSAGE_COUNT = 10000;\n\n \/** Read from a file or device.\n * @param file file reference for this device\n * @param buf location to place read data\n * @param count number of bytes to read\n * @return number of bytes read upon success, -1 upon failure with errno\n * containing the cause\n *\/\n ssize_t read(File *file, void *buf, size_t count) override\n {\n ssize_t result = Can::read(file, buf, count);\n\n if (result > 0)\n {\n if (readCount_ == 0)\n {\n readTimeFirst_ = OSTime::get_monotonic();\n }\n\n readCount_ += result \/ sizeof(struct can_frame);\n\n if (readCount_ >= MESSAGE_COUNT && readTime10000_ == 0)\n {\n readTime10000_ = OSTime::get_monotonic();\n }\n }\n\n return result;\n }\n\n \/** Write to a file or device.\n * @param file file reference for this device\n * @param buf location to find write data\n * @param count number of bytes to write\n * @return number of bytes written upon success, -1 upon failure with errno\n * containing the cause\n *\/\n ssize_t write(File *file, const void *buf, size_t count) override\n {\n \/* drop all the write data on the floor *\/\n return count;\n }\n\n long long readTimeFirst_; \/**< timestamp of first read in nsec *\/\n long long readTime10000_; \/**< timestamp of 10,000th read in nsec *\/\n\n size_t readCount_; \/**< running count of all the reads *\/\n\n DISALLOW_COPY_AND_ASSIGN(TivaCanNullTx);\n};\n\n#endif \/* _FREERTOS_DRIVERS_TI_TIVACANNULLTX_HXX_ *\/\n<|endoftext|>"} {"text":"\/\/..............................................................................\n\/\/\n\/\/ This file is part of the Jancy toolkit.\n\/\/\n\/\/ Jancy is distributed under the MIT license.\n\/\/ For details see accompanying license.txt file,\n\/\/ the public copy of which is also available at:\n\/\/ http:\/\/tibbo.com\/downloads\/archive\/jancy\/license.txt\n\/\/\n\/\/..............................................................................\n\n#include \"pch.h\"\n#include \"jnc_io_ChildProcess.h\"\n#include \"jnc_io_IoLib.h\"\n\nnamespace jnc {\nnamespace io {\n\n\/\/..............................................................................\n\n#if (_JNC_OS_WIN)\nbool\ncreateStdioPipe(\n\thandle_t* readHandle,\n\thandle_t* writeHandle,\n\tdword_t readMode,\n\tdword_t writeMode\n\t)\n{\n\tstatic int32_t pipeId = 0;\n\n\tchar buffer[256];wait pid timeout\n\tsl::String_w pipeName(ref::BufKind_Stack, buffer, sizeof(buffer));\n\tpipeName.format(\n\t\tL\"\\\\\\\\.\\\\pipe\\\\jnc.ChildProcess.%p.%d\",\n\t\tsys::getCurrentProcessId(),\n\t\tsys::atomicInc(&pipeId)\n\t\t);\n\n\taxl::io::win::NamedPipe pipe;\n\taxl::io::win::File file;\n\n\tSECURITY_ATTRIBUTES secAttr = { 0 };\n\tsecAttr.nLength = sizeof(SECURITY_ATTRIBUTES);\n\tsecAttr.bInheritHandle = true;\n\n\tbool result =\n\t\tpipe.create(\n\t\t\tpipeName,\n\t\t\tPIPE_ACCESS_INBOUND | readMode,\n\t\t\tPIPE_TYPE_BYTE | PIPE_READMODE_BYTE,\n\t\t\t1,\n\t\t\t0, 0, 0,\n\t\t\t&secAttr\n\t\t\t) &&\n\t\tfile.create(\n\t\t\tpipeName,\n\t\t\tGENERIC_WRITE,\n\t\t\t0,\n\t\t\t&secAttr,\n\t\t\tOPEN_EXISTING,\n\t\t\twriteMode\n\t\t\t);\n\n\tif (!result)\n\t\treturn false;\n\n\t*readHandle = pipe.detach();\n\t*writeHandle = file.detach();\n\treturn true;\n}\n#else\nbool\nexec(const char* commandLine)\n{\n\tchar buffer[256];\n\tsl::Array argv(ref::BufKind_Stack, buffer, sizeof(buffer));\n\n\tsl::String string = commandLine;\n\n\tsize_t length = string.getLength();\n\tfor (;;)\n\t{\n\t\tstring.trimLeft();\n\t\tif (string.isEmpty())\n\t\t\tbreak;\n\n\t\targv.append(string.p());\n\n\t\tsize_t pos = string.findOneOf(sl::StringDetails::getWhitespace());\n\t\tif (pos == -1)\n\t\t\tbreak;\n\n\t\tstring[pos] = 0;\n\t\tstring = string.getSubString(pos + 1);\n\t}\n\n\tif (argv.isEmpty())\n\t{\n\t\terr::setError(\"empty command line\");\n\t\treturn false;\n\t}\n\n\targv.append(NULL);\n\tint result = ::execvp(argv[0], argv.p());\n\tASSERT(result == -1);\n\terr::setLastSystemError();\n\treturn false;\n}\n#endif\n\n\/\/..............................................................................\n\nJNC_DEFINE_OPAQUE_CLASS_TYPE(\n\tChildProcess,\n\t\"io.ChildProcess\",\n\tg_ioLibGuid,\n\tIoLibCacheSlot_ChildProcess,\n\tChildProcess,\n\tNULL\n\t)\n\nJNC_BEGIN_TYPE_FUNCTION_MAP(ChildProcess)\n\tJNC_MAP_CONSTRUCTOR(&jnc::construct)\n\tJNC_MAP_DESTRUCTOR(&jnc::destruct)\n\tJNC_MAP_FUNCTION(\"start\", &ChildProcess::start)\n\tJNC_MAP_FUNCTION(\"close\", &ChildProcess::close)\n\tJNC_MAP_FUNCTION(\"wait\", &ChildProcess::wait)\n\tJNC_MAP_FUNCTION(\"waitAndClose\", &ChildProcess::waitAndClose)\n\tJNC_MAP_FUNCTION(\"terminate\", &ChildProcess::terminate)\nJNC_END_TYPE_FUNCTION_MAP()\n\n\/\/..............................................................................\n\nChildProcess::ChildProcess()\n{\n\tjnc::construct(m_stdin);\n\tjnc::construct(m_stdout);\n\tjnc::construct(m_stderr);\n}\n\nChildProcess::~ChildProcess()\n{\n\tclose();\n}\n\nbool\nJNC_CDECL\nChildProcess::start(\n\tDataPtr commandLinePtr,\n\tuint_t flags\n\t)\n{\n\tclose();\n\n\tbool isMergedStdoutStderr = (flags & ChildProcessFlag_MergeStdoutStderr) != 0;\n\n#if (_JNC_OS_WIN)\n\tsl::String_w cmdLine = (char*)commandLinePtr.m_p;\n\n\tbool_t result;\n\n\taxl::io::win::File parentStdin;\n\taxl::io::win::File parentStdout;\n\taxl::io::win::File parentStderr;\n\taxl::io::win::File childStdin;\n\taxl::io::win::File childStdout;\n\taxl::io::win::File childStderr;\n\n\tresult =\n\t\tcreateStdioPipe(childStdin.p(), parentStdin.p(), 0, FILE_FLAG_OVERLAPPED) &&\n\t\tcreateStdioPipe(parentStdout.p(), childStdout.p(), FILE_FLAG_OVERLAPPED, 0) &&\n\t\t(isMergedStdoutStderr || createStdioPipe(parentStderr.p(), childStderr.p(), FILE_FLAG_OVERLAPPED, 0));\n\n\tif (!result)\n\t\treturn false;\n\n\tSTARTUPINFOW startupInfo = { 0 };\n\tstartupInfo.cb = sizeof(STARTUPINFO);\n\tstartupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;\n\tstartupInfo.hStdInput = childStdin;\n\tstartupInfo.hStdOutput = childStdout;\n\tstartupInfo.hStdError = isMergedStdoutStderr ? childStdout : childStderr;\n\tstartupInfo.wShowWindow = SW_HIDE;\n\n\tresult = m_process.createProcess(cmdLine, true, CREATE_NEW_CONSOLE, &startupInfo);\n\tif (!result)\n\t\treturn false;\n\n\tattachFileStream(m_stdin, &parentStdin);\n\tattachFileStream(m_stdout, &parentStdout);\n\tattachFileStream(m_stderr, &parentStderr);\n#else\n\taxl::io::psx::Pipe stdinPipe;\n\taxl::io::psx::Pipe stdoutPipe;\n\taxl::io::psx::Pipe stderrPipe;\n\n\tbool result =\n\t\tstdinPipe.create() &&\n\t\tstdinPipe.m_writeFile.setBlockingMode(false) &&\n\t\tstdoutPipe.create() &&\n\t\tstdoutPipe.m_readFile.setBlockingMode(false) &&\n\t\t(isMergedStdoutStderr ||\n\t\tstderrPipe.create() &&\n\t\tstderrPipe.m_readFile.setBlockingMode(false));\n\n\tif (!result)\n\t\treturn false;\n\n\tpid_t pid = ::fork();\n\tswitch (pid)\n\t{\n\tcase -1:\n\t\terr::setLastSystemError();\n\t\treturn false;\n\n\tcase 0:\n\t\t::dup2(stdinPipe.m_readFile, STDIN_FILENO);\n\t\t::dup2(stdoutPipe.m_writeFile, STDOUT_FILENO);\n\t\t::dup2(isMergedStdoutStderr ? stdoutPipe.m_writeFile : stderrPipe.m_writeFile, STDERR_FILENO);\n\n\t\texec((char*)commandLinePtr.m_p);\n\n\t\t::fprintf(stderr, \"POSIX exec error: %s\\n\", err::getLastErrorDescription().sz());\n\t\t::abort();\n\t\tASSERT(false);\n\n\tdefault:\n\t\tm_pid = pid;\n\t}\n\n\tattachFileStream(m_stdin, &stdinPipe.m_writeFile);\n\tattachFileStream(m_stdout, &stdoutPipe.m_readFile);\n\tattachFileStream(m_stderr, &stderrPipe.m_readFile);\n#endif\n\n\treturn true;\n}\n\nvoid\nJNC_CDECL\nChildProcess::close()\n{\n\tm_stdin->close();\n\tm_stdout->close();\n\tm_stderr->close();\n#if (_JNC_OS_WIN)\n\tm_process.close();\n#endif\n}\n\nuint_t\nJNC_CDECL\nChildProcess::getExitCode()\n{\n#if (_JNC_OS_WIN)\n\tdword_t exitCode = 0;\n\tm_process.getExitCode(&exitCode);\n\treturn exitCode;\n#endif\n\treturn 0;\n}\n\nbool\nJNC_CDECL\nChildProcess::wait(uint_t timeout)\n{\n\treturn true;\n}\n\nvoid\nJNC_CDECL\nChildProcess::waitAndClose(uint_t timeout)\n{\n\tclose();\n}\n\nbool\nJNC_CDECL\nChildProcess::terminate()\n{\n\treturn true;\n}\n\nvoid\nChildProcess::attachFileStream(\n\tio::FileStream* fileStream,\n\tAxlOsFile* file\n\t)\n{\n\tfileStream->close();\n\n\tif (!file->isOpen())\n\t\treturn;\n\n\tfileStream->m_file.m_file.attach(file->detach());\n\tfileStream->m_fileStreamKind = FileStreamKind_Pipe;\n\/*\tfileStream->setReadParallelism(m_readParallelism);\n\tfileStream->setReadBlockSize(m_readBlockSize);\n\tfileStream->setReadBufferSize(m_readBufferSize);\n\tfileStream->setWriteBufferSize(m_writeBufferSize);\n\tfileStream->setOptions(m_options); *\/\n#if (_JNC_OS_WIN)\n\tASSERT(!fileStream->m_overlappedIo);\n\tfileStream->m_overlappedIo = AXL_MEM_NEW(FileStream::OverlappedIo);\n#else\n#endif\n\tfileStream->AsyncIoDevice::open();\n\tfileStream->m_ioThread.start();\n}\n\n\/\/..............................................................................\n\n} \/\/ namespace io\n} \/\/ namespace jnc\n[jnc_io] added proper handling for execvp success\/failure (via a dedicated pipe with FD_CLOEXEC)\/\/..............................................................................\n\/\/\n\/\/ This file is part of the Jancy toolkit.\n\/\/\n\/\/ Jancy is distributed under the MIT license.\n\/\/ For details see accompanying license.txt file,\n\/\/ the public copy of which is also available at:\n\/\/ http:\/\/tibbo.com\/downloads\/archive\/jancy\/license.txt\n\/\/\n\/\/..............................................................................\n\n#include \"pch.h\"\n#include \"jnc_io_ChildProcess.h\"\n#include \"jnc_io_IoLib.h\"\n\nnamespace jnc {\nnamespace io {\n\n\/\/..............................................................................\n\n#if (_JNC_OS_WIN)\nbool\ncreateStdioPipe(\n\thandle_t* readHandle,\n\thandle_t* writeHandle,\n\tdword_t readMode,\n\tdword_t writeMode\n\t)\n{\n\tstatic int32_t pipeId = 0;\n\n\tchar buffer[256];wait pid timeout\n\tsl::String_w pipeName(ref::BufKind_Stack, buffer, sizeof(buffer));\n\tpipeName.format(\n\t\tL\"\\\\\\\\.\\\\pipe\\\\jnc.ChildProcess.%p.%d\",\n\t\tsys::getCurrentProcessId(),\n\t\tsys::atomicInc(&pipeId)\n\t\t);\n\n\taxl::io::win::NamedPipe pipe;\n\taxl::io::win::File file;\n\n\tSECURITY_ATTRIBUTES secAttr = { 0 };\n\tsecAttr.nLength = sizeof(SECURITY_ATTRIBUTES);\n\tsecAttr.bInheritHandle = true;\n\n\tbool result =\n\t\tpipe.create(\n\t\t\tpipeName,\n\t\t\tPIPE_ACCESS_INBOUND | readMode,\n\t\t\tPIPE_TYPE_BYTE | PIPE_READMODE_BYTE,\n\t\t\t1,\n\t\t\t0, 0, 0,\n\t\t\t&secAttr\n\t\t\t) &&\n\t\tfile.create(\n\t\t\tpipeName,\n\t\t\tGENERIC_WRITE,\n\t\t\t0,\n\t\t\t&secAttr,\n\t\t\tOPEN_EXISTING,\n\t\t\twriteMode\n\t\t\t);\n\n\tif (!result)\n\t\treturn false;\n\n\t*readHandle = pipe.detach();\n\t*writeHandle = file.detach();\n\treturn true;\n}\n#else\nvoid\nexec(const char* commandLine) \/\/ returns on failure only\n{\n\tchar buffer[256];\n\tsl::Array argv(ref::BufKind_Stack, buffer, sizeof(buffer));\n\n\tsl::String string = commandLine;\n\n\tsize_t length = string.getLength();\n\tfor (;;)\n\t{\n\t\tstring.trimLeft();\n\t\tif (string.isEmpty())\n\t\t\tbreak;\n\n\t\targv.append(string.p());\n\n\t\tsize_t pos = string.findOneOf(sl::StringDetails::getWhitespace());\n\t\tif (pos == -1)\n\t\t\tbreak;\n\n\t\tstring[pos] = 0;\n\t\tstring = string.getSubString(pos + 1);\n\t}\n\n\tif (argv.isEmpty())\n\t{\n\t\terr::setError(\"empty command line\");\n\t\treturn;\n\t}\n\n\targv.append(NULL);\n\n\tint result = ::execvp(argv[0], argv.p());\n\tASSERT(result == -1);\n\terr::setLastSystemError();\n}\n#endif\n\n\/\/..............................................................................\n\nJNC_DEFINE_OPAQUE_CLASS_TYPE(\n\tChildProcess,\n\t\"io.ChildProcess\",\n\tg_ioLibGuid,\n\tIoLibCacheSlot_ChildProcess,\n\tChildProcess,\n\tNULL\n\t)\n\nJNC_BEGIN_TYPE_FUNCTION_MAP(ChildProcess)\n\tJNC_MAP_CONSTRUCTOR(&jnc::construct)\n\tJNC_MAP_DESTRUCTOR(&jnc::destruct)\n\tJNC_MAP_FUNCTION(\"start\", &ChildProcess::start)\n\tJNC_MAP_FUNCTION(\"close\", &ChildProcess::close)\n\tJNC_MAP_FUNCTION(\"wait\", &ChildProcess::wait)\n\tJNC_MAP_FUNCTION(\"waitAndClose\", &ChildProcess::waitAndClose)\n\tJNC_MAP_FUNCTION(\"terminate\", &ChildProcess::terminate)\nJNC_END_TYPE_FUNCTION_MAP()\n\n\/\/..............................................................................\n\nChildProcess::ChildProcess()\n{\n\tjnc::construct(m_stdin);\n\tjnc::construct(m_stdout);\n\tjnc::construct(m_stderr);\n}\n\nChildProcess::~ChildProcess()\n{\n\tclose();\n}\n\nbool\nJNC_CDECL\nChildProcess::start(\n\tDataPtr commandLinePtr,\n\tuint_t flags\n\t)\n{\n\tclose();\n\n\tbool isMergedStdoutStderr = (flags & ChildProcessFlag_MergeStdoutStderr) != 0;\n\n#if (_JNC_OS_WIN)\n\tsl::String_w cmdLine = (char*)commandLinePtr.m_p;\n\n\tbool_t result;\n\n\taxl::io::win::File parentStdin;\n\taxl::io::win::File parentStdout;\n\taxl::io::win::File parentStderr;\n\taxl::io::win::File childStdin;\n\taxl::io::win::File childStdout;\n\taxl::io::win::File childStderr;\n\n\tresult =\n\t\tcreateStdioPipe(childStdin.p(), parentStdin.p(), 0, FILE_FLAG_OVERLAPPED) &&\n\t\tcreateStdioPipe(parentStdout.p(), childStdout.p(), FILE_FLAG_OVERLAPPED, 0) &&\n\t\t(isMergedStdoutStderr || createStdioPipe(parentStderr.p(), childStderr.p(), FILE_FLAG_OVERLAPPED, 0));\n\n\tif (!result)\n\t\treturn false;\n\n\tSTARTUPINFOW startupInfo = { 0 };\n\tstartupInfo.cb = sizeof(STARTUPINFO);\n\tstartupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;\n\tstartupInfo.hStdInput = childStdin;\n\tstartupInfo.hStdOutput = childStdout;\n\tstartupInfo.hStdError = isMergedStdoutStderr ? childStdout : childStderr;\n\tstartupInfo.wShowWindow = SW_HIDE;\n\n\tresult = m_process.createProcess(cmdLine, true, CREATE_NEW_CONSOLE, &startupInfo);\n\tif (!result)\n\t\treturn false;\n\n\tattachFileStream(m_stdin, &parentStdin);\n\tattachFileStream(m_stdout, &parentStdout);\n\tattachFileStream(m_stderr, &parentStderr);\n#else\n\taxl::io::psx::Pipe stdinPipe;\n\taxl::io::psx::Pipe stdoutPipe;\n\taxl::io::psx::Pipe stderrPipe;\n\taxl::io::psx::Pipe execPipe;\n\n\tbool result =\n\t\tstdinPipe.create() &&\n\t\tstdinPipe.m_writeFile.setBlockingMode(false) &&\n\t\tstdoutPipe.create() &&\n\t\tstdoutPipe.m_readFile.setBlockingMode(false) &&\n\t\t(isMergedStdoutStderr ||\n\t\tstderrPipe.create() &&\n\t\tstderrPipe.m_readFile.setBlockingMode(false)) &&\n\t\texecPipe.create();\n\n\tif (!result)\n\t\treturn false;\n\n\texecPipe.m_writeFile.fcntl(F_SETFD, FD_CLOEXEC);\n\n\terr::Error error;\n\n\tpid_t pid = ::fork();\n\tswitch (pid)\n\t{\n\tcase -1:\n\t\terr::setLastSystemError();\n\t\treturn false;\n\n\tcase 0:\n\t\t::dup2(stdinPipe.m_readFile, STDIN_FILENO);\n\t\t::dup2(stdoutPipe.m_writeFile, STDOUT_FILENO);\n\t\t::dup2(isMergedStdoutStderr ? stdoutPipe.m_writeFile : stderrPipe.m_writeFile, STDERR_FILENO);\n\n\t\texec((char*)commandLinePtr.m_p);\n\n\t\terror = err::getLastError();\n\t\texecPipe.m_writeFile.write(error, error->m_size);\n\t\texecPipe.m_writeFile.flush();\n\n\t\t::_exit(-1);\n\t\tASSERT(false);\n\n\tdefault:\n\t\texecPipe.m_writeFile.close();\n\n\t\tfd_set rdset;\n\t\tFD_ZERO(&rdset);\n\t\tFD_SET(execPipe.m_readFile, &rdset);\n\n\t\tchar buffer[256];\n\t\tsize_t size = execPipe.m_readFile.read(buffer, sizeof(buffer));\n\t\tif (size == 0 || size == -1)\n\t\t{\n\t\t\tm_pid = pid;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (((err::ErrorHdr*)buffer)->m_size == size)\n\t\t\terr::setError((err::ErrorHdr*)buffer);\n\t\telse\n\t\t\terr::setError(\"POSIX execvp failed\"); \/\/ unlikely fallback\n\n\t\treturn false;\n\t}\n\n\tattachFileStream(m_stdin, &stdinPipe.m_writeFile);\n\tattachFileStream(m_stdout, &stdoutPipe.m_readFile);\n\tattachFileStream(m_stderr, &stderrPipe.m_readFile);\n#endif\n\n\treturn true;\n}\n\nvoid\nJNC_CDECL\nChildProcess::close()\n{\n\tm_stdin->close();\n\tm_stdout->close();\n\tm_stderr->close();\n#if (_JNC_OS_WIN)\n\tm_process.close();\n#endif\n}\n\nuint_t\nJNC_CDECL\nChildProcess::getExitCode()\n{\n#if (_JNC_OS_WIN)\n\tdword_t exitCode = 0;\n\tm_process.getExitCode(&exitCode);\n\treturn exitCode;\n#endif\n\treturn 0;\n}\n\nbool\nJNC_CDECL\nChildProcess::wait(uint_t timeout)\n{\n\treturn true;\n}\n\nvoid\nJNC_CDECL\nChildProcess::waitAndClose(uint_t timeout)\n{\n\tclose();\n}\n\nbool\nJNC_CDECL\nChildProcess::terminate()\n{\n\treturn true;\n}\n\nvoid\nChildProcess::attachFileStream(\n\tio::FileStream* fileStream,\n\tAxlOsFile* file\n\t)\n{\n\tfileStream->close();\n\n\tif (!file->isOpen())\n\t\treturn;\n\n\tfileStream->m_file.m_file.attach(file->detach());\n\tfileStream->m_fileStreamKind = FileStreamKind_Pipe;\n\/*\tfileStream->setReadParallelism(m_readParallelism);\n\tfileStream->setReadBlockSize(m_readBlockSize);\n\tfileStream->setReadBufferSize(m_readBufferSize);\n\tfileStream->setWriteBufferSize(m_writeBufferSize);\n\tfileStream->setOptions(m_options); *\/\n#if (_JNC_OS_WIN)\n\tASSERT(!fileStream->m_overlappedIo);\n\tfileStream->m_overlappedIo = AXL_MEM_NEW(FileStream::OverlappedIo);\n#endif\n\tfileStream->AsyncIoDevice::open();\n\tfileStream->m_ioThread.start();\n}\n\n\/\/..............................................................................\n\n} \/\/ namespace io\n} \/\/ namespace jnc\n<|endoftext|>"} {"text":"\/* -*- mode: c++; indent-tabs-mode: nil -*- *\/\n\n\/*\n The thaw depth evaluator gets the subsurface temperature.\n This computes the thaw depth over time.\n This is SecondaryVariablesFieldEvaluator and depends on the subsurface temperature, \n\n Authors: Ahmad Jan (jana@ornl.gov)\n*\/\n\n#ifndef AMANZI_FLOWRELATIONS_INITIAL_ELEV_EVALUATOR_\n#define AMANZI_FLOWRELATIONS_INITIAL_ELVE_EVALUATOR_\n\n#include \"Factory.hh\"\n#include \"secondary_variable_field_evaluator.hh\"\n\nnamespace Amanzi {\nnamespace Flow {\n\nclass InitialElevationEvaluator : public SecondaryVariableFieldEvaluator {\n\npublic:\n explicit\n InitialElevationEvaluator(Teuchos::ParameterList& plist);\n InitialElevationEvaluator(const InitialElevationEvaluator& other);\n Teuchos::RCP Clone() const;\n \nprotected:\n \/\/ Required methods from SecondaryVariableFieldEvaluator\n virtual void EvaluateField_(const Teuchos::Ptr& S,\n const Teuchos::Ptr& result);\n virtual void EvaluateFieldPartialDerivative_(const Teuchos::Ptr& S,\n Key wrt_key, const Teuchos::Ptr& result);\n \n \n virtual bool HasFieldChanged(const Teuchos::Ptr& S, Key request);\n \n virtual void EnsureCompatibility(const Teuchos::Ptr& S);\n\n\n bool updated_once_;\n Key domain_;\n Key bp_key_;\nprivate:\n static Utils::RegisteredFactory reg_;\n\n};\n \n} \/\/namespace\n} \/\/namespace \n\n#endif\nfixes mismatched pragma hh protection\/* -*- mode: c++; indent-tabs-mode: nil -*- *\/\n\n\/*\n The thaw depth evaluator gets the subsurface temperature.\n This computes the thaw depth over time.\n This is SecondaryVariablesFieldEvaluator and depends on the subsurface temperature, \n\n Authors: Ahmad Jan (jana@ornl.gov)\n*\/\n\n#pragma once\n\n#include \"Factory.hh\"\n#include \"secondary_variable_field_evaluator.hh\"\n\nnamespace Amanzi {\nnamespace Flow {\n\nclass InitialElevationEvaluator : public SecondaryVariableFieldEvaluator {\n\npublic:\n explicit\n InitialElevationEvaluator(Teuchos::ParameterList& plist);\n InitialElevationEvaluator(const InitialElevationEvaluator& other);\n Teuchos::RCP Clone() const;\n \nprotected:\n \/\/ Required methods from SecondaryVariableFieldEvaluator\n virtual void EvaluateField_(const Teuchos::Ptr& S,\n const Teuchos::Ptr& result);\n virtual void EvaluateFieldPartialDerivative_(const Teuchos::Ptr& S,\n Key wrt_key, const Teuchos::Ptr& result);\n \n \n virtual bool HasFieldChanged(const Teuchos::Ptr& S, Key request);\n \n virtual void EnsureCompatibility(const Teuchos::Ptr& S);\n\n\n bool updated_once_;\n Key domain_;\n Key bp_key_;\nprivate:\n static Utils::RegisteredFactory reg_;\n\n};\n \n} \/\/namespace\n} \/\/namespace \n\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"webrtc\/modules\/audio_coding\/main\/interface\/audio_coding_module.h\"\n#include \"webrtc\/modules\/audio_coding\/main\/interface\/audio_coding_module_typedefs.h\"\n#include \"webrtc\/modules\/interface\/module_common_types.h\"\n#include \"webrtc\/system_wrappers\/interface\/clock.h\"\n#include \"webrtc\/system_wrappers\/interface\/compile_assert.h\"\n#include \"webrtc\/system_wrappers\/interface\/critical_section_wrapper.h\"\n#include \"webrtc\/system_wrappers\/interface\/event_wrapper.h\"\n#include \"webrtc\/system_wrappers\/interface\/scoped_ptr.h\"\n#include \"webrtc\/system_wrappers\/interface\/thread_annotations.h\"\n#include \"webrtc\/system_wrappers\/interface\/thread_wrapper.h\"\n#include \"webrtc\/test\/testsupport\/gtest_disable.h\"\n\nnamespace webrtc {\n\nconst int kSampleRateHz = 16000;\nconst int kNumSamples10ms = kSampleRateHz \/ 100;\nconst int kFrameSizeMs = 10; \/\/ Multiple of 10.\nconst int kFrameSizeSamples = kFrameSizeMs \/ 10 * kNumSamples10ms;\nconst int kPayloadSizeBytes = kFrameSizeSamples * sizeof(int16_t);\nconst uint8_t kPayloadType = 111;\n\nclass RtpUtility {\n public:\n RtpUtility(int samples_per_packet, uint8_t payload_type)\n : samples_per_packet_(samples_per_packet), payload_type_(payload_type) {}\n\n virtual ~RtpUtility() {}\n\n void Populate(WebRtcRTPHeader* rtp_header) {\n rtp_header->header.sequenceNumber = 0xABCD;\n rtp_header->header.timestamp = 0xABCDEF01;\n rtp_header->header.payloadType = payload_type_;\n rtp_header->header.markerBit = false;\n rtp_header->header.ssrc = 0x1234;\n rtp_header->header.numCSRCs = 0;\n rtp_header->frameType = kAudioFrameSpeech;\n\n rtp_header->header.payload_type_frequency = kSampleRateHz;\n rtp_header->type.Audio.channel = 1;\n rtp_header->type.Audio.isCNG = false;\n }\n\n void Forward(WebRtcRTPHeader* rtp_header) {\n ++rtp_header->header.sequenceNumber;\n rtp_header->header.timestamp += samples_per_packet_;\n }\n\n private:\n int samples_per_packet_;\n uint8_t payload_type_;\n};\n\nclass PacketizationCallbackStub : public AudioPacketizationCallback {\n public:\n PacketizationCallbackStub()\n : num_calls_(0),\n crit_sect_(CriticalSectionWrapper::CreateCriticalSection()) {}\n\n virtual int32_t SendData(\n FrameType frame_type,\n uint8_t payload_type,\n uint32_t timestamp,\n const uint8_t* payload_data,\n uint16_t payload_len_bytes,\n const RTPFragmentationHeader* fragmentation) OVERRIDE {\n CriticalSectionScoped lock(crit_sect_.get());\n ++num_calls_;\n return 0;\n }\n\n int num_calls() const {\n CriticalSectionScoped lock(crit_sect_.get());\n return num_calls_;\n }\n\n private:\n int num_calls_ GUARDED_BY(crit_sect_);\n const scoped_ptr crit_sect_;\n};\n\nclass AudioCodingModuleTest : public ::testing::Test {\n protected:\n AudioCodingModuleTest()\n : id_(1),\n rtp_utility_(new RtpUtility(kFrameSizeSamples, kPayloadType)),\n clock_(Clock::GetRealTimeClock()) {}\n\n ~AudioCodingModuleTest() {}\n\n void TearDown() {}\n\n void SetUp() {\n acm_.reset(AudioCodingModule::Create(id_, clock_));\n\n AudioCodingModule::Codec(\"L16\", &codec_, kSampleRateHz, 1);\n codec_.pltype = kPayloadType;\n\n \/\/ Register L16 codec in ACM.\n ASSERT_EQ(0, acm_->RegisterReceiveCodec(codec_));\n ASSERT_EQ(0, acm_->RegisterSendCodec(codec_));\n\n rtp_utility_->Populate(&rtp_header_);\n\n input_frame_.sample_rate_hz_ = kSampleRateHz;\n input_frame_.samples_per_channel_ = kSampleRateHz * 10 \/ 1000; \/\/ 10 ms.\n COMPILE_ASSERT(kSampleRateHz * 10 \/ 1000 <= AudioFrame::kMaxDataSizeSamples,\n audio_frame_too_small);\n memset(input_frame_.data_,\n 0,\n input_frame_.samples_per_channel_ * sizeof(input_frame_.data_[0]));\n\n ASSERT_EQ(0, acm_->RegisterTransportCallback(&packet_cb_));\n }\n\n void InsertPacketAndPullAudio() {\n InsertPacket();\n PullAudio();\n }\n\n void InsertPacket() {\n const uint8_t kPayload[kPayloadSizeBytes] = {0};\n ASSERT_EQ(0,\n acm_->IncomingPacket(kPayload, kPayloadSizeBytes, rtp_header_));\n rtp_utility_->Forward(&rtp_header_);\n }\n\n void PullAudio() {\n AudioFrame audio_frame;\n ASSERT_EQ(0, acm_->PlayoutData10Ms(-1, &audio_frame));\n }\n\n void InsertAudio() { ASSERT_EQ(0, acm_->Add10MsData(input_frame_)); }\n\n void Encode() {\n int32_t encoded_bytes = acm_->Process();\n \/\/ Expect to get one packet with two bytes per sample, or no packet at all,\n \/\/ depending on how many 10 ms blocks go into |codec_.pacsize|.\n EXPECT_TRUE(encoded_bytes == 2 * codec_.pacsize || encoded_bytes == 0);\n }\n\n const int id_;\n scoped_ptr rtp_utility_;\n scoped_ptr acm_;\n PacketizationCallbackStub packet_cb_;\n WebRtcRTPHeader rtp_header_;\n AudioFrame input_frame_;\n CodecInst codec_;\n Clock* clock_;\n};\n\n\/\/ Check if the statistics are initialized correctly. Before any call to ACM\n\/\/ all fields have to be zero.\nTEST_F(AudioCodingModuleTest, DISABLED_ON_ANDROID(InitializedToZero)) {\n AudioDecodingCallStats stats;\n acm_->GetDecodingCallStatistics(&stats);\n EXPECT_EQ(0, stats.calls_to_neteq);\n EXPECT_EQ(0, stats.calls_to_silence_generator);\n EXPECT_EQ(0, stats.decoded_normal);\n EXPECT_EQ(0, stats.decoded_cng);\n EXPECT_EQ(0, stats.decoded_plc);\n EXPECT_EQ(0, stats.decoded_plc_cng);\n}\n\n\/\/ Apply an initial playout delay. Calls to AudioCodingModule::PlayoutData10ms()\n\/\/ should result in generating silence, check the associated field.\nTEST_F(AudioCodingModuleTest, DISABLED_ON_ANDROID(SilenceGeneratorCalled)) {\n AudioDecodingCallStats stats;\n const int kInitialDelay = 100;\n\n acm_->SetInitialPlayoutDelay(kInitialDelay);\n\n int num_calls = 0;\n for (int time_ms = 0; time_ms < kInitialDelay;\n time_ms += kFrameSizeMs, ++num_calls) {\n InsertPacketAndPullAudio();\n }\n acm_->GetDecodingCallStatistics(&stats);\n EXPECT_EQ(0, stats.calls_to_neteq);\n EXPECT_EQ(num_calls, stats.calls_to_silence_generator);\n EXPECT_EQ(0, stats.decoded_normal);\n EXPECT_EQ(0, stats.decoded_cng);\n EXPECT_EQ(0, stats.decoded_plc);\n EXPECT_EQ(0, stats.decoded_plc_cng);\n}\n\n\/\/ Insert some packets and pull audio. Check statistics are valid. Then,\n\/\/ simulate packet loss and check if PLC and PLC-to-CNG statistics are\n\/\/ correctly updated.\nTEST_F(AudioCodingModuleTest, DISABLED_ON_ANDROID(NetEqCalls)) {\n AudioDecodingCallStats stats;\n const int kNumNormalCalls = 10;\n\n for (int num_calls = 0; num_calls < kNumNormalCalls; ++num_calls) {\n InsertPacketAndPullAudio();\n }\n acm_->GetDecodingCallStatistics(&stats);\n EXPECT_EQ(kNumNormalCalls, stats.calls_to_neteq);\n EXPECT_EQ(0, stats.calls_to_silence_generator);\n EXPECT_EQ(kNumNormalCalls, stats.decoded_normal);\n EXPECT_EQ(0, stats.decoded_cng);\n EXPECT_EQ(0, stats.decoded_plc);\n EXPECT_EQ(0, stats.decoded_plc_cng);\n\n const int kNumPlc = 3;\n const int kNumPlcCng = 5;\n\n \/\/ Simulate packet-loss. NetEq first performs PLC then PLC fades to CNG.\n for (int n = 0; n < kNumPlc + kNumPlcCng; ++n) {\n PullAudio();\n }\n acm_->GetDecodingCallStatistics(&stats);\n EXPECT_EQ(kNumNormalCalls + kNumPlc + kNumPlcCng, stats.calls_to_neteq);\n EXPECT_EQ(0, stats.calls_to_silence_generator);\n EXPECT_EQ(kNumNormalCalls, stats.decoded_normal);\n EXPECT_EQ(0, stats.decoded_cng);\n EXPECT_EQ(kNumPlc, stats.decoded_plc);\n EXPECT_EQ(kNumPlcCng, stats.decoded_plc_cng);\n}\n\nTEST_F(AudioCodingModuleTest, VerifyOutputFrame) {\n AudioFrame audio_frame;\n const int kSampleRateHz = 32000;\n EXPECT_EQ(0, acm_->PlayoutData10Ms(kSampleRateHz, &audio_frame));\n EXPECT_EQ(id_, audio_frame.id_);\n EXPECT_EQ(0u, audio_frame.timestamp_);\n EXPECT_GT(audio_frame.num_channels_, 0);\n EXPECT_EQ(kSampleRateHz \/ 100, audio_frame.samples_per_channel_);\n EXPECT_EQ(kSampleRateHz, audio_frame.sample_rate_hz_);\n}\n\nTEST_F(AudioCodingModuleTest, FailOnZeroDesiredFrequency) {\n AudioFrame audio_frame;\n EXPECT_EQ(-1, acm_->PlayoutData10Ms(0, &audio_frame));\n}\n\nclass AudioCodingModuleMtTest : public AudioCodingModuleTest {\n protected:\n static const int kNumPackets = 10000;\n static const int kNumPullCalls = 10000;\n\n AudioCodingModuleMtTest()\n : AudioCodingModuleTest(),\n send_thread_(ThreadWrapper::CreateThread(CbSendThread,\n this,\n kRealtimePriority,\n \"send\")),\n insert_packet_thread_(ThreadWrapper::CreateThread(CbInsertPacketThread,\n this,\n kRealtimePriority,\n \"insert_packet\")),\n pull_audio_thread_(ThreadWrapper::CreateThread(CbPullAudioThread,\n this,\n kRealtimePriority,\n \"pull_audio\")),\n test_complete_(EventWrapper::Create()),\n send_count_(0),\n insert_packet_count_(0),\n pull_audio_count_(0),\n crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),\n next_insert_packet_time_ms_(0),\n fake_clock_(new SimulatedClock(0)) {\n clock_ = fake_clock_;\n }\n\n ~AudioCodingModuleMtTest() {}\n\n void SetUp() {\n AudioCodingModuleTest::SetUp();\n unsigned int thread_id = 0;\n ASSERT_TRUE(send_thread_->Start(thread_id));\n ASSERT_TRUE(insert_packet_thread_->Start(thread_id));\n ASSERT_TRUE(pull_audio_thread_->Start(thread_id));\n }\n\n void TearDown() {\n AudioCodingModuleTest::TearDown();\n pull_audio_thread_->Stop();\n send_thread_->Stop();\n insert_packet_thread_->Stop();\n }\n\n EventTypeWrapper RunTest() { return test_complete_->Wait(60000); }\n\n private:\n static bool CbSendThread(void* context) {\n return reinterpret_cast(context)->CbSendImpl();\n }\n\n \/\/ The send thread doesn't have to care about the current simulated time,\n \/\/ since only the AcmReceiver is using the clock.\n bool CbSendImpl() {\n ++send_count_;\n InsertAudio();\n Encode();\n if (packet_cb_.num_calls() > kNumPackets) {\n CriticalSectionScoped lock(crit_sect_.get());\n if (pull_audio_count_ > kNumPullCalls) {\n \/\/ Both conditions for completion are met. End the test.\n test_complete_->Set();\n }\n }\n return true;\n }\n\n static bool CbInsertPacketThread(void* context) {\n return reinterpret_cast(context)\n ->CbInsertPacketImpl();\n }\n\n bool CbInsertPacketImpl() {\n {\n CriticalSectionScoped lock(crit_sect_.get());\n if (clock_->TimeInMilliseconds() < next_insert_packet_time_ms_) {\n return true;\n }\n next_insert_packet_time_ms_ += 10;\n }\n \/\/ Now we're not holding the crit sect when calling ACM.\n ++insert_packet_count_;\n InsertPacket();\n return true;\n }\n\n static bool CbPullAudioThread(void* context) {\n return reinterpret_cast(context)\n ->CbPullAudioImpl();\n }\n\n bool CbPullAudioImpl() {\n {\n CriticalSectionScoped lock(crit_sect_.get());\n \/\/ Don't let the insert thread fall behind.\n if (next_insert_packet_time_ms_ < clock_->TimeInMilliseconds()) {\n return true;\n }\n ++pull_audio_count_;\n }\n \/\/ Now we're not holding the crit sect when calling ACM.\n PullAudio();\n fake_clock_->AdvanceTimeMilliseconds(10);\n return true;\n }\n\n scoped_ptr send_thread_;\n scoped_ptr insert_packet_thread_;\n scoped_ptr pull_audio_thread_;\n const scoped_ptr test_complete_;\n int send_count_;\n int insert_packet_count_;\n int pull_audio_count_ GUARDED_BY(crit_sect_);\n const scoped_ptr crit_sect_;\n int64_t next_insert_packet_time_ms_ GUARDED_BY(crit_sect_);\n SimulatedClock* fake_clock_;\n};\n\nTEST_F(AudioCodingModuleMtTest, DoTest) {\n EXPECT_EQ(kEventSignaled, RunTest());\n}\n\n} \/\/ namespace webrtc\nDisable AudioCodingModuleMtTest due to memcheck and tsan failures.\/*\n * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"webrtc\/modules\/audio_coding\/main\/interface\/audio_coding_module.h\"\n#include \"webrtc\/modules\/audio_coding\/main\/interface\/audio_coding_module_typedefs.h\"\n#include \"webrtc\/modules\/interface\/module_common_types.h\"\n#include \"webrtc\/system_wrappers\/interface\/clock.h\"\n#include \"webrtc\/system_wrappers\/interface\/compile_assert.h\"\n#include \"webrtc\/system_wrappers\/interface\/critical_section_wrapper.h\"\n#include \"webrtc\/system_wrappers\/interface\/event_wrapper.h\"\n#include \"webrtc\/system_wrappers\/interface\/scoped_ptr.h\"\n#include \"webrtc\/system_wrappers\/interface\/thread_annotations.h\"\n#include \"webrtc\/system_wrappers\/interface\/thread_wrapper.h\"\n#include \"webrtc\/test\/testsupport\/gtest_disable.h\"\n\nnamespace webrtc {\n\nconst int kSampleRateHz = 16000;\nconst int kNumSamples10ms = kSampleRateHz \/ 100;\nconst int kFrameSizeMs = 10; \/\/ Multiple of 10.\nconst int kFrameSizeSamples = kFrameSizeMs \/ 10 * kNumSamples10ms;\nconst int kPayloadSizeBytes = kFrameSizeSamples * sizeof(int16_t);\nconst uint8_t kPayloadType = 111;\n\nclass RtpUtility {\n public:\n RtpUtility(int samples_per_packet, uint8_t payload_type)\n : samples_per_packet_(samples_per_packet), payload_type_(payload_type) {}\n\n virtual ~RtpUtility() {}\n\n void Populate(WebRtcRTPHeader* rtp_header) {\n rtp_header->header.sequenceNumber = 0xABCD;\n rtp_header->header.timestamp = 0xABCDEF01;\n rtp_header->header.payloadType = payload_type_;\n rtp_header->header.markerBit = false;\n rtp_header->header.ssrc = 0x1234;\n rtp_header->header.numCSRCs = 0;\n rtp_header->frameType = kAudioFrameSpeech;\n\n rtp_header->header.payload_type_frequency = kSampleRateHz;\n rtp_header->type.Audio.channel = 1;\n rtp_header->type.Audio.isCNG = false;\n }\n\n void Forward(WebRtcRTPHeader* rtp_header) {\n ++rtp_header->header.sequenceNumber;\n rtp_header->header.timestamp += samples_per_packet_;\n }\n\n private:\n int samples_per_packet_;\n uint8_t payload_type_;\n};\n\nclass PacketizationCallbackStub : public AudioPacketizationCallback {\n public:\n PacketizationCallbackStub()\n : num_calls_(0),\n crit_sect_(CriticalSectionWrapper::CreateCriticalSection()) {}\n\n virtual int32_t SendData(\n FrameType frame_type,\n uint8_t payload_type,\n uint32_t timestamp,\n const uint8_t* payload_data,\n uint16_t payload_len_bytes,\n const RTPFragmentationHeader* fragmentation) OVERRIDE {\n CriticalSectionScoped lock(crit_sect_.get());\n ++num_calls_;\n return 0;\n }\n\n int num_calls() const {\n CriticalSectionScoped lock(crit_sect_.get());\n return num_calls_;\n }\n\n private:\n int num_calls_ GUARDED_BY(crit_sect_);\n const scoped_ptr crit_sect_;\n};\n\nclass AudioCodingModuleTest : public ::testing::Test {\n protected:\n AudioCodingModuleTest()\n : id_(1),\n rtp_utility_(new RtpUtility(kFrameSizeSamples, kPayloadType)),\n clock_(Clock::GetRealTimeClock()) {}\n\n ~AudioCodingModuleTest() {}\n\n void TearDown() {}\n\n void SetUp() {\n acm_.reset(AudioCodingModule::Create(id_, clock_));\n\n AudioCodingModule::Codec(\"L16\", &codec_, kSampleRateHz, 1);\n codec_.pltype = kPayloadType;\n\n \/\/ Register L16 codec in ACM.\n ASSERT_EQ(0, acm_->RegisterReceiveCodec(codec_));\n ASSERT_EQ(0, acm_->RegisterSendCodec(codec_));\n\n rtp_utility_->Populate(&rtp_header_);\n\n input_frame_.sample_rate_hz_ = kSampleRateHz;\n input_frame_.samples_per_channel_ = kSampleRateHz * 10 \/ 1000; \/\/ 10 ms.\n COMPILE_ASSERT(kSampleRateHz * 10 \/ 1000 <= AudioFrame::kMaxDataSizeSamples,\n audio_frame_too_small);\n memset(input_frame_.data_,\n 0,\n input_frame_.samples_per_channel_ * sizeof(input_frame_.data_[0]));\n\n ASSERT_EQ(0, acm_->RegisterTransportCallback(&packet_cb_));\n }\n\n void InsertPacketAndPullAudio() {\n InsertPacket();\n PullAudio();\n }\n\n void InsertPacket() {\n const uint8_t kPayload[kPayloadSizeBytes] = {0};\n ASSERT_EQ(0,\n acm_->IncomingPacket(kPayload, kPayloadSizeBytes, rtp_header_));\n rtp_utility_->Forward(&rtp_header_);\n }\n\n void PullAudio() {\n AudioFrame audio_frame;\n ASSERT_EQ(0, acm_->PlayoutData10Ms(-1, &audio_frame));\n }\n\n void InsertAudio() { ASSERT_EQ(0, acm_->Add10MsData(input_frame_)); }\n\n void Encode() {\n int32_t encoded_bytes = acm_->Process();\n \/\/ Expect to get one packet with two bytes per sample, or no packet at all,\n \/\/ depending on how many 10 ms blocks go into |codec_.pacsize|.\n EXPECT_TRUE(encoded_bytes == 2 * codec_.pacsize || encoded_bytes == 0);\n }\n\n const int id_;\n scoped_ptr rtp_utility_;\n scoped_ptr acm_;\n PacketizationCallbackStub packet_cb_;\n WebRtcRTPHeader rtp_header_;\n AudioFrame input_frame_;\n CodecInst codec_;\n Clock* clock_;\n};\n\n\/\/ Check if the statistics are initialized correctly. Before any call to ACM\n\/\/ all fields have to be zero.\nTEST_F(AudioCodingModuleTest, DISABLED_ON_ANDROID(InitializedToZero)) {\n AudioDecodingCallStats stats;\n acm_->GetDecodingCallStatistics(&stats);\n EXPECT_EQ(0, stats.calls_to_neteq);\n EXPECT_EQ(0, stats.calls_to_silence_generator);\n EXPECT_EQ(0, stats.decoded_normal);\n EXPECT_EQ(0, stats.decoded_cng);\n EXPECT_EQ(0, stats.decoded_plc);\n EXPECT_EQ(0, stats.decoded_plc_cng);\n}\n\n\/\/ Apply an initial playout delay. Calls to AudioCodingModule::PlayoutData10ms()\n\/\/ should result in generating silence, check the associated field.\nTEST_F(AudioCodingModuleTest, DISABLED_ON_ANDROID(SilenceGeneratorCalled)) {\n AudioDecodingCallStats stats;\n const int kInitialDelay = 100;\n\n acm_->SetInitialPlayoutDelay(kInitialDelay);\n\n int num_calls = 0;\n for (int time_ms = 0; time_ms < kInitialDelay;\n time_ms += kFrameSizeMs, ++num_calls) {\n InsertPacketAndPullAudio();\n }\n acm_->GetDecodingCallStatistics(&stats);\n EXPECT_EQ(0, stats.calls_to_neteq);\n EXPECT_EQ(num_calls, stats.calls_to_silence_generator);\n EXPECT_EQ(0, stats.decoded_normal);\n EXPECT_EQ(0, stats.decoded_cng);\n EXPECT_EQ(0, stats.decoded_plc);\n EXPECT_EQ(0, stats.decoded_plc_cng);\n}\n\n\/\/ Insert some packets and pull audio. Check statistics are valid. Then,\n\/\/ simulate packet loss and check if PLC and PLC-to-CNG statistics are\n\/\/ correctly updated.\nTEST_F(AudioCodingModuleTest, DISABLED_ON_ANDROID(NetEqCalls)) {\n AudioDecodingCallStats stats;\n const int kNumNormalCalls = 10;\n\n for (int num_calls = 0; num_calls < kNumNormalCalls; ++num_calls) {\n InsertPacketAndPullAudio();\n }\n acm_->GetDecodingCallStatistics(&stats);\n EXPECT_EQ(kNumNormalCalls, stats.calls_to_neteq);\n EXPECT_EQ(0, stats.calls_to_silence_generator);\n EXPECT_EQ(kNumNormalCalls, stats.decoded_normal);\n EXPECT_EQ(0, stats.decoded_cng);\n EXPECT_EQ(0, stats.decoded_plc);\n EXPECT_EQ(0, stats.decoded_plc_cng);\n\n const int kNumPlc = 3;\n const int kNumPlcCng = 5;\n\n \/\/ Simulate packet-loss. NetEq first performs PLC then PLC fades to CNG.\n for (int n = 0; n < kNumPlc + kNumPlcCng; ++n) {\n PullAudio();\n }\n acm_->GetDecodingCallStatistics(&stats);\n EXPECT_EQ(kNumNormalCalls + kNumPlc + kNumPlcCng, stats.calls_to_neteq);\n EXPECT_EQ(0, stats.calls_to_silence_generator);\n EXPECT_EQ(kNumNormalCalls, stats.decoded_normal);\n EXPECT_EQ(0, stats.decoded_cng);\n EXPECT_EQ(kNumPlc, stats.decoded_plc);\n EXPECT_EQ(kNumPlcCng, stats.decoded_plc_cng);\n}\n\nTEST_F(AudioCodingModuleTest, VerifyOutputFrame) {\n AudioFrame audio_frame;\n const int kSampleRateHz = 32000;\n EXPECT_EQ(0, acm_->PlayoutData10Ms(kSampleRateHz, &audio_frame));\n EXPECT_EQ(id_, audio_frame.id_);\n EXPECT_EQ(0u, audio_frame.timestamp_);\n EXPECT_GT(audio_frame.num_channels_, 0);\n EXPECT_EQ(kSampleRateHz \/ 100, audio_frame.samples_per_channel_);\n EXPECT_EQ(kSampleRateHz, audio_frame.sample_rate_hz_);\n}\n\nTEST_F(AudioCodingModuleTest, FailOnZeroDesiredFrequency) {\n AudioFrame audio_frame;\n EXPECT_EQ(-1, acm_->PlayoutData10Ms(0, &audio_frame));\n}\n\nclass AudioCodingModuleMtTest : public AudioCodingModuleTest {\n protected:\n static const int kNumPackets = 10000;\n static const int kNumPullCalls = 10000;\n\n AudioCodingModuleMtTest()\n : AudioCodingModuleTest(),\n send_thread_(ThreadWrapper::CreateThread(CbSendThread,\n this,\n kRealtimePriority,\n \"send\")),\n insert_packet_thread_(ThreadWrapper::CreateThread(CbInsertPacketThread,\n this,\n kRealtimePriority,\n \"insert_packet\")),\n pull_audio_thread_(ThreadWrapper::CreateThread(CbPullAudioThread,\n this,\n kRealtimePriority,\n \"pull_audio\")),\n test_complete_(EventWrapper::Create()),\n send_count_(0),\n insert_packet_count_(0),\n pull_audio_count_(0),\n crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),\n next_insert_packet_time_ms_(0),\n fake_clock_(new SimulatedClock(0)) {\n clock_ = fake_clock_;\n }\n\n ~AudioCodingModuleMtTest() {}\n\n void SetUp() {\n AudioCodingModuleTest::SetUp();\n unsigned int thread_id = 0;\n ASSERT_TRUE(send_thread_->Start(thread_id));\n ASSERT_TRUE(insert_packet_thread_->Start(thread_id));\n ASSERT_TRUE(pull_audio_thread_->Start(thread_id));\n }\n\n void TearDown() {\n AudioCodingModuleTest::TearDown();\n pull_audio_thread_->Stop();\n send_thread_->Stop();\n insert_packet_thread_->Stop();\n }\n\n EventTypeWrapper RunTest() { return test_complete_->Wait(60000); }\n\n private:\n static bool CbSendThread(void* context) {\n return reinterpret_cast(context)->CbSendImpl();\n }\n\n \/\/ The send thread doesn't have to care about the current simulated time,\n \/\/ since only the AcmReceiver is using the clock.\n bool CbSendImpl() {\n ++send_count_;\n InsertAudio();\n Encode();\n if (packet_cb_.num_calls() > kNumPackets) {\n CriticalSectionScoped lock(crit_sect_.get());\n if (pull_audio_count_ > kNumPullCalls) {\n \/\/ Both conditions for completion are met. End the test.\n test_complete_->Set();\n }\n }\n return true;\n }\n\n static bool CbInsertPacketThread(void* context) {\n return reinterpret_cast(context)\n ->CbInsertPacketImpl();\n }\n\n bool CbInsertPacketImpl() {\n {\n CriticalSectionScoped lock(crit_sect_.get());\n if (clock_->TimeInMilliseconds() < next_insert_packet_time_ms_) {\n return true;\n }\n next_insert_packet_time_ms_ += 10;\n }\n \/\/ Now we're not holding the crit sect when calling ACM.\n ++insert_packet_count_;\n InsertPacket();\n return true;\n }\n\n static bool CbPullAudioThread(void* context) {\n return reinterpret_cast(context)\n ->CbPullAudioImpl();\n }\n\n bool CbPullAudioImpl() {\n {\n CriticalSectionScoped lock(crit_sect_.get());\n \/\/ Don't let the insert thread fall behind.\n if (next_insert_packet_time_ms_ < clock_->TimeInMilliseconds()) {\n return true;\n }\n ++pull_audio_count_;\n }\n \/\/ Now we're not holding the crit sect when calling ACM.\n PullAudio();\n fake_clock_->AdvanceTimeMilliseconds(10);\n return true;\n }\n\n scoped_ptr send_thread_;\n scoped_ptr insert_packet_thread_;\n scoped_ptr pull_audio_thread_;\n const scoped_ptr test_complete_;\n int send_count_;\n int insert_packet_count_;\n int pull_audio_count_ GUARDED_BY(crit_sect_);\n const scoped_ptr crit_sect_;\n int64_t next_insert_packet_time_ms_ GUARDED_BY(crit_sect_);\n SimulatedClock* fake_clock_;\n};\n\nTEST_F(AudioCodingModuleMtTest, DISABLED_DoTest) {\n EXPECT_EQ(kEventSignaled, RunTest());\n}\n\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/canbus\/vehicle\/gem\/protocol\/wheel_speed_rpt_7a.h\"\n\n#include \"gtest\/gtest.h\"\n\nnamespace apollo {\nnamespace canbus {\nnamespace gem {\n\nclass Wheelspeedrpt7aTest : public ::testing::Test {\n public:\n virtual void SetUp() {}\n};\n\nTEST_F(Wheelspeedrpt7aTest, reset) {\n Wheelspeedrpt7a wheelspeed;\n int32_t length = 8;\n ChassisDetail chassis_detail;\n uint8_t bytes[8] = {0x01, 0x02, 0x03, 0x04, 0x11, 0x12, 0x13, 0x14};\n wheelspeed.Parse(bytes, length, &chassis_detail);\n EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\\\n.wheel_spd_rear_right(), 4884);\n EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\\\n.wheel_spd_rear_left(), 4370);\n EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\\\n.wheel_spd_front_right(), 772);\n EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\\\n.wheel_spd_front_left(), 258);\n}\n\n} \/\/ namespace gem\n} \/\/ namespace canbus\n} \/\/ namespace apollo\n\nUpdate wheel_speed_rpt_7a_test.cc\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/canbus\/vehicle\/gem\/protocol\/wheel_speed_rpt_7a.h\"\n\n#include \"gtest\/gtest.h\"\n\nnamespace apollo {\nnamespace canbus {\nnamespace gem {\n\nclass Wheelspeedrpt7aTest : public ::testing::Test {\n public:\n virtual void SetUp() {}\n};\n\nTEST_F(Wheelspeedrpt7aTest, reset) {\n Wheelspeedrpt7a wheelspeed;\n int32_t length = 8;\n ChassisDetail chassis_detail;\n uint8_t bytes[8] = {0x01, 0x02, 0x03, 0x04, 0x11, 0x12, 0x13, 0x14};\n wheelspeed.Parse(bytes, length, &chassis_detail);\n EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\\\n.wheel_spd_rear_right(), 4884);\n EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\\\n.wheel_spd_rear_left(), 4370);\n EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\\\n.wheel_spd_front_right(), 772);\n EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\\\n.wheel_spd_front_left(), 258);\n}\n\n} \/\/ namespace gem\n} \/\/ namespace canbus\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2016 The Qt Company Ltd.\n** Contact: https:\/\/www.qt.io\/licensing\/\n**\n** This file is part of Qbs.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company. For licensing terms\n** and conditions see https:\/\/www.qt.io\/terms-conditions. For further\n** information use the contact form at https:\/\/www.qt.io\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 3 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL3 included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 3 requirements\n** will be met: https:\/\/www.gnu.org\/licenses\/lgpl-3.0.html.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 2.0 or (at your option) the GNU General\n** Public license version 3 or any later version approved by the KDE Free\n** Qt Foundation. The licenses are as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3\n** included in the packaging of this file. Please review the following\n** information to ensure the GNU General Public License requirements will\n** be met: https:\/\/www.gnu.org\/licenses\/gpl-2.0.html and\n** https:\/\/www.gnu.org\/licenses\/gpl-3.0.html.\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"vsenvironmentdetector.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#ifdef Q_OS_WIN\n#include \n#include \n#endif\n\nnamespace qbs {\nnamespace Internal {\n\nstatic QString windowsSystem32Path()\n{\n#ifdef Q_OS_WIN\n wchar_t str[UNICODE_STRING_MAX_CHARS];\n if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_SYSTEM, NULL, 0, str)))\n return QString::fromUtf16(reinterpret_cast(str));\n#endif\n return {};\n}\n\nVsEnvironmentDetector::VsEnvironmentDetector(QString vcvarsallPath)\n : m_windowsSystemDirPath(windowsSystem32Path())\n , m_vcvarsallPath(std::move(vcvarsallPath))\n{\n}\n\nbool VsEnvironmentDetector::start(MSVC *msvc)\n{\n return start(std::vector{ msvc });\n}\n\nbool VsEnvironmentDetector::start(std::vector msvcs)\n{\n std::sort(msvcs.begin(), msvcs.end(), [] (const MSVC *a, const MSVC *b) -> bool {\n return a->vcInstallPath < b->vcInstallPath;\n });\n\n std::vector compatibleMSVCs;\n QString lastVcInstallPath;\n bool someMSVCDetected = false;\n for (MSVC * const msvc : msvcs) {\n if (lastVcInstallPath != msvc->vcInstallPath) {\n lastVcInstallPath = msvc->vcInstallPath;\n if (!compatibleMSVCs.empty()) {\n if (startDetection(compatibleMSVCs))\n someMSVCDetected = true;\n compatibleMSVCs.clear();\n }\n }\n compatibleMSVCs.push_back(msvc);\n }\n if (startDetection(compatibleMSVCs))\n someMSVCDetected = true;\n return someMSVCDetected;\n}\n\nQString VsEnvironmentDetector::findVcVarsAllBat(const MSVC &msvc,\n std::vector &searchedPaths) const\n{\n \/\/ ### We can only rely on MSVC.vcInstallPath being set\n \/\/ when this is called from utilitiesextension.cpp :-(\n \/\/ If we knew the vsInstallPath at this point we could just use that\n \/\/ instead of searching for vcvarsall.bat candidates.\n QDir dir(msvc.vcInstallPath);\n for (;;) {\n if (!dir.cdUp())\n return {};\n if (dir.dirName() == QLatin1String(\"VC\"))\n break;\n }\n const QString vcvarsallbat = QStringLiteral(\"vcvarsall.bat\");\n QString path = vcvarsallbat;\n QString fullPath = dir.absoluteFilePath(path);\n if (dir.exists(path))\n return fullPath;\n else\n searchedPaths.push_back(fullPath);\n path = QStringLiteral(\"Auxiliary\/Build\/\") + vcvarsallbat;\n fullPath = dir.absoluteFilePath(path);\n if (dir.exists(path))\n return fullPath;\n else\n searchedPaths.push_back(fullPath);\n return {};\n}\n\nbool VsEnvironmentDetector::startDetection(const std::vector &compatibleMSVCs)\n{\n std::vector searchedPaths;\n\n if (!m_vcvarsallPath.isEmpty() && !QFileInfo::exists(m_vcvarsallPath)) {\n m_errorString = Tr::tr(\"%1 does not exist.\").arg(m_vcvarsallPath);\n return false;\n }\n\n const auto vcvarsallbat = !m_vcvarsallPath.isEmpty()\n ? m_vcvarsallPath\n : findVcVarsAllBat(**compatibleMSVCs.begin(), searchedPaths);\n if (vcvarsallbat.isEmpty()) {\n if (!searchedPaths.empty()) {\n m_errorString = Tr::tr(\n \"Cannot find 'vcvarsall.bat' at any of the following locations:\\n\\t\")\n + join(searchedPaths, QStringLiteral(\"\\n\\t\"));\n } else {\n m_errorString = Tr::tr(\"Cannot find 'vcvarsall.bat'.\");\n }\n return false;\n }\n\n QTemporaryFile tmpFile(QDir::tempPath() + QLatin1Char('\/') + QStringLiteral(\"XXXXXX.bat\"));\n if (!tmpFile.open()) {\n m_errorString = Tr::tr(\"Cannot open temporary file '%1' for writing.\").arg(\n tmpFile.fileName());\n return false;\n }\n\n writeBatchFile(&tmpFile, vcvarsallbat, compatibleMSVCs);\n tmpFile.flush();\n\n QProcess process;\n static const QString shellFilePath = QStringLiteral(\"cmd.exe\");\n process.start(shellFilePath, QStringList()\n << QStringLiteral(\"\/C\") << tmpFile.fileName());\n if (!process.waitForStarted()) {\n m_errorString = Tr::tr(\"Failed to start '%1'.\").arg(shellFilePath);\n return false;\n }\n process.waitForFinished(-1);\n if (process.exitStatus() != QProcess::NormalExit) {\n m_errorString = Tr::tr(\"Process '%1' did not exit normally.\").arg(shellFilePath);\n return false;\n }\n if (process.exitCode() != 0) {\n m_errorString = Tr::tr(\"Failed to detect Visual Studio environment.\");\n return false;\n }\n parseBatOutput(process.readAllStandardOutput(), compatibleMSVCs);\n return true;\n\n}\n\nstatic void batClearVars(QTextStream &s, const QStringList &varnames)\n{\n for (const QString &varname : varnames)\n s << \"set \" << varname << '=' << Qt::endl;\n}\n\nstatic void batPrintVars(QTextStream &s, const QStringList &varnames)\n{\n for (const QString &varname : varnames)\n s << \"echo \" << varname << \"=%\" << varname << '%' << Qt::endl;\n}\n\nstatic QString vcArchitecture(const MSVC *msvc)\n{\n QString vcArch = msvc->architecture;\n if (msvc->architecture == StringConstants::armv7Arch())\n vcArch = StringConstants::armArch();\n if (msvc->architecture == StringConstants::x86_64Arch())\n vcArch = StringConstants::amd64Arch();\n\n const QString hostPrefixes[] = {\n StringConstants::x86Arch(),\n QStringLiteral(\"amd64_\"),\n QStringLiteral(\"x86_\")\n };\n for (const QString &hostPrefix : hostPrefixes) {\n if (QFile::exists(msvc->clPathForArchitecture(hostPrefix + vcArch))) {\n vcArch.prepend(hostPrefix);\n break;\n }\n }\n\n return vcArch;\n}\n\nvoid VsEnvironmentDetector::writeBatchFile(QIODevice *device, const QString &vcvarsallbat,\n const std::vector &msvcs) const\n{\n const QStringList varnames = QStringList() << StringConstants::pathEnvVar()\n << QStringLiteral(\"INCLUDE\") << QStringLiteral(\"LIB\") << QStringLiteral(\"WindowsSdkDir\")\n << QStringLiteral(\"WindowsSDKVersion\") << QStringLiteral(\"VSINSTALLDIR\");\n QTextStream s(device);\n using Qt::endl;\n s << \"@echo off\" << endl;\n \/\/ Avoid execution of powershell (in vsdevcmd.bat), which is not in the cleared PATH\n s << \"set VSCMD_SKIP_SENDTELEMETRY=1\" << endl;\n for (const MSVC *msvc : msvcs) {\n s << \"echo --\" << msvc->architecture << \"--\" << endl\n << \"setlocal\" << endl;\n batClearVars(s, varnames);\n s << \"set PATH=\" << m_windowsSystemDirPath << endl; \/\/ vcvarsall.bat needs tools from here\n s << \"call \\\"\" << vcvarsallbat << \"\\\" \" << vcArchitecture(msvc)\n << \" || exit \/b 1\" << endl;\n batPrintVars(s, varnames);\n s << \"endlocal\" << endl;\n }\n}\n\nvoid VsEnvironmentDetector::parseBatOutput(const QByteArray &output, std::vector msvcs)\n{\n QString arch;\n QProcessEnvironment *targetEnv = nullptr;\n const auto lines = output.split('\\n');\n for (QByteArray line : lines) {\n line = line.trimmed();\n if (line.isEmpty())\n continue;\n\n if (line.startsWith(\"--\") && line.endsWith(\"--\")) {\n line.remove(0, 2);\n line.chop(2);\n arch = QString::fromLocal8Bit(line);\n targetEnv = &msvcs.front()->environment;\n msvcs.erase(msvcs.begin());\n } else {\n int idx = line.indexOf('=');\n if (idx < 0)\n continue;\n QBS_CHECK(targetEnv);\n const QString name = QString::fromLocal8Bit(line.left(idx));\n QString value = QString::fromLocal8Bit(line.mid(idx + 1));\n if (name.compare(StringConstants::pathEnvVar(), Qt::CaseInsensitive) == 0)\n value.remove(m_windowsSystemDirPath);\n if (value.endsWith(QLatin1Char(';')))\n value.chop(1);\n if (value.endsWith(QLatin1Char('\\\\')))\n value.chop(1);\n targetEnv->insert(name, value);\n }\n }\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace qbs\nRemove deleting trailing slash from VS env vars\/****************************************************************************\n**\n** Copyright (C) 2016 The Qt Company Ltd.\n** Contact: https:\/\/www.qt.io\/licensing\/\n**\n** This file is part of Qbs.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company. For licensing terms\n** and conditions see https:\/\/www.qt.io\/terms-conditions. For further\n** information use the contact form at https:\/\/www.qt.io\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 3 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL3 included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 3 requirements\n** will be met: https:\/\/www.gnu.org\/licenses\/lgpl-3.0.html.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 2.0 or (at your option) the GNU General\n** Public license version 3 or any later version approved by the KDE Free\n** Qt Foundation. The licenses are as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3\n** included in the packaging of this file. Please review the following\n** information to ensure the GNU General Public License requirements will\n** be met: https:\/\/www.gnu.org\/licenses\/gpl-2.0.html and\n** https:\/\/www.gnu.org\/licenses\/gpl-3.0.html.\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"vsenvironmentdetector.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#ifdef Q_OS_WIN\n#include \n#include \n#endif\n\nnamespace qbs {\nnamespace Internal {\n\nstatic QString windowsSystem32Path()\n{\n#ifdef Q_OS_WIN\n wchar_t str[UNICODE_STRING_MAX_CHARS];\n if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_SYSTEM, NULL, 0, str)))\n return QString::fromUtf16(reinterpret_cast(str));\n#endif\n return {};\n}\n\nVsEnvironmentDetector::VsEnvironmentDetector(QString vcvarsallPath)\n : m_windowsSystemDirPath(windowsSystem32Path())\n , m_vcvarsallPath(std::move(vcvarsallPath))\n{\n}\n\nbool VsEnvironmentDetector::start(MSVC *msvc)\n{\n return start(std::vector{ msvc });\n}\n\nbool VsEnvironmentDetector::start(std::vector msvcs)\n{\n std::sort(msvcs.begin(), msvcs.end(), [] (const MSVC *a, const MSVC *b) -> bool {\n return a->vcInstallPath < b->vcInstallPath;\n });\n\n std::vector compatibleMSVCs;\n QString lastVcInstallPath;\n bool someMSVCDetected = false;\n for (MSVC * const msvc : msvcs) {\n if (lastVcInstallPath != msvc->vcInstallPath) {\n lastVcInstallPath = msvc->vcInstallPath;\n if (!compatibleMSVCs.empty()) {\n if (startDetection(compatibleMSVCs))\n someMSVCDetected = true;\n compatibleMSVCs.clear();\n }\n }\n compatibleMSVCs.push_back(msvc);\n }\n if (startDetection(compatibleMSVCs))\n someMSVCDetected = true;\n return someMSVCDetected;\n}\n\nQString VsEnvironmentDetector::findVcVarsAllBat(const MSVC &msvc,\n std::vector &searchedPaths) const\n{\n \/\/ ### We can only rely on MSVC.vcInstallPath being set\n \/\/ when this is called from utilitiesextension.cpp :-(\n \/\/ If we knew the vsInstallPath at this point we could just use that\n \/\/ instead of searching for vcvarsall.bat candidates.\n QDir dir(msvc.vcInstallPath);\n for (;;) {\n if (!dir.cdUp())\n return {};\n if (dir.dirName() == QLatin1String(\"VC\"))\n break;\n }\n const QString vcvarsallbat = QStringLiteral(\"vcvarsall.bat\");\n QString path = vcvarsallbat;\n QString fullPath = dir.absoluteFilePath(path);\n if (dir.exists(path))\n return fullPath;\n else\n searchedPaths.push_back(fullPath);\n path = QStringLiteral(\"Auxiliary\/Build\/\") + vcvarsallbat;\n fullPath = dir.absoluteFilePath(path);\n if (dir.exists(path))\n return fullPath;\n else\n searchedPaths.push_back(fullPath);\n return {};\n}\n\nbool VsEnvironmentDetector::startDetection(const std::vector &compatibleMSVCs)\n{\n std::vector searchedPaths;\n\n if (!m_vcvarsallPath.isEmpty() && !QFileInfo::exists(m_vcvarsallPath)) {\n m_errorString = Tr::tr(\"%1 does not exist.\").arg(m_vcvarsallPath);\n return false;\n }\n\n const auto vcvarsallbat = !m_vcvarsallPath.isEmpty()\n ? m_vcvarsallPath\n : findVcVarsAllBat(**compatibleMSVCs.begin(), searchedPaths);\n if (vcvarsallbat.isEmpty()) {\n if (!searchedPaths.empty()) {\n m_errorString = Tr::tr(\n \"Cannot find 'vcvarsall.bat' at any of the following locations:\\n\\t\")\n + join(searchedPaths, QStringLiteral(\"\\n\\t\"));\n } else {\n m_errorString = Tr::tr(\"Cannot find 'vcvarsall.bat'.\");\n }\n return false;\n }\n\n QTemporaryFile tmpFile(QDir::tempPath() + QLatin1Char('\/') + QStringLiteral(\"XXXXXX.bat\"));\n if (!tmpFile.open()) {\n m_errorString = Tr::tr(\"Cannot open temporary file '%1' for writing.\").arg(\n tmpFile.fileName());\n return false;\n }\n\n writeBatchFile(&tmpFile, vcvarsallbat, compatibleMSVCs);\n tmpFile.flush();\n\n QProcess process;\n static const QString shellFilePath = QStringLiteral(\"cmd.exe\");\n process.start(shellFilePath, QStringList()\n << QStringLiteral(\"\/C\") << tmpFile.fileName());\n if (!process.waitForStarted()) {\n m_errorString = Tr::tr(\"Failed to start '%1'.\").arg(shellFilePath);\n return false;\n }\n process.waitForFinished(-1);\n if (process.exitStatus() != QProcess::NormalExit) {\n m_errorString = Tr::tr(\"Process '%1' did not exit normally.\").arg(shellFilePath);\n return false;\n }\n if (process.exitCode() != 0) {\n m_errorString = Tr::tr(\"Failed to detect Visual Studio environment.\");\n return false;\n }\n parseBatOutput(process.readAllStandardOutput(), compatibleMSVCs);\n return true;\n\n}\n\nstatic void batClearVars(QTextStream &s, const QStringList &varnames)\n{\n for (const QString &varname : varnames)\n s << \"set \" << varname << '=' << Qt::endl;\n}\n\nstatic void batPrintVars(QTextStream &s, const QStringList &varnames)\n{\n for (const QString &varname : varnames)\n s << \"echo \" << varname << \"=%\" << varname << '%' << Qt::endl;\n}\n\nstatic QString vcArchitecture(const MSVC *msvc)\n{\n QString vcArch = msvc->architecture;\n if (msvc->architecture == StringConstants::armv7Arch())\n vcArch = StringConstants::armArch();\n if (msvc->architecture == StringConstants::x86_64Arch())\n vcArch = StringConstants::amd64Arch();\n\n const QString hostPrefixes[] = {\n StringConstants::x86Arch(),\n QStringLiteral(\"amd64_\"),\n QStringLiteral(\"x86_\")\n };\n for (const QString &hostPrefix : hostPrefixes) {\n if (QFile::exists(msvc->clPathForArchitecture(hostPrefix + vcArch))) {\n vcArch.prepend(hostPrefix);\n break;\n }\n }\n\n return vcArch;\n}\n\nvoid VsEnvironmentDetector::writeBatchFile(QIODevice *device, const QString &vcvarsallbat,\n const std::vector &msvcs) const\n{\n const QStringList varnames = QStringList() << StringConstants::pathEnvVar()\n << QStringLiteral(\"INCLUDE\") << QStringLiteral(\"LIB\") << QStringLiteral(\"WindowsSdkDir\")\n << QStringLiteral(\"WindowsSDKVersion\") << QStringLiteral(\"VSINSTALLDIR\");\n QTextStream s(device);\n using Qt::endl;\n s << \"@echo off\" << endl;\n \/\/ Avoid execution of powershell (in vsdevcmd.bat), which is not in the cleared PATH\n s << \"set VSCMD_SKIP_SENDTELEMETRY=1\" << endl;\n for (const MSVC *msvc : msvcs) {\n s << \"echo --\" << msvc->architecture << \"--\" << endl\n << \"setlocal\" << endl;\n batClearVars(s, varnames);\n s << \"set PATH=\" << m_windowsSystemDirPath << endl; \/\/ vcvarsall.bat needs tools from here\n s << \"call \\\"\" << vcvarsallbat << \"\\\" \" << vcArchitecture(msvc)\n << \" || exit \/b 1\" << endl;\n batPrintVars(s, varnames);\n s << \"endlocal\" << endl;\n }\n}\n\nvoid VsEnvironmentDetector::parseBatOutput(const QByteArray &output, std::vector msvcs)\n{\n QString arch;\n QProcessEnvironment *targetEnv = nullptr;\n const auto lines = output.split('\\n');\n for (QByteArray line : lines) {\n line = line.trimmed();\n if (line.isEmpty())\n continue;\n\n if (line.startsWith(\"--\") && line.endsWith(\"--\")) {\n line.remove(0, 2);\n line.chop(2);\n arch = QString::fromLocal8Bit(line);\n targetEnv = &msvcs.front()->environment;\n msvcs.erase(msvcs.begin());\n } else {\n int idx = line.indexOf('=');\n if (idx < 0)\n continue;\n QBS_CHECK(targetEnv);\n const QString name = QString::fromLocal8Bit(line.left(idx));\n QString value = QString::fromLocal8Bit(line.mid(idx + 1));\n if (name.compare(StringConstants::pathEnvVar(), Qt::CaseInsensitive) == 0)\n value.remove(m_windowsSystemDirPath);\n if (value.endsWith(QLatin1Char(';')))\n value.chop(1);\n targetEnv->insert(name, value);\n }\n }\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace qbs\n<|endoftext|>"} {"text":"\/****************************************************************************\n *\n * Copyright (c) 2015 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file data_validator_group.cpp\n *\n * A data validation group to identify anomalies in data streams\n *\n * @author Lorenz Meier \n *\/\n\n#include \"data_validator_group.h\"\n#include \n\nDataValidatorGroup::DataValidatorGroup(unsigned siblings) :\n\t_first(nullptr),\n\t_curr_best(-1),\n\t_prev_best(-1),\n\t_first_failover_time(0),\n\t_toggle_count(0)\n{\n\tDataValidator *next = _first;\n\n\tfor (unsigned i = 0; i < siblings; i++) {\n\t\tnext = new DataValidator(next);\n\t}\n\n\t_first = next;\n}\n\nDataValidatorGroup::~DataValidatorGroup()\n{\n\n}\n\nvoid\nDataValidatorGroup::set_timeout(uint64_t timeout_interval_us)\n{\n\tDataValidator *next = _first;\n\n\twhile (next != nullptr) {\n\t\tnext->set_timeout(timeout_interval_us);\n\t\tnext = next->sibling();\n\t}\n}\n\nvoid\nDataValidatorGroup::put(unsigned index, uint64_t timestamp, float val[3], uint64_t error_count, int priority)\n{\n\tDataValidator *next = _first;\n\tunsigned i = 0;\n\n\twhile (next != nullptr) {\n\t\tif (i == index) {\n\t\t\tnext->put(timestamp, val, error_count, priority);\n\t\t\tbreak;\n\t\t}\n\t\tnext = next->sibling();\n\t\ti++;\n\t}\n}\n\nfloat*\nDataValidatorGroup::get_best(uint64_t timestamp, int *index)\n{\n\tDataValidator *next = _first;\n\n\t\/\/ XXX This should eventually also include voting\n\tint pre_check_best = _curr_best;\n\tfloat pre_check_confidence = 1.0f;\n\tint pre_check_prio = -1;\n\tfloat max_confidence = -1.0f;\n\tint max_priority = -1000;\n\tint max_index = -1;\n\tDataValidator *best = nullptr;\n\n\tunsigned i = 0;\n\n\twhile (next != nullptr) {\n\t\tfloat confidence = next->confidence(timestamp);\n\n\t\tif (i == pre_check_best) {\n\t\t\tpre_check_prio = next->priority();\n\t\t\tpre_check_confidence = confidence;\n\t\t}\n\n\t\t\/*\n\t\t * Switch if:\n\t\t * 1) the confidence is higher and priority is equal or higher\n\t\t * 2) the confidence is no less than 1% different and the priority is higher\n\t\t *\/\n\t\tif (((max_confidence < MIN_REGULAR_CONFIDENCE) && (confidence >= MIN_REGULAR_CONFIDENCE)) ||\n\t\t\t(confidence > max_confidence && (next->priority() >= max_priority)) ||\n\t\t\t(fabsf(confidence - max_confidence) < 0.01f && (next->priority() > max_priority))\n\t\t\t) {\n\t\t\tmax_index = i;\n\t\t\tmax_confidence = confidence;\n\t\t\tmax_priority = next->priority();\n\t\t\tbest = next;\n\t\t}\n\n\t\tnext = next->sibling();\n\t\ti++;\n\t}\n\n\t\/* the current best sensor is not matching the previous best sensor *\/\n\tif (max_index != _curr_best) {\n\n\t\tbool true_failsafe = true;\n\n\t\t\/* check wether the switch was a failsafe or preferring a higher priority sensor *\/\n\t\tif (pre_check_prio != -1 && pre_check_prio < max_priority &&\n\t\t\tfabsf(pre_check_confidence - max_confidence) < 0.1f) {\n\t\t\t\/* this is not a failover *\/\n\t\t\ttrue_failsafe = false;\n\t\t}\n\n\t\t\/* if we're no initialized, initialize the bookkeeping but do not count a failsafe *\/\n\t\tif (_curr_best < 0) {\n\t\t\t_prev_best = max_index;\n\t\t} else {\n\t\t\t\/* we were initialized before, this is a real failsafe *\/\n\t\t\t_prev_best = pre_check_best;\n\n\t\t\tif (true_failsafe) {\n\t\t\t\t_toggle_count++;\n\n\t\t\t\t\/* if this is the first time, log when we failed *\/\n\t\t\t\tif (_first_failover_time == 0) {\n\t\t\t\t\t_first_failover_time = timestamp;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/* for all cases we want to keep a record of the best index *\/\n\t\t_curr_best = max_index;\n\t}\n\t*index = max_index;\n\treturn (best) ? best->value() : nullptr;\n}\n\nfloat\nDataValidatorGroup::get_vibration_factor(uint64_t timestamp)\n{\n\tDataValidator *next = _first;\n\n\tfloat vibe = 0.0f;\n\n\t\/* find the best RMS value of a non-timed out sensor *\/\n\twhile (next != nullptr) {\n\n\t\tif (next->confidence(timestamp) > 0.5f) {\n\t\t\tfloat* rms = next->rms();\n\n\t\t\tfor (unsigned j = 0; j < 3; j++) {\n\t\t\t\tif (rms[j] > vibe) {\n\t\t\t\t\tvibe = rms[j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tnext = next->sibling();\n\t}\n\n\treturn vibe;\n}\n\nvoid\nDataValidatorGroup::print()\n{\n\t\/* print the group's state *\/\n\tECL_INFO(\"validator: best: %d, prev best: %d, failsafe: %s (# %u)\",\n\t\t_curr_best, _prev_best, (_toggle_count > 0) ? \"YES\" : \"NO\",\n\t\t_toggle_count);\n\n\n\tDataValidator *next = _first;\n\tunsigned i = 0;\n\n\twhile (next != nullptr) {\n\t\tif (next->used()) {\n\t\t\tECL_INFO(\"sensor #%u, prio: %d\", i, next->priority());\n\t\t\tnext->print();\n\t\t}\n\t\tnext = next->sibling();\n\t\ti++;\n\t}\n}\n\nunsigned\nDataValidatorGroup::failover_count()\n{\n\treturn _toggle_count;\n}\nData validator: Fix compile warning on signedness\/****************************************************************************\n *\n * Copyright (c) 2015 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file data_validator_group.cpp\n *\n * A data validation group to identify anomalies in data streams\n *\n * @author Lorenz Meier \n *\/\n\n#include \"data_validator_group.h\"\n#include \n\nDataValidatorGroup::DataValidatorGroup(unsigned siblings) :\n\t_first(nullptr),\n\t_curr_best(-1),\n\t_prev_best(-1),\n\t_first_failover_time(0),\n\t_toggle_count(0)\n{\n\tDataValidator *next = _first;\n\n\tfor (unsigned i = 0; i < siblings; i++) {\n\t\tnext = new DataValidator(next);\n\t}\n\n\t_first = next;\n}\n\nDataValidatorGroup::~DataValidatorGroup()\n{\n\n}\n\nvoid\nDataValidatorGroup::set_timeout(uint64_t timeout_interval_us)\n{\n\tDataValidator *next = _first;\n\n\twhile (next != nullptr) {\n\t\tnext->set_timeout(timeout_interval_us);\n\t\tnext = next->sibling();\n\t}\n}\n\nvoid\nDataValidatorGroup::put(unsigned index, uint64_t timestamp, float val[3], uint64_t error_count, int priority)\n{\n\tDataValidator *next = _first;\n\tunsigned i = 0;\n\n\twhile (next != nullptr) {\n\t\tif (i == index) {\n\t\t\tnext->put(timestamp, val, error_count, priority);\n\t\t\tbreak;\n\t\t}\n\t\tnext = next->sibling();\n\t\ti++;\n\t}\n}\n\nfloat*\nDataValidatorGroup::get_best(uint64_t timestamp, int *index)\n{\n\tDataValidator *next = _first;\n\n\t\/\/ XXX This should eventually also include voting\n\tint pre_check_best = _curr_best;\n\tfloat pre_check_confidence = 1.0f;\n\tint pre_check_prio = -1;\n\tfloat max_confidence = -1.0f;\n\tint max_priority = -1000;\n\tint max_index = -1;\n\tDataValidator *best = nullptr;\n\n\tunsigned i = 0;\n\n\twhile (next != nullptr) {\n\t\tfloat confidence = next->confidence(timestamp);\n\n\t\tif (static_cast(i) == pre_check_best) {\n\t\t\tpre_check_prio = next->priority();\n\t\t\tpre_check_confidence = confidence;\n\t\t}\n\n\t\t\/*\n\t\t * Switch if:\n\t\t * 1) the confidence is higher and priority is equal or higher\n\t\t * 2) the confidence is no less than 1% different and the priority is higher\n\t\t *\/\n\t\tif (((max_confidence < MIN_REGULAR_CONFIDENCE) && (confidence >= MIN_REGULAR_CONFIDENCE)) ||\n\t\t\t(confidence > max_confidence && (next->priority() >= max_priority)) ||\n\t\t\t(fabsf(confidence - max_confidence) < 0.01f && (next->priority() > max_priority))\n\t\t\t) {\n\t\t\tmax_index = i;\n\t\t\tmax_confidence = confidence;\n\t\t\tmax_priority = next->priority();\n\t\t\tbest = next;\n\t\t}\n\n\t\tnext = next->sibling();\n\t\ti++;\n\t}\n\n\t\/* the current best sensor is not matching the previous best sensor *\/\n\tif (max_index != _curr_best) {\n\n\t\tbool true_failsafe = true;\n\n\t\t\/* check wether the switch was a failsafe or preferring a higher priority sensor *\/\n\t\tif (pre_check_prio != -1 && pre_check_prio < max_priority &&\n\t\t\tfabsf(pre_check_confidence - max_confidence) < 0.1f) {\n\t\t\t\/* this is not a failover *\/\n\t\t\ttrue_failsafe = false;\n\t\t}\n\n\t\t\/* if we're no initialized, initialize the bookkeeping but do not count a failsafe *\/\n\t\tif (_curr_best < 0) {\n\t\t\t_prev_best = max_index;\n\t\t} else {\n\t\t\t\/* we were initialized before, this is a real failsafe *\/\n\t\t\t_prev_best = pre_check_best;\n\n\t\t\tif (true_failsafe) {\n\t\t\t\t_toggle_count++;\n\n\t\t\t\t\/* if this is the first time, log when we failed *\/\n\t\t\t\tif (_first_failover_time == 0) {\n\t\t\t\t\t_first_failover_time = timestamp;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/* for all cases we want to keep a record of the best index *\/\n\t\t_curr_best = max_index;\n\t}\n\t*index = max_index;\n\treturn (best) ? best->value() : nullptr;\n}\n\nfloat\nDataValidatorGroup::get_vibration_factor(uint64_t timestamp)\n{\n\tDataValidator *next = _first;\n\n\tfloat vibe = 0.0f;\n\n\t\/* find the best RMS value of a non-timed out sensor *\/\n\twhile (next != nullptr) {\n\n\t\tif (next->confidence(timestamp) > 0.5f) {\n\t\t\tfloat* rms = next->rms();\n\n\t\t\tfor (unsigned j = 0; j < 3; j++) {\n\t\t\t\tif (rms[j] > vibe) {\n\t\t\t\t\tvibe = rms[j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tnext = next->sibling();\n\t}\n\n\treturn vibe;\n}\n\nvoid\nDataValidatorGroup::print()\n{\n\t\/* print the group's state *\/\n\tECL_INFO(\"validator: best: %d, prev best: %d, failsafe: %s (# %u)\",\n\t\t_curr_best, _prev_best, (_toggle_count > 0) ? \"YES\" : \"NO\",\n\t\t_toggle_count);\n\n\n\tDataValidator *next = _first;\n\tunsigned i = 0;\n\n\twhile (next != nullptr) {\n\t\tif (next->used()) {\n\t\t\tECL_INFO(\"sensor #%u, prio: %d\", i, next->priority());\n\t\t\tnext->print();\n\t\t}\n\t\tnext = next->sibling();\n\t\ti++;\n\t}\n}\n\nunsigned\nDataValidatorGroup::failover_count()\n{\n\treturn _toggle_count;\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkExtractSelectedRows.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\/*-------------------------------------------------------------------------\n Copyright 2008 Sandia Corporation.\n Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,\n the U.S. Government retains certain rights in this software.\n-------------------------------------------------------------------------*\/\n\n#include \"vtkExtractSelectedRows.h\"\n\n#include \"vtkAnnotation.h\"\n#include \"vtkAnnotationLayers.h\"\n#include \"vtkCellArray.h\"\n#include \"vtkCellData.h\"\n#include \"vtkCommand.h\"\n#include \"vtkConvertSelection.h\"\n#include \"vtkDataArray.h\"\n#include \"vtkEdgeListIterator.h\"\n#include \"vtkEventForwarderCommand.h\"\n#include \"vtkExtractSelection.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n#include \"vtkPoints.h\"\n#include \"vtkSelection.h\"\n#include \"vtkSelectionNode.h\"\n#include \"vtkSignedCharArray.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkStringArray.h\"\n#include \"vtkTable.h\"\n#include \"vtkTree.h\"\n#include \"vtkVertexListIterator.h\"\n\n#include \n#include \n\nvtkCxxRevisionMacro(vtkExtractSelectedRows, \"1.1\");\nvtkStandardNewMacro(vtkExtractSelectedRows);\n\/\/----------------------------------------------------------------------------\nvtkExtractSelectedRows::vtkExtractSelectedRows()\n{\n this->AddOriginalRowIdsArray = false;\n this->SetNumberOfInputPorts(3);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkExtractSelectedRows::~vtkExtractSelectedRows()\n{\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkExtractSelectedRows::FillInputPortInformation(int port, vtkInformation* info)\n{\n if (port == 0)\n {\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkTable\");\n return 1;\n }\n else if (port == 1)\n {\n info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1);\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkSelection\");\n return 1;\n }\n else if (port == 2)\n {\n info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1);\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkAnnotationLayers\");\n return 1;\n }\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkExtractSelectedRows::SetSelectionConnection(vtkAlgorithmOutput* in)\n{\n this->SetInputConnection(1, in);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkExtractSelectedRows::SetAnnotationLayersConnection(vtkAlgorithmOutput* in)\n{\n this->SetInputConnection(2, in);\n}\n\n\n\/\/----------------------------------------------------------------------------\nint vtkExtractSelectedRows::RequestData(\n vtkInformation* vtkNotUsed(request), \n vtkInformationVector** inputVector, \n vtkInformationVector* outputVector)\n{\n vtkTable* input = vtkTable::GetData(inputVector[0]);\n vtkSelection* inputSelection = vtkSelection::GetData(inputVector[1]);\n vtkAnnotationLayers* inputAnnotations = vtkAnnotationLayers::GetData(inputVector[2]);\n vtkInformation* outInfo = outputVector->GetInformationObject(0);\n vtkTable* output = vtkTable::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()));\n\n if(!inputSelection && !inputAnnotations)\n {\n vtkErrorMacro(\"No vtkSelection or vtkAnnotationLayers provided as input.\");\n return 0;\n }\n\n vtkSmartPointer selection = vtkSmartPointer::New();\n int numSelections = 0;\n if(inputSelection)\n {\n selection->DeepCopy(inputSelection);\n numSelections++;\n }\n\n \/\/ If input annotations are provided, extract their selections only if\n \/\/ they are enabled and not hidden.\n if(inputAnnotations)\n {\n for(unsigned int i=0; iGetNumberOfAnnotations(); ++i)\n {\n vtkAnnotation* a = inputAnnotations->GetAnnotation(i);\n if ((a->GetInformation()->Has(vtkAnnotation::ENABLE()) && \n a->GetInformation()->Get(vtkAnnotation::ENABLE())==0) ||\n (a->GetInformation()->Has(vtkAnnotation::ENABLE()) && \n a->GetInformation()->Get(vtkAnnotation::ENABLE())==1 && \n a->GetInformation()->Has(vtkAnnotation::HIDE()) && \n a->GetInformation()->Get(vtkAnnotation::HIDE())==0))\n {\n continue;\n }\n selection->Union(a->GetSelection());\n numSelections++;\n }\n }\n\n \/\/ Handle case where there was no input selection and no enabled, non-hidden\n \/\/ annotations\n if(numSelections == 0)\n {\n output->ShallowCopy(input);\n return 1;\n }\n\n \/\/ Convert the selection to an INDICES selection\n vtkSmartPointer converted;\n converted.TakeReference(vtkConvertSelection::ToSelectionType(\n selection, input, vtkSelectionNode::INDICES, 0, vtkSelectionNode::ROW));\n if (!converted.GetPointer())\n {\n vtkErrorMacro(\"Selection conversion to INDICES failed.\");\n return 0;\n }\n\n vtkIdTypeArray* originalRowIds = vtkIdTypeArray::New();\n originalRowIds->SetName(\"vtkOriginalRowIds\");\n\n output->GetRowData()->CopyStructure(input->GetRowData());\n for (unsigned int i = 0; i < converted->GetNumberOfNodes(); ++i)\n {\n vtkSelectionNode* node = converted->GetNode(i);\n if (node->GetFieldType() == vtkSelectionNode::ROW)\n {\n vtkIdTypeArray* list = vtkIdTypeArray::SafeDownCast(node->GetSelectionList());\n if (list)\n {\n vtkIdType numTuples = list->GetNumberOfTuples();\n for (vtkIdType j = 0; j < numTuples; ++j)\n {\n vtkIdType val = list->GetValue(j);\n output->InsertNextRow(input->GetRow(val));\n if (this->AddOriginalRowIdsArray)\n {\n originalRowIds->InsertNextValue(val);\n }\n }\n }\n }\n }\n if (this->AddOriginalRowIdsArray)\n {\n output->AddColumn(originalRowIds);\n }\n originalRowIds->Delete();\n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkExtractSelectedRows::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"AddOriginalRowIdsArray: \" << this->AddOriginalRowIdsArray <<\n endl;\n}\nBUG: don't segfault when trying to select from a vtkTable with 0 rows\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkExtractSelectedRows.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\/*-------------------------------------------------------------------------\n Copyright 2008 Sandia Corporation.\n Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,\n the U.S. Government retains certain rights in this software.\n-------------------------------------------------------------------------*\/\n\n#include \"vtkExtractSelectedRows.h\"\n\n#include \"vtkAnnotation.h\"\n#include \"vtkAnnotationLayers.h\"\n#include \"vtkCellArray.h\"\n#include \"vtkCellData.h\"\n#include \"vtkCommand.h\"\n#include \"vtkConvertSelection.h\"\n#include \"vtkDataArray.h\"\n#include \"vtkEdgeListIterator.h\"\n#include \"vtkEventForwarderCommand.h\"\n#include \"vtkExtractSelection.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n#include \"vtkPoints.h\"\n#include \"vtkSelection.h\"\n#include \"vtkSelectionNode.h\"\n#include \"vtkSignedCharArray.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkStringArray.h\"\n#include \"vtkTable.h\"\n#include \"vtkTree.h\"\n#include \"vtkVertexListIterator.h\"\n\n#include \n#include \n\nvtkCxxRevisionMacro(vtkExtractSelectedRows, \"1.2\");\nvtkStandardNewMacro(vtkExtractSelectedRows);\n\/\/----------------------------------------------------------------------------\nvtkExtractSelectedRows::vtkExtractSelectedRows()\n{\n this->AddOriginalRowIdsArray = false;\n this->SetNumberOfInputPorts(3);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkExtractSelectedRows::~vtkExtractSelectedRows()\n{\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkExtractSelectedRows::FillInputPortInformation(int port, vtkInformation* info)\n{\n if (port == 0)\n {\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkTable\");\n return 1;\n }\n else if (port == 1)\n {\n info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1);\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkSelection\");\n return 1;\n }\n else if (port == 2)\n {\n info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1);\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkAnnotationLayers\");\n return 1;\n }\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkExtractSelectedRows::SetSelectionConnection(vtkAlgorithmOutput* in)\n{\n this->SetInputConnection(1, in);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkExtractSelectedRows::SetAnnotationLayersConnection(vtkAlgorithmOutput* in)\n{\n this->SetInputConnection(2, in);\n}\n\n\n\/\/----------------------------------------------------------------------------\nint vtkExtractSelectedRows::RequestData(\n vtkInformation* vtkNotUsed(request), \n vtkInformationVector** inputVector, \n vtkInformationVector* outputVector)\n{\n vtkTable* input = vtkTable::GetData(inputVector[0]);\n vtkSelection* inputSelection = vtkSelection::GetData(inputVector[1]);\n vtkAnnotationLayers* inputAnnotations = vtkAnnotationLayers::GetData(inputVector[2]);\n vtkInformation* outInfo = outputVector->GetInformationObject(0);\n vtkTable* output = vtkTable::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()));\n\n if(!inputSelection && !inputAnnotations)\n {\n vtkErrorMacro(\"No vtkSelection or vtkAnnotationLayers provided as input.\");\n return 0;\n }\n\n vtkSmartPointer selection = vtkSmartPointer::New();\n int numSelections = 0;\n if(inputSelection)\n {\n selection->DeepCopy(inputSelection);\n numSelections++;\n }\n\n \/\/ If input annotations are provided, extract their selections only if\n \/\/ they are enabled and not hidden.\n if(inputAnnotations)\n {\n for(unsigned int i=0; iGetNumberOfAnnotations(); ++i)\n {\n vtkAnnotation* a = inputAnnotations->GetAnnotation(i);\n if ((a->GetInformation()->Has(vtkAnnotation::ENABLE()) && \n a->GetInformation()->Get(vtkAnnotation::ENABLE())==0) ||\n (a->GetInformation()->Has(vtkAnnotation::ENABLE()) && \n a->GetInformation()->Get(vtkAnnotation::ENABLE())==1 && \n a->GetInformation()->Has(vtkAnnotation::HIDE()) && \n a->GetInformation()->Get(vtkAnnotation::HIDE())==0))\n {\n continue;\n }\n selection->Union(a->GetSelection());\n numSelections++;\n }\n }\n\n \/\/ Handle case where there was no input selection and no enabled, non-hidden\n \/\/ annotations\n if(numSelections == 0)\n {\n output->ShallowCopy(input);\n return 1;\n }\n\n \/\/ Convert the selection to an INDICES selection\n vtkSmartPointer converted;\n converted.TakeReference(vtkConvertSelection::ToSelectionType(\n selection, input, vtkSelectionNode::INDICES, 0, vtkSelectionNode::ROW));\n if (!converted.GetPointer())\n {\n vtkErrorMacro(\"Selection conversion to INDICES failed.\");\n return 0;\n }\n\n vtkIdTypeArray* originalRowIds = vtkIdTypeArray::New();\n originalRowIds->SetName(\"vtkOriginalRowIds\");\n\n output->GetRowData()->CopyStructure(input->GetRowData());\n\n \/\/dodge segfault on empty tables\n if(converted->GetNumberOfNodes() > input->GetNumberOfRows())\n {\n vtkErrorMacro(\"Attempting to select more rows than the table contains.\");\n return 0;\n }\n\n for (unsigned int i = 0; i < converted->GetNumberOfNodes(); ++i)\n {\n vtkSelectionNode* node = converted->GetNode(i);\n if (node->GetFieldType() == vtkSelectionNode::ROW)\n {\n vtkIdTypeArray* list = vtkIdTypeArray::SafeDownCast(node->GetSelectionList());\n if (list)\n {\n vtkIdType numTuples = list->GetNumberOfTuples();\n for (vtkIdType j = 0; j < numTuples; ++j)\n {\n vtkIdType val = list->GetValue(j);\n output->InsertNextRow(input->GetRow(val));\n if (this->AddOriginalRowIdsArray)\n {\n originalRowIds->InsertNextValue(val);\n }\n }\n }\n }\n }\n if (this->AddOriginalRowIdsArray)\n {\n output->AddColumn(originalRowIds);\n }\n originalRowIds->Delete();\n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkExtractSelectedRows::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"AddOriginalRowIdsArray: \" << this->AddOriginalRowIdsArray <<\n endl;\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2014 Adam Grandquist\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n *\/\n\/**\n * @author Adam Grandquist\n * @copyright Apache\n *\/\n\n#include \"ReQL-expr.hpp\"\n\n#include \"ReQL.hpp\"\n\n#include \n\nnamespace ReQL {\n\nExpr::Expr() {\n Query _val = expr(_reql_new_null());\n sub_query.push_back(_val);\n query = _reql_new_datum(_val.query);\n}\n\nExpr::Expr(_ReQL_Op val) {\n query = val;\n}\n\nExpr::Expr(std::string val) {\n Query _val = expr(_reql_new_string(val));\n sub_query.push_back(_val);\n query = _reql_new_datum(_val.query);\n}\n\nExpr::Expr(double val) {\n Query _val = expr(_reql_new_number(val));\n sub_query.push_back(_val);\n query = _reql_new_datum(_val.query);\n}\n\nExpr::Expr(bool val) {\n Query _val = expr(_reql_new_bool(val));\n sub_query.push_back(_val);\n query = _reql_new_datum(_val.query);\n}\n\nExpr::Expr(std::vector val) {\n if (val.size() > std::numeric_limits::max()) {\n throw;\n }\n\n sub_query.assign(val.begin(), val.end());\n\n Query _val = expr(_reql_new_array(static_cast(val.size())));\n\n sub_query.push_back(_val);\n\n for (auto iter=val.cbegin(); iter!=val.cend(); ++iter) {\n _reql_array_append(_val.query, iter->query);\n }\n\n query = _reql_new_make_array(_val.query);\n}\n\nExpr::Expr(std::map val) {\n if (val.size() > std::numeric_limits::max()) {\n throw;\n }\n\n Query _val = expr(_reql_new_object(static_cast(val.size())));\n\n sub_query.push_back(_val);\n\n for (auto iter=val.cbegin(); iter!=val.cend(); ++iter) {\n Query key(iter->first);\n sub_query.push_back(key);\n sub_query.push_back(iter->second);\n _reql_object_add(_val.query, key.query, iter->second.query);\n }\n\n query = _reql_new_make_obj(_val.query);\n}\n\nExpr::~Expr() {\n delete query;\n}\n\nQuery expr() {\n return Query();\n}\n\nQuery expr(_ReQL_Op val) {\n return Query(val);\n}\n\nQuery expr(std::string val) {\n return Query(val);\n}\n\nQuery expr(double val) {\n return Query(val);\n}\n\nQuery expr(bool val) {\n return Query(val);\n}\n\nQuery expr(std::vector val) {\n return Query(val);\n}\n\nQuery expr(std::map val) {\n return Query(val);\n}\n\n}\nCatch and delete values that don't get owned properly.\/*\nCopyright 2014 Adam Grandquist\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n *\/\n\/**\n * @author Adam Grandquist\n * @copyright Apache\n *\/\n\n#include \"ReQL-expr.hpp\"\n\n#include \"ReQL.hpp\"\n\n#include \n\nnamespace ReQL {\n\nExpr::Expr() {\n Query _val = expr(_reql_new_null());\n sub_query.push_back(_val);\n query = _reql_new_datum(_val.query);\n}\n\nExpr::Expr(_ReQL_Op val) {\n query = val;\n}\n\nExpr::Expr(std::string val) {\n Query _val = expr(_reql_new_string(val));\n sub_query.push_back(_val);\n query = _reql_new_datum(_val.query);\n}\n\nExpr::Expr(double val) {\n Query _val = expr(_reql_new_number(val));\n sub_query.push_back(_val);\n query = _reql_new_datum(_val.query);\n}\n\nExpr::Expr(bool val) {\n Query _val = expr(_reql_new_bool(val));\n sub_query.push_back(_val);\n query = _reql_new_datum(_val.query);\n}\n\nExpr::Expr(std::vector val) {\n if (val.size() > std::numeric_limits::max()) {\n throw;\n }\n\n sub_query.assign(val.begin(), val.end());\n\n Query _val = expr(_reql_new_array(static_cast(val.size())));\n\n sub_query.push_back(_val);\n\n for (auto iter=val.cbegin(); iter!=val.cend(); ++iter) {\n _reql_array_append(_val.query, iter->query);\n }\n\n query = _reql_new_make_array(_val.query);\n}\n\nExpr::Expr(std::map val) {\n if (val.size() > std::numeric_limits::max()) {\n throw;\n }\n\n Query _val = expr(_reql_new_object(static_cast(val.size())));\n\n sub_query.push_back(_val);\n\n for (auto iter=val.cbegin(); iter!=val.cend(); ++iter) {\n Query key(iter->first);\n sub_query.push_back(key);\n sub_query.push_back(iter->second);\n _reql_object_add(_val.query, key.query, iter->second.query);\n }\n\n query = _reql_new_make_obj(_val.query);\n}\n\nExpr::~Expr() {\n switch (_reql_datum_type(query)) {\n case _REQL_R_ARRAY: {\n delete [] query->obj.datum.json.array.arr;\n break;\n }\n case _REQL_R_OBJECT: {\n delete [] query->obj.datum.json.object.pair;\n break;\n }\n default:\n break;\n }\n delete query;\n}\n\nQuery expr() {\n return Query();\n}\n\nQuery expr(_ReQL_Op val) {\n return Query(val);\n}\n\nQuery expr(std::string val) {\n return Query(val);\n}\n\nQuery expr(double val) {\n return Query(val);\n}\n\nQuery expr(bool val) {\n return Query(val);\n}\n\nQuery expr(std::vector val) {\n return Query(val);\n}\n\nQuery expr(std::map val) {\n return Query(val);\n}\n\n}\n<|endoftext|>"} {"text":"#include \"SoapyAudio.hpp\"\n\n#ifdef USE_HAMLIB\nRigThread::RigThread() {\n terminated.store(true);\n}\n\nRigThread::~RigThread() {\n\n}\n\n#ifdef __APPLE__\nvoid *RigThread::threadMain() {\n terminated.store(false);\n run();\n return this;\n};\n\nvoid *RigThread::pthread_helper(void *context) {\n return ((RigThread *) context)->threadMain();\n};\n#else\nvoid RigThread::threadMain() {\n terminated.store(false);\n run();\n};\n#endif\n\nvoid RigThread::setup(rig_model_t rig_model, std::string rig_file, int serial_rate) {\n rigModel = rig_model;\n rigFile = rig_file;\n serialRate = serial_rate;\n};\n\nvoid RigThread::run() {\n int retcode, status;\n\n SoapySDR_log(SOAPY_SDR_DEBUG, \"Rig thread starting.\"); \n\n rig = rig_init(rigModel);\n\tstrncpy(rig->state.rigport.pathname, rigFile.c_str(), FILPATHLEN - 1);\n\trig->state.rigport.parm.serial.rate = serialRate;\n\tretcode = rig_open(rig);\n\tchar *info_buf = (char *)rig_get_info(rig);\n SoapySDR_logf(SOAPY_SDR_DEBUG, \"Rig Info: %s\", info_buf);\n \n while (!terminated.load()) {\n std::this_thread::sleep_for(std::chrono::milliseconds(150));\n if (freqChanged.load()) {\n status = rig_get_freq(rig, RIG_VFO_CURR, &freq);\n if (freq != newFreq) {\n freq = newFreq;\n rig_set_freq(rig, RIG_VFO_CURR, freq);\n SoapySDR_logf(SOAPY_SDR_DEBUG, \"Set Rig Freq: %f\", newFreq);\n }\n \n freqChanged.store(false);\n } else {\n status = rig_get_freq(rig, RIG_VFO_CURR, &freq);\n }\n \n SoapySDR_logf(SOAPY_SDR_DEBUG, \"Rig Freq: %f\", freq);\n }\n \n rig_close(rig);\n \n SoapySDR_log(SOAPY_SDR_DEBUG, \"Rig thread exiting.\"); \n};\n\nfreq_t RigThread::getFrequency() {\n if (freqChanged.load()) {\n return newFreq;\n } else {\n return freq;\n }\n}\n\nvoid RigThread::setFrequency(freq_t new_freq) {\n newFreq = new_freq;\n freqChanged.store(true);\n}\n\nvoid RigThread::terminate() {\n terminated.store(true);\n};\n\nbool RigThread::isTerminated() {\n return terminated.load();\n}\n#endifMissing rig_cleanup.#include \"SoapyAudio.hpp\"\n\n#ifdef USE_HAMLIB\nRigThread::RigThread() {\n terminated.store(true);\n}\n\nRigThread::~RigThread() {\n\n}\n\n#ifdef __APPLE__\nvoid *RigThread::threadMain() {\n terminated.store(false);\n run();\n return this;\n};\n\nvoid *RigThread::pthread_helper(void *context) {\n return ((RigThread *) context)->threadMain();\n};\n#else\nvoid RigThread::threadMain() {\n terminated.store(false);\n run();\n};\n#endif\n\nvoid RigThread::setup(rig_model_t rig_model, std::string rig_file, int serial_rate) {\n rigModel = rig_model;\n rigFile = rig_file;\n serialRate = serial_rate;\n};\n\nvoid RigThread::run() {\n int retcode, status;\n\n SoapySDR_log(SOAPY_SDR_DEBUG, \"Rig thread starting.\"); \n\n rig = rig_init(rigModel);\n\tstrncpy(rig->state.rigport.pathname, rigFile.c_str(), FILPATHLEN - 1);\n\trig->state.rigport.parm.serial.rate = serialRate;\n\tretcode = rig_open(rig);\n\tchar *info_buf = (char *)rig_get_info(rig);\n SoapySDR_logf(SOAPY_SDR_DEBUG, \"Rig Info: %s\", info_buf);\n \n while (!terminated.load()) {\n std::this_thread::sleep_for(std::chrono::milliseconds(150));\n if (freqChanged.load()) {\n status = rig_get_freq(rig, RIG_VFO_CURR, &freq);\n if (freq != newFreq) {\n freq = newFreq;\n rig_set_freq(rig, RIG_VFO_CURR, freq);\n SoapySDR_logf(SOAPY_SDR_DEBUG, \"Set Rig Freq: %f\", newFreq);\n }\n \n freqChanged.store(false);\n } else {\n status = rig_get_freq(rig, RIG_VFO_CURR, &freq);\n }\n \n SoapySDR_logf(SOAPY_SDR_DEBUG, \"Rig Freq: %f\", freq);\n }\n \n rig_close(rig);\n rig_cleanup(rig);\n \n SoapySDR_log(SOAPY_SDR_DEBUG, \"Rig thread exiting.\"); \n};\n\nfreq_t RigThread::getFrequency() {\n if (freqChanged.load()) {\n return newFreq;\n } else {\n return freq;\n }\n}\n\nvoid RigThread::setFrequency(freq_t new_freq) {\n newFreq = new_freq;\n freqChanged.store(true);\n}\n\nvoid RigThread::terminate() {\n terminated.store(true);\n};\n\nbool RigThread::isTerminated() {\n return terminated.load();\n}\n#endif<|endoftext|>"} {"text":"\/\/\n\/\/ Decoder.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 30\/12\/20.\n\/\/ Copyright © 2020 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef InstructionSets_PowerPC_Decoder_hpp\n#define InstructionSets_PowerPC_Decoder_hpp\n\n#include \"Instruction.hpp\"\n\nnamespace InstructionSet {\nnamespace PowerPC {\n\nenum class Model {\n\t\/\/\/ i.e. 32-bit, with POWER carry-over instructions.\n\tMPC601,\n\t\/\/\/ i.e. 32-bit, no POWER instructions.\n\tMPC603,\n\t\/\/\/ i.e. 64-bit.\n\tMPC620,\n};\n\nconstexpr bool is64bit(Model model) {\n\treturn model == Model::MPC620;\n}\n\nconstexpr bool is32bit(Model model) {\n\treturn !is64bit(model);\n}\n\nconstexpr bool is601(Model model) {\n\treturn model == Model::MPC601;\n}\n\n\/*!\n\tImplements PowerPC instruction decoding.\n\n\t@c model Indicates the instruction set to decode.\n\n\t@c validate_reserved_bits If set to @c true, check that all\n\treserved bits are 0 and produce an invalid opcode if not. Otherwise does no\n\tinspection of reserved bits.\n\n\tTODO: determine what specific models of PowerPC do re: reserved bits.\n*\/\ntemplate struct Decoder {\n\tInstruction decode(uint32_t opcode);\n};\n\n}\n}\n\n#endif \/* InstructionSets_PowerPC_Decoder_hpp *\/\nImprove accuracy of comment.\/\/\n\/\/ Decoder.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 30\/12\/20.\n\/\/ Copyright © 2020 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef InstructionSets_PowerPC_Decoder_hpp\n#define InstructionSets_PowerPC_Decoder_hpp\n\n#include \"Instruction.hpp\"\n\nnamespace InstructionSet {\nnamespace PowerPC {\n\nenum class Model {\n\t\/\/\/ i.e. 32-bit, with POWER carry-over instructions.\n\tMPC601,\n\t\/\/\/ i.e. 32-bit, no POWER instructions.\n\tMPC603,\n\t\/\/\/ i.e. 64-bit.\n\tMPC620,\n};\n\nconstexpr bool is64bit(Model model) {\n\treturn model == Model::MPC620;\n}\n\nconstexpr bool is32bit(Model model) {\n\treturn !is64bit(model);\n}\n\nconstexpr bool is601(Model model) {\n\treturn model == Model::MPC601;\n}\n\n\/*!\n\tImplements PowerPC instruction decoding.\n\n\t@c model Indicates the instruction set to decode.\n\n\t@c validate_reserved_bits If set to @c true, check that all\n\treserved bits are 0 or 1 as required and produce an invalid opcode if not.\n\tOtherwise does no inspection of reserved bits.\n\n\tTODO: determine what specific models of PowerPC do re: reserved bits.\n*\/\ntemplate struct Decoder {\n\tInstruction decode(uint32_t opcode);\n};\n\n}\n}\n\n#endif \/* InstructionSets_PowerPC_Decoder_hpp *\/\n<|endoftext|>"} {"text":"\/*\n * Copyright 2015 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkPathPriv.h\"\n#include \"SkRecords.h\"\n\nnamespace SkRecords {\n PreCachedPath::PreCachedPath(const SkPath& path) : SkPath(path) {\n this->updateBoundsCache();\n#if 0 \/\/ Disabled to see if we ever really race on this. It costs time, chromium:496982.\n SkPathPriv::FirstDirection junk;\n (void)SkPathPriv::CheapComputeFirstDirection(*this, &junk);\n#endif\n }\n\n TypedMatrix::TypedMatrix(const SkMatrix& matrix) : SkMatrix(matrix) {\n (void)this->getType();\n }\n}\nPre-cache SkPath's genID in PreCachedPath too\/*\n * Copyright 2015 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkPathPriv.h\"\n#include \"SkRecords.h\"\n\nnamespace SkRecords {\n PreCachedPath::PreCachedPath(const SkPath& path) : SkPath(path) {\n this->updateBoundsCache();\n (void)this->getGenerationID();\n#if 0 \/\/ Disabled to see if we ever really race on this. It costs time, chromium:496982.\n SkPathPriv::FirstDirection junk;\n (void)SkPathPriv::CheapComputeFirstDirection(*this, &junk);\n#endif\n }\n\n TypedMatrix::TypedMatrix(const SkMatrix& matrix) : SkMatrix(matrix) {\n (void)this->getType();\n }\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtDeclarative module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** GNU Lesser General Public License Usage\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this\n** file. Please review the following information to ensure the GNU Lesser\n** General Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file. Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** Other Usage\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qsgdefaultglyphnode_p_p.h\"\n\n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n\nQT_BEGIN_NAMESPACE\n\nclass QSGTextMaskMaterialData : public QSGMaterialShader\n{\npublic:\n QSGTextMaskMaterialData();\n\n virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);\n virtual char const *const *attributeNames() const;\nprivate:\n virtual void initialize();\n virtual const char *vertexShader() const;\n virtual const char *fragmentShader() const;\n\n int m_matrix_id;\n int m_color_id;\n int m_textureScale_id;\n};\n\nconst char *QSGTextMaskMaterialData::vertexShader() const {\n return\n \"uniform highp mat4 matrix; \\n\"\n \"uniform highp vec2 textureScale; \\n\"\n \"attribute highp vec4 vCoord; \\n\"\n \"attribute highp vec2 tCoord; \\n\"\n \"varying highp vec2 sampleCoord; \\n\"\n \"void main() { \\n\"\n \" sampleCoord = tCoord * textureScale; \\n\"\n \" gl_Position = matrix * vCoord; \\n\"\n \"}\";\n}\n\nconst char *QSGTextMaskMaterialData::fragmentShader() const {\n return\n \"varying highp vec2 sampleCoord; \\n\"\n \"uniform sampler2D texture; \\n\"\n \"uniform lowp vec4 color; \\n\"\n \"void main() { \\n\"\n \" gl_FragColor = color * texture2D(texture, sampleCoord).a; \\n\"\n \"}\";\n}\n\nchar const *const *QSGTextMaskMaterialData::attributeNames() const\n{\n static char const *const attr[] = { \"vCoord\", \"tCoord\", 0 };\n return attr;\n}\n\nQSGTextMaskMaterialData::QSGTextMaskMaterialData()\n{\n}\n\nvoid QSGTextMaskMaterialData::initialize()\n{\n m_matrix_id = program()->uniformLocation(\"matrix\");\n m_color_id = program()->uniformLocation(\"color\");\n m_textureScale_id = program()->uniformLocation(\"textureScale\");\n}\n\nvoid QSGTextMaskMaterialData::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect)\n{\n Q_ASSERT(oldEffect == 0 || newEffect->type() == oldEffect->type());\n QSGTextMaskMaterial *material = static_cast(newEffect);\n QSGTextMaskMaterial *oldMaterial = static_cast(oldEffect);\n\n if (oldMaterial == 0 || material->color() != oldMaterial->color() || state.isOpacityDirty()) {\n QVector4D color(material->color().redF(), material->color().greenF(),\n material->color().blueF(), material->color().alphaF());\n color *= state.opacity();\n program()->setUniformValue(m_color_id, color);\n }\n\n bool updated = material->ensureUpToDate();\n Q_ASSERT(material->texture());\n\n Q_ASSERT(oldMaterial == 0 || oldMaterial->texture());\n if (updated\n || oldMaterial == 0\n || oldMaterial->texture()->textureId() != material->texture()->textureId()) {\n program()->setUniformValue(m_textureScale_id, QVector2D(1.0 \/ material->cacheTextureWidth(),\n 1.0 \/ material->cacheTextureHeight()));\n glBindTexture(GL_TEXTURE_2D, material->texture()->textureId());\n\n \/\/ Set the mag\/min filters to be linear. We only need to do this when the texture\n \/\/ has been recreated.\n if (updated) {\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n }\n }\n\n if (state.isMatrixDirty())\n program()->setUniformValue(m_matrix_id, state.combinedMatrix());\n}\n\nQSGTextMaskMaterial::QSGTextMaskMaterial(const QRawFont &font)\n : m_texture(0), m_glyphCache(), m_font(font)\n{\n init();\n}\n\nQSGTextMaskMaterial::~QSGTextMaskMaterial()\n{\n}\n\nvoid QSGTextMaskMaterial::init()\n{\n Q_ASSERT(m_font.isValid());\n\n QFontEngineGlyphCache::Type type = QFontEngineGlyphCache::Raster_A8;\n setFlag(Blending, true);\n\n QOpenGLContext *ctx = const_cast(QOpenGLContext::currentContext());\n Q_ASSERT(ctx != 0);\n\n QRawFontPrivate *fontD = QRawFontPrivate::get(m_font);\n if (fontD->fontEngine != 0) {\n m_glyphCache = fontD->fontEngine->glyphCache(ctx, type, QTransform());\n if (!m_glyphCache || m_glyphCache->cacheType() != type) {\n m_glyphCache = new QOpenGLTextureGlyphCache(type, QTransform());\n fontD->fontEngine->setGlyphCache(ctx, m_glyphCache.data());\n }\n }\n}\n\nvoid QSGTextMaskMaterial::populate(const QPointF &p,\n const QVector &glyphIndexes,\n const QVector &glyphPositions,\n QSGGeometry *geometry,\n QRectF *boundingRect,\n QPointF *baseLine)\n{\n Q_ASSERT(m_font.isValid());\n QVector fixedPointPositions;\n for (int i=0; ipopulate(fontD->fontEngine, glyphIndexes.size(), glyphIndexes.constData(),\n fixedPointPositions.data());\n cache->fillInPendingGlyphs();\n\n int margin = cache->glyphMargin();\n\n Q_ASSERT(geometry->indexType() == GL_UNSIGNED_SHORT);\n geometry->allocate(glyphIndexes.size() * 4, glyphIndexes.size() * 6);\n QVector4D *vp = (QVector4D *)geometry->vertexDataAsTexturedPoint2D();\n Q_ASSERT(geometry->stride() == sizeof(QVector4D));\n ushort *ip = geometry->indexDataAsUShort();\n\n QPointF position(p.x(), p.y() - m_font.ascent());\n bool supportsSubPixelPositions = fontD->fontEngine->supportsSubPixelPositions();\n for (int i=0; isubPixelPositionForX(QFixed::fromReal(glyphPositions.at(i).x()));\n\n QTextureGlyphCache::GlyphAndSubPixelPosition glyph(glyphIndexes.at(i), subPixelPosition);\n const QTextureGlyphCache::Coord &c = cache->coords.value(glyph);\n\n QPointF glyphPosition = glyphPositions.at(i) + position;\n int x = qRound(glyphPosition.x()) + c.baseLineX - margin;\n int y = qRound(glyphPosition.y()) - c.baseLineY - margin;\n\n *boundingRect |= QRectF(x + margin, y + margin, c.w, c.h);\n\n float cx1 = x;\n float cx2 = x + c.w;\n float cy1 = y;\n float cy2 = y + c.h;\n\n float tx1 = c.x;\n float tx2 = (c.x + c.w);\n float ty1 = c.y;\n float ty2 = (c.y + c.h);\n\n if (baseLine->isNull())\n *baseLine = glyphPosition;\n\n vp[4 * i + 0] = QVector4D(cx1, cy1, tx1, ty1);\n vp[4 * i + 1] = QVector4D(cx2, cy1, tx2, ty1);\n vp[4 * i + 2] = QVector4D(cx1, cy2, tx1, ty2);\n vp[4 * i + 3] = QVector4D(cx2, cy2, tx2, ty2);\n\n int o = i * 4;\n ip[6 * i + 0] = o + 0;\n ip[6 * i + 1] = o + 2;\n ip[6 * i + 2] = o + 3;\n ip[6 * i + 3] = o + 3;\n ip[6 * i + 4] = o + 1;\n ip[6 * i + 5] = o + 0;\n }\n}\n\nQSGMaterialType *QSGTextMaskMaterial::type() const\n{\n static QSGMaterialType type;\n return &type;\n}\n\nQOpenGLTextureGlyphCache *QSGTextMaskMaterial::glyphCache() const\n{\n return static_cast(m_glyphCache.data());\n}\n\nQSGMaterialShader *QSGTextMaskMaterial::createShader() const\n{\n return new QSGTextMaskMaterialData;\n}\n\nint QSGTextMaskMaterial::compare(const QSGMaterial *o) const\n{\n Q_ASSERT(o && type() == o->type());\n const QSGTextMaskMaterial *other = static_cast(o);\n if (m_glyphCache != other->m_glyphCache)\n return m_glyphCache - other->m_glyphCache;\n QRgb c1 = m_color.rgba();\n QRgb c2 = other->m_color.rgba();\n return int(c2 < c1) - int(c1 < c2);\n}\n\nbool QSGTextMaskMaterial::ensureUpToDate()\n{\n QSize glyphCacheSize(glyphCache()->width(), glyphCache()->height());\n if (glyphCacheSize != m_size) {\n if (m_texture)\n delete m_texture;\n m_texture = new QSGPlainTexture();\n m_texture->setTextureId(glyphCache()->texture());\n m_texture->setTextureSize(QSize(glyphCache()->width(), glyphCache()->height()));\n m_texture->setOwnsTexture(false);\n\n m_size = glyphCacheSize;\n\n return true;\n } else {\n return false;\n }\n}\n\nint QSGTextMaskMaterial::cacheTextureWidth() const\n{\n return glyphCache()->width();\n}\n\nint QSGTextMaskMaterial::cacheTextureHeight() const\n{\n return glyphCache()->height();\n}\n\nQT_END_NAMESPACE\nCompile, qtextureglyphcache_gl_p.h -> qopengltextureglyphcache_p.h\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtDeclarative module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** GNU Lesser General Public License Usage\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this\n** file. Please review the following information to ensure the GNU Lesser\n** General Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file. Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** Other Usage\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qsgdefaultglyphnode_p_p.h\"\n\n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n\nQT_BEGIN_NAMESPACE\n\nclass QSGTextMaskMaterialData : public QSGMaterialShader\n{\npublic:\n QSGTextMaskMaterialData();\n\n virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);\n virtual char const *const *attributeNames() const;\nprivate:\n virtual void initialize();\n virtual const char *vertexShader() const;\n virtual const char *fragmentShader() const;\n\n int m_matrix_id;\n int m_color_id;\n int m_textureScale_id;\n};\n\nconst char *QSGTextMaskMaterialData::vertexShader() const {\n return\n \"uniform highp mat4 matrix; \\n\"\n \"uniform highp vec2 textureScale; \\n\"\n \"attribute highp vec4 vCoord; \\n\"\n \"attribute highp vec2 tCoord; \\n\"\n \"varying highp vec2 sampleCoord; \\n\"\n \"void main() { \\n\"\n \" sampleCoord = tCoord * textureScale; \\n\"\n \" gl_Position = matrix * vCoord; \\n\"\n \"}\";\n}\n\nconst char *QSGTextMaskMaterialData::fragmentShader() const {\n return\n \"varying highp vec2 sampleCoord; \\n\"\n \"uniform sampler2D texture; \\n\"\n \"uniform lowp vec4 color; \\n\"\n \"void main() { \\n\"\n \" gl_FragColor = color * texture2D(texture, sampleCoord).a; \\n\"\n \"}\";\n}\n\nchar const *const *QSGTextMaskMaterialData::attributeNames() const\n{\n static char const *const attr[] = { \"vCoord\", \"tCoord\", 0 };\n return attr;\n}\n\nQSGTextMaskMaterialData::QSGTextMaskMaterialData()\n{\n}\n\nvoid QSGTextMaskMaterialData::initialize()\n{\n m_matrix_id = program()->uniformLocation(\"matrix\");\n m_color_id = program()->uniformLocation(\"color\");\n m_textureScale_id = program()->uniformLocation(\"textureScale\");\n}\n\nvoid QSGTextMaskMaterialData::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect)\n{\n Q_ASSERT(oldEffect == 0 || newEffect->type() == oldEffect->type());\n QSGTextMaskMaterial *material = static_cast(newEffect);\n QSGTextMaskMaterial *oldMaterial = static_cast(oldEffect);\n\n if (oldMaterial == 0 || material->color() != oldMaterial->color() || state.isOpacityDirty()) {\n QVector4D color(material->color().redF(), material->color().greenF(),\n material->color().blueF(), material->color().alphaF());\n color *= state.opacity();\n program()->setUniformValue(m_color_id, color);\n }\n\n bool updated = material->ensureUpToDate();\n Q_ASSERT(material->texture());\n\n Q_ASSERT(oldMaterial == 0 || oldMaterial->texture());\n if (updated\n || oldMaterial == 0\n || oldMaterial->texture()->textureId() != material->texture()->textureId()) {\n program()->setUniformValue(m_textureScale_id, QVector2D(1.0 \/ material->cacheTextureWidth(),\n 1.0 \/ material->cacheTextureHeight()));\n glBindTexture(GL_TEXTURE_2D, material->texture()->textureId());\n\n \/\/ Set the mag\/min filters to be linear. We only need to do this when the texture\n \/\/ has been recreated.\n if (updated) {\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n }\n }\n\n if (state.isMatrixDirty())\n program()->setUniformValue(m_matrix_id, state.combinedMatrix());\n}\n\nQSGTextMaskMaterial::QSGTextMaskMaterial(const QRawFont &font)\n : m_texture(0), m_glyphCache(), m_font(font)\n{\n init();\n}\n\nQSGTextMaskMaterial::~QSGTextMaskMaterial()\n{\n}\n\nvoid QSGTextMaskMaterial::init()\n{\n Q_ASSERT(m_font.isValid());\n\n QFontEngineGlyphCache::Type type = QFontEngineGlyphCache::Raster_A8;\n setFlag(Blending, true);\n\n QOpenGLContext *ctx = const_cast(QOpenGLContext::currentContext());\n Q_ASSERT(ctx != 0);\n\n QRawFontPrivate *fontD = QRawFontPrivate::get(m_font);\n if (fontD->fontEngine != 0) {\n m_glyphCache = fontD->fontEngine->glyphCache(ctx, type, QTransform());\n if (!m_glyphCache || m_glyphCache->cacheType() != type) {\n m_glyphCache = new QOpenGLTextureGlyphCache(type, QTransform());\n fontD->fontEngine->setGlyphCache(ctx, m_glyphCache.data());\n }\n }\n}\n\nvoid QSGTextMaskMaterial::populate(const QPointF &p,\n const QVector &glyphIndexes,\n const QVector &glyphPositions,\n QSGGeometry *geometry,\n QRectF *boundingRect,\n QPointF *baseLine)\n{\n Q_ASSERT(m_font.isValid());\n QVector fixedPointPositions;\n for (int i=0; ipopulate(fontD->fontEngine, glyphIndexes.size(), glyphIndexes.constData(),\n fixedPointPositions.data());\n cache->fillInPendingGlyphs();\n\n int margin = cache->glyphMargin();\n\n Q_ASSERT(geometry->indexType() == GL_UNSIGNED_SHORT);\n geometry->allocate(glyphIndexes.size() * 4, glyphIndexes.size() * 6);\n QVector4D *vp = (QVector4D *)geometry->vertexDataAsTexturedPoint2D();\n Q_ASSERT(geometry->stride() == sizeof(QVector4D));\n ushort *ip = geometry->indexDataAsUShort();\n\n QPointF position(p.x(), p.y() - m_font.ascent());\n bool supportsSubPixelPositions = fontD->fontEngine->supportsSubPixelPositions();\n for (int i=0; isubPixelPositionForX(QFixed::fromReal(glyphPositions.at(i).x()));\n\n QTextureGlyphCache::GlyphAndSubPixelPosition glyph(glyphIndexes.at(i), subPixelPosition);\n const QTextureGlyphCache::Coord &c = cache->coords.value(glyph);\n\n QPointF glyphPosition = glyphPositions.at(i) + position;\n int x = qRound(glyphPosition.x()) + c.baseLineX - margin;\n int y = qRound(glyphPosition.y()) - c.baseLineY - margin;\n\n *boundingRect |= QRectF(x + margin, y + margin, c.w, c.h);\n\n float cx1 = x;\n float cx2 = x + c.w;\n float cy1 = y;\n float cy2 = y + c.h;\n\n float tx1 = c.x;\n float tx2 = (c.x + c.w);\n float ty1 = c.y;\n float ty2 = (c.y + c.h);\n\n if (baseLine->isNull())\n *baseLine = glyphPosition;\n\n vp[4 * i + 0] = QVector4D(cx1, cy1, tx1, ty1);\n vp[4 * i + 1] = QVector4D(cx2, cy1, tx2, ty1);\n vp[4 * i + 2] = QVector4D(cx1, cy2, tx1, ty2);\n vp[4 * i + 3] = QVector4D(cx2, cy2, tx2, ty2);\n\n int o = i * 4;\n ip[6 * i + 0] = o + 0;\n ip[6 * i + 1] = o + 2;\n ip[6 * i + 2] = o + 3;\n ip[6 * i + 3] = o + 3;\n ip[6 * i + 4] = o + 1;\n ip[6 * i + 5] = o + 0;\n }\n}\n\nQSGMaterialType *QSGTextMaskMaterial::type() const\n{\n static QSGMaterialType type;\n return &type;\n}\n\nQOpenGLTextureGlyphCache *QSGTextMaskMaterial::glyphCache() const\n{\n return static_cast(m_glyphCache.data());\n}\n\nQSGMaterialShader *QSGTextMaskMaterial::createShader() const\n{\n return new QSGTextMaskMaterialData;\n}\n\nint QSGTextMaskMaterial::compare(const QSGMaterial *o) const\n{\n Q_ASSERT(o && type() == o->type());\n const QSGTextMaskMaterial *other = static_cast(o);\n if (m_glyphCache != other->m_glyphCache)\n return m_glyphCache - other->m_glyphCache;\n QRgb c1 = m_color.rgba();\n QRgb c2 = other->m_color.rgba();\n return int(c2 < c1) - int(c1 < c2);\n}\n\nbool QSGTextMaskMaterial::ensureUpToDate()\n{\n QSize glyphCacheSize(glyphCache()->width(), glyphCache()->height());\n if (glyphCacheSize != m_size) {\n if (m_texture)\n delete m_texture;\n m_texture = new QSGPlainTexture();\n m_texture->setTextureId(glyphCache()->texture());\n m_texture->setTextureSize(QSize(glyphCache()->width(), glyphCache()->height()));\n m_texture->setOwnsTexture(false);\n\n m_size = glyphCacheSize;\n\n return true;\n } else {\n return false;\n }\n}\n\nint QSGTextMaskMaterial::cacheTextureWidth() const\n{\n return glyphCache()->width();\n}\n\nint QSGTextMaskMaterial::cacheTextureHeight() const\n{\n return glyphCache()->height();\n}\n\nQT_END_NAMESPACE\n<|endoftext|>"} {"text":"\/* dtkComposerNodeLoopDataComposite.cpp --- \n * \n * Author: Thibaud Kloczko\n * Copyright (C) 2011 - Thibaud Kloczko, Inria.\n * Created: Wed Oct 12 16:02:18 2011 (+0200)\n * Version: $Id$\n * Last-Updated: Fri Oct 14 16:27:22 2011 (+0200)\n * By: Julien Wintz\n * Update #: 140\n *\/\n\n\/* Commentary: \n * \n *\/\n\n\/* Change log:\n * \n *\/\n\n#include \"dtkComposerNodeLoopDataComposite.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#define DTK_DEBUG_COMPOSER_INTERACTION 1\n#define DTK_DEBUG_COMPOSER_EVALUATION 1\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ dtkComposerNodeLoopDataCompositePrivate declaration\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass dtkComposerNodeLoopDataCompositePrivate\n{\npublic:\n dtkComposerNodeControlBlock *block_loop;\n\npublic:\n dtkxarch_int from_default;\n dtkxarch_int to_default;\n dtkxarch_int step_default;\n\n dtkxarch_int from;\n dtkxarch_int to;\n dtkxarch_int step;\n dtkxarch_int index;\n\n dtkAbstractData *item;\n\n dtkAbstractDataComposite *composite;\n\n bool valid_input_composite;\n};\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ dtkComposerNodeLoopDataComposite implementation\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ndtkComposerNodeLoopDataComposite::dtkComposerNodeLoopDataComposite(dtkComposerNode *parent) : dtkComposerNodeLoop(parent), d(new dtkComposerNodeLoopDataCompositePrivate)\n{\n d->block_loop = this->addBlock(\"loop\");\n d->block_loop->setInteractive(false);\n d->block_loop->setHeightRatio(1);\n this->addInputProperty(d->block_loop->addInputProperty(\"from\", dtkComposerNodeProperty::Input, dtkComposerNodeProperty::Single, dtkComposerNodeProperty::None, this));\n this->addInputProperty(d->block_loop->addInputProperty(\"to\", dtkComposerNodeProperty::Input, dtkComposerNodeProperty::Single, dtkComposerNodeProperty::None, this));\n this->addInputProperty(d->block_loop->addInputProperty(\"step\", dtkComposerNodeProperty::Input, dtkComposerNodeProperty::Single, dtkComposerNodeProperty::None, this));\n this->addInputProperty(d->block_loop->addInputProperty(\"item\", dtkComposerNodeProperty::Output, dtkComposerNodeProperty::Multiple, dtkComposerNodeProperty::AsLoopInput, this));\n\n this->setColor(QColor(\"#2ABFFF\"));\n this->setInputPropertyName(\"composite\");\n this->setTitle(\"Composite Data Loop\");\n this->setType(\"dtkComposerLoopDataComposite\");\n\n d->from_default = 0;\n d->to_default = 0;\n d->step_default = 1;\n\n d->from = -1;\n d->to = -1;\n d->step = -1;\n\n d->index = 0;\n\n d->item = NULL;\n d->composite = NULL;\n\n d->valid_input_composite = false;\n}\n\ndtkComposerNodeLoopDataComposite::~dtkComposerNodeLoopDataComposite(void)\n{\n delete d;\n\n d = NULL;\n}\n\nvoid dtkComposerNodeLoopDataComposite::layout(void)\n{\n dtkComposerNodeControl::layout();\n\n QRectF node_rect = this->boundingRect();\n qreal node_radius = this->nodeRadius();\n\n int j;\n qreal offset = 23;\n\n dtkComposerNodeControlBlock *block = this->blocks().at(0);\n\n block->setRect(QRectF(node_rect.x(),\n node_rect.y() + offset,\n node_rect.width(),\n block->height()));\n\n j = 0;\n foreach(dtkComposerNodeProperty *property, block->inputProperties()) {\n\n property->setRect(QRectF(block->mapRectToParent(block->rect()).left() + node_radius,\n block->mapRectToParent(block->rect()).top() + node_radius * (4*j + 1),\n 2 * node_radius,\n 2 * node_radius ));\n\n if (property->name() == \"item\") {\n property->mirror();\n j++;\n }\n\n j++;\n }\n j = 5;\n foreach(dtkComposerNodeProperty *property, block->outputProperties()) {\n\n property->setRect(QRectF(block->mapRectToParent(block->rect()).right() - node_radius * 3,\n block->mapRectToParent(block->rect()).top() + node_radius * (4*j + 1),\n 2 * node_radius,\n 2 * node_radius ));\n \n j++;\n }\n}\n\nvoid dtkComposerNodeLoopDataComposite::update(void)\n{\n \n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_PRETTY_FUNCTION << this;\n#endif\n\n if (this->isRunning()) {\n\n return;\n \n } else {\n\n if (!this->dirty())\n return;\n\n \/\/ -- Check dirty input value\n\n if (this->dirtyInputValue())\n return;\n\n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_GREEN << DTK_PRETTY_FUNCTION << \"Dirty input value OK\" << DTK_NO_COLOR;\n#endif\n\n \/\/ -- Check dirty inputs\n\n if (this->dtkComposerNode::dirtyUpstreamNodes())\n return;\n\n \/\/ -- Mark dirty outputs\n\n this->dtkComposerNode::markDirtyDownstreamNodes();\n\n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_GREEN << DTK_PRETTY_FUNCTION << \"All output nodes are set to dirty\" << DTK_NO_COLOR;\n#endif\n\n \/\/ -- Clean active input routes\n\n this->cleanInputActiveRoutes();\n\n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << \"Input active routes cleaned\" << DTK_NO_COLOR;\n#endif\n\n \/\/ -- Pull\n\n foreach(dtkComposerEdge *i_route, this->inputRoutes())\n this->pull(i_route, i_route->destination()); \n\n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << \"Pull done\" << DTK_NO_COLOR;\n#endif\n\n \/\/ -- Set input composite and loop options\n\n foreach(dtkComposerEdge *i_route, this->inputActiveRoutes()) {\n if (i_route->destination() == this->inputProperty()) {\n \n dtkAbstractData *data = NULL;\n\n if(dtkAbstractData *dt = qobject_cast(i_route->source()->node()->object())) {\n \n data = dt; \n\n } else if(dtkAbstractProcess *process = qobject_cast(i_route->source()->node()->object())) {\n \n if(i_route->source()->node()->outputProperties().count() >= 1)\n data = process->output(i_route->source()->node()->number(i_route->source()));\n else\n data = process->output();\n\n }\n \n if (data) {\n\n d->composite = qobject_cast(data);\n if (!d->composite) {\n dtkDebug() << DTK_PRETTY_FUNCTION << \"input data is not of dtkAbstractDataComposite* type.\";\n return;\n }\n if (d->composite->count())\n this->setObject((*d->composite)[0]);\n\n d->to_default = d->composite->count()-1;\n \n d->valid_input_composite = true;\n\n } else {\n\n dtkDebug() << DTK_PRETTY_FUNCTION << \"input data is not defined\";\n return;\n\n }\n\n } else if (i_route->destination()->name() == \"from\") {\n\n d->from = (dtkxarch_int)(i_route->source()->node()->value(i_route->source()).toLongLong()); \n\n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << \"from value =\" << d->from << DTK_NO_COLOR;\n#endif\n\n } else if (i_route->destination()->name() == \"to\") {\n\n d->to = (dtkxarch_int)(i_route->source()->node()->value(i_route->source()).toLongLong()); \n\n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << \"to value =\" << d->to << DTK_NO_COLOR;\n#endif\n\n } else if (i_route->destination()->name() == \"step\") {\n\n d->step = (dtkxarch_int)(i_route->source()->node()->value(i_route->source()).toLongLong());\n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << \"step value =\" << d->step << DTK_NO_COLOR;\n#endif\n\n }\n\n qDebug() << i_route;\n\n }\n \n if (!d->valid_input_composite) {\n dtkDebug() << DTK_PRETTY_FUNCTION << \" input composite property is not connected.\";\n return; \n }\n\n if ((d->from > d->to) && (d->from > d->to_default))\n d->from = d->to_default;\n else if (d->from < 0)\n d->from = d->from_default;\n else if (d->to < d->from && d->to < 0)\n d->to = d->from_default;\n else if (d->to > d->to_default)\n d->to = d->to_default;\n\n if (d->step < 0 && (d->from < d->to))\n d->step = d->step_default;\n\n d->index = d->from;\n \n \/\/ -- Running logics of conditional block\n \n this->setRunning(true);\n\n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_RED << \"Loop initialization done\" << DTK_NO_COLOR;\n#endif\n\n while(d->index <= d->to) {\n\n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_RED << \"Loop is running, index = \" << d->index << DTK_NO_COLOR;\n#endif\n \n d->item = (*d->composite)[d->index]; \n this->run();\n this->updatePassThroughVariables();\n d->index += d->step;\n \n }\n \n \/\/ -- Clean active output routes\n\n this->cleanOutputActiveRoutes();\n\n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << \"Output active routes cleaned\" << DTK_NO_COLOR;\n#endif\n \n \/\/ -- Push\n \n foreach(dtkComposerEdge *o_route, this->outputRoutes())\n this->push(o_route, o_route->source());\n\n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << \"Push done\" << DTK_NO_COLOR;\n#endif\n\n \/\/ -- Forward\n \n this->setDirty(false);\n this->setRunning(false);\n \n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_BLUE << DTK_PRETTY_FUNCTION << \"Forward done\" << DTK_NO_COLOR;\n#endif\n\n foreach(dtkComposerEdge *o_route, this->outputRoutes())\n o_route->destination()->node()->update();\n }\n}\n\nvoid dtkComposerNodeLoopDataComposite::onEdgeConnected(dtkComposerEdge *edge)\n{\n if(true)\n edge->invalidate();\n else\n ; \/\/ dtkComposerNodeLoop::onEdgeConnected(edge);\n}\n\nvoid dtkComposerNodeLoopDataComposite::pull(dtkComposerEdge *i_route, dtkComposerNodeProperty *property)\n{\n if (property->name() == \"from\" || property->name() == \"to\" || property->name() == \"step\")\n this->addInputActiveRoute(i_route);\n\n dtkComposerNodeLoop::pull(i_route, property);\n}\n \nQVariant dtkComposerNodeLoopDataComposite::value(dtkComposerNodeProperty *property)\n{\n return QVariant();\n}\nAs property type checking is not yet implemented, composite node data loop will invalidate the edge but build the routes anyway.\/* dtkComposerNodeLoopDataComposite.cpp --- \n * \n * Author: Thibaud Kloczko\n * Copyright (C) 2011 - Thibaud Kloczko, Inria.\n * Created: Wed Oct 12 16:02:18 2011 (+0200)\n * Version: $Id$\n * Last-Updated: Fri Oct 14 16:28:35 2011 (+0200)\n * By: Julien Wintz\n * Update #: 143\n *\/\n\n\/* Commentary: \n * \n *\/\n\n\/* Change log:\n * \n *\/\n\n#include \"dtkComposerNodeLoopDataComposite.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#define DTK_DEBUG_COMPOSER_INTERACTION 1\n#define DTK_DEBUG_COMPOSER_EVALUATION 1\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ dtkComposerNodeLoopDataCompositePrivate declaration\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass dtkComposerNodeLoopDataCompositePrivate\n{\npublic:\n dtkComposerNodeControlBlock *block_loop;\n\npublic:\n dtkxarch_int from_default;\n dtkxarch_int to_default;\n dtkxarch_int step_default;\n\n dtkxarch_int from;\n dtkxarch_int to;\n dtkxarch_int step;\n dtkxarch_int index;\n\n dtkAbstractData *item;\n\n dtkAbstractDataComposite *composite;\n\n bool valid_input_composite;\n};\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ dtkComposerNodeLoopDataComposite implementation\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ndtkComposerNodeLoopDataComposite::dtkComposerNodeLoopDataComposite(dtkComposerNode *parent) : dtkComposerNodeLoop(parent), d(new dtkComposerNodeLoopDataCompositePrivate)\n{\n d->block_loop = this->addBlock(\"loop\");\n d->block_loop->setInteractive(false);\n d->block_loop->setHeightRatio(1);\n this->addInputProperty(d->block_loop->addInputProperty(\"from\", dtkComposerNodeProperty::Input, dtkComposerNodeProperty::Single, dtkComposerNodeProperty::None, this));\n this->addInputProperty(d->block_loop->addInputProperty(\"to\", dtkComposerNodeProperty::Input, dtkComposerNodeProperty::Single, dtkComposerNodeProperty::None, this));\n this->addInputProperty(d->block_loop->addInputProperty(\"step\", dtkComposerNodeProperty::Input, dtkComposerNodeProperty::Single, dtkComposerNodeProperty::None, this));\n this->addInputProperty(d->block_loop->addInputProperty(\"item\", dtkComposerNodeProperty::Output, dtkComposerNodeProperty::Multiple, dtkComposerNodeProperty::AsLoopInput, this));\n\n this->setColor(QColor(\"#2ABFFF\"));\n this->setInputPropertyName(\"composite\");\n this->setTitle(\"Composite Data Loop\");\n this->setType(\"dtkComposerLoopDataComposite\");\n\n d->from_default = 0;\n d->to_default = 0;\n d->step_default = 1;\n\n d->from = -1;\n d->to = -1;\n d->step = -1;\n\n d->index = 0;\n\n d->item = NULL;\n d->composite = NULL;\n\n d->valid_input_composite = false;\n}\n\ndtkComposerNodeLoopDataComposite::~dtkComposerNodeLoopDataComposite(void)\n{\n delete d;\n\n d = NULL;\n}\n\nvoid dtkComposerNodeLoopDataComposite::layout(void)\n{\n dtkComposerNodeControl::layout();\n\n QRectF node_rect = this->boundingRect();\n qreal node_radius = this->nodeRadius();\n\n int j;\n qreal offset = 23;\n\n dtkComposerNodeControlBlock *block = this->blocks().at(0);\n\n block->setRect(QRectF(node_rect.x(),\n node_rect.y() + offset,\n node_rect.width(),\n block->height()));\n\n j = 0;\n foreach(dtkComposerNodeProperty *property, block->inputProperties()) {\n\n property->setRect(QRectF(block->mapRectToParent(block->rect()).left() + node_radius,\n block->mapRectToParent(block->rect()).top() + node_radius * (4*j + 1),\n 2 * node_radius,\n 2 * node_radius ));\n\n if (property->name() == \"item\") {\n property->mirror();\n j++;\n }\n\n j++;\n }\n j = 5;\n foreach(dtkComposerNodeProperty *property, block->outputProperties()) {\n\n property->setRect(QRectF(block->mapRectToParent(block->rect()).right() - node_radius * 3,\n block->mapRectToParent(block->rect()).top() + node_radius * (4*j + 1),\n 2 * node_radius,\n 2 * node_radius ));\n \n j++;\n }\n}\n\nvoid dtkComposerNodeLoopDataComposite::update(void)\n{\n \n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_PRETTY_FUNCTION << this;\n#endif\n\n if (this->isRunning()) {\n\n return;\n \n } else {\n\n if (!this->dirty())\n return;\n\n \/\/ -- Check dirty input value\n\n if (this->dirtyInputValue())\n return;\n\n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_GREEN << DTK_PRETTY_FUNCTION << \"Dirty input value OK\" << DTK_NO_COLOR;\n#endif\n\n \/\/ -- Check dirty inputs\n\n if (this->dtkComposerNode::dirtyUpstreamNodes())\n return;\n\n \/\/ -- Mark dirty outputs\n\n this->dtkComposerNode::markDirtyDownstreamNodes();\n\n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_GREEN << DTK_PRETTY_FUNCTION << \"All output nodes are set to dirty\" << DTK_NO_COLOR;\n#endif\n\n \/\/ -- Clean active input routes\n\n this->cleanInputActiveRoutes();\n\n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << \"Input active routes cleaned\" << DTK_NO_COLOR;\n#endif\n\n \/\/ -- Pull\n\n foreach(dtkComposerEdge *i_route, this->inputRoutes())\n this->pull(i_route, i_route->destination()); \n\n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << \"Pull done\" << DTK_NO_COLOR;\n#endif\n\n \/\/ -- Set input composite and loop options\n\n foreach(dtkComposerEdge *i_route, this->inputActiveRoutes()) {\n if (i_route->destination() == this->inputProperty()) {\n \n dtkAbstractData *data = NULL;\n\n if(dtkAbstractData *dt = qobject_cast(i_route->source()->node()->object())) {\n \n data = dt; \n\n } else if(dtkAbstractProcess *process = qobject_cast(i_route->source()->node()->object())) {\n \n if(i_route->source()->node()->outputProperties().count() >= 1)\n data = process->output(i_route->source()->node()->number(i_route->source()));\n else\n data = process->output();\n\n }\n \n if (data) {\n\n d->composite = qobject_cast(data);\n if (!d->composite) {\n dtkDebug() << DTK_PRETTY_FUNCTION << \"input data is not of dtkAbstractDataComposite* type.\";\n return;\n }\n if (d->composite->count())\n this->setObject((*d->composite)[0]);\n\n d->to_default = d->composite->count()-1;\n \n d->valid_input_composite = true;\n\n } else {\n\n dtkDebug() << DTK_PRETTY_FUNCTION << \"input data is not defined\";\n return;\n\n }\n\n } else if (i_route->destination()->name() == \"from\") {\n\n d->from = (dtkxarch_int)(i_route->source()->node()->value(i_route->source()).toLongLong()); \n\n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << \"from value =\" << d->from << DTK_NO_COLOR;\n#endif\n\n } else if (i_route->destination()->name() == \"to\") {\n\n d->to = (dtkxarch_int)(i_route->source()->node()->value(i_route->source()).toLongLong()); \n\n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << \"to value =\" << d->to << DTK_NO_COLOR;\n#endif\n\n } else if (i_route->destination()->name() == \"step\") {\n\n d->step = (dtkxarch_int)(i_route->source()->node()->value(i_route->source()).toLongLong());\n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << \"step value =\" << d->step << DTK_NO_COLOR;\n#endif\n\n }\n\n qDebug() << i_route;\n\n }\n \n if (!d->valid_input_composite) {\n dtkDebug() << DTK_PRETTY_FUNCTION << \" input composite property is not connected.\";\n return; \n }\n\n if ((d->from > d->to) && (d->from > d->to_default))\n d->from = d->to_default;\n else if (d->from < 0)\n d->from = d->from_default;\n else if (d->to < d->from && d->to < 0)\n d->to = d->from_default;\n else if (d->to > d->to_default)\n d->to = d->to_default;\n\n if (d->step < 0 && (d->from < d->to))\n d->step = d->step_default;\n\n d->index = d->from;\n \n \/\/ -- Running logics of conditional block\n \n this->setRunning(true);\n\n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_RED << \"Loop initialization done\" << DTK_NO_COLOR;\n#endif\n\n while(d->index <= d->to) {\n\n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_RED << \"Loop is running, index = \" << d->index << DTK_NO_COLOR;\n#endif\n \n d->item = (*d->composite)[d->index]; \n this->run();\n this->updatePassThroughVariables();\n d->index += d->step;\n \n }\n \n \/\/ -- Clean active output routes\n\n this->cleanOutputActiveRoutes();\n\n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << \"Output active routes cleaned\" << DTK_NO_COLOR;\n#endif\n \n \/\/ -- Push\n \n foreach(dtkComposerEdge *o_route, this->outputRoutes())\n this->push(o_route, o_route->source());\n\n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << \"Push done\" << DTK_NO_COLOR;\n#endif\n\n \/\/ -- Forward\n \n this->setDirty(false);\n this->setRunning(false);\n \n#if defined(DTK_DEBUG_COMPOSER_EVALUATION)\n qDebug() << DTK_COLOR_BG_BLUE << DTK_PRETTY_FUNCTION << \"Forward done\" << DTK_NO_COLOR;\n#endif\n\n foreach(dtkComposerEdge *o_route, this->outputRoutes())\n o_route->destination()->node()->update();\n }\n}\n\nvoid dtkComposerNodeLoopDataComposite::onEdgeConnected(dtkComposerEdge *edge)\n{\n if(true)\n edge->invalidate();\n else\n ; \/\/ dtkComposerNodeLoop::onEdgeConnected(edge);\n\n dtkComposerNodeLoop::onEdgeConnected(edge); \/\/ TO BE REMOVED LATER ON\n}\n\nvoid dtkComposerNodeLoopDataComposite::pull(dtkComposerEdge *i_route, dtkComposerNodeProperty *property)\n{\n if (property->name() == \"from\" || property->name() == \"to\" || property->name() == \"step\")\n this->addInputActiveRoute(i_route);\n\n dtkComposerNodeLoop::pull(i_route, property);\n}\n \nQVariant dtkComposerNodeLoopDataComposite::value(dtkComposerNodeProperty *property)\n{\n return QVariant();\n}\n<|endoftext|>"} {"text":"\/*\n * fMBT, free Model Based Testing tool\n * Copyright (c) 2011, Intel Corporation.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms and conditions of the GNU Lesser General Public License,\n * version 2.1, as published by the Free Software Foundation.\n *\n * This program is distributed in the hope it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for\n * more details.\n *\n * You should have received a copy of the GNU Lesser General Public License along with\n * this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.\n *\n *\/\n\n#include \"coverage_shared.hh\"\n\nvoid Coverage_shared::receive_from_server()\n{\n \/\/ Read number of active clients\n std::vector tmp;\n\n char* s = NULL;\n size_t si = 0;\n std::vector clients;\n\n g_io_channel_flush(d_stdin,NULL);\n\n while(g_main_context_iteration(NULL,FALSE));\n\n if (getline(&s,&si,d_stdout)<0) {\n status=false;\n return;\n }\n\n if (strlen(s)>2) {\n s[strlen(s)-2]='\\0';\n s++;\n }\n\n if (!string2vector(log,s,clients,0,INT_MAX,this)) {\n status=false;\n return;\n }\n\n \/\/ Read each client...\n for(unsigned i=0;iset_instance(clients[i])) {\n status=false;\n continue;\n }\n \n std::string name,option;\n\n param_cut(std::string(s),name,option);\n std::vector p;\n commalist(option,p);\n\n for(unsigned j=0;status&&(j at;\n param_cut(p[j],name,option);\n commalist(option,at);\n if (at.size()!=2) {\n\tstatus=false;\n\tcontinue;\n }\n int act=atoi(at[0].c_str());\n std::vector tags;\n if (!string2vector(log,at[1].c_str(),tags,0,INT_MAX,this)) {\n\tstatus=false;\n } else {\n\t\/\/ We should pass tags...\n\tchild->execute(act);\n }\n }\n\n }\n \n}\n\nvoid Coverage_shared::communicate(int action)\n{\n if (!status) {\n return;\n }\n \/\/ First, send action\n fprintf(d_stdin,\"(%i,)\\n\",action);\n\n receive_from_server();\n}\n\nFACTORY_DEFAULT_CREATOR(Coverage, Coverage_shared, \"shared\")\ncall child->set_instance(0) at end of receive_from_server() at coverage_shared. If it's not done, current execution is appedned to end of the last received clients execution. That's bad.\/*\n * fMBT, free Model Based Testing tool\n * Copyright (c) 2011, Intel Corporation.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms and conditions of the GNU Lesser General Public License,\n * version 2.1, as published by the Free Software Foundation.\n *\n * This program is distributed in the hope it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for\n * more details.\n *\n * You should have received a copy of the GNU Lesser General Public License along with\n * this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.\n *\n *\/\n\n#include \"coverage_shared.hh\"\n\nvoid Coverage_shared::receive_from_server()\n{\n \/\/ Read number of active clients\n std::vector tmp;\n\n char* s = NULL;\n size_t si = 0;\n std::vector clients;\n\n g_io_channel_flush(d_stdin,NULL);\n\n while(g_main_context_iteration(NULL,FALSE));\n\n if (getline(&s,&si,d_stdout)<0) {\n status=false;\n return;\n }\n\n if (strlen(s)>2) {\n s[strlen(s)-2]='\\0';\n s++;\n }\n\n if (!string2vector(log,s,clients,0,INT_MAX,this)) {\n status=false;\n return;\n }\n\n \/\/ Read each client...\n for(unsigned i=0;iset_instance(clients[i])) {\n status=false;\n continue;\n }\n \n std::string name,option;\n\n param_cut(std::string(s),name,option);\n std::vector p;\n commalist(option,p);\n\n for(unsigned j=0;status&&(j at;\n param_cut(p[j],name,option);\n commalist(option,at);\n if (at.size()!=2) {\n\tstatus=false;\n\tcontinue;\n }\n int act=atoi(at[0].c_str());\n std::vector tags;\n if (!string2vector(log,at[1].c_str(),tags,0,INT_MAX,this)) {\n\tstatus=false;\n } else {\n\t\/\/ We should pass tags...\n\tchild->execute(act);\n }\n }\n\n }\n child->set_instance(0); \n}\n\nvoid Coverage_shared::communicate(int action)\n{\n if (!status) {\n return;\n }\n \/\/ First, send action\n fprintf(d_stdin,\"(%i,)\\n\",action);\n\n receive_from_server();\n}\n\nFACTORY_DEFAULT_CREATOR(Coverage, Coverage_shared, \"shared\")\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2016 Ansho Enigu\n#include \"crypto\/lamport.h\"\n\n#include \"crypto\/ripemd160.h\"\n#include \"crypto\/common.h\"\n#include \"uint256.h\"\nbool LAMPORT::checksig(unsigned char data[10000], char sig[20][2][20], char rootkey[20], char merklewit[])\n{\n\n char exmerklewit[8][20]; \/*this is the merkle wit minus the main public key max number of publickeys to rootkey is 256 due to 2^n where n is the first array index is 8*\/\n char pubkey[20][2][20];\n bool merklecheckfin = false;\n\n \/\/start converting merkle wit to exmerklewit and public key\n char merklebuffer[800]; \/\/size of publickey is the max size of the buffer\n unsigned int i;\n for(i = 0; i < sizeof(merklewit); i++)\n {\n if(merklewit[i] == 0x00 && merklewit[i+1] == 0x00) \/*test for partition beetween merkle segments*\/\n break;\n merklebuffer[i] = merklewit[i];\n }\n\n memcpy(&pubkey, &merklebuffer, sizeof(merklebuffer));\n int o = 0;\n int r = 0; \/\/number of times we have reset o count\n for(; i < sizeof(merklewit); i++)\n {\n if(merklewit[i] == 0x00 && merklewit[i+1] == 0x00)\n {\n memcpy(&exmerklewit[r], &merklebuffer, sizeof(merklebuffer));\n r++;\n i++; \/\/get i+1 index chunk so we can jump to next part of the merklewit at the end of cycle\n o = 0;\n }\n else\n {\n merklebuffer[o] = merklewit[i];\n o++;\n }\n }\n \/\/end decoding merkle wit format\n\n \/\/start checking if new publickey is a part of the root key\n for(int i = 0; !merklecheckfin; i++) \/\/to end if false we will use return to lower processing time\n {\n return false;\n }\n \/\/end checking if new publickey is a part of the root key\n\n \/*\n unsigned char* datapart;\n unsigned char[(160\/LAMPORT::chuncksize)]* datahashs;\n for(int i = 0; i < (160\/LAMPORT::chuncksize); i++)\n {\n\n for(int o = 0; o < chuncksizeinbyte; o++)\n {\n datapart[o] = data[(i * LAMPORT::chuncksize) + o];\n }\n\n CRIPEMD160().Write(begin_ptr(datapart), datapart.size()).Finalize(begin_ptr(datahashs[i]));\n }\n *\/\n return true; \/\/ if compleats all tests return true\n}\n char *** LAMPORT::createsig(unsigned char data[10000], uint512_t prikey, int sellectedpubkey)\n {\n \/* hash of the message *\/\n bool messhashb[160];\n unsigned char messhash[20];\n CRIPEMD160().Write(&data, 10000).Finalize(&messhash);\n\n \/* creating true key from seed (the seed is used as the key by the user but it only is a form of compress key) *\/\n unsigned char[20] vchHash\n unsigned char[64] prikeychar;\n\n memcpy(&prikeychar, &prikey, 64);\n\n CRIPEMD160().Write(&prikeychar, 64).Finalize(&vchHash);\n char temphash[20];\n\n char ichar;\n for(int i =0; i < 320; i++)\n {\n memcpy(&ichar, &i, 1);\n CRIPEMD160().Write(&vchHash, sizeof(vchHash)).Write(&ichar, sizeof(ichar)).Finalize(&temphash);\n prikeys[i] = temphash;\n }\n\n \/* the signing will happen under this *\/\n char sig[20][2][20];\n\n\n return &sig;\n }\nUpdate lamport.cpp\/\/ Copyright (c) 2016 Ansho Enigu\n#include \"crypto\/lamport.h\"\n\n#include \"crypto\/ripemd160.h\"\n#include \"crypto\/common.h\"\n#include \"uint256.h\"\nbool LAMPORT::checksig(unsigned char data[10000], char sig[20][2][20], char rootkey[20], char merklewit[])\n{\n\n char exmerklewit[8][20]; \/*this is the merkle wit minus the main public key max number of publickeys to rootkey is 256 due to 2^n where n is the first array index is 8*\/\n char pubkey[20][2][20];\n bool merklecheckfin = false;\n\n \/\/start converting merkle wit to exmerklewit and public key\n char merklebuffer[800]; \/\/size of publickey is the max size of the buffer\n unsigned int i;\n for(i = 0; i < sizeof(merklewit); i++)\n {\n if(merklewit[i] == 0x00 && merklewit[i+1] == 0x00) \/*test for partition beetween merkle segments*\/\n break;\n merklebuffer[i] = merklewit[i];\n }\n\n memcpy(&pubkey, &merklebuffer, sizeof(merklebuffer));\n int o = 0;\n int r = 0; \/\/number of times we have reset o count\n for(; i < sizeof(merklewit); i++)\n {\n if(merklewit[i] == 0x00 && merklewit[i+1] == 0x00)\n {\n memcpy(&exmerklewit[r], &merklebuffer, sizeof(merklebuffer));\n r++;\n i++; \/\/get i+1 index chunk so we can jump to next part of the merklewit at the end of cycle\n o = 0;\n }\n else\n {\n merklebuffer[o] = merklewit[i];\n o++;\n }\n }\n \/\/end decoding merkle wit format\n\n \/\/start checking if new publickey is a part of the root key\n for(int i = 0; !merklecheckfin; i++) \/\/to end if false we will use return to lower processing time\n {\n return false;\n }\n \/\/end checking if new publickey is a part of the root key\n\n \/*\n unsigned char* datapart;\n unsigned char[(160\/LAMPORT::chuncksize)]* datahashs;\n for(int i = 0; i < (160\/LAMPORT::chuncksize); i++)\n {\n\n for(int o = 0; o < chuncksizeinbyte; o++)\n {\n datapart[o] = data[(i * LAMPORT::chuncksize) + o];\n }\n\n CRIPEMD160().Write(begin_ptr(datapart), datapart.size()).Finalize(begin_ptr(datahashs[i]));\n }\n *\/\n return true; \/\/ if compleats all tests return true\n}\n char *** LAMPORT::createsig(unsigned char data[10000], uint512_t prikey, int sellectedpubkey)\n {\n \/* hash of the message *\/\n bool messhashb[160];\n unsigned char messhash[20];\n CRIPEMD160().Write(&data, 10000).Finalize(&messhash);\n\n \/* creating true key from seed (the seed is used as the key by the user but it only is a form of compress key) *\/\n unsigned char vchHash[20];\n unsigned char prikeychar[64];\n\n memcpy(&prikeychar, &prikey, 64);\n\n CRIPEMD160().Write(&prikeychar, 64).Finalize(&vchHash);\n char temphash[20];\n\n char ichar;\n for(int i =0; i < 320; i++)\n {\n memcpy(&ichar, &i, 1);\n CRIPEMD160().Write(&vchHash, sizeof(vchHash)).Write(&ichar, sizeof(ichar)).Finalize(&temphash);\n memcpy(&prikeys[i], &temphash, sizeof(temphash));\n }\n\n \/* the signing will happen under this *\/\n char sig[20][2][20];\n\n\n return &sig;\n }\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nusing namespace can;\nusing namespace jaguar;\n\nstatic ros::Subscriber sub_twist;\nstatic ros::Publisher pub_odom;\nstatic ros::Publisher pub_vleft, pub_vright;\n\nstatic DiffDriveSettings settings;\nstatic boost::shared_ptr robot;\nstatic boost::shared_ptr pub_tf;\nstatic std::string frame_parent;\nstatic std::string frame_child;\n\nvoid callback_odom(double x, double y, double theta,\n double vx, double vy, double omega)\n{\n ros::Time now = ros::Time::now();\n\n \/\/ odom TF Frame\n geometry_msgs::TransformStamped msg_tf;\n msg_tf.header.stamp = now;\n msg_tf.header.frame_id = frame_parent;\n msg_tf.child_frame_id = frame_child;\n msg_tf.transform.translation.x = x;\n msg_tf.transform.translation.y = y;\n msg_tf.transform.rotation = tf::createQuaternionMsgFromYaw(theta);\n pub_tf->sendTransform(msg_tf);\n\n \/\/ Odometry Message\n nav_msgs::Odometry msg_odom;\n msg_odom.header.stamp = now;\n msg_odom.header.frame_id = frame_parent;\n msg_odom.child_frame_id = frame_child;\n msg_odom.pose.pose.position.x = x;\n msg_odom.pose.pose.position.y = y;\n msg_odom.pose.pose.orientation = tf::createQuaternionMsgFromYaw(theta);\n msg_odom.twist.twist.linear.x = vx;\n msg_odom.twist.twist.linear.y = vy;\n msg_odom.twist.twist.angular.z = omega;\n pub_odom.publish(msg_odom);\n}\n\nvoid callback_speed(DiffDriveRobot::Side side, double speed)\n{\n std_msgs::Float64 msg;\n msg.data = speed;\n\n switch (side) {\n case DiffDriveRobot::kLeft:\n pub_vleft.publish(msg);\n break;\n\n case DiffDriveRobot::kRight:\n pub_vright.publish(msg);\n break;\n\n default:\n ROS_WARN_THROTTLE(10, \"Invalid speed callback.\");\n }\n}\n\nvoid callback_cmd(geometry_msgs::Twist const &twist)\n{\n if (twist.linear.y != 0.0 || twist.linear.z != 0\n || twist.angular.x != 0.0 || twist.angular.y != 0) {\n ROS_WARN_THROTTLE(10.0, \"Ignoring non-zero component of velocity command.\");\n }\n robot->drive(twist.linear.x, twist.angular.z);\n}\n\nvoid callback_reconfigure(jaguar::JaguarConfig &config, uint32_t level)\n{\n \/\/ Speed Control Gains\n if (level & 1) {\n robot->speed_set_p(config.gain_p);\n ROS_INFO(\"Reconfigure, P = %f\", config.gain_p);\n }\n if (level & 2) {\n robot->speed_set_i(config.gain_i);\n ROS_INFO(\"Reconfigure, I = %f\", config.gain_i);\n }\n if (level & 4) {\n robot->speed_set_d(config.gain_d);\n ROS_INFO(\"Reconfigure, D = %f\", config.gain_d);\n }\n if (level & 8) {\n robot->drive_brake(config.brake);\n ROS_INFO(\"Reconfigure, Braking = %d\", config.brake);\n }\n if (level & 16) {\n if (0 < config.ticks_per_rev && config.ticks_per_rev <= std::numeric_limits::max()) {\n robot->robot_set_encoders(config.ticks_per_rev);\n ROS_INFO(\"Reconfigure, Ticks\/Rev = %d\", config.ticks_per_rev);\n } else {\n ROS_WARN(\"Ticks\/rev must be a positive 16-bit unsigned integer.\");\n }\n }\n if (level & 32) {\n if (config.wheel_radius <= 0) {\n ROS_WARN(\"Wheel radius must be positive.\");\n } else if (config.robot_radius <= 0) {\n ROS_WARN(\"Robot radius must be positive.\");\n } else {\n robot->robot_set_radii(config.wheel_radius, config.robot_radius);\n ROS_INFO(\"Reconfigure, Wheel Radius = %f m and Robot Radius = %f m\",\n config.wheel_radius, config.robot_radius\n );\n }\n }\n if (level & 64) {\n robot->drive_raw(config.setpoint, config.setpoint);\n ROS_INFO(\"Reconfigure, Setpoint = %f\", config.setpoint);\n }\n}\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"diff_drive_node\");\n ros::NodeHandle nh;\n\n int ticks_per_rev;\n ros::param::get(\"~port\", settings.port);\n ros::param::get(\"~id_left\", settings.id_left);\n ros::param::get(\"~id_right\", settings.id_right);\n ros::param::get(\"~heartbeat\", settings.heartbeat_ms);\n ros::param::get(\"~status\", settings.status_ms);\n ros::param::get(\"~frame_parent\", frame_parent);\n ros::param::get(\"~frame_child\", frame_child);\n ros::param::get(\"~accel_max\", settings.accel_max_mps2);\n settings.ticks_per_rev = static_cast(ticks_per_rev);\n\n ROS_INFO(\"Port: %s\", settings.port.c_str());\n ROS_INFO(\"ID Left: %d\", settings.id_left);\n ROS_INFO(\"ID Right: %d\", settings.id_right);\n ROS_INFO(\"Heartbeat Rate: %d ms\", settings.heartbeat_ms);\n ROS_INFO(\"Status Rate: %d ms\", settings.status_ms);\n\n \/\/ TODO: Read this from a parameter.\n settings.brake = BrakeCoastSetting::kOverrideCoast;\n\n if (!(1 <= settings.id_left && settings.id_left <= 63)\n || !(1 <= settings.id_right && settings.id_right <= 63)) {\n ROS_FATAL(\"Invalid CAN device id. Must be in the range 1-63.\");\n return 1;\n } else if (settings.heartbeat_ms <= 0 || settings.heartbeat_ms > 100) {\n ROS_FATAL(\"Heartbeat period invalid. Must be in the range 1-500 ms.\");\n return 1;\n } else if (settings.status_ms <= 0 || settings.status_ms > std::numeric_limits::max()) {\n ROS_FATAL(\"Status period invalid must be in the range 1-255 ms.\");\n return 1;\n } else if (ticks_per_rev <= 0) {\n ROS_FATAL(\"Number of ticks per revolution must be positive\");\n return 1;\n } else if (settings.wheel_radius_m <= 0) {\n ROS_FATAL(\"Wheel radius must be positive.\");\n return 1;\n } else if (settings.robot_radius_m <= 0) {\n ROS_FATAL(\"Robot radius must be positive.\");\n return 1;\n }\n\n \/\/ This must be done first because the asynchronous encoder callbacks use\n \/\/ the transform broadcaster.\n sub_twist = nh.subscribe(\"cmd_vel\", 1, &callback_cmd);\n pub_odom = nh.advertise(\"odom\", 100);\n pub_vleft = nh.advertise(\"encoder_left\", 100);\n pub_vright = nh.advertise(\"encoder_right\", 100);\n pub_tf = boost::make_shared();\n\n dynamic_reconfigure::Server server;\n dynamic_reconfigure::Server::CallbackType f;\n f = boost::bind(&callback_reconfigure, _1, _2);\n server.setCallback(f);\n\n robot = boost::make_shared(settings);\n robot->odom_attach(&callback_odom);\n robot->speed_attach(&callback_speed);\n\n \/\/ TODO: Read this heartbeat rate from a parameter.\n ros::Rate heartbeat_rate(50);\n while (ros::ok()) {\n robot->drive_spin(1 \/ 50.);\n robot->heartbeat();\n ros::spinOnce();\n heartbeat_rate.sleep();\n }\n return 0;\n}\nremoved unused variable#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nusing namespace can;\nusing namespace jaguar;\n\nstatic ros::Subscriber sub_twist;\nstatic ros::Publisher pub_odom;\nstatic ros::Publisher pub_vleft, pub_vright;\n\nstatic DiffDriveSettings settings;\nstatic boost::shared_ptr robot;\nstatic boost::shared_ptr pub_tf;\nstatic std::string frame_parent;\nstatic std::string frame_child;\n\nvoid callback_odom(double x, double y, double theta,\n double vx, double vy, double omega)\n{\n ros::Time now = ros::Time::now();\n\n \/\/ odom TF Frame\n geometry_msgs::TransformStamped msg_tf;\n msg_tf.header.stamp = now;\n msg_tf.header.frame_id = frame_parent;\n msg_tf.child_frame_id = frame_child;\n msg_tf.transform.translation.x = x;\n msg_tf.transform.translation.y = y;\n msg_tf.transform.rotation = tf::createQuaternionMsgFromYaw(theta);\n pub_tf->sendTransform(msg_tf);\n\n \/\/ Odometry Message\n nav_msgs::Odometry msg_odom;\n msg_odom.header.stamp = now;\n msg_odom.header.frame_id = frame_parent;\n msg_odom.child_frame_id = frame_child;\n msg_odom.pose.pose.position.x = x;\n msg_odom.pose.pose.position.y = y;\n msg_odom.pose.pose.orientation = tf::createQuaternionMsgFromYaw(theta);\n msg_odom.twist.twist.linear.x = vx;\n msg_odom.twist.twist.linear.y = vy;\n msg_odom.twist.twist.angular.z = omega;\n pub_odom.publish(msg_odom);\n}\n\nvoid callback_speed(DiffDriveRobot::Side side, double speed)\n{\n std_msgs::Float64 msg;\n msg.data = speed;\n\n switch (side) {\n case DiffDriveRobot::kLeft:\n pub_vleft.publish(msg);\n break;\n\n case DiffDriveRobot::kRight:\n pub_vright.publish(msg);\n break;\n\n default:\n ROS_WARN_THROTTLE(10, \"Invalid speed callback.\");\n }\n}\n\nvoid callback_cmd(geometry_msgs::Twist const &twist)\n{\n if (twist.linear.y != 0.0 || twist.linear.z != 0\n || twist.angular.x != 0.0 || twist.angular.y != 0) {\n ROS_WARN_THROTTLE(10.0, \"Ignoring non-zero component of velocity command.\");\n }\n robot->drive(twist.linear.x, twist.angular.z);\n}\n\nvoid callback_reconfigure(jaguar::JaguarConfig &config, uint32_t level)\n{\n \/\/ Speed Control Gains\n if (level & 1) {\n robot->speed_set_p(config.gain_p);\n ROS_INFO(\"Reconfigure, P = %f\", config.gain_p);\n }\n if (level & 2) {\n robot->speed_set_i(config.gain_i);\n ROS_INFO(\"Reconfigure, I = %f\", config.gain_i);\n }\n if (level & 4) {\n robot->speed_set_d(config.gain_d);\n ROS_INFO(\"Reconfigure, D = %f\", config.gain_d);\n }\n if (level & 8) {\n robot->drive_brake(config.brake);\n ROS_INFO(\"Reconfigure, Braking = %d\", config.brake);\n }\n if (level & 16) {\n if (0 < config.ticks_per_rev && config.ticks_per_rev <= std::numeric_limits::max()) {\n robot->robot_set_encoders(config.ticks_per_rev);\n ROS_INFO(\"Reconfigure, Ticks\/Rev = %d\", config.ticks_per_rev);\n } else {\n ROS_WARN(\"Ticks\/rev must be a positive 16-bit unsigned integer.\");\n }\n }\n if (level & 32) {\n if (config.wheel_radius <= 0) {\n ROS_WARN(\"Wheel radius must be positive.\");\n } else if (config.robot_radius <= 0) {\n ROS_WARN(\"Robot radius must be positive.\");\n } else {\n robot->robot_set_radii(config.wheel_radius, config.robot_radius);\n ROS_INFO(\"Reconfigure, Wheel Radius = %f m and Robot Radius = %f m\",\n config.wheel_radius, config.robot_radius\n );\n }\n }\n if (level & 64) {\n robot->drive_raw(config.setpoint, config.setpoint);\n ROS_INFO(\"Reconfigure, Setpoint = %f\", config.setpoint);\n }\n}\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"diff_drive_node\");\n ros::NodeHandle nh;\n\n ros::param::get(\"~port\", settings.port);\n ros::param::get(\"~id_left\", settings.id_left);\n ros::param::get(\"~id_right\", settings.id_right);\n ros::param::get(\"~heartbeat\", settings.heartbeat_ms);\n ros::param::get(\"~status\", settings.status_ms);\n ros::param::get(\"~frame_parent\", frame_parent);\n ros::param::get(\"~frame_child\", frame_child);\n ros::param::get(\"~accel_max\", settings.accel_max_mps2);\n\n ROS_INFO(\"Port: %s\", settings.port.c_str());\n ROS_INFO(\"ID Left: %d\", settings.id_left);\n ROS_INFO(\"ID Right: %d\", settings.id_right);\n ROS_INFO(\"Heartbeat Rate: %d ms\", settings.heartbeat_ms);\n ROS_INFO(\"Status Rate: %d ms\", settings.status_ms);\n\n \/\/ TODO: Read this from a parameter.\n settings.brake = BrakeCoastSetting::kOverrideCoast;\n\n if (!(1 <= settings.id_left && settings.id_left <= 63)\n || !(1 <= settings.id_right && settings.id_right <= 63)) {\n ROS_FATAL(\"Invalid CAN device id. Must be in the range 1-63.\");\n return 1;\n } else if (settings.heartbeat_ms <= 0 || settings.heartbeat_ms > 100) {\n ROS_FATAL(\"Heartbeat period invalid. Must be in the range 1-500 ms.\");\n return 1;\n } else if (settings.status_ms <= 0 || settings.status_ms > std::numeric_limits::max()) {\n ROS_FATAL(\"Status period invalid must be in the range 1-255 ms.\");\n return 1;\n } else if (ticks_per_rev <= 0) {\n ROS_FATAL(\"Number of ticks per revolution must be positive\");\n return 1;\n } else if (settings.wheel_radius_m <= 0) {\n ROS_FATAL(\"Wheel radius must be positive.\");\n return 1;\n } else if (settings.robot_radius_m <= 0) {\n ROS_FATAL(\"Robot radius must be positive.\");\n return 1;\n }\n\n \/\/ This must be done first because the asynchronous encoder callbacks use\n \/\/ the transform broadcaster.\n sub_twist = nh.subscribe(\"cmd_vel\", 1, &callback_cmd);\n pub_odom = nh.advertise(\"odom\", 100);\n pub_vleft = nh.advertise(\"encoder_left\", 100);\n pub_vright = nh.advertise(\"encoder_right\", 100);\n pub_tf = boost::make_shared();\n\n dynamic_reconfigure::Server server;\n dynamic_reconfigure::Server::CallbackType f;\n f = boost::bind(&callback_reconfigure, _1, _2);\n server.setCallback(f);\n\n robot = boost::make_shared(settings);\n robot->odom_attach(&callback_odom);\n robot->speed_attach(&callback_speed);\n\n \/\/ TODO: Read this heartbeat rate from a parameter.\n ros::Rate heartbeat_rate(50);\n while (ros::ok()) {\n robot->drive_spin(1 \/ 50.);\n robot->heartbeat();\n ros::spinOnce();\n heartbeat_rate.sleep();\n }\n return 0;\n}\n<|endoftext|>"} {"text":"#ifndef _SNARKFRONT_COMPILE_QAP_HPP_\n#define _SNARKFRONT_COMPILE_QAP_HPP_\n\n#include \n#include \n#include \n#include \n#include \n\n\/\/ snarklib\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace snarkfront {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ query ABCH\n\/\/\n\ntemplate \nclass QAP_query_ABCH\n{\n typedef typename PAIRING::Fr FR;\n typedef typename snarklib::QAP_QueryABC Q_ABC;\n typedef typename snarklib::QAP_QueryH Q_H;\n typedef typename snarklib::QAP_SystemPoint SYSPT;\n\npublic:\n QAP_query_ABCH(const std::size_t numBlocks,\n const std::string& sysfile,\n const std::string& randfile)\n : m_numBlocks(numBlocks),\n m_hugeSystem(sysfile)\n {\n std::ifstream ifs(randfile);\n m_error = !ifs ||\n !m_lagrangePoint.marshal_in(ifs) ||\n !m_hugeSystem.loadIndex();\n }\n\n \/\/ for g1_exp_count() and g2_exp_count() only\n QAP_query_ABCH(const std::string& sysfile)\n : m_numBlocks(0),\n m_hugeSystem(sysfile)\n {\n m_error = !m_hugeSystem.loadIndex();\n }\n\n bool operator! () const { return m_error; }\n\n void A(const std::string& outfile) {\n writeFilesABC(outfile, Q_ABC::VecSelect::A);\n }\n\n void B(const std::string& outfile) {\n writeFilesABC(outfile, Q_ABC::VecSelect::B);\n }\n\n void C(const std::string& outfile) {\n writeFilesABC(outfile, Q_ABC::VecSelect::C);\n }\n\n void H(const std::string& outfile) {\n writeFilesH(outfile);\n }\n\n std::size_t g1_exp_count(const std::string& afile,\n const std::string& bfile,\n const std::string& cfile,\n const std::string& hfile) {\n return snarklib::g1_exp_count(\n m_hugeSystem.maxIndex(), \/\/ same as QAP numVariables()\n m_hugeSystem.numCircuitInputs(), \/\/ same as QAP numCircuitInputs()\n nonzeroCount(afile),\n nonzeroCount(bfile),\n nonzeroCount(cfile),\n nonzeroCount(hfile));\n }\n\n std::size_t g2_exp_count(const std::string& bfile) {\n return snarklib::g2_exp_count(\n nonzeroCount(bfile));\n }\n\nprivate:\n template \n void writeFiles(const std::string& outfile,\n std::function func)\n {\n const SYSPT qap(m_hugeSystem,\n m_hugeSystem.numCircuitInputs(),\n m_lagrangePoint.point());\n\n const auto Q = func(qap);\n\n auto space = snarklib::BlockVector::space(Q.vec());\n space.blockPartition(std::array{m_numBlocks});\n space.param(Q.nonzeroCount());\n\n std::ofstream ofs(outfile);\n if (!ofs || !write_blockvector(outfile, space, Q.vec()))\n m_error = true;\n else\n space.marshal_out(ofs);\n }\n\n void writeFilesABC(const std::string& outfile,\n const unsigned int mask) {\n writeFiles(\n outfile,\n [&mask] (const SYSPT& qap) { return Q_ABC(qap, mask); });\n }\n\n void writeFilesH(const std::string& outfile) {\n writeFiles(\n outfile,\n [] (const SYSPT& qap) { return Q_H(qap); });\n }\n\n std::size_t nonzeroCount(const std::string& abchfile) {\n snarklib::IndexSpace<1> space;\n std::ifstream ifs(abchfile);\n return (!ifs || !space.marshal_in(ifs))\n ? m_error = false\n : space.param()[0];\n }\n\n const std::size_t m_numBlocks;\n\n snarklib::PPZK_LagrangePoint m_lagrangePoint;\n snarklib::HugeSystem m_hugeSystem;\n bool m_error;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ query K\n\/\/\n\ntemplate \nclass QAP_query_K\n{\n typedef typename PAIRING::Fr FR;\n typedef typename snarklib::QAP_SystemPoint SYSPT;\n\npublic:\n QAP_query_K(const std::string& afile,\n const std::string& bfile,\n const std::string& cfile,\n const std::string& sysfile,\n const std::string& randfile)\n : m_afile(afile),\n m_bfile(bfile),\n m_cfile(cfile),\n m_hugeSystem(sysfile)\n {\n std::ifstream ifs(randfile);\n m_error = !ifs ||\n !m_lagrangePoint.marshal_in(ifs) ||\n !m_clearGreeks.marshal_in(ifs) ||\n !m_hugeSystem.loadIndex();\n }\n\n bool operator! () const { return m_error; }\n\n void K(const std::string& outfile,\n const std::size_t blocknum) {\n writeFiles(outfile, blocknum);\n }\n\nprivate:\n void writeFiles(const std::string& outfile,\n const std::size_t blocknum)\n {\n const SYSPT qap(m_hugeSystem,\n m_hugeSystem.numCircuitInputs(),\n m_lagrangePoint.point());\n\n snarklib::QAP_QueryK Q(qap,\n m_clearGreeks.beta_rA(),\n m_clearGreeks.beta_rB(),\n m_clearGreeks.beta_rC());\n\n std::size_t block = (-1 == blocknum) ? 0 : blocknum;\n bool b = true;\n while (b) {\n snarklib::BlockVector A, B, C;\n\n if (!snarklib::read_blockvector(m_afile, block, A) ||\n !snarklib::read_blockvector(m_bfile, block, B) ||\n !snarklib::read_blockvector(m_cfile, block, C)) {\n m_error = true;\n return;\n }\n\n const auto& space = A.space();\n\n Q.accumVector(A, B, C);\n\n if (!snarklib::write_blockvector(outfile, block, space, Q.vec())) {\n m_error = true;\n return;\n }\n\n b = (-1 == blocknum)\n ? ++block < space.blockID()[0]\n : false;\n\n if (!b) {\n std::ofstream ofs(outfile);\n if (!ofs)\n m_error = true;\n else\n space.marshal_out(ofs);\n }\n }\n }\n\n const std::string m_afile, m_bfile, m_cfile;\n\n snarklib::PPZK_LagrangePoint m_lagrangePoint;\n snarklib::PPZK_BlindGreeks m_clearGreeks;\n snarklib::HugeSystem m_hugeSystem;\n bool m_error;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ query IC\n\/\/\n\ntemplate \nclass QAP_query_IC\n{\n typedef typename PAIRING::Fr FR;\n typedef typename PAIRING::G1 G1;\n typedef typename PAIRING::G2 G2;\n typedef typename snarklib::QAP_SystemPoint SYSPT;\n\npublic:\n QAP_query_IC(const std::string& afile, \/\/ side-effect: file is modified\n const std::string& sysfile,\n const std::string& randfile)\n : m_afile(afile),\n m_hugeSystem(sysfile)\n {\n std::ifstream ifs(randfile);\n m_error = !ifs ||\n !m_lagrangePoint.marshal_in(ifs) ||\n !m_hugeSystem.loadIndex();\n }\n\n bool operator! () const { return m_error; }\n\n void IC(const std::string& outfile) {\n writeFiles(outfile);\n }\n\nprivate:\n void writeFiles(const std::string& outfile) {\n const SYSPT qap(m_hugeSystem,\n m_hugeSystem.numCircuitInputs(),\n m_lagrangePoint.point());\n\n snarklib::QAP_QueryIC Q(qap);\n\n std::size_t block = 0;\n bool b = true;\n while (b) {\n snarklib::BlockVector A;\n\n if (!snarklib::read_blockvector(m_afile, block, A)) {\n m_error = true;\n return;\n }\n\n if (!Q.accumVector(A)) break;\n\n std::stringstream ss;\n ss << m_afile << block;\n\n std::ofstream ofs(ss.str());\n if (!ofs)\n m_error = true;\n else\n A.marshal_out(ofs); \/\/ side-effect: write back to file\n\n b = ++block < A.space().blockID()[0];\n }\n\n std::ofstream ofs(outfile);\n const auto space = snarklib::BlockVector::space(Q.vec());\n if (!ofs || !snarklib::write_blockvector(outfile, space, Q.vec()))\n m_error = true;\n else\n space.marshal_out(ofs);\n }\n\n const std::string m_afile;\n\n snarklib::PPZK_LagrangePoint m_lagrangePoint;\n snarklib::HugeSystem m_hugeSystem;\n bool m_error;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ witness ABCH\n\/\/\n\ntemplate \nclass QAP_witness_ABCH\n{\n typedef typename PAIRING::Fr FR;\n typedef typename snarklib::QAP_SystemPoint SYSPT;\n\npublic:\n QAP_witness_ABCH(const std::size_t numBlocks,\n const std::string& sysfile,\n const std::string& randfile,\n const std::string& witfile)\n : m_numBlocks(numBlocks),\n m_hugeSystem(sysfile)\n {\n std::ifstream ifsR(randfile), ifsW(witfile);\n m_error =\n !ifsR || !m_randomness.marshal_in(ifsR) ||\n !ifsW || !m_witness.marshal_in(ifsW) ||\n !m_hugeSystem.loadIndex();\n }\n\n bool operator! () const { return m_error; }\n\n void writeFiles(const std::string& outfile)\n {\n const SYSPT qap(m_hugeSystem,\n m_hugeSystem.numCircuitInputs());\n\n const snarklib::QAP_WitnessABCH\n ABCH(qap,\n m_witness,\n m_randomness.d1(),\n m_randomness.d2(),\n m_randomness.d3());\n\n auto space = snarklib::BlockVector::space(ABCH.vec());\n space.blockPartition(std::array{m_numBlocks});\n\n if (! write_blockvector(outfile, space, ABCH.vec()))\n m_error = true;\n }\n\nprivate:\n const std::size_t m_numBlocks;\n\n snarklib::R1Witness m_witness;\n snarklib::PPZK_ProofRandomness m_randomness;\n snarklib::HugeSystem m_hugeSystem;\n bool m_error;\n};\n\n} \/\/ namespace snarkfront\n\n#endif\nconstructor randomness arguments#ifndef _SNARKFRONT_COMPILE_QAP_HPP_\n#define _SNARKFRONT_COMPILE_QAP_HPP_\n\n#include \n#include \n#include \n#include \n#include \n\n\/\/ snarklib\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace snarkfront {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ query ABCH\n\/\/\n\ntemplate \nclass QAP_query_ABCH\n{\n typedef typename PAIRING::Fr FR;\n typedef typename snarklib::QAP_QueryABC Q_ABC;\n typedef typename snarklib::QAP_QueryH Q_H;\n typedef typename snarklib::QAP_SystemPoint SYSPT;\n\npublic:\n QAP_query_ABCH(const std::size_t numBlocks,\n const std::string& sysfile,\n const std::string& randfile)\n : m_numBlocks(numBlocks),\n m_hugeSystem(sysfile)\n {\n std::ifstream ifs(randfile);\n m_error = !ifs ||\n !m_lagrangePoint.marshal_in(ifs) ||\n !m_hugeSystem.loadIndex();\n }\n\n QAP_query_ABCH(const std::size_t numBlocks,\n const std::string& sysfile,\n const snarklib::PPZK_LagrangePoint& lagrangeRand)\n : m_numBlocks(numBlocks),\n m_hugeSystem(sysfile),\n m_lagrangePoint(lagrangeRand)\n {\n m_error = !m_hugeSystem.loadIndex();\n }\n\n \/\/ for g1_exp_count() and g2_exp_count() only\n QAP_query_ABCH(const std::string& sysfile)\n : m_numBlocks(0),\n m_hugeSystem(sysfile)\n {\n m_error = !m_hugeSystem.loadIndex();\n }\n\n bool operator! () const { return m_error; }\n\n void A(const std::string& outfile) {\n writeFilesABC(outfile, Q_ABC::VecSelect::A);\n }\n\n void B(const std::string& outfile) {\n writeFilesABC(outfile, Q_ABC::VecSelect::B);\n }\n\n void C(const std::string& outfile) {\n writeFilesABC(outfile, Q_ABC::VecSelect::C);\n }\n\n void H(const std::string& outfile) {\n writeFilesH(outfile);\n }\n\n std::size_t g1_exp_count(const std::string& afile,\n const std::string& bfile,\n const std::string& cfile,\n const std::string& hfile) {\n return snarklib::g1_exp_count(\n m_hugeSystem.maxIndex(), \/\/ same as QAP numVariables()\n m_hugeSystem.numCircuitInputs(), \/\/ same as QAP numCircuitInputs()\n nonzeroCount(afile),\n nonzeroCount(bfile),\n nonzeroCount(cfile),\n nonzeroCount(hfile));\n }\n\n std::size_t g2_exp_count(const std::string& bfile) {\n return snarklib::g2_exp_count(\n nonzeroCount(bfile));\n }\n\nprivate:\n template \n void writeFiles(const std::string& outfile,\n std::function func)\n {\n const SYSPT qap(m_hugeSystem,\n m_hugeSystem.numCircuitInputs(),\n m_lagrangePoint.point());\n\n const auto Q = func(qap);\n\n auto space = snarklib::BlockVector::space(Q.vec());\n space.blockPartition(std::array{m_numBlocks});\n space.param(Q.nonzeroCount());\n\n std::ofstream ofs(outfile);\n if (!ofs || !write_blockvector(outfile, space, Q.vec()))\n m_error = true;\n else\n space.marshal_out(ofs);\n }\n\n void writeFilesABC(const std::string& outfile,\n const unsigned int mask) {\n writeFiles(\n outfile,\n [&mask] (const SYSPT& qap) { return Q_ABC(qap, mask); });\n }\n\n void writeFilesH(const std::string& outfile) {\n writeFiles(\n outfile,\n [] (const SYSPT& qap) { return Q_H(qap); });\n }\n\n std::size_t nonzeroCount(const std::string& abchfile) {\n snarklib::IndexSpace<1> space;\n std::ifstream ifs(abchfile);\n return (!ifs || !space.marshal_in(ifs))\n ? m_error = false\n : space.param()[0];\n }\n\n const std::size_t m_numBlocks;\n\n snarklib::PPZK_LagrangePoint m_lagrangePoint;\n snarklib::HugeSystem m_hugeSystem;\n bool m_error;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ query K\n\/\/\n\ntemplate \nclass QAP_query_K\n{\n typedef typename PAIRING::Fr FR;\n typedef typename snarklib::QAP_SystemPoint SYSPT;\n\npublic:\n QAP_query_K(const std::string& afile,\n const std::string& bfile,\n const std::string& cfile,\n const std::string& sysfile,\n const std::string& randfile)\n : m_afile(afile),\n m_bfile(bfile),\n m_cfile(cfile),\n m_hugeSystem(sysfile)\n {\n std::ifstream ifs(randfile);\n m_error = !ifs ||\n !m_lagrangePoint.marshal_in(ifs) ||\n !m_clearGreeks.marshal_in(ifs) ||\n !m_hugeSystem.loadIndex();\n }\n\n QAP_query_K(const std::string& afile,\n const std::string& bfile,\n const std::string& cfile,\n const std::string& sysfile,\n const snarklib::PPZK_LagrangePoint& lagrangeRand,\n const snarklib::PPZK_BlindGreeks& greeksRand)\n : m_afile(afile),\n m_bfile(bfile),\n m_cfile(cfile),\n m_hugeSystem(sysfile),\n m_lagrangePoint(lagrangeRand),\n m_clearGreeks(greeksRand)\n {\n m_error = !m_hugeSystem.loadIndex();\n }\n\n bool operator! () const { return m_error; }\n\n void K(const std::string& outfile,\n const std::size_t blocknum) {\n writeFiles(outfile, blocknum);\n }\n\nprivate:\n void writeFiles(const std::string& outfile,\n const std::size_t blocknum)\n {\n const SYSPT qap(m_hugeSystem,\n m_hugeSystem.numCircuitInputs(),\n m_lagrangePoint.point());\n\n snarklib::QAP_QueryK Q(qap,\n m_clearGreeks.beta_rA(),\n m_clearGreeks.beta_rB(),\n m_clearGreeks.beta_rC());\n\n std::size_t block = (-1 == blocknum) ? 0 : blocknum;\n bool b = true;\n while (b) {\n snarklib::BlockVector A, B, C;\n\n if (!snarklib::read_blockvector(m_afile, block, A) ||\n !snarklib::read_blockvector(m_bfile, block, B) ||\n !snarklib::read_blockvector(m_cfile, block, C)) {\n m_error = true;\n return;\n }\n\n const auto& space = A.space();\n\n Q.accumVector(A, B, C);\n\n if (!snarklib::write_blockvector(outfile, block, space, Q.vec())) {\n m_error = true;\n return;\n }\n\n b = (-1 == blocknum)\n ? ++block < space.blockID()[0]\n : false;\n\n if (!b) {\n std::ofstream ofs(outfile);\n if (!ofs)\n m_error = true;\n else\n space.marshal_out(ofs);\n }\n }\n }\n\n const std::string m_afile, m_bfile, m_cfile;\n\n snarklib::PPZK_LagrangePoint m_lagrangePoint;\n snarklib::PPZK_BlindGreeks m_clearGreeks;\n snarklib::HugeSystem m_hugeSystem;\n bool m_error;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ query IC\n\/\/\n\ntemplate \nclass QAP_query_IC\n{\n typedef typename PAIRING::Fr FR;\n typedef typename PAIRING::G1 G1;\n typedef typename PAIRING::G2 G2;\n typedef typename snarklib::QAP_SystemPoint SYSPT;\n\npublic:\n QAP_query_IC(const std::string& afile, \/\/ side-effect: file is modified\n const std::string& sysfile,\n const std::string& randfile)\n : m_afile(afile),\n m_hugeSystem(sysfile)\n {\n std::ifstream ifs(randfile);\n m_error = !ifs ||\n !m_lagrangePoint.marshal_in(ifs) ||\n !m_hugeSystem.loadIndex();\n }\n\n QAP_query_IC(const std::string& afile, \/\/ side-effect: file is modified\n const std::string& sysfile,\n const snarklib::PPZK_LagrangePoint& lagrangeRand)\n : m_afile(afile),\n m_hugeSystem(sysfile),\n m_lagrangePoint(lagrangeRand)\n {\n m_error = !m_hugeSystem.loadIndex();\n }\n\n bool operator! () const { return m_error; }\n\n void IC(const std::string& outfile) {\n writeFiles(outfile);\n }\n\nprivate:\n void writeFiles(const std::string& outfile) {\n const SYSPT qap(m_hugeSystem,\n m_hugeSystem.numCircuitInputs(),\n m_lagrangePoint.point());\n\n snarklib::QAP_QueryIC Q(qap);\n\n std::size_t block = 0;\n bool b = true;\n while (b) {\n snarklib::BlockVector A;\n\n if (!snarklib::read_blockvector(m_afile, block, A)) {\n m_error = true;\n return;\n }\n\n if (!Q.accumVector(A)) break;\n\n std::stringstream ss;\n ss << m_afile << block;\n\n std::ofstream ofs(ss.str());\n if (!ofs)\n m_error = true;\n else\n A.marshal_out(ofs); \/\/ side-effect: write back to file\n\n b = ++block < A.space().blockID()[0];\n }\n\n std::ofstream ofs(outfile);\n const auto space = snarklib::BlockVector::space(Q.vec());\n if (!ofs || !snarklib::write_blockvector(outfile, space, Q.vec()))\n m_error = true;\n else\n space.marshal_out(ofs);\n }\n\n const std::string m_afile;\n\n snarklib::PPZK_LagrangePoint m_lagrangePoint;\n snarklib::HugeSystem m_hugeSystem;\n bool m_error;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ witness ABCH\n\/\/\n\ntemplate \nclass QAP_witness_ABCH\n{\n typedef typename PAIRING::Fr FR;\n typedef typename snarklib::QAP_SystemPoint SYSPT;\n\npublic:\n QAP_witness_ABCH(const std::size_t numBlocks,\n const std::string& sysfile,\n const std::string& randfile,\n const std::string& witfile)\n : m_numBlocks(numBlocks),\n m_hugeSystem(sysfile)\n {\n std::ifstream ifsR(randfile), ifsW(witfile);\n m_error =\n !ifsR || !m_randomness.marshal_in(ifsR) ||\n !ifsW || !m_witness.marshal_in(ifsW) ||\n !m_hugeSystem.loadIndex();\n }\n\n QAP_witness_ABCH(const std::size_t numBlocks,\n const std::string& sysfile,\n const snarklib::PPZK_ProofRandomness& proofRand,\n const std::string& witfile)\n : m_numBlocks(numBlocks),\n m_hugeSystem(sysfile),\n m_randomness(proofRand)\n {\n std::ifstream ifs(witfile);\n m_error =\n !ifs || !m_witness.marshal_in(ifs) ||\n !m_hugeSystem.loadIndex();\n }\n\n bool operator! () const { return m_error; }\n\n void writeFiles(const std::string& outfile)\n {\n const SYSPT qap(m_hugeSystem,\n m_hugeSystem.numCircuitInputs());\n\n const snarklib::QAP_WitnessABCH\n ABCH(qap,\n m_witness,\n m_randomness.d1(),\n m_randomness.d2(),\n m_randomness.d3());\n\n auto space = snarklib::BlockVector::space(ABCH.vec());\n space.blockPartition(std::array{m_numBlocks});\n\n if (! write_blockvector(outfile, space, ABCH.vec()))\n m_error = true;\n }\n\nprivate:\n const std::size_t m_numBlocks;\n\n snarklib::R1Witness m_witness;\n snarklib::PPZK_ProofRandomness m_randomness;\n snarklib::HugeSystem m_hugeSystem;\n bool m_error;\n};\n\n} \/\/ namespace snarkfront\n\n#endif\n<|endoftext|>"} {"text":"\/**\n * @file Connection.cpp\n * @brief\n * @author Travis Lane\n * @version 0.0.1\n * @date 2016-01-05\n *\/\n\n#include \"Connection.h\"\n\nConnection::Connection(Bluetooth &new_bt, int id) : bt(new_bt)\n{\n this->id = id;\n}\n\nint Connection::write(int percent)\n{\n int rc = 0;\n StaticJsonBuffer<200> buffer;\n JsonObject& object = buffer.createObject();\n\n if (!bt.connected()) {\n return -1;\n }\n\n object[\"id\"] = this->id;\n object[\"throttle\"] = percent;\n\n \/* Don't pretty print, I deliminate on \\n *\/\n rc = object.printTo(bt);\n bt.write('\\n');\n\n return rc;\n}\n\nint Connection::read(int *out_percent)\n{\n int rc = 0;\n char buff[200];\n StaticJsonBuffer<200> buffer;\n\n if (!bt.connected()) {\n return -1;\n }\n\n rc = bt.readBytesUntil('\\n', buff, sizeof(buff));\n if (rc <= 0) {\n return -1;\n }\n\n \/* Set last char to NULL *\/\n buff[rc] = '\\0';\n\n JsonObject& object = buffer.parseObject(buff);\n\n if (!object.success()) {\n return -1;\n }\n\n if (object[\"id\"] != id) {\n \/* The ID doesn't match... We should ignore this message *\/\n return -1;\n }\n\n *out_percent = object[\"throttle\"];\n return rc;\n}\nChange status codes for debugging\/**\n * @file Connection.cpp\n * @brief\n * @author Travis Lane\n * @version 0.0.1\n * @date 2016-01-05\n *\/\n\n#include \"Connection.h\"\n\nConnection::Connection(Bluetooth &new_bt, int id) : bt(new_bt)\n{\n this->id = id;\n}\n\nint Connection::write(int percent)\n{\n int rc = 0;\n StaticJsonBuffer<200> buffer;\n JsonObject& object = buffer.createObject();\n\n if (!bt.connected()) {\n return -1;\n }\n\n object[\"id\"] = this->id;\n object[\"throttle\"] = percent;\n\n \/* Don't pretty print, I deliminate on \\n *\/\n rc = object.printTo(bt);\n bt.write('\\n');\n\n return rc;\n}\n\nint Connection::read(int *out_percent)\n{\n int rc = 0;\n char buff[200];\n StaticJsonBuffer<200> buffer;\n\n if (!bt.connected()) {\n return -1;\n }\n\n rc = bt.readBytesUntil('\\n', buff, sizeof(buff));\n if (rc <= 0) {\n return -2;\n }\n\n \/* Set last char to NULL *\/\n buff[rc] = '\\0';\n\n JsonObject& object = buffer.parseObject(buff);\n\n if (!object.success()) {\n return -3;\n }\n\n if (object[\"id\"] != id) {\n \/* The ID doesn't match... We should ignore this message *\/\n return -4;\n }\n\n *out_percent = object[\"throttle\"];\n return rc;\n}\n<|endoftext|>"} {"text":"\/\/*****************************************************************************\n\/\/ Copyright 2017-2019 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/*****************************************************************************\n\n#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \"ngraph\/pass\/manager.hpp\"\n#include \"ngraph\/runtime\/executable.hpp\"\n\nnamespace ngraph\n{\n namespace runtime\n {\n class Backend;\n\n namespace hybrid\n {\n class HybridExecutable;\n }\n } \/\/ namespace runtime\n} \/\/ namespace ngraph\n\nclass ngraph::runtime::hybrid::HybridExecutable : public runtime::Executable\n{\npublic:\n HybridExecutable(const std::vector>& backend_list,\n const std::shared_ptr& func,\n bool enable_performance_collection = false,\n bool debug_enabled = false);\n\n bool call(const std::vector>& outputs,\n const std::vector>& inputs) override;\n\n template \n std::shared_ptr get_as() const\n {\n return std::dynamic_pointer_cast(m_executable);\n }\n\n \/\/\/ Allow overriding the configuration of the pass manager. If you overload this method\n \/\/\/ you must define all passes.\n virtual void configure_passes(ngraph::pass::Manager& pass_manager);\n\nprotected:\n std::shared_ptr m_function;\n std::shared_ptr m_executable;\n std::unordered_map, std::shared_ptr>\n m_map_parameter_to_result;\n\n std::vector> m_backend_list;\n bool m_debug_enabled = false;\n};\nAdd check to hybridexecutable::get_as. (#2998)\/\/*****************************************************************************\n\/\/ Copyright 2017-2019 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/*****************************************************************************\n\n#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \"ngraph\/pass\/manager.hpp\"\n#include \"ngraph\/runtime\/executable.hpp\"\n\nnamespace ngraph\n{\n namespace runtime\n {\n class Backend;\n\n namespace hybrid\n {\n class HybridExecutable;\n }\n } \/\/ namespace runtime\n} \/\/ namespace ngraph\n\nclass ngraph::runtime::hybrid::HybridExecutable : public runtime::Executable\n{\npublic:\n HybridExecutable(const std::vector>& backend_list,\n const std::shared_ptr& func,\n bool enable_performance_collection = false,\n bool debug_enabled = false);\n\n bool call(const std::vector>& outputs,\n const std::vector>& inputs) override;\n\n template \n std::shared_ptr get_as() const\n {\n if (auto exec = std::dynamic_pointer_cast(m_executable))\n {\n return exec;\n }\n else\n {\n throw ngraph::ngraph_error(\"Requested invalid ngraph::Executable subclass\");\n }\n }\n\n \/\/\/ Allow overriding the configuration of the pass manager. If you overload this method\n \/\/\/ you must define all passes.\n virtual void configure_passes(ngraph::pass::Manager& pass_manager);\n\nprotected:\n std::shared_ptr m_function;\n std::shared_ptr m_executable;\n std::unordered_map, std::shared_ptr>\n m_map_parameter_to_result;\n\n std::vector> m_backend_list;\n bool m_debug_enabled = false;\n};\n<|endoftext|>"} {"text":"\/*\n Copyright (c) 2018, 2019 Jouni Siren\n\n Author: Jouni Siren \n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*\/\n\n#include \n#include \n\n#include \n\nusing namespace gbwt;\n\n\/\/------------------------------------------------------------------------------\n\nconst std::string tool_name = \"GBWT sequence remove\";\n\nvoid printUsage(int exit_code = EXIT_SUCCESS);\n\n\/\/------------------------------------------------------------------------------\n\nint\nmain(int argc, char** argv)\n{\n if(argc < 3) { printUsage(); }\n\n int c = 0;\n std::string output;\n size_type chunk_size = DynamicGBWT::REMOVE_CHUNK_SIZE;\n bool range = false;\n while((c = getopt(argc, argv, \"c:o:r\")) != -1)\n {\n switch(c)\n {\n case 'c':\n chunk_size = std::max(1ul, std::stoul(optarg));\n break;\n case 'o':\n output = optarg; break;\n case 'r':\n range = true; break;\n case '?':\n std::exit(EXIT_FAILURE);\n default:\n std::exit(EXIT_FAILURE);\n }\n }\n\n if(optind + 1 >= argc) { printUsage(EXIT_FAILURE); }\n std::string base_name = argv[optind]; optind++;\n if(output.empty()) { output = base_name; }\n std::vector seq_ids;\n if(range)\n {\n if(argc != optind + 2) { printUsage(EXIT_FAILURE); }\n size_type start = std::stoul(argv[optind]); optind++;\n size_type stop = std::stoul(argv[optind]); optind++;\n if(stop < start) { printUsage(EXIT_FAILURE); }\n for(size_type seq_id = start; seq_id <= stop; seq_id++)\n {\n seq_ids.push_back(seq_id);\n }\n }\n else\n {\n while(optind < argc)\n {\n seq_ids.push_back(std::stoul(argv[optind]));\n optind++;\n }\n }\n\n Version::print(std::cout, tool_name);\n\n printHeader(\"Input\"); std::cout << base_name << std::endl;\n printHeader(\"Output\"); std::cout << output << std::endl;\n printHeader(\"Sequences\"); std::cout << seq_ids.size() << std::endl;\n printHeader(\"Chunk size\"); std::cout << chunk_size << std::endl;\n std::cout << std::endl;\n\n double start = readTimer();\n\n DynamicGBWT index;\n if(!sdsl::load_from_file(index, base_name + DynamicGBWT::EXTENSION))\n {\n std::cerr << \"remove_seq: Cannot load the index from \" << (base_name + DynamicGBWT::EXTENSION) << std::endl;\n std::exit(EXIT_FAILURE);\n }\n printStatistics(index, base_name);\n\n size_type total_length = index.remove(seq_ids, chunk_size);\n if(total_length > 0)\n {\n if(!sdsl::store_to_file(index, output + DynamicGBWT::EXTENSION))\n {\n std::cerr << \"remove_seq: Cannot write the index to \" << (output + DynamicGBWT::EXTENSION) << std::endl;\n std::exit(EXIT_FAILURE);\n }\n printStatistics(index, output);\n }\n\n double seconds = readTimer() - start;\n\n std::cout << \"Removed \" << total_length << \" nodes in \" << seconds << \" seconds (\"\n << (total_length \/ seconds) << \" nodes\/second)\" << std::endl;\n std::cout << \"Memory usage \" << inGigabytes(memoryUsage()) << \" GB\" << std::endl;\n std::cout << std::endl;\n\n return 0;\n}\n\n\/\/------------------------------------------------------------------------------\n\nvoid\nprintUsage(int exit_code)\n{\n Version::print(std::cerr, tool_name);\n\n std::cerr << \"Usage: remove_seq [options] base_name seq1 [seq2 ...]\" << std::endl;\n std::cerr << std::endl;\n std::cerr << \" -c N Build the RA in chunks of N sequences per thread (default: \" << DynamicGBWT::REMOVE_CHUNK_SIZE << \")\" << std::endl;\n std::cerr << \" -o X Use X as the base name for output\" << std::endl;\n std::cerr << \" -r Remove a range of sequences (inclusive; requires 2 sequence ids)\" << std::endl;\n std::cerr << std::endl;\n\n std::exit(exit_code);\n}\n\n\/\/------------------------------------------------------------------------------\nRemove sequences by sample\/contig in remove_seq\/*\n Copyright (c) 2018, 2019 Jouni Siren\n\n Author: Jouni Siren \n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*\/\n\n#include \n#include \n\n#include \n\nusing namespace gbwt;\n\n\/\/------------------------------------------------------------------------------\n\nconst std::string tool_name = \"GBWT sequence removal\";\n\nvoid printUsage(int exit_code = EXIT_SUCCESS);\n\n\/\/------------------------------------------------------------------------------\n\nint\nmain(int argc, char** argv)\n{\n if(argc < 3) { printUsage(); }\n\n \/\/ Parse command line options.\n int c = 0;\n std::string output;\n size_type chunk_size = DynamicGBWT::REMOVE_CHUNK_SIZE;\n bool range = false, sample = false, contig = false;\n while((c = getopt(argc, argv, \"c:o:rSC\")) != -1)\n {\n switch(c)\n {\n case 'c':\n chunk_size = std::max(1ul, std::stoul(optarg));\n break;\n case 'o':\n output = optarg; break;\n case 'r':\n range = true; break;\n case 'S':\n sample = true; break;\n case 'C':\n contig = true; break;\n case '?':\n std::exit(EXIT_FAILURE);\n default:\n std::exit(EXIT_FAILURE);\n }\n }\n\n \/\/ Check command line options.\n if(optind + 1 >= argc) { printUsage(EXIT_FAILURE); }\n if((range & sample) || (range & contig) || (sample & contig))\n {\n std::cerr << \"remove_seq: Options -r, -S, and -C are mutually exclusive\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n std::string base_name = argv[optind]; optind++;\n std::string key;\n if(output.empty()) { output = base_name; }\n std::vector seq_ids;\n if(range)\n {\n if(argc != optind + 2) { printUsage(EXIT_FAILURE); }\n size_type start = std::stoul(argv[optind]); optind++;\n size_type stop = std::stoul(argv[optind]); optind++;\n if(stop < start) { printUsage(EXIT_FAILURE); }\n for(size_type seq_id = start; seq_id <= stop; seq_id++)\n {\n seq_ids.push_back(seq_id);\n }\n }\n else if(sample || contig)\n {\n if(argc != optind + 1) { printUsage(EXIT_FAILURE); }\n key = argv[optind];\n }\n else\n {\n while(optind < argc)\n {\n seq_ids.push_back(std::stoul(argv[optind]));\n optind++;\n }\n }\n\n \/\/ Initial output.\n Version::print(std::cout, tool_name);\n printHeader(\"Input\"); std::cout << base_name << std::endl;\n printHeader(\"Output\"); std::cout << output << std::endl;\n if(range)\n {\n printHeader(\"Range\"); std::cout << range_type(seq_ids.front(), seq_ids.back()) << std::endl;\n }\n else if(sample)\n {\n printHeader(\"Sample\"); std::cout << key << std::endl;\n }\n else if(contig)\n {\n printHeader(\"Contig\"); std::cout << key << std::endl;\n }\n else\n {\n printHeader(\"Sequences\"); std::cout << seq_ids.size() << std::endl;\n }\n printHeader(\"Chunk size\"); std::cout << chunk_size << std::endl;\n std::cout << std::endl;\n\n double start = readTimer();\n\n \/\/ Load index.\n DynamicGBWT index;\n if(!sdsl::load_from_file(index, base_name + DynamicGBWT::EXTENSION))\n {\n std::cerr << \"remove_seq: Cannot load the index from \" << (base_name + DynamicGBWT::EXTENSION) << std::endl;\n std::exit(EXIT_FAILURE);\n }\n printStatistics(index, base_name);\n\n \/\/ Handle metadata.\n if(sample)\n {\n if(!(index.hasMetadata()) || !(index.metadata.hasSampleNames()) || !(index.metadata.hasPathNames()))\n {\n std::cerr << \"remove_seq: Option -S requires sample and path names\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n size_type sample_id = index.metadata.sample(key);\n seq_ids = index.metadata.removeSample(sample_id);\n if(seq_ids.empty())\n {\n std::cerr << \"remove_seq: No sequences for sample \" << key << std::endl;\n std::exit(EXIT_FAILURE);\n }\n }\n else if(contig)\n {\n if(!(index.hasMetadata()) || !(index.metadata.hasContigNames()) || !(index.metadata.hasPathNames()))\n {\n std::cerr << \"remove_seq: Option -C requires contig and path names\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n size_type contig_id = index.metadata.contig(key);\n seq_ids = index.metadata.removeContig(contig_id);\n if(seq_ids.empty())\n {\n std::cerr << \"remove_seq: No sequences for contig \" << key << std::endl;\n std::exit(EXIT_FAILURE);\n }\n }\n else\n {\n if(index.hasMetadata() && index.metadata.hasPathNames())\n {\n std::cerr << \"remove_seq: Removing arbitrary sequences would leave the metadata inconsistent\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n }\n\n \/\/ Remove the sequences.\n size_type total_length = index.remove(seq_ids, chunk_size);\n if(total_length > 0)\n {\n if(!sdsl::store_to_file(index, output + DynamicGBWT::EXTENSION))\n {\n std::cerr << \"remove_seq: Cannot write the index to \" << (output + DynamicGBWT::EXTENSION) << std::endl;\n std::exit(EXIT_FAILURE);\n }\n printStatistics(index, output);\n }\n\n double seconds = readTimer() - start;\n\n std::cout << \"Removed \" << total_length << \" nodes in \" << seconds << \" seconds (\"\n << (total_length \/ seconds) << \" nodes\/second)\" << std::endl;\n std::cout << \"Memory usage \" << inGigabytes(memoryUsage()) << \" GB\" << std::endl;\n std::cout << std::endl;\n\n return 0;\n}\n\n\/\/------------------------------------------------------------------------------\n\nvoid\nprintUsage(int exit_code)\n{\n Version::print(std::cerr, tool_name);\n\n std::cerr << \"Usage: remove_seq [options] base_name seq1 [seq2 ...]\" << std::endl;\n std::cerr << std::endl;\n std::cerr << \" -c N Build the RA in chunks of N sequences per thread (default: \" << DynamicGBWT::REMOVE_CHUNK_SIZE << \")\" << std::endl;\n std::cerr << \" -o X Use X as the base name for output\" << std::endl;\n std::cerr << \" -r Remove a range of sequences (inclusive; requires 2 sequence ids)\" << std::endl;\n std::cerr << \" -S Remove all sequences for the sample with name seq1 (cannot have seq2)\" << std::endl;\n std::cerr << \" -C Remove all sequences for the contig with name seq1 (cannot have seq2)\" << std::endl;\n std::cerr << std::endl;\n\n std::exit(exit_code);\n}\n\n\/\/------------------------------------------------------------------------------\n<|endoftext|>"} {"text":"#include \"ylikuutio_string.hpp\"\n\n\/\/ Include standard headers\n#include \/\/ std::FILE, std::fclose, std::fopen, std::fread, std::getchar, std::printf etc.\n#include \/\/ std::memcmp, std::strcmp, std::strlen, std::strncmp\n#include \/\/ std::cout, std::cin, std::cerr\n#include \/\/ std::list\n#include \/\/ std::stringstream\n#include \/\/ std::string\n#include \/\/ std::vector\n\nnamespace string\n{\n bool check_and_report_if_some_string_matches(const char* file_base_pointer, char* file_data_pointer, std::vector identifier_strings_vector)\n {\n for (std::string identifier_string : identifier_strings_vector)\n {\n const char* identifier_string_char = identifier_string.c_str();\n\n if (std::strncmp(file_data_pointer, identifier_string_char, std::strlen(identifier_string_char)) == 0)\n {\n const char* identifier_string_char = identifier_string.c_str();\n uint64_t offset = (uint64_t) file_data_pointer - (uint64_t) file_base_pointer;\n std::printf(\"%s found at file offset 0x%llu (memory address 0x%llu).\\n\", identifier_string_char, offset, (uint64_t) file_data_pointer);\n return true;\n }\n }\n return false;\n }\n\n void extract_string(char* dest_mem_pointer, char* &src_mem_pointer, char* char_end_string)\n {\n while (std::strncmp(src_mem_pointer, char_end_string, std::strlen(char_end_string)) != 0)\n {\n strncpy(dest_mem_pointer++, src_mem_pointer++, 1);\n }\n *dest_mem_pointer = '\\0';\n }\n\n void extract_string_with_several_endings(char* dest_mem_pointer, char*& src_mem_pointer, char* char_end_string)\n {\n \/\/ This function copies characters from `src_mem_pointer` until a character matches.\n\n while (true)\n {\n uint32_t n_of_ending_characters = std::strlen(char_end_string);\n char* end_char_pointer;\n end_char_pointer = char_end_string;\n\n \/\/ Check if current character is any of the ending characters.\n while (*end_char_pointer != '\\0')\n {\n if (std::strncmp(src_mem_pointer, end_char_pointer, 1) == 0)\n {\n *dest_mem_pointer = '\\0';\n return;\n }\n end_char_pointer++;\n }\n\n \/\/ OK, current character is not any of the ending characters.\n \/\/ Copy it and advance the pointers accordingly.\n strncpy(dest_mem_pointer++, src_mem_pointer++, 1);\n }\n }\n\n int32_t extract_int32_t_value_from_string(char*& data_pointer, char* char_end_string, const char* description)\n {\n char char_number_buffer[1024]; \/\/ FIXME: risk of buffer overflow.\n char* dest_mem_pointer;\n dest_mem_pointer = char_number_buffer;\n string::extract_string_with_several_endings(dest_mem_pointer, ++data_pointer, char_end_string);\n uint32_t value = std::atoi(dest_mem_pointer);\n std::printf(\"%s: %d\\n\", description, value);\n return value;\n }\n\n float extract_float_value_from_string(char*& data_pointer, char* char_end_string, const char* description)\n {\n char char_number_buffer[1024]; \/\/ FIXME: risk of buffer overflow.\n char* dest_mem_pointer;\n dest_mem_pointer = char_number_buffer;\n string::extract_string_with_several_endings(dest_mem_pointer, ++data_pointer, char_end_string);\n float value = std::atof(dest_mem_pointer);\n std::printf(\"%s: %f\\n\", description, value);\n return value;\n }\n\n int32_t extract_unicode_value_from_string(const char*& unicode_char_pointer)\n {\n if (*unicode_char_pointer == '\\0')\n {\n unicode_char_pointer++;\n std::cerr << \"Error: Unicode can not begin with \\\\0!\\n\";\n return 0xdfff; \/\/ invalid unicode!\n }\n\n if (*unicode_char_pointer != '&')\n {\n \/\/ it's just a character, so return its value,\n \/\/ and advance to the next character.\n return (int32_t) *unicode_char_pointer++;\n }\n\n if (*++unicode_char_pointer != '#')\n {\n \/\/ not valid format, must begin `\"&#x\"`.\n unicode_char_pointer++;\n std::cerr << \"Error: Unicode string format not supported!\\n\";\n return 0xdfff; \/\/ invalid unicode!\n }\n\n if (*++unicode_char_pointer != 'x')\n {\n \/\/ not valid format, must begin `\"&#x\"`.\n unicode_char_pointer++;\n std::cerr << \"Error: Unicode string format not supported!\\n\";\n return 0xdfff; \/\/ invalid unicode!\n }\n\n \/\/ valid format.\n std::string hex_string;\n\n \/\/ unicode string beginning with '&'\n while (*++unicode_char_pointer != ';')\n {\n if (*unicode_char_pointer == '\\0')\n {\n std::cerr << \"Error: Null character \\\\0 reached before end of Unicode string!\\n\";\n return 0xdfff; \/\/ invalid unicode!\n }\n\n char current_char = *unicode_char_pointer;\n hex_string.append(unicode_char_pointer);\n }\n\n \/\/ Advance to the next character.\n unicode_char_pointer++;\n\n \/\/ convert hexadecimal string to signed integer.\n \/\/ http:\/\/stackoverflow.com\/questions\/1070497\/c-convert-hex-string-to-signed-integer\/1070499#1070499\n uint32_t unicode_value;\n std::stringstream unicode_stringstream;\n unicode_stringstream << std::hex << hex_string;\n unicode_stringstream >> unicode_value;\n return unicode_value;\n }\n\n std::string convert_std_list_char_to_std_string(const std::list& std_list_char)\n {\n std::string my_string;\n\n for (std::list::const_iterator it = std_list_char.begin(); it != std_list_char.end(); it++)\n {\n my_string.push_back(*it);\n }\n\n return my_string;\n }\n\n std::string convert_std_list_char_to_std_string(const std::list& std_list_char, uint32_t first_line_length, uint32_t line_length)\n {\n std::string my_string;\n uint32_t remaining_characters_on_this_line = first_line_length;\n\n for (std::list::const_iterator it = std_list_char.begin(); it != std_list_char.end(); it++)\n {\n if (remaining_characters_on_this_line == 0)\n {\n my_string.push_back('\\\\');\n my_string.push_back('n');\n remaining_characters_on_this_line = line_length;\n }\n my_string.push_back(*it);\n remaining_characters_on_this_line--;\n }\n return my_string;\n }\n}\nIf `description` is `nullptr`, do not `printf` anything.#include \"ylikuutio_string.hpp\"\n\n\/\/ Include standard headers\n#include \/\/ std::FILE, std::fclose, std::fopen, std::fread, std::getchar, std::printf etc.\n#include \/\/ std::memcmp, std::strcmp, std::strlen, std::strncmp\n#include \/\/ std::cout, std::cin, std::cerr\n#include \/\/ std::list\n#include \/\/ std::stringstream\n#include \/\/ std::string\n#include \/\/ std::vector\n\nnamespace string\n{\n bool check_and_report_if_some_string_matches(const char* file_base_pointer, char* file_data_pointer, std::vector identifier_strings_vector)\n {\n for (std::string identifier_string : identifier_strings_vector)\n {\n const char* identifier_string_char = identifier_string.c_str();\n\n if (std::strncmp(file_data_pointer, identifier_string_char, std::strlen(identifier_string_char)) == 0)\n {\n const char* identifier_string_char = identifier_string.c_str();\n uint64_t offset = (uint64_t) file_data_pointer - (uint64_t) file_base_pointer;\n std::printf(\"%s found at file offset 0x%llu (memory address 0x%llu).\\n\", identifier_string_char, offset, (uint64_t) file_data_pointer);\n return true;\n }\n }\n return false;\n }\n\n void extract_string(char* dest_mem_pointer, char* &src_mem_pointer, char* char_end_string)\n {\n while (std::strncmp(src_mem_pointer, char_end_string, std::strlen(char_end_string)) != 0)\n {\n strncpy(dest_mem_pointer++, src_mem_pointer++, 1);\n }\n *dest_mem_pointer = '\\0';\n }\n\n void extract_string_with_several_endings(char* dest_mem_pointer, char*& src_mem_pointer, char* char_end_string)\n {\n \/\/ This function copies characters from `src_mem_pointer` until a character matches.\n\n while (true)\n {\n uint32_t n_of_ending_characters = std::strlen(char_end_string);\n char* end_char_pointer;\n end_char_pointer = char_end_string;\n\n \/\/ Check if current character is any of the ending characters.\n while (*end_char_pointer != '\\0')\n {\n if (std::strncmp(src_mem_pointer, end_char_pointer, 1) == 0)\n {\n *dest_mem_pointer = '\\0';\n return;\n }\n end_char_pointer++;\n }\n\n \/\/ OK, current character is not any of the ending characters.\n \/\/ Copy it and advance the pointers accordingly.\n strncpy(dest_mem_pointer++, src_mem_pointer++, 1);\n }\n }\n\n int32_t extract_int32_t_value_from_string(char*& data_pointer, char* char_end_string, const char* description)\n {\n char char_number_buffer[1024]; \/\/ FIXME: risk of buffer overflow.\n char* dest_mem_pointer;\n dest_mem_pointer = char_number_buffer;\n string::extract_string_with_several_endings(dest_mem_pointer, ++data_pointer, char_end_string);\n uint32_t value = std::atoi(dest_mem_pointer);\n if (description != nullptr)\n {\n std::printf(\"%s: %d\\n\", description, value);\n }\n return value;\n }\n\n float extract_float_value_from_string(char*& data_pointer, char* char_end_string, const char* description)\n {\n char char_number_buffer[1024]; \/\/ FIXME: risk of buffer overflow.\n char* dest_mem_pointer;\n dest_mem_pointer = char_number_buffer;\n string::extract_string_with_several_endings(dest_mem_pointer, ++data_pointer, char_end_string);\n float value = std::atof(dest_mem_pointer);\n\n if (description != nullptr)\n {\n std::printf(\"%s: %f\\n\", description, value);\n }\n return value;\n }\n\n int32_t extract_unicode_value_from_string(const char*& unicode_char_pointer)\n {\n if (*unicode_char_pointer == '\\0')\n {\n unicode_char_pointer++;\n std::cerr << \"Error: Unicode can not begin with \\\\0!\\n\";\n return 0xdfff; \/\/ invalid unicode!\n }\n\n if (*unicode_char_pointer != '&')\n {\n \/\/ it's just a character, so return its value,\n \/\/ and advance to the next character.\n return (int32_t) *unicode_char_pointer++;\n }\n\n if (*++unicode_char_pointer != '#')\n {\n \/\/ not valid format, must begin `\"&#x\"`.\n unicode_char_pointer++;\n std::cerr << \"Error: Unicode string format not supported!\\n\";\n return 0xdfff; \/\/ invalid unicode!\n }\n\n if (*++unicode_char_pointer != 'x')\n {\n \/\/ not valid format, must begin `\"&#x\"`.\n unicode_char_pointer++;\n std::cerr << \"Error: Unicode string format not supported!\\n\";\n return 0xdfff; \/\/ invalid unicode!\n }\n\n \/\/ valid format.\n std::string hex_string;\n\n \/\/ unicode string beginning with '&'\n while (*++unicode_char_pointer != ';')\n {\n if (*unicode_char_pointer == '\\0')\n {\n std::cerr << \"Error: Null character \\\\0 reached before end of Unicode string!\\n\";\n return 0xdfff; \/\/ invalid unicode!\n }\n\n char current_char = *unicode_char_pointer;\n hex_string.append(unicode_char_pointer);\n }\n\n \/\/ Advance to the next character.\n unicode_char_pointer++;\n\n \/\/ convert hexadecimal string to signed integer.\n \/\/ http:\/\/stackoverflow.com\/questions\/1070497\/c-convert-hex-string-to-signed-integer\/1070499#1070499\n uint32_t unicode_value;\n std::stringstream unicode_stringstream;\n unicode_stringstream << std::hex << hex_string;\n unicode_stringstream >> unicode_value;\n return unicode_value;\n }\n\n std::string convert_std_list_char_to_std_string(const std::list& std_list_char)\n {\n std::string my_string;\n\n for (std::list::const_iterator it = std_list_char.begin(); it != std_list_char.end(); it++)\n {\n my_string.push_back(*it);\n }\n\n return my_string;\n }\n\n std::string convert_std_list_char_to_std_string(const std::list& std_list_char, uint32_t first_line_length, uint32_t line_length)\n {\n std::string my_string;\n uint32_t remaining_characters_on_this_line = first_line_length;\n\n for (std::list::const_iterator it = std_list_char.begin(); it != std_list_char.end(); it++)\n {\n if (remaining_characters_on_this_line == 0)\n {\n my_string.push_back('\\\\');\n my_string.push_back('n');\n remaining_characters_on_this_line = line_length;\n }\n my_string.push_back(*it);\n remaining_characters_on_this_line--;\n }\n return my_string;\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"app\/gtk_dnd_util.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/pickle.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"googleurl\/src\/gurl.h\"\n\nstatic const int kBitsPerByte = 8;\n\nusing WebKit::WebDragOperationsMask;\nusing WebKit::WebDragOperation;\nusing WebKit::WebDragOperationNone;\nusing WebKit::WebDragOperationCopy;\nusing WebKit::WebDragOperationLink;\nusing WebKit::WebDragOperationMove;\n\nnamespace {\n\nvoid AddTargetToList(GtkTargetList* targets, int target_code) {\n switch (target_code) {\n case gtk_dnd_util::TEXT_PLAIN:\n gtk_target_list_add_text_targets(targets, gtk_dnd_util::TEXT_PLAIN);\n break;\n\n case gtk_dnd_util::TEXT_URI_LIST:\n gtk_target_list_add_uri_targets(targets, gtk_dnd_util::TEXT_URI_LIST);\n break;\n\n case gtk_dnd_util::TEXT_HTML:\n gtk_target_list_add(\n targets, gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_PLAIN),\n 0, gtk_dnd_util::TEXT_HTML);\n break;\n\n case gtk_dnd_util::NETSCAPE_URL:\n gtk_target_list_add(targets,\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::NETSCAPE_URL),\n 0, gtk_dnd_util::NETSCAPE_URL);\n break;\n\n case gtk_dnd_util::CHROME_TAB:\n case gtk_dnd_util::CHROME_BOOKMARK_ITEM:\n case gtk_dnd_util::CHROME_NAMED_URL:\n gtk_target_list_add(targets, gtk_dnd_util::GetAtomForTarget(target_code),\n GTK_TARGET_SAME_APP, target_code);\n break;\n\n case gtk_dnd_util::DIRECT_SAVE_FILE:\n gtk_target_list_add(targets,\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::DIRECT_SAVE_FILE),\n 0, gtk_dnd_util::DIRECT_SAVE_FILE);\n break;\n\n default:\n NOTREACHED() << \" Unexpected target code: \" << target_code;\n }\n}\n\n} \/\/ namespace\n\nnamespace gtk_dnd_util {\n\nGdkAtom GetAtomForTarget(int target) {\n switch (target) {\n case CHROME_TAB:\n static GdkAtom tab_atom = gdk_atom_intern(\n const_cast(\"application\/x-chrome-tab\"), false);\n return tab_atom;\n\n case TEXT_HTML:\n static GdkAtom html_atom = gdk_atom_intern(\n const_cast(\"text\/html\"), false);\n return html_atom;\n\n case CHROME_BOOKMARK_ITEM:\n static GdkAtom bookmark_atom = gdk_atom_intern(\n const_cast(\"application\/x-chrome-bookmark-item\"), false);\n return bookmark_atom;\n\n case TEXT_PLAIN:\n static GdkAtom text_atom = gdk_atom_intern(\n const_cast(\"text\/plain;charset=utf-8\"), false);\n return text_atom;\n\n case TEXT_URI_LIST:\n static GdkAtom uris_atom = gdk_atom_intern(\n const_cast(\"text\/uri-list\"), false);\n return uris_atom;\n\n case CHROME_NAMED_URL:\n static GdkAtom named_url = gdk_atom_intern(\n const_cast(\"application\/x-chrome-named-url\"), false);\n return named_url;\n\n case NETSCAPE_URL:\n static GdkAtom netscape_url = gdk_atom_intern(\n const_cast(\"_NETSCAPE_URL\"), false);\n return netscape_url;\n\n case TEXT_PLAIN_NO_CHARSET:\n static GdkAtom text_no_charset_atom = gdk_atom_intern(\n const_cast(\"text\/plain\"), false);\n return text_no_charset_atom;\n\n case DIRECT_SAVE_FILE:\n static GdkAtom xds_atom = gdk_atom_intern(\n const_cast(\"XdndDirectSave0\"), false);\n return xds_atom;\n\n default:\n NOTREACHED();\n }\n\n return NULL;\n}\n\nGtkTargetList* GetTargetListFromCodeMask(int code_mask) {\n GtkTargetList* targets = gtk_target_list_new(NULL, 0);\n\n for (size_t i = 1; i < INVALID_TARGET; i = i << 1) {\n if (i == CHROME_WEBDROP_FILE_CONTENTS)\n continue;\n\n if (i & code_mask)\n AddTargetToList(targets, i);\n }\n\n return targets;\n}\n\nvoid SetSourceTargetListFromCodeMask(GtkWidget* source, int code_mask) {\n GtkTargetList* targets = GetTargetListFromCodeMask(code_mask);\n gtk_drag_source_set_target_list(source, targets);\n gtk_target_list_unref(targets);\n}\n\nvoid SetDestTargetList(GtkWidget* dest, const int* target_codes) {\n GtkTargetList* targets = gtk_target_list_new(NULL, 0);\n\n for (size_t i = 0; target_codes[i] != -1; ++i) {\n AddTargetToList(targets, target_codes[i]);\n }\n\n gtk_drag_dest_set_target_list(dest, targets);\n gtk_target_list_unref(targets);\n}\n\nvoid WriteURLWithName(GtkSelectionData* selection_data,\n const GURL& url,\n const string16& title,\n int type) {\n switch (type) {\n case TEXT_PLAIN: {\n gtk_selection_data_set_text(selection_data, url.spec().c_str(),\n url.spec().length());\n break;\n }\n case TEXT_URI_LIST: {\n gchar* uri_array[2];\n uri_array[0] = strdup(url.spec().c_str());\n uri_array[1] = NULL;\n gtk_selection_data_set_uris(selection_data, uri_array);\n free(uri_array[0]);\n break;\n }\n case CHROME_NAMED_URL: {\n Pickle pickle;\n pickle.WriteString(UTF16ToUTF8(title));\n pickle.WriteString(url.spec());\n gtk_selection_data_set(\n selection_data,\n GetAtomForTarget(gtk_dnd_util::CHROME_NAMED_URL),\n kBitsPerByte,\n reinterpret_cast(pickle.data()),\n pickle.size());\n break;\n }\n case NETSCAPE_URL: {\n \/\/ _NETSCAPE_URL format is URL + \\n + title.\n std::string utf8_text = url.spec() + \"\\n\" + UTF16ToUTF8(title);\n gtk_selection_data_set(selection_data,\n selection_data->target,\n kBitsPerByte,\n reinterpret_cast(utf8_text.c_str()),\n utf8_text.length());\n break;\n }\n\n default: {\n NOTREACHED();\n break;\n }\n }\n}\n\nbool ExtractNamedURL(GtkSelectionData* selection_data,\n GURL* url,\n string16* title) {\n Pickle data(reinterpret_cast(selection_data->data),\n selection_data->length);\n void* iter = NULL;\n std::string title_utf8, url_utf8;\n if (!data.ReadString(&iter, &title_utf8) ||\n !data.ReadString(&iter, &url_utf8)) {\n return false;\n }\n\n GURL gurl(url_utf8);\n if (!gurl.is_valid())\n return false;\n\n *url = gurl;\n *title = UTF8ToUTF16(title_utf8);\n return true;\n}\n\nbool ExtractURIList(GtkSelectionData* selection_data, std::vector* urls) {\n gchar** uris = gtk_selection_data_get_uris(selection_data);\n if (!uris)\n return false;\n\n for (size_t i = 0; uris[i] != NULL; ++i) {\n GURL url(uris[i]);\n if (url.is_valid())\n urls->push_back(url);\n }\n\n g_strfreev(uris);\n return true;\n}\n\nGdkDragAction WebDragOpToGdkDragAction(WebDragOperationsMask op) {\n GdkDragAction action = static_cast(0);\n if (op & WebDragOperationCopy)\n action = static_cast(action | GDK_ACTION_COPY);\n if (op & WebDragOperationLink)\n action = static_cast(action | GDK_ACTION_LINK);\n if (op & WebDragOperationMove)\n action = static_cast(action | GDK_ACTION_MOVE);\n return action;\n}\n\nWebDragOperationsMask GdkDragActionToWebDragOp(GdkDragAction action) {\n WebDragOperationsMask op = WebDragOperationNone;\n if (action & GDK_ACTION_COPY)\n op = static_cast(op | WebDragOperationCopy);\n if (action & GDK_ACTION_LINK)\n op = static_cast(op | WebDragOperationLink);\n if (action & GDK_ACTION_MOVE)\n op = static_cast(op | WebDragOperationMove);\n return op;\n}\n\n} \/\/ namespace gtk_dnd_util\nWe DnD shouldn't provide text\/html if it claims to provide text\/text\/plain;charset=utf-8.\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"app\/gtk_dnd_util.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/pickle.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"googleurl\/src\/gurl.h\"\n\nstatic const int kBitsPerByte = 8;\n\nusing WebKit::WebDragOperationsMask;\nusing WebKit::WebDragOperation;\nusing WebKit::WebDragOperationNone;\nusing WebKit::WebDragOperationCopy;\nusing WebKit::WebDragOperationLink;\nusing WebKit::WebDragOperationMove;\n\nnamespace {\n\nvoid AddTargetToList(GtkTargetList* targets, int target_code) {\n switch (target_code) {\n case gtk_dnd_util::TEXT_PLAIN:\n gtk_target_list_add_text_targets(targets, gtk_dnd_util::TEXT_PLAIN);\n break;\n\n case gtk_dnd_util::TEXT_URI_LIST:\n gtk_target_list_add_uri_targets(targets, gtk_dnd_util::TEXT_URI_LIST);\n break;\n\n case gtk_dnd_util::TEXT_HTML:\n gtk_target_list_add(\n targets, gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_HTML),\n 0, gtk_dnd_util::TEXT_HTML);\n break;\n\n case gtk_dnd_util::NETSCAPE_URL:\n gtk_target_list_add(targets,\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::NETSCAPE_URL),\n 0, gtk_dnd_util::NETSCAPE_URL);\n break;\n\n case gtk_dnd_util::CHROME_TAB:\n case gtk_dnd_util::CHROME_BOOKMARK_ITEM:\n case gtk_dnd_util::CHROME_NAMED_URL:\n gtk_target_list_add(targets, gtk_dnd_util::GetAtomForTarget(target_code),\n GTK_TARGET_SAME_APP, target_code);\n break;\n\n case gtk_dnd_util::DIRECT_SAVE_FILE:\n gtk_target_list_add(targets,\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::DIRECT_SAVE_FILE),\n 0, gtk_dnd_util::DIRECT_SAVE_FILE);\n break;\n\n default:\n NOTREACHED() << \" Unexpected target code: \" << target_code;\n }\n}\n\n} \/\/ namespace\n\nnamespace gtk_dnd_util {\n\nGdkAtom GetAtomForTarget(int target) {\n switch (target) {\n case CHROME_TAB:\n static GdkAtom tab_atom = gdk_atom_intern(\n const_cast(\"application\/x-chrome-tab\"), false);\n return tab_atom;\n\n case TEXT_HTML:\n static GdkAtom html_atom = gdk_atom_intern(\n const_cast(\"text\/html\"), false);\n return html_atom;\n\n case CHROME_BOOKMARK_ITEM:\n static GdkAtom bookmark_atom = gdk_atom_intern(\n const_cast(\"application\/x-chrome-bookmark-item\"), false);\n return bookmark_atom;\n\n case TEXT_PLAIN:\n static GdkAtom text_atom = gdk_atom_intern(\n const_cast(\"text\/plain;charset=utf-8\"), false);\n return text_atom;\n\n case TEXT_URI_LIST:\n static GdkAtom uris_atom = gdk_atom_intern(\n const_cast(\"text\/uri-list\"), false);\n return uris_atom;\n\n case CHROME_NAMED_URL:\n static GdkAtom named_url = gdk_atom_intern(\n const_cast(\"application\/x-chrome-named-url\"), false);\n return named_url;\n\n case NETSCAPE_URL:\n static GdkAtom netscape_url = gdk_atom_intern(\n const_cast(\"_NETSCAPE_URL\"), false);\n return netscape_url;\n\n case TEXT_PLAIN_NO_CHARSET:\n static GdkAtom text_no_charset_atom = gdk_atom_intern(\n const_cast(\"text\/plain\"), false);\n return text_no_charset_atom;\n\n case DIRECT_SAVE_FILE:\n static GdkAtom xds_atom = gdk_atom_intern(\n const_cast(\"XdndDirectSave0\"), false);\n return xds_atom;\n\n default:\n NOTREACHED();\n }\n\n return NULL;\n}\n\nGtkTargetList* GetTargetListFromCodeMask(int code_mask) {\n GtkTargetList* targets = gtk_target_list_new(NULL, 0);\n\n for (size_t i = 1; i < INVALID_TARGET; i = i << 1) {\n if (i == CHROME_WEBDROP_FILE_CONTENTS)\n continue;\n\n if (i & code_mask)\n AddTargetToList(targets, i);\n }\n\n return targets;\n}\n\nvoid SetSourceTargetListFromCodeMask(GtkWidget* source, int code_mask) {\n GtkTargetList* targets = GetTargetListFromCodeMask(code_mask);\n gtk_drag_source_set_target_list(source, targets);\n gtk_target_list_unref(targets);\n}\n\nvoid SetDestTargetList(GtkWidget* dest, const int* target_codes) {\n GtkTargetList* targets = gtk_target_list_new(NULL, 0);\n\n for (size_t i = 0; target_codes[i] != -1; ++i) {\n AddTargetToList(targets, target_codes[i]);\n }\n\n gtk_drag_dest_set_target_list(dest, targets);\n gtk_target_list_unref(targets);\n}\n\nvoid WriteURLWithName(GtkSelectionData* selection_data,\n const GURL& url,\n const string16& title,\n int type) {\n switch (type) {\n case TEXT_PLAIN: {\n gtk_selection_data_set_text(selection_data, url.spec().c_str(),\n url.spec().length());\n break;\n }\n case TEXT_URI_LIST: {\n gchar* uri_array[2];\n uri_array[0] = strdup(url.spec().c_str());\n uri_array[1] = NULL;\n gtk_selection_data_set_uris(selection_data, uri_array);\n free(uri_array[0]);\n break;\n }\n case CHROME_NAMED_URL: {\n Pickle pickle;\n pickle.WriteString(UTF16ToUTF8(title));\n pickle.WriteString(url.spec());\n gtk_selection_data_set(\n selection_data,\n GetAtomForTarget(gtk_dnd_util::CHROME_NAMED_URL),\n kBitsPerByte,\n reinterpret_cast(pickle.data()),\n pickle.size());\n break;\n }\n case NETSCAPE_URL: {\n \/\/ _NETSCAPE_URL format is URL + \\n + title.\n std::string utf8_text = url.spec() + \"\\n\" + UTF16ToUTF8(title);\n gtk_selection_data_set(selection_data,\n selection_data->target,\n kBitsPerByte,\n reinterpret_cast(utf8_text.c_str()),\n utf8_text.length());\n break;\n }\n\n default: {\n NOTREACHED();\n break;\n }\n }\n}\n\nbool ExtractNamedURL(GtkSelectionData* selection_data,\n GURL* url,\n string16* title) {\n Pickle data(reinterpret_cast(selection_data->data),\n selection_data->length);\n void* iter = NULL;\n std::string title_utf8, url_utf8;\n if (!data.ReadString(&iter, &title_utf8) ||\n !data.ReadString(&iter, &url_utf8)) {\n return false;\n }\n\n GURL gurl(url_utf8);\n if (!gurl.is_valid())\n return false;\n\n *url = gurl;\n *title = UTF8ToUTF16(title_utf8);\n return true;\n}\n\nbool ExtractURIList(GtkSelectionData* selection_data, std::vector* urls) {\n gchar** uris = gtk_selection_data_get_uris(selection_data);\n if (!uris)\n return false;\n\n for (size_t i = 0; uris[i] != NULL; ++i) {\n GURL url(uris[i]);\n if (url.is_valid())\n urls->push_back(url);\n }\n\n g_strfreev(uris);\n return true;\n}\n\nGdkDragAction WebDragOpToGdkDragAction(WebDragOperationsMask op) {\n GdkDragAction action = static_cast(0);\n if (op & WebDragOperationCopy)\n action = static_cast(action | GDK_ACTION_COPY);\n if (op & WebDragOperationLink)\n action = static_cast(action | GDK_ACTION_LINK);\n if (op & WebDragOperationMove)\n action = static_cast(action | GDK_ACTION_MOVE);\n return action;\n}\n\nWebDragOperationsMask GdkDragActionToWebDragOp(GdkDragAction action) {\n WebDragOperationsMask op = WebDragOperationNone;\n if (action & GDK_ACTION_COPY)\n op = static_cast(op | WebDragOperationCopy);\n if (action & GDK_ACTION_LINK)\n op = static_cast(op | WebDragOperationLink);\n if (action & GDK_ACTION_MOVE)\n op = static_cast(op | WebDragOperationMove);\n return op;\n}\n\n} \/\/ namespace gtk_dnd_util\n<|endoftext|>"} {"text":"#include \"types.h\"\n#include \"amd64.h\"\n#include \"mmu.h\"\n#include \"cpu.hh\"\n#include \"kernel.hh\"\n#include \"bits.hh\"\n#include \"spinlock.h\"\n#include \"kalloc.hh\"\n#include \"queue.h\"\n#include \"condvar.h\"\n#include \"proc.hh\"\n#include \"vm.hh\"\n#include \n\nusing namespace std;\n\nstatic pgmap*\ndescend(pgmap *dir, u64 va, u64 flags, int create, int level)\n{\n atomic *entryp;\n pme_t entry;\n pgmap *next;\n\nretry:\n entryp = &dir->e[PX(level, va)];\n entry = entryp->load();\n if (entry & PTE_P) {\n next = (pgmap*) p2v(PTE_ADDR(entry));\n } else {\n if (!create)\n return NULL;\n next = (pgmap*) kalloc();\n if (!next)\n return NULL;\n memset(next, 0, PGSIZE);\n if (!cmpxch(entryp, entry, v2p(next) | PTE_P | PTE_W | flags)) {\n kfree((void*) next);\n goto retry;\n }\n }\n return next;\n}\n\n\/\/ Return the address of the PTE in page table pgdir\n\/\/ that corresponds to linear address va. If create!=0,\n\/\/ create any required page table pages.\natomic*\nwalkpgdir(pgmap *pml4, u64 va, int create)\n{\n auto pdp = descend(pml4, va, PTE_U, create, 3);\n if (pdp == NULL)\n return NULL;\n auto pd = descend(pdp, va, PTE_U, create, 2);\n if (pd == NULL)\n return NULL;\n auto pt = descend(pd, va, PTE_U, create, 1);\n if (pt == NULL)\n return NULL;\n return &pt->e[PX(0,va)];\n}\n\n\/\/ Map from 0 to 128Gbytes starting at KBASE.\nvoid\ninitpg(void)\n{\n extern char end[]; \n u64 va = KBASE;\n paddr pa = 0;\n\n while (va < (KBASE+(128ull<<30))) {\n auto pdp = descend(&kpml4, va, 0, 1, 3);\n auto pd = descend(pdp, va, 0, 1, 2);\n atomic *sp = &pd->e[PX(1,va)];\n u64 flags = PTE_W | PTE_P | PTE_PS;\n \/\/ Set NX for non-code pages\n if (va >= (u64) end)\n flags |= PTE_NX;\n *sp = pa | flags;\n va = va + PGSIZE*512;\n pa += PGSIZE*512;\n }\n}\n\n\/\/ Set up kernel part of a page table.\npgmap*\nsetupkvm(void)\n{\n pgmap *pml4;\n int k;\n\n if((pml4 = (pgmap*)kalloc()) == 0)\n return 0;\n k = PX(3, KBASE);\n memset(&pml4->e[0], 0, 8*k);\n memmove(&pml4->e[k], &kpml4.e[k], 8*(512-k));\n return pml4;\n}\n\nint\nsetupkshared(pgmap *pml4, char *kshared)\n{\n for (u64 off = 0; off < KSHAREDSIZE; off+=4096) {\n atomic *pte = walkpgdir(pml4, (u64) (KSHARED+off), 1);\n if (pte == NULL)\n panic(\"setupkshared: oops\");\n *pte = v2p(kshared+off) | PTE_P | PTE_U | PTE_W;\n }\n return 0;\n}\n\n\/\/ Switch h\/w page table register to the kernel-only page table,\n\/\/ for when no process is running.\nvoid\nswitchkvm(void)\n{\n lcr3(v2p(&kpml4)); \/\/ switch to the kernel page table\n}\n\n\/\/ Switch TSS and h\/w page table to correspond to process p.\nvoid\nswitchuvm(struct proc *p)\n{\n u64 base = (u64) &mycpu()->ts;\n pushcli();\n mycpu()->gdt[TSSSEG>>3] = (struct segdesc)\n SEGDESC(base, (sizeof(mycpu()->ts)-1), SEG_P|SEG_TSS64A);\n mycpu()->gdt[(TSSSEG>>3)+1] = (struct segdesc) SEGDESCHI(base);\n mycpu()->ts.rsp[0] = (u64) myproc()->kstack + KSTACKSIZE;\n mycpu()->ts.iomba = (u16)offsetof(struct taskstate, iopb);\n ltr(TSSSEG);\n if(p->vmap == 0 || p->vmap->pml4 == 0)\n panic(\"switchuvm: no vmap\/pml4\");\n lcr3(v2p(p->vmap->pml4)); \/\/ switch to new address space\n popcli();\n}\n\nstatic void\nfreepm(pgmap *pm, int level)\n{\n int i;\n\n if (level != 0) {\n for (i = 0; i < 512; i++) {\n pme_t entry = pm->e[i];\n if (entry & PTE_P)\n freepm((pgmap*) p2v(PTE_ADDR(entry)), level - 1);\n }\n }\n\n kfree(pm);\n}\n\n\/\/ Free a page table and all the physical memory pages\n\/\/ in the user part.\nvoid\nfreevm(pgmap *pml4)\n{\n int k;\n int i;\n\n if(pml4 == 0)\n panic(\"freevm: no pgdir\");\n\n \/\/ Don't free kernel portion of the pml4\n k = PX(3, KBASE);\n for (i = 0; i < k; i++) {\n pme_t entry = pml4->e[i];\n if (entry & PTE_P) {\n freepm((pgmap*) p2v(PTE_ADDR(entry)), 2);\n }\n }\n \n kfree(pml4);\n}\n\n\/\/ Set up CPU's kernel segment descriptors.\n\/\/ Run once at boot time on each CPU.\nvoid\ninittls(void)\n{\n struct cpu *c;\n\n \/\/ Initialize cpu-local storage.\n c = &cpus[cpunum()];\n writegs(KDSEG);\n writemsr(MSR_GS_BASE, (u64)&c->cpu);\n c->cpu = c;\n c->proc = NULL;\n c->kmem = &kmems[cpunum()];\n}\n\natomic tlbflush_req;\n\nvoid\ntlbflush()\n{\n u64 myreq = tlbflush_req++;\n\n pushcli();\n \/\/ the caller may not hold any spinlock, because other CPUs might\n \/\/ be spinning waiting for that spinlock, with interrupts disabled,\n \/\/ so we will deadlock waiting for their TLB flush..\n assert(mycpu()->ncli == 1);\n\n int myid = mycpu()->id;\n lcr3(rcr3());\n popcli();\n\n for (int i = 0; i < ncpu; i++)\n if (i != myid)\n lapic_tlbflush(i);\n\n for (int i = 0; i < ncpu; i++)\n if (i != myid)\n while (cpus[i].tlbflush_done < myreq)\n \/* spin *\/ ;\n}\navoid pushcli\/popcli#include \"types.h\"\n#include \"amd64.h\"\n#include \"mmu.h\"\n#include \"cpu.hh\"\n#include \"kernel.hh\"\n#include \"bits.hh\"\n#include \"spinlock.h\"\n#include \"kalloc.hh\"\n#include \"queue.h\"\n#include \"condvar.h\"\n#include \"proc.hh\"\n#include \"vm.hh\"\n#include \n\nusing namespace std;\n\nstatic pgmap*\ndescend(pgmap *dir, u64 va, u64 flags, int create, int level)\n{\n atomic *entryp;\n pme_t entry;\n pgmap *next;\n\nretry:\n entryp = &dir->e[PX(level, va)];\n entry = entryp->load();\n if (entry & PTE_P) {\n next = (pgmap*) p2v(PTE_ADDR(entry));\n } else {\n if (!create)\n return NULL;\n next = (pgmap*) kalloc();\n if (!next)\n return NULL;\n memset(next, 0, PGSIZE);\n if (!cmpxch(entryp, entry, v2p(next) | PTE_P | PTE_W | flags)) {\n kfree((void*) next);\n goto retry;\n }\n }\n return next;\n}\n\n\/\/ Return the address of the PTE in page table pgdir\n\/\/ that corresponds to linear address va. If create!=0,\n\/\/ create any required page table pages.\natomic*\nwalkpgdir(pgmap *pml4, u64 va, int create)\n{\n auto pdp = descend(pml4, va, PTE_U, create, 3);\n if (pdp == NULL)\n return NULL;\n auto pd = descend(pdp, va, PTE_U, create, 2);\n if (pd == NULL)\n return NULL;\n auto pt = descend(pd, va, PTE_U, create, 1);\n if (pt == NULL)\n return NULL;\n return &pt->e[PX(0,va)];\n}\n\n\/\/ Map from 0 to 128Gbytes starting at KBASE.\nvoid\ninitpg(void)\n{\n extern char end[]; \n u64 va = KBASE;\n paddr pa = 0;\n\n while (va < (KBASE+(128ull<<30))) {\n auto pdp = descend(&kpml4, va, 0, 1, 3);\n auto pd = descend(pdp, va, 0, 1, 2);\n atomic *sp = &pd->e[PX(1,va)];\n u64 flags = PTE_W | PTE_P | PTE_PS;\n \/\/ Set NX for non-code pages\n if (va >= (u64) end)\n flags |= PTE_NX;\n *sp = pa | flags;\n va = va + PGSIZE*512;\n pa += PGSIZE*512;\n }\n}\n\n\/\/ Set up kernel part of a page table.\npgmap*\nsetupkvm(void)\n{\n pgmap *pml4;\n int k;\n\n if((pml4 = (pgmap*)kalloc()) == 0)\n return 0;\n k = PX(3, KBASE);\n memset(&pml4->e[0], 0, 8*k);\n memmove(&pml4->e[k], &kpml4.e[k], 8*(512-k));\n return pml4;\n}\n\nint\nsetupkshared(pgmap *pml4, char *kshared)\n{\n for (u64 off = 0; off < KSHAREDSIZE; off+=4096) {\n atomic *pte = walkpgdir(pml4, (u64) (KSHARED+off), 1);\n if (pte == NULL)\n panic(\"setupkshared: oops\");\n *pte = v2p(kshared+off) | PTE_P | PTE_U | PTE_W;\n }\n return 0;\n}\n\n\/\/ Switch h\/w page table register to the kernel-only page table,\n\/\/ for when no process is running.\nvoid\nswitchkvm(void)\n{\n lcr3(v2p(&kpml4)); \/\/ switch to the kernel page table\n}\n\n\/\/ Switch TSS and h\/w page table to correspond to process p.\nvoid\nswitchuvm(struct proc *p)\n{\n u64 base = (u64) &mycpu()->ts;\n pushcli();\n mycpu()->gdt[TSSSEG>>3] = (struct segdesc)\n SEGDESC(base, (sizeof(mycpu()->ts)-1), SEG_P|SEG_TSS64A);\n mycpu()->gdt[(TSSSEG>>3)+1] = (struct segdesc) SEGDESCHI(base);\n mycpu()->ts.rsp[0] = (u64) myproc()->kstack + KSTACKSIZE;\n mycpu()->ts.iomba = (u16)offsetof(struct taskstate, iopb);\n ltr(TSSSEG);\n if(p->vmap == 0 || p->vmap->pml4 == 0)\n panic(\"switchuvm: no vmap\/pml4\");\n lcr3(v2p(p->vmap->pml4)); \/\/ switch to new address space\n popcli();\n}\n\nstatic void\nfreepm(pgmap *pm, int level)\n{\n int i;\n\n if (level != 0) {\n for (i = 0; i < 512; i++) {\n pme_t entry = pm->e[i];\n if (entry & PTE_P)\n freepm((pgmap*) p2v(PTE_ADDR(entry)), level - 1);\n }\n }\n\n kfree(pm);\n}\n\n\/\/ Free a page table and all the physical memory pages\n\/\/ in the user part.\nvoid\nfreevm(pgmap *pml4)\n{\n int k;\n int i;\n\n if(pml4 == 0)\n panic(\"freevm: no pgdir\");\n\n \/\/ Don't free kernel portion of the pml4\n k = PX(3, KBASE);\n for (i = 0; i < k; i++) {\n pme_t entry = pml4->e[i];\n if (entry & PTE_P) {\n freepm((pgmap*) p2v(PTE_ADDR(entry)), 2);\n }\n }\n \n kfree(pml4);\n}\n\n\/\/ Set up CPU's kernel segment descriptors.\n\/\/ Run once at boot time on each CPU.\nvoid\ninittls(void)\n{\n struct cpu *c;\n\n \/\/ Initialize cpu-local storage.\n c = &cpus[cpunum()];\n writegs(KDSEG);\n writemsr(MSR_GS_BASE, (u64)&c->cpu);\n c->cpu = c;\n c->proc = NULL;\n c->kmem = &kmems[cpunum()];\n}\n\natomic tlbflush_req;\n\nvoid\ntlbflush()\n{\n u64 myreq = tlbflush_req++;\n\n \/\/ the caller may not hold any spinlock, because other CPUs might\n \/\/ be spinning waiting for that spinlock, with interrupts disabled,\n \/\/ so we will deadlock waiting for their TLB flush..\n assert(mycpu()->ncli == 0);\n\n for (int i = 0; i < ncpu; i++)\n lapic_tlbflush(i);\n\n for (int i = 0; i < ncpu; i++)\n while (cpus[i].tlbflush_done < myreq)\n \/* spin *\/ ;\n}\n<|endoftext|>"} {"text":"\n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \"filter\/compiler.h\"\n\n#include \"fileemitor.h\"\n#include \"version.h\"\n#include \"worker.h\"\nnamespace po = boost::program_options;\n\nstd::mutex screenMutex;\n\nstd::string recordSeparator = \"\\n\";\nvoid outDocument(const std::string &what) {\n std::lock_guard screenLock(screenMutex);\n std::cout.write(what.data(), what.size());\n std::cout << recordSeparator;\n}\n\nvoid updateSeparator(std::string &sep) {\n std::string res;\n bool esc = false;\n for(char c : sep) {\n if (esc) {\n switch(c) {\n case 'n':\n res += '\\n';\n break;\n case 't':\n res += '\\t';\n break;\n default:\n res += c;\n }\n esc = false;\n continue;\n }\n if (c == '\\\\') {\n esc = true;\n } else {\n res += c;\n }\n }\n sep = res;\n}\n\nvoid correctJobsNumber(u_int &jobs) {\n if (jobs < 1) {\n std::cerr << \"hint: adjusting threads number to 1\" << std::endl;\n jobs = 1;\n } else if (jobs > 10) {\n std::cerr << \"hint: do not be so greedy. adjusting threads number to 10\" << std::endl;\n jobs = 10;\n }\n}\n\nint main(int argc, const char * argv[]) {\n\n std::cout.sync_with_stdio(false);\n\n std::string condition;\n int limit = -1;\n u_int jobs = 1;\n std::string fields;\n bool printProcessingFile = false;\n bool countMode = false;\n bool disableParseLoop = false;\n bool displayVersionAndExit = false;\n std::string fieldSeparator = \"\\t\";\n\n po::options_description desc(\"Allowed options\");\n desc.add_options()\n (\"input-file,f\", po::value< std::vector >(), \"Input files\")\n (\"condition,c\", po::value< std::string >(&condition), \"Expression\")\n (\"limit,n\", po::value< int >(&limit)->default_value(-1), \"Maximum number of records (default -1 means no limit)\")\n (\"fields,l\", po::value< std::string >(&fields), \"Fields to output\")\n (\"print-file\", po::bool_switch(&printProcessingFile), \"Print name of processing file\")\n (\"jobs,j\", po::value< u_int >(&jobs)->default_value(1), \"Number of threads to run\")\n (\"count-only\", po::bool_switch(&countMode), \"Count of matched records, don't print them\")\n (\"record-separator\", po::value(&recordSeparator)->default_value(\"\\\\n\"), \"Record separator (\\\\n by default)\")\n (\"field-separator\", po::value(&fieldSeparator)->default_value(\"\\\\t\"), \"Field separator for TSV output (\\\\t by default)\")\n (\"disable-parse-loop\", po::bool_switch(&disableParseLoop), \"Disable experimental parsing mode (enabled by default)\")\n (\"help,h\", \"Show help message\")\n (\"version\", po::bool_switch(&displayVersionAndExit), \"Display version and exit\")\n ;\n\n po::positional_options_description p;\n p.add(\"input-file\", -1);\n\n po::variables_map vm;\n try {\n po::store(po::command_line_parser(argc, argv).\n options(desc).positional(p).run(), vm);\n po::notify(vm);\n } catch(const boost::program_options::error &e) {\n std::cerr << \"Sorry, I couldn't parse arguments: \" << e.what() << std::endl;\n std::cerr << \"Try --help\" << std::endl;\n return 1;\n }\n if (vm.count(\"help\")) {\n std::cout << desc << std::endl;\n return 0;\n }\n if (displayVersionAndExit) {\n std::cout << \"aq version: \" << avroqVersion() << std::endl;\n return 0;\n }\n\n updateSeparator(recordSeparator);\n updateSeparator(fieldSeparator);\n\n filter::Compiler filterCompiler;\n std::shared_ptr filter;\n\n if (!condition.empty()) {\n try {\n filter = filterCompiler.compile(condition);\n } catch(const filter::Compiler::CompileError &e) {\n std::cerr << \"Condition complile failed: \" << std::endl;\n std::cerr << e.what() << std::endl;\n return 1;\n }\n }\n\n if (vm.count(\"input-file\")) {\n\n const auto &fileList = vm[\"input-file\"].as< std::vector >();\n\n FileEmitor emitor(fileList, limit, outDocument);\n\n emitor.setFilter(filter);\n emitor.setTsvFieldList(fields, fieldSeparator);\n if (printProcessingFile) {\n emitor.enablePrintProcessingFile();\n }\n if (countMode) {\n emitor.enableCountOnlyMode();\n }\n if ( ! disableParseLoop ) {\n emitor.enableParseLoop();\n }\n std::vector workers;\n\n correctJobsNumber(jobs);\n\n for(u_int i = 0; i < jobs; ++i) { \/\/ TODO: check for inadequate values\n workers.emplace_back(\n std::thread(Worker(emitor))\n );\n }\n\n for(auto &p : workers) {\n p.join();\n }\n\n if (countMode) {\n std::cout << \"Matched documents: \" << emitor.getCountedDocuments() << std::endl;\n }\n\n if (emitor.getLastError().size() > 0) {\n std::cerr << emitor.getLastError() << std::endl;\n return 1;\n }\n\n } else {\n std::cerr << \"No input files\" << std::endl;\n return 1;\n }\n\n return 0;\n}\nIncreased threads limit to 16, for 16-x core systems\n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \"filter\/compiler.h\"\n\n#include \"fileemitor.h\"\n#include \"version.h\"\n#include \"worker.h\"\nnamespace po = boost::program_options;\n\nstd::mutex screenMutex;\n\nstd::string recordSeparator = \"\\n\";\nvoid outDocument(const std::string &what) {\n std::lock_guard screenLock(screenMutex);\n std::cout.write(what.data(), what.size());\n std::cout << recordSeparator;\n}\n\nvoid updateSeparator(std::string &sep) {\n std::string res;\n bool esc = false;\n for(char c : sep) {\n if (esc) {\n switch(c) {\n case 'n':\n res += '\\n';\n break;\n case 't':\n res += '\\t';\n break;\n default:\n res += c;\n }\n esc = false;\n continue;\n }\n if (c == '\\\\') {\n esc = true;\n } else {\n res += c;\n }\n }\n sep = res;\n}\n\nvoid correctJobsNumber(u_int &jobs) {\n if (jobs < 1) {\n std::cerr << \"hint: adjusting threads number to 1\" << std::endl;\n jobs = 1;\n } else if (jobs > 16) {\n std::cerr << \"hint: do not be so greedy. adjusting threads number to 16\" << std::endl;\n jobs = 16;\n }\n}\n\nint main(int argc, const char * argv[]) {\n\n std::cout.sync_with_stdio(false);\n\n std::string condition;\n int limit = -1;\n u_int jobs = 1;\n std::string fields;\n bool printProcessingFile = false;\n bool countMode = false;\n bool disableParseLoop = false;\n bool displayVersionAndExit = false;\n std::string fieldSeparator = \"\\t\";\n\n po::options_description desc(\"Allowed options\");\n desc.add_options()\n (\"input-file,f\", po::value< std::vector >(), \"Input files\")\n (\"condition,c\", po::value< std::string >(&condition), \"Expression\")\n (\"limit,n\", po::value< int >(&limit)->default_value(-1), \"Maximum number of records (default -1 means no limit)\")\n (\"fields,l\", po::value< std::string >(&fields), \"Fields to output\")\n (\"print-file\", po::bool_switch(&printProcessingFile), \"Print name of processing file\")\n (\"jobs,j\", po::value< u_int >(&jobs)->default_value(1), \"Number of threads to run\")\n (\"count-only\", po::bool_switch(&countMode), \"Count of matched records, don't print them\")\n (\"record-separator\", po::value(&recordSeparator)->default_value(\"\\\\n\"), \"Record separator (\\\\n by default)\")\n (\"field-separator\", po::value(&fieldSeparator)->default_value(\"\\\\t\"), \"Field separator for TSV output (\\\\t by default)\")\n (\"disable-parse-loop\", po::bool_switch(&disableParseLoop), \"Disable experimental parsing mode (enabled by default)\")\n (\"help,h\", \"Show help message\")\n (\"version\", po::bool_switch(&displayVersionAndExit), \"Display version and exit\")\n ;\n\n po::positional_options_description p;\n p.add(\"input-file\", -1);\n\n po::variables_map vm;\n try {\n po::store(po::command_line_parser(argc, argv).\n options(desc).positional(p).run(), vm);\n po::notify(vm);\n } catch(const boost::program_options::error &e) {\n std::cerr << \"Sorry, I couldn't parse arguments: \" << e.what() << std::endl;\n std::cerr << \"Try --help\" << std::endl;\n return 1;\n }\n if (vm.count(\"help\")) {\n std::cout << desc << std::endl;\n return 0;\n }\n if (displayVersionAndExit) {\n std::cout << \"aq version: \" << avroqVersion() << std::endl;\n return 0;\n }\n\n updateSeparator(recordSeparator);\n updateSeparator(fieldSeparator);\n\n filter::Compiler filterCompiler;\n std::shared_ptr filter;\n\n if (!condition.empty()) {\n try {\n filter = filterCompiler.compile(condition);\n } catch(const filter::Compiler::CompileError &e) {\n std::cerr << \"Condition complile failed: \" << std::endl;\n std::cerr << e.what() << std::endl;\n return 1;\n }\n }\n\n if (vm.count(\"input-file\")) {\n\n const auto &fileList = vm[\"input-file\"].as< std::vector >();\n\n FileEmitor emitor(fileList, limit, outDocument);\n\n emitor.setFilter(filter);\n emitor.setTsvFieldList(fields, fieldSeparator);\n if (printProcessingFile) {\n emitor.enablePrintProcessingFile();\n }\n if (countMode) {\n emitor.enableCountOnlyMode();\n }\n if ( ! disableParseLoop ) {\n emitor.enableParseLoop();\n }\n std::vector workers;\n\n correctJobsNumber(jobs);\n\n for(u_int i = 0; i < jobs; ++i) { \/\/ TODO: check for inadequate values\n workers.emplace_back(\n std::thread(Worker(emitor))\n );\n }\n\n for(auto &p : workers) {\n p.join();\n }\n\n if (countMode) {\n std::cout << \"Matched documents: \" << emitor.getCountedDocuments() << std::endl;\n }\n\n if (emitor.getLastError().size() > 0) {\n std::cerr << emitor.getLastError() << std::endl;\n return 1;\n }\n\n } else {\n std::cerr << \"No input files\" << std::endl;\n return 1;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ =============================================================================\n\/\/ FinishedNodes returns a 1-D tensor listing the nodes that are finished\n\/\/ accumulating.\n#include \"tensorflow\/contrib\/tensor_forest\/core\/ops\/tree_utils.h\"\n\n#include \"tensorflow\/core\/framework\/op.h\"\n#include \"tensorflow\/core\/framework\/op_kernel.h\"\n#include \"tensorflow\/core\/framework\/shape_inference.h\"\n#include \"tensorflow\/core\/kernels\/bounds_check.h\"\n#include \"tensorflow\/core\/lib\/random\/simple_philox.h\"\n#include \"tensorflow\/core\/platform\/env.h\"\n#include \"tensorflow\/core\/platform\/mutex.h\"\n#include \"tensorflow\/core\/util\/work_sharder.h\"\n\nnamespace tensorflow {\n\nusing shape_inference::Dimension;\nusing shape_inference::InferenceContext;\nusing shape_inference::Shape;\n\nusing std::placeholders::_1;\nusing std::placeholders::_2;\n\nusing tensorforest::CheckTensorBounds;\nusing tensorforest::Sum;\nusing tensorforest::BestSplitDominatesClassificationBootstrap;\nusing tensorforest::BestSplitDominatesClassificationChebyshev;\nusing tensorforest::BestSplitDominatesClassificationHoeffding;\nusing tensorforest::BestSplitDominatesRegression;\n\nnamespace {\n\nstruct EvaluateParams {\n Tensor leaves;\n Tensor node_to_accumulator;\n Tensor accumulator_sums;\n Tensor birth_epochs;\n int current_epoch;\n int32 num_split_after_samples;\n int32 min_split_samples;\n bool need_random;\n int64 random_seed;\n std::function dominate_method;\n};\n\nvoid Evaluate(const EvaluateParams& params, mutex* mutex, int32 start,\n int32 end, std::vector* final_finished_leaves,\n std::vector* final_stale) {\n const auto leaves = params.leaves.unaligned_flat();\n const auto node_map = params.node_to_accumulator.unaligned_flat();\n const auto sums = params.accumulator_sums.tensor();\n const auto start_epochs = params.birth_epochs.unaligned_flat();\n\n const int32 num_accumulators =\n static_cast(params.accumulator_sums.shape().dim_size(0));\n\n std::vector finished_leaves;\n std::vector stale;\n\n std::unique_ptr simple_philox;\n random::PhiloxRandom rnd_gen(params.random_seed);\n\n if (params.need_random) {\n simple_philox.reset(new random::SimplePhilox(&rnd_gen));\n }\n\n for (int32 i = start; i < end; i++) {\n const int32 leaf = internal::SubtleMustCopy(leaves(i));\n if (leaf == -1) {\n continue;\n }\n if (!FastBoundsCheck(leaf, node_map.size())) {\n LOG(ERROR) << \"leaf \" << leaf << \" not in valid range.\";\n }\n const int32 accumulator = internal::SubtleMustCopy(node_map(leaf));\n if (accumulator < 0) {\n continue;\n }\n\n if (!FastBoundsCheck(accumulator, num_accumulators)) {\n LOG(ERROR) << \"accumulator \" << accumulator << \" not in valid range.\";\n }\n \/\/ The first column holds the number of samples seen.\n \/\/ For classification, this should be the sum of the other columns.\n int32 count = sums(accumulator, 0);\n\n if (params.current_epoch > start_epochs(leaf) + 1) {\n if (count >= params.min_split_samples) {\n finished_leaves.push_back(leaf);\n } else {\n stale.push_back(leaf);\n }\n continue;\n }\n\n if (count >= params.num_split_after_samples) {\n finished_leaves.push_back(leaf);\n continue;\n }\n\n if (count < params.min_split_samples) {\n continue;\n }\n\n bool finished = params.dominate_method(accumulator, simple_philox.get());\n if (finished) {\n finished_leaves.push_back(leaf);\n }\n }\n mutex_lock m(*mutex);\n final_finished_leaves->insert(final_finished_leaves->end(),\n finished_leaves.begin(), finished_leaves.end());\n final_stale->insert(final_stale->end(), stale.begin(), stale.end());\n}\n} \/\/ namespace\n\nREGISTER_OP(\"FinishedNodes\")\n .Attr(\"regression: bool = false\")\n .Attr(\"num_split_after_samples: int\")\n .Attr(\"min_split_samples: int\")\n .Attr(\"dominate_fraction: float = 0.99\")\n \/\/ TODO(thomaswc): Test out bootstrap on several datasets, confirm it\n \/\/ works well, make it the default.\n .Attr(\n \"dominate_method:\"\n \" {'none', 'hoeffding', 'bootstrap', 'chebyshev'} = 'hoeffding'\")\n .Attr(\"random_seed: int = 0\")\n .Input(\"leaves: int32\")\n .Input(\"node_to_accumulator: int32\")\n .Input(\"split_sums: float\")\n .Input(\"split_squares: float\")\n .Input(\"accumulator_sums: float\")\n .Input(\"accumulator_squares: float\")\n .Input(\"birth_epochs: int32\")\n .Input(\"current_epoch: int32\")\n .Output(\"finished: int32\")\n .Output(\"stale: int32\")\n .SetShapeFn([](InferenceContext* c) {\n c->set_output(0, c->Vector(InferenceContext::kUnknownDim));\n c->set_output(1, c->Vector(InferenceContext::kUnknownDim));\n return Status::OK();\n })\n .Doc(R\"doc(\nDetermines which of the given leaf nodes are done accumulating.\n\nleaves:= A 1-d int32 tensor. Lists the nodes that are currently leaves.\nnode_to_accumulator: If the i-th node is fertile, `node_to_accumulator[i]`\n is it's accumulator slot. Otherwise, `node_to_accumulator[i]` is -1.\nsplit_sums:= a 3-d tensor where `split_sums[a][s]` summarizes the\n training labels for examples that fall into the fertile node associated with\n accumulator slot s and have then taken the *left* branch of candidate split\n s. For a classification problem, `split_sums[a][s][c]` is the count of such\n examples with class c and for regression problems, `split_sums[a][s]` is the\n sum of the regression labels for such examples.\nsplit_squares: Same as split_sums, but it contains the sum of the\n squares of the regression labels. Only used for regression. For\n classification problems, pass a dummy tensor into this.\naccumulator_sums: For classification, `accumulator_sums[a][c]` records how\n many training examples have class c and have ended up in the fertile node\n associated with accumulator slot a. It has the total sum in entry 0 for\n convenience. For regression, it is the same except it contains the sum\n of the input labels that have been seen, and entry 0 contains the number\n of training examples that have been seen.\naccumulator_squares: Same as accumulator_sums, but it contains the sum of the\n squares of the regression labels. Only used for regression. For\n classification problems, pass a dummy tensor into this.\nbirth_epochs:= A 1-d int32 tensor. `birth_epochs[i]` contains the epoch\n the i-th node was created in.\ncurrent_epoch:= A 1-d int32 tensor with shape (1). `current_epoch[0]`\n stores the current epoch number.\nfinished:= A 1-d int32 tensor containing the indices of the finished nodes.\n Nodes are finished if they have received at least num_split_after_samples\n samples, or if they have received min_split_samples and the best scoring\n split is sufficiently greater than the next best split.\nstale:= A 1-d int32 tensor containing the fertile nodes that were created two\n or more epochs ago.\n\n)doc\");\n\nclass FinishedNodes : public OpKernel {\n public:\n explicit FinishedNodes(OpKernelConstruction* context)\n : OpKernel(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\n \"regression\", ®ression_));\n OP_REQUIRES_OK(context, context->GetAttr(\n \"num_split_after_samples\", &num_split_after_samples_));\n OP_REQUIRES_OK(context, context->GetAttr(\n \"min_split_samples\", &min_split_samples_));\n OP_REQUIRES_OK(context, context->GetAttr(\n \"dominate_fraction\", &dominate_fraction_));\n OP_REQUIRES_OK(context,\n context->GetAttr(\"dominate_method\", &dominate_method_));\n OP_REQUIRES_OK(context, context->GetAttr(\"random_seed\", &random_seed_));\n }\n\n void Compute(OpKernelContext* context) override {\n const Tensor& leaf_tensor = context->input(0);\n const Tensor& node_to_accumulator = context->input(1);\n const Tensor& split_sums = context->input(2);\n const Tensor& split_squares = context->input(3);\n const Tensor& accumulator_sums = context->input(4);\n const Tensor& accumulator_squares = context->input(5);\n const Tensor& birth_epochs = context->input(6);\n const Tensor& current_epoch = context->input(7);\n\n OP_REQUIRES(context, leaf_tensor.shape().dims() == 1,\n errors::InvalidArgument(\n \"leaf_tensor should be one-dimensional\"));\n OP_REQUIRES(context, node_to_accumulator.shape().dims() == 1,\n errors::InvalidArgument(\n \"node_to_accumulator should be one-dimensional\"));\n OP_REQUIRES(context, split_sums.shape().dims() == 3,\n errors::InvalidArgument(\n \"split_sums should be three-dimensional\"));\n OP_REQUIRES(context, accumulator_sums.shape().dims() == 2,\n errors::InvalidArgument(\n \"accumulator_sums should be two-dimensional\"));\n OP_REQUIRES(context, birth_epochs.shape().dims() == 1,\n errors::InvalidArgument(\n \"birth_epochs should be one-dimensional\"));\n OP_REQUIRES(\n context,\n birth_epochs.shape().dim_size(0) ==\n node_to_accumulator.shape().dim_size(0),\n errors::InvalidArgument(\n \"birth_epochs and node_to_accumulator should be the same size.\"));\n\n \/\/ Check tensor bounds.\n if (!CheckTensorBounds(context, leaf_tensor)) return;\n if (!CheckTensorBounds(context, node_to_accumulator)) return;\n if (!CheckTensorBounds(context, split_sums)) return;\n if (!CheckTensorBounds(context, split_squares)) return;\n if (!CheckTensorBounds(context, accumulator_sums)) return;\n if (!CheckTensorBounds(context, accumulator_squares)) return;\n if (!CheckTensorBounds(context, birth_epochs)) return;\n if (!CheckTensorBounds(context, current_epoch)) return;\n\n const int32 epoch = current_epoch.unaligned_flat()(0);\n\n const int32 num_leaves = static_cast(\n leaf_tensor.shape().dim_size(0));\n\n auto worker_threads = context->device()->tensorflow_cpu_worker_threads();\n int num_threads = worker_threads->num_threads;\n\n EvaluateParams params;\n params.leaves = leaf_tensor;\n params.node_to_accumulator = node_to_accumulator;\n params.accumulator_sums = accumulator_sums;\n params.birth_epochs = birth_epochs;\n params.current_epoch = epoch;\n params.min_split_samples = min_split_samples_;\n params.num_split_after_samples = num_split_after_samples_;\n params.need_random = false;\n\n if (regression_) {\n params.dominate_method =\n std::bind(&BestSplitDominatesRegression, accumulator_sums,\n accumulator_squares, split_sums, split_squares, _1);\n } else {\n if (dominate_method_ == \"none\") {\n params.dominate_method = [](int, random::SimplePhilox*) {\n return false;\n };\n } else if (dominate_method_ == \"hoeffding\") {\n params.dominate_method =\n std::bind(&BestSplitDominatesClassificationHoeffding,\n accumulator_sums, split_sums, _1, dominate_fraction_);\n } else if (dominate_method_ == \"chebyshev\") {\n params.dominate_method =\n std::bind(&BestSplitDominatesClassificationChebyshev,\n accumulator_sums, split_sums, _1, dominate_fraction_);\n } else if (dominate_method_ == \"bootstrap\") {\n params.need_random = true;\n\n params.random_seed = random_seed_;\n if (params.random_seed == 0) {\n params.random_seed = static_cast(Env::Default()->NowMicros());\n }\n\n params.dominate_method =\n std::bind(&BestSplitDominatesClassificationBootstrap,\n accumulator_sums, split_sums, _1, dominate_fraction_, _2);\n } else {\n LOG(FATAL) << \"Unknown dominate method \" << dominate_method_;\n }\n }\n\n std::vector finished_leaves;\n std::vector stale;\n mutex m;\n \/\/ Require at least 100 leaves per thread. I guess that's about 800 cost\n \/\/ per unit. This isn't well defined.\n const int64 costPerUnit = 800;\n auto work = [¶ms, &finished_leaves, &stale, &m, num_leaves](int64 start,\n int64 end) {\n CHECK(start <= end);\n CHECK(end <= num_leaves);\n Evaluate(params, &m, static_cast(start), static_cast(end),\n &finished_leaves, &stale);\n };\n Shard(num_threads, worker_threads->workers, num_leaves, costPerUnit, work);\n\n \/\/ Copy to output.\n Tensor* output_finished = nullptr;\n TensorShape finished_shape;\n finished_shape.AddDim(finished_leaves.size());\n OP_REQUIRES_OK(context,\n context->allocate_output(0, finished_shape,\n &output_finished));\n auto out_finished = output_finished->unaligned_flat();\n std::copy(finished_leaves.begin(), finished_leaves.end(),\n out_finished.data());\n\n Tensor* output_stale = nullptr;\n TensorShape stale_shape;\n stale_shape.AddDim(stale.size());\n OP_REQUIRES_OK(context,\n context->allocate_output(1, stale_shape,\n &output_stale));\n auto out_stale = output_stale->unaligned_flat();\n std::copy(stale.begin(), stale.end(), out_stale.data());\n }\n\n private:\n bool regression_;\n int32 num_split_after_samples_;\n int32 min_split_samples_;\n float dominate_fraction_;\n string dominate_method_;\n int32 random_seed_;\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"FinishedNodes\").Device(DEVICE_CPU),\n FinishedNodes);\n\n} \/\/ namespace tensorflow\nChange default dominate_method to bootsrap. Change: 137959663\/\/ Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ =============================================================================\n\/\/ FinishedNodes returns a 1-D tensor listing the nodes that are finished\n\/\/ accumulating.\n#include \"tensorflow\/contrib\/tensor_forest\/core\/ops\/tree_utils.h\"\n\n#include \"tensorflow\/core\/framework\/op.h\"\n#include \"tensorflow\/core\/framework\/op_kernel.h\"\n#include \"tensorflow\/core\/framework\/shape_inference.h\"\n#include \"tensorflow\/core\/kernels\/bounds_check.h\"\n#include \"tensorflow\/core\/lib\/random\/simple_philox.h\"\n#include \"tensorflow\/core\/platform\/env.h\"\n#include \"tensorflow\/core\/platform\/mutex.h\"\n#include \"tensorflow\/core\/util\/work_sharder.h\"\n\nnamespace tensorflow {\n\nusing shape_inference::Dimension;\nusing shape_inference::InferenceContext;\nusing shape_inference::Shape;\n\nusing std::placeholders::_1;\nusing std::placeholders::_2;\n\nusing tensorforest::CheckTensorBounds;\nusing tensorforest::Sum;\nusing tensorforest::BestSplitDominatesClassificationBootstrap;\nusing tensorforest::BestSplitDominatesClassificationChebyshev;\nusing tensorforest::BestSplitDominatesClassificationHoeffding;\nusing tensorforest::BestSplitDominatesRegression;\n\nnamespace {\n\nstruct EvaluateParams {\n Tensor leaves;\n Tensor node_to_accumulator;\n Tensor accumulator_sums;\n Tensor birth_epochs;\n int current_epoch;\n int32 num_split_after_samples;\n int32 min_split_samples;\n bool need_random;\n int64 random_seed;\n std::function dominate_method;\n};\n\nvoid Evaluate(const EvaluateParams& params, mutex* mutex, int32 start,\n int32 end, std::vector* final_finished_leaves,\n std::vector* final_stale) {\n const auto leaves = params.leaves.unaligned_flat();\n const auto node_map = params.node_to_accumulator.unaligned_flat();\n const auto sums = params.accumulator_sums.tensor();\n const auto start_epochs = params.birth_epochs.unaligned_flat();\n\n const int32 num_accumulators =\n static_cast(params.accumulator_sums.shape().dim_size(0));\n\n std::vector finished_leaves;\n std::vector stale;\n\n std::unique_ptr simple_philox;\n random::PhiloxRandom rnd_gen(params.random_seed);\n\n if (params.need_random) {\n simple_philox.reset(new random::SimplePhilox(&rnd_gen));\n }\n\n for (int32 i = start; i < end; i++) {\n const int32 leaf = internal::SubtleMustCopy(leaves(i));\n if (leaf == -1) {\n continue;\n }\n if (!FastBoundsCheck(leaf, node_map.size())) {\n LOG(ERROR) << \"leaf \" << leaf << \" not in valid range.\";\n }\n const int32 accumulator = internal::SubtleMustCopy(node_map(leaf));\n if (accumulator < 0) {\n continue;\n }\n\n if (!FastBoundsCheck(accumulator, num_accumulators)) {\n LOG(ERROR) << \"accumulator \" << accumulator << \" not in valid range.\";\n }\n \/\/ The first column holds the number of samples seen.\n \/\/ For classification, this should be the sum of the other columns.\n int32 count = sums(accumulator, 0);\n\n if (params.current_epoch > start_epochs(leaf) + 1) {\n if (count >= params.min_split_samples) {\n finished_leaves.push_back(leaf);\n } else {\n stale.push_back(leaf);\n }\n continue;\n }\n\n if (count >= params.num_split_after_samples) {\n finished_leaves.push_back(leaf);\n continue;\n }\n\n if (count < params.min_split_samples) {\n continue;\n }\n\n bool finished = params.dominate_method(accumulator, simple_philox.get());\n if (finished) {\n finished_leaves.push_back(leaf);\n }\n }\n mutex_lock m(*mutex);\n final_finished_leaves->insert(final_finished_leaves->end(),\n finished_leaves.begin(), finished_leaves.end());\n final_stale->insert(final_stale->end(), stale.begin(), stale.end());\n}\n} \/\/ namespace\n\nREGISTER_OP(\"FinishedNodes\")\n .Attr(\"regression: bool = false\")\n .Attr(\"num_split_after_samples: int\")\n .Attr(\"min_split_samples: int\")\n .Attr(\"dominate_fraction: float = 0.99\")\n .Attr(\n \"dominate_method:\"\n \" {'none', 'hoeffding', 'bootstrap', 'chebyshev'} = 'bootstrap'\")\n .Attr(\"random_seed: int = 0\")\n .Input(\"leaves: int32\")\n .Input(\"node_to_accumulator: int32\")\n .Input(\"split_sums: float\")\n .Input(\"split_squares: float\")\n .Input(\"accumulator_sums: float\")\n .Input(\"accumulator_squares: float\")\n .Input(\"birth_epochs: int32\")\n .Input(\"current_epoch: int32\")\n .Output(\"finished: int32\")\n .Output(\"stale: int32\")\n .SetShapeFn([](InferenceContext* c) {\n c->set_output(0, c->Vector(InferenceContext::kUnknownDim));\n c->set_output(1, c->Vector(InferenceContext::kUnknownDim));\n return Status::OK();\n })\n .Doc(R\"doc(\nDetermines which of the given leaf nodes are done accumulating.\n\nleaves:= A 1-d int32 tensor. Lists the nodes that are currently leaves.\nnode_to_accumulator: If the i-th node is fertile, `node_to_accumulator[i]`\n is it's accumulator slot. Otherwise, `node_to_accumulator[i]` is -1.\nsplit_sums:= a 3-d tensor where `split_sums[a][s]` summarizes the\n training labels for examples that fall into the fertile node associated with\n accumulator slot s and have then taken the *left* branch of candidate split\n s. For a classification problem, `split_sums[a][s][c]` is the count of such\n examples with class c and for regression problems, `split_sums[a][s]` is the\n sum of the regression labels for such examples.\nsplit_squares: Same as split_sums, but it contains the sum of the\n squares of the regression labels. Only used for regression. For\n classification problems, pass a dummy tensor into this.\naccumulator_sums: For classification, `accumulator_sums[a][c]` records how\n many training examples have class c and have ended up in the fertile node\n associated with accumulator slot a. It has the total sum in entry 0 for\n convenience. For regression, it is the same except it contains the sum\n of the input labels that have been seen, and entry 0 contains the number\n of training examples that have been seen.\naccumulator_squares: Same as accumulator_sums, but it contains the sum of the\n squares of the regression labels. Only used for regression. For\n classification problems, pass a dummy tensor into this.\nbirth_epochs:= A 1-d int32 tensor. `birth_epochs[i]` contains the epoch\n the i-th node was created in.\ncurrent_epoch:= A 1-d int32 tensor with shape (1). `current_epoch[0]`\n stores the current epoch number.\nfinished:= A 1-d int32 tensor containing the indices of the finished nodes.\n Nodes are finished if they have received at least num_split_after_samples\n samples, or if they have received min_split_samples and the best scoring\n split is sufficiently greater than the next best split.\nstale:= A 1-d int32 tensor containing the fertile nodes that were created two\n or more epochs ago.\n\n)doc\");\n\nclass FinishedNodes : public OpKernel {\n public:\n explicit FinishedNodes(OpKernelConstruction* context)\n : OpKernel(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\n \"regression\", ®ression_));\n OP_REQUIRES_OK(context, context->GetAttr(\n \"num_split_after_samples\", &num_split_after_samples_));\n OP_REQUIRES_OK(context, context->GetAttr(\n \"min_split_samples\", &min_split_samples_));\n OP_REQUIRES_OK(context, context->GetAttr(\n \"dominate_fraction\", &dominate_fraction_));\n OP_REQUIRES_OK(context,\n context->GetAttr(\"dominate_method\", &dominate_method_));\n OP_REQUIRES_OK(context, context->GetAttr(\"random_seed\", &random_seed_));\n }\n\n void Compute(OpKernelContext* context) override {\n const Tensor& leaf_tensor = context->input(0);\n const Tensor& node_to_accumulator = context->input(1);\n const Tensor& split_sums = context->input(2);\n const Tensor& split_squares = context->input(3);\n const Tensor& accumulator_sums = context->input(4);\n const Tensor& accumulator_squares = context->input(5);\n const Tensor& birth_epochs = context->input(6);\n const Tensor& current_epoch = context->input(7);\n\n OP_REQUIRES(context, leaf_tensor.shape().dims() == 1,\n errors::InvalidArgument(\n \"leaf_tensor should be one-dimensional\"));\n OP_REQUIRES(context, node_to_accumulator.shape().dims() == 1,\n errors::InvalidArgument(\n \"node_to_accumulator should be one-dimensional\"));\n OP_REQUIRES(context, split_sums.shape().dims() == 3,\n errors::InvalidArgument(\n \"split_sums should be three-dimensional\"));\n OP_REQUIRES(context, accumulator_sums.shape().dims() == 2,\n errors::InvalidArgument(\n \"accumulator_sums should be two-dimensional\"));\n OP_REQUIRES(context, birth_epochs.shape().dims() == 1,\n errors::InvalidArgument(\n \"birth_epochs should be one-dimensional\"));\n OP_REQUIRES(\n context,\n birth_epochs.shape().dim_size(0) ==\n node_to_accumulator.shape().dim_size(0),\n errors::InvalidArgument(\n \"birth_epochs and node_to_accumulator should be the same size.\"));\n\n \/\/ Check tensor bounds.\n if (!CheckTensorBounds(context, leaf_tensor)) return;\n if (!CheckTensorBounds(context, node_to_accumulator)) return;\n if (!CheckTensorBounds(context, split_sums)) return;\n if (!CheckTensorBounds(context, split_squares)) return;\n if (!CheckTensorBounds(context, accumulator_sums)) return;\n if (!CheckTensorBounds(context, accumulator_squares)) return;\n if (!CheckTensorBounds(context, birth_epochs)) return;\n if (!CheckTensorBounds(context, current_epoch)) return;\n\n const int32 epoch = current_epoch.unaligned_flat()(0);\n\n const int32 num_leaves = static_cast(\n leaf_tensor.shape().dim_size(0));\n\n auto worker_threads = context->device()->tensorflow_cpu_worker_threads();\n int num_threads = worker_threads->num_threads;\n\n EvaluateParams params;\n params.leaves = leaf_tensor;\n params.node_to_accumulator = node_to_accumulator;\n params.accumulator_sums = accumulator_sums;\n params.birth_epochs = birth_epochs;\n params.current_epoch = epoch;\n params.min_split_samples = min_split_samples_;\n params.num_split_after_samples = num_split_after_samples_;\n params.need_random = false;\n\n if (regression_) {\n params.dominate_method =\n std::bind(&BestSplitDominatesRegression, accumulator_sums,\n accumulator_squares, split_sums, split_squares, _1);\n } else {\n if (dominate_method_ == \"none\") {\n params.dominate_method = [](int, random::SimplePhilox*) {\n return false;\n };\n } else if (dominate_method_ == \"hoeffding\") {\n params.dominate_method =\n std::bind(&BestSplitDominatesClassificationHoeffding,\n accumulator_sums, split_sums, _1, dominate_fraction_);\n } else if (dominate_method_ == \"chebyshev\") {\n params.dominate_method =\n std::bind(&BestSplitDominatesClassificationChebyshev,\n accumulator_sums, split_sums, _1, dominate_fraction_);\n } else if (dominate_method_ == \"bootstrap\") {\n params.need_random = true;\n\n params.random_seed = random_seed_;\n if (params.random_seed == 0) {\n params.random_seed = static_cast(Env::Default()->NowMicros());\n }\n\n params.dominate_method =\n std::bind(&BestSplitDominatesClassificationBootstrap,\n accumulator_sums, split_sums, _1, dominate_fraction_, _2);\n } else {\n LOG(FATAL) << \"Unknown dominate method \" << dominate_method_;\n }\n }\n\n std::vector finished_leaves;\n std::vector stale;\n mutex m;\n \/\/ Require at least 100 leaves per thread. I guess that's about 800 cost\n \/\/ per unit. This isn't well defined.\n const int64 costPerUnit = 800;\n auto work = [¶ms, &finished_leaves, &stale, &m, num_leaves](int64 start,\n int64 end) {\n CHECK(start <= end);\n CHECK(end <= num_leaves);\n Evaluate(params, &m, static_cast(start), static_cast(end),\n &finished_leaves, &stale);\n };\n Shard(num_threads, worker_threads->workers, num_leaves, costPerUnit, work);\n\n \/\/ Copy to output.\n Tensor* output_finished = nullptr;\n TensorShape finished_shape;\n finished_shape.AddDim(finished_leaves.size());\n OP_REQUIRES_OK(context,\n context->allocate_output(0, finished_shape,\n &output_finished));\n auto out_finished = output_finished->unaligned_flat();\n std::copy(finished_leaves.begin(), finished_leaves.end(),\n out_finished.data());\n\n Tensor* output_stale = nullptr;\n TensorShape stale_shape;\n stale_shape.AddDim(stale.size());\n OP_REQUIRES_OK(context,\n context->allocate_output(1, stale_shape,\n &output_stale));\n auto out_stale = output_stale->unaligned_flat();\n std::copy(stale.begin(), stale.end(), out_stale.data());\n }\n\n private:\n bool regression_;\n int32 num_split_after_samples_;\n int32 min_split_samples_;\n float dominate_fraction_;\n string dominate_method_;\n int32 random_seed_;\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"FinishedNodes\").Device(DEVICE_CPU),\n FinishedNodes);\n\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/platform_thread.h\"\n\n#include \n#include \n#include \n\n#if defined(OS_MACOSX)\n#include \n#include \n#include \n#endif\n\n#if defined(OS_LINUX)\n#include \n#include \n#include \n#endif\n\n#include \"base\/logging.h\"\n#include \"base\/safe_strerror_posix.h\"\n\n#if defined(OS_MACOSX)\nnamespace base {\nvoid InitThreading();\n} \/\/ namespace base\n#endif\n\nstatic void* ThreadFunc(void* closure) {\n PlatformThread::Delegate* delegate =\n static_cast(closure);\n delegate->ThreadMain();\n return NULL;\n}\n\n\/\/ static\nPlatformThreadId PlatformThread::CurrentId() {\n \/\/ Pthreads doesn't have the concept of a thread ID, so we have to reach down\n \/\/ into the kernel.\n#if defined(OS_MACOSX)\n return mach_thread_self();\n#elif defined(OS_LINUX)\n return syscall(__NR_gettid);\n#elif defined(OS_FREEBSD)\n \/\/ TODO(BSD): find a better thread ID\n return reinterpret_cast(pthread_self());\n#endif\n}\n\n\/\/ static\nvoid PlatformThread::YieldCurrentThread() {\n sched_yield();\n}\n\n\/\/ static\nvoid PlatformThread::Sleep(int duration_ms) {\n struct timespec sleep_time, remaining;\n\n \/\/ Contains the portion of duration_ms >= 1 sec.\n sleep_time.tv_sec = duration_ms \/ 1000;\n duration_ms -= sleep_time.tv_sec * 1000;\n\n \/\/ Contains the portion of duration_ms < 1 sec.\n sleep_time.tv_nsec = duration_ms * 1000 * 1000; \/\/ nanoseconds.\n\n while (nanosleep(&sleep_time, &remaining) == -1 && errno == EINTR)\n sleep_time = remaining;\n}\n\n\/\/ Linux SetName is currently disabled, as we need to distinguish between\n\/\/ helper threads (where it's ok to make this call) and the main thread\n\/\/ (where making this call renames our process, causing tools like killall\n\/\/ to stop working).\n#if 0 && defined(OS_LINUX)\n\/\/ static\nvoid PlatformThread::SetName(const char* name) {\n \/\/ http:\/\/0pointer.de\/blog\/projects\/name-your-threads.html\n\n \/\/ glibc recently added support for pthread_setname_np, but it's not\n \/\/ commonly available yet. So test for it at runtime.\n int (*dynamic_pthread_setname_np)(pthread_t, const char*);\n *reinterpret_cast(&dynamic_pthread_setname_np) =\n dlsym(RTLD_DEFAULT, \"pthread_setname_np\");\n\n if (dynamic_pthread_setname_np) {\n \/\/ This limit comes from glibc, which gets it from the kernel\n \/\/ (TASK_COMM_LEN).\n const int kMaxNameLength = 15;\n std::string shortened_name = std::string(name).substr(0, kMaxNameLength);\n int err = dynamic_pthread_setname_np(pthread_self(),\n shortened_name.c_str());\n if (err < 0)\n LOG(ERROR) << \"pthread_setname_np: \" << safe_strerror(err);\n } else {\n \/\/ Implementing this function without glibc is simple enough. (We\n \/\/ don't do the name length clipping as above because it will be\n \/\/ truncated by the callee (see TASK_COMM_LEN above).)\n int err = prctl(PR_SET_NAME, name);\n if (err < 0)\n PLOG(ERROR) << \"prctl(PR_SET_NAME)\";\n }\n}\n#elif defined(OS_MACOSX)\n\/\/ Mac is implemented in platform_thread_mac.mm.\n#else\n\/\/ static\nvoid PlatformThread::SetName(const char* name) {\n \/\/ Leave it unimplemented.\n\n \/\/ (This should be relatively simple to implement for the BSDs; I\n \/\/ just don't have one handy to test the code on.)\n}\n#endif \/\/ defined(OS_LINUX)\n\nnamespace {\n\nbool CreateThread(size_t stack_size, bool joinable,\n PlatformThread::Delegate* delegate,\n PlatformThreadHandle* thread_handle) {\n#if defined(OS_MACOSX)\n base::InitThreading();\n#endif \/\/ OS_MACOSX\n\n bool success = false;\n pthread_attr_t attributes;\n pthread_attr_init(&attributes);\n\n \/\/ Pthreads are joinable by default, so only specify the detached attribute if\n \/\/ the thread should be non-joinable.\n if (!joinable) {\n pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED);\n }\n\n#if defined(OS_MACOSX)\n \/\/ The Mac OS X default for a pthread stack size is 512kB.\n \/\/ Libc-594.1.4\/pthreads\/pthread.c's pthread_attr_init uses\n \/\/ DEFAULT_STACK_SIZE for this purpose.\n \/\/\n \/\/ 512kB isn't quite generous enough for some deeply recursive threads that\n \/\/ otherwise request the default stack size by specifying 0. Here, adopt\n \/\/ glibc's behavior as on Linux, which is to use the current stack size\n \/\/ limit (ulimit -s) as the default stack size. See\n \/\/ glibc-2.11.1\/nptl\/nptl-init.c's __pthread_initialize_minimal_internal. To\n \/\/ avoid setting the limit below the Mac OS X default or the minimum usable\n \/\/ stack size, these values are also considered. If any of these values\n \/\/ can't be determined, or if stack size is unlimited (ulimit -s unlimited),\n \/\/ stack_size is left at 0 to get the system default.\n \/\/\n \/\/ Mac OS X normally only applies ulimit -s to the main thread stack. On\n \/\/ contemporary OS X and Linux systems alike, this value is generally 8MB\n \/\/ or in that neighborhood.\n if (stack_size == 0) {\n size_t default_stack_size;\n struct rlimit stack_rlimit;\n if (pthread_attr_getstacksize(&attributes, &default_stack_size) == 0 &&\n getrlimit(RLIMIT_STACK, &stack_rlimit) == 0 &&\n stack_rlimit.rlim_cur != RLIM_INFINITY) {\n stack_size = std::max(std::max(default_stack_size,\n static_cast(PTHREAD_STACK_MIN)),\n static_cast(stack_rlimit.rlim_cur));\n }\n }\n#endif \/\/ OS_MACOSX\n\n if (stack_size > 0)\n pthread_attr_setstacksize(&attributes, stack_size);\n\n success = !pthread_create(thread_handle, &attributes, ThreadFunc, delegate);\n\n pthread_attr_destroy(&attributes);\n return success;\n}\n\n} \/\/ anonymous namespace\n\n\/\/ static\nbool PlatformThread::Create(size_t stack_size, Delegate* delegate,\n PlatformThreadHandle* thread_handle) {\n return CreateThread(stack_size, true \/* joinable thread *\/,\n delegate, thread_handle);\n}\n\n\/\/ static\nbool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) {\n PlatformThreadHandle unused;\n\n bool result = CreateThread(stack_size, false \/* non-joinable thread *\/,\n delegate, &unused);\n return result;\n}\n\n\/\/ static\nvoid PlatformThread::Join(PlatformThreadHandle thread_handle) {\n pthread_join(thread_handle, NULL);\n}\nNaCl bringup of base.\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/platform_thread.h\"\n\n#include \n#include \n\n#if defined(OS_MACOSX)\n#include \n#include \n#include \n#endif\n\n#if defined(OS_LINUX)\n#include \n#include \n#include \n#include \n#endif\n\n#if defined(OS_NACL)\n#include \n#endif\n\n#include \"base\/logging.h\"\n#include \"base\/safe_strerror_posix.h\"\n\n#if defined(OS_MACOSX)\nnamespace base {\nvoid InitThreading();\n} \/\/ namespace base\n#endif\n\nstatic void* ThreadFunc(void* closure) {\n PlatformThread::Delegate* delegate =\n static_cast(closure);\n delegate->ThreadMain();\n return NULL;\n}\n\n\/\/ static\nPlatformThreadId PlatformThread::CurrentId() {\n \/\/ Pthreads doesn't have the concept of a thread ID, so we have to reach down\n \/\/ into the kernel.\n#if defined(OS_MACOSX)\n return mach_thread_self();\n#elif defined(OS_LINUX)\n return syscall(__NR_gettid);\n#elif defined(OS_FREEBSD)\n \/\/ TODO(BSD): find a better thread ID\n return reinterpret_cast(pthread_self());\n#elif defined(OS_NACL)\n return pthread_self();\n#endif\n}\n\n\/\/ static\nvoid PlatformThread::YieldCurrentThread() {\n sched_yield();\n}\n\n\/\/ static\nvoid PlatformThread::Sleep(int duration_ms) {\n struct timespec sleep_time, remaining;\n\n \/\/ Contains the portion of duration_ms >= 1 sec.\n sleep_time.tv_sec = duration_ms \/ 1000;\n duration_ms -= sleep_time.tv_sec * 1000;\n\n \/\/ Contains the portion of duration_ms < 1 sec.\n sleep_time.tv_nsec = duration_ms * 1000 * 1000; \/\/ nanoseconds.\n\n while (nanosleep(&sleep_time, &remaining) == -1 && errno == EINTR)\n sleep_time = remaining;\n}\n\n\/\/ Linux SetName is currently disabled, as we need to distinguish between\n\/\/ helper threads (where it's ok to make this call) and the main thread\n\/\/ (where making this call renames our process, causing tools like killall\n\/\/ to stop working).\n#if 0 && defined(OS_LINUX)\n\/\/ static\nvoid PlatformThread::SetName(const char* name) {\n \/\/ http:\/\/0pointer.de\/blog\/projects\/name-your-threads.html\n\n \/\/ glibc recently added support for pthread_setname_np, but it's not\n \/\/ commonly available yet. So test for it at runtime.\n int (*dynamic_pthread_setname_np)(pthread_t, const char*);\n *reinterpret_cast(&dynamic_pthread_setname_np) =\n dlsym(RTLD_DEFAULT, \"pthread_setname_np\");\n\n if (dynamic_pthread_setname_np) {\n \/\/ This limit comes from glibc, which gets it from the kernel\n \/\/ (TASK_COMM_LEN).\n const int kMaxNameLength = 15;\n std::string shortened_name = std::string(name).substr(0, kMaxNameLength);\n int err = dynamic_pthread_setname_np(pthread_self(),\n shortened_name.c_str());\n if (err < 0)\n LOG(ERROR) << \"pthread_setname_np: \" << safe_strerror(err);\n } else {\n \/\/ Implementing this function without glibc is simple enough. (We\n \/\/ don't do the name length clipping as above because it will be\n \/\/ truncated by the callee (see TASK_COMM_LEN above).)\n int err = prctl(PR_SET_NAME, name);\n if (err < 0)\n PLOG(ERROR) << \"prctl(PR_SET_NAME)\";\n }\n}\n#elif defined(OS_MACOSX)\n\/\/ Mac is implemented in platform_thread_mac.mm.\n#else\n\/\/ static\nvoid PlatformThread::SetName(const char* name) {\n \/\/ Leave it unimplemented.\n\n \/\/ (This should be relatively simple to implement for the BSDs; I\n \/\/ just don't have one handy to test the code on.)\n}\n#endif \/\/ defined(OS_LINUX)\n\nnamespace {\n\nbool CreateThread(size_t stack_size, bool joinable,\n PlatformThread::Delegate* delegate,\n PlatformThreadHandle* thread_handle) {\n#if defined(OS_MACOSX)\n base::InitThreading();\n#endif \/\/ OS_MACOSX\n\n bool success = false;\n pthread_attr_t attributes;\n pthread_attr_init(&attributes);\n\n \/\/ Pthreads are joinable by default, so only specify the detached attribute if\n \/\/ the thread should be non-joinable.\n if (!joinable) {\n pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED);\n }\n\n#if defined(OS_MACOSX)\n \/\/ The Mac OS X default for a pthread stack size is 512kB.\n \/\/ Libc-594.1.4\/pthreads\/pthread.c's pthread_attr_init uses\n \/\/ DEFAULT_STACK_SIZE for this purpose.\n \/\/\n \/\/ 512kB isn't quite generous enough for some deeply recursive threads that\n \/\/ otherwise request the default stack size by specifying 0. Here, adopt\n \/\/ glibc's behavior as on Linux, which is to use the current stack size\n \/\/ limit (ulimit -s) as the default stack size. See\n \/\/ glibc-2.11.1\/nptl\/nptl-init.c's __pthread_initialize_minimal_internal. To\n \/\/ avoid setting the limit below the Mac OS X default or the minimum usable\n \/\/ stack size, these values are also considered. If any of these values\n \/\/ can't be determined, or if stack size is unlimited (ulimit -s unlimited),\n \/\/ stack_size is left at 0 to get the system default.\n \/\/\n \/\/ Mac OS X normally only applies ulimit -s to the main thread stack. On\n \/\/ contemporary OS X and Linux systems alike, this value is generally 8MB\n \/\/ or in that neighborhood.\n if (stack_size == 0) {\n size_t default_stack_size;\n struct rlimit stack_rlimit;\n if (pthread_attr_getstacksize(&attributes, &default_stack_size) == 0 &&\n getrlimit(RLIMIT_STACK, &stack_rlimit) == 0 &&\n stack_rlimit.rlim_cur != RLIM_INFINITY) {\n stack_size = std::max(std::max(default_stack_size,\n static_cast(PTHREAD_STACK_MIN)),\n static_cast(stack_rlimit.rlim_cur));\n }\n }\n#endif \/\/ OS_MACOSX\n\n if (stack_size > 0)\n pthread_attr_setstacksize(&attributes, stack_size);\n\n success = !pthread_create(thread_handle, &attributes, ThreadFunc, delegate);\n\n pthread_attr_destroy(&attributes);\n return success;\n}\n\n} \/\/ anonymous namespace\n\n\/\/ static\nbool PlatformThread::Create(size_t stack_size, Delegate* delegate,\n PlatformThreadHandle* thread_handle) {\n return CreateThread(stack_size, true \/* joinable thread *\/,\n delegate, thread_handle);\n}\n\n\/\/ static\nbool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) {\n PlatformThreadHandle unused;\n\n bool result = CreateThread(stack_size, false \/* non-joinable thread *\/,\n delegate, &unused);\n return result;\n}\n\n\/\/ static\nvoid PlatformThread::Join(PlatformThreadHandle thread_handle) {\n pthread_join(thread_handle, NULL);\n}\n<|endoftext|>"} {"text":"Fix ProcessUtilTest.FDRemapping hang on x86_64 by counting open fds in child process nondestructively BUG=25270 TEST=base_unittests --gtest_filter=ProcessUtilTest.FDRemapping on x86_64 linux<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: sbjsmeth.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 14:22:32 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#ifndef _SB_SBJSMETH_HXX\n#define _SB_SBJSMETH_HXX\n\n#ifndef _SB_SBMETH_HXX\n#include \n#endif\n\n\/\/ Basic-Modul fuer JavaScript-Sourcen.\n\/\/ Alle Basic-spezifischen Methoden muessen virtuell ueberladen und deaktiviert\n\/\/ werden. Die Unterscheidung von normalen Modulen erfolgt uebr RTTI.\n\nclass SbJScriptMethod : public SbMethod\n{\npublic:\n SbJScriptMethod( const String&, SbxDataType, SbModule* );\n virtual ~SbJScriptMethod();\n\n SBX_DECL_PERSIST_NODATA(SBXCR_SBX,SBXID_JSCRIPTMETH,2);\n TYPEINFO();\n};\n\n#ifndef __SB_SBJSCRIPTMETHODREF_HXX\n#define __SB_SBJSCRIPTMETHODREF_HXX\nSV_DECL_IMPL_REF(SbJScriptMethod)\n#endif\n\n#endif\nINTEGRATION: CWS changefileheader (1.5.88); FILE MERGED 2008\/04\/01 10:48:42 thb 1.5.88.2: #i85898# Stripping all external header guards 2008\/03\/28 16:07:28 rt 1.5.88.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: sbjsmeth.hxx,v $\n * $Revision: 1.6 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\n#ifndef _SB_SBJSMETH_HXX\n#define _SB_SBJSMETH_HXX\n\n#include \n\n\/\/ Basic-Modul fuer JavaScript-Sourcen.\n\/\/ Alle Basic-spezifischen Methoden muessen virtuell ueberladen und deaktiviert\n\/\/ werden. Die Unterscheidung von normalen Modulen erfolgt uebr RTTI.\n\nclass SbJScriptMethod : public SbMethod\n{\npublic:\n SbJScriptMethod( const String&, SbxDataType, SbModule* );\n virtual ~SbJScriptMethod();\n\n SBX_DECL_PERSIST_NODATA(SBXCR_SBX,SBXID_JSCRIPTMETH,2);\n TYPEINFO();\n};\n\n#ifndef __SB_SBJSCRIPTMETHODREF_HXX\n#define __SB_SBJSCRIPTMETHODREF_HXX\nSV_DECL_IMPL_REF(SbJScriptMethod)\n#endif\n\n#endif\n<|endoftext|>"} {"text":"\/\/ RUN: %clang_cc1 -std=c++11 -fsyntax-only -fdiagnostics-show-option -verify %s\n\n\/\/ C++98 [basic.lookup.classref]p1:\n\/\/ In a class member access expression (5.2.5), if the . or -> token is\n\/\/ immediately followed by an identifier followed by a <, the identifier must\n\/\/ be looked up to determine whether the < is the beginning of a template\n\/\/ argument list (14.2) or a less-than operator. The identifier is first\n\/\/ looked up in the class of the object expression. If the identifier is not\n\/\/ found, it is then looked up in the context of the entire postfix-expression\n\/\/ and shall name a class or function template. If the lookup in the class of\n\/\/ the object expression finds a template, the name is also looked up in the\n\/\/ context of the entire postfix-expression and\n\/\/ -- if the name is not found, the name found in the class of the object\n\/\/ expression is used, otherwise\n\/\/ -- if the name is found in the context of the entire postfix-expression\n\/\/ and does not name a class template, the name found in the class of the\n\/\/ object expression is used, otherwise\n\/\/ -- if the name found is a class template, it must refer to the same\n\/\/ entity as the one found in the class of the object expression,\n\/\/ otherwise the program is ill-formed.\n\n\/\/ From PR 7247\ntemplate\nstruct set{};\nstruct Value {\n template\n void set(T value) {}\n\n void resolves_to_same() {\n Value v;\n v.set(3.2);\n }\n};\nvoid resolves_to_different() {\n {\n Value v;\n \/\/ The fact that the next line is a warning rather than an error is an\n \/\/ extension.\n v.set(3.2);\n }\n {\n int set; \/\/ Non-template.\n Value v;\n v.set(3.2);\n }\n}\n\nnamespace rdar9915664 {\n struct A {\n template void a();\n };\n\n struct B : A { };\n\n struct C : A { };\n\n struct D : B, C {\n A &getA() { return static_cast(*this); }\n\n void test_a() {\n getA().a();\n }\n };\n}\n\nnamespace PR11856 {\n template T end(T);\n\n template \n void Foo() {\n T it1;\n if (it1->end < it1->end) {\n }\n }\n\n template T *end(T*);\n\n class X { };\n template \n void Foo2() {\n T it1;\n if (it1->end < it1->end) {\n }\n\n X *x;\n if (x->end < 7) { \/\/ expected-error{{no member named 'end' in 'PR11856::X'}}\n }\n }\n}\nWe don't need a lengthy quote from the wrong standard.\/\/ RUN: %clang_cc1 -std=c++11 -fsyntax-only -fdiagnostics-show-option -verify %s\n\ntemplate\nstruct set{};\nstruct Value {\n template\n void set(T value) {}\n\n void resolves_to_same() {\n Value v;\n v.set(3.2);\n }\n};\nvoid resolves_to_different() {\n {\n Value v;\n \/\/ The fact that the next line is a warning rather than an error is an\n \/\/ extension.\n v.set(3.2);\n }\n {\n int set; \/\/ Non-template.\n Value v;\n v.set(3.2);\n }\n}\n\nnamespace rdar9915664 {\n struct A {\n template void a();\n };\n\n struct B : A { };\n\n struct C : A { };\n\n struct D : B, C {\n A &getA() { return static_cast(*this); }\n\n void test_a() {\n getA().a();\n }\n };\n}\n\nnamespace PR11856 {\n template T end(T);\n\n template \n void Foo() {\n T it1;\n if (it1->end < it1->end) {\n }\n }\n\n template T *end(T*);\n\n class X { };\n template \n void Foo2() {\n T it1;\n if (it1->end < it1->end) {\n }\n\n X *x;\n if (x->end < 7) { \/\/ expected-error{{no member named 'end' in 'PR11856::X'}}\n }\n }\n}\n<|endoftext|>"} {"text":"IMPALA-1735: ExpandRmReservation only check parent pools with limit<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nclass BenchCallback :public dariadb::storage::Cursor::Callback {\npublic:\n\tvoid call(dariadb::storage::Chunk_Ptr &) {\n\t\tcount++;\n\t}\n\tsize_t count;\n};\n\nconst std::string storagePath = \"benchStorage\/\";\nconst size_t chunks_count = 1024;\nconst size_t chunks_size = 1024;\n\nint main(int argc, char *argv[]) {\n\t(void)argc;\n\t(void)argv;\n\t{\n\t\tdariadb::Time t = 0;\n\n\t\tdariadb::Meas first;\n\t\tfirst.id = 1;\n\t\tfirst.time = t;\n\n\t\tdariadb::storage::Chunk_Ptr ch = std::make_shared(chunks_size, first);\n\t\tfor (int i = 0;; i++, t++) {\n\t\t\tfirst.flag = dariadb::Flag(i);\n\t\t\tfirst.time = t;\n\t\t\tfirst.value = dariadb::Value(i);\n\t\t\tif (!ch->append(first)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (dariadb::utils::fs::path_exists(storagePath)) {\n\t\t\tdariadb::utils::fs::rm(storagePath);\n\t\t}\n dariadb::storage::PageManager::start(dariadb::storage::PageManager::Params(storagePath, dariadb::storage::MODE::SINGLE, chunks_count, chunks_size));\n\n\t\tauto start = clock();\n\n\t\tfor (size_t i = 0; i < chunks_count; ++i) {\n dariadb::storage::PageManager::instance()->append(ch);\n\t\t\tch->maxTime += dariadb::Time(chunks_size);\n\t\t\tch->minTime += dariadb::Time(chunks_size);\n\t\t}\n\n\t\tauto elapsed = ((float)clock() - start) \/ CLOCKS_PER_SEC;\n\t\tstd::cout << \"insert : \" << elapsed << std::endl;\n\n\t\tBenchCallback*clbk = new BenchCallback;\n\t\tstart = clock();\n\n\t\tdariadb::Time to_t = chunks_size;\n\t\tfor (size_t i = 1; i < chunks_count; i++) {\n\t\t\tauto cursor = dariadb::storage::PageManager::instance()->chunksByIterval(dariadb::IdArray{}, 0, to_t, 0);\n\t\t\tcursor->readAll(clbk);\n\t\t\tcursor = nullptr;\n\t\t\tto_t *= 2;\n\t\t}\n\n\t\telapsed = ((float)clock() - start) \/ CLOCKS_PER_SEC;\n\t\tstd::cout << \"readAll : \" << elapsed << std::endl;\n\t\t\n\t\tdelete clbk;\n\t\tdariadb::storage::PageManager::stop();\n\t\tif (dariadb::utils::fs::path_exists(storagePath)) {\n\t\t\tdariadb::utils::fs::rm(storagePath);\n\t\t}\n\t\tch = nullptr;\n\t}\n}\npage_benchmark: read benchmarks.#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nclass BenchCallback :public dariadb::storage::Cursor::Callback {\npublic:\n void call(dariadb::storage::Chunk_Ptr &) {\n count++;\n }\n size_t count;\n};\n\nconst std::string storagePath = \"benchStorage\/\";\nconst size_t chunks_count = 1024;\nconst size_t chunks_size = 1024;\n\nint main(int argc, char *argv[]) {\n (void)argc;\n (void)argv;\n {\n dariadb::Time t = 0;\n\n dariadb::Meas first;\n first.id = 1;\n first.time = t;\n\n dariadb::storage::Chunk_Ptr ch = std::make_shared(chunks_size, first);\n for (int i = 0;; i++, t++) {\n first.flag = dariadb::Flag(i);\n first.time = t;\n first.value = dariadb::Value(i);\n if (!ch->append(first)) {\n break;\n }\n }\n\n if (dariadb::utils::fs::path_exists(storagePath)) {\n dariadb::utils::fs::rm(storagePath);\n }\n dariadb::storage::PageManager::start(dariadb::storage::PageManager::Params(storagePath, dariadb::storage::MODE::SINGLE, chunks_count, chunks_size));\n\n auto start = clock();\n\n for (size_t i = 0; i < chunks_count; ++i) {\n dariadb::storage::PageManager::instance()->append(ch);\n ch->maxTime += dariadb::Time(chunks_size);\n ch->minTime += dariadb::Time(chunks_size);\n }\n\n auto elapsed = ((float)clock() - start) \/ CLOCKS_PER_SEC;\n std::cout << \"insert : \" << elapsed << std::endl;\n dariadb::storage::PageManager::instance()->flush();\n std::random_device r;\n std::default_random_engine e1(r());\n std::uniform_int_distribution uniform_dist(dariadb::storage::PageManager::instance()->minTime(), dariadb::storage::PageManager::instance()->maxTime());\n\n BenchCallback*clbk = new BenchCallback;\n\n start = clock();\n\n for (size_t i = 0; i < size_t(100); i++) {\n auto time_point1 = uniform_dist(e1);\n auto time_point2 = uniform_dist(e1);\n auto from=std::min(time_point1,time_point2);\n auto to=std::max(time_point1,time_point2);\n auto cursor = dariadb::storage::PageManager::instance()->chunksByIterval(dariadb::IdArray{}, from, to, 0);\n cursor->readAll(clbk);\n cursor = nullptr;\n }\n\n elapsed = ((float)clock() - start) \/ CLOCKS_PER_SEC;\n std::cout << \"interval: \" << elapsed << std::endl;\n\n start = clock();\n\n for (size_t i = 0; i < size_t(100); i++) {\n auto time_point = uniform_dist(e1);\n dariadb::storage::PageManager::instance()->chunksBeforeTimePoint(dariadb::IdArray{}, 0,time_point);\n }\n\n elapsed = ((float)clock() - start) \/ CLOCKS_PER_SEC;\n std::cout << \"timePoint: \" << elapsed << std::endl;\n\n delete clbk;\n\n dariadb::storage::PageManager::stop();\n if (dariadb::utils::fs::path_exists(storagePath)) {\n dariadb::utils::fs::rm(storagePath);\n }\n ch = nullptr;\n }\n}\n<|endoftext|>"} {"text":"\/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n Header: FGTrimAxis.cpp\n Author: Tony Peden\n Date started: 7\/3\/00\n \n --------- Copyright (C) 1999 Anthony K. Peden (apeden@earthlink.net) ---------\n \n This program is free software; you can redistribute it and\/or modify it under\n the terms of the GNU General Public License as published by the Free Software\n Foundation; either version 2 of the License, or (at your option) any later\n version.\n \n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n details.\n \n You should have received a copy of the GNU General Public License along with\n this program; if not, write to the Free Software Foundation, Inc., 59 Temple\n Place - Suite 330, Boston, MA 02111-1307, USA.\n \n Further information about the GNU General Public License can also be found on\n the world wide web at http:\/\/www.gnu.org.\n \n \n HISTORY\n--------------------------------------------------------------------------------\n7\/3\/00 TP Created\n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nINCLUDES\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*\/\n\n#include \n#include \n\n#include \"FGFDMExec.h\"\n#include \"FGAtmosphere.h\"\n#include \"FGInitialCondition.h\"\n#include \"FGTrimAxis.h\"\n#include \"FGAircraft.h\"\n\nstatic const char *IdSrc = \"$Header: \/cvsroot\/jsbsim\/JSBSim\/Attic\/FGTrimAxis.cpp,v 1.10 2000\/11\/01 11:38:09 jsb Exp $\";\nstatic const char *IdHdr = ID_TRIMAXIS;\n\n\/*****************************************************************************\/\n\nFGTrimAxis::FGTrimAxis(FGFDMExec* fdex, FGInitialCondition* ic, Accel acc,\n Control ctrl, float ff) {\n\n fdmex=fdex;\n fgic=ic;\n accel=acc;\n control=ctrl;\n tolerance=ff;\n solver_eps=tolerance;\n max_iterations=10;\n control_value=0;\n its_to_stable_value=0;\n total_iterations=0;\n total_stability_iterations=0;\n accel_convert=1.0;\n control_convert=1.0;\n accel_value=0;\n switch(control) {\n case tThrottle:\n control_min=0;\n control_max=1;\n control_value=0.5;\n break;\n case tBeta:\n control_min=-30*DEGTORAD;\n control_max=30*DEGTORAD;\n control_convert=RADTODEG;\n break;\n case tAlpha:\n control_min=fdmex->GetAircraft()->GetAlphaCLMin();\n control_max=fdmex->GetAircraft()->GetAlphaCLMax();\n if(control_max <= control_min) {\n control_max=20*DEGTORAD;\n control_min=-5*DEGTORAD;\n }\n control_value= (control_min+control_max)\/2;\n control_convert=RADTODEG;\n solver_eps=tolerance\/100;\n break;\n case tPitchTrim:\n case tElevator:\n case tRollTrim:\n case tAileron:\n case tYawTrim:\n case tRudder:\n control_min=-1;\n control_max=1;\n accel_convert=RADTODEG;\n solver_eps=tolerance\/100;\n break;\n case tAltAGL:\n control_min=0;\n control_max=30;\n control_value=fdmex->GetPosition()->GetDistanceAGL();\n solver_eps=tolerance\/100;\n break;\n case tTheta:\n control_min=fdmex->GetRotation()->Gettht() - 5*DEGTORAD;\n control_max=fdmex->GetRotation()->Gettht() + 5*DEGTORAD;\n accel_convert=RADTODEG;\n break;\n case tPhi:\n control_min=fdmex->GetRotation()->Getphi() - 5*DEGTORAD;\n control_max=fdmex->GetRotation()->Getphi() + 5*DEGTORAD;\n accel_convert=RADTODEG;\n break;\n case tGamma:\n solver_eps=tolerance\/100;\n control_min=-80*DEGTORAD;\n control_max=80*DEGTORAD;\n control_convert=RADTODEG;\n break;\n }\n \n}\n\n\/*****************************************************************************\/\n\nFGTrimAxis::~FGTrimAxis() {}\n\n\/*****************************************************************************\/\n\nvoid FGTrimAxis::getAccel(void) {\n switch(accel) {\n case tUdot: accel_value=fdmex -> GetTranslation()->GetUVWdot()(1); break;\n case tVdot: accel_value=fdmex -> GetTranslation()->GetUVWdot()(2); break;\n case tWdot: accel_value=fdmex -> GetTranslation()->GetUVWdot()(3); break;\n case tQdot: accel_value=fdmex -> GetRotation()->GetPQRdot()(2);break;\n case tPdot: accel_value=fdmex -> GetRotation()->GetPQRdot()(1); break;\n case tRdot: accel_value=fdmex -> GetRotation()->GetPQRdot()(3); break;\n }\n}\n\n\/*****************************************************************************\/\n\n\/\/Accels are not settable\n\nvoid FGTrimAxis::getControl(void) {\n switch(control) {\n case tThrottle: control_value=fdmex->GetFCS()->GetThrottleCmd(0); break;\n case tBeta: control_value=fdmex->GetTranslation()->Getalpha(); break;\n case tAlpha: control_value=fdmex->GetTranslation()->Getbeta(); break;\n case tPitchTrim: control_value=fdmex->GetFCS() -> GetPitchTrimCmd(); break;\n case tElevator: control_value=fdmex->GetFCS() -> GetDeCmd(); break;\n case tRollTrim:\n case tAileron: control_value=fdmex->GetFCS() -> GetDaCmd(); break;\n case tYawTrim:\n case tRudder: control_value=fdmex->GetFCS() -> GetDrCmd(); break;\n case tAltAGL: control_value=fdmex->GetPosition()->GetDistanceAGL();break;\n case tTheta: control_value=fdmex->GetRotation()->Gettht(); break;\n case tPhi: control_value=fdmex->GetRotation()->Getphi(); break;\n case tGamma: control_value=fdmex->GetPosition()->GetGamma();break;\n }\n}\n\n\/*****************************************************************************\/\n\n\nvoid FGTrimAxis::setControl(void) {\n switch(control) {\n case tThrottle: setThrottlesPct(); break;\n case tBeta: fgic->SetBetaRadIC(control_value); break;\n case tAlpha: fgic->SetAlphaRadIC(control_value); break;\n case tPitchTrim: fdmex->GetFCS() -> SetPitchTrimCmd(control_value); break;\n case tElevator: fdmex-> GetFCS() -> SetDeCmd(control_value); break;\n case tRollTrim:\n case tAileron: fdmex-> GetFCS() -> SetDaCmd(control_value); break;\n case tYawTrim:\n case tRudder: fdmex-> GetFCS() -> SetDrCmd(control_value); break;\n case tAltAGL: fgic->SetAltitudeAGLFtIC(control_value); break;\n case tTheta: fgic->SetPitchAngleRadIC(control_value); break;\n case tPhi: fgic->SetRollAngleRadIC(control_value); break;\n case tGamma: fgic->SetFlightPathAngleRadIC(control_value); break;\n }\n}\n\n\n \n\n\n\/*****************************************************************************\/\n\n\/\/ the aircraft center of rotation is no longer the cg once the gear\n\/\/ contact the ground so the altitude needs to be changed when pitch \n\/\/ and roll angle are adjusted. Instead of attempting to calculate the \n\/\/ new center of rotation, pick a gear unit as a reference and use its\n\/\/ location vector to calculate the new height change. i.e. new altitude =\n\/\/ earth z component of that vector (which is in body axes ) \nvoid FGTrimAxis::SetThetaOnGround(float ff) {\n int center,i,ref;\n\n \/\/ favor an off-center unit so that the same one can be used for both\n \/\/ pitch and roll. An on-center unit is used (for pitch)if that's all \n \/\/ that's in contact with the ground.\n i=0; ref=-1; center=-1;\n while( (ref < 0) && (i < fdmex->GetAircraft()->GetNumGearUnits()) ) {\n if(fdmex->GetAircraft()->GetGearUnit(i)->GetWOW()) {\n if(fabs(fdmex->GetAircraft()->GetGearUnit(i)->GetBodyLocation()(2)) > 0.01)\n ref=i;\n else\n center=i;\n } \n i++; \n }\n if((ref < 0) && (center >= 0)) {\n ref=center;\n }\n cout << \"SetThetaOnGround ref gear: \" << ref << endl;\n if(ref >= 0) {\n float sp=fdmex->GetRotation()->GetSinphi();\n float cp=fdmex->GetRotation()->GetCosphi();\n float lx=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(1);\n float ly=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(2);\n float lz=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(3);\n float hagl = -1*lx*sin(ff) +\n ly*sp*cos(ff) +\n lz*cp*cos(ff);\n \n fgic->SetAltitudeAGLFtIC(hagl);\n cout << \"SetThetaOnGround new alt: \" << hagl << endl;\n } \n fgic->SetPitchAngleRadIC(ff); \n cout << \"SetThetaOnGround new theta: \" << ff << endl; \n} \n\n\/*****************************************************************************\/\n\nbool FGTrimAxis::initTheta(void) {\n int i,N,iAft, iForward;\n float zAft,zForward,zDiff,theta;\n bool level; \n float saveAlt;\n \n saveAlt=fgic->GetAltitudeAGLFtIC();\n fgic->SetAltitudeAGLFtIC(100);\n \n \n N=fdmex->GetAircraft()->GetNumGearUnits();\n \n \/\/find the first wheel unit forward of the cg\n \/\/the list is short so a simple linear search is fine\n for( i=0; iGetAircraft()->GetGearUnit(i)->GetBodyLocation()(1) > 0 ) {\n iForward=i;\n break;\n }\n }\n \/\/now find the first wheel unit aft of the cg\n for( i=0; iGetAircraft()->GetGearUnit(i)->GetBodyLocation()(1) < 0 ) {\n iAft=i;\n break;\n }\n }\n cout << \"iForward: \" << iForward << endl;\n cout << \"iAft: \" << iAft << endl; \n \t \n \/\/ now adjust theta till the wheels are the same distance from the ground\n zAft=fdmex->GetAircraft()->GetGearUnit(1)->GetLocalGear()(3);\n zForward=fdmex->GetAircraft()->GetGearUnit(0)->GetLocalGear()(3);\n zDiff = zForward - zAft;\n level=false;\n theta=fgic->GetPitchAngleDegIC(); \n while(!level && (i < 100)) {\n\ttheta+=2.0*zDiff;\n\tfgic->SetPitchAngleDegIC(theta); \n\tfdmex->RunIC(fgic);\n\tzAft=fdmex->GetAircraft()->GetGearUnit(1)->GetLocalGear()(3);\n zForward=fdmex->GetAircraft()->GetGearUnit(0)->GetLocalGear()(3);\n zDiff = zForward - zAft;\n\t\/\/cout << endl << theta << \" \" << zDiff << endl;\n\t\/\/cout << \"0: \" << fdmex->GetAircraft()->GetGearUnit(0)->GetLocalGear() << endl;\n\t\/\/cout << \"1: \" << fdmex->GetAircraft()->GetGearUnit(1)->GetLocalGear() << endl;\n\n\tif(fabs(zDiff ) < 0.1) \n\t level=true;\n\ti++; \n }\t \t \t\n \/\/cout << i << endl;\n cout << \"Initial Theta: \" << fdmex->GetRotation()->Gettht()*RADTODEG << endl;\n control_min=(theta+5)*DEGTORAD;\n control_max=(theta-5)*DEGTORAD;\n fgic->SetAltitudeAGLFtIC(saveAlt);\n if(i < 100) \n return true;\n else\n return false; \n} \n\n\/*****************************************************************************\/\n\nvoid FGTrimAxis::SetPhiOnGround(float ff) {\n int i,ref;\n\n i=0; ref=-1;\n \/\/must have an off-center unit here \n while( (ref < 0) && (i < fdmex->GetAircraft()->GetNumGearUnits()) ) {\n if( (fdmex->GetAircraft()->GetGearUnit(i)->GetWOW()) && \n (fabs(fdmex->GetAircraft()->GetGearUnit(i)->GetBodyLocation()(2)) > 0.01))\n ref=i;\n i++; \n }\n if(ref >= 0) {\n float st=fdmex->GetRotation()->GetSintht();\n float ct=fdmex->GetRotation()->GetCostht();\n float lx=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(1);\n float ly=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(2);\n float lz=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(3);\n float hagl = -1*lx*st +\n ly*sin(ff)*ct +\n lz*cos(ff)*ct;\n \n fgic->SetAltitudeAGLFtIC(hagl);\n } \n fgic->SetRollAngleRadIC(ff);\n \n} \n\n\/*****************************************************************************\/\n\nvoid FGTrimAxis::Run(void) {\n\n float last_accel_value;\n int i;\n setControl();\n \/\/cout << \"FGTrimAxis::Run: \" << control_value << endl;\n i=0;\n bool stable=false;\n while(!stable) {\n i++;\n last_accel_value=accel_value;\n fdmex->RunIC(fgic);\n getAccel();\n if(i > 1) {\n if((fabs(last_accel_value - accel_value) < tolerance) || (i >= 100) )\n stable=true;\n }\n }\n\n its_to_stable_value=i;\n total_stability_iterations+=its_to_stable_value;\n total_iterations++;\n}\n\n\/*****************************************************************************\/\n\nvoid FGTrimAxis::setThrottlesPct(void) {\n float tMin,tMax;\n for(unsigned i=0;iGetAircraft()->GetNumEngines();i++) {\n tMin=fdmex->GetAircraft()->GetEngine(i)->GetThrottleMin();\n tMax=fdmex->GetAircraft()->GetEngine(i)->GetThrottleMax();\n \/\/cout << \"setThrottlespct: \" << i << \", \" << control_min << \", \" << control_max << \", \" << control_value;\n fdmex -> GetFCS() -> SetThrottleCmd(i,tMin+control_value*(tMax-tMin));\n }\n}\n\n\n\/*****************************************************************************\/\n\n\nvoid FGTrimAxis::AxisReport(void) {\n \n char out[80];\n sprintf(out,\" %20s: %6.2f %5s: %9.2e Tolerance: %3.0e\\n\",\n GetControlName().c_str(), GetControl()*control_convert,\n GetAccelName().c_str(), GetAccel(), GetTolerance()); \n cout << out;\n\n}\n\n\n\/*****************************************************************************\/\n\nfloat FGTrimAxis::GetAvgStability( void ) {\n if(total_iterations > 0) {\n return float(total_stability_iterations)\/float(total_iterations);\n }\n return 0;\n}\n\nAKP Cleanup\/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n Header: FGTrimAxis.cpp\n Author: Tony Peden\n Date started: 7\/3\/00\n \n --------- Copyright (C) 1999 Anthony K. Peden (apeden@earthlink.net) ---------\n \n This program is free software; you can redistribute it and\/or modify it under\n the terms of the GNU General Public License as published by the Free Software\n Foundation; either version 2 of the License, or (at your option) any later\n version.\n \n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n details.\n \n You should have received a copy of the GNU General Public License along with\n this program; if not, write to the Free Software Foundation, Inc., 59 Temple\n Place - Suite 330, Boston, MA 02111-1307, USA.\n \n Further information about the GNU General Public License can also be found on\n the world wide web at http:\/\/www.gnu.org.\n \n \n HISTORY\n--------------------------------------------------------------------------------\n7\/3\/00 TP Created\n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nINCLUDES\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*\/\n\n#include \n#include \n\n#include \"FGFDMExec.h\"\n#include \"FGAtmosphere.h\"\n#include \"FGInitialCondition.h\"\n#include \"FGTrimAxis.h\"\n#include \"FGAircraft.h\"\n\nstatic const char *IdSrc = \"$Header: \/cvsroot\/jsbsim\/JSBSim\/Attic\/FGTrimAxis.cpp,v 1.11 2000\/11\/01 12:14:48 jsb Exp $\";\nstatic const char *IdHdr = ID_TRIMAXIS;\n\n\/*****************************************************************************\/\n\nFGTrimAxis::FGTrimAxis(FGFDMExec* fdex, FGInitialCondition* ic, Accel acc,\n Control ctrl, float ff) {\n\n fdmex=fdex;\n fgic=ic;\n accel=acc;\n control=ctrl;\n tolerance=ff;\n solver_eps=tolerance;\n max_iterations=10;\n control_value=0;\n its_to_stable_value=0;\n total_iterations=0;\n total_stability_iterations=0;\n accel_convert=1.0;\n control_convert=1.0;\n accel_value=0;\n switch(control) {\n case tThrottle:\n control_min=0;\n control_max=1;\n control_value=0.5;\n break;\n case tBeta:\n control_min=-30*DEGTORAD;\n control_max=30*DEGTORAD;\n control_convert=RADTODEG;\n break;\n case tAlpha:\n control_min=fdmex->GetAircraft()->GetAlphaCLMin();\n control_max=fdmex->GetAircraft()->GetAlphaCLMax();\n if(control_max <= control_min) {\n control_max=20*DEGTORAD;\n control_min=-5*DEGTORAD;\n }\n control_value= (control_min+control_max)\/2;\n control_convert=RADTODEG;\n solver_eps=tolerance\/100;\n break;\n case tPitchTrim:\n case tElevator:\n case tRollTrim:\n case tAileron:\n case tYawTrim:\n case tRudder:\n control_min=-1;\n control_max=1;\n accel_convert=RADTODEG;\n solver_eps=tolerance\/100;\n break;\n case tAltAGL:\n control_min=0;\n control_max=30;\n control_value=fdmex->GetPosition()->GetDistanceAGL();\n solver_eps=tolerance\/100;\n break;\n case tTheta:\n control_min=fdmex->GetRotation()->Gettht() - 5*DEGTORAD;\n control_max=fdmex->GetRotation()->Gettht() + 5*DEGTORAD;\n accel_convert=RADTODEG;\n break;\n case tPhi:\n control_min=fdmex->GetRotation()->Getphi() - 5*DEGTORAD;\n control_max=fdmex->GetRotation()->Getphi() + 5*DEGTORAD;\n accel_convert=RADTODEG;\n break;\n case tGamma:\n solver_eps=tolerance\/100;\n control_min=-80*DEGTORAD;\n control_max=80*DEGTORAD;\n control_convert=RADTODEG;\n break;\n }\n \n}\n\n\/*****************************************************************************\/\n\nFGTrimAxis::~FGTrimAxis() {}\n\n\/*****************************************************************************\/\n\nvoid FGTrimAxis::getAccel(void) {\n switch(accel) {\n case tUdot: accel_value=fdmex -> GetTranslation()->GetUVWdot()(1); break;\n case tVdot: accel_value=fdmex -> GetTranslation()->GetUVWdot()(2); break;\n case tWdot: accel_value=fdmex -> GetTranslation()->GetUVWdot()(3); break;\n case tQdot: accel_value=fdmex -> GetRotation()->GetPQRdot()(2);break;\n case tPdot: accel_value=fdmex -> GetRotation()->GetPQRdot()(1); break;\n case tRdot: accel_value=fdmex -> GetRotation()->GetPQRdot()(3); break;\n }\n}\n\n\/*****************************************************************************\/\n\n\/\/Accels are not settable\n\nvoid FGTrimAxis::getControl(void) {\n switch(control) {\n case tThrottle: control_value=fdmex->GetFCS()->GetThrottleCmd(0); break;\n case tBeta: control_value=fdmex->GetTranslation()->Getalpha(); break;\n case tAlpha: control_value=fdmex->GetTranslation()->Getbeta(); break;\n case tPitchTrim: control_value=fdmex->GetFCS() -> GetPitchTrimCmd(); break;\n case tElevator: control_value=fdmex->GetFCS() -> GetDeCmd(); break;\n case tRollTrim:\n case tAileron: control_value=fdmex->GetFCS() -> GetDaCmd(); break;\n case tYawTrim:\n case tRudder: control_value=fdmex->GetFCS() -> GetDrCmd(); break;\n case tAltAGL: control_value=fdmex->GetPosition()->GetDistanceAGL();break;\n case tTheta: control_value=fdmex->GetRotation()->Gettht(); break;\n case tPhi: control_value=fdmex->GetRotation()->Getphi(); break;\n case tGamma: control_value=fdmex->GetPosition()->GetGamma();break;\n }\n}\n\n\/*****************************************************************************\/\n\n\nvoid FGTrimAxis::setControl(void) {\n switch(control) {\n case tThrottle: setThrottlesPct(); break;\n case tBeta: fgic->SetBetaRadIC(control_value); break;\n case tAlpha: fgic->SetAlphaRadIC(control_value); break;\n case tPitchTrim: fdmex->GetFCS() -> SetPitchTrimCmd(control_value); break;\n case tElevator: fdmex-> GetFCS() -> SetDeCmd(control_value); break;\n case tRollTrim:\n case tAileron: fdmex-> GetFCS() -> SetDaCmd(control_value); break;\n case tYawTrim:\n case tRudder: fdmex-> GetFCS() -> SetDrCmd(control_value); break;\n case tAltAGL: fgic->SetAltitudeAGLFtIC(control_value); break;\n case tTheta: fgic->SetPitchAngleRadIC(control_value); break;\n case tPhi: fgic->SetRollAngleRadIC(control_value); break;\n case tGamma: fgic->SetFlightPathAngleRadIC(control_value); break;\n }\n}\n\n\n \n\n\n\/*****************************************************************************\/\n\n\/\/ the aircraft center of rotation is no longer the cg once the gear\n\/\/ contact the ground so the altitude needs to be changed when pitch \n\/\/ and roll angle are adjusted. Instead of attempting to calculate the \n\/\/ new center of rotation, pick a gear unit as a reference and use its\n\/\/ location vector to calculate the new height change. i.e. new altitude =\n\/\/ earth z component of that vector (which is in body axes ) \nvoid FGTrimAxis::SetThetaOnGround(float ff) {\n int center,i,ref;\n\n \/\/ favor an off-center unit so that the same one can be used for both\n \/\/ pitch and roll. An on-center unit is used (for pitch)if that's all \n \/\/ that's in contact with the ground.\n i=0; ref=-1; center=-1;\n while( (ref < 0) && (i < fdmex->GetAircraft()->GetNumGearUnits()) ) {\n if(fdmex->GetAircraft()->GetGearUnit(i)->GetWOW()) {\n if(fabs(fdmex->GetAircraft()->GetGearUnit(i)->GetBodyLocation()(2)) > 0.01)\n ref=i;\n else\n center=i;\n } \n i++; \n }\n if((ref < 0) && (center >= 0)) {\n ref=center;\n }\n cout << \"SetThetaOnGround ref gear: \" << ref << endl;\n if(ref >= 0) {\n float sp=fdmex->GetRotation()->GetSinphi();\n float cp=fdmex->GetRotation()->GetCosphi();\n float lx=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(1);\n float ly=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(2);\n float lz=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(3);\n float hagl = -1*lx*sin(ff) +\n ly*sp*cos(ff) +\n lz*cp*cos(ff);\n \n fgic->SetAltitudeAGLFtIC(hagl);\n cout << \"SetThetaOnGround new alt: \" << hagl << endl;\n } \n fgic->SetPitchAngleRadIC(ff); \n cout << \"SetThetaOnGround new theta: \" << ff << endl; \n} \n\n\/*****************************************************************************\/\n\nbool FGTrimAxis::initTheta(void) {\n int i,N,iAft, iForward;\n float zAft,zForward,zDiff,theta;\n bool level; \n float saveAlt;\n \n saveAlt=fgic->GetAltitudeAGLFtIC();\n fgic->SetAltitudeAGLFtIC(100);\n \n \n N=fdmex->GetAircraft()->GetNumGearUnits();\n \n \/\/find the first wheel unit forward of the cg\n \/\/the list is short so a simple linear search is fine\n for( i=0; iGetAircraft()->GetGearUnit(i)->GetBodyLocation()(1) > 0 ) {\n iForward=i;\n break;\n }\n }\n \/\/now find the first wheel unit aft of the cg\n for( i=0; iGetAircraft()->GetGearUnit(i)->GetBodyLocation()(1) < 0 ) {\n iAft=i;\n break;\n }\n }\n \t \n \/\/ now adjust theta till the wheels are the same distance from the ground\n zAft=fdmex->GetAircraft()->GetGearUnit(1)->GetLocalGear()(3);\n zForward=fdmex->GetAircraft()->GetGearUnit(0)->GetLocalGear()(3);\n zDiff = zForward - zAft;\n level=false;\n theta=fgic->GetPitchAngleDegIC(); \n while(!level && (i < 100)) {\n\ttheta+=2.0*zDiff;\n\tfgic->SetPitchAngleDegIC(theta); \n\tfdmex->RunIC(fgic);\n\tzAft=fdmex->GetAircraft()->GetGearUnit(1)->GetLocalGear()(3);\n zForward=fdmex->GetAircraft()->GetGearUnit(0)->GetLocalGear()(3);\n zDiff = zForward - zAft;\n\t\/\/cout << endl << theta << \" \" << zDiff << endl;\n\t\/\/cout << \"0: \" << fdmex->GetAircraft()->GetGearUnit(0)->GetLocalGear() << endl;\n\t\/\/cout << \"1: \" << fdmex->GetAircraft()->GetGearUnit(1)->GetLocalGear() << endl;\n\n\tif(fabs(zDiff ) < 0.1) \n\t level=true;\n\ti++; \n }\t \t \t\n \/\/cout << i << endl;\n cout << \" Initial Theta: \" << fdmex->GetRotation()->Gettht()*RADTODEG << endl;\n control_min=(theta+5)*DEGTORAD;\n control_max=(theta-5)*DEGTORAD;\n fgic->SetAltitudeAGLFtIC(saveAlt);\n if(i < 100) \n return true;\n else\n return false; \n} \n\n\/*****************************************************************************\/\n\nvoid FGTrimAxis::SetPhiOnGround(float ff) {\n int i,ref;\n\n i=0; ref=-1;\n \/\/must have an off-center unit here \n while( (ref < 0) && (i < fdmex->GetAircraft()->GetNumGearUnits()) ) {\n if( (fdmex->GetAircraft()->GetGearUnit(i)->GetWOW()) && \n (fabs(fdmex->GetAircraft()->GetGearUnit(i)->GetBodyLocation()(2)) > 0.01))\n ref=i;\n i++; \n }\n if(ref >= 0) {\n float st=fdmex->GetRotation()->GetSintht();\n float ct=fdmex->GetRotation()->GetCostht();\n float lx=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(1);\n float ly=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(2);\n float lz=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(3);\n float hagl = -1*lx*st +\n ly*sin(ff)*ct +\n lz*cos(ff)*ct;\n \n fgic->SetAltitudeAGLFtIC(hagl);\n } \n fgic->SetRollAngleRadIC(ff);\n \n} \n\n\/*****************************************************************************\/\n\nvoid FGTrimAxis::Run(void) {\n\n float last_accel_value;\n int i;\n setControl();\n \/\/cout << \"FGTrimAxis::Run: \" << control_value << endl;\n i=0;\n bool stable=false;\n while(!stable) {\n i++;\n last_accel_value=accel_value;\n fdmex->RunIC(fgic);\n getAccel();\n if(i > 1) {\n if((fabs(last_accel_value - accel_value) < tolerance) || (i >= 100) )\n stable=true;\n }\n }\n\n its_to_stable_value=i;\n total_stability_iterations+=its_to_stable_value;\n total_iterations++;\n}\n\n\/*****************************************************************************\/\n\nvoid FGTrimAxis::setThrottlesPct(void) {\n float tMin,tMax;\n for(unsigned i=0;iGetAircraft()->GetNumEngines();i++) {\n tMin=fdmex->GetAircraft()->GetEngine(i)->GetThrottleMin();\n tMax=fdmex->GetAircraft()->GetEngine(i)->GetThrottleMax();\n \/\/cout << \"setThrottlespct: \" << i << \", \" << control_min << \", \" << control_max << \", \" << control_value;\n fdmex -> GetFCS() -> SetThrottleCmd(i,tMin+control_value*(tMax-tMin));\n }\n}\n\n\n\/*****************************************************************************\/\n\n\nvoid FGTrimAxis::AxisReport(void) {\n \n char out[80];\n sprintf(out,\" %20s: %6.2f %5s: %9.2e Tolerance: %3.0e\\n\",\n GetControlName().c_str(), GetControl()*control_convert,\n GetAccelName().c_str(), GetAccel(), GetTolerance()); \n cout << out;\n\n}\n\n\n\/*****************************************************************************\/\n\nfloat FGTrimAxis::GetAvgStability( void ) {\n if(total_iterations > 0) {\n return float(total_stability_iterations)\/float(total_iterations);\n }\n return 0;\n}\n\n<|endoftext|>"} {"text":"#include \"types.h\"\n#include \"mmu.h\"\n#include \"kernel.hh\"\n#include \"amd64.h\"\n#include \"cpu.hh\"\n#include \"traps.h\"\n#include \"queue.h\"\n#include \"spinlock.h\"\n#include \"condvar.h\"\n#include \"proc.hh\"\n#include \"kmtrace.hh\"\n#include \"bits.hh\"\n#include \"kalloc.hh\"\n#include \"apic.hh\"\n#include \"kstream.hh\"\n\nextern \"C\" void __uaccess_end(void);\n\nstruct intdesc idt[256] __attribute__((aligned(16)));\n\n\/\/ boot.S\nextern u64 trapentry[];\n\nu64\nsysentry_c(u64 a0, u64 a1, u64 a2, u64 a3, u64 a4, u64 a5, u64 num)\n{\n sti();\n\n if(myproc()->killed) {\n mtstart(trap, myproc());\n exit();\n }\n\n trapframe *tf = (trapframe*) (myproc()->kstack + KSTACKSIZE - sizeof(*tf));\n myproc()->tf = tf;\n u64 r = syscall(a0, a1, a2, a3, a4, a5, num);\n\n if(myproc()->killed) {\n mtstart(trap, myproc());\n exit();\n }\n\n return r;\n}\n\nint\ndo_pagefault(struct trapframe *tf)\n{\n uptr addr = rcr2();\n if (myproc()->uaccess_) {\n if (addr >= USERTOP)\n panic(\"do_pagefault: %lx\", addr);\n\n sti();\n if(pagefault(myproc()->vmap, addr, tf->err) >= 0){\n#if MTRACE\n mtstop(myproc());\n if (myproc()->mtrace_stacks.curr >= 0)\n mtresume(myproc());\n#endif\n return 0;\n }\n cprintf(\"pagefault: failed in kernel\\n\");\n tf->rax = -1;\n tf->rip = (u64)__uaccess_end;\n return 0;\n } else if (tf->err & FEC_U) {\n sti();\n if(pagefault(myproc()->vmap, addr, tf->err) >= 0){\n#if MTRACE\n mtstop(myproc());\n if (myproc()->mtrace_stacks.curr >= 0)\n mtresume(myproc());\n#endif\n return 0;\n }\n uerr.println(\"pagefault: failed in user\");\n cli();\n }\n return -1;\n}\n\nvoid\ntrap(struct trapframe *tf)\n{\n if (tf->trapno == T_NMI) {\n \/\/ The only locks that we can acquire during NMI are ones\n \/\/ we acquire only during NMI.\n if (sampintr(tf))\n return;\n panic(\"NMI\");\n }\n\n#if MTRACE\n if (myproc()->mtrace_stacks.curr >= 0)\n mtpause(myproc());\n mtstart(trap, myproc());\n \/\/ XXX mt_ascope ascope(\"trap:%d\", tf->trapno);\n#endif\n\n switch(tf->trapno){\n case T_IRQ0 + IRQ_TIMER:\n if (mycpu()->timer_printpc) {\n cprintf(\"cpu%d: proc %s rip %lx rsp %lx cs %x\\n\",\n mycpu()->id,\n myproc() ? myproc()->name : \"(none)\",\n tf->rip, tf->rsp, tf->cs);\n if (mycpu()->timer_printpc == 2 && tf->rbp > KBASE) {\n uptr pc[10];\n getcallerpcs((void *) tf->rbp, pc, NELEM(pc));\n for (int i = 0; i < 10 && pc[i]; i++)\n cprintf(\"cpu%d: %lx\\n\", mycpu()->id, pc[i]);\n }\n mycpu()->timer_printpc = 0;\n }\n if (mycpu()->id == 0)\n timerintr();\n lapiceoi();\n break;\n case T_IRQ0 + IRQ_IDE:\n ideintr();\n lapiceoi();\n piceoi();\n break;\n case T_IRQ0 + IRQ_IDE+1:\n \/\/ Bochs generates spurious IDE1 interrupts.\n break;\n case T_IRQ0 + IRQ_KBD:\n kbdintr();\n lapiceoi();\n piceoi();\n break;\n case T_IRQ0 + IRQ_COM2:\n case T_IRQ0 + IRQ_COM1:\n uartintr();\n lapiceoi();\n piceoi();\n break;\n case T_IRQ0 + 7:\n case T_IRQ0 + IRQ_SPURIOUS:\n cprintf(\"cpu%d: spurious interrupt at %x:%lx\\n\",\n mycpu()->id, tf->cs, tf->rip);\n lapiceoi();\n break;\n case T_IRQ0 + IRQ_ERROR:\n cprintf(\"cpu%d: lapic error?\\n\", mycpu()->id);\n lapiceoi();\n break;\n case T_TLBFLUSH: {\n lapiceoi();\n u64 nreq = tlbflush_req.load();\n lcr3(rcr3());\n mycpu()->tlbflush_done = nreq;\n break;\n }\n case T_SAMPCONF:\n lapiceoi();\n sampconf(); \n break;\n default:\n if (tf->trapno == T_IRQ0+e1000irq) {\n e1000intr();\n lapiceoi();\n piceoi();\n break;\n }\n\n if (tf->trapno == T_PGFLT && do_pagefault(tf) == 0)\n return;\n \n if (myproc() == 0 || (tf->cs&3) == 0)\n kerneltrap(tf);\n\n \/\/ In user space, assume process misbehaved.\n uerr.println(\"pid \", myproc()->pid, ' ', myproc()->name,\n \": trap \", (u64)tf->trapno, \" err \", (u32)tf->err,\n \" on cpu \", myid(), \" rip \", shex(tf->rip),\n \" rsp \", shex(tf->rsp), \" addr \", shex(rcr2()),\n \"--kill proc\");\n myproc()->killed = 1;\n }\n\n \/\/ Force process exit if it has been killed and is in user space.\n \/\/ (If it is still executing in the kernel, let it keep running \n \/\/ until it gets to the regular system call return.)\n if(myproc() && myproc()->killed && (tf->cs&3) == 0x3)\n exit();\n\n \/\/ Force process to give up CPU on clock tick.\n \/\/ If interrupts were on while locks held, would need to check nlock.\n if(myproc() && myproc()->get_state() == RUNNING && tf->trapno == T_IRQ0+IRQ_TIMER)\n yield();\n\n \/\/ Check if the process has been killed since we yielded\n if(myproc() && myproc()->killed && (tf->cs&3) == 0x3)\n exit();\n\n#if MTRACE\n mtstop(myproc());\n if (myproc()->mtrace_stacks.curr >= 0)\n mtresume(myproc());\n#endif\n}\n\nvoid\ninittrap(void)\n{\n u64 entry;\n u8 bits;\n int i;\n \n bits = INT_P | SEG_INTR64; \/\/ present, interrupt gate\n for(i=0; i<256; i++) {\n entry = trapentry[i];\n idt[i] = INTDESC(KCSEG, entry, bits);\n }\n}\n\nvoid\ninitnmi(void)\n{\n void *nmistackbase = ksalloc(slab_stack);\n mycpu()->ts.ist[1] = (u64) nmistackbase + KSTACKSIZE;\n\n if (mycpu()->id == 0)\n idt[T_NMI].ist = 1;\n}\n\nvoid\ninitseg(void)\n{\n volatile struct desctr dtr;\n struct cpu *c;\n\n dtr.limit = sizeof(idt) - 1;\n dtr.base = (u64)idt;\n lidt((void *)&dtr.limit);\n\n \/\/ TLS might not be ready\n c = &cpus[myid()];\n \/\/ Load per-CPU GDT\n memmove(c->gdt, bootgdt, sizeof(bootgdt));\n dtr.limit = sizeof(c->gdt) - 1;\n dtr.base = (u64)c->gdt;\n lgdt((void *)&dtr.limit);\n\n \/\/ When executing a syscall instruction the CPU sets the SS selector\n \/\/ to (star >> 32) + 8 and the CS selector to (star >> 32).\n \/\/ When executing a sysret instruction the CPU sets the SS selector\n \/\/ to (star >> 48) + 8 and the CS selector to (star >> 48) + 16.\n u64 star = ((((u64)UCSEG|0x3) - 16)<<48)|((u64)KCSEG<<32);\n writemsr(MSR_STAR, star);\n writemsr(MSR_LSTAR, (u64)&sysentry);\n writemsr(MSR_SFMASK, FL_TF | FL_IF);\n}\n\n\/\/ Pushcli\/popcli are like cli\/sti except that they are matched:\n\/\/ it takes two popcli to undo two pushcli. Also, if interrupts\n\/\/ are off, then pushcli, popcli leaves them off.\nvoid\npushcli(void)\n{\n u64 rflags;\n\n rflags = readrflags();\n cli();\n if(mycpu()->ncli++ == 0)\n mycpu()->intena = rflags & FL_IF;\n}\n\nvoid\npopcli(void)\n{\n if(readrflags()&FL_IF)\n panic(\"popcli - interruptible\");\n if(--mycpu()->ncli < 0)\n panic(\"popcli\");\n if(mycpu()->ncli == 0 && mycpu()->intena)\n sti();\n}\n\n\/\/ Record the current call stack in pcs[] by following the %rbp chain.\nvoid\ngetcallerpcs(void *v, uptr pcs[], int n)\n{\n uptr *rbp;\n int i;\n\n rbp = (uptr*)v;\n for(i = 0; i < n; i++){\n if(rbp == 0 || rbp < (uptr*)KBASE || rbp == (uptr*)(~0UL) ||\n (rbp >= (uptr*)KBASEEND && rbp < (uptr*)KCODE))\n break;\n pcs[i] = rbp[1]; \/\/ saved %rip\n rbp = (uptr*)rbp[0]; \/\/ saved %rbp\n }\n for(; i < n; i++)\n pcs[i] = 0;\n}\nSubtract one from PCs recorded by getcallerpcs#include \"types.h\"\n#include \"mmu.h\"\n#include \"kernel.hh\"\n#include \"amd64.h\"\n#include \"cpu.hh\"\n#include \"traps.h\"\n#include \"queue.h\"\n#include \"spinlock.h\"\n#include \"condvar.h\"\n#include \"proc.hh\"\n#include \"kmtrace.hh\"\n#include \"bits.hh\"\n#include \"kalloc.hh\"\n#include \"apic.hh\"\n#include \"kstream.hh\"\n\nextern \"C\" void __uaccess_end(void);\n\nstruct intdesc idt[256] __attribute__((aligned(16)));\n\n\/\/ boot.S\nextern u64 trapentry[];\n\nu64\nsysentry_c(u64 a0, u64 a1, u64 a2, u64 a3, u64 a4, u64 a5, u64 num)\n{\n sti();\n\n if(myproc()->killed) {\n mtstart(trap, myproc());\n exit();\n }\n\n trapframe *tf = (trapframe*) (myproc()->kstack + KSTACKSIZE - sizeof(*tf));\n myproc()->tf = tf;\n u64 r = syscall(a0, a1, a2, a3, a4, a5, num);\n\n if(myproc()->killed) {\n mtstart(trap, myproc());\n exit();\n }\n\n return r;\n}\n\nint\ndo_pagefault(struct trapframe *tf)\n{\n uptr addr = rcr2();\n if (myproc()->uaccess_) {\n if (addr >= USERTOP)\n panic(\"do_pagefault: %lx\", addr);\n\n sti();\n if(pagefault(myproc()->vmap, addr, tf->err) >= 0){\n#if MTRACE\n mtstop(myproc());\n if (myproc()->mtrace_stacks.curr >= 0)\n mtresume(myproc());\n#endif\n return 0;\n }\n cprintf(\"pagefault: failed in kernel\\n\");\n tf->rax = -1;\n tf->rip = (u64)__uaccess_end;\n return 0;\n } else if (tf->err & FEC_U) {\n sti();\n if(pagefault(myproc()->vmap, addr, tf->err) >= 0){\n#if MTRACE\n mtstop(myproc());\n if (myproc()->mtrace_stacks.curr >= 0)\n mtresume(myproc());\n#endif\n return 0;\n }\n uerr.println(\"pagefault: failed in user\");\n cli();\n }\n return -1;\n}\n\nvoid\ntrap(struct trapframe *tf)\n{\n if (tf->trapno == T_NMI) {\n \/\/ The only locks that we can acquire during NMI are ones\n \/\/ we acquire only during NMI.\n if (sampintr(tf))\n return;\n panic(\"NMI\");\n }\n\n#if MTRACE\n if (myproc()->mtrace_stacks.curr >= 0)\n mtpause(myproc());\n mtstart(trap, myproc());\n \/\/ XXX mt_ascope ascope(\"trap:%d\", tf->trapno);\n#endif\n\n switch(tf->trapno){\n case T_IRQ0 + IRQ_TIMER:\n if (mycpu()->timer_printpc) {\n cprintf(\"cpu%d: proc %s rip %lx rsp %lx cs %x\\n\",\n mycpu()->id,\n myproc() ? myproc()->name : \"(none)\",\n tf->rip, tf->rsp, tf->cs);\n if (mycpu()->timer_printpc == 2 && tf->rbp > KBASE) {\n uptr pc[10];\n getcallerpcs((void *) tf->rbp, pc, NELEM(pc));\n for (int i = 0; i < 10 && pc[i]; i++)\n cprintf(\"cpu%d: %lx\\n\", mycpu()->id, pc[i]);\n }\n mycpu()->timer_printpc = 0;\n }\n if (mycpu()->id == 0)\n timerintr();\n lapiceoi();\n break;\n case T_IRQ0 + IRQ_IDE:\n ideintr();\n lapiceoi();\n piceoi();\n break;\n case T_IRQ0 + IRQ_IDE+1:\n \/\/ Bochs generates spurious IDE1 interrupts.\n break;\n case T_IRQ0 + IRQ_KBD:\n kbdintr();\n lapiceoi();\n piceoi();\n break;\n case T_IRQ0 + IRQ_COM2:\n case T_IRQ0 + IRQ_COM1:\n uartintr();\n lapiceoi();\n piceoi();\n break;\n case T_IRQ0 + 7:\n case T_IRQ0 + IRQ_SPURIOUS:\n cprintf(\"cpu%d: spurious interrupt at %x:%lx\\n\",\n mycpu()->id, tf->cs, tf->rip);\n lapiceoi();\n break;\n case T_IRQ0 + IRQ_ERROR:\n cprintf(\"cpu%d: lapic error?\\n\", mycpu()->id);\n lapiceoi();\n break;\n case T_TLBFLUSH: {\n lapiceoi();\n u64 nreq = tlbflush_req.load();\n lcr3(rcr3());\n mycpu()->tlbflush_done = nreq;\n break;\n }\n case T_SAMPCONF:\n lapiceoi();\n sampconf(); \n break;\n default:\n if (tf->trapno == T_IRQ0+e1000irq) {\n e1000intr();\n lapiceoi();\n piceoi();\n break;\n }\n\n if (tf->trapno == T_PGFLT && do_pagefault(tf) == 0)\n return;\n \n if (myproc() == 0 || (tf->cs&3) == 0)\n kerneltrap(tf);\n\n \/\/ In user space, assume process misbehaved.\n uerr.println(\"pid \", myproc()->pid, ' ', myproc()->name,\n \": trap \", (u64)tf->trapno, \" err \", (u32)tf->err,\n \" on cpu \", myid(), \" rip \", shex(tf->rip),\n \" rsp \", shex(tf->rsp), \" addr \", shex(rcr2()),\n \"--kill proc\");\n myproc()->killed = 1;\n }\n\n \/\/ Force process exit if it has been killed and is in user space.\n \/\/ (If it is still executing in the kernel, let it keep running \n \/\/ until it gets to the regular system call return.)\n if(myproc() && myproc()->killed && (tf->cs&3) == 0x3)\n exit();\n\n \/\/ Force process to give up CPU on clock tick.\n \/\/ If interrupts were on while locks held, would need to check nlock.\n if(myproc() && myproc()->get_state() == RUNNING && tf->trapno == T_IRQ0+IRQ_TIMER)\n yield();\n\n \/\/ Check if the process has been killed since we yielded\n if(myproc() && myproc()->killed && (tf->cs&3) == 0x3)\n exit();\n\n#if MTRACE\n mtstop(myproc());\n if (myproc()->mtrace_stacks.curr >= 0)\n mtresume(myproc());\n#endif\n}\n\nvoid\ninittrap(void)\n{\n u64 entry;\n u8 bits;\n int i;\n \n bits = INT_P | SEG_INTR64; \/\/ present, interrupt gate\n for(i=0; i<256; i++) {\n entry = trapentry[i];\n idt[i] = INTDESC(KCSEG, entry, bits);\n }\n}\n\nvoid\ninitnmi(void)\n{\n void *nmistackbase = ksalloc(slab_stack);\n mycpu()->ts.ist[1] = (u64) nmistackbase + KSTACKSIZE;\n\n if (mycpu()->id == 0)\n idt[T_NMI].ist = 1;\n}\n\nvoid\ninitseg(void)\n{\n volatile struct desctr dtr;\n struct cpu *c;\n\n dtr.limit = sizeof(idt) - 1;\n dtr.base = (u64)idt;\n lidt((void *)&dtr.limit);\n\n \/\/ TLS might not be ready\n c = &cpus[myid()];\n \/\/ Load per-CPU GDT\n memmove(c->gdt, bootgdt, sizeof(bootgdt));\n dtr.limit = sizeof(c->gdt) - 1;\n dtr.base = (u64)c->gdt;\n lgdt((void *)&dtr.limit);\n\n \/\/ When executing a syscall instruction the CPU sets the SS selector\n \/\/ to (star >> 32) + 8 and the CS selector to (star >> 32).\n \/\/ When executing a sysret instruction the CPU sets the SS selector\n \/\/ to (star >> 48) + 8 and the CS selector to (star >> 48) + 16.\n u64 star = ((((u64)UCSEG|0x3) - 16)<<48)|((u64)KCSEG<<32);\n writemsr(MSR_STAR, star);\n writemsr(MSR_LSTAR, (u64)&sysentry);\n writemsr(MSR_SFMASK, FL_TF | FL_IF);\n}\n\n\/\/ Pushcli\/popcli are like cli\/sti except that they are matched:\n\/\/ it takes two popcli to undo two pushcli. Also, if interrupts\n\/\/ are off, then pushcli, popcli leaves them off.\nvoid\npushcli(void)\n{\n u64 rflags;\n\n rflags = readrflags();\n cli();\n if(mycpu()->ncli++ == 0)\n mycpu()->intena = rflags & FL_IF;\n}\n\nvoid\npopcli(void)\n{\n if(readrflags()&FL_IF)\n panic(\"popcli - interruptible\");\n if(--mycpu()->ncli < 0)\n panic(\"popcli\");\n if(mycpu()->ncli == 0 && mycpu()->intena)\n sti();\n}\n\n\/\/ Record the current call stack in pcs[] by following the %rbp chain.\nvoid\ngetcallerpcs(void *v, uptr pcs[], int n)\n{\n uptr *rbp;\n int i;\n\n rbp = (uptr*)v;\n for(i = 0; i < n; i++){\n if(rbp == 0 || rbp < (uptr*)KBASE || rbp == (uptr*)(~0UL) ||\n (rbp >= (uptr*)KBASEEND && rbp < (uptr*)KCODE))\n break;\n pcs[i] = rbp[1] - 1; \/\/ saved %rip; - 1 so it points to the call\n \/\/ instruction\n rbp = (uptr*)rbp[0]; \/\/ saved %rbp\n }\n for(; i < n; i++)\n pcs[i] = 0;\n}\n<|endoftext|>"} {"text":"\/\/ File: ebdpConfigFile.cpp\n\/\/ Date: 9\/27\/2017\n\/\/ Auth: K. Loux\n\/\/ Desc: Configuration file object.\n\n\/\/ Local headers\n#include \"ebdpConfigFile.h\"\n\nvoid EBDPConfigFile::BuildConfigItems()\n{\n\tAddConfigItem(_T(\"OBS_DATA_FILE\"), config.dataFileName);\n\tAddConfigItem(_T(\"OUTPUT_FILE\"), config.outputFileName);\n\n\tAddConfigItem(_T(\"COUNTRY\"), config.countryFilter);\n\tAddConfigItem(_T(\"STATE\"), config.stateFilter);\n\tAddConfigItem(_T(\"COUNTY\"), config.countyFilter);\n\tAddConfigItem(_T(\"LOCATION\"), config.locationFilter);\n\n\tAddConfigItem(_T(\"LIST_TYPE\"), config.listType);\n\n\tAddConfigItem(_T(\"SCORE_RARITIES\"), config.generateRarityScores);\n\tAddConfigItem(_T(\"SPECIES_COUNT_ONLY\"), config.speciesCountOnly);\n\tAddConfigItem(_T(\"INCLUDE_PARTIAL_IDS\"), config.includePartialIDs);\n\n\tAddConfigItem(_T(\"PHOTO_FILE\"), config.photoFileName);\n\tAddConfigItem(_T(\"SHOW_PHOTO_NEEDS\"), config.showOnlyPhotoNeeds);\n\n\tAddConfigItem(_T(\"YEAR\"), config.yearFilter);\n\tAddConfigItem(_T(\"MONTH\"), config.monthFilter);\n\tAddConfigItem(_T(\"WEEK\"), config.weekFilter);\n\tAddConfigItem(_T(\"DAY\"), config.dayFilter);\n\n\tAddConfigItem(_T(\"SORT_FIRST\"), config.primarySort);\n\tAddConfigItem(_T(\"SORT_SECOND\"), config.secondarySort);\n\n\tAddConfigItem(_T(\"SHOW_UNIQUE_OBS\"), config.uniqueObservations);\n\n\tAddConfigItem(_T(\"CALENDAR\"), config.generateTargetCalendar);\n\tAddConfigItem(_T(\"TARGET_AREA\"), config.targetNeedArea);\n\tAddConfigItem(_T(\"TOP_COUNT\"), config.topBirdCount);\n\tAddConfigItem(_T(\"FREQUENCY_FILES\"), config.frequencyFilePath);\n\tAddConfigItem(_T(\"TARGET_INFO_FILE_NAME\"), config.targetInfoFileName);\n\tAddConfigItem(_T(\"RECENT_PERIOD\"), config.recentObservationPeriod);\n\n\tAddConfigItem(_T(\"GOOGLE_MAPS_KEY\"), config.googleMapsAPIKey);\n\tAddConfigItem(_T(\"HOME_LOCATION\"), config.homeLocation);\n\tAddConfigItem(_T(\"EBIRD_API_KEY\"), config.eBirdApiKey);\n\n\tAddConfigItem(_T(\"FIND_MAX_NEEDS\"), config.findMaxNeedsLocations);\n\tAddConfigItem(_T(\"KML_LIBRARY\"), config.kmlLibraryPath);\n\n\tAddConfigItem(_T(\"OAUTH_CLIENT_ID\"), config.oAuthClientId);\n\tAddConfigItem(_T(\"OAUTH_CLIENT_SECRET\"), config.oAuthClientSecret);\n\n\tAddConfigItem(_T(\"DATASET\"), config.eBirdDatasetPath);\n}\n\nvoid EBDPConfigFile::AssignDefaults()\n{\n\tconfig.listType = EBDPConfig::ListType::Life;\n\tconfig.speciesCountOnly = false;\n\tconfig.includePartialIDs = false;\n\n\tconfig.yearFilter = 0;\n\tconfig.monthFilter = 0;\n\tconfig.weekFilter = 0;\n\tconfig.dayFilter = 0;\n\n\tconfig.primarySort = EBDPConfig::SortBy::None;\n\tconfig.secondarySort = EBDPConfig::SortBy::None;\n\n\tconfig.uniqueObservations = EBDPConfig::UniquenessType::None;\n\n\tconfig.targetNeedArea = EBDPConfig::TargetNeedArea::None;\n\tconfig.generateTargetCalendar = false;\n\tconfig.generateRarityScores = false;\n\tconfig.topBirdCount = 20;\n\tconfig.recentObservationPeriod = 15;\n\n\tconfig.showOnlyPhotoNeeds = false;\n\tconfig.findMaxNeedsLocations = false;\n}\n\nbool EBDPConfigFile::ConfigIsOK()\n{\n\tbool configurationOK(true);\n\n\tif (!GeneralConfigIsOK())\n\t\tconfigurationOK = false;\n\n\tif (!FrequencyHarvestConfigIsOK())\n\t\tconfigurationOK = false;\n\n\tif (!TargetCalendarConfigIsOK())\n\t\tconfigurationOK = false;\n\n\tif (!FindMaxNeedsConfigIsOK())\n\t\tconfigurationOK = false;\n\n\tif (!RaritiesConfigIsOK())\n\t\tconfigurationOK = false;\n\n\treturn configurationOK;\n}\n\nbool EBDPConfigFile::FrequencyHarvestConfigIsOK()\n{\n\tbool configurationOK(true);\n\n\tif (!config.eBirdDatasetPath.empty() && config.frequencyFilePath.empty())\n\t{\n\t\tCerr << GetKey(config.eBirdDatasetPath) << \" requires \" << GetKey(config.frequencyFilePath) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\treturn configurationOK;\n}\n\nbool EBDPConfigFile::TargetCalendarConfigIsOK()\n{\n if (!config.generateTargetCalendar)\n return true;\n \n\tbool configurationOK(true);\n\n\tif (config.frequencyFilePath.empty())\n\t{\n\t\tCerr << \"Must specify \" << GetKey(config.frequencyFilePath) << \" when using \" << GetKey(config.generateTargetCalendar) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.eBirdApiKey.empty())\n\t{\n\t\tCerr << \"Must specify \" << GetKey(config.eBirdApiKey) << \" when using \" << GetKey(config.generateTargetCalendar) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.uniqueObservations != EBDPConfig::UniquenessType::None)\n\t{\n\t\tCerr << \"Cannot specify both \" << GetKey(config.generateTargetCalendar) << \" and \" << GetKey(config.uniqueObservations) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\treturn configurationOK;\n}\n\nbool EBDPConfigFile::FindMaxNeedsConfigIsOK()\n{\n if (!config.findMaxNeedsLocations)\n return true;\n \n\tbool configurationOK(true);\n\n\tif (config.oAuthClientId.empty() || config.oAuthClientSecret.empty())\n\t{\n\t\tCerr << GetKey(config.findMaxNeedsLocations) << \" requires \"\n\t\t\t<< GetKey(config.oAuthClientId) << \" and \" << GetKey(config.oAuthClientSecret) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.kmlLibraryPath.empty())\n\t{\n\t\tCerr << GetKey(config.findMaxNeedsLocations) << \" requires \" << GetKey(config.kmlLibraryPath) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.eBirdApiKey.empty())\n\t{\n\t\tCerr << GetKey(config.findMaxNeedsLocations) << \" requires \" << GetKey(config.eBirdApiKey) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n \n if (config.frequencyFilePath.empty())\n\t{\n\t\tCerr << \"Must specify \" << GetKey(config.frequencyFilePath) << \" when using \" << GetKey(config.findMaxNeedsLocations) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\treturn configurationOK;\n}\n\nbool EBDPConfigFile::GeneralConfigIsOK()\n{\n\tbool configurationOK(true);\n\n\tif (config.dataFileName.empty())\n\t{\n\t\tCerr << \"Must specify '\" << GetKey(config.dataFileName) << \"'\\n\";\n\t\tconfigurationOK = false;\n\t}\n\n\tif (!config.countryFilter.empty() &&\n\t\tconfig.countryFilter.length() != 2)\n\t{\n\t\tCerr << \"Country (\" << GetKey(config.countryFilter) << \") must be specified using 2-digit abbreviation\\n\";\n\t\tconfigurationOK = false;\n\t}\n\n\tif (!config.stateFilter.empty() &&\n\t\t(config.stateFilter.length() < 2 || config.stateFilter.length() > 3))\n\t{\n\t\tCerr << \"State\/providence (\" << GetKey(config.stateFilter) << \") must be specified using 2- or 3-digit abbreviation\\n\";\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.dayFilter > 31)\n\t{\n\t\tCerr << \"Day (\" << GetKey(config.dayFilter) << \") must be in the range 0 - 31\\n\";\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.monthFilter > 12)\n\t{\n\t\tCerr << \"Month (\" << GetKey(config.monthFilter) << \") must be in the range 0 - 12\\n\";\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.weekFilter > 53)\n\t{\n\t\tCerr << \"Week (\" << GetKey(config.weekFilter) << \") must be in the range 0 - 53\\n\";\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.recentObservationPeriod < 1 || config.recentObservationPeriod > 30)\n\t{\n\t\tCerr << GetKey(config.recentObservationPeriod) << \" must be between 1 and 30\\n\";\n\t\tconfigurationOK = false;\n\t}\n\n\t\/*if (!config.googleMapsAPIKey.empty() && config.homeLocation.empty())\n\t{\n\t\tCerr << \"Must specify \" << GetKey(config.homeLocation) << \" when using \" << GetKey(config.googleMapsAPIKey) << '\\n';\n\t\tconfigurationOK = false;\n\t}*\/\n\n\tif (config.uniqueObservations != EBDPConfig::UniquenessType::None && !config.countryFilter.empty())\n\t{\n\t\tCerr << \"Cannot specify both \" << GetKey(config.countryFilter) << \" and \" << GetKey(config.uniqueObservations) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.showOnlyPhotoNeeds && config.photoFileName.empty())\n\t{\n\t\tCerr << \"Must specify \" << GetKey(config.photoFileName) << \" when using \" << GetKey(config.showOnlyPhotoNeeds) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\treturn configurationOK;\n}\n\nbool EBDPConfigFile::RaritiesConfigIsOK()\n{\n if (!config.generateRarityScores)\n return true;\n \n\tbool configurationOK(true);\n\n\tif (config.frequencyFilePath.empty())\n\t{\n\t\tCerr << \"Must specify \" << GetKey(config.frequencyFilePath) << \" when using \" << GetKey(config.generateRarityScores) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.eBirdApiKey.empty())\n\t{\n\t\tCerr << \"Must specify \" << GetKey(config.eBirdApiKey) << \" when using \" << GetKey(config.generateRarityScores) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.generateTargetCalendar)\n\t{\n\t\tCerr << \"Cannot specify both \" << GetKey(config.generateRarityScores) << \" and \" << GetKey(config.generateTargetCalendar) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.uniqueObservations != EBDPConfig::UniquenessType::None)\n\t{\n\t\tCerr << \"Cannot specify both \" << GetKey(config.generateRarityScores) << \" and \" << GetKey(config.uniqueObservations) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\treturn configurationOK;\n}\nFixed indentation that was generating compiler warning\/\/ File: ebdpConfigFile.cpp\n\/\/ Date: 9\/27\/2017\n\/\/ Auth: K. Loux\n\/\/ Desc: Configuration file object.\n\n\/\/ Local headers\n#include \"ebdpConfigFile.h\"\n\nvoid EBDPConfigFile::BuildConfigItems()\n{\n\tAddConfigItem(_T(\"OBS_DATA_FILE\"), config.dataFileName);\n\tAddConfigItem(_T(\"OUTPUT_FILE\"), config.outputFileName);\n\n\tAddConfigItem(_T(\"COUNTRY\"), config.countryFilter);\n\tAddConfigItem(_T(\"STATE\"), config.stateFilter);\n\tAddConfigItem(_T(\"COUNTY\"), config.countyFilter);\n\tAddConfigItem(_T(\"LOCATION\"), config.locationFilter);\n\n\tAddConfigItem(_T(\"LIST_TYPE\"), config.listType);\n\n\tAddConfigItem(_T(\"SCORE_RARITIES\"), config.generateRarityScores);\n\tAddConfigItem(_T(\"SPECIES_COUNT_ONLY\"), config.speciesCountOnly);\n\tAddConfigItem(_T(\"INCLUDE_PARTIAL_IDS\"), config.includePartialIDs);\n\n\tAddConfigItem(_T(\"PHOTO_FILE\"), config.photoFileName);\n\tAddConfigItem(_T(\"SHOW_PHOTO_NEEDS\"), config.showOnlyPhotoNeeds);\n\n\tAddConfigItem(_T(\"YEAR\"), config.yearFilter);\n\tAddConfigItem(_T(\"MONTH\"), config.monthFilter);\n\tAddConfigItem(_T(\"WEEK\"), config.weekFilter);\n\tAddConfigItem(_T(\"DAY\"), config.dayFilter);\n\n\tAddConfigItem(_T(\"SORT_FIRST\"), config.primarySort);\n\tAddConfigItem(_T(\"SORT_SECOND\"), config.secondarySort);\n\n\tAddConfigItem(_T(\"SHOW_UNIQUE_OBS\"), config.uniqueObservations);\n\n\tAddConfigItem(_T(\"CALENDAR\"), config.generateTargetCalendar);\n\tAddConfigItem(_T(\"TARGET_AREA\"), config.targetNeedArea);\n\tAddConfigItem(_T(\"TOP_COUNT\"), config.topBirdCount);\n\tAddConfigItem(_T(\"FREQUENCY_FILES\"), config.frequencyFilePath);\n\tAddConfigItem(_T(\"TARGET_INFO_FILE_NAME\"), config.targetInfoFileName);\n\tAddConfigItem(_T(\"RECENT_PERIOD\"), config.recentObservationPeriod);\n\n\tAddConfigItem(_T(\"GOOGLE_MAPS_KEY\"), config.googleMapsAPIKey);\n\tAddConfigItem(_T(\"HOME_LOCATION\"), config.homeLocation);\n\tAddConfigItem(_T(\"EBIRD_API_KEY\"), config.eBirdApiKey);\n\n\tAddConfigItem(_T(\"FIND_MAX_NEEDS\"), config.findMaxNeedsLocations);\n\tAddConfigItem(_T(\"KML_LIBRARY\"), config.kmlLibraryPath);\n\n\tAddConfigItem(_T(\"OAUTH_CLIENT_ID\"), config.oAuthClientId);\n\tAddConfigItem(_T(\"OAUTH_CLIENT_SECRET\"), config.oAuthClientSecret);\n\n\tAddConfigItem(_T(\"DATASET\"), config.eBirdDatasetPath);\n}\n\nvoid EBDPConfigFile::AssignDefaults()\n{\n\tconfig.listType = EBDPConfig::ListType::Life;\n\tconfig.speciesCountOnly = false;\n\tconfig.includePartialIDs = false;\n\n\tconfig.yearFilter = 0;\n\tconfig.monthFilter = 0;\n\tconfig.weekFilter = 0;\n\tconfig.dayFilter = 0;\n\n\tconfig.primarySort = EBDPConfig::SortBy::None;\n\tconfig.secondarySort = EBDPConfig::SortBy::None;\n\n\tconfig.uniqueObservations = EBDPConfig::UniquenessType::None;\n\n\tconfig.targetNeedArea = EBDPConfig::TargetNeedArea::None;\n\tconfig.generateTargetCalendar = false;\n\tconfig.generateRarityScores = false;\n\tconfig.topBirdCount = 20;\n\tconfig.recentObservationPeriod = 15;\n\n\tconfig.showOnlyPhotoNeeds = false;\n\tconfig.findMaxNeedsLocations = false;\n}\n\nbool EBDPConfigFile::ConfigIsOK()\n{\n\tbool configurationOK(true);\n\n\tif (!GeneralConfigIsOK())\n\t\tconfigurationOK = false;\n\n\tif (!FrequencyHarvestConfigIsOK())\n\t\tconfigurationOK = false;\n\n\tif (!TargetCalendarConfigIsOK())\n\t\tconfigurationOK = false;\n\n\tif (!FindMaxNeedsConfigIsOK())\n\t\tconfigurationOK = false;\n\n\tif (!RaritiesConfigIsOK())\n\t\tconfigurationOK = false;\n\n\treturn configurationOK;\n}\n\nbool EBDPConfigFile::FrequencyHarvestConfigIsOK()\n{\n\tbool configurationOK(true);\n\n\tif (!config.eBirdDatasetPath.empty() && config.frequencyFilePath.empty())\n\t{\n\t\tCerr << GetKey(config.eBirdDatasetPath) << \" requires \" << GetKey(config.frequencyFilePath) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\treturn configurationOK;\n}\n\nbool EBDPConfigFile::TargetCalendarConfigIsOK()\n{\n\tif (!config.generateTargetCalendar)\n\t\treturn true;\n \n\tbool configurationOK(true);\n\n\tif (config.frequencyFilePath.empty())\n\t{\n\t\tCerr << \"Must specify \" << GetKey(config.frequencyFilePath) << \" when using \" << GetKey(config.generateTargetCalendar) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.eBirdApiKey.empty())\n\t{\n\t\tCerr << \"Must specify \" << GetKey(config.eBirdApiKey) << \" when using \" << GetKey(config.generateTargetCalendar) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.uniqueObservations != EBDPConfig::UniquenessType::None)\n\t{\n\t\tCerr << \"Cannot specify both \" << GetKey(config.generateTargetCalendar) << \" and \" << GetKey(config.uniqueObservations) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\treturn configurationOK;\n}\n\nbool EBDPConfigFile::FindMaxNeedsConfigIsOK()\n{\n\tif (!config.findMaxNeedsLocations)\n\t\treturn true;\n \n\tbool configurationOK(true);\n\n\tif (config.oAuthClientId.empty() || config.oAuthClientSecret.empty())\n\t{\n\t\tCerr << GetKey(config.findMaxNeedsLocations) << \" requires \"\n\t\t\t<< GetKey(config.oAuthClientId) << \" and \" << GetKey(config.oAuthClientSecret) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.kmlLibraryPath.empty())\n\t{\n\t\tCerr << GetKey(config.findMaxNeedsLocations) << \" requires \" << GetKey(config.kmlLibraryPath) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.eBirdApiKey.empty())\n\t{\n\t\tCerr << GetKey(config.findMaxNeedsLocations) << \" requires \" << GetKey(config.eBirdApiKey) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n \n if (config.frequencyFilePath.empty())\n\t{\n\t\tCerr << \"Must specify \" << GetKey(config.frequencyFilePath) << \" when using \" << GetKey(config.findMaxNeedsLocations) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\treturn configurationOK;\n}\n\nbool EBDPConfigFile::GeneralConfigIsOK()\n{\n\tbool configurationOK(true);\n\n\tif (config.dataFileName.empty())\n\t{\n\t\tCerr << \"Must specify '\" << GetKey(config.dataFileName) << \"'\\n\";\n\t\tconfigurationOK = false;\n\t}\n\n\tif (!config.countryFilter.empty() &&\n\t\tconfig.countryFilter.length() != 2)\n\t{\n\t\tCerr << \"Country (\" << GetKey(config.countryFilter) << \") must be specified using 2-digit abbreviation\\n\";\n\t\tconfigurationOK = false;\n\t}\n\n\tif (!config.stateFilter.empty() &&\n\t\t(config.stateFilter.length() < 2 || config.stateFilter.length() > 3))\n\t{\n\t\tCerr << \"State\/providence (\" << GetKey(config.stateFilter) << \") must be specified using 2- or 3-digit abbreviation\\n\";\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.dayFilter > 31)\n\t{\n\t\tCerr << \"Day (\" << GetKey(config.dayFilter) << \") must be in the range 0 - 31\\n\";\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.monthFilter > 12)\n\t{\n\t\tCerr << \"Month (\" << GetKey(config.monthFilter) << \") must be in the range 0 - 12\\n\";\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.weekFilter > 53)\n\t{\n\t\tCerr << \"Week (\" << GetKey(config.weekFilter) << \") must be in the range 0 - 53\\n\";\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.recentObservationPeriod < 1 || config.recentObservationPeriod > 30)\n\t{\n\t\tCerr << GetKey(config.recentObservationPeriod) << \" must be between 1 and 30\\n\";\n\t\tconfigurationOK = false;\n\t}\n\n\t\/*if (!config.googleMapsAPIKey.empty() && config.homeLocation.empty())\n\t{\n\t\tCerr << \"Must specify \" << GetKey(config.homeLocation) << \" when using \" << GetKey(config.googleMapsAPIKey) << '\\n';\n\t\tconfigurationOK = false;\n\t}*\/\n\n\tif (config.uniqueObservations != EBDPConfig::UniquenessType::None && !config.countryFilter.empty())\n\t{\n\t\tCerr << \"Cannot specify both \" << GetKey(config.countryFilter) << \" and \" << GetKey(config.uniqueObservations) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.showOnlyPhotoNeeds && config.photoFileName.empty())\n\t{\n\t\tCerr << \"Must specify \" << GetKey(config.photoFileName) << \" when using \" << GetKey(config.showOnlyPhotoNeeds) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\treturn configurationOK;\n}\n\nbool EBDPConfigFile::RaritiesConfigIsOK()\n{\n\tif (!config.generateRarityScores)\n\t\treturn true;\n \n\tbool configurationOK(true);\n\n\tif (config.frequencyFilePath.empty())\n\t{\n\t\tCerr << \"Must specify \" << GetKey(config.frequencyFilePath) << \" when using \" << GetKey(config.generateRarityScores) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.eBirdApiKey.empty())\n\t{\n\t\tCerr << \"Must specify \" << GetKey(config.eBirdApiKey) << \" when using \" << GetKey(config.generateRarityScores) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.generateTargetCalendar)\n\t{\n\t\tCerr << \"Cannot specify both \" << GetKey(config.generateRarityScores) << \" and \" << GetKey(config.generateTargetCalendar) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\tif (config.uniqueObservations != EBDPConfig::UniquenessType::None)\n\t{\n\t\tCerr << \"Cannot specify both \" << GetKey(config.generateRarityScores) << \" and \" << GetKey(config.uniqueObservations) << '\\n';\n\t\tconfigurationOK = false;\n\t}\n\n\treturn configurationOK;\n}\n<|endoftext|>"} {"text":"\/*\n * This is part of the FL library, a C++ Bayesian filtering library\n * (https:\/\/github.com\/filtering-library)\n *\n * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)\n * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)\n *\n * Max-Planck Institute for Intelligent Systems, AMD Lab\n * University of Southern California, CLMC Lab\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n *\/\n\n\/**\n * \\file multi_sensor_sigma_point_update_policy.hpp\n * \\date August 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n *\/\n\n#ifndef FL__FILTER__GAUSSIAN__MULTI_SENSOR_SIGMA_POINT_UPDATE_POLICY_HPP\n#define FL__FILTER__GAUSSIAN__MULTI_SENSOR_SIGMA_POINT_UPDATE_POLICY_HPP\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace fl\n{\n\n\/\/ Forward declarations\ntemplate class MultiSensorSigmaPointUpdatePolicy;\n\n\/**\n * \\internal\n *\/\ntemplate <\n typename SigmaPointQuadrature,\n typename NonJoinObservationModel\n>\nclass MultiSensorSigmaPointUpdatePolicy<\n SigmaPointQuadrature,\n NonJoinObservationModel>\n{\n static_assert(\n std::is_base_of<\n internal::JointObservationModelIidType, NonJoinObservationModel\n >::value,\n \"\\n\\n\\n\"\n \"====================================================================\\n\"\n \"= Static Assert: You are using the wrong observation model type =\\n\"\n \"====================================================================\\n\"\n \" Observation model type must be a JointObservationModel<...>. \\n\"\n \" For single observation model, use the regular Gaussian filter \\n\"\n \" or the regular SigmaPointUpdatePolicy if you are specifying \\n\"\n \" the update policy explicitly fo the GaussianFilter. \\n\"\n \"====================================================================\\n\"\n );\n};\n\n\ntemplate <\n typename SigmaPointQuadrature,\n typename MultipleOfLocalObsrvModel\n>\nclass MultiSensorSigmaPointUpdatePolicy<\n SigmaPointQuadrature,\n JointObservationModel>\n : public MultiSensorSigmaPointUpdatePolicy<\n SigmaPointQuadrature,\n NonAdditive>>\n{ };\n\ntemplate <\n typename SigmaPointQuadrature,\n typename MultipleOfLocalObsrvModel\n>\nclass MultiSensorSigmaPointUpdatePolicy<\n SigmaPointQuadrature,\n NonAdditive>>\n : public Descriptor\n{\npublic:\n typedef JointObservationModel JointModel;\n typedef typename MultipleOfLocalObsrvModel::Type LocalModel;\n\n typedef typename JointModel::State State;\n typedef typename JointModel::Obsrv Obsrv;\n typedef typename JointModel::Noise Noise;\n\n enum : signed int\n {\n NumberOfPoints = SigmaPointQuadrature::number_of_points(\n JoinSizes<\n SizeOf::Value,\n SizeOf::Value\n >::Size)\n };\n\n typedef PointSet StatePointSet;\n typedef PointSet NoisePointSet;\n typedef PointSet ObsrvPointSet;\n\n template <\n typename Belief\n >\n void operator()(const JointModel& obsrv_function,\n const SigmaPointQuadrature& quadrature,\n const Belief& prior_belief,\n const Obsrv& obsrv,\n Belief& posterior_belief)\n {\n \/\/ static_assert() is non-additive\n\n INIT_PROFILING\n noise_distr_.dimension(obsrv_function.noise_dimension());\n\n auto&& h = [&](const State& x, const Noise& w)\n {\n return obsrv_function.observation(x, w);\n };\n\n quadrature.propergate_gaussian(h, prior_belief, noise_distr_, X, Y, Z);\n MEASURE(\"Integrate\");\n\n auto&& mu_y = Z.center();\n auto&& mu_x = X.center();\n auto&& Z_c = Z.points();\n auto&& X_c = X.points();\n auto&& W = X.covariance_weights_vector();\n auto cov_xx = (X_c * W.asDiagonal() * X_c.transpose()).eval();\n auto cov_xx_inv = (cov_xx.inverse()).eval();\n auto innovation = (obsrv - mu_y).eval();\n\n auto C = cov_xx_inv;\n auto D = mu_x;\n D.setZero();\n\n const int dim_Z_i = obsrv_function.local_obsrv_model().obsrv_dimension();\n const int obsrv_count = obsrv_function.count_local_models();\n\n MEASURE(\"Preparation\");\n\n\/\/ for (int i = 0; i < obsrv_count; ++i)\n\/\/ {\n\/\/ auto Z_i = Z_c.middleRows(i * dim_Z_i, dim_Z_i).eval();\n\/\/ auto cov_xy_i = (X_c * W.asDiagonal() * Z_i.transpose()).eval();\n\/\/ auto cov_yy_i = (Z_i * W.asDiagonal() * Z_i.transpose()).eval();\n\/\/ auto innov_i = innovation.middleRows(i * dim_Z_i, dim_Z_i).eval();\n\n\/\/ auto A_i = (cov_xy_i.transpose() * cov_xx_inv).eval();\n\n\/\/ auto cov_yy_i_inv_given_x =\n\/\/ (cov_yy_i - cov_xy_i.transpose() * cov_xx_inv * cov_xy_i)\n\/\/ .inverse();\n\n\/\/ auto T = (A_i.transpose() * cov_yy_i_inv_given_x).eval();\n\n\/\/ C += T * A_i;\n\/\/ D += T * innov_i;\n\/\/ }\n\n\n auto Z_0 = Z_c.middleRows(0 * dim_Z_i, dim_Z_i).eval();\n auto cov_xy_0 = (X_c * W.asDiagonal() * Z_0.transpose()).eval();\n auto cov_yy_0 = (Z_0 * W.asDiagonal() * Z_0.transpose()).eval();\n auto innov_0 = innovation.middleRows(0 * dim_Z_i, dim_Z_i).eval();\n auto A_0 = (cov_xy_0.transpose() * cov_xx_inv).eval();\n auto cov_yy_i_inv_given_x =\n (cov_yy_0 - cov_xy_0.transpose() * cov_xx_inv * cov_xy_0)\n .inverse();\n auto T0 = (A_0.transpose() * cov_yy_i_inv_given_x).eval();\n MEASURE(\"Debugging temp preparation\");\n\n\n for (int i = 0; i < obsrv_count; ++i) { auto Z_i = Z_c.middleRows(i * dim_Z_i, dim_Z_i).eval(); }\n MEASURE(\"auto Z_i = ...\");\n\n for (int i = 0; i < obsrv_count; ++i) { auto cov_xy_i = (X_c * W.asDiagonal() * Z_0.transpose()).eval(); }\n MEASURE(\"auto cov_xy_i = ...\");\n\n for (int i = 0; i < obsrv_count; ++i) { auto cov_yy_i = (Z_0 * W.asDiagonal() * Z_0.transpose()).eval(); }\n MEASURE(\"auto cov_yy_i = ...\");\n\n for (int i = 0; i < obsrv_count; ++i){ auto innov_i = innovation.middleRows(i * dim_Z_i, dim_Z_i).eval(); }\n MEASURE(\"auto innov_i = ...\");\n\n for (int i = 0; i < obsrv_count; ++i){ auto A_i = (cov_xy_0.transpose() * cov_xx_inv).eval(); }\n MEASURE(\"auto A_i = ...\");\n\n for (int i = 0; i < obsrv_count; ++i){ auto cov_yy_i_inv_given_x =\n (cov_yy_0 - cov_xy_0.transpose() * cov_xx_inv * cov_xy_0)\n .inverse(); }\n MEASURE(\"auto cov_yy_i_inv_given_x = ...\");\n\n for (int i = 0; i < obsrv_count; ++i){ auto T = (A_0.transpose() * cov_yy_i_inv_given_x).eval(); }\n MEASURE(\"auto T = ...\");\n\n for (int i = 0; i < obsrv_count; ++i){ C += T0 * A_0; }\n MEASURE(\"auto C = ...\");\n\n for (int i = 0; i < obsrv_count; ++i){ D += T0 * innov_0; }\n MEASURE(\"auto D = ...\");\n\n\n\n posterior_belief.covariance(C.inverse());\n MEASURE(\"posterior_belief.covariance(C.inverse())\");\n posterior_belief.mean(mu_x + posterior_belief.covariance() * D);\n MEASURE(\"posterior_belief.mean(mu_x + posterior_belief.covariance() * D)\");\n\n std::cout << \"==================================================================\" << std::endl;\n }\n\n virtual std::string name() const\n {\n return \"MultiSensorSigmaPointUpdatePolicy<\"\n + this->list_arguments(\n \"SigmaPointQuadrature\",\n \"NonAdditive\")\n + \">\";\n }\n\n virtual std::string description() const\n {\n return \"Multi-Sensor Sigma Point based filter update policy \"\n \"for joint observation model of multiple local observation \"\n \"models with non-additive noise.\";\n }\n\nprotected:\n StatePointSet X;\n NoisePointSet Y;\n ObsrvPointSet Z;\n Gaussian noise_distr_;\n};\n\n}\n\n#endif\nUpdated MultiSensor update policy. Minor factoriztion and :lipstick:\/*\n * This is part of the FL library, a C++ Bayesian filtering library\n * (https:\/\/github.com\/filtering-library)\n *\n * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)\n * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)\n *\n * Max-Planck Institute for Intelligent Systems, AMD Lab\n * University of Southern California, CLMC Lab\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n *\/\n\n\/**\n * \\file multi_sensor_sigma_point_update_policy.hpp\n * \\date August 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n *\/\n\n#ifndef FL__FILTER__GAUSSIAN__MULTI_SENSOR_SIGMA_POINT_UPDATE_POLICY_HPP\n#define FL__FILTER__GAUSSIAN__MULTI_SENSOR_SIGMA_POINT_UPDATE_POLICY_HPP\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace fl\n{\n\n\/\/ Forward declarations\ntemplate class MultiSensorSigmaPointUpdatePolicy;\n\n\/**\n * \\internal\n *\/\ntemplate <\n typename SigmaPointQuadrature,\n typename NonJoinObservationModel\n>\nclass MultiSensorSigmaPointUpdatePolicy<\n SigmaPointQuadrature,\n NonJoinObservationModel>\n{\n static_assert(\n std::is_base_of<\n internal::JointObservationModelIidType, NonJoinObservationModel\n >::value,\n \"\\n\\n\\n\"\n \"====================================================================\\n\"\n \"= Static Assert: You are using the wrong observation model type =\\n\"\n \"====================================================================\\n\"\n \" Observation model type must be a JointObservationModel<...>. \\n\"\n \" For single observation model, use the regular Gaussian filter \\n\"\n \" or the regular SigmaPointUpdatePolicy if you are specifying \\n\"\n \" the update policy explicitly fo the GaussianFilter. \\n\"\n \"====================================================================\\n\"\n );\n};\n\n\ntemplate <\n typename SigmaPointQuadrature,\n typename MultipleOfLocalObsrvModel\n>\nclass MultiSensorSigmaPointUpdatePolicy<\n SigmaPointQuadrature,\n JointObservationModel>\n : public MultiSensorSigmaPointUpdatePolicy<\n SigmaPointQuadrature,\n NonAdditive>>\n{ };\n\ntemplate <\n typename SigmaPointQuadrature,\n typename MultipleOfLocalObsrvModel\n>\nclass MultiSensorSigmaPointUpdatePolicy<\n SigmaPointQuadrature,\n NonAdditive>>\n : public Descriptor\n{\npublic:\n typedef JointObservationModel JointModel;\n typedef typename MultipleOfLocalObsrvModel::Type LocalModel;\n\n typedef typename JointModel::State State;\n typedef typename JointModel::Obsrv Obsrv;\n typedef typename JointModel::Noise Noise;\n\n typedef typename Traits::LocalObsrv LocalObsrv;\n typedef typename Traits::LocalNoise LocalObsrvNoise;\n\n enum : signed int\n {\n NumberOfPoints = SigmaPointQuadrature::number_of_points(\n JoinSizes<\n SizeOf::Value,\n SizeOf::Value\n >::Size)\n };\n\n typedef PointSet StatePointSet;\n typedef PointSet LocalObsrvPointSet;\n typedef PointSet LocalNoisePointSet;\n\n template <\n typename Belief\n >\n void operator()(JointModel& obsrv_function,\n const SigmaPointQuadrature& quadrature,\n const Belief& prior_belief,\n const Obsrv& y,\n Belief& posterior_belief)\n {\n quadrature.transform_to_points(prior_belief, noise_distr_, p_X, p_Q);\n\n auto& model = obsrv_function.local_obsrv_model();\n auto&& h = [&](const State& x, const LocalObsrvNoise& w)\n {\n return model.observation(x, w);\n };\n\n auto&& mu_x = p_X.center();\n auto&& X = p_X.points();\n auto c_xx = cov(X, X);\n auto c_xx_inv = c_xx.inverse().eval();\n\n auto C = c_xx_inv;\n auto D = State();\n D.setZero(mu_x.size());\n\n const int sensors = obsrv_function.count_local_models();\n for (int i = 0; i < sensors; ++i)\n {\n model.id(i);\n quadrature.propergate_points(h, p_X, p_Q, p_Y);\n\n auto mu_y = p_Y.center();\n auto Y = p_Y.points();\n auto c_yy = cov(Y, Y);\n auto c_xy = cov(X, Y);\n auto c_yx = c_xy.transpose();\n auto A_i = (c_yx * c_xx_inv).eval();\n auto c_yy_given_x_inv = (c_yy - c_yx * c_xx_inv * c_xy).inverse();\n auto T = (A_i.transpose() * c_yy_given_x_inv).eval();\n\n C += T * A_i;\n D += T * (y.middleRows(i * mu_y.size(), mu_y.size()) - mu_y);\n }\n\n posterior_belief.covariance(C.inverse());\n posterior_belief.mean(mu_x + posterior_belief.covariance() * D);\n }\n\n virtual std::string name() const\n {\n return \"MultiSensorSigmaPointUpdatePolicy<\"\n + this->list_arguments(\n \"SigmaPointQuadrature\",\n \"NonAdditive\")\n + \">\";\n }\n\n virtual std::string description() const\n {\n return \"Multi-Sensor Sigma Point based filter update policy \"\n \"for joint observation model of multiple local observation \"\n \"models with non-additive noise.\";\n }\n\nprivate:\n template \n auto cov(const A& a, const B& b) -> decltype((a * b.transpose()).eval())\n {\n auto&& W = p_X.covariance_weights_vector().asDiagonal();\n auto c = (a * W * b.transpose()).eval();\n return c;\n }\n\nprotected:\n StatePointSet p_X;\n LocalNoisePointSet p_Q;\n LocalObsrvPointSet p_Y;\n Gaussian noise_distr_;\n};\n\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/ $Id$\n\/\/ -*-C++-*-\n\/\/ * BeginRiceCopyright *****************************************************\n\/\/ \n\/\/ Copyright ((c)) 2002, Rice University \n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/ \n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ \n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ \n\/\/ * Neither the name of Rice University (RICE) nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/ \n\/\/ This software is provided by RICE and contributors \"as is\" and any\n\/\/ express or implied warranties, including, but not limited to, the\n\/\/ implied warranties of merchantability and fitness for a particular\n\/\/ purpose are disclaimed. In no event shall RICE or contributors be\n\/\/ liable for any direct, indirect, incidental, special, exemplary, or\n\/\/ consequential damages (including, but not limited to, procurement of\n\/\/ substitute goods or services; loss of use, data, or profits; or\n\/\/ business interruption) however caused and on any theory of liability,\n\/\/ whether in contract, strict liability, or tort (including negligence\n\/\/ or otherwise) arising in any way out of the use of this software, even\n\/\/ if advised of the possibility of such damage. \n\/\/ \n\/\/ ******************************************************* EndRiceCopyright *\n\n\/\/***************************************************************************\n\/\/\n\/\/ File:\n\/\/ BloopIRInterface.h\n\/\/\n\/\/ Purpose:\n\/\/ A derivation of the IR interface for the ISA (disassembler) class\n\/\/ of bloop.\n\/\/\n\/\/ Note: many stubs still exist.\n\/\/\n\/\/ Description:\n\/\/ [The set of functions, macros, etc. defined in the file]\n\/\/\n\/\/***************************************************************************\n\n#ifndef BloopIRInterface_h\n#define BloopIRInterface_h\n\n\/\/************************* System Include Files ****************************\n\n#include \n#include \n\n\/\/*************************** User Include Files ****************************\n\n\/\/ OpenAnalysis headers.\n\/\/ Use OA_IRHANDLETYPE_SZ64: size of bfd_vma\/Addr\n#include \n#include \n \n#include \n#include \n#include \n#include \n#include \n\n\/\/*************************** Forward Declarations ***************************\n\nclass BloopIRStmtIterator: public IRStmtIterator {\npublic:\n BloopIRStmtIterator (Procedure &_p) : pii(_p) { };\n ~BloopIRStmtIterator () {};\n\n StmtHandle Current () { return (StmtHandle)(pii.Current()); };\n bool IsValid () { return pii.IsValid(); };\n void operator++ () { ++pii; };\nprivate:\n ProcedureInstructionIterator pii;\n};\n\n\nclass BloopIRUseDefIterator: public IRUseDefIterator {\npublic:\n BloopIRUseDefIterator (Instruction *insn, int uses_or_defs);\n BloopIRUseDefIterator () { BriefAssertion (0); }\n ~BloopIRUseDefIterator () {};\n\n LeafHandle Current () { return 0; };\n bool IsValid () { return false; };\n void operator++ () { };\nprivate:\n};\n\n\/\/*************************** Forward Declarations ***************************\n\nclass BloopIRInterface : public IRInterface {\npublic:\n BloopIRInterface (Procedure *_p);\n BloopIRInterface () { BriefAssertion(0); }\n ~BloopIRInterface () {}\n\n \/\/------------------------------\n \/\/ General - all statement types\n \/\/------------------------------\n IRStmtType GetStmtType (StmtHandle);\n StmtLabel GetLabel (StmtHandle);\n\n \/\/------------------------------\n \/\/ For procedures, compound statements. \n \/\/------------------------------\n IRStmtIterator *ProcBody(ProcHandle h) \n { BriefAssertion(false); return NULL; }\n IRStmtIterator *GetFirstInCompound (StmtHandle h);\n\n \/\/------------------------------\n \/\/ Loops\n \/\/------------------------------\n IRStmtIterator *LoopBody(StmtHandle h);\n StmtHandle LoopHeader (StmtHandle h);\n bool LoopIterationsDefinedAtEntry (StmtHandle h);\n ExprHandle GetLoopCondition (StmtHandle h); \n StmtHandle GetLoopIncrement (StmtHandle h);\n\n \/\/------------------------------\n \/\/ invariant: a two-way conditional or a multi-way conditional MUST provide\n \/\/ provided either a target, or a target label\n \/\/------------------------------\n\n \/\/------------------------------\n \/\/ Structured two-way conditionals\n \/\/------------------------------\n IRStmtIterator *TrueBody (StmtHandle h);\n IRStmtIterator *ElseBody (StmtHandle h);\n\n \/\/------------------------------\n \/\/ Structured multiway conditionals\n \/\/------------------------------\n int NumMultiCases (StmtHandle h);\n \/\/ condition for multi body \n ExprHandle GetSMultiCondition (StmtHandle h, int bodyIndex);\n \/\/ multi-way beginning expression\n ExprHandle GetMultiExpr (StmtHandle h);\n IRStmtIterator *MultiBody (StmtHandle h, int bodyIndex);\n bool IsBreakImplied (StmtHandle multicond);\n IRStmtIterator *GetMultiCatchall (StmtHandle h);\n\n \/\/------------------------------\n \/\/ Unstructured two-way conditionals: \n \/\/------------------------------\n \/\/ two-way branch, loop continue\n StmtLabel GetTargetLabel (StmtHandle h, int n);\n ExprHandle GetCondition (StmtHandle h);\n\n \/\/------------------------------\n \/\/ Unstructured multi-way conditionals\n \/\/------------------------------\n int NumUMultiTargets (StmtHandle h);\n StmtLabel GetUMultiTargetLabel (StmtHandle h, int targetIndex);\n StmtLabel GetUMultiCatchallLabel (StmtHandle h);\n ExprHandle GetUMultiCondition (StmtHandle h, int targetIndex);\n\n \/\/------------------------------\n \/\/ Special\n \/\/------------------------------\n bool ParallelWithSuccessor(StmtHandle h) { return false; }\n\n \/\/ Given an unstructured branch\/jump statement, return the number\n \/\/ of delay slots.\n int NumberOfDelaySlots(StmtHandle h);\n \n \/\/------------------------------\n \/\/ Obtain uses and defs\n \/\/------------------------------\n IRProcCallIterator *GetProcCalls(StmtHandle h) \n { BriefAssertion(false); return NULL; }\n IRUseDefIterator *GetUses (StmtHandle h);\n IRUseDefIterator *GetDefs (StmtHandle h);\n\n \/\/------------------------------\n \/\/ Symbol Handles\n \/\/------------------------------\n SymHandle GetProcSymHandle(ProcHandle h) { return (SymHandle)0; }\n SymHandle GetSymHandle (LeafHandle vh) { return (SymHandle)0; }\n const char *GetSymNameFromSymHandle (SymHandle sh) { return \"\"; }\n\n \/\/------------------------------\n \/\/ Debugging\n \/\/------------------------------\n void PrintLeaf (LeafHandle vh, ostream & os) { };\n void Dump (StmtHandle stmt, ostream& os);\n\nprivate:\n Procedure *proc;\n std::set branchTargetSet;\n};\n\n#endif \/\/ BloopIRInterface_h\nCoordinate with updates to IRInterface\/\/ $Id$\n\/\/ -*-C++-*-\n\/\/ * BeginRiceCopyright *****************************************************\n\/\/ \n\/\/ Copyright ((c)) 2002, Rice University \n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/ \n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ \n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ \n\/\/ * Neither the name of Rice University (RICE) nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/ \n\/\/ This software is provided by RICE and contributors \"as is\" and any\n\/\/ express or implied warranties, including, but not limited to, the\n\/\/ implied warranties of merchantability and fitness for a particular\n\/\/ purpose are disclaimed. In no event shall RICE or contributors be\n\/\/ liable for any direct, indirect, incidental, special, exemplary, or\n\/\/ consequential damages (including, but not limited to, procurement of\n\/\/ substitute goods or services; loss of use, data, or profits; or\n\/\/ business interruption) however caused and on any theory of liability,\n\/\/ whether in contract, strict liability, or tort (including negligence\n\/\/ or otherwise) arising in any way out of the use of this software, even\n\/\/ if advised of the possibility of such damage. \n\/\/ \n\/\/ ******************************************************* EndRiceCopyright *\n\n\/\/***************************************************************************\n\/\/\n\/\/ File:\n\/\/ BloopIRInterface.h\n\/\/\n\/\/ Purpose:\n\/\/ A derivation of the IR interface for the ISA (disassembler) class\n\/\/ of bloop.\n\/\/\n\/\/ Note: many stubs still exist.\n\/\/\n\/\/ Description:\n\/\/ [The set of functions, macros, etc. defined in the file]\n\/\/\n\/\/***************************************************************************\n\n#ifndef BloopIRInterface_h\n#define BloopIRInterface_h\n\n\/\/************************* System Include Files ****************************\n\n#include \n#include \n\n\/\/*************************** User Include Files ****************************\n\n\/\/ OpenAnalysis headers.\n\/\/ Use OA_IRHANDLETYPE_SZ64: size of bfd_vma\/Addr\n#include \n#include \n \n#include \n#include \n#include \n#include \n#include \n\n\/\/*************************** Forward Declarations ***************************\n\nclass BloopIRStmtIterator: public IRStmtIterator {\npublic:\n BloopIRStmtIterator (Procedure &_p) : pii(_p) { }\n ~BloopIRStmtIterator () { }\n\n StmtHandle Current () { return (StmtHandle)(pii.Current()); }\n bool IsValid () { return pii.IsValid(); }\n void operator++ () { ++pii; }\n\n void Reset() { pii.Reset(); }\n \nprivate:\n ProcedureInstructionIterator pii;\n};\n\n\nclass BloopIRUseDefIterator: public IRUseDefIterator {\npublic:\n BloopIRUseDefIterator (Instruction *insn, int uses_or_defs);\n BloopIRUseDefIterator () { BriefAssertion (0); }\n ~BloopIRUseDefIterator () { }\n\n LeafHandle Current () { return 0; }\n bool IsValid () { return false; }\n void operator++ () { }\n\n void Reset() { }\n\nprivate:\n};\n\n\/\/*************************** Forward Declarations ***************************\n\nclass BloopIRInterface : public IRInterface {\npublic:\n BloopIRInterface (Procedure *_p);\n BloopIRInterface () { BriefAssertion(0); }\n ~BloopIRInterface () { }\n\n \/\/--------------------------------------------------------\n \/\/ Procedures and call sites\n \/\/--------------------------------------------------------\n IRProcType GetProcType(ProcHandle h) \n { BriefAssertion(0); return ProcType_ILLEGAL; }\n IRStmtIterator *ProcBody(ProcHandle h) \n { BriefAssertion(0); return NULL; }\n IRCallsiteIterator *GetCallsites(StmtHandle h) \n { BriefAssertion(0); return NULL; } \n IRCallsiteParamIterator *GetCallsiteParams(ExprHandle h) \n { BriefAssertion(0); return NULL; } \n bool IsParamProcRef(ExprHandle h) \n { BriefAssertion(0); return false; }\n virtual bool IsCallThruProcParam(ExprHandle h) \n { BriefAssertion(0); return false; }\n\n \/\/--------------------------------------------------------\n \/\/ Statements: General\n \/\/--------------------------------------------------------\n IRStmtType GetStmtType (StmtHandle);\n StmtLabel GetLabel (StmtHandle);\n IRStmtIterator *GetFirstInCompound (StmtHandle h);\n\n \/\/--------------------------------------------------------\n \/\/ Loops\n \/\/--------------------------------------------------------\n IRStmtIterator *LoopBody(StmtHandle h);\n StmtHandle LoopHeader (StmtHandle h);\n bool LoopIterationsDefinedAtEntry (StmtHandle h);\n ExprHandle GetLoopCondition (StmtHandle h); \n StmtHandle GetLoopIncrement (StmtHandle h);\n\n \/\/--------------------------------------------------------\n \/\/ invariant: a two-way conditional or a multi-way conditional MUST provide\n \/\/ provided either a target, or a target label\n \/\/--------------------------------------------------------\n\n \/\/--------------------------------------------------------\n \/\/ Structured two-way conditionals\n \/\/--------------------------------------------------------\n IRStmtIterator *TrueBody (StmtHandle h);\n IRStmtIterator *ElseBody (StmtHandle h);\n\n \/\/--------------------------------------------------------\n \/\/ Structured multiway conditionals\n \/\/--------------------------------------------------------\n int NumMultiCases (StmtHandle h);\n \/\/ condition for multi body \n ExprHandle GetSMultiCondition (StmtHandle h, int bodyIndex);\n \/\/ multi-way beginning expression\n ExprHandle GetMultiExpr (StmtHandle h);\n IRStmtIterator *MultiBody (StmtHandle h, int bodyIndex);\n bool IsBreakImplied (StmtHandle multicond);\n IRStmtIterator *GetMultiCatchall (StmtHandle h);\n\n \/\/--------------------------------------------------------\n \/\/ Unstructured two-way conditionals: \n \/\/--------------------------------------------------------\n \/\/ two-way branch, loop continue\n StmtLabel GetTargetLabel (StmtHandle h, int n);\n ExprHandle GetCondition (StmtHandle h);\n\n \/\/--------------------------------------------------------\n \/\/ Unstructured multi-way conditionals\n \/\/--------------------------------------------------------\n int NumUMultiTargets (StmtHandle h);\n StmtLabel GetUMultiTargetLabel (StmtHandle h, int targetIndex);\n StmtLabel GetUMultiCatchallLabel (StmtHandle h);\n ExprHandle GetUMultiCondition (StmtHandle h, int targetIndex);\n\n \/\/--------------------------------------------------------\n \/\/ Special\n \/\/--------------------------------------------------------\n bool ParallelWithSuccessor(StmtHandle h) { return false; }\n\n \/\/ Given an unstructured branch\/jump statement, return the number\n \/\/ of delay slots.\n int NumberOfDelaySlots(StmtHandle h);\n \n \/\/--------------------------------------------------------\n \/\/ Obtain uses and defs\n \/\/--------------------------------------------------------\n IRUseDefIterator *GetUses (StmtHandle h);\n IRUseDefIterator *GetDefs (StmtHandle h);\n\n \/\/--------------------------------------------------------\n \/\/ Symbol Handles\n \/\/--------------------------------------------------------\n SymHandle GetProcSymHandle(ProcHandle h) \n { BriefAssertion(0); return (SymHandle)0; }\n SymHandle GetSymHandle (LeafHandle vh) { return (SymHandle)0; }\n const char *GetSymNameFromSymHandle (SymHandle sh) { return \"\"; }\n\n \/\/--------------------------------------------------------\n \/\/ Debugging\n \/\/--------------------------------------------------------\n void PrintLeaf (LeafHandle vh, ostream & os) { };\n void Dump (StmtHandle stmt, ostream& os);\n\nprivate:\n Procedure *proc;\n std::set branchTargetSet;\n};\n\n#endif \/\/ BloopIRInterface_h\n<|endoftext|>"} {"text":"\/\/========================================================\r\n\/\/ Hazi feladat keret.\t\t \r\n\/\/ A \/\/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n\/\/ sorokon beluli reszben celszeru garazdalkodni, mert\r\n\/\/ a tobbit ugyis toroljuk.\r\n\/\/ A Hazi feladat csak ebben a fajlban lehet\r\n\/\/ Tilos:\r\n\/\/ - mast \"beincludolni\", illetve mas konyvtarat hasznalni\r\n\/\/ - faljmuveleteket vegezni\r\n\/\/========================================================\r\n\r\n#include \r\n#include \r\n\r\n#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)\r\n\/\/ MsWindows-on ez is kell\r\n#include \t\r\n#else \/\/ g++ nem fordit a stanard include-ok nelkul :-\/\r\n#include \r\n#endif \/\/ Win32 platform\r\n\r\n#include \r\n#include \r\n\/\/ A GLUT-ot le kell tolteni: http:\/\/www.opengl.org\/resources\/libraries\/glut\/\r\n#include \t\r\n#include \r\n\r\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n\/\/ Innentol modosithatod...\r\n\r\n\/\/--------------------------------------------------------\r\n\/\/ Nev:\t\t \r\n\/\/ Neptun:\r\n\/\/--------------------------------------------------------\r\n\r\n#define ARRAY_SIZE(x) (sizeof(x)\/sizeof(x[0]))\r\n\r\nclass Vector {\r\npublic:\r\n\tfloat x, y, z;\r\n\r\n\tVector(float x0, float y0, float z0) {\r\n\t\tx = x0;\r\n\t\ty = y0;\r\n\t\tz = z0;\r\n\t}\r\n\r\n\tVector operator+(const Vector& v) {\r\n\t\treturn Vector(x + v.x, y + v.y, z + v.z);\r\n\t}\r\n\r\n\tVector operator*(float f) {\r\n\t\treturn Vector(x * f, y * f, z * f);\r\n\t}\r\n};\r\n\r\nclass Matrix {\r\npublic:\r\n\tfloat m[4][4];\r\n\r\n\tvoid Clear() {\r\n\t\tmemset(&m[0][0], 0, sizeof(m));\r\n\t}\r\n\r\n\tvoid LoadIdentify() {\r\n\t\tClear();\r\n\t\tm[0][0] = m[1][1] = m[2][2] = m[3][3] = 1;\r\n\t}\r\n\r\n\tVector operator*(const Vector& v) {\r\n\t\tfloat Xh = m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z + m[0][3];\r\n\t\tfloat Yh = m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z + m[1][3];\r\n\t\tfloat Zh = m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z + m[2][3];\r\n\t\tfloat h = m[3][0] * v.x + m[3][1] * v.y + m[3][2] * v.z + m[3][3];\r\n\r\n\t\treturn Vector(Xh\/h, Yh\/h, Zh\/h);\r\n\t}\r\n};\r\n\r\nenum {\r\n\tNOOP = 0,\r\n\tSCALE,\r\n\tROTATE,\r\n\tSHIFT\r\n};\r\n\r\nint trans_state = NOOP;\r\n\r\n\/\/ csak mert math.ht nemszabad ;-\/\r\n# define M_PI 3.14159265358979323846\r\n\r\nconst Vector* points[2][7];\r\n\r\nMatrix* transs[4];\r\n\r\nvoid onInitialization( ) {\r\n\tpoints[0][0] = new Vector(160, 20, 0);\r\n\tpoints[0][1] = new Vector(250, 80, 0);\r\n\tpoints[0][2] = new Vector(270, 20, 0);\r\n\tpoints[0][3] = new Vector(360, 80, 0);\r\n\tpoints[0][4] = new Vector(390, 20, 0);\r\n\tpoints[0][5] = new Vector(470, 80, 0);\r\n\tpoints[0][6] = new Vector(490, 20, 0);\r\n\r\n\tpoints[1][0] = new Vector(160, 120, 0);\r\n\tpoints[1][1] = new Vector(250, 180, 0);\r\n\tpoints[1][2] = new Vector(270, 120, 0);\r\n\tpoints[1][3] = new Vector(360, 180, 0);\r\n\tpoints[1][4] = new Vector(390, 120, 0);\r\n\tpoints[1][5] = new Vector(470, 180, 0);\r\n\tpoints[1][6] = new Vector(490, 120, 0);\r\n\r\n\t\/*\r\n\t * 1 0 0 0\r\n\t * 0 1 0 0\r\n\t * 0 0 1 0\r\n\t * 0 0 0 1\r\n\t *\/\r\n\ttranss[NOOP] = new Matrix();\r\n\ttranss[NOOP]->LoadIdentify();\r\n\r\n\t\/*\r\n\t * 0.5 0 0 0\r\n\t * 0 0.5 0 0\r\n\t * 0 0 0.5 0\r\n\t * 0 0 0 1\r\n\t *\/\r\n\ttranss[SCALE] = new Matrix();\r\n\ttranss[SCALE]->LoadIdentify();\r\n\ttranss[SCALE]->m[0][0] = 0.5;\r\n\ttranss[SCALE]->m[1][1] = 0.5;\r\n\ttranss[SCALE]->m[2][2] = 0.5;\r\n\r\n\t\/*\r\n\t * cos sin 0 0\r\n\t * -sin cos 0 0\r\n\t * 0 0 1 0\r\n\t * 0 0 0 1\r\n\t *\/\r\n\tfloat angle = M_PI\/4;\r\n\ttranss[ROTATE] = new Matrix();\r\n\ttranss[ROTATE]->LoadIdentify();\r\n\ttranss[ROTATE]->m[0][0] = cosf(angle);\r\n\ttranss[ROTATE]->m[0][1] = -sinf(angle);\r\n\ttranss[ROTATE]->m[1][0] = sinf(angle);\r\n\ttranss[ROTATE]->m[1][1] = cosf(angle);\r\n\r\n\t\/*\r\n\t * 1 0 0 0\r\n\t * 0 1 0 0\r\n\t * 0 0 1 0\r\n\t * px py pz 1\r\n\t *\/\r\n\ttranss[SHIFT] = new Matrix();\r\n\ttranss[SHIFT]->LoadIdentify();\r\n\ttranss[SHIFT]->m[1][3] = 100;\r\n\tgluOrtho2D(0., 500., 0., 500.);\r\n}\r\n\r\nvoid onDisplay( ) {\r\n\tglClearColor(0.1f, 0.2f, 0.3f, 1.0f);\r\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\r\n\tglColor4d(0.9f, 0.8f, 0.7f, 1.0f);\r\n\r\n\tfor (int i = 0; i < ARRAY_SIZE(points); i++) {\r\n\t\tglBegin(GL_LINE_STRIP);\r\n\t\tfor (int j = 0; j < ARRAY_SIZE(points[i]); j++) {\r\n\t\t\tVector v = *transs[trans_state] * *points[i][j];\r\n\t\t\tglVertex2d(v.x, v.y);\r\n\t\t}\r\n\t\tglEnd();\r\n\t}\r\n\r\n\t\/\/ Buffercsere: rajzolas vege\r\n\tglFinish();\r\n\tglutSwapBuffers();\r\n}\r\n\r\nvoid onMouse(int button, int state, int x, int y) {\r\n\t\/\/ A GLUT_LEFT_BUTTON \/ GLUT_RIGHT_BUTTON\r\n\t\/\/ ill. a GLUT_DOWN \/ GLUT_UP makrokat hasznald.\r\n}\r\n\r\nvoid onIdle( ) {\r\n}\r\n\r\nvoid onKeyboard(unsigned char key, int x, int y) {\r\n\tif (key == 's')\r\n\t\ttrans_state = (trans_state + 1) % 4;\r\n\tonDisplay();\r\n}\r\n\r\n\/\/ ...Idaig modosithatod\r\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n\r\nint main(int argc, char **argv) {\r\n\tglutInit(&argc, argv);\r\n\tglutInitWindowSize(600, 600);\r\n\tglutInitWindowPosition(100, 100);\r\n\tglutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);\r\n\r\n\tglutCreateWindow(\"Grafika hazi feladat\");\r\n\r\n\tglMatrixMode(GL_MODELVIEW);\r\n\tglLoadIdentity();\r\n\tglMatrixMode(GL_PROJECTION);\r\n\tglLoadIdentity();\r\n\r\n\tonInitialization();\r\n\r\n\tglutDisplayFunc(onDisplay);\r\n\tglutMouseFunc(onMouse);\r\n\tglutIdleFunc(onIdle);\r\n\tglutKeyboardFunc(onKeyboard);\r\n\r\n\tglutMainLoop();\r\n\t\r\n\treturn 0;\t\r\n}\r\nnev neptunkod\/\/========================================================\r\n\/\/ Hazi feladat keret.\t\t \r\n\/\/ A \/\/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n\/\/ sorokon beluli reszben celszeru garazdalkodni, mert\r\n\/\/ a tobbit ugyis toroljuk.\r\n\/\/ A Hazi feladat csak ebben a fajlban lehet\r\n\/\/ Tilos:\r\n\/\/ - mast \"beincludolni\", illetve mas konyvtarat hasznalni\r\n\/\/ - faljmuveleteket vegezni\r\n\/\/========================================================\r\n\r\n#include \r\n#include \r\n\r\n#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)\r\n\/\/ MsWindows-on ez is kell\r\n#include \t\r\n#else \/\/ g++ nem fordit a stanard include-ok nelkul :-\/\r\n#include \r\n#endif \/\/ Win32 platform\r\n\r\n#include \r\n#include \r\n\/\/ A GLUT-ot le kell tolteni: http:\/\/www.opengl.org\/resources\/libraries\/glut\/\r\n#include \t\r\n#include \r\n\r\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n\/\/ Innentol modosithatod...\r\n\r\n\/\/--------------------------------------------------------\r\n\/\/ Nev: Vajna Miklos\r\n\/\/ Neptun: AYU9RZ\r\n\/\/--------------------------------------------------------\r\n\r\n#define ARRAY_SIZE(x) (sizeof(x)\/sizeof(x[0]))\r\n\r\nclass Vector {\r\npublic:\r\n\tfloat x, y, z;\r\n\r\n\tVector(float x0, float y0, float z0) {\r\n\t\tx = x0;\r\n\t\ty = y0;\r\n\t\tz = z0;\r\n\t}\r\n\r\n\tVector operator+(const Vector& v) {\r\n\t\treturn Vector(x + v.x, y + v.y, z + v.z);\r\n\t}\r\n\r\n\tVector operator*(float f) {\r\n\t\treturn Vector(x * f, y * f, z * f);\r\n\t}\r\n};\r\n\r\nclass Matrix {\r\npublic:\r\n\tfloat m[4][4];\r\n\r\n\tvoid Clear() {\r\n\t\tmemset(&m[0][0], 0, sizeof(m));\r\n\t}\r\n\r\n\tvoid LoadIdentify() {\r\n\t\tClear();\r\n\t\tm[0][0] = m[1][1] = m[2][2] = m[3][3] = 1;\r\n\t}\r\n\r\n\tVector operator*(const Vector& v) {\r\n\t\tfloat Xh = m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z + m[0][3];\r\n\t\tfloat Yh = m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z + m[1][3];\r\n\t\tfloat Zh = m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z + m[2][3];\r\n\t\tfloat h = m[3][0] * v.x + m[3][1] * v.y + m[3][2] * v.z + m[3][3];\r\n\r\n\t\treturn Vector(Xh\/h, Yh\/h, Zh\/h);\r\n\t}\r\n};\r\n\r\nenum {\r\n\tNOOP = 0,\r\n\tSCALE,\r\n\tROTATE,\r\n\tSHIFT\r\n};\r\n\r\nint trans_state = NOOP;\r\n\r\n\/\/ csak mert math.ht nemszabad ;-\/\r\n# define M_PI 3.14159265358979323846\r\n\r\nconst Vector* points[2][7];\r\n\r\nMatrix* transs[4];\r\n\r\nvoid onInitialization( ) {\r\n\tpoints[0][0] = new Vector(160, 20, 0);\r\n\tpoints[0][1] = new Vector(250, 80, 0);\r\n\tpoints[0][2] = new Vector(270, 20, 0);\r\n\tpoints[0][3] = new Vector(360, 80, 0);\r\n\tpoints[0][4] = new Vector(390, 20, 0);\r\n\tpoints[0][5] = new Vector(470, 80, 0);\r\n\tpoints[0][6] = new Vector(490, 20, 0);\r\n\r\n\tpoints[1][0] = new Vector(160, 120, 0);\r\n\tpoints[1][1] = new Vector(250, 180, 0);\r\n\tpoints[1][2] = new Vector(270, 120, 0);\r\n\tpoints[1][3] = new Vector(360, 180, 0);\r\n\tpoints[1][4] = new Vector(390, 120, 0);\r\n\tpoints[1][5] = new Vector(470, 180, 0);\r\n\tpoints[1][6] = new Vector(490, 120, 0);\r\n\r\n\t\/*\r\n\t * 1 0 0 0\r\n\t * 0 1 0 0\r\n\t * 0 0 1 0\r\n\t * 0 0 0 1\r\n\t *\/\r\n\ttranss[NOOP] = new Matrix();\r\n\ttranss[NOOP]->LoadIdentify();\r\n\r\n\t\/*\r\n\t * 0.5 0 0 0\r\n\t * 0 0.5 0 0\r\n\t * 0 0 0.5 0\r\n\t * 0 0 0 1\r\n\t *\/\r\n\ttranss[SCALE] = new Matrix();\r\n\ttranss[SCALE]->LoadIdentify();\r\n\ttranss[SCALE]->m[0][0] = 0.5;\r\n\ttranss[SCALE]->m[1][1] = 0.5;\r\n\ttranss[SCALE]->m[2][2] = 0.5;\r\n\r\n\t\/*\r\n\t * cos sin 0 0\r\n\t * -sin cos 0 0\r\n\t * 0 0 1 0\r\n\t * 0 0 0 1\r\n\t *\/\r\n\tfloat angle = M_PI\/4;\r\n\ttranss[ROTATE] = new Matrix();\r\n\ttranss[ROTATE]->LoadIdentify();\r\n\ttranss[ROTATE]->m[0][0] = cosf(angle);\r\n\ttranss[ROTATE]->m[0][1] = -sinf(angle);\r\n\ttranss[ROTATE]->m[1][0] = sinf(angle);\r\n\ttranss[ROTATE]->m[1][1] = cosf(angle);\r\n\r\n\t\/*\r\n\t * 1 0 0 0\r\n\t * 0 1 0 0\r\n\t * 0 0 1 0\r\n\t * px py pz 1\r\n\t *\/\r\n\ttranss[SHIFT] = new Matrix();\r\n\ttranss[SHIFT]->LoadIdentify();\r\n\ttranss[SHIFT]->m[1][3] = 100;\r\n\tgluOrtho2D(0., 500., 0., 500.);\r\n}\r\n\r\nvoid onDisplay( ) {\r\n\tglClearColor(0.1f, 0.2f, 0.3f, 1.0f);\r\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\r\n\tglColor4d(0.9f, 0.8f, 0.7f, 1.0f);\r\n\r\n\tfor (int i = 0; i < ARRAY_SIZE(points); i++) {\r\n\t\tglBegin(GL_LINE_STRIP);\r\n\t\tfor (int j = 0; j < ARRAY_SIZE(points[i]); j++) {\r\n\t\t\tVector v = *transs[trans_state] * *points[i][j];\r\n\t\t\tglVertex2d(v.x, v.y);\r\n\t\t}\r\n\t\tglEnd();\r\n\t}\r\n\r\n\t\/\/ Buffercsere: rajzolas vege\r\n\tglFinish();\r\n\tglutSwapBuffers();\r\n}\r\n\r\nvoid onMouse(int button, int state, int x, int y) {\r\n\t\/\/ A GLUT_LEFT_BUTTON \/ GLUT_RIGHT_BUTTON\r\n\t\/\/ ill. a GLUT_DOWN \/ GLUT_UP makrokat hasznald.\r\n}\r\n\r\nvoid onIdle( ) {\r\n}\r\n\r\nvoid onKeyboard(unsigned char key, int x, int y) {\r\n\tif (key == 's')\r\n\t\ttrans_state = (trans_state + 1) % 4;\r\n\tonDisplay();\r\n}\r\n\r\n\/\/ ...Idaig modosithatod\r\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n\r\nint main(int argc, char **argv) {\r\n\tglutInit(&argc, argv);\r\n\tglutInitWindowSize(600, 600);\r\n\tglutInitWindowPosition(100, 100);\r\n\tglutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);\r\n\r\n\tglutCreateWindow(\"Grafika hazi feladat\");\r\n\r\n\tglMatrixMode(GL_MODELVIEW);\r\n\tglLoadIdentity();\r\n\tglMatrixMode(GL_PROJECTION);\r\n\tglLoadIdentity();\r\n\r\n\tonInitialization();\r\n\r\n\tglutDisplayFunc(onDisplay);\r\n\tglutMouseFunc(onMouse);\r\n\tglutIdleFunc(onIdle);\r\n\tglutKeyboardFunc(onKeyboard);\r\n\r\n\tglutMainLoop();\r\n\t\r\n\treturn 0;\t\r\n}\r\n<|endoftext|>"} {"text":"\/*\n * MRustC - Rust Compiler\n * - By John Hodge (Mutabah\/thePowersGang)\n *\n * expand\/include.cpp\n * - include!\/include_str!\/include_bytes! support\n *\/\n#include \n#include \/\/ for Expand_BareExpr\n#include \n#include \/\/ for GET_CHECK_TOK\n#include \n#include \/\/ Lexer (new files)\n#include \n#include \n\nnamespace {\n\n ::std::string get_string(const Span& sp, TokenStream& lex, const ::AST::Crate& crate, AST::Module& mod)\n {\n auto n = Parse_ExprVal(lex);\n ASSERT_BUG(sp, n, \"No expression returned\");\n Expand_BareExpr(crate, mod, n);\n\n auto* string_np = dynamic_cast(&*n);\n if( !string_np ) {\n ERROR(sp, E0000, \"include! requires a string literal - got \" << *n);\n }\n return mv$( string_np->m_value );\n }\n\n ::std::string get_path_relative_to(const ::std::string& base_path, ::std::string path)\n {\n DEBUG(base_path << \", \" << path);\n \/\/ Absolute\n if( path[0] == '\/' || path[0] == '\\\\' ) {\n return path;\n }\n \/\/ Windows absolute\n else if( isalnum(path[0]) && path[1] == ':' && (path[2] == '\/' || path[2] == '\\\\') ) {\n return path;\n }\n else if( base_path.size() == 0 ) {\n return path;\n }\n else if( base_path.back() == '\/' || base_path.back() == '\\\\' ) {\n return base_path + path;\n }\n else {\n\n auto slash = ::std::min( base_path.find_last_of('\/'), base_path.find_last_of('\\\\') );\n if( slash == ::std::string::npos )\n {\n return path;\n }\n else\n {\n slash += 1;\n ::std::string rv;\n rv.reserve( slash + path.size() );\n rv.append( base_path.begin(), base_path.begin() + slash );\n rv.append( path.begin(), path.end() );\n return rv;\n }\n }\n }\n};\n\nclass CIncludeExpander:\n public ExpandProcMacro\n{\n ::std::unique_ptr expand(const Span& sp, const AST::Crate& crate, const TokenTree& tt, AST::Module& mod) override\n {\n Token tok;\n auto lex = TTStream(sp, ParseState(crate.m_edition), tt);\n\n auto path = get_string(sp, lex, crate, mod);\n GET_CHECK_TOK(tok, lex, TOK_EOF);\n\n ::std::string file_path = get_path_relative_to(mod.m_file_info.path, mv$(path));\n crate.m_extra_files.push_back(file_path);\n\n try {\n ParseState ps(crate.m_edition);\n ps.module = &mod;\n return box$( Lexer(file_path, ps) );\n }\n catch(::std::runtime_error& e)\n {\n ERROR(sp, E0000, e.what());\n }\n }\n};\n\nclass CIncludeBytesExpander:\n public ExpandProcMacro\n{\n ::std::unique_ptr expand(const Span& sp, const AST::Crate& crate, const TokenTree& tt, AST::Module& mod) override\n {\n Token tok;\n auto lex = TTStream(sp, ParseState(crate.m_edition), tt);\n\n auto path = get_string(sp, lex, crate, mod);\n GET_CHECK_TOK(tok, lex, TOK_EOF);\n\n ::std::string file_path = get_path_relative_to(mod.m_file_info.path, mv$(path));\n crate.m_extra_files.push_back(file_path);\n\n ::std::ifstream is(file_path);\n if( !is.good() ) {\n ERROR(sp, E0000, \"Cannot open file \" << file_path << \" for include_bytes!\");\n }\n ::std::stringstream ss;\n ss << is.rdbuf();\n\n ::std::vector toks;\n toks.push_back(Token(TOK_BYTESTRING, mv$(ss.str())));\n return box$( TTStreamO(sp, ParseState(crate.m_edition), TokenTree(Ident::Hygiene::new_scope(), mv$(toks))) );\n }\n};\n\nclass CIncludeStrExpander:\n public ExpandProcMacro\n{\n ::std::unique_ptr expand(const Span& sp, const AST::Crate& crate, const TokenTree& tt, AST::Module& mod) override\n {\n Token tok;\n auto lex = TTStream(sp, ParseState(crate.m_edition), tt);\n\n auto path = get_string(sp, lex, crate, mod);\n GET_CHECK_TOK(tok, lex, TOK_EOF);\n\n ::std::string file_path = get_path_relative_to(mod.m_file_info.path, mv$(path));\n crate.m_extra_files.push_back(file_path);\n\n ::std::ifstream is(file_path);\n if( !is.good() ) {\n ERROR(sp, E0000, \"Cannot open file \" << file_path << \" for include_str!\");\n }\n ::std::stringstream ss;\n ss << is.rdbuf();\n\n ::std::vector toks;\n toks.push_back(Token(TOK_STRING, mv$(ss.str())));\n return box$( TTStreamO(sp, ParseState(crate.m_edition), TokenTree(Ident::Hygiene::new_scope(), mv$(toks))) );\n }\n};\n\n\/\/ TODO: include_str! and include_bytes!\n\nSTATIC_MACRO(\"include\", CIncludeExpander);\nSTATIC_MACRO(\"include_bytes\", CIncludeBytesExpander);\nSTATIC_MACRO(\"include_str\", CIncludeStrExpander);\n\n\nExpand include - Relative path logic\/*\n * MRustC - Rust Compiler\n * - By John Hodge (Mutabah\/thePowersGang)\n *\n * expand\/include.cpp\n * - include!\/include_str!\/include_bytes! support\n *\/\n#include \n#include \/\/ for Expand_BareExpr\n#include \n#include \/\/ for GET_CHECK_TOK\n#include \n#include \/\/ Lexer (new files)\n#include \n#include \n\nnamespace {\n\n ::std::string get_string(const Span& sp, TokenStream& lex, const ::AST::Crate& crate, AST::Module& mod)\n {\n auto n = Parse_ExprVal(lex);\n ASSERT_BUG(sp, n, \"No expression returned\");\n Expand_BareExpr(crate, mod, n);\n\n auto* string_np = dynamic_cast(&*n);\n if( !string_np ) {\n ERROR(sp, E0000, \"include! requires a string literal - got \" << *n);\n }\n return mv$( string_np->m_value );\n }\n\n ::std::string get_path_relative_to(const ::std::string& base_path, ::std::string path)\n {\n DEBUG(base_path << \", \" << path);\n \/\/ Absolute\n if( path[0] == '\/' || path[0] == '\\\\' ) {\n return path;\n }\n \/\/ Windows absolute\n else if( isalnum(path[0]) && path[1] == ':' && (path[2] == '\/' || path[2] == '\\\\') ) {\n return path;\n }\n else if( base_path.size() == 0 ) {\n return path;\n }\n else if( base_path.back() == '\/' || base_path.back() == '\\\\' ) {\n return base_path + path;\n }\n else {\n\n auto slash_fwd = base_path.find_last_of('\/');\n auto slash_back = base_path.find_last_of('\\\\');\n auto slash =\n slash_fwd == std::string::npos ? slash_back\n : slash_back == std::string::npos ? slash_fwd\n : std::max(slash_fwd, slash_back)\n ;\n if( slash == ::std::string::npos )\n {\n return path;\n }\n else\n {\n DEBUG(\"> slash = \" << slash);\n slash += 1;\n ::std::string rv;\n rv.reserve( slash + path.size() );\n rv.append( base_path.begin(), base_path.begin() + slash );\n rv.append( path.begin(), path.end() );\n return rv;\n }\n }\n }\n};\n\nclass CIncludeExpander:\n public ExpandProcMacro\n{\n ::std::unique_ptr expand(const Span& sp, const AST::Crate& crate, const TokenTree& tt, AST::Module& mod) override\n {\n Token tok;\n auto lex = TTStream(sp, ParseState(crate.m_edition), tt);\n\n auto path = get_string(sp, lex, crate, mod);\n GET_CHECK_TOK(tok, lex, TOK_EOF);\n\n ::std::string file_path = get_path_relative_to(mod.m_file_info.path, mv$(path));\n crate.m_extra_files.push_back(file_path);\n\n try {\n ParseState ps(crate.m_edition);\n ps.module = &mod;\n return box$( Lexer(file_path, ps) );\n }\n catch(::std::runtime_error& e)\n {\n ERROR(sp, E0000, e.what());\n }\n }\n};\n\nclass CIncludeBytesExpander:\n public ExpandProcMacro\n{\n ::std::unique_ptr expand(const Span& sp, const AST::Crate& crate, const TokenTree& tt, AST::Module& mod) override\n {\n Token tok;\n auto lex = TTStream(sp, ParseState(crate.m_edition), tt);\n\n auto path = get_string(sp, lex, crate, mod);\n GET_CHECK_TOK(tok, lex, TOK_EOF);\n\n ::std::string file_path = get_path_relative_to(mod.m_file_info.path, mv$(path));\n crate.m_extra_files.push_back(file_path);\n\n ::std::ifstream is(file_path);\n if( !is.good() ) {\n ERROR(sp, E0000, \"Cannot open file \" << file_path << \" for include_bytes!\");\n }\n ::std::stringstream ss;\n ss << is.rdbuf();\n\n ::std::vector toks;\n toks.push_back(Token(TOK_BYTESTRING, mv$(ss.str())));\n return box$( TTStreamO(sp, ParseState(crate.m_edition), TokenTree(Ident::Hygiene::new_scope(), mv$(toks))) );\n }\n};\n\nclass CIncludeStrExpander:\n public ExpandProcMacro\n{\n ::std::unique_ptr expand(const Span& sp, const AST::Crate& crate, const TokenTree& tt, AST::Module& mod) override\n {\n Token tok;\n auto lex = TTStream(sp, ParseState(crate.m_edition), tt);\n\n auto path = get_string(sp, lex, crate, mod);\n GET_CHECK_TOK(tok, lex, TOK_EOF);\n\n ::std::string file_path = get_path_relative_to(mod.m_file_info.path, mv$(path));\n crate.m_extra_files.push_back(file_path);\n\n ::std::ifstream is(file_path);\n if( !is.good() ) {\n ERROR(sp, E0000, \"Cannot open file \" << file_path << \" for include_str!\");\n }\n ::std::stringstream ss;\n ss << is.rdbuf();\n\n ::std::vector toks;\n toks.push_back(Token(TOK_STRING, mv$(ss.str())));\n return box$( TTStreamO(sp, ParseState(crate.m_edition), TokenTree(Ident::Hygiene::new_scope(), mv$(toks))) );\n }\n};\n\n\/\/ TODO: include_str! and include_bytes!\n\nSTATIC_MACRO(\"include\", CIncludeExpander);\nSTATIC_MACRO(\"include_bytes\", CIncludeBytesExpander);\nSTATIC_MACRO(\"include_str\", CIncludeStrExpander);\n\n\n<|endoftext|>"} {"text":"\/*\nCopyright (c) 2012 Carsten Burstedde, Donna Calhoun\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#ifdef __cplusplus\nextern \"C\"\n{\n#if 0\n}\n#endif\n#endif\n\n\/* This is also called from fclaw2d_initialize, so is not made static *\/\nvoid cb_fclaw2d_regrid_tag4refinement(fclaw2d_domain_t *domain,\n fclaw2d_patch_t *this_patch,\n int this_block_idx,\n int this_patch_idx,\n void *user)\n{\n fclaw2d_vtable_t vt;\n int refine_patch, maxlevel, level;\n const amr_options_t* gparms;\n\n int domain_init = *((int*) user);\n\n vt = fclaw2d_get_vtable(domain);\n gparms = get_domain_parms(domain);\n\n maxlevel = gparms->maxlevel;\n level = this_patch->level;\n\n if (level < maxlevel)\n {\n refine_patch =\n vt.regrid_tag4refinement(domain,this_patch,this_block_idx,\n this_patch_idx, domain_init);\n if (refine_patch == 1)\n {\n fclaw2d_patch_mark_refine(domain, this_block_idx, this_patch_idx);\n }\n }\n}\n\n\/* Tag family for coarsening *\/\nstatic\nvoid cb_regrid_tag4coarsening(fclaw2d_domain_t *domain,\n fclaw2d_patch_t *fine_patches,\n int blockno, int fine0_patchno,\n void *user)\n{\n const amr_options_t *gparms = get_domain_parms(domain);\n fclaw2d_vtable_t vt;\n vt = fclaw2d_get_vtable(domain);\n\n int minlevel = gparms->minlevel;\n\n int level = fine_patches[0].level;\n\n if (level > minlevel)\n {\n int family_coarsened = 1;\n family_coarsened = vt.regrid_tag4coarsening(domain,&fine_patches[0],\n blockno, fine0_patchno);\n if (family_coarsened == 1)\n {\n for (int igrid = 0; igrid < NumSiblings; igrid++)\n {\n int fine_patchno = fine0_patchno + igrid;\n fclaw2d_patch_mark_coarsen(domain,blockno, fine_patchno);\n }\n }\n }\n}\n\n\n\/* ----------------------------------------------------------------\n Public interface\n -------------------------------------------------------------- *\/\n\nvoid cb_fclaw2d_regrid_repopulate(fclaw2d_domain_t * old_domain,\n fclaw2d_patch_t * old_patch,\n fclaw2d_domain_t * new_domain,\n fclaw2d_patch_t * new_patch,\n fclaw2d_patch_relation_t newsize,\n int blockno,\n int old_patchno,\n int new_patchno,\n void *user)\n{\n fclaw2d_vtable_t vt;\n vt = fclaw2d_get_vtable(new_domain);\n\n int domain_init = *((int*) user);\n\n fclaw2d_domain_data_t *ddata_old = fclaw2d_domain_get_data (old_domain);\n fclaw2d_domain_data_t *ddata_new = fclaw2d_domain_get_data (new_domain);\n fclaw2d_build_mode_t build_mode = FCLAW2D_BUILD_FOR_UPDATE;\n\n if (newsize == FCLAW2D_PATCH_SAMESIZE)\n {\n new_patch->user = old_patch->user;\n old_patch->user = NULL;\n ++ddata_old->count_delete_clawpatch;\n ++ddata_new->count_set_clawpatch;\n#if 0\n fclaw2d_clawpatch_initialize_after_regrid(new_domain,\n new_patch,\n blockno,\n new_patchno);\n#endif\n }\n else if (newsize == FCLAW2D_PATCH_HALFSIZE)\n {\n fclaw2d_patch_t *fine_siblings = new_patch;\n fclaw2d_patch_t *coarse_patch = old_patch;\n\n for (int i = 0; i < NumSiblings; i++)\n {\n fclaw2d_patch_t *fine_patch = &fine_siblings[i];\n int fine_patchno = new_patchno + i;\n fclaw2d_patch_data_new(new_domain,fine_patch);\n fclaw2d_clawpatch_build(new_domain,fine_patch,blockno,\n fine_patchno,(void*) &build_mode);\n if (domain_init)\n {\n vt.patch_initialize(new_domain,fine_patch,blockno,fine_patchno);\n }\n }\n\n if (!domain_init)\n {\n int coarse_patchno = old_patchno;\n int fine_patchno = new_patchno;\n\n vt.regrid_interpolate2fine(new_domain,coarse_patch,fine_siblings,\n blockno,coarse_patchno,fine_patchno);\n }\n fclaw2d_patch_data_delete(old_domain,coarse_patch);\n }\n else if (newsize == FCLAW2D_PATCH_DOUBLESIZE)\n {\n if (domain_init)\n {\n fclaw_debugf(\"fclaw2d_regrid.cpp (repopulate): We shouldn't end up here\\n\");\n exit(0);\n }\n\n \/* Old grids are the finer grids; new grid is the coarsened grid *\/\n fclaw2d_patch_t *fine_siblings = old_patch;\n int fine_patchno = old_patchno;\n\n fclaw2d_patch_t *coarse_patch = new_patch;\n int coarse_patchno = new_patchno;\n fclaw2d_patch_data_new(new_domain,coarse_patch);\n\n \/* Area (and possibly other things) should be averaged to coarse grid. *\/\n fclaw2d_clawpatch_build_from_fine(new_domain,fine_siblings,coarse_patch,\n blockno,coarse_patchno,fine_patchno,\n build_mode);\n\n \/* Average the solution. Does this need to be customizable? *\/\n vt.regrid_average2coarse(new_domain,fine_siblings,coarse_patch,\n blockno,coarse_patchno, fine_patchno);\n\n for(int i = 0; i < 4; i++)\n {\n fclaw2d_patch_t* fine_patch = &fine_siblings[i];\n fclaw2d_patch_data_delete(old_domain,fine_patch);\n }\n }\n else\n {\n fclaw_global_essentialf(\"cb_adapt_domain : newsize not recognized\\n\");\n exit(1);\n }\n}\n\n\/* ----------------------------------------------------------------\n Public interface\n -------------------------------------------------------------- *\/\nvoid fclaw2d_regrid(fclaw2d_domain_t **domain)\n{\n fclaw2d_domain_data_t* ddata = fclaw2d_domain_get_data(*domain);\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_REGRID]);\n\n fclaw_global_infof(\"Regridding domain\\n\");\n\n\n \/* First determine which families should be coarsened. *\/\n fclaw2d_domain_iterate_families(*domain, cb_regrid_tag4coarsening,\n (void*) NULL);\n\n int domain_init = 0;\n fclaw2d_domain_iterate_patches(*domain, cb_fclaw2d_regrid_tag4refinement,\n (void *) &domain_init);\n\n \/* Rebuild domain if necessary *\/\n \/* Will return be NULL if no refining was done *\/\n fclaw2d_domain_t *new_domain = fclaw2d_domain_adapt(*domain);\n fclaw_bool have_new_refinement = new_domain != NULL;\n\n \/* Domain data may go out of scope now. *\/\n ddata = NULL;\n\n if (have_new_refinement)\n {\n fclaw_global_infof(\" -- Have new refinement\\n\");\n\n \/* allocate memory for user patch data and user domain data in the new\n domain; copy data from the old to new the domain. *\/\n fclaw2d_domain_setup(*domain, new_domain);\n ddata = fclaw2d_domain_get_data(new_domain);\n\n \/* Average to new coarse grids and interpolate to new fine grids *\/\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_BUILDREGRID]);\n fclaw2d_domain_iterate_adapted(*domain, new_domain,\n cb_fclaw2d_regrid_repopulate,\n (void *) &domain_init);\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_BUILDREGRID]);\n\n \/* free memory associated with old domain *\/\n fclaw2d_domain_reset(domain);\n *domain = new_domain;\n new_domain = NULL;\n\n \/* Repartition for load balancing. Second arg (mode) for vtk output *\/\n fclaw2d_partition_domain(domain, -1);\n\n \/* Need a new timer *\/\n ddata = fclaw2d_domain_get_data(*domain);\n\n \/* Set up ghost patches. No parallel communication is done here *\/\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]);\n fclaw2d_exchange_setup(*domain);\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]);\n\n \/* Update ghost cells. This is needed because we have new coarse or fine\n patches without valid ghost cells. Time_interp = 0, since we only\n only regrid when all levels are time synchronized. *\/\n int minlevel = (*domain)->global_minlevel;\n int maxlevel = (*domain)->global_maxlevel;\n int time_interp = 0;\n double sync_time = fclaw2d_domain_get_time(*domain);\n fclaw2d_ghost_update(*domain,\n minlevel,\n maxlevel,\n sync_time,\n time_interp,\n FCLAW2D_TIMER_REGRID);\n }\n else\n {\n#if 0\n \/* We updated all the ghost cells when leaving advance, so don't need to do\n it here *\/\n \/* Set up ghost patches. No parallel communication is done here *\/\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]);\n fclaw2d_exchange_setup(*domain);\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]);\n#endif\n }\n\n \/* Stop timer *\/\n ddata = fclaw2d_domain_get_data(*domain);\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_REGRID]);\n\n \/* Count calls to this function *\/\n ++ddata->count_amr_regrid;\n}\n\n#ifdef __cplusplus\n#if 0\n{\n#endif\n}\n#endif\nAdding timer around grid adaption\/*\nCopyright (c) 2012 Carsten Burstedde, Donna Calhoun\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#ifdef __cplusplus\nextern \"C\"\n{\n#if 0\n}\n#endif\n#endif\n\n\/* This is also called from fclaw2d_initialize, so is not made static *\/\nvoid cb_fclaw2d_regrid_tag4refinement(fclaw2d_domain_t *domain,\n fclaw2d_patch_t *this_patch,\n int this_block_idx,\n int this_patch_idx,\n void *user)\n{\n fclaw2d_vtable_t vt;\n int refine_patch, maxlevel, level;\n const amr_options_t* gparms;\n\n int domain_init = *((int*) user);\n\n vt = fclaw2d_get_vtable(domain);\n gparms = get_domain_parms(domain);\n\n maxlevel = gparms->maxlevel;\n level = this_patch->level;\n\n if (level < maxlevel)\n {\n refine_patch =\n vt.regrid_tag4refinement(domain,this_patch,this_block_idx,\n this_patch_idx, domain_init);\n if (refine_patch == 1)\n {\n fclaw2d_patch_mark_refine(domain, this_block_idx, this_patch_idx);\n }\n }\n}\n\n\/* Tag family for coarsening *\/\nstatic\nvoid cb_regrid_tag4coarsening(fclaw2d_domain_t *domain,\n fclaw2d_patch_t *fine_patches,\n int blockno, int fine0_patchno,\n void *user)\n{\n const amr_options_t *gparms = get_domain_parms(domain);\n fclaw2d_vtable_t vt;\n vt = fclaw2d_get_vtable(domain);\n\n int minlevel = gparms->minlevel;\n\n int level = fine_patches[0].level;\n\n if (level > minlevel)\n {\n int family_coarsened = 1;\n family_coarsened = vt.regrid_tag4coarsening(domain,&fine_patches[0],\n blockno, fine0_patchno);\n if (family_coarsened == 1)\n {\n for (int igrid = 0; igrid < NumSiblings; igrid++)\n {\n int fine_patchno = fine0_patchno + igrid;\n fclaw2d_patch_mark_coarsen(domain,blockno, fine_patchno);\n }\n }\n }\n}\n\n\n\/* ----------------------------------------------------------------\n Public interface\n -------------------------------------------------------------- *\/\n\nvoid cb_fclaw2d_regrid_repopulate(fclaw2d_domain_t * old_domain,\n fclaw2d_patch_t * old_patch,\n fclaw2d_domain_t * new_domain,\n fclaw2d_patch_t * new_patch,\n fclaw2d_patch_relation_t newsize,\n int blockno,\n int old_patchno,\n int new_patchno,\n void *user)\n{\n fclaw2d_vtable_t vt;\n vt = fclaw2d_get_vtable(new_domain);\n\n int domain_init = *((int*) user);\n\n fclaw2d_domain_data_t *ddata_old = fclaw2d_domain_get_data (old_domain);\n fclaw2d_domain_data_t *ddata_new = fclaw2d_domain_get_data (new_domain);\n fclaw2d_build_mode_t build_mode = FCLAW2D_BUILD_FOR_UPDATE;\n\n if (newsize == FCLAW2D_PATCH_SAMESIZE)\n {\n new_patch->user = old_patch->user;\n old_patch->user = NULL;\n ++ddata_old->count_delete_clawpatch;\n ++ddata_new->count_set_clawpatch;\n#if 0\n fclaw2d_clawpatch_initialize_after_regrid(new_domain,\n new_patch,\n blockno,\n new_patchno);\n#endif\n }\n else if (newsize == FCLAW2D_PATCH_HALFSIZE)\n {\n fclaw2d_patch_t *fine_siblings = new_patch;\n fclaw2d_patch_t *coarse_patch = old_patch;\n\n for (int i = 0; i < NumSiblings; i++)\n {\n fclaw2d_patch_t *fine_patch = &fine_siblings[i];\n int fine_patchno = new_patchno + i;\n fclaw2d_patch_data_new(new_domain,fine_patch);\n fclaw2d_clawpatch_build(new_domain,fine_patch,blockno,\n fine_patchno,(void*) &build_mode);\n if (domain_init)\n {\n vt.patch_initialize(new_domain,fine_patch,blockno,fine_patchno);\n }\n }\n\n if (!domain_init)\n {\n int coarse_patchno = old_patchno;\n int fine_patchno = new_patchno;\n\n vt.regrid_interpolate2fine(new_domain,coarse_patch,fine_siblings,\n blockno,coarse_patchno,fine_patchno);\n }\n fclaw2d_patch_data_delete(old_domain,coarse_patch);\n }\n else if (newsize == FCLAW2D_PATCH_DOUBLESIZE)\n {\n if (domain_init)\n {\n fclaw_debugf(\"fclaw2d_regrid.cpp (repopulate): We shouldn't end up here\\n\");\n exit(0);\n }\n\n \/* Old grids are the finer grids; new grid is the coarsened grid *\/\n fclaw2d_patch_t *fine_siblings = old_patch;\n int fine_patchno = old_patchno;\n\n fclaw2d_patch_t *coarse_patch = new_patch;\n int coarse_patchno = new_patchno;\n fclaw2d_patch_data_new(new_domain,coarse_patch);\n\n \/* Area (and possibly other things) should be averaged to coarse grid. *\/\n fclaw2d_clawpatch_build_from_fine(new_domain,fine_siblings,coarse_patch,\n blockno,coarse_patchno,fine_patchno,\n build_mode);\n\n \/* Average the solution. Does this need to be customizable? *\/\n vt.regrid_average2coarse(new_domain,fine_siblings,coarse_patch,\n blockno,coarse_patchno, fine_patchno);\n\n for(int i = 0; i < 4; i++)\n {\n fclaw2d_patch_t* fine_patch = &fine_siblings[i];\n fclaw2d_patch_data_delete(old_domain,fine_patch);\n }\n }\n else\n {\n fclaw_global_essentialf(\"cb_adapt_domain : newsize not recognized\\n\");\n exit(1);\n }\n}\n\n\/* ----------------------------------------------------------------\n Public interface\n -------------------------------------------------------------- *\/\nvoid fclaw2d_regrid(fclaw2d_domain_t **domain)\n{\n fclaw2d_domain_data_t* ddata = fclaw2d_domain_get_data(*domain);\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_REGRID]);\n\n fclaw_global_infof(\"Regridding domain\\n\");\n\n\n \/* First determine which families should be coarsened. *\/\n fclaw2d_domain_iterate_families(*domain, cb_regrid_tag4coarsening,\n (void*) NULL);\n\n int domain_init = 0;\n fclaw2d_domain_iterate_patches(*domain, cb_fclaw2d_regrid_tag4refinement,\n (void *) &domain_init);\n\n \/* Rebuild domain if necessary *\/\n \/* Will return be NULL if no refining was done *\/\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_EXTRA4]);\n fclaw2d_domain_t *new_domain = fclaw2d_domain_adapt(*domain);\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_EXTRA4]);\n fclaw_bool have_new_refinement = new_domain != NULL;\n\n \/* Domain data may go out of scope now. *\/\n ddata = NULL;\n\n if (have_new_refinement)\n {\n fclaw_global_essentialf(\"-----> We should not be here\\n\");\n exit(0);\n fclaw_global_infof(\" -- Have new refinement\\n\");\n\n \/* allocate memory for user patch data and user domain data in the new\n domain; copy data from the old to new the domain. *\/\n fclaw2d_domain_setup(*domain, new_domain);\n ddata = fclaw2d_domain_get_data(new_domain);\n\n \/* Average to new coarse grids and interpolate to new fine grids *\/\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_BUILDREGRID]);\n fclaw2d_domain_iterate_adapted(*domain, new_domain,\n cb_fclaw2d_regrid_repopulate,\n (void *) &domain_init);\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_BUILDREGRID]);\n\n \/* free memory associated with old domain *\/\n fclaw2d_domain_reset(domain);\n *domain = new_domain;\n new_domain = NULL;\n\n \/* Repartition for load balancing. Second arg (mode) for vtk output *\/\n fclaw2d_partition_domain(domain, -1);\n\n \/* Need a new timer *\/\n ddata = fclaw2d_domain_get_data(*domain);\n\n \/* Set up ghost patches. No parallel communication is done here *\/\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]);\n fclaw2d_exchange_setup(*domain);\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]);\n\n \/* Update ghost cells. This is needed because we have new coarse or fine\n patches without valid ghost cells. Time_interp = 0, since we only\n only regrid when all levels are time synchronized. *\/\n int minlevel = (*domain)->global_minlevel;\n int maxlevel = (*domain)->global_maxlevel;\n int time_interp = 0;\n double sync_time = fclaw2d_domain_get_time(*domain);\n fclaw2d_ghost_update(*domain,\n minlevel,\n maxlevel,\n sync_time,\n time_interp,\n FCLAW2D_TIMER_REGRID);\n }\n else\n {\n#if 0\n \/* We updated all the ghost cells when leaving advance, so don't need to do\n it here *\/\n \/* Set up ghost patches. No parallel communication is done here *\/\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]);\n fclaw2d_exchange_setup(*domain);\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]);\n#endif\n }\n\n \/* Stop timer *\/\n ddata = fclaw2d_domain_get_data(*domain);\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_REGRID]);\n\n \/* Count calls to this function *\/\n ++ddata->count_amr_regrid;\n}\n\n#ifdef __cplusplus\n#if 0\n{\n#endif\n}\n#endif\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2016 Samsung Electronics Co., Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace Dali;\n\nvoid utc_dali_resource_image_startup(void)\n{\n test_return_value = TET_UNDEF;\n}\n\nvoid utc_dali_resource_image_cleanup(void)\n{\n test_return_value = TET_PASS;\n}\n\nstatic const char* gTestImageFilename = \"icon_wrt.png\";\n\nnamespace\n{\n\nvoid LoadBitmapResource(TestPlatformAbstraction& platform)\n{\n Integration::ResourceRequest* request = platform.GetRequest();\n Integration::Bitmap* bitmap = Integration::Bitmap::New( Integration::Bitmap::BITMAP_2D_PACKED_PIXELS, ResourcePolicy::OWNED_DISCARD );\n Integration::ResourcePointer resource(bitmap);\n bitmap->GetPackedPixelsProfile()->ReserveBuffer(Pixel::RGBA8888, 80, 80, 80, 80);\n\n if(request)\n {\n platform.SetResourceLoaded(request->GetId(), request->GetType()->id, resource);\n }\n}\n\n} \/\/ namespace\n\n\n\/\/ 1.1\nint UtcDaliResourceImageNew01(void)\n{\n TestApplication application;\n\n tet_infoline(\"UtcDaliResourceImageNew01 - ResourceImage::New(const std::string&)\");\n\n \/\/ invoke default handle constructor\n ResourceImage image;\n\n DALI_TEST_CHECK( !image );\n\n \/\/ initialise handle\n image = ResourceImage::New(gTestImageFilename);\n\n DALI_TEST_CHECK( image );\n END_TEST;\n}\n\n\/\/ 1.2\nint UtcDaliResourceImageNew02(void)\n{\n TestApplication application;\n\n tet_infoline(\"UtcDaliREsourceImageNew02 - ResourceImage New( const std::string& url, ImageDimensions size, FittingMode scalingMode, SamplingMode samplingMode, bool orientationCorrection = true )\");\n\n \/\/ invoke default handle constructor\n ResourceImage image;\n\n DALI_TEST_CHECK( !image );\n\n \/\/ initialise handle\n image = ResourceImage::New(gTestImageFilename, ImageDimensions( 128, 256 ), FittingMode::FIT_HEIGHT );\n\n DALI_TEST_CHECK( image );\n END_TEST;\n}\n\n\/\/ 1.7\nint UtcDaliResourceImageDownCast(void)\n{\n TestApplication application;\n tet_infoline(\"Testing Dali::ResourceImage::DownCast()\");\n\n ResourceImage image = ResourceImage::New(gTestImageFilename);\n\n BaseHandle object(image);\n\n ResourceImage image2 = ResourceImage::DownCast(object);\n DALI_TEST_CHECK(image2);\n\n ResourceImage image3 = DownCast< ResourceImage >(object);\n DALI_TEST_CHECK(image3);\n\n BaseHandle unInitializedObject;\n ResourceImage image4 = ResourceImage::DownCast(unInitializedObject);\n DALI_TEST_CHECK(!image4);\n\n ResourceImage image5 = DownCast< ResourceImage >(unInitializedObject);\n DALI_TEST_CHECK(!image5);\n\n Image image6 = ResourceImage::New(gTestImageFilename);\n ResourceImage image7 = ResourceImage::DownCast(image6);\n DALI_TEST_CHECK(image7);\n END_TEST;\n}\n\n\/\/ 1.8\nint UtcDaliResourceImageGetImageSize(void)\n{\n TestApplication application;\n TestPlatformAbstraction& platform = application.GetPlatform();\n\n tet_infoline(\"UtcDaliResourceImageGetImageSize - ResourceImage::GetImageSize()\");\n\n Vector2 testSize(8.0f, 16.0f);\n platform.SetClosestImageSize(testSize);\n\n const ImageDimensions size = ResourceImage::GetImageSize(gTestImageFilename);\n\n DALI_TEST_CHECK( application.GetPlatform().GetTrace().FindMethod(\"GetClosestImageSize\"));\n DALI_TEST_EQUALS( Vector2( size.GetX(), size.GetY() ), testSize, TEST_LOCATION);\n END_TEST;\n}\n\n\/\/ 1.9\nint UtcDaliResourceImageGetUrl(void)\n{\n TestApplication application;\n\n tet_infoline(\"UtcDaliResourceImageGetFilename - ResourceImage::GetUrl()\");\n\n \/\/ invoke default handle constructor\n ResourceImage image;\n\n DALI_TEST_CHECK( !image );\n\n \/\/ initialise handle\n image = ResourceImage::New(gTestImageFilename);\n\n DALI_TEST_EQUALS( image.GetUrl(), gTestImageFilename, TEST_LOCATION);\n END_TEST;\n}\n\n\/\/ 1.10\nint UtcDaliResourceImageGetLoadingState01(void)\n{\n TestApplication application;\n tet_infoline(\"UtcDaliResourceImageGetLoadingState01\");\n\n ResourceImage image = ResourceImage::New(gTestImageFilename);\n DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingFailed);\n\n \/\/ simulate load success\n PrepareResourceImage( application, 100u, 100u, Pixel::RGBA8888 );\n image.Reload();\n\n \/\/ Test state == ResourceLoadingSucceeded\n DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingSucceeded);\n END_TEST;\n}\n\n\/\/ 1.11\nint UtcDaliResourceImageGetLoadingState02(void)\n{\n TestApplication application;\n\n tet_infoline(\"UtcDaliResourceImageGetLoadingState02\");\n\n \/\/ invoke default handle constructor\n ResourceImage image;\n\n DALI_TEST_CHECK( !image );\n\n \/\/ initialise handle\n image = ResourceImage::New(gTestImageFilename);\n\n \/\/ Test state == ResourceLoadingFailed\n DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingFailed);\n\n PrepareResourceImage( application, 100u, 100u, Pixel::RGBA8888 );\n image.Reload();\n\n \/\/ Test state == ResourceLoadingFailed\n DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingSucceeded);\n END_TEST;\n}\n\nstatic bool SignalLoadFlag = false;\n\nstatic void SignalLoadHandler(ResourceImage image)\n{\n tet_infoline(\"Received image load finished signal\");\n\n SignalLoadFlag = true;\n}\n\n\/\/ 1.13\nint UtcDaliResourceImageSignalLoadingFinished(void)\n{\n TestApplication application;\n\n tet_infoline(\"UtcDaliResourceImageSignalLoadingFinished\");\n\n SignalLoadFlag = false;\n\n PrepareResourceImage( application, 100u, 100u, Pixel::RGBA8888 );\n ResourceImage image = ResourceImage::New(gTestImageFilename);\n\n image.LoadingFinishedSignal().Connect( SignalLoadHandler );\n image.Reload();\n application.SendNotification();\n application.Render(16);\n\n Integration::ResourceRequest* request = application.GetPlatform().GetRequest();\n if(request)\n {\n application.GetPlatform().SetResourceLoaded(request->GetId(), request->GetType()->id, Integration::ResourcePointer(Integration::Bitmap::New(Integration::Bitmap::BITMAP_2D_PACKED_PIXELS, ResourcePolicy::OWNED_DISCARD)));\n }\n\n application.Render(16);\n application.SendNotification();\n\n DALI_TEST_CHECK( SignalLoadFlag == true );\n END_TEST;\n}\n(GCC 6.2) Remove unused functions from automated tests\/*\n * Copyright (c) 2017 Samsung Electronics Co., Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace Dali;\n\nvoid utc_dali_resource_image_startup(void)\n{\n test_return_value = TET_UNDEF;\n}\n\nvoid utc_dali_resource_image_cleanup(void)\n{\n test_return_value = TET_PASS;\n}\n\nnamespace\n{\nconst char* gTestImageFilename = \"icon_wrt.png\";\n} \/\/ unnamed namespace\n\n\n\/\/ 1.1\nint UtcDaliResourceImageNew01(void)\n{\n TestApplication application;\n\n tet_infoline(\"UtcDaliResourceImageNew01 - ResourceImage::New(const std::string&)\");\n\n \/\/ invoke default handle constructor\n ResourceImage image;\n\n DALI_TEST_CHECK( !image );\n\n \/\/ initialise handle\n image = ResourceImage::New(gTestImageFilename);\n\n DALI_TEST_CHECK( image );\n END_TEST;\n}\n\n\/\/ 1.2\nint UtcDaliResourceImageNew02(void)\n{\n TestApplication application;\n\n tet_infoline(\"UtcDaliREsourceImageNew02 - ResourceImage New( const std::string& url, ImageDimensions size, FittingMode scalingMode, SamplingMode samplingMode, bool orientationCorrection = true )\");\n\n \/\/ invoke default handle constructor\n ResourceImage image;\n\n DALI_TEST_CHECK( !image );\n\n \/\/ initialise handle\n image = ResourceImage::New(gTestImageFilename, ImageDimensions( 128, 256 ), FittingMode::FIT_HEIGHT );\n\n DALI_TEST_CHECK( image );\n END_TEST;\n}\n\n\/\/ 1.7\nint UtcDaliResourceImageDownCast(void)\n{\n TestApplication application;\n tet_infoline(\"Testing Dali::ResourceImage::DownCast()\");\n\n ResourceImage image = ResourceImage::New(gTestImageFilename);\n\n BaseHandle object(image);\n\n ResourceImage image2 = ResourceImage::DownCast(object);\n DALI_TEST_CHECK(image2);\n\n ResourceImage image3 = DownCast< ResourceImage >(object);\n DALI_TEST_CHECK(image3);\n\n BaseHandle unInitializedObject;\n ResourceImage image4 = ResourceImage::DownCast(unInitializedObject);\n DALI_TEST_CHECK(!image4);\n\n ResourceImage image5 = DownCast< ResourceImage >(unInitializedObject);\n DALI_TEST_CHECK(!image5);\n\n Image image6 = ResourceImage::New(gTestImageFilename);\n ResourceImage image7 = ResourceImage::DownCast(image6);\n DALI_TEST_CHECK(image7);\n END_TEST;\n}\n\n\/\/ 1.8\nint UtcDaliResourceImageGetImageSize(void)\n{\n TestApplication application;\n TestPlatformAbstraction& platform = application.GetPlatform();\n\n tet_infoline(\"UtcDaliResourceImageGetImageSize - ResourceImage::GetImageSize()\");\n\n Vector2 testSize(8.0f, 16.0f);\n platform.SetClosestImageSize(testSize);\n\n const ImageDimensions size = ResourceImage::GetImageSize(gTestImageFilename);\n\n DALI_TEST_CHECK( application.GetPlatform().GetTrace().FindMethod(\"GetClosestImageSize\"));\n DALI_TEST_EQUALS( Vector2( size.GetX(), size.GetY() ), testSize, TEST_LOCATION);\n END_TEST;\n}\n\n\/\/ 1.9\nint UtcDaliResourceImageGetUrl(void)\n{\n TestApplication application;\n\n tet_infoline(\"UtcDaliResourceImageGetFilename - ResourceImage::GetUrl()\");\n\n \/\/ invoke default handle constructor\n ResourceImage image;\n\n DALI_TEST_CHECK( !image );\n\n \/\/ initialise handle\n image = ResourceImage::New(gTestImageFilename);\n\n DALI_TEST_EQUALS( image.GetUrl(), gTestImageFilename, TEST_LOCATION);\n END_TEST;\n}\n\n\/\/ 1.10\nint UtcDaliResourceImageGetLoadingState01(void)\n{\n TestApplication application;\n tet_infoline(\"UtcDaliResourceImageGetLoadingState01\");\n\n ResourceImage image = ResourceImage::New(gTestImageFilename);\n DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingFailed);\n\n \/\/ simulate load success\n PrepareResourceImage( application, 100u, 100u, Pixel::RGBA8888 );\n image.Reload();\n\n \/\/ Test state == ResourceLoadingSucceeded\n DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingSucceeded);\n END_TEST;\n}\n\n\/\/ 1.11\nint UtcDaliResourceImageGetLoadingState02(void)\n{\n TestApplication application;\n\n tet_infoline(\"UtcDaliResourceImageGetLoadingState02\");\n\n \/\/ invoke default handle constructor\n ResourceImage image;\n\n DALI_TEST_CHECK( !image );\n\n \/\/ initialise handle\n image = ResourceImage::New(gTestImageFilename);\n\n \/\/ Test state == ResourceLoadingFailed\n DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingFailed);\n\n PrepareResourceImage( application, 100u, 100u, Pixel::RGBA8888 );\n image.Reload();\n\n \/\/ Test state == ResourceLoadingFailed\n DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingSucceeded);\n END_TEST;\n}\n\nstatic bool SignalLoadFlag = false;\n\nstatic void SignalLoadHandler(ResourceImage image)\n{\n tet_infoline(\"Received image load finished signal\");\n\n SignalLoadFlag = true;\n}\n\n\/\/ 1.13\nint UtcDaliResourceImageSignalLoadingFinished(void)\n{\n TestApplication application;\n\n tet_infoline(\"UtcDaliResourceImageSignalLoadingFinished\");\n\n SignalLoadFlag = false;\n\n PrepareResourceImage( application, 100u, 100u, Pixel::RGBA8888 );\n ResourceImage image = ResourceImage::New(gTestImageFilename);\n\n image.LoadingFinishedSignal().Connect( SignalLoadHandler );\n image.Reload();\n application.SendNotification();\n application.Render(16);\n\n Integration::ResourceRequest* request = application.GetPlatform().GetRequest();\n if(request)\n {\n application.GetPlatform().SetResourceLoaded(request->GetId(), request->GetType()->id, Integration::ResourcePointer(Integration::Bitmap::New(Integration::Bitmap::BITMAP_2D_PACKED_PIXELS, ResourcePolicy::OWNED_DISCARD)));\n }\n\n application.Render(16);\n application.SendNotification();\n\n DALI_TEST_CHECK( SignalLoadFlag == true );\n END_TEST;\n}\n<|endoftext|>"} {"text":"\/\/ Begin CVS Header\n\/\/ $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/function\/CFunctionDB.cpp,v $\n\/\/ $Revision: 1.83 $\n\/\/ $Name: $\n\/\/ $Author: aekamal $\n\/\/ $Date: 2009\/06\/12 19:58:24 $\n\/\/ End CVS Header\n\n\/\/ Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., EML Research, gGmbH, University of Heidelberg,\n\/\/ and The University of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc. and EML Research, gGmbH.\n\/\/ All rights reserved.\n\n\/**\n * CFunctionDB\n *\n * Created for Copasi by Stefan Hoops\n * (C) Stefan Hoops 2001\n *\/\n\n#include \n\n#include \"copasi.h\"\n\n#include \"CFunctionDB.h\"\n#include \"CFunction.h\"\n#include \"FunctionDB.xml.h\"\n\n#include \"utilities\/CCopasiException.h\"\n#include \"report\/CCopasiObjectReference.h\"\n#include \"report\/CKeyFactory.h\"\n#include \"xml\/CCopasiXML.h\"\n#include \"model\/CModel.h\"\n\nCFunctionDB::CFunctionDB(const std::string & name,\n const CCopasiContainer * pParent):\n CCopasiContainer(name, pParent, \"FunctionDB\"),\n mFilename(),\n mLoadedFunctions(\"Functions\", this)\n{\n initObjects();\n CONSTRUCTOR_TRACE;\n}\n\nCFunctionDB::~CFunctionDB()\n{\n cleanup();\n DESTRUCTOR_TRACE;\n}\n\nvoid CFunctionDB::cleanup() {mLoadedFunctions.cleanup();}\n\nvoid CFunctionDB::initObjects()\n{\n addObjectReference(\"File\", mFilename);\n}\n\nbool CFunctionDB::load()\n{\n CCopasiXML XML;\n XML.setFunctionList(&mLoadedFunctions);\n\n std::stringstream DB;\n DB.str(FunctionDBxml);\n\n if (DB.fail())\n return false;\n\n if (!XML.load(DB, \"\"))\n return false;\n\n return true;\n}\n\nC_INT32 CFunctionDB::load(CReadConfig &configbuffer)\n{\n CFunction Function;\n CFunction * pFunction = NULL;\n\n C_INT32 Size = 0;\n C_INT32 Fail = 0;\n\n configbuffer.getVariable(\"TotalUDKinetics\", \"C_INT32\", &Size,\n CReadConfig::LOOP);\n\n for (C_INT32 i = 0; i < Size; i++)\n {\n Function.load(configbuffer);\n\n switch (Function.getType())\n {\n case CEvaluationTree::Function:\n pFunction = new CFunction(Function);\n break;\n\n case CEvaluationTree::MassAction:\n pFunction = new CMassAction(Function);\n break;\n\n case CEvaluationTree::PreDefined:\n case CEvaluationTree::UserDefined:\n pFunction = new CKinFunction(Function,\n &configbuffer);\n break;\n\n default:\n fatalError();\n }\n\n pFunction->compile();\n\n if (!mLoadedFunctions.add(pFunction, true))\n {\n pdelete(pFunction);\n\n \/\/ We ignore:\n \/\/ CCopasiVector (2): Object '%s' allready exists.\n if ((MCCopasiVector + 2) != CCopasiMessage::peekLastMessage().getNumber())\n return Fail = 1;\n\n \/\/ Remove the ignored meesage.\n CCopasiMessage::getLastMessage();\n }\n }\n\n return Fail;\n}\n\nvoid CFunctionDB::setFilename(const std::string & filename)\n{mFilename = filename;}\n\nstd::string CFunctionDB::getFilename() const\n{return mFilename;}\n\n#ifdef FFFF\nCFunction * CFunctionDB::dBLoad(const std::string & functionName)\n{\n CFunction Function(\"NoName\", &mLoadedFunctions);\n CFunction * pFunction = NULL;\n\n if (mFilename == \"\") return NULL;\n\n CReadConfig inbuf(mFilename);\n\n while (functionName != Function.getObjectName())\n {\n Function.cleanup();\n Function.load(inbuf);\n }\n\n switch (Function.getType())\n {\n case CFunction::Base:\n pFunction = new CFunction(Function);\n break;\n\n case CFunction::MassAction:\n pFunction = new CMassAction(Function.isReversible());\n break;\n\n case CFunction::PreDefined:\n\n case CFunction::UserDefined:\n pFunction = new CKinFunction(Function, &inbuf);\n break;\n\n case CFunction::Expression:\n fatalError(); \/\/disabled\n \/\/pFunction = new CUDFunction(Function);\n break;\n\n default:\n fatalError();\n }\n\n if (!mLoadedFunctions.add(pFunction))\n {\n pdelete(pFunction);\n\n \/\/ We ignore:\n \/\/ CCopasiVector (2): Object '%s' allready exists.\n if ((MCCopasiVector + 2) != CCopasiMessage::getLastMessage().getNumber())\n\n pFunction = mLoadedFunctions[Function.getObjectName()];\n }\n\n return pFunction;\n}\n#endif \/\/ FFFF\n\n#ifdef FFFF\nCEvaluationTree * CFunctionDB::createFunction(const std::string & name, const CEvaluationTree::Type & type)\n{\n if (mLoadedFunctions.getIndex(name) != C_INVALID_INDEX)\n return NULL;\n\n \/\/CFunction * pFunction = new CFunction(name);\n\n CEvaluationTree * pFunction = NULL;\n\n switch (type)\n {\n case CEvaluationTree::Base:\n pFunction = new CFunction(name);\n break;\n\n case CEvaluationTree::MassAction:\n pFunction = new CMassAction(name);\n break;\n\n case CEvaluationTree::PreDefinedKineticLaw:\n case CEvaluationTree::UserDefinedKineticLaw:\n pFunction = new CKinFunction(name);\n break;\n\n default:\n fatalError();\n }\n\n if (!mLoadedFunctions.add(pFunction, true))\n {\n delete pFunction;\n return NULL;\n }\n\n return pFunction;\n}\n#endif \/\/ FFFF\n\nbool CFunctionDB::add(CEvaluationTree * pFunction,\n const bool & adopt)\n{return mLoadedFunctions.add(pFunction, adopt);}\n\nvoid CFunctionDB::addAndAdaptName(CEvaluationTree * pFunction)\n{\n if (!pFunction) return;\n\n std::string basename = pFunction->getObjectName();\n std::string name = basename;\n \/\/CFunction* pFunc;\n \/\/CCopasiVectorN& FunctionList\n \/\/= this->loadedFunctions();\n int i = 0;\n\n while (mLoadedFunctions.getIndex(name) != C_INVALID_INDEX)\n {\n i++;\n std::ostringstream ss; ss << \"_\" << i;\n name = basename + ss.str();\n }\n\n pFunction->setObjectName(name);\n\n this->add(pFunction, true);\n}\n\nbool CFunctionDB::removeFunction(unsigned C_INT32 index)\n{\n if (index == C_INVALID_INDEX) return false;\n\n mLoadedFunctions.CCopasiVector::remove(index);\n\n return true;\n}\n\nbool CFunctionDB::removeFunction(const std::string &key)\n{\n CEvaluationTree* func = dynamic_cast< CEvaluationTree * >(CCopasiRootContainer::getKeyFactory()->get(key));\n\n if (!func) return false;\n\n unsigned C_INT32 index =\n mLoadedFunctions.CCopasiVector::getIndex(func);\n\n if (index == C_INVALID_INDEX) return false;\n\n mLoadedFunctions.CCopasiVector::remove(index);\n\n return true;\n}\n\nCEvaluationTree * CFunctionDB::findFunction(const std::string & functionName)\n{\n unsigned C_INT32 index = mLoadedFunctions.getIndex(functionName);\n\n if (index != C_INVALID_INDEX)\n return mLoadedFunctions[index];\n else\n return NULL;\n}\n\nCEvaluationTree * CFunctionDB::findLoadFunction(const std::string & functionName)\n{\n unsigned C_INT32 i;\n\n for (i = 0; i < mLoadedFunctions.size(); i++)\n if (functionName == mLoadedFunctions[i]->getObjectName())\n return mLoadedFunctions[i];\n\n return NULL;\n}\n\nCCopasiVectorN < CEvaluationTree > & CFunctionDB::loadedFunctions()\n{return mLoadedFunctions;}\n\nstd::vector\nCFunctionDB::suitableFunctions(const unsigned C_INT32 noSubstrates,\n const unsigned C_INT32 noProducts,\n const TriLogic reversibility)\n{\n std::vector ret;\n CFunction *pFunction;\n\n unsigned C_INT32 i, imax = mLoadedFunctions.size();\n\n for (i = 0; i < imax; i++)\n {\n pFunction = dynamic_cast(mLoadedFunctions[i]);\n\n if (!pFunction) continue;\n\n if (pFunction->isSuitable(noSubstrates, noProducts, reversibility))\n ret.push_back(pFunction);\n }\n\n \/\/always add constant flux it is is missing\n if (reversibility == TriTrue)\n {\n if ((noSubstrates > 0) || (noProducts > 0)) \/\/constant flux was not yet added\n {\n pFunction = dynamic_cast(findFunction(\"Constant flux (reversible)\"));\n\n if (!pFunction) fatalError();\n\n ret.push_back(pFunction);\n }\n }\n else \/\/irreversible\n {\n if (noSubstrates > 0) \/\/constant flux was not yet added\n {\n pFunction = dynamic_cast(findFunction(\"Constant flux (irreversible)\"));\n\n if (!pFunction) fatalError();\n\n ret.push_back(pFunction);\n }\n }\n\n return ret;\n}\n\nbool CFunctionDB::appendDependentFunctions(std::set< const CCopasiObject * > candidates,\n std::set< const CCopasiObject * > & dependentFunctions) const\n{\n size_t Size = dependentFunctions.size();\n\n CCopasiVectorN< CEvaluationTree >::const_iterator it = mLoadedFunctions.begin();\n CCopasiVectorN< CEvaluationTree >::const_iterator end = mLoadedFunctions.end();\n\n for (; it != end; ++it)\n if (candidates.find(*it) == candidates.end() &&\n (*it)->dependsOn(candidates))\n dependentFunctions.insert((*it));\n\n return Size < dependentFunctions.size();\n}\n\nstd::set\nCFunctionDB::listDependentTrees(const std::string & name) const\n{\n std::set List;\n\n CCopasiVectorN < CEvaluationTree >::const_iterator it = mLoadedFunctions.begin();\n CCopasiVectorN < CEvaluationTree >::const_iterator end = mLoadedFunctions.end();\n\n for (; it != end; ++it)\n if ((*it)->dependsOnTree(name))\n List.insert((*it)->getObjectName());\n\n return List;\n}\n\nstd::vector< CEvaluationTree * > CFunctionDB::getUsedFunctions(const CModel* pModel) const\n{\n std::vector< CEvaluationTree * > UsedFunctions;\n CCopasiVectorN < CEvaluationTree >::const_iterator it = mLoadedFunctions.begin();\n CCopasiVectorN < CEvaluationTree >::const_iterator end = mLoadedFunctions.end();\n\n for (; it != end; ++it)\n {\n \/\/ :TODO: Bug 719\n \/\/ This will have to be modified as soon as the optimization problem stores its on expression\n if ((*it)->getType() == CEvaluationTree::Expression)\n {\n UsedFunctions.push_back(*it);\n continue;\n }\n\n std::set< const CCopasiObject * > Function;\n Function.insert(*it);\n\n std::set< const CCopasiObject * > Reactions;\n std::set< const CCopasiObject * > Metabolites;\n std::set< const CCopasiObject * > Values;\n std::set< const CCopasiObject * > Compartments;\n std::set< const CCopasiObject * > Events;\n\n pModel->appendDependentModelObjects(Function,\n Reactions, Metabolites, Compartments, Values, Events);\n\n if (Reactions.size() != 0)\n {\n UsedFunctions.push_back(*it);\n continue;\n }\n\n if (Metabolites.size() != 0)\n {\n UsedFunctions.push_back(*it);\n continue;\n }\n\n if (Values.size() != 0)\n {\n UsedFunctions.push_back(*it);\n continue;\n }\n\n if (Compartments.size() != 0)\n {\n UsedFunctions.push_back(*it);\n continue;\n }\n\n if (Events.size() != 0)\n {\n UsedFunctions.push_back(*it);\n continue;\n }\n }\n\n CEvaluationTree::completeEvaluationTreeList(UsedFunctions);\n\n return UsedFunctions;\n}\nRemoved obsolete code.\/\/ Begin CVS Header\n\/\/ $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/function\/CFunctionDB.cpp,v $\n\/\/ $Revision: 1.84 $\n\/\/ $Name: $\n\/\/ $Author: shoops $\n\/\/ $Date: 2009\/10\/26 22:08:51 $\n\/\/ End CVS Header\n\n\/\/ Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., EML Research, gGmbH, University of Heidelberg,\n\/\/ and The University of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc. and EML Research, gGmbH.\n\/\/ All rights reserved.\n\n\/**\n * CFunctionDB\n *\n * Created for Copasi by Stefan Hoops\n * (C) Stefan Hoops 2001\n *\/\n\n#include \n\n#include \"copasi.h\"\n\n#include \"CFunctionDB.h\"\n#include \"CFunction.h\"\n#include \"FunctionDB.xml.h\"\n\n#include \"utilities\/CCopasiException.h\"\n#include \"report\/CCopasiObjectReference.h\"\n#include \"report\/CKeyFactory.h\"\n#include \"xml\/CCopasiXML.h\"\n#include \"model\/CModel.h\"\n\nCFunctionDB::CFunctionDB(const std::string & name,\n const CCopasiContainer * pParent):\n CCopasiContainer(name, pParent, \"FunctionDB\"),\n mFilename(),\n mLoadedFunctions(\"Functions\", this)\n{\n initObjects();\n CONSTRUCTOR_TRACE;\n}\n\nCFunctionDB::~CFunctionDB()\n{\n cleanup();\n DESTRUCTOR_TRACE;\n}\n\nvoid CFunctionDB::cleanup() {mLoadedFunctions.cleanup();}\n\nvoid CFunctionDB::initObjects()\n{\n addObjectReference(\"File\", mFilename);\n}\n\nbool CFunctionDB::load()\n{\n CCopasiXML XML;\n XML.setFunctionList(&mLoadedFunctions);\n\n std::stringstream DB;\n DB.str(FunctionDBxml);\n\n if (DB.fail())\n return false;\n\n if (!XML.load(DB, \"\"))\n return false;\n\n return true;\n}\n\nC_INT32 CFunctionDB::load(CReadConfig &configbuffer)\n{\n CFunction Function;\n CFunction * pFunction = NULL;\n\n C_INT32 Size = 0;\n C_INT32 Fail = 0;\n\n configbuffer.getVariable(\"TotalUDKinetics\", \"C_INT32\", &Size,\n CReadConfig::LOOP);\n\n for (C_INT32 i = 0; i < Size; i++)\n {\n Function.load(configbuffer);\n\n switch (Function.getType())\n {\n case CEvaluationTree::Function:\n pFunction = new CFunction(Function);\n break;\n\n case CEvaluationTree::MassAction:\n pFunction = new CMassAction(Function);\n break;\n\n case CEvaluationTree::PreDefined:\n case CEvaluationTree::UserDefined:\n pFunction = new CKinFunction(Function,\n &configbuffer);\n break;\n\n default:\n fatalError();\n }\n\n pFunction->compile();\n\n if (!mLoadedFunctions.add(pFunction, true))\n {\n pdelete(pFunction);\n\n \/\/ We ignore:\n \/\/ CCopasiVector (2): Object '%s' allready exists.\n if ((MCCopasiVector + 2) != CCopasiMessage::peekLastMessage().getNumber())\n return Fail = 1;\n\n \/\/ Remove the ignored meesage.\n CCopasiMessage::getLastMessage();\n }\n }\n\n return Fail;\n}\n\nvoid CFunctionDB::setFilename(const std::string & filename)\n{mFilename = filename;}\n\nstd::string CFunctionDB::getFilename() const\n{return mFilename;}\n\n#ifdef FFFF\nCFunction * CFunctionDB::dBLoad(const std::string & functionName)\n{\n CFunction Function(\"NoName\", &mLoadedFunctions);\n CFunction * pFunction = NULL;\n\n if (mFilename == \"\") return NULL;\n\n CReadConfig inbuf(mFilename);\n\n while (functionName != Function.getObjectName())\n {\n Function.cleanup();\n Function.load(inbuf);\n }\n\n switch (Function.getType())\n {\n case CFunction::Base:\n pFunction = new CFunction(Function);\n break;\n\n case CFunction::MassAction:\n pFunction = new CMassAction(Function.isReversible());\n break;\n\n case CFunction::PreDefined:\n\n case CFunction::UserDefined:\n pFunction = new CKinFunction(Function, &inbuf);\n break;\n\n case CFunction::Expression:\n fatalError(); \/\/disabled\n \/\/pFunction = new CUDFunction(Function);\n break;\n\n default:\n fatalError();\n }\n\n if (!mLoadedFunctions.add(pFunction))\n {\n pdelete(pFunction);\n\n \/\/ We ignore:\n \/\/ CCopasiVector (2): Object '%s' allready exists.\n if ((MCCopasiVector + 2) != CCopasiMessage::getLastMessage().getNumber())\n\n pFunction = mLoadedFunctions[Function.getObjectName()];\n }\n\n return pFunction;\n}\n#endif \/\/ FFFF\n\n#ifdef FFFF\nCEvaluationTree * CFunctionDB::createFunction(const std::string & name, const CEvaluationTree::Type & type)\n{\n if (mLoadedFunctions.getIndex(name) != C_INVALID_INDEX)\n return NULL;\n\n \/\/CFunction * pFunction = new CFunction(name);\n\n CEvaluationTree * pFunction = NULL;\n\n switch (type)\n {\n case CEvaluationTree::Base:\n pFunction = new CFunction(name);\n break;\n\n case CEvaluationTree::MassAction:\n pFunction = new CMassAction(name);\n break;\n\n case CEvaluationTree::PreDefinedKineticLaw:\n case CEvaluationTree::UserDefinedKineticLaw:\n pFunction = new CKinFunction(name);\n break;\n\n default:\n fatalError();\n }\n\n if (!mLoadedFunctions.add(pFunction, true))\n {\n delete pFunction;\n return NULL;\n }\n\n return pFunction;\n}\n#endif \/\/ FFFF\n\nbool CFunctionDB::add(CEvaluationTree * pFunction,\n const bool & adopt)\n{return mLoadedFunctions.add(pFunction, adopt);}\n\nvoid CFunctionDB::addAndAdaptName(CEvaluationTree * pFunction)\n{\n if (!pFunction) return;\n\n std::string basename = pFunction->getObjectName();\n std::string name = basename;\n \/\/CFunction* pFunc;\n \/\/CCopasiVectorN& FunctionList\n \/\/= this->loadedFunctions();\n int i = 0;\n\n while (mLoadedFunctions.getIndex(name) != C_INVALID_INDEX)\n {\n i++;\n std::ostringstream ss; ss << \"_\" << i;\n name = basename + ss.str();\n }\n\n pFunction->setObjectName(name);\n\n this->add(pFunction, true);\n}\n\nbool CFunctionDB::removeFunction(unsigned C_INT32 index)\n{\n if (index == C_INVALID_INDEX) return false;\n\n mLoadedFunctions.CCopasiVector::remove(index);\n\n return true;\n}\n\nbool CFunctionDB::removeFunction(const std::string &key)\n{\n CEvaluationTree* func = dynamic_cast< CEvaluationTree * >(CCopasiRootContainer::getKeyFactory()->get(key));\n\n if (!func) return false;\n\n unsigned C_INT32 index =\n mLoadedFunctions.CCopasiVector::getIndex(func);\n\n if (index == C_INVALID_INDEX) return false;\n\n mLoadedFunctions.CCopasiVector::remove(index);\n\n return true;\n}\n\nCEvaluationTree * CFunctionDB::findFunction(const std::string & functionName)\n{\n unsigned C_INT32 index = mLoadedFunctions.getIndex(functionName);\n\n if (index != C_INVALID_INDEX)\n return mLoadedFunctions[index];\n else\n return NULL;\n}\n\nCEvaluationTree * CFunctionDB::findLoadFunction(const std::string & functionName)\n{\n unsigned C_INT32 i;\n\n for (i = 0; i < mLoadedFunctions.size(); i++)\n if (functionName == mLoadedFunctions[i]->getObjectName())\n return mLoadedFunctions[i];\n\n return NULL;\n}\n\nCCopasiVectorN < CEvaluationTree > & CFunctionDB::loadedFunctions()\n{return mLoadedFunctions;}\n\nstd::vector\nCFunctionDB::suitableFunctions(const unsigned C_INT32 noSubstrates,\n const unsigned C_INT32 noProducts,\n const TriLogic reversibility)\n{\n std::vector ret;\n CFunction *pFunction;\n\n unsigned C_INT32 i, imax = mLoadedFunctions.size();\n\n for (i = 0; i < imax; i++)\n {\n pFunction = dynamic_cast(mLoadedFunctions[i]);\n\n if (!pFunction) continue;\n\n if (pFunction->isSuitable(noSubstrates, noProducts, reversibility))\n ret.push_back(pFunction);\n }\n\n \/\/always add constant flux it is is missing\n if (reversibility == TriTrue)\n {\n if ((noSubstrates > 0) || (noProducts > 0)) \/\/constant flux was not yet added\n {\n pFunction = dynamic_cast(findFunction(\"Constant flux (reversible)\"));\n\n if (!pFunction) fatalError();\n\n ret.push_back(pFunction);\n }\n }\n else \/\/irreversible\n {\n if (noSubstrates > 0) \/\/constant flux was not yet added\n {\n pFunction = dynamic_cast(findFunction(\"Constant flux (irreversible)\"));\n\n if (!pFunction) fatalError();\n\n ret.push_back(pFunction);\n }\n }\n\n return ret;\n}\n\nbool CFunctionDB::appendDependentFunctions(std::set< const CCopasiObject * > candidates,\n std::set< const CCopasiObject * > & dependentFunctions) const\n{\n size_t Size = dependentFunctions.size();\n\n CCopasiVectorN< CEvaluationTree >::const_iterator it = mLoadedFunctions.begin();\n CCopasiVectorN< CEvaluationTree >::const_iterator end = mLoadedFunctions.end();\n\n for (; it != end; ++it)\n if (candidates.find(*it) == candidates.end() &&\n (*it)->dependsOn(candidates))\n dependentFunctions.insert((*it));\n\n return Size < dependentFunctions.size();\n}\n\nstd::set\nCFunctionDB::listDependentTrees(const std::string & name) const\n{\n std::set List;\n\n CCopasiVectorN < CEvaluationTree >::const_iterator it = mLoadedFunctions.begin();\n CCopasiVectorN < CEvaluationTree >::const_iterator end = mLoadedFunctions.end();\n\n for (; it != end; ++it)\n if ((*it)->dependsOnTree(name))\n List.insert((*it)->getObjectName());\n\n return List;\n}\n\nstd::vector< CEvaluationTree * > CFunctionDB::getUsedFunctions(const CModel* pModel) const\n{\n std::vector< CEvaluationTree * > UsedFunctions;\n CCopasiVectorN < CEvaluationTree >::const_iterator it = mLoadedFunctions.begin();\n CCopasiVectorN < CEvaluationTree >::const_iterator end = mLoadedFunctions.end();\n\n for (; it != end; ++it)\n {\n std::set< const CCopasiObject * > Function;\n Function.insert(*it);\n\n std::set< const CCopasiObject * > Reactions;\n std::set< const CCopasiObject * > Metabolites;\n std::set< const CCopasiObject * > Values;\n std::set< const CCopasiObject * > Compartments;\n std::set< const CCopasiObject * > Events;\n\n pModel->appendDependentModelObjects(Function,\n Reactions, Metabolites, Compartments, Values, Events);\n\n if (Reactions.size() != 0)\n {\n UsedFunctions.push_back(*it);\n continue;\n }\n\n if (Metabolites.size() != 0)\n {\n UsedFunctions.push_back(*it);\n continue;\n }\n\n if (Values.size() != 0)\n {\n UsedFunctions.push_back(*it);\n continue;\n }\n\n if (Compartments.size() != 0)\n {\n UsedFunctions.push_back(*it);\n continue;\n }\n\n if (Events.size() != 0)\n {\n UsedFunctions.push_back(*it);\n continue;\n }\n }\n\n CEvaluationTree::completeEvaluationTreeList(UsedFunctions);\n\n return UsedFunctions;\n}\n<|endoftext|>"} {"text":"#include \"src\/fillers.h\"\n#include \"src\/utils.h\"\n\n\/* ***** *\/\nvoid gfx_flatFill(const gfx_Triangle *t, gfx_drawBuffer *buffer, enum TriangleType type)\n{\n const gfx_Vertex *v0 = &t->vertices[0];\n const gfx_Vertex *v1 = &t->vertices[1];\n const gfx_Vertex *v2 = &t->vertices[2];\n double invDy, dxLeft, dxRight, xLeft, xRight;\n double y, yDir = 1;\n \/\/ variables used if depth test is enabled\n float startInvZ, endInvZ, invZ0, invZ1, invZ2, invY02;\n\n if(type == FLAT_BOTTOM)\n {\n invDy = 1.f \/ (v2->position.y - v0->position.y);\n }\n else\n {\n invDy = 1.f \/ (v0->position.y - v2->position.y);\n yDir = -1;\n }\n\n dxLeft = (v2->position.x - v0->position.x) * invDy;\n dxRight = (v1->position.x - v0->position.x) * invDy;\n xLeft = v0->position.x;\n xRight = xLeft;\n\n \/\/ skip the unnecessary divisions if there's no depth testing\n if(buffer->drawOpts.depthFunc != DF_ALWAYS)\n {\n invZ0 = 1.f \/ v0->position.z;\n invZ1 = 1.f \/ v1->position.z;\n invZ2 = 1.f \/ v2->position.z;\n invY02 = 1.f \/ (v0->position.y - v2->position.y);\n }\n\n for(y = v0->position.y; ; y += yDir)\n {\n if(type == FLAT_TOP && y < v2->position.y)\n break;\n else if(type == FLAT_BOTTOM && y > v2->position.y)\n {\n \/\/ to avoid pixel wide gaps, render extra line at the junction between two final points\n if(buffer->drawOpts.depthFunc != DF_ALWAYS)\n gfx_drawLine(xLeft-dxLeft, y, 1.f\/startInvZ, xRight-dxRight, y, 1.f\/endInvZ, t->color, buffer);\n else\n gfx_drawLine(xLeft-dxLeft, y, 0.f, xRight-dxRight, y, 0.f, t->color, buffer);\n break;\n }\n\n \/\/ interpolate 1\/z only if depth testing is enabled\n if(buffer->drawOpts.depthFunc != DF_ALWAYS)\n {\n float r1 = (v0->position.y - y) * invY02;\n startInvZ = LERP(invZ0, invZ2, r1);\n endInvZ = LERP(invZ0, invZ1, r1);\n gfx_drawLine(xLeft, y, 1.f\/startInvZ, xRight, y, 1.f\/endInvZ, t->color, buffer);\n }\n else\n gfx_drawLine(xLeft, y, 0.f, xRight, y, 0.f, t->color, buffer);\n\n xLeft += dxLeft;\n xRight += dxRight;\n }\n}\n\n\/* ***** *\/\nvoid gfx_perspectiveTextureMap(const gfx_Triangle *t, gfx_drawBuffer *buffer, enum TriangleType type)\n{\n const gfx_Vertex *v0 = &t->vertices[0];\n const gfx_Vertex *v1 = &t->vertices[1];\n const gfx_Vertex *v2 = &t->vertices[2];\n double x, y, invDy, dxLeft, dxRight, yDir = 1;\n int useColorKey = buffer->drawOpts.colorKey != -1 ? 1 : 0;\n int texW = t->texture->width - 1;\n int texH = t->texture->height - 1;\n int texArea = texW * texH;\n float startX = v0->position.x;\n float endX = startX;\n float invZ0, invZ1, invZ2, invY02 = 1.f;\n int finished = 0;\n\n if(type == FLAT_BOTTOM)\n {\n invDy = 1.f \/ (v2->position.y - v0->position.y);\n }\n else\n {\n invDy = 1.f \/ (v0->position.y - v2->position.y);\n yDir = -1;\n }\n\n dxLeft = (v2->position.x - v0->position.x) * invDy;\n dxRight = (v1->position.x - v0->position.x) * invDy;\n\n invZ0 = 1.f \/ v0->position.z;\n invZ1 = 1.f \/ v1->position.z;\n invZ2 = 1.f \/ v2->position.z;\n invY02 = 1.f \/ (v0->position.y - v2->position.y);\n\n for(y = v0->position.y; ; y += yDir)\n {\n float startInvZ, endInvZ, r1, invLineLength = 0.f;\n float startU = texW, startV = texH, endU = texW, endV = texH;\n\n if(type == FLAT_BOTTOM && y > v2->position.y)\n {\n \/\/ in final iteration draw extra scanline to avoid pixel wide gaps\n startX -= dxLeft;\n endX -= dxRight;\n y = v2->position.y;\n finished = 1;\n }\n else if ( type == FLAT_TOP && y < v2->position.y)\n break;\n\n r1 = (v0->position.y - y) * invY02;\n startInvZ = LERP(invZ0, invZ2, r1);\n endInvZ = LERP(invZ0, invZ1, r1);\n\n startU *= LERP(v0->uv.u * invZ0, v2->uv.u * invZ2, r1);\n startV *= LERP(v0->uv.v * invZ0, v2->uv.v * invZ2, r1);\n endU *= LERP(v0->uv.u * invZ0, v1->uv.u * invZ1, r1);\n endV *= LERP(v0->uv.v * invZ0, v1->uv.v * invZ1, r1);\n\n if(startX != endX)\n invLineLength = 1.f \/ (endX - startX);\n\n for(x = startX; x <= endX; ++x)\n {\n \/\/ interpolate 1\/z for each pixel in the scanline\n float r = (x - startX) * invLineLength;\n float lerpInvZ = LERP(startInvZ, endInvZ, r);\n float z = 1.f\/lerpInvZ;\n float u = z * LERP(startU, endU, r);\n float v = z * LERP(startV, endV, r);\n\n \/\/ fetch texture data with a texArea modulus for proper effect in case u or v are > 1\n unsigned char pixel = t->texture->data[((int)u + ((int)v * t->texture->height)) % texArea];\n\n if(!useColorKey || (useColorKey && pixel != (unsigned char)buffer->drawOpts.colorKey))\n {\n \/\/ DF_ALWAYS = no depth test\n if(buffer->drawOpts.depthFunc == DF_ALWAYS)\n gfx_drawPixel(x, y, pixel, buffer);\n else\n gfx_drawPixelWithDepth(x, y, lerpInvZ, pixel, buffer);\n }\n }\n\n startX += dxLeft;\n endX += dxRight;\n\n if(finished) break;\n }\n}\n\n\/* ***** *\/\nvoid gfx_affineTextureMap(const gfx_Triangle *t, gfx_drawBuffer *buffer, enum TriangleType type)\n{\n const gfx_Vertex *v0 = &t->vertices[0];\n const gfx_Vertex *v1 = &t->vertices[1];\n const gfx_Vertex *v2 = &t->vertices[2];\n double x, y, invDy, dxLeft, dxRight, yDir = 1;\n int useColorKey = buffer->drawOpts.colorKey != -1 ? 1 : 0;\n float duLeft, dvLeft, duRight, dvRight;\n float startU, startV, invDx, du, dv, startX, endX;\n float texW = t->texture->width - 1;\n float texH = t->texture->height - 1;\n int texArea = texW * texH;\n \/\/ variables used only if depth test is enabled\n float invZ0, invZ1, invZ2, invY02 = 1.f;\n int finished = 0;\n\n if(type == FLAT_BOTTOM)\n {\n invDy = 1.f \/ (v2->position.y - v0->position.y);\n }\n else\n {\n invDy = 1.f \/ (v0->position.y - v2->position.y);\n yDir = -1;\n }\n\n dxLeft = (v2->position.x - v0->position.x) * invDy;\n dxRight = (v1->position.x - v0->position.x) * invDy;\n\n duLeft = texW * (v2->uv.u - v0->uv.u) * invDy;\n dvLeft = texH * (v2->uv.v - v0->uv.v) * invDy;\n duRight = texW * (v1->uv.u - v0->uv.u) * invDy;\n dvRight = texH * (v1->uv.v - v0->uv.v) * invDy;\n\n startU = texW * v0->uv.u;\n startV = texH * v0->uv.v;\n \/\/ With triangles the texture gradients (u,v slopes over the triangle surface)\n \/\/ are guaranteed to be constant, so we need to calculate du and dv only once.\n invDx = 1.f \/ (dxRight - dxLeft);\n du = (duRight - duLeft) * invDx;\n dv = (dvRight - dvLeft) * invDx;\n startX = v0->position.x;\n endX = startX;\n\n \/\/ skip the unnecessary divisions if there's no depth testing\n if(buffer->drawOpts.depthFunc != DF_ALWAYS)\n {\n invZ0 = 1.f \/ v0->position.z;\n invZ1 = 1.f \/ v1->position.z;\n invZ2 = 1.f \/ v2->position.z;\n invY02 = 1.f \/ (v0->position.y - v2->position.y);\n }\n\n for(y = v0->position.y; ; y += yDir)\n {\n float u = startU;\n float v = startV;\n \/\/ variables used only if depth test is enabled\n float startInvZ, endInvZ, invLineLength = 0.f;\n\n if(type == FLAT_BOTTOM && y > v2->position.y)\n {\n \/\/ in final iteration draw extra scanline to avoid pixel wide gaps\n u -= duLeft;\n v -= dvLeft;\n startX -= dxLeft;\n endX -= dxRight;\n finished = 1;\n }\n else if ( type == FLAT_TOP && y < v2->position.y)\n break;\n\n \/\/ interpolate 1\/z only if depth testing is enabled\n if(buffer->drawOpts.depthFunc != DF_ALWAYS)\n {\n float r1 = (v0->position.y - y) * invY02;\n startInvZ = LERP(invZ0, invZ2, r1);\n endInvZ = LERP(invZ0, invZ1, r1);\n\n if(startX != endX)\n invLineLength = 1.f \/ (endX - startX);\n }\n\n for(x = startX; x <= endX; ++x)\n {\n \/\/ fetch texture data with a texArea modulus for proper effect in case u or v are > 1\n unsigned char pixel = t->texture->data[((int)u + ((int)v * t->texture->height)) % texArea];\n\n if(!useColorKey || (useColorKey && pixel != (unsigned char)buffer->drawOpts.colorKey))\n {\n \/\/ DF_ALWAYS = no depth test\n if(buffer->drawOpts.depthFunc == DF_ALWAYS)\n gfx_drawPixel(x, y, pixel, buffer);\n else\n {\n float r = (x - startX) * invLineLength;\n float lerpInvZ = LERP(startInvZ, endInvZ, r);\n gfx_drawPixelWithDepth(x, y, lerpInvZ, pixel, buffer);\n }\n }\n u += du;\n v += dv;\n }\n\n startX += dxLeft;\n endX += dxRight;\n startU += duLeft;\n startV += dvLeft;\n\n if(finished) break;\n }\n}\nslightly tighter scanline gap handling for triangle rendering#include \"src\/fillers.h\"\n#include \"src\/utils.h\"\n\n\/* ***** *\/\nvoid gfx_flatFill(const gfx_Triangle *t, gfx_drawBuffer *buffer, enum TriangleType type)\n{\n const gfx_Vertex *v0 = &t->vertices[0];\n const gfx_Vertex *v1 = &t->vertices[1];\n const gfx_Vertex *v2 = &t->vertices[2];\n double y, invDy, dxLeft, dxRight, xLeft, xRight;\n int currLine, numScanlines, yDir = 1;\n \/\/ variables used if depth test is enabled\n float startInvZ, endInvZ, invZ0, invZ1, invZ2, invY02;\n\n if(type == FLAT_BOTTOM)\n {\n invDy = 1.0 \/ (v2->position.y - v0->position.y);\n numScanlines = ceil(v2->position.y) - ceil(v0->position.y);\n }\n else\n {\n invDy = 1.0 \/ (v0->position.y - v2->position.y);\n yDir = -1;\n numScanlines = ceil(v0->position.y) - ceil(v2->position.y);\n }\n\n dxLeft = (v2->position.x - v0->position.x) * invDy;\n dxRight = (v1->position.x - v0->position.x) * invDy;\n xLeft = v0->position.x;\n xRight = xLeft;\n\n \/\/ skip the unnecessary divisions if there's no depth testing\n if(buffer->drawOpts.depthFunc != DF_ALWAYS)\n {\n invZ0 = 1.f \/ v0->position.z;\n invZ1 = 1.f \/ v1->position.z;\n invZ2 = 1.f \/ v2->position.z;\n invY02 = 1.f \/ (v0->position.y - v2->position.y);\n }\n\n for(currLine = 0, y = v0->position.y; currLine <= numScanlines; y += yDir)\n {\n \/\/ interpolate 1\/z only if depth testing is enabled\n if(buffer->drawOpts.depthFunc != DF_ALWAYS)\n {\n float r1 = (v0->position.y - y) * invY02;\n startInvZ = LERP(invZ0, invZ2, r1);\n endInvZ = LERP(invZ0, invZ1, r1);\n gfx_drawLine(xLeft, y, 1.f\/startInvZ, xRight, y, 1.f\/endInvZ, t->color, buffer);\n }\n else\n gfx_drawLine(xLeft, y, 0.f, xRight, y, 0.f, t->color, buffer);\n\n xLeft += dxLeft;\n xRight += dxRight;\n\n if(++currLine == numScanlines)\n {\n xLeft -= dxLeft;\n xRight -= dxRight;\n }\n }\n}\n\n\/* ***** *\/\nvoid gfx_perspectiveTextureMap(const gfx_Triangle *t, gfx_drawBuffer *buffer, enum TriangleType type)\n{\n const gfx_Vertex *v0 = &t->vertices[0];\n const gfx_Vertex *v1 = &t->vertices[1];\n const gfx_Vertex *v2 = &t->vertices[2];\n double x, y, invDy, dxLeft, dxRight, yDir = 1;\n int useColorKey = buffer->drawOpts.colorKey != -1 ? 1 : 0;\n int texW = t->texture->width - 1;\n int texH = t->texture->height - 1;\n int texArea = texW * texH;\n float startX = v0->position.x;\n float endX = startX;\n float invZ0, invZ1, invZ2, invY02 = 1.f;\n int currLine, numScanlines;\n\n if(type == FLAT_BOTTOM)\n {\n invDy = 1.0 \/ (v2->position.y - v0->position.y);\n numScanlines = ceil(v2->position.y) - ceil(v0->position.y);\n }\n else\n {\n invDy = 1.0 \/ (v0->position.y - v2->position.y);\n numScanlines = ceil(v0->position.y) - ceil(v2->position.y);\n yDir = -1;\n }\n\n dxLeft = (v2->position.x - v0->position.x) * invDy;\n dxRight = (v1->position.x - v0->position.x) * invDy;\n\n invZ0 = 1.f \/ v0->position.z;\n invZ1 = 1.f \/ v1->position.z;\n invZ2 = 1.f \/ v2->position.z;\n invY02 = 1.f \/ (v0->position.y - v2->position.y);\n\n for(currLine = 0, y = v0->position.y; currLine <= numScanlines; y += yDir)\n {\n float startInvZ, endInvZ, r1, invLineLength = 0.f;\n float startU = texW, startV = texH, endU = texW, endV = texH;\n\n r1 = (v0->position.y - y) * invY02;\n startInvZ = LERP(invZ0, invZ2, r1);\n endInvZ = LERP(invZ0, invZ1, r1);\n\n startU *= LERP(v0->uv.u * invZ0, v2->uv.u * invZ2, r1);\n startV *= LERP(v0->uv.v * invZ0, v2->uv.v * invZ2, r1);\n endU *= LERP(v0->uv.u * invZ0, v1->uv.u * invZ1, r1);\n endV *= LERP(v0->uv.v * invZ0, v1->uv.v * invZ1, r1);\n\n if(startX != endX)\n invLineLength = 1.f \/ (endX - startX);\n\n for(x = startX; x <= endX; ++x)\n {\n \/\/ interpolate 1\/z for each pixel in the scanline\n float r = (x - startX) * invLineLength;\n float lerpInvZ = LERP(startInvZ, endInvZ, r);\n float z = 1.f\/lerpInvZ;\n float u = z * LERP(startU, endU, r);\n float v = z * LERP(startV, endV, r);\n\n \/\/ fetch texture data with a texArea modulus for proper effect in case u or v are > 1\n unsigned char pixel = t->texture->data[((int)u + ((int)v * t->texture->height)) % texArea];\n\n if(!useColorKey || (useColorKey && pixel != (unsigned char)buffer->drawOpts.colorKey))\n {\n \/\/ DF_ALWAYS = no depth test\n if(buffer->drawOpts.depthFunc == DF_ALWAYS)\n gfx_drawPixel(x, y, pixel, buffer);\n else\n gfx_drawPixelWithDepth(x, y, lerpInvZ, pixel, buffer);\n }\n }\n\n startX += dxLeft;\n endX += dxRight;\n\n if(++currLine == numScanlines)\n {\n startX -= dxLeft;\n endX -= dxRight;\n }\n }\n}\n\n\/* ***** *\/\nvoid gfx_affineTextureMap(const gfx_Triangle *t, gfx_drawBuffer *buffer, enum TriangleType type)\n{\n const gfx_Vertex *v0 = &t->vertices[0];\n const gfx_Vertex *v1 = &t->vertices[1];\n const gfx_Vertex *v2 = &t->vertices[2];\n double x, y, invDy, dxLeft, dxRight, yDir = 1;\n int useColorKey = buffer->drawOpts.colorKey != -1 ? 1 : 0;\n float duLeft, dvLeft, duRight, dvRight;\n float startU, startV, invDx, du, dv, startX, endX;\n float texW = t->texture->width - 1;\n float texH = t->texture->height - 1;\n int texArea = texW * texH;\n \/\/ variables used only if depth test is enabled\n float invZ0, invZ1, invZ2, invY02 = 1.f;\n int currLine, numScanlines;\n\n if(type == FLAT_BOTTOM)\n {\n invDy = 1.f \/ (v2->position.y - v0->position.y);\n numScanlines = ceil(v2->position.y) - ceil(v0->position.y);\n }\n else\n {\n invDy = 1.f \/ (v0->position.y - v2->position.y);\n numScanlines = ceil(v0->position.y) - ceil(v2->position.y);\n yDir = -1;\n }\n\n dxLeft = (v2->position.x - v0->position.x) * invDy;\n dxRight = (v1->position.x - v0->position.x) * invDy;\n\n duLeft = texW * (v2->uv.u - v0->uv.u) * invDy;\n dvLeft = texH * (v2->uv.v - v0->uv.v) * invDy;\n duRight = texW * (v1->uv.u - v0->uv.u) * invDy;\n dvRight = texH * (v1->uv.v - v0->uv.v) * invDy;\n\n startU = texW * v0->uv.u;\n startV = texH * v0->uv.v;\n \/\/ With triangles the texture gradients (u,v slopes over the triangle surface)\n \/\/ are guaranteed to be constant, so we need to calculate du and dv only once.\n invDx = 1.f \/ (dxRight - dxLeft);\n du = (duRight - duLeft) * invDx;\n dv = (dvRight - dvLeft) * invDx;\n startX = v0->position.x;\n endX = startX;\n\n \/\/ skip the unnecessary divisions if there's no depth testing\n if(buffer->drawOpts.depthFunc != DF_ALWAYS)\n {\n invZ0 = 1.f \/ v0->position.z;\n invZ1 = 1.f \/ v1->position.z;\n invZ2 = 1.f \/ v2->position.z;\n invY02 = 1.f \/ (v0->position.y - v2->position.y);\n }\n\n for(currLine = 0, y = v0->position.y; currLine <= numScanlines ; y += yDir)\n {\n float u = startU;\n float v = startV;\n \/\/ variables used only if depth test is enabled\n float startInvZ, endInvZ, invLineLength = 0.f;\n\n \/\/ interpolate 1\/z only if depth testing is enabled\n if(buffer->drawOpts.depthFunc != DF_ALWAYS)\n {\n float r1 = (v0->position.y - y) * invY02;\n startInvZ = LERP(invZ0, invZ2, r1);\n endInvZ = LERP(invZ0, invZ1, r1);\n\n if(startX != endX)\n invLineLength = 1.f \/ (endX - startX);\n }\n\n for(x = startX; x <= endX; ++x)\n {\n \/\/ fetch texture data with a texArea modulus for proper effect in case u or v are > 1\n unsigned char pixel = t->texture->data[((int)u + ((int)v * t->texture->height)) % texArea];\n\n if(!useColorKey || (useColorKey && pixel != (unsigned char)buffer->drawOpts.colorKey))\n {\n \/\/ DF_ALWAYS = no depth test\n if(buffer->drawOpts.depthFunc == DF_ALWAYS)\n gfx_drawPixel(x, y, pixel, buffer);\n else\n {\n float r = (x - startX) * invLineLength;\n float lerpInvZ = LERP(startInvZ, endInvZ, r);\n gfx_drawPixelWithDepth(x, y, lerpInvZ, pixel, buffer);\n }\n }\n u += du;\n v += dv;\n }\n\n startX += dxLeft;\n endX += dxRight;\n startU += duLeft;\n startV += dvLeft;\n\n if(++currLine == numScanlines)\n {\n startX -= dxLeft;\n endX -= dxRight;\n startU -= duLeft;\n startV -= dvLeft;\n }\n }\n}\n<|endoftext|>"} {"text":"#include \"bbprojectmanager.hpp\"\n#include \"bbprojectmanagerplugin.hpp\"\n#include \"bbprojectmanagerconstants.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace BoostBuildProjectManager { namespace Internal {\n\nBoostBuildPlugin::BoostBuildPlugin()\n{\n \/\/ Create your members\n}\n\nBoostBuildPlugin::~BoostBuildPlugin()\n{\n \/\/ Unregister objects from the plugin manager's object pool\n \/\/ Delete members\n}\n\nbool BoostBuildPlugin::initialize(QStringList const& arguments, QString* errorString)\n{\n Q_UNUSED(arguments)\n\n \/\/ Register objects in the plugin manager's object pool\n \/\/ Load settings\n \/\/ Add actions to menus\n \/\/ Connect to other plugins' signals\n \/\/ In the initialize function, a plugin can be sure that the plugins it\n \/\/ depends on have initialized their members.\n\n QLatin1String const mimeTypes(\":boostbuildproject\/BoostBuildProjectManager.mimetypes.xml\");\n if (!Core::MimeDatabase::addMimeTypes(mimeTypes, errorString))\n return false;\n\n addAutoReleasedObject(new ProjectManager);\n\n return true;\n}\n\nvoid BoostBuildPlugin::extensionsInitialized()\n{\n \/\/ Retrieve objects from the plugin manager's object pool\n \/\/ In the extensionsInitialized function, a plugin can be sure that all\n \/\/ plugins that depend on it are completely initialized.\n}\n\nExtensionSystem::IPlugin::ShutdownFlag BoostBuildPlugin::aboutToShutdown()\n{\n \/\/ Save settings\n \/\/ Disconnect from signals that are not needed during shutdown\n \/\/ Hide UI (if you add UI that is not in the main window directly)\n return SynchronousShutdown;\n}\n\n}}\nAdd BuildConfigurationFactory and BuildStepFactory to auto-released objects#include \"bbbuildconfiguration.hpp\"\n#include \"bbbuildstep.hpp\"\n#include \"bbprojectmanager.hpp\"\n#include \"bbprojectmanagerplugin.hpp\"\n#include \"bbprojectmanagerconstants.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace BoostBuildProjectManager { namespace Internal {\n\nBoostBuildPlugin::BoostBuildPlugin()\n{\n \/\/ Create your members\n}\n\nBoostBuildPlugin::~BoostBuildPlugin()\n{\n \/\/ Unregister objects from the plugin manager's object pool\n \/\/ Delete members\n}\n\nbool BoostBuildPlugin::initialize(QStringList const& arguments, QString* errorString)\n{\n Q_UNUSED(arguments)\n\n \/\/ Register objects in the plugin manager's object pool\n \/\/ Load settings\n \/\/ Add actions to menus\n \/\/ Connect to other plugins' signals\n \/\/ In the initialize function, a plugin can be sure that the plugins it\n \/\/ depends on have initialized their members.\n\n QLatin1String const mimeTypes(\":boostbuildproject\/BoostBuildProjectManager.mimetypes.xml\");\n if (!Core::MimeDatabase::addMimeTypes(mimeTypes, errorString))\n return false;\n\n addAutoReleasedObject(new BuildConfigurationFactory);\n addAutoReleasedObject(new BuildStepFactory);\n \/\/TODO addAutoReleasedObject(new RunConfigurationFactory);\n addAutoReleasedObject(new ProjectManager);\n\n return true;\n}\n\nvoid BoostBuildPlugin::extensionsInitialized()\n{\n \/\/ Retrieve objects from the plugin manager's object pool\n \/\/ In the extensionsInitialized function, a plugin can be sure that all\n \/\/ plugins that depend on it are completely initialized.\n}\n\nExtensionSystem::IPlugin::ShutdownFlag BoostBuildPlugin::aboutToShutdown()\n{\n \/\/ Save settings\n \/\/ Disconnect from signals that are not needed during shutdown\n \/\/ Hide UI (if you add UI that is not in the main window directly)\n return SynchronousShutdown;\n}\n\n}}\n<|endoftext|>"} {"text":"\/*\n * FastRPC -- Fast RPC library compatible with XML-RPC\n * Copyright (C) 2005-7 Seznam.cz, a.s.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * Seznam.cz, a.s.\n * Radlicka 2, Praha 5, 15000, Czech Republic\n * http:\/\/www.seznam.cz, mailto:fastrpc@firma.seznam.cz\n *\n * FILE $Id: frpcserverproxy.cc,v 1.11 2011-02-18 10:37:45 skeleton-golem Exp $\n *\n * DESCRIPTION\n *\n * AUTHOR\n * Miroslav Talasek \n *\n * HISTORY\n *\n *\/\n\n#include \n#include \n\n#include \n\n#include \"frpcserverproxy.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\nnamespace {\n FRPC::Pool_t localPool;\n\n int getTimeout(const FRPC::Struct_t &config, const std::string &name,\n int defaultValue)\n {\n \/\/ get key from config and check for existence\n const FRPC::Value_t *val(config.get(name));\n if (!val) return defaultValue;\n\n \/\/ OK\n return FRPC::Int(*val);\n }\n\n FRPC::ProtocolVersion_t parseProtocolVersion(const FRPC::Struct_t &config,\n const std::string &name)\n {\n std::string strver\n (FRPC::String(config.get(name, FRPC::String_t::FRPC_EMPTY)));\n \/\/ empty\/undefined => current version\n if (strver.empty()) return FRPC::ProtocolVersion_t();\n\n \/\/ parse input\n std::istringstream is(strver);\n int major, minor;\n is >> major >> minor;\n\n \/\/ OK\n return FRPC::ProtocolVersion_t(major, minor);\n }\n\n FRPC::ServerProxy_t::Config_t configFromStruct(const FRPC::Struct_t &s)\n {\n FRPC::ServerProxy_t::Config_t config;\n\n config.proxyUrl = FRPC::String(s.get(\"proxyUrl\", FRPC::String_t::FRPC_EMPTY));\n config.readTimeout = getTimeout(s, \"readTimeout\", 10000);\n config.writeTimeout = getTimeout(s, \"writeTimeout\", 1000);\n config.useBinary = FRPC::Int(s.get(\"transferMode\", FRPC::Int_t::FRPC_ZERO));\n config.useHTTP10 = FRPC::Bool(s.get(\"useHTTP10\", FRPC::Bool_t::FRPC_FALSE));\n config.protocolVersion = parseProtocolVersion(s, \"protocolVersion\");\n config.connectTimeout = getTimeout(s, \"connectTimeout\", 10000);\n config.keepAlive = FRPC::Bool(s.get(\"keepAlive\", FRPC::Bool_t::FRPC_FALSE));\n\n return config;\n }\n}\n\nnamespace FRPC {\n\nclass ServerProxyImpl_t {\npublic:\n ServerProxyImpl_t(const std::string &server,\n const ServerProxy_t::Config_t &config)\n : url(server, config.proxyUrl),\n io(-1, config.readTimeout, config.writeTimeout, -1 ,-1),\n rpcTransferMode(config.useBinary), useHTTP10(config.useHTTP10),\n serverSupportedProtocols(HTTPClient_t::XML_RPC),\n protocolVersion(config.protocolVersion),\n connector(new SimpleConnectorIPv6_t(url, config.connectTimeout,\n config.keepAlive))\n {}\n\n \/** Set new read timeout *\/\n void setReadTimeout(int timeout) {\n io.setReadTimeout(timeout);\n }\n\n \/** Set new write timeout *\/\n void setWriteTimeout(int timeout) {\n io.setWriteTimeout(timeout);\n }\n\n \/** Set new connect timeout *\/\n void setConnectTimeout(int timeout) {\n connector->setTimeout(timeout);\n }\n\n const URL_t& getURL() {\n return url;\n }\n\n \/** Create marshaller.\n *\/\n Marshaller_t* createMarshaller(HTTPClient_t &client);\n\n \/** Call method.\n *\/\n Value_t& call(Pool_t &pool, const std::string &methodName,\n const Array_t ¶ms);\n\n void call(DataBuilder_t &builder, const std::string &methodName,\n const Array_t ¶ms);\n\n \/** Call method with variable number of arguments.\n *\/\n Value_t& call(Pool_t &pool, const char *methodName, va_list args);\n\nprivate:\n URL_t url;\n HTTPIO_t io;\n unsigned int rpcTransferMode;\n bool useHTTP10;\n unsigned int serverSupportedProtocols;\n ProtocolVersion_t protocolVersion;\n std::auto_ptr connector;\n};\n\nMarshaller_t* ServerProxyImpl_t::createMarshaller(HTTPClient_t &client) {\n Marshaller_t *marshaller;\n switch (rpcTransferMode) {\n case ServerProxy_t::Config_t::ON_SUPPORT:\n {\n if (serverSupportedProtocols & HTTPClient_t::BINARY_RPC) {\n \/\/using BINARY_RPC\n marshaller= Marshaller_t::create(Marshaller_t::BINARY_RPC,\n client,protocolVersion);\n client.prepare(HTTPClient_t::BINARY_RPC);\n } else {\n \/\/using XML_RPC\n marshaller = Marshaller_t::create\n (Marshaller_t::XML_RPC,client, protocolVersion);\n client.prepare(HTTPClient_t::XML_RPC);\n }\n }\n break;\n\n case ServerProxy_t::Config_t::NEVER:\n {\n \/\/ never using BINARY_RPC\n marshaller= Marshaller_t::create(Marshaller_t::XML_RPC,\n client,protocolVersion);\n client.prepare(HTTPClient_t::XML_RPC);\n }\n break;\n\n case ServerProxy_t::Config_t::ALWAYS:\n {\n \/\/using BINARY_RPC always\n marshaller= Marshaller_t::create(Marshaller_t::BINARY_RPC,\n client,protocolVersion);\n client.prepare(HTTPClient_t::BINARY_RPC);\n }\n break;\n\n case ServerProxy_t::Config_t::ON_SUPPORT_ON_KEEP_ALIVE:\n default:\n {\n if ((serverSupportedProtocols & HTTPClient_t::XML_RPC)\n || connector->getKeepAlive() == false\n || io.socket() != -1) {\n \/\/using XML_RPC\n marshaller= Marshaller_t::create\n (Marshaller_t::XML_RPC,client, protocolVersion);\n client.prepare(HTTPClient_t::XML_RPC);\n } else {\n \/\/using BINARY_RPC\n marshaller= Marshaller_t::create\n (Marshaller_t::BINARY_RPC, client,protocolVersion);\n client.prepare(HTTPClient_t::BINARY_RPC);\n }\n }\n break;\n }\n\n \/\/ OK\n return marshaller;\n}\n\nServerProxy_t::ServerProxy_t(const std::string &server, const Config_t &config)\n : sp(new ServerProxyImpl_t(server, config))\n{}\n\nServerProxy_t::ServerProxy_t(const std::string &server, const Struct_t &config)\n : sp(new ServerProxyImpl_t(server, configFromStruct(config)))\n{}\n\n\nServerProxy_t::~ServerProxy_t() {\n \/\/ get rid of implementation\n}\n\nValue_t& ServerProxyImpl_t::call(Pool_t &pool, const std::string &methodName,\n const Array_t ¶ms)\n{\n HTTPClient_t client(io, url, connector.get(), useHTTP10);\n TreeBuilder_t builder(pool);\n std::auto_ptrmarshaller(createMarshaller(client));\n TreeFeeder_t feeder(*marshaller);\n\n try {\n marshaller->packMethodCall(methodName.c_str());\n for (Array_t::const_iterator\n iparams = params.begin(),\n eparams = params.end();\n iparams != eparams; ++iparams) {\n feeder.feedValue(**iparams);\n }\n\n marshaller->flush();\n } catch (const ResponseError_t &e) {}\n\n client.readResponse(builder);\n serverSupportedProtocols = client.getSupportedProtocols();\n protocolVersion = client.getProtocolVersion();\n if (&(builder.getUnMarshaledData()) == 0)\n throw Fault_t(builder.getUnMarshaledErrorNumber(),\n builder.getUnMarshaledErrorMessage());\n\n \/\/ OK, return unmarshalled data\n return builder.getUnMarshaledData();\n}\n\n\nvoid ServerProxyImpl_t::call(DataBuilder_t &builder, const std::string &methodName,\n const Array_t ¶ms)\n{\n HTTPClient_t client(io, url, connector.get(), useHTTP10);\n std::auto_ptrmarshaller(createMarshaller(client));\n TreeFeeder_t feeder(*marshaller);\n\n try {\n marshaller->packMethodCall(methodName.c_str());\n for (Array_t::const_iterator\n iparams = params.begin(),\n eparams = params.end();\n iparams != eparams; ++iparams) {\n feeder.feedValue(**iparams);\n }\n\n marshaller->flush();\n } catch (const ResponseError_t &e) {}\n\n client.readResponse(builder);\n serverSupportedProtocols = client.getSupportedProtocols();\n protocolVersion = client.getProtocolVersion();\n}\n\n\nValue_t& ServerProxy_t::call(Pool_t &pool, const std::string &methodName,\n const Array_t ¶ms)\n{\n return sp->call(pool, methodName, params);\n}\n\nValue_t& ServerProxyImpl_t::call(Pool_t &pool, const char *methodName,\n va_list args)\n{\n HTTPClient_t client(io, url, connector.get(), useHTTP10);\n TreeBuilder_t builder(pool);\n std::auto_ptrmarshaller(createMarshaller(client));\n TreeFeeder_t feeder(*marshaller);\n\n try {\n marshaller->packMethodCall(methodName);\n\n \/\/ marshall all passed values until null pointer\n while (const Value_t *value = va_arg(args, Value_t*))\n feeder.feedValue(*value);\n\n marshaller->flush();\n } catch (const ResponseError_t &e) {}\n\n client.readResponse(builder);\n serverSupportedProtocols = client.getSupportedProtocols();\n protocolVersion = client.getProtocolVersion();\n if(&(builder.getUnMarshaledData()) == 0)\n throw Fault_t(builder.getUnMarshaledErrorNumber(),\n builder.getUnMarshaledErrorMessage());\n\n \/\/ OK, return unmarshalled data\n return builder.getUnMarshaledData();\n}\n\nnamespace {\n \/** Hold va_list and destroy it (via va_end) on destruction.\n *\/\n struct VaListHolder_t {\n VaListHolder_t(va_list &args) : args(args) {}\n ~VaListHolder_t() { va_end(args); }\n va_list &args;\n };\n}\n\nValue_t& ServerProxy_t::call(Pool_t &pool, const char *methodName, ...) {\n \/\/ get variadic arguments\n va_list args;\n va_start(args, methodName);\n VaListHolder_t argsHolder(args);\n\n \/\/ use implementation\n return sp->call(pool, methodName, args);\n}\n\nvoid ServerProxy_t::call(DataBuilder_t &builder,\n const std::string &methodName, const Array_t ¶ms)\n{\n sp->call(builder, methodName, params);\n}\n\nvoid ServerProxy_t::setReadTimeout(int timeout) {\n sp->setReadTimeout(timeout);\n}\n\nvoid ServerProxy_t::setWriteTimeout(int timeout) {\n sp->setWriteTimeout(timeout);\n}\n\nvoid ServerProxy_t::setConnectTimeout(int timeout) {\n sp->setConnectTimeout(timeout);\n}\n\nconst URL_t& ServerProxy_t::getURL() {\n return sp->getURL();\n}\n\n} \/\/ namespace FRPC\n\nServerProxy_t supports unix:\/\/ schema\/*\n * FastRPC -- Fast RPC library compatible with XML-RPC\n * Copyright (C) 2005-7 Seznam.cz, a.s.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * Seznam.cz, a.s.\n * Radlicka 2, Praha 5, 15000, Czech Republic\n * http:\/\/www.seznam.cz, mailto:fastrpc@firma.seznam.cz\n *\n * FILE $Id: frpcserverproxy.cc,v 1.11 2011-02-18 10:37:45 skeleton-golem Exp $\n *\n * DESCRIPTION\n *\n * AUTHOR\n * Miroslav Talasek \n *\n * HISTORY\n *\n *\/\n\n#include \n#include \n\n#include \n\n#include \"frpcserverproxy.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\nnamespace {\n FRPC::Pool_t localPool;\n\n int getTimeout(const FRPC::Struct_t &config, const std::string &name,\n int defaultValue)\n {\n \/\/ get key from config and check for existence\n const FRPC::Value_t *val(config.get(name));\n if (!val) return defaultValue;\n\n \/\/ OK\n return FRPC::Int(*val);\n }\n\n FRPC::ProtocolVersion_t parseProtocolVersion(const FRPC::Struct_t &config,\n const std::string &name)\n {\n std::string strver\n (FRPC::String(config.get(name, FRPC::String_t::FRPC_EMPTY)));\n \/\/ empty\/undefined => current version\n if (strver.empty()) return FRPC::ProtocolVersion_t();\n\n \/\/ parse input\n std::istringstream is(strver);\n int major, minor;\n is >> major >> minor;\n\n \/\/ OK\n return FRPC::ProtocolVersion_t(major, minor);\n }\n\n FRPC::ServerProxy_t::Config_t configFromStruct(const FRPC::Struct_t &s)\n {\n FRPC::ServerProxy_t::Config_t config;\n\n config.proxyUrl = FRPC::String(s.get(\"proxyUrl\", FRPC::String_t::FRPC_EMPTY));\n config.readTimeout = getTimeout(s, \"readTimeout\", 10000);\n config.writeTimeout = getTimeout(s, \"writeTimeout\", 1000);\n config.useBinary = FRPC::Int(s.get(\"transferMode\", FRPC::Int_t::FRPC_ZERO));\n config.useHTTP10 = FRPC::Bool(s.get(\"useHTTP10\", FRPC::Bool_t::FRPC_FALSE));\n config.protocolVersion = parseProtocolVersion(s, \"protocolVersion\");\n config.connectTimeout = getTimeout(s, \"connectTimeout\", 10000);\n config.keepAlive = FRPC::Bool(s.get(\"keepAlive\", FRPC::Bool_t::FRPC_FALSE));\n\n return config;\n }\n\n FRPC::Connector_t* makeConnector(\n const FRPC::URL_t &url,\n const unsigned &connectTimeout,\n const bool &keepAlive)\n {\n if (url.isUnix()) {\n return new FRPC::SimpleConnectorUnix_t(\n url, connectTimeout, keepAlive);\n }\n return new FRPC::SimpleConnectorIPv6_t(url, connectTimeout, keepAlive);\n }\n}\n\nnamespace FRPC {\n\nclass ServerProxyImpl_t {\npublic:\n ServerProxyImpl_t(const std::string &server,\n const ServerProxy_t::Config_t &config)\n : url(server, config.proxyUrl),\n io(-1, config.readTimeout, config.writeTimeout, -1 ,-1),\n rpcTransferMode(config.useBinary), useHTTP10(config.useHTTP10),\n serverSupportedProtocols(HTTPClient_t::XML_RPC),\n protocolVersion(config.protocolVersion),\n connector(makeConnector(url, config.connectTimeout,\n config.keepAlive))\n {}\n\n \/** Set new read timeout *\/\n void setReadTimeout(int timeout) {\n io.setReadTimeout(timeout);\n }\n\n \/** Set new write timeout *\/\n void setWriteTimeout(int timeout) {\n io.setWriteTimeout(timeout);\n }\n\n \/** Set new connect timeout *\/\n void setConnectTimeout(int timeout) {\n connector->setTimeout(timeout);\n }\n\n const URL_t& getURL() {\n return url;\n }\n\n \/** Create marshaller.\n *\/\n Marshaller_t* createMarshaller(HTTPClient_t &client);\n\n \/** Call method.\n *\/\n Value_t& call(Pool_t &pool, const std::string &methodName,\n const Array_t ¶ms);\n\n void call(DataBuilder_t &builder, const std::string &methodName,\n const Array_t ¶ms);\n\n \/** Call method with variable number of arguments.\n *\/\n Value_t& call(Pool_t &pool, const char *methodName, va_list args);\n\nprivate:\n URL_t url;\n HTTPIO_t io;\n unsigned int rpcTransferMode;\n bool useHTTP10;\n unsigned int serverSupportedProtocols;\n ProtocolVersion_t protocolVersion;\n std::auto_ptr connector;\n};\n\nMarshaller_t* ServerProxyImpl_t::createMarshaller(HTTPClient_t &client) {\n Marshaller_t *marshaller;\n switch (rpcTransferMode) {\n case ServerProxy_t::Config_t::ON_SUPPORT:\n {\n if (serverSupportedProtocols & HTTPClient_t::BINARY_RPC) {\n \/\/using BINARY_RPC\n marshaller= Marshaller_t::create(Marshaller_t::BINARY_RPC,\n client,protocolVersion);\n client.prepare(HTTPClient_t::BINARY_RPC);\n } else {\n \/\/using XML_RPC\n marshaller = Marshaller_t::create\n (Marshaller_t::XML_RPC,client, protocolVersion);\n client.prepare(HTTPClient_t::XML_RPC);\n }\n }\n break;\n\n case ServerProxy_t::Config_t::NEVER:\n {\n \/\/ never using BINARY_RPC\n marshaller= Marshaller_t::create(Marshaller_t::XML_RPC,\n client,protocolVersion);\n client.prepare(HTTPClient_t::XML_RPC);\n }\n break;\n\n case ServerProxy_t::Config_t::ALWAYS:\n {\n \/\/using BINARY_RPC always\n marshaller= Marshaller_t::create(Marshaller_t::BINARY_RPC,\n client,protocolVersion);\n client.prepare(HTTPClient_t::BINARY_RPC);\n }\n break;\n\n case ServerProxy_t::Config_t::ON_SUPPORT_ON_KEEP_ALIVE:\n default:\n {\n if ((serverSupportedProtocols & HTTPClient_t::XML_RPC)\n || connector->getKeepAlive() == false\n || io.socket() != -1) {\n \/\/using XML_RPC\n marshaller= Marshaller_t::create\n (Marshaller_t::XML_RPC,client, protocolVersion);\n client.prepare(HTTPClient_t::XML_RPC);\n } else {\n \/\/using BINARY_RPC\n marshaller= Marshaller_t::create\n (Marshaller_t::BINARY_RPC, client,protocolVersion);\n client.prepare(HTTPClient_t::BINARY_RPC);\n }\n }\n break;\n }\n\n \/\/ OK\n return marshaller;\n}\n\nServerProxy_t::ServerProxy_t(const std::string &server, const Config_t &config)\n : sp(new ServerProxyImpl_t(server, config))\n{}\n\nServerProxy_t::ServerProxy_t(const std::string &server, const Struct_t &config)\n : sp(new ServerProxyImpl_t(server, configFromStruct(config)))\n{}\n\n\nServerProxy_t::~ServerProxy_t() {\n \/\/ get rid of implementation\n}\n\nValue_t& ServerProxyImpl_t::call(Pool_t &pool, const std::string &methodName,\n const Array_t ¶ms)\n{\n HTTPClient_t client(io, url, connector.get(), useHTTP10);\n TreeBuilder_t builder(pool);\n std::auto_ptrmarshaller(createMarshaller(client));\n TreeFeeder_t feeder(*marshaller);\n\n try {\n marshaller->packMethodCall(methodName.c_str());\n for (Array_t::const_iterator\n iparams = params.begin(),\n eparams = params.end();\n iparams != eparams; ++iparams) {\n feeder.feedValue(**iparams);\n }\n\n marshaller->flush();\n } catch (const ResponseError_t &e) {}\n\n client.readResponse(builder);\n serverSupportedProtocols = client.getSupportedProtocols();\n protocolVersion = client.getProtocolVersion();\n if (&(builder.getUnMarshaledData()) == 0)\n throw Fault_t(builder.getUnMarshaledErrorNumber(),\n builder.getUnMarshaledErrorMessage());\n\n \/\/ OK, return unmarshalled data\n return builder.getUnMarshaledData();\n}\n\n\nvoid ServerProxyImpl_t::call(DataBuilder_t &builder, const std::string &methodName,\n const Array_t ¶ms)\n{\n HTTPClient_t client(io, url, connector.get(), useHTTP10);\n std::auto_ptrmarshaller(createMarshaller(client));\n TreeFeeder_t feeder(*marshaller);\n\n try {\n marshaller->packMethodCall(methodName.c_str());\n for (Array_t::const_iterator\n iparams = params.begin(),\n eparams = params.end();\n iparams != eparams; ++iparams) {\n feeder.feedValue(**iparams);\n }\n\n marshaller->flush();\n } catch (const ResponseError_t &e) {}\n\n client.readResponse(builder);\n serverSupportedProtocols = client.getSupportedProtocols();\n protocolVersion = client.getProtocolVersion();\n}\n\n\nValue_t& ServerProxy_t::call(Pool_t &pool, const std::string &methodName,\n const Array_t ¶ms)\n{\n return sp->call(pool, methodName, params);\n}\n\nValue_t& ServerProxyImpl_t::call(Pool_t &pool, const char *methodName,\n va_list args)\n{\n HTTPClient_t client(io, url, connector.get(), useHTTP10);\n TreeBuilder_t builder(pool);\n std::auto_ptrmarshaller(createMarshaller(client));\n TreeFeeder_t feeder(*marshaller);\n\n try {\n marshaller->packMethodCall(methodName);\n\n \/\/ marshall all passed values until null pointer\n while (const Value_t *value = va_arg(args, Value_t*))\n feeder.feedValue(*value);\n\n marshaller->flush();\n } catch (const ResponseError_t &e) {}\n\n client.readResponse(builder);\n serverSupportedProtocols = client.getSupportedProtocols();\n protocolVersion = client.getProtocolVersion();\n if(&(builder.getUnMarshaledData()) == 0)\n throw Fault_t(builder.getUnMarshaledErrorNumber(),\n builder.getUnMarshaledErrorMessage());\n\n \/\/ OK, return unmarshalled data\n return builder.getUnMarshaledData();\n}\n\nnamespace {\n \/** Hold va_list and destroy it (via va_end) on destruction.\n *\/\n struct VaListHolder_t {\n VaListHolder_t(va_list &args) : args(args) {}\n ~VaListHolder_t() { va_end(args); }\n va_list &args;\n };\n}\n\nValue_t& ServerProxy_t::call(Pool_t &pool, const char *methodName, ...) {\n \/\/ get variadic arguments\n va_list args;\n va_start(args, methodName);\n VaListHolder_t argsHolder(args);\n\n \/\/ use implementation\n return sp->call(pool, methodName, args);\n}\n\nvoid ServerProxy_t::call(DataBuilder_t &builder,\n const std::string &methodName, const Array_t ¶ms)\n{\n sp->call(builder, methodName, params);\n}\n\nvoid ServerProxy_t::setReadTimeout(int timeout) {\n sp->setReadTimeout(timeout);\n}\n\nvoid ServerProxy_t::setWriteTimeout(int timeout) {\n sp->setWriteTimeout(timeout);\n}\n\nvoid ServerProxy_t::setConnectTimeout(int timeout) {\n sp->setConnectTimeout(timeout);\n}\n\nconst URL_t& ServerProxy_t::getURL() {\n return sp->getURL();\n}\n\n} \/\/ namespace FRPC\n\n<|endoftext|>"} {"text":"refactored code to select reference camera<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: AGroup.cxx,v $\n *\n * $Revision: 1.19 $\n *\n * last change: $Author: vg $ $Date: 2007-03-26 13:56:48 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_connectivity.hxx\"\n\n#ifndef _CONNECTIVITY_ADO_GROUP_HXX_\n#include \"ado\/AGroup.hxx\"\n#endif\n#ifndef _CONNECTIVITY_ADO_USERS_HXX_\n#include \"ado\/AUsers.hxx\"\n#endif\n#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_SEQUENCE_HXX_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_\n#include \n#endif\n#ifndef _CONNECTIVITY_ADO_BCONNECTION_HXX_\n#include \"ado\/AConnection.hxx\"\n#endif\n#ifndef CONNECTIVITY_CONNECTION_HXX\n#include \"TConnection.hxx\"\n#endif\n\nusing namespace connectivity::ado;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::beans;\nusing namespace com::sun::star::sdbc;\nusing namespace com::sun::star::sdbcx;\n\n\/\/ -------------------------------------------------------------------------\nvoid WpADOGroup::Create()\n{\n HRESULT hr = -1;\n ADOGroup* pGroup = NULL;\n hr = CoCreateInstance(ADOS::CLSID_ADOGROUP_25,\n NULL,\n CLSCTX_INPROC_SERVER,\n ADOS::IID_ADOGROUP_25,\n (void**)&pGroup );\n\n\n if( !FAILED( hr ) )\n {\n operator=( pGroup );\n pGroup->Release();\n }\n}\n\/\/ -------------------------------------------------------------------------\nOAdoGroup::OAdoGroup(OCatalog* _pParent,sal_Bool _bCase, ADOGroup* _pGroup) : OGroup_ADO(_bCase),m_pCatalog(_pParent)\n{\n construct();\n if(_pGroup)\n m_aGroup = WpADOGroup(_pGroup);\n else\n m_aGroup.Create();\n\n}\n\/\/ -------------------------------------------------------------------------\nOAdoGroup::OAdoGroup(OCatalog* _pParent,sal_Bool _bCase, const ::rtl::OUString& _Name) : OGroup_ADO(_Name,_bCase),m_pCatalog(_pParent)\n{\n construct();\n m_aGroup.Create();\n m_aGroup.put_Name(_Name);\n}\n\/\/ -------------------------------------------------------------------------\nvoid OAdoGroup::refreshUsers()\n{\n TStringVector aVector;\n\n WpADOUsers aUsers = m_aGroup.get_Users();\n aUsers.fillElementNames(aVector);\n\n if(m_pUsers)\n m_pUsers->reFill(aVector);\n else\n m_pUsers = new OUsers(m_pCatalog,m_aMutex,aVector,aUsers,isCaseSensitive());\n}\n\/\/--------------------------------------------------------------------------\nSequence< sal_Int8 > OAdoGroup::getUnoTunnelImplementationId()\n{\n static ::cppu::OImplementationId * pId = 0;\n if (! pId)\n {\n ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );\n if (! pId)\n {\n static ::cppu::OImplementationId aId;\n pId = &aId;\n }\n }\n return pId->getImplementationId();\n}\n\n\/\/ com::sun::star::lang::XUnoTunnel\n\/\/------------------------------------------------------------------\nsal_Int64 OAdoGroup::getSomething( const Sequence< sal_Int8 > & rId ) throw (RuntimeException)\n{\n return (rId.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(), rId.getConstArray(), 16 ) )\n ? reinterpret_cast< sal_Int64 >( this )\n : OGroup_ADO::getSomething(rId);\n}\n\n\/\/ -------------------------------------------------------------------------\nvoid OAdoGroup::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue)throw (Exception)\n{\n if(m_aGroup.IsValid())\n {\n\n switch(nHandle)\n {\n case PROPERTY_ID_NAME:\n {\n ::rtl::OUString aVal;\n rValue >>= aVal;\n m_aGroup.put_Name(aVal);\n }\n break;\n }\n }\n}\n\/\/ -------------------------------------------------------------------------\nvoid OAdoGroup::getFastPropertyValue(Any& rValue,sal_Int32 nHandle) const\n{\n if(m_aGroup.IsValid())\n {\n switch(nHandle)\n {\n case PROPERTY_ID_NAME:\n rValue <<= m_aGroup.get_Name();\n break;\n }\n }\n}\n\/\/ -------------------------------------------------------------------------\n\nsal_Int32 SAL_CALL OAdoGroup::getPrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)\n{\n return MapRight(m_aGroup.GetPermissions(objName,MapObjectType(objType)));\n}\n\/\/ -------------------------------------------------------------------------\nsal_Int32 SAL_CALL OAdoGroup::getGrantablePrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)\n{\n RightsEnum eNum = m_aGroup.GetPermissions(objName,MapObjectType(objType));\n if(eNum & adRightWithGrant)\n return MapRight(eNum);\n return 0;\n}\n\/\/ -------------------------------------------------------------------------\nvoid SAL_CALL OAdoGroup::grantPrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)\n{\n m_aGroup.SetPermissions(objName,MapObjectType(objType),adAccessGrant,Map2Right(objPrivileges));\n}\n\/\/ -------------------------------------------------------------------------\nvoid SAL_CALL OAdoGroup::revokePrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)\n{\n m_aGroup.SetPermissions(objName,MapObjectType(objType),adAccessDeny,Map2Right(objPrivileges));\n}\n\n\/\/ -----------------------------------------------------------------------------\nvoid SAL_CALL OAdoGroup::acquire() throw()\n{\n OGroup_ADO::acquire();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid SAL_CALL OAdoGroup::release() throw()\n{\n OGroup_ADO::release();\n}\n\/\/ -----------------------------------------------------------------------------\n\n\nINTEGRATION: CWS changefileheader (1.19.144); FILE MERGED 2008\/04\/01 15:08:35 thb 1.19.144.3: #i85898# Stripping all external header guards 2008\/04\/01 10:52:49 thb 1.19.144.2: #i85898# Stripping all external header guards 2008\/03\/28 15:23:26 rt 1.19.144.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: AGroup.cxx,v $\n * $Revision: 1.20 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_connectivity.hxx\"\n\n#ifndef _CONNECTIVITY_ADO_GROUP_HXX_\n#include \"ado\/AGroup.hxx\"\n#endif\n#include \"ado\/AUsers.hxx\"\n#include \n#include \n#include \n#include \n#ifndef _CONNECTIVITY_ADO_BCONNECTION_HXX_\n#include \"ado\/AConnection.hxx\"\n#endif\n#include \"TConnection.hxx\"\n\nusing namespace connectivity::ado;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::beans;\nusing namespace com::sun::star::sdbc;\nusing namespace com::sun::star::sdbcx;\n\n\/\/ -------------------------------------------------------------------------\nvoid WpADOGroup::Create()\n{\n HRESULT hr = -1;\n ADOGroup* pGroup = NULL;\n hr = CoCreateInstance(ADOS::CLSID_ADOGROUP_25,\n NULL,\n CLSCTX_INPROC_SERVER,\n ADOS::IID_ADOGROUP_25,\n (void**)&pGroup );\n\n\n if( !FAILED( hr ) )\n {\n operator=( pGroup );\n pGroup->Release();\n }\n}\n\/\/ -------------------------------------------------------------------------\nOAdoGroup::OAdoGroup(OCatalog* _pParent,sal_Bool _bCase, ADOGroup* _pGroup) : OGroup_ADO(_bCase),m_pCatalog(_pParent)\n{\n construct();\n if(_pGroup)\n m_aGroup = WpADOGroup(_pGroup);\n else\n m_aGroup.Create();\n\n}\n\/\/ -------------------------------------------------------------------------\nOAdoGroup::OAdoGroup(OCatalog* _pParent,sal_Bool _bCase, const ::rtl::OUString& _Name) : OGroup_ADO(_Name,_bCase),m_pCatalog(_pParent)\n{\n construct();\n m_aGroup.Create();\n m_aGroup.put_Name(_Name);\n}\n\/\/ -------------------------------------------------------------------------\nvoid OAdoGroup::refreshUsers()\n{\n TStringVector aVector;\n\n WpADOUsers aUsers = m_aGroup.get_Users();\n aUsers.fillElementNames(aVector);\n\n if(m_pUsers)\n m_pUsers->reFill(aVector);\n else\n m_pUsers = new OUsers(m_pCatalog,m_aMutex,aVector,aUsers,isCaseSensitive());\n}\n\/\/--------------------------------------------------------------------------\nSequence< sal_Int8 > OAdoGroup::getUnoTunnelImplementationId()\n{\n static ::cppu::OImplementationId * pId = 0;\n if (! pId)\n {\n ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );\n if (! pId)\n {\n static ::cppu::OImplementationId aId;\n pId = &aId;\n }\n }\n return pId->getImplementationId();\n}\n\n\/\/ com::sun::star::lang::XUnoTunnel\n\/\/------------------------------------------------------------------\nsal_Int64 OAdoGroup::getSomething( const Sequence< sal_Int8 > & rId ) throw (RuntimeException)\n{\n return (rId.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(), rId.getConstArray(), 16 ) )\n ? reinterpret_cast< sal_Int64 >( this )\n : OGroup_ADO::getSomething(rId);\n}\n\n\/\/ -------------------------------------------------------------------------\nvoid OAdoGroup::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue)throw (Exception)\n{\n if(m_aGroup.IsValid())\n {\n\n switch(nHandle)\n {\n case PROPERTY_ID_NAME:\n {\n ::rtl::OUString aVal;\n rValue >>= aVal;\n m_aGroup.put_Name(aVal);\n }\n break;\n }\n }\n}\n\/\/ -------------------------------------------------------------------------\nvoid OAdoGroup::getFastPropertyValue(Any& rValue,sal_Int32 nHandle) const\n{\n if(m_aGroup.IsValid())\n {\n switch(nHandle)\n {\n case PROPERTY_ID_NAME:\n rValue <<= m_aGroup.get_Name();\n break;\n }\n }\n}\n\/\/ -------------------------------------------------------------------------\n\nsal_Int32 SAL_CALL OAdoGroup::getPrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)\n{\n return MapRight(m_aGroup.GetPermissions(objName,MapObjectType(objType)));\n}\n\/\/ -------------------------------------------------------------------------\nsal_Int32 SAL_CALL OAdoGroup::getGrantablePrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)\n{\n RightsEnum eNum = m_aGroup.GetPermissions(objName,MapObjectType(objType));\n if(eNum & adRightWithGrant)\n return MapRight(eNum);\n return 0;\n}\n\/\/ -------------------------------------------------------------------------\nvoid SAL_CALL OAdoGroup::grantPrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)\n{\n m_aGroup.SetPermissions(objName,MapObjectType(objType),adAccessGrant,Map2Right(objPrivileges));\n}\n\/\/ -------------------------------------------------------------------------\nvoid SAL_CALL OAdoGroup::revokePrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)\n{\n m_aGroup.SetPermissions(objName,MapObjectType(objType),adAccessDeny,Map2Right(objPrivileges));\n}\n\n\/\/ -----------------------------------------------------------------------------\nvoid SAL_CALL OAdoGroup::acquire() throw()\n{\n OGroup_ADO::acquire();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid SAL_CALL OAdoGroup::release() throw()\n{\n OGroup_ADO::release();\n}\n\/\/ -----------------------------------------------------------------------------\n\n\n<|endoftext|>"} {"text":"INTEGRATION: CWS impress2 (1.1.2); FILE ADDED 2004\/02\/13 12:14:08 af 1.1.2.1: #i22705# Initial revision.<|endoftext|>"} {"text":"integration-quickbrown-casemapping: Added tests for Hungarian strings.<|endoftext|>"} {"text":"Prediction: use simple-version of move_sequence_predictor<|endoftext|>"} {"text":"\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef __STOUT_WINDOWS_OS_HPP__\n#define __STOUT_WINDOWS_OS_HPP__\n\n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace os {\n\n\n\/*\n\/\/ Sets the value associated with the specified key in the set of\n\/\/ environment variables.\ninline void setenv(const std::string& key,\n const std::string& value,\n bool overwrite = true)\n{\n UNIMPLEMENTED;\n}\n\n\n\/\/ Unsets the value associated with the specified key in the set of\n\/\/ environment variables.\ninline void unsetenv(const std::string& key)\n{\n UNIMPLEMENTED;\n}\n\n\n\/\/ Executes a command by calling \"\/bin\/sh -c \", and returns\n\/\/ after the command has been completed. Returns 0 if succeeds, and\n\/\/ return -1 on error (e.g., fork\/exec\/waitpid failed). This function\n\/\/ is async signal safe. We return int instead of returning a Try\n\/\/ because Try involves 'new', which is not async signal safe.\ninline int system(const std::string& command)\n{\n UNIMPLEMENTED;\n}\n\n\n\/\/ This function is a portable version of execvpe ('p' means searching\n\/\/ executable from PATH and 'e' means setting environments). We add\n\/\/ this function because it is not available on all systems.\n\/\/\n\/\/ NOTE: This function is not thread safe. It is supposed to be used\n\/\/ only after fork (when there is only one thread). This function is\n\/\/ async signal safe.\ninline int execvpe(const char* file, char** argv, char** envp)\n{\n UNIMPLEMENTED;\n}\n\n\ninline Try chown(\n uid_t uid,\n gid_t gid,\n const std::string& path,\n bool recursive)\n{\n UNIMPLEMENTED;\n}\n\n\ninline Try chmod(const std::string& path, int mode)\n{\n UNIMPLEMENTED;\n}\n\n\ninline Try chroot(const std::string& directory)\n{\n UNIMPLEMENTED;\n}\n\n\ninline Try mknod(\n const std::string& path,\n mode_t mode,\n dev_t dev)\n{\n UNIMPLEMENTED;\n}\n\n\ninline Result getuid(const Option& user = None())\n{\n UNIMPLEMENTED;\n}\n\n\ninline Result getgid(const Option& user = None())\n{\n UNIMPLEMENTED;\n}\n\n\ninline Try su(const std::string& user)\n{\n UNIMPLEMENTED;\n}\n\n\ninline Result user(Option uid = None())\n{\n UNIMPLEMENTED;\n}\n\n\n\/\/ Suspends execution for the given duration.\ninline Try sleep(const Duration& duration)\n{\n UNIMPLEMENTED;\n}\n\n\n\/\/ Returns the list of files that match the given (shell) pattern.\ninline Try> glob(const std::string& pattern)\n{\n UNIMPLEMENTED;\n}\n\n\n\/\/ Returns the total number of cpus (cores).\ninline Try cpus()\n{\n UNIMPLEMENTED;\n}\n\n\n\/\/ Returns load struct with average system loads for the last\n\/\/ 1, 5 and 15 minutes respectively.\n\/\/ Load values should be interpreted as usual average loads from\n\/\/ uptime(1).\ninline Try loadavg()\n{\n UNIMPLEMENTED;\n}\n\n\n\/\/ Returns the total size of main and free memory.\ninline Try memory()\n{\n UNIMPLEMENTED;\n}\n\n\n\/\/ Return the system information.\ninline Try uname()\n{\n UNIMPLEMENTED;\n}\n\n\ninline Try> processes()\n{\n UNIMPLEMENTED;\n}\n\n\n\/\/ Overload of os::pids for filtering by groups and sessions.\n\/\/ A group \/ session id of 0 will fitler on the group \/ session ID\n\/\/ of the calling process.\ninline Try> pids(Option group, Option session)\n{\n UNIMPLEMENTED;\n}\n*\/\n} \/\/ namespace os {\n\n#endif \/\/ __STOUT_WINDOWS_OS_HPP__\nWindows: Added `stout\/os\/read.hpp` include to `windows\/os.hpp`.\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef __STOUT_WINDOWS_OS_HPP__\n#define __STOUT_WINDOWS_OS_HPP__\n\n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\nnamespace os {\n\n\n\/*\n\/\/ Sets the value associated with the specified key in the set of\n\/\/ environment variables.\ninline void setenv(const std::string& key,\n const std::string& value,\n bool overwrite = true)\n{\n UNIMPLEMENTED;\n}\n\n\n\/\/ Unsets the value associated with the specified key in the set of\n\/\/ environment variables.\ninline void unsetenv(const std::string& key)\n{\n UNIMPLEMENTED;\n}\n\n\n\/\/ Executes a command by calling \"\/bin\/sh -c \", and returns\n\/\/ after the command has been completed. Returns 0 if succeeds, and\n\/\/ return -1 on error (e.g., fork\/exec\/waitpid failed). This function\n\/\/ is async signal safe. We return int instead of returning a Try\n\/\/ because Try involves 'new', which is not async signal safe.\ninline int system(const std::string& command)\n{\n UNIMPLEMENTED;\n}\n\n\n\/\/ This function is a portable version of execvpe ('p' means searching\n\/\/ executable from PATH and 'e' means setting environments). We add\n\/\/ this function because it is not available on all systems.\n\/\/\n\/\/ NOTE: This function is not thread safe. It is supposed to be used\n\/\/ only after fork (when there is only one thread). This function is\n\/\/ async signal safe.\ninline int execvpe(const char* file, char** argv, char** envp)\n{\n UNIMPLEMENTED;\n}\n\n\ninline Try chown(\n uid_t uid,\n gid_t gid,\n const std::string& path,\n bool recursive)\n{\n UNIMPLEMENTED;\n}\n\n\ninline Try chmod(const std::string& path, int mode)\n{\n UNIMPLEMENTED;\n}\n\n\ninline Try chroot(const std::string& directory)\n{\n UNIMPLEMENTED;\n}\n\n\ninline Try mknod(\n const std::string& path,\n mode_t mode,\n dev_t dev)\n{\n UNIMPLEMENTED;\n}\n\n\ninline Result getuid(const Option& user = None())\n{\n UNIMPLEMENTED;\n}\n\n\ninline Result getgid(const Option& user = None())\n{\n UNIMPLEMENTED;\n}\n\n\ninline Try su(const std::string& user)\n{\n UNIMPLEMENTED;\n}\n\n\ninline Result user(Option uid = None())\n{\n UNIMPLEMENTED;\n}\n\n\n\/\/ Suspends execution for the given duration.\ninline Try sleep(const Duration& duration)\n{\n UNIMPLEMENTED;\n}\n\n\n\/\/ Returns the list of files that match the given (shell) pattern.\ninline Try> glob(const std::string& pattern)\n{\n UNIMPLEMENTED;\n}\n\n\n\/\/ Returns the total number of cpus (cores).\ninline Try cpus()\n{\n UNIMPLEMENTED;\n}\n\n\n\/\/ Returns load struct with average system loads for the last\n\/\/ 1, 5 and 15 minutes respectively.\n\/\/ Load values should be interpreted as usual average loads from\n\/\/ uptime(1).\ninline Try loadavg()\n{\n UNIMPLEMENTED;\n}\n\n\n\/\/ Returns the total size of main and free memory.\ninline Try memory()\n{\n UNIMPLEMENTED;\n}\n\n\n\/\/ Return the system information.\ninline Try uname()\n{\n UNIMPLEMENTED;\n}\n\n\ninline Try> processes()\n{\n UNIMPLEMENTED;\n}\n\n\n\/\/ Overload of os::pids for filtering by groups and sessions.\n\/\/ A group \/ session id of 0 will fitler on the group \/ session ID\n\/\/ of the calling process.\ninline Try> pids(Option group, Option session)\n{\n UNIMPLEMENTED;\n}\n*\/\n} \/\/ namespace os {\n\n#endif \/\/ __STOUT_WINDOWS_OS_HPP__\n<|endoftext|>"} {"text":"\/** \\file map_ddc_and_rvk_to_ixtheo_notations.cc\n * \\brief Map certain DDC and RVK categories to ixTheo notations and add them to field 652a.\n * \\author Dr. Johannes Ruscheinski\n *\/\n\n\/*\n Copyright (C) 2015, Library of the University of Tübingen\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see .\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"MarcUtil.h\"\n#include \"StringUtil.h\"\n#include \"Subfields.h\"\n#include \"util.h\"\n\n\nvoid Usage() {\n std::cerr << \"Usage: \" << progname << \" [--verbose] marc_input marc_output ddc_to_ixtheo_notations_map \"\n\t << \"rvk_to_ixtheo_notations_map\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\n\/** \\class IxTheoMapper\n * \\brief Maps from a DDC or RVK hierarchy entry to an IxTheo notation.\n *\/\nclass IxTheoMapper {\n std::string from_hierarchy_;\n std::string to_ix_theo_notation_;\n std::vector exclusions_;\npublic:\n explicit IxTheoMapper(const std::vector &map_file_line);\n\n \/** \\brief Returns an IxTheo notation if we can match \"hierarchy_classification\". O\/w we return the empty string. *\/\n std::string map(const std::string &hierarchy_classification) const;\n};\n\n\nIxTheoMapper::IxTheoMapper(const std::vector &map_file_line) {\n if (map_file_line.size() < 2)\n\tthrow std::runtime_error(\"in IxTheoMapper::IxTheoMapper: need at least 2 elements in \\\"map_file_line\\\"!\");\n from_hierarchy_ = map_file_line[0];\n to_ix_theo_notation_ = map_file_line[1];\n std::copy(map_file_line.begin() + 2, map_file_line.end(), std::back_inserter(exclusions_));\n}\n\n\nstd::string IxTheoMapper::map(const std::string &hierarchy_classification) const {\n if (not StringUtil::StartsWith(hierarchy_classification, from_hierarchy_))\n\treturn \"\";\n\n for (const auto &exclusion : exclusions_) {\n\tif (StringUtil::StartsWith(hierarchy_classification, exclusion))\n\t return \"\";\n }\n\n return to_ix_theo_notation_;\n}\n\n\nvoid LoadCSVFile(const bool verbose, const std::string &filename, std::vector * const mappers) {\n DSVReader csv_reader(filename);\n std::vector csv_values;\n while (csv_reader.readLine(&csv_values))\n\tmappers->emplace_back(csv_values);\n\n if (verbose)\n\tstd::cerr << \"Read \" << mappers->size() << \" mappings from \\\"\" << filename << \"\\\".\\n\";\n}\n\n\nvoid UpdateIxTheoNotations(const std::vector &mappers, const std::vector &orig_values,\n\t\t\t std::string * const ixtheo_notations_list)\n{\n std::vector ixtheo_notations_vector;\n StringUtil::Split(*ixtheo_notations_list, ':', &ixtheo_notations_vector);\n std::set previously_assigned_notations(std::make_move_iterator(ixtheo_notations_vector.begin()),\n\t\t\t\t\t\t\tstd::make_move_iterator(ixtheo_notations_vector.end()));\n\n for (const auto &mapper : mappers) {\n\tfor (const auto &orig_value : orig_values) {\n\t const std::string mapped_value(mapper.map(orig_value));\n\t if (not mapped_value.empty()\n\t\tand previously_assigned_notations.find(mapped_value) == previously_assigned_notations.end())\n\t {\n\t\tif (not ixtheo_notations_list->empty())\n\t\t *ixtheo_notations_list += ':';\n\t\t*ixtheo_notations_list += mapped_value;\n\t\tpreviously_assigned_notations.insert(mapped_value);\n\t }\n\t}\n }\n}\n\n\nvoid ProcessRecords(const bool verbose, const std::shared_ptr &input, const std::shared_ptr &output,\n\t\t const std::vector &ddc_to_ixtheo_notation_mappers,\n\t\t const std::vector &\/*rvk_to_ixtheo_notation_mappers*\/)\n{\n unsigned count(0), records_with_ixtheo_notations(0), records_with_new_notations(0), skipped_group_count(0);\n while (MarcUtil::Record record = MarcUtil::Record(input.get())) {\n ++count;\n\n\tconst std::vector &dir_entries(record.getDirEntries());\n if (dir_entries[0].getTag() != \"001\")\n Error(\"First field is not \\\"001\\\"!\");\n\n\tstd::string ixtheo_notations_list(record.extractFirstSubfield(\"652\", 'a'));\n\tif (not ixtheo_notations_list.empty()) {\n\t ++records_with_ixtheo_notations;\n\t record.write(output.get());\n\t continue;\n\t}\n\n\tstd::vector ddc_values;\n\tif (record.extractSubfield(\"082\", 'a', &ddc_values) == 0) {\n\t record.write(output.get());\n\t continue;\n\t}\n\n\tif (std::find(ddc_values.cbegin(), ddc_values.cend(), \"K\") != ddc_values.cend()\n\t or std::find(ddc_values.cbegin(), ddc_values.cend(), \"B\") != ddc_values.cend())\n\t{\n\t ++skipped_group_count;\n\t continue;\n\t}\n\n\t\/\/ Many DDCs have superfluous backslashes which are non-standard and need to be removed before further\n\t\/\/ processing can take place:\n\tfor (auto &ddc_value : ddc_values)\n\t StringUtil::RemoveChars(\"\/\", &ddc_value);\n\n\tUpdateIxTheoNotations(ddc_to_ixtheo_notation_mappers, ddc_values, &ixtheo_notations_list);\n\tif (verbose and not ixtheo_notations_list.empty()) {\n\t const std::vector &fields(record.getFields());\n\t std::cout << fields[0] << \": \" << StringUtil::Join(ddc_values, ',') << \" -> \" << ixtheo_notations_list << '\\n';\n }\n\n\/*\n\tstd::vector rvk_values;\n\tint _084_index(record.getFieldIndex(\"084\"));\n\tif (_084_index != -1) {\n\t const std::vector &fields(record.getFields());\n\t while (_084_index < static_cast(dir_entries.size()) and dir_entries[_084_index].getTag() == \"084\") {\n\t\tconst Subfields subfields(fields[_084_index]);\n\t\tif (subfields.hasSubfieldWithValue('2', \"rvk\"))\n\t\t rvk_values.emplace_back(subfields.getFirstSubfieldValue('a'));\n\t\t++_084_index;\n\t }\n\t}\n\tUpdateIxTheoNotations(rvk_to_ixtheo_notation_mappers, rvk_values, &ixtheo_notations_list);\n*\/\n\n\tif (not ixtheo_notations_list.empty()) {\n\t ++records_with_new_notations;\n\t record.insertField(\"652\", \" \"\"\\x1F\"\"a\" + ixtheo_notations_list);\n\t}\n\n\trecord.write(output.get());\n }\n\n if (verbose) {\n\tstd::cerr << \"Read \" << count << \" records.\\n\";\n\tstd::cerr << records_with_ixtheo_notations << \" records had Ixtheo notations.\\n\";\n\tstd::cerr << records_with_new_notations << \" records received new Ixtheo notations.\\n\";\n\tstd::cerr << skipped_group_count << \" records where skipped because they were in a group that we are not interested in.\\n\";\n }\n}\n\n\nint main(int argc, char **argv) {\n progname = argv[0];\n\n if (argc != 5 and argc != 6)\n Usage();\n\n bool verbose(false);\n if (argc == 6) {\n\tif (std::strcmp(argv[1], \"--verbose\") != 0)\n\t Usage();\n\tverbose = true;\n }\n\n const std::string marc_input_filename(argv[verbose ? 2 : 1]);\n std::shared_ptr marc_input(std::fopen(marc_input_filename.c_str(), \"rbm\"), std::fclose);\n if (marc_input == nullptr)\n Error(\"can't open \\\"\" + marc_input_filename + \"\\\" for reading!\");\n\n const std::string marc_output_filename(argv[verbose ? 3 : 2]);\n std::shared_ptr marc_output(std::fopen(marc_output_filename.c_str(), \"wb\"), std::fclose);\n if (marc_output == nullptr)\n Error(\"can't open \\\"\" + marc_output_filename + \"\\\" for writing!\");\n\n try {\n\tstd::vector ddc_to_ixtheo_notation_mappers;\n\tLoadCSVFile(verbose, argv[verbose ? 4 : 3], &ddc_to_ixtheo_notation_mappers);\n\n\tstd::vector rvk_to_ixtheo_notation_mappers;\n\/\/\tLoadCSVFile(verbose, argv[verbose ? 5 : 4], &rvk_to_ixtheo_notation_mappers);\n\n\tProcessRecords(verbose, marc_input, marc_output, ddc_to_ixtheo_notation_mappers, rvk_to_ixtheo_notation_mappers);\n } catch (const std::exception &x) {\n\tError(\"caught exception: \" + std::string(x.what()));\n }\n}\nAdded a comment.\/** \\file map_ddc_and_rvk_to_ixtheo_notations.cc\n * \\brief Map certain DDC and RVK categories to ixTheo notations and add them to field 652a.\n * \\author Dr. Johannes Ruscheinski\n *\/\n\n\/*\n Copyright (C) 2015, Library of the University of Tübingen\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see .\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"MarcUtil.h\"\n#include \"StringUtil.h\"\n#include \"Subfields.h\"\n#include \"util.h\"\n\n\nvoid Usage() {\n std::cerr << \"Usage: \" << progname << \" [--verbose] marc_input marc_output ddc_to_ixtheo_notations_map \"\n\t << \"rvk_to_ixtheo_notations_map\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\n\/** \\class IxTheoMapper\n * \\brief Maps from a DDC or RVK hierarchy entry to an IxTheo notation.\n *\/\nclass IxTheoMapper {\n std::string from_hierarchy_;\n std::string to_ix_theo_notation_;\n std::vector exclusions_;\npublic:\n explicit IxTheoMapper(const std::vector &map_file_line);\n\n \/** \\brief Returns an IxTheo notation if we can match \"hierarchy_classification\". O\/w we return the empty string. *\/\n std::string map(const std::string &hierarchy_classification) const;\n};\n\n\nIxTheoMapper::IxTheoMapper(const std::vector &map_file_line) {\n if (map_file_line.size() < 2)\n\tthrow std::runtime_error(\"in IxTheoMapper::IxTheoMapper: need at least 2 elements in \\\"map_file_line\\\"!\");\n from_hierarchy_ = map_file_line[0];\n to_ix_theo_notation_ = map_file_line[1];\n std::copy(map_file_line.begin() + 2, map_file_line.end(), std::back_inserter(exclusions_));\n}\n\n\nstd::string IxTheoMapper::map(const std::string &hierarchy_classification) const {\n if (not StringUtil::StartsWith(hierarchy_classification, from_hierarchy_))\n\treturn \"\";\n\n for (const auto &exclusion : exclusions_) {\n\tif (StringUtil::StartsWith(hierarchy_classification, exclusion))\n\t return \"\";\n }\n\n return to_ix_theo_notation_;\n}\n\n\nvoid LoadCSVFile(const bool verbose, const std::string &filename, std::vector * const mappers) {\n DSVReader csv_reader(filename);\n std::vector csv_values;\n while (csv_reader.readLine(&csv_values))\n\tmappers->emplace_back(csv_values);\n\n if (verbose)\n\tstd::cerr << \"Read \" << mappers->size() << \" mappings from \\\"\" << filename << \"\\\".\\n\";\n}\n\n\nvoid UpdateIxTheoNotations(const std::vector &mappers, const std::vector &orig_values,\n\t\t\t std::string * const ixtheo_notations_list)\n{\n std::vector ixtheo_notations_vector;\n StringUtil::Split(*ixtheo_notations_list, ':', &ixtheo_notations_vector);\n std::set previously_assigned_notations(std::make_move_iterator(ixtheo_notations_vector.begin()),\n\t\t\t\t\t\t\tstd::make_move_iterator(ixtheo_notations_vector.end()));\n\n for (const auto &mapper : mappers) {\n\tfor (const auto &orig_value : orig_values) {\n\t const std::string mapped_value(mapper.map(orig_value));\n\t if (not mapped_value.empty()\n\t\tand previously_assigned_notations.find(mapped_value) == previously_assigned_notations.end())\n\t {\n\t\tif (not ixtheo_notations_list->empty())\n\t\t *ixtheo_notations_list += ':';\n\t\t*ixtheo_notations_list += mapped_value;\n\t\tpreviously_assigned_notations.insert(mapped_value);\n\t }\n\t}\n }\n}\n\n\nvoid ProcessRecords(const bool verbose, const std::shared_ptr &input, const std::shared_ptr &output,\n\t\t const std::vector &ddc_to_ixtheo_notation_mappers,\n\t\t const std::vector &\/*rvk_to_ixtheo_notation_mappers*\/)\n{\n unsigned count(0), records_with_ixtheo_notations(0), records_with_new_notations(0), skipped_group_count(0);\n while (MarcUtil::Record record = MarcUtil::Record(input.get())) {\n ++count;\n\n\tconst std::vector &dir_entries(record.getDirEntries());\n if (dir_entries[0].getTag() != \"001\")\n Error(\"First field is not \\\"001\\\"!\");\n\n\tstd::string ixtheo_notations_list(record.extractFirstSubfield(\"652\", 'a'));\n\tif (not ixtheo_notations_list.empty()) {\n\t ++records_with_ixtheo_notations;\n\t record.write(output.get());\n\t continue;\n\t}\n\n\tstd::vector ddc_values;\n\tif (record.extractSubfield(\"082\", 'a', &ddc_values) == 0) {\n\t record.write(output.get());\n\t continue;\n\t}\n\n\t\/\/ \"K\" stands for children's literature and \"B\" stands for fiction, both of which we don't want to\n\t\/\/ import into IxTheo;\n\tif (std::find(ddc_values.cbegin(), ddc_values.cend(), \"K\") != ddc_values.cend()\n\t or std::find(ddc_values.cbegin(), ddc_values.cend(), \"B\") != ddc_values.cend())\n\t{\n\t ++skipped_group_count;\n\t continue;\n\t}\n\n\t\/\/ Many DDCs have superfluous backslashes which are non-standard and need to be removed before further\n\t\/\/ processing can take place:\n\tfor (auto &ddc_value : ddc_values)\n\t StringUtil::RemoveChars(\"\/\", &ddc_value);\n\n\tUpdateIxTheoNotations(ddc_to_ixtheo_notation_mappers, ddc_values, &ixtheo_notations_list);\n\tif (verbose and not ixtheo_notations_list.empty()) {\n\t const std::vector &fields(record.getFields());\n\t std::cout << fields[0] << \": \" << StringUtil::Join(ddc_values, ',') << \" -> \" << ixtheo_notations_list << '\\n';\n }\n\n\/*\n\tstd::vector rvk_values;\n\tint _084_index(record.getFieldIndex(\"084\"));\n\tif (_084_index != -1) {\n\t const std::vector &fields(record.getFields());\n\t while (_084_index < static_cast(dir_entries.size()) and dir_entries[_084_index].getTag() == \"084\") {\n\t\tconst Subfields subfields(fields[_084_index]);\n\t\tif (subfields.hasSubfieldWithValue('2', \"rvk\"))\n\t\t rvk_values.emplace_back(subfields.getFirstSubfieldValue('a'));\n\t\t++_084_index;\n\t }\n\t}\n\tUpdateIxTheoNotations(rvk_to_ixtheo_notation_mappers, rvk_values, &ixtheo_notations_list);\n*\/\n\n\tif (not ixtheo_notations_list.empty()) {\n\t ++records_with_new_notations;\n\t record.insertField(\"652\", \" \"\"\\x1F\"\"a\" + ixtheo_notations_list);\n\t}\n\n\trecord.write(output.get());\n }\n\n if (verbose) {\n\tstd::cerr << \"Read \" << count << \" records.\\n\";\n\tstd::cerr << records_with_ixtheo_notations << \" records had Ixtheo notations.\\n\";\n\tstd::cerr << records_with_new_notations << \" records received new Ixtheo notations.\\n\";\n\tstd::cerr << skipped_group_count << \" records where skipped because they were in a group that we are not interested in.\\n\";\n }\n}\n\n\nint main(int argc, char **argv) {\n progname = argv[0];\n\n if (argc != 5 and argc != 6)\n Usage();\n\n bool verbose(false);\n if (argc == 6) {\n\tif (std::strcmp(argv[1], \"--verbose\") != 0)\n\t Usage();\n\tverbose = true;\n }\n\n const std::string marc_input_filename(argv[verbose ? 2 : 1]);\n std::shared_ptr marc_input(std::fopen(marc_input_filename.c_str(), \"rbm\"), std::fclose);\n if (marc_input == nullptr)\n Error(\"can't open \\\"\" + marc_input_filename + \"\\\" for reading!\");\n\n const std::string marc_output_filename(argv[verbose ? 3 : 2]);\n std::shared_ptr marc_output(std::fopen(marc_output_filename.c_str(), \"wb\"), std::fclose);\n if (marc_output == nullptr)\n Error(\"can't open \\\"\" + marc_output_filename + \"\\\" for writing!\");\n\n try {\n\tstd::vector ddc_to_ixtheo_notation_mappers;\n\tLoadCSVFile(verbose, argv[verbose ? 4 : 3], &ddc_to_ixtheo_notation_mappers);\n\n\tstd::vector rvk_to_ixtheo_notation_mappers;\n\/\/\tLoadCSVFile(verbose, argv[verbose ? 5 : 4], &rvk_to_ixtheo_notation_mappers);\n\n\tProcessRecords(verbose, marc_input, marc_output, ddc_to_ixtheo_notation_mappers, rvk_to_ixtheo_notation_mappers);\n } catch (const std::exception &x) {\n\tError(\"caught exception: \" + std::string(x.what()));\n }\n}\n<|endoftext|>"} {"text":"\/\/ This class\n#include \n\/\/#include \/\/ Included for the sake of particle data. Kinda silly, really\n#include \n\n\/\/ 3rd parties\n\nusing namespace DirectX;\nusing namespace physx;\nnamespace DoremiEngine\n{\n namespace Physics\n {\n ParticleEmitter::ParticleEmitter(ParticleEmitterData p_data, InternalPhysicsUtils& p_utils)\n : m_this(p_data), m_utils(p_utils), m_timeSinceLast(0)\n {\n m_nextIndex = 0;\n m_particleSystem = m_utils.m_physics->createParticleSystem(PARTICLE_MAX_COUNT);\n m_particleSystem->setMaxMotionDistance(PARTICLE_MAX_MOTION_DISTANCE);\n m_particleSystem->setParticleReadDataFlag(PxParticleReadDataFlag::eVELOCITY_BUFFER, true);\n m_utils.m_worldScene->addActor(*m_particleSystem);\n \/\/ Might be necessary to set flag to collide with dynamics\n \/\/ m_particleSystem->setParticleBaseFlag(PxParticleBaseFlag::eCOLLISION_WITH_DYNAMIC_ACTORS, true);\n m_particleSystem->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, true); \/\/ Should not be here\n }\n ParticleEmitter::~ParticleEmitter() {}\n\n void ParticleEmitter::SetPosition(XMFLOAT3 p_position) { m_this.m_position = p_position; }\n void ParticleEmitter::SetDirection(XMFLOAT4 p_direction) { m_this.m_direction = p_direction; }\n void ParticleEmitter::SetGravity(bool p_gravity) { m_particleSystem->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, p_gravity); }\n\n void ParticleEmitter::GetPositions(vector& o_positions)\n {\n \/\/ This is a bit harder than it really ought to be...\n PxParticleReadData* readData = m_particleSystem->lockParticleReadData();\n PxStrideIterator positions = readData->positionBuffer;\n PxStrideIterator velocities = readData->velocityBuffer;\n PxStrideIterator flags = readData->flagsBuffer;\n vector velocitiesVector;\n\n vector indicesOfParticlesToBeReleased;\n\n uint32_t numParticles = readData->validParticleRange;\n for(uint32_t i = 0; i < numParticles; i++)\n {\n \/\/ Check if particles are supposed to be removed\n XMFLOAT3 position = XMFLOAT3(positions[i].x, positions[i].y, positions[i].z);\n XMFLOAT3 velocity = XMFLOAT3(velocities[i].x, velocities[i].y, velocities[i].z);\n XMVECTOR velVec = XMLoadFloat3(&velocity);\n velVec = XMVector3Normalize(velVec);\n XMStoreFloat3(&velocity, velVec); \/\/ TODOJB Remove normalization once it's fixed in CastRay\n if(flags[i] & (PxParticleFlag::eCOLLISION_WITH_DRAIN)) \/\/ | PxParticleFlag::eVALID))\n {\n \/\/\/ Particle should be removed\n \/\/ Add index to release list\n indicesOfParticlesToBeReleased.push_back(i);\n \/\/ Find out which actor it collided with using ray tracing (seriously. It was this easy...)\n m_drainsHit.push_back(m_utils.m_rayCastManager->CastRay(position, velocity, 5)); \/\/ Zero might turn up buggy\n }\n else if(flags[i] & PxParticleFlag::eVALID)\n {\n o_positions.push_back(position);\n }\n }\n readData->unlock();\n if(indicesOfParticlesToBeReleased.size() != 0)\n {\n PxStrideIterator inicesPX(reinterpret_cast(&indicesOfParticlesToBeReleased[0]));\n m_particleSystem->releaseParticles(indicesOfParticlesToBeReleased.size(), inicesPX);\n }\n }\n\n vector ParticleEmitter::GetDrainsHit() { return m_drainsHit; }\n\n void ParticleEmitter::SetData(ParticleEmitterData p_data) { m_this = p_data; }\n\n void ParticleEmitter::UpdateParticleLifeTimeAndRemoveExpired(float p_dt)\n {\n \/\/ Get particle indexData\n PxParticleReadData* t_particleData = m_particleSystem->lockParticleReadData();\n PX_ASSERT(t_particleData);\n std::vector t_indicesToRemove;\n PxU32 newvalidRange = 0;\n \/\/ Kolla om vi har ngra particlar som r valid annars ondigt att ens brja uppdatera\n if (t_particleData->validParticleRange > 0)\n {\n for (PxU32 i = 0; i <= (t_particleData->validParticleRange - 1) >> 5; i++)\n {\n for (PxU32 j = t_particleData->validParticleBitmap[i]; j; j &= j - 1)\n {\n \/\/ TODOXX super unsafe. I am not sure what i am doing here. I was following a tutorial and a function they used was missing. This seems to be what they did essentially but WARNING!!\n unsigned long b;\n _BitScanForward(&b, j);\n PxU32 t_index = (i << 5 | b);\n if (m_particlesLifeTime[t_index] = -p_dt < 0.0)\n {\n m_particlesLifeTime[t_index] = 0;\n t_indicesToRemove.push_back(t_index);\n }\n\n }\n }\n t_particleData->unlock();\n PxStrideIterator t_indexData(&t_indicesToRemove[0]);\n m_particleSystem->releaseParticles(static_cast(t_indicesToRemove.size()), t_indexData);\n \/\/ TODOLH om vi skaffar indexPool kr m_indexpool->freeIndices(indices.size(), indexData);\n }\n else\n {\n \/\/ Do nothing\n }\n }\n\n void ParticleEmitter::Update(float p_dt)\n {\n m_drainsHit.clear();\n if(m_this.m_active)\n {\n \/\/ Update time since last particle wave was spawned\n m_timeSinceLast += p_dt;\n if(m_timeSinceLast > m_this.m_emissionRate)\n {\n m_timeSinceLast = 0;\n vector velocities;\n vector positions;\n vector indices;\n \/\/\/ Time for more particles!\n \/\/\/ These particles will be spawned in a sort of grid (atm)\n for(int x = -m_this.m_density; x < m_this.m_density * 2 - 1; x++)\n {\n for(int y = -m_this.m_density; y < m_this.m_density * 2; y++)\n {\n \/\/ Calculate angles in local space\n float xAngle = (x \/ m_this.m_density) * m_this.m_emissionAreaDimensions.x;\n float yAngle = (y \/ m_this.m_density) * m_this.m_emissionAreaDimensions.y;\n \/\/ Define standard target in local space\n XMVECTOR particleVelocityVec = XMLoadFloat3(&XMFLOAT3(0, 0, 1));\n XMMATRIX rotMatLocal = XMMatrixRotationRollPitchYaw(xAngle, yAngle, 0);\n particleVelocityVec = XMVector3Transform(particleVelocityVec, rotMatLocal);\n \/\/ Move velocity vector into world space\n XMMATRIX rotMatWorld = XMMatrixRotationQuaternion(XMLoadFloat4(&m_this.m_direction));\n particleVelocityVec = XMVector3Transform(particleVelocityVec, rotMatWorld);\n \/\/ Multiply with pressure\n particleVelocityVec *= m_this.m_launchPressure;\n \/\/ Store in vector\n XMFLOAT3 velocity;\n XMStoreFloat3(&velocity, particleVelocityVec);\n velocities.push_back(velocity);\n\n \/\/ Add position (only emitts from the center of the emitter atm\n float launchOffset = 0.1f;\n XMVECTOR positionVec = XMLoadFloat3(&m_this.m_position);\n positionVec += launchOffset * particleVelocityVec;\n XMFLOAT3 position;\n XMStoreFloat3(&position, positionVec);\n\n positions.push_back(position);\n\n \/\/ Add index (silly way just to make it work atm)\n indices.push_back(m_nextIndex);\n \/\/ Set the lifetime of this particle TODOLH maybe add support for particles without lifetime. Some kind of bool. Hopefully we dont have to do this. Seems hard at first glance\n m_particlesLifeTime[m_nextIndex] = m_lifeTime;\n m_nextIndex++;\n }\n }\n\n\n if(positions.size() > 0 && !(m_nextIndex > PARTICLE_MAX_COUNT)) \/\/ no point doing things if there's no new particles\n {\n \/\/ Cast into PhysX datatypes\n PxVec3* positionsPX = reinterpret_cast(&positions[0]);\n PxVec3* velocitiesPX = reinterpret_cast(&velocities[0]);\n PxU32* indicesPX = reinterpret_cast(&indices[0]);\n\n \n \/\/ Create the particles\n PxParticleCreationData newParticlesData;\n newParticlesData.numParticles = positions.size();\n newParticlesData.positionBuffer = PxStrideIterator(positionsPX);\n newParticlesData.velocityBuffer = PxStrideIterator(velocitiesPX);\n newParticlesData.indexBuffer = PxStrideIterator(indicesPX);\n m_particleSystem->createParticles(newParticlesData);\n }\n else\n {\n \/\/ No new particles. Do nothing\n }\n }\n }\n }\n }\n}Added support for Particle Lifetime\/\/ This class\n#include \n\/\/#include \/\/ Included for the sake of particle data. Kinda silly, really\n#include \n\n\/\/ 3rd parties\n\nusing namespace DirectX;\nusing namespace physx;\nnamespace DoremiEngine\n{\n namespace Physics\n {\n ParticleEmitter::ParticleEmitter(ParticleEmitterData p_data, InternalPhysicsUtils& p_utils)\n : m_this(p_data), m_utils(p_utils), m_timeSinceLast(0)\n {\n m_nextIndex = 0;\n m_particleSystem = m_utils.m_physics->createParticleSystem(PARTICLE_MAX_COUNT);\n m_particleSystem->setMaxMotionDistance(PARTICLE_MAX_MOTION_DISTANCE);\n m_particleSystem->setParticleReadDataFlag(PxParticleReadDataFlag::eVELOCITY_BUFFER, true);\n m_utils.m_worldScene->addActor(*m_particleSystem);\n \/\/ Might be necessary to set flag to collide with dynamics\n \/\/ m_particleSystem->setParticleBaseFlag(PxParticleBaseFlag::eCOLLISION_WITH_DYNAMIC_ACTORS, true);\n m_particleSystem->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, true); \/\/ Should not be here\n }\n ParticleEmitter::~ParticleEmitter() {}\n\n void ParticleEmitter::SetPosition(XMFLOAT3 p_position) { m_this.m_position = p_position; }\n void ParticleEmitter::SetDirection(XMFLOAT4 p_direction) { m_this.m_direction = p_direction; }\n void ParticleEmitter::SetGravity(bool p_gravity) { m_particleSystem->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, p_gravity); }\n\n void ParticleEmitter::GetPositions(vector& o_positions)\n {\n \/\/ This is a bit harder than it really ought to be...\n PxParticleReadData* readData = m_particleSystem->lockParticleReadData();\n PxStrideIterator positions = readData->positionBuffer;\n PxStrideIterator velocities = readData->velocityBuffer;\n PxStrideIterator flags = readData->flagsBuffer;\n vector velocitiesVector;\n\n vector indicesOfParticlesToBeReleased;\n\n uint32_t numParticles = readData->validParticleRange;\n for(uint32_t i = 0; i < numParticles; i++)\n {\n \/\/ Check if particles are supposed to be removed\n XMFLOAT3 position = XMFLOAT3(positions[i].x, positions[i].y, positions[i].z);\n XMFLOAT3 velocity = XMFLOAT3(velocities[i].x, velocities[i].y, velocities[i].z);\n XMVECTOR velVec = XMLoadFloat3(&velocity);\n velVec = XMVector3Normalize(velVec);\n XMStoreFloat3(&velocity, velVec); \/\/ TODOJB Remove normalization once it's fixed in CastRay\n if(flags[i] & (PxParticleFlag::eCOLLISION_WITH_DRAIN)) \/\/ | PxParticleFlag::eVALID))\n {\n \/\/\/ Particle should be removed\n \/\/ Add index to release list\n indicesOfParticlesToBeReleased.push_back(i);\n \/\/ Find out which actor it collided with using ray tracing (seriously. It was this easy...)\n m_drainsHit.push_back(m_utils.m_rayCastManager->CastRay(position, velocity, 5)); \/\/ Zero might turn up buggy\n }\n else if(flags[i] & PxParticleFlag::eVALID)\n {\n o_positions.push_back(position);\n }\n }\n readData->unlock();\n if(indicesOfParticlesToBeReleased.size() != 0)\n {\n PxStrideIterator inicesPX(reinterpret_cast(&indicesOfParticlesToBeReleased[0]));\n m_particleSystem->releaseParticles(indicesOfParticlesToBeReleased.size(), inicesPX);\n }\n }\n\n vector ParticleEmitter::GetDrainsHit() { return m_drainsHit; }\n\n void ParticleEmitter::SetData(ParticleEmitterData p_data) { m_this = p_data; }\n\n void ParticleEmitter::UpdateParticleLifeTimeAndRemoveExpired(float p_dt)\n {\n std::vector t_indicesToRemove;\n \/\/ Get particle indexData\n PxParticleReadData* t_particleData = m_particleSystem->lockParticleReadData();\n PX_ASSERT(t_particleData);\n \/\/ Kolla om vi har ngra particlar som r valid annars ondigt att ens brja uppdatera\n if(t_particleData->validParticleRange > 0)\n {\n int length = t_particleData->validParticleRange;\n\n for(PxU32 i = 0; i <= (t_particleData->validParticleRange - 1) >> 5; i++)\n {\n\n for(PxU32 j = t_particleData->validParticleBitmap[i]; j; j &= j - 1)\n {\n \/\/ TODOXX super unsafe. I am not sure what i am doing here. I was following a tutorial and a function they used was missing.\n \/\/ This seems to be what they did essentially but WARNING!!\n \/\/ Get index from physx. you have to use bitoperations from their bittable for indices. Its pretty complicated and Im not 100%\n \/\/ sure this code is safe\n unsigned long b;\n _BitScanForward(&b, j);\n PxU32 t_index = (i << 5 | (PxU32)b);\n \/\/ Update particle lifetime\n m_particlesLifeTime[t_index] -= p_dt;\n \/\/ CHeck if particle is still alive\n if((m_particlesLifeTime[t_index]) < 0.0)\n {\n m_particlesLifeTime[t_index] = 0;\n t_indicesToRemove.push_back(t_index);\n }\n }\n }\n }\n else\n {\n \/\/ Do nothing\n }\n \/\/ Release the data we have been looking at\n t_particleData->unlock();\n \/\/ Needs to not crash\n if(t_indicesToRemove.size() > 0)\n {\n \/\/ Need Stride for releaseparticle.\n PxStrideIterator t_indexData(&t_indicesToRemove[0]);\n \/\/ Now release the particles that we want to remove\n m_particleSystem->releaseParticles(static_cast(t_indicesToRemove.size()), t_indexData);\n \/\/ TODOLH om vi skaffar indexPool kr m_indexpool->freeIndices(indices.size(), indexData);\n }\n }\n\n void ParticleEmitter::Update(float p_dt)\n {\n m_drainsHit.clear();\n UpdateParticleLifeTimeAndRemoveExpired(p_dt);\n if(m_this.m_active)\n {\n \/\/ Update time since last particle wave was spawned\n m_timeSinceLast += p_dt;\n if(m_timeSinceLast > m_this.m_emissionRate)\n {\n m_timeSinceLast = 0;\n vector velocities;\n vector positions;\n vector indices;\n \/\/\/ Time for more particles!\n \/\/\/ These particles will be spawned in a sort of grid (atm)\n for(int x = -m_this.m_density; x < m_this.m_density * 2 - 1; x++)\n {\n for(int y = -m_this.m_density; y < m_this.m_density * 2; y++)\n {\n \/\/ Calculate angles in local space\n float xAngle = (x \/ m_this.m_density) * m_this.m_emissionAreaDimensions.x;\n float yAngle = (y \/ m_this.m_density) * m_this.m_emissionAreaDimensions.y;\n \/\/ Define standard target in local space\n XMVECTOR particleVelocityVec = XMLoadFloat3(&XMFLOAT3(0, 0, 1));\n XMMATRIX rotMatLocal = XMMatrixRotationRollPitchYaw(xAngle, yAngle, 0);\n particleVelocityVec = XMVector3Transform(particleVelocityVec, rotMatLocal);\n \/\/ Move velocity vector into world space\n XMMATRIX rotMatWorld = XMMatrixRotationQuaternion(XMLoadFloat4(&m_this.m_direction));\n particleVelocityVec = XMVector3Transform(particleVelocityVec, rotMatWorld);\n \/\/ Multiply with pressure\n particleVelocityVec *= m_this.m_launchPressure;\n \/\/ Store in vector\n XMFLOAT3 velocity;\n XMStoreFloat3(&velocity, particleVelocityVec);\n velocities.push_back(velocity);\n\n \/\/ Add position (only emitts from the center of the emitter atm\n float launchOffset = 0.1f;\n XMVECTOR positionVec = XMLoadFloat3(&m_this.m_position);\n positionVec += launchOffset * particleVelocityVec;\n XMFLOAT3 position;\n XMStoreFloat3(&position, positionVec);\n\n positions.push_back(position);\n\n \/\/ Add index (silly way just to make it work atm)\n indices.push_back(m_nextIndex);\n \/\/ Set the lifetime of this particle TODOLH maybe add support for particles without lifetime. Some kind of bool. Hopefully we dont have to do this. Seems hard at first glance\n m_particlesLifeTime[m_nextIndex] = m_lifeTime;\n m_nextIndex++;\n }\n }\n\n\n if(positions.size() > 0 && !(m_nextIndex > PARTICLE_MAX_COUNT)) \/\/ no point doing things if there's no new particles\n {\n \/\/ Cast into PhysX datatypes\n PxVec3* positionsPX = reinterpret_cast(&positions[0]);\n PxVec3* velocitiesPX = reinterpret_cast(&velocities[0]);\n PxU32* indicesPX = reinterpret_cast(&indices[0]);\n\n \n \/\/ Create the particles\n PxParticleCreationData newParticlesData;\n newParticlesData.numParticles = positions.size();\n newParticlesData.positionBuffer = PxStrideIterator(positionsPX);\n newParticlesData.velocityBuffer = PxStrideIterator(velocitiesPX);\n newParticlesData.indexBuffer = PxStrideIterator(indicesPX);\n m_particleSystem->createParticles(newParticlesData);\n }\n else\n {\n \/\/ No new particles. Do nothing\n }\n }\n }\n }\n }\n}<|endoftext|>"} {"text":"\/*\nCopyright 2017 Google Inc. All Rights Reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \"ofLog.h\"\n\n#include \"MidiThread.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n\nMidiThread::MidiThread(Poco::FastMutex &synthMutex, NSynth &synth)\n\t: ofThread(), synthMutex(synthMutex), synth(synth){\n}\n\n\nbool MidiThread::setup(const std::string &device, int channel){\n\tthis->channel = channel;\n\n\t\/\/ The device setup is performed twice to ensure it works on device\n\t\/\/ startup.\n\n\tfor(int i=0; i<2; ++i){\n\t\tif(i != 0){\n\t\t\tclose(deviceFd);\n\t\t}\n\n\t\tdeviceFd = open(device.c_str(), O_RDONLY | O_NOCTTY);\n\t\tif(deviceFd < 0){\n\t\t\tofLog(OF_LOG_WARNING) << \"Failed to open MIDI input \" << device;\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/ Configure the serial port at 38400 baud. Settings on the Raspberry Pi\n\t\t\/\/ should adapt this to the MIDI baud rate of 31250.\n\t\tstruct termios tty;\n\t\tmemset(&tty, 0, sizeof tty);\n\t\tif(tcgetattr(deviceFd, &tty) != 0){\n\t\t\treturn false;\n\t\t}\n\n\t\tcfsetospeed(&tty, B38400);\n\t\tcfsetispeed(&tty, B38400);\n\n\t\ttty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;\n\t\ttty.c_iflag &= ~IGNBRK;\n\t\ttty.c_lflag = 0;\n\t\ttty.c_oflag = 0;\n\t\ttty.c_cc[VMIN] = 1;\n\t\ttty.c_cc[VTIME] = 0;\n\n\t\ttty.c_iflag &= ~(IXON | IXOFF | IXANY);\n\n\t\ttty.c_cflag |= (CLOCAL | CREAD);\n\t\ttty.c_cflag &= ~(PARENB | PARODD);\n\t\ttty.c_cflag &= ~CSTOPB;\n\t\ttty.c_cflag &= ~CRTSCTS;\n\n\t\tif(tcsetattr(deviceFd, TCSANOW, &tty) != 0){\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\n\nvoid MidiThread::threadedFunction(){\n\tauto read1 = [this]()->uint8_t{\n\t\tuint8_t result;\n\t\twhile(read(deviceFd, &result, 1) != 1){\n\t\t\tif(!isThreadRunning()){\n\t\t\t\treturn 0xff;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t};\n\n\tuint8_t header = read1();\n\twhile(isThreadRunning()){\n\t\tif((header & 0xf0) == 0x90){\n\t\t\t\/\/ Note on - this is a 3 byte message.\n\t\t\tuint8_t note = read1();\n\t\t\tif(!isThreadRunning()){\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif(note & 0x80){\n\t\t\t\t\/\/ The note is badly formed, discard the current header\n\t\t\t\t\/\/ and continue;\n\t\t\t\theader = note;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tuint8_t velocity = read1();\n\t\t\tif(!isThreadRunning()){\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif(velocity & 0x80){\n\t\t\t\t\/\/ The note is badly formed, discard the current header\n\t\t\t\t\/\/ and continue;\n\t\t\t\theader = note;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif((header & 0x0f) == channel){\n\t\t\t\tsynthMutex.lock();\n\t\t\t\tsynth.on(note, static_cast(velocity) \/ 127.0f);\n\t\t\t\tsynthMutex.unlock();\n\t\t\t}\n\n\t\t\t\/\/ Start on the next message.\n\t\t\theader = read1();\n\t\t}else if((header & 0xf0) == 0x80){\n\t\t\t\/\/ Note off - this is a 3 byte message.\n\t\t\tuint8_t note = read1();\n\t\t\tif(!isThreadRunning()){\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif(note & 0x80){\n\t\t\t\t\/\/ The note is badly formed, discard the current header\n\t\t\t\t\/\/ and continue;\n\t\t\t\theader = note;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tuint8_t velocity = read1();\n\t\t\tif(!isThreadRunning()){\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif(velocity & 0x80){\n\t\t\t\t\/\/ The note is badly formed, discard the current header\n\t\t\t\t\/\/ and continue;\n\t\t\t\theader = note;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif((header & 0x0f) == channel){\n\t\t\t\tsynthMutex.lock();\n\t\t\t\tsynth.off(note);\n\t\t\t\tsynthMutex.unlock();\n\t\t\t}\n\n\t\t\t\/\/ Start on the next message.\n\t\t\theader = read1();\n\t\t}else{\n\t\t\t\/\/ Discard the header as it is not understood.\n\t\t\theader = read1();\n\t\t}\n\t}\n}\nFix #43 by filtering out system real-time messages\/*\nCopyright 2017 Google Inc. All Rights Reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \"ofLog.h\"\n\n#include \"MidiThread.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n\nMidiThread::MidiThread(Poco::FastMutex &synthMutex, NSynth &synth)\n\t: ofThread(), synthMutex(synthMutex), synth(synth){\n}\n\n\nbool MidiThread::setup(const std::string &device, int channel){\n\tthis->channel = channel;\n\n\t\/\/ The device setup is performed twice to ensure it works on device\n\t\/\/ startup.\n\n\tfor(int i=0; i<2; ++i){\n\t\tif(i != 0){\n\t\t\tclose(deviceFd);\n\t\t}\n\n\t\tdeviceFd = open(device.c_str(), O_RDONLY | O_NOCTTY);\n\t\tif(deviceFd < 0){\n\t\t\tofLog(OF_LOG_WARNING) << \"Failed to open MIDI input \" << device;\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/ Configure the serial port at 38400 baud. Settings on the Raspberry Pi\n\t\t\/\/ should adapt this to the MIDI baud rate of 31250.\n\t\tstruct termios tty;\n\t\tmemset(&tty, 0, sizeof tty);\n\t\tif(tcgetattr(deviceFd, &tty) != 0){\n\t\t\treturn false;\n\t\t}\n\n\t\tcfsetospeed(&tty, B38400);\n\t\tcfsetispeed(&tty, B38400);\n\n\t\ttty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;\n\t\ttty.c_iflag &= ~IGNBRK;\n\t\ttty.c_lflag = 0;\n\t\ttty.c_oflag = 0;\n\t\ttty.c_cc[VMIN] = 1;\n\t\ttty.c_cc[VTIME] = 0;\n\n\t\ttty.c_iflag &= ~(IXON | IXOFF | IXANY);\n\n\t\ttty.c_cflag |= (CLOCAL | CREAD);\n\t\ttty.c_cflag &= ~(PARENB | PARODD);\n\t\ttty.c_cflag &= ~CSTOPB;\n\t\ttty.c_cflag &= ~CRTSCTS;\n\n\t\tif(tcsetattr(deviceFd, TCSANOW, &tty) != 0){\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\n\nvoid MidiThread::threadedFunction(){\n\tauto read1 = [this]()->uint8_t{\n\t\tuint8_t result;\n\t\twhile(true) {\n if(!isThreadRunning()){\n\t\t\t\treturn 0xff;\n }\n\t\t\t\n\t\t\tint readCount = read(deviceFd, &result, 1);\n if (readCount != 1) {\n continue;\n }\n\n\t\t\t\/\/ ignore system real time bytes\n if (result == 0xFE || result == 0xFF || result == 0xF8 || result == 0xFA || result == 0xFB || result == 0xFC) {\n continue;\n }\n\t\t\t\n\t\t\treturn result;\n\t\t}\n\t};\n\n\tuint8_t header = read1();\n\twhile(isThreadRunning()){\n\t\tif((header & 0xf0) == 0x90){\n\t\t\t\/\/ Note on - this is a 3 byte message.\n\t\t\tuint8_t note = read1();\n\t\t\tif(!isThreadRunning()){\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif(note & 0x80){\n\t\t\t\t\/\/ The note is badly formed, discard the current header\n\t\t\t\t\/\/ and continue;\n\t\t\t\theader = note;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tuint8_t velocity = read1();\n\t\t\tif(!isThreadRunning()){\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif(velocity & 0x80){\n\t\t\t\t\/\/ The note is badly formed, discard the current header\n\t\t\t\t\/\/ and continue;\n\t\t\t\theader = note;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif((header & 0x0f) == channel){\n\t\t\t\tsynthMutex.lock();\n\t\t\t\tsynth.on(note, static_cast(velocity) \/ 127.0f);\n\t\t\t\tsynthMutex.unlock();\n\t\t\t}\n\n\t\t\t\/\/ Start on the next message.\n\t\t\theader = read1();\n\t\t}else if((header & 0xf0) == 0x80){\n\t\t\t\/\/ Note off - this is a 3 byte message.\n\t\t\tuint8_t note = read1();\n\t\t\tif(!isThreadRunning()){\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif(note & 0x80){\n\t\t\t\t\/\/ The note is badly formed, discard the current header\n\t\t\t\t\/\/ and continue;\n\t\t\t\theader = note;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tuint8_t velocity = read1();\n\t\t\tif(!isThreadRunning()){\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif(velocity & 0x80){\n\t\t\t\t\/\/ The note is badly formed, discard the current header\n\t\t\t\t\/\/ and continue;\n\t\t\t\theader = note;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif((header & 0x0f) == channel){\n\t\t\t\tsynthMutex.lock();\n\t\t\t\tsynth.off(note);\n\t\t\t\tsynthMutex.unlock();\n\t\t\t}\n\n\t\t\t\/\/ Start on the next message.\n\t\t\theader = read1();\n\t\t}else{\n\t\t\t\/\/ Discard the header as it is not understood.\n\t\t\theader = read1();\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: QueryViewSwitch.hxx,v $\n * $Revision: 1.14 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef DBAUI_QUERYVIEWSWITCH_HXX\n#define DBAUI_QUERYVIEWSWITCH_HXX\n\n#ifndef DBAUI_QUERYVIEW_HXX\n#include \"queryview.hxx\"\n#endif\n\nnamespace dbaui\n{\n class OQueryDesignView;\n class OQueryTextView;\n class OAddTableDlg;\n class OQueryContainerWindow;\n class OQueryViewSwitch\n {\n OQueryDesignView* m_pDesignView;\n OQueryTextView* m_pTextView;\n sal_Bool m_bAddTableDialogWasVisible; \/\/ true if so\n public:\n OQueryViewSwitch(OQueryContainerWindow* pParent, OQueryController* _pController,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& );\n virtual ~OQueryViewSwitch();\n\n virtual sal_Bool isCutAllowed();\n virtual sal_Bool isPasteAllowed();\n virtual sal_Bool isCopyAllowed();\n virtual void copy();\n virtual void cut();\n virtual void paste();\n \/\/ clears the whole query\n virtual void clear();\n \/\/ set the view readonly or not\n virtual void setReadOnly(sal_Bool _bReadOnly);\n \/\/ check if the statement is correct when not returning false\n virtual sal_Bool checkStatement();\n \/\/ set the statement for representation\n virtual void setStatement(const ::rtl::OUString& _rsStatement);\n \/\/ returns the current sql statement\n virtual ::rtl::OUString getStatement();\n \/\/\/ late construction\n virtual void Construct();\n virtual void initialize();\n \/** show the text or the design view\n @return\n when all went right otherwise which implies an aditional\n call of switchView from the controller to restore the old state\n *\/\n sal_Bool switchView();\n sal_Bool isSlotEnabled(sal_Int32 _nSlotId);\n void setSlotEnabled(sal_Int32 _nSlotId,sal_Bool _bEnable);\n void setNoneVisbleRow(sal_Int32 _nRows);\n \/\/ returs the add table dialog from the design view\n OAddTableDlg* getAddTableDialog();\n void SaveUIConfig();\n void reset();\n void GrabFocus();\n\n OQueryDesignView* getDesignView() const { return m_pDesignView; }\n OQueryContainerWindow* getContainer() const;\n\n void SetPosSizePixel( Point _rPt,Size _rSize);\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getORB() const;\n protected:\n \/\/ return the Rectangle where I can paint myself\n virtual void resizeDocumentView(Rectangle& rRect);\n };\n}\n#endif \/\/ DBAUI_QUERYVIEWSWITCH_HXX\n\nINTEGRATION: CWS dba30d (1.14.30); FILE MERGED 2008\/05\/29 11:25:58 fs 1.14.30.1: during #i80943#: refactoring: IController now passed around as reference, not as pointer\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: QueryViewSwitch.hxx,v $\n * $Revision: 1.15 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef DBAUI_QUERYVIEWSWITCH_HXX\n#define DBAUI_QUERYVIEWSWITCH_HXX\n\n#ifndef DBAUI_QUERYVIEW_HXX\n#include \"queryview.hxx\"\n#endif\n\nnamespace dbaui\n{\n class OQueryDesignView;\n class OQueryTextView;\n class OAddTableDlg;\n class OQueryContainerWindow;\n class OQueryViewSwitch\n {\n OQueryDesignView* m_pDesignView;\n OQueryTextView* m_pTextView;\n sal_Bool m_bAddTableDialogWasVisible; \/\/ true if so\n public:\n OQueryViewSwitch(OQueryContainerWindow* pParent, OQueryController& _rController,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& );\n virtual ~OQueryViewSwitch();\n\n virtual sal_Bool isCutAllowed();\n virtual sal_Bool isPasteAllowed();\n virtual sal_Bool isCopyAllowed();\n virtual void copy();\n virtual void cut();\n virtual void paste();\n \/\/ clears the whole query\n virtual void clear();\n \/\/ set the view readonly or not\n virtual void setReadOnly(sal_Bool _bReadOnly);\n \/\/ check if the statement is correct when not returning false\n virtual sal_Bool checkStatement();\n \/\/ set the statement for representation\n virtual void setStatement(const ::rtl::OUString& _rsStatement);\n \/\/ returns the current sql statement\n virtual ::rtl::OUString getStatement();\n \/\/\/ late construction\n virtual void Construct();\n virtual void initialize();\n \/** show the text or the design view\n @return\n when all went right otherwise which implies an aditional\n call of switchView from the controller to restore the old state\n *\/\n sal_Bool switchView();\n sal_Bool isSlotEnabled(sal_Int32 _nSlotId);\n void setSlotEnabled(sal_Int32 _nSlotId,sal_Bool _bEnable);\n void setNoneVisbleRow(sal_Int32 _nRows);\n \/\/ returs the add table dialog from the design view\n OAddTableDlg* getAddTableDialog();\n void SaveUIConfig();\n void reset();\n void GrabFocus();\n\n OQueryDesignView* getDesignView() const { return m_pDesignView; }\n OQueryContainerWindow* getContainer() const;\n\n void SetPosSizePixel( Point _rPt,Size _rSize);\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getORB() const;\n protected:\n \/\/ return the Rectangle where I can paint myself\n virtual void resizeDocumentView(Rectangle& rRect);\n };\n}\n#endif \/\/ DBAUI_QUERYVIEWSWITCH_HXX\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: RelationControl.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: oj $ $Date: 2002-11-08 09:27:37 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef DBAUI_RELATIONCONTROL_HXX\n#define DBAUI_RELATIONCONTROL_HXX\n\n#ifndef _FIXED_HXX \/\/autogen\n#include \n#endif\n#ifndef _SV_LSTBOX_HXX \/\/autogen\n#include \n#endif\n#ifndef DBAUI_JOINTABLEVIEW_HXX\n#include \"JoinTableView.hxx\"\n#endif\n\nnamespace dbaui\n{\n \/\/========================================================================\n class OTableListBoxControl;\n class OTableConnectionData;\n class ORelationTableConnectionData;\n class IRelationControlInterface;\n class ORelationControl;\n\n class OTableListBoxControl : public Window\n {\n FixedLine m_aFL_InvolvedTables;\n ListBox m_lmbLeftTable,\n m_lmbRightTable;\n FixedLine m_aFL_InvolvedFields;\n\n ORelationControl* m_pRC_Tables;\n const OJoinTableView::OTableWindowMap* m_pTableMap;\n IRelationControlInterface* m_pParentDialog;\n String m_strCurrentLeft;\n String m_strCurrentRight;\n private:\n DECL_LINK( OnTableChanged, ListBox* );\n public:\n OTableListBoxControl(Window* _pParent,\n const ResId& _rResId,\n const OJoinTableView::OTableWindowMap* _pTableMap,\n IRelationControlInterface* _pParentDialog);\n virtual ~OTableListBoxControl();\n\n \/** fillListBoxes fills the list boxes with the table windows\n *\/\n void fillListBoxes();\n\n \/** fillAndDisable fill the listboxes only with one entry and then disable them\n @param _pConnectionData\n contains the data which should be filled into the listboxes\n *\/\n void fillAndDisable(OTableConnectionData* _pConnectionData);\n\n \/** NotifyCellChange notifies the browse control that the conenction data has changed\n *\/\n void NotifyCellChange();\n\n \/** Init is a call through to the control inside this one\n @param _pConnData\n the connection data which is used to init the control\n *\/\n void Init(OTableConnectionData* _pConnData);\n void lateInit();\n\n BOOL SaveModified();\n\n String getSourceWinName() const;\n String getDestWinName() const;\n\n \/** getContainer returns the container interface\n @return the interface of the container\n *\/\n IRelationControlInterface* getContainer() const { return m_pParentDialog; }\n };\n}\n#endif \/\/ DBAUI_RELATIONCONTROL_HXX\nINTEGRATION: CWS ooo19126 (1.3.472); FILE MERGED 2005\/09\/05 17:34:24 rt 1.3.472.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: RelationControl.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 15:32:26 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef DBAUI_RELATIONCONTROL_HXX\n#define DBAUI_RELATIONCONTROL_HXX\n\n#ifndef _FIXED_HXX \/\/autogen\n#include \n#endif\n#ifndef _SV_LSTBOX_HXX \/\/autogen\n#include \n#endif\n#ifndef DBAUI_JOINTABLEVIEW_HXX\n#include \"JoinTableView.hxx\"\n#endif\n\nnamespace dbaui\n{\n \/\/========================================================================\n class OTableListBoxControl;\n class OTableConnectionData;\n class ORelationTableConnectionData;\n class IRelationControlInterface;\n class ORelationControl;\n\n class OTableListBoxControl : public Window\n {\n FixedLine m_aFL_InvolvedTables;\n ListBox m_lmbLeftTable,\n m_lmbRightTable;\n FixedLine m_aFL_InvolvedFields;\n\n ORelationControl* m_pRC_Tables;\n const OJoinTableView::OTableWindowMap* m_pTableMap;\n IRelationControlInterface* m_pParentDialog;\n String m_strCurrentLeft;\n String m_strCurrentRight;\n private:\n DECL_LINK( OnTableChanged, ListBox* );\n public:\n OTableListBoxControl(Window* _pParent,\n const ResId& _rResId,\n const OJoinTableView::OTableWindowMap* _pTableMap,\n IRelationControlInterface* _pParentDialog);\n virtual ~OTableListBoxControl();\n\n \/** fillListBoxes fills the list boxes with the table windows\n *\/\n void fillListBoxes();\n\n \/** fillAndDisable fill the listboxes only with one entry and then disable them\n @param _pConnectionData\n contains the data which should be filled into the listboxes\n *\/\n void fillAndDisable(OTableConnectionData* _pConnectionData);\n\n \/** NotifyCellChange notifies the browse control that the conenction data has changed\n *\/\n void NotifyCellChange();\n\n \/** Init is a call through to the control inside this one\n @param _pConnData\n the connection data which is used to init the control\n *\/\n void Init(OTableConnectionData* _pConnData);\n void lateInit();\n\n BOOL SaveModified();\n\n String getSourceWinName() const;\n String getDestWinName() const;\n\n \/** getContainer returns the container interface\n @return the interface of the container\n *\/\n IRelationControlInterface* getContainer() const { return m_pParentDialog; }\n };\n}\n#endif \/\/ DBAUI_RELATIONCONTROL_HXX\n<|endoftext|>"} {"text":"\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of duicompositor.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"mdecoratorwindow.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\nclass MDecorator: public MAbstractDecorator\n{\n Q_OBJECT\npublic:\n MDecorator(MDecoratorWindow *p)\n : MAbstractDecorator(p),\n decorwindow(p)\n {\n }\n\n ~MDecorator() {\n }\n\n virtual void manageEvent(Qt::HANDLE window)\n {\n XTextProperty p;\n QString title;\n\n if(XGetWMName(QX11Info::display(), window, &p)) {\n if (p.value) {\n title = (char*) p.value;\n XFree(p.value);\n }\n }\n decorwindow->setInputRegion();\n setAvailableGeometry(decorwindow->availableClientRect());\n decorwindow->setWindowTitle(title);\n }\n\nprotected:\n virtual void activateEvent() {\n }\n\n virtual void setAutoRotation(bool mode)\n {\n Q_UNUSED(mode)\n \/\/ we follow the orientation of the topmost app\n }\n\n virtual void setOnlyStatusbar(bool mode) \n {\n decorwindow->setOnlyStatusbar(mode);\n decorwindow->setInputRegion();\n setAvailableGeometry(decorwindow->availableClientRect());\n }\n\nprivate:\n\n MDecoratorWindow *decorwindow;\n};\n\n#if 0\nstatic QRect windowRectFromGraphicsItem(const QGraphicsView &view,\n const QGraphicsItem &item)\n{\n return view.mapFromScene(\n item.mapToScene(\n item.boundingRect()\n )\n ).boundingRect();\n}\n#endif\n\nMDecoratorWindow::MDecoratorWindow(QWidget *parent)\n : MWindow(parent)\n{\n onlyStatusbarAtom = XInternAtom(QX11Info::display(),\n \"_MDECORATOR_ONLY_STATUSBAR\", False);\n managedWindowAtom = XInternAtom(QX11Info::display(),\n \"_MDECORATOR_MANAGED_WINDOW\", False);\n\n homeButtonPanel = new MHomeButtonPanel();\n escapeButtonPanel = new MEscapeButtonPanel();\n navigationBar = new MNavigationBar();\n statusBar = new MStatusBar();\n\n connect(homeButtonPanel, SIGNAL(buttonClicked()), this,\n SIGNAL(homeClicked()));\n connect(escapeButtonPanel, SIGNAL(buttonClicked()), this,\n SIGNAL(escapeClicked()));\n\n sceneManager()->appearSceneWindowNow(statusBar);\n setOnlyStatusbar(false);\n\n d = new MDecorator(this);\n connect(this, SIGNAL(homeClicked()), d, SLOT(minimize()));\n connect(this, SIGNAL(escapeClicked()), d, SLOT(close()));\n connect(sceneManager(),\n SIGNAL(orientationChanged(M::Orientation)),\n this,\n SLOT(screenRotated(M::Orientation)));\n\n setFocusPolicy(Qt::NoFocus);\n setSceneSize();\n setMDecoratorWindowProperty();\n\n setInputRegion();\n setProperty(\"followsCurrentApplicationWindowOrientation\", true);\n}\n\nvoid MDecoratorWindow::setWindowTitle(const QString& title)\n{\n navigationBar->setViewMenuDescription(title);\n}\n\nMDecoratorWindow::~MDecoratorWindow()\n{\n}\n\nbool MDecoratorWindow::x11Event(XEvent *e)\n{\n Atom actual;\n int format, result;\n unsigned long n, left;\n unsigned char *data = 0;\n if (e->type == PropertyNotify\n && ((XPropertyEvent*)e)->atom == onlyStatusbarAtom) {\n result = XGetWindowProperty(QX11Info::display(), winId(),\n onlyStatusbarAtom, 0, 1, False,\n XA_CARDINAL, &actual, &format,\n &n, &left, &data);\n if (result == Success && data) {\n bool val = *((long*)data);\n if (val != only_statusbar)\n d->RemoteSetOnlyStatusbar(val);\n }\n if (data)\n XFree(data);\n return true;\n } else if (e->type == PropertyNotify\n && ((XPropertyEvent*)e)->atom == managedWindowAtom) {\n result = XGetWindowProperty(QX11Info::display(), winId(),\n managedWindowAtom, 0, 1, False,\n XA_WINDOW, &actual, &format,\n &n, &left, &data);\n if (result == Success && data)\n d->RemoteSetManagedWinId(*((long*)data));\n if (data)\n XFree(data);\n return true;\n }\n return false;\n}\n\nvoid MDecoratorWindow::setOnlyStatusbar(bool mode)\n{\n if (mode) {\n sceneManager()->disappearSceneWindowNow(navigationBar);\n sceneManager()->disappearSceneWindowNow(homeButtonPanel);\n sceneManager()->disappearSceneWindowNow(escapeButtonPanel);\n } else {\n sceneManager()->appearSceneWindowNow(navigationBar);\n sceneManager()->appearSceneWindowNow(homeButtonPanel);\n sceneManager()->appearSceneWindowNow(escapeButtonPanel);\n }\n only_statusbar = mode;\n}\n\nvoid MDecoratorWindow::screenRotated(const M::Orientation &orientation)\n{\n Q_UNUSED(orientation);\n setInputRegion();\n d->setAvailableGeometry(availableClientRect());\n}\n\nXRectangle MDecoratorWindow::itemRectToScreenRect(const QRect& r)\n{\n XRectangle rect;\n Display *dpy = QX11Info::display();\n int xres = ScreenOfDisplay(dpy, DefaultScreen(dpy))->width;\n int yres = ScreenOfDisplay(dpy, DefaultScreen(dpy))->height;\n switch (sceneManager()->orientationAngle()) {\n case 0:\n rect.x = r.x();\n rect.y = r.y();\n rect.width = r.width();\n rect.height = r.height();\n break;\n case 90:\n rect.x = xres - r.height();\n rect.y = 0;\n rect.width = r.height();\n rect.height = r.width();\n break;\n case 270:\n rect.x = rect.y = 0;\n rect.width = r.height();\n rect.height = r.width();\n break;\n case 180:\n rect.x = 0;\n rect.y = yres - r.height();\n rect.width = r.width();\n rect.height = r.height();\n break;\n default:\n memset(&rect, 0, sizeof(rect));\n break;\n }\n return rect;\n}\n\nvoid MDecoratorWindow::setInputRegion()\n{\n static XRectangle prev_rect = {0, 0, 0, 0};\n QRegion region;\n QRect r_tmp(statusBar->geometry().toRect());\n region += statusBar->mapToScene(r_tmp).boundingRect().toRect();\n if (!only_statusbar) {\n r_tmp = QRect(navigationBar->geometry().toRect());\n region += navigationBar->mapToScene(r_tmp).boundingRect().toRect();\n r_tmp = QRect(homeButtonPanel->geometry().toRect());\n region += homeButtonPanel->mapToScene(r_tmp).boundingRect().toRect();\n r_tmp = QRect(escapeButtonPanel->geometry().toRect());\n region += escapeButtonPanel->mapToScene(r_tmp).boundingRect().toRect();\n }\n\n const QRect fs(QApplication::desktop()->screenGeometry());\n decoratorRect = region.boundingRect();\n \/\/ crop it to fullscreen to work around a weird issue\n if (decoratorRect.width() > fs.width())\n decoratorRect.setWidth(fs.width());\n if (decoratorRect.height() > fs.height())\n decoratorRect.setHeight(fs.height());\n\n if (!only_statusbar && decoratorRect.width() > fs.width() \/ 2\n && decoratorRect.height() > fs.height() \/ 2) {\n \/\/ decorator is so big that it is probably in more than one part\n \/\/ (which is not yet supported)\n setOnlyStatusbar(true);\n region = decoratorRect = statusBar->geometry().toRect();\n }\n XRectangle rect = itemRectToScreenRect(decoratorRect);\n if (memcmp(&prev_rect, &rect, sizeof(XRectangle))) {\n Display *dpy = QX11Info::display();\n XserverRegion shapeRegion = XFixesCreateRegion(dpy, &rect, 1);\n XShapeCombineRectangles(dpy, winId(), ShapeBounding, 0, 0, &rect, 1,\n ShapeSet, Unsorted);\n XFixesSetWindowShapeRegion(dpy, winId(), ShapeInput, 0, 0, shapeRegion);\n XFixesDestroyRegion(dpy, shapeRegion);\n XSync(dpy, False);\n prev_rect = rect;\n }\n\n \/\/ selective compositing\n if (isVisible() && region.isEmpty()) {\n hide();\n } else if (!isVisible() && !region.isEmpty()) {\n show();\n }\n}\n\nvoid MDecoratorWindow::setSceneSize()\n{\n \/\/ always keep landscape size\n Display *dpy = QX11Info::display();\n int xres = ScreenOfDisplay(dpy, DefaultScreen(dpy))->width;\n int yres = ScreenOfDisplay(dpy, DefaultScreen(dpy))->height;\n scene()->setSceneRect(0, 0, xres, yres);\n setMinimumSize(xres, yres);\n setMaximumSize(xres, yres);\n}\n\nvoid MDecoratorWindow::setMDecoratorWindowProperty()\n{\n\n long on = 1;\n\n XChangeProperty(QX11Info::display(), winId(),\n XInternAtom(QX11Info::display(), \"_MEEGOTOUCH_DECORATOR_WINDOW\", False),\n XA_CARDINAL,\n 32, PropModeReplace,\n (unsigned char *) &on, 1);\n}\n\n\nconst QRect MDecoratorWindow::availableClientRect() const\n{\n return decoratorRect;\n}\n\nvoid MDecoratorWindow::closeEvent(QCloseEvent * event )\n{\n \/\/ never close the decorator!\n return event->ignore();\n}\n\n#include \"mdecoratorwindow.moc\"\nset right decoratorRect in case it's too large\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of duicompositor.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"mdecoratorwindow.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\nclass MDecorator: public MAbstractDecorator\n{\n Q_OBJECT\npublic:\n MDecorator(MDecoratorWindow *p)\n : MAbstractDecorator(p),\n decorwindow(p)\n {\n }\n\n ~MDecorator() {\n }\n\n virtual void manageEvent(Qt::HANDLE window)\n {\n XTextProperty p;\n QString title;\n\n if(XGetWMName(QX11Info::display(), window, &p)) {\n if (p.value) {\n title = (char*) p.value;\n XFree(p.value);\n }\n }\n decorwindow->setInputRegion();\n setAvailableGeometry(decorwindow->availableClientRect());\n decorwindow->setWindowTitle(title);\n }\n\nprotected:\n virtual void activateEvent() {\n }\n\n virtual void setAutoRotation(bool mode)\n {\n Q_UNUSED(mode)\n \/\/ we follow the orientation of the topmost app\n }\n\n virtual void setOnlyStatusbar(bool mode) \n {\n decorwindow->setOnlyStatusbar(mode);\n decorwindow->setInputRegion();\n setAvailableGeometry(decorwindow->availableClientRect());\n }\n\nprivate:\n\n MDecoratorWindow *decorwindow;\n};\n\n#if 0\nstatic QRect windowRectFromGraphicsItem(const QGraphicsView &view,\n const QGraphicsItem &item)\n{\n return view.mapFromScene(\n item.mapToScene(\n item.boundingRect()\n )\n ).boundingRect();\n}\n#endif\n\nMDecoratorWindow::MDecoratorWindow(QWidget *parent)\n : MWindow(parent)\n{\n onlyStatusbarAtom = XInternAtom(QX11Info::display(),\n \"_MDECORATOR_ONLY_STATUSBAR\", False);\n managedWindowAtom = XInternAtom(QX11Info::display(),\n \"_MDECORATOR_MANAGED_WINDOW\", False);\n\n homeButtonPanel = new MHomeButtonPanel();\n escapeButtonPanel = new MEscapeButtonPanel();\n navigationBar = new MNavigationBar();\n statusBar = new MStatusBar();\n\n connect(homeButtonPanel, SIGNAL(buttonClicked()), this,\n SIGNAL(homeClicked()));\n connect(escapeButtonPanel, SIGNAL(buttonClicked()), this,\n SIGNAL(escapeClicked()));\n\n sceneManager()->appearSceneWindowNow(statusBar);\n setOnlyStatusbar(false);\n\n d = new MDecorator(this);\n connect(this, SIGNAL(homeClicked()), d, SLOT(minimize()));\n connect(this, SIGNAL(escapeClicked()), d, SLOT(close()));\n connect(sceneManager(),\n SIGNAL(orientationChanged(M::Orientation)),\n this,\n SLOT(screenRotated(M::Orientation)));\n\n setFocusPolicy(Qt::NoFocus);\n setSceneSize();\n setMDecoratorWindowProperty();\n\n setInputRegion();\n setProperty(\"followsCurrentApplicationWindowOrientation\", true);\n}\n\nvoid MDecoratorWindow::setWindowTitle(const QString& title)\n{\n navigationBar->setViewMenuDescription(title);\n}\n\nMDecoratorWindow::~MDecoratorWindow()\n{\n}\n\nbool MDecoratorWindow::x11Event(XEvent *e)\n{\n Atom actual;\n int format, result;\n unsigned long n, left;\n unsigned char *data = 0;\n if (e->type == PropertyNotify\n && ((XPropertyEvent*)e)->atom == onlyStatusbarAtom) {\n result = XGetWindowProperty(QX11Info::display(), winId(),\n onlyStatusbarAtom, 0, 1, False,\n XA_CARDINAL, &actual, &format,\n &n, &left, &data);\n if (result == Success && data) {\n bool val = *((long*)data);\n if (val != only_statusbar)\n d->RemoteSetOnlyStatusbar(val);\n }\n if (data)\n XFree(data);\n return true;\n } else if (e->type == PropertyNotify\n && ((XPropertyEvent*)e)->atom == managedWindowAtom) {\n result = XGetWindowProperty(QX11Info::display(), winId(),\n managedWindowAtom, 0, 1, False,\n XA_WINDOW, &actual, &format,\n &n, &left, &data);\n if (result == Success && data)\n d->RemoteSetManagedWinId(*((long*)data));\n if (data)\n XFree(data);\n return true;\n }\n return false;\n}\n\nvoid MDecoratorWindow::setOnlyStatusbar(bool mode)\n{\n if (mode) {\n sceneManager()->disappearSceneWindowNow(navigationBar);\n sceneManager()->disappearSceneWindowNow(homeButtonPanel);\n sceneManager()->disappearSceneWindowNow(escapeButtonPanel);\n } else {\n sceneManager()->appearSceneWindowNow(navigationBar);\n sceneManager()->appearSceneWindowNow(homeButtonPanel);\n sceneManager()->appearSceneWindowNow(escapeButtonPanel);\n }\n only_statusbar = mode;\n}\n\nvoid MDecoratorWindow::screenRotated(const M::Orientation &orientation)\n{\n Q_UNUSED(orientation);\n setInputRegion();\n d->setAvailableGeometry(availableClientRect());\n}\n\nXRectangle MDecoratorWindow::itemRectToScreenRect(const QRect& r)\n{\n XRectangle rect;\n Display *dpy = QX11Info::display();\n int xres = ScreenOfDisplay(dpy, DefaultScreen(dpy))->width;\n int yres = ScreenOfDisplay(dpy, DefaultScreen(dpy))->height;\n switch (sceneManager()->orientationAngle()) {\n case 0:\n rect.x = r.x();\n rect.y = r.y();\n rect.width = r.width();\n rect.height = r.height();\n break;\n case 90:\n rect.x = xres - r.height();\n rect.y = 0;\n rect.width = r.height();\n rect.height = r.width();\n break;\n case 270:\n rect.x = rect.y = 0;\n rect.width = r.height();\n rect.height = r.width();\n break;\n case 180:\n rect.x = 0;\n rect.y = yres - r.height();\n rect.width = r.width();\n rect.height = r.height();\n break;\n default:\n memset(&rect, 0, sizeof(rect));\n break;\n }\n return rect;\n}\n\nvoid MDecoratorWindow::setInputRegion()\n{\n static XRectangle prev_rect = {0, 0, 0, 0};\n QRegion region;\n QRect r_tmp(statusBar->geometry().toRect());\n region += statusBar->mapToScene(r_tmp).boundingRect().toRect();\n if (!only_statusbar) {\n r_tmp = QRect(navigationBar->geometry().toRect());\n region += navigationBar->mapToScene(r_tmp).boundingRect().toRect();\n r_tmp = QRect(homeButtonPanel->geometry().toRect());\n region += homeButtonPanel->mapToScene(r_tmp).boundingRect().toRect();\n r_tmp = QRect(escapeButtonPanel->geometry().toRect());\n region += escapeButtonPanel->mapToScene(r_tmp).boundingRect().toRect();\n }\n\n const QRect fs(QApplication::desktop()->screenGeometry());\n decoratorRect = region.boundingRect();\n \/\/ crop it to fullscreen to work around a weird issue\n if (decoratorRect.width() > fs.width())\n decoratorRect.setWidth(fs.width());\n if (decoratorRect.height() > fs.height())\n decoratorRect.setHeight(fs.height());\n\n if (!only_statusbar && decoratorRect.width() > fs.width() \/ 2\n && decoratorRect.height() > fs.height() \/ 2) {\n \/\/ decorator is so big that it is probably in more than one part\n \/\/ (which is not yet supported)\n setOnlyStatusbar(true);\n r_tmp = statusBar->geometry().toRect();\n region = decoratorRect = statusBar->mapToScene(r_tmp).boundingRect().toRect();\n }\n XRectangle rect = itemRectToScreenRect(decoratorRect);\n if (memcmp(&prev_rect, &rect, sizeof(XRectangle))) {\n Display *dpy = QX11Info::display();\n XserverRegion shapeRegion = XFixesCreateRegion(dpy, &rect, 1);\n XShapeCombineRectangles(dpy, winId(), ShapeBounding, 0, 0, &rect, 1,\n ShapeSet, Unsorted);\n XFixesSetWindowShapeRegion(dpy, winId(), ShapeInput, 0, 0, shapeRegion);\n XFixesDestroyRegion(dpy, shapeRegion);\n XSync(dpy, False);\n prev_rect = rect;\n }\n\n \/\/ selective compositing\n if (isVisible() && region.isEmpty()) {\n hide();\n } else if (!isVisible() && !region.isEmpty()) {\n show();\n }\n}\n\nvoid MDecoratorWindow::setSceneSize()\n{\n \/\/ always keep landscape size\n Display *dpy = QX11Info::display();\n int xres = ScreenOfDisplay(dpy, DefaultScreen(dpy))->width;\n int yres = ScreenOfDisplay(dpy, DefaultScreen(dpy))->height;\n scene()->setSceneRect(0, 0, xres, yres);\n setMinimumSize(xres, yres);\n setMaximumSize(xres, yres);\n}\n\nvoid MDecoratorWindow::setMDecoratorWindowProperty()\n{\n\n long on = 1;\n\n XChangeProperty(QX11Info::display(), winId(),\n XInternAtom(QX11Info::display(), \"_MEEGOTOUCH_DECORATOR_WINDOW\", False),\n XA_CARDINAL,\n 32, PropModeReplace,\n (unsigned char *) &on, 1);\n}\n\n\nconst QRect MDecoratorWindow::availableClientRect() const\n{\n return decoratorRect;\n}\n\nvoid MDecoratorWindow::closeEvent(QCloseEvent * event )\n{\n \/\/ never close the decorator!\n return event->ignore();\n}\n\n#include \"mdecoratorwindow.moc\"\n<|endoftext|>"} {"text":"#include \"Animation_Seasonal.hpp\"\n\n\/* ~~~ Animation Seasonal Spring: Clear Sky Blue Color Fade *\/\n\nAnimation_Seasonal_Spring_ClearSkyFade::Animation_Seasonal_Spring_ClearSkyFade(Adafruit_NeoPixel* strip) {\n\tthis->strip = strip;\n}\n\nvoid Animation_Seasonal_Spring_ClearSkyFade::init() {\n \tAnimation_Seasonal::init();\n\tthis->name = getNameOfStrip(this->strip);\n \tthis->name += F(\": Clear Skies\");\n\tthis->num_strips = 1;\n\tthis->update_rate = 50;\n\tthis->strips = getAsStripArray(this->strip);\n\n\tthis->stack = new LocalStack();\n\tthis->stack->push(new MemObj(new unsigned int(0)));\n\tthis->stack->push(new MemObj(new bool(true)));\n\tthis->stack->push(new MemObj(new unsigned short int(0)));\n\tthis->stack->push(new MemObj(new unsigned short int(0)));\n}\n\nvoid Animation_Seasonal_Spring_ClearSkyFade::step() {\n\tstatic const int MAX_RED = 200;\n\tstatic const int MAX_GREEN = 180;\n\tstatic const int BLUE = 255;\n\n\tunsigned int& i = this->stack->get(0)->get();\n\tbool& increasing = this->stack->get(1)->get();\n\tunsigned short int& red = this->stack->get(2)->get();\n\tunsigned short int& green = this->stack->get(3)->get();\n\n\t\/\/ step animation\n\tfor (unsigned int x = 0; x < this->strip->numPixels(); x++) {\n\t\tthis->strip->setPixelColor(x, MAX_RED - i, MAX_GREEN - i, BLUE);\n\t}\n\n\tif (increasing) {\n\t\tif (i >= 50) {\n\t\t\ti--;\n\t\t\tincreasing = false;\n\t\t} else {\n\t\t\ti++;\n\t\t}\n\t} else {\n\t\tif (i <= 0) {\n\t\t\ti++;\n\t\t\tincreasing = true;\n \t\tthis->current_exec++;\n\t\t} else {\n\t\t\ti--;\n\t\t}\n\t}\n\n}\n\nvoid Animation_Seasonal_Spring_ClearSkyFade::clean() {\n\tthis->stack->get(0)->destroy();\n\tthis->stack->get(1)->destroy();\n\tthis->stack->get(2)->destroy();\n\tthis->stack->get(3)->destroy();\n\n\tdelete this->stack;\n}\nshow() helps things actually work#include \"Animation_Seasonal.hpp\"\n\n\/* ~~~ Animation Seasonal Spring: Clear Sky Blue Color Fade *\/\n\nAnimation_Seasonal_Spring_ClearSkyFade::Animation_Seasonal_Spring_ClearSkyFade(Adafruit_NeoPixel* strip) {\n\tthis->strip = strip;\n}\n\nvoid Animation_Seasonal_Spring_ClearSkyFade::init() {\n \tAnimation_Seasonal::init();\n\tthis->name = getNameOfStrip(this->strip);\n \tthis->name += F(\": Clear Skies\");\n\tthis->num_strips = 1;\n\tthis->update_rate = 50;\n\tthis->strips = getAsStripArray(this->strip);\n\n\tthis->stack = new LocalStack();\n\tthis->stack->push(new MemObj(new unsigned int(0)));\n\tthis->stack->push(new MemObj(new bool(true)));\n\tthis->stack->push(new MemObj(new unsigned short int(0)));\n\tthis->stack->push(new MemObj(new unsigned short int(0)));\n}\n\nvoid Animation_Seasonal_Spring_ClearSkyFade::step() {\n\tstatic const int MAX_RED = 200;\n\tstatic const int MAX_GREEN = 180;\n\tstatic const int BLUE = 255;\n\n\tunsigned int& i = this->stack->get(0)->get();\n\tbool& increasing = this->stack->get(1)->get();\n\n\t\/\/ step animation\n\tfor (unsigned int x = 0; x < this->strip->numPixels(); x++) {\n\t\tthis->strip->setPixelColor(x, MAX_RED - i, MAX_GREEN - i, BLUE);\n\t}\n\n\tthis->strip->show();\n\n\tif (increasing) {\n\t\tif (i >= 150) {\n\t\t\ti--;\n\t\t\tincreasing = false;\n\t\t} else {\n\t\t\ti++;\n\t\t}\n\t} else {\n\t\tif (i <= 0) {\n\t\t\ti++;\n\t\t\tincreasing = true;\n \t\tthis->current_exec++;\n\t\t} else {\n\t\t\ti--;\n\t\t}\n\t}\n\n}\n\nvoid Animation_Seasonal_Spring_ClearSkyFade::clean() {\n\tthis->stack->get(0)->destroy();\n\tthis->stack->get(1)->destroy();\n\tthis->stack->get(2)->destroy();\n\tthis->stack->get(3)->destroy();\n\n\tdelete this->stack;\n}\n<|endoftext|>"} {"text":"\/*\n * filter_rbpitch.c -- adjust audio pitch\n * Copyright (C) 2020 Meltytech, LLC\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\nusing namespace RubberBand;\n\n\/\/ Private Types\ntypedef struct\n{\n\tRubberBandStretcher* s;\n\tint rubberband_frequency;\n\tuint64_t in_samples;\n\tuint64_t out_samples;\n} private_data;\n\nstatic const size_t MAX_CHANNELS = 10;\n\nstatic int rbpitch_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )\n{\n\tmlt_filter filter = static_cast(mlt_frame_pop_audio( frame ));\n\tmlt_properties filter_properties = MLT_FILTER_PROPERTIES(filter);\n\tprivate_data* pdata = (private_data*)filter->child;\n\tif ( *channels > (int)MAX_CHANNELS )\n\t{\n\t\tmlt_log_error( MLT_FILTER_SERVICE(filter), \"Too many channels requested: %d > %d\\n\", *channels, (int)MAX_CHANNELS );\n\t\treturn mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );\n\t}\n\n\tint requested_samples = *samples;\n\tmlt_properties unique_properties = mlt_frame_get_unique_properties( frame, MLT_FILTER_SERVICE(filter) );\n\tif ( !unique_properties )\n\t{\n\t\tmlt_log_error( MLT_FILTER_SERVICE(filter), \"Missing unique_properites\\n\" );\n\t\treturn mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );\n\t}\n\n\t\/\/ Get the producer's audio\n\t*format = mlt_audio_float;\n\tint error = mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );\n\tif ( error ) return error;\n\n\t\/\/ Make sure the audio is in the correct format\n\t\/\/ This is useful if the filter is encapsulated in a producer and does not\n\t\/\/ have a normalizing filter before it.\n\tif (*format != mlt_audio_float && frame->convert_audio != NULL)\n\t{\n\t\tframe->convert_audio( frame, buffer, format, mlt_audio_float );\n\t}\n\n\t\/\/ Sanity check parameters\n\t\/\/ rubberband library crashes have been seen with a very large scale factor\n\t\/\/ or very small sampling frequency. Very small scale factor and very high\n\t\/\/ sampling frequency can result in too much audio lag.\n\t\/\/ Disallow these extreme scenarios for now. Maybe it will be improved in\n\t\/\/ the future.\n\tdouble pitchscale = mlt_properties_get_double( unique_properties, \"pitchscale\" );\n\tpitchscale = CLAMP( pitchscale, 0.05, 50.0 );\n\tint rubberband_frequency = CLAMP( *frequency, 10000, 300000 );\n\n\t\/\/ Protect the RubberBandStretcher instance.\n\tmlt_service_lock( MLT_FILTER_SERVICE(filter) );\n\n\t\/\/ Configure the stretcher.\n\tRubberBandStretcher* s = pdata->s;\n\tif ( !s || s->available() == -1 || (int)s->getChannelCount() != *channels || pdata->rubberband_frequency != rubberband_frequency )\n\t{\n\t\tmlt_log_debug( MLT_FILTER_SERVICE(filter), \"Create a new stretcher\\t%d\\t%d\\t%f\\n\", *channels, rubberband_frequency, pitchscale );\n\t\tdelete s;\n\t\t\/\/ Create a rubberband instance\n\t\tRubberBandStretcher::Options options = RubberBandStretcher::OptionProcessRealTime;\n\t\ts = new RubberBandStretcher(rubberband_frequency, *channels, options, 1.0, pitchscale);\n\t\tpdata->s = s;\n\t\tpdata->rubberband_frequency = rubberband_frequency;\n\t\tpdata->in_samples = 0;\n\t\tpdata->out_samples = 0;\n\t}\n\ts->setPitchScale(pitchscale);\n\tif( pitchscale > 0.5 && pitchscale < 2.0 )\n\t{\n\t\t\/\/ Pitch adjustment < 200%\n\t\ts->setPitchOption(RubberBandStretcher::OptionPitchHighQuality);\n\t\ts->setTransientsOption(RubberBandStretcher::OptionTransientsCrisp);\n\t}\n\telse\n\t{\n\t\t\/\/ Pitch adjustment > 200%\n\t\t\/\/ \"HighConsistency\" and \"Smooth\" options help to avoid large memory\n\t\t\/\/ consumption and crashes that can occur for large pitch adjustments.\n\t\ts->setPitchOption(RubberBandStretcher::OptionPitchHighConsistency);\n\t\ts->setTransientsOption(RubberBandStretcher::OptionTransientsSmooth);\n\t}\n\n\t\/\/ Configure input and output buffers and counters.\n\tint consumed_samples = 0;\n\tint total_consumed_samples = 0;\n\tint received_samples = 0;\n\tstruct mlt_audio_s in;\n\tstruct mlt_audio_s out;\n\tmlt_audio_set_values( &in, *buffer, *frequency, *format, *samples, *channels );\n\tmlt_audio_set_values( &out, NULL, *frequency, *format, *samples, *channels );\n\tmlt_audio_alloc_data( &out );\n\n\t\/\/ Process all input samples\n\twhile ( true )\n\t{\n\t\t\/\/ Send more samples to the stretcher\n\t\tif ( consumed_samples == in.samples )\n\t\t{\n\t\t\t\/\/ Continue to repeat input samples into the stretcher until it\n\t\t\t\/\/ provides the desired number of samples out.\n\t\t\tconsumed_samples = 0;\n\t\t\tmlt_log_debug( MLT_FILTER_SERVICE(filter), \"Repeat samples\\n\");\n\t\t}\n\t\tint process_samples = std::min( in.samples - consumed_samples, (int)s->getSamplesRequired() );\n\t\tif ( process_samples == 0 && received_samples == out.samples && total_consumed_samples < in.samples )\n\t\t{\n\t\t\t\/\/ No more out samples are needed, but input samples are still available.\n\t\t\t\/\/ Send the final input samples for processing.\n\t\t\tprocess_samples = in.samples - total_consumed_samples;\n\t\t}\n\t\tif ( process_samples > 0 )\n\t\t{\n\t\t\tfloat* in_planes[MAX_CHANNELS];\n\t\t\tfor ( int i = 0; i < in.channels; i++ )\n\t\t\t{\n\t\t\t\tin_planes[i] = ((float*)in.data) + (in.samples * i) + consumed_samples;\n\t\t\t}\n\t\t\ts->process( in_planes, process_samples, false );\n\t\t\tconsumed_samples += process_samples;\n\t\t\ttotal_consumed_samples += process_samples;\n\t\t\tpdata->in_samples += process_samples;\n\t\t}\n\n\t\t\/\/ Receive samples from the stretcher\n\t\tint retrieve_samples = std::min( out.samples - received_samples, s->available() );\n\t\tif ( retrieve_samples > 0 )\n\t\t{\n\t\t\tfloat* out_planes[MAX_CHANNELS];\n\t\t\tfor ( int i = 0; i < out.channels; i++ )\n\t\t\t{\n\t\t\t\tout_planes[i] = ((float*)out.data) + (out.samples * i) + received_samples;\n\t\t\t}\n\t\t\tretrieve_samples = (int)s->retrieve( out_planes, retrieve_samples );\n\t\t\treceived_samples += retrieve_samples;\n\t\t\tpdata->out_samples += retrieve_samples;\n\t\t}\n\n\t\tmlt_log_debug( MLT_FILTER_SERVICE(filter), \"Process: %d\\t Retrieve: %d\\n\", process_samples, retrieve_samples );\n\n\t\tif ( received_samples == out.samples && total_consumed_samples >= in.samples )\n\t\t{\n\t\t\t\/\/ There is nothing more to do;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/\/ Save the processed samples.\n\tmlt_audio_shrink( &out, received_samples );\n\tmlt_frame_set_audio( frame, out.data, out.format, 0, out.release_data );\n\tmlt_audio_get_values( &out, buffer, frequency, format, samples, channels );\n\n\t\/\/ Report the latency.\n\tdouble latency = (double)(pdata->in_samples - pdata->out_samples) * 1000.0 \/ (double)*frequency;\n\tmlt_properties_set_double( filter_properties, \"latency\", latency );\n\n\tmlt_service_unlock( MLT_FILTER_SERVICE(filter) );\n\n\tmlt_log_debug( MLT_FILTER_SERVICE(filter), \"Requested: %d\\tReceived: %d\\tSent: %d\\tLatency: %d(%fms)\\n\", requested_samples, in.samples, out.samples, (int)(pdata->in_samples - pdata->out_samples), latency );\n\treturn error;\n}\n\nstatic mlt_frame filter_process( mlt_filter filter, mlt_frame frame )\n{\n\tmlt_properties filter_properties = MLT_FILTER_PROPERTIES( filter );\n\tmlt_position position = mlt_filter_get_position( filter, frame );\n\tmlt_position length = mlt_filter_get_length2( filter, frame );\n\n\t\/\/ Determine the pitchscale\n\tdouble pitchscale = 1.0;\n\tif ( mlt_properties_exists( filter_properties, \"pitchscale\" ) )\n\t{\n\t\tpitchscale = mlt_properties_anim_get_double( filter_properties, \"pitchscale\", position, length );\n\t}\n\telse\n\t{\n\t\tdouble octaveshift = mlt_properties_anim_get_double( filter_properties, \"octaveshift\", position, length );\n\t\tpitchscale = pow(2, octaveshift);\n\t}\n\tif ( pitchscale <= 0.0 || \/*check for nan:*\/pitchscale != pitchscale )\n\t{\n\t\tpitchscale = 1.0;\n\t}\n\n\t\/\/ Save the pitchscale on the frame to be used in rbpitch_get_audio\n\tmlt_properties unique_properties = mlt_frame_unique_properties( frame, MLT_FILTER_SERVICE(filter) );\n\tmlt_properties_set_double( unique_properties, \"pitchscale\", pitchscale );\n\n\tmlt_frame_push_audio( frame, (void*)filter );\n\tmlt_frame_push_audio( frame, (void*)rbpitch_get_audio );\n\n\treturn frame;\n}\n\nstatic void close_filter( mlt_filter filter )\n{\n\tprivate_data* pdata = (private_data*)filter->child;\n\tif ( pdata )\n\t{\n\t\tRubberBandStretcher* s = static_cast(pdata->s);\n\t\tif ( s )\n\t\t{\n\t\t\tdelete s;\n\t\t}\n\t\tfree( pdata );\n\t\tfilter->child = NULL;\n\t}\n}\n\nextern \"C\" {\n\nmlt_filter filter_rbpitch_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )\n{\n\tmlt_filter filter = mlt_filter_new();\n\tprivate_data* pdata = (private_data*)calloc( 1, sizeof(private_data) );\n\n\tif( filter && pdata )\n\t{\n\t\tpdata->s = NULL;\n\t\tpdata->rubberband_frequency = 0;\n\t\tpdata->in_samples = 0;\n\t\tpdata->out_samples = 0;\n\n\t\tfilter->process = filter_process;\n\t\tfilter->close = close_filter;\n\t\tfilter->child = pdata;\n\t}\n\telse\n\t{\n\t\tmlt_log_error( MLT_FILTER_SERVICE(filter), \"Failed to initialize\\n\" );\n\n\t\tif( filter )\n\t\t{\n\t\t\tmlt_filter_close( filter );\n\t\t}\n\n\t\tif( pdata )\n\t\t{\n\t\t\tfree( pdata );\n\t\t}\n\n\t\tfilter = NULL;\n\t}\n\treturn filter;\n}\n\n}\nInclude 0.5 and 2.0 in higher quality transient setting\/*\n * filter_rbpitch.c -- adjust audio pitch\n * Copyright (C) 2020 Meltytech, LLC\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\nusing namespace RubberBand;\n\n\/\/ Private Types\ntypedef struct\n{\n\tRubberBandStretcher* s;\n\tint rubberband_frequency;\n\tuint64_t in_samples;\n\tuint64_t out_samples;\n} private_data;\n\nstatic const size_t MAX_CHANNELS = 10;\n\nstatic int rbpitch_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )\n{\n\tmlt_filter filter = static_cast(mlt_frame_pop_audio( frame ));\n\tmlt_properties filter_properties = MLT_FILTER_PROPERTIES(filter);\n\tprivate_data* pdata = (private_data*)filter->child;\n\tif ( *channels > (int)MAX_CHANNELS )\n\t{\n\t\tmlt_log_error( MLT_FILTER_SERVICE(filter), \"Too many channels requested: %d > %d\\n\", *channels, (int)MAX_CHANNELS );\n\t\treturn mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );\n\t}\n\n\tint requested_samples = *samples;\n\tmlt_properties unique_properties = mlt_frame_get_unique_properties( frame, MLT_FILTER_SERVICE(filter) );\n\tif ( !unique_properties )\n\t{\n\t\tmlt_log_error( MLT_FILTER_SERVICE(filter), \"Missing unique_properites\\n\" );\n\t\treturn mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );\n\t}\n\n\t\/\/ Get the producer's audio\n\t*format = mlt_audio_float;\n\tint error = mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );\n\tif ( error ) return error;\n\n\t\/\/ Make sure the audio is in the correct format\n\t\/\/ This is useful if the filter is encapsulated in a producer and does not\n\t\/\/ have a normalizing filter before it.\n\tif (*format != mlt_audio_float && frame->convert_audio != NULL)\n\t{\n\t\tframe->convert_audio( frame, buffer, format, mlt_audio_float );\n\t}\n\n\t\/\/ Sanity check parameters\n\t\/\/ rubberband library crashes have been seen with a very large scale factor\n\t\/\/ or very small sampling frequency. Very small scale factor and very high\n\t\/\/ sampling frequency can result in too much audio lag.\n\t\/\/ Disallow these extreme scenarios for now. Maybe it will be improved in\n\t\/\/ the future.\n\tdouble pitchscale = mlt_properties_get_double( unique_properties, \"pitchscale\" );\n\tpitchscale = CLAMP( pitchscale, 0.05, 50.0 );\n\tint rubberband_frequency = CLAMP( *frequency, 10000, 300000 );\n\n\t\/\/ Protect the RubberBandStretcher instance.\n\tmlt_service_lock( MLT_FILTER_SERVICE(filter) );\n\n\t\/\/ Configure the stretcher.\n\tRubberBandStretcher* s = pdata->s;\n\tif ( !s || s->available() == -1 || (int)s->getChannelCount() != *channels || pdata->rubberband_frequency != rubberband_frequency )\n\t{\n\t\tmlt_log_debug( MLT_FILTER_SERVICE(filter), \"Create a new stretcher\\t%d\\t%d\\t%f\\n\", *channels, rubberband_frequency, pitchscale );\n\t\tdelete s;\n\t\t\/\/ Create a rubberband instance\n\t\tRubberBandStretcher::Options options = RubberBandStretcher::OptionProcessRealTime;\n\t\ts = new RubberBandStretcher(rubberband_frequency, *channels, options, 1.0, pitchscale);\n\t\tpdata->s = s;\n\t\tpdata->rubberband_frequency = rubberband_frequency;\n\t\tpdata->in_samples = 0;\n\t\tpdata->out_samples = 0;\n\t}\n\ts->setPitchScale(pitchscale);\n\tif( pitchscale >= 0.5 && pitchscale <= 2.0 )\n\t{\n\t\t\/\/ Pitch adjustment < 200%\n\t\ts->setPitchOption(RubberBandStretcher::OptionPitchHighQuality);\n\t\ts->setTransientsOption(RubberBandStretcher::OptionTransientsCrisp);\n\t}\n\telse\n\t{\n\t\t\/\/ Pitch adjustment > 200%\n\t\t\/\/ \"HighConsistency\" and \"Smooth\" options help to avoid large memory\n\t\t\/\/ consumption and crashes that can occur for large pitch adjustments.\n\t\ts->setPitchOption(RubberBandStretcher::OptionPitchHighConsistency);\n\t\ts->setTransientsOption(RubberBandStretcher::OptionTransientsSmooth);\n\t}\n\n\t\/\/ Configure input and output buffers and counters.\n\tint consumed_samples = 0;\n\tint total_consumed_samples = 0;\n\tint received_samples = 0;\n\tstruct mlt_audio_s in;\n\tstruct mlt_audio_s out;\n\tmlt_audio_set_values( &in, *buffer, *frequency, *format, *samples, *channels );\n\tmlt_audio_set_values( &out, NULL, *frequency, *format, *samples, *channels );\n\tmlt_audio_alloc_data( &out );\n\n\t\/\/ Process all input samples\n\twhile ( true )\n\t{\n\t\t\/\/ Send more samples to the stretcher\n\t\tif ( consumed_samples == in.samples )\n\t\t{\n\t\t\t\/\/ Continue to repeat input samples into the stretcher until it\n\t\t\t\/\/ provides the desired number of samples out.\n\t\t\tconsumed_samples = 0;\n\t\t\tmlt_log_debug( MLT_FILTER_SERVICE(filter), \"Repeat samples\\n\");\n\t\t}\n\t\tint process_samples = std::min( in.samples - consumed_samples, (int)s->getSamplesRequired() );\n\t\tif ( process_samples == 0 && received_samples == out.samples && total_consumed_samples < in.samples )\n\t\t{\n\t\t\t\/\/ No more out samples are needed, but input samples are still available.\n\t\t\t\/\/ Send the final input samples for processing.\n\t\t\tprocess_samples = in.samples - total_consumed_samples;\n\t\t}\n\t\tif ( process_samples > 0 )\n\t\t{\n\t\t\tfloat* in_planes[MAX_CHANNELS];\n\t\t\tfor ( int i = 0; i < in.channels; i++ )\n\t\t\t{\n\t\t\t\tin_planes[i] = ((float*)in.data) + (in.samples * i) + consumed_samples;\n\t\t\t}\n\t\t\ts->process( in_planes, process_samples, false );\n\t\t\tconsumed_samples += process_samples;\n\t\t\ttotal_consumed_samples += process_samples;\n\t\t\tpdata->in_samples += process_samples;\n\t\t}\n\n\t\t\/\/ Receive samples from the stretcher\n\t\tint retrieve_samples = std::min( out.samples - received_samples, s->available() );\n\t\tif ( retrieve_samples > 0 )\n\t\t{\n\t\t\tfloat* out_planes[MAX_CHANNELS];\n\t\t\tfor ( int i = 0; i < out.channels; i++ )\n\t\t\t{\n\t\t\t\tout_planes[i] = ((float*)out.data) + (out.samples * i) + received_samples;\n\t\t\t}\n\t\t\tretrieve_samples = (int)s->retrieve( out_planes, retrieve_samples );\n\t\t\treceived_samples += retrieve_samples;\n\t\t\tpdata->out_samples += retrieve_samples;\n\t\t}\n\n\t\tmlt_log_debug( MLT_FILTER_SERVICE(filter), \"Process: %d\\t Retrieve: %d\\n\", process_samples, retrieve_samples );\n\n\t\tif ( received_samples == out.samples && total_consumed_samples >= in.samples )\n\t\t{\n\t\t\t\/\/ There is nothing more to do;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/\/ Save the processed samples.\n\tmlt_audio_shrink( &out, received_samples );\n\tmlt_frame_set_audio( frame, out.data, out.format, 0, out.release_data );\n\tmlt_audio_get_values( &out, buffer, frequency, format, samples, channels );\n\n\t\/\/ Report the latency.\n\tdouble latency = (double)(pdata->in_samples - pdata->out_samples) * 1000.0 \/ (double)*frequency;\n\tmlt_properties_set_double( filter_properties, \"latency\", latency );\n\n\tmlt_service_unlock( MLT_FILTER_SERVICE(filter) );\n\n\tmlt_log_debug( MLT_FILTER_SERVICE(filter), \"Requested: %d\\tReceived: %d\\tSent: %d\\tLatency: %d(%fms)\\n\", requested_samples, in.samples, out.samples, (int)(pdata->in_samples - pdata->out_samples), latency );\n\treturn error;\n}\n\nstatic mlt_frame filter_process( mlt_filter filter, mlt_frame frame )\n{\n\tmlt_properties filter_properties = MLT_FILTER_PROPERTIES( filter );\n\tmlt_position position = mlt_filter_get_position( filter, frame );\n\tmlt_position length = mlt_filter_get_length2( filter, frame );\n\n\t\/\/ Determine the pitchscale\n\tdouble pitchscale = 1.0;\n\tif ( mlt_properties_exists( filter_properties, \"pitchscale\" ) )\n\t{\n\t\tpitchscale = mlt_properties_anim_get_double( filter_properties, \"pitchscale\", position, length );\n\t}\n\telse\n\t{\n\t\tdouble octaveshift = mlt_properties_anim_get_double( filter_properties, \"octaveshift\", position, length );\n\t\tpitchscale = pow(2, octaveshift);\n\t}\n\tif ( pitchscale <= 0.0 || \/*check for nan:*\/pitchscale != pitchscale )\n\t{\n\t\tpitchscale = 1.0;\n\t}\n\n\t\/\/ Save the pitchscale on the frame to be used in rbpitch_get_audio\n\tmlt_properties unique_properties = mlt_frame_unique_properties( frame, MLT_FILTER_SERVICE(filter) );\n\tmlt_properties_set_double( unique_properties, \"pitchscale\", pitchscale );\n\n\tmlt_frame_push_audio( frame, (void*)filter );\n\tmlt_frame_push_audio( frame, (void*)rbpitch_get_audio );\n\n\treturn frame;\n}\n\nstatic void close_filter( mlt_filter filter )\n{\n\tprivate_data* pdata = (private_data*)filter->child;\n\tif ( pdata )\n\t{\n\t\tRubberBandStretcher* s = static_cast(pdata->s);\n\t\tif ( s )\n\t\t{\n\t\t\tdelete s;\n\t\t}\n\t\tfree( pdata );\n\t\tfilter->child = NULL;\n\t}\n}\n\nextern \"C\" {\n\nmlt_filter filter_rbpitch_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )\n{\n\tmlt_filter filter = mlt_filter_new();\n\tprivate_data* pdata = (private_data*)calloc( 1, sizeof(private_data) );\n\n\tif( filter && pdata )\n\t{\n\t\tpdata->s = NULL;\n\t\tpdata->rubberband_frequency = 0;\n\t\tpdata->in_samples = 0;\n\t\tpdata->out_samples = 0;\n\n\t\tfilter->process = filter_process;\n\t\tfilter->close = close_filter;\n\t\tfilter->child = pdata;\n\t}\n\telse\n\t{\n\t\tmlt_log_error( MLT_FILTER_SERVICE(filter), \"Failed to initialize\\n\" );\n\n\t\tif( filter )\n\t\t{\n\t\t\tmlt_filter_close( filter );\n\t\t}\n\n\t\tif( pdata )\n\t\t{\n\t\t\tfree( pdata );\n\t\t}\n\n\t\tfilter = NULL;\n\t}\n\treturn filter;\n}\n\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved\n *\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#if qPlatform_Windows\n#include \n#include \n#include \n#elif qPlatform_POSIX\n#include \n#endif\n\n#include \"..\/..\/Characters\/StringBuilder.h\"\n#include \"..\/..\/Containers\/Set.h\"\n#if qPlatform_Windows\n#include \"..\/..\/Execution\/Platform\/Windows\/Exception.h\"\n#include \"..\/..\/Execution\/Platform\/Windows\/HRESULTErrorException.h\"\n#endif\n#include \"..\/..\/Execution\/ErrNoException.h\"\n\n#include \"..\/..\/IO\/FileAccessException.h\"\n#include \"..\/..\/IO\/FileBusyException.h\"\n#include \"..\/..\/IO\/FileFormatException.h\"\n#include \"..\/..\/Memory\/SmallStackBuffer.h\"\n\n#include \"FileUtils.h\"\n\n#include \"FileSystem.h\"\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::Containers;\nusing namespace Stroika::Foundation::Execution;\nusing namespace Stroika::Foundation::IO;\nusing namespace Stroika::Foundation::IO::FileSystem;\n\n\n#if qPlatform_Windows\nusing Execution::Platform::Windows::ThrowIfFalseGetLastError;\nusing Execution::Platform::Windows::ThrowIfZeroGetLastError;\n#endif\n\n\n\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n\n\n\n\n\n\/*\n ********************************************************************************\n **************************** FileSystem::FileSystem ****************************\n ********************************************************************************\n *\/\nIO::FileSystem::FileSystem IO::FileSystem::FileSystem::Default ()\n{\n static IO::FileSystem::FileSystem sThe_;\n return sThe_;\n}\n\nbool IO::FileSystem::FileSystem::Access (const String& fileFullPath, FileAccessMode accessMode) const\n{\n#if qPlatform_Windows\n if ((accessMode & FileAccessMode::eRead) == FileAccessMode::eRead) {\n DWORD attribs = ::GetFileAttributesW (fileFullPath.c_str ());\n if (attribs == INVALID_FILE_ATTRIBUTES) {\n return false;\n }\n }\n if ((accessMode & FileAccessMode::eWrite) == FileAccessMode::eWrite) {\n DWORD attribs = ::GetFileAttributesW (fileFullPath.c_str ());\n if ((attribs == INVALID_FILE_ATTRIBUTES) or (attribs & FILE_ATTRIBUTE_READONLY)) {\n return false;\n }\n }\n return true;\n#elif qPlatform_POSIX\n \/\/ Not REALLY right - but an OK hack for now... -- LGP 2011-09-26\n \/\/http:\/\/linux.die.net\/man\/2\/access\n if ((accessMode & FileAccessMode::eRead) == FileAccessMode::eRead) {\n if (access (fileFullPath.AsSDKString().c_str (), R_OK) != 0) {\n return false;\n }\n }\n if ((accessMode & FileAccessMode::eWrite) == FileAccessMode::eWrite) {\n if (access (fileFullPath.AsSDKString().c_str (), W_OK) != 0) {\n return false;\n }\n }\n return true;\n#else\n AssertNotImplemented ();\n return false;\n#endif\n}\n\nvoid IO::FileSystem::FileSystem::CheckAccess (const String& fileFullPath, FileAccessMode accessMode)\n{\n \/\/ quick hack - not fully implemented - but since advsiory only - not too important...\n\n if (not Access (fileFullPath, accessMode)) {\n \/\/ FOR NOW - MIMIC OLD CODE - BUT FIX TO CHECK READ AND WRITE (AND BOTH) ACCESS DEPENDING ON ARGS) -- LGP 2009-08-15\n Execution::DoThrow (FileAccessException (fileFullPath, accessMode));\n }\n}\n\nvoid IO::FileSystem::FileSystem::CheckFileAccess (const String& fileFullPath, bool checkCanRead, bool checkCanWrite)\n{\n if (checkCanRead and checkCanWrite) {\n CheckAccess (fileFullPath, IO::FileAccessMode::eReadWrite);\n }\n else if (checkCanRead) {\n CheckAccess (fileFullPath, IO::FileAccessMode::eRead);\n }\n else if (checkCanWrite) {\n CheckAccess (fileFullPath, IO::FileAccessMode::eWrite);\n }\n}\n\nString IO::FileSystem::FileSystem::ResolveShortcut (const String& path2FileOrShortcut)\n{\n#if qPlatform_Windows\n \/\/ @todo WRONG semantics if file doesnt exist. Wed should raise an exception here.\n \/\/ But OK if not a shortcut. THEN just rutn the givne file\n \/\/\n \/\/\n \/\/ NB: this requires COM, and for now - I don't want the support module depending on the COM module,\n \/\/ so just allow this to fail if COM isn't initialized.\n \/\/ -- LGP 2007-09-23\n \/\/\n {\n SHFILEINFO info;\n memset (&info, 0, sizeof (info));\n if (::SHGetFileInfo (path2FileOrShortcut.AsSDKString ().c_str (), 0, &info, sizeof (info), SHGFI_ATTRIBUTES) == 0)\n {\n return path2FileOrShortcut;\n }\n \/\/ not a shortcut?\n if (!(info.dwAttributes & SFGAO_LINK))\n {\n return path2FileOrShortcut;\n }\n }\n\n \/\/ obtain the IShellLink interface\n IShellLink* psl = nullptr;\n IPersistFile* ppf = nullptr;\n try {\n if (FAILED (::CoCreateInstance (CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl))) {\n return path2FileOrShortcut;\n }\n if (SUCCEEDED (psl->QueryInterface (IID_IPersistFile, (LPVOID*)&ppf))) {\n if (SUCCEEDED (ppf->Load (path2FileOrShortcut.c_str (), STGM_READ))) {\n \/\/ Resolve the link, this may post UI to find the link\n if (SUCCEEDED (psl->Resolve(0, SLR_NO_UI))) {\n TCHAR path[MAX_PATH + 1];\n memset (path, 0, sizeof (path));\n if (SUCCEEDED (psl->GetPath (path, NEltsOf (path), nullptr, 0))) {\n ppf->Release ();\n ppf = nullptr;\n psl->Release ();\n psl = nullptr;\n return String::FromSDKString (path);\n }\n }\n }\n }\n }\n catch (...) {\n if (ppf != nullptr) {\n ppf->Release ();\n }\n if (psl != nullptr) {\n psl->Release ();\n }\n Execution::DoReThrow ();\n }\n if (ppf != nullptr) {\n ppf->Release ();\n }\n if (psl != nullptr) {\n psl->Release ();\n }\n return path2FileOrShortcut;\n#else\n Memory::SmallStackBuffer buf (1024);\n ssize_t n;\n while ( (n = ::readlink (path2FileOrShortcut.AsSDKString ().c_str (), buf, buf.GetSize ())) == buf.GetSize ()) {\n buf.GrowToSize (buf.GetSize () * 2);\n }\n if (n < 0) {\n auto e = errno;\n if (e == EINVAL) {\n \/\/ According to http:\/\/linux.die.net\/man\/2\/readlink - this means the target is not a shortcut which is OK\n return path2FileOrShortcut;\n }\n else {\n Execution::errno_ErrorException::DoThrow (e);\n }\n }\n Assert (n <= buf.GetSize ()); \/\/ could leave no room for NUL-byte, but not needed\n constexpr bool kWorkaroundBuggyCentos5ReturnsNulBytesInBuf_ = true;\n if (kWorkaroundBuggyCentos5ReturnsNulBytesInBuf_) {\n const Characters::SDKChar* b = buf.begin ();\n const Characters::SDKChar* e = b + n;\n const Characters::SDKChar* i = find (b, e, '\\0');\n if (i != e) {\n size_t newN = i - buf.begin ();\n Assert (newN < n);\n n = newN;\n }\n }\n return String::FromSDKString (SDKString (buf.begin (), buf.begin () + n));\n#endif\n}\n\nString IO::FileSystem::FileSystem::CanonicalizeName (const String& path2FileOrShortcut, bool throwIfComponentsNotFound)\n{\n#if qPlatform_POSIX\n \/\/ We used to call canonicalize_file_name() - but this doesnt work with AIX 7.1\/g++4.9.2, and\n \/\/ according to http:\/\/man7.org\/linux\/man-pages\/man3\/canonicalize_file_name.3.html:\n \/\/ The call canonicalize_file_name(path) is equivalent to the call:\n \/\/ realpath(path, NULL)\n char* tmp { ::realpath (path2FileOrShortcut.AsSDKString ().c_str (), nullptr) };\n if (tmp == nullptr) {\n errno_ErrorException::DoThrow (errno);\n }\n String result { String::FromNarrowSDKString (tmp) };\n free (tmp);\n return result;\n#elif qPlatform_Windows\n\n \/\/ @todo LARGELY UNSTED ROUGH DRAFT - 2015-05-11\n \/*\n * Note: PathCanonicalize has lots of problems, PathCanonicalizeCh, and\n * PathCchCanonicalizeEx is better, but only works with windows 8 or later.\n *\/\n using Characters::StringBuilder;\n String tmp = ResolveShortcut (path2FileOrShortcut);\n StringBuilder sb;\n Components c = GetPathComponents (path2FileOrShortcut);\n if (c.fAbsolutePath == Components::eAbsolutePath) {\n \/\/ use UNC notation\n sb += L\"\\\\\\\\?\";\n if (c.fDriveLetter) {\n sb += *c.fDriveLetter;\n }\n else if (c.fServerAndShare) {\n sb += c.fServerAndShare->fServer + L\"\\\\\" + c.fServerAndShare->fShare;\n }\n else {\n Execution::DoThrow (Execution::StringException (L\"for absolute path need drive letter or server\/share\"));\n }\n }\n else {\n if (c.fDriveLetter) {\n sb += *c.fDriveLetter + L\":\";\n }\n }\n bool prefixWIthSlash = false;\n for (String i : c.fPath) {\n if (prefixWIthSlash) {\n sb += L\"\\\\\";\n }\n sb += i;\n prefixWIthSlash = true;\n }\n return sb.str ();\n#else\n AssertNotImplemented ();\n return path2FileOrShortcut;\n#endif\n}\n\nString IO::FileSystem::FileSystem::CanonicalizeName (const String& path2FileOrShortcut, const String& relativeToDirectory, bool throwIfComponentsNotFound)\n{\n AssertNotImplemented ();\n return path2FileOrShortcut;\n}\n\nIO::FileSystem::FileSystem::Components IO::FileSystem::FileSystem::GetPathComponents (const String& fileName)\n{\n \/\/ @todo LARGELY UNSTED ROUGH DRAFT - 2015-05-11\n \/\/ See http:\/\/en.wikipedia.org\/wiki\/Path_%28computing%29 to write this\n#if 0\n\/\/windows\nC:\n \\user\\docs\\Letter.txt\n \/ user \/ docs \/ Letter.txt\nC:\n Letter.txt\n \\\\Server01\\user\\docs\\Letter.txt\n \\\\ ? \\UNC\\Server01\\user\\docs\\Letter.txt\n \\\\ ? \\C : \\user\\docs\\Letter.txt\n C : \\user\\docs\\somefile.ext : alternate_stream_name\n . \/ inthisdir\n .. \/ .. \/ greatgrandparent\n#endif\n#if 0\n\/\/ unix\n \/ home \/ user \/ docs \/ Letter.txt\n . \/ inthisdir\n .. \/ .. \/ greatgrandparent\n ~ \/ .rcinfo\n#endif\n IO::FileSystem::FileSystem::Components result;\n using Traversal::Iterator;\n using Characters::Character;\n\n#if qPlatform_Windows\n bool isUNCName = fileName.length () > 2 and fileName.StartsWith (L\"\\\\\\\\\");\n bool isAbsolutePath = fileName.length () >= 1 and fileName.StartsWith (L\"\\\\\");\n#else\n#endif\n#if qPlatform_Windows\n const Set kSlashChars_ = { '\\\\', '\/' };\n#else\n const Set kSlashChars_ = { '\/' };\n#endif\n Sequence rawComponents = fileName.Tokenize (kSlashChars_, false);\n Iterator i = rawComponents.begin ();\n#if qPlatform_Windows\n if (isUNCName) {\n \/\/ work todo\n }\n#endif\n for (; i != rawComponents.end (); ++i) {\n result.fPath.Append (*i);\n }\n AssertNotImplemented ();\n return result;\n}\n\nFileOffset_t IO::FileSystem::FileSystem::GetFileSize (const String& fileName)\n{\n#if qPlatform_Windows\n WIN32_FILE_ATTRIBUTE_DATA fileAttrData;\n (void)::memset (&fileAttrData, 0, sizeof (fileAttrData));\n Execution::Platform::Windows::ThrowIfFalseGetLastError (::GetFileAttributesExW (fileName.c_str (), GetFileExInfoStandard, &fileAttrData));\n return fileAttrData.nFileSizeLow + (static_cast (fileAttrData.nFileSizeHigh) << 32);\n#else\n AssertNotImplemented ();\n return 0;\n#endif\n}\n\nDateTime IO::FileSystem::FileSystem::GetFileLastModificationDate (const String& fileName)\n{\n#if qPlatform_Windows\n WIN32_FILE_ATTRIBUTE_DATA fileAttrData;\n (void)::memset (&fileAttrData, 0, sizeof (fileAttrData));\n ThrowIfFalseGetLastError (::GetFileAttributesExW (fileName.c_str (), GetFileExInfoStandard, &fileAttrData));\n return DateTime (fileAttrData.ftLastWriteTime);\n#else\n AssertNotImplemented ();\n return DateTime ();\n#endif\n}\n\nDateTime IO::FileSystem::FileSystem::GetFileLastAccessDate (const String& fileName)\n{\n#if qPlatform_Windows\n WIN32_FILE_ATTRIBUTE_DATA fileAttrData;\n (void)::memset (&fileAttrData, 0, sizeof (fileAttrData));\n ThrowIfFalseGetLastError (::GetFileAttributesExW (fileName.c_str (), GetFileExInfoStandard, &fileAttrData));\n return DateTime (fileAttrData.ftLastAccessTime);\n#else\n AssertNotImplemented ();\n return DateTime ();\n#endif\n}\n\nvoid IO::FileSystem::FileSystem::RemoveFile (const String& fileName)\n{\n#if qPlatform_Windows && qTargetPlatformSDKUseswchar_t\n Execution::ThrowErrNoIfNegative (::_wunlink (fileName.c_str ()));\n#else\n Execution::ThrowErrNoIfNegative (::unlink (fileName.AsNarrowSDKString ().c_str ()));\n#endif\n}\n\nvoid IO::FileSystem::FileSystem::RemoveFileIf (const String& fileName)\n{\n#if qPlatform_Windows && qTargetPlatformSDKUseswchar_t\n int r = ::_wunlink (fileName.c_str ());\n#else\n int r = ::unlink (fileName.AsNarrowSDKString ().c_str ());\n#endif\n if (r < 0) {\n if (errno != ENOENT) {\n errno_ErrorException::DoThrow (errno);\n }\n }\n}\n\nString IO::FileSystem::FileSystem::GetCurrentDirectory () const\n{\n#if qPlatform_POSIX\n SDKChar buf[MAX_PATH];\n Execution::ThrowErrNoIfNull (::getcwd (buf, NEltsOf (buf)));\n return String::FromSDKString (buf);\n#elif qPlatform_Windows\n SDKChar buf[MAX_PATH];\n ThrowIfZeroGetLastError (::GetCurrentDirectory (MAX_PATH, buf));\n return String::FromSDKString (buf);\n#else\n#endif\n}\n\nvoid IO::FileSystem::FileSystem::SetCurrentDirectory (const String& newDir)\n{\n#if qPlatform_POSIX\n Execution::ThrowErrNoIfNegative (::chdir (newDir.AsNarrowSDKString ().c_str ()));\n#elif qPlatform_Windows\n ::SetCurrentDirectory(newDir.AsSDKString ().c_str ());\n#else\n#endif\n}\nPOSIX typo\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved\n *\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#if qPlatform_Windows\n#include \n#include \n#include \n#elif qPlatform_POSIX\n#include \n#endif\n\n#include \"..\/..\/Characters\/StringBuilder.h\"\n#include \"..\/..\/Containers\/Set.h\"\n#if qPlatform_Windows\n#include \"..\/..\/Execution\/Platform\/Windows\/Exception.h\"\n#include \"..\/..\/Execution\/Platform\/Windows\/HRESULTErrorException.h\"\n#endif\n#include \"..\/..\/Execution\/ErrNoException.h\"\n\n#include \"..\/..\/IO\/FileAccessException.h\"\n#include \"..\/..\/IO\/FileBusyException.h\"\n#include \"..\/..\/IO\/FileFormatException.h\"\n#include \"..\/..\/Memory\/SmallStackBuffer.h\"\n\n#include \"FileUtils.h\"\n\n#include \"FileSystem.h\"\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::Containers;\nusing namespace Stroika::Foundation::Execution;\nusing namespace Stroika::Foundation::IO;\nusing namespace Stroika::Foundation::IO::FileSystem;\n\n\n#if qPlatform_Windows\nusing Execution::Platform::Windows::ThrowIfFalseGetLastError;\nusing Execution::Platform::Windows::ThrowIfZeroGetLastError;\n#endif\n\n\n\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n\n\n\n\n\n\/*\n ********************************************************************************\n **************************** FileSystem::FileSystem ****************************\n ********************************************************************************\n *\/\nIO::FileSystem::FileSystem IO::FileSystem::FileSystem::Default ()\n{\n static IO::FileSystem::FileSystem sThe_;\n return sThe_;\n}\n\nbool IO::FileSystem::FileSystem::Access (const String& fileFullPath, FileAccessMode accessMode) const\n{\n#if qPlatform_Windows\n if ((accessMode & FileAccessMode::eRead) == FileAccessMode::eRead) {\n DWORD attribs = ::GetFileAttributesW (fileFullPath.c_str ());\n if (attribs == INVALID_FILE_ATTRIBUTES) {\n return false;\n }\n }\n if ((accessMode & FileAccessMode::eWrite) == FileAccessMode::eWrite) {\n DWORD attribs = ::GetFileAttributesW (fileFullPath.c_str ());\n if ((attribs == INVALID_FILE_ATTRIBUTES) or (attribs & FILE_ATTRIBUTE_READONLY)) {\n return false;\n }\n }\n return true;\n#elif qPlatform_POSIX\n \/\/ Not REALLY right - but an OK hack for now... -- LGP 2011-09-26\n \/\/http:\/\/linux.die.net\/man\/2\/access\n if ((accessMode & FileAccessMode::eRead) == FileAccessMode::eRead) {\n if (access (fileFullPath.AsSDKString().c_str (), R_OK) != 0) {\n return false;\n }\n }\n if ((accessMode & FileAccessMode::eWrite) == FileAccessMode::eWrite) {\n if (access (fileFullPath.AsSDKString().c_str (), W_OK) != 0) {\n return false;\n }\n }\n return true;\n#else\n AssertNotImplemented ();\n return false;\n#endif\n}\n\nvoid IO::FileSystem::FileSystem::CheckAccess (const String& fileFullPath, FileAccessMode accessMode)\n{\n \/\/ quick hack - not fully implemented - but since advsiory only - not too important...\n\n if (not Access (fileFullPath, accessMode)) {\n \/\/ FOR NOW - MIMIC OLD CODE - BUT FIX TO CHECK READ AND WRITE (AND BOTH) ACCESS DEPENDING ON ARGS) -- LGP 2009-08-15\n Execution::DoThrow (FileAccessException (fileFullPath, accessMode));\n }\n}\n\nvoid IO::FileSystem::FileSystem::CheckFileAccess (const String& fileFullPath, bool checkCanRead, bool checkCanWrite)\n{\n if (checkCanRead and checkCanWrite) {\n CheckAccess (fileFullPath, IO::FileAccessMode::eReadWrite);\n }\n else if (checkCanRead) {\n CheckAccess (fileFullPath, IO::FileAccessMode::eRead);\n }\n else if (checkCanWrite) {\n CheckAccess (fileFullPath, IO::FileAccessMode::eWrite);\n }\n}\n\nString IO::FileSystem::FileSystem::ResolveShortcut (const String& path2FileOrShortcut)\n{\n#if qPlatform_Windows\n \/\/ @todo WRONG semantics if file doesnt exist. Wed should raise an exception here.\n \/\/ But OK if not a shortcut. THEN just rutn the givne file\n \/\/\n \/\/\n \/\/ NB: this requires COM, and for now - I don't want the support module depending on the COM module,\n \/\/ so just allow this to fail if COM isn't initialized.\n \/\/ -- LGP 2007-09-23\n \/\/\n {\n SHFILEINFO info;\n memset (&info, 0, sizeof (info));\n if (::SHGetFileInfo (path2FileOrShortcut.AsSDKString ().c_str (), 0, &info, sizeof (info), SHGFI_ATTRIBUTES) == 0)\n {\n return path2FileOrShortcut;\n }\n \/\/ not a shortcut?\n if (!(info.dwAttributes & SFGAO_LINK))\n {\n return path2FileOrShortcut;\n }\n }\n\n \/\/ obtain the IShellLink interface\n IShellLink* psl = nullptr;\n IPersistFile* ppf = nullptr;\n try {\n if (FAILED (::CoCreateInstance (CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl))) {\n return path2FileOrShortcut;\n }\n if (SUCCEEDED (psl->QueryInterface (IID_IPersistFile, (LPVOID*)&ppf))) {\n if (SUCCEEDED (ppf->Load (path2FileOrShortcut.c_str (), STGM_READ))) {\n \/\/ Resolve the link, this may post UI to find the link\n if (SUCCEEDED (psl->Resolve(0, SLR_NO_UI))) {\n TCHAR path[MAX_PATH + 1];\n memset (path, 0, sizeof (path));\n if (SUCCEEDED (psl->GetPath (path, NEltsOf (path), nullptr, 0))) {\n ppf->Release ();\n ppf = nullptr;\n psl->Release ();\n psl = nullptr;\n return String::FromSDKString (path);\n }\n }\n }\n }\n }\n catch (...) {\n if (ppf != nullptr) {\n ppf->Release ();\n }\n if (psl != nullptr) {\n psl->Release ();\n }\n Execution::DoReThrow ();\n }\n if (ppf != nullptr) {\n ppf->Release ();\n }\n if (psl != nullptr) {\n psl->Release ();\n }\n return path2FileOrShortcut;\n#else\n Memory::SmallStackBuffer buf (1024);\n ssize_t n;\n while ( (n = ::readlink (path2FileOrShortcut.AsSDKString ().c_str (), buf, buf.GetSize ())) == buf.GetSize ()) {\n buf.GrowToSize (buf.GetSize () * 2);\n }\n if (n < 0) {\n auto e = errno;\n if (e == EINVAL) {\n \/\/ According to http:\/\/linux.die.net\/man\/2\/readlink - this means the target is not a shortcut which is OK\n return path2FileOrShortcut;\n }\n else {\n Execution::errno_ErrorException::DoThrow (e);\n }\n }\n Assert (n <= buf.GetSize ()); \/\/ could leave no room for NUL-byte, but not needed\n constexpr bool kWorkaroundBuggyCentos5ReturnsNulBytesInBuf_ = true;\n if (kWorkaroundBuggyCentos5ReturnsNulBytesInBuf_) {\n const Characters::SDKChar* b = buf.begin ();\n const Characters::SDKChar* e = b + n;\n const Characters::SDKChar* i = find (b, e, '\\0');\n if (i != e) {\n size_t newN = i - buf.begin ();\n Assert (newN < n);\n n = newN;\n }\n }\n return String::FromSDKString (SDKString (buf.begin (), buf.begin () + n));\n#endif\n}\n\nString IO::FileSystem::FileSystem::CanonicalizeName (const String& path2FileOrShortcut, bool throwIfComponentsNotFound)\n{\n#if qPlatform_POSIX\n \/\/ We used to call canonicalize_file_name() - but this doesnt work with AIX 7.1\/g++4.9.2, and\n \/\/ according to http:\/\/man7.org\/linux\/man-pages\/man3\/canonicalize_file_name.3.html:\n \/\/ The call canonicalize_file_name(path) is equivalent to the call:\n \/\/ realpath(path, NULL)\n char* tmp { ::realpath (path2FileOrShortcut.AsSDKString ().c_str (), nullptr) };\n if (tmp == nullptr) {\n errno_ErrorException::DoThrow (errno);\n }\n String result { String::FromNarrowSDKString (tmp) };\n free (tmp);\n return result;\n#elif qPlatform_Windows\n\n \/\/ @todo LARGELY UNSTED ROUGH DRAFT - 2015-05-11\n \/*\n * Note: PathCanonicalize has lots of problems, PathCanonicalizeCh, and\n * PathCchCanonicalizeEx is better, but only works with windows 8 or later.\n *\/\n using Characters::StringBuilder;\n String tmp = ResolveShortcut (path2FileOrShortcut);\n StringBuilder sb;\n Components c = GetPathComponents (path2FileOrShortcut);\n if (c.fAbsolutePath == Components::eAbsolutePath) {\n \/\/ use UNC notation\n sb += L\"\\\\\\\\?\";\n if (c.fDriveLetter) {\n sb += *c.fDriveLetter;\n }\n else if (c.fServerAndShare) {\n sb += c.fServerAndShare->fServer + L\"\\\\\" + c.fServerAndShare->fShare;\n }\n else {\n Execution::DoThrow (Execution::StringException (L\"for absolute path need drive letter or server\/share\"));\n }\n }\n else {\n if (c.fDriveLetter) {\n sb += *c.fDriveLetter + L\":\";\n }\n }\n bool prefixWIthSlash = false;\n for (String i : c.fPath) {\n if (prefixWIthSlash) {\n sb += L\"\\\\\";\n }\n sb += i;\n prefixWIthSlash = true;\n }\n return sb.str ();\n#else\n AssertNotImplemented ();\n return path2FileOrShortcut;\n#endif\n}\n\nString IO::FileSystem::FileSystem::CanonicalizeName (const String& path2FileOrShortcut, const String& relativeToDirectory, bool throwIfComponentsNotFound)\n{\n AssertNotImplemented ();\n return path2FileOrShortcut;\n}\n\nIO::FileSystem::FileSystem::Components IO::FileSystem::FileSystem::GetPathComponents (const String& fileName)\n{\n \/\/ @todo LARGELY UNSTED ROUGH DRAFT - 2015-05-11\n \/\/ See http:\/\/en.wikipedia.org\/wiki\/Path_%28computing%29 to write this\n#if 0\n\/\/windows\nC:\n \\user\\docs\\Letter.txt\n \/ user \/ docs \/ Letter.txt\nC:\n Letter.txt\n \\\\Server01\\user\\docs\\Letter.txt\n \\\\ ? \\UNC\\Server01\\user\\docs\\Letter.txt\n \\\\ ? \\C : \\user\\docs\\Letter.txt\n C : \\user\\docs\\somefile.ext : alternate_stream_name\n . \/ inthisdir\n .. \/ .. \/ greatgrandparent\n#endif\n#if 0\n\/\/ unix\n \/ home \/ user \/ docs \/ Letter.txt\n . \/ inthisdir\n .. \/ .. \/ greatgrandparent\n ~ \/ .rcinfo\n#endif\n IO::FileSystem::FileSystem::Components result;\n using Traversal::Iterator;\n using Characters::Character;\n\n#if qPlatform_Windows\n bool isUNCName = fileName.length () > 2 and fileName.StartsWith (L\"\\\\\\\\\");\n bool isAbsolutePath = fileName.length () >= 1 and fileName.StartsWith (L\"\\\\\");\n#else\n#endif\n#if qPlatform_Windows\n const Set kSlashChars_ = { '\\\\', '\/' };\n#else\n const Set kSlashChars_ = { '\/' };\n#endif\n Sequence rawComponents = fileName.Tokenize (kSlashChars_, false);\n Iterator i = rawComponents.begin ();\n#if qPlatform_Windows\n if (isUNCName) {\n \/\/ work todo\n }\n#endif\n for (; i != rawComponents.end (); ++i) {\n result.fPath.Append (*i);\n }\n AssertNotImplemented ();\n return result;\n}\n\nFileOffset_t IO::FileSystem::FileSystem::GetFileSize (const String& fileName)\n{\n#if qPlatform_Windows\n WIN32_FILE_ATTRIBUTE_DATA fileAttrData;\n (void)::memset (&fileAttrData, 0, sizeof (fileAttrData));\n Execution::Platform::Windows::ThrowIfFalseGetLastError (::GetFileAttributesExW (fileName.c_str (), GetFileExInfoStandard, &fileAttrData));\n return fileAttrData.nFileSizeLow + (static_cast (fileAttrData.nFileSizeHigh) << 32);\n#else\n AssertNotImplemented ();\n return 0;\n#endif\n}\n\nDateTime IO::FileSystem::FileSystem::GetFileLastModificationDate (const String& fileName)\n{\n#if qPlatform_Windows\n WIN32_FILE_ATTRIBUTE_DATA fileAttrData;\n (void)::memset (&fileAttrData, 0, sizeof (fileAttrData));\n ThrowIfFalseGetLastError (::GetFileAttributesExW (fileName.c_str (), GetFileExInfoStandard, &fileAttrData));\n return DateTime (fileAttrData.ftLastWriteTime);\n#else\n AssertNotImplemented ();\n return DateTime ();\n#endif\n}\n\nDateTime IO::FileSystem::FileSystem::GetFileLastAccessDate (const String& fileName)\n{\n#if qPlatform_Windows\n WIN32_FILE_ATTRIBUTE_DATA fileAttrData;\n (void)::memset (&fileAttrData, 0, sizeof (fileAttrData));\n ThrowIfFalseGetLastError (::GetFileAttributesExW (fileName.c_str (), GetFileExInfoStandard, &fileAttrData));\n return DateTime (fileAttrData.ftLastAccessTime);\n#else\n AssertNotImplemented ();\n return DateTime ();\n#endif\n}\n\nvoid IO::FileSystem::FileSystem::RemoveFile (const String& fileName)\n{\n#if qPlatform_Windows && qTargetPlatformSDKUseswchar_t\n Execution::ThrowErrNoIfNegative (::_wunlink (fileName.c_str ()));\n#else\n Execution::ThrowErrNoIfNegative (::unlink (fileName.AsNarrowSDKString ().c_str ()));\n#endif\n}\n\nvoid IO::FileSystem::FileSystem::RemoveFileIf (const String& fileName)\n{\n#if qPlatform_Windows && qTargetPlatformSDKUseswchar_t\n int r = ::_wunlink (fileName.c_str ());\n#else\n int r = ::unlink (fileName.AsNarrowSDKString ().c_str ());\n#endif\n if (r < 0) {\n if (errno != ENOENT) {\n errno_ErrorException::DoThrow (errno);\n }\n }\n}\n\nString IO::FileSystem::FileSystem::GetCurrentDirectory () const\n{\n#if qPlatform_POSIX\n SDKChar buf[PATH_MAX];\n Execution::ThrowErrNoIfNull (::getcwd (buf, NEltsOf (buf)));\n return String::FromSDKString (buf);\n#elif qPlatform_Windows\n SDKChar buf[MAX_PATH];\n ThrowIfZeroGetLastError (::GetCurrentDirectory (NEltsOf (buf), buf));\n return String::FromSDKString (buf);\n#else\n#endif\n}\n\nvoid IO::FileSystem::FileSystem::SetCurrentDirectory (const String& newDir)\n{\n#if qPlatform_POSIX\n Execution::ThrowErrNoIfNegative (::chdir (newDir.AsNarrowSDKString ().c_str ()));\n#elif qPlatform_Windows\n ::SetCurrentDirectory(newDir.AsSDKString ().c_str ());\n#else\n#endif\n}\n<|endoftext|>"} {"text":"#include \"motor\/multirotor_tri_motor_mapper.hpp\"\n\n#include \n#include \n#include \"protocol\/messages.hpp\"\n#include \"util\/time.hpp\"\n#include \n\nconstexpr float M_PI = 3.1415926535;\n\nMultirotorTriMotorMapper::MultirotorTriMotorMapper(PWMDeviceGroup<3>& motors, PWMDeviceGroup<1>& servos, Communicator& communicator, Logger& logger)\n : motors(motors),\n servos(servos),\n throttleStream(communicator, 5),\n logger(logger){\n}\n\nvoid MultirotorTriMotorMapper::run(bool armed, ActuatorSetpoint& input) {\n \/\/ TODO(yoos): comment on motor indexing convention starting from positive\n \/\/ X in counterclockwise order.\n \/\/ Calculate servo output\n std::array sOutputs;\n sOutputs[0] = 0.540 - 0.5*input.yaw; \/\/ Magic number servo bias for pusher yaw prop.\n sOutputs[0] = std::min(1.0, std::max(-1.0, sOutputs[0]));\n servos.set(armed, sOutputs);\n\n \/\/ Scale throttle to compensate for roll and pitch up to max angles\n input.throttle \/= std::cos(std::min(std::fabs(input.roll), M_PI\/3));\n input.throttle \/= std::cos(std::min(std::fabs(input.pitch), M_PI\/3));\n input.throttle = std::min(input.throttle, 1.0); \/\/ Not entirely necessary, but perhaps preserve some control authority.\n\n \/\/ Calculate motor outputs\n std::array mOutputs;\n mOutputs[0] = input.throttle + 0.866025*input.roll - 0.5*input.pitch; \/\/ Left\n mOutputs[1] = input.throttle + input.pitch; \/\/ Tail\n mOutputs[2] = input.throttle - 0.866025*input.roll - 0.5*input.pitch; \/\/ Right\n motors.set(armed, mOutputs);\n\n \/\/ Scale tail thrust per servo tilt\n \/\/ TODO(yoos): Again, resolve magic number.\n mOutputs[1] \/= std::cos(3.1415926535\/4*input.yaw);\n\n \/\/ DEBUG\n \/\/static int loop=0;\n \/\/if (loop == 0) {\n \/\/ chprintf((BaseSequentialStream*)&SD4, \"MM %f %f %f %f\\r\\n\", mOutputs[0], mOutputs[1], mOutputs[2], sOutputs[0]);\n \/\/}\n \/\/loop = (loop+1) % 50;\n\n protocol::message::motor_throttle_message_t m {\n .time = ST2MS(chibios_rt::System::getTime()),\n .throttles = { mOutputs[0], mOutputs[1], mOutputs[2], sOutputs[0] }\n };\n\n if(throttleStream.ready()) {\n throttleStream.publish(m);\n }\n logger.write(m);\n}\nScale tail thrust based on capped output.#include \"motor\/multirotor_tri_motor_mapper.hpp\"\n\n#include \n#include \n#include \"protocol\/messages.hpp\"\n#include \"util\/time.hpp\"\n#include \n\nconstexpr float M_PI = 3.1415926535;\n\nMultirotorTriMotorMapper::MultirotorTriMotorMapper(PWMDeviceGroup<3>& motors, PWMDeviceGroup<1>& servos, Communicator& communicator, Logger& logger)\n : motors(motors),\n servos(servos),\n throttleStream(communicator, 5),\n logger(logger){\n}\n\nvoid MultirotorTriMotorMapper::run(bool armed, ActuatorSetpoint& input) {\n \/\/ TODO(yoos): comment on motor indexing convention starting from positive\n \/\/ X in counterclockwise order.\n \/\/ Calculate servo output\n std::array sOutputs;\n sOutputs[0] = 0.540 - 0.5*input.yaw; \/\/ Magic number servo bias for pusher yaw prop.\n sOutputs[0] = std::min(1.0, std::max(-1.0, sOutputs[0]));\n servos.set(armed, sOutputs);\n\n \/\/ Scale throttle to compensate for roll and pitch up to max angles\n input.throttle \/= std::cos(std::min(std::fabs(input.roll), M_PI\/3));\n input.throttle \/= std::cos(std::min(std::fabs(input.pitch), M_PI\/3));\n input.throttle = std::min(input.throttle, 1.0); \/\/ Not entirely necessary, but perhaps preserve some control authority.\n\n \/\/ Calculate motor outputs\n std::array mOutputs;\n mOutputs[0] = input.throttle + 0.866025*input.roll - 0.5*input.pitch; \/\/ Left\n mOutputs[1] = input.throttle + input.pitch; \/\/ Tail\n mOutputs[2] = input.throttle - 0.866025*input.roll - 0.5*input.pitch; \/\/ Right\n motors.set(armed, mOutputs);\n\n \/\/ Scale tail thrust per servo tilt\n \/\/ TODO(yoos): Again, resolve magic number.\n mOutputs[1] \/= std::cos(3.1415926535\/4*sOutputs[0]);\n\n \/\/ DEBUG\n \/\/static int loop=0;\n \/\/if (loop == 0) {\n \/\/ chprintf((BaseSequentialStream*)&SD4, \"MM %f %f %f %f\\r\\n\", mOutputs[0], mOutputs[1], mOutputs[2], sOutputs[0]);\n \/\/}\n \/\/loop = (loop+1) % 50;\n\n protocol::message::motor_throttle_message_t m {\n .time = ST2MS(chibios_rt::System::getTime()),\n .throttles = { mOutputs[0], mOutputs[1], mOutputs[2], sOutputs[0] }\n };\n\n if(throttleStream.ready()) {\n throttleStream.publish(m);\n }\n logger.write(m);\n}\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n\nnamespace BABYLON {\n\nRawTexture2DArray::RawTexture2DArray(const ArrayBufferView& data, int width, int height, int depth,\n unsigned int iFormat, Scene* scene, bool generateMipMaps,\n bool iInvertY, unsigned int iSamplingMode,\n unsigned int iTextureType)\n : Texture{nullptr, scene, !generateMipMaps, iInvertY}, format{iFormat}\n{\n _texture = scene->getEngine()->createRawTexture2DArray(data, \/\/\n width, \/\/\n height, \/\/\n depth, \/\/\n iFormat, \/\/\n generateMipMaps, \/\/\n invertY, \/\/\n iSamplingMode, \/\/\n \"\", \/\/\n iTextureType \/\/\n );\n\n is2DArray = true;\n}\n\nRawTexture2DArray::~RawTexture2DArray() = default;\n\nvoid RawTexture2DArray::update(const ArrayBufferView& data)\n{\n if (!_texture) {\n return;\n }\n _getEngine()->updateRawTexture2DArray(_texture, data, _texture->format, _texture->invertY, \"\",\n _texture->type);\n}\n\n} \/\/ end of namespace BABYLON\nChecking for valid engine reference#include \n\n#include \n#include \n#include \n\nnamespace BABYLON {\n\nRawTexture2DArray::RawTexture2DArray(const ArrayBufferView& data, int width, int height, int depth,\n unsigned int iFormat, Scene* scene, bool generateMipMaps,\n bool iInvertY, unsigned int iSamplingMode,\n unsigned int iTextureType)\n : Texture{nullptr, scene, !generateMipMaps, iInvertY}, format{iFormat}\n{\n _texture = scene->getEngine()->createRawTexture2DArray(data, \/\/\n width, \/\/\n height, \/\/\n depth, \/\/\n iFormat, \/\/\n generateMipMaps, \/\/\n invertY, \/\/\n iSamplingMode, \/\/\n \"\", \/\/\n iTextureType \/\/\n );\n\n is2DArray = true;\n}\n\nRawTexture2DArray::~RawTexture2DArray() = default;\n\nvoid RawTexture2DArray::update(const ArrayBufferView& data)\n{\n if (!_texture || !_getEngine()) {\n return;\n }\n _getEngine()->updateRawTexture2DArray(_texture, data, _texture->format, _texture->invertY, \"\",\n _texture->type);\n}\n\n} \/\/ end of namespace BABYLON\n<|endoftext|>"} {"text":"\/* \n * File: rigResection.hpp\n * Author: sgaspari\n *\n * Created on January 2, 2016, 5:51 PM\n *\/\n\n#pragma once\n\n#include \n#include \n#include \n\n#include \n\nnamespace openMVG{\nnamespace localization{\n\n#if HAVE_OPENGV\n\nbool rigResection(const std::vector &pts2d, \n const std::vector &pts3d,\n const std::vector &vec_queryIntrinsics,\n const std::vector &vec_subPoses,\n geometry::Pose3 &rigPose,\n std::vector > &inliers,\n double threshold = 1e-6,\n size_t maxIterations = 100, \n bool verbosity = true);\n\n#endif\n\n}\n}\n[localization] doc rigResection\/* \n * File: rigResection.hpp\n * Author: sgaspari\n *\n * Created on January 2, 2016, 5:51 PM\n *\/\n\n#pragma once\n\n#include \n#include \n#include \n\n#include \n\nnamespace openMVG{\nnamespace localization{\n\n#if HAVE_OPENGV\n\n\/**\n * @brief It computes the pose of a camera rig given the 2d-3d associations of \n * each camera along with the internal calibration of each camera and the external \n * calibration of the cameras wrt the main one.\n * \n * @param[in] vec_pts2d A vector of the same size as the number of the camera in \n * the rig, each element of the vector contains the 2d points of the associations \n * for each camera.\n * @param[in] vec_pts3d A vector of the same size as the number of the camera in \n * the rig, each element of the vector contains the 3d points of the associations \n * for each camera. A 2d-3d association is represented by (vec_pts2d[i].col(j), vec_pts3d[i].col(j)).\n * @param[in] vec_queryIntrinsics A vector containing the intrinsics for each \n * camera of the rig.\n * @param[in] vec_subPoses A vector containing the subposes of the cameras wrt \n * the main one, ie the camera 0. This vector has numCameras-1 elements.\n * @param[out] rigPose The rig pose referred to the position of the main camera.\n * @param[out] inliers A vector of the same size as the number of cameras c\n * ontaining the indices of inliers.\n * @param[in] threshold The threshold to use in the ransac process. Note that the \n * threshold is an cos(angle), more specifically it's the maximum angle allowed \n * between the 3D direction of the feature point and the 3D direction of the \n * associated 3D point. The reprojection error computed in the ransac is 1-cos(angle),\n * where angle is the angle between the two directions.\n * @param[in] maxIterations Maximum number of iteration for the ransac process.\n * @param[in] verbosity Mute\/unmute the debugging messages.\n * @return true if the ransac has success.\n *\/\nbool rigResection(const std::vector &vec_pts2d, \n const std::vector &vec_pts3d,\n const std::vector &vec_queryIntrinsics,\n const std::vector &vec_subPoses,\n geometry::Pose3 &rigPose,\n std::vector > &inliers,\n double threshold = 1-std::cos(0.00141421368), \/\/ ~0.1deg\n size_t maxIterations = 100, \n bool verbosity = true);\n\n#endif\n\n}\n}\n<|endoftext|>"} {"text":"#include \"Decoder_polar_SCAN_naive_sys.hpp\"\n\nnamespace aff3ct\n{\nnamespace module\n{\ntemplate I, tools::proto_f F, tools::proto_v V, tools::proto_h H>\nDecoder_polar_SCAN_naive_sys\n::Decoder_polar_SCAN_naive_sys(const int &K, const int &N, const int &max_iter, const mipp::vector &frozen_bits,\n const int n_frames, const std::string name)\n: Decoder_polar_SCAN_naive(K, N, max_iter, frozen_bits, n_frames, name)\n{\n}\n\ntemplate I, tools::proto_f F, tools::proto_v V, tools::proto_h H>\nDecoder_polar_SCAN_naive_sys\n::~Decoder_polar_SCAN_naive_sys()\n{\n}\n\ntemplate I, tools::proto_f F, tools::proto_v V, tools::proto_h H>\nvoid Decoder_polar_SCAN_naive_sys\n::_soft_decode(const R *sys, const R *par, R *ext, const int frame_id)\n{\n\t\/\/ ----------------------------------------------------------------------------------------------------------- LOAD\n\tthis->_load_init();\n\t\n\t\/\/ init the softGraph (special case for the right most stage)\n\tauto sys_idx = 0, par_idx = 0;\n\tfor (auto i = 0; i < this->N; i++)\n\t\tif (!this->frozen_bits[i])\n\t\t\tthis->soft_graph[this->layers_count - 1][i] = sys[sys_idx++];\n\t\telse\n\t\t\tthis->soft_graph[this->layers_count - 1][i] = par[par_idx++];\n\n\t\/\/ --------------------------------------------------------------------------------------------------------- DECODE\n\tDecoder_polar_SCAN_naive::_decode();\n\n\t\/\/ ---------------------------------------------------------------------------------------------------------- STORE\n\tsys_idx = 0;\n\tfor (auto i = 0; i < this->N; i++)\n\t\tif (!this->frozen_bits[i]) \/\/ if \"i\" is NOT a frozen bit (information bit = sytematic bit)\n\t\t\text[sys_idx++] = this->feedback_graph[this->layers_count -1][i];\n}\n\ntemplate I, tools::proto_f F, tools::proto_v V, tools::proto_h H>\nvoid Decoder_polar_SCAN_naive_sys\n::_soft_decode(const R *Y_N1, R *Y_N2, const int frame_id)\n{\n\t\/\/ ----------------------------------------------------------------------------------------------------------- LOAD\n\tthis->_load(Y_N1);\n\n\t\/\/ --------------------------------------------------------------------------------------------------------- DECODE\n\tDecoder_polar_SCAN_naive::_decode();\n\n\t\/\/ ---------------------------------------------------------------------------------------------------------- STORE\n\tfor (auto i = 0; i < this->N; i++)\n\t\tY_N2[i] = this->feedback_graph[this->layers_count -1][i];\n}\n\ntemplate I, tools::proto_f F, tools::proto_v V, tools::proto_h H>\nvoid Decoder_polar_SCAN_naive_sys\n::_store(B *V_N) const\n{\n\tauto k = 0;\n\tfor (auto i = 0; i < this->N; i++)\n\t{\n\t\tif (!this->frozen_bits[i]) \/\/ if i is not a frozen bit\n\t\t\tV_N[k++] = (H(this->feedback_graph[this->layers_count -1][i]) == 0) ? (B)0 : (B)1;\n\t}\n}\n}\n}\nModification of the SCAN store function.#include \"Decoder_polar_SCAN_naive_sys.hpp\"\n\nnamespace aff3ct\n{\nnamespace module\n{\ntemplate I, tools::proto_f F, tools::proto_v V, tools::proto_h H>\nDecoder_polar_SCAN_naive_sys\n::Decoder_polar_SCAN_naive_sys(const int &K, const int &N, const int &max_iter, const mipp::vector &frozen_bits,\n const int n_frames, const std::string name)\n: Decoder_polar_SCAN_naive(K, N, max_iter, frozen_bits, n_frames, name)\n{\n}\n\ntemplate I, tools::proto_f F, tools::proto_v V, tools::proto_h H>\nDecoder_polar_SCAN_naive_sys\n::~Decoder_polar_SCAN_naive_sys()\n{\n}\n\ntemplate I, tools::proto_f F, tools::proto_v V, tools::proto_h H>\nvoid Decoder_polar_SCAN_naive_sys\n::_soft_decode(const R *sys, const R *par, R *ext, const int frame_id)\n{\n\t\/\/ ----------------------------------------------------------------------------------------------------------- LOAD\n\tthis->_load_init();\n\t\n\t\/\/ init the softGraph (special case for the right most stage)\n\tauto sys_idx = 0, par_idx = 0;\n\tfor (auto i = 0; i < this->N; i++)\n\t\tif (!this->frozen_bits[i])\n\t\t\tthis->soft_graph[this->layers_count - 1][i] = sys[sys_idx++];\n\t\telse\n\t\t\tthis->soft_graph[this->layers_count - 1][i] = par[par_idx++];\n\n\t\/\/ --------------------------------------------------------------------------------------------------------- DECODE\n\tDecoder_polar_SCAN_naive::_decode();\n\n\t\/\/ ---------------------------------------------------------------------------------------------------------- STORE\n\tsys_idx = 0;\n\tfor (auto i = 0; i < this->N; i++)\n\t\tif (!this->frozen_bits[i]) \/\/ if \"i\" is NOT a frozen bit (information bit = sytematic bit)\n\t\t\text[sys_idx++] = this->feedback_graph[this->layers_count -1][i];\n}\n\ntemplate I, tools::proto_f F, tools::proto_v V, tools::proto_h H>\nvoid Decoder_polar_SCAN_naive_sys\n::_soft_decode(const R *Y_N1, R *Y_N2, const int frame_id)\n{\n\t\/\/ ----------------------------------------------------------------------------------------------------------- LOAD\n\tthis->_load(Y_N1);\n\n\t\/\/ --------------------------------------------------------------------------------------------------------- DECODE\n\tDecoder_polar_SCAN_naive::_decode();\n\n\t\/\/ ---------------------------------------------------------------------------------------------------------- STORE\n\tfor (auto i = 0; i < this->N; i++)\n\t\tY_N2[i] = this->feedback_graph[this->layers_count -1][i];\n}\n\ntemplate I, tools::proto_f F, tools::proto_v V, tools::proto_h H>\nvoid Decoder_polar_SCAN_naive_sys\n::_store(B *V_N) const\n{\n\tauto k = 0;\n\tfor (auto i = 0; i < this->N; i++)\n\t{\n\t\tif (!this->frozen_bits[i]) \/\/ if i is not a frozen bit\n\t\t\tV_N[k++] = (H(this->feedback_graph[this->layers_count -1][i] + this->soft_graph[this->layers_count -1][i]) == 0) ? (B)0 : (B)1;\n\t}\n}\n}\n}\n<|endoftext|>"} {"text":"\/**\n * Author: derselbst\n * Description: provides functions that are used by the worker processes to check whether a bruteforced string generated by the master process matches pwdHash\n *\/\n\n#include \n#include \/\/ memcmp()\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n#include \"worker.h\"\n#include \"master.h\"\n#include \"alphabet.h\"\n\n\/\/ contains the hash of the unknown password\nchar pwdHash[SHA256_DIGEST_LENGTH];\n\n\/\/ contains the hash of a bruteforced string\nchar bruteHash[SHA256_DIGEST_LENGTH];\n\n\/\/ used when sending messages\nenum MpiMsgTag\n{\n task,\n success \/\/ hashes match, unused ATM\n};\n\n\/**\n * @brief prints 32 bytes of memory\n *\n * prints a hex dump of 32 bytes of memory pointed to\n *\n * @param[in] pbuf: pointer to some memory, usually containing an SHA256 hash\n *\/\nvoid printSHAHash(const unsigned int *const pbuf)\n{\n \/\/ byteswap the integer pointed to, to display hex dump in correct order\n \/\/ TODO: how to deal with big endian machines\n cout << std::hex << std::uppercase << setw(8) << setfill('0')\n << bswap_32(*(pbuf))\n << bswap_32(*(pbuf+1))\n << bswap_32(*(pbuf+2))\n << bswap_32(*(pbuf+3))\n << bswap_32(*(pbuf+4))\n << bswap_32(*(pbuf+5))\n << bswap_32(*(pbuf+6))\n << bswap_32(*(pbuf+7))\n << endl;\n}\n\n\/**\n * @brief generates an SHA256 hash\n *\n * generates an SHA256 hash using openSSL\n *\n * @param[in] input: a const pointer to const block of data, usually a char array of which the hash is being generated\n * @param[in] length: the number of bytes the that input points to holds\n * @param[in,out] hashStr: const pointer to an array of SHA256_DIGEST_LENGTH bytes that will receive the hash\n *\n * @return returns true if the hash has been generated successfully; returns false if input or hashStr is NULL or length==0; else: false\n *\/\nbool generateSHA256(const void *const input, const size_t &length, char *const hashStr)\n{\n if(!hashStr || !input || length==0)\n {\n return false;\n }\n\n SHA256_CTX hash;\n if(!SHA256_Init(&hash))\n {\n return false;\n }\n\n if(!SHA256_Update(&hash, input, length))\n {\n return false;\n }\n\n if(!SHA256_Final(reinterpret_cast(hashStr), &hash))\n {\n return false;\n }\n\n return true;\n}\n\n\/**\n * @brief checks equality of two hashes\n *\n * calculates the SHA256 hash of 'password' and compares it\n * with the initial password hash\n *\n * @param[in] password: a const string containing a guessed password\n *\n * @return returns true if hashes match; false if generation of hash failed or hashes not match\n *\/\nbool checkPassword(const string &password)\n{\n#ifdef VERBOSE\n cout << \"checking \" << password << endl;\n#endif \/\/ VERBOSE\n\n \/\/ generate sha hash from entered string and write it to pwdHash\n if(!generateSHA256(password.c_str(), password.length(), bruteHash))\n {\n cerr << \"Error when generating SHA256 from \\\"\" << password << \"\\\"\" << endl;\n return false;\n }\n\n if (!memcmp(bruteHash, pwdHash, SHA256_DIGEST_LENGTH))\n {\n cout << \"match [\" << password << \"]\" << endl << \"hash: \" << endl;\n printSHAHash((unsigned int*)bruteHash);\n return true;\n }\n\n return false;\n}\n\n\/**\n * @brief the main loop for a worker process\n *\n * continuously looks for incoming strings, generates the SHA\n * hash of it and checks if it matches the secret hash\n *\/\nvoid worker()\n{\n char buf[MaxChars];\n MPI_Status state;\n\n while(true)\n {\n \/\/ check for new msg\n MPI_Probe(MasterProcess, task, MPI_COMM_WORLD, &state);\n\n int len;\n \/\/ now check status to determine how many bytes were actually received\n MPI_Get_count(&state, MPI_BYTE, &len);\n\n \/\/ receive len bytes\n MPI_Recv(buf, len, MPI_BYTE, MasterProcess, task, MPI_COMM_WORLD, &state);\n\n string baseStr(buf, len);\n\n for(int i=0; i(baseStr+alphabet[i].c_str()), baseStr+alphabet[i].length(), MPI_CHAR, MasterProcess, success, MPI_COMM_WORLD);\n cout << \"Password found: \" << baseStr+alphabet[i] << endl;\n MPI_Abort(MPI_COMM_WORLD, 0);\n\n break;\n }\n }\n }\n}\nreceive MPI_ANY_TAG\/**\n * Author: derselbst\n * Description: provides functions that are used by the worker processes to check whether a bruteforced string generated by the master process matches pwdHash\n *\/\n\n#include \n#include \/\/ memcmp()\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n#include \"worker.h\"\n#include \"master.h\"\n#include \"alphabet.h\"\n\n\/\/ contains the hash of the unknown password\nchar pwdHash[SHA256_DIGEST_LENGTH];\n\n\/\/ contains the hash of a bruteforced string\nchar bruteHash[SHA256_DIGEST_LENGTH];\n\n\/\/ used when sending messages\nenum MpiMsgTag\n{\n task,\n success \/\/ hashes match, unused ATM\n};\n\n\/**\n * @brief prints 32 bytes of memory\n *\n * prints a hex dump of 32 bytes of memory pointed to\n *\n * @param[in] pbuf: pointer to some memory, usually containing an SHA256 hash\n *\/\nvoid printSHAHash(const unsigned int *const pbuf)\n{\n \/\/ byteswap the integer pointed to, to display hex dump in correct order\n \/\/ TODO: how to deal with big endian machines\n cout << std::hex << std::uppercase << setw(8) << setfill('0')\n << bswap_32(*(pbuf))\n << bswap_32(*(pbuf+1))\n << bswap_32(*(pbuf+2))\n << bswap_32(*(pbuf+3))\n << bswap_32(*(pbuf+4))\n << bswap_32(*(pbuf+5))\n << bswap_32(*(pbuf+6))\n << bswap_32(*(pbuf+7))\n << endl;\n}\n\n\/**\n * @brief generates an SHA256 hash\n *\n * generates an SHA256 hash using openSSL\n *\n * @param[in] input: a const pointer to const block of data, usually a char array of which the hash is being generated\n * @param[in] length: the number of bytes the that input points to holds\n * @param[in,out] hashStr: const pointer to an array of SHA256_DIGEST_LENGTH bytes that will receive the hash\n *\n * @return returns true if the hash has been generated successfully; returns false if input or hashStr is NULL or length==0; else: false\n *\/\nbool generateSHA256(const void *const input, const size_t &length, char *const hashStr)\n{\n if(!hashStr || !input || length==0)\n {\n return false;\n }\n\n SHA256_CTX hash;\n if(!SHA256_Init(&hash))\n {\n return false;\n }\n\n if(!SHA256_Update(&hash, input, length))\n {\n return false;\n }\n\n if(!SHA256_Final(reinterpret_cast(hashStr), &hash))\n {\n return false;\n }\n\n return true;\n}\n\n\/**\n * @brief checks equality of two hashes\n *\n * calculates the SHA256 hash of 'password' and compares it\n * with the initial password hash\n *\n * @param[in] password: a const string containing a guessed password\n *\n * @return returns true if hashes match; false if generation of hash failed or hashes not match\n *\/\nbool checkPassword(const string &password)\n{\n#ifdef VERBOSE\n cout << \"checking \" << password << endl;\n#endif \/\/ VERBOSE\n\n \/\/ generate sha hash from entered string and write it to pwdHash\n if(!generateSHA256(password.c_str(), password.length(), bruteHash))\n {\n cerr << \"Error when generating SHA256 from \\\"\" << password << \"\\\"\" << endl;\n return false;\n }\n\n if (!memcmp(bruteHash, pwdHash, SHA256_DIGEST_LENGTH))\n {\n cout << \"match [\" << password << \"]\" << endl << \"hash: \" << endl;\n printSHAHash((unsigned int*)bruteHash);\n return true;\n }\n\n return false;\n}\n\n\/**\n * @brief the main loop for a worker process\n *\n * continuously looks for incoming strings, generates the SHA\n * hash of it and checks if it matches the secret hash\n *\/\nvoid worker()\n{\n char buf[MaxChars];\n MPI_Status state;\n\n while(true)\n {\n \/\/ check for new msg\n MPI_Probe(MasterProcess, MPI_ANY_TAG, MPI_COMM_WORLD, &state);\n\n int len;\n \/\/ now check status to determine how many bytes were actually received\n MPI_Get_count(&state, MPI_BYTE, &len);\n\n \/\/ receive len bytes\n MPI_Recv(buf, len, MPI_BYTE, MasterProcess, MPI_ANY_TAG, MPI_COMM_WORLD, &state);\n\n string baseStr(buf, len);\n\n for(int i=0; i(baseStr+alphabet[i].c_str()), baseStr+alphabet[i].length(), MPI_CHAR, MasterProcess, success, MPI_COMM_WORLD);\n cout << \"Password found: \" << baseStr+alphabet[i] << endl;\n MPI_Abort(MPI_COMM_WORLD, 0);\n\n break;\n }\n }\n }\n}\n<|endoftext|>"} {"text":"new macro for MC gen train, Pythia with shoving and flavour ropes<|endoftext|>"} {"text":"Updated maximum histogram bucket for UseCountering of CSS properties.<|endoftext|>"} {"text":"\/**\n * @file head_finder.cpp\n * @author Chase Geigle\n *\/\n\n#include \n#include \n\n#include \"logging\/logger.h\"\n#include \"meta.h\"\n#include \"parser\/trees\/visitors\/head_finder.h\"\n#include \"parser\/trees\/internal_node.h\"\n#include \"parser\/trees\/leaf_node.h\"\n#include \"util\/optional.h\"\n\nnamespace meta\n{\nnamespace parser\n{\n\nnamespace\n{\n\n\/**\n * A normal head rule following Collins' head finding algorithm.\n *\/\nstruct normal_head_rule : public head_rule\n{\n template \n normal_head_rule(Args&&... args)\n : candidates_{{std::forward(args)...}}\n {\n \/\/ nothing\n }\n\n std::vector candidates_;\n};\n\n\/**\n * A head rule that starts its search from the leftmost child.\n *\/\nstruct head_initial : public normal_head_rule\n{\n using normal_head_rule::normal_head_rule;\n\n uint64_t find_head(const internal_node& inode) const override\n {\n for (const auto& cand : candidates_)\n {\n for (uint64_t idx = 0; idx < inode.num_children(); ++idx)\n {\n auto child = inode.child(idx);\n if (child->category() == cand)\n return idx;\n }\n }\n\n \/\/ no matches, use left most node\n return 0;\n }\n};\n\n\/**\n * A head rule that starts its search from the rightmost child.\n *\/\nstruct head_final : public normal_head_rule\n{\n using normal_head_rule::normal_head_rule;\n\n uint64_t find_head(const internal_node& inode) const override\n {\n for (const auto& cand : candidates_)\n {\n for (uint64_t idx = 0; idx < inode.num_children(); ++idx)\n {\n \/\/ iterate in reverse, from right to left\n auto ridx = inode.num_children() - 1 - idx;\n auto child = inode.child(ridx);\n if (child->category() == cand)\n return ridx;\n }\n }\n\n \/\/ no matches, use right most node\n return inode.num_children() - 1;\n }\n};\n\n\/**\n * The special case for noun phrases in Collins' head finding algorithm.\n * @see Collins' thesis, page 238-239\n *\/\nstruct head_np : public head_rule\n{\n struct head_final_np\n {\n std::unordered_set candidates_;\n\n util::optional find_head(const internal_node& inode) const\n {\n for (uint64_t idx = 0; idx < inode.num_children(); ++idx)\n {\n auto ridx = inode.num_children() - 1 - idx;\n auto child = inode.child(ridx);\n if (candidates_.find(child->category()) != candidates_.end())\n return {ridx};\n }\n\n return util::nullopt;\n }\n };\n\n struct head_initial_np\n {\n std::unordered_set candidates_;\n\n util::optional find_head(const internal_node& inode) const\n {\n for (uint64_t idx = 0; idx < inode.num_children(); ++idx)\n {\n auto child = inode.child(idx);\n if (candidates_.find(child->category()) != candidates_.end())\n return {idx};\n }\n\n return util::nullopt;\n }\n };\n\n uint64_t find_head(const internal_node& inode) const override\n {\n head_final_np first_pass{{\"NN\"_cl, \"NNP\"_cl, \"NNPS\"_cl, \"NNS\"_cl,\n \"NX\"_cl, \"POS\"_cl, \"JJR\"_cl}};\n if (auto idx = first_pass.find_head(inode))\n return *idx;\n\n head_initial_np second_pass{{\"NP\"_cl}};\n if (auto idx = second_pass.find_head(inode))\n return *idx;\n\n head_final_np third_pass{{\"$\"_cl, \"ADJP\"_cl, \"PRN\"_cl}};\n if (auto idx = third_pass.find_head(inode))\n return *idx;\n\n head_final_np fourth_pass{{\"CD\"_cl}};\n if (auto idx = fourth_pass.find_head(inode))\n return *idx;\n\n head_final_np fifth_pass{{\"JJ\"_cl, \"JJS\"_cl, \"RB\"_cl, \"QP\"_cl}};\n if (auto idx = fifth_pass.find_head(inode))\n return *idx;\n\n \/\/ no matches, just use last child\n return inode.num_children() - 1;\n }\n};\n}\n\nhead_finder::head_finder()\n{\n \/\/\/ @see: http:\/\/www.cs.columbia.edu\/~mcollins\/papers\/heads\n \/\/\/ @see Collins' thesis, page 240\n rules_[\"ADJP\"_cl] = make_unique(\n \"NNS\"_cl, \"QP\"_cl, \"NN\"_cl, \"$\"_cl, \"ADVP\"_cl, \"JJ\"_cl, \"VBN\"_cl,\n \"VBG\"_cl, \"ADJP\"_cl, \"JJR\"_cl, \"NP\"_cl, \"JJS\"_cl, \"DT\"_cl, \"FW\"_cl,\n \"RBR\"_cl, \"RBS\"_cl, \"SBAR\"_cl, \"RB\"_cl);\n\n rules_[\"ADVP\"_cl] = make_unique(\n \"RB\"_cl, \"RBR\"_cl, \"RBS\"_cl, \"FW\"_cl, \"ADVP\"_cl, \"TO\"_cl, \"CD\"_cl,\n \"JJR\"_cl, \"JJ\"_cl, \"IN\"_cl, \"NP\"_cl, \"JJS\"_cl, \"NN\"_cl);\n\n rules_[\"CONJP\"_cl] = make_unique(\"CC\"_cl, \"RB\"_cl, \"IN\"_cl);\n\n rules_[\"FRAG\"_cl] = make_unique();\n\n rules_[\"INTJ\"_cl] = make_unique();\n\n rules_[\"LST\"_cl] = make_unique(\"LS\"_cl, \":\"_cl);\n\n rules_[\"NAC\"_cl] = make_unique(\n \"NN\"_cl, \"NNS\"_cl, \"NNP\"_cl, \"NNPS\"_cl, \"NP\"_cl, \"NAC\"_cl, \"EX\"_cl,\n \"$\"_cl, \"CD\"_cl, \"QP\"_cl, \"PRP\"_cl, \"VBG\"_cl, \"JJ\"_cl, \"JJS\"_cl,\n \"JJR\"_cl, \"ADJP\"_cl, \"FW\"_cl);\n\n rules_[\"PP\"_cl] = make_unique(\"IN\"_cl, \"TO\"_cl, \"VBG\"_cl,\n \"VBN\"_cl, \"RP\"_cl, \"FW\"_cl);\n\n rules_[\"PRN\"_cl] = make_unique();\n\n rules_[\"PRT\"_cl] = make_unique(\"RP\"_cl);\n\n rules_[\"QP\"_cl] = make_unique(\n \"$\"_cl, \"IN\"_cl, \"NNS\"_cl, \"NN\"_cl, \"JJ\"_cl, \"RB\"_cl, \"DT\"_cl, \"CD\"_cl,\n \"NCD\"_cl, \"QP\"_cl, \"JJR\"_cl, \"JJS\"_cl);\n\n rules_[\"RRC\"_cl] = make_unique(\"VP\"_cl, \"NP\"_cl, \"ADVP\"_cl,\n \"ADJP\"_cl, \"PP\"_cl);\n\n rules_[\"S\"_cl]\n = make_unique(\"TO\"_cl, \"IN\"_cl, \"VP\"_cl, \"S\"_cl,\n \"SBAR\"_cl, \"ADJP\"_cl, \"UCP\"_cl, \"NP\"_cl);\n\n rules_[\"SBAR\"_cl] = make_unique(\n \"WHNP\"_cl, \"WHPP\"_cl, \"WHADVP\"_cl, \"WHADJP\"_cl, \"IN\"_cl, \"DT\"_cl,\n \"S\"_cl, \"SQ\"_cl, \"SINV\"_cl, \"SBAR\"_cl, \"FRAG\"_cl);\n\n rules_[\"SBARQ\"_cl] = make_unique(\"SQ\"_cl, \"S\"_cl, \"SINV\"_cl,\n \"SBARQ\"_cl, \"FRAG\"_cl);\n\n rules_[\"SINV\"_cl] = make_unique(\n \"VBZ\"_cl, \"VBD\"_cl, \"VBP\"_cl, \"VB\"_cl, \"MD\"_cl, \"VP\"_cl, \"S\"_cl,\n \"SINV\"_cl, \"ADJP\"_cl, \"NP\"_cl);\n\n rules_[\"SQ\"_cl] = make_unique(\n \"VBZ\"_cl, \"VBD\"_cl, \"VBP\"_cl, \"VB\"_cl, \"MD\"_cl, \"VP\"_cl, \"SQ\"_cl);\n\n rules_[\"UCP\"_cl] = make_unique();\n\n rules_[\"VP\"_cl] = make_unique(\n \"TO\"_cl, \"VBD\"_cl, \"VBN\"_cl, \"MD\"_cl, \"VBZ\"_cl, \"VB\"_cl, \"VBG\"_cl,\n \"VBP\"_cl, \"VP\"_cl, \"ADJP\"_cl, \"NN\"_cl, \"NNS\"_cl, \"NP\"_cl);\n\n rules_[\"WHADJP\"_cl]\n = make_unique(\"CC\"_cl, \"WRB\"_cl, \"JJ\"_cl, \"ADJP\"_cl);\n\n rules_[\"WHADVP\"_cl] = make_unique(\"CC\"_cl, \"WRB\"_cl);\n\n rules_[\"WHNP\"_cl] = make_unique(\n \"WDT\"_cl, \"WP\"_cl, \"WP$\"_cl, \"WHADJP\"_cl, \"WHPP\"_cl, \"WHNP\"_cl);\n\n rules_[\"WHPP\"_cl] = make_unique(\"IN\"_cl, \"TO\"_cl, \"FW\"_cl);\n\n rules_[\"NP\"_cl] = make_unique();\n\n rules_[\"NX\"_cl]\n = make_unique(); \/\/ not present in collins' thesis...\n\n rules_[\"X\"_cl]\n = make_unique(); \/\/ not present in collins' thesis...\n\n rules_[\"ROOT\"_cl] = make_unique();\n}\n\nhead_finder::head_finder(rule_table&& table) : rules_{std::move(table)}\n{\n \/\/ nothing\n}\n\nvoid head_finder::operator()(leaf_node&)\n{\n \/\/ head annotations are only populated for internal nodes; leaf nodes\n \/\/ are the trivial case\n return;\n}\n\nvoid head_finder::operator()(internal_node& inode)\n{\n \/\/ recurse, as we need the head annotations of all child nodes first\n inode.each_child([&](node* child)\n {\n child->accept(*this);\n });\n\n if (rules_.find(inode.category()) == rules_.end())\n LOG(fatal) << \"No rule found for category \" << inode.category()\n << \" in rule table\" << ENDLG;\n\n \/\/ run the head finder for the syntactic category of the current node\n auto idx = rules_.at(inode.category())->find_head(inode);\n inode.head(inode.child(idx));\n\n \/\/ clean up stage for handling coordinating clauses\n if (idx > 1 && inode.child(idx - 1)->category() == class_label{\"CC\"})\n inode.head(inode.child(idx - 2));\n}\n}\n}\nAppease the compilers when in release mode.\/**\n * @file head_finder.cpp\n * @author Chase Geigle\n *\/\n\n#include \n#include \n\n#include \"logging\/logger.h\"\n#include \"meta.h\"\n#include \"parser\/trees\/visitors\/head_finder.h\"\n#include \"parser\/trees\/internal_node.h\"\n#include \"parser\/trees\/leaf_node.h\"\n#include \"util\/optional.h\"\n\nnamespace meta\n{\nnamespace parser\n{\n\nnamespace\n{\n\n\/**\n * A normal head rule following Collins' head finding algorithm.\n *\/\nstruct normal_head_rule : public head_rule\n{\n template \n normal_head_rule(Args&&... args)\n : candidates_({std::forward(args)...})\n {\n \/\/ nothing\n }\n\n std::vector candidates_;\n};\n\n\/**\n * A head rule that starts its search from the leftmost child.\n *\/\nstruct head_initial : public normal_head_rule\n{\n using normal_head_rule::normal_head_rule;\n\n uint64_t find_head(const internal_node& inode) const override\n {\n for (const auto& cand : candidates_)\n {\n for (uint64_t idx = 0; idx < inode.num_children(); ++idx)\n {\n auto child = inode.child(idx);\n if (child->category() == cand)\n return idx;\n }\n }\n\n \/\/ no matches, use left most node\n return 0;\n }\n};\n\n\/**\n * A head rule that starts its search from the rightmost child.\n *\/\nstruct head_final : public normal_head_rule\n{\n using normal_head_rule::normal_head_rule;\n\n uint64_t find_head(const internal_node& inode) const override\n {\n for (const auto& cand : candidates_)\n {\n for (uint64_t idx = 0; idx < inode.num_children(); ++idx)\n {\n \/\/ iterate in reverse, from right to left\n auto ridx = inode.num_children() - 1 - idx;\n auto child = inode.child(ridx);\n if (child->category() == cand)\n return ridx;\n }\n }\n\n \/\/ no matches, use right most node\n return inode.num_children() - 1;\n }\n};\n\n\/**\n * The special case for noun phrases in Collins' head finding algorithm.\n * @see Collins' thesis, page 238-239\n *\/\nstruct head_np : public head_rule\n{\n struct head_final_np\n {\n std::unordered_set candidates_;\n\n util::optional find_head(const internal_node& inode) const\n {\n for (uint64_t idx = 0; idx < inode.num_children(); ++idx)\n {\n auto ridx = inode.num_children() - 1 - idx;\n auto child = inode.child(ridx);\n if (candidates_.find(child->category()) != candidates_.end())\n return {ridx};\n }\n\n return util::nullopt;\n }\n };\n\n struct head_initial_np\n {\n std::unordered_set candidates_;\n\n util::optional find_head(const internal_node& inode) const\n {\n for (uint64_t idx = 0; idx < inode.num_children(); ++idx)\n {\n auto child = inode.child(idx);\n if (candidates_.find(child->category()) != candidates_.end())\n return {idx};\n }\n\n return util::nullopt;\n }\n };\n\n uint64_t find_head(const internal_node& inode) const override\n {\n head_final_np first_pass{{\"NN\"_cl, \"NNP\"_cl, \"NNPS\"_cl, \"NNS\"_cl,\n \"NX\"_cl, \"POS\"_cl, \"JJR\"_cl}};\n if (auto idx = first_pass.find_head(inode))\n return *idx;\n\n head_initial_np second_pass{{\"NP\"_cl}};\n if (auto idx = second_pass.find_head(inode))\n return *idx;\n\n head_final_np third_pass{{\"$\"_cl, \"ADJP\"_cl, \"PRN\"_cl}};\n if (auto idx = third_pass.find_head(inode))\n return *idx;\n\n head_final_np fourth_pass{{\"CD\"_cl}};\n if (auto idx = fourth_pass.find_head(inode))\n return *idx;\n\n head_final_np fifth_pass{{\"JJ\"_cl, \"JJS\"_cl, \"RB\"_cl, \"QP\"_cl}};\n if (auto idx = fifth_pass.find_head(inode))\n return *idx;\n\n \/\/ no matches, just use last child\n return inode.num_children() - 1;\n }\n};\n}\n\nhead_finder::head_finder()\n{\n \/\/\/ @see: http:\/\/www.cs.columbia.edu\/~mcollins\/papers\/heads\n \/\/\/ @see Collins' thesis, page 240\n rules_[\"ADJP\"_cl] = make_unique(\n \"NNS\"_cl, \"QP\"_cl, \"NN\"_cl, \"$\"_cl, \"ADVP\"_cl, \"JJ\"_cl, \"VBN\"_cl,\n \"VBG\"_cl, \"ADJP\"_cl, \"JJR\"_cl, \"NP\"_cl, \"JJS\"_cl, \"DT\"_cl, \"FW\"_cl,\n \"RBR\"_cl, \"RBS\"_cl, \"SBAR\"_cl, \"RB\"_cl);\n\n rules_[\"ADVP\"_cl] = make_unique(\n \"RB\"_cl, \"RBR\"_cl, \"RBS\"_cl, \"FW\"_cl, \"ADVP\"_cl, \"TO\"_cl, \"CD\"_cl,\n \"JJR\"_cl, \"JJ\"_cl, \"IN\"_cl, \"NP\"_cl, \"JJS\"_cl, \"NN\"_cl);\n\n rules_[\"CONJP\"_cl] = make_unique(\"CC\"_cl, \"RB\"_cl, \"IN\"_cl);\n\n rules_[\"FRAG\"_cl] = make_unique();\n\n rules_[\"INTJ\"_cl] = make_unique();\n\n rules_[\"LST\"_cl] = make_unique(\"LS\"_cl, \":\"_cl);\n\n rules_[\"NAC\"_cl] = make_unique(\n \"NN\"_cl, \"NNS\"_cl, \"NNP\"_cl, \"NNPS\"_cl, \"NP\"_cl, \"NAC\"_cl, \"EX\"_cl,\n \"$\"_cl, \"CD\"_cl, \"QP\"_cl, \"PRP\"_cl, \"VBG\"_cl, \"JJ\"_cl, \"JJS\"_cl,\n \"JJR\"_cl, \"ADJP\"_cl, \"FW\"_cl);\n\n rules_[\"PP\"_cl] = make_unique(\"IN\"_cl, \"TO\"_cl, \"VBG\"_cl,\n \"VBN\"_cl, \"RP\"_cl, \"FW\"_cl);\n\n rules_[\"PRN\"_cl] = make_unique();\n\n rules_[\"PRT\"_cl] = make_unique(\"RP\"_cl);\n\n rules_[\"QP\"_cl] = make_unique(\n \"$\"_cl, \"IN\"_cl, \"NNS\"_cl, \"NN\"_cl, \"JJ\"_cl, \"RB\"_cl, \"DT\"_cl, \"CD\"_cl,\n \"NCD\"_cl, \"QP\"_cl, \"JJR\"_cl, \"JJS\"_cl);\n\n rules_[\"RRC\"_cl] = make_unique(\"VP\"_cl, \"NP\"_cl, \"ADVP\"_cl,\n \"ADJP\"_cl, \"PP\"_cl);\n\n rules_[\"S\"_cl]\n = make_unique(\"TO\"_cl, \"IN\"_cl, \"VP\"_cl, \"S\"_cl,\n \"SBAR\"_cl, \"ADJP\"_cl, \"UCP\"_cl, \"NP\"_cl);\n\n rules_[\"SBAR\"_cl] = make_unique(\n \"WHNP\"_cl, \"WHPP\"_cl, \"WHADVP\"_cl, \"WHADJP\"_cl, \"IN\"_cl, \"DT\"_cl,\n \"S\"_cl, \"SQ\"_cl, \"SINV\"_cl, \"SBAR\"_cl, \"FRAG\"_cl);\n\n rules_[\"SBARQ\"_cl] = make_unique(\"SQ\"_cl, \"S\"_cl, \"SINV\"_cl,\n \"SBARQ\"_cl, \"FRAG\"_cl);\n\n rules_[\"SINV\"_cl] = make_unique(\n \"VBZ\"_cl, \"VBD\"_cl, \"VBP\"_cl, \"VB\"_cl, \"MD\"_cl, \"VP\"_cl, \"S\"_cl,\n \"SINV\"_cl, \"ADJP\"_cl, \"NP\"_cl);\n\n rules_[\"SQ\"_cl] = make_unique(\n \"VBZ\"_cl, \"VBD\"_cl, \"VBP\"_cl, \"VB\"_cl, \"MD\"_cl, \"VP\"_cl, \"SQ\"_cl);\n\n rules_[\"UCP\"_cl] = make_unique();\n\n rules_[\"VP\"_cl] = make_unique(\n \"TO\"_cl, \"VBD\"_cl, \"VBN\"_cl, \"MD\"_cl, \"VBZ\"_cl, \"VB\"_cl, \"VBG\"_cl,\n \"VBP\"_cl, \"VP\"_cl, \"ADJP\"_cl, \"NN\"_cl, \"NNS\"_cl, \"NP\"_cl);\n\n rules_[\"WHADJP\"_cl]\n = make_unique(\"CC\"_cl, \"WRB\"_cl, \"JJ\"_cl, \"ADJP\"_cl);\n\n rules_[\"WHADVP\"_cl] = make_unique(\"CC\"_cl, \"WRB\"_cl);\n\n rules_[\"WHNP\"_cl] = make_unique(\n \"WDT\"_cl, \"WP\"_cl, \"WP$\"_cl, \"WHADJP\"_cl, \"WHPP\"_cl, \"WHNP\"_cl);\n\n rules_[\"WHPP\"_cl] = make_unique(\"IN\"_cl, \"TO\"_cl, \"FW\"_cl);\n\n rules_[\"NP\"_cl] = make_unique();\n\n rules_[\"NX\"_cl]\n = make_unique(); \/\/ not present in collins' thesis...\n\n rules_[\"X\"_cl]\n = make_unique(); \/\/ not present in collins' thesis...\n\n rules_[\"ROOT\"_cl] = make_unique();\n}\n\nhead_finder::head_finder(rule_table&& table) : rules_{std::move(table)}\n{\n \/\/ nothing\n}\n\nvoid head_finder::operator()(leaf_node&)\n{\n \/\/ head annotations are only populated for internal nodes; leaf nodes\n \/\/ are the trivial case\n return;\n}\n\nvoid head_finder::operator()(internal_node& inode)\n{\n \/\/ recurse, as we need the head annotations of all child nodes first\n inode.each_child([&](node* child)\n {\n child->accept(*this);\n });\n\n if (rules_.find(inode.category()) == rules_.end())\n LOG(fatal) << \"No rule found for category \" << inode.category()\n << \" in rule table\" << ENDLG;\n\n \/\/ run the head finder for the syntactic category of the current node\n auto idx = rules_.at(inode.category())->find_head(inode);\n inode.head(inode.child(idx));\n\n \/\/ clean up stage for handling coordinating clauses\n if (idx > 1 && inode.child(idx - 1)->category() == class_label{\"CC\"})\n inode.head(inode.child(idx - 2));\n}\n}\n}\n<|endoftext|>"} {"text":"\/*\n * This file is part of the UnTech Editor Suite.\n * Copyright (c) 2016 - 2018, Marcus Rowe .\n * Distributed under The MIT License: https:\/\/opensource.org\/licenses\/MIT\n *\/\n\n#pragma once\n#include \"models\/common\/vectorset.h\"\n#include \"models\/metasprite\/metasprite.h\"\n#include \"models\/metasprite\/spriteimporter.h\"\n#include \n#include \n#include \n#include \n#include \n\nnamespace UnTech {\nnamespace MetaSprite {\nnamespace Utsi2UtmsPrivate {\n\nnamespace MS = UnTech::MetaSprite::MetaSprite;\nnamespace SI = UnTech::MetaSprite::SpriteImporter;\n\nclass PaletteConverter {\n const SI::FrameSet& siFrameSet;\n const Image& image;\n MS::FrameSet& msFrameSet;\n ErrorList& errorList;\n\n \/\/ Faster than std::unordered_map, only contains a max of 16 elements\n std::map _colorMap;\n\npublic:\n PaletteConverter(const SI::FrameSet& siFrameSet,\n const Image& image,\n MS::FrameSet& msFrameSet,\n ErrorList& errorList)\n : siFrameSet(siFrameSet)\n , image(image)\n , msFrameSet(msFrameSet)\n , errorList(errorList)\n , _colorMap()\n {\n }\n\n const auto& colorMap() const { return _colorMap; }\n\n void process()\n {\n try {\n if (siFrameSet.palette.usesUserSuppliedPalette()) {\n buildUserSuppliedPalettes();\n }\n else {\n buildAutomaticPalette();\n }\n }\n catch (const std::exception& ex) {\n errorList.addError(siFrameSet, ex.what());\n }\n }\n\nprivate:\n vectorset getColorsFromImage() const\n {\n assert(image.empty() == false);\n\n vectorset colors;\n\n for (const auto& siFrameIt : siFrameSet.frames) {\n const SI::Frame& siFrame = siFrameIt.second;\n\n for (const SI::FrameObject& obj : siFrame.objects) {\n unsigned lx = siFrame.location.aabb.x + obj.location.x;\n unsigned ly = siFrame.location.aabb.y + obj.location.y;\n\n for (unsigned y = 0; y < obj.sizePx(); y++) {\n const rgba* p = image.scanline(ly + y) + lx;\n\n for (unsigned x = 0; x < obj.sizePx(); x++) {\n colors.insert(*p++);\n }\n }\n\n if (colors.size() > (PALETTE_COLORS)) {\n throw std::runtime_error(\"Too many colors, expected a max of 16\");\n }\n }\n }\n\n \/\/ remove transparent from colors list\n auto tIt = colors.find(siFrameSet.transparentColor);\n if (tIt != colors.end()) {\n colors.erase(tIt);\n }\n else {\n errorList.addWarning(siFrameSet, \"Transparent color is not in frame objects\");\n }\n\n return colors;\n }\n\n inline void buildUserSuppliedPalettes()\n {\n validateUserSuppliedPalettes();\n\n const unsigned colorSize = siFrameSet.palette.colorSize;\n\n for (unsigned pal = 0; pal < siFrameSet.palette.nPalettes; pal++) {\n const unsigned yPos = image.size().height - pal * colorSize - 1;\n\n msFrameSet.palettes.emplace_back();\n Snes::Palette4bpp& palette = msFrameSet.palettes.back();\n\n for (unsigned i = 0; i < PALETTE_COLORS; i++) {\n const rgba c = image.getPixel(i * colorSize, yPos);\n\n palette.color(i).setRgb(c);\n\n if (pal == 0) {\n _colorMap.insert({ c, i });\n }\n }\n }\n }\n\n inline void validateUserSuppliedPalettes() const\n {\n const usize imageSize = image.size();\n const usize paletteSize = siFrameSet.palette.paletteSize();\n\n if (imageSize.width < paletteSize.width || imageSize.height < paletteSize.height) {\n throw std::runtime_error(\"Cannot load custom palette, image is too small\");\n }\n\n for (unsigned pal = 0; pal < siFrameSet.palette.nPalettes; pal++) {\n validateUserSuppliedPalette(pal);\n }\n\n validateFirstUserSuppliedPalette();\n }\n\n inline void validateUserSuppliedPalette(unsigned pal) const\n {\n const unsigned colorSize = siFrameSet.palette.colorSize;\n const unsigned yPos = image.size().height - pal * colorSize - 1;\n\n const rgba* scanline = image.scanline(yPos);\n\n \/\/ ensure the scanlines of the palette equal\n\n for (unsigned l = 1; l < colorSize; l++) {\n const rgba* linetoTest = image.scanline(yPos - l);\n\n if (std::memcmp(scanline, linetoTest, sizeof(rgba) * colorSize * PALETTE_COLORS) != 0) {\n throw std::runtime_error(\"Custom Palette is invalid A\");\n }\n }\n\n \/\/ ensure each of the palette colors are equally colored squares\n for (unsigned c = 0; c < PALETTE_COLORS; c++) {\n const rgba* imgBits = scanline + c * colorSize;\n\n for (unsigned i = 1; i < colorSize; i++) {\n if (imgBits[0] != imgBits[i]) {\n throw std::runtime_error(\"Custom Palette is invalid\");\n }\n }\n }\n\n \/\/ ensure first color is transparent\n if (scanline[0] != siFrameSet.transparentColor) {\n throw std::runtime_error(\"First color of custom palette \" + std::to_string(pal)\n + \" is not the transparent color\");\n }\n }\n\n inline void validateFirstUserSuppliedPalette() const\n {\n const unsigned colorSize = siFrameSet.palette.colorSize;\n\n vectorset colorSet = getColorsFromImage();\n const rgba* scanline = image.scanline(image.size().height - 1);\n\n for (unsigned i = 0; i < PALETTE_COLORS; i++) {\n const rgba c = scanline[i * colorSize];\n colorSet.erase(c);\n }\n\n if (colorSet.size() > 0) {\n std::stringstream out;\n out << \"Palette 0 is invalid (missing\";\n\n for (const rgba& c : colorSet) {\n out << \" \" << std::hex << std::setfill('0') << std::setw(6) << c.rgb();\n }\n out << \")\";\n\n throw std::runtime_error(out.str());\n }\n }\n\n inline void buildAutomaticPalette()\n {\n vectorset colors = getColorsFromImage();\n assert(colors.size() <= PALETTE_COLORS - 1);\n\n \/\/ Store palette in MetaSprite\n msFrameSet.palettes.emplace_back();\n Snes::Palette4bpp& palette = msFrameSet.palettes.back();\n\n _colorMap.insert({ siFrameSet.transparentColor, 0 });\n palette.color(0).setRgb(siFrameSet.transparentColor);\n\n int i = 1;\n for (auto& c : colors) {\n _colorMap.insert({ c, i });\n palette.color(i).setRgb(c);\n i++;\n }\n }\n};\n}\n}\n}\nFix crash in utsi2utms palette converter\/*\n * This file is part of the UnTech Editor Suite.\n * Copyright (c) 2016 - 2018, Marcus Rowe .\n * Distributed under The MIT License: https:\/\/opensource.org\/licenses\/MIT\n *\/\n\n#pragma once\n#include \"models\/common\/vectorset.h\"\n#include \"models\/metasprite\/metasprite.h\"\n#include \"models\/metasprite\/spriteimporter.h\"\n#include \n#include \n#include \n#include \n#include \n\nnamespace UnTech {\nnamespace MetaSprite {\nnamespace Utsi2UtmsPrivate {\n\nnamespace MS = UnTech::MetaSprite::MetaSprite;\nnamespace SI = UnTech::MetaSprite::SpriteImporter;\n\nclass PaletteConverter {\n const SI::FrameSet& siFrameSet;\n const Image& image;\n MS::FrameSet& msFrameSet;\n ErrorList& errorList;\n\n \/\/ Faster than std::unordered_map, only contains a max of 16 elements\n std::map _colorMap;\n\npublic:\n PaletteConverter(const SI::FrameSet& siFrameSet,\n const Image& image,\n MS::FrameSet& msFrameSet,\n ErrorList& errorList)\n : siFrameSet(siFrameSet)\n , image(image)\n , msFrameSet(msFrameSet)\n , errorList(errorList)\n , _colorMap()\n {\n }\n\n const auto& colorMap() const { return _colorMap; }\n\n void process()\n {\n try {\n if (siFrameSet.palette.usesUserSuppliedPalette()) {\n buildUserSuppliedPalettes();\n }\n else {\n buildAutomaticPalette();\n }\n }\n catch (const std::exception& ex) {\n errorList.addError(siFrameSet, ex.what());\n }\n }\n\nprivate:\n vectorset getColorsFromImage() const\n {\n assert(image.empty() == false);\n\n vectorset colors;\n\n for (const auto& siFrameIt : siFrameSet.frames) {\n const SI::Frame& siFrame = siFrameIt.second;\n\n for (const SI::FrameObject& obj : siFrame.objects) {\n unsigned lx = siFrame.location.aabb.x + obj.location.x;\n unsigned ly = siFrame.location.aabb.y + obj.location.y;\n\n for (unsigned y = 0; y < obj.sizePx(); y++) {\n const rgba* p = image.scanline(ly + y) + lx;\n\n for (unsigned x = 0; x < obj.sizePx(); x++) {\n const bool newColor = colors.insert(*p++);\n if (newColor) {\n if (colors.size() > PALETTE_COLORS) {\n throw std::runtime_error(\"Too many colors, expected a maximum of 16 colors\");\n }\n }\n }\n }\n }\n }\n\n \/\/ remove transparent from colors list\n auto tIt = colors.find(siFrameSet.transparentColor);\n if (tIt != colors.end()) {\n colors.erase(tIt);\n }\n else {\n errorList.addWarning(siFrameSet, \"Transparent color is not in frame objects\");\n\n if (colors.size() > (PALETTE_COLORS - 1)) {\n throw std::runtime_error(\"Too many colors, expected a maximum of 15 colors after removing transparency\");\n }\n }\n\n return colors;\n }\n\n inline void buildUserSuppliedPalettes()\n {\n validateUserSuppliedPalettes();\n\n const unsigned colorSize = siFrameSet.palette.colorSize;\n\n for (unsigned pal = 0; pal < siFrameSet.palette.nPalettes; pal++) {\n const unsigned yPos = image.size().height - pal * colorSize - 1;\n\n msFrameSet.palettes.emplace_back();\n Snes::Palette4bpp& palette = msFrameSet.palettes.back();\n\n for (unsigned i = 0; i < PALETTE_COLORS; i++) {\n const rgba c = image.getPixel(i * colorSize, yPos);\n\n palette.color(i).setRgb(c);\n\n if (pal == 0) {\n _colorMap.insert({ c, i });\n }\n }\n }\n }\n\n inline void validateUserSuppliedPalettes() const\n {\n const usize imageSize = image.size();\n const usize paletteSize = siFrameSet.palette.paletteSize();\n\n if (imageSize.width < paletteSize.width || imageSize.height < paletteSize.height) {\n throw std::runtime_error(\"Cannot load custom palette, image is too small\");\n }\n\n for (unsigned pal = 0; pal < siFrameSet.palette.nPalettes; pal++) {\n validateUserSuppliedPalette(pal);\n }\n\n validateFirstUserSuppliedPalette();\n }\n\n inline void validateUserSuppliedPalette(unsigned pal) const\n {\n const unsigned colorSize = siFrameSet.palette.colorSize;\n const unsigned yPos = image.size().height - pal * colorSize - 1;\n\n const rgba* scanline = image.scanline(yPos);\n\n \/\/ ensure the scanlines of the palette equal\n\n for (unsigned l = 1; l < colorSize; l++) {\n const rgba* linetoTest = image.scanline(yPos - l);\n\n if (std::memcmp(scanline, linetoTest, sizeof(rgba) * colorSize * PALETTE_COLORS) != 0) {\n throw std::runtime_error(\"Custom Palette is invalid A\");\n }\n }\n\n \/\/ ensure each of the palette colors are equally colored squares\n for (unsigned c = 0; c < PALETTE_COLORS; c++) {\n const rgba* imgBits = scanline + c * colorSize;\n\n for (unsigned i = 1; i < colorSize; i++) {\n if (imgBits[0] != imgBits[i]) {\n throw std::runtime_error(\"Custom Palette is invalid\");\n }\n }\n }\n\n \/\/ ensure first color is transparent\n if (scanline[0] != siFrameSet.transparentColor) {\n throw std::runtime_error(\"First color of custom palette \" + std::to_string(pal)\n + \" is not the transparent color\");\n }\n }\n\n inline void validateFirstUserSuppliedPalette() const\n {\n const unsigned colorSize = siFrameSet.palette.colorSize;\n\n vectorset colorSet = getColorsFromImage();\n assert(colorSet.size() <= PALETTE_COLORS - 1);\n\n const rgba* scanline = image.scanline(image.size().height - 1);\n\n for (unsigned i = 0; i < PALETTE_COLORS; i++) {\n const rgba c = scanline[i * colorSize];\n colorSet.erase(c);\n }\n\n if (colorSet.size() > 0) {\n std::stringstream out;\n out << \"Palette 0 is invalid (missing\";\n\n for (const rgba& c : colorSet) {\n out << \" \" << std::hex << std::setfill('0') << std::setw(6) << c.rgb();\n }\n out << \")\";\n\n throw std::runtime_error(out.str());\n }\n }\n\n inline void buildAutomaticPalette()\n {\n vectorset colors = getColorsFromImage();\n assert(colors.size() <= PALETTE_COLORS - 1);\n\n \/\/ Store palette in MetaSprite\n msFrameSet.palettes.emplace_back();\n Snes::Palette4bpp& palette = msFrameSet.palettes.back();\n\n _colorMap.insert({ siFrameSet.transparentColor, 0 });\n palette.color(0).setRgb(siFrameSet.transparentColor);\n\n int i = 1;\n for (auto& c : colors) {\n _colorMap.insert({ c, i });\n palette.color(i).setRgb(c);\n i++;\n }\n }\n};\n}\n}\n}\n<|endoftext|>"} {"text":"extern \"C\" {\n\n#include \"halide_hexagon_remote.h\"\n#include \n#include \n#include \n#include \n\n#define FARF_LOW 1\n#include \"HAP_farf.h\"\n\n}\n\n#include \"..\/HalideRuntime.h\"\n\n\nvoid halide_print(void *user_context, const char *str) {\n FARF(LOW, \"%s\", str);\n}\n\nvoid halide_error(void *user_context, const char *str) {\n halide_print(user_context, str);\n}\n\nvoid *halide_malloc(void *user_context, size_t x) {\n \/\/ Allocate enough space for aligning the pointer we return.\n const size_t alignment = 128;\n void *orig = malloc(x + alignment);\n if (orig == NULL) {\n \/\/ Will result in a failed assertion and a call to halide_error\n return NULL;\n }\n \/\/ We want to store the original pointer prior to the pointer we return.\n void *ptr = (void *)(((size_t)orig + alignment + sizeof(void*) - 1) & ~(alignment - 1));\n ((void **)ptr)[-1] = orig;\n return ptr;\n}\n\nvoid halide_free(void *user_context, void *ptr) {\n free(((void**)ptr)[-1]);\n}\n\nint halide_do_task(void *user_context, halide_task_t f, int idx,\n uint8_t *closure) {\n return f(user_context, idx, closure);\n}\n\nint halide_do_par_for(void *user_context, halide_task_t f,\n int min, int size, uint8_t *closure) {\n for (int x = min; x < min + size; x++) {\n int result = halide_do_task(user_context, f, x, closure);\n if (result) {\n return result;\n }\n }\n return 0;\n}\n\nstatic const int alignment = 4096;\n\nextern \"C\" {\n\nint halide_hexagon_remote_initialize_kernels(const unsigned char *code, int codeLen, int init_runtime_offset,\n halide_hexagon_remote_uintptr_t *module_ptr) {\n \/\/ Map some memory for the code and copy it in.\n int aligned_codeLen = (codeLen + alignment - 1) & ~(alignment - 1);\n void *executable = mmap(0, aligned_codeLen, PROT_READ | PROT_WRITE, MAP_ANON, -1, 0);\n if (executable == MAP_FAILED) {\n return -1;\n }\n memcpy(executable, code, codeLen);\n\n \/\/ Change memory to be executable (but not writable).\n if (mprotect(executable, aligned_codeLen, PROT_READ | PROT_EXEC) < 0) {\n munmap(executable, aligned_codeLen);\n return -1;\n }\n\n \/\/ Initialize the runtime. The Hexagon runtime can't call any\n \/\/ system functions (because we can't link them), so we put all\n \/\/ the implementations that need to do so here, and pass poiners\n \/\/ to them in here.\n typedef int (*init_runtime_t)(halide_malloc_t user_malloc,\n halide_free_t custom_free,\n halide_print_t print,\n halide_error_handler_t error_handler,\n halide_do_par_for_t do_par_for,\n halide_do_task_t do_task);\n init_runtime_t init_runtime = (init_runtime_t)((char *)executable + init_runtime_offset);\n int result = init_runtime(halide_malloc,\n halide_free,\n halide_print,\n halide_error,\n halide_do_par_for,\n halide_do_task);\n if (result != 0) {\n munmap(executable, aligned_codeLen);\n return result;\n }\n\n *module_ptr = (halide_hexagon_remote_uintptr_t)executable;\n return 0;\n}\n\nint halide_hexagon_remote_run(halide_hexagon_remote_uintptr_t module_ptr, int offset,\n const halide_hexagon_remote_buffer *arg_ptrs, int arg_ptrsLen,\n halide_hexagon_remote_buffer *outputs, int outputsLen) {\n \/\/ Get a pointer to the argv version of the pipeline.\n typedef int (*pipeline_argv_t)(void **);\n pipeline_argv_t pipeline = (pipeline_argv_t)(module_ptr + offset);\n\n \/\/ Construct a list of arguments.\n void **args = (void **)__builtin_alloca((arg_ptrsLen + outputsLen) * sizeof(void *));\n for (int i = 0; i < arg_ptrsLen; i++) {\n args[i] = arg_ptrs[i].data;\n }\n for (int i = 0; i < outputsLen; i++) {\n args[i + arg_ptrsLen] = outputs[i].data;\n }\n\n \/\/ Call the pipeline and return the result.\n return pipeline(args);\n}\n\nint halide_hexagon_remote_release_kernels(halide_hexagon_remote_uintptr_t module_ptr, int codeLen) {\n void *executable = (void *)module_ptr;\n codeLen = (codeLen + alignment - 1) & (alignment - 1);\n munmap(executable, codeLen);\n return 0;\n}\n\n} \/\/ extern \"C\"\nReduced confusion between two alignment constants.extern \"C\" {\n\n#include \"halide_hexagon_remote.h\"\n#include \n#include \n#include \n#include \n\n#define FARF_LOW 1\n#include \"HAP_farf.h\"\n\n}\n\n#include \"..\/HalideRuntime.h\"\n\n\nvoid halide_print(void *user_context, const char *str) {\n FARF(LOW, \"%s\", str);\n}\n\nvoid halide_error(void *user_context, const char *str) {\n halide_print(user_context, str);\n}\n\nvoid *halide_malloc(void *user_context, size_t x) {\n \/\/ Allocate enough space for aligning the pointer we return.\n const size_t alignment = 128;\n void *orig = malloc(x + alignment);\n if (orig == NULL) {\n \/\/ Will result in a failed assertion and a call to halide_error\n return NULL;\n }\n \/\/ We want to store the original pointer prior to the pointer we return.\n void *ptr = (void *)(((size_t)orig + alignment + sizeof(void*) - 1) & ~(alignment - 1));\n ((void **)ptr)[-1] = orig;\n return ptr;\n}\n\nvoid halide_free(void *user_context, void *ptr) {\n free(((void**)ptr)[-1]);\n}\n\nint halide_do_task(void *user_context, halide_task_t f, int idx,\n uint8_t *closure) {\n return f(user_context, idx, closure);\n}\n\nint halide_do_par_for(void *user_context, halide_task_t f,\n int min, int size, uint8_t *closure) {\n for (int x = min; x < min + size; x++) {\n int result = halide_do_task(user_context, f, x, closure);\n if (result) {\n return result;\n }\n }\n return 0;\n}\n\nextern \"C\" {\n\nconst int map_alignment = 4096;\n\nint halide_hexagon_remote_initialize_kernels(const unsigned char *code, int codeLen, int init_runtime_offset,\n halide_hexagon_remote_uintptr_t *module_ptr) {\n \/\/ Map some memory for the code and copy it in.\n int aligned_codeLen = (codeLen + map_alignment - 1) & ~(map_alignment - 1);\n void *executable = mmap(0, aligned_codeLen, PROT_READ | PROT_WRITE, MAP_ANON, -1, 0);\n if (executable == MAP_FAILED) {\n return -1;\n }\n memcpy(executable, code, codeLen);\n\n \/\/ Change memory to be executable (but not writable).\n if (mprotect(executable, aligned_codeLen, PROT_READ | PROT_EXEC) < 0) {\n munmap(executable, aligned_codeLen);\n return -1;\n }\n\n \/\/ Initialize the runtime. The Hexagon runtime can't call any\n \/\/ system functions (because we can't link them), so we put all\n \/\/ the implementations that need to do so here, and pass poiners\n \/\/ to them in here.\n typedef int (*init_runtime_t)(halide_malloc_t user_malloc,\n halide_free_t custom_free,\n halide_print_t print,\n halide_error_handler_t error_handler,\n halide_do_par_for_t do_par_for,\n halide_do_task_t do_task);\n init_runtime_t init_runtime = (init_runtime_t)((char *)executable + init_runtime_offset);\n int result = init_runtime(halide_malloc,\n halide_free,\n halide_print,\n halide_error,\n halide_do_par_for,\n halide_do_task);\n if (result != 0) {\n munmap(executable, aligned_codeLen);\n return result;\n }\n\n *module_ptr = (halide_hexagon_remote_uintptr_t)executable;\n return 0;\n}\n\nint halide_hexagon_remote_run(halide_hexagon_remote_uintptr_t module_ptr, int offset,\n const halide_hexagon_remote_buffer *arg_ptrs, int arg_ptrsLen,\n halide_hexagon_remote_buffer *outputs, int outputsLen) {\n \/\/ Get a pointer to the argv version of the pipeline.\n typedef int (*pipeline_argv_t)(void **);\n pipeline_argv_t pipeline = (pipeline_argv_t)(module_ptr + offset);\n\n \/\/ Construct a list of arguments.\n void **args = (void **)__builtin_alloca((arg_ptrsLen + outputsLen) * sizeof(void *));\n for (int i = 0; i < arg_ptrsLen; i++) {\n args[i] = arg_ptrs[i].data;\n }\n for (int i = 0; i < outputsLen; i++) {\n args[i + arg_ptrsLen] = outputs[i].data;\n }\n\n \/\/ Call the pipeline and return the result.\n return pipeline(args);\n}\n\nint halide_hexagon_remote_release_kernels(halide_hexagon_remote_uintptr_t module_ptr, int codeLen) {\n void *executable = (void *)module_ptr;\n codeLen = (codeLen + map_alignment - 1) & (map_alignment - 1);\n munmap(executable, codeLen);\n return 0;\n}\n\n} \/\/ extern \"C\"\n<|endoftext|>"} {"text":"\n#include \"yeseulWhitneyScene.h\"\n\nvoid yeseulWhitneyScene::setup(){\n \n setAuthor(\"Yeseul Song\");\n setOriginalArtist(\"John Whitney\");\n\n parameters.add(spinSpeed.set(\"spinSpeed\", 10, 20, 70));\n parameters.add(diffusionInterval.set(\"diffusionInterval\", 5, 5, 10));\n parameters.add(diffusionSize.set(\"diffusionSize\", 1.3, 1, 3));\n \n lastDiffusionTime = 0;\n \n integratedTime = 0;\n lastTime = 0;\n\n loadCode(\"scenes\/yeseulWhitneyScene\/exampleCode.cpp\");\n\n}\n\n\nvoid yeseulWhitneyScene::update(){\n \n}\n\n\nvoid yeseulWhitneyScene::draw(){\n \n ofPushMatrix();\n \n ofTranslate(dimensions.width\/2, dimensions.height\/2);\n \n drawPattern();\n \n diffusion();\n \n ofPopMatrix();\n \n}\n\n\nvoid yeseulWhitneyScene::drawPattern(){\n \n ofSetColor(255);\n ofFill();\n \n float now = getElapsedTimef();\n if (lastTime == 0) {\n lastTime = now;\n }\n float dt = now - lastTime;\n lastTime = now;\n \n integratedTime += spinSpeed * dt;\n float k = integratedTime;\n\n for (int r=0; r<35; r+=1) {\n ofRotate(k*sin(r));\n for (int a=0; a<20; a+=1) {\n ofRotate(360\/20);\n ofDrawCircle(0, r*10, 1);\n \n }\n }\n \n}\n\n\nvoid yeseulWhitneyScene::diffusion() {\n \n float t = getElapsedTimef();\n\n if (lastDiffusionTime == 0 || diffusionInterval <= t - lastDiffusionTime) {\n diffs.push_back(circlesDiffusion(t, diffusionSize));\n cout << \"add difff\" << diffusionInterval << endl;\n lastDiffusionTime = t;\n }\n \n for(int i = 0; i < diffs.size(); i++){\n if(diffs[i].bKill){\n cout << \"kill diff: \" << i << endl;\n diffs.erase(diffs.begin() + i);\n i--;\n }\n }\n \n for(int i = 0; i < diffs.size(); i++){\n diffs[i].draw(t);\n }\n}\n\nUpdate yeseulWhitneyScene.cpp\n#include \"yeseulWhitneyScene.h\"\n\nvoid yeseulWhitneyScene::setup(){\n \n setAuthor(\"Yeseul Song\");\n setOriginalArtist(\"John Whitney\");\n\n parameters.add(spinSpeed.set(\"spinSpeed\", 10, 10, 70));\n parameters.add(diffusionInterval.set(\"diffusionInterval\", 5, 5, 10));\n parameters.add(diffusionSize.set(\"diffusionSize\", 1.3, 1, 3));\n \n lastDiffusionTime = 0;\n \n integratedTime = 0;\n lastTime = 0;\n\n loadCode(\"scenes\/yeseulWhitneyScene\/exampleCode.cpp\");\n\n}\n\n\nvoid yeseulWhitneyScene::update(){\n \n}\n\n\nvoid yeseulWhitneyScene::draw(){\n \n ofPushMatrix();\n \n ofTranslate(dimensions.width\/2, dimensions.height\/2);\n \n drawPattern();\n \n diffusion();\n \n ofPopMatrix();\n \n}\n\n\nvoid yeseulWhitneyScene::drawPattern(){\n \n ofSetColor(255);\n ofFill();\n \n float now = getElapsedTimef();\n if (lastTime == 0) {\n lastTime = now;\n }\n float dt = now - lastTime;\n lastTime = now;\n \n integratedTime += spinSpeed * dt;\n float k = integratedTime;\n\n for (int r=0; r<35; r+=1) {\n ofRotate(k*sin(r));\n for (int a=0; a<20; a+=1) {\n ofRotate(360\/20);\n ofDrawCircle(0, r*10, 1);\n \n }\n }\n \n}\n\n\nvoid yeseulWhitneyScene::diffusion() {\n \n float t = getElapsedTimef();\n\n if (lastDiffusionTime == 0 || diffusionInterval <= t - lastDiffusionTime) {\n diffs.push_back(circlesDiffusion(t, diffusionSize));\n cout << \"add difff\" << diffusionInterval << endl;\n lastDiffusionTime = t;\n }\n \n for(int i = 0; i < diffs.size(); i++){\n if(diffs[i].bKill){\n cout << \"kill diff: \" << i << endl;\n diffs.erase(diffs.begin() + i);\n i--;\n }\n }\n \n for(int i = 0; i < diffs.size(); i++){\n diffs[i].draw(t);\n }\n}\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2015 SeNDA\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\/**\n * FILE BundleProcessor.cpp\n * AUTHOR Blackcatn13\n * DATE Dec 17, 2015\n * VERSION 1\n *\n *\/\n\n#include \"Node\/BundleProcessor\/BundleProcessor.h\"\n#include \n#include \n#include \n#include \"Node\/BundleQueue\/BundleQueue.h\"\n#include \"Node\/Neighbour\/NeighbourTable.h\"\n#include \"Node\/Config.h\"\n#include \"Node\/BundleQueue\/BundleContainer.h\"\n#include \"Bundle\/Bundle.h\"\n\nBundleProcessor::BundleProcessor(\n Config config, std::shared_ptr bundleQueue,\n std::shared_ptr neighbourTable\n \/*, std::shared_ptr listeningAppsTable*\/)\n : m_config(config),\n m_bundleQueue(bundleQueue),\n m_neighbourTable(neighbourTable) {\n}\n\nBundleProcessor::~BundleProcessor() {\n}\n\nvoid BundleProcessor::processBundles() {\n}\n\nvoid BundleProcessor::receiveBundles() {\n}\n\nvoid dispatch(std::shared_ptr bundle,\n std::vector destinations) {\n}\n\nvoid forward(std::shared_ptr bundle, std::vector nextHop) {\n}\n\nvoid discard(std::shared_ptr bundle) {\n}\n\nvoid restore(std::shared_ptr bundle) {\n}\nImplements constructor and processBundles.\/*\n * Copyright (c) 2015 SeNDA\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\/**\n * FILE BundleProcessor.cpp\n * AUTHOR Blackcatn13\n * DATE Dec 17, 2015\n * VERSION 1\n *\n *\/\n\n#include \"Node\/BundleProcessor\/BundleProcessor.h\"\n#include \n#include \n#include \n#include \n#include \"Node\/BundleQueue\/BundleQueue.h\"\n#include \"Node\/Neighbour\/NeighbourTable.h\"\n#include \"Node\/Config.h\"\n#include \"Node\/BundleQueue\/BundleContainer.h\"\n#include \"Bundle\/Bundle.h\"\n#include \"Utils\/globals.h\"\n\nBundleProcessor::BundleProcessor(\n Config config, std::shared_ptr bundleQueue,\n std::shared_ptr neighbourTable\n \/*, std::shared_ptr listeningAppsTable*\/)\n : m_config(config),\n m_bundleQueue(bundleQueue),\n m_neighbourTable(neighbourTable) {\n std::thread t = std::thread(&BundleProcessor::processBundles, this);\n t.detach();\n t = std::thread(&BundleProcessor::receiveBundles, this);\n t.detach();\n}\n\nBundleProcessor::~BundleProcessor() {\n}\n\nvoid BundleProcessor::processBundles() {\n while (!g_stop.load()) {\n try {\n std::shared_ptr bc = m_bundleQueue->dequeue();\n processBundle(bc);\n } catch (const std::exception &e) {\n }\n }\n}\n\nvoid BundleProcessor::receiveBundles() {\n}\n\nvoid BundleProcessor::dispatch(std::shared_ptr bundle,\n std::vector destinations) {\n}\n\nvoid BundleProcessor::forward(std::shared_ptr bundle,\n std::vector nextHop) {\n}\n\nvoid BundleProcessor::discard(std::shared_ptr bundle) {\n}\n\nvoid BundleProcessor::restore(std::shared_ptr bundle) {\n}\n<|endoftext|>"} {"text":"\/\/ Important do not use this FilterTask for final Filtered AOD productions!\n\/\/ Due to the variability of the used config file, it is to easy to loose track of the used settings!\n\nAliAnalysisTask *AddTask_caklein_LMEEFilter_PbPb(\n TString cfg=\"ConfigLMEE_nano_PbPb.C\",\n Bool_t gridconf=kFALSE,\n TString period=\"\",\n Bool_t storeLS = kFALSE,\n Bool_t hasMC_aod = kFALSE,\n \/\/ ULong64_t triggers=AliVEvent::kMB+AliVEvent::kCentral+AliVEvent::kSemiCentral+AliVEvent::kEMCEGA+AliVEvent::kEMCEJE\n ULong64_t triggers=AliVEvent::kINT7\n ){\n\n \/\/get the current analysis manager\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n Error(\"AddTaskLMEEFilter\", \"No analysis manager found.\");\n return 0;\n }\n\n \/\/check for output aod handler\n if (!mgr->GetOutputEventHandler()||mgr->GetOutputEventHandler()->IsA()!=AliAODHandler::Class()) {\n Warning(\"AddTaskLMEEFilter\",\"No AOD output handler available. Not adding the task!\");\n return 0;\n }\n\n \/\/Do we have an MC handler?\n Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0)||hasMC_aod;\n\n \/\/Do we run on AOD?\n Bool_t isAOD=mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class();\n\n \/\/Allow merging of the filtered aods on grid trains\n if(mgr->GetGridHandler()) {\n printf(\" SET MERGE FILTERED AODs \\n\");\n \/\/mgr->GetGridHandler()->SetMergeAOD(kTRUE);\n }\n\n\n TString configFile(\"\");\n printf(\"pwd: %s \\n\",gSystem->pwd());\n if(cfg.IsNull()) cfg=\"ConfigLMEE_nano_PbPb.C\";\n\n TString alienPath(\"alien:\/\/\/alice\/cern.ch\/user\/c\/cklein\/PWGDQ\/dielectron\/macrosLMEE\/\");\n TString alirootPath(\"$ALICE_PHYSICS\/PWGDQ\/dielectron\/macrosLMEE\/\");\n\n \/\/\/\/\/\/\/\/\/\/ >>>>>>>>>> alien config\n if(gridconf) {\n if(!gSystem->Exec(Form(\"alien_cp %s\/%s .\",alienPath.Data(),cfg.Data()))) {\n gSystem->Exec(Form(\"ls -l %s\",gSystem->pwd()));\n configFile=gSystem->pwd();\n }\n else {\n printf(\"ERROR: couldn't copy file %s\/%s from grid \\n\", alienPath.Data(),cfg.Data() );\n return;\n }\n }\n \/\/\/\/\/\/\/\/\/ >>>>>>>>> aliroot config\n else if(!gridconf) configFile=alirootPath.Data();\n \/\/\/\/\/\/\/\/\/ add config to path\n configFile+=\"\/\";\n configFile+=cfg.Data();\n\n \/\/load dielectron configuration file (only once)\n TString checkconfig=\"ConfigLMEE_nano_PbPb\";\n if (!gROOT->GetListOfGlobalFunctions()->FindObject(checkconfig.Data()))\n gROOT->LoadMacro(configFile.Data());\n\n AliDielectron *diEle=ConfigLMEE_nano_PbPb(0,hasMC,period);\n\n if(isAOD) {\n \/\/add options to AliAODHandler to duplicate input event\n AliAODHandler *aodHandler = (AliAODHandler*)mgr->GetOutputEventHandler();\n aodHandler->SetCreateNonStandardAOD();\n aodHandler->SetNeedsHeaderReplication();\n\n if(!period.Contains(\"LHC10h\")) aodHandler->SetNeedsTOFHeaderReplication();\n aodHandler->SetNeedsVZEROReplication();\n \/*aodHandler->SetNeedsTracksBranchReplication();\n aodHandler->SetNeedsCaloClustersBranchReplication();\n aodHandler->SetNeedsVerticesBranchReplication();\n aodHandler->SetNeedsCascadesBranchReplication();\n aodHandler->SetNeedsTrackletsBranchReplication();\n aodHandler->SetNeedsPMDClustersBranchReplication();\n aodHandler->SetNeedsJetsBranchReplication();\n aodHandler->SetNeedsFMDClustersBranchReplication();\n \/\/aodHandler->SetNeedsMCParticlesBranchReplication();\n aodHandler->SetNeedsDimuonsBranchReplication();*\/ \/\/ deactivates several branches\n \/\/ if(hasMC) aodHandler->SetNeedsV0sBranchReplication();\n if(hasMC) aodHandler->SetNeedsMCParticlesBranchReplication();\n diEle->SetHasMC(hasMC);\n }\n\n \/\/Create task and add it to the analysis manager\n AliAnalysisTaskDielectronFilter *task=new AliAnalysisTaskDielectronFilter(\"LMEE_DielectronFilter\");\n task->SetTriggerMask(triggers);\n if (!hasMC) task->UsePhysicsSelection();\n\n\n task->SetDielectron(diEle);\n if(storeLS) task->SetStoreLikeSignCandidates(storeLS);\n task->SetCreateNanoAODs(kTRUE);\n task->SetStoreEventplanes(kTRUE);\n task->SetStoreEventsWithSingleTracks(kTRUE); \n \/\/ task->SetStoreHeader(kTRUE);\n mgr->AddTask(task);\n\n \/\/----------------------\n \/\/create data containers\n \/\/----------------------\n\n\n TString containerName = mgr->GetCommonFileName();\n containerName += \":PWGDQ_dielectronFilter\";\n\n \/\/create output container\n\n AliAnalysisDataContainer *cOutputHist1 =\n mgr->CreateContainer(\"LMEE_FilterQA\",\n THashList::Class(),\n AliAnalysisManager::kOutputContainer,\n containerName.Data());\n\n AliAnalysisDataContainer *cOutputHist2 =\n mgr->CreateContainer(\"LMEE_FilterEventStat\",\n TH1D::Class(),\n AliAnalysisManager::kOutputContainer,\n containerName.Data());\n\n\n mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(task, 0, mgr->GetCommonOutputContainer());\n mgr->ConnectOutput(task, 1, cOutputHist1);\n mgr->ConnectOutput(task, 2, cOutputHist2);\n\n return task;\n}\ncorrecting macro name\/\/ Important do not use this FilterTask for final Filtered AOD productions!\n\/\/ Due to the variability of the used config file, it is to easy to loose track of the used settings!\n\nAliAnalysisTask *AddTaskLMEEFilter_PbPb(\n TString cfg=\"ConfigLMEE_nano_PbPb.C\",\n Bool_t gridconf=kFALSE,\n TString period=\"\",\n Bool_t storeLS = kFALSE,\n Bool_t hasMC_aod = kFALSE,\n \/\/ ULong64_t triggers=AliVEvent::kMB+AliVEvent::kCentral+AliVEvent::kSemiCentral+AliVEvent::kEMCEGA+AliVEvent::kEMCEJE\n ULong64_t triggers=AliVEvent::kINT7\n ){\n\n \/\/get the current analysis manager\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n Error(\"AddTaskLMEEFilter\", \"No analysis manager found.\");\n return 0;\n }\n\n \/\/check for output aod handler\n if (!mgr->GetOutputEventHandler()||mgr->GetOutputEventHandler()->IsA()!=AliAODHandler::Class()) {\n Warning(\"AddTaskLMEEFilter\",\"No AOD output handler available. Not adding the task!\");\n return 0;\n }\n\n \/\/Do we have an MC handler?\n Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0)||hasMC_aod;\n\n \/\/Do we run on AOD?\n Bool_t isAOD=mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class();\n\n \/\/Allow merging of the filtered aods on grid trains\n if(mgr->GetGridHandler()) {\n printf(\" SET MERGE FILTERED AODs \\n\");\n \/\/mgr->GetGridHandler()->SetMergeAOD(kTRUE);\n }\n\n\n TString configFile(\"\");\n printf(\"pwd: %s \\n\",gSystem->pwd());\n if(cfg.IsNull()) cfg=\"ConfigLMEE_nano_PbPb.C\";\n\n TString alienPath(\"alien:\/\/\/alice\/cern.ch\/user\/c\/cklein\/PWGDQ\/dielectron\/macrosLMEE\/\");\n TString alirootPath(\"$ALICE_PHYSICS\/PWGDQ\/dielectron\/macrosLMEE\/\");\n\n \/\/\/\/\/\/\/\/\/\/ >>>>>>>>>> alien config\n if(gridconf) {\n if(!gSystem->Exec(Form(\"alien_cp %s\/%s .\",alienPath.Data(),cfg.Data()))) {\n gSystem->Exec(Form(\"ls -l %s\",gSystem->pwd()));\n configFile=gSystem->pwd();\n }\n else {\n printf(\"ERROR: couldn't copy file %s\/%s from grid \\n\", alienPath.Data(),cfg.Data() );\n return;\n }\n }\n \/\/\/\/\/\/\/\/\/ >>>>>>>>> aliroot config\n else if(!gridconf) configFile=alirootPath.Data();\n \/\/\/\/\/\/\/\/\/ add config to path\n configFile+=\"\/\";\n configFile+=cfg.Data();\n\n \/\/load dielectron configuration file (only once)\n TString checkconfig=\"ConfigLMEE_nano_PbPb\";\n if (!gROOT->GetListOfGlobalFunctions()->FindObject(checkconfig.Data()))\n gROOT->LoadMacro(configFile.Data());\n\n AliDielectron *diEle=ConfigLMEE_nano_PbPb(0,hasMC,period);\n\n if(isAOD) {\n \/\/add options to AliAODHandler to duplicate input event\n AliAODHandler *aodHandler = (AliAODHandler*)mgr->GetOutputEventHandler();\n aodHandler->SetCreateNonStandardAOD();\n aodHandler->SetNeedsHeaderReplication();\n\n if(!period.Contains(\"LHC10h\")) aodHandler->SetNeedsTOFHeaderReplication();\n aodHandler->SetNeedsVZEROReplication();\n \/*aodHandler->SetNeedsTracksBranchReplication();\n aodHandler->SetNeedsCaloClustersBranchReplication();\n aodHandler->SetNeedsVerticesBranchReplication();\n aodHandler->SetNeedsCascadesBranchReplication();\n aodHandler->SetNeedsTrackletsBranchReplication();\n aodHandler->SetNeedsPMDClustersBranchReplication();\n aodHandler->SetNeedsJetsBranchReplication();\n aodHandler->SetNeedsFMDClustersBranchReplication();\n \/\/aodHandler->SetNeedsMCParticlesBranchReplication();\n aodHandler->SetNeedsDimuonsBranchReplication();*\/ \/\/ deactivates several branches\n \/\/ if(hasMC) aodHandler->SetNeedsV0sBranchReplication();\n if(hasMC) aodHandler->SetNeedsMCParticlesBranchReplication();\n diEle->SetHasMC(hasMC);\n }\n\n \/\/Create task and add it to the analysis manager\n AliAnalysisTaskDielectronFilter *task=new AliAnalysisTaskDielectronFilter(\"LMEE_DielectronFilter\");\n task->SetTriggerMask(triggers);\n if (!hasMC) task->UsePhysicsSelection();\n\n\n task->SetDielectron(diEle);\n if(storeLS) task->SetStoreLikeSignCandidates(storeLS);\n task->SetCreateNanoAODs(kTRUE);\n task->SetStoreEventplanes(kTRUE);\n task->SetStoreEventsWithSingleTracks(kTRUE); \n \/\/ task->SetStoreHeader(kTRUE);\n mgr->AddTask(task);\n\n \/\/----------------------\n \/\/create data containers\n \/\/----------------------\n\n\n TString containerName = mgr->GetCommonFileName();\n containerName += \":PWGDQ_dielectronFilter\";\n\n \/\/create output container\n\n AliAnalysisDataContainer *cOutputHist1 =\n mgr->CreateContainer(\"LMEE_FilterQA\",\n THashList::Class(),\n AliAnalysisManager::kOutputContainer,\n containerName.Data());\n\n AliAnalysisDataContainer *cOutputHist2 =\n mgr->CreateContainer(\"LMEE_FilterEventStat\",\n TH1D::Class(),\n AliAnalysisManager::kOutputContainer,\n containerName.Data());\n\n\n mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(task, 0, mgr->GetCommonOutputContainer());\n mgr->ConnectOutput(task, 1, cOutputHist1);\n mgr->ConnectOutput(task, 2, cOutputHist2);\n\n return task;\n}\n<|endoftext|>"} {"text":"INTEGRATION: CWS tl01 (1.2.38); FILE MERGED 2004\/04\/20 14:41:59 tl 1.2.38.5: RESYNC: (1.2-1.3); FILE MERGED 2004\/04\/02 10:29:22 tl 1.2.38.4: #110762# change in Hangul\/Hanja text conversion API 2004\/03\/22 11:18:21 tl 1.2.38.3: #111082# eDirection for Hangul\/Hanja conversion fixed 2003\/07\/31 10:57:30 tl 1.2.38.2: #110762# make use of Hangul\/Hanja user dictionaries 2003\/07\/31 10:56:09 tl 1.2.38.1: #110763# make use of Hangul\/Hanja user dictionaries<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/perv\/p9_set_fsi_gp_shadow.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/------------------------------------------------------------------------------\n\/\/\/ @file p9_set_fsi_gp_shadow.C\n\/\/\/\n\/\/\/ @brief --IPL step 0.8 proc_prep_ipl\n\/\/------------------------------------------------------------------------------\n\/\/ *HWP HW Owner : Anusha Reddy Rangareddygari \n\/\/ *HWP HW Backup Owner : Srinivas V Naga \n\/\/ *HWP FW Owner : Brian Silver \n\/\/ *HWP Team : Perv\n\/\/ *HWP Level : 2\n\/\/ *HWP Consumed by : SBE\n\/\/------------------------------------------------------------------------------\n\n\n\/\/## auto_generated\n#include \"p9_set_fsi_gp_shadow.H\"\n\/\/## auto_generated\n#include \"p9_const_common.H\"\n\n#include \n#include \n\n\nfapi2::ReturnCode p9_set_fsi_gp_shadow(const\n fapi2::Target& i_target_chip)\n{\n fapi2::buffer l_read_attr;\n fapi2::buffer l_cfam_data;\n FAPI_INF(\"p9_set_fsi_gp_shadow: Entering ...\");\n\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_FSI_GP_SHADOWS_OVERWRITE, i_target_chip,\n l_read_attr));\n\n if ( l_read_attr )\n {\n FAPI_DBG(\"Setting flush values for root_ctrl_copy and perv_ctrl_copy registers\");\n \/\/Setting ROOT_CTRL0_COPY register value\n \/\/CFAM.ROOT_CTRL0_COPY = p9SetFsiGpShadow::ROOT_CTRL0_FLUSHVALUE\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL0_COPY_FSI,\n p9SetFsiGpShadow::ROOT_CTRL0_FLUSHVALUE));\n\n \/\/Setting ROOT_CTRL1_COPY register value\n \/\/CFAM.ROOT_CTRL1_COPY = p9SetFsiGpShadow::ROOT_CTRL1_FLUSHVALUE\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL1_COPY_FSI,\n p9SetFsiGpShadow::ROOT_CTRL1_FLUSHVALUE));\n\n \/\/Setting ROOT_CTRL2_COPY register value\n \/\/CFAM.ROOT_CTRL2_COPY = p9SetFsiGpShadow::ROOT_CTRL2_FLUSHVALUE\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL2_COPY_FSI,\n p9SetFsiGpShadow::ROOT_CTRL2_FLUSHVALUE));\n\n \/\/Setting ROOT_CTRL3_COPY register value\n \/\/CFAM.ROOT_CTRL3_COPY = p9SetFsiGpShadow::ROOT_CTRL3_FLUSHVALUE\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL3_COPY_FSI,\n p9SetFsiGpShadow::ROOT_CTRL3_FLUSHVALUE));\n\n \/\/Setting ROOT_CTRL4_COPY register value\n \/\/CFAM.ROOT_CTRL4_COPY = p9SetFsiGpShadow::ROOT_CTRL4_FLUSHVALUE\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL4_COPY_FSI,\n p9SetFsiGpShadow::ROOT_CTRL4_FLUSHVALUE));\n\n \/\/Setting ROOT_CTRL5_COPY register value\n \/\/CFAM.ROOT_CTRL5_COPY = p9SetFsiGpShadow::ROOT_CTRL5_FLUSHVALUE\n FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL5_COPY_FSI,\n l_cfam_data));\n l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL5_MASK) |\n p9SetFsiGpShadow::ROOT_CTRL5_FLUSHVALUE;\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL5_COPY_FSI,\n l_cfam_data));\n\n \/\/Setting ROOT_CTRL6_COPY register value\n \/\/CFAM.ROOT_CTRL6_COPY = p9SetFsiGpShadow::ROOT_CTRL6_FLUSHVALUE\n FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL6_COPY_FSI,\n l_cfam_data));\n l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL6_MASK) |\n p9SetFsiGpShadow::ROOT_CTRL6_FLUSHVALUE;\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL6_COPY_FSI,\n l_cfam_data));\n\n \/\/Setting ROOT_CTRL7_COPY register value\n \/\/CFAM.ROOT_CTRL7_COPY = p9SetFsiGpShadow::ROOT_CTRL7_FLUSHVALUE\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL7_COPY_FSI,\n p9SetFsiGpShadow::ROOT_CTRL7_FLUSHVALUE));\n\n \/\/Setting ROOT_CTRL8_COPY register value\n \/\/CFAM.ROOT_CTRL8_COPY = p9SetFsiGpShadow::ROOT_CTRL8_FLUSHVALUE\n FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL8_COPY_FSI,\n l_cfam_data));\n l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL8_MASK) |\n p9SetFsiGpShadow::ROOT_CTRL8_FLUSHVALUE;\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL8_COPY_FSI,\n l_cfam_data));\n\n \/\/Setting PERV_CTRL0_COPY register value\n \/\/CFAM.PERV_CTRL0_COPY = p9SetFsiGpShadow::PERV_CTRL0_FLUSHVALUE\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_PERV_CTRL0_COPY_FSI,\n p9SetFsiGpShadow::PERV_CTRL0_FLUSHVALUE));\n\n \/\/Setting PERV_CTRL1_COPY register value\n \/\/CFAM.PERV_CTRL1_COPY = p9SetFsiGpShadow::PERV_CTRL1_FLUSHVALUE\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_PERV_CTRL1_COPY_FSI,\n p9SetFsiGpShadow::PERV_CTRL1_FLUSHVALUE));\n }\n\n \/* Write the value of FUSED_CORE_MODE into PERV_CTRL0(23) regardless of chip EC; the bit is nonfunctional on Nimbus DD1 *\/\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FUSED_CORE_MODE, fapi2::Target(), l_read_attr));\n FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_PERV_CTRL0_COPY_FSI, l_cfam_data));\n\n if (l_read_attr)\n {\n l_cfam_data.setBit();\n }\n else\n {\n l_cfam_data.clearBit();\n }\n\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_PERV_CTRL0_COPY_FSI, l_cfam_data));\n\n FAPI_INF(\"p9_set_fsi_gp_shadow: Exiting ...\");\n\nfapi_try_exit:\n return fapi2::current_err;\n\n}\nUpdate hardware procedure metadata\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/perv\/p9_set_fsi_gp_shadow.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/------------------------------------------------------------------------------\n\/\/\/ @file p9_set_fsi_gp_shadow.C\n\/\/\/\n\/\/\/ @brief --IPL step 0.8 proc_prep_ipl\n\/\/------------------------------------------------------------------------------\n\/\/ *HWP HW Owner : Anusha Reddy Rangareddygari \n\/\/ *HWP HW Backup Owner : Srinivas V Naga \n\/\/ *HWP FW Owner : Brian Silver \n\/\/ *HWP Team : Perv\n\/\/ *HWP Level : 3\n\/\/ *HWP Consumed by : SBE\n\/\/------------------------------------------------------------------------------\n\n\n\/\/## auto_generated\n#include \"p9_set_fsi_gp_shadow.H\"\n\/\/## auto_generated\n#include \"p9_const_common.H\"\n\n#include \n#include \n\n\nfapi2::ReturnCode p9_set_fsi_gp_shadow(const\n fapi2::Target& i_target_chip)\n{\n fapi2::buffer l_read_attr;\n fapi2::buffer l_cfam_data;\n FAPI_INF(\"p9_set_fsi_gp_shadow: Entering ...\");\n\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_FSI_GP_SHADOWS_OVERWRITE, i_target_chip,\n l_read_attr));\n\n if ( l_read_attr )\n {\n FAPI_DBG(\"Setting flush values for root_ctrl_copy and perv_ctrl_copy registers\");\n \/\/Setting ROOT_CTRL0_COPY register value\n \/\/CFAM.ROOT_CTRL0_COPY = p9SetFsiGpShadow::ROOT_CTRL0_FLUSHVALUE\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL0_COPY_FSI,\n p9SetFsiGpShadow::ROOT_CTRL0_FLUSHVALUE));\n\n \/\/Setting ROOT_CTRL1_COPY register value\n \/\/CFAM.ROOT_CTRL1_COPY = p9SetFsiGpShadow::ROOT_CTRL1_FLUSHVALUE\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL1_COPY_FSI,\n p9SetFsiGpShadow::ROOT_CTRL1_FLUSHVALUE));\n\n \/\/Setting ROOT_CTRL2_COPY register value\n \/\/CFAM.ROOT_CTRL2_COPY = p9SetFsiGpShadow::ROOT_CTRL2_FLUSHVALUE\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL2_COPY_FSI,\n p9SetFsiGpShadow::ROOT_CTRL2_FLUSHVALUE));\n\n \/\/Setting ROOT_CTRL3_COPY register value\n \/\/CFAM.ROOT_CTRL3_COPY = p9SetFsiGpShadow::ROOT_CTRL3_FLUSHVALUE\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL3_COPY_FSI,\n p9SetFsiGpShadow::ROOT_CTRL3_FLUSHVALUE));\n\n \/\/Setting ROOT_CTRL4_COPY register value\n \/\/CFAM.ROOT_CTRL4_COPY = p9SetFsiGpShadow::ROOT_CTRL4_FLUSHVALUE\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL4_COPY_FSI,\n p9SetFsiGpShadow::ROOT_CTRL4_FLUSHVALUE));\n\n \/\/Setting ROOT_CTRL5_COPY register value\n \/\/CFAM.ROOT_CTRL5_COPY = p9SetFsiGpShadow::ROOT_CTRL5_FLUSHVALUE\n FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL5_COPY_FSI,\n l_cfam_data));\n l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL5_MASK) |\n p9SetFsiGpShadow::ROOT_CTRL5_FLUSHVALUE;\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL5_COPY_FSI,\n l_cfam_data));\n\n \/\/Setting ROOT_CTRL6_COPY register value\n \/\/CFAM.ROOT_CTRL6_COPY = p9SetFsiGpShadow::ROOT_CTRL6_FLUSHVALUE\n FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL6_COPY_FSI,\n l_cfam_data));\n l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL6_MASK) |\n p9SetFsiGpShadow::ROOT_CTRL6_FLUSHVALUE;\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL6_COPY_FSI,\n l_cfam_data));\n\n \/\/Setting ROOT_CTRL7_COPY register value\n \/\/CFAM.ROOT_CTRL7_COPY = p9SetFsiGpShadow::ROOT_CTRL7_FLUSHVALUE\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL7_COPY_FSI,\n p9SetFsiGpShadow::ROOT_CTRL7_FLUSHVALUE));\n\n \/\/Setting ROOT_CTRL8_COPY register value\n \/\/CFAM.ROOT_CTRL8_COPY = p9SetFsiGpShadow::ROOT_CTRL8_FLUSHVALUE\n FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL8_COPY_FSI,\n l_cfam_data));\n l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL8_MASK) |\n p9SetFsiGpShadow::ROOT_CTRL8_FLUSHVALUE;\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL8_COPY_FSI,\n l_cfam_data));\n\n \/\/Setting PERV_CTRL0_COPY register value\n \/\/CFAM.PERV_CTRL0_COPY = p9SetFsiGpShadow::PERV_CTRL0_FLUSHVALUE\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_PERV_CTRL0_COPY_FSI,\n p9SetFsiGpShadow::PERV_CTRL0_FLUSHVALUE));\n\n \/\/Setting PERV_CTRL1_COPY register value\n \/\/CFAM.PERV_CTRL1_COPY = p9SetFsiGpShadow::PERV_CTRL1_FLUSHVALUE\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_PERV_CTRL1_COPY_FSI,\n p9SetFsiGpShadow::PERV_CTRL1_FLUSHVALUE));\n }\n\n \/* Write the value of FUSED_CORE_MODE into PERV_CTRL0(23) regardless of chip EC; the bit is nonfunctional on Nimbus DD1 *\/\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FUSED_CORE_MODE, fapi2::Target(), l_read_attr));\n FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_PERV_CTRL0_COPY_FSI, l_cfam_data));\n\n if (l_read_attr)\n {\n l_cfam_data.setBit();\n }\n else\n {\n l_cfam_data.clearBit();\n }\n\n FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_PERV_CTRL0_COPY_FSI, l_cfam_data));\n\n FAPI_INF(\"p9_set_fsi_gp_shadow: Exiting ...\");\n\nfapi_try_exit:\n return fapi2::current_err;\n\n}\n<|endoftext|>"} {"text":"ProjectionToPlaneMultiMapping: minor improvments<|endoftext|>"} {"text":"\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \n#include \n#include \n#include \n\n#include \"cyber\/common\/file.h\"\n#include \"cyber\/common\/log.h\"\n#include \"gflags\/gflags.h\"\n#include \"modules\/common\/proto\/error_code.pb.h\"\n#include \"modules\/common\/time\/time.h\"\n#include \"modules\/common\/util\/factory.h\"\n#include \"modules\/drivers\/canbus\/can_client\/can_client.h\"\n#include \"modules\/drivers\/canbus\/can_client\/can_client_factory.h\"\n#include \"modules\/drivers\/canbus\/common\/byte.h\"\n#include \"modules\/drivers\/canbus\/proto\/can_card_parameter.pb.h\"\n\nDEFINE_bool(only_one_send, false, \"only send test.\");\nDEFINE_string(can_client_conf_file_a,\n \"modules\/canbus\/conf\/can_client_conf_a.pb.txt\",\n \"can client conf for client a\");\nDEFINE_string(can_client_conf_file_b,\n \"modules\/canbus\/conf\/can_client_conf_b.pb.txt\",\n \"can client conf for client b\");\nDEFINE_int64(agent_mutual_send_frames, 1000, \"Every agent send frame num\");\n\nconst int32_t MAX_CAN_SEND_FRAME_LEN = 1;\nconst int32_t MAX_CAN_RECV_FRAME_LEN = 10;\n\nnamespace apollo {\nnamespace drivers {\nnamespace canbus {\n\nstruct TestCanParam {\n CANCardParameter conf;\n bool is_first_agent = false;\n int32_t recv_cnt = 0;\n int32_t recv_err_cnt = 0;\n int32_t send_cnt = 0;\n int32_t send_err_cnt = 0;\n int32_t send_lost_cnt = 0;\n int32_t send_time = 0;\n int32_t recv_time = 0;\n CanClient *can_client = nullptr;\n\n TestCanParam() = default;\n\n void print() {\n AINFO << \"conf: \" << conf.ShortDebugString()\n << \", total send: \" << send_cnt + send_err_cnt << \"\/\"\n << FLAGS_agent_mutual_send_frames << \", send_ok: \" << send_cnt\n << \" , send_err_cnt: \" << send_err_cnt\n << \", send_lost_cnt: \" << send_lost_cnt << \", recv_cnt: \" << recv_cnt\n << \", send_time: \" << send_time << \", recv_time: \" << recv_time;\n }\n};\n\nclass CanAgent {\n public:\n explicit CanAgent(TestCanParam *param_ptr) : param_ptr_(param_ptr) {}\n\n TestCanParam *param_ptr() { return param_ptr_; }\n\n CanAgent *other_agent() { return other_agent_; }\n\n bool Start() {\n thread_recv_.reset(new std::thread([this] { RecvThreadFunc(); }));\n if (thread_recv_ == nullptr) {\n AERROR << \"Unable to create recv thread.\";\n return false;\n }\n thread_send_.reset(new std::thread([this] { SendThreadFunc(); }));\n if (thread_send_ == nullptr) {\n AERROR << \"Unable to create send thread.\";\n return false;\n }\n return true;\n }\n\n void SendThreadFunc() {\n using common::ErrorCode;\n using common::time::AsInt64;\n using common::time::Clock;\n using common::time::micros;\n AINFO << \"Send thread starting...\";\n TestCanParam *param = param_ptr();\n CanClient *client = param->can_client;\n std::vector frames;\n frames.resize(MAX_CAN_SEND_FRAME_LEN);\n\n int32_t count = 0;\n int32_t start_id = 0;\n int32_t end_id = 0;\n int32_t id = 0;\n if (param->is_first_agent) {\n start_id = 1;\n end_id = 128;\n } else {\n start_id = 129;\n end_id = start_id + 127;\n }\n id = start_id;\n int32_t send_id = id;\n AINFO << \"port:\" << param->conf.ShortDebugString()\n << \", start_id:\" << start_id << \", end_id:\" << end_id;\n\n \/\/ wait for other agent receiving is ok.\n while (!other_agent()->is_receiving()) {\n std::this_thread::yield();\n }\n int64_t start = AsInt64(Clock::Now());\n while (true) {\n \/\/ param->print();\n if (count >= FLAGS_agent_mutual_send_frames) {\n break;\n }\n for (int32_t i = 0; i < MAX_CAN_SEND_FRAME_LEN; ++i) {\n \/\/ frames[i].id = id_count & 0x3FF;\n send_id = id;\n frames[i].id = id;\n frames[i].len = 8;\n frames[i].data[7] = static_cast(count % 256);\n for (uint8_t j = 0; j < 7; ++j) {\n frames[i].data[j] = j;\n }\n ++count;\n ++id;\n if (id > end_id) {\n id = start_id;\n }\n }\n int32_t frame_num = MAX_CAN_SEND_FRAME_LEN;\n if (client->Send(frames, &frame_num) != ErrorCode::OK) {\n param->send_err_cnt += MAX_CAN_SEND_FRAME_LEN;\n AERROR << \"send_thread send msg failed!, id:\" << send_id\n << \", conf:\" << param->conf.ShortDebugString();\n } else {\n param->send_cnt += frame_num;\n param->send_lost_cnt += MAX_CAN_SEND_FRAME_LEN - frame_num;\n AINFO << \"send_frames: \" << frame_num << \"send_frame#\"\n << frames[0].CanFrameString()\n << \" send lost:\" << MAX_CAN_SEND_FRAME_LEN - frame_num\n << \", conf:\" << param->conf.ShortDebugString();\n }\n }\n int64_t end = AsInt64(Clock::Now());\n param->send_time = static_cast(end - start);\n \/\/ In case for finish too quick to receiver miss some msg\n sleep(2);\n AINFO << \"Send thread stopping...\" << param->conf.ShortDebugString();\n is_sending_finish(true);\n return;\n }\n\n void AddOtherAgent(CanAgent *agent) { other_agent_ = agent; }\n\n bool is_receiving() const { return is_receiving_; }\n\n void is_receiving(bool val) { is_receiving_ = val; }\n\n bool is_sending_finish() const { return is_sending_finish_; }\n\n void is_sending_finish(bool val) { is_sending_finish_ = val; }\n\n void RecvThreadFunc() {\n using common::ErrorCode;\n using common::time::AsInt64;\n using common::time::Clock;\n using common::time::micros;\n AINFO << \"Receive thread starting...\";\n TestCanParam *param = param_ptr();\n CanClient *client = param->can_client;\n int64_t start = 0;\n std::vector buf;\n\n bool first = true;\n while (!other_agent()->is_sending_finish()) {\n is_receiving(true);\n int32_t len = MAX_CAN_RECV_FRAME_LEN;\n ErrorCode ret = client->Receive(&buf, &len);\n if (len == 0) {\n AINFO << \"recv frame:0\";\n continue;\n }\n if (first) {\n start = AsInt64(Clock::Now());\n first = false;\n }\n if (ret != ErrorCode::OK || len == 0) {\n \/\/ AINFO << \"channel:\" << param->conf.channel_id()\n \/\/ << \", recv frame:failed, code:\" << ret;\n AINFO << \"recv error:\" << ret;\n continue;\n }\n for (int32_t i = 0; i < len; ++i) {\n param->recv_cnt = param->recv_cnt + 1;\n AINFO << \"recv_frame#\" << buf[i].CanFrameString()\n << \" conf:\" << param->conf.ShortDebugString()\n << \",recv_cnt: \" << param->recv_cnt;\n }\n }\n int64_t end = AsInt64(Clock::Now());\n param->recv_time = static_cast(end - start);\n AINFO << \"Recv thread stopping..., conf:\" << param->conf.ShortDebugString();\n return;\n }\n\n void WaitForFinish() {\n if (thread_send_ != nullptr && thread_send_->joinable()) {\n thread_send_->join();\n thread_send_.reset();\n AINFO << \"Send thread stopped. conf:\"\n << param_ptr_->conf.ShortDebugString();\n }\n if (thread_recv_ != nullptr && thread_recv_->joinable()) {\n thread_recv_->join();\n thread_recv_.reset();\n AINFO << \"Recv thread stopped. conf:\"\n << param_ptr_->conf.ShortDebugString();\n }\n }\n\n private:\n bool is_receiving_ = false;\n bool is_sending_finish_ = false;\n CanAgent *other_agent_ = nullptr;\n TestCanParam *param_ptr_ = nullptr;\n std::unique_ptr thread_recv_;\n std::unique_ptr thread_send_;\n};\n\n} \/\/ namespace canbus\n} \/\/ namespace drivers\n} \/\/ namespace apollo\n\nint main(int32_t argc, char **argv) {\n google::InitGoogleLogging(argv[0]);\n google::ParseCommandLineFlags(&argc, &argv, true);\n\n using apollo::common::ErrorCode;\n using apollo::drivers::canbus::CanAgent;\n using apollo::drivers::canbus::CANCardParameter;\n using apollo::drivers::canbus::CanClient;\n using apollo::drivers::canbus::CanClientFactory;\n using apollo::drivers::canbus::TestCanParam;\n CANCardParameter can_client_conf_a;\n std::shared_ptr param_ptr_a(new TestCanParam());\n std::shared_ptr param_ptr_b(new TestCanParam());\n\n auto can_client_factory = CanClientFactory::Instance();\n can_client_factory->RegisterCanClients();\n\n if (!apollo::cyber::common::GetProtoFromFile(FLAGS_can_client_conf_file_a,\n &can_client_conf_a)) {\n AERROR << \"Unable to load canbus conf file: \"\n << FLAGS_can_client_conf_file_a;\n return 1;\n } else {\n AINFO << \"Conf file is loaded: \" << FLAGS_can_client_conf_file_a;\n }\n AINFO << can_client_conf_a.ShortDebugString();\n auto client_a = can_client_factory->CreateObject(can_client_conf_a.brand());\n if (!client_a || !client_a->Init(can_client_conf_a) ||\n client_a->Start() != ErrorCode::OK) {\n AERROR << \"Create can client a failed.\";\n return 1;\n }\n param_ptr_a->can_client = client_a.get();\n param_ptr_a->is_first_agent = true;\n param_ptr_a->conf = can_client_conf_a;\n\n CANCardParameter can_client_conf_b;\n std::unique_ptr client_b;\n if (!FLAGS_only_one_send) {\n if (!apollo::cyber::common::GetProtoFromFile(FLAGS_can_client_conf_file_b,\n &can_client_conf_b)) {\n AERROR << \"Unable to load canbus conf file: \"\n << FLAGS_can_client_conf_file_b;\n return 1;\n } else {\n AINFO << \"Conf file is loaded: \" << FLAGS_can_client_conf_file_b;\n }\n AINFO << can_client_conf_b.ShortDebugString();\n client_b = can_client_factory->CreateObject(can_client_conf_b.brand());\n if (!client_b || !client_b->Init(can_client_conf_b) ||\n client_b->Start() != ErrorCode::OK) {\n AERROR << \"Create can client b failed.\";\n return 1;\n }\n param_ptr_b->can_client = client_b.get();\n param_ptr_b->conf = can_client_conf_b;\n }\n\n CanAgent agent_a(param_ptr_a.get());\n CanAgent agent_b(param_ptr_b.get());\n agent_a.AddOtherAgent(&agent_b);\n agent_b.AddOtherAgent(&agent_a);\n if (!agent_a.Start()) {\n AERROR << \"Agent a start failed.\";\n return -1;\n }\n if (FLAGS_only_one_send) {\n agent_b.is_receiving(true);\n agent_b.is_sending_finish(true);\n } else {\n if (!agent_b.Start()) {\n AERROR << \"Agent b start failed.\";\n return -1;\n }\n }\n\n agent_a.WaitForFinish();\n if (!FLAGS_only_one_send) {\n agent_b.WaitForFinish();\n }\n param_ptr_a->print();\n if (!FLAGS_only_one_send) {\n param_ptr_b->print();\n }\n\n return 0;\n}\nDrivers: fix return value\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \n#include \n#include \n#include \n\n#include \"cyber\/common\/file.h\"\n#include \"cyber\/common\/log.h\"\n#include \"gflags\/gflags.h\"\n#include \"modules\/common\/proto\/error_code.pb.h\"\n#include \"modules\/common\/time\/time.h\"\n#include \"modules\/common\/util\/factory.h\"\n#include \"modules\/drivers\/canbus\/can_client\/can_client.h\"\n#include \"modules\/drivers\/canbus\/can_client\/can_client_factory.h\"\n#include \"modules\/drivers\/canbus\/common\/byte.h\"\n#include \"modules\/drivers\/canbus\/proto\/can_card_parameter.pb.h\"\n\nDEFINE_bool(only_one_send, false, \"only send test.\");\nDEFINE_string(can_client_conf_file_a,\n \"modules\/canbus\/conf\/can_client_conf_a.pb.txt\",\n \"can client conf for client a\");\nDEFINE_string(can_client_conf_file_b,\n \"modules\/canbus\/conf\/can_client_conf_b.pb.txt\",\n \"can client conf for client b\");\nDEFINE_int64(agent_mutual_send_frames, 1000, \"Every agent send frame num\");\n\nconst int32_t MAX_CAN_SEND_FRAME_LEN = 1;\nconst int32_t MAX_CAN_RECV_FRAME_LEN = 10;\n\nnamespace apollo {\nnamespace drivers {\nnamespace canbus {\n\nstruct TestCanParam {\n CANCardParameter conf;\n bool is_first_agent = false;\n int32_t recv_cnt = 0;\n int32_t recv_err_cnt = 0;\n int32_t send_cnt = 0;\n int32_t send_err_cnt = 0;\n int32_t send_lost_cnt = 0;\n int32_t send_time = 0;\n int32_t recv_time = 0;\n CanClient *can_client = nullptr;\n\n TestCanParam() = default;\n\n void print() {\n AINFO << \"conf: \" << conf.ShortDebugString()\n << \", total send: \" << send_cnt + send_err_cnt << \"\/\"\n << FLAGS_agent_mutual_send_frames << \", send_ok: \" << send_cnt\n << \" , send_err_cnt: \" << send_err_cnt\n << \", send_lost_cnt: \" << send_lost_cnt << \", recv_cnt: \" << recv_cnt\n << \", send_time: \" << send_time << \", recv_time: \" << recv_time;\n }\n};\n\nclass CanAgent {\n public:\n explicit CanAgent(TestCanParam *param_ptr) : param_ptr_(param_ptr) {}\n\n TestCanParam *param_ptr() { return param_ptr_; }\n\n CanAgent *other_agent() { return other_agent_; }\n\n bool Start() {\n thread_recv_.reset(new std::thread([this] { RecvThreadFunc(); }));\n if (thread_recv_ == nullptr) {\n AERROR << \"Unable to create recv thread.\";\n return false;\n }\n thread_send_.reset(new std::thread([this] { SendThreadFunc(); }));\n if (thread_send_ == nullptr) {\n AERROR << \"Unable to create send thread.\";\n return false;\n }\n return true;\n }\n\n void SendThreadFunc() {\n using common::ErrorCode;\n using common::time::AsInt64;\n using common::time::Clock;\n using common::time::micros;\n AINFO << \"Send thread starting...\";\n TestCanParam *param = param_ptr();\n CanClient *client = param->can_client;\n std::vector frames;\n frames.resize(MAX_CAN_SEND_FRAME_LEN);\n\n int32_t count = 0;\n int32_t start_id = 0;\n int32_t end_id = 0;\n int32_t id = 0;\n if (param->is_first_agent) {\n start_id = 1;\n end_id = 128;\n } else {\n start_id = 129;\n end_id = start_id + 127;\n }\n id = start_id;\n int32_t send_id = id;\n AINFO << \"port:\" << param->conf.ShortDebugString()\n << \", start_id:\" << start_id << \", end_id:\" << end_id;\n\n \/\/ wait for other agent receiving is ok.\n while (!other_agent()->is_receiving()) {\n std::this_thread::yield();\n }\n int64_t start = AsInt64(Clock::Now());\n while (true) {\n \/\/ param->print();\n if (count >= FLAGS_agent_mutual_send_frames) {\n break;\n }\n for (int32_t i = 0; i < MAX_CAN_SEND_FRAME_LEN; ++i) {\n \/\/ frames[i].id = id_count & 0x3FF;\n send_id = id;\n frames[i].id = id;\n frames[i].len = 8;\n frames[i].data[7] = static_cast(count % 256);\n for (uint8_t j = 0; j < 7; ++j) {\n frames[i].data[j] = j;\n }\n ++count;\n ++id;\n if (id > end_id) {\n id = start_id;\n }\n }\n int32_t frame_num = MAX_CAN_SEND_FRAME_LEN;\n if (client->Send(frames, &frame_num) != ErrorCode::OK) {\n param->send_err_cnt += MAX_CAN_SEND_FRAME_LEN;\n AERROR << \"send_thread send msg failed!, id:\" << send_id\n << \", conf:\" << param->conf.ShortDebugString();\n } else {\n param->send_cnt += frame_num;\n param->send_lost_cnt += MAX_CAN_SEND_FRAME_LEN - frame_num;\n AINFO << \"send_frames: \" << frame_num << \"send_frame#\"\n << frames[0].CanFrameString()\n << \" send lost:\" << MAX_CAN_SEND_FRAME_LEN - frame_num\n << \", conf:\" << param->conf.ShortDebugString();\n }\n }\n int64_t end = AsInt64(Clock::Now());\n param->send_time = static_cast(end - start);\n \/\/ In case for finish too quick to receiver miss some msg\n sleep(2);\n AINFO << \"Send thread stopping...\" << param->conf.ShortDebugString();\n is_sending_finish(true);\n return;\n }\n\n void AddOtherAgent(CanAgent *agent) { other_agent_ = agent; }\n\n bool is_receiving() const { return is_receiving_; }\n\n void is_receiving(bool val) { is_receiving_ = val; }\n\n bool is_sending_finish() const { return is_sending_finish_; }\n\n void is_sending_finish(bool val) { is_sending_finish_ = val; }\n\n void RecvThreadFunc() {\n using common::ErrorCode;\n using common::time::AsInt64;\n using common::time::Clock;\n using common::time::micros;\n AINFO << \"Receive thread starting...\";\n TestCanParam *param = param_ptr();\n CanClient *client = param->can_client;\n int64_t start = 0;\n std::vector buf;\n\n bool first = true;\n while (!other_agent()->is_sending_finish()) {\n is_receiving(true);\n int32_t len = MAX_CAN_RECV_FRAME_LEN;\n ErrorCode ret = client->Receive(&buf, &len);\n if (len == 0) {\n AINFO << \"recv frame:0\";\n continue;\n }\n if (first) {\n start = AsInt64(Clock::Now());\n first = false;\n }\n if (ret != ErrorCode::OK || len == 0) {\n \/\/ AINFO << \"channel:\" << param->conf.channel_id()\n \/\/ << \", recv frame:failed, code:\" << ret;\n AINFO << \"recv error:\" << ret;\n continue;\n }\n for (int32_t i = 0; i < len; ++i) {\n param->recv_cnt = param->recv_cnt + 1;\n AINFO << \"recv_frame#\" << buf[i].CanFrameString()\n << \" conf:\" << param->conf.ShortDebugString()\n << \",recv_cnt: \" << param->recv_cnt;\n }\n }\n int64_t end = AsInt64(Clock::Now());\n param->recv_time = static_cast(end - start);\n AINFO << \"Recv thread stopping..., conf:\" << param->conf.ShortDebugString();\n return;\n }\n\n void WaitForFinish() {\n if (thread_send_ != nullptr && thread_send_->joinable()) {\n thread_send_->join();\n thread_send_.reset();\n AINFO << \"Send thread stopped. conf:\"\n << param_ptr_->conf.ShortDebugString();\n }\n if (thread_recv_ != nullptr && thread_recv_->joinable()) {\n thread_recv_->join();\n thread_recv_.reset();\n AINFO << \"Recv thread stopped. conf:\"\n << param_ptr_->conf.ShortDebugString();\n }\n }\n\n private:\n bool is_receiving_ = false;\n bool is_sending_finish_ = false;\n CanAgent *other_agent_ = nullptr;\n TestCanParam *param_ptr_ = nullptr;\n std::unique_ptr thread_recv_;\n std::unique_ptr thread_send_;\n};\n\n} \/\/ namespace canbus\n} \/\/ namespace drivers\n} \/\/ namespace apollo\n\nint main(int32_t argc, char **argv) {\n google::InitGoogleLogging(argv[0]);\n google::ParseCommandLineFlags(&argc, &argv, true);\n\n using apollo::common::ErrorCode;\n using apollo::drivers::canbus::CanAgent;\n using apollo::drivers::canbus::CANCardParameter;\n using apollo::drivers::canbus::CanClient;\n using apollo::drivers::canbus::CanClientFactory;\n using apollo::drivers::canbus::TestCanParam;\n CANCardParameter can_client_conf_a;\n std::shared_ptr param_ptr_a(new TestCanParam());\n std::shared_ptr param_ptr_b(new TestCanParam());\n\n auto can_client_factory = CanClientFactory::Instance();\n can_client_factory->RegisterCanClients();\n\n if (!apollo::cyber::common::GetProtoFromFile(FLAGS_can_client_conf_file_a,\n &can_client_conf_a)) {\n AERROR << \"Unable to load canbus conf file: \"\n << FLAGS_can_client_conf_file_a;\n return -1;\n }\n AINFO << \"Conf file is loaded: \" << FLAGS_can_client_conf_file_a;\n AINFO << can_client_conf_a.ShortDebugString();\n auto client_a = can_client_factory->CreateObject(can_client_conf_a.brand());\n if (!client_a || !client_a->Init(can_client_conf_a) ||\n client_a->Start() != ErrorCode::OK) {\n AERROR << \"Create can client a failed.\";\n return -1;\n }\n param_ptr_a->can_client = client_a.get();\n param_ptr_a->is_first_agent = true;\n param_ptr_a->conf = can_client_conf_a;\n\n CANCardParameter can_client_conf_b;\n std::unique_ptr client_b;\n if (!FLAGS_only_one_send) {\n if (!apollo::cyber::common::GetProtoFromFile(FLAGS_can_client_conf_file_b,\n &can_client_conf_b)) {\n AERROR << \"Unable to load canbus conf file: \"\n << FLAGS_can_client_conf_file_b;\n return -1;\n }\n AINFO << \"Conf file is loaded: \" << FLAGS_can_client_conf_file_b;\n AINFO << can_client_conf_b.ShortDebugString();\n client_b = can_client_factory->CreateObject(can_client_conf_b.brand());\n if (!client_b || !client_b->Init(can_client_conf_b) ||\n client_b->Start() != ErrorCode::OK) {\n AERROR << \"Create can client b failed.\";\n return -1;\n }\n param_ptr_b->can_client = client_b.get();\n param_ptr_b->conf = can_client_conf_b;\n }\n\n CanAgent agent_a(param_ptr_a.get());\n CanAgent agent_b(param_ptr_b.get());\n agent_a.AddOtherAgent(&agent_b);\n agent_b.AddOtherAgent(&agent_a);\n if (!agent_a.Start()) {\n AERROR << \"Agent a start failed.\";\n return -1;\n }\n if (FLAGS_only_one_send) {\n agent_b.is_receiving(true);\n agent_b.is_sending_finish(true);\n } else {\n if (!agent_b.Start()) {\n AERROR << \"Agent b start failed.\";\n return -1;\n }\n }\n\n agent_a.WaitForFinish();\n if (!FLAGS_only_one_send) {\n agent_b.WaitForFinish();\n }\n param_ptr_a->print();\n if (!FLAGS_only_one_send) {\n param_ptr_b->print();\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/****************** *****************\n *\n * VR Juggler Portable Runtime\n *\n * Original Authors:\n * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira\n *\n * -----------------------------------------------------------------\n * File: $RCSfile$\n * Date modified: $Date$\n * Version: $Revision$\n * -----------------------------------------------------------------\n *\n ****************** ******************\/\n\n\/*************** **************\n *\n * VR Juggler is (C) Copyright 1998-2005 by Iowa State University\n *\n * Original Authors:\n * Allen Bierbaum, Christopher Just,\n * Patrick Hartling, Kevin Meinert,\n * Carolina Cruz-Neira, Albert Baker\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n *************** ***************\/\n\n#include \n\nnamespace vpr\n{\n\nUncaughtThreadException::UncaughtThreadException(const std::string& msg,\n const std::string& location) throw()\n : Exception(msg, location)\n{\n \/* Do nothing. *\/ ;\n}\n\nUncaughtThreadException::~UncaughtThreadException() throw()\n{\n \/* Do nothing. *\/ ;\n}\n\nvoid UncaughtThreadException::setException(const vpr::Exception& ex)\n{\n mDescription = ex.getExceptionName() + \": \" + ex.getDescription();\n mLocation = ex.getLocation();\n mStackTrace = ex.getStackTrace();\n}\n\nvoid UncaughtThreadException::setException(const std::exception& ex)\n{\n mDescription = ex.what();\n mLocation = \"Location not availible with std::exception.\";\n mStackTrace = \"Stacktrace not availible with std::exception.\";\n}\n\n}\nFixed Visual C++ 7.0 compile error.\/****************** *****************\n *\n * VR Juggler Portable Runtime\n *\n * Original Authors:\n * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira\n *\n * -----------------------------------------------------------------\n * File: $RCSfile$\n * Date modified: $Date$\n * Version: $Revision$\n * -----------------------------------------------------------------\n *\n ****************** ******************\/\n\n\/*************** **************\n *\n * VR Juggler is (C) Copyright 1998-2005 by Iowa State University\n *\n * Original Authors:\n * Allen Bierbaum, Christopher Just,\n * Patrick Hartling, Kevin Meinert,\n * Carolina Cruz-Neira, Albert Baker\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n *************** ***************\/\n\n#include \n\n#include \n\n#include \n\nnamespace vpr\n{\n\nUncaughtThreadException::UncaughtThreadException(const std::string& msg,\n const std::string& location)\n throw()\n : Exception(msg, location)\n{\n \/* Do nothing. *\/ ;\n}\n\nUncaughtThreadException::~UncaughtThreadException() throw()\n{\n \/* Do nothing. *\/ ;\n}\n\nvoid UncaughtThreadException::setException(const vpr::Exception& ex)\n{\n std::stringstream desc_stream;\n desc_stream << ex.getExceptionName() << \": \" + ex.getDescription();\n\n mDescription = desc_stream.str();\n mLocation = ex.getLocation();\n mStackTrace = ex.getStackTrace();\n}\n\nvoid UncaughtThreadException::setException(const std::exception& ex)\n{\n mDescription = ex.what();\n mLocation = \"Location not availible with std::exception.\";\n mStackTrace = \"Stacktrace not availible with std::exception.\";\n}\n\n}\n<|endoftext|>"} {"text":"new_client: updated xtfs_send against Yield changes<|endoftext|>"} {"text":"\n#pragma once\n\n\n#include \n\n#include \n\n#include \n#include \n\n\nnamespace gloperate\n{\n\n\ntemplate \ntemplate \nauto Slot::DereferenceHelper::pointer(U * value) -> Pointer\n{\n return value;\n}\n\ntemplate \ntemplate \nauto Slot::DereferenceHelper::pointer(U ** value) -> Pointer\n{\n return *value;\n}\n\ntemplate \ntemplate \nauto Slot::DereferenceHelper::pointer(U * const * value) -> Pointer\n{\n return *value;\n}\n\n\ntemplate \nSlot::Slot(SlotType slotType, const std::string & name, Stage * parent, const T & value)\n: cppexpose::DirectValue(value)\n, m_valid(true)\n, m_source(nullptr)\n{\n \/\/ Do not add property to object, yet. Just initialize the property itself\n this->initProperty(name, nullptr);\n\n \/\/ Initialize slot, will also add slot as a property\n this->initSlot(slotType, parent);\n}\n\ntemplate \nSlot::Slot(SlotType slotType, const std::string & name, const T & value)\n: cppexpose::DirectValue(value)\n, m_valid(true)\n, m_source(nullptr)\n{\n \/\/ Make as a dynamic slot\n this->m_dynamic = true;\n\n \/\/ Do not add property to object, yet. Just initialize the property itself\n this->initProperty(name, nullptr);\n\n \/\/ Initialize slot\n this->initSlot(slotType, nullptr);\n}\n\ntemplate \nSlot::~Slot()\n{\n}\n\ntemplate \nbool Slot::connect(Slot * source)\n{\n assert(source != nullptr);\n\n cppassist::debug(2, \"gloperate\") << this->qualifiedName() << \": connect slot \" << source->qualifiedName();\n\n \/\/ Check if source is valid\n if (!source) {\n return false;\n }\n\n \/\/ Set source\n m_source = source;\n\n \/\/ Connect to data container; no direct binding of member function to achive virtual lookup\n m_valueConnection = m_source->valueChanged.connect([this] (const T & value)\n {\n this->onValueChanged(value);\n } );\n m_validConnection = m_source->valueInvalidated.connect([this] ()\n {\n this->onValueInvalidated();\n } );\n\n \/\/ Emit events\n this->promoteConnection();\n this->promoteRequired();\n this->onValueChanged(m_source->value());\n\n \/\/ Success\n return true;\n}\n\ntemplate \nSlot & Slot::operator<<(Slot & source)\n{\n this->connect(&source);\n return *this;\n}\n\ntemplate \nconst T & Slot::operator*() const\n{\n return *this->ptr();\n}\n\ntemplate \nauto Slot::operator->() -> typename DereferenceHelper::Pointer\n{\n return DereferenceHelper::pointer(this->ptr());\n}\n\ntemplate \nauto Slot::operator->() const -> const typename DereferenceHelper::Pointer\n{\n return DereferenceHelper::pointer(this->ptr());\n}\n\ntemplate \nbool Slot::isCompatible(const AbstractSlot * source) const\n{\n \/\/ Check if source is valid and compatible data container\n if (!source)\n {\n return false;\n }\n\n \/\/ Check if types are equal\n return this->type() == source->type();\n}\n\ntemplate \nbool Slot::connect(AbstractSlot * source)\n{\n \/\/ Check if source is valid and compatible data container\n if (!source || !isCompatible(source))\n {\n cppassist::debug(2, \"gloperate\") << this->qualifiedName() << \": connect slot failed for \" << source->qualifiedName();\n return false;\n }\n\n \/\/ Connect to source data\n return connect(static_cast< Slot * >(source));\n}\n\ntemplate \nvoid Slot::disconnect()\n{\n \/\/ Reset source property\n m_source = nullptr;\n m_valueConnection = cppexpose::ScopedConnection();\n m_validConnection = cppexpose::ScopedConnection();\n\n cppassist::debug(2, \"gloperate\") << this->qualifiedName() << \": disconnect slot\";\n\n \/\/ Emit events\n this->promoteConnection();\n this->onValueChanged(this->m_value);\n}\n\ntemplate \nconst AbstractSlot * Slot::source() const\n{\n return m_source;\n}\n\ntemplate \nbool Slot::isValid() const\n{\n \/\/ If connected, return validity of source slot\n if (m_source)\n {\n return m_source->isValid();\n }\n\n \/\/ Return validity of own data\n return m_valid;\n}\n\ntemplate \nvoid Slot::invalidate()\n{\n if (!m_valid)\n {\n return;\n }\n\n \/\/ If connected, abort function\n if (!m_source)\n {\n m_valid = false;\n }\n\n \/\/ Emit signal if it was invalidated\n this->onValueInvalidated();\n}\n\ntemplate \nbool Slot::hasChanged() const\n{\n return m_changed;\n}\n\ntemplate \nvoid Slot::setChanged(bool hasChanged)\n{\n m_changed = hasChanged;\n}\n\ntemplate \nvoid Slot::onRequiredChanged()\n{\n promoteRequired();\n}\n\ntemplate \nT Slot::value() const\n{\n \/\/ If connected, return value of source slot\n if (m_source)\n {\n return m_source->value();\n }\n\n \/\/ Return own data\n return this->m_value;\n}\n\ntemplate \nvoid Slot::setValue(const T & value)\n{\n \/\/ If connected, abort function\n if (m_source)\n {\n return;\n }\n\n \/\/ Set own data\n this->m_value = value;\n this->m_valid = true;\n\n \/\/ Emit signal\n this->onValueChanged(this->m_value);\n}\n\ntemplate \nconst T * Slot::ptr() const\n{\n \/\/ If connected, return value of source slot\n if (m_source)\n {\n return m_source->ptr();\n }\n\n \/\/ Return own data\n return &this->m_value;\n}\n\ntemplate \nT * Slot::ptr()\n{\n \/\/ If connected, return value of source slot\n if (m_source)\n {\n return m_source->ptr();\n }\n\n \/\/ Return own data\n return &this->m_value;\n}\n\ntemplate \nstd::unique_ptr Slot::clone() const\n{\n return nullptr;\n}\n\ntemplate \nbool Slot::isObject() const\n{\n return false;\n}\n\ntemplate \nvoid Slot::promoteConnection()\n{\n \/\/ Emit signal\n this->connectionChanged();\n this->parentStage()->invalidateInputConnections();\n}\n\ntemplate \nvoid Slot::promoteRequired()\n{\n \/\/ Check if input slot is connected\n if (!m_source)\n {\n return;\n }\n\n \/\/ Promote required-flag to connected slot\n m_source->setRequired(this->m_required);\n}\n\n\n} \/\/ namespace gloperate\nFix Slot::promoteConnection behavior\n#pragma once\n\n\n#include \n\n#include \n\n#include \n#include \n\n\nnamespace gloperate\n{\n\n\ntemplate \ntemplate \nauto Slot::DereferenceHelper::pointer(U * value) -> Pointer\n{\n return value;\n}\n\ntemplate \ntemplate \nauto Slot::DereferenceHelper::pointer(U ** value) -> Pointer\n{\n return *value;\n}\n\ntemplate \ntemplate \nauto Slot::DereferenceHelper::pointer(U * const * value) -> Pointer\n{\n return *value;\n}\n\n\ntemplate \nSlot::Slot(SlotType slotType, const std::string & name, Stage * parent, const T & value)\n: cppexpose::DirectValue(value)\n, m_valid(true)\n, m_source(nullptr)\n{\n \/\/ Do not add property to object, yet. Just initialize the property itself\n this->initProperty(name, nullptr);\n\n \/\/ Initialize slot, will also add slot as a property\n this->initSlot(slotType, parent);\n}\n\ntemplate \nSlot::Slot(SlotType slotType, const std::string & name, const T & value)\n: cppexpose::DirectValue(value)\n, m_valid(true)\n, m_source(nullptr)\n{\n \/\/ Make as a dynamic slot\n this->m_dynamic = true;\n\n \/\/ Do not add property to object, yet. Just initialize the property itself\n this->initProperty(name, nullptr);\n\n \/\/ Initialize slot\n this->initSlot(slotType, nullptr);\n}\n\ntemplate \nSlot::~Slot()\n{\n}\n\ntemplate \nbool Slot::connect(Slot * source)\n{\n assert(source != nullptr);\n\n cppassist::debug(2, \"gloperate\") << this->qualifiedName() << \": connect slot \" << source->qualifiedName();\n\n \/\/ Check if source is valid\n if (!source) {\n return false;\n }\n\n \/\/ Set source\n m_source = source;\n\n \/\/ Connect to data container; no direct binding of member function to achive virtual lookup\n m_valueConnection = m_source->valueChanged.connect([this] (const T & value)\n {\n this->onValueChanged(value);\n } );\n m_validConnection = m_source->valueInvalidated.connect([this] ()\n {\n this->onValueInvalidated();\n } );\n\n \/\/ Emit events\n this->promoteConnection();\n this->promoteRequired();\n this->onValueChanged(m_source->value());\n\n \/\/ Success\n return true;\n}\n\ntemplate \nSlot & Slot::operator<<(Slot & source)\n{\n this->connect(&source);\n return *this;\n}\n\ntemplate \nconst T & Slot::operator*() const\n{\n return *this->ptr();\n}\n\ntemplate \nauto Slot::operator->() -> typename DereferenceHelper::Pointer\n{\n return DereferenceHelper::pointer(this->ptr());\n}\n\ntemplate \nauto Slot::operator->() const -> const typename DereferenceHelper::Pointer\n{\n return DereferenceHelper::pointer(this->ptr());\n}\n\ntemplate \nbool Slot::isCompatible(const AbstractSlot * source) const\n{\n \/\/ Check if source is valid and compatible data container\n if (!source)\n {\n return false;\n }\n\n \/\/ Check if types are equal\n return this->type() == source->type();\n}\n\ntemplate \nbool Slot::connect(AbstractSlot * source)\n{\n \/\/ Check if source is valid and compatible data container\n if (!source || !isCompatible(source))\n {\n cppassist::debug(2, \"gloperate\") << this->qualifiedName() << \": connect slot failed for \" << source->qualifiedName();\n return false;\n }\n\n \/\/ Connect to source data\n return connect(static_cast< Slot * >(source));\n}\n\ntemplate \nvoid Slot::disconnect()\n{\n \/\/ Reset source property\n m_source = nullptr;\n m_valueConnection = cppexpose::ScopedConnection();\n m_validConnection = cppexpose::ScopedConnection();\n\n cppassist::debug(2, \"gloperate\") << this->qualifiedName() << \": disconnect slot\";\n\n \/\/ Emit events\n this->promoteConnection();\n this->onValueChanged(this->m_value);\n}\n\ntemplate \nconst AbstractSlot * Slot::source() const\n{\n return m_source;\n}\n\ntemplate \nbool Slot::isValid() const\n{\n \/\/ If connected, return validity of source slot\n if (m_source)\n {\n return m_source->isValid();\n }\n\n \/\/ Return validity of own data\n return m_valid;\n}\n\ntemplate \nvoid Slot::invalidate()\n{\n if (!m_valid)\n {\n return;\n }\n\n \/\/ If connected, abort function\n if (!m_source)\n {\n m_valid = false;\n }\n\n \/\/ Emit signal if it was invalidated\n this->onValueInvalidated();\n}\n\ntemplate \nbool Slot::hasChanged() const\n{\n return m_changed;\n}\n\ntemplate \nvoid Slot::setChanged(bool hasChanged)\n{\n m_changed = hasChanged;\n}\n\ntemplate \nvoid Slot::onRequiredChanged()\n{\n promoteRequired();\n}\n\ntemplate \nT Slot::value() const\n{\n \/\/ If connected, return value of source slot\n if (m_source)\n {\n return m_source->value();\n }\n\n \/\/ Return own data\n return this->m_value;\n}\n\ntemplate \nvoid Slot::setValue(const T & value)\n{\n \/\/ If connected, abort function\n if (m_source)\n {\n return;\n }\n\n \/\/ Set own data\n this->m_value = value;\n this->m_valid = true;\n\n \/\/ Emit signal\n this->onValueChanged(this->m_value);\n}\n\ntemplate \nconst T * Slot::ptr() const\n{\n \/\/ If connected, return value of source slot\n if (m_source)\n {\n return m_source->ptr();\n }\n\n \/\/ Return own data\n return &this->m_value;\n}\n\ntemplate \nT * Slot::ptr()\n{\n \/\/ If connected, return value of source slot\n if (m_source)\n {\n return m_source->ptr();\n }\n\n \/\/ Return own data\n return &this->m_value;\n}\n\ntemplate \nstd::unique_ptr Slot::clone() const\n{\n return nullptr;\n}\n\ntemplate \nbool Slot::isObject() const\n{\n return false;\n}\n\ntemplate \nvoid Slot::promoteConnection()\n{\n \/\/ Emit signal\n this->connectionChanged();\n if (this->parentStage())\n {\n this->parentStage()->invalidateInputConnections();\n }\n}\n\ntemplate \nvoid Slot::promoteRequired()\n{\n \/\/ Check if input slot is connected\n if (!m_source)\n {\n return;\n }\n\n \/\/ Promote required-flag to connected slot\n m_source->setRequired(this->m_required);\n}\n\n\n} \/\/ namespace gloperate\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n#include \"Font.h\"\n\n#include \"FloatRect.h\"\n#include \"GlyphBuffer.h\"\n#include \"GraphicsContext.h\"\n#include \"NotImplemented.h\"\n#include \"PlatformContextSkia.h\"\n#include \"SimpleFontData.h\"\n\n#include \"SkCanvas.h\"\n#include \"SkPaint.h\"\n#include \"SkTemplates.h\"\n#include \"SkTypeface.h\"\n#include \"SkUtils.h\"\n\nnamespace WebCore {\n\nvoid Font::drawGlyphs(GraphicsContext* gc, const SimpleFontData* font,\n const GlyphBuffer& glyphBuffer, int from, int numGlyphs,\n const FloatPoint& point) const {\n SkCanvas* canvas = gc->platformContext()->canvas();\n SkPaint paint;\n\n font->platformData().setupPaint(&paint);\n paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);\n paint.setColor(gc->fillColor().rgb());\n\n SkASSERT(sizeof(GlyphBufferGlyph) == sizeof(uint16_t)); \/\/ compile-time assert\n\n const GlyphBufferGlyph* glyphs = glyphBuffer.glyphs(from);\n SkScalar x = SkFloatToScalar(point.x());\n SkScalar y = SkFloatToScalar(point.y());\n\n \/\/ TODO(port): Android WebCore has patches for PLATFORM(SGL) which involves\n \/\/ this, however we don't have these patches and it's unclear when Android\n \/\/ may upstream them.\n#if 0\n if (glyphBuffer.hasAdjustedWidths()) {\n const GlyphBufferAdvance* adv = glyphBuffer.advances(from);\n SkAutoSTMalloc<32, SkPoint> storage(numGlyphs);\n SkPoint* pos = storage.get();\n\n for (int i = 0; i < numGlyphs; i++) {\n pos[i].set(x, y);\n x += SkFloatToScalar(adv[i].width());\n y += SkFloatToScalar(adv[i].height());\n }\n canvas->drawPosText(glyphs, numGlyphs << 1, pos, paint);\n } else {\n canvas->drawText(glyphs, numGlyphs << 1, x, y, paint);\n }\n#endif\n\n canvas->drawText(glyphs, numGlyphs << 1, x, y, paint);\n}\n\nvoid Font::drawComplexText(GraphicsContext* context, const TextRun& run,\n const FloatPoint& point, int from, int to) const\n{\n notImplemented();\n}\n\nfloat Font::floatWidthForComplexText(const TextRun& run) const\n{\n notImplemented();\n return 0;\n}\n\nint Font::offsetForPositionForComplexText(const TextRun& run, int x,\n bool includePartialGlyphs) const\n{\n notImplemented();\n return 0;\n}\n\nFloatRect Font::selectionRectForComplexText(const TextRun& run,\n const IntPoint& point, int h,\n int from, int to) const\n{\n notImplemented();\n return FloatRect();\n}\n\n} \/\/ namespace WebCore\nLinux: respect non-standard advance widths for glyphs.\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n#include \"Font.h\"\n\n#include \"FloatRect.h\"\n#include \"GlyphBuffer.h\"\n#include \"GraphicsContext.h\"\n#include \"NotImplemented.h\"\n#include \"PlatformContextSkia.h\"\n#include \"SimpleFontData.h\"\n\n#include \"SkCanvas.h\"\n#include \"SkPaint.h\"\n#include \"SkTemplates.h\"\n#include \"SkTypeface.h\"\n#include \"SkUtils.h\"\n\nnamespace WebCore {\n\nvoid Font::drawGlyphs(GraphicsContext* gc, const SimpleFontData* font,\n const GlyphBuffer& glyphBuffer, int from, int numGlyphs,\n const FloatPoint& point) const {\n SkCanvas* canvas = gc->platformContext()->canvas();\n SkPaint paint;\n\n font->platformData().setupPaint(&paint);\n paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);\n paint.setColor(gc->fillColor().rgb());\n\n SkASSERT(sizeof(GlyphBufferGlyph) == sizeof(uint16_t)); \/\/ compile-time assert\n\n const GlyphBufferGlyph* glyphs = glyphBuffer.glyphs(from);\n SkScalar x = SkFloatToScalar(point.x());\n SkScalar y = SkFloatToScalar(point.y());\n\n \/\/ TODO(port): text rendering speed:\n \/\/ Android has code in their WebCore fork to special case when the\n \/\/ GlyphBuffer has no advances other than the defaults. In that case the\n \/\/ text drawing can proceed faster. However, it's unclear when those\n \/\/ patches may be upstreamed to WebKit so we always use the slower path\n \/\/ here.\n const GlyphBufferAdvance* adv = glyphBuffer.advances(from);\n SkAutoSTMalloc<32, SkPoint> storage(numGlyphs);\n SkPoint* pos = storage.get();\n\n for (int i = 0; i < numGlyphs; i++) {\n pos[i].set(x, y);\n x += SkFloatToScalar(adv[i].width());\n y += SkFloatToScalar(adv[i].height());\n }\n canvas->drawPosText(glyphs, numGlyphs << 1, pos, paint);\n}\n\nvoid Font::drawComplexText(GraphicsContext* context, const TextRun& run,\n const FloatPoint& point, int from, int to) const\n{\n notImplemented();\n}\n\nfloat Font::floatWidthForComplexText(const TextRun& run) const\n{\n notImplemented();\n return 0;\n}\n\nint Font::offsetForPositionForComplexText(const TextRun& run, int x,\n bool includePartialGlyphs) const\n{\n notImplemented();\n return 0;\n}\n\nFloatRect Font::selectionRectForComplexText(const TextRun& run,\n const IntPoint& point, int h,\n int from, int to) const\n{\n notImplemented();\n return FloatRect();\n}\n\n} \/\/ namespace WebCore\n<|endoftext|>"} {"text":"#include \"stdafx.h\"\n#include \"CppUnitTest.h\"\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\n\nnamespace EffiData_Test\n{\t\t\n\tTEST_CLASS(EffiData_Test)\n\t{\n\tprotected:\n\t\tstreambuf * oldStdoutBuf;\n\t\tstringstream consoleOutput;\n\t\tstring consoleDump(){ \n\t\t\tstd::istreambuf_iterator eos;\n\t\t\tstd::string sout(std::istreambuf_iterator(consoleOutput), eos);\n\t\t\treturn sout;\n\t\t}\n\tpublic:\n\t\t\/\/Redirect cout.\n\t\tTEST_METHOD_INITIALIZE(pre) {\n\t\t\toldStdoutBuf = std::cout.rdbuf();\n\t\t\tstd::cout.rdbuf(consoleOutput.rdbuf());\n\t\t}\n\n\t\t\/\/Restore redirect cout\n\t\tTEST_METHOD_CLEANUP(post) \n\t\t{\n\t\t\tstd::cout.rdbuf(oldStdoutBuf);\n\t\t}\n\n\t\tTEST_METHOD(BasicPrintCheck)\n\t\t{\/\/id = 0\n\t\t\tEvent e(\"test event\");\n\t\t\tstring expected = \"{\\n\"\n\t\t\t\" \\\"name\\\": \\\"test event\\\",\\n\"\n\t\t\t\" \\\"id\\\": \\\"0\\\",\\n\"\n\t\t\t\" \\\"priority\\\": \\\"5\\\",\\n\"\n\t\t\t\" \\\"tags\\\": \\\"\\\",\\n\" \/\/Should be [], but boost property tree doesn't support it.\n\t\t\t\" \\\"complete\\\": \\\"false\\\",\\n\"\n\t\t\t\" \\\"start\\\": \\\"0\\\",\\n\"\n\t\t\t\" \\\"end\\\": \\\"0\\\",\\n\"\n\t\t\t\" \\\"parent\\\": \\\"0\\\",\\n\"\n\t\t\t\" \\\"content\\\": \\\"0\\\"\\n\"\n\t\t\t\"}\\n\";\n\t\t\tstd::cout<>e;\n\t\t\tstd::cout<[DB] Test changes#include \"stdafx.h\"\n#include \"CppUnitTest.h\"\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\n\nnamespace EffiData_Test\n{\t\t\n\tTEST_CLASS(EffiData_Test)\n\t{\n\tprotected:\n\t\tstreambuf * oldStdoutBuf;\n\t\tstringstream consoleOutput;\n\t\tstring consoleDump(){ \n\t\t\tstd::istreambuf_iterator eos;\n\t\t\tstd::string sout(std::istreambuf_iterator(consoleOutput), eos);\n\t\t\treturn sout;\n\t\t}\n\tpublic:\n\t\t\/\/Redirect cout.\n\t\tTEST_METHOD_INITIALIZE(pre) {\n\t\t\toldStdoutBuf = std::cout.rdbuf();\n\t\t\tstd::cout.rdbuf(consoleOutput.rdbuf());\n\t\t}\n\n\t\t\/\/Restore redirect cout\n\t\tTEST_METHOD_CLEANUP(post) \n\t\t{\n\t\t\tstd::cout.rdbuf(oldStdoutBuf);\n\t\t}\n\n\t\tTEST_METHOD(BasicPrintCheck)\n\t\t{\/\/id = 1\n\t\t\tEvent e(\"test event\");\n\t\t\tstring expected = \"{\\n\"\n\t\t\t\" \\\"name\\\": \\\"test event\\\",\\n\"\n\t\t\t\" \\\"id\\\": \\\"1\\\",\\n\"\n\t\t\t\" \\\"priority\\\": \\\"5\\\",\\n\"\n\t\t\t\" \\\"tags\\\": \\\"\\\",\\n\" \/\/Should be [], but boost property tree doesn't support it.\n\t\t\t\" \\\"complete\\\": \\\"false\\\",\\n\"\n\t\t\t\" \\\"start\\\": \\\"0\\\",\\n\"\n\t\t\t\" \\\"end\\\": \\\"0\\\",\\n\"\n\t\t\t\" \\\"parent\\\": \\\"0\\\",\\n\"\n\t\t\t\" \\\"content\\\": \\\"0\\\"\\n\"\n\t\t\t\"}\\n\";\n\t\t\tstd::cout<>e;\n\t\t\tstd::cout<"} {"text":"\/\/@author A0097630B\n#include \"stdafx.h\"\n#include \n#include \"You-NLP\/parse_tree\/task_priority.h\"\n#include \"internal\/query_executor.h\"\n#include \"internal\/query_executor_builder_visitor.h\"\n#include \"exceptions\/context_index_out_of_range_exception.h\"\n\n#include \"..\/mocks\/task_list.h\"\n#include \"..\/mocks\/query.h\"\n\nusing Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;\n\nnamespace Microsoft {\nnamespace VisualStudio {\nnamespace CppUnitTestFramework {\n\nstd::wstring ToString(You::Controller::Task::Priority priority) {\n\treturn ToString(static_cast(priority));\n}\n\n} \/\/ namespace CppUnitTestFramework\n} \/\/ namespace VisualStudio\n} \/\/ namespace Microsoft\n\nnamespace You {\nnamespace Controller {\nnamespace Internal {\nnamespace UnitTests {\n\nnamespace Mocks {\n\t\/\/ NOLINTNEXTLINE(build\/namespaces)\n\tusing namespace You::Controller::UnitTests::Mocks;\n}\n\nusing Task = You::Controller::Task;\nusing TaskPriority = You::NLP::TaskPriority;\n\nTEST_CLASS(QueryExecutorBuilderVisitorTests) {\n\tTEST_METHOD(getsCorrectTypeForAddQueries) {\n\t\tMocks::TaskList taskList;\n\t\tQueryExecutorBuilderVisitor visitor(taskList);\n\n\t\tYou::NLP::QUERY query(Mocks::Queries::ADD_QUERY);\n\t\tstd::unique_ptr executor(\n\t\t\tboost::apply_visitor(visitor, query));\n\t\tADD_RESULT result(\n\t\t\tboost::get(executor->execute()));\n\n\t\tAssert::AreEqual(\n\t\t\tMocks::Queries::ADD_QUERY.description,\n\t\t\tresult.task.getDescription());\n\t\tAssert::AreEqual(\n\t\t\tTask::Priority::NORMAL,\n\t\t\tresult.task.getPriority());\n\t\tAssert::AreEqual(\n\t\t\tMocks::Queries::ADD_QUERY.deadline.get(),\n\t\t\tresult.task.getDeadline());\n\n\t\tYou::NLP::ADD_QUERY queryWithoutDeadline(Mocks::Queries::ADD_QUERY);\n\t\tqueryWithoutDeadline.deadline =\n\t\t\tYou::Utils::Option();\n\t\tquery = queryWithoutDeadline;\n\t\texecutor = boost::apply_visitor(visitor, query);\n\t\tresult = boost::get(executor->execute());\n\n\t\tAssert::AreEqual(\n\t\t\tMocks::Queries::ADD_QUERY.description,\n\t\t\tresult.task.getDescription());\n\t\tAssert::AreEqual(\n\t\t\tTask::Priority::NORMAL,\n\t\t\tresult.task.getPriority());\n\t\tAssert::AreEqual(\n\t\t\tTask::DEFAULT_DEADLINE,\n\t\t\tresult.task.getDeadline());\n\n\t\tYou::NLP::ADD_QUERY queryWithPriority(Mocks::Queries::ADD_QUERY);\n\t\tqueryWithPriority.priority = TaskPriority::HIGH;\n\t\tquery = queryWithPriority;\n\t\texecutor = boost::apply_visitor(visitor, query);\n\t\tresult = boost::get(executor->execute());\n\n\t\tAssert::AreEqual(\n\t\t\tMocks::Queries::ADD_QUERY.description,\n\t\t\tresult.task.getDescription());\n\t\tAssert::AreEqual(\n\t\t\tTask::Priority::HIGH,\n\t\t\tresult.task.getPriority());\n\t\tAssert::AreEqual(\n\t\t\tMocks::Queries::ADD_QUERY.deadline.get(),\n\t\t\tresult.task.getDeadline());\n\t}\n\n\tTEST_METHOD(getsCorrectTypeForShowQueries) {\n\t\tMocks::TaskList taskList(5);\n\t\tQueryExecutorBuilderVisitor visitor(taskList);\n\n\t\tYou::NLP::QUERY query(Mocks::Queries::SHOW_QUERY);\n\t\tstd::unique_ptr executor(\n\t\t\tboost::apply_visitor(visitor, query));\n\t\tSHOW_RESULT result(\n\t\t\tboost::get(executor->execute()));\n\n\t\tAssert::IsTrue(\n\t\t\tstd::is_sorted(begin(result.tasks), end(result.tasks),\n\t\t\t[](const Task& left, const Task& right) {\n\t\t\t\treturn left.getDeadline() >= right.getDeadline();\n\t\t}));\n\n\t\t{ \/\/ NOLINT(whitespace\/braces)\n\t\t\tYou::NLP::SHOW_QUERY templ = Mocks::Queries::SHOW_QUERY;\n\t\t\ttempl.order = {\n\t\t\t\t{\n\t\t\t\t\tYou::NLP::TaskField::DESCRIPTION,\n\t\t\t\t\tYou::NLP::SHOW_QUERY::Order::ASCENDING\n\t\t\t\t}\n\t\t\t};\n\t\t\tquery = std::move(templ);\n\t\t}\n\t\texecutor = boost::apply_visitor(visitor, query);\n\t\tresult = boost::get(executor->execute());\n\n\t\tAssert::IsTrue(\n\t\t\tstd::is_sorted(begin(result.tasks), end(result.tasks),\n\t\t\t[](const Task& left, const Task& right) {\n\t\t\treturn left.getDescription() <= right.getDescription();\n\t\t}));\n\n\t\t{ \/\/ NOLINT(whitespace\/braces)\n\t\t\tYou::NLP::SHOW_QUERY templ = Mocks::Queries::SHOW_QUERY;\n\t\t\ttempl.order = {\n\t\t\t\t{\n\t\t\t\t\tYou::NLP::TaskField::PRIORITY,\n\t\t\t\t\tYou::NLP::SHOW_QUERY::Order::DESCENDING\n\t\t\t\t}\n\t\t\t};\n\t\t\tquery = std::move(templ);\n\t\t}\n\t\texecutor = boost::apply_visitor(visitor, query);\n\t\tresult = boost::get(executor->execute());\n\n\t\tAssert::IsTrue(\n\t\t\tstd::is_sorted(begin(result.tasks), end(result.tasks),\n\t\t\t[](const Task& left, const Task& right) {\n\t\t\treturn left.getPriority() >= right.getPriority();\n\t\t}));\n\t}\n\n\tTEST_METHOD(getsCorrectTypeForEditQueries) {\n\t\tgetsCorrectTypeForEditQueries1();\n\t\tgetsCorrectTypeForEditQueries2();\n\t\tgetsCorrectTypeForEditQueries3();\n\t\tgetsCorrectTypeForEditQueries4();\n\t}\n\n\tvoid getsCorrectTypeForEditQueries1() {\n\t\tMocks::TaskList taskList;\n\t\tQueryExecutorBuilderVisitor visitor(taskList);\n\n\t\tYou::NLP::QUERY query(Mocks::Queries::EDIT_QUERY);\n\t\tstd::unique_ptr executor(\n\t\t\tboost::apply_visitor(visitor, query));\n\t\tEDIT_RESULT result(\n\t\t\tboost::get(executor->execute()));\n\n\t\tAssert::AreEqual(taskList.front().getID(),\n\t\t\tresult.task.getID());\n\t\tAssert::AreEqual(Mocks::Queries::EDIT_QUERY.description.get(),\n\t\t\tresult.task.getDescription());\n\t\tAssert::AreEqual(nlpPriorityToTaskPriority(\n\t\t\tMocks::Queries::EDIT_QUERY.priority.get()),\n\t\t\tresult.task.getPriority());\n\t\tAssert::AreEqual(Mocks::Queries::EDIT_QUERY.deadline.get(),\n\t\t\tresult.task.getDeadline());\n\t}\n\n\tvoid getsCorrectTypeForEditQueries2() {\n\t\tMocks::TaskList taskList;\n\t\tQueryExecutorBuilderVisitor visitor(taskList);\n\n\t\tYou::NLP::EDIT_QUERY query2(Mocks::Queries::EDIT_QUERY);\n\t\tquery2.deadline =\n\t\t\tYou::Utils::Option();\n\t\tYou::NLP::QUERY query(query2);\n\t\tstd::unique_ptr executor(\n\t\t\tboost::apply_visitor(visitor, query));\n\t\tEDIT_RESULT result(\n\t\t\tboost::get(executor->execute()));\n\n\t\tAssert::AreEqual(taskList.front().getID(),\n\t\t\tresult.task.getID());\n\t\tAssert::AreEqual(Mocks::Queries::EDIT_QUERY.description.get(),\n\t\t\tresult.task.getDescription());\n\t\tAssert::AreEqual(nlpPriorityToTaskPriority(\n\t\t\tMocks::Queries::EDIT_QUERY.priority.get()),\n\t\t\tresult.task.getPriority());\n\t\tAssert::AreEqual(taskList.front().getDeadline(),\n\t\t\tresult.task.getDeadline());\n\t}\n\n\tvoid getsCorrectTypeForEditQueries3() {\n\t\tMocks::TaskList taskList;\n\t\tQueryExecutorBuilderVisitor visitor(taskList);\n\n\t\tYou::NLP::EDIT_QUERY query2(Mocks::Queries::EDIT_QUERY);\n\t\tquery2.description =\n\t\t\tYou::Utils::Option();\n\t\tYou::NLP::QUERY query(query2);\n\t\tstd::unique_ptr executor(\n\t\t\tboost::apply_visitor(visitor, query));\n\t\tEDIT_RESULT result(\n\t\t\tboost::get(executor->execute()));\n\n\t\tAssert::AreEqual(taskList.front().getID(),\n\t\t\tresult.task.getID());\n\t\tAssert::AreEqual(taskList.front().getDescription(),\n\t\t\tresult.task.getDescription());\n\t\tAssert::AreEqual(nlpPriorityToTaskPriority(\n\t\t\tMocks::Queries::EDIT_QUERY.priority.get()),\n\t\t\tresult.task.getPriority());\n\t\tAssert::AreEqual(Mocks::Queries::EDIT_QUERY.deadline.get(),\n\t\t\tresult.task.getDeadline());\n\t}\n\n\tvoid getsCorrectTypeForEditQueries4() {\n\t\tMocks::TaskList taskList;\n\t\tQueryExecutorBuilderVisitor visitor(taskList);\n\n\t\tYou::NLP::EDIT_QUERY query2(Mocks::Queries::EDIT_QUERY);\n\t\tquery2.priority =\n\t\t\tYou::Utils::Option();\n\t\tYou::NLP::QUERY query(query2);\n\t\tstd::unique_ptr executor(\n\t\t\tboost::apply_visitor(visitor, query));\n\t\tEDIT_RESULT result(\n\t\t\tboost::get(executor->execute()));\n\n\t\tAssert::AreEqual(taskList.front().getID(),\n\t\t\tresult.task.getID());\n\t\tAssert::AreEqual(Mocks::Queries::EDIT_QUERY.description.get(),\n\t\t\tresult.task.getDescription());\n\t\tAssert::AreEqual(taskList.front().getPriority(),\n\t\t\tresult.task.getPriority());\n\t\tAssert::AreEqual(Mocks::Queries::EDIT_QUERY.deadline.get(),\n\t\t\tresult.task.getDeadline());\n\t}\n\n\tTEST_METHOD(editQueriesOutOfBoundsThrowsContextOutOfRange) {\n\t\tMocks::TaskList taskList(0);\n\t\tQueryExecutorBuilderVisitor visitor(taskList);\n\n\t\tYou::NLP::QUERY query(Mocks::Queries::EDIT_QUERY);\n\t\tAssert::ExpectException([&]() {\n\t\t\tboost::apply_visitor(visitor, query);\n\t\t});\n\t}\n\n\tTEST_METHOD(getsCorrectTypeForDeleteQueries) {\n\t\tMocks::TaskList taskList;\n\t\tQueryExecutorBuilderVisitor visitor(taskList);\n\n\t\tYou::NLP::QUERY query(Mocks::Queries::DELETE_QUERY);\n\t\tstd::unique_ptr executor(\n\t\t\tboost::apply_visitor(visitor, query));\n\t\tDELETE_RESULT result(\n\t\t\tboost::get(executor->execute()));\n\n\t\tAssert::AreEqual(taskList.front().getID(),\n\t\t\tresult.task);\n\t}\n\n\tTEST_METHOD(deleteQueriesOutOfBoundsThrowsContextOutOfRange) {\n\t\tMocks::TaskList taskList(0);\n\t\tQueryExecutorBuilderVisitor visitor(taskList);\n\n\t\tYou::NLP::QUERY query(Mocks::Queries::DELETE_QUERY);\n\t\tAssert::ExpectException([&]() {\n\t\t\tboost::apply_visitor(visitor, query);\n\t\t});\n\t}\n\n\tTEST_METHOD(getsCorrectTypeForUndoQueries) {\n\t\tMocks::TaskList taskList;\n\t\tQueryExecutorBuilderVisitor visitor(taskList);\n\n\t\tYou::NLP::QUERY query(Mocks::Queries::UNDO_QUERY);\n\t\tstd::unique_ptr executor(\n\t\t\tboost::apply_visitor(visitor, query));\n\t\tUNDO_RESULT result(\n\t\t\tboost::get(executor->execute()));\n\n\t\t\/\/ TODO(lowjoel): test for..?\n\t}\n\nprivate:\n\tTask::Priority nlpPriorityToTaskPriority(NLP::TaskPriority priority) {\n\t\tauto iterator = nlpPriorityToTaskPriorityMap.find(priority);\n\t\tassert(iterator != end(nlpPriorityToTaskPriorityMap));\n\t\treturn iterator->second;\n\t}\n\nprivate:\n\tstatic const std::unordered_map\n\t\tnlpPriorityToTaskPriorityMap;\n};\n\nconst std::unordered_map\nQueryExecutorBuilderVisitorTests::nlpPriorityToTaskPriorityMap({\n\t{ NLP::TaskPriority::NORMAL, Task::Priority::NORMAL },\n\t{ NLP::TaskPriority::HIGH, Task::Priority::HIGH }\n});\n\n} \/\/ namespace UnitTests\n} \/\/ namespace Internal\n} \/\/ namespace Controller\n} \/\/ namespace You\nComparators in C++ never check for equality.\/\/@author A0097630B\n#include \"stdafx.h\"\n#include \n#include \"You-NLP\/parse_tree\/task_priority.h\"\n#include \"internal\/query_executor.h\"\n#include \"internal\/query_executor_builder_visitor.h\"\n#include \"exceptions\/context_index_out_of_range_exception.h\"\n\n#include \"..\/mocks\/task_list.h\"\n#include \"..\/mocks\/query.h\"\n\nusing Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;\n\nnamespace Microsoft {\nnamespace VisualStudio {\nnamespace CppUnitTestFramework {\n\nstd::wstring ToString(You::Controller::Task::Priority priority) {\n\treturn ToString(static_cast(priority));\n}\n\n} \/\/ namespace CppUnitTestFramework\n} \/\/ namespace VisualStudio\n} \/\/ namespace Microsoft\n\nnamespace You {\nnamespace Controller {\nnamespace Internal {\nnamespace UnitTests {\n\nnamespace Mocks {\n\t\/\/ NOLINTNEXTLINE(build\/namespaces)\n\tusing namespace You::Controller::UnitTests::Mocks;\n}\n\nusing Task = You::Controller::Task;\nusing TaskPriority = You::NLP::TaskPriority;\n\nTEST_CLASS(QueryExecutorBuilderVisitorTests) {\n\tTEST_METHOD(getsCorrectTypeForAddQueries) {\n\t\tMocks::TaskList taskList;\n\t\tQueryExecutorBuilderVisitor visitor(taskList);\n\n\t\tYou::NLP::QUERY query(Mocks::Queries::ADD_QUERY);\n\t\tstd::unique_ptr executor(\n\t\t\tboost::apply_visitor(visitor, query));\n\t\tADD_RESULT result(\n\t\t\tboost::get(executor->execute()));\n\n\t\tAssert::AreEqual(\n\t\t\tMocks::Queries::ADD_QUERY.description,\n\t\t\tresult.task.getDescription());\n\t\tAssert::AreEqual(\n\t\t\tTask::Priority::NORMAL,\n\t\t\tresult.task.getPriority());\n\t\tAssert::AreEqual(\n\t\t\tMocks::Queries::ADD_QUERY.deadline.get(),\n\t\t\tresult.task.getDeadline());\n\n\t\tYou::NLP::ADD_QUERY queryWithoutDeadline(Mocks::Queries::ADD_QUERY);\n\t\tqueryWithoutDeadline.deadline =\n\t\t\tYou::Utils::Option();\n\t\tquery = queryWithoutDeadline;\n\t\texecutor = boost::apply_visitor(visitor, query);\n\t\tresult = boost::get(executor->execute());\n\n\t\tAssert::AreEqual(\n\t\t\tMocks::Queries::ADD_QUERY.description,\n\t\t\tresult.task.getDescription());\n\t\tAssert::AreEqual(\n\t\t\tTask::Priority::NORMAL,\n\t\t\tresult.task.getPriority());\n\t\tAssert::AreEqual(\n\t\t\tTask::DEFAULT_DEADLINE,\n\t\t\tresult.task.getDeadline());\n\n\t\tYou::NLP::ADD_QUERY queryWithPriority(Mocks::Queries::ADD_QUERY);\n\t\tqueryWithPriority.priority = TaskPriority::HIGH;\n\t\tquery = queryWithPriority;\n\t\texecutor = boost::apply_visitor(visitor, query);\n\t\tresult = boost::get(executor->execute());\n\n\t\tAssert::AreEqual(\n\t\t\tMocks::Queries::ADD_QUERY.description,\n\t\t\tresult.task.getDescription());\n\t\tAssert::AreEqual(\n\t\t\tTask::Priority::HIGH,\n\t\t\tresult.task.getPriority());\n\t\tAssert::AreEqual(\n\t\t\tMocks::Queries::ADD_QUERY.deadline.get(),\n\t\t\tresult.task.getDeadline());\n\t}\n\n\tTEST_METHOD(getsCorrectTypeForShowQueries) {\n\t\tMocks::TaskList taskList(5);\n\t\tQueryExecutorBuilderVisitor visitor(taskList);\n\n\t\tYou::NLP::QUERY query(Mocks::Queries::SHOW_QUERY);\n\t\tstd::unique_ptr executor(\n\t\t\tboost::apply_visitor(visitor, query));\n\t\tSHOW_RESULT result(\n\t\t\tboost::get(executor->execute()));\n\n\t\tAssert::IsTrue(\n\t\t\tstd::is_sorted(begin(result.tasks), end(result.tasks),\n\t\t\t[](const Task& left, const Task& right) {\n\t\t\t\treturn left.getDeadline() > right.getDeadline();\n\t\t}));\n\n\t\t{ \/\/ NOLINT(whitespace\/braces)\n\t\t\tYou::NLP::SHOW_QUERY templ = Mocks::Queries::SHOW_QUERY;\n\t\t\ttempl.order = {\n\t\t\t\t{\n\t\t\t\t\tYou::NLP::TaskField::DESCRIPTION,\n\t\t\t\t\tYou::NLP::SHOW_QUERY::Order::ASCENDING\n\t\t\t\t}\n\t\t\t};\n\t\t\tquery = std::move(templ);\n\t\t}\n\t\texecutor = boost::apply_visitor(visitor, query);\n\t\tresult = boost::get(executor->execute());\n\n\t\tAssert::IsTrue(\n\t\t\tstd::is_sorted(begin(result.tasks), end(result.tasks),\n\t\t\t[](const Task& left, const Task& right) {\n\t\t\treturn left.getDescription() < right.getDescription();\n\t\t}));\n\n\t\t{ \/\/ NOLINT(whitespace\/braces)\n\t\t\tYou::NLP::SHOW_QUERY templ = Mocks::Queries::SHOW_QUERY;\n\t\t\ttempl.order = {\n\t\t\t\t{\n\t\t\t\t\tYou::NLP::TaskField::PRIORITY,\n\t\t\t\t\tYou::NLP::SHOW_QUERY::Order::DESCENDING\n\t\t\t\t}\n\t\t\t};\n\t\t\tquery = std::move(templ);\n\t\t}\n\t\texecutor = boost::apply_visitor(visitor, query);\n\t\tresult = boost::get(executor->execute());\n\n\t\tAssert::IsTrue(\n\t\t\tstd::is_sorted(begin(result.tasks), end(result.tasks),\n\t\t\t[](const Task& left, const Task& right) {\n\t\t\treturn left.getPriority() > right.getPriority();\n\t\t}));\n\t}\n\n\tTEST_METHOD(getsCorrectTypeForEditQueries) {\n\t\tgetsCorrectTypeForEditQueries1();\n\t\tgetsCorrectTypeForEditQueries2();\n\t\tgetsCorrectTypeForEditQueries3();\n\t\tgetsCorrectTypeForEditQueries4();\n\t}\n\n\tvoid getsCorrectTypeForEditQueries1() {\n\t\tMocks::TaskList taskList;\n\t\tQueryExecutorBuilderVisitor visitor(taskList);\n\n\t\tYou::NLP::QUERY query(Mocks::Queries::EDIT_QUERY);\n\t\tstd::unique_ptr executor(\n\t\t\tboost::apply_visitor(visitor, query));\n\t\tEDIT_RESULT result(\n\t\t\tboost::get(executor->execute()));\n\n\t\tAssert::AreEqual(taskList.front().getID(),\n\t\t\tresult.task.getID());\n\t\tAssert::AreEqual(Mocks::Queries::EDIT_QUERY.description.get(),\n\t\t\tresult.task.getDescription());\n\t\tAssert::AreEqual(nlpPriorityToTaskPriority(\n\t\t\tMocks::Queries::EDIT_QUERY.priority.get()),\n\t\t\tresult.task.getPriority());\n\t\tAssert::AreEqual(Mocks::Queries::EDIT_QUERY.deadline.get(),\n\t\t\tresult.task.getDeadline());\n\t}\n\n\tvoid getsCorrectTypeForEditQueries2() {\n\t\tMocks::TaskList taskList;\n\t\tQueryExecutorBuilderVisitor visitor(taskList);\n\n\t\tYou::NLP::EDIT_QUERY query2(Mocks::Queries::EDIT_QUERY);\n\t\tquery2.deadline =\n\t\t\tYou::Utils::Option();\n\t\tYou::NLP::QUERY query(query2);\n\t\tstd::unique_ptr executor(\n\t\t\tboost::apply_visitor(visitor, query));\n\t\tEDIT_RESULT result(\n\t\t\tboost::get(executor->execute()));\n\n\t\tAssert::AreEqual(taskList.front().getID(),\n\t\t\tresult.task.getID());\n\t\tAssert::AreEqual(Mocks::Queries::EDIT_QUERY.description.get(),\n\t\t\tresult.task.getDescription());\n\t\tAssert::AreEqual(nlpPriorityToTaskPriority(\n\t\t\tMocks::Queries::EDIT_QUERY.priority.get()),\n\t\t\tresult.task.getPriority());\n\t\tAssert::AreEqual(taskList.front().getDeadline(),\n\t\t\tresult.task.getDeadline());\n\t}\n\n\tvoid getsCorrectTypeForEditQueries3() {\n\t\tMocks::TaskList taskList;\n\t\tQueryExecutorBuilderVisitor visitor(taskList);\n\n\t\tYou::NLP::EDIT_QUERY query2(Mocks::Queries::EDIT_QUERY);\n\t\tquery2.description =\n\t\t\tYou::Utils::Option();\n\t\tYou::NLP::QUERY query(query2);\n\t\tstd::unique_ptr executor(\n\t\t\tboost::apply_visitor(visitor, query));\n\t\tEDIT_RESULT result(\n\t\t\tboost::get(executor->execute()));\n\n\t\tAssert::AreEqual(taskList.front().getID(),\n\t\t\tresult.task.getID());\n\t\tAssert::AreEqual(taskList.front().getDescription(),\n\t\t\tresult.task.getDescription());\n\t\tAssert::AreEqual(nlpPriorityToTaskPriority(\n\t\t\tMocks::Queries::EDIT_QUERY.priority.get()),\n\t\t\tresult.task.getPriority());\n\t\tAssert::AreEqual(Mocks::Queries::EDIT_QUERY.deadline.get(),\n\t\t\tresult.task.getDeadline());\n\t}\n\n\tvoid getsCorrectTypeForEditQueries4() {\n\t\tMocks::TaskList taskList;\n\t\tQueryExecutorBuilderVisitor visitor(taskList);\n\n\t\tYou::NLP::EDIT_QUERY query2(Mocks::Queries::EDIT_QUERY);\n\t\tquery2.priority =\n\t\t\tYou::Utils::Option();\n\t\tYou::NLP::QUERY query(query2);\n\t\tstd::unique_ptr executor(\n\t\t\tboost::apply_visitor(visitor, query));\n\t\tEDIT_RESULT result(\n\t\t\tboost::get(executor->execute()));\n\n\t\tAssert::AreEqual(taskList.front().getID(),\n\t\t\tresult.task.getID());\n\t\tAssert::AreEqual(Mocks::Queries::EDIT_QUERY.description.get(),\n\t\t\tresult.task.getDescription());\n\t\tAssert::AreEqual(taskList.front().getPriority(),\n\t\t\tresult.task.getPriority());\n\t\tAssert::AreEqual(Mocks::Queries::EDIT_QUERY.deadline.get(),\n\t\t\tresult.task.getDeadline());\n\t}\n\n\tTEST_METHOD(editQueriesOutOfBoundsThrowsContextOutOfRange) {\n\t\tMocks::TaskList taskList(0);\n\t\tQueryExecutorBuilderVisitor visitor(taskList);\n\n\t\tYou::NLP::QUERY query(Mocks::Queries::EDIT_QUERY);\n\t\tAssert::ExpectException([&]() {\n\t\t\tboost::apply_visitor(visitor, query);\n\t\t});\n\t}\n\n\tTEST_METHOD(getsCorrectTypeForDeleteQueries) {\n\t\tMocks::TaskList taskList;\n\t\tQueryExecutorBuilderVisitor visitor(taskList);\n\n\t\tYou::NLP::QUERY query(Mocks::Queries::DELETE_QUERY);\n\t\tstd::unique_ptr executor(\n\t\t\tboost::apply_visitor(visitor, query));\n\t\tDELETE_RESULT result(\n\t\t\tboost::get(executor->execute()));\n\n\t\tAssert::AreEqual(taskList.front().getID(),\n\t\t\tresult.task);\n\t}\n\n\tTEST_METHOD(deleteQueriesOutOfBoundsThrowsContextOutOfRange) {\n\t\tMocks::TaskList taskList(0);\n\t\tQueryExecutorBuilderVisitor visitor(taskList);\n\n\t\tYou::NLP::QUERY query(Mocks::Queries::DELETE_QUERY);\n\t\tAssert::ExpectException([&]() {\n\t\t\tboost::apply_visitor(visitor, query);\n\t\t});\n\t}\n\n\tTEST_METHOD(getsCorrectTypeForUndoQueries) {\n\t\tMocks::TaskList taskList;\n\t\tQueryExecutorBuilderVisitor visitor(taskList);\n\n\t\tYou::NLP::QUERY query(Mocks::Queries::UNDO_QUERY);\n\t\tstd::unique_ptr executor(\n\t\t\tboost::apply_visitor(visitor, query));\n\t\tUNDO_RESULT result(\n\t\t\tboost::get(executor->execute()));\n\n\t\t\/\/ TODO(lowjoel): test for..?\n\t}\n\nprivate:\n\tTask::Priority nlpPriorityToTaskPriority(NLP::TaskPriority priority) {\n\t\tauto iterator = nlpPriorityToTaskPriorityMap.find(priority);\n\t\tassert(iterator != end(nlpPriorityToTaskPriorityMap));\n\t\treturn iterator->second;\n\t}\n\nprivate:\n\tstatic const std::unordered_map\n\t\tnlpPriorityToTaskPriorityMap;\n};\n\nconst std::unordered_map\nQueryExecutorBuilderVisitorTests::nlpPriorityToTaskPriorityMap({\n\t{ NLP::TaskPriority::NORMAL, Task::Priority::NORMAL },\n\t{ NLP::TaskPriority::HIGH, Task::Priority::HIGH }\n});\n\n} \/\/ namespace UnitTests\n} \/\/ namespace Internal\n} \/\/ namespace Controller\n} \/\/ namespace You\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/process_util.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/tabs\/tab_strip_model.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/find_bar\/find_bar_controller.h\"\n#include \"chrome\/browser\/ui\/find_bar\/find_notification_details.h\"\n#include \"chrome\/browser\/ui\/view_ids.h\"\n#include \"chrome\/browser\/ui\/views\/find_bar_host.h\"\n#include \"chrome\/browser\/ui\/views\/frame\/browser_view.h\"\n#include \"chrome\/common\/chrome_notification_types.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/browser\/notification_service.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"net\/test\/test_server.h\"\n#include \"ui\/base\/clipboard\/clipboard.h\"\n#include \"ui\/base\/keycodes\/keyboard_codes.h\"\n#include \"ui\/views\/focus\/focus_manager.h\"\n#include \"ui\/views\/view.h\"\n#include \"ui\/views\/views_delegate.h\"\n\nusing content::WebContents;\n\nnamespace {\n\n\/\/ The delay waited after sending an OS simulated event.\nstatic const int kActionDelayMs = 500;\nstatic const char kSimplePage[] = \"files\/find_in_page\/simple.html\";\n\nvoid Checkpoint(const char* message, const base::TimeTicks& start_time) {\n LOG(INFO) << message << \" : \"\n << (base::TimeTicks::Now() - start_time).InMilliseconds()\n << \" ms\" << std::flush;\n}\n\nclass FindInPageTest : public InProcessBrowserTest {\n public:\n FindInPageTest() :\n#if defined(USE_AURA)\n location_bar_focus_view_id_(VIEW_ID_OMNIBOX)\n#else\n location_bar_focus_view_id_(VIEW_ID_LOCATION_BAR)\n#endif\n {\n set_show_window(true);\n FindBarHost::disable_animations_during_testing_ = true;\n }\n\n string16 GetFindBarText() {\n FindBarTesting* find_bar =\n browser()->GetFindBarController()->find_bar()->GetFindBarTesting();\n return find_bar->GetFindText();\n }\n\n string16 GetFindBarSelectedText() {\n FindBarTesting* find_bar =\n browser()->GetFindBarController()->find_bar()->GetFindBarTesting();\n return find_bar->GetFindSelectedText();\n }\n\n ViewID location_bar_focus_view_id_;\n\n private:\n DISALLOW_COPY_AND_ASSIGN(FindInPageTest);\n};\n\n} \/\/ namespace\n\nIN_PROC_BROWSER_TEST_F(FindInPageTest, CrashEscHandlers) {\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ First we navigate to our test page (tab A).\n GURL url = test_server()->GetURL(kSimplePage);\n ui_test_utils::NavigateToURL(browser(), url);\n\n browser()->Find();\n\n \/\/ Open another tab (tab B).\n browser()->AddSelectedTabWithURL(url, content::PAGE_TRANSITION_TYPED);\n\n browser()->Find();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n\n \/\/ Select tab A.\n browser()->ActivateTabAt(0, true);\n\n \/\/ Close tab B.\n browser()->CloseTabContents(browser()->GetWebContentsAt(1));\n\n \/\/ Click on the location bar so that Find box loses focus.\n ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(),\n VIEW_ID_LOCATION_BAR));\n \/\/ Check the location bar is focused.\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n location_bar_focus_view_id_));\n\n \/\/ This used to crash until bug 1303709 was fixed.\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_ESCAPE, false, false, false, false));\n}\n\nIN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestore) {\n ASSERT_TRUE(test_server()->Start());\n\n GURL url = test_server()->GetURL(\"title1.html\");\n ui_test_utils::NavigateToURL(browser(), url);\n\n \/\/ Focus the location bar, open and close the find-in-page, focus should\n \/\/ return to the location bar.\n browser()->FocusLocationBar();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n location_bar_focus_view_id_));\n \/\/ Ensure the creation of the find bar controller.\n browser()->GetFindBarController()->Show();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n browser()->GetFindBarController()->EndFindSession(\n FindBarController::kKeepSelection);\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n location_bar_focus_view_id_));\n\n \/\/ Focus the location bar, find something on the page, close the find box,\n \/\/ focus should go to the page.\n browser()->FocusLocationBar();\n browser()->Find();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),\n ASCIIToUTF16(\"a\"), true, false, NULL);\n browser()->GetFindBarController()->EndFindSession(\n FindBarController::kKeepSelection);\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));\n\n \/\/ Focus the location bar, open and close the find box, focus should return to\n \/\/ the location bar (same as before, just checking that http:\/\/crbug.com\/23599\n \/\/ is fixed).\n browser()->FocusLocationBar();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n location_bar_focus_view_id_));\n browser()->GetFindBarController()->Show();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n browser()->GetFindBarController()->EndFindSession(\n FindBarController::kKeepSelection);\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n location_bar_focus_view_id_));\n}\n\nIN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestoreOnTabSwitch) {\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ First we navigate to our test page (tab A).\n GURL url = test_server()->GetURL(kSimplePage);\n ui_test_utils::NavigateToURL(browser(), url);\n\n browser()->Find();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n\n FindBarTesting* find_bar =\n browser()->GetFindBarController()->find_bar()->GetFindBarTesting();\n\n \/\/ Search for 'a'.\n ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),\n ASCIIToUTF16(\"a\"), true, false, NULL);\n EXPECT_TRUE(ASCIIToUTF16(\"a\") == find_bar->GetFindSelectedText());\n\n \/\/ Open another tab (tab B).\n ui_test_utils::WindowedNotificationObserver observer(\n content::NOTIFICATION_LOAD_STOP,\n content::NotificationService::AllSources());\n browser()->AddSelectedTabWithURL(url, content::PAGE_TRANSITION_TYPED);\n observer.Wait();\n\n \/\/ Make sure Find box is open.\n browser()->Find();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n\n \/\/ Search for 'b'.\n ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),\n ASCIIToUTF16(\"b\"), true, false, NULL);\n EXPECT_TRUE(ASCIIToUTF16(\"b\") == find_bar->GetFindSelectedText());\n\n \/\/ Set focus away from the Find bar (to the Location bar).\n browser()->FocusLocationBar();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n location_bar_focus_view_id_));\n\n \/\/ Select tab A. Find bar should get focus.\n browser()->ActivateTabAt(0, true);\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n EXPECT_TRUE(ASCIIToUTF16(\"a\") == find_bar->GetFindSelectedText());\n\n \/\/ Select tab B. Location bar should get focus.\n browser()->ActivateTabAt(1, true);\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n location_bar_focus_view_id_));\n}\n\n\/\/ This tests that whenever you clear values from the Find box and close it that\n\/\/ it respects that and doesn't show you the last search, as reported in bug:\n\/\/ http:\/\/crbug.com\/40121.\nIN_PROC_BROWSER_TEST_F(FindInPageTest, PrepopulateRespectBlank) {\n#if defined(OS_MACOSX)\n \/\/ FindInPage on Mac doesn't use prepopulated values. Search there is global.\n return;\n#endif\n base::TimeTicks start_time = base::TimeTicks::Now();\n Checkpoint(\"Test starting\", start_time);\n\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ Make sure Chrome is in the foreground, otherwise sending input\n \/\/ won't do anything and the test will hang.\n ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));\n\n Checkpoint(\"Navigate\", start_time);\n\n \/\/ First we navigate to any page.\n GURL url = test_server()->GetURL(kSimplePage);\n ui_test_utils::NavigateToURL(browser(), url);\n\n Checkpoint(\"Show Find bar\", start_time);\n\n \/\/ Show the Find bar.\n browser()->GetFindBarController()->Show();\n\n Checkpoint(\"Search for 'a'\", start_time);\n\n \/\/ Search for \"a\".\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_A, false, false, false, false));\n\n \/\/ We should find \"a\" here.\n EXPECT_EQ(ASCIIToUTF16(\"a\"), GetFindBarText());\n\n Checkpoint(\"Delete 'a'\", start_time);\n\n \/\/ Delete \"a\".\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_BACK, false, false, false, false));\n\n \/\/ Validate we have cleared the text.\n EXPECT_EQ(string16(), GetFindBarText());\n\n Checkpoint(\"Close find bar\", start_time);\n\n \/\/ Close the Find box.\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_ESCAPE, false, false, false, false));\n\n Checkpoint(\"Show Find bar\", start_time);\n\n \/\/ Show the Find bar.\n browser()->GetFindBarController()->Show();\n\n Checkpoint(\"Validate text\", start_time);\n\n \/\/ After the Find box has been reopened, it should not have been prepopulated\n \/\/ with \"a\" again.\n EXPECT_EQ(string16(), GetFindBarText());\n\n Checkpoint(\"Close Find bar\", start_time);\n\n \/\/ Close the Find box.\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_ESCAPE, false, false, false, false));\n\n Checkpoint(\"FindNext\", start_time);\n\n \/\/ Press F3 to trigger FindNext.\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_F3, false, false, false, false));\n\n Checkpoint(\"Validate\", start_time);\n\n \/\/ After the Find box has been reopened, it should still have no prepopulate\n \/\/ value.\n EXPECT_EQ(string16(), GetFindBarText());\n\n Checkpoint(\"Test done\", start_time);\n}\n\n\/\/ Flaky on Win. http:\/\/crbug.com\/92467\n#if defined(OS_WIN)\n#define MAYBE_PasteWithoutTextChange DISABLED_PasteWithoutTextChange\n#else\n#define MAYBE_PasteWithoutTextChange PasteWithoutTextChange\n#endif\n\nIN_PROC_BROWSER_TEST_F(FindInPageTest, MAYBE_PasteWithoutTextChange) {\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ Make sure Chrome is in the foreground, otherwise sending input\n \/\/ won't do anything and the test will hang.\n ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));\n\n \/\/ First we navigate to any page.\n GURL url = test_server()->GetURL(kSimplePage);\n ui_test_utils::NavigateToURL(browser(), url);\n\n \/\/ Show the Find bar.\n browser()->GetFindBarController()->Show();\n\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n\n \/\/ Search for \"a\".\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_A, false, false, false, false));\n\n \/\/ We should find \"a\" here.\n EXPECT_EQ(ASCIIToUTF16(\"a\"), GetFindBarText());\n\n \/\/ Reload the page to clear the matching result.\n browser()->Reload(CURRENT_TAB);\n\n \/\/ Focus the Find bar again to make sure the text is selected.\n browser()->GetFindBarController()->Show();\n\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n\n \/\/ \"a\" should be selected.\n EXPECT_EQ(ASCIIToUTF16(\"a\"), GetFindBarSelectedText());\n\n \/\/ Press Ctrl-C to copy the content.\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_C, true, false, false, false));\n\n string16 str;\n views::ViewsDelegate::views_delegate->GetClipboard()->\n ReadText(ui::Clipboard::BUFFER_STANDARD, &str);\n\n \/\/ Make sure the text is copied successfully.\n EXPECT_EQ(ASCIIToUTF16(\"a\"), str);\n\n \/\/ Press Ctrl-V to paste the content back, it should start finding even if the\n \/\/ content is not changed.\n content::Source notification_source(\n browser()->GetSelectedWebContents());\n ui_test_utils::WindowedNotificationObserverWithDetails\n observer(\n chrome::NOTIFICATION_FIND_RESULT_AVAILABLE, notification_source);\n\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_V, true, false, false, false));\n\n ASSERT_NO_FATAL_FAILURE(observer.Wait());\n FindNotificationDetails details;\n ASSERT_TRUE(observer.GetDetailsFor(notification_source.map_key(), &details));\n EXPECT_TRUE(details.number_of_matches() > 0);\n}\nMark FindInPageTest.PasteWithoutTextChange flaky on CrOS\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/process_util.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/tabs\/tab_strip_model.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/find_bar\/find_bar_controller.h\"\n#include \"chrome\/browser\/ui\/find_bar\/find_notification_details.h\"\n#include \"chrome\/browser\/ui\/view_ids.h\"\n#include \"chrome\/browser\/ui\/views\/find_bar_host.h\"\n#include \"chrome\/browser\/ui\/views\/frame\/browser_view.h\"\n#include \"chrome\/common\/chrome_notification_types.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/browser\/notification_service.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"net\/test\/test_server.h\"\n#include \"ui\/base\/clipboard\/clipboard.h\"\n#include \"ui\/base\/keycodes\/keyboard_codes.h\"\n#include \"ui\/views\/focus\/focus_manager.h\"\n#include \"ui\/views\/view.h\"\n#include \"ui\/views\/views_delegate.h\"\n\nusing content::WebContents;\n\nnamespace {\n\n\/\/ The delay waited after sending an OS simulated event.\nstatic const int kActionDelayMs = 500;\nstatic const char kSimplePage[] = \"files\/find_in_page\/simple.html\";\n\nvoid Checkpoint(const char* message, const base::TimeTicks& start_time) {\n LOG(INFO) << message << \" : \"\n << (base::TimeTicks::Now() - start_time).InMilliseconds()\n << \" ms\" << std::flush;\n}\n\nclass FindInPageTest : public InProcessBrowserTest {\n public:\n FindInPageTest() :\n#if defined(USE_AURA)\n location_bar_focus_view_id_(VIEW_ID_OMNIBOX)\n#else\n location_bar_focus_view_id_(VIEW_ID_LOCATION_BAR)\n#endif\n {\n set_show_window(true);\n FindBarHost::disable_animations_during_testing_ = true;\n }\n\n string16 GetFindBarText() {\n FindBarTesting* find_bar =\n browser()->GetFindBarController()->find_bar()->GetFindBarTesting();\n return find_bar->GetFindText();\n }\n\n string16 GetFindBarSelectedText() {\n FindBarTesting* find_bar =\n browser()->GetFindBarController()->find_bar()->GetFindBarTesting();\n return find_bar->GetFindSelectedText();\n }\n\n ViewID location_bar_focus_view_id_;\n\n private:\n DISALLOW_COPY_AND_ASSIGN(FindInPageTest);\n};\n\n} \/\/ namespace\n\nIN_PROC_BROWSER_TEST_F(FindInPageTest, CrashEscHandlers) {\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ First we navigate to our test page (tab A).\n GURL url = test_server()->GetURL(kSimplePage);\n ui_test_utils::NavigateToURL(browser(), url);\n\n browser()->Find();\n\n \/\/ Open another tab (tab B).\n browser()->AddSelectedTabWithURL(url, content::PAGE_TRANSITION_TYPED);\n\n browser()->Find();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n\n \/\/ Select tab A.\n browser()->ActivateTabAt(0, true);\n\n \/\/ Close tab B.\n browser()->CloseTabContents(browser()->GetWebContentsAt(1));\n\n \/\/ Click on the location bar so that Find box loses focus.\n ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(),\n VIEW_ID_LOCATION_BAR));\n \/\/ Check the location bar is focused.\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n location_bar_focus_view_id_));\n\n \/\/ This used to crash until bug 1303709 was fixed.\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_ESCAPE, false, false, false, false));\n}\n\nIN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestore) {\n ASSERT_TRUE(test_server()->Start());\n\n GURL url = test_server()->GetURL(\"title1.html\");\n ui_test_utils::NavigateToURL(browser(), url);\n\n \/\/ Focus the location bar, open and close the find-in-page, focus should\n \/\/ return to the location bar.\n browser()->FocusLocationBar();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n location_bar_focus_view_id_));\n \/\/ Ensure the creation of the find bar controller.\n browser()->GetFindBarController()->Show();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n browser()->GetFindBarController()->EndFindSession(\n FindBarController::kKeepSelection);\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n location_bar_focus_view_id_));\n\n \/\/ Focus the location bar, find something on the page, close the find box,\n \/\/ focus should go to the page.\n browser()->FocusLocationBar();\n browser()->Find();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),\n ASCIIToUTF16(\"a\"), true, false, NULL);\n browser()->GetFindBarController()->EndFindSession(\n FindBarController::kKeepSelection);\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));\n\n \/\/ Focus the location bar, open and close the find box, focus should return to\n \/\/ the location bar (same as before, just checking that http:\/\/crbug.com\/23599\n \/\/ is fixed).\n browser()->FocusLocationBar();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n location_bar_focus_view_id_));\n browser()->GetFindBarController()->Show();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n browser()->GetFindBarController()->EndFindSession(\n FindBarController::kKeepSelection);\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n location_bar_focus_view_id_));\n}\n\nIN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestoreOnTabSwitch) {\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ First we navigate to our test page (tab A).\n GURL url = test_server()->GetURL(kSimplePage);\n ui_test_utils::NavigateToURL(browser(), url);\n\n browser()->Find();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n\n FindBarTesting* find_bar =\n browser()->GetFindBarController()->find_bar()->GetFindBarTesting();\n\n \/\/ Search for 'a'.\n ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),\n ASCIIToUTF16(\"a\"), true, false, NULL);\n EXPECT_TRUE(ASCIIToUTF16(\"a\") == find_bar->GetFindSelectedText());\n\n \/\/ Open another tab (tab B).\n ui_test_utils::WindowedNotificationObserver observer(\n content::NOTIFICATION_LOAD_STOP,\n content::NotificationService::AllSources());\n browser()->AddSelectedTabWithURL(url, content::PAGE_TRANSITION_TYPED);\n observer.Wait();\n\n \/\/ Make sure Find box is open.\n browser()->Find();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n\n \/\/ Search for 'b'.\n ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),\n ASCIIToUTF16(\"b\"), true, false, NULL);\n EXPECT_TRUE(ASCIIToUTF16(\"b\") == find_bar->GetFindSelectedText());\n\n \/\/ Set focus away from the Find bar (to the Location bar).\n browser()->FocusLocationBar();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n location_bar_focus_view_id_));\n\n \/\/ Select tab A. Find bar should get focus.\n browser()->ActivateTabAt(0, true);\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n EXPECT_TRUE(ASCIIToUTF16(\"a\") == find_bar->GetFindSelectedText());\n\n \/\/ Select tab B. Location bar should get focus.\n browser()->ActivateTabAt(1, true);\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n location_bar_focus_view_id_));\n}\n\n\/\/ This tests that whenever you clear values from the Find box and close it that\n\/\/ it respects that and doesn't show you the last search, as reported in bug:\n\/\/ http:\/\/crbug.com\/40121.\nIN_PROC_BROWSER_TEST_F(FindInPageTest, PrepopulateRespectBlank) {\n#if defined(OS_MACOSX)\n \/\/ FindInPage on Mac doesn't use prepopulated values. Search there is global.\n return;\n#endif\n base::TimeTicks start_time = base::TimeTicks::Now();\n Checkpoint(\"Test starting\", start_time);\n\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ Make sure Chrome is in the foreground, otherwise sending input\n \/\/ won't do anything and the test will hang.\n ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));\n\n Checkpoint(\"Navigate\", start_time);\n\n \/\/ First we navigate to any page.\n GURL url = test_server()->GetURL(kSimplePage);\n ui_test_utils::NavigateToURL(browser(), url);\n\n Checkpoint(\"Show Find bar\", start_time);\n\n \/\/ Show the Find bar.\n browser()->GetFindBarController()->Show();\n\n Checkpoint(\"Search for 'a'\", start_time);\n\n \/\/ Search for \"a\".\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_A, false, false, false, false));\n\n \/\/ We should find \"a\" here.\n EXPECT_EQ(ASCIIToUTF16(\"a\"), GetFindBarText());\n\n Checkpoint(\"Delete 'a'\", start_time);\n\n \/\/ Delete \"a\".\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_BACK, false, false, false, false));\n\n \/\/ Validate we have cleared the text.\n EXPECT_EQ(string16(), GetFindBarText());\n\n Checkpoint(\"Close find bar\", start_time);\n\n \/\/ Close the Find box.\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_ESCAPE, false, false, false, false));\n\n Checkpoint(\"Show Find bar\", start_time);\n\n \/\/ Show the Find bar.\n browser()->GetFindBarController()->Show();\n\n Checkpoint(\"Validate text\", start_time);\n\n \/\/ After the Find box has been reopened, it should not have been prepopulated\n \/\/ with \"a\" again.\n EXPECT_EQ(string16(), GetFindBarText());\n\n Checkpoint(\"Close Find bar\", start_time);\n\n \/\/ Close the Find box.\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_ESCAPE, false, false, false, false));\n\n Checkpoint(\"FindNext\", start_time);\n\n \/\/ Press F3 to trigger FindNext.\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_F3, false, false, false, false));\n\n Checkpoint(\"Validate\", start_time);\n\n \/\/ After the Find box has been reopened, it should still have no prepopulate\n \/\/ value.\n EXPECT_EQ(string16(), GetFindBarText());\n\n Checkpoint(\"Test done\", start_time);\n}\n\n\/\/ Flaky on Win. http:\/\/crbug.com\/92467\n\/\/ Flaky on ChromeOS. http:\/\/crbug.com\/118216\n#if defined(OS_WIN) || defined(OS_CHROMEOS)\n#define MAYBE_PasteWithoutTextChange DISABLED_PasteWithoutTextChange\n#else\n#define MAYBE_PasteWithoutTextChange PasteWithoutTextChange\n#endif\n\nIN_PROC_BROWSER_TEST_F(FindInPageTest, MAYBE_PasteWithoutTextChange) {\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ Make sure Chrome is in the foreground, otherwise sending input\n \/\/ won't do anything and the test will hang.\n ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));\n\n \/\/ First we navigate to any page.\n GURL url = test_server()->GetURL(kSimplePage);\n ui_test_utils::NavigateToURL(browser(), url);\n\n \/\/ Show the Find bar.\n browser()->GetFindBarController()->Show();\n\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n\n \/\/ Search for \"a\".\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_A, false, false, false, false));\n\n \/\/ We should find \"a\" here.\n EXPECT_EQ(ASCIIToUTF16(\"a\"), GetFindBarText());\n\n \/\/ Reload the page to clear the matching result.\n browser()->Reload(CURRENT_TAB);\n\n \/\/ Focus the Find bar again to make sure the text is selected.\n browser()->GetFindBarController()->Show();\n\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n\n \/\/ \"a\" should be selected.\n EXPECT_EQ(ASCIIToUTF16(\"a\"), GetFindBarSelectedText());\n\n \/\/ Press Ctrl-C to copy the content.\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_C, true, false, false, false));\n\n string16 str;\n views::ViewsDelegate::views_delegate->GetClipboard()->\n ReadText(ui::Clipboard::BUFFER_STANDARD, &str);\n\n \/\/ Make sure the text is copied successfully.\n EXPECT_EQ(ASCIIToUTF16(\"a\"), str);\n\n \/\/ Press Ctrl-V to paste the content back, it should start finding even if the\n \/\/ content is not changed.\n content::Source notification_source(\n browser()->GetSelectedWebContents());\n ui_test_utils::WindowedNotificationObserverWithDetails\n observer(\n chrome::NOTIFICATION_FIND_RESULT_AVAILABLE, notification_source);\n\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_V, true, false, false, false));\n\n ASSERT_NO_FATAL_FAILURE(observer.Wait());\n FindNotificationDetails details;\n ASSERT_TRUE(observer.GetDetailsFor(notification_source.map_key(), &details));\n EXPECT_TRUE(details.number_of_matches() > 0);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/webui\/options\/language_options_handler.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"base\/basictypes.h\"\n#include \"base\/command_line.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/metrics\/user_metrics.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\nLanguageOptionsHandler::LanguageOptionsHandler() {\n}\n\nLanguageOptionsHandler::~LanguageOptionsHandler() {\n}\n\nvoid LanguageOptionsHandler::GetLocalizedValues(\n DictionaryValue* localized_strings) {\n LanguageOptionsHandlerCommon::GetLocalizedValues(localized_strings);\n\n localized_strings->SetString(\"restart_button\",\n l10n_util::GetStringUTF16(\n IDS_OPTIONS_SETTINGS_LANGUAGES_RELAUNCH_BUTTON));\n localized_strings->Set(\"languageList\", GetLanguageList());\n}\n\nvoid LanguageOptionsHandler::RegisterMessages() {\n LanguageOptionsHandlerCommon::RegisterMessages();\n\n web_ui_->RegisterMessageCallback(\"uiLanguageRestart\",\n NewCallback(this, &LanguageOptionsHandler::RestartCallback));\n}\n\nListValue* LanguageOptionsHandler::GetLanguageList() {\n \/\/ Collect the language codes from the supported accept-languages.\n const std::string app_locale = g_browser_process->GetApplicationLocale();\n std::vector language_codes;\n l10n_util::GetAcceptLanguagesForLocale(app_locale, &language_codes);\n\n \/\/ Map of display name -> {language code, native_display_name}.\n \/\/ In theory, we should be able to create a map that is sorted by\n \/\/ display names using ICU comparator, but doing it is hard, thus we'll\n \/\/ use an auxiliary vector to achieve the same result.\n typedef std::pair LanguagePair;\n typedef std::map LanguageMap;\n LanguageMap language_map;\n \/\/ The auxiliary vector mentioned above.\n std::vector display_names;\n\n \/\/ Build the list of display names, and build the language map.\n for (size_t i = 0; i < language_codes.size(); ++i) {\n const string16 display_name =\n l10n_util::GetDisplayNameForLocale(language_codes[i], app_locale, true);\n const string16 native_display_name =\n l10n_util::GetDisplayNameForLocale(language_codes[i], language_codes[i],\n true);\n display_names.push_back(display_name);\n language_map[display_name] =\n std::make_pair(language_codes[i], native_display_name);\n }\n DCHECK_EQ(display_names.size(), language_map.size());\n\n \/\/ Sort display names using locale specific sorter.\n l10n_util::SortStrings16(app_locale, &display_names);\n\n \/\/ Build the language list from the language map.\n ListValue* language_list = new ListValue();\n for (size_t i = 0; i < display_names.size(); ++i) {\n const LanguagePair& pair = language_map[display_names[i]];\n DictionaryValue* dictionary = new DictionaryValue();\n dictionary->SetString(\"code\", pair.first);\n dictionary->SetString(\"displayName\", display_names[i]);\n dictionary->SetString(\"nativeDisplayName\", pair.second);\n language_list->Append(dictionary);\n }\n\n return language_list;\n}\n\nstring16 LanguageOptionsHandler::GetProductName() {\n return l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);\n}\n\nvoid LanguageOptionsHandler::SetApplicationLocale(\n const std::string& language_code) {\n PrefService* pref_service = g_browser_process->local_state();\n pref_service->SetString(prefs::kApplicationLocale, language_code);\n}\n\nvoid LanguageOptionsHandler::RestartCallback(const ListValue* args) {\n UserMetrics::RecordAction(UserMetricsAction(\"LanguageOptions_Restart\"));\n\n \/\/ Set the flag to restore state after the restart.\n PrefService* pref_service = g_browser_process->local_state();\n pref_service->SetBoolean(prefs::kRestartLastSessionOnShutdown, true);\n BrowserList::CloseAllBrowsersAndExit();\n}\nweb-ui settings: Fix display of languages for RTL systems.\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/webui\/options\/language_options_handler.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"base\/basictypes.h\"\n#include \"base\/command_line.h\"\n#include \"base\/i18n\/rtl.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/metrics\/user_metrics.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\nLanguageOptionsHandler::LanguageOptionsHandler() {\n}\n\nLanguageOptionsHandler::~LanguageOptionsHandler() {\n}\n\nvoid LanguageOptionsHandler::GetLocalizedValues(\n DictionaryValue* localized_strings) {\n LanguageOptionsHandlerCommon::GetLocalizedValues(localized_strings);\n\n localized_strings->SetString(\"restart_button\",\n l10n_util::GetStringUTF16(\n IDS_OPTIONS_SETTINGS_LANGUAGES_RELAUNCH_BUTTON));\n localized_strings->Set(\"languageList\", GetLanguageList());\n}\n\nvoid LanguageOptionsHandler::RegisterMessages() {\n LanguageOptionsHandlerCommon::RegisterMessages();\n\n web_ui_->RegisterMessageCallback(\"uiLanguageRestart\",\n NewCallback(this, &LanguageOptionsHandler::RestartCallback));\n}\n\nListValue* LanguageOptionsHandler::GetLanguageList() {\n \/\/ Collect the language codes from the supported accept-languages.\n const std::string app_locale = g_browser_process->GetApplicationLocale();\n std::vector language_codes;\n l10n_util::GetAcceptLanguagesForLocale(app_locale, &language_codes);\n\n \/\/ Map of display name -> {language code, native_display_name}.\n \/\/ In theory, we should be able to create a map that is sorted by\n \/\/ display names using ICU comparator, but doing it is hard, thus we'll\n \/\/ use an auxiliary vector to achieve the same result.\n typedef std::pair LanguagePair;\n typedef std::map LanguageMap;\n LanguageMap language_map;\n \/\/ The auxiliary vector mentioned above.\n std::vector display_names;\n\n \/\/ Build the list of display names, and build the language map.\n for (size_t i = 0; i < language_codes.size(); ++i) {\n string16 display_name =\n l10n_util::GetDisplayNameForLocale(language_codes[i], app_locale,\n false);\n base::i18n::AdjustStringForLocaleDirection(&display_name);\n string16 native_display_name =\n l10n_util::GetDisplayNameForLocale(language_codes[i], language_codes[i],\n false);\n base::i18n::AdjustStringForLocaleDirection(&native_display_name);\n display_names.push_back(display_name);\n language_map[display_name] =\n std::make_pair(language_codes[i], native_display_name);\n }\n DCHECK_EQ(display_names.size(), language_map.size());\n\n \/\/ Sort display names using locale specific sorter.\n l10n_util::SortStrings16(app_locale, &display_names);\n\n \/\/ Build the language list from the language map.\n ListValue* language_list = new ListValue();\n for (size_t i = 0; i < display_names.size(); ++i) {\n const LanguagePair& pair = language_map[display_names[i]];\n DictionaryValue* dictionary = new DictionaryValue();\n dictionary->SetString(\"code\", pair.first);\n dictionary->SetString(\"displayName\", display_names[i]);\n dictionary->SetString(\"nativeDisplayName\", pair.second);\n language_list->Append(dictionary);\n }\n\n return language_list;\n}\n\nstring16 LanguageOptionsHandler::GetProductName() {\n return l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);\n}\n\nvoid LanguageOptionsHandler::SetApplicationLocale(\n const std::string& language_code) {\n PrefService* pref_service = g_browser_process->local_state();\n pref_service->SetString(prefs::kApplicationLocale, language_code);\n}\n\nvoid LanguageOptionsHandler::RestartCallback(const ListValue* args) {\n UserMetrics::RecordAction(UserMetricsAction(\"LanguageOptions_Restart\"));\n\n \/\/ Set the flag to restore state after the restart.\n PrefService* pref_service = g_browser_process->local_state();\n pref_service->SetBoolean(prefs::kRestartLastSessionOnShutdown, true);\n BrowserList::CloseAllBrowsersAndExit();\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/api\/sessions\/sessions_api.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/path_service.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"chrome\/browser\/extensions\/api\/tabs\/tabs_api.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_function_test_utils.h\"\n#include \"chrome\/browser\/profiles\/profile_manager.h\"\n#include \"chrome\/browser\/sync\/glue\/session_model_associator.h\"\n#include \"chrome\/browser\/sync\/profile_sync_service.h\"\n#include \"chrome\/browser\/sync\/profile_sync_service_factory.h\"\n#include \"chrome\/browser\/sync\/profile_sync_service_mock.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/test_switches.h\"\n#include \"chrome\/test\/base\/testing_browser_process.h\"\n\nnamespace utils = extension_function_test_utils;\n\nnamespace extensions {\n\nnamespace {\n\n\/\/ If more sessions are added to session tags, num sessions should be updated.\nconst char* kSessionTags[] = {\"tag0\", \"tag1\", \"tag2\", \"tag3\", \"tag4\"};\nconst size_t kNumSessions = 5;\n\nvoid BuildSessionSpecifics(const std::string& tag,\n sync_pb::SessionSpecifics* meta) {\n meta->set_session_tag(tag);\n sync_pb::SessionHeader* header = meta->mutable_header();\n header->set_device_type(sync_pb::SyncEnums_DeviceType_TYPE_LINUX);\n header->set_client_name(tag);\n}\n\nvoid BuildWindowSpecifics(int window_id,\n const std::vector& tab_list,\n sync_pb::SessionSpecifics* meta) {\n sync_pb::SessionHeader* header = meta->mutable_header();\n sync_pb::SessionWindow* window = header->add_window();\n window->set_window_id(window_id);\n window->set_selected_tab_index(0);\n window->set_browser_type(sync_pb::SessionWindow_BrowserType_TYPE_TABBED);\n for (std::vector::const_iterator iter = tab_list.begin();\n iter != tab_list.end(); ++iter) {\n window->add_tab(*iter);\n }\n}\n\nvoid BuildTabSpecifics(const std::string& tag, int window_id, int tab_id,\n sync_pb::SessionSpecifics* tab_base) {\n tab_base->set_session_tag(tag);\n tab_base->set_tab_node_id(0);\n sync_pb::SessionTab* tab = tab_base->mutable_tab();\n tab->set_tab_id(tab_id);\n tab->set_tab_visual_index(1);\n tab->set_current_navigation_index(0);\n tab->set_pinned(true);\n tab->set_extension_app_id(\"app_id\");\n sync_pb::TabNavigation* navigation = tab->add_navigation();\n navigation->set_virtual_url(\"http:\/\/foo\/1\");\n navigation->set_referrer(\"referrer\");\n navigation->set_title(\"title\");\n navigation->set_page_transition(sync_pb::SyncEnums_PageTransition_TYPED);\n}\n\n} \/\/ namespace\n\nclass ExtensionSessionsTest : public InProcessBrowserTest {\n public:\n virtual void SetUpOnMainThread() OVERRIDE;\n protected:\n void CreateTestProfileSyncService();\n void CreateTestExtension();\n void CreateSessionModels();\n\n template \n scoped_refptr CreateFunction(bool has_callback) {\n scoped_refptr fn(new T());\n fn->set_extension(extension_.get());\n fn->set_has_callback(has_callback);\n return fn;\n };\n\n Browser* browser_;\n browser_sync::SessionModelAssociator* associator_;\n scoped_refptr extension_;\n};\n\nvoid ExtensionSessionsTest::SetUpOnMainThread() {\n CreateTestProfileSyncService();\n CreateTestExtension();\n}\n\nvoid ExtensionSessionsTest::CreateTestProfileSyncService() {\n ProfileManager* profile_manager = g_browser_process->profile_manager();\n base::FilePath path;\n PathService::Get(chrome::DIR_USER_DATA, &path);\n path = path.AppendASCII(\"test_profile\");\n if (!base::PathExists(path))\n CHECK(file_util::CreateDirectory(path));\n Profile* profile =\n Profile::CreateProfile(path, NULL, Profile::CREATE_MODE_SYNCHRONOUS);\n profile_manager->RegisterTestingProfile(profile, true, false);\n browser_ = new Browser(Browser::CreateParams(\n profile, chrome::HOST_DESKTOP_TYPE_NATIVE));\n ProfileSyncServiceMock* service = static_cast(\n ProfileSyncServiceFactory::GetInstance()->SetTestingFactoryAndUse(\n profile, &ProfileSyncServiceMock::BuildMockProfileSyncService));\n\n associator_ = new browser_sync::SessionModelAssociator(\n static_cast(service), true);\n syncer::ModelTypeSet preferred_types;\n preferred_types.Put(syncer::SESSIONS);\n GoogleServiceAuthError no_error(GoogleServiceAuthError::NONE);\n\n ON_CALL(*service, GetSessionModelAssociator()).WillByDefault(\n testing::Return(associator_));\n ON_CALL(*service, GetPreferredDataTypes()).WillByDefault(\n testing::Return(preferred_types));\n EXPECT_CALL(*service, GetAuthError()).WillRepeatedly(\n testing::ReturnRef(no_error));\n ON_CALL(*service, GetActiveDataTypes()).WillByDefault(\n testing::Return(preferred_types));\n EXPECT_CALL(*service, AddObserver(testing::_)).Times(testing::AnyNumber());\n EXPECT_CALL(*service, RemoveObserver(testing::_)).Times(testing::AnyNumber());\n\n service->Initialize();\n}\n\nvoid ExtensionSessionsTest::CreateTestExtension() {\n scoped_ptr test_extension_value(\n utils::ParseDictionary(\n \"{\\\"name\\\": \\\"Test\\\", \\\"version\\\": \\\"1.0\\\", \"\n \"\\\"permissions\\\": [\\\"sessions\\\", \\\"tabs\\\"]}\"));\n extension_ = utils::CreateExtension(test_extension_value.get());\n}\n\nvoid ExtensionSessionsTest::CreateSessionModels() {\n for (size_t index = 0; index < kNumSessions; ++index) {\n \/\/ Fill an instance of session specifics with a foreign session's data.\n sync_pb::SessionSpecifics meta;\n BuildSessionSpecifics(kSessionTags[index], &meta);\n SessionID::id_type tab_nums1[] = {5, 10, 13, 17};\n std::vector tab_list1(\n tab_nums1, tab_nums1 + arraysize(tab_nums1));\n BuildWindowSpecifics(index, tab_list1, &meta);\n std::vector tabs1;\n tabs1.resize(tab_list1.size());\n for (size_t i = 0; i < tab_list1.size(); ++i) {\n BuildTabSpecifics(kSessionTags[index], 0, tab_list1[i], &tabs1[i]);\n }\n\n associator_->SetCurrentMachineTagForTesting(kSessionTags[index]);\n \/\/ Update associator with the session's meta node containing one window.\n associator_->AssociateForeignSpecifics(meta, base::Time());\n \/\/ Add tabs for the window.\n for (std::vector::iterator iter = tabs1.begin();\n iter != tabs1.end(); ++iter) {\n associator_->AssociateForeignSpecifics(*iter, base::Time());\n }\n }\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, GetDevices) {\n CreateSessionModels();\n\n scoped_ptr result(utils::ToList(\n utils::RunFunctionAndReturnSingleResult(\n CreateFunction(true).get(),\n \"[{\\\"maxResults\\\": 0}]\",\n browser_)));\n ASSERT_TRUE(result);\n ListValue* devices = result.get();\n EXPECT_EQ(5u, devices->GetSize());\n DictionaryValue* device = NULL;\n ListValue* sessions = NULL;\n for (size_t i = 0; i < devices->GetSize(); ++i) {\n EXPECT_TRUE(devices->GetDictionary(i, &device));\n EXPECT_EQ(kSessionTags[i], utils::GetString(device, \"info\"));\n EXPECT_TRUE(device->GetList(\"sessions\", &sessions));\n EXPECT_EQ(0u, sessions->GetSize());\n }\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, GetDevicesMaxResults) {\n CreateSessionModels();\n\n scoped_ptr result(utils::ToList(\n utils::RunFunctionAndReturnSingleResult(\n CreateFunction(true).get(),\n \"[]\",\n browser_)));\n ASSERT_TRUE(result);\n ListValue* devices = result.get();\n EXPECT_EQ(5u, devices->GetSize());\n DictionaryValue* device = NULL;\n ListValue* sessions = NULL;\n for (size_t i = 0; i < devices->GetSize(); ++i) {\n EXPECT_TRUE(devices->GetDictionary(i, &device));\n EXPECT_EQ(kSessionTags[i], utils::GetString(device, \"info\"));\n EXPECT_TRUE(device->GetList(\"sessions\", &sessions));\n EXPECT_EQ(1u, sessions->GetSize());\n }\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, GetDevicesListEmpty) {\n scoped_ptr result(utils::ToList(\n utils::RunFunctionAndReturnSingleResult(\n CreateFunction(true).get(),\n \"[]\",\n browser_)));\n\n ASSERT_TRUE(result);\n ListValue* devices = result.get();\n EXPECT_EQ(0u, devices->GetSize());\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, RestoreForeignSessionWindow) {\n CreateSessionModels();\n\n scoped_ptr restored_window_session(utils::ToDictionary(\n utils::RunFunctionAndReturnSingleResult(\n CreateFunction(true).get(),\n \"[\\\"tag3.3\\\"]\",\n browser_,\n utils::INCLUDE_INCOGNITO)));\n ASSERT_TRUE(restored_window_session);\n\n scoped_ptr result(utils::ToList(\n utils::RunFunctionAndReturnSingleResult(\n CreateFunction(true).get(),\n \"[]\",\n browser_)));\n ASSERT_TRUE(result);\n\n ListValue* windows = result.get();\n EXPECT_EQ(2u, windows->GetSize());\n DictionaryValue* restored_window = NULL;\n EXPECT_TRUE(restored_window_session->GetDictionary(\"window\",\n &restored_window));\n DictionaryValue* window = NULL;\n int restored_id = utils::GetInteger(restored_window, \"id\");\n for (size_t i = 0; i < windows->GetSize(); ++i) {\n EXPECT_TRUE(windows->GetDictionary(i, &window));\n if (utils::GetInteger(window, \"id\") == restored_id)\n break;\n }\n EXPECT_EQ(restored_id, utils::GetInteger(window, \"id\"));\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, RestoreForeignSessionInvalidId) {\n CreateSessionModels();\n\n EXPECT_TRUE(MatchPattern(utils::RunFunctionAndReturnError(\n CreateFunction(true).get(),\n \"[\\\"tag3.0\\\"]\",\n browser_), \"Invalid session id: \\\"tag3.0\\\".\"));\n}\n\n\/\/ Flaky on ChromeOS, times out on OSX Debug http:\/\/crbug.com\/251199\n#if defined(OS_CHROMEOS) || (defined(OS_MACOSX) && !defined(NDEBUG))\n#define MAYBE_SessionsApis DISABLED_SessionsApis\n#else\n#define MAYBE_SessionsApis SessionsApis\n#endif\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_SessionsApis) {\n#if defined(OS_WIN) && defined(USE_ASH)\n \/\/ Disable this test in Metro+Ash for now (http:\/\/crbug.com\/262796).\n if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))\n return;\n#endif\n\n ASSERT_TRUE(RunExtensionSubtest(\"sessions\",\n \"sessions.html\")) << message_;\n}\n\n} \/\/ namespace extensions\nDisable flaky ExtensionSessionsTest.RestoreForeignSessionWindow.\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/api\/sessions\/sessions_api.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/path_service.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"chrome\/browser\/extensions\/api\/tabs\/tabs_api.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_function_test_utils.h\"\n#include \"chrome\/browser\/profiles\/profile_manager.h\"\n#include \"chrome\/browser\/sync\/glue\/session_model_associator.h\"\n#include \"chrome\/browser\/sync\/profile_sync_service.h\"\n#include \"chrome\/browser\/sync\/profile_sync_service_factory.h\"\n#include \"chrome\/browser\/sync\/profile_sync_service_mock.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/test_switches.h\"\n#include \"chrome\/test\/base\/testing_browser_process.h\"\n\nnamespace utils = extension_function_test_utils;\n\nnamespace extensions {\n\nnamespace {\n\n\/\/ If more sessions are added to session tags, num sessions should be updated.\nconst char* kSessionTags[] = {\"tag0\", \"tag1\", \"tag2\", \"tag3\", \"tag4\"};\nconst size_t kNumSessions = 5;\n\nvoid BuildSessionSpecifics(const std::string& tag,\n sync_pb::SessionSpecifics* meta) {\n meta->set_session_tag(tag);\n sync_pb::SessionHeader* header = meta->mutable_header();\n header->set_device_type(sync_pb::SyncEnums_DeviceType_TYPE_LINUX);\n header->set_client_name(tag);\n}\n\nvoid BuildWindowSpecifics(int window_id,\n const std::vector& tab_list,\n sync_pb::SessionSpecifics* meta) {\n sync_pb::SessionHeader* header = meta->mutable_header();\n sync_pb::SessionWindow* window = header->add_window();\n window->set_window_id(window_id);\n window->set_selected_tab_index(0);\n window->set_browser_type(sync_pb::SessionWindow_BrowserType_TYPE_TABBED);\n for (std::vector::const_iterator iter = tab_list.begin();\n iter != tab_list.end(); ++iter) {\n window->add_tab(*iter);\n }\n}\n\nvoid BuildTabSpecifics(const std::string& tag, int window_id, int tab_id,\n sync_pb::SessionSpecifics* tab_base) {\n tab_base->set_session_tag(tag);\n tab_base->set_tab_node_id(0);\n sync_pb::SessionTab* tab = tab_base->mutable_tab();\n tab->set_tab_id(tab_id);\n tab->set_tab_visual_index(1);\n tab->set_current_navigation_index(0);\n tab->set_pinned(true);\n tab->set_extension_app_id(\"app_id\");\n sync_pb::TabNavigation* navigation = tab->add_navigation();\n navigation->set_virtual_url(\"http:\/\/foo\/1\");\n navigation->set_referrer(\"referrer\");\n navigation->set_title(\"title\");\n navigation->set_page_transition(sync_pb::SyncEnums_PageTransition_TYPED);\n}\n\n} \/\/ namespace\n\nclass ExtensionSessionsTest : public InProcessBrowserTest {\n public:\n virtual void SetUpOnMainThread() OVERRIDE;\n protected:\n void CreateTestProfileSyncService();\n void CreateTestExtension();\n void CreateSessionModels();\n\n template \n scoped_refptr CreateFunction(bool has_callback) {\n scoped_refptr fn(new T());\n fn->set_extension(extension_.get());\n fn->set_has_callback(has_callback);\n return fn;\n };\n\n Browser* browser_;\n browser_sync::SessionModelAssociator* associator_;\n scoped_refptr extension_;\n};\n\nvoid ExtensionSessionsTest::SetUpOnMainThread() {\n CreateTestProfileSyncService();\n CreateTestExtension();\n}\n\nvoid ExtensionSessionsTest::CreateTestProfileSyncService() {\n ProfileManager* profile_manager = g_browser_process->profile_manager();\n base::FilePath path;\n PathService::Get(chrome::DIR_USER_DATA, &path);\n path = path.AppendASCII(\"test_profile\");\n if (!base::PathExists(path))\n CHECK(file_util::CreateDirectory(path));\n Profile* profile =\n Profile::CreateProfile(path, NULL, Profile::CREATE_MODE_SYNCHRONOUS);\n profile_manager->RegisterTestingProfile(profile, true, false);\n browser_ = new Browser(Browser::CreateParams(\n profile, chrome::HOST_DESKTOP_TYPE_NATIVE));\n ProfileSyncServiceMock* service = static_cast(\n ProfileSyncServiceFactory::GetInstance()->SetTestingFactoryAndUse(\n profile, &ProfileSyncServiceMock::BuildMockProfileSyncService));\n\n associator_ = new browser_sync::SessionModelAssociator(\n static_cast(service), true);\n syncer::ModelTypeSet preferred_types;\n preferred_types.Put(syncer::SESSIONS);\n GoogleServiceAuthError no_error(GoogleServiceAuthError::NONE);\n\n ON_CALL(*service, GetSessionModelAssociator()).WillByDefault(\n testing::Return(associator_));\n ON_CALL(*service, GetPreferredDataTypes()).WillByDefault(\n testing::Return(preferred_types));\n EXPECT_CALL(*service, GetAuthError()).WillRepeatedly(\n testing::ReturnRef(no_error));\n ON_CALL(*service, GetActiveDataTypes()).WillByDefault(\n testing::Return(preferred_types));\n EXPECT_CALL(*service, AddObserver(testing::_)).Times(testing::AnyNumber());\n EXPECT_CALL(*service, RemoveObserver(testing::_)).Times(testing::AnyNumber());\n\n service->Initialize();\n}\n\nvoid ExtensionSessionsTest::CreateTestExtension() {\n scoped_ptr test_extension_value(\n utils::ParseDictionary(\n \"{\\\"name\\\": \\\"Test\\\", \\\"version\\\": \\\"1.0\\\", \"\n \"\\\"permissions\\\": [\\\"sessions\\\", \\\"tabs\\\"]}\"));\n extension_ = utils::CreateExtension(test_extension_value.get());\n}\n\nvoid ExtensionSessionsTest::CreateSessionModels() {\n for (size_t index = 0; index < kNumSessions; ++index) {\n \/\/ Fill an instance of session specifics with a foreign session's data.\n sync_pb::SessionSpecifics meta;\n BuildSessionSpecifics(kSessionTags[index], &meta);\n SessionID::id_type tab_nums1[] = {5, 10, 13, 17};\n std::vector tab_list1(\n tab_nums1, tab_nums1 + arraysize(tab_nums1));\n BuildWindowSpecifics(index, tab_list1, &meta);\n std::vector tabs1;\n tabs1.resize(tab_list1.size());\n for (size_t i = 0; i < tab_list1.size(); ++i) {\n BuildTabSpecifics(kSessionTags[index], 0, tab_list1[i], &tabs1[i]);\n }\n\n associator_->SetCurrentMachineTagForTesting(kSessionTags[index]);\n \/\/ Update associator with the session's meta node containing one window.\n associator_->AssociateForeignSpecifics(meta, base::Time());\n \/\/ Add tabs for the window.\n for (std::vector::iterator iter = tabs1.begin();\n iter != tabs1.end(); ++iter) {\n associator_->AssociateForeignSpecifics(*iter, base::Time());\n }\n }\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, GetDevices) {\n CreateSessionModels();\n\n scoped_ptr result(utils::ToList(\n utils::RunFunctionAndReturnSingleResult(\n CreateFunction(true).get(),\n \"[{\\\"maxResults\\\": 0}]\",\n browser_)));\n ASSERT_TRUE(result);\n ListValue* devices = result.get();\n EXPECT_EQ(5u, devices->GetSize());\n DictionaryValue* device = NULL;\n ListValue* sessions = NULL;\n for (size_t i = 0; i < devices->GetSize(); ++i) {\n EXPECT_TRUE(devices->GetDictionary(i, &device));\n EXPECT_EQ(kSessionTags[i], utils::GetString(device, \"info\"));\n EXPECT_TRUE(device->GetList(\"sessions\", &sessions));\n EXPECT_EQ(0u, sessions->GetSize());\n }\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, GetDevicesMaxResults) {\n CreateSessionModels();\n\n scoped_ptr result(utils::ToList(\n utils::RunFunctionAndReturnSingleResult(\n CreateFunction(true).get(),\n \"[]\",\n browser_)));\n ASSERT_TRUE(result);\n ListValue* devices = result.get();\n EXPECT_EQ(5u, devices->GetSize());\n DictionaryValue* device = NULL;\n ListValue* sessions = NULL;\n for (size_t i = 0; i < devices->GetSize(); ++i) {\n EXPECT_TRUE(devices->GetDictionary(i, &device));\n EXPECT_EQ(kSessionTags[i], utils::GetString(device, \"info\"));\n EXPECT_TRUE(device->GetList(\"sessions\", &sessions));\n EXPECT_EQ(1u, sessions->GetSize());\n }\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, GetDevicesListEmpty) {\n scoped_ptr result(utils::ToList(\n utils::RunFunctionAndReturnSingleResult(\n CreateFunction(true).get(),\n \"[]\",\n browser_)));\n\n ASSERT_TRUE(result);\n ListValue* devices = result.get();\n EXPECT_EQ(0u, devices->GetSize());\n}\n\n\/\/ Flaky timeout: http:\/\/crbug.com\/278372\nIN_PROC_BROWSER_TEST_F(ExtensionSessionsTest,\n DISABLED_RestoreForeignSessionWindow) {\n CreateSessionModels();\n\n scoped_ptr restored_window_session(utils::ToDictionary(\n utils::RunFunctionAndReturnSingleResult(\n CreateFunction(true).get(),\n \"[\\\"tag3.3\\\"]\",\n browser_,\n utils::INCLUDE_INCOGNITO)));\n ASSERT_TRUE(restored_window_session);\n\n scoped_ptr result(utils::ToList(\n utils::RunFunctionAndReturnSingleResult(\n CreateFunction(true).get(),\n \"[]\",\n browser_)));\n ASSERT_TRUE(result);\n\n ListValue* windows = result.get();\n EXPECT_EQ(2u, windows->GetSize());\n DictionaryValue* restored_window = NULL;\n EXPECT_TRUE(restored_window_session->GetDictionary(\"window\",\n &restored_window));\n DictionaryValue* window = NULL;\n int restored_id = utils::GetInteger(restored_window, \"id\");\n for (size_t i = 0; i < windows->GetSize(); ++i) {\n EXPECT_TRUE(windows->GetDictionary(i, &window));\n if (utils::GetInteger(window, \"id\") == restored_id)\n break;\n }\n EXPECT_EQ(restored_id, utils::GetInteger(window, \"id\"));\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, RestoreForeignSessionInvalidId) {\n CreateSessionModels();\n\n EXPECT_TRUE(MatchPattern(utils::RunFunctionAndReturnError(\n CreateFunction(true).get(),\n \"[\\\"tag3.0\\\"]\",\n browser_), \"Invalid session id: \\\"tag3.0\\\".\"));\n}\n\n\/\/ Flaky on ChromeOS, times out on OSX Debug http:\/\/crbug.com\/251199\n#if defined(OS_CHROMEOS) || (defined(OS_MACOSX) && !defined(NDEBUG))\n#define MAYBE_SessionsApis DISABLED_SessionsApis\n#else\n#define MAYBE_SessionsApis SessionsApis\n#endif\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_SessionsApis) {\n#if defined(OS_WIN) && defined(USE_ASH)\n \/\/ Disable this test in Metro+Ash for now (http:\/\/crbug.com\/262796).\n if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))\n return;\n#endif\n\n ASSERT_TRUE(RunExtensionSubtest(\"sessions\",\n \"sessions.html\")) << message_;\n}\n\n} \/\/ namespace extensions\n<|endoftext|>"} {"text":"\/*\n * Copyright 2016 The Cartographer Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"cartographer\/mapping_3d\/pose_graph\/constraint_builder.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"Eigen\/Eigenvalues\"\n#include \"cartographer\/common\/make_unique.h\"\n#include \"cartographer\/common\/math.h\"\n#include \"cartographer\/common\/thread_pool.h\"\n#include \"cartographer\/mapping_3d\/scan_matching\/proto\/ceres_scan_matcher_options.pb.h\"\n#include \"cartographer\/mapping_3d\/scan_matching\/proto\/fast_correlative_scan_matcher_options.pb.h\"\n#include \"cartographer\/transform\/transform.h\"\n#include \"glog\/logging.h\"\n\nnamespace cartographer {\nnamespace mapping_3d {\nnamespace pose_graph {\n\nConstraintBuilder::ConstraintBuilder(\n const mapping::pose_graph::proto::ConstraintBuilderOptions& options,\n common::ThreadPool* const thread_pool)\n : options_(options),\n thread_pool_(thread_pool),\n sampler_(options.sampling_ratio()),\n ceres_scan_matcher_(options.ceres_scan_matcher_options_3d()) {}\n\nConstraintBuilder::~ConstraintBuilder() {\n common::MutexLocker locker(&mutex_);\n CHECK_EQ(constraints_.size(), 0) << \"WhenDone() was not called\";\n CHECK_EQ(pending_computations_.size(), 0);\n CHECK_EQ(submap_queued_work_items_.size(), 0);\n CHECK(when_done_ == nullptr);\n}\n\nvoid ConstraintBuilder::MaybeAddConstraint(\n const mapping::SubmapId& submap_id, const Submap* const submap,\n const mapping::NodeId& node_id,\n const mapping::TrajectoryNode::Data* const constant_data,\n const std::vector& submap_nodes,\n const transform::Rigid3d& global_node_pose,\n const transform::Rigid3d& global_submap_pose) {\n if ((global_node_pose.translation() - global_submap_pose.translation())\n .norm() > options_.max_constraint_distance()) {\n return;\n }\n if (sampler_.Pulse()) {\n common::MutexLocker locker(&mutex_);\n constraints_.emplace_back();\n auto* const constraint = &constraints_.back();\n ++pending_computations_[current_computation_];\n const int current_computation = current_computation_;\n ScheduleSubmapScanMatcherConstructionAndQueueWorkItem(\n submap_id, submap_nodes, submap, [=]() EXCLUDES(mutex_) {\n ComputeConstraint(submap_id, node_id, false, \/* match_full_submap *\/\n constant_data, global_node_pose, global_submap_pose,\n constraint);\n FinishComputation(current_computation);\n });\n }\n}\n\nvoid ConstraintBuilder::MaybeAddGlobalConstraint(\n const mapping::SubmapId& submap_id, const Submap* const submap,\n const mapping::NodeId& node_id,\n const mapping::TrajectoryNode::Data* const constant_data,\n const std::vector& submap_nodes,\n const Eigen::Quaterniond& global_node_rotation,\n const Eigen::Quaterniond& global_submap_rotation) {\n common::MutexLocker locker(&mutex_);\n constraints_.emplace_back();\n auto* const constraint = &constraints_.back();\n ++pending_computations_[current_computation_];\n const int current_computation = current_computation_;\n ScheduleSubmapScanMatcherConstructionAndQueueWorkItem(\n submap_id, submap_nodes, submap, [=]() EXCLUDES(mutex_) {\n ComputeConstraint(\n submap_id, node_id, true, \/* match_full_submap *\/\n constant_data, transform::Rigid3d::Rotation(global_node_rotation),\n transform::Rigid3d::Rotation(global_submap_rotation), constraint);\n FinishComputation(current_computation);\n });\n}\n\nvoid ConstraintBuilder::NotifyEndOfNode() {\n common::MutexLocker locker(&mutex_);\n ++current_computation_;\n}\n\nvoid ConstraintBuilder::WhenDone(\n const std::function& callback) {\n common::MutexLocker locker(&mutex_);\n CHECK(when_done_ == nullptr);\n when_done_ =\n common::make_unique>(callback);\n ++pending_computations_[current_computation_];\n const int current_computation = current_computation_;\n thread_pool_->Schedule(\n [this, current_computation] { FinishComputation(current_computation); });\n}\n\nvoid ConstraintBuilder::ScheduleSubmapScanMatcherConstructionAndQueueWorkItem(\n const mapping::SubmapId& submap_id,\n const std::vector& submap_nodes,\n const Submap* const submap, const std::function& work_item) {\n if (submap_scan_matchers_[submap_id].fast_correlative_scan_matcher !=\n nullptr) {\n thread_pool_->Schedule(work_item);\n } else {\n submap_queued_work_items_[submap_id].push_back(work_item);\n if (submap_queued_work_items_[submap_id].size() == 1) {\n thread_pool_->Schedule([=]() {\n ConstructSubmapScanMatcher(submap_id, submap_nodes, submap);\n });\n }\n }\n}\n\nvoid ConstraintBuilder::ConstructSubmapScanMatcher(\n const mapping::SubmapId& submap_id,\n const std::vector& submap_nodes,\n const Submap* const submap) {\n auto submap_scan_matcher =\n common::make_unique(\n submap->high_resolution_hybrid_grid(),\n &submap->low_resolution_hybrid_grid(), submap_nodes,\n options_.fast_correlative_scan_matcher_options_3d());\n common::MutexLocker locker(&mutex_);\n submap_scan_matchers_[submap_id] = {&submap->high_resolution_hybrid_grid(),\n &submap->low_resolution_hybrid_grid(),\n std::move(submap_scan_matcher)};\n for (const std::function& work_item :\n submap_queued_work_items_[submap_id]) {\n thread_pool_->Schedule(work_item);\n }\n submap_queued_work_items_.erase(submap_id);\n}\n\nconst ConstraintBuilder::SubmapScanMatcher*\nConstraintBuilder::GetSubmapScanMatcher(const mapping::SubmapId& submap_id) {\n common::MutexLocker locker(&mutex_);\n const SubmapScanMatcher* submap_scan_matcher =\n &submap_scan_matchers_[submap_id];\n CHECK(submap_scan_matcher->fast_correlative_scan_matcher != nullptr);\n return submap_scan_matcher;\n}\n\nvoid ConstraintBuilder::ComputeConstraint(\n const mapping::SubmapId& submap_id, const mapping::NodeId& node_id,\n bool match_full_submap,\n const mapping::TrajectoryNode::Data* const constant_data,\n const transform::Rigid3d& global_node_pose,\n const transform::Rigid3d& global_submap_pose,\n std::unique_ptr* constraint) {\n const SubmapScanMatcher* const submap_scan_matcher =\n GetSubmapScanMatcher(submap_id);\n\n \/\/ The 'constraint_transform' (submap i <- node j) is computed from:\n \/\/ - a 'high_resolution_point_cloud' in node j and\n \/\/ - the initial guess 'initial_pose' (submap i <- node j).\n std::unique_ptr\n match_result;\n\n \/\/ Compute 'pose_estimate' in three stages:\n \/\/ 1. Fast estimate using the fast correlative scan matcher.\n \/\/ 2. Prune if the score is too low.\n \/\/ 3. Refine.\n if (match_full_submap) {\n match_result =\n submap_scan_matcher->fast_correlative_scan_matcher->MatchFullSubmap(\n global_node_pose.rotation(), global_submap_pose.rotation(),\n *constant_data, options_.global_localization_min_score());\n if (match_result != nullptr) {\n CHECK_GT(match_result->score, options_.global_localization_min_score());\n CHECK_GE(node_id.trajectory_id, 0);\n CHECK_GE(submap_id.trajectory_id, 0);\n } else {\n return;\n }\n } else {\n match_result = submap_scan_matcher->fast_correlative_scan_matcher->Match(\n global_node_pose, global_submap_pose, *constant_data,\n options_.min_score());\n if (match_result != nullptr) {\n \/\/ We've reported a successful local match.\n CHECK_GT(match_result->score, options_.min_score());\n } else {\n return;\n }\n }\n {\n common::MutexLocker locker(&mutex_);\n score_histogram_.Add(match_result->score);\n rotational_score_histogram_.Add(match_result->rotational_score);\n low_resolution_score_histogram_.Add(match_result->low_resolution_score);\n }\n\n \/\/ Use the CSM estimate as both the initial and previous pose. This has the\n \/\/ effect that, in the absence of better information, we prefer the original\n \/\/ CSM estimate.\n ceres::Solver::Summary unused_summary;\n transform::Rigid3d constraint_transform;\n ceres_scan_matcher_.Match(match_result->pose_estimate.translation(),\n match_result->pose_estimate,\n {{&constant_data->high_resolution_point_cloud,\n submap_scan_matcher->high_resolution_hybrid_grid},\n {&constant_data->low_resolution_point_cloud,\n submap_scan_matcher->low_resolution_hybrid_grid}},\n &constraint_transform, &unused_summary);\n\n constraint->reset(new OptimizationProblem::Constraint{\n submap_id,\n node_id,\n {constraint_transform, options_.loop_closure_translation_weight(),\n options_.loop_closure_rotation_weight()},\n OptimizationProblem::Constraint::INTER_SUBMAP});\n\n if (options_.log_matches()) {\n std::ostringstream info;\n info << \"Node \" << node_id << \" with \"\n << constant_data->high_resolution_point_cloud.size()\n << \" points on submap \" << submap_id << std::fixed;\n if (match_full_submap) {\n info << \" matches\";\n } else {\n const transform::Rigid3d difference = global_submap_pose.inverse() *\n global_node_pose *\n constraint_transform;\n info << \" differs by translation \" << std::setprecision(2)\n << difference.translation().norm() << \" rotation \"\n << std::setprecision(3) << transform::GetAngle(difference);\n }\n info << \" with score \" << std::setprecision(1) << 100. * match_result->score\n << \"%.\";\n LOG(INFO) << info.str();\n }\n}\n\nvoid ConstraintBuilder::FinishComputation(const int computation_index) {\n Result result;\n std::unique_ptr> callback;\n {\n common::MutexLocker locker(&mutex_);\n if (--pending_computations_[computation_index] == 0) {\n pending_computations_.erase(computation_index);\n }\n if (pending_computations_.empty()) {\n CHECK_EQ(submap_queued_work_items_.size(), 0);\n if (when_done_ != nullptr) {\n for (const std::unique_ptr&\n constraint : constraints_) {\n if (constraint != nullptr) {\n result.push_back(*constraint);\n }\n }\n if (options_.log_matches()) {\n LOG(INFO) << constraints_.size() << \" computations resulted in \"\n << result.size() << \" additional constraints.\";\n LOG(INFO) << \"Score histogram:\\n\" << score_histogram_.ToString(10);\n LOG(INFO) << \"Rotational score histogram:\\n\"\n << rotational_score_histogram_.ToString(10);\n LOG(INFO) << \"Low resolution score histogram:\\n\"\n << low_resolution_score_histogram_.ToString(10);\n }\n constraints_.clear();\n callback = std::move(when_done_);\n when_done_.reset();\n }\n }\n }\n if (callback != nullptr) {\n (*callback)(result);\n }\n}\n\nint ConstraintBuilder::GetNumFinishedNodes() {\n common::MutexLocker locker(&mutex_);\n if (pending_computations_.empty()) {\n return current_computation_;\n }\n return pending_computations_.begin()->first;\n}\n\nvoid ConstraintBuilder::DeleteScanMatcher(const mapping::SubmapId& submap_id) {\n common::MutexLocker locker(&mutex_);\n CHECK(pending_computations_.empty());\n submap_scan_matchers_.erase(submap_id);\n}\n\n} \/\/ namespace pose_graph\n} \/\/ namespace mapping_3d\n} \/\/ namespace cartographer\nFix debug output for 3D loop closure error. (#826)\/*\n * Copyright 2016 The Cartographer Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"cartographer\/mapping_3d\/pose_graph\/constraint_builder.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"Eigen\/Eigenvalues\"\n#include \"cartographer\/common\/make_unique.h\"\n#include \"cartographer\/common\/math.h\"\n#include \"cartographer\/common\/thread_pool.h\"\n#include \"cartographer\/mapping_3d\/scan_matching\/proto\/ceres_scan_matcher_options.pb.h\"\n#include \"cartographer\/mapping_3d\/scan_matching\/proto\/fast_correlative_scan_matcher_options.pb.h\"\n#include \"cartographer\/transform\/transform.h\"\n#include \"glog\/logging.h\"\n\nnamespace cartographer {\nnamespace mapping_3d {\nnamespace pose_graph {\n\nConstraintBuilder::ConstraintBuilder(\n const mapping::pose_graph::proto::ConstraintBuilderOptions& options,\n common::ThreadPool* const thread_pool)\n : options_(options),\n thread_pool_(thread_pool),\n sampler_(options.sampling_ratio()),\n ceres_scan_matcher_(options.ceres_scan_matcher_options_3d()) {}\n\nConstraintBuilder::~ConstraintBuilder() {\n common::MutexLocker locker(&mutex_);\n CHECK_EQ(constraints_.size(), 0) << \"WhenDone() was not called\";\n CHECK_EQ(pending_computations_.size(), 0);\n CHECK_EQ(submap_queued_work_items_.size(), 0);\n CHECK(when_done_ == nullptr);\n}\n\nvoid ConstraintBuilder::MaybeAddConstraint(\n const mapping::SubmapId& submap_id, const Submap* const submap,\n const mapping::NodeId& node_id,\n const mapping::TrajectoryNode::Data* const constant_data,\n const std::vector& submap_nodes,\n const transform::Rigid3d& global_node_pose,\n const transform::Rigid3d& global_submap_pose) {\n if ((global_node_pose.translation() - global_submap_pose.translation())\n .norm() > options_.max_constraint_distance()) {\n return;\n }\n if (sampler_.Pulse()) {\n common::MutexLocker locker(&mutex_);\n constraints_.emplace_back();\n auto* const constraint = &constraints_.back();\n ++pending_computations_[current_computation_];\n const int current_computation = current_computation_;\n ScheduleSubmapScanMatcherConstructionAndQueueWorkItem(\n submap_id, submap_nodes, submap, [=]() EXCLUDES(mutex_) {\n ComputeConstraint(submap_id, node_id, false, \/* match_full_submap *\/\n constant_data, global_node_pose, global_submap_pose,\n constraint);\n FinishComputation(current_computation);\n });\n }\n}\n\nvoid ConstraintBuilder::MaybeAddGlobalConstraint(\n const mapping::SubmapId& submap_id, const Submap* const submap,\n const mapping::NodeId& node_id,\n const mapping::TrajectoryNode::Data* const constant_data,\n const std::vector& submap_nodes,\n const Eigen::Quaterniond& global_node_rotation,\n const Eigen::Quaterniond& global_submap_rotation) {\n common::MutexLocker locker(&mutex_);\n constraints_.emplace_back();\n auto* const constraint = &constraints_.back();\n ++pending_computations_[current_computation_];\n const int current_computation = current_computation_;\n ScheduleSubmapScanMatcherConstructionAndQueueWorkItem(\n submap_id, submap_nodes, submap, [=]() EXCLUDES(mutex_) {\n ComputeConstraint(\n submap_id, node_id, true, \/* match_full_submap *\/\n constant_data, transform::Rigid3d::Rotation(global_node_rotation),\n transform::Rigid3d::Rotation(global_submap_rotation), constraint);\n FinishComputation(current_computation);\n });\n}\n\nvoid ConstraintBuilder::NotifyEndOfNode() {\n common::MutexLocker locker(&mutex_);\n ++current_computation_;\n}\n\nvoid ConstraintBuilder::WhenDone(\n const std::function& callback) {\n common::MutexLocker locker(&mutex_);\n CHECK(when_done_ == nullptr);\n when_done_ =\n common::make_unique>(callback);\n ++pending_computations_[current_computation_];\n const int current_computation = current_computation_;\n thread_pool_->Schedule(\n [this, current_computation] { FinishComputation(current_computation); });\n}\n\nvoid ConstraintBuilder::ScheduleSubmapScanMatcherConstructionAndQueueWorkItem(\n const mapping::SubmapId& submap_id,\n const std::vector& submap_nodes,\n const Submap* const submap, const std::function& work_item) {\n if (submap_scan_matchers_[submap_id].fast_correlative_scan_matcher !=\n nullptr) {\n thread_pool_->Schedule(work_item);\n } else {\n submap_queued_work_items_[submap_id].push_back(work_item);\n if (submap_queued_work_items_[submap_id].size() == 1) {\n thread_pool_->Schedule([=]() {\n ConstructSubmapScanMatcher(submap_id, submap_nodes, submap);\n });\n }\n }\n}\n\nvoid ConstraintBuilder::ConstructSubmapScanMatcher(\n const mapping::SubmapId& submap_id,\n const std::vector& submap_nodes,\n const Submap* const submap) {\n auto submap_scan_matcher =\n common::make_unique(\n submap->high_resolution_hybrid_grid(),\n &submap->low_resolution_hybrid_grid(), submap_nodes,\n options_.fast_correlative_scan_matcher_options_3d());\n common::MutexLocker locker(&mutex_);\n submap_scan_matchers_[submap_id] = {&submap->high_resolution_hybrid_grid(),\n &submap->low_resolution_hybrid_grid(),\n std::move(submap_scan_matcher)};\n for (const std::function& work_item :\n submap_queued_work_items_[submap_id]) {\n thread_pool_->Schedule(work_item);\n }\n submap_queued_work_items_.erase(submap_id);\n}\n\nconst ConstraintBuilder::SubmapScanMatcher*\nConstraintBuilder::GetSubmapScanMatcher(const mapping::SubmapId& submap_id) {\n common::MutexLocker locker(&mutex_);\n const SubmapScanMatcher* submap_scan_matcher =\n &submap_scan_matchers_[submap_id];\n CHECK(submap_scan_matcher->fast_correlative_scan_matcher != nullptr);\n return submap_scan_matcher;\n}\n\nvoid ConstraintBuilder::ComputeConstraint(\n const mapping::SubmapId& submap_id, const mapping::NodeId& node_id,\n bool match_full_submap,\n const mapping::TrajectoryNode::Data* const constant_data,\n const transform::Rigid3d& global_node_pose,\n const transform::Rigid3d& global_submap_pose,\n std::unique_ptr* constraint) {\n const SubmapScanMatcher* const submap_scan_matcher =\n GetSubmapScanMatcher(submap_id);\n\n \/\/ The 'constraint_transform' (submap i <- node j) is computed from:\n \/\/ - a 'high_resolution_point_cloud' in node j and\n \/\/ - the initial guess 'initial_pose' (submap i <- node j).\n std::unique_ptr\n match_result;\n\n \/\/ Compute 'pose_estimate' in three stages:\n \/\/ 1. Fast estimate using the fast correlative scan matcher.\n \/\/ 2. Prune if the score is too low.\n \/\/ 3. Refine.\n if (match_full_submap) {\n match_result =\n submap_scan_matcher->fast_correlative_scan_matcher->MatchFullSubmap(\n global_node_pose.rotation(), global_submap_pose.rotation(),\n *constant_data, options_.global_localization_min_score());\n if (match_result != nullptr) {\n CHECK_GT(match_result->score, options_.global_localization_min_score());\n CHECK_GE(node_id.trajectory_id, 0);\n CHECK_GE(submap_id.trajectory_id, 0);\n } else {\n return;\n }\n } else {\n match_result = submap_scan_matcher->fast_correlative_scan_matcher->Match(\n global_node_pose, global_submap_pose, *constant_data,\n options_.min_score());\n if (match_result != nullptr) {\n \/\/ We've reported a successful local match.\n CHECK_GT(match_result->score, options_.min_score());\n } else {\n return;\n }\n }\n {\n common::MutexLocker locker(&mutex_);\n score_histogram_.Add(match_result->score);\n rotational_score_histogram_.Add(match_result->rotational_score);\n low_resolution_score_histogram_.Add(match_result->low_resolution_score);\n }\n\n \/\/ Use the CSM estimate as both the initial and previous pose. This has the\n \/\/ effect that, in the absence of better information, we prefer the original\n \/\/ CSM estimate.\n ceres::Solver::Summary unused_summary;\n transform::Rigid3d constraint_transform;\n ceres_scan_matcher_.Match(match_result->pose_estimate.translation(),\n match_result->pose_estimate,\n {{&constant_data->high_resolution_point_cloud,\n submap_scan_matcher->high_resolution_hybrid_grid},\n {&constant_data->low_resolution_point_cloud,\n submap_scan_matcher->low_resolution_hybrid_grid}},\n &constraint_transform, &unused_summary);\n\n constraint->reset(new OptimizationProblem::Constraint{\n submap_id,\n node_id,\n {constraint_transform, options_.loop_closure_translation_weight(),\n options_.loop_closure_rotation_weight()},\n OptimizationProblem::Constraint::INTER_SUBMAP});\n\n if (options_.log_matches()) {\n std::ostringstream info;\n info << \"Node \" << node_id << \" with \"\n << constant_data->high_resolution_point_cloud.size()\n << \" points on submap \" << submap_id << std::fixed;\n if (match_full_submap) {\n info << \" matches\";\n } else {\n \/\/ Compute the difference between (submap i <- node j) according to loop\n \/\/ closure ('constraint_transform') and according to global SLAM state.\n const transform::Rigid3d difference = global_node_pose.inverse() *\n global_submap_pose *\n constraint_transform;\n info << \" differs by translation \" << std::setprecision(2)\n << difference.translation().norm() << \" rotation \"\n << std::setprecision(3) << transform::GetAngle(difference);\n }\n info << \" with score \" << std::setprecision(1) << 100. * match_result->score\n << \"%.\";\n LOG(INFO) << info.str();\n }\n}\n\nvoid ConstraintBuilder::FinishComputation(const int computation_index) {\n Result result;\n std::unique_ptr> callback;\n {\n common::MutexLocker locker(&mutex_);\n if (--pending_computations_[computation_index] == 0) {\n pending_computations_.erase(computation_index);\n }\n if (pending_computations_.empty()) {\n CHECK_EQ(submap_queued_work_items_.size(), 0);\n if (when_done_ != nullptr) {\n for (const std::unique_ptr&\n constraint : constraints_) {\n if (constraint != nullptr) {\n result.push_back(*constraint);\n }\n }\n if (options_.log_matches()) {\n LOG(INFO) << constraints_.size() << \" computations resulted in \"\n << result.size() << \" additional constraints.\";\n LOG(INFO) << \"Score histogram:\\n\" << score_histogram_.ToString(10);\n LOG(INFO) << \"Rotational score histogram:\\n\"\n << rotational_score_histogram_.ToString(10);\n LOG(INFO) << \"Low resolution score histogram:\\n\"\n << low_resolution_score_histogram_.ToString(10);\n }\n constraints_.clear();\n callback = std::move(when_done_);\n when_done_.reset();\n }\n }\n }\n if (callback != nullptr) {\n (*callback)(result);\n }\n}\n\nint ConstraintBuilder::GetNumFinishedNodes() {\n common::MutexLocker locker(&mutex_);\n if (pending_computations_.empty()) {\n return current_computation_;\n }\n return pending_computations_.begin()->first;\n}\n\nvoid ConstraintBuilder::DeleteScanMatcher(const mapping::SubmapId& submap_id) {\n common::MutexLocker locker(&mutex_);\n CHECK(pending_computations_.empty());\n submap_scan_matchers_.erase(submap_id);\n}\n\n} \/\/ namespace pose_graph\n} \/\/ namespace mapping_3d\n} \/\/ namespace cartographer\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/renderer_host\/resource_message_filter.h\"\n\n#include \"base\/gfx\/gtk_native_view_id_manager.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/common\/x11_util.h\"\n\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebScreenInfo.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/x11\/WebScreenInfoFactory.h\"\n\nusing WebKit::WebScreenInfo;\nusing WebKit::WebScreenInfoFactory;\n\n\/\/ We get null window_ids passed into the two functions below; please see\n\/\/ http:\/\/crbug.com\/9060 for more details.\n\n\/\/ Called on the IO thread.\nvoid ResourceMessageFilter::SendBackgroundX11Reply(IPC::Message* reply_msg) {\n Send(reply_msg);\n}\n\n\/\/ Called on the BACKGROUND_X11 thread.\nvoid ResourceMessageFilter::DoOnGetScreenInfo(gfx::NativeViewId view,\n IPC::Message* reply_msg) {\n Display* display = x11_util::GetSecondaryDisplay();\n int screen = x11_util::GetDefaultScreen(display);\n WebScreenInfo results = WebScreenInfoFactory::screenInfo(display, screen);\n ViewHostMsg_GetScreenInfo::WriteReplyParams(reply_msg, results);\n\n ChromeThread::GetMessageLoop(ChromeThread::IO)->PostTask(\n FROM_HERE, NewRunnableMethod(\n this, &ResourceMessageFilter::SendBackgroundX11Reply, reply_msg));\n}\n\n\/\/ Called on the BACKGROUND_X11 thread.\nvoid ResourceMessageFilter::DoOnGetWindowRect(gfx::NativeViewId view,\n IPC::Message* reply_msg) {\n \/\/ This is called to get the x, y offset (in screen coordinates) of the given\n \/\/ view and its width and height.\n gfx::Rect rect;\n XID window;\n\n if (Singleton()->GetXIDForId(&window, view)) {\n if (window) {\n int x, y;\n unsigned width, height;\n if (x11_util::GetWindowGeometry(&x, &y, &width, &height, window))\n rect = gfx::Rect(x, y, width, height);\n }\n }\n\n ViewHostMsg_GetWindowRect::WriteReplyParams(reply_msg, rect);\n\n ChromeThread::GetMessageLoop(ChromeThread::IO)->PostTask(\n FROM_HERE, NewRunnableMethod(\n this, &ResourceMessageFilter::SendBackgroundX11Reply, reply_msg));\n}\n\n\/\/ Return the top-level parent of the given window. Called on the\n\/\/ BACKGROUND_X11 thread.\nstatic XID GetTopLevelWindow(XID window) {\n bool parent_is_root;\n XID parent_window;\n\n if (!x11_util::GetWindowParent(&parent_window, &parent_is_root, window))\n return 0;\n if (parent_is_root)\n return window;\n\n return GetTopLevelWindow(parent_window);\n}\n\n\/\/ Called on the BACKGROUND_X11 thread.\nvoid ResourceMessageFilter::DoOnGetRootWindowRect(gfx::NativeViewId view,\n IPC::Message* reply_msg) {\n \/\/ This is called to get the screen coordinates and size of the browser\n \/\/ window itself.\n gfx::Rect rect;\n XID window;\n\n if (Singleton()->GetXIDForId(&window, view)) {\n if (window) {\n const XID toplevel = GetTopLevelWindow(toplevel);\n int x, y;\n unsigned width, height;\n if (x11_util::GetWindowGeometry(&x, &y, &width, &height, window))\n rect = gfx::Rect(x, y, width, height);\n }\n }\n\n ViewHostMsg_GetRootWindowRect::WriteReplyParams(reply_msg, rect);\n\n ChromeThread::GetMessageLoop(ChromeThread::IO)->PostTask(\n FROM_HERE, NewRunnableMethod(\n this, &ResourceMessageFilter::SendBackgroundX11Reply, reply_msg));\n}\n\n\/\/ Called on the IO thread.\nvoid ResourceMessageFilter::OnGetScreenInfo(gfx::NativeViewId view,\n IPC::Message* reply_msg) {\n ChromeThread::GetMessageLoop(ChromeThread::BACKGROUND_X11)->PostTask(\n FROM_HERE, NewRunnableMethod(\n this, &ResourceMessageFilter::DoOnGetScreenInfo, view, reply_msg));\n}\n\n\/\/ Called on the IO thread.\nvoid ResourceMessageFilter::OnGetWindowRect(gfx::NativeViewId view,\n IPC::Message* reply_msg) {\n ChromeThread::GetMessageLoop(ChromeThread::BACKGROUND_X11)->PostTask(\n FROM_HERE, NewRunnableMethod(\n this, &ResourceMessageFilter::DoOnGetWindowRect, view, reply_msg));\n}\n\n\/\/ Called on the IO thread.\nvoid ResourceMessageFilter::OnGetRootWindowRect(gfx::NativeViewId view,\n IPC::Message* reply_msg) {\n ChromeThread::GetMessageLoop(ChromeThread::BACKGROUND_X11)->PostTask(\n FROM_HERE, NewRunnableMethod(\n this, &ResourceMessageFilter::DoOnGetRootWindowRect, view, reply_msg));\n}\nLinux: fix root window co-ordinates.\/\/ Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/renderer_host\/resource_message_filter.h\"\n\n#include \"base\/gfx\/gtk_native_view_id_manager.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/common\/x11_util.h\"\n\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebScreenInfo.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/x11\/WebScreenInfoFactory.h\"\n\nusing WebKit::WebScreenInfo;\nusing WebKit::WebScreenInfoFactory;\n\n\/\/ We get null window_ids passed into the two functions below; please see\n\/\/ http:\/\/crbug.com\/9060 for more details.\n\n\/\/ Called on the IO thread.\nvoid ResourceMessageFilter::SendBackgroundX11Reply(IPC::Message* reply_msg) {\n Send(reply_msg);\n}\n\n\/\/ Called on the BACKGROUND_X11 thread.\nvoid ResourceMessageFilter::DoOnGetScreenInfo(gfx::NativeViewId view,\n IPC::Message* reply_msg) {\n Display* display = x11_util::GetSecondaryDisplay();\n int screen = x11_util::GetDefaultScreen(display);\n WebScreenInfo results = WebScreenInfoFactory::screenInfo(display, screen);\n ViewHostMsg_GetScreenInfo::WriteReplyParams(reply_msg, results);\n\n ChromeThread::GetMessageLoop(ChromeThread::IO)->PostTask(\n FROM_HERE, NewRunnableMethod(\n this, &ResourceMessageFilter::SendBackgroundX11Reply, reply_msg));\n}\n\n\/\/ Called on the BACKGROUND_X11 thread.\nvoid ResourceMessageFilter::DoOnGetWindowRect(gfx::NativeViewId view,\n IPC::Message* reply_msg) {\n \/\/ This is called to get the x, y offset (in screen coordinates) of the given\n \/\/ view and its width and height.\n gfx::Rect rect;\n XID window;\n\n if (Singleton()->GetXIDForId(&window, view)) {\n if (window) {\n int x, y;\n unsigned width, height;\n if (x11_util::GetWindowGeometry(&x, &y, &width, &height, window))\n rect = gfx::Rect(x, y, width, height);\n }\n }\n\n ViewHostMsg_GetWindowRect::WriteReplyParams(reply_msg, rect);\n\n ChromeThread::GetMessageLoop(ChromeThread::IO)->PostTask(\n FROM_HERE, NewRunnableMethod(\n this, &ResourceMessageFilter::SendBackgroundX11Reply, reply_msg));\n}\n\n\/\/ Return the top-level parent of the given window. Called on the\n\/\/ BACKGROUND_X11 thread.\nstatic XID GetTopLevelWindow(XID window) {\n bool parent_is_root;\n XID parent_window;\n\n if (!x11_util::GetWindowParent(&parent_window, &parent_is_root, window))\n return 0;\n if (parent_is_root)\n return window;\n\n return GetTopLevelWindow(parent_window);\n}\n\n\/\/ Called on the BACKGROUND_X11 thread.\nvoid ResourceMessageFilter::DoOnGetRootWindowRect(gfx::NativeViewId view,\n IPC::Message* reply_msg) {\n \/\/ This is called to get the screen coordinates and size of the browser\n \/\/ window itself.\n gfx::Rect rect;\n XID window;\n\n if (Singleton()->GetXIDForId(&window, view)) {\n if (window) {\n const XID toplevel = GetTopLevelWindow(window);\n int x, y;\n unsigned width, height;\n if (x11_util::GetWindowGeometry(&x, &y, &width, &height, toplevel))\n rect = gfx::Rect(x, y, width, height);\n }\n }\n\n ViewHostMsg_GetRootWindowRect::WriteReplyParams(reply_msg, rect);\n\n ChromeThread::GetMessageLoop(ChromeThread::IO)->PostTask(\n FROM_HERE, NewRunnableMethod(\n this, &ResourceMessageFilter::SendBackgroundX11Reply, reply_msg));\n}\n\n\/\/ Called on the IO thread.\nvoid ResourceMessageFilter::OnGetScreenInfo(gfx::NativeViewId view,\n IPC::Message* reply_msg) {\n ChromeThread::GetMessageLoop(ChromeThread::BACKGROUND_X11)->PostTask(\n FROM_HERE, NewRunnableMethod(\n this, &ResourceMessageFilter::DoOnGetScreenInfo, view, reply_msg));\n}\n\n\/\/ Called on the IO thread.\nvoid ResourceMessageFilter::OnGetWindowRect(gfx::NativeViewId view,\n IPC::Message* reply_msg) {\n ChromeThread::GetMessageLoop(ChromeThread::BACKGROUND_X11)->PostTask(\n FROM_HERE, NewRunnableMethod(\n this, &ResourceMessageFilter::DoOnGetWindowRect, view, reply_msg));\n}\n\n\/\/ Called on the IO thread.\nvoid ResourceMessageFilter::OnGetRootWindowRect(gfx::NativeViewId view,\n IPC::Message* reply_msg) {\n ChromeThread::GetMessageLoop(ChromeThread::BACKGROUND_X11)->PostTask(\n FROM_HERE, NewRunnableMethod(\n this, &ResourceMessageFilter::DoOnGetRootWindowRect, view, reply_msg));\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/gtk\/translate\/translate_infobar_base_gtk.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"app\/slide_animation.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/translate\/options_menu_model.h\"\n#include \"chrome\/browser\/translate\/translate_infobar_delegate.h\"\n#include \"chrome\/browser\/gtk\/translate\/after_translate_infobar_gtk.h\"\n#include \"chrome\/browser\/gtk\/translate\/before_translate_infobar_gtk.h\"\n#include \"chrome\/browser\/gtk\/translate\/translate_message_infobar_gtk.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n#include \"chrome\/browser\/gtk\/menu_gtk.h\"\n#include \"gfx\/canvas.h\"\n#include \"gfx\/gtk_util.h\"\n#include \"grit\/generated_resources.h\"\n\nnamespace {\n\n\/\/ To be able to map from language id <-> entry in the combo box, we\n\/\/ store the language id in the combo box data model in addition to the\n\/\/ displayed name.\nenum {\n LANGUAGE_COMBO_COLUMN_ID,\n LANGUAGE_COMBO_COLUMN_NAME,\n LANGUAGE_COMBO_COLUMN_COUNT\n};\n\n} \/\/ namespace\n\nTranslateInfoBarBase::TranslateInfoBarBase(TranslateInfoBarDelegate* delegate)\n : InfoBar(delegate) {\n TranslateInfoBarDelegate::BackgroundAnimationType animation =\n delegate->background_animation_type();\n if (animation != TranslateInfoBarDelegate::kNone) {\n background_color_animation_.reset(new SlideAnimation(this));\n background_color_animation_->SetTweenType(Tween::LINEAR);\n background_color_animation_->SetSlideDuration(500);\n if (animation == TranslateInfoBarDelegate::kNormalToError) {\n background_color_animation_->Show();\n } else {\n DCHECK_EQ(TranslateInfoBarDelegate::kErrorToNormal, animation);\n \/\/ Hide() runs the animation in reverse.\n background_color_animation_->Reset(1.0);\n background_color_animation_->Hide();\n }\n }\n}\n\nTranslateInfoBarBase::~TranslateInfoBarBase() {\n}\n\nvoid TranslateInfoBarBase::Init() {\n if (!ShowOptionsMenuButton())\n return;\n\n \/\/ The options button sits outside the translate_box so that it can be end\n \/\/ packed in hbox_.\n GtkWidget* options_menu_button = BuildOptionsMenuButton();\n g_signal_connect(options_menu_button, \"clicked\",\n G_CALLBACK(&OnOptionsClickedThunk), this);\n gtk_widget_show_all(options_menu_button);\n gtk_util::CenterWidgetInHBox(hbox_, options_menu_button, true, 0);\n}\n\nvoid TranslateInfoBarBase::GetTopColor(InfoBarDelegate::Type type,\n double* r, double* g, double *b) {\n if (background_error_percent_ <= 0) {\n InfoBar::GetTopColor(InfoBarDelegate::PAGE_ACTION_TYPE, r, g, b);\n } else if (background_error_percent_ >= 1) {\n InfoBar::GetTopColor(InfoBarDelegate::ERROR_TYPE, r, g, b);\n } else {\n double normal_r, normal_g, normal_b;\n InfoBar::GetTopColor(InfoBarDelegate::PAGE_ACTION_TYPE,\n &normal_r, &normal_g, &normal_b);\n\n double error_r, error_g, error_b;\n InfoBar::GetTopColor(InfoBarDelegate::ERROR_TYPE,\n &error_r, &error_g, &error_b);\n\n double offset_r = error_r - normal_r;\n double offset_g = error_g - normal_g;\n double offset_b = error_b - normal_b;\n\n *r = normal_r + (background_error_percent_ * offset_r);\n *g = normal_g + (background_error_percent_ * offset_g);\n *b = normal_b + (background_error_percent_ * offset_b);\n }\n}\n\nvoid TranslateInfoBarBase::GetBottomColor(InfoBarDelegate::Type type,\n double* r, double* g, double *b) {\n if (background_error_percent_ <= 0) {\n InfoBar::GetBottomColor(InfoBarDelegate::PAGE_ACTION_TYPE, r, g, b);\n } else if (background_error_percent_ >= 1) {\n InfoBar::GetBottomColor(InfoBarDelegate::ERROR_TYPE, r, g, b);\n } else {\n double normal_r, normal_g, normal_b;\n InfoBar::GetBottomColor(InfoBarDelegate::PAGE_ACTION_TYPE,\n &normal_r, &normal_g, &normal_b);\n\n double error_r, error_g, error_b;\n InfoBar::GetBottomColor(InfoBarDelegate::ERROR_TYPE,\n &error_r, &error_g, &error_b);\n\n double offset_r = error_r - normal_r;\n double offset_g = error_g - normal_g;\n double offset_b = error_b - normal_b;\n\n *r = normal_r + (background_error_percent_ * offset_r);\n *g = normal_g + (background_error_percent_ * offset_g);\n *b = normal_b + (background_error_percent_ * offset_b);\n }\n}\n\nvoid TranslateInfoBarBase::AnimationProgressed(const Animation* animation) {\n DCHECK(animation == background_color_animation_.get());\n background_error_percent_ = animation->GetCurrentValue();\n \/\/ Queue the info bar widget for redisplay so it repaints its background.\n gtk_widget_queue_draw(widget());\n}\n\nGtkWidget* TranslateInfoBarBase::CreateLabel(const std::string& text) {\n GtkWidget* label = gtk_label_new(text.c_str());\n gtk_widget_modify_fg(label, GTK_STATE_NORMAL, &gfx::kGdkBlack);\n return label;\n}\n\nGtkWidget* TranslateInfoBarBase::CreateLanguageCombobox(int selected_language,\n int exclude_language) {\n GtkListStore* model = gtk_list_store_new(LANGUAGE_COMBO_COLUMN_COUNT,\n G_TYPE_INT, G_TYPE_STRING);\n bool set_selection = false;\n GtkTreeIter selected_iter;\n TranslateInfoBarDelegate* delegate = GetDelegate();\n for (int i = 0; i < delegate->GetLanguageCount(); ++i) {\n if (i == exclude_language)\n continue;\n GtkTreeIter tree_iter;\n const string16& name = delegate->GetLanguageDisplayableNameAt(i);\n\n gtk_list_store_append(model, &tree_iter);\n gtk_list_store_set(model, &tree_iter,\n LANGUAGE_COMBO_COLUMN_ID, i,\n LANGUAGE_COMBO_COLUMN_NAME, UTF16ToUTF8(name).c_str(),\n -1);\n if (i == selected_language) {\n selected_iter = tree_iter;\n set_selection = true;\n }\n }\n\n GtkWidget* combobox = gtk_combo_box_new_with_model(GTK_TREE_MODEL(model));\n if (set_selection)\n gtk_combo_box_set_active_iter(GTK_COMBO_BOX(combobox), &selected_iter);\n g_object_unref(model);\n GtkCellRenderer* renderer = gtk_cell_renderer_text_new();\n gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(combobox), renderer, TRUE);\n gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(combobox), renderer,\n \"text\", LANGUAGE_COMBO_COLUMN_NAME,\n NULL);\n return combobox;\n}\n\n\/\/ static\nint TranslateInfoBarBase::GetLanguageComboboxActiveId(GtkComboBox* combo) {\n GtkTreeIter iter;\n if (!gtk_combo_box_get_active_iter(combo, &iter))\n return 0;\n\n gint id = 0;\n gtk_tree_model_get(gtk_combo_box_get_model(combo), &iter,\n LANGUAGE_COMBO_COLUMN_ID, &id,\n -1);\n return id;\n}\n\nTranslateInfoBarDelegate* TranslateInfoBarBase::GetDelegate() const {\n return static_cast(delegate());\n}\n\n\/\/ static\nGtkWidget* TranslateInfoBarBase::BuildOptionsMenuButton() {\n GtkWidget* button = gtk_button_new();\n GtkWidget* former_child = gtk_bin_get_child(GTK_BIN(button));\n if (former_child)\n gtk_container_remove(GTK_CONTAINER(button), former_child);\n\n GtkWidget* hbox = gtk_hbox_new(FALSE, 0);\n\n GtkWidget* label = gtk_label_new(\n l10n_util::GetStringUTF8(IDS_TRANSLATE_INFOBAR_OPTIONS).c_str());\n gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0);\n\n GtkWidget* arrow = gtk_arrow_new(GTK_ARROW_DOWN, GTK_SHADOW_NONE);\n gtk_box_pack_start(GTK_BOX(hbox), arrow, FALSE, FALSE, 0);\n\n gtk_container_add(GTK_CONTAINER(button), hbox);\n\n return button;\n}\n\nvoid TranslateInfoBarBase::OnOptionsClicked(GtkWidget* sender) {\n if (!options_menu_model_.get()) {\n options_menu_model_.reset(new OptionsMenuModel(GetDelegate()));\n options_menu_menu_.reset(new MenuGtk(NULL, options_menu_model_.get()));\n }\n options_menu_menu_->Popup(sender, 1, gtk_get_current_event_time());\n}\n\n\/\/ TranslateInfoBarDelegate specific method:\nInfoBar* TranslateInfoBarDelegate::CreateInfoBar() {\n TranslateInfoBarBase* infobar = NULL;\n switch (type_) {\n case kBeforeTranslate:\n infobar = new BeforeTranslateInfoBar(this);\n break;\n case kAfterTranslate:\n infobar = new AfterTranslateInfoBar(this);\n break;\n case kTranslating:\n case kTranslationError:\n infobar = new TranslateMessageInfoBar(this);\n break;\n default:\n NOTREACHED();\n }\n infobar->Init();\n \/\/ Set |infobar_view_| so that the model can notify the infobar when it\n \/\/ changes.\n infobar_view_ = infobar;\n return infobar;\n}\nFixing translate infobar background. In some cases the infobar background was not the right color.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/gtk\/translate\/translate_infobar_base_gtk.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"app\/slide_animation.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/translate\/options_menu_model.h\"\n#include \"chrome\/browser\/translate\/translate_infobar_delegate.h\"\n#include \"chrome\/browser\/gtk\/translate\/after_translate_infobar_gtk.h\"\n#include \"chrome\/browser\/gtk\/translate\/before_translate_infobar_gtk.h\"\n#include \"chrome\/browser\/gtk\/translate\/translate_message_infobar_gtk.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n#include \"chrome\/browser\/gtk\/menu_gtk.h\"\n#include \"gfx\/canvas.h\"\n#include \"gfx\/gtk_util.h\"\n#include \"grit\/generated_resources.h\"\n\nnamespace {\n\n\/\/ To be able to map from language id <-> entry in the combo box, we\n\/\/ store the language id in the combo box data model in addition to the\n\/\/ displayed name.\nenum {\n LANGUAGE_COMBO_COLUMN_ID,\n LANGUAGE_COMBO_COLUMN_NAME,\n LANGUAGE_COMBO_COLUMN_COUNT\n};\n\n} \/\/ namespace\n\nTranslateInfoBarBase::TranslateInfoBarBase(TranslateInfoBarDelegate* delegate)\n : InfoBar(delegate) {\n TranslateInfoBarDelegate::BackgroundAnimationType animation =\n delegate->background_animation_type();\n if (animation != TranslateInfoBarDelegate::kNone) {\n background_color_animation_.reset(new SlideAnimation(this));\n background_color_animation_->SetTweenType(Tween::LINEAR);\n background_color_animation_->SetSlideDuration(500);\n if (animation == TranslateInfoBarDelegate::kNormalToError) {\n background_color_animation_->Show();\n } else {\n DCHECK_EQ(TranslateInfoBarDelegate::kErrorToNormal, animation);\n \/\/ Hide() runs the animation in reverse.\n background_color_animation_->Reset(1.0);\n background_color_animation_->Hide();\n }\n } else {\n background_error_percent_ = delegate->IsError() ? 1 : 0;\n }\n}\n\nTranslateInfoBarBase::~TranslateInfoBarBase() {\n}\n\nvoid TranslateInfoBarBase::Init() {\n if (!ShowOptionsMenuButton())\n return;\n\n \/\/ The options button sits outside the translate_box so that it can be end\n \/\/ packed in hbox_.\n GtkWidget* options_menu_button = BuildOptionsMenuButton();\n g_signal_connect(options_menu_button, \"clicked\",\n G_CALLBACK(&OnOptionsClickedThunk), this);\n gtk_widget_show_all(options_menu_button);\n gtk_util::CenterWidgetInHBox(hbox_, options_menu_button, true, 0);\n}\n\nvoid TranslateInfoBarBase::GetTopColor(InfoBarDelegate::Type type,\n double* r, double* g, double *b) {\n if (background_error_percent_ <= 0) {\n InfoBar::GetTopColor(InfoBarDelegate::PAGE_ACTION_TYPE, r, g, b);\n } else if (background_error_percent_ >= 1) {\n InfoBar::GetTopColor(InfoBarDelegate::ERROR_TYPE, r, g, b);\n } else {\n double normal_r, normal_g, normal_b;\n InfoBar::GetTopColor(InfoBarDelegate::PAGE_ACTION_TYPE,\n &normal_r, &normal_g, &normal_b);\n\n double error_r, error_g, error_b;\n InfoBar::GetTopColor(InfoBarDelegate::ERROR_TYPE,\n &error_r, &error_g, &error_b);\n\n double offset_r = error_r - normal_r;\n double offset_g = error_g - normal_g;\n double offset_b = error_b - normal_b;\n\n *r = normal_r + (background_error_percent_ * offset_r);\n *g = normal_g + (background_error_percent_ * offset_g);\n *b = normal_b + (background_error_percent_ * offset_b);\n }\n}\n\nvoid TranslateInfoBarBase::GetBottomColor(InfoBarDelegate::Type type,\n double* r, double* g, double *b) {\n if (background_error_percent_ <= 0) {\n InfoBar::GetBottomColor(InfoBarDelegate::PAGE_ACTION_TYPE, r, g, b);\n } else if (background_error_percent_ >= 1) {\n InfoBar::GetBottomColor(InfoBarDelegate::ERROR_TYPE, r, g, b);\n } else {\n double normal_r, normal_g, normal_b;\n InfoBar::GetBottomColor(InfoBarDelegate::PAGE_ACTION_TYPE,\n &normal_r, &normal_g, &normal_b);\n\n double error_r, error_g, error_b;\n InfoBar::GetBottomColor(InfoBarDelegate::ERROR_TYPE,\n &error_r, &error_g, &error_b);\n\n double offset_r = error_r - normal_r;\n double offset_g = error_g - normal_g;\n double offset_b = error_b - normal_b;\n\n *r = normal_r + (background_error_percent_ * offset_r);\n *g = normal_g + (background_error_percent_ * offset_g);\n *b = normal_b + (background_error_percent_ * offset_b);\n }\n}\n\nvoid TranslateInfoBarBase::AnimationProgressed(const Animation* animation) {\n DCHECK(animation == background_color_animation_.get());\n background_error_percent_ = animation->GetCurrentValue();\n \/\/ Queue the info bar widget for redisplay so it repaints its background.\n gtk_widget_queue_draw(widget());\n}\n\nGtkWidget* TranslateInfoBarBase::CreateLabel(const std::string& text) {\n GtkWidget* label = gtk_label_new(text.c_str());\n gtk_widget_modify_fg(label, GTK_STATE_NORMAL, &gfx::kGdkBlack);\n return label;\n}\n\nGtkWidget* TranslateInfoBarBase::CreateLanguageCombobox(int selected_language,\n int exclude_language) {\n GtkListStore* model = gtk_list_store_new(LANGUAGE_COMBO_COLUMN_COUNT,\n G_TYPE_INT, G_TYPE_STRING);\n bool set_selection = false;\n GtkTreeIter selected_iter;\n TranslateInfoBarDelegate* delegate = GetDelegate();\n for (int i = 0; i < delegate->GetLanguageCount(); ++i) {\n if (i == exclude_language)\n continue;\n GtkTreeIter tree_iter;\n const string16& name = delegate->GetLanguageDisplayableNameAt(i);\n\n gtk_list_store_append(model, &tree_iter);\n gtk_list_store_set(model, &tree_iter,\n LANGUAGE_COMBO_COLUMN_ID, i,\n LANGUAGE_COMBO_COLUMN_NAME, UTF16ToUTF8(name).c_str(),\n -1);\n if (i == selected_language) {\n selected_iter = tree_iter;\n set_selection = true;\n }\n }\n\n GtkWidget* combobox = gtk_combo_box_new_with_model(GTK_TREE_MODEL(model));\n if (set_selection)\n gtk_combo_box_set_active_iter(GTK_COMBO_BOX(combobox), &selected_iter);\n g_object_unref(model);\n GtkCellRenderer* renderer = gtk_cell_renderer_text_new();\n gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(combobox), renderer, TRUE);\n gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(combobox), renderer,\n \"text\", LANGUAGE_COMBO_COLUMN_NAME,\n NULL);\n return combobox;\n}\n\n\/\/ static\nint TranslateInfoBarBase::GetLanguageComboboxActiveId(GtkComboBox* combo) {\n GtkTreeIter iter;\n if (!gtk_combo_box_get_active_iter(combo, &iter))\n return 0;\n\n gint id = 0;\n gtk_tree_model_get(gtk_combo_box_get_model(combo), &iter,\n LANGUAGE_COMBO_COLUMN_ID, &id,\n -1);\n return id;\n}\n\nTranslateInfoBarDelegate* TranslateInfoBarBase::GetDelegate() const {\n return static_cast(delegate());\n}\n\n\/\/ static\nGtkWidget* TranslateInfoBarBase::BuildOptionsMenuButton() {\n GtkWidget* button = gtk_button_new();\n GtkWidget* former_child = gtk_bin_get_child(GTK_BIN(button));\n if (former_child)\n gtk_container_remove(GTK_CONTAINER(button), former_child);\n\n GtkWidget* hbox = gtk_hbox_new(FALSE, 0);\n\n GtkWidget* label = gtk_label_new(\n l10n_util::GetStringUTF8(IDS_TRANSLATE_INFOBAR_OPTIONS).c_str());\n gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0);\n\n GtkWidget* arrow = gtk_arrow_new(GTK_ARROW_DOWN, GTK_SHADOW_NONE);\n gtk_box_pack_start(GTK_BOX(hbox), arrow, FALSE, FALSE, 0);\n\n gtk_container_add(GTK_CONTAINER(button), hbox);\n\n return button;\n}\n\nvoid TranslateInfoBarBase::OnOptionsClicked(GtkWidget* sender) {\n if (!options_menu_model_.get()) {\n options_menu_model_.reset(new OptionsMenuModel(GetDelegate()));\n options_menu_menu_.reset(new MenuGtk(NULL, options_menu_model_.get()));\n }\n options_menu_menu_->Popup(sender, 1, gtk_get_current_event_time());\n}\n\n\/\/ TranslateInfoBarDelegate specific method:\nInfoBar* TranslateInfoBarDelegate::CreateInfoBar() {\n TranslateInfoBarBase* infobar = NULL;\n switch (type_) {\n case kBeforeTranslate:\n infobar = new BeforeTranslateInfoBar(this);\n break;\n case kAfterTranslate:\n infobar = new AfterTranslateInfoBar(this);\n break;\n case kTranslating:\n case kTranslationError:\n infobar = new TranslateMessageInfoBar(this);\n break;\n default:\n NOTREACHED();\n }\n infobar->Init();\n \/\/ Set |infobar_view_| so that the model can notify the infobar when it\n \/\/ changes.\n infobar_view_ = infobar;\n return infobar;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/process_util.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/tabs\/tab_strip_model.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/find_bar\/find_bar_controller.h\"\n#include \"chrome\/browser\/ui\/find_bar\/find_notification_details.h\"\n#include \"chrome\/browser\/ui\/view_ids.h\"\n#include \"chrome\/browser\/ui\/views\/find_bar_host.h\"\n#include \"chrome\/browser\/ui\/views\/frame\/browser_view.h\"\n#include \"chrome\/common\/chrome_notification_types.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"net\/test\/test_server.h\"\n#include \"ui\/base\/clipboard\/clipboard.h\"\n#include \"ui\/base\/keycodes\/keyboard_codes.h\"\n#include \"views\/focus\/focus_manager.h\"\n#include \"views\/view.h\"\n#include \"views\/views_delegate.h\"\n\nnamespace {\n\n\/\/ The delay waited after sending an OS simulated event.\nstatic const int kActionDelayMs = 500;\nstatic const char kSimplePage[] = \"files\/find_in_page\/simple.html\";\n\nvoid Checkpoint(const char* message, const base::TimeTicks& start_time) {\n LOG(INFO) << message << \" : \"\n << (base::TimeTicks::Now() - start_time).InMilliseconds()\n << \" ms\" << std::flush;\n}\n\nclass FindInPageTest : public InProcessBrowserTest {\n public:\n FindInPageTest() {\n set_show_window(true);\n FindBarHost::disable_animations_during_testing_ = true;\n }\n\n string16 GetFindBarText() {\n FindBarTesting* find_bar =\n browser()->GetFindBarController()->find_bar()->GetFindBarTesting();\n return find_bar->GetFindText();\n }\n\n string16 GetFindBarSelectedText() {\n FindBarTesting* find_bar =\n browser()->GetFindBarController()->find_bar()->GetFindBarTesting();\n return find_bar->GetFindSelectedText();\n }\n};\n\n} \/\/ namespace\n\n#if defined(TOOLKIT_USES_GTK)\n#define MAYBE_CrashEscHandlers FLAKY_CrashEscHandlers\n#else\n#define MAYBE_CrashEscHandlers CrashEscHandlers\n#endif\n\nIN_PROC_BROWSER_TEST_F(FindInPageTest, MAYBE_CrashEscHandlers) {\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ First we navigate to our test page (tab A).\n GURL url = test_server()->GetURL(kSimplePage);\n ui_test_utils::NavigateToURL(browser(), url);\n\n browser()->Find();\n\n \/\/ Open another tab (tab B).\n browser()->AddSelectedTabWithURL(url, PageTransition::TYPED);\n\n browser()->Find();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n\n \/\/ Select tab A.\n browser()->ActivateTabAt(0, true);\n\n \/\/ Close tab B.\n browser()->CloseTabContents(browser()->GetTabContentsAt(1));\n\n \/\/ Click on the location bar so that Find box loses focus.\n ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(),\n VIEW_ID_LOCATION_BAR));\n#if defined(TOOLKIT_VIEWS) || defined(OS_WIN)\n \/\/ Check the location bar is focused.\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));\n#endif\n\n \/\/ This used to crash until bug 1303709 was fixed.\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_ESCAPE, false, false, false, false));\n}\n\nIN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestore) {\n ASSERT_TRUE(test_server()->Start());\n\n GURL url = test_server()->GetURL(\"title1.html\");\n ui_test_utils::NavigateToURL(browser(), url);\n\n \/\/ Focus the location bar, open and close the find-in-page, focus should\n \/\/ return to the location bar.\n browser()->FocusLocationBar();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));\n \/\/ Ensure the creation of the find bar controller.\n browser()->GetFindBarController()->Show();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n browser()->GetFindBarController()->EndFindSession(\n FindBarController::kKeepSelection);\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));\n\n \/\/ Focus the location bar, find something on the page, close the find box,\n \/\/ focus should go to the page.\n browser()->FocusLocationBar();\n browser()->Find();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),\n ASCIIToUTF16(\"a\"), true, false, NULL);\n browser()->GetFindBarController()->EndFindSession(\n FindBarController::kKeepSelection);\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));\n\n \/\/ Focus the location bar, open and close the find box, focus should return to\n \/\/ the location bar (same as before, just checking that http:\/\/crbug.com\/23599\n \/\/ is fixed).\n browser()->FocusLocationBar();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));\n browser()->GetFindBarController()->Show();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n browser()->GetFindBarController()->EndFindSession(\n FindBarController::kKeepSelection);\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));\n}\n\nIN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestoreOnTabSwitch) {\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ First we navigate to our test page (tab A).\n GURL url = test_server()->GetURL(kSimplePage);\n ui_test_utils::NavigateToURL(browser(), url);\n\n browser()->Find();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n\n FindBarTesting* find_bar =\n browser()->GetFindBarController()->find_bar()->GetFindBarTesting();\n\n \/\/ Search for 'a'.\n ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),\n ASCIIToUTF16(\"a\"), true, false, NULL);\n EXPECT_TRUE(ASCIIToUTF16(\"a\") == find_bar->GetFindSelectedText());\n\n \/\/ Open another tab (tab B).\n browser()->AddSelectedTabWithURL(url, PageTransition::TYPED);\n ASSERT_TRUE(ui_test_utils::WaitForNavigationInCurrentTab(browser()));\n\n \/\/ Make sure Find box is open.\n browser()->Find();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n\n \/\/ Search for 'b'.\n ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),\n ASCIIToUTF16(\"b\"), true, false, NULL);\n EXPECT_TRUE(ASCIIToUTF16(\"b\") == find_bar->GetFindSelectedText());\n\n \/\/ Set focus away from the Find bar (to the Location bar).\n browser()->FocusLocationBar();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));\n\n \/\/ Select tab A. Find bar should get focus.\n browser()->ActivateTabAt(0, true);\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n EXPECT_TRUE(ASCIIToUTF16(\"a\") == find_bar->GetFindSelectedText());\n\n \/\/ Select tab B. Location bar should get focus.\n browser()->ActivateTabAt(1, true);\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));\n}\n\n\/\/ This tests that whenever you clear values from the Find box and close it that\n\/\/ it respects that and doesn't show you the last search, as reported in bug:\n\/\/ http:\/\/crbug.com\/40121.\nIN_PROC_BROWSER_TEST_F(FindInPageTest, PrepopulateRespectBlank) {\n#if defined(OS_MACOSX)\n \/\/ FindInPage on Mac doesn't use prepopulated values. Search there is global.\n return;\n#endif\n base::TimeTicks start_time = base::TimeTicks::Now();\n Checkpoint(\"Test starting\", start_time);\n\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ Make sure Chrome is in the foreground, otherwise sending input\n \/\/ won't do anything and the test will hang.\n ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));\n\n Checkpoint(\"Navigate\", start_time);\n\n \/\/ First we navigate to any page.\n GURL url = test_server()->GetURL(kSimplePage);\n ui_test_utils::NavigateToURL(browser(), url);\n\n Checkpoint(\"Show Find bar\", start_time);\n\n \/\/ Show the Find bar.\n browser()->GetFindBarController()->Show();\n\n Checkpoint(\"Search for 'a'\", start_time);\n\n \/\/ Search for \"a\".\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_A, false, false, false, false));\n\n \/\/ We should find \"a\" here.\n EXPECT_EQ(ASCIIToUTF16(\"a\"), GetFindBarText());\n\n Checkpoint(\"Delete 'a'\", start_time);\n\n \/\/ Delete \"a\".\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_BACK, false, false, false, false));\n\n \/\/ Validate we have cleared the text.\n EXPECT_EQ(string16(), GetFindBarText());\n\n Checkpoint(\"Close find bar\", start_time);\n\n \/\/ Close the Find box.\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_ESCAPE, false, false, false, false));\n\n Checkpoint(\"Show Find bar\", start_time);\n\n \/\/ Show the Find bar.\n browser()->GetFindBarController()->Show();\n\n Checkpoint(\"Validate text\", start_time);\n\n \/\/ After the Find box has been reopened, it should not have been prepopulated\n \/\/ with \"a\" again.\n EXPECT_EQ(string16(), GetFindBarText());\n\n Checkpoint(\"Close Find bar\", start_time);\n\n \/\/ Close the Find box.\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_ESCAPE, false, false, false, false));\n\n Checkpoint(\"FindNext\", start_time);\n\n \/\/ Press F3 to trigger FindNext.\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_F3, false, false, false, false));\n\n Checkpoint(\"Validate\", start_time);\n\n \/\/ After the Find box has been reopened, it should still have no prepopulate\n \/\/ value.\n EXPECT_EQ(string16(), GetFindBarText());\n\n Checkpoint(\"Test done\", start_time);\n}\n\nIN_PROC_BROWSER_TEST_F(FindInPageTest, PasteWithoutTextChange) {\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ Make sure Chrome is in the foreground, otherwise sending input\n \/\/ won't do anything and the test will hang.\n ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));\n\n \/\/ First we navigate to any page.\n GURL url = test_server()->GetURL(kSimplePage);\n ui_test_utils::NavigateToURL(browser(), url);\n\n \/\/ Show the Find bar.\n browser()->GetFindBarController()->Show();\n\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n\n \/\/ Search for \"a\".\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_A, false, false, false, false));\n\n \/\/ We should find \"a\" here.\n EXPECT_EQ(ASCIIToUTF16(\"a\"), GetFindBarText());\n\n \/\/ Reload the page to clear the matching result.\n browser()->Reload(CURRENT_TAB);\n\n \/\/ Focus the Find bar again to make sure the text is selected.\n browser()->GetFindBarController()->Show();\n\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n\n \/\/ \"a\" should be selected.\n EXPECT_EQ(ASCIIToUTF16(\"a\"), GetFindBarSelectedText());\n\n \/\/ Press Ctrl-C to copy the content.\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_C, true, false, false, false));\n\n string16 str;\n views::ViewsDelegate::views_delegate->GetClipboard()->\n ReadText(ui::Clipboard::BUFFER_STANDARD, &str);\n\n \/\/ Make sure the text is copied successfully.\n EXPECT_EQ(ASCIIToUTF16(\"a\"), str);\n\n \/\/ Press Ctrl-V to paste the content back, it should start finding even if the\n \/\/ content is not changed.\n Source notification_source(browser()->GetSelectedTabContents());\n ui_test_utils::WindowedNotificationObserverWithDetails\n observer(\n chrome::NOTIFICATION_FIND_RESULT_AVAILABLE, notification_source);\n\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_V, true, false, false, false));\n\n ASSERT_NO_FATAL_FAILURE(observer.Wait());\n FindNotificationDetails details;\n ASSERT_TRUE(observer.GetDetailsFor(notification_source.map_key(), &details));\n EXPECT_TRUE(details.number_of_matches() > 0);\n}\nMark FindInPageTest.PasteWithoutTextChange flaky on Win.\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/process_util.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/tabs\/tab_strip_model.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/find_bar\/find_bar_controller.h\"\n#include \"chrome\/browser\/ui\/find_bar\/find_notification_details.h\"\n#include \"chrome\/browser\/ui\/view_ids.h\"\n#include \"chrome\/browser\/ui\/views\/find_bar_host.h\"\n#include \"chrome\/browser\/ui\/views\/frame\/browser_view.h\"\n#include \"chrome\/common\/chrome_notification_types.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"net\/test\/test_server.h\"\n#include \"ui\/base\/clipboard\/clipboard.h\"\n#include \"ui\/base\/keycodes\/keyboard_codes.h\"\n#include \"views\/focus\/focus_manager.h\"\n#include \"views\/view.h\"\n#include \"views\/views_delegate.h\"\n\nnamespace {\n\n\/\/ The delay waited after sending an OS simulated event.\nstatic const int kActionDelayMs = 500;\nstatic const char kSimplePage[] = \"files\/find_in_page\/simple.html\";\n\nvoid Checkpoint(const char* message, const base::TimeTicks& start_time) {\n LOG(INFO) << message << \" : \"\n << (base::TimeTicks::Now() - start_time).InMilliseconds()\n << \" ms\" << std::flush;\n}\n\nclass FindInPageTest : public InProcessBrowserTest {\n public:\n FindInPageTest() {\n set_show_window(true);\n FindBarHost::disable_animations_during_testing_ = true;\n }\n\n string16 GetFindBarText() {\n FindBarTesting* find_bar =\n browser()->GetFindBarController()->find_bar()->GetFindBarTesting();\n return find_bar->GetFindText();\n }\n\n string16 GetFindBarSelectedText() {\n FindBarTesting* find_bar =\n browser()->GetFindBarController()->find_bar()->GetFindBarTesting();\n return find_bar->GetFindSelectedText();\n }\n};\n\n} \/\/ namespace\n\n#if defined(TOOLKIT_USES_GTK)\n#define MAYBE_CrashEscHandlers FLAKY_CrashEscHandlers\n#else\n#define MAYBE_CrashEscHandlers CrashEscHandlers\n#endif\n\nIN_PROC_BROWSER_TEST_F(FindInPageTest, MAYBE_CrashEscHandlers) {\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ First we navigate to our test page (tab A).\n GURL url = test_server()->GetURL(kSimplePage);\n ui_test_utils::NavigateToURL(browser(), url);\n\n browser()->Find();\n\n \/\/ Open another tab (tab B).\n browser()->AddSelectedTabWithURL(url, PageTransition::TYPED);\n\n browser()->Find();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n\n \/\/ Select tab A.\n browser()->ActivateTabAt(0, true);\n\n \/\/ Close tab B.\n browser()->CloseTabContents(browser()->GetTabContentsAt(1));\n\n \/\/ Click on the location bar so that Find box loses focus.\n ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(),\n VIEW_ID_LOCATION_BAR));\n#if defined(TOOLKIT_VIEWS) || defined(OS_WIN)\n \/\/ Check the location bar is focused.\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));\n#endif\n\n \/\/ This used to crash until bug 1303709 was fixed.\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_ESCAPE, false, false, false, false));\n}\n\nIN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestore) {\n ASSERT_TRUE(test_server()->Start());\n\n GURL url = test_server()->GetURL(\"title1.html\");\n ui_test_utils::NavigateToURL(browser(), url);\n\n \/\/ Focus the location bar, open and close the find-in-page, focus should\n \/\/ return to the location bar.\n browser()->FocusLocationBar();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));\n \/\/ Ensure the creation of the find bar controller.\n browser()->GetFindBarController()->Show();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n browser()->GetFindBarController()->EndFindSession(\n FindBarController::kKeepSelection);\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));\n\n \/\/ Focus the location bar, find something on the page, close the find box,\n \/\/ focus should go to the page.\n browser()->FocusLocationBar();\n browser()->Find();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),\n ASCIIToUTF16(\"a\"), true, false, NULL);\n browser()->GetFindBarController()->EndFindSession(\n FindBarController::kKeepSelection);\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));\n\n \/\/ Focus the location bar, open and close the find box, focus should return to\n \/\/ the location bar (same as before, just checking that http:\/\/crbug.com\/23599\n \/\/ is fixed).\n browser()->FocusLocationBar();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));\n browser()->GetFindBarController()->Show();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n browser()->GetFindBarController()->EndFindSession(\n FindBarController::kKeepSelection);\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));\n}\n\nIN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestoreOnTabSwitch) {\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ First we navigate to our test page (tab A).\n GURL url = test_server()->GetURL(kSimplePage);\n ui_test_utils::NavigateToURL(browser(), url);\n\n browser()->Find();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n\n FindBarTesting* find_bar =\n browser()->GetFindBarController()->find_bar()->GetFindBarTesting();\n\n \/\/ Search for 'a'.\n ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),\n ASCIIToUTF16(\"a\"), true, false, NULL);\n EXPECT_TRUE(ASCIIToUTF16(\"a\") == find_bar->GetFindSelectedText());\n\n \/\/ Open another tab (tab B).\n browser()->AddSelectedTabWithURL(url, PageTransition::TYPED);\n ASSERT_TRUE(ui_test_utils::WaitForNavigationInCurrentTab(browser()));\n\n \/\/ Make sure Find box is open.\n browser()->Find();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n\n \/\/ Search for 'b'.\n ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),\n ASCIIToUTF16(\"b\"), true, false, NULL);\n EXPECT_TRUE(ASCIIToUTF16(\"b\") == find_bar->GetFindSelectedText());\n\n \/\/ Set focus away from the Find bar (to the Location bar).\n browser()->FocusLocationBar();\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));\n\n \/\/ Select tab A. Find bar should get focus.\n browser()->ActivateTabAt(0, true);\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n EXPECT_TRUE(ASCIIToUTF16(\"a\") == find_bar->GetFindSelectedText());\n\n \/\/ Select tab B. Location bar should get focus.\n browser()->ActivateTabAt(1, true);\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));\n}\n\n\/\/ This tests that whenever you clear values from the Find box and close it that\n\/\/ it respects that and doesn't show you the last search, as reported in bug:\n\/\/ http:\/\/crbug.com\/40121.\nIN_PROC_BROWSER_TEST_F(FindInPageTest, PrepopulateRespectBlank) {\n#if defined(OS_MACOSX)\n \/\/ FindInPage on Mac doesn't use prepopulated values. Search there is global.\n return;\n#endif\n base::TimeTicks start_time = base::TimeTicks::Now();\n Checkpoint(\"Test starting\", start_time);\n\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ Make sure Chrome is in the foreground, otherwise sending input\n \/\/ won't do anything and the test will hang.\n ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));\n\n Checkpoint(\"Navigate\", start_time);\n\n \/\/ First we navigate to any page.\n GURL url = test_server()->GetURL(kSimplePage);\n ui_test_utils::NavigateToURL(browser(), url);\n\n Checkpoint(\"Show Find bar\", start_time);\n\n \/\/ Show the Find bar.\n browser()->GetFindBarController()->Show();\n\n Checkpoint(\"Search for 'a'\", start_time);\n\n \/\/ Search for \"a\".\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_A, false, false, false, false));\n\n \/\/ We should find \"a\" here.\n EXPECT_EQ(ASCIIToUTF16(\"a\"), GetFindBarText());\n\n Checkpoint(\"Delete 'a'\", start_time);\n\n \/\/ Delete \"a\".\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_BACK, false, false, false, false));\n\n \/\/ Validate we have cleared the text.\n EXPECT_EQ(string16(), GetFindBarText());\n\n Checkpoint(\"Close find bar\", start_time);\n\n \/\/ Close the Find box.\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_ESCAPE, false, false, false, false));\n\n Checkpoint(\"Show Find bar\", start_time);\n\n \/\/ Show the Find bar.\n browser()->GetFindBarController()->Show();\n\n Checkpoint(\"Validate text\", start_time);\n\n \/\/ After the Find box has been reopened, it should not have been prepopulated\n \/\/ with \"a\" again.\n EXPECT_EQ(string16(), GetFindBarText());\n\n Checkpoint(\"Close Find bar\", start_time);\n\n \/\/ Close the Find box.\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_ESCAPE, false, false, false, false));\n\n Checkpoint(\"FindNext\", start_time);\n\n \/\/ Press F3 to trigger FindNext.\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_F3, false, false, false, false));\n\n Checkpoint(\"Validate\", start_time);\n\n \/\/ After the Find box has been reopened, it should still have no prepopulate\n \/\/ value.\n EXPECT_EQ(string16(), GetFindBarText());\n\n Checkpoint(\"Test done\", start_time);\n}\n\n\/\/ Flaky on Win. http:\/\/crbug.com\/92467\n#if defined(OS_WIN)\n#define MAYBE_PasteWithoutTextChange FLAKY_PasteWithoutTextChange\n#else\n#define MAYBE_PasteWithoutTextChange PasteWithoutTextChange\n#endif\n\nIN_PROC_BROWSER_TEST_F(FindInPageTest, MAYBE_PasteWithoutTextChange) {\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ Make sure Chrome is in the foreground, otherwise sending input\n \/\/ won't do anything and the test will hang.\n ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));\n\n \/\/ First we navigate to any page.\n GURL url = test_server()->GetURL(kSimplePage);\n ui_test_utils::NavigateToURL(browser(), url);\n\n \/\/ Show the Find bar.\n browser()->GetFindBarController()->Show();\n\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n\n \/\/ Search for \"a\".\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_A, false, false, false, false));\n\n \/\/ We should find \"a\" here.\n EXPECT_EQ(ASCIIToUTF16(\"a\"), GetFindBarText());\n\n \/\/ Reload the page to clear the matching result.\n browser()->Reload(CURRENT_TAB);\n\n \/\/ Focus the Find bar again to make sure the text is selected.\n browser()->GetFindBarController()->Show();\n\n EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),\n VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));\n\n \/\/ \"a\" should be selected.\n EXPECT_EQ(ASCIIToUTF16(\"a\"), GetFindBarSelectedText());\n\n \/\/ Press Ctrl-C to copy the content.\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_C, true, false, false, false));\n\n string16 str;\n views::ViewsDelegate::views_delegate->GetClipboard()->\n ReadText(ui::Clipboard::BUFFER_STANDARD, &str);\n\n \/\/ Make sure the text is copied successfully.\n EXPECT_EQ(ASCIIToUTF16(\"a\"), str);\n\n \/\/ Press Ctrl-V to paste the content back, it should start finding even if the\n \/\/ content is not changed.\n Source notification_source(browser()->GetSelectedTabContents());\n ui_test_utils::WindowedNotificationObserverWithDetails\n observer(\n chrome::NOTIFICATION_FIND_RESULT_AVAILABLE, notification_source);\n\n ASSERT_TRUE(ui_test_utils::SendKeyPressSync(\n browser(), ui::VKEY_V, true, false, false, false));\n\n ASSERT_NO_FATAL_FAILURE(observer.Wait());\n FindNotificationDetails details;\n ASSERT_TRUE(observer.GetDetailsFor(notification_source.map_key(), &details));\n EXPECT_TRUE(details.number_of_matches() > 0);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/constrained_window_frame_simple.h\"\n\n#include \"chrome\/browser\/ui\/constrained_window.h\"\n#include \"chrome\/browser\/ui\/views\/constrained_window_views.h\"\n#include \"grit\/ui_resources.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/google_chrome_strings.h\"\n#include \"grit\/shared_resources.h\"\n#include \"grit\/theme_resources.h\"\n#include \"ui\/base\/hit_test.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/gfx\/canvas.h\"\n#include \"ui\/gfx\/rect.h\"\n#include \"ui\/gfx\/path.h\"\n#include \"ui\/views\/background.h\"\n#include \"ui\/views\/controls\/label.h\"\n#include \"ui\/views\/controls\/button\/image_button.h\"\n#include \"ui\/views\/layout\/grid_layout.h\"\n#include \"ui\/views\/layout\/layout_manager.h\"\n#include \"ui\/views\/layout\/layout_constants.h\"\n#include \"ui\/views\/widget\/widget.h\"\n#include \"ui\/views\/widget\/widget_delegate.h\"\n\nnamespace {\n\ntypedef ConstrainedWindowFrameSimple::HeaderViews HeaderViews;\n\n\/\/ A layout manager that lays out the header view with proper padding,\n\/\/ and sized to the widget's client view.\nclass HeaderLayout : public views::LayoutManager {\n public:\n explicit HeaderLayout(views::Widget* container) : container_(container) {}\n virtual ~HeaderLayout() {}\n\n \/\/ Overridden from LayoutManager\n virtual void Layout(views::View* host);\n virtual gfx::Size GetPreferredSize(views::View* host);\n\n private:\n views::Widget* container_;\n\n DISALLOW_COPY_AND_ASSIGN(HeaderLayout);\n};\n\nvoid HeaderLayout::Layout(views::View* host) {\n if (!host->has_children())\n return;\n\n int horizontal_padding = ConstrainedWindow::kHorizontalPadding;\n int vertical_padding = ConstrainedWindow::kVerticalPadding;\n int row_padding = ConstrainedWindow::kRowPadding;\n\n views::View* header = host->child_at(0);\n gfx::Size preferred_size = GetPreferredSize(host);\n int width = preferred_size.width() - 2 * horizontal_padding;\n int height = preferred_size.height() - vertical_padding - row_padding;\n\n header->SetBounds(horizontal_padding, vertical_padding, width, height);\n}\n\ngfx::Size HeaderLayout::GetPreferredSize(views::View* host) {\n int horizontal_padding = ConstrainedWindow::kHorizontalPadding;\n int vertical_padding = ConstrainedWindow::kVerticalPadding;\n int row_padding = ConstrainedWindow::kRowPadding;\n\n views::View* header = host->child_at(0);\n views::View* client_view = container_->client_view();\n\n gfx::Size header_size = header ? header->GetPreferredSize() : gfx::Size();\n gfx::Size client_size =\n client_view ? client_view->GetPreferredSize() : gfx::Size();\n int width = std::max(client_size.width(), header_size.width()) +\n 2 * horizontal_padding;\n int height = vertical_padding + header_size.height() + row_padding;\n return gfx::Size(width, height);\n}\n\n} \/\/ namespace\n\nConstrainedWindowFrameSimple::HeaderViews::HeaderViews(\n views::View* header,\n views::Label* title_label,\n views::Button* close_button)\n : header(header),\n title_label(title_label),\n close_button(close_button) {\n DCHECK(header);\n}\n\nConstrainedWindowFrameSimple::ConstrainedWindowFrameSimple(\n ConstrainedWindowViews* container)\n : container_(container) {\n container_->set_frame_type(views::Widget::FRAME_TYPE_FORCE_CUSTOM);\n\n layout_ = new HeaderLayout(container_);\n SetLayoutManager(layout_);\n\n SetHeaderView(CreateDefaultHeaderView());\n\n set_background(views::Background::CreateSolidBackground(\n ConstrainedWindow::GetBackgroundColor()));\n}\n\nConstrainedWindowFrameSimple::~ConstrainedWindowFrameSimple() {\n}\n\nvoid ConstrainedWindowFrameSimple::SetHeaderView(HeaderViews* header_views)\n{\n RemoveAllChildViews(true);\n\n header_views_.reset(header_views);\n\n AddChildView(header_views_->header);\n}\n\nHeaderViews* ConstrainedWindowFrameSimple::CreateDefaultHeaderView() {\n views::View* header_view = new views::View;\n\n views::GridLayout* grid_layout = new views::GridLayout(header_view);\n header_view->SetLayoutManager(grid_layout);\n\n views::ColumnSet* header_cs = grid_layout->AddColumnSet(0);\n header_cs->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER, 0,\n views::GridLayout::USE_PREF, 0, 0); \/\/ Title.\n header_cs->AddPaddingColumn(1, views::kUnrelatedControlHorizontalSpacing);\n header_cs->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER, 0,\n views::GridLayout::USE_PREF, 0, 0); \/\/ Close Button.\n\n \/\/ Header row.\n ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();\n grid_layout->StartRow(0, 0);\n views::Label* title_label = new views::Label();\n title_label->SetHorizontalAlignment(views::Label::ALIGN_LEFT);\n title_label->SetFont(rb.GetFont(ConstrainedWindow::kTitleFontStyle));\n title_label->SetEnabledColor(ConstrainedWindow::GetTextColor());\n title_label->SetText(container_->widget_delegate()->GetWindowTitle());\n grid_layout->AddView(title_label);\n\n views::Button* close_button = CreateCloseButton();\n grid_layout->AddView(close_button);\n\n return new HeaderViews(header_view, title_label, close_button);\n}\n\ngfx::Rect ConstrainedWindowFrameSimple::GetBoundsForClientView() const {\n int horizontal_padding = ConstrainedWindow::kHorizontalPadding;\n int vertical_padding = ConstrainedWindow::kVerticalPadding;\n int row_padding = ConstrainedWindow::kRowPadding;\n gfx::Size header_size =\n header_views_->header ?\n header_views_->header->GetPreferredSize() : gfx::Size();\n\n return gfx::Rect(horizontal_padding,\n vertical_padding + header_size.height() + row_padding,\n std::max(0, width() - 2 * horizontal_padding),\n std::max(0, (height() - 2 * vertical_padding -\n header_size.height() - row_padding)));\n}\n\ngfx::Rect ConstrainedWindowFrameSimple::GetWindowBoundsForClientBounds(\n const gfx::Rect& client_bounds) const {\n int horizontal_padding = ConstrainedWindow::kHorizontalPadding;\n int vertical_padding = ConstrainedWindow::kVerticalPadding;\n int row_padding = ConstrainedWindow::kRowPadding;\n gfx::Size header_size =\n header_views_->header ?\n header_views_->header->GetPreferredSize() : gfx::Size();\n\n int x = client_bounds.x() - horizontal_padding;\n int y = client_bounds.y() - vertical_padding - header_size.height() -\n row_padding;\n int width = client_bounds.width() + 2 * horizontal_padding;\n int height = client_bounds.height() + 2 * vertical_padding +\n header_size.height() + row_padding;\n\n return gfx::Rect(x, y, width, height);\n}\n\nint ConstrainedWindowFrameSimple::NonClientHitTest(const gfx::Point& point) {\n if (!bounds().Contains(point))\n return HTNOWHERE;\n return HTCLIENT;\n}\n\nvoid ConstrainedWindowFrameSimple::GetWindowMask(const gfx::Size& size,\n gfx::Path* window_mask) {\n SkRect rect = {0, 0, size.width() - 1, size.height() - 1};\n SkScalar radius = SkIntToScalar(ConstrainedWindow::kBorderRadius);\n SkScalar radii[8] = {radius, radius, radius, radius,\n radius, radius, radius, radius};\n\n \/\/ NB: We're not using the addRoundRect uniform radius overload as it\n \/\/ mishandles the bottom corners on Windows\n window_mask->addRoundRect(rect, radii);\n}\n\nvoid ConstrainedWindowFrameSimple::ResetWindowControls() {\n}\n\nvoid ConstrainedWindowFrameSimple::UpdateWindowIcon() {\n}\n\nvoid ConstrainedWindowFrameSimple::UpdateWindowTitle() {\n if (!header_views_->title_label)\n return;\n\n string16 text = container_->widget_delegate()->GetWindowTitle();\n header_views_->title_label->SetText(text);\n}\n\ngfx::Size ConstrainedWindowFrameSimple::GetPreferredSize() {\n return container_->non_client_view()->GetWindowBoundsForClientBounds(\n gfx::Rect(container_->client_view()->GetPreferredSize())).size();\n}\n\nvoid ConstrainedWindowFrameSimple::ButtonPressed(views::Button* sender,\n const ui::Event& event) {\n if (header_views_->close_button && sender == header_views_->close_button)\n sender->GetWidget()->Close();\n}\n\nviews::ImageButton* ConstrainedWindowFrameSimple::CreateCloseButton() {\n ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();\n views::ImageButton* close_button = new views::ImageButton(this);\n close_button->SetImage(views::CustomButton::BS_NORMAL,\n rb.GetImageSkiaNamed(IDR_SHARED_IMAGES_X));\n close_button->SetImage(views::CustomButton::BS_HOT,\n rb.GetImageSkiaNamed(IDR_SHARED_IMAGES_X_HOVER));\n close_button->SetImage(views::CustomButton::BS_PUSHED,\n rb.GetImageSkiaNamed(IDR_SHARED_IMAGES_X_HOVER));\n return close_button;\n}\nAdd workaround for window mask off-by-one bug\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/constrained_window_frame_simple.h\"\n\n#include \"chrome\/browser\/ui\/constrained_window.h\"\n#include \"chrome\/browser\/ui\/views\/constrained_window_views.h\"\n#include \"grit\/ui_resources.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/google_chrome_strings.h\"\n#include \"grit\/shared_resources.h\"\n#include \"grit\/theme_resources.h\"\n#include \"ui\/base\/hit_test.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/gfx\/canvas.h\"\n#include \"ui\/gfx\/rect.h\"\n#include \"ui\/gfx\/path.h\"\n#include \"ui\/views\/background.h\"\n#include \"ui\/views\/controls\/label.h\"\n#include \"ui\/views\/controls\/button\/image_button.h\"\n#include \"ui\/views\/layout\/grid_layout.h\"\n#include \"ui\/views\/layout\/layout_manager.h\"\n#include \"ui\/views\/layout\/layout_constants.h\"\n#include \"ui\/views\/widget\/widget.h\"\n#include \"ui\/views\/widget\/widget_delegate.h\"\n\nnamespace {\n\ntypedef ConstrainedWindowFrameSimple::HeaderViews HeaderViews;\n\n\/\/ A layout manager that lays out the header view with proper padding,\n\/\/ and sized to the widget's client view.\nclass HeaderLayout : public views::LayoutManager {\n public:\n explicit HeaderLayout(views::Widget* container) : container_(container) {}\n virtual ~HeaderLayout() {}\n\n \/\/ Overridden from LayoutManager\n virtual void Layout(views::View* host);\n virtual gfx::Size GetPreferredSize(views::View* host);\n\n private:\n views::Widget* container_;\n\n DISALLOW_COPY_AND_ASSIGN(HeaderLayout);\n};\n\nvoid HeaderLayout::Layout(views::View* host) {\n if (!host->has_children())\n return;\n\n int horizontal_padding = ConstrainedWindow::kHorizontalPadding;\n int vertical_padding = ConstrainedWindow::kVerticalPadding;\n int row_padding = ConstrainedWindow::kRowPadding;\n\n views::View* header = host->child_at(0);\n gfx::Size preferred_size = GetPreferredSize(host);\n int width = preferred_size.width() - 2 * horizontal_padding;\n int height = preferred_size.height() - vertical_padding - row_padding;\n\n header->SetBounds(horizontal_padding, vertical_padding, width, height);\n}\n\ngfx::Size HeaderLayout::GetPreferredSize(views::View* host) {\n int horizontal_padding = ConstrainedWindow::kHorizontalPadding;\n int vertical_padding = ConstrainedWindow::kVerticalPadding;\n int row_padding = ConstrainedWindow::kRowPadding;\n\n views::View* header = host->child_at(0);\n views::View* client_view = container_->client_view();\n\n gfx::Size header_size = header ? header->GetPreferredSize() : gfx::Size();\n gfx::Size client_size =\n client_view ? client_view->GetPreferredSize() : gfx::Size();\n int width = std::max(client_size.width(), header_size.width()) +\n 2 * horizontal_padding;\n int height = vertical_padding + header_size.height() + row_padding;\n return gfx::Size(width, height);\n}\n\n} \/\/ namespace\n\nConstrainedWindowFrameSimple::HeaderViews::HeaderViews(\n views::View* header,\n views::Label* title_label,\n views::Button* close_button)\n : header(header),\n title_label(title_label),\n close_button(close_button) {\n DCHECK(header);\n}\n\nConstrainedWindowFrameSimple::ConstrainedWindowFrameSimple(\n ConstrainedWindowViews* container)\n : container_(container) {\n container_->set_frame_type(views::Widget::FRAME_TYPE_FORCE_CUSTOM);\n\n layout_ = new HeaderLayout(container_);\n SetLayoutManager(layout_);\n\n SetHeaderView(CreateDefaultHeaderView());\n\n set_background(views::Background::CreateSolidBackground(\n ConstrainedWindow::GetBackgroundColor()));\n}\n\nConstrainedWindowFrameSimple::~ConstrainedWindowFrameSimple() {\n}\n\nvoid ConstrainedWindowFrameSimple::SetHeaderView(HeaderViews* header_views)\n{\n RemoveAllChildViews(true);\n\n header_views_.reset(header_views);\n\n AddChildView(header_views_->header);\n}\n\nHeaderViews* ConstrainedWindowFrameSimple::CreateDefaultHeaderView() {\n views::View* header_view = new views::View;\n\n views::GridLayout* grid_layout = new views::GridLayout(header_view);\n header_view->SetLayoutManager(grid_layout);\n\n views::ColumnSet* header_cs = grid_layout->AddColumnSet(0);\n header_cs->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER, 0,\n views::GridLayout::USE_PREF, 0, 0); \/\/ Title.\n header_cs->AddPaddingColumn(1, views::kUnrelatedControlHorizontalSpacing);\n header_cs->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER, 0,\n views::GridLayout::USE_PREF, 0, 0); \/\/ Close Button.\n\n \/\/ Header row.\n ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();\n grid_layout->StartRow(0, 0);\n views::Label* title_label = new views::Label();\n title_label->SetHorizontalAlignment(views::Label::ALIGN_LEFT);\n title_label->SetFont(rb.GetFont(ConstrainedWindow::kTitleFontStyle));\n title_label->SetEnabledColor(ConstrainedWindow::GetTextColor());\n title_label->SetText(container_->widget_delegate()->GetWindowTitle());\n grid_layout->AddView(title_label);\n\n views::Button* close_button = CreateCloseButton();\n grid_layout->AddView(close_button);\n\n return new HeaderViews(header_view, title_label, close_button);\n}\n\ngfx::Rect ConstrainedWindowFrameSimple::GetBoundsForClientView() const {\n int horizontal_padding = ConstrainedWindow::kHorizontalPadding;\n int vertical_padding = ConstrainedWindow::kVerticalPadding;\n int row_padding = ConstrainedWindow::kRowPadding;\n gfx::Size header_size =\n header_views_->header ?\n header_views_->header->GetPreferredSize() : gfx::Size();\n\n return gfx::Rect(horizontal_padding,\n vertical_padding + header_size.height() + row_padding,\n std::max(0, width() - 2 * horizontal_padding),\n std::max(0, (height() - 2 * vertical_padding -\n header_size.height() - row_padding)));\n}\n\ngfx::Rect ConstrainedWindowFrameSimple::GetWindowBoundsForClientBounds(\n const gfx::Rect& client_bounds) const {\n int horizontal_padding = ConstrainedWindow::kHorizontalPadding;\n int vertical_padding = ConstrainedWindow::kVerticalPadding;\n int row_padding = ConstrainedWindow::kRowPadding;\n gfx::Size header_size =\n header_views_->header ?\n header_views_->header->GetPreferredSize() : gfx::Size();\n\n int x = client_bounds.x() - horizontal_padding;\n int y = client_bounds.y() - vertical_padding - header_size.height() -\n row_padding;\n int width = client_bounds.width() + 2 * horizontal_padding;\n int height = client_bounds.height() + 2 * vertical_padding +\n header_size.height() + row_padding;\n\n return gfx::Rect(x, y, width, height);\n}\n\nint ConstrainedWindowFrameSimple::NonClientHitTest(const gfx::Point& point) {\n if (!bounds().Contains(point))\n return HTNOWHERE;\n return HTCLIENT;\n}\n\nvoid ConstrainedWindowFrameSimple::GetWindowMask(const gfx::Size& size,\n gfx::Path* window_mask) {\n#if defined(USE_AURA)\n SkRect rect = {0, 0, size.width() - 1, size.height() - 1};\n#else\n \/\/ There appears to be a bug in the window mask calculation on Windows\n \/\/ which causes the width, but not the height, to be off by one.\n SkRect rect = {0, 0, size.width(), size.height() - 1};\n#endif\n SkScalar radius = SkIntToScalar(ConstrainedWindow::kBorderRadius);\n SkScalar radii[8] = {radius, radius, radius, radius,\n radius, radius, radius, radius};\n\n \/\/ NB: We're not using the addRoundRect uniform radius overload as it\n \/\/ mishandles the bottom corners on Windows\n window_mask->addRoundRect(rect, radii);\n}\n\nvoid ConstrainedWindowFrameSimple::ResetWindowControls() {\n}\n\nvoid ConstrainedWindowFrameSimple::UpdateWindowIcon() {\n}\n\nvoid ConstrainedWindowFrameSimple::UpdateWindowTitle() {\n if (!header_views_->title_label)\n return;\n\n string16 text = container_->widget_delegate()->GetWindowTitle();\n header_views_->title_label->SetText(text);\n}\n\ngfx::Size ConstrainedWindowFrameSimple::GetPreferredSize() {\n return container_->non_client_view()->GetWindowBoundsForClientBounds(\n gfx::Rect(container_->client_view()->GetPreferredSize())).size();\n}\n\nvoid ConstrainedWindowFrameSimple::ButtonPressed(views::Button* sender,\n const ui::Event& event) {\n if (header_views_->close_button && sender == header_views_->close_button)\n sender->GetWidget()->Close();\n}\n\nviews::ImageButton* ConstrainedWindowFrameSimple::CreateCloseButton() {\n ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();\n views::ImageButton* close_button = new views::ImageButton(this);\n close_button->SetImage(views::CustomButton::BS_NORMAL,\n rb.GetImageSkiaNamed(IDR_SHARED_IMAGES_X));\n close_button->SetImage(views::CustomButton::BS_HOT,\n rb.GetImageSkiaNamed(IDR_SHARED_IMAGES_X_HOVER));\n close_button->SetImage(views::CustomButton::BS_PUSHED,\n rb.GetImageSkiaNamed(IDR_SHARED_IMAGES_X_HOVER));\n return close_button;\n}\n<|endoftext|>"} {"text":"#include \"EditorApp.h\"\n#include \"ECS\/Component.h\"\n#include \"Engine\/Clock.h\"\n#include \"Components\/Transform.h\"\n#include \"ECS\/Entity.h\"\n#include \n#include \"Engine\/Input.h\"\n#include \"Components\/Camera.h\"\n#include \"Components\/Physics\/Rigidbody.h\"\n#include \"Components\/Graphics\/Model.h\"\n#include \"Components\/Lighting\/Light.h\"\n\n#include \n#include \"Engine\/World.h\"\n#include \"Path.h\"\n#include \"Cores\/EditorCore.h\"\n#include \"Engine\/Engine.h\"\n#include \"Havana.h\"\n#include \"Cores\/SceneGraph.h\"\n#include \"Events\/SceneEvents.h\"\n#include \"RenderCommands.h\"\n#include \"Events\/Event.h\"\n#include \n#include \"Math\/Matirx4.h\"\n#include \"Math\/Frustrum.h\"\n\nEditorApp::EditorApp()\n{\n\tstd::vector events;\n\tevents.push_back(NewSceneEvent::GetEventId());\n\tevents.push_back(SceneLoadedEvent::GetEventId());\n\tEventManager::GetInstance().RegisterReceiver(this, events);\n\n}\n\nEditorApp::~EditorApp()\n{\n}\n\nvoid EditorApp::OnStart()\n{\n}\n\nvoid EditorApp::OnUpdate(float DeltaTime)\n{\n\tEditor->NewFrame([this]() {\n\t\tStartGame();\n\t\tm_isGamePaused = false;\n\t\tm_isGameRunning = true;\n\t\t}\n\t\t, [this]() {\n\t\t\tm_isGamePaused = true;\n\t\t}\n\t\t\t, [this]() {\n\t\t\tStopGame();\n\t\t\tm_isGameRunning = false;\n\t\t\tm_isGamePaused = false;\n\t\t\tEditor->ClearSelection();\n\t\t\t\/\/GetEngine().LoadScene(\"Assets\/Alley.lvl\");\n\t\t});\n\n\tEditorSceneManager->Update(DeltaTime, GetEngine().SceneNodes->GetRootTransform());\n\n\tEditor->UpdateWorld(GetEngine().GetWorld().lock().get(), GetEngine().SceneNodes->GetRootTransform(), EditorSceneManager->GetEntities());\n\n\tUpdateCameras();\n}\n\nvoid EditorApp::UpdateCameras()\n{\n\tVector2 MainOutputSize = Editor->GetGameOutputSize();\n\n\tif (!Camera::CurrentCamera)\n\t{\n\t\tCamera::CurrentCamera = Camera::EditorCamera;\n\t}\n\n\tMoonlight::CameraData EditorCamera;\n\n\tCamera::CurrentCamera->OutputSize = MainOutputSize;\n\tEditorCamera.Position = EditorSceneManager->GetEditorCameraTransform()->GetWorldPosition();\n\tEditorCamera.Front = EditorSceneManager->GetEditorCameraTransform()->Front();\n\tEditorCamera.Up = Vector3::Up;\n\tEditorCamera.OutputSize = Editor->WorldViewRenderSize;\n\tEditorCamera.FOV = Camera::EditorCamera->GetFOV();\n\tEditorCamera.Near = Camera::EditorCamera->Near;\n\tEditorCamera.Far = Camera::EditorCamera->Far;\n\tEditorCamera.Skybox = Camera::CurrentCamera->Skybox;\n\tEditorCamera.ClearColor = Camera::CurrentCamera->ClearColor;\n\tEditorCamera.ClearType = Camera::CurrentCamera->ClearType;\n\tEditorCamera.Projection = Camera::EditorCamera->Projection;\n\tEditorCamera.OrthographicSize = Camera::EditorCamera->OrthographicSize;\n\tEditorCamera.CameraFrustum = Camera::EditorCamera->CameraFrustum;\n\n\tGetEngine().EditorCamera = EditorCamera;\n}\n\nvoid EditorApp::OnEnd()\n{\n\n\t\/\/destroy(mGame);\n}\n\nvoid EditorApp::OnInitialize()\n{\n\tif (!Editor)\n\t{\n\t\tInitialLevel = GetEngine().GetConfig().GetValue(\"CurrentScene\");\n\t\tEditor = std::make_unique(&GetEngine(), this, &GetEngine().GetRenderer());\n\t\tEditorSceneManager = new EditorCore(Editor.get());\n\t\tNewSceneEvent evt;\n\t\tevt.Fire();\n\t\tGetEngine().GetWorld().lock()->AddCore(*EditorSceneManager);\n\t\tGetEngine().LoadScene(InitialLevel);\n\t}\n\telse\n\t{\n\t\tGetEngine().GetWorld().lock()->AddCore(*EditorSceneManager);\n\t}\n}\n\nvoid EditorApp::PostRender()\n{\n\tEditor->Render(GetEngine().EditorCamera);\n}\n\nvoid EditorApp::StartGame()\n{\n\tif (!m_isGameRunning)\n\t{\n\t\tGetEngine().GetWorld().lock()->Start();\n\t\tm_isGameRunning = true;\n\t}\n}\n\nvoid EditorApp::StopGame()\n{\n\tif (m_isGameRunning)\n\t{\n\t\tif (GetEngine().GetWorld().lock())\n\t\t{\n\t\t\tGetEngine().GetWorld().lock()->Destroy();\n\t\t}\n\t\tNewSceneEvent evt;\n\t\tevt.Fire();\n\t\tGetEngine().LoadScene(InitialLevel);\n\t\tGetEngine().GetWorld().lock()->Stop();\n\t\tm_isGameRunning = false;\n\t}\n}\n\nconst bool EditorApp::IsGameRunning() const\n{\n\treturn m_isGameRunning;\n}\n\nconst bool EditorApp::IsGamePaused() const\n{\n\treturn m_isGamePaused;\n}\n\nbool EditorApp::OnEvent(const BaseEvent& evt)\n{\n\tif (evt.GetEventId() == NewSceneEvent::GetEventId())\n\t{\n\t\tconst NewSceneEvent& test = static_cast(evt);\n\t\tGetEngine().LoadScene(\"\");\n\t\tGetEngine().InitGame();\n\t\tGetEngine().GetWorld().lock()->Simulate();\n\t}\n\telse if (evt.GetEventId() == SceneLoadedEvent::GetEventId())\n\t{\n\t\tconst SceneLoadedEvent& test = static_cast(evt);\n\n\t\tEditor->SetWindowTitle(\"Havana - \" + test.LoadedScene->FilePath.LocalPath);\n\t\tif (m_isGameRunning)\n\t\t{\n\t\t\tGetEngine().GetWorld().lock()->Start();\n\t\t}\n\t}\n\n\treturn false;\n}🛑 Fixing a bug when stopping the game and starting game systems#include \"EditorApp.h\"\n#include \"ECS\/Component.h\"\n#include \"Engine\/Clock.h\"\n#include \"Components\/Transform.h\"\n#include \"ECS\/Entity.h\"\n#include \n#include \"Engine\/Input.h\"\n#include \"Components\/Camera.h\"\n#include \"Components\/Physics\/Rigidbody.h\"\n#include \"Components\/Graphics\/Model.h\"\n#include \"Components\/Lighting\/Light.h\"\n\n#include \n#include \"Engine\/World.h\"\n#include \"Path.h\"\n#include \"Cores\/EditorCore.h\"\n#include \"Engine\/Engine.h\"\n#include \"Havana.h\"\n#include \"Cores\/SceneGraph.h\"\n#include \"Events\/SceneEvents.h\"\n#include \"RenderCommands.h\"\n#include \"Events\/Event.h\"\n#include \n#include \"Math\/Matirx4.h\"\n#include \"Math\/Frustrum.h\"\n\nEditorApp::EditorApp()\n{\n\tstd::vector events;\n\tevents.push_back(NewSceneEvent::GetEventId());\n\tevents.push_back(SceneLoadedEvent::GetEventId());\n\tEventManager::GetInstance().RegisterReceiver(this, events);\n\n}\n\nEditorApp::~EditorApp()\n{\n}\n\nvoid EditorApp::OnStart()\n{\n}\n\nvoid EditorApp::OnUpdate(float DeltaTime)\n{\n\tEditor->NewFrame([this]() {\n\t\tStartGame();\n\t\tm_isGamePaused = false;\n\t\tm_isGameRunning = true;\n\t\t}\n\t\t, [this]() {\n\t\t\tm_isGamePaused = true;\n\t\t}\n\t\t\t, [this]() {\n\t\t\tm_isGamePaused = false;\n\t\t\tEditor->ClearSelection();\n\t\t\tStopGame();\n\t\t\t\/\/GetEngine().LoadScene(\"Assets\/Alley.lvl\");\n\t\t});\n\n\tEditorSceneManager->Update(DeltaTime, GetEngine().SceneNodes->GetRootTransform());\n\n\tEditor->UpdateWorld(GetEngine().GetWorld().lock().get(), GetEngine().SceneNodes->GetRootTransform(), EditorSceneManager->GetEntities());\n\n\tUpdateCameras();\n}\n\nvoid EditorApp::UpdateCameras()\n{\n\tVector2 MainOutputSize = Editor->GetGameOutputSize();\n\n\tif (!Camera::CurrentCamera)\n\t{\n\t\tCamera::CurrentCamera = Camera::EditorCamera;\n\t}\n\n\tMoonlight::CameraData EditorCamera;\n\n\tCamera::CurrentCamera->OutputSize = MainOutputSize;\n\tEditorCamera.Position = EditorSceneManager->GetEditorCameraTransform()->GetWorldPosition();\n\tEditorCamera.Front = EditorSceneManager->GetEditorCameraTransform()->Front();\n\tEditorCamera.Up = Vector3::Up;\n\tEditorCamera.OutputSize = Editor->WorldViewRenderSize;\n\tEditorCamera.FOV = Camera::EditorCamera->GetFOV();\n\tEditorCamera.Near = Camera::EditorCamera->Near;\n\tEditorCamera.Far = Camera::EditorCamera->Far;\n\tEditorCamera.Skybox = Camera::CurrentCamera->Skybox;\n\tEditorCamera.ClearColor = Camera::CurrentCamera->ClearColor;\n\tEditorCamera.ClearType = Camera::CurrentCamera->ClearType;\n\tEditorCamera.Projection = Camera::EditorCamera->Projection;\n\tEditorCamera.OrthographicSize = Camera::EditorCamera->OrthographicSize;\n\tEditorCamera.CameraFrustum = Camera::EditorCamera->CameraFrustum;\n\n\tGetEngine().EditorCamera = EditorCamera;\n}\n\nvoid EditorApp::OnEnd()\n{\n\n\t\/\/destroy(mGame);\n}\n\nvoid EditorApp::OnInitialize()\n{\n\tif (!Editor)\n\t{\n\t\tInitialLevel = GetEngine().GetConfig().GetValue(\"CurrentScene\");\n\t\tEditor = std::make_unique(&GetEngine(), this, &GetEngine().GetRenderer());\n\t\tEditorSceneManager = new EditorCore(Editor.get());\n\t\tNewSceneEvent evt;\n\t\tevt.Fire();\n\t\tGetEngine().GetWorld().lock()->AddCore(*EditorSceneManager);\n\t\tGetEngine().LoadScene(InitialLevel);\n\t}\n\telse\n\t{\n\t\tGetEngine().GetWorld().lock()->AddCore(*EditorSceneManager);\n\t}\n}\n\nvoid EditorApp::PostRender()\n{\n\tEditor->Render(GetEngine().EditorCamera);\n}\n\nvoid EditorApp::StartGame()\n{\n\tif (!m_isGameRunning)\n\t{\n\t\tGetEngine().GetWorld().lock()->Start();\n\t\tm_isGameRunning = true;\n\t}\n}\n\nvoid EditorApp::StopGame()\n{\n\tif (m_isGameRunning)\n\t{\n\t\tif (GetEngine().GetWorld().lock())\n\t\t{\n\t\t\tGetEngine().GetWorld().lock()->Destroy();\n\t\t}\n\t\tm_isGameRunning = false;\n\t\tNewSceneEvent evt;\n\t\tevt.Fire();\n\t\tGetEngine().LoadScene(InitialLevel);\n\t\tGetEngine().GetWorld().lock()->Stop();\n\t}\n}\n\nconst bool EditorApp::IsGameRunning() const\n{\n\treturn m_isGameRunning;\n}\n\nconst bool EditorApp::IsGamePaused() const\n{\n\treturn m_isGamePaused;\n}\n\nbool EditorApp::OnEvent(const BaseEvent& evt)\n{\n\tif (evt.GetEventId() == NewSceneEvent::GetEventId())\n\t{\n\t\tconst NewSceneEvent& test = static_cast(evt);\n\t\tGetEngine().LoadScene(\"\");\n\t\tGetEngine().InitGame();\n\t\tGetEngine().GetWorld().lock()->Simulate();\n\t}\n\telse if (evt.GetEventId() == SceneLoadedEvent::GetEventId())\n\t{\n\t\tconst SceneLoadedEvent& test = static_cast(evt);\n\n\t\tEditor->SetWindowTitle(\"Havana - \" + test.LoadedScene->FilePath.LocalPath);\n\t\tif (m_isGameRunning)\n\t\t{\n\t\t\tGetEngine().GetWorld().lock()->Start();\n\t\t}\n\t}\n\n\treturn false;\n}<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"sortedtimelinemodel.h\"\nnamespace QmlProfiler {\n\n\/*!\n \\class QmlProfiler::SortedTimelineModel\n \\brief The SortedTimelineModel class provides a sorted model for timeline data.\n\n The SortedTimelineModel lets you keep range data sorted by both start and end times, so that\n visible ranges can easily be computed. The only precondition for that to work is that the ranges\n must be perfectly nested. A \"parent\" range of a range R is defined as a range for which the\n start time is smaller than R's start time and the end time is greater than R's end time. A set\n of ranges is perfectly nested if all parent ranges of any given range have a common parent\n range. Mind that you can always make that happen by defining a range that spans the whole\n available time span. That, however, will make any code that uses firstStartTime() and\n lastEndTime() for selecting subsets of the model always select all of it.\n\n \\note Indices returned from the various methods are only valid until a new range is inserted\n before them. Inserting a new range before a given index moves the range pointed to by the\n index by one. Incrementing the index by one will make it point to the item again.\n*\/\n\n\/*!\n \\fn SortedTimelineModel::clear()\n Clears the ranges and their end times.\n*\/\nvoid SortedTimelineModel::clear()\n{\n ranges.clear();\n endTimes.clear();\n}\n\n\/*!\n \\fn int SortedTimelineModel::count() const\n Returns the number of ranges in the model.\n*\/\n\n\/*!\n \\fn qint64 SortedTimelineModel::firstStartTime() const\n Returns the begin of the first range in the model.\n*\/\n\n\/*!\n \\fn qint64 SortedTimelineModel::lastEndTime() const\n Returns the end of the last range in the model.\n*\/\n\n\/*!\n \\fn const SortedTimelineModel::Range &SortedTimelineModel::range(int index) const\n Returns the range data at the specified index.\n*\/\n\n\/*!\n \\fn int SortedTimelineModel::insert(qint64 startTime, qint64 duration)\n Inserts a range at the given time position and returns its index.\n*\/\n\n\/*!\n \\fn int SortedTimelineModel::insertStart(qint64 startTime, const Data &item)\n Inserts the given data as range start at the given time position and\n returns its index. The range end is not set.\n*\/\n\n\/*!\n \\fn int SortedTimelineModel::insertEnd(int index, qint64 duration)\n Adds a range end for the given start index.\n*\/\n\n\/*!\n \\fn int SortedTimelineModel::firstIndexNoParents(qint64 startTime) const\n Looks up the first range with an end time greater than the given time and\n returns its index. If no such range is found, it returns -1.\n*\/\n\n\/*!\n \\fn int SortedTimelineModel::firstIndex(qint64 startTime) const\n Looks up the first range with an end time greater than the given time and\n returns its parent's index. If no such range is found, it returns -1. If there\n is no parent, it returns the found range's index. The parent of a range is the\n range with the lowest start time that completely covers the child range.\n \"Completely covers\" means:\n parent.startTime <= child.startTime && parent.endTime >= child.endTime\n*\/\n\n\/*!\n \\fn int SortedTimelineModel::lastIndex(qint64 endTime) const\n Looks up the last range with a start time smaller than the given time and\n returns its index. If no such range is found, it returns -1.\n*\/\n\n\/*!\n \\fn void SortedTimelineModel::computeNesting()\n Compute all ranges' parents.\n \\sa findFirstIndex\n*\/\nvoid SortedTimelineModel::computeNesting()\n{\n QLinkedList parents;\n for (int range = 0; range != count(); ++range) {\n Range ¤t = ranges[range];\n for (QLinkedList::iterator parentIt = parents.begin();;) {\n Range &parent = ranges[*parentIt];\n qint64 parentEnd = parent.start + parent.duration;\n if (parentEnd < current.start) {\n if (parent.start == current.start) {\n if (parent.parent == -1) {\n parent.parent = range;\n } else {\n Range &ancestor = ranges[parent.parent];\n if (ancestor.start == current.start &&\n ancestor.duration < current.duration)\n parent.parent = range;\n }\n \/\/ Just switch the old parent range for the new, larger one\n *parentIt = range;\n break;\n } else {\n parentIt = parents.erase(parentIt);\n }\n } else if (parentEnd >= current.start + current.duration) {\n \/\/ no need to insert\n current.parent = *parentIt;\n break;\n } else {\n ++parentIt;\n }\n\n if (parentIt == parents.end()) {\n parents.append(range);\n break;\n }\n }\n }\n}\n\n}\nQmlProfiler: Fix invalid list access when nesting timeline events\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"sortedtimelinemodel.h\"\nnamespace QmlProfiler {\n\n\/*!\n \\class QmlProfiler::SortedTimelineModel\n \\brief The SortedTimelineModel class provides a sorted model for timeline data.\n\n The SortedTimelineModel lets you keep range data sorted by both start and end times, so that\n visible ranges can easily be computed. The only precondition for that to work is that the ranges\n must be perfectly nested. A \"parent\" range of a range R is defined as a range for which the\n start time is smaller than R's start time and the end time is greater than R's end time. A set\n of ranges is perfectly nested if all parent ranges of any given range have a common parent\n range. Mind that you can always make that happen by defining a range that spans the whole\n available time span. That, however, will make any code that uses firstStartTime() and\n lastEndTime() for selecting subsets of the model always select all of it.\n\n \\note Indices returned from the various methods are only valid until a new range is inserted\n before them. Inserting a new range before a given index moves the range pointed to by the\n index by one. Incrementing the index by one will make it point to the item again.\n*\/\n\n\/*!\n \\fn SortedTimelineModel::clear()\n Clears the ranges and their end times.\n*\/\nvoid SortedTimelineModel::clear()\n{\n ranges.clear();\n endTimes.clear();\n}\n\n\/*!\n \\fn int SortedTimelineModel::count() const\n Returns the number of ranges in the model.\n*\/\n\n\/*!\n \\fn qint64 SortedTimelineModel::firstStartTime() const\n Returns the begin of the first range in the model.\n*\/\n\n\/*!\n \\fn qint64 SortedTimelineModel::lastEndTime() const\n Returns the end of the last range in the model.\n*\/\n\n\/*!\n \\fn const SortedTimelineModel::Range &SortedTimelineModel::range(int index) const\n Returns the range data at the specified index.\n*\/\n\n\/*!\n \\fn int SortedTimelineModel::insert(qint64 startTime, qint64 duration)\n Inserts a range at the given time position and returns its index.\n*\/\n\n\/*!\n \\fn int SortedTimelineModel::insertStart(qint64 startTime, const Data &item)\n Inserts the given data as range start at the given time position and\n returns its index. The range end is not set.\n*\/\n\n\/*!\n \\fn int SortedTimelineModel::insertEnd(int index, qint64 duration)\n Adds a range end for the given start index.\n*\/\n\n\/*!\n \\fn int SortedTimelineModel::firstIndexNoParents(qint64 startTime) const\n Looks up the first range with an end time greater than the given time and\n returns its index. If no such range is found, it returns -1.\n*\/\n\n\/*!\n \\fn int SortedTimelineModel::firstIndex(qint64 startTime) const\n Looks up the first range with an end time greater than the given time and\n returns its parent's index. If no such range is found, it returns -1. If there\n is no parent, it returns the found range's index. The parent of a range is the\n range with the lowest start time that completely covers the child range.\n \"Completely covers\" means:\n parent.startTime <= child.startTime && parent.endTime >= child.endTime\n*\/\n\n\/*!\n \\fn int SortedTimelineModel::lastIndex(qint64 endTime) const\n Looks up the last range with a start time smaller than the given time and\n returns its index. If no such range is found, it returns -1.\n*\/\n\n\/*!\n \\fn void SortedTimelineModel::computeNesting()\n Compute all ranges' parents.\n \\sa findFirstIndex\n*\/\nvoid SortedTimelineModel::computeNesting()\n{\n QLinkedList parents;\n for (int range = 0; range != count(); ++range) {\n Range ¤t = ranges[range];\n for (QLinkedList::iterator parentIt = parents.begin();;) {\n if (parentIt == parents.end()) {\n parents.append(range);\n break;\n }\n\n Range &parent = ranges[*parentIt];\n qint64 parentEnd = parent.start + parent.duration;\n if (parentEnd < current.start) {\n if (parent.start == current.start) {\n if (parent.parent == -1) {\n parent.parent = range;\n } else {\n Range &ancestor = ranges[parent.parent];\n if (ancestor.start == current.start &&\n ancestor.duration < current.duration)\n parent.parent = range;\n }\n \/\/ Just switch the old parent range for the new, larger one\n *parentIt = range;\n break;\n } else {\n parentIt = parents.erase(parentIt);\n }\n } else if (parentEnd >= current.start + current.duration) {\n \/\/ no need to insert\n current.parent = *parentIt;\n break;\n } else {\n ++parentIt;\n }\n }\n }\n}\n\n}\n<|endoftext|>"} {"text":"\/*\n * esteid-browser-plugin - a browser plugin for Estonian EID card\n *\n * Copyright (C) 2010 Estonian Informatics Centre\n * Copyright (C) 2010 Smartlink OÜ\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"pininputdialog.h\"\n#include \"basedialog.h\"\n#include \"utf8_tools.h\"\n\n#include \n#include \n#include \"Win\/pininputdialog_res.h\"\n\n#define BUF_SIZE 100\n\nPinInputDialog::PinInputDialog(HINSTANCE hInst)\n : BaseDialog(hInst),\n m_retry(false),\n m_triesLeft(0),\n m_minPinLength(5)\n{\n}\n\n\nPinInputDialog::~PinInputDialog()\n{\n}\n\n\nvoid PinInputDialog::showPinBlocked(HWND hParent)\n{\n MessageBox(hParent, L\"PIN2 blocked.\\nPlease run ID card Utility to unlock the PIN.\",\n L\"Error\", MB_OK | MB_ICONHAND);\n}\n\n\nvoid PinInputDialog::setSubject(const std::string& subject)\n{\n m_subject = FB::utf8_to_wstring(subject) + L\" (PIN2)\";\n}\n\n\nvoid PinInputDialog::setRetry(bool retry)\n{\n m_retry = retry;\n}\n\n\nvoid PinInputDialog::setTries(int tries)\n{\n m_triesLeft = tries;\n}\n\n\nstd::string PinInputDialog::getPinInternal()\n{\n char *buf = new char[BUF_SIZE];\n\n GetDlgItemTextA(m_hWnd, IDC_PINEDIT, buf, BUF_SIZE);\n\n std::string ret(buf);\n delete[] buf;\n\n return ret;\n}\n\n\nstd::string PinInputDialog::getPin()\n{\n return m_pin;\n}\n\n\nvoid PinInputDialog::clearPin()\n{\n m_pin = \"\";\n}\n\n\nHICON PinInputDialog::getCreduiIcon()\n{\n HMODULE module = LoadLibraryExA(\"credui.dll\", NULL, LOAD_LIBRARY_AS_DATAFILE);\n if (!module)\n return NULL;\n return LoadIcon(module, MAKEINTRESOURCE(1201));\n}\n\n\nHICON PinInputDialog::getIcon()\n{\n HICON icon = getCreduiIcon();\n if (!icon) \/\/ fall back to embedded icon\n icon = LoadIcon(m_hInst, MAKEINTRESOURCE(IDI_PINICON));\n return icon;\n}\n\n\nvoid PinInputDialog::setFontSize(HWND hText, int fontSize)\n{\n HFONT hOldFont = (HFONT)SendMessage(hText, WM_GETFONT, 0, 0);\n HDC hDC = GetDC(hText);\n LOGFONT lf;\n GetObject(hOldFont, sizeof(LOGFONT), &lf);\n lf.lfHeight = -MulDiv(fontSize, GetDeviceCaps(hDC, LOGPIXELSY), 72);\n HFONT hNewFont = CreateFontIndirect(&lf);\n SendMessage(hText, WM_SETFONT, (WPARAM)hNewFont, MAKELPARAM(TRUE, 0));\n ReleaseDC(hText, hDC);\n}\n\n\n\/\/ calculate control's width needed to fit text\nint PinInputDialog::preferredWidth(HWND hWnd, const std::wstring& text)\n{\n HDC hdc;\n SIZE size;\n\n hdc = GetDC(hWnd);\n GetTextExtentPoint32(hdc, text.c_str(), (int)text.size(), &size);\n ReleaseDC(hWnd, hdc);\n\n return size.cx;\n}\n\n\n\/\/ get control's current width\nint PinInputDialog::currentWidth(HWND hWnd)\n{\n RECT rect;\n POINT ptDiff;\n\n GetClientRect(hWnd, &rect);\n ptDiff.x = (rect.right - rect.left);\n ptDiff.y = (rect.bottom - rect.top);\n\n return ptDiff.x;\n}\n\n\nvoid PinInputDialog::resizeWindow(HWND hWnd, int width, int height)\n{\n RECT rect;\n POINT ptDiff;\n\n GetWindowRect(hWnd, &rect);\n ptDiff.x = (rect.right - rect.left);\n ptDiff.y = (rect.bottom - rect.top);\n\n MoveWindow(hWnd, rect.left, rect.top, ptDiff.x + width, ptDiff.y + height, TRUE);\n}\n\n\nvoid PinInputDialog::resizeControl(HWND hWnd, HWND hControl, int width, int height)\n{\n RECT rect;\n POINT point;\n\n GetWindowRect(hControl, &rect);\n point.x = rect.left;\n point.y = rect.top;\n ScreenToClient(hWnd, &point);\n GetClientRect(hControl, &rect);\n\n MoveWindow(hControl, point.x, point.y, (rect.right - rect.left) + width, (rect.bottom - rect.top) + height, TRUE);\n}\n\n\nvoid PinInputDialog::moveControl(HWND hWnd, HWND hControl, int dx, int dy)\n{\n RECT rect;\n POINT point;\n\n GetWindowRect(hControl, &rect);\n point.x = rect.left;\n point.y = rect.top;\n ScreenToClient(hWnd, &point);\n GetClientRect(hControl, &rect);\n\n MoveWindow(hControl, point.x + dx, point.y + dy, rect.right - rect.left, rect.bottom - rect.top, TRUE);\n}\n\n\nvoid PinInputDialog::showWrongPin(HWND hParent, int tries)\n{\n static const std::wstring title = L\"Wrong PIN!\";\n std::wstringstream out;\n out << L\"Tries left: \" << m_triesLeft;\n std::wstring text = out.str();\n\n\/\/ mingw doesn't have EDITBALLOONTIP\n#ifdef EM_SHOWBALLOONTIP\n EDITBALLOONTIP ebt = {0};\n ebt.cbStruct = sizeof(EDITBALLOONTIP);\n ebt.pszTitle = const_cast(title.c_str());\n ebt.pszText = const_cast(text.c_str());\n ebt.ttiIcon = TTI_ERROR;\n if (!SendMessage(hParent, EM_SHOWBALLOONTIP, 0, (LPARAM)&ebt)) {\n#endif\n MessageBox(hParent, const_cast((title + L\"\\n\" + text).c_str()), L\"Warning\", MB_OK | MB_ICONHAND);\n#ifdef EM_SHOWBALLOONTIP\n }\n#endif\n}\n\n\nLRESULT PinInputDialog::on_initdialog(WPARAM wParam)\n{\n HWND hLabel = GetDlgItem(m_hWnd, IDC_LABEL);\n HWND hPinedit = GetDlgItem(m_hWnd, IDC_PINEDIT);\n\n SetDlgItemText(m_hWnd, IDC_LABEL, const_cast(m_subject.c_str()));\n\n setFontSize(hLabel, 10);\n\n \/\/ set icon\n HICON icon = getIcon();\n SendDlgItemMessage(m_hWnd, IDI_PINICON, STM_SETIMAGE, IMAGE_ICON, (LPARAM)icon);\n\n \/\/ set maximum pin length\n SendDlgItemMessage(m_hWnd, IDC_PINEDIT, EM_SETLIMITTEXT, 12, 0);\n\n \/\/ resize dialog to fit long names\n if (currentWidth(hLabel) < preferredWidth(hLabel, m_subject)) {\n int dx = preferredWidth(hLabel, m_subject) - currentWidth(hLabel);\n \/\/ for reasons unknown, the width of IDC_LABEL and IDC_PINEDIT differ a little bit\n int dx2 = preferredWidth(hLabel, m_subject) - currentWidth(hPinedit);\n\n resizeWindow(m_hWnd, dx, 0);\n resizeControl(m_hWnd, hLabel, dx, 0);\n resizeControl(m_hWnd, hPinedit, dx2, 0);\n moveControl(m_hWnd, GetDlgItem(m_hWnd, IDOK), dx, 0);\n moveControl(m_hWnd, GetDlgItem(m_hWnd, IDCANCEL), dx, 0);\n }\n\n if (m_retry)\n showWrongPin(hPinedit, m_triesLeft);\n\n if (GetDlgCtrlID((HWND) wParam) != IDC_PINEDIT) {\n SetFocus(hPinedit);\n return FALSE;\n }\n\n return TRUE;\n}\n\n\nLRESULT PinInputDialog::on_command(WPARAM wParam, LPARAM lParam)\n{\n switch (LOWORD(wParam)) {\n\n case IDC_PINEDIT:\n if (HIWORD(wParam) == EN_CHANGE) {\n std::string pin = getPinInternal();\n if (pin.size() >= m_minPinLength)\n EnableWindow(GetDlgItem(m_hWnd, IDOK), TRUE);\n else\n EnableWindow(GetDlgItem(m_hWnd, IDOK), FALSE);\n }\n break;\n\n case IDOK:\n m_pin = getPinInternal();\n SetDlgItemTextA(m_hWnd, IDC_PINEDIT, \"\");\n\n if (m_modalDialog) {\n EndDialog(m_hWnd, wParam);\n } else {\n DestroyWindow(m_hWnd);\n releaseIEModalLock();\n signalResponse(RESPONSE_OK);\n }\n return TRUE;\n break;\n\n case IDCANCEL:\n m_pin = \"\";\n SetDlgItemTextA(m_hWnd, IDC_PINEDIT, \"\");\n\n if (m_modalDialog) {\n EndDialog(m_hWnd, wParam);\n } else {\n DestroyWindow(m_hWnd);\n releaseIEModalLock();\n signalResponse(RESPONSE_CANCEL);\n }\n return TRUE;\n break;\n }\n\n return FALSE;\n}\n\n\nbool PinInputDialog::doDialog(HWND hParent)\n{\n return BaseDialog::doDialog(IDD_PINDIALOG, hParent);\n}\n\nint PinInputDialog::doModalDialog(HWND hParent)\n{\n int rv = BaseDialog::doModalDialog(IDD_PINDIALOG, hParent);\n if (rv == IDOK)\n return RESPONSE_OK;\n else\n return RESPONSE_CANCEL;\n}\nesteid-browser-plugin: Use boost::lexical_cast for readability\/*\n * esteid-browser-plugin - a browser plugin for Estonian EID card\n *\n * Copyright (C) 2010 Estonian Informatics Centre\n * Copyright (C) 2010 Smartlink OÜ\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"pininputdialog.h\"\n#include \"basedialog.h\"\n#include \"utf8_tools.h\"\n\n#include \n#include \n#include \n#include \"Win\/pininputdialog_res.h\"\n\n#define BUF_SIZE 100\n\nPinInputDialog::PinInputDialog(HINSTANCE hInst)\n : BaseDialog(hInst),\n m_retry(false),\n m_triesLeft(0),\n m_minPinLength(5)\n{\n}\n\n\nPinInputDialog::~PinInputDialog()\n{\n}\n\n\nvoid PinInputDialog::showPinBlocked(HWND hParent)\n{\n MessageBox(hParent, L\"PIN2 blocked.\\nPlease run ID card Utility to unlock the PIN.\",\n L\"Error\", MB_OK | MB_ICONHAND);\n}\n\n\nvoid PinInputDialog::setSubject(const std::string& subject)\n{\n m_subject = FB::utf8_to_wstring(subject) + L\" (PIN2)\";\n}\n\n\nvoid PinInputDialog::setRetry(bool retry)\n{\n m_retry = retry;\n}\n\n\nvoid PinInputDialog::setTries(int tries)\n{\n m_triesLeft = tries;\n}\n\n\nstd::string PinInputDialog::getPinInternal()\n{\n char *buf = new char[BUF_SIZE];\n\n GetDlgItemTextA(m_hWnd, IDC_PINEDIT, buf, BUF_SIZE);\n\n std::string ret(buf);\n delete[] buf;\n\n return ret;\n}\n\n\nstd::string PinInputDialog::getPin()\n{\n return m_pin;\n}\n\n\nvoid PinInputDialog::clearPin()\n{\n m_pin = \"\";\n}\n\n\nHICON PinInputDialog::getCreduiIcon()\n{\n HMODULE module = LoadLibraryExA(\"credui.dll\", NULL, LOAD_LIBRARY_AS_DATAFILE);\n if (!module)\n return NULL;\n return LoadIcon(module, MAKEINTRESOURCE(1201));\n}\n\n\nHICON PinInputDialog::getIcon()\n{\n HICON icon = getCreduiIcon();\n if (!icon) \/\/ fall back to embedded icon\n icon = LoadIcon(m_hInst, MAKEINTRESOURCE(IDI_PINICON));\n return icon;\n}\n\n\nvoid PinInputDialog::setFontSize(HWND hText, int fontSize)\n{\n HFONT hOldFont = (HFONT)SendMessage(hText, WM_GETFONT, 0, 0);\n HDC hDC = GetDC(hText);\n LOGFONT lf;\n GetObject(hOldFont, sizeof(LOGFONT), &lf);\n lf.lfHeight = -MulDiv(fontSize, GetDeviceCaps(hDC, LOGPIXELSY), 72);\n HFONT hNewFont = CreateFontIndirect(&lf);\n SendMessage(hText, WM_SETFONT, (WPARAM)hNewFont, MAKELPARAM(TRUE, 0));\n ReleaseDC(hText, hDC);\n}\n\n\n\/\/ calculate control's width needed to fit text\nint PinInputDialog::preferredWidth(HWND hWnd, const std::wstring& text)\n{\n HDC hdc;\n SIZE size;\n\n hdc = GetDC(hWnd);\n GetTextExtentPoint32(hdc, text.c_str(), (int)text.size(), &size);\n ReleaseDC(hWnd, hdc);\n\n return size.cx;\n}\n\n\n\/\/ get control's current width\nint PinInputDialog::currentWidth(HWND hWnd)\n{\n RECT rect;\n POINT ptDiff;\n\n GetClientRect(hWnd, &rect);\n ptDiff.x = (rect.right - rect.left);\n ptDiff.y = (rect.bottom - rect.top);\n\n return ptDiff.x;\n}\n\n\nvoid PinInputDialog::resizeWindow(HWND hWnd, int width, int height)\n{\n RECT rect;\n POINT ptDiff;\n\n GetWindowRect(hWnd, &rect);\n ptDiff.x = (rect.right - rect.left);\n ptDiff.y = (rect.bottom - rect.top);\n\n MoveWindow(hWnd, rect.left, rect.top, ptDiff.x + width, ptDiff.y + height, TRUE);\n}\n\n\nvoid PinInputDialog::resizeControl(HWND hWnd, HWND hControl, int width, int height)\n{\n RECT rect;\n POINT point;\n\n GetWindowRect(hControl, &rect);\n point.x = rect.left;\n point.y = rect.top;\n ScreenToClient(hWnd, &point);\n GetClientRect(hControl, &rect);\n\n MoveWindow(hControl, point.x, point.y, (rect.right - rect.left) + width, (rect.bottom - rect.top) + height, TRUE);\n}\n\n\nvoid PinInputDialog::moveControl(HWND hWnd, HWND hControl, int dx, int dy)\n{\n RECT rect;\n POINT point;\n\n GetWindowRect(hControl, &rect);\n point.x = rect.left;\n point.y = rect.top;\n ScreenToClient(hWnd, &point);\n GetClientRect(hControl, &rect);\n\n MoveWindow(hControl, point.x + dx, point.y + dy, rect.right - rect.left, rect.bottom - rect.top, TRUE);\n}\n\n\nvoid PinInputDialog::showWrongPin(HWND hParent, int tries)\n{\n static const std::wstring title = L\"Wrong PIN!\";\n std::wstring text(L\"Tries left: \" + boost::lexical_cast(tries));\n\n\/\/ mingw doesn't have EDITBALLOONTIP\n#ifdef EM_SHOWBALLOONTIP\n EDITBALLOONTIP ebt = {0};\n ebt.cbStruct = sizeof(EDITBALLOONTIP);\n ebt.pszTitle = const_cast(title.c_str());\n ebt.pszText = const_cast(text.c_str());\n ebt.ttiIcon = TTI_ERROR;\n if (!SendMessage(hParent, EM_SHOWBALLOONTIP, 0, (LPARAM)&ebt)) {\n#endif\n MessageBox(hParent, const_cast((title + L\"\\n\" + text).c_str()), L\"Warning\", MB_OK | MB_ICONHAND);\n#ifdef EM_SHOWBALLOONTIP\n }\n#endif\n}\n\n\nLRESULT PinInputDialog::on_initdialog(WPARAM wParam)\n{\n HWND hLabel = GetDlgItem(m_hWnd, IDC_LABEL);\n HWND hPinedit = GetDlgItem(m_hWnd, IDC_PINEDIT);\n\n SetDlgItemText(m_hWnd, IDC_LABEL, const_cast(m_subject.c_str()));\n\n setFontSize(hLabel, 10);\n\n \/\/ set icon\n HICON icon = getIcon();\n SendDlgItemMessage(m_hWnd, IDI_PINICON, STM_SETIMAGE, IMAGE_ICON, (LPARAM)icon);\n\n \/\/ set maximum pin length\n SendDlgItemMessage(m_hWnd, IDC_PINEDIT, EM_SETLIMITTEXT, 12, 0);\n\n \/\/ resize dialog to fit long names\n if (currentWidth(hLabel) < preferredWidth(hLabel, m_subject)) {\n int dx = preferredWidth(hLabel, m_subject) - currentWidth(hLabel);\n \/\/ for reasons unknown, the width of IDC_LABEL and IDC_PINEDIT differ a little bit\n int dx2 = preferredWidth(hLabel, m_subject) - currentWidth(hPinedit);\n\n resizeWindow(m_hWnd, dx, 0);\n resizeControl(m_hWnd, hLabel, dx, 0);\n resizeControl(m_hWnd, hPinedit, dx2, 0);\n moveControl(m_hWnd, GetDlgItem(m_hWnd, IDOK), dx, 0);\n moveControl(m_hWnd, GetDlgItem(m_hWnd, IDCANCEL), dx, 0);\n }\n\n if (m_retry)\n showWrongPin(hPinedit, m_triesLeft);\n\n if (GetDlgCtrlID((HWND) wParam) != IDC_PINEDIT) {\n SetFocus(hPinedit);\n return FALSE;\n }\n\n return TRUE;\n}\n\n\nLRESULT PinInputDialog::on_command(WPARAM wParam, LPARAM lParam)\n{\n switch (LOWORD(wParam)) {\n\n case IDC_PINEDIT:\n if (HIWORD(wParam) == EN_CHANGE) {\n std::string pin = getPinInternal();\n if (pin.size() >= m_minPinLength)\n EnableWindow(GetDlgItem(m_hWnd, IDOK), TRUE);\n else\n EnableWindow(GetDlgItem(m_hWnd, IDOK), FALSE);\n }\n break;\n\n case IDOK:\n m_pin = getPinInternal();\n SetDlgItemTextA(m_hWnd, IDC_PINEDIT, \"\");\n\n if (m_modalDialog) {\n EndDialog(m_hWnd, wParam);\n } else {\n DestroyWindow(m_hWnd);\n releaseIEModalLock();\n signalResponse(RESPONSE_OK);\n }\n return TRUE;\n break;\n\n case IDCANCEL:\n m_pin = \"\";\n SetDlgItemTextA(m_hWnd, IDC_PINEDIT, \"\");\n\n if (m_modalDialog) {\n EndDialog(m_hWnd, wParam);\n } else {\n DestroyWindow(m_hWnd);\n releaseIEModalLock();\n signalResponse(RESPONSE_CANCEL);\n }\n return TRUE;\n break;\n }\n\n return FALSE;\n}\n\n\nbool PinInputDialog::doDialog(HWND hParent)\n{\n return BaseDialog::doDialog(IDD_PINDIALOG, hParent);\n}\n\nint PinInputDialog::doModalDialog(HWND hParent)\n{\n int rv = BaseDialog::doModalDialog(IDD_PINDIALOG, hParent);\n if (rv == IDOK)\n return RESPONSE_OK;\n else\n return RESPONSE_CANCEL;\n}\n<|endoftext|>"} {"text":"`typedef struct` -> `typedef struct KeyAndCallbackStruct`.<|endoftext|>"} {"text":"\/* Copyright 2016 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow_serving\/servables\/tensorflow\/bundle_factory_util.h\"\n\n#include \"google\/protobuf\/wrappers.pb.h\"\n#include \"tensorflow\/core\/kernels\/batching_util\/batch_scheduler.h\"\n#include \"tensorflow\/core\/lib\/core\/errors.h\"\n#include \"tensorflow\/core\/lib\/io\/path.h\"\n#include \"tensorflow\/core\/platform\/env.h\"\n#include \"tensorflow\/core\/platform\/types.h\"\n#include \"tensorflow_serving\/resources\/resource_values.h\"\n#include \"tensorflow_serving\/servables\/tensorflow\/serving_session.h\"\n\nnamespace tensorflow {\nnamespace serving {\n\nnamespace {\n\nusing Batcher = SharedBatchScheduler;\n\n\/\/ Constants used in the resource estimation heuristic. See the documentation\n\/\/ on EstimateResourceFromPath().\nconstexpr double kResourceEstimateRAMMultiplier = 1.2;\nconstexpr int kResourceEstimateRAMPadBytes = 0;\n\n\/\/ Returns all the descendants, both directories and files, recursively under\n\/\/ 'dirname'. The paths returned are all prefixed with 'dirname'.\nStatus GetAllDescendants(const string& dirname, FileProbingEnv* env,\n std::vector* const descendants) {\n descendants->clear();\n \/\/ Make sure that dirname exists;\n TF_RETURN_IF_ERROR(env->FileExists(dirname));\n std::deque dir_q; \/\/ Queue for the BFS\n std::vector dir_list; \/\/ List of all dirs discovered\n dir_q.push_back(dirname);\n Status ret; \/\/ Status to be returned.\n \/\/ Do a BFS on the directory to discover all immediate children.\n while (!dir_q.empty()) {\n string dir = dir_q.front();\n dir_q.pop_front();\n std::vector children;\n \/\/ GetChildren might fail if we don't have appropriate permissions.\n TF_RETURN_IF_ERROR(env->GetChildren(dir, &children));\n for (const string& child : children) {\n const string child_path = io::JoinPath(dir, child);\n descendants->push_back(child_path);\n \/\/ If the child is a directory add it to the queue.\n if (env->IsDirectory(child_path).ok()) {\n dir_q.push_back(child_path);\n }\n }\n }\n return Status::OK();\n}\n\n} \/\/ namespace\n\nSessionOptions GetSessionOptions(const SessionBundleConfig& config) {\n SessionOptions options;\n options.target = config.session_target();\n options.config = config.session_config();\n return options;\n}\n\nRunOptions GetRunOptions(const SessionBundleConfig& config) {\n RunOptions run_options;\n if (config.has_session_run_load_threadpool_index()) {\n run_options.set_inter_op_thread_pool(\n config.session_run_load_threadpool_index().value());\n }\n return run_options;\n}\n\nStatus CreateBatchScheduler(const BatchingParameters& batching_config,\n std::shared_ptr* batch_scheduler) {\n if (!batching_config.allowed_batch_sizes().empty()) {\n \/\/ Verify that the last allowed batch size matches the max batch size.\n const int last_allowed_size = batching_config.allowed_batch_sizes(\n batching_config.allowed_batch_sizes().size() - 1);\n const int max_size = batching_config.has_max_batch_size()\n ? batching_config.max_batch_size().value()\n : Batcher::QueueOptions().max_batch_size;\n if (last_allowed_size != max_size) {\n return errors::InvalidArgument(\n \"Last entry in allowed_batch_sizes must match max_batch_size; last \"\n \"entry was \",\n last_allowed_size, \"; expected \", max_size);\n }\n }\n\n Batcher::Options options;\n if (batching_config.has_num_batch_threads()) {\n options.num_batch_threads = batching_config.num_batch_threads().value();\n }\n if (batching_config.has_thread_pool_name()) {\n options.thread_pool_name = batching_config.thread_pool_name().value();\n }\n return Batcher::Create(options, batch_scheduler);\n}\n\nStatus EstimateResourceFromPath(const string& path,\n ResourceAllocation* estimate) {\n TensorflowFileProbingEnv env(Env::Default());\n return EstimateResourceFromPath(path, &env, estimate);\n}\n\nStatus EstimateResourceFromPath(const string& path, FileProbingEnv* env,\n ResourceAllocation* estimate) {\n if (env == nullptr) {\n return errors::Internal(\"FileProbingEnv not set\");\n }\n\n std::vector descendants;\n TF_RETURN_IF_ERROR(GetAllDescendants(path, env, &descendants));\n uint64 total_file_size = 0;\n for (const string& descendant : descendants) {\n if (!(env->IsDirectory(descendant).ok())) {\n uint64 file_size;\n TF_RETURN_IF_ERROR(env->GetFileSize(descendant, &file_size));\n total_file_size += file_size;\n }\n }\n const uint64 ram_requirement =\n total_file_size * kResourceEstimateRAMMultiplier +\n kResourceEstimateRAMPadBytes;\n\n ResourceAllocation::Entry* ram_entry = estimate->add_resource_quantities();\n Resource* ram_resource = ram_entry->mutable_resource();\n ram_resource->set_device(device_types::kMain);\n ram_resource->set_kind(resource_kinds::kRamBytes);\n ram_entry->set_quantity(ram_requirement);\n\n return Status::OK();\n}\n\nStatus WrapSessionForBatching(const BatchingParameters& batching_config,\n std::shared_ptr batch_scheduler,\n const std::vector& signatures,\n std::unique_ptr* session) {\n LOG(INFO) << \"Wrapping session to perform batch processing\";\n\n if (batch_scheduler == nullptr) {\n return errors::Internal(\"batch_scheduler not set\");\n }\n if (*session == nullptr) {\n return errors::Internal(\"session not set\");\n }\n\n Batcher::QueueOptions queue_options;\n if (batching_config.has_max_batch_size()) {\n queue_options.max_batch_size = batching_config.max_batch_size().value();\n }\n if (batching_config.has_batch_timeout_micros()) {\n queue_options.batch_timeout_micros =\n batching_config.batch_timeout_micros().value();\n }\n if (batching_config.has_max_enqueued_batches()) {\n queue_options.max_enqueued_batches =\n batching_config.max_enqueued_batches().value();\n }\n\n BatchingSessionOptions batching_session_options;\n for (int allowed_batch_size : batching_config.allowed_batch_sizes()) {\n batching_session_options.allowed_batch_sizes.push_back(allowed_batch_size);\n }\n\n batching_session_options.pad_variable_length_inputs =\n batching_config.pad_variable_length_inputs();\n\n auto create_queue = [batch_scheduler, queue_options](\n std::function>)>\n process_batch_callback,\n std::unique_ptr>* queue) {\n TF_RETURN_IF_ERROR(batch_scheduler->AddQueue(\n queue_options, process_batch_callback, queue));\n return Status::OK();\n };\n std::vector\n signatures_with_scheduler_creators;\n for (const SignatureDef& signature : signatures) {\n const TensorSignature tensor_signature =\n TensorSignatureFromSignatureDef(signature);\n signatures_with_scheduler_creators.push_back(\n {tensor_signature, create_queue});\n }\n\n return CreateBatchingSession(batching_session_options,\n signatures_with_scheduler_creators,\n std::move(*session), session);\n}\n\nStatus WrapSession(std::unique_ptr* session) {\n session->reset(new ServingSessionWrapper(std::move(*session)));\n return Status::OK();\n}\n\n} \/\/ namespace serving\n} \/\/ namespace tensorflow\nIn shared batch scheduler, rename 'max_batch_size' to 'input_batch_size_limit'.\/* Copyright 2016 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow_serving\/servables\/tensorflow\/bundle_factory_util.h\"\n\n#include \"google\/protobuf\/wrappers.pb.h\"\n#include \"tensorflow\/core\/kernels\/batching_util\/batch_scheduler.h\"\n#include \"tensorflow\/core\/lib\/core\/errors.h\"\n#include \"tensorflow\/core\/lib\/io\/path.h\"\n#include \"tensorflow\/core\/platform\/env.h\"\n#include \"tensorflow\/core\/platform\/types.h\"\n#include \"tensorflow_serving\/resources\/resource_values.h\"\n#include \"tensorflow_serving\/servables\/tensorflow\/serving_session.h\"\n\nnamespace tensorflow {\nnamespace serving {\n\nnamespace {\n\nusing Batcher = SharedBatchScheduler;\n\n\/\/ Constants used in the resource estimation heuristic. See the documentation\n\/\/ on EstimateResourceFromPath().\nconstexpr double kResourceEstimateRAMMultiplier = 1.2;\nconstexpr int kResourceEstimateRAMPadBytes = 0;\n\n\/\/ Returns all the descendants, both directories and files, recursively under\n\/\/ 'dirname'. The paths returned are all prefixed with 'dirname'.\nStatus GetAllDescendants(const string& dirname, FileProbingEnv* env,\n std::vector* const descendants) {\n descendants->clear();\n \/\/ Make sure that dirname exists;\n TF_RETURN_IF_ERROR(env->FileExists(dirname));\n std::deque dir_q; \/\/ Queue for the BFS\n std::vector dir_list; \/\/ List of all dirs discovered\n dir_q.push_back(dirname);\n Status ret; \/\/ Status to be returned.\n \/\/ Do a BFS on the directory to discover all immediate children.\n while (!dir_q.empty()) {\n string dir = dir_q.front();\n dir_q.pop_front();\n std::vector children;\n \/\/ GetChildren might fail if we don't have appropriate permissions.\n TF_RETURN_IF_ERROR(env->GetChildren(dir, &children));\n for (const string& child : children) {\n const string child_path = io::JoinPath(dir, child);\n descendants->push_back(child_path);\n \/\/ If the child is a directory add it to the queue.\n if (env->IsDirectory(child_path).ok()) {\n dir_q.push_back(child_path);\n }\n }\n }\n return Status::OK();\n}\n\n} \/\/ namespace\n\nSessionOptions GetSessionOptions(const SessionBundleConfig& config) {\n SessionOptions options;\n options.target = config.session_target();\n options.config = config.session_config();\n return options;\n}\n\nRunOptions GetRunOptions(const SessionBundleConfig& config) {\n RunOptions run_options;\n if (config.has_session_run_load_threadpool_index()) {\n run_options.set_inter_op_thread_pool(\n config.session_run_load_threadpool_index().value());\n }\n return run_options;\n}\n\nStatus CreateBatchScheduler(const BatchingParameters& batching_config,\n std::shared_ptr* batch_scheduler) {\n if (!batching_config.allowed_batch_sizes().empty()) {\n \/\/ Verify that the last allowed batch size matches the max batch size.\n const int last_allowed_size = batching_config.allowed_batch_sizes(\n batching_config.allowed_batch_sizes().size() - 1);\n const int max_size = batching_config.has_max_batch_size()\n ? batching_config.max_batch_size().value()\n : Batcher::QueueOptions().input_batch_size_limit;\n if (last_allowed_size != max_size) {\n return errors::InvalidArgument(\n \"Last entry in allowed_batch_sizes must match max_batch_size; last \"\n \"entry was \",\n last_allowed_size, \"; expected \", max_size);\n }\n }\n\n Batcher::Options options;\n if (batching_config.has_num_batch_threads()) {\n options.num_batch_threads = batching_config.num_batch_threads().value();\n }\n if (batching_config.has_thread_pool_name()) {\n options.thread_pool_name = batching_config.thread_pool_name().value();\n }\n return Batcher::Create(options, batch_scheduler);\n}\n\nStatus EstimateResourceFromPath(const string& path,\n ResourceAllocation* estimate) {\n TensorflowFileProbingEnv env(Env::Default());\n return EstimateResourceFromPath(path, &env, estimate);\n}\n\nStatus EstimateResourceFromPath(const string& path, FileProbingEnv* env,\n ResourceAllocation* estimate) {\n if (env == nullptr) {\n return errors::Internal(\"FileProbingEnv not set\");\n }\n\n std::vector descendants;\n TF_RETURN_IF_ERROR(GetAllDescendants(path, env, &descendants));\n uint64 total_file_size = 0;\n for (const string& descendant : descendants) {\n if (!(env->IsDirectory(descendant).ok())) {\n uint64 file_size;\n TF_RETURN_IF_ERROR(env->GetFileSize(descendant, &file_size));\n total_file_size += file_size;\n }\n }\n const uint64 ram_requirement =\n total_file_size * kResourceEstimateRAMMultiplier +\n kResourceEstimateRAMPadBytes;\n\n ResourceAllocation::Entry* ram_entry = estimate->add_resource_quantities();\n Resource* ram_resource = ram_entry->mutable_resource();\n ram_resource->set_device(device_types::kMain);\n ram_resource->set_kind(resource_kinds::kRamBytes);\n ram_entry->set_quantity(ram_requirement);\n\n return Status::OK();\n}\n\nStatus WrapSessionForBatching(const BatchingParameters& batching_config,\n std::shared_ptr batch_scheduler,\n const std::vector& signatures,\n std::unique_ptr* session) {\n LOG(INFO) << \"Wrapping session to perform batch processing\";\n\n if (batch_scheduler == nullptr) {\n return errors::Internal(\"batch_scheduler not set\");\n }\n if (*session == nullptr) {\n return errors::Internal(\"session not set\");\n }\n\n Batcher::QueueOptions queue_options;\n if (batching_config.has_max_batch_size()) {\n queue_options.input_batch_size_limit =\n batching_config.max_batch_size().value();\n }\n if (batching_config.has_batch_timeout_micros()) {\n queue_options.batch_timeout_micros =\n batching_config.batch_timeout_micros().value();\n }\n if (batching_config.has_max_enqueued_batches()) {\n queue_options.max_enqueued_batches =\n batching_config.max_enqueued_batches().value();\n }\n\n BatchingSessionOptions batching_session_options;\n for (int allowed_batch_size : batching_config.allowed_batch_sizes()) {\n batching_session_options.allowed_batch_sizes.push_back(allowed_batch_size);\n }\n\n batching_session_options.pad_variable_length_inputs =\n batching_config.pad_variable_length_inputs();\n\n auto create_queue = [batch_scheduler, queue_options](\n std::function>)>\n process_batch_callback,\n std::unique_ptr>* queue) {\n TF_RETURN_IF_ERROR(batch_scheduler->AddQueue(\n queue_options, process_batch_callback, queue));\n return Status::OK();\n };\n std::vector\n signatures_with_scheduler_creators;\n for (const SignatureDef& signature : signatures) {\n const TensorSignature tensor_signature =\n TensorSignatureFromSignatureDef(signature);\n signatures_with_scheduler_creators.push_back(\n {tensor_signature, create_queue});\n }\n\n return CreateBatchingSession(batching_session_options,\n signatures_with_scheduler_creators,\n std::move(*session), session);\n}\n\nStatus WrapSession(std::unique_ptr* session) {\n session->reset(new ServingSessionWrapper(std::move(*session)));\n return Status::OK();\n}\n\n} \/\/ namespace serving\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"#include \n#include \"commands\/HelpCommand.h\"\n#include \"commands\/LsCommand.h\"\n#include \"commands\/WatchCommand.h\"\n#include \"commands\/CdCommand.h\"\n#include \"commands\/ClearCommand.h\"\n#include \"commands\/LogCommand.h\"\n#include \"commands\/SyncCommand.h\"\n#include \"commands\/PlotCommand.h\"\n#include \"commands\/DiffCommand.h\"\n#include \"commands\/LoadCommand.h\"\n#include \"commands\/SaveCommand.h\"\n#include \"commands\/TreeCommand.h\"\n#include \"commands\/CatCommand.h\"\n#include \"commands\/RepeatCommand.h\"\n#include \"commands\/DelayCommand.h\"\n#include \"commands\/PadCommand.h\"\n#ifdef HAS_CURSES\n#include \"commands\/TuneCommand.h\"\n#endif\n#include \"Shell.h\"\n\nusing namespace RhIO;\n\nShell *shell = NULL;\n\nvoid shell_quit(int s)\n{\n (void) s;\n if (shell != NULL) {\n shell->quit();\n }\n exit(1);\n}\n\nint main(int argc, char *argv[])\n{\n signal(SIGINT, shell_quit);\n\n std::string server = \"localhost\";\n\n if (argc > 1) {\n server = std::string(argv[1]);\n }\n\n shell = new Shell(server);\n shell->registerCommand(new HelpCommand);\n shell->registerCommand(new LsCommand);\n shell->registerCommand(new CdCommand);\n shell->registerCommand(new ClearCommand);\n shell->registerCommand(new WatchCommand);\n shell->registerCommand(new LogCommand);\n shell->registerCommand(new SyncCommand);\n shell->registerCommand(new PlotCommand);\n shell->registerCommand(new DiffCommand);\n shell->registerCommand(new LoadCommand);\n shell->registerCommand(new SaveCommand);\n shell->registerCommand(new TreeCommand);\n shell->registerCommand(new CatCommand);\n shell->registerCommand(new RepeatCommand);\n shell->registerCommand(new DelayCommand);\n shell->registerCommand(new PadCommand);\n#ifdef HAS_CURSES\n shell->registerCommand(new TuneCommand);\n#endif\n\n shell->addAlias(\"ll\", \"ls\");\n\n if (argc > 2) {\n std::string args = \"\";\n for (int k=2; krun(args);\n } else {\n shell->run();\n }\n}\nAdding aliases#include \n#include \"commands\/HelpCommand.h\"\n#include \"commands\/LsCommand.h\"\n#include \"commands\/WatchCommand.h\"\n#include \"commands\/CdCommand.h\"\n#include \"commands\/ClearCommand.h\"\n#include \"commands\/LogCommand.h\"\n#include \"commands\/SyncCommand.h\"\n#include \"commands\/PlotCommand.h\"\n#include \"commands\/DiffCommand.h\"\n#include \"commands\/LoadCommand.h\"\n#include \"commands\/SaveCommand.h\"\n#include \"commands\/TreeCommand.h\"\n#include \"commands\/CatCommand.h\"\n#include \"commands\/RepeatCommand.h\"\n#include \"commands\/DelayCommand.h\"\n#include \"commands\/PadCommand.h\"\n#ifdef HAS_CURSES\n#include \"commands\/TuneCommand.h\"\n#endif\n#include \"Shell.h\"\n\nusing namespace RhIO;\n\nShell *shell = NULL;\n\nvoid shell_quit(int s)\n{\n (void) s;\n if (shell != NULL) {\n shell->quit();\n }\n exit(1);\n}\n\nint main(int argc, char *argv[])\n{\n signal(SIGINT, shell_quit);\n\n std::string server = \"localhost\";\n\n if (argc > 1) {\n server = std::string(argv[1]);\n }\n\n shell = new Shell(server);\n shell->registerCommand(new HelpCommand);\n shell->registerCommand(new LsCommand);\n shell->registerCommand(new CdCommand);\n shell->registerCommand(new ClearCommand);\n shell->registerCommand(new WatchCommand);\n shell->registerCommand(new LogCommand);\n shell->registerCommand(new SyncCommand);\n shell->registerCommand(new PlotCommand);\n shell->registerCommand(new DiffCommand);\n shell->registerCommand(new LoadCommand);\n shell->registerCommand(new SaveCommand);\n shell->registerCommand(new TreeCommand);\n shell->registerCommand(new CatCommand);\n shell->registerCommand(new RepeatCommand);\n shell->registerCommand(new DelayCommand);\n shell->registerCommand(new PadCommand);\n#ifdef HAS_CURSES\n shell->registerCommand(new TuneCommand);\n#endif\n\n shell->addAlias(\"ll\", \"ls\");\n shell->addAlias(\"rep\", \"repeat\");\n shell->addAlias(\"del\", \"delay\");\n\n if (argc > 2) {\n std::string args = \"\";\n for (int k=2; krun(args);\n } else {\n shell->run();\n }\n}\n<|endoftext|>"} {"text":"\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"Client.h\"\n#include \"ClientProtocol.h\"\n\nClient::Client() : zdb(0), selectedTable(0)\n{\n VERIFY(zlimdb_init() == 0);\n}\n\nClient::~Client()\n{\n disconnect();\n VERIFY(zlimdb_cleanup() == 0);\n}\n\nbool_t Client::connect(const String& user, const String& password, const String& address)\n{\n disconnect();\n\n \/\/ create connection\n zdb = zlimdb_create((void (*)(void*, const zlimdb_header*))(void (*)(void*, const void*))zlimdbCallback, this);\n if(!zdb)\n {\n error = getZlimdbError();\n return false;\n }\n uint16_t port = 0;\n String host = address;\n const char_t* colon = address.find(':');\n if(colon)\n {\n port = String::toUInt(colon + 1);\n host = address.substr(0, colon - (const char_t*)address);\n }\n if(zlimdb_connect(zdb, host, port, user, password) != 0)\n {\n error = getZlimdbError();\n return false;\n }\n\n \/\/ start receive thread\n keepRunning = true;\n if(!thread.start(threadProc, this))\n {\n error = Error::getErrorString();\n return false;\n }\n return true;\n}\n\nvoid_t Client::disconnect()\n{\n if(zdb)\n {\n keepRunning = false;\n zlimdb_interrupt(zdb);\n }\n thread.join();\n actions.clear();\n selectedTable = 0;\n}\n\nvoid_t Client::listUsers()\n{\n if(!zdb)\n return;\n actionMutex.lock();\n Action& action = actions.append(Action());\n action.type = listUsersAction;\n actionMutex.unlock();\n zlimdb_interrupt(zdb);\n}\n\nvoid_t Client::addUser(const String& userName, const String& password)\n{\n if(!zdb)\n return;\n actionMutex.lock();\n Action& action = actions.append(Action());\n action.type = addUserAction;\n action.param1 = userName;\n action.param2 = password;\n actionMutex.unlock();\n zlimdb_interrupt(zdb);\n}\n\nvoid_t Client::listTables()\n{\n if(!zdb)\n return;\n actionMutex.lock();\n Action& action = actions.append(Action());\n action.type = listTablesAction;\n actionMutex.unlock();\n zlimdb_interrupt(zdb);\n}\n\nvoid_t Client::createTable(const String& name)\n{\n if(!zdb)\n return;\n actionMutex.lock();\n Action& action = actions.append(Action());\n action.type = createTableAction;\n action.param1 = name;\n actionMutex.unlock();\n zlimdb_interrupt(zdb);\n}\n\nvoid_t Client::selectTable(uint32_t tableId)\n{\n if(!zdb)\n return;\n actionMutex.lock();\n Action& action = actions.append(Action());\n action.type = selectTableAction;\n action.param1 = tableId;\n actionMutex.unlock();\n zlimdb_interrupt(zdb);\n}\n\nvoid_t Client::query()\n{\n if(!zdb)\n return;\n actionMutex.lock();\n Action& action = actions.append(Action());\n action.type = queryAction;\n actionMutex.unlock();\n zlimdb_interrupt(zdb);\n}\n\nvoid_t Client::query(uint64_t sinceId)\n{\n if(!zdb)\n return;\n actionMutex.lock();\n Action& action = actions.append(Action());\n action.type = queryAction;\n action.param1 = sinceId;\n actionMutex.unlock();\n zlimdb_interrupt(zdb);\n}\n\nvoid_t Client::add(const String& value)\n{\n if(!zdb)\n return;\n actionMutex.lock();\n Action& action = actions.append(Action());\n action.type = addAction;\n action.param1 = value;\n actionMutex.unlock();\n zlimdb_interrupt(zdb);\n}\n\nvoid_t Client::subscribe()\n{\n if(!zdb)\n return;\n actionMutex.lock();\n Action& action = actions.append(Action());\n action.type = subscribeAction;\n actionMutex.unlock();\n zlimdb_interrupt(zdb);\n}\n\nvoid_t Client::sync()\n{\n if(!zdb)\n return;\n actionMutex.lock();\n Action& action = actions.append(Action());\n action.type = syncAction;\n actionMutex.unlock();\n zlimdb_interrupt(zdb);\n}\n\nuint_t Client::threadProc(void_t* param)\n{\n Client* client = (Client*)param;\n return client->process();;\n}\n\nuint8_t Client::process()\n{\n while(keepRunning && zlimdb_is_connected(zdb) == 0)\n if(zlimdb_exec(zdb, 5 * 60 * 1000) != 0)\n switch(zlimdb_errno())\n {\n case zlimdb_local_error_interrupted:\n {\n Action action = {quitAction};\n bool actionEmpty = true;\n do\n {\n actionMutex.lock();\n if(!actions.isEmpty())\n {\n action = actions.front();\n actions.removeFront();\n actionEmpty = actions.isEmpty();\n }\n actionMutex.unlock();\n handleAction(action);\n } while(!actionEmpty);\n }\n break;\n case zlimdb_local_error_timeout:\n break;\n default:\n Console::errorf(\"error: Could not receive data: %s\\n\", (const char_t*)getZlimdbError());\n return 1;\n }\n return 0;\n}\n\nvoid_t Client::handleAction(const Action& action)\n{\n switch(action.type)\n {\n case listUsersAction:\n {\n if(zlimdb_query(zdb, zlimdb_table_tables, zlimdb_query_type_all, 0) != 0)\n {\n Console::errorf(\"error: Could not send query: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n Buffer buffer;\n buffer.resize(0xffff);\n uint32_t size;\n while(zlimdb_get_response(zdb, (zlimdb_entity*)(byte_t*)buffer, buffer.size(), &size) == 0)\n {\n for(const zlimdb_table_entity* table = (const zlimdb_table_entity*)(const byte_t*)buffer, * end = (const zlimdb_table_entity*)((const byte_t*)table + size); table < end; table = (const zlimdb_table_entity*)((const byte_t*)table + table->entity.size))\n {\n String tableName;\n ClientProtocol::getString((const byte_t*)buffer, size, table->entity, sizeof(zlimdb_table_entity), table->name_size, tableName);\n if(!tableName.startsWith(\"users\/\"))\n continue;\n tableName.resize(tableName.length()); \/\/ enfore NULL termination\n Console::printf(\"%6llu: %s\\n\", table->entity.id, (const char_t*)File::basename(File::dirname(tableName)));\n }\n }\n if(zlimdb_errno() != zlimdb_local_error_none)\n {\n Console::errorf(\"error: Could not receive query response: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n }\n break;\n case addUserAction:\n {\n const String userName = action.param1.toString();\n const String password = action.param2.toString();\n if(zlimdb_add_user(zdb, userName, password) != 0)\n {\n Console::errorf(\"error: Could not send add user request: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n }\n break;\n case listTablesAction:\n {\n if(zlimdb_query(zdb, zlimdb_table_tables, zlimdb_query_type_all, 0) != 0)\n {\n Console::errorf(\"error: Could not send query: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n Buffer buffer;\n buffer.resize(0xffff);\n uint32_t size;\n while(zlimdb_get_response(zdb, (zlimdb_entity*)(byte_t*)buffer, buffer.size(), &size) == 0)\n {\n for(const zlimdb_table_entity* table = (const zlimdb_table_entity*)(const byte_t*)buffer, * end = (const zlimdb_table_entity*)((const byte_t*)table + size); table < end; table = (const zlimdb_table_entity*)((const byte_t*)table + table->entity.size))\n {\n String tableName;\n ClientProtocol::getString((const byte_t*)buffer, size, table->entity, sizeof(zlimdb_table_entity), table->name_size, tableName);\n tableName.resize(tableName.length()); \/\/ enfore NULL termination\n Console::printf(\"%6llu: %s\\n\", table->entity.id, (const char_t*)tableName);\n }\n }\n if(zlimdb_errno() != zlimdb_local_error_none)\n {\n Console::errorf(\"error: Could not receive query response: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n }\n break;\n case selectTableAction:\n selectedTable = action.param1.toUInt();\n \/\/Console::printf(\"selected table %u\\n\", action.param);\n break;\n case createTableAction:\n {\n const String tableName = action.param1.toString();\n uint32_t tableId;\n if(zlimdb_add_table(zdb, tableName, &tableId) != 0)\n {\n Console::errorf(\"error: Could not send add request: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n Console::printf(\"%6llu: %s\\n\", tableId, (const char_t*)tableName);\n }\n break;\n case queryAction:\n {\n zlimdb_query_type queryType = zlimdb_query_type_all;\n uint64_t param = 0;\n if(!action.param1.isNull())\n {\n queryType = zlimdb_query_type_since_id;\n param = action.param1.toUInt64();\n }\n if(zlimdb_query(zdb, selectedTable, queryType, param) != 0)\n {\n Console::errorf(\"error: Could not send query: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n Buffer buffer;\n buffer.resize(0xffff);\n uint32_t size;\n while(zlimdb_get_response(zdb, (zlimdb_entity*)(byte_t*)buffer, buffer.size(), &size) == 0)\n {\n for(const zlimdb_entity* entity = (const zlimdb_entity*)(const byte_t*)buffer, * end = (const zlimdb_entity*)((const byte_t*)entity + size); entity < end; entity = (const zlimdb_entity*)((const byte_t*)entity + entity->size))\n {\n Console::printf(\"id=%llu, size=%u, time=%llu\\n\", entity->id, (uint_t)entity->size, entity->time);\n }\n }\n if(zlimdb_errno() != zlimdb_local_error_none)\n {\n Console::errorf(\"error: Could not receive query response: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n }\n break;\n case subscribeAction:\n {\n if(zlimdb_subscribe(zdb, selectedTable, zlimdb_query_type_all, 0) != 0)\n {\n Console::errorf(\"error: Could not send subscribe request: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n Buffer buffer;\n buffer.resize(0xffff);\n uint32_t size;\n while(zlimdb_get_response(zdb, (zlimdb_entity*)(byte_t*)buffer, buffer.size(), &size) == 0)\n {\n for(const zlimdb_entity* entity = (const zlimdb_entity*)(const byte_t*)buffer, * end = (const zlimdb_entity*)((const byte_t*)entity + size); entity < end; entity = (const zlimdb_entity*)((const byte_t*)entity + entity->size))\n {\n Console::printf(\"id=%llu, size=%u, time=%llu\\n\", entity->id, (uint_t)entity->size, entity->time);\n }\n }\n if(zlimdb_errno() != zlimdb_local_error_none)\n {\n Console::errorf(\"error: Could not receive subscribe response: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n }\n break;\n case addAction:\n {\n const String value = action.param1.toString();\n Buffer buffer;\n buffer.resize(sizeof(zlimdb_table_entity) + value.length());\n zlimdb_table_entity* entity = (zlimdb_table_entity*)(const byte_t*)buffer;\n ClientProtocol::setEntityHeader(entity->entity, 0, Time::time(), sizeof(zlimdb_table_entity) + value.length());\n ClientProtocol::setString(entity->entity, entity->name_size, sizeof(*entity), value);\n if(zlimdb_add(zdb, selectedTable, &entity->entity))\n {\n Console::errorf(\"error: Could not send add request: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n }\n break;\n case syncAction:\n {\n timestamp_t serverTime, tableTime;\n if(zlimdb_sync(zdb, selectedTable, &serverTime, &tableTime))\n {\n Console::errorf(\"error: Could not send sync request: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n Console::printf(\"serverTime=%llu, tableTime=%llu\\n\", serverTime, tableTime);\n }\n break;\n case quitAction:\n break;\n }\n}\n\nvoid_t Client::zlimdbCallback(const void_t* data)\n{\n const zlimdb_header* header = (const zlimdb_header*)data;\n \/\/ todo: check sizes\n switch(header->message_type)\n {\n case zlimdb_message_error_response:\n {\n const zlimdb_error_response* errorResponse = (const zlimdb_error_response*)header;\n Console::printf(\"subscribe: errorResponse=%s (%d)\\n\", (const char_t*)getZlimdbError(), (int)errorResponse->error);\n }\n break;\n default:\n Console::printf(\"subscribe: messageType=%u\\n\", (uint_t)header->message_type);\n break;\n }\n}\n\nString Client::getZlimdbError()\n{\n int err = zlimdb_errno();\n if(err == zlimdb_local_error_system)\n return Error::getErrorString();\n else\n {\n const char* errstr = zlimdb_strerror(err);\n return String(errstr, String::length(errstr));\n }\n}\nFix create table command\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"Client.h\"\n#include \"ClientProtocol.h\"\n\nClient::Client() : zdb(0), selectedTable(0)\n{\n VERIFY(zlimdb_init() == 0);\n}\n\nClient::~Client()\n{\n disconnect();\n VERIFY(zlimdb_cleanup() == 0);\n}\n\nbool_t Client::connect(const String& user, const String& password, const String& address)\n{\n disconnect();\n\n \/\/ create connection\n zdb = zlimdb_create((void (*)(void*, const zlimdb_header*))(void (*)(void*, const void*))zlimdbCallback, this);\n if(!zdb)\n {\n error = getZlimdbError();\n return false;\n }\n uint16_t port = 0;\n String host = address;\n const char_t* colon = address.find(':');\n if(colon)\n {\n port = String::toUInt(colon + 1);\n host = address.substr(0, colon - (const char_t*)address);\n }\n if(zlimdb_connect(zdb, host, port, user, password) != 0)\n {\n error = getZlimdbError();\n return false;\n }\n\n \/\/ start receive thread\n keepRunning = true;\n if(!thread.start(threadProc, this))\n {\n error = Error::getErrorString();\n return false;\n }\n return true;\n}\n\nvoid_t Client::disconnect()\n{\n if(zdb)\n {\n keepRunning = false;\n zlimdb_interrupt(zdb);\n }\n thread.join();\n actions.clear();\n selectedTable = 0;\n}\n\nvoid_t Client::listUsers()\n{\n if(!zdb)\n return;\n actionMutex.lock();\n Action& action = actions.append(Action());\n action.type = listUsersAction;\n actionMutex.unlock();\n zlimdb_interrupt(zdb);\n}\n\nvoid_t Client::addUser(const String& userName, const String& password)\n{\n if(!zdb)\n return;\n actionMutex.lock();\n Action& action = actions.append(Action());\n action.type = addUserAction;\n action.param1 = userName;\n action.param2 = password;\n actionMutex.unlock();\n zlimdb_interrupt(zdb);\n}\n\nvoid_t Client::listTables()\n{\n if(!zdb)\n return;\n actionMutex.lock();\n Action& action = actions.append(Action());\n action.type = listTablesAction;\n actionMutex.unlock();\n zlimdb_interrupt(zdb);\n}\n\nvoid_t Client::createTable(const String& name)\n{\n if(!zdb)\n return;\n actionMutex.lock();\n Action& action = actions.append(Action());\n action.type = createTableAction;\n action.param1 = name;\n actionMutex.unlock();\n zlimdb_interrupt(zdb);\n}\n\nvoid_t Client::selectTable(uint32_t tableId)\n{\n if(!zdb)\n return;\n actionMutex.lock();\n Action& action = actions.append(Action());\n action.type = selectTableAction;\n action.param1 = tableId;\n actionMutex.unlock();\n zlimdb_interrupt(zdb);\n}\n\nvoid_t Client::query()\n{\n if(!zdb)\n return;\n actionMutex.lock();\n Action& action = actions.append(Action());\n action.type = queryAction;\n actionMutex.unlock();\n zlimdb_interrupt(zdb);\n}\n\nvoid_t Client::query(uint64_t sinceId)\n{\n if(!zdb)\n return;\n actionMutex.lock();\n Action& action = actions.append(Action());\n action.type = queryAction;\n action.param1 = sinceId;\n actionMutex.unlock();\n zlimdb_interrupt(zdb);\n}\n\nvoid_t Client::add(const String& value)\n{\n if(!zdb)\n return;\n actionMutex.lock();\n Action& action = actions.append(Action());\n action.type = addAction;\n action.param1 = value;\n actionMutex.unlock();\n zlimdb_interrupt(zdb);\n}\n\nvoid_t Client::subscribe()\n{\n if(!zdb)\n return;\n actionMutex.lock();\n Action& action = actions.append(Action());\n action.type = subscribeAction;\n actionMutex.unlock();\n zlimdb_interrupt(zdb);\n}\n\nvoid_t Client::sync()\n{\n if(!zdb)\n return;\n actionMutex.lock();\n Action& action = actions.append(Action());\n action.type = syncAction;\n actionMutex.unlock();\n zlimdb_interrupt(zdb);\n}\n\nuint_t Client::threadProc(void_t* param)\n{\n Client* client = (Client*)param;\n return client->process();;\n}\n\nuint8_t Client::process()\n{\n while(keepRunning && zlimdb_is_connected(zdb) == 0)\n if(zlimdb_exec(zdb, 5 * 60 * 1000) != 0)\n switch(zlimdb_errno())\n {\n case zlimdb_local_error_interrupted:\n {\n Action action = {quitAction};\n bool actionEmpty = true;\n do\n {\n actionMutex.lock();\n if(!actions.isEmpty())\n {\n action = actions.front();\n actions.removeFront();\n actionEmpty = actions.isEmpty();\n }\n actionMutex.unlock();\n handleAction(action);\n } while(!actionEmpty);\n }\n break;\n case zlimdb_local_error_timeout:\n break;\n default:\n Console::errorf(\"error: Could not receive data: %s\\n\", (const char_t*)getZlimdbError());\n return 1;\n }\n return 0;\n}\n\nvoid_t Client::handleAction(const Action& action)\n{\n switch(action.type)\n {\n case listUsersAction:\n {\n if(zlimdb_query(zdb, zlimdb_table_tables, zlimdb_query_type_all, 0) != 0)\n {\n Console::errorf(\"error: Could not send query: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n Buffer buffer;\n buffer.resize(0xffff);\n uint32_t size;\n while(zlimdb_get_response(zdb, (zlimdb_entity*)(byte_t*)buffer, buffer.size(), &size) == 0)\n {\n for(const zlimdb_table_entity* table = (const zlimdb_table_entity*)(const byte_t*)buffer, * end = (const zlimdb_table_entity*)((const byte_t*)table + size); table < end; table = (const zlimdb_table_entity*)((const byte_t*)table + table->entity.size))\n {\n String tableName;\n ClientProtocol::getString((const byte_t*)buffer, size, table->entity, sizeof(zlimdb_table_entity), table->name_size, tableName);\n if(!tableName.startsWith(\"users\/\"))\n continue;\n tableName.resize(tableName.length()); \/\/ enfore NULL termination\n Console::printf(\"%6llu: %s\\n\", table->entity.id, (const char_t*)File::basename(File::dirname(tableName)));\n }\n }\n if(zlimdb_errno() != zlimdb_local_error_none)\n {\n Console::errorf(\"error: Could not receive query response: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n }\n break;\n case addUserAction:\n {\n const String userName = action.param1.toString();\n const String password = action.param2.toString();\n if(zlimdb_add_user(zdb, userName, password) != 0)\n {\n Console::errorf(\"error: Could not send add user request: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n }\n break;\n case listTablesAction:\n {\n if(zlimdb_query(zdb, zlimdb_table_tables, zlimdb_query_type_all, 0) != 0)\n {\n Console::errorf(\"error: Could not send query: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n Buffer buffer;\n buffer.resize(0xffff);\n uint32_t size;\n while(zlimdb_get_response(zdb, (zlimdb_entity*)(byte_t*)buffer, buffer.size(), &size) == 0)\n {\n for(const zlimdb_table_entity* table = (const zlimdb_table_entity*)(const byte_t*)buffer, * end = (const zlimdb_table_entity*)((const byte_t*)table + size); table < end; table = (const zlimdb_table_entity*)((const byte_t*)table + table->entity.size))\n {\n String tableName;\n ClientProtocol::getString((const byte_t*)buffer, size, table->entity, sizeof(zlimdb_table_entity), table->name_size, tableName);\n tableName.resize(tableName.length()); \/\/ enfore NULL termination\n Console::printf(\"%6llu: %s\\n\", table->entity.id, (const char_t*)tableName);\n }\n }\n if(zlimdb_errno() != zlimdb_local_error_none)\n {\n Console::errorf(\"error: Could not receive query response: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n }\n break;\n case selectTableAction:\n selectedTable = action.param1.toUInt();\n \/\/Console::printf(\"selected table %u\\n\", action.param);\n break;\n case createTableAction:\n {\n const String tableName = action.param1.toString();\n uint32_t tableId;\n if(zlimdb_add_table(zdb, tableName, &tableId) != 0)\n {\n Console::errorf(\"error: Could not send add request: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n Console::printf(\"%6u: %s\\n\", tableId, (const char_t*)tableName);\n }\n break;\n case queryAction:\n {\n zlimdb_query_type queryType = zlimdb_query_type_all;\n uint64_t param = 0;\n if(!action.param1.isNull())\n {\n queryType = zlimdb_query_type_since_id;\n param = action.param1.toUInt64();\n }\n if(zlimdb_query(zdb, selectedTable, queryType, param) != 0)\n {\n Console::errorf(\"error: Could not send query: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n Buffer buffer;\n buffer.resize(0xffff);\n uint32_t size;\n while(zlimdb_get_response(zdb, (zlimdb_entity*)(byte_t*)buffer, buffer.size(), &size) == 0)\n {\n for(const zlimdb_entity* entity = (const zlimdb_entity*)(const byte_t*)buffer, * end = (const zlimdb_entity*)((const byte_t*)entity + size); entity < end; entity = (const zlimdb_entity*)((const byte_t*)entity + entity->size))\n {\n Console::printf(\"id=%llu, size=%u, time=%llu\\n\", entity->id, (uint_t)entity->size, entity->time);\n }\n }\n if(zlimdb_errno() != zlimdb_local_error_none)\n {\n Console::errorf(\"error: Could not receive query response: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n }\n break;\n case subscribeAction:\n {\n if(zlimdb_subscribe(zdb, selectedTable, zlimdb_query_type_all, 0) != 0)\n {\n Console::errorf(\"error: Could not send subscribe request: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n Buffer buffer;\n buffer.resize(0xffff);\n uint32_t size;\n while(zlimdb_get_response(zdb, (zlimdb_entity*)(byte_t*)buffer, buffer.size(), &size) == 0)\n {\n for(const zlimdb_entity* entity = (const zlimdb_entity*)(const byte_t*)buffer, * end = (const zlimdb_entity*)((const byte_t*)entity + size); entity < end; entity = (const zlimdb_entity*)((const byte_t*)entity + entity->size))\n {\n Console::printf(\"id=%llu, size=%u, time=%llu\\n\", entity->id, (uint_t)entity->size, entity->time);\n }\n }\n if(zlimdb_errno() != zlimdb_local_error_none)\n {\n Console::errorf(\"error: Could not receive subscribe response: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n }\n break;\n case addAction:\n {\n const String value = action.param1.toString();\n Buffer buffer;\n buffer.resize(sizeof(zlimdb_table_entity) + value.length());\n zlimdb_table_entity* entity = (zlimdb_table_entity*)(const byte_t*)buffer;\n ClientProtocol::setEntityHeader(entity->entity, 0, Time::time(), sizeof(zlimdb_table_entity) + value.length());\n ClientProtocol::setString(entity->entity, entity->name_size, sizeof(*entity), value);\n if(zlimdb_add(zdb, selectedTable, &entity->entity))\n {\n Console::errorf(\"error: Could not send add request: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n }\n break;\n case syncAction:\n {\n timestamp_t serverTime, tableTime;\n if(zlimdb_sync(zdb, selectedTable, &serverTime, &tableTime))\n {\n Console::errorf(\"error: Could not send sync request: %s\\n\", (const char_t*)getZlimdbError());\n return;\n }\n Console::printf(\"serverTime=%llu, tableTime=%llu\\n\", serverTime, tableTime);\n }\n break;\n case quitAction:\n break;\n }\n}\n\nvoid_t Client::zlimdbCallback(const void_t* data)\n{\n const zlimdb_header* header = (const zlimdb_header*)data;\n \/\/ todo: check sizes\n switch(header->message_type)\n {\n case zlimdb_message_error_response:\n {\n const zlimdb_error_response* errorResponse = (const zlimdb_error_response*)header;\n Console::printf(\"subscribe: errorResponse=%s (%d)\\n\", (const char_t*)getZlimdbError(), (int)errorResponse->error);\n }\n break;\n default:\n Console::printf(\"subscribe: messageType=%u\\n\", (uint_t)header->message_type);\n break;\n }\n}\n\nString Client::getZlimdbError()\n{\n int err = zlimdb_errno();\n if(err == zlimdb_local_error_system)\n return Error::getErrorString();\n else\n {\n const char* errstr = zlimdb_strerror(err);\n return String(errstr, String::length(errstr));\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2004-present Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nDECLARE_int32(force_channel_version);\n\nnamespace apache {\nnamespace thrift {\n\nnamespace {\n\/\/ Class for managing lifetime of objects supporting an HTTP2 session.\nclass HTTP2RoutingSessionManager : public proxygen::HTTPSession::InfoCallback,\n public proxygen::SimpleController {\n public:\n HTTP2RoutingSessionManager(\n std::unique_ptr acceptor,\n ThriftProcessor* processor)\n : proxygen::HTTPSession::InfoCallback(),\n proxygen::SimpleController(acceptor.get()),\n processor_(processor),\n negotiatedChannelVersion_(FLAGS_force_channel_version) {\n acceptor_ = std::move(acceptor);\n if (FLAGS_force_channel_version > 0) {\n \/\/ This prevents the inspection of the HTTP2 header for the channel\n \/\/ version.\n stableId_ = 0;\n } else {\n stableId_ = std::numeric_limits::max();\n }\n }\n\n ~HTTP2RoutingSessionManager() = default;\n\n proxygen::HTTPDownstreamSession* createSession(\n folly::AsyncTransportWrapper::UniquePtr sock,\n folly::SocketAddress* peerAddress,\n std::unique_ptr h2codec,\n wangle::TransportInfo const& tinfo) {\n \/\/ Obtain the proper routing address\n folly::SocketAddress localAddress;\n try {\n sock->getLocalAddress(&localAddress);\n } catch (...) {\n VLOG(3) << \"couldn't get local address for socket\";\n localAddress = folly::SocketAddress(\"0.0.0.0\", 0);\n }\n VLOG(4) << \"Created new session for peer \" << *peerAddress;\n\n \/\/ Create the DownstreamSession. Note that \"this\" occurs twice\n \/\/ because it acts as both a controller as well as a info\n \/\/ callback.\n auto session = new proxygen::HTTPDownstreamSession(\n proxygen::WheelTimerInstance(std::chrono::milliseconds(5)),\n std::move(sock),\n localAddress,\n *peerAddress,\n this,\n std::move(h2codec),\n tinfo,\n this);\n\n return session;\n }\n\n \/\/ begin HTTPSession::InfoCallback methods\n\n \/\/ We do not override onDestroy() to self destroy because this object\n \/\/ doubles as both the InfoCallback and the SimpleController. The\n \/\/ session destructor calls onDestroy() first and then detachSession()\n \/\/ so we self destroy at detachSession().\n\n void onSettings(\n const proxygen::HTTPSessionBase&,\n const proxygen::SettingsList& settings) override {\n if (FLAGS_force_channel_version > 0) {\n \/\/ Do not use the negotiated settings.\n return;\n }\n for (auto& setting : settings) {\n if (setting.id == kChannelSettingId) {\n negotiatedChannelVersion_ =\n std::min(setting.value, kMaxSupportedChannelVersion);\n VLOG(2) << \"Peer channel version is \" << setting.value;\n VLOG(2) << \"Negotiated channel version is \"\n << negotiatedChannelVersion_;\n }\n }\n if (negotiatedChannelVersion_ == 0) {\n \/\/ Did not receive a channel version, assuming legacy peer.\n negotiatedChannelVersion_ = 1;\n }\n }\n\n \/\/ end HTTPSession::InfoCallback methods\n\n \/\/ begin SimpleController methods\n\n proxygen::HTTPTransactionHandler* getRequestHandler(\n proxygen::HTTPTransaction& txn,\n proxygen::HTTPMessage* msg) override {\n folly::SocketAddress clientAddr, vipAddr;\n txn.getPeerAddress(clientAddr);\n txn.getLocalAddress(vipAddr);\n msg->setClientAddress(clientAddr);\n msg->setDstAddress(vipAddr);\n\n \/\/ This checks that the SETTINGS frame arrives before the first RPC.\n DCHECK(negotiatedChannelVersion_ > 0);\n\n \/\/ Determine channel version for this HTTP2 stream.\n uint32_t version = negotiatedChannelVersion_;\n if (UNLIKELY(txn.getID() < stableId_)) {\n auto val = msg->getHeaders().rawGet(kChannelVersionKey);\n try {\n version = folly::to(val);\n } catch (const std::exception& ex) {\n LOG(WARNING) << \"Channel version not set properly in header: \" << val;\n \/\/ This could be from a legacy client.\n version = 1;\n }\n DCHECK(version == 1 || version == negotiatedChannelVersion_);\n if (version == negotiatedChannelVersion_) {\n stableId_ = txn.getID();\n }\n }\n\n proxygen::RequestHandler* handler =\n new ThriftRequestHandler(processor_, version);\n return new proxygen::RequestHandlerAdaptor(handler);\n }\n\n void detachSession(const proxygen::HTTPSession*) override {\n VLOG(4) << \"HTTP2RoutingSessionManager::detachSession\";\n \/\/ Session destroyed, so self destroy.\n delete this;\n }\n\n \/\/ end SimpleController methods\n\n private:\n \/\/ Supporting objects for HTTP2 session managed by the callback.\n std::unique_ptr acceptor_;\n\n ThriftProcessor* processor_;\n\n \/\/ The negotiated channel version - 0 means negotiation has not\n \/\/ taken place yet. Negotiation is completed when the server\n \/\/ receives a header with a non-zero channel version.\n uint32_t negotiatedChannelVersion_;\n\n \/\/ The stream id after which the server can assume that the channel\n \/\/ version will be the negotiated version.\n proxygen::HTTPCodec::StreamID stableId_;\n};\n\n} \/\/ anonymous namespace\n\nbool HTTP2RoutingHandler::canAcceptConnection(\n const std::vector& bytes) {\n \/*\n * HTTP\/2.0 requests start with the following sequence:\n * Octal: 0x505249202a20485454502f322e300d0a0d0a534d0d0a0d0a\n * String: \"PRI * HTTP\/2.0\\r\\n\\r\\nSM\\r\\n\\r\\n\"\n *\n * For more, see: https:\/\/tools.ietf.org\/html\/rfc7540#section-3.5\n *\/\n if (bytes[0] == 0x50 && bytes[1] == 0x52 && bytes[2] == 0x49) {\n return true;\n }\n\n \/*\n * HTTP requests start with the following sequence:\n * Octal: \"0x485454502f...\"\n * String: \"HTTP\/X.X\"\n *\n * For more, see: https:\/\/tools.ietf.org\/html\/rfc2616#section-3\n *\/\n if (bytes[0] == 0x48 && bytes[1] == 0x54 && bytes[2] == 0x54) {\n return true;\n }\n\n return false;\n}\n\nbool HTTP2RoutingHandler::canAcceptEncryptedConnection(\n const std::string& protocolName) {\n return protocolName == \"h2\" || protocolName == \"http\";\n}\n\nvoid HTTP2RoutingHandler::handleConnection(\n wangle::ConnectionManager* connectionManager,\n folly::AsyncTransportWrapper::UniquePtr sock,\n folly::SocketAddress* peerAddress,\n wangle::TransportInfo const& tinfo) {\n \/\/ Create the DownstreamSession manager.\n auto ipConfig = proxygen::HTTPServer::IPConfig(\n *peerAddress, proxygen::HTTPServer::Protocol::HTTP2);\n auto acceptorConfig =\n proxygen::HTTPServerAcceptor::makeConfig(ipConfig, *options_);\n auto acceptor = proxygen::HTTPServerAcceptor::make(acceptorConfig, *options_);\n auto sessionManager =\n new HTTP2RoutingSessionManager(std::move(acceptor), processor_);\n \/\/ Get the HTTP2 Codec\n auto codecFactory = proxygen::HTTPDefaultSessionCodecFactory(acceptorConfig);\n auto h2codec =\n codecFactory.getCodec(\"h2\", proxygen::TransportDirection::DOWNSTREAM);\n \/\/ Create the DownstreamSession\n auto session = sessionManager->createSession(\n std::move(sock), peerAddress, std::move(h2codec), tinfo);\n \/\/ Set HTTP2 priorities flag on session object.\n session->setHTTP2PrioritiesEnabled(acceptorConfig.HTTP2PrioritiesEnabled);\n \/*\n if (acceptorConfig.maxConcurrentIncomingStreams) {\n session->setMaxConcurrentIncomingStreams(\n acceptorConfig.maxConcurrentIncomingStreams);\n }\n *\/\n \/\/ TODO: Improve the way max incoming streams is set\n session->setMaxConcurrentIncomingStreams(100000);\n\n \/\/ Set flow control parameters.\n session->setFlowControl(\n acceptorConfig.initialReceiveWindow,\n acceptorConfig.receiveStreamWindowSize,\n acceptorConfig.receiveSessionWindowSize);\n if (acceptorConfig.writeBufferLimit > 0) {\n session->setWriteBufferLimit(acceptorConfig.writeBufferLimit);\n }\n session->setEgressSettings(\n {{kChannelSettingId, kMaxSupportedChannelVersion}});\n\n \/\/ Route the connection.\n connectionManager->addConnection(session);\n session->startNow();\n}\n\n} \/\/ namspace thrift\n} \/\/ namespace apache\nMake HTTPSessionController callbacks take HTTPSessionBase\/*\n * Copyright 2004-present Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nDECLARE_int32(force_channel_version);\n\nnamespace apache {\nnamespace thrift {\n\nnamespace {\n\/\/ Class for managing lifetime of objects supporting an HTTP2 session.\nclass HTTP2RoutingSessionManager : public proxygen::HTTPSession::InfoCallback,\n public proxygen::SimpleController {\n public:\n HTTP2RoutingSessionManager(\n std::unique_ptr acceptor,\n ThriftProcessor* processor)\n : proxygen::HTTPSession::InfoCallback(),\n proxygen::SimpleController(acceptor.get()),\n processor_(processor),\n negotiatedChannelVersion_(FLAGS_force_channel_version) {\n acceptor_ = std::move(acceptor);\n if (FLAGS_force_channel_version > 0) {\n \/\/ This prevents the inspection of the HTTP2 header for the channel\n \/\/ version.\n stableId_ = 0;\n } else {\n stableId_ = std::numeric_limits::max();\n }\n }\n\n ~HTTP2RoutingSessionManager() = default;\n\n proxygen::HTTPDownstreamSession* createSession(\n folly::AsyncTransportWrapper::UniquePtr sock,\n folly::SocketAddress* peerAddress,\n std::unique_ptr h2codec,\n wangle::TransportInfo const& tinfo) {\n \/\/ Obtain the proper routing address\n folly::SocketAddress localAddress;\n try {\n sock->getLocalAddress(&localAddress);\n } catch (...) {\n VLOG(3) << \"couldn't get local address for socket\";\n localAddress = folly::SocketAddress(\"0.0.0.0\", 0);\n }\n VLOG(4) << \"Created new session for peer \" << *peerAddress;\n\n \/\/ Create the DownstreamSession. Note that \"this\" occurs twice\n \/\/ because it acts as both a controller as well as a info\n \/\/ callback.\n auto session = new proxygen::HTTPDownstreamSession(\n proxygen::WheelTimerInstance(std::chrono::milliseconds(5)),\n std::move(sock),\n localAddress,\n *peerAddress,\n this,\n std::move(h2codec),\n tinfo,\n this);\n\n return session;\n }\n\n \/\/ begin HTTPSession::InfoCallback methods\n\n \/\/ We do not override onDestroy() to self destroy because this object\n \/\/ doubles as both the InfoCallback and the SimpleController. The\n \/\/ session destructor calls onDestroy() first and then detachSession()\n \/\/ so we self destroy at detachSession().\n\n void onSettings(\n const proxygen::HTTPSessionBase&,\n const proxygen::SettingsList& settings) override {\n if (FLAGS_force_channel_version > 0) {\n \/\/ Do not use the negotiated settings.\n return;\n }\n for (auto& setting : settings) {\n if (setting.id == kChannelSettingId) {\n negotiatedChannelVersion_ =\n std::min(setting.value, kMaxSupportedChannelVersion);\n VLOG(2) << \"Peer channel version is \" << setting.value;\n VLOG(2) << \"Negotiated channel version is \"\n << negotiatedChannelVersion_;\n }\n }\n if (negotiatedChannelVersion_ == 0) {\n \/\/ Did not receive a channel version, assuming legacy peer.\n negotiatedChannelVersion_ = 1;\n }\n }\n\n \/\/ end HTTPSession::InfoCallback methods\n\n \/\/ begin SimpleController methods\n\n proxygen::HTTPTransactionHandler* getRequestHandler(\n proxygen::HTTPTransaction& txn,\n proxygen::HTTPMessage* msg) override {\n folly::SocketAddress clientAddr, vipAddr;\n txn.getPeerAddress(clientAddr);\n txn.getLocalAddress(vipAddr);\n msg->setClientAddress(clientAddr);\n msg->setDstAddress(vipAddr);\n\n \/\/ This checks that the SETTINGS frame arrives before the first RPC.\n DCHECK(negotiatedChannelVersion_ > 0);\n\n \/\/ Determine channel version for this HTTP2 stream.\n uint32_t version = negotiatedChannelVersion_;\n if (UNLIKELY(txn.getID() < stableId_)) {\n auto val = msg->getHeaders().rawGet(kChannelVersionKey);\n try {\n version = folly::to(val);\n } catch (const std::exception& ex) {\n LOG(WARNING) << \"Channel version not set properly in header: \" << val;\n \/\/ This could be from a legacy client.\n version = 1;\n }\n DCHECK(version == 1 || version == negotiatedChannelVersion_);\n if (version == negotiatedChannelVersion_) {\n stableId_ = txn.getID();\n }\n }\n\n proxygen::RequestHandler* handler =\n new ThriftRequestHandler(processor_, version);\n return new proxygen::RequestHandlerAdaptor(handler);\n }\n\n void detachSession(const proxygen::HTTPSessionBase*) override {\n VLOG(4) << \"HTTP2RoutingSessionManager::detachSession\";\n \/\/ Session destroyed, so self destroy.\n delete this;\n }\n\n \/\/ end SimpleController methods\n\n private:\n \/\/ Supporting objects for HTTP2 session managed by the callback.\n std::unique_ptr acceptor_;\n\n ThriftProcessor* processor_;\n\n \/\/ The negotiated channel version - 0 means negotiation has not\n \/\/ taken place yet. Negotiation is completed when the server\n \/\/ receives a header with a non-zero channel version.\n uint32_t negotiatedChannelVersion_;\n\n \/\/ The stream id after which the server can assume that the channel\n \/\/ version will be the negotiated version.\n proxygen::HTTPCodec::StreamID stableId_;\n};\n\n} \/\/ anonymous namespace\n\nbool HTTP2RoutingHandler::canAcceptConnection(\n const std::vector& bytes) {\n \/*\n * HTTP\/2.0 requests start with the following sequence:\n * Octal: 0x505249202a20485454502f322e300d0a0d0a534d0d0a0d0a\n * String: \"PRI * HTTP\/2.0\\r\\n\\r\\nSM\\r\\n\\r\\n\"\n *\n * For more, see: https:\/\/tools.ietf.org\/html\/rfc7540#section-3.5\n *\/\n if (bytes[0] == 0x50 && bytes[1] == 0x52 && bytes[2] == 0x49) {\n return true;\n }\n\n \/*\n * HTTP requests start with the following sequence:\n * Octal: \"0x485454502f...\"\n * String: \"HTTP\/X.X\"\n *\n * For more, see: https:\/\/tools.ietf.org\/html\/rfc2616#section-3\n *\/\n if (bytes[0] == 0x48 && bytes[1] == 0x54 && bytes[2] == 0x54) {\n return true;\n }\n\n return false;\n}\n\nbool HTTP2RoutingHandler::canAcceptEncryptedConnection(\n const std::string& protocolName) {\n return protocolName == \"h2\" || protocolName == \"http\";\n}\n\nvoid HTTP2RoutingHandler::handleConnection(\n wangle::ConnectionManager* connectionManager,\n folly::AsyncTransportWrapper::UniquePtr sock,\n folly::SocketAddress* peerAddress,\n wangle::TransportInfo const& tinfo) {\n \/\/ Create the DownstreamSession manager.\n auto ipConfig = proxygen::HTTPServer::IPConfig(\n *peerAddress, proxygen::HTTPServer::Protocol::HTTP2);\n auto acceptorConfig =\n proxygen::HTTPServerAcceptor::makeConfig(ipConfig, *options_);\n auto acceptor = proxygen::HTTPServerAcceptor::make(acceptorConfig, *options_);\n auto sessionManager =\n new HTTP2RoutingSessionManager(std::move(acceptor), processor_);\n \/\/ Get the HTTP2 Codec\n auto codecFactory = proxygen::HTTPDefaultSessionCodecFactory(acceptorConfig);\n auto h2codec =\n codecFactory.getCodec(\"h2\", proxygen::TransportDirection::DOWNSTREAM);\n \/\/ Create the DownstreamSession\n auto session = sessionManager->createSession(\n std::move(sock), peerAddress, std::move(h2codec), tinfo);\n \/\/ Set HTTP2 priorities flag on session object.\n session->setHTTP2PrioritiesEnabled(acceptorConfig.HTTP2PrioritiesEnabled);\n \/*\n if (acceptorConfig.maxConcurrentIncomingStreams) {\n session->setMaxConcurrentIncomingStreams(\n acceptorConfig.maxConcurrentIncomingStreams);\n }\n *\/\n \/\/ TODO: Improve the way max incoming streams is set\n session->setMaxConcurrentIncomingStreams(100000);\n\n \/\/ Set flow control parameters.\n session->setFlowControl(\n acceptorConfig.initialReceiveWindow,\n acceptorConfig.receiveStreamWindowSize,\n acceptorConfig.receiveSessionWindowSize);\n if (acceptorConfig.writeBufferLimit > 0) {\n session->setWriteBufferLimit(acceptorConfig.writeBufferLimit);\n }\n session->setEgressSettings(\n {{kChannelSettingId, kMaxSupportedChannelVersion}});\n\n \/\/ Route the connection.\n connectionManager->addConnection(session);\n session->startNow();\n}\n\n} \/\/ namspace thrift\n} \/\/ namespace apache\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \n\n#include \"Display.h\"\n#include \"GXRenderer.hpp\"\n#include \"GXContext.hpp\"\n#include \"GXLayer.hpp\"\n#include \"GXColor.hpp\"\n\n\nclass C1 : public GXLayer\n{\npublic:\n C1(const std::string &fileImg) :\n file(fileImg),\n imgH(-1)\n {}\n \n void paint( GXContext* context , const GXRect& bounds) override\n {\n context->beginPath();\n \/\/nvgBeginPath(context->_ctx);\n \/\/static int imgH = -1;\n \n if( imgH == -1)\n {\n imgH = context->createImage(file , 0);\/\/ nvgCreateImage(context->_ctx, file.c_str() , 0);\n }\n \n GXPaint imgPaint = context->imagePattern(GXPointMakeNull(), bounds.size, 0.0f\/180.0f*M_PI, imgH, 1.f);\n \/\/nvgImagePattern(context->_ctx, 0, 0, bounds.size.width , bounds.size.height, 0.0f\/180.0f*NVG_PI, imgH, 1.f);\n \n context->addRoundedRect(GXRectMake(GXPointMakeNull(), bounds.size), 5);\n \/\/nvgRoundedRect(context->_ctx, 0,0, bounds.size.width , bounds.size.height, 5);\n \n context->setFillPainter( imgPaint);\n \/\/nvgFillPaint(context->_ctx, imgPaint);\n \n context->fill();\n \/\/nvgFill(context->_ctx);\n }\n \n const std::string file;\n int imgH;\n};\n\nclass CWin : public GXLayer\n{\npublic:\n CWin()\n {\n str = \"Test\";\n background = GXColors::DarkGray;\n }\n \n void paint( GXContext* context , const GXRect& bounds) override\n {\n\n context->beginPath();\n \/\/nvgBeginPath( context->_ctx );\n \n context->addRoundedRect(bounds, 5);\n \/\/nvgRoundedRect(context->_ctx, bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height , 5);\n \/\/nvgFillColor(context->_ctx, background);\n context->setFillColor(background);\n context->fill();\n \/\/nvgFill( context->_ctx );\n \n \n const std::string fontName = \"Roboto-Regular.ttf\";\n \n int fontHandle = context->createFont(fontName);\n \/\/nvgCreateFont( context->_ctx, fontName.c_str(), fontName.c_str());\n assert( fontHandle != -1);\n \n context->setFontId( fontHandle);\n \/\/nvgFontFaceId( context->_ctx, fontHandle);\n \n \/\/nvgFontSize(context->_ctx, 20.f);\n context->setFontSize(20.f);\n \n context->setFillColor( GXColors::Red );\n \/\/nvgFillColor(context->_ctx, GXColors::Red);\n \n \/\/const std::string &str = \"Hello World\";\n \/\/nvgTextBox(context->_ctx, bounds.origin.x, bounds.origin.y, bounds.size.width-20, str.c_str(), NULL);\n \n context->addTextBox(GXPointMake(20, 20), bounds.size.width-20, str);\n \/\/nvgTextBox(context->_ctx, 20 , 20, bounds.size.width-20, str.c_str(), NULL);\n \n \/\/nvgText(context->_ctx , bounds.origin.x, bounds.origin.y , str.c_str() , NULL);\n \n \n }\n std::string str;\n};\n\n\nstatic CWin* mainWidget = nullptr;\nstatic CWin* imgWidget = nullptr;\nstatic GXContext* context = nullptr;\nstatic GXRenderer* renderer = nullptr;\n\nstatic void renderScreen( GXRenderer *render , Display* disp , GXContext *ctx)\n{\n \n \/\/glClearColor(0.0, 0.0f, 0.0f, 1.0f);\n \/\/glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);\n\n render->draw( ctx );\n DisplaySwap( disp );\n \/\/DisplayWaitEvents( disp );\n DisplayPollEvents( disp );\n \n}\n\n\nstatic void eventListener(void* d , const GXEvent *evt)\n{\n assert(d);\n assert(evt);\n \n Display* disp =(Display* ) d;\n assert(disp);\n \n \n switch (evt->type)\n {\n case GXEventTypeKey:\n {\n const GXEventKey* key = (const GXEventKey*) evt;\n assert(key);\n \n if( key->action == GXKeyAction_Press)\n {\n static std::string buf;\n \n const char* b = GXKeyGetChar(key);\n if( b)\n {\n if( key->code == GXKey_ENTER)\n {\n \n buf.clear();\n }\n else\n {\n buf.push_back(b[0]);\n \n }\n }\n else if( key->code == GXKey_BACKSPACE)\n {\n \n buf.pop_back();\/\/ erase(buf.end());\n }\n else\n {\n printf(\"Unkown char %i \\n\" , key->code);\n }\n printf(\"'%s'\\n\" , buf.c_str() );\n assert(mainWidget);\n \n mainWidget->str = buf;\n mainWidget->setNeedsDisplay();\n renderer->renderLayer( context, mainWidget, 1.f);\n \n \/*\n assert(renderer);\n assert(context);\n \n widget->str = buf;\n renderer->renderLayer( context, widget, 1.f);\n *\/\n \n }\n }\n break;\n \n case GXEventTypeMouse:\n {\n const GXEventMouse* mouse = (const GXEventMouse*) evt;\n \n printf(\"Mouse button %i state %i at (%f,%f) \\n\" , mouse->button , mouse->state , mouse->x , mouse->y);\n \n assert(imgWidget);\n imgWidget->bounds.origin = GXPointMake( mouse->x , mouse->y);\n break;\n }\n \n default:\n assert(false);\n break;\n }\n}\n\nint main()\n{\n GXRenderer render;\n \n Display disp;\n {\n \n \/**\/\n if( DisplayInit(&disp) == 0)\n {\n printf(\"Display init error \\n\");\n return -1;\n }\n\n int winWidth, winHeight;\n int fbWidth, fbHeight;\n float pxRatio;\n\n if (!disp._handle)\n {\n return -1;\n }\n \n DisplayMakeContextCurrent( &disp );\n\n DisplayGetWindowSize( &disp, &winWidth, &winHeight);\n DisplayGetFramebufferSize( &disp , &fbWidth, &fbHeight);\n \n DisplaySetEventCallback(&disp, eventListener);\n \n \/\/ Calculate pixel ration for hi-dpi devices.\n pxRatio = (float)fbWidth \/ (float)winWidth;\n \n GXContext ctx;\n \n#ifdef USE_GLFW\n assert(DisplayGetType(&disp) == DisplayGLFW);\n#elif defined USE_DISPMAN\n assert(DisplayGetType(&disp) == DisplayDispman);\n#endif\n \n \/**\/\n \n CWin mainLayer;\n CWin t1;\/\/(\"images\/image1.jpg\");\n C1 t2(\"images\/image2.jpg\");\n \n mainWidget = &mainLayer;\n imgWidget = &t1;\n renderer = &render;\n context = &ctx;\n \n mainLayer.bounds = GXRectMake(0, 0, winWidth, winHeight);\n mainLayer.background = GXColors::LightGray;\n \n \n render.setRoot(&mainLayer);\n mainLayer.addChild(&t1);\n \/\/mainLayer.addChild(&t2);\n \n t1.background = GXColorMake(0.5, 0.5, 0 , 0.5);\n t1.bounds.size = GXSizeMake(200, 200);\n t1.bounds.origin = GXPointMake(40, 10);\n \n \n t2.bounds.size = GXSizeMake(200, 200);\n t2.bounds.origin = GXPointMake(140, 160);\n t1.addChild(&t2);\n \/*\n mainLayer.setNeedsDisplay();\n t1.setNeedsDisplay();\n t2.setNeedsDisplay();\n *\/\n \n GLint defaultFBO = -1;\n glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO);\n assert(defaultFBO == 0);\n \n render.renderLayer(&ctx, &mainLayer, pxRatio);\n render.renderLayer(&ctx, &t1, pxRatio);\n render.renderLayer(&ctx, &t2, pxRatio);\n \n \n \/\/GLint defaultFBO = -1;\n glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO);\n assert(defaultFBO == 0);\n \n DisplayGetWindowSize( &disp, &winWidth, &winHeight);\n DisplayGetFramebufferSize(&disp, &fbWidth, &fbHeight);\n pxRatio = (float)fbWidth \/ (float)winWidth;\n \n glViewport(0, 0, fbWidth, fbHeight);\n \n \n GB::RunLoop runL;\n \n \/**\/\n \n GB::Timer t;\n t.setInterval(40);\n t.setCallback([&](GB::Timer &timer)\n {\n GLint defaultFBO = -1;\n glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO);\n assert(defaultFBO == 0);\n \n renderScreen(&render , &disp , &ctx);\n \n if( DisplayShouldClose( &disp ))\n {\n runL.stop();\n }\n });\n \n runL.addSource(t);\n \n \/**\/\n \/*\n GB::Timer animTime;\n animTime.setInterval(50);\n animTime.setCallback([&t2](GB::Timer &timer)\n {\n t2.bounds.origin += GXPointMake(10, 10);\n if( t2.bounds.origin.y > 600)\n {\n t2.bounds.origin = GXPointMake(10, 10);\n }\n });\n \n runL.addSource(animTime);\n *\/\n \/**\/\n \/*\n GB::FDSource input(fileno(stdin));\n input.notification = [&](GBRunLoopSourceNotification notif)\n {\n if( notif == GBRunLoopSourceCanRead)\n {\n static char buf[128];\n if(input.read(buf, 128))\n {\n printf(\"Read '%s' \\n\" , buf);\n }\n }\n };\n \n runL.addSource(input);\n *\/\n \/**\/\n\n runL.run();\n }\n \n DisplayRelease(&disp);\n\t\n\treturn 0;\n}\nTest update#include \n#include \n#include \n\n#include \n\n#include \"Display.h\"\n#include \"GXRenderer.hpp\"\n#include \"GXContext.hpp\"\n#include \"GXLayer.hpp\"\n#include \"GXColor.hpp\"\n\n\nclass C1 : public GXLayer\n{\npublic:\n C1(const std::string &fileImg) :\n file(fileImg),\n imgH(-1)\n {}\n \n void paint( GXContext* context , const GXRect& bounds) override\n {\n context->beginPath();\n \/\/nvgBeginPath(context->_ctx);\n \/\/static int imgH = -1;\n \n if( imgH == -1)\n {\n imgH = context->createImage(file , 0);\/\/ nvgCreateImage(context->_ctx, file.c_str() , 0);\n }\n \n GXPaint imgPaint = context->imagePattern(GXPointMakeNull(), bounds.size, 0.0f\/180.0f*M_PI, imgH, 1.f);\n \/\/nvgImagePattern(context->_ctx, 0, 0, bounds.size.width , bounds.size.height, 0.0f\/180.0f*NVG_PI, imgH, 1.f);\n \n context->addRoundedRect(GXRectMake(GXPointMakeNull(), bounds.size), 5);\n \/\/nvgRoundedRect(context->_ctx, 0,0, bounds.size.width , bounds.size.height, 5);\n \n context->setFillPainter( imgPaint);\n \/\/nvgFillPaint(context->_ctx, imgPaint);\n \n context->fill();\n \/\/nvgFill(context->_ctx);\n }\n \n const std::string file;\n int imgH;\n};\n\nclass CWin : public GXLayer\n{\npublic:\n CWin()\n {\n str = \"Test\";\n background = GXColors::DarkGray;\n }\n \n void paint( GXContext* context , const GXRect& bounds) override\n {\n\n context->beginPath();\n \/\/nvgBeginPath( context->_ctx );\n \n context->addRoundedRect(bounds, 5);\n \/\/nvgRoundedRect(context->_ctx, bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height , 5);\n \/\/nvgFillColor(context->_ctx, background);\n context->setFillColor(background);\n context->fill();\n \/\/nvgFill( context->_ctx );\n \n \n const std::string fontName = \"Roboto-Regular.ttf\";\n \n int fontHandle = context->createFont(fontName);\n \/\/nvgCreateFont( context->_ctx, fontName.c_str(), fontName.c_str());\n assert( fontHandle != -1);\n \n context->setFontId( fontHandle);\n \/\/nvgFontFaceId( context->_ctx, fontHandle);\n \n \/\/nvgFontSize(context->_ctx, 20.f);\n context->setFontSize(20.f);\n \n context->setFillColor( GXColors::Red );\n \/\/nvgFillColor(context->_ctx, GXColors::Red);\n \n \/\/const std::string &str = \"Hello World\";\n \/\/nvgTextBox(context->_ctx, bounds.origin.x, bounds.origin.y, bounds.size.width-20, str.c_str(), NULL);\n \n context->addTextBox(GXPointMake(20, 20), bounds.size.width-20, str);\n \/\/nvgTextBox(context->_ctx, 20 , 20, bounds.size.width-20, str.c_str(), NULL);\n \n \/\/nvgText(context->_ctx , bounds.origin.x, bounds.origin.y , str.c_str() , NULL);\n \n \n }\n std::string str;\n};\n\n\nstatic CWin* mainWidget = nullptr;\nstatic CWin* imgWidget = nullptr;\nstatic GXContext* context = nullptr;\nstatic GXRenderer* renderer = nullptr;\n\nstatic void renderScreen( GXRenderer *render , Display* disp , GXContext *ctx)\n{\n \n \/\/glClearColor(0.0, 0.0f, 0.0f, 1.0f);\n \/\/glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);\n\n render->draw( ctx );\n DisplaySwap( disp );\n \/\/DisplayWaitEvents( disp );\n DisplayPollEvents( disp );\n \n}\n\n\nstatic void eventListener(void* d , const GXEvent *evt)\n{\n assert(d);\n assert(evt);\n \n Display* disp =(Display* ) d;\n assert(disp);\n \n \n switch (evt->type)\n {\n case GXEventTypeKey:\n {\n const GXEventKey* key = (const GXEventKey*) evt;\n assert(key);\n \n if( key->action == GXKeyAction_Press)\n {\n static std::string buf;\n \n const char* b = GXKeyGetChar(key);\n if( b)\n {\n if( key->code == GXKey_ENTER)\n {\n \n buf.clear();\n }\n else\n {\n buf.push_back(b[0]);\n \n }\n }\n else if( key->code == GXKey_BACKSPACE)\n {\n \n buf.pop_back();\/\/ erase(buf.end());\n }\n else\n {\n printf(\"Unkown char %i \\n\" , key->code);\n }\n printf(\"'%s'\\n\" , buf.c_str() );\n assert(mainWidget);\n \n mainWidget->str = buf;\n mainWidget->setNeedsDisplay();\n renderer->renderLayer( context, mainWidget, 1.f);\n \n \/*\n assert(renderer);\n assert(context);\n \n widget->str = buf;\n renderer->renderLayer( context, widget, 1.f);\n *\/\n \n }\n }\n break;\n \n case GXEventTypeMouse:\n {\n const GXEventMouse* mouse = (const GXEventMouse*) evt;\n \n printf(\"Mouse button %i state %i at (%f,%f) \\n\" , mouse->button , mouse->state , mouse->x , mouse->y);\n \n assert(imgWidget);\n imgWidget->bounds.origin = GXPointMake( mouse->x , mouse->y);\n break;\n }\n \n default:\n assert(false);\n break;\n }\n}\n\nint main()\n{\n GXRenderer render;\n \n Display disp;\n {\n \n \/**\/\n if( DisplayInit(&disp) == 0)\n {\n printf(\"Display init error \\n\");\n return -1;\n }\n\n int winWidth, winHeight;\n int fbWidth, fbHeight;\n float pxRatio;\n\n if (!disp._handle)\n {\n return -1;\n }\n \n DisplayMakeContextCurrent( &disp );\n\n DisplayGetWindowSize( &disp, &winWidth, &winHeight);\n DisplayGetFramebufferSize( &disp , &fbWidth, &fbHeight);\n \n DisplaySetEventCallback(&disp, eventListener);\n \n \/\/ Calculate pixel ration for hi-dpi devices.\n pxRatio = (float)fbWidth \/ (float)winWidth;\n \n GXContext ctx;\n \n#ifdef USE_GLFW\n assert(DisplayGetType(&disp) == DisplayGLFW);\n#elif defined USE_DISPMAN\n assert(DisplayGetType(&disp) == DisplayDispman);\n#endif\n \n \/**\/\n \n CWin mainLayer;\n CWin t1;\/\/(\"images\/image1.jpg\");\n C1 t2(\"images\/image2.jpg\");\n \n mainWidget = &mainLayer;\n imgWidget = &t1;\n renderer = &render;\n context = &ctx;\n \n mainLayer.bounds = GXRectMake(0, 0, winWidth, winHeight);\n mainLayer.background = GXColors::LightGray;\n \n \n render.setRoot(&mainLayer);\n mainLayer.addChild(&t1);\n \/\/mainLayer.addChild(&t2);\n \n t1.background = GXColorMake(0.5, 0.5, 0 , 0.5);\n t1.bounds.size = GXSizeMake(200, 200);\n t1.bounds.origin = GXPointMake(40, 10);\n \n \n t2.bounds.size = GXSizeMake(200, 200);\n t2.bounds.origin = GXPointMake(140, 160);\n t1.addChild(&t2);\n \/*\n mainLayer.setNeedsDisplay();\n t1.setNeedsDisplay();\n t2.setNeedsDisplay();\n *\/\n \n \/*\n GLint defaultFBO = -1;\n glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO);\n assert(defaultFBO == 0);\n *\/\n render.renderLayer(&ctx, &mainLayer, pxRatio);\n render.renderLayer(&ctx, &t1, pxRatio);\n render.renderLayer(&ctx, &t2, pxRatio);\n \n \/*\n \/\/GLint defaultFBO = -1;\n glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO);\n assert(defaultFBO == 0);\n *\/\n DisplayGetWindowSize( &disp, &winWidth, &winHeight);\n DisplayGetFramebufferSize(&disp, &fbWidth, &fbHeight);\n pxRatio = (float)fbWidth \/ (float)winWidth;\n \n glViewport(0, 0, fbWidth, fbHeight);\n \n \n GB::RunLoop runL;\n \n \/**\/\n \n GB::Timer t;\n t.setInterval(40);\n t.setCallback([&](GB::Timer &timer)\n {\n \/*\n GLint defaultFBO = -1;\n glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO);\n assert(defaultFBO == 0);\n *\/\n renderScreen(&render , &disp , &ctx);\n \n if( DisplayShouldClose( &disp ))\n {\n runL.stop();\n }\n });\n \n runL.addSource(t);\n \n \/**\/\n \/*\n GB::Timer animTime;\n animTime.setInterval(50);\n animTime.setCallback([&t2](GB::Timer &timer)\n {\n t2.bounds.origin += GXPointMake(10, 10);\n if( t2.bounds.origin.y > 600)\n {\n t2.bounds.origin = GXPointMake(10, 10);\n }\n });\n \n runL.addSource(animTime);\n *\/\n \/**\/\n \/*\n GB::FDSource input(fileno(stdin));\n input.notification = [&](GBRunLoopSourceNotification notif)\n {\n if( notif == GBRunLoopSourceCanRead)\n {\n static char buf[128];\n if(input.read(buf, 128))\n {\n printf(\"Read '%s' \\n\" , buf);\n }\n }\n };\n \n runL.addSource(input);\n *\/\n \/**\/\n\n runL.run();\n }\n \n DisplayRelease(&disp);\n\t\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\n\/*\n * Copyright (c) 2012 Karl N. Redgate\n * \n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n\/** \\file UUID_Module.cc\n * \\brief \n *\n *\/\n\n#include \n\n#include \n#include \"tcl_util.h\"\n\n#include \"logger.h\"\n#include \"xuid.h\"\n#include \"UUID.h\"\n#include \"AppInit.h\"\n\nnamespace { int debug = 0; }\n\n\/**\n *\/\nstatic int\nUUID_obj( ClientData data, Tcl_Interp *interp,\n int objc, Tcl_Obj * CONST *objv )\n{\n UUID *uuid = (UUID *)data;\n\n if ( objc == 1 ) {\n Tcl_SetObjResult( interp, Tcl_NewLongObj((long)(uuid)) );\n return TCL_OK;\n }\n\n char *command = Tcl_GetStringFromObj( objv[1], NULL );\n if ( Tcl_StringMatch(command, \"type\") ) {\n Svc_SetResult( interp, \"UUID\", TCL_STATIC );\n return TCL_OK;\n }\n\n if ( Tcl_StringMatch(command, \"data\") ) {\n Tcl_Obj *obj = Tcl_NewByteArrayObj( uuid->raw(), 16 );\n Tcl_SetObjResult( interp, obj );\n return TCL_OK;\n }\n\n if ( Tcl_StringMatch(command, \"string\") ) {\n Tcl_Obj *obj = Tcl_NewStringObj( uuid->to_s(), -1 );\n Tcl_SetObjResult( interp, obj );\n return TCL_OK;\n }\n\n if ( Tcl_StringMatch(command, \"set\") ) {\n if ( objc < 3 ) {\n Tcl_ResetResult( interp );\n Tcl_WrongNumArgs( interp, 1, objv, \"set value\" );\n return TCL_ERROR;\n }\n char *uuid_string = Tcl_GetStringFromObj( objv[2], NULL );\n uuid->set( uuid_string );\n Tcl_Obj *obj = Tcl_NewStringObj( uuid->to_s(), -1 );\n Tcl_SetObjResult( interp, obj );\n return TCL_OK;\n }\n\n uint8_t *x = uuid->raw();\n if ( Tcl_StringMatch(command, \"dump\") ) {\n printf( \"%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\\n\",\n x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7],\n x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15] );\n Tcl_ResetResult( interp );\n return TCL_OK;\n }\n\n Svc_SetResult( interp, \"Unknown command for UUID object\", TCL_STATIC );\n return TCL_ERROR;\n}\n\n\/**\n *\/\nstatic void\nUUID_delete( ClientData data ) {\n UUID *uuid = (UUID *)data;\n delete uuid;\n}\n\n\/**\n *\/\nstatic int\nUUID_cmd( ClientData data, Tcl_Interp *interp,\n int objc, Tcl_Obj * CONST *objv )\n{\n if ( objc < 2 ) {\n Tcl_ResetResult( interp );\n Tcl_WrongNumArgs( interp, 1, objv, \"name [value]\" );\n return TCL_ERROR;\n }\n char *name = Tcl_GetStringFromObj( objv[1], NULL );\n\n if ( objc == 2 ) {\n UUID *object = new UUID();\n Tcl_CreateObjCommand( interp, name, UUID_obj, (ClientData)object, UUID_delete );\n Svc_SetResult( interp, name, TCL_VOLATILE );\n return TCL_OK;\n }\n\n if ( objc != 3 ) {\n Tcl_ResetResult( interp );\n Tcl_WrongNumArgs( interp, 1, objv, \"name value\" );\n return TCL_ERROR;\n }\n char *uuid_string = Tcl_GetStringFromObj( objv[2], NULL );\n UUID *object = new UUID( uuid_string );\n Tcl_CreateObjCommand( interp, name, UUID_obj, (ClientData)object, UUID_delete );\n Svc_SetResult( interp, name, TCL_VOLATILE );\n return TCL_OK;\n}\n\n\/**\n *\/\nstatic int\nguid_obj( ClientData data, Tcl_Interp *interp,\n int objc, Tcl_Obj * CONST *objv )\n{\n guid_t *guid = (guid_t *)data;\n char buffer[36];\n\n if ( objc == 1 ) {\n Tcl_SetObjResult( interp, Tcl_NewLongObj((long)(guid)) );\n return TCL_OK;\n }\n\n char *command = Tcl_GetStringFromObj( objv[1], NULL );\n if ( Tcl_StringMatch(command, \"type\") ) {\n Svc_SetResult( interp, \"UUID\", TCL_STATIC );\n return TCL_OK;\n }\n\n#if 0\n if ( Tcl_StringMatch(command, \"data\") ) {\n Tcl_Obj *obj = Tcl_NewByteArrayObj( uuid->raw(), 16 );\n Tcl_SetObjResult( interp, obj );\n return TCL_OK;\n }\n#endif\n\n if ( Tcl_StringMatch(command, \"string\") ) {\n format_guid( buffer, guid );\n Tcl_Obj *obj = Tcl_NewStringObj( buffer, 36 );\n Tcl_SetObjResult( interp, obj );\n return TCL_OK;\n }\n\n if ( Tcl_StringMatch(command, \"set\") ) {\n if ( objc < 3 ) {\n Tcl_ResetResult( interp );\n Tcl_WrongNumArgs( interp, 1, objv, \"set value\" );\n return TCL_ERROR;\n }\n char *guid_string = Tcl_GetStringFromObj( objv[2], NULL );\n parse_guid( guid_string, guid );\n format_guid( buffer, guid );\n Tcl_Obj *obj = Tcl_NewStringObj( buffer, 36 );\n Tcl_SetObjResult( interp, obj );\n return TCL_OK;\n }\n\n#if 0\n uint8_t *x = uuid->raw();\n if ( Tcl_StringMatch(command, \"dump\") ) {\n printf( \"%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\\n\",\n x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7],\n x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15] );\n Tcl_ResetResult( interp );\n return TCL_OK;\n }\n#endif\n\n Svc_SetResult( interp, \"Unknown command for UUID object\", TCL_STATIC );\n return TCL_ERROR;\n}\n\n\/**\n *\/\nstatic void\nguid_delete( ClientData data ) {\n guid_t *guid = (guid_t *)data;\n free( guid );\n}\n\n\n\/**\n *\/\nstatic int\nguid_cmd( ClientData data, Tcl_Interp *interp,\n int objc, Tcl_Obj * CONST *objv )\n{\n if ( objc < 2 ) {\n Tcl_ResetResult( interp );\n Tcl_WrongNumArgs( interp, 1, objv, \"name [value]\" );\n return TCL_ERROR;\n }\n char *name = Tcl_GetStringFromObj( objv[1], NULL );\n\n if ( objc == 2 ) {\n guid_t *object = (guid_t *)malloc( sizeof(guid_t) );\n Tcl_CreateObjCommand( interp, name, guid_obj, (ClientData)object, guid_delete );\n Svc_SetResult( interp, name, TCL_VOLATILE );\n return TCL_OK;\n }\n\n if ( objc != 3 ) {\n Tcl_ResetResult( interp );\n Tcl_WrongNumArgs( interp, 1, objv, \"name value\" );\n return TCL_ERROR;\n }\n\n char *guid_string = Tcl_GetStringFromObj( objv[2], NULL );\n guid_t *object = (guid_t *)malloc( sizeof(guid_t) );\n Tcl_CreateObjCommand( interp, name, guid_obj, (ClientData)object, guid_delete );\n Svc_SetResult( interp, name, TCL_VOLATILE );\n return TCL_OK;\n}\n\n\/**\n *\/\nstatic bool\nUUID_Module( Tcl_Interp *interp ) {\n Tcl_Command command;\n\n Tcl_Namespace *ns = Tcl_CreateNamespace(interp, \"UUID\", (ClientData)0, NULL);\n if ( ns == NULL ) {\n return false;\n }\n\n if ( Tcl_LinkVar(interp, \"UUID::debug\", (char *)&debug, TCL_LINK_INT) != TCL_OK ) {\n log_err( \"failed to link ICMPv6::debug\" );\n exit( 1 );\n }\n\n command = Tcl_CreateObjCommand(interp, \"UUID\", UUID_cmd, (ClientData)0, NULL);\n if ( command == NULL ) {\n return false;\n }\n\n return true;\n}\n\napp_init( UUID_Module );\n\n\/* vim: set autoindent expandtab sw=4 syntax=c : *\/\nconnect guid cmds to interp\n\/*\n * Copyright (c) 2012 Karl N. Redgate\n * \n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n\/** \\file UUID_Module.cc\n * \\brief \n *\n *\/\n\n#include \n\n#include \n#include \"tcl_util.h\"\n\n#include \"logger.h\"\n#include \"xuid.h\"\n#include \"UUID.h\"\n#include \"AppInit.h\"\n\nnamespace { int debug = 0; }\n\n\/**\n *\/\nstatic int\nUUID_obj( ClientData data, Tcl_Interp *interp,\n int objc, Tcl_Obj * CONST *objv )\n{\n UUID *uuid = (UUID *)data;\n\n if ( objc == 1 ) {\n Tcl_SetObjResult( interp, Tcl_NewLongObj((long)(uuid)) );\n return TCL_OK;\n }\n\n char *command = Tcl_GetStringFromObj( objv[1], NULL );\n if ( Tcl_StringMatch(command, \"type\") ) {\n Svc_SetResult( interp, \"UUID\", TCL_STATIC );\n return TCL_OK;\n }\n\n if ( Tcl_StringMatch(command, \"data\") ) {\n Tcl_Obj *obj = Tcl_NewByteArrayObj( uuid->raw(), 16 );\n Tcl_SetObjResult( interp, obj );\n return TCL_OK;\n }\n\n if ( Tcl_StringMatch(command, \"string\") ) {\n Tcl_Obj *obj = Tcl_NewStringObj( uuid->to_s(), -1 );\n Tcl_SetObjResult( interp, obj );\n return TCL_OK;\n }\n\n if ( Tcl_StringMatch(command, \"set\") ) {\n if ( objc < 3 ) {\n Tcl_ResetResult( interp );\n Tcl_WrongNumArgs( interp, 1, objv, \"set value\" );\n return TCL_ERROR;\n }\n char *uuid_string = Tcl_GetStringFromObj( objv[2], NULL );\n uuid->set( uuid_string );\n Tcl_Obj *obj = Tcl_NewStringObj( uuid->to_s(), -1 );\n Tcl_SetObjResult( interp, obj );\n return TCL_OK;\n }\n\n uint8_t *x = uuid->raw();\n if ( Tcl_StringMatch(command, \"dump\") ) {\n printf( \"%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\\n\",\n x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7],\n x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15] );\n Tcl_ResetResult( interp );\n return TCL_OK;\n }\n\n Svc_SetResult( interp, \"Unknown command for UUID object\", TCL_STATIC );\n return TCL_ERROR;\n}\n\n\/**\n *\/\nstatic void\nUUID_delete( ClientData data ) {\n UUID *uuid = (UUID *)data;\n delete uuid;\n}\n\n\/**\n *\/\nstatic int\nUUID_cmd( ClientData data, Tcl_Interp *interp,\n int objc, Tcl_Obj * CONST *objv )\n{\n if ( objc < 2 ) {\n Tcl_ResetResult( interp );\n Tcl_WrongNumArgs( interp, 1, objv, \"name [value]\" );\n return TCL_ERROR;\n }\n char *name = Tcl_GetStringFromObj( objv[1], NULL );\n\n if ( objc == 2 ) {\n UUID *object = new UUID();\n Tcl_CreateObjCommand( interp, name, UUID_obj, (ClientData)object, UUID_delete );\n Svc_SetResult( interp, name, TCL_VOLATILE );\n return TCL_OK;\n }\n\n if ( objc != 3 ) {\n Tcl_ResetResult( interp );\n Tcl_WrongNumArgs( interp, 1, objv, \"name value\" );\n return TCL_ERROR;\n }\n char *uuid_string = Tcl_GetStringFromObj( objv[2], NULL );\n UUID *object = new UUID( uuid_string );\n Tcl_CreateObjCommand( interp, name, UUID_obj, (ClientData)object, UUID_delete );\n Svc_SetResult( interp, name, TCL_VOLATILE );\n return TCL_OK;\n}\n\n\/**\n *\/\nstatic int\nguid_obj( ClientData data, Tcl_Interp *interp,\n int objc, Tcl_Obj * CONST *objv )\n{\n guid_t *guid = (guid_t *)data;\n char buffer[36];\n\n if ( objc == 1 ) {\n Tcl_SetObjResult( interp, Tcl_NewLongObj((long)(guid)) );\n return TCL_OK;\n }\n\n char *command = Tcl_GetStringFromObj( objv[1], NULL );\n if ( Tcl_StringMatch(command, \"type\") ) {\n Svc_SetResult( interp, \"UUID\", TCL_STATIC );\n return TCL_OK;\n }\n\n#if 0\n if ( Tcl_StringMatch(command, \"data\") ) {\n Tcl_Obj *obj = Tcl_NewByteArrayObj( uuid->raw(), 16 );\n Tcl_SetObjResult( interp, obj );\n return TCL_OK;\n }\n#endif\n\n if ( Tcl_StringMatch(command, \"string\") ) {\n format_guid( buffer, guid );\n Tcl_Obj *obj = Tcl_NewStringObj( buffer, 36 );\n Tcl_SetObjResult( interp, obj );\n return TCL_OK;\n }\n\n if ( Tcl_StringMatch(command, \"set\") ) {\n if ( objc < 3 ) {\n Tcl_ResetResult( interp );\n Tcl_WrongNumArgs( interp, 1, objv, \"set value\" );\n return TCL_ERROR;\n }\n char *guid_string = Tcl_GetStringFromObj( objv[2], NULL );\n parse_guid( guid_string, guid );\n format_guid( buffer, guid );\n Tcl_Obj *obj = Tcl_NewStringObj( buffer, 36 );\n Tcl_SetObjResult( interp, obj );\n return TCL_OK;\n }\n\n#if 0\n uint8_t *x = uuid->raw();\n if ( Tcl_StringMatch(command, \"dump\") ) {\n printf( \"%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\\n\",\n x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7],\n x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15] );\n Tcl_ResetResult( interp );\n return TCL_OK;\n }\n#endif\n\n Svc_SetResult( interp, \"Unknown command for UUID object\", TCL_STATIC );\n return TCL_ERROR;\n}\n\n\/**\n *\/\nstatic void\nguid_delete( ClientData data ) {\n guid_t *guid = (guid_t *)data;\n free( guid );\n}\n\n\n\/**\n *\/\nstatic int\nguid_cmd( ClientData data, Tcl_Interp *interp,\n int objc, Tcl_Obj * CONST *objv )\n{\n if ( objc < 2 ) {\n Tcl_ResetResult( interp );\n Tcl_WrongNumArgs( interp, 1, objv, \"name [value]\" );\n return TCL_ERROR;\n }\n char *name = Tcl_GetStringFromObj( objv[1], NULL );\n\n if ( objc == 2 ) {\n guid_t *object = (guid_t *)malloc( sizeof(guid_t) );\n Tcl_CreateObjCommand( interp, name, guid_obj, (ClientData)object, guid_delete );\n Svc_SetResult( interp, name, TCL_VOLATILE );\n return TCL_OK;\n }\n\n if ( objc != 3 ) {\n Tcl_ResetResult( interp );\n Tcl_WrongNumArgs( interp, 1, objv, \"name value\" );\n return TCL_ERROR;\n }\n\n char *guid_string = Tcl_GetStringFromObj( objv[2], NULL );\n guid_t *object = (guid_t *)malloc( sizeof(guid_t) );\n Tcl_CreateObjCommand( interp, name, guid_obj, (ClientData)object, guid_delete );\n Svc_SetResult( interp, name, TCL_VOLATILE );\n return TCL_OK;\n}\n\n\/**\n *\/\nstatic bool\nUUID_Module( Tcl_Interp *interp ) {\n Tcl_Command command;\n\n Tcl_Namespace *ns = Tcl_CreateNamespace(interp, \"UUID\", (ClientData)0, NULL);\n if ( ns == NULL ) {\n return false;\n }\n\n if ( Tcl_LinkVar(interp, \"UUID::debug\", (char *)&debug, TCL_LINK_INT) != TCL_OK ) {\n log_err( \"failed to link ICMPv6::debug\" );\n exit( 1 );\n }\n\n command = Tcl_CreateObjCommand(interp, \"UUID::UUID\", UUID_cmd, (ClientData)0, NULL);\n if ( command == NULL ) {\n return false;\n }\n\n command = Tcl_CreateObjCommand(interp, \"UUID::guid\", guid_cmd, (ClientData)0, NULL);\n if ( command == NULL ) {\n \/\/ logger ?? want to report TCL Error\n return false;\n }\n\n return true;\n}\n\napp_init( UUID_Module );\n\n\/* vim: set autoindent expandtab sw=4 syntax=c : *\/\n<|endoftext|>"} {"text":"\/**@file Module for managing Linux signals and allowing multiple handlers per signal. *\/\n\/*\n* Copyright 2014 Range Networks, Inc.\n*\n* This software is distributed under the terms of the GNU Affero Public License.\n* See the COPYING file in the main directory for details.\n*\n* This use of this software may be subject to additional restrictions.\n* See the LEGAL file in the main directory for details.\n\n\tThis program is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU Affero General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tThis program is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU Affero General Public License for more details.\n\n\tYou should have received a copy of the GNU Affero General Public License\n\talong with this program. If not, see .\n\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"coredumper.h\"\n#include \"UnixSignal.h\"\n#include \"Logger.h\"\n\n\/\/UnixSignal gSigVec;\n\nstatic void _sigHandler(int sig)\n{\n signal(sig, SIG_IGN);\n if (sig <= 0 || sig >= UnixSignal::C_NSIG)\n {\n\tLOG(ERR) << \"Signal Handler for signal \" << sig << \" (out of range)\";\n\treturn;\n }\n \/\/ work around C++ issue with function pointers and class based function pointers\n gSigVec.Handler(sig);\n signal(sig, SIG_DFL);\n printf(\"Rethrowing signal %d\\n\", sig);\n kill(getpid(), sig);\n}\n\nvoid UnixSignal::Handler(int sig)\n{\n \/\/ Only write core files for the signals that need core\n switch(sig)\n {\n case SIGQUIT: case SIGILL: case SIGABRT: case SIGFPE: case SIGSEGV:\n case SIGBUS: case SIGSYS: case SIGTRAP: case SIGXCPU: case SIGXFSZ:\n\t{\n\t char buf[BUFSIZ];\n\t if (mAddPid)\n\t\tsnprintf(buf, sizeof(buf)-1, \"%s.%d\", mCoreFile.c_str(), getpid());\n\t else\n\t\tsnprintf(buf, sizeof(buf)-1, \"%s\", mCoreFile.c_str());\n\t WriteCoreDump(buf);\n\n\t \/\/ and save the files if needed\n\t if (mSaveFiles)\n\t {\n\t \tchar buf[BUFSIZ];\n\t\tstd::string s;\n\t\tstd::string p;\n\t\tsprintf(buf, \"%d\", getpid());\n\t\tp = buf;\n\t\ts = \"rm -rf \/tmp\/staging.\" ; s += p; s += \"\/ ; \";\n\t\ts += \"mkdir \/tmp\/staging.\" ; s += p; s += \"\/ ; \";\n\t\ts += \"cp --parents \/etc\/issue \/tmp\/staging.\" ; s += p; s += \"\/ ; \";\n\t\ts += \"cp --parents \/proc\/cpuinfo \/proc\/interrupts \/proc\/iomem \/proc\/ioports \/proc\/diskstats \/proc\/loadavg \/proc\/locks \/proc\/meminfo \/proc\/softirqs \/proc\/stat \/proc\/uptime \/proc\/version \/proc\/version_signature \/proc\/vmstat \/tmp\/staging.\" ; s += p; s += \"\/ ; \";\n\n\t\ts += \"for i in cmdline cpuset environ io limits maps net\/tcp net\/udp net\/tcp6 net\/udp6 net\/unix net\/netstat sched schedstat smaps stat statm status ; \";\n\t\ts += \"do cp --parents \/proc\/\" ; s += p; s += \"\/$i \/tmp\/staging.\" ; s += p; s += \"\/ ; \";\n\t\ts += \"cp --parents \/proc\/\"; s += p; s += \"\/task\/*\/stat* \/tmp\/staging.\"; s += p; s += \"\/ ; \";\n\t\ts += \"done ; \";\n\t\ts += \"tar --create --verbose --file=- --directory=\/proc\/\"; s += p; s += \" fd | ( cd \/tmp\/staging.\"; s += p; s += \"\/proc\/\"; s += p; s += \"\/ ; tar xpvf - ) ; \";\n\t\ts += \"tar --create --verbose --file=- --directory=\/tmp\/staging.\"; s += p; s += \"\/ . | gzip > \"; s += mTarFile; s += \" ; \";\n\t\ts += \"rm -rf \/tmp\/staging.\" ; s += p;\n\t\tprintf(\"Running '%s'\\n\", s.c_str());\n\t\tsystem(s.c_str());\n\t }\n\t}\n\tbreak;\n default:\n\tbreak;\n }\n\n printf(\"Processing signal vector for sig %d\\n\", sig);\n mLock[sig].lock();\n for (std::list::iterator i = mListHandlers[sig].begin();\n\ti != mListHandlers[sig].end(); i++)\n {\n \t(*i)(sig);\n }\n mLock[sig].unlock();\n printf(\"Done processing signal vector for sig %d\\n\", sig);\n}\n\nUnixSignal::UnixSignal(void)\n{\n for (int i = 0; i < C_NSIG; i++)\n {\n\tmListHandlers[i].clear();\n\t\/\/signal(i, _sigHandler);\n }\n mAddPid = false;\n mCoreFile = \"core\";\n}\n\nUnixSignal::~UnixSignal(void)\n{\n for (int i = 0; i < C_NSIG; i++)\n {\n\tmListHandlers[i].clear();\n\tsignal(i, SIG_DFL);\n }\n}\n\nvoid UnixSignal::Register(sighandler_t handler, int sig) \/\/ register the handler to the signal\n{\n if (sig <= 0 || sig >= C_NSIG)\n {\n\tLOG(ERR) << \"Unable to register callback for UnixSignal \" << sig << \" (out of range)\";\n\treturn;\n }\n mLock[sig].lock();\n signal(sig, _sigHandler); \/\/ only catch signals that have been registered\n mListHandlers[sig].insert(mListHandlers[sig].end(), handler);\n mLock[sig].unlock();\n}\n\nvoid UnixSignal::Dump(void)\n{\n for (int sig = 0; sig < C_NSIG; sig++)\n {\n\tmLock[sig].lock();\n\tif (mListHandlers[sig].size() != 0)\n\t{\n\t printf(\"Signal vectors for signal %d: \", sig);\n\t for (std::list::iterator i = mListHandlers[sig].begin();\n\t\ti != mListHandlers[sig].end(); i++)\n\t {\n\t\tprintf(\"%s0x%p\", i == mListHandlers[sig].begin() ? \"\" : \", \", *i);\n\t }\n\t printf(\"\\n\");\n\t}\n\tmLock[sig].unlock();\n }\n}\n- remove need for 3rdParty include reference, libcoredump now can be built-from-scratch and installed as lib and -dev headers\/**@file Module for managing Linux signals and allowing multiple handlers per signal. *\/\n\/*\n* Copyright 2014 Range Networks, Inc.\n*\n* This software is distributed under the terms of the GNU Affero Public License.\n* See the COPYING file in the main directory for details.\n*\n* This use of this software may be subject to additional restrictions.\n* See the LEGAL file in the main directory for details.\n\n\tThis program is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU Affero General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tThis program is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU Affero General Public License for more details.\n\n\tYou should have received a copy of the GNU Affero General Public License\n\talong with this program. If not, see .\n\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"UnixSignal.h\"\n#include \"Logger.h\"\n\n\/\/UnixSignal gSigVec;\n\nstatic void _sigHandler(int sig)\n{\n signal(sig, SIG_IGN);\n if (sig <= 0 || sig >= UnixSignal::C_NSIG)\n {\n\tLOG(ERR) << \"Signal Handler for signal \" << sig << \" (out of range)\";\n\treturn;\n }\n \/\/ work around C++ issue with function pointers and class based function pointers\n gSigVec.Handler(sig);\n signal(sig, SIG_DFL);\n printf(\"Rethrowing signal %d\\n\", sig);\n kill(getpid(), sig);\n}\n\nvoid UnixSignal::Handler(int sig)\n{\n \/\/ Only write core files for the signals that need core\n switch(sig)\n {\n case SIGQUIT: case SIGILL: case SIGABRT: case SIGFPE: case SIGSEGV:\n case SIGBUS: case SIGSYS: case SIGTRAP: case SIGXCPU: case SIGXFSZ:\n\t{\n\t char buf[BUFSIZ];\n\t if (mAddPid)\n\t\tsnprintf(buf, sizeof(buf)-1, \"%s.%d\", mCoreFile.c_str(), getpid());\n\t else\n\t\tsnprintf(buf, sizeof(buf)-1, \"%s\", mCoreFile.c_str());\n\t WriteCoreDump(buf);\n\n\t \/\/ and save the files if needed\n\t if (mSaveFiles)\n\t {\n\t \tchar buf[BUFSIZ];\n\t\tstd::string s;\n\t\tstd::string p;\n\t\tsprintf(buf, \"%d\", getpid());\n\t\tp = buf;\n\t\ts = \"rm -rf \/tmp\/staging.\" ; s += p; s += \"\/ ; \";\n\t\ts += \"mkdir \/tmp\/staging.\" ; s += p; s += \"\/ ; \";\n\t\ts += \"cp --parents \/etc\/issue \/tmp\/staging.\" ; s += p; s += \"\/ ; \";\n\t\ts += \"cp --parents \/proc\/cpuinfo \/proc\/interrupts \/proc\/iomem \/proc\/ioports \/proc\/diskstats \/proc\/loadavg \/proc\/locks \/proc\/meminfo \/proc\/softirqs \/proc\/stat \/proc\/uptime \/proc\/version \/proc\/version_signature \/proc\/vmstat \/tmp\/staging.\" ; s += p; s += \"\/ ; \";\n\n\t\ts += \"for i in cmdline cpuset environ io limits maps net\/tcp net\/udp net\/tcp6 net\/udp6 net\/unix net\/netstat sched schedstat smaps stat statm status ; \";\n\t\ts += \"do cp --parents \/proc\/\" ; s += p; s += \"\/$i \/tmp\/staging.\" ; s += p; s += \"\/ ; \";\n\t\ts += \"cp --parents \/proc\/\"; s += p; s += \"\/task\/*\/stat* \/tmp\/staging.\"; s += p; s += \"\/ ; \";\n\t\ts += \"done ; \";\n\t\ts += \"tar --create --verbose --file=- --directory=\/proc\/\"; s += p; s += \" fd | ( cd \/tmp\/staging.\"; s += p; s += \"\/proc\/\"; s += p; s += \"\/ ; tar xpvf - ) ; \";\n\t\ts += \"tar --create --verbose --file=- --directory=\/tmp\/staging.\"; s += p; s += \"\/ . | gzip > \"; s += mTarFile; s += \" ; \";\n\t\ts += \"rm -rf \/tmp\/staging.\" ; s += p;\n\t\tprintf(\"Running '%s'\\n\", s.c_str());\n\t\tsystem(s.c_str());\n\t }\n\t}\n\tbreak;\n default:\n\tbreak;\n }\n\n printf(\"Processing signal vector for sig %d\\n\", sig);\n mLock[sig].lock();\n for (std::list::iterator i = mListHandlers[sig].begin();\n\ti != mListHandlers[sig].end(); i++)\n {\n \t(*i)(sig);\n }\n mLock[sig].unlock();\n printf(\"Done processing signal vector for sig %d\\n\", sig);\n}\n\nUnixSignal::UnixSignal(void)\n{\n for (int i = 0; i < C_NSIG; i++)\n {\n\tmListHandlers[i].clear();\n\t\/\/signal(i, _sigHandler);\n }\n mAddPid = false;\n mCoreFile = \"core\";\n}\n\nUnixSignal::~UnixSignal(void)\n{\n for (int i = 0; i < C_NSIG; i++)\n {\n\tmListHandlers[i].clear();\n\tsignal(i, SIG_DFL);\n }\n}\n\nvoid UnixSignal::Register(sighandler_t handler, int sig) \/\/ register the handler to the signal\n{\n if (sig <= 0 || sig >= C_NSIG)\n {\n\tLOG(ERR) << \"Unable to register callback for UnixSignal \" << sig << \" (out of range)\";\n\treturn;\n }\n mLock[sig].lock();\n signal(sig, _sigHandler); \/\/ only catch signals that have been registered\n mListHandlers[sig].insert(mListHandlers[sig].end(), handler);\n mLock[sig].unlock();\n}\n\nvoid UnixSignal::Dump(void)\n{\n for (int sig = 0; sig < C_NSIG; sig++)\n {\n\tmLock[sig].lock();\n\tif (mListHandlers[sig].size() != 0)\n\t{\n\t printf(\"Signal vectors for signal %d: \", sig);\n\t for (std::list::iterator i = mListHandlers[sig].begin();\n\t\ti != mListHandlers[sig].end(); i++)\n\t {\n\t\tprintf(\"%s0x%p\", i == mListHandlers[sig].begin() ? \"\" : \", \", *i);\n\t }\n\t printf(\"\\n\");\n\t}\n\tmLock[sig].unlock();\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"Plane.h\"\n#include \"Shader.h\"\n#include \"Texture.h\"\n#include \"GameTime.h\"\n\n#pragma region Variables\n\nGLFWwindow* window;\n\nGameTime gameTime;\n\nGLuint shader;\nGLuint shader2;\n\nGLuint waterTex;\nGLuint tex;\n\nPlane* plane;\nPlane* plane2;\n\nCamera cam;\n\nglm::vec2 mousePosLast;\n#pragma endregion\n\n#pragma region Function Headers\n\nvoid setupWindowAndContext();\n\nvoid update();\nvoid render();\n\n#pragma endregion\nint main()\n{\n\tsetupWindowAndContext();\n\n\tglClearColor(100\/255.0f, 149\/255.0f, 237\/255.0f, 1.0f);\n\n\tshader = loadShader(\"vertex.glsl\", \"fragment.phong.glsl\");\n\tshader2 = loadShader(\"vertex.glsl\", \"fragment.glsl\");\n\n\tplane = new Plane();\n\n\tplane2 = new Plane();\n\n\tcam.position = glm::vec3(3, 5, 3);\n\t\/\/cam.direction = glm::vec3(1, 1, 0);\n\n\tcam.light = glm::vec3(0.0f, 0.0f, 0.0f);\n\n\twaterTex = loadTexture(\"water3.jpg\");\n\t\/\/waterTex = loadTexture(\"18_vertex_texture_02.jpg\");\n\tplane->texture=waterTex;\n\ttex = loadTexture(\"rubber_duck-1331px.png\");\n\ttex = loadTexture(\"pebbles2.jpg\");\n\n\t\/\/tex = loadTexture(\"magic.jpg\");\n\tglActiveTexture(GL_TEXTURE1);\n\tglBindTexture(GL_TEXTURE_2D, tex);\n\tglActiveTexture(GL_TEXTURE0);\n\tplane2->texture = tex;\n\n\twhile(!glfwWindowShouldClose(window))\n\t{\n\t\tupdate();\n\t\trender();\n\t}\n\treturn 0;\n}\n\nvoid setupWindowAndContext()\n{\n\tif(!glfwInit())\n\t{\n\t\tstd::cout << \"GLFW Failed to Initialize!\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tglfwWindowHint(GLFW_DECORATED, GL_FALSE);\n\tglfwWindowHint(GLFW_VISIBLE, GL_FALSE);\n\tglfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n\tglfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n\tglfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n\twindow = glfwCreateWindow(WIN_WIDTH, WIN_HEIGHT, \"OpenGL Water Demo\", NULL, NULL);\n\tglfwShowWindow(window);\n\tglfwMakeContextCurrent(window);\n\n\tglewExperimental = true;\n\tif(glewInit() != GLEW_OK)\n\t{\n\t\tstd::cout << \"Glew Failed to Initialize!\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\tglEnable(GL_BLEND);\n\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n}\n\nvoid update()\n{\n\tgameTime.Update();\n\t\/\/cam.position -= glm::vec3(0.5f,1.0f,0) * gameTime.GetDeltaTimeSecondsF();\n\tcam.light -= glm::vec3(0.1f,0.2f,0) * gameTime.GetDeltaTimeSecondsF();\n\n\tcam.UpdateRotation(window, 20.0f * gameTime.GetDeltaTimeSecondsF());\n\n\t\/\/Camera Rotations\n\tdouble xpos, ypos;\n\tglfwGetCursorPos(window, &xpos, &ypos);\n\t\/\/cam.Rotation(-(xpos-mousePosLast.x), glm::vec3(0, 1, 0));\n\t\/\/cam.Rotation((ypos-mousePosLast.y), glm::vec3(1, 0, 0));\n\tmousePosLast = glm::vec2(xpos, ypos);\n\n\t\/\/Camera Translations\n\tglm::vec3 vel;\n\tif (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)\n\t{\n\t\tvel += glm::vec3(-1, 0, 0);\n\t}\n\tif (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)\n\t{\n\t\tvel += glm::vec3(1, 0, 0);\n\t}\n\tif (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)\n\t{\n\t\tvel += glm::vec3(0, 0, 1);\n\t}\n\tif (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)\n\t{\n\t\tvel += glm::vec3(0, 0, -1);\n\t}\n\n\tif (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS)\n\t{\n\t\tshader = loadShader(\"vertex.glsl\", \"fragment.phong.glsl\");\n\t}\n\n\n\tvel *= gameTime.GetDeltaTimeSecondsF();\n\n\tcam.Translate(vel);\n\t\n\n\tglfwPollEvents();\n}\n\nvoid render()\n{\n\tglClear(GL_COLOR_BUFFER_BIT);\n\n\t\/\/plane2->Draw(shader2, cam);\n\tplane->Draw(shader, cam);\n\n\tglfwSwapBuffers(window);\n}\nSet default camera rotation#include \n#include \n#include \n\n#include \"Plane.h\"\n#include \"Shader.h\"\n#include \"Texture.h\"\n#include \"GameTime.h\"\n\n#pragma region Variables\n\nGLFWwindow* window;\n\nGameTime gameTime;\n\nGLuint shader;\nGLuint shader2;\n\nGLuint waterTex;\nGLuint tex;\n\nPlane* plane;\nPlane* plane2;\n\nCamera cam;\n\nglm::vec2 mousePosLast;\n#pragma endregion\n\n#pragma region Function Headers\n\nvoid setupWindowAndContext();\n\nvoid update();\nvoid render();\n\n#pragma endregion\nint main()\n{\n\tsetupWindowAndContext();\n\n\tglClearColor(100\/255.0f, 149\/255.0f, 237\/255.0f, 1.0f);\n\n\tshader = loadShader(\"vertex.glsl\", \"fragment.phong.glsl\");\n\tshader2 = loadShader(\"vertex.glsl\", \"fragment.glsl\");\n\n\tplane = new Plane();\n\n\tplane2 = new Plane();\n\n\tcam.position = glm::vec3(3, 5, 3);\n\t\/\/cam.direction = glm::vec3(1, 1, 0);\n\n\tcam.light = glm::vec3(0.0f, 0.0f, 0.0f);\n\n\twaterTex = loadTexture(\"water3.jpg\");\n\t\/\/waterTex = loadTexture(\"18_vertex_texture_02.jpg\");\n\tplane->texture=waterTex;\n\ttex = loadTexture(\"rubber_duck-1331px.png\");\n\ttex = loadTexture(\"pebbles2.jpg\");\n\n\t\/\/tex = loadTexture(\"magic.jpg\");\n\tglActiveTexture(GL_TEXTURE1);\n\tglBindTexture(GL_TEXTURE_2D, tex);\n\tglActiveTexture(GL_TEXTURE0);\n\tplane2->texture = tex;\n\n\tcam.rotation = glm::vec3(-173, -142, 0);\n\n\twhile(!glfwWindowShouldClose(window))\n\t{\n\t\tupdate();\n\t\trender();\n\t}\n\treturn 0;\n}\n\nvoid setupWindowAndContext()\n{\n\tif(!glfwInit())\n\t{\n\t\tstd::cout << \"GLFW Failed to Initialize!\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tglfwWindowHint(GLFW_DECORATED, GL_FALSE);\n\tglfwWindowHint(GLFW_VISIBLE, GL_FALSE);\n\tglfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n\tglfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n\tglfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n\twindow = glfwCreateWindow(WIN_WIDTH, WIN_HEIGHT, \"OpenGL Water Demo\", NULL, NULL);\n\tglfwShowWindow(window);\n\tglfwMakeContextCurrent(window);\n\n\tglewExperimental = true;\n\tif(glewInit() != GLEW_OK)\n\t{\n\t\tstd::cout << \"Glew Failed to Initialize!\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\tglEnable(GL_BLEND);\n\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n}\n\nvoid update()\n{\n\tgameTime.Update();\n\t\/\/cam.position -= glm::vec3(0.5f,1.0f,0) * gameTime.GetDeltaTimeSecondsF();\n\tcam.light -= glm::vec3(0.1f,0.2f,0) * gameTime.GetDeltaTimeSecondsF();\n\n\tcam.UpdateRotation(window, 20.0f * gameTime.GetDeltaTimeSecondsF());\n\n\t\/\/Camera Rotations\n\tdouble xpos, ypos;\n\tglfwGetCursorPos(window, &xpos, &ypos);\n\t\/\/cam.Rotation(-(xpos-mousePosLast.x), glm::vec3(0, 1, 0));\n\t\/\/cam.Rotation((ypos-mousePosLast.y), glm::vec3(1, 0, 0));\n\tmousePosLast = glm::vec2(xpos, ypos);\n\n\t\/\/Camera Translations\n\tglm::vec3 vel;\n\tif (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)\n\t{\n\t\tvel += glm::vec3(-1, 0, 0);\n\t}\n\tif (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)\n\t{\n\t\tvel += glm::vec3(1, 0, 0);\n\t}\n\tif (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)\n\t{\n\t\tvel += glm::vec3(0, 0, 1);\n\t}\n\tif (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)\n\t{\n\t\tvel += glm::vec3(0, 0, -1);\n\t}\n\n\tif (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS)\n\t{\n\t\tshader = loadShader(\"vertex.glsl\", \"fragment.phong.glsl\");\n\t}\n\n\n\tvel *= gameTime.GetDeltaTimeSecondsF();\n\n\tcam.Translate(vel);\n\t\n\n\tglfwPollEvents();\n}\n\nvoid render()\n{\n\tglClear(GL_COLOR_BUFFER_BIT);\n\n\t\/\/plane2->Draw(shader2, cam);\n\tplane->Draw(shader, cam);\n\n\tglfwSwapBuffers(window);\n}\n<|endoftext|>"} {"text":"\/\/ The MIT License (MIT)\r\n\/\/\r\n\/\/ \tCopyright (c) 2015 Sergey Makeev, Vadim Slyusarev\r\n\/\/\r\n\/\/ \tPermission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ \tof this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ \tin the Software without restriction, including without limitation the rights\r\n\/\/ \tto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ \tcopies of the Software, and to permit persons to whom the Software is\r\n\/\/ \tfurnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ \tall copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ \tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ \tIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ \tFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ \tAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ \tLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ \tOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ \tTHE SOFTWARE.\r\n\r\n#include \r\n\r\nnamespace MT\r\n{\r\n\tFiberContext::FiberContext()\r\n\t\t: threadContext(nullptr)\r\n\t\t, taskStatus(FiberTaskStatus::UNKNOWN)\r\n\t\t, childrenFibersCount(0)\r\n\t\t, parentFiber(nullptr)\r\n\t\t, stackRequirements(StackRequirements::INVALID)\r\n\t{\r\n\t}\r\n\r\n\tvoid FiberContext::SetStatus(FiberTaskStatus::Type _taskStatus)\r\n\t{\r\n\t\tMT_ASSERT(threadContext, \"Sanity check failed\");\r\n\t\tMT_ASSERT(threadContext->thread.IsCurrentThread(), \"You can change task status only from owner thread\");\r\n\t\ttaskStatus = _taskStatus;\r\n\t}\r\n\r\n\tFiberTaskStatus::Type FiberContext::GetStatus() const\r\n\t{\r\n\t\treturn taskStatus;\r\n\t}\r\n\r\n\tvoid FiberContext::SetThreadContext(internal::ThreadContext * _threadContext)\r\n\t{\r\n\t\tif (_threadContext)\r\n\t\t{\r\n\t\t\t_threadContext->lastActiveFiberContext = this;\r\n\t\t}\r\n\r\n\t\tthreadContext = _threadContext;\r\n\t}\r\n\r\n\tinternal::ThreadContext* FiberContext::GetThreadContext()\r\n\t{\r\n\t\treturn threadContext;\r\n\t}\r\n\r\n\tvoid FiberContext::Reset()\r\n\t{\r\n\t\tMT_ASSERT(childrenFibersCount.Load() == 0, \"Can't release fiber with active children fibers\");\r\n\t\tcurrentTask = internal::TaskDesc();\r\n\t\tparentFiber = nullptr;\r\n\t\tthreadContext = nullptr;\r\n\t\tstackRequirements = StackRequirements::INVALID;\r\n\t}\r\n\r\n\tvoid FiberContext::WaitGroupAndYield(TaskGroup group)\r\n\t{\r\n\t\tMT_ASSERT(threadContext, \"Sanity check failed!\");\r\n\t\tMT_ASSERT(threadContext->taskScheduler, \"Sanity check failed!\");\r\n\t\tMT_ASSERT(threadContext->taskScheduler->IsWorkerThread(), \"Can't use WaitGroupAndYield outside Task. Use TaskScheduler.WaitGroup() instead.\");\r\n\t\tMT_ASSERT(threadContext->thread.IsCurrentThread(), \"Thread context sanity check failed\");\r\n\r\n\t\tMT_VERIFY(group != currentGroup, \"Can't wait the same group. Deadlock detected!\", return);\r\n\t\tMT_VERIFY(group.IsValid(), \"Invalid group!\", return);\r\n\r\n\t\tTaskScheduler::TaskGroupDescription & groupDesc = threadContext->taskScheduler->GetGroupDesc(group);\r\n\r\n\t\tConcurrentQueueLIFO & groupQueue = groupDesc.GetWaitQueue();\r\n\r\n\t\t\/\/ Change status\r\n\t\ttaskStatus = FiberTaskStatus::AWAITING_GROUP;\r\n\r\n\t\t\/\/ Add current fiber to awaiting queue\r\n\t\tgroupQueue.Push(this);\r\n\r\n\t\tFiber & schedulerFiber = threadContext->schedulerFiber;\r\n\r\n#ifdef MT_INSTRUMENTED_BUILD\r\n\t\tthreadContext->NotifyTaskYielded(currentTask);\r\n#endif\r\n\r\n\t\t\/\/ Yielding, so reset thread context\r\n\t\tthreadContext = nullptr;\r\n\r\n\t\t\/\/switch to scheduler\r\n\t\tFiber::SwitchTo(fiber, schedulerFiber);\r\n\t}\r\n\r\n\tvoid FiberContext::RunSubtasksAndYieldImpl(ArrayView& buckets)\r\n\t{\r\n\t\tMT_ASSERT(threadContext, \"Sanity check failed!\");\r\n\t\tMT_ASSERT(threadContext->taskScheduler, \"Sanity check failed!\");\r\n\t\tMT_ASSERT(threadContext->taskScheduler->IsWorkerThread(), \"Can't use RunSubtasksAndYield outside Task. Use TaskScheduler.WaitGroup() instead.\");\r\n\t\tMT_ASSERT(threadContext->thread.IsCurrentThread(), \"Thread context sanity check failed\");\r\n\r\n\t\t\/\/ add to scheduler\r\n\t\tthreadContext->taskScheduler->RunTasksImpl(buckets, this, false);\r\n\r\n\t\t\/\/\r\n\t\tMT_ASSERT(threadContext->thread.IsCurrentThread(), \"Thread context sanity check failed\");\r\n\r\n\t\t\/\/ Change status\r\n\t\ttaskStatus = FiberTaskStatus::AWAITING_CHILD;\r\n\r\n\t\tFiber & schedulerFiber = threadContext->schedulerFiber;\r\n\r\n#ifdef MT_INSTRUMENTED_BUILD\r\n\t\tthreadContext->NotifyTaskYielded(currentTask);\r\n#endif\r\n\r\n\t\t\/\/ Yielding, so reset thread context\r\n\t\tthreadContext = nullptr;\r\n\r\n\t\t\/\/switch to scheduler\r\n\t\tFiber::SwitchTo(fiber, schedulerFiber);\r\n\t}\r\n\r\n\r\n\tvoid FiberContext::RunAsync(TaskGroup taskGroup, const TaskHandle* taskHandleArray, uint32 taskHandleCount)\r\n\t{\r\n\t\tMT_ASSERT(threadContext, \"ThreadContext is nullptr\");\r\n\t\tMT_ASSERT(threadContext->taskScheduler, \"Sanity check failed!\");\r\n\t\tMT_ASSERT(threadContext->taskScheduler->IsWorkerThread(), \"Can't use RunAsync outside Task. Use TaskScheduler.RunAsync() instead.\");\r\n\r\n\t\tTaskScheduler& scheduler = *(threadContext->taskScheduler);\r\n\r\n\t\tArrayView buffer(threadContext->descBuffer, taskHandleCount);\r\n\r\n\t\tuint32 bucketCount = MT::Min((uint32)scheduler.GetWorkersCount(), taskHandleCount);\r\n\t\tArrayView\tbuckets(MT_ALLOCATE_ON_STACK(sizeof(internal::TaskBucket) * bucketCount), bucketCount);\r\n\r\n\t\tinternal::DistibuteDescriptions(taskGroup, taskHandleArray, buffer, buckets);\r\n\t\tscheduler.RunTasksImpl(buckets, nullptr, false);\r\n\t}\r\n\r\n\r\n\tvoid FiberContext::RunSubtasksAndYield(TaskGroup taskGroup, const TaskHandle* taskHandleArray, uint32 taskHandleCount)\r\n\t{\r\n\t\tMT_ASSERT(threadContext, \"ThreadContext is nullptr\");\r\n\t\tMT_ASSERT(threadContext->taskScheduler, \"TaskScheduler is nullptr\");\r\n\r\n\t\tMT_ASSERT(taskHandleCount < internal::TASK_BUFFER_CAPACITY, \"Buffer overrun!\");\r\n\r\n\t\tTaskScheduler& scheduler = *(threadContext->taskScheduler);\r\n\r\n\t\tArrayView buffer(threadContext->descBuffer, taskHandleCount);\r\n\r\n\t\tuint32 bucketCount = MT::Min((uint32)scheduler.GetWorkersCount(), taskHandleCount);\r\n\t\tArrayView buckets(MT_ALLOCATE_ON_STACK(sizeof(internal::TaskBucket) * bucketCount), bucketCount);\r\n\r\n\t\tinternal::DistibuteDescriptions(taskGroup, taskHandleArray, buffer, buckets);\r\n\t\tRunSubtasksAndYieldImpl(buckets);\r\n\t}\r\n\r\n\r\n\r\n}\r\nfixed field initialization warning\/\/ The MIT License (MIT)\r\n\/\/\r\n\/\/ \tCopyright (c) 2015 Sergey Makeev, Vadim Slyusarev\r\n\/\/\r\n\/\/ \tPermission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ \tof this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ \tin the Software without restriction, including without limitation the rights\r\n\/\/ \tto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ \tcopies of the Software, and to permit persons to whom the Software is\r\n\/\/ \tfurnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ \tall copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ \tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ \tIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ \tFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ \tAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ \tLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ \tOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ \tTHE SOFTWARE.\r\n\r\n#include \r\n\r\nnamespace MT\r\n{\r\n\tFiberContext::FiberContext()\r\n\t\t: threadContext(nullptr)\r\n\t\t, taskStatus(FiberTaskStatus::UNKNOWN)\r\n\t\t, stackRequirements(StackRequirements::INVALID)\r\n\t\t, childrenFibersCount(0)\r\n\t\t, parentFiber(nullptr)\r\n\t{\r\n\t}\r\n\r\n\tvoid FiberContext::SetStatus(FiberTaskStatus::Type _taskStatus)\r\n\t{\r\n\t\tMT_ASSERT(threadContext, \"Sanity check failed\");\r\n\t\tMT_ASSERT(threadContext->thread.IsCurrentThread(), \"You can change task status only from owner thread\");\r\n\t\ttaskStatus = _taskStatus;\r\n\t}\r\n\r\n\tFiberTaskStatus::Type FiberContext::GetStatus() const\r\n\t{\r\n\t\treturn taskStatus;\r\n\t}\r\n\r\n\tvoid FiberContext::SetThreadContext(internal::ThreadContext * _threadContext)\r\n\t{\r\n\t\tif (_threadContext)\r\n\t\t{\r\n\t\t\t_threadContext->lastActiveFiberContext = this;\r\n\t\t}\r\n\r\n\t\tthreadContext = _threadContext;\r\n\t}\r\n\r\n\tinternal::ThreadContext* FiberContext::GetThreadContext()\r\n\t{\r\n\t\treturn threadContext;\r\n\t}\r\n\r\n\tvoid FiberContext::Reset()\r\n\t{\r\n\t\tMT_ASSERT(childrenFibersCount.Load() == 0, \"Can't release fiber with active children fibers\");\r\n\t\tcurrentTask = internal::TaskDesc();\r\n\t\tparentFiber = nullptr;\r\n\t\tthreadContext = nullptr;\r\n\t\tstackRequirements = StackRequirements::INVALID;\r\n\t}\r\n\r\n\tvoid FiberContext::WaitGroupAndYield(TaskGroup group)\r\n\t{\r\n\t\tMT_ASSERT(threadContext, \"Sanity check failed!\");\r\n\t\tMT_ASSERT(threadContext->taskScheduler, \"Sanity check failed!\");\r\n\t\tMT_ASSERT(threadContext->taskScheduler->IsWorkerThread(), \"Can't use WaitGroupAndYield outside Task. Use TaskScheduler.WaitGroup() instead.\");\r\n\t\tMT_ASSERT(threadContext->thread.IsCurrentThread(), \"Thread context sanity check failed\");\r\n\r\n\t\tMT_VERIFY(group != currentGroup, \"Can't wait the same group. Deadlock detected!\", return);\r\n\t\tMT_VERIFY(group.IsValid(), \"Invalid group!\", return);\r\n\r\n\t\tTaskScheduler::TaskGroupDescription & groupDesc = threadContext->taskScheduler->GetGroupDesc(group);\r\n\r\n\t\tConcurrentQueueLIFO & groupQueue = groupDesc.GetWaitQueue();\r\n\r\n\t\t\/\/ Change status\r\n\t\ttaskStatus = FiberTaskStatus::AWAITING_GROUP;\r\n\r\n\t\t\/\/ Add current fiber to awaiting queue\r\n\t\tgroupQueue.Push(this);\r\n\r\n\t\tFiber & schedulerFiber = threadContext->schedulerFiber;\r\n\r\n#ifdef MT_INSTRUMENTED_BUILD\r\n\t\tthreadContext->NotifyTaskYielded(currentTask);\r\n#endif\r\n\r\n\t\t\/\/ Yielding, so reset thread context\r\n\t\tthreadContext = nullptr;\r\n\r\n\t\t\/\/switch to scheduler\r\n\t\tFiber::SwitchTo(fiber, schedulerFiber);\r\n\t}\r\n\r\n\tvoid FiberContext::RunSubtasksAndYieldImpl(ArrayView& buckets)\r\n\t{\r\n\t\tMT_ASSERT(threadContext, \"Sanity check failed!\");\r\n\t\tMT_ASSERT(threadContext->taskScheduler, \"Sanity check failed!\");\r\n\t\tMT_ASSERT(threadContext->taskScheduler->IsWorkerThread(), \"Can't use RunSubtasksAndYield outside Task. Use TaskScheduler.WaitGroup() instead.\");\r\n\t\tMT_ASSERT(threadContext->thread.IsCurrentThread(), \"Thread context sanity check failed\");\r\n\r\n\t\t\/\/ add to scheduler\r\n\t\tthreadContext->taskScheduler->RunTasksImpl(buckets, this, false);\r\n\r\n\t\t\/\/\r\n\t\tMT_ASSERT(threadContext->thread.IsCurrentThread(), \"Thread context sanity check failed\");\r\n\r\n\t\t\/\/ Change status\r\n\t\ttaskStatus = FiberTaskStatus::AWAITING_CHILD;\r\n\r\n\t\tFiber & schedulerFiber = threadContext->schedulerFiber;\r\n\r\n#ifdef MT_INSTRUMENTED_BUILD\r\n\t\tthreadContext->NotifyTaskYielded(currentTask);\r\n#endif\r\n\r\n\t\t\/\/ Yielding, so reset thread context\r\n\t\tthreadContext = nullptr;\r\n\r\n\t\t\/\/switch to scheduler\r\n\t\tFiber::SwitchTo(fiber, schedulerFiber);\r\n\t}\r\n\r\n\r\n\tvoid FiberContext::RunAsync(TaskGroup taskGroup, const TaskHandle* taskHandleArray, uint32 taskHandleCount)\r\n\t{\r\n\t\tMT_ASSERT(threadContext, \"ThreadContext is nullptr\");\r\n\t\tMT_ASSERT(threadContext->taskScheduler, \"Sanity check failed!\");\r\n\t\tMT_ASSERT(threadContext->taskScheduler->IsWorkerThread(), \"Can't use RunAsync outside Task. Use TaskScheduler.RunAsync() instead.\");\r\n\r\n\t\tTaskScheduler& scheduler = *(threadContext->taskScheduler);\r\n\r\n\t\tArrayView buffer(threadContext->descBuffer, taskHandleCount);\r\n\r\n\t\tuint32 bucketCount = MT::Min((uint32)scheduler.GetWorkersCount(), taskHandleCount);\r\n\t\tArrayView\tbuckets(MT_ALLOCATE_ON_STACK(sizeof(internal::TaskBucket) * bucketCount), bucketCount);\r\n\r\n\t\tinternal::DistibuteDescriptions(taskGroup, taskHandleArray, buffer, buckets);\r\n\t\tscheduler.RunTasksImpl(buckets, nullptr, false);\r\n\t}\r\n\r\n\r\n\tvoid FiberContext::RunSubtasksAndYield(TaskGroup taskGroup, const TaskHandle* taskHandleArray, uint32 taskHandleCount)\r\n\t{\r\n\t\tMT_ASSERT(threadContext, \"ThreadContext is nullptr\");\r\n\t\tMT_ASSERT(threadContext->taskScheduler, \"TaskScheduler is nullptr\");\r\n\r\n\t\tMT_ASSERT(taskHandleCount < internal::TASK_BUFFER_CAPACITY, \"Buffer overrun!\");\r\n\r\n\t\tTaskScheduler& scheduler = *(threadContext->taskScheduler);\r\n\r\n\t\tArrayView buffer(threadContext->descBuffer, taskHandleCount);\r\n\r\n\t\tuint32 bucketCount = MT::Min((uint32)scheduler.GetWorkersCount(), taskHandleCount);\r\n\t\tArrayView buckets(MT_ALLOCATE_ON_STACK(sizeof(internal::TaskBucket) * bucketCount), bucketCount);\r\n\r\n\t\tinternal::DistibuteDescriptions(taskGroup, taskHandleArray, buffer, buckets);\r\n\t\tRunSubtasksAndYieldImpl(buckets);\r\n\t}\r\n\r\n\r\n\r\n}\r\n<|endoftext|>"} {"text":"\/** \\brief Tool to adjust validation rules for journal set to selective\n * evaluation to avoid failing QS checks for field not eligible\n * in this context\n * \\author Johannes Riedl\n *\n * \\copyright 2021 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n*\/\n\n#include \n#include \"Compiler.h\"\n#include \"DbConnection.h\"\n#include \"DbResultSet.h\"\n#include \"DbRow.h\"\n#include \"StringUtil.h\"\n#include \"UBTools.h\"\n#include \"util.h\"\n#include \"ZoteroHarvesterConfig.h\"\n\n\nnamespace {\n\n\nusing namespace ZoteroHarvester;\n\n\n[[noreturn]] void Usage() {\n std::cerr << \"Usage: \" << ::progname << \" zotero_harvester.conf\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nstd::string AssembleValaditionRulesIfNotExist(const std::string journal_id)\n{\n const auto tag(\"084\");\n const std::vector subfield_codes({ 'a', '2' });\n const std::vector record_types({\"regular_article\", \"review\"});\n std::vector values;\n const auto field_presence(\"ignore\");\n \/\/ The following is the logic for \"Insert if not exists beforehand\"\n \/\/ The SELECTs in the for loop generate anonymous tuples that are merged in an multi row table by UNION ALL\n for (const auto &subfield_code : subfield_codes)\n for (const auto &record_type : record_types)\n values.emplace_back(\"(SELECT \" + journal_id + \", \\'\" + tag + \"\\', \\'\" + subfield_code + \"\\', NULL, \\'\"\n + record_type + \"\\', \\'\" + field_presence + \"\\')\");\n\n return std::string(\"INSERT INTO metadata_presence_tracer \") +\n \"SELECT * FROM (\" + StringUtil::Join(values, \" UNION ALL \") + \") AS tmp \" +\n \"WHERE NOT EXISTS(SELECT 1 FROM metadata_presence_tracer WHERE journal_id=\" + journal_id\n + \" AND marc_field_tag=\" + tag + \" LIMIT 1);\";\n}\n\n\nvoid LoadHarvesterConfig(const std::string &config_path,\n std::vector> * const journal_params)\n{\n std::unique_ptr global_params;\n std::vector> group_params;\n Config::LoadHarvesterConfigFile(config_path,\n &global_params,\n &group_params,\n journal_params);\n}\n\n\nstd::string GetJournalId(DbConnection * const db_connection, const std::string &zeder_id, const std::string &group) {\n db_connection->queryOrDie(\"SELECT id FROM zeder_journals WHERE zeder_id=\\'\" + zeder_id +\n \"\\' AND zeder_instance=\\'\" + group + \"\\'\");\n DbResultSet result_set(db_connection->getLastResultSet());\n if (result_set.size() != 1)\n LOG_ERROR(\"Unable to uniquely determine journal_id for zeder_id \" + zeder_id + \" and group \" + group);\n return result_set.getNextRow()[\"id\"];\n}\n\n\nvoid UpdateRules(DbConnection * const db_connection, const std::vector> &journal_params) {\n for (const auto &journal : journal_params)\n if (journal->selective_evaluation_) {\n const std::string journal_id(GetJournalId(db_connection, std::to_string(journal->zeder_id_),\n StringUtil::ASCIIToLower(journal->group_)));\n db_connection->queryOrDie(AssembleValaditionRulesIfNotExist(journal_id));\n }\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char *argv[]) {\n if (argc != 2)\n Usage();\n\n const std::string config_path(argv[1]);\n std::vector> journal_params;\n LoadHarvesterConfig(config_path, &journal_params);\n DbConnection db_connection;\n UpdateRules(&db_connection, journal_params);\n return EXIT_SUCCESS;\n}\nWorkaround\/** \\brief Tool to adjust validation rules for journal set to selective\n * evaluation to avoid failing QS checks for field not eligible\n * in this context\n * \\author Johannes Riedl\n *\n * \\copyright 2021 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n*\/\n\n#include \n#include \"Compiler.h\"\n#include \"DbConnection.h\"\n#include \"DbResultSet.h\"\n#include \"DbRow.h\"\n#include \"StringUtil.h\"\n#include \"UBTools.h\"\n#include \"util.h\"\n#include \"ZoteroHarvesterConfig.h\"\n\n\nnamespace {\n\n\nusing namespace ZoteroHarvester;\n\n\n[[noreturn]] void Usage() {\n std::cerr << \"Usage: \" << ::progname << \" zotero_harvester.conf\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nstd::string AssembleValaditionRulesIfNotExist(const std::string journal_id)\n{\n const auto tag(\"084\");\n const std::vector subfield_codes({ 'a', '2' });\n const std::vector record_types({\"regular_article\", \"review\"});\n std::vector values;\n const auto field_presence(\"ignore\");\n \/\/ The following is the logic for \"Insert if not exists beforehand\"\n \/\/ The SELECTs in the for loop generate anonymous tuples that are merged in an multi row table by UNION ALL\n for (const auto &subfield_code : subfield_codes)\n for (const auto &record_type : record_types)\n values.emplace_back(\"(SELECT \" + journal_id + \", \\'\" + tag + \"\\', \\'\" + subfield_code + \"\\', NULL, \\'\"\n + record_type + \"\\', \\'\" + field_presence + \"\\')\");\n\n return std::string(\"INSERT INTO metadata_presence_tracer \") +\n \"SELECT * FROM (\" + StringUtil::Join(values, \" UNION ALL \") + \") AS tmp \" +\n \"WHERE NOT EXISTS(SELECT 1 FROM metadata_presence_tracer WHERE journal_id=\" + journal_id\n + \" AND marc_field_tag=\" + tag + \" LIMIT 1);\";\n}\n\n\nvoid LoadHarvesterConfig(const std::string &config_path,\n std::vector> * const journal_params)\n{\n std::unique_ptr global_params;\n std::vector> group_params;\n Config::LoadHarvesterConfigFile(config_path,\n &global_params,\n &group_params,\n journal_params);\n}\n\n\nstd::string GetJournalId(DbConnection * const db_connection, const std::string &zeder_id, const std::string &group) {\n db_connection->queryOrDie(\"SELECT id FROM zeder_journals WHERE zeder_id=\\'\" + zeder_id +\n \"\\' AND zeder_instance=\\'\" + group + \"\\'\");\n DbResultSet result_set(db_connection->getLastResultSet());\n if (not result_set.size()) {\n return \"\";\n }\n if (result_set.size() != 1)\n LOG_ERROR(\"Unable to uniquely determine journal_id for zeder_id \" + zeder_id + \" and group \" + group);\n return result_set.getNextRow()[\"id\"];\n}\n\n\nvoid UpdateRules(DbConnection * const db_connection, const std::vector> &journal_params) {\n for (const auto &journal : journal_params)\n if (journal->selective_evaluation_) {\n const std::string journal_id(GetJournalId(db_connection, std::to_string(journal->zeder_id_),\n StringUtil::ASCIIToLower(journal->group_)));\n if (journal_id.empty()) {\n LOG_WARNING(\"No journal_id result for zeder_id \" + std::to_string(journal->zeder_id_)\n + \" in group \" + journal->group_ + \" - Skipping journal\");\n continue;\n }\n db_connection->queryOrDie(AssembleValaditionRulesIfNotExist(journal_id));\n }\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char *argv[]) {\n if (argc != 2)\n Usage();\n\n const std::string config_path(argv[1]);\n std::vector> journal_params;\n LoadHarvesterConfig(config_path, &journal_params);\n DbConnection db_connection;\n UpdateRules(&db_connection, journal_params);\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/\/\r\n\/\/ Copyright (c) 2008-2015 the Urho3D project.\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ THE SOFTWARE.\r\n\/\/\r\n\r\n#include \"..\/Precompiled.h\"\r\n\r\n#include \"..\/Core\/ProcessUtils.h\"\r\n\r\n#include \r\n#include \r\n\r\n#ifdef __APPLE__\r\n#include \"TargetConditionals.h\"\r\n#endif\r\n\r\n#if defined(IOS)\r\n#include \"..\/Math\/MathDefs.h\"\r\n#include \r\n#elif !defined(ANDROID) && !defined(RPI) && !defined(EMSCRIPTEN)\r\n#include \r\n#endif\r\n\r\n#ifdef WIN32\r\n#include \r\n#include \r\n#else\r\n#include \r\n#endif\r\n\r\n#if defined(_MSC_VER)\r\n#include \r\n#elif !defined(ANDROID) && !defined(IOS) && !defined(RPI) && !defined(EMSCRIPTEN)\r\n\/\/ From http:\/\/stereopsis.com\/FPU.html\r\n\r\n#define FPU_CW_PREC_MASK 0x0300\r\n#define FPU_CW_PREC_SINGLE 0x0000\r\n#define FPU_CW_PREC_DOUBLE 0x0200\r\n#define FPU_CW_PREC_EXTENDED 0x0300\r\n#define FPU_CW_ROUND_MASK 0x0c00\r\n#define FPU_CW_ROUND_NEAR 0x0000\r\n#define FPU_CW_ROUND_DOWN 0x0400\r\n#define FPU_CW_ROUND_UP 0x0800\r\n#define FPU_CW_ROUND_CHOP 0x0c00\r\n\r\ninline unsigned GetFPUState()\r\n{\r\n unsigned control = 0;\r\n __asm__ __volatile__ (\"fnstcw %0\" : \"=m\" (control));\r\n return control;\r\n}\r\n\r\ninline void SetFPUState(unsigned control)\r\n{\r\n __asm__ __volatile__ (\"fldcw %0\" : : \"m\" (control));\r\n}\r\n\r\n#endif\r\n\r\n#include \"..\/DebugNew.h\"\r\n\r\nnamespace Atomic\r\n{\r\n\r\n#ifdef WIN32\r\nstatic bool consoleOpened = false;\r\n#endif\r\nstatic String currentLine;\r\nstatic Vector arguments;\r\n\r\n#if defined(IOS)\r\nstatic void GetCPUData(host_basic_info_data_t* data)\r\n{\r\n mach_msg_type_number_t infoCount;\r\n infoCount = HOST_BASIC_INFO_COUNT;\r\n host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)data, &infoCount);\r\n}\r\n#elif !defined(ANDROID) && !defined(RPI) && !defined(EMSCRIPTEN)\r\n\r\nstatic void GetCPUData(struct cpu_id_t* data)\r\n{\r\n if (cpu_identify(0, data) < 0)\r\n {\r\n data->num_logical_cpus = 1;\r\n data->num_cores = 1;\r\n }\r\n}\r\n\r\n#endif\r\n\r\nvoid InitFPU()\r\n{\r\n#if !defined(ATOMIC_LUAJIT) && !defined(ANDROID) && !defined(IOS) && !defined(RPI) && !defined(__x86_64__) && !defined(_M_AMD64) && !defined(EMSCRIPTEN)\r\n \/\/ Make sure FPU is in round-to-nearest, single precision mode\r\n \/\/ This ensures Direct3D and OpenGL behave similarly, and all threads behave similarly\r\n#ifdef _MSC_VER\r\n _controlfp(_RC_NEAR | _PC_24, _MCW_RC | _MCW_PC);\r\n#else\r\n unsigned control = GetFPUState();\r\n control &= ~(FPU_CW_PREC_MASK | FPU_CW_ROUND_MASK);\r\n control |= (FPU_CW_PREC_SINGLE | FPU_CW_ROUND_NEAR);\r\n SetFPUState(control);\r\n#endif\r\n#endif\r\n}\r\n\r\nvoid ErrorDialog(const String& title, const String& message)\r\n{\r\n#ifdef WIN32\r\n MessageBoxW(0, WString(message).CString(), WString(title).CString(), 0);\r\n#else\r\n PrintLine(message, true);\r\n#endif\r\n}\r\n\r\nvoid ErrorExit(const String& message, int exitCode)\r\n{\r\n if (!message.Empty())\r\n PrintLine(message, true);\r\n\r\n exit(exitCode);\r\n}\r\n\r\nvoid OpenConsoleWindow()\r\n{\r\n#ifdef WIN32\r\n if (consoleOpened)\r\n return;\r\n\r\n AllocConsole();\r\n\r\n HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);\r\n int hCrt = _open_osfhandle((size_t)hOut, _O_TEXT);\r\n FILE* outFile = _fdopen(hCrt, \"w\");\r\n setvbuf(outFile, NULL, _IONBF, 1);\r\n *stdout = *outFile;\r\n\r\n HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE);\r\n hCrt = _open_osfhandle((size_t)hIn, _O_TEXT);\r\n FILE* inFile = _fdopen(hCrt, \"r\");\r\n setvbuf(inFile, NULL, _IONBF, 128);\r\n *stdin = *inFile;\r\n\r\n consoleOpened = true;\r\n#endif\r\n}\r\n\r\nvoid PrintUnicode(const String& str, bool error)\r\n{\r\n#if !defined(ANDROID) && !defined(IOS)\r\n#ifdef WIN32\r\n \/\/ If the output stream has been redirected, use fprintf instead of WriteConsoleW,\r\n \/\/ though it means that proper Unicode output will not work\r\n FILE* out = error ? stderr : stdout;\r\n if (!_isatty(_fileno(out)))\r\n fprintf(out, \"%s\", str.CString());\r\n else\r\n {\r\n HANDLE stream = GetStdHandle(error ? STD_ERROR_HANDLE : STD_OUTPUT_HANDLE);\r\n if (stream == INVALID_HANDLE_VALUE)\r\n return;\r\n WString strW(str);\r\n DWORD charsWritten;\r\n WriteConsoleW(stream, strW.CString(), strW.Length(), &charsWritten, 0);\r\n }\r\n#else\r\n fprintf(error ? stderr : stdout, \"%s\", str.CString());\r\n#endif\r\n#endif\r\n}\r\n\r\nvoid PrintUnicodeLine(const String& str, bool error)\r\n{\r\n PrintUnicode(str + '\\n', error);\r\n}\r\n\r\nvoid PrintLine(const String& str, bool error)\r\n{\r\n#if !defined(ANDROID) && !defined(IOS)\r\n fprintf(error ? stderr : stdout, \"%s\\n\", str.CString());\r\n#endif\r\n}\r\n\r\nconst Vector& ParseArguments(const String& cmdLine, bool skipFirstArgument)\r\n{\r\n arguments.Clear();\r\n\r\n unsigned cmdStart = 0, cmdEnd = 0;\r\n bool inCmd = false;\r\n bool inQuote = false;\r\n\r\n for (unsigned i = 0; i < cmdLine.Length(); ++i)\r\n {\r\n if (cmdLine[i] == '\\\"')\r\n inQuote = !inQuote;\r\n if (cmdLine[i] == ' ' && !inQuote)\r\n {\r\n if (inCmd)\r\n {\r\n inCmd = false;\r\n cmdEnd = i;\r\n \/\/ Do not store the first argument (executable name)\r\n if (!skipFirstArgument)\r\n arguments.Push(cmdLine.Substring(cmdStart, cmdEnd - cmdStart));\r\n skipFirstArgument = false;\r\n }\r\n }\r\n else\r\n {\r\n if (!inCmd)\r\n {\r\n inCmd = true;\r\n cmdStart = i;\r\n }\r\n }\r\n }\r\n if (inCmd)\r\n {\r\n cmdEnd = cmdLine.Length();\r\n if (!skipFirstArgument)\r\n arguments.Push(cmdLine.Substring(cmdStart, cmdEnd - cmdStart));\r\n }\r\n\r\n \/\/ Strip double quotes from the arguments\r\n for (unsigned i = 0; i < arguments.Size(); ++i)\r\n arguments[i].Replace(\"\\\"\", \"\");\r\n\r\n return arguments;\r\n}\r\n\r\nconst Vector& ParseArguments(const char* cmdLine)\r\n{\r\n return ParseArguments(String(cmdLine));\r\n}\r\n\r\nconst Vector& ParseArguments(const WString& cmdLine)\r\n{\r\n return ParseArguments(String(cmdLine));\r\n}\r\n\r\nconst Vector& ParseArguments(const wchar_t* cmdLine)\r\n{\r\n return ParseArguments(String(cmdLine));\r\n}\r\n\r\nconst Vector& ParseArguments(int argc, char** argv)\r\n{\r\n String cmdLine;\r\n\r\n for (int i = 0; i < argc; ++i)\r\n cmdLine.AppendWithFormat(\"\\\"%s\\\" \", (const char*)argv[i]);\r\n\r\n return ParseArguments(cmdLine);\r\n}\r\n\r\nconst Vector& GetArguments()\r\n{\r\n return arguments;\r\n}\r\n\r\nString GetConsoleInput()\r\n{\r\n String ret;\r\n#ifdef ATOMIC_TESTING\r\n \/\/ When we are running automated tests, reading the console may block. Just return empty in that case\r\n return ret;\r\n#endif\r\n\r\n#ifdef WIN32\r\n HANDLE input = GetStdHandle(STD_INPUT_HANDLE);\r\n HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);\r\n if (input == INVALID_HANDLE_VALUE || output == INVALID_HANDLE_VALUE)\r\n return ret;\r\n\r\n \/\/ Use char-based input\r\n SetConsoleMode(input, ENABLE_PROCESSED_INPUT);\r\n\r\n INPUT_RECORD record;\r\n DWORD events = 0;\r\n DWORD readEvents = 0;\r\n\r\n if (!GetNumberOfConsoleInputEvents(input, &events))\r\n return ret;\r\n\r\n while (events--)\r\n {\r\n ReadConsoleInputW(input, &record, 1, &readEvents);\r\n if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown)\r\n {\r\n unsigned c = record.Event.KeyEvent.uChar.UnicodeChar;\r\n if (c)\r\n {\r\n if (c == '\\b')\r\n {\r\n PrintUnicode(\"\\b \\b\");\r\n int length = currentLine.LengthUTF8();\r\n if (length)\r\n currentLine = currentLine.SubstringUTF8(0, length - 1);\r\n }\r\n else if (c == '\\r')\r\n {\r\n PrintUnicode(\"\\n\");\r\n ret = currentLine;\r\n currentLine.Clear();\r\n return ret;\r\n }\r\n else\r\n {\r\n \/\/ We have disabled echo, so echo manually\r\n wchar_t out = c;\r\n DWORD charsWritten;\r\n WriteConsoleW(output, &out, 1, &charsWritten, 0);\r\n currentLine.AppendUTF8(c);\r\n }\r\n }\r\n }\r\n }\r\n#elif !defined(ANDROID) && !defined(IOS)\r\n int flags = fcntl(STDIN_FILENO, F_GETFL);\r\n fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);\r\n for (;;)\r\n {\r\n int ch = fgetc(stdin);\r\n if (ch >= 0 && ch != '\\n')\r\n ret += (char)ch;\r\n else\r\n break;\r\n }\r\n#endif\r\n\r\n return ret;\r\n}\r\n\r\nString GetPlatform()\r\n{\r\n#if defined(ANDROID)\r\n return \"Android\";\r\n#elif defined(IOS)\r\n return \"iOS\";\r\n#elif defined(WIN32)\r\n return \"Windows\";\r\n#elif defined(__APPLE__)\r\n return \"Mac OS X\";\r\n#elif defined(RPI)\r\n return \"Raspberry Pi\";\r\n#elif defined(EMSCRIPTEN)\r\n return \"HTML5\";\r\n#elif defined(__linux__)\r\n return \"Linux\";\r\n#else\r\n return String::EMPTY;\r\n#endif\r\n}\r\n\r\n#if defined(ANDROID) || defined(RPI)\r\nstatic unsigned GetArmCPUCount()\r\n{\r\n FILE* fp;\r\n int res, i = -1, j = -1;\r\n\r\n fp = fopen(\"\/sys\/devices\/system\/cpu\/present\", \"r\");\r\n \/\/ If failed, return at least 1\r\n if (fp == 0)\r\n return 1;\r\n\r\n res = fscanf(fp, \"%d-%d\", &i, &j);\r\n fclose(fp);\r\n\r\n if (res == 1 && i == 0)\r\n return 1;\r\n else if (res == 2 && i == 0)\r\n return j + 1;\r\n\r\n \/\/ If failed, return at least 1\r\n return 1;\r\n}\r\n#endif\r\n\r\nunsigned GetNumPhysicalCPUs()\r\n{\r\n#if defined(IOS)\r\n host_basic_info_data_t data;\r\n GetCPUData(&data);\r\n#if defined(TARGET_IPHONE_SIMULATOR)\r\n \/\/ Hardcoded to dual-core on simulator mode even if the host has more\r\n return Min(2, data.physical_cpu);\r\n#else\r\n return data.physical_cpu;\r\n#endif\r\n#elif defined(ANDROID) || defined(RPI)\r\n return GetArmCPUCount();\r\n#elif !defined(EMSCRIPTEN)\r\n struct cpu_id_t data;\r\n GetCPUData(&data);\r\n return (unsigned)data.num_cores;\r\n#else\r\n \/\/\/ \\todo Implement properly\r\n return 1;\r\n#endif\r\n}\r\n\r\nunsigned GetNumLogicalCPUs()\r\n{\r\n#if defined(IOS)\r\n host_basic_info_data_t data;\r\n GetCPUData(&data);\r\n#if defined(TARGET_IPHONE_SIMULATOR)\r\n return Min(2, data.logical_cpu);\r\n#else\r\n return data.logical_cpu;\r\n#endif\r\n#elif defined(ANDROID) || defined (RPI)\r\n return GetArmCPUCount();\r\n#elif !defined(EMSCRIPTEN)\r\n struct cpu_id_t data;\r\n GetCPUData(&data);\r\n return (unsigned)data.num_logical_cpus;\r\n#else\r\n \/\/\/ \\todo Implement properly\r\n return 1;\r\n#endif\r\n}\r\n\r\n}\r\n--log-std now logs to debugging Visual Studio's output pane while editor is running\/\/\r\n\/\/ Copyright (c) 2008-2015 the Urho3D project.\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ THE SOFTWARE.\r\n\/\/\r\n\r\n#include \"..\/Precompiled.h\"\r\n\r\n#include \"..\/Core\/ProcessUtils.h\"\r\n\r\n#include \r\n#include \r\n\r\n#ifdef __APPLE__\r\n#include \"TargetConditionals.h\"\r\n#endif\r\n\r\n#if defined(IOS)\r\n#include \"..\/Math\/MathDefs.h\"\r\n#include \r\n#elif !defined(ANDROID) && !defined(RPI) && !defined(EMSCRIPTEN)\r\n#include \r\n#endif\r\n\r\n#ifdef WIN32\r\n#include \r\n#include \r\n#else\r\n#include \r\n#endif\r\n\r\n#if defined(_MSC_VER)\r\n#include \r\n#elif !defined(ANDROID) && !defined(IOS) && !defined(RPI) && !defined(EMSCRIPTEN)\r\n\/\/ From http:\/\/stereopsis.com\/FPU.html\r\n\r\n#define FPU_CW_PREC_MASK 0x0300\r\n#define FPU_CW_PREC_SINGLE 0x0000\r\n#define FPU_CW_PREC_DOUBLE 0x0200\r\n#define FPU_CW_PREC_EXTENDED 0x0300\r\n#define FPU_CW_ROUND_MASK 0x0c00\r\n#define FPU_CW_ROUND_NEAR 0x0000\r\n#define FPU_CW_ROUND_DOWN 0x0400\r\n#define FPU_CW_ROUND_UP 0x0800\r\n#define FPU_CW_ROUND_CHOP 0x0c00\r\n\r\ninline unsigned GetFPUState()\r\n{\r\n unsigned control = 0;\r\n __asm__ __volatile__ (\"fnstcw %0\" : \"=m\" (control));\r\n return control;\r\n}\r\n\r\ninline void SetFPUState(unsigned control)\r\n{\r\n __asm__ __volatile__ (\"fldcw %0\" : : \"m\" (control));\r\n}\r\n\r\n#endif\r\n\r\n#include \"..\/DebugNew.h\"\r\n\r\nnamespace Atomic\r\n{\r\n\r\n#ifdef WIN32\r\nstatic bool consoleOpened = false;\r\n#endif\r\nstatic String currentLine;\r\nstatic Vector arguments;\r\n\r\n#if defined(IOS)\r\nstatic void GetCPUData(host_basic_info_data_t* data)\r\n{\r\n mach_msg_type_number_t infoCount;\r\n infoCount = HOST_BASIC_INFO_COUNT;\r\n host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)data, &infoCount);\r\n}\r\n#elif !defined(ANDROID) && !defined(RPI) && !defined(EMSCRIPTEN)\r\n\r\nstatic void GetCPUData(struct cpu_id_t* data)\r\n{\r\n if (cpu_identify(0, data) < 0)\r\n {\r\n data->num_logical_cpus = 1;\r\n data->num_cores = 1;\r\n }\r\n}\r\n\r\n#endif\r\n\r\nvoid InitFPU()\r\n{\r\n#if !defined(ATOMIC_LUAJIT) && !defined(ANDROID) && !defined(IOS) && !defined(RPI) && !defined(__x86_64__) && !defined(_M_AMD64) && !defined(EMSCRIPTEN)\r\n \/\/ Make sure FPU is in round-to-nearest, single precision mode\r\n \/\/ This ensures Direct3D and OpenGL behave similarly, and all threads behave similarly\r\n#ifdef _MSC_VER\r\n _controlfp(_RC_NEAR | _PC_24, _MCW_RC | _MCW_PC);\r\n#else\r\n unsigned control = GetFPUState();\r\n control &= ~(FPU_CW_PREC_MASK | FPU_CW_ROUND_MASK);\r\n control |= (FPU_CW_PREC_SINGLE | FPU_CW_ROUND_NEAR);\r\n SetFPUState(control);\r\n#endif\r\n#endif\r\n}\r\n\r\nvoid ErrorDialog(const String& title, const String& message)\r\n{\r\n#ifdef WIN32\r\n MessageBoxW(0, WString(message).CString(), WString(title).CString(), 0);\r\n#else\r\n PrintLine(message, true);\r\n#endif\r\n}\r\n\r\nvoid ErrorExit(const String& message, int exitCode)\r\n{\r\n if (!message.Empty())\r\n PrintLine(message, true);\r\n\r\n exit(exitCode);\r\n}\r\n\r\nvoid OpenConsoleWindow()\r\n{\r\n#ifdef WIN32\r\n if (consoleOpened)\r\n return;\r\n\r\n AllocConsole();\r\n\r\n HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);\r\n int hCrt = _open_osfhandle((size_t)hOut, _O_TEXT);\r\n FILE* outFile = _fdopen(hCrt, \"w\");\r\n setvbuf(outFile, NULL, _IONBF, 1);\r\n *stdout = *outFile;\r\n\r\n HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE);\r\n hCrt = _open_osfhandle((size_t)hIn, _O_TEXT);\r\n FILE* inFile = _fdopen(hCrt, \"r\");\r\n setvbuf(inFile, NULL, _IONBF, 128);\r\n *stdin = *inFile;\r\n\r\n consoleOpened = true;\r\n#endif\r\n}\r\n\r\nvoid PrintUnicode(const String& str, bool error)\r\n{\r\n#if !defined(ANDROID) && !defined(IOS)\r\n#ifdef WIN32\r\n \/\/ If the output stream has been redirected, use fprintf instead of WriteConsoleW,\r\n \/\/ though it means that proper Unicode output will not work\r\n FILE* out = error ? stderr : stdout;\r\n if (!_isatty(_fileno(out)))\r\n fprintf(out, \"%s\", str.CString());\r\n else\r\n {\r\n HANDLE stream = GetStdHandle(error ? STD_ERROR_HANDLE : STD_OUTPUT_HANDLE);\r\n if (stream == INVALID_HANDLE_VALUE)\r\n return;\r\n WString strW(str);\r\n DWORD charsWritten;\r\n WriteConsoleW(stream, strW.CString(), strW.Length(), &charsWritten, 0);\r\n if (IsDebuggerPresent())\r\n {\r\n OutputDebugString(str.CString());\r\n }\r\n }\r\n#else\r\n fprintf(error ? stderr : stdout, \"%s\", str.CString());\r\n#endif\r\n#endif\r\n}\r\n\r\nvoid PrintUnicodeLine(const String& str, bool error)\r\n{\r\n PrintUnicode(str + '\\n', error);\r\n}\r\n\r\nvoid PrintLine(const String& str, bool error)\r\n{\r\n#if !defined(ANDROID) && !defined(IOS)\r\n fprintf(error ? stderr : stdout, \"%s\\n\", str.CString());\r\n#endif\r\n}\r\n\r\nconst Vector& ParseArguments(const String& cmdLine, bool skipFirstArgument)\r\n{\r\n arguments.Clear();\r\n\r\n unsigned cmdStart = 0, cmdEnd = 0;\r\n bool inCmd = false;\r\n bool inQuote = false;\r\n\r\n for (unsigned i = 0; i < cmdLine.Length(); ++i)\r\n {\r\n if (cmdLine[i] == '\\\"')\r\n inQuote = !inQuote;\r\n if (cmdLine[i] == ' ' && !inQuote)\r\n {\r\n if (inCmd)\r\n {\r\n inCmd = false;\r\n cmdEnd = i;\r\n \/\/ Do not store the first argument (executable name)\r\n if (!skipFirstArgument)\r\n arguments.Push(cmdLine.Substring(cmdStart, cmdEnd - cmdStart));\r\n skipFirstArgument = false;\r\n }\r\n }\r\n else\r\n {\r\n if (!inCmd)\r\n {\r\n inCmd = true;\r\n cmdStart = i;\r\n }\r\n }\r\n }\r\n if (inCmd)\r\n {\r\n cmdEnd = cmdLine.Length();\r\n if (!skipFirstArgument)\r\n arguments.Push(cmdLine.Substring(cmdStart, cmdEnd - cmdStart));\r\n }\r\n\r\n \/\/ Strip double quotes from the arguments\r\n for (unsigned i = 0; i < arguments.Size(); ++i)\r\n arguments[i].Replace(\"\\\"\", \"\");\r\n\r\n return arguments;\r\n}\r\n\r\nconst Vector& ParseArguments(const char* cmdLine)\r\n{\r\n return ParseArguments(String(cmdLine));\r\n}\r\n\r\nconst Vector& ParseArguments(const WString& cmdLine)\r\n{\r\n return ParseArguments(String(cmdLine));\r\n}\r\n\r\nconst Vector& ParseArguments(const wchar_t* cmdLine)\r\n{\r\n return ParseArguments(String(cmdLine));\r\n}\r\n\r\nconst Vector& ParseArguments(int argc, char** argv)\r\n{\r\n String cmdLine;\r\n\r\n for (int i = 0; i < argc; ++i)\r\n cmdLine.AppendWithFormat(\"\\\"%s\\\" \", (const char*)argv[i]);\r\n\r\n return ParseArguments(cmdLine);\r\n}\r\n\r\nconst Vector& GetArguments()\r\n{\r\n return arguments;\r\n}\r\n\r\nString GetConsoleInput()\r\n{\r\n String ret;\r\n#ifdef ATOMIC_TESTING\r\n \/\/ When we are running automated tests, reading the console may block. Just return empty in that case\r\n return ret;\r\n#endif\r\n\r\n#ifdef WIN32\r\n HANDLE input = GetStdHandle(STD_INPUT_HANDLE);\r\n HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);\r\n if (input == INVALID_HANDLE_VALUE || output == INVALID_HANDLE_VALUE)\r\n return ret;\r\n\r\n \/\/ Use char-based input\r\n SetConsoleMode(input, ENABLE_PROCESSED_INPUT);\r\n\r\n INPUT_RECORD record;\r\n DWORD events = 0;\r\n DWORD readEvents = 0;\r\n\r\n if (!GetNumberOfConsoleInputEvents(input, &events))\r\n return ret;\r\n\r\n while (events--)\r\n {\r\n ReadConsoleInputW(input, &record, 1, &readEvents);\r\n if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown)\r\n {\r\n unsigned c = record.Event.KeyEvent.uChar.UnicodeChar;\r\n if (c)\r\n {\r\n if (c == '\\b')\r\n {\r\n PrintUnicode(\"\\b \\b\");\r\n int length = currentLine.LengthUTF8();\r\n if (length)\r\n currentLine = currentLine.SubstringUTF8(0, length - 1);\r\n }\r\n else if (c == '\\r')\r\n {\r\n PrintUnicode(\"\\n\");\r\n ret = currentLine;\r\n currentLine.Clear();\r\n return ret;\r\n }\r\n else\r\n {\r\n \/\/ We have disabled echo, so echo manually\r\n wchar_t out = c;\r\n DWORD charsWritten;\r\n WriteConsoleW(output, &out, 1, &charsWritten, 0);\r\n currentLine.AppendUTF8(c);\r\n }\r\n }\r\n }\r\n }\r\n#elif !defined(ANDROID) && !defined(IOS)\r\n int flags = fcntl(STDIN_FILENO, F_GETFL);\r\n fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);\r\n for (;;)\r\n {\r\n int ch = fgetc(stdin);\r\n if (ch >= 0 && ch != '\\n')\r\n ret += (char)ch;\r\n else\r\n break;\r\n }\r\n#endif\r\n\r\n return ret;\r\n}\r\n\r\nString GetPlatform()\r\n{\r\n#if defined(ANDROID)\r\n return \"Android\";\r\n#elif defined(IOS)\r\n return \"iOS\";\r\n#elif defined(WIN32)\r\n return \"Windows\";\r\n#elif defined(__APPLE__)\r\n return \"Mac OS X\";\r\n#elif defined(RPI)\r\n return \"Raspberry Pi\";\r\n#elif defined(EMSCRIPTEN)\r\n return \"HTML5\";\r\n#elif defined(__linux__)\r\n return \"Linux\";\r\n#else\r\n return String::EMPTY;\r\n#endif\r\n}\r\n\r\n#if defined(ANDROID) || defined(RPI)\r\nstatic unsigned GetArmCPUCount()\r\n{\r\n FILE* fp;\r\n int res, i = -1, j = -1;\r\n\r\n fp = fopen(\"\/sys\/devices\/system\/cpu\/present\", \"r\");\r\n \/\/ If failed, return at least 1\r\n if (fp == 0)\r\n return 1;\r\n\r\n res = fscanf(fp, \"%d-%d\", &i, &j);\r\n fclose(fp);\r\n\r\n if (res == 1 && i == 0)\r\n return 1;\r\n else if (res == 2 && i == 0)\r\n return j + 1;\r\n\r\n \/\/ If failed, return at least 1\r\n return 1;\r\n}\r\n#endif\r\n\r\nunsigned GetNumPhysicalCPUs()\r\n{\r\n#if defined(IOS)\r\n host_basic_info_data_t data;\r\n GetCPUData(&data);\r\n#if defined(TARGET_IPHONE_SIMULATOR)\r\n \/\/ Hardcoded to dual-core on simulator mode even if the host has more\r\n return Min(2, data.physical_cpu);\r\n#else\r\n return data.physical_cpu;\r\n#endif\r\n#elif defined(ANDROID) || defined(RPI)\r\n return GetArmCPUCount();\r\n#elif !defined(EMSCRIPTEN)\r\n struct cpu_id_t data;\r\n GetCPUData(&data);\r\n return (unsigned)data.num_cores;\r\n#else\r\n \/\/\/ \\todo Implement properly\r\n return 1;\r\n#endif\r\n}\r\n\r\nunsigned GetNumLogicalCPUs()\r\n{\r\n#if defined(IOS)\r\n host_basic_info_data_t data;\r\n GetCPUData(&data);\r\n#if defined(TARGET_IPHONE_SIMULATOR)\r\n return Min(2, data.logical_cpu);\r\n#else\r\n return data.logical_cpu;\r\n#endif\r\n#elif defined(ANDROID) || defined (RPI)\r\n return GetArmCPUCount();\r\n#elif !defined(EMSCRIPTEN)\r\n struct cpu_id_t data;\r\n GetCPUData(&data);\r\n return (unsigned)data.num_logical_cpus;\r\n#else\r\n \/\/\/ \\todo Implement properly\r\n return 1;\r\n#endif\r\n}\r\n\r\n}\r\n<|endoftext|>"} {"text":"#include \"QMLPlugin.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\/\/\n#ifdef DOXYGEN_WORKAROUND\n\nnamespace CuteHMI {\nnamespace GUI {\n\n\/**\n * Exposes cutehmi::gui::CuteApplication to QML.\n *\/\nclass CuteApplication: public cutehmi::gui::CuteApplication {};\n\n\/**\n * Exposes cutehmi::gui::ColorSet to QML.\n *\/\nclass ColorSet: public cutehmi::gui::ColorSet {};\n\n\/**\n * Exposes cutehmi::gui::Palette to QML.\n *\/\nclass Palette: public cutehmi::gui::Palette {};\n\n\/**\n * Exposes cutehmi::gui::Fonts to QML.\n *\/\nclass Fonts: public cutehmi::gui::Fonts {};\n\n\/**\n * Exposes cutehmi::gui::Units to QML.\n *\/\nclass Units: public cutehmi::gui::Units {};\n\n\/**\n * Exposes cutehmi::gui::Theme to QML.\n *\/\nclass Theme: public cutehmi::gui::Theme {};\n\n}\n}\n\n#endif\n\/\/<\/Doxygen-3.workaround>\n\nnamespace cutehmi {\nnamespace gui {\nnamespace internal {\n\n\/**\n * Register QML types.\n * @param uri URI.\n *\/\nvoid QMLPlugin::registerTypes(const char * uri)\n{\n\tQ_ASSERT(uri == QLatin1String(\"CuteHMI.GUI\"));\n\n\t\/\/ @uri CuteHMI.GUI\n\tqmlRegisterType(uri, CUTEHMI_GUI_MAJOR, 0, \"ColorSet\");\n\tqmlRegisterType(uri, CUTEHMI_GUI_MAJOR, 0, \"Palette\");\n\tqmlRegisterType(uri, CUTEHMI_GUI_MAJOR, 0, \"Fonts\");\n\tqmlRegisterType(uri, CUTEHMI_GUI_MAJOR, 0, \"Units\");\n\n\tqmlRegisterSingletonType(uri, CUTEHMI_GUI_MAJOR, 0, \"Theme\", ThemeProvider);\n\n\tif (qEnvironmentVariableIsSet(\"QML_PUPPET_MODE\")) {\n\t\t\/\/\n\t\t\/\/ @uri CuteHMI.GUI\n\t\tqmlRegisterSingletonType(uri, CUTEHMI_GUI_MAJOR, 0, \"CuteApplication\", CuteApplicationProvider);\n\t\t\/\/<\/CuteHMI.LockScreen-1.workaround>\n\t}\n}\n\nQObject * QMLPlugin::CuteApplicationProvider(QQmlEngine * engine, QJSEngine * scriptEngine)\n{\n\tQ_UNUSED(scriptEngine)\n\n\tQObject * app = cutehmi::gui::CuteApplication::instance();\n\tengine->setObjectOwnership(app, QQmlEngine::CppOwnership);\n\treturn app;\n}\n\nQObject * QMLPlugin::ThemeProvider(QQmlEngine * engine, QJSEngine * scriptEngine)\n{\n\tQ_UNUSED(scriptEngine)\n\n\tQObject * theme = & cutehmi::gui::Theme::Instance();\n\tengine->setObjectOwnership(theme, QQmlEngine::CppOwnership);\n\treturn theme;\n}\n\n}\n}\n}\n\n\/\/(c)C: Copyright © 2020, Michał Policht . All rights reserved.\n\/\/(c)C: SPDX-License-Identifier: LGPL-3.0-or-later OR MIT\n\/\/(c)C: This file is a part of CuteHMI.\n\/\/(c)C: CuteHMI 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 3 of the License, or (at your option) any later version.\n\/\/(c)C: CuteHMI 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.\n\/\/(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see .\n\/\/(c)C: Additionally, this file is licensed under terms of MIT license as expressed below.\n\/\/(c)C: 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:\n\/\/(c)C: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\/\/(c)C: 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.\nFix condition#include \"QMLPlugin.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\/\/\n#ifdef DOXYGEN_WORKAROUND\n\nnamespace CuteHMI {\nnamespace GUI {\n\n\/**\n * Exposes cutehmi::gui::CuteApplication to QML.\n *\/\nclass CuteApplication: public cutehmi::gui::CuteApplication {};\n\n\/**\n * Exposes cutehmi::gui::ColorSet to QML.\n *\/\nclass ColorSet: public cutehmi::gui::ColorSet {};\n\n\/**\n * Exposes cutehmi::gui::Palette to QML.\n *\/\nclass Palette: public cutehmi::gui::Palette {};\n\n\/**\n * Exposes cutehmi::gui::Fonts to QML.\n *\/\nclass Fonts: public cutehmi::gui::Fonts {};\n\n\/**\n * Exposes cutehmi::gui::Units to QML.\n *\/\nclass Units: public cutehmi::gui::Units {};\n\n\/**\n * Exposes cutehmi::gui::Theme to QML.\n *\/\nclass Theme: public cutehmi::gui::Theme {};\n\n}\n}\n\n#endif\n\/\/<\/Doxygen-3.workaround>\n\nnamespace cutehmi {\nnamespace gui {\nnamespace internal {\n\n\/**\n * Register QML types.\n * @param uri URI.\n *\/\nvoid QMLPlugin::registerTypes(const char * uri)\n{\n\tQ_ASSERT(uri == QLatin1String(\"CuteHMI.GUI\"));\n\n\t\/\/ @uri CuteHMI.GUI\n\tqmlRegisterType(uri, CUTEHMI_GUI_MAJOR, 0, \"ColorSet\");\n\tqmlRegisterType(uri, CUTEHMI_GUI_MAJOR, 0, \"Palette\");\n\tqmlRegisterType(uri, CUTEHMI_GUI_MAJOR, 0, \"Fonts\");\n\tqmlRegisterType(uri, CUTEHMI_GUI_MAJOR, 0, \"Units\");\n\n\tqmlRegisterSingletonType(uri, CUTEHMI_GUI_MAJOR, 0, \"Theme\", ThemeProvider);\n\n\tif (!qEnvironmentVariableIsSet(\"QML_PUPPET_MODE\")) {\n\t\t\/\/\n\t\t\/\/ @uri CuteHMI.GUI\n\t\tqmlRegisterSingletonType(uri, CUTEHMI_GUI_MAJOR, 0, \"CuteApplication\", CuteApplicationProvider);\n\t\t\/\/<\/CuteHMI.LockScreen-1.workaround>\n\t}\n}\n\nQObject * QMLPlugin::CuteApplicationProvider(QQmlEngine * engine, QJSEngine * scriptEngine)\n{\n\tQ_UNUSED(scriptEngine)\n\n\tQObject * app = cutehmi::gui::CuteApplication::instance();\n\tengine->setObjectOwnership(app, QQmlEngine::CppOwnership);\n\treturn app;\n}\n\nQObject * QMLPlugin::ThemeProvider(QQmlEngine * engine, QJSEngine * scriptEngine)\n{\n\tQ_UNUSED(scriptEngine)\n\n\tQObject * theme = & cutehmi::gui::Theme::Instance();\n\tengine->setObjectOwnership(theme, QQmlEngine::CppOwnership);\n\treturn theme;\n}\n\n}\n}\n}\n\n\/\/(c)C: Copyright © 2020, Michał Policht . All rights reserved.\n\/\/(c)C: SPDX-License-Identifier: LGPL-3.0-or-later OR MIT\n\/\/(c)C: This file is a part of CuteHMI.\n\/\/(c)C: CuteHMI 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 3 of the License, or (at your option) any later version.\n\/\/(c)C: CuteHMI 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.\n\/\/(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see .\n\/\/(c)C: Additionally, this file is licensed under terms of MIT license as expressed below.\n\/\/(c)C: 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:\n\/\/(c)C: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\/\/(c)C: 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.\n<|endoftext|>"} {"text":"#include \"CellFeature.h\"\n\n#include \"GameEntity.h\"\n#include \"GamePlayer.h\"\n#include \"GameType.h\"\n#include \"RtsGame.h\"\n#include \"MetaData.h\"\n#include \n\nusing namespace IStrategizer;\n\nCellFeature::CellFeature(const PlanStepParameters& p_parameters)\n{\n\tm_alliedBuildingDescription.m_numberOfBuildings = p_parameters.at(PARAM_AlliedBuildingsCount);\n\tm_alliedBuildingDescription.m_numberOfCriticalBuildings = p_parameters.at(PARAM_AlliedCriticalBuildingsCount);\n\tm_alliedForceDescription.m_numberOfUnits = p_parameters.at(PARAM_AlliedUnitsCount);\n\tm_alliedForceDescription.m_totalDamage = p_parameters.at(PARAM_AlliedUnitsTotalDamage);\n\tm_alliedForceDescription.m_totalHP = p_parameters.at(PARAM_AlliedUnitsTotalHP);\n\tm_enemyBuildingDescription.m_numberOfBuildings = p_parameters.at(PARAM_EnemyBuildingsCount);\n\tm_enemyBuildingDescription.m_numberOfCriticalBuildings = p_parameters.at(PARAM_EnemyCriticalBuildingsCount);\n\tm_enemyForceDescription.m_numberOfUnits = p_parameters.at(PARAM_EnemyUnitsCount);\n\tm_enemyForceDescription.m_totalDamage = p_parameters.at(PARAM_EnemyUnitsTotalDamage);\n\tm_enemyForceDescription.m_totalHP = p_parameters.at(PARAM_EnemyUnitsTotalHP);\n\tm_resourceDescription.m_numberOfPrimary = p_parameters.at(PARAM_NumberOfPrimaryResources);\n\tm_resourceDescription.m_numberOfSecondary = p_parameters.at(PARAM_NumberOfSecondaryResources);\n\tm_resourceDescription.m_numberOfSupply = p_parameters.at(PARAM_NumberOfSupplyResources);\n\tm_distanceFromBase = p_parameters.at(PARAM_DistanceToBase);\n\tm_distanceFromEnemyBase = p_parameters.at(PARAM_DistanceToEnemyBase);\n}\n\/\/----------------------------------------------------------------------------------------------\nvoid CellFeature::To(PlanStepParameters& p_parameters) const\n{\n\tp_parameters[PARAM_AlliedBuildingsCount] = m_alliedBuildingDescription.m_numberOfBuildings;\n\tp_parameters[PARAM_AlliedCriticalBuildingsCount] = m_alliedBuildingDescription.m_numberOfCriticalBuildings;\n\tp_parameters[PARAM_AlliedUnitsCount] = m_alliedForceDescription.m_numberOfUnits;\n\tp_parameters[PARAM_AlliedUnitsTotalDamage] = m_alliedForceDescription.m_totalDamage;\n\tp_parameters[PARAM_AlliedUnitsTotalHP] = m_alliedForceDescription.m_totalHP;\n\tp_parameters[PARAM_EnemyBuildingsCount] = m_enemyBuildingDescription.m_numberOfBuildings;\n\tp_parameters[PARAM_EnemyCriticalBuildingsCount] = m_enemyBuildingDescription.m_numberOfCriticalBuildings;\n\tp_parameters[PARAM_EnemyUnitsCount] = m_enemyForceDescription.m_numberOfUnits;\n\tp_parameters[PARAM_EnemyUnitsTotalDamage] = m_enemyForceDescription.m_totalDamage;\n\tp_parameters[PARAM_EnemyUnitsTotalHP] = m_enemyForceDescription.m_totalHP;\n\tp_parameters[PARAM_NumberOfPrimaryResources] = m_resourceDescription.m_numberOfPrimary;\n\tp_parameters[PARAM_NumberOfSecondaryResources] = m_resourceDescription.m_numberOfSecondary;\n\tp_parameters[PARAM_NumberOfSupplyResources] = m_resourceDescription.m_numberOfSupply;\n\tp_parameters[PARAM_DistanceToBase] = m_distanceFromBase;\n\tp_parameters[PARAM_DistanceToEnemyBase] = m_distanceFromEnemyBase;\n}\n\/\/----------------------------------------------------------------------------------------------\nvoid CellFeature::AddEntity(GameEntity *p_entity, bool p_isAllied)\n{\n\tif(g_Game->GetEntityType(p_entity->Type())->Attr(ECATTR_IsBuilding))\n\t{\n\t\tif(p_isAllied)\n\t\t\tm_alliedBuildingDescription.AddEntity(p_entity);\n\t\telse\n\t\t\tm_enemyBuildingDescription.AddEntity(p_entity);\n\t\t\t\n\t}\n\telse if(g_Game->GetEntityType(p_entity->Type())->Attr(ECATTR_CanAttack))\n\t{\n\t\tif(p_isAllied)\n\t\t\tm_alliedForceDescription.AddEntity(p_entity);\n\t\telse\n\t\t\tm_enemyForceDescription.AddEntity(p_entity);\n\t}\n\telse\n\t{\n\t\tm_resourceDescription.AddEntity(p_entity);\n\t}\n}\n\/\/----------------------------------------------------------------------------------------------\nvoid CellFeature::RemoveEntity(GameEntity *p_entity, bool p_isAllied)\n{\n\tif(g_Game->GetEntityType(p_entity->Type())->Attr(ECATTR_IsBuilding))\n\t{\n\t\tif(p_isAllied)\n\t\t\tm_alliedBuildingDescription.RemoveEntity(p_entity);\n\t\telse\n\t\t\tm_enemyBuildingDescription.RemoveEntity(p_entity);\n\n\t}\n\telse if(g_Game->GetEntityType(p_entity->Type())->Attr(ECATTR_CanAttack))\n\t{\n\t\tif(p_isAllied)\n\t\t\tm_alliedForceDescription.RemoveEntity(p_entity);\n\t\telse\n\t\t\tm_enemyForceDescription.RemoveEntity(p_entity);\n\t}\n\telse\n\t{\n\t\tm_resourceDescription.RemoveEntity(p_entity);\n\t}\n}\n\/\/----------------------------------------------------------------------------------------------\nvoid CellFeature::Clear()\n{\n\tm_alliedBuildingDescription.Clear();\n\tm_enemyBuildingDescription.Clear();\n\tm_alliedForceDescription.Clear();\n\tm_enemyForceDescription.Clear();\n\tm_resourceDescription.Clear();\n\tm_distanceFromBase = 0;\n\tm_distanceFromEnemyBase = 0;\n}\n\/\/----------------------------------------------------------------------------------------------\nfloat CellFeature::GetDistance(CellFeature *p_other)\n{\n\tfloat res = 0.0;\n\tfloat alliedBuildingDistance = m_alliedBuildingDescription.GetDistance(&(p_other->m_alliedBuildingDescription));\n\tfloat enemyBuildingDistance = m_enemyBuildingDescription.GetDistance(&(p_other->m_enemyBuildingDescription));\n\tfloat alliedForceDistance = m_alliedForceDescription.GetDistance(&(p_other->m_alliedForceDescription));\n\tfloat enemyForceDistance = m_enemyForceDescription.GetDistance(&(p_other->m_enemyForceDescription));\n\tfloat resourceDistance = m_resourceDescription.GetDistance(&(p_other->m_resourceDescription));\n\tfloat distanceFromBase = GetBaseDistance(this->m_distanceFromBase, p_other->m_distanceFromBase);\n\tfloat distanceFromEnemyBase = GetBaseDistance(this->m_distanceFromEnemyBase, p_other->m_distanceFromEnemyBase);\n\t\n\tres += alliedBuildingDistance;\n\tres += enemyBuildingDistance;\n\tres += alliedForceDistance;\n\tres += enemyForceDistance;\n\tres += resourceDistance;\n\tres += distanceFromBase;\n\tres += distanceFromEnemyBase;\n\n\treturn sqrt(res);\n}\n\/\/----------------------------------------------------------------------------------------------\nvoid CellFeature::CalculateDistanceToBases(Vector2 cellWorldPosition)\n{\n\tvector bases;\n\n\tg_Game->Enemy()->GetBases(bases);\n\tCalculateDistanceToBasesAux(cellWorldPosition, bases, m_distanceFromEnemyBase);\n\tg_Game->Self()->GetBases(bases);\n\tCalculateDistanceToBasesAux(cellWorldPosition, bases, m_distanceFromBase);\n}\nvoid CellFeature::CalculateDistanceToBasesAux(Vector2 cellWorldPosition, vector bases, double& distance)\n{\n\tassert(bases.size() > 0);\n\tTID baseId = bases[0];\n\tGameEntity* pBase = g_Game->Self()->GetEntity(baseId);\n\n\tif (pBase == nullptr)\n\t\tpBase = g_Game->Enemy()->GetEntity(baseId);\n\n\tassert(pBase);\n\n\tdistance = cellWorldPosition.Distance(pBase->GetPosition());\n}\n\/\/----------------------------------------------------------------------------------------------\nfloat CellFeature::GetBaseDistance(double firstBase, double secondBase) const\n{\n\treturn pow((float)(firstBase - secondBase), 2);\n}Add line separator#include \"CellFeature.h\"\n\n#include \"GameEntity.h\"\n#include \"GamePlayer.h\"\n#include \"GameType.h\"\n#include \"RtsGame.h\"\n#include \"MetaData.h\"\n#include \n\nusing namespace IStrategizer;\n\nCellFeature::CellFeature(const PlanStepParameters& p_parameters)\n{\n\tm_alliedBuildingDescription.m_numberOfBuildings = p_parameters.at(PARAM_AlliedBuildingsCount);\n\tm_alliedBuildingDescription.m_numberOfCriticalBuildings = p_parameters.at(PARAM_AlliedCriticalBuildingsCount);\n\tm_alliedForceDescription.m_numberOfUnits = p_parameters.at(PARAM_AlliedUnitsCount);\n\tm_alliedForceDescription.m_totalDamage = p_parameters.at(PARAM_AlliedUnitsTotalDamage);\n\tm_alliedForceDescription.m_totalHP = p_parameters.at(PARAM_AlliedUnitsTotalHP);\n\tm_enemyBuildingDescription.m_numberOfBuildings = p_parameters.at(PARAM_EnemyBuildingsCount);\n\tm_enemyBuildingDescription.m_numberOfCriticalBuildings = p_parameters.at(PARAM_EnemyCriticalBuildingsCount);\n\tm_enemyForceDescription.m_numberOfUnits = p_parameters.at(PARAM_EnemyUnitsCount);\n\tm_enemyForceDescription.m_totalDamage = p_parameters.at(PARAM_EnemyUnitsTotalDamage);\n\tm_enemyForceDescription.m_totalHP = p_parameters.at(PARAM_EnemyUnitsTotalHP);\n\tm_resourceDescription.m_numberOfPrimary = p_parameters.at(PARAM_NumberOfPrimaryResources);\n\tm_resourceDescription.m_numberOfSecondary = p_parameters.at(PARAM_NumberOfSecondaryResources);\n\tm_resourceDescription.m_numberOfSupply = p_parameters.at(PARAM_NumberOfSupplyResources);\n\tm_distanceFromBase = p_parameters.at(PARAM_DistanceToBase);\n\tm_distanceFromEnemyBase = p_parameters.at(PARAM_DistanceToEnemyBase);\n}\n\/\/----------------------------------------------------------------------------------------------\nvoid CellFeature::To(PlanStepParameters& p_parameters) const\n{\n\tp_parameters[PARAM_AlliedBuildingsCount] = m_alliedBuildingDescription.m_numberOfBuildings;\n\tp_parameters[PARAM_AlliedCriticalBuildingsCount] = m_alliedBuildingDescription.m_numberOfCriticalBuildings;\n\tp_parameters[PARAM_AlliedUnitsCount] = m_alliedForceDescription.m_numberOfUnits;\n\tp_parameters[PARAM_AlliedUnitsTotalDamage] = m_alliedForceDescription.m_totalDamage;\n\tp_parameters[PARAM_AlliedUnitsTotalHP] = m_alliedForceDescription.m_totalHP;\n\tp_parameters[PARAM_EnemyBuildingsCount] = m_enemyBuildingDescription.m_numberOfBuildings;\n\tp_parameters[PARAM_EnemyCriticalBuildingsCount] = m_enemyBuildingDescription.m_numberOfCriticalBuildings;\n\tp_parameters[PARAM_EnemyUnitsCount] = m_enemyForceDescription.m_numberOfUnits;\n\tp_parameters[PARAM_EnemyUnitsTotalDamage] = m_enemyForceDescription.m_totalDamage;\n\tp_parameters[PARAM_EnemyUnitsTotalHP] = m_enemyForceDescription.m_totalHP;\n\tp_parameters[PARAM_NumberOfPrimaryResources] = m_resourceDescription.m_numberOfPrimary;\n\tp_parameters[PARAM_NumberOfSecondaryResources] = m_resourceDescription.m_numberOfSecondary;\n\tp_parameters[PARAM_NumberOfSupplyResources] = m_resourceDescription.m_numberOfSupply;\n\tp_parameters[PARAM_DistanceToBase] = m_distanceFromBase;\n\tp_parameters[PARAM_DistanceToEnemyBase] = m_distanceFromEnemyBase;\n}\n\/\/----------------------------------------------------------------------------------------------\nvoid CellFeature::AddEntity(GameEntity *p_entity, bool p_isAllied)\n{\n\tif(g_Game->GetEntityType(p_entity->Type())->Attr(ECATTR_IsBuilding))\n\t{\n\t\tif(p_isAllied)\n\t\t\tm_alliedBuildingDescription.AddEntity(p_entity);\n\t\telse\n\t\t\tm_enemyBuildingDescription.AddEntity(p_entity);\n\t\t\t\n\t}\n\telse if(g_Game->GetEntityType(p_entity->Type())->Attr(ECATTR_CanAttack))\n\t{\n\t\tif(p_isAllied)\n\t\t\tm_alliedForceDescription.AddEntity(p_entity);\n\t\telse\n\t\t\tm_enemyForceDescription.AddEntity(p_entity);\n\t}\n\telse\n\t{\n\t\tm_resourceDescription.AddEntity(p_entity);\n\t}\n}\n\/\/----------------------------------------------------------------------------------------------\nvoid CellFeature::RemoveEntity(GameEntity *p_entity, bool p_isAllied)\n{\n\tif(g_Game->GetEntityType(p_entity->Type())->Attr(ECATTR_IsBuilding))\n\t{\n\t\tif(p_isAllied)\n\t\t\tm_alliedBuildingDescription.RemoveEntity(p_entity);\n\t\telse\n\t\t\tm_enemyBuildingDescription.RemoveEntity(p_entity);\n\n\t}\n\telse if(g_Game->GetEntityType(p_entity->Type())->Attr(ECATTR_CanAttack))\n\t{\n\t\tif(p_isAllied)\n\t\t\tm_alliedForceDescription.RemoveEntity(p_entity);\n\t\telse\n\t\t\tm_enemyForceDescription.RemoveEntity(p_entity);\n\t}\n\telse\n\t{\n\t\tm_resourceDescription.RemoveEntity(p_entity);\n\t}\n}\n\/\/----------------------------------------------------------------------------------------------\nvoid CellFeature::Clear()\n{\n\tm_alliedBuildingDescription.Clear();\n\tm_enemyBuildingDescription.Clear();\n\tm_alliedForceDescription.Clear();\n\tm_enemyForceDescription.Clear();\n\tm_resourceDescription.Clear();\n\tm_distanceFromBase = 0;\n\tm_distanceFromEnemyBase = 0;\n}\n\/\/----------------------------------------------------------------------------------------------\nfloat CellFeature::GetDistance(CellFeature *p_other)\n{\n\tfloat res = 0.0;\n\tfloat alliedBuildingDistance = m_alliedBuildingDescription.GetDistance(&(p_other->m_alliedBuildingDescription));\n\tfloat enemyBuildingDistance = m_enemyBuildingDescription.GetDistance(&(p_other->m_enemyBuildingDescription));\n\tfloat alliedForceDistance = m_alliedForceDescription.GetDistance(&(p_other->m_alliedForceDescription));\n\tfloat enemyForceDistance = m_enemyForceDescription.GetDistance(&(p_other->m_enemyForceDescription));\n\tfloat resourceDistance = m_resourceDescription.GetDistance(&(p_other->m_resourceDescription));\n\tfloat distanceFromBase = GetBaseDistance(this->m_distanceFromBase, p_other->m_distanceFromBase);\n\tfloat distanceFromEnemyBase = GetBaseDistance(this->m_distanceFromEnemyBase, p_other->m_distanceFromEnemyBase);\n\t\n\tres += alliedBuildingDistance;\n\tres += enemyBuildingDistance;\n\tres += alliedForceDistance;\n\tres += enemyForceDistance;\n\tres += resourceDistance;\n\tres += distanceFromBase;\n\tres += distanceFromEnemyBase;\n\n\treturn sqrt(res);\n}\n\/\/----------------------------------------------------------------------------------------------\nvoid CellFeature::CalculateDistanceToBases(Vector2 cellWorldPosition)\n{\n\tvector bases;\n\n\tg_Game->Enemy()->GetBases(bases);\n\tCalculateDistanceToBasesAux(cellWorldPosition, bases, m_distanceFromEnemyBase);\n\tg_Game->Self()->GetBases(bases);\n\tCalculateDistanceToBasesAux(cellWorldPosition, bases, m_distanceFromBase);\n}\n\/\/----------------------------------------------------------------------------------------------\nvoid CellFeature::CalculateDistanceToBasesAux(Vector2 cellWorldPosition, vector bases, double& distance)\n{\n\tassert(bases.size() > 0);\n\tTID baseId = bases[0];\n\tGameEntity* pBase = g_Game->Self()->GetEntity(baseId);\n\n\tif (pBase == nullptr)\n\t\tpBase = g_Game->Enemy()->GetEntity(baseId);\n\n\tassert(pBase);\n\n\tdistance = cellWorldPosition.Distance(pBase->GetPosition());\n}\n\/\/----------------------------------------------------------------------------------------------\nfloat CellFeature::GetBaseDistance(double firstBase, double secondBase) const\n{\n\treturn pow((float)(firstBase - secondBase), 2);\n}<|endoftext|>"} {"text":"#include \"stdafx.h\"\n#include \"CppUnitTest.h\"\n#include \"..\\ProjectEuler\\Problem1.h\"\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\n\nnamespace ProjectEulerTests\n{\t\t\n\tTEST_CLASS(Problem1Tests)\n\t{\n\tpublic:\n\t\t\n\t\tTEST_METHOD(SumMultiplesOf3And5Below_Input0_Returns0)\n\t\t{\n auto result = Problem1::SumMultiplesOf3And5Below(0);\n Assert::AreEqual(0, result);\n\t\t}\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input1_Returns0)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(1);\n Assert::AreEqual(0, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input2_Returns0)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(2);\n Assert::AreEqual(0, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input3_Returns0)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(3);\n Assert::AreEqual(0, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input4_Returns3)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(4);\n Assert::AreEqual(3, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input5_Returns3)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(5);\n Assert::AreEqual(3, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input6_Returns8)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(6);\n Assert::AreEqual(8, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input7_Returns14)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(7);\n Assert::AreEqual(14, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input8_Returns14)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(8);\n Assert::AreEqual(14, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input9_Returns14)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(9);\n Assert::AreEqual(14, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input10_Returns23)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(10);\n Assert::AreEqual(23, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input100_Returns2318)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(100);\n Assert::AreEqual(2318, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input1000_Returns233168)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(1000);\n Assert::AreEqual(233168, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input10000_Returns23331668)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(10000);\n Assert::AreEqual(23331668, result);\n }\n\n TEST_METHOD(SumBelow_Input0_Returns0)\n {\n auto result = Problem1::SumBelow(0);\n Assert::AreEqual(0L, result);\n }\n\n TEST_METHOD(SumBelow_Input1_Returns0)\n {\n auto result = Problem1::SumBelow(1);\n Assert::AreEqual(0L, result);\n }\n\n TEST_METHOD(SumBelow_Input2_Returns1)\n {\n auto result = Problem1::SumBelow(2);\n Assert::AreEqual(1L, result);\n }\n\n TEST_METHOD(SumBelow_Input3_Returns3)\n {\n auto result = Problem1::SumBelow(3);\n Assert::AreEqual(3L, result);\n }\n\n TEST_METHOD(SumBelow_Input4_Returns6)\n {\n auto result = Problem1::SumBelow(4);\n Assert::AreEqual(6L, result);\n }\n\n TEST_METHOD(SumBelow_Input5_Returns10)\n {\n auto result = Problem1::SumBelow(5);\n Assert::AreEqual(10L, result);\n }\n\n TEST_METHOD(SumBelow_Input6_Returns15)\n {\n auto result = Problem1::SumBelow(6);\n Assert::AreEqual(15L, result);\n }\n\n TEST_METHOD(SumBelow_Input7_Returns21)\n {\n auto result = Problem1::SumBelow(7);\n Assert::AreEqual(21L, result);\n }\n\n TEST_METHOD(SumBelow_Input8_Returns28)\n {\n auto result = Problem1::SumBelow(8);\n Assert::AreEqual(28L, result);\n }\n\n TEST_METHOD(SumBelow_Input9_Returns36)\n {\n auto result = Problem1::SumBelow(9);\n Assert::AreEqual(36L, result);\n }\n\n TEST_METHOD(SumBelow_Input10_Returns45)\n {\n auto result = Problem1::SumBelow(10);\n Assert::AreEqual(45L, result);\n }\n\n TEST_METHOD(SumBelow_Input100_Returns4950)\n {\n auto result = Problem1::SumBelow(100);\n Assert::AreEqual(4950L, result);\n }\n\n TEST_METHOD(SumBelow_Input100000_Returns704982704)\n {\n auto result = Problem1::SumBelow(100000);\n Assert::AreEqual(704982704L, result);\n }\n\n TEST_METHOD(SumDivisibleBy_Input3and0_Returns0)\n {\n auto result = Problem1::SumDivisibleBy(3, 0L);\n Assert::AreEqual(0L, result);\n }\n\n TEST_METHOD(SumDivisibleBy_Input3and1_Returns0)\n {\n auto result = Problem1::SumDivisibleBy(3, 1L);\n Assert::AreEqual(0L, result);\n }\n\n TEST_METHOD(SumDivisibleBy_Input3and2_Returns0)\n {\n auto result = Problem1::SumDivisibleBy(3, 2L);\n Assert::AreEqual(0L, result);\n }\n\n TEST_METHOD(SumDivisibleBy_Input3and3_Returns0)\n {\n auto result = Problem1::SumDivisibleBy(3, 3L);\n Assert::AreEqual(0L, result);\n }\n\n TEST_METHOD(SumDivisibleBy_Input3and4_Returns3)\n {\n auto result = Problem1::SumDivisibleBy(3, 4L);\n Assert::AreEqual(3L, result);\n }\n\n TEST_METHOD(SumDivisibleBy_Input5and0_Returns0)\n {\n auto result = Problem1::SumDivisibleBy(5, 0L);\n Assert::AreEqual(0L, result);\n }\n\n TEST_METHOD(SumDivisibleBy_Input5and1_Returns0)\n {\n auto result = Problem1::SumDivisibleBy(5, 1L);\n Assert::AreEqual(0L, result);\n }\n\n TEST_METHOD(SumDivisibleBy_Input5and2_Returns0)\n {\n auto result = Problem1::SumDivisibleBy(5, 2L);\n Assert::AreEqual(0L, result);\n }\n\n TEST_METHOD(SumDivisibleBy_Input5and3_Returns0)\n {\n auto result = Problem1::SumDivisibleBy(5, 3L);\n Assert::AreEqual(0L, result);\n }\n\t};\n}red-commit - SumDivisibleBy_Input5and4_Returns0#include \"stdafx.h\"\n#include \"CppUnitTest.h\"\n#include \"..\\ProjectEuler\\Problem1.h\"\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\n\nnamespace ProjectEulerTests\n{\t\t\n\tTEST_CLASS(Problem1Tests)\n\t{\n\tpublic:\n\t\t\n\t\tTEST_METHOD(SumMultiplesOf3And5Below_Input0_Returns0)\n\t\t{\n auto result = Problem1::SumMultiplesOf3And5Below(0);\n Assert::AreEqual(0, result);\n\t\t}\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input1_Returns0)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(1);\n Assert::AreEqual(0, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input2_Returns0)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(2);\n Assert::AreEqual(0, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input3_Returns0)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(3);\n Assert::AreEqual(0, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input4_Returns3)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(4);\n Assert::AreEqual(3, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input5_Returns3)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(5);\n Assert::AreEqual(3, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input6_Returns8)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(6);\n Assert::AreEqual(8, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input7_Returns14)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(7);\n Assert::AreEqual(14, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input8_Returns14)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(8);\n Assert::AreEqual(14, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input9_Returns14)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(9);\n Assert::AreEqual(14, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input10_Returns23)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(10);\n Assert::AreEqual(23, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input100_Returns2318)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(100);\n Assert::AreEqual(2318, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input1000_Returns233168)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(1000);\n Assert::AreEqual(233168, result);\n }\n\n TEST_METHOD(SumMultiplesOf3And5Below_Input10000_Returns23331668)\n {\n auto result = Problem1::SumMultiplesOf3And5Below(10000);\n Assert::AreEqual(23331668, result);\n }\n\n TEST_METHOD(SumBelow_Input0_Returns0)\n {\n auto result = Problem1::SumBelow(0);\n Assert::AreEqual(0L, result);\n }\n\n TEST_METHOD(SumBelow_Input1_Returns0)\n {\n auto result = Problem1::SumBelow(1);\n Assert::AreEqual(0L, result);\n }\n\n TEST_METHOD(SumBelow_Input2_Returns1)\n {\n auto result = Problem1::SumBelow(2);\n Assert::AreEqual(1L, result);\n }\n\n TEST_METHOD(SumBelow_Input3_Returns3)\n {\n auto result = Problem1::SumBelow(3);\n Assert::AreEqual(3L, result);\n }\n\n TEST_METHOD(SumBelow_Input4_Returns6)\n {\n auto result = Problem1::SumBelow(4);\n Assert::AreEqual(6L, result);\n }\n\n TEST_METHOD(SumBelow_Input5_Returns10)\n {\n auto result = Problem1::SumBelow(5);\n Assert::AreEqual(10L, result);\n }\n\n TEST_METHOD(SumBelow_Input6_Returns15)\n {\n auto result = Problem1::SumBelow(6);\n Assert::AreEqual(15L, result);\n }\n\n TEST_METHOD(SumBelow_Input7_Returns21)\n {\n auto result = Problem1::SumBelow(7);\n Assert::AreEqual(21L, result);\n }\n\n TEST_METHOD(SumBelow_Input8_Returns28)\n {\n auto result = Problem1::SumBelow(8);\n Assert::AreEqual(28L, result);\n }\n\n TEST_METHOD(SumBelow_Input9_Returns36)\n {\n auto result = Problem1::SumBelow(9);\n Assert::AreEqual(36L, result);\n }\n\n TEST_METHOD(SumBelow_Input10_Returns45)\n {\n auto result = Problem1::SumBelow(10);\n Assert::AreEqual(45L, result);\n }\n\n TEST_METHOD(SumBelow_Input100_Returns4950)\n {\n auto result = Problem1::SumBelow(100);\n Assert::AreEqual(4950L, result);\n }\n\n TEST_METHOD(SumBelow_Input100000_Returns704982704)\n {\n auto result = Problem1::SumBelow(100000);\n Assert::AreEqual(704982704L, result);\n }\n\n TEST_METHOD(SumDivisibleBy_Input3and0_Returns0)\n {\n auto result = Problem1::SumDivisibleBy(3, 0L);\n Assert::AreEqual(0L, result);\n }\n\n TEST_METHOD(SumDivisibleBy_Input3and1_Returns0)\n {\n auto result = Problem1::SumDivisibleBy(3, 1L);\n Assert::AreEqual(0L, result);\n }\n\n TEST_METHOD(SumDivisibleBy_Input3and2_Returns0)\n {\n auto result = Problem1::SumDivisibleBy(3, 2L);\n Assert::AreEqual(0L, result);\n }\n\n TEST_METHOD(SumDivisibleBy_Input3and3_Returns0)\n {\n auto result = Problem1::SumDivisibleBy(3, 3L);\n Assert::AreEqual(0L, result);\n }\n\n TEST_METHOD(SumDivisibleBy_Input3and4_Returns3)\n {\n auto result = Problem1::SumDivisibleBy(3, 4L);\n Assert::AreEqual(3L, result);\n }\n\n TEST_METHOD(SumDivisibleBy_Input5and0_Returns0)\n {\n auto result = Problem1::SumDivisibleBy(5, 0L);\n Assert::AreEqual(0L, result);\n }\n\n TEST_METHOD(SumDivisibleBy_Input5and1_Returns0)\n {\n auto result = Problem1::SumDivisibleBy(5, 1L);\n Assert::AreEqual(0L, result);\n }\n\n TEST_METHOD(SumDivisibleBy_Input5and2_Returns0)\n {\n auto result = Problem1::SumDivisibleBy(5, 2L);\n Assert::AreEqual(0L, result);\n }\n\n TEST_METHOD(SumDivisibleBy_Input5and3_Returns0)\n {\n auto result = Problem1::SumDivisibleBy(5, 3L);\n Assert::AreEqual(0L, result);\n }\n\n TEST_METHOD(SumDivisibleBy_Input5and4_Returns0)\n {\n auto result = Problem1::SumDivisibleBy(5, 4L);\n Assert::AreEqual(0L, result);\n }\n\t};\n}<|endoftext|>"} {"text":"\/*\n * This file is part of TelepathyQt4\n *\n * Copyright (C) 2010 Collabora Ltd. \n * Copyright (C) 2010 Nokia Corporation\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \n#include \"TelepathyQt4\/dbus-proxy-factory-internal.h\"\n\n#include \"TelepathyQt4\/_gen\/dbus-proxy-factory-internal.moc.hpp\"\n\n#include \"TelepathyQt4\/debug-internal.h\"\n\n#include \n#include \n#include \n\n#include \n\nnamespace Tp\n{\n\nstruct DBusProxyFactory::Private\n{\n Private(const QDBusConnection &bus)\n : bus(bus), cache(new Cache) {}\n\n ~Private()\n {\n delete cache;\n }\n\n QDBusConnection bus;\n Cache *cache;\n};\n\n\/**\n * \\class DBusProxyFactory\n * \\ingroup clientreadiness\n * \\headerfile TelepathyQt4\/dbus-proxy-factory.h \n *\n * Base class for all D-Bus proxy factory classes. Handles proxy caching and making them ready as\n * appropriate.\n *\/\n\n\/**\n * Class constructor.\n *\n * The intention for storing the bus here is that it generally doesn't make sense to construct\n * proxies for multiple buses in the same context. Allowing that would lead to more complex keying\n * needs in the cache, as well.\n *\n * \\param bus The D-Bus bus connection for the objects constructed using this factory.\n *\/\nDBusProxyFactory::DBusProxyFactory(const QDBusConnection &bus)\n : mPriv(new Private(bus))\n{\n}\n\n\/**\n * Class destructor.\n *\/\nDBusProxyFactory::~DBusProxyFactory()\n{\n delete mPriv;\n}\n\n\/**\n * Returns the D-Bus connection all of the proxies from this factory communicate with.\n *\n * \\return The connection.\n *\/\nconst QDBusConnection &DBusProxyFactory::dbusConnection() const\n{\n return mPriv->bus;\n}\n\n\/**\n * Returns a cached proxy with the given \\a busName and \\a objectPath.\n *\n * If a proxy has not been previously put into the cache by nowHaveProxy for those identifying\n * attributes, or a previously cached proxy has since been invalidated and\/or destroyed, a \\c Null\n * shared pointer is returned instead.\n *\n * \\param busName Bus name of the proxy to return.\n * \\param objectPath Object path of the proxy to return.\n * \\return The proxy, if any.\n *\/\nSharedPtr DBusProxyFactory::cachedProxy(const QString &busName,\n const QString &objectPath) const\n{\n QString finalName = finalBusNameFrom(busName);\n return mPriv->cache->get(Cache::Key(finalName, objectPath));\n}\n\n\/**\n * Should be called by subclasses when they have a proxy, be it a newly-constructed one or one from\n * the cache.\n *\n * This function will then do the rest of the factory work, including caching the proxy if it's not\n * cached already, doing any prepare() work if appropriate, and making the features from\n * featuresFor() ready if they aren't already.\n *\n * The returned PendingReady only finishes when the prepare() operation for the proxy has completed,\n * and the requested features have all been made ready (or found unable to be made ready). Note that\n * this might have happened already before calling this function, if the proxy was not a newly\n * created one, but was looked up from the cache. DBusProxyFactory handles the necessary subleties\n * for this to work.\n *\n * Access to the proxy instance is allowed as soon as this method returns through\n * PendingReady::proxy(), if the proxy is needed in a context where it's not required to be ready.\n *\n * \\param proxy The proxy which the factory should now make sure is prepared and made ready.\n * \\return Readifying operation, which finishes when the proxy is usable.\n *\/\nPendingReady *DBusProxyFactory::nowHaveProxy(const SharedPtr &proxy) const\n{\n Q_ASSERT(!proxy.isNull());\n\n \/\/ I really hate the casts needed in this function - we must really do something about the\n \/\/ DBusProxy class hierarchy so that every DBusProxy(Something) is always a ReadyObject and a\n \/\/ RefCounted, in the API\/ABI break - then most of these proxyMisc-> things become just proxy->\n\n ReadyObject *proxyReady = dynamic_cast(proxy.data());\n Q_ASSERT(proxyReady != NULL);\n\n Features specificFeatures = featuresFor(proxy);\n\n \/\/ FIXME: prepare currently doesn't work\n PendingOperation *prepareOp = NULL;\n\n mPriv->cache->put(proxy);\n\n if (prepareOp || (!specificFeatures.isEmpty() && !proxyReady->isReady(specificFeatures))) {\n return new PendingReady(prepareOp, specificFeatures, proxy, 0);\n }\n\n \/\/ No features requested or they are all ready - optimize a bit by not calling ReadinessHelper\n PendingReady *readyOp = new PendingReady(0, specificFeatures, proxy, 0);\n readyOp->setFinished();\n return readyOp;\n}\n\n\/**\n * Allows subclasses to do arbitrary manipulation on the object before it is attempted to be made\n * ready.\n *\n * If a non-\\c NULL operation is returned, the completion of that operation is waited for before\n * starting to make the object ready whenever nowHaveProxy() is called the first time around for a\n * given proxy.\n *\n * \\return \\c NULL ie. nothing to do.\n *\/\nPendingOperation *DBusProxyFactory::prepare(const SharedPtr &object) const\n{\n \/\/ Nothing we could think about needs doing\n return NULL;\n}\n\nDBusProxyFactory::Cache::Cache()\n{\n}\n\nDBusProxyFactory::Cache::~Cache()\n{\n}\n\nSharedPtr DBusProxyFactory::Cache::get(const Key &key) const\n{\n SharedPtr counted(proxies.value(key));\n\n \/\/ We already assert for it being a DBusProxy in put()\n if (!counted || !dynamic_cast(counted.data())->isValid()) {\n \/\/ Weak pointer invalidated or proxy invalidated during this mainloop iteration and we still\n \/\/ haven't got the invalidated() signal for it\n return SharedPtr();\n }\n\n return counted;\n}\n\nvoid DBusProxyFactory::Cache::put(const SharedPtr &obj)\n{\n DBusProxy *proxyProxy = dynamic_cast(obj.data());\n Q_ASSERT(proxyProxy != NULL);\n\n Key key(proxyProxy->busName(), proxyProxy->objectPath());\n\n SharedPtr existingProxy = SharedPtr(proxies.value(key));\n if (!existingProxy || existingProxy != obj) {\n connect(proxyProxy,\n SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),\n SLOT(onProxyInvalidated(Tp::DBusProxy*)));\n\n debug() << \"Inserting to factory cache proxy for\" << key;\n proxies.insert(key, obj);\n }\n}\n\nvoid DBusProxyFactory::Cache::onProxyInvalidated(Tp::DBusProxy *proxy)\n{\n Key key(proxy->busName(), proxy->objectPath());\n\n \/\/ Not having it would indicate invalidated() signaled twice for the same proxy, or us having\n \/\/ connected to two proxies with the same key, neither of which should happen\n Q_ASSERT(proxies.contains(key));\n\n debug() << \"Removing from factory cache invalidated proxy for\" << key;\n\n proxies.remove(key);\n}\n\n}\nWarn in DBusProxyFactory docs that prepare() is not currently really used\/*\n * This file is part of TelepathyQt4\n *\n * Copyright (C) 2010 Collabora Ltd. \n * Copyright (C) 2010 Nokia Corporation\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \n#include \"TelepathyQt4\/dbus-proxy-factory-internal.h\"\n\n#include \"TelepathyQt4\/_gen\/dbus-proxy-factory-internal.moc.hpp\"\n\n#include \"TelepathyQt4\/debug-internal.h\"\n\n#include \n#include \n#include \n\n#include \n\nnamespace Tp\n{\n\nstruct DBusProxyFactory::Private\n{\n Private(const QDBusConnection &bus)\n : bus(bus), cache(new Cache) {}\n\n ~Private()\n {\n delete cache;\n }\n\n QDBusConnection bus;\n Cache *cache;\n};\n\n\/**\n * \\class DBusProxyFactory\n * \\ingroup clientreadiness\n * \\headerfile TelepathyQt4\/dbus-proxy-factory.h \n *\n * Base class for all D-Bus proxy factory classes. Handles proxy caching and making them ready as\n * appropriate.\n *\/\n\n\/**\n * Class constructor.\n *\n * The intention for storing the bus here is that it generally doesn't make sense to construct\n * proxies for multiple buses in the same context. Allowing that would lead to more complex keying\n * needs in the cache, as well.\n *\n * \\param bus The D-Bus bus connection for the objects constructed using this factory.\n *\/\nDBusProxyFactory::DBusProxyFactory(const QDBusConnection &bus)\n : mPriv(new Private(bus))\n{\n}\n\n\/**\n * Class destructor.\n *\/\nDBusProxyFactory::~DBusProxyFactory()\n{\n delete mPriv;\n}\n\n\/**\n * Returns the D-Bus connection all of the proxies from this factory communicate with.\n *\n * \\return The connection.\n *\/\nconst QDBusConnection &DBusProxyFactory::dbusConnection() const\n{\n return mPriv->bus;\n}\n\n\/**\n * Returns a cached proxy with the given \\a busName and \\a objectPath.\n *\n * If a proxy has not been previously put into the cache by nowHaveProxy for those identifying\n * attributes, or a previously cached proxy has since been invalidated and\/or destroyed, a \\c Null\n * shared pointer is returned instead.\n *\n * \\param busName Bus name of the proxy to return.\n * \\param objectPath Object path of the proxy to return.\n * \\return The proxy, if any.\n *\/\nSharedPtr DBusProxyFactory::cachedProxy(const QString &busName,\n const QString &objectPath) const\n{\n QString finalName = finalBusNameFrom(busName);\n return mPriv->cache->get(Cache::Key(finalName, objectPath));\n}\n\n\/**\n * Should be called by subclasses when they have a proxy, be it a newly-constructed one or one from\n * the cache.\n *\n * This function will then do the rest of the factory work, including caching the proxy if it's not\n * cached already, doing any prepare() work if appropriate, and making the features from\n * featuresFor() ready if they aren't already.\n *\n * The returned PendingReady only finishes when the prepare() operation for the proxy has completed,\n * and the requested features have all been made ready (or found unable to be made ready). Note that\n * this might have happened already before calling this function, if the proxy was not a newly\n * created one, but was looked up from the cache. DBusProxyFactory handles the necessary subleties\n * for this to work.\n *\n * Access to the proxy instance is allowed as soon as this method returns through\n * PendingReady::proxy(), if the proxy is needed in a context where it's not required to be ready.\n *\n * \\param proxy The proxy which the factory should now make sure is prepared and made ready.\n * \\return Readifying operation, which finishes when the proxy is usable.\n *\/\nPendingReady *DBusProxyFactory::nowHaveProxy(const SharedPtr &proxy) const\n{\n Q_ASSERT(!proxy.isNull());\n\n \/\/ I really hate the casts needed in this function - we must really do something about the\n \/\/ DBusProxy class hierarchy so that every DBusProxy(Something) is always a ReadyObject and a\n \/\/ RefCounted, in the API\/ABI break - then most of these proxyMisc-> things become just proxy->\n\n ReadyObject *proxyReady = dynamic_cast(proxy.data());\n Q_ASSERT(proxyReady != NULL);\n\n Features specificFeatures = featuresFor(proxy);\n\n \/\/ FIXME: prepare currently doesn't work\n PendingOperation *prepareOp = NULL;\n\n mPriv->cache->put(proxy);\n\n if (prepareOp || (!specificFeatures.isEmpty() && !proxyReady->isReady(specificFeatures))) {\n return new PendingReady(prepareOp, specificFeatures, proxy, 0);\n }\n\n \/\/ No features requested or they are all ready - optimize a bit by not calling ReadinessHelper\n PendingReady *readyOp = new PendingReady(0, specificFeatures, proxy, 0);\n readyOp->setFinished();\n return readyOp;\n}\n\n\/**\n * Allows subclasses to do arbitrary manipulation on the object before it is attempted to be made\n * ready.\n *\n * If a non-\\c NULL operation is returned, the completion of that operation is waited for before\n * starting to make the object ready whenever nowHaveProxy() is called the first time around for a\n * given proxy.\n *\n * \\todo FIXME actually implement this... :)\n * \\return \\c NULL ie. nothing to do.\n *\/\nPendingOperation *DBusProxyFactory::prepare(const SharedPtr &object) const\n{\n \/\/ Nothing we could think about needs doing\n return NULL;\n}\n\nDBusProxyFactory::Cache::Cache()\n{\n}\n\nDBusProxyFactory::Cache::~Cache()\n{\n}\n\nSharedPtr DBusProxyFactory::Cache::get(const Key &key) const\n{\n SharedPtr counted(proxies.value(key));\n\n \/\/ We already assert for it being a DBusProxy in put()\n if (!counted || !dynamic_cast(counted.data())->isValid()) {\n \/\/ Weak pointer invalidated or proxy invalidated during this mainloop iteration and we still\n \/\/ haven't got the invalidated() signal for it\n return SharedPtr();\n }\n\n return counted;\n}\n\nvoid DBusProxyFactory::Cache::put(const SharedPtr &obj)\n{\n DBusProxy *proxyProxy = dynamic_cast(obj.data());\n Q_ASSERT(proxyProxy != NULL);\n\n Key key(proxyProxy->busName(), proxyProxy->objectPath());\n\n SharedPtr existingProxy = SharedPtr(proxies.value(key));\n if (!existingProxy || existingProxy != obj) {\n connect(proxyProxy,\n SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),\n SLOT(onProxyInvalidated(Tp::DBusProxy*)));\n\n debug() << \"Inserting to factory cache proxy for\" << key;\n proxies.insert(key, obj);\n }\n}\n\nvoid DBusProxyFactory::Cache::onProxyInvalidated(Tp::DBusProxy *proxy)\n{\n Key key(proxy->busName(), proxy->objectPath());\n\n \/\/ Not having it would indicate invalidated() signaled twice for the same proxy, or us having\n \/\/ connected to two proxies with the same key, neither of which should happen\n Q_ASSERT(proxies.contains(key));\n\n debug() << \"Removing from factory cache invalidated proxy for\" << key;\n\n proxies.remove(key);\n}\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nchar proc_char(char c)\n{\n if (c == -127) c = -111;\n else if (c <= -81) c += 32;\n if (c >= -74) c++;\n if (c == -111) c = -74;\n return c; \n}\n\nbool cmp(char c1, char c2)\n{\n if ((c1 == -48 || c1 == -47) && (c2 == -48 || c2 == -47)) return false;\n return proc_char(c1) < proc_char(c2);\n}\n\nint main()\n{\n int n;\n string s; \n cin >> n;\n list lst;\n for (int i = 0; i< n; i++)\n {\n cin >> s;\n lst.push_back(s);\n }\n lst.sort();\n lst.reverse();\n\n cout << \"\\nSorted + reversed:\\n\";\n for (auto i = lst.begin(); i != lst.end(); i++)\n cout << *i << endl;\n\n cout << \"\\nRemoved strings with digits in first place:\\n\";\n\n lst.remove_if([](string& s){return isdigit(s[0]);});\n\n for (auto i = lst.begin(); i != lst.end(); i++)\n cout << *i << endl;\n\n cout << \"\\nRussian strings sorted properly:\\n\";\n\n lst.sort([](string& s1, string& s2){return lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), cmp);});\n\n for (auto i = lst.begin(); i != lst.end(); i++)\n cout << *i << endl;\n\n \n return 0;\n}\nAdded copyright\/*\n Copyright (c) 2017 Maxim Teryokhin\n This code is licensed under MIT. See LICENSE file for more details.\n*\/\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nchar proc_char(char c)\n{\n if (c == -127) c = -111;\n else if (c <= -81) c += 32;\n if (c >= -74) c++;\n if (c == -111) c = -74;\n return c; \n}\n\nbool cmp(char c1, char c2)\n{\n if ((c1 == -48 || c1 == -47) && (c2 == -48 || c2 == -47)) return false;\n return proc_char(c1) < proc_char(c2);\n}\n\nint main()\n{\n int n;\n string s; \n cin >> n;\n list lst;\n for (int i = 0; i< n; i++)\n {\n cin >> s;\n lst.push_back(s);\n }\n lst.sort();\n lst.reverse();\n\n cout << \"\\nSorted + reversed:\\n\";\n for (auto i = lst.begin(); i != lst.end(); i++)\n cout << *i << endl;\n\n cout << \"\\nRemoved strings with digits in first place:\\n\";\n\n lst.remove_if([](string& s){return isdigit(s[0]);});\n\n for (auto i = lst.begin(); i != lst.end(); i++)\n cout << *i << endl;\n\n cout << \"\\nRussian strings sorted properly:\\n\";\n\n lst.sort([](string& s1, string& s2){return lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), cmp);});\n\n for (auto i = lst.begin(); i != lst.end(); i++)\n cout << *i << endl;\n\n \n return 0;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ SRTerrain class : a subclass of vtDynTerrainGeom which encapsulates\n\/\/ Stefan Roettger's CLOD algorithm.\n\/\/\n\/\/ utilizes: Roettger's MINI library implementation\n\/\/ http:\/\/wwwvis.informatik.uni-stuttgart.de\/~roettger\n\/\/\n\/\/ Copyright (c) 2002-2004 Virtual Terrain Project\n\/\/ Free for all uses, see license.txt for details.\n\/\/\n\n#include \"vtlib\/vtlib.h\"\n#include \"SRTerrain.h\"\n#include \"vtdata\/vtLog.h\"\n\n#if VTLIB_NI\n\/\/ stub\nSRTerrain::SRTerrain() {}\nSRTerrain::~SRTerrain() {}\nfloat SRTerrain::GetElevation(int iX, int iZ, bool bTrue) const { return 0; }\nvoid SRTerrain::GetWorldLocation(int i, int j, FPoint3 &p, bool bTrue) const {}\nvoid SRTerrain::DoCulling(const vtCamera *pCam) {}\nvoid SRTerrain::DoRender() {}\nvoid SRTerrain::SetVerticalExag(float fExag) {}\nDTErr SRTerrain::Init(const vtElevationGrid *pGrid, float fZScale) { return DTErr_NOMEM; }\n#else\n\n#include \"mini.h\"\n#include \"ministub.hpp\"\n\nusing namespace mini;\n#ifdef _MSC_VER\n#pragma comment( lib, \"libMini.lib\" )\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\n\/\/ Constructor\/destructor\n\/\/\nSRTerrain::SRTerrain() : vtDynTerrainGeom()\n{\n\tm_fResolution\t= 10000.0f;\n\tm_fHResolution\t= 20000.0f;\n\tm_fLResolution\t= 0.0f;\n\tm_pMini = NULL;\n}\n\nSRTerrain::~SRTerrain()\n{\n\tif (m_pMini)\n\t{\n\t\tdelete m_pMini;\n\t\tm_pMini = NULL;\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\n\/\/ Unfortunately the following statics are required because libMini only\n\/\/ supports some functionality by callback, and the callback is only a\n\/\/ simple C function which has no context to tell us which terrain.\n\/\/\nstatic const vtElevationGrid *s_pGrid;\nstatic SRTerrain *s_pSRTerrain;\nstatic int myfancnt, myvtxcnt;\n\nvoid beginfan_vtp()\n{\n\tif (myfancnt++>0)\n\t\tglEnd();\n\tglBegin(GL_TRIANGLE_FAN);\n\tmyvtxcnt-=2;\t\/\/ 2 vertices are needed to start each fan\n}\n\nvoid fanvertex_vtp(float x, float y, float z)\n{\n\tglVertex3f(x,y,z);\n\tmyvtxcnt++;\n}\n\nvoid notify_vtp(int i, int j, int size)\n{\n\t\/\/ check to see if we need to switch texture\n\tif (s_pSRTerrain->m_iTPatchDim > 1 && size == s_pSRTerrain->m_iBlockSize)\n\t{\n\t\tint a = i \/ size;\n\t\tint b = j \/ size;\n\t\ts_pSRTerrain->LoadBlockMaterial(a, b);\n\t}\n}\n\nshort int getelevation_vtp1(int i, int j, int size)\n{\n\treturn s_pGrid->GetValue(i, j);\n}\n\nfloat getelevation_vtp2(int i, int j, int size)\n{\n\treturn s_pGrid->GetFValue(i, j);\n}\n\n\/\/\n\/\/ Initialize the terrain data\n\/\/ fZScale converts from height values (meters) to world coordinates\n\/\/\nDTErr SRTerrain::Init(const vtElevationGrid *pGrid, float fZScale)\n{\n\t\/\/ Initializes necessary field of the parent class\n\tDTErr err = BasicInit(pGrid);\n\tif (err != DTErr_OK)\n\t\treturn err;\n\n\tif (m_iColumns != m_iRows)\n\t\treturn DTErr_NOTSQUARE;\n\n\t\/\/ compute n (log2 of grid size)\n\t\/\/ ensure that the grid is size (1 << n) + 1\n\tint n = vt_log2(m_iColumns - 1);\n\tint required_size = (1< 967)\n\t\/\/\n\t\/\/ \tscale * maximum_height \/ dim > 967\n\t\/\/\tscale > dim * 967 \/ maximum_height\n\t\/\/\n\tfloat fMin, fMax;\n\tpGrid->GetHeightExtents(fMin, fMax);\n\t\/\/ Avoid trouble with fMax small or zero\n\tif (fMax < 10) fMax = 10;\n\t\/\/ compute the largest supported value for MaxScale\n\tfloat fMaxMax = dim * 960 \/ fMax;\n\t\/\/ values greater than 10 are unnecessarily large\n\tif (fMaxMax > 10)\n\t\tfMaxMax = 10;\n\tm_fMaximumScale = fMaxMax;\n#else\n\t\/\/ This maxiumum scale is a reasonable tradeoff between the exaggeration\n\t\/\/ that the user is likely to need, and numerical precision issues.\n\tm_fMaximumScale = 10;\n#endif\n\n\tm_fHeightScale = fZScale;\n\tm_fDrawScale = m_fHeightScale \/ m_fMaximumScale;\n\n\tif (pGrid->IsFloatMode())\n\t{\n\t\tfloat *image = NULL;\n\t\tm_pMini = new ministub(image,\n\t\t\t\t&size, &dim, m_fMaximumScale, cellaspect,\n\t\t\t\tbeginfan_vtp, fanvertex_vtp, notify_vtp,\n\t\t\t\tgetelevation_vtp2);\n\t}\n\telse\n\t{\n\t\tshort *image = NULL;\n\t\tm_pMini = new ministub(image,\n\t\t\t\t&size, &dim, m_fMaximumScale, cellaspect,\n\t\t\t\tbeginfan_vtp, fanvertex_vtp, notify_vtp,\n\t\t\t\tgetelevation_vtp1);\n\t}\n\n\tm_iDrawnTriangles = -1;\n\tm_iBlockSize = m_iColumns \/ 4;\n\n\treturn DTErr_OK;\n}\n\nvoid SRTerrain::SetVerticalExag(float fExag)\n{\n\tm_fHeightScale = fExag;\n\n\t\/\/ safety check\n\tif (m_fHeightScale > m_fMaximumScale)\n\t\tm_fHeightScale = m_fMaximumScale;\n\n\tm_fDrawScale = m_fHeightScale \/ m_fMaximumScale;\n}\n\n\n\/\/\n\/\/ This will be called once per frame, during the culling pass.\n\/\/\n\/\/ However, libMini does not allow you to call the culling pass\n\/\/ independently of the rendering pass, so we cannot do culling here.\n\/\/ Instead, just store the values for later use.\n\/\/\nvoid SRTerrain::DoCulling(const vtCamera *pCam)\n{\n\t\/\/ Grab necessary values from the VTP Scene framework, store for later\n\tm_eyepos_ogl = pCam->GetTrans();\n\tm_window_size = vtGetScene()->GetWindowSize();\n\tm_fAspect = (float)m_window_size.x \/ m_window_size.y;\n\tm_fNear = pCam->GetHither();\n\tm_fFar = pCam->GetYon();\n\n\t\/\/ Get up vector and direction vector from camera matrix\n\tFMatrix4 mat;\n\tpCam->GetTransform1(mat);\n\tFPoint3 up(0.0f, 1.0f, 0.0f);\n\tmat.TransformVector(up, eye_up);\n\n\tFPoint3 forward(0.0f, 0.0f, -1.0f);\n\tmat.TransformVector(forward, eye_forward);\n\n\tif (pCam->IsOrtho())\n\t{\n\t\t\/\/ libMini supports orthographic viewing as of libMini 5.0.\n\t\t\/\/ A negative FOV value indicates to the library that the FOV is\n\t\t\/\/ actually the orthographic height of the camera.\n\t\tm_fFOVY = pCam->GetWidth() \/ m_fAspect;\n\t\tm_fFOVY = -m_fFOVY;\n\t}\n\telse\n\t{\n\t\tfloat fov = pCam->GetFOV();\n\t\tfloat fov_y2 = atan(tan (fov\/2) \/ m_fAspect);\n\t\tm_fFOVY = fov_y2 * 2.0f * 180 \/ PIf;\n\t}\n}\n\n\nvoid SRTerrain::DoRender()\n{\n\t\/\/ Prepare the render state for our OpenGL usage\n\tPreRender();\n\n\t\/\/ Render the triangles\n\tRenderSurface();\n\n\t\/\/ Clean up\n\tPostRender();\n}\n\n\nvoid SRTerrain::LoadSingleMaterial()\n{\n\t\/\/ single texture for the whole terrain\n\tvtMaterial *pMat = GetMaterial(0);\n\tif (pMat)\n\t{\n\t\tpMat->Apply();\n\t\tSetupTexGen(1.0f);\n\t}\n}\n\n\nvoid SRTerrain::LoadBlockMaterial(int a, int b)\n{\n\t\/\/ we can't change the texture between glBegin\/glEnd\n\tif (myfancnt++>0)\n\t\tglEnd();\n\n\t\/\/ each block has it's own texture map\n\tint matidx = a*m_iTPatchDim + (m_iTPatchDim-1-b);\n\tvtMaterial *pMat = GetMaterial(matidx);\n\tif (pMat)\n\t{\n\t\tpMat->Apply();\n\t\tSetupBlockTexGen(a, b);\n\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\t}\n\n\tglBegin(GL_TRIANGLE_FAN);\n}\n\n\nvoid SRTerrain::RenderSurface()\n{\n\ts_pSRTerrain = this;\n\n\tif (m_iTPatchDim == 1)\n\t\tLoadSingleMaterial();\n\n\tRenderPass();\n\n\t\/\/ how to do a second rendering pass\n\tif (m_bDetailTexture)\n\t{\n\t\t\/\/ once again, with the detail texture material\n\t\tm_pDetailMat->Apply();\n\n\t\t\/\/ the uv tiling is different (usually highly repetitive)\n\t\tSetupTexGen(m_fDetailTiling);\n\n\t\t\/\/ draw the second pass\n\t\tglPolygonOffset(-1.0f, -1.0f);\n\t\tglEnable(GL_POLYGON_OFFSET_FILL);\n\t\tRenderPass();\n\t\tglDisable(GL_POLYGON_OFFSET_FILL);\n\t}\n\tDisableTexGen();\n}\n\n\nvoid SRTerrain::RenderPass()\n{\n\tfloat ex = m_eyepos_ogl.x;\n\tfloat ey = m_eyepos_ogl.y;\n\tfloat ez = m_eyepos_ogl.z;\n\n\tfloat fov = m_fFOVY;\n\n\tfloat ux = eye_up.x;\n\tfloat uy = eye_up.y;\n\tfloat uz = eye_up.z;\n\n\tfloat dx = eye_forward.x;\n\tfloat dy = eye_forward.y;\n\tfloat dz = eye_forward.z;\n\n\tmyfancnt = myvtxcnt = 0;\n\n\t\/\/ Convert the eye location to the unusual coordinate scheme of libMini.\n\tex -= (m_iColumns\/2)*m_fXStep;\n\tez += (m_iRows\/2)*m_fZStep;\n\n\tm_pMini->draw(m_fResolution,\n\t\t\t\tex, ey, ez,\n\t\t\t\tdx, dy, dz,\n\t\t\t\tux, uy, uz,\n\t\t\t\tfov, m_fAspect,\n\t\t\t\tm_fNear, m_fFar,\n\t\t\t\tm_fDrawScale);\n\n\tif (myfancnt>0) glEnd();\n\n\t\/\/ We are drawing fans, so the number of triangles is roughly equal to\n\t\/\/ number of vertices\n\tm_iDrawnTriangles = myvtxcnt;\n\n\t\/\/ adaptively adjust resolution threshold up or down to attain\n\t\/\/ the desired polygon (vertex) count target\n\tint diff = m_iDrawnTriangles - m_iPolygonTarget;\n\tint iRange = m_iPolygonTarget \/ 10;\t\t\/\/ ensure within 10%\n\n\t\/\/ If we aren't within the triangle count range adjust the input resolution\n\t\/\/ like a binary search\n\tif (diff < -iRange || diff > iRange)\n\t{\n\/\/\t\tVTLOG(\"diff %d, \", diff);\n\t\tif (diff < -iRange)\n\t\t{\n\t\t\tm_fLResolution = m_fResolution;\n\t\t\t\n\t\t\t\/\/ if the high end isn't high enough, double it\n\t\t\tif (m_fLResolution + 5 >= m_fHResolution)\n\t\t\t{\n\/\/\t\t\t\tVTLOG(\"increase HRes, \");\n\t\t\t\tm_fHResolution *= 10;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_fHResolution = m_fResolution;\n\t\t\tif (m_fLResolution + 5 >= m_fHResolution)\n\t\t\t{\n\/\/\t\t\t\tVTLOG(\"decrease LRes, \");\n\t\t\t\tm_fLResolution = 0;\n\t\t\t}\n\t\t}\n\t\tm_fResolution = m_fLResolution + (m_fHResolution - m_fLResolution) \/ 2;\n\/\/\t\tVTLOG(\"rez: [%.1f, %.1f, %.1f] (%d\/%d)\\n\", m_fLResolution, m_fResolution, m_fHResolution, m_iDrawnTriangles, m_iPolygonTarget);\n\n\t\t\/\/ keep the error within reasonable bounds\n\t\tif (m_fResolution < 5.0f)\n\t\t\tm_fResolution = 5.0f;\n\t\tif (m_fResolution > 4E7)\n\t\t\tm_fResolution = 4E7;\n\t}\n}\n\n\/\/\n\/\/ These methods are called when the framework needs to know the surface\n\/\/ position of the terrain at a given grid point. Supply the height\n\/\/ value from our own data structures.\n\/\/\nfloat SRTerrain::GetElevation(int iX, int iZ, bool bTrue) const\n{\n\tfloat height = m_pMini->getheight(iX, iZ);\n\n\tif (iX<0 || iX>m_iColumns-1 || iZ<0 || iZ>m_iRows-1)\n\t\treturn 0.0f;\n\n\tif (bTrue)\n\t\t\/\/ convert stored value to true value\n\t\treturn height \/ m_fMaximumScale;\n\telse\n\t\t\/\/ convert stored value to drawn value\n\t\treturn height * m_fDrawScale;\n}\n\nvoid SRTerrain::GetWorldLocation(int i, int j, FPoint3 &p, bool bTrue) const\n{\n\tfloat height = m_pMini->getheight(i, j);\n\n\tif (bTrue)\n\t\t\/\/ convert stored value to true value\n\t\theight \/= m_fMaximumScale;\n\telse\n\t\t\/\/ convert stored value to drawn value\n\t\theight *= m_fDrawScale;\n\n\tp.Set(m_fXLookup[i],\n\t\t height,\n\t\t m_fZLookup[j]);\n}\n\nvoid SRTerrain::SetPolygonCount(int iPolygonCount)\n{\n\tvtDynTerrainGeom::SetPolygonCount(iPolygonCount);\n\tm_fResolution = iPolygonCount * 5;\n\tm_fHResolution = 2 * m_fResolution;\n\tm_fLResolution = 0;\n}\n\n#endif\t\/\/ VTLIB_NI\nupdated for libMini 5.4\/\/\n\/\/ SRTerrain class : a subclass of vtDynTerrainGeom which encapsulates\n\/\/ Stefan Roettger's CLOD algorithm.\n\/\/\n\/\/ utilizes: Roettger's MINI library implementation\n\/\/ http:\/\/wwwvis.informatik.uni-stuttgart.de\/~roettger\n\/\/\n\/\/ Copyright (c) 2002-2004 Virtual Terrain Project\n\/\/ Free for all uses, see license.txt for details.\n\/\/\n\n#include \"vtlib\/vtlib.h\"\n#include \"SRTerrain.h\"\n#include \"vtdata\/vtLog.h\"\n\n#if VTLIB_NI\n\/\/ stub\nSRTerrain::SRTerrain() {}\nSRTerrain::~SRTerrain() {}\nfloat SRTerrain::GetElevation(int iX, int iZ, bool bTrue) const { return 0; }\nvoid SRTerrain::GetWorldLocation(int i, int j, FPoint3 &p, bool bTrue) const {}\nvoid SRTerrain::DoCulling(const vtCamera *pCam) {}\nvoid SRTerrain::DoRender() {}\nvoid SRTerrain::SetVerticalExag(float fExag) {}\nDTErr SRTerrain::Init(const vtElevationGrid *pGrid, float fZScale) { return DTErr_NOMEM; }\n#else\n\n#include \"mini.h\"\n#include \"ministub.hpp\"\n\nusing namespace mini;\n#ifdef _MSC_VER\n#pragma comment( lib, \"libMini.lib\" )\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\n\/\/ Constructor\/destructor\n\/\/\nSRTerrain::SRTerrain() : vtDynTerrainGeom()\n{\n\tm_fResolution\t= 10000.0f;\n\tm_fHResolution\t= 20000.0f;\n\tm_fLResolution\t= 0.0f;\n\tm_pMini = NULL;\n}\n\nSRTerrain::~SRTerrain()\n{\n\tif (m_pMini)\n\t{\n\t\tdelete m_pMini;\n\t\tm_pMini = NULL;\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\n\/\/ Unfortunately the following statics are required because libMini only\n\/\/ supports some functionality by callback, and the callback is only a\n\/\/ simple C function which has no context to tell us which terrain.\n\/\/\nstatic const vtElevationGrid *s_pGrid;\nstatic SRTerrain *s_pSRTerrain;\nstatic int myfancnt, myvtxcnt;\nstatic int s_iRows;\n\nvoid beginfan_vtp()\n{\n\tif (myfancnt++>0)\n\t\tglEnd();\n\tglBegin(GL_TRIANGLE_FAN);\n\tmyvtxcnt-=2;\t\/\/ 2 vertices are needed to start each fan\n}\n\nvoid fanvertex_vtp(float x, float y, float z)\n{\n\tglVertex3f(x,y,z);\n\tmyvtxcnt++;\n}\n\nvoid notify_vtp(int i, int j, int size)\n{\n\t\/\/ check to see if we need to switch texture\n\tif (s_pSRTerrain->m_iTPatchDim > 1 && size == s_pSRTerrain->m_iBlockSize)\n\t{\n\t\tint a = i \/ size;\n\t\tint b = j \/ size;\n\t\ts_pSRTerrain->LoadBlockMaterial(a, b);\n\t}\n}\n\nshort int getelevation_vtp1(int i, int j, int size, void *data_unused)\n{\n\treturn s_pGrid->GetValue(i, s_iRows-1-j);\n}\n\nfloat getelevation_vtp2(int i, int j, int size, void *data_unused)\n{\n\treturn s_pGrid->GetFValue(i, s_iRows-1-j);\n}\n\n\/\/\n\/\/ Initialize the terrain data\n\/\/ fZScale converts from height values (meters) to world coordinates\n\/\/\nDTErr SRTerrain::Init(const vtElevationGrid *pGrid, float fZScale)\n{\n\t\/\/ Initializes necessary field of the parent class\n\tDTErr err = BasicInit(pGrid);\n\tif (err != DTErr_OK)\n\t\treturn err;\n\n\tif (m_iColumns != m_iRows)\n\t\treturn DTErr_NOTSQUARE;\n\n\t\/\/ compute n (log2 of grid size)\n\t\/\/ ensure that the grid is size (1 << n) + 1\n\tint n = vt_log2(m_iColumns - 1);\n\tint required_size = (1< 967)\n\t\/\/\n\t\/\/ \tscale * maximum_height \/ dim > 967\n\t\/\/\tscale > dim * 967 \/ maximum_height\n\t\/\/\n\tfloat fMin, fMax;\n\tpGrid->GetHeightExtents(fMin, fMax);\n\t\/\/ Avoid trouble with fMax small or zero\n\tif (fMax < 10) fMax = 10;\n\t\/\/ compute the largest supported value for MaxScale\n\tfloat fMaxMax = dim * 960 \/ fMax;\n\t\/\/ values greater than 10 are unnecessarily large\n\tif (fMaxMax > 10)\n\t\tfMaxMax = 10;\n\tm_fMaximumScale = fMaxMax;\n#else\n\t\/\/ This maxiumum scale is a reasonable tradeoff between the exaggeration\n\t\/\/ that the user is likely to need, and numerical precision issues.\n\tm_fMaximumScale = 10;\n#endif\n\n\tm_fHeightScale = fZScale;\n\tm_fDrawScale = m_fHeightScale \/ m_fMaximumScale;\n\n\tif (pGrid->IsFloatMode())\n\t{\n\t\tfloat *image = NULL;\n\t\tm_pMini = new ministub(image,\n\t\t\t\t&size, &dim, m_fMaximumScale, cellaspect,\n\t\t\t\t0.0f, 0.0f, 0.0f,\t\/\/ grid center\n\t\t\t\tbeginfan_vtp, fanvertex_vtp, notify_vtp,\n\t\t\t\tgetelevation_vtp2);\n\t}\n\telse\n\t{\n\t\tshort *image = NULL;\n\t\tm_pMini = new ministub(image,\n\t\t\t\t&size, &dim, m_fMaximumScale, cellaspect,\n\t\t\t\t0.0f, 0.0f, 0.0f,\t\/\/ grid center\n\t\t\t\tbeginfan_vtp, fanvertex_vtp, notify_vtp,\n\t\t\t\tgetelevation_vtp1);\n\t}\n\n\tm_iDrawnTriangles = -1;\n\tm_iBlockSize = m_iColumns \/ 4;\n\n\treturn DTErr_OK;\n}\n\nvoid SRTerrain::SetVerticalExag(float fExag)\n{\n\tm_fHeightScale = fExag;\n\n\t\/\/ safety check\n\tif (m_fHeightScale > m_fMaximumScale)\n\t\tm_fHeightScale = m_fMaximumScale;\n\n\tm_fDrawScale = m_fHeightScale \/ m_fMaximumScale;\n}\n\n\n\/\/\n\/\/ This will be called once per frame, during the culling pass.\n\/\/\n\/\/ However, libMini does not allow you to call the culling pass\n\/\/ independently of the rendering pass, so we cannot do culling here.\n\/\/ Instead, just store the values for later use.\n\/\/\nvoid SRTerrain::DoCulling(const vtCamera *pCam)\n{\n\t\/\/ Grab necessary values from the VTP Scene framework, store for later\n\tm_eyepos_ogl = pCam->GetTrans();\n\tm_window_size = vtGetScene()->GetWindowSize();\n\tm_fAspect = (float)m_window_size.x \/ m_window_size.y;\n\tm_fNear = pCam->GetHither();\n\tm_fFar = pCam->GetYon();\n\n\t\/\/ Get up vector and direction vector from camera matrix\n\tFMatrix4 mat;\n\tpCam->GetTransform1(mat);\n\tFPoint3 up(0.0f, 1.0f, 0.0f);\n\tmat.TransformVector(up, eye_up);\n\n\tFPoint3 forward(0.0f, 0.0f, -1.0f);\n\tmat.TransformVector(forward, eye_forward);\n\n\tif (pCam->IsOrtho())\n\t{\n\t\t\/\/ libMini supports orthographic viewing as of libMini 5.0.\n\t\t\/\/ A negative FOV value indicates to the library that the FOV is\n\t\t\/\/ actually the orthographic height of the camera.\n\t\tm_fFOVY = pCam->GetWidth() \/ m_fAspect;\n\t\tm_fFOVY = -m_fFOVY;\n\t}\n\telse\n\t{\n\t\tfloat fov = pCam->GetFOV();\n\t\tfloat fov_y2 = atan(tan (fov\/2) \/ m_fAspect);\n\t\tm_fFOVY = fov_y2 * 2.0f * 180 \/ PIf;\n\t}\n}\n\n\nvoid SRTerrain::DoRender()\n{\n\t\/\/ Prepare the render state for our OpenGL usage\n\tPreRender();\n\n\t\/\/ Render the triangles\n\tRenderSurface();\n\n\t\/\/ Clean up\n\tPostRender();\n}\n\n\nvoid SRTerrain::LoadSingleMaterial()\n{\n\t\/\/ single texture for the whole terrain\n\tvtMaterial *pMat = GetMaterial(0);\n\tif (pMat)\n\t{\n\t\tpMat->Apply();\n\t\tSetupTexGen(1.0f);\n\t}\n}\n\n\nvoid SRTerrain::LoadBlockMaterial(int a, int b)\n{\n\t\/\/ we can't change the texture between glBegin\/glEnd\n\tif (myfancnt++>0)\n\t\tglEnd();\n\n\t\/\/ each block has it's own texture map\n\tint matidx = a*m_iTPatchDim + (m_iTPatchDim-1-b);\n\tvtMaterial *pMat = GetMaterial(matidx);\n\tif (pMat)\n\t{\n\t\tpMat->Apply();\n\t\tSetupBlockTexGen(a, b);\n\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\t}\n\n\tglBegin(GL_TRIANGLE_FAN);\n}\n\n\nvoid SRTerrain::RenderSurface()\n{\n\ts_pSRTerrain = this;\n\n\tif (m_iTPatchDim == 1)\n\t\tLoadSingleMaterial();\n\n\tRenderPass();\n\n\t\/\/ how to do a second rendering pass\n\tif (m_bDetailTexture)\n\t{\n\t\t\/\/ once again, with the detail texture material\n\t\tm_pDetailMat->Apply();\n\n\t\t\/\/ the uv tiling is different (usually highly repetitive)\n\t\tSetupTexGen(m_fDetailTiling);\n\n\t\t\/\/ draw the second pass\n\t\tglPolygonOffset(-1.0f, -1.0f);\n\t\tglEnable(GL_POLYGON_OFFSET_FILL);\n\t\tRenderPass();\n\t\tglDisable(GL_POLYGON_OFFSET_FILL);\n\t}\n\tDisableTexGen();\n}\n\n\nvoid SRTerrain::RenderPass()\n{\n\tfloat ex = m_eyepos_ogl.x;\n\tfloat ey = m_eyepos_ogl.y;\n\tfloat ez = m_eyepos_ogl.z;\n\n\tfloat fov = m_fFOVY;\n\n\tfloat ux = eye_up.x;\n\tfloat uy = eye_up.y;\n\tfloat uz = eye_up.z;\n\n\tfloat dx = eye_forward.x;\n\tfloat dy = eye_forward.y;\n\tfloat dz = eye_forward.z;\n\n\tmyfancnt = myvtxcnt = 0;\n\n\t\/\/ Convert the eye location to the unusual coordinate scheme of libMini.\n\tex -= (m_iColumns\/2)*m_fXStep;\n\tez += (m_iRows\/2)*m_fZStep;\n\n\tm_pMini->draw(m_fResolution,\n\t\t\t\tex, ey, ez,\n\t\t\t\tdx, dy, dz,\n\t\t\t\tux, uy, uz,\n\t\t\t\tfov, m_fAspect,\n\t\t\t\tm_fNear, m_fFar,\n\t\t\t\tm_fDrawScale);\n\n\tif (myfancnt>0) glEnd();\n\n\t\/\/ We are drawing fans, so the number of triangles is roughly equal to\n\t\/\/ number of vertices\n\tm_iDrawnTriangles = myvtxcnt;\n\n\t\/\/ adaptively adjust resolution threshold up or down to attain\n\t\/\/ the desired polygon (vertex) count target\n\tint diff = m_iDrawnTriangles - m_iPolygonTarget;\n\tint iRange = m_iPolygonTarget \/ 10;\t\t\/\/ ensure within 10%\n\n\t\/\/ If we aren't within the triangle count range adjust the input resolution\n\t\/\/ like a binary search\n\tif (diff < -iRange || diff > iRange)\n\t{\n\/\/\t\tVTLOG(\"diff %d, \", diff);\n\t\tif (diff < -iRange)\n\t\t{\n\t\t\tm_fLResolution = m_fResolution;\n\t\t\t\n\t\t\t\/\/ if the high end isn't high enough, double it\n\t\t\tif (m_fLResolution + 5 >= m_fHResolution)\n\t\t\t{\n\/\/\t\t\t\tVTLOG(\"increase HRes, \");\n\t\t\t\tm_fHResolution *= 10;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_fHResolution = m_fResolution;\n\t\t\tif (m_fLResolution + 5 >= m_fHResolution)\n\t\t\t{\n\/\/\t\t\t\tVTLOG(\"decrease LRes, \");\n\t\t\t\tm_fLResolution = 0;\n\t\t\t}\n\t\t}\n\t\tm_fResolution = m_fLResolution + (m_fHResolution - m_fLResolution) \/ 2;\n\/\/\t\tVTLOG(\"rez: [%.1f, %.1f, %.1f] (%d\/%d)\\n\", m_fLResolution, m_fResolution, m_fHResolution, m_iDrawnTriangles, m_iPolygonTarget);\n\n\t\t\/\/ keep the error within reasonable bounds\n\t\tif (m_fResolution < 5.0f)\n\t\t\tm_fResolution = 5.0f;\n\t\tif (m_fResolution > 4E7)\n\t\t\tm_fResolution = 4E7;\n\t}\n}\n\n\/\/\n\/\/ These methods are called when the framework needs to know the surface\n\/\/ position of the terrain at a given grid point. Supply the height\n\/\/ value from our own data structures.\n\/\/\nfloat SRTerrain::GetElevation(int iX, int iZ, bool bTrue) const\n{\n\tfloat height = m_pMini->getheight(iX, iZ);\n\n\tif (iX<0 || iX>m_iColumns-1 || iZ<0 || iZ>m_iRows-1)\n\t\treturn 0.0f;\n\n\tif (bTrue)\n\t\t\/\/ convert stored value to true value\n\t\treturn height \/ m_fMaximumScale;\n\telse\n\t\t\/\/ convert stored value to drawn value\n\t\treturn height * m_fDrawScale;\n}\n\nvoid SRTerrain::GetWorldLocation(int i, int j, FPoint3 &p, bool bTrue) const\n{\n\tfloat height = m_pMini->getheight(i, j);\n\n\tif (bTrue)\n\t\t\/\/ convert stored value to true value\n\t\theight \/= m_fMaximumScale;\n\telse\n\t\t\/\/ convert stored value to drawn value\n\t\theight *= m_fDrawScale;\n\n\tp.Set(m_fXLookup[i],\n\t\t height,\n\t\t m_fZLookup[j]);\n}\n\nvoid SRTerrain::SetPolygonCount(int iPolygonCount)\n{\n\tvtDynTerrainGeom::SetPolygonCount(iPolygonCount);\n\tm_fResolution = iPolygonCount * 5;\n\tm_fHResolution = 2 * m_fResolution;\n\tm_fLResolution = 0;\n}\n\n#endif\t\/\/ VTLIB_NI\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n\n#include \"Runtime\/GCNTypes.hpp\"\n#include \"Runtime\/Character\/CharacterCommon.hpp\"\n#include \"Runtime\/World\/CActor.hpp\"\n\n#include \n\nnamespace urde {\nclass CScriptCoverPoint : public CActor {\n bool xe8_26_landHere : 1;\n bool xe8_27_wallHang : 1;\n bool xe8_28_stay : 1;\n bool xe8_29_ : 1;\n bool xe8_30_attackDirection : 1;\n float xec_cosHorizontalAngle;\n float xf0_sinVerticalAngle;\n float xf4_coverTime;\n bool xf8_24_crouch : 1;\n bool xf8_25_inUse : 1;\n TUniqueId xfa_occupant = kInvalidUniqueId;\n TUniqueId xfc_retreating = kInvalidUniqueId;\n std::optional x100_touchBounds;\n float x11c_timeLeft = 0.f;\n\npublic:\n CScriptCoverPoint(TUniqueId uid, std::string_view name, const CEntityInfo& info, zeus::CTransform xf, bool active,\n u32 flags, bool crouch, float horizontalAngle, float verticalAngle, float coverTime);\n\n void Accept(IVisitor& visitor) override;\n void Think(float, CStateManager&) override;\n void AddToRenderer(const zeus::CFrustum&, CStateManager&) override {}\n void AcceptScriptMsg(EScriptObjectMessage, TUniqueId, CStateManager&) override;\n void Render(CStateManager&) override {}\n std::optional GetTouchBounds() const override;\n void SetInUse(bool inUse);\n bool GetInUse(TUniqueId uid) const;\n bool ShouldLandHere() const { return xe8_26_landHere; }\n bool ShouldWallHang() const { return xe8_27_wallHang; }\n bool ShouldStay() const { return xe8_28_stay; }\n bool ShouldCrouch() const { return xf8_24_crouch; }\n bool Blown(const zeus::CVector3f& pos) const;\n float GetSinSqVerticalAngle() const;\n float GetCosHorizontalAngle() const { return xec_cosHorizontalAngle; }\n pas::ECoverDirection GetAttackDirection() const {\n return xe8_30_attackDirection ? pas::ECoverDirection::Left : pas::ECoverDirection::Right;\n }\n void Reserve(TUniqueId id) { xfa_occupant = id; }\n};\n} \/\/ namespace urde\nCScriptCoverPoint: Fix GetAttackDirection return value#pragma once\n\n#include \n#include \n\n#include \"Runtime\/GCNTypes.hpp\"\n#include \"Runtime\/Character\/CharacterCommon.hpp\"\n#include \"Runtime\/World\/CActor.hpp\"\n\n#include \n\nnamespace urde {\nclass CScriptCoverPoint : public CActor {\n bool xe8_26_landHere : 1;\n bool xe8_27_wallHang : 1;\n bool xe8_28_stay : 1;\n bool xe8_29_ : 1;\n bool xe8_30_attackDirection : 1;\n float xec_cosHorizontalAngle;\n float xf0_sinVerticalAngle;\n float xf4_coverTime;\n bool xf8_24_crouch : 1;\n bool xf8_25_inUse : 1;\n TUniqueId xfa_occupant = kInvalidUniqueId;\n TUniqueId xfc_retreating = kInvalidUniqueId;\n std::optional x100_touchBounds;\n float x11c_timeLeft = 0.f;\n\npublic:\n CScriptCoverPoint(TUniqueId uid, std::string_view name, const CEntityInfo& info, zeus::CTransform xf, bool active,\n u32 flags, bool crouch, float horizontalAngle, float verticalAngle, float coverTime);\n\n void Accept(IVisitor& visitor) override;\n void Think(float, CStateManager&) override;\n void AddToRenderer(const zeus::CFrustum&, CStateManager&) override {}\n void AcceptScriptMsg(EScriptObjectMessage, TUniqueId, CStateManager&) override;\n void Render(CStateManager&) override {}\n std::optional GetTouchBounds() const override;\n void SetInUse(bool inUse);\n bool GetInUse(TUniqueId uid) const;\n bool ShouldLandHere() const { return xe8_26_landHere; }\n bool ShouldWallHang() const { return xe8_27_wallHang; }\n bool ShouldStay() const { return xe8_28_stay; }\n bool ShouldCrouch() const { return xf8_24_crouch; }\n bool Blown(const zeus::CVector3f& pos) const;\n float GetSinSqVerticalAngle() const;\n float GetCosHorizontalAngle() const { return xec_cosHorizontalAngle; }\n pas::ECoverDirection GetAttackDirection() const {\n return xe8_30_attackDirection ? pas::ECoverDirection::Right : pas::ECoverDirection::Left;\n }\n void Reserve(TUniqueId id) { xfa_occupant = id; }\n};\n} \/\/ namespace urde\n<|endoftext|>"} {"text":"\/*\n * Copyright 2008-2013 NVIDIA Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n\nnamespace agency\n{\nnamespace cuda\n{\n\n\ntemplate class future;\n\n\ntemplate<>\nclass future\n{\n public:\n \/\/ XXX stream_ should default to per-thread default stream\n __host__ __device__\n future()\n : stream_{0}, event_{0}\n {}\n\n \/\/ XXX this should be private\n \/\/ XXX stream_ should default to per-thread default stream\n __host__ __device__\n future(cudaEvent_t e)\n : stream_{0}, event_{e}\n {\n } \/\/ end future()\n\n __host__ __device__\n future(cudaStream_t s)\n : stream_{s}\n {\n#if __cuda_lib_has_cudart\n detail::throw_on_error(cudaEventCreateWithFlags(&event_, event_create_flags), \"cudaEventCreateWithFlags in agency::cuda::future ctor\");\n detail::throw_on_error(cudaEventRecord(event_, stream_), \"cudaEventRecord in agency::cuda::future ctor\");\n#else\n detail::terminate_with_message(\"agency::cuda::future ctor requires CUDART\");\n#endif \/\/ __cuda_lib_has_cudart\n } \/\/ end future()\n\n __host__ __device__\n future(future&& other)\n : stream_{0}, event_{0}\n {\n future::swap(stream_, other.stream_);\n future::swap(event_, other.event_);\n } \/\/ end future()\n\n __host__ __device__\n future &operator=(future&& other)\n {\n future::swap(stream_, other.stream_);\n future::swap(event_, other.event_);\n return *this;\n } \/\/ end operator=()\n\n __host__ __device__\n ~future()\n {\n if(valid())\n {\n#if __cuda_lib_has_cudart\n \/\/ swallow errors\n cudaError_t e = cudaEventDestroy(event_);\n\n#if __cuda_lib_has_printf\n if(e)\n {\n printf(\"CUDA error after cudaEventDestroy in agency::cuda::future dtor: %s\", cudaGetErrorString(e));\n } \/\/ end if\n#endif \/\/ __cuda_lib_has_printf\n#endif \/\/ __cuda_lib_has_cudart\n } \/\/ end if\n } \/\/ end ~future()\n\n __host__ __device__\n void wait() const\n {\n \/\/ XXX should probably check for valid() here\n\n#if __cuda_lib_has_cudart\n\n#ifndef __CUDA_ARCH__\n \/\/ XXX need to capture the error as an exception and then throw it in .get()\n detail::throw_on_error(cudaEventSynchronize(event_), \"cudaEventSynchronize in agency::cuda::future::wait\");\n#else\n \/\/ XXX need to capture the error as an exception and then throw it in .get()\n detail::throw_on_error(cudaDeviceSynchronize(), \"cudaDeviceSynchronize in agency::cuda::future::wait\");\n#endif \/\/ __CUDA_ARCH__\n\n#else\n detail::terminate_with_message(\"agency::cuda::future::wait() requires CUDART\");\n#endif \/\/ __cuda_lib_has_cudart\n } \/\/ end wait()\n\n __host__ __device__\n void get() const\n {\n wait();\n } \/\/ end get()\n\n __host__ __device__\n bool valid() const\n {\n return event_ != 0;\n } \/\/ end valid()\n\n __host__ __device__\n cudaEvent_t event() const\n {\n return event_;\n } \/\/ end event()\n\n __host__ __device__\n cudaStream_t stream() const\n {\n return stream_;\n } \/\/ end stream()\n\n __host__ __device__\n static future make_ready()\n {\n cudaEvent_t ready_event = 0;\n\n#if __cuda_lib_has_cudart\n detail::throw_on_error(cudaEventCreateWithFlags(&ready_event, event_create_flags), \"cudaEventCreateWithFlags in agency::cuda::future::make_ready\");\n#else\n detail::terminate_with_message(\"agency::cuda::future::make_ready() requires CUDART\");\n#endif\n\n return future{ready_event};\n }\n\n \/\/ XXX this is only used by grid_executor::then_execute()\n __host__ __device__\n std::nullptr_t ptr()\n {\n return nullptr;\n }\n\n private:\n \/\/ implement swap to avoid depending on thrust::swap\n template\n __host__ __device__\n static void swap(T& a, T& b)\n {\n T tmp{a};\n a = b;\n b = tmp;\n }\n\n static const int event_create_flags = cudaEventDisableTiming;\n\n cudaStream_t stream_;\n cudaEvent_t event_;\n}; \/\/ end future\n\n\ntemplate\nclass future\n{\n public:\n __host__ __device__\n future()\n : event_()\n {}\n\n \/\/ XXX this should be private\n template\n __host__ __device__\n future(U&& value, future& e)\n : event_(std::move(e)),\n value_(detail::make_unique(event_.stream(), std::forward(value)))\n {\n } \/\/ end future()\n\n __host__ __device__\n future(cudaStream_t s)\n : event_(s)\n {\n } \/\/ end future()\n\n __host__ __device__\n future(future&& other)\n : event_(std::move(other.event_)),\n value_(std::move(other.value_))\n {\n } \/\/ end future()\n\n __host__ __device__\n future &operator=(future&& other)\n {\n event_ = std::move(other.event_);\n value_ = std::move(other.value_);\n return *this;\n } \/\/ end operator=()\n\n __host__ __device__\n void wait() const\n {\n event_.wait();\n } \/\/ end wait()\n\n __host__ __device__\n T get() const\n {\n wait();\n\n return *value_;\n } \/\/ end get()\n\n __host__ __device__\n bool valid() const\n {\n return event_.valid();\n } \/\/ end valid()\n\n \/\/ XXX only used by grid_executor\n \/\/ think of a better way to expose this\n __host__ __device__\n future& void_future()\n {\n return event_;\n } \/\/ end void_future()\n\n template\n __host__ __device__\n static future make_ready(U&& value)\n {\n auto event = future::make_ready();\n\n return future{std::forward(value), event};\n }\n\n \/\/ XXX this is only used by grid_executor::then_execute()\n __host__ __device__\n T* ptr()\n {\n return value_.get();\n }\n\n private:\n future event_;\n detail::unique_ptr value_;\n}; \/\/ end future\n\n\ninline __host__ __device__\nfuture make_ready_future()\n{\n return future::make_ready();\n} \/\/ end make_ready_future()\n\n\ntemplate\ninline __host__ __device__\nfuture::type> make_ready_future(T&& value)\n{\n return future::type>::make_ready(std::forward(value));\n} \/\/ end make_ready_future()\n\n\n} \/\/ end namespace cuda\n} \/\/ end namespace agency\n\nImplement cuda::future::discard_value()\/*\n * Copyright 2008-2013 NVIDIA Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n\nnamespace agency\n{\nnamespace cuda\n{\n\n\ntemplate class future;\n\n\ntemplate<>\nclass future\n{\n public:\n \/\/ XXX stream_ should default to per-thread default stream\n __host__ __device__\n future()\n : stream_{0}, event_{0}\n {}\n\n \/\/ XXX this should be private\n \/\/ XXX stream_ should default to per-thread default stream\n __host__ __device__\n future(cudaEvent_t e)\n : stream_{0}, event_{e}\n {\n } \/\/ end future()\n\n __host__ __device__\n future(cudaStream_t s)\n : stream_{s}\n {\n#if __cuda_lib_has_cudart\n detail::throw_on_error(cudaEventCreateWithFlags(&event_, event_create_flags), \"cudaEventCreateWithFlags in agency::cuda::future ctor\");\n detail::throw_on_error(cudaEventRecord(event_, stream_), \"cudaEventRecord in agency::cuda::future ctor\");\n#else\n detail::terminate_with_message(\"agency::cuda::future ctor requires CUDART\");\n#endif \/\/ __cuda_lib_has_cudart\n } \/\/ end future()\n\n __host__ __device__\n future(future&& other)\n : stream_{0}, event_{0}\n {\n future::swap(stream_, other.stream_);\n future::swap(event_, other.event_);\n } \/\/ end future()\n\n __host__ __device__\n future &operator=(future&& other)\n {\n future::swap(stream_, other.stream_);\n future::swap(event_, other.event_);\n return *this;\n } \/\/ end operator=()\n\n __host__ __device__\n ~future()\n {\n if(valid())\n {\n#if __cuda_lib_has_cudart\n \/\/ swallow errors\n cudaError_t e = cudaEventDestroy(event_);\n\n#if __cuda_lib_has_printf\n if(e)\n {\n printf(\"CUDA error after cudaEventDestroy in agency::cuda::future dtor: %s\", cudaGetErrorString(e));\n } \/\/ end if\n#endif \/\/ __cuda_lib_has_printf\n#endif \/\/ __cuda_lib_has_cudart\n } \/\/ end if\n } \/\/ end ~future()\n\n __host__ __device__\n void wait() const\n {\n \/\/ XXX should probably check for valid() here\n\n#if __cuda_lib_has_cudart\n\n#ifndef __CUDA_ARCH__\n \/\/ XXX need to capture the error as an exception and then throw it in .get()\n detail::throw_on_error(cudaEventSynchronize(event_), \"cudaEventSynchronize in agency::cuda::future::wait\");\n#else\n \/\/ XXX need to capture the error as an exception and then throw it in .get()\n detail::throw_on_error(cudaDeviceSynchronize(), \"cudaDeviceSynchronize in agency::cuda::future::wait\");\n#endif \/\/ __CUDA_ARCH__\n\n#else\n detail::terminate_with_message(\"agency::cuda::future::wait() requires CUDART\");\n#endif \/\/ __cuda_lib_has_cudart\n } \/\/ end wait()\n\n __host__ __device__\n void get() const\n {\n wait();\n } \/\/ end get()\n\n __host__ __device__\n future discard_value()\n {\n return std::move(*this);\n } \/\/ end discard_value()\n\n __host__ __device__\n bool valid() const\n {\n return event_ != 0;\n } \/\/ end valid()\n\n __host__ __device__\n cudaEvent_t event() const\n {\n return event_;\n } \/\/ end event()\n\n __host__ __device__\n cudaStream_t stream() const\n {\n return stream_;\n } \/\/ end stream()\n\n __host__ __device__\n static future make_ready()\n {\n cudaEvent_t ready_event = 0;\n\n#if __cuda_lib_has_cudart\n detail::throw_on_error(cudaEventCreateWithFlags(&ready_event, event_create_flags), \"cudaEventCreateWithFlags in agency::cuda::future::make_ready\");\n#else\n detail::terminate_with_message(\"agency::cuda::future::make_ready() requires CUDART\");\n#endif\n\n return future{ready_event};\n }\n\n \/\/ XXX this is only used by grid_executor::then_execute()\n __host__ __device__\n std::nullptr_t ptr()\n {\n return nullptr;\n }\n\n private:\n \/\/ implement swap to avoid depending on thrust::swap\n template\n __host__ __device__\n static void swap(T& a, T& b)\n {\n T tmp{a};\n a = b;\n b = tmp;\n }\n\n static const int event_create_flags = cudaEventDisableTiming;\n\n cudaStream_t stream_;\n cudaEvent_t event_;\n}; \/\/ end future\n\n\ntemplate\nclass future\n{\n public:\n __host__ __device__\n future()\n : event_()\n {}\n\n \/\/ XXX this should be private\n template\n __host__ __device__\n future(U&& value, future& e)\n : event_(std::move(e)),\n value_(detail::make_unique(event_.stream(), std::forward(value)))\n {\n } \/\/ end future()\n\n __host__ __device__\n future(cudaStream_t s)\n : event_(s)\n {\n } \/\/ end future()\n\n __host__ __device__\n future(future&& other)\n : event_(std::move(other.event_)),\n value_(std::move(other.value_))\n {\n } \/\/ end future()\n\n __host__ __device__\n future &operator=(future&& other)\n {\n event_ = std::move(other.event_);\n value_ = std::move(other.value_);\n return *this;\n } \/\/ end operator=()\n\n __host__ __device__\n void wait() const\n {\n event_.wait();\n } \/\/ end wait()\n\n __host__ __device__\n T get() const\n {\n wait();\n\n return *value_;\n } \/\/ end get()\n\n __host__ __device__\n future discard_value()\n {\n return std::move(event_);\n } \/\/ end discard_value()\n\n __host__ __device__\n bool valid() const\n {\n return event_.valid();\n } \/\/ end valid()\n\n \/\/ XXX only used by grid_executor\n \/\/ think of a better way to expose this\n __host__ __device__\n future& void_future()\n {\n return event_;\n } \/\/ end void_future()\n\n template\n __host__ __device__\n static future make_ready(U&& value)\n {\n auto event = future::make_ready();\n\n return future{std::forward(value), event};\n }\n\n \/\/ XXX this is only used by grid_executor::then_execute()\n __host__ __device__\n T* ptr()\n {\n return value_.get();\n }\n\n private:\n future event_;\n detail::unique_ptr value_;\n}; \/\/ end future\n\n\ninline __host__ __device__\nfuture make_ready_future()\n{\n return future::make_ready();\n} \/\/ end make_ready_future()\n\n\ntemplate\ninline __host__ __device__\nfuture::type> make_ready_future(T&& value)\n{\n return future::type>::make_ready(std::forward(value));\n} \/\/ end make_ready_future()\n\n\n} \/\/ end namespace cuda\n} \/\/ end namespace agency\n\n<|endoftext|>"} {"text":"\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\n\nCopyright (c) 2000-2012 Torus Knot Software Ltd\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n#include \"SamplePlugin.h\"\n#include \"VolumeCSG.h\"\n\n#include \"OgreVolumeCSGSource.h\"\n#include \"OgreVolumeCacheSource.h\"\n#include \"OgreVolumeTextureSource.h\"\n#include \"OgreVolumeMeshBuilder.h\"\n#include \"OgreMath.h\"\n\nusing namespace Ogre;\nusing namespace OgreBites;\nusing namespace Ogre::Volume;\n\nvoid Sample_VolumeCSG::setupContent(void)\n{\n setupControls();\n setupShaderGenerator();\n Real size = (Real)31.0;\n Vector3 to(size);\n \n \/\/ Light\n Light* directionalLight0 = mSceneMgr->createLight(\"directionalLight0\");\n directionalLight0->setType(Light::LT_DIRECTIONAL);\n directionalLight0->setDirection(Vector3((Real)1, (Real)-1, (Real)1));\n directionalLight0->setDiffuseColour((Real)1, (Real)0.98, (Real)0.73);\n directionalLight0->setSpecularColour((Real)0.1, (Real)0.1, (Real)0.1);\n \n \/\/ Spheres\n CSGSphereSource sphere1((Real)5.0, Vector3((Real)5.5));\n CSGSphereSource sphere2((Real)5.0, Vector3((Real)25.5, (Real)5.5, (Real)5.5));\n CSGSphereSource sphere3((Real)5.0, Vector3((Real)25.5, (Real)5.5, (Real)25.5));\n CSGSphereSource sphere4((Real)5.0, Vector3((Real)5.5, (Real)5.5, (Real)25.5));\n\n \/\/ Cubes\n Real halfWidth = (Real)(2.5 \/ 2.0);\n CSGCubeSource cube1(Vector3((Real)5.5 - halfWidth), Vector3((Real)25.5 + halfWidth, (Real)5.5 + halfWidth, (Real)25.5 + halfWidth));\n CSGCubeSource cube2(Vector3((Real)5.5 + halfWidth, (Real)0.0, (Real)5.5 + halfWidth), Vector3((Real)25.5 - halfWidth, to.y, (Real)25.5 - halfWidth));\n CSGDifferenceSource difference1(&cube1, &cube2);\n\n \/\/ Inner rounded cube\n Real innerHalfWidth = (Real)(7.0 \/ 2.0);\n Vector3 center((Real)15.5, (Real)5.5, (Real)15.5);\n CSGCubeSource cube3(center - innerHalfWidth, center + innerHalfWidth);\n CSGSphereSource sphere5(innerHalfWidth + (Real)0.75, center);\n CSGIntersectionSource intersection1(&cube3, &sphere5);\n\n \/\/ A plane with noise\n CSGPlaneSource plane1((Real)1.0, Vector3::UNIT_Y);\n Real frequencies[] = {(Real)1.01, (Real)0.48};\n Real amplitudes[] = {(Real)0.25, (Real)0.5};\n CSGNoiseSource noise1(&plane1, frequencies, amplitudes, 2, 100);\n\n \/\/ Combine everything\n CSGUnionSource union1(&sphere1, &sphere2);\n CSGUnionSource union2(&union1, &sphere3);\n CSGUnionSource union3(&union2, &sphere4);\n CSGUnionSource union4(&union3, &difference1);\n CSGUnionSource union5(&union4, &intersection1);\n CSGUnionSource union6(&union5, &noise1);\n Source *src = &union6;\n\n mVolumeRoot = OGRE_NEW Chunk();\n SceneNode *volumeRootNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(\"VolumeParent\");\n\n \n ChunkParameters parameters;\n parameters.sceneManager = mSceneMgr;\n parameters.src = src;\n parameters.baseError = (Real)0.25;\n\n mVolumeRoot->load(volumeRootNode, Vector3::ZERO, to, 1, ¶meters);\n\n mVolumeRoot->setMaterial(\"Ogre\/RTShader\/TriplanarTexturing\");\n\n \/\/ Camera\n mCamera->setPosition(to + (Real)7.5);\n mCamera->lookAt(center + (Real)11.0);\n mCamera->setNearClipDistance((Real)0.5);\n\n mRotation = (Real)0.0;\n\n}\n \n\/\/-----------------------------------------------------------------------\n\nvoid Sample_VolumeCSG::setupControls(void)\n{\n mTrayMgr->showCursor();\n#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS\n setDragLook(true);\n#endif\n mCameraMan->setStyle(OgreBites::CS_MANUAL);\n mCameraMan->setTopSpeed((Real)25.0);\n \/\/ make room for the volume\n mTrayMgr->showLogo(TL_TOPRIGHT);\n mTrayMgr->showFrameStats(TL_TOPRIGHT);\n mTrayMgr->toggleAdvancedFrameStats();\n}\n \n\/\/-----------------------------------------------------------------------\n\nvoid Sample_VolumeCSG::setupShaderGenerator()\n{\n RTShader::ShaderGenerator* mGen = RTShader::ShaderGenerator::getSingletonPtr();\n mGen->setTargetLanguage(\"cg\");\n \n RTShader::RenderState* pMainRenderState = \n mGen->createOrRetrieveRenderState(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME).first;\n pMainRenderState->reset();\n \n mGen->invalidateScheme(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);\n\n \/\/ Make this viewport work with shader generator scheme.\n mViewport->setMaterialScheme(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);\n}\n \n\/\/-----------------------------------------------------------------------\n\nvoid Sample_VolumeCSG::cleanupContent(void)\n{ \n OGRE_DELETE mVolumeRoot;\n mVolumeRoot = 0;\n}\n \n\/\/-----------------------------------------------------------------------\n\nSample_VolumeCSG::Sample_VolumeCSG(void) : mVolumeRoot(0), mHideAll(false)\n{\n mInfo[\"Title\"] = \"Volume CSG and RTSS triplanar texturing\";\n mInfo[\"Description\"] = \"Demonstrates a volumetric CSG scene, showing sphere, cube, plane, union, difference and intersection. The triplanar texturing is generated by the RTSS.\";\n mInfo[\"Thumbnail\"] = \"thumb_volumecsg.png\";\n mInfo[\"Category\"] = \"Geometry\";\n}\n \n\/\/-----------------------------------------------------------------------\n\nbool Sample_VolumeCSG::keyPressed(const OIS::KeyEvent& evt)\n{\n if (evt.key == OIS::KC_H)\n {\n if (mHideAll)\n {\n mTrayMgr->showAll();\n }\n else\n {\n mTrayMgr->hideAll();\n }\n mHideAll = !mHideAll;\n }\n return SdkSample::keyPressed(evt);\n}\n \nbool Sample_VolumeCSG::frameRenderingQueued(const Ogre::FrameEvent& evt)\n{\n Vector3 center((Real)15.5, (Real)5.5, (Real)15.5);\n mRotation += Radian(evt.timeSinceLastFrame * (Real)0.5);\n Real r = (Real)35.0;\n mCamera->setPosition(\n Math::Sin(mRotation) * r + center.x,\n (Real)15.0 + center.y,\n Math::Cos(mRotation) * r + center.z\n );\n mCamera->lookAt(center);\n return SdkSample::frameRenderingQueued(evt);\n}\n\n\/\/-----------------------------------------------------------------------\n\nvoid Sample_VolumeCSG::_shutdown()\n{\n RTShader::RenderState* pMainRenderState = \n RTShader::ShaderGenerator::getSingleton().createOrRetrieveRenderState(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME).first;\n pMainRenderState->reset();\n \n SdkSample::_shutdown();\n}\n\n\/\/-----------------------------------------------------------------------\n\n#ifndef OGRE_STATIC_LIB\n\nSamplePlugin* sp;\nSample* s;\n \n\/\/-----------------------------------------------------------------------\n\nextern \"C\" _OgreSampleExport void dllStartPlugin()\n{\n s = new Sample_VolumeCSG();\n sp = OGRE_NEW SamplePlugin(s->getInfo()[\"Title\"] + \" Sample\");\n sp->addSample(s);\n Root::getSingleton().installPlugin(sp);\n}\n \n\/\/-----------------------------------------------------------------------\n\nextern \"C\" _OgreSampleExport void dllStopPlugin()\n{\n Root::getSingleton().uninstallPlugin(sp); \n OGRE_DELETE sp;\n delete s;\n}\n\n#endif\nBackout changeset 91b796f879aba6fc030b36895769ae1ef5d7c856\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\n\nCopyright (c) 2000-2012 Torus Knot Software Ltd\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n#include \"SamplePlugin.h\"\n#include \"VolumeCSG.h\"\n\n#include \"OgreVolumeCSGSource.h\"\n#include \"OgreVolumeCacheSource.h\"\n#include \"OgreVolumeTextureSource.h\"\n#include \"OgreVolumeMeshBuilder.h\"\n#include \"OgreMath.h\"\n\nusing namespace Ogre;\nusing namespace OgreBites;\nusing namespace Ogre::Volume;\n\nvoid Sample_VolumeCSG::setupContent(void)\n{\n setupControls();\n setupShaderGenerator();\n Real size = (Real)31.0;\n Vector3 to(size);\n \n \/\/ Light\n Light* directionalLight0 = mSceneMgr->createLight(\"directionalLight0\");\n directionalLight0->setType(Light::LT_DIRECTIONAL);\n directionalLight0->setDirection(Vector3((Real)1, (Real)-1, (Real)1));\n directionalLight0->setDiffuseColour((Real)1, (Real)0.98, (Real)0.73);\n directionalLight0->setSpecularColour((Real)0.1, (Real)0.1, (Real)0.1);\n \n \/\/ Spheres\n CSGSphereSource sphere1((Real)5.0, Vector3((Real)5.5));\n CSGSphereSource sphere2((Real)5.0, Vector3((Real)25.5, (Real)5.5, (Real)5.5));\n CSGSphereSource sphere3((Real)5.0, Vector3((Real)25.5, (Real)5.5, (Real)25.5));\n CSGSphereSource sphere4((Real)5.0, Vector3((Real)5.5, (Real)5.5, (Real)25.5));\n\n \/\/ Cubes\n Real halfWidth = (Real)(2.5 \/ 2.0);\n CSGCubeSource cube1(Vector3((Real)5.5 - halfWidth), Vector3((Real)25.5 + halfWidth, (Real)5.5 + halfWidth, (Real)25.5 + halfWidth));\n CSGCubeSource cube2(Vector3((Real)5.5 + halfWidth, (Real)0.0, (Real)5.5 + halfWidth), Vector3((Real)25.5 - halfWidth, to.y, (Real)25.5 - halfWidth));\n CSGDifferenceSource difference1(&cube1, &cube2);\n\n \/\/ Inner rounded cube\n Real innerHalfWidth = (Real)(7.0 \/ 2.0);\n Vector3 center((Real)15.5, (Real)5.5, (Real)15.5);\n CSGCubeSource cube3(center - innerHalfWidth, center + innerHalfWidth);\n CSGSphereSource sphere5(innerHalfWidth + (Real)0.75, center);\n CSGIntersectionSource intersection1(&cube3, &sphere5);\n\n \/\/ A plane with noise\n CSGPlaneSource plane1((Real)1.0, Vector3::UNIT_Y);\n Real frequencies[] = {(Real)1.01, (Real)0.48};\n Real amplitudes[] = {(Real)0.25, (Real)0.5};\n CSGNoiseSource noise1(&plane1, frequencies, amplitudes, 2, 100);\n\n \/\/ Combine everything\n CSGUnionSource union1(&sphere1, &sphere2);\n CSGUnionSource union2(&union1, &sphere3);\n CSGUnionSource union3(&union2, &sphere4);\n CSGUnionSource union4(&union3, &difference1);\n CSGUnionSource union5(&union4, &intersection1);\n CSGUnionSource union6(&union5, &noise1);\n Source *src = &union6;\n\n src->serialize(Vector3::ZERO, to, (Real)0.12109375, \"volume.dat\");\n\n mVolumeRoot = OGRE_NEW Chunk();\n SceneNode *volumeRootNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(\"VolumeParent\");\n\n \n ChunkParameters parameters;\n parameters.sceneManager = mSceneMgr;\n parameters.src = src;\n parameters.baseError = (Real)0.25;\n\n mVolumeRoot->load(volumeRootNode, Vector3::ZERO, to, 1, ¶meters);\n\n mVolumeRoot->setMaterial(\"Ogre\/RTShader\/TriplanarTexturing\");\n\n \/\/ Camera\n mCamera->setPosition(to + (Real)7.5);\n mCamera->lookAt(center + (Real)11.0);\n mCamera->setNearClipDistance((Real)0.5);\n\n mRotation = (Real)0.0;\n\n}\n \n\/\/-----------------------------------------------------------------------\n\nvoid Sample_VolumeCSG::setupControls(void)\n{\n mTrayMgr->showCursor();\n#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS\n setDragLook(true);\n#endif\n mCameraMan->setStyle(OgreBites::CS_MANUAL);\n mCameraMan->setTopSpeed((Real)25.0);\n \/\/ make room for the volume\n mTrayMgr->showLogo(TL_TOPRIGHT);\n mTrayMgr->showFrameStats(TL_TOPRIGHT);\n mTrayMgr->toggleAdvancedFrameStats();\n}\n \n\/\/-----------------------------------------------------------------------\n\nvoid Sample_VolumeCSG::setupShaderGenerator()\n{\n RTShader::ShaderGenerator* mGen = RTShader::ShaderGenerator::getSingletonPtr();\n mGen->setTargetLanguage(\"cg\");\n \n RTShader::RenderState* pMainRenderState = \n mGen->createOrRetrieveRenderState(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME).first;\n pMainRenderState->reset();\n \n mGen->invalidateScheme(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);\n\n \/\/ Make this viewport work with shader generator scheme.\n mViewport->setMaterialScheme(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);\n}\n \n\/\/-----------------------------------------------------------------------\n\nvoid Sample_VolumeCSG::cleanupContent(void)\n{ \n OGRE_DELETE mVolumeRoot;\n mVolumeRoot = 0;\n}\n \n\/\/-----------------------------------------------------------------------\n\nSample_VolumeCSG::Sample_VolumeCSG(void) : mVolumeRoot(0), mHideAll(false)\n{\n mInfo[\"Title\"] = \"Volume CSG and RTSS triplanar texturing\";\n mInfo[\"Description\"] = \"Demonstrates a volumetric CSG scene, showing sphere, cube, plane, union, difference and intersection. The triplanar texturing is generated by the RTSS.\";\n mInfo[\"Thumbnail\"] = \"thumb_volumecsg.png\";\n mInfo[\"Category\"] = \"Geometry\";\n}\n \n\/\/-----------------------------------------------------------------------\n\nbool Sample_VolumeCSG::keyPressed(const OIS::KeyEvent& evt)\n{\n if (evt.key == OIS::KC_H)\n {\n if (mHideAll)\n {\n mTrayMgr->showAll();\n }\n else\n {\n mTrayMgr->hideAll();\n }\n mHideAll = !mHideAll;\n }\n return SdkSample::keyPressed(evt);\n}\n \nbool Sample_VolumeCSG::frameRenderingQueued(const Ogre::FrameEvent& evt)\n{\n Vector3 center((Real)15.5, (Real)5.5, (Real)15.5);\n mRotation += Radian(evt.timeSinceLastFrame * (Real)0.5);\n Real r = (Real)35.0;\n mCamera->setPosition(\n Math::Sin(mRotation) * r + center.x,\n (Real)15.0 + center.y,\n Math::Cos(mRotation) * r + center.z\n );\n mCamera->lookAt(center);\n return SdkSample::frameRenderingQueued(evt);\n}\n\n\/\/-----------------------------------------------------------------------\n\nvoid Sample_VolumeCSG::_shutdown()\n{\n RTShader::RenderState* pMainRenderState = \n RTShader::ShaderGenerator::getSingleton().createOrRetrieveRenderState(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME).first;\n pMainRenderState->reset();\n \n SdkSample::_shutdown();\n}\n\n\/\/-----------------------------------------------------------------------\n\n#ifndef OGRE_STATIC_LIB\n\nSamplePlugin* sp;\nSample* s;\n \n\/\/-----------------------------------------------------------------------\n\nextern \"C\" _OgreSampleExport void dllStartPlugin()\n{\n s = new Sample_VolumeCSG();\n sp = OGRE_NEW SamplePlugin(s->getInfo()[\"Title\"] + \" Sample\");\n sp->addSample(s);\n Root::getSingleton().installPlugin(sp);\n}\n \n\/\/-----------------------------------------------------------------------\n\nextern \"C\" _OgreSampleExport void dllStopPlugin()\n{\n Root::getSingleton().uninstallPlugin(sp); \n OGRE_DELETE sp;\n delete s;\n}\n\n#endif\n<|endoftext|>"} {"text":"\/* Copyright (c) MediaArea.net SARL. All Rights Reserved.\r\n *\r\n * Use of this source code is governed by a BSD-style license that can\r\n * be found in the License.html file in the root of the source tree.\r\n *\/\r\n\r\n\/\/---------------------------------------------------------------------------\r\n\/\/ Pre-compilation\r\n#include \"MediaInfo\/PreComp.h\"\r\n#ifdef __BORLANDC__\r\n #pragma hdrstop\r\n#endif\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#include \"MediaInfo\/Setup.h\"\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#if defined(MEDIAINFO_TTML_YES)\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#include \"MediaInfo\/Text\/File_Ttml.h\"\r\n#if MEDIAINFO_EVENTS\r\n #include \"MediaInfo\/MediaInfo_Config_MediaInfo.h\"\r\n #include \"MediaInfo\/MediaInfo_Events_Internal.h\"\r\n#endif \/\/MEDIAINFO_EVENTS\r\n#include \"tinyxml2.h\"\r\n#include \r\nusing namespace tinyxml2;\r\nusing namespace std;\r\n\/\/---------------------------------------------------------------------------\r\n\r\nnamespace MediaInfoLib\r\n{\r\n\r\n\/\/***************************************************************************\r\n\/\/ Utils\r\n\/\/***************************************************************************\r\n\r\nint64u Ttml_str2timecode(const char* Value)\r\n{\r\n size_t Length=strlen(Value);\r\n if (Length>=8\r\n && Value[0]>='0' && Value[0]<='9'\r\n && Value[1]>='0' && Value[1]<='9'\r\n && Value[2]==':'\r\n && Value[3]>='0' && Value[3]<='9'\r\n && Value[4]>='0' && Value[4]<='9'\r\n && Value[5]==':'\r\n && Value[6]>='0' && Value[6]<='9'\r\n && Value[7]>='0' && Value[7]<='9')\r\n {\r\n int64u ToReturn=(int64u)(Value[0]-'0')*10*60*60*1000000000\r\n +(int64u)(Value[1]-'0') *60*60*1000000000\r\n +(int64u)(Value[3]-'0') *10*60*1000000000\r\n +(int64u)(Value[4]-'0') *60*1000000000\r\n +(int64u)(Value[6]-'0') *10*1000000000\r\n +(int64u)(Value[7]-'0') *1000000000;\r\n if (Length>=9 && (Value[8]=='.' || Value[8]==','))\r\n {\r\n if (Length>9+9)\r\n Length=9+9; \/\/Nanoseconds max\r\n const char* Value_End=Value+Length;\r\n Value+=9;\r\n int64u Multiplier=100000000;\r\n while (Value=2\r\n && Value[Length-1]=='s')\r\n {\r\n return (int64u)(atof(Value)*1000000000);\r\n }\r\n else\r\n return (int64u)-1;\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Constructor\/Destructor\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nFile_Ttml::File_Ttml()\r\n:File__Analyze()\r\n{\r\n \/\/Configuration\r\n #if MEDIAINFO_EVENTS\r\n ParserIDs[0]=MediaInfo_Parser_Ttml;\r\n StreamIDs_Width[0]=0;\r\n #endif \/\/MEDIAINFO_EVENTS\r\n\r\n \/\/Init\r\n Frame_Count=0;\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Streams management\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Ttml::Streams_Accept()\r\n{\r\n Fill(Stream_General, 0, General_Format, \"TTML\");\r\n\r\n Stream_Prepare(Stream_Text);\r\n Fill(Stream_Text, 0, \"Format\", \"TTML\");\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Buffer - Global\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Ttml::Read_Buffer_Unsynched()\r\n{\r\n GoTo(0);\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#if MEDIAINFO_SEEK\r\nsize_t File_Ttml::Read_Buffer_Seek (size_t Method, int64u Value, int64u ID)\r\n{\r\n Open_Buffer_Unsynch();\r\n return 1;\r\n}\r\n#endif \/\/MEDIAINFO_SEEK\r\n\r\n\/\/***************************************************************************\r\n\/\/ Buffer - File header\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nbool File_Ttml::FileHeader_Begin()\r\n{\r\n \/\/All should be OK...\r\n return true;\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Ttml::Read_Buffer_Continue()\r\n{\r\n tinyxml2::XMLDocument document;\r\n\r\n if (!FileHeader_Begin_XML(document))\r\n return;\r\n\r\n XMLElement* Root=document.FirstChildElement(\"tt\");\r\n if (!Root)\r\n {\r\n Reject();\r\n return;\r\n }\r\n\r\n if (!Status[IsAccepted])\r\n {\r\n Accept();\r\n\r\n #if MEDIAINFO_EVENTS\r\n MuxingMode=(int8u)-1;\r\n if (StreamIDs_Size>=2 && ParserIDs[StreamIDs_Size-2]==MediaInfo_Parser_Mpeg4)\r\n MuxingMode=11; \/\/MPEG-4\r\n if (StreamIDs_Size>2 && ParserIDs[StreamIDs_Size-2]==MediaInfo_Parser_Mxf) \/\/Only if referenced MXF\r\n MuxingMode=13; \/\/MXF\r\n #endif MEDIAINFO_EVENTS\r\n }\r\n\r\n tinyxml2::XMLElement* div=NULL;\r\n #if MEDIAINFO_EVENTS\r\n tinyxml2::XMLElement* p=NULL;\r\n #endif \/\/MEDIAINFO_EVENTS\r\n for (XMLElement* tt_element=Root->FirstChildElement(); tt_element; tt_element=tt_element->NextSiblingElement())\r\n {\r\n \/\/body\r\n if (!strcmp(tt_element->Value(), \"body\"))\r\n {\r\n for (XMLElement* body_element=tt_element->FirstChildElement(); body_element; body_element=body_element->NextSiblingElement())\r\n {\r\n \/\/div\r\n if (!strcmp(body_element->Value(), \"div\"))\r\n {\r\n for (XMLElement* div_element=body_element->FirstChildElement(); div_element; div_element=div_element->NextSiblingElement())\r\n {\r\n \/\/p\r\n if (!strcmp(div_element->Value(), \"p\"))\r\n {\r\n div=body_element;\r\n #if MEDIAINFO_EVENTS\r\n p=div_element;\r\n #endif \/\/MEDIAINFO_EVENTS\r\n break;\r\n }\r\n }\r\n\r\n if (div)\r\n break;\r\n }\r\n }\r\n\r\n if (div)\r\n break;\r\n }\r\n }\r\n\r\n #if MEDIAINFO_DEMUX\r\n Demux(Buffer, Buffer_Size, ContentType_MainStream);\r\n #endif \/\/MEDIAINFO_DEMUX\r\n\r\n \/\/ Output\r\n #if MEDIAINFO_EVENTS\r\n for (; p; p=p->NextSiblingElement())\r\n {\r\n \/\/p\r\n if (!strcmp(p->Value(), \"p\"))\r\n {\r\n const char* Attribute;\r\n\r\n int64u DTS_Begin=(int64u)-1;\r\n Attribute=p->Attribute(\"begin\");\r\n if (Attribute)\r\n DTS_Begin=Ttml_str2timecode(Attribute);\r\n int64u DTS_End=(int64u)-1;\r\n Attribute=p->Attribute(\"end\");\r\n if (Attribute)\r\n DTS_End=Ttml_str2timecode(Attribute);\r\n string ContentUtf8;\r\n XMLPrinter printer;\r\n p->Accept(&printer);\r\n ContentUtf8+=printer.CStr();\r\n while (!ContentUtf8.empty() && (ContentUtf8[ContentUtf8.size()-1]=='\\r' || ContentUtf8[ContentUtf8.size()-1]=='\\n'))\r\n ContentUtf8.resize(ContentUtf8.size()-1);\r\n Ztring Content; if (p->FirstChild()) Content.From_UTF8(p->FirstChild()->Value());\r\n Frame_Count++;\r\n }\r\n }\r\n #endif MEDIAINFO_EVENTS\r\n\r\n Buffer_Offset=Buffer_Size;\r\n}\r\n\r\n} \/\/NameSpace\r\n\r\n#endif \/\/MEDIAINFO_TTML_YES\r\nx TTML demux was done too early with NextPacket interface\/* Copyright (c) MediaArea.net SARL. All Rights Reserved.\r\n *\r\n * Use of this source code is governed by a BSD-style license that can\r\n * be found in the License.html file in the root of the source tree.\r\n *\/\r\n\r\n\/\/---------------------------------------------------------------------------\r\n\/\/ Pre-compilation\r\n#include \"MediaInfo\/PreComp.h\"\r\n#ifdef __BORLANDC__\r\n #pragma hdrstop\r\n#endif\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#include \"MediaInfo\/Setup.h\"\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#if defined(MEDIAINFO_TTML_YES)\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#include \"MediaInfo\/Text\/File_Ttml.h\"\r\n#if MEDIAINFO_EVENTS\r\n #include \"MediaInfo\/MediaInfo_Config_MediaInfo.h\"\r\n #include \"MediaInfo\/MediaInfo_Events_Internal.h\"\r\n#endif \/\/MEDIAINFO_EVENTS\r\n#include \"tinyxml2.h\"\r\n#include \r\nusing namespace tinyxml2;\r\nusing namespace std;\r\n\/\/---------------------------------------------------------------------------\r\n\r\nnamespace MediaInfoLib\r\n{\r\n\r\n\/\/***************************************************************************\r\n\/\/ Utils\r\n\/\/***************************************************************************\r\n\r\nint64u Ttml_str2timecode(const char* Value)\r\n{\r\n size_t Length=strlen(Value);\r\n if (Length>=8\r\n && Value[0]>='0' && Value[0]<='9'\r\n && Value[1]>='0' && Value[1]<='9'\r\n && Value[2]==':'\r\n && Value[3]>='0' && Value[3]<='9'\r\n && Value[4]>='0' && Value[4]<='9'\r\n && Value[5]==':'\r\n && Value[6]>='0' && Value[6]<='9'\r\n && Value[7]>='0' && Value[7]<='9')\r\n {\r\n int64u ToReturn=(int64u)(Value[0]-'0')*10*60*60*1000000000\r\n +(int64u)(Value[1]-'0') *60*60*1000000000\r\n +(int64u)(Value[3]-'0') *10*60*1000000000\r\n +(int64u)(Value[4]-'0') *60*1000000000\r\n +(int64u)(Value[6]-'0') *10*1000000000\r\n +(int64u)(Value[7]-'0') *1000000000;\r\n if (Length>=9 && (Value[8]=='.' || Value[8]==','))\r\n {\r\n if (Length>9+9)\r\n Length=9+9; \/\/Nanoseconds max\r\n const char* Value_End=Value+Length;\r\n Value+=9;\r\n int64u Multiplier=100000000;\r\n while (Value=2\r\n && Value[Length-1]=='s')\r\n {\r\n return (int64u)(atof(Value)*1000000000);\r\n }\r\n else\r\n return (int64u)-1;\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Constructor\/Destructor\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nFile_Ttml::File_Ttml()\r\n:File__Analyze()\r\n{\r\n \/\/Configuration\r\n #if MEDIAINFO_EVENTS\r\n ParserIDs[0]=MediaInfo_Parser_Ttml;\r\n StreamIDs_Width[0]=0;\r\n #endif \/\/MEDIAINFO_EVENTS\r\n\r\n \/\/Init\r\n Frame_Count=0;\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Streams management\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Ttml::Streams_Accept()\r\n{\r\n Fill(Stream_General, 0, General_Format, \"TTML\");\r\n\r\n Stream_Prepare(Stream_Text);\r\n Fill(Stream_Text, 0, \"Format\", \"TTML\");\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Buffer - Global\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Ttml::Read_Buffer_Unsynched()\r\n{\r\n GoTo(0);\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#if MEDIAINFO_SEEK\r\nsize_t File_Ttml::Read_Buffer_Seek (size_t Method, int64u Value, int64u ID)\r\n{\r\n Open_Buffer_Unsynch();\r\n return 1;\r\n}\r\n#endif \/\/MEDIAINFO_SEEK\r\n\r\n\/\/***************************************************************************\r\n\/\/ Buffer - File header\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nbool File_Ttml::FileHeader_Begin()\r\n{\r\n \/\/All should be OK...\r\n return true;\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Ttml::Read_Buffer_Continue()\r\n{\r\n tinyxml2::XMLDocument document;\r\n\r\n if (!FileHeader_Begin_XML(document))\r\n return;\r\n\r\n XMLElement* Root=document.FirstChildElement(\"tt\");\r\n if (!Root)\r\n {\r\n Reject();\r\n return;\r\n }\r\n\r\n if (!Status[IsAccepted])\r\n {\r\n Accept();\r\n\r\n #if MEDIAINFO_EVENTS\r\n MuxingMode=(int8u)-1;\r\n if (StreamIDs_Size>=2 && ParserIDs[StreamIDs_Size-2]==MediaInfo_Parser_Mpeg4)\r\n MuxingMode=11; \/\/MPEG-4\r\n if (StreamIDs_Size>2 && ParserIDs[StreamIDs_Size-2]==MediaInfo_Parser_Mxf) \/\/Only if referenced MXF\r\n MuxingMode=13; \/\/MXF\r\n #endif MEDIAINFO_EVENTS\r\n\r\n #if MEDIAINFO_DEMUX && MEDIAINFO_NEXTPACKET\r\n if (Config->NextPacket_Get() && Config->Event_CallBackFunction_IsSet())\r\n return; \/\/ Waiting for NextPacket\r\n #endif \/\/MEDIAINFO_DEMUX && MEDIAINFO_NEXTPACKET\r\n }\r\n\r\n tinyxml2::XMLElement* div=NULL;\r\n #if MEDIAINFO_EVENTS\r\n tinyxml2::XMLElement* p=NULL;\r\n #endif \/\/MEDIAINFO_EVENTS\r\n for (XMLElement* tt_element=Root->FirstChildElement(); tt_element; tt_element=tt_element->NextSiblingElement())\r\n {\r\n \/\/body\r\n if (!strcmp(tt_element->Value(), \"body\"))\r\n {\r\n for (XMLElement* body_element=tt_element->FirstChildElement(); body_element; body_element=body_element->NextSiblingElement())\r\n {\r\n \/\/div\r\n if (!strcmp(body_element->Value(), \"div\"))\r\n {\r\n for (XMLElement* div_element=body_element->FirstChildElement(); div_element; div_element=div_element->NextSiblingElement())\r\n {\r\n \/\/p\r\n if (!strcmp(div_element->Value(), \"p\"))\r\n {\r\n div=body_element;\r\n #if MEDIAINFO_EVENTS\r\n p=div_element;\r\n #endif \/\/MEDIAINFO_EVENTS\r\n break;\r\n }\r\n }\r\n\r\n if (div)\r\n break;\r\n }\r\n }\r\n\r\n if (div)\r\n break;\r\n }\r\n }\r\n\r\n #if MEDIAINFO_DEMUX\r\n Demux(Buffer, Buffer_Size, ContentType_MainStream);\r\n #endif \/\/MEDIAINFO_DEMUX\r\n\r\n \/\/ Output\r\n #if MEDIAINFO_EVENTS\r\n for (; p; p=p->NextSiblingElement())\r\n {\r\n \/\/p\r\n if (!strcmp(p->Value(), \"p\"))\r\n {\r\n const char* Attribute;\r\n\r\n int64u DTS_Begin=(int64u)-1;\r\n Attribute=p->Attribute(\"begin\");\r\n if (Attribute)\r\n DTS_Begin=Ttml_str2timecode(Attribute);\r\n int64u DTS_End=(int64u)-1;\r\n Attribute=p->Attribute(\"end\");\r\n if (Attribute)\r\n DTS_End=Ttml_str2timecode(Attribute);\r\n string ContentUtf8;\r\n XMLPrinter printer;\r\n p->Accept(&printer);\r\n ContentUtf8+=printer.CStr();\r\n while (!ContentUtf8.empty() && (ContentUtf8[ContentUtf8.size()-1]=='\\r' || ContentUtf8[ContentUtf8.size()-1]=='\\n'))\r\n ContentUtf8.resize(ContentUtf8.size()-1);\r\n Ztring Content; if (p->FirstChild()) Content.From_UTF8(p->FirstChild()->Value());\r\n Frame_Count++;\r\n }\r\n }\r\n #endif MEDIAINFO_EVENTS\r\n\r\n Buffer_Offset=Buffer_Size;\r\n}\r\n\r\n} \/\/NameSpace\r\n\r\n#endif \/\/MEDIAINFO_TTML_YES\r\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#define\tTIMER_MS\t1000\n\nstatic uint8_t zbuf[8192];\n\nclass BufferSpeed {\n\tuintmax_t bytes_;\n\tAction *callback_action_;\n\tAction *timeout_action_;\npublic:\n\tBufferSpeed(void)\n\t: callback_action_(NULL),\n\t timeout_action_(NULL)\n\t{\n\t\tcallback_action_ = callback(this, &BufferSpeed::callback_complete)->schedule();\n\n\t\tINFO(\"\/example\/buffer\/append\/speed1\") << \"Arming timer.\";\n\t\ttimeout_action_ = EventSystem::instance()->timeout(TIMER_MS, callback(this, &BufferSpeed::timer));\n\t}\n\n\t~BufferSpeed()\n\t{\n\t\tASSERT(timeout_action_ == NULL);\n\t}\n\nprivate:\n\tvoid callback_complete(void)\n\t{\n\t\tcallback_action_->cancel();\n\t\tcallback_action_ = NULL;\n\n\t\tBuffer tmp;\n\t\ttmp.append(zbuf, sizeof zbuf);\n\t\tbytes_ += tmp.length();\n\n\t\tcallback_action_ = callback(this, &BufferSpeed::callback_complete)->schedule();\n\t}\n\n\tvoid timer(void)\n\t{\n\t\ttimeout_action_->cancel();\n\t\ttimeout_action_ = NULL;\n\n\t\tASSERT(callback_action_ != NULL);\n\t\tcallback_action_->cancel();\n\t\tcallback_action_ = NULL;\n\n\t\tINFO(\"\/example\/buffer\/append\/speed1\") << \"Timer expired; \" << bytes_ << \" bytes appended.\";\n\t}\n};\n\nint\nmain(void)\n{\n\tINFO(\"\/example\/buffer\/append\/speed1\") << \"Timer delay: \" << TIMER_MS << \"ms\";\n\n\tmemset(zbuf, 0, sizeof zbuf);\n\n\tBufferSpeed *cs = new BufferSpeed();\n\n\tevent_main();\n\n\tdelete cs;\n}\nInitialize the byte counter.#include \n#include \n#include \n\n#define\tTIMER_MS\t1000\n\nstatic uint8_t zbuf[8192];\n\nclass BufferSpeed {\n\tuintmax_t bytes_;\n\tAction *callback_action_;\n\tAction *timeout_action_;\npublic:\n\tBufferSpeed(void)\n\t: bytes_(0),\n\t callback_action_(NULL),\n\t timeout_action_(NULL)\n\t{\n\t\tcallback_action_ = callback(this, &BufferSpeed::callback_complete)->schedule();\n\n\t\tINFO(\"\/example\/buffer\/append\/speed1\") << \"Arming timer.\";\n\t\ttimeout_action_ = EventSystem::instance()->timeout(TIMER_MS, callback(this, &BufferSpeed::timer));\n\t}\n\n\t~BufferSpeed()\n\t{\n\t\tASSERT(timeout_action_ == NULL);\n\t}\n\nprivate:\n\tvoid callback_complete(void)\n\t{\n\t\tcallback_action_->cancel();\n\t\tcallback_action_ = NULL;\n\n\t\tBuffer tmp;\n\t\ttmp.append(zbuf, sizeof zbuf);\n\t\tbytes_ += tmp.length();\n\n\t\tcallback_action_ = callback(this, &BufferSpeed::callback_complete)->schedule();\n\t}\n\n\tvoid timer(void)\n\t{\n\t\ttimeout_action_->cancel();\n\t\ttimeout_action_ = NULL;\n\n\t\tASSERT(callback_action_ != NULL);\n\t\tcallback_action_->cancel();\n\t\tcallback_action_ = NULL;\n\n\t\tINFO(\"\/example\/buffer\/append\/speed1\") << \"Timer expired; \" << bytes_ << \" bytes appended.\";\n\t}\n};\n\nint\nmain(void)\n{\n\tINFO(\"\/example\/buffer\/append\/speed1\") << \"Timer delay: \" << TIMER_MS << \"ms\";\n\n\tmemset(zbuf, 0, sizeof zbuf);\n\n\tBufferSpeed *cs = new BufferSpeed();\n\n\tevent_main();\n\n\tdelete cs;\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: $RCSfile: antsCommandLineParser.cxx,v $\n Language: C++\n Date: $Date: 2009\/01\/22 22:43:11 $\n Version: $Revision: 1.1 $\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"antsCommandLineParser.h\"\n\n#include \n\nnamespace itk\n{\nnamespace ants\n{\nCommandLineParser\n::CommandLineParser()\n{\n this->m_Options.clear();\n this->m_Command.clear();\n this->m_CommandDescription.clear();\n this->m_UnknownOptions.clear();\n\n this->m_LeftDelimiter = '[';\n this->m_RightDelimiter = ']';\n}\n\nvoid\nCommandLineParser\n::AddOption( OptionType::Pointer option )\n{\n if( ( option->GetShortName() != '\\0' ||\n !this->GetOption( option->GetShortName() ) )\n || ( !option->GetLongName().empty() ||\n !this->GetOption( option->GetLongName() ) ) )\n {\n this->m_Options.push_back( option );\n }\n else\n {\n if( option->GetShortName() != '\\0' &&\n this->GetOption( option->GetShortName() ) )\n {\n itkWarningMacro( \"Duplicate short option '-\"\n << option->GetShortName() << \"'\" );\n }\n if( !( option->GetLongName().empty() ) &&\n this->GetOption( option->GetLongName() ) )\n {\n itkWarningMacro( \"Duplicate long option '--\"\n << option->GetLongName() << \"'\" );\n }\n }\n}\n\nvoid\nCommandLineParser\n::Parse( unsigned int argc, char * *argv )\n{\n std::vector arguments =\n this->RegroupCommandLineArguments( argc, argv );\n\n unsigned int n = 0;\n\n this->m_Command = arguments[n++];\n\n while( n < arguments.size() )\n {\n std::string argument = arguments[n++];\n std::string name;\n\n name.clear();\n if( argument.find( \"--\" ) == 0 )\n {\n name = argument.substr( 2, argument.length() - 1 );\n }\n else if( argument.find( \"-\" ) == 0 && argument.find( \"--\" ) > 0 )\n {\n name = argument.substr( 1, 2 );\n }\n\n if( !( name.empty() ) )\n {\n OptionType::Pointer option = this->GetOption( name );\n if( !option )\n {\n OptionType::Pointer unknownOption = OptionType::New();\n if( name.length() > 1 )\n {\n unknownOption->SetLongName( name );\n }\n else\n {\n unknownOption->SetShortName( name.at( 0 ) );\n }\n if( n == arguments.size() )\n {\n unknownOption->AddValue( \"1\",\n this->m_LeftDelimiter, this->m_RightDelimiter );\n }\n else\n {\n for( unsigned int m = n; m < arguments.size(); m++ )\n {\n std::string value = arguments[m];\n if( value.find( \"-\" ) != 0 )\n {\n unknownOption->AddValue( value,\n this->m_LeftDelimiter, this->m_RightDelimiter );\n }\n else\n {\n if( m == n )\n {\n unknownOption->AddValue( \"1\",\n this->m_LeftDelimiter, this->m_RightDelimiter );\n }\n n = m;\n break;\n }\n }\n }\n this->m_UnknownOptions.push_back( unknownOption );\n }\n else \/\/ the option exists\n {\n if( n == arguments.size() )\n {\n option->AddValue( \"1\",\n this->m_LeftDelimiter, this->m_RightDelimiter );\n }\n else\n {\n for( unsigned int m = n; m < arguments.size(); m++ )\n {\n std::string value = arguments[m];\n if( value.find( \"-\" ) != 0 )\n {\n option->AddValue( value,\n this->m_LeftDelimiter, this->m_RightDelimiter );\n }\n else\n {\n if( m == n )\n {\n option->AddValue( \"1\",\n this->m_LeftDelimiter, this->m_RightDelimiter );\n }\n n = m;\n break;\n }\n }\n }\n }\n }\n }\n}\n\nstd::vector\nCommandLineParser\n::RegroupCommandLineArguments( unsigned int argc, char * *argv )\n{\n \/**\n * Inclusion of this function allows the user to use spaces inside\n * the left and right delimiters. Also replace other left and right\n * delimiters.\n *\/\n std::vector arguments;\n\n std::string currentArg( \"\" );\n bool isArgOpen = false;\n\n for( unsigned int n = 0; n < argc; n++ )\n {\n std::string a( argv[n] );\n\n \/\/ replace left delimiters\n std::replace( a.begin(), a.end(), '{', '[' );\n std::replace( a.begin(), a.end(), '(', '[' );\n std::replace( a.begin(), a.end(), '<', '[' );\n\n \/\/ replace right delimiters\n std::replace( a.begin(), a.end(), '}', ']' );\n std::replace( a.begin(), a.end(), ')', ']' );\n std::replace( a.begin(), a.end(), '>', ']' );\n\n if( isArgOpen )\n {\n std::size_t leftDelimiterPosition = a.find( this->m_LeftDelimiter );\n if( leftDelimiterPosition != std::string::npos )\n {\n itkExceptionMacro( \"Incorrect command line specification.\" );\n }\n\n std::size_t rightDelimiterPosition = a.find( this->m_RightDelimiter );\n if( rightDelimiterPosition != std::string::npos )\n {\n if( rightDelimiterPosition < a.length() - 1 )\n {\n itkExceptionMacro( \"Incorrect command line specification.\" );\n }\n else\n {\n currentArg += a;\n arguments.push_back( currentArg );\n currentArg.clear();\n isArgOpen = false;\n }\n }\n else\n {\n currentArg += a;\n }\n }\n else\n {\n std::size_t leftDelimiterPosition = a.find( this->m_LeftDelimiter );\n std::size_t rightDelimiterPosition = a.find( this->m_RightDelimiter );\n\n if( leftDelimiterPosition == std::string::npos )\n {\n if( rightDelimiterPosition == std::string::npos )\n {\n currentArg += a;\n arguments.push_back( currentArg );\n currentArg.clear();\n }\n else\n {\n itkExceptionMacro( \"Incorrect command line specification.\" );\n }\n }\n else if( leftDelimiterPosition != std::string::npos &&\n rightDelimiterPosition != std::string::npos &&\n leftDelimiterPosition < rightDelimiterPosition )\n {\n if( rightDelimiterPosition < a.length() - 1 )\n {\n itkExceptionMacro( \"Incorrect command line specification.\" );\n }\n currentArg += a;\n arguments.push_back( currentArg );\n currentArg.clear();\n isArgOpen = false;\n }\n else if( rightDelimiterPosition == std::string::npos &&\n leftDelimiterPosition != std::string::npos )\n {\n currentArg += a;\n isArgOpen = true;\n }\n }\n }\n\n return arguments;\n}\n\nCommandLineParser::OptionType::Pointer\nCommandLineParser\n::GetOption( std::string name )\n{\n if( name.length() == 1 )\n {\n return this->GetOption( name.at( 0 ) );\n }\n\n OptionListType::iterator it;\n for( it = this->m_Options.begin(); it != this->m_Options.end(); it++ )\n {\n if( name.compare( (*it)->GetLongName() ) == 0 )\n {\n return *it;\n }\n }\n return NULL;\n}\n\nCommandLineParser::OptionType::Pointer\nCommandLineParser\n::GetOption( char name )\n{\n OptionListType::iterator it;\n\n for( it = this->m_Options.begin(); it != this->m_Options.end(); it++ )\n {\n if( name == (*it)->GetShortName() )\n {\n return *it;\n }\n }\n return NULL;\n}\n\nvoid\nCommandLineParser\n::PrintMenu( std::ostream& os, Indent indent, bool printShortVersion ) const\n{\n os << std::endl;\n os << \"COMMAND: \" << std::endl;\n os << indent << this->m_Command << std::endl;\n if( !this->m_CommandDescription.empty() && !printShortVersion )\n {\n std::stringstream ss1;\n ss1 << indent << indent;\n\n std::stringstream ss2;\n ss2 << this->m_CommandDescription;\n\n std::string description = this->BreakUpStringIntoNewLines(\n ss2.str(), ss1.str(), 80 );\n\n os << indent << indent << description << std::endl;\n }\n os << std::endl;\n os << \"OPTIONS: \" << std::endl;\n\n OptionListType::const_iterator it;\n for( it = this->m_Options.begin(); it != this->m_Options.end(); it++ )\n {\n os << indent;\n std::stringstream ss;\n ss << indent;\n\n if( (*it)->GetShortName() != '\\0' )\n {\n os << \"-\" << (*it)->GetShortName();\n ss << Indent( 2 );\n if( !( (*it)->GetLongName() ).empty() )\n {\n os << \", \" << \"--\" << (*it)->GetLongName() << \" \" << std::flush;\n ss << Indent( 5 + ( (*it)->GetLongName() ).length() );\n }\n else\n {\n os << \" \" << std::flush;\n ss << Indent( 1 );\n }\n }\n else\n {\n os << \"--\" << (*it)->GetLongName() << \" \" << std::flush;\n ss << Indent( 3 + ( (*it)->GetLongName() ).length() );\n }\n if( (*it)->GetNumberOfUsageOptions() > 0 )\n {\n os << (*it)->GetUsageOption( 0 ) << std::endl;\n for( unsigned int i = 1; i < (*it)->GetNumberOfUsageOptions(); i++ )\n {\n os << ss.str() << (*it)->GetUsageOption( i ) << std::endl;\n }\n }\n else\n {\n os << std::endl;\n }\n\n if( !( (*it)->GetDescription().empty() ) && !printShortVersion )\n {\n std::stringstream ss1;\n ss1 << indent << indent;\n\n std::stringstream ss2;\n ss2 << (*it)->GetDescription();\n\n std::string description = this->BreakUpStringIntoNewLines(\n ss2.str(), ss1.str(), 80 );\n\n os << indent << indent << description << std::endl;\n }\n if( !printShortVersion )\n {\n if( (*it)->GetValues().size() == 1 )\n {\n os << indent << indent << \": \" << (*it)->GetValue( 0 );\n if( (*it)->GetParameters( 0 ).size() > 0 )\n {\n os << \"[\";\n if( (*it)->GetParameters( 0 ).size() == 1 )\n {\n os << (*it)->GetParameter( 0, 0 );\n }\n else\n {\n for( unsigned int i = 0;\n i < (*it)->GetParameters( 0 ).size() - 1; i++ )\n {\n os << (*it)->GetParameter( 0, i ) << \",\";\n }\n os << (*it)->GetParameter( 0, (*it)->GetParameters( 0 ).size() - 1 );\n }\n os << \"]\";\n }\n os << std::endl;\n }\n else if( (*it)->GetValues().size() > 1 )\n {\n os << indent << indent << \": \";\n for( unsigned int n = 0; n < (*it)->GetValues().size() - 1; n++ )\n {\n os << (*it)->GetValue( n );\n if( (*it)->GetParameters( n ).size() > 0 )\n {\n os << \"[\";\n if( (*it)->GetParameters( n ).size() == 1 )\n {\n os << (*it)->GetParameter( n, 0 ) << \"], \";\n }\n else\n {\n for( unsigned int i = 0;\n i < (*it)->GetParameters( n ).size() - 1; i++ )\n {\n os << (*it)->GetParameter( n, i ) << \",\";\n }\n os << (*it)->GetParameter( n,\n (*it)->GetParameters( n ).size() - 1 ) << \"], \";\n }\n }\n else\n {\n os << \", \";\n }\n }\n\n unsigned int nn = (*it)->GetValues().size() - 1;\n\n os << (*it)->GetValue( nn );\n if( (*it)->GetParameters( nn ).size() > 0 )\n {\n os << \"[\";\n if( (*it)->GetParameters( nn ).size() == 1 )\n {\n os << (*it)->GetParameter( nn, 0 ) << \"]\";\n }\n else\n {\n for( unsigned int i = 0;\n i < (*it)->GetParameters( nn ).size() - 1; i++ )\n {\n os << (*it)->GetParameter( nn, i ) << \",\";\n }\n os << (*it)->GetParameter( nn,\n (*it)->GetParameters( nn ).size() - 1 ) << \"]\";\n }\n }\n }\n os << std::endl;\n }\n }\n}\n\nstd::string\nCommandLineParser\n::BreakUpStringIntoNewLines( std::string longString,\n std::string indentString, unsigned int numberOfCharactersPerLine ) const\n{\n std::vector tokens;\n\n this->TokenizeString( longString, tokens, \" \" );\n\n std::string newString( \"\" );\n unsigned int currentTokenId = 0;\n unsigned int currentLineLength = 0;\n while( currentTokenId < tokens.size() )\n {\n if( tokens[currentTokenId].length() >= numberOfCharactersPerLine )\n {\n newString += ( std::string( \"\\n\" ) + tokens[currentTokenId]\n + std::string( \"\\n\" ) );\n currentTokenId++;\n currentLineLength = 0;\n }\n else if( currentTokenId < tokens.size() && currentLineLength\n + tokens[currentTokenId].length() > numberOfCharactersPerLine )\n {\n newString += ( std::string( \"\\n\" ) + indentString );\n currentLineLength = 0;\n }\n else\n {\n newString += ( tokens[currentTokenId] + std::string( \" \" ) );\n currentLineLength += ( tokens[currentTokenId].length() + 1 );\n currentTokenId++;\n }\n }\n\n return newString;\n}\n\nvoid\nCommandLineParser\n::TokenizeString( std::string str, std::vector & tokens,\n std::string delimiters ) const\n{\n \/\/ Skip delimiters at beginning.\n std::string::size_type lastPos = str.find_first_not_of( delimiters, 0 );\n \/\/ Find first \"non-delimiter\".\n std::string::size_type pos = str.find_first_of( delimiters, lastPos );\n\n while( std::string::npos != pos || std::string::npos != lastPos )\n {\n \/\/ Found a token, add it to the vector.\n tokens.push_back( str.substr( lastPos, pos - lastPos ) );\n \/\/ Skip delimiters. Note the \"not_of\"\n lastPos = str.find_first_not_of( delimiters, pos );\n \/\/ Find next \"non-delimiter\"\n pos = str.find_first_of( delimiters, lastPos );\n }\n}\n\n\/**\n * Standard \"PrintSelf\" method\n *\/\nvoid\nCommandLineParser\n::PrintSelf( std::ostream& os, Indent indent) const\n{\n Superclass::PrintSelf( os, indent );\n\n os << indent << \"Command: \" << this->m_Command << std::endl;\n os << indent << \"Options: \" << std::endl;\n\n OptionListType::const_iterator it;\n for( it = this->m_Options.begin(); it != this->m_Options.end(); it++ )\n {\n (*it)->Print( os, indent );\n }\n\n if( this->m_UnknownOptions.size() )\n {\n os << indent << \"Unknown Options: \" << std::endl;\n OptionListType::const_iterator its;\n for( its = this->m_UnknownOptions.begin();\n its != this->m_UnknownOptions.end(); its++ )\n {\n (*its)->Print( os, indent );\n }\n }\n}\n} \/\/ end namespace ants\n} \/\/ end namespace itk\nBUG: Negative volues weren't being processed on the command line correctly.\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: $RCSfile: antsCommandLineParser.cxx,v $\n Language: C++\n Date: $Date: 2009\/01\/22 22:43:11 $\n Version: $Revision: 1.1 $\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"antsCommandLineParser.h\"\n\n#include \n\nnamespace itk\n{\nnamespace ants\n{\nCommandLineParser\n::CommandLineParser()\n{\n this->m_Options.clear();\n this->m_Command.clear();\n this->m_CommandDescription.clear();\n this->m_UnknownOptions.clear();\n\n this->m_LeftDelimiter = '[';\n this->m_RightDelimiter = ']';\n}\n\nvoid\nCommandLineParser\n::AddOption( OptionType::Pointer option )\n{\n if( ( option->GetShortName() != '\\0' ||\n !this->GetOption( option->GetShortName() ) )\n || ( !option->GetLongName().empty() ||\n !this->GetOption( option->GetLongName() ) ) )\n {\n this->m_Options.push_back( option );\n }\n else\n {\n if( option->GetShortName() != '\\0' &&\n this->GetOption( option->GetShortName() ) )\n {\n itkWarningMacro( \"Duplicate short option '-\"\n << option->GetShortName() << \"'\" );\n }\n if( !( option->GetLongName().empty() ) &&\n this->GetOption( option->GetLongName() ) )\n {\n itkWarningMacro( \"Duplicate long option '--\"\n << option->GetLongName() << \"'\" );\n }\n }\n}\n\nvoid\nCommandLineParser\n::Parse( unsigned int argc, char * *argv )\n{\n std::vector arguments =\n this->RegroupCommandLineArguments( argc, argv );\n\n unsigned int n = 0;\n\n this->m_Command = arguments[n++];\n\n while( n < arguments.size() )\n {\n std::string argument = arguments[n++];\n std::string name;\n\n name.clear();\n if( argument.find( \"--\" ) == 0 )\n {\n name = argument.substr( 2, argument.length() - 1 );\n }\n else if( argument.find( \"-\" ) == 0 && argument.find( \"--\" ) > 0 )\n {\n name = argument.substr( 1, 2 );\n }\n\n if( !( name.empty() ) && !atof( name.c_str() ) )\n {\n OptionType::Pointer option = this->GetOption( name );\n if( !option )\n {\n OptionType::Pointer unknownOption = OptionType::New();\n if( name.length() > 1 )\n {\n unknownOption->SetLongName( name );\n }\n else\n {\n unknownOption->SetShortName( name.at( 0 ) );\n }\n if( n == arguments.size() )\n {\n unknownOption->AddValue( \"1\",\n this->m_LeftDelimiter, this->m_RightDelimiter );\n }\n else\n {\n for( unsigned int m = n; m < arguments.size(); m++ )\n {\n std::string value = arguments[m];\n if( value.find( \"-\" ) != 0 )\n {\n unknownOption->AddValue( value,\n this->m_LeftDelimiter, this->m_RightDelimiter );\n }\n else\n {\n if( m == n )\n {\n unknownOption->AddValue( \"1\",\n this->m_LeftDelimiter, this->m_RightDelimiter );\n }\n n = m;\n break;\n }\n }\n }\n this->m_UnknownOptions.push_back( unknownOption );\n }\n else \/\/ the option exists\n {\n if( n == arguments.size() )\n {\n option->AddValue( \"1\",\n this->m_LeftDelimiter, this->m_RightDelimiter );\n }\n else\n {\n for( unsigned int m = n; m < arguments.size(); m++ )\n {\n std::string value = arguments[m];\n if( value.find( \"-\" ) != 0 || atof( value.c_str() ) )\n {\n option->AddValue( value,\n this->m_LeftDelimiter, this->m_RightDelimiter );\n }\n else\n {\n if( m == n )\n {\n option->AddValue( \"1\",\n this->m_LeftDelimiter, this->m_RightDelimiter );\n }\n n = m;\n break;\n }\n }\n }\n }\n }\n }\n}\n\nstd::vector\nCommandLineParser\n::RegroupCommandLineArguments( unsigned int argc, char * *argv )\n{\n \/**\n * Inclusion of this function allows the user to use spaces inside\n * the left and right delimiters. Also replace other left and right\n * delimiters.\n *\/\n std::vector arguments;\n\n std::string currentArg( \"\" );\n bool isArgOpen = false;\n\n for( unsigned int n = 0; n < argc; n++ )\n {\n std::string a( argv[n] );\n\n \/\/ replace left delimiters\n std::replace( a.begin(), a.end(), '{', '[' );\n std::replace( a.begin(), a.end(), '(', '[' );\n std::replace( a.begin(), a.end(), '<', '[' );\n\n \/\/ replace right delimiters\n std::replace( a.begin(), a.end(), '}', ']' );\n std::replace( a.begin(), a.end(), ')', ']' );\n std::replace( a.begin(), a.end(), '>', ']' );\n\n if( isArgOpen )\n {\n std::size_t leftDelimiterPosition = a.find( this->m_LeftDelimiter );\n if( leftDelimiterPosition != std::string::npos )\n {\n itkExceptionMacro( \"Incorrect command line specification.\" );\n }\n\n std::size_t rightDelimiterPosition = a.find( this->m_RightDelimiter );\n if( rightDelimiterPosition != std::string::npos )\n {\n if( rightDelimiterPosition < a.length() - 1 )\n {\n itkExceptionMacro( \"Incorrect command line specification.\" );\n }\n else\n {\n currentArg += a;\n arguments.push_back( currentArg );\n currentArg.clear();\n isArgOpen = false;\n }\n }\n else\n {\n currentArg += a;\n }\n }\n else\n {\n std::size_t leftDelimiterPosition = a.find( this->m_LeftDelimiter );\n std::size_t rightDelimiterPosition = a.find( this->m_RightDelimiter );\n\n if( leftDelimiterPosition == std::string::npos )\n {\n if( rightDelimiterPosition == std::string::npos )\n {\n currentArg += a;\n arguments.push_back( currentArg );\n currentArg.clear();\n }\n else\n {\n itkExceptionMacro( \"Incorrect command line specification.\" );\n }\n }\n else if( leftDelimiterPosition != std::string::npos &&\n rightDelimiterPosition != std::string::npos &&\n leftDelimiterPosition < rightDelimiterPosition )\n {\n if( rightDelimiterPosition < a.length() - 1 )\n {\n itkExceptionMacro( \"Incorrect command line specification.\" );\n }\n currentArg += a;\n arguments.push_back( currentArg );\n currentArg.clear();\n isArgOpen = false;\n }\n else if( rightDelimiterPosition == std::string::npos &&\n leftDelimiterPosition != std::string::npos )\n {\n currentArg += a;\n isArgOpen = true;\n }\n }\n }\n\n return arguments;\n}\n\nCommandLineParser::OptionType::Pointer\nCommandLineParser\n::GetOption( std::string name )\n{\n if( name.length() == 1 )\n {\n return this->GetOption( name.at( 0 ) );\n }\n\n OptionListType::iterator it;\n for( it = this->m_Options.begin(); it != this->m_Options.end(); it++ )\n {\n if( name.compare( (*it)->GetLongName() ) == 0 )\n {\n return *it;\n }\n }\n return NULL;\n}\n\nCommandLineParser::OptionType::Pointer\nCommandLineParser\n::GetOption( char name )\n{\n OptionListType::iterator it;\n\n for( it = this->m_Options.begin(); it != this->m_Options.end(); it++ )\n {\n if( name == (*it)->GetShortName() )\n {\n return *it;\n }\n }\n return NULL;\n}\n\nvoid\nCommandLineParser\n::PrintMenu( std::ostream& os, Indent indent, bool printShortVersion ) const\n{\n os << std::endl;\n os << \"COMMAND: \" << std::endl;\n os << indent << this->m_Command << std::endl;\n if( !this->m_CommandDescription.empty() && !printShortVersion )\n {\n std::stringstream ss1;\n ss1 << indent << indent;\n\n std::stringstream ss2;\n ss2 << this->m_CommandDescription;\n\n std::string description = this->BreakUpStringIntoNewLines(\n ss2.str(), ss1.str(), 80 );\n\n os << indent << indent << description << std::endl;\n }\n os << std::endl;\n os << \"OPTIONS: \" << std::endl;\n\n OptionListType::const_iterator it;\n for( it = this->m_Options.begin(); it != this->m_Options.end(); it++ )\n {\n os << indent;\n std::stringstream ss;\n ss << indent;\n\n if( (*it)->GetShortName() != '\\0' )\n {\n os << \"-\" << (*it)->GetShortName();\n ss << Indent( 2 );\n if( !( (*it)->GetLongName() ).empty() )\n {\n os << \", \" << \"--\" << (*it)->GetLongName() << \" \" << std::flush;\n ss << Indent( 5 + ( (*it)->GetLongName() ).length() );\n }\n else\n {\n os << \" \" << std::flush;\n ss << Indent( 1 );\n }\n }\n else\n {\n os << \"--\" << (*it)->GetLongName() << \" \" << std::flush;\n ss << Indent( 3 + ( (*it)->GetLongName() ).length() );\n }\n if( (*it)->GetNumberOfUsageOptions() > 0 )\n {\n os << (*it)->GetUsageOption( 0 ) << std::endl;\n for( unsigned int i = 1; i < (*it)->GetNumberOfUsageOptions(); i++ )\n {\n os << ss.str() << (*it)->GetUsageOption( i ) << std::endl;\n }\n }\n else\n {\n os << std::endl;\n }\n\n if( !( (*it)->GetDescription().empty() ) && !printShortVersion )\n {\n std::stringstream ss1;\n ss1 << indent << indent;\n\n std::stringstream ss2;\n ss2 << (*it)->GetDescription();\n\n std::string description = this->BreakUpStringIntoNewLines(\n ss2.str(), ss1.str(), 80 );\n\n os << indent << indent << description << std::endl;\n }\n if( !printShortVersion )\n {\n if( (*it)->GetValues().size() == 1 )\n {\n os << indent << indent << \": \" << (*it)->GetValue( 0 );\n if( (*it)->GetParameters( 0 ).size() > 0 )\n {\n os << \"[\";\n if( (*it)->GetParameters( 0 ).size() == 1 )\n {\n os << (*it)->GetParameter( 0, 0 );\n }\n else\n {\n for( unsigned int i = 0;\n i < (*it)->GetParameters( 0 ).size() - 1; i++ )\n {\n os << (*it)->GetParameter( 0, i ) << \",\";\n }\n os << (*it)->GetParameter( 0, (*it)->GetParameters( 0 ).size() - 1 );\n }\n os << \"]\";\n }\n os << std::endl;\n }\n else if( (*it)->GetValues().size() > 1 )\n {\n os << indent << indent << \": \";\n for( unsigned int n = 0; n < (*it)->GetValues().size() - 1; n++ )\n {\n os << (*it)->GetValue( n );\n if( (*it)->GetParameters( n ).size() > 0 )\n {\n os << \"[\";\n if( (*it)->GetParameters( n ).size() == 1 )\n {\n os << (*it)->GetParameter( n, 0 ) << \"], \";\n }\n else\n {\n for( unsigned int i = 0;\n i < (*it)->GetParameters( n ).size() - 1; i++ )\n {\n os << (*it)->GetParameter( n, i ) << \",\";\n }\n os << (*it)->GetParameter( n,\n (*it)->GetParameters( n ).size() - 1 ) << \"], \";\n }\n }\n else\n {\n os << \", \";\n }\n }\n\n unsigned int nn = (*it)->GetValues().size() - 1;\n\n os << (*it)->GetValue( nn );\n if( (*it)->GetParameters( nn ).size() > 0 )\n {\n os << \"[\";\n if( (*it)->GetParameters( nn ).size() == 1 )\n {\n os << (*it)->GetParameter( nn, 0 ) << \"]\";\n }\n else\n {\n for( unsigned int i = 0;\n i < (*it)->GetParameters( nn ).size() - 1; i++ )\n {\n os << (*it)->GetParameter( nn, i ) << \",\";\n }\n os << (*it)->GetParameter( nn,\n (*it)->GetParameters( nn ).size() - 1 ) << \"]\";\n }\n }\n }\n os << std::endl;\n }\n }\n}\n\nstd::string\nCommandLineParser\n::BreakUpStringIntoNewLines( std::string longString,\n std::string indentString, unsigned int numberOfCharactersPerLine ) const\n{\n std::vector tokens;\n\n this->TokenizeString( longString, tokens, \" \" );\n\n std::string newString( \"\" );\n unsigned int currentTokenId = 0;\n unsigned int currentLineLength = 0;\n while( currentTokenId < tokens.size() )\n {\n if( tokens[currentTokenId].length() >= numberOfCharactersPerLine )\n {\n newString += ( std::string( \"\\n\" ) + tokens[currentTokenId]\n + std::string( \"\\n\" ) );\n currentTokenId++;\n currentLineLength = 0;\n }\n else if( currentTokenId < tokens.size() && currentLineLength\n + tokens[currentTokenId].length() > numberOfCharactersPerLine )\n {\n newString += ( std::string( \"\\n\" ) + indentString );\n currentLineLength = 0;\n }\n else\n {\n newString += ( tokens[currentTokenId] + std::string( \" \" ) );\n currentLineLength += ( tokens[currentTokenId].length() + 1 );\n currentTokenId++;\n }\n }\n\n return newString;\n}\n\nvoid\nCommandLineParser\n::TokenizeString( std::string str, std::vector & tokens,\n std::string delimiters ) const\n{\n \/\/ Skip delimiters at beginning.\n std::string::size_type lastPos = str.find_first_not_of( delimiters, 0 );\n \/\/ Find first \"non-delimiter\".\n std::string::size_type pos = str.find_first_of( delimiters, lastPos );\n\n while( std::string::npos != pos || std::string::npos != lastPos )\n {\n \/\/ Found a token, add it to the vector.\n tokens.push_back( str.substr( lastPos, pos - lastPos ) );\n \/\/ Skip delimiters. Note the \"not_of\"\n lastPos = str.find_first_not_of( delimiters, pos );\n \/\/ Find next \"non-delimiter\"\n pos = str.find_first_of( delimiters, lastPos );\n }\n}\n\n\/**\n * Standard \"PrintSelf\" method\n *\/\nvoid\nCommandLineParser\n::PrintSelf( std::ostream& os, Indent indent) const\n{\n Superclass::PrintSelf( os, indent );\n\n os << indent << \"Command: \" << this->m_Command << std::endl;\n os << indent << \"Options: \" << std::endl;\n\n OptionListType::const_iterator it;\n for( it = this->m_Options.begin(); it != this->m_Options.end(); it++ )\n {\n (*it)->Print( os, indent );\n }\n\n if( this->m_UnknownOptions.size() )\n {\n os << indent << \"Unknown Options: \" << std::endl;\n OptionListType::const_iterator its;\n for( its = this->m_UnknownOptions.begin();\n its != this->m_UnknownOptions.end(); its++ )\n {\n (*its)->Print( os, indent );\n }\n }\n}\n} \/\/ end namespace ants\n} \/\/ end namespace itk\n<|endoftext|>"} {"text":"\/*\n * ElevationChangeDetection.cpp\n *\n * Created on: Mar 26, 2015\n * Author: Martin Wermelinger\n * Institute: ETH Zurich, Autonomous Systems Lab\n *\/\n\n#include \"elevation_change_detection\/ElevationChangeDetection.hpp\"\n\n#include \n\n\/\/ Eigenvalues\n#include \n\nusing namespace Eigen;\nusing namespace grid_map;\n\nnamespace elevation_change_detection {\n\nElevationChangeDetection::ElevationChangeDetection(ros::NodeHandle& nodeHandle)\n : nodeHandle_(nodeHandle),\n type_(\"elevation\")\n{\n ROS_INFO(\"Elevation change detection node started.\");\n\n readParameters();\n\n submapClient_ = nodeHandle_.serviceClient(submapServiceName_);\n elevationChangePublisher_ = nodeHandle_.advertise(\"elevation_change_map\", 1, true);\n groundTruthPublisher_ = nodeHandle_.advertise(\"ground_truth_map\", 1, true);\n\n updateTimer_ = nodeHandle_.createTimer(updateDuration_,\n &ElevationChangeDetection::updateTimerCallback, this);\n\n requestedMapTypes_.push_back(type_);\n}\n\nElevationChangeDetection::~ElevationChangeDetection()\n{\n updateTimer_.stop();\n nodeHandle_.shutdown();\n}\n\nbool ElevationChangeDetection::readParameters()\n{\n nodeHandle_.param(\"submap_service\", submapServiceName_, std::string(\"\/get_grid_map\"));\n\n double updateRate;\n nodeHandle_.param(\"update_rate\", updateRate, 1.0);\n updateDuration_.fromSec(1.0 \/ updateRate);\n\n nodeHandle_.param(\"map_frame_id\", mapFrameId_, std::string(\"map\"));\n std::string robotFrameId;\n nodeHandle_.param(\"robot_frame_id\", robotFrameId, std::string(\"base\"));\n double mapCenterX, mapCenterY;\n nodeHandle_.param(\"map_center_x\", mapCenterX, 0.0);\n nodeHandle_.param(\"map_center_y\", mapCenterY, 0.0);\n submapPoint_.header.frame_id = robotFrameId;\n submapPoint_.point.x = mapCenterX;\n submapPoint_.point.y = mapCenterY;\n submapPoint_.point.z = 0.0;\n\n nodeHandle_.param(\"map_length_x\", mapLength_.x(), 5.0);\n nodeHandle_.param(\"map_length_y\", mapLength_.y(), 5.0);\n\n nodeHandle_.param(\"threshold\", threshold_, 0.0);\n\n return true;\n}\n\nbool ElevationChangeDetection::loadElevationMap(const std::string& pathToBag, const std::string& topicName)\n{\n return grid_map::GridMapRosConverter::loadFromBag(pathToBag, topicName, groundTruthMap_);\n}\n\nvoid ElevationChangeDetection::updateTimerCallback(const ros::TimerEvent& timerEvent)\n{\n grid_map_msgs::GridMap mapMessage;\n ROS_DEBUG(\"Sending request to %s.\", submapServiceName_.c_str());\n submapClient_.waitForExistence();\n ROS_DEBUG(\"Sending request to %s.\", submapServiceName_.c_str());\n if (getGridMap(mapMessage)) {\n grid_map::GridMap elevationMap;\n grid_map::GridMapRosConverter::fromMessage(mapMessage, elevationMap);\n computeElevationChange(elevationMap);\n\n \/\/ Publish elevation change map.\n if (!publishElevationChangeMap(elevationMap)) ROS_DEBUG(\"Elevation change map has not been broadcasted.\");\n if (!publishGroundTruthMap(groundTruthMap_)) ROS_DEBUG(\"Ground truth map has not been broadcasted.\");\n } else {\n ROS_WARN(\"Failed to retrieve elevation grid map.\");\n }\n}\n\nbool ElevationChangeDetection::getGridMap(grid_map_msgs::GridMap& map)\n{\n submapPoint_.header.stamp = ros::Time(0);\n geometry_msgs::PointStamped submapPointTransformed;\n\n try {\n transformListener_.transformPoint(mapFrameId_, submapPoint_, submapPointTransformed);\n } catch (tf::TransformException &ex) {\n ROS_ERROR(\"%s\", ex.what());\n }\n\n grid_map_msgs::GetGridMap submapService;\n submapService.request.position_x = submapPointTransformed.point.x;\n submapService.request.position_y = submapPointTransformed.point.y;\n submapService.request.length_x = mapLength_.x();\n submapService.request.length_y = mapLength_.y();\n submapService.request.layers.resize(requestedMapTypes_.size());\n\n for (unsigned int i = 0; i < requestedMapTypes_.size(); ++i) {\n submapService.request.layers[i] = requestedMapTypes_[i];\n }\n\n if (!submapClient_.call(submapService)) return false;\n map = submapService.response.map;\n return true;\n}\n\nvoid ElevationChangeDetection::computeElevationChange(grid_map::GridMap& elevationMap)\n{\n elevationMap.add(\"elevation_change\", elevationMap.get(type_));\n std::vector validTypes;\n std::vector basicLayers;\n validTypes.push_back(type_);\n basicLayers.push_back(\"elevation_change\");\n elevationMap.setBasicLayers(basicLayers);\n elevationMap.clear();\n\n for (GridMapIterator iterator(elevationMap);\n !iterator.isPassedEnd(); ++iterator) {\n \/\/ Check if elevation map has valid value\n if (!elevationMap.isValid(*iterator, validTypes)) continue;\n double height = elevationMap.at(type_, *iterator);\n\n \/\/ Get the ground truth height\n Vector2d position, groundTruthPosition;\n Array2i groundTruthIndex;\n elevationMap.getPosition(*iterator, position);\n groundTruthMap_.getIndex(position, groundTruthIndex);\n if (!groundTruthMap_.isValid(groundTruthIndex, validTypes)) continue;\n double groundTruthHeight = groundTruthMap_.at(type_, groundTruthIndex);\n\n \/\/ Add to elevation change map\n double diffElevation = std::abs(height - groundTruthHeight);\n if (diffElevation <= threshold_) continue;\n elevationMap.at(\"elevation_change\", *iterator) = diffElevation;\n }\n}\n\nbool ElevationChangeDetection::publishElevationChangeMap(const grid_map::GridMap& map)\n{\n if (elevationChangePublisher_.getNumSubscribers() < 1) return false;\n grid_map_msgs::GridMap message;\n GridMapRosConverter::toMessage(map, message);\n elevationChangePublisher_.publish(message);\n ROS_DEBUG(\"Elevation map raw has been published.\");\n return true;\n}\n\nbool ElevationChangeDetection::publishGroundTruthMap(const grid_map::GridMap& map)\n{\n if (groundTruthPublisher_.getNumSubscribers() < 1) return false;\n grid_map_msgs::GridMap message;\n GridMapRosConverter::toMessage(map, message);\n groundTruthPublisher_.publish(message);\n ROS_DEBUG(\"Ground truth map raw has been published.\");\n return true;\n}\n\n} \/* namespace elevation_change_detection *\/\nAdded loading from rosbag.\/*\n * ElevationChangeDetection.cpp\n *\n * Created on: Mar 26, 2015\n * Author: Martin Wermelinger\n * Institute: ETH Zurich, Autonomous Systems Lab\n *\/\n\n#include \"elevation_change_detection\/ElevationChangeDetection.hpp\"\n\n#include \n\n\/\/ Eigenvalues\n#include \n\nusing namespace Eigen;\nusing namespace grid_map;\n\nnamespace elevation_change_detection {\n\nElevationChangeDetection::ElevationChangeDetection(ros::NodeHandle& nodeHandle)\n : nodeHandle_(nodeHandle),\n type_(\"elevation\")\n{\n ROS_INFO(\"Elevation change detection node started.\");\n\n readParameters();\n\n submapClient_ = nodeHandle_.serviceClient(submapServiceName_);\n elevationChangePublisher_ = nodeHandle_.advertise(\"elevation_change_map\", 1, true);\n groundTruthPublisher_ = nodeHandle_.advertise(\"ground_truth_map\", 1, true);\n\n updateTimer_ = nodeHandle_.createTimer(updateDuration_,\n &ElevationChangeDetection::updateTimerCallback, this);\n\n requestedMapTypes_.push_back(type_);\n}\n\nElevationChangeDetection::~ElevationChangeDetection()\n{\n updateTimer_.stop();\n nodeHandle_.shutdown();\n}\n\nbool ElevationChangeDetection::readParameters()\n{\n nodeHandle_.param(\"submap_service\", submapServiceName_, std::string(\"\/get_grid_map\"));\n\n double updateRate;\n nodeHandle_.param(\"update_rate\", updateRate, 1.0);\n updateDuration_.fromSec(1.0 \/ updateRate);\n\n nodeHandle_.param(\"map_frame_id\", mapFrameId_, std::string(\"map\"));\n std::string robotFrameId;\n nodeHandle_.param(\"robot_frame_id\", robotFrameId, std::string(\"base\"));\n double mapCenterX, mapCenterY;\n nodeHandle_.param(\"map_center_x\", mapCenterX, 0.0);\n nodeHandle_.param(\"map_center_y\", mapCenterY, 0.0);\n submapPoint_.header.frame_id = robotFrameId;\n submapPoint_.point.x = mapCenterX;\n submapPoint_.point.y = mapCenterY;\n submapPoint_.point.z = 0.0;\n\n nodeHandle_.param(\"map_length_x\", mapLength_.x(), 5.0);\n nodeHandle_.param(\"map_length_y\", mapLength_.y(), 5.0);\n\n nodeHandle_.param(\"threshold\", threshold_, 0.0);\n\n std::string bagTopicName_, pathToBag_;\n nodeHandle_.param(\"bag_topic_name\", bagTopicName_, std::string(\"grid_map\"));\n nodeHandle_.param(\"path_to_bag\", pathToBag_, std::string(\"lee_ground_truth.bag\"));\n loadElevationMap(pathToBag_, bagTopicName_);\n if (!groundTruthMap_.exists(type_)) ROS_ERROR(\"Can't find bag or topic of the ground truth map!\");\n\n return true;\n}\n\nbool ElevationChangeDetection::loadElevationMap(const std::string& pathToBag, const std::string& topicName)\n{\n return grid_map::GridMapRosConverter::loadFromBag(pathToBag, topicName, groundTruthMap_);\n}\n\nvoid ElevationChangeDetection::updateTimerCallback(const ros::TimerEvent& timerEvent)\n{\n grid_map_msgs::GridMap mapMessage;\n ROS_DEBUG(\"Sending request to %s.\", submapServiceName_.c_str());\n submapClient_.waitForExistence();\n ROS_DEBUG(\"Sending request to %s.\", submapServiceName_.c_str());\n if (getGridMap(mapMessage)) {\n grid_map::GridMap elevationMap;\n grid_map::GridMapRosConverter::fromMessage(mapMessage, elevationMap);\n computeElevationChange(elevationMap);\n\n \/\/ Publish elevation change map.\n if (!publishElevationChangeMap(elevationMap)) ROS_DEBUG(\"Elevation change map has not been broadcasted.\");\n if (!publishGroundTruthMap(groundTruthMap_)) ROS_DEBUG(\"Ground truth map has not been broadcasted.\");\n } else {\n ROS_WARN(\"Failed to retrieve elevation grid map.\");\n }\n}\n\nbool ElevationChangeDetection::getGridMap(grid_map_msgs::GridMap& map)\n{\n submapPoint_.header.stamp = ros::Time(0);\n geometry_msgs::PointStamped submapPointTransformed;\n\n try {\n transformListener_.transformPoint(mapFrameId_, submapPoint_, submapPointTransformed);\n } catch (tf::TransformException &ex) {\n ROS_ERROR(\"%s\", ex.what());\n }\n\n grid_map_msgs::GetGridMap submapService;\n submapService.request.position_x = submapPointTransformed.point.x;\n submapService.request.position_y = submapPointTransformed.point.y;\n submapService.request.length_x = mapLength_.x();\n submapService.request.length_y = mapLength_.y();\n submapService.request.layers.resize(requestedMapTypes_.size());\n\n for (unsigned int i = 0; i < requestedMapTypes_.size(); ++i) {\n submapService.request.layers[i] = requestedMapTypes_[i];\n }\n\n if (!submapClient_.call(submapService)) return false;\n map = submapService.response.map;\n return true;\n}\n\nvoid ElevationChangeDetection::computeElevationChange(grid_map::GridMap& elevationMap)\n{\n elevationMap.add(\"elevation_change\", elevationMap.get(type_));\n std::vector validTypes;\n std::vector basicLayers;\n validTypes.push_back(type_);\n basicLayers.push_back(\"elevation_change\");\n elevationMap.setBasicLayers(basicLayers);\n elevationMap.clear();\n\n for (GridMapIterator iterator(elevationMap);\n !iterator.isPassedEnd(); ++iterator) {\n \/\/ Check if elevation map has valid value\n if (!elevationMap.isValid(*iterator, validTypes)) continue;\n double height = elevationMap.at(type_, *iterator);\n\n \/\/ Get the ground truth height\n Vector2d position, groundTruthPosition;\n Array2i groundTruthIndex;\n elevationMap.getPosition(*iterator, position);\n groundTruthMap_.getIndex(position, groundTruthIndex);\n if (!groundTruthMap_.isValid(groundTruthIndex, validTypes)) continue;\n double groundTruthHeight = groundTruthMap_.at(type_, groundTruthIndex);\n\n \/\/ Add to elevation change map\n double diffElevation = std::abs(height - groundTruthHeight);\n if (diffElevation <= threshold_) continue;\n elevationMap.at(\"elevation_change\", *iterator) = diffElevation;\n }\n}\n\nbool ElevationChangeDetection::publishElevationChangeMap(const grid_map::GridMap& map)\n{\n if (elevationChangePublisher_.getNumSubscribers() < 1) return false;\n grid_map_msgs::GridMap message;\n GridMapRosConverter::toMessage(map, message);\n elevationChangePublisher_.publish(message);\n ROS_DEBUG(\"Elevation map raw has been published.\");\n return true;\n}\n\nbool ElevationChangeDetection::publishGroundTruthMap(const grid_map::GridMap& map)\n{\n if (groundTruthPublisher_.getNumSubscribers() < 1) return false;\n grid_map_msgs::GridMap message;\n GridMapRosConverter::toMessage(map, message);\n groundTruthPublisher_.publish(message);\n ROS_DEBUG(\"Ground truth map raw has been published.\");\n return true;\n}\n\n} \/* namespace elevation_change_detection *\/\n<|endoftext|>"} {"text":"#include \"stdafx.h\"\n#include \"GameManager.h\"\n#include \"FileStuff.h\"\n#include \"ConstVars.h\"\n\/\/̾\n#include \"GameLayer.h\"\n#include \"UILayer.h\"\n\/\/\n#include \"StageInformation.h\"\n#include \"StageScene.h\"\n#include \"GameScene.h\"\n\/\/Ŵ\n#include \"CollectionManager.h\"\n#include \"ColliderManager.h\"\n#include \"TargetManager.h\"\n\/\/ö̴\n#include \"Collider.h\"\n#include \"Bullet.h\"\n#include \"CrossBullet.h\"\n#include \"Explosion.h\"\n\/\/Ÿ\n#include \"Target.h\"\n\/\/\n#include \"Sling.h\"\n\nGameManager* GameManager::m_instance = nullptr;\n\nGameManager* GameManager::GetInstance()\n{\n\tif (m_instance == nullptr)\n\t{\n\t\tm_instance = new GameManager();\n\t}\n\treturn m_instance;\n}\n\nGameManager::GameManager()\n{\n\tm_sling = nullptr;\n\tm_colliderManager = new ColliderManager();\n\tm_targetManager = new TargetManager();\n\tm_isJudged = false;\n\tm_lastTarget = nullptr;\n}\n\nvoid GameManager::Reset()\n{\n\tm_sling = nullptr;\n\tdelete m_colliderManager;\n\tm_colliderManager = new ColliderManager();\n\tdelete m_targetManager;\n\tm_targetManager = new TargetManager();\n\tm_isJudged = false;\n\tm_lastTarget = nullptr;\n}\n\nGameManager::~GameManager() {}\n\nvoid GameManager::SetStage(GameLayer* gameLayer, UILayer* uiLayer, int stageNum)\n{\t\n\tReset();\n\tStageInformation stageInfo(stageNum);\n\tm_targetManager->InitTargets(&stageInfo);\n\tAppendTargetsToLayer(gameLayer);\n\tm_colliderManager->InitBullets(&stageInfo);\n\tAppendBulletsToLayer(uiLayer);\n\tm_sling = InitSling(gameLayer);\n\tm_stage = stageNum;\n}\n\nSling* GameManager::InitSling(GameLayer* gameLayer)\n{\n\tSling* sling = Sling::create();\n\tgameLayer->addChild(sling);\n\tsling->LoadBullet();\n\treturn sling;\n}\n\nvoid GameManager::AppendTargetsToLayer(GameLayer* gameLayer)\n{\n\tfor (Target* target : m_targetManager->m_targets)\n\t{\n\t\tgameLayer->addChild(target);\n\t}\n}\n\nvoid GameManager::AppendBulletsToLayer(UILayer* uiLayer)\n{\n\tfor (int i = 0; i < m_colliderManager->m_bulletNum; i++)\n\t{\n\t\tBullet* bullet = static_cast(m_colliderManager->m_colliders.at(i));\n\t\tSprite* bulletSpr = bullet->GetSprite();\n\t\tuiLayer->addChild(bulletSpr);\n\t\tbulletSpr->setPosition(Vec2(45 + i*25, 50));\n\t}\n}\n\nvoid GameManager::ShotBullet(Sling* sling)\n{\n\tBullet* bullet = m_colliderManager->GetBulletToShot(sling);\n\t\n\tif (bullet)\n\t{\n\t\tScene* currentScene = Director::getInstance()->getRunningScene();\n\t\tGameScene* gameScene = static_cast(currentScene->getChildByName(\"GameScene\"));\n\t\tGameLayer* gameLayer = gameScene->GetGameLayer();\n\t\tUILayer* uiLayer = gameScene->GetUILayer();\n\n\t\tgameLayer->addChild(bullet);\n\n\t\tsling->ShotComplete();\n\n\t\tif (m_colliderManager->HasBulletToShot())\n\t\t{\n\t\t\tsling->LoadBullet();\n\t\t}\n\t}\n}\n\nvoid GameManager::Play(GameLayer* gameLayer, UILayer* uiLayer)\n{\n\tVector& colliders = m_colliderManager->m_colliders;\n\tVector& targets = m_targetManager->m_targets;\n\tCollider* collider = nullptr;\n\n\tfor (int i = 0; i < colliders.size(); i++)\n\t{\n\t\tcollider = colliders.at(i);\n\t\tif (collider->IsFlying())\n\t\t{\n\t\t\tcollider->Act();\n\t\t\tCheckCollide(collider, targets);\n\t\t}\n\n\t\tif (collider->IsBullet())\n\t\t{\n\t\t\tBullet* bullet = static_cast(collider);\n\t\t\tif (bullet->IsToExplode())\n\t\t\t{\n\t\t\t\tExplosion* explosion = bullet->GetExplosion();\n\t\t\t\tm_colliderManager->AddExplosion(explosion);\n\t\t\t\tgameLayer->addChild(explosion);\n\t\t\t}\n\t\t}\n\t}\n\n\tm_colliderManager->EraseDeadColliders();\n\tm_targetManager->EraseDeadTargets();\n\tControlWinFailProgress(uiLayer);\n}\n\nvoid GameManager::CheckCollide(Collider* collider, Vector& targets)\n{\n\tm_lastTarget = nullptr; \/\/ ѹ 浹 Ÿٿ 浹  浹üũ ʵ .\n\tbool collidingCheck = false; \/\/ 浹 Ÿ ִ üũ. --> lastTarget ʿ䰡 ִüũ\n\tfor (Target* target : targets)\n\t{\n\t\tif (target == m_lastTarget)\n\t\t{\n\t\t\tbreak;\n\t\t\tcollidingCheck = true;\n\t\t}\n\n\t\tif (target->IsEnemy())\n\t\t{\n\t\t\tm_targetManager->SaveEnemyPosition(target->getPosition());\n\t\t\tEnemyDyingEffect();\n\t\t}\n\n\t\tif (collider->IsBullet())\n\t\t{\n\n\t\t\tif (IsCollision(target, collider))\n\t\t\t{\n\t\t\t\tm_lastTarget = target;\n\t\t\t\ttarget->ApplyCollisionEffect(collider);\n\t\t\t\tcollidingCheck = true;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tExplosion* explosion = static_cast(collider);\n\t\t\tconst float explosionRadius = explosion->GetBoundingRadius();\n\t\t\tconst Vec2 explosionPosition = explosion->getPosition();\n\t\t\tconst Rect targetBoundingBox = target->GetBoundingArea();\n\n\t\t\tif ( targetBoundingBox.intersectsCircle( explosionPosition, explosionRadius) )\n\t\t\t{\n\t\t\t\ttarget->ApplyCollisionEffect(explosion);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!collidingCheck)\n\t{\n\t\tm_lastTarget = nullptr;\n\t}\n}\n\nvoid GameManager::EnemyDyingEffect()\n{\n\t\/*\n\tParticleSmoke* enemyDyingEffect = ParticleSmoke::create();\n\tenemyDyingEffect->setPosition(enemyPos);\n\tgameLayer->addChild(enemyDyingEffect);\n\t*\/\n}\n\nvoid GameManager::SetCollectionPos(const Vec2& pos)\n{\n\tconst Vec2 compensateToParentPos = Vec2(160, 0);\n\tm_curCollection->setPosition(pos + compensateToParentPos);\n}\n\nvoid GameManager::EarnCollectionEvent(UILayer* uiLayer)\n{\n\tGameScene* gameScene = static_cast(uiLayer->getParent());\n\tconst Point& enemyPos = m_targetManager->GetEnemyPosition();\n\tconst Vec2& aboveCharacterPos = gameScene->GetCharacterPos() + Vec2(0, 100);\n\n\tm_curCollection = m_collectionManager->GetCollectionSprOfStage(m_stage);\n\tm_curCollection->setPosition(enemyPos);\n\tuiLayer->addChild(m_curCollection);\n\n\t\/\/part 1\n\tMoveBy* moveBy_00 = MoveBy::create(1.50f, Point(0, -10));\n\tMoveBy* moveBy_01 = MoveBy::create(1.00f, Point(0, -10));\n\n\tBlink* blink_00 = Blink::create(1.50f, 5);\n\tBlink* blink_01 = Blink::create(1.00f, 5);\n\n\tFadeIn* fadeIn_00 = FadeIn::create(1.50f);\n\tFadeOut* fadeOut_00 = FadeOut::create(1.00f);\n\n\tSpawn* spawn_00 = Spawn::create(fadeIn_00, moveBy_00, blink_00, NULL);\n\tSpawn* spawn_01 = Spawn::create(fadeOut_00, moveBy_01, blink_01, NULL);\n\n\t\/\/part 2\n\tCallFuncN* callFuncN = CallFuncN::create(CC_CALLBACK_0\n\t\t(GameManager::SetCollectionPos, this, aboveCharacterPos));\n\n\tMoveBy* moveBy_02 = MoveBy::create(1.50f, Point(0, -30));\n\tMoveBy* moveBy_03 = MoveBy::create(1.00f, Point(0, -20));\n\n\tBlink* blink_02 = Blink::create(1.50f, 5);\n\tBlink* blink_03 = Blink::create(1.00f, 5);\n\n\tFadeIn* fadeIn_01 = FadeIn::create(0.01f);\n\tFadeOut* fadeOut_01 = FadeOut::create(2.50f);\n\n\tSpawn* spawn_02 = Spawn::create(fadeIn_01, moveBy_02, blink_02, NULL);\n\tSpawn* spawn_03 = Spawn::create(fadeOut_01, moveBy_03, blink_03, NULL);\n\n\tSequence* sequence = Sequence::create(\n\t\tspawn_00, spawn_01, callFuncN, spawn_02, spawn_03, NULL);\n\n\tm_curCollection->runAction(sequence);\n}\n\nvoid GameManager::WinProgress(UILayer* uiLayer)\n{\n\tint lastStage = UserDefault::getInstance()->getIntegerForKey(ConstVars::LASTSTAGE);\n\n\tif (m_stage == lastStage &&\n\t\t(m_stage == CollectionManager::SHOES ||\n\t\tm_stage == CollectionManager::SCARF ||\n\t\tm_stage == CollectionManager::BOTTLE ||\n\t\tm_stage == CollectionManager::MONITOR ||\n\t\tm_stage == CollectionManager::LETTER))\n\t{\n\t\t\/\/EarnCollectionEvent(uiLayer);\n\n\t\t\/\/DelayTime* waitEventTime = DelayTime::create(4.50f);\n\t\t\/\/CallFuncN* showWidget = CallFuncN::create(CC_CALLBACK_0(\n\t\t\/\/\tUILayer::MakeSuccessWidget, uiLayer, m_stage));\n\t\t\/\/Sequence* waitAndshow = Sequence::create(waitEventTime, showWidget, NULL);\n\n\t\t\/\/uiLayer->runAction(waitAndshow);\n\t\tuiLayer->MakeSuccessWidget(m_stage);\n\t}\n\telse\n\t{\n\t\tif (m_stage==0)\n\t\t{\n\t\t\tDirector::getInstance()->popScene();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tuiLayer->MakeSuccessWidget(m_stage);\n\t\t}\n\t}\n\n\tif (lastStage == m_stage && m_stage + 1 <= StageInformation::GetMaxStageNum())\n\t{\n\t\tUserDefault::getInstance()->setIntegerForKey(ConstVars::LASTSTAGE, m_stage + 1);\n\t}\n}\n\nvoid GameManager::FailProgress(UILayer* uiLayer)\n{\n\tif (m_stage == 0)\n\t{\n\t\tDirector::getInstance()->popScene();\n\t}\n\telse\n\t{\n\t\tuiLayer->MakeFailWidget(m_stage);\n\t}\n}\n\nvoid GameManager::ControlWinFailProgress(UILayer* uiLayer)\n{\n\tif (!m_isJudged)\n\t{\n\t\tif (!m_targetManager->HasEnemy())\n\t\t{\n\t\t\tm_isJudged = true;\n\t\t\tm_sling->ShotComplete();\n\t\t\tWinProgress(uiLayer);\n\t\t}\n\t\telse if (!m_colliderManager->HasCollider()){\n\t\t\tm_isJudged = true;\n\t\t\tm_sling->ShotComplete();\n\t\t\tFailProgress(uiLayer);\n\t\t}\n\t}\n}\n\nbool GameManager::IsCollision(Target* target, Collider* collider)\n{\n\t\n\tfloat rotation = target->getRotation();\n\tconst Rect colliderBoundingBox = static_cast(collider)->GetBoundingArea();\n\tconst Rect targetBoundingBox = target->GetBoundingArea();\n\n\tif (rotation < 1 && rotation > -1){ \/\/ȸ \n\t\t\/\/ 簢 浹 \t\n\t\tif (targetBoundingBox.intersectsRect(colliderBoundingBox))\n\t\t\treturn true;\n\n\t\treturn false;\n\t}\n\n\tfloat colliderX = collider->getPosition().x;\n\tfloat colliderY = collider->getPosition().y;\n\n\tfloat minX = targetBoundingBox.getMinX(); \/\/ left margin\n\tfloat maxX = targetBoundingBox.getMaxX(); \/\/ right margin\n\tfloat minY = targetBoundingBox.getMinY(); \/\/ lower margin\n\tfloat maxY = targetBoundingBox.getMaxY(); \/\/ upper margin\n\tPoint LL(minX, minY);\n\tPoint LU(minX, maxY);\n\tPoint RL(maxX, minY);\n\tPoint RU(maxX, maxY);\n\n\t\/\/ȸ簢\n\tLL.rotate(target->getPosition(), -CC_DEGREES_TO_RADIANS(target->getRotation()));\n\tLU.rotate(target->getPosition(), -CC_DEGREES_TO_RADIANS(target->getRotation()));\n\tRL.rotate(target->getPosition(), -CC_DEGREES_TO_RADIANS(target->getRotation()));\n\tRU.rotate(target->getPosition(), -CC_DEGREES_TO_RADIANS(target->getRotation()));\n\t\n\t\/\/ y = Ax + upperB\n\t\/\/ y = Ax + lowerB\n\t\/\/ y = -1\/Ax + leftB\n\t\/\/ y = -1\/Ax + rightB\n\tfloat a = (RU.y- LU.y) \/ (RU.x - LU.x); \/\/\n\t\n\t\/\/ RU.y = a * RU.x + upperB\n\tfloat upperB = RU.y - a * (RU.x);\n\tfloat lowerB = LL.y - a * (LL.x);\n\t\n\t\/\/ LL.y = (-1\/a) * LL.x + leftB\n\tfloat leftB = LL.y - (-1 \/ a) * LL.x;\n\tfloat rightB = RU.y - (-1 \/ a) * RU.x;\n\n\t\/\/ װ ȿ ִ üũ.\n\t\/\/ uppermargin lowermargin ̿ ִ X, Y (y-uppermargin) *(y-lowermargin) < 0 \n\t\/\/ left right .\n\t\n\t\/\/׿ dot\n\t\/\/makeDebugPoint(Point(colliderX, (colliderX * a + upperB)), target->getParent());\n\t\/\/makeDebugPoint(Point(colliderX, (colliderX * a + lowerB)), target->getParent());\n\t\/\/makeDebugPoint(Point(colliderX, (colliderX * (-1 \/ a) + rightB)), target->getParent());\n\t\/\/makeDebugPoint(Point(colliderX, (colliderX * (-1 \/ a) + leftB)), target->getParent());\n\n\tif (\n\t\t((colliderX * a + upperB) - colliderY) * ((colliderX * a + lowerB) - colliderY) < 0\n\t\t&&\n\t\t((colliderX * (-1 \/ a) + leftB) - colliderY) * ((colliderX * (-1 \/ a) + rightB) - colliderY) < 0\n\t\t)\n\t{\n\t\treturn true;\n\t}\n\telse \n\t\treturn false;\n\t\n}\n\nvoid GameManager::makeDebugPoint(Point p, Node* spr)\n{\n\tSprite* dot = Sprite::create(FileStuff::DEBRIS);\n\tdot->setScale(2.);\n\tspr->addChild(dot);\n\tPoint pos = spr->convertToWorldSpace(Point::ZERO);\n\tdot->setPosition(p - pos);\n\n\tSequence* action = Sequence::create(DelayTime::create(0.1), RemoveSelf::create(),NULL);\n\tdot->runAction(action);\n}add collision angle infinte bug#include \"stdafx.h\"\n#include \"GameManager.h\"\n#include \"FileStuff.h\"\n#include \"ConstVars.h\"\n\/\/̾\n#include \"GameLayer.h\"\n#include \"UILayer.h\"\n\/\/\n#include \"StageInformation.h\"\n#include \"StageScene.h\"\n#include \"GameScene.h\"\n\/\/Ŵ\n#include \"CollectionManager.h\"\n#include \"ColliderManager.h\"\n#include \"TargetManager.h\"\n\/\/ö̴\n#include \"Collider.h\"\n#include \"Bullet.h\"\n#include \"CrossBullet.h\"\n#include \"Explosion.h\"\n\/\/Ÿ\n#include \"Target.h\"\n\/\/\n#include \"Sling.h\"\n\nGameManager* GameManager::m_instance = nullptr;\n\nGameManager* GameManager::GetInstance()\n{\n\tif (m_instance == nullptr)\n\t{\n\t\tm_instance = new GameManager();\n\t}\n\treturn m_instance;\n}\n\nGameManager::GameManager()\n{\n\tm_sling = nullptr;\n\tm_colliderManager = new ColliderManager();\n\tm_targetManager = new TargetManager();\n\tm_isJudged = false;\n\tm_lastTarget = nullptr;\n}\n\nvoid GameManager::Reset()\n{\n\tm_sling = nullptr;\n\tdelete m_colliderManager;\n\tm_colliderManager = new ColliderManager();\n\tdelete m_targetManager;\n\tm_targetManager = new TargetManager();\n\tm_isJudged = false;\n\tm_lastTarget = nullptr;\n}\n\nGameManager::~GameManager() {}\n\nvoid GameManager::SetStage(GameLayer* gameLayer, UILayer* uiLayer, int stageNum)\n{\t\n\tReset();\n\tStageInformation stageInfo(stageNum);\n\tm_targetManager->InitTargets(&stageInfo);\n\tAppendTargetsToLayer(gameLayer);\n\tm_colliderManager->InitBullets(&stageInfo);\n\tAppendBulletsToLayer(uiLayer);\n\tm_sling = InitSling(gameLayer);\n\tm_stage = stageNum;\n}\n\nSling* GameManager::InitSling(GameLayer* gameLayer)\n{\n\tSling* sling = Sling::create();\n\tgameLayer->addChild(sling);\n\tsling->LoadBullet();\n\treturn sling;\n}\n\nvoid GameManager::AppendTargetsToLayer(GameLayer* gameLayer)\n{\n\tfor (Target* target : m_targetManager->m_targets)\n\t{\n\t\tgameLayer->addChild(target);\n\t}\n}\n\nvoid GameManager::AppendBulletsToLayer(UILayer* uiLayer)\n{\n\tfor (int i = 0; i < m_colliderManager->m_bulletNum; i++)\n\t{\n\t\tBullet* bullet = static_cast(m_colliderManager->m_colliders.at(i));\n\t\tSprite* bulletSpr = bullet->GetSprite();\n\t\tuiLayer->addChild(bulletSpr);\n\t\tbulletSpr->setPosition(Vec2(45 + i*25, 50));\n\t}\n}\n\nvoid GameManager::ShotBullet(Sling* sling)\n{\n\tBullet* bullet = m_colliderManager->GetBulletToShot(sling);\n\t\n\tif (bullet)\n\t{\n\t\tScene* currentScene = Director::getInstance()->getRunningScene();\n\t\tGameScene* gameScene = static_cast(currentScene->getChildByName(\"GameScene\"));\n\t\tGameLayer* gameLayer = gameScene->GetGameLayer();\n\t\tUILayer* uiLayer = gameScene->GetUILayer();\n\n\t\tgameLayer->addChild(bullet);\n\n\t\tsling->ShotComplete();\n\n\t\tif (m_colliderManager->HasBulletToShot())\n\t\t{\n\t\t\tsling->LoadBullet();\n\t\t}\n\t}\n}\n\nvoid GameManager::Play(GameLayer* gameLayer, UILayer* uiLayer)\n{\n\tVector& colliders = m_colliderManager->m_colliders;\n\tVector& targets = m_targetManager->m_targets;\n\tCollider* collider = nullptr;\n\n\tfor (int i = 0; i < colliders.size(); i++)\n\t{\n\t\tcollider = colliders.at(i);\n\t\tif (collider->IsFlying())\n\t\t{\n\t\t\tcollider->Act();\n\t\t\tCheckCollide(collider, targets);\n\t\t}\n\n\t\tif (collider->IsBullet())\n\t\t{\n\t\t\tBullet* bullet = static_cast(collider);\n\t\t\tif (bullet->IsToExplode())\n\t\t\t{\n\t\t\t\tExplosion* explosion = bullet->GetExplosion();\n\t\t\t\tm_colliderManager->AddExplosion(explosion);\n\t\t\t\tgameLayer->addChild(explosion);\n\t\t\t}\n\t\t}\n\t}\n\n\tm_colliderManager->EraseDeadColliders();\n\tm_targetManager->EraseDeadTargets();\n\tControlWinFailProgress(uiLayer);\n}\n\nvoid GameManager::CheckCollide(Collider* collider, Vector& targets)\n{\n\tm_lastTarget = nullptr; \/\/ ѹ 浹 Ÿٿ 浹  浹üũ ʵ .\n\tbool collidingCheck = false; \/\/ 浹 Ÿ ִ üũ. --> lastTarget ʿ䰡 ִüũ\n\tfor (Target* target : targets)\n\t{\n\t\tif (target == m_lastTarget)\n\t\t{\n\t\t\tbreak;\n\t\t\tcollidingCheck = true;\n\t\t}\n\n\t\tif (target->IsEnemy())\n\t\t{\n\t\t\tm_targetManager->SaveEnemyPosition(target->getPosition());\n\t\t\tEnemyDyingEffect();\n\t\t}\n\n\t\tif (collider->IsBullet())\n\t\t{\n\n\t\t\tif (IsCollision(target, collider))\n\t\t\t{\n\t\t\t\tm_lastTarget = target;\n\t\t\t\ttarget->ApplyCollisionEffect(collider);\n\t\t\t\tcollidingCheck = true;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tExplosion* explosion = static_cast(collider);\n\t\t\tconst float explosionRadius = explosion->GetBoundingRadius();\n\t\t\tconst Vec2 explosionPosition = explosion->getPosition();\n\t\t\tconst Rect targetBoundingBox = target->GetBoundingArea();\n\n\t\t\tif ( targetBoundingBox.intersectsCircle( explosionPosition, explosionRadius) )\n\t\t\t{\n\t\t\t\ttarget->ApplyCollisionEffect(explosion);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!collidingCheck)\n\t{\n\t\tm_lastTarget = nullptr;\n\t}\n}\n\nvoid GameManager::EnemyDyingEffect()\n{\n\t\/*\n\tParticleSmoke* enemyDyingEffect = ParticleSmoke::create();\n\tenemyDyingEffect->setPosition(enemyPos);\n\tgameLayer->addChild(enemyDyingEffect);\n\t*\/\n}\n\nvoid GameManager::SetCollectionPos(const Vec2& pos)\n{\n\tconst Vec2 compensateToParentPos = Vec2(160, 0);\n\tm_curCollection->setPosition(pos + compensateToParentPos);\n}\n\nvoid GameManager::EarnCollectionEvent(UILayer* uiLayer)\n{\n\tGameScene* gameScene = static_cast(uiLayer->getParent());\n\tconst Point& enemyPos = m_targetManager->GetEnemyPosition();\n\tconst Vec2& aboveCharacterPos = gameScene->GetCharacterPos() + Vec2(0, 100);\n\n\tm_curCollection = m_collectionManager->GetCollectionSprOfStage(m_stage);\n\tm_curCollection->setPosition(enemyPos);\n\tuiLayer->addChild(m_curCollection);\n\n\t\/\/part 1\n\tMoveBy* moveBy_00 = MoveBy::create(1.50f, Point(0, -10));\n\tMoveBy* moveBy_01 = MoveBy::create(1.00f, Point(0, -10));\n\n\tBlink* blink_00 = Blink::create(1.50f, 5);\n\tBlink* blink_01 = Blink::create(1.00f, 5);\n\n\tFadeIn* fadeIn_00 = FadeIn::create(1.50f);\n\tFadeOut* fadeOut_00 = FadeOut::create(1.00f);\n\n\tSpawn* spawn_00 = Spawn::create(fadeIn_00, moveBy_00, blink_00, NULL);\n\tSpawn* spawn_01 = Spawn::create(fadeOut_00, moveBy_01, blink_01, NULL);\n\n\t\/\/part 2\n\tCallFuncN* callFuncN = CallFuncN::create(CC_CALLBACK_0\n\t\t(GameManager::SetCollectionPos, this, aboveCharacterPos));\n\n\tMoveBy* moveBy_02 = MoveBy::create(1.50f, Point(0, -30));\n\tMoveBy* moveBy_03 = MoveBy::create(1.00f, Point(0, -20));\n\n\tBlink* blink_02 = Blink::create(1.50f, 5);\n\tBlink* blink_03 = Blink::create(1.00f, 5);\n\n\tFadeIn* fadeIn_01 = FadeIn::create(0.01f);\n\tFadeOut* fadeOut_01 = FadeOut::create(2.50f);\n\n\tSpawn* spawn_02 = Spawn::create(fadeIn_01, moveBy_02, blink_02, NULL);\n\tSpawn* spawn_03 = Spawn::create(fadeOut_01, moveBy_03, blink_03, NULL);\n\n\tSequence* sequence = Sequence::create(\n\t\tspawn_00, spawn_01, callFuncN, spawn_02, spawn_03, NULL);\n\n\tm_curCollection->runAction(sequence);\n}\n\nvoid GameManager::WinProgress(UILayer* uiLayer)\n{\n\tint lastStage = UserDefault::getInstance()->getIntegerForKey(ConstVars::LASTSTAGE);\n\n\tif (m_stage == lastStage &&\n\t\t(m_stage == CollectionManager::SHOES ||\n\t\tm_stage == CollectionManager::SCARF ||\n\t\tm_stage == CollectionManager::BOTTLE ||\n\t\tm_stage == CollectionManager::MONITOR ||\n\t\tm_stage == CollectionManager::LETTER))\n\t{\n\t\t\/\/EarnCollectionEvent(uiLayer);\n\n\t\t\/\/DelayTime* waitEventTime = DelayTime::create(4.50f);\n\t\t\/\/CallFuncN* showWidget = CallFuncN::create(CC_CALLBACK_0(\n\t\t\/\/\tUILayer::MakeSuccessWidget, uiLayer, m_stage));\n\t\t\/\/Sequence* waitAndshow = Sequence::create(waitEventTime, showWidget, NULL);\n\n\t\t\/\/uiLayer->runAction(waitAndshow);\n\t\tuiLayer->MakeSuccessWidget(m_stage);\n\t}\n\telse\n\t{\n\t\tif (m_stage==0)\n\t\t{\n\t\t\tDirector::getInstance()->popScene();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tuiLayer->MakeSuccessWidget(m_stage);\n\t\t}\n\t}\n\n\tif (lastStage == m_stage && m_stage + 1 <= StageInformation::GetMaxStageNum())\n\t{\n\t\tUserDefault::getInstance()->setIntegerForKey(ConstVars::LASTSTAGE, m_stage + 1);\n\t}\n}\n\nvoid GameManager::FailProgress(UILayer* uiLayer)\n{\n\tif (m_stage == 0)\n\t{\n\t\tDirector::getInstance()->popScene();\n\t}\n\telse\n\t{\n\t\tuiLayer->MakeFailWidget(m_stage);\n\t}\n}\n\nvoid GameManager::ControlWinFailProgress(UILayer* uiLayer)\n{\n\tif (!m_isJudged)\n\t{\n\t\tif (!m_targetManager->HasEnemy())\n\t\t{\n\t\t\tm_isJudged = true;\n\t\t\tm_sling->ShotComplete();\n\t\t\tWinProgress(uiLayer);\n\t\t}\n\t\telse if (!m_colliderManager->HasCollider()){\n\t\t\tm_isJudged = true;\n\t\t\tm_sling->ShotComplete();\n\t\t\tFailProgress(uiLayer);\n\t\t}\n\t}\n}\n\nbool GameManager::IsCollision(Target* target, Collider* collider)\n{\n\t\n\tfloat rotation = target->getRotation();\n\tconst Rect colliderBoundingBox = static_cast(collider)->GetBoundingArea();\n\tconst Rect targetBoundingBox = target->GetBoundingArea();\n\n\tif (rotation< 3 && rotation > -3 \n\t\t|| rotation< 93 && rotation > 87 \n\t\t|| rotation< 183 && rotation > 177 \n\t\t|| rotation< 273 && rotation > 267){ \/\/ȸ \n\t\t\/\/ 簢 浹 \t\n\t\tif (targetBoundingBox.intersectsRect(colliderBoundingBox))\n\t\t\treturn true;\n\n\t\treturn false;\n\t}\n\n\tfloat colliderX = collider->getPosition().x;\n\tfloat colliderY = collider->getPosition().y;\n\n\tfloat minX = targetBoundingBox.getMinX(); \/\/ left margin\n\tfloat maxX = targetBoundingBox.getMaxX(); \/\/ right margin\n\tfloat minY = targetBoundingBox.getMinY(); \/\/ lower margin\n\tfloat maxY = targetBoundingBox.getMaxY(); \/\/ upper margin\n\tPoint LL(minX, minY);\n\tPoint LU(minX, maxY);\n\tPoint RL(maxX, minY);\n\tPoint RU(maxX, maxY);\n\n\t\/\/ȸ簢\n\tLL.rotate(target->getPosition(), -CC_DEGREES_TO_RADIANS(target->getRotation()));\n\tLU.rotate(target->getPosition(), -CC_DEGREES_TO_RADIANS(target->getRotation()));\n\tRL.rotate(target->getPosition(), -CC_DEGREES_TO_RADIANS(target->getRotation()));\n\tRU.rotate(target->getPosition(), -CC_DEGREES_TO_RADIANS(target->getRotation()));\n\t\n\t\/\/ y = Ax + upperB\n\t\/\/ y = Ax + lowerB\n\t\/\/ y = -1\/Ax + leftB\n\t\/\/ y = -1\/Ax + rightB\n\tfloat a = (RU.y- LU.y) \/ (RU.x - LU.x); \/\/\n\t\n\t\/\/ RU.y = a * RU.x + upperB\n\tfloat upperB = RU.y - a * (RU.x);\n\tfloat lowerB = LL.y - a * (LL.x);\n\t\n\t\/\/ LL.y = (-1\/a) * LL.x + leftB\n\tfloat leftB = LL.y - (-1 \/ a) * LL.x;\n\tfloat rightB = RU.y - (-1 \/ a) * RU.x;\n\n\t\/\/ װ ȿ ִ üũ.\n\t\/\/ uppermargin lowermargin ̿ ִ X, Y (y-uppermargin) *(y-lowermargin) < 0 \n\t\/\/ left right .\n\t\n\t\/\/׿ dot\n\t\/\/makeDebugPoint(Point(colliderX, (colliderX * a + upperB)), target->getParent());\n\t\/\/makeDebugPoint(Point(colliderX, (colliderX * a + lowerB)), target->getParent());\n\t\/\/makeDebugPoint(Point(colliderX, (colliderX * (-1 \/ a) + rightB)), target->getParent());\n\t\/\/makeDebugPoint(Point(colliderX, (colliderX * (-1 \/ a) + leftB)), target->getParent());\n\n\tif (\n\t\t((colliderX * a + upperB) - colliderY) * ((colliderX * a + lowerB) - colliderY) < 0\n\t\t&&\n\t\t((colliderX * (-1 \/ a) + leftB) - colliderY) * ((colliderX * (-1 \/ a) + rightB) - colliderY) < 0\n\t\t)\n\t{\n\t\treturn true;\n\t}\n\telse \n\t\treturn false;\n\t\n}\n\nvoid GameManager::makeDebugPoint(Point p, Node* spr)\n{\n\tSprite* dot = Sprite::create(FileStuff::DEBRIS);\n\tdot->setScale(2.);\n\tspr->addChild(dot);\n\tPoint pos = spr->convertToWorldSpace(Point::ZERO);\n\tdot->setPosition(p - pos);\n\n\tSequence* action = Sequence::create(DelayTime::create(0.1), RemoveSelf::create(),NULL);\n\tdot->runAction(action);\n}<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit (ITK)\n Module:\n Language: C++\n Date:\n Version:\n\n\nCopyright (c) 2000 National Library of Medicine\nAll rights reserved.\n\nSee COPYRIGHT.txt for copyright details.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \n\/\/ This file has been generated by BuildHeaderTest.tcl\n\/\/ Test to include each header file for Insight\n\n#include \"itkAnalyzeImageIO.h\"\n#include \"itkAnalyzeImageIOFactory.h\"\n#include \"itkConvertPixelBuffer.txx\"\n#include \"itkDICOMImageIO2.h\"\n#include \"itkDICOMImageIO2Factory.h\"\n#include \"itkDefaultConvertPixelTraits.h\"\n#include \"itkDicomImageIO.h\"\n#include \"itkDicomImageIOFactory.h\"\n#include \"itkFileIteratorBase.h\"\n#include \"itkGE4ImageIO.h\"\n#include \"itkGE4ImageIOFactory.h\"\n#include \"itkGE5ImageIO.h\"\n#include \"itkGE5ImageIOFactory.h\"\n#include \"itkGEAdwImageIO.h\"\n#include \"itkGEAdwImageIOFactory.h\"\n#include \"itkGEImageHeader.h\"\n#include \"itkGiplImageIO.h\"\n#include \"itkGiplImageIOFactory.h\"\n#include \"itkIOCommon.h\"\n#include \"itkIPLCommonImageIO.h\"\n#include \"itkImageFileReader.txx\"\n#include \"itkImageFileWriter.txx\"\n#include \"itkImageIOBase.h\"\n#include \"itkImageIOFactory.h\"\n#include \"itkImageIORegion.h\"\n#include \"itkImageSeriesReader.txx\"\n#include \"itkImageSeriesWriter.txx\"\n#include \"itkImageWriter.txx\"\n#include \"itkMetaImageIO.h\"\n#include \"itkMetaImageIOFactory.h\"\n#include \"itkMvtSunf.h\"\n#include \"itkNumericSeriesFileIterator.h\"\n#include \"itkPNGImageIO.h\"\n#include \"itkPNGImageIOFactory.h\"\n#include \"itkRawImageIO.txx\"\n#include \"itkRawImageWriter.txx\"\n#include \"itkSiemensVisionImageIO.h\"\n#include \"itkSiemensVisionImageIOFactory.h\"\n#include \"itkStimulateImageIO.h\"\n#include \"itkStimulateImageIOFactory.h\"\n#include \"itkVOLImageIO.h\"\n#include \"itkVOLImageIOFactory.h\"\n#include \"itkVTKImageIO.h\"\n#include \"itkVTKImageIOFactory.h\"\n#include \"itkWriter.h\"\n#include \"pixeldata.h\"\n\nint main ( int , char* )\n{\n \n return 0;\n}\n\nENH: Updated to latest headers\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit (ITK)\n Module:\n Language: C++\n Date:\n Version:\n\n\nCopyright (c) 2000 National Library of Medicine\nAll rights reserved.\n\nSee COPYRIGHT.txt for copyright details.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \n\/\/ This file has been generated by BuildHeaderTest.tcl\n\/\/ Test to include each header file for Insight\n\n#include \"itkAnalyzeDbh.h\"\n#include \"itkAnalyzeImageIO.h\"\n#include \"itkAnalyzeImageIOFactory.h\"\n#include \"itkConvertPixelBuffer.txx\"\n#include \"itkDICOMImageIO2.h\"\n#include \"itkDICOMImageIO2Factory.h\"\n#include \"itkDefaultConvertPixelTraits.h\"\n#include \"itkDicomImageIO.h\"\n#include \"itkDicomImageIOFactory.h\"\n#include \"itkFileIteratorBase.h\"\n#include \"itkGE4ImageIO.h\"\n#include \"itkGE4ImageIOFactory.h\"\n#include \"itkGE5ImageIO.h\"\n#include \"itkGE5ImageIOFactory.h\"\n#include \"itkGEAdwImageIO.h\"\n#include \"itkGEAdwImageIOFactory.h\"\n#include \"itkGEImageHeader.h\"\n#include \"itkGiplImageIO.h\"\n#include \"itkGiplImageIOFactory.h\"\n#include \"itkIOCommon.h\"\n#include \"itkIPLCommonImageIO.h\"\n#include \"itkImageFileReader.txx\"\n#include \"itkImageFileWriter.txx\"\n#include \"itkImageIOBase.h\"\n#include \"itkImageIOFactory.h\"\n#include \"itkImageIORegion.h\"\n#include \"itkImageSeriesReader.txx\"\n#include \"itkImageSeriesWriter.txx\"\n#include \"itkImageWriter.txx\"\n#include \"itkMetaImageIO.h\"\n#include \"itkMetaImageIOFactory.h\"\n#include \"itkMvtSunf.h\"\n#include \"itkNumericSeriesFileIterator.h\"\n#include \"itkPNGImageIO.h\"\n#include \"itkPNGImageIOFactory.h\"\n#include \"itkRawImageIO.txx\"\n#include \"itkRawImageWriter.txx\"\n#include \"itkSiemensVisionImageIO.h\"\n#include \"itkSiemensVisionImageIOFactory.h\"\n#include \"itkStimulateImageIO.h\"\n#include \"itkStimulateImageIOFactory.h\"\n#include \"itkVOLImageIO.h\"\n#include \"itkVOLImageIOFactory.h\"\n#include \"itkVTKImageIO.h\"\n#include \"itkVTKImageIOFactory.h\"\n#include \"itkWriter.h\"\n#include \"pixeldata.h\"\n\nint main ( int , char* )\n{\n \n return 0;\n}\n\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n#include \"otbMultiResolutionPyramid.h\"\n\n#include \"otbImage.h\"\n#include \"otbVectorImage.h\"\n#include \"otbPerBandVectorImageFilter.h\"\n#include \"itkDiscreteGaussianImageFilter.h\"\n#include \"itkShrinkImageFilter.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbObjectList.h\"\n#include \"otbStreamingImageFileWriter.h\"\n#include \"otbCommandLineArgumentParser.h\"\n#include \"otbStandardWriterWatcher.h\"\n\nnamespace otb\n{\n\nint MultiResolutionPyramid::Describe(ApplicationDescriptor* descriptor)\n{\n descriptor->SetName(\"Multi-resolution pyramid tool\");\n descriptor->SetDescription(\"Build a multi-resolution pyramid of the image.\");\n descriptor->AddInputImage();\n descriptor->AddOption(\"NumberOfLevels\",\"Number of levels in the pyramid (default is 1)\",\"level\",1,false, ApplicationDescriptor::Integer);\n descriptor->AddOption(\"ShrinkFactor\",\"Subsampling factor (default is 2)\",\"sfactor\",1,false, ApplicationDescriptor::Integer);\n descriptor->AddOption(\"VarianceFactor\",\"Before subsampling, image is smoothed with a gaussian kernel of variance VarianceFactor*ShrinkFactor. Higher values will result in more blur, lower in more aliasing (default is 0.6)\",\"vfactor\",1,false,ApplicationDescriptor::Real);\n descriptor->AddOption(\"FastScheme\",\"If used, this option allows to speed-up computation by iteratively subsampling previous level of pyramid instead of processing the full input image each time. Please note that this may result in extra blur or extra aliasing.\",\"fast\",0,false,ApplicationDescriptor::Integer);\n descriptor->AddOption(\"OutputPrefixAndExtextension\",\"prefix for the output files, and extension\",\"out\",2,true,ApplicationDescriptor::String);\n descriptor->AddOption(\"AvailableMemory\",\"Set the maximum of available memory for the pipeline execution in mega bytes (optional, 256 by default)\",\"ram\", 1, false, otb::ApplicationDescriptor::Integer);\n return EXIT_SUCCESS;\n}\n\nint MultiResolutionPyramid::Execute(otb::ApplicationOptionsResult* parseResult)\n{\n const unsigned int Dimension = 2;\n typedef otb::Image USImageType;\n typedef otb::VectorImage USVectorImageType;\n typedef otb::Image SImageType;\n typedef otb::VectorImage SVectorImageType;\n typedef otb::ImageFileReader ReaderType;\n typedef itk::DiscreteGaussianImageFilter SmoothingImageFilterType;\n typedef otb::PerBandVectorImageFilter SmoothingVectorImageFilterType;\n typedef itk::ShrinkImageFilter ShrinkFilterType;\n typedef otb::StreamingImageFileWriter WriterType;\n\n unsigned int nbLevels = 1;\n \n if(parseResult->IsOptionPresent(\"NumberOfLevels\"))\n {\n nbLevels = parseResult->GetParameterUInt(\"NumberOfLevels\");\n }\n\n unsigned int shrinkFactor = 2;\n\n if(parseResult->IsOptionPresent(\"ShrinkFactor\"))\n {\n shrinkFactor = parseResult->GetParameterUInt(\"ShrinkFactor\");\n }\n\n double varianceFactor = 0.6;\n \n if(parseResult->IsOptionPresent(\"VarianceFactor\"))\n {\n varianceFactor = parseResult->GetParameterDouble(\"VarianceFactor\");\n }\n\n bool fastScheme = parseResult->IsOptionPresent(\"FastScheme\");\n\n std::string prefix = parseResult->GetParameterString(\"OutputPrefixAndExtextension\",0);\n std::string ext = parseResult->GetParameterString(\"OutputPrefixAndExtextension\",1);\n\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName(parseResult->GetInputImage());\n\n unsigned int currentLevel = 1;\n unsigned int currentFactor = shrinkFactor;\n\n while(currentLevel <= nbLevels)\n {\n std::cout<<\"Processing level \"< 1)\n {\n itk::OStringStream oss;\n oss<SetFileName(oss.str().c_str());\n }\n\n\n SmoothingVectorImageFilterType::Pointer smoothingFilter = SmoothingVectorImageFilterType::New();\n smoothingFilter->SetInput(reader->GetOutput());\n\n \/\/ According to\n \/\/ http:\/\/www.ipol.im\/pub\/algo\/gjmr_line_segment_detector\/\n \/\/ This is a good balance between blur and aliasing\n double variance = varianceFactor * static_cast(currentFactor);\n smoothingFilter->GetFilter()->SetVariance(variance);\n\n ShrinkFilterType::Pointer shrinkFilter = ShrinkFilterType::New();\n shrinkFilter->SetInput(smoothingFilter->GetOutput());\n shrinkFilter->SetShrinkFactors(currentFactor);\n\n itk::OStringStream oss;\n oss<SetInput(shrinkFilter->GetOutput());\n writer->SetFileName(oss.str().c_str());\n\n unsigned int ram = 256;\n if (parseResult->IsOptionPresent(\"AvailableMemory\"))\n {\n ram = parseResult->GetParameterUInt(\"AvailableMemory\");\n }\n writer->SetAutomaticTiledStreaming(ram);\n \n oss.str(\"\");\n oss<<\"Writing \"<Update();\n\n if(!fastScheme)\n {\n currentFactor*=shrinkFactor;\n }\n \n ++currentLevel;\n }\n\n return EXIT_SUCCESS;\n}\n\n}\n\nSTYLE\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n#include \"otbMultiResolutionPyramid.h\"\n\n#include \"otbImage.h\"\n#include \"otbVectorImage.h\"\n#include \"otbPerBandVectorImageFilter.h\"\n#include \"itkDiscreteGaussianImageFilter.h\"\n#include \"itkShrinkImageFilter.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbObjectList.h\"\n#include \"otbStreamingImageFileWriter.h\"\n#include \"otbCommandLineArgumentParser.h\"\n#include \"otbStandardWriterWatcher.h\"\n\nnamespace otb\n{\n\nint MultiResolutionPyramid::Describe(ApplicationDescriptor* descriptor)\n{\n descriptor->SetName(\"Multi-resolution pyramid tool\");\n descriptor->SetDescription(\"Build a multi-resolution pyramid of the image.\");\n descriptor->AddInputImage();\n descriptor->AddOption(\"NumberOfLevels\",\"Number of levels in the pyramid (default is 1)\",\"level\", 1, false, ApplicationDescriptor::Integer);\n descriptor->AddOption(\"ShrinkFactor\",\"Subsampling factor (default is 2)\",\"sfactor\", 1, false, ApplicationDescriptor::Integer);\n descriptor->AddOption(\"VarianceFactor\",\"Before subsampling, image is smoothed with a gaussian kernel of variance VarianceFactor*ShrinkFactor. Higher values will result in more blur, lower in more aliasing (default is 0.6)\",\"vfactor\", 1, false, ApplicationDescriptor::Real);\n descriptor->AddOption(\"FastScheme\",\"If used, this option allows to speed-up computation by iteratively subsampling previous level of pyramid instead of processing the full input image each time. Please note that this may result in extra blur or extra aliasing.\",\"fast\", 0, false, ApplicationDescriptor::Integer);\n descriptor->AddOption(\"OutputPrefixAndExtextension\",\"prefix for the output files, and extension\",\"out\", 2, true, ApplicationDescriptor::String);\n descriptor->AddOption(\"AvailableMemory\",\"Set the maximum of available memory for the pipeline execution in mega bytes (optional, 256 by default)\",\"ram\", 1, false, otb::ApplicationDescriptor::Integer);\n return EXIT_SUCCESS;\n}\n\nint MultiResolutionPyramid::Execute(otb::ApplicationOptionsResult* parseResult)\n{\n const unsigned int Dimension = 2;\n typedef otb::Image USImageType;\n typedef otb::VectorImage USVectorImageType;\n typedef otb::Image SImageType;\n typedef otb::VectorImage SVectorImageType;\n typedef otb::ImageFileReader ReaderType;\n typedef itk::DiscreteGaussianImageFilter SmoothingImageFilterType;\n typedef otb::PerBandVectorImageFilter SmoothingVectorImageFilterType;\n typedef itk::ShrinkImageFilter ShrinkFilterType;\n typedef otb::StreamingImageFileWriter WriterType;\n\n unsigned int nbLevels = 1;\n \n if(parseResult->IsOptionPresent(\"NumberOfLevels\"))\n {\n nbLevels = parseResult->GetParameterUInt(\"NumberOfLevels\");\n }\n\n unsigned int shrinkFactor = 2;\n\n if(parseResult->IsOptionPresent(\"ShrinkFactor\"))\n {\n shrinkFactor = parseResult->GetParameterUInt(\"ShrinkFactor\");\n }\n\n double varianceFactor = 0.6;\n \n if(parseResult->IsOptionPresent(\"VarianceFactor\"))\n {\n varianceFactor = parseResult->GetParameterDouble(\"VarianceFactor\");\n }\n\n bool fastScheme = parseResult->IsOptionPresent(\"FastScheme\");\n\n std::string prefix = parseResult->GetParameterString(\"OutputPrefixAndExtextension\", 0);\n std::string ext = parseResult->GetParameterString(\"OutputPrefixAndExtextension\", 1);\n\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName(parseResult->GetInputImage());\n\n unsigned int currentLevel = 1;\n unsigned int currentFactor = shrinkFactor;\n\n while(currentLevel <= nbLevels)\n {\n std::cout<<\"Processing level \"< 1)\n {\n itk::OStringStream oss;\n oss<SetFileName(oss.str().c_str());\n }\n\n\n SmoothingVectorImageFilterType::Pointer smoothingFilter = SmoothingVectorImageFilterType::New();\n smoothingFilter->SetInput(reader->GetOutput());\n\n \/\/ According to\n \/\/ http:\/\/www.ipol.im\/pub\/algo\/gjmr_line_segment_detector\/\n \/\/ This is a good balance between blur and aliasing\n double variance = varianceFactor * static_cast(currentFactor);\n smoothingFilter->GetFilter()->SetVariance(variance);\n\n ShrinkFilterType::Pointer shrinkFilter = ShrinkFilterType::New();\n shrinkFilter->SetInput(smoothingFilter->GetOutput());\n shrinkFilter->SetShrinkFactors(currentFactor);\n\n itk::OStringStream oss;\n oss<SetInput(shrinkFilter->GetOutput());\n writer->SetFileName(oss.str().c_str());\n\n unsigned int ram = 256;\n if (parseResult->IsOptionPresent(\"AvailableMemory\"))\n {\n ram = parseResult->GetParameterUInt(\"AvailableMemory\");\n }\n writer->SetAutomaticTiledStreaming(ram);\n \n oss.str(\"\");\n oss<<\"Writing \"<Update();\n\n if(!fastScheme)\n {\n currentFactor*=shrinkFactor;\n }\n \n ++currentLevel;\n }\n\n return EXIT_SUCCESS;\n}\n\n}\n\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkHandleRepresentation.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkHandleRepresentation.h\"\n#include \"vtkCoordinate.h\"\n#include \"vtkInteractorObserver.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n\n\nvtkCxxRevisionMacro(vtkHandleRepresentation, \"1.7\");\n\n\/\/----------------------------------------------------------------------\nvtkHandleRepresentation::vtkHandleRepresentation()\n{\n \/\/ Positions are maintained via a vtkCoordinate\n this->DisplayPosition = vtkCoordinate::New();\n this->DisplayPosition->SetCoordinateSystemToDisplay();\n\n this->WorldPosition = vtkCoordinate::New();\n this->WorldPosition->SetCoordinateSystemToWorld();\n\n this->InteractionState = vtkHandleRepresentation::Outside;\n this->Tolerance = 15;\n this->ActiveRepresentation = 0;\n this->Constrained = 0;\n\n this->DisplayPositionTime.Modified();\n this->WorldPositionTime.Modified();\n}\n\n\/\/----------------------------------------------------------------------\nvtkHandleRepresentation::~vtkHandleRepresentation()\n{\n this->DisplayPosition->Delete();\n this->WorldPosition->Delete();\n}\n\n\/\/----------------------------------------------------------------------\nvoid vtkHandleRepresentation::SetDisplayPosition(double pos[3])\n{\n this->DisplayPosition->SetValue(pos);\n if ( this->Renderer )\n {\n double *p = this->DisplayPosition->GetComputedWorldValue(this->Renderer);\n this->WorldPosition->SetValue(p[0], p[1], p[2]);\n }\n this->DisplayPositionTime.Modified();\n}\n\n\/\/----------------------------------------------------------------------\nvoid vtkHandleRepresentation::GetDisplayPosition(double pos[3])\n{\n \/\/ The world position maintains the position\n if ( this->Renderer && (this->WorldPositionTime > this->DisplayPositionTime) )\n {\n int *p = this->WorldPosition->GetComputedDisplayValue(this->Renderer);\n this->DisplayPosition->SetValue(p[0],p[1],0.0);\n }\n this->DisplayPosition->GetValue(pos);\n}\n\ndouble* vtkHandleRepresentation::GetDisplayPosition()\n{\n return this->DisplayPosition->GetValue();\n}\n\n\/\/----------------------------------------------------------------------\nvoid vtkHandleRepresentation::SetWorldPosition(double pos[3])\n{\n this->WorldPosition->SetValue(pos);\n this->WorldPositionTime.Modified();\n}\n\n\/\/----------------------------------------------------------------------\nvoid vtkHandleRepresentation::GetWorldPosition(double pos[3])\n{\n this->WorldPosition->GetValue(pos);\n}\n\ndouble* vtkHandleRepresentation::GetWorldPosition()\n{\n return this->WorldPosition->GetValue();\n}\n\n\/\/----------------------------------------------------------------------\nvoid vtkHandleRepresentation::SetRenderer(vtkRenderer *ren)\n{\n this->DisplayPosition->SetViewport(ren);\n this->WorldPosition->SetViewport(ren);\n this->Superclass::SetRenderer(ren);\n}\n\n\/\/----------------------------------------------------------------------\nvoid vtkHandleRepresentation::ShallowCopy(vtkProp *prop)\n{\n vtkHandleRepresentation *rep = vtkHandleRepresentation::SafeDownCast(prop);\n if ( rep )\n {\n this->SetTolerance(rep->GetTolerance());\n this->SetActiveRepresentation(rep->GetActiveRepresentation());\n this->SetConstrained(rep->GetConstrained());\n }\n this->Superclass::ShallowCopy(prop);\n}\n\n\/\/----------------------------------------------------------------------\nunsigned long vtkHandleRepresentation::GetMTime()\n{\n unsigned long mTime=this->Superclass::GetMTime();\n unsigned long wMTime=this->WorldPosition->GetMTime();\n mTime = ( wMTime > mTime ? wMTime : mTime );\n unsigned long dMTime=this->DisplayPosition->GetMTime();\n mTime = ( dMTime > mTime ? dMTime : mTime );\n \n return mTime;\n}\n\n\/\/----------------------------------------------------------------------\nvoid vtkHandleRepresentation::PrintSelf(ostream& os, vtkIndent indent)\n{\n \/\/Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h\n this->Superclass::PrintSelf(os,indent);\n \n double p[3];\n this->GetDisplayPosition(p);\n os << indent << \"Display Position: (\" << p[0] << \", \"\n << p[1] << \", \" << p[2] << \")\\n\";\n\n this->GetWorldPosition(p);\n os << indent << \"World Position: (\" << p[0] << \", \"\n << p[1] << \", \" << p[2] << \")\\n\";\n\n os << indent << \"Constrained: \" \n << (this->Constrained ? \"On\" : \"Off\") << \"\\n\";\n\n os << indent << \"Tolerance: \" << this->Tolerance << \"\\n\";\n\n os << indent << \"Active Representation: \" \n << (this->ActiveRepresentation ? \"On\" : \"Off\") << \"\\n\";\n}\nSTYLE:Marked method\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkHandleRepresentation.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkHandleRepresentation.h\"\n#include \"vtkCoordinate.h\"\n#include \"vtkInteractorObserver.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n\n\nvtkCxxRevisionMacro(vtkHandleRepresentation, \"1.8\");\n\n\/\/----------------------------------------------------------------------\nvtkHandleRepresentation::vtkHandleRepresentation()\n{\n \/\/ Positions are maintained via a vtkCoordinate\n this->DisplayPosition = vtkCoordinate::New();\n this->DisplayPosition->SetCoordinateSystemToDisplay();\n\n this->WorldPosition = vtkCoordinate::New();\n this->WorldPosition->SetCoordinateSystemToWorld();\n\n this->InteractionState = vtkHandleRepresentation::Outside;\n this->Tolerance = 15;\n this->ActiveRepresentation = 0;\n this->Constrained = 0;\n\n this->DisplayPositionTime.Modified();\n this->WorldPositionTime.Modified();\n}\n\n\/\/----------------------------------------------------------------------\nvtkHandleRepresentation::~vtkHandleRepresentation()\n{\n this->DisplayPosition->Delete();\n this->WorldPosition->Delete();\n}\n\n\/\/----------------------------------------------------------------------\nvoid vtkHandleRepresentation::SetDisplayPosition(double pos[3])\n{\n this->DisplayPosition->SetValue(pos);\n if ( this->Renderer )\n {\n double *p = this->DisplayPosition->GetComputedWorldValue(this->Renderer);\n this->WorldPosition->SetValue(p[0], p[1], p[2]);\n }\n this->DisplayPositionTime.Modified();\n}\n\n\/\/----------------------------------------------------------------------\nvoid vtkHandleRepresentation::GetDisplayPosition(double pos[3])\n{\n \/\/ The world position maintains the position\n if ( this->Renderer && (this->WorldPositionTime > this->DisplayPositionTime) )\n {\n int *p = this->WorldPosition->GetComputedDisplayValue(this->Renderer);\n this->DisplayPosition->SetValue(p[0],p[1],0.0);\n }\n this->DisplayPosition->GetValue(pos);\n}\n\n\/\/----------------------------------------------------------------------\ndouble* vtkHandleRepresentation::GetDisplayPosition()\n{\n return this->DisplayPosition->GetValue();\n}\n\n\/\/----------------------------------------------------------------------\nvoid vtkHandleRepresentation::SetWorldPosition(double pos[3])\n{\n this->WorldPosition->SetValue(pos);\n this->WorldPositionTime.Modified();\n}\n\n\/\/----------------------------------------------------------------------\nvoid vtkHandleRepresentation::GetWorldPosition(double pos[3])\n{\n this->WorldPosition->GetValue(pos);\n}\n\ndouble* vtkHandleRepresentation::GetWorldPosition()\n{\n return this->WorldPosition->GetValue();\n}\n\n\/\/----------------------------------------------------------------------\nvoid vtkHandleRepresentation::SetRenderer(vtkRenderer *ren)\n{\n this->DisplayPosition->SetViewport(ren);\n this->WorldPosition->SetViewport(ren);\n this->Superclass::SetRenderer(ren);\n}\n\n\/\/----------------------------------------------------------------------\nvoid vtkHandleRepresentation::ShallowCopy(vtkProp *prop)\n{\n vtkHandleRepresentation *rep = vtkHandleRepresentation::SafeDownCast(prop);\n if ( rep )\n {\n this->SetTolerance(rep->GetTolerance());\n this->SetActiveRepresentation(rep->GetActiveRepresentation());\n this->SetConstrained(rep->GetConstrained());\n }\n this->Superclass::ShallowCopy(prop);\n}\n\n\/\/----------------------------------------------------------------------\nunsigned long vtkHandleRepresentation::GetMTime()\n{\n unsigned long mTime=this->Superclass::GetMTime();\n unsigned long wMTime=this->WorldPosition->GetMTime();\n mTime = ( wMTime > mTime ? wMTime : mTime );\n unsigned long dMTime=this->DisplayPosition->GetMTime();\n mTime = ( dMTime > mTime ? dMTime : mTime );\n \n return mTime;\n}\n\n\/\/----------------------------------------------------------------------\nvoid vtkHandleRepresentation::PrintSelf(ostream& os, vtkIndent indent)\n{\n \/\/Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h\n this->Superclass::PrintSelf(os,indent);\n \n double p[3];\n this->GetDisplayPosition(p);\n os << indent << \"Display Position: (\" << p[0] << \", \"\n << p[1] << \", \" << p[2] << \")\\n\";\n\n this->GetWorldPosition(p);\n os << indent << \"World Position: (\" << p[0] << \", \"\n << p[1] << \", \" << p[2] << \")\\n\";\n\n os << indent << \"Constrained: \" \n << (this->Constrained ? \"On\" : \"Off\") << \"\\n\";\n\n os << indent << \"Tolerance: \" << this->Tolerance << \"\\n\";\n\n os << indent << \"Active Representation: \" \n << (this->ActiveRepresentation ? \"On\" : \"Off\") << \"\\n\";\n}\n<|endoftext|>"} {"text":"#include \"Camera.h\"\n#include \"Utility.h\"\n#include \n#include \n#include \n#include \n#include \n\nCamera::Camera( glm::vec2 windowSize, ProjectionType type, glm::vec2 zLimits) :\n\twindowSize( windowSize ), projectionType( type ), projectionZLimit( zLimits ),\n\tposition({ 0.0f, 5.0f, 0.0f }), forward({ 0.0f, 0.0f, -1.0f }), up({ 0.0f, 1.0f, 0.0f }), axis(glm::cross(forward, up))\n{\n\tsetupView();\n\trefreshProjection();\n\trefreshViewProjection();\n}\n\n\nCamera::~Camera(void)\n{\n}\n\n\/\/ VIEW\nvoid Camera::setupView()\n{\n\tview = glm::lookAt(position, position + forward, -glm::cross(forward,axis));\n\trefreshViewProjection();\n}\n\nvoid Camera::applyOffset(glm::vec3 offset)\n{\n\tposition += offset;\n\tsetupView();\n}\n\nvoid Camera::setMoveForward(bool movement) {\n\tmoveForward = movement;\n}\n\nvoid Camera::setMoveBackward(bool movement) {\n\tmoveBackward = movement;\n}\n\nvoid Camera::setMoveLeft(bool movement) {\n\tmoveLeft = movement;\n}\n\nvoid Camera::setMoveRight(bool movement) {\n\tmoveRight = movement;\n}\n\nvoid Camera::rotate(int idx, int idy)\n{\n\tfloat dx = -100.f * idx \/ windowSize.x;\n\tfloat dy = -100.f * idy \/ windowSize.y;\n\n\tauto pitch = glm::angleAxis(dy, axis);\n\tauto heading = glm::angleAxis(dx, up);\n\n\tglm::quat temp = glm::cross(pitch, heading);\n\ttemp = glm::normalize(temp);\n\t\/\/update the direction from the quaternion\n\tforward = glm::rotate(temp, forward);\n\taxis = glm::rotate(heading, axis);\n\t\/\/ if up changes, camera becomes too free\n\t\/\/up = glm::rotate(pitch, up);\n\n\tsetupView();\n}\n\nvoid Camera::update(float dt)\n{\n\tint forwardMovement = (moveForward ? 1 : 0) + (moveBackward ? -1 : 0);\n\tif (forwardMovement != 0) {\n\t\tapplyOffset( forward * (forwardMovement * dt * 10.0f) );\n\t}\n\tint sideMovement = (moveLeft ? -1 : 0) + (moveRight ? 1 : 0);\n\tif (sideMovement != 0) {\n\t\tapplyOffset( axis * (sideMovement * dt * 10.0f) );\n\t}\n}\n\nconst glm::mat4 & Camera::getView() const\n{\n\treturn view;\n}\n\n\/\/ PROJECTION\n\nvoid Camera::refreshProjection()\n{\n\tif (projectionType == PERSPECTIVE) {\n\t\tsetupPerspectiveProjection( 45.0f, windowSize.x\/windowSize.y, projectionZLimit.x, projectionZLimit.y);\n\t}\n\telse {\n\t\t\/\/ TODO: projection start and size are dependant on the world and cameras relative eye offset\n\t\t\/\/ Ortho size could and should be open to outside interpretations, for now it is fixed\n\t\tsetupOtrhographicProjection({ 0.0f,0.0f }, { windowSize.x,windowSize.y }, projectionZLimit.x, projectionZLimit.y);\n\t}\n}\n\nvoid Camera::setupOtrhographicProjection(glm::vec2 projectionStart, glm::vec2 projectionSize, float zNear, float zFar)\n{\n\tprojectionType = ProjectionType::OTRHOGRAPHIC;\n\tthis->projectionStart = projectionStart;\n\tthis->projectionSize = projectionSize;\n\tprojection = glm::ortho(\n\t\tprojectionStart.x, projectionStart.x + projectionSize.x, \n\t\tprojectionStart.y, projectionStart.y + projectionSize.y, \n\t\tzNear, zFar);\n\trefreshViewProjection();\n}\n\nvoid Camera::setupPerspectiveProjection(float fovy, float aspectRatio, float zNear, float zFar)\n{\n\tprojectionType = ProjectionType::PERSPECTIVE;\n\tprojection = glm::perspective(fovy, aspectRatio, zNear, zFar);\n\trefreshViewProjection();\n}\n\nconst glm::mat4 & Camera::getProjection() const\n{\n\treturn projection;\n}\n\n\/\/ VIEW PROJECTION\nvoid Camera::refreshViewProjection()\n{\n\tviewProjection = projection * view;\n}\n\nconst glm::mat4& Camera::getViewProjection() const\n{\n\treturn viewProjection;\n}\n\nvoid Camera::updateCamera()\n{\n\t\/\/ OLD: \n\t\/*glMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\n\tglTranslatef(0, 0, -distance);\n\n\tglRotatef(angles.x, 1.0, 0.0, 0.0);\n\tglRotatef(angles.y, 0.0, 1.0, 0.0);\n\n\tglTranslatef(-center.x, -center.y, -center.z);*\/\n\t\/*glMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(FOVy, aspectRatio, NCP, FCP); *\/\n\tfrustum.setupGLProjection();\n\tfrustum.CalculateFrustum();\n}\n\n\/\/ VIEWPORT\nvoid Camera::windowDidResize(float width, float height)\n{\n\t\/\/ TODO: viewport could stretch to fit, or it could be static\n\twindowSize.x = width;\n\twindowSize.y = height;\n\tsetupViewport(0,0,width,height);\n\trefreshProjection();\n}\n\nvoid Camera::setupViewport(float x, float y, float width, float height)\n{\n\tviewportPos.x = x;\n\tviewportPos.y = y;\n\tviewportSize.x = width;\n\tviewportSize.y = height;\n}\n\nvoid Camera::loadViewport()\n{\n\tglViewport(viewportPos.x, viewportPos.y, viewportSize.x, viewportSize.y);\n}\n\nconst Frustum & Camera::getFrustum() const\n{\n\treturn frustum;\n}\nSpeed up camera movement.#include \"Camera.h\"\n#include \"Utility.h\"\n#include \n#include \n#include \n#include \n#include \n\nCamera::Camera( glm::vec2 windowSize, ProjectionType type, glm::vec2 zLimits) :\n\twindowSize( windowSize ), projectionType( type ), projectionZLimit( zLimits ),\n\tposition({ 0.0f, 5.0f, 0.0f }), forward({ 0.0f, 0.0f, -1.0f }), up({ 0.0f, 1.0f, 0.0f }), axis(glm::cross(forward, up))\n{\n\tsetupView();\n\trefreshProjection();\n\trefreshViewProjection();\n}\n\n\nCamera::~Camera(void)\n{\n}\n\n\/\/ VIEW\nvoid Camera::setupView()\n{\n\tview = glm::lookAt(position, position + forward, -glm::cross(forward,axis));\n\trefreshViewProjection();\n}\n\nvoid Camera::applyOffset(glm::vec3 offset)\n{\n\tposition += offset;\n\tsetupView();\n}\n\nvoid Camera::setMoveForward(bool movement) {\n\tmoveForward = movement;\n}\n\nvoid Camera::setMoveBackward(bool movement) {\n\tmoveBackward = movement;\n}\n\nvoid Camera::setMoveLeft(bool movement) {\n\tmoveLeft = movement;\n}\n\nvoid Camera::setMoveRight(bool movement) {\n\tmoveRight = movement;\n}\n\nvoid Camera::rotate(int idx, int idy)\n{\n\tfloat dx = -100.f * idx \/ windowSize.x;\n\tfloat dy = -100.f * idy \/ windowSize.y;\n\n\tauto pitch = glm::angleAxis(dy, axis);\n\tauto heading = glm::angleAxis(dx, up);\n\n\tglm::quat temp = glm::cross(pitch, heading);\n\ttemp = glm::normalize(temp);\n\t\/\/update the direction from the quaternion\n\tforward = glm::rotate(temp, forward);\n\taxis = glm::rotate(heading, axis);\n\t\/\/ if up changes, camera becomes too free\n\t\/\/up = glm::rotate(pitch, up);\n\n\tsetupView();\n}\n\nvoid Camera::update(float dt)\n{\n\tfloat speed = 30.0f;\n\tint forwardMovement = (moveForward ? 1 : 0) + (moveBackward ? -1 : 0);\n\tif (forwardMovement != 0) {\n\t\tapplyOffset( forward * (forwardMovement * dt * speed) );\n\t}\n\tint sideMovement = (moveLeft ? -1 : 0) + (moveRight ? 1 : 0);\n\tif (sideMovement != 0) {\n\t\tapplyOffset( axis * (sideMovement * dt * speed) );\n\t}\n}\n\nconst glm::mat4 & Camera::getView() const\n{\n\treturn view;\n}\n\n\/\/ PROJECTION\n\nvoid Camera::refreshProjection()\n{\n\tif (projectionType == PERSPECTIVE) {\n\t\tsetupPerspectiveProjection( 45.0f, windowSize.x\/windowSize.y, projectionZLimit.x, projectionZLimit.y);\n\t}\n\telse {\n\t\t\/\/ TODO: projection start and size are dependant on the world and cameras relative eye offset\n\t\t\/\/ Ortho size could and should be open to outside interpretations, for now it is fixed\n\t\tsetupOtrhographicProjection({ 0.0f,0.0f }, { windowSize.x,windowSize.y }, projectionZLimit.x, projectionZLimit.y);\n\t}\n}\n\nvoid Camera::setupOtrhographicProjection(glm::vec2 projectionStart, glm::vec2 projectionSize, float zNear, float zFar)\n{\n\tprojectionType = ProjectionType::OTRHOGRAPHIC;\n\tthis->projectionStart = projectionStart;\n\tthis->projectionSize = projectionSize;\n\tprojection = glm::ortho(\n\t\tprojectionStart.x, projectionStart.x + projectionSize.x, \n\t\tprojectionStart.y, projectionStart.y + projectionSize.y, \n\t\tzNear, zFar);\n\trefreshViewProjection();\n}\n\nvoid Camera::setupPerspectiveProjection(float fovy, float aspectRatio, float zNear, float zFar)\n{\n\tprojectionType = ProjectionType::PERSPECTIVE;\n\tprojection = glm::perspective(fovy, aspectRatio, zNear, zFar);\n\trefreshViewProjection();\n}\n\nconst glm::mat4 & Camera::getProjection() const\n{\n\treturn projection;\n}\n\n\/\/ VIEW PROJECTION\nvoid Camera::refreshViewProjection()\n{\n\tviewProjection = projection * view;\n}\n\nconst glm::mat4& Camera::getViewProjection() const\n{\n\treturn viewProjection;\n}\n\nvoid Camera::updateCamera()\n{\n\t\/\/ OLD: \n\t\/*glMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\n\tglTranslatef(0, 0, -distance);\n\n\tglRotatef(angles.x, 1.0, 0.0, 0.0);\n\tglRotatef(angles.y, 0.0, 1.0, 0.0);\n\n\tglTranslatef(-center.x, -center.y, -center.z);*\/\n\t\/*glMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(FOVy, aspectRatio, NCP, FCP); *\/\n\tfrustum.setupGLProjection();\n\tfrustum.CalculateFrustum();\n}\n\n\/\/ VIEWPORT\nvoid Camera::windowDidResize(float width, float height)\n{\n\t\/\/ TODO: viewport could stretch to fit, or it could be static\n\twindowSize.x = width;\n\twindowSize.y = height;\n\tsetupViewport(0,0,width,height);\n\trefreshProjection();\n}\n\nvoid Camera::setupViewport(float x, float y, float width, float height)\n{\n\tviewportPos.x = x;\n\tviewportPos.y = y;\n\tviewportSize.x = width;\n\tviewportSize.y = height;\n}\n\nvoid Camera::loadViewport()\n{\n\tglViewport(viewportPos.x, viewportPos.y, viewportSize.x, viewportSize.y);\n}\n\nconst Frustum & Camera::getFrustum() const\n{\n\treturn frustum;\n}\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2014 Couchbase, Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"config.h\"\n#include \"ep_engine.h\"\n#include \"connmap.h\"\n#include \"dcp-backfill-manager.h\"\n#include \"dcp-backfill.h\"\n#include \"dcp-producer.h\"\n\nstatic const size_t sleepTime = 1;\n\nclass BackfillManagerTask : public GlobalTask {\npublic:\n BackfillManagerTask(EventuallyPersistentEngine* e, connection_t c,\n const Priority &p, double sleeptime = 0,\n bool shutdown = false)\n : GlobalTask(e, p, sleeptime, shutdown), conn(c) {}\n\n bool run();\n\n std::string getDescription();\n\nprivate:\n connection_t conn;\n};\n\nbool BackfillManagerTask::run() {\n DcpProducer* producer = static_cast(conn.get());\n if (producer->doDisconnect()) {\n return false;\n }\n\n backfill_status_t status = producer->getBackfillManager()->backfill();\n if (status == backfill_finished) {\n return false;\n } else if (status == backfill_snooze) {\n snooze(sleepTime);\n }\n\n if (engine->getEpStats().isShutdown) {\n return false;\n }\n\n return true;\n}\n\nstd::string BackfillManagerTask::getDescription() {\n std::stringstream ss;\n ss << \"Backfilling items for \" << conn->getName();\n return ss.str();\n}\n\nBackfillManager::BackfillManager(EventuallyPersistentEngine* e, connection_t c)\n : engine(e), conn(c), managerTask(NULL) {\n\n Configuration& config = e->getConfiguration();\n\n scanBuffer.bytesRead = 0;\n scanBuffer.itemsRead = 0;\n scanBuffer.maxBytes = config.getDcpScanByteLimit();\n scanBuffer.maxItems = config.getDcpScanItemLimit();\n\n buffer.bytesRead = 0;\n buffer.maxBytes = config.getDcpBackfillByteLimit();\n buffer.nextReadSize = 0;\n buffer.full = false;\n}\n\nBackfillManager::~BackfillManager() {\n LockHolder lh(lock);\n if (managerTask) {\n managerTask->cancel();\n }\n\n while (!activeBackfills.empty()) {\n DCPBackfill* backfill = activeBackfills.front();\n activeBackfills.pop();\n backfill->cancel();\n delete backfill;\n }\n\n while (!snoozingBackfills.empty()) {\n DCPBackfill* backfill = (snoozingBackfills.front()).second;\n snoozingBackfills.pop_front();\n backfill->cancel();\n delete backfill;\n }\n}\n\nvoid BackfillManager::schedule(stream_t stream, uint64_t start, uint64_t end) {\n LockHolder lh(lock);\n activeBackfills.push(new DCPBackfill(engine, stream, start, end));\n\n if (managerTask) {\n managerTask->snooze(0);\n return;\n }\n\n managerTask = new BackfillManagerTask(engine, conn,\n Priority::BackfillTaskPriority);\n ExecutorPool::get()->schedule(managerTask, NONIO_TASK_IDX);\n}\n\nbool BackfillManager::bytesRead(uint32_t bytes) {\n LockHolder lh(lock);\n if (scanBuffer.itemsRead >= scanBuffer.maxItems) {\n return false;\n }\n\n \/\/ Always allow an item to be backfilled if the scan buffer is empty,\n \/\/ otherwise check to see if there is room for the item.\n if (scanBuffer.bytesRead + bytes <= scanBuffer.maxBytes ||\n scanBuffer.bytesRead == 0) {\n scanBuffer.bytesRead += bytes;\n }\n\n if (buffer.bytesRead == 0 || buffer.bytesRead + bytes <= buffer.maxBytes) {\n buffer.bytesRead += bytes;\n } else {\n scanBuffer.bytesRead -= bytes;\n buffer.full = true;\n buffer.nextReadSize = bytes;\n return false;\n }\n\n scanBuffer.itemsRead++;\n\n return true;\n}\n\nvoid BackfillManager::bytesSent(uint32_t bytes) {\n LockHolder lh(lock);\n cb_assert(buffer.bytesRead >= bytes);\n buffer.bytesRead -= bytes;\n\n if (buffer.full) {\n uint32_t bufferSize = buffer.bytesRead;\n bool canFitNext = buffer.maxBytes - bufferSize >= buffer.nextReadSize;\n bool enoughCleared = bufferSize < (buffer.maxBytes * 3 \/ 4);\n if (canFitNext && enoughCleared) {\n buffer.nextReadSize = 0;\n buffer.full = false;\n if (managerTask) {\n managerTask->snooze(0);\n }\n }\n }\n}\n\nbackfill_status_t BackfillManager::backfill() {\n LockHolder lh(lock);\n if (buffer.full) {\n return backfill_snooze;\n }\n\n if (activeBackfills.empty() && snoozingBackfills.empty()) {\n managerTask.reset();\n return backfill_finished;\n }\n\n if (engine->getEpStore()->isMemoryUsageTooHigh()) {\n LOG(EXTENSION_LOG_WARNING, \"DCP backfilling task for connection %s \"\n \"temporarily suspended because the current memory usage is too \"\n \"high\", conn->getName().c_str());\n return backfill_snooze;\n }\n\n while (!snoozingBackfills.empty()) {\n std::pair snoozer = snoozingBackfills.front();\n \/\/ If snoozing task is found to be sleeping for greater than\n \/\/ allowed snoozetime, push into active queue\n if (snoozer.first + sleepTime <= ep_current_time()) {\n DCPBackfill* bfill = snoozer.second;\n activeBackfills.push(bfill);\n snoozingBackfills.pop_front();\n } else {\n break;\n }\n }\n\n if (activeBackfills.empty()) {\n return backfill_snooze;\n }\n\n DCPBackfill* backfill = activeBackfills.front();\n\n lh.unlock();\n backfill_status_t status = backfill->run();\n lh.lock();\n\n if (status == backfill_success && buffer.full) {\n \/\/ Snooze while the buffer is full\n return backfill_snooze;\n }\n\n scanBuffer.bytesRead = 0;\n scanBuffer.itemsRead = 0;\n\n activeBackfills.pop();\n if (status == backfill_success) {\n activeBackfills.push(backfill);\n } else if (status == backfill_finished) {\n lh.unlock();\n delete backfill;\n } else if (status == backfill_snooze) {\n uint16_t vbid = backfill->getVBucketId();\n RCPtr vb = engine->getVBucket(vbid);\n if (vb) {\n snoozingBackfills.push_back(\n std::make_pair(ep_current_time(), backfill));\n shared_ptr >\n cb(new BackfillCallback(backfill->getEndSeqno(),\n vbid, conn));\n vb->addPersistenceNotification(cb);\n } else {\n lh.unlock();\n LOG(EXTENSION_LOG_WARNING, \"Deleting the backfill, as vbucket %d \"\n \"seems to have been deleted!\", vbid);\n backfill->cancel();\n delete backfill;\n }\n } else {\n abort();\n }\n\n return backfill_success;\n}\n\nvoid BackfillManager::wakeUpTask() {\n LockHolder lh(lock);\n if (managerTask) {\n managerTask->snooze(0);\n }\n}\n\nvoid BackfillManager::wakeUpSnoozingBackfills(uint16_t vbid) {\n LockHolder lh(lock);\n std::list >::iterator it;\n for (it = snoozingBackfills.begin(); it != snoozingBackfills.end(); ++it) {\n DCPBackfill *bfill = (*it).second;\n if (vbid == bfill->getVBucketId()) {\n activeBackfills.push(bfill);\n snoozingBackfills.erase(it);\n managerTask->snooze(0);\n return;\n }\n }\n}\n\nbool BackfillManager::addIfLessThanMax(AtomicValue& val,\n uint32_t incr, uint32_t max) {\n do {\n uint32_t oldVal = val.load();\n uint32_t newVal = oldVal + incr;\n\n if (newVal > max) {\n return false;\n }\n\n if (val.compare_exchange_strong(oldVal, newVal)) {\n return true;\n }\n } while (true);\n}\nMB-13070: Check for a dead backfill task when scheduling backfill\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2014 Couchbase, Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"config.h\"\n#include \"ep_engine.h\"\n#include \"connmap.h\"\n#include \"dcp-backfill-manager.h\"\n#include \"dcp-backfill.h\"\n#include \"dcp-producer.h\"\n\nstatic const size_t sleepTime = 1;\n\nclass BackfillManagerTask : public GlobalTask {\npublic:\n BackfillManagerTask(EventuallyPersistentEngine* e, connection_t c,\n const Priority &p, double sleeptime = 0,\n bool shutdown = false)\n : GlobalTask(e, p, sleeptime, shutdown), conn(c) {}\n\n bool run();\n\n std::string getDescription();\n\nprivate:\n connection_t conn;\n};\n\nbool BackfillManagerTask::run() {\n DcpProducer* producer = static_cast(conn.get());\n if (producer->doDisconnect()) {\n return false;\n }\n\n backfill_status_t status = producer->getBackfillManager()->backfill();\n if (status == backfill_finished) {\n return false;\n } else if (status == backfill_snooze) {\n snooze(sleepTime);\n }\n\n if (engine->getEpStats().isShutdown) {\n return false;\n }\n\n return true;\n}\n\nstd::string BackfillManagerTask::getDescription() {\n std::stringstream ss;\n ss << \"Backfilling items for \" << conn->getName();\n return ss.str();\n}\n\nBackfillManager::BackfillManager(EventuallyPersistentEngine* e, connection_t c)\n : engine(e), conn(c), managerTask(NULL) {\n\n Configuration& config = e->getConfiguration();\n\n scanBuffer.bytesRead = 0;\n scanBuffer.itemsRead = 0;\n scanBuffer.maxBytes = config.getDcpScanByteLimit();\n scanBuffer.maxItems = config.getDcpScanItemLimit();\n\n buffer.bytesRead = 0;\n buffer.maxBytes = config.getDcpBackfillByteLimit();\n buffer.nextReadSize = 0;\n buffer.full = false;\n}\n\nBackfillManager::~BackfillManager() {\n LockHolder lh(lock);\n if (managerTask) {\n managerTask->cancel();\n }\n\n while (!activeBackfills.empty()) {\n DCPBackfill* backfill = activeBackfills.front();\n activeBackfills.pop();\n backfill->cancel();\n delete backfill;\n }\n\n while (!snoozingBackfills.empty()) {\n DCPBackfill* backfill = (snoozingBackfills.front()).second;\n snoozingBackfills.pop_front();\n backfill->cancel();\n delete backfill;\n }\n}\n\nvoid BackfillManager::schedule(stream_t stream, uint64_t start, uint64_t end) {\n LockHolder lh(lock);\n activeBackfills.push(new DCPBackfill(engine, stream, start, end));\n\n if (managerTask && !managerTask->isdead()) {\n managerTask->snooze(0);\n return;\n }\n\n managerTask.reset(new BackfillManagerTask(engine, conn,\n Priority::BackfillTaskPriority));\n ExecutorPool::get()->schedule(managerTask, NONIO_TASK_IDX);\n}\n\nbool BackfillManager::bytesRead(uint32_t bytes) {\n LockHolder lh(lock);\n if (scanBuffer.itemsRead >= scanBuffer.maxItems) {\n return false;\n }\n\n \/\/ Always allow an item to be backfilled if the scan buffer is empty,\n \/\/ otherwise check to see if there is room for the item.\n if (scanBuffer.bytesRead + bytes <= scanBuffer.maxBytes ||\n scanBuffer.bytesRead == 0) {\n scanBuffer.bytesRead += bytes;\n }\n\n if (buffer.bytesRead == 0 || buffer.bytesRead + bytes <= buffer.maxBytes) {\n buffer.bytesRead += bytes;\n } else {\n scanBuffer.bytesRead -= bytes;\n buffer.full = true;\n buffer.nextReadSize = bytes;\n return false;\n }\n\n scanBuffer.itemsRead++;\n\n return true;\n}\n\nvoid BackfillManager::bytesSent(uint32_t bytes) {\n LockHolder lh(lock);\n cb_assert(buffer.bytesRead >= bytes);\n buffer.bytesRead -= bytes;\n\n if (buffer.full) {\n uint32_t bufferSize = buffer.bytesRead;\n bool canFitNext = buffer.maxBytes - bufferSize >= buffer.nextReadSize;\n bool enoughCleared = bufferSize < (buffer.maxBytes * 3 \/ 4);\n if (canFitNext && enoughCleared) {\n buffer.nextReadSize = 0;\n buffer.full = false;\n if (managerTask) {\n managerTask->snooze(0);\n }\n }\n }\n}\n\nbackfill_status_t BackfillManager::backfill() {\n LockHolder lh(lock);\n if (buffer.full) {\n return backfill_snooze;\n }\n\n if (activeBackfills.empty() && snoozingBackfills.empty()) {\n managerTask.reset();\n return backfill_finished;\n }\n\n if (engine->getEpStore()->isMemoryUsageTooHigh()) {\n LOG(EXTENSION_LOG_WARNING, \"DCP backfilling task for connection %s \"\n \"temporarily suspended because the current memory usage is too \"\n \"high\", conn->getName().c_str());\n return backfill_snooze;\n }\n\n while (!snoozingBackfills.empty()) {\n std::pair snoozer = snoozingBackfills.front();\n \/\/ If snoozing task is found to be sleeping for greater than\n \/\/ allowed snoozetime, push into active queue\n if (snoozer.first + sleepTime <= ep_current_time()) {\n DCPBackfill* bfill = snoozer.second;\n activeBackfills.push(bfill);\n snoozingBackfills.pop_front();\n } else {\n break;\n }\n }\n\n if (activeBackfills.empty()) {\n return backfill_snooze;\n }\n\n DCPBackfill* backfill = activeBackfills.front();\n\n lh.unlock();\n backfill_status_t status = backfill->run();\n lh.lock();\n\n if (status == backfill_success && buffer.full) {\n \/\/ Snooze while the buffer is full\n return backfill_snooze;\n }\n\n scanBuffer.bytesRead = 0;\n scanBuffer.itemsRead = 0;\n\n activeBackfills.pop();\n if (status == backfill_success) {\n activeBackfills.push(backfill);\n } else if (status == backfill_finished) {\n lh.unlock();\n delete backfill;\n } else if (status == backfill_snooze) {\n uint16_t vbid = backfill->getVBucketId();\n RCPtr vb = engine->getVBucket(vbid);\n if (vb) {\n snoozingBackfills.push_back(\n std::make_pair(ep_current_time(), backfill));\n shared_ptr >\n cb(new BackfillCallback(backfill->getEndSeqno(),\n vbid, conn));\n vb->addPersistenceNotification(cb);\n } else {\n lh.unlock();\n LOG(EXTENSION_LOG_WARNING, \"Deleting the backfill, as vbucket %d \"\n \"seems to have been deleted!\", vbid);\n backfill->cancel();\n delete backfill;\n }\n } else {\n abort();\n }\n\n return backfill_success;\n}\n\nvoid BackfillManager::wakeUpTask() {\n LockHolder lh(lock);\n if (managerTask) {\n managerTask->snooze(0);\n }\n}\n\nvoid BackfillManager::wakeUpSnoozingBackfills(uint16_t vbid) {\n LockHolder lh(lock);\n std::list >::iterator it;\n for (it = snoozingBackfills.begin(); it != snoozingBackfills.end(); ++it) {\n DCPBackfill *bfill = (*it).second;\n if (vbid == bfill->getVBucketId()) {\n activeBackfills.push(bfill);\n snoozingBackfills.erase(it);\n managerTask->snooze(0);\n return;\n }\n }\n}\n\nbool BackfillManager::addIfLessThanMax(AtomicValue& val,\n uint32_t incr, uint32_t max) {\n do {\n uint32_t oldVal = val.load();\n uint32_t newVal = oldVal + incr;\n\n if (newVal > max) {\n return false;\n }\n\n if (val.compare_exchange_strong(oldVal, newVal)) {\n return true;\n }\n } while (true);\n}\n<|endoftext|>"} {"text":"\/**\n * This file is part of the \"libfnord\" project\n * Copyright (c) 2015 Paul Asmuth\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * .\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace fnord;\n\nnamespace dproc {\n\nLocalScheduler::LocalScheduler(\n const String& tempdir \/* = \"\/tmp\" *\/,\n size_t max_threads \/* = 8 *\/,\n size_t max_requests \/* = 32 *\/) :\n tempdir_(tempdir),\n tpool_(max_threads),\n req_tpool_(max_requests) {}\n\nvoid LocalScheduler::start() {\n req_tpool_.start();\n tpool_.start();\n}\n\nvoid LocalScheduler::stop() {\n req_tpool_.stop();\n tpool_.stop();\n}\n\nRefPtr LocalScheduler::run(\n RefPtr app,\n const TaskSpec& task) {\n RefPtr result(new TaskResultFuture());\n\n try {\n auto instance = mkRef(\n new LocalTaskRef(\n app,\n task.task_name(),\n Buffer(task.params().data(), task.params().size())));\n\n req_tpool_.run([this, app, result, instance] () {\n try {\n LocalTaskPipeline pipeline;\n pipeline.tasks.push_back(instance);\n runPipeline(app.get(), &pipeline, result);\n\n if (instance->failed) {\n RAISE(kRuntimeError, \"task failed\");\n }\n\n result->returnResult(instance->task);\n } catch (const StandardException& e) {\n fnord::logError(\"dproc.scheduler\", e, \"task failed\");\n result->returnError(e);\n }\n });\n } catch (const StandardException& e) {\n fnord::logError(\"dproc.scheduler\", e, \"task failed\");\n result->returnError(e);\n }\n\n return result;\n}\n\nvoid LocalScheduler::runPipeline(\n Application* app,\n LocalTaskPipeline* pipeline,\n RefPtr result) {\n fnord::logDebug(\n \"fnord.dproc\",\n \"Starting local pipeline id=$0 tasks=$1\",\n (void*) pipeline,\n pipeline->tasks.size());\n\n std::unique_lock lk(pipeline->mutex);\n result->updateStatus([&pipeline] (TaskStatus* status) {\n status->num_subtasks_total = pipeline->tasks.size();\n });\n\n while (pipeline->tasks.size() > 0) {\n bool waiting = true;\n size_t num_waiting = 0;\n size_t num_running = 0;\n size_t num_completed = 0;\n\n for (auto& taskref : pipeline->tasks) {\n\n if (taskref->finished) {\n ++num_completed;\n continue;\n }\n\n if (taskref->running) {\n ++num_running;\n continue;\n }\n\n if (!taskref->expanded) {\n taskref->expanded = true;\n\n auto rdd = dynamic_cast(taskref->task.get());\n if (rdd != nullptr) {\n auto cache_key = rdd->cacheKeySHA1();\n if (!cache_key.isEmpty()) {\n taskref->cache_filename = FileUtil::joinPaths(\n tempdir_,\n StringUtil::format(\"$0.rdd\", cache_key.get()));\n }\n\n if (!taskref->cache_filename.empty() &&\n FileUtil::exists(taskref->cache_filename)) {\n fnord::logDebug(\n \"fnord.dproc\",\n \"Read RDD from cache: $0, key=$1\",\n taskref->debug_name,\n cache_key.get());\n\n taskref->readCache();\n\n result->updateStatus([&pipeline] (TaskStatus* status) {\n ++status->num_subtasks_completed;\n });\n\n taskref->finished = true;\n waiting = false;\n break;\n }\n }\n\n auto parent_task = taskref;\n size_t numdeps = 0;\n for (const auto& dep : taskref->task->dependencies()) {\n RefPtr depref(new LocalTaskRef(app, dep.task_name, dep.params));\n parent_task->dependencies.emplace_back(depref);\n pipeline->tasks.emplace_back(depref);\n ++numdeps;\n }\n\n if (numdeps > 0) {\n result->updateStatus([numdeps] (TaskStatus* status) {\n status->num_subtasks_total += numdeps;\n });\n }\n\n waiting = false;\n break;\n }\n\n bool deps_finished = true;\n for (const auto& dep : taskref->dependencies) {\n if (dep->failed) {\n taskref->failed = true;\n taskref->finished = true;\n waiting = false;\n }\n\n if (!dep->finished) {\n deps_finished = false;\n }\n }\n\n if (!taskref->finished) {\n if (!deps_finished) {\n ++num_waiting;\n continue;\n }\n\n fnord::logDebug(\n \"fnord.dproc\",\n \"Computing RDD: $0\",\n taskref->debug_name);\n\n taskref->running = true;\n tpool_.run(std::bind(\n &LocalScheduler::runTask,\n this,\n pipeline,\n taskref,\n result));\n\n waiting = false;\n }\n }\n\n fnord::logDebug(\n \"fnord.dproc\",\n \"Running local pipeline id=$0: $1\",\n (void*) pipeline,\n result->status().toString());\n\n if (waiting) {\n pipeline->wakeup.wait(lk);\n }\n\n while (pipeline->tasks.size() > 0 && pipeline->tasks.back()->finished) {\n pipeline->tasks.pop_back();\n }\n }\n\n fnord::logDebug(\n \"fnord.dproc\",\n \"Completed local pipeline id=$0\",\n (void*) pipeline);\n}\n\nvoid LocalScheduler::runTask(\n LocalTaskPipeline* pipeline,\n RefPtr task,\n RefPtr result) {\n bool from_cache = false;\n\n auto rdd = dynamic_cast(task->task.get());\n if (rdd != nullptr &&\n !task->cache_filename.empty() &&\n FileUtil::exists(task->cache_filename)) {\n fnord::logDebug(\n \"fnord.dproc\",\n \"Read RDD from cache: $0, key=$1\",\n task->debug_name,\n rdd->cacheKeySHA1().get());\n\n task->readCache();\n\n from_cache = true;\n }\n\n if (!from_cache) {\n try {\n task->task->compute(task.get());\n\n if (rdd != nullptr && !task->cache_filename.empty()) {\n auto cache_file = task->cache_filename;\n auto cache = rdd->encode();\n\n auto f = File::openFile(\n cache_file + \"~\",\n File::O_CREATEOROPEN | File::O_WRITE | File::O_TRUNCATE);\n\n f.write(cache->data(), cache->size());\n\n FileUtil::mv(cache_file + \"~\", cache_file);\n }\n } catch (const std::exception& e) {\n task->failed = true;\n fnord::logError(\"fnord.dproc\", e, \"error\");\n }\n }\n\n result->updateStatus([&pipeline] (TaskStatus* status) {\n ++status->num_subtasks_completed;\n });\n\n std::unique_lock lk(pipeline->mutex);\n task->finished = true;\n lk.unlock();\n pipeline->wakeup.notify_all();\n}\n\nLocalScheduler::LocalTaskRef::LocalTaskRef(\n RefPtr app,\n const String& task_name,\n const Buffer& params) :\n task(app->getTaskInstance(task_name, params)),\n debug_name(StringUtil::format(\"$0#$1\", app->name(), task_name)),\n running(false),\n expanded(false),\n finished(false),\n failed(false) {}\n\nvoid LocalScheduler::LocalTaskRef::readCache() {\n auto rdd = dynamic_cast(task.get());\n if (rdd == nullptr) {\n RAISE(kRuntimeError, \"can't cache actions\");\n }\n\n rdd->decode(\n new io::MmappedFile(\n File::openFile(\n cache_filename,\n File::O_READ)));\n}\n\nRefPtr LocalScheduler::LocalTaskRef::getDependency(size_t index) {\n if (index >= dependencies.size()) {\n RAISEF(kIndexError, \"invalid dependecy index: $0\", index);\n }\n\n const auto& dep = dependencies[index];\n return dynamic_cast(dep->task.get());\n}\n\nsize_t LocalScheduler::LocalTaskRef::numDependencies() const {\n return dependencies.size();\n}\n\n} \/\/ namespace dproc\ndproc log namespace\/**\n * This file is part of the \"libfnord\" project\n * Copyright (c) 2015 Paul Asmuth\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * .\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace fnord;\n\nnamespace dproc {\n\nLocalScheduler::LocalScheduler(\n const String& tempdir \/* = \"\/tmp\" *\/,\n size_t max_threads \/* = 8 *\/,\n size_t max_requests \/* = 32 *\/) :\n tempdir_(tempdir),\n tpool_(max_threads),\n req_tpool_(max_requests) {}\n\nvoid LocalScheduler::start() {\n req_tpool_.start();\n tpool_.start();\n}\n\nvoid LocalScheduler::stop() {\n req_tpool_.stop();\n tpool_.stop();\n}\n\nRefPtr LocalScheduler::run(\n RefPtr app,\n const TaskSpec& task) {\n RefPtr result(new TaskResultFuture());\n\n try {\n auto instance = mkRef(\n new LocalTaskRef(\n app,\n task.task_name(),\n Buffer(task.params().data(), task.params().size())));\n\n req_tpool_.run([this, app, result, instance] () {\n try {\n LocalTaskPipeline pipeline;\n pipeline.tasks.push_back(instance);\n runPipeline(app.get(), &pipeline, result);\n\n if (instance->failed) {\n RAISE(kRuntimeError, \"task failed\");\n }\n\n result->returnResult(instance->task);\n } catch (const StandardException& e) {\n fnord::logError(\"dproc.scheduler\", e, \"task failed\");\n result->returnError(e);\n }\n });\n } catch (const StandardException& e) {\n fnord::logError(\"dproc.scheduler\", e, \"task failed\");\n result->returnError(e);\n }\n\n return result;\n}\n\nvoid LocalScheduler::runPipeline(\n Application* app,\n LocalTaskPipeline* pipeline,\n RefPtr result) {\n fnord::logDebug(\n \"dproc\",\n \"Starting local pipeline id=$0 tasks=$1\",\n (void*) pipeline,\n pipeline->tasks.size());\n\n std::unique_lock lk(pipeline->mutex);\n result->updateStatus([&pipeline] (TaskStatus* status) {\n status->num_subtasks_total = pipeline->tasks.size();\n });\n\n while (pipeline->tasks.size() > 0) {\n bool waiting = true;\n size_t num_waiting = 0;\n size_t num_running = 0;\n size_t num_completed = 0;\n\n for (auto& taskref : pipeline->tasks) {\n\n if (taskref->finished) {\n ++num_completed;\n continue;\n }\n\n if (taskref->running) {\n ++num_running;\n continue;\n }\n\n if (!taskref->expanded) {\n taskref->expanded = true;\n\n auto rdd = dynamic_cast(taskref->task.get());\n if (rdd != nullptr) {\n auto cache_key = rdd->cacheKeySHA1();\n if (!cache_key.isEmpty()) {\n taskref->cache_filename = FileUtil::joinPaths(\n tempdir_,\n StringUtil::format(\"$0.rdd\", cache_key.get()));\n }\n\n if (!taskref->cache_filename.empty() &&\n FileUtil::exists(taskref->cache_filename)) {\n fnord::logDebug(\n \"dproc\",\n \"Read RDD from cache: $0, key=$1\",\n taskref->debug_name,\n cache_key.get());\n\n taskref->readCache();\n\n result->updateStatus([&pipeline] (TaskStatus* status) {\n ++status->num_subtasks_completed;\n });\n\n taskref->finished = true;\n waiting = false;\n break;\n }\n }\n\n auto parent_task = taskref;\n size_t numdeps = 0;\n for (const auto& dep : taskref->task->dependencies()) {\n RefPtr depref(new LocalTaskRef(app, dep.task_name, dep.params));\n parent_task->dependencies.emplace_back(depref);\n pipeline->tasks.emplace_back(depref);\n ++numdeps;\n }\n\n if (numdeps > 0) {\n result->updateStatus([numdeps] (TaskStatus* status) {\n status->num_subtasks_total += numdeps;\n });\n }\n\n waiting = false;\n break;\n }\n\n bool deps_finished = true;\n for (const auto& dep : taskref->dependencies) {\n if (dep->failed) {\n taskref->failed = true;\n taskref->finished = true;\n waiting = false;\n }\n\n if (!dep->finished) {\n deps_finished = false;\n }\n }\n\n if (!taskref->finished) {\n if (!deps_finished) {\n ++num_waiting;\n continue;\n }\n\n fnord::logDebug(\n \"dproc\",\n \"Computing RDD: $0\",\n taskref->debug_name);\n\n taskref->running = true;\n tpool_.run(std::bind(\n &LocalScheduler::runTask,\n this,\n pipeline,\n taskref,\n result));\n\n waiting = false;\n }\n }\n\n fnord::logDebug(\n \"dproc\",\n \"Running local pipeline id=$0: $1\",\n (void*) pipeline,\n result->status().toString());\n\n if (waiting) {\n pipeline->wakeup.wait(lk);\n }\n\n while (pipeline->tasks.size() > 0 && pipeline->tasks.back()->finished) {\n pipeline->tasks.pop_back();\n }\n }\n\n fnord::logDebug(\n \"dproc\",\n \"Completed local pipeline id=$0\",\n (void*) pipeline);\n}\n\nvoid LocalScheduler::runTask(\n LocalTaskPipeline* pipeline,\n RefPtr task,\n RefPtr result) {\n bool from_cache = false;\n\n auto rdd = dynamic_cast(task->task.get());\n if (rdd != nullptr &&\n !task->cache_filename.empty() &&\n FileUtil::exists(task->cache_filename)) {\n fnord::logDebug(\n \"dproc\",\n \"Read RDD from cache: $0, key=$1\",\n task->debug_name,\n rdd->cacheKeySHA1().get());\n\n task->readCache();\n\n from_cache = true;\n }\n\n if (!from_cache) {\n try {\n task->task->compute(task.get());\n\n if (rdd != nullptr && !task->cache_filename.empty()) {\n auto cache_file = task->cache_filename;\n auto cache = rdd->encode();\n\n auto f = File::openFile(\n cache_file + \"~\",\n File::O_CREATEOROPEN | File::O_WRITE | File::O_TRUNCATE);\n\n f.write(cache->data(), cache->size());\n\n FileUtil::mv(cache_file + \"~\", cache_file);\n }\n } catch (const std::exception& e) {\n task->failed = true;\n fnord::logError(\"dproc\", e, \"error\");\n }\n }\n\n result->updateStatus([&pipeline] (TaskStatus* status) {\n ++status->num_subtasks_completed;\n });\n\n std::unique_lock lk(pipeline->mutex);\n task->finished = true;\n lk.unlock();\n pipeline->wakeup.notify_all();\n}\n\nLocalScheduler::LocalTaskRef::LocalTaskRef(\n RefPtr app,\n const String& task_name,\n const Buffer& params) :\n task(app->getTaskInstance(task_name, params)),\n debug_name(StringUtil::format(\"$0#$1\", app->name(), task_name)),\n running(false),\n expanded(false),\n finished(false),\n failed(false) {}\n\nvoid LocalScheduler::LocalTaskRef::readCache() {\n auto rdd = dynamic_cast(task.get());\n if (rdd == nullptr) {\n RAISE(kRuntimeError, \"can't cache actions\");\n }\n\n rdd->decode(\n new io::MmappedFile(\n File::openFile(\n cache_filename,\n File::O_READ)));\n}\n\nRefPtr LocalScheduler::LocalTaskRef::getDependency(size_t index) {\n if (index >= dependencies.size()) {\n RAISEF(kIndexError, \"invalid dependecy index: $0\", index);\n }\n\n const auto& dep = dependencies[index];\n return dynamic_cast(dep->task.get());\n}\n\nsize_t LocalScheduler::LocalTaskRef::numDependencies() const {\n return dependencies.size();\n}\n\n} \/\/ namespace dproc\n<|endoftext|>"} {"text":"#include \"QtWebSockets\/QWebSocketServer\"\n#include \"QtWebSockets\/QWebSocket\"\n#include \n#include \"WebSocketServer.h\"\n#include \"Player.h\"\n\nWebSocketServer::WebSocketServer(quint16 port, QObject *parent) :\n QObject(parent),\n m_pWebSocketServer(Q_NULLPTR),\n m_clients()\n{\n m_pWebSocketServer = new QWebSocketServer(QStringLiteral(\"Chat Server\"),\n QWebSocketServer::NonSecureMode,\n this);\n if (m_pWebSocketServer->listen(QHostAddress::Any, port))\n {\n qDebug() << \"WebSocket server listening on port \" << port;\n connect(m_pWebSocketServer, &QWebSocketServer::newConnection,\n this, &WebSocketServer::onNewConnection);\n connect(Player::instance(), &Player::statusChanged,\n this, &WebSocketServer::broadcastStatus);\n connect(Player::instance(), &Player::playlistChanged,\n this, &WebSocketServer::broadcastPlaylist);\n }\n}\n\nWebSocketServer::~WebSocketServer()\n{\n m_pWebSocketServer->close();\n qDeleteAll(m_clients.begin(), m_clients.end());\n}\n\nvoid WebSocketServer::onNewConnection()\n{\n QWebSocket *socket = m_pWebSocketServer->nextPendingConnection();\n\n connect(socket, &QWebSocket::disconnected, this, &WebSocketServer::socketDisconnected);\n\n JsonApi *api = new JsonApi(socket);\n connect(socket, &QWebSocket::textMessageReceived, api, &JsonApi::processMessage);\n\n m_clients[socket] = api;\n}\n\nvoid WebSocketServer::broadcastStatus(EMSPlayerStatus newStatus)\n{\n foreach( JsonApi *api, m_clients.values() )\n {\n if (api)\n {\n api->sendStatus(newStatus);\n }\n }\n}\n\nvoid WebSocketServer::broadcastPlaylist(EMSPlaylist newPlaylist)\n{\n foreach( JsonApi *api, m_clients.values() )\n {\n if (api)\n {\n api->sendPlaylist(newPlaylist);\n }\n }\n}\n\nvoid WebSocketServer::sendAuthRequestToLocalUI(const EMSClient client)\n{\n QMapIterator client_it(m_clients);\n qDebug() << \"WebSocketServer: nb clients = \" << m_clients.size();\n\n \/\/ Search the websocket for the local UI,\n while (client_it.hasNext()) {\n client_it.next();\n if (client_it.key()->peerAddress() == QHostAddress::LocalHost) {\n \/\/ and send the authentication request message\n client_it.value()->sendAuthRequest(client);\n return;\n }\n }\n}\n\nvoid WebSocketServer::processMessage(QString message)\n{\n QWebSocket *client = qobject_cast(sender());\n m_clients[client]->processMessage(message);\n}\n\nvoid WebSocketServer::socketDisconnected()\n{\n QWebSocket *client = qobject_cast(sender());\n if (client)\n {\n delete m_clients[client];\n m_clients.remove(client);\n }\n}\nAccept client: add log for debug#include \"QtWebSockets\/QWebSocketServer\"\n#include \"QtWebSockets\/QWebSocket\"\n#include \n#include \"WebSocketServer.h\"\n#include \"Player.h\"\n\nWebSocketServer::WebSocketServer(quint16 port, QObject *parent) :\n QObject(parent),\n m_pWebSocketServer(Q_NULLPTR),\n m_clients()\n{\n m_pWebSocketServer = new QWebSocketServer(QStringLiteral(\"Chat Server\"),\n QWebSocketServer::NonSecureMode,\n this);\n if (m_pWebSocketServer->listen(QHostAddress::Any, port))\n {\n qDebug() << \"WebSocket server listening on port \" << port;\n connect(m_pWebSocketServer, &QWebSocketServer::newConnection,\n this, &WebSocketServer::onNewConnection);\n connect(Player::instance(), &Player::statusChanged,\n this, &WebSocketServer::broadcastStatus);\n connect(Player::instance(), &Player::playlistChanged,\n this, &WebSocketServer::broadcastPlaylist);\n }\n}\n\nWebSocketServer::~WebSocketServer()\n{\n m_pWebSocketServer->close();\n qDeleteAll(m_clients.begin(), m_clients.end());\n}\n\nvoid WebSocketServer::onNewConnection()\n{\n QWebSocket *socket = m_pWebSocketServer->nextPendingConnection();\n\n connect(socket, &QWebSocket::disconnected, this, &WebSocketServer::socketDisconnected);\n\n JsonApi *api = new JsonApi(socket);\n connect(socket, &QWebSocket::textMessageReceived, api, &JsonApi::processMessage);\n\n m_clients[socket] = api;\n}\n\nvoid WebSocketServer::broadcastStatus(EMSPlayerStatus newStatus)\n{\n foreach( JsonApi *api, m_clients.values() )\n {\n if (api)\n {\n api->sendStatus(newStatus);\n }\n }\n}\n\nvoid WebSocketServer::broadcastPlaylist(EMSPlaylist newPlaylist)\n{\n foreach( JsonApi *api, m_clients.values() )\n {\n if (api)\n {\n api->sendPlaylist(newPlaylist);\n }\n }\n}\n\nvoid WebSocketServer::sendAuthRequestToLocalUI(const EMSClient client)\n{\n QMapIterator client_it(m_clients);\n qDebug() << \"WebSocketServer: sent the 'authentication' request for \" << client.uuid;\n qDebug() << \"WebSocketServer: nb connected clients = \" << m_clients.size();\n\n \/\/ Search the websocket for the local UI,\n while (client_it.hasNext()) {\n client_it.next();\n if (client_it.key()->peerAddress() == QHostAddress::LocalHost) {\n \/\/ and send the authentication request message\n client_it.value()->sendAuthRequest(client);\n return;\n }\n }\n}\n\nvoid WebSocketServer::processMessage(QString message)\n{\n QWebSocket *client = qobject_cast(sender());\n m_clients[client]->processMessage(message);\n}\n\nvoid WebSocketServer::socketDisconnected()\n{\n QWebSocket *client = qobject_cast(sender());\n if (client)\n {\n delete m_clients[client];\n m_clients.remove(client);\n }\n}\n<|endoftext|>"} {"text":"\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Library General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * e133-receiver.cpp\n * Copyright (C) 2011 Simon Newton\n *\n * This creates a E1.33 receiver with one (emulated) RDM responder. The node is\n * registered in slp and the RDM responder responds to E1.33 commands.\n *\/\n\n#if HAVE_CONFIG_H\n# include \n#endif\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#ifdef USE_SPI\n#include \"plugins\/spi\/SPIBackend.h\"\nusing ola::plugin::spi::SPIBackend;\nDEFINE_string(spi_device, \"\", \"Path to the SPI device to use.\");\n#endif\n\n#include \"plugins\/e131\/e131\/E131Node.h\"\n#include \"plugins\/usbpro\/BaseUsbProWidget.h\"\n#include \"plugins\/usbpro\/DmxTriWidget.h\"\n#include \"tools\/e133\/SimpleE133Node.h\"\n\nusing ola::DmxBuffer;\nusing ola::acn::CID;\nusing ola::network::IPV4Address;\nusing ola::rdm::UID;\nusing std::auto_ptr;\nusing std::string;\nusing std::vector;\nusing ola::plugin::usbpro::DmxTriWidget;\n\nDEFINE_bool(dummy, true, \"Include a dummy responder endpoint\");\nDEFINE_bool(e131, true, \"Include E1.31 support\");\nDEFINE_string(listen_ip, \"\", \"The IP address to listen on.\");\nDEFINE_string(uid, \"7a70:00000001\", \"The UID of the responder.\");\nDEFINE_s_uint16(lifetime, t, 300, \"The value to use for the service lifetime\");\nDEFINE_s_uint32(universe, u, 1, \"The E1.31 universe to listen on.\");\nDEFINE_string(tri_device, \"\", \"Path to the RDM-TRI device to use.\");\n\nSimpleE133Node *simple_node;\n\n\/*\n * Terminate cleanly on interrupt.\n *\/\nstatic void InteruptSignal(int signo) {\n if (simple_node)\n simple_node->Stop();\n (void) signo;\n}\n\nvoid HandleDMX(DmxBuffer *buffer, DmxTriWidget *widget) {\n widget->SendDMX(*buffer);\n}\n\n\n#ifdef USE_SPI\nvoid HandleDMX(DmxBuffer *buffer, SPIBackend *backend) {\n backend->WriteDMX(*buffer, 0);\n}\n#endif\n\n\n\/*\n * Startup a node\n *\/\nint main(int argc, char *argv[]) {\n ola::SetHelpString(\n \"[options]\",\n \"Run a very simple E1.33 Responder.\");\n ola::ParseFlags(&argc, argv);\n ola::InitLoggingFromFlags();\n\n auto_ptr uid(UID::FromString(FLAGS_uid));\n if (!uid.get()) {\n OLA_WARN << \"Invalid UID: \" << FLAGS_uid;\n ola::DisplayUsage();\n exit(EX_USAGE);\n }\n\n CID cid = CID::Generate();\n\n \/\/ Find a network interface to use\n ola::network::Interface interface;\n\n {\n auto_ptr picker(\n ola::network::InterfacePicker::NewPicker());\n if (!picker->ChooseInterface(&interface, FLAGS_listen_ip)) {\n OLA_INFO << \"Failed to find an interface\";\n exit(EX_UNAVAILABLE);\n }\n }\n\n \/\/ Setup the Node.\n SimpleE133Node::Options opts(cid, interface.ip_address, *uid, FLAGS_lifetime);\n SimpleE133Node node(opts);\n\n \/\/ Optionally attach some other endpoints.\n vector endpoints;\n auto_ptr dummy_responder;\n auto_ptr\n discoverable_dummy_responder;\n auto_ptr tri_widget;\n\n ola::rdm::UIDAllocator uid_allocator(*uid);\n \/\/ The first uid is used for the management endpoint so we burn a UID here.\n {\n auto_ptr dummy_uid(uid_allocator.AllocateNext());\n }\n\n \/\/ Setup E1.31 if required.\n auto_ptr e131_node;\n if (FLAGS_e131) {\n e131_node.reset(new ola::plugin::e131::E131Node(FLAGS_listen_ip, cid));\n if (!e131_node->Start()) {\n OLA_WARN << \"Failed to start E1.31 node\";\n exit(EX_UNAVAILABLE);\n }\n OLA_INFO << \"Started E1.31 node!\";\n node.SelectServer()->AddReadDescriptor(e131_node->GetSocket());\n }\n\n if (FLAGS_dummy) {\n auto_ptr dummy_uid(uid_allocator.AllocateNext());\n if (!dummy_uid.get()) {\n OLA_WARN << \"Failed to allocate a UID for the DummyResponder.\";\n exit(EX_USAGE);\n }\n\n dummy_responder.reset(new ola::plugin::dummy::DummyResponder(*dummy_uid));\n discoverable_dummy_responder.reset(\n new ola::rdm::DiscoverableRDMControllerAdaptor(\n *dummy_uid, dummy_responder.get()));\n endpoints.push_back(new E133Endpoint(discoverable_dummy_responder.get(),\n E133Endpoint::EndpointProperties()));\n }\n\n \/\/ uber hack for now.\n \/\/ TODO(simon): fix this\n DmxBuffer tri_buffer;\n uint8_t unused_priority;\n if (!FLAGS_tri_device.str().empty()) {\n ola::io::ConnectedDescriptor *descriptor =\n ola::plugin::usbpro::BaseUsbProWidget::OpenDevice(FLAGS_tri_device);\n if (!descriptor) {\n OLA_WARN << \"Failed to open \" << FLAGS_tri_device;\n exit(EX_USAGE);\n }\n tri_widget.reset(new DmxTriWidget(node.SelectServer(), descriptor));\n node.SelectServer()->AddReadDescriptor(descriptor);\n E133Endpoint::EndpointProperties properties;\n properties.is_physical = true;\n endpoints.push_back(\n new E133Endpoint(tri_widget.get(), properties));\n\n if (e131_node.get()) {\n \/\/ Danger!\n e131_node->SetHandler(\n 1, &tri_buffer, &unused_priority,\n NewCallback(&HandleDMX, &tri_buffer, tri_widget.get()));\n }\n }\n\n \/\/ uber hack for now.\n \/\/ TODO(simon): fix this\n#ifdef USE_SPI\n auto_ptr spi_backend;\n DmxBuffer spi_buffer;\n\n if (!FLAGS_spi_device.str().empty()) {\n auto_ptr spi_uid(uid_allocator.AllocateNext());\n if (!spi_uid.get()) {\n OLA_WARN << \"Failed to allocate a UID for the SPI device.\";\n exit(EX_USAGE);\n }\n\n spi_backend.reset(\n new SPIBackend(FLAGS_spi_device, *spi_uid, SPIBackend::Options()));\n E133Endpoint::EndpointProperties properties;\n properties.is_physical = true;\n endpoints.push_back(new E133Endpoint(spi_backend.get(), properties));\n\n if (e131_node.get()) {\n \/\/ Danger!\n e131_node->SetHandler(\n 1, &spi_buffer, &unused_priority,\n NewCallback(&HandleDMX, &spi_buffer, spi_backend.get()));\n }\n }\n#endif\n\n for (unsigned int i = 0; i < endpoints.size(); i++) {\n node.AddEndpoint(i + 1, endpoints[i]);\n }\n simple_node = &node;\n\n if (!node.Init())\n exit(EX_UNAVAILABLE);\n\n \/\/ signal handler\n if (!ola::InstallSignal(SIGINT, &InteruptSignal))\n return false;\n\n node.Run();\n if (e131_node.get()) {\n node.SelectServer()->RemoveReadDescriptor(e131_node->GetSocket());\n }\n for (unsigned int i = 0; i < endpoints.size(); i++) {\n node.RemoveEndpoint(i + 1);\n }\n ola::STLDeleteElements(&endpoints);\n}\n* make the function names unique\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Library General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * e133-receiver.cpp\n * Copyright (C) 2011 Simon Newton\n *\n * This creates a E1.33 receiver with one (emulated) RDM responder. The node is\n * registered in slp and the RDM responder responds to E1.33 commands.\n *\/\n\n#if HAVE_CONFIG_H\n# include \n#endif\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#ifdef USE_SPI\n#include \"plugins\/spi\/SPIBackend.h\"\nusing ola::plugin::spi::SPIBackend;\nDEFINE_string(spi_device, \"\", \"Path to the SPI device to use.\");\n#endif\n\n#include \"plugins\/e131\/e131\/E131Node.h\"\n#include \"plugins\/usbpro\/BaseUsbProWidget.h\"\n#include \"plugins\/usbpro\/DmxTriWidget.h\"\n#include \"tools\/e133\/SimpleE133Node.h\"\n\nusing ola::DmxBuffer;\nusing ola::acn::CID;\nusing ola::network::IPV4Address;\nusing ola::rdm::UID;\nusing std::auto_ptr;\nusing std::string;\nusing std::vector;\nusing ola::plugin::usbpro::DmxTriWidget;\n\nDEFINE_bool(dummy, true, \"Include a dummy responder endpoint\");\nDEFINE_bool(e131, true, \"Include E1.31 support\");\nDEFINE_string(listen_ip, \"\", \"The IP address to listen on.\");\nDEFINE_string(uid, \"7a70:00000001\", \"The UID of the responder.\");\nDEFINE_s_uint16(lifetime, t, 300, \"The value to use for the service lifetime\");\nDEFINE_s_uint32(universe, u, 1, \"The E1.31 universe to listen on.\");\nDEFINE_string(tri_device, \"\", \"Path to the RDM-TRI device to use.\");\n\nSimpleE133Node *simple_node;\n\n\/*\n * Terminate cleanly on interrupt.\n *\/\nstatic void InteruptSignal(int signo) {\n if (simple_node)\n simple_node->Stop();\n (void) signo;\n}\n\nvoid HandleTriDMX(DmxBuffer *buffer, DmxTriWidget *widget) {\n widget->SendDMX(*buffer);\n}\n\n\n#ifdef USE_SPI\nvoid HandleSpiDMX(DmxBuffer *buffer, SPIBackend *backend) {\n backend->WriteDMX(*buffer, 0);\n}\n#endif\n\n\n\/*\n * Startup a node\n *\/\nint main(int argc, char *argv[]) {\n ola::SetHelpString(\n \"[options]\",\n \"Run a very simple E1.33 Responder.\");\n ola::ParseFlags(&argc, argv);\n ola::InitLoggingFromFlags();\n\n auto_ptr uid(UID::FromString(FLAGS_uid));\n if (!uid.get()) {\n OLA_WARN << \"Invalid UID: \" << FLAGS_uid;\n ola::DisplayUsage();\n exit(EX_USAGE);\n }\n\n CID cid = CID::Generate();\n\n \/\/ Find a network interface to use\n ola::network::Interface interface;\n\n {\n auto_ptr picker(\n ola::network::InterfacePicker::NewPicker());\n if (!picker->ChooseInterface(&interface, FLAGS_listen_ip)) {\n OLA_INFO << \"Failed to find an interface\";\n exit(EX_UNAVAILABLE);\n }\n }\n\n \/\/ Setup the Node.\n SimpleE133Node::Options opts(cid, interface.ip_address, *uid, FLAGS_lifetime);\n SimpleE133Node node(opts);\n\n \/\/ Optionally attach some other endpoints.\n vector endpoints;\n auto_ptr dummy_responder;\n auto_ptr\n discoverable_dummy_responder;\n auto_ptr tri_widget;\n\n ola::rdm::UIDAllocator uid_allocator(*uid);\n \/\/ The first uid is used for the management endpoint so we burn a UID here.\n {\n auto_ptr dummy_uid(uid_allocator.AllocateNext());\n }\n\n \/\/ Setup E1.31 if required.\n auto_ptr e131_node;\n if (FLAGS_e131) {\n e131_node.reset(new ola::plugin::e131::E131Node(FLAGS_listen_ip, cid));\n if (!e131_node->Start()) {\n OLA_WARN << \"Failed to start E1.31 node\";\n exit(EX_UNAVAILABLE);\n }\n OLA_INFO << \"Started E1.31 node!\";\n node.SelectServer()->AddReadDescriptor(e131_node->GetSocket());\n }\n\n if (FLAGS_dummy) {\n auto_ptr dummy_uid(uid_allocator.AllocateNext());\n if (!dummy_uid.get()) {\n OLA_WARN << \"Failed to allocate a UID for the DummyResponder.\";\n exit(EX_USAGE);\n }\n\n dummy_responder.reset(new ola::plugin::dummy::DummyResponder(*dummy_uid));\n discoverable_dummy_responder.reset(\n new ola::rdm::DiscoverableRDMControllerAdaptor(\n *dummy_uid, dummy_responder.get()));\n endpoints.push_back(new E133Endpoint(discoverable_dummy_responder.get(),\n E133Endpoint::EndpointProperties()));\n }\n\n \/\/ uber hack for now.\n \/\/ TODO(simon): fix this\n DmxBuffer tri_buffer;\n uint8_t unused_priority;\n if (!FLAGS_tri_device.str().empty()) {\n ola::io::ConnectedDescriptor *descriptor =\n ola::plugin::usbpro::BaseUsbProWidget::OpenDevice(FLAGS_tri_device);\n if (!descriptor) {\n OLA_WARN << \"Failed to open \" << FLAGS_tri_device;\n exit(EX_USAGE);\n }\n tri_widget.reset(new DmxTriWidget(node.SelectServer(), descriptor));\n node.SelectServer()->AddReadDescriptor(descriptor);\n E133Endpoint::EndpointProperties properties;\n properties.is_physical = true;\n endpoints.push_back(\n new E133Endpoint(tri_widget.get(), properties));\n\n if (e131_node.get()) {\n \/\/ Danger!\n e131_node->SetHandler(\n 1, &tri_buffer, &unused_priority,\n NewCallback(&HandleTriDMX, &tri_buffer, tri_widget.get()));\n }\n }\n\n \/\/ uber hack for now.\n \/\/ TODO(simon): fix this\n#ifdef USE_SPI\n auto_ptr spi_backend;\n DmxBuffer spi_buffer;\n\n if (!FLAGS_spi_device.str().empty()) {\n auto_ptr spi_uid(uid_allocator.AllocateNext());\n if (!spi_uid.get()) {\n OLA_WARN << \"Failed to allocate a UID for the SPI device.\";\n exit(EX_USAGE);\n }\n\n spi_backend.reset(\n new SPIBackend(FLAGS_spi_device, *spi_uid, SPIBackend::Options()));\n E133Endpoint::EndpointProperties properties;\n properties.is_physical = true;\n endpoints.push_back(new E133Endpoint(spi_backend.get(), properties));\n\n if (e131_node.get()) {\n \/\/ Danger!\n e131_node->SetHandler(\n 1, &spi_buffer, &unused_priority,\n NewCallback(&HandleSpiDMX, &spi_buffer, spi_backend.get()));\n }\n }\n#endif\n\n for (unsigned int i = 0; i < endpoints.size(); i++) {\n node.AddEndpoint(i + 1, endpoints[i]);\n }\n simple_node = &node;\n\n if (!node.Init())\n exit(EX_UNAVAILABLE);\n\n \/\/ signal handler\n if (!ola::InstallSignal(SIGINT, &InteruptSignal))\n return false;\n\n node.Run();\n if (e131_node.get()) {\n node.SelectServer()->RemoveReadDescriptor(e131_node->GetSocket());\n }\n for (unsigned int i = 0; i < endpoints.size(); i++) {\n node.RemoveEndpoint(i + 1);\n }\n ola::STLDeleteElements(&endpoints);\n}\n<|endoftext|>"} {"text":"#include \"Spectrum2.h\"\n\nSpectrum2::Spectrum2(uint16_t columns,\n uint16_t rows,\n uint16_t rowOffset,\n uint16_t length,\n uint8_t hue,\n uint8_t saturation,\n bool invert,\n CRGB * leds)\n: Visualization(columns, rows, hue, saturation, leds) {\n this->rowOffset = rowOffset;\n this->invert = invert;\n this->length = length;\n this->density = 0.06;\n this->threshold = 1000.0;\n this->peak = 2000.0;\n this->drift = 0;\n this->totalMagnitudeMovingAverage = 20000.0;\n}\n\nvoid Spectrum2::display(float* magnitudes) {\n uint_fast16_t peakCount = 0;\n bool overPeak = false;\n\n float sorted[this->length];\n memcpy(sorted, magnitudes, sizeof(magnitudes[0]) * this->length);\n std::sort(sorted, sorted+sizeof(sorted)\/sizeof(sorted[0]));\n\n const float alpha = 0.9;\n\n float cutoffMagnitude = sorted[(uint_fast16_t)((1 - this->density)*this->length)];\n float peakMagnitude = sorted[this->length - 2];\n this->threshold = (this->threshold * alpha) + (cutoffMagnitude* (1 - alpha));\n this->peak = (this->peak * alpha) + (peakMagnitude * (1 - alpha));\n\n float magnitude;\n float magnitudeSum = 0;\n\n for (uint8_t y=0; ylength; y++) {\n overPeak = false;\n magnitudeSum += magnitudes[y];\n\n if (magnitudes[y] < this->threshold) {\n continue;\n }\n\n if (magnitudes[y] > this->peak * 1.2) {\n peakCount++;\n overPeak = true;\n }\n\n magnitude = ((magnitudes[y] - this->threshold) \/ (this->peak - this->threshold));\n magnitude = min(magnitude, 1);\n magnitude = max(magnitude, 0.15);\n\n CRGB c = CHSV(this->hue, this->saturation, magnitude*255);\n CRGB c2 = CHSV(this->hue, this->saturation, magnitude*128);\n for (uint8_t x=0; xcolumns; x++) {\n if (this->invert) {\n leds[this->xy2Pos(x, this->rowOffset - y)] = c;\n if (overPeak) {\n if (y > 0) {\n leds[this->xy2Pos(x, (this->rowOffset - (y - 1)))] = c2;\n }\n if (y < this->length - 1) {\n leds[this->xy2Pos(x, (this->rowOffset - (y + 1)))] = c2;\n }\n }\n } else {\n leds[this->xy2Pos(x, y + this->rowOffset)] = c;\n if (overPeak) {\n if (y > 0) {\n leds[this->xy2Pos(x, (y + this->rowOffset) - 1)] = c2;\n }\n if (y < this->length - 1) {\n leds[this->xy2Pos(x, y + this->rowOffset + 1)] = c2;\n }\n }\n }\n }\n if (overPeak) {\n y++;\n }\n }\n\n this->hue += this->drift;\n\n \/\/ Change hue to pink on big volume increases\n if (this->drift > 0 && magnitudeSum > this->totalMagnitudeMovingAverage * 1.75) {\n this->hue = 240;\n }\n\n this->totalMagnitudeMovingAverage = (this->totalMagnitudeMovingAverage * (0.9998)) + (magnitudeSum\/5000.0);\n\n\n uint_fast32_t currentTime = millis();\n\n \/\/ put things we want to log here\n if (currentTime > this->loggingTimestamp + 5000) {\n this->loggingTimestamp = currentTime;\n\n \/\/ Serial.print(peakCount);\n \/\/ Serial.print(cutoffMagnitude);\n \/\/ Serial.print(\"\\t\");\n \/\/ Serial.print(peakMagnitude);\n \/\/ Serial.print(\"\\t\");\n \/\/ Serial.print(this->threshold);\n \/\/ Serial.print(\"\\t\");\n \/\/ Serial.print(this->peak);\n \/\/ Serial.print(\"\\t\");\n \/\/ Serial.print(this->hue);\n \/\/ Serial.print(\"\\t\");\n \/\/ Serial.print(magnitudeSum);\n \/\/ Serial.print(\"\\t\");\n \/\/ Serial.print(this->totalMagnitudeMovingAverage);\n \/\/ Serial.println(\"\");\n }\n}\n\nvoid Spectrum2::setDrift(uint8_t drift) {\n this->drift = drift;\n}\n\nfloat Spectrum2::getDensity() {\n return this->density;\n}\n\nvoid Spectrum2::setDensity(float density) {\n this->density = density;\n}\nmake drift time based vs cycle based#include \"Spectrum2.h\"\n\nSpectrum2::Spectrum2(uint16_t columns,\n uint16_t rows,\n uint16_t rowOffset,\n uint16_t length,\n uint8_t hue,\n uint8_t saturation,\n bool invert,\n CRGB * leds)\n: Visualization(columns, rows, hue, saturation, leds) {\n this->rowOffset = rowOffset;\n this->invert = invert;\n this->length = length;\n this->density = 0.06;\n this->threshold = 1000.0;\n this->peak = 2000.0;\n this->drift = 0;\n this->totalMagnitudeMovingAverage = 20000.0;\n}\n\nvoid Spectrum2::display(float* magnitudes) {\n uint_fast16_t peakCount = 0;\n bool overPeak = false;\n\n float sorted[this->length];\n memcpy(sorted, magnitudes, sizeof(magnitudes[0]) * this->length);\n std::sort(sorted, sorted+sizeof(sorted)\/sizeof(sorted[0]));\n\n const float alpha = 0.9;\n\n float cutoffMagnitude = sorted[(uint_fast16_t)((1 - this->density)*this->length)];\n float peakMagnitude = sorted[this->length - 2];\n this->threshold = (this->threshold * alpha) + (cutoffMagnitude* (1 - alpha));\n this->peak = (this->peak * alpha) + (peakMagnitude * (1 - alpha));\n\n float magnitude;\n float magnitudeSum = 0;\n\n for (uint8_t y=0; ylength; y++) {\n overPeak = false;\n magnitudeSum += magnitudes[y];\n\n if (magnitudes[y] < this->threshold) {\n continue;\n }\n\n if (magnitudes[y] > this->peak * 1.2) {\n peakCount++;\n overPeak = true;\n }\n\n magnitude = ((magnitudes[y] - this->threshold) \/ (this->peak - this->threshold));\n magnitude = min(magnitude, 1);\n magnitude = max(magnitude, 0.15);\n\n CRGB c = CHSV(this->hue, this->saturation, magnitude*255);\n CRGB c2 = CHSV(this->hue, this->saturation, magnitude*128);\n for (uint8_t x=0; xcolumns; x++) {\n if (this->invert) {\n leds[this->xy2Pos(x, this->rowOffset - y)] = c;\n if (overPeak) {\n if (y > 0) {\n leds[this->xy2Pos(x, (this->rowOffset - (y - 1)))] = c2;\n }\n if (y < this->length - 1) {\n leds[this->xy2Pos(x, (this->rowOffset - (y + 1)))] = c2;\n }\n }\n } else {\n leds[this->xy2Pos(x, y + this->rowOffset)] = c;\n if (overPeak) {\n if (y > 0) {\n leds[this->xy2Pos(x, (y + this->rowOffset) - 1)] = c2;\n }\n if (y < this->length - 1) {\n leds[this->xy2Pos(x, y + this->rowOffset + 1)] = c2;\n }\n }\n }\n }\n if (overPeak) {\n y++;\n }\n }\n\n uint_fast32_t currentTime = millis();\n\n this->hue = (currentTime \/ this->drift) % 256;\n\n \/\/ Change hue to pink on big volume increases\n if (this->drift > 0 && magnitudeSum > this->totalMagnitudeMovingAverage * 1.75) {\n this->hue = 240;\n }\n\n this->totalMagnitudeMovingAverage = (this->totalMagnitudeMovingAverage * (0.9998)) + (magnitudeSum\/5000.0);\n\n\n \/\/ put things we want to log here\n if (currentTime > this->loggingTimestamp + 5000) {\n this->loggingTimestamp = currentTime;\n\n \/\/ Serial.print(peakCount);\n \/\/ Serial.print(cutoffMagnitude);\n \/\/ Serial.print(\"\\t\");\n \/\/ Serial.print(peakMagnitude);\n \/\/ Serial.print(\"\\t\");\n \/\/ Serial.print(this->threshold);\n \/\/ Serial.print(\"\\t\");\n \/\/ Serial.print(this->peak);\n \/\/ Serial.print(\"\\t\");\n \/\/ Serial.print(this->hue);\n \/\/ Serial.print(\"\\t\");\n \/\/ Serial.print(magnitudeSum);\n \/\/ Serial.print(\"\\t\");\n \/\/ Serial.print(this->totalMagnitudeMovingAverage);\n \/\/ Serial.println(\"\");\n }\n}\n\nvoid Spectrum2::setDrift(uint8_t drift) {\n this->drift = drift;\n}\n\nfloat Spectrum2::getDensity() {\n return this->density;\n}\n\nvoid Spectrum2::setDensity(float density) {\n this->density = density;\n}\n<|endoftext|>"} {"text":"\/*\n** Copyright 2015 Centreon\n**\n** Licensed under the Apache License, Version 2.0 (the \"License\");\n** you may not use this file except in compliance with the License.\n** You may obtain a copy of the License at\n**\n** http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n**\n** Unless required by applicable law or agreed to in writing, software\n** distributed under the License is distributed on an \"AS IS\" BASIS,\n** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n** See the License for the specific language governing permissions and\n** limitations under the License.\n**\n** For more information : contact@centreon.com\n*\/\n\n#include \n#include \"com\/centreon\/broker\/database.hh\"\n#include \"com\/centreon\/broker\/database_preparator.hh\"\n#include \"com\/centreon\/broker\/exceptions\/msg.hh\"\n#include \"com\/centreon\/broker\/io\/events.hh\"\n#include \"com\/centreon\/broker\/mapping\/entry.hh\"\n\nusing namespace com::centreon::broker;\n\n\/**\n * Constructor.\n *\n * @param[in] event_id Event ID.\n * @param[in] unique Event UNIQUE.\n * @param[in] excluded Fields excluded from the query.\n *\/\ndatabase_preparator::database_preparator(\n unsigned int event_id,\n database_preparator::event_unique const& unique,\n database_query::excluded_fields const& excluded)\n : _event_id(event_id), _excluded(excluded), _unique(unique) {}\n\n\/**\n * Copy constructor.\n *\n * @param[in] other Object to copy.\n *\/\ndatabase_preparator::database_preparator(\n database_preparator const& other) {\n _event_id = other._event_id;\n _excluded = other._excluded;\n _unique = other._unique;\n}\n\n\/**\n * Destructor.\n *\/\ndatabase_preparator::~database_preparator() {}\n\n\/**\n * Assignment operator.\n *\n * @param[in] other Object to copy.\n *\n * @return This object.\n *\/\ndatabase_preparator& database_preparator::operator=(\n database_preparator const& other) {\n if (this != &other) {\n _event_id = other._event_id;\n _excluded = other._excluded;\n _unique = other._unique;\n }\n return (*this);\n}\n\n\/**\n * Prepare insertion query for specified event.\n *\n * @param[out] q Database query, prepared and ready to run.\n *\/\nvoid database_preparator::prepare_insert(database_query& q) {\n \/\/ Find event info.\n io::event_info const*\n info(io::events::instance().get_event_info(_event_id));\n if (!info)\n throw (exceptions::msg()\n << \"could not prepare insertion query for event of type \"\n << _event_id << \": event is not registered\");\n\n \/\/ Database schema version.\n bool schema_v2(q.db_object().schema_version() == database::v2);\n\n \/\/ Build query string.\n std::string query;\n query = \"INSERT INTO \";\n if (schema_v2)\n query.append(info->get_table_v2());\n else\n query.append(info->get_table());\n query.append(\" (\");\n mapping::entry const* entries(info->get_mapping());\n for (int i(0); !entries[i].is_null(); ++i) {\n char const* entry_name;\n if (schema_v2)\n entry_name = entries[i].get_name_v2();\n else\n entry_name = entries[i].get_name();\n if (!entry_name\n || !entry_name[0]\n || (_excluded.find(entry_name) != _excluded.end()))\n continue ;\n query.append(entry_name);\n query.append(\", \");\n }\n query.resize(query.size() - 2);\n query.append(\") VALUES(\");\n for (int i(0); !entries[i].is_null(); ++i) {\n char const* entry_name;\n if (schema_v2)\n entry_name = entries[i].get_name_v2();\n else\n entry_name = entries[i].get_name();\n if (!entry_name\n || !entry_name[0]\n || (_excluded.find(entry_name) != _excluded.end()))\n continue ;\n query.append(\":\");\n query.append(entry_name);\n query.append(\", \");\n }\n query.resize(query.size() - 2);\n query.append(\")\");\n\n \/\/ Prepare statement.\n try {\n q.prepare(query);\n }\n catch (std::exception const& e) {\n throw (exceptions::msg()\n << \"could not prepare insertion query for event '\"\n << info->get_name() << \"' in table '\"\n << info->get_table() << \"': \" << e.what());\n }\n\n return ;\n}\n\n\/**\n * Prepare update query for specified event.\n *\n * @param[out] q Database query, prepared and ready to run.\n *\/\nvoid database_preparator::prepare_update(database_query& q) {\n \/\/ Find event info.\n io::event_info const*\n info(io::events::instance().get_event_info(_event_id));\n if (!info)\n throw (exceptions::msg()\n << \"could not prepare update query for event of type \"\n << _event_id << \": event is not registered\");\n\n \/\/ Database schema version.\n bool schema_v2(q.db_object().schema_version() == database::v2);\n\n \/\/ Build query string.\n std::string query;\n std::string where;\n query = \"UPDATE \";\n if (schema_v2)\n query.append(info->get_table_v2());\n else\n query.append(info->get_table());\n query.append(\" SET \");\n where = \" WHERE \";\n mapping::entry const* entries(info->get_mapping());\n for (int i(0); !entries[i].is_null(); ++i) {\n char const* entry_name;\n if (schema_v2)\n entry_name = entries[i].get_name_v2();\n else\n entry_name = entries[i].get_name();\n if (!entry_name\n || !entry_name[0]\n || (_excluded.find(entry_name) != _excluded.end()))\n continue ;\n \/\/ Standard field.\n if (_unique.find(entry_name) == _unique.end()) {\n query.append(entry_name);\n query.append(\"=:\");\n query.append(entry_name);\n query.append(\", \");\n }\n \/\/ Part of ID field.\n else {\n where.append(\"COALESCE(\");\n where.append(entry_name);\n where.append(\", -1)=COALESCE(:\");\n where.append(entry_name);\n where.append(\", -1) AND \");\n }\n }\n query.resize(query.size() - 2);\n query.append(where, 0, where.size() - 5);\n\n \/\/ Prepare statement.\n try {\n q.prepare(query);\n }\n catch (std::exception const& e) {\n throw (exceptions::msg()\n << \"could not prepare update query for event '\"\n << info->get_name() << \"' on table '\"\n << info->get_table() << \"': \" << e.what());\n }\n\n return ;\n}\n\n\/**\n * Prepare deletion query for specified event.\n *\n * @param[out] q Database query, prepared and ready to run.\n *\/\nvoid database_preparator::prepare_delete(database_query& q) {\n \/\/ Find event info.\n io::event_info const*\n info(io::events::instance().get_event_info(_event_id));\n if (!info)\n throw (exceptions::msg()\n << \"could not prepare deletion query for event of type \"\n << _event_id << \": event is not registered\");\n\n \/\/ Database schema version.\n bool schema_v2(q.db_object().schema_version() == database::v2);\n\n \/\/ Prepare query.\n std::string query;\n query = \"DELETE FROM \";\n if (schema_v2)\n query.append(info->get_table_v2());\n else\n query.append(info->get_table());\n query.append(\" WHERE \");\n for (event_unique::const_iterator\n it(_unique.begin()),\n end(_unique.end());\n it != end;\n ++it) {\n query.append(\"COALESCE(\");\n query.append(*it);\n query.append(\", -1)=COALESCE(:\");\n query.append(*it);\n query.append(\", -1) AND \");\n }\n query.resize(query.size() - 5);\n\n \/\/ Prepare statement.\n try {\n q.prepare(query);\n }\n catch (std::exception const& e) {\n throw (exceptions::msg()\n << \"could not prepare deletion query for event '\"\n << info->get_name() << \"' on table '\"\n << info->get_table() << \"': \" << e.what());\n }\n\n return ;\n}\nCore: fix indexing in database preparator queries.\/*\n** Copyright 2015 Centreon\n**\n** Licensed under the Apache License, Version 2.0 (the \"License\");\n** you may not use this file except in compliance with the License.\n** You may obtain a copy of the License at\n**\n** http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n**\n** Unless required by applicable law or agreed to in writing, software\n** distributed under the License is distributed on an \"AS IS\" BASIS,\n** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n** See the License for the specific language governing permissions and\n** limitations under the License.\n**\n** For more information : contact@centreon.com\n*\/\n\n#include \n#include \"com\/centreon\/broker\/database.hh\"\n#include \"com\/centreon\/broker\/database_preparator.hh\"\n#include \"com\/centreon\/broker\/exceptions\/msg.hh\"\n#include \"com\/centreon\/broker\/io\/events.hh\"\n#include \"com\/centreon\/broker\/mapping\/entry.hh\"\n\nusing namespace com::centreon::broker;\n\n\/**\n * Constructor.\n *\n * @param[in] event_id Event ID.\n * @param[in] unique Event UNIQUE.\n * @param[in] excluded Fields excluded from the query.\n *\/\ndatabase_preparator::database_preparator(\n unsigned int event_id,\n database_preparator::event_unique const& unique,\n database_query::excluded_fields const& excluded)\n : _event_id(event_id), _excluded(excluded), _unique(unique) {}\n\n\/**\n * Copy constructor.\n *\n * @param[in] other Object to copy.\n *\/\ndatabase_preparator::database_preparator(\n database_preparator const& other) {\n _event_id = other._event_id;\n _excluded = other._excluded;\n _unique = other._unique;\n}\n\n\/**\n * Destructor.\n *\/\ndatabase_preparator::~database_preparator() {}\n\n\/**\n * Assignment operator.\n *\n * @param[in] other Object to copy.\n *\n * @return This object.\n *\/\ndatabase_preparator& database_preparator::operator=(\n database_preparator const& other) {\n if (this != &other) {\n _event_id = other._event_id;\n _excluded = other._excluded;\n _unique = other._unique;\n }\n return (*this);\n}\n\n\/**\n * Prepare insertion query for specified event.\n *\n * @param[out] q Database query, prepared and ready to run.\n *\/\nvoid database_preparator::prepare_insert(database_query& q) {\n \/\/ Find event info.\n io::event_info const*\n info(io::events::instance().get_event_info(_event_id));\n if (!info)\n throw (exceptions::msg()\n << \"could not prepare insertion query for event of type \"\n << _event_id << \": event is not registered\");\n\n \/\/ Database schema version.\n bool schema_v2(q.db_object().schema_version() == database::v2);\n\n \/\/ Build query string.\n std::string query;\n query = \"INSERT INTO \";\n if (schema_v2)\n query.append(info->get_table_v2());\n else\n query.append(info->get_table());\n query.append(\" (\");\n mapping::entry const* entries(info->get_mapping());\n for (int i(0); !entries[i].is_null(); ++i) {\n char const* entry_name;\n if (schema_v2)\n entry_name = entries[i].get_name_v2();\n else\n entry_name = entries[i].get_name();\n if (!entry_name\n || !entry_name[0]\n || (_excluded.find(entry_name) != _excluded.end()))\n continue ;\n query.append(entry_name);\n query.append(\", \");\n }\n query.resize(query.size() - 2);\n query.append(\") VALUES(\");\n for (int i(0); !entries[i].is_null(); ++i) {\n char const* entry_name;\n if (schema_v2)\n entry_name = entries[i].get_name_v2();\n else\n entry_name = entries[i].get_name();\n if (!entry_name\n || !entry_name[0]\n || (_excluded.find(entry_name) != _excluded.end()))\n continue ;\n query.append(\":\");\n query.append(entry_name);\n query.append(\", \");\n }\n query.resize(query.size() - 2);\n query.append(\")\");\n\n \/\/ Prepare statement.\n try {\n q.prepare(query);\n }\n catch (std::exception const& e) {\n throw (exceptions::msg()\n << \"could not prepare insertion query for event '\"\n << info->get_name() << \"' in table '\"\n << info->get_table() << \"': \" << e.what());\n }\n\n return ;\n}\n\n\/**\n * Prepare update query for specified event.\n *\n * @param[out] q Database query, prepared and ready to run.\n *\/\nvoid database_preparator::prepare_update(database_query& q) {\n \/\/ Find event info.\n io::event_info const*\n info(io::events::instance().get_event_info(_event_id));\n if (!info)\n throw (exceptions::msg()\n << \"could not prepare update query for event of type \"\n << _event_id << \": event is not registered\");\n\n \/\/ Database schema version.\n bool schema_v2(q.db_object().schema_version() == database::v2);\n\n \/\/ Build query string.\n std::string query;\n std::string where;\n query = \"UPDATE \";\n if (schema_v2)\n query.append(info->get_table_v2());\n else\n query.append(info->get_table());\n query.append(\" SET \");\n where = \" WHERE \";\n mapping::entry const* entries(info->get_mapping());\n for (int i(0); !entries[i].is_null(); ++i) {\n char const* entry_name;\n if (schema_v2)\n entry_name = entries[i].get_name_v2();\n else\n entry_name = entries[i].get_name();\n if (!entry_name\n || !entry_name[0]\n || (_excluded.find(entry_name) != _excluded.end()))\n continue ;\n \/\/ Standard field.\n if (_unique.find(entry_name) == _unique.end()) {\n query.append(entry_name);\n query.append(\"=:\");\n query.append(entry_name);\n query.append(\", \");\n }\n \/\/ Part of ID field.\n else {\n where.append(entry_name);\n where.append(\"=COALESCE(:\");\n where.append(entry_name);\n where.append(\", -1) AND \");\n }\n }\n query.resize(query.size() - 2);\n query.append(where, 0, where.size() - 5);\n\n \/\/ Prepare statement.\n try {\n q.prepare(query);\n }\n catch (std::exception const& e) {\n throw (exceptions::msg()\n << \"could not prepare update query for event '\"\n << info->get_name() << \"' on table '\"\n << info->get_table() << \"': \" << e.what());\n }\n\n return ;\n}\n\n\/**\n * Prepare deletion query for specified event.\n *\n * @param[out] q Database query, prepared and ready to run.\n *\/\nvoid database_preparator::prepare_delete(database_query& q) {\n \/\/ Find event info.\n io::event_info const*\n info(io::events::instance().get_event_info(_event_id));\n if (!info)\n throw (exceptions::msg()\n << \"could not prepare deletion query for event of type \"\n << _event_id << \": event is not registered\");\n\n \/\/ Database schema version.\n bool schema_v2(q.db_object().schema_version() == database::v2);\n\n \/\/ Prepare query.\n std::string query;\n query = \"DELETE FROM \";\n if (schema_v2)\n query.append(info->get_table_v2());\n else\n query.append(info->get_table());\n query.append(\" WHERE \");\n for (event_unique::const_iterator\n it(_unique.begin()),\n end(_unique.end());\n it != end;\n ++it) {\n query.append(*it);\n query.append(\"=COALESCE(:\");\n query.append(*it);\n query.append(\", -1) AND \");\n }\n query.resize(query.size() - 5);\n\n \/\/ Prepare statement.\n try {\n q.prepare(query);\n }\n catch (std::exception const& e) {\n throw (exceptions::msg()\n << \"could not prepare deletion query for event '\"\n << info->get_name() << \"' on table '\"\n << info->get_table() << \"': \" << e.what());\n }\n\n return ;\n}\n<|endoftext|>"} {"text":"#include \"styleContext.h\"\n#include \"platform.h\"\n#include \"builders.h\"\n#include \"scene\/scene.h\"\n\n#define DUMP(...) \/\/do { logMsg(__VA_ARGS__); duk_dump_context_stderr(m_ctx); } while(0)\n\n\nnamespace Tangram {\n\nconst static char DATA_ID[] = \"\\xff\"\"\\xff\"\"data\";\nconst static char ATTR_ID[] = \"\\xff\"\"\\xff\"\"attr\";\nconst static char FUNC_ID[] = \"\\xff\"\"\\xff\"\"fns\";\n\nStyleContext::StyleContext() {\n m_ctx = duk_create_heap_default();\n\n \/\/ add empty feature_object\n duk_push_object(m_ctx);\n\n \/\/ assign instance to feature_object\n duk_push_pointer(m_ctx, this);\n if (!duk_put_prop_string(m_ctx, -2, DATA_ID)) {\n LOGE(\"Ctx not assigned\");\n }\n\n \/\/ put object in global scope\n if (!duk_put_global_string(m_ctx, \"feature\")) {\n LOGE(\"Feature not assigned\");\n }\n\n DUMP(\"init\\n\");\n}\n\nStyleContext::~StyleContext() {\n duk_destroy_heap(m_ctx);\n}\n\nvoid StyleContext::initFunctions(const Scene& _scene) {\n\n if (_scene.id == m_sceneId) {\n return;\n }\n m_sceneId = _scene.id;\n\n auto arr_idx = duk_push_array(m_ctx);\n int id = 0;\n\n for (auto& function : _scene.functions()) {\n LOGD(\"compile '%s'\", function.c_str());\n duk_push_string(m_ctx, function.c_str());\n duk_push_string(m_ctx, \"\");\n\n if (duk_pcompile(m_ctx, DUK_COMPILE_FUNCTION) == 0) {\n duk_put_prop_index(m_ctx, arr_idx, id);\n } else {\n LOGE(\"Compile failed: %s\", duk_safe_to_string(m_ctx, -1));\n duk_pop(m_ctx);\n }\n id++;\n }\n\n if (!duk_put_global_string(m_ctx, FUNC_ID)) {\n LOGE(\"'fns' object not set\");\n }\n\n DUMP(\"setScene - %d functions\\n\", id);\n}\n\nvoid StyleContext::setFeature(const Feature& _feature) {\n m_feature = &_feature;\n\n for (auto& item : _feature.props.items()) {\n addAccessor(item.key);\n }\n}\n\nvoid StyleContext::setGlobalZoom(float _zoom) {\n static const std::string _key(\"$zoom\");\n if (_zoom != m_globalZoom) {\n setGlobal(_key, _zoom);\n }\n}\n\nvoid StyleContext::setGlobal(const std::string& _key, const Value& _val) {\n Value& entry = m_globals[_key];\n if (entry == _val) { return; }\n\n entry = _val;\n\n if (_val.is()) {\n duk_push_number(m_ctx, _val.get());\n duk_put_global_string(m_ctx, _key.c_str());\n\n if (_key == \"$zoom\") { m_globalZoom = _val.get(); }\n\n } else if (_val.is()) {\n duk_push_string(m_ctx, _val.get().c_str());\n duk_put_global_string(m_ctx, _key.c_str());\n }\n}\n\nconst Value& StyleContext::getGlobal(const std::string& _key) const {\n\n const static Value NOT_FOUND(none_type{});\n\n auto it = m_globals.find(_key);\n if (it != m_globals.end()) {\n return it->second;\n }\n return NOT_FOUND;\n}\n\n\nvoid StyleContext::clear() {\n m_feature = nullptr;\n}\n\nbool StyleContext::addFunction(const std::string& _name, const std::string& _func) {\n\n duk_push_string(m_ctx, _func.c_str());\n duk_push_string(m_ctx, _name.c_str());\n\n if (duk_pcompile(m_ctx, DUK_COMPILE_FUNCTION) != 0) {\n LOGE(\"Compile failed: %s\", duk_safe_to_string(m_ctx, -1));\n return false;\n }\n\n \/\/ Put function in global scope\n duk_put_global_string(m_ctx, _name.c_str());\n\n\n DUMP(\"addFunction\\n\");\n return true;\n}\n\nbool StyleContext::evalFilter(FunctionID _id) const {\n if (!duk_get_global_string(m_ctx, FUNC_ID)) {\n LOGE(\"EvalFilterFn - functions not initialized\");\n return false;\n }\n\n if (!duk_get_prop_index(m_ctx, -1, _id)) {\n LOGE(\"EvalFilterFn - function %d not set\", _id);\n }\n\n if (duk_pcall(m_ctx, 0) != 0) {\n LOGE(\"EvalFilterFn: %s\", duk_safe_to_string(m_ctx, -1));\n }\n\n bool result = false;\n\n if (duk_is_boolean(m_ctx, -1)) {\n result = duk_get_boolean(m_ctx, -1);\n }\n\n \/\/ pop result\n duk_pop(m_ctx);\n \/\/ pop fns obj\n duk_pop(m_ctx);\n\n DUMP(\"evalFilterFn\\n\");\n return result;\n}\n\nbool StyleContext::evalFilterFn(const std::string& _name) {\n if (!duk_get_global_string(m_ctx, _name.c_str())) {\n LOGE(\"EvalFilter %s\", _name.c_str());\n return false;\n }\n\n if (duk_pcall(m_ctx, 0) != 0) {\n LOGE(\"EvalFilterFn: %s\", duk_safe_to_string(m_ctx, -1));\n }\n\n bool result = false;\n\n if (duk_is_boolean(m_ctx, -1)) {\n result = duk_get_boolean(m_ctx, -1);\n }\n\n \/\/ pop result\n duk_pop(m_ctx);\n\n DUMP(\"evalFilterFn\\n\");\n return result;\n}\n\nbool StyleContext::parseStyleResult(StyleParamKey _key, StyleParam::Value& _val) const {\n _val = none_type{};\n\n if (duk_is_string(m_ctx, -1)) {\n std::string value(duk_get_string(m_ctx, -1));\n _val = StyleParam::parseString(_key, value);\n\n } else if (duk_is_boolean(m_ctx, -1)) {\n bool value = duk_get_boolean(m_ctx, -1);\n\n switch (_key) {\n case StyleParamKey::visible:\n _val = value;\n break;\n case StyleParamKey::extrude:\n _val = value ? glm::vec2(NAN, NAN) : glm::vec2(0.0f, 0.0f);\n break;\n default:\n break;\n }\n\n } else if (duk_is_array(m_ctx, -1)) {\n duk_get_prop_string(m_ctx, -1, \"length\");\n int len = duk_get_int(m_ctx, -1);\n duk_pop(m_ctx);\n\n switch (_key) {\n case StyleParamKey::extrude: {\n if (len != 2) {\n LOGW(\"Wrong array size for extrusion: '%d'.\", len);\n break;\n }\n\n duk_get_prop_index(m_ctx, -1, 0);\n double v1 = duk_get_number(m_ctx, -1);\n duk_pop(m_ctx);\n\n duk_get_prop_index(m_ctx, -1, 1);\n double v2 = duk_get_number(m_ctx, -1);\n duk_pop(m_ctx);\n\n _val = glm::vec2(v1, v2);\n break;\n }\n case StyleParamKey::color:\n case StyleParamKey::outline_color:\n case StyleParamKey::font_fill:\n case StyleParamKey::font_stroke_color: {\n if (len < 3 || len > 4) {\n LOGW(\"Wrong array size for color: '%d'.\", len);\n break;\n }\n duk_get_prop_index(m_ctx, -1, 0);\n double r = duk_get_number(m_ctx, -1);\n duk_pop(m_ctx);\n\n duk_get_prop_index(m_ctx, -1, 1);\n double g = duk_get_number(m_ctx, -1);\n duk_pop(m_ctx);\n\n duk_get_prop_index(m_ctx, -1, 2);\n double b = duk_get_number(m_ctx, -1);\n duk_pop(m_ctx);\n\n double a = 1.0;\n if (len == 4) {\n duk_get_prop_index(m_ctx, -1, 3);\n a = duk_get_number(m_ctx, -1);\n duk_pop(m_ctx);\n }\n\n _val = (((uint32_t)(255.0 * a) & 0xff) << 24) |\n (((uint32_t)(255.0 * r) & 0xff)<< 16) |\n (((uint32_t)(255.0 * g) & 0xff)<< 8) |\n (((uint32_t)(255.0 * b) & 0xff));\n break;\n }\n default:\n break;\n }\n\n } else if (duk_is_number(m_ctx, -1)) {\n\n switch (_key) {\n case StyleParamKey::width:\n case StyleParamKey::outline_width:\n case StyleParamKey::font_stroke_width: {\n double v = duk_get_number(m_ctx, -1);\n _val = StyleParam::Width{static_cast(v)};\n break;\n }\n case StyleParamKey::order:\n case StyleParamKey::priority:\n case StyleParamKey::color:\n case StyleParamKey::outline_color:\n case StyleParamKey::font_fill:\n case StyleParamKey::font_stroke_color: {\n _val = static_cast(duk_get_uint(m_ctx, -1));\n break;\n }\n default:\n break;\n }\n } else {\n LOGW(\"Unhandled return type from Javascript function.\");\n }\n\n duk_pop(m_ctx);\n\n DUMP(\"parseStyleResult\\n\");\n return !_val.is();\n}\n\nbool StyleContext::evalStyle(FunctionID _id, StyleParamKey _key, StyleParam::Value& _val) const {\n if (!duk_get_global_string(m_ctx, FUNC_ID)) {\n LOGE(\"EvalFilterFn - functions array not initialized\");\n return false;\n }\n\n if (!duk_get_prop_index(m_ctx, -1, _id)) {\n LOGE(\"EvalFilterFn - function %d not set\", _id);\n }\n\n \/\/ pop fns array\n duk_remove(m_ctx, -2);\n\n if (duk_pcall(m_ctx, 0) != 0) {\n LOGE(\"EvalFilterFn: %s\", duk_safe_to_string(m_ctx, -1));\n duk_pop(m_ctx);\n return false;\n }\n\n return parseStyleResult(_key, _val);\n}\n\n\nbool StyleContext::evalStyleFn(const std::string& name, StyleParamKey _key, StyleParam::Value& _val) {\n if (!duk_get_global_string(m_ctx, name.c_str())) {\n LOGE(\"EvalFilter %s\", name.c_str());\n return false;\n }\n\n if (duk_pcall(m_ctx, 0) != 0) {\n LOGE(\"EvalStyleFn: %s\", duk_safe_to_string(m_ctx, -1));\n duk_pop(m_ctx);\n return false;\n }\n\n return parseStyleResult(_key, _val);\n}\n\n\nvoid StyleContext::addAccessor(const std::string& _name) {\n\n auto it = m_accessors.find(_name);\n if (it != m_accessors.end()) {\n return;\n }\n\n auto entry = m_accessors.emplace(_name, Accessor{_name, this});\n if (!entry.second) {\n return; \/\/ hmm, already added..\n }\n\n Accessor& attr = (*entry.first).second;\n\n \/\/ push 'feature' obj onto stack\n if (!duk_get_global_string(m_ctx, \"feature\")) {\n LOGE(\"'feature' not in global scope\");\n return;\n }\n\n \/\/ push property name\n duk_push_string(m_ctx, _name.c_str());\n\n \/\/ push getter function\n duk_push_c_function(m_ctx, jsPropertyGetter, 0 \/*nargs*\/);\n duk_push_pointer(m_ctx, (void*)&attr);\n duk_put_prop_string(m_ctx, -2, ATTR_ID);\n\n \/\/ push setter function\n \/\/ duk_push_c_function(m_ctx, jsPropertySetter, 1 \/*nargs*\/);\n \/\/ duk_push_pointer(m_ctx, (void*)&attr);\n \/\/ duk_put_prop_string(m_ctx, -2, ATTR_ID);\n\n \/\/ stack: [ feature_obj, name, getter, setter ] -> [ feature_obj.name ]\n duk_def_prop(m_ctx, -3,\n DUK_DEFPROP_HAVE_GETTER |\n \/\/ DUK_DEFPROP_HAVE_SETTER |\n \/\/ DUK_DEFPROP_WRITABLE |\n \/\/ DUK_DEFPROP_HAVE_ENUMERABLE |\n \/\/ DUK_DEFPROP_ENUMERABLE |\n \/\/ DUK_DEFPROP_HAVE_CONFIGURABLE |\n 0);\n\n \/\/ pop feature obj\n duk_pop(m_ctx);\n\n DUMP(\"addAccessor\\n\");\n}\n\nduk_ret_t StyleContext::jsPropertyGetter(duk_context *_ctx) {\n\n \/\/ Storing state for a Duktape\/C function:\n \/\/ http:\/\/duktape.org\/guide.html#programming.9\n duk_push_current_function(_ctx);\n duk_get_prop_string(_ctx, -1, ATTR_ID);\n auto* attr = static_cast (duk_to_pointer(_ctx, -1));\n\n if (!attr || !attr->ctx || !attr->ctx->m_feature) {\n LOGE(\"Error: no context set %p %p\",\n attr,\n attr ? attr->ctx : nullptr);\n\n duk_pop(_ctx);\n return 0;\n }\n\n auto it = attr->ctx->m_feature->props.get(attr->key);\n\n if (it.is()) {\n duk_push_string(_ctx, it.get().c_str());\n } else if (it.is()) {\n duk_push_number(_ctx, it.get());\n } else {\n duk_push_undefined(_ctx);\n }\n\n return 1;\n}\n\nduk_ret_t StyleContext::jsPropertySetter(duk_context *_ctx) {\n return 0;\n}\n\n}\nfix: stroke width is still just a float#include \"styleContext.h\"\n#include \"platform.h\"\n#include \"builders.h\"\n#include \"scene\/scene.h\"\n\n#define DUMP(...) \/\/do { logMsg(__VA_ARGS__); duk_dump_context_stderr(m_ctx); } while(0)\n\n\nnamespace Tangram {\n\nconst static char DATA_ID[] = \"\\xff\"\"\\xff\"\"data\";\nconst static char ATTR_ID[] = \"\\xff\"\"\\xff\"\"attr\";\nconst static char FUNC_ID[] = \"\\xff\"\"\\xff\"\"fns\";\n\nStyleContext::StyleContext() {\n m_ctx = duk_create_heap_default();\n\n \/\/ add empty feature_object\n duk_push_object(m_ctx);\n\n \/\/ assign instance to feature_object\n duk_push_pointer(m_ctx, this);\n if (!duk_put_prop_string(m_ctx, -2, DATA_ID)) {\n LOGE(\"Ctx not assigned\");\n }\n\n \/\/ put object in global scope\n if (!duk_put_global_string(m_ctx, \"feature\")) {\n LOGE(\"Feature not assigned\");\n }\n\n DUMP(\"init\\n\");\n}\n\nStyleContext::~StyleContext() {\n duk_destroy_heap(m_ctx);\n}\n\nvoid StyleContext::initFunctions(const Scene& _scene) {\n\n if (_scene.id == m_sceneId) {\n return;\n }\n m_sceneId = _scene.id;\n\n auto arr_idx = duk_push_array(m_ctx);\n int id = 0;\n\n for (auto& function : _scene.functions()) {\n LOGD(\"compile '%s'\", function.c_str());\n duk_push_string(m_ctx, function.c_str());\n duk_push_string(m_ctx, \"\");\n\n if (duk_pcompile(m_ctx, DUK_COMPILE_FUNCTION) == 0) {\n duk_put_prop_index(m_ctx, arr_idx, id);\n } else {\n LOGE(\"Compile failed: %s\", duk_safe_to_string(m_ctx, -1));\n duk_pop(m_ctx);\n }\n id++;\n }\n\n if (!duk_put_global_string(m_ctx, FUNC_ID)) {\n LOGE(\"'fns' object not set\");\n }\n\n DUMP(\"setScene - %d functions\\n\", id);\n}\n\nvoid StyleContext::setFeature(const Feature& _feature) {\n m_feature = &_feature;\n\n for (auto& item : _feature.props.items()) {\n addAccessor(item.key);\n }\n}\n\nvoid StyleContext::setGlobalZoom(float _zoom) {\n static const std::string _key(\"$zoom\");\n if (_zoom != m_globalZoom) {\n setGlobal(_key, _zoom);\n }\n}\n\nvoid StyleContext::setGlobal(const std::string& _key, const Value& _val) {\n Value& entry = m_globals[_key];\n if (entry == _val) { return; }\n\n entry = _val;\n\n if (_val.is()) {\n duk_push_number(m_ctx, _val.get());\n duk_put_global_string(m_ctx, _key.c_str());\n\n if (_key == \"$zoom\") { m_globalZoom = _val.get(); }\n\n } else if (_val.is()) {\n duk_push_string(m_ctx, _val.get().c_str());\n duk_put_global_string(m_ctx, _key.c_str());\n }\n}\n\nconst Value& StyleContext::getGlobal(const std::string& _key) const {\n\n const static Value NOT_FOUND(none_type{});\n\n auto it = m_globals.find(_key);\n if (it != m_globals.end()) {\n return it->second;\n }\n return NOT_FOUND;\n}\n\n\nvoid StyleContext::clear() {\n m_feature = nullptr;\n}\n\nbool StyleContext::addFunction(const std::string& _name, const std::string& _func) {\n\n duk_push_string(m_ctx, _func.c_str());\n duk_push_string(m_ctx, _name.c_str());\n\n if (duk_pcompile(m_ctx, DUK_COMPILE_FUNCTION) != 0) {\n LOGE(\"Compile failed: %s\", duk_safe_to_string(m_ctx, -1));\n return false;\n }\n\n \/\/ Put function in global scope\n duk_put_global_string(m_ctx, _name.c_str());\n\n\n DUMP(\"addFunction\\n\");\n return true;\n}\n\nbool StyleContext::evalFilter(FunctionID _id) const {\n if (!duk_get_global_string(m_ctx, FUNC_ID)) {\n LOGE(\"EvalFilterFn - functions not initialized\");\n return false;\n }\n\n if (!duk_get_prop_index(m_ctx, -1, _id)) {\n LOGE(\"EvalFilterFn - function %d not set\", _id);\n }\n\n if (duk_pcall(m_ctx, 0) != 0) {\n LOGE(\"EvalFilterFn: %s\", duk_safe_to_string(m_ctx, -1));\n }\n\n bool result = false;\n\n if (duk_is_boolean(m_ctx, -1)) {\n result = duk_get_boolean(m_ctx, -1);\n }\n\n \/\/ pop result\n duk_pop(m_ctx);\n \/\/ pop fns obj\n duk_pop(m_ctx);\n\n DUMP(\"evalFilterFn\\n\");\n return result;\n}\n\nbool StyleContext::evalFilterFn(const std::string& _name) {\n if (!duk_get_global_string(m_ctx, _name.c_str())) {\n LOGE(\"EvalFilter %s\", _name.c_str());\n return false;\n }\n\n if (duk_pcall(m_ctx, 0) != 0) {\n LOGE(\"EvalFilterFn: %s\", duk_safe_to_string(m_ctx, -1));\n }\n\n bool result = false;\n\n if (duk_is_boolean(m_ctx, -1)) {\n result = duk_get_boolean(m_ctx, -1);\n }\n\n \/\/ pop result\n duk_pop(m_ctx);\n\n DUMP(\"evalFilterFn\\n\");\n return result;\n}\n\nbool StyleContext::parseStyleResult(StyleParamKey _key, StyleParam::Value& _val) const {\n _val = none_type{};\n\n if (duk_is_string(m_ctx, -1)) {\n std::string value(duk_get_string(m_ctx, -1));\n _val = StyleParam::parseString(_key, value);\n\n } else if (duk_is_boolean(m_ctx, -1)) {\n bool value = duk_get_boolean(m_ctx, -1);\n\n switch (_key) {\n case StyleParamKey::visible:\n _val = value;\n break;\n case StyleParamKey::extrude:\n _val = value ? glm::vec2(NAN, NAN) : glm::vec2(0.0f, 0.0f);\n break;\n default:\n break;\n }\n\n } else if (duk_is_array(m_ctx, -1)) {\n duk_get_prop_string(m_ctx, -1, \"length\");\n int len = duk_get_int(m_ctx, -1);\n duk_pop(m_ctx);\n\n switch (_key) {\n case StyleParamKey::extrude: {\n if (len != 2) {\n LOGW(\"Wrong array size for extrusion: '%d'.\", len);\n break;\n }\n\n duk_get_prop_index(m_ctx, -1, 0);\n double v1 = duk_get_number(m_ctx, -1);\n duk_pop(m_ctx);\n\n duk_get_prop_index(m_ctx, -1, 1);\n double v2 = duk_get_number(m_ctx, -1);\n duk_pop(m_ctx);\n\n _val = glm::vec2(v1, v2);\n break;\n }\n case StyleParamKey::color:\n case StyleParamKey::outline_color:\n case StyleParamKey::font_fill:\n case StyleParamKey::font_stroke_color: {\n if (len < 3 || len > 4) {\n LOGW(\"Wrong array size for color: '%d'.\", len);\n break;\n }\n duk_get_prop_index(m_ctx, -1, 0);\n double r = duk_get_number(m_ctx, -1);\n duk_pop(m_ctx);\n\n duk_get_prop_index(m_ctx, -1, 1);\n double g = duk_get_number(m_ctx, -1);\n duk_pop(m_ctx);\n\n duk_get_prop_index(m_ctx, -1, 2);\n double b = duk_get_number(m_ctx, -1);\n duk_pop(m_ctx);\n\n double a = 1.0;\n if (len == 4) {\n duk_get_prop_index(m_ctx, -1, 3);\n a = duk_get_number(m_ctx, -1);\n duk_pop(m_ctx);\n }\n\n _val = (((uint32_t)(255.0 * a) & 0xff) << 24) |\n (((uint32_t)(255.0 * r) & 0xff)<< 16) |\n (((uint32_t)(255.0 * g) & 0xff)<< 8) |\n (((uint32_t)(255.0 * b) & 0xff));\n break;\n }\n default:\n break;\n }\n\n } else if (duk_is_number(m_ctx, -1)) {\n\n switch (_key) {\n case StyleParamKey::width:\n case StyleParamKey::outline_width: {\n \/\/ TODO more efficient way to return pixels.\n \/\/ atm this only works by return value as string\n double v = duk_get_number(m_ctx, -1);\n _val = StyleParam::Width{static_cast(v)};\n break;\n }\n case StyleParamKey::font_stroke_width: {\n double v = duk_get_number(m_ctx, -1);\n _val = static_cast(v);\n break;\n }\n case StyleParamKey::order:\n case StyleParamKey::priority:\n case StyleParamKey::color:\n case StyleParamKey::outline_color:\n case StyleParamKey::font_fill:\n case StyleParamKey::font_stroke_color: {\n _val = static_cast(duk_get_uint(m_ctx, -1));\n break;\n }\n default:\n break;\n }\n } else {\n LOGW(\"Unhandled return type from Javascript function.\");\n }\n\n duk_pop(m_ctx);\n\n DUMP(\"parseStyleResult\\n\");\n return !_val.is();\n}\n\nbool StyleContext::evalStyle(FunctionID _id, StyleParamKey _key, StyleParam::Value& _val) const {\n if (!duk_get_global_string(m_ctx, FUNC_ID)) {\n LOGE(\"EvalFilterFn - functions array not initialized\");\n return false;\n }\n\n if (!duk_get_prop_index(m_ctx, -1, _id)) {\n LOGE(\"EvalFilterFn - function %d not set\", _id);\n }\n\n \/\/ pop fns array\n duk_remove(m_ctx, -2);\n\n if (duk_pcall(m_ctx, 0) != 0) {\n LOGE(\"EvalFilterFn: %s\", duk_safe_to_string(m_ctx, -1));\n duk_pop(m_ctx);\n return false;\n }\n\n return parseStyleResult(_key, _val);\n}\n\n\nbool StyleContext::evalStyleFn(const std::string& name, StyleParamKey _key, StyleParam::Value& _val) {\n if (!duk_get_global_string(m_ctx, name.c_str())) {\n LOGE(\"EvalFilter %s\", name.c_str());\n return false;\n }\n\n if (duk_pcall(m_ctx, 0) != 0) {\n LOGE(\"EvalStyleFn: %s\", duk_safe_to_string(m_ctx, -1));\n duk_pop(m_ctx);\n return false;\n }\n\n return parseStyleResult(_key, _val);\n}\n\n\nvoid StyleContext::addAccessor(const std::string& _name) {\n\n auto it = m_accessors.find(_name);\n if (it != m_accessors.end()) {\n return;\n }\n\n auto entry = m_accessors.emplace(_name, Accessor{_name, this});\n if (!entry.second) {\n return; \/\/ hmm, already added..\n }\n\n Accessor& attr = (*entry.first).second;\n\n \/\/ push 'feature' obj onto stack\n if (!duk_get_global_string(m_ctx, \"feature\")) {\n LOGE(\"'feature' not in global scope\");\n return;\n }\n\n \/\/ push property name\n duk_push_string(m_ctx, _name.c_str());\n\n \/\/ push getter function\n duk_push_c_function(m_ctx, jsPropertyGetter, 0 \/*nargs*\/);\n duk_push_pointer(m_ctx, (void*)&attr);\n duk_put_prop_string(m_ctx, -2, ATTR_ID);\n\n \/\/ push setter function\n \/\/ duk_push_c_function(m_ctx, jsPropertySetter, 1 \/*nargs*\/);\n \/\/ duk_push_pointer(m_ctx, (void*)&attr);\n \/\/ duk_put_prop_string(m_ctx, -2, ATTR_ID);\n\n \/\/ stack: [ feature_obj, name, getter, setter ] -> [ feature_obj.name ]\n duk_def_prop(m_ctx, -3,\n DUK_DEFPROP_HAVE_GETTER |\n \/\/ DUK_DEFPROP_HAVE_SETTER |\n \/\/ DUK_DEFPROP_WRITABLE |\n \/\/ DUK_DEFPROP_HAVE_ENUMERABLE |\n \/\/ DUK_DEFPROP_ENUMERABLE |\n \/\/ DUK_DEFPROP_HAVE_CONFIGURABLE |\n 0);\n\n \/\/ pop feature obj\n duk_pop(m_ctx);\n\n DUMP(\"addAccessor\\n\");\n}\n\nduk_ret_t StyleContext::jsPropertyGetter(duk_context *_ctx) {\n\n \/\/ Storing state for a Duktape\/C function:\n \/\/ http:\/\/duktape.org\/guide.html#programming.9\n duk_push_current_function(_ctx);\n duk_get_prop_string(_ctx, -1, ATTR_ID);\n auto* attr = static_cast (duk_to_pointer(_ctx, -1));\n\n if (!attr || !attr->ctx || !attr->ctx->m_feature) {\n LOGE(\"Error: no context set %p %p\",\n attr,\n attr ? attr->ctx : nullptr);\n\n duk_pop(_ctx);\n return 0;\n }\n\n auto it = attr->ctx->m_feature->props.get(attr->key);\n\n if (it.is()) {\n duk_push_string(_ctx, it.get().c_str());\n } else if (it.is()) {\n duk_push_number(_ctx, it.get());\n } else {\n duk_push_undefined(_ctx);\n }\n\n return 1;\n}\n\nduk_ret_t StyleContext::jsPropertySetter(duk_context *_ctx) {\n return 0;\n}\n\n}\n<|endoftext|>"} {"text":"\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n\/\/ This file implements logic for lowering MHLO general dot to a regular dot.\n\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/StringSwitch.h\"\n#include \"mlir-hlo\/Dialect\/mhlo\/IR\/hlo_ops.h\"\n#include \"mlir-hlo\/Dialect\/mhlo\/transforms\/passes.h\"\n#include \"mlir-hlo\/Dialect\/mhlo\/transforms\/rewriters.h\"\n#include \"mlir\/Dialect\/StandardOps\/IR\/Ops.h\"\n#include \"mlir\/IR\/Attributes.h\"\n#include \"mlir\/IR\/Function.h\"\n#include \"mlir\/IR\/Location.h\"\n#include \"mlir\/IR\/Operation.h\"\n#include \"mlir\/IR\/PatternMatch.h\"\n#include \"mlir\/IR\/StandardTypes.h\"\n#include \"mlir\/IR\/TypeUtilities.h\"\n#include \"mlir\/Pass\/Pass.h\"\n\nusing mlir::DenseIntElementsAttr;\nusing mlir::ElementsAttr;\nusing mlir::failure;\nusing mlir::FunctionPass;\nusing mlir::LogicalResult;\nusing mlir::MLIRContext;\nusing mlir::OpRewritePattern;\nusing mlir::OwningRewritePatternList;\nusing mlir::PassRegistration;\nusing mlir::PassWrapper;\nusing mlir::PatternRewriter;\nusing mlir::RankedTensorType;\nusing mlir::success;\nusing mlir::Value;\n\nnamespace {\n\nValue TransposeReshape(Value arg, mlir::Location loc,\n llvm::ArrayRef left_dims,\n llvm::ArrayRef right_dims,\n llvm::ArrayRef arg_shape,\n PatternRewriter *rewriter) {\n auto element_type = mlir::getElementTypeOrSelf(arg.getType());\n\n int64_t left_size = 1;\n for (auto dim : left_dims) {\n left_size *= arg_shape[dim];\n }\n\n int64_t right_size = 1;\n for (auto dim : right_dims) {\n right_size *= arg_shape[dim];\n }\n\n \/\/ Generate the transpose permutation attribute.\n llvm::SmallVector transpose_permutation(left_dims.begin(),\n left_dims.end());\n transpose_permutation.append(right_dims.begin(), right_dims.end());\n\n mlir::TensorType transpose_permutation_type = RankedTensorType::get(\n {static_cast(transpose_permutation.size())},\n rewriter->getIntegerType(64));\n\n auto transpose_permutation_attr =\n DenseIntElementsAttr::get(transpose_permutation_type,\n llvm::makeArrayRef(transpose_permutation))\n .cast();\n\n \/\/ Compute the resulting shape.\n llvm::SmallVector transposed_shape;\n for (auto val : transpose_permutation) {\n transposed_shape.push_back(arg_shape[val]);\n }\n auto transpose_type = RankedTensorType::get(transposed_shape, element_type);\n auto transpose_result = rewriter->create(\n loc, transpose_type, arg, transpose_permutation_attr);\n\n \/\/ Return the final result.\n auto reshaped_type =\n RankedTensorType::get({left_size, right_size}, element_type);\n return rewriter->create(loc, reshaped_type,\n transpose_result);\n}\n\nValue ProcessDotArg(Value arg, mlir::Location loc,\n ElementsAttr contract_dims_attr, bool outer_dims_first,\n PatternRewriter *rewriter) {\n auto shape = arg.getType().cast().getShape();\n\n llvm::SmallVector is_outer_dim;\n is_outer_dim.resize(shape.size(), true);\n\n \/\/ Compute the contract dimension ordering.\n llvm::SmallVector contract_dims;\n for (auto dim : contract_dims_attr.getValues()) {\n contract_dims.push_back(dim);\n is_outer_dim[dim] = false;\n }\n\n \/\/ Compute the outer dimension orderings.\n llvm::SmallVector outer_dims;\n for (auto it : llvm::enumerate(is_outer_dim)) {\n if (it.value()) {\n outer_dims.push_back(it.index());\n }\n }\n\n if (outer_dims_first) {\n return TransposeReshape(arg, loc, outer_dims, contract_dims, shape,\n rewriter);\n }\n\n return TransposeReshape(arg, loc, contract_dims, outer_dims, shape, rewriter);\n}\n\nstruct GeneralDotConvert : public OpRewritePattern {\n \/\/ Attempts to lower a General Dot operator to a standard Dot operator.\n \/\/ General dots include batching dimensions and can have collapsing\n \/\/ dimensions along any axis. Inserting correctly arrange transpose and\n \/\/ reshape operators organizes the tensors and allows the General Dot to be\n \/\/ replaced with the standard Dot operator.\n \/\/\n \/\/ Note: This requires an empty list of batch dimensions.\n\n explicit GeneralDotConvert(MLIRContext *context)\n : OpRewritePattern(context) {}\n\n LogicalResult matchAndRewrite(mlir::mhlo::DotGeneralOp op,\n PatternRewriter &rewriter) const override {\n auto dot_element_type = mlir::getElementTypeOrSelf(op);\n\n auto dot_numbers = op.dot_dimension_numbers();\n if (dot_numbers.lhs_batching_dimensions().getNumElements() != 0 ||\n dot_numbers.rhs_batching_dimensions().getNumElements() != 0) {\n return failure();\n }\n\n auto lhs = ProcessDotArg(op.lhs(), op.getLoc(),\n dot_numbers.lhs_contracting_dimensions(),\n \/*outer_dims_first=*\/true, &rewriter);\n\n auto rhs = ProcessDotArg(op.rhs(), op.getLoc(),\n dot_numbers.rhs_contracting_dimensions(),\n \/*outer_dims_first=*\/false, &rewriter);\n\n \/\/ Dot resulting shape.\n auto lhs_shape = lhs.getType().cast().getShape();\n auto rhs_shape = rhs.getType().cast().getShape();\n auto new_dot_type =\n RankedTensorType::get({lhs_shape[0], rhs_shape[1]}, dot_element_type);\n\n auto new_dot_op = rewriter.create(\n op.getLoc(), new_dot_type, lhs, rhs, *(op.precision_config()));\n\n rewriter.replaceOpWithNewOp(op, op.getType(),\n new_dot_op);\n return success();\n }\n};\n\nstruct LegalizeGeneralDotPass\n : public PassWrapper {\n \/\/\/ Lower all general dots that can be represented as a non-batched matmul.\n void runOnFunction() override {\n OwningRewritePatternList patterns;\n mlir::mhlo::PopulateGeneralDotOpLoweringPatterns(&patterns, &getContext());\n applyPatternsAndFoldGreedily(getFunction(), patterns);\n }\n};\n\n} \/\/ namespace\n\nvoid mlir::mhlo::PopulateGeneralDotOpLoweringPatterns(\n OwningRewritePatternList *patterns, MLIRContext *ctx) {\n patterns->insert(ctx);\n}\n\nstd::unique_ptr<::mlir::Pass> mlir::mhlo::createLegalizeGeneralDotPass() {\n return std::make_unique();\n}\nOnly apply GeneralDotOpLoweringPatterns for static shaped inputs\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n\/\/ This file implements logic for lowering MHLO general dot to a regular dot.\n\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/StringSwitch.h\"\n#include \"mlir-hlo\/Dialect\/mhlo\/IR\/hlo_ops.h\"\n#include \"mlir-hlo\/Dialect\/mhlo\/transforms\/passes.h\"\n#include \"mlir-hlo\/Dialect\/mhlo\/transforms\/rewriters.h\"\n#include \"mlir\/Dialect\/StandardOps\/IR\/Ops.h\"\n#include \"mlir\/IR\/Attributes.h\"\n#include \"mlir\/IR\/Function.h\"\n#include \"mlir\/IR\/Location.h\"\n#include \"mlir\/IR\/Operation.h\"\n#include \"mlir\/IR\/PatternMatch.h\"\n#include \"mlir\/IR\/StandardTypes.h\"\n#include \"mlir\/IR\/TypeUtilities.h\"\n#include \"mlir\/Pass\/Pass.h\"\n\nusing mlir::DenseIntElementsAttr;\nusing mlir::ElementsAttr;\nusing mlir::failure;\nusing mlir::FunctionPass;\nusing mlir::LogicalResult;\nusing mlir::MLIRContext;\nusing mlir::OpRewritePattern;\nusing mlir::OwningRewritePatternList;\nusing mlir::PassRegistration;\nusing mlir::PassWrapper;\nusing mlir::PatternRewriter;\nusing mlir::RankedTensorType;\nusing mlir::success;\nusing mlir::Value;\n\nnamespace {\n\nValue TransposeReshape(Value arg, mlir::Location loc,\n llvm::ArrayRef left_dims,\n llvm::ArrayRef right_dims,\n llvm::ArrayRef arg_shape,\n PatternRewriter *rewriter) {\n auto element_type = mlir::getElementTypeOrSelf(arg.getType());\n\n int64_t left_size = 1;\n for (auto dim : left_dims) {\n left_size *= arg_shape[dim];\n }\n\n int64_t right_size = 1;\n for (auto dim : right_dims) {\n right_size *= arg_shape[dim];\n }\n\n \/\/ Generate the transpose permutation attribute.\n llvm::SmallVector transpose_permutation(left_dims.begin(),\n left_dims.end());\n transpose_permutation.append(right_dims.begin(), right_dims.end());\n\n mlir::TensorType transpose_permutation_type = RankedTensorType::get(\n {static_cast(transpose_permutation.size())},\n rewriter->getIntegerType(64));\n\n auto transpose_permutation_attr =\n DenseIntElementsAttr::get(transpose_permutation_type,\n llvm::makeArrayRef(transpose_permutation))\n .cast();\n\n \/\/ Compute the resulting shape.\n llvm::SmallVector transposed_shape;\n for (auto val : transpose_permutation) {\n transposed_shape.push_back(arg_shape[val]);\n }\n auto transpose_type = RankedTensorType::get(transposed_shape, element_type);\n auto transpose_result = rewriter->create(\n loc, transpose_type, arg, transpose_permutation_attr);\n\n \/\/ Return the final result.\n auto reshaped_type =\n RankedTensorType::get({left_size, right_size}, element_type);\n return rewriter->create(loc, reshaped_type,\n transpose_result);\n}\n\nValue ProcessDotArg(Value arg, mlir::Location loc,\n ElementsAttr contract_dims_attr, bool outer_dims_first,\n PatternRewriter *rewriter) {\n auto shape = arg.getType().cast().getShape();\n\n llvm::SmallVector is_outer_dim;\n is_outer_dim.resize(shape.size(), true);\n\n \/\/ Compute the contract dimension ordering.\n llvm::SmallVector contract_dims;\n for (auto dim : contract_dims_attr.getValues()) {\n contract_dims.push_back(dim);\n is_outer_dim[dim] = false;\n }\n\n \/\/ Compute the outer dimension orderings.\n llvm::SmallVector outer_dims;\n for (auto it : llvm::enumerate(is_outer_dim)) {\n if (it.value()) {\n outer_dims.push_back(it.index());\n }\n }\n\n if (outer_dims_first) {\n return TransposeReshape(arg, loc, outer_dims, contract_dims, shape,\n rewriter);\n }\n\n return TransposeReshape(arg, loc, contract_dims, outer_dims, shape, rewriter);\n}\n\nstruct GeneralDotConvert : public OpRewritePattern {\n \/\/ Attempts to lower a General Dot operator to a standard Dot operator.\n \/\/ General dots include batching dimensions and can have collapsing\n \/\/ dimensions along any axis. Inserting correctly arrange transpose and\n \/\/ reshape operators organizes the tensors and allows the General Dot to be\n \/\/ replaced with the standard Dot operator.\n \/\/\n \/\/ Note: This requires an empty list of batch dimensions.\n\n explicit GeneralDotConvert(MLIRContext *context)\n : OpRewritePattern(context) {}\n\n LogicalResult matchAndRewrite(mlir::mhlo::DotGeneralOp op,\n PatternRewriter &rewriter) const override {\n auto dot_element_type = mlir::getElementTypeOrSelf(op);\n\n auto dot_numbers = op.dot_dimension_numbers();\n if (dot_numbers.lhs_batching_dimensions().getNumElements() != 0 ||\n dot_numbers.rhs_batching_dimensions().getNumElements() != 0) {\n return failure();\n }\n\n auto lhs = ProcessDotArg(op.lhs(), op.getLoc(),\n dot_numbers.lhs_contracting_dimensions(),\n \/*outer_dims_first=*\/true, &rewriter);\n\n auto rhs = ProcessDotArg(op.rhs(), op.getLoc(),\n dot_numbers.rhs_contracting_dimensions(),\n \/*outer_dims_first=*\/false, &rewriter);\n\n \/\/ Accept only static shaped types.\n auto lhs_shape_type = lhs.getType().dyn_cast_or_null();\n auto rhs_shape_type = rhs.getType().dyn_cast_or_null();\n if (!lhs_shape_type || !rhs_shape_type) return failure();\n if (!lhs_shape_type.hasStaticShape() || !rhs_shape_type.hasStaticShape())\n return failure();\n\n \/\/ Dot resulting shape.\n auto lhs_shape = lhs_shape_type.getShape();\n auto rhs_shape = rhs_shape_type.getShape();\n auto new_dot_type =\n RankedTensorType::get({lhs_shape[0], rhs_shape[1]}, dot_element_type);\n\n auto new_dot_op = rewriter.create(\n op.getLoc(), new_dot_type, lhs, rhs, *(op.precision_config()));\n\n rewriter.replaceOpWithNewOp(op, op.getType(),\n new_dot_op);\n return success();\n }\n};\n\nstruct LegalizeGeneralDotPass\n : public PassWrapper {\n \/\/\/ Lower all general dots that can be represented as a non-batched matmul.\n void runOnFunction() override {\n OwningRewritePatternList patterns;\n mlir::mhlo::PopulateGeneralDotOpLoweringPatterns(&patterns, &getContext());\n applyPatternsAndFoldGreedily(getFunction(), patterns);\n }\n};\n\n} \/\/ namespace\n\nvoid mlir::mhlo::PopulateGeneralDotOpLoweringPatterns(\n OwningRewritePatternList *patterns, MLIRContext *ctx) {\n patterns->insert(ctx);\n}\n\nstd::unique_ptr<::mlir::Pass> mlir::mhlo::createLegalizeGeneralDotPass() {\n return std::make_unique();\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\nclass DownloadsApiTest : public ExtensionApiTest {\n public:\n void SetUpCommandLine(CommandLine* command_line) {\n ExtensionApiTest::SetUpCommandLine(command_line);\n command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);\n }\n};\n\n\/\/ Disabled: see http:\/\/crbug.com\/101170\nIN_PROC_BROWSER_TEST_F(DownloadsApiTest, DISABLED_Downloads) {\n ASSERT_TRUE(StartTestServer());\n ASSERT_TRUE(RunExtensionTest(\"downloads\")) << message_;\n}\nDownloadsApiTest uses a ScopedTempDir to clean up after itself. BUG=101162\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/pref_names.h\"\n\nclass DownloadsApiTest : public ExtensionApiTest {\n public:\n void SetUpCommandLine(CommandLine* command_line) {\n ExtensionApiTest::SetUpCommandLine(command_line);\n command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);\n }\n\n void SetUpTempDownloadsDir() {\n ASSERT_TRUE(tmpdir.CreateUniqueTempDir());\n browser()->profile()->GetPrefs()->SetFilePath(\n prefs::kDownloadDefaultDirectory, tmpdir.path());\n }\n\n private:\n ScopedTempDir tmpdir;\n};\n\nIN_PROC_BROWSER_TEST_F(DownloadsApiTest, Downloads) {\n SetUpTempDownloadsDir();\n ASSERT_TRUE(StartTestServer());\n ASSERT_TRUE(RunExtensionTest(\"downloads\")) << message_;\n}\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2006, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#include \n#include \n#include \n\n#include \"libtorrent\/kademlia\/node_id.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \"libtorrent\/assert.hpp\"\n\nusing boost::bind;\n\nnamespace libtorrent { namespace dht\n{\n\n\/\/ returns the distance between the two nodes\n\/\/ using the kademlia XOR-metric\nnode_id distance(node_id const& n1, node_id const& n2)\n{\n\tnode_id ret;\n\tnode_id::iterator k = ret.begin();\n\tfor (node_id::const_iterator i = n1.begin(), j = n2.begin()\n\t\t, end(n1.end()); i != end; ++i, ++j, ++k)\n\t{\n\t\t*k = *i ^ *j;\n\t}\n\treturn ret;\n}\n\n\/\/ returns true if: distance(n1, ref) < distance(n2, ref)\nbool compare_ref(node_id const& n1, node_id const& n2, node_id const& ref)\n{\n\tfor (node_id::const_iterator i = n1.begin(), j = n2.begin()\n\t\t, k = ref.begin(), end(n1.end()); i != end; ++i, ++j, ++k)\n\t{\n\t\tboost::uint8_t lhs = (*i ^ *k);\n\t\tboost::uint8_t rhs = (*j ^ *k);\n\t\tif (lhs < rhs) return true;\n\t\tif (lhs > rhs) return false;\n\t}\n\treturn false;\n}\n\n\/\/ returns n in: 2^n <= distance(n1, n2) < 2^(n+1)\n\/\/ useful for finding out which bucket a node belongs to\nint distance_exp(node_id const& n1, node_id const& n2)\n{\n\tint byte = node_id::size - 1;\n\tfor (node_id::const_iterator i = n1.begin(), j = n2.begin()\n\t\t, end(n1.end()); i != end; ++i, ++j, --byte)\n\t{\n\t\tTORRENT_ASSERT(byte >= 0);\n\t\tboost::uint8_t t = *i ^ *j;\n\t\tif (t == 0) continue;\n\t\t\/\/ we have found the first non-zero byte\n\t\t\/\/ return the bit-number of the first bit\n\t\t\/\/ that differs\n\t\tint bit = byte * 8;\n\t\tfor (int b = 7; b >= 0; --b)\n\t\t\tif (t >= (1 << b)) return bit + b;\n\t\treturn bit;\n\t}\n\n\treturn 0;\n}\n\nstruct static_ { static_() { std::srand(std::time(0)); } } static__;\n\t\nnode_id generate_id()\n{\n\tchar random[20];\n#ifdef _MSC_VER\n\tstd::generate(random, random + 20, &rand);\n#else\n\tstd::generate(random, random + 20, &std::rand);\n#endif\n\n\thasher h;\n\th.update(random, 20);\n\treturn h.final();\n}\n\n} } \/\/ namespace libtorrent::dht\n\nadded missing include statement\/*\n\nCopyright (c) 2006, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#include \n#include \n#include \n#include \n\n#include \"libtorrent\/kademlia\/node_id.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \"libtorrent\/assert.hpp\"\n\nusing boost::bind;\n\nnamespace libtorrent { namespace dht\n{\n\n\/\/ returns the distance between the two nodes\n\/\/ using the kademlia XOR-metric\nnode_id distance(node_id const& n1, node_id const& n2)\n{\n\tnode_id ret;\n\tnode_id::iterator k = ret.begin();\n\tfor (node_id::const_iterator i = n1.begin(), j = n2.begin()\n\t\t, end(n1.end()); i != end; ++i, ++j, ++k)\n\t{\n\t\t*k = *i ^ *j;\n\t}\n\treturn ret;\n}\n\n\/\/ returns true if: distance(n1, ref) < distance(n2, ref)\nbool compare_ref(node_id const& n1, node_id const& n2, node_id const& ref)\n{\n\tfor (node_id::const_iterator i = n1.begin(), j = n2.begin()\n\t\t, k = ref.begin(), end(n1.end()); i != end; ++i, ++j, ++k)\n\t{\n\t\tboost::uint8_t lhs = (*i ^ *k);\n\t\tboost::uint8_t rhs = (*j ^ *k);\n\t\tif (lhs < rhs) return true;\n\t\tif (lhs > rhs) return false;\n\t}\n\treturn false;\n}\n\n\/\/ returns n in: 2^n <= distance(n1, n2) < 2^(n+1)\n\/\/ useful for finding out which bucket a node belongs to\nint distance_exp(node_id const& n1, node_id const& n2)\n{\n\tint byte = node_id::size - 1;\n\tfor (node_id::const_iterator i = n1.begin(), j = n2.begin()\n\t\t, end(n1.end()); i != end; ++i, ++j, --byte)\n\t{\n\t\tTORRENT_ASSERT(byte >= 0);\n\t\tboost::uint8_t t = *i ^ *j;\n\t\tif (t == 0) continue;\n\t\t\/\/ we have found the first non-zero byte\n\t\t\/\/ return the bit-number of the first bit\n\t\t\/\/ that differs\n\t\tint bit = byte * 8;\n\t\tfor (int b = 7; b >= 0; --b)\n\t\t\tif (t >= (1 << b)) return bit + b;\n\t\treturn bit;\n\t}\n\n\treturn 0;\n}\n\nstruct static_ { static_() { std::srand(std::time(0)); } } static__;\n\t\nnode_id generate_id()\n{\n\tchar random[20];\n#ifdef _MSC_VER\n\tstd::generate(random, random + 20, &rand);\n#else\n\tstd::generate(random, random + 20, &std::rand);\n#endif\n\n\thasher h;\n\th.update(random, 20);\n\treturn h.final();\n}\n\n} } \/\/ namespace libtorrent::dht\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/extensions\/browser_action_test_util.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n#include \"chrome\/browser\/extensions\/user_script_master.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n\nIN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoNoScript) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ Loads a simple extension which attempts to change the title of every page\n \/\/ that loads to \"modified\".\n ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"incognito\").AppendASCII(\"content_scripts\")));\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n Browser* otr_browser = BrowserList::FindBrowserWithType(\n browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n false);\n TabContents* tab = otr_browser->GetSelectedTabContents();\n\n \/\/ Verify the script didn't run.\n bool result = false;\n ui_test_utils::ExecuteJavaScriptAndExtractBool(\n tab->render_view_host(), L\"\",\n L\"window.domAutomationController.send(document.title == 'Unmodified')\",\n &result);\n EXPECT_TRUE(result);\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoYesScript) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ Load a dummy extension. This just tests that we don't regress a\n \/\/ crash fix when multiple incognito- and non-incognito-enabled extensions\n \/\/ are mixed.\n ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"content_scripts\").AppendASCII(\"all_frames\")));\n\n \/\/ Loads a simple extension which attempts to change the title of every page\n \/\/ that loads to \"modified\".\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"incognito\").AppendASCII(\"content_scripts\")));\n\n \/\/ Dummy extension #2.\n ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"content_scripts\").AppendASCII(\"isolated_world1\")));\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n Browser* otr_browser = BrowserList::FindBrowserWithType(\n browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n false);\n TabContents* tab = otr_browser->GetSelectedTabContents();\n\n \/\/ Verify the script ran.\n bool result = false;\n ui_test_utils::ExecuteJavaScriptAndExtractBool(\n tab->render_view_host(), L\"\",\n L\"window.domAutomationController.send(document.title == 'modified')\",\n &result);\n EXPECT_TRUE(result);\n}\n\n\/\/ Tests that the APIs in an incognito-enabled extension work properly.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n ResultCatcher catcher;\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"apis\")));\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ Tests that the APIs in an incognito-enabled split-mode extension work\n\/\/ properly.\n#if defined(OS_CHROMEOS) || defined(OS_LINUX)\n\/\/ Hanging on ChromeOS and linux: http:\/\/crbug.com\/53991\n#define MAYBE_IncognitoSplitMode DISABLED_IncognitoSplitMode\n#else\n#define MAYBE_IncognitoSplitMode IncognitoSplitMode\n#endif\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_IncognitoSplitMode) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ We need 2 ResultCatchers because we'll be running the same test in both\n \/\/ regular and incognito mode.\n ResultCatcher catcher;\n catcher.RestrictToProfile(browser()->profile());\n ResultCatcher catcher_incognito;\n catcher_incognito.RestrictToProfile(\n browser()->profile()->GetOffTheRecordProfile());\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"split\")));\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();\n}\n\n\/\/ Tests that the APIs in an incognito-disabled extension don't see incognito\n\/\/ events or callbacks.\n\/\/ Hangy, http:\/\/crbug.com\/53869.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_IncognitoDisabled) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n ResultCatcher catcher;\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n\n ASSERT_TRUE(LoadExtension(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"apis_disabled\")));\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ Test that opening a popup from an incognito browser window works properly.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n ResultCatcher catcher;\n\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"popup\")));\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n Browser* incognito_browser = BrowserList::FindBrowserWithType(\n browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n false);\n\n \/\/ Simulate the incognito's browser action being clicked.\n BrowserActionTestUtil(incognito_browser).Press(0);\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\nDisable IncognitoSplitMode everywhere, it's failing and hangy. Working on a fix.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/extensions\/browser_action_test_util.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n#include \"chrome\/browser\/extensions\/user_script_master.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n\nIN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoNoScript) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ Loads a simple extension which attempts to change the title of every page\n \/\/ that loads to \"modified\".\n ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"incognito\").AppendASCII(\"content_scripts\")));\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n Browser* otr_browser = BrowserList::FindBrowserWithType(\n browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n false);\n TabContents* tab = otr_browser->GetSelectedTabContents();\n\n \/\/ Verify the script didn't run.\n bool result = false;\n ui_test_utils::ExecuteJavaScriptAndExtractBool(\n tab->render_view_host(), L\"\",\n L\"window.domAutomationController.send(document.title == 'Unmodified')\",\n &result);\n EXPECT_TRUE(result);\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoYesScript) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ Load a dummy extension. This just tests that we don't regress a\n \/\/ crash fix when multiple incognito- and non-incognito-enabled extensions\n \/\/ are mixed.\n ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"content_scripts\").AppendASCII(\"all_frames\")));\n\n \/\/ Loads a simple extension which attempts to change the title of every page\n \/\/ that loads to \"modified\".\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"incognito\").AppendASCII(\"content_scripts\")));\n\n \/\/ Dummy extension #2.\n ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"content_scripts\").AppendASCII(\"isolated_world1\")));\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n Browser* otr_browser = BrowserList::FindBrowserWithType(\n browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n false);\n TabContents* tab = otr_browser->GetSelectedTabContents();\n\n \/\/ Verify the script ran.\n bool result = false;\n ui_test_utils::ExecuteJavaScriptAndExtractBool(\n tab->render_view_host(), L\"\",\n L\"window.domAutomationController.send(document.title == 'modified')\",\n &result);\n EXPECT_TRUE(result);\n}\n\n\/\/ Tests that the APIs in an incognito-enabled extension work properly.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n ResultCatcher catcher;\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"apis\")));\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ Tests that the APIs in an incognito-enabled split-mode extension work\n\/\/ properly.\n\/\/ Hanging\/failing: http:\/\/crbug.com\/53991\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_IncognitoSplitMode) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ We need 2 ResultCatchers because we'll be running the same test in both\n \/\/ regular and incognito mode.\n ResultCatcher catcher;\n catcher.RestrictToProfile(browser()->profile());\n ResultCatcher catcher_incognito;\n catcher_incognito.RestrictToProfile(\n browser()->profile()->GetOffTheRecordProfile());\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"split\")));\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();\n}\n\n\/\/ Tests that the APIs in an incognito-disabled extension don't see incognito\n\/\/ events or callbacks.\n\/\/ Hangy, http:\/\/crbug.com\/53869.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_IncognitoDisabled) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n ResultCatcher catcher;\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n\n ASSERT_TRUE(LoadExtension(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"apis_disabled\")));\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ Test that opening a popup from an incognito browser window works properly.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n ResultCatcher catcher;\n\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"popup\")));\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n Browser* incognito_browser = BrowserList::FindBrowserWithType(\n browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n false);\n\n \/\/ Simulate the incognito's browser action being clicked.\n BrowserActionTestUtil(incognito_browser).Press(0);\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extension_message_service.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/renderer\/extensions\/event_bindings.h\"\n#include \"chrome\/renderer\/extensions\/renderer_extension_bindings.h\"\n#include \"chrome\/test\/render_view_test.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nstatic void DispatchOnConnect(int source_port_id, const std::string& name,\n const std::string& tab_json) {\n ListValue args;\n args.Set(0, Value::CreateIntegerValue(source_port_id));\n args.Set(1, Value::CreateStringValue(name));\n args.Set(2, Value::CreateStringValue(tab_json));\n args.Set(3, Value::CreateStringValue(\"\")); \/\/ extension ID is empty for tests\n args.Set(4, Value::CreateStringValue(\"\")); \/\/ extension ID is empty for tests\n RendererExtensionBindings::Invoke(\n ExtensionMessageService::kDispatchOnConnect, args, NULL, false, GURL());\n}\n\nstatic void DispatchOnDisconnect(int source_port_id) {\n ListValue args;\n args.Set(0, Value::CreateIntegerValue(source_port_id));\n RendererExtensionBindings::Invoke(\n ExtensionMessageService::kDispatchOnDisconnect, args, NULL, false,\n GURL());\n}\n\nstatic void DispatchOnMessage(const std::string& message, int source_port_id) {\n ListValue args;\n args.Set(0, Value::CreateStringValue(message));\n args.Set(1, Value::CreateIntegerValue(source_port_id));\n RendererExtensionBindings::Invoke(\n ExtensionMessageService::kDispatchOnMessage, args, NULL, false, GURL());\n}\n\n\/\/ Tests that the bindings for opening a channel to an extension and sending\n\/\/ and receiving messages through that channel all works.\nTEST_F(RenderViewTest, DISABLED_ExtensionMessagesOpenChannel) {\n render_thread_.sink().ClearMessages();\n LoadHTML(\"<\/body>\");\n ExecuteJavaScript(\n \"var port = chrome.extension.connect({name:'testName'});\"\n \"port.onMessage.addListener(doOnMessage);\"\n \"port.postMessage({message: 'content ready'});\"\n \"function doOnMessage(msg, port) {\"\n \" alert('content got: ' + msg.val);\"\n \"}\");\n\n \/\/ Verify that we opened a channel and sent a message through it.\n const IPC::Message* open_channel_msg =\n render_thread_.sink().GetUniqueMessageMatching(\n ViewHostMsg_OpenChannelToExtension::ID);\n ASSERT_TRUE(open_channel_msg);\n void* iter = IPC::SyncMessage::GetDataIterator(open_channel_msg);\n ViewHostMsg_OpenChannelToExtension::SendParam open_params;\n ASSERT_TRUE(IPC::ReadParam(open_channel_msg, &iter, &open_params));\n EXPECT_EQ(\"testName\", open_params.d);\n\n const IPC::Message* post_msg =\n render_thread_.sink().GetUniqueMessageMatching(\n ViewHostMsg_ExtensionPostMessage::ID);\n ASSERT_TRUE(post_msg);\n ViewHostMsg_ExtensionPostMessage::Param post_params;\n ViewHostMsg_ExtensionPostMessage::Read(post_msg, &post_params);\n EXPECT_EQ(\"{\\\"message\\\":\\\"content ready\\\"}\", post_params.b);\n\n \/\/ Now simulate getting a message back from the other side.\n render_thread_.sink().ClearMessages();\n const int kPortId = 0;\n DispatchOnMessage(\"{\\\"val\\\": 42}\", kPortId);\n\n \/\/ Verify that we got it.\n const IPC::Message* alert_msg =\n render_thread_.sink().GetUniqueMessageMatching(\n ViewHostMsg_RunJavaScriptMessage::ID);\n ASSERT_TRUE(alert_msg);\n iter = IPC::SyncMessage::GetDataIterator(alert_msg);\n ViewHostMsg_RunJavaScriptMessage::SendParam alert_param;\n ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));\n EXPECT_EQ(L\"content got: 42\", alert_param.a);\n}\n\n\/\/ Tests that the bindings for handling a new channel connection and channel\n\/\/ closing all works.\nTEST_F(RenderViewTest, DISABLED_ExtensionMessagesOnConnect) {\n LoadHTML(\"<\/body>\");\n ExecuteJavaScript(\n \"chrome.extension.onConnect.addListener(function (port) {\"\n \" port.test = 24;\"\n \" port.onMessage.addListener(doOnMessage);\"\n \" port.onDisconnect.addListener(doOnDisconnect);\"\n \" port.postMessage({message: 'onconnect from ' + port.tab.url + \"\n \" ' name ' + port.name});\"\n \"});\"\n \"function doOnMessage(msg, port) {\"\n \" alert('got: ' + msg.val);\"\n \"}\"\n \"function doOnDisconnect(port) {\"\n \" alert('disconnected: ' + port.test);\"\n \"}\");\n\n render_thread_.sink().ClearMessages();\n\n \/\/ Simulate a new connection being opened.\n const int kPortId = 0;\n const std::string kPortName = \"testName\";\n DispatchOnConnect(kPortId, kPortName, \"{\\\"url\\\":\\\"foo:\/\/bar\\\"}\");\n\n \/\/ Verify that we handled the new connection by posting a message.\n const IPC::Message* post_msg =\n render_thread_.sink().GetUniqueMessageMatching(\n ViewHostMsg_ExtensionPostMessage::ID);\n ASSERT_TRUE(post_msg);\n ViewHostMsg_ExtensionPostMessage::Param post_params;\n ViewHostMsg_ExtensionPostMessage::Read(post_msg, &post_params);\n std::string expected_msg =\n \"{\\\"message\\\":\\\"onconnect from foo:\/\/bar name \" + kPortName + \"\\\"}\";\n EXPECT_EQ(expected_msg, post_params.b);\n\n \/\/ Now simulate getting a message back from the channel opener.\n render_thread_.sink().ClearMessages();\n DispatchOnMessage(\"{\\\"val\\\": 42}\", kPortId);\n\n \/\/ Verify that we got it.\n const IPC::Message* alert_msg =\n render_thread_.sink().GetUniqueMessageMatching(\n ViewHostMsg_RunJavaScriptMessage::ID);\n ASSERT_TRUE(alert_msg);\n void* iter = IPC::SyncMessage::GetDataIterator(alert_msg);\n ViewHostMsg_RunJavaScriptMessage::SendParam alert_param;\n ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));\n EXPECT_EQ(L\"got: 42\", alert_param.a);\n\n \/\/ Now simulate the channel closing.\n render_thread_.sink().ClearMessages();\n DispatchOnDisconnect(kPortId);\n\n \/\/ Verify that we got it.\n alert_msg =\n render_thread_.sink().GetUniqueMessageMatching(\n ViewHostMsg_RunJavaScriptMessage::ID);\n ASSERT_TRUE(alert_msg);\n iter = IPC::SyncMessage::GetDataIterator(alert_msg);\n ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));\n EXPECT_EQ(L\"disconnected: 24\", alert_param.a);\n}\nIt seems all RenderView tests have issues. I'll try reverting last significant RenderView change and see if that helps.\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extension_message_service.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/renderer\/extensions\/event_bindings.h\"\n#include \"chrome\/renderer\/extensions\/renderer_extension_bindings.h\"\n#include \"chrome\/test\/render_view_test.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nstatic void DispatchOnConnect(int source_port_id, const std::string& name,\n const std::string& tab_json) {\n ListValue args;\n args.Set(0, Value::CreateIntegerValue(source_port_id));\n args.Set(1, Value::CreateStringValue(name));\n args.Set(2, Value::CreateStringValue(tab_json));\n args.Set(3, Value::CreateStringValue(\"\")); \/\/ extension ID is empty for tests\n args.Set(4, Value::CreateStringValue(\"\")); \/\/ extension ID is empty for tests\n RendererExtensionBindings::Invoke(\n ExtensionMessageService::kDispatchOnConnect, args, NULL, false, GURL());\n}\n\nstatic void DispatchOnDisconnect(int source_port_id) {\n ListValue args;\n args.Set(0, Value::CreateIntegerValue(source_port_id));\n RendererExtensionBindings::Invoke(\n ExtensionMessageService::kDispatchOnDisconnect, args, NULL, false,\n GURL());\n}\n\nstatic void DispatchOnMessage(const std::string& message, int source_port_id) {\n ListValue args;\n args.Set(0, Value::CreateStringValue(message));\n args.Set(1, Value::CreateIntegerValue(source_port_id));\n RendererExtensionBindings::Invoke(\n ExtensionMessageService::kDispatchOnMessage, args, NULL, false, GURL());\n}\n\n\/\/ Tests that the bindings for opening a channel to an extension and sending\n\/\/ and receiving messages through that channel all works.\nTEST_F(RenderViewTest, ExtensionMessagesOpenChannel) {\n render_thread_.sink().ClearMessages();\n LoadHTML(\"<\/body>\");\n ExecuteJavaScript(\n \"var port = chrome.extension.connect({name:'testName'});\"\n \"port.onMessage.addListener(doOnMessage);\"\n \"port.postMessage({message: 'content ready'});\"\n \"function doOnMessage(msg, port) {\"\n \" alert('content got: ' + msg.val);\"\n \"}\");\n\n \/\/ Verify that we opened a channel and sent a message through it.\n const IPC::Message* open_channel_msg =\n render_thread_.sink().GetUniqueMessageMatching(\n ViewHostMsg_OpenChannelToExtension::ID);\n ASSERT_TRUE(open_channel_msg);\n void* iter = IPC::SyncMessage::GetDataIterator(open_channel_msg);\n ViewHostMsg_OpenChannelToExtension::SendParam open_params;\n ASSERT_TRUE(IPC::ReadParam(open_channel_msg, &iter, &open_params));\n EXPECT_EQ(\"testName\", open_params.d);\n\n const IPC::Message* post_msg =\n render_thread_.sink().GetUniqueMessageMatching(\n ViewHostMsg_ExtensionPostMessage::ID);\n ASSERT_TRUE(post_msg);\n ViewHostMsg_ExtensionPostMessage::Param post_params;\n ViewHostMsg_ExtensionPostMessage::Read(post_msg, &post_params);\n EXPECT_EQ(\"{\\\"message\\\":\\\"content ready\\\"}\", post_params.b);\n\n \/\/ Now simulate getting a message back from the other side.\n render_thread_.sink().ClearMessages();\n const int kPortId = 0;\n DispatchOnMessage(\"{\\\"val\\\": 42}\", kPortId);\n\n \/\/ Verify that we got it.\n const IPC::Message* alert_msg =\n render_thread_.sink().GetUniqueMessageMatching(\n ViewHostMsg_RunJavaScriptMessage::ID);\n ASSERT_TRUE(alert_msg);\n iter = IPC::SyncMessage::GetDataIterator(alert_msg);\n ViewHostMsg_RunJavaScriptMessage::SendParam alert_param;\n ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));\n EXPECT_EQ(L\"content got: 42\", alert_param.a);\n}\n\n\/\/ Tests that the bindings for handling a new channel connection and channel\n\/\/ closing all works.\nTEST_F(RenderViewTest, ExtensionMessagesOnConnect) {\n LoadHTML(\"<\/body>\");\n ExecuteJavaScript(\n \"chrome.extension.onConnect.addListener(function (port) {\"\n \" port.test = 24;\"\n \" port.onMessage.addListener(doOnMessage);\"\n \" port.onDisconnect.addListener(doOnDisconnect);\"\n \" port.postMessage({message: 'onconnect from ' + port.tab.url + \"\n \" ' name ' + port.name});\"\n \"});\"\n \"function doOnMessage(msg, port) {\"\n \" alert('got: ' + msg.val);\"\n \"}\"\n \"function doOnDisconnect(port) {\"\n \" alert('disconnected: ' + port.test);\"\n \"}\");\n\n render_thread_.sink().ClearMessages();\n\n \/\/ Simulate a new connection being opened.\n const int kPortId = 0;\n const std::string kPortName = \"testName\";\n DispatchOnConnect(kPortId, kPortName, \"{\\\"url\\\":\\\"foo:\/\/bar\\\"}\");\n\n \/\/ Verify that we handled the new connection by posting a message.\n const IPC::Message* post_msg =\n render_thread_.sink().GetUniqueMessageMatching(\n ViewHostMsg_ExtensionPostMessage::ID);\n ASSERT_TRUE(post_msg);\n ViewHostMsg_ExtensionPostMessage::Param post_params;\n ViewHostMsg_ExtensionPostMessage::Read(post_msg, &post_params);\n std::string expected_msg =\n \"{\\\"message\\\":\\\"onconnect from foo:\/\/bar name \" + kPortName + \"\\\"}\";\n EXPECT_EQ(expected_msg, post_params.b);\n\n \/\/ Now simulate getting a message back from the channel opener.\n render_thread_.sink().ClearMessages();\n DispatchOnMessage(\"{\\\"val\\\": 42}\", kPortId);\n\n \/\/ Verify that we got it.\n const IPC::Message* alert_msg =\n render_thread_.sink().GetUniqueMessageMatching(\n ViewHostMsg_RunJavaScriptMessage::ID);\n ASSERT_TRUE(alert_msg);\n void* iter = IPC::SyncMessage::GetDataIterator(alert_msg);\n ViewHostMsg_RunJavaScriptMessage::SendParam alert_param;\n ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));\n EXPECT_EQ(L\"got: 42\", alert_param.a);\n\n \/\/ Now simulate the channel closing.\n render_thread_.sink().ClearMessages();\n DispatchOnDisconnect(kPortId);\n\n \/\/ Verify that we got it.\n alert_msg =\n render_thread_.sink().GetUniqueMessageMatching(\n ViewHostMsg_RunJavaScriptMessage::ID);\n ASSERT_TRUE(alert_msg);\n iter = IPC::SyncMessage::GetDataIterator(alert_msg);\n ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));\n EXPECT_EQ(L\"disconnected: 24\", alert_param.a);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2020 The Google Research Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"test_util.h\"\n\n#include \n#include \n\n#include \"definitions.h\"\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n\nnamespace automl_zero {\n\nusing ::std::function; \/\/ NOLINT;\nusing ::std::pair; \/\/ NOLINT;\nusing ::std::unordered_set; \/\/ NOLINT;\nusing ::testing::Pair;\nusing ::testing::UnorderedElementsAre;\n\nIntegerT cycle_up_to_five() {\n static IntegerT x = 0;\n return x++ % 5;\n}\n\nTEST(IsEventuallyTest, CorrectAnswer) {\n EXPECT_TRUE(IsEventually(\n function(cycle_up_to_five),\n {0, 1, 2, 3, 4}, {0, 1, 2, 3, 4}));\n}\n\nTEST(IsEventuallyTest, DisallowedNumber) {\n EXPECT_FALSE(IsEventually(\n function(cycle_up_to_five),\n {0, 1, 2, 4}, {0, 1, 2, 3, 4}));\n}\n\nTEST(IsEventuallyTest, MissingRequiredNumber) {\n EXPECT_FALSE(IsEventually(\n function(cycle_up_to_five),\n {0, 1, 2, 3, 4}, {0, 1, 2, 3, 4, 5}));\n}\n\nTEST(IsEventuallyTest, NotRequiredNumber) {\n EXPECT_TRUE(IsEventually(\n function(cycle_up_to_five),\n {0, 1, 2, 3, 4}, {0, 1, 2, 4}));\n}\n\nTEST(IsEventuallyTest, MissingAllowedNumber) {\n EXPECT_TRUE(IsEventually(\n function(cycle_up_to_five),\n {0, 1, 2, 3, 4, 5}, {0, 1, 2, 3, 4}));\n}\n\nTEST(IsNeverTest, ExcludedValue) {\n EXPECT_FALSE(IsNever(\n function(cycle_up_to_five),\n {3}, 3.0));\n}\n\nTEST(IsNeverTest, NotExcludedValue) {\n EXPECT_TRUE(IsNever(\n function(cycle_up_to_five),\n {6}, 3.0));\n}\n\nTEST(RangeTest, WorksCorrectly) {\n EXPECT_THAT(Range(0, 5), UnorderedElementsAre(0, 1, 2, 3, 4));\n}\n\nTEST(CartesianProductTest, WorksCorrectly) {\n EXPECT_THAT(CartesianProduct(Range(0, 3),\n Range(3, 5)),\n UnorderedElementsAre(Pair(0, 3), Pair(0, 4),\n Pair(1, 3), Pair(1, 4),\n Pair(2, 3), Pair(2, 4)));\n}\n\n} \/\/ namespace automl_zero\nInternal change\/\/ Copyright 2020 The Google Research Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"test_util.h\"\n\n#include \n#include \n\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n#include \"absl\/container\/node_hash_set.h\"\n#include \"definitions.h\"\n\nnamespace automl_zero {\n\nusing ::std::function; \/\/ NOLINT;\nusing ::std::pair; \/\/ NOLINT;\n\/\/ NOLINT;\nusing ::testing::Pair;\nusing ::testing::UnorderedElementsAre;\n\nIntegerT cycle_up_to_five() {\n static IntegerT x = 0;\n return x++ % 5;\n}\n\nTEST(IsEventuallyTest, CorrectAnswer) {\n EXPECT_TRUE(IsEventually(\n function(cycle_up_to_five),\n {0, 1, 2, 3, 4}, {0, 1, 2, 3, 4}));\n}\n\nTEST(IsEventuallyTest, DisallowedNumber) {\n EXPECT_FALSE(IsEventually(\n function(cycle_up_to_five),\n {0, 1, 2, 4}, {0, 1, 2, 3, 4}));\n}\n\nTEST(IsEventuallyTest, MissingRequiredNumber) {\n EXPECT_FALSE(IsEventually(\n function(cycle_up_to_five),\n {0, 1, 2, 3, 4}, {0, 1, 2, 3, 4, 5}));\n}\n\nTEST(IsEventuallyTest, NotRequiredNumber) {\n EXPECT_TRUE(IsEventually(\n function(cycle_up_to_five),\n {0, 1, 2, 3, 4}, {0, 1, 2, 4}));\n}\n\nTEST(IsEventuallyTest, MissingAllowedNumber) {\n EXPECT_TRUE(IsEventually(\n function(cycle_up_to_five),\n {0, 1, 2, 3, 4, 5}, {0, 1, 2, 3, 4}));\n}\n\nTEST(IsNeverTest, ExcludedValue) {\n EXPECT_FALSE(IsNever(\n function(cycle_up_to_five),\n {3}, 3.0));\n}\n\nTEST(IsNeverTest, NotExcludedValue) {\n EXPECT_TRUE(IsNever(\n function(cycle_up_to_five),\n {6}, 3.0));\n}\n\nTEST(RangeTest, WorksCorrectly) {\n EXPECT_THAT(Range(0, 5), UnorderedElementsAre(0, 1, 2, 3, 4));\n}\n\nTEST(CartesianProductTest, WorksCorrectly) {\n EXPECT_THAT(CartesianProduct(Range(0, 3),\n Range(3, 5)),\n UnorderedElementsAre(Pair(0, 3), Pair(0, 4),\n Pair(1, 3), Pair(1, 4),\n Pair(2, 3), Pair(2, 4)));\n}\n\n} \/\/ namespace automl_zero\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, Toolstrip) {\n ASSERT_TRUE(RunExtensionTest(\"toolstrip\")) << message_;\n}\nTBR: rafaelw,leiz disable a ExtensionApiTest.Toolstrip which is flaky on linux\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n\n\/\/ TODO(rafaelw,erikkay) disabled due to flakiness\n\/\/ BUG=22668 (probably the same bug)\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Toolstrip) {\n ASSERT_TRUE(RunExtensionTest(\"toolstrip\")) << message_;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/path_service.h\"\n#include \"base\/process\/launch.h\"\n#include \"base\/rand_util.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/media\/webrtc_browsertest_base.h\"\n#include \"chrome\/browser\/media\/webrtc_browsertest_common.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_tabstrip.h\"\n#include \"chrome\/browser\/ui\/tabs\/tab_strip_model.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"content\/public\/test\/browser_test_utils.h\"\n#include \"net\/test\/python_utils.h\"\n\n\n\/\/ You need this solution to run this test. The solution will download appengine\n\/\/ and the apprtc code for you.\nconst char kAdviseOnGclientSolution[] =\n \"You need to add this solution to your .gclient to run this test:\\n\"\n \"{\\n\"\n \" \\\"name\\\" : \\\"webrtc.DEPS\\\",\\n\"\n \" \\\"url\\\" : \\\"svn:\/\/svn.chromium.org\/chrome\/trunk\/deps\/\"\n \"third_party\/webrtc\/webrtc.DEPS\\\",\\n\"\n \"}\";\nconst char kTitlePageOfAppEngineAdminPage[] = \"Instances\";\n\n\n\/\/ WebRTC-AppRTC integration test. Requires a real webcam and microphone\n\/\/ on the running system. This test is not meant to run in the main browser\n\/\/ test suite since normal tester machines do not have webcams.\n\/\/\n\/\/ This test will bring up a AppRTC instance on localhost and verify that the\n\/\/ call gets up when connecting to the same room from two tabs in a browser.\nclass WebrtcApprtcBrowserTest : public WebRtcTestBase {\n public:\n virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {\n EXPECT_FALSE(command_line->HasSwitch(\n switches::kUseFakeDeviceForMediaStream));\n EXPECT_FALSE(command_line->HasSwitch(\n switches::kUseFakeUIForMediaStream));\n\n \/\/ The video playback will not work without a GPU, so force its use here.\n command_line->AppendSwitch(switches::kUseGpuInTests);\n }\n\n protected:\n bool LaunchApprtcInstanceOnLocalhost() {\n base::FilePath appengine_dev_appserver =\n GetSourceDir().Append(\n FILE_PATH_LITERAL(\"..\/google_appengine\/dev_appserver.py\"));\n if (!base::PathExists(appengine_dev_appserver)) {\n LOG(ERROR) << \"Missing appengine sdk at \" <<\n appengine_dev_appserver.value() << \". \" << kAdviseOnGclientSolution;\n return false;\n }\n\n base::FilePath apprtc_dir =\n GetSourceDir().Append(\n FILE_PATH_LITERAL(\"third_party\/webrtc_apprtc\/apprtc\"));\n if (!base::PathExists(apprtc_dir)) {\n LOG(ERROR) << \"Missing AppRTC code at \" <<\n apprtc_dir.value() << \". \" << kAdviseOnGclientSolution;\n return false;\n }\n\n CommandLine command_line(CommandLine::NO_PROGRAM);\n EXPECT_TRUE(GetPythonCommand(&command_line));\n\n command_line.AppendArgPath(appengine_dev_appserver);\n command_line.AppendArgPath(apprtc_dir);\n command_line.AppendArg(\"--port=9999\");\n command_line.AppendArg(\"--admin_port=9998\");\n command_line.AppendArg(\"--skip_sdk_update_check\");\n\n LOG(INFO) << \"Running \" << command_line.GetCommandLineString();\n return base::LaunchProcess(command_line, base::LaunchOptions(),\n &dev_appserver_);\n }\n\n bool LocalApprtcInstanceIsUp() {\n \/\/ Load the admin page and see if we manage to load it right.\n ui_test_utils::NavigateToURL(browser(), GURL(\"localhost:9998\"));\n content::WebContents* tab_contents =\n browser()->tab_strip_model()->GetActiveWebContents();\n std::string javascript =\n \"window.domAutomationController.send(document.title)\";\n std::string result;\n if (!content::ExecuteScriptAndExtractString(tab_contents, javascript,\n &result))\n return false;\n\n return result == kTitlePageOfAppEngineAdminPage;\n }\n\n bool StopApprtcInstance() {\n return base::KillProcess(dev_appserver_, 0, false);\n }\n\n bool WaitForCallToComeUp(content::WebContents* tab_contents) {\n \/\/ Apprtc will set remoteVideo.style.opacity to 1 when the call comes up.\n std::string javascript =\n \"window.domAutomationController.send(remoteVideo.style.opacity)\";\n return PollingWaitUntil(javascript, \"1\", tab_contents);\n }\n\n base::FilePath GetSourceDir() {\n base::FilePath source_dir;\n PathService::Get(base::DIR_SOURCE_ROOT, &source_dir);\n return source_dir;\n }\n\n private:\n base::ProcessHandle dev_appserver_;\n};\n\n#if defined (OS_WIN) || defined(OS_MACOSX)\n#define MAYBE_MANUAL_WorksOnApprtc DISABLED_MANUAL_WorksOnApprtc\n#else\n#define MAYBE_MANUAL_WorksOnApprtc MANUAL_WorksOnApprtc\n#endif\n\nIN_PROC_BROWSER_TEST_F(WebrtcApprtcBrowserTest, MAYBE_MANUAL_WorksOnApprtc) {\n if (!LaunchApprtcInstanceOnLocalhost()) {\n \/\/ TODO(phoglund): assert on this once everything is in place on the bots.\n return;\n }\n while (!LocalApprtcInstanceIsUp())\n LOG(INFO) << \"Waiting for AppRTC to come up...\";\n\n GURL room_url = GURL(base::StringPrintf(\"localhost:9999?r=room_%d\",\n base::RandInt(0, 65536)));\n\n chrome::AddBlankTabAt(browser(), -1, true);\n content::WebContents* left_tab = OpenPageAndAcceptUserMedia(room_url);\n chrome::AddBlankTabAt(browser(), -1, true);\n content::WebContents* right_tab = OpenPageAndAcceptUserMedia(room_url);\n\n ASSERT_TRUE(WaitForCallToComeUp(left_tab));\n ASSERT_TRUE(WaitForCallToComeUp(right_tab));\n\n ASSERT_TRUE(StopApprtcInstance());\n}\nNow looking at AppRTC from the out\/ directory.\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/path_service.h\"\n#include \"base\/process\/launch.h\"\n#include \"base\/rand_util.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/media\/webrtc_browsertest_base.h\"\n#include \"chrome\/browser\/media\/webrtc_browsertest_common.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_tabstrip.h\"\n#include \"chrome\/browser\/ui\/tabs\/tab_strip_model.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"content\/public\/test\/browser_test_utils.h\"\n#include \"net\/test\/python_utils.h\"\n\n\n\/\/ You need this solution to run this test. The solution will download appengine\n\/\/ and the apprtc code for you.\nconst char kAdviseOnGclientSolution[] =\n \"You need to add this solution to your .gclient to run this test:\\n\"\n \"{\\n\"\n \" \\\"name\\\" : \\\"webrtc.DEPS\\\",\\n\"\n \" \\\"url\\\" : \\\"svn:\/\/svn.chromium.org\/chrome\/trunk\/deps\/\"\n \"third_party\/webrtc\/webrtc.DEPS\\\",\\n\"\n \"}\";\nconst char kTitlePageOfAppEngineAdminPage[] = \"Instances\";\n\n\n\/\/ WebRTC-AppRTC integration test. Requires a real webcam and microphone\n\/\/ on the running system. This test is not meant to run in the main browser\n\/\/ test suite since normal tester machines do not have webcams.\n\/\/\n\/\/ This test will bring up a AppRTC instance on localhost and verify that the\n\/\/ call gets up when connecting to the same room from two tabs in a browser.\nclass WebrtcApprtcBrowserTest : public WebRtcTestBase {\n public:\n virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {\n EXPECT_FALSE(command_line->HasSwitch(\n switches::kUseFakeDeviceForMediaStream));\n EXPECT_FALSE(command_line->HasSwitch(\n switches::kUseFakeUIForMediaStream));\n\n \/\/ The video playback will not work without a GPU, so force its use here.\n command_line->AppendSwitch(switches::kUseGpuInTests);\n }\n\n protected:\n bool LaunchApprtcInstanceOnLocalhost() {\n base::FilePath appengine_dev_appserver =\n GetSourceDir().Append(\n FILE_PATH_LITERAL(\"..\/google_appengine\/dev_appserver.py\"));\n if (!base::PathExists(appengine_dev_appserver)) {\n LOG(ERROR) << \"Missing appengine sdk at \" <<\n appengine_dev_appserver.value() << \". \" << kAdviseOnGclientSolution;\n return false;\n }\n\n base::FilePath apprtc_dir =\n GetSourceDir().Append(FILE_PATH_LITERAL(\"out\/apprtc\"));\n if (!base::PathExists(apprtc_dir)) {\n LOG(ERROR) << \"Missing AppRTC code at \" <<\n apprtc_dir.value() << \". \" << kAdviseOnGclientSolution;\n return false;\n }\n\n CommandLine command_line(CommandLine::NO_PROGRAM);\n EXPECT_TRUE(GetPythonCommand(&command_line));\n\n command_line.AppendArgPath(appengine_dev_appserver);\n command_line.AppendArgPath(apprtc_dir);\n command_line.AppendArg(\"--port=9999\");\n command_line.AppendArg(\"--admin_port=9998\");\n command_line.AppendArg(\"--skip_sdk_update_check\");\n\n LOG(INFO) << \"Running \" << command_line.GetCommandLineString();\n return base::LaunchProcess(command_line, base::LaunchOptions(),\n &dev_appserver_);\n }\n\n bool LocalApprtcInstanceIsUp() {\n \/\/ Load the admin page and see if we manage to load it right.\n ui_test_utils::NavigateToURL(browser(), GURL(\"localhost:9998\"));\n content::WebContents* tab_contents =\n browser()->tab_strip_model()->GetActiveWebContents();\n std::string javascript =\n \"window.domAutomationController.send(document.title)\";\n std::string result;\n if (!content::ExecuteScriptAndExtractString(tab_contents, javascript,\n &result))\n return false;\n\n return result == kTitlePageOfAppEngineAdminPage;\n }\n\n bool StopApprtcInstance() {\n return base::KillProcess(dev_appserver_, 0, false);\n }\n\n bool WaitForCallToComeUp(content::WebContents* tab_contents) {\n \/\/ Apprtc will set remoteVideo.style.opacity to 1 when the call comes up.\n std::string javascript =\n \"window.domAutomationController.send(remoteVideo.style.opacity)\";\n return PollingWaitUntil(javascript, \"1\", tab_contents);\n }\n\n base::FilePath GetSourceDir() {\n base::FilePath source_dir;\n PathService::Get(base::DIR_SOURCE_ROOT, &source_dir);\n return source_dir;\n }\n\n private:\n base::ProcessHandle dev_appserver_;\n};\n\n#if defined (OS_WIN) || defined(OS_MACOSX)\n#define MAYBE_MANUAL_WorksOnApprtc DISABLED_MANUAL_WorksOnApprtc\n#else\n#define MAYBE_MANUAL_WorksOnApprtc MANUAL_WorksOnApprtc\n#endif\n\nIN_PROC_BROWSER_TEST_F(WebrtcApprtcBrowserTest, MAYBE_MANUAL_WorksOnApprtc) {\n ASSERT_TRUE(LaunchApprtcInstanceOnLocalhost());\n while (!LocalApprtcInstanceIsUp())\n LOG(INFO) << \"Waiting for AppRTC to come up...\";\n\n GURL room_url = GURL(base::StringPrintf(\"localhost:9999?r=room_%d\",\n base::RandInt(0, 65536)));\n\n chrome::AddBlankTabAt(browser(), -1, true);\n content::WebContents* left_tab = OpenPageAndAcceptUserMedia(room_url);\n chrome::AddBlankTabAt(browser(), -1, true);\n content::WebContents* right_tab = OpenPageAndAcceptUserMedia(room_url);\n\n ASSERT_TRUE(WaitForCallToComeUp(left_tab));\n ASSERT_TRUE(WaitForCallToComeUp(right_tab));\n\n ASSERT_TRUE(StopApprtcInstance());\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: toolbar.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: os $ $Date: 2002-05-07 13:49:06 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _BIB_TOOLBAR_HXX\n#define _BIB_TOOLBAR_HXX\n\n#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_\n#include \n#endif\n\n\n\n#ifndef _SV_TOOLBOX_HXX \/\/autogen wg. ToolBox\n#include \n#endif\n\n#ifndef _SV_LSTBOX_HXX \/\/autogen wg. ::com::sun::star::form\n#include \n#endif\n\n#ifndef _SV_EDIT_HXX \/\/autogen wg. Edit\n#include \n#endif\n\n#ifndef _SV_FIXED_HXX \/\/autogen wg. FixedText\n#include \n#endif\n\n#ifndef _SVARRAY_HXX\n#include \n#endif\n\n#ifndef _SV_TIMER_HXX \/\/autogen wg. Timer\n#include \n#endif\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include \/\/ helper for implementations\n#endif\n\nclass BibDataManager;\nclass BibToolBar;\n\nclass BibToolBarListener: public cppu::WeakImplHelper1 < ::com::sun::star::frame::XStatusListener>\n{\nprivate:\n\n sal_uInt16 nIndex;\n rtl::OUString aCommand;\n\nprotected:\n\n BibToolBar *pToolBar;\n\npublic:\n\n BibToolBarListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId);\n ~BibToolBarListener();\n\n rtl::OUString GetCommand();\n void SetCommand(const rtl::OUString& aStr);\n\n sal_uInt16 GetIndex();\n void SetIndex(sal_uInt16 nIndex);\n\n \/\/ ::com::sun::star::lang::XEventListener\n \/\/ we do not hold References to dispatches, so there is nothing to do on disposal\n virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source)\n throw( ::com::sun::star::uno::RuntimeException ){};\n\n \/\/ ::com::sun::star::frame::XStatusListener\n virtual void SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event)\n throw( ::com::sun::star::uno::RuntimeException );\n\n};\n\nclass BibTBListBoxListener: public BibToolBarListener\n{\npublic:\n\n BibTBListBoxListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId);\n ~BibTBListBoxListener();\n\n virtual void SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event)\n throw( ::com::sun::star::uno::RuntimeException );\n\n};\n\nclass BibTBEditListener: public BibToolBarListener\n{\npublic:\n\n BibTBEditListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId);\n ~BibTBEditListener();\n\n virtual void SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event)\n throw( ::com::sun::star::uno::RuntimeException );\n\n};\n\nclass BibTBQueryMenuListener: public BibToolBarListener\n{\npublic:\n\n BibTBQueryMenuListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId);\n ~BibTBQueryMenuListener();\n\n virtual void SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event)\n throw( ::com::sun::star::uno::RuntimeException );\n\n};\n\n\ntypedef ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener>* BibToolBarListenerPtr;\nSV_DECL_PTRARR_DEL( BibToolBarListenerArr, BibToolBarListenerPtr, 4, 4 );\n\nclass BibToolBar: public ToolBox\n{\n private:\n\n BibToolBarListenerArr aListenerArr;\n ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController > xController;\n Timer aTimer;\n Timer aMenuTimer;\n ImageList aImgLst;\n ImageList aImgLstHC;\n FixedText aFtSource;\n ListBox aLBSource;\n FixedText aFtQuery;\n Edit aEdQuery;\n PopupMenu aPopupMenu;\n sal_uInt16 nMenuId;\n sal_uInt16 nSelMenuItem;\n rtl::OUString aQueryField;\n\n BibDataManager* pDatMan;\n DECL_LINK( SelHdl, ListBox* );\n DECL_LINK( SendSelHdl, Timer* );\n DECL_LINK( MenuHdl, Timer* );\n\n void ApplyImageList();\n protected:\n\n void DataChanged( const DataChangedEvent& rDCEvt );\n void InitListener();\n virtual void Select();\n virtual void Click();\n void SendDispatch(sal_uInt16 nId, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rArgs);\n long PreNotify( NotifyEvent& rNEvt );\n\n\n public:\n\n BibToolBar(Window* pParent, WinBits nStyle = WB_3DLOOK );\n ~BibToolBar();\n\n void SetXController(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController > &);\n\n void ClearSourceList();\n void UpdateSourceList(sal_Bool bFlag=sal_True);\n void EnableSourceList(sal_Bool bFlag=sal_True);\n void InsertSourceEntry(const XubString&,sal_uInt16 nPos=LISTBOX_APPEND );\n void SelectSourceEntry(const XubString& );\n\n void EnableQuery(sal_Bool bFlag=sal_True);\n void SetQueryString(const XubString& );\n\n void ClearFilterMenu();\n sal_uInt16 InsertFilterItem(const XubString& );\n void SelectFilterItem(sal_uInt16 nId);\n\n void statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event)\n throw( ::com::sun::star::uno::RuntimeException );\n\n void SetDatMan(BibDataManager& rDatMan) {pDatMan = &rDatMan;}\n};\n\n\n\n\n#endif\nINTEGRATION: CWS os8 (1.5.70); FILE MERGED 2003\/04\/03 06:39:23 cd 1.5.70.1: #108520# Support automatic toolbar button size depending on menu text height\/*************************************************************************\n *\n * $RCSfile: toolbar.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: vg $ $Date: 2003-04-17 16:13:03 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _BIB_TOOLBAR_HXX\n#define _BIB_TOOLBAR_HXX\n\n#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_\n#include \n#endif\n\n\n\n#ifndef _SV_TOOLBOX_HXX \/\/autogen wg. ToolBox\n#include \n#endif\n\n#ifndef _SV_LSTBOX_HXX \/\/autogen wg. ::com::sun::star::form\n#include \n#endif\n\n#ifndef _SV_EDIT_HXX \/\/autogen wg. Edit\n#include \n#endif\n\n#ifndef _SV_FIXED_HXX \/\/autogen wg. FixedText\n#include \n#endif\n\n#ifndef _SVARRAY_HXX\n#include \n#endif\n\n#ifndef _SV_TIMER_HXX \/\/autogen wg. Timer\n#include \n#endif\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include \/\/ helper for implementations\n#endif\n\nclass BibDataManager;\nclass BibToolBar;\n\nclass BibToolBarListener: public cppu::WeakImplHelper1 < ::com::sun::star::frame::XStatusListener>\n{\nprivate:\n\n sal_uInt16 nIndex;\n rtl::OUString aCommand;\n\nprotected:\n\n BibToolBar *pToolBar;\n\npublic:\n\n BibToolBarListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId);\n ~BibToolBarListener();\n\n rtl::OUString GetCommand();\n void SetCommand(const rtl::OUString& aStr);\n\n sal_uInt16 GetIndex();\n void SetIndex(sal_uInt16 nIndex);\n\n \/\/ ::com::sun::star::lang::XEventListener\n \/\/ we do not hold References to dispatches, so there is nothing to do on disposal\n virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source)\n throw( ::com::sun::star::uno::RuntimeException ){};\n\n \/\/ ::com::sun::star::frame::XStatusListener\n virtual void SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event)\n throw( ::com::sun::star::uno::RuntimeException );\n\n};\n\nclass BibTBListBoxListener: public BibToolBarListener\n{\npublic:\n\n BibTBListBoxListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId);\n ~BibTBListBoxListener();\n\n virtual void SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event)\n throw( ::com::sun::star::uno::RuntimeException );\n\n};\n\nclass BibTBEditListener: public BibToolBarListener\n{\npublic:\n\n BibTBEditListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId);\n ~BibTBEditListener();\n\n virtual void SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event)\n throw( ::com::sun::star::uno::RuntimeException );\n\n};\n\nclass BibTBQueryMenuListener: public BibToolBarListener\n{\npublic:\n\n BibTBQueryMenuListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId);\n ~BibTBQueryMenuListener();\n\n virtual void SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event)\n throw( ::com::sun::star::uno::RuntimeException );\n\n};\n\n\ntypedef ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener>* BibToolBarListenerPtr;\nSV_DECL_PTRARR_DEL( BibToolBarListenerArr, BibToolBarListenerPtr, 4, 4 );\n\nclass BibToolBar: public ToolBox\n{\n private:\n\n BibToolBarListenerArr aListenerArr;\n ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController > xController;\n Timer aTimer;\n Timer aMenuTimer;\n ImageList aImgLst;\n ImageList aImgLstHC;\n ImageList aBigImgLst;\n ImageList aBigImgLstHC;\n FixedText aFtSource;\n ListBox aLBSource;\n FixedText aFtQuery;\n Edit aEdQuery;\n PopupMenu aPopupMenu;\n sal_uInt16 nMenuId;\n sal_uInt16 nSelMenuItem;\n rtl::OUString aQueryField;\n Link aLayoutManager;\n sal_Int16 nSymbolSet;\n sal_Int16 nOutStyle;\n\n BibDataManager* pDatMan;\n DECL_LINK( SelHdl, ListBox* );\n DECL_LINK( SendSelHdl, Timer* );\n DECL_LINK( MenuHdl, Timer* );\n DECL_LINK( OptionsChanged_Impl, void* );\n DECL_LINK( SettingsChanged_Impl, void* );\n\n void ApplyImageList();\n void RebuildToolbar();\n\n protected:\n\n void DataChanged( const DataChangedEvent& rDCEvt );\n void InitListener();\n virtual void Select();\n virtual void Click();\n void SendDispatch(sal_uInt16 nId, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rArgs);\n long PreNotify( NotifyEvent& rNEvt );\n sal_Int16 GetCurrentSymbolSet();\n\n\n public:\n\n BibToolBar(Window* pParent, Link aLink, WinBits nStyle = WB_3DLOOK );\n ~BibToolBar();\n\n void SetXController(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController > &);\n\n void ClearSourceList();\n void UpdateSourceList(sal_Bool bFlag=sal_True);\n void EnableSourceList(sal_Bool bFlag=sal_True);\n void InsertSourceEntry(const XubString&,sal_uInt16 nPos=LISTBOX_APPEND );\n void SelectSourceEntry(const XubString& );\n\n void EnableQuery(sal_Bool bFlag=sal_True);\n void SetQueryString(const XubString& );\n void AdjustToolBox();\n\n void ClearFilterMenu();\n sal_uInt16 InsertFilterItem(const XubString& );\n void SelectFilterItem(sal_uInt16 nId);\n\n void statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event)\n throw( ::com::sun::star::uno::RuntimeException );\n\n void SetDatMan(BibDataManager& rDatMan) {pDatMan = &rDatMan;}\n};\n\n\n\n\n#endif\n<|endoftext|>"} {"text":"\/*******************************************************************************\n * This file is part of \"Patrick's Programming Library\", Version 7 (PPL7).\n * Web: http:\/\/www.pfp.de\/ppl\/\n *\n * $Author$\n * $Revision$\n * $Date$\n * $Id$\n *\n *******************************************************************************\n * Copyright (c) 2013, Patrick Fedick \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n * THE POSSIBILITY OF SUCH DAMAGE.\n *******************************************************************************\/\n\n#include \"prolog.h\"\n#ifdef HAVE_STDIO_H\n#include \n#endif\n#ifdef HAVE_STDLIB_H\n#include \n#endif\n#ifdef HAVE_STRING_H\n#include \n#endif\n#ifdef HAVE_MATH_H\n#include \n#endif\n\n#include \"ppl7.h\"\n#include \"ppl7-grafix.h\"\n\n\n#ifdef HAVE_FREETYPE2\n#include \n#include FT_FREETYPE_H\n#endif\n\n\n\/\/#undef HAVE_X86_ASSEMBLER\n\n\/\/ Font-Blitter\ntypedef struct tagGLYPH {\n\tconst char *data;\n\tchar *target;\n\tppluint32 pitch;\n\tpplint32 color;\n} GLYPH;\n\nextern \"C\" {\n\tint BltGlyph_M8_32 (GLYPH *g);\n\tint BltGlyph_M1_32 (GLYPH *g);\n\tint BltGlyph_AA8_32 (GLYPH *g);\n\tint BltGlyph_AA2_32 (GLYPH *g);\n\tint BltGlyph_AA4_32 (GLYPH *g);\n}\n\nnamespace ppl7 {\nnamespace grafix {\n\n\/*!\\class FontEngineFreeType\n * \\ingroup PPLGroupGrafik\n * \\brief Font-Engine für von FreeType unterstützte Fonts\n *\n * Diese Engine unterstützt TrueType, OpenType, Type1 und weitere von der Freetype-Library\n * unterstützte Formate.\n *\n * \\see\n * http:\/\/www.freetype.org\/\n *\/\n\n\n#ifdef HAVE_FREETYPE2\ntypedef struct tagFreeTypeEngineData {\n\tFT_Library\tftlib;\n} FREETYPE_ENGINE_DATA;\n\ntypedef struct tagFreeTypeFaceData {\n\tFT_Byte *buffer;\n\tFT_Face\tface;\n\tint\t\tkerning;\n} FREETYPE_FACE_DATA;\n#endif\n\nFontEngineFreeType::FontEngineFreeType()\n{\n\tft=NULL;\n#ifdef HAVE_FREETYPE2\n#endif\n}\n\nFontEngineFreeType::~FontEngineFreeType()\n{\n#ifdef HAVE_FREETYPE2\n\tFREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA*)ft;\n\tif (f) {\n\t\tFT_Done_FreeType(f->ftlib);\n\t\tfree(f);\n\t}\n#endif\n}\n\nString FontEngineFreeType::name() const\n{\n\treturn \"FontEngineFreeType\";\n}\n\nString FontEngineFreeType::description() const\n{\n\treturn \"Rendering of TrueType and OpenType fonts\";\n}\n\n\nvoid FontEngineFreeType::init()\n{\n#ifndef HAVE_FREETYPE2\n\tthrow UnsupportedFeatureException(\"Freetype2\");\n#else\n\tif (ft) return;\n\tFREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA *)malloc(sizeof(FREETYPE_ENGINE_DATA));\n\tif (!f) throw OutOfMemoryException();\n\tint error=FT_Init_FreeType(&f->ftlib );\n\tif (error) {\n\t\tfree(f);\n\t\tthrow FontEngineInitializationException();\n\t}\n\tft=f;\n#endif\n}\n\nint FontEngineFreeType::ident(FileObject &file) throw()\n{\n#ifndef HAVE_FREETYPE2\n\treturn 0;\n#else\n\tFREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA*)ft;\n\tif (!f) return 0;\n\tconst FT_Byte *buffer=(const FT_Byte *)file.map();\n\tsize_t size=file.size();\n\tFT_Face face;\n\tint error = FT_New_Memory_Face(f->ftlib, buffer, (FT_Long)size, 0, &face );\n\tif (error!=0) return 0;\n\tFT_Done_Face(face);\n\treturn 1;\n#endif\n}\n\nFontFile *FontEngineFreeType::loadFont(FileObject &file, const String &fontname)\n{\n#ifndef HAVE_FREETYPE2\n\tthrow UnsupportedFeatureException(\"Freetype2\");\n#else\n\tFREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA*)ft;\n\tif (!f) throw FontEngineUninitializedException();\n\tFREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)malloc(sizeof(FREETYPE_FACE_DATA));\n\tif (!face) throw OutOfMemoryException();\n\tface->buffer=(FT_Byte *)file.load();\n\tsize_t size=file.size();\n\tint error = FT_New_Memory_Face(f->ftlib, face->buffer, (FT_Long)size, 0, &face->face );\n\tif (error!=0) {\n\t\tfree(face->buffer);\n\t\tfree(face);\n\t\tif (error!=0) throw InvalidFontException();\n\t}\n\tString name=fontname;\n\tif (name.isEmpty()) name.set(face->face->family_name);\n\tface->kerning=(int)FT_HAS_KERNING(face->face);\t\t\/\/ Kerning unterstützt?\n\tFontFile *ff=new FontFile;\n\tff->Name=fontname;\n\tff->engine=this;\n\tff->priv=face;\n\treturn ff;\n#endif\n}\n\nvoid FontEngineFreeType::deleteFont(FontFile *file)\n{\n#ifndef HAVE_FREETYPE2\n\tthrow UnsupportedFeatureException(\"Freetype2\");\n#else\n\tif (!file) throw NullPointerException();\n\tif (file->engine!=this) throw InvalidFontEngineException();\n\tFREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)file->priv;\n\tif (face) {\n\t\tFT_Done_Face(face->face);\n\t\tfree(face->buffer);\n\t\tfree(face);\n\t\tfile->priv=NULL;\n\t}\n\tfile->engine=NULL;\n#endif\n}\n\n\n#ifdef HAVE_FREETYPE2\nstatic void renderGlyphAA(Drawable &draw, FT_Bitmap *bitmap, int x, int y, const Color &color)\n{\n\tppluint8 v=0;\n\tppluint8 *glyph=(ppluint8 *)bitmap->buffer;\n\tfor (unsigned int gy=0;gyrows;gy++) {\n\t\tfor (unsigned int gx=0;gxwidth;gx++) {\n\t\t\tv=glyph[gx];\n\t\t\tif (v>0) {\n\t\t\t\tdraw.blendPixel(x+gx,y+gy,color,v);\n\t\t\t}\n\t\t}\n\t\tglyph+=bitmap->pitch;\n\t}\n}\n\nstatic void renderGlyphMono(Drawable &draw, FT_Bitmap *bitmap, int x, int y, const Color &color)\n{\n\tppluint8 v=0;\n\tppluint8 *glyph=(ppluint8 *)bitmap->buffer;\n\tfor (unsigned int gy=0;gyrows;gy++) {\n\t\tppluint8 bitcount=0;\n\t\tppluint8 bytecount=0;\n\t\tfor (unsigned int gx=0;gxwidth;gx++) {\n\t\t\tif (!bitcount) {\n\t\t\t\tv=glyph[bytecount];\n\t\t\t\tbitcount=8;\n\t\t\t\tbytecount++;\n\t\t\t}\n\t\t\tif(v&128) {\n\t\t\t\tdraw.putPixel(x+gx,y+gy,color);\n\t\t\t}\n\t\t\tv=v<<1;\n\t\t\tbitcount--;\n\t\t}\n\t\tglyph+=bitmap->pitch;\n\t}\n}\n\n#endif\n\nvoid FontEngineFreeType::render(const FontFile &file, const Font &font, Drawable &draw, int x, int y, const WideString &text, const Color &color)\n{\n#ifndef HAVE_FREETYPE2\n\tthrow UnsupportedFeatureException(\"Freetype2\");\n#else\n\tif (file.priv==NULL) throw InvalidFontException();\n\tFREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)file.priv;\n\tint error=FT_Set_Pixel_Sizes(face->face,0,font.size()+2);\n\tif (error!=0) throw InvalidFontException();\n\n\tint orgx=x<<6;\n\tint orgy=y<<6;\n\tint lastx=orgx;\n\tbool rotate=false;\n\tFT_Matrix matrix; \/* transformation matrix *\/\n\tif (font.rotation()!=0.0) {\n\t\trotate=true;\n\t\tdouble angle=font.rotation()*3.14159265359\/180.0;\n\t\t\/* set up matrix *\/\n\t\tmatrix.xx = (FT_Fixed)( cos( angle ) * 0x10000L );\n\t\tmatrix.xy = (FT_Fixed)( sin( angle ) * 0x10000L );\n\t\tmatrix.yx = (FT_Fixed)( -sin( angle ) * 0x10000L );\n\t\tmatrix.yy = (FT_Fixed)( cos( angle ) * 0x10000L );\n\t\tFT_Set_Transform( face->face, &matrix, NULL );\n\t} else {\n\t\tFT_Set_Transform( face->face, NULL, NULL );\n\t}\n\n\tFT_GlyphSlot slot=face->face->glyph;\n\tFT_UInt\t\t\tglyph_index, last_glyph=0;\n\tFT_Vector\t\tkerning;\n\tkerning.x=0;\n\tkerning.y=0;\n\n\tsize_t p=0;\n\tsize_t textlen=text.len();\n\n\twhile (pface,code);\n\t\t\tif (!glyph_index) continue;\n\t\t\t\/\/ Antialiasing\n\t\t\tif (font.antialias()) {\n\t\t\t\terror=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_RENDER|FT_LOAD_TARGET_NORMAL);\n\t\t\t} else {\n\t\t\t\terror=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_TARGET_MONO|FT_LOAD_RENDER);\n\t\t\t}\n\t\t\tif (error!=0) continue;\n\t\t\t\/\/x=x+(slot->bitmap_left<<6);\n\t\t\t\/\/y=y-(slot->bitmap_top<<6);\n\t\t\tif (face->kerning>0 && last_glyph>0 && rotate==false) {\n\t\t\t\tFT_Get_Kerning(face->face,last_glyph,glyph_index,FT_KERNING_DEFAULT,&kerning);\n\t\t\t\tx+=kerning.x;\n\t\t\t\ty+=kerning.y;\n\t\t\t}\n\n\t\t\tif (font.antialias()) {\n\t\t\t\trenderGlyphAA(draw,&slot->bitmap,(x>>6)+slot->bitmap_left,\n\t\t\t\t\t\t(y>>6)-slot->bitmap_top,color);\n\t\t\t} else {\n\t\t\t\trenderGlyphMono(draw,&slot->bitmap,(x>>6)+slot->bitmap_left,\n\t\t\t\t\t\t(y>>6)-slot->bitmap_top,color);\n\t\t\t}\n\t\t\tif (font.drawUnderline()) {\n\n\t\t\t}\n\t\t\tlastx=x+slot->advance.x;\n\t\t\torgy-=slot->advance.y;\n\t\t\tlast_glyph=glyph_index;\n\t\t}\n\t}\n#endif\n}\n\nSize FontEngineFreeType::measure(const FontFile &file, const Font &font, const WideString &text)\n{\n\tSize s;\n#ifndef HAVE_FREETYPE2\n\tthrow UnsupportedFeatureException(\"Freetype2\");\n#else\n\tif (file.priv==NULL) throw InvalidFontException();\n\tFREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)file.priv;\n\tint error=FT_Set_Pixel_Sizes(face->face,0,font.size()+2);\n\tif (error!=0) throw InvalidFontException();\n\n\tFT_Set_Transform( face->face, NULL, NULL );\n\n\tint width=0,height=0;\n\n\tFT_GlyphSlot slot=face->face->glyph;\n\tFT_UInt\t\t\tglyph_index, last_glyph=0;\n\tFT_Vector\t\tkerning;\n\tkerning.x=0;\n\tkerning.y=0;\n\tsize_t p=0;\n\tsize_t textlen=text.len();\n\twhile (pface,code);\n\t\t\tif (!glyph_index) continue;\n\t\t\t\/\/ Antialiasing\n\t\t\tif (font.antialias()) {\n\t\t\t\terror=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_RENDER|FT_LOAD_TARGET_NORMAL);\n\t\t\t} else {\n\t\t\t\terror=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_TARGET_MONO|FT_LOAD_RENDER);\n\t\t\t}\n\t\t\tif (error!=0) continue;\n\t\t\t\/\/x=x+slot->bitmap_left;\n\t\t\t\/\/y=y-slot->bitmap_top;\n\t\t\tif (face->kerning>0 && last_glyph>0) {\n\t\t\t\terror=FT_Get_Kerning(face->face,last_glyph,glyph_index,FT_KERNING_DEFAULT,&kerning);\n\t\t\t\twidth+=kerning.x;\n\t\t\t}\n\t\t\twidth+=(slot->advance.x);\n\t\t\tif (width>s.width) s.width=width;\n\t\t\tlast_glyph=glyph_index;\n\t\t}\n\t}\n\ts.setHeight(height+font.size()+2);\n\ts.width=s.width>>6;\n\treturn s;\n#endif\n}\n\n\n} \/\/ EOF namespace grafix\n} \/\/ EOF namespace ppl7\n\nputPixel überarbeitet\/*******************************************************************************\n * This file is part of \"Patrick's Programming Library\", Version 7 (PPL7).\n * Web: http:\/\/www.pfp.de\/ppl\/\n *\n * $Author$\n * $Revision$\n * $Date$\n * $Id$\n *\n *******************************************************************************\n * Copyright (c) 2013, Patrick Fedick \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n * THE POSSIBILITY OF SUCH DAMAGE.\n *******************************************************************************\/\n\n#include \"prolog.h\"\n#ifdef HAVE_STDIO_H\n#include \n#endif\n#ifdef HAVE_STDLIB_H\n#include \n#endif\n#ifdef HAVE_STRING_H\n#include \n#endif\n#ifdef HAVE_MATH_H\n#include \n#endif\n\n#include \"ppl7.h\"\n#include \"ppl7-grafix.h\"\n\n\n#ifdef HAVE_FREETYPE2\n#include \n#include FT_FREETYPE_H\n#endif\n\n\n\/\/#undef HAVE_X86_ASSEMBLER\n\n\/\/ Font-Blitter\ntypedef struct tagGLYPH {\n\tconst char *data;\n\tchar *target;\n\tppluint32 pitch;\n\tpplint32 color;\n} GLYPH;\n\nextern \"C\" {\n\tint BltGlyph_M8_32 (GLYPH *g);\n\tint BltGlyph_M1_32 (GLYPH *g);\n\tint BltGlyph_AA8_32 (GLYPH *g);\n\tint BltGlyph_AA2_32 (GLYPH *g);\n\tint BltGlyph_AA4_32 (GLYPH *g);\n}\n\nnamespace ppl7 {\nnamespace grafix {\n\n\/*!\\class FontEngineFreeType\n * \\ingroup PPLGroupGrafik\n * \\brief Font-Engine für von FreeType unterstützte Fonts\n *\n * Diese Engine unterstützt TrueType, OpenType, Type1 und weitere von der Freetype-Library\n * unterstützte Formate.\n *\n * \\see\n * http:\/\/www.freetype.org\/\n *\/\n\n\n#ifdef HAVE_FREETYPE2\ntypedef struct tagFreeTypeEngineData {\n\tFT_Library\tftlib;\n} FREETYPE_ENGINE_DATA;\n\ntypedef struct tagFreeTypeFaceData {\n\tFT_Byte *buffer;\n\tFT_Face\tface;\n\tint\t\tkerning;\n} FREETYPE_FACE_DATA;\n#endif\n\nFontEngineFreeType::FontEngineFreeType()\n{\n\tft=NULL;\n#ifdef HAVE_FREETYPE2\n#endif\n}\n\nFontEngineFreeType::~FontEngineFreeType()\n{\n#ifdef HAVE_FREETYPE2\n\tFREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA*)ft;\n\tif (f) {\n\t\tFT_Done_FreeType(f->ftlib);\n\t\tfree(f);\n\t}\n#endif\n}\n\nString FontEngineFreeType::name() const\n{\n\treturn \"FontEngineFreeType\";\n}\n\nString FontEngineFreeType::description() const\n{\n\treturn \"Rendering of TrueType and OpenType fonts\";\n}\n\n\nvoid FontEngineFreeType::init()\n{\n#ifndef HAVE_FREETYPE2\n\tthrow UnsupportedFeatureException(\"Freetype2\");\n#else\n\tif (ft) return;\n\tFREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA *)malloc(sizeof(FREETYPE_ENGINE_DATA));\n\tif (!f) throw OutOfMemoryException();\n\tint error=FT_Init_FreeType(&f->ftlib );\n\tif (error) {\n\t\tfree(f);\n\t\tthrow FontEngineInitializationException();\n\t}\n\tft=f;\n#endif\n}\n\nint FontEngineFreeType::ident(FileObject &file) throw()\n{\n#ifndef HAVE_FREETYPE2\n\treturn 0;\n#else\n\tFREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA*)ft;\n\tif (!f) return 0;\n\tconst FT_Byte *buffer=(const FT_Byte *)file.map();\n\tsize_t size=file.size();\n\tFT_Face face;\n\tint error = FT_New_Memory_Face(f->ftlib, buffer, (FT_Long)size, 0, &face );\n\tif (error!=0) return 0;\n\tFT_Done_Face(face);\n\treturn 1;\n#endif\n}\n\nFontFile *FontEngineFreeType::loadFont(FileObject &file, const String &fontname)\n{\n#ifndef HAVE_FREETYPE2\n\tthrow UnsupportedFeatureException(\"Freetype2\");\n#else\n\tFREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA*)ft;\n\tif (!f) throw FontEngineUninitializedException();\n\tFREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)malloc(sizeof(FREETYPE_FACE_DATA));\n\tif (!face) throw OutOfMemoryException();\n\tface->buffer=(FT_Byte *)file.load();\n\tsize_t size=file.size();\n\tint error = FT_New_Memory_Face(f->ftlib, face->buffer, (FT_Long)size, 0, &face->face );\n\tif (error!=0) {\n\t\tfree(face->buffer);\n\t\tfree(face);\n\t\tif (error!=0) throw InvalidFontException();\n\t}\n\tString name=fontname;\n\tif (name.isEmpty()) name.set(face->face->family_name);\n\tface->kerning=(int)FT_HAS_KERNING(face->face);\t\t\/\/ Kerning unterstützt?\n\tFontFile *ff=new FontFile;\n\tff->Name=fontname;\n\tff->engine=this;\n\tff->priv=face;\n\treturn ff;\n#endif\n}\n\nvoid FontEngineFreeType::deleteFont(FontFile *file)\n{\n#ifndef HAVE_FREETYPE2\n\tthrow UnsupportedFeatureException(\"Freetype2\");\n#else\n\tif (!file) throw NullPointerException();\n\tif (file->engine!=this) throw InvalidFontEngineException();\n\tFREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)file->priv;\n\tif (face) {\n\t\tFT_Done_Face(face->face);\n\t\tfree(face->buffer);\n\t\tfree(face);\n\t\tfile->priv=NULL;\n\t}\n\tfile->engine=NULL;\n#endif\n}\n\n\nstatic void putPixel(Drawable &draw, int x, int y, const Color &color, int intensity)\n{\n\tColor vg=color;\n\tint a=vg.alpha()*intensity\/255;\n\tif (a==0) return;\n\tif (a==255) {\n\t\tvg.setAlpha(a);\n\t\tdraw.putPixel(x,y,vg);\n\t}\n\tColor &bg=draw.getPixel(x,y);\n\tint reva=255-a;\n\tint red=bg.red()*reva+vg.red()*a;\n\tint green=bg.green()*reva+vg.green()*a;\n\tint blue=bg.blue()*reva+vg.blue()*a;\n\tint alpha=bg.alpha()*reva+vg.alpha()*a;\n\tdraw.putPixel(x,y,Color(red,green,blue,alpha));\n}\n\n#ifdef HAVE_FREETYPE2\nstatic void renderGlyphAA(Drawable &draw, FT_Bitmap *bitmap, int x, int y, const Color &color)\n{\n\tppluint8 v=0;\n\tppluint8 *glyph=(ppluint8 *)bitmap->buffer;\n\tfor (unsigned int gy=0;gyrows;gy++) {\n\t\tfor (unsigned int gx=0;gxwidth;gx++) {\n\t\t\tv=glyph[gx];\n\t\t\tif (v>0) {\n\t\t\t\tputPixel(x+gx,y+gy,color,v);\n\t\t\t\t\/\/draw.blendPixel(x+gx,y+gy,color,v);\n\t\t\t}\n\t\t}\n\t\tglyph+=bitmap->pitch;\n\t}\n}\n\nstatic void renderGlyphMono(Drawable &draw, FT_Bitmap *bitmap, int x, int y, const Color &color)\n{\n\tppluint8 v=0;\n\tppluint8 *glyph=(ppluint8 *)bitmap->buffer;\n\tfor (unsigned int gy=0;gyrows;gy++) {\n\t\tppluint8 bitcount=0;\n\t\tppluint8 bytecount=0;\n\t\tfor (unsigned int gx=0;gxwidth;gx++) {\n\t\t\tif (!bitcount) {\n\t\t\t\tv=glyph[bytecount];\n\t\t\t\tbitcount=8;\n\t\t\t\tbytecount++;\n\t\t\t}\n\t\t\tif(v&128) {\n\t\t\t\tputPixel(x+gx,y+gy,color,255);\n\t\t\t\t\/\/draw.alphaPixel(x+gx,y+gy,color);\n\t\t\t}\n\t\t\tv=v<<1;\n\t\t\tbitcount--;\n\t\t}\n\t\tglyph+=bitmap->pitch;\n\t}\n}\n\n#endif\n\nvoid FontEngineFreeType::render(const FontFile &file, const Font &font, Drawable &draw, int x, int y, const WideString &text, const Color &color)\n{\n#ifndef HAVE_FREETYPE2\n\tthrow UnsupportedFeatureException(\"Freetype2\");\n#else\n\tif (file.priv==NULL) throw InvalidFontException();\n\tFREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)file.priv;\n\tint error=FT_Set_Pixel_Sizes(face->face,0,font.size()+2);\n\tif (error!=0) throw InvalidFontException();\n\n\tint orgx=x<<6;\n\tint orgy=y<<6;\n\tint lastx=orgx;\n\tbool rotate=false;\n\tFT_Matrix matrix; \/* transformation matrix *\/\n\tif (font.rotation()!=0.0) {\n\t\trotate=true;\n\t\tdouble angle=font.rotation()*3.14159265359\/180.0;\n\t\t\/* set up matrix *\/\n\t\tmatrix.xx = (FT_Fixed)( cos( angle ) * 0x10000L );\n\t\tmatrix.xy = (FT_Fixed)( sin( angle ) * 0x10000L );\n\t\tmatrix.yx = (FT_Fixed)( -sin( angle ) * 0x10000L );\n\t\tmatrix.yy = (FT_Fixed)( cos( angle ) * 0x10000L );\n\t\tFT_Set_Transform( face->face, &matrix, NULL );\n\t} else {\n\t\tFT_Set_Transform( face->face, NULL, NULL );\n\t}\n\n\tFT_GlyphSlot slot=face->face->glyph;\n\tFT_UInt\t\t\tglyph_index, last_glyph=0;\n\tFT_Vector\t\tkerning;\n\tkerning.x=0;\n\tkerning.y=0;\n\n\tsize_t p=0;\n\tsize_t textlen=text.len();\n\n\twhile (pface,code);\n\t\t\tif (!glyph_index) continue;\n\t\t\t\/\/ Antialiasing\n\t\t\tif (font.antialias()) {\n\t\t\t\terror=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_RENDER|FT_LOAD_TARGET_NORMAL);\n\t\t\t} else {\n\t\t\t\terror=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_TARGET_MONO|FT_LOAD_RENDER);\n\t\t\t}\n\t\t\tif (error!=0) continue;\n\t\t\t\/\/x=x+(slot->bitmap_left<<6);\n\t\t\t\/\/y=y-(slot->bitmap_top<<6);\n\t\t\tif (face->kerning>0 && last_glyph>0 && rotate==false) {\n\t\t\t\tFT_Get_Kerning(face->face,last_glyph,glyph_index,FT_KERNING_DEFAULT,&kerning);\n\t\t\t\tx+=kerning.x;\n\t\t\t\ty+=kerning.y;\n\t\t\t}\n\n\t\t\tif (font.antialias()) {\n\t\t\t\trenderGlyphAA(draw,&slot->bitmap,(x>>6)+slot->bitmap_left,\n\t\t\t\t\t\t(y>>6)-slot->bitmap_top,color);\n\t\t\t} else {\n\t\t\t\trenderGlyphMono(draw,&slot->bitmap,(x>>6)+slot->bitmap_left,\n\t\t\t\t\t\t(y>>6)-slot->bitmap_top,color);\n\t\t\t}\n\t\t\tif (font.drawUnderline()) {\n\n\t\t\t}\n\t\t\tlastx=x+slot->advance.x;\n\t\t\torgy-=slot->advance.y;\n\t\t\tlast_glyph=glyph_index;\n\t\t}\n\t}\n#endif\n}\n\nSize FontEngineFreeType::measure(const FontFile &file, const Font &font, const WideString &text)\n{\n\tSize s;\n#ifndef HAVE_FREETYPE2\n\tthrow UnsupportedFeatureException(\"Freetype2\");\n#else\n\tif (file.priv==NULL) throw InvalidFontException();\n\tFREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)file.priv;\n\tint error=FT_Set_Pixel_Sizes(face->face,0,font.size()+2);\n\tif (error!=0) throw InvalidFontException();\n\n\tFT_Set_Transform( face->face, NULL, NULL );\n\n\tint width=0,height=0;\n\n\tFT_GlyphSlot slot=face->face->glyph;\n\tFT_UInt\t\t\tglyph_index, last_glyph=0;\n\tFT_Vector\t\tkerning;\n\tkerning.x=0;\n\tkerning.y=0;\n\tsize_t p=0;\n\tsize_t textlen=text.len();\n\twhile (pface,code);\n\t\t\tif (!glyph_index) continue;\n\t\t\t\/\/ Antialiasing\n\t\t\tif (font.antialias()) {\n\t\t\t\terror=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_RENDER|FT_LOAD_TARGET_NORMAL);\n\t\t\t} else {\n\t\t\t\terror=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_TARGET_MONO|FT_LOAD_RENDER);\n\t\t\t}\n\t\t\tif (error!=0) continue;\n\t\t\t\/\/x=x+slot->bitmap_left;\n\t\t\t\/\/y=y-slot->bitmap_top;\n\t\t\tif (face->kerning>0 && last_glyph>0) {\n\t\t\t\terror=FT_Get_Kerning(face->face,last_glyph,glyph_index,FT_KERNING_DEFAULT,&kerning);\n\t\t\t\twidth+=kerning.x;\n\t\t\t}\n\t\t\twidth+=(slot->advance.x);\n\t\t\tif (width>s.width) s.width=width;\n\t\t\tlast_glyph=glyph_index;\n\t\t}\n\t}\n\ts.setHeight(height+font.size()+2);\n\ts.width=s.width>>6;\n\treturn s;\n#endif\n}\n\n\n} \/\/ EOF namespace grafix\n} \/\/ EOF namespace ppl7\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/renderer\/extensions\/app_window_custom_bindings.h\"\n\n#include \n\n#include \"base\/string_util.h\"\n#include \"chrome\/common\/extensions\/extension_action.h\"\n#include \"chrome\/common\/extensions\/extension_messages.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/renderer\/extensions\/extension_dispatcher.h\"\n#include \"chrome\/renderer\/extensions\/extension_helper.h\"\n#include \"content\/public\/renderer\/render_view.h\"\n#include \"grit\/renderer_resources.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebFrame.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebView.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/platform\/WebURLRequest.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebWindowFeatures.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebNavigationPolicy.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n#include \"v8\/include\/v8.h\"\n\n#include \"content\/public\/renderer\/render_view.h\"\n#include \"content\/public\/renderer\/render_view_visitor.h\"\n\nnamespace extensions {\n\nAppWindowCustomBindings::AppWindowCustomBindings(\n ExtensionDispatcher* extension_dispatcher)\n : ChromeV8Extension(extension_dispatcher) {\n RouteStaticFunction(\"GetView\", &GetView);\n}\n\nnamespace {\nclass FindViewByID : public content::RenderViewVisitor {\n public:\n explicit FindViewByID(int route_id) : route_id_(route_id), view_(NULL) {\n }\n\n content::RenderView* view() { return view_; }\n\n \/\/ Returns false to terminate the iteration.\n virtual bool Visit(content::RenderView* render_view) {\n if (render_view->GetRoutingID() == route_id_) {\n view_ = render_view;\n return false;\n }\n return true;\n }\n\n private:\n int route_id_;\n content::RenderView* view_;\n};\n} \/\/ namespace\n\nv8::Handle AppWindowCustomBindings::GetView(\n const v8::Arguments& args) {\n \/\/ TODO(jeremya): convert this to IDL nocompile to get validation, and turn\n \/\/ these argument checks into CHECK().\n if (args.Length() != 1)\n return v8::Undefined();\n\n if (!args[0]->IsInt32())\n return v8::Undefined();\n\n int view_id = args[0]->Int32Value();\n\n if (view_id == MSG_ROUTING_NONE)\n return v8::Undefined();\n\n \/\/ TODO(jeremya): there exists a direct map of routing_id -> RenderView as\n \/\/ ChildThread::current()->ResolveRoute(), but ResolveRoute returns an\n \/\/ IPC::Channel::Listener*, which RenderView doesn't inherit from\n \/\/ (RenderViewImpl does, indirectly, via RenderWidget, but the link isn't\n \/\/ exposed outside of content\/.)\n FindViewByID view_finder(view_id);\n content::RenderView::ForEach(&view_finder);\n content::RenderView* view = view_finder.view();\n if (!view)\n return v8::Undefined();\n\n \/\/ TODO(jeremya): it doesn't really make sense to set the opener here, but we\n \/\/ need to make sure the security origin is set up before returning the DOM\n \/\/ reference. A better way to do this would be to have the browser pass the\n \/\/ opener through so opener_id is set in RenderViewImpl's constructor.\n WebKit::WebFrame* opener = GetCurrentRenderView()->GetWebView()->mainFrame();\n WebKit::WebFrame* frame = view->GetWebView()->mainFrame();\n frame->setOpener(opener);\n\n v8::Local window = frame->mainWorldScriptContext()->Global();\n return window;\n}\n\n} \/\/ namespace extensions\nCoverity NULL_RETURNS issue.\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/renderer\/extensions\/app_window_custom_bindings.h\"\n\n#include \n\n#include \"base\/string_util.h\"\n#include \"chrome\/common\/extensions\/extension_action.h\"\n#include \"chrome\/common\/extensions\/extension_messages.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/renderer\/extensions\/extension_dispatcher.h\"\n#include \"chrome\/renderer\/extensions\/extension_helper.h\"\n#include \"content\/public\/renderer\/render_view.h\"\n#include \"grit\/renderer_resources.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebFrame.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebView.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/platform\/WebURLRequest.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebWindowFeatures.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebNavigationPolicy.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n#include \"v8\/include\/v8.h\"\n\n#include \"content\/public\/renderer\/render_view.h\"\n#include \"content\/public\/renderer\/render_view_visitor.h\"\n\nnamespace extensions {\n\nAppWindowCustomBindings::AppWindowCustomBindings(\n ExtensionDispatcher* extension_dispatcher)\n : ChromeV8Extension(extension_dispatcher) {\n RouteStaticFunction(\"GetView\", &GetView);\n}\n\nnamespace {\nclass FindViewByID : public content::RenderViewVisitor {\n public:\n explicit FindViewByID(int route_id) : route_id_(route_id), view_(NULL) {\n }\n\n content::RenderView* view() { return view_; }\n\n \/\/ Returns false to terminate the iteration.\n virtual bool Visit(content::RenderView* render_view) {\n if (render_view->GetRoutingID() == route_id_) {\n view_ = render_view;\n return false;\n }\n return true;\n }\n\n private:\n int route_id_;\n content::RenderView* view_;\n};\n} \/\/ namespace\n\nv8::Handle AppWindowCustomBindings::GetView(\n const v8::Arguments& args) {\n \/\/ TODO(jeremya): convert this to IDL nocompile to get validation, and turn\n \/\/ these argument checks into CHECK().\n if (args.Length() != 1)\n return v8::Undefined();\n\n if (!args[0]->IsInt32())\n return v8::Undefined();\n\n int view_id = args[0]->Int32Value();\n\n if (view_id == MSG_ROUTING_NONE)\n return v8::Undefined();\n\n \/\/ TODO(jeremya): there exists a direct map of routing_id -> RenderView as\n \/\/ ChildThread::current()->ResolveRoute(), but ResolveRoute returns an\n \/\/ IPC::Channel::Listener*, which RenderView doesn't inherit from\n \/\/ (RenderViewImpl does, indirectly, via RenderWidget, but the link isn't\n \/\/ exposed outside of content\/.)\n FindViewByID view_finder(view_id);\n content::RenderView::ForEach(&view_finder);\n content::RenderView* view = view_finder.view();\n if (!view)\n return v8::Undefined();\n\n \/\/ TODO(jeremya): it doesn't really make sense to set the opener here, but we\n \/\/ need to make sure the security origin is set up before returning the DOM\n \/\/ reference. A better way to do this would be to have the browser pass the\n \/\/ opener through so opener_id is set in RenderViewImpl's constructor.\n content::RenderView* render_view = GetCurrentRenderView();\n if (!render_view)\n return v8::Undefined();\n WebKit::WebFrame* opener = render_view->GetWebView()->mainFrame();\n WebKit::WebFrame* frame = view->GetWebView()->mainFrame();\n frame->setOpener(opener);\n\n v8::Local window = frame->mainWorldScriptContext()->Global();\n return window;\n}\n\n} \/\/ namespace extensions\n<|endoftext|>"} {"text":"\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2011 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"VertexData.h\"\n\n#include \"GLContext.h\"\n\n#include \"..\/base\/Exception.h\"\n#include \"..\/base\/WideLine.h\"\n#include \"..\/base\/ObjectCounter.h\"\n\n#include \n#include \n#include \n\nusing namespace std;\nusing namespace boost;\n\nnamespace avg {\n \nconst int MIN_VERTEXES = 100;\nconst int MIN_INDEXES = 100;\n\nVertexData::VertexData(int reserveVerts, int reserveIndexes)\n : m_NumVerts(0),\n m_NumIndexes(0),\n m_ReserveVerts(reserveVerts),\n m_ReserveIndexes(reserveIndexes),\n m_bDataChanged(true)\n{\n ObjectCounter::get()->incRef(&typeid(*this));\n if (m_ReserveVerts < MIN_VERTEXES) {\n m_ReserveVerts = MIN_VERTEXES;\n }\n if (m_ReserveIndexes < MIN_INDEXES) {\n m_ReserveIndexes = MIN_INDEXES;\n }\n m_pVertexData = new T2V3C4Vertex[m_ReserveVerts];\n m_pIndexData = new unsigned int[m_ReserveIndexes];\n\n}\n\nVertexData::~VertexData()\n{\n delete[] m_pVertexData;\n delete[] m_pIndexData;\n ObjectCounter::get()->decRef(&typeid(*this));\n}\n\nvoid VertexData::appendPos(const glm::vec2& pos, const glm::vec2& texPos,\n const Pixel32& color)\n{\n if (m_NumVerts >= m_ReserveVerts-1) {\n grow();\n }\n T2V3C4Vertex* pVertex = &(m_pVertexData[m_NumVerts]);\n pVertex->m_Pos[0] = (GLfloat)pos.x;\n pVertex->m_Pos[1] = (GLfloat)pos.y;\n pVertex->m_Pos[2] = 0.0;\n pVertex->m_Tex[0] = (GLfloat)texPos.x;\n pVertex->m_Tex[1] = (GLfloat)texPos.y;\n pVertex->m_Color = color;\n m_bDataChanged = true;\n m_NumVerts++;\n}\n\nvoid VertexData::appendTriIndexes(int v0, int v1, int v2)\n{\n if (m_NumIndexes >= m_ReserveIndexes-3) {\n grow();\n }\n m_pIndexData[m_NumIndexes] = v0;\n m_pIndexData[m_NumIndexes+1] = v1;\n m_pIndexData[m_NumIndexes+2] = v2;\n m_NumIndexes += 3;\n}\n\nvoid VertexData::appendQuadIndexes(int v0, int v1, int v2, int v3)\n{\n if (m_NumIndexes >= m_ReserveIndexes-6) {\n grow();\n }\n m_pIndexData[m_NumIndexes] = v0;\n m_pIndexData[m_NumIndexes+1] = v1;\n m_pIndexData[m_NumIndexes+2] = v2;\n m_pIndexData[m_NumIndexes+3] = v1;\n m_pIndexData[m_NumIndexes+4] = v2;\n m_pIndexData[m_NumIndexes+5] = v3;\n m_NumIndexes += 6;\n}\n\nvoid VertexData::addLineData(Pixel32 color, const glm::vec2& p1, const glm::vec2& p2, \n float width, float tc1, float tc2)\n{\n WideLine wl(p1, p2, width);\n int curVertex = getCurVert();\n appendPos(wl.pl0, glm::vec2(tc1, 1), color);\n appendPos(wl.pr0, glm::vec2(tc1, 0), color);\n appendPos(wl.pl1, glm::vec2(tc2, 1), color);\n appendPos(wl.pr1, glm::vec2(tc2, 0), color);\n appendQuadIndexes(curVertex+1, curVertex, curVertex+3, curVertex+2); \n}\n\nvoid VertexData::appendVertexData(VertexDataPtr pVertexes)\n{\n int oldNumVerts = m_NumVerts;\n int oldNumIndexes = m_NumIndexes;\n m_NumVerts += pVertexes->getNumVerts();\n m_NumIndexes += pVertexes->getNumIndexes();\n if (m_NumVerts > m_ReserveVerts || m_NumIndexes > m_ReserveIndexes) {\n grow();\n }\n\n for (int i=0; igetNumVerts(); ++i) {\n m_pVertexData[oldNumVerts+i] = pVertexes->m_pVertexData[i];\n }\n for (int i=0; igetNumIndexes(); ++i) {\n m_pIndexData[oldNumIndexes+i] = pVertexes->m_pIndexData[i]+oldNumVerts;\n }\n m_bDataChanged = true;\n}\n\nbool VertexData::hasDataChanged() const\n{\n return m_bDataChanged;\n}\n\nvoid VertexData::resetDataChanged()\n{\n m_bDataChanged = false;\n}\n\nvoid VertexData::reset()\n{\n m_NumVerts = 0;\n m_NumIndexes = 0;\n}\n\nint VertexData::getCurVert() const\n{\n return m_NumVerts;\n}\n\nint VertexData::getCurIndex() const\n{\n return m_NumIndexes;\n}\n\nvoid VertexData::dump() const\n{\n cerr << m_NumVerts << \" vertexes: \";\n for (int i=0; i= m_ReserveVerts-1) {\n bChanged = true;\n int oldReserveVerts = m_ReserveVerts;\n m_ReserveVerts = int(m_ReserveVerts*1.5);\n if (m_ReserveVerts < m_NumVerts) {\n m_ReserveVerts = m_NumVerts;\n }\n T2V3C4Vertex* pVertexData = m_pVertexData;\n m_pVertexData = new T2V3C4Vertex[m_ReserveVerts];\n memcpy(m_pVertexData, pVertexData, sizeof(T2V3C4Vertex)*oldReserveVerts);\n delete[] pVertexData;\n }\n if (m_NumIndexes >= m_ReserveIndexes-6) {\n bChanged = true;\n int oldReserveIndexes = m_ReserveIndexes;\n m_ReserveIndexes = int(m_ReserveIndexes*1.5);\n if (m_ReserveIndexes < m_NumIndexes) {\n m_ReserveIndexes = m_NumIndexes;\n }\n unsigned int * pIndexData = m_pIndexData;\n m_pIndexData = new unsigned int[m_ReserveIndexes];\n memcpy(m_pIndexData, pIndexData, sizeof(unsigned int)*oldReserveIndexes);\n delete[] pIndexData;\n }\n if (bChanged) {\n m_bDataChanged = true;\n }\n}\n\nint VertexData::getNumVerts() const\n{\n return m_NumVerts;\n}\n\nint VertexData::getNumIndexes() const\n{\n return m_NumIndexes;\n}\n\nint VertexData::getReserveVerts() const\n{\n return m_ReserveVerts;\n}\n\nint VertexData::getReserveIndexes() const\n{\n return m_ReserveIndexes;\n}\n\nconst T2V3C4Vertex * VertexData::getVertexPointer() const\n{\n return m_pVertexData;\n}\n\nconst unsigned int * VertexData::getIndexPointer() const\n{\n return m_pIndexData;\n}\n\nstd::ostream& operator<<(std::ostream& os, const T2V3C4Vertex& v)\n{\n os << \"(\" << v.m_Pos[0] << \", \" << v.m_Pos[1] << \", \" << v.m_Pos[2] << \")\";\n return os;\n}\n\n}\n\nMinor optimization.\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2011 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"VertexData.h\"\n\n#include \"GLContext.h\"\n\n#include \"..\/base\/Exception.h\"\n#include \"..\/base\/WideLine.h\"\n#include \"..\/base\/ObjectCounter.h\"\n\n#include \n#include \n#include \n\nusing namespace std;\nusing namespace boost;\n\nnamespace avg {\n \nconst int MIN_VERTEXES = 100;\nconst int MIN_INDEXES = 100;\n\nVertexData::VertexData(int reserveVerts, int reserveIndexes)\n : m_NumVerts(0),\n m_NumIndexes(0),\n m_ReserveVerts(reserveVerts),\n m_ReserveIndexes(reserveIndexes),\n m_bDataChanged(true)\n{\n ObjectCounter::get()->incRef(&typeid(*this));\n if (m_ReserveVerts < MIN_VERTEXES) {\n m_ReserveVerts = MIN_VERTEXES;\n }\n if (m_ReserveIndexes < MIN_INDEXES) {\n m_ReserveIndexes = MIN_INDEXES;\n }\n m_pVertexData = new T2V3C4Vertex[m_ReserveVerts];\n m_pIndexData = new unsigned int[m_ReserveIndexes];\n\n}\n\nVertexData::~VertexData()\n{\n delete[] m_pVertexData;\n delete[] m_pIndexData;\n ObjectCounter::get()->decRef(&typeid(*this));\n}\n\nvoid VertexData::appendPos(const glm::vec2& pos, const glm::vec2& texPos,\n const Pixel32& color)\n{\n if (m_NumVerts >= m_ReserveVerts-1) {\n grow();\n }\n T2V3C4Vertex* pVertex = &(m_pVertexData[m_NumVerts]);\n pVertex->m_Pos[0] = (GLfloat)pos.x;\n pVertex->m_Pos[1] = (GLfloat)pos.y;\n pVertex->m_Pos[2] = 0.0;\n pVertex->m_Tex[0] = (GLfloat)texPos.x;\n pVertex->m_Tex[1] = (GLfloat)texPos.y;\n pVertex->m_Color = color;\n m_bDataChanged = true;\n m_NumVerts++;\n}\n\nvoid VertexData::appendTriIndexes(int v0, int v1, int v2)\n{\n if (m_NumIndexes >= m_ReserveIndexes-3) {\n grow();\n }\n m_pIndexData[m_NumIndexes] = v0;\n m_pIndexData[m_NumIndexes+1] = v1;\n m_pIndexData[m_NumIndexes+2] = v2;\n m_NumIndexes += 3;\n}\n\nvoid VertexData::appendQuadIndexes(int v0, int v1, int v2, int v3)\n{\n if (m_NumIndexes >= m_ReserveIndexes-6) {\n grow();\n }\n m_pIndexData[m_NumIndexes] = v0;\n m_pIndexData[m_NumIndexes+1] = v1;\n m_pIndexData[m_NumIndexes+2] = v2;\n m_pIndexData[m_NumIndexes+3] = v1;\n m_pIndexData[m_NumIndexes+4] = v2;\n m_pIndexData[m_NumIndexes+5] = v3;\n m_NumIndexes += 6;\n}\n\nvoid VertexData::addLineData(Pixel32 color, const glm::vec2& p1, const glm::vec2& p2, \n float width, float tc1, float tc2)\n{\n WideLine wl(p1, p2, width);\n int curVertex = getCurVert();\n appendPos(wl.pl0, glm::vec2(tc1, 1), color);\n appendPos(wl.pr0, glm::vec2(tc1, 0), color);\n appendPos(wl.pl1, glm::vec2(tc2, 1), color);\n appendPos(wl.pr1, glm::vec2(tc2, 0), color);\n appendQuadIndexes(curVertex+1, curVertex, curVertex+3, curVertex+2); \n}\n\nvoid VertexData::appendVertexData(VertexDataPtr pVertexes)\n{\n int oldNumVerts = m_NumVerts;\n int oldNumIndexes = m_NumIndexes;\n m_NumVerts += pVertexes->getNumVerts();\n m_NumIndexes += pVertexes->getNumIndexes();\n if (m_NumVerts > m_ReserveVerts || m_NumIndexes > m_ReserveIndexes) {\n grow();\n }\n\n memcpy(&(m_pVertexData[oldNumVerts]), pVertexes->m_pVertexData, \n pVertexes->getNumVerts()*sizeof(T2V3C4Vertex));\n\n for (int i=0; igetNumIndexes(); ++i) {\n m_pIndexData[oldNumIndexes+i] = pVertexes->m_pIndexData[i]+oldNumVerts;\n }\n m_bDataChanged = true;\n}\n\nbool VertexData::hasDataChanged() const\n{\n return m_bDataChanged;\n}\n\nvoid VertexData::resetDataChanged()\n{\n m_bDataChanged = false;\n}\n\nvoid VertexData::reset()\n{\n m_NumVerts = 0;\n m_NumIndexes = 0;\n}\n\nint VertexData::getCurVert() const\n{\n return m_NumVerts;\n}\n\nint VertexData::getCurIndex() const\n{\n return m_NumIndexes;\n}\n\nvoid VertexData::dump() const\n{\n cerr << m_NumVerts << \" vertexes: \";\n for (int i=0; i= m_ReserveVerts-1) {\n bChanged = true;\n int oldReserveVerts = m_ReserveVerts;\n m_ReserveVerts = int(m_ReserveVerts*1.5);\n if (m_ReserveVerts < m_NumVerts) {\n m_ReserveVerts = m_NumVerts;\n }\n T2V3C4Vertex* pVertexData = m_pVertexData;\n m_pVertexData = new T2V3C4Vertex[m_ReserveVerts];\n memcpy(m_pVertexData, pVertexData, sizeof(T2V3C4Vertex)*oldReserveVerts);\n delete[] pVertexData;\n }\n if (m_NumIndexes >= m_ReserveIndexes-6) {\n bChanged = true;\n int oldReserveIndexes = m_ReserveIndexes;\n m_ReserveIndexes = int(m_ReserveIndexes*1.5);\n if (m_ReserveIndexes < m_NumIndexes) {\n m_ReserveIndexes = m_NumIndexes;\n }\n unsigned int * pIndexData = m_pIndexData;\n m_pIndexData = new unsigned int[m_ReserveIndexes];\n memcpy(m_pIndexData, pIndexData, sizeof(unsigned int)*oldReserveIndexes);\n delete[] pIndexData;\n }\n if (bChanged) {\n m_bDataChanged = true;\n }\n}\n\nint VertexData::getNumVerts() const\n{\n return m_NumVerts;\n}\n\nint VertexData::getNumIndexes() const\n{\n return m_NumIndexes;\n}\n\nint VertexData::getReserveVerts() const\n{\n return m_ReserveVerts;\n}\n\nint VertexData::getReserveIndexes() const\n{\n return m_ReserveIndexes;\n}\n\nconst T2V3C4Vertex * VertexData::getVertexPointer() const\n{\n return m_pVertexData;\n}\n\nconst unsigned int * VertexData::getIndexPointer() const\n{\n return m_pIndexData;\n}\n\nstd::ostream& operator<<(std::ostream& os, const T2V3C4Vertex& v)\n{\n os << \"(\" << v.m_Pos[0] << \", \" << v.m_Pos[1] << \", \" << v.m_Pos[2] << \")\";\n return os;\n}\n\n}\n\n<|endoftext|>"} {"text":"\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/ \n\/\/ GRINS - General Reacting Incompressible Navier-Stokes \n\/\/\n\/\/ Copyright (C) 2014 Paul T. Bauman, Roy H. Stogner\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\/\/ This class\n#include \"grins\/solver_factory.h\"\n\n\/\/ GRINS\n#include \"grins\/grins_steady_solver.h\"\n#include \"grins\/grins_unsteady_solver.h\"\n#include \"grins\/steady_mesh_adaptive_solver.h\"\n\n\/\/ libMesh\n#include \"libmesh\/getpot.h\"\n\nnamespace GRINS\n{\n SolverFactory::SolverFactory()\n {\n return;\n }\n\n SolverFactory::~SolverFactory()\n {\n return;\n }\n\n std::tr1::shared_ptr SolverFactory::build(const GetPot& input)\n {\n bool mesh_adaptive = input(\"MeshAdaptivity\/mesh_adaptive\", false );\n\n bool transient = input(\"unsteady-solver\/transient\", false );\n\n std::tr1::shared_ptr solver; \/\/ Effectively NULL\n\n if(transient && !mesh_adaptive)\n {\n solver.reset( new UnsteadySolver(input) );\n }\n else if( !transient && !mesh_adaptive )\n {\n solver.reset( new SteadySolver(input) );\n }\n else if( !transient && mesh_adaptive )\n {\n solver.reset( new SteadyMeshAdaptiveSolver(input) );\n }\n else if( transient && mesh_adaptive )\n {\n libmesh_not_implemented();\n }\n else\n {\n std::cerr << \"Invalid solver options!\" << std::endl;\n }\n\n return solver;\n }\n\n} \/\/ namespace GRINS\nAdd displacement solver to solver factory\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/ \n\/\/ GRINS - General Reacting Incompressible Navier-Stokes \n\/\/\n\/\/ Copyright (C) 2014 Paul T. Bauman, Roy H. Stogner\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\/\/ This class\n#include \"grins\/solver_factory.h\"\n\n\/\/ GRINS\n#include \"grins\/grins_steady_solver.h\"\n#include \"grins\/grins_unsteady_solver.h\"\n#include \"grins\/steady_mesh_adaptive_solver.h\"\n#include \"grins\/displacement_continuation_solver.h\"\n\n\/\/ libMesh\n#include \"libmesh\/getpot.h\"\n\nnamespace GRINS\n{\n SolverFactory::SolverFactory()\n {\n return;\n }\n\n SolverFactory::~SolverFactory()\n {\n return;\n }\n\n std::tr1::shared_ptr SolverFactory::build(const GetPot& input)\n {\n bool mesh_adaptive = input(\"MeshAdaptivity\/mesh_adaptive\", false );\n\n bool transient = input(\"unsteady-solver\/transient\", false );\n\n std::tr1::shared_ptr solver; \/\/ Effectively NULL\n\n std::string solver_type = input(\"SolverOptions\/solver_type\", \"DIE!\");\n\n if( solver_type == std::string(\"displacement_continuation\") )\n {\n solver.reset( new DisplacementContinuationSolver(input) );\n }\n else if(transient && !mesh_adaptive)\n {\n solver.reset( new UnsteadySolver(input) );\n }\n else if( !transient && !mesh_adaptive )\n {\n solver.reset( new SteadySolver(input) );\n }\n else if( !transient && mesh_adaptive )\n {\n solver.reset( new SteadyMeshAdaptiveSolver(input) );\n }\n else if( transient && mesh_adaptive )\n {\n libmesh_not_implemented();\n }\n else\n {\n std::cerr << \"Invalid solver options!\" << std::endl;\n }\n\n return solver;\n }\n\n} \/\/ namespace GRINS\n<|endoftext|>"} {"text":"#include \"genstoreDefines.sqf\"\r\n\r\nclass genstored {\r\n\r\n\tidd = genstore_DIALOG;\r\n\tmovingEnable = true;\r\n\tenableSimulation = true;\r\n\tonLoad = \"[0] execVM 'client\\systems\\generalStore\\populateGenStore.sqf'\";\r\n\r\n\tclass controlsBackground {\r\n\t\t\r\n\t\tclass MainBackground: w_RscPicture\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tcolorText[] = {1, 1, 1, 1};\r\n\t\t colorBackground[] = {0,0,0,0};\r\n\t\t\ttext = \"#(argb,8,8,3)color(0,0,0,0.6)\";\r\n\t\t\tmoving = true;\r\n\t\t\tx = 0.1875 * safezoneW + safezoneX;\r\n\t\t\ty = 0.15 * safezoneH + safezoneY;\r\n\t\t\tw = 0.55 * safezoneW;\r\n\t\t\th = 0.65 * safezoneH;\r\n\t\t};\r\n\r\n\t\tclass TopBar: w_RscPicture\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tcolorText[] = {1, 1, 1, 1};\r\n\t\t\tcolorBackground[] = {0,0,0,0};\r\n\t\t\ttext = \"#(argb,8,8,3)color(0.25,0.51,0.96,0.8)\";\r\n\r\n\t\t\tx = 0.1875 * safezoneW + safezoneX;\r\n\t\t\ty = 0.15 * safezoneH + safezoneY;\r\n\t\t\tw = 0.55 * safezoneW;\r\n\t\t\th = 0.05 * safezoneH;\r\n\t\t};\r\n\r\n\t\tclass DialogTitleText: w_RscText\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\ttext = \"General Store Menu\";\r\n\t\t\tfont = \"PuristaMedium\";\r\n\t\t\tsizeEx = \"((((safezoneW \/ safezoneH) min 1.2) \/ 1.2) \/ 25)\";\r\n\t\t\tx = 0.20 * safezoneW + safezoneX;\r\n\t\t\ty = 0.155 * safezoneH + safezoneY;\r\n\t\t\tw = 0.19 * safezoneW;\r\n\t\t\th = 0.0448148 * safezoneH;\r\n\t\t};\r\n\r\n\t\tclass PlayerMoneyText: w_RscText\r\n\t\t{\r\n\t\t\tidc = genstore_money;\r\n\t\t\ttext = \"Cash:\";\r\n\t\t\tfont = \"PuristaMedium\";\r\n\t\t\tsizeEx = \"((((safezoneW \/ safezoneH) min 1.2) \/ 1.2) \/ 25)\";\r\n\t\t\tx = 0.640 * safezoneW + safezoneX;\r\n\t\t\ty = 0.155 * safezoneH + safezoneY;\r\n\t\t\tw = 0.0844792 * safezoneW;\r\n\t\t\th = 0.0448148 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass ItemSelectedPrice: w_RscStructuredTextLeft\r\n\t\t{\r\n\t\t\tidc = genstore_item_TEXT;\r\n\t\t\ttext = \"\";\r\n\r\n\t\t\tx = 0.299 * safezoneW + safezoneX;\r\n\t\t\ty = 0.664 * safezoneH + safezoneY;\r\n\t\t\tw = 0.0891667 * safezoneW;\r\n\t\t\th = 0.068889 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass SellSelectedPrice: w_RscStructuredTextLeft\r\n\t\t{\r\n\t\t\tidc = genstore_sell_TEXT;\r\n\t\t\ttext = \"\";\r\n\r\n\t\t\tx = 0.517 * safezoneW + safezoneX;\r\n\t\t\ty = 0.664 * safezoneH + safezoneY;\r\n\t\t\tw = 0.0891667 * safezoneW;\r\n\t\t\th = 0.068889 * safezoneH;\r\n\t\t};\r\n\t};\r\n\t\r\n\tclass controls {\r\n\t\t\r\n\t\tclass SelectionList: w_RscList\r\n\t\t{\r\n\t\t\tidc = genstore_item_list;\r\n\t\t\tonLBSelChanged = \"[] execvm 'client\\systems\\generalStore\\itemInfo.sqf'\";\r\n\t\t\tfont = \"PuristaMedium\";\r\n\t\t\tsizeEx = \"((((safezoneW \/ safezoneH) min 1.2) \/ 1.2) \/ 25)\";\r\n\t\t\tx = 0.3025 * safezoneW + safezoneX;\r\n\t\t\ty = 0.225 * safezoneH + safezoneY;\r\n\t\t\tw = 0.207 * safezoneW;\r\n\t\t\th = 0.338222 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass ItemDescription: w_RscStructuredTextLeft\r\n\t\t{\r\n\t\t\tidc = genstore_item_desc;\r\n\t\t\ttext = \"\";\r\n\t\t\tsizeEx = 0.02;\r\n\t\t\tcolorBackground[] = { 0, 0, 0, 0.1 };\r\n\t\t\tx = 0.3025 * safezoneW + safezoneX;\r\n\t\t\ty = 0.567 * safezoneH + safezoneY;\r\n\t\t\tw = 0.207 * safezoneW;\r\n\t\t\th = 0.088 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass SellList: w_RscList\r\n\t\t{\r\n\t\t\tidc = genstore_sell_list;\r\n\t\t\tonLBSelChanged = \"[] execvm 'client\\systems\\generalStore\\sellInfo.sqf'\";\r\n\t\t\tfont = \"PuristaMedium\";\r\n\t\t\tsizeEx = \"((((safezoneW \/ safezoneH) min 1.2) \/ 1.2) \/ 25)\";\r\n\t\t\tx = 0.520 * safezoneW + safezoneX;\r\n\t\t\ty = 0.225 * safezoneH + safezoneY;\r\n\t\t\tw = 0.207 * safezoneW;\r\n\t\t\th = 0.422222 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass SellWeapon: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[] execVM 'client\\systems\\selling\\sellWeapon.sqf'\";\r\n\t\t\ttext = \"Sell Weapon\";\r\n\r\n\t\t\tx = 0.360 * safezoneW + safezoneX;\r\n\t\t\ty = 0.740 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass SellUniform: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[] execVM 'client\\systems\\selling\\sellUniform.sqf'\";\r\n\t\t\ttext = \"Sell Uniform\";\r\n\t\t\tx = 0.453 * safezoneW + safezoneX;\r\n\t\t\ty = 0.740 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\r\n class SellVest: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[] execVM 'client\\systems\\selling\\sellVest.sqf'\";\r\n\t\t\ttext = \"Sell Vest\";\r\n\r\n\t\t\tx = 0.546 * safezoneW + safezoneX;\r\n\t\t\ty = 0.740 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass SellBackpack: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[] execVM 'client\\systems\\selling\\sellBackpack.sqf'\";\r\n\t\t\ttext = \"Sell Backpack\";\r\n\r\n\t\t\tx = 0.639 * safezoneW + safezoneX;\r\n\t\t\ty = 0.740 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\r\n\t\tclass CancelButton : w_RscButton {\r\n\t\t\t\r\n\t\t\tidc = -1;\r\n\t\t\ttext = \"Cancel\";\r\n\t\t\tonButtonClick = \"closeDialog 0;\";\r\n\r\n\t\t\tx = 0.20 * safezoneW + safezoneX;\r\n\t\t\ty = 0.740 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass SellItem: w_RscButton\r\n\t\t{\r\n\t\t\tidc = genstore_sell;\r\n\t\t\tonButtonClick = \"[0] execVM 'client\\systems\\generalStore\\sellItems.sqf'\";\r\n\t\t\ttext = \"Sell\";\r\n\r\n\t\t\tx = 0.655 * safezoneW + safezoneX;\r\n\t\t\ty = 0.657 * safezoneH + safezoneY;\r\n\t\t\tw = 0.072 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass BuyItem: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[0] execVM 'client\\systems\\generalStore\\buyItems.sqf'\";\r\n\t\t\ttext = \"Buy\";\r\n\r\n\t\t\tx = 0.438 * safezoneW + safezoneX;\r\n\t\t\ty = 0.657 * safezoneH + safezoneY;\r\n\t\t\tw = 0.072 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass StoreButton0: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[0] execVM 'client\\systems\\generalStore\\populateGenStore.sqf'\";\r\n\t\t\ttext = \"Headgear\";\r\n\r\n\t\t\tx = 0.20 * safezoneW + safezoneX;\r\n\t\t\ty = 0.225 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\r\n\t\t};\r\n\r\n\t\tclass StoreButton1: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[1] execVM 'client\\systems\\generalStore\\populateGenStore.sqf'\";\r\n\t\t\ttext = \"Uniforms\";\r\n\r\n\t\t\tx = 0.20 * safezoneW + safezoneX;\r\n\t\t\ty = 0.275 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\r\n\t\t};\r\n\t\t\r\n\t\tclass StoreButton2: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[2] execVM 'client\\systems\\generalStore\\populateGenStore.sqf'\";\r\n\t\t\ttext = \"Vests\";\r\n\r\n\t\t\tx = 0.20 * safezoneW + safezoneX;\r\n\t\t\ty = 0.325 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass StoreButton3: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[3] execVM 'client\\systems\\generalStore\\populateGenStore.sqf'\";\r\n\t\t\ttext = \"Backpacks\";\r\n\r\n\t\t\tx = 0.20 * safezoneW + safezoneX;\r\n\t\t\ty = 0.375 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass StoreButton4: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[4] execVM 'client\\systems\\generalStore\\populateGenStore.sqf'\";\r\n\t\t\ttext = \"Equipment\";\r\n\r\n\t\t\tx = 0.20 * safezoneW + safezoneX;\r\n\t\t\ty = 0.425 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass StoreButton5: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[5] execVM 'client\\systems\\generalStore\\populateGenStore.sqf'\";\r\n\t\t\ttext = \"Items\";\r\n\r\n\t\t\tx = 0.20 * safezoneW + safezoneX;\r\n\t\t\ty = 0.475 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\r\n\t\tclass StoreButton6: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[6] execVM 'client\\systems\\generalStore\\populateGenStore.sqf'\";\r\n\t\t\ttext = \"Objects\";\r\n\r\n\t\t\tx = 0.20 * safezoneW + safezoneX;\r\n\t\t\ty = 0.525 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\t};\r\n};\r\n\r\nChanged genstore categories text#include \"genstoreDefines.sqf\"\r\n\r\nclass genstored {\r\n\r\n\tidd = genstore_DIALOG;\r\n\tmovingEnable = true;\r\n\tenableSimulation = true;\r\n\tonLoad = \"[0] execVM 'client\\systems\\generalStore\\populateGenStore.sqf'\";\r\n\r\n\tclass controlsBackground {\r\n\t\t\r\n\t\tclass MainBackground: w_RscPicture\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tcolorText[] = {1, 1, 1, 1};\r\n\t\t colorBackground[] = {0,0,0,0};\r\n\t\t\ttext = \"#(argb,8,8,3)color(0,0,0,0.6)\";\r\n\t\t\tmoving = true;\r\n\t\t\tx = 0.1875 * safezoneW + safezoneX;\r\n\t\t\ty = 0.15 * safezoneH + safezoneY;\r\n\t\t\tw = 0.55 * safezoneW;\r\n\t\t\th = 0.65 * safezoneH;\r\n\t\t};\r\n\r\n\t\tclass TopBar: w_RscPicture\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tcolorText[] = {1, 1, 1, 1};\r\n\t\t\tcolorBackground[] = {0,0,0,0};\r\n\t\t\ttext = \"#(argb,8,8,3)color(0.25,0.51,0.96,0.8)\";\r\n\r\n\t\t\tx = 0.1875 * safezoneW + safezoneX;\r\n\t\t\ty = 0.15 * safezoneH + safezoneY;\r\n\t\t\tw = 0.55 * safezoneW;\r\n\t\t\th = 0.05 * safezoneH;\r\n\t\t};\r\n\r\n\t\tclass DialogTitleText: w_RscText\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\ttext = \"General Store Menu\";\r\n\t\t\tfont = \"PuristaMedium\";\r\n\t\t\tsizeEx = \"((((safezoneW \/ safezoneH) min 1.2) \/ 1.2) \/ 25)\";\r\n\t\t\tx = 0.20 * safezoneW + safezoneX;\r\n\t\t\ty = 0.155 * safezoneH + safezoneY;\r\n\t\t\tw = 0.19 * safezoneW;\r\n\t\t\th = 0.0448148 * safezoneH;\r\n\t\t};\r\n\r\n\t\tclass PlayerMoneyText: w_RscText\r\n\t\t{\r\n\t\t\tidc = genstore_money;\r\n\t\t\ttext = \"Cash:\";\r\n\t\t\tfont = \"PuristaMedium\";\r\n\t\t\tsizeEx = \"((((safezoneW \/ safezoneH) min 1.2) \/ 1.2) \/ 25)\";\r\n\t\t\tx = 0.640 * safezoneW + safezoneX;\r\n\t\t\ty = 0.155 * safezoneH + safezoneY;\r\n\t\t\tw = 0.0844792 * safezoneW;\r\n\t\t\th = 0.0448148 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass ItemSelectedPrice: w_RscStructuredTextLeft\r\n\t\t{\r\n\t\t\tidc = genstore_item_TEXT;\r\n\t\t\ttext = \"\";\r\n\r\n\t\t\tx = 0.299 * safezoneW + safezoneX;\r\n\t\t\ty = 0.664 * safezoneH + safezoneY;\r\n\t\t\tw = 0.0891667 * safezoneW;\r\n\t\t\th = 0.068889 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass SellSelectedPrice: w_RscStructuredTextLeft\r\n\t\t{\r\n\t\t\tidc = genstore_sell_TEXT;\r\n\t\t\ttext = \"\";\r\n\r\n\t\t\tx = 0.517 * safezoneW + safezoneX;\r\n\t\t\ty = 0.664 * safezoneH + safezoneY;\r\n\t\t\tw = 0.0891667 * safezoneW;\r\n\t\t\th = 0.068889 * safezoneH;\r\n\t\t};\r\n\t};\r\n\t\r\n\tclass controls {\r\n\t\t\r\n\t\tclass SelectionList: w_RscList\r\n\t\t{\r\n\t\t\tidc = genstore_item_list;\r\n\t\t\tonLBSelChanged = \"[] execvm 'client\\systems\\generalStore\\itemInfo.sqf'\";\r\n\t\t\tfont = \"PuristaMedium\";\r\n\t\t\tsizeEx = \"((((safezoneW \/ safezoneH) min 1.2) \/ 1.2) \/ 25)\";\r\n\t\t\tx = 0.3025 * safezoneW + safezoneX;\r\n\t\t\ty = 0.225 * safezoneH + safezoneY;\r\n\t\t\tw = 0.207 * safezoneW;\r\n\t\t\th = 0.338222 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass ItemDescription: w_RscStructuredTextLeft\r\n\t\t{\r\n\t\t\tidc = genstore_item_desc;\r\n\t\t\ttext = \"\";\r\n\t\t\tsizeEx = 0.02;\r\n\t\t\tcolorBackground[] = { 0, 0, 0, 0.1 };\r\n\t\t\tx = 0.3025 * safezoneW + safezoneX;\r\n\t\t\ty = 0.567 * safezoneH + safezoneY;\r\n\t\t\tw = 0.207 * safezoneW;\r\n\t\t\th = 0.088 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass SellList: w_RscList\r\n\t\t{\r\n\t\t\tidc = genstore_sell_list;\r\n\t\t\tonLBSelChanged = \"[] execvm 'client\\systems\\generalStore\\sellInfo.sqf'\";\r\n\t\t\tfont = \"PuristaMedium\";\r\n\t\t\tsizeEx = \"((((safezoneW \/ safezoneH) min 1.2) \/ 1.2) \/ 25)\";\r\n\t\t\tx = 0.520 * safezoneW + safezoneX;\r\n\t\t\ty = 0.225 * safezoneH + safezoneY;\r\n\t\t\tw = 0.207 * safezoneW;\r\n\t\t\th = 0.422222 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass SellWeapon: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[] execVM 'client\\systems\\selling\\sellWeapon.sqf'\";\r\n\t\t\ttext = \"Sell Weapon\";\r\n\r\n\t\t\tx = 0.360 * safezoneW + safezoneX;\r\n\t\t\ty = 0.740 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass SellUniform: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[] execVM 'client\\systems\\selling\\sellUniform.sqf'\";\r\n\t\t\ttext = \"Sell Uniform\";\r\n\t\t\tx = 0.453 * safezoneW + safezoneX;\r\n\t\t\ty = 0.740 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\r\n class SellVest: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[] execVM 'client\\systems\\selling\\sellVest.sqf'\";\r\n\t\t\ttext = \"Sell Vest\";\r\n\r\n\t\t\tx = 0.546 * safezoneW + safezoneX;\r\n\t\t\ty = 0.740 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass SellBackpack: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[] execVM 'client\\systems\\selling\\sellBackpack.sqf'\";\r\n\t\t\ttext = \"Sell Backpack\";\r\n\r\n\t\t\tx = 0.639 * safezoneW + safezoneX;\r\n\t\t\ty = 0.740 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\r\n\t\tclass CancelButton : w_RscButton {\r\n\t\t\t\r\n\t\t\tidc = -1;\r\n\t\t\ttext = \"Cancel\";\r\n\t\t\tonButtonClick = \"closeDialog 0;\";\r\n\r\n\t\t\tx = 0.20 * safezoneW + safezoneX;\r\n\t\t\ty = 0.740 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass SellItem: w_RscButton\r\n\t\t{\r\n\t\t\tidc = genstore_sell;\r\n\t\t\tonButtonClick = \"[0] execVM 'client\\systems\\generalStore\\sellItems.sqf'\";\r\n\t\t\ttext = \"Sell\";\r\n\r\n\t\t\tx = 0.655 * safezoneW + safezoneX;\r\n\t\t\ty = 0.657 * safezoneH + safezoneY;\r\n\t\t\tw = 0.072 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass BuyItem: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[0] execVM 'client\\systems\\generalStore\\buyItems.sqf'\";\r\n\t\t\ttext = \"Buy\";\r\n\r\n\t\t\tx = 0.438 * safezoneW + safezoneX;\r\n\t\t\ty = 0.657 * safezoneH + safezoneY;\r\n\t\t\tw = 0.072 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass StoreButton0: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[0] execVM 'client\\systems\\generalStore\\populateGenStore.sqf'\";\r\n\t\t\ttext = \"Headgear\";\r\n\r\n\t\t\tx = 0.20 * safezoneW + safezoneX;\r\n\t\t\ty = 0.225 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\r\n\t\t};\r\n\r\n\t\tclass StoreButton1: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[1] execVM 'client\\systems\\generalStore\\populateGenStore.sqf'\";\r\n\t\t\ttext = \"Uniforms\";\r\n\r\n\t\t\tx = 0.20 * safezoneW + safezoneX;\r\n\t\t\ty = 0.275 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\r\n\t\t};\r\n\t\t\r\n\t\tclass StoreButton2: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[2] execVM 'client\\systems\\generalStore\\populateGenStore.sqf'\";\r\n\t\t\ttext = \"Vests\";\r\n\r\n\t\t\tx = 0.20 * safezoneW + safezoneX;\r\n\t\t\ty = 0.325 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass StoreButton3: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[3] execVM 'client\\systems\\generalStore\\populateGenStore.sqf'\";\r\n\t\t\ttext = \"Backpacks\";\r\n\r\n\t\t\tx = 0.20 * safezoneW + safezoneX;\r\n\t\t\ty = 0.375 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass StoreButton4: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[4] execVM 'client\\systems\\generalStore\\populateGenStore.sqf'\";\r\n\t\t\ttext = \"Items\";\r\n\r\n\t\t\tx = 0.20 * safezoneW + safezoneX;\r\n\t\t\ty = 0.425 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\t\t\r\n\t\tclass StoreButton5: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[5] execVM 'client\\systems\\generalStore\\populateGenStore.sqf'\";\r\n\t\t\ttext = \"Supplies\";\r\n\r\n\t\t\tx = 0.20 * safezoneW + safezoneX;\r\n\t\t\ty = 0.475 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\r\n\t\tclass StoreButton6: w_RscButton\r\n\t\t{\r\n\t\t\tidc = -1;\r\n\t\t\tonButtonClick = \"[6] execVM 'client\\systems\\generalStore\\populateGenStore.sqf'\";\r\n\t\t\ttext = \"Objects\";\r\n\r\n\t\t\tx = 0.20 * safezoneW + safezoneX;\r\n\t\t\ty = 0.525 * safezoneH + safezoneY;\r\n\t\t\tw = 0.088 * safezoneW;\r\n\t\t\th = 0.040 * safezoneH;\r\n\t\t};\r\n\t};\r\n};\r\n\r\n<|endoftext|>"} {"text":"\n#include \nusing namespace std;\n\n\nvoid main()\n{\n\n\tcout << \"Hello World\" << endl;\n\n}\nupdate func1\n#include \nusing namespace std;\n\nvoid func1()\n{\n\tcout << \"func1\" << endl;\n}\n\nvoid main()\n{\n\n\tcout << \"Hello World\" << endl;\n\n\tfunc1();\n\n}\n<|endoftext|>"} {"text":"\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n#include \"libmesh\/diff_system.h\"\n#include \"libmesh\/dof_map.h\"\n#include \"libmesh\/libmesh_logging.h\"\n#include \"libmesh\/petsc_diff_solver.h\"\n#include \"libmesh\/petsc_matrix.h\"\n#include \"libmesh\/petsc_vector.h\"\n#include \"libmesh\/petsc_auto_fieldsplit.h\"\n\n#ifdef LIBMESH_HAVE_PETSC\n\nnamespace libMesh\n{\n\n\/\/--------------------------------------------------------------------\n\/\/ Functions with C linkage to pass to PETSc. PETSc will call these\n\/\/ methods as needed.\n\/\/\n\/\/ Since they must have C linkage they have no knowledge of a namespace.\n\/\/ Give them an obscure name to avoid namespace pollution.\nextern \"C\"\n{\n \/\/ Older versions of PETSc do not have the different int typedefs.\n \/\/ On 64-bit machines, PetscInt may actually be a long long int.\n \/\/ This change occurred in Petsc-2.2.1.\n#if PETSC_VERSION_LESS_THAN(2,2,1)\n typedef int PetscErrorCode;\n typedef int PetscInt;\n#endif\n\n \/\/ Function to hand to PETSc's SNES,\n \/\/ which monitors convergence at X\n PetscErrorCode\n __libmesh_petsc_diff_solver_monitor (SNES snes, PetscInt its,\n PetscReal fnorm, void *ctx)\n {\n PetscDiffSolver& solver =\n *(static_cast (ctx));\n\n if (solver.verbose)\n libMesh::out << \" PetscDiffSolver step \" << its\n << \", |residual|_2 = \" << fnorm << std::endl;\n if (solver.linear_solution_monitor.get()) {\n int ierr = 0;\n\n Vec petsc_delta_u;\n ierr = SNESGetSolutionUpdate(snes, &petsc_delta_u);\n CHKERRABORT(solver.comm().get(), ierr);\n PetscVector delta_u(petsc_delta_u, solver.comm());\n delta_u.close();\n\n Vec petsc_u;\n ierr = SNESGetSolution(snes, &petsc_u);\n CHKERRABORT(solver.comm().get(), ierr);\n PetscVector u(petsc_u, solver.comm());\n u.close();\n\n Vec petsc_res;\n ierr = SNESGetFunction(snes, &petsc_res, NULL, NULL);\n CHKERRABORT(solver.comm().get(), ierr);\n PetscVector res(petsc_res, solver.comm());\n res.close();\n\n (*solver.linear_solution_monitor)(\n delta_u, delta_u.l2_norm(),\n u, u.l2_norm(),\n res, res.l2_norm(), its);\n }\n return 0;\n }\n\n \/\/ Functions to hand to PETSc's SNES,\n \/\/ which compute the residual or jacobian at X\n PetscErrorCode\n __libmesh_petsc_diff_solver_residual (SNES, Vec x, Vec r, void *ctx)\n {\n libmesh_assert(x);\n libmesh_assert(r);\n libmesh_assert(ctx);\n\n PetscDiffSolver& solver =\n *(static_cast (ctx));\n ImplicitSystem &sys = solver.system();\n\n if (solver.verbose)\n libMesh::out << \"Assembling the residual\" << std::endl;\n\n PetscVector& X_system =\n *cast_ptr*>(sys.solution.get());\n PetscVector& R_system =\n *cast_ptr*>(sys.rhs);\n PetscVector X_input(x, sys.comm()), R_input(r, sys.comm());\n\n \/\/ DiffSystem assembles from the solution and into the rhs, so swap\n \/\/ those with our input vectors before assembling. They'll probably\n \/\/ already be references to the same vectors, but PETSc might do\n \/\/ something tricky.\n X_input.swap(X_system);\n R_input.swap(R_system);\n\n \/\/ We may need to correct a non-conforming solution\n sys.get_dof_map().enforce_constraints_exactly(sys);\n\n \/\/ We may need to localize a parallel solution\n sys.update();\n\n \/\/ Do DiffSystem assembly\n sys.assembly(true, false);\n R_system.close();\n\n \/\/ Swap back\n X_input.swap(X_system);\n R_input.swap(R_system);\n\n \/\/ No errors, we hope\n return 0;\n }\n\n\n#if PETSC_RELEASE_LESS_THAN(3,5,0)\nPetscErrorCode\n__libmesh_petsc_diff_solver_jacobian (SNES, Vec x, Mat *libmesh_dbg_var(j), Mat *pc,\n MatStructure *msflag, void *ctx)\n#else\nPetscErrorCode\n__libmesh_petsc_diff_solver_jacobian (SNES, Vec x, Mat libmesh_dbg_var(j), Mat pc,\n void *ctx)\n#endif\n{\n libmesh_assert(x);\n libmesh_assert(j);\n\/\/ libmesh_assert_equal_to (pc, j); \/\/ We don't use separate preconditioners yet\n libmesh_assert(ctx);\n\n PetscDiffSolver& solver =\n *(static_cast (ctx));\n ImplicitSystem &sys = solver.system();\n\n if (solver.verbose)\n libMesh::out << \"Assembling the Jacobian\" << std::endl;\n\n PetscVector& X_system =\n *cast_ptr*>(sys.solution.get());\n PetscVector X_input(x, sys.comm());\n\n#if PETSC_RELEASE_LESS_THAN(3,5,0)\n PetscMatrix J_input(*pc, sys.comm());\n#else\n PetscMatrix J_input(pc, sys.comm());\n#endif\n PetscMatrix& J_system =\n *cast_ptr*>(sys.matrix);\n\n \/\/ DiffSystem assembles from the solution and into the jacobian, so\n \/\/ swap those with our input vectors before assembling. They'll\n \/\/ probably already be references to the same vectors, but PETSc\n \/\/ might do something tricky.\n X_input.swap(X_system);\n J_input.swap(J_system);\n\n \/\/ We may need to correct a non-conforming solution\n sys.get_dof_map().enforce_constraints_exactly(sys);\n\n \/\/ We may need to localize a parallel solution\n sys.update();\n\n \/\/ Do DiffSystem assembly\n sys.assembly(false, true);\n J_system.close();\n\n \/\/ Swap back\n X_input.swap(X_system);\n J_input.swap(J_system);\n\n#if PETSC_RELEASE_LESS_THAN(3,5,0)\n *msflag = SAME_NONZERO_PATTERN;\n#endif\n \/\/ No errors, we hope\n return 0;\n}\n\n} \/\/ extern \"C\"\n\n\nPetscDiffSolver::PetscDiffSolver (sys_type& s)\n : Parent(s)\n{\n}\n\n\nvoid PetscDiffSolver::init ()\n{\n START_LOG(\"init()\", \"PetscDiffSolver\");\n\n Parent::init();\n\n int ierr=0;\n\n#if PETSC_VERSION_LESS_THAN(2,1,2)\n \/\/ At least until Petsc 2.1.1, the SNESCreate had a different\n \/\/ calling syntax. The second argument was of type SNESProblemType,\n \/\/ and could have a value of either SNES_NONLINEAR_EQUATIONS or\n \/\/ SNES_UNCONSTRAINED_MINIMIZATION.\n ierr = SNESCreate(this->comm().get(), SNES_NONLINEAR_EQUATIONS, &_snes);\n LIBMESH_CHKERRABORT(ierr);\n#else\n ierr = SNESCreate(this->comm().get(),&_snes);\n LIBMESH_CHKERRABORT(ierr);\n#endif\n\n#if PETSC_VERSION_LESS_THAN(2,3,3)\n ierr = SNESSetMonitor (_snes, __libmesh_petsc_diff_solver_monitor,\n this, PETSC_NULL);\n#else\n \/\/ API name change in PETSc 2.3.3\n ierr = SNESMonitorSet (_snes, __libmesh_petsc_diff_solver_monitor,\n this, PETSC_NULL);\n#endif\n LIBMESH_CHKERRABORT(ierr);\n\n if (libMesh::on_command_line(\"--solver_system_names\"))\n {\n ierr = SNESSetOptionsPrefix(_snes, (_system.name()+\"_\").c_str());\n LIBMESH_CHKERRABORT(ierr);\n }\n\n ierr = SNESSetFromOptions(_snes);\n LIBMESH_CHKERRABORT(ierr);\n\n KSP my_ksp;\n ierr = SNESGetKSP(_snes, &my_ksp);\n LIBMESH_CHKERRABORT(ierr);\n\n PC my_pc;\n ierr = KSPGetPC(my_ksp, &my_pc);\n LIBMESH_CHKERRABORT(ierr);\n\n petsc_auto_fieldsplit(my_pc, _system);\n\n STOP_LOG(\"init()\", \"PetscDiffSolver\");\n}\n\n\n\nPetscDiffSolver::~PetscDiffSolver ()\n{\n}\n\n\n\nvoid PetscDiffSolver::clear()\n{\n START_LOG(\"clear()\", \"PetscDiffSolver\");\n\n int ierr = LibMeshSNESDestroy(&_snes);\n LIBMESH_CHKERRABORT(ierr);\n\n STOP_LOG(\"clear()\", \"PetscDiffSolver\");\n}\n\n\n\nvoid PetscDiffSolver::reinit()\n{\n Parent::reinit();\n\n KSP my_ksp;\n int ierr = SNESGetKSP(_snes, &my_ksp);\n LIBMESH_CHKERRABORT(ierr);\n\n PC my_pc;\n ierr = KSPGetPC(my_ksp, &my_pc);\n LIBMESH_CHKERRABORT(ierr);\n\n petsc_auto_fieldsplit(my_pc, _system);\n}\n\n\n\nDiffSolver::SolveResult convert_solve_result(SNESConvergedReason r)\n{\n switch (r)\n {\n case SNES_CONVERGED_FNORM_ABS:\n return DiffSolver::CONVERGED_ABSOLUTE_RESIDUAL;\n case SNES_CONVERGED_FNORM_RELATIVE:\n return DiffSolver::CONVERGED_RELATIVE_RESIDUAL;\n#if PETSC_VERSION_LESS_THAN(3,2,1)\n case SNES_CONVERGED_PNORM_RELATIVE:\n#else\n case SNES_CONVERGED_SNORM_RELATIVE:\n#endif\n return DiffSolver::CONVERGED_RELATIVE_STEP;\n#if !PETSC_VERSION_LESS_THAN(2,3,3)\n case SNES_CONVERGED_ITS:\n#endif\n case SNES_CONVERGED_TR_DELTA:\n return DiffSolver::CONVERGED_NO_REASON;\n case SNES_DIVERGED_FUNCTION_DOMAIN:\n case SNES_DIVERGED_FUNCTION_COUNT:\n case SNES_DIVERGED_FNORM_NAN:\n#if !PETSC_VERSION_LESS_THAN(3,3,0)\n case SNES_DIVERGED_INNER:\n#endif\n#if !PETSC_VERSION_LESS_THAN(2,3,2)\n case SNES_DIVERGED_LINEAR_SOLVE:\n#endif\n case SNES_DIVERGED_LOCAL_MIN:\n return DiffSolver::DIVERGED_NO_REASON;\n case SNES_DIVERGED_MAX_IT:\n return DiffSolver::DIVERGED_MAX_NONLINEAR_ITERATIONS;\n#if PETSC_VERSION_LESS_THAN(3,2,0)\n case SNES_DIVERGED_LS_FAILURE:\n#else\n case SNES_DIVERGED_LINE_SEARCH:\n#endif\n return DiffSolver::DIVERGED_BACKTRACKING_FAILURE;\n \/\/ In PETSc, SNES_CONVERGED_ITERATING means\n \/\/ the solve is still iterating, but by the\n \/\/ time we get here, we must have either\n \/\/ converged or diverged, so\n \/\/ SNES_CONVERGED_ITERATING is invalid.\n case SNES_CONVERGED_ITERATING:\n return DiffSolver::INVALID_SOLVE_RESULT;\n default:\n }\n return DiffSolver::INVALID_SOLVE_RESULT;\n}\n\n\n\nunsigned int PetscDiffSolver::solve()\n{\n this->init();\n\n START_LOG(\"solve()\", \"PetscDiffSolver\");\n\n PetscVector &x =\n *(cast_ptr*>(_system.solution.get()));\n PetscMatrix &jac =\n *(cast_ptr*>(_system.matrix));\n PetscVector &r =\n *(cast_ptr*>(_system.rhs));\n\n#ifdef LIBMESH_ENABLE_CONSTRAINTS\n _system.get_dof_map().enforce_constraints_exactly(_system);\n#endif\n\n int ierr = 0;\n\n ierr = SNESSetFunction (_snes, r.vec(),\n __libmesh_petsc_diff_solver_residual, this);\n LIBMESH_CHKERRABORT(ierr);\n\n ierr = SNESSetJacobian (_snes, jac.mat(), jac.mat(),\n __libmesh_petsc_diff_solver_jacobian, this);\n LIBMESH_CHKERRABORT(ierr);\n\n# if PETSC_VERSION_LESS_THAN(2,2,0)\n\n ierr = SNESSolve (_snes, x.vec(), &_outer_iterations);\n LIBMESH_CHKERRABORT(ierr);\n\n \/\/ 2.2.x style\n#elif PETSC_VERSION_LESS_THAN(2,3,0)\n\n ierr = SNESSolve (_snes, x.vec());\n LIBMESH_CHKERRABORT(ierr);\n\n \/\/ 2.3.x & newer style\n#else\n\n ierr = SNESSolve (_snes, PETSC_NULL, x.vec());\n LIBMESH_CHKERRABORT(ierr);\n\n#endif\n\n STOP_LOG(\"solve()\", \"PetscDiffSolver\");\n\n SNESConvergedReason reason;\n SNESGetConvergedReason(_snes, &reason);\n\n this->clear();\n\n return convert_solve_result(reason);\n}\n\n\n} \/\/ namespace libMesh\n\n#endif \/\/ LIBMESH_HAVE_PETSC\nFix syntax for missing-default warning fix\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n#include \"libmesh\/diff_system.h\"\n#include \"libmesh\/dof_map.h\"\n#include \"libmesh\/libmesh_logging.h\"\n#include \"libmesh\/petsc_diff_solver.h\"\n#include \"libmesh\/petsc_matrix.h\"\n#include \"libmesh\/petsc_vector.h\"\n#include \"libmesh\/petsc_auto_fieldsplit.h\"\n\n#ifdef LIBMESH_HAVE_PETSC\n\nnamespace libMesh\n{\n\n\/\/--------------------------------------------------------------------\n\/\/ Functions with C linkage to pass to PETSc. PETSc will call these\n\/\/ methods as needed.\n\/\/\n\/\/ Since they must have C linkage they have no knowledge of a namespace.\n\/\/ Give them an obscure name to avoid namespace pollution.\nextern \"C\"\n{\n \/\/ Older versions of PETSc do not have the different int typedefs.\n \/\/ On 64-bit machines, PetscInt may actually be a long long int.\n \/\/ This change occurred in Petsc-2.2.1.\n#if PETSC_VERSION_LESS_THAN(2,2,1)\n typedef int PetscErrorCode;\n typedef int PetscInt;\n#endif\n\n \/\/ Function to hand to PETSc's SNES,\n \/\/ which monitors convergence at X\n PetscErrorCode\n __libmesh_petsc_diff_solver_monitor (SNES snes, PetscInt its,\n PetscReal fnorm, void *ctx)\n {\n PetscDiffSolver& solver =\n *(static_cast (ctx));\n\n if (solver.verbose)\n libMesh::out << \" PetscDiffSolver step \" << its\n << \", |residual|_2 = \" << fnorm << std::endl;\n if (solver.linear_solution_monitor.get()) {\n int ierr = 0;\n\n Vec petsc_delta_u;\n ierr = SNESGetSolutionUpdate(snes, &petsc_delta_u);\n CHKERRABORT(solver.comm().get(), ierr);\n PetscVector delta_u(petsc_delta_u, solver.comm());\n delta_u.close();\n\n Vec petsc_u;\n ierr = SNESGetSolution(snes, &petsc_u);\n CHKERRABORT(solver.comm().get(), ierr);\n PetscVector u(petsc_u, solver.comm());\n u.close();\n\n Vec petsc_res;\n ierr = SNESGetFunction(snes, &petsc_res, NULL, NULL);\n CHKERRABORT(solver.comm().get(), ierr);\n PetscVector res(petsc_res, solver.comm());\n res.close();\n\n (*solver.linear_solution_monitor)(\n delta_u, delta_u.l2_norm(),\n u, u.l2_norm(),\n res, res.l2_norm(), its);\n }\n return 0;\n }\n\n \/\/ Functions to hand to PETSc's SNES,\n \/\/ which compute the residual or jacobian at X\n PetscErrorCode\n __libmesh_petsc_diff_solver_residual (SNES, Vec x, Vec r, void *ctx)\n {\n libmesh_assert(x);\n libmesh_assert(r);\n libmesh_assert(ctx);\n\n PetscDiffSolver& solver =\n *(static_cast (ctx));\n ImplicitSystem &sys = solver.system();\n\n if (solver.verbose)\n libMesh::out << \"Assembling the residual\" << std::endl;\n\n PetscVector& X_system =\n *cast_ptr*>(sys.solution.get());\n PetscVector& R_system =\n *cast_ptr*>(sys.rhs);\n PetscVector X_input(x, sys.comm()), R_input(r, sys.comm());\n\n \/\/ DiffSystem assembles from the solution and into the rhs, so swap\n \/\/ those with our input vectors before assembling. They'll probably\n \/\/ already be references to the same vectors, but PETSc might do\n \/\/ something tricky.\n X_input.swap(X_system);\n R_input.swap(R_system);\n\n \/\/ We may need to correct a non-conforming solution\n sys.get_dof_map().enforce_constraints_exactly(sys);\n\n \/\/ We may need to localize a parallel solution\n sys.update();\n\n \/\/ Do DiffSystem assembly\n sys.assembly(true, false);\n R_system.close();\n\n \/\/ Swap back\n X_input.swap(X_system);\n R_input.swap(R_system);\n\n \/\/ No errors, we hope\n return 0;\n }\n\n\n#if PETSC_RELEASE_LESS_THAN(3,5,0)\nPetscErrorCode\n__libmesh_petsc_diff_solver_jacobian (SNES, Vec x, Mat *libmesh_dbg_var(j), Mat *pc,\n MatStructure *msflag, void *ctx)\n#else\nPetscErrorCode\n__libmesh_petsc_diff_solver_jacobian (SNES, Vec x, Mat libmesh_dbg_var(j), Mat pc,\n void *ctx)\n#endif\n{\n libmesh_assert(x);\n libmesh_assert(j);\n\/\/ libmesh_assert_equal_to (pc, j); \/\/ We don't use separate preconditioners yet\n libmesh_assert(ctx);\n\n PetscDiffSolver& solver =\n *(static_cast (ctx));\n ImplicitSystem &sys = solver.system();\n\n if (solver.verbose)\n libMesh::out << \"Assembling the Jacobian\" << std::endl;\n\n PetscVector& X_system =\n *cast_ptr*>(sys.solution.get());\n PetscVector X_input(x, sys.comm());\n\n#if PETSC_RELEASE_LESS_THAN(3,5,0)\n PetscMatrix J_input(*pc, sys.comm());\n#else\n PetscMatrix J_input(pc, sys.comm());\n#endif\n PetscMatrix& J_system =\n *cast_ptr*>(sys.matrix);\n\n \/\/ DiffSystem assembles from the solution and into the jacobian, so\n \/\/ swap those with our input vectors before assembling. They'll\n \/\/ probably already be references to the same vectors, but PETSc\n \/\/ might do something tricky.\n X_input.swap(X_system);\n J_input.swap(J_system);\n\n \/\/ We may need to correct a non-conforming solution\n sys.get_dof_map().enforce_constraints_exactly(sys);\n\n \/\/ We may need to localize a parallel solution\n sys.update();\n\n \/\/ Do DiffSystem assembly\n sys.assembly(false, true);\n J_system.close();\n\n \/\/ Swap back\n X_input.swap(X_system);\n J_input.swap(J_system);\n\n#if PETSC_RELEASE_LESS_THAN(3,5,0)\n *msflag = SAME_NONZERO_PATTERN;\n#endif\n \/\/ No errors, we hope\n return 0;\n}\n\n} \/\/ extern \"C\"\n\n\nPetscDiffSolver::PetscDiffSolver (sys_type& s)\n : Parent(s)\n{\n}\n\n\nvoid PetscDiffSolver::init ()\n{\n START_LOG(\"init()\", \"PetscDiffSolver\");\n\n Parent::init();\n\n int ierr=0;\n\n#if PETSC_VERSION_LESS_THAN(2,1,2)\n \/\/ At least until Petsc 2.1.1, the SNESCreate had a different\n \/\/ calling syntax. The second argument was of type SNESProblemType,\n \/\/ and could have a value of either SNES_NONLINEAR_EQUATIONS or\n \/\/ SNES_UNCONSTRAINED_MINIMIZATION.\n ierr = SNESCreate(this->comm().get(), SNES_NONLINEAR_EQUATIONS, &_snes);\n LIBMESH_CHKERRABORT(ierr);\n#else\n ierr = SNESCreate(this->comm().get(),&_snes);\n LIBMESH_CHKERRABORT(ierr);\n#endif\n\n#if PETSC_VERSION_LESS_THAN(2,3,3)\n ierr = SNESSetMonitor (_snes, __libmesh_petsc_diff_solver_monitor,\n this, PETSC_NULL);\n#else\n \/\/ API name change in PETSc 2.3.3\n ierr = SNESMonitorSet (_snes, __libmesh_petsc_diff_solver_monitor,\n this, PETSC_NULL);\n#endif\n LIBMESH_CHKERRABORT(ierr);\n\n if (libMesh::on_command_line(\"--solver_system_names\"))\n {\n ierr = SNESSetOptionsPrefix(_snes, (_system.name()+\"_\").c_str());\n LIBMESH_CHKERRABORT(ierr);\n }\n\n ierr = SNESSetFromOptions(_snes);\n LIBMESH_CHKERRABORT(ierr);\n\n KSP my_ksp;\n ierr = SNESGetKSP(_snes, &my_ksp);\n LIBMESH_CHKERRABORT(ierr);\n\n PC my_pc;\n ierr = KSPGetPC(my_ksp, &my_pc);\n LIBMESH_CHKERRABORT(ierr);\n\n petsc_auto_fieldsplit(my_pc, _system);\n\n STOP_LOG(\"init()\", \"PetscDiffSolver\");\n}\n\n\n\nPetscDiffSolver::~PetscDiffSolver ()\n{\n}\n\n\n\nvoid PetscDiffSolver::clear()\n{\n START_LOG(\"clear()\", \"PetscDiffSolver\");\n\n int ierr = LibMeshSNESDestroy(&_snes);\n LIBMESH_CHKERRABORT(ierr);\n\n STOP_LOG(\"clear()\", \"PetscDiffSolver\");\n}\n\n\n\nvoid PetscDiffSolver::reinit()\n{\n Parent::reinit();\n\n KSP my_ksp;\n int ierr = SNESGetKSP(_snes, &my_ksp);\n LIBMESH_CHKERRABORT(ierr);\n\n PC my_pc;\n ierr = KSPGetPC(my_ksp, &my_pc);\n LIBMESH_CHKERRABORT(ierr);\n\n petsc_auto_fieldsplit(my_pc, _system);\n}\n\n\n\nDiffSolver::SolveResult convert_solve_result(SNESConvergedReason r)\n{\n switch (r)\n {\n case SNES_CONVERGED_FNORM_ABS:\n return DiffSolver::CONVERGED_ABSOLUTE_RESIDUAL;\n case SNES_CONVERGED_FNORM_RELATIVE:\n return DiffSolver::CONVERGED_RELATIVE_RESIDUAL;\n#if PETSC_VERSION_LESS_THAN(3,2,1)\n case SNES_CONVERGED_PNORM_RELATIVE:\n#else\n case SNES_CONVERGED_SNORM_RELATIVE:\n#endif\n return DiffSolver::CONVERGED_RELATIVE_STEP;\n#if !PETSC_VERSION_LESS_THAN(2,3,3)\n case SNES_CONVERGED_ITS:\n#endif\n case SNES_CONVERGED_TR_DELTA:\n return DiffSolver::CONVERGED_NO_REASON;\n case SNES_DIVERGED_FUNCTION_DOMAIN:\n case SNES_DIVERGED_FUNCTION_COUNT:\n case SNES_DIVERGED_FNORM_NAN:\n#if !PETSC_VERSION_LESS_THAN(3,3,0)\n case SNES_DIVERGED_INNER:\n#endif\n#if !PETSC_VERSION_LESS_THAN(2,3,2)\n case SNES_DIVERGED_LINEAR_SOLVE:\n#endif\n case SNES_DIVERGED_LOCAL_MIN:\n return DiffSolver::DIVERGED_NO_REASON;\n case SNES_DIVERGED_MAX_IT:\n return DiffSolver::DIVERGED_MAX_NONLINEAR_ITERATIONS;\n#if PETSC_VERSION_LESS_THAN(3,2,0)\n case SNES_DIVERGED_LS_FAILURE:\n#else\n case SNES_DIVERGED_LINE_SEARCH:\n#endif\n return DiffSolver::DIVERGED_BACKTRACKING_FAILURE;\n \/\/ In PETSc, SNES_CONVERGED_ITERATING means\n \/\/ the solve is still iterating, but by the\n \/\/ time we get here, we must have either\n \/\/ converged or diverged, so\n \/\/ SNES_CONVERGED_ITERATING is invalid.\n case SNES_CONVERGED_ITERATING:\n return DiffSolver::INVALID_SOLVE_RESULT;\n default:\n break;\n }\n return DiffSolver::INVALID_SOLVE_RESULT;\n}\n\n\n\nunsigned int PetscDiffSolver::solve()\n{\n this->init();\n\n START_LOG(\"solve()\", \"PetscDiffSolver\");\n\n PetscVector &x =\n *(cast_ptr*>(_system.solution.get()));\n PetscMatrix &jac =\n *(cast_ptr*>(_system.matrix));\n PetscVector &r =\n *(cast_ptr*>(_system.rhs));\n\n#ifdef LIBMESH_ENABLE_CONSTRAINTS\n _system.get_dof_map().enforce_constraints_exactly(_system);\n#endif\n\n int ierr = 0;\n\n ierr = SNESSetFunction (_snes, r.vec(),\n __libmesh_petsc_diff_solver_residual, this);\n LIBMESH_CHKERRABORT(ierr);\n\n ierr = SNESSetJacobian (_snes, jac.mat(), jac.mat(),\n __libmesh_petsc_diff_solver_jacobian, this);\n LIBMESH_CHKERRABORT(ierr);\n\n# if PETSC_VERSION_LESS_THAN(2,2,0)\n\n ierr = SNESSolve (_snes, x.vec(), &_outer_iterations);\n LIBMESH_CHKERRABORT(ierr);\n\n \/\/ 2.2.x style\n#elif PETSC_VERSION_LESS_THAN(2,3,0)\n\n ierr = SNESSolve (_snes, x.vec());\n LIBMESH_CHKERRABORT(ierr);\n\n \/\/ 2.3.x & newer style\n#else\n\n ierr = SNESSolve (_snes, PETSC_NULL, x.vec());\n LIBMESH_CHKERRABORT(ierr);\n\n#endif\n\n STOP_LOG(\"solve()\", \"PetscDiffSolver\");\n\n SNESConvergedReason reason;\n SNESGetConvergedReason(_snes, &reason);\n\n this->clear();\n\n return convert_solve_result(reason);\n}\n\n\n} \/\/ namespace libMesh\n\n#endif \/\/ LIBMESH_HAVE_PETSC\n<|endoftext|>"} {"text":"\n#include \"application.h\"\nSYSTEM_MODE(MANUAL);\n\n#include \"rgbled.h\"\n\n#include \"RHT03.h\"\n#include \"TMP3x.h\"\n#include \"OledDisplay.h\"\n#include \"font_lcd6x8.h\"\n#include \"font_lcd11x16.h\"\n#include \"font_12x16_bold.h\"\n#include \"common.h\"\n\n\/\/ function prototypes\nvoid drawPattern();\nvoid drawText();\nvoid drawTemp();\nvoid getTemp();\n\nint btnUp = D6;\nint btnDn = D5;\nint btnHome = D3;\n\nbool btnUpLatch = false;\nbool btnDnLatch = false;\nbool btnHomeLatch = false;\n\ndouble avgTemp = 0.0;\n\nuint drawMode = 0;\nuint textMode = 0;\n\nOledDisplay display = OledDisplay(D1, D2, D0);;\nRHT03 rht = RHT03(D4, D7);\nTMP3x tmp36 = TMP3x(A0, 10, 1000);\n\nconst font_t* font_lcdSm = parseFont(FONT_LCD6X8);\nconst font_t* font_lcdLg = parseFont(FONT_LCD11X16);\nconst font_t* font_bold = parseFont(FONT_12X16_BOLD);\n\nvoid setup() {\n\n pinMode(btnUp, INPUT_PULLUP);\n pinMode(btnDn, INPUT_PULLUP);\n pinMode(btnHome, INPUT_PULLUP);\n\n \/\/ Spark.variable(\"reading\", &reading, DOUBLE);\n \/\/ Spark.variable(\"volts\", &volts, DOUBLE);\n \/\/ Spark.variable(\"temp\", &avgTemp, DOUBLE);\n\n RGB.control(true);\n RGB.color(0, 0, 0);\n\n display.begin();\n}\n\nvoid loop() {\n tmp36.poll();\n if (rht.poll()) {\n drawTemp();\n }\n\n \/\/ curTime = millis();\n \/\/ \/\/ get temp once per second\n \/\/ if (lastTime + 3000 < curTime) {\n \/\/ lastTime = curTime;\n \/\/ display.clear(CLEAR_OLED);\n \/\/ drawTemp();\n \/\/ }\n\n if (digitalRead(btnHome) == LOW) {\n if (btnHomeLatch) { \/\/ only draw once per press\n drawPattern();\n btnHomeLatch = false;\n }\n } else {\n btnHomeLatch = true;\n }\n\n if (digitalRead(btnUp) == LOW) {\n RGB.color(0,0,255);\n if (btnUpLatch) { \/\/ only draw once per press\n drawTemp();\n btnUpLatch = false;\n }\n } else {\n btnUpLatch = true;\n }\n\n if (digitalRead(btnDn) == LOW) {\n RGB.color(255,0,0);\n if (btnDnLatch) { \/\/ only draw once per press\n drawText();\n btnDnLatch = false;\n }\n } else {\n btnDnLatch = true;\n }\n}\n\nvoid initStat() {\n}\n\nvoid drawTemp() {\n display.clear(CLEAR_OLED);\n display.setFont(font_lcdLg);\n char tempStr[8];\n\n double ftemp = tmp36.getTempF();\n ftemp = (ftemp \/ 10);\n\n sprintf(tempStr, \"%.1f\\x7f\", ftemp);\n display.writeText(0, 0, tempStr);\n\n ftemp = rht.getTempF();\n ftemp = ftemp \/ 10;\n sprintf(tempStr, \"%.1f\\x7f\", ftemp);\n display.writeText(0, 1, tempStr);\n\n ftemp = rht.getRH();\n ftemp = ftemp \/ 10;\n sprintf(tempStr, \"%.1f%%\", ftemp);\n display.writeText(0, 2, tempStr);\n\n \/\/ sprintf(tempStr, \"%d.%d \", rht.getIntCount(), rht.getIgnCount());\n \/\/ display.writeText(1, 4, tempStr);\n display.display();\n}\n\nvoid drawPattern() {\n display.resetPage();\n\n switch (drawMode) {\n case 0: \/\/ blank page\n RGB.color(255,0,0);\n display.clear(CLEAR_BUFF);\n break;\n case 1: \/\/ horizontal lines\n RGB.color(0,255,0);\n display.fill(0xaa);\n break;\n case 2: \/\/ vertical lines\n RGB.color(0,0,255);\n for (int i=0; i<6; i++) {\n for (int j=0; j<32; j++) {\n int c = j*2;\n display.setByte(i, c, 0xff);\n display.setByte(i, c+1, 0x00);\n }\n }\n break;\n case 3: {\/\/ count\n RGB.color(255,255,0);\n byte val = 0x00;\n for (int i=0; i<6; i++) {\n for (int j=0; j<64; j++) {\n display.setByte(i, j, val++);\n if (val > 0xff) val = 0x00;\n }\n }\n break;\n }\n case 4: \/\/ diagnal lines\n RGB.color(255,0,255);\n for (int i=0; i<6; i++) {\n for (int j=0; j<8; j++) {\n int c = j*8;\n display.setByte(i, c, 0x01);\n display.setByte(i, c+1, 0x02);\n display.setByte(i, c+2, 0x04);\n display.setByte(i, c+3, 0x08);\n display.setByte(i, c+4, 0x10);\n display.setByte(i, c+5, 0x20);\n display.setByte(i, c+6, 0x40);\n display.setByte(i, c+7, 0x80);\n }\n }\n break;\n case 5: \/\/ progression\n RGB.color(0,255,255);\n for (int i=0; i<6; i++) {\n for (int j=0; j<8; j++) {\n int c = j*8;\n display.setByte(i, c, 0x01);\n display.setByte(i, c+1, 0x03);\n display.setByte(i, c+2, 0x07);\n display.setByte(i, c+3, 0x0f);\n display.setByte(i, c+4, 0x1f);\n display.setByte(i, c+5, 0x3f);\n display.setByte(i, c+6, 0x7f);\n display.setByte(i, c+7, 0xff);\n }\n }\n break;\n }\n display.display();\n\n drawMode += 1;\n if (drawMode > 5) {\n drawMode = 0;\n }\n}\n\nvoid drawText() {\n display.clear(CLEAR_OLED);\n \/\/ display.setFont(textMode);\n switch (textMode) {\n case 0: \/\/ small\n case 1: \/\/ med\n case 2: \/\/ bold\n \/\/ RGB.color(textMode==0?255:0, textMode==0?0:255, 0);\n display.writeText(0, 0, \"12345\");\n display.writeText(0, 1, \"Hello\");\n display.writeText(0, 2, \"World\");\n break;\n case 3: \/\/ large\n case 4:\n case 5:\n \/\/ RGB.color(0,0,255);\n display.writeText(0, 0, \"12345\");\n if (textMode < 5) {\n display.writeText(0, 1, \"67890\");\n }\n break;\n }\n\n textMode += 1;\n if (textMode > 5) {\n textMode = 0;\n }\n}\nUse new buttons, layout screen, general cleanup\n#include \"application.h\"\nSYSTEM_MODE(MANUAL);\n\n#include \"rgbled.h\"\n\n#include \"common.h\"\n#include \"RHT03.h\"\n#include \"ButtonInterrupt.h\"\n#include \"OledDisplay.h\"\n#include \"font_lcd6x8.h\"\n#include \"font_lcd11x16.h\"\n\n\/\/ function prototypes\nvoid drawPattern();\nvoid drawText();\nvoid drawTemp();\nvoid drawSetTemp();\nvoid getTemp();\nvoid handleButtonHome(int mode);\nvoid handleButtonUp(int mode);\nvoid handleButtonDn(int mode);\n\n#define DRAW_CUR_TEMP 1\n#define DRAW_SET_TEMP 1\n#define DRAW_MENU 2\n\n#define PUFFIN_DEBUG true\n\nbool btnHomeToggle = false;\n\nint curTemp = 0;\nint curRH = 0;\nint setTemp = 72;\nint setRH = 30;\n\nuint drawMode = DRAW_CUR_TEMP;\nuint textMode = 0;\n\nOledDisplay *display;\nRHT03 *rht;\nButtonInterrupt *btnHome;\nButtonInterrupt *btnUp;\nButtonInterrupt *btnDn;\n\nconst font_t* font_lcdSm = parseFont(FONT_LCD6X8);\nconst font_t* font_lcdLg = parseFont(FONT_LCD11X16);\n\nvoid setup() {\n#ifdef PUFFIN_DEBUG\n Serial.begin(9600);\n#endif\n\n pinMode(D7, OUTPUT);\n digitalWrite(D7, LOW);\n\n RGB.control(true);\n RGB.color(0, 0, 0);\n\n display = new OledDisplay(D1, D2, D0);\n display->begin();\n\n rht = new RHT03(D3);\n\n btnHome = new ButtonInterrupt(D4, 100, &handleButtonHome, 2000, 250);\n btnUp = new ButtonInterrupt(D6, 100, &handleButtonUp, 2000, 250);\n btnDn = new ButtonInterrupt(D5, 100, &handleButtonDn, 2000, 250);\n}\n\nvoid loop() {\n if (rht->poll()) {\n getTemp();\n if (drawMode == DRAW_CUR_TEMP) {\n drawTemp();\n }\n }\n\n btnHome->poll();\n btnUp->poll();\n btnDn->poll();\n}\n\nvoid initStat() {\n}\n\nvoid handleButtonHome(int mode) {\n switch(mode) {\n case UP:\n digitalWrite(D7, LOW);\n break;\n\n case FIRST:\n digitalWrite(D7, HIGH);\n btnHomeToggle = true;\n break;\n\n case REPEAT:\n digitalWrite(D7, btnHomeToggle ? HIGH : LOW);\n btnHomeToggle = !btnHomeToggle;\n break;\n\n default:\n break;\n }\n}\n\nvoid handleButtonUp(int mode) {\n switch(mode) {\n case FIRST:\n case REPEAT:\n setTemp++;\n drawSetTemp();\n break;\n\n default:\n break;\n }\n}\n\nvoid handleButtonDn(int mode) {\n switch(mode) {\n case FIRST:\n case REPEAT:\n setTemp--;\n drawSetTemp();\n break;\n\n default:\n break;\n }\n}\n\nvoid getTemp() {\n curTemp = rht->getTempF();\n curRH = rht->getRH();\n \/\/ TODO: Send to server\n}\n\nvoid drawTemp() {\n \/\/ todo: do this only once\n display->clear(CLEAR_BUFF);\n\n display->setFont(font_lcdLg);\n char tempStr[8];\n\n int ftemp = curTemp;\n int fdec = ftemp % 10;\n ftemp = ftemp \/ 10;\n\n display->setFont(font_lcdLg);\n sprintf(tempStr, \"%d.\", ftemp);\n display->writeText(0, 0, tempStr);\n display->setFont(font_lcdSm);\n sprintf(tempStr, \"%d\", fdec);\n display->writeText(5, 1, tempStr);\n\n int rh = curRH;\n int rhdec = rh % 10;\n rh = rh \/ 10;\n display->setFont(font_lcdLg);\n sprintf(tempStr, \"%d.\", rh);\n display->writeText(0, 1, tempStr);\n display->setFont(font_lcdSm);\n sprintf(tempStr, \"%d%%\", rhdec);\n display->writeText(5, 3, tempStr);\n\n display->setFont(font_lcdSm);\n const char *curDate = \"10\/14\";\n const char *curTime = \"12:34\";\n display->writeText(0, 5, curDate);\n display->writeText(6, 5, curTime, -3);\n\n sprintf(tempStr, \"%d\", setTemp);\n display->writeText(8, 0, tempStr, 4);\n sprintf(tempStr, \"%d\", setRH);\n display->writeText(8, 2, tempStr, 4);\n\n display->display();\n}\n\nvoid drawSetTemp() {\n char tempStr[8];\n\n sprintf(tempStr, \"%d\", setTemp);\n display->writeText(8, 0, tempStr, 4);\n sprintf(tempStr, \"%d\", setRH);\n display->writeText(8, 2, tempStr, 4);\n\n display->display();\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ (c) Copyright 2017 DESY,ESS\n\/\/\n\/\/ This file is part of h5cpp.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or modify it\n\/\/ under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation; either version 2.1 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY\n\/\/ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n\/\/ License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this library; if not, write to the\n\/\/ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor\n\/\/ Boston, MA 02110-1301 USA\n\/\/ ===========================================================================\n\/\/\n\/\/ Authors:\n\/\/ Eugen Wintersberger \n\/\/ Martin Shetty \n\/\/ Created on: May 14, 2018\n\/\/\n\n#include \n#include \n#include \n\nnamespace hdf5\n{\nnamespace datatype\n{\n\nEnum::Enum(ObjectHandle&& handle) :\n Datatype(std::move(handle)) {}\n\nEnum::Enum(const Datatype& type) :\n Datatype(type)\n{\n if (get_class() != Class::ENUM)\n {\n std::stringstream ss;\n ss << \"Cannot create Enum datatype from \" << get_class();\n throw std::runtime_error(ss.str());\n }\n}\n\nEnum Enum::create_underlying(const Datatype& base_type)\n{\n hid_t ret = H5Tenum_create(static_cast(base_type));\n if (ret < 0)\n {\n std::stringstream ss;\n ss << \"Could not create Enum of base type =\" << base_type.get_class();\n error::Singleton::instance().throw_with_stack(ss.str());\n }\n return Enum(ObjectHandle(ret));\n}\n\n\/\/ implementation same as for Compound\nsize_t Enum::number_of_values() const\n{\n int n = H5Tget_nmembers(static_cast(*this));\n if (n < 0)\n {\n error::Singleton::instance().throw_with_stack(\"Could not retrieve number of values for enum data type!\");\n }\n return static_cast(n);\n}\n\n\/\/ implementation same as for Compound\nstd::string Enum::name(size_t index) const\n{\n char *buffer = H5Tget_member_name(static_cast(*this), static_cast(index));\n if (buffer == nullptr) {\n std::stringstream ss;\n ss << \"Failure to obtain name of value [\" << index << \"] in enum data type!\";\n error::Singleton::instance().throw_with_stack(ss.str());\n }\n std::string name(buffer);\n\n if (H5free_memory(buffer) < 0) {\n std::stringstream ss;\n ss << \"Failure freeing memory for name buffer of field [\" << index << \"]\"\n << \" in enum data type!\";\n error::Singleton::instance().throw_with_stack(ss.str());\n }\n return name;\n}\n\nbool is_bool(const Enum & etype){\n int s = etype.number_of_values();\n if (s < 0) {\n error::Singleton::instance().throw_with_stack(\"Could not retrieve datatype\");\n return false;\n }\n if(s != 2){\n return false;\n }\n if(etype.name(0) != \"FALSE\"){\n return false;\n }\n if(etype.name(1) != \"TRUE\"){\n return false;\n }\n return true;\n}\n\n\n} \/\/ namespace datatype\n} \/\/ namespace hdf5\nremove duplicated checks\/\/\n\/\/ (c) Copyright 2017 DESY,ESS\n\/\/\n\/\/ This file is part of h5cpp.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or modify it\n\/\/ under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation; either version 2.1 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY\n\/\/ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n\/\/ License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this library; if not, write to the\n\/\/ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor\n\/\/ Boston, MA 02110-1301 USA\n\/\/ ===========================================================================\n\/\/\n\/\/ Authors:\n\/\/ Eugen Wintersberger \n\/\/ Martin Shetty \n\/\/ Created on: May 14, 2018\n\/\/\n\n#include \n#include \n#include \n\nnamespace hdf5\n{\nnamespace datatype\n{\n\nEnum::Enum(ObjectHandle&& handle) :\n Datatype(std::move(handle)) {}\n\nEnum::Enum(const Datatype& type) :\n Datatype(type)\n{\n if (get_class() != Class::ENUM)\n {\n std::stringstream ss;\n ss << \"Cannot create Enum datatype from \" << get_class();\n throw std::runtime_error(ss.str());\n }\n}\n\nEnum Enum::create_underlying(const Datatype& base_type)\n{\n hid_t ret = H5Tenum_create(static_cast(base_type));\n if (ret < 0)\n {\n std::stringstream ss;\n ss << \"Could not create Enum of base type =\" << base_type.get_class();\n error::Singleton::instance().throw_with_stack(ss.str());\n }\n return Enum(ObjectHandle(ret));\n}\n\n\/\/ implementation same as for Compound\nsize_t Enum::number_of_values() const\n{\n int n = H5Tget_nmembers(static_cast(*this));\n if (n < 0)\n {\n error::Singleton::instance().throw_with_stack(\"Could not retrieve number of values for enum data type!\");\n }\n return static_cast(n);\n}\n\n\/\/ implementation same as for Compound\nstd::string Enum::name(size_t index) const\n{\n char *buffer = H5Tget_member_name(static_cast(*this), static_cast(index));\n if (buffer == nullptr) {\n std::stringstream ss;\n ss << \"Failure to obtain name of value [\" << index << \"] in enum data type!\";\n error::Singleton::instance().throw_with_stack(ss.str());\n }\n std::string name(buffer);\n\n if (H5free_memory(buffer) < 0) {\n std::stringstream ss;\n ss << \"Failure freeing memory for name buffer of field [\" << index << \"]\"\n << \" in enum data type!\";\n error::Singleton::instance().throw_with_stack(ss.str());\n }\n return name;\n}\n\nbool is_bool(const Enum & etype){\n int s = etype.number_of_values();\n if(s != 2){\n return false;\n }\n if(etype.name(0) != \"FALSE\"){\n return false;\n }\n if(etype.name(1) != \"TRUE\"){\n return false;\n }\n return true;\n}\n\n\n} \/\/ namespace datatype\n} \/\/ namespace hdf5\n<|endoftext|>"} {"text":"#include \"core\/global.h\"\n#include \"core\/messages.h\"\n#include \n#include \n\n#include \"DistributedObject.h\"\n#include \"StateServer.h\"\n\n\nConfigVariable cfg_channel(\"control\", 0);\n\nStateServer::StateServer(RoleConfig roleconfig) : Role(roleconfig)\n{\n\tchannel_t channel = cfg_channel.get_rval(m_roleconfig);\n\tMessageDirector::singleton.subscribe_channel(this, channel);\n\n\tstd::stringstream name;\n\tname << \"StateServer(\" << channel << \")\";\n\tm_log = new LogCategory(\"stateserver\", name.str());\n}\n\nStateServer::~StateServer()\n{\n\tdelete m_log;\n}\n\nvoid StateServer::handle_generate(DatagramIterator &dgi, bool has_other)\n{\n\tunsigned int parent_id = dgi.read_uint32();\n\tunsigned int zone_id = dgi.read_uint32();\n\tunsigned short dc_id = dgi.read_uint16();\n\tunsigned int do_id = dgi.read_uint32();\n\n\tif(dc_id >= gDCF->get_num_classes())\n\t{\n\t\tm_log->error() << \"Received create for unknown dclass ID=\" << dc_id << std::endl;\n\t\treturn;\n\t}\n\n\tif(m_objs.find(do_id) != m_objs.end())\n\t{\n\t\tm_log->warning() << \"Received generate for already-existing object ID=\" << do_id << std::endl;\n\t\treturn;\n\t}\n\n\tDCClass *dclass = gDCF->get_class(dc_id);\n\tDistributedObject *obj;\n\ttry\n\t{\n\t\tobj = new DistributedObject(this, do_id, dclass, parent_id, zone_id, dgi, has_other);\n\t}\n\tcatch(std::exception &e)\n\t{\n\t\tm_log->error() << \"Received truncated generate for \"\n\t\t << dclass->get_name() << \"(\" << do_id << \")\" << std::endl;\n\t\treturn;\n\t}\n\tm_objs[do_id] = obj;\n}\n\nvoid StateServer::handle_datagram(Datagram &in_dg, DatagramIterator &dgi)\n{\n\tchannel_t sender = dgi.read_uint64();\n\tunsigned short msgtype = dgi.read_uint16();\n\tswitch(msgtype)\n\t{\n\t\tcase STATESERVER_OBJECT_GENERATE_WITH_REQUIRED:\n\t\t{\n\t\t\thandle_generate(dgi, false);\n\t\t\tbreak;\n\t\t}\n\t\tcase STATESERVER_OBJECT_GENERATE_WITH_REQUIRED_OTHER:\n\t\t{\n\t\t\thandle_generate(dgi, true);\n\t\t\tbreak;\n\t\t}\n\t\tcase STATESERVER_SHARD_RESET:\n\t\t{\n\t\t\tchannel_t ai_channel = dgi.read_uint64();\n\t\t\tstd::set targets;\n\t\t\tfor(auto it = m_objs.begin(); it != m_objs.end(); ++it)\n\t\t\t\tif(it->second && it->second->m_ai_channel == ai_channel && it->second->m_ai_explicitly_set)\n\t\t\t\t\ttargets.insert(it->second->m_do_id);\n\n\t\t\tif(targets.size())\n\t\t\t{\n\t\t\t\tDatagram dg(targets, sender, STATESERVER_SHARD_RESET);\n\t\t\t\tdg.add_uint64(ai_channel);\n\t\t\t\tsend(dg);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tm_log->warning() << \"Received unknown message: msgtype=\" << msgtype << std::endl;\n\t}\n}\n\nRoleFactoryItem ss_fact(\"stateserver\");\nStateServer: Fixed includes for clarity, from deletion in unpack_field#include \"core\/global.h\"\n#include \"core\/messages.h\"\n#include \"dcparser\/dcClass.h\"\n#include \n#include \n\n#include \"DistributedObject.h\"\n#include \"StateServer.h\"\n\n\nConfigVariable cfg_channel(\"control\", 0);\n\nStateServer::StateServer(RoleConfig roleconfig) : Role(roleconfig)\n{\n\tchannel_t channel = cfg_channel.get_rval(m_roleconfig);\n\tMessageDirector::singleton.subscribe_channel(this, channel);\n\n\tstd::stringstream name;\n\tname << \"StateServer(\" << channel << \")\";\n\tm_log = new LogCategory(\"stateserver\", name.str());\n}\n\nStateServer::~StateServer()\n{\n\tdelete m_log;\n}\n\nvoid StateServer::handle_generate(DatagramIterator &dgi, bool has_other)\n{\n\tunsigned int parent_id = dgi.read_uint32();\n\tunsigned int zone_id = dgi.read_uint32();\n\tunsigned short dc_id = dgi.read_uint16();\n\tunsigned int do_id = dgi.read_uint32();\n\n\tif(dc_id >= gDCF->get_num_classes())\n\t{\n\t\tm_log->error() << \"Received create for unknown dclass ID=\" << dc_id << std::endl;\n\t\treturn;\n\t}\n\n\tif(m_objs.find(do_id) != m_objs.end())\n\t{\n\t\tm_log->warning() << \"Received generate for already-existing object ID=\" << do_id << std::endl;\n\t\treturn;\n\t}\n\n\tDCClass *dclass = gDCF->get_class(dc_id);\n\tDistributedObject *obj;\n\ttry\n\t{\n\t\tobj = new DistributedObject(this, do_id, dclass, parent_id, zone_id, dgi, has_other);\n\t}\n\tcatch(std::exception &e)\n\t{\n\t\tm_log->error() << \"Received truncated generate for \"\n\t\t << dclass->get_name() << \"(\" << do_id << \")\" << std::endl;\n\t\treturn;\n\t}\n\tm_objs[do_id] = obj;\n}\n\nvoid StateServer::handle_datagram(Datagram &in_dg, DatagramIterator &dgi)\n{\n\tchannel_t sender = dgi.read_uint64();\n\tunsigned short msgtype = dgi.read_uint16();\n\tswitch(msgtype)\n\t{\n\t\tcase STATESERVER_OBJECT_GENERATE_WITH_REQUIRED:\n\t\t{\n\t\t\thandle_generate(dgi, false);\n\t\t\tbreak;\n\t\t}\n\t\tcase STATESERVER_OBJECT_GENERATE_WITH_REQUIRED_OTHER:\n\t\t{\n\t\t\thandle_generate(dgi, true);\n\t\t\tbreak;\n\t\t}\n\t\tcase STATESERVER_SHARD_RESET:\n\t\t{\n\t\t\tchannel_t ai_channel = dgi.read_uint64();\n\t\t\tstd::set targets;\n\t\t\tfor(auto it = m_objs.begin(); it != m_objs.end(); ++it)\n\t\t\t\tif(it->second && it->second->m_ai_channel == ai_channel && it->second->m_ai_explicitly_set)\n\t\t\t\t\ttargets.insert(it->second->m_do_id);\n\n\t\t\tif(targets.size())\n\t\t\t{\n\t\t\t\tDatagram dg(targets, sender, STATESERVER_SHARD_RESET);\n\t\t\t\tdg.add_uint64(ai_channel);\n\t\t\t\tsend(dg);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tm_log->warning() << \"Received unknown message: msgtype=\" << msgtype << std::endl;\n\t}\n}\n\nRoleFactoryItem ss_fact(\"stateserver\");\n<|endoftext|>"} {"text":"\/*\n * Copyright 2006-2011 The FLWOR Foundation.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"json_loader.h\"\n#include \"util\/json_parser.h\"\n#include \"json_items.h\"\n#include \"simple_item_factory.h\"\n#include \"store_defs.h\"\n#include \"simple_store.h\"\n#include \n#include \n\nnamespace zorba\n{\n\nnamespace simplestore\n{\n\nnamespace json\n{\n\n\n\/******************************************************************************\n\n*******************************************************************************\/\nJSONLoader::JSONLoader(std::istream& s)\n : in(s)\n{\n}\n\n\n\/******************************************************************************\n\n*******************************************************************************\/\nJSONLoader::~JSONLoader()\n{\n}\n\n\n\/******************************************************************************\n\n*******************************************************************************\/\nstore::Item_t\nJSONLoader::next( )\n{\n using namespace zorba::json;\n using namespace zorba::simplestore;\n using namespace zorba::simplestore::json;\n\n try\n {\n BasicItemFactory& lFactory = GET_FACTORY();\n\n JSONItem_t lRootItem;\n\n \/\/ stack of objects, arrays, and object pairs\n std::vector lStack;\n\n parser lParser(in);\n\n token lToken;\n\n while (lParser.next(&lToken))\n {\n switch (lToken.get_type())\n {\n case token::begin_array:\n lStack.push_back(new SimpleJSONArray());\n break;\n\n case token::begin_object:\n lStack.push_back(new SimpleJSONObject());\n break;\n\n case token::end_array:\n case token::end_object:\n {\n JSONItem_t lItem = lStack.back();\n\n lStack.pop_back();\n\n if (lStack.empty())\n {\n lRootItem = lItem;\n }\n else\n {\n JSONObjectPair* lOPair = cast(lStack.back());\n lOPair->setValue(lItem);\n lStack.pop_back();\n }\n\n break;\n }\n case token::name_separator:\n case token::value_separator:\n break;\n case token::string:\n {\n store::Item_t lValue;\n zstring s = lToken.get_value();\n lFactory.createString(lValue, s);\n\n addValue(lStack, lValue);\n break;\n }\n case token::number:\n {\n store::Item_t lValue;\n zstring s = lToken.get_value();\n lFactory.createJSONNumber(lValue, s);\n \/\/ todo check return type\n addValue(lStack, lValue);\n break;\n }\n case token::json_false:\n {\n store::Item_t lValue;\n lFactory.createBoolean(lValue, false);\n addValue(lStack, lValue);\n break;\n }\n case token::json_true:\n {\n store::Item_t lValue;\n lFactory.createBoolean(lValue, true);\n addValue(lStack, lValue);\n break;\n }\n case token::json_null:\n {\n store::Item_t lValue;\n lFactory.createJSONNull(lValue);\n addValue(lStack, lValue);\n break;\n }\n default:\n assert(false);\n }\n }\n return lRootItem;\n }\n catch (zorba::json::exception& e)\n {\n std::cerr << e.what() << \" at \" << e.get_loc() << std::endl;\n }\n return NULL;\n}\n\nvoid\nJSONLoader::addValue(\n std::vector& aStack,\n const store::Item_t& aValue)\n{\n JSONItem_t lLast = aStack.back();\n\n JSONObject* lObject = dynamic_cast(lLast.getp());\n\n if (lObject)\n {\n \/\/ if the top of the stack is an object, then\n \/\/ the value must be a string which is the name\n \/\/ of the object's name value pair\n JSONObjectPair_t lOPair = new SimpleJSONObjectPair();\n lOPair->setName(aValue);\n lObject->add(lOPair);\n aStack.push_back(lOPair);\n\n return;\n }\n\n JSONObjectPair* lOPair = dynamic_cast(lLast.getp());\n if (lOPair)\n {\n lOPair->setValue(aValue);\n aStack.pop_back();\n\n return;\n }\n\n JSONArray* lArray = dynamic_cast(lLast.getp());\n assert(lArray);\n\n JSONArrayPair_t lArrayPair(\n new SimpleJSONArrayPair(\n aValue,\n lArray\n )\n );\n lArray->push_back(lArrayPair);\n \n}\n\ntemplate T*\nJSONLoader::cast(const JSONItem_t& j)\n{\n#ifndef NDEBUG\n T* t = dynamic_cast(j.getp());\n assert(t);\n#else\n T* t = static_cast(j.getp());\n#endif\n return t;\n}\n\n} \/* namespace json *\/\n\n} \/* namespace simplestore *\/\n\n} \/* namespace zorba *\/\n\n\/*\n * Local variables:\n * mode: c++\n * End:\n *\/\n\/* vim:set et sw=2 ts=2: *\/\n\nfix for parsing json sequences\/*\n * Copyright 2006-2011 The FLWOR Foundation.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"json_loader.h\"\n#include \"util\/json_parser.h\"\n#include \"json_items.h\"\n#include \"simple_item_factory.h\"\n#include \"store_defs.h\"\n#include \"simple_store.h\"\n#include \n#include \n\nnamespace zorba\n{\n\nnamespace simplestore\n{\n\nnamespace json\n{\n\n\n\/******************************************************************************\n\n*******************************************************************************\/\nJSONLoader::JSONLoader(std::istream& s)\n : in(s)\n{\n}\n\n\n\/******************************************************************************\n\n*******************************************************************************\/\nJSONLoader::~JSONLoader()\n{\n}\n\n\n\/******************************************************************************\n\n*******************************************************************************\/\nstore::Item_t\nJSONLoader::next( )\n{\n using namespace zorba::json;\n using namespace zorba::simplestore;\n using namespace zorba::simplestore::json;\n\n in.peek();\n if (in.eof())\n {\n return NULL;\n }\n\n try\n {\n BasicItemFactory& lFactory = GET_FACTORY();\n\n JSONItem_t lRootItem;\n\n \/\/ stack of objects, arrays, and object pairs\n std::vector lStack;\n\n parser lParser(in);\n\n token lToken;\n\n while (lParser.next(&lToken))\n {\n switch (lToken.get_type())\n {\n case token::begin_array:\n lStack.push_back(new SimpleJSONArray());\n break;\n\n case token::begin_object:\n lStack.push_back(new SimpleJSONObject());\n break;\n\n case token::end_array:\n case token::end_object:\n {\n JSONItem_t lItem = lStack.back();\n\n lStack.pop_back();\n\n if (lStack.empty())\n {\n lRootItem = lItem;\n }\n else\n {\n JSONObjectPair* lOPair = cast(lStack.back());\n lOPair->setValue(lItem);\n lStack.pop_back();\n }\n\n break;\n }\n case token::name_separator:\n case token::value_separator:\n break;\n case token::string:\n {\n store::Item_t lValue;\n zstring s = lToken.get_value();\n lFactory.createString(lValue, s);\n\n addValue(lStack, lValue);\n break;\n }\n case token::number:\n {\n store::Item_t lValue;\n zstring s = lToken.get_value();\n lFactory.createJSONNumber(lValue, s);\n \/\/ todo check return type\n addValue(lStack, lValue);\n break;\n }\n case token::json_false:\n {\n store::Item_t lValue;\n lFactory.createBoolean(lValue, false);\n addValue(lStack, lValue);\n break;\n }\n case token::json_true:\n {\n store::Item_t lValue;\n lFactory.createBoolean(lValue, true);\n addValue(lStack, lValue);\n break;\n }\n case token::json_null:\n {\n store::Item_t lValue;\n lFactory.createJSONNull(lValue);\n addValue(lStack, lValue);\n break;\n }\n default:\n assert(false);\n }\n }\n return lRootItem;\n }\n catch (zorba::json::exception& e)\n {\n std::cerr << e.what() << \" at \" << e.get_loc() << std::endl;\n }\n return NULL;\n}\n\nvoid\nJSONLoader::addValue(\n std::vector& aStack,\n const store::Item_t& aValue)\n{\n JSONItem_t lLast = aStack.back();\n\n JSONObject* lObject = dynamic_cast(lLast.getp());\n\n if (lObject)\n {\n \/\/ if the top of the stack is an object, then\n \/\/ the value must be a string which is the name\n \/\/ of the object's name value pair\n JSONObjectPair_t lOPair = new SimpleJSONObjectPair();\n lOPair->setName(aValue);\n lObject->add(lOPair);\n aStack.push_back(lOPair);\n\n return;\n }\n\n JSONObjectPair* lOPair = dynamic_cast(lLast.getp());\n if (lOPair)\n {\n lOPair->setValue(aValue);\n aStack.pop_back();\n\n return;\n }\n\n JSONArray* lArray = dynamic_cast(lLast.getp());\n assert(lArray);\n\n JSONArrayPair_t lArrayPair(\n new SimpleJSONArrayPair(\n aValue,\n lArray\n )\n );\n lArray->push_back(lArrayPair);\n \n}\n\ntemplate T*\nJSONLoader::cast(const JSONItem_t& j)\n{\n#ifndef NDEBUG\n T* t = dynamic_cast(j.getp());\n assert(t);\n#else\n T* t = static_cast(j.getp());\n#endif\n return t;\n}\n\n} \/* namespace json *\/\n\n} \/* namespace simplestore *\/\n\n} \/* namespace zorba *\/\n\n\/*\n * Local variables:\n * mode: c++\n * End:\n *\/\n\/* vim:set et sw=2 ts=2: *\/\n\n<|endoftext|>"} {"text":"\/*\n Определить функцию для вычисления по формуле Ньютона приблежённого значения\n арифметического квадратного корня. В формуле Ньютона итерации определяются\n по формуле r_[n+1] = (r_[n] + x \/ r_[n]) \/ 2\n\n Версия для C++\n*\/\n#include \n#include \n#include \n\nconst double PRECISION = 0.000000001;\n\n\/*\n Объявление функции с именем newton_root.\n Она принимает один аргумент типа double и возращает значение типа double.\n Объявление без описания тела функции (блок кода в фигурных скобках) - позволяет\n делать вызов этой функции в любом месте, до определения самой функции.\n*\/\ndouble newton_root(double );\n\nint main()\n{\n std::setlocale(LC_ALL, \"RUS\");\n\n double x, result;\n\n std::cout << \"Введите x: \";\n std::cin >> x;\n\n \/\/ вызываем функцию, передавая ей в качестве аргумента переменную x и сохраняя возращённый ею результат в переменной result\n result = newton_root(x);\n std::cout << \"Корень из x: \" << result;\n\n return 0;\n}\n\n\/*\n Ниже производится определение функции. В отличие от объявления, здесь обязательно указание имени передаваемых аргументов.\n Имя аргумента используется только в теле функции.\n\n Стоит заметить, что отделение объявления и определения функции не является обязательным при записи всего в одном файле.\n*\/\ndouble newton_root(double num)\n{\n double r_cur, r_next = num;\n\n \/*\n Действительные числа (float, double) лучше сравнивать с некоторой заранее определённой\n точностью по числу знаков после запятой.\n num == 0.0 - не гарантирует, что сравнение будет истино даже если num = 0;\n *\/\n if (num < PRECISION)\n return 0.0;\n\n do {\n r_cur = r_next;\n r_next = (r_cur + num \/ r_cur) \/ 2;\n } while (fabs(r_cur - r_next) > PRECISION);\n\n return r_next;\n}\nminor fix to from_study_guide\/5_1.cpp\/*\n Определить функцию для вычисления по формуле Ньютона приблежённого значения\n арифметического квадратного корня. В формуле Ньютона итерации определяются\n по формуле r_[n+1] = (r_[n] + x \/ r_[n]) \/ 2\n\n Версия для C++\n*\/\n#include \n#include \n#include \n\nconst double PRECISION = 0.000000001;\n\n\/*\n Объявление функции с именем newton_root.\n Она принимает один аргумент типа double и возращает значение типа double.\n Объявление без описания тела функции (блок кода в фигурных скобках) - позволяет\n делать вызов этой функции в любом месте, до определения самой функции.\n*\/\ndouble newton_root(double );\n\nint main()\n{\n std::setlocale(LC_ALL, \"RUS\");\n\n double x, result;\n\n std::cout << \"Введите x: \";\n std::cin >> x;\n\n \/\/ вызываем функцию, передавая ей в качестве аргумента переменную x и сохраняя возращённый ею результат в переменной result\n result = newton_root(x);\n std::cout << \"Корень из x: \" << result;\n\n return 0;\n}\n\n\/*\n Ниже производится определение функции. В отличие от объявления, здесь обязательно указание имени передаваемых аргументов.\n Имя аргумента используется только в теле функции.\n\n Стоит заметить, что отделение объявления и определения функции не является обязательным при записи всего в одном файле.\n*\/\ndouble newton_root(double num)\n{\n double r_cur, r_next = num;\n\n \/*\n Действительные числа (float, double) лучше сравнивать с некоторой заранее определённой\n точностью по числу знаков после запятой.\n num == 0.0 - не гарантирует, что сравнение будет истино даже если num = 0;\n *\/\n if (num < PRECISION)\n return 0.0;\n\n do {\n r_cur = r_next;\n r_next = (r_cur + num \/ r_cur) \/ 2;\n } while ( abs(r_cur - r_next) > PRECISION );\n\n return r_next;\n}\n<|endoftext|>"} {"text":"\/\/ This file is part of SWGANH which is released under GPL v2.\n\/\/ See file LICENSE or go to http:\/\/swganh.com\/LICENSE\n\n#include \"config_reader.h\"\n\n#include \n#include \n#include \n\n#ifdef WIN32\n#include \n#else\n#include \n#endif\n\n#include \n\n#include \n\nusing namespace swganh::tre;\n\nusing std::ifstream;\nusing std::ios_base;\nusing std::move;\nusing std::invalid_argument;\nusing std::string;\nusing std::vector;\n\n#ifdef WIN32\nusing std::regex;\nusing std::smatch;\nusing std::regex_match;\n#else\nusing boost::regex;\nusing boost::smatch;\nusing boost::regex_match;\n#endif\n\nConfigReader::ConfigReader(std::string filename)\n : config_filename_(move(filename))\n{\n ParseConfig();\n}\n\nconst std::vector& ConfigReader::GetTreFilenames()\n{\n return tre_filenames_;\n}\n\nvoid ConfigReader::ParseConfig()\n{\n ifstream input_stream(config_filename_.c_str());\n\n if (!input_stream.is_open())\n {\n LOG(fatal) << \"Invalid tre configuration file: \" << config_filename_;\n throw invalid_argument(\"Invalid tre configuration file: \" + config_filename_);\n }\n\n boost::filesystem::path p(config_filename_);\n boost::filesystem::path dir = p.parent_path();\n\n#ifdef WIN32\n regex rx(\"searchTree_([0-9]{2})_([0-9]{1,2})=(\\\")?(.*)\\\\3\");\n#else\n regex rx(\"searchTree_([0-9]{2})_([0-9]{1,2})=(\\\")?(.*)(\\\")?\");\n#endif\n\n smatch match;\n string line;\n\n while(!input_stream.eof())\n {\n Getline(input_stream, line);\n\n if (regex_search(line, match, rx))\n {\n boost::filesystem::path tmp = dir;\n boost::filesystem::path filename = match[4].str();\n\n if (!boost::filesystem::is_regular_file(filename))\n {\n tmp \/= filename;\n filename = tmp;\n }\n\n auto native_path = boost::filesystem::system_complete(filename).native();\n tre_filenames_.emplace_back(string(begin(native_path), end(native_path)));\n }\n }\n}\n\n\nstd::istream& ConfigReader::Getline(std::istream& input, std::string& output)\n{\n char c;\n\n output.clear();\n\n while(input.get(c) && c != '\\n' && c != '\\r')\n {\n output += c;\n }\n\n return input;\n}Reverted back to the single regex syntax now that line endings are working proper.\/\/ This file is part of SWGANH which is released under GPL v2.\n\/\/ See file LICENSE or go to http:\/\/swganh.com\/LICENSE\n\n#include \"config_reader.h\"\n\n#include \n#include \n#include \n\n#ifdef WIN32\n#include \n#else\n#include \n#endif\n\n#include \n\n#include \n\nusing namespace swganh::tre;\n\nusing std::ifstream;\nusing std::ios_base;\nusing std::move;\nusing std::invalid_argument;\nusing std::string;\nusing std::vector;\n\n#ifdef WIN32\nusing std::regex;\nusing std::smatch;\nusing std::regex_match;\n#else\nusing boost::regex;\nusing boost::smatch;\nusing boost::regex_match;\n#endif\n\nConfigReader::ConfigReader(std::string filename)\n : config_filename_(move(filename))\n{\n ParseConfig();\n}\n\nconst std::vector& ConfigReader::GetTreFilenames()\n{\n return tre_filenames_;\n}\n\nvoid ConfigReader::ParseConfig()\n{\n ifstream input_stream(config_filename_.c_str());\n\n if (!input_stream.is_open())\n {\n LOG(fatal) << \"Invalid tre configuration file: \" << config_filename_;\n throw invalid_argument(\"Invalid tre configuration file: \" + config_filename_);\n }\n\n boost::filesystem::path p(config_filename_);\n boost::filesystem::path dir = p.parent_path();\n\n regex rx(\"searchTree_([0-9]{2})_([0-9]{1,2})=(\\\")?(.*)\\\\3\");\n smatch match;\n string line;\n\n while(!input_stream.eof())\n {\n Getline(input_stream, line);\n\n if (regex_search(line, match, rx))\n {\n boost::filesystem::path tmp = dir;\n boost::filesystem::path filename = match[4].str();\n\n if (!boost::filesystem::is_regular_file(filename))\n {\n tmp \/= filename;\n filename = tmp;\n }\n\n auto native_path = boost::filesystem::system_complete(filename).native();\n tre_filenames_.emplace_back(string(begin(native_path), end(native_path)));\n }\n }\n}\n\n\nstd::istream& ConfigReader::Getline(std::istream& input, std::string& output)\n{\n char c;\n\n output.clear();\n\n while(input.get(c) && c != '\\n' && c != '\\r')\n {\n output += c;\n }\n\n return input;\n}<|endoftext|>"} {"text":"\/*\n * _____ ___ ___ |\n * | _ |___ ___ _ _|_ |_ | | C\/C++ framework for 32-bit AVRs\n * | | -_| _| | |_ | _| | \n * |__|__|___|_| |_ |___|___| | https:\/\/github.com\/aery32\n * |___| |\n *\n * Copyright (c) 2012, Muiku Oy\n * All rights reserved.\n *\n * LICENSE\n *\n * New BSD License, see the LICENSE.txt bundled with this package. If you did\n * not receive a copy of the license and are unable to obtain it through the\n * world-wide-web, please send an email to contact@muiku.com so we can send\n * you a copy.\n *\/\n\n#include \"aery32\/pwm.h\"\n\nvolatile avr32_pwm_t *aery::pwm = &AVR32_PWM;\n\nint aery::pwm_init_divab(enum Pwm_channel_clk prea, uint8_t diva,\n\t\tenum Pwm_channel_clk preb, uint8_t divb)\n{\n\tif (prea == PWM_CLKA || prea == PWM_CLKB)\n\t\treturn -1;\n\tif (preb == PWM_CLKA || preb == PWM_CLKB)\n\t\treturn -1;\n\t\n\tAVR32_PWM.MR.prea = prea;\n\tAVR32_PWM.MR.diva = diva;\n\n\tAVR32_PWM.MR.preb = preb;\n\tAVR32_PWM.MR.divb = divb;\n\n\treturn 0;\n}\n\nint aery::pwm_init_channel(uint8_t chanum, enum Pwm_channel_clk clk,\n\t\tuint32_t duration, uint32_t period)\n{\n\t\/* Writing in CDTYn and CPRDn is possible while the chan is disabled *\/\n\tif (aery::pwm_isenabled(chanum))\n\t\treturn -1;\n\tif (duration > period)\n\t\treturn -1;\n\n\tvolatile avr32_pwm_channel_t *pwm = &AVR32_PWM.channel[chanum];\n\tpwm->CMR.cpre = clk;\n\tpwm->cdty = duration;\n\tpwm->cprd = period;\n\n\treturn 0;\n}\n\nint aery::pwm_setup_chamode(uint8_t chanum, enum Pwm_alignment align,\n\t\tenum Pwm_polarity polar)\n{\n\t\/* Mode can be modified only when the channel is disabled. *\/\n\tif (aery::pwm_isenabled(chanum))\n\t\treturn -1;\n\n\tAVR32_PWM.channel[chanum].CMR.calg = align;\n\tAVR32_PWM.channel[chanum].CMR.cpol = polar;\n\treturn 0;\n}\n\nint aery::pwm_update_duration(uint8_t chanum, uint32_t newval)\n{\n\tif (newval > AVR32_PWM.channel[chanum].cprd)\n\t\treturn -1;\n\tAVR32_PWM.channel[chanum].CMR.cpd = 0;\n\tAVR32_PWM.channel[chanum].cupd = newval;\n\treturn 0;\n}\n\nint aery::pwm_update_period(uint8_t chanum, uint32_t newval)\n{\n\tif (newval < AVR32_PWM.channel[chanum].cdty)\n\t\treturn -1;\n\tAVR32_PWM.channel[chanum].CMR.cpd = 1;\n\tAVR32_PWM.channel[chanum].cupd = newval;\n\treturn 0;\n}\n\nvoid aery::pwm_wait_periods(uint8_t chanum, uint32_t periods)\n{\n\tvolatile uint32_t status = AVR32_PWM.isr;\n\n\tAVR32_PWM.ier |= (1 << chanum);\n\twhile (periods--)\n\t\twhile ((status = AVR32_PWM.isr) & (1 << chanum));\n\tAVR32_PWM.idr |= (1 << chanum);\n}\n\nint aery::pwm_update_dutycl(uint8_t chanum, double D)\n{\n\tvolatile avr32_pwm_channel_t *pwm = &AVR32_PWM.channel[chanum];\n\n\tif (D > 1.0)\n\t\treturn -1;\n\tif (D < 0.0)\n\t\treturn -1;\n\tif (pwm->CMR.cpd == 0)\n\t\treturn pwm_update_duration(chanum, (uint32_t) (D * pwm->cprd));\n\telse\n\t\treturn pwm_update_period(chanum, (uint32_t) (pwm->cdty \/ D));\n}\n\nvoid aery::pwm_enable(uint8_t chamask)\n{\n\tAVR32_PWM.ena = chamask;\n}\n\nvoid aery::pwm_disable(uint8_t chamask)\n{\n\tAVR32_PWM.dis = chamask;\n}\n\nbool aery::pwm_isenabled(uint8_t chanum)\n{\n\treturn AVR32_PWM.sr & (1 << chanum);\n}Fine tuning the if statement\/*\n * _____ ___ ___ |\n * | _ |___ ___ _ _|_ |_ | | C\/C++ framework for 32-bit AVRs\n * | | -_| _| | |_ | _| | \n * |__|__|___|_| |_ |___|___| | https:\/\/github.com\/aery32\n * |___| |\n *\n * Copyright (c) 2012, Muiku Oy\n * All rights reserved.\n *\n * LICENSE\n *\n * New BSD License, see the LICENSE.txt bundled with this package. If you did\n * not receive a copy of the license and are unable to obtain it through the\n * world-wide-web, please send an email to contact@muiku.com so we can send\n * you a copy.\n *\/\n\n#include \"aery32\/pwm.h\"\n\nvolatile avr32_pwm_t *aery::pwm = &AVR32_PWM;\n\nint aery::pwm_init_divab(enum Pwm_channel_clk prea, uint8_t diva,\n\t\tenum Pwm_channel_clk preb, uint8_t divb)\n{\n\tif (prea == PWM_CLKA || prea == PWM_CLKB)\n\t\treturn -1;\n\tif (preb == PWM_CLKA || preb == PWM_CLKB)\n\t\treturn -1;\n\t\n\tAVR32_PWM.MR.prea = prea;\n\tAVR32_PWM.MR.diva = diva;\n\n\tAVR32_PWM.MR.preb = preb;\n\tAVR32_PWM.MR.divb = divb;\n\n\treturn 0;\n}\n\nint aery::pwm_init_channel(uint8_t chanum, enum Pwm_channel_clk clk,\n\t\tuint32_t duration, uint32_t period)\n{\n\t\/* Writing in CDTYn and CPRDn is possible while the chan is disabled *\/\n\tif (aery::pwm_isenabled(chanum))\n\t\treturn -1;\n\tif (duration > period)\n\t\treturn -1;\n\n\tvolatile avr32_pwm_channel_t *pwm = &AVR32_PWM.channel[chanum];\n\tpwm->CMR.cpre = clk;\n\tpwm->cdty = duration;\n\tpwm->cprd = period;\n\n\treturn 0;\n}\n\nint aery::pwm_setup_chamode(uint8_t chanum, enum Pwm_alignment align,\n\t\tenum Pwm_polarity polar)\n{\n\t\/* Mode can be modified only when the channel is disabled. *\/\n\tif (aery::pwm_isenabled(chanum))\n\t\treturn -1;\n\n\tAVR32_PWM.channel[chanum].CMR.calg = align;\n\tAVR32_PWM.channel[chanum].CMR.cpol = polar;\n\treturn 0;\n}\n\nint aery::pwm_update_duration(uint8_t chanum, uint32_t newval)\n{\n\tif (newval > AVR32_PWM.channel[chanum].cprd)\n\t\treturn -1;\n\tAVR32_PWM.channel[chanum].CMR.cpd = 0;\n\tAVR32_PWM.channel[chanum].cupd = newval;\n\treturn 0;\n}\n\nint aery::pwm_update_period(uint8_t chanum, uint32_t newval)\n{\n\tif (newval < AVR32_PWM.channel[chanum].cdty)\n\t\treturn -1;\n\tAVR32_PWM.channel[chanum].CMR.cpd = 1;\n\tAVR32_PWM.channel[chanum].cupd = newval;\n\treturn 0;\n}\n\nvoid aery::pwm_wait_periods(uint8_t chanum, uint32_t periods)\n{\n\tvolatile uint32_t status = AVR32_PWM.isr;\n\n\tAVR32_PWM.ier |= (1 << chanum);\n\twhile (periods--)\n\t\twhile ((status = AVR32_PWM.isr) & (1 << chanum));\n\tAVR32_PWM.idr |= (1 << chanum);\n}\n\nint aery::pwm_update_dutycl(uint8_t chanum, double D)\n{\n\tvolatile avr32_pwm_channel_t *pwm = &AVR32_PWM.channel[chanum];\n\n\tif (D < 0.0 || D > 1.0)\n\t\treturn -1;\n\tif (pwm->CMR.cpd == 0)\n\t\treturn pwm_update_duration(chanum, (uint32_t) (D * pwm->cprd));\n\telse\n\t\treturn pwm_update_period(chanum, (uint32_t) (pwm->cdty \/ D));\n}\n\nvoid aery::pwm_enable(uint8_t chamask)\n{\n\tAVR32_PWM.ena = chamask;\n}\n\nvoid aery::pwm_disable(uint8_t chamask)\n{\n\tAVR32_PWM.dis = chamask;\n}\n\nbool aery::pwm_isenabled(uint8_t chanum)\n{\n\treturn AVR32_PWM.sr & (1 << chanum);\n}<|endoftext|>"} {"text":"\/\/(c) 2016 by Authors\n\/\/This file is a part of ABruijn program.\n\/\/Released under the BSD license (see LICENSE file)\n\n#include \"multiplicity_inferer.h\"\n#include \"graph_processing.h\"\n#include \"..\/common\/disjoint_set.h\"\n#include \"..\/common\/utils.h\"\n#include \n\n\n\/\/Estimates the mean coverage and assingns edges multiplicity accordingly\nvoid MultiplicityInferer::estimateCoverage()\n{\n\tconst int WINDOW = Config::get(\"coverage_estimate_window\");\n\tconst int SHORT_EDGE = Config::get(\"unique_edge_length\");\n\n\t\/\/alternative coverage\n\tstd::unordered_map> wndCoverage;\n\n\tfor (auto& edge : _graph.iterEdges())\n\t{\n\t\tsize_t numWindows = edge->length() \/ WINDOW;\n\t\twndCoverage[edge].assign(numWindows, 0);\n\t}\n\n\tfor (auto& path : _aligner.getAlignments())\n\t{\n\t\tfor (size_t i = 0; i < path.size(); ++i)\n\t\t{\n\t\t\tauto& ovlp = path[i].overlap;\n\t\t\tauto& coverage = wndCoverage[path[i].edge];\n\t\t\tfor (int pos = ovlp.extBegin \/ WINDOW + 1; \n\t\t\t \t pos < ovlp.extEnd \/ WINDOW; ++pos)\n\t\t\t{\n\t\t\t\tif (pos >= 0 && \n\t\t\t\t\tpos < (int)coverage.size())\n\t\t\t\t{\n\t\t\t\t\t++coverage[pos];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tint64_t sumCov = 0;\n\tint64_t sumLength = 0;\n\tfor (auto& edgeCoverage : wndCoverage)\n\t{\n\t\tif (edgeCoverage.first->length() < SHORT_EDGE) continue;\n\t\tfor (auto& cov : edgeCoverage.second)\n\t\t{\n\t\t\tsumCov += (int64_t)cov;\n\t\t\t++sumLength;\n\t\t}\n\t}\n\t_meanCoverage = (sumLength != 0) ? sumCov \/ sumLength : 1;\n\n\tLogger::get().info() << \"Mean edge coverage: \" << _meanCoverage;\n\n\tstd::vector edgesCoverage;\n\tfor (auto edge : _graph.iterEdges())\n\t{\n\t\tif (wndCoverage[edge].empty()) continue;\n\n\t\tGraphEdge* complEdge = _graph.complementEdge(edge);\n\t\tint32_t medianCov = (median(wndCoverage[edge]) + \n\t\t\t\t\t\t \t median(wndCoverage[complEdge])) \/ 2;\n\n\t\tint estMult = std::round((float)medianCov \/ _meanCoverage);\n\t\tif (estMult == 1)\n\t\t{\n\t\t\tedgesCoverage.push_back(medianCov);\n\t\t}\n\n\t\t\/\/std::string match = estMult != edge->multiplicity ? \"*\" : \" \";\n\t\tstd::string covStr;\n\n\t\tLogger::get().debug() << edge->edgeId.signedId() << \"\\tlen:\"\n\t\t\t\t<< edge->length() << \"\\tcov:\" << medianCov << \"\\tmult:\"\n\t\t\t\t<< (float)medianCov \/ _meanCoverage;\n\n\t\t\/\/edge->multiplicity = estMult;\n\t\tedge->meanCoverage = medianCov;\n\t}\n\n\t_uniqueCovThreshold = 2;\n\tif (!edgesCoverage.empty())\n\t{\n\t\tconst float MULT = 1.75f;\t\/\/at least 1.75x of mean coverage\n\t\t_uniqueCovThreshold = MULT * quantile(edgesCoverage, 75);\n\t}\n\tLogger::get().debug() << \"Unique coverage threshold \" << _uniqueCovThreshold;\n}\n\n\/\/removes edges with low coverage support from the graph\nvoid MultiplicityInferer::removeUnsupportedEdges()\n{\n\tGraphProcessor proc(_graph, _asmSeqs, _readSeqs);\n\tauto unbranchingPaths = proc.getUnbranchingPaths();\n\n\tint32_t coverageThreshold = this->getMeanCoverage() \/ \n\t\t\t\t\t\t\t\tConfig::get(\"graph_cov_drop_rate\");\n\tLogger::get().debug() << \"Read coverage cutoff: \" << coverageThreshold;\n\n\tstd::unordered_set edgesRemove;\n\tfor (auto& path : unbranchingPaths)\n\t{\n\t\tif (!path.id.strand()) continue;\n\n\t\tif (path.meanCoverage <= coverageThreshold)\n\t\t{\n\t\t\tLogger::get().debug() << \"Low coverage: \" \n\t\t\t\t<< path.edgesStr() << \" \" << path.meanCoverage;\n\t\t\tfor (auto& edge : path.path)\n\t\t\t{\n\t\t\t\tedgesRemove.insert(edge);\n\t\t\t\tedgesRemove.insert(_graph.complementEdge(edge));\n\t\t\t}\n\t\t}\n\t}\n\tfor (auto& edge : edgesRemove) _graph.removeEdge(edge);\n\tLogger::get().debug() << \"Removed \" << edgesRemove.size() \/ 2\n\t\t<< \" unsupported edges\";\n\n\t_aligner.updateAlignments();\n}\n\nvoid MultiplicityInferer::removeUnsupportedConnections()\n{\n\tstd::unordered_map rightConnections;\n\tstd::unordered_map leftConnections;\n\n\tfor (auto& readPath : _aligner.getAlignments())\n\t{\n\t\tif (readPath.size() < 2) continue;\n\t\t\/\/int overhang = std::max(readPath.front().overlap.curBegin,\n\t\t\/\/\t\t\t\t\t\treadPath.back().overlap.curLen - \n\t\t\/\/\t\t\t\t\t\t\treadPath.back().overlap.curEnd);\n\t\t\/\/if (overhang > (int)Config::get(\"maximum_overhang\")) continue;\n\n\t\tfor (size_t i = 0; i < readPath.size() - 1; ++i)\n\t\t{\n\t\t\tif (readPath[i].edge == readPath[i + 1].edge &&\n\t\t\t\treadPath[i].edge->isLooped()) continue;\n\t\t\tif (readPath[i].edge->edgeId == \n\t\t\t\treadPath[i + 1].edge->edgeId.rc()) continue;\n\n\t\t\t++rightConnections[readPath[i].edge];\n\t\t\t++leftConnections[readPath[i + 1].edge];\n\t\t\tGraphEdge* complLeft = _graph.complementEdge(readPath[i].edge);\n\t\t\tGraphEdge* complRight = _graph.complementEdge(readPath[i + 1].edge);\n\t\t\t++rightConnections[complRight];\n\t\t\t++leftConnections[complLeft];\n\t\t}\n\t}\n\n\tauto disconnectRight = [this](GraphEdge* edge)\n\t{\n\t\tGraphNode* newNode = _graph.addNode();\n\t\tvecRemove(edge->nodeRight->inEdges, edge);\n\t\tedge->nodeRight = newNode;\n\t\tedge->nodeRight->inEdges.push_back(edge);\n\t};\n\tauto disconnectLeft = [this](GraphEdge* edge)\n\t{\n\t\tGraphNode* newNode = _graph.addNode();\n\t\tvecRemove(edge->nodeLeft->outEdges, edge);\n\t\tedge->nodeLeft = newNode;\n\t\tedge->nodeLeft->outEdges.push_back(edge);\n\t};\n\n\tfor (auto& edge : _graph.iterEdges())\n\t{\n\t\tif (!edge->edgeId.strand() || edge->isLooped()) continue;\n\t\tGraphEdge* complEdge = _graph.complementEdge(edge);\n\n\t\tint32_t coverageThreshold = edge->meanCoverage \/ \n\t\t\t\t\t\t\t\tConfig::get(\"graph_cov_drop_rate\");\n\n\t\t\/\/Logger::get().debug() << \"Adjacencies: \" << edge->edgeId.signedId() << \" \"\n\t\t\/\/\t<< leftConnections[edge] \/ 2 << \" \" << rightConnections[edge] \/ 2;\n\n\t\tif (!edge->nodeRight->isEnd() &&\n\t\t\trightConnections[edge] \/ 2 < coverageThreshold)\n\t\t{\n\t\t\tLogger::get().debug() << \"Chimeric right: \" <<\n\t\t\t\tedge->edgeId.signedId() << \" \" << rightConnections[edge] \/ 2;\n\n\t\t\tdisconnectRight(edge);\n\t\t\tdisconnectLeft(complEdge);\n\n\t\t\tif (edge->selfComplement) continue;\t\/\/already discinnected\n\t\t}\n\t\tif (!edge->nodeLeft->isEnd() &&\n\t\t\tleftConnections[edge] \/ 2 < coverageThreshold)\n\t\t{\n\t\t\tLogger::get().debug() << \"Chimeric left: \" <<\n\t\t\t\tedge->edgeId.signedId() << \" \" << leftConnections[edge] \/ 2;\n\n\t\t\tdisconnectLeft(edge);\n\t\t\tdisconnectRight(complEdge);\n\t\t}\n\t}\n\n\tGraphProcessor proc(_graph, _asmSeqs, _readSeqs);\n\tproc.trimTips();\n\t_aligner.updateAlignments();\n}\n\n\/\/collapse loops (that also could be viewed as\n\/\/bubbles with one branch of length 0)\nvoid MultiplicityInferer::collapseHeterozygousLoops()\n{\n\tconst float COV_MULT = 1.5;\n\n\tGraphProcessor proc(_graph, _asmSeqs, _readSeqs);\n\tauto unbranchingPaths = proc.getUnbranchingPaths();\n\n\tstd::unordered_set toUnroll;\n\tstd::unordered_set toRemove;\n\tfor (auto& loop : unbranchingPaths)\n\t{\n\t\tif (!loop.isLooped()) continue;\n\n\t\tGraphNode* node = loop.nodeLeft();\n\t\tif (node->inEdges.size() != 2 ||\n\t\t\tnode->outEdges.size() != 2) continue;\n\n\t\tUnbranchingPath* entrancePath = nullptr;\n\t\tUnbranchingPath* exitPath = nullptr;\n\t\tfor (auto& cand : unbranchingPaths)\n\t\t{\n\t\t\tif (cand.nodeRight() == node &&\n\t\t\t\tloop.id != cand.id) entrancePath = &cand;\n\t\t\tif (cand.nodeLeft() == node &&\n\t\t\t\tloop.id != cand.id) exitPath = &cand;\n\t\t}\n\n\t\tif (entrancePath->isLooped()) continue;\n\t\tif (entrancePath->id == exitPath->id.rc()) continue;\n\n\t\t\/\/loop coverage should be roughly equal or less\n\t\tif (loop.meanCoverage > COV_MULT * entrancePath->meanCoverage ||\n\t\t\tloop.meanCoverage > COV_MULT * entrancePath->meanCoverage) continue;\n\n\t\t\/\/loop should not be longer than other branches\n\t\tif (loop.length > entrancePath->length ||\n\t\t\tloop.length > exitPath->length) continue;\n\n\t\tif (loop.meanCoverage < \n\t\t\t(entrancePath->meanCoverage + exitPath->meanCoverage) \/ 4)\n\t\t{\n\t\t\ttoRemove.insert(loop.id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttoUnroll.insert(loop.id.rc());\n\t\t}\n\t}\n\n\tfor (auto& path : unbranchingPaths)\n\t{\n\t\tif (toUnroll.count(path.id))\n\t\t{\n\t\t\tGraphNode* newNode = _graph.addNode();\n\t\t\tsize_t id = path.nodeLeft()->inEdges[0] == path.path.front();\n\t\t\tGraphEdge* prevEdge = path.nodeLeft()->inEdges[id];\n\n\t\t\tvecRemove(path.nodeLeft()->outEdges, path.path.front());\n\t\t\tvecRemove(path.nodeLeft()->inEdges, prevEdge);\n\t\t\tpath.nodeLeft() = newNode;\n\t\t\tnewNode->outEdges.push_back(path.path.front());\n\t\t\tprevEdge->nodeRight = newNode;\n\t\t\tnewNode->inEdges.push_back(prevEdge);\n\t\t}\n\t\tif (toRemove.count(path.id))\n\t\t{\n\t\t\tGraphNode* newLeft = _graph.addNode();\n\t\t\tGraphNode* newRight = _graph.addNode();\n\n\t\t\tvecRemove(path.nodeLeft()->outEdges, path.path.front());\n\t\t\tvecRemove(path.nodeLeft()->inEdges, path.path.back());\n\t\t\tpath.nodeLeft() = newLeft;\n\t\t\tnewRight->inEdges.push_back(path.path.back());\n\t\t\tpath.nodeRight() = newRight;\n\t\t\tnewLeft->outEdges.push_back(path.path.front());\n\t\t}\n\t}\n\n\tLogger::get().debug() << \"Unrolled \" << toUnroll.size() \/ 2\n\t\t<< \" heterozygous loops\";\n\tLogger::get().debug() << \"Removed \" << toRemove.size() \/ 2\n\t\t<< \" heterozygous loops\";\n\t_aligner.updateAlignments();\n}\n\nvoid MultiplicityInferer::collapseHeterozygousBulges()\n{\n\tconst float MAX_COV_VAR = 0.20;\n\tconst float MAX_LEN_VAR = 0.50;\n\n\tGraphProcessor proc(_graph, _asmSeqs, _readSeqs);\n\tauto unbranchingPaths = proc.getUnbranchingPaths();\n\n\tstd::unordered_set toSeparate;\n\tfor (auto& path : unbranchingPaths)\n\t{\n\t\tif (path.isLooped()) continue;\n\n\t\tstd::vector twoPaths;\n\t\tfor (auto& candEdge : unbranchingPaths)\n\t\t{\n\t\t\tif (candEdge.nodeLeft() == path.nodeLeft() &&\n\t\t\t\tcandEdge.nodeRight() == path.nodeRight()) \n\t\t\t{\n\t\t\t\ttwoPaths.push_back(&candEdge);\n\t\t\t}\n\t\t}\n\n\t\t\/\/making sure the structure is ok\n\t\tif (twoPaths.size() != 2) continue;\n\t\tif (twoPaths[0]->id == twoPaths[1]->id.rc()) continue;\n\t\tif (toSeparate.count(twoPaths[0]->id) || \n\t\t\ttoSeparate.count(twoPaths[1]->id)) continue;\n\t\tif (twoPaths[0]->nodeLeft()->inEdges.size() != 1 ||\n\t\t\ttwoPaths[0]->nodeRight()->outEdges.size() != 1) continue;\n\n\t\tUnbranchingPath* entrancePath = nullptr;\n\t\tUnbranchingPath* exitPath = nullptr;\n\t\tfor (auto& cand : unbranchingPaths)\n\t\t{\n\t\t\tif (cand.nodeRight() == \n\t\t\t\ttwoPaths[0]->nodeLeft()) entrancePath = &cand;\n\t\t\tif (cand.nodeLeft() == twoPaths[0]->nodeRight()) exitPath = &cand;\n\t\t}\n\n\t\t\/\/coverage requirement: sum over two branches roughly equals to\n\t\t\/\/exit and entrance coverage\n\t\tfloat covSum = twoPaths[0]->meanCoverage + twoPaths[1]->meanCoverage;\n\t\tfloat entranceDiff = fabsf(covSum - entrancePath->meanCoverage) \/ covSum;\n\t\tfloat exitDiff = fabsf(covSum - exitPath->meanCoverage) \/ covSum;\n\t\tif (entranceDiff > MAX_COV_VAR || exitDiff > MAX_COV_VAR) continue;\n\n\t\t\/\/length requirement: branches have roughly the same length\n\t\t\/\/and are significantly shorter than entrance\/exits\n\t\tif (abs(twoPaths[0]->length - twoPaths[1]->length) >\n\t\t\tMAX_LEN_VAR * std::min(twoPaths[0]->length, \n\t\t\t\t\t \t\t\t twoPaths[1]->length)) continue;\n\t\tfloat bubbleSize = (twoPaths[0]->length + twoPaths[1]->length) \/ 2;\n\t\tif (bubbleSize > entrancePath->length ||\n\t\t\tbubbleSize > exitPath->length) continue;\n\n\t\tif (twoPaths[0]->meanCoverage < twoPaths[1]->meanCoverage)\n\t\t{\n\t\t\ttoSeparate.insert(twoPaths[0]->id);\n\t\t\ttoSeparate.insert(twoPaths[0]->id.rc());\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttoSeparate.insert(twoPaths[1]->id);\n\t\t\ttoSeparate.insert(twoPaths[1]->id.rc());\n\t\t}\n\t}\n\n\tfor (auto& path : unbranchingPaths)\n\t{\n\t\tif (toSeparate.count(path.id))\n\t\t{\n\t\t\tGraphNode* newLeft = _graph.addNode();\n\t\t\tGraphNode* newRight = _graph.addNode();\n\t\t\tvecRemove(path.nodeLeft()->outEdges, path.path.front());\n\t\t\tvecRemove(path.nodeRight()->inEdges, path.path.back());\n\t\t\tpath.nodeLeft() = newLeft;\n\t\t\tpath.nodeRight() = newRight;\n\t\t\tnewLeft->outEdges.push_back(path.path.front());\n\t\t\tnewRight->inEdges.push_back(path.path.back());\n\t\t}\n\t}\n\n\tLogger::get().debug() << \"Popped \" << toSeparate.size() \/ 2 \n\t\t<< \" heterozygous bulges\";\n\t_aligner.updateAlignments();\n}\nlow coverage cutoff at least 1\/\/(c) 2016 by Authors\n\/\/This file is a part of ABruijn program.\n\/\/Released under the BSD license (see LICENSE file)\n\n#include \"multiplicity_inferer.h\"\n#include \"graph_processing.h\"\n#include \"..\/common\/disjoint_set.h\"\n#include \"..\/common\/utils.h\"\n#include \n\n\n\/\/Estimates the mean coverage and assingns edges multiplicity accordingly\nvoid MultiplicityInferer::estimateCoverage()\n{\n\tconst int WINDOW = Config::get(\"coverage_estimate_window\");\n\tconst int SHORT_EDGE = Config::get(\"unique_edge_length\");\n\n\t\/\/alternative coverage\n\tstd::unordered_map> wndCoverage;\n\n\tfor (auto& edge : _graph.iterEdges())\n\t{\n\t\tsize_t numWindows = edge->length() \/ WINDOW;\n\t\twndCoverage[edge].assign(numWindows, 0);\n\t}\n\n\tfor (auto& path : _aligner.getAlignments())\n\t{\n\t\tfor (size_t i = 0; i < path.size(); ++i)\n\t\t{\n\t\t\tauto& ovlp = path[i].overlap;\n\t\t\tauto& coverage = wndCoverage[path[i].edge];\n\t\t\tfor (int pos = ovlp.extBegin \/ WINDOW + 1; \n\t\t\t \t pos < ovlp.extEnd \/ WINDOW; ++pos)\n\t\t\t{\n\t\t\t\tif (pos >= 0 && \n\t\t\t\t\tpos < (int)coverage.size())\n\t\t\t\t{\n\t\t\t\t\t++coverage[pos];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tint64_t sumCov = 0;\n\tint64_t sumLength = 0;\n\tfor (auto& edgeCoverage : wndCoverage)\n\t{\n\t\tif (edgeCoverage.first->length() < SHORT_EDGE) continue;\n\t\tfor (auto& cov : edgeCoverage.second)\n\t\t{\n\t\t\tsumCov += (int64_t)cov;\n\t\t\t++sumLength;\n\t\t}\n\t}\n\t_meanCoverage = (sumLength != 0) ? sumCov \/ sumLength : 1;\n\n\tLogger::get().info() << \"Mean edge coverage: \" << _meanCoverage;\n\n\tstd::vector edgesCoverage;\n\tfor (auto edge : _graph.iterEdges())\n\t{\n\t\tif (wndCoverage[edge].empty()) continue;\n\n\t\tGraphEdge* complEdge = _graph.complementEdge(edge);\n\t\tint32_t medianCov = (median(wndCoverage[edge]) + \n\t\t\t\t\t\t \t median(wndCoverage[complEdge])) \/ 2;\n\n\t\tint estMult = std::round((float)medianCov \/ _meanCoverage);\n\t\tif (estMult == 1)\n\t\t{\n\t\t\tedgesCoverage.push_back(medianCov);\n\t\t}\n\n\t\t\/\/std::string match = estMult != edge->multiplicity ? \"*\" : \" \";\n\t\tstd::string covStr;\n\n\t\tLogger::get().debug() << edge->edgeId.signedId() << \"\\tlen:\"\n\t\t\t\t<< edge->length() << \"\\tcov:\" << medianCov << \"\\tmult:\"\n\t\t\t\t<< (float)medianCov \/ _meanCoverage;\n\n\t\t\/\/edge->multiplicity = estMult;\n\t\tedge->meanCoverage = medianCov;\n\t}\n\n\t_uniqueCovThreshold = 2;\n\tif (!edgesCoverage.empty())\n\t{\n\t\tconst float MULT = 1.75f;\t\/\/at least 1.75x of mean coverage\n\t\t_uniqueCovThreshold = MULT * quantile(edgesCoverage, 75);\n\t}\n\tLogger::get().debug() << \"Unique coverage threshold \" << _uniqueCovThreshold;\n}\n\n\/\/removes edges with low coverage support from the graph\nvoid MultiplicityInferer::removeUnsupportedEdges()\n{\n\tGraphProcessor proc(_graph, _asmSeqs, _readSeqs);\n\tauto unbranchingPaths = proc.getUnbranchingPaths();\n\n\tint32_t coverageThreshold = std::round((float)this->getMeanCoverage() \/ \n\t\t\t\t\t\t\t\t\t\t\tConfig::get(\"graph_cov_drop_rate\"));\n\tcoverageThreshold = std::max(1, coverageThreshold);\n\tLogger::get().debug() << \"Read coverage cutoff: \" << coverageThreshold;\n\n\tstd::unordered_set edgesRemove;\n\tfor (auto& path : unbranchingPaths)\n\t{\n\t\tif (!path.id.strand()) continue;\n\n\t\tif (path.meanCoverage <= coverageThreshold)\n\t\t{\n\t\t\tLogger::get().debug() << \"Low coverage: \" \n\t\t\t\t<< path.edgesStr() << \" \" << path.meanCoverage;\n\t\t\tfor (auto& edge : path.path)\n\t\t\t{\n\t\t\t\tedgesRemove.insert(edge);\n\t\t\t\tedgesRemove.insert(_graph.complementEdge(edge));\n\t\t\t}\n\t\t}\n\t}\n\tfor (auto& edge : edgesRemove) _graph.removeEdge(edge);\n\tLogger::get().debug() << \"Removed \" << edgesRemove.size() \/ 2\n\t\t<< \" unsupported edges\";\n\n\t_aligner.updateAlignments();\n}\n\nvoid MultiplicityInferer::removeUnsupportedConnections()\n{\n\tstd::unordered_map rightConnections;\n\tstd::unordered_map leftConnections;\n\n\tfor (auto& readPath : _aligner.getAlignments())\n\t{\n\t\tif (readPath.size() < 2) continue;\n\t\t\/\/int overhang = std::max(readPath.front().overlap.curBegin,\n\t\t\/\/\t\t\t\t\t\treadPath.back().overlap.curLen - \n\t\t\/\/\t\t\t\t\t\t\treadPath.back().overlap.curEnd);\n\t\t\/\/if (overhang > (int)Config::get(\"maximum_overhang\")) continue;\n\n\t\tfor (size_t i = 0; i < readPath.size() - 1; ++i)\n\t\t{\n\t\t\tif (readPath[i].edge == readPath[i + 1].edge &&\n\t\t\t\treadPath[i].edge->isLooped()) continue;\n\t\t\tif (readPath[i].edge->edgeId == \n\t\t\t\treadPath[i + 1].edge->edgeId.rc()) continue;\n\n\t\t\t++rightConnections[readPath[i].edge];\n\t\t\t++leftConnections[readPath[i + 1].edge];\n\t\t\tGraphEdge* complLeft = _graph.complementEdge(readPath[i].edge);\n\t\t\tGraphEdge* complRight = _graph.complementEdge(readPath[i + 1].edge);\n\t\t\t++rightConnections[complRight];\n\t\t\t++leftConnections[complLeft];\n\t\t}\n\t}\n\n\tauto disconnectRight = [this](GraphEdge* edge)\n\t{\n\t\tGraphNode* newNode = _graph.addNode();\n\t\tvecRemove(edge->nodeRight->inEdges, edge);\n\t\tedge->nodeRight = newNode;\n\t\tedge->nodeRight->inEdges.push_back(edge);\n\t};\n\tauto disconnectLeft = [this](GraphEdge* edge)\n\t{\n\t\tGraphNode* newNode = _graph.addNode();\n\t\tvecRemove(edge->nodeLeft->outEdges, edge);\n\t\tedge->nodeLeft = newNode;\n\t\tedge->nodeLeft->outEdges.push_back(edge);\n\t};\n\n\tfor (auto& edge : _graph.iterEdges())\n\t{\n\t\tif (!edge->edgeId.strand() || edge->isLooped()) continue;\n\t\tGraphEdge* complEdge = _graph.complementEdge(edge);\n\n\t\tint32_t coverageThreshold = edge->meanCoverage \/ \n\t\t\t\t\t\t\t\tConfig::get(\"graph_cov_drop_rate\");\n\n\t\t\/\/Logger::get().debug() << \"Adjacencies: \" << edge->edgeId.signedId() << \" \"\n\t\t\/\/\t<< leftConnections[edge] \/ 2 << \" \" << rightConnections[edge] \/ 2;\n\n\t\tif (!edge->nodeRight->isEnd() &&\n\t\t\trightConnections[edge] \/ 2 < coverageThreshold)\n\t\t{\n\t\t\tLogger::get().debug() << \"Chimeric right: \" <<\n\t\t\t\tedge->edgeId.signedId() << \" \" << rightConnections[edge] \/ 2;\n\n\t\t\tdisconnectRight(edge);\n\t\t\tdisconnectLeft(complEdge);\n\n\t\t\tif (edge->selfComplement) continue;\t\/\/already discinnected\n\t\t}\n\t\tif (!edge->nodeLeft->isEnd() &&\n\t\t\tleftConnections[edge] \/ 2 < coverageThreshold)\n\t\t{\n\t\t\tLogger::get().debug() << \"Chimeric left: \" <<\n\t\t\t\tedge->edgeId.signedId() << \" \" << leftConnections[edge] \/ 2;\n\n\t\t\tdisconnectLeft(edge);\n\t\t\tdisconnectRight(complEdge);\n\t\t}\n\t}\n\n\tGraphProcessor proc(_graph, _asmSeqs, _readSeqs);\n\tproc.trimTips();\n\t_aligner.updateAlignments();\n}\n\n\/\/collapse loops (that also could be viewed as\n\/\/bubbles with one branch of length 0)\nvoid MultiplicityInferer::collapseHeterozygousLoops()\n{\n\tconst float COV_MULT = 1.5;\n\n\tGraphProcessor proc(_graph, _asmSeqs, _readSeqs);\n\tauto unbranchingPaths = proc.getUnbranchingPaths();\n\n\tstd::unordered_set toUnroll;\n\tstd::unordered_set toRemove;\n\tfor (auto& loop : unbranchingPaths)\n\t{\n\t\tif (!loop.isLooped()) continue;\n\n\t\tGraphNode* node = loop.nodeLeft();\n\t\tif (node->inEdges.size() != 2 ||\n\t\t\tnode->outEdges.size() != 2) continue;\n\n\t\tUnbranchingPath* entrancePath = nullptr;\n\t\tUnbranchingPath* exitPath = nullptr;\n\t\tfor (auto& cand : unbranchingPaths)\n\t\t{\n\t\t\tif (cand.nodeRight() == node &&\n\t\t\t\tloop.id != cand.id) entrancePath = &cand;\n\t\t\tif (cand.nodeLeft() == node &&\n\t\t\t\tloop.id != cand.id) exitPath = &cand;\n\t\t}\n\n\t\tif (entrancePath->isLooped()) continue;\n\t\tif (entrancePath->id == exitPath->id.rc()) continue;\n\n\t\t\/\/loop coverage should be roughly equal or less\n\t\tif (loop.meanCoverage > COV_MULT * entrancePath->meanCoverage ||\n\t\t\tloop.meanCoverage > COV_MULT * entrancePath->meanCoverage) continue;\n\n\t\t\/\/loop should not be longer than other branches\n\t\tif (loop.length > entrancePath->length ||\n\t\t\tloop.length > exitPath->length) continue;\n\n\t\tif (loop.meanCoverage < \n\t\t\t(entrancePath->meanCoverage + exitPath->meanCoverage) \/ 4)\n\t\t{\n\t\t\ttoRemove.insert(loop.id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttoUnroll.insert(loop.id.rc());\n\t\t}\n\t}\n\n\tfor (auto& path : unbranchingPaths)\n\t{\n\t\tif (toUnroll.count(path.id))\n\t\t{\n\t\t\tGraphNode* newNode = _graph.addNode();\n\t\t\tsize_t id = path.nodeLeft()->inEdges[0] == path.path.front();\n\t\t\tGraphEdge* prevEdge = path.nodeLeft()->inEdges[id];\n\n\t\t\tvecRemove(path.nodeLeft()->outEdges, path.path.front());\n\t\t\tvecRemove(path.nodeLeft()->inEdges, prevEdge);\n\t\t\tpath.nodeLeft() = newNode;\n\t\t\tnewNode->outEdges.push_back(path.path.front());\n\t\t\tprevEdge->nodeRight = newNode;\n\t\t\tnewNode->inEdges.push_back(prevEdge);\n\t\t}\n\t\tif (toRemove.count(path.id))\n\t\t{\n\t\t\tGraphNode* newLeft = _graph.addNode();\n\t\t\tGraphNode* newRight = _graph.addNode();\n\n\t\t\tvecRemove(path.nodeLeft()->outEdges, path.path.front());\n\t\t\tvecRemove(path.nodeLeft()->inEdges, path.path.back());\n\t\t\tpath.nodeLeft() = newLeft;\n\t\t\tnewRight->inEdges.push_back(path.path.back());\n\t\t\tpath.nodeRight() = newRight;\n\t\t\tnewLeft->outEdges.push_back(path.path.front());\n\t\t}\n\t}\n\n\tLogger::get().debug() << \"Unrolled \" << toUnroll.size() \/ 2\n\t\t<< \" heterozygous loops\";\n\tLogger::get().debug() << \"Removed \" << toRemove.size() \/ 2\n\t\t<< \" heterozygous loops\";\n\t_aligner.updateAlignments();\n}\n\nvoid MultiplicityInferer::collapseHeterozygousBulges()\n{\n\tconst float MAX_COV_VAR = 0.20;\n\tconst float MAX_LEN_VAR = 0.50;\n\n\tGraphProcessor proc(_graph, _asmSeqs, _readSeqs);\n\tauto unbranchingPaths = proc.getUnbranchingPaths();\n\n\tstd::unordered_set toSeparate;\n\tfor (auto& path : unbranchingPaths)\n\t{\n\t\tif (path.isLooped()) continue;\n\n\t\tstd::vector twoPaths;\n\t\tfor (auto& candEdge : unbranchingPaths)\n\t\t{\n\t\t\tif (candEdge.nodeLeft() == path.nodeLeft() &&\n\t\t\t\tcandEdge.nodeRight() == path.nodeRight()) \n\t\t\t{\n\t\t\t\ttwoPaths.push_back(&candEdge);\n\t\t\t}\n\t\t}\n\n\t\t\/\/making sure the structure is ok\n\t\tif (twoPaths.size() != 2) continue;\n\t\tif (twoPaths[0]->id == twoPaths[1]->id.rc()) continue;\n\t\tif (toSeparate.count(twoPaths[0]->id) || \n\t\t\ttoSeparate.count(twoPaths[1]->id)) continue;\n\t\tif (twoPaths[0]->nodeLeft()->inEdges.size() != 1 ||\n\t\t\ttwoPaths[0]->nodeRight()->outEdges.size() != 1) continue;\n\n\t\tUnbranchingPath* entrancePath = nullptr;\n\t\tUnbranchingPath* exitPath = nullptr;\n\t\tfor (auto& cand : unbranchingPaths)\n\t\t{\n\t\t\tif (cand.nodeRight() == \n\t\t\t\ttwoPaths[0]->nodeLeft()) entrancePath = &cand;\n\t\t\tif (cand.nodeLeft() == twoPaths[0]->nodeRight()) exitPath = &cand;\n\t\t}\n\n\t\t\/\/coverage requirement: sum over two branches roughly equals to\n\t\t\/\/exit and entrance coverage\n\t\tfloat covSum = twoPaths[0]->meanCoverage + twoPaths[1]->meanCoverage;\n\t\tfloat entranceDiff = fabsf(covSum - entrancePath->meanCoverage) \/ covSum;\n\t\tfloat exitDiff = fabsf(covSum - exitPath->meanCoverage) \/ covSum;\n\t\tif (entranceDiff > MAX_COV_VAR || exitDiff > MAX_COV_VAR) continue;\n\n\t\t\/\/length requirement: branches have roughly the same length\n\t\t\/\/and are significantly shorter than entrance\/exits\n\t\tif (abs(twoPaths[0]->length - twoPaths[1]->length) >\n\t\t\tMAX_LEN_VAR * std::min(twoPaths[0]->length, \n\t\t\t\t\t \t\t\t twoPaths[1]->length)) continue;\n\t\tfloat bubbleSize = (twoPaths[0]->length + twoPaths[1]->length) \/ 2;\n\t\tif (bubbleSize > entrancePath->length ||\n\t\t\tbubbleSize > exitPath->length) continue;\n\n\t\tif (twoPaths[0]->meanCoverage < twoPaths[1]->meanCoverage)\n\t\t{\n\t\t\ttoSeparate.insert(twoPaths[0]->id);\n\t\t\ttoSeparate.insert(twoPaths[0]->id.rc());\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttoSeparate.insert(twoPaths[1]->id);\n\t\t\ttoSeparate.insert(twoPaths[1]->id.rc());\n\t\t}\n\t}\n\n\tfor (auto& path : unbranchingPaths)\n\t{\n\t\tif (toSeparate.count(path.id))\n\t\t{\n\t\t\tGraphNode* newLeft = _graph.addNode();\n\t\t\tGraphNode* newRight = _graph.addNode();\n\t\t\tvecRemove(path.nodeLeft()->outEdges, path.path.front());\n\t\t\tvecRemove(path.nodeRight()->inEdges, path.path.back());\n\t\t\tpath.nodeLeft() = newLeft;\n\t\t\tpath.nodeRight() = newRight;\n\t\t\tnewLeft->outEdges.push_back(path.path.front());\n\t\t\tnewRight->inEdges.push_back(path.path.back());\n\t\t}\n\t}\n\n\tLogger::get().debug() << \"Popped \" << toSeparate.size() \/ 2 \n\t\t<< \" heterozygous bulges\";\n\t_aligner.updateAlignments();\n}\n<|endoftext|>"} {"text":"\/\/ bslstl_algorithm.t.cpp -*-C++-*-\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \/\/ atoi\n#include \/\/ strlen\n\n\/\/ ============================================================================\n\/\/ TEST PLAN\n\/\/ ----------------------------------------------------------------------------\n\/\/ The component under test provides implementations for algorithms not\n\/\/ provided by the underlying standard library implementation.\n\/\/ ----------------------------------------------------------------------------\n\/\/\n\/\/ [ 1] bool all_of (InputIter first, InputIter last, PREDICATE pred);\n\/\/ [ 1] bool any_of (InputIter first, InputIter last, PREDICATE pred);\n\/\/ [ 1] bool none_of(InputIter first, InputIter last, PREDICATE pred);\n\/\/ ----------------------------------------------------------------------------\n\n\/\/ ============================================================================\n\/\/ STANDARD BDE ASSERT TEST MACROS\n\/\/ ----------------------------------------------------------------------------\n\/\/ NOTE: THIS IS A LOW-LEVEL COMPONENT AND MAY NOT USE ANY C++ LIBRARY\n\/\/ FUNCTIONS, INCLUDING IOSTREAMS.\n\nnamespace {\n\nint testStatus = 0;\n\nvoid aSsErT(bool b, const char *s, int i)\n{\n if (b) {\n printf(\"Error \" __FILE__ \"(%d): %s (failed)\\n\", i, s);\n if (testStatus >= 0 && testStatus <= 100) ++testStatus;\n }\n}\n\n} \/\/ close unnamed namespace\n\n\/\/ ============================================================================\n\/\/ STANDARD BDE ASSERT TEST MACROS\n\/\/ ----------------------------------------------------------------------------\n\n#define ASSERT BSLS_BSLTESTUTIL_ASSERT\n#define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT\n#define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT\n#define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT\n#define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT\n#define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT\n#define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT\n#define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT\n#define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT\n#define ASSERTV BSLS_BSLTESTUTIL_ASSERTV\n\n#define Q BSLS_BSLTESTUTIL_Q \/\/ Quote identifier literally.\n#define P BSLS_BSLTESTUTIL_P \/\/ Print identifier and value.\n#define P_ BSLS_BSLTESTUTIL_P_ \/\/ P(X) without '\\n'.\n#define T_ BSLS_BSLTESTUTIL_T_ \/\/ Print a tab (w\/o newline).\n#define L_ BSLS_BSLTESTUTIL_L_ \/\/ current Line number\n\n#define RUN_EACH_TYPE BSLTF_TEMPLATETESTFACILITY_RUN_EACH_TYPE\n\n\/\/ ============================================================================\n\/\/ NEGATIVE-TEST MACRO ABBREVIATIONS\n\/\/ ----------------------------------------------------------------------------\n\n#define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR)\n#define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR)\n#define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR)\n#define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR)\n#define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR)\n#define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR)\n\n\/\/ ============================================================================\n\/\/ PRINTF FORMAT MACRO ABBREVIATIONS\n\/\/ ----------------------------------------------------------------------------\n\n#define ZU BSLS_BSLTESTUTIL_FORMAT_ZU\n\n\/\/ ============================================================================\n\/\/ GLOBAL TEST ALIASES\n\/\/ ----------------------------------------------------------------------------\n\nusing namespace BloombergLP;\n\n\/\/ ============================================================================\n\/\/ GLOBAL TEST VALUES\n\/\/ ----------------------------------------------------------------------------\n\nstatic bool verbose;\nstatic bool veryVerbose;\nstatic bool veryVeryVerbose;\nstatic bool veryVeryVeryVerbose;\n\n\/\/ ============================================================================\n\/\/ TEST FUNCTIONS\n\/\/ ----------------------------------------------------------------------------\n\n#ifndef BSLS_LIBRARYFEATURES_HAS_CPP11_BASELINE_LIBRARY\n\nstruct IsOdd {\n \/\/ A standard compliant C++03 unary predicate functor that returns 'true'\n \/\/ if an 'int' value is odd.\n\n \/\/ PUBLIC TYPES\n typedef char argument_type;\n typedef bool result_type;\n\n \/\/ ACCESSORS\n result_type operator()(argument_type value) const\n \/\/ Return 'true' if the specified 'value' is odd, and 'false'\n \/\/ otherwise.\n {\n return (value % 2) != 0;\n }\n};\n\n\/\/ A function (as opposed to a functor)\nbool isEven(char value)\n \/\/ Return 'true' if the specified 'value' is even, and 'false' otherwise.\n{\n return (value % 2) == 0;\n}\n\ntemplate \nvoid runTestAllOf()\n \/\/ Test driver for 'all_of'.\n{\n struct {\n const char *d_spec;\n bool d_result;\n } DATA_EVEN[] = {\n { \"\", true },\n { \"0\", true },\n { \"1\", false },\n { \"00\", true },\n { \"01\", false },\n { \"10\", false },\n { \"11\", false },\n { \"000\", true },\n { \"001\", false },\n { \"010\", false },\n { \"100\", false },\n { \"111\", false }\n };\n const size_t NUM_DATA_EVEN = sizeof DATA_EVEN \/ sizeof *DATA_EVEN;\n\n for (size_t i = 0; i < NUM_DATA_EVEN; ++i) {\n const char *const SPEC = DATA_EVEN[i].d_spec;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_EVEN[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP == bsl::all_of(values.begin(), values.end(), isEven)));\n }\n\n struct {\n const char *d_spec;\n bool d_result;\n } DATA_ODD[] = {\n { \"\", true },\n { \"0\", false },\n { \"1\", true },\n { \"00\", false },\n { \"01\", false },\n { \"10\", false },\n { \"11\", true },\n { \"000\", false },\n { \"001\", false },\n { \"010\", false },\n { \"100\", false },\n { \"111\", true }\n };\n const size_t NUM_DATA_ODD = sizeof DATA_ODD \/ sizeof *DATA_ODD;\n\n for (size_t i = 0; i < NUM_DATA_ODD; ++i) {\n const char *const SPEC = DATA_ODD[i].d_spec;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_ODD[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP ==\n bsl::all_of(values.begin(), values.end(), IsOdd())));\n }\n}\n\ntemplate \nvoid runTestAnyOf()\n \/\/ Test driver for 'any_of'.\n{\n struct {\n const char *d_spec;\n bool d_result;\n } DATA_EVEN[] = {\n { \"\", false },\n { \"0\", true },\n { \"1\", false },\n { \"00\", true },\n { \"01\", true },\n { \"10\", true },\n { \"11\", false },\n { \"000\", true },\n { \"001\", true },\n { \"010\", true },\n { \"100\", true },\n { \"111\", false }\n };\n const size_t NUM_DATA_EVEN = sizeof DATA_EVEN \/ sizeof *DATA_EVEN;\n\n for (size_t i = 0; i < NUM_DATA_EVEN; ++i) {\n const char *const SPEC = DATA_EVEN[i].d_spec;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_EVEN[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP == bsl::any_of(values.begin(), values.end(), isEven)));\n }\n\n struct {\n const char *d_spec;\n bool d_result;\n } DATA_ODD[] = {\n { \"\", false },\n { \"0\", false },\n { \"1\", true },\n { \"00\", false },\n { \"01\", true },\n { \"10\", true },\n { \"11\", true },\n { \"000\", false },\n { \"001\", true },\n { \"010\", true },\n { \"100\", true },\n { \"111\", true }\n };\n const size_t NUM_DATA_ODD = sizeof DATA_ODD \/ sizeof *DATA_ODD;\n\n for (size_t i = 0; i < NUM_DATA_ODD; ++i) {\n const char *const SPEC = DATA_ODD[i].d_spec;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_ODD[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP ==\n bsl::any_of(values.begin(), values.end(), IsOdd())));\n }\n}\n\ntemplate \nvoid runTestNoneOf()\n \/\/ Test driver for 'none_of'.\n{\n struct {\n const char *d_spec;\n bool d_result;\n } DATA_EVEN[] = {\n { \"\", true },\n { \"0\", false },\n { \"1\", true },\n { \"00\", false },\n { \"01\", false },\n { \"10\", false },\n { \"11\", true },\n { \"000\", false },\n { \"001\", false },\n { \"010\", false },\n { \"100\", false },\n { \"111\", true }\n };\n const size_t NUM_DATA_EVEN = sizeof DATA_EVEN \/ sizeof *DATA_EVEN;\n\n for (size_t i = 0; i < NUM_DATA_EVEN; ++i) {\n const char *const SPEC = DATA_EVEN[i].d_spec;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_EVEN[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP ==\n bsl::none_of(values.begin(), values.end(), isEven)));\n }\n\n struct {\n const char *d_spec;\n bool d_result;\n } DATA_ODD[] = {\n { \"\", true },\n { \"0\", true },\n { \"1\", false },\n { \"00\", true },\n { \"01\", false },\n { \"10\", false },\n { \"11\", false },\n { \"000\", true },\n { \"001\", false },\n { \"010\", false },\n { \"100\", false },\n { \"111\", false }\n };\n const size_t NUM_DATA_ODD = sizeof DATA_ODD \/ sizeof *DATA_ODD;\n\n for (size_t i = 0; i < NUM_DATA_ODD; ++i) {\n const char *const SPEC = DATA_ODD[i].d_spec;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_ODD[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP ==\n bsl::none_of(values.begin(), values.end(), IsOdd())));\n }\n}\n\n#endif\n\n\/\/ ============================================================================\n\/\/ MAIN PROGRAM\n\/\/ ----------------------------------------------------------------------------\n\nint main(int argc, char *argv[])\n{\n int test = argc > 1 ? atoi(argv[1]) : 0;\n\n verbose = argc > 2;\n veryVerbose = argc > 3;\n veryVeryVerbose = argc > 4;\n veryVeryVeryVerbose = argc > 5;\n\n printf(\"TEST \" __FILE__ \" CASE %d\\n\", test);\n\n switch (test) { case 0:\n case 1: {\n \/\/ --------------------------------------------------------------------\n \/\/ FUNCTIONALITY TEST\n \/\/\n \/\/ Concerns:\n \/\/: 1 That the routines exist in the 'bsl' namespace and behave as\n \/\/ expected.\n \/\/\n \/\/ Plan:\n \/\/: 1 Run each method with an empty input range and verify that the\n \/\/: behavior is as expected.\n \/\/: 2 Run each method with a single-element input range and verify that\n \/\/: the behavior is as expected.\n \/\/: 3 Run each method with multiple-element input range and verify that\n \/\/: the behavior is as expected.\n \/\/\n \/\/ Testing:\n \/\/ bool all_of (InputIter first, InputIter last, PREDICATE pred);\n \/\/ bool any_of (InputIter first, InputIter last, PREDICATE pred);\n \/\/ bool none_of(InputIter first, InputIter last, PREDICATE pred);\n \/\/ --------------------------------------------------------------------\n\n if (verbose) printf(\"\\nFUNCTIONALITY TEST\"\n \"\\n==================\\n\");\n\n#ifndef BSLS_LIBRARYFEATURES_HAS_CPP11_BASELINE_LIBRARY\n runTestAllOf();\n runTestAnyOf();\n runTestNoneOf();\n#endif\n\n } break;\n default: {\n fprintf(stderr, \"WARNING: CASE `%d' NOT FOUND.\\n\", test);\n testStatus = -1;\n }\n }\n\n if (testStatus > 0) {\n fprintf(stderr, \"Error, non-zero test status = %d.\\n\", testStatus);\n }\n return testStatus;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Copyright 2020 Bloomberg Finance L.P.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ ----------------------------- END-OF-FILE ----------------------------------\n\nMore feedback from Clay and bde-verify; hopefully we're close now\/\/ bslstl_algorithm.t.cpp -*-C++-*-\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \/\/ atoi\n#include \/\/ strlen\n\n\/\/ ============================================================================\n\/\/ TEST PLAN\n\/\/ ----------------------------------------------------------------------------\n\/\/ The component under test provides implementations for algorithms not\n\/\/ provided by the underlying standard library implementation.\n\/\/ ----------------------------------------------------------------------------\n\/\/\n\/\/ [ 1] bool all_of (InputIter first, InputIter last, PREDICATE pred);\n\/\/ [ 1] bool any_of (InputIter first, InputIter last, PREDICATE pred);\n\/\/ [ 1] bool none_of(InputIter first, InputIter last, PREDICATE pred);\n\/\/ ----------------------------------------------------------------------------\n\n\/\/ ============================================================================\n\/\/ STANDARD BDE ASSERT TEST FUNCTION\n\/\/ ----------------------------------------------------------------------------\n\/\/ NOTE: THIS IS A LOW-LEVEL COMPONENT AND MAY NOT USE ANY C++ LIBRARY\n\/\/ FUNCTIONS, INCLUDING IOSTREAMS.\n\nnamespace {\n\nint testStatus = 0;\n\nvoid aSsErT(bool b, const char *s, int i)\n{\n if (b) {\n printf(\"Error \" __FILE__ \"(%d): %s (failed)\\n\", i, s);\n if (testStatus >= 0 && testStatus <= 100) ++testStatus;\n }\n}\n\n} \/\/ close unnamed namespace\n\n\/\/ ============================================================================\n\/\/ STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS\n\/\/ ----------------------------------------------------------------------------\n\n#define ASSERT BSLS_BSLTESTUTIL_ASSERT\n#define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT\n#define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT\n#define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT\n#define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT\n#define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT\n#define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT\n#define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT\n#define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT\n#define ASSERTV BSLS_BSLTESTUTIL_ASSERTV\n\n#define Q BSLS_BSLTESTUTIL_Q \/\/ Quote identifier literally.\n#define P BSLS_BSLTESTUTIL_P \/\/ Print identifier and value.\n#define P_ BSLS_BSLTESTUTIL_P_ \/\/ P(X) without '\\n'.\n#define T_ BSLS_BSLTESTUTIL_T_ \/\/ Print a tab (w\/o newline).\n#define L_ BSLS_BSLTESTUTIL_L_ \/\/ current Line number\n\n#define RUN_EACH_TYPE BSLTF_TEMPLATETESTFACILITY_RUN_EACH_TYPE\n\n\/\/ ============================================================================\n\/\/ NEGATIVE-TEST MACRO ABBREVIATIONS\n\/\/ ----------------------------------------------------------------------------\n\n#define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR)\n#define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR)\n#define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR)\n#define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR)\n#define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR)\n#define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR)\n\n\/\/ ============================================================================\n\/\/ PRINTF FORMAT MACRO ABBREVIATIONS\n\/\/ ----------------------------------------------------------------------------\n\n#define ZU BSLS_BSLTESTUTIL_FORMAT_ZU\n\n\/\/ ============================================================================\n\/\/ GLOBAL TEST ALIASES\n\/\/ ----------------------------------------------------------------------------\n\nusing namespace BloombergLP;\n\n\/\/ ============================================================================\n\/\/ GLOBAL TEST VALUES\n\/\/ ----------------------------------------------------------------------------\n\nstatic bool verbose;\nstatic bool veryVerbose;\nstatic bool veryVeryVerbose;\nstatic bool veryVeryVeryVerbose;\n\n\/\/ ============================================================================\n\/\/ TEST FUNCTIONS\n\/\/ ----------------------------------------------------------------------------\n\n#ifndef BSLS_LIBRARYFEATURES_HAS_CPP11_BASELINE_LIBRARY\n\nstruct IsOdd {\n \/\/ A standard compliant C++03 unary predicate functor that returns 'true'\n \/\/ if an 'int' value is odd.\n\n \/\/ PUBLIC TYPES\n typedef char argument_type;\n typedef bool result_type;\n\n \/\/ ACCESSORS\n result_type operator()(argument_type value) const\n \/\/ Return 'true' if the specified 'value' is odd, and 'false'\n \/\/ otherwise.\n {\n return (value % 2) != 0;\n }\n};\n\n\/\/ A function (as opposed to a functor)\nbool isEven(char value)\n \/\/ Return 'true' if the specified 'value' is even, and 'false' otherwise.\n{\n return (value % 2) == 0;\n}\n\ntemplate \nvoid runTestAllOf()\n \/\/ Test driver for 'all_of'.\n{\n const struct {\n const char *d_spec_p;\n bool d_result;\n } DATA_EVEN[] = {\n { \"\", true },\n { \"0\", true },\n { \"1\", false },\n { \"00\", true },\n { \"01\", false },\n { \"10\", false },\n { \"11\", false },\n { \"000\", true },\n { \"001\", false },\n { \"010\", false },\n { \"100\", false },\n { \"101\", false },\n { \"111\", false }\n };\n const size_t NUM_DATA_EVEN = sizeof DATA_EVEN \/ sizeof *DATA_EVEN;\n\n for (size_t i = 0; i < NUM_DATA_EVEN; ++i) {\n const char *const SPEC = DATA_EVEN[i].d_spec_p;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_EVEN[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP == bsl::all_of(values.begin(), values.end(), isEven)));\n }\n\n const struct {\n const char *d_spec_p;\n bool d_result;\n } DATA_ODD[] = {\n { \"\", true },\n { \"0\", false },\n { \"1\", true },\n { \"00\", false },\n { \"01\", false },\n { \"10\", false },\n { \"11\", true },\n { \"000\", false },\n { \"001\", false },\n { \"010\", false },\n { \"100\", false },\n { \"101\", false },\n { \"111\", true }\n };\n const size_t NUM_DATA_ODD = sizeof DATA_ODD \/ sizeof *DATA_ODD;\n\n for (size_t i = 0; i < NUM_DATA_ODD; ++i) {\n const char *const SPEC = DATA_ODD[i].d_spec_p;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_ODD[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP ==\n bsl::all_of(values.begin(), values.end(), IsOdd())));\n }\n}\n\ntemplate \nvoid runTestAnyOf()\n \/\/ Test driver for 'any_of'.\n{\n const struct {\n const char *d_spec_p;\n bool d_result;\n } DATA_EVEN[] = {\n { \"\", false },\n { \"0\", true },\n { \"1\", false },\n { \"00\", true },\n { \"01\", true },\n { \"10\", true },\n { \"11\", false },\n { \"000\", true },\n { \"001\", true },\n { \"010\", true },\n { \"100\", true },\n { \"101\", true },\n { \"111\", false }\n };\n const size_t NUM_DATA_EVEN = sizeof DATA_EVEN \/ sizeof *DATA_EVEN;\n\n for (size_t i = 0; i < NUM_DATA_EVEN; ++i) {\n const char *const SPEC = DATA_EVEN[i].d_spec_p;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_EVEN[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP == bsl::any_of(values.begin(), values.end(), isEven)));\n }\n\n const struct {\n const char *d_spec_p;\n bool d_result;\n } DATA_ODD[] = {\n { \"\", false },\n { \"0\", false },\n { \"1\", true },\n { \"00\", false },\n { \"01\", true },\n { \"10\", true },\n { \"11\", true },\n { \"000\", false },\n { \"001\", true },\n { \"010\", true },\n { \"100\", true },\n { \"101\", true },\n { \"111\", true }\n };\n const size_t NUM_DATA_ODD = sizeof DATA_ODD \/ sizeof *DATA_ODD;\n\n for (size_t i = 0; i < NUM_DATA_ODD; ++i) {\n const char *const SPEC = DATA_ODD[i].d_spec_p;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_ODD[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP ==\n bsl::any_of(values.begin(), values.end(), IsOdd())));\n }\n}\n\ntemplate \nvoid runTestNoneOf()\n \/\/ Test driver for 'none_of'.\n{\n const struct {\n const char *d_spec_p;\n bool d_result;\n } DATA_EVEN[] = {\n { \"\", true },\n { \"0\", false },\n { \"1\", true },\n { \"00\", false },\n { \"01\", false },\n { \"10\", false },\n { \"11\", true },\n { \"000\", false },\n { \"001\", false },\n { \"010\", false },\n { \"100\", false },\n { \"101\", false },\n { \"111\", true }\n };\n const size_t NUM_DATA_EVEN = sizeof DATA_EVEN \/ sizeof *DATA_EVEN;\n\n for (size_t i = 0; i < NUM_DATA_EVEN; ++i) {\n const char *const SPEC = DATA_EVEN[i].d_spec_p;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_EVEN[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP ==\n bsl::none_of(values.begin(), values.end(), isEven)));\n }\n\n const struct {\n const char *d_spec_p;\n bool d_result;\n } DATA_ODD[] = {\n { \"\", true },\n { \"0\", true },\n { \"1\", false },\n { \"00\", true },\n { \"01\", false },\n { \"10\", false },\n { \"11\", false },\n { \"000\", true },\n { \"001\", false },\n { \"010\", false },\n { \"100\", false },\n { \"101\", false },\n { \"111\", false }\n };\n const size_t NUM_DATA_ODD = sizeof DATA_ODD \/ sizeof *DATA_ODD;\n\n for (size_t i = 0; i < NUM_DATA_ODD; ++i) {\n const char *const SPEC = DATA_ODD[i].d_spec_p;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_ODD[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP ==\n bsl::none_of(values.begin(), values.end(), IsOdd())));\n }\n}\n\n#endif\n\n\/\/ ============================================================================\n\/\/ MAIN PROGRAM\n\/\/ ----------------------------------------------------------------------------\n\nint main(int argc, char *argv[])\n{\n int test = argc > 1 ? atoi(argv[1]) : 0;\n\n verbose = argc > 2;\n veryVerbose = argc > 3;\n veryVeryVerbose = argc > 4;\n veryVeryVeryVerbose = argc > 5;\n\n printf(\"TEST \" __FILE__ \" CASE %d\\n\", test);\n\n switch (test) { case 0:\n case 1: {\n \/\/ --------------------------------------------------------------------\n \/\/ FUNCTIONALITY TEST\n \/\/\n \/\/ Concerns:\n \/\/: 1 That the routines exist in the 'bsl' namespace and behave as\n \/\/ expected.\n \/\/\n \/\/ Plan:\n \/\/: 1 Run each method with an empty input range and verify that the\n \/\/: behavior is as expected.\n \/\/: 2 Run each method with a single-element input range and verify that\n \/\/: the behavior is as expected.\n \/\/: 3 Run each method with multiple-element input range and verify that\n \/\/: the behavior is as expected.\n \/\/\n \/\/ Testing:\n \/\/ bool all_of (InputIter first, InputIter last, PREDICATE pred);\n \/\/ bool any_of (InputIter first, InputIter last, PREDICATE pred);\n \/\/ bool none_of(InputIter first, InputIter last, PREDICATE pred);\n \/\/ --------------------------------------------------------------------\n\n if (verbose) printf(\"\\nFUNCTIONALITY TEST\"\n \"\\n==================\\n\");\n\n#ifndef BSLS_LIBRARYFEATURES_HAS_CPP11_BASELINE_LIBRARY\n runTestAllOf();\n runTestAnyOf();\n runTestNoneOf();\n#endif\n\n } break;\n default: {\n fprintf(stderr, \"WARNING: CASE `%d' NOT FOUND.\\n\", test);\n testStatus = -1;\n }\n }\n\n if (testStatus > 0) {\n fprintf(stderr, \"Error, non-zero test status = %d.\\n\", testStatus);\n }\n return testStatus;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Copyright 2020 Bloomberg Finance L.P.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ ----------------------------- END-OF-FILE ----------------------------------\n<|endoftext|>"} {"text":"\/\/ bslstl_algorithm.t.cpp -*-C++-*-\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \/\/ atoi\n#include \/\/ strlen\n\n\/\/ ============================================================================\n\/\/ TEST PLAN\n\/\/ ----------------------------------------------------------------------------\n\/\/ The component under test provides implementations for algorithms not\n\/\/ provided by the underlying standard library implementation.\n\/\/ ----------------------------------------------------------------------------\n\/\/\n\/\/ [ 1] bool all_of (InputIter first, InputIter last, PREDICATE pred);\n\/\/ [ 1] bool any_of (InputIter first, InputIter last, PREDICATE pred);\n\/\/ [ 1] bool none_of(InputIter first, InputIter last, PREDICATE pred);\n\/\/ ----------------------------------------------------------------------------\n\n\/\/ ============================================================================\n\/\/ STANDARD BDE ASSERT TEST FUNCTION\n\/\/ ----------------------------------------------------------------------------\n\/\/ NOTE: THIS IS A LOW-LEVEL COMPONENT AND MAY NOT USE ANY C++ LIBRARY\n\/\/ FUNCTIONS, INCLUDING IOSTREAMS.\n\nnamespace {\n\nint testStatus = 0;\n\nvoid aSsErT(bool b, const char *s, int i)\n{\n if (b) {\n printf(\"Error \" __FILE__ \"(%d): %s (failed)\\n\", i, s);\n if (testStatus >= 0 && testStatus <= 100) ++testStatus;\n }\n}\n\n} \/\/ close unnamed namespace\n\n\/\/ ============================================================================\n\/\/ STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS\n\/\/ ----------------------------------------------------------------------------\n\n#define ASSERT BSLS_BSLTESTUTIL_ASSERT\n#define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT\n#define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT\n#define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT\n#define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT\n#define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT\n#define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT\n#define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT\n#define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT\n#define ASSERTV BSLS_BSLTESTUTIL_ASSERTV\n\n#define Q BSLS_BSLTESTUTIL_Q \/\/ Quote identifier literally.\n#define P BSLS_BSLTESTUTIL_P \/\/ Print identifier and value.\n#define P_ BSLS_BSLTESTUTIL_P_ \/\/ P(X) without '\\n'.\n#define T_ BSLS_BSLTESTUTIL_T_ \/\/ Print a tab (w\/o newline).\n#define L_ BSLS_BSLTESTUTIL_L_ \/\/ current Line number\n\n#define RUN_EACH_TYPE BSLTF_TEMPLATETESTFACILITY_RUN_EACH_TYPE\n\n\/\/ ============================================================================\n\/\/ NEGATIVE-TEST MACRO ABBREVIATIONS\n\/\/ ----------------------------------------------------------------------------\n\n#define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR)\n#define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR)\n#define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR)\n#define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR)\n#define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR)\n#define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR)\n\n\/\/ ============================================================================\n\/\/ PRINTF FORMAT MACRO ABBREVIATIONS\n\/\/ ----------------------------------------------------------------------------\n\n#define ZU BSLS_BSLTESTUTIL_FORMAT_ZU\n\n\/\/ ============================================================================\n\/\/ GLOBAL TEST ALIASES\n\/\/ ----------------------------------------------------------------------------\n\nusing namespace BloombergLP;\n\n\/\/ ============================================================================\n\/\/ GLOBAL TEST VALUES\n\/\/ ----------------------------------------------------------------------------\n\nstatic bool verbose;\nstatic bool veryVerbose;\nstatic bool veryVeryVerbose;\nstatic bool veryVeryVeryVerbose;\n\n\/\/ ============================================================================\n\/\/ TEST FUNCTIONS\n\/\/ ----------------------------------------------------------------------------\n\n#ifndef BSLS_LIBRARYFEATURES_HAS_CPP11_BASELINE_LIBRARY\n\nstruct IsOdd {\n \/\/ A standard compliant C++03 unary predicate functor that returns 'true'\n \/\/ if an 'int' value is odd.\n\n \/\/ PUBLIC TYPES\n typedef char argument_type;\n typedef bool result_type;\n\n \/\/ ACCESSORS\n result_type operator()(argument_type value) const\n \/\/ Return 'true' if the specified 'value' is odd, and 'false'\n \/\/ otherwise.\n {\n return (value % 2) != 0;\n }\n};\n\n\/\/ A function (as opposed to a functor)\nbool isEven(char value)\n \/\/ Return 'true' if the specified 'value' is even, and 'false' otherwise.\n{\n return (value % 2) == 0;\n}\n\ntemplate \nvoid runTestAllOf()\n \/\/ Test driver for 'all_of'.\n{\n const struct {\n const char *d_spec_p;\n bool d_result;\n } DATA_EVEN[] = {\n { \"\", true },\n { \"0\", true },\n { \"1\", false },\n { \"00\", true },\n { \"01\", false },\n { \"10\", false },\n { \"11\", false },\n { \"000\", true },\n { \"001\", false },\n { \"010\", false },\n { \"100\", false },\n { \"101\", false },\n { \"111\", false }\n };\n const size_t NUM_DATA_EVEN = sizeof DATA_EVEN \/ sizeof *DATA_EVEN;\n\n for (size_t i = 0; i < NUM_DATA_EVEN; ++i) {\n const char *const SPEC = DATA_EVEN[i].d_spec_p;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_EVEN[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP == bsl::all_of(values.begin(), values.end(), isEven)));\n }\n\n const struct {\n const char *d_spec_p;\n bool d_result;\n } DATA_ODD[] = {\n { \"\", true },\n { \"0\", false },\n { \"1\", true },\n { \"00\", false },\n { \"01\", false },\n { \"10\", false },\n { \"11\", true },\n { \"000\", false },\n { \"001\", false },\n { \"010\", false },\n { \"100\", false },\n { \"101\", false },\n { \"111\", true }\n };\n const size_t NUM_DATA_ODD = sizeof DATA_ODD \/ sizeof *DATA_ODD;\n\n for (size_t i = 0; i < NUM_DATA_ODD; ++i) {\n const char *const SPEC = DATA_ODD[i].d_spec_p;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_ODD[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP ==\n bsl::all_of(values.begin(), values.end(), IsOdd())));\n }\n}\n\ntemplate \nvoid runTestAnyOf()\n \/\/ Test driver for 'any_of'.\n{\n const struct {\n const char *d_spec_p;\n bool d_result;\n } DATA_EVEN[] = {\n { \"\", false },\n { \"0\", true },\n { \"1\", false },\n { \"00\", true },\n { \"01\", true },\n { \"10\", true },\n { \"11\", false },\n { \"000\", true },\n { \"001\", true },\n { \"010\", true },\n { \"100\", true },\n { \"101\", true },\n { \"111\", false }\n };\n const size_t NUM_DATA_EVEN = sizeof DATA_EVEN \/ sizeof *DATA_EVEN;\n\n for (size_t i = 0; i < NUM_DATA_EVEN; ++i) {\n const char *const SPEC = DATA_EVEN[i].d_spec_p;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_EVEN[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP == bsl::any_of(values.begin(), values.end(), isEven)));\n }\n\n const struct {\n const char *d_spec_p;\n bool d_result;\n } DATA_ODD[] = {\n { \"\", false },\n { \"0\", false },\n { \"1\", true },\n { \"00\", false },\n { \"01\", true },\n { \"10\", true },\n { \"11\", true },\n { \"000\", false },\n { \"001\", true },\n { \"010\", true },\n { \"100\", true },\n { \"101\", true },\n { \"111\", true }\n };\n const size_t NUM_DATA_ODD = sizeof DATA_ODD \/ sizeof *DATA_ODD;\n\n for (size_t i = 0; i < NUM_DATA_ODD; ++i) {\n const char *const SPEC = DATA_ODD[i].d_spec_p;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_ODD[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP ==\n bsl::any_of(values.begin(), values.end(), IsOdd())));\n }\n}\n\ntemplate \nvoid runTestNoneOf()\n \/\/ Test driver for 'none_of'.\n{\n const struct {\n const char *d_spec_p;\n bool d_result;\n } DATA_EVEN[] = {\n { \"\", true },\n { \"0\", false },\n { \"1\", true },\n { \"00\", false },\n { \"01\", false },\n { \"10\", false },\n { \"11\", true },\n { \"000\", false },\n { \"001\", false },\n { \"010\", false },\n { \"100\", false },\n { \"101\", false },\n { \"111\", true }\n };\n const size_t NUM_DATA_EVEN = sizeof DATA_EVEN \/ sizeof *DATA_EVEN;\n\n for (size_t i = 0; i < NUM_DATA_EVEN; ++i) {\n const char *const SPEC = DATA_EVEN[i].d_spec_p;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_EVEN[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP ==\n bsl::none_of(values.begin(), values.end(), isEven)));\n }\n\n const struct {\n const char *d_spec_p;\n bool d_result;\n } DATA_ODD[] = {\n { \"\", true },\n { \"0\", true },\n { \"1\", false },\n { \"00\", true },\n { \"01\", false },\n { \"10\", false },\n { \"11\", false },\n { \"000\", true },\n { \"001\", false },\n { \"010\", false },\n { \"100\", false },\n { \"101\", false },\n { \"111\", false }\n };\n const size_t NUM_DATA_ODD = sizeof DATA_ODD \/ sizeof *DATA_ODD;\n\n for (size_t i = 0; i < NUM_DATA_ODD; ++i) {\n const char *const SPEC = DATA_ODD[i].d_spec_p;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_ODD[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP ==\n bsl::none_of(values.begin(), values.end(), IsOdd())));\n }\n}\n\n#endif\n\n\/\/ ============================================================================\n\/\/ MAIN PROGRAM\n\/\/ ----------------------------------------------------------------------------\n\nint main(int argc, char *argv[])\n{\n int test = argc > 1 ? atoi(argv[1]) : 0;\n\n verbose = argc > 2;\n veryVerbose = argc > 3;\n veryVeryVerbose = argc > 4;\n veryVeryVeryVerbose = argc > 5;\n\n printf(\"TEST \" __FILE__ \" CASE %d\\n\", test);\n\n switch (test) { case 0:\n case 1: {\n \/\/ --------------------------------------------------------------------\n \/\/ FUNCTIONALITY TEST\n \/\/\n \/\/ Concerns:\n \/\/: 1 That the routines exist in the 'bsl' namespace and behave as\n \/\/ expected.\n \/\/\n \/\/ Plan:\n \/\/: 1 Run each method with an empty input range and verify that the\n \/\/: behavior is as expected.\n \/\/: 2 Run each method with a single-element input range and verify that\n \/\/: the behavior is as expected.\n \/\/: 3 Run each method with multiple-element input range and verify that\n \/\/: the behavior is as expected.\n \/\/\n \/\/ Testing:\n \/\/ bool all_of (InputIter first, InputIter last, PREDICATE pred);\n \/\/ bool any_of (InputIter first, InputIter last, PREDICATE pred);\n \/\/ bool none_of(InputIter first, InputIter last, PREDICATE pred);\n \/\/ --------------------------------------------------------------------\n\n if (verbose) printf(\"\\nFUNCTIONALITY TEST\"\n \"\\n==================\\n\");\n\n#ifndef BSLS_LIBRARYFEATURES_HAS_CPP11_BASELINE_LIBRARY\n runTestAllOf();\n runTestAnyOf();\n runTestNoneOf();\n#endif\n\n } break;\n default: {\n fprintf(stderr, \"WARNING: CASE `%d' NOT FOUND.\\n\", test);\n testStatus = -1;\n }\n }\n\n if (testStatus > 0) {\n fprintf(stderr, \"Error, non-zero test status = %d.\\n\", testStatus);\n }\n return testStatus;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Copyright 2020 Bloomberg Finance L.P.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ ----------------------------- END-OF-FILE ----------------------------------\nAlphabetize the includes of the blstf headers\/\/ bslstl_algorithm.t.cpp -*-C++-*-\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \/\/ atoi\n#include \/\/ strlen\n\n\/\/ ============================================================================\n\/\/ TEST PLAN\n\/\/ ----------------------------------------------------------------------------\n\/\/ The component under test provides implementations for algorithms not\n\/\/ provided by the underlying standard library implementation.\n\/\/ ----------------------------------------------------------------------------\n\/\/\n\/\/ [ 1] bool all_of (InputIter first, InputIter last, PREDICATE pred);\n\/\/ [ 1] bool any_of (InputIter first, InputIter last, PREDICATE pred);\n\/\/ [ 1] bool none_of(InputIter first, InputIter last, PREDICATE pred);\n\/\/ ----------------------------------------------------------------------------\n\n\/\/ ============================================================================\n\/\/ STANDARD BDE ASSERT TEST FUNCTION\n\/\/ ----------------------------------------------------------------------------\n\/\/ NOTE: THIS IS A LOW-LEVEL COMPONENT AND MAY NOT USE ANY C++ LIBRARY\n\/\/ FUNCTIONS, INCLUDING IOSTREAMS.\n\nnamespace {\n\nint testStatus = 0;\n\nvoid aSsErT(bool b, const char *s, int i)\n{\n if (b) {\n printf(\"Error \" __FILE__ \"(%d): %s (failed)\\n\", i, s);\n if (testStatus >= 0 && testStatus <= 100) ++testStatus;\n }\n}\n\n} \/\/ close unnamed namespace\n\n\/\/ ============================================================================\n\/\/ STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS\n\/\/ ----------------------------------------------------------------------------\n\n#define ASSERT BSLS_BSLTESTUTIL_ASSERT\n#define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT\n#define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT\n#define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT\n#define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT\n#define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT\n#define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT\n#define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT\n#define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT\n#define ASSERTV BSLS_BSLTESTUTIL_ASSERTV\n\n#define Q BSLS_BSLTESTUTIL_Q \/\/ Quote identifier literally.\n#define P BSLS_BSLTESTUTIL_P \/\/ Print identifier and value.\n#define P_ BSLS_BSLTESTUTIL_P_ \/\/ P(X) without '\\n'.\n#define T_ BSLS_BSLTESTUTIL_T_ \/\/ Print a tab (w\/o newline).\n#define L_ BSLS_BSLTESTUTIL_L_ \/\/ current Line number\n\n#define RUN_EACH_TYPE BSLTF_TEMPLATETESTFACILITY_RUN_EACH_TYPE\n\n\/\/ ============================================================================\n\/\/ NEGATIVE-TEST MACRO ABBREVIATIONS\n\/\/ ----------------------------------------------------------------------------\n\n#define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR)\n#define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR)\n#define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR)\n#define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR)\n#define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR)\n#define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR)\n\n\/\/ ============================================================================\n\/\/ PRINTF FORMAT MACRO ABBREVIATIONS\n\/\/ ----------------------------------------------------------------------------\n\n#define ZU BSLS_BSLTESTUTIL_FORMAT_ZU\n\n\/\/ ============================================================================\n\/\/ GLOBAL TEST ALIASES\n\/\/ ----------------------------------------------------------------------------\n\nusing namespace BloombergLP;\n\n\/\/ ============================================================================\n\/\/ GLOBAL TEST VALUES\n\/\/ ----------------------------------------------------------------------------\n\nstatic bool verbose;\nstatic bool veryVerbose;\nstatic bool veryVeryVerbose;\nstatic bool veryVeryVeryVerbose;\n\n\/\/ ============================================================================\n\/\/ TEST FUNCTIONS\n\/\/ ----------------------------------------------------------------------------\n\n#ifndef BSLS_LIBRARYFEATURES_HAS_CPP11_BASELINE_LIBRARY\n\nstruct IsOdd {\n \/\/ A standard compliant C++03 unary predicate functor that returns 'true'\n \/\/ if an 'int' value is odd.\n\n \/\/ PUBLIC TYPES\n typedef char argument_type;\n typedef bool result_type;\n\n \/\/ ACCESSORS\n result_type operator()(argument_type value) const\n \/\/ Return 'true' if the specified 'value' is odd, and 'false'\n \/\/ otherwise.\n {\n return (value % 2) != 0;\n }\n};\n\n\/\/ A function (as opposed to a functor)\nbool isEven(char value)\n \/\/ Return 'true' if the specified 'value' is even, and 'false' otherwise.\n{\n return (value % 2) == 0;\n}\n\ntemplate \nvoid runTestAllOf()\n \/\/ Test driver for 'all_of'.\n{\n const struct {\n const char *d_spec_p;\n bool d_result;\n } DATA_EVEN[] = {\n { \"\", true },\n { \"0\", true },\n { \"1\", false },\n { \"00\", true },\n { \"01\", false },\n { \"10\", false },\n { \"11\", false },\n { \"000\", true },\n { \"001\", false },\n { \"010\", false },\n { \"100\", false },\n { \"101\", false },\n { \"111\", false }\n };\n const size_t NUM_DATA_EVEN = sizeof DATA_EVEN \/ sizeof *DATA_EVEN;\n\n for (size_t i = 0; i < NUM_DATA_EVEN; ++i) {\n const char *const SPEC = DATA_EVEN[i].d_spec_p;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_EVEN[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP == bsl::all_of(values.begin(), values.end(), isEven)));\n }\n\n const struct {\n const char *d_spec_p;\n bool d_result;\n } DATA_ODD[] = {\n { \"\", true },\n { \"0\", false },\n { \"1\", true },\n { \"00\", false },\n { \"01\", false },\n { \"10\", false },\n { \"11\", true },\n { \"000\", false },\n { \"001\", false },\n { \"010\", false },\n { \"100\", false },\n { \"101\", false },\n { \"111\", true }\n };\n const size_t NUM_DATA_ODD = sizeof DATA_ODD \/ sizeof *DATA_ODD;\n\n for (size_t i = 0; i < NUM_DATA_ODD; ++i) {\n const char *const SPEC = DATA_ODD[i].d_spec_p;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_ODD[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP ==\n bsl::all_of(values.begin(), values.end(), IsOdd())));\n }\n}\n\ntemplate \nvoid runTestAnyOf()\n \/\/ Test driver for 'any_of'.\n{\n const struct {\n const char *d_spec_p;\n bool d_result;\n } DATA_EVEN[] = {\n { \"\", false },\n { \"0\", true },\n { \"1\", false },\n { \"00\", true },\n { \"01\", true },\n { \"10\", true },\n { \"11\", false },\n { \"000\", true },\n { \"001\", true },\n { \"010\", true },\n { \"100\", true },\n { \"101\", true },\n { \"111\", false }\n };\n const size_t NUM_DATA_EVEN = sizeof DATA_EVEN \/ sizeof *DATA_EVEN;\n\n for (size_t i = 0; i < NUM_DATA_EVEN; ++i) {\n const char *const SPEC = DATA_EVEN[i].d_spec_p;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_EVEN[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP == bsl::any_of(values.begin(), values.end(), isEven)));\n }\n\n const struct {\n const char *d_spec_p;\n bool d_result;\n } DATA_ODD[] = {\n { \"\", false },\n { \"0\", false },\n { \"1\", true },\n { \"00\", false },\n { \"01\", true },\n { \"10\", true },\n { \"11\", true },\n { \"000\", false },\n { \"001\", true },\n { \"010\", true },\n { \"100\", true },\n { \"101\", true },\n { \"111\", true }\n };\n const size_t NUM_DATA_ODD = sizeof DATA_ODD \/ sizeof *DATA_ODD;\n\n for (size_t i = 0; i < NUM_DATA_ODD; ++i) {\n const char *const SPEC = DATA_ODD[i].d_spec_p;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_ODD[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP ==\n bsl::any_of(values.begin(), values.end(), IsOdd())));\n }\n}\n\ntemplate \nvoid runTestNoneOf()\n \/\/ Test driver for 'none_of'.\n{\n const struct {\n const char *d_spec_p;\n bool d_result;\n } DATA_EVEN[] = {\n { \"\", true },\n { \"0\", false },\n { \"1\", true },\n { \"00\", false },\n { \"01\", false },\n { \"10\", false },\n { \"11\", true },\n { \"000\", false },\n { \"001\", false },\n { \"010\", false },\n { \"100\", false },\n { \"101\", false },\n { \"111\", true }\n };\n const size_t NUM_DATA_EVEN = sizeof DATA_EVEN \/ sizeof *DATA_EVEN;\n\n for (size_t i = 0; i < NUM_DATA_EVEN; ++i) {\n const char *const SPEC = DATA_EVEN[i].d_spec_p;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_EVEN[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP ==\n bsl::none_of(values.begin(), values.end(), isEven)));\n }\n\n const struct {\n const char *d_spec_p;\n bool d_result;\n } DATA_ODD[] = {\n { \"\", true },\n { \"0\", true },\n { \"1\", false },\n { \"00\", true },\n { \"01\", false },\n { \"10\", false },\n { \"11\", false },\n { \"000\", true },\n { \"001\", false },\n { \"010\", false },\n { \"100\", false },\n { \"101\", false },\n { \"111\", false }\n };\n const size_t NUM_DATA_ODD = sizeof DATA_ODD \/ sizeof *DATA_ODD;\n\n for (size_t i = 0; i < NUM_DATA_ODD; ++i) {\n const char *const SPEC = DATA_ODD[i].d_spec_p;\n const VALUE EXP =\n bsltf::TemplateTestFacility::create(DATA_ODD[i].d_result);\n\n bsltf::TestValuesArray values(SPEC);\n ASSERT((EXP ==\n bsl::none_of(values.begin(), values.end(), IsOdd())));\n }\n}\n\n#endif\n\n\/\/ ============================================================================\n\/\/ MAIN PROGRAM\n\/\/ ----------------------------------------------------------------------------\n\nint main(int argc, char *argv[])\n{\n int test = argc > 1 ? atoi(argv[1]) : 0;\n\n verbose = argc > 2;\n veryVerbose = argc > 3;\n veryVeryVerbose = argc > 4;\n veryVeryVeryVerbose = argc > 5;\n\n printf(\"TEST \" __FILE__ \" CASE %d\\n\", test);\n\n switch (test) { case 0:\n case 1: {\n \/\/ --------------------------------------------------------------------\n \/\/ FUNCTIONALITY TEST\n \/\/\n \/\/ Concerns:\n \/\/: 1 That the routines exist in the 'bsl' namespace and behave as\n \/\/ expected.\n \/\/\n \/\/ Plan:\n \/\/: 1 Run each method with an empty input range and verify that the\n \/\/: behavior is as expected.\n \/\/: 2 Run each method with a single-element input range and verify that\n \/\/: the behavior is as expected.\n \/\/: 3 Run each method with multiple-element input range and verify that\n \/\/: the behavior is as expected.\n \/\/\n \/\/ Testing:\n \/\/ bool all_of (InputIter first, InputIter last, PREDICATE pred);\n \/\/ bool any_of (InputIter first, InputIter last, PREDICATE pred);\n \/\/ bool none_of(InputIter first, InputIter last, PREDICATE pred);\n \/\/ --------------------------------------------------------------------\n\n if (verbose) printf(\"\\nFUNCTIONALITY TEST\"\n \"\\n==================\\n\");\n\n#ifndef BSLS_LIBRARYFEATURES_HAS_CPP11_BASELINE_LIBRARY\n runTestAllOf();\n runTestAnyOf();\n runTestNoneOf();\n#endif\n\n } break;\n default: {\n fprintf(stderr, \"WARNING: CASE `%d' NOT FOUND.\\n\", test);\n testStatus = -1;\n }\n }\n\n if (testStatus > 0) {\n fprintf(stderr, \"Error, non-zero test status = %d.\\n\", testStatus);\n }\n return testStatus;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Copyright 2020 Bloomberg Finance L.P.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ ----------------------------- END-OF-FILE ----------------------------------\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \n\nnamespace mlopen {\n\nstd::string GetFileName(const HIPOCProgram::FilePtr& f)\n{\n auto fd = fileno(f.get());\n std::string path = \"\/proc\/self\/fd\/\" + std::to_string(fd);\n std::array buffer{};\n readlink(path.c_str(), buffer.data(), buffer.size());\n return buffer.data();\n}\n\nhipModulePtr CreateModule(const std::string& program_name, std::string params)\n{ \n HIPOCProgram::FilePtr tmpsrc{std::tmpfile()};\n std::string src = GetKernelSrc(program_name);\n std::string src_name = GetFileName(tmpsrc);\n \n if (std::fwrite(src.c_str(), 1, src.size(), tmpsrc.get()) != src.size()) \n MLOPEN_THROW(\"Failed to write to src file\");\n \n std::system((HIP_OC_COMPILER + \n std::string(\" -march=hsail64 -mdevice=Fiji -cl-denorms-are-zero -save-temps=dump -nobin \") + \n params + \" \" +\n src_name).c_str());\n\n std::string obj_file = src_name + \"_obj\";\n\n std::system((HIP_OC_FINALIZER +\n std::string(\"-target=8:0:3 -hsail dump_0_Fiji.hsail -output=\") +\n obj_file\n ).c_str());\n\n hipModule_t raw_m;\n auto status = hipModuleLoad(&raw_m, obj_file.c_str());\n hipModulePtr m{raw_m};\n std::remove(obj_file.c_str());\n if (status != hipSuccess) MLOPEN_THROW(\"Failed creating module\");\n return m;\n}\n\nHIPOCProgram::HIPOCProgram()\n{}\nHIPOCProgram::HIPOCProgram(const std::string &program_name, std::string params)\n{\n this->module = CreateModule(program_name, params);\n}\n}\nLog commands#include \n#include \n#include \n\n#include \n\nnamespace mlopen {\n\nvoid execute(std::string s)\n{\n std::cout << s << std::endl;\n std::system(s.c_str());\n}\n\nstd::string quote(std::string s)\n{\n return '\"' + s + '\"';\n}\n\nstd::string GetFileName(const HIPOCProgram::FilePtr& f)\n{\n auto fd = fileno(f.get());\n std::string path = \"\/proc\/self\/fd\/\" + std::to_string(fd);\n std::array buffer{};\n if (readlink(path.c_str(), buffer.data(), buffer.size()-1) == -1) \n MLOPEN_THROW(\"Error reading filename\");\n return buffer.data();\n}\n\nhipModulePtr CreateModule(const std::string& program_name, std::string params)\n{ \n HIPOCProgram::FilePtr tmpsrc{std::tmpfile()};\n std::string src = GetKernelSrc(program_name);\n std::string src_name = GetFileName(tmpsrc);\n \n if (std::fwrite(src.c_str(), 1, src.size(), tmpsrc.get()) != src.size()) \n MLOPEN_THROW(\"Failed to write to src file\");\n \n execute(HIP_OC_COMPILER + \n std::string(\" -march=hsail64 -mdevice=Fiji -cl-denorms-are-zero -save-temps=dump -nobin \") + \n params + \" \" +\n quote(src_name));\n\n std::string obj_file = src_name + \"_obj\";\n\n execute(HIP_OC_FINALIZER +\n std::string(\" -target=8:0:3 -hsail dump_0_Fiji.hsail -output=\") +\n quote(obj_file)\n );\n\n hipModule_t raw_m;\n auto status = hipModuleLoad(&raw_m, obj_file.c_str());\n hipModulePtr m{raw_m};\n std::remove(obj_file.c_str());\n if (status != hipSuccess) MLOPEN_THROW(\"Failed creating module\");\n return m;\n}\n\nHIPOCProgram::HIPOCProgram()\n{}\nHIPOCProgram::HIPOCProgram(const std::string &program_name, std::string params)\n{\n this->module = CreateModule(program_name, params);\n}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2015 Patrick Putnam\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n#ifndef CLOTHO_NEUTRAL_ALLELE_HPP_\n#define CLOTHO_NEUTRAL_ALLELE_HPP_\n\n#include \"clotho\/data_spaces\/allele_space\/base_allele.hpp\"\n\n#include \"clotho\/utility\/state_object.hpp\"\n#include \"clotho\/utility\/log_helper.hpp\"\n\n#include \"clotho\/utility\/bit_helper.hpp\"\n\nnamespace clotho {\nnamespace genetics {\n\ntemplate < class PositionType >\nclass neutral_allele_vectorized : public base_allele_vectorized< PositionType > {\npublic:\n typedef base_allele_vectorized< PositionType > base_type;\n typedef neutral_allele_vectorized< PositionType > self_type;\n\n typedef unsigned long long block_type;\n typedef block_type * neutrality_vector_type;\n\n typedef clotho::utility::BitHelper< block_type > bit_helper_type;\n\n neutral_allele_vectorized( size_t a = 0 ) :\n base_type( a )\n , m_neutral( NULL )\n , m_block_size(0)\n , m_block_alloc(0)\n {\n this->grow( a );\n }\n\n bool getNeutralAt( size_t index ) const {\n assert( 0 <= index && index < this->m_pos_size );\n\n size_t bidx = index \/ bit_helper_type::BITS_PER_BLOCK;\n block_type bmask = bit_helper_type::bit_offset(index);\n\n return m_neutral[ bidx ] & bmask;\n }\n\n void setNeutralAt( size_t index, bool neu ) {\n assert( 0 <= index && index < this->m_pos_size );\n\n size_t bidx = index \/ bit_helper_type::BITS_PER_BLOCK;\n block_type mask = bit_helper_type::bit_offset(index);\n\n if( ((m_neutral[ bidx ] & mask) == mask) != neu )\n m_neutral[ bidx ] ^= mask;\n }\n\n\/\/ bool getNeutralAt( size_t index ) const {\n\/\/ return m_neutral[ index ];\n\/\/ }\n\/\/\n\/\/ void setNeutralAt( size_t index, bool neu ) {\n\/\/ if( index >= base_type::size() ) {\n\/\/ resize( index + 1 );\n\/\/ }\n\/\/\n\/\/ m_neutral[ index ] = neu;\n\/\/ }\n\n\/\/ bool isAllNeutral() const {\n\/\/ const_neutrality_iterator first = m_neutral.begin(), last = this->m_neutral.end();\n\/\/ bool all_neutral = true;\n\/\/ while( all_neutral && first != last ) {\n\/\/ all_neutral = *first++;\n\/\/ }\n\/\/\n\/\/ return all_neutral;\n\/\/ }\n bool isAllNeutral() const {\n for( size_t i = 0; i < m_block_size - 1; ++i ) {\n if( m_neutral[i] != bit_helper_type::ALL_SET )\n return false;\n }\n\n block_type mask = bit_helper_type::low_bit_mask( this->m_pos_size - 1 );\n\n\/\/ std::cerr << \"Comparing: \" << std::hex << m_neutral[m_block_size - 1] << \" to \" << mask << std::dec << std::endl;\n\n\/\/ std::cerr << \"Checking: \" << (m_block_size - 1) << std::endl;\n\n return m_neutral[m_block_size - 1] == mask;\n }\n\n void inherit( self_type & parent ) {\n \/\/ inherit positions\n assert( parent.size() <= this->size() );\n memcpy( this->m_positions, parent.m_positions, parent.size() * sizeof(typename base_type::base_type::position_type) );\n\n \/\/ inherit neutral\n assert( parent.m_block_size < this->m_block_alloc );\n std::copy( parent.m_neutral, parent.m_neutral + parent.m_block_size, this->m_neutral );\n }\n\n\/\/ neutrality_iterator neutral_begin() {\n\/\/ return m_neutral.begin();\n\/\/ }\n\/\/\n\/\/ neutrality_iterator neutral_end() {\n\/\/ return m_neutral.end();\n\/\/ }\n\/\/\n\/\/ const_neutrality_iterator neutral_begin() const {\n\/\/ return m_neutral.begin();\n\/\/ }\n\/\/\n\/\/ const_neutrality_iterator neutral_end() const {\n\/\/ return m_neutral.end();\n\/\/ }\n\n void push_back( self_type & other, size_t idx ) {\n size_t e = this->size();\n\n this->resize( e + 1 );\n\n this->setPositionAt( e, other.getPositionAt( idx ) );\n this->setNeutralAt( e, other.getNeutralAt( idx ) );\n }\n\n virtual size_t grow( size_t rows ) {\n this->resize( rows );\n\n return this->size();\n }\n\n virtual ~neutral_allele_vectorized() {\n if( m_neutral != NULL ) {\n delete [] m_neutral;\n }\n }\n\nprotected:\n\n virtual void resize( size_t s ) {\n base_type::resize( s );\n\n size_t bc = bit_helper_type::padded_block_count( s );\n if( bc > m_block_alloc ) {\n if( m_neutral != NULL ) {\n delete [] m_neutral;\n }\n\n m_neutral = new block_type[ bc ];\n m_block_alloc = bc;\n\n }\n\n memset( m_neutral, 0, m_block_alloc * sizeof(block_type));\n m_block_size = bc;\n }\n\n neutrality_vector_type m_neutral;\n size_t m_block_size, m_block_alloc;\n};\n\n} \/\/ namespace genetics\n} \/\/ namespace clotho\n\nnamespace clotho {\nnamespace utility {\n\ntemplate < class PositionType >\nstruct state_getter< clotho::genetics::neutral_allele_vectorized< PositionType > > {\n typedef clotho::genetics::neutral_allele_vectorized< PositionType > object_type;\n\n void operator()( boost::property_tree::ptree & s, object_type & obj ) {\n size_t all_count = obj.allele_count();\n size_t i = 0;\n while( i < all_count ) {\n boost::property_tree::ptree all;\n all.put( \"position\", obj.getPositionAt(i) );\n all.put( \"neutral\", obj.getNeutralAt(i) );\n\n s.push_back( std::make_pair(\"\", all ) );\n ++i;\n }\n \n }\n};\n\n} \/\/ namespace utility\n} \/\/ namespace clotho\n\n#endif \/\/ CLOTHO_NEUTRAL_ALLELE_HPP_\nCorrecting block calculation\/\/ Copyright 2015 Patrick Putnam\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n#ifndef CLOTHO_NEUTRAL_ALLELE_HPP_\n#define CLOTHO_NEUTRAL_ALLELE_HPP_\n\n#include \"clotho\/data_spaces\/allele_space\/base_allele.hpp\"\n\n#include \"clotho\/utility\/state_object.hpp\"\n#include \"clotho\/utility\/log_helper.hpp\"\n\n#include \"clotho\/utility\/bit_helper.hpp\"\n\nnamespace clotho {\nnamespace genetics {\n\ntemplate < class PositionType >\nclass neutral_allele_vectorized : public base_allele_vectorized< PositionType > {\npublic:\n typedef base_allele_vectorized< PositionType > base_type;\n typedef neutral_allele_vectorized< PositionType > self_type;\n\n typedef unsigned long long block_type;\n typedef block_type * neutrality_vector_type;\n\n typedef clotho::utility::BitHelper< block_type > bit_helper_type;\n\n neutral_allele_vectorized( size_t a = 0 ) :\n base_type( a )\n , m_neutral( NULL )\n , m_block_size(0)\n , m_block_alloc(0)\n {\n this->grow( a );\n }\n\n bool getNeutralAt( size_t index ) const {\n assert( 0 <= index && index < this->m_pos_size );\n\n size_t bidx = index \/ bit_helper_type::BITS_PER_BLOCK;\n block_type bmask = bit_helper_type::bit_offset(index);\n\n return m_neutral[ bidx ] & bmask;\n }\n\n void setNeutralAt( size_t index, bool neu ) {\n assert( 0 <= index && index < this->m_pos_size );\n\n size_t bidx = index \/ bit_helper_type::BITS_PER_BLOCK;\n block_type mask = bit_helper_type::bit_offset(index);\n\n if( ((m_neutral[ bidx ] & mask) == mask) != neu )\n m_neutral[ bidx ] ^= mask;\n }\n\n\/\/ bool getNeutralAt( size_t index ) const {\n\/\/ return m_neutral[ index ];\n\/\/ }\n\/\/\n\/\/ void setNeutralAt( size_t index, bool neu ) {\n\/\/ if( index >= base_type::size() ) {\n\/\/ resize( index + 1 );\n\/\/ }\n\/\/\n\/\/ m_neutral[ index ] = neu;\n\/\/ }\n\n\/\/ bool isAllNeutral() const {\n\/\/ const_neutrality_iterator first = m_neutral.begin(), last = this->m_neutral.end();\n\/\/ bool all_neutral = true;\n\/\/ while( all_neutral && first != last ) {\n\/\/ all_neutral = *first++;\n\/\/ }\n\/\/\n\/\/ return all_neutral;\n\/\/ }\n bool isAllNeutral() const {\n size_t N = (this->m_pos_size - 1) \/ bit_helper_type::BITS_PER_BLOCK;\n assert( N < m_block_size );\n for( size_t i = 0; i < N; ++i ) {\n if( m_neutral[i] != bit_helper_type::ALL_SET )\n return false;\n }\n\n block_type mask = bit_helper_type::low_bit_mask( this->m_pos_size - 1 );\n\n\/\/ std::cerr << \"Comparing: \" << std::hex << m_neutral[m_block_size - 1] << \" to \" << mask << std::dec << std::endl;\n\n\/\/ std::cerr << \"Checking: \" << (m_block_size - 1) << std::endl;\n\n return m_neutral[N] == mask;\n }\n\n void inherit( self_type & parent ) {\n \/\/ inherit positions\n assert( parent.size() <= this->size() );\n memcpy( this->m_positions, parent.m_positions, parent.size() * sizeof(typename base_type::base_type::position_type) );\n\n \/\/ inherit neutral\n assert( parent.m_block_size < this->m_block_alloc );\n std::copy( parent.m_neutral, parent.m_neutral + parent.m_block_size, this->m_neutral );\n }\n\n\/\/ neutrality_iterator neutral_begin() {\n\/\/ return m_neutral.begin();\n\/\/ }\n\/\/\n\/\/ neutrality_iterator neutral_end() {\n\/\/ return m_neutral.end();\n\/\/ }\n\/\/\n\/\/ const_neutrality_iterator neutral_begin() const {\n\/\/ return m_neutral.begin();\n\/\/ }\n\/\/\n\/\/ const_neutrality_iterator neutral_end() const {\n\/\/ return m_neutral.end();\n\/\/ }\n\n void push_back( self_type & other, size_t idx ) {\n size_t e = this->size();\n\n this->resize( e + 1 );\n\n this->setPositionAt( e, other.getPositionAt( idx ) );\n this->setNeutralAt( e, other.getNeutralAt( idx ) );\n }\n\n virtual size_t grow( size_t rows ) {\n this->resize( rows );\n\n return this->size();\n }\n\n virtual ~neutral_allele_vectorized() {\n if( m_neutral != NULL ) {\n delete [] m_neutral;\n }\n }\n\nprotected:\n\n virtual void resize( size_t s ) {\n base_type::resize( s );\n\n size_t bc = bit_helper_type::padded_block_count( s );\n if( bc > m_block_alloc ) {\n if( m_neutral != NULL ) {\n delete [] m_neutral;\n }\n\n m_neutral = new block_type[ bc ];\n m_block_alloc = bc;\n\n }\n\n memset( m_neutral, 0, m_block_alloc * sizeof(block_type));\n m_block_size = bc;\n }\n\n neutrality_vector_type m_neutral;\n size_t m_block_size, m_block_alloc;\n};\n\n} \/\/ namespace genetics\n} \/\/ namespace clotho\n\nnamespace clotho {\nnamespace utility {\n\ntemplate < class PositionType >\nstruct state_getter< clotho::genetics::neutral_allele_vectorized< PositionType > > {\n typedef clotho::genetics::neutral_allele_vectorized< PositionType > object_type;\n\n void operator()( boost::property_tree::ptree & s, object_type & obj ) {\n size_t all_count = obj.allele_count();\n size_t i = 0;\n while( i < all_count ) {\n boost::property_tree::ptree all;\n all.put( \"position\", obj.getPositionAt(i) );\n all.put( \"neutral\", obj.getNeutralAt(i) );\n\n s.push_back( std::make_pair(\"\", all ) );\n ++i;\n }\n \n }\n};\n\n} \/\/ namespace utility\n} \/\/ namespace clotho\n\n#endif \/\/ CLOTHO_NEUTRAL_ALLELE_HPP_\n<|endoftext|>"} {"text":"\/*\n * MRustC - Rust Compiler\n * - By John Hodge (Mutabah\/thePowersGang)\n *\n * hir_typeck\/impl_ref.cpp\n * - Reference to a trait implementation (either a bound or a impl block)\n *\/\n#include \"impl_ref.hpp\"\n#include \n#include \"static.hpp\" \/\/ for monomorphise_type_with\n\nbool ImplRef::more_specific_than(const ImplRef& other) const\n{\n TU_MATCH(Data, (this->m_data), (te),\n (TraitImpl,\n if( te.impl == nullptr ) {\n return false;\n }\n TU_MATCH(Data, (other.m_data), (oe),\n (TraitImpl,\n if( oe.impl == nullptr ) {\n return true;\n }\n return te.impl->more_specific_than( *oe.impl );\n ),\n (BoundedPtr,\n return false;\n ),\n (Bounded,\n return false;\n )\n )\n ),\n (BoundedPtr,\n if( !other.m_data.is_BoundedPtr() )\n return false;\n const auto& oe = other.m_data.as_BoundedPtr();\n assert( *te.type == *oe.type );\n assert( *te.trait_args == *oe.trait_args );\n if( te.assoc->size() > oe.assoc->size() )\n return true;\n return false;\n ),\n (Bounded,\n if( !other.m_data.is_Bounded() )\n return false;\n const auto& oe = other.m_data.as_Bounded();\n assert( te.type == oe.type );\n assert( te.trait_args == oe.trait_args );\n if( te.assoc.size() > oe.assoc.size() )\n return true;\n return false;\n )\n )\n throw \"\";\n}\nbool ImplRef::overlaps_with(const ::HIR::Crate& crate, const ImplRef& other) const\n{\n if( this->m_data.tag() != other.m_data.tag() )\n return false;\n TU_MATCH(Data, (this->m_data, other.m_data), (te, oe),\n (TraitImpl,\n if( te.impl != nullptr && oe.impl != nullptr )\n return te.impl->overlaps_with( crate, *oe.impl );\n ),\n (BoundedPtr,\n \/\/ TODO: Bounded and BoundedPtr are compatible\n if( *te.type != *oe.type )\n return false;\n if( *te.trait_args != *oe.trait_args )\n return false;\n \/\/ Don't check associated types\n return true;\n ),\n (Bounded,\n if( te.type != oe.type )\n return false;\n if( te.trait_args != oe.trait_args )\n return false;\n \/\/ Don't check associated types\n return true;\n )\n )\n return false;\n}\nbool ImplRef::has_magic_params() const\n{\n if(const auto* e = m_data.opt_TraitImpl())\n {\n for(const auto& t : e->impl_params.m_types)\n if( visit_ty_with(t, [](const ::HIR::TypeRef& t){ return t.data().is_Generic() && (t.data().as_Generic().binding >> 8) == 2; }) )\n return true;\n }\n return false;\n}\nbool ImplRef::type_is_specialisable(const char* name) const\n{\n TU_MATCH(Data, (this->m_data), (e),\n (TraitImpl,\n if( e.impl == nullptr ) {\n \/\/ No impl yet? This type is specialisable.\n return true;\n }\n \/\/TODO(Span(), \"type_is_specializable - Impl = \" << *this << \", Type = \" << name);\n auto it = e.impl->m_types.find(name);\n if( it == e.impl->m_types.end() ) {\n TODO(Span(), \"Handle missing type in \" << *this << \", name = \" << name);\n return false;\n }\n return it->second.is_specialisable;\n ),\n (BoundedPtr,\n return false;\n ),\n (Bounded,\n return false;\n )\n )\n throw \"\";\n}\n\n\/\/ Returns a closure to monomorphise including placeholders (if present)\nImplRef::Monomorph ImplRef::get_cb_monomorph_traitimpl(const Span& sp) const\n{\n const auto& e = this->m_data.as_TraitImpl();\n return Monomorph(e);\n}\n\n::HIR::TypeRef ImplRef::Monomorph::get_type(const Span& sp, const ::HIR::GenericRef& ge) const \/*override*\/\n{\n if( ge.is_self() )\n {\n \/\/ Store (or cache) a monomorphisation of Self, and error if this recurses\n if( this->ti.self_cache == ::HIR::TypeRef() ) {\n this->ti.self_cache = ::HIR::TypeRef::new_diverge();\n this->ti.self_cache = this->monomorph_type(sp, this->ti.impl->m_type);\n }\n else if( this->ti.self_cache == ::HIR::TypeRef::new_diverge() ) {\n \/\/ BUG!\n BUG(sp, \"Use of `Self` in expansion of `Self`\");\n }\n else {\n }\n return this->ti.self_cache.clone();\n }\n ASSERT_BUG(sp, ge.binding < 256, \"Binding in \" << ge << \" out of range (>=256)\");\n ASSERT_BUG(sp, ge.binding < this->ti.impl_params.m_types.size(), \"Binding in \" << ge << \" out of range (>= \" << this->ti.impl_params.m_types.size() << \")\");\n return this->ti.impl_params.m_types.at(ge.binding).clone();\n}\n::HIR::ConstGeneric ImplRef::Monomorph::get_value(const Span& sp, const ::HIR::GenericRef& val) const \/*override*\/\n{\n ASSERT_BUG(sp, val.binding < 256, \"Generic value binding in \" << val << \" out of range (>=256)\");\n ASSERT_BUG(sp, val.binding < this->ti.impl_params.m_values.size(), \"Generic value binding in \" << val << \" out of range (>= \" << this->ti.impl_params.m_values.size() << \")\");\n return this->ti.impl_params.m_values.at(val.binding).clone();\n}\n\n::HIR::TypeRef ImplRef::get_impl_type() const\n{\n Span sp;\n TU_MATCH(Data, (this->m_data), (e),\n (TraitImpl,\n if( e.impl == nullptr ) {\n BUG(Span(), \"nullptr\");\n }\n return this->get_cb_monomorph_traitimpl(sp).monomorph_type(sp, e.impl->m_type);\n ),\n (BoundedPtr,\n return e.type->clone();\n ),\n (Bounded,\n return e.type.clone();\n )\n )\n throw \"\";\n}\n::HIR::PathParams ImplRef::get_trait_params() const\n{\n Span sp;\n TU_MATCH(Data, (this->m_data), (e),\n (TraitImpl,\n if( e.impl == nullptr ) {\n BUG(Span(), \"nullptr\");\n }\n\n return this->get_cb_monomorph_traitimpl(sp).monomorph_path_params(sp, e.impl->m_trait_args, true);\n ),\n (BoundedPtr,\n return e.trait_args->clone();\n ),\n (Bounded,\n return e.trait_args.clone();\n )\n )\n throw \"\";\n}\n::HIR::TypeRef ImplRef::get_trait_ty_param(unsigned int idx) const\n{\n Span sp;\n TU_MATCH(Data, (this->m_data), (e),\n (TraitImpl,\n if( e.impl == nullptr ) {\n BUG(Span(), \"nullptr\");\n }\n if( idx >= e.impl->m_trait_args.m_types.size() )\n return ::HIR::TypeRef();\n return this->get_cb_monomorph_traitimpl(sp).monomorph_type(sp, e.impl->m_trait_args.m_types[idx]);\n ),\n (BoundedPtr,\n if( idx >= e.trait_args->m_types.size() )\n return ::HIR::TypeRef();\n return e.trait_args->m_types.at(idx).clone();\n ),\n (Bounded,\n if( idx >= e.trait_args.m_types.size() )\n return ::HIR::TypeRef();\n return e.trait_args.m_types.at(idx).clone();\n )\n )\n throw \"\";\n TODO(Span(), \"\");\n}\n\n::HIR::TypeRef ImplRef::get_type(const char* name) const\n{\n if( !name[0] )\n return ::HIR::TypeRef();\n static Span sp;\n TU_MATCH(Data, (this->m_data), (e),\n (TraitImpl,\n auto it = e.impl->m_types.find(name);\n if( it == e.impl->m_types.end() )\n return ::HIR::TypeRef();\n const ::HIR::TypeRef& tpl_ty = it->second.data;\n DEBUG(\"name=\" << name << \" tpl_ty=\" << tpl_ty << \" \" << *this);\n if( monomorphise_type_needed(tpl_ty) ) {\n return this->get_cb_monomorph_traitimpl(sp).monomorph_type(sp, tpl_ty);\n }\n else {\n return tpl_ty.clone();\n }\n ),\n (BoundedPtr,\n auto it = e.assoc->find(name);\n if(it == e.assoc->end())\n return ::HIR::TypeRef();\n return it->second.type.clone();\n ),\n (Bounded,\n auto it = e.assoc.find(name);\n if(it == e.assoc.end())\n return ::HIR::TypeRef();\n return it->second.type.clone();\n )\n )\n return ::HIR::TypeRef();\n}\n\n::std::ostream& operator<<(::std::ostream& os, const ImplRef& x)\n{\n TU_MATCH_HDR( (x.m_data), { )\n TU_ARM(x.m_data, TraitImpl, e) {\n if( e.impl == nullptr ) {\n os << \"none\";\n }\n else {\n os << \"impl\";\n os << \"(\" << e.impl << \")\";\n if( e.impl->m_params.m_types.size() )\n {\n os << \"<\";\n for( unsigned int i = 0; i < e.impl->m_params.m_types.size(); i ++ )\n {\n const auto& ty_d = e.impl->m_params.m_types[i];\n os << ty_d.m_name;\n os << \",\";\n }\n os << \">\";\n }\n os << \" \" << *e.trait_path << e.impl->m_trait_args << \" for \" << e.impl->m_type << e.impl->m_params.fmt_bounds();\n os << \" {\";\n for( unsigned int i = 0; i < e.impl->m_params.m_types.size(); i ++ )\n {\n const auto& ty_d = e.impl->m_params.m_types[i];\n os << ty_d.m_name << \" = \";\n if( e.impl_params.m_types[i] != HIR::TypeRef() ) {\n os << e.impl_params.m_types[i];\n }\n else {\n os << \"?\";\n }\n os << \",\";\n }\n for(const auto& aty : e.impl->m_types)\n {\n os << \"Self::\" << aty.first << \" = \" << aty.second.data << \",\";\n }\n os << \"}\";\n }\n }\n TU_ARM(x.m_data, BoundedPtr, e) {\n assert(e.type);\n assert(e.trait_args);\n assert(e.assoc);\n os << \"bound (ptr) \" << *e.type << \" : ?\" << *e.trait_args << \" + {\" << *e.assoc << \"}\";\n }\n TU_ARM(x.m_data, Bounded, e) {\n os << \"bound \" << e.type << \" : ?\" << e.trait_args << \" + {\"<HIR Typecheck - Tweak logic for `type_is_specialisable`\/*\n * MRustC - Rust Compiler\n * - By John Hodge (Mutabah\/thePowersGang)\n *\n * hir_typeck\/impl_ref.cpp\n * - Reference to a trait implementation (either a bound or a impl block)\n *\/\n#include \"impl_ref.hpp\"\n#include \n#include \"static.hpp\" \/\/ for monomorphise_type_with\n\nbool ImplRef::more_specific_than(const ImplRef& other) const\n{\n TU_MATCH(Data, (this->m_data), (te),\n (TraitImpl,\n if( te.impl == nullptr ) {\n return false;\n }\n TU_MATCH(Data, (other.m_data), (oe),\n (TraitImpl,\n if( oe.impl == nullptr ) {\n return true;\n }\n return te.impl->more_specific_than( *oe.impl );\n ),\n (BoundedPtr,\n return false;\n ),\n (Bounded,\n return false;\n )\n )\n ),\n (BoundedPtr,\n if( !other.m_data.is_BoundedPtr() )\n return false;\n const auto& oe = other.m_data.as_BoundedPtr();\n assert( *te.type == *oe.type );\n assert( *te.trait_args == *oe.trait_args );\n if( te.assoc->size() > oe.assoc->size() )\n return true;\n return false;\n ),\n (Bounded,\n if( !other.m_data.is_Bounded() )\n return false;\n const auto& oe = other.m_data.as_Bounded();\n assert( te.type == oe.type );\n assert( te.trait_args == oe.trait_args );\n if( te.assoc.size() > oe.assoc.size() )\n return true;\n return false;\n )\n )\n throw \"\";\n}\nbool ImplRef::overlaps_with(const ::HIR::Crate& crate, const ImplRef& other) const\n{\n if( this->m_data.tag() != other.m_data.tag() )\n return false;\n TU_MATCH(Data, (this->m_data, other.m_data), (te, oe),\n (TraitImpl,\n if( te.impl != nullptr && oe.impl != nullptr )\n return te.impl->overlaps_with( crate, *oe.impl );\n ),\n (BoundedPtr,\n \/\/ TODO: Bounded and BoundedPtr are compatible\n if( *te.type != *oe.type )\n return false;\n if( *te.trait_args != *oe.trait_args )\n return false;\n \/\/ Don't check associated types\n return true;\n ),\n (Bounded,\n if( te.type != oe.type )\n return false;\n if( te.trait_args != oe.trait_args )\n return false;\n \/\/ Don't check associated types\n return true;\n )\n )\n return false;\n}\nbool ImplRef::has_magic_params() const\n{\n if(const auto* e = m_data.opt_TraitImpl())\n {\n for(const auto& t : e->impl_params.m_types)\n if( visit_ty_with(t, [](const ::HIR::TypeRef& t){ return t.data().is_Generic() && (t.data().as_Generic().binding >> 8) == 2; }) )\n return true;\n }\n return false;\n}\nbool ImplRef::type_is_specialisable(const char* name) const\n{\n TU_MATCH_HDRA( (this->m_data), {)\n TU_ARMA(TraitImpl, e) {\n if( e.impl == nullptr ) {\n \/\/ No impl yet? This type is specialisable.\n return true;\n }\n auto it = e.impl->m_types.find(name);\n if( it == e.impl->m_types.end() ) {\n \/\/ If not present (which might happen during UFCS resolution), assume that it's specialisable\n return true;\n }\n return it->second.is_specialisable;\n }\n TU_ARMA(BoundedPtr, e) {\n return false;\n }\n TU_ARMA(Bounded, E) {\n return false;\n }\n }\n throw \"\";\n}\n\n\/\/ Returns a closure to monomorphise including placeholders (if present)\nImplRef::Monomorph ImplRef::get_cb_monomorph_traitimpl(const Span& sp) const\n{\n const auto& e = this->m_data.as_TraitImpl();\n return Monomorph(e);\n}\n\n::HIR::TypeRef ImplRef::Monomorph::get_type(const Span& sp, const ::HIR::GenericRef& ge) const \/*override*\/\n{\n if( ge.is_self() )\n {\n \/\/ Store (or cache) a monomorphisation of Self, and error if this recurses\n if( this->ti.self_cache == ::HIR::TypeRef() ) {\n this->ti.self_cache = ::HIR::TypeRef::new_diverge();\n this->ti.self_cache = this->monomorph_type(sp, this->ti.impl->m_type);\n }\n else if( this->ti.self_cache == ::HIR::TypeRef::new_diverge() ) {\n \/\/ BUG!\n BUG(sp, \"Use of `Self` in expansion of `Self`\");\n }\n else {\n }\n return this->ti.self_cache.clone();\n }\n ASSERT_BUG(sp, ge.binding < 256, \"Binding in \" << ge << \" out of range (>=256)\");\n ASSERT_BUG(sp, ge.binding < this->ti.impl_params.m_types.size(), \"Binding in \" << ge << \" out of range (>= \" << this->ti.impl_params.m_types.size() << \")\");\n return this->ti.impl_params.m_types.at(ge.binding).clone();\n}\n::HIR::ConstGeneric ImplRef::Monomorph::get_value(const Span& sp, const ::HIR::GenericRef& val) const \/*override*\/\n{\n ASSERT_BUG(sp, val.binding < 256, \"Generic value binding in \" << val << \" out of range (>=256)\");\n ASSERT_BUG(sp, val.binding < this->ti.impl_params.m_values.size(), \"Generic value binding in \" << val << \" out of range (>= \" << this->ti.impl_params.m_values.size() << \")\");\n return this->ti.impl_params.m_values.at(val.binding).clone();\n}\n\n::HIR::TypeRef ImplRef::get_impl_type() const\n{\n Span sp;\n TU_MATCH(Data, (this->m_data), (e),\n (TraitImpl,\n if( e.impl == nullptr ) {\n BUG(Span(), \"nullptr\");\n }\n return this->get_cb_monomorph_traitimpl(sp).monomorph_type(sp, e.impl->m_type);\n ),\n (BoundedPtr,\n return e.type->clone();\n ),\n (Bounded,\n return e.type.clone();\n )\n )\n throw \"\";\n}\n::HIR::PathParams ImplRef::get_trait_params() const\n{\n Span sp;\n TU_MATCH(Data, (this->m_data), (e),\n (TraitImpl,\n if( e.impl == nullptr ) {\n BUG(Span(), \"nullptr\");\n }\n\n return this->get_cb_monomorph_traitimpl(sp).monomorph_path_params(sp, e.impl->m_trait_args, true);\n ),\n (BoundedPtr,\n return e.trait_args->clone();\n ),\n (Bounded,\n return e.trait_args.clone();\n )\n )\n throw \"\";\n}\n::HIR::TypeRef ImplRef::get_trait_ty_param(unsigned int idx) const\n{\n Span sp;\n TU_MATCH(Data, (this->m_data), (e),\n (TraitImpl,\n if( e.impl == nullptr ) {\n BUG(Span(), \"nullptr\");\n }\n if( idx >= e.impl->m_trait_args.m_types.size() )\n return ::HIR::TypeRef();\n return this->get_cb_monomorph_traitimpl(sp).monomorph_type(sp, e.impl->m_trait_args.m_types[idx]);\n ),\n (BoundedPtr,\n if( idx >= e.trait_args->m_types.size() )\n return ::HIR::TypeRef();\n return e.trait_args->m_types.at(idx).clone();\n ),\n (Bounded,\n if( idx >= e.trait_args.m_types.size() )\n return ::HIR::TypeRef();\n return e.trait_args.m_types.at(idx).clone();\n )\n )\n throw \"\";\n TODO(Span(), \"\");\n}\n\n::HIR::TypeRef ImplRef::get_type(const char* name) const\n{\n if( !name[0] )\n return ::HIR::TypeRef();\n static Span sp;\n TU_MATCH(Data, (this->m_data), (e),\n (TraitImpl,\n auto it = e.impl->m_types.find(name);\n if( it == e.impl->m_types.end() )\n return ::HIR::TypeRef();\n const ::HIR::TypeRef& tpl_ty = it->second.data;\n DEBUG(\"name=\" << name << \" tpl_ty=\" << tpl_ty << \" \" << *this);\n if( monomorphise_type_needed(tpl_ty) ) {\n return this->get_cb_monomorph_traitimpl(sp).monomorph_type(sp, tpl_ty);\n }\n else {\n return tpl_ty.clone();\n }\n ),\n (BoundedPtr,\n auto it = e.assoc->find(name);\n if(it == e.assoc->end())\n return ::HIR::TypeRef();\n return it->second.type.clone();\n ),\n (Bounded,\n auto it = e.assoc.find(name);\n if(it == e.assoc.end())\n return ::HIR::TypeRef();\n return it->second.type.clone();\n )\n )\n return ::HIR::TypeRef();\n}\n\n::std::ostream& operator<<(::std::ostream& os, const ImplRef& x)\n{\n TU_MATCH_HDR( (x.m_data), { )\n TU_ARM(x.m_data, TraitImpl, e) {\n if( e.impl == nullptr ) {\n os << \"none\";\n }\n else {\n os << \"impl\";\n os << \"(\" << e.impl << \")\";\n if( e.impl->m_params.m_types.size() )\n {\n os << \"<\";\n for( unsigned int i = 0; i < e.impl->m_params.m_types.size(); i ++ )\n {\n const auto& ty_d = e.impl->m_params.m_types[i];\n os << ty_d.m_name;\n os << \",\";\n }\n os << \">\";\n }\n os << \" \" << *e.trait_path << e.impl->m_trait_args << \" for \" << e.impl->m_type << e.impl->m_params.fmt_bounds();\n os << \" {\";\n for( unsigned int i = 0; i < e.impl->m_params.m_types.size(); i ++ )\n {\n const auto& ty_d = e.impl->m_params.m_types[i];\n os << ty_d.m_name << \" = \";\n if( e.impl_params.m_types[i] != HIR::TypeRef() ) {\n os << e.impl_params.m_types[i];\n }\n else {\n os << \"?\";\n }\n os << \",\";\n }\n for(const auto& aty : e.impl->m_types)\n {\n os << \"Self::\" << aty.first << \" = \" << aty.second.data << \",\";\n }\n os << \"}\";\n }\n }\n TU_ARM(x.m_data, BoundedPtr, e) {\n assert(e.type);\n assert(e.trait_args);\n assert(e.assoc);\n os << \"bound (ptr) \" << *e.type << \" : ?\" << *e.trait_args << \" + {\" << *e.assoc << \"}\";\n }\n TU_ARM(x.m_data, Bounded, e) {\n os << \"bound \" << e.type << \" : ?\" << e.trait_args << \" + {\"<"} {"text":"\/*++\nCopyright (c) 2012 Microsoft Corporation\n\nModule Name:\n\n qffpa_tactic.cpp\n\nAbstract:\n\n Tactic for QF_FPA benchmarks.\n\nAuthor:\n\n Christoph (cwinter) 2012-01-16\n\nNotes:\n\n--*\/\n#include\"tactical.h\"\n#include\"simplify_tactic.h\"\n#include\"bit_blaster_tactic.h\"\n#include\"sat_tactic.h\"\n#include\"fpa2bv_tactic.h\"\n\n#include\"qffpa_tactic.h\"\n\ntactic * mk_qffpa_tactic(ast_manager & m, params_ref const & p) {\n params_ref sat_simp_p = p;\n sat_simp_p .set_bool(\"elim_and\", true);\n\n return and_then(mk_simplify_tactic(m, p),\n mk_fpa2bv_tactic(m, p),\n using_params(mk_simplify_tactic(m, p), sat_simp_p),\n mk_bit_blaster_tactic(m, p),\n using_params(mk_simplify_tactic(m, p), sat_simp_p),\n mk_sat_tactic(m, p),\n mk_fail_if_undecided_tactic());\n}\n\nstruct is_non_qffpa_predicate {\n struct found {};\n ast_manager & m;\n float_util u;\n\n is_non_qffpa_predicate(ast_manager & _m) :m(_m), u(m) {}\n\n void operator()(var *) { throw found(); }\n\n void operator()(quantifier *) { throw found(); }\n\n void operator()(app * n) {\n sort * s = get_sort(n);\n if (!m.is_bool(s) && !(u.is_float(s) || u.is_rm(s)))\n throw found();\n family_id fid = s->get_family_id();\n if (fid == m.get_basic_family_id())\n return;\n if (fid == u.get_family_id())\n return;\n\n throw found();\n }\n};\n\nstruct is_non_qffpabv_predicate {\n struct found {};\n ast_manager & m;\n bv_util bu;\n float_util fu;\n\n is_non_qffpabv_predicate(ast_manager & _m) :m(_m), bu(m), fu(m) {}\n\n void operator()(var *) { throw found(); }\n\n void operator()(quantifier *) { throw found(); }\n\n void operator()(app * n) {\n sort * s = get_sort(n);\n if (!m.is_bool(s) && !(fu.is_float(s) || fu.is_rm(s) || bu.is_bv_sort(s)))\n throw found();\n family_id fid = s->get_family_id();\n if (fid == m.get_basic_family_id())\n return;\n if (fid == fu.get_family_id() || fid == bu.get_family_id())\n return;\n\n throw found();\n }\n};\n\nclass is_qffpa_probe : public probe {\npublic:\n virtual result operator()(goal const & g) {\n return !test(g);\n }\n};\n\nclass is_qffpabv_probe : public probe {\npublic:\n virtual result operator()(goal const & g) {\n return !test(g);\n }\n};\n\nprobe * mk_is_qffpa_probe() {\n return alloc(is_qffpa_probe);\n}\n\nprobe * mk_is_qffpabv_probe() {\n return alloc(is_qffpabv_probe);\n}\n bugfix for FPA\/*++\nCopyright (c) 2012 Microsoft Corporation\n\nModule Name:\n\n qffpa_tactic.cpp\n\nAbstract:\n\n Tactic for QF_FPA benchmarks.\n\nAuthor:\n\n Christoph (cwinter) 2012-01-16\n\nNotes:\n\n--*\/\n#include\"tactical.h\"\n#include\"simplify_tactic.h\"\n#include\"bit_blaster_tactic.h\"\n#include\"sat_tactic.h\"\n#include\"fpa2bv_tactic.h\"\n\n#include\"qffpa_tactic.h\"\n\ntactic * mk_qffpa_tactic(ast_manager & m, params_ref const & p) {\n params_ref sat_simp_p = p;\n sat_simp_p .set_bool(\"elim_and\", true);\n\n return and_then(mk_simplify_tactic(m, p),\n mk_fpa2bv_tactic(m, p),\n using_params(mk_simplify_tactic(m, p), sat_simp_p),\n mk_bit_blaster_tactic(m, p),\n using_params(mk_simplify_tactic(m, p), sat_simp_p),\n mk_sat_tactic(m, p),\n mk_fail_if_undecided_tactic());\n}\n\nstruct is_non_qffpa_predicate {\n struct found {};\n ast_manager & m;\n float_util u;\n\n is_non_qffpa_predicate(ast_manager & _m) :m(_m), u(m) {}\n\n void operator()(var *) { throw found(); }\n\n void operator()(quantifier *) { throw found(); }\n\n void operator()(app * n) {\n sort * s = get_sort(n);\n if (!m.is_bool(s) && !(u.is_float(s) || u.is_rm(s)))\n throw found();\n if (is_uninterp(n))\n throw found();\n family_id fid = s->get_family_id();\n if (fid == m.get_basic_family_id())\n return;\n if (fid == u.get_family_id())\n return;\n\n throw found();\n }\n};\n\nstruct is_non_qffpabv_predicate {\n struct found {};\n ast_manager & m;\n bv_util bu;\n float_util fu;\n\n is_non_qffpabv_predicate(ast_manager & _m) :m(_m), bu(m), fu(m) {}\n\n void operator()(var *) { throw found(); }\n\n void operator()(quantifier *) { throw found(); }\n\n void operator()(app * n) {\n sort * s = get_sort(n);\n if (!m.is_bool(s) && !(fu.is_float(s) || fu.is_rm(s) || bu.is_bv_sort(s)))\n throw found();\n if (is_uninterp(n))\n throw found();\n family_id fid = s->get_family_id();\n if (fid == m.get_basic_family_id())\n return;\n if (fid == fu.get_family_id() || fid == bu.get_family_id())\n return;\n\n throw found();\n }\n};\n\nclass is_qffpa_probe : public probe {\npublic:\n virtual result operator()(goal const & g) {\n return !test(g);\n }\n};\n\nclass is_qffpabv_probe : public probe {\npublic:\n virtual result operator()(goal const & g) {\n return !test(g);\n }\n};\n\nprobe * mk_is_qffpa_probe() {\n return alloc(is_qffpa_probe);\n}\n\nprobe * mk_is_qffpabv_probe() {\n return alloc(is_qffpabv_probe);\n}\n <|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n\n#include \"app\/l10n_util.h\"\n#include \"base\/scoped_comptr_win.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/view_ids.h\"\n#include \"chrome\/browser\/views\/bookmark_bar_view.h\"\n#include \"chrome\/browser\/views\/frame\/browser_view.h\"\n#include \"chrome\/browser\/views\/toolbar_view.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"views\/accessibility\/view_accessibility_wrapper.h\"\n#include \"views\/widget\/root_view.h\"\n#include \"views\/widget\/widget_win.h\"\n#include \"views\/window\/window.h\"\n\nnamespace {\n\nVARIANT id_self = {VT_I4, CHILDID_SELF};\n\n\/\/ Dummy class to force creation of ATL module, needed by COM to instantiate\n\/\/ ViewAccessibility.\nclass TestAtlModule : public CAtlDllModuleT< TestAtlModule > {};\nTestAtlModule test_atl_module_;\n\nclass BrowserViewsAccessibilityTest : public InProcessBrowserTest {\n public:\n BrowserViewsAccessibilityTest() {\n ::CoInitialize(NULL);\n }\n\n ~BrowserViewsAccessibilityTest() {\n ::CoUninitialize();\n }\n\n \/\/ Retrieves an instance of BrowserWindowTesting\n BrowserWindowTesting* GetBrowserWindowTesting() {\n BrowserWindow* browser_window = browser()->window();\n\n if (!browser_window)\n return NULL;\n\n return browser_window->GetBrowserWindowTesting();\n }\n\n \/\/ Retrieve an instance of BrowserView\n BrowserView* GetBrowserView() {\n return BrowserView::GetBrowserViewForNativeWindow(\n browser()->window()->GetNativeHandle());\n }\n\n \/\/ Retrieves and initializes an instance of LocationBarView.\n LocationBarView* GetLocationBarView() {\n BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();\n\n if (!browser_window_testing)\n return NULL;\n\n return GetBrowserWindowTesting()->GetLocationBarView();\n }\n\n \/\/ Retrieves and initializes an instance of ToolbarView.\n ToolbarView* GetToolbarView() {\n BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();\n\n if (!browser_window_testing)\n return NULL;\n\n return browser_window_testing->GetToolbarView();\n }\n\n \/\/ Retrieves and initializes an instance of BookmarkBarView.\n BookmarkBarView* GetBookmarkBarView() {\n BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();\n\n if (!browser_window_testing)\n return NULL;\n\n return browser_window_testing->GetBookmarkBarView();\n }\n\n \/\/ Retrieves and verifies the accessibility object for the given View.\n void TestViewAccessibilityObject(views::View* view, std::wstring name,\n int32 role) {\n ASSERT_TRUE(NULL != view);\n\n IAccessible* acc_obj = NULL;\n HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance(\n IID_IAccessible, reinterpret_cast(&acc_obj));\n ASSERT_EQ(S_OK, hr);\n ASSERT_TRUE(NULL != acc_obj);\n\n TestAccessibilityInfo(acc_obj, name, role);\n }\n\n\n \/\/ Verifies MSAA Name and Role properties of the given IAccessible.\n void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name,\n int32 role) {\n \/\/ Verify MSAA Name property.\n BSTR acc_name;\n\n HRESULT hr = acc_obj->get_accName(id_self, &acc_name);\n ASSERT_EQ(S_OK, hr);\n EXPECT_STREQ(acc_name, name.c_str());\n\n \/\/ Verify MSAA Role property.\n VARIANT acc_role;\n ::VariantInit(&acc_role);\n\n hr = acc_obj->get_accRole(id_self, &acc_role);\n ASSERT_EQ(S_OK, hr);\n EXPECT_EQ(VT_I4, acc_role.vt);\n EXPECT_EQ(role, acc_role.lVal);\n\n ::VariantClear(&acc_role);\n ::SysFreeString(acc_name);\n }\n};\n\n\/\/ Retrieve accessibility object for main window and verify accessibility info.\n\/\/ Fails, http:\/\/crbug.com\/44486.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n FAILS_TestChromeWindowAccObj) {\n BrowserWindow* browser_window = browser()->window();\n ASSERT_TRUE(NULL != browser_window);\n\n HWND hwnd = browser_window->GetNativeHandle();\n ASSERT_TRUE(NULL != hwnd);\n\n \/\/ Get accessibility object.\n ScopedComPtr acc_obj;\n HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible,\n reinterpret_cast(&acc_obj));\n ASSERT_EQ(S_OK, hr);\n ASSERT_TRUE(NULL != acc_obj);\n\n ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));\n std::wstring title =\n l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT,\n ASCIIToWide(chrome::kAboutBlankURL));\n TestAccessibilityInfo(acc_obj, title, ROLE_SYSTEM_WINDOW);\n}\n\n\/\/ Retrieve accessibility object for non client view and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) {\n views::View* non_client_view =\n GetBrowserView()->GetWindow()->GetNonClientView();\n\n TestViewAccessibilityObject(non_client_view,\n l10n_util::GetString(IDS_PRODUCT_NAME),\n ROLE_SYSTEM_WINDOW);\n}\n\n\/\/ Retrieve accessibility object for browser root view and verify\n\/\/ accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n TestBrowserRootViewAccObj) {\n views::View* browser_root_view =\n GetBrowserView()->frame()->GetFrameView()->GetRootView();\n\n TestViewAccessibilityObject(browser_root_view,\n l10n_util::GetString(IDS_PRODUCT_NAME),\n ROLE_SYSTEM_APPLICATION);\n}\n\n\/\/ Retrieve accessibility object for browser view and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) {\n \/\/ Verify root view MSAA name and role.\n TestViewAccessibilityObject(GetBrowserView(),\n l10n_util::GetString(IDS_PRODUCT_NAME),\n ROLE_SYSTEM_CLIENT);\n}\n\n\/\/ Retrieve accessibility object for toolbar view and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) {\n \/\/ Verify toolbar MSAA name and role.\n TestViewAccessibilityObject(GetToolbarView(),\n l10n_util::GetString(IDS_ACCNAME_TOOLBAR),\n ROLE_SYSTEM_TOOLBAR);\n}\n\n\/\/ Retrieve accessibility object for Back button and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) {\n \/\/ Verify Back button MSAA name and role.\n TestViewAccessibilityObject(\n GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN);\n}\n\n\/\/ Retrieve accessibility object for Forward button and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) {\n \/\/ Verify Forward button MSAA name and role.\n TestViewAccessibilityObject(\n GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN);\n}\n\n\/\/ Retrieve accessibility object for Reload button and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) {\n \/\/ Verify Reload button MSAA name and role.\n TestViewAccessibilityObject(\n GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON);\n}\n\n\/\/ Retrieve accessibility object for Home button and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) {\n \/\/ Verify Home button MSAA name and role.\n TestViewAccessibilityObject(\n GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON);\n}\n\n\/\/ Retrieve accessibility object for Star button and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n TestStarButtonAccObj) {\n \/\/ Verify Star button MSAA name and role.\n TestViewAccessibilityObject(\n GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON);\n}\n\n\/\/ Retrieve accessibility object for location bar view and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n TestLocationBarViewAccObj) {\n \/\/ Verify location bar MSAA name and role.\n TestViewAccessibilityObject(GetLocationBarView(),\n l10n_util::GetString(IDS_ACCNAME_LOCATION),\n ROLE_SYSTEM_GROUPING);\n}\n\n\/\/ Retrieve accessibility object for Go button and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) {\n \/\/ Verify Go button MSAA name and role.\n TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_GO),\n ROLE_SYSTEM_PUSHBUTTON);\n}\n\n\/\/ Retrieve accessibility object for Page menu button and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) {\n \/\/ Verify Page menu button MSAA name and role.\n TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU),\n l10n_util::GetString(IDS_ACCNAME_PAGE),\n ROLE_SYSTEM_BUTTONMENU);\n}\n\n\/\/ Retrieve accessibility object for App menu button and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) {\n \/\/ Verify App menu button MSAA name and role.\n TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU),\n l10n_util::GetString(IDS_ACCNAME_APP),\n ROLE_SYSTEM_BUTTONMENU);\n}\n\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n TestBookmarkBarViewAccObj) {\n TestViewAccessibilityObject(GetBookmarkBarView(),\n l10n_util::GetString(IDS_ACCNAME_BOOKMARKS),\n ROLE_SYSTEM_TOOLBAR);\n}\n\n\/\/ Fails, http:\/\/crbug.com\/44486.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n FAILS_TestAboutChromeViewAccObj) {\n \/\/ Firstly, test that the WindowDelegate got updated.\n views::Window* aboutChromeWindow = GetBrowserView()->ShowAboutChromeDialog();\n EXPECT_STREQ(aboutChromeWindow->GetDelegate()->GetWindowTitle().c_str(),\n l10n_util::GetString(IDS_ABOUT_CHROME_TITLE).c_str());\n EXPECT_EQ(aboutChromeWindow->GetDelegate()->accessible_role(),\n AccessibilityTypes::ROLE_DIALOG);\n\n \/\/ Also test the accessibility object directly.\n IAccessible* acc_obj = NULL;\n HRESULT hr =\n ::AccessibleObjectFromWindow(aboutChromeWindow->GetNativeWindow(),\n OBJID_CLIENT,\n IID_IAccessible,\n reinterpret_cast(&acc_obj));\n ASSERT_EQ(S_OK, hr);\n ASSERT_TRUE(NULL != acc_obj);\n\n TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_ABOUT_CHROME_TITLE),\n ROLE_SYSTEM_DIALOG);\n\n acc_obj->Release();\n}\n} \/\/ Namespace.\n\nRe-enabling TestAboutChromeViewAccObj.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n\n#include \"app\/l10n_util.h\"\n#include \"base\/scoped_comptr_win.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/view_ids.h\"\n#include \"chrome\/browser\/views\/bookmark_bar_view.h\"\n#include \"chrome\/browser\/views\/frame\/browser_view.h\"\n#include \"chrome\/browser\/views\/toolbar_view.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"views\/accessibility\/view_accessibility_wrapper.h\"\n#include \"views\/widget\/root_view.h\"\n#include \"views\/widget\/widget_win.h\"\n#include \"views\/window\/window.h\"\n\nnamespace {\n\nVARIANT id_self = {VT_I4, CHILDID_SELF};\n\n\/\/ Dummy class to force creation of ATL module, needed by COM to instantiate\n\/\/ ViewAccessibility.\nclass TestAtlModule : public CAtlDllModuleT< TestAtlModule > {};\nTestAtlModule test_atl_module_;\n\nclass BrowserViewsAccessibilityTest : public InProcessBrowserTest {\n public:\n BrowserViewsAccessibilityTest() {\n ::CoInitialize(NULL);\n }\n\n ~BrowserViewsAccessibilityTest() {\n ::CoUninitialize();\n }\n\n \/\/ Retrieves an instance of BrowserWindowTesting\n BrowserWindowTesting* GetBrowserWindowTesting() {\n BrowserWindow* browser_window = browser()->window();\n\n if (!browser_window)\n return NULL;\n\n return browser_window->GetBrowserWindowTesting();\n }\n\n \/\/ Retrieve an instance of BrowserView\n BrowserView* GetBrowserView() {\n return BrowserView::GetBrowserViewForNativeWindow(\n browser()->window()->GetNativeHandle());\n }\n\n \/\/ Retrieves and initializes an instance of LocationBarView.\n LocationBarView* GetLocationBarView() {\n BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();\n\n if (!browser_window_testing)\n return NULL;\n\n return GetBrowserWindowTesting()->GetLocationBarView();\n }\n\n \/\/ Retrieves and initializes an instance of ToolbarView.\n ToolbarView* GetToolbarView() {\n BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();\n\n if (!browser_window_testing)\n return NULL;\n\n return browser_window_testing->GetToolbarView();\n }\n\n \/\/ Retrieves and initializes an instance of BookmarkBarView.\n BookmarkBarView* GetBookmarkBarView() {\n BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();\n\n if (!browser_window_testing)\n return NULL;\n\n return browser_window_testing->GetBookmarkBarView();\n }\n\n \/\/ Retrieves and verifies the accessibility object for the given View.\n void TestViewAccessibilityObject(views::View* view, std::wstring name,\n int32 role) {\n ASSERT_TRUE(NULL != view);\n\n IAccessible* acc_obj = NULL;\n HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance(\n IID_IAccessible, reinterpret_cast(&acc_obj));\n ASSERT_EQ(S_OK, hr);\n ASSERT_TRUE(NULL != acc_obj);\n\n TestAccessibilityInfo(acc_obj, name, role);\n }\n\n\n \/\/ Verifies MSAA Name and Role properties of the given IAccessible.\n void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name,\n int32 role) {\n \/\/ Verify MSAA Name property.\n BSTR acc_name;\n\n HRESULT hr = acc_obj->get_accName(id_self, &acc_name);\n ASSERT_EQ(S_OK, hr);\n EXPECT_STREQ(acc_name, name.c_str());\n\n \/\/ Verify MSAA Role property.\n VARIANT acc_role;\n ::VariantInit(&acc_role);\n\n hr = acc_obj->get_accRole(id_self, &acc_role);\n ASSERT_EQ(S_OK, hr);\n EXPECT_EQ(VT_I4, acc_role.vt);\n EXPECT_EQ(role, acc_role.lVal);\n\n ::VariantClear(&acc_role);\n ::SysFreeString(acc_name);\n }\n};\n\n\/\/ Retrieve accessibility object for main window and verify accessibility info.\n\/\/ Fails, http:\/\/crbug.com\/44486.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n FAILS_TestChromeWindowAccObj) {\n BrowserWindow* browser_window = browser()->window();\n ASSERT_TRUE(NULL != browser_window);\n\n HWND hwnd = browser_window->GetNativeHandle();\n ASSERT_TRUE(NULL != hwnd);\n\n \/\/ Get accessibility object.\n ScopedComPtr acc_obj;\n HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible,\n reinterpret_cast(&acc_obj));\n ASSERT_EQ(S_OK, hr);\n ASSERT_TRUE(NULL != acc_obj);\n\n ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));\n std::wstring title =\n l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT,\n ASCIIToWide(chrome::kAboutBlankURL));\n TestAccessibilityInfo(acc_obj, title, ROLE_SYSTEM_WINDOW);\n}\n\n\/\/ Retrieve accessibility object for non client view and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) {\n views::View* non_client_view =\n GetBrowserView()->GetWindow()->GetNonClientView();\n\n TestViewAccessibilityObject(non_client_view,\n l10n_util::GetString(IDS_PRODUCT_NAME),\n ROLE_SYSTEM_WINDOW);\n}\n\n\/\/ Retrieve accessibility object for browser root view and verify\n\/\/ accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n TestBrowserRootViewAccObj) {\n views::View* browser_root_view =\n GetBrowserView()->frame()->GetFrameView()->GetRootView();\n\n TestViewAccessibilityObject(browser_root_view,\n l10n_util::GetString(IDS_PRODUCT_NAME),\n ROLE_SYSTEM_APPLICATION);\n}\n\n\/\/ Retrieve accessibility object for browser view and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) {\n \/\/ Verify root view MSAA name and role.\n TestViewAccessibilityObject(GetBrowserView(),\n l10n_util::GetString(IDS_PRODUCT_NAME),\n ROLE_SYSTEM_CLIENT);\n}\n\n\/\/ Retrieve accessibility object for toolbar view and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) {\n \/\/ Verify toolbar MSAA name and role.\n TestViewAccessibilityObject(GetToolbarView(),\n l10n_util::GetString(IDS_ACCNAME_TOOLBAR),\n ROLE_SYSTEM_TOOLBAR);\n}\n\n\/\/ Retrieve accessibility object for Back button and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) {\n \/\/ Verify Back button MSAA name and role.\n TestViewAccessibilityObject(\n GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN);\n}\n\n\/\/ Retrieve accessibility object for Forward button and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) {\n \/\/ Verify Forward button MSAA name and role.\n TestViewAccessibilityObject(\n GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN);\n}\n\n\/\/ Retrieve accessibility object for Reload button and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) {\n \/\/ Verify Reload button MSAA name and role.\n TestViewAccessibilityObject(\n GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON);\n}\n\n\/\/ Retrieve accessibility object for Home button and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) {\n \/\/ Verify Home button MSAA name and role.\n TestViewAccessibilityObject(\n GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON);\n}\n\n\/\/ Retrieve accessibility object for Star button and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n TestStarButtonAccObj) {\n \/\/ Verify Star button MSAA name and role.\n TestViewAccessibilityObject(\n GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON);\n}\n\n\/\/ Retrieve accessibility object for location bar view and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n TestLocationBarViewAccObj) {\n \/\/ Verify location bar MSAA name and role.\n TestViewAccessibilityObject(GetLocationBarView(),\n l10n_util::GetString(IDS_ACCNAME_LOCATION),\n ROLE_SYSTEM_GROUPING);\n}\n\n\/\/ Retrieve accessibility object for Go button and verify accessibility info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) {\n \/\/ Verify Go button MSAA name and role.\n TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON),\n l10n_util::GetString(IDS_ACCNAME_GO),\n ROLE_SYSTEM_PUSHBUTTON);\n}\n\n\/\/ Retrieve accessibility object for Page menu button and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) {\n \/\/ Verify Page menu button MSAA name and role.\n TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU),\n l10n_util::GetString(IDS_ACCNAME_PAGE),\n ROLE_SYSTEM_BUTTONMENU);\n}\n\n\/\/ Retrieve accessibility object for App menu button and verify accessibility\n\/\/ info.\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) {\n \/\/ Verify App menu button MSAA name and role.\n TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU),\n l10n_util::GetString(IDS_ACCNAME_APP),\n ROLE_SYSTEM_BUTTONMENU);\n}\n\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n TestBookmarkBarViewAccObj) {\n TestViewAccessibilityObject(GetBookmarkBarView(),\n l10n_util::GetString(IDS_ACCNAME_BOOKMARKS),\n ROLE_SYSTEM_TOOLBAR);\n}\n\nIN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,\n TestAboutChromeViewAccObj) {\n \/\/ Firstly, test that the WindowDelegate got updated.\n views::Window* aboutChromeWindow = GetBrowserView()->ShowAboutChromeDialog();\n EXPECT_STREQ(aboutChromeWindow->GetDelegate()->GetWindowTitle().c_str(),\n l10n_util::GetString(IDS_ABOUT_CHROME_TITLE).c_str());\n EXPECT_EQ(aboutChromeWindow->GetDelegate()->accessible_role(),\n AccessibilityTypes::ROLE_DIALOG);\n\n \/\/ Also test the accessibility object directly.\n IAccessible* acc_obj = NULL;\n HRESULT hr =\n ::AccessibleObjectFromWindow(aboutChromeWindow->GetNativeWindow(),\n OBJID_CLIENT,\n IID_IAccessible,\n reinterpret_cast(&acc_obj));\n ASSERT_EQ(S_OK, hr);\n ASSERT_TRUE(NULL != acc_obj);\n\n TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_ABOUT_CHROME_TITLE),\n ROLE_SYSTEM_DIALOG);\n\n acc_obj->Release();\n}\n} \/\/ Namespace.\n\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n#include \n\n#ifdef BTS_TEST_NETWORK\n#define NETWORK_MIN_CONNECTION_COUNT_DEFAULT 0\n#else\n#define NETWORK_MIN_CONNECTION_COUNT_DEFAULT 4\n#endif\n\n#define BTS_BLOCKCHAIN_AVERAGE_TRX_SIZE 512 \/\/ just a random assumption used to calibrate TRX per SEC\n\/** defines the maximum block size allowed, 2 MB per hour *\/\n#define BTS_BLOCKCHAIN_MAX_BLOCK_SIZE (10 * BTS_BLOCKCHAIN_AVERAGE_TRX_SIZE * BTS_BLOCKCHAIN_MAX_PENDING_QUEUE_SIZE )\n\nnamespace bts { namespace blockchain {\n\nstruct delegate_config\n{\n uint32_t network_min_connection_count = NETWORK_MIN_CONNECTION_COUNT_DEFAULT;\n\n uint32_t block_max_transaction_count = -1;\n uint32_t block_max_size = BTS_BLOCKCHAIN_MAX_BLOCK_SIZE;\n fc::microseconds block_max_production_time = fc::seconds( 3 );\n\n uint32_t transaction_max_size = BTS_BLOCKCHAIN_MAX_BLOCK_SIZE;\n bool transaction_canonical_signatures_required = false;\n share_type transaction_min_fee = BTS_BLOCKCHAIN_PRECISION \/ 10;\n\n set transaction_blacklist;\n set operation_blacklist;\n\n void validate()const\n { try {\n FC_ASSERT( block_max_size <= BTS_BLOCKCHAIN_MAX_BLOCK_SIZE );\n FC_ASSERT( block_max_production_time.count() >= 0 );\n FC_ASSERT( block_max_production_time.to_seconds() <= BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC );\n FC_ASSERT( transaction_max_size <= block_max_size );\n FC_ASSERT( transaction_min_fee >= 0 );\n FC_ASSERT( transaction_min_fee <= BTS_BLOCKCHAIN_MAX_SHARES );\n } FC_CAPTURE_AND_RETHROW() }\n};\n\n} } \/\/ bts::blockchain\n\nFC_REFLECT( bts::blockchain::delegate_config,\n (network_min_connection_count)\n (block_max_transaction_count)\n (block_max_size)\n (block_max_production_time)\n (transaction_max_size)\n (transaction_canonical_signatures_required)\n (transaction_min_fee)\n (transaction_blacklist)\n (operation_blacklist)\n )\nupdate min net count for dev to 1#pragma once\n\n#include \n#include \n#include \n\n#ifdef BTS_TEST_NETWORK\n#define NETWORK_MIN_CONNECTION_COUNT_DEFAULT 0\n#else\n#define NETWORK_MIN_CONNECTION_COUNT_DEFAULT 1\n#endif\n\n#define BTS_BLOCKCHAIN_AVERAGE_TRX_SIZE 512 \/\/ just a random assumption used to calibrate TRX per SEC\n\/** defines the maximum block size allowed, 2 MB per hour *\/\n#define BTS_BLOCKCHAIN_MAX_BLOCK_SIZE (10 * BTS_BLOCKCHAIN_AVERAGE_TRX_SIZE * BTS_BLOCKCHAIN_MAX_PENDING_QUEUE_SIZE )\n\nnamespace bts { namespace blockchain {\n\nstruct delegate_config\n{\n uint32_t network_min_connection_count = NETWORK_MIN_CONNECTION_COUNT_DEFAULT;\n\n uint32_t block_max_transaction_count = -1;\n uint32_t block_max_size = BTS_BLOCKCHAIN_MAX_BLOCK_SIZE;\n fc::microseconds block_max_production_time = fc::seconds( 3 );\n\n uint32_t transaction_max_size = BTS_BLOCKCHAIN_MAX_BLOCK_SIZE;\n bool transaction_canonical_signatures_required = false;\n share_type transaction_min_fee = BTS_BLOCKCHAIN_PRECISION \/ 10;\n\n set transaction_blacklist;\n set operation_blacklist;\n\n void validate()const\n { try {\n FC_ASSERT( block_max_size <= BTS_BLOCKCHAIN_MAX_BLOCK_SIZE );\n FC_ASSERT( block_max_production_time.count() >= 0 );\n FC_ASSERT( block_max_production_time.to_seconds() <= BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC );\n FC_ASSERT( transaction_max_size <= block_max_size );\n FC_ASSERT( transaction_min_fee >= 0 );\n FC_ASSERT( transaction_min_fee <= BTS_BLOCKCHAIN_MAX_SHARES );\n } FC_CAPTURE_AND_RETHROW() }\n};\n\n} } \/\/ bts::blockchain\n\nFC_REFLECT( bts::blockchain::delegate_config,\n (network_min_connection_count)\n (block_max_transaction_count)\n (block_max_size)\n (block_max_production_time)\n (transaction_max_size)\n (transaction_canonical_signatures_required)\n (transaction_min_fee)\n (transaction_blacklist)\n (operation_blacklist)\n )\n<|endoftext|>"} {"text":"\/\/ (c) Mathias Panzenböck\n\/\/ http:\/\/github.com\/panzi\/mathfun\/blob\/master\/examples\/portable_endian.h\n\/\/\n\n#pragma once\n\n#if (defined(_WIN16) || defined(_WIN32) || defined(_WIN64)) && !defined(__WINDOWS__)\n\n# define __WINDOWS__\n\n#endif\n\n\/\/ use standard posix style headers for apple emscripten builds as well since emscripten sdk now ships its own\n\/\/ libc headers\n#if defined(__linux__) || defined(__CYGWIN__) || defined(__EMSCRIPTEN__)\n\n# include \n\n#elif defined(__APPLE__)\n\n# include \n# include \n\n# define htobe16 OSSwapHostToBigInt16\n# define htole16 OSSwapHostToLittleInt16\n# define be16toh OSSwapBigToHostInt16\n# define le16toh OSSwapLittleToHostInt16\n\n# define htobe32 OSSwapHostToBigInt32\n# define htole32 OSSwapHostToLittleInt32\n# define be32toh OSSwapBigToHostInt32\n# define le32toh OSSwapLittleToHostInt32\n\n# define htobe64 OSSwapHostToBigInt64\n# define htole64 OSSwapHostToLittleInt64\n# define be64toh OSSwapBigToHostInt64\n# define le64toh OSSwapLittleToHostInt64\n\n\/**\n# define __BYTE_ORDER BYTE_ORDER\n# define __BIG_ENDIAN BIG_ENDIAN\n# define __LITTLE_ENDIAN LITTLE_ENDIAN\n# define __PDP_ENDIAN PDP_ENDIAN\n**\/\n\n#elif defined(__OpenBSD__)|| defined(__FreeBSD__) \n\n# include \n\n#elif defined(__NetBSD__) || defined(__DragonFly__)\n\n# define be16toh betoh16\n# define le16toh letoh16\n\n# define be32toh betoh32\n# define le32toh letoh32\n\n# define be64toh betoh64\n# define le64toh letoh64\n\n#elif defined(__WINDOWS__)\n\n# include \n\n# if BYTE_ORDER == LITTLE_ENDIAN\n\n# define htobe16 htons\n# define htole16(x) (x)\n# define be16toh ntohs\n# define le16toh(x) (x)\n\n# define htobe32 htonl\n# define htole32(x) (x)\n# define be32toh ntohl\n# define le32toh(x) (x)\n \n# define htole64(x) (x)\n# define le64toh(x) (x)\n# ifndef __MINGW32__\n# define be64toh ntohll\n# define htobe64 htonll\n# else\n# define be64toh(x) ((((uint64_t)ntohl((x) & 0xFFFFFFFFUL)) << 32) | ntohl((uint32_t)((x) >> 32)))\n# define htobe64(x) ((((uint64_t)htonl((x) & 0xFFFFFFFFUL)) << 32) | htonl((uint32_t)((x) >> 32)))\n# endif\n \n# elif BYTE_ORDER == BIG_ENDIAN\n\n \/* that would be xbox 360 *\/\n# define htobe16(x) (x)\n# define htole16(x) __builtin_bswap16(x)\n# define be16toh(x) (x)\n# define le16toh(x) __builtin_bswap16(x)\n\n# define htobe32(x) (x)\n# define htole32(x) __builtin_bswap32(x)\n# define be32toh(x) (x)\n# define le32toh(x) __builtin_bswap32(x)\n\n# define htobe64(x) (x)\n# define htole64(x) __builtin_bswap64(x)\n# define be64toh(x) (x)\n# define le64toh(x) __builtin_bswap64(x)\n\n# else\n\n# error byte order not supported\n\n# endif\n\n# define __BYTE_ORDER BYTE_ORDER\n# define __BIG_ENDIAN BIG_ENDIAN\n# define __LITTLE_ENDIAN LITTLE_ENDIAN\n# define __PDP_ENDIAN PDP_ENDIAN\n\n#else\n\n# error platform not supported\n\n#endif\nMore flexible endian.h handling for *BSD platforms (#119)\/\/ (c) Mathias Panzenböck\n\/\/ http:\/\/github.com\/panzi\/mathfun\/blob\/master\/examples\/portable_endian.h\n\/\/\n\n#pragma once\n\n#if (defined(_WIN16) || defined(_WIN32) || defined(_WIN64)) && !defined(__WINDOWS__)\n\n# define __WINDOWS__\n\n#endif\n\n\/\/ use standard posix style headers for apple emscripten builds as well since emscripten sdk now ships its own\n\/\/ libc headers\n#if defined(__linux__) || defined(__CYGWIN__) || defined(__EMSCRIPTEN__)\n\n# include \n\n#elif defined(__APPLE__)\n\n# include \n# include \n\n# define htobe16 OSSwapHostToBigInt16\n# define htole16 OSSwapHostToLittleInt16\n# define be16toh OSSwapBigToHostInt16\n# define le16toh OSSwapLittleToHostInt16\n\n# define htobe32 OSSwapHostToBigInt32\n# define htole32 OSSwapHostToLittleInt32\n# define be32toh OSSwapBigToHostInt32\n# define le32toh OSSwapLittleToHostInt32\n\n# define htobe64 OSSwapHostToBigInt64\n# define htole64 OSSwapHostToLittleInt64\n# define be64toh OSSwapBigToHostInt64\n# define le64toh OSSwapLittleToHostInt64\n\n\/**\n# define __BYTE_ORDER BYTE_ORDER\n# define __BIG_ENDIAN BIG_ENDIAN\n# define __LITTLE_ENDIAN LITTLE_ENDIAN\n# define __PDP_ENDIAN PDP_ENDIAN\n**\/\n\n#elif defined(__OpenBSD__)|| defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)\n\n# if defined __has_include && __has_include ()\n# include \n# elif defined __has_include && __has_include ()\n# include \n# else\n# define be16toh betoh16\n# define le16toh letoh16\n# define be32toh betoh32\n# define le32toh letoh32\n# define be64toh betoh64\n# define le64toh letoh64\n# endif\n\n#elif defined(__WINDOWS__)\n\n# include \n\n# if BYTE_ORDER == LITTLE_ENDIAN\n# define htobe16 htons\n# define htole16(x) (x)\n# define be16toh ntohs\n# define le16toh(x) (x)\n\n# define htobe32 htonl\n# define htole32(x) (x)\n# define be32toh ntohl\n# define le32toh(x) (x)\n \n# define htole64(x) (x)\n# define le64toh(x) (x)\n# ifndef __MINGW32__\n# define be64toh ntohll\n# define htobe64 htonll\n# else\n# define be64toh(x) ((((uint64_t)ntohl((x) & 0xFFFFFFFFUL)) << 32) | ntohl((uint32_t)((x) >> 32)))\n# define htobe64(x) ((((uint64_t)htonl((x) & 0xFFFFFFFFUL)) << 32) | htonl((uint32_t)((x) >> 32)))\n# endif\n \n# elif BYTE_ORDER == BIG_ENDIAN\n\n \/* that would be xbox 360 *\/\n# define htobe16(x) (x)\n# define htole16(x) __builtin_bswap16(x)\n# define be16toh(x) (x)\n# define le16toh(x) __builtin_bswap16(x)\n\n# define htobe32(x) (x)\n# define htole32(x) __builtin_bswap32(x)\n# define be32toh(x) (x)\n# define le32toh(x) __builtin_bswap32(x)\n\n# define htobe64(x) (x)\n# define htole64(x) __builtin_bswap64(x)\n# define be64toh(x) (x)\n# define le64toh(x) __builtin_bswap64(x)\n\n# else\n\n# error byte order not supported\n\n# endif\n\n# define __BYTE_ORDER BYTE_ORDER\n# define __BIG_ENDIAN BIG_ENDIAN\n# define __LITTLE_ENDIAN LITTLE_ENDIAN\n# define __PDP_ENDIAN PDP_ENDIAN\n\n#else\n\n# error platform not supported\n\n#endif\n<|endoftext|>"} {"text":"\/\/ dllmain.cpp : Defines the entry point for the DLL application.\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"stdafx.h\"\r\n#include \"supp\/timer.h\"\r\n#include \"core\/armor_up.h\"\r\n#include \"utils\/query.h\"\r\n\r\nusing namespace monster_avengers;\r\nstd::unique_ptr a;\r\nstd::string result;\r\nTimer timer;\r\n\r\nextern \"C\"\r\n{\r\n\t__declspec(dllexport) const char *DisplayHelloFromDLL()\r\n\t{\r\n\t\tresult = std::to_string(timer.Toc());\r\n\t\treturn result.c_str();\r\n\t}\r\n\t__declspec(dllexport) void DoSearch(const wchar_t* text) {\r\n\t\tstd::wstring query_text = text;\r\n\t\tsetlocale(LC_ALL, \"en_US.UTF-8\");\r\n\t\tQuery query;\r\n\t\twprintf(L\"sizeof(wchar_t): %d\\n\", sizeof(wchar_t));\r\n\t\twprintf(L\"Get %lc\\n\", a);\r\n\t\t\r\n\t\t\/\/ ArmorUp armor_up(\"d:\/pf\/projects\/monster-avengers\/dataset\/MH4GU\");\r\n\t\t\/\/ armor_up.Search(\"(:weaopn-type \");\r\n\t}\r\n}\r\n\r\nBOOL APIENTRY DllMain( HMODULE hModule,\r\n DWORD ul_reason_for_call,\r\n LPVOID lpReserved\r\n\t\t\t\t\t )\r\n{\r\n\tswitch (ul_reason_for_call)\r\n\t{\r\n\tcase DLL_PROCESS_ATTACH:\r\n\t\ttimer.Tic();\r\n\t\ta.reset(new int(24));\r\n\t\tbreak;\r\n\tcase DLL_THREAD_ATTACH:\r\n\tcase DLL_THREAD_DETACH:\r\n\tcase DLL_PROCESS_DETACH:\r\n\t\ta.release();\r\n\t\tbreak;\r\n\t}\r\n\treturn TRUE;\r\n}\r\n\r\nworking version, preliminary.\/\/ dllmain.cpp : Defines the entry point for the DLL application.\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"stdafx.h\"\r\n#include \"supp\/timer.h\"\r\n#include \"core\/armor_up.h\"\r\n#include \"utils\/query.h\"\r\n\r\nusing namespace monster_avengers;\r\nstd::unique_ptr a;\r\nstd::string result;\r\nTimer timer;\r\n\r\nextern \"C\"\r\n{\r\n\t__declspec(dllexport) const char *DisplayHelloFromDLL()\r\n\t{\r\n\t\tresult = std::to_string(timer.Toc());\r\n\t\treturn result.c_str();\r\n\t}\r\n\t__declspec(dllexport) void DoSearch(const wchar_t* text) {\r\n\t\tstd::wstring query_text = text;\r\n\t\t\r\n\t\tQuery query;\r\n\t\tCHECK_SUCCESS(Query::Parse(query_text, &query));\r\n\t\tquery.DebugPrint();\r\n\t\t\r\n\t\tArmorUp armor_up(\"d:\/pf\/projects\/monster-avengers\/dataset\/MH4GU\");\r\n\t\tarmor_up.Summarize();\r\n\t\tarmor_up.Search(query);\r\n\t}\r\n}\r\n\r\nBOOL APIENTRY DllMain( HMODULE hModule,\r\n DWORD ul_reason_for_call,\r\n LPVOID lpReserved\r\n\t\t\t\t\t )\r\n{\r\n\tswitch (ul_reason_for_call)\r\n\t{\r\n\tcase DLL_PROCESS_ATTACH:\r\n\t\tsetlocale(LC_ALL, \"en_US.UTF-8\");\r\n\t\ttimer.Tic();\r\n\t\ta.reset(new int(24));\r\n\t\tbreak;\r\n\tcase DLL_THREAD_ATTACH:\r\n\tcase DLL_THREAD_DETACH:\r\n\tcase DLL_PROCESS_DETACH:\r\n\t\ta.release();\r\n\t\tbreak;\r\n\t}\r\n\treturn TRUE;\r\n}\r\n\r\n<|endoftext|>"} {"text":"\/\/\/ \\file TFormulaGradientTests.cxx\n\/\/\/\n\/\/\/ \\brief The file contain unit tests which test the clad-based gradient\n\/\/\/ computations.\n\/\/\/\n\/\/\/ \\author Vassil Vassilev \n\/\/\/\n\/\/\/ \\date Oct, 2018\n\/\/\/\n\/*************************************************************************\n * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"ROOTUnitTestSupport.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"gtest\/gtest.h\"\n#include \"gmock\/gmock.h\"\n\nTEST(TFormulaGradientPar, Sanity)\n{\n TFormula f(\"f\", \"x*std::sin([0]) - y*std::cos([1])\");\n double p[] = {30, 60};\n f.SetParameters(p);\n double x[] = {1, 2};\n TFormula::CladStorage result(2);\n f.GradientPar(x, result);\n\n ASSERT_FLOAT_EQ(x[0] * std::cos(30), result[0]);\n ASSERT_FLOAT_EQ(-x[1] * -std::sin(60), result[1]);\n}\n\nTEST(TFormulaGradientPar, ResultUpsize)\n{\n TFormula f(\"f\", \"std::sin([1]) - std::cos([0])\");\n double p[] = {60, 30};\n f.SetParameters(p);\n TFormula::CladStorage result;\n double x[] = {2, 1};\n\n ASSERT_TRUE(0 == result.size());\n ROOT_EXPECT_WARNING(f.GradientPar(x, result),\n \"TFormula::GradientPar\",\n \"The size of gradient result is 0 but 2 is required. Resizing.\"\n );\n\n ASSERT_FLOAT_EQ(std::cos(30), result[1]);\n ASSERT_FLOAT_EQ(std::sin(60), result[0]);\n ASSERT_TRUE(2 == result.size());\n}\n\nTEST(TFormulaGradientPar, ResultDownsize)\n{\n TFormula f(\"f\", \"std::sin([0])\");\n double p[] = {60};\n f.SetParameters(p);\n TFormula::CladStorage result(2);\n double x[] = {1};\n\n ASSERT_TRUE(2 == result.size());\n\n ROOT_EXPECT_NODIAG(f.GradientPar(x, result));\n\n ASSERT_FLOAT_EQ(std::cos(60), result[0]);\n ASSERT_TRUE(2 == result.size());\n}\n\nTEST(TFormulaGradientPar, GausCrossCheck)\n{\n auto h = new TF1(\"f1\", \"gaus\");\n \/\/ auto h = new TF1(\"f1\", \"landau\"); -- inheritently does not work. See DIFLAN\n \/\/crystalball, breitwigner, cheb3, bigaus,\n \/\/auto h = new TF1(\"f1\", \"\");\n double p[] = {3, 1, 2};\n h->SetParameters(p);\n double x[] = {0};\n TFormula::CladStorage result_clad(3);\n h->GetFormula()->GradientPar(x, result_clad);\n\n TFormula::CladStorage result_num(3);\n h->GradientPar(x, result_num.data());\n\n ASSERT_FLOAT_EQ(result_num[0], result_clad[0]);\n ASSERT_FLOAT_EQ(result_num[1], result_clad[1]);\n ASSERT_FLOAT_EQ(result_num[2], result_clad[2]);\n}\n\nTEST(TFormulaGradientPar, BreitWignerCrossCheck)\n{\n auto h = new TF1(\"f1\", \"breitwigner\");\n double p[] = {3, 1, 2.1};\n h->SetParameters(p);\n double x[] = {0};\n TFormula::CladStorage result_clad(3);\n TFormula* formula = h->GetFormula();\n formula->GradientPar(x, result_clad);\n TFormula::CladStorage result_num(3);\n h->GradientPar(x, result_num.data());\n\n ASSERT_FLOAT_EQ(result_num[0], result_clad[0]);\n ASSERT_FLOAT_EQ(result_num[1], result_clad[1]);\n ASSERT_FLOAT_EQ(result_num[2], result_clad[2]);\n}\n\nTEST(TFormulaGradientPar, BreitWignerCrossCheckAccuracyDemo)\n{\n auto h = new TF1(\"f1\", \"breitwigner\");\n double p[] = {3, 1, 2};\n h->SetParameters(p);\n double x[] = {0};\n TFormula::CladStorage result_clad(3);\n TFormula* formula = h->GetFormula();\n formula->GradientPar(x, result_clad);\n TFormula::CladStorage result_num(3);\n h->GradientPar(x, result_num.data());\n\n \/\/ This is a classical example why clad is better.\n \/\/ The gradient with respect to gamma leads to a cancellation when gamma is\n \/\/ set to 2. This is not a problem for clad yielding the correct result of 0\n ASSERT_FLOAT_EQ(0, result_clad[2]);\n\n \/\/ However, that is not the case for the numerical approach where we give\n \/\/ a small but non-zero result.\n EXPECT_NEAR(0, result_num[2], \/*abs_error*\/1e-13);\n}\n\n\/\/ FIXME: Add more: crystalball, cheb3, bigaus?\n\nTEST(TFormulaGradientPar, GetGradFormula)\n{\n TFormula f(\"f\", \"gaus\");\n double p[] = {3, 1, 2};\n f.SetParameters(p);\n ASSERT_TRUE(f.GenerateGradientPar());\n std::string s = f.GetGradientFormula().Data();\n \/\/ Windows does not support posix regex which are necessary here.\n#ifndef R__WIN32\n ASSERT_THAT(s, testing::ContainsRegex(\"void TFormula____id[0-9]*_grad_1\"));\n#endif \/\/ R__WIN32\n}\n\n[clad] Extend test coverage with bigaus function.\/\/\/ \\file TFormulaGradientTests.cxx\n\/\/\/\n\/\/\/ \\brief The file contain unit tests which test the clad-based gradient\n\/\/\/ computations.\n\/\/\/\n\/\/\/ \\author Vassil Vassilev \n\/\/\/\n\/\/\/ \\date Oct, 2018\n\/\/\/\n\/*************************************************************************\n * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"ROOTUnitTestSupport.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"gtest\/gtest.h\"\n#include \"gmock\/gmock.h\"\n\nTEST(TFormulaGradientPar, Sanity)\n{\n TFormula f(\"f\", \"x*std::sin([0]) - y*std::cos([1])\");\n double p[] = {30, 60};\n f.SetParameters(p);\n double x[] = {1, 2};\n TFormula::CladStorage result(2);\n f.GradientPar(x, result);\n\n ASSERT_FLOAT_EQ(x[0] * std::cos(30), result[0]);\n ASSERT_FLOAT_EQ(-x[1] * -std::sin(60), result[1]);\n}\n\nTEST(TFormulaGradientPar, ResultUpsize)\n{\n TFormula f(\"f\", \"std::sin([1]) - std::cos([0])\");\n double p[] = {60, 30};\n f.SetParameters(p);\n TFormula::CladStorage result;\n double x[] = {2, 1};\n\n ASSERT_TRUE(0 == result.size());\n ROOT_EXPECT_WARNING(f.GradientPar(x, result),\n \"TFormula::GradientPar\",\n \"The size of gradient result is 0 but 2 is required. Resizing.\"\n );\n\n ASSERT_FLOAT_EQ(std::cos(30), result[1]);\n ASSERT_FLOAT_EQ(std::sin(60), result[0]);\n ASSERT_TRUE(2 == result.size());\n}\n\nTEST(TFormulaGradientPar, ResultDownsize)\n{\n TFormula f(\"f\", \"std::sin([0])\");\n double p[] = {60};\n f.SetParameters(p);\n TFormula::CladStorage result(2);\n double x[] = {1};\n\n ASSERT_TRUE(2 == result.size());\n\n ROOT_EXPECT_NODIAG(f.GradientPar(x, result));\n\n ASSERT_FLOAT_EQ(std::cos(60), result[0]);\n ASSERT_TRUE(2 == result.size());\n}\n\nTEST(TFormulaGradientPar, GausCrossCheck)\n{\n auto h = new TF1(\"f1\", \"gaus\");\n \/\/ auto h = new TF1(\"f1\", \"landau\"); -- inheritently does not work. See DIFLAN\n \/\/crystalball, breitwigner, cheb3, bigaus,\n \/\/auto h = new TF1(\"f1\", \"\");\n double p[] = {3, 1, 2};\n h->SetParameters(p);\n double x[] = {0};\n TFormula::CladStorage result_clad(3);\n h->GetFormula()->GradientPar(x, result_clad);\n\n TFormula::CladStorage result_num(3);\n h->GradientPar(x, result_num.data());\n\n ASSERT_FLOAT_EQ(result_num[0], result_clad[0]);\n ASSERT_FLOAT_EQ(result_num[1], result_clad[1]);\n ASSERT_FLOAT_EQ(result_num[2], result_clad[2]);\n}\n\nTEST(TFormulaGradientPar, BreitWignerCrossCheck)\n{\n auto h = new TF1(\"f1\", \"breitwigner\");\n double p[] = {3, 1, 2.1};\n h->SetParameters(p);\n double x[] = {0};\n TFormula::CladStorage result_clad(3);\n TFormula* formula = h->GetFormula();\n formula->GradientPar(x, result_clad);\n TFormula::CladStorage result_num(3);\n h->GradientPar(x, result_num.data());\n\n ASSERT_FLOAT_EQ(result_num[0], result_clad[0]);\n ASSERT_FLOAT_EQ(result_num[1], result_clad[1]);\n ASSERT_FLOAT_EQ(result_num[2], result_clad[2]);\n}\n\nTEST(TFormulaGradientPar, BreitWignerCrossCheckAccuracyDemo)\n{\n auto h = new TF1(\"f1\", \"breitwigner\");\n double p[] = {3, 1, 2};\n h->SetParameters(p);\n double x[] = {0};\n TFormula::CladStorage result_clad(3);\n TFormula* formula = h->GetFormula();\n formula->GradientPar(x, result_clad);\n TFormula::CladStorage result_num(3);\n h->GradientPar(x, result_num.data());\n\n \/\/ This is a classical example why clad is better.\n \/\/ The gradient with respect to gamma leads to a cancellation when gamma is\n \/\/ set to 2. This is not a problem for clad yielding the correct result of 0\n ASSERT_FLOAT_EQ(0, result_clad[2]);\n\n \/\/ However, that is not the case for the numerical approach where we give\n \/\/ a small but non-zero result.\n EXPECT_NEAR(0, result_num[2], \/*abs_error*\/1e-13);\n}\n\nTEST(TFormulaGradientPar, BigausCrossCheck)\n{\n auto h = new TF2(\"f1\", \"bigaus\");\n const unsigned len = 6;\n double p[] = {\/*Constant=*\/1,\/*MeanX=*\/0,\/*SigmaX=*\/1,\/*MeanY=*\/1,\/*SigmaY=*\/2,\/*Rho=*\/0.};\n h->SetParameters(p);\n double x[] = {0};\n TFormula::CladStorage result_clad(len);\n TFormula* formula = h->GetFormula();\n formula->GradientPar(x, result_clad);\n TFormula::CladStorage result_num(len);\n h->GradientPar(x, result_num.data());\n\n for (unsigned i = 0; i < len; ++i)\n ASSERT_FLOAT_EQ(result_num[i], result_clad[i]);\n}\n\n\/\/ FIXME: Add more: crystalball, cheb3?\n\nTEST(TFormulaGradientPar, GetGradFormula)\n{\n TFormula f(\"f\", \"gaus\");\n double p[] = {3, 1, 2};\n f.SetParameters(p);\n ASSERT_TRUE(f.GenerateGradientPar());\n std::string s = f.GetGradientFormula().Data();\n \/\/ Windows does not support posix regex which are necessary here.\n#ifndef R__WIN32\n ASSERT_THAT(s, testing::ContainsRegex(\"void TFormula____id[0-9]*_grad_1\"));\n#endif \/\/ R__WIN32\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009-2018 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\nconst std::function G_TRANSLATION_FUN = nullptr;\n\nenum TEST_ID {\n CBLOCK_DESERIALIZE=0,\n CTRANSACTION_DESERIALIZE,\n CBLOCKLOCATOR_DESERIALIZE,\n CBLOCKMERKLEROOT,\n CADDRMAN_DESERIALIZE,\n CBLOCKHEADER_DESERIALIZE,\n CBANENTRY_DESERIALIZE,\n CTXUNDO_DESERIALIZE,\n CBLOCKUNDO_DESERIALIZE,\n CCOINS_DESERIALIZE,\n CNETADDR_DESERIALIZE,\n CSERVICE_DESERIALIZE,\n CMESSAGEHEADER_DESERIALIZE,\n CADDRESS_DESERIALIZE,\n CINV_DESERIALIZE,\n CBLOOMFILTER_DESERIALIZE,\n CDISKBLOCKINDEX_DESERIALIZE,\n CTXOUTCOMPRESSOR_DESERIALIZE,\n BLOCKTRANSACTIONS_DESERIALIZE,\n BLOCKTRANSACTIONSREQUEST_DESERIALIZE,\n TEST_ID_END\n};\n\nstatic bool read_stdin(std::vector &data) {\n uint8_t buffer[1024];\n ssize_t length=0;\n while((length = read(STDIN_FILENO, buffer, 1024)) > 0) {\n data.insert(data.end(), buffer, buffer+length);\n\n if (data.size() > (1<<20)) return false;\n }\n return length==0;\n}\n\nstatic int test_one_input(std::vector buffer) {\n if (buffer.size() < sizeof(uint32_t)) return 0;\n\n uint32_t test_id = 0xffffffff;\n memcpy(&test_id, buffer.data(), sizeof(uint32_t));\n buffer.erase(buffer.begin(), buffer.begin() + sizeof(uint32_t));\n\n if (test_id >= TEST_ID_END) return 0;\n\n CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION);\n try {\n int nVersion;\n ds >> nVersion;\n ds.SetVersion(nVersion);\n } catch (const std::ios_base::failure& e) {\n return 0;\n }\n\n switch(test_id) {\n case CBLOCK_DESERIALIZE:\n {\n try\n {\n CBlock block;\n ds >> block;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CTRANSACTION_DESERIALIZE:\n {\n try\n {\n CTransaction tx(deserialize, ds);\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CBLOCKLOCATOR_DESERIALIZE:\n {\n try\n {\n CBlockLocator bl;\n ds >> bl;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CBLOCKMERKLEROOT:\n {\n try\n {\n CBlock block;\n ds >> block;\n bool mutated;\n BlockMerkleRoot(block, &mutated);\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CADDRMAN_DESERIALIZE:\n {\n try\n {\n CAddrMan am;\n ds >> am;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CBLOCKHEADER_DESERIALIZE:\n {\n try\n {\n CBlockHeader bh;\n ds >> bh;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CBANENTRY_DESERIALIZE:\n {\n try\n {\n CBanEntry be;\n ds >> be;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CTXUNDO_DESERIALIZE:\n {\n try\n {\n CTxUndo tu;\n ds >> tu;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CBLOCKUNDO_DESERIALIZE:\n {\n try\n {\n CBlockUndo bu;\n ds >> bu;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CCOINS_DESERIALIZE:\n {\n try\n {\n Coin coin;\n ds >> coin;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CNETADDR_DESERIALIZE:\n {\n try\n {\n CNetAddr na;\n ds >> na;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CSERVICE_DESERIALIZE:\n {\n try\n {\n CService s;\n ds >> s;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CMESSAGEHEADER_DESERIALIZE:\n {\n CMessageHeader::MessageStartChars pchMessageStart = {0x00, 0x00, 0x00, 0x00};\n try\n {\n CMessageHeader mh(pchMessageStart);\n ds >> mh;\n if (!mh.IsValid(pchMessageStart)) {return 0;}\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CADDRESS_DESERIALIZE:\n {\n try\n {\n CAddress a;\n ds >> a;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CINV_DESERIALIZE:\n {\n try\n {\n CInv i;\n ds >> i;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CBLOOMFILTER_DESERIALIZE:\n {\n try\n {\n CBloomFilter bf;\n ds >> bf;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CDISKBLOCKINDEX_DESERIALIZE:\n {\n try\n {\n CDiskBlockIndex dbi;\n ds >> dbi;\n } catch (const std::ios_base::failure& e) {return 0;}\n break;\n }\n case CTXOUTCOMPRESSOR_DESERIALIZE:\n {\n CTxOut to;\n CTxOutCompressor toc(to);\n try\n {\n ds >> toc;\n } catch (const std::ios_base::failure& e) {return 0;}\n\n break;\n }\n case BLOCKTRANSACTIONS_DESERIALIZE:\n {\n try\n {\n BlockTransactions bt;\n ds >> bt;\n } catch (const std::ios_base::failure& e) {return 0;}\n\n break;\n }\n case BLOCKTRANSACTIONSREQUEST_DESERIALIZE:\n {\n try\n {\n BlockTransactionsRequest btr;\n ds >> btr;\n } catch (const std::ios_base::failure& e) {return 0;}\n\n break;\n }\n default:\n return 0;\n }\n return 0;\n}\n\nstatic std::unique_ptr globalVerifyHandle;\nvoid initialize() {\n globalVerifyHandle = MakeUnique();\n}\n\n\/\/ This function is used by libFuzzer\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {\n test_one_input(std::vector(data, data + size));\n return 0;\n}\n\n\/\/ This function is used by libFuzzer\nextern \"C\" int LLVMFuzzerInitialize(int *argc, char ***argv) {\n initialize();\n return 0;\n}\n\n\/\/ Disabled under WIN32 due to clash with Cygwin's WinMain.\n#ifndef WIN32\n\/\/ Declare main(...) \"weak\" to allow for libFuzzer linking. libFuzzer provides\n\/\/ the main(...) function.\n__attribute__((weak))\n#endif\nint main(int argc, char **argv)\n{\n initialize();\n#ifdef __AFL_INIT\n \/\/ Enable AFL deferred forkserver mode. Requires compilation using\n \/\/ afl-clang-fast++. See fuzzing.md for details.\n __AFL_INIT();\n#endif\n\n#ifdef __AFL_LOOP\n \/\/ Enable AFL persistent mode. Requires compilation using afl-clang-fast++.\n \/\/ See fuzzing.md for details.\n int ret = 0;\n while (__AFL_LOOP(1000)) {\n std::vector buffer;\n if (!read_stdin(buffer)) {\n continue;\n }\n ret = test_one_input(buffer);\n }\n return ret;\n#else\n std::vector buffer;\n if (!read_stdin(buffer)) {\n return 0;\n }\n return test_one_input(buffer);\n#endif\n}\n[test] fuzz: make test_one_input return void\/\/ Copyright (c) 2009-2018 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\nconst std::function G_TRANSLATION_FUN = nullptr;\n\nenum TEST_ID {\n CBLOCK_DESERIALIZE=0,\n CTRANSACTION_DESERIALIZE,\n CBLOCKLOCATOR_DESERIALIZE,\n CBLOCKMERKLEROOT,\n CADDRMAN_DESERIALIZE,\n CBLOCKHEADER_DESERIALIZE,\n CBANENTRY_DESERIALIZE,\n CTXUNDO_DESERIALIZE,\n CBLOCKUNDO_DESERIALIZE,\n CCOINS_DESERIALIZE,\n CNETADDR_DESERIALIZE,\n CSERVICE_DESERIALIZE,\n CMESSAGEHEADER_DESERIALIZE,\n CADDRESS_DESERIALIZE,\n CINV_DESERIALIZE,\n CBLOOMFILTER_DESERIALIZE,\n CDISKBLOCKINDEX_DESERIALIZE,\n CTXOUTCOMPRESSOR_DESERIALIZE,\n BLOCKTRANSACTIONS_DESERIALIZE,\n BLOCKTRANSACTIONSREQUEST_DESERIALIZE,\n TEST_ID_END\n};\n\nstatic bool read_stdin(std::vector& data)\n{\n uint8_t buffer[1024];\n ssize_t length = 0;\n while ((length = read(STDIN_FILENO, buffer, 1024)) > 0) {\n data.insert(data.end(), buffer, buffer + length);\n\n if (data.size() > (1 << 20)) return false;\n }\n return length == 0;\n}\n\nvoid test_one_input(std::vector buffer)\n{\n if (buffer.size() < sizeof(uint32_t)) return;\n\n uint32_t test_id = 0xffffffff;\n memcpy(&test_id, buffer.data(), sizeof(uint32_t));\n buffer.erase(buffer.begin(), buffer.begin() + sizeof(uint32_t));\n\n if (test_id >= TEST_ID_END) return;\n\n CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION);\n try {\n int nVersion;\n ds >> nVersion;\n ds.SetVersion(nVersion);\n } catch (const std::ios_base::failure& e) {\n return;\n }\n\n switch(test_id) {\n case CBLOCK_DESERIALIZE:\n {\n try\n {\n CBlock block;\n ds >> block;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CTRANSACTION_DESERIALIZE:\n {\n try\n {\n CTransaction tx(deserialize, ds);\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CBLOCKLOCATOR_DESERIALIZE:\n {\n try\n {\n CBlockLocator bl;\n ds >> bl;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CBLOCKMERKLEROOT:\n {\n try\n {\n CBlock block;\n ds >> block;\n bool mutated;\n BlockMerkleRoot(block, &mutated);\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CADDRMAN_DESERIALIZE:\n {\n try\n {\n CAddrMan am;\n ds >> am;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CBLOCKHEADER_DESERIALIZE:\n {\n try\n {\n CBlockHeader bh;\n ds >> bh;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CBANENTRY_DESERIALIZE:\n {\n try\n {\n CBanEntry be;\n ds >> be;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CTXUNDO_DESERIALIZE:\n {\n try\n {\n CTxUndo tu;\n ds >> tu;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CBLOCKUNDO_DESERIALIZE:\n {\n try\n {\n CBlockUndo bu;\n ds >> bu;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CCOINS_DESERIALIZE:\n {\n try\n {\n Coin coin;\n ds >> coin;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CNETADDR_DESERIALIZE:\n {\n try\n {\n CNetAddr na;\n ds >> na;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CSERVICE_DESERIALIZE:\n {\n try\n {\n CService s;\n ds >> s;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CMESSAGEHEADER_DESERIALIZE:\n {\n CMessageHeader::MessageStartChars pchMessageStart = {0x00, 0x00, 0x00, 0x00};\n try\n {\n CMessageHeader mh(pchMessageStart);\n ds >> mh;\n if (!mh.IsValid(pchMessageStart)) {return;}\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CADDRESS_DESERIALIZE:\n {\n try\n {\n CAddress a;\n ds >> a;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CINV_DESERIALIZE:\n {\n try\n {\n CInv i;\n ds >> i;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CBLOOMFILTER_DESERIALIZE:\n {\n try\n {\n CBloomFilter bf;\n ds >> bf;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CDISKBLOCKINDEX_DESERIALIZE:\n {\n try\n {\n CDiskBlockIndex dbi;\n ds >> dbi;\n } catch (const std::ios_base::failure& e) {return;}\n break;\n }\n case CTXOUTCOMPRESSOR_DESERIALIZE:\n {\n CTxOut to;\n CTxOutCompressor toc(to);\n try\n {\n ds >> toc;\n } catch (const std::ios_base::failure& e) {return;}\n\n break;\n }\n case BLOCKTRANSACTIONS_DESERIALIZE:\n {\n try\n {\n BlockTransactions bt;\n ds >> bt;\n } catch (const std::ios_base::failure& e) {return;}\n\n break;\n }\n case BLOCKTRANSACTIONSREQUEST_DESERIALIZE:\n {\n try\n {\n BlockTransactionsRequest btr;\n ds >> btr;\n } catch (const std::ios_base::failure& e) {return;}\n\n break;\n }\n default:\n return;\n }\n return;\n}\n\nvoid initialize()\n{\n const static auto verify_handle = MakeUnique();\n}\n\n\/\/ This function is used by libFuzzer\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)\n{\n test_one_input(std::vector(data, data + size));\n return 0;\n}\n\n\/\/ This function is used by libFuzzer\nextern \"C\" int LLVMFuzzerInitialize(int* argc, char*** argv)\n{\n initialize();\n return 0;\n}\n\n\/\/ Disabled under WIN32 due to clash with Cygwin's WinMain.\n#ifndef WIN32\n\/\/ Declare main(...) \"weak\" to allow for libFuzzer linking. libFuzzer provides\n\/\/ the main(...) function.\n__attribute__((weak))\n#endif\nint main(int argc, char **argv)\n{\n initialize();\n#ifdef __AFL_INIT\n \/\/ Enable AFL deferred forkserver mode. Requires compilation using\n \/\/ afl-clang-fast++. See fuzzing.md for details.\n __AFL_INIT();\n#endif\n\n#ifdef __AFL_LOOP\n \/\/ Enable AFL persistent mode. Requires compilation using afl-clang-fast++.\n \/\/ See fuzzing.md for details.\n while (__AFL_LOOP(1000)) {\n std::vector buffer;\n if (!read_stdin(buffer)) {\n continue;\n }\n test_one_input(buffer);\n }\n#else\n std::vector buffer;\n if (!read_stdin(buffer)) {\n return 0;\n }\n test_one_input(buffer);\n#endif\n}\n<|endoftext|>"} {"text":"\/*\n This file is part of tgl-library\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n Copyright Vitaly Valtman 2014-2015\n Copyright Topology LP 2016\n*\/\n\n#include \"tgl.h\"\n\n#include \"crypto\/rsa_pem.h\"\n#include \"crypto\/sha.h\"\n#include \"tools.h\"\n#include \"mtproto-client.h\"\n#include \"structures.h\"\n#include \"tgl_transfer_manager.h\"\n#include \"tgl-timer.h\"\n#include \"tgl-queries.h\"\n#include \"tools.h\"\n#include \"types\/tgl_online_status_observer.h\"\n#include \"types\/tgl_update_callback.h\"\n#include \"types\/tgl_rsa_key.h\"\n#include \"types\/tgl_secret_chat.h\"\n#include \"queries.h\"\n\n#include \n#include \n\nconstexpr int MAX_DC_ID = 10;\nconstexpr int32_t TG_APP_ID = 10534;\nconstexpr const char* TG_APP_HASH = \"844584f2b1fd2daecee726166dcc1ef8\";\n\nstd::unique_ptr tgl_state::s_instance;\n\ntgl_state::tgl_state()\n : locks(0)\n , ev_login(NULL)\n , m_is_started(false)\n , m_online_status(tgl_online_status::not_online)\n , m_app_id(0)\n , m_error_code(0)\n , m_temp_key_expire_time(0)\n , m_pts(0)\n , m_qts(0)\n , m_date(0)\n , m_seq(0)\n , m_test_mode(0)\n , m_our_id()\n , m_enable_pfs(false)\n , m_ipv6_enabled(false)\n , m_bn_ctx(TGLC_bn_ctx_new())\n , m_online_status_observers()\n{\n}\n\ntgl_state* tgl_state::instance()\n{\n if (!s_instance) {\n s_instance.reset(new tgl_state);\n }\n return s_instance.get();\n}\n\nvoid tgl_state::reset()\n{\n s_instance.reset();\n}\n\nvoid tgl_state::set_auth_key(int num, const char* buf)\n{\n assert(num > 0 && num <= MAX_DC_ID);\n assert(m_dcs[num]);\n\n if (buf) {\n memcpy(m_dcs[num]->auth_key, buf, 256);\n }\n\n unsigned char sha1_buffer[20];\n memset(sha1_buffer, 0, sizeof(sha1_buffer));\n TGLC_sha1((unsigned char *)m_dcs[num]->auth_key, 256, sha1_buffer);\n memcpy(&m_dcs[num]->auth_key_id, sha1_buffer + 12, 8);\n\n m_dcs[num]->set_authorized();\n\n m_callback->dc_update(m_dcs[num]);\n}\n\nvoid tgl_state::set_our_id(int id)\n{\n if (m_our_id.peer_id == id) {\n return;\n }\n m_our_id.peer_id = id;\n m_our_id.peer_type = tgl_peer_type::user;\n assert(our_id().peer_id > 0);\n m_callback->our_id(our_id().peer_id);\n}\n\nvoid tgl_state::set_dc_option(bool is_v6, int id, const std::string& ip, int port)\n{\n if (id < 0) {\n return;\n }\n\n if (static_cast(id) >= m_dcs.size()) {\n m_dcs.resize(id+1, nullptr);\n }\n\n if (!m_dcs[id]) {\n m_dcs[id] = tgl_state::instance()->allocate_dc(id);\n if (tgl_state::instance()->pfs_enabled()) {\n \/\/dc->ev = tgl_state::instance()->timer_factory()->create_timer(std::bind(®en_temp_key_gw, DC));\n \/\/dc->ev->start(0);\n }\n }\n if (is_v6) {\n m_dcs[id]->ipv6_options.option_list.push_back(std::make_pair(ip, port));\n } else {\n m_dcs[id]->ipv4_options.option_list.push_back(std::make_pair(ip, port));\n }\n}\n\nvoid tgl_state::set_dc_logged_in(int num)\n{\n TGL_DEBUG2(\"set signed \" << num);\n assert(num > 0 && num <= MAX_DC_ID);\n assert(m_dcs[num]);\n m_dcs[num]->set_logged_in();\n m_callback->dc_update(m_dcs[num]);\n}\n\nvoid tgl_state::set_working_dc(int num)\n{\n if (m_working_dc && m_working_dc->id == num) {\n return;\n }\n TGL_DEBUG2(\"change working DC to \" << num);\n assert(num > 0 && num <= MAX_DC_ID);\n m_working_dc = m_dcs[num];\n m_callback->change_active_dc(num);\n}\n\nvoid tgl_state::set_qts(int32_t qts, bool force)\n{\n if (locks & TGL_LOCK_DIFF) {\n return;\n }\n\n if (qts <= m_qts && !force) {\n return;\n }\n\n m_qts = qts;\n m_callback->qts_changed(qts);\n}\n\nvoid tgl_state::set_pts(int32_t pts, bool force)\n{\n if (locks & TGL_LOCK_DIFF && !force) {\n return;\n }\n\n if (pts <= m_pts && !force) {\n return;\n }\n\n m_pts = pts;\n m_callback->pts_changed(pts);\n}\n\nvoid tgl_state::set_date(int64_t date, bool force)\n{\n if (locks & TGL_LOCK_DIFF && !force) {\n return;\n }\n\n if (date <= m_date && !force) {\n return;\n }\n\n m_date = date;\n m_callback->date_changed(date);\n}\n\nvoid tgl_state::set_seq(int32_t seq)\n{\n if (locks & TGL_LOCK_DIFF) {\n return;\n }\n\n if (seq <= m_seq) {\n return;\n }\n\n m_seq = seq;\n}\n\nvoid tgl_state::reset_server_state()\n{\n m_qts = 0;\n m_pts = 0;\n m_date = 0;\n m_seq = 0;\n}\n\nvoid tgl_state::add_rsa_key(const std::string& key)\n{\n m_rsa_key_list.push_back(std::unique_ptr(new tgl_rsa_key(key)));\n}\n\nint tgl_state::init(const std::string& download_dir, int app_id, const std::string& app_hash, const std::string& app_version)\n{\n m_transfer_manager = std::make_shared(download_dir);\n m_app_id = app_id;\n m_app_hash = app_hash;\n m_app_version = app_version;\n assert(m_timer_factory);\n assert(m_connection_factory);\n if (!m_temp_key_expire_time) {\n m_temp_key_expire_time = 7200; \/\/ seconds\n }\n\n if (tglmp_on_start() < 0) {\n return -1;\n }\n\n if (!m_app_id) {\n m_app_id = TG_APP_ID;\n m_app_hash = TG_APP_HASH;\n }\n\n m_state_lookup_timer = m_timer_factory->create_timer(std::bind(&tgl_state::state_lookup_timeout, this));\n m_state_lookup_timer->start(3600);\n return 0;\n}\n\nvoid tgl_state::set_enable_pfs(bool val)\n{\n m_enable_pfs = val;\n}\n\nvoid tgl_state::set_test_mode(bool val)\n{\n m_test_mode = val;\n}\n\nvoid tgl_state::set_enable_ipv6(bool val)\n{\n m_ipv6_enabled = val;\n}\n\nvoid tgl_state::set_error(const std::string& error, int error_code)\n{\n m_error = error;\n m_error_code = error_code;\n}\n\nint32_t tgl_state::create_secret_chat_id()\n{\n int chat_id = tgl_random();\n while (tgl_state::instance()->secret_chat_for_id(chat_id)) {\n chat_id = tgl_random();\n }\n return chat_id;\n}\n\nstd::shared_ptr tgl_state::create_secret_chat(int32_t id)\n{\n int chat_id;\n if (id) {\n chat_id = id;\n } else {\n chat_id = create_secret_chat_id();\n }\n\n auto secret_chat = std::make_shared();\n secret_chat->id = tgl_input_peer_t(tgl_peer_type::enc_chat, chat_id, 0);\n m_secret_chats[chat_id] = secret_chat;\n\n return secret_chat;\n}\n\nstd::shared_ptr tgl_state::create_secret_chat(const tgl_input_peer_t& chat_id)\n{\n if (m_secret_chats.find(chat_id.peer_id) != m_secret_chats.end()) {\n return nullptr;\n }\n\n auto secret_chat = std::make_shared();\n secret_chat->id = chat_id;\n m_secret_chats[chat_id.peer_id] = secret_chat;\n\n return secret_chat;\n}\n\nstd::shared_ptr tgl_state::secret_chat_for_id(int chat_id) const\n{\n auto secret_chat_it = m_secret_chats.find(chat_id);\n if (secret_chat_it == m_secret_chats.end()) {\n return nullptr;\n }\n return secret_chat_it->second;\n}\n\nvoid tgl_state::add_secret_chat(const std::shared_ptr& secret_chat)\n{\n m_secret_chats[secret_chat->id.peer_id] = secret_chat;\n}\n\nvoid tgl_state::add_query(const std::shared_ptr& q)\n{\n auto id = q->msg_id();\n assert(id);\n auto inserted_iterator_pair = m_active_queries.emplace(id, q);\n if (inserted_iterator_pair.second) {\n q->dc()->increase_active_queries();\n } else {\n inserted_iterator_pair.first->second = q;\n }\n}\n\nstd::shared_ptr tgl_state::get_query(int64_t id) const\n{\n assert(id);\n auto it = m_active_queries.find(id);\n if (it == m_active_queries.end()) {\n return nullptr;\n }\n return it->second;\n}\n\nvoid tgl_state::remove_query(const std::shared_ptr& q)\n{\n auto id = q->msg_id();\n assert(id);\n auto it = m_active_queries.find(id);\n if (it != m_active_queries.end()) {\n m_active_queries.erase(it);\n q->dc()->decrease_active_queries();\n }\n}\n\nvoid tgl_state::remove_all_queries()\n{\n m_active_queries.clear();\n}\n\nstd::shared_ptr tgl_state::dc_at(int id)\n{\n if (static_cast(id) >= m_dcs.size()) {\n return nullptr;\n }\n\n return m_dcs[id];\n}\n\nstd::shared_ptr tgl_state::allocate_dc(int id)\n{\n if (static_cast(id) >= m_dcs.size()) {\n m_dcs.resize(id+1, nullptr);\n }\n\n assert(!m_dcs[id]);\n\n std::shared_ptr dc = std::make_shared();\n dc->id = id;\n m_dcs[id] = dc;\n\n return dc;\n}\n\nvoid tgl_state::state_lookup_timeout()\n{\n tgl_do_lookup_state();\n if (m_state_lookup_timer) {\n m_state_lookup_timer->start(3600);\n }\n}\n\nvoid tgl_state::logout()\n{\n tgl_do_logout(nullptr);\n}\n\nvoid tgl_state::set_online_status(tgl_online_status status)\n{\n if (status == m_online_status) {\n return;\n }\n\n m_online_status = status;\n for (const auto& weak_observer: m_online_status_observers) {\n if (auto observer = weak_observer.lock()) {\n observer->on_online_status_changed(status);\n }\n }\n}\nAdd log message when changing online status\/*\n This file is part of tgl-library\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n Copyright Vitaly Valtman 2014-2015\n Copyright Topology LP 2016\n*\/\n\n#include \"tgl.h\"\n\n#include \"crypto\/rsa_pem.h\"\n#include \"crypto\/sha.h\"\n#include \"tools.h\"\n#include \"mtproto-client.h\"\n#include \"structures.h\"\n#include \"tgl_transfer_manager.h\"\n#include \"tgl-timer.h\"\n#include \"tgl-queries.h\"\n#include \"tools.h\"\n#include \"types\/tgl_online_status_observer.h\"\n#include \"types\/tgl_update_callback.h\"\n#include \"types\/tgl_rsa_key.h\"\n#include \"types\/tgl_secret_chat.h\"\n#include \"queries.h\"\n\n#include \n#include \n\nconstexpr int MAX_DC_ID = 10;\nconstexpr int32_t TG_APP_ID = 10534;\nconstexpr const char* TG_APP_HASH = \"844584f2b1fd2daecee726166dcc1ef8\";\n\nstd::unique_ptr tgl_state::s_instance;\n\ntgl_state::tgl_state()\n : locks(0)\n , ev_login(NULL)\n , m_is_started(false)\n , m_online_status(tgl_online_status::not_online)\n , m_app_id(0)\n , m_error_code(0)\n , m_temp_key_expire_time(0)\n , m_pts(0)\n , m_qts(0)\n , m_date(0)\n , m_seq(0)\n , m_test_mode(0)\n , m_our_id()\n , m_enable_pfs(false)\n , m_ipv6_enabled(false)\n , m_bn_ctx(TGLC_bn_ctx_new())\n , m_online_status_observers()\n{\n}\n\ntgl_state* tgl_state::instance()\n{\n if (!s_instance) {\n s_instance.reset(new tgl_state);\n }\n return s_instance.get();\n}\n\nvoid tgl_state::reset()\n{\n s_instance.reset();\n}\n\nvoid tgl_state::set_auth_key(int num, const char* buf)\n{\n assert(num > 0 && num <= MAX_DC_ID);\n assert(m_dcs[num]);\n\n if (buf) {\n memcpy(m_dcs[num]->auth_key, buf, 256);\n }\n\n unsigned char sha1_buffer[20];\n memset(sha1_buffer, 0, sizeof(sha1_buffer));\n TGLC_sha1((unsigned char *)m_dcs[num]->auth_key, 256, sha1_buffer);\n memcpy(&m_dcs[num]->auth_key_id, sha1_buffer + 12, 8);\n\n m_dcs[num]->set_authorized();\n\n m_callback->dc_update(m_dcs[num]);\n}\n\nvoid tgl_state::set_our_id(int id)\n{\n if (m_our_id.peer_id == id) {\n return;\n }\n m_our_id.peer_id = id;\n m_our_id.peer_type = tgl_peer_type::user;\n assert(our_id().peer_id > 0);\n m_callback->our_id(our_id().peer_id);\n}\n\nvoid tgl_state::set_dc_option(bool is_v6, int id, const std::string& ip, int port)\n{\n if (id < 0) {\n return;\n }\n\n if (static_cast(id) >= m_dcs.size()) {\n m_dcs.resize(id+1, nullptr);\n }\n\n if (!m_dcs[id]) {\n m_dcs[id] = tgl_state::instance()->allocate_dc(id);\n if (tgl_state::instance()->pfs_enabled()) {\n \/\/dc->ev = tgl_state::instance()->timer_factory()->create_timer(std::bind(®en_temp_key_gw, DC));\n \/\/dc->ev->start(0);\n }\n }\n if (is_v6) {\n m_dcs[id]->ipv6_options.option_list.push_back(std::make_pair(ip, port));\n } else {\n m_dcs[id]->ipv4_options.option_list.push_back(std::make_pair(ip, port));\n }\n}\n\nvoid tgl_state::set_dc_logged_in(int num)\n{\n TGL_DEBUG2(\"set signed \" << num);\n assert(num > 0 && num <= MAX_DC_ID);\n assert(m_dcs[num]);\n m_dcs[num]->set_logged_in();\n m_callback->dc_update(m_dcs[num]);\n}\n\nvoid tgl_state::set_working_dc(int num)\n{\n if (m_working_dc && m_working_dc->id == num) {\n return;\n }\n TGL_DEBUG2(\"change working DC to \" << num);\n assert(num > 0 && num <= MAX_DC_ID);\n m_working_dc = m_dcs[num];\n m_callback->change_active_dc(num);\n}\n\nvoid tgl_state::set_qts(int32_t qts, bool force)\n{\n if (locks & TGL_LOCK_DIFF) {\n return;\n }\n\n if (qts <= m_qts && !force) {\n return;\n }\n\n m_qts = qts;\n m_callback->qts_changed(qts);\n}\n\nvoid tgl_state::set_pts(int32_t pts, bool force)\n{\n if (locks & TGL_LOCK_DIFF && !force) {\n return;\n }\n\n if (pts <= m_pts && !force) {\n return;\n }\n\n m_pts = pts;\n m_callback->pts_changed(pts);\n}\n\nvoid tgl_state::set_date(int64_t date, bool force)\n{\n if (locks & TGL_LOCK_DIFF && !force) {\n return;\n }\n\n if (date <= m_date && !force) {\n return;\n }\n\n m_date = date;\n m_callback->date_changed(date);\n}\n\nvoid tgl_state::set_seq(int32_t seq)\n{\n if (locks & TGL_LOCK_DIFF) {\n return;\n }\n\n if (seq <= m_seq) {\n return;\n }\n\n m_seq = seq;\n}\n\nvoid tgl_state::reset_server_state()\n{\n m_qts = 0;\n m_pts = 0;\n m_date = 0;\n m_seq = 0;\n}\n\nvoid tgl_state::add_rsa_key(const std::string& key)\n{\n m_rsa_key_list.push_back(std::unique_ptr(new tgl_rsa_key(key)));\n}\n\nint tgl_state::init(const std::string& download_dir, int app_id, const std::string& app_hash, const std::string& app_version)\n{\n m_transfer_manager = std::make_shared(download_dir);\n m_app_id = app_id;\n m_app_hash = app_hash;\n m_app_version = app_version;\n assert(m_timer_factory);\n assert(m_connection_factory);\n if (!m_temp_key_expire_time) {\n m_temp_key_expire_time = 7200; \/\/ seconds\n }\n\n if (tglmp_on_start() < 0) {\n return -1;\n }\n\n if (!m_app_id) {\n m_app_id = TG_APP_ID;\n m_app_hash = TG_APP_HASH;\n }\n\n m_state_lookup_timer = m_timer_factory->create_timer(std::bind(&tgl_state::state_lookup_timeout, this));\n m_state_lookup_timer->start(3600);\n return 0;\n}\n\nvoid tgl_state::set_enable_pfs(bool val)\n{\n m_enable_pfs = val;\n}\n\nvoid tgl_state::set_test_mode(bool val)\n{\n m_test_mode = val;\n}\n\nvoid tgl_state::set_enable_ipv6(bool val)\n{\n m_ipv6_enabled = val;\n}\n\nvoid tgl_state::set_error(const std::string& error, int error_code)\n{\n m_error = error;\n m_error_code = error_code;\n}\n\nint32_t tgl_state::create_secret_chat_id()\n{\n int chat_id = tgl_random();\n while (tgl_state::instance()->secret_chat_for_id(chat_id)) {\n chat_id = tgl_random();\n }\n return chat_id;\n}\n\nstd::shared_ptr tgl_state::create_secret_chat(int32_t id)\n{\n int chat_id;\n if (id) {\n chat_id = id;\n } else {\n chat_id = create_secret_chat_id();\n }\n\n auto secret_chat = std::make_shared();\n secret_chat->id = tgl_input_peer_t(tgl_peer_type::enc_chat, chat_id, 0);\n m_secret_chats[chat_id] = secret_chat;\n\n return secret_chat;\n}\n\nstd::shared_ptr tgl_state::create_secret_chat(const tgl_input_peer_t& chat_id)\n{\n if (m_secret_chats.find(chat_id.peer_id) != m_secret_chats.end()) {\n return nullptr;\n }\n\n auto secret_chat = std::make_shared();\n secret_chat->id = chat_id;\n m_secret_chats[chat_id.peer_id] = secret_chat;\n\n return secret_chat;\n}\n\nstd::shared_ptr tgl_state::secret_chat_for_id(int chat_id) const\n{\n auto secret_chat_it = m_secret_chats.find(chat_id);\n if (secret_chat_it == m_secret_chats.end()) {\n return nullptr;\n }\n return secret_chat_it->second;\n}\n\nvoid tgl_state::add_secret_chat(const std::shared_ptr& secret_chat)\n{\n m_secret_chats[secret_chat->id.peer_id] = secret_chat;\n}\n\nvoid tgl_state::add_query(const std::shared_ptr& q)\n{\n auto id = q->msg_id();\n assert(id);\n auto inserted_iterator_pair = m_active_queries.emplace(id, q);\n if (inserted_iterator_pair.second) {\n q->dc()->increase_active_queries();\n } else {\n inserted_iterator_pair.first->second = q;\n }\n}\n\nstd::shared_ptr tgl_state::get_query(int64_t id) const\n{\n assert(id);\n auto it = m_active_queries.find(id);\n if (it == m_active_queries.end()) {\n return nullptr;\n }\n return it->second;\n}\n\nvoid tgl_state::remove_query(const std::shared_ptr& q)\n{\n auto id = q->msg_id();\n assert(id);\n auto it = m_active_queries.find(id);\n if (it != m_active_queries.end()) {\n m_active_queries.erase(it);\n q->dc()->decrease_active_queries();\n }\n}\n\nvoid tgl_state::remove_all_queries()\n{\n m_active_queries.clear();\n}\n\nstd::shared_ptr tgl_state::dc_at(int id)\n{\n if (static_cast(id) >= m_dcs.size()) {\n return nullptr;\n }\n\n return m_dcs[id];\n}\n\nstd::shared_ptr tgl_state::allocate_dc(int id)\n{\n if (static_cast(id) >= m_dcs.size()) {\n m_dcs.resize(id+1, nullptr);\n }\n\n assert(!m_dcs[id]);\n\n std::shared_ptr dc = std::make_shared();\n dc->id = id;\n m_dcs[id] = dc;\n\n return dc;\n}\n\nvoid tgl_state::state_lookup_timeout()\n{\n tgl_do_lookup_state();\n if (m_state_lookup_timer) {\n m_state_lookup_timer->start(3600);\n }\n}\n\nvoid tgl_state::logout()\n{\n tgl_do_logout(nullptr);\n}\n\nvoid tgl_state::set_online_status(tgl_online_status status)\n{\n if (status == m_online_status) {\n return;\n }\n\n TGL_DEBUG(\"setting online status to \" << static_cast(status)\n << \" (previous: \" << static_cast(m_online_status) << \")\");\n m_online_status = status;\n for (const auto& weak_observer: m_online_status_observers) {\n if (auto observer = weak_observer.lock()) {\n observer->on_online_status_changed(status);\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Created by Harvey on 2017\/1\/4.\n\/\/\n\n#include \"strade_share_engine.h\"\n\n#define DEFAULT_CONFIG_PATH \".\/strade_share\/stradeshare_config.xml\"\n\nstrade_share::SSEngine* GetStradeShareEngine(void) {\n return strade_share::SSEngineImpl::GetInstance();\n}\n\nnamespace strade_share {\n\nSSEngineImpl* SSEngineImpl::instance_ = NULL;\nSSEngineImpl::SSEngineImpl() {\n if (!Init()) {\n LOG_ERROR(\"StradeShareEngineImpl Init error\");\n assert(0);\n }\n}\n\nSSEngineImpl* SSEngineImpl::GetInstance() {\n if (NULL == instance_) {\n instance_ = new SSEngineImpl();\n }\n return instance_;\n}\n\nbool SSEngineImpl::Init() {\n InitThreadrw(&lock_);\n bool r = false;\n std::string path = DEFAULT_CONFIG_PATH;\n config::FileConfig* config = config::FileConfig::GetFileConfig();\n if (config == NULL) {\n return false;\n }\n r = config->LoadConfig(path);\n if (!r) {\n return false;\n }\n mysql_engine_ = new StradeShareDB(config);\n LoadAllStockBasicInfo();\n return true;\n}\n\nvoid SSEngineImpl::AttachObserver(strade_logic::Observer* observer) {\n if(NULL != observer) {\n base_logic::WLockGd lk(lock_);\n this->Attach(observer);\n }\n}\n\nvoid SSEngineImpl::DetachObserver(strade_logic::Observer* observer) {\n if(NULL != observer) {\n base_logic::WLockGd lk(lock_);\n this->Detach(observer);\n }\n}\n\nvoid SSEngineImpl::LoadAllStockBasicInfo() {\n base_logic::WLockGd lk(lock_);\n std::vector stock_vec;\n mysql_engine_->FetchAllStockList(stock_vec);\n std::vector::iterator iter(stock_vec.begin());\n for (; iter != stock_vec.end(); ++iter) {\n strade_logic::StockTotalInfo& stock_total_info = (*iter);\n std::vector stock_hist_vec;\n mysql_engine_->FetchStockHistList(\n stock_total_info.GetStockCode(), stock_hist_vec);\n stock_total_info.AddStockHistVec(stock_hist_vec);\n AddStockTotalInfoNonblock(stock_total_info);\n }\n}\n\nvoid SSEngineImpl::UpdateStockRealMarketData(\n REAL_MARKET_DATA_VEC& stocks_market_data) {\n\n {\n base_logic::WLockGd lk(lock_);\n int total_count = 0;\n REAL_MARKET_DATA_VEC::const_iterator iter(stocks_market_data.begin());\n for (; iter != stocks_market_data.end(); ++iter) {\n const strade_logic::StockRealInfo& stock_real_info = *iter;\n const std::string& stock_code = stock_real_info.GetStockCode();\n const time_t& trade_time = stock_real_info.GetTradeTime();\n strade_logic::StockTotalInfo* stock_total_info = NULL;\n GetStockTotalNonBlock(stock_code, &stock_total_info);\n if (NULL == stock_total_info) {\n LOG_ERROR2(\"UpdateStockRealMarketData stock_code=%s, not exists!!!!\",\n stock_code.c_str());\n continue;\n }\n stock_total_info->AddStockRealInfoByTime(trade_time, stock_real_info);\n ++total_count;\n }\n LOG_DEBUG2(\"UpdateStockRealMarketData total_count=%d, current_time=%d\",\n total_count, time(NULL));\n }\n\n \/\/ 通知所有需要实时行情数据的观察者\n this->Notify(strade_logic::REALTIME_MARKET_VALUE_UPDATE);\n}\n\nbool SSEngineImpl::UpdateStockHistInfoByDate(const std::string& stock_code,\n const std::string& date,\n strade_logic::StockHistInfo& stock_hist_info) {\n base_logic::WLockGd lk(lock_);\n strade_logic::StockTotalInfo* stock_total_info = NULL;\n GetStockTotalNonBlock(stock_code, &stock_total_info);\n if (NULL != stock_total_info) {\n return stock_total_info->AddStockHistInfoByDate(date, stock_hist_info);\n }\n return false;\n}\n\nbool SSEngineImpl::ClearOldRealTradeMap() {\n base_logic::WLockGd lk(lock_);\n STOCKS_MAP::iterator iter(share_cache_.stocks_map_.begin());\n for (; iter != share_cache_.stocks_map_.end(); ++iter) {\n iter->second.ClearRealMap();\n }\n return true;\n}\n\nbool SSEngineImpl::UpdateStockHistDataVec(\n const std::string& stock_code,\n STOCK_HIST_DATA_VEC& stock_vec) {\n base_logic::WLockGd lk(lock_);\n strade_logic::StockTotalInfo* stock_total_info = NULL;\n GetStockTotalNonBlock(stock_code, &stock_total_info);\n if (NULL == stock_total_info) {\n return false;\n }\n stock_total_info->AddStockHistVec(stock_vec);\n return true;\n}\n\nbool SSEngineImpl::AddStockTotalInfoNonblock(\n const strade_logic::StockTotalInfo& stock_total_info) {\n const std::string& stock_code = stock_total_info.GetStockCode();\n share_cache_.stocks_map_[stock_code] = stock_total_info;\n return true;\n}\n\nbool SSEngineImpl::AddStockTotalInfoBlock(\n const strade_logic::StockTotalInfo& stock_total_info) {\n base_logic::WLockGd lk(lock_);\n AddStockTotalInfoNonblock(stock_total_info);\n}\n\nconst STOCKS_MAP& SSEngineImpl::GetAllStockTotalMap() {\n base_logic::RLockGd lk(lock_);\n return share_cache_.stocks_map_;\n}\n\nconst STOCK_HIST_MAP& SSEngineImpl::GetStockHistMap(\n const std::string& stock_code) {\n base_logic::RLockGd lk(lock_);\n strade_logic::StockTotalInfo* stock_total_info = NULL;\n GetStockTotalNonBlock(stock_code, &stock_total_info);\n if (NULL != stock_total_info) {\n return stock_total_info->GetStockHistMap();\n }\n return STOCK_HIST_MAP();\n}\n\nconst STOCK_REAL_MAP& SSEngineImpl::GetStockRealInfoMap(\n const std::string& stock_code) {\n base_logic::RLockGd lk(lock_);\n strade_logic::StockTotalInfo* stock_total_info = NULL;\n GetStockTotalNonBlock(stock_code, &stock_total_info);\n if (NULL != stock_total_info) {\n return stock_total_info->GetStockRealMap();\n }\n return STOCK_REAL_MAP();\n}\n\nSTOCKS_MAP SSEngineImpl::GetAllStockTotalMapCopy() {\n base_logic::RLockGd lk(lock_);\n return share_cache_.stocks_map_;\n}\n\nSTOCK_HIST_MAP SSEngineImpl::GetStockHistMapByCodeCopy(\n const std::string& stock_code) {\n const STOCK_HIST_MAP& stock_hist_map =\n GetStockHistMap(stock_code);\n return stock_hist_map;\n}\n\nSTOCK_REAL_MAP SSEngineImpl::GetStockRealInfoMapCopy(\n const std::string& stock_code) {\n const STOCK_REAL_MAP& stock_real_map =\n GetStockRealInfoMap(stock_code);\n return stock_real_map;\n}\n\nbool SSEngineImpl::GetStockTotalInfoByCode(\n const std::string& stock_code,\n strade_logic::StockTotalInfo* stock_total_info) {\n base_logic::WLockGd lk(lock_);\n GetStockTotalNonBlock(stock_code, &stock_total_info);\n}\n\nbool SSEngineImpl::GetStockHistInfoByDate(\n const std::string& stock_code,\n const std::string& date,\n strade_logic::StockHistInfo* stock_hist_info) {\n base_logic::WLockGd lk(lock_);\n strade_logic::StockTotalInfo* stock_total_info(NULL);\n GetStockTotalNonBlock(stock_code, &stock_total_info);\n if (NULL == stock_total_info) {\n return false;\n }\n return stock_total_info->GetStockHistInfoByDate(date, &stock_hist_info);\n}\n\nbool SSEngineImpl::GetStockRealMarketDataByTime(\n const std::string& stock_code,\n const time_t& time,\n strade_logic::StockRealInfo* stock_real_info) {\n base_logic::WLockGd lk(lock_);\n strade_logic::StockTotalInfo* stock_total_info(NULL);\n GetStockTotalNonBlock(stock_code, &stock_total_info);\n if (NULL == stock_total_info) {\n return false;\n }\n return stock_total_info->GetStockRealInfoByTradeTime(time, &stock_real_info);\n}\n\n} \/* namespace strade_share *\/\n修改共享库返回map时为拷贝\/\/\n\/\/ Created by Harvey on 2017\/1\/4.\n\/\/\n\n#include \"strade_share_engine.h\"\n\n#define DEFAULT_CONFIG_PATH \".\/strade_share\/stradeshare_config.xml\"\n\nstrade_share::SSEngine* GetStradeShareEngine(void) {\n return strade_share::SSEngineImpl::GetInstance();\n}\n\nnamespace strade_share {\n\nSSEngineImpl* SSEngineImpl::instance_ = NULL;\nSSEngineImpl::SSEngineImpl() {\n if (!Init()) {\n LOG_ERROR(\"StradeShareEngineImpl Init error\");\n assert(0);\n }\n}\n\nSSEngineImpl* SSEngineImpl::GetInstance() {\n if (NULL == instance_) {\n instance_ = new SSEngineImpl();\n }\n return instance_;\n}\n\nbool SSEngineImpl::Init() {\n InitThreadrw(&lock_);\n bool r = false;\n std::string path = DEFAULT_CONFIG_PATH;\n config::FileConfig* config = config::FileConfig::GetFileConfig();\n if (config == NULL) {\n return false;\n }\n r = config->LoadConfig(path);\n if (!r) {\n return false;\n }\n mysql_engine_ = new StradeShareDB(config);\n LoadAllStockBasicInfo();\n return true;\n}\n\nvoid SSEngineImpl::AttachObserver(strade_logic::Observer* observer) {\n if(NULL != observer) {\n base_logic::WLockGd lk(lock_);\n this->Attach(observer);\n }\n}\n\nvoid SSEngineImpl::DetachObserver(strade_logic::Observer* observer) {\n if(NULL != observer) {\n base_logic::WLockGd lk(lock_);\n this->Detach(observer);\n }\n}\n\nvoid SSEngineImpl::LoadAllStockBasicInfo() {\n base_logic::WLockGd lk(lock_);\n std::vector stock_vec;\n mysql_engine_->FetchAllStockList(stock_vec);\n std::vector::iterator iter(stock_vec.begin());\n for (; iter != stock_vec.end(); ++iter) {\n strade_logic::StockTotalInfo& stock_total_info = (*iter);\n std::vector stock_hist_vec;\n mysql_engine_->FetchStockHistList(\n stock_total_info.GetStockCode(), stock_hist_vec);\n stock_total_info.AddStockHistVec(stock_hist_vec);\n AddStockTotalInfoNonblock(stock_total_info);\n }\n}\n\nvoid SSEngineImpl::UpdateStockRealMarketData(\n REAL_MARKET_DATA_VEC& stocks_market_data) {\n\n {\n base_logic::WLockGd lk(lock_);\n int total_count = 0;\n REAL_MARKET_DATA_VEC::const_iterator iter(stocks_market_data.begin());\n for (; iter != stocks_market_data.end(); ++iter) {\n const strade_logic::StockRealInfo& stock_real_info = *iter;\n const std::string& stock_code = stock_real_info.GetStockCode();\n const time_t& trade_time = stock_real_info.GetTradeTime();\n strade_logic::StockTotalInfo* stock_total_info = NULL;\n GetStockTotalNonBlock(stock_code, &stock_total_info);\n if (NULL == stock_total_info) {\n LOG_ERROR2(\"UpdateStockRealMarketData stock_code=%s, not exists!!!!\",\n stock_code.c_str());\n continue;\n }\n stock_total_info->AddStockRealInfoByTime(trade_time, stock_real_info);\n ++total_count;\n }\n LOG_DEBUG2(\"UpdateStockRealMarketData total_count=%d, current_time=%d\",\n total_count, time(NULL));\n }\n\n \/\/ 通知所有需要实时行情数据的观察者\n this->Notify(strade_logic::REALTIME_MARKET_VALUE_UPDATE);\n}\n\nbool SSEngineImpl::UpdateStockHistInfoByDate(const std::string& stock_code,\n const std::string& date,\n strade_logic::StockHistInfo& stock_hist_info) {\n base_logic::WLockGd lk(lock_);\n strade_logic::StockTotalInfo* stock_total_info = NULL;\n GetStockTotalNonBlock(stock_code, &stock_total_info);\n if (NULL != stock_total_info) {\n return stock_total_info->AddStockHistInfoByDate(date, stock_hist_info);\n }\n return false;\n}\n\nbool SSEngineImpl::ClearOldRealTradeMap() {\n base_logic::WLockGd lk(lock_);\n STOCKS_MAP::iterator iter(share_cache_.stocks_map_.begin());\n for (; iter != share_cache_.stocks_map_.end(); ++iter) {\n iter->second.ClearRealMap();\n }\n return true;\n}\n\nbool SSEngineImpl::UpdateStockHistDataVec(\n const std::string& stock_code,\n STOCK_HIST_DATA_VEC& stock_vec) {\n base_logic::WLockGd lk(lock_);\n strade_logic::StockTotalInfo* stock_total_info = NULL;\n GetStockTotalNonBlock(stock_code, &stock_total_info);\n if (NULL == stock_total_info) {\n return false;\n }\n stock_total_info->AddStockHistVec(stock_vec);\n return true;\n}\n\nbool SSEngineImpl::AddStockTotalInfoNonblock(\n const strade_logic::StockTotalInfo& stock_total_info) {\n const std::string& stock_code = stock_total_info.GetStockCode();\n share_cache_.stocks_map_[stock_code] = stock_total_info;\n return true;\n}\n\nbool SSEngineImpl::AddStockTotalInfoBlock(\n const strade_logic::StockTotalInfo& stock_total_info) {\n base_logic::WLockGd lk(lock_);\n AddStockTotalInfoNonblock(stock_total_info);\n return true;\n}\n\nconst STOCKS_MAP& SSEngineImpl::GetAllStockTotalMap() {\n base_logic::RLockGd lk(lock_);\n return share_cache_.stocks_map_;\n}\n\nconst STOCK_HIST_MAP& SSEngineImpl::GetStockHistMap(\n const std::string& stock_code) {\n base_logic::RLockGd lk(lock_);\n strade_logic::StockTotalInfo* stock_total_info = NULL;\n GetStockTotalNonBlock(stock_code, &stock_total_info);\n if (NULL != stock_total_info) {\n return stock_total_info->GetStockHistMap();\n }\n return STOCK_HIST_MAP();\n}\n\nconst STOCK_REAL_MAP& SSEngineImpl::GetStockRealInfoMap(\n const std::string& stock_code) {\n base_logic::RLockGd lk(lock_);\n strade_logic::StockTotalInfo* stock_total_info = NULL;\n GetStockTotalNonBlock(stock_code, &stock_total_info);\n if (NULL != stock_total_info) {\n return stock_total_info->GetStockRealMap();\n }\n return STOCK_REAL_MAP();\n}\n\nSTOCKS_MAP SSEngineImpl::GetAllStockTotalMapCopy() {\n base_logic::RLockGd lk(lock_);\n return share_cache_.stocks_map_;\n}\n\nSTOCK_HIST_MAP SSEngineImpl::GetStockHistMapByCodeCopy(\n const std::string& stock_code) {\n const STOCK_HIST_MAP& stock_hist_map =\n GetStockHistMap(stock_code);\n return stock_hist_map;\n}\n\nSTOCK_REAL_MAP SSEngineImpl::GetStockRealInfoMapCopy(\n const std::string& stock_code) {\n const STOCK_REAL_MAP& stock_real_map =\n GetStockRealInfoMap(stock_code);\n return stock_real_map;\n}\n\nbool SSEngineImpl::GetStockTotalInfoByCode(\n const std::string& stock_code,\n strade_logic::StockTotalInfo* stock_total_info) {\n base_logic::WLockGd lk(lock_);\n GetStockTotalNonBlock(stock_code, &stock_total_info);\n}\n\nbool SSEngineImpl::GetStockHistInfoByDate(\n const std::string& stock_code,\n const std::string& date,\n strade_logic::StockHistInfo* stock_hist_info) {\n base_logic::WLockGd lk(lock_);\n strade_logic::StockTotalInfo* stock_total_info(NULL);\n GetStockTotalNonBlock(stock_code, &stock_total_info);\n if (NULL == stock_total_info) {\n return false;\n }\n return stock_total_info->GetStockHistInfoByDate(date, &stock_hist_info);\n}\n\nbool SSEngineImpl::GetStockRealMarketDataByTime(\n const std::string& stock_code,\n const time_t& time,\n strade_logic::StockRealInfo* stock_real_info) {\n base_logic::WLockGd lk(lock_);\n strade_logic::StockTotalInfo* stock_total_info(NULL);\n GetStockTotalNonBlock(stock_code, &stock_total_info);\n if (NULL == stock_total_info) {\n return false;\n }\n return stock_total_info->GetStockRealInfoByTradeTime(time, &stock_real_info);\n}\n\n} \/* namespace strade_share *\/\n<|endoftext|>"} {"text":"\/*!\r\n \\copyright (c) RDO-Team, 2003-2012\r\n \\file app\/rdo_studio_mfc\/src\/model\/model_view.cpp\r\n \\author (rdo@rk9.bmstu.ru)\r\n \\date 20.02.2003\r\n \\brief \r\n \\indent 4T\r\n*\/\r\n\r\n\/\/ ---------------------------------------------------------------------------- PCH\r\n#include \"app\/rdo_studio_mfc\/pch\/stdpch.h\"\r\n\/\/ ----------------------------------------------------------------------- INCLUDES\r\n#include \r\n#include \r\n#include \r\n\/\/ ----------------------------------------------------------------------- SYNOPSIS\r\n#include \"app\/rdo_studio_mfc\/src\/model\/model_view.h\"\r\n#include \"app\/rdo_studio_mfc\/src\/application.h\"\r\n#include \"app\/rdo_studio_mfc\/src\/main_windows_base.h\"\r\n#include \"app\/rdo_studio_mfc\/edit_ctrls\/rdofindedit.h\"\r\n#include \"app\/rdo_studio_mfc\/rdo_edit\/rdoeditortabctrl.h\"\r\n#include \"app\/rdo_studio_mfc\/resource.h\"\r\n#include \"app\/rdo_studio_mfc\/src\/main_frm.h\"\r\n\/\/ --------------------------------------------------------------------------------\r\n\r\nusing namespace rdoEditor;\r\n\r\n\/\/ --------------------------------------------------------------------------------\r\n\/\/ -------------------- RDOStudioModelView\r\n\/\/ --------------------------------------------------------------------------------\r\n\r\n\/\/ ON_UPDATE_COMMAND_UI \r\n\r\n\/\/! @todo qt\r\n\/\/ RDOStudioEditBaseView -> QWidget\r\n\/\/BEGIN_MESSAGE_MAP(RDOStudioModelView, RDOStudioEditBaseView)\r\n\/\/\tON_WM_CREATE()\r\n\/\/\tON_WM_SETFOCUS()\r\n\/\/\tON_WM_SIZE()\r\n\/\/END_MESSAGE_MAP()\r\n\r\nRDOStudioModelView::RDOStudioModelView(PTR(QWidget) pParent)\r\n\t: parent_type(pParent)\r\n\t, m_pModel (NULL)\r\n\t, m_pTabCtrl (NULL)\r\n\t, m_pFindDialog(NULL)\r\n{\r\n\tm_pTabCtrl = new RDOEditorTabCtrl(this, this);\r\n\r\n\tPTR(QVBoxLayout) pLayout = new QVBoxLayout(this);\r\n\tpLayout->setSpacing(0);\r\n\tpLayout->setContentsMargins(0, 0, 0, 0);\r\n\tpLayout->addWidget(m_pTabCtrl);\r\n\r\n\tRDOStudioMainFrame* pMainWindow = studioApp.getMainWndUI();\r\n\tASSERT(pMainWindow);\r\n\tpMainWindow->actSearchFindInModel->setEnabled(true);\r\n\tconnect(pMainWindow->actSearchFindInModel, SIGNAL(triggered(bool)), this, SLOT(onSearchFindInModel()));\r\n}\r\n\r\nRDOStudioModelView::~RDOStudioModelView()\r\n{\r\n\tRDOStudioMainFrame* pMainWindow = studioApp.getMainWndUI();\r\n\tASSERT(pMainWindow);\r\n\tdisconnect(pMainWindow->actSearchFindInModel, SIGNAL(triggered(bool)), this, SLOT(onSearchFindInModel()));\r\n}\r\n\r\nvoid RDOStudioModelView::setModel(PTR(RDOStudioModel) pModel)\r\n{\r\n\tASSERT(m_pModel != pModel);\r\n\tm_pModel = pModel;\r\n}\r\n\r\nvoid RDOStudioModelView::closeEvent(PTR(QCloseEvent) event)\r\n{\r\n\tif (m_pModel)\r\n\t{\r\n\t\tif (m_pModel->closeModel())\r\n\t\t{\r\n\t\t\tevent->accept();\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tevent->ignore();\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\/\/! @todo qt\r\n\/\/BOOL RDOStudioModelView::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo) \r\n\/\/{\r\n\/\/\tif ( m_pTabCtrl->getCurrentEdit()->OnCmdMsg( nID, nCode, pExtra, pHandlerInfo ) ) return TRUE;\r\n\/\/\treturn RDOStudioEditBaseView::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo);\r\n\/\/}\r\n\/\/\r\n\/\/void RDOStudioModelView::OnSetFocus(CWnd* pOldWnd)\r\n\/\/{\r\n\/\/\tRDOStudioEditBaseView::OnSetFocus( pOldWnd );\r\n\/\/\tm_pTabCtrl->SetFocus();\r\n\/\/}\r\n\/\/\r\n\r\nREF(rdoEditor::RDOEditorTabCtrl) RDOStudioModelView::getTab()\r\n{\r\n\treturn *m_pTabCtrl;\r\n}\r\n\r\nvoid RDOStudioModelView::onSearchFindInModel()\r\n{\r\n\tm_findSettings.what = m_pTabCtrl->getCurrentEdit()->getWordForFind();\r\n\r\n\tif (!m_pFindDialog)\r\n\t{\r\n\t\tm_pFindDialog = new FindDialog(\r\n\t\t\tthis,\r\n\t\t\tboost::bind(&RDOStudioModelView::onFindDlgFind, this, _1),\r\n\t\t\tboost::bind(&RDOStudioModelView::onFindDlgClose, this)\r\n\t\t);\r\n\t}\r\n\r\n\tm_pFindDialog->setSettings(m_findSettings);\r\n\tm_pFindDialog->show();\r\n\tm_pFindDialog->raise();\r\n\tm_pFindDialog->activateWindow();\r\n}\r\n\r\nvoid RDOStudioModelView::onFindDlgFind(CREF(FindDialog::Settings) settings)\r\n{\r\n\tm_findSettings = settings;\r\n\tonSearchFindAll();\r\n}\r\n\r\nvoid RDOStudioModelView::onFindDlgClose()\r\n{\r\n\tm_pFindDialog = NULL;\r\n}\r\n\r\nvoid RDOStudioModelView::onSearchFindAll()\r\n{\r\n\tstudioApp.getIMainWnd()->getDockFind().clear();\r\n\tstudioApp.getIMainWnd()->getDockFind().raise();\r\n\ttstring findStr = m_findSettings.what;\r\n\trbool bMatchCase = m_findSettings.matchCase;\r\n\trbool bMatchWholeWord = m_findSettings.matchWholeWord;\r\n\tstudioApp.getIMainWnd()->getDockFind().getContext().setKeyword(findStr, bMatchCase);\r\n\tstudioApp.getIMainWnd()->getDockFind().appendString(rdo::format(ID_FINDINMODEL_BEGINMSG, findStr.c_str()));\r\n\tint count = 0;\r\n\tfor (int i = 0; i < m_pTabCtrl->count(); i++)\r\n\t{\r\n\t\tPTR(RDOEditorEdit) pEdit = m_pTabCtrl->getItemEdit(i);\r\n\t\tint pos = 0;\r\n\t\tint line = 0;\r\n\t\twhile (pos != -1)\r\n\t\t{\r\n\t\t\tpos = pEdit->findPos(findStr, line, bMatchCase, bMatchWholeWord);\r\n\t\t\tif (pos != -1)\r\n\t\t\t{\r\n\t\t\t\tline = pEdit->getLineFromPosition(pos);\r\n\t\t\t\tstudioApp.getIMainWnd()->getDockFind().appendString(pEdit->getLine(line), m_pTabCtrl->indexToType(i), line, pos - pEdit->getPositionFromLine(line));\r\n\t\t\t\tline++;\r\n\t\t\t\tcount++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tm_pFindDialog = NULL;\r\n\ttstring s = count\r\n\t\t? rdo::format(ID_FINDINMODEL_ENDMSG_COUNT, count)\r\n\t\t: rdo::format(ID_FINDINMODEL_ENDMSG_NOTFOUND, findStr.c_str());\r\n\tstudioApp.getIMainWnd()->getDockFind().appendString(s);\r\n} - чистка кода\/*!\r\n \\copyright (c) RDO-Team, 2003-2012\r\n \\file app\/rdo_studio_mfc\/src\/model\/model_view.cpp\r\n \\author (rdo@rk9.bmstu.ru)\r\n \\date 20.02.2003\r\n \\brief \r\n \\indent 4T\r\n*\/\r\n\r\n\/\/ ---------------------------------------------------------------------------- PCH\r\n#include \"app\/rdo_studio_mfc\/pch\/stdpch.h\"\r\n\/\/ ----------------------------------------------------------------------- INCLUDES\r\n#include \r\n#include \r\n#include \r\n\/\/ ----------------------------------------------------------------------- SYNOPSIS\r\n#include \"app\/rdo_studio_mfc\/src\/model\/model_view.h\"\r\n#include \"app\/rdo_studio_mfc\/src\/application.h\"\r\n#include \"app\/rdo_studio_mfc\/src\/main_windows_base.h\"\r\n#include \"app\/rdo_studio_mfc\/edit_ctrls\/rdofindedit.h\"\r\n#include \"app\/rdo_studio_mfc\/rdo_edit\/rdoeditortabctrl.h\"\r\n#include \"app\/rdo_studio_mfc\/resource.h\"\r\n#include \"app\/rdo_studio_mfc\/src\/main_frm.h\"\r\n\/\/ --------------------------------------------------------------------------------\r\n\r\nusing namespace rdoEditor;\r\n\r\n\/\/ --------------------------------------------------------------------------------\r\n\/\/ -------------------- RDOStudioModelView\r\n\/\/ --------------------------------------------------------------------------------\r\nRDOStudioModelView::RDOStudioModelView(PTR(QWidget) pParent)\r\n\t: parent_type(pParent)\r\n\t, m_pModel (NULL)\r\n\t, m_pTabCtrl (NULL)\r\n\t, m_pFindDialog(NULL)\r\n{\r\n\tm_pTabCtrl = new RDOEditorTabCtrl(this, this);\r\n\r\n\tPTR(QVBoxLayout) pLayout = new QVBoxLayout(this);\r\n\tpLayout->setSpacing(0);\r\n\tpLayout->setContentsMargins(0, 0, 0, 0);\r\n\tpLayout->addWidget(m_pTabCtrl);\r\n\r\n\tRDOStudioMainFrame* pMainWindow = studioApp.getMainWndUI();\r\n\tASSERT(pMainWindow);\r\n\tpMainWindow->actSearchFindInModel->setEnabled(true);\r\n\tconnect(pMainWindow->actSearchFindInModel, SIGNAL(triggered(bool)), this, SLOT(onSearchFindInModel()));\r\n}\r\n\r\nRDOStudioModelView::~RDOStudioModelView()\r\n{\r\n\tRDOStudioMainFrame* pMainWindow = studioApp.getMainWndUI();\r\n\tASSERT(pMainWindow);\r\n\tdisconnect(pMainWindow->actSearchFindInModel, SIGNAL(triggered(bool)), this, SLOT(onSearchFindInModel()));\r\n}\r\n\r\nvoid RDOStudioModelView::setModel(PTR(RDOStudioModel) pModel)\r\n{\r\n\tASSERT(m_pModel != pModel);\r\n\tm_pModel = pModel;\r\n}\r\n\r\nvoid RDOStudioModelView::closeEvent(PTR(QCloseEvent) event)\r\n{\r\n\tif (m_pModel)\r\n\t{\r\n\t\tif (m_pModel->closeModel())\r\n\t\t{\r\n\t\t\tevent->accept();\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tevent->ignore();\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\/\/! @todo qt\r\n\/\/BOOL RDOStudioModelView::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo) \r\n\/\/{\r\n\/\/\tif ( m_pTabCtrl->getCurrentEdit()->OnCmdMsg( nID, nCode, pExtra, pHandlerInfo ) ) return TRUE;\r\n\/\/\treturn RDOStudioEditBaseView::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo);\r\n\/\/}\r\n\/\/\r\n\/\/void RDOStudioModelView::OnSetFocus(CWnd* pOldWnd)\r\n\/\/{\r\n\/\/\tRDOStudioEditBaseView::OnSetFocus( pOldWnd );\r\n\/\/\tm_pTabCtrl->SetFocus();\r\n\/\/}\r\n\/\/\r\n\r\nREF(rdoEditor::RDOEditorTabCtrl) RDOStudioModelView::getTab()\r\n{\r\n\treturn *m_pTabCtrl;\r\n}\r\n\r\nvoid RDOStudioModelView::onSearchFindInModel()\r\n{\r\n\tm_findSettings.what = m_pTabCtrl->getCurrentEdit()->getWordForFind();\r\n\r\n\tif (!m_pFindDialog)\r\n\t{\r\n\t\tm_pFindDialog = new FindDialog(\r\n\t\t\tthis,\r\n\t\t\tboost::bind(&RDOStudioModelView::onFindDlgFind, this, _1),\r\n\t\t\tboost::bind(&RDOStudioModelView::onFindDlgClose, this)\r\n\t\t);\r\n\t}\r\n\r\n\tm_pFindDialog->setSettings(m_findSettings);\r\n\tm_pFindDialog->show();\r\n\tm_pFindDialog->raise();\r\n\tm_pFindDialog->activateWindow();\r\n}\r\n\r\nvoid RDOStudioModelView::onFindDlgFind(CREF(FindDialog::Settings) settings)\r\n{\r\n\tm_findSettings = settings;\r\n\tonSearchFindAll();\r\n}\r\n\r\nvoid RDOStudioModelView::onFindDlgClose()\r\n{\r\n\tm_pFindDialog = NULL;\r\n}\r\n\r\nvoid RDOStudioModelView::onSearchFindAll()\r\n{\r\n\tstudioApp.getIMainWnd()->getDockFind().clear();\r\n\tstudioApp.getIMainWnd()->getDockFind().raise();\r\n\ttstring findStr = m_findSettings.what;\r\n\trbool bMatchCase = m_findSettings.matchCase;\r\n\trbool bMatchWholeWord = m_findSettings.matchWholeWord;\r\n\tstudioApp.getIMainWnd()->getDockFind().getContext().setKeyword(findStr, bMatchCase);\r\n\tstudioApp.getIMainWnd()->getDockFind().appendString(rdo::format(ID_FINDINMODEL_BEGINMSG, findStr.c_str()));\r\n\tint count = 0;\r\n\tfor (int i = 0; i < m_pTabCtrl->count(); i++)\r\n\t{\r\n\t\tPTR(RDOEditorEdit) pEdit = m_pTabCtrl->getItemEdit(i);\r\n\t\tint pos = 0;\r\n\t\tint line = 0;\r\n\t\twhile (pos != -1)\r\n\t\t{\r\n\t\t\tpos = pEdit->findPos(findStr, line, bMatchCase, bMatchWholeWord);\r\n\t\t\tif (pos != -1)\r\n\t\t\t{\r\n\t\t\t\tline = pEdit->getLineFromPosition(pos);\r\n\t\t\t\tstudioApp.getIMainWnd()->getDockFind().appendString(pEdit->getLine(line), m_pTabCtrl->indexToType(i), line, pos - pEdit->getPositionFromLine(line));\r\n\t\t\t\tline++;\r\n\t\t\t\tcount++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tm_pFindDialog = NULL;\r\n\ttstring s = count\r\n\t\t? rdo::format(ID_FINDINMODEL_ENDMSG_COUNT, count)\r\n\t\t: rdo::format(ID_FINDINMODEL_ENDMSG_NOTFOUND, findStr.c_str());\r\n\tstudioApp.getIMainWnd()->getDockFind().appendString(s);\r\n}<|endoftext|>"} {"text":"\/*******************************************************************************\n * ALMA - Atacama Large Millimiter Array\n * (c) European Southern Observatory, 2011\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * \"@(#) $Id: bulkDataNTReaderListener.cpp,v 1.34 2011\/12\/22 15:59:57 bjeram Exp $\"\n *\n * who when what\n * -------- -------- ----------------------------------------------\n * bjeram 2011-04-19 created\n *\/\n\n#include \"bulkDataNTReaderListener.h\"\n#include \"ACS_BD_Errors.h\"\n#include \n#include \n#include \n#include \n\nusing namespace ACS_BD_Errors;\nusing namespace ACS_DDS_Errors;\nusing namespace AcsBulkdata;\nusing namespace std;\n\n#define BDNT_READER_LISTENER_USER_ERR(call)\t\t \t\t\t\t\t\t\t\t\\\n try { call; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n }catch(const ACSErr::ACSbaseExImpl &ex){\t\t\t\t\t\t\t\t\t\t\\\n UserCallbackErrorCompletion ucb(ex, __FILE__, __LINE__, __FUNCTION__);\t\t\\\n ucb.setCall(\"#call\");\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n callback_mp->onError(ucb);\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n }catch(const std::exception &stdex){\t\t\t\t\t\t\t\t\t\t\t\\\n ACSErrTypeCommon::StdExceptionExImpl ex(__FILE__, __LINE__, __FUNCTION__); \\\n ex.setWhat(stdex.what());\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n UserCallbackErrorCompletion ucb(ex, __FILE__, __LINE__, __FUNCTION__);\t\t\\\n ucb.setCall(\"#call\");\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n callback_mp->onError(ucb);\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n }catch(...){\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n ACSErrTypeCommon::UnknownExImpl ex(__FILE__, __LINE__, __FUNCTION__); \t\\\n UserCallbackErrorCompletion ucb(ex, __FILE__, __LINE__, __FUNCTION__);\t\t\\\n ucb.setCall(\"#call\");\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n callback_mp->onError(ucb);\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n }\n\n\nBulkDataNTReaderListener::BulkDataNTReaderListener(const char* name, BulkDataNTCallback* cb)\n: BulkDataNTDDSLoggable(\"BulkDataNT:\"+string(name)),\n currentState_m(StartState),\n topicName_m(name),\n dataLength_m(0),\n frameCounter_m(0),\n totalFrames_m(0),\n callback_mp (cb)\n{\n ACS_TRACE(__FUNCTION__);\n nextFrame_m=0;\n frameDataReader_mp=0;\n conseqErrorCount_m=0;\n maxConseqErrorCount_m = 4; \/\/TBD now hardcoded, to be get from somewhere else\n cbReceiveTimeoutSec_m = callback_mp->getCBReceiveProcessTimeout();\n}\/\/BulkDataNTReaderListener\n\n\nBulkDataNTReaderListener::~BulkDataNTReaderListener ()\n{\n ACS_TRACE(__FUNCTION__);\n}\/\/~BulkDataNTReaderListener\n\nvoid BulkDataNTReaderListener::on_data_available(DDS::DataReader* reader)\n{\n DDS::ReturnCode_t retCode;\n DDS::SampleInfo si ;\n ACSBulkData::BulkDataNTFrame message;\n unsigned char tmpArray[ACSBulkData::FRAME_MAX_LEN];\n\n initalizeLogging(); \/\/force initialization of logging sys TBD changed\n\n if (frameDataReader_mp==NULL)\n {\n frameDataReader_mp = ACSBulkData::BulkDataNTFrameDataReader::narrow(reader);\n if ( frameDataReader_mp==NULL) {\n ACS_DDS_Errors::DDSNarrowFailedCompletion nerr(__FILE__, __LINE__, __FUNCTION__);\n nerr.setVariable(\"frameDataReader_mp\");\n nerr.setNarrowType(\"ACSBulkData::BulkDataNTFrameDataReader\");\n callback_mp->onError(nerr);\n return;\n }\/\/if\n }\/\/if\n\n message.data.maximum(ACSBulkData::FRAME_MAX_LEN); \/\/TBD constant from\n while (\t(retCode = frameDataReader_mp->take_next_sample(message, si)) != DDS::RETCODE_NO_DATA )\n {\n if (retCode == DDS::RETCODE_OK)\n {\n if (si.valid_data == true)\n {\n switch(message.dataType)\n {\n case ACSBulkData::BD_PARAM:\n {\n cout << topicName_m << \" startSend: parameter size: \" << message.data.length() << endl;\n if (currentState_m==StartState || currentState_m==StopState)\n {\n dataLength_m = 0;\n frameCounter_m = 0;\n currentState_m = DataRcvState;\n message.data.to_array(tmpArray, message.data.length());\n BDNT_READER_LISTENER_USER_ERR( callback_mp->cbStart(tmpArray, message.data.length()) )\n conseqErrorCount_m=0;\n }\n else \/\/error\n {\n WrongFrameOrderCompletion wfo(__FILE__, __LINE__, __FUNCTION__);\n wfo.setDataType(\"BD_PARAM\"); wfo.setState(currentState_m);\n wfo.setFlow(topicName_m.c_str()); wfo.setFrameCount(frameCounter_m);\n wfo.setTotalFrameCount(totalFrames_m); wfo.setFrameLength(message.data.length());\n callback_mp->onError(wfo);\n increasConseqErrorCount();\n }\/\/if-else\n break;\n }\/\/\tcase ACSBulkData::BD_PARAM:\n case ACSBulkData::BD_DATA:\n {\n if (currentState_m==DataRcvState)\n {\n if (dataLength_m==0) \/\/ we get the first data frame\n {\n std::cout << \" ************************* New sendData @ \" << topicName_m << \" *******************************\" << std::endl;\n start_time = ACE_OS::gettimeofday();\n totalFrames_m = message.restDataLength+1;\n frameCounter_m = 0;\n }\/\/if\n\n dataLength_m += message.data.length();\n frameCounter_m ++;\n\n if ( message.restDataLength>0)\n {\n if (nextFrame_m!=0 && nextFrame_m!=message.restDataLength) \/\/ do we miss a frame ?\n {\n FrameLostCompletion lde(__FILE__, __LINE__, __FUNCTION__);\n lde.setNextDataFrame(nextFrame_m);\n lde.setFrameCount(frameCounter_m);\n lde.setRestFrames(message.restDataLength);\n lde.setFrameLength(message.data.length());\n lde.setFlow(topicName_m.c_str());\n callback_mp->onError(lde);\n increasConseqErrorCount();\n return; \/\/ ??\n }\n nextFrame_m = message.restDataLength-1;\n }\n else \/\/message.restDataLength==0 what means we got the last frame\n {\n ACE_Time_Value elapsed_time = ACE_OS::gettimeofday() - start_time;\n cout <<\ttopicName_m << \" Received all data from sendData: \" << dataLength_m << \" Bytes in \";\n cout <<(elapsed_time.sec()+( elapsed_time.usec() \/ 1000000.0 ));\n cout << \"secs. => Rate: \";\n cout << ((dataLength_m\/(1024.0*1024.0))\/(elapsed_time.sec()+( elapsed_time.usec() \/ 1000000.0 ))) << \"MBytes\/sec\" << endl;\n\n DDS::SampleLostStatus s;\n reader->get_sample_lost_status(s);\n cerr << topicName_m << \" LOST samples: \\t\\t total_count: \" << s.total_count << \" total_count_change: \" << s.total_count_change << endl;\n dataLength_m = 0;\n }\n\n cbReceiveStartTime_m = ACE_OS::gettimeofday();\n message.data.to_array(tmpArray, message.data.length());\n BDNT_READER_LISTENER_USER_ERR( callback_mp->cbReceive(tmpArray, message.data.length()) )\n conseqErrorCount_m=0;\n cbReceiveElapsedTime_m = ACE_OS::gettimeofday() - cbReceiveStartTime_m;\n cbReceiveElapsedTimeSec_m = cbReceiveElapsedTime_m.sec() + (cbReceiveElapsedTime_m.usec() \/ 1000000.0);\n if (cbReceiveElapsedTimeSec_m>cbReceiveTimeoutSec_m)\n {\n \t CBReceiveProcessTimeoutCompletion cbReceiveTO(__FILE__, __LINE__, __FUNCTION__);\n \t cbReceiveTO.setProcessTimeoutSec(cbReceiveTimeoutSec_m);\n \t cbReceiveTO.setActaullProcessTime(cbReceiveElapsedTimeSec_m);\n \t callback_mp->onError(cbReceiveTO);\n \t \/\/TBD should we increase error counter here or not ?\n }\/\/if cbReceiveTimeoutSec_m\n }\n else \/\/error\n {\n WrongFrameOrderCompletion wfo(__FILE__, __LINE__, __FUNCTION__);\n wfo.setDataType(\"BD_DATA\"); wfo.setState(currentState_m);\n wfo.setFlow(topicName_m.c_str()); wfo.setFrameCount(frameCounter_m);\n wfo.setTotalFrameCount(totalFrames_m); wfo.setFrameLength(message.data.length());\n callback_mp->onError(wfo);\n increasConseqErrorCount();\n }\n break;\n }\/\/case ACSBulkData::BD_DATA\n case ACSBulkData::BD_STOP:\n {\n if (currentState_m==DataRcvState)\n {\n currentState_m = StopState;\n cout <<\ttopicName_m << \" Received sendStop\" << endl;\n cout << \"===============================================================\" << endl;\n if (frameCounter_m==0)\n {\n ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,\n (LM_WARNING, \"On %s got stop (BD_STOP) before any data (sendData)!\",\n topicName_m.c_str()));\n }else\n {\n if (frameCounter_m != totalFrames_m)\n {\n ACS_BD_Errors::FrameLostCompletion lde(__FILE__, __LINE__, __FUNCTION__);\n lde.setNextDataFrame(nextFrame_m);\n lde.setFrameCount(frameCounter_m);\n lde.setRestFrames(message.restDataLength); \/\/ should be ??\n lde.setFrameLength(message.data.length()); \/\/ should be 0\n lde.setFlow(topicName_m.c_str());\n callback_mp->onError(lde);\n increasConseqErrorCount();\n }\/\/if\n }\/\/if-else\n }else\n {\n if (currentState_m==StopState)\n {\n ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,\n (LM_WARNING, \"On %s stop (BD_STOP) arrived in stop state - will be ignored!\",\n topicName_m.c_str()));\n }\n else \/\/StartState\n {\n ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,\n (LM_WARNING, \"On %s stop (BD_STOP) arrived in start state: no parameter data (startSend) has arrived!\",\n topicName_m.c_str()));\n }\/\/if-else\n }\n \/\/ in all above warning\/error case we call user's cbStop()\n BDNT_READER_LISTENER_USER_ERR( callback_mp->cbStop() )\n conseqErrorCount_m=0;\n break;\n }\/\/case ACSBulkData::BD_STOP\n default:\n conseqErrorCount_m++;\n UnknownDataTypeCompletion udt(__FILE__, __LINE__, __FUNCTION__);\n udt.setDataType(message.dataType);\n udt.setFrameCount(frameCounter_m);\n udt.setTotalFrameCount(totalFrames_m);\n callback_mp->onError(udt);\n }\/\/switch\n }\/\/if(si.valid_data)\n }\n else\n {\n conseqErrorCount_m++;\n DDSReturnErrorCompletion retErr(__FILE__, __LINE__, __FUNCTION__);\n retErr.setRetCode(retCode); \/\/would be good if we can give also string value\n callback_mp->onError(retErr);\n }\/\/if(retCode)\n }\/\/while\n}\/\/on_data_available\n\nvoid BulkDataNTReaderListener::on_requested_deadline_missed(DDS::DataReader*, const DDS::RequestedDeadlineMissedStatus& )\n{\n ACS_DDS_Errors::DDSDeadlineMissedCompletion dmerr(__FILE__, __LINE__, __FUNCTION__);\n initalizeLogging(); \/\/force initialization of logging sys TBD changed\n callback_mp->onError(dmerr);\n}\/\/on_requested_deadline_missed\n\nvoid BulkDataNTReaderListener::on_requested_incompatible_qos(DDS::DataReader*, const DDS::RequestedIncompatibleQosStatus&)\n{\n ACS_DDS_Errors::DDSIncompatibleQoSCompletion iqerr(__FILE__, __LINE__, __FUNCTION__);\n initalizeLogging(); \/\/force initialization of logging sys TBD changed\n callback_mp->onError(iqerr);\n}\/\/on_requested_incompatible_qos\n\nvoid BulkDataNTReaderListener::on_liveliness_changed(DDS::DataReader*, const DDS::LivelinessChangedStatus& lcs)\n{\n if (lcs.alive_count_change>0)\n {\n for(int i=0; igetFlowName(), callback_mp->getStreamName(),\n lcs.alive_count));\n BDNT_READER_LISTENER_USER_ERR( callback_mp->onSenderConnect() )\n }\/\/for\n }else\n {\n for(int i=lcs.alive_count_change; i<0; i++)\n {\n ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,\n (LM_INFO, \"A sender has disconnected to flow: %s of the stream: %s. Total alive connection(s): %d\",\n callback_mp->getFlowName(), callback_mp->getStreamName(),\n lcs.alive_count));\n BDNT_READER_LISTENER_USER_ERR( callback_mp->onSenderDisconnect() )\n }\/\/for\n }\/\/if-else\n}\/\/on_liveliness_changed\n\nvoid BulkDataNTReaderListener::on_subscription_matched(DDS::DataReader*, const DDS::SubscriptionMatchedStatus&)\n{\n ACS_TRACE(__FUNCTION__);\n}\/\/on_subscription_matched\n\nvoid BulkDataNTReaderListener::on_sample_rejected( DDS::DataReader*, const DDS::SampleRejectedStatus& srs)\n{\n ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,\n (LM_WARNING, \"Sample Rejected: reason %d, change: %d, total: %d!\",\n srs.last_reason, srs.total_count_change, srs.total_count));\n}\/\/on_sample_rejected\n\nvoid BulkDataNTReaderListener::on_sample_lost(DDS::DataReader*, const DDS::SampleLostStatus& s)\n{\n ACS_BD_Errors::SampleLostCompletion sle(__FILE__, __LINE__, __FUNCTION__);\n sle.setLostSamples(s.total_count_change);\n sle.setNextDataFrame(nextFrame_m);\n sle.setFrameCount(frameCounter_m);\n sle.setFlow(topicName_m.c_str());\n initalizeLogging(); \/\/force initialization of logging sys TBD changed\n callback_mp->onError(sle);\n}\/\/on_sample_lost\n\nvoid BulkDataNTReaderListener::increasConseqErrorCount()\n{\n conseqErrorCount_m++;\n if (conseqErrorCount_m>=maxConseqErrorCount_m)\n {\n\n ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,\n (LM_ALERT, \"Too many consequent errors: %d\/%d on %s\",\n conseqErrorCount_m, maxConseqErrorCount_m, topicName_m.c_str()));\n \/\/TBD: disconnect\n }\n}\/\/increasConseqErroCount\n\nset FlowName to CBReceiveProcessTimeoutCompletion\/*******************************************************************************\n * ALMA - Atacama Large Millimiter Array\n * (c) European Southern Observatory, 2011\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * \"@(#) $Id: bulkDataNTReaderListener.cpp,v 1.35 2011\/12\/22 16:05:45 bjeram Exp $\"\n *\n * who when what\n * -------- -------- ----------------------------------------------\n * bjeram 2011-04-19 created\n *\/\n\n#include \"bulkDataNTReaderListener.h\"\n#include \"ACS_BD_Errors.h\"\n#include \n#include \n#include \n#include \n\nusing namespace ACS_BD_Errors;\nusing namespace ACS_DDS_Errors;\nusing namespace AcsBulkdata;\nusing namespace std;\n\n#define BDNT_READER_LISTENER_USER_ERR(call)\t\t \t\t\t\t\t\t\t\t\\\n try { call; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n }catch(const ACSErr::ACSbaseExImpl &ex){\t\t\t\t\t\t\t\t\t\t\\\n UserCallbackErrorCompletion ucb(ex, __FILE__, __LINE__, __FUNCTION__);\t\t\\\n ucb.setCall(\"#call\");\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n callback_mp->onError(ucb);\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n }catch(const std::exception &stdex){\t\t\t\t\t\t\t\t\t\t\t\\\n ACSErrTypeCommon::StdExceptionExImpl ex(__FILE__, __LINE__, __FUNCTION__); \\\n ex.setWhat(stdex.what());\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n UserCallbackErrorCompletion ucb(ex, __FILE__, __LINE__, __FUNCTION__);\t\t\\\n ucb.setCall(\"#call\");\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n callback_mp->onError(ucb);\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n }catch(...){\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n ACSErrTypeCommon::UnknownExImpl ex(__FILE__, __LINE__, __FUNCTION__); \t\\\n UserCallbackErrorCompletion ucb(ex, __FILE__, __LINE__, __FUNCTION__);\t\t\\\n ucb.setCall(\"#call\");\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n callback_mp->onError(ucb);\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n }\n\n\nBulkDataNTReaderListener::BulkDataNTReaderListener(const char* name, BulkDataNTCallback* cb)\n: BulkDataNTDDSLoggable(\"BulkDataNT:\"+string(name)),\n currentState_m(StartState),\n topicName_m(name),\n dataLength_m(0),\n frameCounter_m(0),\n totalFrames_m(0),\n callback_mp (cb)\n{\n ACS_TRACE(__FUNCTION__);\n nextFrame_m=0;\n frameDataReader_mp=0;\n conseqErrorCount_m=0;\n maxConseqErrorCount_m = 4; \/\/TBD now hardcoded, to be get from somewhere else\n cbReceiveTimeoutSec_m = callback_mp->getCBReceiveProcessTimeout();\n}\/\/BulkDataNTReaderListener\n\n\nBulkDataNTReaderListener::~BulkDataNTReaderListener ()\n{\n ACS_TRACE(__FUNCTION__);\n}\/\/~BulkDataNTReaderListener\n\nvoid BulkDataNTReaderListener::on_data_available(DDS::DataReader* reader)\n{\n DDS::ReturnCode_t retCode;\n DDS::SampleInfo si ;\n ACSBulkData::BulkDataNTFrame message;\n unsigned char tmpArray[ACSBulkData::FRAME_MAX_LEN];\n\n initalizeLogging(); \/\/force initialization of logging sys TBD changed\n\n if (frameDataReader_mp==NULL)\n {\n frameDataReader_mp = ACSBulkData::BulkDataNTFrameDataReader::narrow(reader);\n if ( frameDataReader_mp==NULL) {\n ACS_DDS_Errors::DDSNarrowFailedCompletion nerr(__FILE__, __LINE__, __FUNCTION__);\n nerr.setVariable(\"frameDataReader_mp\");\n nerr.setNarrowType(\"ACSBulkData::BulkDataNTFrameDataReader\");\n callback_mp->onError(nerr);\n return;\n }\/\/if\n }\/\/if\n\n message.data.maximum(ACSBulkData::FRAME_MAX_LEN); \/\/TBD constant from\n while (\t(retCode = frameDataReader_mp->take_next_sample(message, si)) != DDS::RETCODE_NO_DATA )\n {\n if (retCode == DDS::RETCODE_OK)\n {\n if (si.valid_data == true)\n {\n switch(message.dataType)\n {\n case ACSBulkData::BD_PARAM:\n {\n cout << topicName_m << \" startSend: parameter size: \" << message.data.length() << endl;\n if (currentState_m==StartState || currentState_m==StopState)\n {\n dataLength_m = 0;\n frameCounter_m = 0;\n currentState_m = DataRcvState;\n message.data.to_array(tmpArray, message.data.length());\n BDNT_READER_LISTENER_USER_ERR( callback_mp->cbStart(tmpArray, message.data.length()) )\n conseqErrorCount_m=0;\n }\n else \/\/error\n {\n WrongFrameOrderCompletion wfo(__FILE__, __LINE__, __FUNCTION__);\n wfo.setDataType(\"BD_PARAM\"); wfo.setState(currentState_m);\n wfo.setFlow(topicName_m.c_str()); wfo.setFrameCount(frameCounter_m);\n wfo.setTotalFrameCount(totalFrames_m); wfo.setFrameLength(message.data.length());\n callback_mp->onError(wfo);\n increasConseqErrorCount();\n }\/\/if-else\n break;\n }\/\/\tcase ACSBulkData::BD_PARAM:\n case ACSBulkData::BD_DATA:\n {\n if (currentState_m==DataRcvState)\n {\n if (dataLength_m==0) \/\/ we get the first data frame\n {\n std::cout << \" ************************* New sendData @ \" << topicName_m << \" *******************************\" << std::endl;\n start_time = ACE_OS::gettimeofday();\n totalFrames_m = message.restDataLength+1;\n frameCounter_m = 0;\n }\/\/if\n\n dataLength_m += message.data.length();\n frameCounter_m ++;\n\n if ( message.restDataLength>0)\n {\n if (nextFrame_m!=0 && nextFrame_m!=message.restDataLength) \/\/ do we miss a frame ?\n {\n FrameLostCompletion lde(__FILE__, __LINE__, __FUNCTION__);\n lde.setNextDataFrame(nextFrame_m);\n lde.setFrameCount(frameCounter_m);\n lde.setRestFrames(message.restDataLength);\n lde.setFrameLength(message.data.length());\n lde.setFlow(topicName_m.c_str());\n callback_mp->onError(lde);\n increasConseqErrorCount();\n return; \/\/ ??\n }\n nextFrame_m = message.restDataLength-1;\n }\n else \/\/message.restDataLength==0 what means we got the last frame\n {\n ACE_Time_Value elapsed_time = ACE_OS::gettimeofday() - start_time;\n cout <<\ttopicName_m << \" Received all data from sendData: \" << dataLength_m << \" Bytes in \";\n cout <<(elapsed_time.sec()+( elapsed_time.usec() \/ 1000000.0 ));\n cout << \"secs. => Rate: \";\n cout << ((dataLength_m\/(1024.0*1024.0))\/(elapsed_time.sec()+( elapsed_time.usec() \/ 1000000.0 ))) << \"MBytes\/sec\" << endl;\n\n DDS::SampleLostStatus s;\n reader->get_sample_lost_status(s);\n cerr << topicName_m << \" LOST samples: \\t\\t total_count: \" << s.total_count << \" total_count_change: \" << s.total_count_change << endl;\n dataLength_m = 0;\n }\n\n cbReceiveStartTime_m = ACE_OS::gettimeofday();\n message.data.to_array(tmpArray, message.data.length());\n BDNT_READER_LISTENER_USER_ERR( callback_mp->cbReceive(tmpArray, message.data.length()) )\n conseqErrorCount_m=0;\n cbReceiveElapsedTime_m = ACE_OS::gettimeofday() - cbReceiveStartTime_m;\n cbReceiveElapsedTimeSec_m = cbReceiveElapsedTime_m.sec() + (cbReceiveElapsedTime_m.usec() \/ 1000000.0);\n if (cbReceiveElapsedTimeSec_m>cbReceiveTimeoutSec_m)\n {\n \t CBReceiveProcessTimeoutCompletion cbReceiveTO(__FILE__, __LINE__, __FUNCTION__);\n \t cbReceiveTO.setFlowName(topicName_m.c_str());\n \t cbReceiveTO.setProcessTimeoutSec(cbReceiveTimeoutSec_m);\n \t cbReceiveTO.setActaullProcessTime(cbReceiveElapsedTimeSec_m);\n \t callback_mp->onError(cbReceiveTO);\n \t \/\/TBD should we increase error counter here or not ?\n }\/\/if cbReceiveTimeoutSec_m\n }\n else \/\/error\n {\n WrongFrameOrderCompletion wfo(__FILE__, __LINE__, __FUNCTION__);\n wfo.setDataType(\"BD_DATA\"); wfo.setState(currentState_m);\n wfo.setFlow(topicName_m.c_str()); wfo.setFrameCount(frameCounter_m);\n wfo.setTotalFrameCount(totalFrames_m); wfo.setFrameLength(message.data.length());\n callback_mp->onError(wfo);\n increasConseqErrorCount();\n }\n break;\n }\/\/case ACSBulkData::BD_DATA\n case ACSBulkData::BD_STOP:\n {\n if (currentState_m==DataRcvState)\n {\n currentState_m = StopState;\n cout <<\ttopicName_m << \" Received sendStop\" << endl;\n cout << \"===============================================================\" << endl;\n if (frameCounter_m==0)\n {\n ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,\n (LM_WARNING, \"On %s got stop (BD_STOP) before any data (sendData)!\",\n topicName_m.c_str()));\n }else\n {\n if (frameCounter_m != totalFrames_m)\n {\n ACS_BD_Errors::FrameLostCompletion lde(__FILE__, __LINE__, __FUNCTION__);\n lde.setNextDataFrame(nextFrame_m);\n lde.setFrameCount(frameCounter_m);\n lde.setRestFrames(message.restDataLength); \/\/ should be ??\n lde.setFrameLength(message.data.length()); \/\/ should be 0\n lde.setFlow(topicName_m.c_str());\n callback_mp->onError(lde);\n increasConseqErrorCount();\n }\/\/if\n }\/\/if-else\n }else\n {\n if (currentState_m==StopState)\n {\n ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,\n (LM_WARNING, \"On %s stop (BD_STOP) arrived in stop state - will be ignored!\",\n topicName_m.c_str()));\n }\n else \/\/StartState\n {\n ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,\n (LM_WARNING, \"On %s stop (BD_STOP) arrived in start state: no parameter data (startSend) has arrived!\",\n topicName_m.c_str()));\n }\/\/if-else\n }\n \/\/ in all above warning\/error case we call user's cbStop()\n BDNT_READER_LISTENER_USER_ERR( callback_mp->cbStop() )\n conseqErrorCount_m=0;\n break;\n }\/\/case ACSBulkData::BD_STOP\n default:\n conseqErrorCount_m++;\n UnknownDataTypeCompletion udt(__FILE__, __LINE__, __FUNCTION__);\n udt.setDataType(message.dataType);\n udt.setFrameCount(frameCounter_m);\n udt.setTotalFrameCount(totalFrames_m);\n callback_mp->onError(udt);\n }\/\/switch\n }\/\/if(si.valid_data)\n }\n else\n {\n conseqErrorCount_m++;\n DDSReturnErrorCompletion retErr(__FILE__, __LINE__, __FUNCTION__);\n retErr.setRetCode(retCode); \/\/would be good if we can give also string value\n callback_mp->onError(retErr);\n }\/\/if(retCode)\n }\/\/while\n}\/\/on_data_available\n\nvoid BulkDataNTReaderListener::on_requested_deadline_missed(DDS::DataReader*, const DDS::RequestedDeadlineMissedStatus& )\n{\n ACS_DDS_Errors::DDSDeadlineMissedCompletion dmerr(__FILE__, __LINE__, __FUNCTION__);\n initalizeLogging(); \/\/force initialization of logging sys TBD changed\n callback_mp->onError(dmerr);\n}\/\/on_requested_deadline_missed\n\nvoid BulkDataNTReaderListener::on_requested_incompatible_qos(DDS::DataReader*, const DDS::RequestedIncompatibleQosStatus&)\n{\n ACS_DDS_Errors::DDSIncompatibleQoSCompletion iqerr(__FILE__, __LINE__, __FUNCTION__);\n initalizeLogging(); \/\/force initialization of logging sys TBD changed\n callback_mp->onError(iqerr);\n}\/\/on_requested_incompatible_qos\n\nvoid BulkDataNTReaderListener::on_liveliness_changed(DDS::DataReader*, const DDS::LivelinessChangedStatus& lcs)\n{\n if (lcs.alive_count_change>0)\n {\n for(int i=0; igetFlowName(), callback_mp->getStreamName(),\n lcs.alive_count));\n BDNT_READER_LISTENER_USER_ERR( callback_mp->onSenderConnect() )\n }\/\/for\n }else\n {\n for(int i=lcs.alive_count_change; i<0; i++)\n {\n ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,\n (LM_INFO, \"A sender has disconnected to flow: %s of the stream: %s. Total alive connection(s): %d\",\n callback_mp->getFlowName(), callback_mp->getStreamName(),\n lcs.alive_count));\n BDNT_READER_LISTENER_USER_ERR( callback_mp->onSenderDisconnect() )\n }\/\/for\n }\/\/if-else\n}\/\/on_liveliness_changed\n\nvoid BulkDataNTReaderListener::on_subscription_matched(DDS::DataReader*, const DDS::SubscriptionMatchedStatus&)\n{\n ACS_TRACE(__FUNCTION__);\n}\/\/on_subscription_matched\n\nvoid BulkDataNTReaderListener::on_sample_rejected( DDS::DataReader*, const DDS::SampleRejectedStatus& srs)\n{\n ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,\n (LM_WARNING, \"Sample Rejected: reason %d, change: %d, total: %d!\",\n srs.last_reason, srs.total_count_change, srs.total_count));\n}\/\/on_sample_rejected\n\nvoid BulkDataNTReaderListener::on_sample_lost(DDS::DataReader*, const DDS::SampleLostStatus& s)\n{\n ACS_BD_Errors::SampleLostCompletion sle(__FILE__, __LINE__, __FUNCTION__);\n sle.setLostSamples(s.total_count_change);\n sle.setNextDataFrame(nextFrame_m);\n sle.setFrameCount(frameCounter_m);\n sle.setFlow(topicName_m.c_str());\n initalizeLogging(); \/\/force initialization of logging sys TBD changed\n callback_mp->onError(sle);\n}\/\/on_sample_lost\n\nvoid BulkDataNTReaderListener::increasConseqErrorCount()\n{\n conseqErrorCount_m++;\n if (conseqErrorCount_m>=maxConseqErrorCount_m)\n {\n\n ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,\n (LM_ALERT, \"Too many consequent errors: %d\/%d on %s\",\n conseqErrorCount_m, maxConseqErrorCount_m, topicName_m.c_str()));\n \/\/TBD: disconnect\n }\n}\/\/increasConseqErroCount\n\n<|endoftext|>"} {"text":"Update DepthBuffer.cpp<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include \"..\/IO\/FileAccessException.h\"\n\n#include \"Exceptions.h\"\n\n#include \"ErrNoException.h\"\n\nusing namespace Stroika;\nusing namespace Stroika::Foundation;\n\nusing namespace Characters;\nusing namespace Execution;\n\nusing Debug::TraceContextBumper;\n\n\/*\n ********************************************************************************\n ***************************** errno_ErrorException *****************************\n ********************************************************************************\n *\/\nerrno_ErrorException::errno_ErrorException (Execution::errno_t e)\n : StringException (SDKString2Wide (LookupMessage (e)))\n , fError (e)\n{\n}\n\nSDKString errno_ErrorException::LookupMessage (Execution::errno_t e)\n{\n SDKString justErrnoNumberMessage;\n {\n SDKChar justNumBuf[2048];\n justNumBuf[0] = '\\0';\n#if qPlatform_Windows\n (void)::_stprintf_s (justNumBuf, SDKSTR (\"errno: %d\"), e);\n#else\n (void)::snprintf (justNumBuf, NEltsOf (justNumBuf), SDKSTR (\"errno: %d\"), e);\n#endif\n justErrnoNumberMessage = justNumBuf;\n }\n SDKChar buf[2048];\n buf[0] = '\\0';\n#if qPlatform_Windows\n if (::_tcserror_s (buf, e) == 0) {\n return buf + SDKString (SDKSTR (\" (\") + justErrnoNumberMessage + SDKSTR (\")\"));\n }\n#elif qPlatform_POSIX\n\/*\n * A bit quirky - gcc and POSIX handle this API fairly differently.\n * https:\/\/linux.die.net\/man\/3\/strerror_r - in one case returns int and 0 means worked, and other case 0 means didnt work\n *\/\n#if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE\n \/\/ The XSI-compliant strerror_r() function returns 0 on success\n if (::strerror_r (e, buf, NEltsOf (buf)) == 0) {\n return buf + SDKString (SDKSTR (\" (\") + justErrnoNumberMessage + SDKSTR (\")\"));\n }\n#else\n \/\/ The strerror() and the GNU-specific strerror_r() functions return the appropriate error description string\n (void)::strerror_r (e, buf, NEltsOf (buf));\n return buf + SDKString (SDKSTR (\" (\") + justErrnoNumberMessage + SDKSTR (\")\"));\n#endif\n#else\n AssertNotImplemented ();\n#endif\n return justErrnoNumberMessage;\n}\n\n[[noreturn]] void errno_ErrorException::Throw (Execution::errno_t error)\n{\n \/\/REVIEW EXCPETIONS ANMD MPAPING - THIS IS NOT GOOD - NOT EVEN CLOSE!!! -- LGP 2011-09-29\n switch (error) {\n case ENOMEM: {\n Execution::Throw (bad_alloc (), \"errno_ErrorException::Throw (ENOMEM) - throwing bad_alloc\");\n }\n case ENOENT: {\n Execution::Throw (IO::FileAccessException ()); \/\/ don't know if they were reading or writing at this level..., and don't know file name...\n }\n case EACCES: {\n Execution::Throw (IO::FileAccessException ()); \/\/ don't know if they were reading or writing at this level..., and don't know file name...\n }\n\/\/ If I decide to pursue mapping, this maybe a good place to start\n\/\/ http:\/\/aplawrence.com\/Unixart\/errors.html\n\/\/ -- LGP 2009-01-02\n#if 0\n case EPERM: {\n \/\/ not sure any point in this unification. Maybe if I added my OWN private 'access denied' exception\n \/\/ the mapping\/unification would make sense.\n \/\/ -- LGP 2009-01-02\n DbgTrace (\"errno_ErrorException::Throw (EPERM) - throwing ERROR_ACCESS_DENIED\");\n throw Win32Exception (ERROR_ACCESS_DENIED);\n }\n#endif\n }\n DbgTrace (L\"errno_ErrorException::Throw (%d) - throwing errno_ErrorException '%s'\", error, SDKString2Wide (LookupMessage (error)).c_str ());\n throw errno_ErrorException (error);\n}\nfixed another bug with Execution\/ErrNoException - using GNU verison of strerror_r\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include \"..\/IO\/FileAccessException.h\"\n\n#include \"Exceptions.h\"\n\n#include \"ErrNoException.h\"\n\nusing namespace Stroika;\nusing namespace Stroika::Foundation;\n\nusing namespace Characters;\nusing namespace Execution;\n\nusing Debug::TraceContextBumper;\n\n\/*\n ********************************************************************************\n ***************************** errno_ErrorException *****************************\n ********************************************************************************\n *\/\nerrno_ErrorException::errno_ErrorException (Execution::errno_t e)\n : StringException (SDKString2Wide (LookupMessage (e)))\n , fError (e)\n{\n}\n\nSDKString errno_ErrorException::LookupMessage (Execution::errno_t e)\n{\n SDKString justErrnoNumberMessage;\n {\n SDKChar justNumBuf[2048];\n justNumBuf[0] = '\\0';\n#if qPlatform_Windows\n (void)::_stprintf_s (justNumBuf, SDKSTR (\"errno: %d\"), e);\n#else\n (void)::snprintf (justNumBuf, NEltsOf (justNumBuf), SDKSTR (\"errno: %d\"), e);\n#endif\n justErrnoNumberMessage = justNumBuf;\n }\n SDKChar buf[2048];\n buf[0] = '\\0';\n#if qPlatform_Windows\n if (::_tcserror_s (buf, e) == 0) {\n return buf + SDKString (SDKSTR (\" (\") + justErrnoNumberMessage + SDKSTR (\")\"));\n }\n#elif qPlatform_POSIX\n\/*\n * A bit quirky - gcc and POSIX handle this API fairly differently.\n * https:\/\/linux.die.net\/man\/3\/strerror_r - in one case returns int and 0 means worked, and other case 0 means didnt work\n *\/\n#if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE\n \/\/ The XSI-compliant strerror_r() function returns 0 on success\n if (::strerror_r (e, buf, NEltsOf (buf)) == 0) {\n return buf + SDKString (SDKSTR (\" (\") + justErrnoNumberMessage + SDKSTR (\")\"));\n }\n#else\n \/\/ the GNU-specific strerror_r() functions return the appropriate error description string\n return ::strerror_r (e, buf, NEltsOf (buf)) + SDKString (SDKSTR (\" (\") + justErrnoNumberMessage + SDKSTR (\")\"));\n#endif\n#else\n AssertNotImplemented ();\n#endif\n return justErrnoNumberMessage;\n}\n\n[[noreturn]] void errno_ErrorException::Throw (Execution::errno_t error)\n{\n \/\/REVIEW EXCPETIONS ANMD MPAPING - THIS IS NOT GOOD - NOT EVEN CLOSE!!! -- LGP 2011-09-29\n switch (error) {\n case ENOMEM: {\n Execution::Throw (bad_alloc (), \"errno_ErrorException::Throw (ENOMEM) - throwing bad_alloc\");\n }\n case ENOENT: {\n Execution::Throw (IO::FileAccessException ()); \/\/ don't know if they were reading or writing at this level..., and don't know file name...\n }\n case EACCES: {\n Execution::Throw (IO::FileAccessException ()); \/\/ don't know if they were reading or writing at this level..., and don't know file name...\n }\n\/\/ If I decide to pursue mapping, this maybe a good place to start\n\/\/ http:\/\/aplawrence.com\/Unixart\/errors.html\n\/\/ -- LGP 2009-01-02\n#if 0\n case EPERM: {\n \/\/ not sure any point in this unification. Maybe if I added my OWN private 'access denied' exception\n \/\/ the mapping\/unification would make sense.\n \/\/ -- LGP 2009-01-02\n DbgTrace (\"errno_ErrorException::Throw (EPERM) - throwing ERROR_ACCESS_DENIED\");\n throw Win32Exception (ERROR_ACCESS_DENIED);\n }\n#endif\n }\n DbgTrace (L\"errno_ErrorException::Throw (%d) - throwing errno_ErrorException '%s'\", error, SDKString2Wide (LookupMessage (error)).c_str ());\n throw errno_ErrorException (error);\n}\n<|endoftext|>"} {"text":"#include \"stan\/math\/functions\/fma.hpp\"\r\n#include \r\n\r\nTEST(MathFunctions, fma) {\r\n using stan::math::fma;\r\n \r\n EXPECT_FLOAT_EQ(5.0, fma(1.0,2.0,3.0));\r\n EXPECT_FLOAT_EQ(10.0, fma(2.0,3.0,4.0));\r\n}\r\n\r\nadded NaN test for fma#include \n#include \n#include \n\nTEST(MathFunctions, fma) {\n using stan::math::fma;\n \n EXPECT_FLOAT_EQ(5.0, fma(1.0,2.0,3.0));\n EXPECT_FLOAT_EQ(10.0, fma(2.0,3.0,4.0));\n}\n\nTEST(MathFunctions, fma_nan) {\n double nan = std::numeric_limits::quiet_NaN();\n \n EXPECT_PRED1(boost::math::isnan,\n stan::math::fma(1.0, 2.0, nan));\n\n EXPECT_PRED1(boost::math::isnan,\n stan::math::fma(1.0, nan, 3.0));\n\n EXPECT_PRED1(boost::math::isnan,\n stan::math::fma(1.0, nan, nan));\n\n EXPECT_PRED1(boost::math::isnan,\n stan::math::fma(nan, 2.0, 3.0));\n\n EXPECT_PRED1(boost::math::isnan,\n stan::math::fma(nan, 2.0, nan));\n\n EXPECT_PRED1(boost::math::isnan,\n stan::math::fma(nan, nan, 3.0));\n\n EXPECT_PRED1(boost::math::isnan,\n stan::math::fma(nan, nan, nan));\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *\n* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This library is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This library is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this library; if not, write to the Free Software Foundation, *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Modules *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n\/\/ Author: Hadrien Courtecuisse\n\/\/\n\/\/ Copyright: See COPYING file that comes with this distribution\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace linearsolver\n{\n\nusing namespace sofa::defaulttype;\nusing namespace sofa::core::behavior;\nusing namespace sofa::simulation;\nusing namespace sofa::core::objectmodel;\nusing sofa::helper::system::thread::CTime;\nusing sofa::helper::system::thread::ctime_t;\nusing std::cerr;\nusing std::endl;\n\ntemplate\nShewchukPCGLinearSolver::ShewchukPCGLinearSolver()\n : f_maxIter( initData(&f_maxIter,(unsigned)25,\"iterations\",\"maximum number of iterations of the Conjugate Gradient solution\") )\n , f_tolerance( initData(&f_tolerance,1e-5,\"tolerance\",\"desired precision of the Conjugate Gradient Solution (ratio of current residual norm over initial residual norm)\") )\n , f_verbose( initData(&f_verbose,false,\"verbose\",\"Dump system state at each iteration\") )\n , f_update_iteration( initData(&f_update_iteration,(unsigned)0,\"update_iteration\",\"Number of CG iterations before next refresh of precondtioner\") )\n , f_update_step( initData(&f_update_step,(unsigned)1,\"update_step\",\"Number of steps before the next refresh of precondtioners\") )\n , f_use_precond( initData(&f_use_precond,true,\"use_precond\",\"Use preconditioners\") )\n , f_preconditioners( initData(&f_preconditioners, \"preconditioners\", \"If not empty: path to the solvers to use as preconditioners\") )\n , f_graph( initData(&f_graph,\"graph\",\"Graph of residuals at each iteration\") )\n{\n f_graph.setWidget(\"graph\");\n\/\/ f_graph.setReadOnly(true);\n usePrecond = true;\n first = true;\n}\n\ntemplate\nvoid ShewchukPCGLinearSolver::init()\n{\n std::vector solvers;\n BaseContext * c = this->getContext();\n\n const helper::vector& precondNames = f_preconditioners.getValue();\n if (precondNames.empty() && f_use_precond.getValue())\n {\n c->get(&solvers,BaseContext::SearchDown);\n }\n else\n {\n for (unsigned int i=0; iget(s, precondNames[i]);\n if (s) solvers.push_back(s);\n else serr << \"Solver \\\"\" << precondNames[i] << \"\\\" not found.\" << sendl;\n }\n }\n\n for (unsigned int i=0; ipreconditioners.push_back(solvers[i]);\n }\n }\n\n sout<<\"Found \" << this->preconditioners.size() << \" preconditioners\"<\nvoid ShewchukPCGLinearSolver::setSystemMBKMatrix(double mFact, double bFact, double kFact)\n{\n sofa::helper::AdvancedTimer::valSet(\"PCG::buildMBK\", 1);\n sofa::helper::AdvancedTimer::stepBegin(\"PCG::setSystemMBKMatrix\");\n\n Inherit::setSystemMBKMatrix(mFact,bFact,kFact);\n\n sofa::helper::AdvancedTimer::stepEnd(\"PCG::setSystemMBKMatrix(Precond)\");\n\n if (preconditioners.size()==0) return;\n\n if (first) \/\/We initialize all the preconditioners for the first step\n {\n for (unsigned int i=0; ipreconditioners.size(); ++i)\n {\n preconditioners[i]->setSystemMBKMatrix(mFact,bFact,kFact);\n }\n first = false;\n next_refresh_iteration = 1;\n next_refresh_step = 1;\n }\n else if (f_use_precond.getValue()) \/\/ We use only the first precond in the list\n {\n sofa::helper::AdvancedTimer::valSet(\"PCG::PrecondBuildMBK\", 1);\n sofa::helper::AdvancedTimer::stepBegin(\"PCG::PrecondSetSystemMBKMatrix\");\n\n if (f_update_step.getValue()>0)\n {\n if (next_refresh_step>=f_update_step.getValue())\n {\n preconditioners[0]->setSystemMBKMatrix(mFact,bFact,kFact);\n next_refresh_step=1;\n }\n else\n {\n next_refresh_step++;\n }\n }\n else if (f_update_iteration.getValue()>0)\n {\n if (next_refresh_iteration>=f_update_iteration.getValue())\n {\n preconditioners[0]->setSystemMBKMatrix(mFact,bFact,kFact);\n next_refresh_iteration=1;\n }\n }\n sofa::helper::AdvancedTimer::stepEnd(\"PCG::PrecondSetSystemMBKMatrix\");\n }\n\n\n}\n\ntemplate<>\ninline void ShewchukPCGLinearSolver::cgstep_beta(Vector& p, Vector& r, double beta)\n{\n this->v_op(p,r,p,beta); \/\/ p = p*beta + r\n}\n\ntemplate<>\ninline void ShewchukPCGLinearSolver::cgstep_alpha(Vector& x, Vector& p, double alpha)\n{\n x.peq(p,alpha); \/\/ x = x + alpha p\n}\n\ntemplate\nvoid ShewchukPCGLinearSolver::solve (Matrix& M, Vector& x, Vector& b)\n{\n sofa::helper::AdvancedTimer::stepBegin(\"PCGLinearSolver::solve\");\n\n Vector& r = *this->createVector();\n Vector& d = *this->createVector();\n Vector& q = *this->createVector();\n Vector& s = *this->createVector();\n const bool verbose = f_verbose.getValue();\n\n unsigned iter=1;\n r = M*x;\n\n cgstep_beta(r,b,-1);\/\/for (int i=0; ipreconditioners.size()>0 && usePrecond)\n {\n sofa::helper::AdvancedTimer::stepEnd(\"PCGLinearSolver::solve\");\n sofa::helper::AdvancedTimer::stepBegin(\"PCGLinearSolver::apply Precond\");\n preconditioners[0]->setSystemLHVector(d);\n preconditioners[0]->setSystemRHVector(r);\n preconditioners[0]->freezeSystemMatrix();\n preconditioners[0]->solveSystem();\n \/\/Use freeze boolean to specify the preconditioner that's the fist solve of the step (for example if stepMBK is not call)\n preconditioners[0]->updateSystemMatrix();\n sofa::helper::AdvancedTimer::stepEnd(\"PCGLinearSolver::apply Precond\");\n sofa::helper::AdvancedTimer::stepBegin(\"PCGLinearSolver::solve\");\n }\n else\n {\n d = r;\n }\n\n\n double deltaNew = r.dot(d);\n double delta0 = deltaNew;\n double eps = f_tolerance.getValue() * f_tolerance.getValue() * delta0;\n std::map < std::string, sofa::helper::vector >& graph = * f_graph.beginEdit();\n sofa::helper::vector& graph_error = graph[\"Error\"];\n graph_error.clear();\n\n while ((iter <= f_maxIter.getValue()) && (deltaNew > eps))\n {\n if (verbose) printf(\"CG iteration %d: current L2 error vs initial error=%G\\n\", iter, sqrt(deltaNew\/delta0));\n\n graph_error.push_back(deltaNew);\n\n q = M * d;\n double dtq = d.dot(q);\n double alpha = deltaNew \/ dtq;\n\n cgstep_alpha(x,d,alpha);\/\/for(int i=0; ipreconditioners.size()>0 && usePrecond)\n {\n sofa::helper::AdvancedTimer::stepEnd(\"PCGLinearSolver::solve\");\n sofa::helper::AdvancedTimer::stepBegin(\"PCGLinearSolver::apply Precond\");\n preconditioners[0]->setSystemLHVector(s);\n preconditioners[0]->setSystemRHVector(r);\n preconditioners[0]->solveSystem();\n sofa::helper::AdvancedTimer::stepEnd(\"PCGLinearSolver::apply Precond\");\n sofa::helper::AdvancedTimer::stepBegin(\"PCGLinearSolver::solve\");\n\n }\n else\n {\n s = r;\n }\n\n\n double deltaOld = deltaNew;\n deltaNew = r.dot(s);\n double beta = deltaNew \/ deltaOld;\n\n cgstep_beta(d,s,beta);\/\/for (int i=0; ideleteVector(&r);\n this->deleteVector(&q);\n this->deleteVector(&d);\n this->deleteVector(&s);\n sofa::helper::AdvancedTimer::stepEnd(\"PCGLinearSolver::solve\");\n}\n\nSOFA_DECL_CLASS(ShewchukPCGLinearSolver)\n\nint ShewchukPCGLinearSolverClass = core::RegisterObject(\"Linear system solver using the conjugate gradient iterative algorithm\")\n .add< ShewchukPCGLinearSolver >(true)\n ;\n\n} \/\/ namespace linearsolver\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n\nr7803\/sofa-dev : Small changes in ShewchukPCGLinearSolver\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *\n* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This library is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This library is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this library; if not, write to the Free Software Foundation, *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Modules *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n\/\/ Author: Hadrien Courtecuisse\n\/\/\n\/\/ Copyright: See COPYING file that comes with this distribution\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace linearsolver\n{\n\nusing namespace sofa::defaulttype;\nusing namespace sofa::core::behavior;\nusing namespace sofa::simulation;\nusing namespace sofa::core::objectmodel;\nusing sofa::helper::system::thread::CTime;\nusing sofa::helper::system::thread::ctime_t;\nusing std::cerr;\nusing std::endl;\n\ntemplate\nShewchukPCGLinearSolver::ShewchukPCGLinearSolver()\n : f_maxIter( initData(&f_maxIter,(unsigned)25,\"iterations\",\"maximum number of iterations of the Conjugate Gradient solution\") )\n , f_tolerance( initData(&f_tolerance,1e-5,\"tolerance\",\"desired precision of the Conjugate Gradient Solution (ratio of current residual norm over initial residual norm)\") )\n , f_verbose( initData(&f_verbose,false,\"verbose\",\"Dump system state at each iteration\") )\n , f_update_iteration( initData(&f_update_iteration,(unsigned)0,\"update_iteration\",\"Number of CG iterations before next refresh of precondtioner\") )\n , f_update_step( initData(&f_update_step,(unsigned)1,\"update_step\",\"Number of steps before the next refresh of precondtioners\") )\n , f_use_precond( initData(&f_use_precond,true,\"use_precond\",\"Use preconditioners\") )\n , f_preconditioners( initData(&f_preconditioners, \"preconditioners\", \"If not empty: path to the solvers to use as preconditioners\") )\n , f_graph( initData(&f_graph,\"graph\",\"Graph of residuals at each iteration\") )\n{\n f_graph.setWidget(\"graph\");\n\/\/ f_graph.setReadOnly(true);\n usePrecond = true;\n first = true;\n}\n\ntemplate\nvoid ShewchukPCGLinearSolver::init()\n{\n std::vector solvers;\n BaseContext * c = this->getContext();\n\n const helper::vector& precondNames = f_preconditioners.getValue();\n if (precondNames.empty() && f_use_precond.getValue())\n {\n c->get(&solvers,BaseContext::SearchDown);\n }\n else\n {\n for (unsigned int i=0; iget(s, precondNames[i]);\n if (s) solvers.push_back(s);\n else serr << \"Solver \\\"\" << precondNames[i] << \"\\\" not found.\" << sendl;\n }\n }\n\n for (unsigned int i=0; ipreconditioners.push_back(solvers[i]);\n }\n }\n\n sout<<\"Found \" << this->preconditioners.size() << \" preconditioners\"<\nvoid ShewchukPCGLinearSolver::setSystemMBKMatrix(double mFact, double bFact, double kFact)\n{\n sofa::helper::AdvancedTimer::valSet(\"PCG::buildMBK\", 1);\n sofa::helper::AdvancedTimer::stepBegin(\"PCG::setSystemMBKMatrix\");\n\n Inherit::setSystemMBKMatrix(mFact,bFact,kFact);\n\n sofa::helper::AdvancedTimer::stepEnd(\"PCG::setSystemMBKMatrix(Precond)\");\n\n if (preconditioners.size()==0) return;\n\n if (first) \/\/We initialize all the preconditioners for the first step\n {\n for (unsigned int i=0; ipreconditioners.size(); ++i)\n {\n preconditioners[i]->setSystemMBKMatrix(mFact,bFact,kFact);\n }\n first = false;\n next_refresh_step = 1;\n }\n else if (f_use_precond.getValue()) \/\/ We use only the first precond in the list\n {\n sofa::helper::AdvancedTimer::valSet(\"PCG::PrecondBuildMBK\", 1);\n sofa::helper::AdvancedTimer::stepBegin(\"PCG::PrecondSetSystemMBKMatrix\");\n\n if ((f_update_step.getValue()>0) && (f_update_iteration.getValue()>0))\n {\n if ((next_refresh_step>=f_update_step.getValue()) && (next_refresh_iteration>=f_update_iteration.getValue()))\n {\n preconditioners[0]->setSystemMBKMatrix(mFact,bFact,kFact);\n next_refresh_step=1;\n }\n else\n {\n next_refresh_step++;\n }\n }\n else if (f_update_step.getValue()>0)\n {\n if (next_refresh_step>=f_update_step.getValue())\n {\n preconditioners[0]->setSystemMBKMatrix(mFact,bFact,kFact);\n next_refresh_step=1;\n }\n else\n {\n next_refresh_step++;\n }\n }\n else if (f_update_iteration.getValue()>0)\n {\n if (next_refresh_iteration>=f_update_iteration.getValue())\n {\n preconditioners[0]->setSystemMBKMatrix(mFact,bFact,kFact);\n next_refresh_iteration=1;\n }\n }\n sofa::helper::AdvancedTimer::stepEnd(\"PCG::PrecondSetSystemMBKMatrix\");\n }\n next_refresh_iteration = 1;\n\n\n}\n\ntemplate<>\ninline void ShewchukPCGLinearSolver::cgstep_beta(Vector& p, Vector& r, double beta)\n{\n this->v_op(p,r,p,beta); \/\/ p = p*beta + r\n}\n\ntemplate<>\ninline void ShewchukPCGLinearSolver::cgstep_alpha(Vector& x, Vector& p, double alpha)\n{\n x.peq(p,alpha); \/\/ x = x + alpha p\n}\n\ntemplate\nvoid ShewchukPCGLinearSolver::solve (Matrix& M, Vector& x, Vector& b)\n{\n sofa::helper::AdvancedTimer::stepBegin(\"PCGLinearSolver::solve\");\n\n Vector& r = *this->createVector();\n Vector& d = *this->createVector();\n Vector& q = *this->createVector();\n Vector& s = *this->createVector();\n const bool verbose = f_verbose.getValue();\n\n unsigned iter=1;\n r = M*x;\n\n cgstep_beta(r,b,-1);\/\/for (int i=0; ipreconditioners.size()>0 && usePrecond)\n {\n sofa::helper::AdvancedTimer::stepEnd(\"PCGLinearSolver::solve\");\n sofa::helper::AdvancedTimer::stepBegin(\"PCGLinearSolver::apply Precond\");\n preconditioners[0]->setSystemLHVector(d);\n preconditioners[0]->setSystemRHVector(r);\n preconditioners[0]->freezeSystemMatrix();\n preconditioners[0]->solveSystem();\n \/\/Use freeze boolean to specify the preconditioner that's the fist solve of the step (for example if stepMBK is not call)\n preconditioners[0]->updateSystemMatrix();\n sofa::helper::AdvancedTimer::stepEnd(\"PCGLinearSolver::apply Precond\");\n sofa::helper::AdvancedTimer::stepBegin(\"PCGLinearSolver::solve\");\n }\n else\n {\n d = r;\n }\n\n\n double deltaNew = r.dot(d);\n double delta0 = deltaNew;\n double eps = f_tolerance.getValue() * f_tolerance.getValue() * delta0;\n std::map < std::string, sofa::helper::vector >& graph = * f_graph.beginEdit();\n sofa::helper::vector& graph_error = graph[\"Error\"];\n graph_error.clear();\n\n while ((iter <= f_maxIter.getValue()) && (deltaNew > eps))\n {\n if (verbose) printf(\"CG iteration %d: current L2 error vs initial error=%G\\n\", iter, sqrt(deltaNew\/delta0));\n\n graph_error.push_back(deltaNew);\n\n q = M * d;\n double dtq = d.dot(q);\n double alpha = deltaNew \/ dtq;\n\n cgstep_alpha(x,d,alpha);\/\/for(int i=0; ipreconditioners.size()>0 && usePrecond)\n {\n sofa::helper::AdvancedTimer::stepEnd(\"PCGLinearSolver::solve\");\n sofa::helper::AdvancedTimer::stepBegin(\"PCGLinearSolver::apply Precond\");\n preconditioners[0]->setSystemLHVector(s);\n preconditioners[0]->setSystemRHVector(r);\n preconditioners[0]->solveSystem();\n sofa::helper::AdvancedTimer::stepEnd(\"PCGLinearSolver::apply Precond\");\n sofa::helper::AdvancedTimer::stepBegin(\"PCGLinearSolver::solve\");\n\n }\n else\n {\n s = r;\n }\n\n\n double deltaOld = deltaNew;\n deltaNew = r.dot(s);\n double beta = deltaNew \/ deltaOld;\n\n cgstep_beta(d,s,beta);\/\/for (int i=0; ideleteVector(&r);\n this->deleteVector(&q);\n this->deleteVector(&d);\n this->deleteVector(&s);\n sofa::helper::AdvancedTimer::stepEnd(\"PCGLinearSolver::solve\");\n}\n\nSOFA_DECL_CLASS(ShewchukPCGLinearSolver)\n\nint ShewchukPCGLinearSolverClass = core::RegisterObject(\"Linear system solver using the conjugate gradient iterative algorithm\")\n .add< ShewchukPCGLinearSolver >(true)\n ;\n\n} \/\/ namespace linearsolver\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n\n<|endoftext|>"} {"text":"#ifndef REFL_INFORMATION_HPP\n#define REFL_INFORMATION_HPP\n\n#include \"..\/meta_utils\/meta_utils.hpp\"\n#include \"variables\/reflect_information_variable.hpp\"\n#include \"functions\/reflect_information_method.hpp\"\n\nnamespace reflect {\n\n\/**\n * @brief Namespace related to all reflection information(metadata, names, etc)\n *\/\nnamespace info {\n\n\/**\n * @brief SFINAE check if class is generator\n *\/\ntemplate \nstruct is_generator {\n template static constexpr ::std::true_type check(decltype (&C::template generate<::boost::hana::tuple<::boost::hana::size_t...>>));\n template static constexpr ::std::false_type check(...);\n static constexpr bool value = ::std::is_same<::std::true_type, decltype(check(nullptr))>::value;\n};\n\ntemplate constexpr bool is_generator_v = is_generator::value;\n\n\/**\n * @brief SFINAE check if class is reflected\n *\n *\/\ntemplate \nstruct is_reflected {\n\n \/**\n * @brief If is_reflected method exist\n *\n * @return ::std::true_type\n *\/\n template static constexpr ::std::true_type check(decltype(&C::is_reflected));\n \/**\n * @brief If is_reflected method doesn't exist\n *\n * @return ::std::false_type\n *\/\n template static constexpr ::std::false_type check(...);\n static constexpr bool value = ::std::is_same<::std::true_type, decltype(check(nullptr))>::value; \/**< true true if reflected, othervise false *\/\n};\n\ntemplate constexpr bool is_reflected_v = is_reflected::value; \/**< Helper variable template for is_reflected *\/\n\nnamespace detail {\n\n\/**\n * @brief Concating all names in one tuple\n *\/\ntemplate \nconstexpr decltype (auto) names_tuple (::std::index_sequence&&) {\n return metautils::multiple_concat(names_state(metautils::counter{},static_cast(nullptr),static_cast(nullptr))...);\n}\n\n\/**\n * @brief Concating all metadata in one tuple\n *\/\ntemplate \nconstexpr decltype (auto) metadata_tuple (::std::index_sequence&&) {\n return metautils::multiple_concat(metadata_state(metautils::counter{},static_cast(nullptr),static_cast(nullptr))...);\n}\n\n}\n\n\/**\n * @brief Class that stores meta-information about T\n *\n *\/\ntemplate \nstruct MetaClass {\n using Type = typename T::Type;\n using MetaInfo_type = T;\n static constexpr auto class_name {HANA_STR(class_name_detail(static_cast(nullptr),static_cast(nullptr)))}; \/**< compile-time string of class name *\/\n static constexpr auto names {detail::names_tuple(::std::make_index_sequence{},static_cast(nullptr)))::value>{})}; \/**< tuple of all variable names *\/\n static constexpr auto metadata {detail::metadata_tuple(::std::make_index_sequence{},static_cast(nullptr)))::value>{})}; \/**< tuple of all method names *\/\n};\n\nclass EmptyGenerator;\n\n\/**\n * @brief The DefaultIndexGenerator class - generate tuple of indices [0..N-1] where N - tuple size\n *\/\nclass DefaultIndexGenerator final {\npublic:\n using reverse = EmptyGenerator;\n\n \/**\n * @brief Generate tuple of indices\n * @return ::boost::hana::tuple<0...N-1>\n *\/\n template\n constexpr static decltype (auto) generate () {\n return metautils::gen_inds_tup()))>();\n }\n};\n\n\/**\n * @brief Empty generator\n *\/\nclass EmptyGenerator final {\npublic:\n using reverse = DefaultIndexGenerator;\n\n template\n \/**\n * @brief Generate empty tuple\n * @return ::boost::hana::tuple<>\n *\/\n constexpr static ::boost::hana::tuple<> generate () {\n return {};\n }\n};\n\n\/**\n * @brief Class that stores meta-functions\n *\/\ntemplate \nstruct MetaInfo;\n\n}\n\n}\n\n#define IN_METAINFO(TYPE) \\\n using Type = TYPE; \\\n using MetaInfo_type = TYPE; \\\n static constexpr auto is_reflected () {return std::true_type();} \\\n friend constexpr auto class_name_detail(const Type*, const MetaInfo_type*) -> decltype (#TYPE) { return #TYPE; } \\\n friend constexpr ::reflect::metautils::counter<0> counter (::reflect::metautils::counter<0>, const MetaInfo_type*);\n\n#define OUT_METAINFO(TYPE) \\\n friend struct reflect::info::MetaInfo; \\\n using MetaInfo_type = ::reflect::info::MetaInfo; \\\n static constexpr auto is_reflected () {return std::true_type();}\n\n\n#define METAINFO(TYPE) \\\n namespace reflect { \\\n namespace info { \\\n template <> \\\n struct MetaInfo { \\\n using Type = TYPE; \\\n using MetaInfo_type = ::reflect::info::MetaInfo; \\\n friend constexpr auto class_name_detail(const Type*, const MetaInfo_type*) -> decltype (#TYPE) { return #TYPE; } \\\n friend constexpr ::reflect::metautils::counter<0> counter (::reflect::metautils::counter<0>, const MetaInfo_type*);\n\n#define TEMPLATE_METAINFO(TYPE,TEMPLATE_TYPE,TEMPLATE) \\\n namespace reflect { \\\n namespace info { \\\n template \\\n struct MetaInfo> { \\\n using Type = TYPE