hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
fa90c5bdcf1ce8692c0d37e671381e3e46bc9357
11,675
hpp
C++
cpp/oneapi/dal/algo/knn/common.hpp
cmsxbc/oneDAL
eeb8523285907dc359c84ca4894579d5d1d9f57e
[ "Apache-2.0" ]
null
null
null
cpp/oneapi/dal/algo/knn/common.hpp
cmsxbc/oneDAL
eeb8523285907dc359c84ca4894579d5d1d9f57e
[ "Apache-2.0" ]
null
null
null
cpp/oneapi/dal/algo/knn/common.hpp
cmsxbc/oneDAL
eeb8523285907dc359c84ca4894579d5d1d9f57e
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright 2020-2021 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #pragma once #include "oneapi/dal/algo/knn/detail/distance.hpp" #include "oneapi/dal/util/result_option_id.hpp" #include "oneapi/dal/detail/serialization.hpp" #include "oneapi/dal/detail/common.hpp" #include "oneapi/dal/table/common.hpp" #include "oneapi/dal/common.hpp" namespace oneapi::dal::knn { namespace v1 { /// Weight function used in prediction enum class voting_mode { /// Uniform weights for neighbors for prediction voting. uniform, /// Weight neighbors by the inverse of their distance. distance }; } // namespace v1 using v1::voting_mode; namespace task { namespace v1 { /// Tag-type that parameterizes entities used for solving /// :capterm:`classification problem <classification>`. struct classification {}; /// Tag-type that parameterizes entities used for solving /// the :capterm:`search problem <search>`. struct search {}; /// Alias tag-type for classification task. using by_default = classification; } // namespace v1 using v1::classification; using v1::search; using v1::by_default; } // namespace task namespace method { namespace v1 { /// Tag-type that denotes :ref:`k-d tree <knn_t_math_kd_tree>` computational method. struct kd_tree {}; /// Tag-type that denotes :ref:`brute-force <knn_t_math_brute_force>` computational /// method. struct brute_force {}; /// Alias tag-type for :ref:`brute-force <knn_t_math_brute_force>` computational /// method. using by_default = brute_force; } // namespace v1 using v1::kd_tree; using v1::brute_force; using v1::by_default; } // namespace method /// Represents result option flag /// Behaves like a regular :expr`enum`. class result_option_id : public result_option_id_base { public: constexpr result_option_id() = default; constexpr explicit result_option_id(const result_option_id_base& base) : result_option_id_base{ base } {} }; namespace detail { ONEDAL_EXPORT result_option_id get_indices_id(); ONEDAL_EXPORT result_option_id get_distances_id(); ONEDAL_EXPORT result_option_id get_responses_id(); } // namespace detail /// Result options are used to define /// what should algorithm return namespace result_options { const inline result_option_id indices = detail::get_indices_id(); const inline result_option_id distances = detail::get_distances_id(); const inline result_option_id responses = detail::get_responses_id(); } // namespace result_options namespace detail { namespace v1 { struct descriptor_tag {}; template <typename Task> class descriptor_impl; template <typename Task> class model_impl; template <typename Float> constexpr bool is_valid_float_v = dal::detail::is_one_of_v<Float, float, double>; template <typename Method> constexpr bool is_valid_method_v = dal::detail::is_one_of_v<Method, method::kd_tree, method::brute_force>; template <typename Task> constexpr bool is_valid_task_v = dal::detail::is_one_of_v<Task, task::classification, task::search>; template <typename Distance> constexpr bool is_valid_distance_v = dal::detail::is_tag_one_of_v<Distance, minkowski_distance::detail::descriptor_tag, chebyshev_distance::detail::descriptor_tag, cosine_distance::detail::descriptor_tag>; template <typename T> using enable_if_search_t = std::enable_if_t<std::is_same_v<std::decay_t<T>, task::search>>; template <typename T> using enable_if_classification_t = std::enable_if_t<std::is_same_v<std::decay_t<T>, task::classification>>; template <typename T> using enable_if_brute_force_t = std::enable_if_t<std::is_same_v<std::decay_t<T>, method::brute_force>>; template <typename Task = task::by_default> class descriptor_base : public base { static_assert(is_valid_task_v<Task>); friend detail::distance_accessor; public: using tag_t = descriptor_tag; using float_t = float; using method_t = method::by_default; using task_t = Task; using distance_t = minkowski_distance::descriptor<float_t>; descriptor_base(); std::int64_t get_class_count() const; std::int64_t get_neighbor_count() const; voting_mode get_voting_mode() const; result_option_id get_result_options() const; protected: explicit descriptor_base(const detail::distance_ptr& distance); void set_class_count_impl(std::int64_t value); void set_neighbor_count_impl(std::int64_t value); void set_voting_mode_impl(voting_mode value); void set_distance_impl(const detail::distance_ptr& distance); const detail::distance_ptr& get_distance_impl() const; void set_result_options_impl(const result_option_id& value); private: dal::detail::pimpl<descriptor_impl<Task>> impl_; }; } // namespace v1 using v1::descriptor_tag; using v1::descriptor_impl; using v1::model_impl; using v1::descriptor_base; using v1::is_valid_float_v; using v1::is_valid_method_v; using v1::is_valid_task_v; using v1::is_valid_distance_v; using v1::enable_if_search_t; using v1::enable_if_classification_t; using v1::enable_if_brute_force_t; } // namespace detail namespace v1 { /// @tparam Float The floating-point type that the algorithm uses for /// intermediate computations. Can be :expr:`float` or /// :expr:`double`. /// @tparam Method Tag-type that specifies an implementation of algorithm. Can /// be :expr:`method::brute_force` or :expr:`method::kd_tree`. /// @tparam Task Tag-type that specifies type of the problem to solve. Can /// be :expr:`task::classification`. /// @tparam Distance The descriptor of the distance used for computations. Can be /// :expr:`minkowski_distance::descriptor` or /// :expr:`chebyshev_distance::descriptor` template <typename Float = float, typename Method = method::by_default, typename Task = task::by_default, typename Distance = oneapi::dal::minkowski_distance::descriptor<Float>> class descriptor : public detail::descriptor_base<Task> { static_assert(detail::is_valid_float_v<Float>); static_assert(detail::is_valid_method_v<Method>); static_assert(detail::is_valid_task_v<Task>); static_assert(detail::is_valid_distance_v<Distance>, "Custom distances for kNN is not supported. " "Use one of the predefined distances."); using base_t = detail::descriptor_base<Task>; public: using float_t = Float; using method_t = Method; using task_t = Task; using distance_t = Distance; /// Creates a new instance of the class with the given :literal:`class_count` /// and :literal:`neighbor_count` property values explicit descriptor(std::int64_t class_count, std::int64_t neighbor_count) : base_t(std::make_shared<detail::distance<distance_t>>(distance_t{})) { set_class_count(class_count); set_neighbor_count(neighbor_count); } /// Creates a new instance of the class with the given :literal:`class_count`, /// :literal:`neighbor_count` and :literal:`distance` property values. /// Used with :expr:`method::brute_force` only. template <typename M = Method, typename = detail::enable_if_brute_force_t<M>> explicit descriptor(std::int64_t class_count, std::int64_t neighbor_count, const distance_t& distance) : base_t(std::make_shared<detail::distance<distance_t>>(distance)) { set_class_count(class_count); set_neighbor_count(neighbor_count); } /// Creates a new instance of the class with the given :literal:`neighbor_count` /// property value. /// Used with :expr:`task::search` only. template <typename T = Task, typename = detail::enable_if_search_t<T>> explicit descriptor(std::int64_t neighbor_count) { set_neighbor_count(neighbor_count); } /// Creates a new instance of the class with the given :literal:`neighbor_count` /// and :literal:`distance` property values. /// Used with :expr:`task::search` only. template <typename T = Task, typename = detail::enable_if_search_t<T>> explicit descriptor(std::int64_t neighbor_count, const distance_t& distance) : base_t(std::make_shared<detail::distance<distance_t>>(distance)) { set_neighbor_count(neighbor_count); } /// The number of classes c /// @invariant :expr:`class_count > 1` std::int64_t get_class_count() const { return base_t::get_class_count(); } auto& set_class_count(std::int64_t value) { base_t::set_class_count_impl(value); return *this; } /// The number of neighbors k /// @invariant :expr:`neighbor_count > 0` std::int64_t get_neighbor_count() const { return base_t::get_neighbor_count(); } auto& set_neighbor_count(std::int64_t value) { base_t::set_neighbor_count_impl(value); return *this; } /// The voting mode. voting_mode get_voting_mode() const { return base_t::get_voting_mode(); } auto& set_voting_mode(voting_mode value) { base_t::set_voting_mode_impl(value); return *this; } /// Choose distance type for calculations. Used with :expr:`method::brute_force` only. template <typename M = Method, typename = detail::enable_if_brute_force_t<M>> const distance_t& get_distance() const { using dist_t = detail::distance<distance_t>; const auto dist = std::static_pointer_cast<dist_t>(base_t::get_distance_impl()); return dist; } template <typename M = Method, typename = detail::enable_if_brute_force_t<M>> auto& set_distance(const distance_t& dist) { base_t::set_distance_impl(std::make_shared<detail::distance<distance_t>>(dist)); return *this; } /// Choose which results should be computed and returned. result_option_id get_result_options() const { return base_t::get_result_options(); } auto& set_result_options(const result_option_id& value) { base_t::set_result_options_impl(value); return *this; } }; /// @tparam Task Tag-type that specifies type of the problem to solve. Can /// be :expr:`task::classification`. template <typename Task = task::by_default> class model : public base { static_assert(detail::is_valid_task_v<Task>); friend dal::detail::pimpl_accessor; friend dal::detail::serialization_accessor; public: /// Creates a new instance of the class with the default property values. model(); private: void serialize(dal::detail::output_archive& ar) const; void deserialize(dal::detail::input_archive& ar); explicit model(const std::shared_ptr<detail::model_impl<Task>>& impl); dal::detail::pimpl<detail::model_impl<Task>> impl_; }; } // namespace v1 using v1::descriptor; using v1::model; } // namespace oneapi::dal::knn
33.742775
100
0.697045
cmsxbc
fa928843ab1b25467505e98c581818e8b4248c4c
1,222
cxx
C++
src/Core/Common/DistanceBetweenIndices/Code.cxx
aaron-bray/ITKExamples
7ad0d445bb0139cf010e0e1cc906dccce97dda7c
[ "Apache-2.0" ]
null
null
null
src/Core/Common/DistanceBetweenIndices/Code.cxx
aaron-bray/ITKExamples
7ad0d445bb0139cf010e0e1cc906dccce97dda7c
[ "Apache-2.0" ]
null
null
null
src/Core/Common/DistanceBetweenIndices/Code.cxx
aaron-bray/ITKExamples
7ad0d445bb0139cf010e0e1cc906dccce97dda7c
[ "Apache-2.0" ]
null
null
null
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkPoint.h" #include "itkIndex.h" #include "itkMath.h" #include <iostream> int main(int, char *[]) { itk::Index<2> pixel1; pixel1.Fill(2); itk::Index<2> pixel2; pixel2.Fill(4); itk::Point<double, 2> p1; p1[0] = pixel1[0]; p1[1] = pixel1[1]; itk::Point<double, 2> p2; p2[0] = pixel2[0]; p2[1] = pixel2[1]; double distance = p2.EuclideanDistanceTo(p1); std::cout << "Distance: " << distance << std::endl; }
27.155556
77
0.590835
aaron-bray
fa92e2e35611cb44abe44a3a91f953f3e25d4efb
7,779
cpp
C++
3rdparty/webkit/Source/WebCore/page/DeprecatedGlobalSettings.cpp
mchiasson/PhaserNative
f867454602c395484bf730a7c43b9c586c102ac2
[ "MIT" ]
null
null
null
3rdparty/webkit/Source/WebCore/page/DeprecatedGlobalSettings.cpp
mchiasson/PhaserNative
f867454602c395484bf730a7c43b9c586c102ac2
[ "MIT" ]
null
null
null
3rdparty/webkit/Source/WebCore/page/DeprecatedGlobalSettings.cpp
mchiasson/PhaserNative
f867454602c395484bf730a7c43b9c586c102ac2
[ "MIT" ]
1
2019-01-25T13:55:25.000Z
2019-01-25T13:55:25.000Z
/* * Copyright (C) 2006, 2007, 2008, 2009, 2011, 2012 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "DeprecatedGlobalSettings.h" #include "AudioSession.h" #include "HTMLMediaElement.h" #include "RuntimeApplicationChecks.h" #include <wtf/NeverDestroyed.h> #if ENABLE(MEDIA_STREAM) #include "MockRealtimeMediaSourceCenter.h" #if USE(AVFOUNDATION) #include "RealtimeMediaSourceCenterMac.h" #endif #endif namespace WebCore { #if USE(AVFOUNDATION) bool DeprecatedGlobalSettings::gAVFoundationEnabled = true; bool DeprecatedGlobalSettings::gAVFoundationNSURLSessionEnabled = true; #endif #if USE(GSTREAMER) bool DeprecatedGlobalSettings::gGStreamerEnabled = true; #endif bool DeprecatedGlobalSettings::gMockScrollbarsEnabled = false; bool DeprecatedGlobalSettings::gUsesOverlayScrollbars = false; bool DeprecatedGlobalSettings::gMockScrollAnimatorEnabled = false; #if ENABLE(MEDIA_STREAM) bool DeprecatedGlobalSettings::gMockCaptureDevicesEnabled = false; bool DeprecatedGlobalSettings::gMediaCaptureRequiresSecureConnection = true; #endif #if PLATFORM(WIN) bool DeprecatedGlobalSettings::gShouldUseHighResolutionTimers = true; #endif bool DeprecatedGlobalSettings::gShouldRespectPriorityInCSSAttributeSetters = false; bool DeprecatedGlobalSettings::gLowPowerVideoAudioBufferSizeEnabled = false; bool DeprecatedGlobalSettings::gResourceLoadStatisticsEnabledEnabled = false; bool DeprecatedGlobalSettings::gAllowsAnySSLCertificate = false; #if PLATFORM(IOS) bool DeprecatedGlobalSettings::gNetworkDataUsageTrackingEnabled = false; bool DeprecatedGlobalSettings::gAVKitEnabled = false; bool DeprecatedGlobalSettings::gShouldOptOutOfNetworkStateObservation = false; #endif bool DeprecatedGlobalSettings::gManageAudioSession = false; #if PLATFORM(WIN) void DeprecatedGlobalSettings::setShouldUseHighResolutionTimers(bool shouldUseHighResolutionTimers) { gShouldUseHighResolutionTimers = shouldUseHighResolutionTimers; } #endif #if USE(AVFOUNDATION) void DeprecatedGlobalSettings::setAVFoundationEnabled(bool enabled) { if (gAVFoundationEnabled == enabled) return; gAVFoundationEnabled = enabled; HTMLMediaElement::resetMediaEngines(); } void DeprecatedGlobalSettings::setAVFoundationNSURLSessionEnabled(bool enabled) { if (gAVFoundationNSURLSessionEnabled == enabled) return; gAVFoundationNSURLSessionEnabled = enabled; } #endif #if USE(GSTREAMER) void DeprecatedGlobalSettings::setGStreamerEnabled(bool enabled) { if (gGStreamerEnabled == enabled) return; gGStreamerEnabled = enabled; #if ENABLE(VIDEO) HTMLMediaElement::resetMediaEngines(); #endif } #endif #if ENABLE(MEDIA_STREAM) bool DeprecatedGlobalSettings::mockCaptureDevicesEnabled() { return gMockCaptureDevicesEnabled; } void DeprecatedGlobalSettings::setMockCaptureDevicesEnabled(bool enabled) { gMockCaptureDevicesEnabled = enabled; MockRealtimeMediaSourceCenter::setMockRealtimeMediaSourceCenterEnabled(enabled); } bool DeprecatedGlobalSettings::mediaCaptureRequiresSecureConnection() { return gMediaCaptureRequiresSecureConnection; } void DeprecatedGlobalSettings::setMediaCaptureRequiresSecureConnection(bool mediaCaptureRequiresSecureConnection) { gMediaCaptureRequiresSecureConnection = mediaCaptureRequiresSecureConnection; } #endif // It's very important that this setting doesn't change in the middle of a document's lifetime. // The Mac port uses this flag when registering and deregistering platform-dependent scrollbar // objects. Therefore, if this changes at an unexpected time, deregistration may not happen // correctly, which may cause the platform to follow dangling pointers. void DeprecatedGlobalSettings::setMockScrollbarsEnabled(bool flag) { gMockScrollbarsEnabled = flag; // FIXME: This should update scroll bars in existing pages. } bool DeprecatedGlobalSettings::mockScrollbarsEnabled() { return gMockScrollbarsEnabled; } void DeprecatedGlobalSettings::setUsesOverlayScrollbars(bool flag) { gUsesOverlayScrollbars = flag; // FIXME: This should update scroll bars in existing pages. } bool DeprecatedGlobalSettings::usesOverlayScrollbars() { return gUsesOverlayScrollbars; } void DeprecatedGlobalSettings::setUsesMockScrollAnimator(bool flag) { gMockScrollAnimatorEnabled = flag; } bool DeprecatedGlobalSettings::usesMockScrollAnimator() { return gMockScrollAnimatorEnabled; } void DeprecatedGlobalSettings::setShouldRespectPriorityInCSSAttributeSetters(bool flag) { gShouldRespectPriorityInCSSAttributeSetters = flag; } bool DeprecatedGlobalSettings::shouldRespectPriorityInCSSAttributeSetters() { return gShouldRespectPriorityInCSSAttributeSetters; } void DeprecatedGlobalSettings::setLowPowerVideoAudioBufferSizeEnabled(bool flag) { gLowPowerVideoAudioBufferSizeEnabled = flag; } void DeprecatedGlobalSettings::setResourceLoadStatisticsEnabled(bool flag) { gResourceLoadStatisticsEnabledEnabled = flag; } #if PLATFORM(IOS) void DeprecatedGlobalSettings::setAudioSessionCategoryOverride(unsigned sessionCategory) { AudioSession::sharedSession().setCategoryOverride(static_cast<AudioSession::CategoryType>(sessionCategory)); } unsigned DeprecatedGlobalSettings::audioSessionCategoryOverride() { return AudioSession::sharedSession().categoryOverride(); } void DeprecatedGlobalSettings::setNetworkDataUsageTrackingEnabled(bool trackingEnabled) { gNetworkDataUsageTrackingEnabled = trackingEnabled; } bool DeprecatedGlobalSettings::networkDataUsageTrackingEnabled() { return gNetworkDataUsageTrackingEnabled; } static String& sharedNetworkInterfaceNameGlobal() { static NeverDestroyed<String> networkInterfaceName; return networkInterfaceName; } void DeprecatedGlobalSettings::setNetworkInterfaceName(const String& networkInterfaceName) { sharedNetworkInterfaceNameGlobal() = networkInterfaceName; } const String& DeprecatedGlobalSettings::networkInterfaceName() { return sharedNetworkInterfaceNameGlobal(); } #endif bool DeprecatedGlobalSettings::globalConstRedeclarationShouldThrow() { #if PLATFORM(MAC) return !MacApplication::isIBooks(); #elif PLATFORM(IOS) return !IOSApplication::isIBooks(); #else return true; #endif } void DeprecatedGlobalSettings::setAllowsAnySSLCertificate(bool allowAnySSLCertificate) { gAllowsAnySSLCertificate = allowAnySSLCertificate; } bool DeprecatedGlobalSettings::allowsAnySSLCertificate() { return gAllowsAnySSLCertificate; } } // namespace WebCore
30.268482
113
0.811801
mchiasson
fa998feef8edbb4fa6a19de46241a75869655a88
10,531
cpp
C++
Sunny-Core/01_FRAMEWORK/app/Window.cpp
adunStudio/Sunny
9f71c1816aa62bbc0d02d2f8d6414f4bf9aee7e7
[ "Apache-2.0" ]
20
2018-01-19T06:28:36.000Z
2021-08-06T14:06:13.000Z
Sunny-Core/01_FRAMEWORK/app/Window.cpp
adunStudio/Sunny
9f71c1816aa62bbc0d02d2f8d6414f4bf9aee7e7
[ "Apache-2.0" ]
null
null
null
Sunny-Core/01_FRAMEWORK/app/Window.cpp
adunStudio/Sunny
9f71c1816aa62bbc0d02d2f8d6414f4bf9aee7e7
[ "Apache-2.0" ]
3
2019-01-29T08:58:04.000Z
2021-01-02T06:33:20.000Z
// // Created by adunstudio on 2018-01-08. // #include "Window.h" #include "../directx/Context.h" #include "../directx/Renderer.h" #include "../graphics/fonts/FontManager.h" #include "../audio/MusicManager.h" EXTERN_C IMAGE_DOS_HEADER __ImageBase; extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); namespace sunny { // 메시지를 처리하는 함수 LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); // Input.cpp extern void KeyCallback(InputManager* inputManager, int flags, int key, unsigned int message); extern void MouseButtonCallback(InputManager* inputManager, int button, int x, int y); // Server.cpp extern void ServerPacketCallback(ServerManager* serverManager, SOCKET socket); extern void ServerCloseCallback (ServerManager* serverManager, SOCKET socket); HINSTANCE hInstance; // 윈도우 핸들 인스턴스 식별자 HDC hDc; // 윈도우 핸들 디바이스 컨텍스트 HWND hWnd; // 윈도우 핸들 (번호) std::map<void*, Window*> Window::s_handles; void Window::RegisterWindowClass(void* handle, Window* window) { s_handles[handle] = window; } Window* Window::GetWindowClass(void* handle) { if(handle == nullptr) return s_handles.begin()->second; return s_handles[handle]; } Window::Window(const std::string title, const WindowProperties& properties) : m_title(title), m_properties(properties), m_handle(nullptr), m_closed(false) { m_resolutionWidth = m_properties.width ; m_resolutionHeight = m_properties.height; if(!Init()) { // TODO: Debug System return; } using namespace graphics; //FontManager::SetScale(maths::vec2(m_properties.width, m_properties.height)); FontManager::Add(new Font("nanum", "04_ASSET/FONT/NanumGothic.ttf", 32)); FontManager::Add(new Font("nanum", "04_ASSET/FONT/NanumGothic.ttf", 24)); FontManager::Add(new Font("nanum", "04_ASSET/FONT/NanumGothic.ttf", 16)); FontManager::Add(new Font("consola", "04_ASSET/FONT/consola.ttf", 32)); FontManager::Add(new Font("SourceSansPro", "04_ASSET/FONT/SourceSansPro-Light.ttf", 32)); FontManager::Add(new Font("dot", "04_ASSET/FONT/small_dot_digital-7.ttf", 32)); FontManager::Add(new Font("dot", "04_ASSET/FONT/small_dot_digital-7.ttf", 24)); FontManager::Add(new Font("dot", "04_ASSET/FONT/small_dot_digital-7.ttf", 16)); FontManager::Add(new Font("power", "04_ASSET/FONT/power_pixel-7.ttf", 32)); FontManager::Add(new Font("power", "04_ASSET/FONT/power_pixel-7.ttf", 24)); FontManager::Add(new Font("power", "04_ASSET/FONT/power_pixel-7.ttf", 16)); FontManager::Add(new Font("dash", "04_ASSET/FONT/dash_dot_lcd-7.ttf", 32)); FontManager::Add(new Font("dash", "04_ASSET/FONT/dash_dot_lcd-7.ttf", 28)); FontManager::Add(new Font("dash", "04_ASSET/FONT/dash_dot_lcd-7.ttf", 24)); FontManager::Add(new Font("dash", "04_ASSET/FONT/dash_dot_lcd-7.ttf", 16)); FontManager::Add(new Font("kopub", "04_ASSET/FONT/KoPub_Dotum_Medium.ttf", 16)); FontManager::Add(new Font("kopub", "04_ASSET/FONT/KoPub_Dotum_Medium.ttf", 24)); FontManager::Add(new Font("kopub", "04_ASSET/FONT/KoPub_Dotum_Medium.ttf", 28)); FontManager::Add(new Font("kopub", "04_ASSET/FONT/KoPub_Dotum_Medium.ttf", 32)); m_inputManager = new InputManager(); m_serverManager = new ServerManager(); audio::MusicManager::Init(); } Window::~Window() { audio::MusicManager::Clean(); } bool Window::Init() { hInstance = (HINSTANCE)&__ImageBase; WNDCLASS winClass = {}; // 생성하려는 윈도우의 속성 값을 저장해 등록하는 구조체 winClass.hInstance = hInstance; // winClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // 윈도우가 출력되는 형태 winClass.lpfnWndProc = (WNDPROC)WndProc; // 메시지 처리에 사용될 함수 winClass.lpszClassName = (LPCTSTR)"Sunny Win64 Window"; // 윈도우 클래스의 이름 (윈도우를 만들 때 이 이름을 이용한다.) winClass.hCursor = LoadCursor(nullptr, IDC_ARROW); // 기본 커서 winClass.hIcon = LoadIcon(nullptr, IDI_WINLOGO); // 기본 아이콘 /* winClass.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); // 윈도우의 배경 색 winClass.cbClsExtra = 0; // 클래스를 위한 여분의 메모리 크기 winClass.cbWndExtra = 0; // 윈도우를 위한 여분의 메모리 크기 */ // 윈도우 클래스를 커널에 등록한다. if(!RegisterClass(&winClass)) { // TODO: Debug System return false; } RECT size = { 0, 0, m_properties.width, m_properties.height }; DWORD style = WS_OVERLAPPED | WS_CAPTION | WS_MINIMIZEBOX | WS_SYSMENU | WS_BORDER; // WS_OVERLAPPEDWINDOW : 타이틀 바에 최소화, 최대화, 닫기 버튼이 나타나고 오른쪽 버튼을 눌렀을 때 시스템 메뉴가 나타난다. // WS_OVERLAPPED : 기본적인 윈도우로 아이콘이 없고 최소화, 최대화, 닫기 버튼도 없다, 또한 시스템 메뉴가 나타나지 않는다. // ... 검색 AdjustWindowRect(&size, style, false); // TODO: 한글 처리 hWnd = CreateWindowEx( WS_EX_APPWINDOW | WS_EX_WINDOWEDGE, // 태스크바에 나타낸다. winClass.lpszClassName, // 윈도우 클래스의 이름 //(LPCWSTR)m_title.c_str(), // 만들어질 윈도우의 타이틀 바에 나타내는 문자열 _T("가나sunny"), // 만들어질 윈도우의 타이틀 바에 나타내는 문자열 WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, // 윈도우 스타일 조합 GetSystemMetrics(SM_CXSCREEN) / 2 - m_properties.width / 2, // 윈도우 생성 위치 x GetSystemMetrics(SM_CYSCREEN) / 2 - m_properties.height / 2 - 40, // 윈도우 생성 위치 y // TODO: This requires some... attention size.right + (-size.left), size.bottom + (-size.top), // 생성되는 윈도우의 폭과 높이 NULL, NULL, hInstance, NULL ); m_handle = hWnd; if(!hWnd) { // TODO: Debug System return false; } RegisterWindowClass(hWnd, this); directx::Context::Create(m_properties, hWnd); ShowWindow(hWnd, SW_SHOW); SetFocus(hWnd); directx::Renderer::Init(); directx::GeometryBuffer::Init(); SetTitle(m_title); // imGui IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; ImFont* pFont = io.Fonts->AddFontFromFileTTF("04_ASSET/FONT/NanumGothic.ttf", 17, NULL, io.Fonts->GetGlyphRangesKorean()); ImGui_ImplDX11_Init(hWnd, directx::Context::GetDevice(), directx::Context::GetDeviceContext(DIMENSION::D2)); ImGui::StyleColorsDark(); return true; } void Window::Update() { MSG message; while(PeekMessage(&message, nullptr, 0, 0, PM_REMOVE) > 0) { if (message.message == WM_QUIT) { m_closed = true; return; } TranslateMessage(&message); DispatchMessage(&message); } audio::MusicManager::Update(); m_inputManager->Update(); directx::Renderer::Present(); } void Window::Clear() const { // 화면을 지워주는 작업 directx::Renderer::Clear(RENDERER_BUFFER_COLOR | RENDERER_BUFFER_DEPTH | RENDERER_BUFFER_SHADOW | RENDERER_BUFFER_DEFERRED); } bool Window::Closed() const { return m_closed; } void Window::SetTitle(const std::string title) { m_title = title; wchar_t* text = CA2W(title.c_str()); SetWindowText(hWnd, text); } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { if (ImGui_ImplWin32_WndProcHandler(hWnd, message, wParam, lParam)) return true; LRESULT result = NULL; Window* window = Window::GetWindowClass(hWnd); if(window == nullptr) return DefWindowProc(hWnd, message, wParam, lParam); InputManager* inputManager = window->GetInputManager(); ServerManager* serverManager = window->GetServerManager(); switch(message) { case WM_SETFOCUS: FocusCallback(window, true); break; case WM_KILLFOCUS: FocusCallback(window, false); break; case WM_CLOSE: case WM_DESTROY: PostQuitMessage(0); break; case WM_KEYDOWN: case WM_KEYUP: case WM_SYSKEYDOWN: case WM_SYSKEYUP: KeyCallback(inputManager, lParam, wParam, message); break; case WM_LBUTTONDOWN: case WM_LBUTTONUP: case WM_RBUTTONDOWN: case WM_RBUTTONUP: case WM_MBUTTONDOWN: case WM_MBUTTONUP: MouseButtonCallback(inputManager, message, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); break; case WM_SIZE: ResizeCallback(window, LOWORD(lParam), HIWORD(lParam)); break; case WM_SOCKET: if (WSAGETSELECTERROR(lParam)) { ServerCloseCallback(serverManager, (SOCKET)wParam); break; } switch (WSAGETSELECTEVENT(lParam)) { case FD_READ: ServerPacketCallback(serverManager, (SOCKET)wParam); break; case FD_CLOSE: ServerCloseCallback(serverManager, (SOCKET)wParam); break; } default: result = DefWindowProc(hWnd, message, wParam, lParam); } return result; } void Window::SetVsnyc(bool enabled) { m_properties.vsync = enabled; } void Window::SetEventCallback(const WindowEventCallback& callback) { m_eventCallback = callback; m_inputManager->SetEventCallback(m_eventCallback); m_serverManager->SetEventCallback(m_eventCallback); } void ResizeCallback(Window* window, int width, int height) { window->m_properties.width = width; window->m_properties.height = height; if (window->m_eventCallback) window->m_eventCallback(events::ResizeEvent((unsigned int)width, (unsigned int)height)); } void FocusCallback(Window* window, bool focused) { // 포커싱 또는 포커싱을 잃었을때 작업하는 함수 } }
34.191558
126
0.590827
adunStudio
fa9b9569e128e6765cfef8410ef41af5fe873ef2
600
hpp
C++
include/gui/gui_manager.hpp
kodo-pp/IVR
e904341d1850baf81e8aeecbf498691fbe8e50aa
[ "MIT" ]
null
null
null
include/gui/gui_manager.hpp
kodo-pp/IVR
e904341d1850baf81e8aeecbf498691fbe8e50aa
[ "MIT" ]
8
2018-05-26T19:27:53.000Z
2018-10-28T19:31:33.000Z
include/gui/gui_manager.hpp
kodo-pp/IVR
e904341d1850baf81e8aeecbf498691fbe8e50aa
[ "MIT" ]
1
2019-05-07T15:32:38.000Z
2019-05-07T15:32:38.000Z
#ifndef GUI_GUI_MANAGER_HPP #define GUI_GUI_MANAGER_HPP #include <unordered_set> #include <modbox/gui/gui.hpp> /** * Manages GUI elements * * WARNING: should be instantiated only once */ class GuiManager { public: GuiManager(std::unordered_set<GuiElement> _guiElements); virtual ~GuiManager(); void drawAll(); void addGuiElement(GuiElement elem); void removeGuiElement(GuiElement elem); protected: std::unordered_set<GuiElement> guiElements; }; // The only instance of this class extern GuiManager guiManager; #endif /* end of include guard: GUI_GUI_MANAGER_HPP */
19.354839
60
0.743333
kodo-pp
b7049d549d8582f8a0b6737ba1d93c8034ecf9ea
17,549
cpp
C++
ardupilot/libraries/AP_Motors/AP_MotorsMatrix.cpp
quadrotor-IITKgp/emulate_GPS
3c888d5b27b81fb17e74d995370f64bdb110fb65
[ "MIT" ]
1
2021-07-17T11:37:16.000Z
2021-07-17T11:37:16.000Z
ardupilot/libraries/AP_Motors/AP_MotorsMatrix.cpp
arl-kgp/emulate_GPS
3c888d5b27b81fb17e74d995370f64bdb110fb65
[ "MIT" ]
null
null
null
ardupilot/libraries/AP_Motors/AP_MotorsMatrix.cpp
arl-kgp/emulate_GPS
3c888d5b27b81fb17e74d995370f64bdb110fb65
[ "MIT" ]
null
null
null
// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- /* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AP_MotorsMatrix.cpp - ArduCopter motors library * Code by RandyMackay. DIYDrones.com * */ #include <AP_HAL/AP_HAL.h> #include "AP_MotorsMatrix.h" extern const AP_HAL::HAL& hal; // Init void AP_MotorsMatrix::Init() { // setup the motors setup_motors(); // enable fast channels or instant pwm set_update_rate(_speed_hz); } // set update rate to motors - a value in hertz void AP_MotorsMatrix::set_update_rate( uint16_t speed_hz ) { uint8_t i; // record requested speed _speed_hz = speed_hz; // check each enabled motor uint32_t mask = 0; for( i=0; i<AP_MOTORS_MAX_NUM_MOTORS; i++ ) { if( motor_enabled[i] ) { mask |= 1U << i; } } hal.rcout->set_freq( mask, _speed_hz ); } // set frame orientation (normally + or X) void AP_MotorsMatrix::set_frame_orientation( uint8_t new_orientation ) { // return if nothing has changed if( new_orientation == _flags.frame_orientation ) { return; } // call parent AP_Motors::set_frame_orientation( new_orientation ); // setup the motors setup_motors(); // enable fast channels or instant pwm set_update_rate(_speed_hz); } // enable - starts allowing signals to be sent to motors void AP_MotorsMatrix::enable() { int8_t i; // enable output channels for( i=0; i<AP_MOTORS_MAX_NUM_MOTORS; i++ ) { if( motor_enabled[i] ) { hal.rcout->enable_ch(i); } } } // output_min - sends minimum values out to the motors void AP_MotorsMatrix::output_min() { int8_t i; // set limits flags limit.roll_pitch = true; limit.yaw = true; limit.throttle_lower = true; limit.throttle_upper = false; // fill the motor_out[] array for HIL use and send minimum value to each motor hal.rcout->cork(); for( i=0; i<AP_MOTORS_MAX_NUM_MOTORS; i++ ) { if( motor_enabled[i] ) { hal.rcout->write(i, _throttle_radio_min); } } hal.rcout->push(); } // get_motor_mask - returns a bitmask of which outputs are being used for motors (1 means being used) // this can be used to ensure other pwm outputs (i.e. for servos) do not conflict uint16_t AP_MotorsMatrix::get_motor_mask() { uint16_t mask = 0; for (uint8_t i=0; i<AP_MOTORS_MAX_NUM_MOTORS; i++) { if (motor_enabled[i]) { mask |= 1U << i; } } return mask; } void AP_MotorsMatrix::output_armed_not_stabilizing() { uint8_t i; int16_t throttle_radio_output; // total throttle pwm value, summed onto throttle channel minimum, typically ~1100-1900 int16_t motor_out[AP_MOTORS_MAX_NUM_MOTORS]; // final outputs sent to the motors int16_t out_min_pwm = _throttle_radio_min + _min_throttle; // minimum pwm value we can send to the motors int16_t out_max_pwm = _throttle_radio_max; // maximum pwm value we can send to the motors // initialize limits flags limit.roll_pitch = true; limit.yaw = true; limit.throttle_lower = false; limit.throttle_upper = false; int16_t thr_in_min = rel_pwm_to_thr_range(_spin_when_armed_ramped); if (_throttle_control_input <= thr_in_min) { _throttle_control_input = thr_in_min; limit.throttle_lower = true; } if (_throttle_control_input >= _hover_out) { _throttle_control_input = _hover_out; limit.throttle_upper = true; } throttle_radio_output = calc_throttle_radio_output(); // set output throttle for (i=0; i<AP_MOTORS_MAX_NUM_MOTORS; i++) { if (motor_enabled[i]) { motor_out[i] = throttle_radio_output; } } if(throttle_radio_output >= out_min_pwm) { // apply thrust curve and voltage scaling for (i=0; i<AP_MOTORS_MAX_NUM_MOTORS; i++) { if (motor_enabled[i]) { motor_out[i] = apply_thrust_curve_and_volt_scaling(motor_out[i], out_min_pwm, out_max_pwm); } } } // send output to each motor hal.rcout->cork(); for( i=0; i<AP_MOTORS_MAX_NUM_MOTORS; i++ ) { if( motor_enabled[i] ) { hal.rcout->write(i, motor_out[i]); } } hal.rcout->push(); } // output_armed - sends commands to the motors // includes new scaling stability patch // TODO pull code that is common to output_armed_not_stabilizing into helper functions void AP_MotorsMatrix::output_armed_stabilizing() { int8_t i; int16_t roll_pwm; // roll pwm value, initially calculated by calc_roll_pwm() but may be modified after, +/- 400 int16_t pitch_pwm; // pitch pwm value, initially calculated by calc_roll_pwm() but may be modified after, +/- 400 int16_t yaw_pwm; // yaw pwm value, initially calculated by calc_yaw_pwm() but may be modified after, +/- 400 int16_t throttle_radio_output; // total throttle pwm value, summed onto throttle channel minimum, typically ~1100-1900 int16_t out_min_pwm = _throttle_radio_min + _min_throttle; // minimum pwm value we can send to the motors int16_t out_max_pwm = _throttle_radio_max; // maximum pwm value we can send to the motors int16_t out_mid_pwm = (out_min_pwm+out_max_pwm)/2; // mid pwm value we can send to the motors int16_t out_best_thr_pwm; // the is the best throttle we can come up which provides good control without climbing float rpy_scale = 1.0; // this is used to scale the roll, pitch and yaw to fit within the motor limits int16_t rpy_out[AP_MOTORS_MAX_NUM_MOTORS]; // buffer so we don't have to multiply coefficients multiple times. int16_t motor_out[AP_MOTORS_MAX_NUM_MOTORS]; // final outputs sent to the motors int16_t rpy_low = 0; // lowest motor value int16_t rpy_high = 0; // highest motor value int16_t yaw_allowed; // amount of yaw we can fit in int16_t thr_adj; // the difference between the pilot's desired throttle and out_best_thr_pwm (the throttle that is actually provided) // initialize limits flags limit.roll_pitch = false; limit.yaw = false; limit.throttle_lower = false; limit.throttle_upper = false; // Ensure throttle is within bounds of 0 to 1000 int16_t thr_in_min = rel_pwm_to_thr_range(_min_throttle); if (_throttle_control_input <= thr_in_min) { _throttle_control_input = thr_in_min; limit.throttle_lower = true; } if (_throttle_control_input >= _max_throttle) { _throttle_control_input = _max_throttle; limit.throttle_upper = true; } roll_pwm = calc_roll_pwm(); pitch_pwm = calc_pitch_pwm(); yaw_pwm = calc_yaw_pwm(); throttle_radio_output = calc_throttle_radio_output(); // calculate roll and pitch for each motor // set rpy_low and rpy_high to the lowest and highest values of the motors for (i=0; i<AP_MOTORS_MAX_NUM_MOTORS; i++) { if (motor_enabled[i]) { rpy_out[i] = roll_pwm * _roll_factor[i] * get_compensation_gain() + pitch_pwm * _pitch_factor[i] * get_compensation_gain(); // record lowest roll pitch command if (rpy_out[i] < rpy_low) { rpy_low = rpy_out[i]; } // record highest roll pich command if (rpy_out[i] > rpy_high) { rpy_high = rpy_out[i]; } } } // calculate throttle that gives most possible room for yaw (range 1000 ~ 2000) which is the lower of: // 1. mid throttle - average of highest and lowest motor (this would give the maximum possible room margin above the highest motor and below the lowest) // 2. the higher of: // a) the pilot's throttle input // b) the mid point between the pilot's input throttle and hover-throttle // Situation #2 ensure we never increase the throttle above hover throttle unless the pilot has commanded this. // Situation #2b allows us to raise the throttle above what the pilot commanded but not so far that it would actually cause the copter to rise. // We will choose #1 (the best throttle for yaw control) if that means reducing throttle to the motors (i.e. we favour reducing throttle *because* it provides better yaw control) // We will choose #2 (a mix of pilot and hover throttle) only when the throttle is quite low. We favour reducing throttle instead of better yaw control because the pilot has commanded it int16_t motor_mid = (rpy_low+rpy_high)/2; out_best_thr_pwm = min(out_mid_pwm - motor_mid, max(throttle_radio_output, throttle_radio_output*max(0,1.0f-_throttle_thr_mix)+get_hover_throttle_as_pwm()*_throttle_thr_mix)); // calculate amount of yaw we can fit into the throttle range // this is always equal to or less than the requested yaw from the pilot or rate controller yaw_allowed = min(out_max_pwm - out_best_thr_pwm, out_best_thr_pwm - out_min_pwm) - (rpy_high-rpy_low)/2; yaw_allowed = max(yaw_allowed, _yaw_headroom); if (yaw_pwm >= 0) { // if yawing right if (yaw_allowed > yaw_pwm * get_compensation_gain()) { yaw_allowed = yaw_pwm * get_compensation_gain(); // to-do: this is bad form for yaw_allows to change meaning to become the amount that we are going to output }else{ limit.yaw = true; } }else{ // if yawing left yaw_allowed = -yaw_allowed; if (yaw_allowed < yaw_pwm * get_compensation_gain()) { yaw_allowed = yaw_pwm * get_compensation_gain(); // to-do: this is bad form for yaw_allows to change meaning to become the amount that we are going to output }else{ limit.yaw = true; } } // add yaw to intermediate numbers for each motor rpy_low = 0; rpy_high = 0; for (i=0; i<AP_MOTORS_MAX_NUM_MOTORS; i++) { if (motor_enabled[i]) { rpy_out[i] = rpy_out[i] + yaw_allowed * _yaw_factor[i]; // record lowest roll+pitch+yaw command if( rpy_out[i] < rpy_low ) { rpy_low = rpy_out[i]; } // record highest roll+pitch+yaw command if( rpy_out[i] > rpy_high) { rpy_high = rpy_out[i]; } } } // check everything fits thr_adj = throttle_radio_output - out_best_thr_pwm; // calculate upper and lower limits of thr_adj int16_t thr_adj_max = max(out_max_pwm-(out_best_thr_pwm+rpy_high),0); // if we are increasing the throttle (situation #2 above).. if (thr_adj > 0) { // increase throttle as close as possible to requested throttle // without going over out_max_pwm if (thr_adj > thr_adj_max){ thr_adj = thr_adj_max; // we haven't even been able to apply full throttle command limit.throttle_upper = true; } }else if(thr_adj < 0){ // decrease throttle as close as possible to requested throttle // without going under out_min_pwm or over out_max_pwm // earlier code ensures we can't break both boundaries int16_t thr_adj_min = min(out_min_pwm-(out_best_thr_pwm+rpy_low),0); if (thr_adj > thr_adj_max) { thr_adj = thr_adj_max; limit.throttle_upper = true; } if (thr_adj < thr_adj_min) { thr_adj = thr_adj_min; } } // do we need to reduce roll, pitch, yaw command // earlier code does not allow both limit's to be passed simultaneously with abs(_yaw_factor)<1 if ((rpy_low+out_best_thr_pwm)+thr_adj < out_min_pwm){ // protect against divide by zero if (rpy_low != 0) { rpy_scale = (float)(out_min_pwm-thr_adj-out_best_thr_pwm)/rpy_low; } // we haven't even been able to apply full roll, pitch and minimal yaw without scaling limit.roll_pitch = true; limit.yaw = true; }else if((rpy_high+out_best_thr_pwm)+thr_adj > out_max_pwm){ // protect against divide by zero if (rpy_high != 0) { rpy_scale = (float)(out_max_pwm-thr_adj-out_best_thr_pwm)/rpy_high; } // we haven't even been able to apply full roll, pitch and minimal yaw without scaling limit.roll_pitch = true; limit.yaw = true; } // add scaled roll, pitch, constrained yaw and throttle for each motor for (i=0; i<AP_MOTORS_MAX_NUM_MOTORS; i++) { if (motor_enabled[i]) { motor_out[i] = out_best_thr_pwm+thr_adj + rpy_scale*rpy_out[i]; } } // apply thrust curve and voltage scaling for (i=0; i<AP_MOTORS_MAX_NUM_MOTORS; i++) { if (motor_enabled[i]) { motor_out[i] = apply_thrust_curve_and_volt_scaling(motor_out[i], out_min_pwm, out_max_pwm); } } // clip motor output if required (shouldn't be) for (i=0; i<AP_MOTORS_MAX_NUM_MOTORS; i++) { if (motor_enabled[i]) { motor_out[i] = constrain_int16(motor_out[i], out_min_pwm, out_max_pwm); } } // send output to each motor hal.rcout->cork(); for( i=0; i<AP_MOTORS_MAX_NUM_MOTORS; i++ ) { if( motor_enabled[i] ) { hal.rcout->write(i, motor_out[i]); } } hal.rcout->push(); } // output_disarmed - sends commands to the motors void AP_MotorsMatrix::output_disarmed() { // Send minimum values to all motors output_min(); } // output_test - spin a motor at the pwm value specified // motor_seq is the motor's sequence number from 1 to the number of motors on the frame // pwm value is an actual pwm value that will be output, normally in the range of 1000 ~ 2000 void AP_MotorsMatrix::output_test(uint8_t motor_seq, int16_t pwm) { // exit immediately if not armed if (!armed()) { return; } // loop through all the possible orders spinning any motors that match that description hal.rcout->cork(); for (uint8_t i=0; i<AP_MOTORS_MAX_NUM_MOTORS; i++) { if (motor_enabled[i] && _test_order[i] == motor_seq) { // turn on this motor hal.rcout->write(i, pwm); } } hal.rcout->push(); } // add_motor void AP_MotorsMatrix::add_motor_raw(int8_t motor_num, float roll_fac, float pitch_fac, float yaw_fac, uint8_t testing_order) { // ensure valid motor number is provided if( motor_num >= 0 && motor_num < AP_MOTORS_MAX_NUM_MOTORS ) { // increment number of motors if this motor is being newly motor_enabled if( !motor_enabled[motor_num] ) { motor_enabled[motor_num] = true; } // set roll, pitch, thottle factors and opposite motor (for stability patch) _roll_factor[motor_num] = roll_fac; _pitch_factor[motor_num] = pitch_fac; _yaw_factor[motor_num] = yaw_fac; // set order that motor appears in test _test_order[motor_num] = testing_order; // disable this channel from being used by RC_Channel_aux RC_Channel_aux::disable_aux_channel(motor_num); } } // add_motor using just position and prop direction - assumes that for each motor, roll and pitch factors are equal void AP_MotorsMatrix::add_motor(int8_t motor_num, float angle_degrees, float yaw_factor, uint8_t testing_order) { add_motor(motor_num, angle_degrees, angle_degrees, yaw_factor, testing_order); } // add_motor using position and prop direction. Roll and Pitch factors can differ (for asymmetrical frames) void AP_MotorsMatrix::add_motor(int8_t motor_num, float roll_factor_in_degrees, float pitch_factor_in_degrees, float yaw_factor, uint8_t testing_order) { add_motor_raw( motor_num, cosf(radians(roll_factor_in_degrees + 90)), cosf(radians(pitch_factor_in_degrees)), yaw_factor, testing_order); } // remove_motor - disabled motor and clears all roll, pitch, throttle factors for this motor void AP_MotorsMatrix::remove_motor(int8_t motor_num) { // ensure valid motor number is provided if( motor_num >= 0 && motor_num < AP_MOTORS_MAX_NUM_MOTORS ) { // disable the motor, set all factors to zero motor_enabled[motor_num] = false; _roll_factor[motor_num] = 0; _pitch_factor[motor_num] = 0; _yaw_factor[motor_num] = 0; } } // remove_all_motors - removes all motor definitions void AP_MotorsMatrix::remove_all_motors() { for( int8_t i=0; i<AP_MOTORS_MAX_NUM_MOTORS; i++ ) { remove_motor(i); } }
38.15
196
0.647729
quadrotor-IITKgp
b709c7b500a0492d0c671d56147ebbf9410e0376
2,042
cpp
C++
src/xercesc/util/Compilers/OS400SetDefs.cpp
rherardi/xerces-c-src_2_7_0
a23711292bba70519940d7e6aeb07100319b607c
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/xercesc/util/Compilers/OS400SetDefs.cpp
rherardi/xerces-c-src_2_7_0
a23711292bba70519940d7e6aeb07100319b607c
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/xercesc/util/Compilers/OS400SetDefs.cpp
rherardi/xerces-c-src_2_7_0
a23711292bba70519940d7e6aeb07100319b607c
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright 1999-2000,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: OS400SetDefs.cpp 191054 2005-06-17 02:56:35Z jberry $ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <sys/types.h> #include <ctype.h> int strcasecmp (const char *string1,const char * string2) { char *s1, *s2; int result; s1 = (char *)string1; s2 = (char *)string2; while ((result = tolower (*s1) - tolower (*s2)) == 0) { if (*s1++ == '\0') return 0; s2++; } return (result); } int strncasecmp (const char *string1,const char *string2,size_t count) { register char *s1, *s2; register int r; register unsigned int rcount; rcount = (unsigned int) count; if (rcount > 0) { s1 = (char *)string1; s2 = (char *)string2; do { if ((r = tolower (*s1) - tolower (*s2)) != 0) return r; if (*s1++ == '\0') break; s2++; } while (--rcount != 0); } return (0); } /* des not appear as though the following is needed */ #ifndef __OS400__ int stricmp(const char* str1, const char* str2) { return strcasecmp(str1, str2); } int strnicmp(const char* str1, const char* str2, const unsigned int count) { if (count == 0) return 0; return strncasecmp( str1, str2, (size_t)count); } #endif
24.902439
79
0.561704
rherardi
b70d3602bc5861b554330ee86a5a93f71674d0ac
1,542
cpp
C++
leetcode/480_Sliding-Window-Median/MedianSlidingWindow.cpp
chasingegg/Online_Judge
8a3f4b5b207cbeda921c743a527a25bf9c7b6248
[ "MIT" ]
1
2017-10-13T10:34:46.000Z
2017-10-13T10:34:46.000Z
leetcode/480_Sliding-Window-Median/MedianSlidingWindow.cpp
chasingegg/Online_Judge
8a3f4b5b207cbeda921c743a527a25bf9c7b6248
[ "MIT" ]
null
null
null
leetcode/480_Sliding-Window-Median/MedianSlidingWindow.cpp
chasingegg/Online_Judge
8a3f4b5b207cbeda921c743a527a25bf9c7b6248
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include <set> using namespace std; class Solution { public: vector<double> medianSlidingWindow(vector<int>& nums, int k) { vector<double> result; int n = nums.size(); if (n == 0) return result; multiset<double> max, min; for (int i = 0; i < k; ++i) max.insert(nums[i]); for (int i = 0; i < k/2; ++i) { min.insert(*max.rbegin()); // 删除 第一个大于等于某个键的迭代器,如果没有就删除末端元素 max.erase(max.lower_bound(*max.rbegin())); } for (int i = k; i < n; ++i) { if(k % 2 ) result.push_back(*max.rbegin()); else result.push_back((*max.rbegin() + *min.begin()) / 2); if (max.find(nums[i-k]) != max.end()) { max.erase(max.find(nums[i-k])); max.insert(nums[i]); } else { min.erase(min.find(nums[i-k])); min.insert(nums[i]); } if (max.size() > 0 && min.size() > 0 && *max.rbegin() > *min.begin()) { int tmp = *max.rbegin(); max.erase(max.lower_bound(*max.rbegin())); max.insert(*min.begin()); min.erase(min.begin()); min.insert(tmp); } } if(k % 2 ) result.push_back(*max.rbegin()); else result.push_back((*max.rbegin() + *min.begin()) / 2); return result; } };
29.653846
83
0.446174
chasingegg
b710336e07b0b9bf6a9d9ce277efd5d7fb416817
221
cpp
C++
src/actionscript/extern.cpp
feliwir/libapt
43b05b3de632896cb7d1351191a07c0f0cdf801a
[ "MIT" ]
7
2016-12-19T21:13:41.000Z
2021-03-19T11:14:29.000Z
src/actionscript/extern.cpp
feliwir/libapt
43b05b3de632896cb7d1351191a07c0f0cdf801a
[ "MIT" ]
1
2017-06-17T12:14:08.000Z
2017-06-17T14:47:20.000Z
src/actionscript/extern.cpp
feliwir/libapt
43b05b3de632896cb7d1351191a07c0f0cdf801a
[ "MIT" ]
3
2017-11-07T12:22:10.000Z
2020-04-30T20:48:59.000Z
#include "extern.hpp" using namespace libapt; using namespace libapt::as; Value Extern::GetProperty(const std::string & property) { return Value(); } void Extern::SetProperty(const std::string & property, Value v) { }
17
63
0.733032
feliwir
b711c7ee3b83ff7e90973f9174d5ef31e350fb28
1,463
cpp
C++
src/libraries/core/interpolation/surfaceInterpolation/schemes/reverseLinear/reverseLinear.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/interpolation/surfaceInterpolation/schemes/reverseLinear/reverseLinear.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/interpolation/surfaceInterpolation/schemes/reverseLinear/reverseLinear.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CAELUS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CAELUS. If not, see <http://www.gnu.org/licenses/>. Description Reverse-central-differencing interpolation scheme class which is a linear scheme but uses 1 - weighting factors. Currently the sole use of this scheme is as the basis of harmonic interpolation. \*---------------------------------------------------------------------------*/ #include "fvMesh.hpp" #include "reverseLinear.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { makeSurfaceInterpolationScheme(reverseLinear) } // ************************************************************************* //
36.575
79
0.544771
MrAwesomeRocks
b711e7c11ff601db91700d6e00c83529e7742b52
20,780
hpp
C++
src/ttauri/bigint.hpp
RustWorks/ttauri
4b093eb16465091d01d80159e23fd26e5d4e4c03
[ "BSL-1.0" ]
279
2021-02-17T09:53:40.000Z
2022-03-22T04:08:40.000Z
src/ttauri/bigint.hpp
RustWorks/ttauri
4b093eb16465091d01d80159e23fd26e5d4e4c03
[ "BSL-1.0" ]
269
2021-02-17T12:53:15.000Z
2022-03-29T22:10:49.000Z
src/ttauri/bigint.hpp
sthagen/ttauri
772f4e55c007e0bc199a07d86ef4e2d4d46af139
[ "BSL-1.0" ]
25
2021-02-17T17:14:10.000Z
2022-03-16T04:13:00.000Z
// Copyright Take Vos 2019-2020. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) #pragma once #include "strings.hpp" #include "math.hpp" #include "int_carry.hpp" #include "codec/base_n.hpp" #include <format> #include <type_traits> #include <ostream> #include <concepts> namespace tt::inline v1 { /** High performance big integer implementation. * The bigint is a fixed width integer which will allow the compiler * to make aggressive optimizations, unrolling most loops and easy inlining. */ template<std::unsigned_integral DigitType, std::size_t NumDigits, bool IsSigned> struct bigint { using digit_type = DigitType; using signed_digit_type = std::make_signed_t<digit_type>; static constexpr auto num_digits = NumDigits; static constexpr auto is_signed = IsSigned; static constexpr auto bits_per_digit = sizeof(digit_type) * CHAR_BIT; static constexpr digit_type zero_digit = 0; static constexpr digit_type min1_digit = static_cast<digit_type>(signed_digit_type{-1}); /** Digits, in little endian order. */ digit_type digits[num_digits]; /** Construct and clear an bigint. */ constexpr bigint() noexcept { for (std::size_t i = 0; i != num_digits; ++i) { digits[i] = zero_digit; } } constexpr bigint(bigint const &) noexcept = default; constexpr bigint &operator=(bigint const &) noexcept = default; constexpr bigint(bigint &&) noexcept = default; constexpr bigint &operator=(bigint &&) noexcept = default; /** Construct from a small bigint. */ template<std::size_t N, bool S> constexpr bigint(bigint<digit_type, N, S> const &rhs) noexcept requires(N < num_digits) { std::size_t i = 0; // Copy the data from a smaller bigint. for (; i != N; ++i) { digits[i] = rhs.digits[i]; } // Sign extent the most-siginificant-digit. ttlet sign = rhs.is_negative() ? min1_digit : zero_digit; for (; i != num_digits; ++i) { digits[i] = sign; } } /** Assign from a small bigint. */ template<std::size_t N, bool S> constexpr bigint &operator=(bigint<digit_type, N, S> const &rhs) noexcept requires(N < num_digits) { std::size_t i = 0; // Copy the data from a smaller bigint. for (; i != N; ++i) { digits[i] = rhs.digits[i]; } // Sign extent the most-siginificant-digit. ttlet sign = rhs.is_negative() ? min1_digit : zero_digit; for (; i != num_digits; ++i) { digits[i] = sign; } return *this; } constexpr bigint(std::integral auto value) noexcept { static_assert(sizeof(value) <= sizeof(digit_type)); static_assert(num_digits > 0); if constexpr (std::is_signed_v<decltype(value)>) { // Sign extent the value to the size of the first digit. digits[0] = static_cast<digit_type>(static_cast<signed_digit_type>(value)); } else { digits[0] = static_cast<digit_type>(value); } // Sign extent to the rest of the digits. ttlet sign = value < 0 ? min1_digit : zero_digit; for (std::size_t i = 1; i != num_digits; ++i) { digits[i] = sign; } } constexpr bigint &operator=(std::integral auto value) noexcept { static_assert(sizeof(value) <= sizeof(digit_type)); static_assert(num_digits > 0); if constexpr (std::is_signed_v<decltype(value)>) { // Sign extent the value to the size of the first digit. digits[0] = static_cast<digit_type>(static_cast<signed_digit_type>(value)); } else { digits[0] = static_cast<digit_type>(value); } // Sign extent to the rest of the digits. ttlet sign = value < 0 ? min1_digit : zero_digit; for (std::size_t i = 1; i != num_digits; ++i) { digits[i] = sign; } return *this; } constexpr explicit bigint(std::string_view str, int base = 10) noexcept : bigint() { std::size_t i = 0; for (; i < str.size(); ++i) { (*this) *= base; (*this) += base16::int_from_char<int>(str[i]); } } constexpr explicit operator unsigned long long() const noexcept { return static_cast<unsigned long long>(digits[0]); } constexpr explicit operator signed long long() const noexcept { return static_cast<signed long long>(digits[0]); } constexpr explicit operator unsigned long() const noexcept { return static_cast<unsigned long>(digits[0]); } constexpr explicit operator signed long() const noexcept { return static_cast<signed long>(digits[0]); } constexpr explicit operator unsigned int() const noexcept { return static_cast<unsigned int>(digits[0]); } constexpr explicit operator signed int() const noexcept { return static_cast<signed int>(digits[0]); } constexpr explicit operator unsigned short() const noexcept { return static_cast<unsigned short>(digits[0]); } constexpr explicit operator signed short() const noexcept { return static_cast<signed short>(digits[0]); } constexpr explicit operator unsigned char() const noexcept { return static_cast<unsigned char>(digits[0]); } constexpr explicit operator signed char() const noexcept { return static_cast<signed char>(digits[0]); } constexpr explicit operator bool() const noexcept { for (std::size_t i = 0; i != num_digits; ++i) { if (digits[i] != 0) { return true; } } return false; } [[nodiscard]] constexpr bool is_negative() const noexcept { if constexpr (is_signed and num_digits > 0) { return static_cast<signed_digit_type>(digits[num_digits - 1]) < 0; } else { return false; } } template<std::size_t N, bool S> constexpr explicit operator bigint<digit_type, N, S>() const noexcept { auto r = bigint<digit_type, N, S>{}; ttlet sign = is_negative() ? min1_digit : zero_digit; for (auto i = 0; i != N; ++i) { r.digits[i] = i < num_digits ? digits[i] : sign; } return r; } std::string string() const noexcept { constexpr auto oneOver10 = reciprocal(bigint<digit_type, num_digits * 2, is_signed>{10}); auto tmp = *this; std::string r; if (tmp == 0) { r = "0"; } else { while (tmp > 0) { bigint remainder; std::tie(tmp, remainder) = div(tmp, bigint{10}, oneOver10); r += (static_cast<unsigned char>(remainder) + '0'); } } std::reverse(r.begin(), r.end()); return r; } std::string uuid_string() const noexcept { static_assert( std::is_same_v<digit_type, uint64_t> && num_digits == 2, "uuid_string should only be called on a uuid compatible type"); return std::format( "{:08x}-{:04x}-{:04x}-{:04x}-{:012x}", static_cast<uint32_t>(digits[1] >> 32), static_cast<uint16_t>(digits[1] >> 16), static_cast<uint16_t>(digits[1]), static_cast<uint16_t>(digits[0] >> 48), digits[0] & 0x0000ffff'ffffffffULL); } [[nodiscard]] constexpr bigint operator-() const noexcept { bigint r; neg_carry_chain(r.digits, digits, num_digits); return r; } constexpr bigint &operator<<=(std::size_t rhs) noexcept { sll_carry_chain(digits, digits, rhs, num_digits); return *this; } constexpr bigint &operator>>=(std::size_t rhs) noexcept { if constexpr (is_signed) { sra_carry_chain(digits, digits, rhs, num_digits); } else { srl_carry_chain(digits, digits, rhs, num_digits); } return *this; } constexpr bigint &operator*=(bigint const &rhs) noexcept { auto r = bigint{0}; mul_carry_chain(r.digits, digits, rhs.digits, num_digits); *this = r; return *this; } constexpr bigint &operator+=(bigint const &rhs) noexcept { add_carry_chain(digits, digits, rhs.digits, num_digits); return *this; } constexpr bigint &operator-=(bigint const &rhs) noexcept { sub_carry_chain(digits, digits, rhs.digits, num_digits); return *this; } constexpr bigint &operator&=(bigint const &rhs) noexcept { and_carry_chain(digits, digits, rhs.digits, num_digits); return *this; } constexpr bigint &operator|=(bigint const &rhs) noexcept { or_carry_chain(digits, digits, rhs.digits, num_digits); return *this; } constexpr bigint &operator^=(bigint const &rhs) noexcept { xor_carry_chain(digits, digits, rhs.digits, num_digits); return *this; } static bigint from_big_endian(uint8_t const *data) noexcept { auto r = bigint{}; for (ssize_t i = static_cast<ssize_t>(num_digits) - 1; i >= 0; i--) { digit_type d = 0; for (std::size_t j = 0; j < sizeof(digit_type); j++) { d <<= 8; d |= *(data++); } r.digits[i] = d; } return r; } static bigint from_little_endian(uint8_t const *data) noexcept { auto r = bigint{}; for (int i = 0; i < num_digits; ++i) { digit_type d = 0; for (std::size_t j = 0; j < sizeof(digit_type); j++) { d |= static_cast<digit_type>(*(data++)) << (j * 8); } r.digits[i] = d; } return r; } static bigint from_big_endian(void const *data) noexcept { return from_big_endian(static_cast<uint8_t const *>(data)); } static bigint from_little_endian(void const *data) noexcept { return from_little_endian(static_cast<uint8_t const *>(data)); } /*! Calculate the remainder of a CRC check. * \param r Return value, the remainder. * \param lhs The number to check. * \param rhs Polynomial. */ [[nodiscard]] constexpr friend bigint crc(bigint const &lhs, bigint const &rhs) noexcept requires(not is_signed) { ttlet polynomialOrder = bsr_carry_chain(rhs.digits, rhs.num_digits); tt_assert(polynomialOrder >= 0); auto tmp = static_cast<bigint<digit_type, 2 * num_digits>>(lhs) << polynomialOrder; auto rhs_ = static_cast<bigint<digit_type, 2 * num_digits>>(rhs); auto tmp_highest_bit = bsr_carry_chain(tmp.digits, tmp.num_digits); while (tmp_highest_bit >= polynomialOrder) { ttlet divident = rhs_ << (tmp_highest_bit - polynomialOrder); tmp ^= divident; tmp_highest_bit = bsr_carry_chain(tmp.digits, tmp.num_digits); } return static_cast<bigint>(tmp); } /*! Calculate the reciprocal at a certain precision. * * N should be two times the size of the eventual numerator. * * \param divider The divider of 1. * \return (1 << (K*sizeof(T)*8)) / divider */ [[nodiscard]] constexpr friend bigint reciprocal(bigint const &rhs) { auto r = bigint<digit_type, num_digits + 1, is_signed>(0); r.digits[num_digits] = 1; return static_cast<bigint>(r / rhs); } [[nodiscard]] constexpr friend bool operator==(bigint const &lhs, bigint const &rhs) noexcept { return eq_carry_chain(lhs.digits, rhs.digits, lhs.num_digits); } [[nodiscard]] constexpr friend std::strong_ordering operator<=>(bigint const &lhs, bigint const &rhs) noexcept { if constexpr (lhs.is_signed or rhs.is_signed) { return cmp_signed_carry_chain(lhs.digits, rhs.digits, lhs.num_digits); } else { return cmp_unsigned_carry_chain(lhs.digits, rhs.digits, lhs.num_digits); } } [[nodiscard]] constexpr friend bigint operator<<(bigint const &lhs, std::size_t rhs) noexcept { auto r = bigint{}; sll_carry_chain(r.digits, lhs.digits, rhs, lhs.num_digits); return r; } [[nodiscard]] constexpr friend bigint operator>>(bigint const &lhs, std::size_t rhs) noexcept { auto r = bigint{}; if constexpr (lhs.is_signed) { sra_carry_chain(r.digits, lhs.digits, rhs, lhs.num_digits); } else { srl_carry_chain(r.digits, lhs.digits, rhs, lhs.num_digits); } return r; } [[nodiscard]] constexpr friend bigint operator*(bigint const &lhs, bigint const &rhs) noexcept { auto r = bigint{}; mul_carry_chain(r.digits, lhs.digits, rhs.digits, lhs.num_digits); return r; } [[nodiscard]] constexpr friend bigint operator+(bigint const &lhs, bigint const &rhs) noexcept { auto r = bigint{}; add_carry_chain(r.digits, lhs.digits, rhs.digits, lhs.num_digits); return r; } [[nodiscard]] constexpr friend bigint operator-(bigint const &lhs, bigint const &rhs) noexcept { auto r = bigint{}; sub_carry_chain(r.digits, lhs.digits, rhs.digits, lhs.num_digits); return r; } [[nodiscard]] constexpr friend bigint operator~(bigint const &rhs) noexcept { auto r = bigint{}; invert_carry_chain(r.digits, rhs.digits, rhs.num_digits); return r; } [[nodiscard]] constexpr friend bigint operator|(bigint const &lhs, bigint const &rhs) noexcept { auto r = bigint{}; or_carry_chain(r.digits, lhs.digits, rhs.digits, lhs.num_digits); return r; } [[nodiscard]] constexpr friend bigint operator&(bigint const &lhs, bigint const &rhs) noexcept { auto r = bigint{}; and_carry_chain(r.digits, lhs.digits, rhs.digits, lhs.num_digits); return r; } [[nodiscard]] constexpr friend bigint operator^(bigint const &lhs, bigint const &rhs) noexcept { auto r = bigint{}; xor_carry_chain(r.digits, lhs.digits, rhs.digits, lhs.num_digits); return r; } [[nodiscard]] constexpr friend std::pair<bigint, bigint> div(bigint const &lhs, bigint const &rhs) noexcept { auto quotient = bigint{}; auto remainder = bigint{}; if constexpr (is_signed) { signed_div_carry_chain(quotient.digits, remainder.digits, lhs.digits, rhs.digits, lhs.num_digits); } else { div_carry_chain(quotient.digits, remainder.digits, lhs.digits, rhs.digits, lhs.num_digits); } return std::pair{quotient, remainder}; } [[nodiscard]] constexpr friend std::pair<bigint, bigint> div(bigint const &lhs, bigint const &rhs, bigint<digit_type, 2 * num_digits, is_signed> const &rhs_reciprocal) noexcept requires(not is_signed) { constexpr auto nr_bits = num_digits * bits_per_digit; using bigint_x3_type = bigint<digit_type, 3 * num_digits, is_signed>; auto quotient = bigint_x3_type{lhs} * bigint_x3_type{rhs_reciprocal}; quotient >>= (2 * nr_bits); auto product = bigint_x3_type{quotient} * bigint_x3_type{rhs}; tt_axiom(product <= lhs); auto remainder = lhs - product; int retry = 0; while (remainder >= rhs) { if (retry++ > 3) { return div(lhs, rhs); } remainder -= rhs; quotient += 1; } return std::pair{static_cast<bigint>(quotient), static_cast<bigint>(remainder)}; } [[nodiscard]] constexpr friend bigint operator/(bigint const &lhs, bigint const &rhs) noexcept { auto quotient = bigint{}; auto remainder = bigint{}; if constexpr (is_signed) { signed_div_carry_chain(quotient.digits, remainder.digits, lhs.digits, rhs.digits, lhs.num_digits); } else { div_carry_chain(quotient.digits, remainder.digits, lhs.digits, rhs.digits, lhs.num_digits); } return quotient; } [[nodiscard]] constexpr friend bigint operator%(bigint const &lhs, bigint const &rhs) noexcept { auto quotient = bigint{}; auto remainder = bigint{}; if constexpr (is_signed) { signed_div_carry_chain(quotient.digits, remainder.digits, lhs.digits, rhs.digits, lhs.num_digits); } else { div_carry_chain(quotient.digits, remainder.digits, lhs.digits, rhs.digits, lhs.num_digits); } return remainder; } friend std::ostream &operator<<(std::ostream &lhs, bigint const &rhs) { return lhs << rhs.string(); } }; template<std::unsigned_integral T, std::size_t N> struct is_numeric_unsigned_integral<bigint<T, N, false>> : std::true_type { }; template<std::unsigned_integral T, std::size_t N> struct is_numeric_signed_integral<bigint<T, N, true>> : std::true_type { }; template<std::unsigned_integral T, std::size_t N, bool S> struct is_numeric_integral<bigint<T, N, S>> : std::true_type { }; using ubig128 = bigint<uint64_t, 2, false>; using big128 = bigint<uint64_t, 2, true>; using uuid = bigint<uint64_t, 2, false>; } // namespace tt::inline v1 template<std::unsigned_integral DigitType, std::size_t NumDigits, bool IsSigned> struct std::numeric_limits<tt::bigint<DigitType, NumDigits, IsSigned>> { using value_type = tt::bigint<DigitType, NumDigits, IsSigned>; static constexpr bool is_specialized = true; static constexpr bool is_signed = IsSigned; static constexpr bool is_integer = true; static constexpr bool is_exact = true; static constexpr bool has_infinity = false; static constexpr bool has_quiet_NaN = false; static constexpr bool has_signaling_NaN = false; static constexpr float_denorm_style has_denorm = std::denorm_absent; static constexpr bool has_denorm_loss = false; static constexpr float_round_style round_style = std::round_toward_zero; static constexpr bool is_iec559 = false; static constexpr bool is_bounded = true; static constexpr bool is_modulo = true; static constexpr int digits = std::numeric_limits<DigitType>::digits * NumDigits; static constexpr int digits10 = std::numeric_limits<DigitType>::digits10 * NumDigits; static constexpr int max_digits10 = 0; static constexpr int min_exponent = 0; static constexpr int min_exponent10 = 0; static constexpr int max_exponent = 0; static constexpr int max_exponent10 = 0; static constexpr bool traps = std::numeric_limits<DigitType>::traps; static constexpr bool tinyness_before = false; static constexpr value_type min() noexcept { auto r = value_type{}; constexpr auto smin = std::numeric_limits<value_type::signed_digit_type>::min(); constexpr auto umin = std::numeric_limits<value_type::digit_type>::min(); for (std::size_t i = 0; i != value_type::num_digits; ++i) { r.digits[i] = umin; } if constexpr (value_type::is_signed and value_type::num_digits > 0) { r.digits[value_type::num_digits - 1] = static_cast<value_type::digit_type>(smin); } return r; } static constexpr value_type lowest() noexcept { return min(); } static constexpr value_type max() noexcept { auto r = value_type{}; constexpr auto smax = std::numeric_limits<value_type::signed_digit_type>::max(); constexpr auto umax = std::numeric_limits<value_type::digit_type>::max(); for (std::size_t i = 0; i != value_type::num_digits; ++i) { r.digits[i] = umax; } if constexpr (value_type::is_signed and value_type::num_digits > 0) { r.digits[value_type::num_digits - 1] = smax; } return r; } static constexpr value_type epsilon() noexcept { return value_type{0}; } static constexpr value_type round_error() noexcept { return value_type{0}; } static constexpr value_type infinity() noexcept { return value_type{0}; } static constexpr value_type quiet_NaN() noexcept { return value_type{0}; } static constexpr value_type signaling_NaN() noexcept { return value_type{0}; } static constexpr value_type denorm_min() noexcept { return value_type{0}; } };
31.871166
123
0.612079
RustWorks
b713076d6f439c91ff9028bbea1626c4be59c644
1,409
cpp
C++
LeetCode/C++/477. Total Hamming Distance.cpp
shreejitverma/GeeksforGeeks
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-18T05:14:28.000Z
2022-03-08T07:00:08.000Z
LeetCode/C++/477. Total Hamming Distance.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
6
2022-01-13T04:31:04.000Z
2022-03-12T01:06:16.000Z
LeetCode/C++/477. Total Hamming Distance.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-14T19:53:53.000Z
2022-02-18T05:14:30.000Z
//TLE //38 / 47 test cases passed. class Solution { public: int count_set_bit(int x){ int bits = 0; while(x != 0){ bits += x&1; x >>= 1; } return bits; } int totalHammingDistance(vector<int>& nums) { int N = nums.size(); int ans = 0; for(int i = 0; i < N-1; i++){ for(int j = i+1; j < N; j++){ int xorResult = nums[i]^nums[j]; ans += count_set_bit(xorResult); } } return ans; } }; //iterate from MSB //https://leetcode.com/problems/total-hamming-distance/discuss/96226/Java-O(n)-time-O(1)-Space //Runtime: 88 ms, faster than 10.31% of C++ online submissions for Total Hamming Distance. //Memory Usage: 8 MB, less than 100.00% of C++ online submissions for Total Hamming Distance. //time: O(N), space: O(1) class Solution { public: int totalHammingDistance(vector<int>& nums) { int N = nums.size(); int ans = 0; for(int i = 31; i >= 0; i--){ int mask = 1 << i; int set = 0, noset = 0; for(int num : nums){ if(num & mask){ set++; }else{ noset++; } } ans += set*noset; } return ans; } };
24.293103
94
0.446416
shreejitverma
b713535b6607cb55390fc64880ae912462bff049
3,442
cpp
C++
LeetCode/C++/51. N-Queens.cpp
shreejitverma/GeeksforGeeks
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
3
2020-12-30T00:29:59.000Z
2021-01-24T22:43:04.000Z
LeetCode/C++/51. N-Queens.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
6
2022-01-13T04:31:04.000Z
2022-03-12T01:06:16.000Z
LeetCode/C++/51. N-Queens.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-14T19:53:53.000Z
2022-02-18T05:14:30.000Z
//Backtracking //Runtime: 12 ms, faster than 59.92% of C++ online submissions for N-Queens. //Memory Usage: 8 MB, less than 32.76% of C++ online submissions for N-Queens. class Solution { public: int n; void backtrack(vector<bool>& used_col, vector<bool>& used_pos_diag, vector<bool>& used_neg_diag, int r, vector<int>& curpos, vector<vector<string>>& ans){ if(r == n){ vector<string> curans; for(int i = 0; i < n; ++i){ string row(n, '.'); row[curpos[i]] = 'Q'; curans.push_back(row); } ans.push_back(curans); }else{ for(int c = 0; c < n; ++c){ if(!used_col[c] && !used_pos_diag[r-c+n-1] && !used_neg_diag[r+c]){ curpos.push_back(c); used_col[c] = true; used_pos_diag[r-c+n-1] = true; used_neg_diag[r+c] = true; backtrack(used_col, used_pos_diag, used_neg_diag, r+1, curpos, ans); used_col[c] = false; used_pos_diag[r-c+n-1] = false; used_neg_diag[r+c] = false; curpos.pop_back(); } } } }; vector<vector<string>> solveNQueens(int n) { this->n = n; vector<int> curpos; vector<vector<string>> ans; //in each recursion, r is different, so there must be only one Q in a row //for each row, need to check if that column is used vector<bool> used_col(n, false); //also check if that positive diagonals is used //there are 2*n-1 positive diagonals vector<bool> used_pos_diag(2*n-1, false); //also check if that positive diagonals is used //there are 2*n-1 negative diagonals vector<bool> used_neg_diag(2*n-1, false); backtrack(used_col, used_pos_diag, used_neg_diag, 0, curpos, ans); return ans; } }; //+speed up, vector<bool> -> vector<int>, build ans on the fly //https://leetcode.com/problems/n-queens/discuss/19808/Accepted-4ms-c%2B%2B-solution-use-backtracking-and-bitmask-easy-understand //Runtime: 0 ms, faster than 100.00% of C++ online submissions for N-Queens. //Memory Usage: 7.2 MB, less than 91.99% of C++ online submissions for N-Queens. class Solution { public: int n; void backtrack(vector<int>& used, int r, vector<string>& cur, vector<vector<string>>& ans){ if(r == n){ ans.push_back(cur); }else{ for(int c = 0; c < n; ++c){ if(!used[c] && !used[n+r-c+n-1] && !used[n+2*n-1+r+c]){ cur[r][c] = 'Q'; used[c] = used[n+r-c+n-1] = used[n+2*n-1+r+c] = true; backtrack(used, r+1, cur, ans); used[c] = used[n+r-c+n-1] = used[n+2*n-1+r+c] = false; cur[r][c] = '.'; } } } }; vector<vector<string>> solveNQueens(int n) { this->n = n; vector<string> cur(n, string(n, '.')); vector<vector<string>> ans; vector<int> used(n + 2*n-1 + 2*n-1, false); backtrack(used, 0, cur, ans); return ans; } };
35.854167
129
0.490703
shreejitverma
b717465d9f435083c6e894c1a5652c02087b0bef
588
cpp
C++
tests/lexy/dsl/return.cpp
gkgoat1/lexy
9c600fa906e81efbb3e34b8951ebc56809f2a0df
[ "BSL-1.0" ]
null
null
null
tests/lexy/dsl/return.cpp
gkgoat1/lexy
9c600fa906e81efbb3e34b8951ebc56809f2a0df
[ "BSL-1.0" ]
null
null
null
tests/lexy/dsl/return.cpp
gkgoat1/lexy
9c600fa906e81efbb3e34b8951ebc56809f2a0df
[ "BSL-1.0" ]
null
null
null
// Copyright (C) 2020-2022 Jonathan Müller and lexy contributors // SPDX-License-Identifier: BSL-1.0 #include <lexy/dsl/return.hpp> #include "verify.hpp" TEST_CASE("dsl::return_") { constexpr auto rule = dsl::return_ + LEXY_LIT("abc"); CHECK(lexy::is_rule<decltype(dsl::return_)>); constexpr auto callback = token_callback; auto empty = LEXY_VERIFY(""); CHECK(empty.status == test_result::success); CHECK(empty.trace == test_trace()); auto abc = LEXY_VERIFY("abc"); CHECK(abc.status == test_result::success); CHECK(abc.trace == test_trace()); }
24.5
64
0.67517
gkgoat1
b717b1aa60a714ff583c84d3a5f3841858bc683c
247
cpp
C++
code/chapter_7-DISPLAY_ELEMENTS/04-using_web_links_with_labels/main.cpp
ordinary-developer/book_qt_5_3_m_shlee
9e760323ef8ecd32fb0ef775a8633f8021da972c
[ "MIT" ]
1
2017-05-04T08:23:46.000Z
2017-05-04T08:23:46.000Z
books/techno/qt/qt_5_3_m_shlee/code/ch_07-DISPLAY_ELEMENTS/04-using_web_links_with_labels/main.cpp
ordinary-developer/lin_education
13d65b20cdbc3e5467b2383e5c09c73bbcdcb227
[ "MIT" ]
null
null
null
books/techno/qt/qt_5_3_m_shlee/code/ch_07-DISPLAY_ELEMENTS/04-using_web_links_with_labels/main.cpp
ordinary-developer/lin_education
13d65b20cdbc3e5467b2383e5c09c73bbcdcb227
[ "MIT" ]
null
null
null
#include <QtWidgets> int main(int argc, char** argv) { QApplication app{ argc, argv }; QLabel label { "<a href=\"http://www.bhv.ru\">www.bhv.ru</a>" }; label.setOpenExternalLinks(true); label.show(); app.exec(); }
17.642857
59
0.578947
ordinary-developer
b718ae99d05bc5705416f536178441a04077fe37
543
cpp
C++
TAO/tao/QtResource/QtResource_Loader.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tao/QtResource/QtResource_Loader.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tao/QtResource/QtResource_Loader.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
//$Id: QtResource_Loader.cpp 91628 2010-09-07 11:11:12Z johnnyw $ #include "tao/QtResource/QtResource_Loader.h" #include "tao/ORB_Core.h" #include "tao/QtResource/QtResource_Factory.h" TAO_BEGIN_VERSIONED_NAMESPACE_DECL namespace TAO { QtResource_Loader::QtResource_Loader (QApplication *qapp) { QtResource_Factory *tmp = 0; ACE_NEW (tmp, QtResource_Factory (qapp)); TAO_ORB_Core::set_gui_resource_factory (tmp); } QtResource_Loader::~QtResource_Loader (void) { } } TAO_END_VERSIONED_NAMESPACE_DECL
20.111111
65
0.744015
cflowe
b71ab820ce1d29a86af167f60c7b75ec80756a5c
7,825
cpp
C++
src/server/main.cpp
Kuga23/Projet-M2
85c879b8fd1ed4fdf89eedd9f89841cbd7a1e433
[ "MIT" ]
null
null
null
src/server/main.cpp
Kuga23/Projet-M2
85c879b8fd1ed4fdf89eedd9f89841cbd7a1e433
[ "MIT" ]
null
null
null
src/server/main.cpp
Kuga23/Projet-M2
85c879b8fd1ed4fdf89eedd9f89841cbd7a1e433
[ "MIT" ]
null
null
null
#include <iostream> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> // Pour compter une minute d'enregistrement #include <fstream> // Pour la gestion des fichiers #include <sstream> #include <map> #include <memory> #include <microhttpd.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/types.h> #include <sys/select.h> #include "state.h" #include "engine.h" #include "ai.h" #include "server.h" using namespace std; using namespace state; using namespace engine; using namespace ai; using namespace server; class Request { public: struct MHD_PostProcessor *pp = nullptr; string data; ~Request() { if (pp) MHD_destroy_post_processor(pp); } }; static int post_iterator(void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { return MHD_NO; } static int handler(void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **ptr) { Request *request = (Request *)*ptr; if (!request) { request = new Request(); if (!request) { return MHD_NO; } *ptr = request; if (strcmp(method, MHD_HTTP_METHOD_POST) == 0 || strcmp(method, MHD_HTTP_METHOD_PUT) == 0) { request->pp = MHD_create_post_processor(connection, 1024, &post_iterator, request); if (!request->pp) { cerr << "Failed to setup post processor for " << url << endl; return MHD_NO; } } return MHD_YES; } if (strcmp(method, MHD_HTTP_METHOD_POST) == 0 || strcmp(method, MHD_HTTP_METHOD_PUT) == 0) { MHD_post_process(request->pp, upload_data, *upload_data_size); if (*upload_data_size != 0) { request->data = upload_data; *upload_data_size = 0; return MHD_YES; } } HttpStatus status; string response; try { ServicesManager *manager = (ServicesManager *)cls; status = manager->queryService(response, request->data, url, method); } catch (ServiceException &e) { status = e.getStatus(); response += "\n"; } catch (exception &e) { status = HttpStatus::SERVER_ERROR; response = e.what(); response += "\n"; } catch (...) { status = HttpStatus::SERVER_ERROR; response = "Unknown exception\n"; } struct MHD_Response *mhd_response; mhd_response = MHD_create_response_from_buffer(response.size(), (void *)response.c_str(), MHD_RESPMEM_MUST_COPY); if (strcmp(method, MHD_HTTP_METHOD_GET) == 0) { MHD_add_response_header(mhd_response, "Content-Type", "application/json; charset=utf-8"); } int ret = MHD_queue_response(connection, status, mhd_response); MHD_destroy_response(mhd_response); return ret; } static void request_completed(void *cls, struct MHD_Connection *connection, void **con_cls, enum MHD_RequestTerminationCode toe) { Request *request = (Request *)*con_cls; if (request) { delete request; *con_cls = nullptr; } } int main(int argc, char const *argv[]) { if (argc > 1){ // Test pour un Hello if (strcmp(argv[1], "Hello") == 0) cout << "Bonjour " << endl; else if (strcmp(argv[1], "record") == 0){ std::string commands_file = "res/record/replay.txt"; engine::Engine myEngine; myEngine.setEnableRecord(true); myEngine.getState().initPlayers(); myEngine.getState().initCharacters(); myEngine.getState().initMapCell(); ai::HeuristicAI AI_1(myEngine, 1); ai::HeuristicAI AI_2(myEngine, 2); cout << "<<< Record >>>" << endl; cout << "HAi vs HAI" << commands_file << endl; sleep(2); cout << "<<< Début de l'enregistrement >>>" << endl; // On joue une minute de jeu clock_t time; while (time=clock()/CLOCKS_PER_SEC <=60){ // joueur1 if(myEngine.getState().getEndGame()) break; if (myEngine.getState().getRound() % 2 != 0) { AI_1.run(myEngine); } // joueur2 else { AI_2.run(myEngine); } } cout << "<<< Fin de l'enregistrement >>>" << endl; cout << "<<< ###############################################################" << endl; cout << " ENREGISTREMENT DANS LE FICHIER REPLAY.TXT "<<endl; cout << "<<< ###############################################################" << endl; // Ouverture du fichier en ecriture en effacant son contenu à l'ouverture std::ofstream written_file(commands_file, ios::out | ios::trunc); if (written_file){ Json::Value record = myEngine.getRecord(); cout << record << endl; // Ecriture dans le fichier du tableau de commandes de cette partie written_file << record; // Fermeture du fichier written_file.close(); } else{ cerr << "Impossible d'ouvrir le fichier pour l'ecriture" << endl; } } else if (strcmp(argv[1], "listen") == 0){ try { VersionService versionService; std::unique_ptr<AbstractService> ptr_versionService(new VersionService(versionService)); ServicesManager servicesManager; servicesManager.registerService(move(ptr_versionService)); Game game; PlayerService playerService(std::ref(game)); std::unique_ptr<AbstractService> ptr_playerService(new PlayerService(playerService)); servicesManager.registerService(move(ptr_playerService)); struct MHD_Daemon *d; if (argc != 2) { printf("%s PORT\n", argv[0]); return 1; } int port_id = 80; d = MHD_start_daemon( // MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG | MHD_USE_POLL, MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG, // MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG | MHD_USE_POLL, // MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG, port_id, NULL, NULL, &handler, (void *)&servicesManager, MHD_OPTION_NOTIFY_COMPLETED, request_completed, NULL, MHD_OPTION_END); if (d == NULL) return 1; cout << "server is listening in port " << port_id << endl << "press any button to stop the server" << endl; (void)getc(stdin); MHD_stop_daemon(d); } catch (exception &e) { cerr << "Exception: " << e.what() << endl; } } } }
30.212355
128
0.511182
Kuga23
b71b00f47e7de6b078f53209e6a9019f96dc56e1
1,845
cpp
C++
第九周/Insertion or Heap Sort/Insertion or Heap Sort.cpp
Daipuwei/-MOOC-
e6589e4b62f86c50fb34f2b395230c8dd49cf3d1
[ "MIT" ]
11
2019-11-12T09:22:03.000Z
2021-01-24T02:26:10.000Z
第九周/Insertion or Heap Sort/Insertion or Heap Sort.cpp
Daipuwei/-MOOC-
e6589e4b62f86c50fb34f2b395230c8dd49cf3d1
[ "MIT" ]
null
null
null
第九周/Insertion or Heap Sort/Insertion or Heap Sort.cpp
Daipuwei/-MOOC-
e6589e4b62f86c50fb34f2b395230c8dd49cf3d1
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; bool Check(int a[],int b[],int N) { bool flag = true; for ( int i = 0 ; i < N ; i++){ if ( a[i] != b[i]){ flag = false; break; } } return flag; } void Print(int a[],int N) { cout<<a[0]; for (int i = 1 ; i < N ; i++){ cout<<" "<<a[i]; } } bool Insert_Sort(int a[],int b[],int N) { bool isInsert = false; for ( int i = 1 ; i < N ; i++){ int tmp = a[i]; int j; for (j = i ; j > 0 && a[j-1] > tmp ; j--){ a[j] = a[j-1]; } a[j] = tmp; if (isInsert){ cout<<"Insertion Sort"<<endl; Print(a,N); break; }else if(Check(a,b,N)){ isInsert = true; } } return isInsert; } void PreDown(int a[],int p,int N) { int parent,child; int x = a[p]; for ( parent = p ; (parent * 2 + 1) < N ; parent = child){ child = parent * 2 + 1; if ( (child != N -1) && ( a[child] < a[child+1])){ child++; } if ( x >= a[child]){ break; }else{ a[parent] = a[child]; } } a[parent] = x; } void swap(int* a ,int* b) { int tmp = *a; *a = *b; *b = tmp; } bool Heap_Sort(int a[],int b[],int N) { bool isHeap = false; for ( int i = N/2-1 ; i >= 0 ; i--){ PreDown(a,i,N); } for ( int i = N-1 ; i > 0 ; i--){ swap(&a[0],&a[i]); PreDown(a,0,i); if (isHeap){ cout<<"Heap Sort"<<endl; Print(a,N); break; }else if(Check(a,b,N)){ isHeap = true; } } } int main() { int len; cin>>len; int *A,*B,*C; A = new int[len]; B = new int[len]; C = new int[len]; for ( int i = 0 ; i < len ; i++){ cin>>A[i]; C[i] = A[i]; } for ( int i = 0 ; i < len ; i++){ cin>>B[i]; } bool isHeap = Heap_Sort(A,B,len); if ( isHeap){ return 0; }else{ bool isInsert = Insert_Sort(C,B,len); return 0; } return 0; }
16.043478
60
0.452033
Daipuwei
b71c41bf6a917a0818128e07e9d8a7969c309bb0
2,489
cpp
C++
QtOrm/Registry.cpp
rensfo/QtOrm
46a16ee507cff4b1367b674420365137bf20aa9f
[ "MIT" ]
null
null
null
QtOrm/Registry.cpp
rensfo/QtOrm
46a16ee507cff4b1367b674420365137bf20aa9f
[ "MIT" ]
1
2016-11-04T14:26:58.000Z
2016-11-04T14:27:57.000Z
QtOrm/Registry.cpp
rensfo/QtOrm
46a16ee507cff4b1367b674420365137bf20aa9f
[ "MIT" ]
null
null
null
#include "Registry.h" #include <QMetaObject> #include "Mappings/ConfigurationMap.h" #include "Mappings/SubClassMap.h" namespace QtOrm { Registry::Registry(QObject *parent) : QObject(parent) { } bool Registry::contains(const QString &table, const IdType &id) { if (data.contains(table)) { return data.value(table).contains(id); } return false; } void Registry::insert(const QString &table, const IdType &id, ItemType object) { if (data.contains(table)) { if (!data.value(table).contains(id)) { data[table].insert(id, object); itemsIds.insert(object, id); } } else { RegistryData ids; ids.insert(id, object); data.insert(table, ids); itemsIds.insert(object, id); } } void Registry::remove(const QString &table, const IdType &id) { if (contains(table, id)) { auto object = value(table, id); itemsIds.remove(object); data[table].remove(id); } } void Registry::remove(ItemType object) { for (RegistryData &ids : data) { for (QSharedPointer<QObject> &registryObject : ids) { if (registryObject == object) { IdType key = ids.key(object); ids.remove(key); itemsIds.remove(object); return; } } } } Registry::ItemType Registry::value(const QString &table, const IdType &id) { if (contains(table, id)) { return data[table][id]; } return ItemType(); } Registry::ItemType Registry::value(QObject *object) { QString className = object->metaObject()->className(); QString tableName; auto classBase = configuration->getMappedClass(className); if(Mapping::SubClassMap::isClassTableInheritance(classBase)){ classBase = classBase->toSubclass()->getBaseClass(); } tableName = classBase->getTable(); if (data.contains(tableName)) { for (QSharedPointer<QObject> &registryObject : data[tableName]) { if (registryObject.data() == object) { return registryObject; } } } return QSharedPointer<QObject>(); } bool Registry::contains(Registry::ItemType object) { return itemsIds.contains(object); } Registry::IdType Registry::getId(ItemType object) { return itemsIds.value(object); } void Registry::clear() { data.clear(); } QSharedPointer<Config::ConfigurationMap> Registry::getConfiguration() const { return configuration; } void Registry::setConfiguration(QSharedPointer<Config::ConfigurationMap> value) { configuration = value; } } uint qHash(const QVariant&var) { return qHash(var.toString()); }
22.223214
80
0.677782
rensfo
b71e843ee4b54e0ab2b62d7df324ae043137354a
1,124
hxx
C++
com/ole32/stg/ref/h/docfilep.hxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/ole32/stg/ref/h/docfilep.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/ole32/stg/ref/h/docfilep.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+-------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1992 - 1996. // // File: docfilep.hxx // // Contents: Private DocFile definitions // //--------------------------------------------------------------- #ifndef __DOCFILEP_HXX__ #define __DOCFILEP_HXX__ #define CWCMAXPATHCOMPLEN CWCSTREAMNAME #define CBMAXPATHCOMPLEN (CWCMAXPATHCOMPLEN*sizeof(WCHAR)) // Common bundles of STGM flags #define STGM_RDWR (STGM_READ | STGM_WRITE | STGM_READWRITE) #define STGM_DENY (STGM_SHARE_DENY_NONE | STGM_SHARE_DENY_READ | \ STGM_SHARE_DENY_WRITE | STGM_SHARE_EXCLUSIVE) #define VALID_IFTHERE(it) \ ((it) == STG_FAILIFTHERE || (it) == STG_CREATEIFTHERE || \ (it) == STG_CONVERTIFTHERE) #define VALID_COMMIT(cf) \ (((cf) & ~(STGC_OVERWRITE | STGC_ONLYIFCURRENT | \ STGC_DANGEROUSLYCOMMITMERELYTODISKCACHE)) == 0) #define VALID_LOCKTYPE(lt) \ ((lt) == LOCK_WRITE || (lt) == LOCK_EXCLUSIVE || \ (lt) == LOCK_ONLYONCE) #define FLUSH_CACHE(cf) \ ((cf & STGC_DANGEROUSLYCOMMITMERELYTODISKCACHE) == 0) #endif
27.414634
66
0.624555
npocmaka
b71ec959e3b67a00b0ad45464015ab0bec1d1615
1,543
cc
C++
2021/PTA/Pratice 1/M.cc
slowbear/TrainingCode
688872b9dab784a410069b787457f8c0871648aa
[ "CC0-1.0" ]
null
null
null
2021/PTA/Pratice 1/M.cc
slowbear/TrainingCode
688872b9dab784a410069b787457f8c0871648aa
[ "CC0-1.0" ]
null
null
null
2021/PTA/Pratice 1/M.cc
slowbear/TrainingCode
688872b9dab784a410069b787457f8c0871648aa
[ "CC0-1.0" ]
null
null
null
#include <bits/extc++.h> #include <bits/stdc++.h> using namespace std; using LL = long long; using Pii = pair<int, int>; using Pll = pair<LL, LL>; using VI = vector<int>; using VP = vector<pair<int, int>>; #define rep(i, a, b) for (auto i = (a); i < (b); ++i) #define rev(i, a, b) for (auto i = (b - 1); i >= (a); --i) #define grep(i, u) for (auto i = gh[u]; i != -1; i = gn[i]) #define mem(x, v) memset(x, v, sizeof(x)) #define cpy(x, y) memcpy(x, y, sizeof(x)) #define SZ(V) static_cast<int>(V.size()) #define pb push_back #define mp make_pair constexpr int maxn = 1010; int lc[maxn], rc[maxn], fa[maxn], val[maxn], total; int insert(int rt, int key) { if (!rt) { lc[total] = rc[total] = fa[total] = 0; val[total] = key; return total++; } if (key > val[rt]) { lc[rt] = insert(lc[rt], key); fa[lc[rt]] = rt; } else { rc[rt] = insert(rc[rt], key); fa[rc[rt]] = rt; } return rt; } int tag[maxn], cnt; int main() { int n, rt = 0; total = 1; scanf("%d", &n); rep(i, 0, n) { int x; scanf("%d", &x); rt = insert(rt, x); } bool flag = true, first_print = true; queue<int> que; que.push(rt); cnt = 1; while (!que.empty()) { int u = que.front(); que.pop(); tag[u] = cnt++; if (tag[fa[u]] != tag[u] / 2) flag = false; if (!lc[u] && rc[u]) flag = false; if (!first_print) putchar(' '); printf("%d", val[u]); first_print = false; if (lc[u]) que.push(lc[u]); if (rc[u]) que.push(rc[u]); } printf("\n"); puts(flag ? "YES" : "NO"); }
22.691176
59
0.528192
slowbear
b71edd52079289ee9815d3e9422ff530e4ebfe59
2,050
cpp
C++
Fedoraware/TeamFortress2/TeamFortress2/Features/Aimbot/Aimbot.cpp
hyperventilation/Fedoraware
4cd6bea1711a31a797adf855f6ee979138558d3c
[ "WTFPL" ]
28
2022-02-02T04:36:09.000Z
2022-03-31T19:05:10.000Z
Fedoraware/TeamFortress2/TeamFortress2/Features/Aimbot/Aimbot.cpp
hyperventilation/Fedoraware
4cd6bea1711a31a797adf855f6ee979138558d3c
[ "WTFPL" ]
103
2022-02-03T11:52:24.000Z
2022-03-31T18:33:55.000Z
Fedoraware/TeamFortress2/TeamFortress2/Features/Aimbot/Aimbot.cpp
hyperventilation/Fedoraware
4cd6bea1711a31a797adf855f6ee979138558d3c
[ "WTFPL" ]
39
2022-02-02T23:34:15.000Z
2022-03-27T21:36:05.000Z
#include "Aimbot.h" #include "../Vars.h" #include "AimbotHitscan/AimbotHitscan.h" #include "AimbotProjectile/AimbotProjectile.h" #include "AimbotMelee/AimbotMelee.h" bool CAimbot::ShouldRun(CBaseEntity* pLocal, CBaseCombatWeapon* pWeapon) { if (G::FreecamActive) return false; if (!Vars::Aimbot::Global::Active.Value) return false; if (I::EngineVGui->IsGameUIVisible() || I::Surface->IsCursorVisible()) return false; if (!pLocal->IsAlive() || pLocal->IsTaunting() || pLocal->IsBonked() || pLocal->GetFeignDeathReady() || pLocal->IsCloaked() || pLocal->IsInBumperKart() || pLocal->IsAGhost()) return false; switch (G::CurItemDefIndex) { case Soldier_m_RocketJumper: case Demoman_s_StickyJumper: return false; default: break; } switch (pWeapon->GetWeaponID()) { case TF_WEAPON_PDA: case TF_WEAPON_PDA_ENGINEER_BUILD: case TF_WEAPON_PDA_ENGINEER_DESTROY: case TF_WEAPON_PDA_SPY: case TF_WEAPON_PDA_SPY_BUILD: case TF_WEAPON_BUILDER: case TF_WEAPON_INVIS: case TF_WEAPON_BUFF_ITEM: case TF_WEAPON_GRAPPLINGHOOK: { return false; } default: break; } return true; } void CAimbot::Run(CUserCmd* pCmd) { G::CurrentTargetIdx = 0; G::CurAimFOV = 0.0f; G::PredictedPos = Vec3(); G::HitscanRunning = false; G::HitscanSilentActive = false; G::ProjectileSilentActive = false; G::AimPos = Vec3(); auto pLocal = I::EntityList->GetClientEntity(I::Engine->GetLocalPlayer()); if (pLocal) { auto pWeapon = pLocal->GetActiveWeapon(); if (!pWeapon) { return; } if (!ShouldRun(pLocal, pWeapon)) return; SandvichAimbot::IsSandvich(); if (SandvichAimbot::bIsSandvich) { G::CurWeaponType = EWeaponType::HITSCAN; } switch (G::CurWeaponType) { case EWeaponType::HITSCAN: { F::AimbotHitscan.Run(pLocal, pWeapon, pCmd); break; } case EWeaponType::PROJECTILE: { F::AimbotProjectile.Run(pLocal, pWeapon, pCmd); break; } case EWeaponType::MELEE: { F::AimbotMelee.Run(pLocal, pWeapon, pCmd); break; } default: break; } } }
18.807339
75
0.694634
hyperventilation
b71ef886c7bf06ebcb1cc3b42866438a517da7e4
4,382
cpp
C++
code archive/TIOJ/1840.cpp
brianbbsu/program
c4505f2b8c0b91010e157db914a63c49638516bc
[ "MIT" ]
4
2018-04-08T08:07:58.000Z
2021-06-07T14:55:24.000Z
code archive/TIOJ/1840.cpp
brianbbsu/program
c4505f2b8c0b91010e157db914a63c49638516bc
[ "MIT" ]
null
null
null
code archive/TIOJ/1840.cpp
brianbbsu/program
c4505f2b8c0b91010e157db914a63c49638516bc
[ "MIT" ]
1
2018-10-29T12:37:25.000Z
2018-10-29T12:37:25.000Z
//{ #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef double lf; typedef pair<ll,ll> ii; #define REP(i,n) for(ll i=0;i<n;i++) #define FILL(i,n) memset(i,n,sizeof i) #define X first #define Y second #define SZ(_a) (int)_a.size() #define ALL(_a) _a.begin(),_a.end() #define pb push_back #ifdef brian #define debug(...) do{\ fprintf(stderr,"%s - %d (%s) = ",__PRETTY_FUNCTION__,__LINE__,#__VA_ARGS__);\ _do(__VA_ARGS__);\ }while(0) template<typename T>void _do(T &&_x){cerr<<_x<<endl;} template<typename T,typename ...S> void _do(T &&_x,S &&..._t){cerr<<_x<<" ,";_do(_t...);} template<typename _a,typename _b> ostream& operator << (ostream &_s,const pair<_a,_b> &_p){return _s<<"("<<_p.X<<","<<_p.Y<<")";} template<typename It> ostream& _OUTC(ostream &_s,It _ita,It _itb) { _s<<"{"; for(It _it=_ita;_it!=_itb;_it++) { _s<<(_it==_ita?"":",")<<*_it; } _s<<"}"; return _s; } template<typename _a> ostream &operator << (ostream &_s,vector<_a> &_c){return _OUTC(_s,ALL(_c));} template<typename _a> ostream &operator << (ostream &_s,set<_a> &_c){return _OUTC(_s,ALL(_c));} template<typename _a,typename _b> ostream &operator << (ostream &_s,map<_a,_b> &_c){return _OUTC(_s,ALL(_c));} template<typename _t> void pary(_t _a,_t _b){_OUTC(cerr,_a,_b);cerr<<endl;} #else #define debug(...) #define pary(...) #define endl '\n' #endif // brian //} const ll MAXn=7e4+5,MAXlg=__lg(10*MAXn)+2; const ll MOD=1000000007; const ll INF=ll(1e15); struct chtag{ ll t,p,x,type; chtag(ll ti,ll pi,ll xi,ll tpi):t(ti),p(pi),x(xi),type(tpi){} }; struct qrtag{ ll t,l,r,k; qrtag(ll ti,ll li,ll ri,ll ki):t(ti),l(li),r(ri),k(ki){} }; ll aryd[10*MAXn]; vector<chtag> ch[MAXlg],tmpch; vector<qrtag> qr[MAXlg],tmpqr; stack<chtag> st; ll n,q; ll it=-1; ll ans[10*MAXn]; vector<ll> uni; //bit ll bit[MAXn*10]; void ins(ll x,ll k){ while(x<=n)bit[x]+=k,x+=x&-x; } ll precnt(ll x){ ll r=0;while(x>0)r+=bit[x],x-=x&-x;return r; } void DC(ll now,ll l,ll r) { assert(now<MAXlg); debug(now,l,r); if(l==r-1) { for(auto &k:qr[now])ans[k.t]=uni[r]; return; } tmpqr.clear(); tmpch.clear(); ch[now+1].clear(); qr[now+1].clear(); ll chit=0; ll h=(l+r)/2; assert(h>=0); for(auto &k:qr[now]) { while(chit<SZ(ch[now])&&ch[now][chit].t<k.t) { if(ch[now][chit].x<=h) { auto &chn=ch[now][chit]; st.push(chn); ins(chn.p,chn.type); } chit++; } ll tmps=precnt(k.r)-precnt(k.l-1); if(tmps>=k.k) { qr[now+1].pb(k); } else { k.k-=tmps; tmpqr.pb(k); } } while(SZ(st)) { ins(st.top().p,st.top().type*-1); st.pop(); } for(auto &k:ch[now]) { if(k.x<=h)ch[now+1].pb(k); else tmpch.pb(k); } ch[now].swap(tmpch); qr[now].swap(tmpqr); DC(now+1,l,h); ch[now+1].swap(ch[now]); qr[now+1].swap(qr[now]); DC(now+1,h,r); } int main() { ios_base::sync_with_stdio(0);cin.tie(0); debug(MAXlg); ll T; cin>>T; while(T--&&cin>>n>>q) { it=-1; REP(i,MAXlg)ch[i].clear(),qr[i].clear(); uni.clear(); FILL(bit,0); while(SZ(st))st.pop(); REP(i,n)cin>>aryd[i+1],uni.pb(aryd[i+1]),ch[0].pb(chtag(-1,i+1,aryd[i+1],1)); //input REP(i,q) { ll t; cin>>t; if(t==1) { ll l,r,k; cin>>l>>r>>k; it++; qr[0].pb(qrtag(it,l,r,k)); } else if(t==2) { ll x,k; cin>>x>>k; ch[0].pb(chtag(it,x,k,1)); ch[0].pb(chtag(it,x,aryd[x],-1)); aryd[x]=k; uni.pb(k); } else { ll x; cin>>x>>x; it++; ans[it]=7122; } } sort(ALL(uni)); uni.resize(unique(ALL(uni))-uni.begin()); assert(SZ(uni)<MAXn*10); for(auto &k:ch[0])k.x=lower_bound(ALL(uni),k.x)-uni.begin(); DC(0,-1,SZ(uni)-1); REP(i,it+1)cout<<ans[i]<<endl; } }
23.185185
129
0.482656
brianbbsu
b71f9b6c94e743610a2a49426cc057f29dfa1cc0
6,192
hpp
C++
mps_voxels/include/mps_voxels/graph_matrix_utils_impl.hpp
UM-ARM-Lab/multihypothesis_segmentation_tracking
801d460afbf028100374c880bc684187ec8b909f
[ "MIT" ]
3
2020-10-31T21:42:36.000Z
2021-12-16T12:56:02.000Z
mps_voxels/include/mps_voxels/graph_matrix_utils_impl.hpp
UM-ARM-Lab/multihypothesis_segmentation_tracking
801d460afbf028100374c880bc684187ec8b909f
[ "MIT" ]
1
2020-11-11T03:46:08.000Z
2020-11-11T03:46:08.000Z
mps_voxels/include/mps_voxels/graph_matrix_utils_impl.hpp
UM-ARM-Lab/multihypothesis_segmentation_tracking
801d460afbf028100374c880bc684187ec8b909f
[ "MIT" ]
1
2022-03-02T12:32:21.000Z
2022-03-02T12:32:21.000Z
/* * Copyright (c) 2020 Andrew Price * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef MPS_GRAPH_MATRIX_UTILS_HPP #define MPS_GRAPH_MATRIX_UTILS_HPP #include "mps_voxels/graph_matrix_utils.h" #include "mps_voxels/video_graph.h" template <typename Graph> Eigen::MatrixXd getLaplacian(const Graph& graph) { const int numCells = boost::num_vertices(graph); Eigen::MatrixXd laplacian = Eigen::MatrixXd::Zero(numCells, numCells); for (typename Graph::vertex_descriptor vd : make_range(boost::vertices(graph))) { size_t degree = boost::out_degree(vd, graph); // Degree Matrix laplacian(vd, vd) = degree; // Minus Adjacency Matrix for (typename Graph::edge_descriptor ed : make_range(boost::out_edges(vd, graph))) { typename Graph::vertex_descriptor u = boost::target(ed, graph); laplacian(vd, u) = -graph[ed].affinity; } } return laplacian; } template <typename Graph> Eigen::MatrixXd getLaplacianNormalized(const Graph& graph) { const int numCells = boost::num_vertices(graph); Eigen::MatrixXd laplacian = Eigen::MatrixXd::Zero(numCells, numCells); Eigen::VectorXd d(numCells); for (typename Graph::vertex_descriptor vd : make_range(boost::vertices(graph))) { size_t degree = boost::out_degree(vd, graph); // Degree Matrix laplacian(vd, vd) = degree; // Degree Matrix Normalizer d(vd) = 1.0/sqrt(static_cast<double>(degree)); // Minus Adjacency Matrix for (typename Graph::edge_descriptor ed : make_range(boost::out_edges(vd, graph))) { typename Graph::vertex_descriptor u = boost::target(ed, graph); laplacian(vd, u) = -graph[ed].affinity; } } return d.asDiagonal() * laplacian * d.asDiagonal(); } template <typename Graph> Eigen::SparseMatrix<double> getLaplacianSparse(const Graph& graph) { const int numCells = boost::num_vertices(graph); typedef Eigen::Triplet<double> Tripletd; std::vector<Tripletd> triplets; triplets.reserve(numCells); for (typename Graph::vertex_descriptor vd : make_range(boost::vertices(graph))) { size_t degree = boost::out_degree(vd, graph); // Degree Matrix triplets.emplace_back(Tripletd(vd, vd, degree)); // Minus Adjacency Matrix for (typename Graph::edge_descriptor ed : make_range(boost::out_edges(vd, graph))) { typename Graph::vertex_descriptor u = boost::target(ed, graph); triplets.emplace_back(Tripletd(vd, u, -graph[ed].affinity)); // u->v is added when vd = u } } Eigen::SparseMatrix<double> laplacian(numCells, numCells); laplacian.setFromTriplets(triplets.begin(), triplets.end()); return laplacian; } template <typename Graph> Eigen::SparseMatrix<double> getLaplacianSparseNormalized(const Graph& graph) { const int numCells = boost::num_vertices(graph); typedef Eigen::Triplet<double> Tripletd; std::vector<Tripletd> triplets; triplets.reserve(numCells); Eigen::VectorXd d(numCells); for (typename Graph::vertex_descriptor vd : make_range(boost::vertices(graph))) { size_t degree = boost::out_degree(vd, graph); // Degree Matrix triplets.emplace_back(Tripletd(vd, vd, degree)); // Degree Matrix Normalizer d(vd) = 1.0/sqrt(static_cast<double>(degree)); // Minus Adjacency Matrix for (typename Graph::edge_descriptor ed : make_range(boost::out_edges(vd, graph))) { typename Graph::vertex_descriptor u = boost::target(ed, graph); triplets.emplace_back(Tripletd(vd, u, -graph[ed].affinity)); } } Eigen::SparseMatrix<double> laplacian(numCells, numCells); laplacian.setFromTriplets(triplets.begin(), triplets.end()); return d.asDiagonal() * laplacian * d.asDiagonal(); } template <typename Graph> Eigen::SparseMatrix<double> getAdjacencySparse(const Graph& graph) { const int numCells = boost::num_vertices(graph); typedef Eigen::Triplet<double> Tripletd; std::vector<Tripletd> triplets; triplets.reserve(2*numCells); for (typename Graph::vertex_descriptor vd : make_range(boost::vertices(graph))) { // Adjacency Matrix for (typename Graph::edge_descriptor ed : make_range(boost::out_edges(vd, graph))) { typename Graph::vertex_descriptor u = boost::target(ed, graph); triplets.emplace_back(Tripletd(vd, u, graph[ed].affinity)); // u->v is added when vd = u } } Eigen::SparseMatrix<double> adjacency(numCells, numCells); adjacency.setFromTriplets(triplets.begin(), triplets.end()); return adjacency; } template <typename Scalar> std::vector<Eigen::Triplet<Scalar>> to_triplets(const Eigen::SparseMatrix<Scalar> & M) { std::vector<Eigen::Triplet<Scalar>> v; for(int i = 0; i < M.outerSize(); i++) for(typename Eigen::SparseMatrix<Scalar>::InnerIterator it(M,i); it; ++it) v.emplace_back(it.row(),it.col(),it.value()); return v; } #endif // MPS_GRAPH_MATRIX_UTILS_HPP
32.589474
92
0.738534
UM-ARM-Lab
b7253a6f511f2a7e69a54f27bcf6a2dc20c5d63d
11,489
hpp
C++
Controller/CPU-related/AMD/beginningWithFam10h/voltage.hpp
st-gb/CPUinfoAndControl
5e93d4a195b4692d147bb05cfef534e38d7f8b64
[ "MIT" ]
null
null
null
Controller/CPU-related/AMD/beginningWithFam10h/voltage.hpp
st-gb/CPUinfoAndControl
5e93d4a195b4692d147bb05cfef534e38d7f8b64
[ "MIT" ]
null
null
null
Controller/CPU-related/AMD/beginningWithFam10h/voltage.hpp
st-gb/CPUinfoAndControl
5e93d4a195b4692d147bb05cfef534e38d7f8b64
[ "MIT" ]
1
2021-07-16T21:01:26.000Z
2021-07-16T21:01:26.000Z
/* * from_K10.h * * Created on: Aug 28, 2013 * Author: Stefan */ #ifndef FROM_K10_VOLTAGE_H_ #define FROM_K10_VOLTAGE_H_ #include <hardware/CPU/fastest_data_type.h> //typedef fastestUnsignedDataType #include <preprocessor_macros/bitmasks.h> #include <stdint.h> // uint32_t //ReadMSR(...) #include <Controller/AssignPointersToExportedExeFunctions/inline_register_access_functions.hpp> //CPU_TEMPERATURE_DEVICE_AND_FUNCTION_NUMBER, ... #include "../configuration_space_addresses.h" extern ReadPCIconfigSpace_func_type g_pfnReadPCIconfigSpace; /** Use prefix "COFVID_STATUS_MSR" to be eindeutig (because there may * also be a field with the same meaning in e.g. another register, but at * another start address) */ /** "48:42 [...]: minimum voltage. Read-only. Specifies the VID code * corresponding to the minimum voltage (highest VID code) that the processor * drives. 00h indicates that no minimum VID code is specified. * See section 2.4.1 [Processor Power Planes And Voltage Control]." */ #define COFVID_STATUS_MSR_START_BIT_FOR_MIN_VOLTAGE_VID 42 #define COFVID_STATUS_MSR_START_BIT_FOR_MAX_VID \ COFVID_STATUS_MSR_START_BIT_FOR_MIN_VOLTAGE_VID #define COFVID_STATUS_MSR_START_BIT_FOR_MIN_VOLTAGE_VID_IN_EDX \ (COFVID_STATUS_MSR_START_BIT_FOR_MIN_VOLTAGE_VID - 32) #define COFVID_STATUS_MSR_START_BIT_FOR_MAX_VID_IN_EDX \ COFVID_STATUS_MSR_START_BIT_FOR_MIN_VOLTAGE_VID_IN_EDX #define COFVID_STATUS_MSR_START_BIT_FOR_MAX_VOLTAGE_VID 35 #define COFVID_STATUS_MSR_START_BIT_FOR_MAX_VOLTAGE_VID_IN_EDX \ COFVID_STATUS_REGISTER_START_BIT_FOR_MAX_VOLTAGE_VID - 32 /** "MSRC001_0071 COFVID Status" : "41:35 MaxVid: maximum voltage." * "VID code corresponding to the maximum voltage" */ #define COFVID_STATUS_REGISTER_START_BIT_FOR_MIN_VID \ COFVID_STATUS_MSR_START_BIT_FOR_MAX_VOLTAGE_VID //"MSRC001_0070 COFVID Control Register" #define COFVID_CONTROL_REGISTER_MSR_ADDRESS 0xC0010070 /** see "31116 Rev 3.00 - September 07, 2007 AMD Family 10h Processor BKDG" * "MSRC001_0071 COFVID Status Register" */ #define COFVID_STATUS_REGISTER_MSR_ADDRESS 0xC0010071 extern float g_fMaxMultiplier; namespace AMD { /** function for AMD CPUs beginning with K10 (including 15hex. */ namespace fromK10 { /** Applies to AMD family 10h,11h */ inline float GetVoltageInVolt(const fastestUnsignedDataType voltageID) { /** BIOS and Kernel Developer’s Guide (BKDG) For AMD Family 10h Processors 31116 Rev 3.62 - January 11, 2013 MSRC001_0071CO COFVID Status Register * 2.4.1.6.3 Serial VID (SVI) Encodings: 1.550V - 0.0125V * SviVid[6:0]; /** BIOS and Kernel Developer’s Guide (BKDG) For AMD Family 10h Processors 31116 Rev 3.62 - January 11, 2013 MSRC001_0071CO COFVID Status Register * 15:9 CurCpuVid: current core VID. Read-only. In dual-node processors, CurCpuVid on internal node 0 is the voltage driven to VDD. CurCpuVid on internal node 1 is the voltage of the higest performance * P-state (lowest numbered P-state) requested by all cores on internal * node 1. CurCpuVid on internal node 1 is greater than or equal to * CurCpuVid on internal node 0. */ /** For AMD Turion X2 Ultra (family 11h) : * VID 28 = 1.2 = 1.55 - 28 * 0.0125 ; VID 64 = 0.75 = 1.55 - 64 * 0.0125 => 1.55 - voltageID * 0.0125 */ /** 41256 Rev 3.00 - July 07, 2008 AMD Family 11h Processor BKDG * chapter "2.4.1.2 Serial VID Interface" : * "The processor includes an interface, intended to control external * voltage regulators, called the serial VID inter-face (SVI)." * * see "31116 Rev 3.00 - September 07, 2007 AMD Family 10h Processor BKDG" * chapter "2.4.1.6.3 Serial VID (SVI) Encodings" * * see Intersil "ISL6265 FN6599.0 Data Sheet May 7, 2008", * "TABLE 3. SERIAL VID CODES" * * For family 15h CPU: inbetween VID "148" is shown when under load and on highest multiplier * VID 11 corresponds to 1.428 V? in CPU-Z 1.55 - 11 * 0.0125 = 1,4125 * VID 14 corresponds to 1.296/ 1.284 V in CPU-Z * VID 47 corresponds to 1.008 V shown in CPU-Z 1.55 - 47×0,0125=0,9625 * * 1.296V-1.008V=0,288V 47-14=33 * 1.428V- 1.008V=0,42V */ return 1.55f - voltageID*0.0125f; } inline fastestUnsignedDataType GetMaximumVoltageID() { // return 64 ; uint32_t dwEAXlowMostBits, dwEDXhighMostBits ; ReadMSR( COFVID_STATUS_REGISTER_MSR_ADDRESS, & dwEAXlowMostBits, & dwEDXhighMostBits, 1 ) ; fastestUnsignedDataType highestVID = ( dwEDXhighMostBits >> ( COFVID_STATUS_MSR_START_BIT_FOR_MAX_VID - 32 ) ) & BITMASK_FOR_LOWMOST_7BIT; DEBUGN("highest VID:" << highestVID) return highestVID ; } inline fastestUnsignedDataType GetMinimumVoltageID() { // return 36 ; uint32_t dwEAXlowMostBits, dwEDXhighMostBits ; ReadMSR( COFVID_STATUS_REGISTER_MSR_ADDRESS, & dwEAXlowMostBits, & dwEDXhighMostBits, 1 ) ; const fastestUnsignedDataType lowestVID = ( dwEDXhighMostBits >> ( COFVID_STATUS_REGISTER_START_BIT_FOR_MIN_VID - 32 ) ) & BITMASK_FOR_LOWMOST_7BIT; DEBUGN("lowest VID:" << lowestVID) return lowestVID ; } /** Applies to AMD family 10h, 11h, 15h */ inline void GetMinAndMaxVoltageID( fastestUnsignedDataType & voltageIDforLowestVoltage, fastestUnsignedDataType & voltageIDforHighestVoltage) { static uint32_t lowmost32bit, highmost32bit; ReadMSR( COFVID_STATUS_REGISTER_MSR_ADDRESS, & lowmost32bit, & highmost32bit, 1 ) ; /** -"42301 Rev 3.14 - January 23, 2013 BKDG for AMD Family 15h Models" * 00h-0Fh Processors", * -"31116 Rev 3.62 - January 11, 2013 AMD Family 10h Processor BKDG" * -"41256 Rev 3.00 - July 07, 2008 AMD Family 11h Processor BKDG": * "MSRC001_0071 COFVID Status:" * "48:42 MinVid: minimum voltage." "41:35 MaxVid: maximum voltage." */ voltageIDforLowestVoltage = ( highmost32bit >> ( COFVID_STATUS_MSR_START_BIT_FOR_MAX_VID_IN_EDX ) ) & BITMASK_FOR_LOWMOST_7BIT; /** -31116 Rev 3.62 - January 11, 2013 AMD Family 10h Processor BKDG : * "MSRC001_0071 COFVID Status Register", * "48:42 MinVid: minimum voltage" : * "00h indicates that no minimum VID code is specified." */ if( voltageIDforLowestVoltage == 0 ) voltageIDforLowestVoltage = 0b1010100; //Table 8: SVI and internal VID codes: 101_0100b 0.5000 V DEBUGN("voltage ID for minimum voltage::" << voltageIDforLowestVoltage ) voltageIDforHighestVoltage = ( highmost32bit >> /** -31116 Rev 3.62 - January 11, 2013 AMD Family 10h Processor BKDG : * "MSRC001_0071 COFVID Status Register", * "41:35 MaxVid: maximum voltages. Read-only. Specifies the VID code" : * "00h indicates that no maximum VID code is specified." */ /** 41256 Rev 3.00 - July 07, 2008 AMD Family 11h Processor BKDG : * MSRC001_0071 COFVID Status Register : * "41:35 [...]: maximum voltage. Read-only. Specifies the VID code * corresponding to the maximum voltage (lowest VID code) that the processor * drives. 00h indicates that no maximum VID code is specified. * See section 2.4.1 [Processor Power Planes And Voltage Control].*/ ( COFVID_STATUS_REGISTER_START_BIT_FOR_MIN_VID - 32 ) ) & BITMASK_FOR_LOWMOST_7BIT; DEBUGN("lowest VID:" << voltageIDforHighestVoltage ) } inline void GetCurrentVoltageIDfromCOFVIDstatusRegisterBits( const DWORD dwMSRlowmost, BYTE & byVoltageID) { /** 31116 Rev 3.62 - January 11, 2013 AMD Family 10h Processor BKDG * "15:9 CurCpuVid: current core VID. Read-only." */ byVoltageID = //(BYTE) ( // (g_dwLowmostBits & BITMASK_FOR_CPU_CORE_VOLTAGE_ID//=1111111000000000bin // ) >> 9 ) ; //<=>bits 9-15 shifted } ( dwMSRlowmost >> 9 ) & BITMASK_FOR_LOWMOST_7BIT ; } /** works for family 15 model 0-F, but not for family 15 model F-1F?! */ inline fastestUnsignedDataType GetCurrentVoltageIDfromCOFVIDstatusRegisterBits( const DWORD dwMSRlowmost) { /** 31116 Rev 3.62 - January 11, 2013 AMD Family 10h Processor BKDG * "15:9 CurCpuVid: current core VID. Read-only." */ return //(BYTE) ( // (g_dwLowmostBits & BITMASK_FOR_CPU_CORE_VOLTAGE_ID//=1111111000000000bin // ) >> 9 ) ; //<=>bits 9-15 shifted } ( dwMSRlowmost >> 9 ) & BITMASK_FOR_LOWMOST_7BIT ; } /** Uses table "Table 5: SVI and internal VID codes" (7 bit) because same * bit width as "15:9 CurCpuVid: current CPU core VID." (7 bit) ? */ inline fastestUnsignedDataType GetVoltageID(const float fVoltageInVolt ) { /** E.g. for "1.1" V the float value is 1.0999999 * (because not all numbers are representable with a 8 byte value) * so the voltage ID as float value gets "36.000004". */ /** 31116 Rev 3.62 - January 11, 2013 AMD Family 10h Processor BKDG : * "voltage = 1.550V - 0.0125V * SviVid[6:0];" * voltage = 1,55V - 0.0125V * voltageID | - 1.55V * voltage - 1.55 V = - 0.0125V * voltageID | : -0.0125V * (voltage - 1.55 V) / -0.0125V = voltageID */ float fVoltageID = (fVoltageInVolt - 1.55f) / -0.0125f; fastestUnsignedDataType voltageID = /** without explicit cast: compiler warning * Avoid g++ warning "warning: converting to `WORD' from `float'" */ (fastestUnsignedDataType) fVoltageID; /** Check to which integer voltage ID the float value is nearer. * E.g. for: "36.0000008" - "36" = "0.0000008". -> use "36" */ if (fVoltageID - (float) voltageID >= 0.5) ++ voltageID; return voltageID; } /** Applies to AMD family 10h, 11h */ inline float * GetAvailableVoltagesInVolt( WORD wCoreID , WORD * p_wNum ) { /** Must be a signed data type, else in the comparison in the loop the * signed data type is converted to the data type of this variable * (unsigned) */ fastestSignedDataType voltageIDforHighestVoltage; fastestUnsignedDataType voltageIDforLowestVoltage; GetMinAndMaxVoltageID(voltageIDforLowestVoltage, (fastestUnsignedDataType &) voltageIDforHighestVoltage); const fastestUnsignedDataType numAvailableVoltages = voltageIDforLowestVoltage - voltageIDforHighestVoltage + 1; float * ar_f = new float[numAvailableVoltages]; if( ar_f) { fastestUnsignedDataType arrayIndex = 0; /** see 31116 Rev 3.62 - January 11, 2013 AMD Family 10h Processor BKDG * , "Table 8: SVI and internal VID codes" : * Higher voltage IDs mean lower voltages */ for( /** Use signed data type here, else the value wraps to the max * value for the data type if 0 is decremented. */ fastestSignedDataType voltageID = voltageIDforLowestVoltage; voltageID >= voltageIDforHighestVoltage; voltageID --) { ar_f[arrayIndex ++] = GetVoltageInVolt(voltageID); } * p_wNum = numAvailableVoltages; } else * p_wNum = 0; return ar_f; } /*inline void GetAvailableVoltagesInVolt(VIDforLowestVoltage, minVID) { }*/ } } #endif /* FROM_K10_H_ */
42.238971
95
0.675081
st-gb
b72b4b4cc783b391ba99f760423d6b2772d66a1c
454
hpp
C++
2018/ED/T2/include/ScreenMenu.hpp
LorhanSohaky/UFSCar
af0e84946cbb61b12dfa738610065bbb0f4887a2
[ "MIT" ]
1
2021-04-24T05:33:26.000Z
2021-04-24T05:33:26.000Z
2018/ED/T2/include/ScreenMenu.hpp
LorhanSohaky/UFSCar
af0e84946cbb61b12dfa738610065bbb0f4887a2
[ "MIT" ]
8
2020-11-21T05:22:13.000Z
2021-09-22T13:42:22.000Z
2018/ED/T2/include/ScreenMenu.hpp
LorhanSohaky/UFSCar
af0e84946cbb61b12dfa738610065bbb0f4887a2
[ "MIT" ]
1
2018-11-18T15:50:55.000Z
2018-11-18T15:50:55.000Z
#ifndef SCREEN_MENU_HPP #define SCREEN_MENU_HPP #include "Screen.hpp" #include <SFML/Audio.hpp> #include <SFML/Graphics.hpp> class ScreenMenu : Screen { public: explicit ScreenMenu( GameRef& gameRef ); void loadAssets(); void draw(); void update(); private: sf::Sprite background; sf::Sprite playButton; sf::Sprite creditsButton; sf::Sprite audioButton; sf::Music* music; sf::Sound clickSound; }; #endif
16.814815
44
0.676211
LorhanSohaky
b72fb196dd2c5415588ce2146628e6f56fc4cb26
12,364
cpp
C++
Chapter04/scratchpad.cpp
trantrongquy/Hands-On-System-Programming-with-CPP
c29f464c4df79f0d5a55a61f02a2558be74a329c
[ "MIT" ]
88
2018-07-20T17:38:40.000Z
2022-03-16T15:00:20.000Z
Chapter04/scratchpad.cpp
trantrongquy/Hands-On-System-Programming-with-CPP
c29f464c4df79f0d5a55a61f02a2558be74a329c
[ "MIT" ]
1
2020-01-01T08:12:24.000Z
2020-01-01T08:12:24.000Z
Chapter04/scratchpad.cpp
trantrongquy/Hands-On-System-Programming-with-CPP
c29f464c4df79f0d5a55a61f02a2558be74a329c
[ "MIT" ]
46
2019-01-27T15:19:45.000Z
2022-03-04T13:21:23.000Z
// // Copyright (C) 2018 Rian Quinn <rianquinn@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // ----------------------------------------------------------------------------- // Section: Stream Based IO // ----------------------------------------------------------------------------- #if SNIPPET01 #include <iostream> int main(void) { if (auto i = 42; i > 0) { std::cout << "Hello World\n"; } } // > g++ scratchpad.cpp; ./a.out // Hello World #endif #if SNIPPET02 #include <iostream> int main(void) { switch(auto i = 42) { case 42: std::cout << "Hello World\n"; break; default: break; } } // > g++ scratchpad.cpp; ./a.out // Hello World #endif #if SNIPPET03 #include <iostream> constexpr const auto val = true; int main(void) { if (val) { std::cout << "Hello World\n"; } } // > g++ scratchpad.cpp; ./a.out // Hello World #endif #if SNIPPET04 #include <iostream> int main(void) { if constexpr (constexpr const auto i = 42; i > 0) { std::cout << "Hello World\n"; } } // > g++ scratchpad.cpp; ./a.out // Hello World #endif #if SNIPPET05 #include <iostream> int main(void) { static_assert(42 == 42, "the answer"); } // > g++ scratchpad.cpp; ./a.out // #endif #if SNIPPET06 #include <iostream> int main(void) { static_assert(42 == 42); } // > g++ scratchpad.cpp; ./a.out // #endif #if SNIPPET07 #include <iostream> namespace X::Y::Z { auto msg = "Hello World\n"; } int main(void) { std::cout << X::Y::Z::msg; } // > g++ scratchpad.cpp; ./a.out // Hello World #endif #if SNIPPET08 #include <iostream> namespace X { namespace Y { namespace Z { auto msg = "Hello World\n"; } } } int main(void) { std::cout << X::Y::Z::msg; } // > g++ scratchpad.cpp; ./a.out // Hello World #endif #if SNIPPET09 #include <iostream> std::pair<const char *, int> give_me_a_pair() { return {"The answer is: ", 42}; } int main(void) { auto [msg, answer] = give_me_a_pair(); std::cout << msg << answer << '\n'; } // > g++ scratchpad.cpp; ./a.out // The answer is: 42 #endif #if SNIPPET10 #include <utility> #include <iostream> std::pair<const char *, int> give_me_a_pair() { return {"The answer is: ", 42}; } int main(void) { auto p = give_me_a_pair(); std::cout << std::get<0>(p) << std::get<1>(p) << '\n'; } // > g++ scratchpad.cpp; ./a.out // The answer is: 42 #endif #if SNIPPET11 #include <iostream> struct mystruct { const char *msg; int answer; }; mystruct give_me_a_struct() { return {"The answer is: ", 42}; } int main(void) { auto [msg, answer] = give_me_a_struct(); std::cout << msg << answer << '\n'; } // > g++ scratchpad.cpp; ./a.out // The answer is: 42 #endif #if SNIPPET12 #include <iostream> inline auto msg = "Hello World\n"; int main(void) { std::cout << msg; } // > g++ scratchpad.cpp; ./a.out // Hello World #endif #if SNIPPET13 #include <iostream> #include <string_view> int main(void) { std::string_view str("Hello World\n"); std::cout << str; } // > g++ scratchpad.cpp; ./a.out // Hello World #endif #if SNIPPET14 #include <iostream> #include <string_view> int main(void) { std::string_view str("Hello World"); std::cout << str.front() << '\n'; std::cout << str.back() << '\n'; std::cout << str.at(1) << '\n'; std::cout << str.data() << '\n'; } // > g++ scratchpad.cpp; ./a.out // H // d // e // Hello World #endif #if SNIPPET15 #include <iostream> #include <string_view> int main(void) { std::string_view str("Hello World"); std::cout << str.size() << '\n'; std::cout << str.max_size() << '\n'; std::cout << str.empty() << '\n'; } // > g++ scratchpad.cpp; ./a.out // 11 // 4611686018427387899 // 0 #endif #if SNIPPET16 #include <iostream> #include <string_view> int main(void) { std::string_view str("Hello World"); str.remove_prefix(1); str.remove_suffix(1); std::cout << str << '\n'; } // > g++ scratchpad.cpp; ./a.out // ello Worl #endif #if SNIPPET17 #include <iostream> #include <string_view> int main(void) { std::string_view str("Hello World"); std::cout << str.substr(0, 5) << '\n'; } // > g++ scratchpad.cpp; ./a.out // Hello #endif #if SNIPPET18 #include <iostream> #include <string_view> int main(void) { std::string_view str("Hello World"); if (str.compare("Hello World") == 0) { std::cout << "Hello World\n"; } std::cout << str.compare("Hello") << '\n'; std::cout << str.compare("World") << '\n'; } // > g++ scratchpad.cpp; ./a.out // Hello World // 6 // -1 #endif #if SNIPPET19 #include <iostream> int main(void) { std::string_view str("Hello this is a test of Hello World"); std::cout << str.find("Hello") << '\n'; std::cout << str.rfind("Hello") << '\n'; std::cout << str.find_first_of("Hello") << '\n'; std::cout << str.find_last_of("Hello") << '\n'; std::cout << str.find_first_not_of("Hello") << '\n'; std::cout << str.find_last_not_of("Hello") << '\n'; } // > g++ scratchpad.cpp; ./a.out // 0 // 24 // 0 // 33 // 5 // 34 #endif #if SNIPPET20 #include <iostream> #include <any> struct mystruct { int data; }; int main(void) { auto myany = std::make_any<int>(42); std::cout << std::any_cast<int>(myany) << '\n'; myany = 4.2; std::cout << std::any_cast<double>(myany) << '\n'; myany = mystruct{42}; std::cout << std::any_cast<mystruct>(myany).data << '\n'; } // > g++ scratchpad.cpp; ./a.out // 42 // 4.2 // 42 #endif #if SNIPPET21 #include <iostream> #include <variant> int main(void) { std::variant<int, double> v = 42; std::cout << std::get<int>(v) << '\n'; v = 4.2; std::cout << std::get<double>(v) << '\n'; } // > g++ scratchpad.cpp; ./a.out // 42 // 4.2 #endif #if SNIPPET22 #include <iostream> #include <optional> class myclass { public: int val; myclass(int v) : val{v} { std::cout << "constructed\n"; } }; int main(void) { std::optional<myclass> o; std::cout << "created, but not constructed\n"; if (o) { std::cout << "Attempt #1: " << o->val << '\n'; } o = myclass{42}; if (o) { std::cout << "Attempt #2: " << o->val << '\n'; } } // > g++ scratchpad.cpp; ./a.out // created, but not constructed // constructed // Attempt #2: 42 #endif #if SNIPPET23 #include <iostream> class myclass { public: myclass() { std::cout << "Hello from constructor\n"; } ~myclass() { std::cout << "Hello from destructor\n"; } }; int main(void) { myclass c; } // > g++ scratchpad.cpp; ./a.out // Hello from constructor // Hello from destructor #endif #if SNIPPET24 #include <iostream> class myclass { int *ptr; public: myclass() : ptr{new int(42)} { } ~myclass() { delete ptr; } int get() { return *ptr; } }; int main(void) { myclass c; std::cout << "The answer is: " << c.get() << '\n'; } // > g++ scratchpad.cpp; ./a.out // The answer is: 42 #endif #if SNIPPET25 #include <iostream> class myclass { FILE *m_file; public: myclass(const char *filename) : m_file{fopen(filename, "rb")} { if (m_file == 0) { throw std::runtime_error("unable to open file"); } } ~myclass() { fclose(m_file); std::clog << "Hello from destructor\n"; } }; int main(void) { myclass c1("test.txt"); try { myclass c2("does_not_exist.txt"); } catch(const std::exception &e) { std::cout << "exception: " << e.what() << '\n'; } } // > g++ scratchpad.cpp; touch test.txt; ./a.out // exception: unable to open file // Hello from destructor #endif #if SNIPPET26 #include <gsl/gsl> void init(int *p) { *p = 0; } int main(void) { auto p = new int; init(p); delete p; } // > g++ scratchpad.cpp; ./a.out // #endif #if SNIPPET27 #include <gsl/gsl> void init(int *p) { *p = 0; } int main(void) { gsl::owner<int *> p = new int; init(p); delete p; } // > g++ scratchpad.cpp; ./a.out // #endif #if SNIPPET28 #include <gsl/gsl> gsl::not_null<int *> test(gsl::not_null<int *> p) { return p; } int main(void) { auto p1 = std::make_unique<int>(); auto p2 = test(gsl::not_null(p1.get())); } // > g++ scratchpad.cpp; ./a.out // #endif #if SNIPPET29 #define GSL_THROW_ON_CONTRACT_VIOLATION #include <gsl/gsl> #include <iostream> int main(void) { int array[5] = {1, 2, 3, 4, 5}; auto span = gsl::span(array); for (const auto &elem : span) { std::clog << elem << '\n'; } for (auto i = 0; i < 5; i++) { std::clog << span[i] << '\n'; } try { std::clog << span[5] << '\n'; } catch(const gsl::fail_fast &e) { std::cout << "exception: " << e.what() << '\n'; } } // > g++ scratchpad.cpp; ./a.out // 1 // 2 // 3 // 4 // 5 // 1 // 2 // 3 // 4 // 5 // exception: GSL: Precondition failure at ... #endif #if SNIPPET30 #include <gsl/gsl> #include <iostream> int main(void) { gsl::cstring_span<> str = gsl::ensure_z("Hello World\n"); std::cout << str.data(); for (const auto &elem : str) { std::clog << elem; } } // > g++ scratchpad.cpp; ./a.out // Hello World // Hello World #endif #if SNIPPET31 #define GSL_THROW_ON_CONTRACT_VIOLATION #include <gsl/gsl> #include <iostream> int main(void) { try { Expects(false); } catch(const gsl::fail_fast &e) { std::cout << "exception: " << e.what() << '\n'; } } // > g++ scratchpad.cpp; ./a.out // exception: GSL: Precondition failure at ... #endif #if SNIPPET32 #define GSL_THROW_ON_CONTRACT_VIOLATION #include <gsl/gsl> #include <iostream> int test(int i) { Expects(i >= 0 && i < 41); i++; Ensures(i < 42); return i; } int main(void) { test(0); try { test(42); } catch(const gsl::fail_fast &e) { std::cout << "exception: " << e.what() << '\n'; } } // > g++ scratchpad.cpp; ./a.out // exception: GSL: Precondition failure at ... #endif #if SNIPPET33 #include <gsl/gsl> #include <iostream> int test(int i) { Expects(i < 42); i = 42; Ensures(i == 42); return i; } int main(void) { std::cout << test(0) << '\n'; } // > g++ scratchpad.cpp; ./a.out // 42 #endif #if SNIPPET34 #define concat1(a,b) a ## b #define concat2(a,b) concat1(a,b) #define ___ concat2(dont_care, __COUNTER__) #include <gsl/gsl> #include <iostream> int main(void) { auto ___ = gsl::finally([]{ std::cout << "Hello World\n"; }); } // > g++ scratchpad.cpp; ./a.out // Hello World #endif #if SNIPPET35 #include <gsl/gsl> #include <iostream> int main(void) { uint64_t val = 42; auto val1 = gsl::narrow<uint32_t>(val); auto val2 = gsl::narrow_cast<uint32_t>(val); } // > g++ scratchpad.cpp; ./a.out // #endif #if SNIPPET36 #define GSL_THROW_ON_CONTRACT_VIOLATION #include <gsl/gsl> #include <iostream> int main(void) { uint64_t val = 0xFFFFFFFFFFFFFFFF; try { gsl::narrow<uint32_t>(val); } catch(...) { std::cout << "narrow failed\n"; } } // > g++ scratchpad.cpp; ./a.out // narrow failed #endif
14.376744
81
0.566564
trantrongquy
b73291326c1b1a358be83c6fd9b28064b53e461e
1,194
cc
C++
examples/rpcbench/server.cc
byzhang/claire-protorpc
18decb2592d117b73f5943614990adfe9f7687b3
[ "BSD-2-Clause" ]
null
null
null
examples/rpcbench/server.cc
byzhang/claire-protorpc
18decb2592d117b73f5943614990adfe9f7687b3
[ "BSD-2-Clause" ]
null
null
null
examples/rpcbench/server.cc
byzhang/claire-protorpc
18decb2592d117b73f5943614990adfe9f7687b3
[ "BSD-2-Clause" ]
null
null
null
#include <examples/rpcbench/echo.pb.h> #include <boost/bind.hpp> #include <claire/protorpc/RpcServer.h> #include <claire/common/events/EventLoop.h> #include <claire/common/logging/Logging.h> #include <claire/netty/InetAddress.h> using namespace claire; DEFINE_int32(num_threads, 4, "num of RpcServer threads"); namespace echo { class EchoServiceImpl : public EchoService { public: virtual void Echo(RpcControllerPtr& controller, const ::echo::EchoRequestPtr& request, const ::echo::EchoResponse* response_prototype, const RpcDoneCallback& done) { EchoResponse response; response.set_str(request->str()); done(controller, &response); } }; } int main(int argc, char* argv[]) { ::google::ParseCommandLineFlags(&argc, &argv, true); ::google::InitGoogleLogging(argv[0]); EventLoop loop; InetAddress listen_address(8081); InetAddress stats_address(8082); echo::EchoServiceImpl impl; RpcServer server(&loop, listen_address, stats_address); server.set_num_threads(FLAGS_num_threads); server.RegisterService(&impl); server.Start(); loop.loop(); }
24.367347
69
0.679229
byzhang
b7340c408c1c4898afc411a34aa908f0ed5ca779
2,378
cpp
C++
framework/sphere.cpp
henrik-leisdon/programmiersprachen-raytracer-1
bd3185095ba50b55f85394d361deb43a7a30c871
[ "MIT" ]
null
null
null
framework/sphere.cpp
henrik-leisdon/programmiersprachen-raytracer-1
bd3185095ba50b55f85394d361deb43a7a30c871
[ "MIT" ]
1
2019-08-03T11:36:46.000Z
2019-08-27T16:23:08.000Z
framework/sphere.cpp
henrik-leisdon/programmiersprachen-raytracer-1
bd3185095ba50b55f85394d361deb43a7a30c871
[ "MIT" ]
null
null
null
#include "sphere.hpp" #include <math.h> #include <glm/gtx/intersect.hpp> using namespace std; using namespace glm; Sphere::Sphere(): Shape(), center_({0.0,0.0,0.0}), radius_{0.0} {}; Sphere::Sphere(string name, vec3 const& center, double radius, shared_ptr<Material> material): Shape{name, material}, center_{center}, radius_{radius} {}; Sphere::~Sphere() {} vec3 Sphere::getCenter() const { return center_; } double Sphere::getRadius() const { return radius_; } double Sphere::area() const { double area = 4*M_PI*pow(getRadius(),2); return area; } double Sphere::volume() const { double volume = (4.0/3.0)*M_PI*pow(getRadius(),3); return volume; } Hit Sphere::intersect(Ray const &firstRay, float &t) { bool intersect; Hit result; Ray ray={firstRay.origin, firstRay.direction}; if(isTransformed_){ ray = transformRay(inverse_world_transform_, ray); } else { ray = firstRay; } vec3 normDir = normalize(ray.direction); intersect = intersectRaySphere(ray.origin, normalize(ray.direction), center_ ,radius_*radius_, t); if(intersect) { vec3 hitpoint = vec3{ray.origin+normDir*t}; vec3 normToShape = vec3{hitpoint-center_}; //cout << getName() << " normal in intersect: " << normToShape.x << " " << normToShape.y << " " << normToShape.z << "\n"; result.hit_ = true; result.hitnormal_ = normToShape; result.hitpoint_ = hitpoint; result.dist_ = t; result.direction_ = normDir; if(isTransformed_) { vec4 transformNormal = glm::normalize(transpose(inverse_world_transform_)*vec4{result.hitnormal_,0}); result.hitnormal_ = vec3({transformNormal.x, transformNormal.y, transformNormal.z}); vec4 transformHit = world_transform_ * vec4{result.hitpoint_, 1}; result.hitpoint_ = vec3{transformHit.x, transformHit.y, transformHit.z}; } return result; } else { Hit result = Hit(); return result; } } ostream& Sphere::print(ostream &os) const { Shape::print(os); os << "Position : " << center_.x << ", " << center_.y << ", " << center_.z << "\n" << "Radius : " << radius_ << "\n"; return os; } ostream& operator << (ostream& os, const Sphere s) { return s.print(os); }
25.297872
130
0.611438
henrik-leisdon
b7354fe300e0432d917e1ede407279516064052d
1,288
cpp
C++
clang-tools-extra/include-cleaner/lib/WalkAST.cpp
ornata/llvm-project
494913b8b4e4bce0b3525e5569d8e486e82b9a52
[ "Apache-2.0" ]
null
null
null
clang-tools-extra/include-cleaner/lib/WalkAST.cpp
ornata/llvm-project
494913b8b4e4bce0b3525e5569d8e486e82b9a52
[ "Apache-2.0" ]
null
null
null
clang-tools-extra/include-cleaner/lib/WalkAST.cpp
ornata/llvm-project
494913b8b4e4bce0b3525e5569d8e486e82b9a52
[ "Apache-2.0" ]
null
null
null
//===--- WalkAST.cpp - Find declaration references in the AST -------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "AnalysisInternal.h" #include "clang/AST/RecursiveASTVisitor.h" namespace clang { namespace include_cleaner { namespace { using DeclCallback = llvm::function_ref<void(SourceLocation, NamedDecl &)>; class ASTWalker : public RecursiveASTVisitor<ASTWalker> { DeclCallback Callback; void report(SourceLocation Loc, NamedDecl *ND) { if (!ND || Loc.isInvalid()) return; Callback(Loc, *cast<NamedDecl>(ND->getCanonicalDecl())); } public: ASTWalker(DeclCallback Callback) : Callback(Callback) {} bool VisitTagTypeLoc(TagTypeLoc TTL) { report(TTL.getNameLoc(), TTL.getDecl()); return true; } bool VisitDeclRefExpr(DeclRefExpr *DRE) { report(DRE->getLocation(), DRE->getFoundDecl()); return true; } }; } // namespace void walkAST(Decl &Root, DeclCallback Callback) { ASTWalker(Callback).TraverseDecl(&Root); } } // namespace include_cleaner } // namespace clang
26.833333
80
0.662267
ornata
b735666407b772b124d341e3278a9272d3e27841
289
cpp
C++
software/GCSQt/TrajectoryGen/trajectory_utils.cpp
tucuongbrt/PIFer
e2ac4d4443e1c6a6263f91c32f28dbe767590359
[ "MIT" ]
2
2021-03-17T18:23:15.000Z
2021-03-18T06:19:44.000Z
software/GCSQt/TrajectoryGen/trajectory_utils.cpp
tucuongbrt/PIFer
e2ac4d4443e1c6a6263f91c32f28dbe767590359
[ "MIT" ]
2
2021-04-03T08:50:46.000Z
2021-04-03T08:50:57.000Z
software/GCSQt/TrajectoryGen/trajectory_utils.cpp
tucuongbrt/PIFer
e2ac4d4443e1c6a6263f91c32f28dbe767590359
[ "MIT" ]
2
2021-04-14T00:18:23.000Z
2021-05-06T05:57:54.000Z
#include "trajectory_utils.h" QScatterDataArray to_scatter_data_array(QVector<trajectory_point_2d_t> trajectory){ QScatterDataArray data_array; for (trajectory_point_2d_t point : trajectory){ data_array << QVector3D(point.x, point.y, 0.0f); } return data_array; }
28.9
83
0.747405
tucuongbrt
b738175f4ebe5b9369135316a54a20bd5967766b
1,600
cc
C++
UVa/409_Excuses, Excuses!/409.cc
pdszhh/ACM
956b3d03a5d3f070ef24c940b7459f5cccb11d6c
[ "MIT" ]
1
2019-05-05T03:51:20.000Z
2019-05-05T03:51:20.000Z
UVa/409_Excuses, Excuses!/409.cc
pdszhh/ACM
956b3d03a5d3f070ef24c940b7459f5cccb11d6c
[ "MIT" ]
null
null
null
UVa/409_Excuses, Excuses!/409.cc
pdszhh/ACM
956b3d03a5d3f070ef24c940b7459f5cccb11d6c
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <algorithm> #include <locale> using namespace std; int main() { std::locale loc; int k, e; int index = 1; while (cin >> k >> e) { cin.get(); string *keyword = new string[k]; string *excuse = new string[e]; string *excuseLower = new string[e]; int *times = new int[e]; int maxTimes = 0; // input for (int i = 0; i < k; i++) { getline(cin, keyword[i]); } for (int i = 0; i < e; i++) { getline(cin, excuse[i]); excuseLower[i] = excuse[i]; transform(excuseLower[i].begin(), excuseLower[i].end(), excuseLower[i].begin(), ::tolower); } // calc for (int i = 0; i < e; i++) { times[i] = -1; for (int j = 0; j < k; j++) { int pos = -1; while ((pos = excuseLower[i].find(keyword[j], pos + 1)) != excuseLower[i].npos) { if (pos == 0 or pos + keyword[j].length() == excuseLower[i].length() or (not isalpha(excuseLower[i][pos - 1], loc) and not isalpha(excuseLower[i][pos + keyword[j].length()], loc))) times[i]++; } maxTimes = max(times[i], maxTimes); } } // output cout << "Excuse Set #" << index++ << endl; for (int i = 0; i < e; i++) if (times[i] == maxTimes) cout << excuse[i] << endl; cout << endl; } return 0; }
28.571429
103
0.434375
pdszhh
b7385a71a9bcf5c02ed00ee07eebbb6b98551212
12,793
cpp
C++
benchmark-tests/benchmark_tests_fftw3.cpp
opalcompany/Simple-FFT
5f397670ecac53c68ab1df90c36a319bd277b5d3
[ "MIT" ]
115
2015-01-11T23:41:28.000Z
2022-03-08T01:09:49.000Z
benchmark-tests/benchmark_tests_fftw3.cpp
opalcompany/Simple-FFT
5f397670ecac53c68ab1df90c36a319bd277b5d3
[ "MIT" ]
7
2018-07-26T21:42:40.000Z
2021-11-08T20:24:03.000Z
benchmark-tests/benchmark_tests_fftw3.cpp
opalcompany/Simple-FFT
5f397670ecac53c68ab1df90c36a319bd277b5d3
[ "MIT" ]
25
2015-03-20T14:41:56.000Z
2021-12-29T09:51:54.000Z
#include "../include/simple_fft/fft_settings.h" #ifndef __USE_SQUARE_BRACKETS_FOR_ELEMENT_ACCESS_OPERATOR #define __USE_SQUARE_BRACKETS_FOR_ELEMENT_ACCESS_OPERATOR #endif #include "benchmark_tests_fftw3.h" #include "../unit-tests/test_fft.hpp" #include <vector> #include <complex> #include <ctime> #include <iostream> #include <iomanip> #include <fftw3.h> namespace simple_fft { namespace fft_test { bool BenchmarkTestAgainstFFTW3() { bool res; const char * err_str = NULL; const int numFFTLoops1D = 10000; const int numFFTLoops2D = 500; const int numFFTLoops3D = 15; using namespace pulse_params; std::vector<real_type> t, x, y; makeGridsForPulse3D(t, x, y); // typedefing vectors typedef std::vector<real_type> RealArray1D; typedef std::vector<complex_type> ComplexArray1D; typedef std::vector<std::vector<real_type> > RealArray2D; typedef std::vector<std::vector<complex_type> > ComplexArray2D; typedef std::vector<std::vector<std::vector<real_type> > > RealArray3D; typedef std::vector<std::vector<std::vector<complex_type> > > ComplexArray3D; // 1D fields and spectrum RealArray1D E1_real(nt); ComplexArray1D E1_complex(nt), G1(nt); // 2D fields and spectrum RealArray2D E2_real(nt); ComplexArray2D E2_complex(nt), G2(nt); int grid_size_t = static_cast<int>(nt); #ifndef __clang__ #ifdef __USE_OPENMP #pragma omp parallel for #endif #endif for(int i = 0; i < grid_size_t; ++i) { E2_real[i].resize(nx); E2_complex[i].resize(nx); G2[i].resize(nx); } // 3D fields and spectrum RealArray3D E3_real(nt); ComplexArray3D E3_complex(nt), G3(nt); int grid_size_x = static_cast<int>(nx); #ifndef __clang__ #ifdef __USE_OPENMP #pragma omp parallel for #endif #endif for(int i = 0; i < grid_size_t; ++i) { E3_real[i].resize(nx); E3_complex[i].resize(nx); G3[i].resize(nx); for(int j = 0; j < grid_size_x; ++j) { E3_real[i][j].resize(ny); E3_complex[i][j].resize(ny); G3[i][j].resize(ny); } } CMakeInitialPulses3D<RealArray1D,RealArray2D,RealArray3D,true>::makeInitialPulses(E1_real, E2_real, E3_real); CMakeInitialPulses3D<ComplexArray1D,ComplexArray2D,ComplexArray3D,false>::makeInitialPulses(E1_complex, E2_complex, E3_complex); // Measure the execution time of Simple FFT // 1) 1D Simple FFT for real data clock_t beginTime = clock(); for(int i = 0; i < numFFTLoops1D; ++i) { res = FFT(E1_real, G1, nt, err_str); if (!res) { std::cout << "Simple FFT 1D real failed: " << err_str << std::endl; return false; } } std::cout << "Simple 1D FFT for real data: execution time for " << numFFTLoops1D << " loops: " << std::setprecision(20) << real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl; // 2) 1D Simple FFT for complex data beginTime = clock(); for(int i = 0; i < numFFTLoops1D; ++i) { res = FFT(E1_complex, G1, nt, err_str); if (!res) { std::cout << "Simple FFT 1D complex failed: " << err_str << std::endl; return false; } } std::cout << "Simple 1D FFT for complex data: execution time for " << numFFTLoops1D << " loops: " << std::setprecision(20) << real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl; // 3) 2D Simple FFT for real data beginTime = clock(); for(int i = 0; i < numFFTLoops2D; ++i) { res = FFT(E2_real, G2, nt, nx, err_str); if (!res) { std::cout << "Simple FFT 2D real failed: " << err_str << std::endl; return false; } } std::cout << "Simple 2D FFT for real data: execution time for " << numFFTLoops2D << " loops: " << std::setprecision(20) << real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl; // 4) 2D Simple FFT for complex data beginTime = clock(); for(int i = 0; i < numFFTLoops2D; ++i) { res = FFT(E2_complex, G2, nt, nx, err_str); if (!res) { std::cout << "Simple FFT 2D complex failed: " << err_str << std::endl; return false; } } std::cout << "Simple 2D FFT for complex data: execution time for " << numFFTLoops2D << " loops: " << std::setprecision(20) << real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl; // 5) 3D Simple FFT for real data beginTime = clock(); for(int i = 0; i < numFFTLoops3D; ++i) { res = FFT(E3_real, G3, nt, nx, ny, err_str); if (!res) { std::cout << "Simple FFT 3D real failed: " << err_str << std::endl; return false; } } std::cout << "Simple 3D FFT for real data: execution time for " << numFFTLoops3D << " loops: " << std::setprecision(20) << real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl; // 6) 3D Simple FFT for complex data beginTime = clock(); for(int i = 0; i < numFFTLoops3D; ++i) { res = FFT(E3_complex, G3, nt, nx, ny, err_str); if (!res) { std::cout << "Simple FFT 3D complex failed: " << err_str << std::endl; return false; } } std::cout << "Simple 3D FFT for complex data: execution time for " << numFFTLoops3D << " loops: " << std::setprecision(20) << real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl; // Measure the execution time for FFTW3 // 1) FFTW 1D for real data fftw_plan fftwPlan = fftw_plan_dft_r2c_1d(nt, &E1_real[0], reinterpret_cast<fftw_complex*>(&G1[0]), FFTW_MEASURE); beginTime = clock(); for(int i = 0; i < numFFTLoops1D; ++i) { fftw_execute(fftwPlan); } std::cout << "FFTW3 1D FFT for real data: execution time for " << numFFTLoops1D << " loops: " << std::setprecision(20) << real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl; fftw_destroy_plan(fftwPlan); // 2) FFTW 1D for complex data fftwPlan = fftw_plan_dft_1d(nt, reinterpret_cast<fftw_complex*>(&E1_complex[0]), reinterpret_cast<fftw_complex*>(&G1[0]), FFTW_FORWARD, FFTW_MEASURE); beginTime = clock(); for(int i = 0; i < numFFTLoops1D; ++i) { fftw_execute(fftwPlan); } std::cout << "FFTW3 1D FFT for complex data: execution time for " << numFFTLoops1D << " loops: " << std::setprecision(20) << real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl; fftw_destroy_plan(fftwPlan); // 3) FFTW 2D for real data // NOTE: I can't pass my data to FFTW in its original form, it causes runtime errors, // so I'm allocating another buffer array and copying my data twice - // before and after the FFT. And yes, I'm including the time it takes // into the measurement because I'm measuring the time to get the job done, // not the time of some function being running. beginTime = clock(); real_type* twoDimRealArray = (real_type*)(fftw_malloc(nt*nx*sizeof(real_type))); fftw_complex* twoDimComplexArray = (fftw_complex*)(fftw_malloc(nt*nx*sizeof(fftw_complex))); for(size_t i = 0; i < nt; ++i) { for(size_t j = 0; j < nx; ++j) { *(twoDimRealArray + i * nx + j) = E2_real[i][j]; } } fftwPlan = fftw_plan_dft_r2c_2d(nt, nx, twoDimRealArray, twoDimComplexArray, FFTW_MEASURE); for(int i = 0; i < numFFTLoops2D; ++i) { fftw_execute(fftwPlan); } for(size_t i = 0; i < nt; ++i) { for(size_t j = 0; j < nx; ++j) { G2[i][j] = complex_type((*(twoDimComplexArray + i*nx + j))[0], (*(twoDimComplexArray + i*nx + j))[1]); } } std::cout << "FFTW 2D FFT for real data: execution time for " << numFFTLoops2D << " loops: " << std::setprecision(20) << real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl; fftw_destroy_plan(fftwPlan); // 4) FFTW 2D for complex data beginTime = clock(); twoDimComplexArray = (fftw_complex*)(fftw_malloc(nt*nx*sizeof(fftw_complex))); fftw_complex* twoDimComplexArraySpectrum = (fftw_complex*)(fftw_malloc(nt*nx*sizeof(fftw_complex))); for(size_t i = 0; i < nt; ++i) { for(size_t j = 0; j < nx; ++j) { *(twoDimComplexArray + i * nx + j)[0] = std::real(E2_complex[i][j]); *(twoDimComplexArray + i * nx + j)[1] = std::imag(E2_complex[i][j]); } } fftwPlan = fftw_plan_dft_2d(nt, nx, twoDimComplexArray, twoDimComplexArraySpectrum, FFTW_FORWARD, FFTW_MEASURE); for(int i = 0; i < numFFTLoops2D; ++i) { fftw_execute(fftwPlan); } for(size_t i = 0; i < nt; ++i) { for(size_t j = 0; j < nx; ++j) { G2[i][j] = complex_type((*(twoDimComplexArraySpectrum + i*nx + j))[0], (*(twoDimComplexArraySpectrum + i*nx + j))[1]); } } std::cout << "FFTW 2D FFT for complex data: execution time for " << numFFTLoops2D << " loops: " << std::setprecision(20) << real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl; fftw_destroy_plan(fftwPlan); // 5) FFTW 3D for real data beginTime = clock(); real_type* threeDimRealArray = (real_type*)(fftw_malloc(nt*nx*ny*sizeof(real_type))); fftw_complex* threeDimComplexArray = (fftw_complex*)(fftw_malloc(nt*nx*ny*sizeof(fftw_complex))); for(size_t i = 0; i < nt; ++i) { for(size_t j = 0; j < nx; ++j) { for(size_t k = 0; k < ny; ++k) { *(threeDimRealArray + i * nx * ny + j * ny + k) = E3_real[i][j][k]; } } } fftwPlan = fftw_plan_dft_r2c_3d(nt, nx, ny, threeDimRealArray, threeDimComplexArray, FFTW_MEASURE); for(int i = 0; i < numFFTLoops3D; ++i) { fftw_execute(fftwPlan); } for(size_t i = 0; i < nt; ++i) { for(size_t j = 0; j < nx; ++j) { for(size_t k = 0; k < ny; ++k) { E3_real[i][j][k] = *(threeDimRealArray + i * nx * ny + j * ny + k); G3[i][j][k] = complex_type((*(threeDimComplexArray + i * nx * ny + j * ny + k))[0], (*(threeDimComplexArray + i * nx * ny + j * ny + k))[1]); } } } std::cout << "FFTW 3D FFT for real data: execution time for " << numFFTLoops3D << " loops: " << std::setprecision(20) << real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl; fftw_destroy_plan(fftwPlan); // 6) FFTW 3D for complex data beginTime = clock(); threeDimComplexArray = (fftw_complex*)(fftw_malloc(nt*nx*ny*sizeof(fftw_complex))); fftw_complex* threeDimComplexArraySpectrum = (fftw_complex*)(fftw_malloc(nt*nx*ny*sizeof(fftw_complex))); for(size_t i = 0; i < nt; ++i) { for(size_t j = 0; j < nx; ++j) { for(size_t k = 0; k < ny; ++k) { *(threeDimComplexArray + i * nx * ny + j * ny + k)[0] = std::real(E3_complex[i][j][k]); *(threeDimComplexArray + i * nx * ny + j * ny + k)[1] = std::imag(E3_complex[i][j][k]); } } } fftwPlan = fftw_plan_dft_3d(nt, nx, ny, threeDimComplexArray, threeDimComplexArraySpectrum, FFTW_FORWARD, FFTW_MEASURE); for(int i = 0; i < numFFTLoops3D; ++i) { fftw_execute(fftwPlan); } for(size_t i = 0; i < nt; ++i) { for(size_t j = 0; j < nx; ++j) { for(size_t k = 0; k < ny; ++k) { G3[i][j][k] = complex_type((*(threeDimComplexArraySpectrum + i * nx * ny + j * ny + k))[0], (*(threeDimComplexArraySpectrum + i * nx * ny + j * ny + k))[1]); } } } std::cout << "FFTW 3D FFT for complex data: execution time for " << numFFTLoops3D << " loops: " << std::setprecision(20) << real_type(clock() - beginTime)/CLOCKS_PER_SEC << std::endl; fftw_destroy_plan(fftwPlan); return true; } } // namespace fft_test } // namespace simple_fft
41.944262
133
0.551317
opalcompany
b738eb2d98a690db116106b3dc53c5bc86bc13ab
1,536
cpp
C++
aws-cpp-sdk-route53/source/model/ListHostedZonesByVPCRequest.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-route53/source/model/ListHostedZonesByVPCRequest.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-route53/source/model/ListHostedZonesByVPCRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/route53/model/ListHostedZonesByVPCRequest.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <aws/core/http/URI.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Route53::Model; using namespace Aws::Utils::Xml; using namespace Aws::Utils; using namespace Aws::Http; ListHostedZonesByVPCRequest::ListHostedZonesByVPCRequest() : m_vPCIdHasBeenSet(false), m_vPCRegion(VPCRegion::NOT_SET), m_vPCRegionHasBeenSet(false), m_maxItemsHasBeenSet(false), m_nextTokenHasBeenSet(false) { } Aws::String ListHostedZonesByVPCRequest::SerializePayload() const { return {}; } void ListHostedZonesByVPCRequest::AddQueryStringParameters(URI& uri) const { Aws::StringStream ss; if(m_vPCIdHasBeenSet) { ss << m_vPCId; uri.AddQueryStringParameter("vpcid", ss.str()); ss.str(""); } if(m_vPCRegionHasBeenSet) { ss << VPCRegionMapper::GetNameForVPCRegion(m_vPCRegion); uri.AddQueryStringParameter("vpcregion", ss.str()); ss.str(""); } if(m_maxItemsHasBeenSet) { ss << m_maxItems; uri.AddQueryStringParameter("maxitems", ss.str()); ss.str(""); } if(m_nextTokenHasBeenSet) { ss << m_nextToken; uri.AddQueryStringParameter("nexttoken", ss.str()); ss.str(""); } }
23.272727
74
0.688802
lintonv
b73bcc568506cfed291532a642ee8941cfce80be
1,736
cpp
C++
docker/build/face_detection/face_detector/src/utils.cpp
mykiscool/DeepCamera
e77cdbf45ab09895f315aa299bd6ac87b3bb6d66
[ "MIT" ]
914
2019-03-07T14:57:45.000Z
2022-03-31T14:54:15.000Z
docker/build/face_detection/face_detector/src/utils.cpp
mykiscool/DeepCamera
e77cdbf45ab09895f315aa299bd6ac87b3bb6d66
[ "MIT" ]
45
2019-03-11T09:53:37.000Z
2022-03-30T21:59:37.000Z
docker/build/face_detection/face_detector/src/utils.cpp
mykiscool/DeepCamera
e77cdbf45ab09895f315aa299bd6ac87b3bb6d66
[ "MIT" ]
148
2019-03-08T00:40:28.000Z
2022-03-30T09:22:18.000Z
#include <iostream> #include "utils.h" #include <sys/types.h> #include <dirent.h> #include <sys/stat.h> float getElapse(struct timeval *tv1,struct timeval *tv2) { float t = 0.0f; if (tv1->tv_sec == tv2->tv_sec) t = (tv2->tv_usec - tv1->tv_usec)/1000.0f; else t = ((tv2->tv_sec - tv1->tv_sec) * 1000 * 1000 + tv2->tv_usec - tv1->tv_usec)/1000.0f; return t; } int trave_dir(std::string& path, std::vector<std::string>& file_list) { DIR *d; //声明一个句柄 struct dirent* dt; //readdir函数的返回值就存放在这个结构体中 struct stat sb; if(!(d = opendir(path.c_str()))) { std::cout << "Error opendir: " << path << std::endl; return -1; } while((dt = readdir(d)) != NULL) { // std::cout << "file name: " << dt->d_name << std::endl; std::string file_name = dt->d_name; if(file_name[0] == '.') { continue; } // if(strncmp(dt->d_name, ".", 1) == 0 || strncmp(dt->d_name, "..", 2) == 0) { // continue; // } std::string file_path = path + "/" + dt->d_name; // std::cout << "file path: " << file_path << std::endl; if(stat(file_path.c_str(), &sb) < 0) { std::cout << "Error stat file: " << file_path << std::endl; return -1; } if (S_ISDIR(sb.st_mode)) { // is a directory // std::cout << "directory: " << file_path << std::endl; trave_dir(file_path, file_list); } else { // is a regular file // std::cout << "file: " << file_path << std::endl; file_list.push_back(file_path); } } // close directory closedir(d); return 0; }
28
94
0.49712
mykiscool
b73ebe1ddd7c7c326523e29757b1db694d23a093
993
cpp
C++
backup/2/hackerrank/c++/find-merge-point-of-two-lists.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
21
2019-11-16T19:08:35.000Z
2021-11-12T12:26:01.000Z
backup/2/hackerrank/c++/find-merge-point-of-two-lists.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
1
2022-02-04T16:02:53.000Z
2022-02-04T16:02:53.000Z
backup/2/hackerrank/c++/find-merge-point-of-two-lists.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
4
2020-05-15T19:39:41.000Z
2021-10-30T06:40:31.000Z
// Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site . // For this specific algothmic problem, visit my Youtube Video : . // It's fascinating to solve algothmic problems, follow Yanzhan to learn more! // Blog URL for this problem: https://yanzhan.site/hackerrank/find-merge-point-of-two-lists.html . int findMergeNode(SinglyLinkedListNode *head1, SinglyLinkedListNode *head2) { auto curr1 = head1, curr2 = head2; while (curr1 != curr2) { if (curr1->next) { curr1 = curr1->next; } else { curr1 = head2; } if (curr2->next) { curr2 = curr2->next; } else { curr2 = head1; } } return curr1; }
45.136364
345
0.655589
yangyanzhan
b7445619d9bd7f854a18db5c420fca73f506de22
9,223
cxx
C++
inetcore/winhttp/tools/w3spoof/om/url/url.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetcore/winhttp/tools/w3spoof/om/url/url.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetcore/winhttp/tools/w3spoof/om/url/url.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Copyright (c) 2000 Microsoft Corporation Module Name: url.cxx Abstract: Implements the Url object. Author: Paul M Midgen (pmidge) 10-November-2000 Revision History: 10-November-2000 pmidge Created =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--*/ #include "common.h" LPWSTR g_wszUrlObjectName = L"url"; //----------------------------------------------------------------------------- // CUrl methods //----------------------------------------------------------------------------- CUrl::CUrl(): m_cRefs(1), m_pSite(NULL), m_pti(NULL), m_bReadOnly(FALSE), m_szOriginalUrl(NULL), m_szUnescapedUrl(NULL), m_bEscaped(FALSE), m_wszUrl(NULL), m_wszScheme(NULL), m_usPort(0), m_wszServer(NULL), m_wszPath(NULL), m_wszResource(NULL), m_wszQuery(NULL), m_wszFragment(NULL) { DEBUG_TRACE(URL, ("CUrl [%#x] created", this)); } CUrl::~CUrl() { DEBUG_TRACE(URL, ("CUrl [%#x] deleted", this)); } HRESULT CUrl::Create(CHAR* url, BOOL bReadOnly, PURLOBJ* ppurl) { DEBUG_ENTER(( DBG_URL, rt_hresult, "CUrl::Create", "url=%s; bReadOnly=%d; ppurl=%#x", url, bReadOnly, ppurl )); HRESULT hr = S_OK; PURLOBJ puo = NULL; if( !url ) { hr = E_INVALIDARG; goto quit; } if( !ppurl ) { hr = E_POINTER; goto quit; } if( puo = new URLOBJ ) { if( SUCCEEDED(puo->_Initialize(url, bReadOnly)) ) { *ppurl = puo; } else { delete puo; *ppurl = NULL; hr = E_FAIL; } } else { hr = E_OUTOFMEMORY; } quit: DEBUG_LEAVE(hr); return hr; } HRESULT CUrl::_Initialize(CHAR* url, BOOL bReadOnly) { DEBUG_ENTER(( DBG_URL, rt_hresult, "CUrl::_Initialize", "this=%#x; bReadOnly=%d; url=%s", this, bReadOnly, url )); HRESULT hr = S_OK; BOOL bCracked = FALSE; URLCOMP uc; if( !url ) { hr = E_INVALIDARG; goto quit; } m_bReadOnly = bReadOnly; m_szOriginalUrl = __strdup(url); m_szUnescapedUrl = __unescape(url); m_wszUrl = __ansitowide(m_szUnescapedUrl); uc.dwStructSize = sizeof(URLCOMP); uc.lpszScheme = NULL; uc.dwSchemeLength = -1; uc.nScheme = INTERNET_SCHEME_UNKNOWN; uc.lpszHostName = NULL; uc.dwHostNameLength = -1; uc.nPort = 0; uc.lpszUrlPath = NULL; uc.dwUrlPathLength = -1; uc.lpszExtraInfo = NULL; uc.dwExtraInfoLength = -1; uc.lpszUserName = NULL; uc.dwUserNameLength = 0L; uc.lpszPassword = NULL; uc.dwPasswordLength = 0L; bCracked = WinHttpCrackUrl( m_wszUrl, wcslen(m_wszUrl), 0, &uc ); if( bCracked && (uc.nScheme != INTERNET_SCHEME_UNKNOWN) ) { WCHAR* token = NULL; WCHAR* tmp = NULL; // duplicate the scheme and hostname fields m_wszScheme = __wstrndup(uc.lpszScheme, uc.dwSchemeLength); m_wszServer = __wstrndup(uc.lpszHostName, uc.dwHostNameLength); // split out and duplicate the path and resource fields tmp = __wstrndup(uc.lpszUrlPath, uc.dwUrlPathLength); token = wcsrchr(tmp, L'/')+1; m_wszPath = __wstrndup( tmp, (uc.dwUrlPathLength - wcslen(token)) ); m_wszResource = __wstrndup( (tmp + wcslen(m_wszPath)), wcslen(token) ); SAFEDELETEBUF(tmp); // duplicate the query string field m_wszQuery = __wstrndup(uc.lpszExtraInfo, uc.dwExtraInfoLength); m_wszFragment = NULL; // set the requested server port m_usPort = uc.nPort; } else { DEBUG_TRACE(URL, ("WinHttpCrackUrl failed with %s", MapErrorToString(GetLastError()))); CHAR* token = NULL; CHAR* tmpurl = __unescape(url); // snag the extra info token = strrchr(tmpurl, '?'); if( token ) { m_wszQuery = __ansitowide(token); *token = '\0'; } // snag the resource token = strrchr(tmpurl, '/')+1; if( token ) { m_wszResource = __ansitowide(token); *token = '\0'; } // snag the path m_wszPath = __ansitowide(tmpurl); SAFEDELETEBUF(tmpurl); } quit: DEBUG_LEAVE(hr); return hr; } void CUrl::_Cleanup(void) { DEBUG_TRACE(URL, ("CUrl [%#x] cleaning up", this)); m_bEscaped = FALSE; SAFEDELETEBUF(m_szOriginalUrl); SAFEDELETEBUF(m_szUnescapedUrl); SAFEDELETEBUF(m_wszUrl); SAFEDELETEBUF(m_wszScheme); SAFEDELETEBUF(m_wszServer); SAFEDELETEBUF(m_wszPath); SAFEDELETEBUF(m_wszResource); SAFEDELETEBUF(m_wszQuery); SAFEDELETEBUF(m_wszFragment); } void CUrl::Terminate(void) { DEBUG_TRACE(URL, ("CUrl [%#x] terminating", this)); m_bReadOnly = FALSE; SAFERELEASE(m_pSite); Release(); } //----------------------------------------------------------------------------- // IUnknown //----------------------------------------------------------------------------- HRESULT __stdcall CUrl::QueryInterface(REFIID riid, void** ppv) { DEBUG_ENTER(( DBG_REFCOUNT, rt_hresult, "CUrl::QueryInterface", "this=%#x; riid=%s; ppv=%#x", this, MapIIDToString(riid), ppv )); HRESULT hr = S_OK; if( !ppv ) { hr = E_POINTER; goto quit; } if( IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IDispatch) || IsEqualIID(riid, IID_IUrl) ) { *ppv = static_cast<IUrl*>(this); } else if( IsEqualIID(riid, IID_IProvideClassInfo) ) { *ppv = static_cast<IProvideClassInfo*>(this); } else if( IsEqualIID(riid, IID_IObjectWithSite) ) { *ppv = static_cast<IObjectWithSite*>(this); } else { *ppv = NULL; hr = E_NOINTERFACE; } if( SUCCEEDED(hr) ) { reinterpret_cast<IUnknown*>(*ppv)->AddRef(); } quit: DEBUG_LEAVE(hr); return hr; } ULONG __stdcall CUrl::AddRef(void) { InterlockedIncrement(&m_cRefs); DEBUG_ADDREF("CUrl", m_cRefs); return m_cRefs; } ULONG __stdcall CUrl::Release(void) { InterlockedDecrement(&m_cRefs); DEBUG_RELEASE("CUrl", m_cRefs); if( m_cRefs == 0 ) { DEBUG_FINALRELEASE("CUrl"); _Cleanup(); SAFERELEASE(m_pti); delete this; return 0; } return m_cRefs; } //----------------------------------------------------------------------------- // IProvideClassInfo //----------------------------------------------------------------------------- HRESULT __stdcall CUrl::GetClassInfo(ITypeInfo** ppti) { DEBUG_ENTER(( DBG_URL, rt_hresult, "CUrl::GetClassInfo", "this=%#x; ppti=%#x", this, ppti )); HRESULT hr = S_OK; if( ppti ) { m_pti->AddRef(); *ppti = m_pti; } else { hr = E_POINTER; } DEBUG_LEAVE(hr); return hr; } //----------------------------------------------------------------------------- // IObjectWithSite //----------------------------------------------------------------------------- HRESULT __stdcall CUrl::SetSite(IUnknown* pUnkSite) { DEBUG_ENTER(( DBG_URL, rt_hresult, "CUrl::SetSite", "this=%#x; pUnkSite=%#x", this, pUnkSite )); HRESULT hr = S_OK; IActiveScriptSite* pias = NULL; IObjectWithSite* pcontainer = NULL; if( !pUnkSite ) { hr = E_INVALIDARG; } else { SAFERELEASE(m_pSite); SAFERELEASE(m_pti); m_pSite = pUnkSite; m_pSite->AddRef(); hr = m_pSite->QueryInterface(IID_IObjectWithSite, (void**) &pcontainer); if( SUCCEEDED(hr) ) { hr = pcontainer->GetSite(IID_IActiveScriptSite, (void**) &pias); if( SUCCEEDED(hr) ) { hr = pias->GetItemInfo( g_wszUrlObjectName, SCRIPTINFO_ITYPEINFO, NULL, &m_pti ); } } } SAFERELEASE(pcontainer); SAFERELEASE(pias); DEBUG_LEAVE(hr); return hr; } HRESULT __stdcall CUrl::GetSite(REFIID riid, void** ppvSite) { DEBUG_ENTER(( DBG_URL, rt_hresult, "CUrl::GetSite", "this=%#x; riid=%s; ppvSite=%#x", this, MapIIDToString(riid), ppvSite )); HRESULT hr = S_OK; if( !ppvSite ) { hr = E_POINTER; } else { if( m_pSite ) { hr = m_pSite->QueryInterface(riid, ppvSite); } else { hr = E_FAIL; } } DEBUG_LEAVE(hr); return hr; }
19.294979
92
0.490621
npocmaka
b744b10f31a5dee404f71196448427003b79ebb8
4,573
cpp
C++
src/strategy/values/LootValues.cpp
htc16/mod-playerbots
2307e3f980035a244bfb4fedefda5bc55903d470
[ "MIT" ]
12
2022-03-23T05:14:53.000Z
2022-03-30T12:12:58.000Z
src/strategy/values/LootValues.cpp
htc16/mod-playerbots
2307e3f980035a244bfb4fedefda5bc55903d470
[ "MIT" ]
24
2022-03-23T13:56:37.000Z
2022-03-31T18:23:32.000Z
src/strategy/values/LootValues.cpp
htc16/mod-playerbots
2307e3f980035a244bfb4fedefda5bc55903d470
[ "MIT" ]
3
2022-03-24T21:47:10.000Z
2022-03-31T06:21:46.000Z
/* * Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU GPL v2 license, you may redistribute it and/or modify it under version 2 of the License, or (at your option), any later version. */ #include "LootValues.h" #include "SharedValueContext.h" #include "Playerbots.h" LootTemplateAccess const* DropMapValue::GetLootTemplate(ObjectGuid guid, LootType type) { LootTemplate const* lTemplate = nullptr; if (guid.IsCreature()) { CreatureTemplate const* info = sObjectMgr->GetCreatureTemplate(guid.GetEntry()); if (info) { if (type == LOOT_CORPSE) lTemplate = LootTemplates_Creature.GetLootFor(info->lootid); else if (type == LOOT_PICKPOCKETING && info->pickpocketLootId) lTemplate = LootTemplates_Pickpocketing.GetLootFor(info->pickpocketLootId); else if (type == LOOT_SKINNING && info->SkinLootId) lTemplate = LootTemplates_Skinning.GetLootFor(info->SkinLootId); } } else if (guid.IsGameObject()) { GameObjectTemplate const* info = sObjectMgr->GetGameObjectTemplate(guid.GetEntry()); if (info && info->GetLootId() != 0) { if (type == LOOT_CORPSE) lTemplate = LootTemplates_Gameobject.GetLootFor(info->GetLootId()); else if (type == LOOT_FISHINGHOLE) lTemplate = LootTemplates_Fishing.GetLootFor(info->GetLootId()); } } else if (guid.IsItem()) { ItemTemplate const* proto = sObjectMgr->GetItemTemplate(guid.GetEntry()); if (proto) { if (type == LOOT_CORPSE) lTemplate = LootTemplates_Item.GetLootFor(proto->ItemId); else if (type == LOOT_DISENCHANTING && proto->DisenchantID) lTemplate = LootTemplates_Disenchant.GetLootFor(proto->DisenchantID); if (type == LOOT_MILLING) lTemplate = LootTemplates_Milling.GetLootFor(proto->ItemId); if (type == LOOT_PROSPECTING) lTemplate = LootTemplates_Prospecting.GetLootFor(proto->ItemId); } } LootTemplateAccess const* lTemplateA = reinterpret_cast<LootTemplateAccess const*>(lTemplate); return lTemplateA; } DropMap* DropMapValue::Calculate() { DropMap* dropMap = new DropMap; int32 sEntry = 0; if (CreatureTemplateContainer const* creatures = sObjectMgr->GetCreatureTemplates()) { for (CreatureTemplateContainer::const_iterator itr = creatures->begin(); itr != creatures->end(); ++itr) { sEntry = itr->first; if (LootTemplateAccess const* lTemplateA = GetLootTemplate(ObjectGuid::Create<HighGuid::Unit>(sEntry, uint32(1)), LOOT_CORPSE)) for (auto const& lItem : lTemplateA->Entries) dropMap->insert(std::make_pair(lItem->itemid, sEntry)); } } if (GameObjectTemplateContainer const* gameobjects = sObjectMgr->GetGameObjectTemplates()) { for (auto const& itr : *gameobjects) { sEntry = itr.first; if (LootTemplateAccess const* lTemplateA = GetLootTemplate(ObjectGuid::Create<HighGuid::GameObject>(sEntry, uint32(1)), LOOT_CORPSE)) for (auto const& lItem : lTemplateA->Entries) dropMap->insert(std::make_pair(lItem->itemid, -sEntry)); } } return dropMap; } //What items does this entry have in its loot list? std::vector<int32> ItemDropListValue::Calculate() { uint32 itemId = stoi(getQualifier()); DropMap* dropMap = GAI_VALUE(DropMap*, "drop map"); std::vector<int32> entries; auto range = dropMap->equal_range(itemId); for (auto itr = range.first; itr != range.second; ++itr) entries.push_back(itr->second); return entries; } //What items does this entry have in its loot list? std::vector<uint32> EntryLootListValue::Calculate() { int32 entry = stoi(getQualifier()); std::vector<uint32> items; LootTemplateAccess const* lTemplateA; if (entry > 0) lTemplateA = DropMapValue::GetLootTemplate(ObjectGuid::Create<HighGuid::Unit>(entry, uint32(1)), LOOT_CORPSE); else lTemplateA = DropMapValue::GetLootTemplate(ObjectGuid::Create<HighGuid::GameObject>(entry, uint32(1)), LOOT_CORPSE); if (lTemplateA) for (auto const& lItem : lTemplateA->Entries) items.push_back(lItem->itemid); return items; } itemUsageMap EntryLootUsageValue::Calculate() { itemUsageMap items; for (auto itemId : GAI_VALUE2(std::vector<uint32>, "entry loot list", getQualifier())) { items[AI_VALUE2(ItemUsage, "item usage", itemId)].push_back(itemId); } return items; }; bool HasUpgradeValue::Calculate() { itemUsageMap uMap = AI_VALUE2(itemUsageMap, "entry loot usage", getQualifier()); return uMap.find(ITEM_USAGE_EQUIP) != uMap.end() || uMap.find(ITEM_USAGE_REPLACE) != uMap.end(); }
30.898649
205
0.704352
htc16
b7461dc3c38f04a368b803fea9a21530d882799f
6,821
cpp
C++
src/libcipcm/cwrap.cpp
wrathematics/pbdPAPI
cb3fad3bccd54b7aeeef9e687b52d938613a356e
[ "Intel", "BSD-3-Clause" ]
8
2015-02-14T17:00:51.000Z
2016-02-01T20:13:43.000Z
src/libcipcm/cwrap.cpp
QuantScientist3/pbdPAPI
708bee501de20eb82829e03b92b24b6352044f49
[ "Intel", "BSD-3-Clause" ]
null
null
null
src/libcipcm/cwrap.cpp
QuantScientist3/pbdPAPI
708bee501de20eb82829e03b92b24b6352044f49
[ "Intel", "BSD-3-Clause" ]
3
2015-03-26T13:41:27.000Z
2015-04-01T11:36:34.000Z
#define HACK_TO_REMOVE_DUPLICATE_ERROR #include <iostream> #ifdef OK_WIN_BUILD #pragma warning(disable : 4996) // for sprintf #include <windows.h> #include "PCM_Win/windriver.h" #else #include <unistd.h> #include <signal.h> #endif #include <math.h> #include <iomanip> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <string> #include <assert.h> #include "cpucounters.h" #include "utils.h" #include "cwrap.h" using namespace std; #define SIZE (10000000) #define DELAY 1 // in seconds struct CSysCounterState{ PCM *m; SystemCounterState start; SystemCounterState end; int cpu_model; }global_state; struct event_list_s{ uint64(*event_function)(const SystemCounterState&,const SystemCounterState&); int atom; }; static const struct event_list_s event_list[]={ {getL2CacheMisses,1}, {getL2CacheHits,1}, {getInstructionsRetired,1}, {getCycles,1}, {getL3CacheHitsNoSnoop,0}, {getL3CacheHitsSnoop,0}, {getL3CacheHits,0}, {getL3CacheMisses,0}, }; static int global_cpu_model=0; static long long global_nominal_frequency=0; static int global_max_cpus=0; long long ipcm_get_frequency(){ return global_nominal_frequency; } int ipcm_get_cpus(){ return global_max_cpus; } void ipcm_get_cpuid(int *family, int *model){ *family=global_state.m->getCPUFamily(); *model=global_state.m->getCPUModel(); } void ipcm_cpu_strings(char *vendor, char *model, char *codename){ int i; const char *tmp = global_state.m->getCPUBrandString().c_str(); for(i=0;tmp[i] && tmp[i]!=' ';i++); memcpy(vendor,tmp,i); tmp+=i+1; strcpy(model,tmp); tmp=global_state.m->getUArchCodename(); strcpy(codename,tmp); } int ipcm_event_avail(const int code){ if(code>=IPCM_START_EVENT && code<IPCM_NULL_EVENT){ if(global_cpu_model==PCM::ATOM) return event_list[code].atom; else return 1; } return 0; } static void set_diff_vals(PCM *m, const SystemCounterState *sstate1, const SystemCounterState *sstate2, const int cpu_model, ipcm_event_val_t *values, const int num){ int i; for(i=0;i<num;i++){ //if(values[i].code>=IPCM_START_EVENT && values[i].code<IPCM_NULL_EVENT){ if(ipcm_event_avail(values[i].code)) values[i].val=event_list[values[i].code].event_function(*sstate1,*sstate2); else values[i].val=-1; } } static void print_diff( PCM *m, const SystemCounterState *sstate1, const SystemCounterState *sstate2, const int cpu_model){ if (cpu_model != PCM::ATOM) { cout << " TOTAL * " << getExecUsage(*sstate1, *sstate2) << " " << getIPC(*sstate1, *sstate2) << " " << getRelativeFrequency(*sstate1, *sstate2) << " " << getActiveRelativeFrequency(*sstate1, *sstate2) << " " << unit_format(getL3CacheMisses(*sstate1, *sstate2)) << " " << unit_format(getL2CacheMisses(*sstate1, *sstate2)) << " " << getL3CacheHitRatio(*sstate1, *sstate2) << " " << getL2CacheHitRatio(*sstate1, *sstate2) << " " << getCyclesLostDueL3CacheMisses(*sstate1, *sstate2) << " " << getCyclesLostDueL2CacheMisses(*sstate1, *sstate2); if (!(m->memoryTrafficMetricsAvailable())) cout << " N/A N/A"; else cout << " " << getBytesReadFromMC(*sstate1, *sstate2) / double(1024ULL * 1024ULL * 1024ULL) << " " << getBytesWrittenToMC(*sstate1, *sstate2) / double(1024ULL * 1024ULL * 1024ULL); cout << " N/A\n"; } else cout << " TOTAL * " << getExecUsage(*sstate1, *sstate2) << " " << getIPC(*sstate1, *sstate2) << " " << getRelativeFrequency(*sstate1, *sstate2) << " " << unit_format(getL2CacheMisses(*sstate1, *sstate2)) << " " << getL2CacheHitRatio(*sstate1, *sstate2) << " N/A\n"; } int ipcm_init(){ //struct CSysCounterState *ret; #ifdef PCM_FORCE_SILENT streambuf *oldout, *olderr; null_stream nullStream1, nullStream2; oldout=std::cout.rdbuf(); olderr=std::cerr.rdbuf(); std::cout.rdbuf(&nullStream1); std::cerr.rdbuf(&nullStream2); #endif #ifdef OK_WIN_BUILD // Increase the priority a bit to improve context switching delays on Windows SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL); char driverPath[1040]; // length for current directory + "\\msr.sys" //TCHAR driverPath[1040]; // length for current directory + "\\msr.sys" GetCurrentDirectory(1024, driverPath); strncat(driverPath,"\\msr.sys",1040); //strcat_s(driverPath, 1040, "\\msr.sys"); //wcscat_s(driverPath, 1040, L"\\msr.sys"); SetConsoleCtrlHandler((PHANDLER_ROUTINE)cleanup, TRUE); #else /* signal(SIGPIPE, cleanup); signal(SIGINT, cleanup); signal(SIGKILL, cleanup); signal(SIGTERM, cleanup); */ #endif // interesting start int tryagain=0; PCM * m = PCM::getInstance(); //if(disable_JKT_workaround) m->disableJKTWorkaround(); PCM::ErrorCode status = m->program(); PCM::ErrorCode secondstatus; switch (status) { case PCM::Success: break; case PCM::MSRAccessDenied: cerr << "Access to Intel(r) Performance Counter Monitor has denied (no MSR or PCI CFG space access)." << endl; return 0; case PCM::PMUBusy: cerr << "Access to Intel(r) Performance Counter Monitor has denied (Performance Monitoring Unit is occupied by other application). Try to stop the application that uses PMU." << endl; cerr << "Alternatively you can try to reset PMU configuration at your own risk. Try to reset? (y/n)" << endl; //char yn; //std::cin >> yn; //if ('y' == yn) //{ m->resetPMU(); cout << "PMU configuration has been reset. Try to rerun the program again." << endl; //} //return 0; m = PCM::getInstance(); secondstatus=m->program(); if(secondstatus!=PCM::Success) return 0; break; default: cerr << "Access to Intel(r) Performance Counter Monitor has denied (Unknown error)." << endl; return 0; } //global_state=(struct CSysCounterState*)malloc(sizeof(*ret)); global_state.m=m; global_cpu_model=m->getCPUModel(); global_nominal_frequency=m->getNominalFrequency(); global_max_cpus=m->getNumCores(); #ifdef PCM_FORCE_SILENT std::cout.rdbuf(oldout); std::cerr.rdbuf(olderr); #endif return 1; } void ipcm_get_events(){ std::vector<CoreCounterState> cstates1, cstates2; std::vector<SocketCounterState> sktstate1, sktstate2; //SystemCounterState sstate1, sstate2; uint64 TimeAfterSleep = 0; global_state.m->getAllCounterStates(global_state.start, sktstate1, cstates1); //return ret; } void ipcm_end_events(ipcm_event_val_t *values, const int num){ std::vector<CoreCounterState> cstates1, cstates2; std::vector<SocketCounterState> sktstate1, sktstate2; //struct CSysCounterState *sa=(struct CSysCounterState*)state; global_state.m->getAllCounterStates(global_state.end, sktstate2, cstates2); //print_diff(sa->m,&sa->start,&sa->end,sa->cpu_model); set_diff_vals(global_state.m,&global_state.start,&global_state.end,global_state.cpu_model,values,num); //free(state); }
28.069959
186
0.702536
wrathematics
b74866f1493fc08fac3da9777ba9f8d85878cc8b
1,787
cpp
C++
code-forces/Educational 89/D.cpp
ErickJoestar/competitive-programming
76afb766dbc18e16315559c863fbff19a955a569
[ "MIT" ]
1
2020-04-23T00:35:38.000Z
2020-04-23T00:35:38.000Z
code-forces/Educational 89/D.cpp
ErickJoestar/competitive-programming
76afb766dbc18e16315559c863fbff19a955a569
[ "MIT" ]
null
null
null
code-forces/Educational 89/D.cpp
ErickJoestar/competitive-programming
76afb766dbc18e16315559c863fbff19a955a569
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define ENDL '\n' #define deb(u) cout << #u " : " << (u) << ENDL; #define deba(alias, u) cout << alias << ": " << (u) << ENDL; #define debp(u, v) cout << u << " : " << v << ENDL; #define pb push_back #define F first #define S second #define lli long long #define pii pair<int, int> #define pll pair<lli, lli> #define ALL(a) (a).begin(), (a).end() #define ALLR(a) (a).rbegin(), (a).rend() #define FOR(i, a, n) for (int i = (a); i < (n); ++i) #define FORN(i, a, n) for (int i = (a - 1); i >= n; --i) #define IO \ ios_base::sync_with_stdio(false); \ cin.tie(0); \ cout.tie(0) using namespace std; #define INF 10000020LL vector<int> d(INF, -1); void criba() { for (lli i = 2; i < INF; i++) { if (d[i] == -1) { d[i] = i; for (lli j = 2; (j * i) < INF; j++) { d[j * i] = d[j * i] == -1 ? i : d[j * i]; } } } } int main() { IO; int n; cin >> n; vector<int> v(n); FOR(i, 0, n) cin >> v[i]; criba(); vector<pii> ans; for (auto u : v) { map<int, int> m; if (u == d[u]) { ans.pb({-1, -1}); continue; } int copy = u; while (copy != 1) { m[d[copy]]++; copy /= d[copy]; } if (m.size() == 1) { ans.pb({-1, -1}); continue; } else { int a = u / d[u], b = d[u]; // debp(a, b); // deb(__gcd(u, a + b)); while (__gcd(u, (a + b)) != 1 && a > 1 && b > 1) { b *= d[a]; a = a / d[a]; } if (a > 1 && b > 1) ans.pb({a, b}); else ans.pb({-1, -1}); } } for (auto e : ans) { cout << e.F << " "; } cout << ENDL; for (auto e : ans) { cout << e.S << " "; } return 0; }
18.42268
60
0.404589
ErickJoestar
b748e30bcef883d86729495dfe82623b2538f6df
3,006
cpp
C++
Strings/Knuth-Morris-Pratt.cpp
Rand0mUsername/Algorithms
05ec0d7ed7f0a4d13000d9d77d743812ac9a27e0
[ "MIT" ]
2
2020-01-10T14:12:03.000Z
2020-05-28T19:12:21.000Z
Strings/Knuth-Morris-Pratt.cpp
Rand0mUsername/algorithms
05ec0d7ed7f0a4d13000d9d77d743812ac9a27e0
[ "MIT" ]
null
null
null
Strings/Knuth-Morris-Pratt.cpp
Rand0mUsername/algorithms
05ec0d7ed7f0a4d13000d9d77d743812ac9a27e0
[ "MIT" ]
1
2022-01-11T03:14:48.000Z
2022-01-11T03:14:48.000Z
// RandomUsername (Nikola Jovanovic) // Knuth-Morris-Pratt (KMP) // String matching: O( N + M ) // N - word length, M - text length #include <bits/stdc++.h> #define DBG false #define debug(x) if(DBG) printf("(ln %d) %s = %d\n", __LINE__, #x, x); #define lld long long #define ff(i,a,b) for(int i=a; i<=b; i++) #define fb(i,a,b) for(int i=a; i>=b; i--) #define par pair<int, int> #define fi first #define se second #define mid (l+r)/2 #define INF 1000000000 #define MAXLEN 100005 using namespace std; /* Useful tutorial: http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=stringSearching Failure function f[i] := the length of the longest proper suffix=prefix for string w[ 0 ]..w[ i-1 ] (string of length i) If we align t[j] and w[i] and fail to match a character, we should try to match w[f[i]] and t[j] We move our word to the right skipping all the unnecessary comparations f[f[i]] is the second "best" prefix=suffix (best prefix=suffix of the best prefix=suffix ) */ // Text and text length, word and word length // Searching for word in text char t[MAXLEN]; int tl; char w[MAXLEN]; int wl; // Matches will be stored here vector<int> matches; // Failure function int F[MAXLEN]; // KMP void KMP() { // Computing the faliure function int i, j; // Base cases F[0] = F[1] = 0; // Computing F[i] for(i = 2; i <= wl; i++) { // Expanding the solution for i-1 is our best guess for F[i] j = F[i-1]; while(1) { // If w[j] and w[i-1] match, we expand, F[i] is found, break if(w[j] == w[i-1]) { F[i] = j + 1; break; } // If we failed to expand an empty string, we have to quit trying, F[i] is zero, break if(j == 0) { F[i] = 0; break; } // Otherwise we just try expanding the next best match j = F[j]; } } // Doing the actual matching // i - word iterator, j - text iterator i = j = 0; while(1) { // We reached the end of the text if(j == tl) break; // We are trying to match t[j] and w[i] if(t[j] == w[i]) { // If they match, move on i++, j++; // We reached the end of the word, we found a full match! if(i == wl) { // The match starts at t[j-wl] matches.push_back(j - wl); // The next possible match i = F[i]; } } // If they do not match, try the next possible match for t[j] else if(i > 0) i = F[i]; // If i=0 failed to match there are no more possible matches for t[j], move on else j++; } } // Testing // Test problem: http://www.spoj.com/problems/NHAY/ int main() { scanf("%s", t); scanf("%s", w); tl = strlen(t); wl = strlen(w); KMP(); printf("Matches:\n"); for(int i = 0; i < matches.size(); i++) printf("%d ", matches[i]); return 0; }
27.833333
124
0.549235
Rand0mUsername
b74cf868fa30cc892de947e9935f79d7ae32cc3d
6,651
cpp
C++
modules/frontend/src/frontend.cpp
state-of-the-art/aSocial
aa9e94f5af7300531f5ec9529955f60be8cd504c
[ "Apache-2.0" ]
13
2021-02-07T21:09:43.000Z
2021-05-13T20:00:53.000Z
modules/frontend/src/frontend.cpp
state-of-the-art/aSocial
aa9e94f5af7300531f5ec9529955f60be8cd504c
[ "Apache-2.0" ]
null
null
null
modules/frontend/src/frontend.cpp
state-of-the-art/aSocial
aa9e94f5af7300531f5ec9529955f60be8cd504c
[ "Apache-2.0" ]
null
null
null
#include "frontend/frontend.h" #include <signal.h> #include <QDebug> #include <QDir> #include <QEventLoop> #include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlComponent> #include <QScreen> #include <QStandardPaths> #include <QTimer> #include <QTranslator> #include <QtQml/QQmlContext> #include "accountdatabase.h" #include "backend/backend.h" #include "crypto/crypto.h" #include "fedatabase.h" #include "settings.h" #include "storage/internalimageprovider.h" #include "wdate.h" Frontend *Frontend::s_pInstance = NULL; Frontend::Frontend(QObject *parent) : QObject(parent) , m_engine(NULL) , m_app(NULL) , m_translator(NULL) , m_device_passkey(NULL) , m_backend(NULL) , m_database(NULL) { qDebug("Init aSocial v%s", PROJECT_VERSION); signal(SIGINT, Frontend::signalHandler); QCoreApplication::setOrganizationName("asocial.co"); QCoreApplication::setOrganizationDomain("asocial.co"); QCoreApplication::setApplicationName("asocial.co"); QCoreApplication::setApplicationVersion(PROJECT_VERSION); // Application locale Settings::I()->setDefault("frontend/locale", QLocale::system().name()); // Database name & path Settings::I()->setDefault("frontend/database_name", "private.asc"); Settings::I()->setDefault("frontend/database_path", QStandardPaths::writableLocation(QStandardPaths::DataLocation)); } Frontend::~Frontend() { delete m_database; delete m_backend; delete m_device_passkey; Settings::destroyI(); delete m_translator; delete m_engine; delete m_date_wrapper; qDebug("Destroy Frontend"); } void Frontend::init(QGuiApplication *app) { qDebug("Init Frontend"); m_app = app; connect(app, SIGNAL(aboutToQuit()), this, SLOT(deleteMe())); m_date_wrapper = new WDate(); initInterface(); initLocale(); initEngine(); // Run postinit after application starts QTimer::singleShot(0, this, SLOT(postinit())); } void Frontend::initInterface() { qDebug("Init Frontend interface"); m_engine = new QQmlApplicationEngine(this); m_context = m_engine->rootContext(); m_context->setContextProperty("app", this); m_context->setContextProperty("settings", Settings::I()); m_context->setContextProperty("wdate", m_date_wrapper); m_context->setContextProperty("screenScale", QGuiApplication::primaryScreen()->physicalDotsPerInch() * QGuiApplication::primaryScreen()->devicePixelRatio() / 100); qmlRegisterUncreatableType<WDate>("co.asocial", 1, 0, "WDate", "External type"); qmlRegisterUncreatableType<AccountDatabase>("co.asocial", 1, 0, "AccountDatabase", "External type"); m_engine->addImageProvider(QLatin1String("InternalStorage"), new InternalImageProvider); } void Frontend::initLocale() { qDebug("Init Frontend locale"); m_translator = new QTranslator(this); setLocale(Settings::I()->setting("frontend/locale").toString()); m_app->installTranslator(m_translator); } void Frontend::initEngine() { qDebug("Loading qml interface"); m_engine->load(QUrl(QStringLiteral("qrc:/qml/main.qml"))); } void Frontend::postinit() { qDebug("PostInit Frontend"); postinitDevicePassKey(); postinitBackend(); postinitDatabase(); emit postinitDone(); } void Frontend::postinitDevicePassKey() { qDebug("PostInit Frontend device pass key"); if( Settings::I()->isNull("common/device_passkey") ) { qDebug("Create new device passkey"); m_device_passkey = Crypto::I()->genKey(); QString password = passwordGetWait(qtTrId("Encrypt your Device PassKey"), true); if( ! password.isEmpty() ) { m_device_passkey->encrypt(password); password.fill('*'); } else qWarning("Device PassKey is not encrypted"); Settings::I()->setDefault("common/device_passkey", QString(m_device_passkey->getData().toHex())); Settings::I()->setDefault("common/device_passkey_encrypted", m_device_passkey->isEncrypted()); } else { m_device_passkey = new PrivKey( this, QByteArray::fromHex(Settings::I()->setting("common/device_passkey").toString().toLocal8Bit()), Settings::I()->setting("common/device_passkey_encrypted").toBool()); } while( ! m_device_passkey->decryptForever(passwordGetWait(qtTrId("Enter your Device PassKey password"))) ) { } } void Frontend::postinitBackend() { qDebug("PostInit Frontend backend"); m_backend = new Backend(this); m_backend->init(m_device_passkey); } void Frontend::postinitDatabase() { qDebug("PostInit Frontend database"); m_database = new FEDatabase(this, Settings::I()->setting("frontend/database_name").toString(), Settings::I()->setting("frontend/database_path").toString()); m_database->open(QString(Crypto::sha3256(m_device_passkey->getData()).toHex())); } void Frontend::setLocale(QString locale) { qDebug() << "Set locale to" << locale; if( ! m_translator->load("tr_" + locale, ":/") ) { m_translator->load("tr_en", ":/"); Settings::I()->setting("frontend/locale", "en"); } } QString Frontend::passwordGetWait(const QString &description, const bool create) { qDebug() << "Request password and wait"; m_password = ""; QString password; emit requestPassword(description, create); QEventLoop wait_loop; connect(this, &Frontend::donePassword, &wait_loop, &QEventLoop::exit); if( wait_loop.exec() == -1 ) { qFatal("Frontend closed. Exiting."); } password = m_password; m_password = ""; return password; } QJsonArray Frontend::getAccounts() { return m_database->getAccounts(); } int Frontend::createAccount(const QJsonObject &account, const QString &password) { return m_database->createAccount(account, password); } bool Frontend::openAccount(const int id) { return m_database->openAccount(id); } void Frontend::closeAccount() { return m_database->closeAccount(); } AccountDatabase *Frontend::getCurrentAccount() { return m_database->getCurrentAccount(); } QColor Frontend::getTextColor(QColor background_color) { if( 0.2126 * background_color.redF() + 0.7152 * background_color.greenF() + 0.0722 * background_color.blueF() > 0.5 ) return QColor(Qt::black); else return QColor(Qt::white); } void Frontend::responsePassword(const QString password) { m_password = password; emit donePassword(0); } void Frontend::signalHandler(int signal) { qDebug() << "Received signal:" << signal; }
27.59751
120
0.681702
state-of-the-art
b74ee0958769bd372b7827df5002c781291c7133
2,310
cpp
C++
cs284/assignment2/Account.cpp
gsteelman/mst
e5729016e3584107a8b6222c059bf41a20d3cb22
[ "Apache-2.0" ]
1
2015-04-11T17:36:20.000Z
2015-04-11T17:36:20.000Z
cs284/assignment2/Account.cpp
gsteelman/mst
e5729016e3584107a8b6222c059bf41a20d3cb22
[ "Apache-2.0" ]
null
null
null
cs284/assignment2/Account.cpp
gsteelman/mst
e5729016e3584107a8b6222c059bf41a20d3cb22
[ "Apache-2.0" ]
null
null
null
// BEGINNING OF FILE ---------------------------------------------------------- /////////////////////////////////////////////////////////////////////////////// /// @auth Gary Steelman /// @file Account.cpp /// @edit 31 Sept 2009 /// @brief The implementation for the Account class /////////////////////////////////////////////////////////////////////////////// #include "Account.h" #include <iostream> #include <string> Account::Account() { m_cBal = 0; m_sBal = 0; } Account::~Account() { } double Account::get_cBal() const { return m_cBal; } double Account::get_sBal() const { return m_sBal; } void Account::set_cBal( const double& amount ) { m_cBal = amount; return; } void Account::set_sBal( const double& amount ) { m_sBal = amount; return; } void Account::deposit ( const int& to, const double& amount ) { //Depositing to the checking account if ( to == 0 ) { set_cBal( get_cBal() + amount ); } //Depositing to the savigns account else if ( to == 1) { set_sBal( get_sBal() + amount ); } //Depositing money to nowhere... else { std::cout << "Error has occurred in depositing" << std::endl; } return; } void Account::transfer( const int& to, const double& amount ) { //Transfer to checking account //Withdraw from savings, deposit to checkings if ( to == 0 ) { withdraw( 1, amount ); deposit( 0, amount ); } //Transfer to savings account //Withdraw from checking, deposit to saving else if ( to == 1 ) { withdraw( 0, amount ); deposit( 1, amount ); } return; } void Account::withdraw( const int& from, const double& amount ) { //Withdrawing from the checking account if ( from == 0 ) { set_cBal( get_cBal() - amount ); } //Withdrawing from the savigns account else if ( from == 1) { set_sBal( get_sBal() - amount ); } //Withdrawing from somewhere that doesn't exist... else { std::cout << "Error has occurred in withdrawing." << std::endl; } return; } std::string Account::get_uName( const int& uID ) { if ( uID == 1 ) return "Bruce"; else if ( uID == 2 ) return "Jennfier"; else if ( uID == 3 ) return "Jill"; return "NONAME"; } // END OF FILE ----------------------------------------------------------------
18.333333
79
0.535065
gsteelman
b752d2cb209b319d440006ea473d20d14827e4e7
1,468
hpp
C++
include/edyn/comp/tag.hpp
xissburg/EntityDynamics
115da67243da53f7b5001a83260b2f3d7a0355b4
[ "MIT" ]
null
null
null
include/edyn/comp/tag.hpp
xissburg/EntityDynamics
115da67243da53f7b5001a83260b2f3d7a0355b4
[ "MIT" ]
null
null
null
include/edyn/comp/tag.hpp
xissburg/EntityDynamics
115da67243da53f7b5001a83260b2f3d7a0355b4
[ "MIT" ]
null
null
null
#ifndef EDYN_COMP_TAG_HPP #define EDYN_COMP_TAG_HPP namespace edyn { /** * Rigid body. */ struct rigidbody_tag {}; /** * Dynamic rigid body. */ struct dynamic_tag {}; /** * Kinematic rigid body. */ struct kinematic_tag {}; /** * Static rigid body. */ struct static_tag {}; /** * Procedural entity, which is an entity that has calculated state and can only * be present in a single island. */ struct procedural_tag {}; /** * An entity that is synchronized between client and server. */ struct networked_tag {}; /** * An entity that is currently asleep. */ struct sleeping_tag {}; /** * An entity that won't be put to sleep when inactive. */ struct sleeping_disabled_tag {}; /** * Disabled entity. */ struct disabled_tag {}; /** * A rigid body which will have its contact state continuously updated in the * main registry. */ struct continuous_contacts_tag {}; /** * A rigid body which holds a shape that can roll. An extra step will be * performed to help improve contact point persistence when rolling at * higher speeds. */ struct rolling_tag {}; /** * An entity that was created externally and tagged via * `edyn::tag_external_entity` (i.e. it doesn't represent any of the internal * Edyn entity types such as rigid bodies and constraints) and is part of the * entity graph and can be attached to an internal Edyn entity by means of a * `edyn::null_constraint`. */ struct external_tag {}; } #endif // EDYN_COMP_TAG_HPP
19.064935
79
0.702997
xissburg
b75917a6a569ffb4ca4d4912db8ab9ae7ef4d253
1,341
hpp
C++
include/context.hpp
chGoodchild/powerloader
11b48413d0b3fb953430666153caf95e68158e4d
[ "BSD-3-Clause" ]
null
null
null
include/context.hpp
chGoodchild/powerloader
11b48413d0b3fb953430666153caf95e68158e4d
[ "BSD-3-Clause" ]
null
null
null
include/context.hpp
chGoodchild/powerloader
11b48413d0b3fb953430666153caf95e68158e4d
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <vector> #include <string> #include <chrono> #include <map> #ifdef WITH_ZCHUNK extern "C" { #include <zck.h> } #endif #include "mirror.hpp" namespace powerloader { class Context { public: bool offline = false; int verbosity = 0; bool adaptive_mirror_sorting = true; bool disable_ssl = false; long connect_timeout = 30L; long low_speed_time = 30L; long low_speed_limit = 1000L; bool ftp_use_seepsv = true; fs::path cache_dir; std::size_t retry_backoff_factor = 2; std::size_t max_resume_count = 3; std::chrono::steady_clock::duration retry_default_timeout = std::chrono::seconds(2); std::map<std::string, std::vector<std::shared_ptr<Mirror>>> mirror_map; std::vector<std::string> additional_httpheaders; static Context& instance(); inline void set_verbosity(int v) { verbosity = v; if (v > 0) { #ifdef WITH_ZCHUNK zck_set_log_level(ZCK_LOG_DEBUG); #endif spdlog::set_level(spdlog::level::debug); } else { spdlog::set_level(spdlog::level::warn); } } private: Context(); ~Context() = default; }; }
20.630769
92
0.56525
chGoodchild
b75f589c332ceafcdedd5da03c1a1f8acd656f28
3,974
cpp
C++
ad_map_access/impl/tests/generated/ad/map/landmark/TrafficLightTypeValidInputRangeTests.cpp
seowwj/map
2afacd50e1b732395c64b1884ccfaeeca0040ee7
[ "MIT" ]
null
null
null
ad_map_access/impl/tests/generated/ad/map/landmark/TrafficLightTypeValidInputRangeTests.cpp
seowwj/map
2afacd50e1b732395c64b1884ccfaeeca0040ee7
[ "MIT" ]
null
null
null
ad_map_access/impl/tests/generated/ad/map/landmark/TrafficLightTypeValidInputRangeTests.cpp
seowwj/map
2afacd50e1b732395c64b1884ccfaeeca0040ee7
[ "MIT" ]
1
2020-10-27T11:09:30.000Z
2020-10-27T11:09:30.000Z
/* * ----------------- BEGIN LICENSE BLOCK --------------------------------- * * Copyright (C) 2018-2020 Intel Corporation * * SPDX-License-Identifier: MIT * * ----------------- END LICENSE BLOCK ----------------------------------- */ /* * Generated file */ #include <gtest/gtest.h> #include <limits> #include "ad/map/landmark/TrafficLightTypeValidInputRange.hpp" TEST(TrafficLightTypeValidInputRangeTests, testValidInputRangeValid) { ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::INVALID)); ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::UNKNOWN)); ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::SOLID_RED_YELLOW)); ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::SOLID_RED_YELLOW_GREEN)); ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::LEFT_RED_YELLOW_GREEN)); ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::RIGHT_RED_YELLOW_GREEN)); ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::STRAIGHT_RED_YELLOW_GREEN)); ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::LEFT_STRAIGHT_RED_YELLOW_GREEN)); ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::RIGHT_STRAIGHT_RED_YELLOW_GREEN)); ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::PEDESTRIAN_RED_GREEN)); ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::BIKE_RED_GREEN)); ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::BIKE_PEDESTRIAN_RED_GREEN)); ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::PEDESTRIAN_RED_YELLOW_GREEN)); ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::BIKE_RED_YELLOW_GREEN)); ASSERT_TRUE(withinValidInputRange(::ad::map::landmark::TrafficLightType::BIKE_PEDESTRIAN_RED_YELLOW_GREEN)); } TEST(TrafficLightTypeValidInputRangeTests, testValidInputRangeInvalid) { int32_t minValue = std::numeric_limits<int32_t>::max(); minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::INVALID)); minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::UNKNOWN)); minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::SOLID_RED_YELLOW)); minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::SOLID_RED_YELLOW_GREEN)); minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::LEFT_RED_YELLOW_GREEN)); minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::RIGHT_RED_YELLOW_GREEN)); minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::STRAIGHT_RED_YELLOW_GREEN)); minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::LEFT_STRAIGHT_RED_YELLOW_GREEN)); minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::RIGHT_STRAIGHT_RED_YELLOW_GREEN)); minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::PEDESTRIAN_RED_GREEN)); minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::BIKE_RED_GREEN)); minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::BIKE_PEDESTRIAN_RED_GREEN)); minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::PEDESTRIAN_RED_YELLOW_GREEN)); minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::BIKE_RED_YELLOW_GREEN)); minValue = std::min(minValue, static_cast<int32_t>(::ad::map::landmark::TrafficLightType::BIKE_PEDESTRIAN_RED_YELLOW_GREEN)); ASSERT_FALSE(withinValidInputRange(static_cast<::ad::map::landmark::TrafficLightType>(minValue - 1))); }
60.212121
120
0.762959
seowwj
b75fb5c1b8a68b30c3c076bc8e577ca19d64ab25
5,354
cpp
C++
src/game/shared/tf/tf_projectile_nail.cpp
Xen-alpha/UltraFortress
3c2e0cbb5c6d1efe362619cd3fb94bac9067f913
[ "Unlicense" ]
null
null
null
src/game/shared/tf/tf_projectile_nail.cpp
Xen-alpha/UltraFortress
3c2e0cbb5c6d1efe362619cd3fb94bac9067f913
[ "Unlicense" ]
null
null
null
src/game/shared/tf/tf_projectile_nail.cpp
Xen-alpha/UltraFortress
3c2e0cbb5c6d1efe362619cd3fb94bac9067f913
[ "Unlicense" ]
null
null
null
//====== Copyright ?1996-2005, Valve Corporation, All rights reserved. ======= // // TF Nail // //============================================================================= #include "cbase.h" #include "tf_projectile_nail.h" #include "tf_gamerules.h" #ifdef CLIENT_DLL #include "c_basetempentity.h" #include "c_te_legacytempents.h" #include "c_te_effect_dispatch.h" #include "input.h" #include "c_tf_player.h" #include "cliententitylist.h" #endif #define NAIL_MODEL "models/weapons/w_models/w_nail.mdl" #define NAIL_DISPATCH_EFFECT "ClientProjectile_Syringe" #define NAIL_GRAVITY 0.2f LINK_ENTITY_TO_CLASS(tf_projectile_nail, CTFProjectile_Nail); PRECACHE_REGISTER(tf_projectile_nail); short g_sModelIndexNail; void PrecacheNail(void *pUser) { g_sModelIndexNail = modelinfo->GetModelIndex(NAIL_MODEL); } PRECACHE_REGISTER_FN(PrecacheNail); CTFProjectile_Nail::CTFProjectile_Nail() { } CTFProjectile_Nail::~CTFProjectile_Nail() { } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CTFProjectile_Nail *CTFProjectile_Nail::Create(const Vector &vecOrigin, const QAngle &vecAngles, CBaseEntity *pOwner, CBaseEntity *pScorer, bool bCritical) { return static_cast<CTFProjectile_Nail*>(CTFBaseProjectile::Create("tf_projectile_nail", vecOrigin, vecAngles, pOwner, CTFProjectile_Nail::GetInitialVelocity(), g_sModelIndexNail, NAIL_DISPATCH_EFFECT, pScorer, bCritical)); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- const char *CTFProjectile_Nail::GetProjectileModelName(void) { return NAIL_MODEL; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CTFProjectile_Nail::GetGravity(void) { return NAIL_GRAVITY; } //============================================================================= // // TF Syringe Projectile functions (Server specific). // #define SYRINGE_MODEL "models/weapons/w_models/w_syringe_proj.mdl" #define SYRINGE_DISPATCH_EFFECT "ClientProjectile_Syringe" #define SYRINGE_GRAVITY 0.3f LINK_ENTITY_TO_CLASS( tf_projectile_syringe, CTFProjectile_Syringe ); PRECACHE_REGISTER( tf_projectile_syringe ); short g_sModelIndexSyringe; void PrecacheSyringe(void *pUser) { g_sModelIndexSyringe = modelinfo->GetModelIndex( SYRINGE_MODEL ); } PRECACHE_REGISTER_FN(PrecacheSyringe); CTFProjectile_Syringe::CTFProjectile_Syringe() { } CTFProjectile_Syringe::~CTFProjectile_Syringe() { } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CTFProjectile_Syringe *CTFProjectile_Syringe::Create( const Vector &vecOrigin, const QAngle &vecAngles, CBaseEntity *pOwner, CBaseEntity *pScorer, bool bCritical ) { return static_cast<CTFProjectile_Syringe*>( CTFBaseProjectile::Create( "tf_projectile_syringe", vecOrigin, vecAngles, pOwner, CTFProjectile_Syringe::GetInitialVelocity(), g_sModelIndexSyringe, SYRINGE_DISPATCH_EFFECT, pScorer, bCritical ) ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- const char *CTFProjectile_Syringe::GetProjectileModelName( void ) { return SYRINGE_MODEL; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CTFProjectile_Syringe::GetGravity( void ) { return SYRINGE_GRAVITY; } #ifdef CLIENT_DLL //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *GetSyringeTrailParticleName( int iTeamNumber, bool bCritical ) { const char *pszFormat = bCritical ? "nailtrails_medic_%s_crit" : "nailtrails_medic_%s"; return ConstructTeamParticle( pszFormat, iTeamNumber, true ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void ClientsideProjectileSyringeCallback( const CEffectData &data ) { // Get the syringe and add it to the client entity list, so we can attach a particle system to it. C_TFPlayer *pPlayer = dynamic_cast<C_TFPlayer*>( ClientEntityList().GetBaseEntityFromHandle( data.m_hEntity ) ); if ( pPlayer ) { C_LocalTempEntity *pSyringe = ClientsideProjectileCallback( data, SYRINGE_GRAVITY ); if ( pSyringe ) { switch (pPlayer->GetTeamNumber()) { case TF_TEAM_RED: pSyringe->m_nSkin = 0; break; case TF_TEAM_BLUE: pSyringe->m_nSkin = 1; break; } bool bCritical = ( ( data.m_nDamageType & DMG_CRITICAL ) != 0 ); pSyringe->AddParticleEffect(GetSyringeTrailParticleName(pPlayer->GetTeamNumber(), bCritical)); pSyringe->AddEffects( EF_NOSHADOW ); pSyringe->flags |= FTENT_USEFASTCOLLISIONS; } } } DECLARE_CLIENT_EFFECT( SYRINGE_DISPATCH_EFFECT, ClientsideProjectileSyringeCallback ); #endif
33.049383
242
0.570601
Xen-alpha
b76273f9a93001b428035a625a7e94184337fe13
3,579
hpp
C++
src/Cpp/Events/ConnectionList.hpp
faizol/cpp-events
ceace40f38cdf42a6c1dcd393101d35c63859526
[ "MIT" ]
3
2015-02-05T21:34:38.000Z
2016-09-04T05:30:54.000Z
src/Cpp/Events/ConnectionList.hpp
faizol/cpp-events
ceace40f38cdf42a6c1dcd393101d35c63859526
[ "MIT" ]
1
2019-01-14T01:21:18.000Z
2019-01-14T01:21:18.000Z
src/Cpp/Events/ConnectionList.hpp
faizol/cpp-events
ceace40f38cdf42a6c1dcd393101d35c63859526
[ "MIT" ]
null
null
null
// Copyright (c) 2010 Nickolas Pohilets // // This file is a part of the CppEvents library. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #ifndef __CPP__EVENTS__CONNECTION_LIST__HPP #define __CPP__EVENTS__CONNECTION_LIST__HPP #include <Cpp/Events/BorrowableData.hpp> namespace Cpp { namespace Private { namespace Events { //------------------------------------------------------------------------------ class ConnectionList { friend void AbstractConnection::doDisconnect(); CPP_DISABLE_COPY(ConnectionList) public: class FireLock; ConnectionList(); ~ConnectionList(); void connect(ConnectionList * peer, AbstractConnection * conn); size_t connectionCount() const; size_t connectionCount(AbstractDelegate const & deleg) const; size_t connectionCount(ConnectionList * peer) const; size_t connectionCount(ConnectionList * peer, AbstractDelegate const & deleg) const; bool hasConnections() const; bool hasConnections(AbstractDelegate const & deleg) const; bool hasConnections(ConnectionList * peer) const; bool hasConnections(ConnectionList * peer, AbstractDelegate const & deleg) const; size_t disconnectAll(); size_t disconnectAll(AbstractDelegate const & deleg); size_t disconnectAll(ConnectionList * peer); size_t disconnectAll(ConnectionList * peer, AbstractDelegate const & deleg); bool disconnectOne(AbstractDelegate const & deleg); bool disconnectOne(ConnectionList * peer); bool disconnectOne(ConnectionList * peer, AbstractDelegate const & deleg); private: class NullComparer; class DelegateComparer; class PeerComparer; class FullComparer; mutable ThreadDataRef lock_; BorrowableData data_; template<class Comparer> inline size_t getConnectionCount(Comparer const &) const; template<class Comparer> inline bool getHasConnections(Comparer const &) const; template<class Comparer> inline size_t doDisconnectAll(Comparer const & ); template<class Comparer> inline bool doDisconnectOne(Comparer const & ); }; //------------------------------------------------------------------------------ class ConnectionList::FireLock { CPP_DISABLE_COPY(FireLock) public: FireLock(ConnectionList const * list) : locker_(list->lock_) , borrower_(&list->data_) {} ConnectionsVector const & constData() const { return borrower_.constData(); } private: ThreadDataLocker locker_; BorrowableData::Borrower borrower_; }; //------------------------------------------------------------------------------ } //namespace Events } //namespace Private } //namespace Cpp #endif //__CPP__EVENTS__CONNECTION_LIST__HPP
35.79
85
0.73093
faizol
b7628b6db5bf6f1739d9cb6fbc5b3fce98b7e3dd
585
cpp
C++
C++/Strings/StringStream/Solution.cpp
iamnambiar/HackerRank-Solutions
6fdcab79b18e66a6d7278b979a8be087f8f6c696
[ "MIT" ]
2
2020-04-06T10:32:08.000Z
2021-04-23T04:32:45.000Z
C++/Strings/StringStream/Solution.cpp
iamnambiar/HackerRank-Solutions
6fdcab79b18e66a6d7278b979a8be087f8f6c696
[ "MIT" ]
null
null
null
C++/Strings/StringStream/Solution.cpp
iamnambiar/HackerRank-Solutions
6fdcab79b18e66a6d7278b979a8be087f8f6c696
[ "MIT" ]
null
null
null
// https://www.hackerrank.com/challenges/c-tutorial-stringstream/problem #include <sstream> #include <vector> #include <iostream> using namespace std; vector<int> parseInts(string str) { // Complete this function stringstream ss(str); vector<int> vect; int num; while(ss>>num) { vect.push_back(num); char ch; ss>>ch; } return vect; } int main() { string str; cin >> str; vector<int> integers = parseInts(str); for(int i = 0; i < integers.size(); i++) { cout << integers[i] << "\n"; } return 0; }
18.870968
72
0.582906
iamnambiar
b762e751d7391c15134c15de56bc730b88fb99d7
737
cpp
C++
src/dsm_to_dtm.cpp
pierriko/clara
3b0f788f5d120ca4be8a1ae5ab65c7c4d811a49d
[ "BSD-3-Clause" ]
1
2015-04-23T02:21:11.000Z
2015-04-23T02:21:11.000Z
src/dsm_to_dtm.cpp
pierriko/clara
3b0f788f5d120ca4be8a1ae5ab65c7c4d811a49d
[ "BSD-3-Clause" ]
null
null
null
src/dsm_to_dtm.cpp
pierriko/clara
3b0f788f5d120ca4be8a1ae5ab65c7c4d811a49d
[ "BSD-3-Clause" ]
null
null
null
/* * region.cpp * * Common LAAS Raster library * * author: Pierrick Koch <pierrick.koch@laas.fr> * created: 2013-06-12 * license: BSD */ #include <string> // for string #include <stdexcept> // for runtime_error #include <cstdlib> // exit status #include <cmath> #include "gdalwrap/gdal.hpp" int main(int argc, char * argv[]) { std::cout<<"Common LAAS Raster library"<<std::endl; if (argc < 3) { std::cerr<<"usage: "<<argv[0]<<" dsm.dtm dtm.tif"<<std::endl; return EXIT_FAILURE; } gdalwrap::gdal dsm(argv[1]); dsm.names = {"Z_MAX", "N_POINTS"}; dsm.bands.push_back(gdalwrap::raster(dsm.bands[0].size(), 1)); dsm.save(argv[2]); return EXIT_SUCCESS; }
22.333333
69
0.598372
pierriko
b766226e90bd1d9a173a974a1d869d1f0a82f44b
391
cpp
C++
AtCoder/abc207/b/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
null
null
null
AtCoder/abc207/b/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
1
2021-10-19T08:47:23.000Z
2022-03-07T05:23:56.000Z
AtCoder/abc207/b/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> #include <algorithm> #include <vector> using namespace std; int main() { long long int a, b, c, d; cin >> a >> b >> c >> d; long long int x = a, y = 0; for (int i = 1; i <= a; i++) { x += b, y += c; if (x <= d * y) { cout << i << endl; return 0; } } cout << -1 << endl; return 0; }
20.578947
54
0.432225
H-Tatsuhiro
b766df7a9a673ca5d27835decb2168f0ee903708
1,108
cpp
C++
src/main/cpp/Robot.cpp
team2053tigertronics/Robot2020
021fae6f8cfc412bb645a4c50c7b4cd9e65e6524
[ "MIT" ]
5
2019-12-20T16:37:22.000Z
2021-06-16T05:47:40.000Z
src/main/cpp/Robot.cpp
team2053tigertronics/Robot2020
021fae6f8cfc412bb645a4c50c7b4cd9e65e6524
[ "MIT" ]
null
null
null
src/main/cpp/Robot.cpp
team2053tigertronics/Robot2020
021fae6f8cfc412bb645a4c50c7b4cd9e65e6524
[ "MIT" ]
null
null
null
#include "Robot.h" #include <frc/smartdashboard/SmartDashboard.h> #include <frc2/command/CommandScheduler.h> #include <frc2/command/WaitCommand.h> #include <frc2/command/SequentialCommandGroup.h> #include <frc/shuffleboard/Shuffleboard.h> #include <wpi/PortForwarder.h> void Robot::RobotInit() { wpi::PortForwarder::GetInstance().Add(5800, "chameleon-vision.local", 5800); wpi::PortForwarder::GetInstance().Add(1181, "chameleon-vision.local", 1181); } void Robot::RobotPeriodic() { frc2::CommandScheduler::GetInstance().Run(); } void Robot::DisabledInit() {} void Robot::DisabledPeriodic() {} void Robot::AutonomousInit() { m_autonomousCommand = m_container.GetAutonomousCommand(); if (m_autonomousCommand != nullptr) { m_autonomousCommand->Schedule(); } } void Robot::AutonomousPeriodic() { } void Robot::TeleopInit() { if (m_autonomousCommand != nullptr) { m_autonomousCommand->Cancel(); m_autonomousCommand = nullptr; } } void Robot::TeleopPeriodic() { } void Robot::TestPeriodic() {} #ifndef RUNNING_FRC_TESTS int main() { return frc::StartRobot<Robot>(); } #endif
23.083333
78
0.730144
team2053tigertronics
b768d9ae87f1069a6b2fa493f74aa314abdf0a08
5,032
cpp
C++
scope_onboard_st4.cpp
iphantomsky/open-phd-guiding
41f6f277cd2a2efd25dc198eae3206cf95102608
[ "BSD-3-Clause" ]
null
null
null
scope_onboard_st4.cpp
iphantomsky/open-phd-guiding
41f6f277cd2a2efd25dc198eae3206cf95102608
[ "BSD-3-Clause" ]
null
null
null
scope_onboard_st4.cpp
iphantomsky/open-phd-guiding
41f6f277cd2a2efd25dc198eae3206cf95102608
[ "BSD-3-Clause" ]
null
null
null
/* * scope_onboard_st4.cpp * PHD Guiding * * Created by Bret McKee * Copyright (c) 2012 Bret McKee * All rights reserved. * * This source code is distributed under the following "BSD" license * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * Neither the name of Bret McKee, Dad Dog Development, * Craig Stark, Stark Labs nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include "phd.h" #include "scope_onboard_st4.h" ScopeOnboardST4::ScopeOnboardST4(void) { m_pOnboardHost = NULL; } ScopeOnboardST4::~ScopeOnboardST4(void) { if (IsConnected()) { Disconnect(); } m_pOnboardHost = NULL; } bool ScopeOnboardST4::ConnectOnboardST4(OnboardST4 *pOnboardHost) { bool bError = false; try { if (!pOnboardHost) { throw ERROR_INFO("Attempt to Connect OnboardST4 mount with pOnboardHost == NULL"); } m_pOnboardHost = pOnboardHost; if (IsConnected()) { Disconnect(); } if (!m_pOnboardHost->ST4HasGuideOutput()) { throw ERROR_INFO("Attempt to Connect Onboard ST4 mount when host does not have guide output"); } if (!m_pOnboardHost->ST4HostConnected()) { throw ERROR_INFO("Attempt to Connect Onboard ST4 mount when host is not connected"); } Scope::Connect(); } catch (wxString Msg) { POSSIBLY_UNUSED(Msg); bError = true; } return bError; } bool ScopeOnboardST4::Disconnect(void) { bool bError = false; try { if (!IsConnected()) { throw ERROR_INFO("Attempt to Disconnect On Camera mount when not connected"); } assert(m_pOnboardHost); m_pOnboardHost = NULL; bError = Scope::Disconnect(); } catch (wxString Msg) { POSSIBLY_UNUSED(Msg); bError = true; } return bError; } Mount::MOVE_RESULT ScopeOnboardST4::Guide(GUIDE_DIRECTION direction, int duration) { MOVE_RESULT result = MOVE_OK; try { if (!IsConnected()) { throw ERROR_INFO("Attempt to Guide On Camera mount when not connected"); } if (!m_pOnboardHost) { throw ERROR_INFO("Attempt to Guide OnboardST4 mount when m_pOnboardHost == NULL"); } if (!m_pOnboardHost->ST4HostConnected()) { throw ERROR_INFO("Attempt to Guide On Camera mount when camera is not connected"); } if (m_pOnboardHost->ST4PulseGuideScope(direction,duration)) { result = MOVE_ERROR; } } catch (wxString Msg) { POSSIBLY_UNUSED(Msg); result = MOVE_ERROR; } return result; } bool ScopeOnboardST4::HasNonGuiMove(void) { bool bReturn = false; try { if (!IsConnected()) { throw ERROR_INFO("Attempt to HasNonGuiMove On Camera mount when not connected"); } if (!m_pOnboardHost->ST4HostConnected()) { throw ERROR_INFO("Attempt to HasNonGuiMove On Camera mount when camera is not connected"); } if (!m_pOnboardHost) { throw ERROR_INFO("Attempt HasNonGuiMove OnboardST4 mount when m_pOnboardHost == NULL"); } bReturn = m_pOnboardHost->ST4HasNonGuiMove(); } catch (wxString Msg) { POSSIBLY_UNUSED(Msg); } return bReturn; }
27.497268
107
0.618641
iphantomsky
b768f8c2923c44ca69840774707ed8be76aeb06a
487
hpp
C++
Siv3D/src/Siv3D/Webcam/CWebcam.hpp
Fuyutsubaki/OpenSiv3D
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
[ "MIT" ]
null
null
null
Siv3D/src/Siv3D/Webcam/CWebcam.hpp
Fuyutsubaki/OpenSiv3D
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
[ "MIT" ]
null
null
null
Siv3D/src/Siv3D/Webcam/CWebcam.hpp
Fuyutsubaki/OpenSiv3D
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
[ "MIT" ]
null
null
null
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2018 Ryo Suzuki // Copyright (c) 2016-2018 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include "IWebcam.hpp" # include <Siv3D/Webcam.hpp> namespace s3d { class CWebcam : public ISiv3DWebcam { private: public: CWebcam(); ~CWebcam() override; bool init() override; }; }
15.709677
50
0.529774
Fuyutsubaki
b769d4045bb1ab804f3a9277da0387545ef41505
13,587
cpp
C++
applications/physbam/physbam-lib/Public_Library/PhysBAM_Solids/PhysBAM_Deformables/Bindings/SOFT_BINDINGS.cpp
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
20
2017-07-03T19:09:09.000Z
2021-09-10T02:53:56.000Z
applications/physbam/physbam-lib/Public_Library/PhysBAM_Solids/PhysBAM_Deformables/Bindings/SOFT_BINDINGS.cpp
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
null
null
null
applications/physbam/physbam-lib/Public_Library/PhysBAM_Solids/PhysBAM_Deformables/Bindings/SOFT_BINDINGS.cpp
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
9
2017-09-17T02:05:06.000Z
2020-01-31T00:12:01.000Z
//##################################################################### // Copyright 2006-2008, Geoffrey Irving, Tamar Shinar, Eftychios Sifakis. // This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt. //##################################################################### // Class SOFT_BINDINGS //##################################################################### #include <PhysBAM_Tools/Data_Structures/HASHTABLE_ITERATOR.h> #include <PhysBAM_Tools/Data_Structures/SPARSE_UNION_FIND.h> #include <PhysBAM_Tools/Log/LOG.h> #include <PhysBAM_Tools/Read_Write/Arrays/READ_WRITE_ARRAY.h> #include <PhysBAM_Solids/PhysBAM_Deformables/Bindings/SOFT_BINDINGS.h> #include <PhysBAM_Solids/PhysBAM_Deformables/Deformable_Objects/DEFORMABLE_BODY_COLLECTION.h> using namespace PhysBAM; //##################################################################### // Constructor //##################################################################### template<class TV> SOFT_BINDINGS<TV>:: SOFT_BINDINGS(BINDING_LIST<TV>& binding_list_input) :binding_list(binding_list_input),particles(binding_list_input.particles),binding_mesh(0),use_gauss_seidel_for_impulse_based_collisions(false),last_read(-1),is_stale(true),frame_list(0) {} //##################################################################### // Destructor //##################################################################### template<class TV> SOFT_BINDINGS<TV>:: ~SOFT_BINDINGS() { delete binding_mesh; } //##################################################################### // Function Initialize_Binding_Mesh //##################################################################### template<class TV> void SOFT_BINDINGS<TV>:: Initialize_Binding_Mesh(const bool exclude_particles_using_impulses_for_collisions) { delete binding_mesh; if(exclude_particles_using_impulses_for_collisions){ binding_mesh=new SEGMENT_MESH;binding_mesh->Set_Number_Nodes(particles.array_collection->Size()); for(int b=1;b<=bindings.m;b++) if(!use_impulses_for_collisions(b)) binding_mesh->elements.Append(bindings(b));} else binding_mesh=new SEGMENT_MESH(particles.array_collection->Size(),bindings); } //##################################################################### // Function Add_Dependencies //##################################################################### template<class TV> void SOFT_BINDINGS<TV>:: Add_Dependencies(SEGMENT_MESH& dependency_mesh) const { for(int i=1;i<=bindings.m;i++) dependency_mesh.Add_Element_If_Not_Already_There(bindings(i)); } //##################################################################### // Function Set_Mass_From_Effective_Mass //##################################################################### template<class TV> void SOFT_BINDINGS<TV>:: Set_Mass_From_Effective_Mass() { for(int b=1;b<=bindings.m;b++){ particles.mass(bindings(b).x)=particles.effective_mass(bindings(b).x); particles.one_over_mass(bindings(b).x)=particles.one_over_effective_mass(bindings(b).x);} } //##################################################################### // Function Remove_Soft_Bound_Particles //##################################################################### template<class TV> void SOFT_BINDINGS<TV>:: Remove_Soft_Bound_Particles(ARRAY<int>& particles) const { for(int i=particles.m;i>=1;i--) if(Particle_Is_Bound(particles(i))) particles.Remove_Index_Lazy(i); } //##################################################################### // Function Adjust_Parents_For_Changes_In_Surface_Children //##################################################################### template<class TV> int SOFT_BINDINGS<TV>:: Adjust_Parents_For_Changes_In_Surface_Children(const ARRAY<bool>& particle_on_surface) { PHYSBAM_ASSERT(binding_list.deformable_body_collection); bool nothing_to_do=true; if(bindings_using_impulses_for_collisions.m) nothing_to_do=false; // TODO: MPI if(nothing_to_do) return 0; int interactions=0; HASHTABLE<int,TV> total_delta_X,total_delta_V; HASHTABLE<int> self_collision,parents_changed; HASHTABLE<int,int> number_of_children; // figure out which embedded points are not where they should be or have differing velocities for(int i=1;i<=bindings_using_impulses_for_collisions.m;i++){ int p,parent;bindings(bindings_using_impulses_for_collisions(i)).Get(p,parent); BINDING<TV>* hard_binding=binding_list.Binding(parent); ARRAY<int> parents;if(hard_binding) parents=hard_binding->Parents();else parents.Append(parent); if(particle_on_surface(p)){ if(hard_binding){hard_binding->Clamp_To_Embedded_Position();hard_binding->Clamp_To_Embedded_Velocity();} // TODO: make this unnecessary if(particles.X(p)!=particles.X(parent) || particles.V(p)!=particles.V(parent)){interactions++; TV delta_X=particles.X(p)-particles.X(parent),delta_V=particles.V(p)-particles.V(parent); for(int j=1;j<=parents.m;j++) if(!particle_on_surface(parents(j))){ self_collision.Set(parents(j)); if(hard_binding) parents_changed.Set(parent); total_delta_X.Get_Or_Insert(parents(j))+=delta_X;total_delta_V.Get_Or_Insert(parents(j))+=delta_V;}}} // TODO: consider only counting children that are on the surface for(int j=1;j<=parents.m;j++) number_of_children.Get_Or_Insert(parents(j))++;} // adjust parents to match changes in children, skipping parents on the surface since they may also be self-colliding for(typename HASHTABLE<int>::ITERATOR it(self_collision);it.Valid();it.Next()){int p=it.Key(); T one_over_number_of_children=(T)1/number_of_children.Get(p); particles.X(p)+=total_delta_X.Get(p)*one_over_number_of_children; particles.V(p)+=total_delta_V.Get(p)*one_over_number_of_children;} // update affected hard bindings // TODO: this can be simplified if we completely disallow modification of hard-bound particles for(typename HASHTABLE<int>::ITERATOR it(parents_changed);it.Valid();it.Next()){int b=binding_list.binding_index_from_particle_index(it.Key()); binding_list.bindings(b)->Clamp_To_Embedded_Position();binding_list.bindings(b)->Clamp_To_Embedded_Velocity();} return interactions; } //##################################################################### // Function Adjust_Parents_For_Changes_In_Surface_Children_Velocities //##################################################################### template<class TV> int SOFT_BINDINGS<TV>:: Adjust_Parents_For_Changes_In_Surface_Children_Velocities(const ARRAY<bool>& particle_on_surface) { PHYSBAM_ASSERT(binding_list.deformable_body_collection); bool nothing_to_do=true; if(bindings_using_impulses_for_collisions.m) nothing_to_do=false; // TODO: MPI if(nothing_to_do) return 0; int interactions=0; HASHTABLE<int,TV> total_delta_V; HASHTABLE<int> self_collision,parents_changed; HASHTABLE<int,int> number_of_children; // figure out which embedded points are not where they should be or have differing velocities for(int i=1;i<=bindings_using_impulses_for_collisions.m;i++){ int p,parent;bindings(bindings_using_impulses_for_collisions(i)).Get(p,parent); BINDING<TV>* hard_binding=binding_list.Binding(parent); ARRAY<int> parents;if(hard_binding) parents=hard_binding->Parents();else parents.Append(parent); if(particle_on_surface(p)){ if(hard_binding) hard_binding->Clamp_To_Embedded_Velocity(); // TODO: make this unnecessary if(particles.V(p)!=particles.V(parent)){interactions++; TV delta_V=particles.V(p)-particles.V(parent); for(int j=1;j<=parents.m;j++) if(!particle_on_surface(parents(j))){ self_collision.Set(parents(j)); if(hard_binding) parents_changed.Set(parent); total_delta_V.Get_Or_Insert(parents(j))+=delta_V;}}} // TODO: consider only counting children that are on the surface for(int j=1;j<=parents.m;j++) number_of_children.Get_Or_Insert(parents(j))++;} // adjust parents to match changes in children, skipping parents on the surface since they may also be self-colliding for(typename HASHTABLE<int>::ITERATOR it(self_collision);it.Valid();it.Next()){int p=it.Key(); T one_over_number_of_children=(T)1/number_of_children.Get(p); particles.V(p)+=total_delta_V.Get(p)*one_over_number_of_children;} // update affected hard bindings // TODO: this can be simplified if we completely disallow modification of hard-bound particles for(typename HASHTABLE<int>::ITERATOR it(parents_changed);it.Valid();it.Next()){int b=binding_list.binding_index_from_particle_index(it.Key()); binding_list.bindings(b)->Clamp_To_Embedded_Velocity();} return interactions; } //##################################################################### // Function Need_Bindings_Mapped //##################################################################### template<class TV> bool SOFT_BINDINGS<TV>:: Need_Bindings_Mapped() const { return (bindings_using_forces_for_collisions.m!=0)?true:false; } //##################################################################### // Function Map_Forces_From_Parents //##################################################################### template<class TV> void SOFT_BINDINGS<TV>:: Map_Forces_From_Parents(ARRAY_VIEW<TV> F_full,ARRAY_VIEW<const TWIST<TV> > wrench_full) const { for(int b=1;b<=bindings.m;b++){ // TODO: MPI BINDING<TV>* hard_binding=binding_list.Binding(bindings(b).y); if(hard_binding) F_full(bindings(b).x)+=particles.mass(bindings(b).x)*hard_binding->Embedded_Acceleration(F_full,wrench_full); else F_full(bindings(b).x)+=particles.mass(bindings(b).x)*particles.one_over_mass(bindings(b).y)*F_full(bindings(b).y);} } //##################################################################### // Function Clamp_Particles_To_Embedded_Positions //##################################################################### template<class TV> void SOFT_BINDINGS<TV>:: Clamp_Particles_To_Embedded_Positions(const bool bindings_using_impulses_for_collisions_only) const { if(bindings_using_impulses_for_collisions_only){ for(int i=1;i<=bindings_using_impulses_for_collisions.m;i++){ const VECTOR<int,2>& binding=bindings(bindings_using_impulses_for_collisions(i));particles.X(binding.x)=particles.X(binding.y);}} else for(int i=1;i<=bindings.m;i++){particles.X(bindings(i).x)=particles.X(bindings(i).y);} } //##################################################################### // Function Clamp_Particles_To_Embedded_Velocities //##################################################################### template<class TV> void SOFT_BINDINGS<TV>:: Clamp_Particles_To_Embedded_Velocities(const bool bindings_using_impulses_for_collisions_only) const { if(bindings_using_impulses_for_collisions_only){ for(int i=1;i<=bindings_using_impulses_for_collisions.m;i++){ const VECTOR<int,2>& binding=bindings(bindings_using_impulses_for_collisions(i));particles.V(binding.x)=particles.V(binding.y);}} else for(int i=1;i<=bindings.m;i++){particles.V(bindings(i).x)=particles.V(bindings(i).y);} } //##################################################################### // Function Update_Binding_Index_From_Particle_Index //##################################################################### template<class TV> void SOFT_BINDINGS<TV>:: Update_Binding_Index_From_Particle_Index() { binding_index_from_particle_index.Clean_Memory(); int max_particle_index=0;for(int b=1;b<=bindings.m;b++) max_particle_index=max(max_particle_index,bindings(b).x); binding_index_from_particle_index.Resize(max_particle_index); for(int b=1;b<=bindings.m;b++){assert(!binding_index_from_particle_index(bindings(b).x));binding_index_from_particle_index(bindings(b).x)=b;} } //##################################################################### // Function Read //##################################################################### template<class TV> void SOFT_BINDINGS<TV>:: Read(TYPED_ISTREAM& input) { SEGMENT_MESH* binding_mesh_save=binding_mesh;binding_mesh=0; // save binding mesh so we don't kill it in Clean_Memory Clean_Memory();int backward_compatible;Read_Binary(input,backward_compatible,bindings); if(bindings.m) Read_Binary(input,use_impulses_for_collisions); // TODO: remove this backwards compatibility hack after Siggraph Update_Binding_Index_From_Particle_Index(); if(binding_mesh_save){binding_mesh=binding_mesh_save;binding_mesh->Initialize_Mesh(particles.array_collection->Size(),bindings);} } //##################################################################### // Function Write //##################################################################### template<class TV> void SOFT_BINDINGS<TV>:: Write(TYPED_OSTREAM& output) const { Write_Binary(output,2,bindings,use_impulses_for_collisions); } //##################################################################### template class SOFT_BINDINGS<VECTOR<float,1> >; template class SOFT_BINDINGS<VECTOR<float,2> >; template class SOFT_BINDINGS<VECTOR<float,3> >; #ifndef COMPILE_WITHOUT_DOUBLE_SUPPORT template class SOFT_BINDINGS<VECTOR<double,1> >; template class SOFT_BINDINGS<VECTOR<double,2> >; template class SOFT_BINDINGS<VECTOR<double,3> >; #endif
56.849372
189
0.622433
schinmayee
b76a4bfae5704831e9f9e2867814a38e3cd6abd1
5,486
cpp
C++
src/main.cpp
ilyayunkin/StocksMonitor
92ba47fa4e92e9dab498ea6751178ef823a83bbc
[ "MIT" ]
null
null
null
src/main.cpp
ilyayunkin/StocksMonitor
92ba47fa4e92e9dab498ea6751178ef823a83bbc
[ "MIT" ]
null
null
null
src/main.cpp
ilyayunkin/StocksMonitor
92ba47fa4e92e9dab498ea6751178ef823a83bbc
[ "MIT" ]
1
2020-12-04T08:18:21.000Z
2020-12-04T08:18:21.000Z
#include "WidgetsUi/mainwindow.h" #include <QApplication> #include <QDir> #include <QDebug> #include <QMessageBox> #include <vector> #include "logger.h" #include "ExceptionClasses.h" #include "WidgetsUi/Dialogs.h" #include "WidgetsUi/Notifier.h" #include "WidgetsUi/Sounds/Signalizer.h" #include "Application/PluginsLoader.h" #include "Application/Market.h" #include "Application/CurrencyConverter.h" #include "Application/CurrencyCourseSource.h" #include "Application/Browser.h" #include "Application/StatisticsCsvSaver.h" #include "Application/StatisticsConfigDatabase.h" #include "Application/PortfolioDatabase.h" #include "Application/Controllers/StatisticsController.h" #include "Application/Controllers/ProcessStatisticsController.h" #include "Application/PortfolioInterface.h" #include "Application/StatisticsConfigDatabase.h" #include "Rules/Portfolio.h" #include "Rules/ProcessStatisticsInteractor.h" #include "Rules/StatisticsInteractor.h" #include "Rules/AddToPortfolioInteractor.h" #include "Rules/UpdatePortfolioFromStocksInteractor.h" #include "Rules/OpenUrlInteractor.h" #include "Rules/ChainOfStocksProcessing/DummyNode.h" typedef std::vector<std::unique_ptr<Market>> MarketsList; MarketsList createMarkets(AbstractDialogs &dialogs) { MarketsList list; auto plugins = PluginsLoader::loadPlugins(); list.reserve(plugins.size()); for(auto &p : plugins){ list.push_back(std::make_unique<Market>(&dialogs, *p)); } return list; } StocksInterfacesList createStocksInterfacesList(MarketsList &markets) { StocksInterfacesList list; list.reserve(markets.size()); for(auto &market : markets){ list.push_back(&*market); } return list; } CurrencyConverter createCurrencyConverter(const MarketsList &markets, const Dialogs &dialogs) { auto getCurrencySourceInterface = [&]{ auto cbrfInterfaceIterator = std::find_if(markets.begin(), markets.end(), [](const auto &interface){return interface->getPluginName() == PluginName("CBRF-Currency");}); if(cbrfInterfaceIterator != markets.end()) return new CurrencyCourseSource(**cbrfInterfaceIterator); return static_cast<CurrencyCourseSource *>(nullptr); }; return CurrencyConverter (CurrencyCode("RUB"), dialogs, getCurrencySourceInterface()); } int main(int argc, char *argv[]) { QApplication a(argc, argv); a.setOrganizationName("Ilya"); a.setApplicationName("StocksMonitor"); int ret = -1; try { Logger::instance().log("The program is started"); Dialogs dialogs; auto markets = createMarkets(dialogs); auto stocksInterfacesList = createStocksInterfacesList(markets); CurrencyConverter currencyConverter = createCurrencyConverter(markets, dialogs); Portfolio portfolio(std::make_unique<PortfolioDatabase>()); PortfolioInterface portfolioInterface( portfolio, stocksInterfacesList, currencyConverter); StatisticsCsvSaver csvSaver; StatisticsConfigList statisticsConfigList; ProcessStatisticsInteractor processStatisticsInteractor(statisticsConfigList, currencyConverter); StatisticsInteractor statisticsInteractor(std::make_unique<StatisticsConfigDatabase>(), statisticsConfigList, dialogs); StatisticsController statisticsController(statisticsInteractor); ProcessStatisticsController processStatisticsController( portfolio, processStatisticsInteractor, csvSaver); MainWindow w; Browser browser; AddToPortfolioInteractor addToPortfolioInteractor(portfolio, stocksInterfacesList, dialogs); UpdatePortfolioFromStocksInteractor updatePortfolioFromStocksInteractor(portfolio, stocksInterfacesList, dialogs); OpenUrlInteractor openUrlInteractor(stocksInterfacesList, browser); StocksProcessing::DummyNode processingHeadDummy; for(auto &m : markets){ StocksProcessing::connect(&*m, &processingHeadDummy); } StocksProcessing::connect(&portfolioInterface, &processingHeadDummy, &addToPortfolioInteractor, &updatePortfolioFromStocksInteractor, &openUrlInteractor, w.getNotifier()); for(auto &m : markets){ w.addTab(*m, *m); } w.addTab(portfolioInterface); w.addTab(processStatisticsController, statisticsController, stocksInterfacesList); w.showMaximized(); dialogs.setMainWindow(&w); ret = a.exec(); }catch(std::runtime_error &e) { Logger::instance().log(e.what()); QMessageBox::critical(nullptr, QObject::tr("Critical error"), QObject::tr("Application will be closed: %1" "\nCheck the log file.").arg(e.what())); std::terminate(); }catch (...) { Logger::instance().log("Undefined exception"); QMessageBox::critical(nullptr, QObject::tr("Critical error"), QObject::tr("Application will be closed: " "Undefined exception" "\nCheck the log file.")); std::terminate(); } return ret; }
37.319728
144
0.666788
ilyayunkin
b76b38b2e3b3456212205a2de6e37d6c993eff79
1,796
cpp
C++
Treap (Cartesian Tree)/Treap.cpp
yokeshrana/Fast_Algorithms_in_Data_Structures
2346fee16c6c3ffceac7cb79b1f449b4d8dc9df2
[ "MIT" ]
null
null
null
Treap (Cartesian Tree)/Treap.cpp
yokeshrana/Fast_Algorithms_in_Data_Structures
2346fee16c6c3ffceac7cb79b1f449b4d8dc9df2
[ "MIT" ]
null
null
null
Treap (Cartesian Tree)/Treap.cpp
yokeshrana/Fast_Algorithms_in_Data_Structures
2346fee16c6c3ffceac7cb79b1f449b4d8dc9df2
[ "MIT" ]
1
2021-06-23T04:48:59.000Z
2021-06-23T04:48:59.000Z
// github.com/andy489 #include <cstdio> #include <cstdlib> #include <ctime> #include <algorithm> using namespace std; struct item { int key, prior; item *l, *r; int cnt = 0; item(int key, int prior) : key(key), prior(prior), l(nullptr), r(nullptr) {}; }; typedef item *pitem; int cnt(pitem t) { return t ? t->cnt : 0; } void upd_cnt(pitem t) { if (t) t->cnt = 1 + cnt(t->l) + cnt(t->r); } void heapify(pitem t) { if (!t) return; pitem max = t; if (t->l != nullptr && t->l->prior > max->prior) max = t->l; if (t->r != nullptr && t->r->prior > max->prior) max = t->r; if (max != t) { swap(t->prior, max->prior); heapify(max); } } pitem build(int *a, int n) { /// Construct a treap on values {a[0], a[1], ..., a[n-1]} if (n == 0) return nullptr; int mid = n >> 1; pitem t = new item(a[mid], rand() % 300); t->l = build(a, mid); t->r = build(a + mid + 1, n - mid - 1); heapify(t); upd_cnt(t); return t; } void dfs(pitem t) { if (!t) return; dfs(t->l); printf("%d %d, ", t->key, t->prior); dfs(t->r); } #include <queue> void bfs(pitem t) { queue<pitem> Q; Q.push(t); int SZ; while (!Q.empty()) { SZ = Q.size(); while (SZ--) { pitem curr = Q.front(); Q.pop(); printf("%d %d, ", curr->key, curr->prior); if (curr->l) Q.push(curr->l); if (curr->r) Q.push(curr->r); } printf("\n"); } } int main() { srand(time(nullptr)); int a[] = {2, 4, 8, 3, 6, 22, 9, 1}; int n = sizeof a / sizeof(int); pitem treap = build(a, n); dfs(treap); printf("\n\n"); bfs(treap); return 0; }
19.521739
81
0.465479
yokeshrana
b76dd0bf6e6892127b6e62f52dbc3b7b1a7ba30a
536
cpp
C++
TacticsVictory/src/local/Updater/main_updater.cpp
Sasha7b9/U-Cube2
f1991605dcdac2e24eb3e92ef9ce001f9ed4b451
[ "MIT" ]
null
null
null
TacticsVictory/src/local/Updater/main_updater.cpp
Sasha7b9/U-Cube2
f1991605dcdac2e24eb3e92ef9ce001f9ed4b451
[ "MIT" ]
null
null
null
TacticsVictory/src/local/Updater/main_updater.cpp
Sasha7b9/U-Cube2
f1991605dcdac2e24eb3e92ef9ce001f9ed4b451
[ "MIT" ]
null
null
null
// 2021/04/02 17:14:22 (c) Aleksandr Shevchenko e-mail : Sasha7b9@tut.by #include "stdafx.h" #include "Network/Other/ConnectorTCP_v.h" int main(int argc, char * /*argv*/ []) { setlocale(LC_ALL, "Russian"); LOGWRITE("Start Updater"); if (argc != 2) { LOGERROR("No address master server specified."); LOGERROR("Define it: Updater.exe 127.0.0.1:40000"); return -1; } // TheMasterServer.Connect(argv[1]); //TheMasterServer.Destroy(); LOGWRITE("Exit Updater"); return 0; }
19.142857
72
0.61194
Sasha7b9
b770222dc888eba5d4a8dadd20d596b2b4c0a7a8
8,995
cc
C++
tests/libtests/materials/data/obsolete/DruckerPrager3DElasticData.cc
Grant-Block/pylith
f6338261b17551eba879da998a5aaf2d91f5f658
[ "MIT" ]
93
2015-01-08T16:41:22.000Z
2022-02-25T13:40:02.000Z
tests/libtests/materials/data/obsolete/DruckerPrager3DElasticData.cc
Grant-Block/pylith
f6338261b17551eba879da998a5aaf2d91f5f658
[ "MIT" ]
277
2015-02-20T16:27:35.000Z
2022-03-30T21:13:09.000Z
tests/libtests/materials/data/obsolete/DruckerPrager3DElasticData.cc
Grant-Block/pylith
f6338261b17551eba879da998a5aaf2d91f5f658
[ "MIT" ]
71
2015-03-24T12:11:08.000Z
2022-03-03T04:26:02.000Z
// -*- C++ -*- // // ====================================================================== // // Brad T. Aagaard, U.S. Geological Survey // Charles A. Williams, GNS Science // Matthew G. Knepley, University of Chicago // // This code was developed as part of the Computational Infrastructure // for Geodynamics (http://geodynamics.org). // // Copyright (c) 2010-2017 University of California, Davis // // See COPYING for license information. // // ====================================================================== // // DO NOT EDIT THIS FILE // This file was generated from python application druckerprager3delastic. #include "DruckerPrager3DElasticData.hh" const int pylith::materials::DruckerPrager3DElasticData::_dimension = 3; const int pylith::materials::DruckerPrager3DElasticData::_numLocs = 2; const int pylith::materials::DruckerPrager3DElasticData::_numProperties = 6; const int pylith::materials::DruckerPrager3DElasticData::_numStateVars = 1; const int pylith::materials::DruckerPrager3DElasticData::_numDBProperties = 6; const int pylith::materials::DruckerPrager3DElasticData::_numDBStateVars = 6; const int pylith::materials::DruckerPrager3DElasticData::_numPropsQuadPt = 6; const int pylith::materials::DruckerPrager3DElasticData::_numVarsQuadPt = 6; const PylithScalar pylith::materials::DruckerPrager3DElasticData::_lengthScale = 1.00000000e+03; const PylithScalar pylith::materials::DruckerPrager3DElasticData::_timeScale = 1.00000000e+00; const PylithScalar pylith::materials::DruckerPrager3DElasticData::_pressureScale = 2.25000000e+10; const PylithScalar pylith::materials::DruckerPrager3DElasticData::_densityScale = 2.25000000e+04; const PylithScalar pylith::materials::DruckerPrager3DElasticData::_dtStableImplicit = 1.00000000e+10; const PylithScalar pylith::materials::DruckerPrager3DElasticData::_dtStableExplicit = 1.92450090e-01; const int pylith::materials::DruckerPrager3DElasticData::_numPropertyValues[] = { 1, 1, 1, 1, 1, 1, }; const int pylith::materials::DruckerPrager3DElasticData::_numStateVarValues[] = { 6, }; const char* pylith::materials::DruckerPrager3DElasticData::_dbPropertyValues[] = { "density", "vs", "vp", "friction-angle", "cohesion", "dilatation-angle", }; const char* pylith::materials::DruckerPrager3DElasticData::_dbStateVarValues[] = { "plastic-strain-xx", "plastic-strain-yy", "plastic-strain-zz", "plastic-strain-xy", "plastic-strain-yz", "plastic-strain-xz", }; const PylithScalar pylith::materials::DruckerPrager3DElasticData::_dbProperties[] = { 2.50000000e+03, 3.00000000e+03, 5.19615242e+03, 5.23598776e-01, 3.00000000e+05, 3.49065850e-01, 2.00000000e+03, 1.20000000e+03, 2.07846097e+03, 4.36332313e-01, 1.00000000e+05, 4.36332313e-01, }; const PylithScalar pylith::materials::DruckerPrager3DElasticData::_dbStateVars[] = { 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, }; const PylithScalar pylith::materials::DruckerPrager3DElasticData::_properties[] = { 2.50000000e+03, 2.25000000e+10, 2.25000000e+10, 2.30940108e-01, 3.60000000e+05, 1.48583084e-01, 2.00000000e+03, 2.88000000e+09, 2.88000000e+09, 1.89338478e-01, 1.21811303e+05, 1.89338478e-01, }; const PylithScalar pylith::materials::DruckerPrager3DElasticData::_stateVars[] = { 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, }; const PylithScalar pylith::materials::DruckerPrager3DElasticData::_propertiesNondim[] = { 1.11111111e-01, 1.00000000e+00, 1.00000000e+00, 2.30940108e-01, 1.60000000e-05, 1.48583084e-01, 8.88888889e-02, 1.28000000e-01, 1.28000000e-01, 1.89338478e-01, 5.41383567e-06, 1.89338478e-01, }; const PylithScalar pylith::materials::DruckerPrager3DElasticData::_stateVarsNondim[] = { 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, }; const PylithScalar pylith::materials::DruckerPrager3DElasticData::_density[] = { 2.50000000e+03, 2.00000000e+03, }; const PylithScalar pylith::materials::DruckerPrager3DElasticData::_strain[] = { -1.10000000e-04, -1.20000000e-04, -1.30000000e-04, 1.40000000e-04, 1.50000000e-04, 1.60000000e-04, 4.10000000e-04, 4.20000000e-04, 4.30000000e-04, 4.40000000e-04, 4.50000000e-04, 4.60000000e-04, }; const PylithScalar pylith::materials::DruckerPrager3DElasticData::_stress[] = { -4.85790000e+07, -4.94780000e+07, -5.03770000e+07, -8.97600000e+06, -8.97500000e+06, -8.97400000e+06, -2.82900000e+06, -2.82800000e+06, -2.82700000e+06, -1.09800000e+06, -1.09700000e+06, -1.09600000e+06, }; const PylithScalar pylith::materials::DruckerPrager3DElasticData::_elasticConsts[] = { 6.75000000e+10, 2.25000000e+10, 2.25000000e+10, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 2.25000000e+10, 6.75000000e+10, 2.25000000e+10, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 2.25000000e+10, 2.25000000e+10, 6.75000000e+10, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 4.50000000e+10, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 4.50000000e+10, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 4.50000000e+10, 8.64000000e+09, 2.88000000e+09, 2.88000000e+09, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 2.88000000e+09, 8.64000000e+09, 2.88000000e+09, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 2.88000000e+09, 2.88000000e+09, 8.64000000e+09, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 5.76000000e+09, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 5.76000000e+09, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 5.76000000e+09, }; const PylithScalar pylith::materials::DruckerPrager3DElasticData::_initialStress[] = { 2.10000000e+04, 2.20000000e+04, 2.30000000e+04, 2.40000000e+04, 2.50000000e+04, 2.60000000e+04, 5.10000000e+04, 5.20000000e+04, 5.30000000e+04, 5.40000000e+04, 5.50000000e+04, 5.60000000e+04, }; const PylithScalar pylith::materials::DruckerPrager3DElasticData::_initialStrain[] = { 3.10000000e-04, 3.20000000e-04, 3.30000000e-04, 3.40000000e-04, 3.50000000e-04, 3.60000000e-04, 6.10000000e-04, 6.20000000e-04, 6.30000000e-04, 6.40000000e-04, 6.50000000e-04, 6.60000000e-04, }; const PylithScalar pylith::materials::DruckerPrager3DElasticData::_stateVarsUpdated[] = { 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, }; pylith::materials::DruckerPrager3DElasticData::DruckerPrager3DElasticData(void) { // constructor dimension = _dimension; numLocs = _numLocs; numProperties = _numProperties; numStateVars = _numStateVars; numDBProperties = _numDBProperties; numDBStateVars = _numDBStateVars; numPropsQuadPt = _numPropsQuadPt; numVarsQuadPt = _numVarsQuadPt; lengthScale = _lengthScale; timeScale = _timeScale; pressureScale = _pressureScale; densityScale = _densityScale; dtStableImplicit = _dtStableImplicit; dtStableExplicit = _dtStableExplicit; numPropertyValues = const_cast<int*>(_numPropertyValues); numStateVarValues = const_cast<int*>(_numStateVarValues); dbPropertyValues = const_cast<char**>(_dbPropertyValues); dbStateVarValues = const_cast<char**>(_dbStateVarValues); dbProperties = const_cast<PylithScalar*>(_dbProperties); dbStateVars = const_cast<PylithScalar*>(_dbStateVars); properties = const_cast<PylithScalar*>(_properties); stateVars = const_cast<PylithScalar*>(_stateVars); propertiesNondim = const_cast<PylithScalar*>(_propertiesNondim); stateVarsNondim = const_cast<PylithScalar*>(_stateVarsNondim); density = const_cast<PylithScalar*>(_density); strain = const_cast<PylithScalar*>(_strain); stress = const_cast<PylithScalar*>(_stress); elasticConsts = const_cast<PylithScalar*>(_elasticConsts); initialStress = const_cast<PylithScalar*>(_initialStress); initialStrain = const_cast<PylithScalar*>(_initialStrain); stateVarsUpdated = const_cast<PylithScalar*>(_stateVarsUpdated); } // constructor pylith::materials::DruckerPrager3DElasticData::~DruckerPrager3DElasticData(void) {} // End of file
24.442935
103
0.722179
Grant-Block
b77104c671b2196abd39c3d53f1fea5c1d4a0e7b
5,824
cpp
C++
features/netsocket/emac-drivers/TARGET_UNISOC_EMAC/uwpWiFiInterface.cpp
caixue901102/mbed-os
483833a8d4612845408fea5b1986d20ab8428580
[ "Apache-2.0" ]
null
null
null
features/netsocket/emac-drivers/TARGET_UNISOC_EMAC/uwpWiFiInterface.cpp
caixue901102/mbed-os
483833a8d4612845408fea5b1986d20ab8428580
[ "Apache-2.0" ]
null
null
null
features/netsocket/emac-drivers/TARGET_UNISOC_EMAC/uwpWiFiInterface.cpp
caixue901102/mbed-os
483833a8d4612845408fea5b1986d20ab8428580
[ "Apache-2.0" ]
4
2018-12-10T12:03:54.000Z
2019-01-26T02:46:40.000Z
/* LWIP implementation of NetworkInterfaceAPI * Copyright (c) 2015 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "WiFiInterface.h" #include "uwpWiFiInterface.h" #include "nsapi_types.h" #include "uwp_emac.h" #include "uwp_wifi_cmdevt.h" #include "uwp_wifi_api.h" /* Interface implementation */ //WiFiInterface::WiFiInterface(EMAC &emac, OnboardNetworkStack &stack) : //{ //} //RDAWiFiInterface *RDAWiFiInterface::get_target_default_instance() //{ // static RDAWiFiInterface wifinet; // return wifinet; //} nsapi_error_t UWPWiFiInterface::set_channel(uint8_t channel) { #if 0 int ret= 0; init(); if (channel > 13) return NSAPI_ERROR_PARAMETER; if (channel == 0){ _channel = 0; return NSAPI_ERROR_OK; } ret = rda5981_set_channel(channel); if (ret == 0) { _channel = channel; return NSAPI_ERROR_OK; } else return NSAPI_ERROR_TIMEOUT; #endif printf("%s\r\n",__func__); return NSAPI_ERROR_OK; } int8_t UWPWiFiInterface::get_rssi() { #if 0 return rda5981_get_rssi(); #endif printf("%s\r\n",__func__); return 0; } nsapi_error_t UWPWiFiInterface::init() { #if 1 if (!_interface) { if (!_emac.power_up()) { printf("power up failed!\n"); } int ret = uwp_mgmt_open(); if(ret != 0) printf("wifi open failed\r\n"); nsapi_error_t err = _stack.add_ethernet_interface(_emac, true, &_interface); if (err != NSAPI_ERROR_OK) { _interface = NULL; return err; } _interface->attach(_connection_status_cb); } #endif return NSAPI_ERROR_OK; } // TODO:need confirm nsapi_error_t UWPWiFiInterface::set_credentials(const char *ssid, const char *pass, nsapi_security_t security) { if(ssid == 0 || strlen(ssid) == 0) return NSAPI_ERROR_PARAMETER; if(security != NSAPI_SECURITY_NONE && (pass == 0 || strlen(pass) == 0)) return NSAPI_ERROR_PARAMETER; if(strlen(ssid) > 32 || strlen(pass) > 63) return NSAPI_ERROR_PARAMETER; memcpy((void*)_ssid, (void*)ssid, strlen(ssid)); _ssid[strlen(ssid)] = '\0'; memcpy((void*)_pass, (void*)pass, strlen(pass)); _pass[strlen(pass)] = '\0'; _security = security; return NSAPI_ERROR_OK; } nsapi_error_t UWPWiFiInterface::connect(const char *ssid, const char *pass, nsapi_security_t security, uint8_t channel) { int ret; bool find = false; int retry_count = 4; printf("%s\r\n",__func__); if (ssid == NULL || ssid[0] == 0) { return NSAPI_ERROR_PARAMETER; } init(); /*because cp will check whether there is a "ssid" in scan_result list, if not the connect cmd will return an error. */ if (uwp_mgmt_scan_result_name(ssid) == false) { uwp_mgmt_scan(0, 0, NULL); if(uwp_mgmt_scan_result_name(ssid) == false) { while(retry_count-- > 0) { //maybe it's a hidden ssid, transfer ssid to probe it. uwp_mgmt_scan(0, 0, ssid); if(uwp_mgmt_scan_result_name(ssid) == true) { find = true; break; } } } else find = true; } else find = true; if (!find) { printf("no %s cached in scan result list!\r\n", ssid); return NSAPI_ERROR_NO_SSID; } ret = uwp_mgmt_connect(ssid,pass,channel); if (ret) { printf("uwp_mgmt_connect failed:%d\n", ret); return ret; } osDelay(300); ret = _interface->bringup(_dhcp, _ip_address[0] ? _ip_address : 0, _netmask[0] ? _netmask : 0, _gateway[0] ? _gateway : 0, DEFAULT_STACK, _blocking); if (ret == NSAPI_ERROR_DHCP_FAILURE) ret = NSAPI_ERROR_CONNECTION_TIMEOUT; return ret; } nsapi_error_t UWPWiFiInterface::connect() { printf("%s\r\n",__func__); return connect(_ssid, _pass, _security, _channel); } // TODO: return value nsapi_error_t UWPWiFiInterface::disconnect() { #if 0 rda_msg msg; if(sta_state < 2) return NSAPI_ERROR_NO_CONNECTION; init(); msg.type = WLAND_DISCONNECT; rda_mail_put(wland_msgQ, (void*)&msg, osWaitForever); if (_interface) { return _interface->bringdown(); } #endif printf("%s\r\n",__func__); int ret = uwp_mgmt_disconnect(); if(_interface) return _interface->bringdown(); } // TODO: only test scan nsapi_size_or_error_t UWPWiFiInterface::scan(WiFiAccessPoint *res, nsapi_size_t count) { int ret; init(); ret = uwp_mgmt_scan(0, 0, NULL); struct event_scan_result *bss = (struct event_scan_result *)malloc(ret * sizeof(struct event_scan_result)); if(bss == NULL) return NSAPI_ERROR_NO_MEMORY; memset(bss, 0, ret * sizeof(struct event_scan_result)); uwp_mgmt_get_scan_result(bss, ret); for(int i=0; i<ret; i++){ printf("%-32s %-10s %-2d %02x:%02x:%02x:%02x:%02x:%02x\r\n", bss[i].ssid, security2str(bss[i].encrypt_mode), bss[i].rssi, (bss[i].bssid)[0],(bss[i].bssid)[1],(bss[i].bssid)[2], (bss[i].bssid)[3],(bss[i].bssid)[4],(bss[i].bssid)[5]); } free(bss); return 0; } WiFiInterface *WiFiInterface::get_default_instance() { static UWPWiFiInterface wifinet; return &wifinet; }
26.83871
111
0.6341
caixue901102
b773841f0caf6dd398eed65387790391a6b1b77a
3,232
cpp
C++
Library/Calculator.cpp
SosnovGennadiy2006/cppEvalFunction
548071bdab0ac9097a0cbbb12f9c55886ce0b757
[ "MIT" ]
null
null
null
Library/Calculator.cpp
SosnovGennadiy2006/cppEvalFunction
548071bdab0ac9097a0cbbb12f9c55886ce0b757
[ "MIT" ]
null
null
null
Library/Calculator.cpp
SosnovGennadiy2006/cppEvalFunction
548071bdab0ac9097a0cbbb12f9c55886ce0b757
[ "MIT" ]
null
null
null
#include "Calculator.h" Calculator::Calculator() { this->expression = ""; } Calculator::Calculator(const std::string &exp) { this->expression = exp; } double Calculator::Solve() { return SolveFromExpression(this->expression); } double Calculator::SolveOperation(const std::string &s) { std::string number1 = "", number2 = ""; char _operator = 'n'; bool flag = true; for (size_t i = 0; i < s.length(); i++) { if (isdigit(s[i]) || s[i] == '.') { if (flag) { number1 += s[i]; } else { number2 += s[i]; } } else if(s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') { _operator = s[i]; flag = false; } } switch (_operator) { case '+': return atof(number1.c_str()) + atof(number2.c_str()); case '-': return atof(number1.c_str()) - atof(number2.c_str()); case '*': return atof(number1.c_str()) * atof(number2.c_str()); case '/': return atof(number1.c_str()) / atof(number2.c_str()); default: return 0; } } double Calculator::SolveFromExpression(std::string exp) { size_t pos = exp.find('^'); while (pos != std::string::npos) { exp.replace(pos, 1, "**"); pos = exp.find('^'); } std::smatch _match; while (std::regex_search(exp, _match, std::regex("[(][^)(]+[)]"), \ std::regex_constants::match_default)) { std::string elem = _match.str(); elem = elem.substr(1, elem.length() - 2); exp = _match.prefix().str() + \ std::to_string(SolveFromExpression(elem)) \ + _match.suffix().str(); } while (std::regex_search(exp, _match, \ std::regex("([0-9]|[.])+[!]"), \ std::regex_constants::match_default)) { std::string elem = _match.str(); double number = atof(elem.c_str()); exp = _match.prefix().str() + \ std::to_string(factorial(number)) \ + _match.suffix().str(); } while (std::regex_search(exp, _match, \ std::regex("([0-9]|[.])+[*][*]([0-9]|[.])+"), \ std::regex_constants::match_default)) { std::string elem = _match.str(); std::string number1 = "", number2 = ""; bool flag = true; for (auto item : elem) { if (isdigit(item) || item == '.') { if (flag) { number1 += item; } else { number2 += item; } } else if(item != ' ') { flag = false; } } exp = _match.prefix().str() + \ std::to_string(pow(atof(number1.c_str()), atof(number2.c_str()))) \ + _match.suffix().str(); } SolveOperators(std::string("/*"), exp); SolveOperators(std::string("+-"), exp); return atof(exp.c_str()); } void Calculator::SolveOperators(const std::string& operators, std::string &exp) { std::smatch _match; while (std::regex_search(exp, _match, \ std::regex("([0-9]|[.])+[" + operators + "]([0-9]|[.])+") , \ std::regex_constants::match_default)) { std::string elem = _match.str(); exp = _match.prefix().str() + \ std::to_string(SolveOperation(elem)) + _match.suffix().str(); } } void Calculator::setExpression(const std::string& exp) { this->expression = exp; } std::string Calculator::getExpression() const { return this->expression; } unsigned long long Calculator::factorial(unsigned short int number) { unsigned long long Ans = 1; for (unsigned short int i = 1; i <= number; i++) { Ans *= i; } return Ans; }
19.950617
79
0.581374
SosnovGennadiy2006
b773bee6933cda5dcd5403f1422959faeb6da2c8
636
cpp
C++
editDistance.cpp
anishmo99/DailyInterviewPro
d8724e8feec558ab1882d22c9ca63b850b767753
[ "MIT" ]
1
2020-08-09T07:07:53.000Z
2020-08-09T07:07:53.000Z
editDistance.cpp
anishmo99/DailyInterviewPro
d8724e8feec558ab1882d22c9ca63b850b767753
[ "MIT" ]
null
null
null
editDistance.cpp
anishmo99/DailyInterviewPro
d8724e8feec558ab1882d22c9ca63b850b767753
[ "MIT" ]
1
2020-06-06T20:56:33.000Z
2020-06-06T20:56:33.000Z
class Solution { public: int minDistance(string s1, string s2) { int m=s1.length(),n=s2.length(); int dp[m+1][n+1]; for(int i=0;i<=m;i++) { for(int j=0;j<=n;j++) { if(i==0) dp[i][j]=j; else if(j==0) dp[i][j]=i; else if(s1[i-1]==s2[j-1]) dp[i][j]=dp[i-1][j-1]; else dp[i][j]=1+min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1])); } } return dp[m][n]; } };
23.555556
76
0.295597
anishmo99
b775356f31220f50c749b7302d4af49dd8e5ea54
3,311
cpp
C++
ListaClientes.cpp
psicobloc/dataStructuresII
01f494ed3091e54f9b2a587a66f255be2f079339
[ "MIT" ]
null
null
null
ListaClientes.cpp
psicobloc/dataStructuresII
01f494ed3091e54f9b2a587a66f255be2f079339
[ "MIT" ]
null
null
null
ListaClientes.cpp
psicobloc/dataStructuresII
01f494ed3091e54f9b2a587a66f255be2f079339
[ "MIT" ]
null
null
null
// Created by Hugo. #include "ListaClientes.h" using namespace std; ListaClientes::ListaClientes() { if ((header = new NodoCliente) == nullptr) //creando header { cout << "exception, constructor ListaClientes" << endl; } header->setPrev(header); header->setNext(header); } ListaClientes::ListaClientes(ListaClientes &lista) : ListaClientes() { copyAll(lista); } ListaClientes::~ListaClientes() { deleteAll(); delete header; } bool ListaClientes::isEmpty() { return header->getNext() == header; } bool ListaClientes::isValidPos(NodoCliente *nodo) { NodoCliente *aux(header->getNext()); while (aux != header) { if (aux == nodo) { return true; } aux = aux->getNext(); } return false; } void ListaClientes::insertData(NodoCliente *prevNode, Cliente &clnt) { if (prevNode != nullptr and !isValidPos(prevNode)) { cout << "posicion invalida, insert clientes" << endl; } NodoCliente* aux(nullptr); aux = new NodoCliente(clnt); if (prevNode == nullptr) { prevNode = header; } cout << "insert data .. " << aux->getData().toString() << endl; aux->setPrev(prevNode); aux->setNext(prevNode->getNext()); prevNode->getNext()->setPrev(aux); prevNode->setNext(aux); } void ListaClientes::copyAll(ListaClientes &lst) { NodoCliente *aux(lst.header->getNext()); NodoCliente *newNode; while (aux != lst.header) { if ((newNode = new NodoCliente(aux->getData())) == nullptr) { cout << "excepcion, ListaClientes copyAll" << endl; } newNode->setPrev(header->getPrev()); //** neWnode->setprev() newNode->setNext(header); header->getPrev()->setNext(newNode); header->setPrev(newNode); aux = aux->getNext(); } } void ListaClientes::deleteData(NodoCliente *nodoEliminar) { nodoEliminar->getPrev()->setNext(nodoEliminar->getNext()); nodoEliminar->getNext()->setPrev(nodoEliminar->getPrev()); delete nodoEliminar; } void ListaClientes::deleteAll() { NodoCliente *aux(nullptr); while (header->getNext() != header) { aux = header->getNext(); header->setNext(aux->getNext()); delete aux; } header->setPrev(header); } NodoCliente *ListaClientes::getLastPos() { if (isEmpty()) { return nullptr; } return header->getPrev(); } NodoCliente *ListaClientes::findData(Cliente &clnt) { NodoCliente *aux(header->getNext()); while (aux != header) { if (aux->getData() == clnt) { return aux; } aux = aux->getNext(); } return nullptr; } Cliente &ListaClientes::retrieve(NodoCliente *nodo) { if (!isValidPos(nodo)) { cout << "Posicion invalida, intentando recuperar de lista de Productos" << endl; } return nodo->getData(); } std::string ListaClientes::toString() { NodoCliente* aux(header->getNext()); string result; while (aux != header) { result += aux->getData().toString() + "\n\n"; aux = aux->getNext(); } return result; } ListaClientes &ListaClientes::operator=(ListaClientes &list) { deleteAll(); copyAll(list); return *this; }
19.708333
88
0.597403
psicobloc
b7777dc3e401af320b7d119684b1266e5867a9d8
288
cc
C++
042. Multiply Strings/TEST.cc
corkiwang1122/LeetCode
39b1680b58173e6ec23a475605c3450ce8f78a81
[ "MIT" ]
3,690
2015-01-03T03:40:23.000Z
2022-03-31T08:10:19.000Z
042. Multiply Strings/TEST.cc
Windfall94/LeetCode
1756256d7e619164076bbf358c8f7ca68cd8bd79
[ "MIT" ]
21
2015-01-25T16:39:43.000Z
2021-02-26T05:28:22.000Z
042. Multiply Strings/TEST.cc
Windfall94/LeetCode
1756256d7e619164076bbf358c8f7ca68cd8bd79
[ "MIT" ]
1,290
2015-01-09T01:28:20.000Z
2022-03-28T12:20:39.000Z
#define CATCH_CONFIG_MAIN #include "../Catch/single_include/catch.hpp" #include "solution.h" TEST_CASE("Multiply Strings", "multiply") { Solution s; REQUIRE(s.multiply("123456", "789") == "97406784"); REQUIRE(s.multiply("123456789", "987654321") == "121932631112635269"); }
24
74
0.690972
corkiwang1122
b778adfcf7d3ab6d428304f8db799fe0d8151954
219
cc
C++
cpp/others/open_img.cc
Incipe-win/opencv
b9a1f8958fa9e8007c11494a8eed3c813550896f
[ "Apache-2.0" ]
1
2021-07-14T07:42:07.000Z
2021-07-14T07:42:07.000Z
cpp/others/open_img.cc
Incipe-win/opencv
b9a1f8958fa9e8007c11494a8eed3c813550896f
[ "Apache-2.0" ]
null
null
null
cpp/others/open_img.cc
Incipe-win/opencv
b9a1f8958fa9e8007c11494a8eed3c813550896f
[ "Apache-2.0" ]
null
null
null
#include <opencv2/opencv.hpp> using namespace cv; int main() { Mat img = cv::imread("./flower.jpg", 1); imshow("open a pic", img); int k = waitKey(0); if (k == 27) { destroyAllWindows(); } return 0; }
15.642857
42
0.584475
Incipe-win
b778e069dbbad5b352c9ae66f6512e2c87046021
12,612
cpp
C++
src/extern/inventor/lib/database/src/so/engines/SoCompose.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
2
2020-05-21T07:06:07.000Z
2021-06-28T02:14:34.000Z
src/extern/inventor/lib/database/src/so/engines/SoCompose.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
null
null
null
src/extern/inventor/lib/database/src/so/engines/SoCompose.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
6
2016-03-21T19:53:18.000Z
2021-06-08T18:06:03.000Z
/* * * Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy, * Mountain View, CA 94043, or: * * http://www.sgi.com * * For further information regarding this notice, see: * * http://oss.sgi.com/projects/GenInfo/NoticeExplan/ * */ /* * Copyright (C) 1990,91 Silicon Graphics, Inc. * _______________________________________________________________________ ______________ S I L I C O N G R A P H I C S I N C . ____________ | | $Revision: 1.1.1.1 $ | | Classes: | SoComposeVec3f | | Author(s) : Ronen Barzel | ______________ S I L I C O N G R A P H I C S I N C . ____________ _______________________________________________________________________ */ #include <Inventor/engines/SoCompose.h> #include "SoEngineUtil.h" ////////////////// // // Utility macro defines basic source for composition/decomposition // engines // #define SO_COMPOSE__SOURCE(Name) \ SO_ENGINE_SOURCE(Name); \ Name::~Name() { } //////////////////////////////////////////////////////////////////////// // // Source for SoComposeVec2f // SO_COMPOSE__SOURCE(SoComposeVec2f); SoComposeVec2f::SoComposeVec2f() { SO_ENGINE_CONSTRUCTOR(SoComposeVec2f); SO_ENGINE_ADD_INPUT(x, (0.0)); SO_ENGINE_ADD_INPUT(y, (0.0)); SO_ENGINE_ADD_OUTPUT(vector, SoMFVec2f); isBuiltIn = TRUE; } void SoComposeVec2f::evaluate() { int nx = x.getNum(); int ny = y.getNum(); int nout = max(nx,ny); SO_ENGINE_OUTPUT(vector, SoMFVec2f, setNum(nout)); for (int i=0; i<nout; i++) { float vx = x[clamp(i,nx)]; float vy = y[clamp(i,ny)]; SO_ENGINE_OUTPUT(vector, SoMFVec2f, set1Value(i, vx, vy)); } } //////////////////////////////////////////////////////////////////////// // // Source for SoComposeVec3f // SO_COMPOSE__SOURCE(SoComposeVec3f); SoComposeVec3f::SoComposeVec3f() { SO_ENGINE_CONSTRUCTOR(SoComposeVec3f); SO_ENGINE_ADD_INPUT(x, (0.0)); SO_ENGINE_ADD_INPUT(y, (0.0)); SO_ENGINE_ADD_INPUT(z, (0.0)); SO_ENGINE_ADD_OUTPUT(vector, SoMFVec3f); isBuiltIn = TRUE; } void SoComposeVec3f::evaluate() { int nx = x.getNum(); int ny = y.getNum(); int nz = z.getNum(); int nout=max(nx,ny,nz); SO_ENGINE_OUTPUT(vector, SoMFVec3f, setNum(nout)); for (int i=0; i<nout; i++) { float vx = x[clamp(i,nx)]; float vy = y[clamp(i,ny)]; float vz = z[clamp(i,nz)]; SO_ENGINE_OUTPUT(vector, SoMFVec3f, set1Value(i, vx, vy, vz)); } } //////////////////////////////////////////////////////////////////////// // // Source for SoComposeVec4f // SO_COMPOSE__SOURCE(SoComposeVec4f); SoComposeVec4f::SoComposeVec4f() { SO_ENGINE_CONSTRUCTOR(SoComposeVec4f); SO_ENGINE_ADD_INPUT(x, (0.0)); SO_ENGINE_ADD_INPUT(y, (0.0)); SO_ENGINE_ADD_INPUT(z, (0.0)); SO_ENGINE_ADD_INPUT(w, (0.0)); SO_ENGINE_ADD_OUTPUT(vector, SoMFVec4f); isBuiltIn = TRUE; } void SoComposeVec4f::evaluate() { int nx = x.getNum(); int ny = y.getNum(); int nz = z.getNum(); int nw = w.getNum(); int nout=max(nx,ny,nz,nw); SO_ENGINE_OUTPUT(vector, SoMFVec4f, setNum(nout)); for (int i=0; i<nout; i++) { float vx = x[clamp(i,nx)]; float vy = y[clamp(i,ny)]; float vz = z[clamp(i,nz)]; float vw = w[clamp(i,nw)]; SO_ENGINE_OUTPUT(vector, SoMFVec4f, set1Value(i, vx, vy, vz, vw)); } } //////////////////////////////////////////////////////////////////////// // // Source for SoDecomposeVec2f // SO_COMPOSE__SOURCE(SoDecomposeVec2f); SoDecomposeVec2f::SoDecomposeVec2f() { SO_ENGINE_CONSTRUCTOR(SoDecomposeVec2f); SO_ENGINE_ADD_INPUT(vector, (SbVec2f(0,0))); SO_ENGINE_ADD_OUTPUT(x, SoMFFloat); SO_ENGINE_ADD_OUTPUT(y, SoMFFloat); isBuiltIn = TRUE; } void SoDecomposeVec2f::evaluate() { int nout=vector.getNum(); SO_ENGINE_OUTPUT(x, SoMFFloat, setNum(nout)); SO_ENGINE_OUTPUT(y, SoMFFloat, setNum(nout)); for (int i=0; i<nout; i++) { SO_ENGINE_OUTPUT(x, SoMFFloat, set1Value(i,vector[i][0])); SO_ENGINE_OUTPUT(y, SoMFFloat, set1Value(i,vector[i][1])); } } //////////////////////////////////////////////////////////////////////// // // Source for SoDecomposeVec3f // SO_COMPOSE__SOURCE(SoDecomposeVec3f); SoDecomposeVec3f::SoDecomposeVec3f() { SO_ENGINE_CONSTRUCTOR(SoDecomposeVec3f); SO_ENGINE_ADD_INPUT(vector, (SbVec3f(0,0,0))); SO_ENGINE_ADD_OUTPUT(x, SoMFFloat); SO_ENGINE_ADD_OUTPUT(y, SoMFFloat); SO_ENGINE_ADD_OUTPUT(z, SoMFFloat); isBuiltIn = TRUE; } void SoDecomposeVec3f::evaluate() { int nout=vector.getNum(); SO_ENGINE_OUTPUT(x, SoMFFloat, setNum(nout)); SO_ENGINE_OUTPUT(y, SoMFFloat, setNum(nout)); SO_ENGINE_OUTPUT(z, SoMFFloat, setNum(nout)); for (int i=0; i<nout; i++) { SO_ENGINE_OUTPUT(x, SoMFFloat, set1Value(i,vector[i][0])); SO_ENGINE_OUTPUT(y, SoMFFloat, set1Value(i,vector[i][1])); SO_ENGINE_OUTPUT(z, SoMFFloat, set1Value(i,vector[i][2])); } } //////////////////////////////////////////////////////////////////////// // // Source for SoDecomposeVec4f // SO_COMPOSE__SOURCE(SoDecomposeVec4f); SoDecomposeVec4f::SoDecomposeVec4f() { SO_ENGINE_CONSTRUCTOR(SoDecomposeVec4f); SO_ENGINE_ADD_INPUT(vector, (SbVec4f(0,0,0,0))); SO_ENGINE_ADD_OUTPUT(x, SoMFFloat); SO_ENGINE_ADD_OUTPUT(y, SoMFFloat); SO_ENGINE_ADD_OUTPUT(z, SoMFFloat); SO_ENGINE_ADD_OUTPUT(w, SoMFFloat); isBuiltIn = TRUE; } void SoDecomposeVec4f::evaluate() { int nout=vector.getNum(); SO_ENGINE_OUTPUT(x, SoMFFloat, setNum(nout)); SO_ENGINE_OUTPUT(y, SoMFFloat, setNum(nout)); SO_ENGINE_OUTPUT(z, SoMFFloat, setNum(nout)); SO_ENGINE_OUTPUT(w, SoMFFloat, setNum(nout)); for (int i=0; i<nout; i++) { SO_ENGINE_OUTPUT(x, SoMFFloat, set1Value(i,vector[i][0])); SO_ENGINE_OUTPUT(y, SoMFFloat, set1Value(i,vector[i][1])); SO_ENGINE_OUTPUT(z, SoMFFloat, set1Value(i,vector[i][2])); SO_ENGINE_OUTPUT(w, SoMFFloat, set1Value(i,vector[i][3])); } } //////////////////////////////////////////////////////////////////////// // // Source for SoComposeRotation // SO_COMPOSE__SOURCE(SoComposeRotation); SoComposeRotation::SoComposeRotation() { SO_ENGINE_CONSTRUCTOR(SoComposeRotation); SO_ENGINE_ADD_INPUT(axis, (SbVec3f(0,0,1))); SO_ENGINE_ADD_INPUT(angle, (0.0)); SO_ENGINE_ADD_OUTPUT(rotation, SoMFRotation); isBuiltIn = TRUE; } void SoComposeRotation::evaluate() { int naxis = axis.getNum(); int nangle = angle.getNum(); int nout=max(naxis,nangle); SO_ENGINE_OUTPUT(rotation, SoMFRotation, setNum(nout)); for (int i=0; i<nout; i++) { SbVec3f vaxis = axis[clamp(i,naxis)]; float vangle = angle[clamp(i,nangle)]; SO_ENGINE_OUTPUT(rotation, SoMFRotation, set1Value(i, vaxis, vangle)); } } //////////////////////////////////////////////////////////////////////// // // Source for SoComposeRotationFromTo // SO_COMPOSE__SOURCE(SoComposeRotationFromTo); SoComposeRotationFromTo::SoComposeRotationFromTo() { SO_ENGINE_CONSTRUCTOR(SoComposeRotationFromTo); SO_ENGINE_ADD_INPUT(from, (SbVec3f(0,0,1))); SO_ENGINE_ADD_INPUT(to, (SbVec3f(0,0,1))); SO_ENGINE_ADD_OUTPUT(rotation, SoMFRotation); isBuiltIn = TRUE; } void SoComposeRotationFromTo::evaluate() { int nfrom = from.getNum(); int nto = to.getNum(); int nout=max(nfrom,nto); SO_ENGINE_OUTPUT(rotation, SoMFRotation, setNum(nout)); for (int i=0; i<nout; i++) { SbVec3f vfrom = from[clamp(i,nfrom)]; SbVec3f vto = to[clamp(i,nto)]; SO_ENGINE_OUTPUT(rotation, SoMFRotation, set1Value(i, SbRotation(vfrom, vto))); } } //////////////////////////////////////////////////////////////////////// // // Source for SoDecomposeRotation // SO_COMPOSE__SOURCE(SoDecomposeRotation); SoDecomposeRotation::SoDecomposeRotation() { SO_ENGINE_CONSTRUCTOR(SoDecomposeRotation); SO_ENGINE_ADD_INPUT(rotation, (SbRotation::identity())); SO_ENGINE_ADD_OUTPUT(axis, SoMFVec3f); SO_ENGINE_ADD_OUTPUT(angle, SoMFFloat); isBuiltIn = TRUE; } void SoDecomposeRotation::evaluate() { int nout=rotation.getNum(); SO_ENGINE_OUTPUT(axis, SoMFVec3f, setNum(nout)); SO_ENGINE_OUTPUT(angle, SoMFFloat, setNum(nout)); for (int i=0; i<nout; i++) { SbVec3f vaxis; float vangle; rotation[i].getValue(vaxis, vangle); SO_ENGINE_OUTPUT(axis, SoMFVec3f, set1Value(i,vaxis)); SO_ENGINE_OUTPUT(angle, SoMFFloat, set1Value(i,vangle)); } } //////////////////////////////////////////////////////////////////////// // // Source for SoComposeMatrix // SO_COMPOSE__SOURCE(SoComposeMatrix); SoComposeMatrix::SoComposeMatrix() { SO_ENGINE_CONSTRUCTOR(SoComposeMatrix); SO_ENGINE_ADD_INPUT(translation, (SbVec3f(0,0,0))); SO_ENGINE_ADD_INPUT(rotation, (SbRotation::identity())); SO_ENGINE_ADD_INPUT(scaleFactor, (SbVec3f(1,1,1))); SO_ENGINE_ADD_INPUT(scaleOrientation,(SbRotation::identity())); SO_ENGINE_ADD_INPUT(center, (SbVec3f(0,0,0))); SO_ENGINE_ADD_OUTPUT(matrix, SoMFMatrix); isBuiltIn = TRUE; } void SoComposeMatrix::evaluate() { int ntranslation = translation.getNum(); int nrotation = rotation.getNum(); int nscaleFactor = scaleFactor.getNum(); int nscaleOrientation = scaleOrientation.getNum(); int ncenter = center.getNum(); int nout=max(ntranslation,nrotation,nscaleFactor,nscaleOrientation,ncenter); SO_ENGINE_OUTPUT(matrix, SoMFMatrix, setNum(nout)); for (int i=0; i<nout; i++) { SbVec3f vtrans = translation[clamp(i,ntranslation)]; SbRotation vrot = rotation[clamp(i,nrotation)]; SbVec3f vscale = scaleFactor[clamp(i,nscaleFactor)]; SbRotation vscaleO = scaleOrientation[clamp(i,nscaleOrientation)]; SbVec3f vcenter = center[clamp(i,ncenter)]; SbMatrix m; m.setTransform(vtrans, vrot, vscale, vscaleO, vcenter); SO_ENGINE_OUTPUT(matrix, SoMFMatrix, set1Value(i, m)); } } //////////////////////////////////////////////////////////////////////// // // Source for SoDecomposeMatrix // SO_COMPOSE__SOURCE(SoDecomposeMatrix); SoDecomposeMatrix::SoDecomposeMatrix() { SO_ENGINE_CONSTRUCTOR(SoDecomposeMatrix); SO_ENGINE_ADD_INPUT(matrix, (SbMatrix::identity())); SO_ENGINE_ADD_INPUT(center, (SbVec3f(0,0,0))); SO_ENGINE_ADD_OUTPUT(translation, SoMFVec3f); SO_ENGINE_ADD_OUTPUT(rotation, SoMFRotation); SO_ENGINE_ADD_OUTPUT(scaleFactor, SoMFVec3f); SO_ENGINE_ADD_OUTPUT(scaleOrientation, SoMFRotation); isBuiltIn = TRUE; } void SoDecomposeMatrix::evaluate() { int nmatrix = matrix.getNum(); int ncenter = center.getNum(); int nout=max(nmatrix,ncenter); SO_ENGINE_OUTPUT(translation, SoMFVec3f, setNum(nout)); SO_ENGINE_OUTPUT(rotation, SoMFRotation, setNum(nout)); SO_ENGINE_OUTPUT(scaleFactor, SoMFVec3f, setNum(nout)); SO_ENGINE_OUTPUT(scaleOrientation, SoMFRotation, setNum(nout)); for (int i=0; i<nout; i++) { SbVec3f trans; SbRotation rot; SbVec3f scale; SbRotation scaleO; SbVec3f vcenter = center[clamp(i,ncenter)]; SbMatrix vmatrix = matrix[clamp(i,nmatrix)]; vmatrix.getTransform(trans, rot, scale, scaleO, vcenter); SO_ENGINE_OUTPUT(translation, SoMFVec3f, set1Value(i, trans)); SO_ENGINE_OUTPUT(rotation, SoMFRotation, set1Value(i, rot)); SO_ENGINE_OUTPUT(scaleFactor, SoMFVec3f, set1Value(i, scale)); SO_ENGINE_OUTPUT(scaleOrientation, SoMFRotation, set1Value(i, scaleO)); } }
29.127021
80
0.660006
OpenXIP
b77aca1fd6485a14df48ba50d7967575c7478b9d
1,226
cpp
C++
Thread/ThreadPool.cpp
ReliaSolve/acl
a0b305e7bf6a2d86839fb6f00d7d8fbf2bd583b9
[ "MIT" ]
null
null
null
Thread/ThreadPool.cpp
ReliaSolve/acl
a0b305e7bf6a2d86839fb6f00d7d8fbf2bd583b9
[ "MIT" ]
null
null
null
Thread/ThreadPool.cpp
ReliaSolve/acl
a0b305e7bf6a2d86839fb6f00d7d8fbf2bd583b9
[ "MIT" ]
null
null
null
/** * \copyright Copyright 2021 Aqueti, Inc. All rights reserved. * \license This project is released under the MIT Public License. **/ /** * \file ThreadPool.cpp **/ #include "ThreadPool.h" namespace acl { /** * \brief initializes the thread pool * * \param [in] numThreads the number of threads * \param [in] maxJobLength the maximum number of jobs that can be submitted * \param [in] timeout the time a thread should process before moving on **/ ThreadPool::ThreadPool(int numThreads, int maxJobLength, double timeout): MultiThread(numThreads), TSQueue<std::function<void()>>() { set_max_size(maxJobLength); m_timeout = timeout; } /** * \brief adds jobs to the pool * * \param [in] f the job to be added * \return true if the job has been successfully enqueued **/ bool ThreadPool::push_job(std::function<void()> f) { return enqueue(f); } /** * \brief main function to loop through the queue and run jobs **/ void ThreadPool::mainLoop() { std::function<void()> f; if (dequeue(f, m_timeout) && f) { f(); } } /** * \brief sets the timeout value * * \param [in] timeout the timeout value to be set **/ void ThreadPool::setTimeout(double timeout) { m_timeout = timeout; } }
20.433333
131
0.677814
ReliaSolve
b77afe8b34309b0172477a8b8841fa95a17d3724
186,235
cpp
C++
test/unittest/DatabaseQueue/DatabaseQueueTests.cpp
eProsima/Fast-DDS-statistics-backend
fd54801ee35c45bd758d2fb01197e3b999aa24f7
[ "Apache-2.0" ]
11
2021-03-31T13:54:12.000Z
2022-02-22T08:28:05.000Z
test/unittest/DatabaseQueue/DatabaseQueueTests.cpp
AhmedMounir/Fast-DDS-statistics-backend
4c119e7757ba180666deb9d0651f35203f0e8690
[ "Apache-2.0" ]
124
2021-03-22T12:13:26.000Z
2022-03-24T13:28:25.000Z
test/unittest/DatabaseQueue/DatabaseQueueTests.cpp
AhmedMounir/Fast-DDS-statistics-backend
4c119e7757ba180666deb9d0651f35203f0e8690
[ "Apache-2.0" ]
1
2021-12-17T18:14:34.000Z
2021-12-17T18:14:34.000Z
// Copyright 2021 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <functional> #include <gtest_aux.hpp> #include <gtest/gtest.h> #include <gmock/gmock.h> #include <database/database.hpp> #include <database/database_queue.hpp> #include <topic_types/types.h> using namespace eprosima::fastdds::statistics; using namespace eprosima::statistics_backend; using namespace eprosima::statistics_backend::database; using StatisticsData = eprosima::fastdds::statistics::Data; using ::testing::_; using ::testing::Invoke; using ::testing::Return; using ::testing::Throw; using ::testing::AnyNumber; // Wrapper class to expose the internal attributes of the queue class DatabaseEntityQueueWrapper : public DatabaseEntityQueue { public: DatabaseEntityQueueWrapper( Database* database) : DatabaseEntityQueue(database) { } const std::queue<queue_item_type> get_foreground_queue() { return *foreground_queue_; } const std::queue<queue_item_type> get_background_queue() { return *background_queue_; } void do_swap() { swap(); } /** * @brief Processes one sample and removes it from the front queue * * This is necessary to check exception handling on the consumer * Consumers must be stopped and the queues swapped manually * * @return true if anything was consumed */ bool consume_sample() { if (empty()) { return false; } process_sample(); pop(); return true; } }; // Wrapper class to expose the internal attributes of the queue class DatabaseDataQueueWrapper : public DatabaseDataQueue { public: DatabaseDataQueueWrapper( Database* database) : DatabaseDataQueue(database) { } const std::queue<queue_item_type> get_foreground_queue() { return *foreground_queue_; } const std::queue<queue_item_type> get_background_queue() { return *background_queue_; } void do_swap() { swap(); } /** * @brief Processes one sample and removes it from the front queue * * This is necessary to check exception handling on the consumer * Consumers must be stopped and the queues swapped manually * * @return true if anything was consumed */ bool consume_sample() { if (empty()) { return false; } process_sample(); pop(); return true; } void do_process_sample_type( EntityId& domain, EntityId& entity, EntityKind entity_kind, ByteToLocatorCountSample& sample, const StatisticsEntity2LocatorTraffic& item) const { process_sample_type<ByteToLocatorCountSample, StatisticsEntity2LocatorTraffic>( domain, entity, entity_kind, sample, item); } }; struct InsertDataArgs { InsertDataArgs ( std::function<void( const EntityId&, const EntityId&, const StatisticsSample&)> func) : callback_(func) { } void insert( const EntityId& domain_id, const EntityId& id, const StatisticsSample& sample) { return callback_(domain_id, id, sample); } std::function<void( const EntityId&, const EntityId&, const StatisticsSample&)> callback_; }; struct InsertEntityArgs { InsertEntityArgs ( std::function<EntityId(std::shared_ptr<Entity>)> func) : callback_(func) { } EntityId insert( std::shared_ptr<Entity> entity) { entity_ = entity; return callback_(entity); } std::function<EntityId(std::shared_ptr<Entity> entity)> callback_; std::shared_ptr<Entity> entity_; }; class database_queue_tests : public ::testing::Test { public: Database database; DatabaseEntityQueueWrapper entity_queue; DatabaseDataQueueWrapper data_queue; database_queue_tests() : entity_queue(&database) , data_queue(&database) { } }; TEST_F(database_queue_tests, start_stop_flush) { // Generate some data std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::shared_ptr<Host> host = std::make_shared<Host>("hostname"); std::shared_ptr<User> user = std::make_shared<User>("username", host); std::shared_ptr<Process> process = std::make_shared<Process>("processname", "1", user); // Add something to the stopped queue EXPECT_CALL(database, insert(_)).Times(0); EXPECT_TRUE(entity_queue.stop_consumer()); entity_queue.push(timestamp, {host, 0, details::StatisticsBackendData::DISCOVERY}); entity_queue.push(timestamp, {user, 0, details::StatisticsBackendData::DISCOVERY}); entity_queue.push(timestamp, {process, 0, details::StatisticsBackendData::DISCOVERY}); EXPECT_TRUE(entity_queue.get_foreground_queue().empty()); EXPECT_EQ(3, entity_queue.get_background_queue().size()); // Flushing a stopped queue does nothing EXPECT_CALL(database, insert(_)).Times(0); entity_queue.flush(); EXPECT_TRUE(entity_queue.get_foreground_queue().empty()); EXPECT_EQ(3, entity_queue.get_background_queue().size()); // Start the queue and flush EXPECT_CALL(database, insert(_)).Times(3); EXPECT_TRUE(entity_queue.start_consumer()); entity_queue.flush(); EXPECT_TRUE(entity_queue.get_foreground_queue().empty()); EXPECT_TRUE(entity_queue.get_background_queue().empty()); // Start the consumer when it is already started EXPECT_CALL(database, insert(_)).Times(0); EXPECT_FALSE(entity_queue.start_consumer()); EXPECT_TRUE(entity_queue.get_foreground_queue().empty()); EXPECT_TRUE(entity_queue.get_background_queue().empty()); // Flush on an empty queue with running consumer EXPECT_CALL(database, insert(_)).Times(0); entity_queue.flush(); EXPECT_TRUE(entity_queue.get_foreground_queue().empty()); EXPECT_TRUE(entity_queue.get_background_queue().empty()); // Flush on an empty queue with a stopped consumer EXPECT_TRUE(entity_queue.stop_consumer()); EXPECT_CALL(database, insert(_)).Times(0); entity_queue.flush(); EXPECT_TRUE(entity_queue.get_foreground_queue().empty()); EXPECT_TRUE(entity_queue.get_background_queue().empty()); // Stop the consumer when it is already stopped EXPECT_CALL(database, insert(_)).Times(0); EXPECT_FALSE(entity_queue.stop_consumer()); EXPECT_TRUE(entity_queue.get_foreground_queue().empty()); EXPECT_TRUE(entity_queue.get_background_queue().empty()); // Start the consumer with an empty queue EXPECT_CALL(database, insert(_)).Times(0); EXPECT_TRUE(entity_queue.start_consumer()); EXPECT_TRUE(entity_queue.get_foreground_queue().empty()); EXPECT_TRUE(entity_queue.get_background_queue().empty()); } TEST_F(database_queue_tests, push_host) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string hostname = "hostname"; // Create the entity hierarchy std::shared_ptr<Host> host = std::make_shared<Host>(hostname); // Expectation: The host is created and given ID 1 InsertEntityArgs insert_args([&]( std::shared_ptr<Entity> entity) { EXPECT_EQ(entity->kind, EntityKind::HOST); EXPECT_EQ(entity->name, hostname); EXPECT_EQ(entity->alias, hostname); return EntityId(1); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args, &InsertEntityArgs::insert)); // Expectations: Request the backend to notify user (if needed) EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(EntityId(0), EntityId(1), EntityKind::HOST, details::StatisticsBackendData::DISCOVERY)).Times(1); // Add to the queue and wait to be processed entity_queue.push(timestamp, {host, 0, details::StatisticsBackendData::DISCOVERY}); entity_queue.flush(); } TEST_F(database_queue_tests, push_host_throws) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string hostname = "hostname"; // Create the entity hierarchy std::shared_ptr<Host> host = std::make_shared<Host>(hostname); // Expectation: The host creation throws InsertEntityArgs insert_args([&]( std::shared_ptr<Entity> entity) -> EntityId { EXPECT_EQ(entity->kind, EntityKind::HOST); EXPECT_EQ(entity->name, hostname); EXPECT_EQ(entity->alias, hostname); throw BadParameter("Error"); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args, &InsertEntityArgs::insert)); // Expectations: No notification to user EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(_, _, _, _)).Times(0); // Add to the queue and wait to be processed entity_queue.stop_consumer(); entity_queue.push(timestamp, {host, DomainId(0), details::StatisticsBackendData::DISCOVERY}); entity_queue.do_swap(); EXPECT_NO_THROW(entity_queue.consume_sample()); } TEST_F(database_queue_tests, push_user) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string hostname = "hostname"; std::string username = "username"; // Create the entity hierarchy std::shared_ptr<Host> host = std::make_shared<Host>(hostname); std::shared_ptr<User> user = std::make_shared<User>(username, host); // Expectation: The user is created and given ID 2 InsertEntityArgs insert_args([&]( std::shared_ptr<Entity> entity) { EXPECT_EQ(entity->kind, EntityKind::USER); EXPECT_EQ(entity->name, username); EXPECT_EQ(entity->alias, username); EXPECT_EQ(std::dynamic_pointer_cast<User>(entity)->host, host); return EntityId(2); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args, &InsertEntityArgs::insert)); // Expectations: Request the backend to notify user (if needed) EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(EntityId(0), EntityId(2), EntityKind::USER, details::StatisticsBackendData::DISCOVERY)).Times(1); // Add to the queue and wait to be processed entity_queue.push(timestamp, {user, 0, details::StatisticsBackendData::DISCOVERY}); entity_queue.flush(); } TEST_F(database_queue_tests, push_user_throws) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string hostname = "hostname"; std::string username = "username"; // Create the entity hierarchy std::shared_ptr<Host> host = std::make_shared<Host>(hostname); std::shared_ptr<User> user = std::make_shared<User>(username, host); // Expectation: The user creation throws InsertEntityArgs insert_args([&]( std::shared_ptr<Entity> entity) -> EntityId { EXPECT_EQ(entity->kind, EntityKind::USER); EXPECT_EQ(entity->name, username); EXPECT_EQ(entity->alias, username); EXPECT_EQ(std::dynamic_pointer_cast<User>(entity)->host, host); throw BadParameter("Error"); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args, &InsertEntityArgs::insert)); // Expectations: No notification to user EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(_, _, _, _)).Times(0); // Add to the queue and wait to be processed entity_queue.stop_consumer(); entity_queue.push(timestamp, {user, 0, details::StatisticsBackendData::DISCOVERY}); entity_queue.do_swap(); EXPECT_NO_THROW(entity_queue.consume_sample()); } TEST_F(database_queue_tests, push_process) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string hostname = "hostname"; std::string username = "username"; std::string command = "command"; std::string pid = "1234"; // Create the entity hierarchy std::shared_ptr<Host> host = std::make_shared<Host>(hostname); std::shared_ptr<User> user = std::make_shared<User>(username, host); std::shared_ptr<Process> process = std::make_shared<Process>(command, pid, user); // Expectation: The process is created and given ID 2 InsertEntityArgs insert_args([&]( std::shared_ptr<Entity> entity) { EXPECT_EQ(entity->kind, EntityKind::PROCESS); EXPECT_EQ(entity->name, command); EXPECT_EQ(entity->alias, command); EXPECT_EQ(std::dynamic_pointer_cast<Process>(entity)->pid, pid); EXPECT_EQ(std::dynamic_pointer_cast<Process>(entity)->user, user); return EntityId(2); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args, &InsertEntityArgs::insert)); // Expectations: Request the backend to notify user (if needed) EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(EntityId(0), EntityId(2), EntityKind::PROCESS, details::StatisticsBackendData::DISCOVERY)).Times(1); // Add to the queue and wait to be processed entity_queue.push(timestamp, {process, 0, details::StatisticsBackendData::DISCOVERY}); entity_queue.flush(); } TEST_F(database_queue_tests, push_process_throws) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string hostname = "hostname"; std::string username = "username"; std::string command = "command"; std::string pid = "1234"; // Create the entity hierarchy std::shared_ptr<Host> host = std::make_shared<Host>(hostname); std::shared_ptr<User> user = std::make_shared<User>(username, host); std::shared_ptr<Process> process = std::make_shared<Process>(command, pid, user); // Expectation: The process creation throws InsertEntityArgs insert_args([&]( std::shared_ptr<Entity> entity) -> EntityId { EXPECT_EQ(entity->kind, EntityKind::PROCESS); EXPECT_EQ(entity->name, command); EXPECT_EQ(entity->alias, command); EXPECT_EQ(std::dynamic_pointer_cast<Process>(entity)->pid, pid); EXPECT_EQ(std::dynamic_pointer_cast<Process>(entity)->user, user); throw BadParameter("Error"); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args, &InsertEntityArgs::insert)); // Expectations: No notification to user EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(_, _, _, _)).Times(0); // Add to the queue and wait to be processed entity_queue.stop_consumer(); entity_queue.push(timestamp, {process, 0, details::StatisticsBackendData::DISCOVERY}); entity_queue.do_swap(); EXPECT_NO_THROW(entity_queue.consume_sample()); } TEST_F(database_queue_tests, push_domain) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string domain_name = "domain name"; // Create the domain hierarchy std::shared_ptr<Domain> domain = std::make_shared<Domain>(domain_name); // Expectation: The domain is created and given ID 0 InsertEntityArgs insert_args([&]( std::shared_ptr<Entity> entity) { EXPECT_EQ(entity->kind, EntityKind::DOMAIN); EXPECT_EQ(entity->name, domain_name); EXPECT_EQ(entity->alias, domain_name); return EntityId(0); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args, &InsertEntityArgs::insert)); // Expectations: Domains are not discovered, they are created on monitor initialization // Never try to inform the user EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(EntityId(0), EntityId( 0), EntityKind::DOMAIN, details::StatisticsBackendData::DISCOVERY)).Times(0); // Add to the queue and wait to be processed entity_queue.push(timestamp, {domain, 0, details::StatisticsBackendData::DISCOVERY}); entity_queue.flush(); } TEST_F(database_queue_tests, push_domain_throws) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string domain_name = "domain name"; // Create the domain hierarchy std::shared_ptr<Domain> domain = std::make_shared<Domain>(domain_name); // Expectation: The domain creation throws InsertEntityArgs insert_args([&]( std::shared_ptr<Entity> entity) -> EntityId { EXPECT_EQ(entity->kind, EntityKind::DOMAIN); EXPECT_EQ(entity->name, domain_name); EXPECT_EQ(entity->alias, domain_name); throw BadParameter("Error"); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args, &InsertEntityArgs::insert)); // Expectations: No notification to user EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(_, _, _, _)).Times(0); // Add to the queue and wait to be processed entity_queue.stop_consumer(); entity_queue.push(timestamp, {domain, 0, details::StatisticsBackendData::DISCOVERY}); entity_queue.do_swap(); EXPECT_NO_THROW(entity_queue.consume_sample()); } TEST_F(database_queue_tests, push_participant_process_exists) { // Create the process std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string command = "command"; std::string pid = "1234"; std::shared_ptr<Process> process = std::make_shared<Process>(command, pid, std::shared_ptr<User>()); // Create the domain hierarchy std::string participant_name = "participant name"; Qos participant_qos; std::string participant_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.0"; std::shared_ptr<Domain> domain; std::shared_ptr<DomainParticipant> participant = std::make_shared<DomainParticipant>(participant_name, participant_qos, participant_guid_str, process, domain); // Participant undiscovery: FAILURE { EXPECT_CALL(database, insert(_)).Times(0); // Expectations: The status will throw an exception because the participant is not in the database EXPECT_CALL(database, change_entity_status(_, false)).Times(AnyNumber()) .WillRepeatedly(Throw(BadParameter("Error"))); // Expectations: No notification to user EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(_, _, _, _)).Times(0); // Add to the queue and wait to be processed entity_queue.push(timestamp, {participant, 0, details::StatisticsBackendData::UNDISCOVERY}); entity_queue.flush(); } // Participant update: FAILURE { EXPECT_CALL(database, insert(_)).Times(0); // Expectations: The status will throw an exception because the participant is not in the database EXPECT_CALL(database, change_entity_status(_, true)).Times(AnyNumber()) .WillRepeatedly(Throw(BadParameter("Error"))); // Expectations: No notification to user EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(_, _, _, _)).Times(0); // Add to the queue and wait to be processed entity_queue.push(timestamp, {participant, 0, details::StatisticsBackendData::UPDATE}); entity_queue.flush(); } // Participant discovery: SUCCESS { // Expectation: The participant is created and given ID 1 InsertEntityArgs insert_args([&]( std::shared_ptr<Entity> entity) { EXPECT_EQ(entity->kind, EntityKind::PARTICIPANT); EXPECT_EQ(entity->name, participant_name); EXPECT_EQ(std::dynamic_pointer_cast<DomainParticipant>(entity)->qos, participant_qos); EXPECT_EQ(std::dynamic_pointer_cast<DomainParticipant>(entity)->domain, domain); EXPECT_EQ(std::dynamic_pointer_cast<DomainParticipant>(entity)->process, process); return EntityId(1); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args, &InsertEntityArgs::insert)); // Expectations: The status will be updated EXPECT_CALL(database, change_entity_status( EntityId(1), true)).Times(1); // Expectations: Request the backend to notify user (if needed) EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(EntityId(0), EntityId(1), EntityKind::PARTICIPANT, details::StatisticsBackendData::DISCOVERY)).Times(1); // Add to the queue and wait to be processed entity_queue.push(timestamp, {participant, 0, details::StatisticsBackendData::DISCOVERY}); entity_queue.flush(); } // Participant update: SUCCESS { EXPECT_CALL(database, insert(_)).Times(0); // Expectations: The status will be updated EXPECT_CALL(database, change_entity_status(_, true)).Times(1); // Expectations: Request the backend to notify user (if needed) EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(EntityId(0), _, EntityKind::PARTICIPANT, details::StatisticsBackendData::UPDATE)).Times(1); // Add to the queue and wait to be processed entity_queue.push(timestamp, {participant, 0, details::StatisticsBackendData::UPDATE}); entity_queue.flush(); } // Participant undiscovery: SUCCESS { EXPECT_CALL(database, insert(_)).Times(0); // Expectations: The status will be updated EXPECT_CALL(database, change_entity_status(_, false)).Times(1); // Expectations: Request the backend to notify user (if needed) EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(EntityId(0), _, EntityKind::PARTICIPANT, details::StatisticsBackendData::UNDISCOVERY)).Times(1); // Add to the queue and wait to be processed entity_queue.push(timestamp, {participant, 0, details::StatisticsBackendData::UNDISCOVERY}); entity_queue.flush(); } } TEST_F(database_queue_tests, push_participant_no_process_exists) { // Create the domain hierarchy std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string participant_name = "participant name"; Qos participant_qos; std::string participant_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.0"; std::shared_ptr<Domain> domain; std::shared_ptr<Process> process; std::shared_ptr<DomainParticipant> participant = std::make_shared<DomainParticipant>(participant_name, participant_qos, participant_guid_str, process, domain); // Participant undiscovery: FAILURE { EXPECT_CALL(database, insert(_)).Times(0); // Expectations: The status will throw an exception because the participant is not in the database EXPECT_CALL(database, change_entity_status(_, false)).Times(AnyNumber()) .WillRepeatedly(Throw(BadParameter("Error"))); // Expectations: No notification to user EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(_, _, _, _)).Times(0); // Add to the queue and wait to be processed entity_queue.push(timestamp, {participant, 0, details::StatisticsBackendData::UNDISCOVERY}); entity_queue.flush(); } // Participant update: FAILURE { EXPECT_CALL(database, insert(_)).Times(0); // Expectations: The status will throw an exception because the participant is not in the database EXPECT_CALL(database, change_entity_status(_, true)).Times(AnyNumber()) .WillRepeatedly(Throw(BadParameter("Error"))); // Expectations: No notification to user EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(_, _, _, _)).Times(0); // Add to the queue and wait to be processed entity_queue.push(timestamp, {participant, 0, details::StatisticsBackendData::UPDATE}); entity_queue.flush(); } // Participant discovery: SUCCESS { // Expectation: The participant is created and given ID 1 InsertEntityArgs insert_args([&]( std::shared_ptr<Entity> entity) { EXPECT_EQ(entity->kind, EntityKind::PARTICIPANT); EXPECT_EQ(entity->name, participant_name); EXPECT_EQ(std::dynamic_pointer_cast<DomainParticipant>(entity)->qos, participant_qos); EXPECT_EQ(std::dynamic_pointer_cast<DomainParticipant>(entity)->domain, domain); EXPECT_EQ(std::dynamic_pointer_cast<DomainParticipant>(entity)->process, process); return EntityId(1); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args, &InsertEntityArgs::insert)); // Expectations: The status will be updated EXPECT_CALL(database, change_entity_status( EntityId(1), true)).Times(1); // Expectations: Request the backend to notify user (if needed) EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(EntityId(0), EntityId(1), EntityKind::PARTICIPANT, details::StatisticsBackendData::DISCOVERY)).Times(1); // Add to the queue and wait to be processed entity_queue.push(timestamp, {participant, 0, details::StatisticsBackendData::DISCOVERY}); entity_queue.flush(); } // Participant update: SUCCESS { EXPECT_CALL(database, insert(_)).Times(0); // Expectations: The status will be updated EXPECT_CALL(database, change_entity_status(_, true)).Times(1); // Expectations: Request the backend to notify user (if needed) EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(EntityId(0), _, EntityKind::PARTICIPANT, details::StatisticsBackendData::UPDATE)).Times(1); // Add to the queue and wait to be processed entity_queue.push(timestamp, {participant, 0, details::StatisticsBackendData::UPDATE}); entity_queue.flush(); } // Participant undiscovery: SUCCESS { EXPECT_CALL(database, insert(_)).Times(0); // Expectations: The status will be updated EXPECT_CALL(database, change_entity_status(_, false)).Times(1); // Expectations: Request the backend to notify user (if needed) EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(EntityId(0), _, EntityKind::PARTICIPANT, details::StatisticsBackendData::UNDISCOVERY)).Times(1); // Add to the queue and wait to be processed entity_queue.push(timestamp, {participant, 0, details::StatisticsBackendData::UNDISCOVERY}); entity_queue.flush(); } } TEST_F(database_queue_tests, push_participant_throws) { // Create the domain hierarchy std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string participant_name = "participant name"; Qos participant_qos; std::string participant_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.0"; std::shared_ptr<Domain> domain; std::shared_ptr<Process> process; std::shared_ptr<DomainParticipant> participant = std::make_shared<DomainParticipant>(participant_name, participant_qos, participant_guid_str, process, domain); // Expectation: The participant creation throws InsertEntityArgs insert_args([&]( std::shared_ptr<Entity> entity) -> EntityId { EXPECT_EQ(entity->kind, EntityKind::PARTICIPANT); EXPECT_EQ(entity->name, participant_name); EXPECT_EQ(std::dynamic_pointer_cast<DomainParticipant>(entity)->qos, participant_qos); EXPECT_EQ(std::dynamic_pointer_cast<DomainParticipant>(entity)->domain, domain); EXPECT_EQ(std::dynamic_pointer_cast<DomainParticipant>(entity)->process, process); throw BadParameter("Error"); }); EXPECT_CALL(database, insert(_)).Times(1).WillOnce(Invoke(&insert_args, &InsertEntityArgs::insert)); // Expectations: No notification to user EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(_, _, _, _)).Times(0); // Add to the queue and wait to be processed entity_queue.stop_consumer(); entity_queue.push(timestamp, {participant, 0, details::StatisticsBackendData::DISCOVERY}); entity_queue.do_swap(); EXPECT_NO_THROW(entity_queue.consume_sample()); } TEST_F(database_queue_tests, push_topic) { // Create the domain hierarchy std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string topic_name = "topic"; std::string type_name = "type"; std::shared_ptr<Domain> domain; std::shared_ptr<Topic> topic = std::make_shared<Topic>(topic_name, type_name, domain); // Expectation: The topic is created and given ID 1 InsertEntityArgs insert_args([&]( std::shared_ptr<Entity> entity) { EXPECT_EQ(entity->kind, EntityKind::TOPIC); EXPECT_EQ(entity->name, topic_name); EXPECT_EQ(entity->alias, topic_name); EXPECT_EQ(std::dynamic_pointer_cast<Topic>(entity)->data_type, type_name); EXPECT_EQ(std::dynamic_pointer_cast<Topic>(entity)->domain, domain); return EntityId(1); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args, &InsertEntityArgs::insert)); // Expectations: Request the backend to notify user (if needed) EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(EntityId(0), EntityId(1), EntityKind::TOPIC, details::StatisticsBackendData::DISCOVERY)).Times(1); // Add to the queue and wait to be processed entity_queue.push(timestamp, {topic, 0, details::StatisticsBackendData::DISCOVERY}); entity_queue.flush(); } TEST_F(database_queue_tests, push_topic_throws) { // Create the domain hierarchy std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string topic_name = "topic"; std::string type_name = "type"; std::shared_ptr<Domain> domain; std::shared_ptr<Topic> topic = std::make_shared<Topic>(topic_name, type_name, domain); // Expectation: The topic creation throws InsertEntityArgs insert_args([&]( std::shared_ptr<Entity> entity) -> EntityId { EXPECT_EQ(entity->kind, EntityKind::TOPIC); EXPECT_EQ(entity->name, topic_name); EXPECT_EQ(entity->alias, topic_name); EXPECT_EQ(std::dynamic_pointer_cast<Topic>(entity)->data_type, type_name); EXPECT_EQ(std::dynamic_pointer_cast<Topic>(entity)->domain, domain); throw BadParameter("Error"); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args, &InsertEntityArgs::insert)); // Expectations: No notification to user EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(_, _, _, _)).Times(0); // Add to the queue and wait to be processed entity_queue.stop_consumer(); entity_queue.push(timestamp, {topic, 0, details::StatisticsBackendData::DISCOVERY}); entity_queue.do_swap(); EXPECT_NO_THROW(entity_queue.consume_sample()); } TEST_F(database_queue_tests, push_datawriter) { // Create the domain hierarchy std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string datawriter_name = "datawriter"; Qos datawriter_qos; std::string datawriter_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.1"; std::shared_ptr<Topic> topic; std::shared_ptr<DomainParticipant> participant; std::shared_ptr<DataWriter> datawriter = std::make_shared<DataWriter>(datawriter_name, datawriter_qos, datawriter_guid_str, participant, topic); // Datawriter undiscovery: FAILURE { EXPECT_CALL(database, insert(_)).Times(0); // Expectations: The status will throw an exception because the datawriter is not in the database EXPECT_CALL(database, change_entity_status(_, false)).Times(AnyNumber()) .WillRepeatedly(Throw(BadParameter("Error"))); // Expectations: No notification to user EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(_, _, _, _)).Times(0); // Add to the queue and wait to be processed entity_queue.push(timestamp, {datawriter, 0, details::StatisticsBackendData::UNDISCOVERY}); entity_queue.flush(); } // Datawriter update: FAILURE { EXPECT_CALL(database, insert(_)).Times(0); // Expectations: The status will throw an exception because the datawriter is not in the database EXPECT_CALL(database, change_entity_status(_, true)).Times(AnyNumber()) .WillRepeatedly(Throw(BadParameter("Error"))); // Expectations: No notification to user EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(_, _, _, _)).Times(0); // Add to the queue and wait to be processed entity_queue.push(timestamp, {datawriter, 0, details::StatisticsBackendData::UPDATE}); entity_queue.flush(); } // Datawriter discovery: SUCCESS { // Expectation: The datawriter is created and given ID 1 InsertEntityArgs insert_args([&]( std::shared_ptr<Entity> entity) { EXPECT_EQ(entity->kind, EntityKind::DATAWRITER); EXPECT_EQ(entity->name, datawriter_name); EXPECT_EQ(entity->alias, datawriter_name); EXPECT_EQ(std::dynamic_pointer_cast<DataWriter>(entity)->guid, datawriter_guid_str); EXPECT_EQ(std::dynamic_pointer_cast<DataWriter>(entity)->qos, datawriter_qos); return EntityId(1); }); EXPECT_CALL(database, insert(_)).Times(1).WillOnce(Invoke(&insert_args, &InsertEntityArgs::insert)); // Expectations: The status will be updated EXPECT_CALL(database, change_entity_status( EntityId(1), true)).Times(1); // Expectations: Request the backend to notify user (if needed) EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(EntityId(0), EntityId(1), EntityKind::DATAWRITER, details::StatisticsBackendData::DISCOVERY)) .Times(1); // Add to the queue and wait to be processed entity_queue.push(timestamp, {datawriter, 0, details::StatisticsBackendData::DISCOVERY}); entity_queue.flush(); } // Datawriter update: SUCCESS { EXPECT_CALL(database, insert(_)).Times(0); // Expectations: The status will be updated EXPECT_CALL(database, change_entity_status(_, true)).Times(1); // Expectations: Request the backend to notify user (if needed) EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(EntityId(0), _, EntityKind::DATAWRITER, details::StatisticsBackendData::UPDATE)).Times(1); // Add to the queue and wait to be processed entity_queue.push(timestamp, {datawriter, 0, details::StatisticsBackendData::UPDATE}); entity_queue.flush(); } // Datawriter undiscovery: SUCCESS { EXPECT_CALL(database, insert(_)).Times(0); // Expectations: The status will be updated EXPECT_CALL(database, change_entity_status(_, false)).Times(1); // Expectations: Request the backend to notify user (if needed) EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(EntityId(0), _, EntityKind::DATAWRITER, details::StatisticsBackendData::UNDISCOVERY)).Times(1); // Add to the queue and wait to be processed entity_queue.push(timestamp, {datawriter, 0, details::StatisticsBackendData::UNDISCOVERY}); entity_queue.flush(); } } TEST_F(database_queue_tests, push_datawriter_throws) { // Create the domain hierarchy std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string datawriter_name = "datawriter"; Qos datawriter_qos; std::string datawriter_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.1"; std::shared_ptr<Topic> topic; std::shared_ptr<DomainParticipant> participant; std::shared_ptr<DataWriter> datawriter = std::make_shared<DataWriter>(datawriter_name, datawriter_qos, datawriter_guid_str, participant, topic); // Expectation: The datawriter creation throws InsertEntityArgs insert_args([&]( std::shared_ptr<Entity> entity) -> EntityId { EXPECT_EQ(entity->kind, EntityKind::DATAWRITER); EXPECT_EQ(entity->name, datawriter_name); EXPECT_EQ(entity->alias, datawriter_name); EXPECT_EQ(std::dynamic_pointer_cast<DataWriter>(entity)->guid, datawriter_guid_str); EXPECT_EQ(std::dynamic_pointer_cast<DataWriter>(entity)->qos, datawriter_qos); throw BadParameter("Error"); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args, &InsertEntityArgs::insert)); // Expectations: No notification to user EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(_, _, _, _)).Times(0); // Add to the queue and wait to be processed entity_queue.stop_consumer(); entity_queue.push(timestamp, {datawriter, 0, details::StatisticsBackendData::DISCOVERY}); entity_queue.do_swap(); EXPECT_NO_THROW(entity_queue.consume_sample()); } TEST_F(database_queue_tests, push_datareader) { // Create the domain hierarchy std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string datareader_name = "datareader"; Qos datareader_qos; std::string datareader_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; std::shared_ptr<Topic> topic; std::shared_ptr<DomainParticipant> participant; std::shared_ptr<DataReader> datareader = std::make_shared<DataReader>(datareader_name, datareader_qos, datareader_guid_str, participant, topic); // Datareader undiscovery: FAILURE { EXPECT_CALL(database, insert(_)).Times(0); // Expectations: The status will throw an exception because the datareader is not in the database EXPECT_CALL(database, change_entity_status(_, false)).Times(AnyNumber()).WillRepeatedly(Throw(BadParameter("Error"))); // Expectations: No notification to user EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(_, _, _, _)).Times(0); // Add to the queue and wait to be processed entity_queue.push(timestamp, {datareader, 0, details::StatisticsBackendData::UNDISCOVERY}); entity_queue.flush(); } // Datareader update: FAILURE { EXPECT_CALL(database, insert(_)).Times(0); // Expectations: The status will throw an exception because the datareader is not in the database EXPECT_CALL(database, change_entity_status(_, true)).Times(AnyNumber()).WillRepeatedly(Throw(BadParameter("Error"))); // Expectations: No notification to user EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(_, _, _, _)).Times(0); // Add to the queue and wait to be processed entity_queue.push(timestamp, {datareader, 0, details::StatisticsBackendData::UPDATE}); entity_queue.flush(); } // Datareader discovery: SUCCESS { // Expectation: The datareader is created and given ID 1 InsertEntityArgs insert_args([&]( std::shared_ptr<Entity> entity) { EXPECT_EQ(entity->kind, EntityKind::DATAREADER); EXPECT_EQ(entity->name, datareader_name); EXPECT_EQ(entity->alias, datareader_name); EXPECT_EQ(std::dynamic_pointer_cast<DataReader>(entity)->guid, datareader_guid_str); EXPECT_EQ(std::dynamic_pointer_cast<DataReader>(entity)->qos, datareader_qos); return EntityId(1); }); EXPECT_CALL(database, insert(_)).Times(1).WillOnce(Invoke(&insert_args, &InsertEntityArgs::insert)); // Expectations: The status will be updated EXPECT_CALL(database, change_entity_status( EntityId(1), true)).Times(1); // Expectations: Request the backend to notify user (if needed) EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(EntityId(0), EntityId(1), EntityKind::DATAREADER, details::StatisticsBackendData::DISCOVERY)) .Times(1); // Add to the queue and wait to be processed entity_queue.push(timestamp, {datareader, 0, details::StatisticsBackendData::DISCOVERY}); entity_queue.flush(); } // Datareader update: SUCCESS { EXPECT_CALL(database, insert(_)).Times(0); // Expectations: The status will be updated EXPECT_CALL(database, change_entity_status(_, true)).Times(1); // Expectations: Request the backend to notify user (if needed) EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(EntityId(0), _, EntityKind::DATAREADER, details::StatisticsBackendData::UPDATE)) .Times(1); // Add to the queue and wait to be processed entity_queue.push(timestamp, {datareader, 0, details::StatisticsBackendData::UPDATE}); entity_queue.flush(); } // Datareader undiscovery: SUCCESS { EXPECT_CALL(database, insert(_)).Times(0); // Expectations: The status will be updated EXPECT_CALL(database, change_entity_status(_, false)).Times(1); // Expectations: Request the backend to notify user (if needed) EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(EntityId(0), _, EntityKind::DATAREADER, details::StatisticsBackendData::UNDISCOVERY)) .Times(1); // Add to the queue and wait to be processed entity_queue.push(timestamp, {datareader, 0, details::StatisticsBackendData::UNDISCOVERY}); entity_queue.flush(); } } TEST_F(database_queue_tests, push_datareader_throws) { // Create the domain hierarchy std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string datareader_name = "datareader"; Qos datareader_qos; std::string datareader_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; std::shared_ptr<Topic> topic; std::shared_ptr<DomainParticipant> participant; std::shared_ptr<DataReader> datareader = std::make_shared<DataReader>(datareader_name, datareader_qos, datareader_guid_str, participant, topic); // Expectation: The datareader creation throws InsertEntityArgs insert_args([&]( std::shared_ptr<Entity> entity) -> EntityId { EXPECT_EQ(entity->kind, EntityKind::DATAREADER); EXPECT_EQ(entity->name, datareader_name); EXPECT_EQ(entity->alias, datareader_name); EXPECT_EQ(std::dynamic_pointer_cast<DataReader>(entity)->guid, datareader_guid_str); EXPECT_EQ(std::dynamic_pointer_cast<DataReader>(entity)->qos, datareader_qos); throw BadParameter("Error"); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args, &InsertEntityArgs::insert)); // Expectations: No notification to user EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(_, _, _, _)).Times(0); // Add to the queue and wait to be processed entity_queue.stop_consumer(); entity_queue.push(timestamp, {datareader, 0, details::StatisticsBackendData::DISCOVERY}); entity_queue.do_swap(); EXPECT_NO_THROW(entity_queue.consume_sample()); } TEST_F(database_queue_tests, push_locator) { // Create the domain hierarchy std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string locator_name = "locator"; std::shared_ptr<Locator> locator = std::make_shared<Locator>(locator_name); // Expectation: The locator is created and given ID 1 InsertEntityArgs insert_args([&]( std::shared_ptr<Entity> entity) { EXPECT_EQ(entity->kind, EntityKind::LOCATOR); EXPECT_EQ(entity->name, locator_name); EXPECT_EQ(entity->alias, locator_name); return EntityId(1); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args, &InsertEntityArgs::insert)); // Expectations: Request the backend to notify user (if needed) EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(EntityId(0), EntityId(1), EntityKind::LOCATOR, details::StatisticsBackendData::DISCOVERY)).Times(1); // Add to the queue and wait to be processed entity_queue.push(timestamp, {locator, 0, details::StatisticsBackendData::DISCOVERY}); entity_queue.flush(); } TEST_F(database_queue_tests, push_locator_throws) { // Create the domain hierarchy std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string locator_name = "locator"; std::shared_ptr<Locator> locator = std::make_shared<Locator>(locator_name); // Expectation: The locator creation throws InsertEntityArgs insert_args([&]( std::shared_ptr<Entity> entity) -> EntityId { EXPECT_EQ(entity->kind, EntityKind::LOCATOR); EXPECT_EQ(entity->name, locator_name); EXPECT_EQ(entity->alias, locator_name); throw BadParameter("Error"); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args, &InsertEntityArgs::insert)); // Expectations: No notification to user EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_domain_entity_discovery(_, _, _, _)).Times(0); // Add to the queue and wait to be processed entity_queue.stop_consumer(); entity_queue.push(timestamp, {locator, 0, details::StatisticsBackendData::DISCOVERY}); entity_queue.do_swap(); EXPECT_NO_THROW(entity_queue.consume_sample()); } TEST_F(database_queue_tests, push_history_latency) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> reader_id = {0, 0, 0, 1}; std::array<uint8_t, 4> writer_id = {0, 0, 0, 2}; std::string reader_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.1"; std::string writer_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; // Build the reader GUID DatabaseDataQueue::StatisticsGuidPrefix reader_prefix; reader_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId reader_entity_id; reader_entity_id.value(reader_id); DatabaseDataQueue::StatisticsGuid reader_guid; reader_guid.guidPrefix(reader_prefix); reader_guid.entityId(reader_entity_id); // Build the writer GUID DatabaseDataQueue::StatisticsGuidPrefix writer_prefix; writer_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId writer_entity_id; writer_entity_id.value(writer_id); DatabaseDataQueue::StatisticsGuid writer_guid; writer_guid.guidPrefix(writer_prefix); writer_guid.entityId(writer_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsWriterReaderData inner_data; inner_data.data(1.0); inner_data.writer_guid(writer_guid); inner_data.reader_guid(reader_guid); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->writer_reader_data(inner_data); data->_d(EventKind::HISTORY2HISTORY_LATENCY); // Precondition: The writer exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAWRITER, writer_guid_str)).Times(1) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(1)))); // Precondition: The reader exists and has ID 2 EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAREADER, reader_guid_str)).Times(1) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(2)))); // Expectation: The insert method is called with appropriate arguments InsertDataArgs args([&]( const EntityId& domain_id, const EntityId& entity_id, const StatisticsSample& sample) { EXPECT_EQ(entity_id, 1); EXPECT_EQ(domain_id, 0); EXPECT_EQ(sample.src_ts, timestamp); EXPECT_EQ(sample.kind, DataKind::FASTDDS_LATENCY); EXPECT_EQ(dynamic_cast<const HistoryLatencySample&>(sample).reader, 2); EXPECT_EQ(dynamic_cast<const HistoryLatencySample&>(sample).data, 1.0); }); EXPECT_CALL(database, insert(_, _, _)).Times(1) .WillOnce(Invoke(&args, &InsertDataArgs::insert)); // Expectation: The user is notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(EntityId(0), EntityId(1), DataKind::FASTDDS_LATENCY)).Times(1); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_history_latency_no_reader) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> reader_id = {0, 0, 0, 1}; std::array<uint8_t, 4> writer_id = {0, 0, 0, 2}; std::string reader_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.1"; std::string writer_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; // Build the reader GUID DatabaseDataQueue::StatisticsGuidPrefix reader_prefix; reader_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId reader_entity_id; reader_entity_id.value(reader_id); DatabaseDataQueue::StatisticsGuid reader_guid; reader_guid.guidPrefix(reader_prefix); reader_guid.entityId(reader_entity_id); // Build the writer GUID DatabaseDataQueue::StatisticsGuidPrefix writer_prefix; writer_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId writer_entity_id; writer_entity_id.value(writer_id); DatabaseDataQueue::StatisticsGuid writer_guid; writer_guid.guidPrefix(writer_prefix); writer_guid.entityId(writer_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsWriterReaderData inner_data; inner_data.data(1.0); inner_data.writer_guid(writer_guid); inner_data.reader_guid(reader_guid); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->writer_reader_data(inner_data); data->_d(EventKind::HISTORY2HISTORY_LATENCY); // Precondition: The writer exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAWRITER, writer_guid_str)).Times(AnyNumber()) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(1)))); // Precondition: The reader does not exist EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAREADER, reader_guid_str)).Times(AnyNumber()) .WillOnce(Throw(BadParameter("Error"))); // Expectation: The insert method is not called, data dropped EXPECT_CALL(database, insert(_, _, _)).Times(0); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(_, _, _)).Times(0); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_history_latency_no_writer) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> reader_id = {0, 0, 0, 1}; std::array<uint8_t, 4> writer_id = {0, 0, 0, 2}; std::string reader_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.1"; std::string writer_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; // Build the reader GUID DatabaseDataQueue::StatisticsGuidPrefix reader_prefix; reader_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId reader_entity_id; reader_entity_id.value(reader_id); DatabaseDataQueue::StatisticsGuid reader_guid; reader_guid.guidPrefix(reader_prefix); reader_guid.entityId(reader_entity_id); // Build the writer GUID DatabaseDataQueue::StatisticsGuidPrefix writer_prefix; writer_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId writer_entity_id; writer_entity_id.value(writer_id); DatabaseDataQueue::StatisticsGuid writer_guid; writer_guid.guidPrefix(writer_prefix); writer_guid.entityId(writer_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsWriterReaderData inner_data; inner_data.data(1.0); inner_data.writer_guid(writer_guid); inner_data.reader_guid(reader_guid); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->writer_reader_data(inner_data); data->_d(EventKind::HISTORY2HISTORY_LATENCY); // Precondition: The writer does not exist EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAWRITER, writer_guid_str)).Times(AnyNumber()) .WillOnce(Throw(BadParameter("Error"))); // Precondition: The reader exists and has ID 2 EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAREADER, reader_guid_str)).Times(AnyNumber()) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(2)))); // Expectation: The insert method is not called, data dropped EXPECT_CALL(database, insert(_, _, _)).Times(0); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(_, _, _)).Times(0); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_network_latency) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 16> src_locator_address = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; uint32_t src_locator_port = 0; std::string src_locator_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|d.e.f.10"; std::array<uint8_t, 16> dst_locator_address = {16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; uint32_t dst_locator_port = 2048; std::string dst_locator_str = "TCPv4:[4.3.2.1]:2048"; // Build the source locator DatabaseDataQueue::StatisticsLocator src_locator; src_locator.kind(LOCATOR_KIND_TCPv4); src_locator.port(src_locator_port); src_locator.address(src_locator_address); // Build the destination locator DatabaseDataQueue::StatisticsLocator dst_locator; dst_locator.kind(LOCATOR_KIND_TCPv4); dst_locator.port(dst_locator_port); dst_locator.address(dst_locator_address); // Build the Statistics data DatabaseDataQueue::StatisticsLocator2LocatorData inner_data; inner_data.data(1.0); inner_data.src_locator(src_locator); inner_data.dst_locator(dst_locator); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->locator2locator_data(inner_data); data->_d(EventKind::NETWORK_LATENCY); // Precondition: The participant exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::PARTICIPANT, src_locator_str)).Times(1) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(1)))); // Precondition: The destination locator exists and has ID 2 EXPECT_CALL(database, get_entities_by_name(EntityKind::LOCATOR, dst_locator_str)).Times(1) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(2))))); // Expectation: The insert method is called with appropriate arguments InsertDataArgs args([&]( const EntityId& domain_id, const EntityId& entity_id, const StatisticsSample& sample) { EXPECT_EQ(entity_id, 1); EXPECT_EQ(domain_id, 0); EXPECT_EQ(sample.src_ts, timestamp); EXPECT_EQ(sample.kind, DataKind::NETWORK_LATENCY); EXPECT_EQ(dynamic_cast<const NetworkLatencySample&>(sample).remote_locator, 2); }); EXPECT_CALL(database, insert(_, _, _)).Times(1) .WillOnce(Invoke(&args, &InsertDataArgs::insert)); // Expectation: The user is notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(EntityId(0), EntityId(1), DataKind::NETWORK_LATENCY)).Times(1); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_network_latency_no_participant) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 16> src_locator_address = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; uint32_t src_locator_port = 0; std::string src_locator_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|d.e.f.10"; std::array<uint8_t, 16> dst_locator_address = {16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; uint32_t dst_locator_port = 2048; std::string dst_locator_str = "TCPv4:[4.3.2.1]:2048"; // Build the source locator DatabaseDataQueue::StatisticsLocator src_locator; src_locator.kind(LOCATOR_KIND_TCPv4); src_locator.port(src_locator_port); src_locator.address(src_locator_address); // Build the destination locator DatabaseDataQueue::StatisticsLocator dst_locator; dst_locator.kind(LOCATOR_KIND_TCPv4); dst_locator.port(dst_locator_port); dst_locator.address(dst_locator_address); // Build the Statistics data DatabaseDataQueue::StatisticsLocator2LocatorData inner_data; inner_data.data(1.0); inner_data.src_locator(src_locator); inner_data.dst_locator(dst_locator); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->locator2locator_data(inner_data); data->_d(EventKind::NETWORK_LATENCY); // Precondition: The participant does not exist EXPECT_CALL(database, get_entity_by_guid(EntityKind::PARTICIPANT, src_locator_str)).Times(AnyNumber()) .WillOnce(Throw(BadParameter("Error"))); // Precondition: The destination locator exists and has ID 2 EXPECT_CALL(database, get_entities_by_name(EntityKind::LOCATOR, dst_locator_str)).Times(AnyNumber()) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(2))))); // Expectation: The insert method is never called, data dropped EXPECT_CALL(database, insert(_, _, _)).Times(0); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(_, _, _)).Times(0); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_network_latency_wrong_participant_format) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 16> src_locator_address = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; uint32_t src_locator_port = 1; std::string src_locator_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|d.e.f.10"; std::array<uint8_t, 16> dst_locator_address = {16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; uint32_t dst_locator_port = 2048; std::string dst_locator_str = "TCPv4:[4.3.2.1]:2048"; // Build the source locator DatabaseDataQueue::StatisticsLocator src_locator; src_locator.kind(LOCATOR_KIND_TCPv4); src_locator.port(src_locator_port); src_locator.address(src_locator_address); // Build the destination locator DatabaseDataQueue::StatisticsLocator dst_locator; dst_locator.kind(LOCATOR_KIND_TCPv4); dst_locator.port(dst_locator_port); dst_locator.address(dst_locator_address); // Build the Statistics data DatabaseDataQueue::StatisticsLocator2LocatorData inner_data; inner_data.data(1.0); inner_data.src_locator(src_locator); inner_data.dst_locator(dst_locator); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->locator2locator_data(inner_data); data->_d(EventKind::NETWORK_LATENCY); // Precondition: The participant is not searched EXPECT_CALL(database, get_entity_by_guid(EntityKind::PARTICIPANT, src_locator_str)).Times(0); // Precondition: The destination locator exists and has ID 2 EXPECT_CALL(database, get_entities_by_name(EntityKind::LOCATOR, dst_locator_str)).Times(AnyNumber()) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(2))))); // Expectation: The insert method is never called, data dropped EXPECT_CALL(database, insert(_, _, _)).Times(0); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(_, _, _)).Times(0); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_network_latency_no_destination_locator) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 16> src_locator_address = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; uint32_t src_locator_port = 0; std::string src_locator_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|d.e.f.10"; std::array<uint8_t, 16> dst_locator_address = {16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; uint32_t dst_locator_port = 2048; std::string dst_locator_str = "TCPv4:[4.3.2.1]:2048"; // Build the source locator DatabaseDataQueue::StatisticsLocator src_locator; src_locator.kind(LOCATOR_KIND_TCPv4); src_locator.port(src_locator_port); src_locator.address(src_locator_address); // Build the destination locator DatabaseDataQueue::StatisticsLocator dst_locator; dst_locator.kind(LOCATOR_KIND_TCPv4); dst_locator.port(dst_locator_port); dst_locator.address(dst_locator_address); // Build the Statistics data DatabaseDataQueue::StatisticsLocator2LocatorData inner_data; inner_data.data(1.0); inner_data.src_locator(src_locator); inner_data.dst_locator(dst_locator); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->locator2locator_data(inner_data); data->_d(EventKind::NETWORK_LATENCY); // Precondition: The participant exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::PARTICIPANT, src_locator_str)).Times(AnyNumber()) .WillOnce(Return(std::pair<EntityId, EntityId>(std::make_pair(EntityId(0), EntityId(1))))); // Precondition: The destination locator does not exist the first time // Precondition: The destination locator exists and has ID 2 EXPECT_CALL(database, get_entities_by_name(EntityKind::LOCATOR, dst_locator_str)).Times(AnyNumber()) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>())) .WillRepeatedly(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(2))))); // Expectation: The insert method is called with appropriate arguments InsertDataArgs args([&]( const EntityId& domain_id, const EntityId& entity_id, const StatisticsSample& sample) { EXPECT_EQ(entity_id, 1); EXPECT_EQ(domain_id, 0); EXPECT_EQ(sample.src_ts, timestamp); EXPECT_EQ(sample.kind, DataKind::NETWORK_LATENCY); EXPECT_EQ(dynamic_cast<const NetworkLatencySample&>(sample).remote_locator, 2); }); EXPECT_CALL(database, insert(_, _, _)).Times(1) .WillOnce(Invoke(&args, &InsertDataArgs::insert)); // Expectation: the remote locator is created and given ID 2 InsertEntityArgs insert_args([&]( std::shared_ptr<Entity> entity) { EXPECT_EQ(entity->kind, EntityKind::LOCATOR); EXPECT_EQ(entity->name, dst_locator_str); EXPECT_EQ(entity->alias, dst_locator_str); return EntityId(2); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args, &InsertEntityArgs::insert)); // Expectation: The user is notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(EntityId(0), EntityId(1), DataKind::NETWORK_LATENCY)).Times(1); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_publication_throughput) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> writer_id = {0, 0, 0, 2}; std::string writer_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; // Build the writer GUID DatabaseDataQueue::StatisticsGuidPrefix writer_prefix; writer_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId writer_entity_id; writer_entity_id.value(writer_id); DatabaseDataQueue::StatisticsGuid writer_guid; writer_guid.guidPrefix(writer_prefix); writer_guid.entityId(writer_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsEntityData inner_data; inner_data.data(1.0); inner_data.guid(writer_guid); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity_data(inner_data); data->_d(EventKind::PUBLICATION_THROUGHPUT); // Precondition: The writer exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAWRITER, writer_guid_str)).Times(1) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(1)))); // Expectation: The insert method is called with appropriate arguments InsertDataArgs args([&]( const EntityId& domain_id, const EntityId& entity_id, const StatisticsSample& sample) { EXPECT_EQ(entity_id, 1); EXPECT_EQ(domain_id, 0); EXPECT_EQ(sample.src_ts, timestamp); EXPECT_EQ(sample.kind, DataKind::PUBLICATION_THROUGHPUT); EXPECT_EQ(dynamic_cast<const PublicationThroughputSample&>(sample).data, 1.0); }); EXPECT_CALL(database, insert(_, _, _)).Times(1) .WillOnce(Invoke(&args, &InsertDataArgs::insert)); // Expectation: The user is notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(EntityId(0), EntityId(1), DataKind::PUBLICATION_THROUGHPUT)).Times(1); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_publication_throughput_no_writer) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> writer_id = {0, 0, 0, 2}; std::string writer_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; // Build the writer GUID DatabaseDataQueue::StatisticsGuidPrefix writer_prefix; writer_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId writer_entity_id; writer_entity_id.value(writer_id); DatabaseDataQueue::StatisticsGuid writer_guid; writer_guid.guidPrefix(writer_prefix); writer_guid.entityId(writer_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsEntityData inner_data; inner_data.data(1.0); inner_data.guid(writer_guid); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity_data(inner_data); data->_d(EventKind::PUBLICATION_THROUGHPUT); // Precondition: The writer does not exist EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAWRITER, writer_guid_str)).Times(AnyNumber()) .WillOnce(Throw(BadParameter("Error"))); // Expectation: The insert method is never called, data dropped EXPECT_CALL(database, insert(_, _, _)).Times(0); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(_, _, _)).Times(0); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_subscription_throughput) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> reader_id = {0, 0, 0, 1}; std::string reader_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.1"; // Build the reader GUID DatabaseDataQueue::StatisticsGuidPrefix reader_prefix; reader_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId reader_entity_id; reader_entity_id.value(reader_id); DatabaseDataQueue::StatisticsGuid reader_guid; reader_guid.guidPrefix(reader_prefix); reader_guid.entityId(reader_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsEntityData inner_data; inner_data.data(1.0); inner_data.guid(reader_guid); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity_data(inner_data); data->_d(EventKind::SUBSCRIPTION_THROUGHPUT); // Precondition: The reader exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAREADER, reader_guid_str)).Times(1) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(1)))); // Expectation: The insert method is called with appropriate arguments InsertDataArgs args([&]( const EntityId& domain_id, const EntityId& entity_id, const StatisticsSample& sample) { EXPECT_EQ(entity_id, 1); EXPECT_EQ(domain_id, 0); EXPECT_EQ(sample.kind, DataKind::SUBSCRIPTION_THROUGHPUT); EXPECT_EQ(sample.src_ts, timestamp); EXPECT_EQ(dynamic_cast<const SubscriptionThroughputSample&>(sample).data, 1.0); }); EXPECT_CALL(database, insert(_, _, _)).Times(1) .WillOnce(Invoke(&args, &InsertDataArgs::insert)); // Expectation: The user is notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(EntityId(0), EntityId(1), DataKind::SUBSCRIPTION_THROUGHPUT)).Times(1); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_subscription_throughput_no_reder) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> reader_id = {0, 0, 0, 1}; std::string reader_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.1"; // Build the reader GUID DatabaseDataQueue::StatisticsGuidPrefix reader_prefix; reader_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId reader_entity_id; reader_entity_id.value(reader_id); DatabaseDataQueue::StatisticsGuid reader_guid; reader_guid.guidPrefix(reader_prefix); reader_guid.entityId(reader_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsEntityData inner_data; inner_data.data(1.0); inner_data.guid(reader_guid); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity_data(inner_data); data->_d(EventKind::SUBSCRIPTION_THROUGHPUT); // Precondition: The reader does not exist EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAREADER, reader_guid_str)).Times(AnyNumber()) .WillOnce(Throw(BadParameter("Error"))); // Expectation: The insert method is never called, data dropped EXPECT_CALL(database, insert(_, _, _)).Times(0); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(_, _, _)).Times(0); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_rtps_sent) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> writer_id = {0, 0, 0, 2}; std::array<uint8_t, 16> dst_locator_address = {16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; uint32_t dst_locator_port = 2048; std::string writer_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; std::string dst_locator_str = "TCPv4:[4.3.2.1]:2048"; // Build the writer GUID DatabaseDataQueue::StatisticsGuidPrefix writer_prefix; writer_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId writer_entity_id; writer_entity_id.value(writer_id); DatabaseDataQueue::StatisticsGuid writer_guid; writer_guid.guidPrefix(writer_prefix); writer_guid.entityId(writer_entity_id); // Build the locator address DatabaseDataQueue::StatisticsLocator dst_locator; dst_locator.kind(LOCATOR_KIND_TCPv4); dst_locator.port(dst_locator_port); dst_locator.address(dst_locator_address); // Build the Statistics data DatabaseDataQueue::StatisticsEntity2LocatorTraffic inner_data; inner_data.src_guid(writer_guid); inner_data.dst_locator(dst_locator); inner_data.packet_count(1024); inner_data.byte_count(2048); inner_data.byte_magnitude_order(10); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity2locator_traffic(inner_data); data->_d(EventKind::RTPS_SENT); // Precondition: The writer exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAWRITER, writer_guid_str)).Times(2) .WillRepeatedly(Return(std::make_pair(EntityId(0), EntityId(1)))); // Precondition: The locator exists and has ID 2 EXPECT_CALL(database, get_entities_by_name(EntityKind::LOCATOR, dst_locator_str)).Times(2) .WillRepeatedly(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(2))))); // Expectation: The insert method is called with appropriate arguments InsertDataArgs args1([&]( const EntityId& domain_id, const EntityId& entity_id, const StatisticsSample& sample) { EXPECT_EQ(entity_id, 1); EXPECT_EQ(domain_id, 0); EXPECT_EQ(sample.src_ts, timestamp); EXPECT_EQ(sample.kind, DataKind::RTPS_PACKETS_SENT); EXPECT_EQ(dynamic_cast<const RtpsPacketsSentSample&>(sample).count, 1024); EXPECT_EQ(dynamic_cast<const RtpsPacketsSentSample&>(sample).remote_locator, 2); }); InsertDataArgs args2([&]( const EntityId& domain_id, const EntityId& entity_id, const StatisticsSample& sample) { EXPECT_EQ(entity_id, 1); EXPECT_EQ(domain_id, 0); EXPECT_EQ(sample.src_ts, timestamp); EXPECT_EQ(sample.kind, DataKind::RTPS_BYTES_SENT); EXPECT_EQ(dynamic_cast<const RtpsBytesSentSample&>(sample).count, 2048); EXPECT_EQ(dynamic_cast<const RtpsBytesSentSample&>(sample).magnitude_order, 10); EXPECT_EQ(dynamic_cast<const RtpsBytesSentSample&>(sample).remote_locator, 2); }); EXPECT_CALL(database, insert(_, _, _)).Times(2) .WillOnce(Invoke(&args1, &InsertDataArgs::insert)) .WillOnce(Invoke(&args2, &InsertDataArgs::insert)); // Expectation: The user is notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(EntityId(0), EntityId(1), DataKind::RTPS_PACKETS_SENT)).Times(1); EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(EntityId(0), EntityId(1), DataKind::RTPS_BYTES_SENT)).Times(1); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_rtps_sent_no_writer) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> writer_id = {0, 0, 0, 2}; std::array<uint8_t, 16> dst_locator_address = {16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; uint32_t dst_locator_port = 2048; std::string writer_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; std::string dst_locator_str = "TCPv4:[4.3.2.1]:2048"; // Build the writer GUID DatabaseDataQueue::StatisticsGuidPrefix writer_prefix; writer_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId writer_entity_id; writer_entity_id.value(writer_id); DatabaseDataQueue::StatisticsGuid writer_guid; writer_guid.guidPrefix(writer_prefix); writer_guid.entityId(writer_entity_id); // Build the locator address DatabaseDataQueue::StatisticsLocator dst_locator; dst_locator.kind(LOCATOR_KIND_TCPv4); dst_locator.port(dst_locator_port); dst_locator.address(dst_locator_address); // Build the Statistics data DatabaseDataQueue::StatisticsEntity2LocatorTraffic inner_data; inner_data.src_guid(writer_guid); inner_data.dst_locator(dst_locator); inner_data.packet_count(1024); inner_data.byte_count(2048); inner_data.byte_magnitude_order(10); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity2locator_traffic(inner_data); data->_d(EventKind::RTPS_SENT); // Precondition: The writer does not exist EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAWRITER, writer_guid_str)).Times(AnyNumber()) .WillRepeatedly(Throw(BadParameter("Error"))); // Precondition: The locator exists and has ID 2 EXPECT_CALL(database, get_entities_by_name(EntityKind::LOCATOR, dst_locator_str)).Times(AnyNumber()) .WillRepeatedly(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(2))))); // Expectation: The insert method is never called, data dropped EXPECT_CALL(database, insert(_, _, _)).Times(0); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(_, _, _)).Times(0); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_rtps_sent_no_locator) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> writer_id = {0, 0, 0, 2}; std::array<uint8_t, 16> dst_locator_address = {16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; uint32_t dst_locator_port = 2048; std::string writer_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; std::string dst_locator_str = "TCPv4:[4.3.2.1]:2048"; // Build the writer GUID DatabaseDataQueue::StatisticsGuidPrefix writer_prefix; writer_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId writer_entity_id; writer_entity_id.value(writer_id); DatabaseDataQueue::StatisticsGuid writer_guid; writer_guid.guidPrefix(writer_prefix); writer_guid.entityId(writer_entity_id); // Build the locator address DatabaseDataQueue::StatisticsLocator dst_locator; dst_locator.kind(LOCATOR_KIND_TCPv4); dst_locator.port(dst_locator_port); dst_locator.address(dst_locator_address); // Build the Statistics data DatabaseDataQueue::StatisticsEntity2LocatorTraffic inner_data; inner_data.src_guid(writer_guid); inner_data.dst_locator(dst_locator); inner_data.packet_count(1024); inner_data.byte_count(2048); inner_data.byte_magnitude_order(10); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity2locator_traffic(inner_data); data->_d(EventKind::RTPS_SENT); // Precondition: The writer exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAWRITER, writer_guid_str)).Times(AnyNumber()) .WillRepeatedly(Return(std::make_pair(EntityId(0), EntityId(1)))); // Precondition: The destination locator does not exist the first time // Precondition: The destination locator exists and has ID 2 EXPECT_CALL(database, get_entities_by_name(EntityKind::LOCATOR, dst_locator_str)).Times(AnyNumber()) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>())) .WillRepeatedly(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(2))))); // Expectation: the remote locator is created and given ID 2 InsertEntityArgs insert_args([&]( std::shared_ptr<Entity> entity) { EXPECT_EQ(entity->kind, EntityKind::LOCATOR); EXPECT_EQ(entity->name, dst_locator_str); EXPECT_EQ(entity->alias, dst_locator_str); return EntityId(2); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args, &InsertEntityArgs::insert)); // Expectation: The insert method is called with appropriate arguments InsertDataArgs args1([&]( const EntityId& domain_id, const EntityId& entity_id, const StatisticsSample& sample) { EXPECT_EQ(entity_id, 1); EXPECT_EQ(domain_id, 0); EXPECT_EQ(sample.src_ts, timestamp); EXPECT_EQ(sample.kind, DataKind::RTPS_PACKETS_SENT); EXPECT_EQ(dynamic_cast<const RtpsPacketsSentSample&>(sample).count, 1024); EXPECT_EQ(dynamic_cast<const RtpsPacketsSentSample&>(sample).remote_locator, 2); }); InsertDataArgs args2([&]( const EntityId& domain_id, const EntityId& entity_id, const StatisticsSample& sample) { EXPECT_EQ(entity_id, 1); EXPECT_EQ(domain_id, 0); EXPECT_EQ(sample.src_ts, timestamp); EXPECT_EQ(sample.kind, DataKind::RTPS_BYTES_SENT); EXPECT_EQ(dynamic_cast<const RtpsBytesSentSample&>(sample).count, 2048); EXPECT_EQ(dynamic_cast<const RtpsBytesSentSample&>(sample).magnitude_order, 10); EXPECT_EQ(dynamic_cast<const RtpsBytesSentSample&>(sample).remote_locator, 2); }); EXPECT_CALL(database, insert(_, _, _)).Times(2) .WillOnce(Invoke(&args1, &InsertDataArgs::insert)) .WillOnce(Invoke(&args2, &InsertDataArgs::insert)); // Expectation: The user is notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(EntityId(0), EntityId(1), DataKind::RTPS_PACKETS_SENT)).Times(1); EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(EntityId(0), EntityId(1), DataKind::RTPS_BYTES_SENT)).Times(1); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_rtps_lost) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> writer_id = {0, 0, 0, 2}; std::array<uint8_t, 16> dst_locator_address = {16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; uint32_t dst_locator_port = 2048; std::string writer_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; std::string dst_locator_str = "TCPv4:[4.3.2.1]:2048"; // Build the writer GUID DatabaseDataQueue::StatisticsGuidPrefix writer_prefix; writer_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId writer_entity_id; writer_entity_id.value(writer_id); DatabaseDataQueue::StatisticsGuid writer_guid; writer_guid.guidPrefix(writer_prefix); writer_guid.entityId(writer_entity_id); // Build the locator address DatabaseDataQueue::StatisticsLocator dst_locator; dst_locator.kind(LOCATOR_KIND_TCPv4); dst_locator.port(dst_locator_port); dst_locator.address(dst_locator_address); // Build the Statistics data DatabaseDataQueue::StatisticsEntity2LocatorTraffic inner_data; inner_data.src_guid(writer_guid); inner_data.dst_locator(dst_locator); inner_data.packet_count(1024); inner_data.byte_count(2048); inner_data.byte_magnitude_order(10); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity2locator_traffic(inner_data); data->_d(EventKind::RTPS_LOST); // Precondition: The writer exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAWRITER, writer_guid_str)).Times(2) .WillRepeatedly(Return(std::make_pair(EntityId(0), EntityId(1)))); // Precondition: The locator exists and has ID 2 EXPECT_CALL(database, get_entities_by_name(EntityKind::LOCATOR, dst_locator_str)).Times(2) .WillRepeatedly(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(2))))); // Expectation: The insert method is called with appropriate arguments InsertDataArgs args1([&]( const EntityId& domain_id, const EntityId& entity_id, const StatisticsSample& sample) { EXPECT_EQ(entity_id, 1); EXPECT_EQ(domain_id, 0); EXPECT_EQ(sample.src_ts, timestamp); EXPECT_EQ(sample.kind, DataKind::RTPS_PACKETS_LOST); EXPECT_EQ(dynamic_cast<const RtpsPacketsLostSample&>(sample).count, 1024); EXPECT_EQ(dynamic_cast<const RtpsPacketsLostSample&>(sample).remote_locator, 2); }); InsertDataArgs args2([&]( const EntityId& domain_id, const EntityId& entity_id, const StatisticsSample& sample) { EXPECT_EQ(entity_id, 1); EXPECT_EQ(domain_id, 0); EXPECT_EQ(sample.src_ts, timestamp); EXPECT_EQ(sample.kind, DataKind::RTPS_BYTES_LOST); EXPECT_EQ(dynamic_cast<const RtpsBytesLostSample&>(sample).count, 2048); EXPECT_EQ(dynamic_cast<const RtpsBytesLostSample&>(sample).magnitude_order, 10); EXPECT_EQ(dynamic_cast<const RtpsBytesLostSample&>(sample).remote_locator, 2); }); EXPECT_CALL(database, insert(_, _, _)).Times(2) .WillOnce(Invoke(&args1, &InsertDataArgs::insert)) .WillOnce(Invoke(&args2, &InsertDataArgs::insert)); // Expectation: The user is notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(EntityId(0), EntityId(1), DataKind::RTPS_PACKETS_LOST)).Times(1); EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(EntityId(0), EntityId(1), DataKind::RTPS_BYTES_LOST)).Times(1); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_rtps_lost_no_writer) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> writer_id = {0, 0, 0, 2}; std::array<uint8_t, 16> dst_locator_address = {16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; uint32_t dst_locator_port = 2048; std::string writer_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; std::string dst_locator_str = "TCPv4:[4.3.2.1]:2048"; // Build the writer GUID DatabaseDataQueue::StatisticsGuidPrefix writer_prefix; writer_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId writer_entity_id; writer_entity_id.value(writer_id); DatabaseDataQueue::StatisticsGuid writer_guid; writer_guid.guidPrefix(writer_prefix); writer_guid.entityId(writer_entity_id); // Build the locator address DatabaseDataQueue::StatisticsLocator dst_locator; dst_locator.kind(LOCATOR_KIND_TCPv4); dst_locator.port(dst_locator_port); dst_locator.address(dst_locator_address); // Build the Statistics data DatabaseDataQueue::StatisticsEntity2LocatorTraffic inner_data; inner_data.src_guid(writer_guid); inner_data.dst_locator(dst_locator); inner_data.packet_count(1024); inner_data.byte_count(2048); inner_data.byte_magnitude_order(10); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity2locator_traffic(inner_data); data->_d(EventKind::RTPS_LOST); // Precondition: The writer does not exist EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAWRITER, writer_guid_str)).Times(AnyNumber()) .WillRepeatedly(Throw(BadParameter("Error"))); // Precondition: The locator exists and has ID 2 EXPECT_CALL(database, get_entities_by_name(EntityKind::LOCATOR, dst_locator_str)).Times(AnyNumber()) .WillRepeatedly(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(2))))); // Expectation: The insert method is never called, data dropped EXPECT_CALL(database, insert(_, _, _)).Times(0); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(_, _, _)).Times(0); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_rtps_lost_no_locator) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> writer_id = {0, 0, 0, 2}; std::array<uint8_t, 16> dst_locator_address = {16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; uint32_t dst_locator_port = 2048; std::string writer_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; std::string dst_locator_str = "TCPv4:[4.3.2.1]:2048"; // Build the writer GUID DatabaseDataQueue::StatisticsGuidPrefix writer_prefix; writer_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId writer_entity_id; writer_entity_id.value(writer_id); DatabaseDataQueue::StatisticsGuid writer_guid; writer_guid.guidPrefix(writer_prefix); writer_guid.entityId(writer_entity_id); // Build the locator address DatabaseDataQueue::StatisticsLocator dst_locator; dst_locator.kind(LOCATOR_KIND_TCPv4); dst_locator.port(dst_locator_port); dst_locator.address(dst_locator_address); // Build the Statistics data DatabaseDataQueue::StatisticsEntity2LocatorTraffic inner_data; inner_data.src_guid(writer_guid); inner_data.dst_locator(dst_locator); inner_data.packet_count(1024); inner_data.byte_count(2048); inner_data.byte_magnitude_order(10); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity2locator_traffic(inner_data); data->_d(EventKind::RTPS_LOST); // Precondition: The writer exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAWRITER, writer_guid_str)).Times(AnyNumber()) .WillRepeatedly(Return(std::make_pair(EntityId(0), EntityId(1)))); // Precondition: The destination locator does not exist the first time // Precondition: The destination locator exists and has ID 2 EXPECT_CALL(database, get_entities_by_name(EntityKind::LOCATOR, dst_locator_str)).Times(AnyNumber()) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>())) .WillRepeatedly(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(2))))); // Expectation: the remote locator is created and given ID 2 InsertEntityArgs insert_args([&]( std::shared_ptr<Entity> entity) { EXPECT_EQ(entity->kind, EntityKind::LOCATOR); EXPECT_EQ(entity->name, dst_locator_str); EXPECT_EQ(entity->alias, dst_locator_str); return EntityId(2); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args, &InsertEntityArgs::insert)); // Expectation: The insert method is called with appropriate arguments InsertDataArgs args1([&]( const EntityId& domain_id, const EntityId& entity_id, const StatisticsSample& sample) { EXPECT_EQ(entity_id, 1); EXPECT_EQ(domain_id, 0); EXPECT_EQ(sample.src_ts, timestamp); EXPECT_EQ(sample.kind, DataKind::RTPS_PACKETS_LOST); EXPECT_EQ(dynamic_cast<const RtpsPacketsLostSample&>(sample).count, 1024); EXPECT_EQ(dynamic_cast<const RtpsPacketsLostSample&>(sample).remote_locator, 2); }); InsertDataArgs args2([&]( const EntityId& domain_id, const EntityId& entity_id, const StatisticsSample& sample) { EXPECT_EQ(entity_id, 1); EXPECT_EQ(domain_id, 0); EXPECT_EQ(sample.src_ts, timestamp); EXPECT_EQ(sample.kind, DataKind::RTPS_BYTES_LOST); EXPECT_EQ(dynamic_cast<const RtpsBytesLostSample&>(sample).count, 2048); EXPECT_EQ(dynamic_cast<const RtpsBytesLostSample&>(sample).magnitude_order, 10); EXPECT_EQ(dynamic_cast<const RtpsBytesLostSample&>(sample).remote_locator, 2); }); EXPECT_CALL(database, insert(_, _, _)).Times(2) .WillOnce(Invoke(&args1, &InsertDataArgs::insert)) .WillOnce(Invoke(&args2, &InsertDataArgs::insert)); // Expectation: The user is notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(EntityId(0), EntityId(1), DataKind::RTPS_PACKETS_LOST)).Times(1); EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(EntityId(0), EntityId(1), DataKind::RTPS_BYTES_LOST)).Times(1); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_rtps_bytes_no_writer) { std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> writer_id = {0, 0, 0, 2}; std::array<uint8_t, 16> dst_locator_address = {16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; uint32_t dst_locator_port = 2048; std::string writer_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; std::string dst_locator_str = "TCPv4:[4.3.2.1]:2048"; // Build the writer GUID DatabaseDataQueue::StatisticsGuidPrefix writer_prefix; writer_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId writer_entity_id; writer_entity_id.value(writer_id); DatabaseDataQueue::StatisticsGuid writer_guid; writer_guid.guidPrefix(writer_prefix); writer_guid.entityId(writer_entity_id); // Build the locator address DatabaseDataQueue::StatisticsLocator dst_locator; dst_locator.kind(LOCATOR_KIND_TCPv4); dst_locator.port(dst_locator_port); dst_locator.address(dst_locator_address); // Build the Statistics data DatabaseDataQueue::StatisticsEntity2LocatorTraffic inner_data; inner_data.src_guid(writer_guid); inner_data.dst_locator(dst_locator); inner_data.packet_count(1024); inner_data.byte_count(2048); inner_data.byte_magnitude_order(10); // Precondition: The writer does not exist EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAWRITER, writer_guid_str)).Times(AnyNumber()) .WillRepeatedly(Throw(BadParameter("Error"))); // Precondition: The locator exists and has ID 2 EXPECT_CALL(database, get_entities_by_name(EntityKind::LOCATOR, dst_locator_str)).Times(AnyNumber()) .WillRepeatedly(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(2))))); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(_, _, _)).Times(0); // Add to the queue and wait to be processed ByteToLocatorCountSample sample; EntityId domain; EntityId entity; EXPECT_THROW(data_queue.do_process_sample_type(domain, entity, EntityKind::DATAWRITER, sample, inner_data), Error); } TEST_F(database_queue_tests, push_rtps_bytes_no_locator) { std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> writer_id = {0, 0, 0, 2}; std::array<uint8_t, 16> dst_locator_address = {16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; uint32_t dst_locator_port = 2048; std::string writer_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; std::string dst_locator_str = "TCPv4:[4.3.2.1]:2048"; // Build the writer GUID DatabaseDataQueue::StatisticsGuidPrefix writer_prefix; writer_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId writer_entity_id; writer_entity_id.value(writer_id); DatabaseDataQueue::StatisticsGuid writer_guid; writer_guid.guidPrefix(writer_prefix); writer_guid.entityId(writer_entity_id); // Build the locator address DatabaseDataQueue::StatisticsLocator dst_locator; dst_locator.kind(LOCATOR_KIND_TCPv4); dst_locator.port(dst_locator_port); dst_locator.address(dst_locator_address); // Build the Statistics data DatabaseDataQueue::StatisticsEntity2LocatorTraffic inner_data; inner_data.src_guid(writer_guid); inner_data.dst_locator(dst_locator); inner_data.packet_count(1024); inner_data.byte_count(2048); inner_data.byte_magnitude_order(10); // Precondition: The writer exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAWRITER, writer_guid_str)).Times(AnyNumber()) .WillRepeatedly(Return(std::make_pair(EntityId(0), EntityId(1)))); // Precondition: The locator does not exist EXPECT_CALL(database, get_entities_by_name(EntityKind::LOCATOR, dst_locator_str)).Times(AnyNumber()) .WillRepeatedly(Return(std::vector<std::pair<EntityId, EntityId>>())); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(_, _, _)).Times(0); // Add to the queue and wait to be processed // Add to the queue and wait to be processed ByteToLocatorCountSample sample; EntityId domain; EntityId entity; EXPECT_THROW(data_queue.do_process_sample_type(domain, entity, EntityKind::DATAWRITER, sample, inner_data), Error); } TEST_F(database_queue_tests, push_resent_datas) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> writer_id = {0, 0, 0, 2}; std::string writer_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; // Build the writer GUID DatabaseDataQueue::StatisticsGuidPrefix writer_prefix; writer_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId writer_entity_id; writer_entity_id.value(writer_id); DatabaseDataQueue::StatisticsGuid writer_guid; writer_guid.guidPrefix(writer_prefix); writer_guid.entityId(writer_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsEntityCount inner_data; inner_data.guid(writer_guid); inner_data.count(1024); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity_count(inner_data); data->_d(EventKind::RESENT_DATAS); // Precondition: The writer exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAWRITER, writer_guid_str)).Times(1) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(1)))); // Expectation: The insert method is called with appropriate arguments InsertDataArgs args([&]( const EntityId& domain_id, const EntityId& entity_id, const StatisticsSample& sample) { EXPECT_EQ(entity_id, 1); EXPECT_EQ(domain_id, 0); EXPECT_EQ(sample.src_ts, timestamp); EXPECT_EQ(sample.kind, DataKind::RESENT_DATA); EXPECT_EQ(dynamic_cast<const ResentDataSample&>(sample).count, 1024); }); EXPECT_CALL(database, insert(_, _, _)).Times(1) .WillOnce(Invoke(&args, &InsertDataArgs::insert)); // Expectation: The user is notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(EntityId(0), EntityId(1), DataKind::RESENT_DATA)).Times(1); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_resent_datas_no_writer) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> writer_id = {0, 0, 0, 2}; std::string writer_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; // Build the writer GUID DatabaseDataQueue::StatisticsGuidPrefix writer_prefix; writer_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId writer_entity_id; writer_entity_id.value(writer_id); DatabaseDataQueue::StatisticsGuid writer_guid; writer_guid.guidPrefix(writer_prefix); writer_guid.entityId(writer_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsEntityCount inner_data; inner_data.guid(writer_guid); inner_data.count(1024); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity_count(inner_data); data->_d(EventKind::RESENT_DATAS); // Precondition: The writer does not exist EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAWRITER, writer_guid_str)).Times(AnyNumber()) .WillOnce(Throw(BadParameter("Error"))); // Expectation: The insert method is never called, data dropped EXPECT_CALL(database, insert(_, _, _)).Times(0); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(_, _, _)).Times(0); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_heartbeat_count) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> writer_id = {0, 0, 0, 2}; std::string writer_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; // Build the writer GUID DatabaseDataQueue::StatisticsGuidPrefix writer_prefix; writer_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId writer_entity_id; writer_entity_id.value(writer_id); DatabaseDataQueue::StatisticsGuid writer_guid; writer_guid.guidPrefix(writer_prefix); writer_guid.entityId(writer_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsEntityCount inner_data; inner_data.guid(writer_guid); inner_data.count(1024); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity_count(inner_data); data->_d(EventKind::HEARTBEAT_COUNT); // Precondition: The writer exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAWRITER, writer_guid_str)).Times(1) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(1)))); // Expectation: The insert method is called with appropriate arguments InsertDataArgs args([&]( const EntityId& domain_id, const EntityId& entity_id, const StatisticsSample& sample) { EXPECT_EQ(entity_id, 1); EXPECT_EQ(domain_id, 0); EXPECT_EQ(sample.src_ts, timestamp); EXPECT_EQ(sample.kind, DataKind::HEARTBEAT_COUNT); EXPECT_EQ(dynamic_cast<const HeartbeatCountSample&>(sample).count, 1024); }); EXPECT_CALL(database, insert(_, _, _)).Times(1) .WillOnce(Invoke(&args, &InsertDataArgs::insert)); // Expectation: The user is notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(EntityId(0), EntityId(1), DataKind::HEARTBEAT_COUNT)).Times(1); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_heartbeat_count_no_writer) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> writer_id = {0, 0, 0, 2}; std::string writer_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; // Build the writer GUID DatabaseDataQueue::StatisticsGuidPrefix writer_prefix; writer_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId writer_entity_id; writer_entity_id.value(writer_id); DatabaseDataQueue::StatisticsGuid writer_guid; writer_guid.guidPrefix(writer_prefix); writer_guid.entityId(writer_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsEntityCount inner_data; inner_data.guid(writer_guid); inner_data.count(1024); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity_count(inner_data); data->_d(EventKind::HEARTBEAT_COUNT); // Precondition: The writer does not exist EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAWRITER, writer_guid_str)).Times(AnyNumber()) .WillOnce(Throw(BadParameter("Error"))); // Expectation: The insert method is never called, data dropped EXPECT_CALL(database, insert(_, _, _)).Times(0); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(_, _, _)).Times(0); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_acknack_count) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> reader_id = {0, 0, 0, 1}; std::string reader_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.1"; // Build the reader GUID DatabaseDataQueue::StatisticsGuidPrefix reader_prefix; reader_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId reader_entity_id; reader_entity_id.value(reader_id); DatabaseDataQueue::StatisticsGuid reader_guid; reader_guid.guidPrefix(reader_prefix); reader_guid.entityId(reader_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsEntityCount inner_data; inner_data.guid(reader_guid); inner_data.count(1024); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity_count(inner_data); data->_d(EventKind::ACKNACK_COUNT); // Precondition: The reader exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAREADER, reader_guid_str)).Times(1) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(1)))); // Expectation: The insert method is called with appropriate arguments InsertDataArgs args([&]( const EntityId& domain_id, const EntityId& entity_id, const StatisticsSample& sample) { EXPECT_EQ(entity_id, 1); EXPECT_EQ(domain_id, 0); EXPECT_EQ(sample.src_ts, timestamp); EXPECT_EQ(sample.kind, DataKind::ACKNACK_COUNT); EXPECT_EQ(dynamic_cast<const AcknackCountSample&>(sample).count, 1024); }); EXPECT_CALL(database, insert(_, _, _)).Times(1) .WillOnce(Invoke(&args, &InsertDataArgs::insert)); // Expectation: The user is notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(EntityId(0), EntityId(1), DataKind::ACKNACK_COUNT)).Times(1); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_acknack_count_no_reader) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> reader_id = {0, 0, 0, 1}; std::string reader_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.1"; // Build the reader GUID DatabaseDataQueue::StatisticsGuidPrefix reader_prefix; reader_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId reader_entity_id; reader_entity_id.value(reader_id); DatabaseDataQueue::StatisticsGuid reader_guid; reader_guid.guidPrefix(reader_prefix); reader_guid.entityId(reader_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsEntityCount inner_data; inner_data.guid(reader_guid); inner_data.count(1024); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity_count(inner_data); data->_d(EventKind::ACKNACK_COUNT); // Precondition: The reader does not exist EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAREADER, reader_guid_str)).Times(AnyNumber()) .WillOnce(Throw(BadParameter("Error"))); // Expectation: The insert method is never called, data dropped EXPECT_CALL(database, insert(_, _, _)).Times(0); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(_, _, _)).Times(0); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_nackfrag_count) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> reader_id = {0, 0, 0, 1}; std::string reader_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.1"; // Build the reader GUID DatabaseDataQueue::StatisticsGuidPrefix reader_prefix; reader_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId reader_entity_id; reader_entity_id.value(reader_id); DatabaseDataQueue::StatisticsGuid reader_guid; reader_guid.guidPrefix(reader_prefix); reader_guid.entityId(reader_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsEntityCount inner_data; inner_data.guid(reader_guid); inner_data.count(1024); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity_count(inner_data); data->_d(EventKind::NACKFRAG_COUNT); // Precondition: The reader exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAREADER, reader_guid_str)).Times(1) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(1)))); // Expectation: The insert method is called with appropriate arguments InsertDataArgs args([&]( const EntityId& domain_id, const EntityId& entity_id, const StatisticsSample& sample) { EXPECT_EQ(entity_id, 1); EXPECT_EQ(domain_id, 0); EXPECT_EQ(sample.src_ts, timestamp); EXPECT_EQ(sample.kind, DataKind::NACKFRAG_COUNT); EXPECT_EQ(dynamic_cast<const NackfragCountSample&>(sample).count, 1024); }); EXPECT_CALL(database, insert(_, _, _)).Times(1) .WillOnce(Invoke(&args, &InsertDataArgs::insert)); // Expectation: The user is notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(EntityId(0), EntityId(1), DataKind::NACKFRAG_COUNT)).Times(1); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_nackfrag_count_no_reader) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> reader_id = {0, 0, 0, 1}; std::string reader_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.1"; // Build the reader GUID DatabaseDataQueue::StatisticsGuidPrefix reader_prefix; reader_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId reader_entity_id; reader_entity_id.value(reader_id); DatabaseDataQueue::StatisticsGuid reader_guid; reader_guid.guidPrefix(reader_prefix); reader_guid.entityId(reader_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsEntityCount inner_data; inner_data.guid(reader_guid); inner_data.count(1024); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity_count(inner_data); data->_d(EventKind::NACKFRAG_COUNT); // Precondition: The reader does not exist EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAREADER, reader_guid_str)).Times(AnyNumber()) .WillOnce(Throw(BadParameter("Error"))); // Expectation: The insert method is never called, data dropped EXPECT_CALL(database, insert(_, _, _)).Times(0); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(_, _, _)).Times(0); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_gap_count) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> writer_id = {0, 0, 0, 2}; std::string writer_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; // Build the writer GUID DatabaseDataQueue::StatisticsGuidPrefix writer_prefix; writer_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId writer_entity_id; writer_entity_id.value(writer_id); DatabaseDataQueue::StatisticsGuid writer_guid; writer_guid.guidPrefix(writer_prefix); writer_guid.entityId(writer_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsEntityCount inner_data; inner_data.guid(writer_guid); inner_data.count(1024); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity_count(inner_data); data->_d(EventKind::GAP_COUNT); // Precondition: The writer exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAWRITER, writer_guid_str)).Times(1) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(1)))); // Expectation: The insert method is called with appropriate arguments InsertDataArgs args([&]( const EntityId& domain_id, const EntityId& entity_id, const StatisticsSample& sample) { EXPECT_EQ(entity_id, 1); EXPECT_EQ(domain_id, 0); EXPECT_EQ(sample.src_ts, timestamp); EXPECT_EQ(sample.kind, DataKind::GAP_COUNT); EXPECT_EQ(dynamic_cast<const GapCountSample&>(sample).count, 1024); }); EXPECT_CALL(database, insert(_, _, _)).Times(1) .WillOnce(Invoke(&args, &InsertDataArgs::insert)); // Expectation: The user is notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(EntityId(0), EntityId(1), DataKind::GAP_COUNT)).Times(1); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_gap_count_no_writer) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> writer_id = {0, 0, 0, 2}; std::string writer_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; // Build the writer GUID DatabaseDataQueue::StatisticsGuidPrefix writer_prefix; writer_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId writer_entity_id; writer_entity_id.value(writer_id); DatabaseDataQueue::StatisticsGuid writer_guid; writer_guid.guidPrefix(writer_prefix); writer_guid.entityId(writer_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsEntityCount inner_data; inner_data.guid(writer_guid); inner_data.count(1024); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity_count(inner_data); data->_d(EventKind::GAP_COUNT); // Precondition: The writer does not exist EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAWRITER, writer_guid_str)).Times(AnyNumber()) .WillOnce(Throw(BadParameter("Error"))); // Expectation: The insert method is never called, data dropped EXPECT_CALL(database, insert(_, _, _)).Times(0); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(_, _, _)).Times(0); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_data_count) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> writer_id = {0, 0, 0, 2}; std::string writer_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; // Build the writer GUID DatabaseDataQueue::StatisticsGuidPrefix writer_prefix; writer_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId writer_entity_id; writer_entity_id.value(writer_id); DatabaseDataQueue::StatisticsGuid writer_guid; writer_guid.guidPrefix(writer_prefix); writer_guid.entityId(writer_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsEntityCount inner_data; inner_data.guid(writer_guid); inner_data.count(1024); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity_count(inner_data); data->_d(EventKind::DATA_COUNT); // Precondition: The writer exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAWRITER, writer_guid_str)).Times(1) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(1)))); // Expectation: The insert method is called with appropriate arguments InsertDataArgs args([&]( const EntityId& domain_id, const EntityId& entity_id, const StatisticsSample& sample) { EXPECT_EQ(entity_id, 1); EXPECT_EQ(domain_id, 0); EXPECT_EQ(sample.src_ts, timestamp); EXPECT_EQ(sample.kind, DataKind::DATA_COUNT); EXPECT_EQ(dynamic_cast<const DataCountSample&>(sample).count, 1024); }); EXPECT_CALL(database, insert(_, _, _)).Times(1) .WillOnce(Invoke(&args, &InsertDataArgs::insert)); // Expectation: The user is notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(EntityId(0), EntityId(1), DataKind::DATA_COUNT)).Times(1); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_data_count_no_writer) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> writer_id = {0, 0, 0, 2}; std::string writer_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; // Build the writer GUID DatabaseDataQueue::StatisticsGuidPrefix writer_prefix; writer_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId writer_entity_id; writer_entity_id.value(writer_id); DatabaseDataQueue::StatisticsGuid writer_guid; writer_guid.guidPrefix(writer_prefix); writer_guid.entityId(writer_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsEntityCount inner_data; inner_data.guid(writer_guid); inner_data.count(1024); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity_count(inner_data); data->_d(EventKind::DATA_COUNT); // Precondition: The writer does not exist EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAWRITER, writer_guid_str)).Times(AnyNumber()) .WillOnce(Throw(BadParameter("Error"))); // Expectation: The insert method is never called, data dropped EXPECT_CALL(database, insert(_, _, _)).Times(0); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(_, _, _)).Times(0); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_pdp_count) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> participant_id = {0, 0, 0, 0}; std::string participant_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.0"; // Build the participant GUID DatabaseDataQueue::StatisticsGuidPrefix participant_prefix; participant_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId participant_entity_id; participant_entity_id.value(participant_id); DatabaseDataQueue::StatisticsGuid participant_guid; participant_guid.guidPrefix(participant_prefix); participant_guid.entityId(participant_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsEntityCount inner_data; inner_data.guid(participant_guid); inner_data.count(1024); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity_count(inner_data); data->_d(EventKind::PDP_PACKETS); // Precondition: The participant exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::PARTICIPANT, participant_guid_str)).Times(1) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(1)))); // Expectation: The insert method is called with appropriate arguments InsertDataArgs args([&]( const EntityId& domain_id, const EntityId& entity_id, const StatisticsSample& sample) { EXPECT_EQ(entity_id, 1); EXPECT_EQ(domain_id, 0); EXPECT_EQ(sample.src_ts, timestamp); EXPECT_EQ(sample.kind, DataKind::PDP_PACKETS); EXPECT_EQ(dynamic_cast<const PdpCountSample&>(sample).count, 1024); }); EXPECT_CALL(database, insert(_, _, _)).Times(1) .WillOnce(Invoke(&args, &InsertDataArgs::insert)); // Expectation: The user is notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(EntityId(0), EntityId(1), DataKind::PDP_PACKETS)).Times(1); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_pdp_count_no_participant) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> participant_id = {0, 0, 0, 0}; std::string participant_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.0"; // Build the participant GUID DatabaseDataQueue::StatisticsGuidPrefix participant_prefix; participant_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId participant_entity_id; participant_entity_id.value(participant_id); DatabaseDataQueue::StatisticsGuid participant_guid; participant_guid.guidPrefix(participant_prefix); participant_guid.entityId(participant_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsEntityCount inner_data; inner_data.guid(participant_guid); inner_data.count(1024); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity_count(inner_data); data->_d(EventKind::PDP_PACKETS); // Precondition: The participant does not exist EXPECT_CALL(database, get_entity_by_guid(EntityKind::PARTICIPANT, participant_guid_str)).Times(AnyNumber()) .WillOnce(Throw(BadParameter("Error"))); // Expectation: The insert method is never called, data dropped EXPECT_CALL(database, insert(_, _, _)).Times(0); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(_, _, _)).Times(0); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_edp_count) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> participant_id = {0, 0, 0, 0}; std::string participant_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.0"; // Build the participant GUID DatabaseDataQueue::StatisticsGuidPrefix participant_prefix; participant_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId participant_entity_id; participant_entity_id.value(participant_id); DatabaseDataQueue::StatisticsGuid participant_guid; participant_guid.guidPrefix(participant_prefix); participant_guid.entityId(participant_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsEntityCount inner_data; inner_data.guid(participant_guid); inner_data.count(1024); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity_count(inner_data); data->_d(EventKind::EDP_PACKETS); // Precondition: The participant exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::PARTICIPANT, participant_guid_str)).Times(1) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(1)))); // Expectation: The insert method is called with appropriate arguments InsertDataArgs args([&]( const EntityId& domain_id, const EntityId& entity_id, const StatisticsSample& sample) { EXPECT_EQ(entity_id, 1); EXPECT_EQ(domain_id, 0); EXPECT_EQ(sample.src_ts, timestamp); EXPECT_EQ(sample.kind, DataKind::EDP_PACKETS); EXPECT_EQ(dynamic_cast<const EdpCountSample&>(sample).count, 1024); }); EXPECT_CALL(database, insert(_, _, _)).Times(1) .WillOnce(Invoke(&args, &InsertDataArgs::insert)); // Expectation: The user is notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(EntityId(0), EntityId(1), DataKind::EDP_PACKETS)).Times(1); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_edp_count_no_participant) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> participant_id = {0, 0, 0, 0}; std::string participant_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.0"; // Build the participant GUID DatabaseDataQueue::StatisticsGuidPrefix participant_prefix; participant_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId participant_entity_id; participant_entity_id.value(participant_id); DatabaseDataQueue::StatisticsGuid participant_guid; participant_guid.guidPrefix(participant_prefix); participant_guid.entityId(participant_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsEntityCount inner_data; inner_data.guid(participant_guid); inner_data.count(1024); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->entity_count(inner_data); data->_d(EventKind::EDP_PACKETS); // Precondition: The participant does not exist EXPECT_CALL(database, get_entity_by_guid(EntityKind::PARTICIPANT, participant_guid_str)).Times(AnyNumber()) .WillOnce(Throw(BadParameter("Error"))); // Expectation: The insert method is never called, data dropped EXPECT_CALL(database, insert(_, _, _)).Times(0); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(_, _, _)).Times(0); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_discovery_times) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> participant_id = {0, 0, 0, 0}; std::array<uint8_t, 4> entity_id = {0, 0, 0, 1}; // discovery time must be rounded to tenths of nanosecond to avoid truncation by // windows system_clock uint64_t discovery_time = 1000; std::string participant_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.0"; std::string remote_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.1"; std::chrono::system_clock::time_point discovery_timestamp = eprosima::statistics_backend::nanoseconds_to_systemclock(discovery_time); // Build the participant GUID DatabaseDataQueue::StatisticsGuidPrefix participant_prefix; participant_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId participant_entity_id; participant_entity_id.value(participant_id); DatabaseDataQueue::StatisticsGuid participant_guid; participant_guid.guidPrefix(participant_prefix); participant_guid.entityId(participant_entity_id); // Build the remote GUID DatabaseDataQueue::StatisticsGuidPrefix remote_prefix; remote_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId remote_entity_id; remote_entity_id.value(entity_id); DatabaseDataQueue::StatisticsGuid remote_guid; remote_guid.guidPrefix(remote_prefix); remote_guid.entityId(remote_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsDiscoveryTime inner_data; inner_data.local_participant_guid(participant_guid); inner_data.remote_entity_guid(remote_guid); inner_data.time(discovery_time); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->discovery_time(inner_data); data->_d(EventKind::DISCOVERED_ENTITY); // Precondition: The participant exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::PARTICIPANT, participant_guid_str)).Times(1) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(1)))); // Precondition: The remote entity exists and has ID 2 EXPECT_CALL(database, get_entity_by_guid(EntityKind::PARTICIPANT, remote_guid_str)).Times(1) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(2)))); // Expectation: The insert method is called with appropriate arguments InsertDataArgs args([&]( const EntityId& domain_id, const EntityId& entity_id, const StatisticsSample& sample) { EXPECT_EQ(entity_id, 1); EXPECT_EQ(domain_id, 0); EXPECT_EQ(sample.src_ts, timestamp); EXPECT_EQ(sample.kind, DataKind::DISCOVERY_TIME); EXPECT_EQ(dynamic_cast<const DiscoveryTimeSample&>(sample).remote_entity, 2); EXPECT_EQ(dynamic_cast<const DiscoveryTimeSample&>(sample).time, discovery_timestamp); }); // Expectation: The user is notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(EntityId(0), EntityId(1), DataKind::DISCOVERY_TIME)).Times(1); EXPECT_CALL(database, insert(_, _, _)).Times(1) .WillOnce(Invoke(&args, &InsertDataArgs::insert)); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_discovery_times_no_participant) { std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> participant_id = {0, 0, 0, 0}; std::array<uint8_t, 4> entity_id = {0, 0, 0, 1}; std::string participant_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.0"; std::string remote_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.1"; long long discovery_time = 1024; std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); // Build the participant GUID DatabaseDataQueue::StatisticsGuidPrefix participant_prefix; participant_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId participant_entity_id; participant_entity_id.value(participant_id); DatabaseDataQueue::StatisticsGuid participant_guid; participant_guid.guidPrefix(participant_prefix); participant_guid.entityId(participant_entity_id); // Build the remote GUID DatabaseDataQueue::StatisticsGuidPrefix remote_prefix; remote_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId remote_entity_id; remote_entity_id.value(entity_id); DatabaseDataQueue::StatisticsGuid remote_guid; remote_guid.guidPrefix(remote_prefix); remote_guid.entityId(remote_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsDiscoveryTime inner_data; inner_data.local_participant_guid(participant_guid); inner_data.remote_entity_guid(remote_guid); inner_data.time(discovery_time); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->discovery_time(inner_data); data->_d(EventKind::DISCOVERED_ENTITY); // Precondition: The participant does not exist EXPECT_CALL(database, get_entity_by_guid(EntityKind::PARTICIPANT, participant_guid_str)).Times(AnyNumber()) .WillOnce(Throw(BadParameter("Error"))); // Precondition: The remote entity exists and has ID 2 EXPECT_CALL(database, get_entity_by_guid(EntityKind::PARTICIPANT, remote_guid_str)).Times(AnyNumber()) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(2)))); // Expectation: The insert method is never called, data dropped EXPECT_CALL(database, insert(_, _, _)).Times(0); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(_, _, _)).Times(0); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_discovery_times_no_entity) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> participant_id = {0, 0, 0, 0}; std::array<uint8_t, 4> entity_id = {0, 0, 0, 1}; uint64_t discovery_time = 1024; std::string participant_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.0"; std::string remote_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.1"; // Build the participant GUID DatabaseDataQueue::StatisticsGuidPrefix participant_prefix; participant_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId participant_entity_id; participant_entity_id.value(participant_id); DatabaseDataQueue::StatisticsGuid participant_guid; participant_guid.guidPrefix(participant_prefix); participant_guid.entityId(participant_entity_id); // Build the remote GUID DatabaseDataQueue::StatisticsGuidPrefix remote_prefix; remote_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId remote_entity_id; remote_entity_id.value(entity_id); DatabaseDataQueue::StatisticsGuid remote_guid; remote_guid.guidPrefix(remote_prefix); remote_guid.entityId(remote_entity_id); // Build the Statistics data DatabaseDataQueue::StatisticsDiscoveryTime inner_data; inner_data.local_participant_guid(participant_guid); inner_data.remote_entity_guid(remote_guid); inner_data.time(discovery_time); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->discovery_time(inner_data); data->_d(EventKind::DISCOVERED_ENTITY); // Precondition: The participant exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::PARTICIPANT, participant_guid_str)).Times(AnyNumber()) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(1)))); // Precondition: The remote entity does not exist EXPECT_CALL(database, get_entity_by_guid(EntityKind::PARTICIPANT, remote_guid_str)).Times(AnyNumber()) .WillOnce(Throw(BadParameter("Error"))); // Expectation: The insert method is never called, data dropped EXPECT_CALL(database, insert(_, _, _)).Times(0); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(_, _, _)).Times(0); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_sample_datas) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> writer_id = {0, 0, 0, 2}; int32_t sn_high = 2048; uint32_t sn_low = 4096; std::string writer_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; eprosima::fastrtps::rtps::SequenceNumber_t sn (sn_high, sn_low); // Build the writer GUID DatabaseDataQueue::StatisticsGuidPrefix writer_prefix; writer_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId writer_entity_id; writer_entity_id.value(writer_id); DatabaseDataQueue::StatisticsGuid writer_guid; writer_guid.guidPrefix(writer_prefix); writer_guid.entityId(writer_entity_id); DatabaseDataQueue::StatisticsSequenceNumber sequence_number; sequence_number.high(sn_high); sequence_number.low(sn_low); DatabaseDataQueue::StatisticsSampleIdentity sample_identity; sample_identity.writer_guid(writer_guid); sample_identity.sequence_number(sequence_number); // Build the Statistics data DatabaseDataQueue::StatisticsSampleIdentityCount inner_data; inner_data.count(1024); inner_data.sample_id(sample_identity); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->sample_identity_count(inner_data); data->_d(EventKind::SAMPLE_DATAS); // Precondition: The writer exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAWRITER, writer_guid_str)).Times(1) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(1)))); // Expectation: The insert method is called with appropriate arguments InsertDataArgs args([&]( const EntityId& domain_id, const EntityId& entity_id, const StatisticsSample& sample) { EXPECT_EQ(entity_id, 1); EXPECT_EQ(domain_id, 0); EXPECT_EQ(sample.src_ts, timestamp); EXPECT_EQ(sample.kind, DataKind::SAMPLE_DATAS); EXPECT_EQ(dynamic_cast<const SampleDatasCountSample&>(sample).count, 1024); EXPECT_EQ(dynamic_cast<const SampleDatasCountSample&>(sample).sequence_number, sn.to64long()); }); EXPECT_CALL(database, insert(_, _, _)).Times(1) .WillOnce(Invoke(&args, &InsertDataArgs::insert)); // Expectation: The user is notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(EntityId(0), EntityId(1), DataKind::SAMPLE_DATAS)).Times(1); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_sample_datas_no_writer) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> writer_id = {0, 0, 0, 2}; int32_t sn_high = 2048; uint32_t sn_low = 4096; std::string writer_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.2"; eprosima::fastrtps::rtps::SequenceNumber_t sn (sn_high, sn_low); // Build the writer GUID DatabaseDataQueue::StatisticsGuidPrefix writer_prefix; writer_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId writer_entity_id; writer_entity_id.value(writer_id); DatabaseDataQueue::StatisticsGuid writer_guid; writer_guid.guidPrefix(writer_prefix); writer_guid.entityId(writer_entity_id); DatabaseDataQueue::StatisticsSequenceNumber sequence_number; sequence_number.high(sn_high); sequence_number.low(sn_low); DatabaseDataQueue::StatisticsSampleIdentity sample_identity; sample_identity.writer_guid(writer_guid); sample_identity.sequence_number(sequence_number); // Build the Statistics data DatabaseDataQueue::StatisticsSampleIdentityCount inner_data; inner_data.count(1024); inner_data.sample_id(sample_identity); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->sample_identity_count(inner_data); data->_d(EventKind::SAMPLE_DATAS); // Precondition: The writer does not exist EXPECT_CALL(database, get_entity_by_guid(EntityKind::DATAWRITER, writer_guid_str)).Times(AnyNumber()) .WillOnce(Throw(BadParameter("Error"))); // Expectation: The insert method is never called, data dropped EXPECT_CALL(database, insert(_, _, _)).Times(0); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_data_available(_, _, _)).Times(0); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_physical_data_process_exists) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string processname = "command"; std::string pid = "1234"; std::string username = "user"; std::string hostname = "host"; std::string participant_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.0"; // Build the participant GUID std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> participant_id = {0, 0, 0, 0}; DatabaseDataQueue::StatisticsGuidPrefix participant_prefix; participant_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId participant_entity_id; participant_entity_id.value(participant_id); DatabaseDataQueue::StatisticsGuid participant_guid; participant_guid.guidPrefix(participant_prefix); participant_guid.entityId(participant_entity_id); // Build the process name std::stringstream ss; ss << processname << ":" << pid; std::string processname_pid = ss.str(); // Build the Statistics data DatabaseDataQueue::StatisticsPhysicalData inner_data; inner_data.host(hostname); inner_data.user(username); inner_data.process(processname_pid); inner_data.participant_guid(participant_guid); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->physical_data(inner_data); data->_d(EventKind::PHYSICAL_DATA); // Precondition: The participant exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::PARTICIPANT, participant_guid_str)).Times(1) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(1)))); // Precondition: The host exists and has ID 2 EXPECT_CALL(database, get_entities_by_name(EntityKind::HOST, hostname)).Times(1) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(2))))); auto host = std::make_shared<Host>(hostname); host->id = EntityId(2); EXPECT_CALL(database, get_entity(EntityId(2))).Times(1) .WillOnce(Return(host)); // Precondition: The user exists and has ID 3 EXPECT_CALL(database, get_entities_by_name(EntityKind::USER, username)).Times(1) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(3))))); auto user = std::make_shared<User>(username, host); user->id = EntityId(3); EXPECT_CALL(database, get_entity(EntityId(3))).Times(1) .WillOnce(Return(user)); // Precondition: The process exists and has ID 4 EXPECT_CALL(database, get_entities_by_name(EntityKind::PROCESS, processname)).Times(1) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(4))))); auto process = std::make_shared<Process>(processname, pid, user); process->id = EntityId(4); EXPECT_CALL(database, get_entity(EntityId(4))).Times(1) .WillOnce(Return(process)); // Expectation: The link method is called with appropriate arguments EXPECT_CALL(database, link_participant_with_process(EntityId(1), EntityId(4))).Times(1); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_physical_entity_discovery(_, _, _)).Times(0); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_physical_data_no_participant_exists) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string processname = "command"; std::string pid = "1234"; std::string username = "user"; std::string hostname = "host"; std::string participant_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.0"; // Build the participant GUID std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> participant_id = {0, 0, 0, 0}; DatabaseDataQueue::StatisticsGuidPrefix participant_prefix; participant_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId participant_entity_id; participant_entity_id.value(participant_id); DatabaseDataQueue::StatisticsGuid participant_guid; participant_guid.guidPrefix(participant_prefix); participant_guid.entityId(participant_entity_id); // Build the process name std::stringstream ss; ss << processname << ":" << pid; std::string processname_pid = ss.str(); // Build the Statistics data DatabaseDataQueue::StatisticsPhysicalData inner_data; inner_data.host(hostname); inner_data.user(username); inner_data.process(processname_pid); inner_data.participant_guid(participant_guid); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->physical_data(inner_data); data->_d(EventKind::PHYSICAL_DATA); // Precondition: The participant does not exist EXPECT_CALL(database, get_entity_by_guid(EntityKind::PARTICIPANT, participant_guid_str)).Times(1) .WillOnce(Throw(BadParameter("Error"))); // Precondition: The host exists and has ID 2 EXPECT_CALL(database, get_entities_by_name(EntityKind::HOST, hostname)).Times(AnyNumber()) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(2))))); auto host = std::make_shared<Host>(hostname); host->id = EntityId(2); EXPECT_CALL(database, get_entity(EntityId(2))).Times(AnyNumber()) .WillOnce(Return(host)); // Precondition: The user exists and has ID 3 EXPECT_CALL(database, get_entities_by_name(EntityKind::USER, username)).Times(AnyNumber()) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(3))))); auto user = std::make_shared<User>(username, host); user->id = EntityId(3); EXPECT_CALL(database, get_entity(EntityId(3))).Times(AnyNumber()) .WillOnce(Return(user)); // Precondition: The process exists and has ID 4 EXPECT_CALL(database, get_entities_by_name(EntityKind::PROCESS, processname)).Times(AnyNumber()) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(4))))); auto process = std::make_shared<Process>(processname, pid, user); process->id = EntityId(4); EXPECT_CALL(database, get_entity(EntityId(4))).Times(AnyNumber()) .WillOnce(Return(process)); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_physical_entity_discovery(_, _, _)).Times(0); // Add to the queue and wait to be processed // The processing should not progress the exception. data_queue.stop_consumer(); data_queue.push(timestamp, data); data_queue.do_swap(); EXPECT_NO_THROW(data_queue.consume_sample()); } TEST_F(database_queue_tests, push_physical_data_no_process_exists) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string processname = "command"; std::string pid = "1234"; std::string username = "user"; std::string hostname = "host"; std::string participant_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.0"; // Build the participant GUID std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> participant_id = {0, 0, 0, 0}; DatabaseDataQueue::StatisticsGuidPrefix participant_prefix; participant_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId participant_entity_id; participant_entity_id.value(participant_id); DatabaseDataQueue::StatisticsGuid participant_guid; participant_guid.guidPrefix(participant_prefix); participant_guid.entityId(participant_entity_id); // Build the process name std::stringstream ss; ss << processname << ":" << pid; std::string processname_pid = ss.str(); // Build the Statistics data DatabaseDataQueue::StatisticsPhysicalData inner_data; inner_data.host(hostname); inner_data.user(username); inner_data.process(processname_pid); inner_data.participant_guid(participant_guid); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->physical_data(inner_data); data->_d(EventKind::PHYSICAL_DATA); // Precondition: The participant exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::PARTICIPANT, participant_guid_str)).Times(1) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(1)))); // Precondition: The host exists and has ID 2 EXPECT_CALL(database, get_entities_by_name(EntityKind::HOST, hostname)).Times(1) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(2))))); auto host = std::make_shared<Host>(hostname); host->id = EntityId(2); EXPECT_CALL(database, get_entity(EntityId(2))).Times(1) .WillOnce(Return(host)); // Precondition: The user exists and has ID 3 EXPECT_CALL(database, get_entities_by_name(EntityKind::USER, username)).Times(1) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(3))))); auto user = std::make_shared<User>(username, host); user->id = EntityId(3); EXPECT_CALL(database, get_entity(EntityId(3))).Times(1) .WillOnce(Return(user)); // Precondition: The process does not exist EXPECT_CALL(database, get_entities_by_name(EntityKind::PROCESS, processname)).Times(1) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>())); // Expectation: The process is created and given ID 4 InsertEntityArgs insert_args_process([&]( std::shared_ptr<Entity> entity) { EXPECT_EQ(entity->kind, EntityKind::PROCESS); EXPECT_EQ(entity->name, processname); EXPECT_EQ(entity->alias, processname); EXPECT_EQ(std::dynamic_pointer_cast<Process>(entity)->pid, pid); EXPECT_EQ(std::dynamic_pointer_cast<Process>(entity)->user, user); return EntityId(4); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args_process, &InsertEntityArgs::insert)); // Expectation: The user is notified of the new process EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_physical_entity_discovery(EntityId(4), EntityKind::PROCESS, details::StatisticsBackendData::DiscoveryStatus::DISCOVERY)).Times(1); // Expectation: The link method is called with appropriate arguments EXPECT_CALL(database, link_participant_with_process(EntityId(1), EntityId(4))).Times(1); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_physical_data_no_process_exists_process_insert_throws) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string processname = "command"; std::string pid = "1234"; std::string username = "user"; std::string hostname = "host"; std::string participant_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.0"; // Build the participant GUID std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> participant_id = {0, 0, 0, 0}; DatabaseDataQueue::StatisticsGuidPrefix participant_prefix; participant_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId participant_entity_id; participant_entity_id.value(participant_id); DatabaseDataQueue::StatisticsGuid participant_guid; participant_guid.guidPrefix(participant_prefix); participant_guid.entityId(participant_entity_id); // Build the process name std::stringstream ss; ss << processname << ":" << pid; std::string processname_pid = ss.str(); // Build the Statistics data DatabaseDataQueue::StatisticsPhysicalData inner_data; inner_data.host(hostname); inner_data.user(username); inner_data.process(processname_pid); inner_data.participant_guid(participant_guid); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->physical_data(inner_data); data->_d(EventKind::PHYSICAL_DATA); // Precondition: The participant exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::PARTICIPANT, participant_guid_str)).Times(AnyNumber()) .WillRepeatedly(Return(std::make_pair(EntityId(0), EntityId(1)))); // Precondition: The host exists and has ID 2 EXPECT_CALL(database, get_entities_by_name(EntityKind::HOST, hostname)).Times(AnyNumber()) .WillRepeatedly(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(2))))); auto host = std::make_shared<Host>(hostname); host->id = EntityId(2); EXPECT_CALL(database, get_entity(EntityId(2))).Times(1) .WillOnce(Return(host)); // Precondition: The user exists and has ID 3 EXPECT_CALL(database, get_entities_by_name(EntityKind::USER, username)).Times(AnyNumber()) .WillRepeatedly(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(3))))); auto user = std::make_shared<User>(username, host); user->id = EntityId(3); EXPECT_CALL(database, get_entity(EntityId(3))).Times(1) .WillOnce(Return(user)); // Precondition: The process does not exist EXPECT_CALL(database, get_entities_by_name(EntityKind::PROCESS, processname)).Times(AnyNumber()) .WillRepeatedly(Return(std::vector<std::pair<EntityId, EntityId>>())); // Expectation: The process creation throws InsertEntityArgs insert_args_process([&]( std::shared_ptr<Entity> entity) -> EntityId { EXPECT_EQ(entity->kind, EntityKind::PROCESS); EXPECT_EQ(entity->name, processname); EXPECT_EQ(entity->alias, processname); EXPECT_EQ(std::dynamic_pointer_cast<Process>(entity)->pid, pid); EXPECT_EQ(std::dynamic_pointer_cast<Process>(entity)->user, user); throw BadParameter("Error"); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args_process, &InsertEntityArgs::insert)); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_physical_entity_discovery(_, _, _)).Times(0); // Expectation: The link method is not called EXPECT_CALL(database, link_participant_with_process(EntityId(1), EntityId(4))).Times(0); // Add to the queue and wait to be processed data_queue.stop_consumer(); data_queue.push(timestamp, data); data_queue.do_swap(); EXPECT_NO_THROW(data_queue.consume_sample()); } TEST_F(database_queue_tests, push_physical_data_no_process_no_user_exists) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string processname = "command"; std::string pid = "1234"; std::string username = "user"; std::string hostname = "host"; std::string participant_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.0"; // Build the participant GUID std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> participant_id = {0, 0, 0, 0}; DatabaseDataQueue::StatisticsGuidPrefix participant_prefix; participant_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId participant_entity_id; participant_entity_id.value(participant_id); DatabaseDataQueue::StatisticsGuid participant_guid; participant_guid.guidPrefix(participant_prefix); participant_guid.entityId(participant_entity_id); // Build the process name std::stringstream ss; ss << processname << ":" << pid; std::string processname_pid = ss.str(); // Build the Statistics data DatabaseDataQueue::StatisticsPhysicalData inner_data; inner_data.host(hostname); inner_data.user(username); inner_data.process(processname_pid); inner_data.participant_guid(participant_guid); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->physical_data(inner_data); data->_d(EventKind::PHYSICAL_DATA); // Precondition: The participant exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::PARTICIPANT, participant_guid_str)).Times(1) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(1)))); // Precondition: The host exists and has ID 2 EXPECT_CALL(database, get_entities_by_name(EntityKind::HOST, hostname)).Times(1) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(2))))); auto host = std::make_shared<Host>(hostname); host->id = EntityId(2); EXPECT_CALL(database, get_entity(EntityId(2))).Times(1) .WillOnce(Return(host)); // Precondition: The user does not exist EXPECT_CALL(database, get_entities_by_name(EntityKind::USER, username)).Times(1) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>())); // Precondition: The process does not exist EXPECT_CALL(database, get_entities_by_name(EntityKind::PROCESS, processname)).Times(1) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>())); // Expectation: The user is created and given ID 3 InsertEntityArgs insert_args_user([&]( std::shared_ptr<Entity> entity) { EXPECT_EQ(entity->kind, EntityKind::USER); EXPECT_EQ(entity->name, username); EXPECT_EQ(entity->alias, username); EXPECT_EQ(std::dynamic_pointer_cast<User>(entity)->host, host); return EntityId(3); }); // Expectation: The user is notified of the new process EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_physical_entity_discovery(EntityId(3), EntityKind::USER, details::StatisticsBackendData::DiscoveryStatus::DISCOVERY)).Times(1); // Expectation: The process is created and given ID 4 InsertEntityArgs insert_args_process([&]( std::shared_ptr<Entity> entity) { EXPECT_EQ(entity->kind, EntityKind::PROCESS); EXPECT_EQ(entity->name, processname); EXPECT_EQ(entity->alias, processname); EXPECT_EQ(std::dynamic_pointer_cast<Process>(entity)->pid, pid); EXPECT_EQ(std::dynamic_pointer_cast<Process>(entity)->user, insert_args_user.entity_); return EntityId(4); }); // Expectation: The user is notified of the new process EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_physical_entity_discovery(EntityId(4), EntityKind::PROCESS, details::StatisticsBackendData::DiscoveryStatus::DISCOVERY)).Times(1); EXPECT_CALL(database, insert(_)).Times(2) .WillOnce(Invoke(&insert_args_user, &InsertEntityArgs::insert)) .WillOnce(Invoke(&insert_args_process, &InsertEntityArgs::insert)); // Expectation: The link method is called with appropriate arguments EXPECT_CALL(database, link_participant_with_process(EntityId(1), EntityId(4))).Times(1); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_physical_data_no_process_no_user_exists_user_insert_throws) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string processname = "command"; std::string pid = "1234"; std::string username = "user"; std::string hostname = "host"; std::string participant_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.0"; // Build the participant GUID std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> participant_id = {0, 0, 0, 0}; DatabaseDataQueue::StatisticsGuidPrefix participant_prefix; participant_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId participant_entity_id; participant_entity_id.value(participant_id); DatabaseDataQueue::StatisticsGuid participant_guid; participant_guid.guidPrefix(participant_prefix); participant_guid.entityId(participant_entity_id); // Build the process name std::stringstream ss; ss << processname << ":" << pid; std::string processname_pid = ss.str(); // Build the Statistics data DatabaseDataQueue::StatisticsPhysicalData inner_data; inner_data.host(hostname); inner_data.user(username); inner_data.process(processname_pid); inner_data.participant_guid(participant_guid); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->physical_data(inner_data); data->_d(EventKind::PHYSICAL_DATA); // Precondition: The participant exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::PARTICIPANT, participant_guid_str)).Times(AnyNumber()) .WillRepeatedly(Return(std::make_pair(EntityId(0), EntityId(1)))); // Precondition: The host exists and has ID 2 EXPECT_CALL(database, get_entities_by_name(EntityKind::HOST, hostname)).Times(AnyNumber()) .WillRepeatedly(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(2))))); auto host = std::make_shared<Host>(hostname); host->id = EntityId(2); EXPECT_CALL(database, get_entity(EntityId(2))).Times(1) .WillOnce(Return(host)); // Precondition: The user does not exist EXPECT_CALL(database, get_entities_by_name(EntityKind::USER, username)).Times(AnyNumber()) .WillRepeatedly(Return(std::vector<std::pair<EntityId, EntityId>>())); // Precondition: The process does not exist EXPECT_CALL(database, get_entities_by_name(EntityKind::PROCESS, processname)).Times(AnyNumber()) .WillRepeatedly(Return(std::vector<std::pair<EntityId, EntityId>>())); // Expectation: The user creation throws InsertEntityArgs insert_args_user([&]( std::shared_ptr<Entity> entity) -> EntityId { EXPECT_EQ(entity->kind, EntityKind::USER); EXPECT_EQ(entity->name, username); EXPECT_EQ(entity->alias, username); EXPECT_EQ(std::dynamic_pointer_cast<User>(entity)->host, host); throw BadParameter("Error"); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args_user, &InsertEntityArgs::insert)); // Expectation: The user is not notified of the new user EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_physical_entity_discovery(_, _, _)).Times(0); // Expectation: The link method is not called EXPECT_CALL(database, link_participant_with_process(EntityId(1), EntityId(4))).Times(0); // Add to the queue and wait to be processed data_queue.stop_consumer(); data_queue.push(timestamp, data); data_queue.do_swap(); EXPECT_NO_THROW(data_queue.consume_sample()); } TEST_F(database_queue_tests, push_physical_data_no_process_no_user_no_host_exists) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string processname = "command"; std::string pid = "1234"; std::string username = "user"; std::string hostname = "host"; std::string participant_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.0"; // Build the participant GUID std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> participant_id = {0, 0, 0, 0}; DatabaseDataQueue::StatisticsGuidPrefix participant_prefix; participant_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId participant_entity_id; participant_entity_id.value(participant_id); DatabaseDataQueue::StatisticsGuid participant_guid; participant_guid.guidPrefix(participant_prefix); participant_guid.entityId(participant_entity_id); // Build the process name std::stringstream ss; ss << processname << ":" << pid; std::string processname_pid = ss.str(); // Build the Statistics data DatabaseDataQueue::StatisticsPhysicalData inner_data; inner_data.host(hostname); inner_data.user(username); inner_data.process(processname_pid); inner_data.participant_guid(participant_guid); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->physical_data(inner_data); data->_d(EventKind::PHYSICAL_DATA); // Precondition: The participant exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::PARTICIPANT, participant_guid_str)).Times(1) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(1)))); // Precondition: The host does not exist EXPECT_CALL(database, get_entities_by_name(EntityKind::HOST, hostname)).Times(1) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>())); // Precondition: The user does not exist EXPECT_CALL(database, get_entities_by_name(EntityKind::USER, username)).Times(1) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>())); // Precondition: The process does not exist EXPECT_CALL(database, get_entities_by_name(EntityKind::PROCESS, processname)).Times(1) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>())); // Expectation: The host is created and given ID 3 InsertEntityArgs insert_args_host([&]( std::shared_ptr<Entity> entity) { EXPECT_EQ(entity->kind, EntityKind::HOST); EXPECT_EQ(entity->name, hostname); EXPECT_EQ(entity->alias, hostname); return EntityId(3); }); // Expectation: The user is notified of the new host EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_physical_entity_discovery(EntityId(3), EntityKind::HOST, details::StatisticsBackendData::DiscoveryStatus::DISCOVERY)).Times(1); // Expectation: The user is created and given ID 4 InsertEntityArgs insert_args_user([&]( std::shared_ptr<Entity> entity) { EXPECT_EQ(entity->kind, EntityKind::USER); EXPECT_EQ(entity->name, username); EXPECT_EQ(entity->alias, username); EXPECT_EQ(std::dynamic_pointer_cast<User>(entity)->host, insert_args_host.entity_); return EntityId(4); }); // Expectation: The user is notified of the new user EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_physical_entity_discovery(EntityId(4), EntityKind::USER, details::StatisticsBackendData::DiscoveryStatus::DISCOVERY)).Times(1); // Expectation: The process is created and given ID 5 InsertEntityArgs insert_args_process([&]( std::shared_ptr<Entity> entity) { EXPECT_EQ(entity->kind, EntityKind::PROCESS); EXPECT_EQ(entity->name, processname); EXPECT_EQ(entity->alias, processname); EXPECT_EQ(std::dynamic_pointer_cast<Process>(entity)->pid, pid); EXPECT_EQ(std::dynamic_pointer_cast<Process>(entity)->user, insert_args_user.entity_); return EntityId(5); }); // Expectation: The user is notified of the new process EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_physical_entity_discovery(EntityId(5), EntityKind::PROCESS, details::StatisticsBackendData::DiscoveryStatus::DISCOVERY)).Times(1); EXPECT_CALL(database, insert(_)).Times(3) .WillOnce(Invoke(&insert_args_host, &InsertEntityArgs::insert)) .WillOnce(Invoke(&insert_args_user, &InsertEntityArgs::insert)) .WillOnce(Invoke(&insert_args_process, &InsertEntityArgs::insert)); // Expectation: The link method is called with appropriate arguments EXPECT_CALL(database, link_participant_with_process(EntityId(1), EntityId(5))).Times(1); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } TEST_F(database_queue_tests, push_physical_data_no_process_no_user_no_host_exists_host_insert_throws) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string processname = "command"; std::string pid = "1234"; std::string username = "user"; std::string hostname = "host"; std::string participant_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.0"; // Build the participant GUID std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> participant_id = {0, 0, 0, 0}; DatabaseDataQueue::StatisticsGuidPrefix participant_prefix; participant_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId participant_entity_id; participant_entity_id.value(participant_id); DatabaseDataQueue::StatisticsGuid participant_guid; participant_guid.guidPrefix(participant_prefix); participant_guid.entityId(participant_entity_id); // Build the process name std::stringstream ss; ss << processname << ":" << pid; std::string processname_pid = ss.str(); // Build the Statistics data DatabaseDataQueue::StatisticsPhysicalData inner_data; inner_data.host(hostname); inner_data.user(username); inner_data.process(processname_pid); inner_data.participant_guid(participant_guid); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->physical_data(inner_data); data->_d(EventKind::PHYSICAL_DATA); // Precondition: The participant exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::PARTICIPANT, participant_guid_str)).Times(AnyNumber()) .WillRepeatedly(Return(std::make_pair(EntityId(0), EntityId(1)))); // Precondition: The host does not exist EXPECT_CALL(database, get_entities_by_name(EntityKind::HOST, hostname)).Times(AnyNumber()) .WillRepeatedly(Return(std::vector<std::pair<EntityId, EntityId>>())); // Precondition: The user does not exist EXPECT_CALL(database, get_entities_by_name(EntityKind::USER, username)).Times(AnyNumber()) .WillRepeatedly(Return(std::vector<std::pair<EntityId, EntityId>>())); // Precondition: The process does not exist EXPECT_CALL(database, get_entities_by_name(EntityKind::PROCESS, processname)).Times(AnyNumber()) .WillRepeatedly(Return(std::vector<std::pair<EntityId, EntityId>>())); // Expectation: The host creation throws InsertEntityArgs insert_args_host([&]( std::shared_ptr<Entity> entity) -> EntityId { EXPECT_EQ(entity->kind, EntityKind::HOST); EXPECT_EQ(entity->name, hostname); EXPECT_EQ(entity->alias, hostname); throw BadParameter("Error"); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args_host, &InsertEntityArgs::insert)); // Expectation: The user is not notified EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_physical_entity_discovery(_, _, _)).Times(0); // Expectation: The link method is not called EXPECT_CALL(database, link_participant_with_process(EntityId(1), EntityId(5))).Times(0); // Add to the queue and wait to be processed data_queue.stop_consumer(); data_queue.push(timestamp, data); data_queue.do_swap(); EXPECT_NO_THROW(data_queue.consume_sample()); } TEST_F(database_queue_tests, push_physical_data_wrong_processname_format) { std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); std::string processname = "command"; std::string pid = "1234"; std::string username = "user"; std::string hostname = "host"; std::string participant_guid_str = "01.02.03.04.05.06.07.08.09.0a.0b.0c|0.0.0.0"; // Build the participant GUID std::array<uint8_t, 12> prefix = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::array<uint8_t, 4> participant_id = {0, 0, 0, 0}; DatabaseDataQueue::StatisticsGuidPrefix participant_prefix; participant_prefix.value(prefix); DatabaseDataQueue::StatisticsEntityId participant_entity_id; participant_entity_id.value(participant_id); DatabaseDataQueue::StatisticsGuid participant_guid; participant_guid.guidPrefix(participant_prefix); participant_guid.entityId(participant_entity_id); // Build the process name with the wrong format std::stringstream ss; ss << processname << pid; std::string processname_pid = ss.str(); // Build the Statistics data DatabaseDataQueue::StatisticsPhysicalData inner_data; inner_data.host(hostname); inner_data.user(username); inner_data.process(processname_pid); inner_data.participant_guid(participant_guid); std::shared_ptr<eprosima::fastdds::statistics::Data> data = std::make_shared<eprosima::fastdds::statistics::Data>(); data->physical_data(inner_data); data->_d(EventKind::PHYSICAL_DATA); // Precondition: The participant exists and has ID 1 EXPECT_CALL(database, get_entity_by_guid(EntityKind::PARTICIPANT, participant_guid_str)).Times(1) .WillOnce(Return(std::make_pair(EntityId(0), EntityId(1)))); // Precondition: The host exists and has ID 2 EXPECT_CALL(database, get_entities_by_name(EntityKind::HOST, hostname)).Times(AnyNumber()) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(2))))); auto host = std::make_shared<Host>(hostname); host->id = EntityId(2); EXPECT_CALL(database, get_entity(EntityId(2))).Times(AnyNumber()) .WillOnce(Return(host)); // Precondition: The user exists and has ID 3 EXPECT_CALL(database, get_entities_by_name(EntityKind::USER, username)).Times(AnyNumber()) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>(1, std::make_pair(EntityId(0), EntityId(3))))); auto user = std::make_shared<User>(username, host); user->id = EntityId(3); EXPECT_CALL(database, get_entity(EntityId(3))).Times(AnyNumber()) .WillOnce(Return(user)); // Precondition: The process does not exist EXPECT_CALL(database, get_entities_by_name(EntityKind::PROCESS, processname_pid)).Times(1) .WillOnce(Return(std::vector<std::pair<EntityId, EntityId>>())); // Expectation: The process is created and given ID 4 InsertEntityArgs insert_args_process([&]( std::shared_ptr<Entity> entity) { EXPECT_EQ(entity->kind, EntityKind::PROCESS); EXPECT_EQ(entity->name, processname_pid); EXPECT_EQ(entity->alias, processname_pid); EXPECT_EQ(std::dynamic_pointer_cast<Process>(entity)->pid, processname_pid); EXPECT_EQ(std::dynamic_pointer_cast<Process>(entity)->user, user); return EntityId(4); }); EXPECT_CALL(database, insert(_)).Times(1) .WillOnce(Invoke(&insert_args_process, &InsertEntityArgs::insert)); // Expectation: The user is notified of the new process EXPECT_CALL(*details::StatisticsBackendData::get_instance(), on_physical_entity_discovery(EntityId(4), EntityKind::PROCESS, details::StatisticsBackendData::DiscoveryStatus::DISCOVERY)).Times(1); // Expectation: The link method is called with appropriate arguments EXPECT_CALL(database, link_participant_with_process(EntityId(1), EntityId(4))).Times(1); // Add to the queue and wait to be processed data_queue.push(timestamp, data); data_queue.flush(); } int main( int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
42.306906
120
0.685779
eProsima
b77b530d3b6239307317187caaf9c2a06a9f69df
4,915
hpp
C++
include/humanize/numbers.hpp
pajlada/humanize
13867379249c64cd44b9cd4c03f18c1a52d56587
[ "MIT" ]
2
2017-12-17T02:12:33.000Z
2018-06-05T16:49:51.000Z
include/humanize/numbers.hpp
pajlada/humanize
13867379249c64cd44b9cd4c03f18c1a52d56587
[ "MIT" ]
null
null
null
include/humanize/numbers.hpp
pajlada/humanize
13867379249c64cd44b9cd4c03f18c1a52d56587
[ "MIT" ]
null
null
null
#pragma once #include "humanize/format_string.hpp" #include <array> #include <cstring> #include <limits> #include <string> #include <type_traits> namespace humanize { namespace { struct NumberStruct { int length; char suffix; }; // return const char * with arguments typename Number, and input char buffer // with size of numeric_limits<Number, and with input format string from // format_string<Number> template <typename Number> void numberToChars(char *str, Number x) { std::sprintf(str, format_string<Number>::format(), x); } template <typename Number> void absValue(Number &x, typename std::enable_if<std::is_signed<Number>::value>::type * = 0) { x = static_cast<Number>(std::abs(x)); } template <typename Number> void absValue(Number &, typename std::enable_if<std::is_unsigned<Number>::value>::type * = 0) { // do nothing } template <bool IsSigned> struct SignedHelper { }; template <> struct SignedHelper<false> { template <typename Number> static char * getStringWithoutSign(char *str, Number) { return str; } template <typename Number> static void test(char *str, Number, unsigned decimals, const char *numberStr, int decimalIndex, const NumberStruct &ns) { if (decimals > 0) { std::sprintf(str, "%.*s.%.*s%c", decimalIndex, numberStr, decimals, numberStr + decimalIndex, ns.suffix); } else { std::sprintf(str, "%.*s%c", decimalIndex, numberStr, ns.suffix); } } }; template <> struct SignedHelper<true> { template <typename Number> static char * getStringWithoutSign(char *str, Number number) { if (number < 0) { return str + 1; } else { return str; } } template <typename Number> static void test(char *str, Number number, unsigned decimals, const char *numberStr, int decimalIndex, const NumberStruct &ns) { if (number < 0) { if (decimals > 0) { std::sprintf(str, "-%.*s.%.*s%c", decimalIndex, numberStr, decimals, numberStr + decimalIndex, ns.suffix); } else { std::sprintf(str, "-%.*s%c", decimalIndex, numberStr, ns.suffix); } } else { SignedHelper<false>::test(str, number, decimals, numberStr, decimalIndex, ns); } } }; } // anonymous namespace // Signed integer template <typename Number, typename = typename std::enable_if< std::is_integral<Number>::value>::type> std::string compactInteger(Number number, unsigned decimals = 0) { constexpr auto maxStringSize = std::numeric_limits<Number>::digits10 + std::numeric_limits<Number>::is_signed + 2; char str[maxStringSize]; numberToChars<Number>(str, number); Number absNumber = number; absValue(absNumber); static std::array<NumberStruct, 4> numberLengths = {{ {13, 'T'}, // {10, 'B'}, // {7, 'M'}, // {4, 'k'}, // }}; char *numberStr = SignedHelper<std::is_signed<Number>::value>::getStringWithoutSign( str, number); int absNumberLength = static_cast<int>(std::strlen(numberStr)); if (absNumber < 1000) { return str; } // do complicated shit for (const auto &numberStruct : numberLengths) { if (absNumberLength >= numberStruct.length) { // Found matching NumberStruct int decimalIndex = absNumberLength - numberStruct.length + 1; char finalStr[maxStringSize]; SignedHelper<std::is_signed<Number>::value>::test( finalStr, number, decimals, numberStr, decimalIndex, numberStruct); return finalStr; } } // This should never happen return "?"; } template <typename Number, typename = typename std::enable_if< std::is_integral<Number>::value>::type> std::string ordinal(const Number number) { std::string numString = std::to_string(number); if (number < 0) { return numString; } std::string end; switch (number % 100) { case 11: case 12: case 13: end = "th"; break; default: { switch (number % 10) { case 1: end = "st"; break; case 2: end = "nd"; break; case 3: end = "rd"; break; default: end = "th"; break; } } break; } return numString + end; } } // namespace humanize
24.698492
79
0.546083
pajlada
b77bc5e85478a41af59b4d57e231db4900b50d4f
21,205
cpp
C++
dbms/src/Functions/tests/gtest_bitand.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
85
2022-03-25T09:03:16.000Z
2022-03-25T09:45:03.000Z
dbms/src/Functions/tests/gtest_bitand.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
7
2022-03-25T08:59:10.000Z
2022-03-25T09:40:13.000Z
dbms/src/Functions/tests/gtest_bitand.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
11
2022-03-25T09:15:36.000Z
2022-03-25T09:45:07.000Z
// Copyright 2022 PingCAP, Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <Columns/ColumnConst.h> #include <Columns/ColumnString.h> #include <Common/Exception.h> #include <DataTypes/DataTypeNothing.h> #include <Functions/FunctionFactory.h> #include <Interpreters/Context.h> #include <TestUtils/FunctionTestUtils.h> #include <TestUtils/TiFlashTestBasic.h> #include <string> #include <unordered_map> #include <vector> namespace DB { namespace tests { class TestFunctionBitAnd : public DB::tests::FunctionTest { }; #define ASSERT_BITAND(t1, t2, result) \ ASSERT_COLUMN_EQ(result, executeFunction("bitAnd", {t1, t2})) TEST_F(TestFunctionBitAnd, Simple) try { ASSERT_BITAND(createColumn<Nullable<Int64>>({-1, 1}), createColumn<Nullable<Int64>>({0, 0}), createColumn<Nullable<Int64>>({0, 0})); } CATCH /// Note: Only IntX and UIntX will be received by BitAnd, others will be casted by TiDB Planner. TEST_F(TestFunctionBitAnd, TypePromotion) try { // Type Promotion ASSERT_BITAND(createColumn<Nullable<Int8>>({1}), createColumn<Nullable<Int16>>({0}), createColumn<Nullable<Int16>>({0})); ASSERT_BITAND(createColumn<Nullable<Int16>>({1}), createColumn<Nullable<Int32>>({0}), createColumn<Nullable<Int32>>({0})); ASSERT_BITAND(createColumn<Nullable<Int32>>({1}), createColumn<Nullable<Int64>>({0}), createColumn<Nullable<Int64>>({0})); ASSERT_BITAND(createColumn<Nullable<Int8>>({1}), createColumn<Nullable<Int64>>({0}), createColumn<Nullable<Int64>>({0})); ASSERT_BITAND(createColumn<Nullable<UInt8>>({1}), createColumn<Nullable<UInt16>>({0}), createColumn<Nullable<UInt16>>({0})); ASSERT_BITAND(createColumn<Nullable<UInt16>>({1}), createColumn<Nullable<UInt32>>({0}), createColumn<Nullable<UInt32>>({0})); ASSERT_BITAND(createColumn<Nullable<UInt32>>({1}), createColumn<Nullable<UInt64>>({0}), createColumn<Nullable<UInt64>>({0})); ASSERT_BITAND(createColumn<Nullable<UInt8>>({1}), createColumn<Nullable<UInt64>>({0}), createColumn<Nullable<UInt64>>({0})); // Type Promotion across signed/unsigned ASSERT_BITAND(createColumn<Nullable<Int16>>({1}), createColumn<Nullable<UInt32>>({0}), createColumn<Nullable<Int32>>({0})); ASSERT_BITAND(createColumn<Nullable<Int64>>({1}), createColumn<Nullable<UInt8>>({0}), createColumn<Nullable<Int64>>({0})); ASSERT_BITAND(createColumn<Nullable<UInt32>>({1}), createColumn<Nullable<Int16>>({0}), createColumn<Nullable<Int32>>({0})); ASSERT_BITAND(createColumn<Nullable<UInt8>>({1}), createColumn<Nullable<Int64>>({0}), createColumn<Nullable<Int64>>({0})); } CATCH TEST_F(TestFunctionBitAnd, Nullable) try { // Non Nullable ASSERT_BITAND(createColumn<Int8>({1}), createColumn<Int16>({0}), createColumn<Int16>({0})); ASSERT_BITAND(createColumn<Int16>({1}), createColumn<Int32>({0}), createColumn<Int32>({0})); ASSERT_BITAND(createColumn<Int32>({1}), createColumn<Int64>({0}), createColumn<Int64>({0})); ASSERT_BITAND(createColumn<Int8>({1}), createColumn<Int64>({0}), createColumn<Int64>({0})); ASSERT_BITAND(createColumn<UInt8>({1}), createColumn<UInt16>({0}), createColumn<UInt16>({0})); ASSERT_BITAND(createColumn<UInt16>({1}), createColumn<UInt32>({0}), createColumn<UInt32>({0})); ASSERT_BITAND(createColumn<UInt32>({1}), createColumn<UInt64>({0}), createColumn<UInt64>({0})); ASSERT_BITAND(createColumn<UInt8>({1}), createColumn<UInt64>({0}), createColumn<UInt64>({0})); ASSERT_BITAND(createColumn<Int16>({1}), createColumn<UInt32>({0}), createColumn<Int32>({0})); ASSERT_BITAND(createColumn<Int64>({1}), createColumn<UInt8>({0}), createColumn<Int64>({0})); ASSERT_BITAND(createColumn<UInt32>({1}), createColumn<Int16>({0}), createColumn<Int32>({0})); ASSERT_BITAND(createColumn<UInt8>({1}), createColumn<Int64>({0}), createColumn<Int64>({0})); // Across Nullable and non-Nullable ASSERT_BITAND(createColumn<Int8>({1}), createColumn<Nullable<Int16>>({0}), createColumn<Nullable<Int16>>({0})); ASSERT_BITAND(createColumn<Int16>({1}), createColumn<Nullable<Int32>>({0}), createColumn<Nullable<Int32>>({0})); ASSERT_BITAND(createColumn<Int32>({1}), createColumn<Nullable<Int64>>({0}), createColumn<Nullable<Int64>>({0})); ASSERT_BITAND(createColumn<Int8>({1}), createColumn<Nullable<Int64>>({0}), createColumn<Nullable<Int64>>({0})); ASSERT_BITAND(createColumn<UInt8>({1}), createColumn<Nullable<UInt16>>({0}), createColumn<Nullable<UInt16>>({0})); ASSERT_BITAND(createColumn<UInt16>({1}), createColumn<Nullable<UInt32>>({0}), createColumn<Nullable<UInt32>>({0})); ASSERT_BITAND(createColumn<UInt32>({1}), createColumn<Nullable<UInt64>>({0}), createColumn<Nullable<UInt64>>({0})); ASSERT_BITAND(createColumn<UInt8>({1}), createColumn<Nullable<UInt64>>({0}), createColumn<Nullable<UInt64>>({0})); ASSERT_BITAND(createColumn<Int16>({1}), createColumn<Nullable<UInt32>>({0}), createColumn<Nullable<Int32>>({0})); ASSERT_BITAND(createColumn<Int64>({1}), createColumn<Nullable<UInt8>>({0}), createColumn<Nullable<Int64>>({0})); ASSERT_BITAND(createColumn<UInt32>({1}), createColumn<Nullable<Int16>>({0}), createColumn<Nullable<Int32>>({0})); ASSERT_BITAND(createColumn<UInt8>({1}), createColumn<Nullable<Int64>>({0}), createColumn<Nullable<Int64>>({0})); ASSERT_BITAND(createColumn<Nullable<Int8>>({1}), createColumn<Int16>({0}), createColumn<Nullable<Int16>>({0})); ASSERT_BITAND(createColumn<Nullable<Int16>>({1}), createColumn<Int32>({0}), createColumn<Nullable<Int32>>({0})); ASSERT_BITAND(createColumn<Nullable<Int32>>({1}), createColumn<Int64>({0}), createColumn<Nullable<Int64>>({0})); ASSERT_BITAND(createColumn<Nullable<Int8>>({1}), createColumn<Int64>({0}), createColumn<Nullable<Int64>>({0})); ASSERT_BITAND(createColumn<Nullable<UInt8>>({1}), createColumn<UInt16>({0}), createColumn<Nullable<UInt16>>({0})); ASSERT_BITAND(createColumn<Nullable<UInt16>>({1}), createColumn<UInt32>({0}), createColumn<Nullable<UInt32>>({0})); ASSERT_BITAND(createColumn<Nullable<UInt32>>({1}), createColumn<UInt64>({0}), createColumn<Nullable<UInt64>>({0})); ASSERT_BITAND(createColumn<Nullable<UInt8>>({1}), createColumn<UInt64>({0}), createColumn<Nullable<UInt64>>({0})); ASSERT_BITAND(createColumn<Nullable<Int16>>({1}), createColumn<UInt32>({0}), createColumn<Nullable<Int32>>({0})); ASSERT_BITAND(createColumn<Nullable<Int64>>({1}), createColumn<UInt8>({0}), createColumn<Nullable<Int64>>({0})); ASSERT_BITAND(createColumn<Nullable<UInt32>>({1}), createColumn<Int16>({0}), createColumn<Nullable<Int32>>({0})); ASSERT_BITAND(createColumn<Nullable<UInt8>>({1}), createColumn<Int64>({0}), createColumn<Nullable<Int64>>({0})); } CATCH TEST_F(TestFunctionBitAnd, TypeCastWithConst) try { /// need test these kinds of columns: /// 1. ColumnVector /// 2. ColumnVector<Nullable> /// 3. ColumnConst /// 4. ColumnConst<Nullable>, value != null /// 5. ColumnConst<Nullable>, value = null ASSERT_BITAND(createColumn<Int8>({0, 0, 1, 1}), createColumn<UInt64>({0, 1, 0, 1}), createColumn<Int64>({0, 0, 0, 1})); ASSERT_BITAND(createColumn<Int8>({0, 0, 1, 1}), createColumn<Nullable<UInt64>>({0, 1, std::nullopt, std::nullopt}), createColumn<Nullable<Int64>>({0, 0, std::nullopt, std::nullopt})); ASSERT_BITAND(createColumn<Int8>({0, 0, 1, 1}), createConstColumn<UInt64>(4, 0), createColumn<Int64>({0, 0, 0, 0})); ASSERT_BITAND(createColumn<Int8>({0, 0, 1, 1}), createConstColumn<Nullable<UInt64>>(4, 0), createColumn<Nullable<Int64>>({0, 0, 0, 0})); ASSERT_BITAND(createColumn<Int8>({0, 0, 1, 1}), createConstColumn<Nullable<UInt64>>(4, std::nullopt), createConstColumn<Nullable<Int64>>(4, std::nullopt)); // become const in wrapInNullable ASSERT_BITAND(createColumn<Nullable<Int8>>({0, 1, std::nullopt, std::nullopt}), createColumn<UInt64>({0, 1, 0, 1}), createColumn<Nullable<Int64>>({0, 1, std::nullopt, std::nullopt})); ASSERT_BITAND(createColumn<Nullable<Int8>>({0, 1, std::nullopt, std::nullopt}), createColumn<Nullable<UInt64>>({0, 1, std::nullopt, std::nullopt}), createColumn<Nullable<Int64>>({0, 1, std::nullopt, std::nullopt})); ASSERT_BITAND(createColumn<Nullable<Int8>>({0, 1, std::nullopt, std::nullopt}), createConstColumn<UInt64>(4, 0), createColumn<Nullable<Int64>>({0, 0, std::nullopt, std::nullopt})); ASSERT_BITAND(createColumn<Nullable<Int8>>({0, 1, std::nullopt, std::nullopt}), createConstColumn<Nullable<UInt64>>(4, 0), createColumn<Nullable<Int64>>({0, 0, std::nullopt, std::nullopt})); ASSERT_BITAND(createColumn<Nullable<Int8>>({0, 1, std::nullopt, std::nullopt}), createConstColumn<Nullable<UInt64>>(4, std::nullopt), createConstColumn<Nullable<Int64>>(4, std::nullopt)); ASSERT_BITAND(createConstColumn<Int8>(4, 0), createColumn<UInt64>({0, 1, 0, 1}), createColumn<Int64>({0, 0, 0, 0})); ASSERT_BITAND(createConstColumn<Int8>(4, 0), createColumn<Nullable<UInt64>>({0, 1, std::nullopt, std::nullopt}), createColumn<Nullable<Int64>>({0, 0, std::nullopt, std::nullopt})); ASSERT_BITAND(createConstColumn<Int8>(4, 0), createConstColumn<UInt64>(4, 0), createConstColumn<Int64>(4, 0)); ASSERT_BITAND(createConstColumn<Int8>(4, 0), createConstColumn<Nullable<UInt64>>(4, 0), createConstColumn<Nullable<Int64>>(4, 0)); ASSERT_BITAND(createConstColumn<Int8>(4, 0), createConstColumn<Nullable<UInt64>>(4, std::nullopt), createConstColumn<Nullable<Int64>>(4, std::nullopt)); ASSERT_BITAND(createConstColumn<Nullable<Int8>>(4, 0), createColumn<UInt64>({0, 1, 0, 1}), createColumn<Nullable<Int64>>({0, 0, 0, 0})); ASSERT_BITAND(createConstColumn<Nullable<Int8>>(4, 0), createColumn<Nullable<UInt64>>({0, 1, std::nullopt, std::nullopt}), createColumn<Nullable<Int64>>({0, 0, std::nullopt, std::nullopt})); ASSERT_BITAND(createConstColumn<Nullable<Int8>>(4, 0), createConstColumn<UInt64>(4, 0), createConstColumn<Nullable<Int64>>(4, 0)); ASSERT_BITAND(createConstColumn<Nullable<Int8>>(4, 0), createConstColumn<Nullable<UInt64>>(4, 0), createConstColumn<Nullable<Int64>>(4, 0)); ASSERT_BITAND(createConstColumn<Nullable<Int8>>(4, 0), createConstColumn<Nullable<UInt64>>(4, std::nullopt), createConstColumn<Nullable<Int64>>(4, std::nullopt)); ASSERT_BITAND(createConstColumn<Nullable<Int8>>(4, std::nullopt), createColumn<UInt64>({0, 1, 0, 1}), createConstColumn<Nullable<Int64>>(4, std::nullopt)); ASSERT_BITAND(createConstColumn<Nullable<Int8>>(4, std::nullopt), createColumn<Nullable<UInt64>>({0, 1, std::nullopt, std::nullopt}), createConstColumn<Nullable<Int64>>(4, std::nullopt)); ASSERT_BITAND(createConstColumn<Nullable<Int8>>(4, std::nullopt), createConstColumn<UInt64>(4, 0), createConstColumn<Nullable<Int64>>(4, std::nullopt)); ASSERT_BITAND(createConstColumn<Nullable<Int8>>(4, std::nullopt), createConstColumn<Nullable<UInt64>>(4, 0), createConstColumn<Nullable<Int64>>(4, std::nullopt)); ASSERT_BITAND(createConstColumn<Nullable<Int8>>(4, std::nullopt), createConstColumn<Nullable<UInt64>>(4, std::nullopt), createConstColumn<Nullable<Int64>>(4, std::nullopt)); } CATCH TEST_F(TestFunctionBitAnd, Boundary) try { ASSERT_BITAND(createColumn<Int8>({127, 127, -128, -128}), createColumn<UInt8>({0, 255, 0, 255}), createColumn<Int8>({0, 127, 0, -128})); ASSERT_BITAND(createColumn<Int8>({127, 127, -128, -128}), createColumn<UInt16>({0, 65535, 0, 65535}), createColumn<Int16>({0, 127, 0, -128})); ASSERT_BITAND(createColumn<Int16>({32767, 32767, -32768, -32768}), createColumn<UInt8>({0, 255, 0, 255}), createColumn<Int16>({0, 255, 0, 0})); ASSERT_BITAND(createColumn<Int64>({0, 0, 1, 1, -1, -1, INT64_MAX, INT64_MAX, INT64_MIN, INT64_MIN}), createColumn<UInt64>({0, UINT64_MAX, 0, UINT64_MAX, 0, UINT64_MAX, 0, UINT64_MAX, 0, UINT64_MAX}), createColumn<Int64>({0, 0, 0, 1, 0, -1, 0, INT64_MAX, 0, INT64_MIN})); } CATCH TEST_F(TestFunctionBitAnd, UINT64) try { ASSERT_BITAND(createColumn<UInt64>({0, 0, UINT64_MAX, UINT64_MAX}), createColumn<UInt64>({0, UINT64_MAX, 0, UINT64_MAX}), createColumn<UInt64>({0, 0, 0, UINT64_MAX})); ASSERT_BITAND(createColumn<Nullable<UInt64>>({0, 0, UINT64_MAX, UINT64_MAX, 0, std::nullopt}), createColumn<Nullable<UInt64>>({0, UINT64_MAX, 0, UINT64_MAX, std::nullopt, 0}), createColumn<Nullable<UInt64>>({0, 0, 0, UINT64_MAX, std::nullopt, std::nullopt})); ASSERT_BITAND(createColumn<Nullable<UInt64>>({0, 0, UINT64_MAX, UINT64_MAX, std::nullopt}), createColumn<UInt64>({0, UINT64_MAX, 0, UINT64_MAX, 0}), createColumn<Nullable<UInt64>>({0, 0, 0, UINT64_MAX, std::nullopt})); ASSERT_BITAND(createColumn<UInt64>({0, UINT64_MAX, 0, UINT64_MAX, 0}), createColumn<Nullable<UInt64>>({0, 0, UINT64_MAX, UINT64_MAX, std::nullopt}), createColumn<Nullable<UInt64>>({0, 0, 0, UINT64_MAX, std::nullopt})); /* std::mt19937 gen(std::random_device{}()); std::uniform_int_distribution<unsigned long long> dis( std::numeric_limits<std::uint64_t>::min(), std::numeric_limits<std::uint64_t>::max() ); size_t count = 100; std::vector<UINT64> v1(count), v2(count), res(count); for (size_t i=0; i<count; ++i) { v1[i] = dis(gen); v2[i] = dis(gen); res[i] = v1[i] & v2[i]; } */ // clang-format off ASSERT_BITAND(createColumn<UInt64>({7091597907609164394ull,12147405979737555885ull,4944752083022751199ull,5266856817029714805ull,16249582031829054894ull,14585895400450077565ull,16559878625296112963ull,11686022872732312883ull,2252836050652542276ull,18270461639320085260ull,477362305064009683ull,5924031996839311984ull,13502342125078821090ull,1983692735111761557ull,7075393861938658224ull,8534577556983106270ull,6961865328371185981ull,8145880463914069438ull,5244290579560821188ull,10259565555661135100ull,4653092958722629712ull,8153941146514590265ull,16445187578470766485ull,126971754730186422ull,12494401415606381041ull,821635861271395080ull,10789756166060569460ull,17220753103104465161ull,4214870374383746276ull,11087492977524287663ull,13202884495831508537ull,15975448051191870337ull,14627676554537635677ull,4349811632778009896ull,17130992699769672908ull,11200975303296257603ull,7275004492439954170ull,16274625055262694174ull,9100812775640660847ull,10611801488751952495ull,13988464420037366691ull,12715906540348551121ull,11766429052248709786ull,3338715427749605ull,2190861738386064756ull,2380874473443914065ull,5805871478722753955ull,18380152411992198484ull,17753836161221930124ull,558899075728331952ull,6945707259485057305ull,15540448118791785514ull,14100396407684167764ull,7686576470926131642ull,6847113332786445596ull,8571497544299597952ull,5107506230492840013ull,13809089677202756103ull,11850464950116242772ull,8665410045503026098ull,12611995970725331088ull,14716086967124651162ull,8332337353906700486ull,1055042741385964424ull,15747416080677248841ull,14915670236539320530ull,7900308686393206650ull,4979886344023150111ull,5902402781825910141ull,3255426766738440460ull,15073047456619535065ull,14385299733787058194ull,9204231696702233102ull,10378053593247535553ull,17743937090908512033ull,284875276098321550ull,8191444072549517566ull,11831960808665605673ull,16522251628765377415ull,9489110493662951639ull,2985165104683868371ull,1923666239526938648ull,2608156467518575538ull,15010176170111705563ull,8595623925997760729ull,5537255266788969170ull,4026706972241118255ull,10146297908886518879ull,11571719523540239514ull,8947543025284496775ull,6474440949527995615ull,8042516419360849959ull,12772931646054458863ull,8362173284515136314ull,2965170807480292156ull,3697936742835324831ull,2548596695355670143ull,678615102317890017ull,18347860548317292650ull,5348024243900531994ull, }), createColumn<UInt64>({1963993824751904883ull,8092151856919135067ull,5131775057722478077ull,15715528133814023746ull,15505304522311288171ull,10286790629013975231ull,1501823745926746029ull,12973914748851182578ull,8210074373542591108ull,13460194198694121125ull,5224676877811702912ull,9335603723497191999ull,14816589124295502018ull,4954279722715295418ull,11100674508285551899ull,13464602075238859455ull,16853392590959687352ull,1817058812112508107ull,15556867487501561584ull,10284485237014856710ull,14437749781215352280ull,5771839681340207927ull,16055484011087334393ull,3176481359853048004ull,7814936607178752912ull,2494931346489092259ull,8767088596499268464ull,14226279241180503276ull,7473321867985919185ull,6734041306837931713ull,13235889048871924509ull,10991267203008554602ull,16751923766106295286ull,10095830120191421323ull,16222110847614790525ull,9842614984677906240ull,4933809552431881486ull,8405192294344557484ull,4959648925715618956ull,6697802956154799897ull,12131820337280328334ull,7842863996271662529ull,16569735361616664303ull,12858241103410228367ull,5513953872175351416ull,859413842831558633ull,13344669626051684726ull,13723621615205909176ull,15587646588258269977ull,14455229124733503750ull,1897402925930790108ull,15359004855099545708ull,12520174369297951929ull,10652815703651083579ull,8168743478119503616ull,13222025305950777542ull,1407449211367397936ull,719150994271271568ull,13201069077204373904ull,7881062513337573241ull,505835289877393142ull,16274255003040284083ull,5851222720449930723ull,10184171151253590546ull,10760806328248813948ull,11613887821236610307ull,396890304498933892ull,2817599718757852634ull,206272906874991324ull,11706414073185557053ull,1232629356308009454ull,11720363557979026158ull,7397814221360500092ull,17105630191392625269ull,17759165119137150028ull,11745869976822508796ull,13060766979359736635ull,6099807408799721275ull,9051766638104113010ull,9942483311080030083ull,5022375889081250419ull,16686942398742544149ull,17812504368324647606ull,14378217067310861473ull,13056638079919822910ull,6759774801955234976ull,12848167735234317960ull,532081090242244444ull,6210198885610140778ull,12902504877688878394ull,16860750806044045906ull,9057877269281939547ull,6387131386245764054ull,14021225438163328133ull,17155620859144768173ull,5353199724262717805ull,2748605048746777638ull,18127535939063270402ull,7104584635051455285ull,12463829834478575910ull, }), createColumn<UInt64>({162130378342041698ull,2306970147751363337ull,4906399183902082525ull,5192791187330961984ull,13907124735635686698ull,9962525953971236925ull,346918583778004225ull,11532613229130318130ull,1243004632125550596ull,13298056637815390724ull,36528456736988288ull,1726331243280944ull,9872189512905173186ull,36347689790344848ull,144256074823770384ull,3625644066346730142ull,6953842598776156216ull,1225956686928544906ull,4667154241155113152ull,10241542350102922244ull,4616489114865270864ull,5767017669974884913ull,14127801515980751761ull,281625320505476ull,3198685346327036304ull,146085883425597440ull,1272513185338262384ull,14153799398103144456ull,2465177654445579456ull,1825101351191904385ull,13198379756955640345ull,10988802093375644160ull,14446070136962059092ull,871868740806920456ull,16222109997211058252ull,9804857694914446912ull,4931441594151796746ull,6953862676154024716ull,4919078683284953100ull,1170971123190399497ull,9223374512903684738ull,2330455578176390593ull,11619991280813265546ull,426645963123845ull,866099620573742192ull,74309462839738689ull,1157574982499393826ull,13695456519373488144ull,15006629391026759688ull,36321322981392384ull,19151158298030104ull,15357838821927438376ull,9331608240669354000ull,181309540438966586ull,5838094792777667840ull,3923780495183728768ull,180145741880360960ull,694310827035464192ull,11831253089948602640ull,7512330184322847536ull,505536205530431632ull,13841813592565902482ull,5846279246746534082ull,865889046541369856ull,10376856859172309320ull,9235775630514724866ull,396889200523485184ull,367043386831602714ull,56440184765546588ull,2316408220766846988ull,1227838705627107528ull,9413113126569910274ull,7397814219170809868ull,9224005362282401857ull,17741122064043496448ull,216195325862358156ull,3531114965719253050ull,297959404870379049ull,7280724381522551554ull,9344973233195333763ull,81346546033008723ull,185258913461970960ull,2608156312547431090ull,13837468399527035009ull,3819134019844542488ull,5532681290774216832ull,3621347271012271112ull,306882631328345180ull,1970980911154186ull,3462149708829635842ull,5321356472062500946ull,7895938256515104771ull,1153625330601771462ull,4612917523078266880ull,2883431871756632620ull,162165595591180557ull,2451085405657799718ull,648765478774114304ull,7097813840969080864ull,590089416916222210ull, })); // clang-format on } CATCH } // namespace tests } // namespace DB
94.665179
2,386
0.777317
solotzg
b77d00b0b3cc78953d68a764bf11a7ebe8b6ef3f
1,336
cpp
C++
src/scene/SpriteScene.cpp
projectivemotion/sdlgame1
9e126b6ef096605008dfc5db8e9264b68582b38a
[ "MIT" ]
null
null
null
src/scene/SpriteScene.cpp
projectivemotion/sdlgame1
9e126b6ef096605008dfc5db8e9264b68582b38a
[ "MIT" ]
null
null
null
src/scene/SpriteScene.cpp
projectivemotion/sdlgame1
9e126b6ef096605008dfc5db8e9264b68582b38a
[ "MIT" ]
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: SpriteScene.cpp * Author: eye * * Created on October 15, 2019, 4:33 PM */ #include "SpriteScene.h" #include "DrawableTexture.h" #include "entities/entity.h" bool SpriteScene::init() { auto am = app->getAssetManager(); auto canvas = am.createSurfaceEntity(300, 200); auto dots = am.openid(ASSET_DOTSIMG); entity<SDL_Surface> a(dots, 100, 100, 0, 0); entity<SDL_Surface> b(dots, 100, 100, 1, 0); entity<SDL_Surface> c(dots, 100, 100, 0, 1); entity<SDL_Surface> d(dots, 100, 100, 1, 1); entity<SDL_Surface> z(dots, 200, 200); canvas.draw(z.move(200,100).resize(100,100)); canvas.draw(a.move(0,0)); canvas.draw(b.move(100,0)); canvas.draw(c.move(200,0)); canvas.draw(d.move(0,100)); // canvas.draw(d); // auto clip = am.fromSurface(canvas, app).resize(100, 100); auto stretched = am.fromSurface(canvas, app).resize(300, 300); auto proportional = am.fromSurface(canvas, app).resize(300, 200).move(300,0); group.add(stretched, app); group.add(proportional, app); return true; } SpriteScene::~SpriteScene() { }
25.692308
81
0.637725
projectivemotion
b787d8c8027dd9c81a46ae29f82fbb07871ae73c
1,077
cpp
C++
tests/test_connect_ports.cpp
verificationcontractor/sc_enhance
d4aa800a0ec20e420c1479fb6ba81c366eaf884f
[ "MIT" ]
3
2021-01-10T13:35:11.000Z
2022-02-08T06:42:55.000Z
tests/test_connect_ports.cpp
verificationcontractor/sc_enhance
d4aa800a0ec20e420c1479fb6ba81c366eaf884f
[ "MIT" ]
1
2022-02-07T19:19:23.000Z
2022-02-12T10:40:23.000Z
tests/test_connect_ports.cpp
verificationcontractor/sc_enhance
d4aa800a0ec20e420c1479fb6ba81c366eaf884f
[ "MIT" ]
null
null
null
#include <systemc> #include "sc_enhance.hpp" using namespace sc_core; using namespace sc_dt; SC_MODULE(producer) { SC_PROCESS_UTILS(producer); sc_out_decl(bool, out_port); SC_THREAD_DECLARE(logic) SC_THREAD_BEGIN bool x = false; out_port.write(0); sc_repeat(5) { out_port.write(x); x = !x; wait(5, SC_NS); } sc_stop(); SC_THREAD_END SC_CONS(producer) {} }; SC_MODULE(consumer) { SC_PROCESS_UTILS(consumer); sc_in_decl(bool, in_port); SC_METHOD_DECLARE(logic) sensitive << in_port.pos(); SC_METHOD_BEGIN std::cout << "Found posedge." << std::endl; SC_METHOD_END SC_CONS(consumer) {} }; SC_MODULE(tb) { SC_PROCESS_UTILS(tb); sc_signal_decl(bool, signal); sc_instance(producer, prod); sc_instance(consumer, cons); CONNECT_PORTS_BEGIN prod.out_port(signal); cons.in_port(signal); CONNECT_PORTS_END SC_CONS(tb) {} }; int sc_main(int argc, char** argv) { tb tb_inst("tb_inst"); sc_start(); return 0; }
17.370968
49
0.628598
verificationcontractor
b78bbdae64676266973a03e73617c37f4f107cd1
6,244
cpp
C++
openEAR-0.1.0/src/SMILExtract.cpp
trimlab/Voice-Emotion-Detection
c7272dd2f70e2d4b8eee304e68578494d7ef624c
[ "MIT" ]
null
null
null
openEAR-0.1.0/src/SMILExtract.cpp
trimlab/Voice-Emotion-Detection
c7272dd2f70e2d4b8eee304e68578494d7ef624c
[ "MIT" ]
null
null
null
openEAR-0.1.0/src/SMILExtract.cpp
trimlab/Voice-Emotion-Detection
c7272dd2f70e2d4b8eee304e68578494d7ef624c
[ "MIT" ]
null
null
null
/*F****************************************************************************** * * openSMILE - open Speech and Music Interpretation by Large-space Extraction * the open-source Munich Audio Feature Extraction Toolkit * Copyright (C) 2008-2009 Florian Eyben, Martin Woellmer, Bjoern Schuller * * * Institute for Human-Machine Communication * Technische Universitaet Muenchen (TUM) * D-80333 Munich, Germany * * * If you use openSMILE or any code from openSMILE in your research work, * you are kindly asked to acknowledge the use of openSMILE in your publications. * See the file CITING.txt for details. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ******************************************************************************E*/ /* This is the main commandline application */ #include <smileCommon.hpp> #include <configManager.hpp> #include <commandlineParser.hpp> #include <componentManager.hpp> #define MODULE "SMILExtract" /************** Ctrl+C signal handler **/ #include <signal.h> cComponentManager *cmanGlob = NULL; void INThandler(int); int ctrlc = 0; void INThandler(int sig) { signal(sig, SIG_IGN); if (cmanGlob != NULL) cmanGlob->requestAbort(); signal(SIGINT, INThandler); ctrlc = 1; } /*******************************************/ int main(int argc, char *argv[]) { try { // set up the smile logger LOGGER.setLogLevel(1); LOGGER.enableConsoleOutput(); // commandline parser: cCommandlineParser cmdline(argc,argv); cmdline.addStr( "configfile", 'C', "Path to openSMILE config file", "smile.conf" ); cmdline.addInt( "loglevel", 'l', "Verbosity level (0-9)", 2 ); #ifdef DEBUG cmdline.addBoolean( "debug", 'd', "Show debug messages (on/off)", 0 ); #endif cmdline.addInt( "nticks", 't', "Number of ticks to process (-1 = infinite) (only works for single thread processing, i.e. nThreads=1)", -1 ); //cmdline.addBoolean( "configHelp", 'H', "Show documentation of registered config types (on/off)", 0 ); cmdline.addBoolean( "components", 'L', "Show component list", 0 ); cmdline.addStr( "configHelp", 'H', "Show documentation of registered config types (on/off/argument) (if an argument is given, show only documentation for config types beginning with the name given in the argument)", NULL, 0 ); cmdline.addBoolean( "ccmdHelp", 'c', "Show custom commandline option help (those specified in config file)", 0 ); cmdline.addStr( "logfile", 0, "set log file", "smile.log" ); cmdline.addBoolean( "nologfile", 0, "don't write to a log file (e.g. on a read-only filesystem)", 0 ); cmdline.addBoolean( "noconsoleoutput", 0, "don't output any messages to the console (log file is not affected by this option)", 0 ); cmdline.addBoolean( "appendLogfile", 0, "append log messages to an existing logfile instead of overwriting the logfile at every start", 0 ); int help = 0; if (cmdline.doParse() == -1) { LOGGER.setLogLevel(0); help = 1; } if (argc <= 1) { printf("\nNo commandline options were given.\n Please run ' SMILExtract -h ' to see some usage information!\n\n"); return 10; } if (cmdline.getBoolean("nologfile")) { LOGGER.setLogFile((const char *)NULL,0,!(cmdline.getBoolean("noconsoleoutput"))); } else { LOGGER.setLogFile(cmdline.getStr("logfile"),cmdline.getBoolean("appendLogfile"),!(cmdline.getBoolean("noconsoleoutput"))); } LOGGER.setLogLevel(cmdline.getInt("loglevel")); SMILE_MSG(2,"openSMILE starting!"); #ifdef DEBUG // ?? if (!cmdline.getBoolean("debug")) LOGGER.setLogLevel(LOG_DEBUG, 0); #endif SMILE_MSG(2,"config file is: %s",cmdline.getStr("configfile")); // create configManager: cConfigManager *configManager = new cConfigManager(&cmdline); cComponentManager *cMan = new cComponentManager(configManager,componentlist); const char *selStr=NULL; if (cmdline.isSet("configHelp")) { selStr = cmdline.getStr("configHelp"); configManager->printTypeHelp(0,selStr); help = 1; } if (cmdline.getBoolean("components")) { cMan->printComponentList(); help = 1; } if (help==1) { delete configManager; delete cMan; return -1; } // TODO: read config here and print ccmdHelp... // add the file config reader: configManager->addReader( new cFileConfigReader( cmdline.getStr("configfile") ) ); configManager->readConfig(); /* re-parse the command-line to include options created in the config file */ cmdline.doParse(1,0); // warn if unknown options are detected on the commandline if (cmdline.getBoolean("ccmdHelp")) { cmdline.showUsage(); delete configManager; delete cMan; return -1; } /* create all instances specified in the config file */ cMan->createInstances(0); // 0 = do not read config (we already did that above..) /* MAIN TICK LOOP : */ cmanGlob = cMan; signal(SIGINT, INThandler); // install Ctrl+C signal handler /* run single or mutli-threaded, depending on componentManager config in config file */ long long nTicks = cMan->runMultiThreaded(cmdline.getInt("nticks")); /* it is important that configManager is deleted BEFORE componentManger! (since component Manger unregisters plugin Dlls, which might have allocated configTypes, etc.) */ delete configManager; delete cMan; } catch(cSMILException *c) { // free exception ?? return EXIT_ERROR; } if (ctrlc) return EXIT_CTRLC; return EXIT_SUCCESS; }
34.882682
230
0.662076
trimlab
b7958d2cf1e1eccf58eaa1a4ecb4497f7fcb3737
9,814
cpp
C++
src/AST/domain.cpp
NVIDIA/Forma
486bd4bd1fdde5c51bafca3fb80901be904967c0
[ "BSD-3-Clause" ]
10
2016-08-12T05:50:20.000Z
2020-09-22T04:32:27.000Z
src/AST/domain.cpp
NVIDIA/Forma
486bd4bd1fdde5c51bafca3fb80901be904967c0
[ "BSD-3-Clause" ]
null
null
null
src/AST/domain.cpp
NVIDIA/Forma
486bd4bd1fdde5c51bafca3fb80901be904967c0
[ "BSD-3-Clause" ]
8
2017-02-19T06:43:37.000Z
2021-05-20T08:30:34.000Z
//****************************************************************************// //* Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved. *// //* *// //* Redistribution and use in source and binary forms, with or without *// //* modification, are permitted provided that the following conditions *// //* are met: *// //* * Redistributions of source code must retain the above copyright *// //* notice, this list of conditions and the following disclaimer. *// //* * Redistributions in binary form must reproduce the above copyright *// //* notice, this list of conditions and the following disclaimer in the *// //* documentation and/or other materials provided with the distribution. *// //* * Neither the name of NVIDIA CORPORATION nor the names of its *// //* contributors may be used to endorse or promote products derived *// //* from this software without specific prior written permission. *// //* *// //* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY *// //* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE *// //* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR *// //* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR *// //* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, *// //* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, *// //* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR *// //* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY *// //* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *// //* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE *// //* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *// //****************************************************************************// #include "AST/domain.hpp" #include <cassert> using namespace std; void domain_node::init_domain(const domain_node* inp_domain) { for( deque<range_coeffs>::iterator it = range_list.begin(); it != range_list.end() ; it++ ){ delete it->lb; delete it->ub; } range_list.clear(); for( deque<range_coeffs>::const_iterator it = inp_domain->range_list.begin() ; it != inp_domain->range_list.end() ; it++ ){ //assert(("[ME] : ERROR! : While initializing, base domain is undefined\n", !it->lb->is_default() && ! it->ub->is_default())); range_list.push_back(range_coeffs(parametric_exp::copy(it->lb),parametric_exp::copy(it->ub))); //printf("Allocated : %p , %p\n",range_list.back().lb,range_list.back().ub); } } bool domain_node::check_defined() const { for( deque<range_coeffs>::const_iterator it = range_list.begin(); it != range_list.end() ; it++ ){ if( it->lb->is_default() || it->ub->is_default() ){ return false; } } return true; } void domain_node::realign_domain() { for( deque<range_coeffs>::iterator it = range_list.begin(); it != range_list.end() ; it++){ it->ub = it->ub->subtract(it->lb); delete it->lb; it->lb = new int_expr(0); } } void domain_node::compute_intersection(const domain_node* sub_domain) { assert(sub_domain->get_dim() == (int)range_list.size()); ///Range in sub_domain is a..b deque<range_coeffs>::const_iterator it = sub_domain->range_list.begin(); ///Range in expr_domain is c..d , deque<range_coeffs>::iterator jt = range_list.begin(); int dim_num = 0; for( ; it != sub_domain->range_list.end() ; it++, jt++, dim_num++){ assert( (!jt->lb->is_default() && ! jt->ub->is_default()) && "[ME] : ERROR! : While computing intersection, base domain is undefined\n"); parametric_exp *low,*high; low = ( it->lb->is_default() ? jt->lb : jt->lb->max(it->lb) ); high = ( it->ub->is_default() ? jt->ub : jt->ub->min(it->ub) ); // jt->lb = new int_expr(0); // jt->ub = high->subtract(low,true); jt->lb = low; jt->ub = high; } } void domain_node::compute_scale_down(const domainfn_node* scale_fn) { assert(scale_fn->get_dim() == (int)range_list.size()); ///Scale fn is (c,d) deque<scale_coeffs>::const_iterator it = scale_fn->scale_fn.begin(); ///Range in sub_domain is a..b deque<range_coeffs>::iterator jt = range_list.begin(); int dim_num = 0; for( ; it != scale_fn->scale_fn.end() ; it++,jt++,dim_num++){ assert(( !jt->lb->is_default() && ! jt->ub->is_default()) && "[ME] : ERROR! : While computing scale_down, base domain is undefined\n"); assert( (jt->lb->type == P_INT && static_cast<const int_expr*>(jt->lb)->value == 0 ) && "[ME] : Failed assumption that lower bound of scaled down domain is always 0"); parametric_exp *low,*high; if( it->scale == 1 ){ low = (jt->lb); high = (jt->ub); } else{ // low = jt->lb->subtract(it->offset)->ceil(it->scale); //CEIL(jt->lb - it->offset,it->scale); // high = jt->ub->subtract(it->offset)->divide(it->scale); // (jt->ub - it->offset) / it->scale; low = jt->lb; high = jt->ub->add(1)->divide(it->scale)->subtract(1); } // jt->lb = new int_expr(0); // jt->ub = high->subtract(low,true); jt->lb = low; jt->ub = high; } } void domain_node::compute_scale_up(const domainfn_node* scale_fn) { assert(scale_fn->get_dim() == (int)range_list.size()); ///Scale fn is (c,d) deque<scale_coeffs>::const_iterator it = scale_fn->scale_fn.begin(); ///Range in sub_domain is a..b deque<range_coeffs>::iterator jt = range_list.begin(); int dim_num = 0; for( ; it != scale_fn->scale_fn.end() ; it++,jt++,dim_num++){ assert((!jt->lb->is_default() && ! jt->ub->is_default()) && "[ME] : ERROR! : While computing scale_up, base domain is undefined\n"); assert( (jt->lb->type == P_INT && static_cast<const int_expr*>(jt->lb)->value == 0 ) && "[ME] : Failed assumption that lower bound of scaled up domain is always 0"); ///For now, the output domain, always starts at 0, and ends at c+b*d parametric_exp *low,*high; if( it->scale == 1 ){ low = jt->lb; high = jt->ub; } else{ // int min_input = CEIL( 0 - it->offset , it->scale ); // low = MIN(0,it->offset + it->scale * min_input); delete jt->lb; low = new int_expr(0); // (it->offset < 0 ? new int_expr(it->scale + it->offset) : new int_expr(it->offset) ); // high = jt->ub->multiply(it->scale)->add(it->offset); /// it->offset + jt->ub * it->scale; high = jt->ub->add(1)->multiply(it->scale)->subtract(1); } // jt->lb = new int_expr(0); // jt->ub = high->subtract(low,true); jt->lb = low; jt->ub = high; } } void domain_node::compute_union(const domain_node* union_domain) { assert(range_list.size() == union_domain->range_list.size()); ///The range of the input domain is c..d deque<range_coeffs>::const_iterator it = union_domain->range_list.begin(); ///The range of the current domain is a..b deque<range_coeffs>::iterator jt = range_list.begin(); int dim_num = 0; for( ; it != union_domain->range_list.end() ; it++, jt++, dim_num++){ assert((!jt->lb->is_default() && ! jt->ub->is_default()) && "[ME] : ERROR! : While computing union, base domain is undefined\n"); parametric_exp* low = ( it->lb->is_default() ? jt->lb : jt->lb->min(it->lb)); parametric_exp* high = ( it->ub->is_default() ? jt->ub : jt->ub->max(it->ub)); // jt->lb = new int_expr(0); // jt->ub = high->subtract(low,true); jt->lb = low; jt->ub = high; } } int domain_node::check_if_offset() const { for( deque<range_coeffs>::const_iterator it = range_list.begin() ; it != range_list.end() ; it++ ){ if( !it->ub->is_default() ){ return 0; } } return 1; } void domain_node::add_offset(const domain_node* offset_info) { assert(offset_info->get_dim() >= (int)range_list.size()) ; deque<range_coeffs>::const_reverse_iterator it = offset_info->range_list.rbegin() ; deque<range_coeffs>::reverse_iterator jt = range_list.rbegin(); int dim_num = 0; for( ; jt != range_list.rend() ; it++, jt++, dim_num++ ){ //assert(it->lb == it->ub && it->lb != DEFAULT_RANGE); if (! it->lb->is_default() ){ jt->ub = jt->ub->add(it->lb); } } for( ; it != offset_info->range_list.rend() ; it++ ){ range_list.insert(range_list.begin(),range_coeffs(new int_expr(0),parametric_exp::copy(it->lb))); } // range_list.push_back(range_coeffs(0,it->lb)); } // void domain_node::compute_stencil_domain(const deque<const domainfn_node*>& stencil_accesses) // { // assert(stencil_bounds.size() == range_list.size() ); // deque<range_coeffs>::iterator it = range_list.begin(); // deque<stencil_access_info>::const_iterator jt = stencil_bounds.begin(); // int dim_num = 0; // for( ; jt != stencil_bounds.end() ; jt++ ,it++, dim_num++ ){ // assert(it->lb != DEFAULT_RANGE && it->ub != DEFAULT_RANGE) ; // if( jt->min_scale == 1 ){ // int low = it->lb - jt->min_offset; // int high = it->ub - jt->max_offset; // if( low > high ) { // fprintf(stderr,"[ME] : ERROR!! : At dim %d, Computed range of output of stencil experssion [%d,%d] has no points ",dim_num, low,high); // exit(1); // } // it->lb = 0; // it->ub = high - low; // } // else{ // int npoints = ( it->ub / jt->min_scale ) - ( it->lb / jt->scale ) + 1; // if( npoints <= 0 ){ // fprintf(stderr,"[ME] : ERROR!! : At dim %d, the number of points in output domain is 0",dim_num); // exit(1); // } // } // } // }
42.855895
171
0.593132
NVIDIA
b7974f5615870f97c9dcc40c9b346dca3cb54ddf
2,584
cpp
C++
src/Verde/graphics/Graphics.cpp
Cannedfood/Verde2D
3a09e2ecc6b62281e5190183faef55c8f0447d27
[ "CC0-1.0" ]
null
null
null
src/Verde/graphics/Graphics.cpp
Cannedfood/Verde2D
3a09e2ecc6b62281e5190183faef55c8f0447d27
[ "CC0-1.0" ]
null
null
null
src/Verde/graphics/Graphics.cpp
Cannedfood/Verde2D
3a09e2ecc6b62281e5190183faef55c8f0447d27
[ "CC0-1.0" ]
null
null
null
#include "Graphics.hpp" #include "StaticGraphics.hpp" #include "AtlasAnimation.hpp" #include <unordered_map> #include <cstring> #include <fstream> void Graphics::writeOrPrefab(YAML::Emitter &to) { if(mPrefab.size() != 0) to << mPrefab; else write(to); } std::unordered_map<std::string, std::shared_ptr<Graphics>>* pGraphicsCache = nullptr; void Graphics::InitCache() { pGraphicsCache = new std::unordered_map<std::string, std::shared_ptr<Graphics>>; } void Graphics::FreeCache() { delete pGraphicsCache; } void Graphics::CleanCache() { // TODO: remove unique shared_ptr from cache } std::shared_ptr<Graphics> Graphics::Load(const std::string &s) { if(pGraphicsCache) { auto& p = (*pGraphicsCache)[s]; if(!p) { if(s.size() > 4 && strcmp(s.c_str() + s.size() - 4, ".yml") == 0) { std::ifstream file(s, std::ios::binary); if(!file) printf("Failed loading description file %s\n", s.c_str()); else { YAML::Node data; try { data = YAML::Load(file); p = Graphics::Load(data); p->mPrefab = s; } catch(std::exception& e) { printf("Failed loading %s: %s\n", s.c_str(), e.what()); return nullptr; } } } else { p = std::make_shared<StaticGraphics>(); YAML::Node node; node = s; try { if(!((StaticGraphics*)p.get())->load(node)) // Failed loading texture p.reset(); } catch(std::exception& e) { printf("Failed loading %s: %s\n", s.c_str(), e.what()); return nullptr; } } } return p; } else { auto p = std::make_shared<StaticGraphics>(); YAML::Node tmp; tmp = s; if(((StaticGraphics*)p.get())->load(tmp)) return p; else return nullptr; } } std::shared_ptr<Graphics> Graphics::Load(YAML::Node n) { if(!n) return nullptr; if(n.IsScalar()) return Load(n.as<std::string>()); std::shared_ptr<Graphics> p; YAML::Node type_n = n["type"]; if(type_n) { std::string type_s = type_n.as<std::string>(); if(type_s != "default") { if(type_s == "atlas-animation") { p = std::make_shared<AtlasAnimation>(); if(((AtlasAnimation*) p.get())->load(n)) return p; else { printf("Failed loading atlas-animation\n"); return nullptr; } } printf("Graphics: Type %s not supported\n", type_s.c_str()); return nullptr; } } p = Load(n["texture"].as<std::string>()); if(YAML::Node nn = n["wrapping"]) { if(nn.IsSequence()) { p->setWrapping({ nn[0].as<float>(), nn[1].as<float>() }); } else { p->setWrapping(glm::vec2(nn.as<float>())); } } return p; }
20.83871
85
0.596362
Cannedfood
b79787bdc9ae38a4c2f08bc48cdd75e41c4c59d2
433
cpp
C++
C-Programming-Udemy-master/Code/Tutorial 076 - Vectors/Mac/C Plus Plus Tutorial/C Plus Plus Tutorial/main.cpp
PacktPublishing/C-Development-Tutorial-Series---The-Complete-Coding-Guide
7b2d3708a052d9ebda3872603f6bef3dc6003560
[ "MIT" ]
1
2021-10-01T23:23:50.000Z
2021-10-01T23:23:50.000Z
C-Programming-Udemy-master/Code/Tutorial 076 - Vectors/Windows/CPlusPlusTutorial/CPlusPlusTutorial/main.cpp
PacktPublishing/C-Development-Tutorial-Series---The-Complete-Coding-Guide
7b2d3708a052d9ebda3872603f6bef3dc6003560
[ "MIT" ]
null
null
null
C-Programming-Udemy-master/Code/Tutorial 076 - Vectors/Windows/CPlusPlusTutorial/CPlusPlusTutorial/main.cpp
PacktPublishing/C-Development-Tutorial-Series---The-Complete-Coding-Guide
7b2d3708a052d9ebda3872603f6bef3dc6003560
[ "MIT" ]
null
null
null
// // main.cpp // JJJ // // Created by Sonar Systems on 03/07/2014. // Copyright (c) 2014 Sonar Systems. All rights reserved. // #include <iostream> #include <Vector> int main(int argc, const char * argv[]) { std::vector<int> myVector; myVector.push_back(45); myVector.push_back(23); myVector.push_back(1); myVector.push_back(989); std::cout << myVector[3] << std::endl; return 0; }
16.653846
58
0.612009
PacktPublishing
b797b8da62ddc030639442dbbcda567330b71efa
1,718
cpp
C++
Stats_Simulator/Varistein_BattleSimulator/Main.cpp
KuronoaScarlet/Varistein-Battle-Prototype
4409087771a0d00be0e707838858c6782435cf85
[ "MIT" ]
null
null
null
Stats_Simulator/Varistein_BattleSimulator/Main.cpp
KuronoaScarlet/Varistein-Battle-Prototype
4409087771a0d00be0e707838858c6782435cf85
[ "MIT" ]
null
null
null
Stats_Simulator/Varistein_BattleSimulator/Main.cpp
KuronoaScarlet/Varistein-Battle-Prototype
4409087771a0d00be0e707838858c6782435cf85
[ "MIT" ]
null
null
null
#include <iostream> #include "Utils.h" #include <sys/types.h> using namespace std; int main() { srand(time(NULL)); float repeat = 10, simNum = 1000, allyWins, enemWins; int atk = 4, def = 5, hp = 100, cc = 10; int eatk = 10, edef = 10, ehp = 100, ecc = 10; Ability* punch = new Ability(0, 20, 0, "Punch", Tag::OFFENSIVE); Ability* chargedPunch = new Ability(2, 40, 0, "Charged Punch", Tag::OFFENSIVE); Ability* cleave = new Ability(0, 40, 0, "Cleave", Tag::OFFENSIVE); bool cont = true; for (unsigned int i = 0; i < repeat; i++) { allyWins = enemWins = 0; for (unsigned int i = 0; i < simNum; i++) { // Starter variables Character* player = new Character(hp, def, atk, cc, "Nicole"); Character* enemy = new Character(ehp, edef, eatk, ecc, "Monster"); allies.push_back(player); enemies.push_back(enemy); player->abilities.push_back(punch); player->abilities.push_back(chargedPunch); enemy->abilities.push_back(cleave); do { // Player Action if (allies.size() != 0) { PerformSimulatedAction(allies, enemies); cont = Check(); } // Enemy Action if (enemies.size() != 0) { PerformSimulatedAction(enemies, allies); cont = Check(); } } while (cont); if (allies.size() != 0) { allyWins++; allies[0]->abilities.clear(); allies.clear(); } if (enemies.size() != 0) { enemWins++; enemies[0]->abilities.clear(); enemies.clear(); } cont = true; } float aWr = (allyWins / simNum) * 100.0f; float eWr = (enemWins / simNum) * 100.0f; std::cout << "Allies Wr: " << aWr << "%" << endl << "Enemies Wr: " << eWr << "%" << endl << endl; } system("pause"); return 0; }
22.025641
99
0.587893
KuronoaScarlet
b7982235013471533a08b9062c71f6e7de1b5e5f
2,147
hpp
C++
Air-Engine/src/Engine/IO/KeyCodes.hpp
Hyxogen/Air-Engine
a33d0b5bba3b6b71e125c40212a72115c2f73958
[ "Apache-2.0" ]
null
null
null
Air-Engine/src/Engine/IO/KeyCodes.hpp
Hyxogen/Air-Engine
a33d0b5bba3b6b71e125c40212a72115c2f73958
[ "Apache-2.0" ]
11
2021-04-18T15:42:05.000Z
2021-09-08T09:55:04.000Z
Air-Engine/src/Engine/IO/KeyCodes.hpp
Hyxogen/Air-Engine
a33d0b5bba3b6b71e125c40212a72115c2f73958
[ "Apache-2.0" ]
null
null
null
#pragma once namespace engine { namespace io { //Add prefix to keys enum KeyCode { //Non-numpad numbers KEY_0 = 0x01, KEY_1 = 0x02, KEY_2 = 0x03, KEY_3 = 0x04, KEY_4 = 0x05, KEY_5 = 0x06, KEY_6 = 0x07, KEY_7 = 0x08, KEY_8 = 0x09, KEY_9 = 0x0A, //Characters KEY_A = 0x0B, KEY_B = 0x0C, KEY_C = 0x0D, KEY_D = 0x0E, KEY_E = 0x0F, KEY_F = 0x10, KEY_G = 0x11, KEY_H = 0x12, KEY_I = 0x13, KEY_J = 0x14, KEY_K = 0x15, KEY_L = 0x16, KEY_M = 0x17, KEY_N = 0x18, KEY_O = 0x19, KEY_P = 0x1A, KEY_Q = 0x1B, KEY_R = 0x1C, KEY_S = 0x1D, KEY_T = 0x1E, KEY_U = 0x1F, KEY_V = 0x20, KEY_W = 0x21, KEY_X = 0x22, KEY_Y = 0x23, KEY_Z = 0x24, KEY_ESCAPE = 0x25, KEY_TILDE = 0x26, KEY_TAB = 0x27, KEY_CAPS_LOCK = 0x28, KEY_PRINTSCR = 0x29, KEY_INSERT = 0x2A, KEY_DELETE = 0x2B, KEY_SCRLCK = 0x2C, KEY_HOME = 0x2D, KEY_END = 0x2E, KEY_PAUSE = 0x2F, KEY_PAGEUP = 0x30, KEY_PAGEDOWN = 0x31, KEY_UP = 0x32, KEY_LEFT = 0x33, KEY_RIGHT = 0x34, KEY_DOWN = 0x35, KEY_F1 = 0x36, KEY_F2 = 0x37, KEY_F3 = 0x38, KEY_F4 = 0x39, KEY_F5 = 0x3A, KEY_F6 = 0x3B, KEY_F7 = 0x3C, KEY_F8 = 0x3D, KEY_F9 = 0x3E, KEY_F10 = 0x3F, KEY_F11 = 0x40, KEY_F12 = 0x41, KEY_F13 = 0x42, KEY_F14 = 0x43, KEY_F15 = 0x44, KEY_F16 = 0x45, KEY_KP_MULTIPLY = 0x46, KEY_KP_DIVIDE = 0x47, KEY_KP_SUBTRACT = 0x48, KEY_KP_PERIOD = 0x49, KEY_KP_ADD = 0x4A, KEY_KP_0 = 0x4B, KEY_KP_1 = 0x4C, KEY_KP_2 = 0x4D, KEY_KP_3 = 0x4E, KEY_KP_4 = 0x4F, KEY_KP_5 = 0x50, KEY_KP_6 = 0x51, KEY_KP_7 = 0x52, KEY_KP_8 = 0x53, KEY_KP_9 = 0x54, KEY_LSHIFT = 0x55, KEY_LCTRL = 0x56, KEY_RSHIFT = 0x57, KEY_RCTRL = 0x58, KEY_ENTER = 0x59, KEY_BACKSLASH = 0x5A, KEY_UNKNOWN = 0x00 }; } }
19.697248
27
0.517
Hyxogen
b799c1ee976390431876cf1e3d57d4b2066ecc41
7,197
cpp
C++
src/hssh/global_topological/graph.cpp
h2ssh/Vulcan
cc46ec79fea43227d578bee39cb4129ad9bb1603
[ "MIT" ]
6
2020-03-29T09:37:01.000Z
2022-01-20T08:56:31.000Z
src/hssh/global_topological/graph.cpp
h2ssh/Vulcan
cc46ec79fea43227d578bee39cb4129ad9bb1603
[ "MIT" ]
1
2021-03-05T08:00:50.000Z
2021-03-05T08:00:50.000Z
src/hssh/global_topological/graph.cpp
h2ssh/Vulcan
cc46ec79fea43227d578bee39cb4129ad9bb1603
[ "MIT" ]
11
2019-05-13T00:04:38.000Z
2022-01-20T08:56:38.000Z
/* Copyright (C) 2010-2019, The Regents of The University of Michigan. All rights reserved. This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an MIT-style License that can be found at "https://github.com/h2ssh/Vulcan". */ /** * \file graph.cpp * \author Collin Johnson * * Definition of convert_map_to_graph. */ #include <hssh/global_topological/graph.h> #include <hssh/global_topological/topological_map.h> #include <boost/range/adaptor/map.hpp> #include <cassert> namespace vulcan { namespace hssh { TopologicalVertex convert_path_segment_to_vertex(const GlobalPathSegment& segment, const Point<float>& plusPosition, const Point<float>& minusPosition); TopologicalVertex convert_frontier_path_segment_to_vertex(const GlobalPathSegment& segment, const Point<float>& position); void add_explored_segment(const GlobalPathSegment& segment, const TopologicalMap& map, TopologicalGraph& graph); void add_frontier_segment(const GlobalPathSegment& segment, const TopologicalMap& map, TopologicalGraph& graph); GlobalPlace transition_place(const GlobalTransition& transition, const GlobalPathSegment& segment, const TopologicalMap& map); TopologicalGraph convert_map_to_graph(const TopologicalMap& map) { auto& segments = map.segments(); TopologicalGraph graph; for(auto& s : boost::adaptors::values(segments)) { if(s->isFrontier()) { add_frontier_segment(*s, map, graph); } else { add_explored_segment(*s, map, graph); } } return graph; } TopologicalVertex convert_location_to_vertex(const GlobalLocation& location, const TopologicalMap& map) { if(location.areaType == AreaType::path_segment) { assert(map.getPathSegment(location.areaId)); GlobalPathSegment segment = *map.getPathSegment(location.areaId); if(!segment.isFrontier()) { const GlobalPlace plus = transition_place(segment.plusTransition(), segment, map); const GlobalPlace minus = transition_place(segment.minusTransition(), segment, map); return TopologicalVertex(convert_path_segment_to_vertex(segment, map.referenceFrame(plus.id()).toPoint(), map.referenceFrame(minus.id()).toPoint())); } else { auto transition = segment.plusTransition().isFrontier() ? segment.plusTransition() : segment.minusTransition(); GlobalPlace place = transition_place(transition, segment, map); return TopologicalVertex(convert_frontier_path_segment_to_vertex(segment, map.referenceFrame(place.id()).toPoint())); } } else // at a place { return convert_place_to_vertex(*map.getPlace(location.areaId), map); } } TopologicalVertex convert_place_to_vertex(const GlobalPlace& place, const TopologicalMap& map) { Point<float> location = map.referenceFrame(place.id()).toPoint(); return TopologicalVertex(place.id(), location, NodeData(place.id())); } TopologicalVertex convert_path_segment_to_vertex(const GlobalPathSegment& segment, const Point<float>& plusPosition, const Point<float>& minusPosition) { Point<float> segmentLocation((plusPosition.x + minusPosition.x) / 2.0f, (plusPosition.y + minusPosition.y) / 2.0f); return TopologicalVertex(segment.id(), segmentLocation, NodeData(segment.id(), true), segment.lambda().magnitude()); } TopologicalVertex convert_frontier_path_segment_to_vertex(const GlobalPathSegment& segment, const Point<float>& position) { // For frontier segments, put the location halfway down the explored section of the segment. Point<float> segmentLocation((position.x + segment.lambda().x) / 2.0f, (position.y + segment.lambda().y) / 2.0f); return TopologicalVertex(segment.id(), segmentLocation, NodeData(segment.id(), true), segment.lambda().magnitude()); } void add_explored_segment(const GlobalPathSegment& segment, const TopologicalMap& map, TopologicalGraph& graph) { // Ids for the edges in the graph are monotonically increasing. Can just use the current number of edges // as the benchmark for determining the next id auto plus = segment.plusTransition(); auto minus = segment.minusTransition(); TopologicalVertex plusVertex = convert_place_to_vertex(transition_place(plus, segment, map), map); TopologicalVertex minusVertex = convert_place_to_vertex(transition_place(minus, segment, map), map); TopologicalVertex segmentVertex = convert_path_segment_to_vertex(segment, plusVertex.getPosition(), minusVertex.getPosition()); TopologicalEdge plusEdge (graph.numEdges() + 1, plusVertex, segmentVertex, 0.0); TopologicalEdge minusEdge(graph.numEdges() + 2, minusVertex, segmentVertex, 0.0); graph.addVertex(plusVertex); graph.addVertex(minusVertex); graph.addVertex(segmentVertex); graph.addEdge(plusEdge); graph.addEdge(minusEdge); } void add_frontier_segment(const GlobalPathSegment& segment, const TopologicalMap& map, TopologicalGraph& graph) { auto transition = segment.plusTransition().isFrontier() ? segment.plusTransition() : segment.minusTransition(); TopologicalVertex placeVertex = convert_place_to_vertex(transition_place(transition, segment, map), map); TopologicalVertex segmentVertex = convert_frontier_path_segment_to_vertex(segment, placeVertex.getPosition()); TopologicalEdge edge(graph.numEdges() + 1, placeVertex, segmentVertex, 0.0); graph.addVertex(placeVertex); graph.addVertex(segmentVertex); graph.addEdge(edge); } GlobalPlace transition_place(const GlobalTransition& transition, const GlobalPathSegment& segment, const TopologicalMap& map) { return *map.getPlace(transition.otherArea(segment.toArea()).id()); } } // namespace hssh } // namespace vulcan
38.486631
123
0.610393
h2ssh
b79eee5cf0d83a16756de405e62c96c1bfb95195
1,031
hpp
C++
includes/Lists/LinkedList.hpp
matthieu-locussol/Structura
b6b6505b9fcb0ff0689ca42b6f4fcd8d5d80e460
[ "MIT" ]
1
2021-04-29T11:43:27.000Z
2021-04-29T11:43:27.000Z
includes/Lists/LinkedList.hpp
matthieu-locussol/Structura
b6b6505b9fcb0ff0689ca42b6f4fcd8d5d80e460
[ "MIT" ]
null
null
null
includes/Lists/LinkedList.hpp
matthieu-locussol/Structura
b6b6505b9fcb0ff0689ca42b6f4fcd8d5d80e460
[ "MIT" ]
null
null
null
#pragma once #ifndef LISTS_LINKEDLIST_HPP #define LISTS_LINKEDLIST_HPP #include <string> namespace St { template <typename T> class LinkedList { public: LinkedList() = default; LinkedList(LinkedList&&) = default; LinkedList(const LinkedList&) = delete; LinkedList& operator=(LinkedList&&) = default; LinkedList& operator=(const LinkedList&) = delete; std::string serialize() const; const T& get(int position = 0) const; const int& remove(int position = 0); const int& insert(const T& value, int position = 0); const int& append(const T& value); const int& size() const; bool isEmpty() const; ~LinkedList(); private: struct Node { T _value; Node* _next = nullptr; Node(const T& value, Node* next) : _value(value), _next(next){}; }; int _size = 0; Node* _head = nullptr; }; } // namespace St #include <Lists/LinkedList.inl> #endif
23.431818
76
0.583899
matthieu-locussol
b7a21ee24a54fed701d3ae10fc5fffe59fead599
634
cpp
C++
source/glbinding/source/gl/functions_h.cpp
dutow/glbinding
ac12883c4387650c29dbbf01278b7198083750d9
[ "MIT" ]
null
null
null
source/glbinding/source/gl/functions_h.cpp
dutow/glbinding
ac12883c4387650c29dbbf01278b7198083750d9
[ "MIT" ]
null
null
null
source/glbinding/source/gl/functions_h.cpp
dutow/glbinding
ac12883c4387650c29dbbf01278b7198083750d9
[ "MIT" ]
1
2021-07-01T07:45:44.000Z
2021-07-01T07:45:44.000Z
#include "../Binding_pch.h" #include <glbinding/gl/functions.h> using namespace glbinding; namespace gl { void glHint(GLenum target, GLenum mode) { return Binding::Hint(target, mode); } void glHintPGI(GLenum target, GLint mode) { return Binding::HintPGI(target, mode); } void glHistogram(GLenum target, GLsizei width, GLenum internalformat, GLboolean sink) { return Binding::Histogram(target, width, internalformat, sink); } void glHistogramEXT(GLenum target, GLsizei width, GLenum internalformat, GLboolean sink) { return Binding::HistogramEXT(target, width, internalformat, sink); } } // namespace gl
16.684211
88
0.736593
dutow
b7a4edfdc3e3e6749161566872415d40fb41527a
25,029
cpp
C++
server/ttsd_player.cpp
tizenorg/platform.core.uifw.tts
af44daf564960ed74bc1f6b1be5d6842abdce321
[ "Apache-2.0" ]
null
null
null
server/ttsd_player.cpp
tizenorg/platform.core.uifw.tts
af44daf564960ed74bc1f6b1be5d6842abdce321
[ "Apache-2.0" ]
null
null
null
server/ttsd_player.cpp
tizenorg/platform.core.uifw.tts
af44daf564960ed74bc1f6b1be5d6842abdce321
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <mm_types.h> #include <mm_player.h> #include <mm_error.h> #include <Ecore.h> #include "ttsd_main.h" #include "ttsd_player.h" #include "ttsd_data.h" #include "ttsd_dbus.h" /* * Internal data structure */ #define TEMP_FILE_MAX 36 typedef struct { char riff[4]; int file_size; char wave[4]; char fmt[4]; int header_size; short sample_format; short n_channels; int sample_rate; int bytes_per_second; short block_align; short bits_per_sample; char data[4]; int data_size; } WavHeader; typedef struct { int uid; /** client id */ MMHandleType player_handle; /** mm player handle */ int utt_id; /** utt_id of next file */ ttsp_result_event_e event; /** event of callback */ } player_s; typedef struct { int uid; int utt_id; ttsp_result_event_e event; char filename[TEMP_FILE_MAX]; } user_data_s; /* * static data */ #define TEMP_FILE_PATH "/tmp" #define FILE_PATH_SIZE 256 /** player init info */ static bool g_player_init = false; /** tts engine list */ static GList *g_player_list; /** current player information */ static player_s* g_playing_info; /** player callback function */ static player_result_callback_func g_result_callback; /** numbering for temp file */ static unsigned int g_index; /* * Internal Interfaces */ player_s* __player_get_item(int uid); int __save_file(const int uid, const int index, const sound_data_s data, char** filename); int __set_and_start(player_s* player); int __init_wave_header(WavHeader* hdr, size_t nsamples, size_t sampling_rate, int channel); static int msg_callback(int message, void *data, void *user_param) ; /* * Player Interfaces */ int ttsd_player_init(player_result_callback_func result_cb) { if (NULL == result_cb) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] invalid parameter"); return TTSD_ERROR_INVALID_PARAMETER; } g_result_callback = result_cb; g_playing_info = NULL; g_index = 1; g_player_init = true; return 0; } int ttsd_player_release(void) { if (false == g_player_init) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] Not Initialized"); return TTSD_ERROR_OPERATION_FAILED; } /* clear g_player_list */ g_playing_info = NULL; g_player_init = false; return 0; } int ttsd_player_create_instance(const int uid) { if (false == g_player_init) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] Not Initialized" ); return -1; } /* Check uid is duplicated */ if (NULL != __player_get_item(uid)) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] uid(%d) is already registered", uid); return -1; } int ret = MM_ERROR_NONE; MMHandleType player_handle; ret = mm_player_create(&player_handle); if (ret != MM_ERROR_NONE || 0 == player_handle) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] fail mm_player_create() : %x", ret); return -2; } player_s* new_client = (player_s*)g_malloc0( sizeof(player_s) * 1); new_client->uid = uid; new_client->player_handle = player_handle; new_client->utt_id = -1; new_client->event = TTSP_RESULT_EVENT_FINISH; SLOG(LOG_DEBUG, TAG_TTSD, "[Player] Create player : uid(%d), handle(%d)", uid, player_handle ); g_player_list = g_list_append(g_player_list, new_client); return 0; } int ttsd_player_destroy_instance(int uid) { if (false == g_player_init) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] Not Initialized" ); return -1; } player_s* current; current = __player_get_item(uid); if (NULL == current) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] uid(%d) is not valid", uid); return -1; } if (NULL != g_playing_info) { if (uid == g_playing_info->uid) { g_playing_info = NULL; } } MMPlayerStateType player_state; mm_player_get_state(current->player_handle, &player_state); SLOG(LOG_DEBUG, TAG_TTSD, "[PLAYER] State changed : state(%d)", player_state); int ret = -1; /* destroy player */ switch (player_state) { case MM_PLAYER_STATE_PLAYING: case MM_PLAYER_STATE_PAUSED: case MM_PLAYER_STATE_READY: ret = mm_player_unrealize(current->player_handle); if (MM_ERROR_NONE != ret) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] fail mm_player_unrealize() : %x", ret); } /* NO break for destroy */ case MM_PLAYER_STATE_NULL: ret = mm_player_destroy(current->player_handle); if (MM_ERROR_NONE != ret) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] fail mm_player_destroy() : %x", ret); } break; default: break; } GList *iter = NULL; player_s *data = NULL; if (0 < g_list_length(g_player_list)) { /* Get a first item */ iter = g_list_first(g_player_list); while (NULL != iter) { /* Get handle data from list */ data = (player_s*)iter->data; /* compare uid */ if (uid == data->uid) { g_player_list = g_list_remove_link(g_player_list, iter); if (NULL != data) { g_free(data); } break; } /* Get next item */ iter = g_list_next(iter); } } SLOG(LOG_DEBUG, TAG_TTSD, "[PLAYER Success] Destroy instance"); return 0; } int ttsd_player_play(const int uid) { SLOG(LOG_DEBUG, TAG_TTSD, "[Player] start play : uid(%d)", uid ); if (false == g_player_init) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] Not Initialized" ); return -1; } if (NULL != g_playing_info) { if (uid == g_playing_info->uid) { SLOG(LOG_WARN, TAG_TTSD, "[Player WARNING] uid(%d) has already played", g_playing_info->uid); return 0; } } /* Check sound queue size */ if (0 == ttsd_data_get_sound_data_size(uid)) { SLOG(LOG_WARN, TAG_TTSD, "[Player WARNING] A sound queue of current player(%d) is empty", uid); return -1; } /* Check uid */ player_s* current; current = __player_get_item(uid); if (NULL == current) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] uid(%d) is not valid", uid); return -1; } MMPlayerStateType player_state; mm_player_get_state(current->player_handle, &player_state); SLOG(LOG_DEBUG, TAG_TTSD, "[PLAYER] State changed : state(%d)", player_state); switch (player_state) { case MM_PLAYER_STATE_PLAYING: SLOG(LOG_WARN, TAG_TTSD, "[Player] Current player is playing. Do not start new sound."); return 0; case MM_PLAYER_STATE_PAUSED: SLOG(LOG_WARN, TAG_TTSD, "[Player] Player is paused. Do not start new sound."); return -1; case MM_PLAYER_STATE_READY: SLOG(LOG_WARN, TAG_TTSD, "[Player] Player is ready for next play. Do not start new sound."); return -1; case MM_PLAYER_STATE_NULL: break; case MM_PLAYER_STATE_NONE: SLOG(LOG_WARN, TAG_TTSD, "[Player] Player is created. Do not start new sound."); return -1; default: return -1; } int ret; ret = __set_and_start(current); if (0 != ret) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] fail to set or start mm_player"); } SLOG(LOG_DEBUG, TAG_TTSD, "[Player] Started play and wait for played callback : uid(%d)", uid); return 0; } int ttsd_player_next_play(int uid) { if (false == g_player_init) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] Not Initialized" ); return -1; } /* Check uid */ player_s* current; current = __player_get_item(uid); if (NULL == current) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] uid(%d) is not valid", uid); g_playing_info = NULL; return -1; } if (NULL != g_playing_info) { if (uid != g_playing_info->uid) { SLOG(LOG_WARN, TAG_TTSD, "[Player WARNING] Current player(%d) is NOT uid(%d)", g_playing_info->uid, uid); return 0; } } else { SLOG(LOG_WARN, TAG_TTSD, "[Player WARNING] Current player do NOT exist"); return -1; } MMPlayerStateType player_state; mm_player_get_state(current->player_handle, &player_state); SLOG(LOG_DEBUG, TAG_TTSD, "[PLAYER] State changed : state(%d)", player_state); int ret = -1; /* stop player */ switch (player_state) { case MM_PLAYER_STATE_PLAYING: case MM_PLAYER_STATE_PAUSED: case MM_PLAYER_STATE_READY: ret = mm_player_unrealize(current->player_handle); if (MM_ERROR_NONE != ret) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] fail mm_player_unrealize() : %x", ret); return -1; } break; case MM_PLAYER_STATE_NULL: break; default: break; } /* Check sound queue size */ if (0 == ttsd_data_get_sound_data_size(uid)) { SLOG(LOG_WARN, TAG_TTSD, "[Player WARNING] A sound queue of current player(%d) is empty", uid); g_playing_info = NULL; return -1; } ret = __set_and_start(current); if (0 != ret) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] fail to set or start mm_player"); } SLOG(LOG_DEBUG, TAG_TTSD, "[Player] Started play and wait for played callback : uid(%d)", uid); return 0; } int ttsd_player_stop(const int uid) { SLOG(LOG_DEBUG, TAG_TTSD, "[Player] stop player : uid(%d)", uid ); if (false == g_player_init) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] Not Initialized" ); return -1; } /* Check uid */ player_s* current; current = __player_get_item(uid); if (NULL == current) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] uid(%d) is not valid", uid); return -1; } /* check whether uid is current playing or not */ if (NULL != g_playing_info) { if (uid == g_playing_info->uid) { /* release current playing info */ g_playing_info = NULL; } } else { SLOG(LOG_DEBUG, TAG_TTSD, "[Player] No current playing"); } current->utt_id = -1; MMPlayerStateType player_state; mm_player_get_state(current->player_handle, &player_state); SLOG(LOG_DEBUG, TAG_TTSD, "[PLAYER] Current state(%d)", player_state); int ret = -1; switch (player_state) { case MM_PLAYER_STATE_PLAYING: case MM_PLAYER_STATE_PAUSED: case MM_PLAYER_STATE_READY: ret = mm_player_unrealize(current->player_handle); if (MM_ERROR_NONE != ret) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] fail mm_player_unrealize() : %x", ret); return -1; } break; case MM_PLAYER_STATE_NULL: break; default: break; } SLOG(LOG_DEBUG, TAG_TTSD, "[Player SUCCESS] Stop player : uid(%d)", uid); return 0; } int ttsd_player_pause(const int uid) { SLOG(LOG_DEBUG, TAG_TTSD, "[Player] pause player : uid(%d)", uid ); if (false == g_player_init) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] Not Initialized" ); return -1; } /* Check uid */ player_s* current; current = __player_get_item(uid); if (NULL == current) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] ttsd_player_pause() : uid(%d) is not valid", uid); return -1; } /* check whether uid is current playing or not */ if (NULL != g_playing_info) { if (uid == g_playing_info->uid) { /* release current playing info */ g_playing_info = NULL; } else { /* error case */ } } MMPlayerStateType player_state; mm_player_get_state(current->player_handle, &player_state); SLOG(LOG_DEBUG, TAG_TTSD, "[PLAYER] Current state(%d)", player_state); int ret = 0; if (MM_PLAYER_STATE_PLAYING == player_state) { ret = mm_player_pause(current->player_handle); if (MM_ERROR_NONE != ret) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] fail mm_player_pause : %x ", ret); } } else { SLOG(LOG_WARN, TAG_TTSD, "[Player WARNING] Current player is NOT 'playing'"); } return 0; } int ttsd_player_resume(const int uid) { SLOG(LOG_DEBUG, TAG_TTSD, "[Player] Resume player : uid(%d)", uid ); if (false == g_player_init) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] Not Initialized" ); return -1; } /* Check id */ player_s* current; current = __player_get_item(uid); if (NULL == current) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] uid(%d) is not valid", uid); return -1; } /* check current player */ if (NULL != g_playing_info) g_playing_info = NULL; MMPlayerStateType player_state; mm_player_get_state(current->player_handle, &player_state); SLOG(LOG_DEBUG, TAG_TTSD, "[PLAYER] Current state(%d)", player_state); int ret = -1; if (MM_PLAYER_STATE_PAUSED == player_state) { ret = mm_player_resume(current->player_handle); if (MM_ERROR_NONE != ret) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] fail mm_player_resume() : %d", ret); return -1; } else { SLOG(LOG_DEBUG, TAG_TTSD, "[Player] Resume player"); } g_playing_info = current; } else { SLOG(LOG_WARN, TAG_TTSD, "[Player WARNING] Current uid is NOT paused state."); } return 0; } int ttsd_player_get_current_client() { if (false == g_player_init) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] Not Initialized" ); return -1; } if (NULL != g_playing_info) return g_playing_info->uid; SLOG(LOG_WARN, TAG_TTSD, "[Player WARNING] No current player"); return 0; } int ttsd_player_get_current_utterance_id(const int uid) { SLOG(LOG_DEBUG, TAG_TTSD, "[Player] get current utt id : uid(%d)", uid ); if (false == g_player_init) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] Not Initialized" ); return -1; } /* Check uid */ player_s* current; current = __player_get_item(uid); if (NULL == current) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] uid(%d) is not valid", uid); return -1; } return current->utt_id; } int ttsd_player_all_stop() { if (false == g_player_init) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] Not Initialized" ); return -1; } g_playing_info = NULL; int ret = -1; GList *iter = NULL; player_s *data = NULL; if (0 < g_list_length(g_player_list)) { /* Get a first item */ iter = g_list_first(g_player_list); while (NULL != iter) { /* Get handle data from list */ data = (player_s*)iter->data; app_state_e state; if (0 > ttsd_data_get_client_state(data->uid, &state)) { SLOG(LOG_ERROR, TAG_TTSD, "[player ERROR] ttsd_player_all_stop : uid is not valid "); ttsd_player_destroy_instance(data->uid); iter = g_list_next(iter); continue; } if (APP_STATE_PLAYING == state || APP_STATE_PAUSED == state) { /* unrealize player */ ret = mm_player_unrealize(data->player_handle); if (MM_ERROR_NONE != ret) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] fail mm_player_unrealize() : %x", ret); } data->utt_id = -1; data->event = TTSP_RESULT_EVENT_FINISH; } /* Get next item */ iter = g_list_next(iter); } } SLOG(LOG_DEBUG, TAG_TTSD, "[Player SUCCESS] player all stop!! "); return 0; } static Eina_Bool __player_next_play(void *data) { SLOG(LOG_DEBUG, TAG_TTSD, "===== PLAYER NEXT PLAY"); int* uid = (int*)data; SLOG(LOG_DEBUG, TAG_TTSD, "[PLAYER] uid = %d", *uid); if (0 != ttsd_player_next_play(*uid)) { SLOG(LOG_WARN, TAG_TTSD, "[PLAYER WARNING] Fail to play next"); } if (NULL != uid) free(uid); SLOG(LOG_DEBUG, TAG_TTSD, "====="); SLOG(LOG_DEBUG, TAG_TTSD, " "); return EINA_FALSE; } static int msg_callback(int message, void *data, void *user_param) { user_data_s* user_data; user_data = (user_data_s*)user_param; int uid = user_data->uid; int utt_id = user_data->utt_id; switch (message) { case MM_MESSAGE_ERROR: { SLOG(LOG_DEBUG, TAG_TTSD, "===== PLAYER ERROR CALLBACK"); SLOG(LOG_ERROR, TAG_TTSD, "[PLAYER ERROR] Info : uid(%d), utt id(%d), error file(%s)", uid, utt_id, user_data->filename); /* send error info */ g_result_callback(PLAYER_ERROR, uid, utt_id); player_s* current; current = __player_get_item(uid); if (NULL == current) { SLOG(LOG_ERROR, TAG_TTSD, "[PLAYER ERROR] uid(%d) is NOT valid ", uid); } else { current->event = TTSP_RESULT_EVENT_FINISH; } if (NULL != user_data) g_free(user_data); /* check current player */ if (NULL != g_playing_info) { if (uid == g_playing_info->uid) { g_playing_info = NULL; SLOG(LOG_WARN, TAG_TTSD, "[PLAYER] Current Player is NOT uid(%d)", uid); } } SLOG(LOG_DEBUG, TAG_TTSD, "====="); SLOG(LOG_DEBUG, TAG_TTSD, " "); } break; /*MM_MESSAGE_ERROR*/ case MM_MESSAGE_BEGIN_OF_STREAM: { SLOG(LOG_DEBUG, TAG_TTSD, "===== BEGIN OF STREAM CALLBACK"); /* Check uid */ player_s* current; current = __player_get_item(uid); if (NULL == current) { SLOG(LOG_ERROR, TAG_TTSD, "[PLAYER] uid(%d) is NOT valid ", uid); return -1; } if (TTSP_RESULT_EVENT_START == user_data->event || (TTSP_RESULT_EVENT_FINISH == current->event && TTSP_RESULT_EVENT_FINISH == user_data->event)) { int pid; pid = ttsd_data_get_pid(uid); /* send utterance start message */ if (0 == ttsdc_send_utt_start_message(pid, uid, utt_id)) { SLOG(LOG_DEBUG, TAG_TTSD, "[Send SUCCESS] Send Utterance Start Signal : pid(%d), uid(%d), uttid(%d)", pid, uid, utt_id); } else SLOG(LOG_ERROR, TAG_TTSD, "[Send ERROR] Fail to send Utterance Start Signal : pid(%d), uid(%d), uttid(%d)", pid, uid, utt_id); } else { SLOG(LOG_DEBUG, TAG_TTSD, "[PLAYER] Don't need to send Utterance Start Signal"); } /* set current playing info */ current->utt_id = utt_id; current->event = user_data->event; g_playing_info = current; app_state_e state; ttsd_data_get_client_state(uid, &state); /* for sync problem */ if (APP_STATE_PAUSED == state) { MMPlayerStateType player_state; mm_player_get_state(current->player_handle, &player_state); SLOG(LOG_DEBUG, TAG_TTSD, "[PLAYER] Current state(%d)", player_state); int ret = 0; if (MM_PLAYER_STATE_PLAYING == player_state) { ret = mm_player_pause(current->player_handle); if (MM_ERROR_NONE != ret) { SLOG(LOG_ERROR, TAG_TTSD, "[PLAYER ERROR] fail mm_player_pause() : %x", ret); } else { SLOG(LOG_DEBUG, TAG_TTSD, "[PLAYER] uid(%d) changes 'Pause' state ", uid); } } } SLOG(LOG_DEBUG, TAG_TTSD, "====="); SLOG(LOG_DEBUG, TAG_TTSD, " "); } break; case MM_MESSAGE_END_OF_STREAM: { SLOG(LOG_DEBUG, TAG_TTSD, "===== END OF STREAM CALLBACK"); remove(user_data->filename); /* Check uid */ player_s* current; current = __player_get_item(uid); if (NULL == current) { SLOG(LOG_ERROR, TAG_TTSD, "[PLAYER ERROR] uid(%d) is NOT valid", uid); if (NULL != g_playing_info) { if (uid == g_playing_info->uid) { g_playing_info = NULL; SLOG(LOG_WARN, TAG_TTSD, "[PLAYER] Current Player is NOT uid(%d)", uid); } } SLOG(LOG_DEBUG, TAG_TTSD, "====="); SLOG(LOG_DEBUG, TAG_TTSD, " "); return -1; } if (NULL != user_data) g_free(user_data); int pid = ttsd_data_get_pid(uid); /* send utterence finish signal */ if (TTSP_RESULT_EVENT_FINISH == current->event) { if (0 == ttsdc_send_utt_finish_message(pid, uid, utt_id)) SLOG(LOG_DEBUG, TAG_TTSD, "[Send SUCCESS] Send Utterance Completed Signal : pid(%d), uid(%d), uttid(%d)", pid, uid, utt_id); else SLOG(LOG_ERROR, TAG_TTSD, "[Send ERROR] Fail to send Utterance Completed Signal : pid(%d), uid(%d), uttid(%d)", pid, uid, utt_id); } int* uid_data = (int*) g_malloc0(sizeof(int)); *uid_data = uid; SLOG(LOG_DEBUG, TAG_TTSD, "[PLAYER] uid = %d", *uid_data); ecore_timer_add(0, __player_next_play, (void*)uid_data); SLOG(LOG_DEBUG, TAG_TTSD, "====="); SLOG(LOG_DEBUG, TAG_TTSD, " "); } break; /*MM_MESSAGE_END_OF_STREAM*/ case MM_MESSAGE_STATE_CHANGED: break; default: break; } return TRUE; } player_s* __player_get_item(int uid) { GList *iter = NULL; player_s *data = NULL; if (0 < g_list_length(g_player_list)) { /* Get a first item */ iter = g_list_first(g_player_list); while (NULL != iter) { /* Get handle data from list */ data = (player_s*)iter->data; /* compare uid */ if (uid == data->uid) return data; /* Get next item */ iter = g_list_next(iter); } } return NULL; } int __save_file(const int uid, const int index, const sound_data_s data, char** filename) { char postfix[5]; memset(postfix, 0, 5); switch (data.audio_type) { case TTSP_AUDIO_TYPE_RAW: case TTSP_AUDIO_TYPE_WAV: strncpy(postfix, "wav", strlen("wav")); break; case TTSP_AUDIO_TYPE_MP3: strncpy(postfix, "mp3", strlen("mp3")); break; case TTSP_AUDIO_TYPE_AMR: strncpy(postfix, "amr", strlen("amr")); break; default: SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] Audio type(%d) is NOT valid", data.audio_type); return -1; } /* make filename to save */ char* temp; temp = *filename; snprintf(temp, FILE_PATH_SIZE, "%s/ttstemp%d_%d.%s", TEMP_FILE_PATH, uid, index, postfix ); FILE* fp; fp = fopen(temp, "wb"); if (fp == NULL) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] temp file open error"); return -1; } if (data.audio_type == TTSP_AUDIO_TYPE_RAW) { WavHeader header; if (0 != __init_wave_header(&header, data.data_size, data.rate, data.channels)) { fclose(fp); return -1; } if (0 >= fwrite(&header, sizeof(WavHeader), 1, fp)) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] fail to write wav header to file"); fclose(fp); return -1; } } int size = fwrite(data.data, data.data_size, 1, fp); if (size <= 0) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] Fail to write date"); fclose(fp); return -1; } fclose(fp); SLOG(LOG_DEBUG, TAG_TTSD, " "); SLOG(LOG_DEBUG, TAG_TTSD, "Filepath : %s ", temp); SLOG(LOG_DEBUG, TAG_TTSD, "Header : Data size(%d), Sample rate(%d), Channel(%d) ", data.data_size, data.rate, data.channels); return 0; } int __init_wave_header (WavHeader* hdr, size_t nsamples, size_t sampling_rate, int channel) { if (hdr == NULL || nsamples <= 0 || sampling_rate <= 0 || channel <= 0) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] __init_wave_header : input parameter invalid"); return TTSD_ERROR_INVALID_PARAMETER; } size_t bytesize = nsamples; strncpy(hdr->riff, "RIFF", 4); hdr->file_size = (int)(bytesize + 36); strncpy(hdr->wave, "WAVE", 4); strncpy(hdr->fmt, "fmt ", 4); hdr->header_size = 16; hdr->sample_format = 1; /* WAVE_FORMAT_PCM */ hdr->n_channels = channel; hdr->sample_rate = (int)(sampling_rate); hdr->bytes_per_second = (int)sampling_rate * sizeof(short); hdr->block_align = sizeof(short); hdr->bits_per_sample = sizeof(short)*8; strncpy(hdr->data, "data", 4); hdr->data_size = (int)bytesize; return 0; } int __set_and_start(player_s* player) { /* get sound data */ sound_data_s wdata; if (0 != ttsd_data_get_sound_data(player->uid, &wdata)) { SLOG(LOG_WARN, TAG_TTSD, "[Player WARNING] A sound queue of current player(%d) is empty", player->uid); return -1; } g_index++; if (65534 <= g_index) { g_index = 1; } /* make sound file for mmplayer */ char* sound_file = NULL; sound_file = (char*) g_malloc0( sizeof(char) * FILE_PATH_SIZE ); if (0 != __save_file(player->uid, g_index, wdata, &sound_file)) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] fail to make sound file"); return -1; } user_data_s* user_data = (user_data_s*)g_malloc0(sizeof(user_data_s)); user_data->uid = player->uid; user_data->utt_id = wdata.utt_id; user_data->event = wdata.event; memset(user_data->filename, 0, TEMP_FILE_MAX); strncpy( user_data->filename, sound_file, strlen(sound_file) ); SLOG(LOG_DEBUG, TAG_TTSD, "Info : uid(%d), utt(%d), filename(%s) , event(%d)", user_data->uid, user_data->utt_id, user_data->filename, user_data->event); SLOG(LOG_DEBUG, TAG_TTSD, " "); int ret; /* set callback func */ ret = mm_player_set_message_callback(player->player_handle, msg_callback, (void*)user_data); if (MM_ERROR_NONE != ret) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] Fail mm_player_set_message_callback() : %x ", ret); return -1; } /* set playing info to mm player */ char* err_attr_name = NULL; if (0 != access(sound_file, R_OK)) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] Fail to read sound file (%s)", sound_file); return -1; } ret = mm_player_set_attribute(player->player_handle, &err_attr_name, "profile_uri", sound_file , strlen( sound_file ) + 1, "sound_volume_type", MM_SOUND_VOLUME_TYPE_MEDIA, "sound_route", MM_AUDIOROUTE_PLAYBACK_NORMAL, NULL ); if (MM_ERROR_NONE != ret) { if (NULL != err_attr_name) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] Fail mm_player_set_attribute() : msg(%s), result(%x) ", err_attr_name, ret); } return -1; } /* realize and start mm player */ ret = mm_player_realize(player->player_handle); if (MM_ERROR_NONE != ret) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] fail mm_player_realize() : %x", ret); return -2; } ret = mm_player_start(player->player_handle); if (MM_ERROR_NONE != ret) { SLOG(LOG_ERROR, TAG_TTSD, "[Player ERROR] fail mm_player_start() : %x", ret); mm_player_unrealize(player->player_handle); return -3; } if( NULL != sound_file ) g_free(sound_file); if( NULL != wdata.data ) g_free(wdata.data); return 0; }
24.979042
135
0.673818
tizenorg
b7a6cbea9cff8d1602e5b7f70ebf37a7fb6e41a8
9,647
cpp
C++
igraph/src/prpack_base_graph.cpp
jmazon/haskell-igraph
c000ec7939e73d4f563a85751aaeb973bfda7d40
[ "MIT" ]
8
2017-07-22T21:49:37.000Z
2021-02-24T20:57:15.000Z
igraph/src/prpack_base_graph.cpp
jmazon/haskell-igraph
c000ec7939e73d4f563a85751aaeb973bfda7d40
[ "MIT" ]
4
2018-05-22T17:48:16.000Z
2021-03-16T20:23:23.000Z
igraph/src/prpack_base_graph.cpp
jmazon/haskell-igraph
c000ec7939e73d4f563a85751aaeb973bfda7d40
[ "MIT" ]
3
2017-09-08T07:49:21.000Z
2021-04-26T13:00:56.000Z
#include "prpack_base_graph.h" #include "prpack_utils.h" #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <vector> #include <limits> using namespace prpack; using namespace std; void prpack_base_graph::initialize() { heads = NULL; tails = NULL; vals = NULL; } prpack_base_graph::prpack_base_graph() { initialize(); num_vs = num_es = 0; } prpack_base_graph::prpack_base_graph(const prpack_csc* g) { initialize(); num_vs = g->num_vs; num_es = g->num_es; // fill in heads and tails num_self_es = 0; int* hs = g->heads; int* ts = g->tails; tails = new int[num_vs]; memset(tails, 0, num_vs*sizeof(tails[0])); for (int h = 0; h < num_vs; ++h) { const int start_ti = hs[h]; const int end_ti = (h + 1 != num_vs) ? hs[h + 1] : num_es; for (int ti = start_ti; ti < end_ti; ++ti) { const int t = ts[ti]; ++tails[t]; if (h == t) ++num_self_es; } } for (int i = 0, sum = 0; i < num_vs; ++i) { const int temp = sum; sum += tails[i]; tails[i] = temp; } heads = new int[num_es]; int* osets = new int[num_vs]; memset(osets, 0, num_vs*sizeof(osets[0])); for (int h = 0; h < num_vs; ++h) { const int start_ti = hs[h]; const int end_ti = (h + 1 != num_vs) ? hs[h + 1] : num_es; for (int ti = start_ti; ti < end_ti; ++ti) { const int t = ts[ti]; heads[tails[t] + osets[t]++] = h; } } // clean up delete[] osets; } prpack_base_graph::prpack_base_graph(const prpack_int64_csc* g) { initialize(); // TODO remove the assert and add better behavior assert(num_vs <= std::numeric_limits<int>::max()); num_vs = (int)g->num_vs; num_es = (int)g->num_es; // fill in heads and tails num_self_es = 0; int64_t* hs = g->heads; int64_t* ts = g->tails; tails = new int[num_vs]; memset(tails, 0, num_vs*sizeof(tails[0])); for (int h = 0; h < num_vs; ++h) { const int start_ti = (int)hs[h]; const int end_ti = (h + 1 != num_vs) ? (int)hs[h + 1] : num_es; for (int ti = start_ti; ti < end_ti; ++ti) { const int t = (int)ts[ti]; ++tails[t]; if (h == t) ++num_self_es; } } for (int i = 0, sum = 0; i < num_vs; ++i) { const int temp = sum; sum += tails[i]; tails[i] = temp; } heads = new int[num_es]; int* osets = new int[num_vs]; memset(osets, 0, num_vs*sizeof(osets[0])); for (int h = 0; h < num_vs; ++h) { const int start_ti = (int)hs[h]; const int end_ti = (h + 1 != num_vs) ? (int)hs[h + 1] : num_es; for (int ti = start_ti; ti < end_ti; ++ti) { const int t = (int)ts[ti]; heads[tails[t] + osets[t]++] = h; } } // clean up delete[] osets; } prpack_base_graph::prpack_base_graph(const prpack_csr* g) { initialize(); assert(false); // TODO } prpack_base_graph::prpack_base_graph(const prpack_edge_list* g) { initialize(); num_vs = g->num_vs; num_es = g->num_es; // fill in heads and tails num_self_es = 0; int* hs = g->heads; int* ts = g->tails; tails = new int[num_vs]; memset(tails, 0, num_vs*sizeof(tails[0])); for (int i = 0; i < num_es; ++i) { ++tails[ts[i]]; if (hs[i] == ts[i]) ++num_self_es; } for (int i = 0, sum = 0; i < num_vs; ++i) { const int temp = sum; sum += tails[i]; tails[i] = temp; } heads = new int[num_es]; int* osets = new int[num_vs]; memset(osets, 0, num_vs*sizeof(osets[0])); for (int i = 0; i < num_es; ++i) heads[tails[ts[i]] + osets[ts[i]]++] = hs[i]; // clean up delete[] osets; } prpack_base_graph::prpack_base_graph(const char* filename, const char* format, const bool weighted) { initialize(); FILE* f = fopen(filename, "r"); const string s(filename); const string t(format); const string ext = (t == "") ? s.substr(s.rfind('.') + 1) : t; if (ext == "smat") { read_smat(f, weighted); } else { prpack_utils::validate(!weighted, "Error: graph format is not compatible with weighted option."); if (ext == "edges" || ext == "eg2") { read_edges(f); } else if (ext == "graph-txt") { read_ascii(f); } else { prpack_utils::validate(false, "Error: invalid graph format."); } } fclose(f); } prpack_base_graph::~prpack_base_graph() { delete[] heads; delete[] tails; delete[] vals; } void prpack_base_graph::read_smat(FILE* f, const bool weighted) { // read in header double ignore = 0.0; assert(fscanf(f, "%d %lf %d", &num_vs, &ignore, &num_es) == 3); // fill in heads and tails num_self_es = 0; int* hs = new int[num_es]; int* ts = new int[num_es]; heads = new int[num_es]; tails = new int[num_vs]; double* vs = NULL; if (weighted) { vs = new double[num_es]; vals = new double[num_es]; } memset(tails, 0, num_vs*sizeof(tails[0])); for (int i = 0; i < num_es; ++i) { assert(fscanf(f, "%d %d %lf", &hs[i], &ts[i], &((weighted) ? vs[i] : ignore)) == 3); ++tails[ts[i]]; if (hs[i] == ts[i]) ++num_self_es; } for (int i = 0, sum = 0; i < num_vs; ++i) { const int temp = sum; sum += tails[i]; tails[i] = temp; } int* osets = new int[num_vs]; memset(osets, 0, num_vs*sizeof(osets[0])); for (int i = 0; i < num_es; ++i) { const int idx = tails[ts[i]] + osets[ts[i]]++; heads[idx] = hs[i]; if (weighted) vals[idx] = vs[i]; } // clean up delete[] hs; delete[] ts; delete[] vs; delete[] osets; } void prpack_base_graph::read_edges(FILE* f) { vector<vector<int> > al; int h, t; num_es = num_self_es = 0; while (fscanf(f, "%d %d", &h, &t) == 2) { const int m = (h < t) ? t : h; if ((int) al.size() < m + 1) al.resize(m + 1); al[t].push_back(h); ++num_es; if (h == t) ++num_self_es; } num_vs = al.size(); heads = new int[num_es]; tails = new int[num_vs]; for (int tails_i = 0, heads_i = 0; tails_i < num_vs; ++tails_i) { tails[tails_i] = heads_i; for (int j = 0; j < (int) al[tails_i].size(); ++j) heads[heads_i++] = al[tails_i][j]; } } void prpack_base_graph::read_ascii(FILE* f) { assert(fscanf(f, "%d", &num_vs) == 1); while (getc(f) != '\n'); vector<int>* al = new vector<int>[num_vs]; num_es = num_self_es = 0; char s[32]; for (int h = 0; h < num_vs; ++h) { bool line_ended = false; while (!line_ended) { for (int i = 0; ; ++i) { s[i] = getc(f); if ('9' < s[i] || s[i] < '0') { line_ended = s[i] == '\n'; if (i != 0) { s[i] = '\0'; const int t = atoi(s); al[t].push_back(h); ++num_es; if (h == t) ++num_self_es; } break; } } } } heads = new int[num_es]; tails = new int[num_vs]; for (int tails_i = 0, heads_i = 0; tails_i < num_vs; ++tails_i) { tails[tails_i] = heads_i; for (int j = 0; j < (int) al[tails_i].size(); ++j) heads[heads_i++] = al[tails_i][j]; } delete[] al; } prpack_base_graph::prpack_base_graph(int nverts, int nedges, std::pair<int,int>* edges) { initialize(); num_vs = nverts; num_es = nedges; // fill in heads and tails num_self_es = 0; int* hs = new int[num_es]; int* ts = new int[num_es]; tails = new int[num_vs]; memset(tails, 0, num_vs*sizeof(tails[0])); for (int i = 0; i < num_es; ++i) { assert(edges[i].first >= 0 && edges[i].first < num_vs); assert(edges[i].second >= 0 && edges[i].second < num_vs); hs[i] = edges[i].first; ts[i] = edges[i].second; ++tails[ts[i]]; if (hs[i] == ts[i]) ++num_self_es; } for (int i = 0, sum = 0; i < num_vs; ++i) { int temp = sum; sum += tails[i]; tails[i] = temp; } heads = new int[num_es]; int* osets = new int[num_vs]; memset(osets, 0, num_vs*sizeof(osets[0])); for (int i = 0; i < num_es; ++i) heads[tails[ts[i]] + osets[ts[i]]++] = hs[i]; // clean up delete[] hs; delete[] ts; delete[] osets; } /** Normalize the edge weights to sum to one. */ void prpack_base_graph::normalize_weights() { if (!vals) { // skip normalizing weights if not using values return; } std::vector<double> rowsums(num_vs,0.); // the graph is in a compressed in-edge list. for (int i=0; i<num_vs; ++i) { int end_ei = (i + 1 != num_vs) ? tails[i + 1] : num_es; for (int ei=tails[i]; ei < end_ei; ++ei) { int head = heads[ei]; rowsums[head] += vals[ei]; } } for (int i=0; i<num_vs; ++i) { rowsums[i] = 1./rowsums[i]; } for (int i=0; i<num_vs; ++i) { int end_ei = (i + 1 != num_vs) ? tails[i + 1] : num_es; for (int ei=tails[i]; ei < end_ei; ++ei) { vals[ei] *= rowsums[heads[ei]]; } } }
28.883234
101
0.497357
jmazon
b7a6dad9078d2a05fed828dfa606c14d9ec831c4
181
cpp
C++
src/asserter.cpp
IanHG/cutee
b3b3eba5d78b4871847a5251d311b588e7ba97c0
[ "MIT" ]
null
null
null
src/asserter.cpp
IanHG/cutee
b3b3eba5d78b4871847a5251d311b588e7ba97c0
[ "MIT" ]
12
2018-06-18T12:56:33.000Z
2020-09-08T10:29:29.000Z
src/asserter.cpp
IanHG/cutee
b3b3eba5d78b4871847a5251d311b588e7ba97c0
[ "MIT" ]
null
null
null
#include "../include/cutee/typedef.hpp" #include "../include/cutee/suite.hpp" namespace cutee { Cutee_thread_local suite* asserter::_suite_ptr = nullptr; } /* namespace cutee */
18.1
57
0.729282
IanHG
b7aa4dd7bf752da74e01f9965d6e97d55b0fcc23
1,672
cpp
C++
MMOCoreORB/src/server/zone/objects/tangible/variables/SkillModMap.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
18
2017-02-09T15:36:05.000Z
2021-12-21T04:22:15.000Z
MMOCoreORB/src/server/zone/objects/tangible/variables/SkillModMap.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
61
2016-12-30T21:51:10.000Z
2021-12-10T20:25:56.000Z
MMOCoreORB/src/server/zone/objects/tangible/variables/SkillModMap.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
71
2017-01-01T05:34:38.000Z
2022-03-29T01:04:00.000Z
/* * SkillModMap.cpp * * Created on: Jan 31, 2012 * Author: xyborn */ #include "SkillModMap.h" SkillModMap::SkillModMap() { skillMods.setNoDuplicateInsertPlan(); skillMods.setNullValue(0); addSerializableVariables(); } SkillModMap::SkillModMap(const SkillModMap& smm) : Object() { skillMods = smm.skillMods; addSerializableVariables(); } SkillModMap& SkillModMap::operator=(const SkillModMap& smm) { if (this == &smm) return *this; skillMods = smm.skillMods; return *this; } void SkillModMap::add(SkillModMap* smm) { for (int i = 0; i < smm->size(); ++i) { VectorMapEntry<String, int64> entry = smm->skillMods.elementAt(i); skillMods.put(entry.getKey(), skillMods.get(entry.getKey()) + entry.getValue()); } } void SkillModMap::add(VectorMap<String, int64>* map) { for (int i = 0; i < map->size(); ++i) { VectorMapEntry<String, int64> entry = map->elementAt(i); skillMods.put(entry.getKey(), skillMods.get(entry.getKey()) + entry.getValue()); } } void SkillModMap::subtract(SkillModMap* smm) { for (int i = 0; i < smm->skillMods.size(); ++i) { VectorMapEntry<String, int64> entry = smm->skillMods.elementAt(i); int val = skillMods.get(entry.getKey()) - entry.getValue(); if (val <= 0) { skillMods.drop(entry.getKey()); } else { skillMods.put(entry.getKey(), val); } } } void SkillModMap::subtract(VectorMap<String, int64>* map) { for (int i = 0; i < map->size(); ++i) { VectorMapEntry<String, int64> entry = map->elementAt(i); int val = skillMods.get(entry.getKey()) - entry.getValue(); if (val <= 0) { skillMods.drop(entry.getKey()); } else { skillMods.put(entry.getKey(), val); } } }
22.293333
82
0.657895
V-Fib
b7ac322ae93e3bfbb48e3a227c2f936b2046853b
30,362
cpp
C++
CodeGenere/photogram/cEqAppui_PProjInc_M2CEbner.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
451
2016-11-25T09:40:28.000Z
2022-03-30T04:20:42.000Z
CodeGenere/photogram/cEqAppui_PProjInc_M2CEbner.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
143
2016-11-25T20:35:57.000Z
2022-03-01T11:58:02.000Z
CodeGenere/photogram/cEqAppui_PProjInc_M2CEbner.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
139
2016-12-02T10:26:21.000Z
2022-03-10T19:40:29.000Z
// File Automatically generated by eLiSe #include "StdAfx.h" #include "cEqAppui_PProjInc_M2CEbner.h" cEqAppui_PProjInc_M2CEbner::cEqAppui_PProjInc_M2CEbner(): cElCompiledFonc(2) { AddIntRef (cIncIntervale("Intr",0,15)); AddIntRef (cIncIntervale("Orient",15,21)); AddIntRef (cIncIntervale("Tmp_PTer",21,24)); Close(false); } void cEqAppui_PProjInc_M2CEbner::ComputeVal() { double tmp0_ = mCompCoord[15]; double tmp1_ = mCompCoord[16]; double tmp2_ = cos(tmp1_); double tmp3_ = mCompCoord[21]; double tmp4_ = mCompCoord[22]; double tmp5_ = mCompCoord[23]; double tmp6_ = sin(tmp0_); double tmp7_ = cos(tmp0_); double tmp8_ = sin(tmp1_); double tmp9_ = mCompCoord[17]; double tmp10_ = mLocProjI_x * tmp3_; double tmp11_ = mLocProjP0_x + tmp10_; double tmp12_ = mLocProjJ_x * tmp4_; double tmp13_ = tmp11_ + tmp12_; double tmp14_ = mLocProjK_x * tmp5_; double tmp15_ = tmp13_ + tmp14_; double tmp16_ = mCompCoord[18]; double tmp17_ = (tmp15_) - tmp16_; double tmp18_ = sin(tmp9_); double tmp19_ = -(tmp18_); double tmp20_ = -(tmp8_); double tmp21_ = cos(tmp9_); double tmp22_ = mLocProjI_y * tmp3_; double tmp23_ = mLocProjP0_y + tmp22_; double tmp24_ = mLocProjJ_y * tmp4_; double tmp25_ = tmp23_ + tmp24_; double tmp26_ = mLocProjK_y * tmp5_; double tmp27_ = tmp25_ + tmp26_; double tmp28_ = mCompCoord[19]; double tmp29_ = (tmp27_) - tmp28_; double tmp30_ = mLocProjI_z * tmp3_; double tmp31_ = mLocProjP0_z + tmp30_; double tmp32_ = mLocProjJ_z * tmp4_; double tmp33_ = tmp31_ + tmp32_; double tmp34_ = mLocProjK_z * tmp5_; double tmp35_ = tmp33_ + tmp34_; double tmp36_ = mCompCoord[20]; double tmp37_ = (tmp35_) - tmp36_; double tmp38_ = -(tmp6_); double tmp39_ = tmp7_ * tmp20_; double tmp40_ = tmp6_ * tmp20_; double tmp41_ = mCompCoord[0]; double tmp42_ = tmp38_ * tmp19_; double tmp43_ = tmp39_ * tmp21_; double tmp44_ = tmp42_ + tmp43_; double tmp45_ = (tmp44_) * (tmp17_); double tmp46_ = tmp7_ * tmp19_; double tmp47_ = tmp40_ * tmp21_; double tmp48_ = tmp46_ + tmp47_; double tmp49_ = (tmp48_) * (tmp29_); double tmp50_ = tmp45_ + tmp49_; double tmp51_ = tmp2_ * tmp21_; double tmp52_ = tmp51_ * (tmp37_); double tmp53_ = tmp50_ + tmp52_; double tmp54_ = tmp41_ / (tmp53_); double tmp55_ = tmp7_ * tmp2_; double tmp56_ = tmp55_ * (tmp17_); double tmp57_ = tmp6_ * tmp2_; double tmp58_ = tmp57_ * (tmp29_); double tmp59_ = tmp56_ + tmp58_; double tmp60_ = tmp8_ * (tmp37_); double tmp61_ = tmp59_ + tmp60_; double tmp62_ = (tmp61_) * (tmp54_); double tmp63_ = mCompCoord[1]; double tmp64_ = tmp62_ + tmp63_; double tmp65_ = tmp38_ * tmp21_; double tmp66_ = tmp39_ * tmp18_; double tmp67_ = tmp65_ + tmp66_; double tmp68_ = (tmp67_) * (tmp17_); double tmp69_ = tmp7_ * tmp21_; double tmp70_ = tmp40_ * tmp18_; double tmp71_ = tmp69_ + tmp70_; double tmp72_ = (tmp71_) * (tmp29_); double tmp73_ = tmp68_ + tmp72_; double tmp74_ = tmp2_ * tmp18_; double tmp75_ = tmp74_ * (tmp37_); double tmp76_ = tmp73_ + tmp75_; double tmp77_ = (tmp76_) * (tmp54_); double tmp78_ = mCompCoord[2]; double tmp79_ = tmp77_ + tmp78_; double tmp80_ = mLocEbner_State_0_0 * mLocEbner_State_0_0; double tmp81_ = tmp80_ * 0.666667; double tmp82_ = (tmp79_) * (tmp79_); double tmp83_ = tmp82_ - tmp81_; double tmp84_ = (tmp64_) * (tmp64_); double tmp85_ = tmp84_ - tmp81_; double tmp86_ = mCompCoord[3]; double tmp87_ = mCompCoord[4]; double tmp88_ = mCompCoord[5]; double tmp89_ = (tmp64_) * (tmp79_); double tmp90_ = mCompCoord[6]; mVal[0] = ((((1 + tmp86_) * (tmp64_) + tmp87_ * (tmp79_)) - tmp88_ * 2 * (tmp85_) + tmp90_ * tmp89_ + mCompCoord[7] * (tmp83_) + mCompCoord[9] * (tmp64_) * (tmp83_) + mCompCoord[11] * (tmp79_) * (tmp85_) + mCompCoord[13] * (tmp85_) * (tmp83_)) - mLocXIm) * mLocScNorm; mVal[1] = ((((1 - tmp86_) * (tmp79_) + tmp87_ * (tmp64_) + tmp88_ * tmp89_) - tmp90_ * 2 * (tmp83_) + mCompCoord[8] * (tmp85_) + mCompCoord[10] * (tmp79_) * (tmp85_) + mCompCoord[12] * (tmp64_) * (tmp83_) + mCompCoord[14] * (tmp85_) * (tmp83_)) - mLocYIm) * mLocScNorm; } void cEqAppui_PProjInc_M2CEbner::ComputeValDeriv() { double tmp0_ = mCompCoord[15]; double tmp1_ = mCompCoord[16]; double tmp2_ = cos(tmp1_); double tmp3_ = mCompCoord[21]; double tmp4_ = mCompCoord[22]; double tmp5_ = mCompCoord[23]; double tmp6_ = sin(tmp0_); double tmp7_ = cos(tmp0_); double tmp8_ = sin(tmp1_); double tmp9_ = mCompCoord[17]; double tmp10_ = mLocProjI_x * tmp3_; double tmp11_ = mLocProjP0_x + tmp10_; double tmp12_ = mLocProjJ_x * tmp4_; double tmp13_ = tmp11_ + tmp12_; double tmp14_ = mLocProjK_x * tmp5_; double tmp15_ = tmp13_ + tmp14_; double tmp16_ = mCompCoord[18]; double tmp17_ = (tmp15_) - tmp16_; double tmp18_ = sin(tmp9_); double tmp19_ = -(tmp18_); double tmp20_ = -(tmp8_); double tmp21_ = cos(tmp9_); double tmp22_ = mLocProjI_y * tmp3_; double tmp23_ = mLocProjP0_y + tmp22_; double tmp24_ = mLocProjJ_y * tmp4_; double tmp25_ = tmp23_ + tmp24_; double tmp26_ = mLocProjK_y * tmp5_; double tmp27_ = tmp25_ + tmp26_; double tmp28_ = mCompCoord[19]; double tmp29_ = (tmp27_) - tmp28_; double tmp30_ = mLocProjI_z * tmp3_; double tmp31_ = mLocProjP0_z + tmp30_; double tmp32_ = mLocProjJ_z * tmp4_; double tmp33_ = tmp31_ + tmp32_; double tmp34_ = mLocProjK_z * tmp5_; double tmp35_ = tmp33_ + tmp34_; double tmp36_ = mCompCoord[20]; double tmp37_ = (tmp35_) - tmp36_; double tmp38_ = -(tmp6_); double tmp39_ = tmp7_ * tmp20_; double tmp40_ = tmp6_ * tmp20_; double tmp41_ = mCompCoord[0]; double tmp42_ = tmp38_ * tmp19_; double tmp43_ = tmp39_ * tmp21_; double tmp44_ = tmp42_ + tmp43_; double tmp45_ = (tmp44_) * (tmp17_); double tmp46_ = tmp7_ * tmp19_; double tmp47_ = tmp40_ * tmp21_; double tmp48_ = tmp46_ + tmp47_; double tmp49_ = (tmp48_) * (tmp29_); double tmp50_ = tmp45_ + tmp49_; double tmp51_ = tmp2_ * tmp21_; double tmp52_ = tmp51_ * (tmp37_); double tmp53_ = tmp50_ + tmp52_; double tmp54_ = tmp41_ / (tmp53_); double tmp55_ = tmp7_ * tmp2_; double tmp56_ = tmp55_ * (tmp17_); double tmp57_ = tmp6_ * tmp2_; double tmp58_ = tmp57_ * (tmp29_); double tmp59_ = tmp56_ + tmp58_; double tmp60_ = tmp8_ * (tmp37_); double tmp61_ = tmp59_ + tmp60_; double tmp62_ = (tmp61_) * (tmp54_); double tmp63_ = mCompCoord[1]; double tmp64_ = tmp62_ + tmp63_; double tmp65_ = tmp38_ * tmp21_; double tmp66_ = tmp39_ * tmp18_; double tmp67_ = tmp65_ + tmp66_; double tmp68_ = (tmp67_) * (tmp17_); double tmp69_ = tmp7_ * tmp21_; double tmp70_ = tmp40_ * tmp18_; double tmp71_ = tmp69_ + tmp70_; double tmp72_ = (tmp71_) * (tmp29_); double tmp73_ = tmp68_ + tmp72_; double tmp74_ = tmp2_ * tmp18_; double tmp75_ = tmp74_ * (tmp37_); double tmp76_ = tmp73_ + tmp75_; double tmp77_ = (tmp76_) * (tmp54_); double tmp78_ = mCompCoord[2]; double tmp79_ = tmp77_ + tmp78_; double tmp80_ = mLocEbner_State_0_0 * mLocEbner_State_0_0; double tmp81_ = tmp80_ * 0.666667; double tmp82_ = (tmp79_) * (tmp79_); double tmp83_ = tmp82_ - tmp81_; double tmp84_ = (tmp64_) * (tmp64_); double tmp85_ = tmp84_ - tmp81_; double tmp86_ = mCompCoord[3]; double tmp87_ = 1 + tmp86_; double tmp88_ = ElSquare(tmp53_); double tmp89_ = (tmp53_) / tmp88_; double tmp90_ = mCompCoord[4]; double tmp91_ = (tmp89_) * (tmp61_); double tmp92_ = tmp91_ * (tmp64_); double tmp93_ = mCompCoord[5]; double tmp94_ = tmp93_ * 2; double tmp95_ = (tmp89_) * (tmp76_); double tmp96_ = mCompCoord[6]; double tmp97_ = tmp95_ * (tmp79_); double tmp98_ = mCompCoord[7]; double tmp99_ = mCompCoord[9]; double tmp100_ = tmp97_ + tmp97_; double tmp101_ = tmp99_ * (tmp64_); double tmp102_ = mCompCoord[11]; double tmp103_ = tmp92_ + tmp92_; double tmp104_ = tmp102_ * (tmp79_); double tmp105_ = mCompCoord[13]; double tmp106_ = tmp105_ * (tmp85_); double tmp107_ = tmp64_ + tmp64_; double tmp108_ = tmp79_ + tmp79_; double tmp109_ = (tmp64_) * (tmp79_); double tmp110_ = -(1); double tmp111_ = tmp110_ * tmp6_; double tmp112_ = -(tmp7_); double tmp113_ = tmp111_ * tmp20_; double tmp114_ = tmp112_ * tmp19_; double tmp115_ = tmp113_ * tmp21_; double tmp116_ = tmp114_ + tmp115_; double tmp117_ = (tmp116_) * (tmp17_); double tmp118_ = tmp111_ * tmp19_; double tmp119_ = tmp118_ + tmp43_; double tmp120_ = (tmp119_) * (tmp29_); double tmp121_ = tmp117_ + tmp120_; double tmp122_ = tmp41_ * (tmp121_); double tmp123_ = -(tmp122_); double tmp124_ = tmp123_ / tmp88_; double tmp125_ = tmp111_ * tmp2_; double tmp126_ = tmp125_ * (tmp17_); double tmp127_ = tmp55_ * (tmp29_); double tmp128_ = tmp126_ + tmp127_; double tmp129_ = (tmp128_) * (tmp54_); double tmp130_ = (tmp124_) * (tmp61_); double tmp131_ = tmp129_ + tmp130_; double tmp132_ = (tmp131_) * (tmp64_); double tmp133_ = tmp112_ * tmp21_; double tmp134_ = tmp113_ * tmp18_; double tmp135_ = tmp133_ + tmp134_; double tmp136_ = (tmp135_) * (tmp17_); double tmp137_ = tmp111_ * tmp21_; double tmp138_ = tmp137_ + tmp66_; double tmp139_ = (tmp138_) * (tmp29_); double tmp140_ = tmp136_ + tmp139_; double tmp141_ = (tmp140_) * (tmp54_); double tmp142_ = (tmp124_) * (tmp76_); double tmp143_ = tmp141_ + tmp142_; double tmp144_ = (tmp143_) * (tmp79_); double tmp145_ = tmp144_ + tmp144_; double tmp146_ = tmp132_ + tmp132_; double tmp147_ = tmp110_ * tmp8_; double tmp148_ = -(tmp2_); double tmp149_ = tmp148_ * tmp7_; double tmp150_ = tmp148_ * tmp6_; double tmp151_ = tmp149_ * tmp21_; double tmp152_ = tmp151_ * (tmp17_); double tmp153_ = tmp150_ * tmp21_; double tmp154_ = tmp153_ * (tmp29_); double tmp155_ = tmp152_ + tmp154_; double tmp156_ = tmp147_ * tmp21_; double tmp157_ = tmp156_ * (tmp37_); double tmp158_ = tmp155_ + tmp157_; double tmp159_ = tmp41_ * (tmp158_); double tmp160_ = -(tmp159_); double tmp161_ = tmp160_ / tmp88_; double tmp162_ = tmp147_ * tmp7_; double tmp163_ = tmp162_ * (tmp17_); double tmp164_ = tmp147_ * tmp6_; double tmp165_ = tmp164_ * (tmp29_); double tmp166_ = tmp163_ + tmp165_; double tmp167_ = tmp2_ * (tmp37_); double tmp168_ = tmp166_ + tmp167_; double tmp169_ = (tmp168_) * (tmp54_); double tmp170_ = (tmp161_) * (tmp61_); double tmp171_ = tmp169_ + tmp170_; double tmp172_ = (tmp171_) * (tmp64_); double tmp173_ = tmp149_ * tmp18_; double tmp174_ = tmp173_ * (tmp17_); double tmp175_ = tmp150_ * tmp18_; double tmp176_ = tmp175_ * (tmp29_); double tmp177_ = tmp174_ + tmp176_; double tmp178_ = tmp147_ * tmp18_; double tmp179_ = tmp178_ * (tmp37_); double tmp180_ = tmp177_ + tmp179_; double tmp181_ = (tmp180_) * (tmp54_); double tmp182_ = (tmp161_) * (tmp76_); double tmp183_ = tmp181_ + tmp182_; double tmp184_ = (tmp183_) * (tmp79_); double tmp185_ = tmp184_ + tmp184_; double tmp186_ = tmp172_ + tmp172_; double tmp187_ = -(tmp21_); double tmp188_ = tmp110_ * tmp18_; double tmp189_ = tmp187_ * tmp38_; double tmp190_ = tmp188_ * tmp39_; double tmp191_ = tmp189_ + tmp190_; double tmp192_ = (tmp191_) * (tmp17_); double tmp193_ = tmp187_ * tmp7_; double tmp194_ = tmp188_ * tmp40_; double tmp195_ = tmp193_ + tmp194_; double tmp196_ = (tmp195_) * (tmp29_); double tmp197_ = tmp192_ + tmp196_; double tmp198_ = tmp188_ * tmp2_; double tmp199_ = tmp198_ * (tmp37_); double tmp200_ = tmp197_ + tmp199_; double tmp201_ = tmp41_ * (tmp200_); double tmp202_ = -(tmp201_); double tmp203_ = tmp202_ / tmp88_; double tmp204_ = (tmp203_) * (tmp61_); double tmp205_ = tmp204_ * (tmp64_); double tmp206_ = tmp188_ * tmp38_; double tmp207_ = tmp21_ * tmp39_; double tmp208_ = tmp206_ + tmp207_; double tmp209_ = (tmp208_) * (tmp17_); double tmp210_ = tmp188_ * tmp7_; double tmp211_ = tmp21_ * tmp40_; double tmp212_ = tmp210_ + tmp211_; double tmp213_ = (tmp212_) * (tmp29_); double tmp214_ = tmp209_ + tmp213_; double tmp215_ = tmp21_ * tmp2_; double tmp216_ = tmp215_ * (tmp37_); double tmp217_ = tmp214_ + tmp216_; double tmp218_ = (tmp217_) * (tmp54_); double tmp219_ = (tmp203_) * (tmp76_); double tmp220_ = tmp218_ + tmp219_; double tmp221_ = (tmp220_) * (tmp79_); double tmp222_ = tmp221_ + tmp221_; double tmp223_ = tmp205_ + tmp205_; double tmp224_ = tmp110_ * (tmp44_); double tmp225_ = tmp41_ * tmp224_; double tmp226_ = -(tmp225_); double tmp227_ = tmp226_ / tmp88_; double tmp228_ = tmp110_ * tmp55_; double tmp229_ = tmp228_ * (tmp54_); double tmp230_ = (tmp227_) * (tmp61_); double tmp231_ = tmp229_ + tmp230_; double tmp232_ = (tmp231_) * (tmp64_); double tmp233_ = tmp110_ * (tmp67_); double tmp234_ = tmp233_ * (tmp54_); double tmp235_ = (tmp227_) * (tmp76_); double tmp236_ = tmp234_ + tmp235_; double tmp237_ = (tmp236_) * (tmp79_); double tmp238_ = tmp237_ + tmp237_; double tmp239_ = tmp232_ + tmp232_; double tmp240_ = tmp110_ * (tmp48_); double tmp241_ = tmp41_ * tmp240_; double tmp242_ = -(tmp241_); double tmp243_ = tmp242_ / tmp88_; double tmp244_ = tmp110_ * tmp57_; double tmp245_ = tmp244_ * (tmp54_); double tmp246_ = (tmp243_) * (tmp61_); double tmp247_ = tmp245_ + tmp246_; double tmp248_ = (tmp247_) * (tmp64_); double tmp249_ = tmp110_ * (tmp71_); double tmp250_ = tmp249_ * (tmp54_); double tmp251_ = (tmp243_) * (tmp76_); double tmp252_ = tmp250_ + tmp251_; double tmp253_ = (tmp252_) * (tmp79_); double tmp254_ = tmp253_ + tmp253_; double tmp255_ = tmp248_ + tmp248_; double tmp256_ = tmp110_ * tmp51_; double tmp257_ = tmp41_ * tmp256_; double tmp258_ = -(tmp257_); double tmp259_ = tmp258_ / tmp88_; double tmp260_ = tmp147_ * (tmp54_); double tmp261_ = (tmp259_) * (tmp61_); double tmp262_ = tmp260_ + tmp261_; double tmp263_ = (tmp262_) * (tmp64_); double tmp264_ = tmp110_ * tmp74_; double tmp265_ = tmp264_ * (tmp54_); double tmp266_ = (tmp259_) * (tmp76_); double tmp267_ = tmp265_ + tmp266_; double tmp268_ = (tmp267_) * (tmp79_); double tmp269_ = tmp268_ + tmp268_; double tmp270_ = tmp263_ + tmp263_; double tmp271_ = mLocProjI_x * (tmp44_); double tmp272_ = mLocProjI_y * (tmp48_); double tmp273_ = tmp271_ + tmp272_; double tmp274_ = mLocProjI_z * tmp51_; double tmp275_ = tmp273_ + tmp274_; double tmp276_ = tmp41_ * (tmp275_); double tmp277_ = -(tmp276_); double tmp278_ = tmp277_ / tmp88_; double tmp279_ = mLocProjI_x * tmp55_; double tmp280_ = mLocProjI_y * tmp57_; double tmp281_ = tmp279_ + tmp280_; double tmp282_ = mLocProjI_z * tmp8_; double tmp283_ = tmp281_ + tmp282_; double tmp284_ = (tmp283_) * (tmp54_); double tmp285_ = (tmp278_) * (tmp61_); double tmp286_ = tmp284_ + tmp285_; double tmp287_ = (tmp286_) * (tmp64_); double tmp288_ = mLocProjI_x * (tmp67_); double tmp289_ = mLocProjI_y * (tmp71_); double tmp290_ = tmp288_ + tmp289_; double tmp291_ = mLocProjI_z * tmp74_; double tmp292_ = tmp290_ + tmp291_; double tmp293_ = (tmp292_) * (tmp54_); double tmp294_ = (tmp278_) * (tmp76_); double tmp295_ = tmp293_ + tmp294_; double tmp296_ = (tmp295_) * (tmp79_); double tmp297_ = tmp296_ + tmp296_; double tmp298_ = tmp287_ + tmp287_; double tmp299_ = mLocProjJ_x * (tmp44_); double tmp300_ = mLocProjJ_y * (tmp48_); double tmp301_ = tmp299_ + tmp300_; double tmp302_ = mLocProjJ_z * tmp51_; double tmp303_ = tmp301_ + tmp302_; double tmp304_ = tmp41_ * (tmp303_); double tmp305_ = -(tmp304_); double tmp306_ = tmp305_ / tmp88_; double tmp307_ = mLocProjJ_x * tmp55_; double tmp308_ = mLocProjJ_y * tmp57_; double tmp309_ = tmp307_ + tmp308_; double tmp310_ = mLocProjJ_z * tmp8_; double tmp311_ = tmp309_ + tmp310_; double tmp312_ = (tmp311_) * (tmp54_); double tmp313_ = (tmp306_) * (tmp61_); double tmp314_ = tmp312_ + tmp313_; double tmp315_ = (tmp314_) * (tmp64_); double tmp316_ = mLocProjJ_x * (tmp67_); double tmp317_ = mLocProjJ_y * (tmp71_); double tmp318_ = tmp316_ + tmp317_; double tmp319_ = mLocProjJ_z * tmp74_; double tmp320_ = tmp318_ + tmp319_; double tmp321_ = (tmp320_) * (tmp54_); double tmp322_ = (tmp306_) * (tmp76_); double tmp323_ = tmp321_ + tmp322_; double tmp324_ = (tmp323_) * (tmp79_); double tmp325_ = tmp324_ + tmp324_; double tmp326_ = tmp315_ + tmp315_; double tmp327_ = mLocProjK_x * (tmp44_); double tmp328_ = mLocProjK_y * (tmp48_); double tmp329_ = tmp327_ + tmp328_; double tmp330_ = mLocProjK_z * tmp51_; double tmp331_ = tmp329_ + tmp330_; double tmp332_ = tmp41_ * (tmp331_); double tmp333_ = -(tmp332_); double tmp334_ = tmp333_ / tmp88_; double tmp335_ = mLocProjK_x * tmp55_; double tmp336_ = mLocProjK_y * tmp57_; double tmp337_ = tmp335_ + tmp336_; double tmp338_ = mLocProjK_z * tmp8_; double tmp339_ = tmp337_ + tmp338_; double tmp340_ = (tmp339_) * (tmp54_); double tmp341_ = (tmp334_) * (tmp61_); double tmp342_ = tmp340_ + tmp341_; double tmp343_ = (tmp342_) * (tmp64_); double tmp344_ = mLocProjK_x * (tmp67_); double tmp345_ = mLocProjK_y * (tmp71_); double tmp346_ = tmp344_ + tmp345_; double tmp347_ = mLocProjK_z * tmp74_; double tmp348_ = tmp346_ + tmp347_; double tmp349_ = (tmp348_) * (tmp54_); double tmp350_ = (tmp334_) * (tmp76_); double tmp351_ = tmp349_ + tmp350_; double tmp352_ = (tmp351_) * (tmp79_); double tmp353_ = tmp352_ + tmp352_; double tmp354_ = tmp343_ + tmp343_; double tmp355_ = 1 - tmp86_; double tmp356_ = tmp91_ * (tmp79_); double tmp357_ = tmp95_ * (tmp64_); double tmp358_ = tmp356_ + tmp357_; double tmp359_ = tmp96_ * 2; double tmp360_ = mCompCoord[8]; double tmp361_ = mCompCoord[10]; double tmp362_ = tmp361_ * (tmp79_); double tmp363_ = mCompCoord[12]; double tmp364_ = tmp363_ * (tmp64_); double tmp365_ = mCompCoord[14]; double tmp366_ = tmp365_ * (tmp85_); double tmp367_ = (tmp64_) * mLocScNorm; double tmp368_ = tmp109_ * mLocScNorm; double tmp369_ = (tmp79_) * (tmp85_); double tmp370_ = tmp369_ * mLocScNorm; double tmp371_ = (tmp64_) * (tmp83_); double tmp372_ = tmp371_ * mLocScNorm; double tmp373_ = (tmp85_) * (tmp83_); double tmp374_ = tmp373_ * mLocScNorm; double tmp375_ = (tmp131_) * (tmp79_); double tmp376_ = (tmp143_) * (tmp64_); double tmp377_ = tmp375_ + tmp376_; double tmp378_ = (tmp171_) * (tmp79_); double tmp379_ = (tmp183_) * (tmp64_); double tmp380_ = tmp378_ + tmp379_; double tmp381_ = tmp204_ * (tmp79_); double tmp382_ = (tmp220_) * (tmp64_); double tmp383_ = tmp381_ + tmp382_; double tmp384_ = (tmp231_) * (tmp79_); double tmp385_ = (tmp236_) * (tmp64_); double tmp386_ = tmp384_ + tmp385_; double tmp387_ = (tmp247_) * (tmp79_); double tmp388_ = (tmp252_) * (tmp64_); double tmp389_ = tmp387_ + tmp388_; double tmp390_ = (tmp262_) * (tmp79_); double tmp391_ = (tmp267_) * (tmp64_); double tmp392_ = tmp390_ + tmp391_; double tmp393_ = (tmp286_) * (tmp79_); double tmp394_ = (tmp295_) * (tmp64_); double tmp395_ = tmp393_ + tmp394_; double tmp396_ = (tmp314_) * (tmp79_); double tmp397_ = (tmp323_) * (tmp64_); double tmp398_ = tmp396_ + tmp397_; double tmp399_ = (tmp342_) * (tmp79_); double tmp400_ = (tmp351_) * (tmp64_); double tmp401_ = tmp399_ + tmp400_; mVal[0] = ((((tmp87_) * (tmp64_) + tmp90_ * (tmp79_)) - tmp94_ * (tmp85_) + tmp96_ * tmp109_ + tmp98_ * (tmp83_) + tmp101_ * (tmp83_) + tmp104_ * (tmp85_) + tmp106_ * (tmp83_)) - mLocXIm) * mLocScNorm; mCompDer[0][0] = ((tmp91_ * (tmp87_) + tmp95_ * tmp90_) - (tmp103_) * tmp94_ + (tmp358_) * tmp96_ + (tmp100_) * tmp98_ + tmp91_ * tmp99_ * (tmp83_) + (tmp100_) * tmp101_ + tmp95_ * tmp102_ * (tmp85_) + (tmp103_) * tmp104_ + (tmp103_) * tmp105_ * (tmp83_) + (tmp100_) * tmp106_) * mLocScNorm; mCompDer[0][1] = ((tmp87_) - (tmp107_) * tmp94_ + (tmp79_) * tmp96_ + tmp99_ * (tmp83_) + (tmp107_) * tmp104_ + (tmp107_) * tmp105_ * (tmp83_)) * mLocScNorm; mCompDer[0][2] = (tmp90_ + (tmp64_) * tmp96_ + (tmp108_) * tmp98_ + (tmp108_) * tmp101_ + tmp102_ * (tmp85_) + (tmp108_) * tmp106_) * mLocScNorm; mCompDer[0][3] = tmp367_; mCompDer[0][4] = (tmp79_) * mLocScNorm; mCompDer[0][5] = -(2 * (tmp85_)) * mLocScNorm; mCompDer[0][6] = tmp368_; mCompDer[0][7] = (tmp83_) * mLocScNorm; mCompDer[0][8] = 0; mCompDer[0][9] = tmp372_; mCompDer[0][10] = 0; mCompDer[0][11] = tmp370_; mCompDer[0][12] = 0; mCompDer[0][13] = tmp374_; mCompDer[0][14] = 0; mCompDer[0][15] = (((tmp131_) * (tmp87_) + (tmp143_) * tmp90_) - (tmp146_) * tmp94_ + (tmp377_) * tmp96_ + (tmp145_) * tmp98_ + (tmp131_) * tmp99_ * (tmp83_) + (tmp145_) * tmp101_ + (tmp143_) * tmp102_ * (tmp85_) + (tmp146_) * tmp104_ + (tmp146_) * tmp105_ * (tmp83_) + (tmp145_) * tmp106_) * mLocScNorm; mCompDer[0][16] = (((tmp171_) * (tmp87_) + (tmp183_) * tmp90_) - (tmp186_) * tmp94_ + (tmp380_) * tmp96_ + (tmp185_) * tmp98_ + (tmp171_) * tmp99_ * (tmp83_) + (tmp185_) * tmp101_ + (tmp183_) * tmp102_ * (tmp85_) + (tmp186_) * tmp104_ + (tmp186_) * tmp105_ * (tmp83_) + (tmp185_) * tmp106_) * mLocScNorm; mCompDer[0][17] = ((tmp204_ * (tmp87_) + (tmp220_) * tmp90_) - (tmp223_) * tmp94_ + (tmp383_) * tmp96_ + (tmp222_) * tmp98_ + tmp204_ * tmp99_ * (tmp83_) + (tmp222_) * tmp101_ + (tmp220_) * tmp102_ * (tmp85_) + (tmp223_) * tmp104_ + (tmp223_) * tmp105_ * (tmp83_) + (tmp222_) * tmp106_) * mLocScNorm; mCompDer[0][18] = (((tmp231_) * (tmp87_) + (tmp236_) * tmp90_) - (tmp239_) * tmp94_ + (tmp386_) * tmp96_ + (tmp238_) * tmp98_ + (tmp231_) * tmp99_ * (tmp83_) + (tmp238_) * tmp101_ + (tmp236_) * tmp102_ * (tmp85_) + (tmp239_) * tmp104_ + (tmp239_) * tmp105_ * (tmp83_) + (tmp238_) * tmp106_) * mLocScNorm; mCompDer[0][19] = (((tmp247_) * (tmp87_) + (tmp252_) * tmp90_) - (tmp255_) * tmp94_ + (tmp389_) * tmp96_ + (tmp254_) * tmp98_ + (tmp247_) * tmp99_ * (tmp83_) + (tmp254_) * tmp101_ + (tmp252_) * tmp102_ * (tmp85_) + (tmp255_) * tmp104_ + (tmp255_) * tmp105_ * (tmp83_) + (tmp254_) * tmp106_) * mLocScNorm; mCompDer[0][20] = (((tmp262_) * (tmp87_) + (tmp267_) * tmp90_) - (tmp270_) * tmp94_ + (tmp392_) * tmp96_ + (tmp269_) * tmp98_ + (tmp262_) * tmp99_ * (tmp83_) + (tmp269_) * tmp101_ + (tmp267_) * tmp102_ * (tmp85_) + (tmp270_) * tmp104_ + (tmp270_) * tmp105_ * (tmp83_) + (tmp269_) * tmp106_) * mLocScNorm; mCompDer[0][21] = (((tmp286_) * (tmp87_) + (tmp295_) * tmp90_) - (tmp298_) * tmp94_ + (tmp395_) * tmp96_ + (tmp297_) * tmp98_ + (tmp286_) * tmp99_ * (tmp83_) + (tmp297_) * tmp101_ + (tmp295_) * tmp102_ * (tmp85_) + (tmp298_) * tmp104_ + (tmp298_) * tmp105_ * (tmp83_) + (tmp297_) * tmp106_) * mLocScNorm; mCompDer[0][22] = (((tmp314_) * (tmp87_) + (tmp323_) * tmp90_) - (tmp326_) * tmp94_ + (tmp398_) * tmp96_ + (tmp325_) * tmp98_ + (tmp314_) * tmp99_ * (tmp83_) + (tmp325_) * tmp101_ + (tmp323_) * tmp102_ * (tmp85_) + (tmp326_) * tmp104_ + (tmp326_) * tmp105_ * (tmp83_) + (tmp325_) * tmp106_) * mLocScNorm; mCompDer[0][23] = (((tmp342_) * (tmp87_) + (tmp351_) * tmp90_) - (tmp354_) * tmp94_ + (tmp401_) * tmp96_ + (tmp353_) * tmp98_ + (tmp342_) * tmp99_ * (tmp83_) + (tmp353_) * tmp101_ + (tmp351_) * tmp102_ * (tmp85_) + (tmp354_) * tmp104_ + (tmp354_) * tmp105_ * (tmp83_) + (tmp353_) * tmp106_) * mLocScNorm; mVal[1] = ((((tmp355_) * (tmp79_) + tmp90_ * (tmp64_) + tmp93_ * tmp109_) - tmp359_ * (tmp83_) + tmp360_ * (tmp85_) + tmp362_ * (tmp85_) + tmp364_ * (tmp83_) + tmp366_ * (tmp83_)) - mLocYIm) * mLocScNorm; mCompDer[1][0] = ((tmp95_ * (tmp355_) + tmp91_ * tmp90_ + (tmp358_) * tmp93_) - (tmp100_) * tmp359_ + (tmp103_) * tmp360_ + tmp95_ * tmp361_ * (tmp85_) + (tmp103_) * tmp362_ + tmp91_ * tmp363_ * (tmp83_) + (tmp100_) * tmp364_ + (tmp103_) * tmp365_ * (tmp83_) + (tmp100_) * tmp366_) * mLocScNorm; mCompDer[1][1] = (tmp90_ + (tmp79_) * tmp93_ + (tmp107_) * tmp360_ + (tmp107_) * tmp362_ + tmp363_ * (tmp83_) + (tmp107_) * tmp365_ * (tmp83_)) * mLocScNorm; mCompDer[1][2] = ((tmp355_ + (tmp64_) * tmp93_) - (tmp108_) * tmp359_ + tmp361_ * (tmp85_) + (tmp108_) * tmp364_ + (tmp108_) * tmp366_) * mLocScNorm; mCompDer[1][3] = tmp110_ * (tmp79_) * mLocScNorm; mCompDer[1][4] = tmp367_; mCompDer[1][5] = tmp368_; mCompDer[1][6] = -(2 * (tmp83_)) * mLocScNorm; mCompDer[1][7] = 0; mCompDer[1][8] = (tmp85_) * mLocScNorm; mCompDer[1][9] = 0; mCompDer[1][10] = tmp370_; mCompDer[1][11] = 0; mCompDer[1][12] = tmp372_; mCompDer[1][13] = 0; mCompDer[1][14] = tmp374_; mCompDer[1][15] = (((tmp143_) * (tmp355_) + (tmp131_) * tmp90_ + (tmp377_) * tmp93_) - (tmp145_) * tmp359_ + (tmp146_) * tmp360_ + (tmp143_) * tmp361_ * (tmp85_) + (tmp146_) * tmp362_ + (tmp131_) * tmp363_ * (tmp83_) + (tmp145_) * tmp364_ + (tmp146_) * tmp365_ * (tmp83_) + (tmp145_) * tmp366_) * mLocScNorm; mCompDer[1][16] = (((tmp183_) * (tmp355_) + (tmp171_) * tmp90_ + (tmp380_) * tmp93_) - (tmp185_) * tmp359_ + (tmp186_) * tmp360_ + (tmp183_) * tmp361_ * (tmp85_) + (tmp186_) * tmp362_ + (tmp171_) * tmp363_ * (tmp83_) + (tmp185_) * tmp364_ + (tmp186_) * tmp365_ * (tmp83_) + (tmp185_) * tmp366_) * mLocScNorm; mCompDer[1][17] = (((tmp220_) * (tmp355_) + tmp204_ * tmp90_ + (tmp383_) * tmp93_) - (tmp222_) * tmp359_ + (tmp223_) * tmp360_ + (tmp220_) * tmp361_ * (tmp85_) + (tmp223_) * tmp362_ + tmp204_ * tmp363_ * (tmp83_) + (tmp222_) * tmp364_ + (tmp223_) * tmp365_ * (tmp83_) + (tmp222_) * tmp366_) * mLocScNorm; mCompDer[1][18] = (((tmp236_) * (tmp355_) + (tmp231_) * tmp90_ + (tmp386_) * tmp93_) - (tmp238_) * tmp359_ + (tmp239_) * tmp360_ + (tmp236_) * tmp361_ * (tmp85_) + (tmp239_) * tmp362_ + (tmp231_) * tmp363_ * (tmp83_) + (tmp238_) * tmp364_ + (tmp239_) * tmp365_ * (tmp83_) + (tmp238_) * tmp366_) * mLocScNorm; mCompDer[1][19] = (((tmp252_) * (tmp355_) + (tmp247_) * tmp90_ + (tmp389_) * tmp93_) - (tmp254_) * tmp359_ + (tmp255_) * tmp360_ + (tmp252_) * tmp361_ * (tmp85_) + (tmp255_) * tmp362_ + (tmp247_) * tmp363_ * (tmp83_) + (tmp254_) * tmp364_ + (tmp255_) * tmp365_ * (tmp83_) + (tmp254_) * tmp366_) * mLocScNorm; mCompDer[1][20] = (((tmp267_) * (tmp355_) + (tmp262_) * tmp90_ + (tmp392_) * tmp93_) - (tmp269_) * tmp359_ + (tmp270_) * tmp360_ + (tmp267_) * tmp361_ * (tmp85_) + (tmp270_) * tmp362_ + (tmp262_) * tmp363_ * (tmp83_) + (tmp269_) * tmp364_ + (tmp270_) * tmp365_ * (tmp83_) + (tmp269_) * tmp366_) * mLocScNorm; mCompDer[1][21] = (((tmp295_) * (tmp355_) + (tmp286_) * tmp90_ + (tmp395_) * tmp93_) - (tmp297_) * tmp359_ + (tmp298_) * tmp360_ + (tmp295_) * tmp361_ * (tmp85_) + (tmp298_) * tmp362_ + (tmp286_) * tmp363_ * (tmp83_) + (tmp297_) * tmp364_ + (tmp298_) * tmp365_ * (tmp83_) + (tmp297_) * tmp366_) * mLocScNorm; mCompDer[1][22] = (((tmp323_) * (tmp355_) + (tmp314_) * tmp90_ + (tmp398_) * tmp93_) - (tmp325_) * tmp359_ + (tmp326_) * tmp360_ + (tmp323_) * tmp361_ * (tmp85_) + (tmp326_) * tmp362_ + (tmp314_) * tmp363_ * (tmp83_) + (tmp325_) * tmp364_ + (tmp326_) * tmp365_ * (tmp83_) + (tmp325_) * tmp366_) * mLocScNorm; mCompDer[1][23] = (((tmp351_) * (tmp355_) + (tmp342_) * tmp90_ + (tmp401_) * tmp93_) - (tmp353_) * tmp359_ + (tmp354_) * tmp360_ + (tmp351_) * tmp361_ * (tmp85_) + (tmp354_) * tmp362_ + (tmp342_) * tmp363_ * (tmp83_) + (tmp353_) * tmp364_ + (tmp354_) * tmp365_ * (tmp83_) + (tmp353_) * tmp366_) * mLocScNorm; } void cEqAppui_PProjInc_M2CEbner::ComputeValDerivHessian() { ELISE_ASSERT(false,"Foncteur cEqAppui_PProjInc_M2CEbner Has no Der Sec"); } void cEqAppui_PProjInc_M2CEbner::SetEbner_State_0_0(double aVal){ mLocEbner_State_0_0 = aVal;} void cEqAppui_PProjInc_M2CEbner::SetProjI_x(double aVal){ mLocProjI_x = aVal;} void cEqAppui_PProjInc_M2CEbner::SetProjI_y(double aVal){ mLocProjI_y = aVal;} void cEqAppui_PProjInc_M2CEbner::SetProjI_z(double aVal){ mLocProjI_z = aVal;} void cEqAppui_PProjInc_M2CEbner::SetProjJ_x(double aVal){ mLocProjJ_x = aVal;} void cEqAppui_PProjInc_M2CEbner::SetProjJ_y(double aVal){ mLocProjJ_y = aVal;} void cEqAppui_PProjInc_M2CEbner::SetProjJ_z(double aVal){ mLocProjJ_z = aVal;} void cEqAppui_PProjInc_M2CEbner::SetProjK_x(double aVal){ mLocProjK_x = aVal;} void cEqAppui_PProjInc_M2CEbner::SetProjK_y(double aVal){ mLocProjK_y = aVal;} void cEqAppui_PProjInc_M2CEbner::SetProjK_z(double aVal){ mLocProjK_z = aVal;} void cEqAppui_PProjInc_M2CEbner::SetProjP0_x(double aVal){ mLocProjP0_x = aVal;} void cEqAppui_PProjInc_M2CEbner::SetProjP0_y(double aVal){ mLocProjP0_y = aVal;} void cEqAppui_PProjInc_M2CEbner::SetProjP0_z(double aVal){ mLocProjP0_z = aVal;} void cEqAppui_PProjInc_M2CEbner::SetScNorm(double aVal){ mLocScNorm = aVal;} void cEqAppui_PProjInc_M2CEbner::SetXIm(double aVal){ mLocXIm = aVal;} void cEqAppui_PProjInc_M2CEbner::SetYIm(double aVal){ mLocYIm = aVal;} double * cEqAppui_PProjInc_M2CEbner::AdrVarLocFromString(const std::string & aName) { if (aName == "Ebner_State_0_0") return & mLocEbner_State_0_0; if (aName == "ProjI_x") return & mLocProjI_x; if (aName == "ProjI_y") return & mLocProjI_y; if (aName == "ProjI_z") return & mLocProjI_z; if (aName == "ProjJ_x") return & mLocProjJ_x; if (aName == "ProjJ_y") return & mLocProjJ_y; if (aName == "ProjJ_z") return & mLocProjJ_z; if (aName == "ProjK_x") return & mLocProjK_x; if (aName == "ProjK_y") return & mLocProjK_y; if (aName == "ProjK_z") return & mLocProjK_z; if (aName == "ProjP0_x") return & mLocProjP0_x; if (aName == "ProjP0_y") return & mLocProjP0_y; if (aName == "ProjP0_z") return & mLocProjP0_z; if (aName == "ScNorm") return & mLocScNorm; if (aName == "XIm") return & mLocXIm; if (aName == "YIm") return & mLocYIm; return 0; } cElCompiledFonc::cAutoAddEntry cEqAppui_PProjInc_M2CEbner::mTheAuto("cEqAppui_PProjInc_M2CEbner",cEqAppui_PProjInc_M2CEbner::Alloc); cElCompiledFonc * cEqAppui_PProjInc_M2CEbner::Alloc() { return new cEqAppui_PProjInc_M2CEbner(); }
48.041139
310
0.656775
kikislater
b7ac72637aa6f8b8a7cc7147ea7462a528fffbc1
57
cpp
C++
src/sink.cpp
JacknJo/JacksHome
b1b2d0d7683eb1a8adcfdd02380c6b620e567fe2
[ "MIT" ]
null
null
null
src/sink.cpp
JacknJo/JacksHome
b1b2d0d7683eb1a8adcfdd02380c6b620e567fe2
[ "MIT" ]
null
null
null
src/sink.cpp
JacknJo/JacksHome
b1b2d0d7683eb1a8adcfdd02380c6b620e567fe2
[ "MIT" ]
null
null
null
#include "sink.hpp" namespace jhm { } // namespace jhm.
11.4
20
0.666667
JacknJo
b7ad65a26c97cb14a2497f45b667f3303bafb8fc
10,685
cpp
C++
test/acl_sampler_test.cpp
sherry-yuan/fpga-runtime-for-opencl
df4be1924268cdb7841da2a6b0618b7bb8a47628
[ "BSD-3-Clause" ]
11
2021-11-19T20:52:09.000Z
2022-03-23T10:41:42.000Z
test/acl_sampler_test.cpp
sherry-yuan/fpga-runtime-for-opencl
df4be1924268cdb7841da2a6b0618b7bb8a47628
[ "BSD-3-Clause" ]
49
2021-11-08T18:26:37.000Z
2022-03-31T14:25:29.000Z
test/acl_sampler_test.cpp
sherry-yuan/fpga-runtime-for-opencl
df4be1924268cdb7841da2a6b0618b7bb8a47628
[ "BSD-3-Clause" ]
6
2021-11-02T17:45:37.000Z
2022-02-12T00:47:15.000Z
// Copyright (C) 2010-2021 Intel Corporation // SPDX-License-Identifier: BSD-3-Clause #if ACL_SUPPORT_IMAGES == 1 #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4100) // unreferenced formal parameter #endif #include <CppUTest/TestHarness.h> #ifdef _MSC_VER #pragma warning(pop) #endif #include <CL/opencl.h> #include <acl.h> #include <acl_types.h> #include <acl_util.h> #include "acl_test.h" MT_TEST_GROUP(acl_sampler) { enum { MAX_DEVICES = 100 }; void setup() { if (threadNum() == 0) { acl_test_setup_generic_system(); } syncThreads(); m_callback_count = 0; m_callback_errinfo = 0; this->load(); } void teardown() { syncThreads(); if (threadNum() == 0) { acl_test_teardown_generic_system(); } acl_test_run_standard_teardown_checks(); } void load(void) { CHECK_EQUAL(CL_SUCCESS, clGetPlatformIDs(1, &m_platform, 0)); ACL_LOCKED(CHECK(acl_platform_is_valid(m_platform))); CHECK_EQUAL(CL_SUCCESS, clGetDeviceIDs(m_platform, CL_DEVICE_TYPE_ALL, MAX_DEVICES, &m_device[0], &m_num_devices)); CHECK(m_num_devices >= 3); } protected: cl_platform_id m_platform; cl_device_id m_device[MAX_DEVICES]; cl_uint m_num_devices; public: cl_ulong m_callback_count; const char *m_callback_errinfo; }; static void CL_CALLBACK notify_me(const char *errinfo, const void *private_info, size_t cb, void *user_data) { CppUTestGroupacl_sampler *inst = (CppUTestGroupacl_sampler *)user_data; if (inst) { inst->m_callback_count++; inst->m_callback_errinfo = errinfo; } cb = cb; // avoid warning on windows private_info = private_info; // avoid warning on windows } MT_TEST(acl_sampler, basic) { cl_sampler sampler; cl_int status; cl_sampler_properties sampler_properties[7]; cl_uint ref_count; cl_context test_context; cl_addressing_mode test_addressing_mode; cl_filter_mode test_filter_mode; cl_bool test_normalized_coord; cl_context context = clCreateContext(0, m_num_devices, &m_device[0], notify_me, this, &status); CHECK_EQUAL(CL_SUCCESS, status); // Just grab devices that are present. CHECK(m_device[0]); CHECK(m_device[0]->present); CHECK(m_device[1]); CHECK(m_device[1]->present); CHECK(m_device[2]); CHECK(m_device[2]->present); m_num_devices = 3; // Bad contexts sampler = (cl_sampler)1; status = CL_SUCCESS; sampler = clCreateSampler(0, CL_TRUE, CL_ADDRESS_REPEAT, CL_FILTER_NEAREST, &status); CHECK_EQUAL(0, sampler); CHECK_EQUAL(CL_INVALID_CONTEXT, status); syncThreads(); acl_set_allow_invalid_type<cl_context>(1); syncThreads(); status = CL_SUCCESS; struct _cl_context fake_context = {0}; sampler = clCreateSampler(&fake_context, CL_TRUE, CL_ADDRESS_REPEAT, CL_FILTER_NEAREST, &status); CHECK_EQUAL(0, sampler); CHECK_EQUAL(CL_INVALID_CONTEXT, status); syncThreads(); acl_set_allow_invalid_type<cl_context>(0); syncThreads(); // Invalid value sampler = (cl_sampler)1; status = CL_SUCCESS; sampler = clCreateSampler(context, CL_TRUE, CL_ADDRESS_REPEAT + 6, CL_FILTER_NEAREST, &status); CHECK_EQUAL(0, sampler); CHECK_EQUAL(CL_INVALID_VALUE, status); sampler = (cl_sampler)1; status = CL_SUCCESS; sampler = clCreateSampler(context, CL_TRUE, CL_ADDRESS_REPEAT, CL_FILTER_NEAREST + 2, &status); CHECK_EQUAL(0, sampler); CHECK_EQUAL(CL_INVALID_VALUE, status); sampler = (cl_sampler)1; status = CL_SUCCESS; sampler = clCreateSampler(context, CL_TRUE + 2, CL_ADDRESS_REPEAT, CL_FILTER_NEAREST, &status); CHECK_EQUAL(0, sampler); CHECK_EQUAL(CL_INVALID_VALUE, status); sampler_properties[0] = CL_SAMPLER_NORMALIZED_COORDS + 5; sampler_properties[1] = CL_TRUE; sampler_properties[2] = 0; sampler = (cl_sampler)1; status = CL_SUCCESS; sampler = clCreateSamplerWithProperties(context, sampler_properties, &status); CHECK_EQUAL(0, sampler); CHECK_EQUAL(CL_INVALID_VALUE, status); sampler_properties[0] = CL_SAMPLER_NORMALIZED_COORDS; sampler_properties[1] = CL_TRUE + 3; sampler_properties[2] = 0; sampler = (cl_sampler)1; status = CL_SUCCESS; sampler = clCreateSamplerWithProperties(context, sampler_properties, &status); CHECK_EQUAL(0, sampler); CHECK_EQUAL(CL_INVALID_VALUE, status); sampler_properties[0] = CL_SAMPLER_NORMALIZED_COORDS; sampler_properties[1] = CL_TRUE; sampler_properties[2] = CL_SAMPLER_NORMALIZED_COORDS; sampler_properties[3] = CL_TRUE; sampler_properties[4] = 0; sampler = (cl_sampler)1; status = CL_SUCCESS; sampler = clCreateSamplerWithProperties(context, sampler_properties, &status); CHECK_EQUAL(0, sampler); CHECK_EQUAL(CL_INVALID_VALUE, status); // Invalid sampler CHECK_EQUAL(CL_INVALID_SAMPLER, clReleaseSampler(0)); CHECK_EQUAL(CL_INVALID_SAMPLER, clReleaseSampler((cl_sampler)&status)); CHECK_EQUAL(CL_INVALID_SAMPLER, clGetSamplerInfo(0, CL_SAMPLER_REFERENCE_COUNT, 0, 0, 0)); CHECK_EQUAL(CL_INVALID_SAMPLER, clGetSamplerInfo((cl_sampler)&status, CL_SAMPLER_REFERENCE_COUNT, 0, 0, 0)); // Good sampler sampler = (cl_sampler)1; status = CL_SUCCESS; sampler = clCreateSampler(context, CL_TRUE, CL_ADDRESS_REPEAT, CL_FILTER_NEAREST, &status); CHECK(sampler != 0); CHECK_EQUAL(CL_SUCCESS, status); status = clReleaseSampler(sampler); CHECK_EQUAL(CL_SUCCESS, status); sampler_properties[0] = CL_SAMPLER_NORMALIZED_COORDS; sampler_properties[1] = CL_TRUE; sampler_properties[2] = 0; sampler = (cl_sampler)1; status = CL_SUCCESS; sampler = clCreateSamplerWithProperties(context, sampler_properties, &status); CHECK(sampler != 0); CHECK_EQUAL(CL_SUCCESS, status); status = clReleaseSampler(sampler); CHECK_EQUAL(CL_SUCCESS, status); sampler_properties[0] = CL_SAMPLER_NORMALIZED_COORDS; sampler_properties[1] = CL_FALSE; sampler_properties[2] = CL_SAMPLER_ADDRESSING_MODE; sampler_properties[3] = CL_ADDRESS_REPEAT; sampler_properties[4] = CL_SAMPLER_FILTER_MODE; sampler_properties[5] = CL_FILTER_LINEAR; sampler_properties[6] = 0; sampler = (cl_sampler)1; status = CL_SUCCESS; sampler = clCreateSamplerWithProperties(context, sampler_properties, &status); CHECK(sampler != 0); CHECK_EQUAL(CL_SUCCESS, status); status = clReleaseSampler(sampler); CHECK_EQUAL(CL_SUCCESS, status); CHECK_EQUAL(6, this->m_callback_count); sampler = clCreateSamplerWithProperties(context, sampler_properties, &status); CHECK_EQUAL(CL_SUCCESS, status); // let all threads get different samplers before continuing syncThreads(); CHECK_EQUAL(CL_INVALID_SAMPLER, clRetainSampler(0)); CHECK_EQUAL(CL_INVALID_SAMPLER, clRetainSampler((cl_sampler)&status)); CHECK_EQUAL(CL_SUCCESS, clRetainSampler(sampler)); CHECK_EQUAL(CL_SUCCESS, clGetSamplerInfo(sampler, CL_SAMPLER_REFERENCE_COUNT, sizeof(cl_uint), &ref_count, NULL)); CHECK_EQUAL(2, ref_count); CHECK_EQUAL(CL_SUCCESS, clRetainSampler(sampler)); CHECK_EQUAL(CL_SUCCESS, clGetSamplerInfo(sampler, CL_SAMPLER_REFERENCE_COUNT, sizeof(cl_uint), &ref_count, NULL)); CHECK_EQUAL(3, ref_count); CHECK_EQUAL(CL_SUCCESS, clGetSamplerInfo(sampler, CL_SAMPLER_CONTEXT, sizeof(cl_context), &test_context, NULL)); CHECK_EQUAL(context, test_context); CHECK_EQUAL(CL_SUCCESS, clGetSamplerInfo(sampler, CL_SAMPLER_ADDRESSING_MODE, sizeof(cl_addressing_mode), &test_addressing_mode, NULL)); CHECK_EQUAL(CL_ADDRESS_REPEAT, test_addressing_mode); CHECK_EQUAL(CL_SUCCESS, clGetSamplerInfo(sampler, CL_SAMPLER_FILTER_MODE, sizeof(cl_filter_mode), &test_filter_mode, NULL)); CHECK_EQUAL(CL_FILTER_LINEAR, test_filter_mode); CHECK_EQUAL(CL_SUCCESS, clGetSamplerInfo(sampler, CL_SAMPLER_NORMALIZED_COORDS, sizeof(cl_bool), &test_normalized_coord, NULL)); CHECK_EQUAL(CL_FALSE, test_normalized_coord); CHECK_EQUAL(CL_SUCCESS, clReleaseSampler(sampler)); CHECK_EQUAL(CL_SUCCESS, clGetSamplerInfo(sampler, CL_SAMPLER_REFERENCE_COUNT, sizeof(cl_uint), &ref_count, NULL)); CHECK_EQUAL(2, ref_count); CHECK_EQUAL(CL_SUCCESS, clReleaseSampler(sampler)); CHECK_EQUAL(CL_SUCCESS, clGetSamplerInfo(sampler, CL_SAMPLER_REFERENCE_COUNT, sizeof(cl_uint), &ref_count, NULL)); CHECK_EQUAL(1, ref_count); CHECK_EQUAL(CL_SUCCESS, clReleaseSampler(sampler)); CHECK_EQUAL(CL_INVALID_SAMPLER, clGetSamplerInfo(sampler, CL_SAMPLER_REFERENCE_COUNT, sizeof(cl_uint), &ref_count, NULL)); // don't let any thread create a new sampler before we check // CL_INVALID_SAMPLER above using the old sampler pointer syncThreads(); // Check that default values are used when nothing is provided sampler_properties[0] = 0; sampler = (cl_sampler)1; status = CL_SUCCESS; sampler = clCreateSamplerWithProperties(context, sampler_properties, &status); CHECK_EQUAL(CL_SUCCESS, status); // let all threads get different samplers before continuing syncThreads(); CHECK_EQUAL(CL_SUCCESS, clGetSamplerInfo(sampler, CL_SAMPLER_ADDRESSING_MODE, sizeof(cl_addressing_mode), &test_addressing_mode, NULL)); CHECK_EQUAL(CL_ADDRESS_CLAMP, test_addressing_mode); CHECK_EQUAL(CL_SUCCESS, clGetSamplerInfo(sampler, CL_SAMPLER_FILTER_MODE, sizeof(cl_filter_mode), &test_filter_mode, NULL)); CHECK_EQUAL(CL_FILTER_NEAREST, test_filter_mode); CHECK_EQUAL(CL_SUCCESS, clGetSamplerInfo(sampler, CL_SAMPLER_NORMALIZED_COORDS, sizeof(cl_bool), &test_normalized_coord, NULL)); CHECK_EQUAL(CL_TRUE, test_normalized_coord); CHECK_EQUAL(CL_SUCCESS, clReleaseSampler(sampler)); CHECK_EQUAL(CL_INVALID_SAMPLER, clGetSamplerInfo(sampler, CL_SAMPLER_REFERENCE_COUNT, sizeof(cl_uint), &ref_count, NULL)); CHECK_EQUAL(CL_SUCCESS, clReleaseContext(context)); } #endif
34.691558
80
0.69153
sherry-yuan
b7b0d41ce7c0d9e3f31ebf247c1b6a5a57f9b276
6,982
cpp
C++
source/engine/adl_editor/adlSpawn_editor.cpp
AtakanFire/adlGame
d617988b166c1cdd50dd7acb26507231a502a537
[ "MIT" ]
6
2018-08-28T19:52:03.000Z
2020-12-02T13:59:00.000Z
source/engine/adl_editor/adlSpawn_editor.cpp
AtakanFire/adlGame
d617988b166c1cdd50dd7acb26507231a502a537
[ "MIT" ]
16
2019-03-01T09:37:33.000Z
2019-05-13T13:10:54.000Z
source/engine/adl_editor/adlSpawn_editor.cpp
AtakanFire/adlGame
d617988b166c1cdd50dd7acb26507231a502a537
[ "MIT" ]
4
2018-10-29T18:04:18.000Z
2021-02-05T13:13:00.000Z
#include "adlSpawn_editor.h" #include "engine/adl_debug/imgui/imgui.h" #include "engine/adl_entities/adlEntity_factory.h" #include "engine/adl_resource/adlResource_manager.h" adlSpawn_editor::adlSpawn_editor() { } adlSpawn_editor::~adlSpawn_editor() { } void adlSpawn_editor::init() { spawn_transform_.scale = adlVec3(1.0f); } void adlSpawn_editor::update(adlScene_manager* scene_manager) { is_visible_ = true; adlEntity_factory* factory = &adlEntity_factory::get(); adlResource_manager* adl_rm = &adlResource_manager::get(); const std::vector<std::string>& entities = adl_rm->get_all_entity_names(); ImGui::Begin("Spawn Editor"); for (unsigned int i = 0; i < entities.size(); i++) { ImGui::Indent(); if (ImGui::Button(entities[i].c_str())) { scene_manager->add_entity_to_scene(entities[i].c_str()); //factory->construct_entity(entities[i]); } ImGui::Unindent(); } ImGui::End(); //ImGui::Begin("Spawn Editor"); //if (ImGui::CollapsingHeader("Entities")) //{ // ImGui::Indent(); // for (size_t i = 0; i < actors.size(); i++) // { // if (ImGui::CollapsingHeader(actors[i].data())) // { // ImGui::Indent(); // adlVec3 actor_position = spawn_transform_.o; // adlVec3 actor_rotation = spawn_transform_.rot; // adlVec3 actor_scale = spawn_transform_.scale; // if (ImGui::CollapsingHeader("Transform")) // { // ImGui::Indent(); // if (ImGui::CollapsingHeader("Position")) // { // ImGui::Text("Position(x,y,z)"); // std::string label = actors[i] + " Pos"; // float actorPos[3] = { actor_position.x, actor_position.y, actor_position.z }; // ImGui::InputFloat3(label.data(), &actorPos[0], 2); // actor_position = adlVec3(actorPos[0], actorPos[1], actorPos[2]); // } // if (ImGui::CollapsingHeader("Rotation")) // { // ImGui::Text("Rotation(x,y,z)"); // std::string label = actors[i] + " Rot"; // float actorRot[3] = { adlMath::rad_to_deg(actor_rotation.x), adlMath::rad_to_deg(actor_rotation.y), adlMath::rad_to_deg(actor_rotation.z) }; // ImGui::InputFloat3(label.data(), &actorRot[0], 2); // actor_rotation = adlVec3(adlMath::deg_to_rad(actorRot[0]), adlMath::deg_to_rad(actorRot[1]), adlMath::deg_to_rad(actorRot[2])); // } // if (ImGui::CollapsingHeader("Scale")) // { // ImGui::Text("Scale(x,y,z)"); // std::string label = actors[i] + " Scale"; // float actorScale[3] = { actor_scale.x, actor_scale.y, actor_scale.z }; // ImGui::InputFloat3(label.data(), &actorScale[0], 2); // actor_scale = adlVec3(actorScale[0], actorScale[1], actorScale[2]); // } // spawn_transform_.o = actor_position; // spawn_transform_.rot = actor_rotation; // spawn_transform_.scale = actor_scale; // ImGui::Unindent(); // } // if (ImGui::CollapsingHeader("Actor Properties")) // { // ImGui::Indent(); // if (ImGui::CollapsingHeader("Model")) // { // ImGui::Indent(); // if (ImGui::CollapsingHeader("Mesh")) // { // ImGui::Indent(); // static char model_name[20] = {}; // ImGui::Text("Mesh(Name)"); // ImGui::InputText("(max 20 char)", model_name, sizeof(model_name)); // if (ImGui::Button("Refresh Mesh")) // { // spawn_model_ = adl_rm->get_model(model_name); // } // ImGui::Unindent(); // } // if (ImGui::CollapsingHeader("Material")) // { // ImGui::Indent(); // static char material_name[20] = {}; // ImGui::Text("Material(Name)"); // ImGui::InputText("(max 20 char)", material_name, sizeof(material_name)); // if (ImGui::Button("Refresh Material")) // { // spawn_material_ = adl_rm->get_material(material_name); // } // ImGui::Unindent(); // } // ImGui::Unindent(); // } // ImGui::Unindent(); // } // std::string button_label = "Spawn " + actors[i] + " actor"; // if (ImGui::Button(button_label.data())) // { // ImGui::Indent(); // //adlActor_shared_ptr spawned_actor = scene_manager->spawn_actor(actors[i].data(), spawn_transform_.o, spawn_transform_.rot, spawn_transform_.scale); // if (spawn_model_ != nullptr) // { // //spawned_actor->set_model(spawn_model_); // spawn_model_ = adl_rm->get_model(""); // } // if (spawn_material_ != nullptr) // { // //spawned_actor->set_material(spawn_material_); // spawn_material_ = adl_rm->get_material(""); // } // //is_visible_ = false; // ImGui::Unindent(); // } // ImGui::Unindent(); // } // } // ImGui::Unindent(); //} //if (ImGui::CollapsingHeader("Lights")) //{ // ImGui::Indent(); // for (size_t i = 0; i < lights.size(); i++) // { // if (ImGui::CollapsingHeader(lights[i].data())) // { // ImGui::Indent(); // adlVec3 light_position = spawn_transform_.o; // adlVec3 light_rotation = spawn_transform_.rot; // adlVec3 light_scale = spawn_transform_.scale; // if (ImGui::CollapsingHeader("Transform")) // { // ImGui::Indent(); // if (ImGui::CollapsingHeader("Position")) // { // ImGui::Text("Position(x,y,z)"); // std::string label = lights[i] + " Pos"; // float lightPos[3] = { light_position.x, light_position.y, light_position.z }; // ImGui::InputFloat3(label.data(), &lightPos[0], 2); // light_position = adlVec3(lightPos[0], lightPos[1], lightPos[2]); // } // if (ImGui::CollapsingHeader("Rotation")) // { // ImGui::Text("Rotation(x,y,z)"); // std::string label = lights[i] + " Rot"; // float lightRot[3] = { adlMath::rad_to_deg(light_rotation.x), adlMath::rad_to_deg(light_rotation.y), adlMath::rad_to_deg(light_rotation.z) }; // ImGui::InputFloat3(label.data(), &lightRot[0], 2); // light_rotation = adlVec3(adlMath::deg_to_rad(lightRot[0]), adlMath::deg_to_rad(lightRot[1]), adlMath::deg_to_rad(lightRot[2])); // } // if (ImGui::CollapsingHeader("Scale")) // { // ImGui::Text("Scale(x,y,z)"); // std::string label = lights[i] + " Scale"; // float lightScale[3] = { light_scale.x, light_scale.y, light_scale.z }; // ImGui::InputFloat3(label.data(), &lightScale[0], 2); // light_scale = adlVec3(lightScale[0], lightScale[1], lightScale[2]); // } // spawn_transform_.o = light_position; // spawn_transform_.rot = light_rotation; // spawn_transform_.scale = light_scale; // ImGui::Unindent(); // } // std::string button_label = "Spawn " + lights[i] + " light"; // if (ImGui::Button(button_label.data())) // { // ImGui::Indent(); // //scene_manager->spawn_light(lights[i].data(), spawn_transform_.o, spawn_transform_.rot, spawn_transform_.scale); // is_visible_ = false; // ImGui::Unindent(); // } // ImGui::Unindent(); // } // } // ImGui::Unindent(); //} //ImGui::End(); } bool adlSpawn_editor::get_visible() { return is_visible_; }
26.24812
156
0.600687
AtakanFire
b7b1421c6992b2f7df2f48a563a55201391df9a3
2,330
hpp
C++
test/TestApp/Source/MaidChanGame.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
test/TestApp/Source/MaidChanGame.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
test/TestApp/Source/MaidChanGame.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
// Copyright (c) 2013-2015 mogemimi. // Distributed under the MIT license. See LICENSE.md file for details. #ifndef POMDOG_MAIDCHANGAME_FB2D5E96_HPP #define POMDOG_MAIDCHANGAME_FB2D5E96_HPP #include <Pomdog.Experimental/InGameEditor/detail/EditorBackground.hpp> #include <Pomdog.Experimental/Skeletal2D/detail/AnimationTimer.hpp> #include <Pomdog.Experimental/Experimental.hpp> #include <Pomdog/Pomdog.hpp> namespace Pomdog { class SpriteBatch; class SpriteRenderer; }// namespace Pomdog namespace TestApp { using namespace Pomdog; class MaidChanGame: public Game { public: explicit MaidChanGame(std::shared_ptr<GameHost> const& gameHost); ~MaidChanGame(); void Initialize(); void Update(); void Draw(); private: void DrawSprites(); private: std::shared_ptr<GameHost> gameHost; std::shared_ptr<GameWindow> window; std::shared_ptr<GraphicsDevice> graphicsDevice; std::shared_ptr<GraphicsContext> graphicsContext; std::shared_ptr<Texture2D> texture; std::unique_ptr<SpriteRenderer> spriteRenderer; std::shared_ptr<SamplerState> samplerPoint; std::shared_ptr<RenderTarget2D> renderTarget; std::unique_ptr<FXAA> fxaa; std::unique_ptr<ScreenQuad> screenQuad; std::unique_ptr<SceneEditor::InGameEditor> gameEditor; std::unique_ptr<SceneEditor::EditorBackground> editorBackground; std::shared_ptr<UI::ScenePanel> scenePanel; std::shared_ptr<UI::Slider> slider1; std::shared_ptr<UI::Slider> slider2; std::shared_ptr<UI::ToggleSwitch> toggleSwitch1; std::shared_ptr<UI::ToggleSwitch> toggleSwitch2; std::shared_ptr<UI::ToggleSwitch> toggleSwitch3; std::shared_ptr<UI::ToggleSwitch> toggleSwitch4; GameWorld gameWorld; GameObject mainCamera; AnimationSystem animationSystem; std::shared_ptr<Skeleton> maidSkeleton; std::shared_ptr<SkeletonPose> maidSkeletonPose; std::shared_ptr<AnimationState> maidAnimationState; std::shared_ptr<Texture2D> maidTexture; std::vector<Matrix3x2> maidGlobalPose; Detail::Skeletal2D::AnimationTimer maidAnimationTimer; Skin maidSkin; std::vector<Detail::Skeletal2D::SpriteAnimationTrack> maidSpriteAnimationTracks; ConnectionList connections; Viewport clientViewport; }; }// namespace TestApp #endif // POMDOG_MAIDCHANGAME_FB2D5E96_HPP
28.414634
84
0.762661
bis83
5d9984e04d15961ed5b67450a951d2c7c1cf4a75
3,761
hpp
C++
external/cfmesh/meshLibrary/utilities/decomposeCells/decomposeCells.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
external/cfmesh/meshLibrary/utilities/decomposeCells/decomposeCells.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
external/cfmesh/meshLibrary/utilities/decomposeCells/decomposeCells.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) Creative Fields, Ltd. ------------------------------------------------------------------------------- License This file is part of cfMesh. cfMesh is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. cfMesh is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cfMesh. If not, see <http://www.gnu.org/licenses/>. Class decomposeCells Description Decomposes selected cells into pyramids Author: Franjo Juretic (franjo.juretic@c-fields.com) SourceFiles \*---------------------------------------------------------------------------*/ #ifndef decomposeCells_HPP #define decomposeCells_HPP #include "polyMeshGenModifier.hpp" #include "VRWGraphList.hpp" #include "DynList.hpp" namespace CML { /*---------------------------------------------------------------------------*\ Class decomposeCells Declaration \*---------------------------------------------------------------------------*/ class decomposeCells { // private data //- reference to the mesh polyMeshGen& mesh_; //- new boundary faces wordList patchNames_; wordList patchTypes_; VRWGraph newBoundaryFaces_; labelLongList newBoundaryPatches_; VRWGraphList facesOfNewCells_; // Private member functions //- check if the valid pyramids are generated from the split cells //- this check splits faces which could //- result in multiple inbetween faces void checkFaceConnections(const boolList& decomposeCell); //- create addressing needed to decompose the cell void findAddressingForCell ( const label cellI, DynList<label, 32>& vrt, DynList<edge, 64>& edges, DynList<DynList<label, 8> >& faceEdges, DynList<DynList<label, 2>, 64>& edgeFaces ) const; //- find the apex of the pyramids label findTopVertex ( const label cellI, const DynList<label, 32>& vrt, const DynList<edge, 64>& edges, const DynList<DynList<label, 2>, 64>& edgeFaces ); void decomposeCellIntoPyramids(const label cellI); void createPointsAndCellFaces(const boolList& decomposeCell); void storeBoundaryFaces(const boolList& decomposeCell); void removeDecomposedCells(const boolList& decomposeCell); void addNewCells(); //- disallows bitwise construct void operator=(const decomposeCells&); //- copy constructor decomposeCells(const decomposeCells&); public: // Constructors //- construct from polyMeshGen and a list containing patches //- for each point decomposeCells(polyMeshGen& mesh); //- Destructor ~decomposeCells(); // Member functions //- perform decomposition of selected cell into pyramids void decomposeMesh(const boolList&); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace CML // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
29.155039
79
0.549588
MrAwesomeRocks
5d99aaf3f20c3de5cc7027e6501eefb0a1d2925b
5,716
cpp
C++
TAO/orbsvcs/orbsvcs/Naming/FaultTolerant/FT_PG_Object_Group_Storable.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/orbsvcs/orbsvcs/Naming/FaultTolerant/FT_PG_Object_Group_Storable.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/orbsvcs/orbsvcs/Naming/FaultTolerant/FT_PG_Object_Group_Storable.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// $Id: FT_PG_Object_Group_Storable.cpp 97014 2013-04-12 22:47:02Z mitza $ #include "orbsvcs/Log_Macros.h" #include "orbsvcs/Naming/FaultTolerant/FT_PG_Object_Group_Storable.h" #include "orbsvcs/PortableGroup/PG_Object_Group_Storable.h" #include "orbsvcs/Naming/FaultTolerant/FT_Naming_Replication_Manager.h" #include "tao/Stub.h" TAO_BEGIN_VERSIONED_NAMESPACE_DECL TAO::FT_PG_Object_Group_Storable::FT_PG_Object_Group_Storable ( CORBA::ORB_ptr orb, PortableGroup::FactoryRegistry_ptr factory_registry, TAO::PG_Object_Group_Manipulator & manipulator, CORBA::Object_ptr empty_group, const PortableGroup::TagGroupTaggedComponent & tagged_component, const char * type_id, const PortableGroup::Criteria & the_criteria, const TAO::PG_Property_Set_var & type_properties, TAO::Storable_Factory & storable_factory) : PG_Object_Group_Storable(orb, factory_registry, manipulator, empty_group, tagged_component, type_id, the_criteria, type_properties, storable_factory) , stale_ (false) , file_created_ (false) { } TAO::FT_PG_Object_Group_Storable::FT_PG_Object_Group_Storable ( PortableGroup::ObjectGroupId group_id, CORBA::ORB_ptr orb, PortableGroup::FactoryRegistry_ptr factory_registry, TAO::PG_Object_Group_Manipulator & manipulator, TAO::Storable_Factory & storable_factory) : PG_Object_Group_Storable(group_id, orb, factory_registry, manipulator, storable_factory) , stale_ (false) , file_created_ (true) { } TAO::FT_PG_Object_Group_Storable::~FT_PG_Object_Group_Storable (void) { } void TAO::FT_PG_Object_Group_Storable::stale (bool is_stale) { this->stale_ = is_stale; } bool TAO::FT_PG_Object_Group_Storable::stale () { return this->stale_; } int TAO::FT_PG_Object_Group_Storable::propagate_update_notification (FT_Naming::ChangeType change_type) { // Notify the peer of the changed context FT_Naming::ReplicationManager_var peer = TAO_FT_Naming_Replication_Manager::peer_replica (); if (CORBA::is_nil (peer.in ())) { // Replication is not supported without a peer replica. return 1; } FT_Naming::ObjectGroupUpdate object_group_info; object_group_info.id = PG_Object_Group::get_object_group_id (); object_group_info.change_type = change_type; try { // Notify the naming_manager of the updated context if (TAO_debug_level > 3) { ORBSVCS_DEBUG ((LM_DEBUG, ACE_TEXT ("TAO (%P|%t) - propagate_update_notification ") ACE_TEXT ("Notifying peer that object group with ID %lld ") ACE_TEXT ("has been updated\n"), object_group_info.id )); } peer->notify_updated_object_group (object_group_info); } catch (CORBA::Exception& ex) { if (TAO_debug_level > 3) ex._tao_print_exception ( ACE_TEXT ("Unable to communicate with peer.\n")); return -1; } return 0; } void TAO::FT_PG_Object_Group_Storable::state_written (void) { FT_Naming::ChangeType change_type; if (!this->file_created_) { change_type = FT_Naming::NEW; this->file_created_ = true; } else if (this->destroyed_) change_type = FT_Naming::DELETED; else change_type = FT_Naming::UPDATED; // If peer is available notify that state has changed. // Otherwise, rely on file time stamps exclusively // for update notification. this->propagate_update_notification (change_type); this->write_occurred_ = false; } bool TAO::FT_PG_Object_Group_Storable::is_obsolete (time_t stored_time) { ACE_UNUSED_ARG (stored_time); return (!this->loaded_from_stream_) || this->stale_; } PortableGroup::ObjectGroup_ptr TAO::FT_PG_Object_Group_Storable::add_member_to_iogr (CORBA::Object_ptr member) { // If this is the first member added to the group and it's type_id does // not match the member, then the object group should assume the same // type id as the first member. We will need to replace the object // reference with an empty reference of the specified type id. if (CORBA::is_nil (member)) {// A null object reference is not an acceptable member of the group. ORBSVCS_ERROR ((LM_ERROR, ACE_TEXT ("(%P|%t) ERROR: Unable to add null member ") ACE_TEXT ("to object group with id: %s\n"), this->tagged_component_.object_group_id)); return CORBA::Object::_nil (); } const char* member_type_id = member->_stubobj ()->type_id.in (); if ((this->members_.current_size () == 0) && (ACE_OS::strcmp (this->type_id_, member_type_id) != 0) ) { try { this->type_id_ = member_type_id; this->reference_ = manipulator_.create_object_group_using_id ( this->type_id_, this->tagged_component_.group_domain_id, this->tagged_component_.object_group_id); } catch (const CORBA::Exception&) { ORBSVCS_ERROR ((LM_ERROR, ACE_TEXT ("(%P|%t) ERROR: Unable to add member ") ACE_TEXT ("to object group with id: %s for object ") ACE_TEXT ("of type: %s\n"), this->tagged_component_.object_group_id, member_type_id)); return CORBA::Object::_nil (); } } return PG_Object_Group::add_member_to_iogr (member); } TAO_END_VERSIONED_NAMESPACE_DECL
31.065217
79
0.654129
cflowe
5d9a97058e433a3b6d127826efd220407aac5e5a
694
cpp
C++
Array/Kadane's Algorithm/05. PrintLongestEvenOddSubarray.cpp
sohamnandi77/Cpp-Data-Structures-And-Algorithm
f29a14760964103a5b58cfff925cd8f7ed5aa6c1
[ "MIT" ]
2
2021-05-21T17:10:02.000Z
2021-05-29T05:13:06.000Z
Array/Kadane's Algorithm/05. PrintLongestEvenOddSubarray.cpp
sohamnandi77/Cpp-Data-Structures-And-Algorithm
f29a14760964103a5b58cfff925cd8f7ed5aa6c1
[ "MIT" ]
null
null
null
Array/Kadane's Algorithm/05. PrintLongestEvenOddSubarray.cpp
sohamnandi77/Cpp-Data-Structures-And-Algorithm
f29a14760964103a5b58cfff925cd8f7ed5aa6c1
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; void printLongestEvenOddOP(int arr[], int n) { int res = 1, curr = 1, endIndex = 0; for (int i = 1; i < n; i++) { if ((arr[i] % 2 == 0 && arr[i - 1] % 2 != 0) || (arr[i] % 2 != 0 && arr[i - 1] % 2 == 0)) { curr++; if (res < curr) { res = curr; endIndex = i; } } else curr = 1; } int startIndex = endIndex - res + 1; for (int i = startIndex; i <= endIndex; i++) cout << arr[i] << " "; } int main() { int arr[] = {5, 10, 20, 6, 3, 8}, n = 6; printLongestEvenOddOP(arr, n); return 0; }
21.6875
97
0.403458
sohamnandi77
5d9c42384fa7a6528beb8ffb7c9d16dfa8a4cc67
3,429
cpp
C++
Source/TitaniumKit/src/Contacts/Group.cpp
garymathews/titanium_mobile_windows
ff2a02d096984c6cad08f498e1227adf496f84df
[ "Apache-2.0" ]
20
2015-04-02T06:55:30.000Z
2022-03-29T04:27:30.000Z
Source/TitaniumKit/src/Contacts/Group.cpp
garymathews/titanium_mobile_windows
ff2a02d096984c6cad08f498e1227adf496f84df
[ "Apache-2.0" ]
692
2015-04-01T21:05:49.000Z
2020-03-10T10:11:57.000Z
Source/TitaniumKit/src/Contacts/Group.cpp
garymathews/titanium_mobile_windows
ff2a02d096984c6cad08f498e1227adf496f84df
[ "Apache-2.0" ]
22
2015-04-01T20:57:51.000Z
2022-01-18T17:33:15.000Z
/** * TitaniumKit Titanium.Contacts.Group * * Copyright (c) 2015-2016 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License. * Please see the LICENSE included with this distribution for details. */ #include "Titanium/Contacts/Group.hpp" #include "Titanium/Contacts/Person.hpp" #include "Titanium/detail/TiImpl.hpp" namespace Titanium { namespace Contacts { Group::Group(const JSContext& js_context, const std::vector<JSValue>& arguments) TITANIUM_NOEXCEPT : Module(js_context, "Ti.Contacts.Group") { } TITANIUM_PROPERTY_READ(Group, std::string, identifier) TITANIUM_PROPERTY_READWRITE(Group, std::string, name) TITANIUM_PROPERTY_READWRITE(Group, uint32_t, recordId) void Group::add(const std::shared_ptr<Person>& person) TITANIUM_NOEXCEPT { TITANIUM_LOG_WARN("Group::add: Unimplemented"); } std::vector<std::shared_ptr<Person>> Group::members() TITANIUM_NOEXCEPT { TITANIUM_LOG_WARN("Group::members: Unimplemented"); return std::vector<std::shared_ptr<Person>>(); } void Group::remove(const std::shared_ptr<Person>& person) TITANIUM_NOEXCEPT { TITANIUM_LOG_WARN("Group::remove: Unimplemented"); } std::vector<std::shared_ptr<Person>> Group::sortedMembers(const SORT& sortBy) TITANIUM_NOEXCEPT { TITANIUM_LOG_WARN("Group::sortedMembers: Unimplemented"); return std::vector<std::shared_ptr<Person>>(); } void Group::JSExportInitialize() { JSExport<Group>::SetClassVersion(1); JSExport<Group>::SetParent(JSExport<Module>::Class()); TITANIUM_ADD_PROPERTY_READONLY(Group, identifier); TITANIUM_ADD_PROPERTY(Group, name); TITANIUM_ADD_PROPERTY(Group, recordId); TITANIUM_ADD_FUNCTION(Group, add); TITANIUM_ADD_FUNCTION(Group, members); TITANIUM_ADD_FUNCTION(Group, remove); TITANIUM_ADD_FUNCTION(Group, sortedMembers); TITANIUM_ADD_FUNCTION(Group, getName); TITANIUM_ADD_FUNCTION(Group, setName); TITANIUM_ADD_FUNCTION(Group, getRecordId); TITANIUM_ADD_FUNCTION(Group, setRecordId); } TITANIUM_PROPERTY_GETTER_STRING(Group, identifier); TITANIUM_PROPERTY_GETTER_STRING(Group, name); TITANIUM_PROPERTY_SETTER_STRING(Group, name); TITANIUM_PROPERTY_GETTER_UINT(Group, recordId); TITANIUM_PROPERTY_SETTER_UINT(Group, recordId); TITANIUM_FUNCTION(Group, add) { ENSURE_OBJECT_AT_INDEX(person, 0); add(person.GetPrivate<Person>()); return get_context().CreateUndefined(); } TITANIUM_FUNCTION(Group, members) { std::vector<JSValue> values; for (auto value : members()) { values.push_back(value->get_object()); } return get_context().CreateArray(values); } TITANIUM_FUNCTION(Group, remove) { ENSURE_OBJECT_AT_INDEX(person, 0); remove(person.GetPrivate<Person>()); return get_context().CreateUndefined(); } TITANIUM_FUNCTION(Group, sortedMembers) { ENSURE_ENUM_AT_INDEX(sortBy, 0, SORT); std::vector<JSValue> values; for (auto value : sortedMembers(sortBy)) { values.push_back(value->get_object()); } return get_context().CreateArray(values); } TITANIUM_FUNCTION_AS_GETTER(Group, getIdentifier, identifier) TITANIUM_FUNCTION_AS_GETTER(Group, getName, name) TITANIUM_FUNCTION_AS_SETTER(Group, setName, name) TITANIUM_FUNCTION_AS_GETTER(Group, getRecordId, recordId) TITANIUM_FUNCTION_AS_SETTER(Group, setRecordId, recordId) } // namespace Contacts } // namespace Titanium
29.059322
100
0.748906
garymathews
5d9e739a24a0eb6d1220b884088075ffee052893
420
cpp
C++
Cpp_Workspace/C++ Primer Plus/Chapter04/Chapter4_3.instr1.cpp
agent1894/Quant-Practice-Workspace
f102e136389e2247bbbfb36ef78c16807a0ba7d2
[ "MIT" ]
1
2021-03-17T01:25:05.000Z
2021-03-17T01:25:05.000Z
Cpp_Workspace/C++ Primer Plus/Chapter04/Chapter4_3.instr1.cpp
agent1894/Quant-Practice-Workspace
f102e136389e2247bbbfb36ef78c16807a0ba7d2
[ "MIT" ]
null
null
null
Cpp_Workspace/C++ Primer Plus/Chapter04/Chapter4_3.instr1.cpp
agent1894/Quant-Practice-Workspace
f102e136389e2247bbbfb36ef78c16807a0ba7d2
[ "MIT" ]
2
2020-06-29T15:31:10.000Z
2021-03-24T14:20:15.000Z
// instr1.cpp -- reading more than one string #include <iostream> int main() { using namespace std; const int ARSIZE = 20; char name[ARSIZE]; char dessert[ARSIZE]; cout << "Enter your name:" << endl; cin >> name; cout << "Enter your favourite dessert:" << endl; cin >> dessert; cout << "I have some delicious " << dessert; cout << " for you, " << name << endl; return 0; }
21
52
0.580952
agent1894
5d9f259a634a78e419e3dcb757da5854cc0ec8d8
97,198
hpp
C++
include/vole/internal/generated/methods.hpp
synesissoftware/VOLE
19811c5f1697d898f1fd2bd3506feb272ff2dd66
[ "BSD-2-Clause" ]
1
2019-01-01T14:46:33.000Z
2019-01-01T14:46:33.000Z
include/vole/internal/generated/methods.hpp
synesissoftware/VOLE
19811c5f1697d898f1fd2bd3506feb272ff2dd66
[ "BSD-2-Clause" ]
null
null
null
include/vole/internal/generated/methods.hpp
synesissoftware/VOLE
19811c5f1697d898f1fd2bd3506feb272ff2dd66
[ "BSD-2-Clause" ]
null
null
null
/* ///////////////////////////////////////////////////////////////////////// * File: vole/internal/generated/methods.hpp * * Generated: 2nd August 2012 * * Status: This file is auto-generated: DO NOT EDIT!!!!!!!!!!! * * Copyright: The copyright restrictions of the VOLE library, enumerated * in the header file <vole/util/common.hpp>, apply to this file * * ////////////////////////////////////////////////////////////////////// */ #ifndef VOLE_INCL_VOLE_HPP_OBJECT # error This file is included by vole/server.hpp, and cannot be include directly #endif /* !VOLE_INCL_VOLE_HPP_OBJECT */ // 0 params template <typename R> R invoke_method(LPCOLESTR methodName) { typedef com_return_traits<R> return_traits_t; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); object_helper_type_::internal_invoke_method(*this, &result, methodName, NULL, 0); return return_traits_t::convert(result, m_coercionLevel); } template <typename R> R invoke_method(of_type<R>, LPCOLESTR methodName) { typedef com_return_traits<R> return_traits_t; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); object_helper_type_::internal_invoke_method(*this, &result, methodName, NULL, 0); return return_traits_t::convert(result, m_coercionLevel); } // 1 param template <typename R, typename T0> R invoke_method(LPCOLESTR methodName, T0 const &a0) { typedef com_return_traits<R> return_traits_t; varx_type var0(a0); VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); object_helper_type_::internal_invoke_method(*this, &result, methodName, &var0, 1); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0) { typedef com_return_traits<R> return_traits_t; varx_type var0(a0); VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); object_helper_type_::internal_invoke_method(*this, &result, methodName, &var0, 1); return return_traits_t::convert(result, m_coercionLevel); } // 2 params template <typename R, typename T0, typename T1> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[2]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[1]); varx_type(a1).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[2]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[1]); varx_type(a1).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 3 params template <typename R, typename T0, typename T1, typename T2> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[3]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[2]); varx_type(a1).swap(vars[1]); varx_type(a2).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[3]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[2]); varx_type(a1).swap(vars[1]); varx_type(a2).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 4 params template <typename R, typename T0, typename T1, typename T2, typename T3> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[4]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[3]); varx_type(a1).swap(vars[2]); varx_type(a2).swap(vars[1]); varx_type(a3).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[4]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[3]); varx_type(a1).swap(vars[2]); varx_type(a2).swap(vars[1]); varx_type(a3).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 5 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[5]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[4]); varx_type(a1).swap(vars[3]); varx_type(a2).swap(vars[2]); varx_type(a3).swap(vars[1]); varx_type(a4).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[5]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[4]); varx_type(a1).swap(vars[3]); varx_type(a2).swap(vars[2]); varx_type(a3).swap(vars[1]); varx_type(a4).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 6 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[6]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[5]); varx_type(a1).swap(vars[4]); varx_type(a2).swap(vars[3]); varx_type(a3).swap(vars[2]); varx_type(a4).swap(vars[1]); varx_type(a5).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[6]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[5]); varx_type(a1).swap(vars[4]); varx_type(a2).swap(vars[3]); varx_type(a3).swap(vars[2]); varx_type(a4).swap(vars[1]); varx_type(a5).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 7 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[7]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[6]); varx_type(a1).swap(vars[5]); varx_type(a2).swap(vars[4]); varx_type(a3).swap(vars[3]); varx_type(a4).swap(vars[2]); varx_type(a5).swap(vars[1]); varx_type(a6).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[7]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[6]); varx_type(a1).swap(vars[5]); varx_type(a2).swap(vars[4]); varx_type(a3).swap(vars[3]); varx_type(a4).swap(vars[2]); varx_type(a5).swap(vars[1]); varx_type(a6).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 8 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[8]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[7]); varx_type(a1).swap(vars[6]); varx_type(a2).swap(vars[5]); varx_type(a3).swap(vars[4]); varx_type(a4).swap(vars[3]); varx_type(a5).swap(vars[2]); varx_type(a6).swap(vars[1]); varx_type(a7).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[8]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[7]); varx_type(a1).swap(vars[6]); varx_type(a2).swap(vars[5]); varx_type(a3).swap(vars[4]); varx_type(a4).swap(vars[3]); varx_type(a5).swap(vars[2]); varx_type(a6).swap(vars[1]); varx_type(a7).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 9 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[9]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[8]); varx_type(a1).swap(vars[7]); varx_type(a2).swap(vars[6]); varx_type(a3).swap(vars[5]); varx_type(a4).swap(vars[4]); varx_type(a5).swap(vars[3]); varx_type(a6).swap(vars[2]); varx_type(a7).swap(vars[1]); varx_type(a8).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[9]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[8]); varx_type(a1).swap(vars[7]); varx_type(a2).swap(vars[6]); varx_type(a3).swap(vars[5]); varx_type(a4).swap(vars[4]); varx_type(a5).swap(vars[3]); varx_type(a6).swap(vars[2]); varx_type(a7).swap(vars[1]); varx_type(a8).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 10 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[10]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[9]); varx_type(a1).swap(vars[8]); varx_type(a2).swap(vars[7]); varx_type(a3).swap(vars[6]); varx_type(a4).swap(vars[5]); varx_type(a5).swap(vars[4]); varx_type(a6).swap(vars[3]); varx_type(a7).swap(vars[2]); varx_type(a8).swap(vars[1]); varx_type(a9).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[10]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[9]); varx_type(a1).swap(vars[8]); varx_type(a2).swap(vars[7]); varx_type(a3).swap(vars[6]); varx_type(a4).swap(vars[5]); varx_type(a5).swap(vars[4]); varx_type(a6).swap(vars[3]); varx_type(a7).swap(vars[2]); varx_type(a8).swap(vars[1]); varx_type(a9).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 11 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[11]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[10]); varx_type(a1).swap(vars[9]); varx_type(a2).swap(vars[8]); varx_type(a3).swap(vars[7]); varx_type(a4).swap(vars[6]); varx_type(a5).swap(vars[5]); varx_type(a6).swap(vars[4]); varx_type(a7).swap(vars[3]); varx_type(a8).swap(vars[2]); varx_type(a9).swap(vars[1]); varx_type(a10).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[11]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[10]); varx_type(a1).swap(vars[9]); varx_type(a2).swap(vars[8]); varx_type(a3).swap(vars[7]); varx_type(a4).swap(vars[6]); varx_type(a5).swap(vars[5]); varx_type(a6).swap(vars[4]); varx_type(a7).swap(vars[3]); varx_type(a8).swap(vars[2]); varx_type(a9).swap(vars[1]); varx_type(a10).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 12 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[12]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[11]); varx_type(a1).swap(vars[10]); varx_type(a2).swap(vars[9]); varx_type(a3).swap(vars[8]); varx_type(a4).swap(vars[7]); varx_type(a5).swap(vars[6]); varx_type(a6).swap(vars[5]); varx_type(a7).swap(vars[4]); varx_type(a8).swap(vars[3]); varx_type(a9).swap(vars[2]); varx_type(a10).swap(vars[1]); varx_type(a11).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[12]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[11]); varx_type(a1).swap(vars[10]); varx_type(a2).swap(vars[9]); varx_type(a3).swap(vars[8]); varx_type(a4).swap(vars[7]); varx_type(a5).swap(vars[6]); varx_type(a6).swap(vars[5]); varx_type(a7).swap(vars[4]); varx_type(a8).swap(vars[3]); varx_type(a9).swap(vars[2]); varx_type(a10).swap(vars[1]); varx_type(a11).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 13 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[13]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[12]); varx_type(a1).swap(vars[11]); varx_type(a2).swap(vars[10]); varx_type(a3).swap(vars[9]); varx_type(a4).swap(vars[8]); varx_type(a5).swap(vars[7]); varx_type(a6).swap(vars[6]); varx_type(a7).swap(vars[5]); varx_type(a8).swap(vars[4]); varx_type(a9).swap(vars[3]); varx_type(a10).swap(vars[2]); varx_type(a11).swap(vars[1]); varx_type(a12).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[13]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[12]); varx_type(a1).swap(vars[11]); varx_type(a2).swap(vars[10]); varx_type(a3).swap(vars[9]); varx_type(a4).swap(vars[8]); varx_type(a5).swap(vars[7]); varx_type(a6).swap(vars[6]); varx_type(a7).swap(vars[5]); varx_type(a8).swap(vars[4]); varx_type(a9).swap(vars[3]); varx_type(a10).swap(vars[2]); varx_type(a11).swap(vars[1]); varx_type(a12).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 14 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[14]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[13]); varx_type(a1).swap(vars[12]); varx_type(a2).swap(vars[11]); varx_type(a3).swap(vars[10]); varx_type(a4).swap(vars[9]); varx_type(a5).swap(vars[8]); varx_type(a6).swap(vars[7]); varx_type(a7).swap(vars[6]); varx_type(a8).swap(vars[5]); varx_type(a9).swap(vars[4]); varx_type(a10).swap(vars[3]); varx_type(a11).swap(vars[2]); varx_type(a12).swap(vars[1]); varx_type(a13).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[14]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[13]); varx_type(a1).swap(vars[12]); varx_type(a2).swap(vars[11]); varx_type(a3).swap(vars[10]); varx_type(a4).swap(vars[9]); varx_type(a5).swap(vars[8]); varx_type(a6).swap(vars[7]); varx_type(a7).swap(vars[6]); varx_type(a8).swap(vars[5]); varx_type(a9).swap(vars[4]); varx_type(a10).swap(vars[3]); varx_type(a11).swap(vars[2]); varx_type(a12).swap(vars[1]); varx_type(a13).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 15 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[15]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[14]); varx_type(a1).swap(vars[13]); varx_type(a2).swap(vars[12]); varx_type(a3).swap(vars[11]); varx_type(a4).swap(vars[10]); varx_type(a5).swap(vars[9]); varx_type(a6).swap(vars[8]); varx_type(a7).swap(vars[7]); varx_type(a8).swap(vars[6]); varx_type(a9).swap(vars[5]); varx_type(a10).swap(vars[4]); varx_type(a11).swap(vars[3]); varx_type(a12).swap(vars[2]); varx_type(a13).swap(vars[1]); varx_type(a14).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[15]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[14]); varx_type(a1).swap(vars[13]); varx_type(a2).swap(vars[12]); varx_type(a3).swap(vars[11]); varx_type(a4).swap(vars[10]); varx_type(a5).swap(vars[9]); varx_type(a6).swap(vars[8]); varx_type(a7).swap(vars[7]); varx_type(a8).swap(vars[6]); varx_type(a9).swap(vars[5]); varx_type(a10).swap(vars[4]); varx_type(a11).swap(vars[3]); varx_type(a12).swap(vars[2]); varx_type(a13).swap(vars[1]); varx_type(a14).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 16 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[16]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[15]); varx_type(a1).swap(vars[14]); varx_type(a2).swap(vars[13]); varx_type(a3).swap(vars[12]); varx_type(a4).swap(vars[11]); varx_type(a5).swap(vars[10]); varx_type(a6).swap(vars[9]); varx_type(a7).swap(vars[8]); varx_type(a8).swap(vars[7]); varx_type(a9).swap(vars[6]); varx_type(a10).swap(vars[5]); varx_type(a11).swap(vars[4]); varx_type(a12).swap(vars[3]); varx_type(a13).swap(vars[2]); varx_type(a14).swap(vars[1]); varx_type(a15).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[16]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[15]); varx_type(a1).swap(vars[14]); varx_type(a2).swap(vars[13]); varx_type(a3).swap(vars[12]); varx_type(a4).swap(vars[11]); varx_type(a5).swap(vars[10]); varx_type(a6).swap(vars[9]); varx_type(a7).swap(vars[8]); varx_type(a8).swap(vars[7]); varx_type(a9).swap(vars[6]); varx_type(a10).swap(vars[5]); varx_type(a11).swap(vars[4]); varx_type(a12).swap(vars[3]); varx_type(a13).swap(vars[2]); varx_type(a14).swap(vars[1]); varx_type(a15).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 17 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[17]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[16]); varx_type(a1).swap(vars[15]); varx_type(a2).swap(vars[14]); varx_type(a3).swap(vars[13]); varx_type(a4).swap(vars[12]); varx_type(a5).swap(vars[11]); varx_type(a6).swap(vars[10]); varx_type(a7).swap(vars[9]); varx_type(a8).swap(vars[8]); varx_type(a9).swap(vars[7]); varx_type(a10).swap(vars[6]); varx_type(a11).swap(vars[5]); varx_type(a12).swap(vars[4]); varx_type(a13).swap(vars[3]); varx_type(a14).swap(vars[2]); varx_type(a15).swap(vars[1]); varx_type(a16).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[17]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[16]); varx_type(a1).swap(vars[15]); varx_type(a2).swap(vars[14]); varx_type(a3).swap(vars[13]); varx_type(a4).swap(vars[12]); varx_type(a5).swap(vars[11]); varx_type(a6).swap(vars[10]); varx_type(a7).swap(vars[9]); varx_type(a8).swap(vars[8]); varx_type(a9).swap(vars[7]); varx_type(a10).swap(vars[6]); varx_type(a11).swap(vars[5]); varx_type(a12).swap(vars[4]); varx_type(a13).swap(vars[3]); varx_type(a14).swap(vars[2]); varx_type(a15).swap(vars[1]); varx_type(a16).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 18 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[18]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[17]); varx_type(a1).swap(vars[16]); varx_type(a2).swap(vars[15]); varx_type(a3).swap(vars[14]); varx_type(a4).swap(vars[13]); varx_type(a5).swap(vars[12]); varx_type(a6).swap(vars[11]); varx_type(a7).swap(vars[10]); varx_type(a8).swap(vars[9]); varx_type(a9).swap(vars[8]); varx_type(a10).swap(vars[7]); varx_type(a11).swap(vars[6]); varx_type(a12).swap(vars[5]); varx_type(a13).swap(vars[4]); varx_type(a14).swap(vars[3]); varx_type(a15).swap(vars[2]); varx_type(a16).swap(vars[1]); varx_type(a17).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[18]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[17]); varx_type(a1).swap(vars[16]); varx_type(a2).swap(vars[15]); varx_type(a3).swap(vars[14]); varx_type(a4).swap(vars[13]); varx_type(a5).swap(vars[12]); varx_type(a6).swap(vars[11]); varx_type(a7).swap(vars[10]); varx_type(a8).swap(vars[9]); varx_type(a9).swap(vars[8]); varx_type(a10).swap(vars[7]); varx_type(a11).swap(vars[6]); varx_type(a12).swap(vars[5]); varx_type(a13).swap(vars[4]); varx_type(a14).swap(vars[3]); varx_type(a15).swap(vars[2]); varx_type(a16).swap(vars[1]); varx_type(a17).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 19 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[19]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[18]); varx_type(a1).swap(vars[17]); varx_type(a2).swap(vars[16]); varx_type(a3).swap(vars[15]); varx_type(a4).swap(vars[14]); varx_type(a5).swap(vars[13]); varx_type(a6).swap(vars[12]); varx_type(a7).swap(vars[11]); varx_type(a8).swap(vars[10]); varx_type(a9).swap(vars[9]); varx_type(a10).swap(vars[8]); varx_type(a11).swap(vars[7]); varx_type(a12).swap(vars[6]); varx_type(a13).swap(vars[5]); varx_type(a14).swap(vars[4]); varx_type(a15).swap(vars[3]); varx_type(a16).swap(vars[2]); varx_type(a17).swap(vars[1]); varx_type(a18).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[19]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[18]); varx_type(a1).swap(vars[17]); varx_type(a2).swap(vars[16]); varx_type(a3).swap(vars[15]); varx_type(a4).swap(vars[14]); varx_type(a5).swap(vars[13]); varx_type(a6).swap(vars[12]); varx_type(a7).swap(vars[11]); varx_type(a8).swap(vars[10]); varx_type(a9).swap(vars[9]); varx_type(a10).swap(vars[8]); varx_type(a11).swap(vars[7]); varx_type(a12).swap(vars[6]); varx_type(a13).swap(vars[5]); varx_type(a14).swap(vars[4]); varx_type(a15).swap(vars[3]); varx_type(a16).swap(vars[2]); varx_type(a17).swap(vars[1]); varx_type(a18).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 20 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[20]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[19]); varx_type(a1).swap(vars[18]); varx_type(a2).swap(vars[17]); varx_type(a3).swap(vars[16]); varx_type(a4).swap(vars[15]); varx_type(a5).swap(vars[14]); varx_type(a6).swap(vars[13]); varx_type(a7).swap(vars[12]); varx_type(a8).swap(vars[11]); varx_type(a9).swap(vars[10]); varx_type(a10).swap(vars[9]); varx_type(a11).swap(vars[8]); varx_type(a12).swap(vars[7]); varx_type(a13).swap(vars[6]); varx_type(a14).swap(vars[5]); varx_type(a15).swap(vars[4]); varx_type(a16).swap(vars[3]); varx_type(a17).swap(vars[2]); varx_type(a18).swap(vars[1]); varx_type(a19).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[20]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[19]); varx_type(a1).swap(vars[18]); varx_type(a2).swap(vars[17]); varx_type(a3).swap(vars[16]); varx_type(a4).swap(vars[15]); varx_type(a5).swap(vars[14]); varx_type(a6).swap(vars[13]); varx_type(a7).swap(vars[12]); varx_type(a8).swap(vars[11]); varx_type(a9).swap(vars[10]); varx_type(a10).swap(vars[9]); varx_type(a11).swap(vars[8]); varx_type(a12).swap(vars[7]); varx_type(a13).swap(vars[6]); varx_type(a14).swap(vars[5]); varx_type(a15).swap(vars[4]); varx_type(a16).swap(vars[3]); varx_type(a17).swap(vars[2]); varx_type(a18).swap(vars[1]); varx_type(a19).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 21 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[21]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[20]); varx_type(a1).swap(vars[19]); varx_type(a2).swap(vars[18]); varx_type(a3).swap(vars[17]); varx_type(a4).swap(vars[16]); varx_type(a5).swap(vars[15]); varx_type(a6).swap(vars[14]); varx_type(a7).swap(vars[13]); varx_type(a8).swap(vars[12]); varx_type(a9).swap(vars[11]); varx_type(a10).swap(vars[10]); varx_type(a11).swap(vars[9]); varx_type(a12).swap(vars[8]); varx_type(a13).swap(vars[7]); varx_type(a14).swap(vars[6]); varx_type(a15).swap(vars[5]); varx_type(a16).swap(vars[4]); varx_type(a17).swap(vars[3]); varx_type(a18).swap(vars[2]); varx_type(a19).swap(vars[1]); varx_type(a20).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[21]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[20]); varx_type(a1).swap(vars[19]); varx_type(a2).swap(vars[18]); varx_type(a3).swap(vars[17]); varx_type(a4).swap(vars[16]); varx_type(a5).swap(vars[15]); varx_type(a6).swap(vars[14]); varx_type(a7).swap(vars[13]); varx_type(a8).swap(vars[12]); varx_type(a9).swap(vars[11]); varx_type(a10).swap(vars[10]); varx_type(a11).swap(vars[9]); varx_type(a12).swap(vars[8]); varx_type(a13).swap(vars[7]); varx_type(a14).swap(vars[6]); varx_type(a15).swap(vars[5]); varx_type(a16).swap(vars[4]); varx_type(a17).swap(vars[3]); varx_type(a18).swap(vars[2]); varx_type(a19).swap(vars[1]); varx_type(a20).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 22 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20, T21 const &a21) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[22]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[21]); varx_type(a1).swap(vars[20]); varx_type(a2).swap(vars[19]); varx_type(a3).swap(vars[18]); varx_type(a4).swap(vars[17]); varx_type(a5).swap(vars[16]); varx_type(a6).swap(vars[15]); varx_type(a7).swap(vars[14]); varx_type(a8).swap(vars[13]); varx_type(a9).swap(vars[12]); varx_type(a10).swap(vars[11]); varx_type(a11).swap(vars[10]); varx_type(a12).swap(vars[9]); varx_type(a13).swap(vars[8]); varx_type(a14).swap(vars[7]); varx_type(a15).swap(vars[6]); varx_type(a16).swap(vars[5]); varx_type(a17).swap(vars[4]); varx_type(a18).swap(vars[3]); varx_type(a19).swap(vars[2]); varx_type(a20).swap(vars[1]); varx_type(a21).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20, T21 const &a21) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[22]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[21]); varx_type(a1).swap(vars[20]); varx_type(a2).swap(vars[19]); varx_type(a3).swap(vars[18]); varx_type(a4).swap(vars[17]); varx_type(a5).swap(vars[16]); varx_type(a6).swap(vars[15]); varx_type(a7).swap(vars[14]); varx_type(a8).swap(vars[13]); varx_type(a9).swap(vars[12]); varx_type(a10).swap(vars[11]); varx_type(a11).swap(vars[10]); varx_type(a12).swap(vars[9]); varx_type(a13).swap(vars[8]); varx_type(a14).swap(vars[7]); varx_type(a15).swap(vars[6]); varx_type(a16).swap(vars[5]); varx_type(a17).swap(vars[4]); varx_type(a18).swap(vars[3]); varx_type(a19).swap(vars[2]); varx_type(a20).swap(vars[1]); varx_type(a21).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 23 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20, T21 const &a21, T22 const &a22) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[23]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[22]); varx_type(a1).swap(vars[21]); varx_type(a2).swap(vars[20]); varx_type(a3).swap(vars[19]); varx_type(a4).swap(vars[18]); varx_type(a5).swap(vars[17]); varx_type(a6).swap(vars[16]); varx_type(a7).swap(vars[15]); varx_type(a8).swap(vars[14]); varx_type(a9).swap(vars[13]); varx_type(a10).swap(vars[12]); varx_type(a11).swap(vars[11]); varx_type(a12).swap(vars[10]); varx_type(a13).swap(vars[9]); varx_type(a14).swap(vars[8]); varx_type(a15).swap(vars[7]); varx_type(a16).swap(vars[6]); varx_type(a17).swap(vars[5]); varx_type(a18).swap(vars[4]); varx_type(a19).swap(vars[3]); varx_type(a20).swap(vars[2]); varx_type(a21).swap(vars[1]); varx_type(a22).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20, T21 const &a21, T22 const &a22) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[23]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[22]); varx_type(a1).swap(vars[21]); varx_type(a2).swap(vars[20]); varx_type(a3).swap(vars[19]); varx_type(a4).swap(vars[18]); varx_type(a5).swap(vars[17]); varx_type(a6).swap(vars[16]); varx_type(a7).swap(vars[15]); varx_type(a8).swap(vars[14]); varx_type(a9).swap(vars[13]); varx_type(a10).swap(vars[12]); varx_type(a11).swap(vars[11]); varx_type(a12).swap(vars[10]); varx_type(a13).swap(vars[9]); varx_type(a14).swap(vars[8]); varx_type(a15).swap(vars[7]); varx_type(a16).swap(vars[6]); varx_type(a17).swap(vars[5]); varx_type(a18).swap(vars[4]); varx_type(a19).swap(vars[3]); varx_type(a20).swap(vars[2]); varx_type(a21).swap(vars[1]); varx_type(a22).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 24 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20, T21 const &a21, T22 const &a22, T23 const &a23) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[24]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[23]); varx_type(a1).swap(vars[22]); varx_type(a2).swap(vars[21]); varx_type(a3).swap(vars[20]); varx_type(a4).swap(vars[19]); varx_type(a5).swap(vars[18]); varx_type(a6).swap(vars[17]); varx_type(a7).swap(vars[16]); varx_type(a8).swap(vars[15]); varx_type(a9).swap(vars[14]); varx_type(a10).swap(vars[13]); varx_type(a11).swap(vars[12]); varx_type(a12).swap(vars[11]); varx_type(a13).swap(vars[10]); varx_type(a14).swap(vars[9]); varx_type(a15).swap(vars[8]); varx_type(a16).swap(vars[7]); varx_type(a17).swap(vars[6]); varx_type(a18).swap(vars[5]); varx_type(a19).swap(vars[4]); varx_type(a20).swap(vars[3]); varx_type(a21).swap(vars[2]); varx_type(a22).swap(vars[1]); varx_type(a23).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20, T21 const &a21, T22 const &a22, T23 const &a23) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[24]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[23]); varx_type(a1).swap(vars[22]); varx_type(a2).swap(vars[21]); varx_type(a3).swap(vars[20]); varx_type(a4).swap(vars[19]); varx_type(a5).swap(vars[18]); varx_type(a6).swap(vars[17]); varx_type(a7).swap(vars[16]); varx_type(a8).swap(vars[15]); varx_type(a9).swap(vars[14]); varx_type(a10).swap(vars[13]); varx_type(a11).swap(vars[12]); varx_type(a12).swap(vars[11]); varx_type(a13).swap(vars[10]); varx_type(a14).swap(vars[9]); varx_type(a15).swap(vars[8]); varx_type(a16).swap(vars[7]); varx_type(a17).swap(vars[6]); varx_type(a18).swap(vars[5]); varx_type(a19).swap(vars[4]); varx_type(a20).swap(vars[3]); varx_type(a21).swap(vars[2]); varx_type(a22).swap(vars[1]); varx_type(a23).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 25 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20, T21 const &a21, T22 const &a22, T23 const &a23, T24 const &a24) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[25]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[24]); varx_type(a1).swap(vars[23]); varx_type(a2).swap(vars[22]); varx_type(a3).swap(vars[21]); varx_type(a4).swap(vars[20]); varx_type(a5).swap(vars[19]); varx_type(a6).swap(vars[18]); varx_type(a7).swap(vars[17]); varx_type(a8).swap(vars[16]); varx_type(a9).swap(vars[15]); varx_type(a10).swap(vars[14]); varx_type(a11).swap(vars[13]); varx_type(a12).swap(vars[12]); varx_type(a13).swap(vars[11]); varx_type(a14).swap(vars[10]); varx_type(a15).swap(vars[9]); varx_type(a16).swap(vars[8]); varx_type(a17).swap(vars[7]); varx_type(a18).swap(vars[6]); varx_type(a19).swap(vars[5]); varx_type(a20).swap(vars[4]); varx_type(a21).swap(vars[3]); varx_type(a22).swap(vars[2]); varx_type(a23).swap(vars[1]); varx_type(a24).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20, T21 const &a21, T22 const &a22, T23 const &a23, T24 const &a24) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[25]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[24]); varx_type(a1).swap(vars[23]); varx_type(a2).swap(vars[22]); varx_type(a3).swap(vars[21]); varx_type(a4).swap(vars[20]); varx_type(a5).swap(vars[19]); varx_type(a6).swap(vars[18]); varx_type(a7).swap(vars[17]); varx_type(a8).swap(vars[16]); varx_type(a9).swap(vars[15]); varx_type(a10).swap(vars[14]); varx_type(a11).swap(vars[13]); varx_type(a12).swap(vars[12]); varx_type(a13).swap(vars[11]); varx_type(a14).swap(vars[10]); varx_type(a15).swap(vars[9]); varx_type(a16).swap(vars[8]); varx_type(a17).swap(vars[7]); varx_type(a18).swap(vars[6]); varx_type(a19).swap(vars[5]); varx_type(a20).swap(vars[4]); varx_type(a21).swap(vars[3]); varx_type(a22).swap(vars[2]); varx_type(a23).swap(vars[1]); varx_type(a24).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 26 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20, T21 const &a21, T22 const &a22, T23 const &a23, T24 const &a24, T25 const &a25) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[26]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[25]); varx_type(a1).swap(vars[24]); varx_type(a2).swap(vars[23]); varx_type(a3).swap(vars[22]); varx_type(a4).swap(vars[21]); varx_type(a5).swap(vars[20]); varx_type(a6).swap(vars[19]); varx_type(a7).swap(vars[18]); varx_type(a8).swap(vars[17]); varx_type(a9).swap(vars[16]); varx_type(a10).swap(vars[15]); varx_type(a11).swap(vars[14]); varx_type(a12).swap(vars[13]); varx_type(a13).swap(vars[12]); varx_type(a14).swap(vars[11]); varx_type(a15).swap(vars[10]); varx_type(a16).swap(vars[9]); varx_type(a17).swap(vars[8]); varx_type(a18).swap(vars[7]); varx_type(a19).swap(vars[6]); varx_type(a20).swap(vars[5]); varx_type(a21).swap(vars[4]); varx_type(a22).swap(vars[3]); varx_type(a23).swap(vars[2]); varx_type(a24).swap(vars[1]); varx_type(a25).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20, T21 const &a21, T22 const &a22, T23 const &a23, T24 const &a24, T25 const &a25) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[26]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[25]); varx_type(a1).swap(vars[24]); varx_type(a2).swap(vars[23]); varx_type(a3).swap(vars[22]); varx_type(a4).swap(vars[21]); varx_type(a5).swap(vars[20]); varx_type(a6).swap(vars[19]); varx_type(a7).swap(vars[18]); varx_type(a8).swap(vars[17]); varx_type(a9).swap(vars[16]); varx_type(a10).swap(vars[15]); varx_type(a11).swap(vars[14]); varx_type(a12).swap(vars[13]); varx_type(a13).swap(vars[12]); varx_type(a14).swap(vars[11]); varx_type(a15).swap(vars[10]); varx_type(a16).swap(vars[9]); varx_type(a17).swap(vars[8]); varx_type(a18).swap(vars[7]); varx_type(a19).swap(vars[6]); varx_type(a20).swap(vars[5]); varx_type(a21).swap(vars[4]); varx_type(a22).swap(vars[3]); varx_type(a23).swap(vars[2]); varx_type(a24).swap(vars[1]); varx_type(a25).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 27 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20, T21 const &a21, T22 const &a22, T23 const &a23, T24 const &a24, T25 const &a25, T26 const &a26) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[27]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[26]); varx_type(a1).swap(vars[25]); varx_type(a2).swap(vars[24]); varx_type(a3).swap(vars[23]); varx_type(a4).swap(vars[22]); varx_type(a5).swap(vars[21]); varx_type(a6).swap(vars[20]); varx_type(a7).swap(vars[19]); varx_type(a8).swap(vars[18]); varx_type(a9).swap(vars[17]); varx_type(a10).swap(vars[16]); varx_type(a11).swap(vars[15]); varx_type(a12).swap(vars[14]); varx_type(a13).swap(vars[13]); varx_type(a14).swap(vars[12]); varx_type(a15).swap(vars[11]); varx_type(a16).swap(vars[10]); varx_type(a17).swap(vars[9]); varx_type(a18).swap(vars[8]); varx_type(a19).swap(vars[7]); varx_type(a20).swap(vars[6]); varx_type(a21).swap(vars[5]); varx_type(a22).swap(vars[4]); varx_type(a23).swap(vars[3]); varx_type(a24).swap(vars[2]); varx_type(a25).swap(vars[1]); varx_type(a26).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20, T21 const &a21, T22 const &a22, T23 const &a23, T24 const &a24, T25 const &a25, T26 const &a26) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[27]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[26]); varx_type(a1).swap(vars[25]); varx_type(a2).swap(vars[24]); varx_type(a3).swap(vars[23]); varx_type(a4).swap(vars[22]); varx_type(a5).swap(vars[21]); varx_type(a6).swap(vars[20]); varx_type(a7).swap(vars[19]); varx_type(a8).swap(vars[18]); varx_type(a9).swap(vars[17]); varx_type(a10).swap(vars[16]); varx_type(a11).swap(vars[15]); varx_type(a12).swap(vars[14]); varx_type(a13).swap(vars[13]); varx_type(a14).swap(vars[12]); varx_type(a15).swap(vars[11]); varx_type(a16).swap(vars[10]); varx_type(a17).swap(vars[9]); varx_type(a18).swap(vars[8]); varx_type(a19).swap(vars[7]); varx_type(a20).swap(vars[6]); varx_type(a21).swap(vars[5]); varx_type(a22).swap(vars[4]); varx_type(a23).swap(vars[3]); varx_type(a24).swap(vars[2]); varx_type(a25).swap(vars[1]); varx_type(a26).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 28 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20, T21 const &a21, T22 const &a22, T23 const &a23, T24 const &a24, T25 const &a25, T26 const &a26, T27 const &a27) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[28]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[27]); varx_type(a1).swap(vars[26]); varx_type(a2).swap(vars[25]); varx_type(a3).swap(vars[24]); varx_type(a4).swap(vars[23]); varx_type(a5).swap(vars[22]); varx_type(a6).swap(vars[21]); varx_type(a7).swap(vars[20]); varx_type(a8).swap(vars[19]); varx_type(a9).swap(vars[18]); varx_type(a10).swap(vars[17]); varx_type(a11).swap(vars[16]); varx_type(a12).swap(vars[15]); varx_type(a13).swap(vars[14]); varx_type(a14).swap(vars[13]); varx_type(a15).swap(vars[12]); varx_type(a16).swap(vars[11]); varx_type(a17).swap(vars[10]); varx_type(a18).swap(vars[9]); varx_type(a19).swap(vars[8]); varx_type(a20).swap(vars[7]); varx_type(a21).swap(vars[6]); varx_type(a22).swap(vars[5]); varx_type(a23).swap(vars[4]); varx_type(a24).swap(vars[3]); varx_type(a25).swap(vars[2]); varx_type(a26).swap(vars[1]); varx_type(a27).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20, T21 const &a21, T22 const &a22, T23 const &a23, T24 const &a24, T25 const &a25, T26 const &a26, T27 const &a27) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[28]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[27]); varx_type(a1).swap(vars[26]); varx_type(a2).swap(vars[25]); varx_type(a3).swap(vars[24]); varx_type(a4).swap(vars[23]); varx_type(a5).swap(vars[22]); varx_type(a6).swap(vars[21]); varx_type(a7).swap(vars[20]); varx_type(a8).swap(vars[19]); varx_type(a9).swap(vars[18]); varx_type(a10).swap(vars[17]); varx_type(a11).swap(vars[16]); varx_type(a12).swap(vars[15]); varx_type(a13).swap(vars[14]); varx_type(a14).swap(vars[13]); varx_type(a15).swap(vars[12]); varx_type(a16).swap(vars[11]); varx_type(a17).swap(vars[10]); varx_type(a18).swap(vars[9]); varx_type(a19).swap(vars[8]); varx_type(a20).swap(vars[7]); varx_type(a21).swap(vars[6]); varx_type(a22).swap(vars[5]); varx_type(a23).swap(vars[4]); varx_type(a24).swap(vars[3]); varx_type(a25).swap(vars[2]); varx_type(a26).swap(vars[1]); varx_type(a27).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 29 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20, T21 const &a21, T22 const &a22, T23 const &a23, T24 const &a24, T25 const &a25, T26 const &a26, T27 const &a27, T28 const &a28) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[29]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[28]); varx_type(a1).swap(vars[27]); varx_type(a2).swap(vars[26]); varx_type(a3).swap(vars[25]); varx_type(a4).swap(vars[24]); varx_type(a5).swap(vars[23]); varx_type(a6).swap(vars[22]); varx_type(a7).swap(vars[21]); varx_type(a8).swap(vars[20]); varx_type(a9).swap(vars[19]); varx_type(a10).swap(vars[18]); varx_type(a11).swap(vars[17]); varx_type(a12).swap(vars[16]); varx_type(a13).swap(vars[15]); varx_type(a14).swap(vars[14]); varx_type(a15).swap(vars[13]); varx_type(a16).swap(vars[12]); varx_type(a17).swap(vars[11]); varx_type(a18).swap(vars[10]); varx_type(a19).swap(vars[9]); varx_type(a20).swap(vars[8]); varx_type(a21).swap(vars[7]); varx_type(a22).swap(vars[6]); varx_type(a23).swap(vars[5]); varx_type(a24).swap(vars[4]); varx_type(a25).swap(vars[3]); varx_type(a26).swap(vars[2]); varx_type(a27).swap(vars[1]); varx_type(a28).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20, T21 const &a21, T22 const &a22, T23 const &a23, T24 const &a24, T25 const &a25, T26 const &a26, T27 const &a27, T28 const &a28) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[29]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[28]); varx_type(a1).swap(vars[27]); varx_type(a2).swap(vars[26]); varx_type(a3).swap(vars[25]); varx_type(a4).swap(vars[24]); varx_type(a5).swap(vars[23]); varx_type(a6).swap(vars[22]); varx_type(a7).swap(vars[21]); varx_type(a8).swap(vars[20]); varx_type(a9).swap(vars[19]); varx_type(a10).swap(vars[18]); varx_type(a11).swap(vars[17]); varx_type(a12).swap(vars[16]); varx_type(a13).swap(vars[15]); varx_type(a14).swap(vars[14]); varx_type(a15).swap(vars[13]); varx_type(a16).swap(vars[12]); varx_type(a17).swap(vars[11]); varx_type(a18).swap(vars[10]); varx_type(a19).swap(vars[9]); varx_type(a20).swap(vars[8]); varx_type(a21).swap(vars[7]); varx_type(a22).swap(vars[6]); varx_type(a23).swap(vars[5]); varx_type(a24).swap(vars[4]); varx_type(a25).swap(vars[3]); varx_type(a26).swap(vars[2]); varx_type(a27).swap(vars[1]); varx_type(a28).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 30 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20, T21 const &a21, T22 const &a22, T23 const &a23, T24 const &a24, T25 const &a25, T26 const &a26, T27 const &a27, T28 const &a28, T29 const &a29) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[30]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[29]); varx_type(a1).swap(vars[28]); varx_type(a2).swap(vars[27]); varx_type(a3).swap(vars[26]); varx_type(a4).swap(vars[25]); varx_type(a5).swap(vars[24]); varx_type(a6).swap(vars[23]); varx_type(a7).swap(vars[22]); varx_type(a8).swap(vars[21]); varx_type(a9).swap(vars[20]); varx_type(a10).swap(vars[19]); varx_type(a11).swap(vars[18]); varx_type(a12).swap(vars[17]); varx_type(a13).swap(vars[16]); varx_type(a14).swap(vars[15]); varx_type(a15).swap(vars[14]); varx_type(a16).swap(vars[13]); varx_type(a17).swap(vars[12]); varx_type(a18).swap(vars[11]); varx_type(a19).swap(vars[10]); varx_type(a20).swap(vars[9]); varx_type(a21).swap(vars[8]); varx_type(a22).swap(vars[7]); varx_type(a23).swap(vars[6]); varx_type(a24).swap(vars[5]); varx_type(a25).swap(vars[4]); varx_type(a26).swap(vars[3]); varx_type(a27).swap(vars[2]); varx_type(a28).swap(vars[1]); varx_type(a29).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20, T21 const &a21, T22 const &a22, T23 const &a23, T24 const &a24, T25 const &a25, T26 const &a26, T27 const &a27, T28 const &a28, T29 const &a29) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[30]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[29]); varx_type(a1).swap(vars[28]); varx_type(a2).swap(vars[27]); varx_type(a3).swap(vars[26]); varx_type(a4).swap(vars[25]); varx_type(a5).swap(vars[24]); varx_type(a6).swap(vars[23]); varx_type(a7).swap(vars[22]); varx_type(a8).swap(vars[21]); varx_type(a9).swap(vars[20]); varx_type(a10).swap(vars[19]); varx_type(a11).swap(vars[18]); varx_type(a12).swap(vars[17]); varx_type(a13).swap(vars[16]); varx_type(a14).swap(vars[15]); varx_type(a15).swap(vars[14]); varx_type(a16).swap(vars[13]); varx_type(a17).swap(vars[12]); varx_type(a18).swap(vars[11]); varx_type(a19).swap(vars[10]); varx_type(a20).swap(vars[9]); varx_type(a21).swap(vars[8]); varx_type(a22).swap(vars[7]); varx_type(a23).swap(vars[6]); varx_type(a24).swap(vars[5]); varx_type(a25).swap(vars[4]); varx_type(a26).swap(vars[3]); varx_type(a27).swap(vars[2]); varx_type(a28).swap(vars[1]); varx_type(a29).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 31 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20, T21 const &a21, T22 const &a22, T23 const &a23, T24 const &a24, T25 const &a25, T26 const &a26, T27 const &a27, T28 const &a28, T29 const &a29, T30 const &a30) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[31]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[30]); varx_type(a1).swap(vars[29]); varx_type(a2).swap(vars[28]); varx_type(a3).swap(vars[27]); varx_type(a4).swap(vars[26]); varx_type(a5).swap(vars[25]); varx_type(a6).swap(vars[24]); varx_type(a7).swap(vars[23]); varx_type(a8).swap(vars[22]); varx_type(a9).swap(vars[21]); varx_type(a10).swap(vars[20]); varx_type(a11).swap(vars[19]); varx_type(a12).swap(vars[18]); varx_type(a13).swap(vars[17]); varx_type(a14).swap(vars[16]); varx_type(a15).swap(vars[15]); varx_type(a16).swap(vars[14]); varx_type(a17).swap(vars[13]); varx_type(a18).swap(vars[12]); varx_type(a19).swap(vars[11]); varx_type(a20).swap(vars[10]); varx_type(a21).swap(vars[9]); varx_type(a22).swap(vars[8]); varx_type(a23).swap(vars[7]); varx_type(a24).swap(vars[6]); varx_type(a25).swap(vars[5]); varx_type(a26).swap(vars[4]); varx_type(a27).swap(vars[3]); varx_type(a28).swap(vars[2]); varx_type(a29).swap(vars[1]); varx_type(a30).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20, T21 const &a21, T22 const &a22, T23 const &a23, T24 const &a24, T25 const &a25, T26 const &a26, T27 const &a27, T28 const &a28, T29 const &a29, T30 const &a30) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[31]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[30]); varx_type(a1).swap(vars[29]); varx_type(a2).swap(vars[28]); varx_type(a3).swap(vars[27]); varx_type(a4).swap(vars[26]); varx_type(a5).swap(vars[25]); varx_type(a6).swap(vars[24]); varx_type(a7).swap(vars[23]); varx_type(a8).swap(vars[22]); varx_type(a9).swap(vars[21]); varx_type(a10).swap(vars[20]); varx_type(a11).swap(vars[19]); varx_type(a12).swap(vars[18]); varx_type(a13).swap(vars[17]); varx_type(a14).swap(vars[16]); varx_type(a15).swap(vars[15]); varx_type(a16).swap(vars[14]); varx_type(a17).swap(vars[13]); varx_type(a18).swap(vars[12]); varx_type(a19).swap(vars[11]); varx_type(a20).swap(vars[10]); varx_type(a21).swap(vars[9]); varx_type(a22).swap(vars[8]); varx_type(a23).swap(vars[7]); varx_type(a24).swap(vars[6]); varx_type(a25).swap(vars[5]); varx_type(a26).swap(vars[4]); varx_type(a27).swap(vars[3]); varx_type(a28).swap(vars[2]); varx_type(a29).swap(vars[1]); varx_type(a30).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } // 32 params template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31> R invoke_method(LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20, T21 const &a21, T22 const &a22, T23 const &a23, T24 const &a24, T25 const &a25, T26 const &a26, T27 const &a27, T28 const &a28, T29 const &a29, T30 const &a30, T31 const &a31) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[32]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[31]); varx_type(a1).swap(vars[30]); varx_type(a2).swap(vars[29]); varx_type(a3).swap(vars[28]); varx_type(a4).swap(vars[27]); varx_type(a5).swap(vars[26]); varx_type(a6).swap(vars[25]); varx_type(a7).swap(vars[24]); varx_type(a8).swap(vars[23]); varx_type(a9).swap(vars[22]); varx_type(a10).swap(vars[21]); varx_type(a11).swap(vars[20]); varx_type(a12).swap(vars[19]); varx_type(a13).swap(vars[18]); varx_type(a14).swap(vars[17]); varx_type(a15).swap(vars[16]); varx_type(a16).swap(vars[15]); varx_type(a17).swap(vars[14]); varx_type(a18).swap(vars[13]); varx_type(a19).swap(vars[12]); varx_type(a20).swap(vars[11]); varx_type(a21).swap(vars[10]); varx_type(a22).swap(vars[9]); varx_type(a23).swap(vars[8]); varx_type(a24).swap(vars[7]); varx_type(a25).swap(vars[6]); varx_type(a26).swap(vars[5]); varx_type(a27).swap(vars[4]); varx_type(a28).swap(vars[3]); varx_type(a29).swap(vars[2]); varx_type(a30).swap(vars[1]); varx_type(a31).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } template <typename R, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31> R invoke_method(of_type<R>, LPCOLESTR methodName, T0 const &a0, T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8, T9 const &a9, T10 const &a10, T11 const &a11, T12 const &a12, T13 const &a13, T14 const &a14, T15 const &a15, T16 const &a16, T17 const &a17, T18 const &a18, T19 const &a19, T20 const &a20, T21 const &a21, T22 const &a22, T23 const &a23, T24 const &a24, T25 const &a25, T26 const &a26, T27 const &a27, T28 const &a28, T29 const &a29, T30 const &a30, T31 const &a31) { typedef com_return_traits<R> return_traits_t; STLSOFT_STATIC_ASSERT(sizeof(varx_type) == sizeof(VARIANT)); varx_type vars[32]; VARIANT result; ::VariantInit(&result); stlsoft::scoped_handle<VARIANT*> result_(&result, ::VariantClear); // arguments must be reversed varx_type(a0).swap(vars[31]); varx_type(a1).swap(vars[30]); varx_type(a2).swap(vars[29]); varx_type(a3).swap(vars[28]); varx_type(a4).swap(vars[27]); varx_type(a5).swap(vars[26]); varx_type(a6).swap(vars[25]); varx_type(a7).swap(vars[24]); varx_type(a8).swap(vars[23]); varx_type(a9).swap(vars[22]); varx_type(a10).swap(vars[21]); varx_type(a11).swap(vars[20]); varx_type(a12).swap(vars[19]); varx_type(a13).swap(vars[18]); varx_type(a14).swap(vars[17]); varx_type(a15).swap(vars[16]); varx_type(a16).swap(vars[15]); varx_type(a17).swap(vars[14]); varx_type(a18).swap(vars[13]); varx_type(a19).swap(vars[12]); varx_type(a20).swap(vars[11]); varx_type(a21).swap(vars[10]); varx_type(a22).swap(vars[9]); varx_type(a23).swap(vars[8]); varx_type(a24).swap(vars[7]); varx_type(a25).swap(vars[6]); varx_type(a26).swap(vars[5]); varx_type(a27).swap(vars[4]); varx_type(a28).swap(vars[3]); varx_type(a29).swap(vars[2]); varx_type(a30).swap(vars[1]); varx_type(a31).swap(vars[0]); object_helper_type_::internal_invoke_method(*this, &result, methodName, &vars[0], STLSOFT_NUM_ELEMENTS(vars)); return return_traits_t::convert(result, m_coercionLevel); } /* ///////////////////////////// end of file //////////////////////////// */
47.367446
541
0.723924
synesissoftware
5da16658b607fe7a8707377b605c51f20f3efe09
6,555
cpp
C++
experimental/graphite/src/DrawWriter.cpp
stayf/skia
454c04e8f3b45ba0c518cbdd49f67bfb95d83c35
[ "BSD-3-Clause" ]
5
2022-02-12T07:52:56.000Z
2022-03-10T23:55:51.000Z
experimental/graphite/src/DrawWriter.cpp
stayf/skia
454c04e8f3b45ba0c518cbdd49f67bfb95d83c35
[ "BSD-3-Clause" ]
3
2019-07-05T17:29:15.000Z
2019-08-19T15:01:09.000Z
experimental/graphite/src/DrawWriter.cpp
stayf/skia
454c04e8f3b45ba0c518cbdd49f67bfb95d83c35
[ "BSD-3-Clause" ]
2
2022-02-12T07:52:59.000Z
2022-03-03T03:06:23.000Z
/* * Copyright 2021 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "experimental/graphite/src/DrawWriter.h" #include "experimental/graphite/src/DrawBufferManager.h" #include "src/gpu/BufferWriter.h" namespace skgpu { DrawWriter::DrawWriter(DrawDispatcher* dispatcher, DrawBufferManager* bufferManager) : DrawWriter(dispatcher, bufferManager, PrimitiveType::kTriangles, 0, 0) {} DrawWriter::DrawWriter(DrawDispatcher* dispatcher, DrawBufferManager* bufferManager, PrimitiveType primitiveType, size_t vertexStride, size_t instanceStride) : fDispatcher(dispatcher) , fManager(bufferManager) , fPrimitiveType(primitiveType) , fVertexStride(vertexStride) , fInstanceStride(instanceStride) { SkASSERT(dispatcher && bufferManager); } void DrawWriter::setTemplateInternal(BindBufferInfo vertices, BindBufferInfo indices, unsigned int count, bool drawPendingVertices) { SkASSERT(!vertices || fVertexStride > 0); if (vertices != fFixedVertexBuffer || indices != fFixedIndexBuffer || count != fFixedVertexCount) { // Issue any accumulated data that referred to the old template. if (drawPendingVertices) { this->drawPendingVertices(); } fFixedBuffersDirty = true; fFixedVertexBuffer = vertices; fFixedIndexBuffer = indices; fFixedVertexCount = count; } } void DrawWriter::drawInternal(BindBufferInfo instances, unsigned int base, unsigned int instanceCount) { // Draw calls that are only 1 instance and have no extra instance data get routed to // the simpler draw APIs. // TODO: Is there any benefit to this? Does it help hint to drivers? Avoid more bugs? // Or should we always call drawInstanced and drawIndexedInstanced? const bool useNonInstancedDraw = !SkToBool(instances) && base == 0 && instanceCount == 1; SkASSERT(!useNonInstancedDraw || fInstanceStride == 0); // Issue new buffer binds only as necessary // TODO: Should this instead be the responsibility of the CB or DrawDispatcher to remember // what was last bound? if (fFixedBuffersDirty || instances != fLastInstanceBuffer) { fDispatcher->bindDrawBuffers(fFixedVertexBuffer, instances, fFixedIndexBuffer); fFixedBuffersDirty = false; fLastInstanceBuffer = instances; } if (useNonInstancedDraw) { if (fFixedIndexBuffer) { // Should only get here from a direct draw, in which case base should be 0 and any // offset needs to be embedded in the BindBufferInfo by caller. SkASSERT(base == 0); fDispatcher->drawIndexed(fPrimitiveType, 0, fFixedVertexCount, 0); } else { // 'base' offsets accumulated vertex data from another DrawWriter across a state change. fDispatcher->draw(fPrimitiveType, base, fFixedVertexCount); } } else { // 'base' offsets accumulated instance data (or is 0 for a direct instanced draw). It is // assumed that any base vertex and index have been folded into the BindBufferInfos already. if (fFixedIndexBuffer) { fDispatcher->drawIndexedInstanced(fPrimitiveType, 0, fFixedVertexCount, 0, base, instanceCount); } else { fDispatcher->drawInstanced(fPrimitiveType, 0, fFixedVertexCount, base, instanceCount); } } } void DrawWriter::drawPendingVertices() { if (fPendingCount > 0) { if (fPendingMode == VertexMode::kInstances) { // This uses instanced draws, so 'base' will be interpreted in instance units. this->drawInternal(fPendingAttrs, fPendingBaseVertex, fPendingCount); } else { // This triggers a non-instanced draw call so 'base' passed to drawInternal is // interpreted in vertex units. this->setTemplateInternal(fPendingAttrs, {}, fPendingCount, /*drawPending=*/false); this->drawInternal({}, fPendingBaseVertex, 1); } fPendingCount = 0; fPendingBaseVertex = 0; fPendingAttrs = {}; } } VertexWriter DrawWriter::appendData(VertexMode mode, size_t stride, unsigned int count) { if (fPendingMode != mode) { // Switched between accumulating vertices and instances, so issue draws for the old data. this->drawPendingVertices(); fPendingMode = mode; } auto [writer, nextChunk] = fManager->getVertexWriter(count * stride); // Check if next chunk's data is contiguous with what's previously been appended if (nextChunk.fBuffer == fPendingAttrs.fBuffer && fPendingAttrs.fOffset + (fPendingBaseVertex + fPendingCount) * stride == nextChunk.fOffset) { // It is, so the next chunk's vertices that will be written can be folded into the next draw fPendingCount += count; } else { // Alignment mismatch, or the old buffer filled up this->drawPendingVertices(); fPendingCount = count; fPendingBaseVertex = 0; fPendingAttrs = nextChunk; } return std::move(writer); } void DrawWriter::newDynamicState() { // Remember where we left off after we draw, since drawPendingVertices() resets all pending data BindBufferInfo base = fPendingAttrs; unsigned int baseVertex = fPendingBaseVertex + fPendingCount; // Draw anything that used the previous dynamic state this->drawPendingVertices(); fPendingAttrs = base; fPendingBaseVertex = baseVertex; } void DrawWriter::newPipelineState(PrimitiveType type, size_t vertexStride, size_t instanceStride) { // Draw anything that used the previous pipeline this->drawPendingVertices(); // For simplicity, if there's a new pipeline, just forget about any previous buffer bindings, // in which case the new writer only needs to use the dispatcher and buffer manager. this->setTemplateInternal({}, {}, 0, false); fLastInstanceBuffer = {}; fPrimitiveType = type; fVertexStride = vertexStride; fInstanceStride = instanceStride; } } // namespace skgpu
39.727273
100
0.646529
stayf
5da1ba293012352740ac98832ab029fa028a558d
4,818
cc
C++
contrib/fluxbox/src/cli_cfiles.cc
xk2600/lightbox
987d901366fe706de1a8bbd1efd49b87abff3e0b
[ "BSD-2-Clause" ]
null
null
null
contrib/fluxbox/src/cli_cfiles.cc
xk2600/lightbox
987d901366fe706de1a8bbd1efd49b87abff3e0b
[ "BSD-2-Clause" ]
null
null
null
contrib/fluxbox/src/cli_cfiles.cc
xk2600/lightbox
987d901366fe706de1a8bbd1efd49b87abff3e0b
[ "BSD-2-Clause" ]
null
null
null
// cli_cfiles.cc for Fluxbox Window Manager // Copyright (c) 2014 - Mathias Gumz <akira at fluxbox.org> // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #include "cli.hh" #include "defaults.hh" #include "Debug.hh" #include "FbTk/FileUtil.hh" #include "FbTk/I18n.hh" #include "FbTk/Resource.hh" #include "FbTk/StringUtil.hh" #ifdef HAVE_CSTRING #include <cstring> #else #include <string.h> #endif #ifdef HAVE_SYS_STAT_H #include <sys/types.h> #include <sys/stat.h> #endif // HAVE_SYS_STAT_H #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_CSTDLIB #include <cstdlib> #else #include <stdlib.h> #endif using std::string; using std::endl; using std::cerr; #ifdef _WIN32 /** Wrapper function for Windows builds - mkdir takes only one param. */ static int mkdir(const char *dirname, int /*permissions*/) { return mkdir(dirname); } #endif /** setup the configutation files in home directory */ void FluxboxCli::setupConfigFiles(const std::string& dirname, const std::string& rc) { _FB_USES_NLS; const bool has_dir = FbTk::FileUtil::isDirectory(dirname.c_str()); struct CFInfo { bool create_file; const char* default_name; const std::string filename; } cfiles[] = { { !has_dir, DEFAULT_INITFILE, rc }, { !has_dir, DEFAULTKEYSFILE, dirname + "/keys" }, { !has_dir, DEFAULTMENU, dirname + "/menu" }, { !has_dir, DEFAULT_APPSFILE, dirname + "/apps" }, { !has_dir, DEFAULT_OVERLAY, dirname + "/overlay" }, { !has_dir, DEFAULT_WINDOWMENU, dirname + "/windowmenu" } }; const size_t nr_of_cfiles = sizeof(cfiles)/sizeof(CFInfo); if (has_dir) { // check if anything with these names exists, if not create new for (size_t i = 0; i < nr_of_cfiles; ++i) { cfiles[i].create_file = access(cfiles[i].filename.c_str(), F_OK); } } else { fbdbg << "Creating dir: " << dirname << endl; if (mkdir(dirname.c_str(), 0700)) { fprintf(stderr, _FB_CONSOLETEXT(Fluxbox, ErrorCreatingDirectory, "Can't create %s directory", "Can't create a directory, one %s for directory name").c_str(), dirname.c_str()); cerr << endl; return; } } bool sync_fs = false; // copy default files if needed for (size_t i = 0; i < nr_of_cfiles; ++i) { if (cfiles[i].create_file) { FbTk::FileUtil::copyFile(FbTk::StringUtil::expandFilename(cfiles[i].default_name).c_str(), cfiles[i].filename.c_str()); sync_fs = true; } } #ifdef HAVE_SYNC if (sync_fs) { sync(); } #endif } // configs might be out of date, so run fluxbox-update_configs // if necassary. void FluxboxCli::updateConfigFilesIfNeeded(const std::string& rc_file) { FbTk::ResourceManager r_mgr(rc_file.c_str(), false); FbTk::Resource<int> c_version(r_mgr, 0, "session.configVersion", "Session.ConfigVersion"); if (!r_mgr.load(rc_file.c_str())) { _FB_USES_NLS; cerr << _FB_CONSOLETEXT(Fluxbox, CantLoadRCFile, "Failed to load database", "") << ": " << rc_file << endl; return; } if (*c_version < CONFIG_VERSION) { fbdbg << "updating config files from version " << *c_version << " to " << CONFIG_VERSION << endl; string commandargs = realProgramName("fluxbox-update_configs"); commandargs += " -rc " + rc_file; if (system(commandargs.c_str())) { fbdbg << "running '" << commandargs << "' failed." << endl; } #ifdef HAVE_SYNC sync(); #endif // HAVE_SYNC } }
28.850299
131
0.633665
xk2600
5da7f2858ef7bc278e13fbc2a11ced848291d7dc
1,255
cpp
C++
MCA/CPP/Lab/Q17.cpp
muhammadmuzzammil1998/CollegeStuff
618cec9ebfbfd29a2d1e5a182b90cfb36b38a906
[ "MIT" ]
3
2018-03-13T12:34:51.000Z
2018-10-02T18:54:22.000Z
MCA/CPP/Lab/Q17.cpp
muhammadmuzzammil1998/CollegeStuff
618cec9ebfbfd29a2d1e5a182b90cfb36b38a906
[ "MIT" ]
null
null
null
MCA/CPP/Lab/Q17.cpp
muhammadmuzzammil1998/CollegeStuff
618cec9ebfbfd29a2d1e5a182b90cfb36b38a906
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; class Student { int rollno; double marks; string name; void _print() { cout << " " << this->rollno << " " << this->name << "\t\t " << this->marks << endl; } public: void UpdateRollNo(int rollno) { this->rollno = rollno; } void UpdateMarks(double marks) { this->marks = marks; } void UpdateName(string name) { this->name = name; } int RollNo() { return this->rollno; } double Marks() { return this->marks; } string Name() { return this->name; } void PrintDetails() { this->_print(); } void GetDetails() { cout << "\n\nEnter Name: "; cin.ignore(); getline(cin, this->name); cout << "Enter rollno: "; cin >> this->rollno; cout << "Enter Marks: "; cin >> this->marks; } }; int main() { int n; cout << "Enter number of students: "; cin >> n; Student students[n]; for (int i = 0; i < n; i++) { students[i].GetDetails(); } students[0].UpdateName("Muzammil"); cout << "\n\nStudents:\n"; for (int i = 0; i < n; i++) { students[i].PrintDetails(); } double sum; for (int i = 0; i < n; i++) { sum += students[i].Marks(); } cout << "\nClass average: " << sum / n << endl; return 0; }
19.920635
78
0.555378
muhammadmuzzammil1998
5da91969a5720632623d148beafd7ec7359bd343
26,468
cpp
C++
source/App/TAppDownConvert/TAppDownConvert.cpp
mdasari823/shvc
17c99abbb2bcab3a382d092d75a42e57b74cff1d
[ "BSD-3-Clause" ]
null
null
null
source/App/TAppDownConvert/TAppDownConvert.cpp
mdasari823/shvc
17c99abbb2bcab3a382d092d75a42e57b74cff1d
[ "BSD-3-Clause" ]
null
null
null
source/App/TAppDownConvert/TAppDownConvert.cpp
mdasari823/shvc
17c99abbb2bcab3a382d092d75a42e57b74cff1d
[ "BSD-3-Clause" ]
null
null
null
/* The copyright in this software is being made available under the BSD * License, included below. This software may be subject to other third party * and contributor rights, including patent rights, and no such rights are * granted under this license. * * Copyright (c) 2010-2016, ITU/ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the ITU/ISO/IEC nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ /** \file TAppDownConvert.cpp \brief Down convert application main */ #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include "DownConvert.h" typedef struct { int stride; int lines; short* data; short* data2; } ColorComponent; typedef struct { int inputBitDepth; int outputBitDepth; ColorComponent y; ColorComponent u; ColorComponent v; } YuvFrame; void createColorComponent( ColorComponent& c, int maxwidth, int maxheight ) { maxwidth = ( ( maxwidth + 15 ) >> 4 ) << 4; maxheight = ( ( maxheight + 15 ) >> 4 ) << 4; int size = maxwidth * maxheight; c.stride = maxwidth; c.lines = maxheight; c.data = new short [ size ]; c.data2 = new short [ size ]; if( ! c.data || ! c.data2 ) { fprintf(stderr, "\nERROR: memory allocation failed!\n\n"); exit(1); } } void deleteColorComponent( ColorComponent& c ) { delete[] c.data; delete[] c.data2; c.stride = 0; c.lines = 0; c.data = 0; c.data2 = 0; } int readColorComponent( ColorComponent& c, FILE* file, int width, int height, int inputBitDepth, bool second ) { assert( width <= c.stride ); assert( height <= c.lines ); unsigned char *temp=NULL; int iMaxPadWidth = gMin( c.stride, ( ( width + 15 ) >> 4 ) << 4 ); int iMaxPadHeight = gMin( c.lines, ( ( height + 31 ) >> 5 ) << 5 ); for( int i = 0; i < height; i++ ) { short* buffer = ( second ? c.data2 : c.data ) + i * c.stride; int rsize; if (inputBitDepth == 10) { rsize = (int)fread( buffer, sizeof(short), width, file ); } else { if (temp == NULL) temp = (unsigned char * )calloc(width, sizeof(unsigned char)); rsize = (int)fread( temp, sizeof(unsigned char), width, file ); for (int j = 0; j < width; j++) buffer[j] = (short) temp[j]; } if( rsize != width ) { return 1; } for( int xp = width; xp < iMaxPadWidth; xp++ ) { buffer[xp] = buffer[xp-1]; } } for( int yp = height; yp < iMaxPadHeight; yp++ ) { short* buffer = ( second ? c.data2 : c.data ) + yp * c.stride; short* bufferX = buffer - c.stride; for( int xp = 0; xp < c.stride; xp++ ) { buffer[xp] = bufferX[xp]; } } if (temp!=NULL) free(temp); return 0; } void duplicateColorComponent( ColorComponent& c ) { memcpy( c.data2, c.data, c.stride * c.lines * sizeof(short) ); } void combineTopAndBottomInColorComponent( ColorComponent& c, Bool bBotField ) { int offs = ( bBotField ? c.stride : 0 ); short* pDes = c.data + offs; short* pSrc = c.data2 + offs; for( int i = 0; i < c.lines / 2; i++, pDes += 2*c.stride, pSrc += 2*c.stride ) { memcpy( pDes, pSrc, c.stride * sizeof(short) ); } } void writeColorComponent( ColorComponent& c, FILE* file, int width, int height, int outputBitDepth, bool second ) { assert( width <= c.stride ); assert( height <= c.lines ); unsigned char* temp = NULL; for( int i = 0; i < height; i++ ) { short* buffer = ( second ? c.data2 : c.data ) + i * c.stride; int wsize; if ( outputBitDepth == 8 ) { if (temp == NULL) temp = (unsigned char * )calloc(width, sizeof(unsigned char)); for (int j = 0; j < width; j ++) temp[j] = (unsigned char)buffer[j]; wsize = (int)fwrite( temp, sizeof(unsigned char), width, file ); } else { wsize = (int)fwrite( buffer, sizeof(short), width, file ); } if( wsize != width ) { fprintf(stderr, "\nERROR: while writing to output file!\n\n"); exit(1); } } } void createFrame( YuvFrame& f, int width, int height, int inputBitDepth, int outputBitDepth ) { f.inputBitDepth = inputBitDepth; f.outputBitDepth = outputBitDepth; createColorComponent( f.y, width, height ); createColorComponent( f.u, width >> 1, height >> 1 ); createColorComponent( f.v, width >> 1, height >> 1 ); } void deleteFrame( YuvFrame& f ) { deleteColorComponent( f.y ); deleteColorComponent( f.u ); deleteColorComponent( f.v ); } int readFrame( YuvFrame& f, FILE* file, int width, int height, bool second = false ) { ROTRS( readColorComponent( f.y, file, width, height, f.inputBitDepth, second ), 1 ); ROTRS( readColorComponent( f.u, file, width >> 1, height >> 1, f.inputBitDepth, second ), 1 ); ROTRS( readColorComponent( f.v, file, width >> 1, height >> 1, f.inputBitDepth, second ), 1 ); return 0; } void duplicateFrame( YuvFrame& f ) { duplicateColorComponent( f.y ); duplicateColorComponent( f.u ); duplicateColorComponent( f.v ); } void combineTopAndBottomInFrame( YuvFrame& f, Bool botField ) { combineTopAndBottomInColorComponent( f.y, botField ); combineTopAndBottomInColorComponent( f.u, botField ); combineTopAndBottomInColorComponent( f.v, botField ); } void writeFrame( YuvFrame& f, FILE* file, int width, int height, bool both = false ) { writeColorComponent( f.y, file, width, height, f.outputBitDepth, false ); writeColorComponent( f.u, file, width >> 1, height >> 1, f.outputBitDepth, false ); writeColorComponent( f.v, file, width >> 1, height >> 1, f.outputBitDepth, false ); if( both ) { writeColorComponent( f.y, file, width, height, f.outputBitDepth, true ); writeColorComponent( f.u, file, width >> 1, height >> 1, f.outputBitDepth, true ); writeColorComponent( f.v, file, width >> 1, height >> 1, f.outputBitDepth, true ); } } void print_usage_and_exit( int test, const char* name, const char* message = 0 ) { if( test ) { if( message ) { fprintf ( stderr, "\nERROR: %s\n", message ); } fprintf ( stderr, "\nUsage: %s <win> <hin> <in> <wout> <hout> <out> [<bin> <bout> <method> <t> [<skip> [<frms>]]] [[-phase <args>] ]\n\n", name ); fprintf ( stderr, " win : input width (luma samples)\n" ); fprintf ( stderr, " hin : input height (luma samples)\n" ); fprintf ( stderr, " in : input file\n" ); fprintf ( stderr, " wout : output width (luma samples)\n" ); fprintf ( stderr, " hout : output height (luma samples)\n" ); fprintf ( stderr, " out : output file\n" ); fprintf ( stderr, "\n--------------------------- OPTIONAL ---------------------------\n\n" ); fprintf ( stderr, " bin : input bit depth (8 or 10) (default: 8)\n" ); fprintf ( stderr, " bout : output bit depth (8 or 10) (default: 8)\n" ); fprintf ( stderr, " method : sampling method (0, 1, 2, 3, 4) (default: 0)\n" ); fprintf ( stderr, " t : number of temporal downsampling stages (default: 0)\n" ); fprintf ( stderr, " skip : number of frames to skip at start (default: 0)\n" ); fprintf ( stderr, " frms : number of frames wanted in output file (default: max)\n" ); fprintf ( stderr, "\n-------------------------- OVERLOADED --------------------------\n\n" ); fprintf ( stderr, " -phase <in_uv_ph_x> <in_uv_ph_y> <out_uv_ph_x> <out_uv_ph_y>\n"); fprintf ( stderr, " in_uv_ph_x : input chroma phase shift in horizontal direction (default:-1)\n" ); fprintf ( stderr, " in_uv_ph_y : input chroma phase shift in vertical direction (default: 0)\n" ); fprintf ( stderr, " out_uv_ph_x: output chroma phase shift in horizontal direction (default:-1)\n" ); fprintf ( stderr, " out_uv_ph_y: output chroma phase shift in vertical direction (default: 0)\n" ); fprintf ( stderr, "\n-------------------------- EXAMPLE --------------------------\n\n" ); fprintf ( stderr, "\nUsage: %s 4096 2048 input_video_4096x2048_10bits.yuv 2048 1024 output_video_2048x1024_8bits.yuv 10 8\n\n", name ); fprintf ( stderr, "\n\n"); exit ( 1 ); } } void updateCropParametersFromFile( ResizeParameters& cRP, FILE* cropFile, int resamplingMethod, char* name ) { int crop_x0 = 0; int crop_y0 = 0; int crop_w = 0; int crop_h = 0; if( fscanf( cropFile, "%d,%d,%d,%d\n", &crop_x0, &crop_y0, &crop_w, &crop_h ) == 4 ) { cRP.m_iLeftFrmOffset = crop_x0; cRP.m_iTopFrmOffset = crop_y0; cRP.m_iScaledRefFrmWidth = crop_w; cRP.m_iScaledRefFrmHeight = crop_h; } print_usage_and_exit( cRP.m_iLeftFrmOffset & 1 || cRP.m_iTopFrmOffset & 1, name, "cropping parameters must be even values" ); print_usage_and_exit( cRP.m_iScaledRefFrmWidth & 1 || cRP.m_iScaledRefFrmHeight & 1, name, "cropping parameters must be even values" ); print_usage_and_exit( resamplingMethod == 2 && cRP.m_iScaledRefFrmWidth != gMin( cRP.m_iRefLayerFrmWidth, cRP.m_iFrameWidth ), name, "crop dimensions must be the same as the minimal dimensions" ); print_usage_and_exit( resamplingMethod == 2 && cRP.m_iScaledRefFrmHeight != gMin( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight ), name, "crop dimensions must be the same as the minimal dimensions" ); print_usage_and_exit( cRP.m_iScaledRefFrmWidth > gMax( cRP.m_iRefLayerFrmWidth, cRP.m_iFrameWidth ), name, "wrong crop window size" ); print_usage_and_exit( cRP.m_iScaledRefFrmHeight > gMax( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight ), name, "wrong crop window size" ); print_usage_and_exit( cRP.m_iScaledRefFrmWidth < gMin( cRP.m_iRefLayerFrmWidth, cRP.m_iFrameWidth ), name, "wrong crop window size" ); print_usage_and_exit( cRP.m_iScaledRefFrmHeight < gMin( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight ), name, "wrong crop window size" ); print_usage_and_exit( cRP.m_iLeftFrmOffset + cRP.m_iScaledRefFrmWidth > gMax( cRP.m_iRefLayerFrmWidth, cRP.m_iFrameWidth ), name, "wrong crop window size and origin" ); print_usage_and_exit( cRP.m_iTopFrmOffset + cRP.m_iScaledRefFrmHeight > gMax( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight ), name, "wrong crop window size and origin" ); } void resampleFrame( YuvFrame& rcFrame, DownConvert& rcDownConvert, ResizeParameters& rcRP, int resamplingMethod, int resamplingMode, bool resampling, bool upsampling, bool bSecondInputFrame ) { assert( upsampling == 0 ); //===== downsampling ===== ResizeParameters cRP = rcRP; { Int iRefVerMbShift = ( cRP.m_bRefLayerFrameMbsOnlyFlag ? 4 : 5 ); Int iScaledVerShift = ( cRP.m_bFrameMbsOnlyFlag ? 1 : 2 ); Int iHorDiv = ( cRP.m_iFrameWidth << 1 ); Int iVerDiv = ( cRP.m_iFrameHeight << iScaledVerShift ); Int iRefFrmW = ( ( cRP.m_iFrameWidth + ( 1 << 4 ) - 1 ) >> 4 ) << 4; // round to next multiple of 16 Int iRefFrmH = ( ( cRP.m_iFrameHeight + ( 1 << iRefVerMbShift ) - 1 ) >> iRefVerMbShift ) << iRefVerMbShift; // round to next multiple of 16 or 32 (for interlaced) Int iScaledRefFrmW = ( ( cRP.m_iScaledRefFrmWidth * iRefFrmW + ( iHorDiv >> 1 ) ) / iHorDiv ) << 1; // scale and round to next multiple of 2 Int iScaledRefFrmH = ( ( cRP.m_iScaledRefFrmHeight * iRefFrmH + ( iVerDiv >> 1 ) ) / iVerDiv ) << iScaledVerShift; // scale and round to next multiple of 2 or 4 (for interlaced) cRP.m_iFrameWidth = iRefFrmW; cRP.m_iFrameHeight = iRefFrmH; cRP.m_iScaledRefFrmWidth = iScaledRefFrmW; cRP.m_iScaledRefFrmHeight = iScaledRefFrmH; cRP.inputBitDepth = rcFrame.inputBitDepth; cRP.outputBitDepth = rcFrame.outputBitDepth; } assert( resamplingMethod == 0 ); if( resamplingMode < 4 ) { rcDownConvert.downsamplingSVC ( rcFrame.y.data, rcFrame.y.stride, rcFrame.u.data, rcFrame.u.stride, rcFrame.v.data, rcFrame.v.stride, &cRP, resamplingMode == 3 ); return; } } int main( int argc, char *argv[] ) { //===== set standard resize parameters ===== ResizeParameters cRP; cRP.m_bRefLayerFrameMbsOnlyFlag = true; cRP.m_bFrameMbsOnlyFlag = true; cRP.m_bRefLayerFieldPicFlag = false; cRP.m_bFieldPicFlag = false; cRP.m_bRefLayerBotFieldFlag = false; cRP.m_bBotFieldFlag = false; cRP.m_bRefLayerIsMbAffFrame = false; cRP.m_bIsMbAffFrame = false; #if ZERO_PHASE cRP.m_iRefLayerChromaPhaseX = 0; cRP.m_iRefLayerChromaPhaseY = 1; cRP.m_iChromaPhaseX = 0; cRP.m_iChromaPhaseY = 1; #else cRP.m_iRefLayerChromaPhaseX = -1; cRP.m_iRefLayerChromaPhaseY = 0; cRP.m_iChromaPhaseX = -1; cRP.m_iChromaPhaseY = 0; #endif cRP.m_iRefLayerFrmWidth = 0; cRP.m_iRefLayerFrmHeight = 0; cRP.m_iScaledRefFrmWidth = 0; cRP.m_iScaledRefFrmHeight = 0; cRP.m_iFrameWidth = 0; cRP.m_iFrameHeight = 0; cRP.m_iLeftFrmOffset = 0; cRP.m_iTopFrmOffset = 0; //cRP.m_iExtendedSpatialScalability = 0; cRP.m_iLevelIdc = 0; //===== init parameters ===== FILE* inputFile = 0; FILE* outputFile = 0; FILE* croppingParametersFile = 0; int inputBitDepth = 8; int outputBitDepth = 8; int resamplingMethod = 0; int resamplingMode = 0; bool croppingInitialized = false; bool phaseInitialized = false; bool methodInitialized = false; bool resampling = false; bool upsampling = false; int numSpatialDyadicStages = 0; int skipBetween = 0; int skipAtStart = 0; int maxNumOutputFrames = 0; //===== read input parameters ===== print_usage_and_exit( ( argc < 7 || argc > 24 ), argv[0], "wrong number of arguments" ); cRP.m_iRefLayerFrmWidth = atoi ( argv[1] ); cRP.m_iRefLayerFrmHeight = atoi ( argv[2] ); inputFile = fopen ( argv[3], "rb" ); cRP.m_iFrameWidth = atoi ( argv[4] ); cRP.m_iFrameHeight = atoi ( argv[5] ); outputFile = fopen ( argv[6], "wb" ); print_usage_and_exit( ! inputFile, argv[0], "failed to open input file" ); print_usage_and_exit( ! outputFile, argv[0], "failed to open input file" ); print_usage_and_exit( cRP.m_iRefLayerFrmWidth > cRP.m_iFrameWidth && cRP.m_iRefLayerFrmHeight < cRP.m_iFrameHeight, argv[0], "mixed upsampling and downsampling not supported" ); print_usage_and_exit( cRP.m_iRefLayerFrmWidth < cRP.m_iFrameWidth && cRP.m_iRefLayerFrmHeight > cRP.m_iFrameHeight, argv[0], "mixed upsampling and downsampling not supported" ); for( int i = 7; i < argc; ) { if( ! strcmp( argv[i], "-phase" ) ) { print_usage_and_exit( resamplingMethod != 0, argv[0], "phases only supported in normative resampling" ); print_usage_and_exit( phaseInitialized || argc < i+5, argv[0], "wrong number of phase parameters" ); phaseInitialized = true; i++; cRP.m_iRefLayerChromaPhaseX = atoi( argv[i++] ); cRP.m_iRefLayerChromaPhaseY = atoi( argv[i++] ); cRP.m_iChromaPhaseX = atoi( argv[i++] ); cRP.m_iChromaPhaseY = atoi( argv[i++] ); print_usage_and_exit( cRP.m_iRefLayerChromaPhaseX > 0 || cRP.m_iRefLayerChromaPhaseX < -1, argv[0], "wrong phase x parameters (range : [-1, 0])"); print_usage_and_exit( cRP.m_iRefLayerChromaPhaseY > 1 || cRP.m_iRefLayerChromaPhaseY < -1, argv[0], "wrong phase x parameters (range : [-1, 1])"); print_usage_and_exit( cRP.m_iChromaPhaseX > 0 || cRP.m_iChromaPhaseX < -1, argv[0], "wrong phase x parameters (range : [-1, 0])"); print_usage_and_exit( cRP.m_iChromaPhaseY > 1 || cRP.m_iChromaPhaseY < -1, argv[0], "wrong phase x parameters (range : [-1, 1])"); } else if (i == 7) // input bit depth { inputBitDepth = atoi( argv[i++] ); print_usage_and_exit( inputBitDepth != 8 && inputBitDepth != 10, argv[0], "wrong input bit depth (8 bit or 10 bit)"); } else if (i == 8) // output bit depth { outputBitDepth = atoi( argv[i++] ); print_usage_and_exit( outputBitDepth != 8 && outputBitDepth != 10, argv[0], "wrong output bit depth (8 bit or 10 bit)"); } else if (i == 9) // downsampling methods { methodInitialized = true; resamplingMethod = atoi( argv[i++] ); print_usage_and_exit( resamplingMethod < 0 || resamplingMethod > 4, argv[0], "unsupported method" ); if( resamplingMethod > 2 ) { print_usage_and_exit( cRP.m_iRefLayerFrmWidth > cRP.m_iFrameWidth, argv[0], "method 3 and 4 are not supported for downsampling" ); print_usage_and_exit( cRP.m_iRefLayerFrmHeight > cRP.m_iFrameHeight, argv[0], "method 3 and 4 are not supported for downsampling" ); } if( resamplingMethod != 2 ) { resampling = true; upsampling = ( cRP.m_iRefLayerFrmWidth < cRP.m_iFrameWidth ) || ( cRP.m_iRefLayerFrmHeight < cRP.m_iFrameHeight ); } if( resamplingMethod == 1 ) { if( upsampling ) { int div = cRP.m_iFrameWidth / cRP.m_iRefLayerFrmWidth; if ( div == 1) numSpatialDyadicStages = 0; else if( div == 2) numSpatialDyadicStages = 1; else if( div == 4) numSpatialDyadicStages = 2; else if( div == 8) numSpatialDyadicStages = 3; else numSpatialDyadicStages = -1; print_usage_and_exit( numSpatialDyadicStages < 0, argv[0], "ratio not supported for dyadic upsampling method" ); print_usage_and_exit( div * cRP.m_iRefLayerFrmWidth != cRP.m_iFrameWidth, argv[0], "ratio is not dyadic in dyadic mode" ); print_usage_and_exit( div * cRP.m_iRefLayerFrmHeight != cRP.m_iFrameHeight, argv[0], "different horizontal and vertical ratio in dyadic mode" ); } else { int div = cRP.m_iRefLayerFrmWidth / cRP.m_iFrameWidth; if ( div == 1) numSpatialDyadicStages = 0; else if( div == 2) numSpatialDyadicStages = 1; else if( div == 4) numSpatialDyadicStages = 2; else if( div == 8) numSpatialDyadicStages = 3; else numSpatialDyadicStages = -1; print_usage_and_exit( numSpatialDyadicStages < 0, argv[0], "ratio not supported for dyadic downsampling method" ); print_usage_and_exit( div * cRP.m_iFrameWidth != cRP.m_iRefLayerFrmWidth, argv[0], "ratio is not dyadic in dyadic mode" ); print_usage_and_exit( div * cRP.m_iFrameHeight != cRP.m_iRefLayerFrmHeight, argv[0], "different horizontal and vertical ratio in dyadic mode" ); } } } else if( i == 10 ) // temporal stages { int TStages = atoi( argv[i++] ); skipBetween = ( 1 << TStages ) - 1; print_usage_and_exit( TStages < 0, argv[0], "negative number of temporal stages" ); } else if( i == 11 ) // skipped frames { skipAtStart = atoi( argv[i++] ); print_usage_and_exit( skipAtStart < 0, argv[0], "negative number of skipped frames at start" ); } else if( i == 12 ) // output frames { maxNumOutputFrames = atoi( argv[i++] ); print_usage_and_exit( maxNumOutputFrames < 0 , argv[0], "negative number of output frames" ); } else { print_usage_and_exit( true, argv[0], "error in command line parameters" ); } } if( ! methodInitialized ) { resampling = true; upsampling = ( cRP.m_iRefLayerFrmWidth < cRP.m_iFrameWidth ) || ( cRP.m_iRefLayerFrmHeight < cRP.m_iFrameHeight ); } if( ! croppingInitialized ) { if( resamplingMethod == 2 ) { cRP.m_iScaledRefFrmWidth = gMin( cRP.m_iRefLayerFrmWidth, cRP.m_iFrameWidth ); cRP.m_iScaledRefFrmHeight = gMin( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight ); } else { cRP.m_iScaledRefFrmWidth = gMax( cRP.m_iRefLayerFrmWidth, cRP.m_iFrameWidth ); cRP.m_iScaledRefFrmHeight = gMax( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight ); } } //===== set basic parameters for resampling control ===== if( resamplingMethod == 0 ) { if( resamplingMode == 1 ) { cRP.m_bRefLayerFrameMbsOnlyFlag = false; cRP.m_bFrameMbsOnlyFlag = false; } else if( resamplingMode == 2 || resamplingMode == 3 ) { cRP.m_bFrameMbsOnlyFlag = false; if( ! upsampling ) { cRP.m_bFieldPicFlag = true; cRP.m_bBotFieldFlag = ( resamplingMode == 3 ); } } else if( resamplingMode == 4 || resamplingMode == 5 ) { cRP.m_bRefLayerFrameMbsOnlyFlag = false; cRP.m_bRefLayerFieldPicFlag = true; } } //===== initialize classes ===== YuvFrame cFrame; DownConvert cDownConvert; { int maxWidth = gMax( cRP.m_iRefLayerFrmWidth, cRP.m_iFrameWidth ); int maxHeight = gMax( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight ); int minWidth = gMin( cRP.m_iRefLayerFrmWidth, cRP.m_iFrameWidth ); int minHeight = gMin( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight ); int minWRnd16 = ( ( minWidth + 15 ) >> 4 ) << 4; int minHRnd32 = ( ( minHeight + 31 ) >> 5 ) << 5; maxWidth = ( ( maxWidth * minWRnd16 + ( minWidth << 4 ) - 1 ) / ( minWidth << 4 ) ) << 4; maxHeight = ( ( maxHeight * minHRnd32 + ( minHeight << 4 ) - 1 ) / ( minHeight << 4 ) ) << 4; createFrame( cFrame, maxWidth, maxHeight, inputBitDepth, outputBitDepth ); cDownConvert.init( maxWidth, maxHeight ); } printf("Resampler\n\n"); //===== loop over frames ===== int skip = skipAtStart; int writtenFrames = 0; int numInputFrames = ( resamplingMode >= 4 && ! upsampling ? 2 : 1 ); int numOutputFrames = ( resamplingMode >= 4 && upsampling ? 2 : 1 ); bool bFinished = false; long startTime = clock(); while( ! bFinished ) { for( int inputFrame = 0; inputFrame < numInputFrames && ! bFinished; inputFrame++ ) { //===== read input frame ===== for( int numToRead = skip + 1; numToRead > 0 && ! bFinished; numToRead-- ) { bFinished = ( readFrame( cFrame, inputFile, cRP.m_iRefLayerFrmWidth, cRP.m_iRefLayerFrmHeight, inputFrame != 0 ) != 0 ); } skip = skipBetween; if( cRP.m_iExtendedSpatialScalability == 2 && ! bFinished ) { updateCropParametersFromFile( cRP, croppingParametersFile, resamplingMethod, argv[0] ); } //===== set resampling parameter ===== if( resamplingMethod != 0 && cRP.m_iScaledRefFrmWidth == gMin( cRP.m_iRefLayerFrmWidth, cRP.m_iFrameWidth ) && cRP.m_iScaledRefFrmHeight == gMin( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight ) ) { resampling = false; } else { resampling = true; } //===== resample input frame ===== if( ! bFinished ) { resampleFrame( cFrame, cDownConvert, cRP, resamplingMethod, resamplingMode, resampling, upsampling, inputFrame != 0 ); } } //===== write output frame ===== if( ! bFinished ) { Bool bWriteTwoFrames = ( numOutputFrames == 2 && ( maxNumOutputFrames == 0 || writtenFrames + 1 < maxNumOutputFrames ) ); writeFrame( cFrame, outputFile, cRP.m_iFrameWidth, cRP.m_iFrameHeight, bWriteTwoFrames ); writtenFrames += ( bWriteTwoFrames ? 2 : 1 ); bFinished = ( maxNumOutputFrames != 0 && writtenFrames == maxNumOutputFrames ); fprintf( stderr, "\r%6d frames converted", writtenFrames ); } } long endTime = clock(); deleteFrame( cFrame ); fclose ( inputFile ); fclose ( outputFile ); if( croppingParametersFile ) { fclose ( croppingParametersFile ); } fprintf( stderr, "\n" ); double deltaInSecond = (double)( endTime - startTime) / (double)CLOCKS_PER_SEC; fprintf( stderr, "in %.2lf seconds => %.0lf ms/frame\n", deltaInSecond, deltaInSecond / (double)writtenFrames * 1000.0 ); if( writtenFrames < maxNumOutputFrames ) { fprintf( stderr, "\nNOTE: less output frames generated than specified!!!\n\n" ); } return 0; }
40.972136
202
0.610737
mdasari823