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
109
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
48.5k
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
143b6b698831ee4bf8d154e9568860a5354cbb5c
2,764
cc
C++
shared/ortcustomops.cc
vvchernov/onnxruntime-extensions
cc858e831b719d31e4f34ee9adb391105b4ce26b
[ "MIT" ]
59
2021-04-29T07:39:42.000Z
2022-03-29T21:12:05.000Z
shared/ortcustomops.cc
vvchernov/onnxruntime-extensions
cc858e831b719d31e4f34ee9adb391105b4ce26b
[ "MIT" ]
45
2021-05-12T08:32:58.000Z
2022-03-29T21:11:59.000Z
shared/ortcustomops.cc
vvchernov/onnxruntime-extensions
cc858e831b719d31e4f34ee9adb391105b4ce26b
[ "MIT" ]
18
2021-05-10T10:15:46.000Z
2022-03-22T10:46:36.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include <set> #include "onnxruntime_extensions.h" #include "ocos.h" class ExternalCustomOps { public: ExternalCustomOps() { } static ExternalCustomOps& instance() { static ExternalCustomOps g_instance; return g_instance; } void Add(const OrtCustomOp* c_op) { op_array_.push_back(c_op); } const OrtCustomOp* GetNextOp(size_t& idx) { if (idx >= op_array_.size()) { return nullptr; } return op_array_[idx++]; } ExternalCustomOps(ExternalCustomOps const&) = delete; void operator=(ExternalCustomOps const&) = delete; private: std::vector<const OrtCustomOp*> op_array_; }; extern "C" bool ORT_API_CALL AddExternalCustomOp(const OrtCustomOp* c_op) { ExternalCustomOps::instance().Add(c_op); return true; } extern "C" OrtStatus* ORT_API_CALL RegisterCustomOps(OrtSessionOptions* options, const OrtApiBase* api) { OrtCustomOpDomain* domain = nullptr; const OrtApi* ortApi = api->GetApi(ORT_API_VERSION); std::set<std::string> pyop_nameset; OrtStatus* status = nullptr; #if defined(PYTHON_OP_SUPPORT) if (status = RegisterPythonDomainAndOps(options, ortApi)){ return status; } #endif // PYTHON_OP_SUPPORT if (status = ortApi->CreateCustomOpDomain(c_OpDomain, &domain)) { return status; } #if defined(PYTHON_OP_SUPPORT) size_t count = 0; const OrtCustomOp* c_ops = FetchPyCustomOps(count); while (c_ops != nullptr) { if (status = ortApi->CustomOpDomain_Add(domain, c_ops)) { return status; } else { pyop_nameset.emplace(c_ops->GetName(c_ops)); } ++count; c_ops = FetchPyCustomOps(count); } #endif static std::vector<FxLoadCustomOpFactory> c_factories = { LoadCustomOpClasses<CustomOpClassBegin> #if defined(ENABLE_TF_STRING) , LoadCustomOpClasses_Text #endif // ENABLE_TF_STRING #if defined(ENABLE_MATH) , LoadCustomOpClasses_Math #endif #if defined(ENABLE_TOKENIZER) , LoadCustomOpClasses_Tokenizer #endif }; for (auto fx : c_factories) { auto ops = fx(); while (*ops != nullptr) { if (pyop_nameset.find((*ops)->GetName(*ops)) == pyop_nameset.end()) { if (status = ortApi->CustomOpDomain_Add(domain, *ops)) { return status; } } ++ops; } } size_t idx = 0; const OrtCustomOp* e_ops = ExternalCustomOps::instance().GetNextOp(idx); while (e_ops != nullptr) { if (pyop_nameset.find(e_ops->GetName(e_ops)) == pyop_nameset.end()) { if (status = ortApi->CustomOpDomain_Add(domain, e_ops)) { return status; } e_ops = ExternalCustomOps::instance().GetNextOp(idx); } } return ortApi->AddCustomOpDomain(options, domain); }
24.678571
105
0.686686
vvchernov
143ca63aa83dc435341cc33e07f47564e0b7c809
8,593
cpp
C++
viceplugins/retrojsvice/src/vice_plugin_api.cpp
hackyannick/browservice
10022849a15683e0f72a14aaee475b8daf13dbb1
[ "MIT" ]
null
null
null
viceplugins/retrojsvice/src/vice_plugin_api.cpp
hackyannick/browservice
10022849a15683e0f72a14aaee475b8daf13dbb1
[ "MIT" ]
null
null
null
viceplugins/retrojsvice/src/vice_plugin_api.cpp
hackyannick/browservice
10022849a15683e0f72a14aaee475b8daf13dbb1
[ "MIT" ]
null
null
null
#include "context.hpp" #include "../../../vice_plugin_api.h" namespace { using namespace retrojsvice; const char* RetrojsviceVersion = "0.9.2.1"; template <typename T> class GlobalCallback { private: struct Inner { T callback; void* data; void (*destructorCallback)(void* data); Inner( T callback, void* data, void (*destructorCallback)(void* data) ) : callback(callback), data(data), destructorCallback(destructorCallback) {} DISABLE_COPY_MOVE(Inner); ~Inner() { if(destructorCallback != nullptr) { destructorCallback(data); } } }; shared_ptr<Inner> inner_; public: template <typename... Arg> GlobalCallback(Arg... arg) : inner_(make_shared<Inner>(arg...)) {} template <typename... Arg> void operator()(Arg... arg) const { inner_->callback(inner_->data, arg...); } }; void setOutString(char** out, string val) { if(out != nullptr) { *out = createMallocString(val); } } #define API_EXPORT __attribute__((visibility("default"))) #define API_FUNC_START \ try { #define API_FUNC_END \ } catch(const exception& e) { \ PANIC("Unhandled exception traversing the vice plugin API: ", e.what()); \ abort(); \ } catch(...) { \ PANIC("Unhandled exception traversing the vice plugin API"); \ abort(); \ } } extern "C" { struct VicePluginAPI_Context { shared_ptr<Context> impl; }; API_EXPORT int vicePluginAPI_isAPIVersionSupported(uint64_t apiVersion) { API_FUNC_START return (int)(apiVersion == (uint64_t)1000000); API_FUNC_END } API_EXPORT char* vicePluginAPI_getVersionString() { API_FUNC_START return createMallocString(string("Retrojsvice ") + RetrojsviceVersion); API_FUNC_END } API_EXPORT VicePluginAPI_Context* vicePluginAPI_initContext( uint64_t apiVersion, const char** optionNames, const char** optionValues, size_t optionCount, const char* programName, char** initErrorMsgOut ) { API_FUNC_START REQUIRE(apiVersion == (uint64_t)1000000); REQUIRE(programName != nullptr); vector<pair<string, string>> options; for(size_t i = 0; i < optionCount; ++i) { REQUIRE(optionNames != nullptr); REQUIRE(optionValues != nullptr); REQUIRE(optionNames[i] != nullptr); REQUIRE(optionValues[i] != nullptr); options.emplace_back(optionNames[i], optionValues[i]); } variant<shared_ptr<Context>, string> result = Context::init(options, programName); shared_ptr<Context> impl; if(shared_ptr<Context>* implPtr = get_if<shared_ptr<Context>>(&result)) { impl = *implPtr; } else { string msg = get<string>(result); setOutString(initErrorMsgOut, msg); return nullptr; } VicePluginAPI_Context* ctx = new VicePluginAPI_Context; ctx->impl = impl; return ctx; API_FUNC_END } API_EXPORT void vicePluginAPI_destroyContext(VicePluginAPI_Context* ctx) { API_FUNC_START REQUIRE(ctx != nullptr); delete ctx; API_FUNC_END } // Convenience macro for creating implementations of API functions that forward // their arguments to corresponding member functions of the Context #define WRAP_CTX_API(funcName, ...) \ { \ API_FUNC_START \ REQUIRE(ctx != nullptr); \ return ctx->impl->funcName(__VA_ARGS__); \ API_FUNC_END \ } API_EXPORT void vicePluginAPI_start( VicePluginAPI_Context* ctx, VicePluginAPI_Callbacks callbacks, void* callbackData ) WRAP_CTX_API(start, callbacks, callbackData) API_EXPORT void vicePluginAPI_shutdown(VicePluginAPI_Context* ctx) WRAP_CTX_API(shutdown) API_EXPORT void vicePluginAPI_pumpEvents(VicePluginAPI_Context* ctx) WRAP_CTX_API(pumpEvents) API_EXPORT int vicePluginAPI_createPopupWindow( VicePluginAPI_Context* ctx, uint64_t parentWindow, uint64_t popupWindow, char** msg ) WRAP_CTX_API(createPopupWindow, parentWindow, popupWindow, msg) API_EXPORT void vicePluginAPI_closeWindow( VicePluginAPI_Context* ctx, uint64_t window ) WRAP_CTX_API(closeWindow, window) API_EXPORT void vicePluginAPI_notifyWindowViewChanged( VicePluginAPI_Context* ctx, uint64_t window ) WRAP_CTX_API(notifyWindowViewChanged, window) API_EXPORT void vicePluginAPI_setWindowCursor( VicePluginAPI_Context* ctx, uint64_t window, VicePluginAPI_MouseCursor cursor ) WRAP_CTX_API(setWindowCursor, window, cursor) API_EXPORT int vicePluginAPI_windowQualitySelectorQuery( VicePluginAPI_Context* ctx, uint64_t window, char** qualityListOut, size_t* currentQualityOut ) WRAP_CTX_API( windowQualitySelectorQuery, window, qualityListOut, currentQualityOut ) API_EXPORT void vicePluginAPI_windowQualityChanged( VicePluginAPI_Context* ctx, uint64_t window, size_t qualityIdx ) WRAP_CTX_API(windowQualityChanged, window, qualityIdx) API_EXPORT int vicePluginAPI_windowNeedsClipboardButtonQuery( VicePluginAPI_Context* ctx, uint64_t window ) WRAP_CTX_API(windowNeedsClipboardButtonQuery, window) API_EXPORT void vicePluginAPI_windowClipboardButtonPressed( VicePluginAPI_Context* ctx, uint64_t window ) WRAP_CTX_API(windowClipboardButtonPressed, window) API_EXPORT void vicePluginAPI_putClipboardContent( VicePluginAPI_Context* ctx, const char* text ) WRAP_CTX_API(putClipboardContent, text) API_EXPORT void vicePluginAPI_putFileDownload( VicePluginAPI_Context* ctx, uint64_t window, const char* name, const char* path, void (*cleanup)(void*), void* cleanupData ) WRAP_CTX_API(putFileDownload, window, name, path, cleanup, cleanupData) API_EXPORT int vicePluginAPI_startFileUpload( VicePluginAPI_Context* ctx, uint64_t window ) WRAP_CTX_API(startFileUpload, window) API_EXPORT void vicePluginAPI_cancelFileUpload( VicePluginAPI_Context* ctx, uint64_t window ) WRAP_CTX_API(cancelFileUpload, window) API_EXPORT void vicePluginAPI_getOptionDocs( uint64_t apiVersion, void (*callback)( void* data, const char* name, const char* valSpec, const char* desc, const char* defaultValStr ), void* data ) { API_FUNC_START REQUIRE(apiVersion == (uint64_t)1000000); REQUIRE(callback != nullptr); vector<tuple<string, string, string, string>> docs = Context::getOptionDocs(); for(const tuple<string, string, string, string>& doc : docs) { string name, valSpec, desc, defaultValStr; tie(name, valSpec, desc, defaultValStr) = doc; callback( data, name.c_str(), valSpec.c_str(), desc.c_str(), defaultValStr.c_str() ); } API_FUNC_END } API_EXPORT void vicePluginAPI_setGlobalLogCallback( uint64_t apiVersion, void (*callback)( void* data, VicePluginAPI_LogLevel logLevel, const char* location, const char* msg ), void* data, void (*destructorCallback)(void* data) ) { API_FUNC_START REQUIRE(apiVersion == (uint64_t)1000000); if(callback == nullptr) { setLogCallback({}); } else { GlobalCallback<decltype(callback)> func( callback, data, destructorCallback ); setLogCallback( [func]( LogLevel logLevel, const char* location, const char* msg ) { VicePluginAPI_LogLevel apiLogLevel; if(logLevel == LogLevel::Error) { apiLogLevel = VICE_PLUGIN_API_LOG_LEVEL_ERROR; } else if(logLevel == LogLevel::Warning) { apiLogLevel = VICE_PLUGIN_API_LOG_LEVEL_WARNING; } else { REQUIRE(logLevel == LogLevel::Info); apiLogLevel = VICE_PLUGIN_API_LOG_LEVEL_INFO; } func(apiLogLevel, location, msg); } ); } API_FUNC_END } API_EXPORT void vicePluginAPI_setGlobalPanicCallback( uint64_t apiVersion, void (*callback)(void* data, const char* location, const char* msg), void* data, void (*destructorCallback)(void* data) ) { API_FUNC_START REQUIRE(apiVersion == (uint64_t)1000000); if(callback == nullptr) { setPanicCallback({}); } else { setPanicCallback( GlobalCallback<decltype(callback)>(callback, data, destructorCallback) ); } API_FUNC_END } }
24.481481
82
0.669615
hackyannick
143d80b09390681feecdc7626536dd75e5a15255
888
cpp
C++
libs/renderer/src/renderer/state/ffp/lighting/light/scoped.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/renderer/src/renderer/state/ffp/lighting/light/scoped.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/renderer/src/renderer/state/ffp/lighting/light/scoped.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <sge/renderer/context/ffp.hpp> #include <sge/renderer/context/ffp_ref.hpp> #include <sge/renderer/state/ffp/lighting/light/const_object_ref_vector.hpp> #include <sge/renderer/state/ffp/lighting/light/scoped.hpp> sge::renderer::state::ffp::lighting::light::scoped::scoped( sge::renderer::context::ffp_ref const _context, sge::renderer::state::ffp::lighting::light::const_object_ref_vector const &_states) : context_(_context) { context_.get().lights_state(_states); } sge::renderer::state::ffp::lighting::light::scoped::~scoped() { context_.get().lights_state( sge::renderer::state::ffp::lighting::light::const_object_ref_vector()); }
37
87
0.726351
cpreh
1444e3d97396e6cdfa54f9f2bc84a35e5748a8af
753
hpp
C++
include/RED4ext/Types/generated/AI/ArgumentSerializableValue.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
1
2021-02-01T23:07:50.000Z
2021-02-01T23:07:50.000Z
include/RED4ext/Types/generated/AI/ArgumentSerializableValue.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
include/RED4ext/Types/generated/AI/ArgumentSerializableValue.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/REDhash.hpp> #include <RED4ext/Handle.hpp> #include <RED4ext/Types/generated/AI/ArgumentDefinition.hpp> #include <RED4ext/Types/generated/AI/ArgumentType.hpp> namespace RED4ext { struct ISerializable; namespace AI { struct ArgumentSerializableValue : AI::ArgumentDefinition { static constexpr const char* NAME = "AIArgumentSerializableValue"; static constexpr const char* ALIAS = NAME; Handle<ISerializable> defaultValue; // 48 AI::ArgumentType type; // 58 uint8_t unk5C[0x60 - 0x5C]; // 5C }; RED4EXT_ASSERT_SIZE(ArgumentSerializableValue, 0x60); } // namespace AI } // namespace RED4ext
25.965517
70
0.756972
Cyberpunk-Extended-Development-Team
144a15106536480fac3c3a2f7bd5bca269c4dd10
3,760
hpp
C++
include/np/ndarray/static/NDArrayStaticIndexImpl.hpp
mgorshkov/np
75c7adff38e7260371135839b547d5340f3ca367
[ "MIT" ]
null
null
null
include/np/ndarray/static/NDArrayStaticIndexImpl.hpp
mgorshkov/np
75c7adff38e7260371135839b547d5340f3ca367
[ "MIT" ]
null
null
null
include/np/ndarray/static/NDArrayStaticIndexImpl.hpp
mgorshkov/np
75c7adff38e7260371135839b547d5340f3ca367
[ "MIT" ]
null
null
null
/* C++ numpy-like template-based array implementation Copyright (c) 2022 Mikhail Gorshkov (mikhail.gorshkov@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. */ #pragma once #include <np/ndarray/static/NDArrayStaticDecl.hpp> namespace np::ndarray::array_static { // Subsetting template<typename DType, Size SizeT, Size... SizeTs> inline void set(NDArrayStatic<DType, SizeT, SizeTs...>& array, Size i, const typename NDArrayStatic<DType, SizeT, SizeTs...>::ReducedType& data) { array.m_ArrayImpl.set(i, data.m_ArrayImpl); } // Select an element at an index // a[2] template<typename DType, Size SizeT, Size... SizeTs> inline typename NDArrayStatic<DType, SizeT, SizeTs...>::ReducedType NDArrayStatic<DType, SizeT, SizeTs...>::operator[](Size i) const { return ReducedType{m_ArrayImpl[i]}; } // a[1,2] Select the element at row and column (same as a[1][2]) // Slicing // a[0:2] Select items at index 0 and 1 // b[0:2,1] Select items at rows 0 and 1 in column 1 // b[:1] Select all items at row 0 (equivalent to b[0:1,:]) // c[1,...] Same as [1,:,:] // a[::-1] Reversed array // Boolean indexing // a[a < 2] Select elements from a less than 2 // Fancy indexing // b[[1, 0, 1, 0], [0, 1, 2, 0]] Select elements (1,0),(0,1),(1,2) and (0,0) // b[[1, 0, 1, 0]][: ,[0, 1, 2, 0]] Select a subset of the matrix’s rows and columns /* TODO template <typename DType, Size SizeT, Size... SizeTs> inline ReducedType& NDArrayStatic<DType, SizeT, SizeTs...>::operator [] (const std::string& i) { return ReducedType{m_ArrayImpl[i]}; } template <typename DType, Size SizeT, Size... SizeTs> inline ReducedType NDArrayStatic<DType, SizeT, SizeTs...>::operator [] (const std::string& i) const { return ReducedType{m_ArrayImpl[i]}; } */ template<typename DType, Size SizeT, Size... SizeTs> inline typename NDArrayStatic<DType, SizeT, SizeTs...>::ReducedType NDArrayStatic<DType, SizeT, SizeTs...>::at(Size i) const { return ReducedType(m_ArrayImpl[i]); } /* TODO template <typename DType, Size SizeT, Size... SizeTs> inline ReducedType& NDArrayStatic<DType, SizeT, SizeTs...>::at(const std::string& i) { return ReducedType{m_ArrayImpl[i]}; } template <typename DType, Size SizeT, Size... SizeTs> inline ReducedType NDArrayStatic<DType, SizeT, SizeTs...>::at(const std::string& i) const { return ReducedType{m_ArrayImpl[i]}; } */ }
41.777778
138
0.645213
mgorshkov
144c4dcff9515405e869ec9fd60e94b33c61d40b
5,771
hpp
C++
Engine/UserInterface/UICommon.hpp
achen889/Warlockery_Engine
160a14e85009057f4505ff5380a8c17258698f3e
[ "MIT" ]
null
null
null
Engine/UserInterface/UICommon.hpp
achen889/Warlockery_Engine
160a14e85009057f4505ff5380a8c17258698f3e
[ "MIT" ]
null
null
null
Engine/UserInterface/UICommon.hpp
achen889/Warlockery_Engine
160a14e85009057f4505ff5380a8c17258698f3e
[ "MIT" ]
null
null
null
//============================================================================================================== //UserInterfaceCommon.hpp //by Albert Chen Apr-18-2016. //============================================================================================================== #pragma once #ifndef _included_UserInterfaceCommon__ #define _included_UserInterfaceCommon__ #include "Engine/Math/Vector2.hpp" #include "Engine/Renderer/OpenGLRenderer.hpp" #include "Engine/Input//InputCommon.hpp" #include "Engine/Core/Clock.hpp" //=========================================================================================================== extern Clock* g_UIClock; void AllocUIClock(); double GetUIDeltaSeconds(); //=========================================================================================================== ///---------------------------------------------------------------------------------------------------------- ///UI constants //anchor points static const Vector2 UI_SCREEN_SIZE = Vector2(1600, 900); static const Vector2 UI_ANCHOR_SCREEN_CENTER = UI_SCREEN_SIZE * 0.5f; static const Vector2 UI_ANCHOR_SCREEN_LEFT_CENTER = Vector2(0.0f, UI_SCREEN_SIZE.y * 0.5f); static const Vector2 UI_ANCHOR_SCREEN_RIGHT_CENTER = Vector2(UI_SCREEN_SIZE.x * 0.5f, UI_SCREEN_SIZE.y * 0.5f); static const Vector2 UI_ANCHOR_SCREEN_TOP_CENTER = Vector2(UI_SCREEN_SIZE.x * 0.5f, UI_SCREEN_SIZE.y); static const Vector2 UI_ANCHOR_SCREEN_BOTTOM_CENTER = Vector2(UI_SCREEN_SIZE.x * 0.5f, 0.0f); static const Vector2 UI_ANCHOR_SCREEN_TOP_LEFT = Vector2(0.0f, UI_SCREEN_SIZE.y); static const Vector2 UI_ANCHOR_SCREEN_TOP_RIGHT = Vector2(UI_SCREEN_SIZE.x, UI_SCREEN_SIZE.y); static const Vector2 UI_ANCHOR_SCREEN_BOTTOM_LEFT = Vector2(0.0f, 0.0f); static const Vector2 UI_ANCHOR_SCREEN_BOTTOM_RIGHT = Vector2(UI_SCREEN_SIZE.x, 0.0f); //=========================================================================================================== enum UIAnchorID { UI_ANCHOR_CENTER, UI_ANCHOR_LEFT_CENTER, UI_ANCHOR_RIGHT_CENTER, UI_ANCHOR_TOP_CENTER, UI_ANCHOR_BOTTOM_CENTER, UI_ANCHOR_TOP_LEFT, UI_ANCHOR_TOP_RIGHT, UI_ANCHOR_BOTTOM_LEFT, UI_ANCHOR_BOTTOM_RIGHT, NUM_UI_ANCHORS, UI_ANCHOR_INVALID }; ///---------------------------------------------------------------------------------------------------------- ///global helpers const Vector2 GetUIAnchorForScreen(const UIAnchorID& anchorEnum); const Vector2 GetPositionForUIAnchorInAABB2(const UIAnchorID&, const AABB2& anchorBounds); const UIAnchorID GetUIAnchorForString(const std::string& anchorString); ///---------------------------------------------------------------------------------------------------------- ///inline globals inline const Vector2 GetUIAnchorForScreen(const UIAnchorID& anchorEnum) { switch(anchorEnum){ case UI_ANCHOR_CENTER: return UI_ANCHOR_SCREEN_CENTER; case UI_ANCHOR_LEFT_CENTER: return UI_ANCHOR_SCREEN_LEFT_CENTER; case UI_ANCHOR_RIGHT_CENTER: return UI_ANCHOR_SCREEN_RIGHT_CENTER; case UI_ANCHOR_TOP_CENTER: return UI_ANCHOR_SCREEN_TOP_CENTER; case UI_ANCHOR_BOTTOM_CENTER: return UI_ANCHOR_SCREEN_BOTTOM_CENTER; case UI_ANCHOR_TOP_LEFT: return UI_ANCHOR_SCREEN_TOP_LEFT; case UI_ANCHOR_TOP_RIGHT: return UI_ANCHOR_SCREEN_TOP_RIGHT; case UI_ANCHOR_BOTTOM_LEFT: return UI_ANCHOR_SCREEN_BOTTOM_LEFT; case UI_ANCHOR_BOTTOM_RIGHT: return UI_ANCHOR_SCREEN_BOTTOM_RIGHT; } return Vector2::ZERO; } //----------------------------------------------------------------------------------------------------------- inline const Vector2 GetPositionForUIAnchorInAABB2(const UIAnchorID& anchorID , const AABB2& anchorBounds) { switch (anchorID) { case UI_ANCHOR_CENTER: return anchorBounds.GetPointAtNormalizedPositionWithinBox(Vector2(0.5f, 0.5f)); case UI_ANCHOR_LEFT_CENTER: return anchorBounds.GetPointAtNormalizedPositionWithinBox(Vector2(0.0f, 0.5f)); case UI_ANCHOR_RIGHT_CENTER: return anchorBounds.GetPointAtNormalizedPositionWithinBox(Vector2(1.0f, 0.5f)); case UI_ANCHOR_TOP_CENTER: return anchorBounds.GetPointAtNormalizedPositionWithinBox(Vector2(0.5f, 1.0f)); case UI_ANCHOR_BOTTOM_CENTER: return anchorBounds.GetPointAtNormalizedPositionWithinBox(Vector2(0.5f, 0.0f)); case UI_ANCHOR_TOP_LEFT: return anchorBounds.GetPointAtNormalizedPositionWithinBox(Vector2(0.0f, 1.0f)); case UI_ANCHOR_TOP_RIGHT: return anchorBounds.GetPointAtNormalizedPositionWithinBox(Vector2(1.0f, 1.0f)); case UI_ANCHOR_BOTTOM_LEFT: return anchorBounds.GetPointAtNormalizedPositionWithinBox(Vector2(0.0f, 0.0f)); case UI_ANCHOR_BOTTOM_RIGHT: return anchorBounds.GetPointAtNormalizedPositionWithinBox(Vector2(1.0f, 0.0f)); } return Vector2::ZERO; } //----------------------------------------------------------------------------------------------------------- inline const UIAnchorID GetUIAnchorForString(const std::string& anchorString){ if (anchorString == "center") { return UI_ANCHOR_CENTER; } else if (anchorString == "left center") { return UI_ANCHOR_LEFT_CENTER; } else if (anchorString == "right center") { return UI_ANCHOR_RIGHT_CENTER; } else if (anchorString == "top center") { return UI_ANCHOR_TOP_CENTER; } else if (anchorString == "bottom center") { return UI_ANCHOR_BOTTOM_CENTER; } else if (anchorString == "top left") { return UI_ANCHOR_TOP_LEFT; } else if (anchorString == "top right") { return UI_ANCHOR_TOP_RIGHT; } else if (anchorString == "bottom left") { return UI_ANCHOR_BOTTOM_LEFT; } else if (anchorString == "bottom right") { return UI_ANCHOR_BOTTOM_RIGHT; } return UI_ANCHOR_INVALID; } //=========================================================================================================== #endif //__includedUserInterfaceCommon__
34.556886
112
0.634032
achen889
144ed7f11ac26f0182a4b081598643bb3c088ece
18,652
cc
C++
src/swig_siqadconn/siqadconn.cc
samuelngsh/qpuanneal-sidb
ba0341a0ba852241de7c9a4e45f6a0a252bc48b4
[ "Apache-2.0" ]
null
null
null
src/swig_siqadconn/siqadconn.cc
samuelngsh/qpuanneal-sidb
ba0341a0ba852241de7c9a4e45f6a0a252bc48b4
[ "Apache-2.0" ]
null
null
null
src/swig_siqadconn/siqadconn.cc
samuelngsh/qpuanneal-sidb
ba0341a0ba852241de7c9a4e45f6a0a252bc48b4
[ "Apache-2.0" ]
null
null
null
// @file: siqadconn.cc // @author: Samuel // @created: 2017.08.23 // @editted: 2019.01.23 - Nathan // @license: Apache License 2.0 // // @desc: Convenient functions for interacting with SiQAD #include "siqadconn.h" #include <iostream> #include <stdexcept> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> using namespace phys; //CONSTRUCTOR SiQADConnector::SiQADConnector(const std::string &eng_name, const std::string &input_path, const std::string &output_path) : eng_name(eng_name), input_path(input_path), output_path(output_path) { // initialize variables item_tree = std::make_shared<Aggregate>(); start_time = std::chrono::system_clock::now(); elec_col = new ElectrodeCollection(item_tree); elec_poly_col = new ElectrodePolyCollection(item_tree); db_col = new DBCollection(item_tree); // read problem from input_path readProblem(input_path); } void SiQADConnector::setExport(std::string type, std::vector< std::pair< std::string, std::string > > &data_in) { if (type == "db_loc") dbl_data = data_in; else throw std::invalid_argument(std::string("No candidate for export type '") + type + std::string("' with class std::vector<std::pair<std::string, std::string>>")); } void SiQADConnector::setExport(std::string type, std::vector< std::vector< std::string > > &data_in) { if (type == "potential") pot_data = data_in; else if (type == "electrodes") elec_data = data_in; else if (type == "db_pot") db_pot_data = data_in; else if (type == "db_charge") db_charge_data = data_in; else throw std::invalid_argument(std::string("No candidate for export type '") + type + std::string("' with class std::vector<std::vector<std::string>>")); } // FILE HANDLING // parse problem XML, return true if successful void SiQADConnector::readProblem(const std::string &path) { std::cout << "Reading problem file: " << input_path << std::endl; bpt::ptree tree; // create empty property tree object bpt::read_xml(path, tree, bpt::xml_parser::no_comments); // parse the input file into property tree // parse XML // read program properties // TODO read program node // read simulation parameters std::cout << "Read simulation parameters" << std::endl; readSimulationParam(tree.get_child("siqad.sim_params")); // read layer properties std::cout << "Read layer properties" << std::endl; readLayers(tree.get_child("siqad.layers")); // read items std::cout << "Read items tree" << std::endl; readDesign(tree.get_child("siqad.design"), item_tree); } void SiQADConnector::readProgramProp(const bpt::ptree &program_prop_tree) { for (bpt::ptree::value_type const &v : program_prop_tree) { program_props.insert(std::map<std::string, std::string>::value_type(v.first, v.second.data())); std::cout << "ProgramProp: Key=" << v.first << ", Value=" << program_props[v.first] << std::endl; } } void SiQADConnector::readLayers(const bpt::ptree &layer_prop_tree) { // if this were structured the same way as readDesign, then only the first layer_prop subtree would be read. // TODO: make this more general. for (bpt::ptree::value_type const &v : layer_prop_tree) readLayerProp(v.second); } void SiQADConnector::readLayerProp(const bpt::ptree &layer_node) { Layer lay; lay.name = layer_node.get<std::string>("name"); lay.type = layer_node.get<std::string>("type"); lay.zoffset = layer_node.get<float>("zoffset"); lay.zheight = layer_node.get<float>("zheight"); layers.push_back(lay); std::cout << "Retrieved layer " << lay.name << " of type " << lay.type << std::endl; } void SiQADConnector::readSimulationParam(const bpt::ptree &sim_params_tree) { for (bpt::ptree::value_type const &v : sim_params_tree) { sim_params.insert(std::map<std::string, std::string>::value_type(v.first, v.second.data())); std::cout << "SimParam: Key=" << v.first << ", Value=" << sim_params[v.first] << std::endl; } } void SiQADConnector::readDesign(const bpt::ptree &subtree, const std::shared_ptr<Aggregate> &agg_parent) { std::cout << "Beginning to read design" << std::endl; for (bpt::ptree::value_type const &layer_tree : subtree) { std::string layer_type = layer_tree.second.get<std::string>("<xmlattr>.type"); if ((!layer_type.compare("DB"))) { std::cout << "Encountered node " << layer_tree.first << " with type " << layer_type << ", entering" << std::endl; readItemTree(layer_tree.second, agg_parent); } else if ( (!layer_type.compare("Electrode"))) { std::cout << "Encountered node " << layer_tree.first << " with type " << layer_type << ", entering" << std::endl; readItemTree(layer_tree.second, agg_parent); } else { std::cout << "Encountered node " << layer_tree.first << " with type " << layer_type << ", no defined action for this layer. Skipping." << std::endl; } } } void SiQADConnector::readItemTree(const bpt::ptree &subtree, const std::shared_ptr<Aggregate> &agg_parent) { for (bpt::ptree::value_type const &item_tree : subtree) { std::string item_name = item_tree.first; std::cout << "item_name: " << item_name << std::endl; if (!item_name.compare("aggregate")) { // add aggregate child to tree agg_parent->aggs.push_back(std::make_shared<Aggregate>()); readItemTree(item_tree.second, agg_parent->aggs.back()); } else if (!item_name.compare("dbdot")) { // add DBDot to tree readDBDot(item_tree.second, agg_parent); } else if (!item_name.compare("electrode")) { // add Electrode to tree readElectrode(item_tree.second, agg_parent); } else if (!item_name.compare("electrode_poly")) { // add Electrode to tree readElectrodePoly(item_tree.second, agg_parent); } else { std::cout << "Encountered unknown item node: " << item_tree.first << std::endl; } } } void SiQADConnector::readElectrode(const bpt::ptree &subtree, const std::shared_ptr<Aggregate> &agg_parent) { double x1, x2, y1, y2, pixel_per_angstrom, potential, phase, angle; int layer_id, electrode_type, net; // read values from XML stream layer_id = subtree.get<int>("layer_id"); angle = subtree.get<double>("angle"); potential = subtree.get<double>("property_map.potential.val"); phase = subtree.get<double>("property_map.phase.val"); std::string electrode_type_s = subtree.get<std::string>("property_map.type.val"); if (!electrode_type_s.compare("fixed")){ electrode_type = 0; } else if (!electrode_type_s.compare("clocked")) { electrode_type = 1; } net = subtree.get<int>("property_map.net.val"); pixel_per_angstrom = subtree.get<double>("pixel_per_angstrom"); x1 = subtree.get<double>("dim.<xmlattr>.x1"); x2 = subtree.get<double>("dim.<xmlattr>.x2"); y1 = subtree.get<double>("dim.<xmlattr>.y1"); y2 = subtree.get<double>("dim.<xmlattr>.y2"); agg_parent->elecs.push_back(std::make_shared<Electrode>(layer_id,x1,x2,y1,y2,potential,phase,electrode_type,pixel_per_angstrom,net,angle)); std::cout << "Electrode created with x1=" << agg_parent->elecs.back()->x1 << ", y1=" << agg_parent->elecs.back()->y1 << ", x2=" << agg_parent->elecs.back()->x2 << ", y2=" << agg_parent->elecs.back()->y2 << ", potential=" << agg_parent->elecs.back()->potential << std::endl; } void SiQADConnector::readElectrodePoly(const bpt::ptree &subtree, const std::shared_ptr<Aggregate> &agg_parent) { double pixel_per_angstrom, potential, phase; std::vector<std::pair<double, double>> vertices; int layer_id, electrode_type, net; // read values from XML stream layer_id = subtree.get<int>("layer_id"); potential = subtree.get<double>("property_map.potential.val"); phase = subtree.get<double>("property_map.phase.val"); std::string electrode_type_s = subtree.get<std::string>("property_map.type.val"); if (!electrode_type_s.compare("fixed")){ electrode_type = 0; } else if (!electrode_type_s.compare("clocked")) { electrode_type = 1; } pixel_per_angstrom = subtree.get<double>("pixel_per_angstrom"); net = subtree.get<int>("property_map.net.val"); //cycle through the vertices std::pair<double, double> point; for (auto val: subtree) { if(val.first == "vertex") { double x = std::stod(val.second.get_child("<xmlattr>.x").data()); double y = std::stod(val.second.get_child("<xmlattr>.y").data()); point = std::make_pair(x, y); vertices.push_back(point); } } agg_parent->elec_polys.push_back(std::make_shared<ElectrodePoly>(layer_id,vertices,potential,phase,electrode_type,pixel_per_angstrom,net)); std::cout << "ElectrodePoly created with " << agg_parent->elec_polys.back()->vertices.size() << " vertices, potential=" << agg_parent->elec_polys.back()->potential << std::endl; } void SiQADConnector::readDBDot(const bpt::ptree &subtree, const std::shared_ptr<Aggregate> &agg_parent) { float x, y; int n, m, l; // read x and y physical locations x = subtree.get<float>("physloc.<xmlattr>.x"); y = subtree.get<float>("physloc.<xmlattr>.y"); // read n, m and l lattice coordinates n = subtree.get<int>("latcoord.<xmlattr>.n"); m = subtree.get<int>("latcoord.<xmlattr>.m"); l = subtree.get<int>("latcoord.<xmlattr>.l"); agg_parent->dbs.push_back(std::make_shared<DBDot>(x, y, n, m, l)); std::cout << "DBDot created with x=" << agg_parent->dbs.back()->x << ", y=" << agg_parent->dbs.back()->y << ", n=" << agg_parent->dbs.back()->n << ", m=" << agg_parent->dbs.back()->m << ", l=" << agg_parent->dbs.back()->l << std::endl; } void SiQADConnector::writeResultsXml() { std::cout << "SiQADConnector::writeResultsXml()" << std::endl; boost::property_tree::ptree node_root; std::cout << "Write results to XML..." << std::endl; // eng_info node_root.add_child("eng_info", engInfoPropertyTree()); // sim_params node_root.add_child("sim_params", simParamsPropertyTree()); // DB locations if (!dbl_data.empty()) node_root.add_child("physloc", dbLocPropertyTree()); // DB electron distributions if(!db_charge_data.empty()) node_root.add_child("elec_dist", dbChargePropertyTree()); // electrode if (!elec_data.empty()) node_root.add_child("electrode", electrodePropertyTree()); //electric potentials if (!pot_data.empty()) node_root.add_child("potential_map", potentialPropertyTree()); //potentials at db locations if (!db_pot_data.empty()) node_root.add_child("dbdots", dbPotentialPropertyTree()); // write full tree to file boost::property_tree::ptree tree; tree.add_child("sim_out", node_root); boost::property_tree::write_xml(output_path, tree, std::locale(), boost::property_tree::xml_writer_make_settings<std::string>(' ',4)); std::cout << "Write to XML complete." << std::endl; } bpt::ptree SiQADConnector::engInfoPropertyTree() { boost::property_tree::ptree node_eng_info; node_eng_info.put("engine", eng_name); node_eng_info.put("version", "TBD"); // TODO real version node_eng_info.put("return_code", std::to_string(return_code).c_str()); //get timing information end_time = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end_time-start_time; std::time_t end = std::chrono::system_clock::to_time_t(end_time); char* end_c_str = std::ctime(&end); *std::remove(end_c_str, end_c_str+strlen(end_c_str), '\n') = '\0'; // removes _all_ new lines from the cstr node_eng_info.put("timestamp", end_c_str); node_eng_info.put("time_elapsed_s", std::to_string(elapsed_seconds.count()).c_str()); return node_eng_info; } bpt::ptree SiQADConnector::simParamsPropertyTree() { bpt::ptree node_sim_params; for (std::pair<std::string, std::string> param : sim_params) node_sim_params.put(param.first, param.second); return node_sim_params; } bpt::ptree SiQADConnector::dbLocPropertyTree() { bpt::ptree node_physloc; for (unsigned int i = 0; i < dbl_data.size(); i++){ bpt::ptree node_dbdot; node_dbdot.put("<xmlattr>.x", dbl_data[i].first.c_str()); node_dbdot.put("<xmlattr>.y", dbl_data[i].second.c_str()); node_physloc.add_child("dbdot", node_dbdot); } return node_physloc; } bpt::ptree SiQADConnector::dbChargePropertyTree() { bpt::ptree node_elec_dist; for (unsigned int i = 0; i < db_charge_data.size(); i++){ bpt::ptree node_dist; node_dist.put("", db_charge_data[i][0]); node_dist.put("<xmlattr>.energy", db_charge_data[i][1]); node_dist.put("<xmlattr>.count", db_charge_data[i][2]); node_elec_dist.add_child("dist", node_dist); } return node_elec_dist; } bpt::ptree SiQADConnector::electrodePropertyTree() { bpt::ptree node_electrode; for (unsigned int i = 0; i < elec_data.size(); i++){ boost::property_tree::ptree node_dim; node_dim.put("<xmlattr>.x1", elec_data[i][0].c_str()); node_dim.put("<xmlattr>.y1", elec_data[i][1].c_str()); node_dim.put("<xmlattr>.x2", elec_data[i][2].c_str()); node_dim.put("<xmlattr>.y2", elec_data[i][3].c_str()); node_electrode.add_child("dim", node_dim); boost::property_tree::ptree node_pot; node_pot.put("", elec_data[i][4].c_str()); node_electrode.add_child("potential", node_pot); } return node_electrode; } bpt::ptree SiQADConnector::potentialPropertyTree() { bpt::ptree node_potential_map; for (unsigned int i = 0; i < pot_data.size(); i++){ boost::property_tree::ptree node_potential_val; node_potential_val.put("<xmlattr>.x", pot_data[i][0].c_str()); node_potential_val.put("<xmlattr>.y", pot_data[i][1].c_str()); node_potential_val.put("<xmlattr>.val", pot_data[i][2].c_str()); node_potential_map.add_child("potential_val", node_potential_val); } return node_potential_map; } bpt::ptree SiQADConnector::dbPotentialPropertyTree() { bpt::ptree node_dbdots; for (unsigned int i = 0; i < db_pot_data.size(); i++){ bpt::ptree node_dbdot; bpt::ptree node_physloc; node_physloc.put("<xmlattr>.x", db_pot_data[i][0].c_str()); node_physloc.put("<xmlattr>.y", db_pot_data[i][1].c_str()); node_dbdot.add_child("physloc", node_physloc); boost::property_tree::ptree node_db_pot; node_db_pot.put("", db_pot_data[i][2].c_str()); node_dbdot.add_child("potential", node_db_pot); node_dbdots.add_child("dbdot", node_dbdot); } return node_dbdots; } //DB ITERATOR DBIterator::DBIterator(std::shared_ptr<Aggregate> root, bool begin) { if(begin){ // keep finding deeper aggregates until one that contains dbs is found while(root->dbs.empty() && !root->aggs.empty()) { push(root); root = root->aggs.front(); } push(root); } else{ db_iter = root->dbs.cend(); } } DBIterator& DBIterator::operator++() { // exhaust the current Aggregate DBs first if(db_iter != curr->dbs.cend()) return ++db_iter != curr->dbs.cend() ? *this : ++(*this); // if available, push the next aggregate onto the stack if(agg_stack.top().second != curr->aggs.cend()){ push(*agg_stack.top().second); return db_iter != curr->dbs.cend() ? *this : ++(*this); } // aggregate is complete, pop off stack pop(); return agg_stack.size() == 0 ? *this : ++(*this); } void DBIterator::push(std::shared_ptr<Aggregate> agg) { if(!agg_stack.empty()) ++agg_stack.top().second; agg_stack.push(std::make_pair(agg, agg->aggs.cbegin())); db_iter = agg->dbs.cbegin(); curr = agg; } void DBIterator::pop() { agg_stack.pop(); // pop complete aggregate off stack if(agg_stack.size() > 0){ curr = agg_stack.top().first; // update current to new top db_iter = curr->dbs.cend(); // don't reread dbs } } // ELEC ITERATOR ElecIterator::ElecIterator(std::shared_ptr<Aggregate> root, bool begin) { if(begin){ // keep finding deeper aggregates until one that contains dbs is found while(root->elecs.empty() && !root->aggs.empty()) { push(root); root = root->aggs.front(); } push(root); } else{ elec_iter = root->elecs.cend(); } } ElecIterator& ElecIterator::operator++() { // exhaust the current Aggregate DBs first if(elec_iter != curr->elecs.cend()) return ++elec_iter != curr->elecs.cend() ? *this : ++(*this); // if available, push the next aggregate onto the stack if(agg_stack.top().second != curr->aggs.cend()){ push(*agg_stack.top().second); return elec_iter != curr->elecs.cend() ? *this : ++(*this); } // aggregate is complete, pop off stack pop(); return agg_stack.size() == 0 ? *this : ++(*this); } void ElecIterator::push(std::shared_ptr<Aggregate> agg) { if(!agg_stack.empty()) ++agg_stack.top().second; agg_stack.push(std::make_pair(agg, agg->aggs.cbegin())); elec_iter = agg->elecs.cbegin(); curr = agg; } void ElecIterator::pop() { agg_stack.pop(); // pop complete aggregate off stack if(agg_stack.size() > 0){ curr = agg_stack.top().first; // update current to new top elec_iter = curr->elecs.cend(); // don't reread dbs } } // ELECPOLY ITERATOR ElecPolyIterator::ElecPolyIterator(std::shared_ptr<Aggregate> root, bool begin) { if(begin){ // keep finding deeper aggregates until one that contains dbs is found while(root->elec_polys.empty() && !root->aggs.empty()) { push(root); root = root->aggs.front(); } push(root); } else{ elec_poly_iter = root->elec_polys.cend(); } } ElecPolyIterator& ElecPolyIterator::operator++() { // exhaust the current Aggregate DBs first if(elec_poly_iter != curr->elec_polys.cend()) return ++elec_poly_iter != curr->elec_polys.cend() ? *this : ++(*this); // if available, push the next aggregate onto the stack if(agg_stack.top().second != curr->aggs.cend()){ push(*agg_stack.top().second); return elec_poly_iter != curr->elec_polys.cend() ? *this : ++(*this); } // aggregate is complete, pop off stack pop(); return agg_stack.size() == 0 ? *this : ++(*this); } void ElecPolyIterator::push(std::shared_ptr<Aggregate> agg) { if(!agg_stack.empty()) ++agg_stack.top().second; agg_stack.push(std::make_pair(agg, agg->aggs.cbegin())); elec_poly_iter = agg->elec_polys.cbegin(); curr = agg; } void ElecPolyIterator::pop() { agg_stack.pop(); // pop complete aggregate off stack if(agg_stack.size() > 0){ curr = agg_stack.top().first; // update current to new top elec_poly_iter = curr->elec_polys.cend(); // don't reread dbs } } // AGGREGATE int Aggregate::size() { int n_elecs=elecs.size(); if(!aggs.empty()) for(auto agg : aggs) n_elecs += agg->size(); return n_elecs; }
33.546763
154
0.670974
samuelngsh
1450fa120cf1fb191e79295c4e1457d208e06999
6,323
cpp
C++
src/aries/utility/Polygon.cpp
IAries/VEDO
8268005d381268cafcf7024ff38fef91c6318ef4
[ "BSD-3-Clause" ]
null
null
null
src/aries/utility/Polygon.cpp
IAries/VEDO
8268005d381268cafcf7024ff38fef91c6318ef4
[ "BSD-3-Clause" ]
null
null
null
src/aries/utility/Polygon.cpp
IAries/VEDO
8268005d381268cafcf7024ff38fef91c6318ef4
[ "BSD-3-Clause" ]
null
null
null
#include <aries/utility/Polygon.h> #include <cmath> #include <cstdlib> #include <iostream> #include <string> #include <vector> namespace aries { Polygon::Polygon() { } const Polygon& Polygon::operator = (const Polygon& p) { _Vertex = p._Vertex; _EdgeVertexSN = p._EdgeVertexSN; _FaceVertexSN = p._FaceVertexSN; ReBuildEdgeAndFace(); return *this; } Polygon::~Polygon() { } const Vector3df* Polygon::GetVertex(const _uint_t& u) const { if (u < (_uint_t)_Vertex.size()) { return &_Vertex[u]; } else { std::cout << "Caution!! Code: Vector3df aries::Polygon::GetVertex(const _uint_t&) const" << std::endl << " Condition: index error!!" << std::endl; std::exit(-1); } } void Polygon::AddVertex(const Vector3df& vPosition) { _Vertex.push_back(vPosition); } void Polygon::UpdateVertex(const _uint_t& polygon_sn, const Vector3df& position) { if (polygon_sn < (_uint_t)_Vertex.size()) { _Vertex[polygon_sn] = position; } else { std::cout << "Caution!! Code: void aries::Polygon::UpdateVertex(const _uint_t&, const Vector3df&)" << std::endl << " Condition: index error!!" << std::endl; std::exit(-1); } } std::pair<const Vector3df*, const Vector3df* > Polygon::GetEdge(const _uint_t& u) const { if (u < (_uint_t)_Edge.size()) { return _Edge[u]; } else { std::cout << "Caution!! Code: std::pair<const Vector3df*, const Vector3df* > aries::Polygon::GetEdge(const _uint_t&) const" << std::endl << " Condition: index error!!" << std::endl; std::exit(-1); } } std::pair<_uint_t, _uint_t> Polygon::GetEdgeVertexSN(const _uint_t& u) const { if (u < (_uint_t)_EdgeVertexSN.size()) { return _EdgeVertexSN[u]; } else { std::cout << "Caution!! std::pair<_uint_t, _uint_t> aries::Polygon::GetEdgeVertexSN(const _uint_t&) const" << std::endl << " Condition: index error!!" << std::endl; std::exit(-1); } } void Polygon::AddEdge(const _uint_t& ui, const _uint_t& uj) { if (std::max(ui, uj) < (_uint_t)_Vertex.size()) { _Edge.push_back(std::make_pair(&(_Vertex[ui]), &(_Vertex[uj]))); _EdgeVertexSN.push_back(std::make_pair(ui, uj)); } else { std::cout << "Caution!! void Polygon::AddEdge(const _uint_t&, const _uint_t&)" << std::endl << " Condition: index error!!" << std::endl; std::exit(-1); } } std::vector<const Vector3df* > Polygon::GetFace(const _uint_t& u) const { if (u < (_uint_t)_Face.size()) { return _Face[u]; } else { std::cout << "Caution!! Code: Vector3df* aries::Polygon::GetFace(const _uint_t&) const" << std::endl << " Condition: index error!!" << std::endl; std::exit(-1); } } const _uint_t* Polygon::GetFaceVertexSN(const _uint_t& u) const { if (u < (_uint_t)_FaceVertexSN.size()) { return &(_FaceVertexSN[u][0]); } else { std::cout << "Caution!! Code: const _uint_t* aries::Polygon::GetFaceVertexSN(const _uint_t&) const" << std::endl << " Condition: index error!!" << std::endl; std::exit(-1); } } void Polygon::AddFace(const _uint_t& ui, const _uint_t& uj, const _uint_t& uk) { if (std::max(std::max(ui, uj), uk) < (_uint_t)_Vertex.size()) { std::vector<const Vector3df* > SingleFace; SingleFace.push_back(&(_Vertex[ui])); SingleFace.push_back(&(_Vertex[uj])); SingleFace.push_back(&(_Vertex[uk])); _Face.push_back(SingleFace); std::vector<_uint_t> SingleFaceSN; SingleFaceSN.push_back(ui); SingleFaceSN.push_back(uj); SingleFaceSN.push_back(uk); _FaceVertexSN.push_back(SingleFaceSN); } else { std::cout << "Caution!! void Polygon::AddFace(const _uint_t&, const _uint_t&, const _uint_t&)" << std::endl << " Condition: index error!!" << std::endl; std::exit(-1); } } void Polygon::CoordinateTransformation(const Vector3df& LocalX, const Vector3df& LocalY, const Vector3df& LocalZ) { for (_uint_t u=0; u<(_uint_t)_Vertex.size(); u++) { _Vertex[u].CoordinateTransformation(LocalX, LocalY, LocalZ); } } void Polygon::CoordinateTransformation (const Vector3df& LocalX, const Vector3df& LocalY, const Vector3df& LocalZ, const Vector3df& Translation) { CoordinateTransformation(LocalX, LocalY, LocalZ); for (_uint_t u=0; u<(_uint_t)_Vertex.size(); u++) { _Vertex[u] += Translation; } } void Polygon::Clear() { _Vertex.clear(); _Edge.clear(); _EdgeVertexSN.clear(); _Face.clear(); _FaceVertexSN.clear(); } Polygon::Polygon(const Polygon& p) { *this = p; } void Polygon::ReBuildEdgeAndFace() { std::pair<_uint_t, _uint_t> uvsn; _Edge.clear(); for (_uint_t u=0; u<(_uint_t)_EdgeVertexSN.size(); u++) { uvsn = _EdgeVertexSN[u]; _Edge.push_back(std::make_pair(&(_Vertex[uvsn.first]), &(_Vertex[uvsn.second]))); } std::vector<const Vector3df* > SingleFace; std::vector<_uint_t> uvsnv; _Face.clear(); for (_uint_t u=0; u<(_uint_t)_FaceVertexSN.size(); u++) { uvsnv = _FaceVertexSN[u]; SingleFace.clear(); SingleFace.push_back(&(_Vertex[uvsnv[0]])); SingleFace.push_back(&(_Vertex[uvsnv[1]])); SingleFace.push_back(&(_Vertex[uvsnv[2]])); _Face.push_back(SingleFace); } } } // namespace aries std::ostream& operator << (std::ostream& os, const aries::Polygon& p) { aries::_uint_t VertexNumber = p.VertexNumber(); for (aries::_uint_t u=0; u<VertexNumber; u++) { os << "Vertex " << u << "/" << VertexNumber << ": " << *p.GetVertex(u); } aries::_uint_t EdgeNumber = p.EdgeNumber(); std::pair<aries::_uint_t, aries::_uint_t> uuev; for (aries::_uint_t u=0; u<EdgeNumber; u++) { uuev = p.GetEdgeVertexSN(u); os << "Edge " << u << "/" << EdgeNumber << ": Vertex " << uuev.first << "-" << uuev.second << std::endl; } aries::_uint_t FaceNumber = p.FaceNumber(); const aries::_uint_t* ufv; for (aries::_uint_t u=0; u<FaceNumber; u++) { ufv = p.GetFaceVertexSN(u); os << "Face " << u << "/" << FaceNumber << ": Vertex " << *ufv << "-" << *(ufv+1) << "-" << *(ufv+2) << std::endl; } return os; }
25.393574
148
0.603037
IAries
1451044b38ed0271bae68880cb6828154f585caf
3,193
cpp
C++
cpp/leetcode/57.insert-interval.cpp
Gerrard-YNWA/piece_of_code
ea8c9f05a453c893cc1f10e9b91d4393838670c1
[ "MIT" ]
1
2021-11-02T05:17:24.000Z
2021-11-02T05:17:24.000Z
cpp/leetcode/57.insert-interval.cpp
Gerrard-YNWA/code
546230593c33ff322d3205499fe17cd6a9a437c1
[ "MIT" ]
null
null
null
cpp/leetcode/57.insert-interval.cpp
Gerrard-YNWA/code
546230593c33ff322d3205499fe17cd6a9a437c1
[ "MIT" ]
null
null
null
/* * @lc app=leetcode id=57 lang=cpp * * [57] Insert Interval */ #include <iostream> #include <vector> using namespace std; // @lc code=start class Solution { public: vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) { vector<vector<int>> res; auto len = intervals.size(); auto start = 0; //前k个 for (int i = 0; i < len; i++) { if (intervals[i][1] < newInterval[0]) { start++; res.push_back(intervals[i]); } else { break; } } // 合并 for (int i = start; i < len; i++) { if (intervals[i][0] <= newInterval[1]) { newInterval[0] = min(newInterval[0], intervals[i][0]); newInterval[1] = max(newInterval[1], intervals[i][1]); start++; } else { break; } } res.push_back(newInterval); //后m个 for (int i = start; i < len; i++) { res.push_back(intervals[i]); } return res; } }; // @lc code=end // print helper void printVectorVector(vector<vector<int>>& vec) { cout << "["; for (auto it = vec.begin(); it != vec.end(); it++) { auto elem = *it; cout << "[" << elem[0] << ", " << elem[1] << "],"; } cout << "]" << endl; } int main() { Solution s; vector<vector<int>> intervals; vector<int> newInterval; intervals.push_back(vector<int>{1, 3}); intervals.push_back(vector<int>{6, 9}); newInterval.push_back(2); newInterval.push_back(5); auto v = s.insert(intervals, newInterval); printVectorVector(v); intervals.clear(); newInterval.clear(); intervals.push_back(vector<int>{1, 2}); intervals.push_back(vector<int>{3, 5}); intervals.push_back(vector<int>{6, 7}); intervals.push_back(vector<int>{8, 10}); intervals.push_back(vector<int>{12, 16}); newInterval.push_back(4); newInterval.push_back(8); v = s.insert(intervals, newInterval); printVectorVector(v); intervals.clear(); newInterval.clear(); newInterval.push_back(5); newInterval.push_back(7); v = s.insert(intervals, newInterval); printVectorVector(v); intervals.clear(); newInterval.clear(); intervals.push_back(vector<int>{1, 5}); newInterval.push_back(2); newInterval.push_back(3); v = s.insert(intervals, newInterval); printVectorVector(v); intervals.clear(); newInterval.clear(); intervals.push_back(vector<int>{1, 5}); newInterval.push_back(6); newInterval.push_back(8); v = s.insert(intervals, newInterval); printVectorVector(v); intervals.clear(); newInterval.clear(); intervals.push_back(vector<int>{1, 5}); newInterval.push_back(0); newInterval.push_back(3); v = s.insert(intervals, newInterval); printVectorVector(v); intervals.clear(); newInterval.clear(); intervals.push_back(vector<int>{1, 5}); newInterval.push_back(0); newInterval.push_back(0); v = s.insert(intervals, newInterval); printVectorVector(v); return 0; }
26.38843
90
0.57125
Gerrard-YNWA
145630173d390683f362c3890da6cdc56da711b8
17,862
cpp
C++
export/debug/windows/obj/src/openfl/display3D/textures/RectangleTexture.cpp
bobisdabbing/Vs-The-United-Lands-stable
0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5
[ "MIT" ]
1
2021-07-19T05:10:43.000Z
2021-07-19T05:10:43.000Z
export/debug/windows/obj/src/openfl/display3D/textures/RectangleTexture.cpp
bobisdabbing/Vs-The-United-Lands-stable
0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5
[ "MIT" ]
null
null
null
export/debug/windows/obj/src/openfl/display3D/textures/RectangleTexture.cpp
bobisdabbing/Vs-The-United-Lands-stable
0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5
[ "MIT" ]
null
null
null
// Generated by Haxe 4.1.5 #include <hxcpp.h> #ifndef INCLUDED_Std #include <Std.h> #endif #ifndef INCLUDED_haxe_Exception #include <haxe/Exception.h> #endif #ifndef INCLUDED_haxe_io_Bytes #include <haxe/io/Bytes.h> #endif #ifndef INCLUDED_lime__internal_backend_native_NativeOpenGLRenderContext #include <lime/_internal/backend/native/NativeOpenGLRenderContext.h> #endif #ifndef INCLUDED_lime_graphics_Image #include <lime/graphics/Image.h> #endif #ifndef INCLUDED_lime_graphics__WebGL2RenderContext_WebGL2RenderContext_Impl_ #include <lime/graphics/_WebGL2RenderContext/WebGL2RenderContext_Impl_.h> #endif #ifndef INCLUDED_lime_graphics_opengl_GLObject #include <lime/graphics/opengl/GLObject.h> #endif #ifndef INCLUDED_lime_utils_ArrayBufferView #include <lime/utils/ArrayBufferView.h> #endif #ifndef INCLUDED_lime_utils_BytePointerData #include <lime/utils/BytePointerData.h> #endif #ifndef INCLUDED_lime_utils_TAError #include <lime/utils/TAError.h> #endif #ifndef INCLUDED_lime_utils__BytePointer_BytePointer_Impl_ #include <lime/utils/_BytePointer/BytePointer_Impl_.h> #endif #ifndef INCLUDED_lime_utils__DataPointer_DataPointer_Impl_ #include <lime/utils/_DataPointer/DataPointer_Impl_.h> #endif #ifndef INCLUDED_openfl__Vector_IVector #include <openfl/_Vector/IVector.h> #endif #ifndef INCLUDED_openfl__Vector_IntVector #include <openfl/_Vector/IntVector.h> #endif #ifndef INCLUDED_openfl_display_BitmapData #include <openfl/display/BitmapData.h> #endif #ifndef INCLUDED_openfl_display_IBitmapDrawable #include <openfl/display/IBitmapDrawable.h> #endif #ifndef INCLUDED_openfl_display__internal_SamplerState #include <openfl/display/_internal/SamplerState.h> #endif #ifndef INCLUDED_openfl_display3D_Context3D #include <openfl/display3D/Context3D.h> #endif #ifndef INCLUDED_openfl_display3D_textures_RectangleTexture #include <openfl/display3D/textures/RectangleTexture.h> #endif #ifndef INCLUDED_openfl_display3D_textures_TextureBase #include <openfl/display3D/textures/TextureBase.h> #endif #ifndef INCLUDED_openfl_events_EventDispatcher #include <openfl/events/EventDispatcher.h> #endif #ifndef INCLUDED_openfl_events_IEventDispatcher #include <openfl/events/IEventDispatcher.h> #endif #ifndef INCLUDED_openfl_utils_ByteArrayData #include <openfl/utils/ByteArrayData.h> #endif #ifndef INCLUDED_openfl_utils_IDataInput #include <openfl/utils/IDataInput.h> #endif #ifndef INCLUDED_openfl_utils_IDataOutput #include <openfl/utils/IDataOutput.h> #endif #ifndef INCLUDED_openfl_utils__ByteArray_ByteArray_Impl_ #include <openfl/utils/_ByteArray/ByteArray_Impl_.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_574e9a3948a11606_28_new,"openfl.display3D.textures.RectangleTexture","new",0xcccbdd5b,"openfl.display3D.textures.RectangleTexture.new","openfl/display3D/textures/RectangleTexture.hx",28,0x83565556) HX_LOCAL_STACK_FRAME(_hx_pos_574e9a3948a11606_53_uploadFromBitmapData,"openfl.display3D.textures.RectangleTexture","uploadFromBitmapData",0x711b2e49,"openfl.display3D.textures.RectangleTexture.uploadFromBitmapData","openfl/display3D/textures/RectangleTexture.hx",53,0x83565556) HX_LOCAL_STACK_FRAME(_hx_pos_574e9a3948a11606_103_uploadFromByteArray,"openfl.display3D.textures.RectangleTexture","uploadFromByteArray",0xfd7a0ae1,"openfl.display3D.textures.RectangleTexture.uploadFromByteArray","openfl/display3D/textures/RectangleTexture.hx",103,0x83565556) HX_LOCAL_STACK_FRAME(_hx_pos_574e9a3948a11606_115_uploadFromTypedArray,"openfl.display3D.textures.RectangleTexture","uploadFromTypedArray",0x35aa255f,"openfl.display3D.textures.RectangleTexture.uploadFromTypedArray","openfl/display3D/textures/RectangleTexture.hx",115,0x83565556) HX_LOCAL_STACK_FRAME(_hx_pos_574e9a3948a11606_124___setSamplerState,"openfl.display3D.textures.RectangleTexture","__setSamplerState",0xea7a95c6,"openfl.display3D.textures.RectangleTexture.__setSamplerState","openfl/display3D/textures/RectangleTexture.hx",124,0x83565556) namespace openfl{ namespace display3D{ namespace textures{ void RectangleTexture_obj::__construct( ::openfl::display3D::Context3D context,int width,int height,::String format,bool optimizeForRenderToTexture){ HX_STACKFRAME(&_hx_pos_574e9a3948a11606_28_new) HXLINE( 29) super::__construct(context); HXLINE( 31) this->_hx___width = width; HXLINE( 32) this->_hx___height = height; HXLINE( 34) this->_hx___optimizeForRenderToTexture = optimizeForRenderToTexture; HXLINE( 36) this->_hx___textureTarget = this->_hx___context->gl->TEXTURE_2D; HXLINE( 37) this->uploadFromTypedArray(null()); HXLINE( 39) if (optimizeForRenderToTexture) { HXLINE( 39) this->_hx___getGLFramebuffer(true,0,0); } } Dynamic RectangleTexture_obj::__CreateEmpty() { return new RectangleTexture_obj; } void *RectangleTexture_obj::_hx_vtable = 0; Dynamic RectangleTexture_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< RectangleTexture_obj > _hx_result = new RectangleTexture_obj(); _hx_result->__construct(inArgs[0],inArgs[1],inArgs[2],inArgs[3],inArgs[4]); return _hx_result; } bool RectangleTexture_obj::_hx_isInstanceOf(int inClassId) { if (inClassId<=(int)0x0c89e854) { if (inClassId<=(int)0x0621e2cf) { return inClassId==(int)0x00000001 || inClassId==(int)0x0621e2cf; } else { return inClassId==(int)0x0c89e854; } } else { return inClassId==(int)0x3247d979; } } void RectangleTexture_obj::uploadFromBitmapData( ::openfl::display::BitmapData source){ HX_STACKFRAME(&_hx_pos_574e9a3948a11606_53_uploadFromBitmapData) HXLINE( 55) if (::hx::IsNull( source )) { HXLINE( 55) return; } HXLINE( 57) ::lime::graphics::Image image = this->_hx___getImage(source); HXLINE( 58) if (::hx::IsNull( image )) { HXLINE( 58) return; } HXLINE( 72) this->uploadFromTypedArray(image->get_data()); } HX_DEFINE_DYNAMIC_FUNC1(RectangleTexture_obj,uploadFromBitmapData,(void)) void RectangleTexture_obj::uploadFromByteArray( ::openfl::utils::ByteArrayData data,int byteArrayOffset){ HX_GC_STACKFRAME(&_hx_pos_574e9a3948a11606_103_uploadFromByteArray) HXDLIN( 103) ::Dynamic elements = null(); HXDLIN( 103) ::haxe::io::Bytes buffer = ::openfl::utils::_ByteArray::ByteArray_Impl__obj::toArrayBuffer(data); HXDLIN( 103) ::cpp::VirtualArray array = null(); HXDLIN( 103) ::openfl::_Vector::IntVector vector = null(); HXDLIN( 103) ::lime::utils::ArrayBufferView view = null(); HXDLIN( 103) ::Dynamic byteoffset = byteArrayOffset; HXDLIN( 103) ::Dynamic len = null(); HXDLIN( 103) if (::hx::IsNull( byteoffset )) { HXDLIN( 103) byteoffset = 0; } HXDLIN( 103) ::lime::utils::ArrayBufferView this1; HXDLIN( 103) if (::hx::IsNotNull( elements )) { HXDLIN( 103) this1 = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,elements,4); } else { HXDLIN( 103) if (::hx::IsNotNull( array )) { HXDLIN( 103) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,4); HXDLIN( 103) _this->byteOffset = 0; HXDLIN( 103) _this->length = array->get_length(); HXDLIN( 103) _this->byteLength = (_this->length * _this->bytesPerElement); HXDLIN( 103) ::haxe::io::Bytes this2 = ::haxe::io::Bytes_obj::alloc(_this->byteLength); HXDLIN( 103) _this->buffer = this2; HXDLIN( 103) _this->copyFromArray(array,null()); HXDLIN( 103) this1 = _this; } else { HXDLIN( 103) if (::hx::IsNotNull( vector )) { HXDLIN( 103) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,4); HXDLIN( 103) ::cpp::VirtualArray array = ( (::cpp::VirtualArray)(vector->__Field(HX_("__array",79,c6,ed,8f),::hx::paccDynamic)) ); HXDLIN( 103) _this->byteOffset = 0; HXDLIN( 103) _this->length = array->get_length(); HXDLIN( 103) _this->byteLength = (_this->length * _this->bytesPerElement); HXDLIN( 103) ::haxe::io::Bytes this2 = ::haxe::io::Bytes_obj::alloc(_this->byteLength); HXDLIN( 103) _this->buffer = this2; HXDLIN( 103) _this->copyFromArray(array,null()); HXDLIN( 103) this1 = _this; } else { HXDLIN( 103) if (::hx::IsNotNull( view )) { HXDLIN( 103) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,4); HXDLIN( 103) ::haxe::io::Bytes srcData = view->buffer; HXDLIN( 103) int srcLength = view->length; HXDLIN( 103) int srcByteOffset = view->byteOffset; HXDLIN( 103) int srcElementSize = view->bytesPerElement; HXDLIN( 103) int elementSize = _this->bytesPerElement; HXDLIN( 103) if ((view->type == _this->type)) { HXDLIN( 103) int srcLength = srcData->length; HXDLIN( 103) int cloneLength = (srcLength - srcByteOffset); HXDLIN( 103) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(cloneLength); HXDLIN( 103) _this->buffer = this1; HXDLIN( 103) _this->buffer->blit(0,srcData,srcByteOffset,cloneLength); } else { HXDLIN( 103) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("unimplemented",09,2f,74,b4))); } HXDLIN( 103) _this->byteLength = (_this->bytesPerElement * srcLength); HXDLIN( 103) _this->byteOffset = 0; HXDLIN( 103) _this->length = srcLength; HXDLIN( 103) this1 = _this; } else { HXDLIN( 103) if (::hx::IsNotNull( buffer )) { HXDLIN( 103) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,4); HXDLIN( 103) int in_byteOffset = ( (int)(byteoffset) ); HXDLIN( 103) if ((in_byteOffset < 0)) { HXDLIN( 103) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 103) if ((::hx::Mod(in_byteOffset,_this->bytesPerElement) != 0)) { HXDLIN( 103) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 103) int bufferByteLength = buffer->length; HXDLIN( 103) int elementSize = _this->bytesPerElement; HXDLIN( 103) int newByteLength = bufferByteLength; HXDLIN( 103) if (::hx::IsNull( len )) { HXDLIN( 103) newByteLength = (bufferByteLength - in_byteOffset); HXDLIN( 103) if ((::hx::Mod(bufferByteLength,_this->bytesPerElement) != 0)) { HXDLIN( 103) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } HXDLIN( 103) if ((newByteLength < 0)) { HXDLIN( 103) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } } else { HXDLIN( 103) newByteLength = (( (int)(len) ) * _this->bytesPerElement); HXDLIN( 103) int newRange = (in_byteOffset + newByteLength); HXDLIN( 103) if ((newRange > bufferByteLength)) { HXDLIN( 103) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn())); } } HXDLIN( 103) _this->buffer = buffer; HXDLIN( 103) _this->byteOffset = in_byteOffset; HXDLIN( 103) _this->byteLength = newByteLength; HXDLIN( 103) _this->length = ::Std_obj::_hx_int((( (Float)(newByteLength) ) / ( (Float)(_this->bytesPerElement) ))); HXDLIN( 103) this1 = _this; } else { HXDLIN( 103) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Invalid constructor arguments for UInt8Array",6b,44,d5,85))); } } } } } HXDLIN( 103) this->uploadFromTypedArray(this1); } HX_DEFINE_DYNAMIC_FUNC2(RectangleTexture_obj,uploadFromByteArray,(void)) void RectangleTexture_obj::uploadFromTypedArray( ::lime::utils::ArrayBufferView data){ HX_STACKFRAME(&_hx_pos_574e9a3948a11606_115_uploadFromTypedArray) HXLINE( 116) ::lime::_internal::backend::native::NativeOpenGLRenderContext gl = this->_hx___context->gl; HXLINE( 118) this->_hx___context->_hx___bindGLTexture2D(this->_hx___textureID); HXLINE( 119) { HXLINE( 119) int target = this->_hx___textureTarget; HXDLIN( 119) int internalformat = this->_hx___internalFormat; HXDLIN( 119) int width = this->_hx___width; HXDLIN( 119) int height = this->_hx___height; HXDLIN( 119) int format = this->_hx___format; HXDLIN( 119) int type = gl->UNSIGNED_BYTE; HXDLIN( 119) { HXLINE( 119) ::lime::utils::_BytePointer::BytePointer_Impl__obj::set(::lime::graphics::_WebGL2RenderContext::WebGL2RenderContext_Impl__obj::_hx___tempPointer,null(),data,null(),0); HXDLIN( 119) gl->texImage2D(target,0,internalformat,width,height,0,format,type,::lime::utils::_DataPointer::DataPointer_Impl__obj::fromBytesPointer(::lime::graphics::_WebGL2RenderContext::WebGL2RenderContext_Impl__obj::_hx___tempPointer)); } } HXLINE( 120) this->_hx___context->_hx___bindGLTexture2D(null()); } HX_DEFINE_DYNAMIC_FUNC1(RectangleTexture_obj,uploadFromTypedArray,(void)) bool RectangleTexture_obj::_hx___setSamplerState( ::openfl::display::_internal::SamplerState state){ HX_STACKFRAME(&_hx_pos_574e9a3948a11606_124___setSamplerState) HXLINE( 125) if (this->super::_hx___setSamplerState(state)) { HXLINE( 127) ::lime::_internal::backend::native::NativeOpenGLRenderContext gl = this->_hx___context->gl; HXLINE( 129) if ((::openfl::display3D::Context3D_obj::_hx___glMaxTextureMaxAnisotropy != 0)) { HXLINE( 131) int aniso; HXDLIN( 131) ::Dynamic _hx_switch_0 = state->filter; if ( (_hx_switch_0==0) ){ HXLINE( 131) aniso = 16; HXDLIN( 131) goto _hx_goto_4; } if ( (_hx_switch_0==1) ){ HXLINE( 131) aniso = 2; HXDLIN( 131) goto _hx_goto_4; } if ( (_hx_switch_0==2) ){ HXLINE( 131) aniso = 4; HXDLIN( 131) goto _hx_goto_4; } if ( (_hx_switch_0==3) ){ HXLINE( 131) aniso = 8; HXDLIN( 131) goto _hx_goto_4; } /* default */{ HXLINE( 131) aniso = 1; } _hx_goto_4:; HXLINE( 140) if ((aniso > ::openfl::display3D::Context3D_obj::_hx___glMaxTextureMaxAnisotropy)) { HXLINE( 142) aniso = ::openfl::display3D::Context3D_obj::_hx___glMaxTextureMaxAnisotropy; } HXLINE( 145) gl->texParameterf(gl->TEXTURE_2D,::openfl::display3D::Context3D_obj::_hx___glTextureMaxAnisotropy,( (Float)(aniso) )); } HXLINE( 148) return true; } HXLINE( 151) return false; } ::hx::ObjectPtr< RectangleTexture_obj > RectangleTexture_obj::__new( ::openfl::display3D::Context3D context,int width,int height,::String format,bool optimizeForRenderToTexture) { ::hx::ObjectPtr< RectangleTexture_obj > __this = new RectangleTexture_obj(); __this->__construct(context,width,height,format,optimizeForRenderToTexture); return __this; } ::hx::ObjectPtr< RectangleTexture_obj > RectangleTexture_obj::__alloc(::hx::Ctx *_hx_ctx, ::openfl::display3D::Context3D context,int width,int height,::String format,bool optimizeForRenderToTexture) { RectangleTexture_obj *__this = (RectangleTexture_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(RectangleTexture_obj), true, "openfl.display3D.textures.RectangleTexture")); *(void **)__this = RectangleTexture_obj::_hx_vtable; __this->__construct(context,width,height,format,optimizeForRenderToTexture); return __this; } RectangleTexture_obj::RectangleTexture_obj() { } ::hx::Val RectangleTexture_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 17: if (HX_FIELD_EQ(inName,"__setSamplerState") ) { return ::hx::Val( _hx___setSamplerState_dyn() ); } break; case 19: if (HX_FIELD_EQ(inName,"uploadFromByteArray") ) { return ::hx::Val( uploadFromByteArray_dyn() ); } break; case 20: if (HX_FIELD_EQ(inName,"uploadFromBitmapData") ) { return ::hx::Val( uploadFromBitmapData_dyn() ); } if (HX_FIELD_EQ(inName,"uploadFromTypedArray") ) { return ::hx::Val( uploadFromTypedArray_dyn() ); } } return super::__Field(inName,inCallProp); } #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo *RectangleTexture_obj_sMemberStorageInfo = 0; static ::hx::StaticInfo *RectangleTexture_obj_sStaticStorageInfo = 0; #endif static ::String RectangleTexture_obj_sMemberFields[] = { HX_("uploadFromBitmapData",a4,85,65,0d), HX_("uploadFromByteArray",e6,17,1b,ee), HX_("uploadFromTypedArray",ba,7c,f4,d1), HX_("__setSamplerState",8b,e7,cf,5d), ::String(null()) }; ::hx::Class RectangleTexture_obj::__mClass; void RectangleTexture_obj::__register() { RectangleTexture_obj _hx_dummy; RectangleTexture_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("openfl.display3D.textures.RectangleTexture",e9,93,ed,a3); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = ::hx::Class_obj::dupFunctions(RectangleTexture_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< RectangleTexture_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = RectangleTexture_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = RectangleTexture_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace openfl } // end namespace display3D } // end namespace textures
46.155039
279
0.716269
bobisdabbing
145b245c696f7437af7e97ce08cf77482ea0acd9
878
cpp
C++
1. Basic Recursion/All_Indices.cpp
bhavinvirani/Competitive-Programming-coding-ninjas
5e50ae7ad3fc969a4970f91f8d895c986353bb71
[ "MIT" ]
null
null
null
1. Basic Recursion/All_Indices.cpp
bhavinvirani/Competitive-Programming-coding-ninjas
5e50ae7ad3fc969a4970f91f8d895c986353bb71
[ "MIT" ]
null
null
null
1. Basic Recursion/All_Indices.cpp
bhavinvirani/Competitive-Programming-coding-ninjas
5e50ae7ad3fc969a4970f91f8d895c986353bb71
[ "MIT" ]
null
null
null
#include <iostream> #include <bits/stdc++.h> using namespace std; int allIndexes(int input[], int size, int x, int output[]) { if(size == 0) return 0; int ans=allIndexes(input, size-1, x, output); if(input[size-1] == x) { output[ans]=size-1; return ans+1; } return ans; } //input // 5 // 9 8 10 8 8 // 8 int main(){ freopen("/home/spy/Desktop/input.txt", "r", stdin); freopen("/home/spy/Desktop/output.txt", "w", stdout); int n; cin >> n; int *input = new int[n]; for(int i = 0; i < n; i++) { cin >> input[i]; } int x; cin >> x; int *output = new int[n]; int size = allIndexes(input, n, x, output); for(int i = 0; i < size; i++) { cout << output[i] << " "; } delete [] input; delete [] output; }
15.678571
60
0.477221
bhavinvirani
145f91f53a91148d68c786f4c75d6d4b4f28cbe1
349
hpp
C++
libs/gui/include/sge/gui/master_fwd.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/gui/include/sge/gui/master_fwd.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/gui/include/sge/gui/master_fwd.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_GUI_MASTER_FWD_HPP_INCLUDED #define SGE_GUI_MASTER_FWD_HPP_INCLUDED namespace sge::gui { class master; } #endif
20.529412
61
0.727794
cpreh
1460b9a061802c50f96cf0d13a7cff4b9c091db9
2,703
cpp
C++
src/routes/miners/MercuryMiner.cpp
xXNurioXx/gta-samp-driver
9bd2b0863281cf5bd68a2b699217d3ef73afc3ca
[ "MIT" ]
3
2020-07-12T15:57:39.000Z
2020-09-06T11:00:06.000Z
src/routes/miners/MercuryMiner.cpp
xXNurioXx/gta-sa-self-driving-car
9bd2b0863281cf5bd68a2b699217d3ef73afc3ca
[ "MIT" ]
null
null
null
src/routes/miners/MercuryMiner.cpp
xXNurioXx/gta-sa-self-driving-car
9bd2b0863281cf5bd68a2b699217d3ef73afc3ca
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <Windows.h> #include "../../drivers/Walker.cpp" #include "../../interactions/CaptchaSolver.cpp" #include "../../interactions/ChatManager.cpp" #include "Miner.cpp" class MercuryMiner { private: Movement *movement = new Movement(); ChatManager *chat = new ChatManager(); GameResources *gameResources; Walker *walker; public: MercuryMiner(GameResources *gameResources) { this->gameResources = gameResources; this->walker = new Walker(gameResources); } public: void Start() { goToStart(); goToOutsideDoor(); goToMercuryStone(); pickStone(); goToInnerDoor(); goDeliveryPoint(); deliverStone(); } private: void deliverStone() { walker->RunToPos(Miner::Checkpoints::DELIVERY_POINT); Sleep(1000); chat->Type("/dejar roca"); solveCaptcha(); Sleep(5000); } private: void goToStart() { movement->StopMovingForward(); movement->StopRunning(); movement->StopSlowlyWalk(); movement->StopMovingBack(); movement->StopMovingLeft(); movement->StopMovingRight(); walker->overSecureWalkTo(Miner::Checkpoints::START_RAMP); } private: void goDeliveryPoint() { walker->RunToPos(Miner::Checkpoints::ENTER_DOOR); walker->RunToPos(Miner::Checkpoints::OUTSIDE_PATH_DOOR_CORNER); walker->RunToPos(Miner::Checkpoints::OUTSIDE_PATH_DOOR_BRIDGE); walker->RunToPos(Miner::Checkpoints::OUTSIDE_PATH_RAMP_CORNER); } private: void goToInnerDoor() { walker->RunToPos(Miner::Checkpoints::MERCURY_STONE); walker->RunToPos(Miner::Checkpoints::RAIL_END); walker->RunToPos(Miner::Checkpoints::EXIT_DOOR); Sleep(1000); movement->JoinOrLeaveInterior(); } private: void goToOutsideDoor() { walker->RunToPos(Miner::Checkpoints::OUTSIDE_PATH_RAMP_CORNER); walker->RunToPos(Miner::Checkpoints::OUTSIDE_PATH_DOOR_BRIDGE); walker->RunToPos(Miner::Checkpoints::OUTSIDE_PATH_DOOR_CORNER); walker->RunToPos(Miner::Checkpoints::ENTER_DOOR); movement->JoinOrLeaveInterior(); } private: void goToMercuryStone() { walker->RunToPos(Miner::Checkpoints::RAIL_END); walker->RunToPos(Miner::Checkpoints::MERCURY_STONE); } private: void pickStone() { Sleep(2500); chat->Type("/picar"); Sleep(20 * 1000); } private: void solveCaptcha() { printf("Starting captcha solver...\n"); Sleep(1500); auto *captchaSolver = new CaptchaSolver(); captchaSolver->Solve(); } };
26.5
71
0.63781
xXNurioXx
1463a9000c0501599b36fc1dd05ddfa1bb9e47bd
73,362
cpp
C++
packages/thirdParty/wxWidgets/wxWidgets-2.9.4/src/propgrid/props.cpp
wivlaro/newton-dynamics
2bafd29aea919f237e56784510db1cb8011d0f40
[ "Zlib" ]
null
null
null
packages/thirdParty/wxWidgets/wxWidgets-2.9.4/src/propgrid/props.cpp
wivlaro/newton-dynamics
2bafd29aea919f237e56784510db1cb8011d0f40
[ "Zlib" ]
null
null
null
packages/thirdParty/wxWidgets/wxWidgets-2.9.4/src/propgrid/props.cpp
wivlaro/newton-dynamics
2bafd29aea919f237e56784510db1cb8011d0f40
[ "Zlib" ]
null
null
null
///////////////////////////////////////////////////////////////////////////// // Name: src/propgrid/props.cpp // Purpose: Basic Property Classes // Author: Jaakko Salli // Modified by: // Created: 2005-05-14 // RCS-ID: $Id$ // Copyright: (c) Jaakko Salli // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_PROPGRID #ifndef WX_PRECOMP #include "wx/defs.h" #include "wx/object.h" #include "wx/hash.h" #include "wx/string.h" #include "wx/log.h" #include "wx/event.h" #include "wx/window.h" #include "wx/panel.h" #include "wx/dc.h" #include "wx/dcclient.h" #include "wx/dcmemory.h" #include "wx/button.h" #include "wx/bmpbuttn.h" #include "wx/pen.h" #include "wx/brush.h" #include "wx/cursor.h" #include "wx/dialog.h" #include "wx/settings.h" #include "wx/msgdlg.h" #include "wx/choice.h" #include "wx/stattext.h" #include "wx/scrolwin.h" #include "wx/dirdlg.h" #include "wx/combobox.h" #include "wx/layout.h" #include "wx/sizer.h" #include "wx/textdlg.h" #include "wx/filedlg.h" #include "wx/intl.h" #endif #include "wx/filename.h" #include "wx/propgrid/propgrid.h" #define wxPG_CUSTOM_IMAGE_WIDTH 20 // for wxColourProperty etc. // ----------------------------------------------------------------------- // wxStringProperty // ----------------------------------------------------------------------- WX_PG_IMPLEMENT_PROPERTY_CLASS(wxStringProperty,wxPGProperty, wxString,const wxString&,TextCtrl) wxStringProperty::wxStringProperty( const wxString& label, const wxString& name, const wxString& value ) : wxPGProperty(label,name) { SetValue(value); } void wxStringProperty::OnSetValue() { if ( !m_value.IsNull() && m_value.GetString() == wxS("<composed>") ) SetFlag(wxPG_PROP_COMPOSED_VALUE); if ( HasFlag(wxPG_PROP_COMPOSED_VALUE) ) { wxString s; DoGenerateComposedValue(s); m_value = s; } } wxStringProperty::~wxStringProperty() { } wxString wxStringProperty::ValueToString( wxVariant& value, int argFlags ) const { wxString s = value.GetString(); if ( GetChildCount() && HasFlag(wxPG_PROP_COMPOSED_VALUE) ) { // Value stored in m_value is non-editable, non-full value if ( (argFlags & wxPG_FULL_VALUE) || (argFlags & wxPG_EDITABLE_VALUE) || !s.length() ) { // Calling this under incorrect conditions will fail wxASSERT_MSG( argFlags & wxPG_VALUE_IS_CURRENT, "Sorry, currently default wxPGProperty::ValueToString() " "implementation only works if value is m_value." ); DoGenerateComposedValue(s, argFlags); } return s; } // If string is password and value is for visual purposes, // then return asterisks instead the actual string. if ( (m_flags & wxPG_PROP_PASSWORD) && !(argFlags & (wxPG_FULL_VALUE|wxPG_EDITABLE_VALUE)) ) return wxString(wxChar('*'), s.Length()); return s; } bool wxStringProperty::StringToValue( wxVariant& variant, const wxString& text, int argFlags ) const { if ( GetChildCount() && HasFlag(wxPG_PROP_COMPOSED_VALUE) ) return wxPGProperty::StringToValue(variant, text, argFlags); if ( variant != text ) { variant = text; return true; } return false; } bool wxStringProperty::DoSetAttribute( const wxString& name, wxVariant& value ) { if ( name == wxPG_STRING_PASSWORD ) { m_flags &= ~(wxPG_PROP_PASSWORD); if ( value.GetLong() ) m_flags |= wxPG_PROP_PASSWORD; RecreateEditor(); return false; } return true; } // ----------------------------------------------------------------------- // wxNumericPropertyValidator // ----------------------------------------------------------------------- #if wxUSE_VALIDATORS wxNumericPropertyValidator:: wxNumericPropertyValidator( NumericType numericType, int base ) : wxTextValidator(wxFILTER_INCLUDE_CHAR_LIST) { wxArrayString arr; arr.Add(wxS("0")); arr.Add(wxS("1")); arr.Add(wxS("2")); arr.Add(wxS("3")); arr.Add(wxS("4")); arr.Add(wxS("5")); arr.Add(wxS("6")); arr.Add(wxS("7")); if ( base >= 10 ) { arr.Add(wxS("8")); arr.Add(wxS("9")); if ( base >= 16 ) { arr.Add(wxS("a")); arr.Add(wxS("A")); arr.Add(wxS("b")); arr.Add(wxS("B")); arr.Add(wxS("c")); arr.Add(wxS("C")); arr.Add(wxS("d")); arr.Add(wxS("D")); arr.Add(wxS("e")); arr.Add(wxS("E")); arr.Add(wxS("f")); arr.Add(wxS("F")); } } if ( numericType == Signed ) { arr.Add(wxS("+")); arr.Add(wxS("-")); } else if ( numericType == Float ) { arr.Add(wxS("+")); arr.Add(wxS("-")); arr.Add(wxS("e")); // Use locale-specific decimal point arr.Add(wxString::Format("%g", 1.1)[1]); } SetIncludes(arr); } bool wxNumericPropertyValidator::Validate(wxWindow* parent) { if ( !wxTextValidator::Validate(parent) ) return false; wxWindow* wnd = GetWindow(); if ( !wxDynamicCast(wnd, wxTextCtrl) ) return true; // Do not allow zero-length string wxTextCtrl* tc = static_cast<wxTextCtrl*>(wnd); wxString text = tc->GetValue(); if ( text.empty() ) return false; return true; } #endif // wxUSE_VALIDATORS // ----------------------------------------------------------------------- // wxIntProperty // ----------------------------------------------------------------------- WX_PG_IMPLEMENT_PROPERTY_CLASS(wxIntProperty,wxPGProperty, long,long,TextCtrl) wxIntProperty::wxIntProperty( const wxString& label, const wxString& name, long value ) : wxPGProperty(label,name) { SetValue(value); } wxIntProperty::wxIntProperty( const wxString& label, const wxString& name, const wxLongLong& value ) : wxPGProperty(label,name) { SetValue(WXVARIANT(value)); } wxIntProperty::~wxIntProperty() { } wxString wxIntProperty::ValueToString( wxVariant& value, int WXUNUSED(argFlags) ) const { if ( value.GetType() == wxPG_VARIANT_TYPE_LONG ) { return wxString::Format(wxS("%li"),value.GetLong()); } else if ( value.GetType() == wxPG_VARIANT_TYPE_LONGLONG ) { wxLongLong ll = value.GetLongLong(); return ll.ToString(); } return wxEmptyString; } bool wxIntProperty::StringToValue( wxVariant& variant, const wxString& text, int argFlags ) const { wxString s; long value32; if ( text.empty() ) { variant.MakeNull(); return true; } // We know it is a number, but let's still check // the return value. if ( text.IsNumber() ) { // Remove leading zeroes, so that the number is not interpreted as octal wxString::const_iterator i = text.begin(); wxString::const_iterator iMax = text.end() - 1; // Let's allow one, last zero though int firstNonZeroPos = 0; for ( ; i != iMax; ++i ) { wxChar c = *i; if ( c != wxS('0') && c != wxS(' ') ) break; firstNonZeroPos++; } wxString useText = text.substr(firstNonZeroPos, text.length() - firstNonZeroPos); wxString variantType = variant.GetType(); bool isPrevLong = variantType == wxPG_VARIANT_TYPE_LONG; wxLongLong_t value64 = 0; if ( useText.ToLongLong(&value64, 10) && ( value64 >= INT_MAX || value64 <= INT_MIN ) ) { bool doChangeValue = isPrevLong; if ( !isPrevLong && variantType == wxPG_VARIANT_TYPE_LONGLONG ) { wxLongLong oldValue = variant.GetLongLong(); if ( oldValue.GetValue() != value64 ) doChangeValue = true; } if ( doChangeValue ) { wxLongLong ll(value64); variant = ll; return true; } } if ( useText.ToLong( &value32, 0 ) ) { if ( !isPrevLong || variant != value32 ) { variant = value32; return true; } } } else if ( argFlags & wxPG_REPORT_ERROR ) { } return false; } bool wxIntProperty::IntToValue( wxVariant& variant, int value, int WXUNUSED(argFlags) ) const { if ( variant.GetType() != wxPG_VARIANT_TYPE_LONG || variant != (long)value ) { variant = (long)value; return true; } return false; } // // Common validation code to be called in ValidateValue() // implementations. // // Note that 'value' is reference on purpose, so we can write // back to it when mode is wxPG_PROPERTY_VALIDATION_SATURATE. // template<typename T> bool NumericValidation( const wxPGProperty* property, T& value, wxPGValidationInfo* pValidationInfo, int mode, const wxString& strFmt ) { T min = (T) wxINT64_MIN; T max = (T) wxINT64_MAX; wxVariant variant; bool minOk = false; bool maxOk = false; variant = property->GetAttribute(wxPGGlobalVars->m_strMin); if ( !variant.IsNull() ) { variant.Convert(&min); minOk = true; } variant = property->GetAttribute(wxPGGlobalVars->m_strMax); if ( !variant.IsNull() ) { variant.Convert(&max); maxOk = true; } if ( minOk ) { if ( value < min ) { if ( mode == wxPG_PROPERTY_VALIDATION_ERROR_MESSAGE ) { wxString msg; wxString smin = wxString::Format(strFmt, min); wxString smax = wxString::Format(strFmt, max); if ( !maxOk ) msg = wxString::Format( _("Value must be %s or higher."), smin.c_str()); else msg = wxString::Format( _("Value must be between %s and %s."), smin.c_str(), smax.c_str()); pValidationInfo->SetFailureMessage(msg); } else if ( mode == wxPG_PROPERTY_VALIDATION_SATURATE ) value = min; else value = max - (min - value); return false; } } if ( maxOk ) { if ( value > max ) { if ( mode == wxPG_PROPERTY_VALIDATION_ERROR_MESSAGE ) { wxString msg; wxString smin = wxString::Format(strFmt, min); wxString smax = wxString::Format(strFmt, max); if ( !minOk ) msg = wxString::Format( _("Value must be %s or less."), smax.c_str()); else msg = wxString::Format( _("Value must be between %s and %s."), smin.c_str(), smax.c_str()); pValidationInfo->SetFailureMessage(msg); } else if ( mode == wxPG_PROPERTY_VALIDATION_SATURATE ) value = max; else value = min + (value - max); return false; } } return true; } bool wxIntProperty::DoValidation( const wxPGProperty* property, wxLongLong_t& value, wxPGValidationInfo* pValidationInfo, int mode ) { return NumericValidation<wxLongLong_t>(property, value, pValidationInfo, mode, wxS("%lld")); } bool wxIntProperty::ValidateValue( wxVariant& value, wxPGValidationInfo& validationInfo ) const { wxLongLong_t ll = value.GetLongLong().GetValue(); return DoValidation(this, ll, &validationInfo, wxPG_PROPERTY_VALIDATION_ERROR_MESSAGE); } wxValidator* wxIntProperty::GetClassValidator() { #if wxUSE_VALIDATORS WX_PG_DOGETVALIDATOR_ENTRY() wxValidator* validator = new wxNumericPropertyValidator( wxNumericPropertyValidator::Signed); WX_PG_DOGETVALIDATOR_EXIT(validator) #else return NULL; #endif } wxValidator* wxIntProperty::DoGetValidator() const { return GetClassValidator(); } // ----------------------------------------------------------------------- // wxUIntProperty // ----------------------------------------------------------------------- #define wxPG_UINT_TEMPLATE_MAX 8 static const wxChar* const gs_uintTemplates32[wxPG_UINT_TEMPLATE_MAX] = { wxT("%lx"),wxT("0x%lx"),wxT("$%lx"), wxT("%lX"),wxT("0x%lX"),wxT("$%lX"), wxT("%lu"),wxT("%lo") }; static const char* const gs_uintTemplates64[wxPG_UINT_TEMPLATE_MAX] = { "%" wxLongLongFmtSpec "x", "0x%" wxLongLongFmtSpec "x", "$%" wxLongLongFmtSpec "x", "%" wxLongLongFmtSpec "X", "0x%" wxLongLongFmtSpec "X", "$%" wxLongLongFmtSpec "X", "%" wxLongLongFmtSpec "u", "%" wxLongLongFmtSpec "o" }; WX_PG_IMPLEMENT_PROPERTY_CLASS(wxUIntProperty,wxPGProperty, long,unsigned long,TextCtrl) void wxUIntProperty::Init() { m_base = 6; // This is magic number for dec base (must be same as in setattribute) m_realBase = 10; m_prefix = wxPG_PREFIX_NONE; } wxUIntProperty::wxUIntProperty( const wxString& label, const wxString& name, unsigned long value ) : wxPGProperty(label,name) { Init(); SetValue((long)value); } wxUIntProperty::wxUIntProperty( const wxString& label, const wxString& name, const wxULongLong& value ) : wxPGProperty(label,name) { Init(); SetValue(WXVARIANT(value)); } wxUIntProperty::~wxUIntProperty() { } wxString wxUIntProperty::ValueToString( wxVariant& value, int WXUNUSED(argFlags) ) const { size_t index = m_base + m_prefix; if ( index >= wxPG_UINT_TEMPLATE_MAX ) index = wxPG_BASE_DEC; if ( value.GetType() == wxPG_VARIANT_TYPE_LONG ) { return wxString::Format(gs_uintTemplates32[index], (unsigned long)value.GetLong()); } wxULongLong ull = value.GetULongLong(); return wxString::Format(gs_uintTemplates64[index], ull.GetValue()); } bool wxUIntProperty::StringToValue( wxVariant& variant, const wxString& text, int WXUNUSED(argFlags) ) const { wxString variantType = variant.GetType(); bool isPrevLong = variantType == wxPG_VARIANT_TYPE_LONG; if ( text.empty() ) { variant.MakeNull(); return true; } size_t start = 0; if ( text[0] == wxS('$') ) start++; wxULongLong_t value64 = 0; wxString s = text.substr(start, text.length() - start); if ( s.ToULongLong(&value64, (unsigned int)m_realBase) ) { if ( value64 >= LONG_MAX ) { bool doChangeValue = isPrevLong; if ( !isPrevLong && variantType == wxPG_VARIANT_TYPE_ULONGLONG ) { wxULongLong oldValue = variant.GetULongLong(); if ( oldValue.GetValue() != value64 ) doChangeValue = true; } if ( doChangeValue ) { variant = wxULongLong(value64); return true; } } else { unsigned long value32 = wxLongLong(value64).GetLo(); if ( !isPrevLong || m_value != (long)value32 ) { variant = (long)value32; return true; } } } return false; } bool wxUIntProperty::IntToValue( wxVariant& variant, int number, int WXUNUSED(argFlags) ) const { if ( variant != (long)number ) { variant = (long)number; return true; } return false; } bool wxUIntProperty::ValidateValue( wxVariant& value, wxPGValidationInfo& validationInfo ) const { wxULongLong_t uul = value.GetULongLong().GetValue(); return NumericValidation<wxULongLong_t>(this, uul, &validationInfo, wxPG_PROPERTY_VALIDATION_ERROR_MESSAGE, wxS("%llu")); } wxValidator* wxUIntProperty::DoGetValidator() const { #if wxUSE_VALIDATORS WX_PG_DOGETVALIDATOR_ENTRY() wxValidator* validator = new wxNumericPropertyValidator( wxNumericPropertyValidator::Unsigned, m_realBase); WX_PG_DOGETVALIDATOR_EXIT(validator) #else return NULL; #endif } bool wxUIntProperty::DoSetAttribute( const wxString& name, wxVariant& value ) { if ( name == wxPG_UINT_BASE ) { int val = value.GetLong(); m_realBase = (wxByte) val; if ( m_realBase > 16 ) m_realBase = 16; // // Translate logical base to a template array index m_base = 7; // oct if ( val == wxPG_BASE_HEX ) m_base = 3; else if ( val == wxPG_BASE_DEC ) m_base = 6; else if ( val == wxPG_BASE_HEXL ) m_base = 0; return true; } else if ( name == wxPG_UINT_PREFIX ) { m_prefix = (wxByte) value.GetLong(); return true; } return false; } // ----------------------------------------------------------------------- // wxFloatProperty // ----------------------------------------------------------------------- WX_PG_IMPLEMENT_PROPERTY_CLASS(wxFloatProperty,wxPGProperty, double,double,TextCtrl) wxFloatProperty::wxFloatProperty( const wxString& label, const wxString& name, double value ) : wxPGProperty(label,name) { m_precision = -1; SetValue(value); } wxFloatProperty::~wxFloatProperty() { } // This helper method provides standard way for floating point-using // properties to convert values to string. const wxString& wxPropertyGrid::DoubleToString(wxString& target, double value, int precision, bool removeZeroes, wxString* precTemplate) { if ( precision >= 0 ) { wxString text1; if (!precTemplate) precTemplate = &text1; if ( precTemplate->empty() ) { *precTemplate = wxS("%."); *precTemplate << wxString::Format( wxS("%i"), precision ); *precTemplate << wxS('f'); } target.Printf( precTemplate->c_str(), value ); } else { target.Printf( wxS("%f"), value ); } if ( removeZeroes && precision != 0 && !target.empty() ) { // Remove excess zeroes (do not remove this code just yet, // since sprintf can't do the same consistently across platforms). wxString::const_iterator i = target.end() - 1; size_t new_len = target.length() - 1; for ( ; i != target.begin(); --i ) { if ( *i != wxS('0') ) break; new_len--; } wxChar cur_char = *i; if ( cur_char != wxS('.') && cur_char != wxS(',') ) new_len++; if ( new_len != target.length() ) target.resize(new_len); } // Remove sign from zero if ( target.length() >= 2 && target[0] == wxS('-') ) { bool isZero = true; wxString::const_iterator i = target.begin() + 1; for ( ; i != target.end(); i++ ) { if ( *i != wxS('0') && *i != wxS('.') && *i != wxS(',') ) { isZero = false; break; } } if ( isZero ) target.erase(target.begin()); } return target; } wxString wxFloatProperty::ValueToString( wxVariant& value, int argFlags ) const { wxString text; if ( !value.IsNull() ) { wxPropertyGrid::DoubleToString(text, value, m_precision, !(argFlags & wxPG_FULL_VALUE), NULL); } return text; } bool wxFloatProperty::StringToValue( wxVariant& variant, const wxString& text, int argFlags ) const { wxString s; double value; if ( text.empty() ) { variant.MakeNull(); return true; } bool res = text.ToDouble(&value); if ( res ) { if ( variant != value ) { variant = value; return true; } } else if ( argFlags & wxPG_REPORT_ERROR ) { } return false; } bool wxFloatProperty::DoValidation( const wxPGProperty* property, double& value, wxPGValidationInfo* pValidationInfo, int mode ) { return NumericValidation<double>(property, value, pValidationInfo, mode, wxS("%g")); } bool wxFloatProperty::ValidateValue( wxVariant& value, wxPGValidationInfo& validationInfo ) const { double fpv = value.GetDouble(); return DoValidation(this, fpv, &validationInfo, wxPG_PROPERTY_VALIDATION_ERROR_MESSAGE); } bool wxFloatProperty::DoSetAttribute( const wxString& name, wxVariant& value ) { if ( name == wxPG_FLOAT_PRECISION ) { m_precision = value.GetLong(); return true; } return false; } wxValidator* wxFloatProperty::GetClassValidator() { #if wxUSE_VALIDATORS WX_PG_DOGETVALIDATOR_ENTRY() wxValidator* validator = new wxNumericPropertyValidator( wxNumericPropertyValidator::Float); WX_PG_DOGETVALIDATOR_EXIT(validator) #else return NULL; #endif } wxValidator* wxFloatProperty::DoGetValidator() const { return GetClassValidator(); } // ----------------------------------------------------------------------- // wxBoolProperty // ----------------------------------------------------------------------- // We cannot use standard WX_PG_IMPLEMENT_PROPERTY_CLASS macro, since // there is a custom GetEditorClass. IMPLEMENT_DYNAMIC_CLASS(wxBoolProperty, wxPGProperty) const wxPGEditor* wxBoolProperty::DoGetEditorClass() const { // Select correct editor control. #if wxPG_INCLUDE_CHECKBOX if ( !(m_flags & wxPG_PROP_USE_CHECKBOX) ) return wxPGEditor_Choice; return wxPGEditor_CheckBox; #else return wxPGEditor_Choice; #endif } wxBoolProperty::wxBoolProperty( const wxString& label, const wxString& name, bool value ) : wxPGProperty(label,name) { m_choices.Assign(wxPGGlobalVars->m_boolChoices); SetValue(wxPGVariant_Bool(value)); m_flags |= wxPG_PROP_USE_DCC; } wxBoolProperty::~wxBoolProperty() { } wxString wxBoolProperty::ValueToString( wxVariant& value, int argFlags ) const { bool boolValue = value.GetBool(); // As a fragment of composite string value, // make it a little more readable. if ( argFlags & wxPG_COMPOSITE_FRAGMENT ) { if ( boolValue ) { return m_label; } else { if ( argFlags & wxPG_UNEDITABLE_COMPOSITE_FRAGMENT ) return wxEmptyString; wxString notFmt; if ( wxPGGlobalVars->m_autoGetTranslation ) notFmt = _("Not %s"); else notFmt = wxS("Not %s"); return wxString::Format(notFmt.c_str(), m_label.c_str()); } } if ( !(argFlags & wxPG_FULL_VALUE) ) { return wxPGGlobalVars->m_boolChoices[boolValue?1:0].GetText(); } wxString text; if ( boolValue ) text = wxS("true"); else text = wxS("false"); return text; } bool wxBoolProperty::StringToValue( wxVariant& variant, const wxString& text, int WXUNUSED(argFlags) ) const { bool boolValue = false; if ( text.CmpNoCase(wxPGGlobalVars->m_boolChoices[1].GetText()) == 0 || text.CmpNoCase(wxS("true")) == 0 || text.CmpNoCase(m_label) == 0 ) boolValue = true; if ( text.empty() ) { variant.MakeNull(); return true; } if ( variant != boolValue ) { variant = wxPGVariant_Bool(boolValue); return true; } return false; } bool wxBoolProperty::IntToValue( wxVariant& variant, int value, int ) const { bool boolValue = value ? true : false; if ( variant != boolValue ) { variant = wxPGVariant_Bool(boolValue); return true; } return false; } bool wxBoolProperty::DoSetAttribute( const wxString& name, wxVariant& value ) { #if wxPG_INCLUDE_CHECKBOX if ( name == wxPG_BOOL_USE_CHECKBOX ) { if ( value.GetLong() ) m_flags |= wxPG_PROP_USE_CHECKBOX; else m_flags &= ~(wxPG_PROP_USE_CHECKBOX); return true; } #endif if ( name == wxPG_BOOL_USE_DOUBLE_CLICK_CYCLING ) { if ( value.GetLong() ) m_flags |= wxPG_PROP_USE_DCC; else m_flags &= ~(wxPG_PROP_USE_DCC); return true; } return false; } // ----------------------------------------------------------------------- // wxEnumProperty // ----------------------------------------------------------------------- IMPLEMENT_DYNAMIC_CLASS(wxEnumProperty, wxPGProperty) WX_PG_IMPLEMENT_PROPERTY_CLASS_PLAIN(wxEnumProperty,long,Choice) wxEnumProperty::wxEnumProperty( const wxString& label, const wxString& name, const wxChar* const* labels, const long* values, int value ) : wxPGProperty(label,name) { SetIndex(0); if ( labels ) { m_choices.Add(labels,values); if ( GetItemCount() ) SetValue( (long)value ); } } wxEnumProperty::wxEnumProperty( const wxString& label, const wxString& name, const wxChar* const* labels, const long* values, wxPGChoices* choicesCache, int value ) : wxPGProperty(label,name) { SetIndex(0); wxASSERT( choicesCache ); if ( choicesCache->IsOk() ) { m_choices.Assign( *choicesCache ); m_value = wxPGVariant_Zero; } else if ( labels ) { m_choices.Add(labels,values); if ( GetItemCount() ) SetValue( (long)value ); } } wxEnumProperty::wxEnumProperty( const wxString& label, const wxString& name, const wxArrayString& labels, const wxArrayInt& values, int value ) : wxPGProperty(label,name) { SetIndex(0); if ( &labels && labels.size() ) { m_choices.Set(labels, values); if ( GetItemCount() ) SetValue( (long)value ); } } wxEnumProperty::wxEnumProperty( const wxString& label, const wxString& name, wxPGChoices& choices, int value ) : wxPGProperty(label,name) { m_choices.Assign( choices ); if ( GetItemCount() ) SetValue( (long)value ); } int wxEnumProperty::GetIndexForValue( int value ) const { if ( !m_choices.IsOk() ) return -1; int intVal = m_choices.Index(value); if ( intVal >= 0 ) return intVal; return value; } wxEnumProperty::~wxEnumProperty () { } int wxEnumProperty::ms_nextIndex = -2; void wxEnumProperty::OnSetValue() { wxString variantType = m_value.GetType(); if ( variantType == wxPG_VARIANT_TYPE_LONG ) { ValueFromInt_( m_value, m_value.GetLong(), wxPG_FULL_VALUE ); } else if ( variantType == wxPG_VARIANT_TYPE_STRING ) { ValueFromString_( m_value, m_value.GetString(), 0 ); } else { wxFAIL; } if ( ms_nextIndex != -2 ) { m_index = ms_nextIndex; ms_nextIndex = -2; } } bool wxEnumProperty::ValidateValue( wxVariant& value, wxPGValidationInfo& WXUNUSED(validationInfo) ) const { // Make sure string value is in the list, // unless property has string as preferred value type // To reduce code size, use conversion here as well if ( value.GetType() == wxPG_VARIANT_TYPE_STRING && !wxDynamicCastThis(wxEditEnumProperty) ) return ValueFromString_( value, value.GetString(), wxPG_PROPERTY_SPECIFIC ); return true; } wxString wxEnumProperty::ValueToString( wxVariant& value, int WXUNUSED(argFlags) ) const { if ( value.GetType() == wxPG_VARIANT_TYPE_STRING ) return value.GetString(); int index = m_choices.Index(value.GetLong()); if ( index < 0 ) return wxEmptyString; return m_choices.GetLabel(index); } bool wxEnumProperty::StringToValue( wxVariant& variant, const wxString& text, int argFlags ) const { return ValueFromString_( variant, text, argFlags ); } bool wxEnumProperty::IntToValue( wxVariant& variant, int intVal, int argFlags ) const { return ValueFromInt_( variant, intVal, argFlags ); } bool wxEnumProperty::ValueFromString_( wxVariant& value, const wxString& text, int argFlags ) const { int useIndex = -1; long useValue = 0; for ( unsigned int i=0; i<m_choices.GetCount(); i++ ) { const wxString& entryLabel = m_choices.GetLabel(i); if ( text.CmpNoCase(entryLabel) == 0 ) { useIndex = (int)i; useValue = m_choices.GetValue(i); break; } } bool asText = false; bool isEdit = this->IsKindOf(wxCLASSINFO(wxEditEnumProperty)); // If text not any of the choices, store as text instead // (but only if we are wxEditEnumProperty) if ( useIndex == -1 && isEdit ) { asText = true; } int setAsNextIndex = -2; if ( asText ) { setAsNextIndex = -1; value = text; } else if ( useIndex != GetIndex() ) { if ( useIndex != -1 ) { setAsNextIndex = useIndex; value = (long)useValue; } else { setAsNextIndex = -1; value = wxPGVariant_MinusOne; } } if ( setAsNextIndex != -2 ) { // If wxPG_PROPERTY_SPECIFIC is set, then this is done for // validation purposes only, and index must not be changed if ( !(argFlags & wxPG_PROPERTY_SPECIFIC) ) ms_nextIndex = setAsNextIndex; if ( isEdit || setAsNextIndex != -1 ) return true; else return false; } return false; } bool wxEnumProperty::ValueFromInt_( wxVariant& variant, int intVal, int argFlags ) const { // If wxPG_FULL_VALUE is *not* in argFlags, then intVal is index from combo box. // ms_nextIndex = -2; if ( argFlags & wxPG_FULL_VALUE ) { ms_nextIndex = GetIndexForValue( intVal ); } else { if ( intVal != GetIndex() ) { ms_nextIndex = intVal; } } if ( ms_nextIndex != -2 ) { if ( !(argFlags & wxPG_FULL_VALUE) ) intVal = m_choices.GetValue(intVal); variant = (long)intVal; return true; } return false; } void wxEnumProperty::OnValidationFailure( wxVariant& WXUNUSED(pendingValue) ) { // Revert index ResetNextIndex(); } void wxEnumProperty::SetIndex( int index ) { ms_nextIndex = -2; m_index = index; } int wxEnumProperty::GetIndex() const { if ( m_value.IsNull() ) return -1; if ( ms_nextIndex != -2 ) return ms_nextIndex; return m_index; } // ----------------------------------------------------------------------- // wxEditEnumProperty // ----------------------------------------------------------------------- IMPLEMENT_DYNAMIC_CLASS(wxEditEnumProperty, wxPGProperty) WX_PG_IMPLEMENT_PROPERTY_CLASS_PLAIN(wxEditEnumProperty,wxString,ComboBox) wxEditEnumProperty::wxEditEnumProperty( const wxString& label, const wxString& name, const wxChar* const* labels, const long* values, const wxString& value ) : wxEnumProperty(label,name,labels,values,0) { SetValue( value ); } wxEditEnumProperty::wxEditEnumProperty( const wxString& label, const wxString& name, const wxChar* const* labels, const long* values, wxPGChoices* choicesCache, const wxString& value ) : wxEnumProperty(label,name,labels,values,choicesCache,0) { SetValue( value ); } wxEditEnumProperty::wxEditEnumProperty( const wxString& label, const wxString& name, const wxArrayString& labels, const wxArrayInt& values, const wxString& value ) : wxEnumProperty(label,name,labels,values,0) { SetValue( value ); } wxEditEnumProperty::wxEditEnumProperty( const wxString& label, const wxString& name, wxPGChoices& choices, const wxString& value ) : wxEnumProperty(label,name,choices,0) { SetValue( value ); } wxEditEnumProperty::~wxEditEnumProperty() { } // ----------------------------------------------------------------------- // wxFlagsProperty // ----------------------------------------------------------------------- IMPLEMENT_DYNAMIC_CLASS(wxFlagsProperty,wxPGProperty) WX_PG_IMPLEMENT_PROPERTY_CLASS_PLAIN(wxFlagsProperty,long,TextCtrl) void wxFlagsProperty::Init() { long value = m_value; // // Generate children // unsigned int i; unsigned int prevChildCount = m_children.size(); int oldSel = -1; if ( prevChildCount ) { wxPropertyGridPageState* state = GetParentState(); // State safety check (it may be NULL in immediate parent) wxASSERT( state ); if ( state ) { wxPGProperty* selected = state->GetSelection(); if ( selected ) { if ( selected->GetParent() == this ) oldSel = selected->GetIndexInParent(); else if ( selected == this ) oldSel = -2; } } state->DoClearSelection(); } // Delete old children for ( i=0; i<prevChildCount; i++ ) delete m_children[i]; m_children.clear(); // Relay wxPG_BOOL_USE_CHECKBOX and wxPG_BOOL_USE_DOUBLE_CLICK_CYCLING // to child bool property controls. long attrUseCheckBox = GetAttributeAsLong(wxPG_BOOL_USE_CHECKBOX, 0); long attrUseDCC = GetAttributeAsLong(wxPG_BOOL_USE_DOUBLE_CLICK_CYCLING, 0); if ( m_choices.IsOk() ) { const wxPGChoices& choices = m_choices; for ( i=0; i<GetItemCount(); i++ ) { bool child_val; child_val = ( value & choices.GetValue(i) )?true:false; wxPGProperty* boolProp; wxString label = GetLabel(i); #if wxUSE_INTL if ( wxPGGlobalVars->m_autoGetTranslation ) { boolProp = new wxBoolProperty( ::wxGetTranslation(label), label, child_val ); } else #endif { boolProp = new wxBoolProperty( label, label, child_val ); } if ( attrUseCheckBox ) boolProp->SetAttribute(wxPG_BOOL_USE_CHECKBOX, true); if ( attrUseDCC ) boolProp->SetAttribute(wxPG_BOOL_USE_DOUBLE_CLICK_CYCLING, true); AddPrivateChild(boolProp); } m_oldChoicesData = m_choices.GetDataPtr(); } m_oldValue = m_value; if ( prevChildCount ) SubPropsChanged(oldSel); } wxFlagsProperty::wxFlagsProperty( const wxString& label, const wxString& name, const wxChar* const* labels, const long* values, long value ) : wxPGProperty(label,name) { m_oldChoicesData = NULL; if ( labels ) { m_choices.Set(labels,values); wxASSERT( GetItemCount() ); SetValue( value ); } else { m_value = wxPGVariant_Zero; } } wxFlagsProperty::wxFlagsProperty( const wxString& label, const wxString& name, const wxArrayString& labels, const wxArrayInt& values, int value ) : wxPGProperty(label,name) { m_oldChoicesData = NULL; if ( &labels && labels.size() ) { m_choices.Set(labels,values); wxASSERT( GetItemCount() ); SetValue( (long)value ); } else { m_value = wxPGVariant_Zero; } } wxFlagsProperty::wxFlagsProperty( const wxString& label, const wxString& name, wxPGChoices& choices, long value ) : wxPGProperty(label,name) { m_oldChoicesData = NULL; if ( choices.IsOk() ) { m_choices.Assign(choices); wxASSERT( GetItemCount() ); SetValue( value ); } else { m_value = wxPGVariant_Zero; } } wxFlagsProperty::~wxFlagsProperty() { } void wxFlagsProperty::OnSetValue() { if ( !m_choices.IsOk() || !GetItemCount() ) { m_value = wxPGVariant_Zero; } else { long val = m_value.GetLong(); long fullFlags = 0; // normalize the value (i.e. remove extra flags) unsigned int i; const wxPGChoices& choices = m_choices; for ( i = 0; i < GetItemCount(); i++ ) { fullFlags |= choices.GetValue(i); } val &= fullFlags; m_value = val; // Need to (re)init now? if ( GetChildCount() != GetItemCount() || m_choices.GetDataPtr() != m_oldChoicesData ) { Init(); } } long newFlags = m_value; if ( newFlags != m_oldValue ) { // Set child modified states unsigned int i; const wxPGChoices& choices = m_choices; for ( i = 0; i<GetItemCount(); i++ ) { int flag; flag = choices.GetValue(i); if ( (newFlags & flag) != (m_oldValue & flag) ) Item(i)->ChangeFlag( wxPG_PROP_MODIFIED, true ); } m_oldValue = newFlags; } } wxString wxFlagsProperty::ValueToString( wxVariant& value, int WXUNUSED(argFlags) ) const { wxString text; if ( !m_choices.IsOk() ) return text; long flags = value; unsigned int i; const wxPGChoices& choices = m_choices; for ( i = 0; i < GetItemCount(); i++ ) { int doAdd; doAdd = ( flags & choices.GetValue(i) ); if ( doAdd ) { text += choices.GetLabel(i); text += wxS(", "); } } // remove last comma if ( text.Len() > 1 ) text.Truncate ( text.Len() - 2 ); return text; } // Translate string into flag tokens bool wxFlagsProperty::StringToValue( wxVariant& variant, const wxString& text, int ) const { if ( !m_choices.IsOk() ) return false; long newFlags = 0; // semicolons are no longer valid delimeters WX_PG_TOKENIZER1_BEGIN(text,wxS(',')) if ( !token.empty() ) { // Determine which one it is long bit = IdToBit( token ); if ( bit != -1 ) { // Changed? newFlags |= bit; } else { break; } } WX_PG_TOKENIZER1_END() if ( variant != (long)newFlags ) { variant = (long)newFlags; return true; } return false; } // Converts string id to a relevant bit. long wxFlagsProperty::IdToBit( const wxString& id ) const { unsigned int i; for ( i = 0; i < GetItemCount(); i++ ) { if ( id == GetLabel(i) ) { return m_choices.GetValue(i); } } return -1; } void wxFlagsProperty::RefreshChildren() { if ( !m_choices.IsOk() || !GetChildCount() ) return; int flags = m_value.GetLong(); const wxPGChoices& choices = m_choices; unsigned int i; for ( i = 0; i < GetItemCount(); i++ ) { long flag; flag = choices.GetValue(i); long subVal = flags & flag; wxPGProperty* p = Item(i); if ( subVal != (m_oldValue & flag) ) p->ChangeFlag( wxPG_PROP_MODIFIED, true ); p->SetValue( subVal?true:false ); } m_oldValue = flags; } wxVariant wxFlagsProperty::ChildChanged( wxVariant& thisValue, int childIndex, wxVariant& childValue ) const { long oldValue = thisValue.GetLong(); long val = childValue.GetLong(); unsigned long vi = m_choices.GetValue(childIndex); if ( val ) return (long) (oldValue | vi); return (long) (oldValue & ~(vi)); } bool wxFlagsProperty::DoSetAttribute( const wxString& name, wxVariant& value ) { if ( name == wxPG_BOOL_USE_CHECKBOX || name == wxPG_BOOL_USE_DOUBLE_CLICK_CYCLING ) { for ( size_t i=0; i<GetChildCount(); i++ ) { Item(i)->SetAttribute(name, value); } // Must return false so that the attribute is stored in // flag property's actual property storage return false; } return false; } // ----------------------------------------------------------------------- // wxDirProperty // ----------------------------------------------------------------------- IMPLEMENT_DYNAMIC_CLASS(wxDirProperty, wxLongStringProperty) wxDirProperty::wxDirProperty( const wxString& name, const wxString& label, const wxString& value ) : wxLongStringProperty(name,label,value) { m_flags |= wxPG_PROP_NO_ESCAPE; } wxDirProperty::~wxDirProperty() { } wxValidator* wxDirProperty::DoGetValidator() const { return wxFileProperty::GetClassValidator(); } bool wxDirProperty::OnButtonClick( wxPropertyGrid* propGrid, wxString& value ) { // Update property value from editor, if necessary wxSize dlg_sz(300,400); wxString dlgMessage(m_dlgMessage); if ( dlgMessage.empty() ) dlgMessage = _("Choose a directory:"); wxDirDialog dlg( propGrid, dlgMessage, value, 0, #if !wxPG_SMALL_SCREEN propGrid->GetGoodEditorDialogPosition(this,dlg_sz), dlg_sz #else wxDefaultPosition, wxDefaultSize #endif ); if ( dlg.ShowModal() == wxID_OK ) { value = dlg.GetPath(); return true; } return false; } bool wxDirProperty::DoSetAttribute( const wxString& name, wxVariant& value ) { if ( name == wxPG_DIR_DIALOG_MESSAGE ) { m_dlgMessage = value.GetString(); return true; } return false; } // ----------------------------------------------------------------------- // wxPGFileDialogAdapter // ----------------------------------------------------------------------- bool wxPGFileDialogAdapter::DoShowDialog( wxPropertyGrid* propGrid, wxPGProperty* property ) { wxFileProperty* fileProp = NULL; wxString path; int indFilter = -1; if ( wxDynamicCast(property, wxFileProperty) ) { fileProp = ((wxFileProperty*)property); wxFileName filename = fileProp->GetValue().GetString(); path = filename.GetPath(); indFilter = fileProp->m_indFilter; if ( path.empty() && !fileProp->m_basePath.empty() ) path = fileProp->m_basePath; } else { wxFileName fn(property->GetValue().GetString()); path = fn.GetPath(); } wxFileDialog dlg( propGrid->GetPanel(), property->GetAttribute(wxS("DialogTitle"), _("Choose a file")), property->GetAttribute(wxS("InitialPath"), path), wxEmptyString, property->GetAttribute(wxPG_FILE_WILDCARD, wxALL_FILES), property->GetAttributeAsLong(wxPG_FILE_DIALOG_STYLE, 0), wxDefaultPosition ); if ( indFilter >= 0 ) dlg.SetFilterIndex( indFilter ); if ( dlg.ShowModal() == wxID_OK ) { if ( fileProp ) fileProp->m_indFilter = dlg.GetFilterIndex(); SetValue( dlg.GetPath() ); return true; } return false; } // ----------------------------------------------------------------------- // wxFileProperty // ----------------------------------------------------------------------- WX_PG_IMPLEMENT_PROPERTY_CLASS(wxFileProperty,wxPGProperty, wxString,const wxString&,TextCtrlAndButton) wxFileProperty::wxFileProperty( const wxString& label, const wxString& name, const wxString& value ) : wxPGProperty(label,name) { m_flags |= wxPG_PROP_SHOW_FULL_FILENAME; m_indFilter = -1; SetAttribute( wxPG_FILE_WILDCARD, wxALL_FILES); SetValue(value); } wxFileProperty::~wxFileProperty() {} wxValidator* wxFileProperty::GetClassValidator() { #if wxUSE_VALIDATORS WX_PG_DOGETVALIDATOR_ENTRY() // Atleast wxPython 2.6.2.1 required that the string argument is given static wxString v; wxTextValidator* validator = new wxTextValidator(wxFILTER_EXCLUDE_CHAR_LIST,&v); wxArrayString exChars; exChars.Add(wxS("?")); exChars.Add(wxS("*")); exChars.Add(wxS("|")); exChars.Add(wxS("<")); exChars.Add(wxS(">")); exChars.Add(wxS("\"")); validator->SetExcludes(exChars); WX_PG_DOGETVALIDATOR_EXIT(validator) #else return NULL; #endif } wxValidator* wxFileProperty::DoGetValidator() const { return GetClassValidator(); } void wxFileProperty::OnSetValue() { const wxString& fnstr = m_value.GetString(); wxFileName filename = fnstr; if ( !filename.HasName() ) { m_value = wxPGVariant_EmptyString; } // Find index for extension. if ( m_indFilter < 0 && !fnstr.empty() ) { wxString ext = filename.GetExt(); int curind = 0; size_t pos = 0; size_t len = m_wildcard.length(); pos = m_wildcard.find(wxS("|"), pos); while ( pos != wxString::npos && pos < (len-3) ) { size_t ext_begin = pos + 3; pos = m_wildcard.find(wxS("|"), ext_begin); if ( pos == wxString::npos ) pos = len; wxString found_ext = m_wildcard.substr(ext_begin, pos-ext_begin); if ( !found_ext.empty() ) { if ( found_ext[0] == wxS('*') ) { m_indFilter = curind; break; } if ( ext.CmpNoCase(found_ext) == 0 ) { m_indFilter = curind; break; } } if ( pos != len ) pos = m_wildcard.find(wxS("|"), pos+1); curind++; } } } wxFileName wxFileProperty::GetFileName() const { wxFileName filename; if ( !m_value.IsNull() ) filename = m_value.GetString(); return filename; } wxString wxFileProperty::ValueToString( wxVariant& value, int argFlags ) const { wxFileName filename = value.GetString(); if ( !filename.HasName() ) return wxEmptyString; wxString fullName = filename.GetFullName(); if ( fullName.empty() ) return wxEmptyString; if ( argFlags & wxPG_FULL_VALUE ) { return filename.GetFullPath(); } else if ( m_flags & wxPG_PROP_SHOW_FULL_FILENAME ) { if ( !m_basePath.empty() ) { wxFileName fn2(filename); fn2.MakeRelativeTo(m_basePath); return fn2.GetFullPath(); } return filename.GetFullPath(); } return filename.GetFullName(); } wxPGEditorDialogAdapter* wxFileProperty::GetEditorDialog() const { return new wxPGFileDialogAdapter(); } bool wxFileProperty::StringToValue( wxVariant& variant, const wxString& text, int argFlags ) const { wxFileName filename = variant.GetString(); if ( (m_flags & wxPG_PROP_SHOW_FULL_FILENAME) || (argFlags & wxPG_FULL_VALUE) ) { if ( filename != text ) { variant = text; return true; } } else { if ( filename.GetFullName() != text ) { wxFileName fn = filename; fn.SetFullName(text); variant = fn.GetFullPath(); return true; } } return false; } bool wxFileProperty::DoSetAttribute( const wxString& name, wxVariant& value ) { // Return false on some occasions to make sure those attribs will get // stored in m_attributes. if ( name == wxPG_FILE_SHOW_FULL_PATH ) { if ( value.GetLong() ) m_flags |= wxPG_PROP_SHOW_FULL_FILENAME; else m_flags &= ~(wxPG_PROP_SHOW_FULL_FILENAME); return true; } else if ( name == wxPG_FILE_WILDCARD ) { m_wildcard = value.GetString(); } else if ( name == wxPG_FILE_SHOW_RELATIVE_PATH ) { m_basePath = value.GetString(); // Make sure wxPG_FILE_SHOW_FULL_PATH is also set m_flags |= wxPG_PROP_SHOW_FULL_FILENAME; } else if ( name == wxPG_FILE_INITIAL_PATH ) { m_initialPath = value.GetString(); return true; } else if ( name == wxPG_FILE_DIALOG_TITLE ) { m_dlgTitle = value.GetString(); return true; } return false; } // ----------------------------------------------------------------------- // wxPGLongStringDialogAdapter // ----------------------------------------------------------------------- bool wxPGLongStringDialogAdapter::DoShowDialog( wxPropertyGrid* propGrid, wxPGProperty* property ) { wxString val1 = property->GetValueAsString(0); wxString val_orig = val1; wxString value; if ( !property->HasFlag(wxPG_PROP_NO_ESCAPE) ) wxPropertyGrid::ExpandEscapeSequences(value, val1); else value = wxString(val1); // Run editor dialog. if ( wxLongStringProperty::DisplayEditorDialog(property, propGrid, value) ) { if ( !property->HasFlag(wxPG_PROP_NO_ESCAPE) ) wxPropertyGrid::CreateEscapeSequences(val1,value); else val1 = value; if ( val1 != val_orig ) { SetValue( val1 ); return true; } } return false; } // ----------------------------------------------------------------------- // wxLongStringProperty // ----------------------------------------------------------------------- WX_PG_IMPLEMENT_PROPERTY_CLASS(wxLongStringProperty,wxPGProperty, wxString,const wxString&,TextCtrlAndButton) wxLongStringProperty::wxLongStringProperty( const wxString& label, const wxString& name, const wxString& value ) : wxPGProperty(label,name) { SetValue(value); } wxLongStringProperty::~wxLongStringProperty() {} wxString wxLongStringProperty::ValueToString( wxVariant& value, int WXUNUSED(argFlags) ) const { return value; } bool wxLongStringProperty::OnEvent( wxPropertyGrid* propGrid, wxWindow* WXUNUSED(primary), wxEvent& event ) { if ( propGrid->IsMainButtonEvent(event) ) { // Update the value wxVariant useValue = propGrid->GetUncommittedPropertyValue(); wxString val1 = useValue.GetString(); wxString val_orig = val1; wxString value; if ( !(m_flags & wxPG_PROP_NO_ESCAPE) ) wxPropertyGrid::ExpandEscapeSequences(value,val1); else value = wxString(val1); // Run editor dialog. if ( OnButtonClick(propGrid,value) ) { if ( !(m_flags & wxPG_PROP_NO_ESCAPE) ) wxPropertyGrid::CreateEscapeSequences(val1,value); else val1 = value; if ( val1 != val_orig ) { SetValueInEvent( val1 ); return true; } } } return false; } bool wxLongStringProperty::OnButtonClick( wxPropertyGrid* propGrid, wxString& value ) { return DisplayEditorDialog(this, propGrid, value); } bool wxLongStringProperty::DisplayEditorDialog( wxPGProperty* prop, wxPropertyGrid* propGrid, wxString& value ) { // launch editor dialog wxDialog* dlg = new wxDialog(propGrid,-1,prop->GetLabel(),wxDefaultPosition,wxDefaultSize, wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER|wxCLIP_CHILDREN); dlg->SetFont(propGrid->GetFont()); // To allow entering chars of the same set as the propGrid // Multi-line text editor dialog. #if !wxPG_SMALL_SCREEN const int spacing = 8; #else const int spacing = 4; #endif wxBoxSizer* topsizer = new wxBoxSizer( wxVERTICAL ); wxBoxSizer* rowsizer = new wxBoxSizer( wxHORIZONTAL ); wxTextCtrl* ed = new wxTextCtrl(dlg,11,value, wxDefaultPosition,wxDefaultSize,wxTE_MULTILINE); rowsizer->Add( ed, 1, wxEXPAND|wxALL, spacing ); topsizer->Add( rowsizer, 1, wxEXPAND, 0 ); wxStdDialogButtonSizer* buttonSizer = new wxStdDialogButtonSizer(); buttonSizer->AddButton(new wxButton(dlg, wxID_OK)); buttonSizer->AddButton(new wxButton(dlg, wxID_CANCEL)); buttonSizer->Realize(); topsizer->Add( buttonSizer, 0, wxALIGN_RIGHT|wxALIGN_CENTRE_VERTICAL|wxBOTTOM|wxRIGHT, spacing ); dlg->SetSizer( topsizer ); topsizer->SetSizeHints( dlg ); #if !wxPG_SMALL_SCREEN dlg->SetSize(400,300); dlg->Move( propGrid->GetGoodEditorDialogPosition(prop,dlg->GetSize()) ); #endif int res = dlg->ShowModal(); if ( res == wxID_OK ) { value = ed->GetValue(); dlg->Destroy(); return true; } dlg->Destroy(); return false; } bool wxLongStringProperty::StringToValue( wxVariant& variant, const wxString& text, int ) const { if ( variant != text ) { variant = text; return true; } return false; } #if wxUSE_EDITABLELISTBOX // ----------------------------------------------------------------------- // wxPGArrayEditorDialog // ----------------------------------------------------------------------- BEGIN_EVENT_TABLE(wxPGArrayEditorDialog, wxDialog) EVT_IDLE(wxPGArrayEditorDialog::OnIdle) END_EVENT_TABLE() IMPLEMENT_ABSTRACT_CLASS(wxPGArrayEditorDialog, wxDialog) #include "wx/editlbox.h" #include "wx/listctrl.h" // ----------------------------------------------------------------------- void wxPGArrayEditorDialog::OnIdle(wxIdleEvent& event) { // Repair focus - wxEditableListBox has bitmap buttons, which // get focus, and lose focus (into the oblivion) when they // become disabled due to change in control state. wxWindow* lastFocused = m_lastFocused; wxWindow* focus = ::wxWindow::FindFocus(); // If last focused control became disabled, set focus back to // wxEditableListBox if ( lastFocused && focus != lastFocused && lastFocused->GetParent() == m_elbSubPanel && !lastFocused->IsEnabled() ) { m_elb->GetListCtrl()->SetFocus(); } m_lastFocused = focus; event.Skip(); } // ----------------------------------------------------------------------- wxPGArrayEditorDialog::wxPGArrayEditorDialog() : wxDialog() { Init(); } // ----------------------------------------------------------------------- void wxPGArrayEditorDialog::Init() { m_lastFocused = NULL; m_hasCustomNewAction = false; m_itemPendingAtIndex = -1; } // ----------------------------------------------------------------------- wxPGArrayEditorDialog::wxPGArrayEditorDialog( wxWindow *parent, const wxString& message, const wxString& caption, long style, const wxPoint& pos, const wxSize& sz ) : wxDialog() { Init(); Create(parent,message,caption,style,pos,sz); } // ----------------------------------------------------------------------- bool wxPGArrayEditorDialog::Create( wxWindow *parent, const wxString& message, const wxString& caption, long style, const wxPoint& pos, const wxSize& sz ) { // On wxMAC the dialog shows incorrectly if style is not exactly wxCAPTION // FIXME: This should be only a temporary fix. #ifdef __WXMAC__ wxUnusedVar(style); int useStyle = wxCAPTION; #else int useStyle = style; #endif bool res = wxDialog::Create(parent, wxID_ANY, caption, pos, sz, useStyle); SetFont(parent->GetFont()); // To allow entering chars of the same set as the propGrid #if !wxPG_SMALL_SCREEN const int spacing = 4; #else const int spacing = 3; #endif m_modified = false; wxBoxSizer* topsizer = new wxBoxSizer( wxVERTICAL ); // Message if ( !message.empty() ) topsizer->Add( new wxStaticText(this,-1,message), 0, wxALIGN_LEFT|wxALIGN_CENTRE_VERTICAL|wxALL, spacing ); m_elb = new wxEditableListBox(this, wxID_ANY, message, wxDefaultPosition, wxDefaultSize, wxEL_ALLOW_NEW | wxEL_ALLOW_EDIT | wxEL_ALLOW_DELETE); // Populate the list box wxArrayString arr; for ( unsigned int i=0; i<ArrayGetCount(); i++ ) arr.push_back(ArrayGet(i)); m_elb->SetStrings(arr); // Connect event handlers wxButton* but; wxListCtrl* lc = m_elb->GetListCtrl(); but = m_elb->GetNewButton(); m_elbSubPanel = but->GetParent(); but->Connect(but->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(wxPGArrayEditorDialog::OnAddClick), NULL, this); but = m_elb->GetDelButton(); but->Connect(but->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(wxPGArrayEditorDialog::OnDeleteClick), NULL, this); but = m_elb->GetUpButton(); but->Connect(but->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(wxPGArrayEditorDialog::OnUpClick), NULL, this); but = m_elb->GetDownButton(); but->Connect(but->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(wxPGArrayEditorDialog::OnDownClick), NULL, this); lc->Connect(lc->GetId(), wxEVT_COMMAND_LIST_END_LABEL_EDIT, wxListEventHandler(wxPGArrayEditorDialog::OnEndLabelEdit), NULL, this); topsizer->Add( m_elb, 1, wxEXPAND, spacing ); // Standard dialog buttons wxStdDialogButtonSizer* buttonSizer = new wxStdDialogButtonSizer(); buttonSizer->AddButton(new wxButton(this, wxID_OK)); buttonSizer->AddButton(new wxButton(this, wxID_CANCEL)); buttonSizer->Realize(); topsizer->Add( buttonSizer, 0, wxALIGN_RIGHT|wxALIGN_CENTRE_VERTICAL|wxALL, spacing ); m_elb->SetFocus(); SetSizer( topsizer ); topsizer->SetSizeHints( this ); #if !wxPG_SMALL_SCREEN if ( sz.x == wxDefaultSize.x && sz.y == wxDefaultSize.y ) SetSize( wxSize(275,360) ); else SetSize(sz); #endif return res; } // ----------------------------------------------------------------------- int wxPGArrayEditorDialog::GetSelection() const { wxListCtrl* lc = m_elb->GetListCtrl(); int index = lc->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED); if ( index == -1 ) return wxNOT_FOUND; return index; } // ----------------------------------------------------------------------- void wxPGArrayEditorDialog::OnAddClick(wxCommandEvent& event) { wxListCtrl* lc = m_elb->GetListCtrl(); int newItemIndex = lc->GetItemCount() - 1; if ( m_hasCustomNewAction ) { wxString str; if ( OnCustomNewAction(&str) ) { if ( ArrayInsert(str, newItemIndex) ) { lc->InsertItem(newItemIndex, str); m_modified = true; } } // Do *not* skip the event! We do not want the wxEditableListBox // to do anything. } else { m_itemPendingAtIndex = newItemIndex; event.Skip(); } } // ----------------------------------------------------------------------- void wxPGArrayEditorDialog::OnDeleteClick(wxCommandEvent& event) { int index = GetSelection(); if ( index >= 0 ) { ArrayRemoveAt( index ); m_modified = true; } event.Skip(); } // ----------------------------------------------------------------------- void wxPGArrayEditorDialog::OnUpClick(wxCommandEvent& event) { int index = GetSelection(); if ( index > 0 ) { ArraySwap(index-1,index); m_modified = true; } event.Skip(); } // ----------------------------------------------------------------------- void wxPGArrayEditorDialog::OnDownClick(wxCommandEvent& event) { wxListCtrl* lc = m_elb->GetListCtrl(); int index = GetSelection(); int lastStringIndex = lc->GetItemCount() - 1; if ( index >= 0 && index < lastStringIndex ) { ArraySwap(index, index+1); m_modified = true; } event.Skip(); } // ----------------------------------------------------------------------- void wxPGArrayEditorDialog::OnEndLabelEdit(wxListEvent& event) { wxString str = event.GetLabel(); if ( m_itemPendingAtIndex >= 0 ) { // Add a new item if ( ArrayInsert(str, m_itemPendingAtIndex) ) { m_modified = true; } else { // Editable list box doesn't really respect Veto(), but // it recognizes if no text was added, so we simulate // Veto() using it. event.m_item.SetText(wxEmptyString); m_elb->GetListCtrl()->SetItemText(m_itemPendingAtIndex, wxEmptyString); event.Veto(); } } else { // Change an existing item int index = GetSelection(); wxASSERT( index != wxNOT_FOUND ); if ( ArraySet(index, str) ) m_modified = true; else event.Veto(); } event.Skip(); } #endif // wxUSE_EDITABLELISTBOX // ----------------------------------------------------------------------- // wxPGArrayStringEditorDialog // ----------------------------------------------------------------------- IMPLEMENT_DYNAMIC_CLASS(wxPGArrayStringEditorDialog, wxPGArrayEditorDialog) BEGIN_EVENT_TABLE(wxPGArrayStringEditorDialog, wxPGArrayEditorDialog) END_EVENT_TABLE() // ----------------------------------------------------------------------- wxString wxPGArrayStringEditorDialog::ArrayGet( size_t index ) { return m_array[index]; } size_t wxPGArrayStringEditorDialog::ArrayGetCount() { return m_array.size(); } bool wxPGArrayStringEditorDialog::ArrayInsert( const wxString& str, int index ) { if (index<0) m_array.Add(str); else m_array.Insert(str,index); return true; } bool wxPGArrayStringEditorDialog::ArraySet( size_t index, const wxString& str ) { m_array[index] = str; return true; } void wxPGArrayStringEditorDialog::ArrayRemoveAt( int index ) { m_array.RemoveAt(index); } void wxPGArrayStringEditorDialog::ArraySwap( size_t first, size_t second ) { wxString old_str = m_array[first]; wxString new_str = m_array[second]; m_array[first] = new_str; m_array[second] = old_str; } wxPGArrayStringEditorDialog::wxPGArrayStringEditorDialog() : wxPGArrayEditorDialog() { Init(); } void wxPGArrayStringEditorDialog::Init() { m_pCallingClass = NULL; } bool wxPGArrayStringEditorDialog::OnCustomNewAction(wxString* resString) { return m_pCallingClass->OnCustomStringEdit(m_parent, *resString); } // ----------------------------------------------------------------------- // wxArrayStringProperty // ----------------------------------------------------------------------- WX_PG_IMPLEMENT_PROPERTY_CLASS(wxArrayStringProperty, // Property name wxPGProperty, // Property we inherit from wxArrayString, // Value type name const wxArrayString&, // Value type, as given in constructor TextCtrlAndButton) // Initial editor wxArrayStringProperty::wxArrayStringProperty( const wxString& label, const wxString& name, const wxArrayString& array ) : wxPGProperty(label,name) { m_delimiter = ','; SetValue( array ); } wxArrayStringProperty::~wxArrayStringProperty() { } void wxArrayStringProperty::OnSetValue() { GenerateValueAsString(); } void wxArrayStringProperty::ConvertArrayToString(const wxArrayString& arr, wxString* pString, const wxUniChar& delimiter) const { if ( delimiter == '"' || delimiter == '\'' ) { // Quoted strings ArrayStringToString(*pString, arr, delimiter, Escape | QuoteStrings); } else { // Regular delimiter ArrayStringToString(*pString, arr, delimiter, 0); } } wxString wxArrayStringProperty::ValueToString( wxVariant& WXUNUSED(value), int argFlags ) const { // // If this is called from GetValueAsString(), return cached string if ( argFlags & wxPG_VALUE_IS_CURRENT ) { return m_display; } wxArrayString arr = m_value.GetArrayString(); wxString s; ConvertArrayToString(arr, &s, m_delimiter); return s; } // Converts wxArrayString to a string separated by delimeters and spaces. // preDelim is useful for "str1" "str2" style. Set flags to 1 to do slash // conversion. void wxArrayStringProperty::ArrayStringToString( wxString& dst, const wxArrayString& src, wxUniChar delimiter, int flags ) { wxString pdr; wxString preas; unsigned int i; unsigned int itemCount = src.size(); dst.Empty(); if ( flags & Escape ) { preas = delimiter; pdr = wxS("\\") + static_cast<wchar_t>(delimiter); } if ( itemCount ) dst.append( preas ); wxString delimStr(delimiter); for ( i = 0; i < itemCount; i++ ) { wxString str( src.Item(i) ); // Do some character conversion. // Converts \ to \\ and $delimiter to \$delimiter // Useful when quoting. if ( flags & Escape ) { str.Replace( wxS("\\"), wxS("\\\\"), true ); if ( !pdr.empty() ) str.Replace( preas, pdr, true ); } dst.append( str ); if ( i < (itemCount-1) ) { dst.append( delimStr ); dst.append( wxS(" ") ); dst.append( preas ); } else if ( flags & QuoteStrings ) dst.append( delimStr ); } } void wxArrayStringProperty::GenerateValueAsString() { wxArrayString arr = m_value.GetArrayString(); ConvertArrayToString(arr, &m_display, m_delimiter); } // Default implementation doesn't do anything. bool wxArrayStringProperty::OnCustomStringEdit( wxWindow*, wxString& ) { return false; } wxPGArrayEditorDialog* wxArrayStringProperty::CreateEditorDialog() { return new wxPGArrayStringEditorDialog(); } bool wxArrayStringProperty::OnButtonClick( wxPropertyGrid* propGrid, wxWindow* WXUNUSED(primaryCtrl), const wxChar* cbt ) { // Update the value wxVariant useValue = propGrid->GetUncommittedPropertyValue(); if ( !propGrid->EditorValidate() ) return false; // Create editor dialog. wxPGArrayEditorDialog* dlg = CreateEditorDialog(); #if wxUSE_VALIDATORS wxValidator* validator = GetValidator(); wxPGInDialogValidator dialogValidator; #endif wxPGArrayStringEditorDialog* strEdDlg = wxDynamicCast(dlg, wxPGArrayStringEditorDialog); if ( strEdDlg ) strEdDlg->SetCustomButton(cbt, this); dlg->SetDialogValue( useValue ); dlg->Create(propGrid, wxEmptyString, m_label); #if !wxPG_SMALL_SCREEN dlg->Move( propGrid->GetGoodEditorDialogPosition(this,dlg->GetSize()) ); #endif bool retVal; for (;;) { retVal = false; int res = dlg->ShowModal(); if ( res == wxID_OK && dlg->IsModified() ) { wxVariant value = dlg->GetDialogValue(); if ( !value.IsNull() ) { wxArrayString actualValue = value.GetArrayString(); wxString tempStr; ConvertArrayToString(actualValue, &tempStr, m_delimiter); #if wxUSE_VALIDATORS if ( dialogValidator.DoValidate(propGrid, validator, tempStr) ) #endif { SetValueInEvent( actualValue ); retVal = true; break; } } else break; } else break; } delete dlg; return retVal; } bool wxArrayStringProperty::OnEvent( wxPropertyGrid* propGrid, wxWindow* primary, wxEvent& event ) { if ( propGrid->IsMainButtonEvent(event) ) return OnButtonClick(propGrid,primary,(const wxChar*) NULL); return false; } bool wxArrayStringProperty::StringToValue( wxVariant& variant, const wxString& text, int ) const { wxArrayString arr; if ( m_delimiter == '"' || m_delimiter == '\'' ) { // Quoted strings WX_PG_TOKENIZER2_BEGIN(text, m_delimiter) // Need to replace backslashes with empty characters // (opposite what is done in ConvertArrayToString()). token.Replace ( wxS("\\\\"), wxS("\\"), true ); arr.Add( token ); WX_PG_TOKENIZER2_END() } else { // Regular delimiter WX_PG_TOKENIZER1_BEGIN(text, m_delimiter) arr.Add( token ); WX_PG_TOKENIZER1_END() } variant = arr; return true; } bool wxArrayStringProperty::DoSetAttribute( const wxString& name, wxVariant& value ) { if ( name == wxPG_ARRAY_DELIMITER ) { m_delimiter = value.GetChar(); GenerateValueAsString(); return false; } return true; } // ----------------------------------------------------------------------- // wxPGInDialogValidator // ----------------------------------------------------------------------- #if wxUSE_VALIDATORS bool wxPGInDialogValidator::DoValidate( wxPropertyGrid* propGrid, wxValidator* validator, const wxString& value ) { if ( !validator ) return true; wxTextCtrl* tc = m_textCtrl; if ( !tc ) { { tc = new wxTextCtrl( propGrid, wxPG_SUBID_TEMP1, wxEmptyString, wxPoint(30000,30000)); tc->Hide(); } m_textCtrl = tc; } tc->SetValue(value); validator->SetWindow(tc); bool res = validator->Validate(propGrid); return res; } #else bool wxPGInDialogValidator::DoValidate( wxPropertyGrid* WXUNUSED(propGrid), wxValidator* WXUNUSED(validator), const wxString& WXUNUSED(value) ) { return true; } #endif // ----------------------------------------------------------------------- #endif // wxUSE_PROPGRID
26.638344
113
0.543388
wivlaro
146932c4f16d0460bd1ae613ca1b5851eaed0b9a
1,098
cpp
C++
Qualification_Round_2/Editorials/cutting_paper_tester.cpp
manojpandey/CodeSprint_India_2014
91ecfc9f565f20ae7517f556a0c414990a84e0d8
[ "MIT" ]
null
null
null
Qualification_Round_2/Editorials/cutting_paper_tester.cpp
manojpandey/CodeSprint_India_2014
91ecfc9f565f20ae7517f556a0c414990a84e0d8
[ "MIT" ]
null
null
null
Qualification_Round_2/Editorials/cutting_paper_tester.cpp
manojpandey/CodeSprint_India_2014
91ecfc9f565f20ae7517f556a0c414990a84e0d8
[ "MIT" ]
2
2015-07-25T11:44:07.000Z
2019-07-14T11:33:48.000Z
#include<bits/stdc++.h> using namespace std; int mat[101][101]; void solve() { mat[0][0] = 0; mat[0][1] = 0; mat[1][0] = 0; for(int i = 1; i <= 100; i++) { mat[i][1] = i; mat[1][i] = i; } for(int i = 2; i <= 100; i++) { for(int j = 2; j <= 100; j++) { int min = i * j, val; if(i == j) { min = 1; } else { for(int k = 1; k < i; k++) { val = mat[k][j] + mat[i - k][j]; if(val < min) min = val; } for(int k = 1; k < j; k++) { val = mat[i][k] + mat[i][j - k]; if(val < min) min = val; } } mat[i][j] = min; } } } int main() { int n, x, y; cin >> n; solve(); for(int i = 0; i < n; i++) { cin >> x >> y; cout << mat[x][y] << endl; } return 0; }
18.931034
52
0.264117
manojpandey
146bc487becac75c3f0629a658fd1aa5d58c7bcf
13,052
cpp
C++
src/SwingCompiler.cpp
SilverJun/SWING
0a9c35d74b3ec75d349a14a59e4d731dbd016069
[ "MIT" ]
8
2017-07-17T16:12:20.000Z
2021-02-20T13:18:33.000Z
src/SwingCompiler.cpp
SilverJun/SWING
0a9c35d74b3ec75d349a14a59e4d731dbd016069
[ "MIT" ]
null
null
null
src/SwingCompiler.cpp
SilverJun/SWING
0a9c35d74b3ec75d349a14a59e4d731dbd016069
[ "MIT" ]
1
2020-02-19T06:51:03.000Z
2020-02-19T06:51:03.000Z
#include "SwingCompiler.h" #include <fstream> #include <sstream> #include "llvm/Support/TargetSelect.h" #include "Type.h" #include "Method.h" #include "StructType.h" #include "ProtocolType.h" #include <iostream> #include "Error.h" #include "FunctionDeclAST.h" namespace swing { std::unique_ptr<SwingCompiler> SwingCompiler::_instance; std::once_flag SwingCompiler::_InitInstance; SwingCompiler::SwingCompiler() : _module("SwingCompiler", _llvmContext), _builder({ llvm::IRBuilder<>(_llvmContext) }), _src(nullptr) { llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmParser(); llvm::InitializeNativeTargetAsmPrinter(); llvm::InitializeNativeTargetDisassembler(); /// built-in Operators _binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Additive, { "+", TokenID::Arithmetic_Add, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Additive })); _binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Additive, { "-", TokenID::Arithmetic_Subtract, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Additive })); _binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Multiplicative, { "*", TokenID::Arithmetic_Multiply, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Multiplicative })); _binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Multiplicative, { "/", TokenID::Arithmetic_Divide, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Multiplicative })); _binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Multiplicative, { "%", TokenID::Arithmetic_Modulo, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Multiplicative })); //_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Multiplicative, { "**", TokenID::Arithmetic_Power, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Multiplicative })); _binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Assignment, { "=", TokenID::Assignment, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Assignment })); /* _binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Bitwise, { "&", TokenID::Bitwise_And, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Bitwise })); _binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Bitwise, { "|", TokenID::Bitwise_Or, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Bitwise })); _binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Bitwise, { "^", TokenID::Bitwise_Xor, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Bitwise })); _binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Bitwise, { ">>", TokenID::Bitwise_ShiftRight, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Bitwise })); _binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Bitwise, { "<<", TokenID::Bitwise_ShiftLeft, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Bitwise })); */ _binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Logical, { "&&", TokenID::Logical_And, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Logical })); _binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Logical, { "||", TokenID::Logical_Or, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Logical })); _binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Relational, { "==", TokenID::Relational_Equal, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Relational })); _binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Relational, { "!=", TokenID::Relational_NotEqual, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Relational })); _binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Relational, { ">", TokenID::Relational_Greater, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Relational })); _binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Relational, { ">=", TokenID::Relational_GreaterEqual, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Relational })); _binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Relational, { "<", TokenID::Relational_Less, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Relational })); _binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Relational, { "<=", TokenID::Relational_LessEqual, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Relational })); //_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Default, { "...", TokenID::Range_Closed, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Default })); //_binOperators.insert(std::pair<int, OperatorType>(OperatorType::Precedence_Default, { "..<", TokenID::Range_Opened, OperatorType::OperatorLocation::Infix, OperatorType::Precedence_Default })); _binOperators.insert(std::pair<int, OperatorType>(70, { "as", TokenID::Casting_As, OperatorType::OperatorLocation::Infix, 70 })); _binOperators.insert(std::pair<int, OperatorType>(70, { "is", TokenID::Casting_Is, OperatorType::OperatorLocation::Infix, 70 })); _binOperators.insert(std::pair<int, OperatorType>(80, { ".", TokenID::MemberReference, OperatorType::OperatorLocation::Infix, 80 })); _preOperators.push_back(OperatorType("!", TokenID::Logical_Not, OperatorType::OperatorLocation::Prefix, OperatorType::Precedence_Logical)); _preOperators.push_back(OperatorType("-", TokenID::Arithmetic_Subtract, OperatorType::OperatorLocation::Prefix, OperatorType::Precedence_Multiplicative)); //_preOperators.push_back(OperatorType("~", TokenID::Bitwise_Not, OperatorType::OperatorLocation::Prefix, OperatorType::Precedence_Bitwise)); //_postOperators.push_back(OperatorType("?", TokenID::Optional_Nilable, OperatorType::OperatorLocation::Postfix, OperatorType::Precedence_Default)); //_postOperators.push_back(OperatorType("!", TokenID::Optional_Binding, OperatorType::OperatorLocation::Postfix, OperatorType::Precedence_Default)); } std::vector<OperatorType*> SwingCompiler::FindOps(int precedenceLevel) { auto range = _binOperators.equal_range(precedenceLevel); std::vector<OperatorType*> ops; if (precedenceLevel >= OperatorType::Precedence_Max) return ops; for (auto value = range.first; value != range.second; ++value) ops.push_back(&value->second); return ops; } OperatorType* SwingCompiler::FindPreFixOp(std::string op) { for (auto value = _preOperators.begin(); value != _preOperators.end(); ++value) { if (value->_opString == op) return &*value; } return nullptr; } OperatorType* SwingCompiler::FindPostFixOp(std::string op) { for (auto value = _postOperators.begin(); value != _postOperators.end(); ++value) { if (value->_opString == op) return &*value; } return nullptr; } void SwingCompiler::AddOperator(OperatorType* op) { /// TODO : 기능 구현. } void SwingCompiler::AddFunction(std::string name, Method* func) { _functions[name] = func; } Method* SwingCompiler::GetFunction(std::string name) { return _functions[name]; } void SwingCompiler::ImplementFunctionLazy(Method* method) { auto ast = new FunctionDeclAST(); ast->_method = method; _src->_sourceAST.push_back(BaseAST::BasePtr(ast)); _src->_sourceAST.shrink_to_fit(); } SwingCompiler* SwingCompiler::GetInstance() { std::call_once(_InitInstance, []() { _instance.reset(new SwingCompiler); }); return _instance.get(); } SwingCompiler::~SwingCompiler() { } void SwingCompiler::Initialize() { /// built-in types _types["void"] = Void; _types["bool"] = Bool; _types["char"] = Char; _types["int"] = Int; _types["float"] = Float; _types["double"] = Double; SwingTable::_localTable.push_back(&_globalTable); std::string line; std::fstream libfile = std::fstream(_swingPath + "libs.txt"); std::string libPath; if (!libfile.is_open()) { std::cout << "libs.txt is not open!"<< std::endl; exit(1); } while (getline(libfile, line)) { std::istringstream iss(line); if (!(iss >> libPath) || line == "") continue; _libs.push_back(libPath); } if (_libs.size() == 0) { std::cout << "libs.txt is empty!" << std::endl; exit(1); } } void SwingCompiler::PushIRBuilder(llvm::IRBuilder<> builder) { _builder.push_back(builder); } void SwingCompiler::PopIRBuilder() { _builder.pop_back(); } llvm::Type * SwingCompiler::GetType(std::string name) { llvm::Type* type = nullptr; type = _types[name]; if (type == nullptr) { _structs[name]->CreateStructType(); type = _types[name]; //type = _structs[name]->_type; } return type; } void SwingCompiler::BreakCurrentBlock() { if (_breakBlocks.size() == 0) throw Error("Can't apply break statement, not in the loop."); _breakBlocks.pop_back(); //_builder.back().CreateBr(_breakBlocks.back()); } llvm::BasicBlock* SwingCompiler::GetEndBlock() { return _breakBlocks.back(); } void SwingCompiler::CompileSource(std::string name, std::string output) { Initialize(); _src = new Source(name); g_Module.setSourceFileName(_src->_name); auto iter = name.rbegin(); for (; iter != name.rend(); ++iter) { if (*iter == '\\') break; } _outputPath = output == "" ? std::string(iter.base(), name.end()) : output; if (_outputPath.back() != '\\') _outputPath.push_back('\\'); Lexer lex; try { lex.LexSource(_src); _src->Parse(); _src->CodeGen(); } catch (LexicalError& e) { std::cout << e.what() << std::endl; system("pause"); exit(-1); } catch (ParsingError& e) { std::cout << e.what() << std::endl; system("pause"); exit(-1); } catch (Error& e) { std::cout << e.what() << std::endl; system("pause"); exit(-1); } /*catch (const std::exception& e) { std::cout << e.what() << std::endl; system("pause"); exit(-1); }*/ /// llc std::string cmd("llc"); cmd += ' '; cmd += "-filetype=obj"; cmd += ' '; cmd += _outputPath + "Test.ll"; cmd += ' '; cmd += "-o " + _outputPath + "Test.obj"; system(cmd.c_str()); std::cout << "Successfully Compiled." << std::endl; } void SwingCompiler::LinkSource(std::string name, std::string output) { Initialize(); std::string cmd; /// cl cmd = "clang-cl"; cmd += ' '; cmd += "-o" + _outputPath + "Test.exe"; cmd += ' '; cmd += name; cmd += ' '; for (auto libPath : _libs) { cmd += libPath; cmd += ' '; } system(cmd.c_str()); std::cout << "Successfully Linked." << std::endl; cmd = _outputPath + "Test.exe"; int retval = system(cmd.c_str()); std::cout << std::endl; std::cout << "SwingCompiler> Program Return " << retval << std::endl << std::endl; } void SwingCompiler::BuildSource(std::string name, std::string output) { Initialize(); _src = new Source(name); g_Module.setSourceFileName(_src->_name); auto iter = name.rbegin(); for (; iter != name.rend(); ++iter) { if (*iter == '\\') break; } _outputPath = output == "" ? std::string(iter.base(), name.end()) : output; if (_outputPath.back() != '\\') _outputPath.push_back('\\'); Lexer lex; try { lex.LexSource(_src); _src->Parse(); _src->CodeGen(); } catch (LexicalError& e) { std::cout << e.what() << std::endl; system("pause"); exit(-1); } catch (ParsingError& e) { std::cout << e.what() << std::endl; system("pause"); exit(-1); } catch (Error& e) { std::cout << e.what() << std::endl; system("pause"); exit(-1); } /*catch (const std::exception& e) { std::cout << e.what() << std::endl; system("pause"); exit(-1); }*/ /// llc std::string cmd("llc"); cmd += ' '; cmd += "-filetype=obj"; cmd += ' '; cmd += _outputPath + "Test.ll"; cmd += ' '; cmd += "-o " + _outputPath + "Test.obj"; system(cmd.c_str()); /// cl cmd = "clang-cl"; cmd += ' '; cmd += "-o" + _outputPath + "Test.exe"; cmd += ' '; cmd += _outputPath + "Test.obj"; cmd += ' '; for (auto libPath : _libs) { cmd += libPath; cmd += ' '; } system(cmd.c_str()); std::cout << "Successfully Built." << std::endl; cmd = _outputPath + "Test.exe"; int retval = system(cmd.c_str()); std::cout << std::endl; std::cout << "SwingCompiler> Program Return " << retval << std::endl << std::endl; } /*void SwingCompiler::CompileProject(Project* project, int optLevel, std::string outputFormat) { project->CompileProject(optLevel, outputFormat); } void SwingCompiler::LinkProject(Project* project) { project->LinkProject(); } void SwingCompiler::BuildProject(Project* project) { CompileProject(project, 0, ".obj"); LinkProject(project); }*/ }
31.990196
213
0.690699
SilverJun
146c552bb08d097cab3c561a85b5ec36e7bfe2d8
4,482
cc
C++
sdk/test/metrics/histogram_aggregator_test.cc
padmaja-nadkarni/opentelemetry-cpp
4751ae5a29e5eeed1b775b7c337bdbe294165346
[ "Apache-2.0" ]
2
2020-06-26T15:26:35.000Z
2020-06-28T16:47:35.000Z
sdk/test/metrics/histogram_aggregator_test.cc
padmaja-nadkarni/opentelemetry-cpp
4751ae5a29e5eeed1b775b7c337bdbe294165346
[ "Apache-2.0" ]
3
2020-07-08T22:36:00.000Z
2020-08-26T16:21:07.000Z
sdk/test/metrics/histogram_aggregator_test.cc
padmaja-nadkarni/opentelemetry-cpp
4751ae5a29e5eeed1b775b7c337bdbe294165346
[ "Apache-2.0" ]
4
2020-05-27T22:08:57.000Z
2020-05-29T19:13:11.000Z
#include "opentelemetry/sdk/metrics/aggregator/histogram_aggregator.h" #include <gtest/gtest.h> #include <iostream> #include <numeric> #include <thread> // #include <chrono> namespace metrics_api = opentelemetry::metrics; OPENTELEMETRY_BEGIN_NAMESPACE namespace sdk { namespace metrics { // Test updating with a uniform set of updates TEST(Histogram, Uniform) { std::vector<double> boundaries{10, 20, 30, 40, 50}; HistogramAggregator<int> alpha(metrics_api::InstrumentKind::Counter, boundaries); EXPECT_EQ(alpha.get_aggregator_kind(), AggregatorKind::Histogram); alpha.checkpoint(); EXPECT_EQ(alpha.get_checkpoint().size(), 2); EXPECT_EQ(alpha.get_counts().size(), 6); for (int i = 0; i < 60; i++) { alpha.update(i); } alpha.checkpoint(); EXPECT_EQ(alpha.get_checkpoint()[0], 1770); EXPECT_EQ(alpha.get_checkpoint()[1], 60); std::vector<int> correct = {10, 10, 10, 10, 10, 10}; EXPECT_EQ(alpha.get_counts(), correct); } // Test updating with a normal distribution TEST(Histogram, Normal) { std::vector<double> boundaries{2, 4, 6, 8, 10, 12}; HistogramAggregator<int> alpha(metrics_api::InstrumentKind::Counter, boundaries); std::vector<int> vals{1, 3, 3, 5, 5, 5, 7, 7, 7, 7, 9, 9, 9, 11, 11, 13}; for (int i : vals) { alpha.update(i); } alpha.checkpoint(); EXPECT_EQ(alpha.get_checkpoint()[0], std::accumulate(vals.begin(), vals.end(), 0)); EXPECT_EQ(alpha.get_checkpoint()[1], vals.size()); std::vector<int> correct = {1, 2, 3, 4, 3, 2, 1}; EXPECT_EQ(alpha.get_counts(), correct); } TEST(Histogram, Merge) { std::vector<double> boundaries{2, 4, 6, 8, 10, 12}; HistogramAggregator<int> alpha(metrics_api::InstrumentKind::Counter, boundaries); HistogramAggregator<int> beta(metrics_api::InstrumentKind::Counter, boundaries); std::vector<int> vals{1, 3, 3, 5, 5, 5, 7, 7, 7, 7, 9, 9, 9, 11, 11, 13}; for (int i : vals) { alpha.update(i); } std::vector<int> otherVals{1, 1, 1, 1, 11, 11, 13, 13, 13, 15}; for (int i : otherVals) { beta.update(i); } alpha.merge(beta); alpha.checkpoint(); EXPECT_EQ(alpha.get_checkpoint()[0], std::accumulate(vals.begin(), vals.end(), 0) + std::accumulate(otherVals.begin(), otherVals.end(), 0)); EXPECT_EQ(alpha.get_checkpoint()[1], vals.size() + otherVals.size()); std::vector<int> correct = {5, 2, 3, 4, 3, 4, 5}; EXPECT_EQ(alpha.get_counts(), correct); } // Update callback used to validate multi-threaded performance void histogramUpdateCallback(Aggregator<int> &agg, std::vector<int> vals) { for (int i : vals) { agg.update(i); } } int randVal() { return rand() % 15; } TEST(Histogram, Concurrency) { std::vector<double> boundaries{2, 4, 6, 8, 10, 12}; HistogramAggregator<int> alpha(metrics_api::InstrumentKind::Counter, boundaries); std::vector<int> vals1(1000); std::generate(vals1.begin(), vals1.end(), randVal); std::vector<int> vals2(1000); std::generate(vals2.begin(), vals2.end(), randVal); std::thread first(histogramUpdateCallback, std::ref(alpha), vals1); std::thread second(histogramUpdateCallback, std::ref(alpha), vals2); first.join(); second.join(); HistogramAggregator<int> beta(metrics_api::InstrumentKind::Counter, boundaries); // Timing harness to compare linear and binary insertion // auto start = std::chrono::system_clock::now(); for (int i : vals1) { beta.update(i); } for (int i : vals2) { beta.update(i); } // auto end = std::chrono::system_clock::now(); // auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start); // std::cout <<"Update time: " <<elapsed.count() <<std::endl; alpha.checkpoint(); beta.checkpoint(); EXPECT_EQ(alpha.get_checkpoint(), beta.get_checkpoint()); EXPECT_EQ(alpha.get_counts(), beta.get_counts()); } #if __EXCEPTIONS TEST(Histogram, Errors) { std::vector<double> boundaries{2, 4, 6, 8, 10, 12}; std::vector<double> boundaries2{1, 4, 6, 8, 10, 12}; std::vector<double> unsortedBoundaries{10, 12, 4, 6, 8}; EXPECT_ANY_THROW( HistogramAggregator<int> alpha(metrics_api::InstrumentKind::Counter, unsortedBoundaries)); HistogramAggregator<int> beta(metrics_api::InstrumentKind::Counter, boundaries); HistogramAggregator<int> gamma(metrics_api::InstrumentKind::Counter, boundaries2); EXPECT_ANY_THROW(beta.merge(gamma)); } #endif } // namespace metrics } // namespace sdk OPENTELEMETRY_END_NAMESPACE
26.678571
99
0.676261
padmaja-nadkarni
146f86d183582cec69a730b2040e6f7acad0f3f1
2,485
cc
C++
Source/Plugins/SubsystemPlugins/BladeGame/source/interface_imp/GameWorldData.cc
OscarGame/blade
6987708cb011813eb38e5c262c7a83888635f002
[ "MIT" ]
146
2018-12-03T08:08:17.000Z
2022-03-21T06:04:06.000Z
Source/Plugins/SubsystemPlugins/BladeGame/source/interface_imp/GameWorldData.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
1
2019-01-18T03:35:49.000Z
2019-01-18T03:36:08.000Z
Source/Plugins/SubsystemPlugins/BladeGame/source/interface_imp/GameWorldData.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
31
2018-12-03T10:32:43.000Z
2021-10-04T06:31:44.000Z
/******************************************************************** created: 2011/05/03 filename: GameWorldData.cc author: Crazii purpose: *********************************************************************/ #include <BladePCH.h> #include "GameWorldData.h" #include <interface/public/graphics/IGraphicsScene.h> #include <interface/public/graphics/IGraphicsSpaceCoordinator.h> #include "GameWorld.h" namespace Blade { const TString GameWorldData::GAME_WORLD_DATA_TYPE = BTString("GameWorldData"); const TString GameWorldData::WORLD_NAME = BTString("Name"); const TString GameWorldData::WORLD_SART_POS = BTString("StartPosition"); ////////////////////////////////////////////////////////////////////////// GameWorldData::GameWorldData() :mScene(NULL) ,mCamera(NULL) { mStartPostition = Vector3::ZERO; } ////////////////////////////////////////////////////////////////////////// GameWorldData::~GameWorldData() { if(mScene != NULL && mScene->getSpaceCoordinator() != NULL) mScene->getSpaceCoordinator()->setPositionReference(NULL); } /************************************************************************/ /* ISerializable interface */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// void GameWorldData::prepareSave() { mStartPostition = this->getPosition(); } ////////////////////////////////////////////////////////////////////////// void GameWorldData::postProcess(const ProgressNotifier& /*callback*/) { if(mScene != NULL && mScene->getSpaceCoordinator() != NULL) mScene->getSpaceCoordinator()->setPositionReference(this); } /************************************************************************/ /* custom methods */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// void GameWorldData::setGraphicsScene(IGraphicsScene* scene) { mScene = scene; if(mScene != NULL && mScene->getSpaceCoordinator() != NULL) mScene->getSpaceCoordinator()->setPositionReference(this); } ////////////////////////////////////////////////////////////////////////// void GameWorldData::onConfigChange(const void* data) { if( data == &mStartPostition ) { } } }//namespace Blade
36.014493
98
0.426559
OscarGame
1471da20d296f07168d10e313d63602c9ddc7654
15,291
cpp
C++
OsirisInventory/Memory.cpp
danielkrupinski/OsirisInventory
e4716de9b05d0c257a1733d96c503e64104b3657
[ "MIT" ]
31
2021-07-08T12:24:40.000Z
2022-03-07T11:24:53.000Z
OsirisInventory/Memory.cpp
danielkrupinski/OsirisInventory
e4716de9b05d0c257a1733d96c503e64104b3657
[ "MIT" ]
21
2021-07-21T11:39:16.000Z
2022-03-24T02:03:26.000Z
OsirisInventory/Memory.cpp
danielkrupinski/OsirisInventory
e4716de9b05d0c257a1733d96c503e64104b3657
[ "MIT" ]
8
2021-12-05T11:29:21.000Z
2022-03-06T06:21:51.000Z
#include <algorithm> #include <array> #include <cassert> #include <cstring> #include <limits> #include <string_view> #include <utility> #ifdef _WIN32 #include <Windows.h> #include <Psapi.h> #elif __linux__ #include <fcntl.h> #include <link.h> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> #endif #include "Interfaces.h" #include "Memory.h" #include "SDK/LocalPlayer.h" template <typename T> static constexpr auto relativeToAbsolute(uintptr_t address) noexcept { return (T)(address + 4 + *reinterpret_cast<std::int32_t*>(address)); } static std::pair<void*, std::size_t> getModuleInformation(const char* name) noexcept { #ifdef _WIN32 if (HMODULE handle = GetModuleHandleA(name)) { if (MODULEINFO moduleInfo; GetModuleInformation(GetCurrentProcess(), handle, &moduleInfo, sizeof(moduleInfo))) return std::make_pair(moduleInfo.lpBaseOfDll, moduleInfo.SizeOfImage); } return {}; #elif __linux__ struct ModuleInfo { const char* name; void* base = nullptr; std::size_t size = 0; } moduleInfo; moduleInfo.name = name; dl_iterate_phdr([](struct dl_phdr_info* info, std::size_t, void* data) { const auto moduleInfo = reinterpret_cast<ModuleInfo*>(data); if (!std::string_view{ info->dlpi_name }.ends_with(moduleInfo->name)) return 0; if (const auto fd = open(info->dlpi_name, O_RDONLY); fd >= 0) { if (struct stat st; fstat(fd, &st) == 0) { if (const auto map = mmap(nullptr, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); map != MAP_FAILED) { const auto ehdr = (ElfW(Ehdr)*)map; const auto shdrs = (ElfW(Shdr)*)(std::uintptr_t(ehdr) + ehdr->e_shoff); const auto strTab = (const char*)(std::uintptr_t(ehdr) + shdrs[ehdr->e_shstrndx].sh_offset); for (auto i = 0; i < ehdr->e_shnum; ++i) { const auto shdr = (ElfW(Shdr)*)(std::uintptr_t(shdrs) + i * ehdr->e_shentsize); if (std::strcmp(strTab + shdr->sh_name, ".text") != 0) continue; moduleInfo->base = (void*)(info->dlpi_addr + shdr->sh_offset); moduleInfo->size = shdr->sh_size; munmap(map, st.st_size); close(fd); return 1; } munmap(map, st.st_size); } } close(fd); } moduleInfo->base = (void*)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr); moduleInfo->size = info->dlpi_phdr[0].p_memsz; return 1; }, &moduleInfo); return std::make_pair(moduleInfo.base, moduleInfo.size); #endif } [[nodiscard]] static auto generateBadCharTable(std::string_view pattern) noexcept { assert(!pattern.empty()); std::array<std::size_t, (std::numeric_limits<std::uint8_t>::max)() + 1> table; auto lastWildcard = pattern.rfind('?'); if (lastWildcard == std::string_view::npos) lastWildcard = 0; const auto defaultShift = (std::max)(std::size_t(1), pattern.length() - 1 - lastWildcard); table.fill(defaultShift); for (auto i = lastWildcard; i < pattern.length() - 1; ++i) table[static_cast<std::uint8_t>(pattern[i])] = pattern.length() - 1 - i; return table; } static std::uintptr_t findPattern(const char* moduleName, std::string_view pattern, bool reportNotFound = true) noexcept { static auto id = 0; ++id; const auto [moduleBase, moduleSize] = getModuleInformation(moduleName); if (moduleBase && moduleSize) { const auto lastIdx = pattern.length() - 1; const auto badCharTable = generateBadCharTable(pattern); auto start = static_cast<const char*>(moduleBase); const auto end = start + moduleSize - pattern.length(); while (start <= end) { int i = lastIdx; while (i >= 0 && (pattern[i] == '?' || start[i] == pattern[i])) --i; if (i < 0) return reinterpret_cast<std::uintptr_t>(start); start += badCharTable[static_cast<std::uint8_t>(start[lastIdx])]; } } assert(false); #ifdef _WIN32 if (reportNotFound) MessageBoxA(nullptr, ("Failed to find pattern #" + std::to_string(id) + '!').c_str(), "Osiris", MB_OK | MB_ICONWARNING); #endif return 0; } Memory::Memory() noexcept { #ifdef _WIN32 present = findPattern("gameoverlayrenderer", "\xFF\x15????\x8B\xF0\x85\xFF") + 2; reset = findPattern("gameoverlayrenderer", "\xC7\x45?????\xFF\x15????\x8B\xD8") + 9; globalVars = **reinterpret_cast<GlobalVars***>((*reinterpret_cast<uintptr_t**>(interfaces->client))[11] + 10); auto temp = reinterpret_cast<std::uintptr_t*>(findPattern(CLIENT_DLL, "\xB9????\xE8????\x8B\x5D\x08") + 1); hud = *temp; findHudElement = relativeToAbsolute<decltype(findHudElement)>(reinterpret_cast<uintptr_t>(temp) + 5); clearHudWeapon = relativeToAbsolute<decltype(clearHudWeapon)>(findPattern(CLIENT_DLL, "\xE8????\x8B\xF0\xC6\x44\x24??\xC6\x44\x24") + 1); itemSystem = relativeToAbsolute<decltype(itemSystem)>(findPattern(CLIENT_DLL, "\xE8????\x0F\xB7\x0F") + 1); const auto tier0 = GetModuleHandleW(L"tier0"); debugMsg = reinterpret_cast<decltype(debugMsg)>(GetProcAddress(tier0, "Msg")); conColorMsg = reinterpret_cast<decltype(conColorMsg)>(GetProcAddress(tier0, "?ConColorMsg@@YAXABVColor@@PBDZZ")); equipWearable = reinterpret_cast<decltype(equipWearable)>(findPattern(CLIENT_DLL, "\x55\x8B\xEC\x83\xEC\x10\x53\x8B\x5D\x08\x57\x8B\xF9")); weaponSystem = *reinterpret_cast<WeaponSystem**>(findPattern(CLIENT_DLL, "\x8B\x35????\xFF\x10\x0F\xB7\xC0") + 2); getEventDescriptor = relativeToAbsolute<decltype(getEventDescriptor)>(findPattern(ENGINE_DLL, "\xE8????\x8B\xD8\x85\xDB\x75\x27") + 1); playerResource = *reinterpret_cast<PlayerResource***>(findPattern(CLIENT_DLL, "\x74\x30\x8B\x35????\x85\xF6") + 4); registeredPanoramaEvents = reinterpret_cast<decltype(registeredPanoramaEvents)>(*reinterpret_cast<std::uintptr_t*>(findPattern(CLIENT_DLL, "\xE8????\xA1????\xA8\x01\x75\x21") + 6) - 36); makePanoramaSymbolFn = relativeToAbsolute<decltype(makePanoramaSymbolFn)>(findPattern(CLIENT_DLL, "\xE8????\x0F\xB7\x45\x0E\x8D\x4D\x0E") + 1); inventoryManager = *reinterpret_cast<InventoryManager**>(findPattern(CLIENT_DLL, "\x8D\x44\x24\x28\xB9") + 5); createEconItemSharedObject = *reinterpret_cast<decltype(createEconItemSharedObject)*>(findPattern(CLIENT_DLL, "\x55\x8B\xEC\x83\xEC\x1C\x8D\x45\xE4\xC7\x45") + 20); addEconItem = relativeToAbsolute<decltype(addEconItem)>(findPattern(CLIENT_DLL, "\xE8????\x84\xC0\x74\xE7") + 1); clearInventoryImageRGBA = reinterpret_cast<decltype(clearInventoryImageRGBA)>(findPattern(CLIENT_DLL, "\x55\x8B\xEC\x81\xEC????\x57\x8B\xF9\xC7\x47")); panoramaMarshallHelper = *reinterpret_cast<decltype(panoramaMarshallHelper)*>(findPattern(CLIENT_DLL, "\x68????\x8B\xC8\xE8????\x8D\x4D\xF4\xFF\x15????\x8B\xCF\xFF\x15????\x5F\x5E\x8B\xE5\x5D\xC3") + 1); setStickerToolSlotGetArgAsNumberReturnAddress = findPattern(CLIENT_DLL, "\xFF\xD2\xDD\x5C\x24\x10\xF2\x0F\x2C\x7C\x24") + 2; setStickerToolSlotGetArgAsStringReturnAddress = setStickerToolSlotGetArgAsNumberReturnAddress - 49; wearItemStickerGetArgAsNumberReturnAddress = findPattern(CLIENT_DLL, "\xDD\x5C\x24\x18\xF2\x0F\x2C\x7C\x24?\x85\xFF"); wearItemStickerGetArgAsStringReturnAddress = wearItemStickerGetArgAsNumberReturnAddress - 80; setNameToolStringGetArgAsStringReturnAddress = findPattern(CLIENT_DLL, "\x8B\xF8\xC6\x45\x08?\x33\xC0"); clearCustomNameGetArgAsStringReturnAddress = findPattern(CLIENT_DLL, "\xFF\x50\x1C\x8B\xF0\x85\xF6\x74\x21") + 3; deleteItemGetArgAsStringReturnAddress = findPattern(CLIENT_DLL, "\x85\xC0\x74\x22\x51"); setStatTrakSwapToolItemsGetArgAsStringReturnAddress1 = findPattern(CLIENT_DLL, "\x85\xC0\x74\x7E\x8B\xC8\xE8????\x8B\x37"); setStatTrakSwapToolItemsGetArgAsStringReturnAddress2 = setStatTrakSwapToolItemsGetArgAsStringReturnAddress1 + 44; acknowledgeNewItemByItemIDGetArgAsStringReturnAddress = findPattern(CLIENT_DLL, "\x85\xC0\x74\x33\x8B\xC8\xE8????\xB9"); findOrCreateEconItemViewForItemID = relativeToAbsolute<decltype(findOrCreateEconItemViewForItemID)>(findPattern(CLIENT_DLL, "\xE8????\x8B\xCE\x83\xC4\x08") + 1); getInventoryItemByItemID = relativeToAbsolute<decltype(getInventoryItemByItemID)>(findPattern(CLIENT_DLL, "\xE8????\x8B\x33\x8B\xD0") + 1); useToolGetArgAsStringReturnAddress = findPattern(CLIENT_DLL, "\x85\xC0\x0F\x84????\x8B\xC8\xE8????\x8B\x37"); useToolGetArg2AsStringReturnAddress = useToolGetArgAsStringReturnAddress + 52; getSOCData = relativeToAbsolute<decltype(getSOCData)>(findPattern(CLIENT_DLL, "\xE8????\x32\xC9") + 1); setCustomName = relativeToAbsolute<decltype(setCustomName)>(findPattern(CLIENT_DLL, "\xE8????\x8B\x46\x78\xC1\xE8\x0A\xA8\x01\x74\x13\x8B\x46\x34") + 1); setDynamicAttributeValueFn = findPattern(CLIENT_DLL, "\x55\x8B\xEC\x83\xE4\xF8\x83\xEC\x3C\x53\x8B\x5D\x08\x56\x57\x6A"); createBaseTypeCache = relativeToAbsolute<decltype(createBaseTypeCache)>(findPattern(CLIENT_DLL, "\xE8????\x8D\x4D\x0F") + 1); uiComponentInventory = *reinterpret_cast<void***>(findPattern(CLIENT_DLL, "\xC6\x44\x24??\x83\x3D") + 7); setItemSessionPropertyValue = relativeToAbsolute<decltype(setItemSessionPropertyValue)>(findPattern(CLIENT_DLL, "\xE8????\x8B\x4C\x24\x2C\x46") + 1); localPlayer.init(*reinterpret_cast<Entity***>(findPattern(CLIENT_DLL, "\xA1????\x89\x45\xBC\x85\xC0") + 1)); #else const auto tier0 = dlopen(TIER0_DLL, RTLD_NOLOAD | RTLD_NOW); debugMsg = decltype(debugMsg)(dlsym(tier0, "Msg")); conColorMsg = decltype(conColorMsg)(dlsym(tier0, "_Z11ConColorMsgRK5ColorPKcz")); dlclose(tier0); const auto libSDL = dlopen("libSDL2-2.0.so.0", RTLD_LAZY | RTLD_NOLOAD); pollEvent = relativeToAbsolute<uintptr_t>(uintptr_t(dlsym(libSDL, "SDL_PollEvent")) + 2); swapWindow = relativeToAbsolute<uintptr_t>(uintptr_t(dlsym(libSDL, "SDL_GL_SwapWindow")) + 2); dlclose(libSDL); globalVars = *relativeToAbsolute<GlobalVars**>((*reinterpret_cast<std::uintptr_t**>(interfaces->client))[11] + 16); itemSystem = relativeToAbsolute<decltype(itemSystem)>(findPattern(CLIENT_DLL, "\xE8????\x4D\x63\xEC") + 1); weaponSystem = *relativeToAbsolute<WeaponSystem**>(findPattern(CLIENT_DLL, "\x48\x8B\x58\x10\x48\x8B\x07\xFF\x10") + 12); hud = relativeToAbsolute<decltype(hud)>(findPattern(CLIENT_DLL, "\x53\x48\x8D\x3D????\x48\x83\xEC\x10\xE8") + 4); findHudElement = relativeToAbsolute<decltype(findHudElement)>(findPattern(CLIENT_DLL, "\xE8????\x48\x8D\x50\xE0") + 1); playerResource = relativeToAbsolute<PlayerResource**>(findPattern(CLIENT_DLL, "\x74\x38\x48\x8B\x3D????\x89\xDE") + 5); getEventDescriptor = relativeToAbsolute<decltype(getEventDescriptor)>(findPattern(ENGINE_DLL, "\xE8????\x48\x85\xC0\x74\x62") + 1); clearHudWeapon = relativeToAbsolute<decltype(clearHudWeapon)>(findPattern(CLIENT_DLL, "\xE8????\xC6\x45\xB8\x01") + 1); equipWearable = reinterpret_cast<decltype(equipWearable)>(findPattern(CLIENT_DLL, "\x55\x48\x89\xE5\x41\x56\x41\x55\x41\x54\x49\x89\xF4\x53\x48\x89\xFB\x48\x83\xEC\x10\x48\x8B\x07")); registeredPanoramaEvents = relativeToAbsolute<decltype(registeredPanoramaEvents)>(relativeToAbsolute<std::uintptr_t>(findPattern(CLIENT_DLL, "\xE8????\x8B\x50\x10\x49\x89\xC6") + 1) + 12); makePanoramaSymbolFn = relativeToAbsolute<decltype(makePanoramaSymbolFn)>(findPattern(CLIENT_DLL, "\xE8????\x0F\xB7\x45\xA0\x31\xF6") + 1); inventoryManager = relativeToAbsolute<decltype(inventoryManager)>(findPattern(CLIENT_DLL, "\x48\x8D\x35????\x48\x8D\x3D????\xE9????\x90\x90\x90\x55") + 3); createEconItemSharedObject = relativeToAbsolute<decltype(createEconItemSharedObject)>(findPattern(CLIENT_DLL, "\x55\x48\x8D\x05????\x31\xD2\x4C\x8D\x0D") + 50); addEconItem = relativeToAbsolute<decltype(addEconItem)>(findPattern(CLIENT_DLL, "\xE8????\x45\x3B\x65\x28\x72\xD6") + 1); clearInventoryImageRGBA = relativeToAbsolute<decltype(clearInventoryImageRGBA)>(findPattern(CLIENT_DLL, "\xE8????\x83\xC3\x01\x49\x83\xC4\x08\x41\x3B\x5D\x50") + 1); panoramaMarshallHelper = relativeToAbsolute<decltype(panoramaMarshallHelper)>(findPattern(CLIENT_DLL, "\xF3\x0F\x11\x05????\x48\x89\x05????\x48\xC7\x05????????\xC7\x05") + 11); setStickerToolSlotGetArgAsNumberReturnAddress = findPattern(CLIENT_DLL, "\xF2\x44\x0F\x2C\xF0\x45\x85\xF6\x78\x32"); setStickerToolSlotGetArgAsStringReturnAddress = setStickerToolSlotGetArgAsNumberReturnAddress - 46; findOrCreateEconItemViewForItemID = relativeToAbsolute<decltype(findOrCreateEconItemViewForItemID)>(findPattern(CLIENT_DLL, "\xE8????\x4C\x89\xEF\x48\x89\x45\xC8") + 1); getInventoryItemByItemID = relativeToAbsolute<decltype(getInventoryItemByItemID)>(findPattern(CLIENT_DLL, "\xE8????\x45\x84\xED\x49\x89\xC1") + 1); getSOCData = relativeToAbsolute<decltype(getSOCData)>(findPattern(CLIENT_DLL, "\xE8????\x5B\x44\x89\xEE") + 1); setCustomName = relativeToAbsolute<decltype(setCustomName)>(findPattern(CLIENT_DLL, "\xE8????\x41\x8B\x84\x24????\xE9????\x8B\x98") + 1); useToolGetArgAsStringReturnAddress = findPattern(CLIENT_DLL, "\x48\x85\xC0\x74\xDA\x48\x89\xC7\xE8????\x48\x8B\x0B"); useToolGetArg2AsStringReturnAddress = useToolGetArgAsStringReturnAddress + 55; wearItemStickerGetArgAsNumberReturnAddress = findPattern(CLIENT_DLL, "\xF2\x44\x0F\x2C\xF8\x45\x39\xFE"); wearItemStickerGetArgAsStringReturnAddress = wearItemStickerGetArgAsNumberReturnAddress - 57; setNameToolStringGetArgAsStringReturnAddress = findPattern(CLIENT_DLL, "\xBA????\x4C\x89\xF6\x48\x89\xC7\x49\x89\xC4"); clearCustomNameGetArgAsStringReturnAddress = findPattern(CLIENT_DLL, "\x48\x85\xC0\x74\xE5\x48\x89\xC7\xE8????\x49\x89\xC4"); deleteItemGetArgAsStringReturnAddress = findPattern(CLIENT_DLL, "\x48\x85\xC0\x74\xDE\x48\x89\xC7\xE8????\x48\x89\xC3\xE8????\x48\x89\xDE"); setDynamicAttributeValueFn = findPattern(CLIENT_DLL, "\x41\x8B\x06\x49\x8D\x7D\x08") - 95; createBaseTypeCache = relativeToAbsolute<decltype(createBaseTypeCache)>(findPattern(CLIENT_DLL, "\xE8????\x48\x89\xDE\x5B\x48\x8B\x10") + 1); uiComponentInventory = relativeToAbsolute<decltype(uiComponentInventory)>(findPattern(CLIENT_DLL, "\xE8????\x4C\x89\x3D????\x4C\x89\xFF\xEB\x9E") + 8); setItemSessionPropertyValue = relativeToAbsolute<decltype(setItemSessionPropertyValue)>(findPattern(CLIENT_DLL, "\xE8????\x48\x8B\x85????\x41\x83\xC4\x01") + 1); setStatTrakSwapToolItemsGetArgAsStringReturnAddress1 = findPattern(CLIENT_DLL, "\x74\x84\x4C\x89\xEE\x4C\x89\xF7\xE8????\x48\x85\xC0") - 86; setStatTrakSwapToolItemsGetArgAsStringReturnAddress2 = setStatTrakSwapToolItemsGetArgAsStringReturnAddress1 + 55; acknowledgeNewItemByItemIDGetArgAsStringReturnAddress = findPattern(CLIENT_DLL, "\x48\x89\xC7\xE8????\x4C\x89\xEF\x48\x89\xC6\xE8????\x48\x8B\x0B") - 5; localPlayer.init(relativeToAbsolute<Entity**>(findPattern(CLIENT_DLL, "\x83\xFF\xFF\x48\x8B\x05") + 6)); #endif }
62.158537
207
0.703943
danielkrupinski
14759b72b661dd3dc94bee2b69b06a9d624bbf83
3,324
cpp
C++
src/common/buses/network/TCPIPv4SocketBus.cpp
udyni/seabreeze
3d3934f8f0df61c11cef70516cf62a8472cab974
[ "MIT" ]
null
null
null
src/common/buses/network/TCPIPv4SocketBus.cpp
udyni/seabreeze
3d3934f8f0df61c11cef70516cf62a8472cab974
[ "MIT" ]
null
null
null
src/common/buses/network/TCPIPv4SocketBus.cpp
udyni/seabreeze
3d3934f8f0df61c11cef70516cf62a8472cab974
[ "MIT" ]
1
2020-07-03T08:36:47.000Z
2020-07-03T08:36:47.000Z
/***************************************************//** * @file TCPIPv4SocketBus.cpp * @date February 2016 * @author Ocean Optics, Inc. * * LICENSE: * * SeaBreeze Copyright (C) 2016, Ocean Optics Inc * * 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 "common/buses/network/TCPIPv4SocketBus.h" #include "common/buses/BusFamilies.h" #include <cstddef> using namespace seabreeze; using namespace std; TCPIPv4SocketBus::TCPIPv4SocketBus() { this->deviceLocator = NULL; } TCPIPv4SocketBus::~TCPIPv4SocketBus() { if(NULL != this->deviceLocator) { delete this->deviceLocator; } clearHelpers(); } Socket *TCPIPv4SocketBus::getSocketDescriptor() { return this->socket; } BusFamily TCPIPv4SocketBus::getBusFamily() const { TCPIPv4BusFamily family; return family; } void TCPIPv4SocketBus::setLocation( const DeviceLocatorInterface &location) throw (IllegalArgumentException) { if(NULL != this->deviceLocator) { delete this->deviceLocator; } this->deviceLocator = location.clone(); } DeviceLocatorInterface *TCPIPv4SocketBus::getLocation() { return this->deviceLocator; } void TCPIPv4SocketBus::addHelper(ProtocolHint *hint, TransferHelper *helper) { this->helperKeys.push_back(hint); this->helperValues.push_back(helper); } void TCPIPv4SocketBus::clearHelpers() { for(unsigned int i = 0; i < this->helperKeys.size(); i++) { delete this->helperKeys[i]; delete this->helperValues[i]; } this->helperKeys.resize(0); this->helperValues.resize(0); } TransferHelper *TCPIPv4SocketBus::getHelper(const vector<ProtocolHint *> &hints) const { /* Just grab the first hint and use that to look up a helper. * The helpers for Ocean Optics USB devices are 1:1 with respect to hints. */ /* Note: this should really be done with a map or hashmap, but I am just not able * to get that to work (it was returning bad values). Feel free to reimplement * this in a cleaner fashion. */ unsigned int i; for(i = 0; i < this->helperKeys.size(); i++) { if((*(this->helperKeys[i])) == (*hints[0])) { return this->helperValues[i]; } } return NULL; }
32.588235
88
0.679904
udyni
1477b1da3f5a6f2bf0785334beaf19fdd22eacc1
1,609
hpp
C++
header/p6_side_panel.hpp
Meta-chan/P6
2323f3f12894d2eb01a777643f69301a368f9c69
[ "MIT" ]
null
null
null
header/p6_side_panel.hpp
Meta-chan/P6
2323f3f12894d2eb01a777643f69301a368f9c69
[ "MIT" ]
null
null
null
header/p6_side_panel.hpp
Meta-chan/P6
2323f3f12894d2eb01a777643f69301a368f9c69
[ "MIT" ]
null
null
null
/* This software is distributed under MIT License, which means: - Do whatever you want - Please keep this notice and include the license file to your project - I provide no warranty Created by Kyrylo Sovailo (github.com/Meta-chan, k.sovailo@gmail.com) Reinventing bicycles since 2020 */ #ifndef P6_SIDE_PANEL #define P6_SIDE_PANEL #include "p6_node_bar.hpp" #include "p6_stick_bar.hpp" #include "p6_force_bar.hpp" #include "p6_material_bar.hpp" #include "p6_move_bar.hpp" #include <wx/wx.h> namespace p6 { class Frame; ///Side panel is container that displays one of bars class SidePanel { private: ///List of available bars enum class Bar { node, stick, force, move, material }; Frame *_frame; ///<Application's window wxPanel *_panel; ///<wxWidget's panel wxBoxSizer *_sizer; ///<Sizer of wxWidget's panel NodeBar _node_bar; ///<Node bar StickBar _stick_bar; ///<Stick bar ForceBar _force_bar; ///<Force bar MaterialBar _material_bar; ///<Material bar MoveBar _move_bar; ///<Move bar Bar _bar = Bar::material; ///<Bar being displayed void _switch(Bar bar); ///<Show certain bar public: SidePanel(Frame *frame) noexcept; ///<Creates side panel wxPanel *panel() noexcept; ///<Returns wxWidget's panel wxBoxSizer *sizer() noexcept; ///<Returns wxWidget's sizer MoveBar *move_bar() noexcept; ///<Returns move bar void refresh() noexcept; ///<Refreshes contents of bar's components, except choice boxes void refresh_materials() noexcept; ///<Refreshes contents of choice boxes }; } #endif
26.377049
93
0.697328
Meta-chan
147907f259fe06961c980374d4046b8f6e8cc18e
6,733
cpp
C++
ds2/lib_demonsaw/component/router/router_idle_component.cpp
demonsaw/Code
b036d455e9e034d7fd178e63d5e992242d62989a
[ "MIT" ]
132
2017-03-22T03:46:38.000Z
2022-03-08T15:08:16.000Z
ds2/lib_demonsaw/component/router/router_idle_component.cpp
demonsaw/Code
b036d455e9e034d7fd178e63d5e992242d62989a
[ "MIT" ]
4
2017-04-06T17:46:10.000Z
2018-08-08T18:27:59.000Z
ds2/lib_demonsaw/component/router/router_idle_component.cpp
demonsaw/Code
b036d455e9e034d7fd178e63d5e992242d62989a
[ "MIT" ]
30
2017-03-26T22:38:17.000Z
2021-11-21T20:50:17.000Z
// // The MIT License(MIT) // // Copyright(c) 2014 Demonsaw LLC // // 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 <thread> #include <boost/format.hpp> #include "router_component.h" #include "router_idle_component.h" #include "router_option_component.h" #include "component/session_component.h" #include "component/spam_component.h" #include "component/timeout_component.h" #include "component/client/client_component.h" #include "component/group/group_component.h" #include "component/transfer/chunk_component.h" #include "entity/entity.h" #include "utility/default_value.h" namespace eja { // Callback bool router_idle_component::on_run() { on_client(); on_spam(); on_transfer(); return idle_component::on_run(); } // Client void router_idle_component::on_client() { try { const auto owner = get_entity(); const auto option = owner->get<router_option_component>(); if (!option) return; const auto session_map = owner->get<session_entity_map_component>(); if (!session_map) return; for (const auto& entity : session_map->get_list()) { const auto timeout = entity->get<timeout_component>(); if (timeout && timeout->expired(option->get_client_timeout())) { if (entity->has<client_component>()) remove_client(entity); else remove_transfer(entity); } } } catch (std::exception& e) { log(e); } catch (...) { log(); } } void router_idle_component::remove_client(const entity::ptr entity) { try { // Entity const auto owner = get_entity(); const auto entity_map = owner->get<entity_map_component>(); if (entity_map) { const std::string& entity_id = entity->get_id(); entity_map->remove(entity_id); } // Session const auto session_map = owner->get<session_entity_map_component>(); if (session_map) { const auto session = entity->get<session_component>(); if (session) { const std::string& session_id = session->get_id(); session_map->remove(session_id); } } // Client const auto client_map = owner->get<client_entity_map_component>(); if (client_map) { const auto client = entity->get<client_component>(); if (client) { const std::string& client_id = client->get_id(); client_map->remove(client_id); call(function_type::client, function_action::remove, entity); } } // Group const auto group_map = owner->get<group_entity_map_component>(); if (group_map) { const auto group = entity->get<group_component>(); if (group) { const std::string& group_id = group->get_id(); const auto group_entity = group_map->get(group_id); if (group_entity) { const auto entity_map = group_entity->get<entity_map_component>(); if (entity_map) { entity_map->remove(entity->get_id()); if (entity_map->empty()) { group_map->remove(group_id); call(function_type::group, function_action::remove, group_entity); } else { call(function_type::group, function_action::refresh, group_entity); } } } } } // Spam remove_spam(entity); } catch (std::exception& e) { log(e); } catch (...) { log(); } } // Spam void router_idle_component::on_spam() { try { const auto owner = get_entity(); const auto option = owner->get<router_option_component>(); if (!option) return; const auto spam_map = owner->get<spam_entity_map_component>(); if (!spam_map) return; for (const auto& entity : spam_map->get_list()) { // Spam timeout const auto spam_timeout = entity->get<spam_timeout_component>(); if (spam_timeout && spam_timeout->expired(option->get_spam_timeout())) remove_spam(entity); } } catch (std::exception& e) { log(e); } catch (...) { log(); } } void router_idle_component::remove_spam(const entity::ptr entity) { try { // Chunk const auto owner = get_entity(); const auto spam_map = owner->get<spam_entity_map_component>(); if (spam_map) { const auto client = entity->get<client_component>(); if (client) spam_map->remove(client->get_id()); } } catch (std::exception& e) { log(e); } catch (...) { log(); } } // Transfer void router_idle_component::on_transfer() { try { const auto owner = get_entity(); const auto option = owner->get<router_option_component>(); if (!option) return; const auto chunk_map = owner->get<chunk_entity_map_component>(); if (!chunk_map) return; for (const auto& entity : chunk_map->get_list()) { // Transfer timeout (>= 1 chunks) const auto timeout = entity->get<timeout_component>(); if (timeout && timeout->expired(option->get_transfer_timeout())) { // Queue timeout (0 chunks) const auto download_queue = entity->get<chunk_download_queue_component>(); if (download_queue && !download_queue->get_chunk_size() && !timeout->expired(option->get_queue_timeout())) continue; remove_transfer(entity); } } } catch (std::exception& e) { log(e); } catch (...) { log(); } } void router_idle_component::remove_transfer(const entity::ptr entity) { try { // Chunk const auto owner = get_entity(); const auto chunk_map = owner->get<chunk_entity_map_component>(); if (chunk_map) { const auto& entity_id = entity->get_id(); chunk_map->remove(entity_id); call(function_type::transfer, function_action::remove, entity); } } catch (std::exception& e) { log(e); } catch (...) { log(); } } }
23.297578
111
0.655428
demonsaw
147b12c0fc00d5ec514f907043bb5151e513d59b
12,821
cc
C++
tests/test_csp.cc
RReverser/libwebp2
c90b5b476004c9a98731ae1c175cebab5de50fbf
[ "Apache-2.0" ]
4
2020-11-10T17:46:57.000Z
2022-03-22T06:24:17.000Z
tests/test_csp.cc
RReverser/libwebp2
c90b5b476004c9a98731ae1c175cebab5de50fbf
[ "Apache-2.0" ]
null
null
null
tests/test_csp.cc
RReverser/libwebp2
c90b5b476004c9a98731ae1c175cebab5de50fbf
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 Google LLC // // 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. // ----------------------------------------------------------------------------- // // Test CSPTransform::Import() and Export() with different CspTypes. #include <cstdio> #include <string> #include <tuple> #include "examples/example_utils.h" #include "imageio/image_dec.h" #include "include/helpers.h" #include "src/dsp/math.h" #include "src/utils/csp.h" #include "src/utils/plane.h" #include "src/wp2/decode.h" #include "src/wp2/encode.h" namespace WP2 { namespace { //------------------------------------------------------------------------------ class CspTest : public ::testing::TestWithParam<Csp> {}; TEST_P(CspTest, Ranges) { const Csp csp_type = GetParam(); CSPTransform transf; ASSERT_WP2_OK(transf.Init(csp_type)); int32_t min[3] = {0}, max[3] = {0}; for (uint32_t i = 0; i < 3; ++i) { for (uint32_t j = 0; j < 3; ++j) { const int16_t rgb_min = 0 - transf.GetRgbAverage()[j]; const int16_t rgb_max = kRgbMax - transf.GetRgbAverage()[j]; const int32_t coeff = transf.GetRgbToYuvMatrix()[i * 3 + j]; min[i] += coeff * ((coeff > 0) ? rgb_min : rgb_max); max[i] += coeff * ((coeff > 0) ? rgb_max : rgb_min); } } const float norm = 1.f / (1 << 12u); for (uint32_t i = 0; i < 3; ++i) { min[i] = std::round(min[i] * norm); max[i] = std::round(max[i] * norm); } transf.Print(); printf("======== Min / Max ==== \n"); for (uint32_t i = 0; i < 3; ++i) { const int16_t min_value = min[i]; const int16_t max_value = max[i]; printf("[%d %d]", min_value, max_value); // Check min/max values fit within YUV precision bits. // TODO(maryla): these are higher bounds for now but it would be nice to // track actual min/max values. EXPECT_LE(std::abs(min_value), 1 << transf.GetYUVPrecisionBits()); EXPECT_LT(std::abs(max_value), 1 << transf.GetYUVPrecisionBits()); } // Check we couldn't be using fewer bits. const int32_t global_min = std::min({min[0], min[1], min[2]}); const int32_t global_max = std::max({max[0], max[1], max[2]}); EXPECT_EQ(global_min, transf.GetYUVMin()); EXPECT_EQ(global_max, transf.GetYUVMax()); EXPECT_GT(std::abs(global_min), 1 << (transf.GetYUVPrecisionBits() - 1)); EXPECT_GT(std::abs(global_max), 1 << (transf.GetYUVPrecisionBits() - 1)); printf("\nNorms:\n {"); for (uint32_t i = 0; i < 3; ++i) { printf("%.3f, ", (float)(max[i] - min[i]) / kRgbMax); } printf("}\n"); uint32_t kExpectedYUVBits[kNumCspTypes] = {/* YCoCg */ 9, /* YCbCr */ 9, /* Custom, not tested */ 0, /* YIQ */ 9}; EXPECT_EQ(transf.GetYUVPrecisionBits(), kExpectedYUVBits[(uint32_t)csp_type]); } TEST_P(CspTest, Precision) { const Csp csp_type = GetParam(); // YCoCg is the only lossless conversion from and to RGB. const int16_t error_margin = (csp_type == Csp::kYCoCg) ? 0 : 1; CSPTransform transf; ASSERT_WP2_OK(transf.Init(csp_type)); double error_sum = 0., error_avg = 0.; uint32_t num_values = 0; // Test some Argb combinations. It is easier than testing YUV combinations // that lead to valid Argb. constexpr int32_t kStep = 7; for (int16_t r = 0; r < (int16_t)kRgbMax + kStep; r += kStep) { for (int16_t g = 0; g < (int16_t)kRgbMax + kStep; g += kStep) { for (int16_t b = 0; b < (int16_t)kRgbMax + kStep; b += kStep) { // Make sure valid extremes are tested. const int16_t in_r = std::min(r, (int16_t)kRgbMax); const int16_t in_g = std::min(g, (int16_t)kRgbMax); const int16_t in_b = std::min(b, (int16_t)kRgbMax); int16_t in_y, in_u, in_v; transf.ToYUV(in_r, in_g, in_b, &in_y, &in_u, &in_v); int16_t out_r, out_g, out_b; transf.ToRGB(in_y, in_u, in_v, &out_r, &out_g, &out_b); error_sum += out_r - in_r + out_g - in_g + out_b - in_b; error_avg += std::abs(out_r - in_r) + std::abs(out_g - in_g) + std::abs(out_b - in_b); num_values += 3; ASSERT_NEAR(out_r, in_r, error_margin); ASSERT_NEAR(out_g, in_g, error_margin); ASSERT_NEAR(out_b, in_b, error_margin); } } } error_sum /= num_values; error_avg /= num_values; EXPECT_LT(std::abs(error_sum), 0.0001); // This should be almost 0. EXPECT_LT(error_avg, 0.05); // Less than 5% of values have an error of +-1. } INSTANTIATE_TEST_SUITE_P(CspTestInstantiation, CspTest, ::testing::Values(Csp::kYCoCg, Csp::kYCbCr, Csp::kYIQ)); //------------------------------------------------------------------------------ class CspImageTest : public ::testing::TestWithParam<std::tuple<std::string, Csp>> {}; TEST_P(CspImageTest, Simple) { const std::string& src_file_name = std::get<0>(GetParam()); const Csp csp_type = std::get<1>(GetParam()); ArgbBuffer src; ASSERT_WP2_OK( ReadImage(testing::GetTestDataPath(src_file_name).c_str(), &src)); CSPTransform transf; ASSERT_WP2_OK(transf.Init(csp_type, src)); transf.Print(); YUVPlane yuv; ASSERT_WP2_OK(yuv.Import(src, src.HasTransparency(), transf, /*resize_if_needed=*/true, /*pad=*/kPredWidth)); ArgbBuffer dst; ASSERT_WP2_OK(yuv.Export(transf, /*resize_if_needed=*/true, &dst)); float disto[5]; ASSERT_WP2_OK(dst.GetDistortion(src, PSNR, disto)); // Alpha is not supported, total is not either. const float min_in_disto = std::min({disto[1], disto[2], disto[3]}); const float min_expected_disto = (csp_type == Csp::kYCoCg) ? 99.f : 45.f; EXPECT_GE(min_in_disto, min_expected_disto) << std::endl << "Distortion A " << disto[0] << ", R " << disto[1] << ", G " << disto[2] << ", B " << disto[3] << ", total " << disto[4] << " for file " << src_file_name << ", csp " << (uint32_t)csp_type; } INSTANTIATE_TEST_SUITE_P( CspImageTestInstantiation, CspImageTest, ::testing::Combine(::testing::Values("source1_64x48.png"), ::testing::Values(Csp::kYCoCg, Csp::kYCbCr, Csp::kCustom, Csp::kYIQ))); // This one takes a while to run so it is disabled. // Can still be run with flag --test_arg=--gunit_also_run_disabled_tests INSTANTIATE_TEST_SUITE_P( DISABLED_CspImageTestInstantiation, CspImageTest, ::testing::Combine(::testing::Values("source0.pgm", "source0.ppm", "source4.webp", "test_exif_xmp.webp"), ::testing::Values(Csp::kYCoCg, Csp::kYCbCr, Csp::kCustom, Csp::kYIQ))); //------------------------------------------------------------------------------ // This test exercizes a value underflow/overflow in ToYUV(). // RGB are multiplied with RGBtoYUV matrix and after rounding, Y is outside the // maximum allowed values of +/-1023 (10 bits + sign). RGBtoYUV matrix float // computation and rounding to int is probably the root cause. class CustomCspTest : public ::testing::TestWithParam<const char*> {}; TEST_P(CustomCspTest, RoundingError) { const char* const file_name = GetParam(); EncoderConfig config = EncoderConfig::kDefault; config.csp_type = Csp::kCustom; ASSERT_WP2_OK(testing::EncodeDecodeCompare(file_name, config)); } INSTANTIATE_TEST_SUITE_P(CustomCspTestInstantiation, CustomCspTest, ::testing::Values("source1_64x48.png")); // This one takes a while to run so it is disabled. // Can still be run with flag --test_arg=--gunit_also_run_disabled_tests INSTANTIATE_TEST_SUITE_P(DISABLED_CustomCspTestInstantiation, CustomCspTest, ::testing::Values("source0.pgm", "source0.ppm", "source1.png", "source3.jpg", "source4.webp")); //------------------------------------------------------------------------------ // Make sure premultiplied color components are at most equal to alpha. class DecodeArgbTest : public ::testing::TestWithParam<std::tuple<std::string, float>> {}; TEST_P(DecodeArgbTest, Valid) { const std::string& src_file_name = std::get<0>(GetParam()); const float quality = std::get<1>(GetParam()); ArgbBuffer src(WP2_Argb_32), dst(WP2_Argb_32); MemoryWriter data; ASSERT_WP2_OK(testing::CompressImage(src_file_name, &data, &src, quality)); ASSERT_WP2_OK(Decode(data.mem_, data.size_, &dst)); ASSERT_TRUE(testing::Compare(src, dst, src_file_name, testing::GetExpectedDistortion(quality))); for (const ArgbBuffer* const buffer : {&src, &dst}) { for (uint32_t y = 0; y < buffer->height; ++y) { const uint8_t* pixel = (const uint8_t*)buffer->GetRow(y); for (uint32_t x = 0; x < buffer->width; ++x) { ASSERT_GE(pixel[0], pixel[1]); ASSERT_GE(pixel[0], pixel[2]); ASSERT_GE(pixel[0], pixel[3]); pixel += 4; } } } } INSTANTIATE_TEST_SUITE_P( DecodeArgbTestInstantiation, DecodeArgbTest, ::testing::Combine(::testing::Values("source1_4x4.png"), ::testing::Values(0.f, 100.f) /* quality */)); //------------------------------------------------------------------------------ // Tests CSPTransform::MakeEigenMatrixEncodable() results. struct MtxValidity { double error; // Maximum offset among all elements. std::array<double, 9> matrix; // Elements. }; class CspTestCustomCsp : public ::testing::TestWithParam<MtxValidity> {}; TEST_P(CspTestCustomCsp, EigenMtx) { const MtxValidity& param = GetParam(); std::array<int16_t, 9> fixed_point_matrix; for (uint32_t i = 0; i < 9; ++i) { fixed_point_matrix[i] = (int16_t)std::lround(param.matrix[i] * (1 << CSPTransform::kMtxShift)); } int32_t error; std::array<int16_t, 9> encodable_matrix; ASSERT_WP2_OK(CSPTransform::MakeEigenMatrixEncodable( fixed_point_matrix.data(), encodable_matrix.data(), &error)); EXPECT_NEAR(error / (double)(1 << CSPTransform::kMtxShift), param.error, 0.0001); } INSTANTIATE_TEST_SUITE_P( CspTestCustomCspInstantiation, CspTestCustomCsp, ::testing::Values( // error, matrix MtxValidity{0., {0., 0., 0., // Empty matrix 0., 0., 0., // 0., 0., 0.}}, MtxValidity{0., {1., 0., 0., // Identity matrix 0., -1., 0., // 0., 0., -1.}}, MtxValidity{0.9988, {1., 0., 0., // Bad matrix 0., -1., 0., // 0., 0., 0.}}, MtxValidity{0.1399, {1., 0., 0., // Bad matrix 0., -0.99, 0., // 0., 0., -1.}}, MtxValidity{0., {0.263184, 0.321289, 0.199707, // Valid output from 0.27002, 0.0107422, -0.373291, // NormalizeFromInput() 0.264893, -0.330078, 0.181885}}, MtxValidity{0.526367, {-0.263184, 0.321289, 0.199707, // Same but flipped 0.27002, 0.0107422, -0.373291, // first sign. 0.264893, -0.330078, 0.181885}}, MtxValidity{0., {0.264893, 0.374023, 0.115967, // Valid 0.269531, -0.0727539, -0.381592, // 0.28418, -0.279785, 0.253906}}, MtxValidity{0., {0.287354, 0.217773, 0.22168, // Valid 0.261719, -0.00708008, -0.33252, // 0.167236, -0.362793, 0.139404}}, MtxValidity{0., {0.333740, 0.265136, 0.364501, // Valid 0.329101, 0.166503, -0.422363, // 0.307861, -0.465087, 0.056152}}, MtxValidity{0.014648, {0.285400, 0.240234, 0.331543, // Valid output but too 0.288330, -0.399170, 0.029297, // imprecise to encode. 0.282227, 0.164795, -0.365234}})); //------------------------------------------------------------------------------ } // namespace } // namespace WP2
38.969605
80
0.566492
RReverser
148014ae662c05e88edbc8c6a03d58093a3ed202
544
hpp
C++
src/ssmkit/map/transition_matrix.hpp
vahid-bastani/ssmpack
68aed98b1c661a7d1c9e5610656de57f6a967532
[ "MIT" ]
7
2016-07-08T09:18:49.000Z
2018-03-10T06:46:55.000Z
src/ssmkit/map/transition_matrix.hpp
vahidbas/ssmkit
68aed98b1c661a7d1c9e5610656de57f6a967532
[ "MIT" ]
null
null
null
src/ssmkit/map/transition_matrix.hpp
vahidbas/ssmkit
68aed98b1c661a7d1c9e5610656de57f6a967532
[ "MIT" ]
1
2018-01-03T17:46:08.000Z
2018-01-03T17:46:08.000Z
#ifndef SSMPACK_MODEL_TRANSITION_MATRIX_HPP #define SSMPACK_MODEL_TRANSITION_MATRIX_HPP #include <armadillo> namespace ssmkit { namespace map { struct TransitionMatrix { using TParameter = arma::vec; using TConditionVAR = int; TransitionMatrix(arma::mat t) : transfer{t} {} // should not be overloaded, should not be template TParameter operator()(const TConditionVAR &x) const { return transfer.col(x); } arma::mat transfer; }; } // namespace map } // namespace ssmkit #endif // SSMPACK_MODEL_TRANSITION_MATRIX_HPP
20.148148
55
0.744485
vahid-bastani
1487ff58e867aa7b2353c2e6e82ed1a0ccbe752b
1,551
cpp
C++
examples/GLUT/28-voxel-basic/WifiSend.cpp
zwells1/HapticMoCap
0f102834b44f6f38473145da4e39090fafa126b2
[ "BSD-3-Clause" ]
null
null
null
examples/GLUT/28-voxel-basic/WifiSend.cpp
zwells1/HapticMoCap
0f102834b44f6f38473145da4e39090fafa126b2
[ "BSD-3-Clause" ]
null
null
null
examples/GLUT/28-voxel-basic/WifiSend.cpp
zwells1/HapticMoCap
0f102834b44f6f38473145da4e39090fafa126b2
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <sstream> #include <boost/array.hpp> #include <boost/asio.hpp> using boost::asio::ip::udp; class UDPClient { public: UDPClient( boost::asio::io_service& io_service, const std::string& host, const std::string& port ) : io_service_(io_service), socket_(io_service, udp::endpoint(udp::v4(), 0)) { udp::resolver resolver(io_service_); udp::resolver::query query(udp::v4(), host, port); udp::resolver::iterator iter = resolver.resolve(query); endpoint_ = *iter; } ~UDPClient() { socket_.close(); } void send(const std::string& msg) { socket_.send_to(boost::asio::buffer(msg, msg.size()), endpoint_); } private: boost::asio::io_service& io_service_; udp::socket socket_; udp::endpoint endpoint_; }; int main() { boost::asio::io_service io_service; UDPClient client(io_service, "192.168.0.194", "123"); /* std::string x; std::stringstream ss; int nint = 4; int LowFreq = 322; int HighFreq = 922; char bytes [6]; bytes[0] = nint & 0x000000ff; bytes[1] = (LowFreq & 0x0000ff00) >> 8; bytes[2] = LowFreq & 0x000000ff; bytes[3] = (HighFreq & 0x0000ff00) >> 8; bytes[4] = HighFreq & 0x000000ff; ss << bytes; ss >> x; std::cout << x.size() << std::endl; client.send(x); */ std::string x; std::stringstream ss; char tokens[1]; int nint = 5; int i; char y = 15; for (i = 0; i < 1; i++) { //tokens[i] = (char)(nint & 0x000000ff); tokens[i] = y; nint++; } //ss << tokens; //ss >> x; //std::cout << tokens.size() << std::endl; client.send(tokens); }
18.247059
80
0.630561
zwells1
149bb0962c3483d3de9ae32d6163b3a4678fb0c4
17,022
cpp
C++
Plugins/DotNET/DotNETExports.cpp
Lord-Nightmare/unified
4b6c7351f1389b741667abe03f950313dcde8e1c
[ "MIT" ]
null
null
null
Plugins/DotNET/DotNETExports.cpp
Lord-Nightmare/unified
4b6c7351f1389b741667abe03f950313dcde8e1c
[ "MIT" ]
null
null
null
Plugins/DotNET/DotNETExports.cpp
Lord-Nightmare/unified
4b6c7351f1389b741667abe03f950313dcde8e1c
[ "MIT" ]
null
null
null
#include "nwnx.hpp" #include "API/CNWSObject.hpp" #include "API/CAppManager.hpp" #include "API/CServerAIMaster.hpp" #include "API/CServerExoApp.hpp" #include "API/CVirtualMachine.hpp" #include "API/CNWVirtualMachineCommands.hpp" #include "API/CWorldTimer.hpp" #include <dlfcn.h> using namespace NWNXLib; using namespace NWNXLib::API; namespace DotNET { // Bootstrap functions using MainLoopHandlerType = void (*)(uint64_t); using RunScriptHandlerType = int (*)(const char *, uint32_t); using ClosureHandlerType = void (*)(uint64_t, uint32_t); using SignalHandlerType = void (*)(const char*); struct AllHandlers { MainLoopHandlerType MainLoop; RunScriptHandlerType RunScript; ClosureHandlerType Closure; SignalHandlerType SignalHandler; }; static AllHandlers s_handlers; static uint32_t s_pushedCount = 0; static std::vector<std::unique_ptr<NWNXLib::Hooks::FunctionHook>> s_managedHooks; static std::string s_nwnxActivePlugin; static std::string s_nwnxActiveFunction; static uintptr_t GetFunctionPointer(const char *name) { void *core = dlopen("NWNX_Core.so", RTLD_LAZY); if (!core) { LOG_ERROR("Failed to open core handle: %s", dlerror()); return 0; } auto ret = reinterpret_cast<uintptr_t>(dlsym(core, name)); if (ret == 0) LOG_WARNING("Failed to get symbol name '%s': %s", name, dlerror()); dlclose(core); return ret; } static void RegisterHandlers(AllHandlers *handlers, unsigned size) { if (size > sizeof(*handlers)) { LOG_ERROR("RegisterHandlers argument contains too many entries, aborting"); return; } if (size < sizeof(*handlers)) { LOG_WARNING("RegisterHandlers argument missing some entries - Managed/Unmanaged mismatch, update managed code"); } LOG_INFO("Registering managed code handlers."); s_handlers = *handlers; LOG_DEBUG("Registered main loop handler: %p", s_handlers.MainLoop); static Hooks::Hook MainLoopHook; MainLoopHook = Hooks::HookFunction(Functions::_ZN21CServerExoAppInternal8MainLoopEv, (void*)+[](CServerExoAppInternal *pServerExoAppInternal) -> int32_t { static uint64_t frame = 0; if (s_handlers.MainLoop) { int spBefore = Utils::PushScriptContext(Constants::OBJECT_INVALID, false); s_handlers.MainLoop(frame); int spAfter = Utils::PopScriptContext(); ASSERT_MSG(spBefore == spAfter, "spBefore=%x, spAfter=%x", spBefore, spAfter); } ++frame; return MainLoopHook->CallOriginal<int32_t>(pServerExoAppInternal); }, Hooks::Order::VeryEarly); LOG_DEBUG("Registered runscript handler: %p", s_handlers.RunScript); static Hooks::Hook RunScriptHook; RunScriptHook = Hooks::HookFunction(Functions::_ZN15CVirtualMachine9RunScriptEP10CExoStringjii, (void*)+[](CVirtualMachine* thisPtr, CExoString* script, ObjectID objId, int32_t valid, int32_t eventId) -> int32_t { if (!script || *script == "") return 1; LOG_DEBUG("Calling managed RunScriptHandler for script '%s' on Object 0x%08x", script->CStr(), objId); int spBefore = Utils::PushScriptContext(objId, !!valid); int32_t retval = s_handlers.RunScript(script->CStr(), objId); int spAfter = Utils::PopScriptContext(); ASSERT_MSG(spBefore == spAfter, "spBefore=%x, spAfter=%x", spBefore, spAfter); // ~0 is returned if runscript request is not handled and needs to be forwarded if (retval != ~0) { Globals::VirtualMachine()->m_nReturnValueParameterType = 0x03; Globals::VirtualMachine()->m_pReturnValue = reinterpret_cast<void*>(retval); return 1; } return RunScriptHook->CallOriginal<int32_t>(thisPtr, script, objId, valid, eventId); }, Hooks::Order::Latest); LOG_DEBUG("Registered closure handler: %p", s_handlers.Closure); static Hooks::Hook RunScriptSituationHook; RunScriptSituationHook = Hooks::HookFunction(Functions::_ZN15CVirtualMachine18RunScriptSituationEPvji, (void*)+[](CVirtualMachine* thisPtr, CVirtualMachineScript* script, ObjectID objId, int32_t valid) -> int32_t { uint64_t eventId; if (script && sscanf(script->m_sScriptName.m_sString, "NWNX_DOTNET_INTERNAL %lu", &eventId) == 1) { LOG_DEBUG("Calling managed RunScriptSituationHandler for event '%lu' on Object 0x%08x", eventId, objId); int spBefore = Utils::PushScriptContext(objId, !!valid); s_handlers.Closure(eventId, objId); int spAfter = Utils::PopScriptContext(); ASSERT_MSG(spBefore == spAfter, "spBefore=%x, spAfter=%x", spBefore, spAfter); delete script; return 1; } return RunScriptSituationHook->CallOriginal<int32_t>(thisPtr, script, objId, valid); }, Hooks::Order::Latest); LOG_DEBUG("Registered core signal handler: %p", s_handlers.SignalHandler); MessageBus::Subscribe("NWNX_CORE_SIGNAL", [](const std::vector<std::string>& message) { int spBefore = Utils::PushScriptContext(Constants::OBJECT_INVALID, false); s_handlers.SignalHandler(message[0].c_str()); int spAfter = Utils::PopScriptContext(); ASSERT_MSG(spBefore == spAfter, "spBefore=%x, spAfter=%x", spBefore, spAfter); }); } static CVirtualMachineScript* CreateScriptForClosure(uint64_t eventId) { CVirtualMachineScript* script = new CVirtualMachineScript(); script->m_pCode = NULL; script->m_nSecondaryInstructPtr = 0; script->m_nInstructPtr = 0; script->m_nStackSize = 0; script->m_pStack = new CVirtualMachineStack(); char buff[128]; sprintf(buff, "%s %lu", "NWNX_DOTNET_INTERNAL", eventId); script->m_sScriptName = CExoString(buff); return script; } static void CallBuiltIn(int32_t id) { auto vm = Globals::VirtualMachine(); auto cmd = static_cast<CNWVirtualMachineCommands*>(Globals::VirtualMachine()->m_pCmdImplementer); LOG_DEBUG("Calling BuiltIn %i.", id); ASSERT(vm->m_nRecursionLevel >= 0); cmd->ExecuteCommand(id, s_pushedCount); s_pushedCount = 0; } static void StackPushInteger(int32_t value) { auto vm = Globals::VirtualMachine(); LOG_DEBUG("Pushing integer %i.", value); ASSERT(vm->m_nRecursionLevel >= 0); if (vm->StackPushInteger(value)) { ++s_pushedCount; } else { LOG_WARNING("Failed to push integer %s - recursion level %i.", value, vm->m_nRecursionLevel); } } static void StackPushFloat(float value) { auto vm = Globals::VirtualMachine(); LOG_DEBUG("Pushing float %f.", value); ASSERT(vm->m_nRecursionLevel >= 0); if (vm->StackPushFloat(value)) { ++s_pushedCount; } else { LOG_WARNING("Failed to push float %f - recursion level %i.", value, vm->m_nRecursionLevel); } } static void StackPushString(const char* value) { auto vm = Globals::VirtualMachine(); ASSERT(vm->m_nRecursionLevel >= 0); LOG_DEBUG("Pushing string '%s'.", value); CExoString str(String::FromUTF8(value).c_str()); if (vm->StackPushString(str)) { ++s_pushedCount; } else { LOG_WARNING("Failed to push string '%s' - recursion level %i.", str.m_sString, vm->m_nRecursionLevel); } } static void StackPushObject(uint32_t value) { auto vm = Globals::VirtualMachine(); LOG_DEBUG("Pushing object 0x%x.", value); ASSERT(vm->m_nRecursionLevel >= 0); if (vm->StackPushObject(value)) { ++s_pushedCount; } else { LOG_WARNING("Failed to push object 0x%x - recursion level %i.", value, vm->m_nRecursionLevel); } } static void StackPushVector(Vector value) { auto vm = Globals::VirtualMachine(); LOG_DEBUG("Pushing vector { %f, %f, %f }.", value.x, value.y, value.z); ASSERT(vm->m_nRecursionLevel >= 0); if (vm->StackPushVector(value)) { ++s_pushedCount; } else { LOG_WARNING("Failed to push vector { %f, %f, %f } - recursion level %i.", value.x, value.y, value.z, vm->m_nRecursionLevel); } } static void StackPushGameDefinedStructure(int32_t structId, void* value) { auto vm = Globals::VirtualMachine(); LOG_DEBUG("Pushing game defined structure %i at 0x%x.", structId, value); ASSERT(vm->m_nRecursionLevel >= 0); auto ret = vm->StackPushEngineStructure(structId, value); if (!ret) { LOG_WARNING("Failed to push game defined structure %i at 0x%x - recursion level %i.", structId, value, vm->m_nRecursionLevel); } s_pushedCount += ret; } static int32_t StackPopInteger() { auto vm = Globals::VirtualMachine(); ASSERT(vm->m_nRecursionLevel >= 0); int32_t value; if (!vm->StackPopInteger(&value)) { LOG_WARNING("Failed to pop integer - recursion level %i.", vm->m_nRecursionLevel); return -1; } LOG_DEBUG("Popped integer %d.", value); return value; } static float StackPopFloat() { auto vm = Globals::VirtualMachine(); ASSERT(vm->m_nRecursionLevel >= 0); float value; if (!vm->StackPopFloat(&value)) { LOG_WARNING("Failed to pop float - recursion level %i.", vm->m_nRecursionLevel); return 0.0f; } LOG_DEBUG("Popped float %f.", value); return value; } static const char* StackPopString() { auto vm = Globals::VirtualMachine(); ASSERT(vm->m_nRecursionLevel >= 0); CExoString value; if (!vm->StackPopString(&value)) { LOG_WARNING("Failed to pop string - recursion level %i.", vm->m_nRecursionLevel); return ""; } LOG_DEBUG("Popped string '%s'.", value.m_sString); // TODO: Less copies return strdup(String::ToUTF8(value.CStr()).c_str()); } static uint32_t StackPopObject() { auto vm = Globals::VirtualMachine(); ASSERT(vm->m_nRecursionLevel >= 0); uint32_t value; if (!vm->StackPopObject(&value)) { LOG_WARNING("Failed to pop object - recursion level %i.", vm->m_nRecursionLevel); return Constants::OBJECT_INVALID; } LOG_DEBUG("Popped object 0x%x.", value); return value; } static Vector StackPopVector() { auto vm = Globals::VirtualMachine(); ASSERT(vm->m_nRecursionLevel >= 0); Vector value; if (!vm->StackPopVector(&value)) { LOG_WARNING("Failed to pop vector - recursion level %i.", vm->m_nRecursionLevel); return value; } LOG_DEBUG("Popping vector { %f, %f, %f }.", value.x, value.y, value.z); return value; } static void* StackPopGameDefinedStructure(int32_t structId) { auto vm = Globals::VirtualMachine(); ASSERT(vm->m_nRecursionLevel >= 0); void* value; if (!vm->StackPopEngineStructure(structId, &value)) { LOG_WARNING("Failed to pop game defined structure %i - recursion level %i.", structId, vm->m_nRecursionLevel); return nullptr; } LOG_DEBUG("Popped game defined structure %i at 0x%x.", structId, value); return value; } static void FreeGameDefinedStructure(int32_t structId, void* ptr) { if (ptr) { auto cmd = static_cast<CNWVirtualMachineCommands*>(Globals::VirtualMachine()->m_pCmdImplementer); LOG_DEBUG("Freeing game structure at 0x%x", ptr); cmd->DestroyGameDefinedStructure(structId, ptr); } } static int32_t ClosureAssignCommand(uint32_t oid, uint64_t eventId) { if (Utils::GetGameObject(oid)) { CServerAIMaster* ai = Globals::AppManager()->m_pServerExoApp->GetServerAIMaster(); ai->AddEventDeltaTime(0, 0, oid, oid, 1, CreateScriptForClosure(eventId)); return 1; } return 0; } static int32_t ClosureDelayCommand(uint32_t oid, float duration, uint64_t eventId) { if (Utils::GetGameObject(oid)) { int32_t days = Globals::AppManager()->m_pServerExoApp->GetWorldTimer()->GetCalendarDayFromSeconds(duration); int32_t time = Globals::AppManager()->m_pServerExoApp->GetWorldTimer()->GetTimeOfDayFromSeconds(duration); CServerAIMaster* ai = Globals::AppManager()->m_pServerExoApp->GetServerAIMaster(); ai->AddEventDeltaTime(days, time, oid, oid, 1, CreateScriptForClosure(eventId)); return 1; } return 0; } static int32_t ClosureActionDoCommand(uint32_t oid, uint64_t eventId) { if (auto *obj = Utils::AsNWSObject(Utils::GetGameObject(oid))) { obj->AddDoCommandAction(CreateScriptForClosure(eventId)); return 1; } return 0; } static void nwnxSetFunction(const char *plugin, const char *function) { s_nwnxActivePlugin = plugin; s_nwnxActiveFunction = function; } static void nwnxPushInt(int32_t n) { Events::Push(n); } static void nwnxPushFloat(float f) { Events::Push(f); } static void nwnxPushObject(uint32_t o) { Events::Push((ObjectID)o); } static void nwnxPushString(const char *s) { Events::Push(String::FromUTF8(s)); } static void nwnxPushEffect(CGameEffect *e) { Events::Push(e); } static void nwnxPushItemProperty(CGameEffect *ip) { Events::Push(ip); } static int32_t nwnxPopInt() { return Events::Pop<int32_t>().value_or(0); } static float nwnxPopFloat() { return Events::Pop<float>().value_or(0.0f); } static uint32_t nwnxPopObject() { return Events::Pop<ObjectID>().value_or(Constants::OBJECT_INVALID); } static const char* nwnxPopString() { auto str = Events::Pop<std::string>().value_or(std::string{""}); return strdup(String::ToUTF8(str).c_str()); } static CGameEffect* nwnxPopEffect() { return Events::Pop<CGameEffect*>().value_or(nullptr); } static CGameEffect* nwnxPopItemProperty() { return Events::Pop<CGameEffect*>().value_or(nullptr); } static void nwnxCallFunction() { Events::Call(s_nwnxActivePlugin, s_nwnxActiveFunction); } static NWNXLib::API::Globals::NWNXExportedGlobals GetNWNXExportedGlobals() { return NWNXLib::API::Globals::ExportedGlobals; } static void* RequestHook(uintptr_t address, void* managedFuncPtr, int32_t order) { auto funchook = s_managedHooks.emplace_back(Hooks::HookFunction(address, managedFuncPtr, order)).get(); return funchook->GetOriginal(); } static void ReturnHook(void* trampoline) { for (auto it = s_managedHooks.begin(); it != s_managedHooks.end(); it++) { if (it->get()->GetOriginal() == trampoline) { s_managedHooks.erase(it); return; } } } std::vector<void*> GetExports() { // // Fill the function table to hand over to managed code // NOTE: Only add new entries to the end of this table, DO NOT RESHUFFLE. // std::vector<void*> exports; exports.push_back((void*)&GetFunctionPointer); exports.push_back((void*)&RegisterHandlers); exports.push_back((void*)&CallBuiltIn); exports.push_back((void*)&StackPushInteger); exports.push_back((void*)&StackPushFloat); exports.push_back((void*)&StackPushString); exports.push_back((void*)&StackPushString); // reserved utf8 exports.push_back((void*)&StackPushObject); exports.push_back((void*)&StackPushVector); exports.push_back((void*)&StackPushGameDefinedStructure); exports.push_back((void*)&StackPopInteger); exports.push_back((void*)&StackPopFloat); exports.push_back((void*)&StackPopString); exports.push_back((void*)&StackPopString); // reserved utf8 exports.push_back((void*)&StackPopObject); exports.push_back((void*)&StackPopVector); exports.push_back((void*)&StackPopGameDefinedStructure); exports.push_back((void*)&FreeGameDefinedStructure); exports.push_back((void*)&ClosureAssignCommand); exports.push_back((void*)&ClosureDelayCommand); exports.push_back((void*)&ClosureActionDoCommand); exports.push_back((void*)&nwnxSetFunction); exports.push_back((void*)&nwnxPushInt); exports.push_back((void*)&nwnxPushFloat); exports.push_back((void*)&nwnxPushObject); exports.push_back((void*)&nwnxPushString); exports.push_back((void*)&nwnxPushString); // reserved utf8 exports.push_back((void*)&nwnxPushEffect); exports.push_back((void*)&nwnxPushItemProperty); exports.push_back((void*)&nwnxPopInt); exports.push_back((void*)&nwnxPopFloat); exports.push_back((void*)&nwnxPopObject); exports.push_back((void*)&nwnxPopString); exports.push_back((void*)&nwnxPopString); // reserved utf8 exports.push_back((void*)&nwnxPopEffect); exports.push_back((void*)&nwnxPopItemProperty); exports.push_back((void*)&nwnxCallFunction); exports.push_back((void*)&GetNWNXExportedGlobals); exports.push_back((void*)&RequestHook); exports.push_back((void*)&ReturnHook); return exports; } }
30.560144
123
0.663024
Lord-Nightmare
149da88c83d91c82c5e6ce254eedb3cdc0cf1e1b
1,951
cpp
C++
Mastermind/src/GameState.cpp
olafur-skulason/CodeExamples
2365bb075695e31ca0d006f2e57479e2c3c67ef3
[ "MIT" ]
null
null
null
Mastermind/src/GameState.cpp
olafur-skulason/CodeExamples
2365bb075695e31ca0d006f2e57479e2c3c67ef3
[ "MIT" ]
null
null
null
Mastermind/src/GameState.cpp
olafur-skulason/CodeExamples
2365bb075695e31ca0d006f2e57479e2c3c67ef3
[ "MIT" ]
null
null
null
/* * GameState.cpp * * Created on: Feb 28, 2020 * Author: olafur */ #include "../inc/GameState.h" #include <iostream> GameState::GameState(unsigned int codeLength, unsigned int attemptLimit, ColorSelector * colorSelector) : color_selector(colorSelector), code_length(codeLength), attempt_limit(attemptLimit), attempts(0), master_code(nullptr), black(0), white(0) { } GameState::~GameState() { delete master_code; } void GameState::Initialize() { attempts = 0; master_code = GenerateMasterCode(); black = 0; white = 0; } bool GameState::IsFinished() { if(black == code_length) { return true; } else if(attempts >= attempt_limit) { return true; } else { return false; } } unsigned char GameState::GetWhitePegs() { return white; } unsigned char GameState::GetBlackPegs() { return black; } unsigned char * GameState::GetMasterCode() { return master_code; } void GameState::SetMasterCode(unsigned char * new_code) { master_code = new_code; } void GameState::InputGuess(unsigned char * guess) { white = 0; black = 0; bool flag[code_length] = {false}; for(unsigned int i = 0; i < code_length; i++) { if(guess[i] == master_code[i]) black++; else { for(unsigned int j = 0; j < code_length; j++) { if (j != i && guess[i] == master_code[j] && !flag[j]) { white++; flag[j]=1; break; } } } } attempts++; } unsigned char * GameState::GenerateMasterCode() { if(master_code != nullptr) delete master_code; unsigned char * new_code = new unsigned char(code_length); std::cout << "Original master code: "; for(unsigned int i = 0; i < code_length; i++) { new_code[i] = color_selector->GetRandomColor(); std::cout << new_code[i]; } std::cout << std::endl; return new_code; } int GameState::CountColor(unsigned char * code, char color) { int result = 0; for(unsigned int i = 0; i < code_length; i++) { if(code[i] == color) result++; } return result; }
18.580952
105
0.655561
olafur-skulason
149ddcab7d584c53e3ceaf9d30b61fb03d6f5a3f
725
hpp
C++
tc_alt.hpp
arbrk1/typeclasses_cpp
7bb180f0daaa7dfeb84387f9913c99b99702be2c
[ "MIT" ]
10
2018-11-16T14:34:50.000Z
2021-11-25T04:37:39.000Z
tc_alt.hpp
arbrk1/typeclasses_cpp
7bb180f0daaa7dfeb84387f9913c99b99702be2c
[ "MIT" ]
null
null
null
tc_alt.hpp
arbrk1/typeclasses_cpp
7bb180f0daaa7dfeb84387f9913c99b99702be2c
[ "MIT" ]
3
2020-06-01T14:22:06.000Z
2021-11-22T20:26:24.000Z
// An alternative to the tc.hpp // arbrk1@gmail.com, 2018 #ifndef _TC_ALT_HPP_ #define _TC_ALT_HPP_ #define TC_DEF(name, params, body...) \ template< params > struct name; \ template< params > struct _tc_methods_##name body; #define TC_INSTANCE(name, params, body...) \ struct name< params > : _tc_methods_##name< params > body; #define PARAMS(args...) args #ifdef TC_COMPAT // compatibility layer with the tc.hpp #define TC_IMPL(tc...) typedef tc template<class T> using tc_impl_t = T; template<class T> struct _tc_dummy_ { static bool const value = true; T t; }; #define TC_REQUIRE(tc...) \ static_assert( _tc_dummy_<tc_impl_t<tc>>::value, "unreachable" ); #endif // TC_COMPAT #endif // _TC_ALT_HPP_
26.851852
77
0.706207
arbrk1
14a8b78c1f826693f60734320b02233323f1a920
2,763
cpp
C++
firmware/utility/ServoFirmata.cpp
fgu-cas/arenomat
81954e82f58178586a31886136d3047cf5a0c4d2
[ "MIT" ]
null
null
null
firmware/utility/ServoFirmata.cpp
fgu-cas/arenomat
81954e82f58178586a31886136d3047cf5a0c4d2
[ "MIT" ]
null
null
null
firmware/utility/ServoFirmata.cpp
fgu-cas/arenomat
81954e82f58178586a31886136d3047cf5a0c4d2
[ "MIT" ]
null
null
null
/* ServoFirmata.cpp - Firmata library Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. Copyright (C) 2009-2011 Jeff Hoefs. All rights reserved. Copyright (C) 2013 Norbert Truchsess. 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. See file LICENSE.txt for further informations on licensing terms. */ #include <Servo.h> #include <Firmata.h> #include <ServoFirmata.h> ServoFirmata *ServoInstance; void servoAnalogWrite(byte pin, int value) { ServoInstance->analogWrite(pin,value); } ServoFirmata::ServoFirmata() { ServoInstance = this; } boolean ServoFirmata::analogWrite(byte pin, int value) { if (IS_PIN_SERVO(pin)) { Servo *servo = servos[PIN_TO_SERVO(pin)]; if (servo) servo->write(value); } } boolean ServoFirmata::handlePinMode(byte pin, int mode) { if (IS_PIN_SERVO(pin)) { if (mode==SERVO) { attach(pin,-1,-1); return true; } else { detach(pin); } } return false; } void ServoFirmata::handleCapability(byte pin) { if (IS_PIN_SERVO(pin)) { Firmata.write(SERVO); Firmata.write(14); //14 bit resolution (Servo takes int as argument) } } boolean ServoFirmata::handleSysex(byte command, byte argc, byte* argv) { if(command == SERVO_CONFIG) { if (argc > 4) { // these vars are here for clarity, they'll optimized away by the compiler byte pin = argv[0]; if (IS_PIN_SERVO(pin) && Firmata.getPinMode(pin)!=IGNORE) { int minPulse = argv[1] + (argv[2] << 7); int maxPulse = argv[3] + (argv[4] << 7); Firmata.setPinMode(pin, SERVO); attach(pin, minPulse, maxPulse); return true; } } } return false; } void ServoFirmata::attach(byte pin, int minPulse, int maxPulse) { Servo *servo = servos[PIN_TO_SERVO(pin)]; if (!servo) { servo = new Servo(); servos[PIN_TO_SERVO(pin)] = servo; } if (servo->attached()) servo->detach(); if (minPulse>=0 || maxPulse>=0) servo->attach(PIN_TO_DIGITAL(pin),minPulse,maxPulse); else servo->attach(PIN_TO_DIGITAL(pin)); } void ServoFirmata::detach(byte pin) { Servo *servo = servos[PIN_TO_SERVO(pin)]; if (servo) { if (servo->attached()) servo->detach(); free(servo); servos[PIN_TO_SERVO(pin)]=NULL; } } void ServoFirmata::reset() { for (byte pin=0;pin<TOTAL_PINS;pin++) { if (IS_PIN_SERVO(pin)) { detach(pin); } } }
24.026087
80
0.661962
fgu-cas
14ab7a328a5431e82e49e9d14d89cb901a13213b
732
hpp
C++
source/framework/algorithm/include/lue/framework/algorithm/default_policies/tan.hpp
pcraster/lue
e64c18f78a8b6d8a602b7578a2572e9740969202
[ "MIT" ]
1
2019-04-14T15:51:12.000Z
2019-04-14T15:51:12.000Z
source/framework/algorithm/include/lue/framework/algorithm/default_policies/tan.hpp
pcraster/lue
e64c18f78a8b6d8a602b7578a2572e9740969202
[ "MIT" ]
262
2016-08-11T10:12:02.000Z
2020-10-13T18:09:16.000Z
source/framework/algorithm/include/lue/framework/algorithm/default_policies/tan.hpp
pcraster/lue
e64c18f78a8b6d8a602b7578a2572e9740969202
[ "MIT" ]
1
2020-03-11T09:49:41.000Z
2020-03-11T09:49:41.000Z
#pragma once #include "lue/framework/algorithm/tan.hpp" namespace lue { namespace policy::tan { template< typename Element> using DefaultPolicies = policy::DefaultPolicies< AllValuesWithinDomain<Element>, OutputElements<Element>, InputElements<Element>>; } // namespace policy::tan namespace default_policies { template< typename Element, Rank rank> auto tan( PartitionedArray<Element, rank> const& array) { using Policies = policy::tan::DefaultPolicies<Element>; return tan(Policies{}, array); } } // namespace default_policies } // namespace lue
22.181818
67
0.584699
pcraster
14ae7a0477b0d332f10a0616ce21b5df60e761b9
2,310
cpp
C++
code/nes/gamepad.cpp
oldGanon/neszett
7b42b042fe74e37e18f93718c3549feeea7d85e7
[ "MIT" ]
null
null
null
code/nes/gamepad.cpp
oldGanon/neszett
7b42b042fe74e37e18f93718c3549feeea7d85e7
[ "MIT" ]
null
null
null
code/nes/gamepad.cpp
oldGanon/neszett
7b42b042fe74e37e18f93718c3549feeea7d85e7
[ "MIT" ]
null
null
null
struct gamepad_frame { u8 Gamepad[2]; u8 Flags; }; struct gamepad_playback { u32 Size; u32 Index; gamepad_frame Frames[1]; }; struct gamepad { console *Console; gamepad_playback *Playback; u8 Strobe; u8 ReadSerial[2]; }; inline u8 Gamepad_GetPlaybackButtons(gamepad_playback *Playback, u8 Index) { return Playback->Frames[Playback->Index].Gamepad[Index]; } inline u8 Gamepad_Read(gamepad *Gamepad, u8 Index) { u8 Buttons; if (Gamepad->Playback) Buttons = Gamepad_GetPlaybackButtons(Gamepad->Playback, Index); else { if (Index == 0) Buttons = Api_GetGamepad(); else Buttons = 0; } if (Gamepad->Strobe) Gamepad->ReadSerial[Index] = 0; u8 Result = Buttons >> Gamepad->ReadSerial[Index]++; if (Gamepad->ReadSerial[Index] > 8) { Gamepad->ReadSerial[Index] = 8; return 1; } return Result & 1; } inline void Gamepad_Write(gamepad *Gamepad, u8 Value) { Gamepad->Strobe = Value & 1; if (Gamepad->Strobe) { Gamepad->ReadSerial[0] = 0; Gamepad->ReadSerial[1] = 0; } } inline void Gamepad_NextFrame(gamepad *Gamepad) { if (!Gamepad->Playback) return; gamepad_playback *Playback = Gamepad->Playback; if (++Playback->Index > Playback->Size) { Api_Free(Playback); Gamepad->Playback = 0; return; } } inline void Gamepad_SetPlayback(gamepad *Gamepad, gamepad_playback *Playback) { if (Gamepad->Playback) Api_Free(Gamepad->Playback); Gamepad->Playback = Playback; } inline void Gamepad_Step(gamepad *Gamepad) { if (!Gamepad->Playback) return; gamepad_playback *Playback = Gamepad->Playback; u8 Flags = Playback->Frames[Playback->Index].Flags; if (Flags & 1) { Gamepad_NextFrame(Gamepad); Console_Reset(Gamepad->Console); } if (Flags & 2) { Gamepad_NextFrame(Gamepad); Console_Power(Gamepad->Console); } } inline gamepad* Gamepad_Create(console *Console) { gamepad *Gamepad = (gamepad *)Api_Malloc(sizeof(gamepad)); Gamepad->Console = Console; return Gamepad; } inline void Gamepad_Free(gamepad *Gamepad) { if (Gamepad->Playback) Api_Free(Gamepad->Playback); Api_Free(Gamepad); }
19.411765
71
0.6329
oldGanon
14b0fdd10453ce38cdd6d6f7d42f88cf84701581
237
cc
C++
cpp/badmacro.cc
iskhanba/epicode
fda752e5e016ab64011083450be91bec9ee8358a
[ "MIT" ]
null
null
null
cpp/badmacro.cc
iskhanba/epicode
fda752e5e016ab64011083450be91bec9ee8358a
[ "MIT" ]
null
null
null
cpp/badmacro.cc
iskhanba/epicode
fda752e5e016ab64011083450be91bec9ee8358a
[ "MIT" ]
null
null
null
#include <cassert> //@include // Avoid overhead of a function call. #define isvowel(c) (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') //@exclude int main(int argc, char** argv) { char c = 'a'; assert(isvowel(c)); }
19.75
77
0.514768
iskhanba
14b115bcd2464a7ef5ba44a606d04d8bc42b7edc
12,259
cp
C++
Std/Mod/Dialog.cp
romiras/Blackbox-fw-playground
6de94dc65513e657a9b86c1772e2c07742b608a8
[ "BSD-2-Clause" ]
1
2016-03-17T08:27:05.000Z
2016-03-17T08:27:05.000Z
Std/Mod/Dialog.cp
romiras/Blackbox-fw-playground
6de94dc65513e657a9b86c1772e2c07742b608a8
[ "BSD-2-Clause" ]
null
null
null
Std/Mod/Dialog.cp
romiras/Blackbox-fw-playground
6de94dc65513e657a9b86c1772e2c07742b608a8
[ "BSD-2-Clause" ]
1
2018-03-14T17:53:27.000Z
2018-03-14T17:53:27.000Z
MODULE StdDialog; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = "" issues = "" **) IMPORT Kernel, Meta, Strings, Files, Stores, Models, Sequencers, Views, Containers, Dialog, Properties, Documents, Converters, Windows; TYPE Item* = POINTER TO EXTENSIBLE RECORD next*: Item; item-, string-, filter-: POINTER TO ARRAY OF CHAR; shortcut-: ARRAY 8 OF CHAR; privateFilter-, failed, trapped: BOOLEAN; (* filter call failed, caused a trap *) res: INTEGER (* result code of failed filter *) END; FilterProcVal = RECORD (Meta.Value) p: Dialog.GuardProc END; FilterProcPVal = RECORD (Meta.Value) p: PROCEDURE(n: INTEGER; VAR p: Dialog.Par) END; ViewHook = POINTER TO RECORD (Views.ViewHook) END; VAR curItem-: Item; (** IN parameter for item filters **) PROCEDURE GetSubLoc* (mod: ARRAY OF CHAR; cat: Files.Name; OUT loc: Files.Locator; OUT name: Files.Name); VAR sub: Files.Name; file: Files.File; type: Files.Type; BEGIN IF (cat[0] = "S") & (cat[1] = "y") & (cat[2] = "m") THEN type := Kernel.symType ELSIF (cat[0] = "C") & (cat[1] = "o") & (cat[2] = "d") & (cat[3] = "e") THEN type := Kernel.objType ELSE type := "" END; Kernel.SplitName(mod, sub, name); Kernel.MakeFileName(name, type); loc := Files.dir.This(sub); file := NIL; IF loc # NIL THEN loc := loc.This(cat); IF sub = "" THEN IF loc # NIL THEN file := Files.dir.Old(loc, name, Files.shared); IF file = NIL THEN loc := NIL END END; IF loc = NIL THEN loc := Files.dir.This("System"); IF loc # NIL THEN loc := loc.This(cat) END END END END END GetSubLoc; PROCEDURE Len (VAR str: ARRAY OF CHAR): INTEGER; VAR i: INTEGER; BEGIN i := 0; WHILE str[i] # 0X DO INC(i) END; RETURN i END Len; PROCEDURE AddItem* (i: Item; item, string, filter, shortcut: ARRAY OF CHAR); VAR j: INTEGER; ch: CHAR; BEGIN ASSERT(i # NIL, 20); NEW(i.item, Len(item) + 1); NEW(i.string, Len(string) + 1); NEW(i.filter, Len(filter) + 1); ASSERT((i.item # NIL) & (i.string # NIL) & (i.filter # NIL), 100); i.item^ := item$; i.string^ := string$; i.filter^ := filter$; i.shortcut := shortcut$; j := 0; ch := filter[0]; WHILE (ch # ".") & (ch # 0X) DO INC(j); ch := filter[j] END; i.privateFilter := (j > 0) & (ch = 0X); i.failed := FALSE; i.trapped := FALSE END AddItem; PROCEDURE ClearGuards* (i: Item); BEGIN i.failed := FALSE; i.trapped := FALSE END ClearGuards; PROCEDURE GetGuardProc (name: ARRAY OF CHAR; VAR i: Meta.Item; VAR par: BOOLEAN; VAR n: INTEGER); VAR j, k: INTEGER; num: ARRAY 32 OF CHAR; BEGIN j := 0; WHILE (name[j] # 0X) & (name[j] # "(") DO INC(j) END; IF name[j] = "(" THEN name[j] := 0X; INC(j); k := 0; WHILE (name[j] # 0X) & (name[j] # ")") DO num[k] := name[j]; INC(j); INC(k) END; IF (name[j] = ")") & (name[j+1] = 0X) THEN num[k] := 0X; Strings.StringToInt(num, n, k); IF k = 0 THEN Meta.LookupPath(name, i); par := TRUE ELSE Meta.Lookup("", i) END ELSE Meta.Lookup("", i) END ELSE Meta.LookupPath(name, i); par := FALSE END END GetGuardProc; PROCEDURE CheckFilter* (i: Item; VAR failed, ok: BOOLEAN; VAR par: Dialog.Par); VAR x: Meta.Item; v: FilterProcVal; vp: FilterProcPVal; p: BOOLEAN; n: INTEGER; BEGIN IF ~i.failed THEN curItem := i; par.disabled := FALSE; par.checked := FALSE; par.label := i.item$; par.undef := FALSE; par.readOnly := FALSE; i.failed := TRUE; i.trapped := TRUE; GetGuardProc(i.filter^, x, p, n); IF (x.obj = Meta.procObj) OR (x.obj = Meta.varObj) & (x.typ = Meta.procTyp) THEN IF p THEN x.GetVal(vp, ok); IF ok THEN vp.p(n, par) END ELSE x.GetVal(v, ok); IF ok THEN v.p(par) END END ELSE ok := FALSE END; IF ok THEN i.res := 0 ELSE i.res := 1 END; i.trapped := FALSE; i.failed := ~ok END; failed := i.failed END CheckFilter; PROCEDURE HandleItem* (i: Item); VAR res: INTEGER; BEGIN IF ~i.failed THEN Views.ClearQueue; res := 0; Dialog.Call(i.string^, " ", res) ELSIF (i # NIL) & i.failed THEN IF i.trapped THEN Dialog.ShowParamMsg("#System:ItemFilterTrapped", i.string^, i.filter^, "") ELSE Dialog.ShowParamMsg("#System:ItemFilterNotFound", i.string^, i.filter^, "") END END END HandleItem; PROCEDURE RecalcView* (v: Views.View); (* recalc size of all subviews of v, then v itself *) VAR m: Models.Model; v1: Views.View; c: Containers.Controller; minW, maxW, minH, maxH, w, h, w0, h0: INTEGER; BEGIN IF v IS Containers.View THEN c := v(Containers.View).ThisController(); IF c # NIL THEN v1 := NIL; c.GetFirstView(Containers.any, v1); WHILE v1 # NIL DO RecalcView(v1); c.GetNextView(Containers.any, v1) END END END; IF v.context # NIL THEN m := v.context.ThisModel(); IF (m # NIL) & (m IS Containers.Model) THEN m(Containers.Model).GetEmbeddingLimits(minW, maxW, minH, maxH); v.context.GetSize(w0, h0); w := w0; h := h0; Properties.PreferredSize(v, minW, maxW, minH, maxH, w, h, w, h); IF (w # w0) OR (h # h0) THEN v.context.SetSize(w, h) END END END END RecalcView; PROCEDURE Open* (v: Views.View; title: ARRAY OF CHAR; loc: Files.Locator; name: Files.Name; conv: Converters.Converter; asTool, asAux, noResize, allowDuplicates, neverDirty: BOOLEAN); VAR t: Views.Title; flags, opts: SET; done: BOOLEAN; d: Documents.Document; i: INTEGER; win: Windows.Window; c: Containers.Controller; seq: ANYPTR; BEGIN IF conv = NIL THEN conv := Converters.list END; (* use document converter *) ASSERT(v # NIL, 20); flags := {}; done := FALSE; IF noResize THEN flags := flags + {Windows.noResize, Windows.noHScroll, Windows.noVScroll} END; IF asTool THEN INCL(flags, Windows.isTool) END; IF asAux THEN INCL(flags, Windows.isAux) END; IF neverDirty THEN INCL(flags, Windows.neverDirty) END; i := 0; WHILE (i < LEN(t) - 1) & (title[i] # 0X) DO t[i] := title[i]; INC(i) END; t[i] := 0X; IF ~allowDuplicates THEN IF ~asTool & ~asAux THEN IF (loc # NIL) & (name # "") THEN Windows.SelectBySpec(loc, name, conv, done) END ELSE IF title # "" THEN Windows.SelectByTitle(v, flags, t, done) END END ELSE INCL(flags, Windows.allowDuplicates) END; IF ~done THEN IF v IS Documents.Document THEN IF v.context # NIL THEN d := Documents.dir.New( Views.CopyOf(v(Documents.Document).ThisView(), Views.shallow), Views.undefined, Views.undefined) ELSE d := v(Documents.Document) END; ASSERT(d.context = NIL, 22); v := d.ThisView(); ASSERT(v # NIL, 23) ELSIF v.context # NIL THEN ASSERT(v.context IS Documents.Context, 24); d := v.context(Documents.Context).ThisDoc(); IF d.context # NIL THEN d := Documents.dir.New(Views.CopyOf(v, Views.shallow), Views.undefined, Views.undefined) END; ASSERT(d.context = NIL, 25) (*IF d.Domain() = NIL THEN Stores.InitDomain(d, v.Domain()) END (for views opened via Views.Old *) ELSE d := Documents.dir.New(v, Views.undefined, Views.undefined) END; IF asTool OR asAux THEN c := d.ThisController(); c.SetOpts(c.opts + {Containers.noSelection}) END; ASSERT(d.Domain() = v.Domain(), 100); ASSERT(d.Domain() # NIL, 101); seq := d.Domain().GetSequencer(); IF neverDirty & (seq # NIL) THEN ASSERT(seq IS Sequencers.Sequencer, 26); seq(Sequencers.Sequencer).SetDirty(FALSE) END; IF neverDirty THEN (* change "fit to page" to "fit to window" in secondary windows *) c := d.ThisController(); opts := c.opts; IF Documents.pageWidth IN opts THEN opts := opts - {Documents.pageWidth} + {Documents.winWidth} END; IF Documents.pageHeight IN opts THEN opts := opts - {Documents.pageHeight} + {Documents.winHeight} END; c.SetOpts(opts) END; win := Windows.dir.New(); IF seq # NIL THEN Windows.dir.OpenSubWindow(win, d, flags, t) ELSE Windows.dir.Open(win, d, flags, t, loc, name, conv) END END END Open; PROCEDURE (h: ViewHook) Open (v: Views.View; title: ARRAY OF CHAR; loc: Files.Locator; name: Files.Name; conv: Converters.Converter; asTool, asAux, noResize, allowDuplicates, neverDirty: BOOLEAN); BEGIN Open(v, title, loc, name, conv, asTool, asAux, noResize, allowDuplicates, neverDirty) END Open; PROCEDURE (h: ViewHook) OldView (loc: Files.Locator; name: Files.Name; VAR conv: Converters.Converter): Views.View; VAR w: Windows.Window; s: Stores.Store; c: Converters.Converter; BEGIN ASSERT(loc # NIL, 20); ASSERT(name # "", 21); Kernel.MakeFileName(name, ""); s := NIL; IF loc.res # 77 THEN w := Windows.dir.First(); c := conv; IF c = NIL THEN c := Converters.list END; (* use document converter *) WHILE (w # NIL) & ((w.loc = NIL) OR (w.name = "") OR (w.loc.res = 77) OR ~Files.dir.SameFile(loc, name, w.loc, w.name) OR (w.conv # c)) DO w := Windows.dir.Next(w) END; IF w # NIL THEN s := w.doc.ThisView() END END; IF s = NIL THEN Converters.Import(loc, name, conv, s); IF s # NIL THEN RecalcView(s(Views.View)) END END; IF s # NIL THEN RETURN s(Views.View) ELSE RETURN NIL END END OldView; PROCEDURE (h: ViewHook) RegisterView (v: Views.View; loc: Files.Locator; name: Files.Name; conv: Converters.Converter); BEGIN ASSERT(v # NIL, 20); ASSERT(loc # NIL, 21); ASSERT(name # "", 22); Kernel.MakeFileName(name, ""); Converters.Export(loc, name, conv, v) END RegisterView; PROCEDURE Init; VAR h: ViewHook; BEGIN NEW(h); Views.SetViewHook(h) END Init; BEGIN Init END StdDialog.
40.062092
126
0.502488
romiras
14b2a7c9b582160d72dc604e7e9deefbf9355764
899
cpp
C++
13.cpp
Sherryhaha/LeetCode
128e344575f8e745b28ff88e6c443b18281ffdc9
[ "MIT" ]
null
null
null
13.cpp
Sherryhaha/LeetCode
128e344575f8e745b28ff88e6c443b18281ffdc9
[ "MIT" ]
null
null
null
13.cpp
Sherryhaha/LeetCode
128e344575f8e745b28ff88e6c443b18281ffdc9
[ "MIT" ]
null
null
null
// // Created by sunguoyan on 2017/3/30. // 将罗马数字转为整数,整数是在1-3999范围内,要先把握下罗马数字的规律,1是"I",两个I就是2...到4是IV,5是V... // 9是IX,10是X,50是L,100是C,500是D,10000是M,因此要注意的是如果识别类似IV,IX,XL....等组合成的罗马数字需要 // 有方法,方法就是从字符串后面往前遍历,如果后一个数字大于前一个数字,那么就减去前一个数字,否则就加上前一个数字 #include "LeetCode.h" int romanToInt(string s) { unordered_map<char,int> roman{{'I',1}, {'V',5}, {'X',10}, {'L',50}, {'C',100}, {'D',500}, {'M',1000}}; int sum = roman[s.back()]; for(int i = s.length()-2;i>=0;i--){ if(roman[s[i]] < roman[s[i+1]]){ sum = sum - roman[s[i]]; }else{ sum = sum + roman[s[i]]; } } return sum; } int main(){ int sum = romanToInt("MXXX"); cout<<sum<<endl; return 0; }
28.09375
74
0.451613
Sherryhaha
14b2e7a935998e4d3e3501b08fa2de9ea72eaceb
2,846
cpp
C++
Engine/Source/Render/Shader/SShaderCompiler.cpp
Aredhele/OOM-Engine
e52f706d17f1867f575a85ba5b87b4cc34a7fa97
[ "MIT" ]
9
2018-07-21T00:30:35.000Z
2021-09-04T02:54:11.000Z
Engine/Source/Render/Shader/SShaderCompiler.cpp
Aredhele/OOM-Engine
e52f706d17f1867f575a85ba5b87b4cc34a7fa97
[ "MIT" ]
null
null
null
Engine/Source/Render/Shader/SShaderCompiler.cpp
Aredhele/OOM-Engine
e52f706d17f1867f575a85ba5b87b4cc34a7fa97
[ "MIT" ]
1
2021-12-03T14:12:41.000Z
2021-12-03T14:12:41.000Z
/// \file SShaderCompiler.cpp /// \date 21/07/2018 /// \project OOM-Engine /// \package Render/Shader /// \author Vincent STEHLY--CALISTO #include <malloc.h> #include "Core/Debug/SLogger.hpp" #include "Render/Shader/SShaderCompiler.hpp" namespace Oom { GLuint SShaderCompiler::CreateProgram(const char* p_shader_name, const char* p_vertex_shader, const char* p_fragment_shader) { // Compiling shader GLuint vertex_shader_id = glCreateShader(GL_VERTEX_SHADER); GLuint fragment_shader_id = glCreateShader(GL_FRAGMENT_SHADER); if(!CompileShader(p_shader_name, "vertex ", p_vertex_shader, vertex_shader_id)) { SLogger::LogWaring("Vertex shader failed to compile, some materials could be disabled."); } if (!CompileShader(p_shader_name, "fragment", p_fragment_shader, fragment_shader_id)) { SLogger::LogWaring("Fragment shader failed to compile, some materials could be disabled."); } // Linking shader to cg program GLuint program_id = glCreateProgram(); glAttachShader(program_id, vertex_shader_id); glAttachShader(program_id, fragment_shader_id); glLinkProgram (program_id); GLint link_result = GL_FALSE; int info_log_lenght = 0; // Check the program GLsizei size = 0; glGetProgramiv(program_id, GL_LINK_STATUS, &link_result); glGetProgramiv(program_id, GL_INFO_LOG_LENGTH, &info_log_lenght); if (info_log_lenght > 0) { auto* p_buffer = (char*)malloc(static_cast<size_t>(info_log_lenght + 1)); glGetShaderInfoLog(program_id, info_log_lenght, nullptr, p_buffer); SLogger::LogError("glLinkProgram failed (%s) : %", p_shader_name, p_buffer); free(p_buffer); } glDetachShader(program_id, vertex_shader_id); glDetachShader(program_id, fragment_shader_id); glDeleteShader(vertex_shader_id); glDeleteShader(fragment_shader_id); return program_id; } bool SShaderCompiler::CompileShader(const char* p_shader_name, const char* p_shader_type, const char* p_shader, GLuint shader_id) { GLint compile_result = GL_FALSE; int info_log_lenght = 0; SLogger::LogInfo("Compiling %s shader %s ...", p_shader_type, p_shader_name); glShaderSource (shader_id, 1, &p_shader, nullptr); glCompileShader(shader_id); glGetShaderiv(shader_id, GL_COMPILE_STATUS, &compile_result); glGetShaderiv(shader_id, GL_INFO_LOG_LENGTH, &info_log_lenght); if (info_log_lenght > 0) { auto* p_buffer = (char*)malloc(1024); glGetShaderInfoLog(shader_id, 1024, nullptr, p_buffer); SLogger::LogError("Shader error (%s) : %", p_shader_name, p_buffer); free(p_buffer); return false; } return true; } }
31.622222
97
0.68201
Aredhele
14b78b3f6db46cf1f7e7774ccce5b9db20263e6f
9,747
cpp
C++
test/afu/Commands.cpp
OpenCAPI/ocse
ddc640fbafe9d027c0218ccad366bc6ce37c34c8
[ "Apache-2.0" ]
3
2019-10-10T19:39:12.000Z
2021-04-05T17:36:33.000Z
test/afu/Commands.cpp
OpenCAPI/ocse
ddc640fbafe9d027c0218ccad366bc6ce37c34c8
[ "Apache-2.0" ]
8
2019-10-25T12:51:45.000Z
2021-04-06T09:31:39.000Z
test/afu/Commands.cpp
OpenCAPI/ocse
ddc640fbafe9d027c0218ccad366bc6ce37c34c8
[ "Apache-2.0" ]
4
2019-10-31T13:05:39.000Z
2021-04-05T17:36:28.000Z
/* * Copyright 2015,2017 International Business Machines * * 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 <stdlib.h> #include "Commands.h" //extern uint8_t memory[128]; Command::Command (uint16_t c, bool comm_addr_par, bool comm_code_par, bool comm_tag_par, bool buff_read_par):code (c), completed (true), state (IDLE), command_address_parity (comm_addr_par), command_code_parity (comm_code_par), command_tag_parity (comm_tag_par), buffer_read_parity (buff_read_par) { } bool Command::is_completed () const { return completed; } uint32_t Command::get_tag () const { return tag; } OtherCommand::OtherCommand (uint16_t c, bool comm_addr_par, bool comm_code_par, bool comm_tag_par, bool buff_read_par): Command (c, comm_addr_par, comm_code_par, comm_tag_par, buff_read_par) { } void OtherCommand::send_command (AFU_EVENT * afu_event, uint32_t new_tag, uint64_t address, uint16_t command_size, uint8_t abort, uint16_t context) { uint8_t cmd_stream_id; uint8_t cmd_dl, cmd_pl; uint64_t cmd_be; uint8_t cmd_flag, cmd_endian, cmd_pg_size; uint16_t cmd_bdf, cmd_actag, cmd_afutag; uint16_t cmd_pasid; int rc, i; uint8_t ea_addr[9]; uint8_t cdata_bus[64], cdata_bad; memcpy((void*)&ea_addr, (void*) &address, sizeof(uint64_t)); //cmd_dl = 0x00; // 1=64 bytes, 2=128 bytes, 3=256 bytes //cmd_pl = 0x03; // 0=1B, 1=2B, 2=4B, 3=8B, 4=16B, 5=32B cmd_dl = afu_event->afu_tlx_cmd_dl; cmd_pl = afu_event->afu_tlx_cmd_pl; cmd_bdf = afu_event->afu_tlx_cmd_bdf; cmd_stream_id = afu_event->afu_tlx_cmd_stream_id; cmd_be = afu_event->afu_tlx_cmd_be; cmd_flag = afu_event->afu_tlx_cmd_flag; cmd_endian = afu_event->afu_tlx_cmd_endian; cmd_pasid = afu_event->afu_tlx_cmd_pasid; cmd_pg_size = afu_event->afu_tlx_cmd_pg_size; cmd_actag = afu_event->afu_tlx_cmd_actag; cmd_afutag = new_tag; printf("OtherCommand: sending command = 0x%x\n", Command::code); debug_msg("calling afu_tlx_send_cmd with command = 0x%x and paddress = 0x%x cmd_actag = 0x%x", Command::code, address, cmd_actag); debug_msg("ACTAG = 0x%x BDF = 0x%x PASID = 0x%x", cmd_actag, cmd_bdf, cmd_pasid); switch(Command::code) { case AFU_CMD_INTRP_REQ: case AFU_CMD_WAKE_HOST_THRD: // if(Command::code == AFU_CMD_INTRP_REQ) { printf("Commands: AFU_CMD_INTRP_REQ or AFU_CMD_WAKE_HOST\n"); rc = afu_tlx_send_cmd(afu_event, Command::code, cmd_actag, cmd_stream_id, ea_addr, cmd_afutag, cmd_dl, cmd_pl, #ifdef TLX4 cmd_os, #endif cmd_be, cmd_flag, cmd_endian, cmd_bdf, cmd_pasid, cmd_pg_size); // } break; case AFU_CMD_INTRP_REQ_D: // else if(Command::code == AFU_CMD_INTRP_REQ_D) { cmd_pl = 3; printf("Commands: AFU_CMD_INTRP_REQ_D\n"); for(i=0; i<8; i++) { cdata_bus[i] = i; } rc = afu_tlx_send_cmd_and_data(afu_event, Command::code, cmd_actag, cmd_stream_id, ea_addr, cmd_afutag, cmd_dl, cmd_pl, #ifdef TLX4 cmd_os, #endif cmd_be, cmd_flag, cmd_endian, cmd_bdf, cmd_pasid, cmd_pg_size, cdata_bus, cdata_bad); break; default: break; } printf("Commands: rc = 0x%x\n", rc); Command::state = WAITING_DATA; Command::tag = new_tag; printf("data = 0x"); for(i=0; i<9; i++) printf("%02x",(uint8_t)ea_addr[i]); printf("\n"); printf("OtherCommand: exit send command\n"); } void OtherCommand::process_command (AFU_EVENT * afu_event, uint8_t *) { if (Command::state == IDLE) { error_msg ("OtherCommand: Attempt to process response when no command is currently active"); } } bool OtherCommand::is_restart () const { return (Command::code ); } LoadCommand::LoadCommand (uint16_t c, bool comm_addr_par, bool comm_code_par, bool comm_tag_par, bool buff_read_par): Command (c, comm_addr_par, comm_code_par, comm_tag_par, buff_read_par) { } void LoadCommand::send_command (AFU_EVENT * afu_event, uint32_t new_tag, uint64_t address, uint16_t command_size, uint8_t abort, uint16_t context) { uint8_t cmd_stream_id; uint8_t cmd_dl, cmd_pl; uint64_t cmd_be; uint8_t cmd_flag, cmd_endian, cmd_pg_size; uint16_t cmd_bdf, cmd_actag, cmd_afutag; uint16_t cmd_pasid; int rc, i; uint8_t ea_addr[9]; memcpy((void*)&ea_addr, (void*) &address, sizeof(uint64_t)); //cmd_dl = 0x00; // 1=64 bytes, 2=128 bytes, 3=256 bytes //cmd_pl = 0x03; // 0=1B, 1=2B, 2=4B, 3=8B, 4=16B, 5=32B cmd_dl = afu_event->afu_tlx_cmd_dl; cmd_pl = afu_event->afu_tlx_cmd_pl; cmd_bdf = afu_event->afu_tlx_cmd_bdf; cmd_stream_id = afu_event->afu_tlx_cmd_stream_id; cmd_be = afu_event->afu_tlx_cmd_be; cmd_flag = afu_event->afu_tlx_cmd_flag; cmd_endian = afu_event->afu_tlx_cmd_endian; cmd_pasid = afu_event->afu_tlx_cmd_pasid; cmd_pg_size = afu_event->afu_tlx_cmd_pg_size; cmd_actag = afu_event->afu_tlx_cmd_actag; //cmd_afutag = afu_event->afu_tlx_cmd_afutag; cmd_afutag = new_tag; printf("LoadCommand: sending command = 0x%x\n", Command::code); //if (Command::state != IDLE) // error_msg // ("LoadCommand: Attempting to send command before previous command is completed"); //Command::completed = false; debug_msg("calling afu_tlx_send_cmd with command = 0x%x and paddress = 0x%x cmd_actag = 0x%x", Command::code, address, cmd_actag); debug_msg("ACTAG = 0x%x BDF = 0x%x PASID = 0x%x", cmd_actag, cmd_bdf, cmd_pasid); rc = afu_tlx_send_cmd(afu_event, Command::code, cmd_actag, cmd_stream_id, ea_addr, cmd_afutag, cmd_dl, cmd_pl, #ifdef TLX4 cmd_os, #endif cmd_be, cmd_flag, cmd_endian, cmd_bdf, cmd_pasid, cmd_pg_size); printf("Commands: rc = 0x%x\n", rc); Command::state = WAITING_DATA; Command::tag = new_tag; printf("data = 0x"); for(i=0; i<9; i++) printf("%02x",(uint8_t)ea_addr[i]); printf("\n"); printf("Command: exit send command\n"); } void LoadCommand::process_command (AFU_EVENT * afu_event, uint8_t * cache_line) { } void LoadCommand::process_buffer_write (AFU_EVENT * afu_event, uint8_t * cache_line) { Command::state = WAITING_RESPONSE; } bool LoadCommand::is_restart () const { return false; } StoreCommand::StoreCommand (uint16_t c, bool comm_addr_par, bool comm_code_par, bool comm_tag_par, bool buff_read_par): Command (c, comm_addr_par, comm_code_par, comm_tag_par, buff_read_par) { } void StoreCommand::send_command (AFU_EVENT * afu_event, uint32_t new_tag, uint64_t address, uint16_t command_size, uint8_t abort, uint16_t context) { uint8_t cmd_stream_id; uint8_t cmd_dl, cmd_pl; uint64_t cmd_be; uint8_t cmd_flag, cmd_endian, cmd_pg_size, cdata_bad; uint16_t cmd_bdf, cmd_actag, cmd_afutag; uint16_t cmd_pasid; int rc; // uint32_t afutag; uint8_t ea_addr[9], i; memcpy((void*)&ea_addr, (void*) &address, sizeof(uint64_t)); //cmd_dl = 0x01; // 1=64 bytes, 2=128 bytes, 3=256 bytes //cmd_pl = 0x03; // 0=1B, 1=2B, 2=4B, 3=8B, 4=16B, 5=32B cmd_dl = afu_event->afu_tlx_cmd_dl; cmd_pl = afu_event->afu_tlx_cmd_pl; cmd_bdf = afu_event->afu_tlx_cmd_bdf; cmd_stream_id = afu_event->afu_tlx_cmd_stream_id; cmd_be = afu_event->afu_tlx_cmd_be; cmd_flag = afu_event->afu_tlx_cmd_flag; cmd_endian = afu_event->afu_tlx_cmd_endian; cmd_pasid = afu_event->afu_tlx_cmd_pasid; cmd_pg_size = afu_event->afu_tlx_cmd_pg_size; cmd_actag = afu_event->afu_tlx_cmd_actag; //cmd_afutag = afu_event->afu_tlx_cmd_afutag; cmd_afutag = new_tag; cdata_bad = 0; printf("StoreCommand: sending command = 0x%x\n", Command::code); printf("memory = 0x"); for(i=0; i<9; i++) { printf("%02x", memory[i]); } printf("\n"); memcpy(afu_event->afu_tlx_cdata_bus, memory, 64); // if (Command::state != IDLE) // error_msg // ("StoreCommand: Attempting to send command before previous command is completed"); // Command::completed = false; debug_msg("calling afu_tlx_send_cmd_and_data with command = 0x%x and paddress = 0x%x cmd_actag = 0x%x", Command::code, address, cmd_actag); debug_msg("ACTAG = 0x%x BDF = 0x%x PASID = 0x%x", cmd_actag, cmd_bdf, cmd_pasid); rc = afu_tlx_send_cmd_and_data(afu_event, Command::code, cmd_actag, cmd_stream_id, ea_addr, cmd_afutag, cmd_dl, cmd_pl, #ifdef TLX4 cmd_os, #endif cmd_be, cmd_flag, cmd_endian, cmd_bdf, cmd_pasid, cmd_pg_size, afu_event->afu_tlx_cdata_bus, cdata_bad); printf("Commands: rc = 0x%x\n", rc); Command::state = WAITING_READ; Command::tag = new_tag; } void StoreCommand::process_command (AFU_EVENT * afu_event, uint8_t * cache_line) { } void StoreCommand::process_buffer_read (AFU_EVENT * afu_event, uint8_t * cache_line) { } bool StoreCommand::is_restart () const { return false; }
31.543689
150
0.672104
OpenCAPI
14b8aa4305d6ab8ad4d5e5b3259e4a80725b823c
3,262
hpp
C++
include/codegen/include/Zenject/StaticMemoryPool_8.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/Zenject/StaticMemoryPool_8.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/Zenject/StaticMemoryPool_8.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:45 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes // Including type: Zenject.StaticMemoryPoolBase`1 #include "Zenject/StaticMemoryPoolBase_1.hpp" // Including type: Zenject.IMemoryPool`8 #include "Zenject/IMemoryPool_8.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: Action`8<T1, T2, T3, T4, T5, T6, T7, T8> template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> class Action_8; // Forward declaring type: Action`1<T> template<typename T> class Action_1; } // Completed forward declares // Type namespace: Zenject namespace Zenject { // Autogenerated type: Zenject.StaticMemoryPool`8 template<typename TValue, typename TParam1, typename TParam2, typename TParam3, typename TParam4, typename TParam5, typename TParam6, typename TParam7> class StaticMemoryPool_8 : public Zenject::StaticMemoryPoolBase_1<TValue>, public Zenject::IMemoryPool_8<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue>, public Zenject::IDespawnableMemoryPool_1<TValue>, public Zenject::IMemoryPool { public: // private System.Action`8<TParam1,TParam2,TParam3,TParam4,TParam5,TParam6,TParam7,TValue> _onSpawnMethod // Offset: 0x0 System::Action_8<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue>* onSpawnMethod; // public System.Void .ctor(System.Action`8<TParam1,TParam2,TParam3,TParam4,TParam5,TParam6,TParam7,TValue> onSpawnMethod, System.Action`1<TValue> onDespawnedMethod) // Offset: 0x15DF380 static StaticMemoryPool_8<TValue, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7>* New_ctor(System::Action_8<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue>* onSpawnMethod, System::Action_1<TValue>* onDespawnedMethod) { return (StaticMemoryPool_8<TValue, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7>*)CRASH_UNLESS(il2cpp_utils::New(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<StaticMemoryPool_8<TValue, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7>*>::get(), onSpawnMethod, onDespawnedMethod)); } // public System.Void set_OnSpawnMethod(System.Action`8<TParam1,TParam2,TParam3,TParam4,TParam5,TParam6,TParam7,TValue> value) // Offset: 0x15DF3DC void set_OnSpawnMethod(System::Action_8<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue>* value) { CRASH_UNLESS(il2cpp_utils::RunMethod(this, "set_OnSpawnMethod", value)); } // public TValue Spawn(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TParam6 p6, TParam7 p7) // Offset: 0x15DF3E4 TValue Spawn(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TParam6 p6, TParam7 p7) { return CRASH_UNLESS(il2cpp_utils::RunMethod<TValue>(this, "Spawn", p1, p2, p3, p4, p5, p6, p7)); } }; // Zenject.StaticMemoryPool`8 } DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(Zenject::StaticMemoryPool_8, "Zenject", "StaticMemoryPool`8"); #pragma pack(pop)
62.730769
324
0.745555
Futuremappermydud
14bcb0cdb3954fea721d40b8fc65340cab770211
985
cpp
C++
FTSE/entities/Book.cpp
melindil/FTSE
c0b54194900ac45ce1ecc778d838a72d09278bab
[ "MIT" ]
3
2019-10-05T15:51:12.000Z
2021-01-08T21:58:48.000Z
FTSE/entities/Book.cpp
melindil/FTSE
c0b54194900ac45ce1ecc778d838a72d09278bab
[ "MIT" ]
2
2021-06-04T13:42:16.000Z
2021-07-27T10:38:38.000Z
FTSE/entities/Book.cpp
melindil/FTSE
c0b54194900ac45ce1ecc778d838a72d09278bab
[ "MIT" ]
2
2018-07-03T11:31:11.000Z
2021-06-16T21:05:38.000Z
#include "Book.h" #include "LuaHelper.h" #include "Helpers.h" Book::Book(EntityID id) : Collectable(id) { } Book::Book(void * ptr) : Collectable(ptr) { } Book::~Book() { } void Book::MakeLuaObject(lua_State * l) { lua_newtable(l); lua_pushinteger(l, GetID()); lua_setfield(l, -2, "id"); lua_getglobal(l, "BookMetaTable"); lua_setmetatable(l, -2); } Book::BookStructType * Book::GetStruct() { return (BookStructType*)(((uint32_t)GetEntityPointer()) + OFFSET_BOOK_STRUCT); } void Book::RegisterLua(lua_State * l, Logger * tmp) { luaL_newmetatable(l, "BookMetaTable"); Collectable::SetLuaSubclass(l); lua_pushcfunction(l, (LuaHelper::THUNK<Book, &Book::GetSkillAffected>())); lua_setfield(l, -2, "GetSkillAffected"); lua_pushstring(l, "Book"); lua_setfield(l, -2, "ClassType"); lua_pushvalue(l, -1); lua_setfield(l, -2, "__index"); lua_setglobal(l, "BookMetaTable"); } std::string Book::GetSkillAffected() { return Helpers::WcharToUTF8(GetStruct()->skill); }
18.240741
79
0.694416
melindil
14c09198d6978f73bc5b6839d7d58a6e12850347
1,367
cpp
C++
src/ui/uicheckbox.cpp
alexeyden/whack
2bff3beb0afb8c5aaba996b2838d2f0b9797039c
[ "WTFPL" ]
null
null
null
src/ui/uicheckbox.cpp
alexeyden/whack
2bff3beb0afb8c5aaba996b2838d2f0b9797039c
[ "WTFPL" ]
null
null
null
src/ui/uicheckbox.cpp
alexeyden/whack
2bff3beb0afb8c5aaba996b2838d2f0b9797039c
[ "WTFPL" ]
null
null
null
#include "uicheckbox.h" UICheckBox::UICheckBox(UIManager* manager): UIElement(manager, false), checked(false) { } void UICheckBox::render(Texture* out) { unsigned color = isPressed() ? _manager->style()->colorActivated : _manager->style()->colorNormal; if(checked) _manager->style()->checkboxChecked.draw(out, bounds.x1 + paddingX, bounds.y1 + paddingY, color); else _manager->style()->checkboxUnchecked.draw(out, bounds.x1 + paddingX, bounds.y1 + paddingY, color); const Font& font = isPressed() ? _manager->style()->fontActivated : _manager->style()->fontNormal; const Rect<int>& min = minBounds(); font.drawText(out, bounds.x1 + paddingX + _manager->style()->checkboxChecked.width() + gap, bounds.y1 + min.centerY() - font.charSize()/2, text.c_str()); } void UICheckBox::update(float dt) { (void) dt; } Rect< int > UICheckBox::minBounds() const { return Rect<int>( 0, 0, _manager->style()->checkboxChecked.width() + gap + _manager->style()->fontNormal.textBounds(text).first + paddingX * 2, std::max(_manager->style()->fontNormal.charSize(), _manager->style()->checkboxChecked.height()) + paddingX * 2 ); } bool UICheckBox::onMouseReleased(double x, double y, int button, int mods) { UIElement::onMouseReleased(x, y, button, mods); checked = !checked; for(auto& ch : _clickHandlers) ch(checked); return true; }
28.479167
121
0.693489
alexeyden
14c5028ed5cc6188928c31226565c539e32d5163
986
cpp
C++
src/interface/graphics/Buffer.cpp
FuriousProton/proton
1bb790932e730d119ad68266159a77ad93eeef99
[ "MIT" ]
null
null
null
src/interface/graphics/Buffer.cpp
FuriousProton/proton
1bb790932e730d119ad68266159a77ad93eeef99
[ "MIT" ]
null
null
null
src/interface/graphics/Buffer.cpp
FuriousProton/proton
1bb790932e730d119ad68266159a77ad93eeef99
[ "MIT" ]
null
null
null
// // Created by teeebor on 2017-10-05. // #include <glbinding/gl/gl.h> #include "../../../include/interface/Buffer.h" namespace proton{ using namespace gl; Buffer::Buffer(const void *data, int count, unsigned int componentCount) { load(data,count,componentCount); } void Buffer::load(const void *data, int count, unsigned int componentCount) { mComponentCount = componentCount; mCount = count; glGenBuffers(1, &mBufferId); glBindBuffer(GL_ARRAY_BUFFER, mBufferId); glBufferData(GL_ARRAY_BUFFER, count * sizeof(float), data, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } Buffer::~Buffer() { glDeleteBuffers(1,&mBufferId); } void Buffer::bind() const { glBindBuffer(GL_ARRAY_BUFFER, mBufferId); } void Buffer::unbind() const { glBindBuffer(GL_ARRAY_BUFFER, 0); } unsigned int Buffer::getComponentCount() { return mComponentCount; } }
25.947368
83
0.64503
FuriousProton
14c921fdda223e050127c85ea61d0bba4216faf4
10,741
hpp
C++
lib/quasimo/base/qcor_qsim.hpp
moar55/qcor
e744642c3e87ededf60813a442b7cde502467de4
[ "BSD-3-Clause" ]
null
null
null
lib/quasimo/base/qcor_qsim.hpp
moar55/qcor
e744642c3e87ededf60813a442b7cde502467de4
[ "BSD-3-Clause" ]
null
null
null
lib/quasimo/base/qcor_qsim.hpp
moar55/qcor
e744642c3e87ededf60813a442b7cde502467de4
[ "BSD-3-Clause" ]
null
null
null
/******************************************************************************* * Copyright (c) 2018-, UT-Battelle, LLC. * All rights reserved. This program and the accompanying materials * are made available under the terms of the BSD 3-Clause License * which accompanies this distribution. * * Contributors: * Alexander J. McCaskey - initial API and implementation * Thien Nguyen - implementation *******************************************************************************/ #pragma once #include <memory> #include <qalloc> #include <xacc_internal_compiler.hpp> #include "Accelerator.hpp" #include "AcceleratorBuffer.hpp" #include "Circuit.hpp" #include "kernel_evaluator.hpp" #include "objective_function.hpp" #include "qcor_observable.hpp" #include "qcor_optimizer.hpp" #include "qcor_utils.hpp" #include "qrt.hpp" #include "quantum_kernel.hpp" using CompositeInstruction = xacc::CompositeInstruction; using Accelerator = xacc::Accelerator; using Identifiable = xacc::Identifiable; namespace qcor { namespace QuaSiMo { // Struct captures a state-preparation circuit. struct Ansatz { std::shared_ptr<CompositeInstruction> circuit; std::vector<std::string> symbol_names; size_t nb_qubits; }; // State-preparation method (i.e. ansatz): // For example, // - Real time Hamiltonian evolution with Trotter approximation (of various // orders) // - Real time Hamiltonian evolution with Taylor series/LCU approach // - Imaginary time evolution with QITE // - Thermo-field doubles state preparation // - Two-point correlation function measurements // - QFT class AnsatzGenerator : public Identifiable { public: virtual Ansatz create_ansatz(Operator *obs = nullptr, const HeterogeneousMap &params = {}) = 0; }; // CostFunctionEvaluator take an unknown quantum state (the circuit that // prepares the unknown state) and a target operator (e.g. Hamiltonian // Observable) as input and produce a estimation as output. class CostFunctionEvaluator : public Identifiable { public: // Evaluate the cost virtual double evaluate(std::shared_ptr<CompositeInstruction> state_prep) = 0; // Batching evaluation: observing multiple kernels in batches. // E.g. for non-vqe cases (Trotter), we have all kernels ready for observable // evaluation virtual std::vector<double> evaluate( std::vector<std::shared_ptr<CompositeInstruction>> state_prep_circuits) { // Default is one-by-one, subclass to provide batching if supported. std::vector<double> result; for (auto &circuit : state_prep_circuits) { result.emplace_back(evaluate(circuit)); } return result; } virtual bool initialize(Operator *observable, const HeterogeneousMap &params = {}); protected: Operator *target_operator; HeterogeneousMap hyperParams; }; // Trotter time-dependent simulation workflow // Time-dependent Hamiltonian is a function mapping from time t to Observable // operator. using TdObservable = std::function<Operator(double)>; // Capture a quantum chemistry problem. // TODO: generalize this to capture all potential use cases. struct QuantumSimulationModel { QuantumSimulationModel() : observable(nullptr) {} // Copy Constructor QuantumSimulationModel(QuantumSimulationModel &other) : name(other.name), observable(other.observable), hamiltonian(other.hamiltonian), user_defined_ansatz(other.user_defined_ansatz), owns_observable(other.owns_observable) { if (other.owns_observable) { // Transfer ownership. other.owns_observable = false; } } // Move Constructor QuantumSimulationModel(QuantumSimulationModel &&other) : name(other.name), observable(other.observable), hamiltonian(other.hamiltonian), user_defined_ansatz(other.user_defined_ansatz), owns_observable(other.owns_observable) { if (other.owns_observable) { // Transfer ownership. other.owns_observable = false; } } // Model name. std::string name; // The Observable operator that needs to be measured/minimized. Operator *observable; // The system Hamiltonian which can be static or dynamic (time-dependent). // This can be the same or different from the observable operator. TdObservable hamiltonian; // QuantumSimulationModel also support a user-defined (fixed) ansatz. std::shared_ptr<KernelFunctor> user_defined_ansatz; // clients can create raw operator pointers, and // provided them to this Model and indicate that // the Model owns the observable, and will delete it // upon destruction bool owns_observable = false; // Destructor, delete observable if we own it ~QuantumSimulationModel() { if (owns_observable) { printf("Deleting the raw ptr\n"); delete observable; } } }; // Generic model builder (factory) // Create a model which capture the problem description. class ModelFactory { public: // Generic Heisenberg model struct HeisenbergModel { double Jx = 0.0; double Jy = 0.0; double Jz = 0.0; double h_ext = 0.0; // Support for H_BAR normalization double H_BAR = 1.0; // "X", "Y", or "Z" std::string ext_dir = "Z"; int num_spins = 2; std::vector<int> initial_spins; // Time-dependent freq. // Default to using the cosine function. double freq = 0.0; // User-provided custom time-dependent function: std::function<double(double)> time_func; // Allows a simple Pythonic kwarg-style initialization. // i.e. all params have preset defaults, only update those that are // specified. void fromDict(const HeterogeneousMap &params); bool validateModel() const { const bool ext_dir_valid = (ext_dir == "X" || ext_dir == "Y" || ext_dir == "Z"); const bool initial_spins_valid = (initial_spins.empty() || (initial_spins.size() == num_spins)); return ext_dir_valid && initial_spins_valid; } }; // ======== Direct model builder ============== // Strongly-typed parameters/argument. // Build a simple Hamiltonian-based model: static Hamiltonian which is also // the observable of interest. static QuantumSimulationModel createModel( Operator *obs, const HeterogeneousMap &params = {}); static QuantumSimulationModel createModel( Operator &obs, const HeterogeneousMap &params = {}) { return createModel(&obs, params); } // Build a time-dependent problem model: // - obs: observable operator to measure. // - td_ham: time-dependent Hamiltonian to evolve the system. // e.g. a function to map from time to Hamiltonian operator. static QuantumSimulationModel createModel( Operator *obs, TdObservable td_ham, const HeterogeneousMap &params = {}); // Pauli operator overload: static QuantumSimulationModel createModel( Operator &obs, TdObservable td_ham, const HeterogeneousMap &params = {}) { return createModel(&obs, td_ham, params); } // ======== High-level model builder ============== // The idea here is to have contributed modules to translate problem // descriptions in various formats, e.g. PyScf, Psi4, broombridge, etc. into // QCOR's Observable type. Inputs: // - format: key to look up module/plugin to digest the input data. // - data: model descriptions in plain-text format, e.g. load from file. // - params: extra parameters to pass to the parser/generator, // e.g. any transformations required in order to generate the // Observable. static QuantumSimulationModel createModel( const std::string &format, const std::string &data, const HeterogeneousMap &params = {}); // Predefined model type that we support intrinsically. enum class ModelType { Heisenberg }; static QuantumSimulationModel createModel(ModelType type, const HeterogeneousMap &params); // ========== QuantumSimulationModel with a fixed (pre-defined) ansatz // ======== The ansatz is provided as a QCOR kernel. template <typename... Args> static inline QuantumSimulationModel createModel( void (*quantum_kernel_functor)(std::shared_ptr<CompositeInstruction>, Args...), Operator *obs, size_t nbQubits, size_t nbParams) { auto kernel_functor = createKernelFunctor(quantum_kernel_functor, nbQubits, nbParams); QuantumSimulationModel model; model.observable = obs; model.user_defined_ansatz = kernel_functor; return model; } template <typename... Args> static inline QuantumSimulationModel createModel( void (*quantum_kernel_functor)(std::shared_ptr<CompositeInstruction>, Args...), Operator &obs, size_t nbQubits, size_t nbParams) { return createModel(quantum_kernel_functor, &obs, nbQubits, nbParams); } // Passing the state-preparation ansatz as a CompositeInstruction static inline QuantumSimulationModel createModel( std::shared_ptr<CompositeInstruction> composite, Operator *obs) { QuantumSimulationModel model; model.observable = obs; model.user_defined_ansatz = createKernelFunctor(composite); return model; } static inline QuantumSimulationModel createModel( std::shared_ptr<CompositeInstruction> composite, Operator &obs) { return createModel(composite, &obs); } }; // Quantum Simulation Workflow (Protocol) // This can handle both variational workflow (optimization loop) // as well as simple Trotter evolution workflow. // Result is stored in a HetMap using QuantumSimulationResult = HeterogeneousMap; // Abstract workflow: class QuantumSimulationWorkflow : public Identifiable { public: virtual bool initialize(const HeterogeneousMap &params) = 0; virtual QuantumSimulationResult execute( const QuantumSimulationModel &model) = 0; protected: std::shared_ptr<CostFunctionEvaluator> evaluator; }; // Get workflow by name: std::shared_ptr<QuantumSimulationWorkflow> getWorkflow( const std::string &name, const HeterogeneousMap &init_params); // Get the Obj (cost) function evaluator: std::shared_ptr<CostFunctionEvaluator> getObjEvaluator( Operator *observable, const std::string &name = "default", const HeterogeneousMap &init_params = {}); inline std::shared_ptr<CostFunctionEvaluator> getObjEvaluator( Operator &obs, const std::string &name = "default", const HeterogeneousMap &init_params = {}) { return getObjEvaluator(&obs, name, init_params); } // Helper to apply optimization/placement before evaluation: void executePassManager( std::vector<std::shared_ptr<CompositeInstruction>> evalKernels); } // namespace QuaSiMo } // namespace qcor
36.534014
81
0.699935
moar55
14c9cda500cfb12a37e94ef483653a53c21f9ca9
3,898
hpp
C++
stan/math/gpu/multiply.hpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
null
null
null
stan/math/gpu/multiply.hpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
null
null
null
stan/math/gpu/multiply.hpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_GPU_MULTIPLY_HPP #define STAN_MATH_GPU_MULTIPLY_HPP #ifdef STAN_OPENCL #include <stan/math/gpu/matrix_gpu.hpp> #include <stan/math/gpu/kernels/scalar_mul.hpp> #include <stan/math/gpu/kernels/matrix_multiply.hpp> #include <Eigen/Dense> namespace stan { namespace math { /** * Multiplies the specified matrix on the GPU * with the specified scalar. * * @param A matrix * @param scalar scalar * @return matrix multipled with scalar */ inline matrix_gpu multiply(const matrix_gpu& A, const double scalar) { matrix_gpu temp(A.rows(), A.cols()); if (A.size() == 0) return temp; try { opencl_kernels::scalar_mul(cl::NDRange(A.rows(), A.cols()), temp.buffer(), A.buffer(), scalar, A.rows(), A.cols()); } catch (const cl::Error& e) { check_opencl_error("multiply scalar", e); } return temp; } /** * Multiplies the specified matrix on the GPU * with the specified scalar. * * @param scalar scalar * @param A matrix * @return matrix multipled with scalar */ inline auto multiply(const double scalar, const matrix_gpu& A) { return multiply(A, scalar); } /** * Computes the product of the specified GPU matrices. * * Computes the matrix multiplication C[M, K] = A[M, N] x B[N, K] * * @param A first matrix * @param B second matrix * @return the product of the first and second matrix * * @throw <code>std::invalid_argument</code> if the * number of columns in A and rows in B do not match */ inline auto multiply(const matrix_gpu& A, const matrix_gpu& B) { check_size_match("multiply (GPU)", "A.cols()", A.cols(), "B.rows()", B.rows()); matrix_gpu temp(A.rows(), B.cols()); if (A.size() == 0 || B.size() == 0) { temp.zeros(); return temp; } int local = opencl_kernels::matrix_multiply.make_functor.get_opts().at( "THREAD_BLOCK_SIZE"); int Mpad = ((A.rows() + local - 1) / local) * local; int Npad = ((B.cols() + local - 1) / local) * local; int Kpad = ((A.cols() + local - 1) / local) * local; // padding the matrices so the dimensions are divisible with local // improves performance and readability because we can omit // if statements in the // multiply kernel matrix_gpu tempPad(Mpad, Npad); matrix_gpu Apad(Mpad, Kpad); matrix_gpu Bpad(Kpad, Npad); opencl_kernels::zeros(cl::NDRange(Mpad, Kpad), Apad.buffer(), Mpad, Kpad, TriangularViewGPU::Entire); opencl_kernels::zeros(cl::NDRange(Kpad, Npad), Bpad.buffer(), Kpad, Npad, TriangularViewGPU::Entire); Apad.sub_block(A, 0, 0, 0, 0, A.rows(), A.cols()); Bpad.sub_block(B, 0, 0, 0, 0, B.rows(), B.cols()); int wpt = opencl_kernels::matrix_multiply.make_functor.get_opts().at( "WORK_PER_THREAD"); try { opencl_kernels::matrix_multiply( cl::NDRange(Mpad, Npad / wpt), cl::NDRange(local, local / wpt), Apad.buffer(), Bpad.buffer(), tempPad.buffer(), Apad.rows(), Bpad.cols(), Bpad.rows()); } catch (cl::Error& e) { check_opencl_error("multiply", e); } // unpadding the result matrix temp.sub_block(tempPad, 0, 0, 0, 0, temp.rows(), temp.cols()); return temp; } /** * Templated product operator for GPU matrices. * * Computes the matrix multiplication C[M, K] = A[M, N] x B[N, K]. * * @param A A matrix or scalar * @param B A matrix or scalar * @return the product of the first and second arguments * * @throw <code>std::invalid_argument</code> if the * number of columns in A and rows in B do not match */ inline matrix_gpu operator*(const matrix_gpu& A, const matrix_gpu& B) { return multiply(A, B); } inline matrix_gpu operator*(const matrix_gpu& B, const double scalar) { return multiply(B, scalar); } inline matrix_gpu operator*(const double scalar, const matrix_gpu& B) { return multiply(scalar, B); } } // namespace math } // namespace stan #endif #endif
31.691057
78
0.65803
jrmie
14c9fce899e636ec1555150d0e5145862770f74d
15,557
cpp
C++
Source/SIMPLib/CoreFilters/CropVertexGeometry.cpp
mmarineBlueQuartz/SIMPL
834f9009944efe69d94b5b77a641d96db3e9543b
[ "NRL" ]
null
null
null
Source/SIMPLib/CoreFilters/CropVertexGeometry.cpp
mmarineBlueQuartz/SIMPL
834f9009944efe69d94b5b77a641d96db3e9543b
[ "NRL" ]
2
2019-02-23T20:46:12.000Z
2019-07-11T15:34:13.000Z
Source/SIMPLib/CoreFilters/CropVertexGeometry.cpp
mmarineBlueQuartz/SIMPL
834f9009944efe69d94b5b77a641d96db3e9543b
[ "NRL" ]
null
null
null
/* ============================================================================ * Copyright (c) 2009-2016 BlueQuartz Software, LLC * * 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 BlueQuartz Software, the US Air Force, 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. * * The code contained herein was partially funded by the followig contracts: * United States Air Force Prime Contract FA8650-07-D-5800 * United States Air Force Prime Contract FA8650-10-D-5210 * United States Prime Contract Navy N00173-07-C-2068 * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #include "CropVertexGeometry.h" #include <cassert> #include "SIMPLib/Common/Constants.h" #include "SIMPLib/Common/TemplateHelpers.h" #include "SIMPLib/FilterParameters/AbstractFilterParametersReader.h" #include "SIMPLib/FilterParameters/DataContainerSelectionFilterParameter.h" #include "SIMPLib/FilterParameters/FloatFilterParameter.h" #include "SIMPLib/FilterParameters/StringFilterParameter.h" #include "SIMPLib/Geometry/VertexGeom.h" #include "SIMPLib/SIMPLibVersion.h" // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- CropVertexGeometry::CropVertexGeometry() : m_DataContainerName(SIMPL::Defaults::VertexDataContainerName) , m_CroppedDataContainerName("CroppedDataContainer") , m_XMin(0) , m_YMin(0) , m_ZMin(0) , m_XMax(0) , m_YMax(0) , m_ZMax(0) { } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- CropVertexGeometry::~CropVertexGeometry() = default; // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CropVertexGeometry::setupFilterParameters() { FilterParameterVector parameters; DataContainerSelectionFilterParameter::RequirementType req; IGeometry::Types reqGeom = {IGeometry::Type::Vertex}; req.dcGeometryTypes = reqGeom; parameters.push_back(SIMPL_NEW_DC_SELECTION_FP("Vertex Geometry to Crop", DataContainerName, FilterParameter::RequiredArray, CropVertexGeometry, req)); parameters.push_back(SIMPL_NEW_FLOAT_FP("X Min", XMin, FilterParameter::Parameter, CropVertexGeometry)); parameters.push_back(SIMPL_NEW_FLOAT_FP("Y Min", YMin, FilterParameter::Parameter, CropVertexGeometry)); parameters.push_back(SIMPL_NEW_FLOAT_FP("Z Min", ZMin, FilterParameter::Parameter, CropVertexGeometry)); parameters.push_back(SIMPL_NEW_FLOAT_FP("X Max", XMax, FilterParameter::Parameter, CropVertexGeometry)); parameters.push_back(SIMPL_NEW_FLOAT_FP("Y Max", YMax, FilterParameter::Parameter, CropVertexGeometry)); parameters.push_back(SIMPL_NEW_FLOAT_FP("Z Max", ZMax, FilterParameter::Parameter, CropVertexGeometry)); parameters.push_back(SIMPL_NEW_STRING_FP("Cropped Data Container", CroppedDataContainerName, FilterParameter::CreatedArray, CropVertexGeometry)); setFilterParameters(parameters); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CropVertexGeometry::readFilterParameters(AbstractFilterParametersReader* reader, int index) { reader->openFilterGroup(this, index); setDataContainerName(reader->readString("DataContainerName", getDataContainerName())); setXMin(reader->readValue("XMin", getXMin())); setYMin(reader->readValue("YMin", getYMin())); setZMin(reader->readValue("ZMin", getZMin())); setXMax(reader->readValue("XMax", getXMax())); setYMax(reader->readValue("YMax", getYMax())); setZMax(reader->readValue("ZMax", getZMax())); setCroppedDataContainerName(reader->readString("CroppedDataContainerName", getCroppedDataContainerName())); reader->closeFilterGroup(); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CropVertexGeometry::initialize() { setErrorCondition(0); setWarningCondition(0); setCancel(false); m_AttrMatList.clear(); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CropVertexGeometry::dataCheck() { setErrorCondition(0); setWarningCondition(0); initialize(); getDataContainerArray()->getPrereqGeometryFromDataContainer<VertexGeom, AbstractFilter>(this, getDataContainerName()); if(getXMax() < getXMin()) { QString ss = QObject::tr("X Max (%1) less than X Min (%2)").arg(getXMax()).arg(getXMin()); setErrorCondition(-5550); notifyErrorMessage(getHumanLabel(), ss, getErrorCondition()); } if(getYMax() < getYMin()) { QString ss = QObject::tr("Y Max (%1) less than Y Min (%2)").arg(getYMax()).arg(getYMin()); setErrorCondition(-5550); notifyErrorMessage(getHumanLabel(), ss, getErrorCondition()); } if(getZMax() < getZMin()) { QString ss = QObject::tr("Z Max (%1) less than Z Min (%2)").arg(getZMax()).arg(getZMin()); setErrorCondition(-5550); notifyErrorMessage(getHumanLabel(), ss, getErrorCondition()); } DataContainer::Pointer dc = getDataContainerArray()->createNonPrereqDataContainer<AbstractFilter>(this, getCroppedDataContainerName()); if(getErrorCondition() < 0) { return; } VertexGeom::Pointer crop = VertexGeom::CreateGeometry(0, SIMPL::Geometry::VertexGeometry, !getInPreflight()); dc->setGeometry(crop); DataContainer::Pointer m = getDataContainerArray()->getDataContainer(getDataContainerName()); m_AttrMatList = m->getAttributeMatrixNames(); QVector<size_t> tDims(1, 0); QList<QString> tempDataArrayList; DataArrayPath tempPath; AttributeMatrix::Type tempAttrMatType = AttributeMatrix::Type::Vertex; if(getErrorCondition() < 0) { return; } for(auto&& attr_mat : m_AttrMatList) { AttributeMatrix::Pointer tmpAttrMat = m->getPrereqAttributeMatrix(this, attr_mat, -301); if(getErrorCondition() >= 0) { tempAttrMatType = tmpAttrMat->getType(); if(tempAttrMatType != AttributeMatrix::Type::Vertex) { AttributeMatrix::Pointer attrMat = tmpAttrMat->deepCopy(getInPreflight()); dc->addAttributeMatrix(attr_mat, attrMat); } else { dc->createNonPrereqAttributeMatrix(this, tmpAttrMat->getName(), tDims, AttributeMatrix::Type::Vertex); tempDataArrayList = tmpAttrMat->getAttributeArrayNames(); for(auto&& data_array : tempDataArrayList) { tempPath.update(getCroppedDataContainerName(), tmpAttrMat->getName(), data_array); IDataArray::Pointer tmpDataArray = tmpAttrMat->getPrereqIDataArray<IDataArray, AbstractFilter>(this, data_array, -90002); if(getErrorCondition() >= 0) { QVector<size_t> cDims = tmpDataArray->getComponentDimensions(); TemplateHelpers::CreateNonPrereqArrayFromArrayType()(this, tempPath, cDims, tmpDataArray); } } } } } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CropVertexGeometry::preflight() { // These are the REQUIRED lines of CODE to make sure the filter behaves correctly setInPreflight(true); // Set the fact that we are preflighting. emit preflightAboutToExecute(); // Emit this signal so that other widgets can do one file update emit updateFilterParameters(this); // Emit this signal to have the widgets push their values down to the filter dataCheck(); // Run our DataCheck to make sure everthing is setup correctly emit preflightExecuted(); // We are done preflighting this filter setInPreflight(false); // Inform the system this filter is NOT in preflight mode anymore. } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- template <typename T> void copyDataToCroppedGeometry(IDataArray::Pointer inDataPtr, IDataArray::Pointer outDataPtr, std::vector<int64_t>& croppedPoints) { typename DataArray<T>::Pointer inputDataPtr = std::dynamic_pointer_cast<DataArray<T>>(inDataPtr); T* inputData = static_cast<T*>(inputDataPtr->getPointer(0)); typename DataArray<T>::Pointer croppedDataPtr = std::dynamic_pointer_cast<DataArray<T>>(outDataPtr); T* croppedData = static_cast<T*>(croppedDataPtr->getPointer(0)); size_t nComps = inDataPtr->getNumberOfComponents(); size_t tmpIndex = 0; size_t ptrIndex = 0; for(std::vector<int64_t>::size_type i = 0; i < croppedPoints.size(); i++) { for(size_t d = 0; d < nComps; d++) { tmpIndex = nComps * i + d; ptrIndex = nComps * croppedPoints[i] + d; croppedData[tmpIndex] = inputData[ptrIndex]; } } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CropVertexGeometry::execute() { setErrorCondition(0); setWarningCondition(0); dataCheck(); if(getErrorCondition() < 0) { return; } DataContainer::Pointer m = getDataContainerArray()->getDataContainer(getDataContainerName()); DataContainer::Pointer dc = getDataContainerArray()->getDataContainer(getCroppedDataContainerName()); VertexGeom::Pointer vertices = getDataContainerArray()->getDataContainer(getDataContainerName())->getGeometryAs<VertexGeom>(); int64_t numVerts = vertices->getNumberOfVertices(); float* allVerts = vertices->getVertexPointer(0); std::vector<int64_t> croppedPoints; croppedPoints.reserve(numVerts); for(int64_t i = 0; i < numVerts; i++) { if(getCancel()) { return; } if(allVerts[3 * i + 0] >= m_XMin && allVerts[3 * i + 0] <= m_XMax && allVerts[3 * i + 1] >= m_YMin && allVerts[3 * i + 1] <= m_YMax && allVerts[3 * i + 2] >= m_ZMin && allVerts[3 * i + 2] <= m_ZMax) { croppedPoints.push_back(i); } } croppedPoints.shrink_to_fit(); VertexGeom::Pointer crop = dc->getGeometryAs<VertexGeom>(); crop->resizeVertexList(croppedPoints.size()); float coords[3] = {0.0f, 0.0f, 0.0f}; for(std::list<int64_t>::size_type i = 0; i < croppedPoints.size(); i++) { if(getCancel()) { return; } vertices->getCoords(croppedPoints[i], coords); crop->setCoords(i, coords); } QVector<size_t> tDims(1, croppedPoints.size()); for(auto&& attr_mat : m_AttrMatList) { AttributeMatrix::Pointer tmpAttrMat = dc->getPrereqAttributeMatrix(this, attr_mat, -301); if(getErrorCondition() >= 0) { AttributeMatrix::Type tempAttrMatType = tmpAttrMat->getType(); if(tempAttrMatType == AttributeMatrix::Type::Vertex) { tmpAttrMat->resizeAttributeArrays(tDims); QList<QString> srcDataArrays = tmpAttrMat->getAttributeArrayNames(); AttributeMatrix::Pointer srcAttrMat = m->getAttributeMatrix(tmpAttrMat->getName()); assert(srcAttrMat); for(auto&& data_array : srcDataArrays) { IDataArray::Pointer src = srcAttrMat->getAttributeArray(data_array); IDataArray::Pointer dest = tmpAttrMat->getAttributeArray(data_array); assert(src); assert(dest); assert(src->getNumberOfComponents() == dest->getNumberOfComponents()); EXECUTE_FUNCTION_TEMPLATE(this, copyDataToCroppedGeometry, src, src, dest, croppedPoints) } } } } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- AbstractFilter::Pointer CropVertexGeometry::newFilterInstance(bool copyFilterParameters) const { CropVertexGeometry::Pointer filter = CropVertexGeometry::New(); if(copyFilterParameters) { copyFilterParameterInstanceVariables(filter.get()); } return filter; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- const QString CropVertexGeometry::getCompiledLibraryName() const { return Core::CoreBaseName; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- const QString CropVertexGeometry::getBrandingString() const { return "SIMPLib Core Filter"; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- const QString CropVertexGeometry::getFilterVersion() const { QString version; QTextStream vStream(&version); vStream << SIMPLib::Version::Major() << "." << SIMPLib::Version::Minor() << "." << SIMPLib::Version::Patch(); return version; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- const QString CropVertexGeometry::getGroupName() const { return SIMPL::FilterGroups::CoreFilters; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- const QUuid CropVertexGeometry::getUuid() { return QUuid("{f28cbf07-f15a-53ca-8c7f-b41a11dae6cc}"); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- const QString CropVertexGeometry::getSubGroupName() const { return SIMPL::FilterSubGroups::CropCutFilters; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- const QString CropVertexGeometry::getHumanLabel() const { return "Crop Geometry (Vertex)"; }
39.787724
171
0.588353
mmarineBlueQuartz
14c9fe8f249b93c1711aa7410d5ea6873577134b
181
cpp
C++
async_pool/test/test.foo.cpp
spjuanjoc/concurrency_cpp
50c25c89d202f945c2d6df7df341880b3b93f0b1
[ "MIT" ]
null
null
null
async_pool/test/test.foo.cpp
spjuanjoc/concurrency_cpp
50c25c89d202f945c2d6df7df341880b3b93f0b1
[ "MIT" ]
null
null
null
async_pool/test/test.foo.cpp
spjuanjoc/concurrency_cpp
50c25c89d202f945c2d6df7df341880b3b93f0b1
[ "MIT" ]
null
null
null
#include "catch2/catch.hpp" #include <optional> #include "ParallelAccumulate.hpp" TEST_CASE("test the execution of foo", "[foo]") { REQUIRE( 1 == 1); std::optional<int> var; }
18.1
47
0.679558
spjuanjoc
14ca452d2c14a4d2f80275281caaa38f78c4b4a9
790
cpp
C++
src/client/client/Command_Client_Thread.cpp
Kuga23/Projet-M2
85c879b8fd1ed4fdf89eedd9f89841cbd7a1e433
[ "MIT" ]
null
null
null
src/client/client/Command_Client_Thread.cpp
Kuga23/Projet-M2
85c879b8fd1ed4fdf89eedd9f89841cbd7a1e433
[ "MIT" ]
null
null
null
src/client/client/Command_Client_Thread.cpp
Kuga23/Projet-M2
85c879b8fd1ed4fdf89eedd9f89841cbd7a1e433
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <string.h> #include <sstream> #include <map> #include <memory> #include <unistd.h> #include <thread> #include <sys/socket.h> #include <netinet/in.h> #include <sys/types.h> #include <state.h> #include "render.h" #include "engine.h" #include "ai.h" #include "client.h" using namespace client; using namespace state; using namespace render; using namespace engine; using namespace std; using namespace client; using namespace std; Command_Client_Thread::Command_Client_Thread() { } void Command_Client_Thread::execute() { sf::RenderWindow window(sf::VideoMode(32*26+500,32*24), "Zorglub"); client::Client client(window,"game"); while (window.isOpen()) { client.run(); sleep(2); window.close(); } }
18.809524
71
0.694937
Kuga23
14d6287cf9a4fb3b87856cf5b60c6159e1a453b6
3,420
hpp
C++
include/System/Security/Principal/WindowsImpersonationContext.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Security/Principal/WindowsImpersonationContext.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Security/Principal/WindowsImpersonationContext.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: System.IDisposable #include "System/IDisposable.hpp" // Including type: System.IntPtr #include "System/IntPtr.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Type namespace: System.Security.Principal namespace System::Security::Principal { // Size: 0x19 #pragma pack(push, 1) // Autogenerated type: System.Security.Principal.WindowsImpersonationContext // [ComVisibleAttribute] Offset: D7D6CC class WindowsImpersonationContext : public ::Il2CppObject/*, public System::IDisposable*/ { public: // private System.IntPtr _token // Size: 0x8 // Offset: 0x10 System::IntPtr token; // Field size check static_assert(sizeof(System::IntPtr) == 0x8); // private System.Boolean undo // Size: 0x1 // Offset: 0x18 bool undo; // Field size check static_assert(sizeof(bool) == 0x1); // Creating value type constructor for type: WindowsImpersonationContext WindowsImpersonationContext(System::IntPtr token_ = {}, bool undo_ = {}) noexcept : token{token_}, undo{undo_} {} // Creating interface conversion operator: operator System::IDisposable operator System::IDisposable() noexcept { return *reinterpret_cast<System::IDisposable*>(this); } // System.Void .ctor(System.IntPtr token) // Offset: 0x1AD88C8 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static WindowsImpersonationContext* New_ctor(System::IntPtr token) { static auto ___internal__logger = ::Logger::get().WithContext("System::Security::Principal::WindowsImpersonationContext::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<WindowsImpersonationContext*, creationType>(token))); } // public System.Void Dispose() // Offset: 0x1AD8E30 void Dispose(); // public System.Void Undo() // Offset: 0x1AD8E40 void Undo(); // static private System.Boolean CloseToken(System.IntPtr token) // Offset: 0x1AD8F04 static bool CloseToken(System::IntPtr token); // static private System.IntPtr DuplicateToken(System.IntPtr token) // Offset: 0x1AD8DF8 static System::IntPtr DuplicateToken(System::IntPtr token); // static private System.Boolean SetCurrentToken(System.IntPtr token) // Offset: 0x1AD8DFC static bool SetCurrentToken(System::IntPtr token); // static private System.Boolean RevertToSelf() // Offset: 0x1AD8F00 static bool RevertToSelf(); }; // System.Security.Principal.WindowsImpersonationContext #pragma pack(pop) static check_size<sizeof(WindowsImpersonationContext), 24 + sizeof(bool)> __System_Security_Principal_WindowsImpersonationContextSizeCheck; static_assert(sizeof(WindowsImpersonationContext) == 0x19); } DEFINE_IL2CPP_ARG_TYPE(System::Security::Principal::WindowsImpersonationContext*, "System.Security.Principal", "WindowsImpersonationContext");
46.849315
143
0.709942
darknight1050
14d6f2d5ba03d1e3a04bb3b24bc95652e7125096
426
cpp
C++
MODDING_API/src/ModdingAPI.cpp
MagicRB/MODDABLE_RPG
567f007b15eead07bac73608a6e980c138553761
[ "MIT" ]
null
null
null
MODDING_API/src/ModdingAPI.cpp
MagicRB/MODDABLE_RPG
567f007b15eead07bac73608a6e980c138553761
[ "MIT" ]
null
null
null
MODDING_API/src/ModdingAPI.cpp
MagicRB/MODDABLE_RPG
567f007b15eead07bac73608a6e980c138553761
[ "MIT" ]
null
null
null
#include "ModdingAPI.hpp" #include <cmath> #include <iostream> chunkified_pos<int> world_to_chunk(int px, int py) { chunkified_pos<int> ch; ch.chunk_x = floor(px / 64.0f); ch.chunk_y = floor(py / 64.0f); ch.x = abs(px) % 64; ch.y = abs(py) % 64; if (ch.chunk_x < 0) { ch.x = 64 - ch.x; } if (ch.chunk_y < 0) { ch.y = 64 - ch.y; } return ch; } modAPI::modAPI() { } modAPI::~modAPI() { }
14.689655
50
0.561033
MagicRB
14d733430d971b341d314683fcf38baac9a5ed93
5,887
cpp
C++
samples/face/lbf_facemark_detector.cpp
raymanfx/seraphim
4d388d21831d349fe1085bc3cb7c73f5d2b103a7
[ "MIT" ]
null
null
null
samples/face/lbf_facemark_detector.cpp
raymanfx/seraphim
4d388d21831d349fe1085bc3cb7c73f5d2b103a7
[ "MIT" ]
null
null
null
samples/face/lbf_facemark_detector.cpp
raymanfx/seraphim
4d388d21831d349fe1085bc3cb7c73f5d2b103a7
[ "MIT" ]
null
null
null
/* * (C) Copyright 2019 * The Seraphim Project Developers. * * SPDX-License-Identifier: MIT */ #include <csignal> #include <opencv2/imgproc.hpp> #include <opencv2/videoio.hpp> #include <optparse.h> #include <seraphim/polygon.h> #include <seraphim/face/lbf_facemark_detector.h> #include <seraphim/face/lbp_face_detector.h> #include <seraphim/gui.h> #include <seraphim/iop/opencv/mat.h> using namespace sph::face; static bool main_loop = true; void signal_handler(int signal) { switch (signal) { case SIGINT: std::cout << "[SIGNAL] SIGINT: Terminating application" << std::endl; main_loop = false; break; default: std::cout << "[SIGNAL] unknown: " << signal << std::endl; break; } } int main(int argc, char **argv) { int camera_index = 0; std::string model_path; std::string cascade_path; std::shared_ptr<LBPFaceDetector> face_detector = std::shared_ptr<LBPFaceDetector>(new LBPFaceDetector()); LBFFacemarkDetector facemark_detector; std::vector<sph::Polygon<int>> faces; std::vector<FacemarkDetector::Facemarks> facemarks; sph::CoreImage image; cv::Mat frame; std::chrono::high_resolution_clock::time_point t_loop_start; std::chrono::high_resolution_clock::time_point t_frame_captured; long frame_time; long process_time; long fps; long elapsed = 0; // register signal handler signal(SIGINT, signal_handler); // build args sph::cmd::OptionParser optparse; sph::cmd::Option inputOpt; inputOpt.name = "input"; inputOpt.shortname = "i"; inputOpt.description = "Camera index"; inputOpt.arg = true; optparse.add(inputOpt, [&](const std::string &val) { camera_index = std::stoi(val); }); sph::cmd::Option modelOpt; inputOpt.name = "model"; inputOpt.shortname = "m"; inputOpt.description = "File path"; inputOpt.arg = true; inputOpt.required = true; optparse.add(inputOpt, [&](const std::string &val) { model_path = val; }); sph::cmd::Option cascadeOpt; inputOpt.name = "cascade"; inputOpt.shortname = "c"; inputOpt.description = "File path"; inputOpt.arg = true; inputOpt.required = true; optparse.add(inputOpt, [&](const std::string &val) { cascade_path = val; }); sph::cmd::Option helpOpt; helpOpt.name = "help"; helpOpt.shortname = "h"; helpOpt.description = "Show help"; optparse.add(helpOpt, [&](const std::string&) { std::cout << "lbf_facemark_detector [args]" << std::endl << std::endl; for (const auto &str : optparse.help(true)) { std::cout << str << std::endl; } exit(0); }); try { optparse.parse(argc, argv); } catch (const std::exception &e) { std::cout << "[ERROR] " << e.what() << std::endl; return 0; } if (model_path.empty() || cascade_path.empty()) { std::cout << "[ERROR] Missing model or cascade path" << std::endl; return 1; } cv::VideoCapture cap; if (!cap.open(camera_index, cv::CAP_V4L2)) { if (!cap.open(camera_index)) { std::cout << "[ERROR] Failed to open camera: " << camera_index << std::endl; return 1; } } if (!face_detector->load_face_cascade(cascade_path)) { std::cout << "[ERROR Failed to read cascade" << std::endl; return 1; } face_detector->set_target(sph::Computable::Target::CPU); if (!facemark_detector.load_facemark_model(model_path)) { std::cout << "[ERROR Failed to read model" << std::endl; return 1; } facemark_detector.set_target(sph::Computable::Target::CPU); auto viewer = sph::gui::WindowFactory::create("LBF Facemark Detector"); while (main_loop) { t_loop_start = std::chrono::high_resolution_clock::now(); if (!cap.read(frame)) { std::cout << "[ERROR] Failed to read frame" << std::endl; break; } t_frame_captured = std::chrono::high_resolution_clock::now(); frame_time = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::high_resolution_clock::now() - t_loop_start) .count(); faces.clear(); facemarks.clear(); image = sph::iop::cv::to_image(frame); if (image.empty()) { std::cout << "[ERROR] Failed to convert Mat to Image" << std::endl; continue; } face_detector->detect(image, faces); if (faces.size() > 0) { facemark_detector.detect(image, faces, facemarks); } process_time = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::high_resolution_clock::now() - t_frame_captured) .count(); for (const auto &face : facemarks) { for (const auto &landmark : face.landmarks) { for (const auto &point : landmark.second) { cv::circle(frame, cv::Point(point.x, point.y), 1, cv::Scalar(0, 255, 0), 2); } } } fps = 1000 / std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::high_resolution_clock::now() - t_loop_start) .count(); elapsed += std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::high_resolution_clock::now() - t_loop_start) .count(); if (elapsed >= 500) { std::cout << "\r" << "[INFO] frame time: " << frame_time << " ms" << ", process time: " << process_time << " ms" << ", fps: " << fps << std::flush; elapsed = 0; } viewer->show(image); } }
31.31383
96
0.572278
raymanfx
14d83ad941e48001baf6ddca0f1e927411a145c8
2,652
cpp
C++
lib/Model.cpp
TurboCartPig/gfxprog
385c3c05cba4d102179f48b0c2b7abe0474293d6
[ "MIT" ]
1
2020-10-11T23:37:48.000Z
2020-10-11T23:37:48.000Z
lib/Model.cpp
TurboCartPig/gfxprog
385c3c05cba4d102179f48b0c2b7abe0474293d6
[ "MIT" ]
null
null
null
lib/Model.cpp
TurboCartPig/gfxprog
385c3c05cba4d102179f48b0c2b7abe0474293d6
[ "MIT" ]
null
null
null
#include <assimp/Importer.hpp> #include <assimp/postprocess.h> #include <assimp/scene.h> #include <glove/Model.h> #include <iostream> void process_node(const aiScene *scene, const aiNode *node, std::vector<Vertex3DNormTex> &vertices, std::vector<uint32_t> & indices) { for (size_t i = 0; i < node->mNumMeshes; ++i) { const auto *mesh = scene->mMeshes[node->mMeshes[i]]; for (size_t j = 0; j < mesh->mNumVertices; ++j) { assert(mesh->HasPositions()); assert(mesh->HasNormals()); assert(mesh->HasTextureCoords(0)); auto position = glm::vec3(mesh->mVertices[j].x, mesh->mVertices[j].y, mesh->mVertices[j].z); auto normal = glm::vec3(mesh->mNormals[j].x, mesh->mNormals[j].y, mesh->mNormals[j].z); auto uv = glm::vec2(mesh->mTextureCoords[0][j].x, mesh->mTextureCoords[0][j].y); vertices.push_back({position, normal, uv}); } for (size_t j = 0; j < mesh->mNumFaces; ++j) { const auto &face = mesh->mFaces[j]; for (size_t k = 0; k < face.mNumIndices; ++k) { indices.push_back(face.mIndices[k]); } } } for (size_t i = 0; i < node->mNumChildren; ++i) { process_node(scene, node->mChildren[i], vertices, indices); } } Model::Model(const std::string &model_path) { Assimp::Importer importer; const auto *scene = importer.ReadFile(model_path, aiProcessPreset_TargetRealtime_Quality); if (scene == nullptr) { std::cout << "Assimp Error: " << importer.GetErrorString() << std::endl; } assert(scene != nullptr); assert(scene->mRootNode != nullptr); assert(!(scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE)); assert(scene->HasMeshes()); std::vector<Vertex3DNormTex> vertices; std::vector<uint32_t> indices; process_node(scene, scene->mRootNode, vertices, indices); m_vbo = std::make_unique<VertexBuffer<Vertex3DNormTex>>(vertices, indices); } void Model::draw() { m_vbo->draw(); } // template <typename InstanceFormat> // void Model::setInstanceArray(const std::vector<InstanceFormat> &instances) { // m_vbo->setInstanceArray(instances); // } // template void // Model::setInstanceArray<glm::mat4>(const std::vector<glm::mat4> &); template <typename InstanceFormat> void Model::enableInstancing() { m_vbo->enableInstancing<InstanceFormat>(); } template <typename InstanceFormat> void Model::uploadInstanceData( const std::vector<InstanceFormat> &instance_data) { m_vbo->uploadInstanceData(instance_data); } template void Model::enableInstancing<glm::mat4>(); template void Model::uploadInstanceData<glm::mat4>(const std::vector<glm::mat4> &);
30.482759
79
0.662519
TurboCartPig
14db6b31e4a4b8e990d68887ddbc99eae9c16b18
9,281
cpp
C++
Sources/Core/Crypto/hash_functions.cpp
ValtoFrameworks/ClanLib
2d6b59386ce275742653b354a1daab42cab7cb3e
[ "Linux-OpenIB" ]
null
null
null
Sources/Core/Crypto/hash_functions.cpp
ValtoFrameworks/ClanLib
2d6b59386ce275742653b354a1daab42cab7cb3e
[ "Linux-OpenIB" ]
null
null
null
Sources/Core/Crypto/hash_functions.cpp
ValtoFrameworks/ClanLib
2d6b59386ce275742653b354a1daab42cab7cb3e
[ "Linux-OpenIB" ]
null
null
null
/* ** ClanLib SDK ** Copyright (c) 1997-2016 The ClanLib Team ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any damages ** arising from the use of this software. ** ** Permission is granted to anyone to use this software for any purpose, ** including commercial applications, and to alter it and redistribute it ** freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not ** claim that you wrote the original software. If you use this software ** in a product, an acknowledgment in the product documentation would be ** appreciated but is not required. ** 2. Altered source versions must be plainly marked as such, and must not be ** misrepresented as being the original software. ** 3. This notice may not be removed or altered from any source distribution. ** ** Note: Some of the libraries ClanLib may link to may have additional ** requirements or restrictions. ** ** File Author(s): ** ** Mark Page */ #include "Core/precomp.h" #include "API/Core/Crypto/hash_functions.h" #include "API/Core/System/databuffer.h" #include "Core/Zip/miniz.h" namespace clan { uint32_t HashFunctions::crc32(const void *data, int size, uint32_t running_crc/*=0*/) { uint32_t crc = running_crc; if (crc == 0) crc = mz_crc32(0L, nullptr, 0); return mz_crc32(running_crc, (const unsigned char*)data, size);; } uint32_t HashFunctions::adler32(const void *data, int size, uint32_t running_adler32/*=0*/) { uint32_t adler = running_adler32; if (adler == 0) adler = mz_adler32(0L, nullptr, 0); return mz_adler32(adler, (const unsigned char*)data, size); } std::string HashFunctions::md5(const void *data, int size, bool uppercase) { SHA1 md5; md5.add(data, size); md5.calculate(); return md5.get_hash(uppercase); } std::string HashFunctions::md5(const std::string &data, bool uppercase) { return md5(data.data(), data.length(), uppercase); } std::string HashFunctions::md5(const DataBuffer &data, bool uppercase) { return md5(data.get_data(), data.get_size(), uppercase); } void HashFunctions::md5(const void *data, int size, unsigned char out_hash[16]) { SHA1 md5; md5.add(data, size); md5.calculate(); md5.get_hash(out_hash); } void HashFunctions::md5(const DataBuffer &data, unsigned char out_hash[16]) { md5(data.get_data(), data.get_size(), out_hash); } void HashFunctions::md5(const std::string &data, unsigned char out_hash[16]) { md5(data.data(), data.length(), out_hash); } std::string HashFunctions::sha1(const void *data, int size, bool uppercase) { SHA1 sha1; sha1.add(data, size); sha1.calculate(); return sha1.get_hash(uppercase); } std::string HashFunctions::sha1(const std::string &data, bool uppercase) { return sha1(data.data(), data.length(), uppercase); } std::string HashFunctions::sha1(const DataBuffer &data, bool uppercase) { return sha1(data.get_data(), data.get_size(), uppercase); } void HashFunctions::sha1(const void *data, int size, unsigned char out_hash[20]) { SHA1 sha1; sha1.add(data, size); sha1.calculate(); sha1.get_hash(out_hash); } void HashFunctions::sha1(const DataBuffer &data, unsigned char out_hash[20]) { sha1(data.get_data(), data.get_size(), out_hash); } void HashFunctions::sha1(const std::string &data, unsigned char out_hash[20]) { sha1(data.data(), data.length(), out_hash); } std::string HashFunctions::sha224(const void *data, int size, bool uppercase) { SHA224 sha224; sha224.add(data, size); sha224.calculate(); return sha224.get_hash(uppercase); } std::string HashFunctions::sha224(const std::string &data, bool uppercase) { return sha224(data.data(), data.length(), uppercase); } std::string HashFunctions::sha224(const DataBuffer &data, bool uppercase) { return sha224(data.get_data(), data.get_size(), uppercase); } void HashFunctions::sha224(const void *data, int size, unsigned char out_hash[28]) { SHA224 sha224; sha224.add(data, size); sha224.calculate(); sha224.get_hash(out_hash); } void HashFunctions::sha224(const DataBuffer &data, unsigned char out_hash[28]) { sha224(data.get_data(), data.get_size(), out_hash); } void HashFunctions::sha224(const std::string &data, unsigned char out_hash[28]) { sha224(data.data(), data.length(), out_hash); } std::string HashFunctions::sha256(const void *data, int size, bool uppercase) { SHA256 sha256; sha256.add(data, size); sha256.calculate(); return sha256.get_hash(uppercase); } std::string HashFunctions::sha256(const std::string &data, bool uppercase) { return sha256(data.data(), data.length(), uppercase); } std::string HashFunctions::sha256(const DataBuffer &data, bool uppercase) { return sha256(data.get_data(), data.get_size(), uppercase); } void HashFunctions::sha256(const void *data, int size, unsigned char out_hash[32]) { SHA256 sha256; sha256.add(data, size); sha256.calculate(); sha256.get_hash(out_hash); } void HashFunctions::sha256(const DataBuffer &data, unsigned char out_hash[32]) { sha256(data.get_data(), data.get_size(), out_hash); } void HashFunctions::sha256(const std::string &data, unsigned char out_hash[32]) { sha256(data.data(), data.length(), out_hash); } std::string HashFunctions::sha384(const void *data, int size, bool uppercase) { SHA384 sha384; sha384.add(data, size); sha384.calculate(); return sha384.get_hash(uppercase); } std::string HashFunctions::sha384(const std::string &data, bool uppercase) { return sha384(data.data(), data.length(), uppercase); } std::string HashFunctions::sha384(const DataBuffer &data, bool uppercase) { return sha384(data.get_data(), data.get_size(), uppercase); } void HashFunctions::sha384(const void *data, int size, unsigned char out_hash[48]) { SHA384 sha384; sha384.add(data, size); sha384.calculate(); sha384.get_hash(out_hash); } void HashFunctions::sha384(const DataBuffer &data, unsigned char out_hash[48]) { sha384(data.get_data(), data.get_size(), out_hash); } void HashFunctions::sha384(const std::string &data, unsigned char out_hash[48]) { sha384(data.data(), data.length(), out_hash); } std::string HashFunctions::sha512(const void *data, int size, bool uppercase) { SHA512 sha512; sha512.add(data, size); sha512.calculate(); return sha512.get_hash(uppercase); } std::string HashFunctions::sha512(const std::string &data, bool uppercase) { return sha512(data.data(), data.length(), uppercase); } std::string HashFunctions::sha512(const DataBuffer &data, bool uppercase) { return sha512(data.get_data(), data.get_size(), uppercase); } void HashFunctions::sha512(const void *data, int size, unsigned char out_hash[64]) { SHA512 sha512; sha512.add(data, size); sha512.calculate(); sha512.get_hash(out_hash); } void HashFunctions::sha512(const DataBuffer &data, unsigned char out_hash[64]) { sha512(data.get_data(), data.get_size(), out_hash); } void HashFunctions::sha512(const std::string &data, unsigned char out_hash[64]) { sha512(data.data(), data.length(), out_hash); } std::string HashFunctions::sha512_224(const void *data, int size, bool uppercase) { SHA512_224 sha512_224; sha512_224.add(data, size); sha512_224.calculate(); return sha512_224.get_hash(uppercase); } std::string HashFunctions::sha512_224(const std::string &data, bool uppercase) { return sha512_224(data.data(), data.length(), uppercase); } std::string HashFunctions::sha512_224(const DataBuffer &data, bool uppercase) { return sha512_224(data.get_data(), data.get_size(), uppercase); } void HashFunctions::sha512_224(const void *data, int size, unsigned char out_hash[28]) { SHA512_224 sha512_224; sha512_224.add(data, size); sha512_224.calculate(); sha512_224.get_hash(out_hash); } void HashFunctions::sha512_224(const DataBuffer &data, unsigned char out_hash[28]) { sha512_224(data.get_data(), data.get_size(), out_hash); } void HashFunctions::sha512_224(const std::string &data, unsigned char out_hash[28]) { sha512_224(data.data(), data.length(), out_hash); } std::string HashFunctions::sha512_256(const void *data, int size, bool uppercase) { SHA512_256 sha512_256; sha512_256.add(data, size); sha512_256.calculate(); return sha512_256.get_hash(uppercase); } std::string HashFunctions::sha512_256(const std::string &data, bool uppercase) { return sha512_256(data.data(), data.length(), uppercase); } std::string HashFunctions::sha512_256(const DataBuffer &data, bool uppercase) { return sha512_256(data.get_data(), data.get_size(), uppercase); } void HashFunctions::sha512_256(const void *data, int size, unsigned char out_hash[32]) { SHA512_256 sha512_256; sha512_256.add(data, size); sha512_256.calculate(); sha512_256.get_hash(out_hash); } void HashFunctions::sha512_256(const DataBuffer &data, unsigned char out_hash[32]) { sha512_256(data.get_data(), data.get_size(), out_hash); } void HashFunctions::sha512_256(const std::string &data, unsigned char out_hash[32]) { sha512_256(data.data(), data.length(), out_hash); } }
26.979651
92
0.715225
ValtoFrameworks
14db6e74a5db750e5d0085a2240a93f419041cfc
9,285
cpp
C++
cocos2dx/platform/CCFileUtils.cpp
wingver/cocos2d-x
1e7a0d18a90cc8bb859b876528677e7119b04a49
[ "Zlib", "MIT" ]
1
2019-10-22T07:32:45.000Z
2019-10-22T07:32:45.000Z
cocos2dx/platform/CCFileUtils.cpp
wingver/cocos2d-x
1e7a0d18a90cc8bb859b876528677e7119b04a49
[ "Zlib", "MIT" ]
null
null
null
cocos2dx/platform/CCFileUtils.cpp
wingver/cocos2d-x
1e7a0d18a90cc8bb859b876528677e7119b04a49
[ "Zlib", "MIT" ]
null
null
null
/**************************************************************************** Copyright (c) 2010 cocos2d-x.org http://www.cocos2d-x.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 "CCFileUtils.h" #if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) && (CC_TARGET_PLATFORM != CC_PLATFORM_AIRPLAY) #include <stack> #include <libxml/parser.h> #include <libxml/tree.h> #include <libxml/xmlmemory.h> #include "CCLibxml2.h" #include "CCString.h" #include "CCSAXParser.h" #include "support/zip_support/unzip.h" NS_CC_BEGIN; typedef enum { SAX_NONE = 0, SAX_KEY, SAX_DICT, SAX_INT, SAX_REAL, SAX_STRING }CCSAXState; class CCDictMaker : public CCSAXDelegator { public: CCDictionary<std::string, CCObject*> *m_pRootDict; CCDictionary<std::string, CCObject*> *m_pCurDict; std::stack<CCDictionary<std::string, CCObject*>*> m_tDictStack; std::string m_sCurKey;///< parsed key CCSAXState m_tState; bool m_bInArray; CCMutableArray<CCObject*> *m_pArray; public: CCDictMaker() : m_pRootDict(NULL), m_pCurDict(NULL), m_tState(SAX_NONE), m_pArray(NULL), m_bInArray(false) { } ~CCDictMaker() { } CCDictionary<std::string, CCObject*> *dictionaryWithContentsOfFile(const char *pFileName) { CCSAXParser parser; if (false == parser.init("UTF-8")) { return NULL; } parser.setDelegator(this); parser.parse(pFileName); return m_pRootDict; } void startElement(void *ctx, const char *name, const char **atts) { std::string sName((char*)name); if( sName == "dict" ) { CCDictionary<std::string, CCObject*> *pNewDict = new CCDictionary<std::string, CCObject*>(); if(! m_pRootDict) { m_pRootDict = pNewDict; pNewDict->autorelease(); } else { CCAssert(m_pCurDict && !m_sCurKey.empty(), ""); m_pCurDict->setObject(pNewDict, m_sCurKey); pNewDict->release(); m_sCurKey.clear(); } m_pCurDict = pNewDict; m_tDictStack.push(m_pCurDict); m_tState = SAX_DICT; } else if(sName == "key") { m_tState = SAX_KEY; } else if(sName == "integer") { m_tState = SAX_INT; } else if(sName == "real") { m_tState = SAX_REAL; } else if(sName == "string") { m_tState = SAX_STRING; } else { if (sName == "array") { m_bInArray = true; m_pArray = new CCMutableArray<CCObject*>(); } m_tState = SAX_NONE; } } void endElement(void *ctx, const char *name) { std::string sName((char*)name); if( sName == "dict" ) { m_tDictStack.pop(); if ( !m_tDictStack.empty() ) { m_pCurDict = (CCDictionary<std::string, CCObject*>*)(m_tDictStack.top()); } } else if (sName == "array") { CCAssert(m_bInArray, "The plist file is wrong!"); m_pCurDict->setObject(m_pArray, m_sCurKey); m_pArray->release(); m_pArray = NULL; m_bInArray = false; } else if (sName == "true") { CCString *str = new CCString("1"); if (m_bInArray) { m_pArray->addObject(str); } else { m_pCurDict->setObject(str, m_sCurKey); } str->release(); } else if (sName == "false") { CCString *str = new CCString("0"); if (m_bInArray) { m_pArray->addObject(str); } else { m_pCurDict->setObject(str, m_sCurKey); } str->release(); } m_tState = SAX_NONE; } void textHandler(void *ctx, const char *ch, int len) { if (m_tState == SAX_NONE) { return; } CCString *pText = new CCString(); pText->m_sString = std::string((char*)ch,0,len); switch(m_tState) { case SAX_KEY: m_sCurKey = pText->m_sString; break; case SAX_INT: case SAX_REAL: case SAX_STRING: { CCAssert(!m_sCurKey.empty(), "not found key : <integet/real>"); if (m_bInArray) { m_pArray->addObject(pText); } else { m_pCurDict->setObject(pText, m_sCurKey); } break; } } pText->release(); } }; std::string& CCFileUtils::ccRemoveHDSuffixFromFile(std::string& path) { #if CC_IS_RETINA_DISPLAY_SUPPORTED if( CC_CONTENT_SCALE_FACTOR() == 2 ) { std::string::size_type pos = path.rfind("/") + 1; // the begin index of last part of path std::string::size_type suffixPos = path.rfind(CC_RETINA_DISPLAY_FILENAME_SUFFIX); if (std::string::npos != suffixPos && suffixPos > pos) { CCLog("cocos2d: FilePath(%s) contains suffix(%s), remove it.", path.c_str(), CC_RETINA_DISPLAY_FILENAME_SUFFIX); path.replace(suffixPos, strlen(CC_RETINA_DISPLAY_FILENAME_SUFFIX), ""); } } #endif // CC_IS_RETINA_DISPLAY_SUPPORTED return path; } CCDictionary<std::string, CCObject*> *CCFileUtils::dictionaryWithContentsOfFile(const char *pFileName) { CCDictMaker tMaker; return tMaker.dictionaryWithContentsOfFile(pFileName); } unsigned char* CCFileUtils::getFileDataFromZip(const char* pszZipFilePath, const char* pszFileName, unsigned long * pSize) { unsigned char * pBuffer = NULL; unzFile pFile = NULL; *pSize = 0; do { CC_BREAK_IF(!pszZipFilePath || !pszFileName); CC_BREAK_IF(strlen(pszZipFilePath) == 0); pFile = unzOpen(pszZipFilePath); CC_BREAK_IF(!pFile); int nRet = unzLocateFile(pFile, pszFileName, 1); CC_BREAK_IF(UNZ_OK != nRet); char szFilePathA[260]; unz_file_info FileInfo; nRet = unzGetCurrentFileInfo(pFile, &FileInfo, szFilePathA, sizeof(szFilePathA), NULL, 0, NULL, 0); CC_BREAK_IF(UNZ_OK != nRet); nRet = unzOpenCurrentFile(pFile); CC_BREAK_IF(UNZ_OK != nRet); pBuffer = new unsigned char[FileInfo.uncompressed_size]; int nSize = 0; nSize = unzReadCurrentFile(pFile, pBuffer, FileInfo.uncompressed_size); CCAssert(nSize == 0 || nSize == FileInfo.uncompressed_size, "the file size is wrong"); *pSize = FileInfo.uncompressed_size; unzCloseCurrentFile(pFile); } while (0); if (pFile) { unzClose(pFile); } return pBuffer; } ////////////////////////////////////////////////////////////////////////// // Notification support when getFileData from invalid file path. ////////////////////////////////////////////////////////////////////////// static bool s_bPopupNotify = true; void CCFileUtils::setIsPopupNotify(bool bNotify) { s_bPopupNotify = bNotify; } bool CCFileUtils::getIsPopupNotify() { return s_bPopupNotify; } NS_CC_END; #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) #include "win32/CCFileUtils_win32.cpp" #endif #if (CC_TARGET_PLATFORM == CC_PLATFORM_WOPHONE) #include "wophone/CCFileUtils_wophone.cpp" #endif #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #include "android/CCFileUtils_android.cpp" #endif #endif // (CC_TARGET_PLATFORM != CC_PLATFORM_IOS && CC_TARGET_PLATFORM != CC_PLATFORM_AIRPLAY)
28.925234
123
0.548088
wingver
14dccff1101fa5ec14a714131603e19e95bb6f57
3,277
cc
C++
libcef_dll/ctocpp/zip_reader_ctocpp.cc
desura/desura-cef1
54106e0abdbbb362b4d547af3095faeb467500d3
[ "BSD-3-Clause" ]
1
2017-01-18T17:04:40.000Z
2017-01-18T17:04:40.000Z
libcef_dll/ctocpp/zip_reader_ctocpp.cc
desura/desura-cef1
54106e0abdbbb362b4d547af3095faeb467500d3
[ "BSD-3-Clause" ]
null
null
null
libcef_dll/ctocpp/zip_reader_ctocpp.cc
desura/desura-cef1
54106e0abdbbb362b4d547af3095faeb467500d3
[ "BSD-3-Clause" ]
1
2015-07-14T02:36:29.000Z
2015-07-14T02:36:29.000Z
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. // // --------------------------------------------------------------------------- // // A portion of this file was generated by the CEF translator tool. When // making changes by hand only do so within the body of existing static and // virtual method implementations. See the translator.README.txt file in the // tools directory for more information. // #include "libcef_dll/ctocpp/stream_reader_ctocpp.h" #include "libcef_dll/ctocpp/zip_reader_ctocpp.h" // STATIC METHODS - Body may be edited by hand. CefRefPtr<CefZipReader> CefZipReader::Create(CefRefPtr<CefStreamReader> stream) { cef_zip_reader_t* impl = cef_zip_reader_create( CefStreamReaderCToCpp::Unwrap(stream)); if(impl) return CefZipReaderCToCpp::Wrap(impl); return NULL; } // VIRTUAL METHODS - Body may be edited by hand. bool CefZipReaderCToCpp::MoveToFirstFile() { if(CEF_MEMBER_MISSING(struct_, move_to_first_file)) return false; return struct_->move_to_first_file(struct_) ? true : false; } bool CefZipReaderCToCpp::MoveToNextFile() { if(CEF_MEMBER_MISSING(struct_, move_to_next_file)) return false; return struct_->move_to_next_file(struct_) ? true : false; } bool CefZipReaderCToCpp::MoveToFile(const CefString& fileName, bool caseSensitive) { if(CEF_MEMBER_MISSING(struct_, move_to_file)) return false; return struct_->move_to_file(struct_, fileName.GetStruct(), caseSensitive) ? true : false; } bool CefZipReaderCToCpp::Close() { if(CEF_MEMBER_MISSING(struct_, close)) return false; return struct_->close(struct_) ? true : false; } CefString CefZipReaderCToCpp::GetFileName() { CefString str; if(CEF_MEMBER_MISSING(struct_, get_file_name)) return str; cef_string_userfree_t strPtr = struct_->get_file_name(struct_); str.AttachToUserFree(strPtr); return str; } long CefZipReaderCToCpp::GetFileSize() { if(CEF_MEMBER_MISSING(struct_, get_file_size)) return -1; return struct_->get_file_size(struct_); } time_t CefZipReaderCToCpp::GetFileLastModified() { if(CEF_MEMBER_MISSING(struct_, get_file_last_modified)) return 0; return struct_->get_file_last_modified(struct_); } bool CefZipReaderCToCpp::OpenFile(const CefString& password) { if(CEF_MEMBER_MISSING(struct_, open_file)) return 0; return struct_->open_file(struct_, password.GetStruct()) ? true : false; } bool CefZipReaderCToCpp::CloseFile() { if(CEF_MEMBER_MISSING(struct_, close_file)) return 0; return struct_->close_file(struct_) ? true : false; } int CefZipReaderCToCpp::ReadFile(void* buffer, size_t bufferSize) { if(CEF_MEMBER_MISSING(struct_, read_file)) return -1; return struct_->read_file(struct_, buffer, bufferSize); } long CefZipReaderCToCpp::Tell() { if(CEF_MEMBER_MISSING(struct_, tell)) return -1; return struct_->tell(struct_); } bool CefZipReaderCToCpp::Eof() { if(CEF_MEMBER_MISSING(struct_, eof)) return false; return struct_->eof(struct_) ? true : false; } #ifndef NDEBUG template<> long CefCToCpp<CefZipReaderCToCpp, CefZipReader, cef_zip_reader_t>::DebugObjCt = 0; #endif
23.746377
79
0.732072
desura
14dd6e9a9e101b9f91e2d0ac0255f434f62d4dcb
3,472
cpp
C++
Source/World/Generation/Structures/TreeGenerator.cpp
UglySwedishFish/MineCraft-One-Week-Challenge
2d8859a977224c1f3d184ab8f2d50f17e43ce6ba
[ "Apache-2.0" ]
1
2020-04-21T18:47:09.000Z
2020-04-21T18:47:09.000Z
Source/World/Generation/Structures/TreeGenerator.cpp
UglySwedishFish/MineCraft-One-Week-Challenge
2d8859a977224c1f3d184ab8f2d50f17e43ce6ba
[ "Apache-2.0" ]
null
null
null
Source/World/Generation/Structures/TreeGenerator.cpp
UglySwedishFish/MineCraft-One-Week-Challenge
2d8859a977224c1f3d184ab8f2d50f17e43ce6ba
[ "Apache-2.0" ]
null
null
null
#include "TreeGenerator.h" #include "../../Chunk/Chunk.h" #include "StructureBuilder.h" constexpr BlockId CACTUS = BlockId::Cactus; namespace { void makeCactus1 (Chunk& chunk, Random<std::minstd_rand>& rand, int x, int y, int z) { StructureBuilder builder; builder.makeColumn(x, z, y, rand.intInRange(4, 7), CACTUS); builder.build(chunk); } void makeCactus2 (Chunk& chunk, Random<std::minstd_rand>& rand, int x, int y, int z) { StructureBuilder builder; int height = rand.intInRange(6, 8); builder.makeColumn(x, z, y, height, CACTUS); int stem = height / 2; builder.makeRowX(x - 2, x + 2, stem + y, z, CACTUS); builder.addBlock(x - 2, stem + y + 1, z, CACTUS); builder.addBlock(x - 2, stem + y + 2, z, CACTUS); builder.addBlock(x + 2, stem + y + 1, z, CACTUS); builder.build(chunk); } void makeCactus3 (Chunk& chunk, Random<std::minstd_rand>& rand, int x, int y, int z) { StructureBuilder builder; int height = rand.intInRange(6, 8); builder.makeColumn(x, z, y, height, CACTUS); int stem = height / 2; builder.makeRowZ(z - 2, z + 2, x, stem + y, CACTUS); builder.addBlock(x, stem + y + 1, z - 2, CACTUS); builder.addBlock(x, stem + y + 2, z - 2, CACTUS); builder.addBlock(x, stem + y + 1, z + 2, CACTUS); builder.build(chunk); } }//name space void makeOakTree(Chunk& chunk, Random<std::minstd_rand>& rand, int x, int y, int z) { StructureBuilder builder; int h = rand.intInRange(4, 7); int leafSize = 2; int newY = h + y; builder.fill(newY, x - leafSize, x + leafSize, z - leafSize, z + leafSize, BlockId::OakLeaf); builder.fill(newY - 1, x - leafSize, x + leafSize, z - leafSize, z + leafSize, BlockId::OakLeaf); for (int32_t zLeaf = -leafSize + 1; zLeaf <= leafSize - 1; zLeaf++) { builder.addBlock(x, newY + 1, z + zLeaf, BlockId::OakLeaf); } for (int32_t xLeaf = -leafSize + 1; xLeaf <= leafSize - 1; xLeaf++) { builder.addBlock(x + xLeaf, newY + 1, z, BlockId::OakLeaf); } builder.makeColumn(x, z, y, h, BlockId::OakBark); builder.build(chunk); } void makePalmTree(Chunk& chunk, Random<std::minstd_rand>& rand, int x, int y, int z) { StructureBuilder builder; int height = rand.intInRange(7, 9); int diameter = rand.intInRange(4, 6); for (int xLeaf = -diameter; xLeaf < diameter; xLeaf++) { builder.addBlock(xLeaf + x, y + height, z, BlockId::OakLeaf); } for (int zLeaf = -diameter; zLeaf < diameter; zLeaf++) { builder.addBlock(x, y + height, zLeaf + z, BlockId::OakLeaf); } builder.addBlock(x, y + height - 1, z + diameter, BlockId::OakLeaf); builder.addBlock(x, y + height - 1, z - diameter, BlockId::OakLeaf); builder.addBlock(x + diameter, y + height - 1, z, BlockId::OakLeaf); builder.addBlock(x - diameter, y + height - 1, z, BlockId::OakLeaf); builder.addBlock(x, y + height + 1, z, BlockId::OakLeaf); builder.makeColumn(x, z, y, height, BlockId::OakBark); builder.build(chunk); } void makeCactus(Chunk& chunk, Random<std::minstd_rand>& rand, int x, int y, int z) { int cac = rand.intInRange(0, 2); switch (cac) { case 0: makeCactus1(chunk, rand, x, y, z); break; case 1: makeCactus2(chunk, rand, x, y, z); break; case 2: makeCactus3(chunk, rand, x, y, z); } }
30.191304
102
0.601094
UglySwedishFish
14df380632e44f767b2aae86c8fc5b4a9c599bd3
21,582
hpp
C++
3rdparty/stlsoft/include/stlsoft/obsolete/conversion_veneer.hpp
wohaaitinciu/zpublic
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
[ "Unlicense" ]
50
2015-01-07T01:54:54.000Z
2021-01-15T00:41:48.000Z
3rdparty/stlsoft/include/stlsoft/obsolete/conversion_veneer.hpp
lib1256/zpublic
64c2be9ef1abab878288680bb58122dcc25df81d
[ "Unlicense" ]
2
2016-01-08T19:32:57.000Z
2019-10-11T03:50:34.000Z
3rdparty/stlsoft/include/stlsoft/obsolete/conversion_veneer.hpp
lib1256/zpublic
64c2be9ef1abab878288680bb58122dcc25df81d
[ "Unlicense" ]
39
2015-01-07T02:03:15.000Z
2021-01-15T00:41:50.000Z
/* ///////////////////////////////////////////////////////////////////////// * File: stlsoft/obsolete/conversion_veneer.hpp * * Purpose: Raw conversion veneer class. * * Created: 30th July 2002 * Updated: 10th August 2009 * * Home: http://stlsoft.org/ * * Copyright (c) 2002-2009, Matthew Wilson and Synesis Software * 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(s) of Matthew Wilson and Synesis Software nor the names of * any 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. * * ////////////////////////////////////////////////////////////////////// */ /// \file stlsoft/obsolete/conversion_veneer.hpp /// /// Raw conversion veneer class. #ifndef STLSOFT_INCL_STLSOFT_OBSOLETE_HPP_CONVERSION_VENEER #define STLSOFT_INCL_STLSOFT_OBSOLETE_HPP_CONVERSION_VENEER #ifndef STLSOFT_DOCUMENTATION_SKIP_SECTION # define STLSOFT_VER_STLSOFT_OBSOLETE_HPP_CONVERSION_VENEER_MAJOR 3 # define STLSOFT_VER_STLSOFT_OBSOLETE_HPP_CONVERSION_VENEER_MINOR 2 # define STLSOFT_VER_STLSOFT_OBSOLETE_HPP_CONVERSION_VENEER_REVISION 2 # define STLSOFT_VER_STLSOFT_OBSOLETE_HPP_CONVERSION_VENEER_EDIT 47 #endif /* !STLSOFT_DOCUMENTATION_SKIP_SECTION */ /* ///////////////////////////////////////////////////////////////////////// * Includes */ #ifndef STLSOFT_INCL_STLSOFT_H_STLSOFT # include <stlsoft/stlsoft.h> #endif /* !STLSOFT_INCL_STLSOFT_H_STLSOFT */ #ifndef STLSOFT_INCL_STLSOFT_UTIL_HPP_CONSTRAINTS # include <stlsoft/util/constraints.hpp> #endif /* !STLSOFT_INCL_STLSOFT_UTIL_HPP_CONSTRAINTS */ /* ///////////////////////////////////////////////////////////////////////// * Namespace */ #ifndef _STLSOFT_NO_NAMESPACE namespace stlsoft { #endif /* _STLSOFT_NO_NAMESPACE */ /* ///////////////////////////////////////////////////////////////////////// * Classes */ // class invalid_conversion /** \brief Prevents any conversion * * \ingroup group__library__obsolete * * \param T The value type * \param C The conversion type */ template< ss_typename_param_k T , ss_typename_param_k C > struct invalid_conversion { protected: /// The invalid type typedef void invalid_type; public: /// The value type typedef T value_type; /// The conversion type typedef C conversion_type; public: /// Converts a pointer to the \c value_type to a pointer to the \c conversion_type static invalid_type convert_pointer(value_type * /* pv */) {} /// Converts a pointer-to-const to the \c value_type to a pointer-to-const to the \c conversion_type static invalid_type convert_const_pointer(value_type const* /* pv */) {} /// Converts a reference to the \c value_type to a reference to the \c conversion_type static invalid_type convert_reference(value_type &/* v */) {} /// Converts a reference-to-const to the \c value_type to a reference-to-const to the \c conversion_type static invalid_type convert_const_reference(value_type const& /* v */) {} /// Pointer conversion type struct pointer_conversion { invalid_type operator ()(value_type * /* pv */) {} }; /// Pointer-to-const conversion type struct pointer_const_conversion { invalid_type operator ()(value_type const* /* pv */) {} }; /// Reference conversion type struct reference_conversion { invalid_type operator ()(value_type &/* v */) {} }; /// Reference-to-const conversion type struct reference_const_conversion { invalid_type operator ()(value_type const& /* v */) {} }; }; // class static_conversion /** \brief Implements conversion via C++'s <code>static_cast</code> * * \ingroup group__library__obsolete * * \param T The value type * \param C The conversion type */ template< ss_typename_param_k T , ss_typename_param_k C > struct static_conversion { public: /// The value type typedef T value_type; /// The conversion type typedef C conversion_type; public: /// Converts a pointer to the \c value_type to a pointer to the \c conversion_type static conversion_type *convert_pointer(value_type *pv) { return static_cast<conversion_type*>(pv); } /// Converts a pointer-to-const to the \c value_type to a pointer-to-const to the \c conversion_type static conversion_type const* convert_const_pointer(value_type const* pv) { return static_cast<conversion_type const*>(pv); } /// Converts a reference to the \c value_type to a reference to the \c conversion_type static conversion_type &convert_reference(value_type &v) { return static_cast<conversion_type&>(v); } /// Converts a reference-to-const to the \c value_type to a reference-to-const to the \c conversion_type static conversion_type const& convert_const_reference(value_type const& v) { return static_cast<conversion_type const&>(v); } /// Pointer conversion type struct pointer_conversion { conversion_type *operator ()(value_type *pv) { return convert_pointer(pv); } }; /// Pointer-to-const conversion type struct pointer_const_conversion { conversion_type const* operator ()(value_type const* pv) { return convert_const_pointer(pv); } }; /// Reference conversion type struct reference_conversion { conversion_type& operator ()(value_type &v) { return convert_reference(v); } }; /// Reference-to-const conversion type struct reference_const_conversion { conversion_type const& operator ()(value_type const& v) { return convert_const_reference(v); } }; }; // class dynamic_conversion /** \brief Implements conversion via C++'s <code>dynamic_cast</code> * * \ingroup group__library__obsolete * * \param T The value type * \param C The conversion type */ template< ss_typename_param_k T , ss_typename_param_k C > struct dynamic_conversion { public: /// The value type typedef T value_type; /// The conversion type typedef C conversion_type; public: /// Converts a pointer to the \c value_type to a pointer to the \c conversion_type static conversion_type *convert_pointer(value_type *pv) { return dynamic_cast<conversion_type*>(pv); } /// Converts a pointer-to-const to the \c value_type to a pointer-to-const to the \c conversion_type static conversion_type const* convert_const_pointer(value_type const* pv) { return dynamic_cast<conversion_type const*>(pv); } /// Converts a reference to the \c value_type to a reference to the \c conversion_type static conversion_type &convert_reference(value_type &v) { return dynamic_cast<conversion_type&>(v); } /// Converts a reference-to-const to the \c value_type to a reference-to-const to the \c conversion_type static conversion_type const& convert_const_reference(value_type const& v) { return dynamic_cast<conversion_type const&>(v); } /// Pointer conversion type struct pointer_conversion { conversion_type *operator ()(value_type *pv) { return convert_pointer(pv); } }; /// Pointer-to-const conversion type struct pointer_const_conversion { conversion_type const* operator ()(value_type const* pv) { return convert_const_pointer(pv); } }; /// Reference conversion type struct reference_conversion { conversion_type& operator ()(value_type &v) { return convert_reference(v); } }; /// Reference-to-const conversion type struct reference_const_conversion { conversion_type const& operator ()(value_type const& v) { return convert_const_reference(v); } }; }; // class reinterpret_conversion /** \brief Implements conversion via C++'s <code>reinterpret_cast</code> * * \ingroup group__library__obsolete * * \param T The value type * \param C The conversion type */ template< ss_typename_param_k T , ss_typename_param_k C > struct reinterpret_conversion { public: /// The value type typedef T value_type; /// The conversion type typedef C conversion_type; public: /// Converts a pointer to the \c value_type to a pointer to the \c conversion_type static conversion_type *convert_pointer(value_type *pv) { return reinterpret_cast<conversion_type*>(pv); } /// Converts a pointer-to-const to the \c value_type to a pointer-to-const to the \c conversion_type static conversion_type const* convert_const_pointer(value_type const* pv) { return reinterpret_cast<conversion_type const*>(pv); } /// Converts a reference to the \c value_type to a reference to the \c conversion_type static conversion_type &convert_reference(value_type &v) { return reinterpret_cast<conversion_type&>(v); } /// Converts a reference-to-const to the \c value_type to a reference-to-const to the \c conversion_type static conversion_type const& convert_const_reference(value_type const& v) { return reinterpret_cast<conversion_type const&>(v); } /// Pointer conversion type struct pointer_conversion { conversion_type *operator ()(value_type *pv) { return convert_pointer(pv); } }; /// Pointer-to-const conversion type struct pointer_const_conversion { conversion_type const* operator ()(value_type const* pv) { return convert_const_pointer(pv); } }; /// Reference conversion type struct reference_conversion { conversion_type& operator ()(value_type &v) { return convert_reference(v); } }; /// Reference-to-const conversion type struct reference_const_conversion { conversion_type const& operator ()(value_type const& v) { return convert_const_reference(v); } }; }; // class c_conversion /** \brief Implements conversion via C-style casts * * \ingroup group__library__obsolete * * \param T The value type * \param C The conversion type */ template< ss_typename_param_k T , ss_typename_param_k C > struct c_conversion { public: /// The value type typedef T value_type; /// The conversion type typedef C conversion_type; public: /// Converts a pointer to the \c value_type to a pointer to the \c conversion_type static conversion_type *convert_pointer(value_type *pv) { return (conversion_type*)(pv); } /// Converts a pointer-to-const to the \c value_type to a pointer-to-const to the \c conversion_type static conversion_type const* convert_const_pointer(value_type const* pv) { return (conversion_type const*)(pv); } /// Converts a reference to the \c value_type to a reference to the \c conversion_type static conversion_type &convert_reference(value_type &v) { return (conversion_type&)(v); } /// Converts a reference-to-const to the \c value_type to a reference-to-const to the \c conversion_type static conversion_type const& convert_const_reference(value_type const& v) { return (conversion_type const&)(v); } /// Pointer conversion type struct pointer_conversion { conversion_type *operator ()(value_type *pv) { return convert_pointer(pv); } }; /// Pointer-to-const conversion type struct pointer_const_conversion { conversion_type const* operator ()(value_type const* pv) { return convert_const_pointer(pv); } }; /// Reference conversion type struct reference_conversion { conversion_type& operator ()(value_type &v) { return convert_reference(v); } }; /// Reference-to-const conversion type struct reference_const_conversion { conversion_type const& operator ()(value_type const& v) { return convert_const_reference(v); } }; }; // class conversion_veneer /** \brief This class allows policy-based control of the four conversions: pointer, non-mutable pointer, reference, non-mutable reference * * \param T The type that will be subjected to the <a href = "http://synesis.com.au/resources/articles/cpp/veneers.pdf">veneer</a> * \param C The type that T will be converted to * \param V The value type. On translators that support default template arguments this defaults to T. * \param P The type that controls the pointer conversion * \param R The type that controls the reference conversion * \param PC The type that controls the pointer-to-const conversion * \param RC The type that controls the reference-to-const conversion * * \ingroup concepts_veneer */ template< ss_typename_param_k T , ss_typename_param_k C #ifdef STLSOFT_CF_TEMPLATE_CLASS_DEFAULT_FUNDAMENTAL_ARGUMENT_SUPPORT , ss_typename_param_k V = T , ss_typename_param_k P = invalid_conversion<T, C> , ss_typename_param_k R = invalid_conversion<T, C> , ss_typename_param_k PC = P , ss_typename_param_k RC = R #else , ss_typename_param_k V , ss_typename_param_k P , ss_typename_param_k R , ss_typename_param_k PC , ss_typename_param_k RC #endif /* STLSOFT_CF_TEMPLATE_CLASS_DEFAULT_FUNDAMENTAL_ARGUMENT_SUPPORT */ > class conversion_veneer : public T { public: /// The parent class type typedef T parent_class_type; /// The conversion type typedef C conversion_type; /// The value type typedef V value_type; /// The pointer conversion type typedef ss_typename_type_k P::pointer_conversion pointer_conversion_type; /// The reference conversion type typedef ss_typename_type_k R::reference_conversion reference_conversion_type; /// The pointer-to-const conversion type typedef ss_typename_type_k PC::pointer_const_conversion pointer_const_conversion_type; /// The reference-to-const conversion type typedef ss_typename_type_k RC::reference_const_conversion reference_const_conversion_type; /// The current parameterisation of the type typedef conversion_veneer<T, C, V, P, R, PC, RC> class_type; // Construction public: /// The default constructor conversion_veneer() { stlsoft_constraint_must_be_same_size(T, class_type); } /// The copy constructor conversion_veneer(class_type const& rhs) : parent_class_type(rhs) { stlsoft_constraint_must_be_same_size(T, class_type); } /// Initialise from a value conversion_veneer(value_type const& rhs) : parent_class_type(rhs) { stlsoft_constraint_must_be_same_size(T, class_type); } #ifdef STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT // For compilers that support member templates, the following constructors // are provided. /// Single parameter constructor template <ss_typename_param_k N1> ss_explicit_k conversion_veneer(N1 &n1) : parent_class_type(n1) {} /// Single parameter constructor template <ss_typename_param_k N1> ss_explicit_k conversion_veneer(N1 *n1) : parent_class_type(n1) {} /// Two parameter constructor template <ss_typename_param_k N1, ss_typename_param_k N2> conversion_veneer(N1 n1, N2 n2) : parent_class_type(n1, n2) {} /// Three parameter constructor template <ss_typename_param_k N1, ss_typename_param_k N2, ss_typename_param_k N3> conversion_veneer(N1 n1, N2 n2, N3 n3) : parent_class_type(n1, n2, n3) {} /// Four parameter constructor template <ss_typename_param_k N1, ss_typename_param_k N2, ss_typename_param_k N3, ss_typename_param_k N4> conversion_veneer(N1 n1, N2 n2, N3 n3, N4 n4) : parent_class_type(n1, n2, n3, n4) {} /// Five parameter constructor template <ss_typename_param_k N1, ss_typename_param_k N2, ss_typename_param_k N3, ss_typename_param_k N4, ss_typename_param_k N5> conversion_veneer(N1 n1, N2 n2, N3 n3, N4 n4, N5 n5) : parent_class_type(n1, n2, n3, n4, n5) {} /// Six parameter constructor template <ss_typename_param_k N1, ss_typename_param_k N2, ss_typename_param_k N3, ss_typename_param_k N4, ss_typename_param_k N5, ss_typename_param_k N6> conversion_veneer(N1 n1, N2 n2, N3 n3, N4 n4, N5 n5, N6 n6) : parent_class_type(n1, n2, n3, n4, n5, n6) {} /// Seven parameter constructor template <ss_typename_param_k N1, ss_typename_param_k N2, ss_typename_param_k N3, ss_typename_param_k N4, ss_typename_param_k N5, ss_typename_param_k N6, ss_typename_param_k N7> conversion_veneer(N1 n1, N2 n2, N3 n3, N4 n4, N5 n5, N6 n6, N7 n7) : parent_class_type(n1, n2, n3, n4, n5, n6, n7) {} /// Eight parameter constructor template <ss_typename_param_k N1, ss_typename_param_k N2, ss_typename_param_k N3, ss_typename_param_k N4, ss_typename_param_k N5, ss_typename_param_k N6, ss_typename_param_k N7, ss_typename_param_k N8> conversion_veneer(N1 n1, N2 n2, N3 n3, N4 n4, N5 n5, N6 n6, N7 n7, N8 n8) : parent_class_type(n1, n2, n3, n4, n5, n6, n7, n8) {} #endif // STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT /// Copy assignment operator class_type& operator =(class_type const& rhs) { static_cast<parent_class_type&>(*this) = rhs; return *this; } /// Copy from a value class_type& operator =(value_type const& rhs) { static_cast<parent_class_type&>(*this) = rhs; return *this; } #ifdef STLSOFT_CF_MEMBER_TEMPLATE_FUNCTION_SUPPORT /// Copy from a value template <ss_typename_param_k T1> class_type& operator =(T1 rhs) { static_cast<parent_class_type&>(*this) = rhs; return *this; } #endif // STLSOFT_CF_MEMBER_TEMPLATE_FUNCTION_SUPPORT // Note that the copy constructor is not defined, and will NOT be defined copy ctor/operator not made // Conversions public: /// Implicit conversion to a reference to the conversion_type operator conversion_type &() { return reference_conversion_type()(*this); } /// Implicit conversion to a reference-to-const to the conversion_type operator conversion_type const& () const { return reference_const_conversion_type()(*this); } /// Address-of operator, returning a pointer to the conversion type conversion_type * operator &() { // Take a local reference, such that the application of the address-of // operator will allow user-defined conversions of the parent_class_type // to be applied. parent_class_type &_this = *this; return pointer_conversion_type()(&_this); } /// Address-of operator, returning a pointer-to-const to the conversion type conversion_type const* operator &() const { // Take a local reference, such that the application of the address-of // operator will allow user-defined conversions of the parent_class_type // to be applied. parent_class_type const& _this = *this; return pointer_const_conversion_type()(&_this); } }; /* ////////////////////////////////////////////////////////////////////// */ #ifndef _STLSOFT_NO_NAMESPACE } // namespace stlsoft #endif /* _STLSOFT_NO_NAMESPACE */ /* ////////////////////////////////////////////////////////////////////// */ #endif /* !STLSOFT_INCL_STLSOFT_OBSOLETE_HPP_CONVERSION_VENEER */ /* ///////////////////////////// end of file //////////////////////////// */
31.69163
205
0.660921
wohaaitinciu
14df72b15cb24dfe3065db9ce7c11d1c257a2752
1,677
cpp
C++
OpenCDMi/CENCParser.cpp
dautapankumardora/rdkservices
d8b60572bcb4ac549b3ab5a9cffa7fbdd0906e15
[ "BSD-2-Clause" ]
11
2020-06-19T15:23:36.000Z
2022-03-29T09:58:48.000Z
OpenCDMi/CENCParser.cpp
dautapankumardora/rdkservices
d8b60572bcb4ac549b3ab5a9cffa7fbdd0906e15
[ "BSD-2-Clause" ]
647
2020-04-07T18:40:51.000Z
2022-03-31T21:07:46.000Z
OpenCDMi/CENCParser.cpp
dautapankumardora/rdkservices
d8b60572bcb4ac549b3ab5a9cffa7fbdd0906e15
[ "BSD-2-Clause" ]
785
2020-03-18T01:47:46.000Z
2022-03-31T15:31:52.000Z
/* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: * * Copyright 2020 RDK Management * * 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 "CENCParser.h" namespace WPEFramework { namespace Plugin { /* static */ const uint8_t CommonEncryptionData::PSSHeader[] = { 0x70, 0x73, 0x73, 0x68 }; /* static */ const uint8_t CommonEncryptionData::CommonEncryption[] = { 0x10, 0x77, 0xef, 0xec, 0xc0, 0xb2, 0x4d, 0x02, 0xac, 0xe3, 0x3c, 0x1e, 0x52, 0xe2, 0xfb, 0x4b }; /* static */ const uint8_t CommonEncryptionData::PlayReady[] = { 0x9a, 0x04, 0xf0, 0x79, 0x98, 0x40, 0x42, 0x86, 0xab, 0x92, 0xe6, 0x5b, 0xe0, 0x88, 0x5f, 0x95 }; /* static */ const uint8_t CommonEncryptionData::WideVine[] = { 0xed, 0xef, 0x8b, 0xa9, 0x79, 0xd6, 0x4a, 0xce, 0xa3, 0xc8, 0x27, 0xdc, 0xd5, 0x1d, 0x21, 0xed }; /* static */ const uint8_t CommonEncryptionData::ClearKey[] = { 0x58, 0x14, 0x7e, 0xc8, 0x04, 0x23, 0x46, 0x59, 0x92, 0xe6, 0xf5, 0x2c, 0x5c, 0xe8, 0xc3, 0xcc }; /* static */ const char CommonEncryptionData::JSONKeyIds[] = "{\"kids\":"; } } // namespace WPEFramework::Plugin
49.323529
173
0.702445
dautapankumardora
14e0fa9bf144ac034c73caec50fdca8ffac24f0e
2,089
cc
C++
engine/service/definition_list.cc
pikacuh/ink
08c2abb5a40a3c75fbaa636d39e572dea3547960
[ "Apache-2.0" ]
1
2021-03-02T22:22:38.000Z
2021-03-02T22:22:38.000Z
engine/service/definition_list.cc
pikacuh/ink
08c2abb5a40a3c75fbaa636d39e572dea3547960
[ "Apache-2.0" ]
null
null
null
engine/service/definition_list.cc
pikacuh/ink
08c2abb5a40a3c75fbaa636d39e572dea3547960
[ "Apache-2.0" ]
1
2021-03-02T22:23:12.000Z
2021-03-02T22:23:12.000Z
// Copyright 2018 Google LLC // // 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 "ink/engine/service/definition_list.h" #include <memory> #include <typeindex> #include "ink/engine/service/common_internal.h" #include "ink/engine/util/dbg/errors.h" namespace ink { namespace service { std::shared_ptr<void> DefinitionList::GetInstance( std::type_index type, const service_internal::TypePointerMap &type_map) const { auto definition_it = definitions_.find(type); if (definition_it != definitions_.end()) { for (const auto dep_type : definition_it->second->DirectDependencies()) { auto dep_it = type_map.find(dep_type); if (dep_it == type_map.end() || dep_it->second == nullptr) { RUNTIME_ERROR("Cannot instantiate service $0: unmet dependency: $1.", type.name(), dep_type.name()); } } return definition_it->second->GetInstance(type_map); } RUNTIME_ERROR("Service $0 is not defined", type.name()); } service_internal::TypeIndexSet DefinitionList::GetDefinedTypes() const { service_internal::TypeIndexSet types; types.reserve(definitions_.size()); for (const auto &pair : definitions_) types.insert(pair.first); return types; } service_internal::TypeIndexSet DefinitionList::GetDirectDependencies( std::type_index type) const { auto definition_it = definitions_.find(type); if (definition_it != definitions_.end()) return definition_it->second->DirectDependencies(); RUNTIME_ERROR("Service $0 is not defined", type.name()); } } // namespace service } // namespace ink
33.693548
77
0.721398
pikacuh
14e26e4628e22a4a8033745d60c59083df74d500
836
cpp
C++
codeforce3/552C. Vanya and Scales.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
codeforce3/552C. Vanya and Scales.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
codeforce3/552C. Vanya and Scales.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
#include <stdio.h> #include <vector> #include <algorithm> using namespace std; int w, m; vector<long long> powers, all[2]; void rec(int i, long long sum, int end, int idx) { if(i == end) { all[idx].push_back(sum); return; } rec(i + 1, sum, end, idx); rec(i + 1, sum + powers[i], end, idx); rec(i + 1, sum - powers[i], end, idx); } int main() { scanf("%d %d", &w, &m); if(w == 2) { puts("YES"); return 0; } long long cur = 1, sum = 0; do { powers.push_back(cur); sum += cur; cur *= w; } while (cur - sum <= m); rec(0, 0, powers.size() / 2, 0); rec(powers.size() / 2, 0, powers.size(), 1); sort(all[0].begin(), all[0].end()); for(int i = 0; i < (int)all[1].size(); ++i) if(binary_search(all[0].begin(), all[0].end(), m + all[1][i])) { puts("YES"); return 0; } puts("NO"); return 0; }
16.076923
66
0.535885
khaled-farouk
14ef66febc537f75f74c13bcd7779b5054b50de8
7,942
cpp
C++
src/armnn/backends/test/IsLayerSupportedTest.cpp
KevinRodrigues05/armnn_caffe2_parser
c577f2c6a3b4ddb6ba87a882723c53a248afbeba
[ "MIT" ]
null
null
null
src/armnn/backends/test/IsLayerSupportedTest.cpp
KevinRodrigues05/armnn_caffe2_parser
c577f2c6a3b4ddb6ba87a882723c53a248afbeba
[ "MIT" ]
null
null
null
src/armnn/backends/test/IsLayerSupportedTest.cpp
KevinRodrigues05/armnn_caffe2_parser
c577f2c6a3b4ddb6ba87a882723c53a248afbeba
[ "MIT" ]
null
null
null
// // Copyright © 2017 Arm Ltd. All rights reserved. // See LICENSE file in the project root for full license information. // #include <boost/test/unit_test.hpp> #include "test/TensorHelpers.hpp" #include "LayerTests.hpp" #include "backends/CpuTensorHandle.hpp" #include "backends/RefWorkloadFactory.hpp" #include <string> #include <iostream> #include <backends/ClWorkloadFactory.hpp> #include <backends/NeonWorkloadFactory.hpp> #include "IsLayerSupportedTestImpl.hpp" #include "ClContextControlFixture.hpp" #include "layers/ConvertFp16ToFp32Layer.hpp" #include "layers/ConvertFp32ToFp16Layer.hpp" BOOST_AUTO_TEST_SUITE(IsLayerSupported) BOOST_AUTO_TEST_CASE(IsLayerSupportedLayerTypeMatches) { LayerTypeMatchesTest(); } BOOST_AUTO_TEST_CASE(IsLayerSupportedFloat16Reference) { armnn::RefWorkloadFactory factory; IsLayerSupportedTests<armnn::RefWorkloadFactory, armnn::DataType::Float16>(&factory); } BOOST_AUTO_TEST_CASE(IsLayerSupportedFloat32Reference) { armnn::RefWorkloadFactory factory; IsLayerSupportedTests<armnn::RefWorkloadFactory, armnn::DataType::Float32>(&factory); } BOOST_AUTO_TEST_CASE(IsLayerSupportedUint8Reference) { armnn::RefWorkloadFactory factory; IsLayerSupportedTests<armnn::RefWorkloadFactory, armnn::DataType::QuantisedAsymm8>(&factory); } BOOST_AUTO_TEST_CASE(IsConvertFp16ToFp32SupportedReference) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::RefWorkloadFactory, armnn::ConvertFp16ToFp32Layer, armnn::DataType::Float16, armnn::DataType::Float32>(reasonIfUnsupported); BOOST_CHECK(result); } BOOST_AUTO_TEST_CASE(IsConvertFp16ToFp32SupportedFp32InputReference) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::RefWorkloadFactory, armnn::ConvertFp16ToFp32Layer, armnn::DataType::Float32, armnn::DataType::Float32>(reasonIfUnsupported); BOOST_CHECK(!result); BOOST_CHECK_EQUAL(reasonIfUnsupported, "Layer is not supported with float32 data type input"); } BOOST_AUTO_TEST_CASE(IsConvertFp16ToFp32SupportedFp16OutputReference) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::RefWorkloadFactory, armnn::ConvertFp16ToFp32Layer, armnn::DataType::Float16, armnn::DataType::Float16>(reasonIfUnsupported); BOOST_CHECK(!result); BOOST_CHECK_EQUAL(reasonIfUnsupported, "Layer is not supported with float16 data type output"); } BOOST_AUTO_TEST_CASE(IsConvertFp32ToFp16SupportedReference) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::RefWorkloadFactory, armnn::ConvertFp32ToFp16Layer, armnn::DataType::Float32, armnn::DataType::Float16>(reasonIfUnsupported); BOOST_CHECK(result); } BOOST_AUTO_TEST_CASE(IsConvertFp32ToFp16SupportedFp16InputReference) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::RefWorkloadFactory, armnn::ConvertFp32ToFp16Layer, armnn::DataType::Float16, armnn::DataType::Float16>(reasonIfUnsupported); BOOST_CHECK(!result); BOOST_CHECK_EQUAL(reasonIfUnsupported, "Layer is not supported with float16 data type input"); } BOOST_AUTO_TEST_CASE(IsConvertFp32ToFp16SupportedFp32OutputReference) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::RefWorkloadFactory, armnn::ConvertFp32ToFp16Layer, armnn::DataType::Float32, armnn::DataType::Float32>(reasonIfUnsupported); BOOST_CHECK(!result); BOOST_CHECK_EQUAL(reasonIfUnsupported, "Layer is not supported with float32 data type output"); } #ifdef ARMCOMPUTENEON_ENABLED BOOST_AUTO_TEST_CASE(IsLayerSupportedFloat16Neon) { armnn::NeonWorkloadFactory factory; IsLayerSupportedTests<armnn::NeonWorkloadFactory, armnn::DataType::Float16>(&factory); } BOOST_AUTO_TEST_CASE(IsLayerSupportedFloat32Neon) { armnn::NeonWorkloadFactory factory; IsLayerSupportedTests<armnn::NeonWorkloadFactory, armnn::DataType::Float32>(&factory); } BOOST_AUTO_TEST_CASE(IsLayerSupportedUint8Neon) { armnn::NeonWorkloadFactory factory; IsLayerSupportedTests<armnn::NeonWorkloadFactory, armnn::DataType::QuantisedAsymm8>(&factory); } BOOST_AUTO_TEST_CASE(IsConvertFp16ToFp32SupportedNeon) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::NeonWorkloadFactory, armnn::ConvertFp16ToFp32Layer, armnn::DataType::Float16, armnn::DataType::Float32>(reasonIfUnsupported); BOOST_CHECK(result); } BOOST_AUTO_TEST_CASE(IsConvertFp32ToFp16SupportedNeon) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::NeonWorkloadFactory, armnn::ConvertFp32ToFp16Layer, armnn::DataType::Float32, armnn::DataType::Float16>(reasonIfUnsupported); BOOST_CHECK(result); } #endif //#ifdef ARMCOMPUTENEON_ENABLED. #ifdef ARMCOMPUTECL_ENABLED BOOST_FIXTURE_TEST_CASE(IsLayerSupportedFloat16Cl, ClContextControlFixture) { armnn::ClWorkloadFactory factory; IsLayerSupportedTests<armnn::ClWorkloadFactory, armnn::DataType::Float16>(&factory); } BOOST_FIXTURE_TEST_CASE(IsLayerSupportedFloat32Cl, ClContextControlFixture) { armnn::ClWorkloadFactory factory; IsLayerSupportedTests<armnn::ClWorkloadFactory, armnn::DataType::Float32>(&factory); } BOOST_FIXTURE_TEST_CASE(IsLayerSupportedUint8Cl, ClContextControlFixture) { armnn::ClWorkloadFactory factory; IsLayerSupportedTests<armnn::ClWorkloadFactory, armnn::DataType::QuantisedAsymm8>(&factory); } BOOST_FIXTURE_TEST_CASE(IsConvertFp16ToFp32SupportedCl, ClContextControlFixture) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::ClWorkloadFactory, armnn::ConvertFp16ToFp32Layer, armnn::DataType::Float16, armnn::DataType::Float32>(reasonIfUnsupported); BOOST_CHECK(result); } BOOST_FIXTURE_TEST_CASE(IsConvertFp16ToFp32SupportedFp32InputCl, ClContextControlFixture) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::ClWorkloadFactory, armnn::ConvertFp16ToFp32Layer, armnn::DataType::Float32, armnn::DataType::Float32>(reasonIfUnsupported); BOOST_CHECK(!result); BOOST_CHECK_EQUAL(reasonIfUnsupported, "Input should be Float16"); } BOOST_FIXTURE_TEST_CASE(IsConvertFp16ToFp32SupportedFp16OutputCl, ClContextControlFixture) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::ClWorkloadFactory, armnn::ConvertFp16ToFp32Layer, armnn::DataType::Float16, armnn::DataType::Float16>(reasonIfUnsupported); BOOST_CHECK(!result); BOOST_CHECK_EQUAL(reasonIfUnsupported, "Output should be Float32"); } BOOST_FIXTURE_TEST_CASE(IsConvertFp32ToFp16SupportedCl, ClContextControlFixture) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::ClWorkloadFactory, armnn::ConvertFp32ToFp16Layer, armnn::DataType::Float32, armnn::DataType::Float16>(reasonIfUnsupported); BOOST_CHECK(result); } BOOST_FIXTURE_TEST_CASE(IsConvertFp32ToFp16SupportedFp16InputCl, ClContextControlFixture) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::ClWorkloadFactory, armnn::ConvertFp32ToFp16Layer, armnn::DataType::Float16, armnn::DataType::Float16>(reasonIfUnsupported); BOOST_CHECK(!result); BOOST_CHECK_EQUAL(reasonIfUnsupported, "Input should be Float32"); } BOOST_FIXTURE_TEST_CASE(IsConvertFp32ToFp16SupportedFp32OutputCl, ClContextControlFixture) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::ClWorkloadFactory, armnn::ConvertFp32ToFp16Layer, armnn::DataType::Float32, armnn::DataType::Float32>(reasonIfUnsupported); BOOST_CHECK(!result); BOOST_CHECK_EQUAL(reasonIfUnsupported, "Output should be Float16"); } #endif //#ifdef ARMCOMPUTECL_ENABLED. BOOST_AUTO_TEST_SUITE_END()
33.091667
105
0.801939
KevinRodrigues05
14f342ae30c8f9eeecb5589c60e4246f99a48a5f
3,772
hpp
C++
lib/geometry/kdtree.hpp
kuhaku-space/atcoder-lib
7fe1365e1be69d3eff11e122b2c7dff997a6c541
[ "Apache-2.0" ]
null
null
null
lib/geometry/kdtree.hpp
kuhaku-space/atcoder-lib
7fe1365e1be69d3eff11e122b2c7dff997a6c541
[ "Apache-2.0" ]
4
2022-01-05T14:40:40.000Z
2022-03-05T08:03:19.000Z
lib/geometry/kdtree.hpp
kuhaku-space/atcoder-lib
7fe1365e1be69d3eff11e122b2c7dff997a6c541
[ "Apache-2.0" ]
null
null
null
#include "template/template.hpp" /* * reference : * https://tjkendev.github.io/procon-library/cpp/range_query/kd-tree.html * verify : * https://onlinejudge.u-aizu.ac.jp/problems/DSL_2_C 21/03/29 * https://atcoder.jp/contests/arc010/tasks/arc010_4 21/03/30 */ struct kdtree { struct Point { int id; int x, y; }; struct Node { int left, right; Point p; }; vector<Point> points; vector<Node> nodes; kdtree() : points(), nodes() {} void add(int x, int y) { int id = points.size(); points.emplace_back(Point{id, x, y}); } int make(int l, int r, int depth) { if (l == r) { return -1; } if (r - l == 1) { int res = nodes.size(); nodes.emplace_back(Node{-1, -1, points[l]}); return res; } int mid = (l + r) >> 1; if (depth & 1) { sort(points.begin() + l, points.begin() + r, [](const Point &a, const Point &b) { return a.x < b.x; }); } else { sort(points.begin() + l, points.begin() + r, [](const Point &a, const Point &b) { return a.y < b.y; }); } int res = nodes.size(); nodes.emplace_back(Node{}); int left = make(l, mid, depth + 1); int right = make(mid + 1, r, depth + 1); nodes[res] = Node{left, right, points[mid]}; return res; } void build() { make(0, points.size(), 0); } int64_t find(int idx, int x, int y, int depth, int64_t r) { if (idx == -1) return r; Point &p = nodes[idx].p; int64_t d = int64_t(x - p.x) * (x - p.x) + int64_t(y - p.y) * (y - p.y); if (r == -1 || d < r) r = d; if (depth & 1) { if (nodes[idx].left != -1 && x - r <= p.x) { r = find(nodes[idx].left, x, y, depth + 1, r); } if (nodes[idx].right != -1 && p.x <= x + r) { r = find(nodes[idx].right, x, y, depth + 1, r); } } else { if (nodes[idx].left != -1 && y - r <= p.y) { r = find(nodes[idx].left, x, y, depth + 1, r); } if (nodes[idx].right != -1 && p.y <= y + r) { r = find(nodes[idx].right, x, y, depth + 1, r); } } return r; } int64_t find(int x, int y) { return find(0, x, y, 0, -1); } // [sx, tx) * [sy, ty) vector<int> find(int idx, int sx, int tx, int sy, int ty, int depth) { vector<int> res; Point &p = nodes[idx].p; if (sx <= p.x && p.x < tx && sy <= p.y && p.y < ty) { res.emplace_back(p.id); } if (depth & 1) { if (nodes[idx].left != -1 && sx <= p.x) { auto v = find(nodes[idx].left, sx, tx, sy, ty, depth + 1); res.insert(res.end(), v.begin(), v.end()); } if (nodes[idx].right != -1 && p.x < tx) { auto v = find(nodes[idx].right, sx, tx, sy, ty, depth + 1); res.insert(res.end(), v.begin(), v.end()); } } else { if (nodes[idx].left != -1 && sy <= p.y) { auto v = find(nodes[idx].left, sx, tx, sy, ty, depth + 1); res.insert(res.end(), v.begin(), v.end()); } if (nodes[idx].right != -1 && p.y < ty) { auto v = find(nodes[idx].right, sx, tx, sy, ty, depth + 1); res.insert(res.end(), v.begin(), v.end()); } } return res; } vector<int> find(int sx, int tx, int sy, int ty) { return find(0, sx, tx, sy, ty, 0); } };
34.290909
94
0.423383
kuhaku-space
14f3bc9e292df48bb32a96d981acff7f45cdee51
3,063
cpp
C++
plugins/pwdemos/src/AbstractTexQuartzRenderer.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
2
2020-10-16T10:15:37.000Z
2021-01-21T13:06:00.000Z
plugins/pwdemos/src/AbstractTexQuartzRenderer.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
null
null
null
plugins/pwdemos/src/AbstractTexQuartzRenderer.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
1
2021-01-28T01:19:54.000Z
2021-01-28T01:19:54.000Z
/* * AbstractTexQuartzRenderer.cpp * * Copyright (C) 2018 by VISUS (Universitaet Stuttgart) * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "AbstractTexQuartzRenderer.h" #include "vislib/graphics/gl/IncludeAllGL.h" #include <vector> namespace megamol { namespace demos { /* * AbstractTexQuartzRenderer::AbstractTexQuartzRenderer */ AbstractTexQuartzRenderer::AbstractTexQuartzRenderer(void) : AbstractQuartzRenderer(), typeTexture(0) { } /* * AbstractTexQuartzRenderer::~AbstractTexQuartzRenderer */ AbstractTexQuartzRenderer::~AbstractTexQuartzRenderer(void) { } /* * AbstractTexQuartzRenderer::assertTypeTexture */ void AbstractTexQuartzRenderer::assertTypeTexture(CrystalDataCall& types) { if ((this->typesDataHash != 0) && (this->typesDataHash == types.DataHash())) return; // all up to date this->typesDataHash = types.DataHash(); if (types.GetCount() == 0) { ::glDeleteTextures(1, &this->typeTexture); this->typeTexture = 0; return; } if (this->typeTexture == 0) { ::glGenTextures(1, &this->typeTexture); } unsigned mfc = 0; for (unsigned int i = 0; i < types.GetCount(); i++) { if (mfc < types.GetCrystals()[i].GetFaceCount()) { mfc = types.GetCrystals()[i].GetFaceCount(); } } std::vector<float> dat; dat.resize(types.GetCount() * mfc * 4); for (unsigned int y = 0; y < types.GetCount(); y++) { const CrystalDataCall::Crystal& c = types.GetCrystals()[y]; unsigned int x; for (x = 0; x < c.GetFaceCount(); x++) { vislib::math::Vector<float, 3> f = c.GetFace(x); dat[(x + y * mfc) * 4 + 3] = f.Normalise(); dat[(x + y * mfc) * 4 + 0] = f.X(); dat[(x + y * mfc) * 4 + 1] = f.Y(); dat[(x + y * mfc) * 4 + 2] = f.Z(); } for (; x < mfc; x++) { dat[(x + y * mfc) * 4 + 0] = 0.0f; dat[(x + y * mfc) * 4 + 1] = 0.0f; dat[(x + y * mfc) * 4 + 2] = 0.0f; dat[(x + y * mfc) * 4 + 3] = 0.0f; } } ::glBindTexture(GL_TEXTURE_2D, this->typeTexture); ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); GLint initial_pack_alignment = 0; ::glGetIntegerv(GL_PACK_ALIGNMENT, &initial_pack_alignment); ::glPixelStorei(GL_PACK_ALIGNMENT, 1); ::glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, mfc, types.GetCount(), 0, GL_RGBA, GL_FLOAT, dat.data()); ::glBindTexture(GL_TEXTURE_2D, 0); ::glPixelStorei(GL_PACK_ALIGNMENT, initial_pack_alignment); } /* * AbstractTexQuartzRenderer::releaseTypeTexture */ void AbstractTexQuartzRenderer::releaseTypeTexture(void) { ::glDeleteTextures(1, &this->typeTexture); this->typeTexture = 0; } } /* end namespace demos */ } /* end namespace megamol */
30.326733
106
0.624551
azuki-monster
14f689dd9f23ac8156584dcddb473a9d0edd1df0
220
hh
C++
include/model/usermodel.hh
MUCZ/meowings
5c691f0a2fb606dad2ddda44f946a94ff8ba3212
[ "Apache-2.0" ]
null
null
null
include/model/usermodel.hh
MUCZ/meowings
5c691f0a2fb606dad2ddda44f946a94ff8ba3212
[ "Apache-2.0" ]
null
null
null
include/model/usermodel.hh
MUCZ/meowings
5c691f0a2fb606dad2ddda44f946a94ff8ba3212
[ "Apache-2.0" ]
null
null
null
#ifndef USERMODEL #define USERMODEL #include "user.hh" class UserModel{ public: bool insert(User &user); User query(int id); bool updateState(User user); void resetState(); }; #endif /* USERMODEL */
12.941176
32
0.663636
MUCZ
14ff9bff8bce2f9903a8b29a82d16116d03dae0c
580
cpp
C++
Challenge18/src/main.cpp
GamesTrap/Challenges
6cfea7ec137fbba35cae6a29c4fc6b124eff07c8
[ "MIT" ]
1
2018-09-15T20:35:23.000Z
2018-09-15T20:35:23.000Z
Challenge18/src/main.cpp
GamesTrap/Challenges
6cfea7ec137fbba35cae6a29c4fc6b124eff07c8
[ "MIT" ]
null
null
null
Challenge18/src/main.cpp
GamesTrap/Challenges
6cfea7ec137fbba35cae6a29c4fc6b124eff07c8
[ "MIT" ]
null
null
null
#include <iostream> #include "GetType.h" int main() { const int i = 0; //Output: std::cout << getType(i) << '\n'; //int const unsigned int ui = 0; std::cout << getType(ui) << '\n'; //unsigned int const char c = 0; std::cout << getType(c) << '\n'; //char const bool b = false; std::cout << getType(b) << '\n'; //bool const float f = 0; //Assumption: float is not considered in getType(); std::cout << getType(f) << '\n'; //unknown type! std::cout << "Press Enter to continue . . . "; std::cin.get(); return 0; }
23.2
95
0.527586
GamesTrap
090221e48f082706e2d7383b62d0adb119fdb096
21,652
cpp
C++
Benchmarks/Applications/ObjectRecognition/FeatureExtractionAndClassification.cpp
jlclemon/MEVBench
da7621b9eb1e92eec37a77dd1c7b69320cffcee1
[ "BSD-3-Clause" ]
8
2015-03-16T18:16:35.000Z
2020-10-30T06:35:31.000Z
Benchmarks/Applications/ObjectRecognition/FeatureExtractionAndClassification.cpp
jlclemon/MEVBench
da7621b9eb1e92eec37a77dd1c7b69320cffcee1
[ "BSD-3-Clause" ]
null
null
null
Benchmarks/Applications/ObjectRecognition/FeatureExtractionAndClassification.cpp
jlclemon/MEVBench
da7621b9eb1e92eec37a77dd1c7b69320cffcee1
[ "BSD-3-Clause" ]
3
2016-03-17T08:27:13.000Z
2020-10-30T06:46:50.000Z
/* * Copyright (c) 2006-2009 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /* * FeatureExtractionAndClassification.cpp * * Created on: May 31, 2011 * Author: jlclemon */ #include <iostream> #include <sched.h> #include <unistd.h> #include <opencv2/features2d/features2d.hpp> #ifndef OPENCV_VER_2_3 #include <opencv2/nonfree/nonfree.hpp> #endif #include <opencv2/highgui/highgui.hpp> #include <opencv2/core/core.hpp> #include <opencv2/core/mat.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <opencv2/objdetect/objdetect.hpp> #include "FeatureExtraction.hpp" #include "FeatureExtractionWorkerThreadInfo.h" #include "FeatureClassification.hpp" #include "WorkerThreadInfo.h" #ifdef USE_MARSS #warning "Using MARSS" #include "ptlcalls.h" #endif #ifdef USE_GEM5 #warning "Using GEM5" extern "C" { #include "m5op.h" } #endif #ifdef USE_GEM5 #include <fenv.h> #include <signal.h> #include <stdio.h> void classification_sig_handler(int signum); #endif #define TIMING_MAX_NUMBER_OF_THREADS 256 #ifdef TSC_TIMING #include "tsc_class.hpp" #endif //#define CLOCK_GETTIME_TIMING #ifdef CLOCK_GETTIME_TIMING #include "time.h" #ifndef GET_TIME_WRAPPER #define GET_TIME_WRAPPER(dataStruct) clock_gettime(CLOCK_THREAD_CPUTIME_ID, &dataStruct) #endif #endif #ifdef TSC_TIMING vector<TSC_VAL_w> fec_timingVector; #endif #ifdef CLOCK_GETTIME_TIMING vector<struct timespec> fec_timeStructVector; #endif using namespace std; using namespace cv; bool globalDone; bool globalDataReady; Mat globalCurrentImage; vector<Point2f> globalCurrentRefs; struct FeatureExtractionAndClassificationConfig { string featureExtractionConfigFile; string featureClassificationConfigFile; int configFileCount; bool noShowWindows; bool noWaitKey; int maxLoops; int currentLoop; }; void internalCallToTestExtractionAlone(int argc, const char * argv[], bool callDirect) { if(callDirect) { multiThreadFeatureExtraction_StandAloneTest(argc,argv); #ifdef TSC_TIMING //READ_TIMESTAMP_WITH_WRAPPER( fec_timingVector[genData->myThread->getThreadLogicalId()+ TIMING_MAX_NUMBER_OF_THREADS*2] ); #endif #ifdef CLOCK_GETTIME_TIMING //GET_TIME_WRAPPER(fec_timeStructVector[genData->myThread->getThreadLogicalId()+ TIMING_MAX_NUMBER_OF_THREADS*2]); #endif featureClassification_testSeperate(argc, argv); } else { cout << "That is false sir" << endl; } } void setExtractedDescriptorsAndKeyPointsToClassificationInput(void * featureExtractionDataPtr, void * featureClassificationDataPtr) { struct WorkerThreadInfo * featureClassificationData = reinterpret_cast<struct WorkerThreadInfo * >(featureClassificationDataPtr); struct FeatureExtractionWorkerThreadInfo *featureExtractionData = reinterpret_cast<FeatureExtractionWorkerThreadInfo *> (featureExtractionDataPtr); struct FeatureExtractionMultiThreadData * myMultiThreadExtractionData = reinterpret_cast<FeatureExtractionMultiThreadData *>(featureExtractionData->multiThreadAlgorithmData); featureClassificationData->queryImage = &((*(featureExtractionData->myFeatureExtractionData->inputImagesPerFrame))[FEATURE_DESC_IMAGE_SOURCE_LOCATION_LEFT_CAMERA]); featureClassificationData->allQueryDescriptors = (myMultiThreadExtractionData->descriptors); featureClassificationData->allQueryKeypoints = (myMultiThreadExtractionData->keypoints); #ifdef VERBOSE_DEBUG cout << "Info From Extraction" << "\n Number Of Extracted Keypoints: "<<featureClassificationData->allQueryKeypoints->size() << "\n Number of extracted descriptors: " << featureClassificationData->allQueryDescriptors->rows << endl; #endif } void * coordinatorThreadFunction(void * threadParam) { int currentLoop = 0; int maxLoops = 20; struct GeneralWorkerThreadData * genData = reinterpret_cast<struct GeneralWorkerThreadData *>(threadParam); struct FeatureExtractionWorkerThreadInfo *featureExtractionData = reinterpret_cast<FeatureExtractionWorkerThreadInfo *> (genData->featureExtractionData); struct WorkerThreadInfo * featureClassificationData = reinterpret_cast<struct WorkerThreadInfo * >(genData->featureClassificationData); //Setup the pieces featureExtractionCoordinatorThreadSetupFunctionStandAlone(genData,genData->featureExtractionData); classificationCoordinatorThreadSetupFunctionStandAlone(genData->featureClassificationData); #ifdef VERBOSE_DEBUG int counting = 0; #endif #ifdef USE_MARSS cout << "Switching to simulation in Object Recognition." << endl; ptlcall_switch_to_sim(); //ptlcall_single_enqueue("-logfile objRecog.log"); //ptlcall_single_enqueue("-stats objRecog.stats"); ptlcall_single_flush("-stats objRecog.stats"); //ptlcall_single_enqueue("-loglevel 0"); #endif #ifdef USE_GEM5 #ifdef GEM5_CHECKPOINT_WORK m5_checkpoint(0, 0); #endif // #ifdef GEM5_SWITCHCPU_AT_WORK // m5_switchcpu(); // #endif m5_dumpreset_stats(0, 0); #endif #ifdef TSC_TIMING READ_TIMESTAMP_WITH_WRAPPER( fec_timingVector[genData->myThread->getThreadLogicalId()] ); #endif #ifdef CLOCK_GETTIME_TIMING GET_TIME_WRAPPER(fec_timeStructVector[genData->myThread->getThreadLogicalId()]); #endif while(!globalDone) { //Call the pieces featureExtractionCoordinatorThreadFunctionStandAlone(genData,genData->featureExtractionData); #ifdef VERBOSE_DEBUG counting ++; cout << "Count: " << counting << endl; if(counting == 11) { cout << "debug here" << endl; } #endif #ifdef TSC_TIMING READ_TIMESTAMP_WITH_WRAPPER( fec_timingVector[genData->myThread->getThreadLogicalId()+ TIMING_MAX_NUMBER_OF_THREADS*2] ); #endif #ifdef CLOCK_GETTIME_TIMING GET_TIME_WRAPPER(fec_timeStructVector[genData->myThread->getThreadLogicalId()+ TIMING_MAX_NUMBER_OF_THREADS*2]); #endif if(featureExtractionData->featureExtractionInfo->outOfImages || featureExtractionData->myFeatureExtractionInfo->outOfImages) { break; } if(featureExtractionData->done) { globalDone = true; } currentLoop++; if(currentLoop >=maxLoops) { globalDone = true; } //Connect the two pieces here setExtractedDescriptorsAndKeyPointsToClassificationInput(genData->featureExtractionData, genData->featureClassificationData); //Run Classification classificationCoordinatorThreadFunctionStandAlone(genData->featureClassificationData); if(globalDataReady ==false) { globalCurrentImage = ((*(featureExtractionData->myFeatureExtractionData->inputImagesPerFrame))[FEATURE_DESC_IMAGE_SOURCE_LOCATION_LEFT_CAMERA]).clone(); globalCurrentRefs = reinterpret_cast<struct SparseFeaturePointObjectClassifier::SparseFeaturePointObjectClassifierMultiThreadData *>(featureClassificationData->multiThreadAlgorithmData)->estimatedRefPoints->getResultsVec(); globalDataReady = true; } } globalDone = true; #ifdef USE_MARSS ptlcall_kill(); #endif #ifdef USE_GEM5 m5_dumpreset_stats(0, 0); #ifdef GEM5_EXIT_AFTER_WORK m5_exit(0); #endif #endif #ifdef TSC_TIMING READ_TIMESTAMP_WITH_WRAPPER( fec_timingVector[genData->myThread->getThreadLogicalId()+ TIMING_MAX_NUMBER_OF_THREADS] ); #endif #ifdef CLOCK_GETTIME_TIMING GET_TIME_WRAPPER(fec_timeStructVector[genData->myThread->getThreadLogicalId()+ TIMING_MAX_NUMBER_OF_THREADS]); #endif cout << "Coordinator Complete" << endl; return NULL; } void * workerThreadFunction(void * threadParam) { struct GeneralWorkerThreadData * genData = reinterpret_cast<struct GeneralWorkerThreadData *>(threadParam); struct FeatureExtractionWorkerThreadInfo *featureExtractionData = reinterpret_cast<FeatureExtractionWorkerThreadInfo *> (genData->featureExtractionData); struct WorkerThreadInfo * featureClassificationData = reinterpret_cast<struct WorkerThreadInfo * >(genData->featureClassificationData); //Setup the pieces featureExtractionWorkerThreadSetupFunctionStandAlone(genData,genData->featureExtractionData); classificationWorkerThreadSetupFunctionStandAlone(genData->featureClassificationData); #ifdef TSC_TIMING READ_TIMESTAMP_WITH_WRAPPER( fec_timingVector[genData->myThread->getThreadLogicalId()] ); #endif #ifdef CLOCK_GETTIME_TIMING GET_TIME_WRAPPER(fec_timeStructVector[genData->myThread->getThreadLogicalId()]); #endif while(!globalDone) { //Run the functions featureExtractionWorkerThreadFunctionStandAlone(genData,genData->featureExtractionData); #ifdef TSC_TIMING READ_TIMESTAMP_WITH_WRAPPER( fec_timingVector[genData->myThread->getThreadLogicalId()+ TIMING_MAX_NUMBER_OF_THREADS*2] ); #endif #ifdef CLOCK_GETTIME_TIMING GET_TIME_WRAPPER(fec_timeStructVector[genData->myThread->getThreadLogicalId()+ TIMING_MAX_NUMBER_OF_THREADS*2]); #endif if(featureExtractionData->featureExtractionInfo->outOfImages || featureExtractionData->myFeatureExtractionInfo->outOfImages) { break; } classificationWorkerThreadFunctionStandAlone(genData->featureClassificationData); } #ifdef TSC_TIMING READ_TIMESTAMP_WITH_WRAPPER( fec_timingVector[genData->myThread->getThreadLogicalId()+ TIMING_MAX_NUMBER_OF_THREADS] ); #endif #ifdef CLOCK_GETTIME_TIMING GET_TIME_WRAPPER(fec_timeStructVector[genData->myThread->getThreadLogicalId()+ TIMING_MAX_NUMBER_OF_THREADS]); #endif globalDone = true; return NULL; } void parseConfigCommandVector(FeatureExtractionAndClassificationConfig & config, vector<string> & commandStringVector, vector <string> &extractionExtraParams, vector<string> &classificationExtraParams) { vector<string>::iterator it_start = commandStringVector.begin(); vector<string>::iterator it_end = commandStringVector.end(); vector<string>::iterator it_current; stringstream stringBuffer; //Set the defaults config.featureClassificationConfigFile = "classificationConfig.txt"; config.featureExtractionConfigFile = "extractionConfig.txt"; config.configFileCount = 0; config.currentLoop = 0; config.maxLoops = 5; config.noShowWindows = false; config.noWaitKey = false; //-desc sift -match knn_flann -classify linear_svm -queryDescFile test.yml -trainDescFile test.yml -loadClassificationStruct test.yml -loadMatchStruct test.yml for(it_current=it_start; it_current!=it_end; ++it_current) { if(!it_current->compare("-extractionConfig") || !it_current->compare("-ExractionConfig")) { config.featureExtractionConfigFile =*(it_current+1); config.configFileCount |= 1; } if(!it_current->compare("-classificationConfig") || !it_current->compare("-ClassificationConfig")) { config.featureClassificationConfigFile =*(it_current+1); config.configFileCount |= 2; } if(!it_current->compare("-noShowWindows") || !it_current->compare("-NoShowWindows")) { config.noShowWindows = true; } if(!it_current->compare("-noWaitKey") || !it_current->compare("-NoWaitKey")) { config.noWaitKey = true; } if(!it_current->compare("-extractXtraParams") || !it_current->compare("-ExtractXtraParams")) { vector<string> xtraParamsVec; string extraParams =*(it_current+1); char currentString[120]; strcpy(currentString, extraParams.c_str()); char * currentTokPointer = strtok(currentString,","); while(currentTokPointer != NULL) { string currentNewString(currentTokPointer); xtraParamsVec.push_back(currentNewString); currentTokPointer = strtok(NULL,","); } extractionExtraParams = xtraParamsVec; } if(!it_current->compare("-classifyXtraParams") || !it_current->compare("-ClassifyXtraParams")) { vector<string> xtraParamsVec; string extraParams =*(it_current+1); char currentString[120]; strcpy(currentString, extraParams.c_str()); char * currentTokPointer = strtok(currentString,","); while(currentTokPointer != NULL) { string currentNewString(currentTokPointer); xtraParamsVec.push_back(currentNewString); currentTokPointer = strtok(NULL,","); } classificationExtraParams = xtraParamsVec; } } if(config.configFileCount != 3) { cout << "Warning: Not enough config files given on command line" << endl; } } void runMultiThreadedFeatureExtractionAndClassification(int argc, const char * argv[]) { vector<string> commandLineArgs; for(int i = 0; i < argc; i++) { string currentString = argv[i]; commandLineArgs.push_back(currentString); } FeatureExtractionAndClassificationConfig config; vector <string> extractionExtraParams; vector <string> classificationExtraParams; parseConfigCommandVector(config, commandLineArgs,extractionExtraParams, classificationExtraParams); FeatureExtractionConfig featureExtractionConfig; FeatureClassificationConfig featureClassificationConfig; setupFeatureExtractionConfigFromFile(config.featureExtractionConfigFile,featureExtractionConfig,extractionExtraParams); featureClassificationConfig = setupFeatureClassificationConfigFromFile(config.featureClassificationConfigFile,classificationExtraParams); //They need to have the same number of threads featureClassificationConfig.numberOfHorizontalProcs = featureExtractionConfig.numberOfHorizontalProcs; featureClassificationConfig.numberOfVerticalProcs = featureExtractionConfig.numberOfVerticalProcs; //Setup Extraction Data******************************* FeatureExtractionData featureExtractionData; featureExtractionSetupFeatureExtractionData(featureExtractionConfig, featureExtractionData); //#define WAIT_FOR_STABLE_STREAM #ifdef WAIT_FOR_STABLE_STREAM if(!config.noShowWindows) { int key = -1; namedWindow("CurrentStream"); while(key ==-1) { getNextImages((*(featureExtractionData.inputImagesPerFrame)),featureExtractionConfig); imshow("CurrentStream",(*(featureExtractionData.inputImagesPerFrame))[0]); key = waitKey(33); } destroyWindow("CurrentStream"); } #endif //Setup classification Data************************ Mat trainDescriptors; Mat trainDescriptorsClasses; vector<KeyPoint> trainKeypoints; Mat trainImage; Mat queryDescriptors; Mat queryDescriptorsClasses; vector<KeyPoint> queryKeypoints; // vector<struct WorkerThreadInfo> workingThreads; MultiThreadedMatResult * multiThreadResultPtr; MultiThreadedMatchResult * multiThreadMatchResultPtr; vector <vector<DMatch> >matches; Mat queryDescriptorsClassesComputed; Mat queryDescriptorsClassesLoaded; Mat queryImage; handleDescLoading(trainDescriptors,trainDescriptorsClasses, queryDescriptors,queryDescriptorsClassesLoaded,featureClassificationConfig); handleKeyPointLoading(trainKeypoints,queryKeypoints,featureClassificationConfig); handleImageLoading(trainImage,queryImage,featureClassificationConfig); //Create thread Manager ThreadManager * threadManager; featureExtractionCreateThreadManager(threadManager,featureExtractionConfig.numberOfVerticalProcs, featureExtractionConfig.numberOfHorizontalProcs); //Create the general struct vector<GeneralWorkerThreadData> genData(featureExtractionConfig.numberOfVerticalProcs *featureExtractionConfig.numberOfHorizontalProcs); //Create the worker infos for extraction and classification vector<struct FeatureExtractionWorkerThreadInfo> extractionWorkingThreads(featureExtractionConfig.numberOfVerticalProcs *featureExtractionConfig.numberOfHorizontalProcs); vector<struct WorkerThreadInfo> classificationWorkingThreads(featureClassificationConfig.numberOfVerticalProcs *featureClassificationConfig.numberOfHorizontalProcs); //Connect the general data and the working threads data for extraction setFeatureExtractionWorkingThreadDataInGeneralWorkingData(genData,extractionWorkingThreads); //Connect the general data and the working threads data for classification setClassificationWorkingThreadDataInGeneralWorkingData(genData, classificationWorkingThreads); //Setup the Extraction featureExtractionMultiThreadedSetupOnly(featureExtractionConfig, featureExtractionData, threadManager,genData); //Setup the Classification multiThreadedSetupOnly(trainDescriptors, trainDescriptorsClasses,trainKeypoints,trainImage,queryDescriptors,queryDescriptorsClasses,queryKeypoints,featureClassificationConfig,threadManager,genData,multiThreadResultPtr,multiThreadMatchResultPtr);; vector<void * > threadArgs(genData.size()); for(int i =0; i< threadArgs.size(); i++) { threadArgs[i] = (void *)&genData[i]; } vector<thread_fptr> threadFunctions(genData.size()); threadFunctions[0] = coordinatorThreadFunction; for(int i = 1; i < threadArgs.size(); i++) { threadFunctions[i] = workerThreadFunction; } //Place the data in the Thread manager featureExtractionSetupThreadManager(threadManager,featureExtractionConfig, threadFunctions, threadArgs,featureExtractionConfig.numberOfVerticalProcs, featureExtractionConfig.numberOfHorizontalProcs); globalDone = false; globalDataReady = false; featureExtractionLaunchThreads(threadManager); // bool globalDone; // bool globalDataReady; // Mat globalCurrentImage; // vector<Point2f> globalCurrentRefs; if(!config.noShowWindows) { namedWindow("CurrentResults"); } Mat currentResults; currentResults.create(480,640,CV_8UC3); vector<Point2f> currentRefs; int mainKey = -1; while(mainKey != 'd' && mainKey != 27 && !globalDone) { if(globalDataReady) { if(!config.noShowWindows) { currentResults = globalCurrentImage.clone(); currentRefs = globalCurrentRefs; } globalDataReady = false; } if(!config.noShowWindows) { for(int i = 0; i < currentRefs.size(); i++) { circle(currentResults,currentRefs[i],5,Scalar(0,255,255),CV_FILLED); } imshow("CurrentResults", currentResults); } if(!config.noWaitKey) { mainKey = waitKey(33) & 0xff; } } globalDone = true; //cout << "Waiting for Threads." << endl; for(int i=0 ; i<threadManager->getNumberOfThreads() ; i++) { pthread_join(threadManager->getThread(i)->getThreadId(), NULL); } //#define SHOW_FEATURE_CLASSIFICATION_OUTPUT_GEOM #ifdef SHOW_FEATURE_CLASSIFICATION_OUTPUT_GEOM namedWindow("Show Where"); vector<Point2f> estimatedPoints = reinterpret_cast<struct SparseFeaturePointObjectClassifier::SparseFeaturePointObjectClassifierMultiThreadData *>(classificationWorkingThreads[0].multiThreadAlgorithmData)->estimatedRefPoints->getResultsVec(); Mat where = classificationWorkingThreads[0].queryImage->clone(); for(int i = 0; i < estimatedPoints.size(); i++) { circle(where,estimatedPoints[i],5,Scalar(0,255,255),CV_FILLED); } imshow("Show Where", where); waitKey(0); destroyWindow("Show Where"); #endif cout << "Multithreaded App complete" << endl; return; } #ifdef TSC_TIMING void fec_writeTimingToFile(vector<TSC_VAL_w> timingVector) { ofstream outputFile; outputFile.open("timing.csv"); outputFile << "Thread,Start,Finish,Mid" << endl; for(int i = 0; i<(TIMING_MAX_NUMBER_OF_THREADS); i++) { outputFile << i << "," << timingVector[i] << "," << timingVector[i+TIMING_MAX_NUMBER_OF_THREADS]<< ","<< timingVector[i+2*TIMING_MAX_NUMBER_OF_THREADS] << endl; } outputFile.close(); } #endif #ifdef CLOCK_GETTIME_TIMING void fec_writeTimingToFile(vector<struct timespec> timingVector) { ofstream outputFile; outputFile.open("timing.csv"); outputFile << "Thread,Start sec, Start nsec,Finish sec, Finish nsec,Mid sec, Mid nsec" << endl; for(int i = 0; i<(TIMING_MAX_NUMBER_OF_THREADS); i++) { outputFile << i << "," << timingVector[i].tv_sec<<","<< timingVector[i].tv_nsec << "," << timingVector[i+TIMING_MAX_NUMBER_OF_THREADS].tv_sec<<","<< timingVector[i+TIMING_MAX_NUMBER_OF_THREADS].tv_nsec<< "," << timingVector[i+2*TIMING_MAX_NUMBER_OF_THREADS].tv_sec<<","<< timingVector[i+2*TIMING_MAX_NUMBER_OF_THREADS].tv_nsec <<endl; } outputFile.close(); } #endif int main (int argc, const char * argv[]) { cout << "Hello world" << endl; #ifdef TSC_TIMING fec_timingVector.resize(TIMING_MAX_NUMBER_OF_THREADS*3); #endif #ifdef CLOCK_GETTIME_TIMING //fec_timeStructVector.resize(16); fec_timeStructVector.resize(TIMING_MAX_NUMBER_OF_THREADS*3); #endif internalCallToTestExtractionAlone(argc,argv,false); runMultiThreadedFeatureExtractionAndClassification(argc,argv); #ifdef TSC_TIMING fec_writeTimingToFile(fec_timingVector); #endif #ifdef CLOCK_GETTIME_TIMING fec_writeTimingToFile(fec_timeStructVector); #endif return 0; }
29.024129
338
0.787225
jlclemon
0904adf7cbbba585ae156ead415d792a96316750
4,027
cpp
C++
Source/MainComponent.cpp
modosc/ffGuiAttachments
7351d1944e5bcba9a7089c61bca333851ce3bc09
[ "BSD-3-Clause" ]
24
2016-07-04T07:17:24.000Z
2021-12-03T18:58:52.000Z
Source/MainComponent.cpp
modosc/ffGuiAttachments
7351d1944e5bcba9a7089c61bca333851ce3bc09
[ "BSD-3-Clause" ]
2
2018-01-27T11:11:26.000Z
2018-03-19T11:59:01.000Z
Source/MainComponent.cpp
modosc/ffGuiAttachments
7351d1944e5bcba9a7089c61bca333851ce3bc09
[ "BSD-3-Clause" ]
7
2017-01-04T16:35:57.000Z
2021-10-03T03:40:23.000Z
/* ============================================================================== This file was auto-generated! ============================================================================== */ #include "../JuceLibraryCode/JuceHeader.h" #include "ff_gui_attachments/ff_gui_attachments.h" #include "MainComponent.h" //============================================================================== MainContentComponent::MainContentComponent() { slider = new Slider(); slider2 = new Slider(); tree = ValueTree ("TestTree"); tree.setProperty ("number", 5.0, nullptr); debugListener = new ValueTreeDebugListener (tree, true); ValueTree select = tree.getOrCreateChildWithName ("ComboBox", nullptr); ValueTree option1 = ValueTree ("Option"); option1.setProperty ("name", "Anything", nullptr); select.addChild (option1, 0, nullptr); ValueTree option2 = ValueTree ("Option"); option2.setProperty ("name", "Something", nullptr); option2.setProperty ("selected", 1, nullptr); select.addChild (option2, 1, nullptr); ValueTree option3 = ValueTree ("Option"); option3.setProperty ("name", "Nothing", nullptr); select.addChild (option3, 2, nullptr); ValueTree labelTree = tree.getOrCreateChildWithName ("Label", nullptr); labelTree.setProperty ("labeltext", "test", nullptr); combo = new ComboBox(); combo1 = new ComboBox(); addAndMakeVisible (slider); addAndMakeVisible (slider2); addAndMakeVisible (combo); addAndMakeVisible (combo1); juce::Array<juce::Button*> btns; ToggleButton* b = new ToggleButton ("Anything"); b->setComponentID ("Anything"); b->setRadioGroupId (100); buttons.add (b); btns.add (b); addAndMakeVisible (b); b = new ToggleButton ("Something"); b->setComponentID ("Something"); b->setRadioGroupId (100); buttons.add (b); btns.add (b); addAndMakeVisible (b); b = new ToggleButton ("Nothing"); b->setComponentID ("Nothing"); b->setRadioGroupId (100); buttons.add (b); btns.add (b); addAndMakeVisible (b); label = new Label(); label->setEditable (true); label->setColour (Label::outlineColourId, Colours::lightgrey); label1 = new Label(); label1->setColour (Label::outlineColourId, Colours::lightgrey); addAndMakeVisible (label); addAndMakeVisible (label1); labelToCombo = new Label(); labelToCombo->setEditable (true); labelToCombo->setColour (Label::outlineColourId, Colours::lightgrey); addAndMakeVisible (labelToCombo); attachment = new ValueTreeSliderAttachment (tree, slider, "number"); attachment2 = new ValueTreeSliderAttachment (tree, slider2, "number"); comboAttachment = new ValueTreeComboBoxAttachment (select, combo, "name", true); comboAttachment1 = new ValueTreeComboBoxAttachment (select, combo1, "name", true); buttonGroupAttachment = new ValueTreeRadioButtonGroupAttachment (select, btns, "name", true); labelAttachment = new ValueTreeLabelAttachment (labelTree, label, "labeltext"); labelAttachment1 = new ValueTreeLabelAttachment (labelTree, label1, "labeltext"); labelToComboAttachment = new ValueTreeLabelAttachment (option1, labelToCombo, "name"); setSize (600, 400); } MainContentComponent::~MainContentComponent() { } void MainContentComponent::paint (Graphics& g) { g.fillAll (Colours::lightcoral); g.setFont (Font (16.0f)); g.setColour (Colours::white); g.drawText ("Hello World!", getLocalBounds(), Justification::centred, true); } void MainContentComponent::resized() { slider->setBounds (5, 5, 150, 60); slider2->setBounds(160, 5, 150, 60); combo->setBounds (5, 70, 150, 20); combo1->setBounds (5, 100, 150, 20); for (int i=0; i < buttons.size(); ++i) { buttons.getUnchecked (i)->setBounds (160, 70 + i * 30, 150, 25); } label->setBounds (330, 10, 150, 20); label1->setBounds (330, 40, 150, 20); labelToCombo->setBounds (330, 80, 150, 20); }
31.460938
97
0.636951
modosc
0908e52a400c8c065bc1b489e94b58c6bfe7c914
710
cpp
C++
models/processor/zesto/ZCOMPS-bpred/bpred-taken.cpp
Basseuph/manifold
99779998911ed7e8b8ff6adacc7f93080409a5fe
[ "BSD-3-Clause" ]
8
2016-01-22T18:28:48.000Z
2021-05-07T02:27:21.000Z
models/processor/zesto/ZCOMPS-bpred/bpred-taken.cpp
Basseuph/manifold
99779998911ed7e8b8ff6adacc7f93080409a5fe
[ "BSD-3-Clause" ]
3
2016-04-15T02:58:58.000Z
2017-01-19T17:07:34.000Z
models/processor/zesto/ZCOMPS-bpred/bpred-taken.cpp
Basseuph/manifold
99779998911ed7e8b8ff6adacc7f93080409a5fe
[ "BSD-3-Clause" ]
10
2015-12-11T04:16:55.000Z
2019-05-25T20:58:13.000Z
/* bpred-taken.cpp: Static always taken predictor */ /* * __COPYRIGHT__ GT */ #define COMPONENT_NAME "taken" #ifdef BPRED_PARSE_ARGS if(!strcasecmp(COMPONENT_NAME,type)) { return new bpred_taken_t(); } #else class bpred_taken_t:public bpred_dir_t { public: /* CREATE */ bpred_taken_t() { init(); name = strdup(COMPONENT_NAME); if(!name) fatal("couldn't malloc taken name (strdup)"); type = strdup("static taken"); if(!type) fatal("couldn't malloc taken type (strdup)"); bits = 0; } /* LOOKUP */ BPRED_LOOKUP_HEADER { BPRED_STAT(lookups++;) scvp->updated = false; return 1; } }; #endif /* BPRED_PARSE_ARGS */ #undef COMPONENT_NAME
15.106383
52
0.638028
Basseuph
0909e18cd34a9a51ec677dd6746c0a2232c25038
145
hpp
C++
options/internal/include/mlibc/thread.hpp
vinix-os/mlibc
4cff8ea22e4dcd25bcce90d00ac5b93a6c51d9d8
[ "MIT" ]
null
null
null
options/internal/include/mlibc/thread.hpp
vinix-os/mlibc
4cff8ea22e4dcd25bcce90d00ac5b93a6c51d9d8
[ "MIT" ]
null
null
null
options/internal/include/mlibc/thread.hpp
vinix-os/mlibc
4cff8ea22e4dcd25bcce90d00ac5b93a6c51d9d8
[ "MIT" ]
null
null
null
#pragma once #include <mlibc/tcb.hpp> #include <stdint.h> namespace mlibc { Tcb *get_current_tcb(); uintptr_t get_sp(); } // namespace mlibc
12.083333
24
0.710345
vinix-os
0909ffb20f77ce06f1a6e30ed5c60373befc0468
1,845
hpp
C++
src/libs/dotparser/Expression.hpp
AirbusCyber/grap
dbb037c4e37926e182d0489295b7d901bd0c7c3b
[ "MIT" ]
171
2017-11-09T00:37:58.000Z
2021-10-20T08:58:44.000Z
src/libs/dotparser/Expression.hpp
QuoSecGmbH/grap
dbb037c4e37926e182d0489295b7d901bd0c7c3b
[ "MIT" ]
2
2018-01-09T12:13:39.000Z
2019-03-11T09:58:36.000Z
src/libs/dotparser/Expression.hpp
AirbusCyber/grap
dbb037c4e37926e182d0489295b7d901bd0c7c3b
[ "MIT" ]
18
2017-11-09T01:17:23.000Z
2020-04-23T07:02:32.000Z
/* * Expression.h * Definition of the structure used to build the syntax tree. */ #ifndef __EXPRESSION_H__ #define __EXPRESSION_H__ #include "graph.hpp" #include "graphIO.hpp" #include "node_info.hpp" #include <stddef.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <iostream> typedef struct GraphList { vsize_t size; graph_t** graphes; } GraphList; typedef struct Couple { vsize_t x; vsize_t y; bool is_numbered; bool is_wildcard; bool is_child1; } Couple; typedef struct CoupleList { vsize_t size; Couple** couples; } CoupleList; typedef struct Option { char* id; char* value; } Option; typedef struct OptionList { vsize_t size; Option** options; } OptionList; vsize_t hash_func(char* s); void debug_print(char* s); GraphList* createGraphList(); GraphList* addGraphToInput(graph_t* g, GraphList* gl); typedef std::list<graph_t*> GraphCppList; void freeGraphList(GraphList* gl, bool freeGraphs, bool free_info); void freeGraphList(GraphCppList gl, bool freeGraphs, bool free_info); GraphCppList MakeGraphList(GraphList* gl); CoupleList* createEdgeList(); void freeEdgeList(CoupleList* cl); char *removeQuotes(char *s); CoupleList* addEdgeToList(Couple* c, CoupleList* cl); Couple* createEdge(char* f, char* c, OptionList* ol); graph_t* addEdgesToGraph(char* name, CoupleList* cl, graph_t* g); node_t* updateNode(OptionList* ol, node_t* n); OptionList* createOptionList(); OptionList* addOptionToList(Option* o, OptionList* ol); Option* createOption(char* I, char* V); /** * @brief It creates a node * @param value The name of the node * @return The graph or NULL in case of no memory */ node_t *createNode(char* value); graph_t *createGraph(); graph_t* addNodeToGraph(node_t* n, graph_t* g); void freeOption(Option* o); void freeOptionList(OptionList* ol); #endif
19.21875
69
0.737127
AirbusCyber
090dcddd5f26674efa0d9183b86319b3f794d507
134,724
cpp
C++
boards/ip/hls/x-order_filter/solution1/syn/systemc/x_order_fir.cpp
xupsh/pynq_x_filter
af6dc348b34ede1c071d96a53e44f51fbb2a961c
[ "BSD-3-Clause" ]
1
2022-03-29T23:17:59.000Z
2022-03-29T23:17:59.000Z
boards/ip/hls/x-order_filter/solution1/syn/systemc/x_order_fir.cpp
xupsh/pynq_x_filter
af6dc348b34ede1c071d96a53e44f51fbb2a961c
[ "BSD-3-Clause" ]
null
null
null
boards/ip/hls/x-order_filter/solution1/syn/systemc/x_order_fir.cpp
xupsh/pynq_x_filter
af6dc348b34ede1c071d96a53e44f51fbb2a961c
[ "BSD-3-Clause" ]
null
null
null
// ============================================================== // RTL generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC // Version: 2018.3 // Copyright (C) 1986-2018 Xilinx, Inc. All Rights Reserved. // // =========================================================== #include "x_order_fir.h" #include "AESL_pkg.h" using namespace std; namespace ap_rtl { const sc_logic x_order_fir::ap_const_logic_1 = sc_dt::Log_1; const sc_logic x_order_fir::ap_const_logic_0 = sc_dt::Log_0; const sc_lv<26> x_order_fir::ap_ST_fsm_state1 = "1"; const sc_lv<26> x_order_fir::ap_ST_fsm_state2 = "10"; const sc_lv<26> x_order_fir::ap_ST_fsm_state3 = "100"; const sc_lv<26> x_order_fir::ap_ST_fsm_state4 = "1000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state5 = "10000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state6 = "100000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state7 = "1000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state8 = "10000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_pp0_stage0 = "100000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state12 = "1000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state13 = "10000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state14 = "100000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state15 = "1000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state16 = "10000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state17 = "100000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state18 = "1000000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state19 = "10000000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_pp1_stage0 = "100000000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state23 = "1000000000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_pp2_stage0 = "10000000000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_pp2_stage1 = "100000000000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state28 = "1000000000000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state29 = "10000000000000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state30 = "100000000000000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state31 = "1000000000000000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state32 = "10000000000000000000000000"; const sc_lv<32> x_order_fir::ap_const_lv32_0 = "00000000000000000000000000000000"; const bool x_order_fir::ap_const_boolean_1 = true; const sc_lv<1> x_order_fir::ap_const_lv1_0 = "0"; const sc_lv<1> x_order_fir::ap_const_lv1_1 = "1"; const sc_lv<2> x_order_fir::ap_const_lv2_0 = "00"; const sc_lv<2> x_order_fir::ap_const_lv2_2 = "10"; const sc_lv<2> x_order_fir::ap_const_lv2_3 = "11"; const sc_lv<2> x_order_fir::ap_const_lv2_1 = "1"; const sc_lv<32> x_order_fir::ap_const_lv32_1 = "1"; const sc_lv<32> x_order_fir::ap_const_lv32_8 = "1000"; const bool x_order_fir::ap_const_boolean_0 = false; const sc_lv<32> x_order_fir::ap_const_lv32_A = "1010"; const sc_lv<32> x_order_fir::ap_const_lv32_11 = "10001"; const sc_lv<32> x_order_fir::ap_const_lv32_18 = "11000"; const sc_lv<32> x_order_fir::ap_const_lv32_19 = "11001"; const sc_lv<32> x_order_fir::ap_const_lv32_17 = "10111"; const int x_order_fir::C_S_AXI_DATA_WIDTH = "100000"; const int x_order_fir::C_M_AXI_GMEM_USER_VALUE = "0000000000000000000000000000000000000000000000000000000000000000"; const int x_order_fir::C_M_AXI_GMEM_PROT_VALUE = "0000000000000000000000000000000000000000000000000000000000000000"; const int x_order_fir::C_M_AXI_GMEM_CACHE_VALUE = "11"; const int x_order_fir::C_M_AXI_DATA_WIDTH = "100000"; const sc_lv<32> x_order_fir::ap_const_lv32_14 = "10100"; const sc_lv<32> x_order_fir::ap_const_lv32_16 = "10110"; const sc_lv<32> x_order_fir::ap_const_lv32_7 = "111"; const sc_lv<32> x_order_fir::ap_const_lv32_9 = "1001"; const sc_lv<32> x_order_fir::ap_const_lv32_13 = "10011"; const sc_lv<32> x_order_fir::ap_const_lv32_10 = "10000"; const sc_lv<32> x_order_fir::ap_const_lv32_12 = "10010"; const sc_lv<30> x_order_fir::ap_const_lv30_0 = "000000000000000000000000000000"; const sc_lv<32> x_order_fir::ap_const_lv32_2 = "10"; const sc_lv<3> x_order_fir::ap_const_lv3_0 = "000"; const sc_lv<4> x_order_fir::ap_const_lv4_0 = "0000"; const sc_lv<32> x_order_fir::ap_const_lv32_15 = "10101"; const sc_lv<10> x_order_fir::ap_const_lv10_0 = "0000000000"; const sc_lv<32> x_order_fir::ap_const_lv32_1F = "11111"; const sc_lv<32> x_order_fir::ap_const_lv32_4 = "100"; const sc_lv<30> x_order_fir::ap_const_lv30_1 = "1"; const sc_lv<32> x_order_fir::ap_const_lv32_FFFFFFFF = "11111111111111111111111111111111"; x_order_fir::x_order_fir(sc_module_name name) : sc_module(name), mVcdFile(0) { coef_U = new x_order_fir_coef("coef_U"); coef_U->clk(ap_clk); coef_U->reset(ap_rst_n_inv); coef_U->address0(coef_address0); coef_U->ce0(coef_ce0); coef_U->we0(coef_we0); coef_U->d0(gmem_addr_1_read_reg_555); coef_U->q0(coef_q0); shift_reg_U = new x_order_fir_coef("shift_reg_U"); shift_reg_U->clk(ap_clk); shift_reg_U->reset(ap_rst_n_inv); shift_reg_U->address0(shift_reg_address0); shift_reg_U->ce0(shift_reg_ce0); shift_reg_U->we0(shift_reg_we0); shift_reg_U->d0(shift_reg_d0); shift_reg_U->q0(shift_reg_q0); x_order_fir_AXILiteS_s_axi_U = new x_order_fir_AXILiteS_s_axi<C_S_AXI_AXILITES_ADDR_WIDTH,C_S_AXI_AXILITES_DATA_WIDTH>("x_order_fir_AXILiteS_s_axi_U"); x_order_fir_AXILiteS_s_axi_U->AWVALID(s_axi_AXILiteS_AWVALID); x_order_fir_AXILiteS_s_axi_U->AWREADY(s_axi_AXILiteS_AWREADY); x_order_fir_AXILiteS_s_axi_U->AWADDR(s_axi_AXILiteS_AWADDR); x_order_fir_AXILiteS_s_axi_U->WVALID(s_axi_AXILiteS_WVALID); x_order_fir_AXILiteS_s_axi_U->WREADY(s_axi_AXILiteS_WREADY); x_order_fir_AXILiteS_s_axi_U->WDATA(s_axi_AXILiteS_WDATA); x_order_fir_AXILiteS_s_axi_U->WSTRB(s_axi_AXILiteS_WSTRB); x_order_fir_AXILiteS_s_axi_U->ARVALID(s_axi_AXILiteS_ARVALID); x_order_fir_AXILiteS_s_axi_U->ARREADY(s_axi_AXILiteS_ARREADY); x_order_fir_AXILiteS_s_axi_U->ARADDR(s_axi_AXILiteS_ARADDR); x_order_fir_AXILiteS_s_axi_U->RVALID(s_axi_AXILiteS_RVALID); x_order_fir_AXILiteS_s_axi_U->RREADY(s_axi_AXILiteS_RREADY); x_order_fir_AXILiteS_s_axi_U->RDATA(s_axi_AXILiteS_RDATA); x_order_fir_AXILiteS_s_axi_U->RRESP(s_axi_AXILiteS_RRESP); x_order_fir_AXILiteS_s_axi_U->BVALID(s_axi_AXILiteS_BVALID); x_order_fir_AXILiteS_s_axi_U->BREADY(s_axi_AXILiteS_BREADY); x_order_fir_AXILiteS_s_axi_U->BRESP(s_axi_AXILiteS_BRESP); x_order_fir_AXILiteS_s_axi_U->ACLK(ap_clk); x_order_fir_AXILiteS_s_axi_U->ARESET(ap_rst_n_inv); x_order_fir_AXILiteS_s_axi_U->ACLK_EN(ap_var_for_const0); x_order_fir_AXILiteS_s_axi_U->ap_start(ap_start); x_order_fir_AXILiteS_s_axi_U->interrupt(interrupt); x_order_fir_AXILiteS_s_axi_U->ap_ready(ap_ready); x_order_fir_AXILiteS_s_axi_U->ap_done(ap_done); x_order_fir_AXILiteS_s_axi_U->ap_idle(ap_idle); x_order_fir_AXILiteS_s_axi_U->coe(coe); x_order_fir_AXILiteS_s_axi_U->ctrl(ctrl); x_order_fir_gmem_m_axi_U = new x_order_fir_gmem_m_axi<0,32,32,5,16,16,16,16,C_M_AXI_GMEM_ID_WIDTH,C_M_AXI_GMEM_ADDR_WIDTH,C_M_AXI_GMEM_DATA_WIDTH,C_M_AXI_GMEM_AWUSER_WIDTH,C_M_AXI_GMEM_ARUSER_WIDTH,C_M_AXI_GMEM_WUSER_WIDTH,C_M_AXI_GMEM_RUSER_WIDTH,C_M_AXI_GMEM_BUSER_WIDTH,C_M_AXI_GMEM_USER_VALUE,C_M_AXI_GMEM_PROT_VALUE,C_M_AXI_GMEM_CACHE_VALUE>("x_order_fir_gmem_m_axi_U"); x_order_fir_gmem_m_axi_U->AWVALID(m_axi_gmem_AWVALID); x_order_fir_gmem_m_axi_U->AWREADY(m_axi_gmem_AWREADY); x_order_fir_gmem_m_axi_U->AWADDR(m_axi_gmem_AWADDR); x_order_fir_gmem_m_axi_U->AWID(m_axi_gmem_AWID); x_order_fir_gmem_m_axi_U->AWLEN(m_axi_gmem_AWLEN); x_order_fir_gmem_m_axi_U->AWSIZE(m_axi_gmem_AWSIZE); x_order_fir_gmem_m_axi_U->AWBURST(m_axi_gmem_AWBURST); x_order_fir_gmem_m_axi_U->AWLOCK(m_axi_gmem_AWLOCK); x_order_fir_gmem_m_axi_U->AWCACHE(m_axi_gmem_AWCACHE); x_order_fir_gmem_m_axi_U->AWPROT(m_axi_gmem_AWPROT); x_order_fir_gmem_m_axi_U->AWQOS(m_axi_gmem_AWQOS); x_order_fir_gmem_m_axi_U->AWREGION(m_axi_gmem_AWREGION); x_order_fir_gmem_m_axi_U->AWUSER(m_axi_gmem_AWUSER); x_order_fir_gmem_m_axi_U->WVALID(m_axi_gmem_WVALID); x_order_fir_gmem_m_axi_U->WREADY(m_axi_gmem_WREADY); x_order_fir_gmem_m_axi_U->WDATA(m_axi_gmem_WDATA); x_order_fir_gmem_m_axi_U->WSTRB(m_axi_gmem_WSTRB); x_order_fir_gmem_m_axi_U->WLAST(m_axi_gmem_WLAST); x_order_fir_gmem_m_axi_U->WID(m_axi_gmem_WID); x_order_fir_gmem_m_axi_U->WUSER(m_axi_gmem_WUSER); x_order_fir_gmem_m_axi_U->ARVALID(m_axi_gmem_ARVALID); x_order_fir_gmem_m_axi_U->ARREADY(m_axi_gmem_ARREADY); x_order_fir_gmem_m_axi_U->ARADDR(m_axi_gmem_ARADDR); x_order_fir_gmem_m_axi_U->ARID(m_axi_gmem_ARID); x_order_fir_gmem_m_axi_U->ARLEN(m_axi_gmem_ARLEN); x_order_fir_gmem_m_axi_U->ARSIZE(m_axi_gmem_ARSIZE); x_order_fir_gmem_m_axi_U->ARBURST(m_axi_gmem_ARBURST); x_order_fir_gmem_m_axi_U->ARLOCK(m_axi_gmem_ARLOCK); x_order_fir_gmem_m_axi_U->ARCACHE(m_axi_gmem_ARCACHE); x_order_fir_gmem_m_axi_U->ARPROT(m_axi_gmem_ARPROT); x_order_fir_gmem_m_axi_U->ARQOS(m_axi_gmem_ARQOS); x_order_fir_gmem_m_axi_U->ARREGION(m_axi_gmem_ARREGION); x_order_fir_gmem_m_axi_U->ARUSER(m_axi_gmem_ARUSER); x_order_fir_gmem_m_axi_U->RVALID(m_axi_gmem_RVALID); x_order_fir_gmem_m_axi_U->RREADY(m_axi_gmem_RREADY); x_order_fir_gmem_m_axi_U->RDATA(m_axi_gmem_RDATA); x_order_fir_gmem_m_axi_U->RLAST(m_axi_gmem_RLAST); x_order_fir_gmem_m_axi_U->RID(m_axi_gmem_RID); x_order_fir_gmem_m_axi_U->RUSER(m_axi_gmem_RUSER); x_order_fir_gmem_m_axi_U->RRESP(m_axi_gmem_RRESP); x_order_fir_gmem_m_axi_U->BVALID(m_axi_gmem_BVALID); x_order_fir_gmem_m_axi_U->BREADY(m_axi_gmem_BREADY); x_order_fir_gmem_m_axi_U->BRESP(m_axi_gmem_BRESP); x_order_fir_gmem_m_axi_U->BID(m_axi_gmem_BID); x_order_fir_gmem_m_axi_U->BUSER(m_axi_gmem_BUSER); x_order_fir_gmem_m_axi_U->ACLK(ap_clk); x_order_fir_gmem_m_axi_U->ARESET(ap_rst_n_inv); x_order_fir_gmem_m_axi_U->ACLK_EN(ap_var_for_const0); x_order_fir_gmem_m_axi_U->I_ARVALID(gmem_ARVALID); x_order_fir_gmem_m_axi_U->I_ARREADY(gmem_ARREADY); x_order_fir_gmem_m_axi_U->I_ARADDR(gmem_ARADDR); x_order_fir_gmem_m_axi_U->I_ARID(ap_var_for_const1); x_order_fir_gmem_m_axi_U->I_ARLEN(gmem_ARLEN); x_order_fir_gmem_m_axi_U->I_ARSIZE(ap_var_for_const2); x_order_fir_gmem_m_axi_U->I_ARLOCK(ap_var_for_const3); x_order_fir_gmem_m_axi_U->I_ARCACHE(ap_var_for_const4); x_order_fir_gmem_m_axi_U->I_ARQOS(ap_var_for_const4); x_order_fir_gmem_m_axi_U->I_ARPROT(ap_var_for_const2); x_order_fir_gmem_m_axi_U->I_ARUSER(ap_var_for_const1); x_order_fir_gmem_m_axi_U->I_ARBURST(ap_var_for_const3); x_order_fir_gmem_m_axi_U->I_ARREGION(ap_var_for_const4); x_order_fir_gmem_m_axi_U->I_RVALID(gmem_RVALID); x_order_fir_gmem_m_axi_U->I_RREADY(gmem_RREADY); x_order_fir_gmem_m_axi_U->I_RDATA(gmem_RDATA); x_order_fir_gmem_m_axi_U->I_RID(gmem_RID); x_order_fir_gmem_m_axi_U->I_RUSER(gmem_RUSER); x_order_fir_gmem_m_axi_U->I_RRESP(gmem_RRESP); x_order_fir_gmem_m_axi_U->I_RLAST(gmem_RLAST); x_order_fir_gmem_m_axi_U->I_AWVALID(ap_var_for_const5); x_order_fir_gmem_m_axi_U->I_AWREADY(gmem_AWREADY); x_order_fir_gmem_m_axi_U->I_AWADDR(ap_var_for_const6); x_order_fir_gmem_m_axi_U->I_AWID(ap_var_for_const1); x_order_fir_gmem_m_axi_U->I_AWLEN(ap_var_for_const6); x_order_fir_gmem_m_axi_U->I_AWSIZE(ap_var_for_const2); x_order_fir_gmem_m_axi_U->I_AWLOCK(ap_var_for_const3); x_order_fir_gmem_m_axi_U->I_AWCACHE(ap_var_for_const4); x_order_fir_gmem_m_axi_U->I_AWQOS(ap_var_for_const4); x_order_fir_gmem_m_axi_U->I_AWPROT(ap_var_for_const2); x_order_fir_gmem_m_axi_U->I_AWUSER(ap_var_for_const1); x_order_fir_gmem_m_axi_U->I_AWBURST(ap_var_for_const3); x_order_fir_gmem_m_axi_U->I_AWREGION(ap_var_for_const4); x_order_fir_gmem_m_axi_U->I_WVALID(ap_var_for_const5); x_order_fir_gmem_m_axi_U->I_WREADY(gmem_WREADY); x_order_fir_gmem_m_axi_U->I_WDATA(ap_var_for_const6); x_order_fir_gmem_m_axi_U->I_WID(ap_var_for_const1); x_order_fir_gmem_m_axi_U->I_WUSER(ap_var_for_const1); x_order_fir_gmem_m_axi_U->I_WLAST(ap_var_for_const5); x_order_fir_gmem_m_axi_U->I_WSTRB(ap_var_for_const4); x_order_fir_gmem_m_axi_U->I_BVALID(gmem_BVALID); x_order_fir_gmem_m_axi_U->I_BREADY(ap_var_for_const5); x_order_fir_gmem_m_axi_U->I_BRESP(gmem_BRESP); x_order_fir_gmem_m_axi_U->I_BID(gmem_BID); x_order_fir_gmem_m_axi_U->I_BUSER(gmem_BUSER); SC_METHOD(thread_ap_clk_no_reset_); dont_initialize(); sensitive << ( ap_clk.pos() ); SC_METHOD(thread_acc_1_fu_472_p2); sensitive << ( acc_reg_290 ); sensitive << ( tmp_3_reg_609 ); SC_METHOD(thread_acc_2_fu_448_p2); sensitive << ( acc_reg_290 ); sensitive << ( tmp_8_reg_589 ); SC_METHOD(thread_ap_CS_fsm_pp0_stage0); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_pp1_stage0); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_pp2_stage0); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_pp2_stage1); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state1); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state12); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state13); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state19); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state2); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state23); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state28); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state29); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state30); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state31); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state32); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state8); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_block_pp0_stage0); SC_METHOD(thread_ap_block_pp0_stage0_11001); sensitive << ( ap_enable_reg_pp0_iter1 ); sensitive << ( exitcond_reg_500 ); sensitive << ( gmem_RVALID ); SC_METHOD(thread_ap_block_pp0_stage0_subdone); sensitive << ( ap_enable_reg_pp0_iter1 ); sensitive << ( exitcond_reg_500 ); sensitive << ( gmem_RVALID ); SC_METHOD(thread_ap_block_pp1_stage0); SC_METHOD(thread_ap_block_pp1_stage0_11001); sensitive << ( ap_enable_reg_pp1_iter1 ); sensitive << ( exitcond1_reg_546 ); sensitive << ( gmem_RVALID ); SC_METHOD(thread_ap_block_pp1_stage0_subdone); sensitive << ( ap_enable_reg_pp1_iter1 ); sensitive << ( exitcond1_reg_546 ); sensitive << ( gmem_RVALID ); SC_METHOD(thread_ap_block_pp2_stage0); SC_METHOD(thread_ap_block_pp2_stage0_11001); SC_METHOD(thread_ap_block_pp2_stage0_subdone); SC_METHOD(thread_ap_block_pp2_stage1); SC_METHOD(thread_ap_block_pp2_stage1_11001); SC_METHOD(thread_ap_block_pp2_stage1_subdone); SC_METHOD(thread_ap_block_state10_pp0_stage0_iter1); sensitive << ( exitcond_reg_500 ); sensitive << ( gmem_RVALID ); SC_METHOD(thread_ap_block_state11_pp0_stage0_iter2); SC_METHOD(thread_ap_block_state20_pp1_stage0_iter0); SC_METHOD(thread_ap_block_state21_pp1_stage0_iter1); sensitive << ( exitcond1_reg_546 ); sensitive << ( gmem_RVALID ); SC_METHOD(thread_ap_block_state22_pp1_stage0_iter2); SC_METHOD(thread_ap_block_state24_pp2_stage0_iter0); SC_METHOD(thread_ap_block_state25_pp2_stage1_iter0); SC_METHOD(thread_ap_block_state26_pp2_stage0_iter1); SC_METHOD(thread_ap_block_state27_pp2_stage1_iter1); SC_METHOD(thread_ap_block_state32); sensitive << ( y_data_1_ack_in ); sensitive << ( y_user_V_1_ack_in ); sensitive << ( y_last_V_1_ack_in ); SC_METHOD(thread_ap_block_state9_pp0_stage0_iter0); SC_METHOD(thread_ap_condition_pp0_exit_iter0_state9); sensitive << ( exitcond_fu_345_p2 ); SC_METHOD(thread_ap_condition_pp1_exit_iter0_state20); sensitive << ( exitcond1_fu_405_p2 ); SC_METHOD(thread_ap_condition_pp2_exit_iter0_state24); sensitive << ( tmp_2_fu_421_p2 ); SC_METHOD(thread_ap_done); sensitive << ( y_data_1_ack_in ); sensitive << ( y_data_1_state ); sensitive << ( y_user_V_1_ack_in ); sensitive << ( y_user_V_1_state ); sensitive << ( y_last_V_1_ack_in ); sensitive << ( y_last_V_1_state ); sensitive << ( ap_CS_fsm_state32 ); SC_METHOD(thread_ap_enable_pp0); sensitive << ( ap_idle_pp0 ); SC_METHOD(thread_ap_enable_pp1); sensitive << ( ap_idle_pp1 ); SC_METHOD(thread_ap_enable_pp2); sensitive << ( ap_idle_pp2 ); SC_METHOD(thread_ap_idle); sensitive << ( ap_start ); sensitive << ( ap_CS_fsm_state1 ); SC_METHOD(thread_ap_idle_pp0); sensitive << ( ap_enable_reg_pp0_iter1 ); sensitive << ( ap_enable_reg_pp0_iter0 ); sensitive << ( ap_enable_reg_pp0_iter2 ); SC_METHOD(thread_ap_idle_pp1); sensitive << ( ap_enable_reg_pp1_iter1 ); sensitive << ( ap_enable_reg_pp1_iter0 ); sensitive << ( ap_enable_reg_pp1_iter2 ); SC_METHOD(thread_ap_idle_pp2); sensitive << ( ap_enable_reg_pp2_iter0 ); sensitive << ( ap_enable_reg_pp2_iter1 ); SC_METHOD(thread_ap_phi_mux_i1_phi_fu_283_p4); sensitive << ( i1_reg_280 ); sensitive << ( tmp_2_reg_560 ); sensitive << ( ap_CS_fsm_pp2_stage0 ); sensitive << ( i_1_reg_564 ); sensitive << ( ap_enable_reg_pp2_iter1 ); sensitive << ( ap_block_pp2_stage0 ); SC_METHOD(thread_ap_phi_mux_indvar1_phi_fu_272_p4); sensitive << ( ap_CS_fsm_pp1_stage0 ); sensitive << ( ap_enable_reg_pp1_iter1 ); sensitive << ( ap_block_pp1_stage0 ); sensitive << ( exitcond1_reg_546 ); sensitive << ( indvar1_reg_268 ); sensitive << ( indvar_next1_reg_550 ); SC_METHOD(thread_ap_ready); sensitive << ( y_data_1_ack_in ); sensitive << ( y_data_1_state ); sensitive << ( y_user_V_1_ack_in ); sensitive << ( y_user_V_1_state ); sensitive << ( y_last_V_1_ack_in ); sensitive << ( y_last_V_1_state ); sensitive << ( ap_CS_fsm_state32 ); SC_METHOD(thread_ap_rst_n_inv); sensitive << ( ap_rst_n ); SC_METHOD(thread_ap_sig_ioackin_gmem_ARREADY); sensitive << ( gmem_ARREADY ); sensitive << ( ap_reg_ioackin_gmem_ARREADY ); SC_METHOD(thread_coef_address0); sensitive << ( ap_block_pp1_stage0 ); sensitive << ( ap_enable_reg_pp2_iter0 ); sensitive << ( ap_CS_fsm_pp2_stage0 ); sensitive << ( tmp_7_fu_438_p1 ); sensitive << ( ap_enable_reg_pp1_iter2 ); sensitive << ( ap_block_pp2_stage0 ); sensitive << ( indvar2_fu_416_p1 ); sensitive << ( ap_CS_fsm_state28 ); SC_METHOD(thread_coef_ce0); sensitive << ( ap_block_pp1_stage0_11001 ); sensitive << ( ap_enable_reg_pp2_iter0 ); sensitive << ( ap_CS_fsm_pp2_stage0 ); sensitive << ( ap_block_pp2_stage0_11001 ); sensitive << ( ap_enable_reg_pp1_iter2 ); sensitive << ( ap_CS_fsm_state28 ); SC_METHOD(thread_coef_we0); sensitive << ( ap_block_pp1_stage0_11001 ); sensitive << ( exitcond1_reg_546_pp1_iter1_reg ); sensitive << ( ap_enable_reg_pp1_iter2 ); SC_METHOD(thread_exitcond1_fu_405_p2); sensitive << ( ap_CS_fsm_pp1_stage0 ); sensitive << ( ap_block_pp1_stage0_11001 ); sensitive << ( p_add7_i32_shr_reg_535 ); sensitive << ( ap_enable_reg_pp1_iter0 ); sensitive << ( ap_phi_mux_indvar1_phi_fu_272_p4 ); SC_METHOD(thread_exitcond_fu_345_p2); sensitive << ( ap_CS_fsm_pp0_stage0 ); sensitive << ( indvar_reg_257 ); sensitive << ( ap_block_pp0_stage0_11001 ); sensitive << ( ap_enable_reg_pp0_iter0 ); SC_METHOD(thread_fir_ctrl_1_1_fu_361_p3); sensitive << ( i_reg_233 ); sensitive << ( tmp_10_reg_509_pp0_iter1_reg ); sensitive << ( fir_ctrl_0_reg_515 ); SC_METHOD(thread_gmem_ARADDR); sensitive << ( ap_CS_fsm_state2 ); sensitive << ( ap_CS_fsm_state13 ); sensitive << ( gmem_addr_1_reg_494 ); sensitive << ( tmp_5_fu_326_p1 ); sensitive << ( ap_reg_ioackin_gmem_ARREADY ); SC_METHOD(thread_gmem_ARLEN); sensitive << ( ap_CS_fsm_state2 ); sensitive << ( ap_CS_fsm_state13 ); sensitive << ( tmp_s_fu_401_p1 ); sensitive << ( ap_reg_ioackin_gmem_ARREADY ); SC_METHOD(thread_gmem_ARVALID); sensitive << ( ap_CS_fsm_state2 ); sensitive << ( ap_CS_fsm_state13 ); sensitive << ( ap_reg_ioackin_gmem_ARREADY ); SC_METHOD(thread_gmem_RREADY); sensitive << ( ap_CS_fsm_pp0_stage0 ); sensitive << ( ap_enable_reg_pp0_iter1 ); sensitive << ( exitcond_reg_500 ); sensitive << ( ap_CS_fsm_pp1_stage0 ); sensitive << ( ap_enable_reg_pp1_iter1 ); sensitive << ( exitcond1_reg_546 ); sensitive << ( ap_block_pp1_stage0_11001 ); sensitive << ( ap_block_pp0_stage0_11001 ); SC_METHOD(thread_gmem_blk_n_AR); sensitive << ( m_axi_gmem_ARREADY ); sensitive << ( ap_CS_fsm_state2 ); sensitive << ( ap_CS_fsm_state13 ); SC_METHOD(thread_gmem_blk_n_R); sensitive << ( m_axi_gmem_RVALID ); sensitive << ( ap_CS_fsm_pp0_stage0 ); sensitive << ( ap_enable_reg_pp0_iter1 ); sensitive << ( ap_block_pp0_stage0 ); sensitive << ( exitcond_reg_500 ); sensitive << ( ap_CS_fsm_pp1_stage0 ); sensitive << ( ap_enable_reg_pp1_iter1 ); sensitive << ( ap_block_pp1_stage0 ); sensitive << ( exitcond1_reg_546 ); SC_METHOD(thread_i_1_fu_427_p2); sensitive << ( ap_phi_mux_i1_phi_fu_283_p4 ); SC_METHOD(thread_indvar2_fu_416_p1); sensitive << ( indvar1_reg_268_pp1_iter1_reg ); SC_METHOD(thread_indvar_next1_fu_410_p2); sensitive << ( ap_phi_mux_indvar1_phi_fu_272_p4 ); SC_METHOD(thread_indvar_next_fu_351_p2); sensitive << ( indvar_reg_257 ); SC_METHOD(thread_reload_1_fu_367_p3); sensitive << ( reload_reg_245 ); sensitive << ( tmp_10_reg_509_pp0_iter1_reg ); sensitive << ( fir_ctrl_0_reg_515 ); SC_METHOD(thread_shift_reg_address0); sensitive << ( ap_CS_fsm_state30 ); sensitive << ( ap_CS_fsm_pp2_stage1 ); sensitive << ( ap_enable_reg_pp2_iter0 ); sensitive << ( ap_CS_fsm_pp2_stage0 ); sensitive << ( tmp_7_reg_574 ); sensitive << ( ap_block_pp2_stage0 ); sensitive << ( tmp_6_fu_433_p1 ); sensitive << ( ap_block_pp2_stage1 ); SC_METHOD(thread_shift_reg_ce0); sensitive << ( x_data_0_vld_out ); sensitive << ( ap_CS_fsm_state30 ); sensitive << ( ap_CS_fsm_pp2_stage1 ); sensitive << ( ap_enable_reg_pp2_iter0 ); sensitive << ( ap_block_pp2_stage1_11001 ); sensitive << ( ap_CS_fsm_pp2_stage0 ); sensitive << ( ap_block_pp2_stage0_11001 ); SC_METHOD(thread_shift_reg_d0); sensitive << ( x_data_0_data_out ); sensitive << ( shift_reg_q0 ); sensitive << ( ap_CS_fsm_state30 ); sensitive << ( ap_CS_fsm_pp2_stage1 ); sensitive << ( ap_enable_reg_pp2_iter0 ); sensitive << ( ap_block_pp2_stage1 ); SC_METHOD(thread_shift_reg_we0); sensitive << ( x_data_0_vld_out ); sensitive << ( ap_CS_fsm_state30 ); sensitive << ( ap_CS_fsm_pp2_stage1 ); sensitive << ( ap_enable_reg_pp2_iter0 ); sensitive << ( ap_block_pp2_stage1_11001 ); sensitive << ( tmp_2_reg_560 ); SC_METHOD(thread_tmp_10_fu_357_p1); sensitive << ( indvar_reg_257 ); SC_METHOD(thread_tmp_12_fu_379_p2); sensitive << ( i_reg_233 ); SC_METHOD(thread_tmp_1_fu_385_p2); sensitive << ( tmp_12_fu_379_p2 ); SC_METHOD(thread_tmp_2_fu_421_p2); sensitive << ( ap_enable_reg_pp2_iter0 ); sensitive << ( ap_CS_fsm_pp2_stage0 ); sensitive << ( ap_block_pp2_stage0_11001 ); sensitive << ( ap_phi_mux_i1_phi_fu_283_p4 ); SC_METHOD(thread_tmp_3_fu_466_p1); sensitive << ( x_data_0_data_out ); sensitive << ( ap_CS_fsm_state30 ); SC_METHOD(thread_tmp_3_fu_466_p2); sensitive << ( reg_302 ); sensitive << ( tmp_3_fu_466_p1 ); SC_METHOD(thread_tmp_5_fu_326_p1); sensitive << ( ctrl3_reg_478 ); SC_METHOD(thread_tmp_6_fu_433_p1); sensitive << ( i_1_fu_427_p2 ); SC_METHOD(thread_tmp_7_fu_438_p1); sensitive << ( ap_phi_mux_i1_phi_fu_283_p4 ); SC_METHOD(thread_tmp_8_fu_443_p2); sensitive << ( reg_302 ); sensitive << ( shift_reg_load_reg_584 ); SC_METHOD(thread_tmp_9_fu_336_p1); sensitive << ( coe1_reg_483 ); SC_METHOD(thread_tmp_fu_373_p2); sensitive << ( reload_reg_245 ); sensitive << ( ap_CS_fsm_state12 ); SC_METHOD(thread_tmp_s_fu_401_p1); sensitive << ( p_add7_i32_shr_reg_535 ); SC_METHOD(thread_x_TDATA_blk_n); sensitive << ( x_data_0_state ); sensitive << ( ap_CS_fsm_state30 ); SC_METHOD(thread_x_TREADY); sensitive << ( x_last_V_0_state ); SC_METHOD(thread_x_data_0_ack_in); sensitive << ( x_data_0_state ); SC_METHOD(thread_x_data_0_ack_out); sensitive << ( x_data_0_vld_out ); sensitive << ( ap_CS_fsm_state30 ); SC_METHOD(thread_x_data_0_data_out); sensitive << ( x_data_0_payload_A ); sensitive << ( x_data_0_payload_B ); sensitive << ( x_data_0_sel ); SC_METHOD(thread_x_data_0_load_A); sensitive << ( x_data_0_sel_wr ); sensitive << ( x_data_0_state_cmp_full ); SC_METHOD(thread_x_data_0_load_B); sensitive << ( x_data_0_sel_wr ); sensitive << ( x_data_0_state_cmp_full ); SC_METHOD(thread_x_data_0_sel); sensitive << ( x_data_0_sel_rd ); SC_METHOD(thread_x_data_0_state_cmp_full); sensitive << ( x_data_0_state ); SC_METHOD(thread_x_data_0_vld_in); sensitive << ( x_TVALID ); SC_METHOD(thread_x_data_0_vld_out); sensitive << ( x_data_0_state ); SC_METHOD(thread_x_last_V_0_ack_in); sensitive << ( x_last_V_0_state ); SC_METHOD(thread_x_last_V_0_ack_out); sensitive << ( x_data_0_vld_out ); sensitive << ( ap_CS_fsm_state30 ); SC_METHOD(thread_x_last_V_0_data_out); sensitive << ( x_last_V_0_payload_A ); sensitive << ( x_last_V_0_payload_B ); sensitive << ( x_last_V_0_sel ); SC_METHOD(thread_x_last_V_0_load_A); sensitive << ( x_last_V_0_sel_wr ); sensitive << ( x_last_V_0_state_cmp_full ); SC_METHOD(thread_x_last_V_0_load_B); sensitive << ( x_last_V_0_sel_wr ); sensitive << ( x_last_V_0_state_cmp_full ); SC_METHOD(thread_x_last_V_0_sel); sensitive << ( x_last_V_0_sel_rd ); SC_METHOD(thread_x_last_V_0_state_cmp_full); sensitive << ( x_last_V_0_state ); SC_METHOD(thread_x_last_V_0_vld_in); sensitive << ( x_TVALID ); SC_METHOD(thread_x_last_V_0_vld_out); sensitive << ( x_last_V_0_state ); SC_METHOD(thread_x_user_V_0_ack_in); sensitive << ( x_user_V_0_state ); SC_METHOD(thread_x_user_V_0_ack_out); sensitive << ( x_data_0_vld_out ); sensitive << ( ap_CS_fsm_state30 ); SC_METHOD(thread_x_user_V_0_data_out); sensitive << ( x_user_V_0_payload_A ); sensitive << ( x_user_V_0_payload_B ); sensitive << ( x_user_V_0_sel ); SC_METHOD(thread_x_user_V_0_load_A); sensitive << ( x_user_V_0_sel_wr ); sensitive << ( x_user_V_0_state_cmp_full ); SC_METHOD(thread_x_user_V_0_load_B); sensitive << ( x_user_V_0_sel_wr ); sensitive << ( x_user_V_0_state_cmp_full ); SC_METHOD(thread_x_user_V_0_sel); sensitive << ( x_user_V_0_sel_rd ); SC_METHOD(thread_x_user_V_0_state_cmp_full); sensitive << ( x_user_V_0_state ); SC_METHOD(thread_x_user_V_0_vld_in); sensitive << ( x_TVALID ); SC_METHOD(thread_x_user_V_0_vld_out); sensitive << ( x_user_V_0_state ); SC_METHOD(thread_y_TDATA); sensitive << ( y_data_1_data_out ); SC_METHOD(thread_y_TDATA_blk_n); sensitive << ( y_data_1_state ); sensitive << ( ap_CS_fsm_state31 ); sensitive << ( ap_CS_fsm_state32 ); SC_METHOD(thread_y_TLAST); sensitive << ( y_last_V_1_data_out ); SC_METHOD(thread_y_TUSER); sensitive << ( y_user_V_1_data_out ); SC_METHOD(thread_y_TVALID); sensitive << ( y_last_V_1_state ); SC_METHOD(thread_y_data_1_ack_in); sensitive << ( y_data_1_state ); SC_METHOD(thread_y_data_1_ack_out); sensitive << ( y_TREADY ); SC_METHOD(thread_y_data_1_data_out); sensitive << ( y_data_1_payload_A ); sensitive << ( y_data_1_payload_B ); sensitive << ( y_data_1_sel ); SC_METHOD(thread_y_data_1_load_A); sensitive << ( y_data_1_sel_wr ); sensitive << ( y_data_1_state_cmp_full ); SC_METHOD(thread_y_data_1_load_B); sensitive << ( y_data_1_sel_wr ); sensitive << ( y_data_1_state_cmp_full ); SC_METHOD(thread_y_data_1_sel); sensitive << ( y_data_1_sel_rd ); SC_METHOD(thread_y_data_1_state_cmp_full); sensitive << ( y_data_1_state ); SC_METHOD(thread_y_data_1_vld_in); sensitive << ( y_data_1_ack_in ); sensitive << ( ap_CS_fsm_state31 ); SC_METHOD(thread_y_data_1_vld_out); sensitive << ( y_data_1_state ); SC_METHOD(thread_y_last_V_1_ack_in); sensitive << ( y_last_V_1_state ); SC_METHOD(thread_y_last_V_1_ack_out); sensitive << ( y_TREADY ); SC_METHOD(thread_y_last_V_1_data_out); sensitive << ( y_last_V_1_payload_A ); sensitive << ( y_last_V_1_payload_B ); sensitive << ( y_last_V_1_sel ); SC_METHOD(thread_y_last_V_1_load_A); sensitive << ( y_last_V_1_sel_wr ); sensitive << ( y_last_V_1_state_cmp_full ); SC_METHOD(thread_y_last_V_1_load_B); sensitive << ( y_last_V_1_sel_wr ); sensitive << ( y_last_V_1_state_cmp_full ); SC_METHOD(thread_y_last_V_1_sel); sensitive << ( y_last_V_1_sel_rd ); SC_METHOD(thread_y_last_V_1_state_cmp_full); sensitive << ( y_last_V_1_state ); SC_METHOD(thread_y_last_V_1_vld_in); sensitive << ( y_data_1_ack_in ); sensitive << ( ap_CS_fsm_state31 ); SC_METHOD(thread_y_last_V_1_vld_out); sensitive << ( y_last_V_1_state ); SC_METHOD(thread_y_user_V_1_ack_in); sensitive << ( y_user_V_1_state ); SC_METHOD(thread_y_user_V_1_ack_out); sensitive << ( y_TREADY ); SC_METHOD(thread_y_user_V_1_data_out); sensitive << ( y_user_V_1_payload_A ); sensitive << ( y_user_V_1_payload_B ); sensitive << ( y_user_V_1_sel ); SC_METHOD(thread_y_user_V_1_load_A); sensitive << ( y_user_V_1_sel_wr ); sensitive << ( y_user_V_1_state_cmp_full ); SC_METHOD(thread_y_user_V_1_load_B); sensitive << ( y_user_V_1_sel_wr ); sensitive << ( y_user_V_1_state_cmp_full ); SC_METHOD(thread_y_user_V_1_sel); sensitive << ( y_user_V_1_sel_rd ); SC_METHOD(thread_y_user_V_1_state_cmp_full); sensitive << ( y_user_V_1_state ); SC_METHOD(thread_y_user_V_1_vld_in); sensitive << ( y_data_1_ack_in ); sensitive << ( ap_CS_fsm_state31 ); SC_METHOD(thread_y_user_V_1_vld_out); sensitive << ( y_user_V_1_state ); SC_METHOD(thread_ap_NS_fsm); sensitive << ( ap_start ); sensitive << ( ap_CS_fsm ); sensitive << ( ap_CS_fsm_state1 ); sensitive << ( y_data_1_ack_in ); sensitive << ( y_data_1_state ); sensitive << ( y_user_V_1_ack_in ); sensitive << ( y_user_V_1_state ); sensitive << ( y_last_V_1_ack_in ); sensitive << ( y_last_V_1_state ); sensitive << ( x_data_0_vld_out ); sensitive << ( ap_CS_fsm_state2 ); sensitive << ( ap_enable_reg_pp0_iter1 ); sensitive << ( ap_CS_fsm_state13 ); sensitive << ( ap_enable_reg_pp1_iter1 ); sensitive << ( ap_CS_fsm_state31 ); sensitive << ( ap_CS_fsm_state32 ); sensitive << ( ap_CS_fsm_state30 ); sensitive << ( ap_CS_fsm_pp2_stage1 ); sensitive << ( ap_enable_reg_pp2_iter0 ); sensitive << ( ap_sig_ioackin_gmem_ARREADY ); sensitive << ( exitcond_fu_345_p2 ); sensitive << ( ap_enable_reg_pp0_iter0 ); sensitive << ( ap_enable_reg_pp0_iter2 ); sensitive << ( tmp_fu_373_p2 ); sensitive << ( ap_CS_fsm_state12 ); sensitive << ( exitcond1_fu_405_p2 ); sensitive << ( ap_enable_reg_pp1_iter0 ); sensitive << ( tmp_2_fu_421_p2 ); sensitive << ( ap_enable_reg_pp2_iter1 ); sensitive << ( ap_block_pp0_stage0_subdone ); sensitive << ( ap_block_pp1_stage0_subdone ); sensitive << ( ap_enable_reg_pp1_iter2 ); sensitive << ( ap_block_pp2_stage0_subdone ); sensitive << ( ap_block_pp2_stage1_subdone ); SC_THREAD(thread_hdltv_gen); sensitive << ( ap_clk.pos() ); SC_THREAD(thread_ap_var_for_const0); SC_THREAD(thread_ap_var_for_const5); SC_THREAD(thread_ap_var_for_const6); SC_THREAD(thread_ap_var_for_const1); SC_THREAD(thread_ap_var_for_const3); SC_THREAD(thread_ap_var_for_const2); SC_THREAD(thread_ap_var_for_const4); ap_CS_fsm = "00000000000000000000000001"; y_data_1_sel_rd = SC_LOGIC_0; y_data_1_sel_wr = SC_LOGIC_0; y_data_1_state = "00"; y_user_V_1_sel_rd = SC_LOGIC_0; y_user_V_1_sel_wr = SC_LOGIC_0; y_user_V_1_state = "00"; y_last_V_1_sel_rd = SC_LOGIC_0; y_last_V_1_sel_wr = SC_LOGIC_0; y_last_V_1_state = "00"; x_data_0_sel_rd = SC_LOGIC_0; x_data_0_sel_wr = SC_LOGIC_0; x_data_0_state = "00"; x_user_V_0_sel_rd = SC_LOGIC_0; x_user_V_0_sel_wr = SC_LOGIC_0; x_user_V_0_state = "00"; x_last_V_0_sel_rd = SC_LOGIC_0; x_last_V_0_sel_wr = SC_LOGIC_0; x_last_V_0_state = "00"; ap_enable_reg_pp0_iter1 = SC_LOGIC_0; ap_enable_reg_pp1_iter1 = SC_LOGIC_0; ap_enable_reg_pp2_iter0 = SC_LOGIC_0; ap_enable_reg_pp0_iter0 = SC_LOGIC_0; ap_enable_reg_pp0_iter2 = SC_LOGIC_0; ap_enable_reg_pp1_iter0 = SC_LOGIC_0; ap_enable_reg_pp2_iter1 = SC_LOGIC_0; ap_enable_reg_pp1_iter2 = SC_LOGIC_0; ap_reg_ioackin_gmem_ARREADY = SC_LOGIC_0; static int apTFileNum = 0; stringstream apTFilenSS; apTFilenSS << "x_order_fir_sc_trace_" << apTFileNum ++; string apTFn = apTFilenSS.str(); mVcdFile = sc_create_vcd_trace_file(apTFn.c_str()); mVcdFile->set_time_unit(1, SC_PS); if (1) { #ifdef __HLS_TRACE_LEVEL_PORT__ sc_trace(mVcdFile, ap_clk, "(port)ap_clk"); sc_trace(mVcdFile, ap_rst_n, "(port)ap_rst_n"); sc_trace(mVcdFile, m_axi_gmem_AWVALID, "(port)m_axi_gmem_AWVALID"); sc_trace(mVcdFile, m_axi_gmem_AWREADY, "(port)m_axi_gmem_AWREADY"); sc_trace(mVcdFile, m_axi_gmem_AWADDR, "(port)m_axi_gmem_AWADDR"); sc_trace(mVcdFile, m_axi_gmem_AWID, "(port)m_axi_gmem_AWID"); sc_trace(mVcdFile, m_axi_gmem_AWLEN, "(port)m_axi_gmem_AWLEN"); sc_trace(mVcdFile, m_axi_gmem_AWSIZE, "(port)m_axi_gmem_AWSIZE"); sc_trace(mVcdFile, m_axi_gmem_AWBURST, "(port)m_axi_gmem_AWBURST"); sc_trace(mVcdFile, m_axi_gmem_AWLOCK, "(port)m_axi_gmem_AWLOCK"); sc_trace(mVcdFile, m_axi_gmem_AWCACHE, "(port)m_axi_gmem_AWCACHE"); sc_trace(mVcdFile, m_axi_gmem_AWPROT, "(port)m_axi_gmem_AWPROT"); sc_trace(mVcdFile, m_axi_gmem_AWQOS, "(port)m_axi_gmem_AWQOS"); sc_trace(mVcdFile, m_axi_gmem_AWREGION, "(port)m_axi_gmem_AWREGION"); sc_trace(mVcdFile, m_axi_gmem_AWUSER, "(port)m_axi_gmem_AWUSER"); sc_trace(mVcdFile, m_axi_gmem_WVALID, "(port)m_axi_gmem_WVALID"); sc_trace(mVcdFile, m_axi_gmem_WREADY, "(port)m_axi_gmem_WREADY"); sc_trace(mVcdFile, m_axi_gmem_WDATA, "(port)m_axi_gmem_WDATA"); sc_trace(mVcdFile, m_axi_gmem_WSTRB, "(port)m_axi_gmem_WSTRB"); sc_trace(mVcdFile, m_axi_gmem_WLAST, "(port)m_axi_gmem_WLAST"); sc_trace(mVcdFile, m_axi_gmem_WID, "(port)m_axi_gmem_WID"); sc_trace(mVcdFile, m_axi_gmem_WUSER, "(port)m_axi_gmem_WUSER"); sc_trace(mVcdFile, m_axi_gmem_ARVALID, "(port)m_axi_gmem_ARVALID"); sc_trace(mVcdFile, m_axi_gmem_ARREADY, "(port)m_axi_gmem_ARREADY"); sc_trace(mVcdFile, m_axi_gmem_ARADDR, "(port)m_axi_gmem_ARADDR"); sc_trace(mVcdFile, m_axi_gmem_ARID, "(port)m_axi_gmem_ARID"); sc_trace(mVcdFile, m_axi_gmem_ARLEN, "(port)m_axi_gmem_ARLEN"); sc_trace(mVcdFile, m_axi_gmem_ARSIZE, "(port)m_axi_gmem_ARSIZE"); sc_trace(mVcdFile, m_axi_gmem_ARBURST, "(port)m_axi_gmem_ARBURST"); sc_trace(mVcdFile, m_axi_gmem_ARLOCK, "(port)m_axi_gmem_ARLOCK"); sc_trace(mVcdFile, m_axi_gmem_ARCACHE, "(port)m_axi_gmem_ARCACHE"); sc_trace(mVcdFile, m_axi_gmem_ARPROT, "(port)m_axi_gmem_ARPROT"); sc_trace(mVcdFile, m_axi_gmem_ARQOS, "(port)m_axi_gmem_ARQOS"); sc_trace(mVcdFile, m_axi_gmem_ARREGION, "(port)m_axi_gmem_ARREGION"); sc_trace(mVcdFile, m_axi_gmem_ARUSER, "(port)m_axi_gmem_ARUSER"); sc_trace(mVcdFile, m_axi_gmem_RVALID, "(port)m_axi_gmem_RVALID"); sc_trace(mVcdFile, m_axi_gmem_RREADY, "(port)m_axi_gmem_RREADY"); sc_trace(mVcdFile, m_axi_gmem_RDATA, "(port)m_axi_gmem_RDATA"); sc_trace(mVcdFile, m_axi_gmem_RLAST, "(port)m_axi_gmem_RLAST"); sc_trace(mVcdFile, m_axi_gmem_RID, "(port)m_axi_gmem_RID"); sc_trace(mVcdFile, m_axi_gmem_RUSER, "(port)m_axi_gmem_RUSER"); sc_trace(mVcdFile, m_axi_gmem_RRESP, "(port)m_axi_gmem_RRESP"); sc_trace(mVcdFile, m_axi_gmem_BVALID, "(port)m_axi_gmem_BVALID"); sc_trace(mVcdFile, m_axi_gmem_BREADY, "(port)m_axi_gmem_BREADY"); sc_trace(mVcdFile, m_axi_gmem_BRESP, "(port)m_axi_gmem_BRESP"); sc_trace(mVcdFile, m_axi_gmem_BID, "(port)m_axi_gmem_BID"); sc_trace(mVcdFile, m_axi_gmem_BUSER, "(port)m_axi_gmem_BUSER"); sc_trace(mVcdFile, y_TDATA, "(port)y_TDATA"); sc_trace(mVcdFile, y_TVALID, "(port)y_TVALID"); sc_trace(mVcdFile, y_TREADY, "(port)y_TREADY"); sc_trace(mVcdFile, y_TUSER, "(port)y_TUSER"); sc_trace(mVcdFile, y_TLAST, "(port)y_TLAST"); sc_trace(mVcdFile, x_TDATA, "(port)x_TDATA"); sc_trace(mVcdFile, x_TVALID, "(port)x_TVALID"); sc_trace(mVcdFile, x_TREADY, "(port)x_TREADY"); sc_trace(mVcdFile, x_TUSER, "(port)x_TUSER"); sc_trace(mVcdFile, x_TLAST, "(port)x_TLAST"); sc_trace(mVcdFile, s_axi_AXILiteS_AWVALID, "(port)s_axi_AXILiteS_AWVALID"); sc_trace(mVcdFile, s_axi_AXILiteS_AWREADY, "(port)s_axi_AXILiteS_AWREADY"); sc_trace(mVcdFile, s_axi_AXILiteS_AWADDR, "(port)s_axi_AXILiteS_AWADDR"); sc_trace(mVcdFile, s_axi_AXILiteS_WVALID, "(port)s_axi_AXILiteS_WVALID"); sc_trace(mVcdFile, s_axi_AXILiteS_WREADY, "(port)s_axi_AXILiteS_WREADY"); sc_trace(mVcdFile, s_axi_AXILiteS_WDATA, "(port)s_axi_AXILiteS_WDATA"); sc_trace(mVcdFile, s_axi_AXILiteS_WSTRB, "(port)s_axi_AXILiteS_WSTRB"); sc_trace(mVcdFile, s_axi_AXILiteS_ARVALID, "(port)s_axi_AXILiteS_ARVALID"); sc_trace(mVcdFile, s_axi_AXILiteS_ARREADY, "(port)s_axi_AXILiteS_ARREADY"); sc_trace(mVcdFile, s_axi_AXILiteS_ARADDR, "(port)s_axi_AXILiteS_ARADDR"); sc_trace(mVcdFile, s_axi_AXILiteS_RVALID, "(port)s_axi_AXILiteS_RVALID"); sc_trace(mVcdFile, s_axi_AXILiteS_RREADY, "(port)s_axi_AXILiteS_RREADY"); sc_trace(mVcdFile, s_axi_AXILiteS_RDATA, "(port)s_axi_AXILiteS_RDATA"); sc_trace(mVcdFile, s_axi_AXILiteS_RRESP, "(port)s_axi_AXILiteS_RRESP"); sc_trace(mVcdFile, s_axi_AXILiteS_BVALID, "(port)s_axi_AXILiteS_BVALID"); sc_trace(mVcdFile, s_axi_AXILiteS_BREADY, "(port)s_axi_AXILiteS_BREADY"); sc_trace(mVcdFile, s_axi_AXILiteS_BRESP, "(port)s_axi_AXILiteS_BRESP"); sc_trace(mVcdFile, interrupt, "(port)interrupt"); #endif #ifdef __HLS_TRACE_LEVEL_INT__ sc_trace(mVcdFile, ap_rst_n_inv, "ap_rst_n_inv"); sc_trace(mVcdFile, ap_start, "ap_start"); sc_trace(mVcdFile, ap_done, "ap_done"); sc_trace(mVcdFile, ap_idle, "ap_idle"); sc_trace(mVcdFile, ap_CS_fsm, "ap_CS_fsm"); sc_trace(mVcdFile, ap_CS_fsm_state1, "ap_CS_fsm_state1"); sc_trace(mVcdFile, ap_ready, "ap_ready"); sc_trace(mVcdFile, y_data_1_data_out, "y_data_1_data_out"); sc_trace(mVcdFile, y_data_1_vld_in, "y_data_1_vld_in"); sc_trace(mVcdFile, y_data_1_vld_out, "y_data_1_vld_out"); sc_trace(mVcdFile, y_data_1_ack_in, "y_data_1_ack_in"); sc_trace(mVcdFile, y_data_1_ack_out, "y_data_1_ack_out"); sc_trace(mVcdFile, y_data_1_payload_A, "y_data_1_payload_A"); sc_trace(mVcdFile, y_data_1_payload_B, "y_data_1_payload_B"); sc_trace(mVcdFile, y_data_1_sel_rd, "y_data_1_sel_rd"); sc_trace(mVcdFile, y_data_1_sel_wr, "y_data_1_sel_wr"); sc_trace(mVcdFile, y_data_1_sel, "y_data_1_sel"); sc_trace(mVcdFile, y_data_1_load_A, "y_data_1_load_A"); sc_trace(mVcdFile, y_data_1_load_B, "y_data_1_load_B"); sc_trace(mVcdFile, y_data_1_state, "y_data_1_state"); sc_trace(mVcdFile, y_data_1_state_cmp_full, "y_data_1_state_cmp_full"); sc_trace(mVcdFile, y_user_V_1_data_out, "y_user_V_1_data_out"); sc_trace(mVcdFile, y_user_V_1_vld_in, "y_user_V_1_vld_in"); sc_trace(mVcdFile, y_user_V_1_vld_out, "y_user_V_1_vld_out"); sc_trace(mVcdFile, y_user_V_1_ack_in, "y_user_V_1_ack_in"); sc_trace(mVcdFile, y_user_V_1_ack_out, "y_user_V_1_ack_out"); sc_trace(mVcdFile, y_user_V_1_payload_A, "y_user_V_1_payload_A"); sc_trace(mVcdFile, y_user_V_1_payload_B, "y_user_V_1_payload_B"); sc_trace(mVcdFile, y_user_V_1_sel_rd, "y_user_V_1_sel_rd"); sc_trace(mVcdFile, y_user_V_1_sel_wr, "y_user_V_1_sel_wr"); sc_trace(mVcdFile, y_user_V_1_sel, "y_user_V_1_sel"); sc_trace(mVcdFile, y_user_V_1_load_A, "y_user_V_1_load_A"); sc_trace(mVcdFile, y_user_V_1_load_B, "y_user_V_1_load_B"); sc_trace(mVcdFile, y_user_V_1_state, "y_user_V_1_state"); sc_trace(mVcdFile, y_user_V_1_state_cmp_full, "y_user_V_1_state_cmp_full"); sc_trace(mVcdFile, y_last_V_1_data_out, "y_last_V_1_data_out"); sc_trace(mVcdFile, y_last_V_1_vld_in, "y_last_V_1_vld_in"); sc_trace(mVcdFile, y_last_V_1_vld_out, "y_last_V_1_vld_out"); sc_trace(mVcdFile, y_last_V_1_ack_in, "y_last_V_1_ack_in"); sc_trace(mVcdFile, y_last_V_1_ack_out, "y_last_V_1_ack_out"); sc_trace(mVcdFile, y_last_V_1_payload_A, "y_last_V_1_payload_A"); sc_trace(mVcdFile, y_last_V_1_payload_B, "y_last_V_1_payload_B"); sc_trace(mVcdFile, y_last_V_1_sel_rd, "y_last_V_1_sel_rd"); sc_trace(mVcdFile, y_last_V_1_sel_wr, "y_last_V_1_sel_wr"); sc_trace(mVcdFile, y_last_V_1_sel, "y_last_V_1_sel"); sc_trace(mVcdFile, y_last_V_1_load_A, "y_last_V_1_load_A"); sc_trace(mVcdFile, y_last_V_1_load_B, "y_last_V_1_load_B"); sc_trace(mVcdFile, y_last_V_1_state, "y_last_V_1_state"); sc_trace(mVcdFile, y_last_V_1_state_cmp_full, "y_last_V_1_state_cmp_full"); sc_trace(mVcdFile, x_data_0_data_out, "x_data_0_data_out"); sc_trace(mVcdFile, x_data_0_vld_in, "x_data_0_vld_in"); sc_trace(mVcdFile, x_data_0_vld_out, "x_data_0_vld_out"); sc_trace(mVcdFile, x_data_0_ack_in, "x_data_0_ack_in"); sc_trace(mVcdFile, x_data_0_ack_out, "x_data_0_ack_out"); sc_trace(mVcdFile, x_data_0_payload_A, "x_data_0_payload_A"); sc_trace(mVcdFile, x_data_0_payload_B, "x_data_0_payload_B"); sc_trace(mVcdFile, x_data_0_sel_rd, "x_data_0_sel_rd"); sc_trace(mVcdFile, x_data_0_sel_wr, "x_data_0_sel_wr"); sc_trace(mVcdFile, x_data_0_sel, "x_data_0_sel"); sc_trace(mVcdFile, x_data_0_load_A, "x_data_0_load_A"); sc_trace(mVcdFile, x_data_0_load_B, "x_data_0_load_B"); sc_trace(mVcdFile, x_data_0_state, "x_data_0_state"); sc_trace(mVcdFile, x_data_0_state_cmp_full, "x_data_0_state_cmp_full"); sc_trace(mVcdFile, x_user_V_0_data_out, "x_user_V_0_data_out"); sc_trace(mVcdFile, x_user_V_0_vld_in, "x_user_V_0_vld_in"); sc_trace(mVcdFile, x_user_V_0_vld_out, "x_user_V_0_vld_out"); sc_trace(mVcdFile, x_user_V_0_ack_in, "x_user_V_0_ack_in"); sc_trace(mVcdFile, x_user_V_0_ack_out, "x_user_V_0_ack_out"); sc_trace(mVcdFile, x_user_V_0_payload_A, "x_user_V_0_payload_A"); sc_trace(mVcdFile, x_user_V_0_payload_B, "x_user_V_0_payload_B"); sc_trace(mVcdFile, x_user_V_0_sel_rd, "x_user_V_0_sel_rd"); sc_trace(mVcdFile, x_user_V_0_sel_wr, "x_user_V_0_sel_wr"); sc_trace(mVcdFile, x_user_V_0_sel, "x_user_V_0_sel"); sc_trace(mVcdFile, x_user_V_0_load_A, "x_user_V_0_load_A"); sc_trace(mVcdFile, x_user_V_0_load_B, "x_user_V_0_load_B"); sc_trace(mVcdFile, x_user_V_0_state, "x_user_V_0_state"); sc_trace(mVcdFile, x_user_V_0_state_cmp_full, "x_user_V_0_state_cmp_full"); sc_trace(mVcdFile, x_last_V_0_data_out, "x_last_V_0_data_out"); sc_trace(mVcdFile, x_last_V_0_vld_in, "x_last_V_0_vld_in"); sc_trace(mVcdFile, x_last_V_0_vld_out, "x_last_V_0_vld_out"); sc_trace(mVcdFile, x_last_V_0_ack_in, "x_last_V_0_ack_in"); sc_trace(mVcdFile, x_last_V_0_ack_out, "x_last_V_0_ack_out"); sc_trace(mVcdFile, x_last_V_0_payload_A, "x_last_V_0_payload_A"); sc_trace(mVcdFile, x_last_V_0_payload_B, "x_last_V_0_payload_B"); sc_trace(mVcdFile, x_last_V_0_sel_rd, "x_last_V_0_sel_rd"); sc_trace(mVcdFile, x_last_V_0_sel_wr, "x_last_V_0_sel_wr"); sc_trace(mVcdFile, x_last_V_0_sel, "x_last_V_0_sel"); sc_trace(mVcdFile, x_last_V_0_load_A, "x_last_V_0_load_A"); sc_trace(mVcdFile, x_last_V_0_load_B, "x_last_V_0_load_B"); sc_trace(mVcdFile, x_last_V_0_state, "x_last_V_0_state"); sc_trace(mVcdFile, x_last_V_0_state_cmp_full, "x_last_V_0_state_cmp_full"); sc_trace(mVcdFile, coe, "coe"); sc_trace(mVcdFile, ctrl, "ctrl"); sc_trace(mVcdFile, coef_address0, "coef_address0"); sc_trace(mVcdFile, coef_ce0, "coef_ce0"); sc_trace(mVcdFile, coef_we0, "coef_we0"); sc_trace(mVcdFile, coef_q0, "coef_q0"); sc_trace(mVcdFile, shift_reg_address0, "shift_reg_address0"); sc_trace(mVcdFile, shift_reg_ce0, "shift_reg_ce0"); sc_trace(mVcdFile, shift_reg_we0, "shift_reg_we0"); sc_trace(mVcdFile, shift_reg_d0, "shift_reg_d0"); sc_trace(mVcdFile, shift_reg_q0, "shift_reg_q0"); sc_trace(mVcdFile, gmem_blk_n_AR, "gmem_blk_n_AR"); sc_trace(mVcdFile, ap_CS_fsm_state2, "ap_CS_fsm_state2"); sc_trace(mVcdFile, gmem_blk_n_R, "gmem_blk_n_R"); sc_trace(mVcdFile, ap_CS_fsm_pp0_stage0, "ap_CS_fsm_pp0_stage0"); sc_trace(mVcdFile, ap_enable_reg_pp0_iter1, "ap_enable_reg_pp0_iter1"); sc_trace(mVcdFile, ap_block_pp0_stage0, "ap_block_pp0_stage0"); sc_trace(mVcdFile, exitcond_reg_500, "exitcond_reg_500"); sc_trace(mVcdFile, ap_CS_fsm_state13, "ap_CS_fsm_state13"); sc_trace(mVcdFile, ap_CS_fsm_pp1_stage0, "ap_CS_fsm_pp1_stage0"); sc_trace(mVcdFile, ap_enable_reg_pp1_iter1, "ap_enable_reg_pp1_iter1"); sc_trace(mVcdFile, ap_block_pp1_stage0, "ap_block_pp1_stage0"); sc_trace(mVcdFile, exitcond1_reg_546, "exitcond1_reg_546"); sc_trace(mVcdFile, y_TDATA_blk_n, "y_TDATA_blk_n"); sc_trace(mVcdFile, ap_CS_fsm_state31, "ap_CS_fsm_state31"); sc_trace(mVcdFile, ap_CS_fsm_state32, "ap_CS_fsm_state32"); sc_trace(mVcdFile, x_TDATA_blk_n, "x_TDATA_blk_n"); sc_trace(mVcdFile, ap_CS_fsm_state30, "ap_CS_fsm_state30"); sc_trace(mVcdFile, gmem_AWREADY, "gmem_AWREADY"); sc_trace(mVcdFile, gmem_WREADY, "gmem_WREADY"); sc_trace(mVcdFile, gmem_ARVALID, "gmem_ARVALID"); sc_trace(mVcdFile, gmem_ARREADY, "gmem_ARREADY"); sc_trace(mVcdFile, gmem_ARADDR, "gmem_ARADDR"); sc_trace(mVcdFile, gmem_ARLEN, "gmem_ARLEN"); sc_trace(mVcdFile, gmem_RVALID, "gmem_RVALID"); sc_trace(mVcdFile, gmem_RREADY, "gmem_RREADY"); sc_trace(mVcdFile, gmem_RDATA, "gmem_RDATA"); sc_trace(mVcdFile, gmem_RLAST, "gmem_RLAST"); sc_trace(mVcdFile, gmem_RID, "gmem_RID"); sc_trace(mVcdFile, gmem_RUSER, "gmem_RUSER"); sc_trace(mVcdFile, gmem_RRESP, "gmem_RRESP"); sc_trace(mVcdFile, gmem_BVALID, "gmem_BVALID"); sc_trace(mVcdFile, gmem_BRESP, "gmem_BRESP"); sc_trace(mVcdFile, gmem_BID, "gmem_BID"); sc_trace(mVcdFile, gmem_BUSER, "gmem_BUSER"); sc_trace(mVcdFile, i_reg_233, "i_reg_233"); sc_trace(mVcdFile, reload_reg_245, "reload_reg_245"); sc_trace(mVcdFile, indvar_reg_257, "indvar_reg_257"); sc_trace(mVcdFile, indvar1_reg_268, "indvar1_reg_268"); sc_trace(mVcdFile, indvar1_reg_268_pp1_iter1_reg, "indvar1_reg_268_pp1_iter1_reg"); sc_trace(mVcdFile, ap_block_state20_pp1_stage0_iter0, "ap_block_state20_pp1_stage0_iter0"); sc_trace(mVcdFile, ap_block_state21_pp1_stage0_iter1, "ap_block_state21_pp1_stage0_iter1"); sc_trace(mVcdFile, ap_block_state22_pp1_stage0_iter2, "ap_block_state22_pp1_stage0_iter2"); sc_trace(mVcdFile, ap_block_pp1_stage0_11001, "ap_block_pp1_stage0_11001"); sc_trace(mVcdFile, i1_reg_280, "i1_reg_280"); sc_trace(mVcdFile, acc_reg_290, "acc_reg_290"); sc_trace(mVcdFile, reg_302, "reg_302"); sc_trace(mVcdFile, ap_CS_fsm_pp2_stage1, "ap_CS_fsm_pp2_stage1"); sc_trace(mVcdFile, ap_enable_reg_pp2_iter0, "ap_enable_reg_pp2_iter0"); sc_trace(mVcdFile, ap_block_state25_pp2_stage1_iter0, "ap_block_state25_pp2_stage1_iter0"); sc_trace(mVcdFile, ap_block_state27_pp2_stage1_iter1, "ap_block_state27_pp2_stage1_iter1"); sc_trace(mVcdFile, ap_block_pp2_stage1_11001, "ap_block_pp2_stage1_11001"); sc_trace(mVcdFile, tmp_2_reg_560, "tmp_2_reg_560"); sc_trace(mVcdFile, ap_CS_fsm_state29, "ap_CS_fsm_state29"); sc_trace(mVcdFile, ctrl3_reg_478, "ctrl3_reg_478"); sc_trace(mVcdFile, coe1_reg_483, "coe1_reg_483"); sc_trace(mVcdFile, ap_sig_ioackin_gmem_ARREADY, "ap_sig_ioackin_gmem_ARREADY"); sc_trace(mVcdFile, gmem_addr_1_reg_494, "gmem_addr_1_reg_494"); sc_trace(mVcdFile, ap_CS_fsm_state8, "ap_CS_fsm_state8"); sc_trace(mVcdFile, exitcond_fu_345_p2, "exitcond_fu_345_p2"); sc_trace(mVcdFile, ap_block_state9_pp0_stage0_iter0, "ap_block_state9_pp0_stage0_iter0"); sc_trace(mVcdFile, ap_block_state10_pp0_stage0_iter1, "ap_block_state10_pp0_stage0_iter1"); sc_trace(mVcdFile, ap_block_state11_pp0_stage0_iter2, "ap_block_state11_pp0_stage0_iter2"); sc_trace(mVcdFile, ap_block_pp0_stage0_11001, "ap_block_pp0_stage0_11001"); sc_trace(mVcdFile, exitcond_reg_500_pp0_iter1_reg, "exitcond_reg_500_pp0_iter1_reg"); sc_trace(mVcdFile, indvar_next_fu_351_p2, "indvar_next_fu_351_p2"); sc_trace(mVcdFile, ap_enable_reg_pp0_iter0, "ap_enable_reg_pp0_iter0"); sc_trace(mVcdFile, tmp_10_fu_357_p1, "tmp_10_fu_357_p1"); sc_trace(mVcdFile, tmp_10_reg_509, "tmp_10_reg_509"); sc_trace(mVcdFile, tmp_10_reg_509_pp0_iter1_reg, "tmp_10_reg_509_pp0_iter1_reg"); sc_trace(mVcdFile, fir_ctrl_0_reg_515, "fir_ctrl_0_reg_515"); sc_trace(mVcdFile, fir_ctrl_1_1_fu_361_p3, "fir_ctrl_1_1_fu_361_p3"); sc_trace(mVcdFile, ap_enable_reg_pp0_iter2, "ap_enable_reg_pp0_iter2"); sc_trace(mVcdFile, reload_1_fu_367_p3, "reload_1_fu_367_p3"); sc_trace(mVcdFile, tmp_fu_373_p2, "tmp_fu_373_p2"); sc_trace(mVcdFile, ap_CS_fsm_state12, "ap_CS_fsm_state12"); sc_trace(mVcdFile, p_add7_i32_shr_reg_535, "p_add7_i32_shr_reg_535"); sc_trace(mVcdFile, tmp_s_fu_401_p1, "tmp_s_fu_401_p1"); sc_trace(mVcdFile, exitcond1_fu_405_p2, "exitcond1_fu_405_p2"); sc_trace(mVcdFile, exitcond1_reg_546_pp1_iter1_reg, "exitcond1_reg_546_pp1_iter1_reg"); sc_trace(mVcdFile, indvar_next1_fu_410_p2, "indvar_next1_fu_410_p2"); sc_trace(mVcdFile, indvar_next1_reg_550, "indvar_next1_reg_550"); sc_trace(mVcdFile, ap_enable_reg_pp1_iter0, "ap_enable_reg_pp1_iter0"); sc_trace(mVcdFile, gmem_addr_1_read_reg_555, "gmem_addr_1_read_reg_555"); sc_trace(mVcdFile, tmp_2_fu_421_p2, "tmp_2_fu_421_p2"); sc_trace(mVcdFile, ap_CS_fsm_pp2_stage0, "ap_CS_fsm_pp2_stage0"); sc_trace(mVcdFile, ap_block_state24_pp2_stage0_iter0, "ap_block_state24_pp2_stage0_iter0"); sc_trace(mVcdFile, ap_block_state26_pp2_stage0_iter1, "ap_block_state26_pp2_stage0_iter1"); sc_trace(mVcdFile, ap_block_pp2_stage0_11001, "ap_block_pp2_stage0_11001"); sc_trace(mVcdFile, tmp_2_reg_560_pp2_iter1_reg, "tmp_2_reg_560_pp2_iter1_reg"); sc_trace(mVcdFile, i_1_fu_427_p2, "i_1_fu_427_p2"); sc_trace(mVcdFile, i_1_reg_564, "i_1_reg_564"); sc_trace(mVcdFile, tmp_7_fu_438_p1, "tmp_7_fu_438_p1"); sc_trace(mVcdFile, tmp_7_reg_574, "tmp_7_reg_574"); sc_trace(mVcdFile, shift_reg_load_reg_584, "shift_reg_load_reg_584"); sc_trace(mVcdFile, tmp_8_fu_443_p2, "tmp_8_fu_443_p2"); sc_trace(mVcdFile, tmp_8_reg_589, "tmp_8_reg_589"); sc_trace(mVcdFile, acc_2_fu_448_p2, "acc_2_fu_448_p2"); sc_trace(mVcdFile, ap_enable_reg_pp2_iter1, "ap_enable_reg_pp2_iter1"); sc_trace(mVcdFile, x_user_V_tmp_reg_599, "x_user_V_tmp_reg_599"); sc_trace(mVcdFile, x_last_V_tmp_reg_604, "x_last_V_tmp_reg_604"); sc_trace(mVcdFile, tmp_3_fu_466_p2, "tmp_3_fu_466_p2"); sc_trace(mVcdFile, tmp_3_reg_609, "tmp_3_reg_609"); sc_trace(mVcdFile, acc_1_fu_472_p2, "acc_1_fu_472_p2"); sc_trace(mVcdFile, ap_block_pp0_stage0_subdone, "ap_block_pp0_stage0_subdone"); sc_trace(mVcdFile, ap_condition_pp0_exit_iter0_state9, "ap_condition_pp0_exit_iter0_state9"); sc_trace(mVcdFile, ap_CS_fsm_state19, "ap_CS_fsm_state19"); sc_trace(mVcdFile, ap_block_pp1_stage0_subdone, "ap_block_pp1_stage0_subdone"); sc_trace(mVcdFile, ap_condition_pp1_exit_iter0_state20, "ap_condition_pp1_exit_iter0_state20"); sc_trace(mVcdFile, ap_enable_reg_pp1_iter2, "ap_enable_reg_pp1_iter2"); sc_trace(mVcdFile, ap_CS_fsm_state23, "ap_CS_fsm_state23"); sc_trace(mVcdFile, ap_block_pp2_stage0_subdone, "ap_block_pp2_stage0_subdone"); sc_trace(mVcdFile, ap_condition_pp2_exit_iter0_state24, "ap_condition_pp2_exit_iter0_state24"); sc_trace(mVcdFile, ap_block_pp2_stage1_subdone, "ap_block_pp2_stage1_subdone"); sc_trace(mVcdFile, ap_phi_mux_indvar1_phi_fu_272_p4, "ap_phi_mux_indvar1_phi_fu_272_p4"); sc_trace(mVcdFile, ap_phi_mux_i1_phi_fu_283_p4, "ap_phi_mux_i1_phi_fu_283_p4"); sc_trace(mVcdFile, ap_block_pp2_stage0, "ap_block_pp2_stage0"); sc_trace(mVcdFile, indvar2_fu_416_p1, "indvar2_fu_416_p1"); sc_trace(mVcdFile, tmp_6_fu_433_p1, "tmp_6_fu_433_p1"); sc_trace(mVcdFile, ap_block_pp2_stage1, "ap_block_pp2_stage1"); sc_trace(mVcdFile, tmp_5_fu_326_p1, "tmp_5_fu_326_p1"); sc_trace(mVcdFile, tmp_9_fu_336_p1, "tmp_9_fu_336_p1"); sc_trace(mVcdFile, ap_reg_ioackin_gmem_ARREADY, "ap_reg_ioackin_gmem_ARREADY"); sc_trace(mVcdFile, ap_CS_fsm_state28, "ap_CS_fsm_state28"); sc_trace(mVcdFile, tmp_12_fu_379_p2, "tmp_12_fu_379_p2"); sc_trace(mVcdFile, tmp_1_fu_385_p2, "tmp_1_fu_385_p2"); sc_trace(mVcdFile, tmp_3_fu_466_p1, "tmp_3_fu_466_p1"); sc_trace(mVcdFile, ap_block_state32, "ap_block_state32"); sc_trace(mVcdFile, ap_NS_fsm, "ap_NS_fsm"); sc_trace(mVcdFile, ap_idle_pp0, "ap_idle_pp0"); sc_trace(mVcdFile, ap_enable_pp0, "ap_enable_pp0"); sc_trace(mVcdFile, ap_idle_pp1, "ap_idle_pp1"); sc_trace(mVcdFile, ap_enable_pp1, "ap_enable_pp1"); sc_trace(mVcdFile, ap_idle_pp2, "ap_idle_pp2"); sc_trace(mVcdFile, ap_enable_pp2, "ap_enable_pp2"); #endif } mHdltvinHandle.open("x_order_fir.hdltvin.dat"); mHdltvoutHandle.open("x_order_fir.hdltvout.dat"); } x_order_fir::~x_order_fir() { if (mVcdFile) sc_close_vcd_trace_file(mVcdFile); mHdltvinHandle << "] " << endl; mHdltvoutHandle << "] " << endl; mHdltvinHandle.close(); mHdltvoutHandle.close(); delete coef_U; delete shift_reg_U; delete x_order_fir_AXILiteS_s_axi_U; delete x_order_fir_gmem_m_axi_U; } void x_order_fir::thread_ap_var_for_const0() { ap_var_for_const0 = ap_const_logic_1; } void x_order_fir::thread_ap_var_for_const5() { ap_var_for_const5 = ap_const_logic_0; } void x_order_fir::thread_ap_var_for_const6() { ap_var_for_const6 = ap_const_lv32_0; } void x_order_fir::thread_ap_var_for_const1() { ap_var_for_const1 = ap_const_lv1_0; } void x_order_fir::thread_ap_var_for_const3() { ap_var_for_const3 = ap_const_lv2_0; } void x_order_fir::thread_ap_var_for_const2() { ap_var_for_const2 = ap_const_lv3_0; } void x_order_fir::thread_ap_var_for_const4() { ap_var_for_const4 = ap_const_lv4_0; } void x_order_fir::thread_ap_clk_no_reset_() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage1.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage1_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter1.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, tmp_2_reg_560_pp2_iter1_reg.read()))) { acc_reg_290 = acc_2_fu_448_p2.read(); } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state23.read())) { acc_reg_290 = ap_const_lv32_0; } if ( ap_rst_n_inv.read() == ap_const_logic_1) { ap_CS_fsm = ap_ST_fsm_state1; } else { ap_CS_fsm = ap_NS_fsm.read(); } if ( ap_rst_n_inv.read() == ap_const_logic_1) { ap_enable_reg_pp0_iter0 = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_condition_pp0_exit_iter0_state9.read()))) { ap_enable_reg_pp0_iter0 = ap_const_logic_0; } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state8.read())) { ap_enable_reg_pp0_iter0 = ap_const_logic_1; } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { ap_enable_reg_pp0_iter1 = ap_const_logic_0; } else { if (esl_seteq<1,1,1>(ap_block_pp0_stage0_subdone.read(), ap_const_boolean_0)) { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_condition_pp0_exit_iter0_state9.read())) { ap_enable_reg_pp0_iter1 = (ap_condition_pp0_exit_iter0_state9.read() ^ ap_const_logic_1); } else if (esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1)) { ap_enable_reg_pp0_iter1 = ap_enable_reg_pp0_iter0.read(); } } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { ap_enable_reg_pp0_iter2 = ap_const_logic_0; } else { if (esl_seteq<1,1,1>(ap_block_pp0_stage0_subdone.read(), ap_const_boolean_0)) { ap_enable_reg_pp0_iter2 = ap_enable_reg_pp0_iter1.read(); } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state8.read())) { ap_enable_reg_pp0_iter2 = ap_const_logic_0; } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { ap_enable_reg_pp1_iter0 = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp1_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp1_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_condition_pp1_exit_iter0_state20.read()))) { ap_enable_reg_pp1_iter0 = ap_const_logic_0; } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state19.read())) { ap_enable_reg_pp1_iter0 = ap_const_logic_1; } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { ap_enable_reg_pp1_iter1 = ap_const_logic_0; } else { if (esl_seteq<1,1,1>(ap_block_pp1_stage0_subdone.read(), ap_const_boolean_0)) { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_condition_pp1_exit_iter0_state20.read())) { ap_enable_reg_pp1_iter1 = (ap_condition_pp1_exit_iter0_state20.read() ^ ap_const_logic_1); } else if (esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1)) { ap_enable_reg_pp1_iter1 = ap_enable_reg_pp1_iter0.read(); } } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { ap_enable_reg_pp1_iter2 = ap_const_logic_0; } else { if (esl_seteq<1,1,1>(ap_block_pp1_stage0_subdone.read(), ap_const_boolean_0)) { ap_enable_reg_pp1_iter2 = ap_enable_reg_pp1_iter1.read(); } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state19.read())) { ap_enable_reg_pp1_iter2 = ap_const_logic_0; } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { ap_enable_reg_pp2_iter0 = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_condition_pp2_exit_iter0_state24.read()))) { ap_enable_reg_pp2_iter0 = ap_const_logic_0; } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state23.read())) { ap_enable_reg_pp2_iter0 = ap_const_logic_1; } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { ap_enable_reg_pp2_iter1 = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage1.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage1_subdone.read(), ap_const_boolean_0))) { ap_enable_reg_pp2_iter1 = ap_enable_reg_pp2_iter0.read(); } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state23.read())) { ap_enable_reg_pp2_iter1 = ap_const_logic_0; } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { ap_reg_ioackin_gmem_ARREADY = ap_const_logic_0; } else { if (((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read()) && esl_seteq<1,1,1>(ap_sig_ioackin_gmem_ARREADY.read(), ap_const_logic_1)) || (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state13.read()) && esl_seteq<1,1,1>(ap_sig_ioackin_gmem_ARREADY.read(), ap_const_logic_1)))) { ap_reg_ioackin_gmem_ARREADY = ap_const_logic_0; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read()) && esl_seteq<1,1,1>(ap_const_logic_1, gmem_ARREADY.read())) || (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state13.read()) && esl_seteq<1,1,1>(ap_const_logic_1, gmem_ARREADY.read())))) { ap_reg_ioackin_gmem_ARREADY = ap_const_logic_1; } } if ((esl_seteq<1,1,1>(ap_const_lv1_0, tmp_2_reg_560.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter1.read()))) { i1_reg_280 = i_1_reg_564.read(); } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state23.read())) { i1_reg_280 = i_reg_233.read(); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp1_stage0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter1.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_546.read()) && esl_seteq<1,1,1>(ap_block_pp1_stage0_11001.read(), ap_const_boolean_0))) { indvar1_reg_268 = indvar_next1_reg_550.read(); } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state19.read())) { indvar1_reg_268 = ap_const_lv30_0; } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter0.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond_fu_345_p2.read()))) { indvar_reg_257 = indvar_next_fu_351_p2.read(); } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state8.read())) { indvar_reg_257 = ap_const_lv2_0; } if ( ap_rst_n_inv.read() == ap_const_logic_1) { x_data_0_sel_rd = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_ack_out.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_vld_out.read()))) { x_data_0_sel_rd = (sc_logic) (~x_data_0_sel_rd.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { x_data_0_sel_wr = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_ack_in.read()))) { x_data_0_sel_wr = (sc_logic) (~x_data_0_sel_wr.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { x_data_0_state = ap_const_lv2_0; } else { if (((esl_seteq<1,1,1>(ap_const_logic_0, x_data_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_3, x_data_0_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_0, x_data_0_vld_in.read()) && esl_seteq<1,2,2>(ap_const_lv2_2, x_data_0_state.read())))) { x_data_0_state = ap_const_lv2_2; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, x_data_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_3, x_data_0_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_0, x_data_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_1, x_data_0_state.read())))) { x_data_0_state = ap_const_lv2_1; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_vld_in.read()) && esl_seteq<1,2,2>(ap_const_lv2_2, x_data_0_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_1, x_data_0_state.read())) || (esl_seteq<1,2,2>(ap_const_lv2_3, x_data_0_state.read()) && !(esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, x_data_0_ack_out.read())) && !(esl_seteq<1,1,1>(ap_const_logic_0, x_data_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_ack_out.read()))))) { x_data_0_state = ap_const_lv2_3; } else { x_data_0_state = ap_const_lv2_2; } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { x_last_V_0_sel_rd = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_ack_out.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_vld_out.read()))) { x_last_V_0_sel_rd = (sc_logic) (~x_last_V_0_sel_rd.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { x_last_V_0_sel_wr = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_ack_in.read()))) { x_last_V_0_sel_wr = (sc_logic) (~x_last_V_0_sel_wr.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { x_last_V_0_state = ap_const_lv2_0; } else { if (((esl_seteq<1,1,1>(ap_const_logic_0, x_last_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_3, x_last_V_0_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_0, x_last_V_0_vld_in.read()) && esl_seteq<1,2,2>(ap_const_lv2_2, x_last_V_0_state.read())))) { x_last_V_0_state = ap_const_lv2_2; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, x_last_V_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_3, x_last_V_0_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_0, x_last_V_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_1, x_last_V_0_state.read())))) { x_last_V_0_state = ap_const_lv2_1; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_vld_in.read()) && esl_seteq<1,2,2>(ap_const_lv2_2, x_last_V_0_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_1, x_last_V_0_state.read())) || (esl_seteq<1,2,2>(ap_const_lv2_3, x_last_V_0_state.read()) && !(esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, x_last_V_0_ack_out.read())) && !(esl_seteq<1,1,1>(ap_const_logic_0, x_last_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_ack_out.read()))))) { x_last_V_0_state = ap_const_lv2_3; } else { x_last_V_0_state = ap_const_lv2_2; } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { x_user_V_0_sel_rd = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_ack_out.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_vld_out.read()))) { x_user_V_0_sel_rd = (sc_logic) (~x_user_V_0_sel_rd.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { x_user_V_0_sel_wr = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_ack_in.read()))) { x_user_V_0_sel_wr = (sc_logic) (~x_user_V_0_sel_wr.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { x_user_V_0_state = ap_const_lv2_0; } else { if (((esl_seteq<1,1,1>(ap_const_logic_0, x_user_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_3, x_user_V_0_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_0, x_user_V_0_vld_in.read()) && esl_seteq<1,2,2>(ap_const_lv2_2, x_user_V_0_state.read())))) { x_user_V_0_state = ap_const_lv2_2; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, x_user_V_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_3, x_user_V_0_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_0, x_user_V_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_1, x_user_V_0_state.read())))) { x_user_V_0_state = ap_const_lv2_1; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_vld_in.read()) && esl_seteq<1,2,2>(ap_const_lv2_2, x_user_V_0_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_1, x_user_V_0_state.read())) || (esl_seteq<1,2,2>(ap_const_lv2_3, x_user_V_0_state.read()) && !(esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, x_user_V_0_ack_out.read())) && !(esl_seteq<1,1,1>(ap_const_logic_0, x_user_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_ack_out.read()))))) { x_user_V_0_state = ap_const_lv2_3; } else { x_user_V_0_state = ap_const_lv2_2; } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { y_data_1_sel_rd = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_ack_out.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_vld_out.read()))) { y_data_1_sel_rd = (sc_logic) (~y_data_1_sel_rd.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { y_data_1_sel_wr = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_ack_in.read()))) { y_data_1_sel_wr = (sc_logic) (~y_data_1_sel_wr.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { y_data_1_state = ap_const_lv2_0; } else { if (((esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_ack_out.read()) && esl_seteq<1,2,2>(y_data_1_state.read(), ap_const_lv2_3)) || (esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_vld_in.read()) && esl_seteq<1,2,2>(y_data_1_state.read(), ap_const_lv2_2)))) { y_data_1_state = ap_const_lv2_2; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_ack_out.read()) && esl_seteq<1,2,2>(y_data_1_state.read(), ap_const_lv2_3)) || (esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_ack_out.read()) && esl_seteq<1,2,2>(y_data_1_state.read(), ap_const_lv2_1)))) { y_data_1_state = ap_const_lv2_1; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_vld_in.read()) && esl_seteq<1,2,2>(y_data_1_state.read(), ap_const_lv2_2)) || (esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_ack_out.read()) && esl_seteq<1,2,2>(y_data_1_state.read(), ap_const_lv2_1)) || (esl_seteq<1,2,2>(y_data_1_state.read(), ap_const_lv2_3) && !(esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_ack_out.read())) && !(esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_ack_out.read()))))) { y_data_1_state = ap_const_lv2_3; } else { y_data_1_state = ap_const_lv2_2; } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { y_last_V_1_sel_rd = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_ack_out.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_vld_out.read()))) { y_last_V_1_sel_rd = (sc_logic) (~y_last_V_1_sel_rd.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { y_last_V_1_sel_wr = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_ack_in.read()))) { y_last_V_1_sel_wr = (sc_logic) (~y_last_V_1_sel_wr.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { y_last_V_1_state = ap_const_lv2_0; } else { if (((esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_3, y_last_V_1_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_vld_in.read()) && esl_seteq<1,2,2>(ap_const_lv2_2, y_last_V_1_state.read())))) { y_last_V_1_state = ap_const_lv2_2; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_3, y_last_V_1_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_1, y_last_V_1_state.read())))) { y_last_V_1_state = ap_const_lv2_1; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_vld_in.read()) && esl_seteq<1,2,2>(ap_const_lv2_2, y_last_V_1_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_1, y_last_V_1_state.read())) || (esl_seteq<1,2,2>(ap_const_lv2_3, y_last_V_1_state.read()) && !(esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_ack_out.read())) && !(esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_ack_out.read()))))) { y_last_V_1_state = ap_const_lv2_3; } else { y_last_V_1_state = ap_const_lv2_2; } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { y_user_V_1_sel_rd = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_ack_out.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_vld_out.read()))) { y_user_V_1_sel_rd = (sc_logic) (~y_user_V_1_sel_rd.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { y_user_V_1_sel_wr = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_ack_in.read()))) { y_user_V_1_sel_wr = (sc_logic) (~y_user_V_1_sel_wr.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { y_user_V_1_state = ap_const_lv2_0; } else { if (((esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_3, y_user_V_1_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_vld_in.read()) && esl_seteq<1,2,2>(ap_const_lv2_2, y_user_V_1_state.read())))) { y_user_V_1_state = ap_const_lv2_2; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_3, y_user_V_1_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_1, y_user_V_1_state.read())))) { y_user_V_1_state = ap_const_lv2_1; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_vld_in.read()) && esl_seteq<1,2,2>(ap_const_lv2_2, y_user_V_1_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_1, y_user_V_1_state.read())) || (esl_seteq<1,2,2>(ap_const_lv2_3, y_user_V_1_state.read()) && !(esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_ack_out.read())) && !(esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_ack_out.read()))))) { y_user_V_1_state = ap_const_lv2_3; } else { y_user_V_1_state = ap_const_lv2_2; } } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state1.read()) && esl_seteq<1,1,1>(ap_start.read(), ap_const_logic_1))) { coe1_reg_483 = coe.read().range(31, 2); ctrl3_reg_478 = ctrl.read().range(31, 2); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp1_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp1_stage0_11001.read(), ap_const_boolean_0))) { exitcond1_reg_546 = exitcond1_fu_405_p2.read(); exitcond1_reg_546_pp1_iter1_reg = exitcond1_reg_546.read(); indvar1_reg_268_pp1_iter1_reg = indvar1_reg_268.read(); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_11001.read(), ap_const_boolean_0))) { exitcond_reg_500 = exitcond_fu_345_p2.read(); exitcond_reg_500_pp0_iter1_reg = exitcond_reg_500.read(); tmp_10_reg_509_pp0_iter1_reg = tmp_10_reg_509.read(); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond_reg_500.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_11001.read(), ap_const_boolean_0))) { fir_ctrl_0_reg_515 = gmem_RDATA.read(); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp1_stage0.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_546.read()) && esl_seteq<1,1,1>(ap_block_pp1_stage0_11001.read(), ap_const_boolean_0))) { gmem_addr_1_read_reg_555 = gmem_RDATA.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state8.read())) { gmem_addr_1_reg_494 = (sc_lv<32>) (tmp_9_fu_336_p1.read()); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_0, tmp_2_fu_421_p2.read()))) { i_1_reg_564 = i_1_fu_427_p2.read(); } if ((esl_seteq<1,1,1>(ap_block_pp0_stage0_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter2.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond_reg_500_pp0_iter1_reg.read()))) { i_reg_233 = fir_ctrl_1_1_fu_361_p3.read(); reload_reg_245 = reload_1_fu_367_p3.read(); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp1_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp1_stage0_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter0.read()))) { indvar_next1_reg_550 = indvar_next1_fu_410_p2.read(); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state12.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, tmp_fu_373_p2.read()))) { p_add7_i32_shr_reg_535 = tmp_1_fu_385_p2.read().range(31, 2); } if (((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage1.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage1_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_0, tmp_2_reg_560.read())) || esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state29.read()))) { reg_302 = coef_q0.read(); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage1.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage1_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_0, tmp_2_reg_560.read()))) { shift_reg_load_reg_584 = shift_reg_q0.read(); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond_fu_345_p2.read()))) { tmp_10_reg_509 = tmp_10_fu_357_p1.read(); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0_11001.read(), ap_const_boolean_0))) { tmp_2_reg_560 = tmp_2_fu_421_p2.read(); tmp_2_reg_560_pp2_iter1_reg = tmp_2_reg_560.read(); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state30.read()) && esl_seteq<1,1,1>(x_data_0_vld_out.read(), ap_const_logic_1))) { tmp_3_reg_609 = tmp_3_fu_466_p2.read(); x_last_V_tmp_reg_604 = x_last_V_0_data_out.read(); x_user_V_tmp_reg_599 = x_user_V_0_data_out.read(); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_0, tmp_2_fu_421_p2.read()))) { tmp_7_reg_574 = tmp_7_fu_438_p1.read(); } if ((esl_seteq<1,1,1>(ap_const_lv1_0, tmp_2_reg_560.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0_11001.read(), ap_const_boolean_0))) { tmp_8_reg_589 = tmp_8_fu_443_p2.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_load_A.read())) { x_data_0_payload_A = x_TDATA.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_load_B.read())) { x_data_0_payload_B = x_TDATA.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_load_A.read())) { x_last_V_0_payload_A = x_TLAST.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_load_B.read())) { x_last_V_0_payload_B = x_TLAST.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_load_A.read())) { x_user_V_0_payload_A = x_TUSER.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_load_B.read())) { x_user_V_0_payload_B = x_TUSER.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_load_A.read())) { y_data_1_payload_A = acc_1_fu_472_p2.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_load_B.read())) { y_data_1_payload_B = acc_1_fu_472_p2.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_load_A.read())) { y_last_V_1_payload_A = x_last_V_tmp_reg_604.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_load_B.read())) { y_last_V_1_payload_B = x_last_V_tmp_reg_604.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_load_A.read())) { y_user_V_1_payload_A = x_user_V_tmp_reg_599.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_load_B.read())) { y_user_V_1_payload_B = x_user_V_tmp_reg_599.read(); } } void x_order_fir::thread_acc_1_fu_472_p2() { acc_1_fu_472_p2 = (!tmp_3_reg_609.read().is_01() || !acc_reg_290.read().is_01())? sc_lv<32>(): (sc_biguint<32>(tmp_3_reg_609.read()) + sc_biguint<32>(acc_reg_290.read())); } void x_order_fir::thread_acc_2_fu_448_p2() { acc_2_fu_448_p2 = (!tmp_8_reg_589.read().is_01() || !acc_reg_290.read().is_01())? sc_lv<32>(): (sc_biguint<32>(tmp_8_reg_589.read()) + sc_biguint<32>(acc_reg_290.read())); } void x_order_fir::thread_ap_CS_fsm_pp0_stage0() { ap_CS_fsm_pp0_stage0 = ap_CS_fsm.read()[8]; } void x_order_fir::thread_ap_CS_fsm_pp1_stage0() { ap_CS_fsm_pp1_stage0 = ap_CS_fsm.read()[17]; } void x_order_fir::thread_ap_CS_fsm_pp2_stage0() { ap_CS_fsm_pp2_stage0 = ap_CS_fsm.read()[19]; } void x_order_fir::thread_ap_CS_fsm_pp2_stage1() { ap_CS_fsm_pp2_stage1 = ap_CS_fsm.read()[20]; } void x_order_fir::thread_ap_CS_fsm_state1() { ap_CS_fsm_state1 = ap_CS_fsm.read()[0]; } void x_order_fir::thread_ap_CS_fsm_state12() { ap_CS_fsm_state12 = ap_CS_fsm.read()[9]; } void x_order_fir::thread_ap_CS_fsm_state13() { ap_CS_fsm_state13 = ap_CS_fsm.read()[10]; } void x_order_fir::thread_ap_CS_fsm_state19() { ap_CS_fsm_state19 = ap_CS_fsm.read()[16]; } void x_order_fir::thread_ap_CS_fsm_state2() { ap_CS_fsm_state2 = ap_CS_fsm.read()[1]; } void x_order_fir::thread_ap_CS_fsm_state23() { ap_CS_fsm_state23 = ap_CS_fsm.read()[18]; } void x_order_fir::thread_ap_CS_fsm_state28() { ap_CS_fsm_state28 = ap_CS_fsm.read()[21]; } void x_order_fir::thread_ap_CS_fsm_state29() { ap_CS_fsm_state29 = ap_CS_fsm.read()[22]; } void x_order_fir::thread_ap_CS_fsm_state30() { ap_CS_fsm_state30 = ap_CS_fsm.read()[23]; } void x_order_fir::thread_ap_CS_fsm_state31() { ap_CS_fsm_state31 = ap_CS_fsm.read()[24]; } void x_order_fir::thread_ap_CS_fsm_state32() { ap_CS_fsm_state32 = ap_CS_fsm.read()[25]; } void x_order_fir::thread_ap_CS_fsm_state8() { ap_CS_fsm_state8 = ap_CS_fsm.read()[7]; } void x_order_fir::thread_ap_block_pp0_stage0() { ap_block_pp0_stage0 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_pp0_stage0_11001() { ap_block_pp0_stage0_11001 = (esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter1.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond_reg_500.read()) && esl_seteq<1,1,1>(ap_const_logic_0, gmem_RVALID.read())); } void x_order_fir::thread_ap_block_pp0_stage0_subdone() { ap_block_pp0_stage0_subdone = (esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter1.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond_reg_500.read()) && esl_seteq<1,1,1>(ap_const_logic_0, gmem_RVALID.read())); } void x_order_fir::thread_ap_block_pp1_stage0() { ap_block_pp1_stage0 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_pp1_stage0_11001() { ap_block_pp1_stage0_11001 = (esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter1.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_546.read()) && esl_seteq<1,1,1>(ap_const_logic_0, gmem_RVALID.read())); } void x_order_fir::thread_ap_block_pp1_stage0_subdone() { ap_block_pp1_stage0_subdone = (esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter1.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_546.read()) && esl_seteq<1,1,1>(ap_const_logic_0, gmem_RVALID.read())); } void x_order_fir::thread_ap_block_pp2_stage0() { ap_block_pp2_stage0 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_pp2_stage0_11001() { ap_block_pp2_stage0_11001 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_pp2_stage0_subdone() { ap_block_pp2_stage0_subdone = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_pp2_stage1() { ap_block_pp2_stage1 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_pp2_stage1_11001() { ap_block_pp2_stage1_11001 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_pp2_stage1_subdone() { ap_block_pp2_stage1_subdone = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_state10_pp0_stage0_iter1() { ap_block_state10_pp0_stage0_iter1 = (esl_seteq<1,1,1>(ap_const_lv1_0, exitcond_reg_500.read()) && esl_seteq<1,1,1>(ap_const_logic_0, gmem_RVALID.read())); } void x_order_fir::thread_ap_block_state11_pp0_stage0_iter2() { ap_block_state11_pp0_stage0_iter2 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_state20_pp1_stage0_iter0() { ap_block_state20_pp1_stage0_iter0 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_state21_pp1_stage0_iter1() { ap_block_state21_pp1_stage0_iter1 = (esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_546.read()) && esl_seteq<1,1,1>(ap_const_logic_0, gmem_RVALID.read())); } void x_order_fir::thread_ap_block_state22_pp1_stage0_iter2() { ap_block_state22_pp1_stage0_iter2 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_state24_pp2_stage0_iter0() { ap_block_state24_pp2_stage0_iter0 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_state25_pp2_stage1_iter0() { ap_block_state25_pp2_stage1_iter0 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_state26_pp2_stage0_iter1() { ap_block_state26_pp2_stage0_iter1 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_state27_pp2_stage1_iter1() { ap_block_state27_pp2_stage1_iter1 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_state32() { ap_block_state32 = (esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_ack_in.read()) || esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_ack_in.read()) || esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_ack_in.read())); } void x_order_fir::thread_ap_block_state9_pp0_stage0_iter0() { ap_block_state9_pp0_stage0_iter0 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_condition_pp0_exit_iter0_state9() { if (esl_seteq<1,1,1>(ap_const_lv1_1, exitcond_fu_345_p2.read())) { ap_condition_pp0_exit_iter0_state9 = ap_const_logic_1; } else { ap_condition_pp0_exit_iter0_state9 = ap_const_logic_0; } } void x_order_fir::thread_ap_condition_pp1_exit_iter0_state20() { if (esl_seteq<1,1,1>(ap_const_lv1_1, exitcond1_fu_405_p2.read())) { ap_condition_pp1_exit_iter0_state20 = ap_const_logic_1; } else { ap_condition_pp1_exit_iter0_state20 = ap_const_logic_0; } } void x_order_fir::thread_ap_condition_pp2_exit_iter0_state24() { if (esl_seteq<1,1,1>(ap_const_lv1_1, tmp_2_fu_421_p2.read())) { ap_condition_pp2_exit_iter0_state24 = ap_const_logic_1; } else { ap_condition_pp2_exit_iter0_state24 = ap_const_logic_0; } } void x_order_fir::thread_ap_done() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state32.read()) && esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_state.read()[0]) && esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_state.read()[0]) && esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_state.read()[0]) && !(esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_ack_in.read()) || esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_ack_in.read()) || esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_ack_in.read())))) { ap_done = ap_const_logic_1; } else { ap_done = ap_const_logic_0; } } void x_order_fir::thread_ap_enable_pp0() { ap_enable_pp0 = (ap_idle_pp0.read() ^ ap_const_logic_1); } void x_order_fir::thread_ap_enable_pp1() { ap_enable_pp1 = (ap_idle_pp1.read() ^ ap_const_logic_1); } void x_order_fir::thread_ap_enable_pp2() { ap_enable_pp2 = (ap_idle_pp2.read() ^ ap_const_logic_1); } void x_order_fir::thread_ap_idle() { if ((esl_seteq<1,1,1>(ap_const_logic_0, ap_start.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state1.read()))) { ap_idle = ap_const_logic_1; } else { ap_idle = ap_const_logic_0; } } void x_order_fir::thread_ap_idle_pp0() { if ((esl_seteq<1,1,1>(ap_const_logic_0, ap_enable_reg_pp0_iter0.read()) && esl_seteq<1,1,1>(ap_const_logic_0, ap_enable_reg_pp0_iter1.read()) && esl_seteq<1,1,1>(ap_const_logic_0, ap_enable_reg_pp0_iter2.read()))) { ap_idle_pp0 = ap_const_logic_1; } else { ap_idle_pp0 = ap_const_logic_0; } } void x_order_fir::thread_ap_idle_pp1() { if ((esl_seteq<1,1,1>(ap_const_logic_0, ap_enable_reg_pp1_iter0.read()) && esl_seteq<1,1,1>(ap_const_logic_0, ap_enable_reg_pp1_iter1.read()) && esl_seteq<1,1,1>(ap_const_logic_0, ap_enable_reg_pp1_iter2.read()))) { ap_idle_pp1 = ap_const_logic_1; } else { ap_idle_pp1 = ap_const_logic_0; } } void x_order_fir::thread_ap_idle_pp2() { if ((esl_seteq<1,1,1>(ap_const_logic_0, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_const_logic_0, ap_enable_reg_pp2_iter1.read()))) { ap_idle_pp2 = ap_const_logic_1; } else { ap_idle_pp2 = ap_const_logic_0; } } void x_order_fir::thread_ap_phi_mux_i1_phi_fu_283_p4() { if ((esl_seteq<1,1,1>(ap_const_lv1_0, tmp_2_reg_560.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter1.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0.read(), ap_const_boolean_0))) { ap_phi_mux_i1_phi_fu_283_p4 = i_1_reg_564.read(); } else { ap_phi_mux_i1_phi_fu_283_p4 = i1_reg_280.read(); } } void x_order_fir::thread_ap_phi_mux_indvar1_phi_fu_272_p4() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp1_stage0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter1.read()) && esl_seteq<1,1,1>(ap_block_pp1_stage0.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_546.read()))) { ap_phi_mux_indvar1_phi_fu_272_p4 = indvar_next1_reg_550.read(); } else { ap_phi_mux_indvar1_phi_fu_272_p4 = indvar1_reg_268.read(); } } void x_order_fir::thread_ap_ready() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state32.read()) && esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_state.read()[0]) && esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_state.read()[0]) && esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_state.read()[0]) && !(esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_ack_in.read()) || esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_ack_in.read()) || esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_ack_in.read())))) { ap_ready = ap_const_logic_1; } else { ap_ready = ap_const_logic_0; } } void x_order_fir::thread_ap_rst_n_inv() { ap_rst_n_inv = (sc_logic) (~ap_rst_n.read()); } void x_order_fir::thread_ap_sig_ioackin_gmem_ARREADY() { if (esl_seteq<1,1,1>(ap_const_logic_0, ap_reg_ioackin_gmem_ARREADY.read())) { ap_sig_ioackin_gmem_ARREADY = gmem_ARREADY.read(); } else { ap_sig_ioackin_gmem_ARREADY = ap_const_logic_1; } } void x_order_fir::thread_coef_address0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state28.read())) { coef_address0 = ap_const_lv10_0; } else if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0.read(), ap_const_boolean_0))) { coef_address0 = (sc_lv<10>) (tmp_7_fu_438_p1.read()); } else if ((esl_seteq<1,1,1>(ap_block_pp1_stage0.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter2.read()))) { coef_address0 = (sc_lv<10>) (indvar2_fu_416_p1.read()); } else { coef_address0 = "XXXXXXXXXX"; } } void x_order_fir::thread_coef_ce0() { if (((esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0_11001.read(), ap_const_boolean_0)) || (esl_seteq<1,1,1>(ap_block_pp1_stage0_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter2.read())) || esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state28.read()))) { coef_ce0 = ap_const_logic_1; } else { coef_ce0 = ap_const_logic_0; } } void x_order_fir::thread_coef_we0() { if ((esl_seteq<1,1,1>(ap_block_pp1_stage0_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter2.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_546_pp1_iter1_reg.read()))) { coef_we0 = ap_const_logic_1; } else { coef_we0 = ap_const_logic_0; } } void x_order_fir::thread_exitcond1_fu_405_p2() { exitcond1_fu_405_p2 = (!ap_phi_mux_indvar1_phi_fu_272_p4.read().is_01() || !p_add7_i32_shr_reg_535.read().is_01())? sc_lv<1>(): sc_lv<1>(ap_phi_mux_indvar1_phi_fu_272_p4.read() == p_add7_i32_shr_reg_535.read()); } void x_order_fir::thread_exitcond_fu_345_p2() { exitcond_fu_345_p2 = (!indvar_reg_257.read().is_01() || !ap_const_lv2_2.is_01())? sc_lv<1>(): sc_lv<1>(indvar_reg_257.read() == ap_const_lv2_2); } void x_order_fir::thread_fir_ctrl_1_1_fu_361_p3() { fir_ctrl_1_1_fu_361_p3 = (!tmp_10_reg_509_pp0_iter1_reg.read()[0].is_01())? sc_lv<32>(): ((tmp_10_reg_509_pp0_iter1_reg.read()[0].to_bool())? fir_ctrl_0_reg_515.read(): i_reg_233.read()); } void x_order_fir::thread_gmem_ARADDR() { if (esl_seteq<1,1,1>(ap_const_logic_0, ap_reg_ioackin_gmem_ARREADY.read())) { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state13.read())) { gmem_ARADDR = gmem_addr_1_reg_494.read(); } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read())) { gmem_ARADDR = (sc_lv<32>) (tmp_5_fu_326_p1.read()); } else { gmem_ARADDR = (sc_lv<32>) ("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); } } else { gmem_ARADDR = (sc_lv<32>) ("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); } } void x_order_fir::thread_gmem_ARLEN() { if (esl_seteq<1,1,1>(ap_const_logic_0, ap_reg_ioackin_gmem_ARREADY.read())) { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state13.read())) { gmem_ARLEN = tmp_s_fu_401_p1.read(); } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read())) { gmem_ARLEN = ap_const_lv32_2; } else { gmem_ARLEN = (sc_lv<32>) ("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); } } else { gmem_ARLEN = (sc_lv<32>) ("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); } } void x_order_fir::thread_gmem_ARVALID() { if (((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read()) && esl_seteq<1,1,1>(ap_const_logic_0, ap_reg_ioackin_gmem_ARREADY.read())) || (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state13.read()) && esl_seteq<1,1,1>(ap_const_logic_0, ap_reg_ioackin_gmem_ARREADY.read())))) { gmem_ARVALID = ap_const_logic_1; } else { gmem_ARVALID = ap_const_logic_0; } } void x_order_fir::thread_gmem_RREADY() { if (((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp1_stage0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter1.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_546.read()) && esl_seteq<1,1,1>(ap_block_pp1_stage0_11001.read(), ap_const_boolean_0)) || (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter1.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond_reg_500.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_11001.read(), ap_const_boolean_0)))) { gmem_RREADY = ap_const_logic_1; } else { gmem_RREADY = ap_const_logic_0; } } void x_order_fir::thread_gmem_blk_n_AR() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read()) || esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state13.read()))) { gmem_blk_n_AR = m_axi_gmem_ARREADY.read(); } else { gmem_blk_n_AR = ap_const_logic_1; } } void x_order_fir::thread_gmem_blk_n_R() { if (((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter1.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond_reg_500.read())) || (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp1_stage0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter1.read()) && esl_seteq<1,1,1>(ap_block_pp1_stage0.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_546.read())))) { gmem_blk_n_R = m_axi_gmem_RVALID.read(); } else { gmem_blk_n_R = ap_const_logic_1; } } void x_order_fir::thread_i_1_fu_427_p2() { i_1_fu_427_p2 = (!ap_phi_mux_i1_phi_fu_283_p4.read().is_01() || !ap_const_lv32_FFFFFFFF.is_01())? sc_lv<32>(): (sc_bigint<32>(ap_phi_mux_i1_phi_fu_283_p4.read()) + sc_bigint<32>(ap_const_lv32_FFFFFFFF)); } void x_order_fir::thread_indvar2_fu_416_p1() { indvar2_fu_416_p1 = esl_zext<64,30>(indvar1_reg_268_pp1_iter1_reg.read()); } void x_order_fir::thread_indvar_next1_fu_410_p2() { indvar_next1_fu_410_p2 = (!ap_phi_mux_indvar1_phi_fu_272_p4.read().is_01() || !ap_const_lv30_1.is_01())? sc_lv<30>(): (sc_biguint<30>(ap_phi_mux_indvar1_phi_fu_272_p4.read()) + sc_biguint<30>(ap_const_lv30_1)); } void x_order_fir::thread_indvar_next_fu_351_p2() { indvar_next_fu_351_p2 = (!indvar_reg_257.read().is_01() || !ap_const_lv2_1.is_01())? sc_lv<2>(): (sc_biguint<2>(indvar_reg_257.read()) + sc_biguint<2>(ap_const_lv2_1)); } void x_order_fir::thread_reload_1_fu_367_p3() { reload_1_fu_367_p3 = (!tmp_10_reg_509_pp0_iter1_reg.read()[0].is_01())? sc_lv<32>(): ((tmp_10_reg_509_pp0_iter1_reg.read()[0].to_bool())? reload_reg_245.read(): fir_ctrl_0_reg_515.read()); } void x_order_fir::thread_shift_reg_address0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state30.read())) { shift_reg_address0 = ap_const_lv10_0; } else if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage1.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage1.read(), ap_const_boolean_0))) { shift_reg_address0 = (sc_lv<10>) (tmp_7_reg_574.read()); } else if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0.read(), ap_const_boolean_0))) { shift_reg_address0 = (sc_lv<10>) (tmp_6_fu_433_p1.read()); } else { shift_reg_address0 = "XXXXXXXXXX"; } } void x_order_fir::thread_shift_reg_ce0() { if (((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage1.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage1_11001.read(), ap_const_boolean_0)) || (esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0_11001.read(), ap_const_boolean_0)) || (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state30.read()) && esl_seteq<1,1,1>(x_data_0_vld_out.read(), ap_const_logic_1)))) { shift_reg_ce0 = ap_const_logic_1; } else { shift_reg_ce0 = ap_const_logic_0; } } void x_order_fir::thread_shift_reg_d0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state30.read())) { shift_reg_d0 = x_data_0_data_out.read(); } else if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage1.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage1.read(), ap_const_boolean_0))) { shift_reg_d0 = shift_reg_q0.read(); } else { shift_reg_d0 = (sc_lv<32>) ("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); } } void x_order_fir::thread_shift_reg_we0() { if (((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage1.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage1_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_0, tmp_2_reg_560.read())) || (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state30.read()) && esl_seteq<1,1,1>(x_data_0_vld_out.read(), ap_const_logic_1)))) { shift_reg_we0 = ap_const_logic_1; } else { shift_reg_we0 = ap_const_logic_0; } } void x_order_fir::thread_tmp_10_fu_357_p1() { tmp_10_fu_357_p1 = indvar_reg_257.read().range(1-1, 0); } void x_order_fir::thread_tmp_12_fu_379_p2() { tmp_12_fu_379_p2 = (!ap_const_lv32_2.is_01())? sc_lv<32>(): i_reg_233.read() << (unsigned short)ap_const_lv32_2.to_uint(); } void x_order_fir::thread_tmp_1_fu_385_p2() { tmp_1_fu_385_p2 = (!ap_const_lv32_4.is_01() || !tmp_12_fu_379_p2.read().is_01())? sc_lv<32>(): (sc_biguint<32>(ap_const_lv32_4) + sc_biguint<32>(tmp_12_fu_379_p2.read())); } void x_order_fir::thread_tmp_2_fu_421_p2() { tmp_2_fu_421_p2 = (!ap_phi_mux_i1_phi_fu_283_p4.read().is_01() || !ap_const_lv32_0.is_01())? sc_lv<1>(): sc_lv<1>(ap_phi_mux_i1_phi_fu_283_p4.read() == ap_const_lv32_0); } void x_order_fir::thread_tmp_3_fu_466_p1() { tmp_3_fu_466_p1 = x_data_0_data_out.read(); } void x_order_fir::thread_tmp_3_fu_466_p2() { tmp_3_fu_466_p2 = (!reg_302.read().is_01() || !tmp_3_fu_466_p1.read().is_01())? sc_lv<32>(): sc_bigint<32>(reg_302.read()) * sc_bigint<32>(tmp_3_fu_466_p1.read()); } void x_order_fir::thread_tmp_5_fu_326_p1() { tmp_5_fu_326_p1 = esl_zext<64,30>(ctrl3_reg_478.read()); } void x_order_fir::thread_tmp_6_fu_433_p1() { tmp_6_fu_433_p1 = esl_sext<64,32>(i_1_fu_427_p2.read()); } void x_order_fir::thread_tmp_7_fu_438_p1() { tmp_7_fu_438_p1 = esl_sext<64,32>(ap_phi_mux_i1_phi_fu_283_p4.read()); } void x_order_fir::thread_tmp_8_fu_443_p2() { tmp_8_fu_443_p2 = (!reg_302.read().is_01() || !shift_reg_load_reg_584.read().is_01())? sc_lv<32>(): sc_bigint<32>(reg_302.read()) * sc_bigint<32>(shift_reg_load_reg_584.read()); } void x_order_fir::thread_tmp_9_fu_336_p1() { tmp_9_fu_336_p1 = esl_zext<64,30>(coe1_reg_483.read()); } void x_order_fir::thread_tmp_fu_373_p2() { tmp_fu_373_p2 = (!reload_reg_245.read().is_01() || !ap_const_lv32_0.is_01())? sc_lv<1>(): sc_lv<1>(reload_reg_245.read() == ap_const_lv32_0); } void x_order_fir::thread_tmp_s_fu_401_p1() { tmp_s_fu_401_p1 = esl_zext<32,30>(p_add7_i32_shr_reg_535.read()); } void x_order_fir::thread_x_TDATA_blk_n() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state30.read())) { x_TDATA_blk_n = x_data_0_state.read()[0]; } else { x_TDATA_blk_n = ap_const_logic_1; } } void x_order_fir::thread_x_TREADY() { x_TREADY = x_last_V_0_state.read()[1]; } void x_order_fir::thread_x_data_0_ack_in() { x_data_0_ack_in = x_data_0_state.read()[1]; } void x_order_fir::thread_x_data_0_ack_out() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state30.read()) && esl_seteq<1,1,1>(x_data_0_vld_out.read(), ap_const_logic_1))) { x_data_0_ack_out = ap_const_logic_1; } else { x_data_0_ack_out = ap_const_logic_0; } } void x_order_fir::thread_x_data_0_data_out() { if (esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_sel.read())) { x_data_0_data_out = x_data_0_payload_B.read(); } else { x_data_0_data_out = x_data_0_payload_A.read(); } } void x_order_fir::thread_x_data_0_load_A() { x_data_0_load_A = (x_data_0_state_cmp_full.read() & ~x_data_0_sel_wr.read()); } void x_order_fir::thread_x_data_0_load_B() { x_data_0_load_B = (x_data_0_sel_wr.read() & x_data_0_state_cmp_full.read()); } void x_order_fir::thread_x_data_0_sel() { x_data_0_sel = x_data_0_sel_rd.read(); } void x_order_fir::thread_x_data_0_state_cmp_full() { x_data_0_state_cmp_full = (sc_logic) ((!x_data_0_state.read().is_01() || !ap_const_lv2_1.is_01())? sc_lv<1>(): sc_lv<1>(x_data_0_state.read() != ap_const_lv2_1))[0]; } void x_order_fir::thread_x_data_0_vld_in() { x_data_0_vld_in = x_TVALID.read(); } void x_order_fir::thread_x_data_0_vld_out() { x_data_0_vld_out = x_data_0_state.read()[0]; } void x_order_fir::thread_x_last_V_0_ack_in() { x_last_V_0_ack_in = x_last_V_0_state.read()[1]; } void x_order_fir::thread_x_last_V_0_ack_out() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state30.read()) && esl_seteq<1,1,1>(x_data_0_vld_out.read(), ap_const_logic_1))) { x_last_V_0_ack_out = ap_const_logic_1; } else { x_last_V_0_ack_out = ap_const_logic_0; } } void x_order_fir::thread_x_last_V_0_data_out() { if (esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_sel.read())) { x_last_V_0_data_out = x_last_V_0_payload_B.read(); } else { x_last_V_0_data_out = x_last_V_0_payload_A.read(); } } void x_order_fir::thread_x_last_V_0_load_A() { x_last_V_0_load_A = (x_last_V_0_state_cmp_full.read() & ~x_last_V_0_sel_wr.read()); } void x_order_fir::thread_x_last_V_0_load_B() { x_last_V_0_load_B = (x_last_V_0_sel_wr.read() & x_last_V_0_state_cmp_full.read()); } void x_order_fir::thread_x_last_V_0_sel() { x_last_V_0_sel = x_last_V_0_sel_rd.read(); } void x_order_fir::thread_x_last_V_0_state_cmp_full() { x_last_V_0_state_cmp_full = (sc_logic) ((!x_last_V_0_state.read().is_01() || !ap_const_lv2_1.is_01())? sc_lv<1>(): sc_lv<1>(x_last_V_0_state.read() != ap_const_lv2_1))[0]; } void x_order_fir::thread_x_last_V_0_vld_in() { x_last_V_0_vld_in = x_TVALID.read(); } void x_order_fir::thread_x_last_V_0_vld_out() { x_last_V_0_vld_out = x_last_V_0_state.read()[0]; } void x_order_fir::thread_x_user_V_0_ack_in() { x_user_V_0_ack_in = x_user_V_0_state.read()[1]; } void x_order_fir::thread_x_user_V_0_ack_out() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state30.read()) && esl_seteq<1,1,1>(x_data_0_vld_out.read(), ap_const_logic_1))) { x_user_V_0_ack_out = ap_const_logic_1; } else { x_user_V_0_ack_out = ap_const_logic_0; } } void x_order_fir::thread_x_user_V_0_data_out() { if (esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_sel.read())) { x_user_V_0_data_out = x_user_V_0_payload_B.read(); } else { x_user_V_0_data_out = x_user_V_0_payload_A.read(); } } void x_order_fir::thread_x_user_V_0_load_A() { x_user_V_0_load_A = (x_user_V_0_state_cmp_full.read() & ~x_user_V_0_sel_wr.read()); } void x_order_fir::thread_x_user_V_0_load_B() { x_user_V_0_load_B = (x_user_V_0_sel_wr.read() & x_user_V_0_state_cmp_full.read()); } void x_order_fir::thread_x_user_V_0_sel() { x_user_V_0_sel = x_user_V_0_sel_rd.read(); } void x_order_fir::thread_x_user_V_0_state_cmp_full() { x_user_V_0_state_cmp_full = (sc_logic) ((!x_user_V_0_state.read().is_01() || !ap_const_lv2_1.is_01())? sc_lv<1>(): sc_lv<1>(x_user_V_0_state.read() != ap_const_lv2_1))[0]; } void x_order_fir::thread_x_user_V_0_vld_in() { x_user_V_0_vld_in = x_TVALID.read(); } void x_order_fir::thread_x_user_V_0_vld_out() { x_user_V_0_vld_out = x_user_V_0_state.read()[0]; } void x_order_fir::thread_y_TDATA() { y_TDATA = y_data_1_data_out.read(); } void x_order_fir::thread_y_TDATA_blk_n() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state31.read()) || esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state32.read()))) { y_TDATA_blk_n = y_data_1_state.read()[1]; } else { y_TDATA_blk_n = ap_const_logic_1; } } void x_order_fir::thread_y_TLAST() { y_TLAST = y_last_V_1_data_out.read(); } void x_order_fir::thread_y_TUSER() { y_TUSER = y_user_V_1_data_out.read(); } void x_order_fir::thread_y_TVALID() { y_TVALID = y_last_V_1_state.read()[0]; } void x_order_fir::thread_y_data_1_ack_in() { y_data_1_ack_in = y_data_1_state.read()[1]; } void x_order_fir::thread_y_data_1_ack_out() { y_data_1_ack_out = y_TREADY.read(); } void x_order_fir::thread_y_data_1_data_out() { if (esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_sel.read())) { y_data_1_data_out = y_data_1_payload_B.read(); } else { y_data_1_data_out = y_data_1_payload_A.read(); } } void x_order_fir::thread_y_data_1_load_A() { y_data_1_load_A = (y_data_1_state_cmp_full.read() & ~y_data_1_sel_wr.read()); } void x_order_fir::thread_y_data_1_load_B() { y_data_1_load_B = (y_data_1_sel_wr.read() & y_data_1_state_cmp_full.read()); } void x_order_fir::thread_y_data_1_sel() { y_data_1_sel = y_data_1_sel_rd.read(); } void x_order_fir::thread_y_data_1_state_cmp_full() { y_data_1_state_cmp_full = (sc_logic) ((!y_data_1_state.read().is_01() || !ap_const_lv2_1.is_01())? sc_lv<1>(): sc_lv<1>(y_data_1_state.read() != ap_const_lv2_1))[0]; } void x_order_fir::thread_y_data_1_vld_in() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state31.read()) && esl_seteq<1,1,1>(y_data_1_ack_in.read(), ap_const_logic_1))) { y_data_1_vld_in = ap_const_logic_1; } else { y_data_1_vld_in = ap_const_logic_0; } } void x_order_fir::thread_y_data_1_vld_out() { y_data_1_vld_out = y_data_1_state.read()[0]; } void x_order_fir::thread_y_last_V_1_ack_in() { y_last_V_1_ack_in = y_last_V_1_state.read()[1]; } void x_order_fir::thread_y_last_V_1_ack_out() { y_last_V_1_ack_out = y_TREADY.read(); } void x_order_fir::thread_y_last_V_1_data_out() { if (esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_sel.read())) { y_last_V_1_data_out = y_last_V_1_payload_B.read(); } else { y_last_V_1_data_out = y_last_V_1_payload_A.read(); } } void x_order_fir::thread_y_last_V_1_load_A() { y_last_V_1_load_A = (y_last_V_1_state_cmp_full.read() & ~y_last_V_1_sel_wr.read()); } void x_order_fir::thread_y_last_V_1_load_B() { y_last_V_1_load_B = (y_last_V_1_sel_wr.read() & y_last_V_1_state_cmp_full.read()); } void x_order_fir::thread_y_last_V_1_sel() { y_last_V_1_sel = y_last_V_1_sel_rd.read(); } void x_order_fir::thread_y_last_V_1_state_cmp_full() { y_last_V_1_state_cmp_full = (sc_logic) ((!y_last_V_1_state.read().is_01() || !ap_const_lv2_1.is_01())? sc_lv<1>(): sc_lv<1>(y_last_V_1_state.read() != ap_const_lv2_1))[0]; } void x_order_fir::thread_y_last_V_1_vld_in() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state31.read()) && esl_seteq<1,1,1>(y_data_1_ack_in.read(), ap_const_logic_1))) { y_last_V_1_vld_in = ap_const_logic_1; } else { y_last_V_1_vld_in = ap_const_logic_0; } } void x_order_fir::thread_y_last_V_1_vld_out() { y_last_V_1_vld_out = y_last_V_1_state.read()[0]; } void x_order_fir::thread_y_user_V_1_ack_in() { y_user_V_1_ack_in = y_user_V_1_state.read()[1]; } void x_order_fir::thread_y_user_V_1_ack_out() { y_user_V_1_ack_out = y_TREADY.read(); } void x_order_fir::thread_y_user_V_1_data_out() { if (esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_sel.read())) { y_user_V_1_data_out = y_user_V_1_payload_B.read(); } else { y_user_V_1_data_out = y_user_V_1_payload_A.read(); } } void x_order_fir::thread_y_user_V_1_load_A() { y_user_V_1_load_A = (y_user_V_1_state_cmp_full.read() & ~y_user_V_1_sel_wr.read()); } void x_order_fir::thread_y_user_V_1_load_B() { y_user_V_1_load_B = (y_user_V_1_sel_wr.read() & y_user_V_1_state_cmp_full.read()); } void x_order_fir::thread_y_user_V_1_sel() { y_user_V_1_sel = y_user_V_1_sel_rd.read(); } void x_order_fir::thread_y_user_V_1_state_cmp_full() { y_user_V_1_state_cmp_full = (sc_logic) ((!y_user_V_1_state.read().is_01() || !ap_const_lv2_1.is_01())? sc_lv<1>(): sc_lv<1>(y_user_V_1_state.read() != ap_const_lv2_1))[0]; } void x_order_fir::thread_y_user_V_1_vld_in() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state31.read()) && esl_seteq<1,1,1>(y_data_1_ack_in.read(), ap_const_logic_1))) { y_user_V_1_vld_in = ap_const_logic_1; } else { y_user_V_1_vld_in = ap_const_logic_0; } } void x_order_fir::thread_y_user_V_1_vld_out() { y_user_V_1_vld_out = y_user_V_1_state.read()[0]; } void x_order_fir::thread_ap_NS_fsm() { switch (ap_CS_fsm.read().to_uint64()) { case 1 : if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state1.read()) && esl_seteq<1,1,1>(ap_start.read(), ap_const_logic_1))) { ap_NS_fsm = ap_ST_fsm_state2; } else { ap_NS_fsm = ap_ST_fsm_state1; } break; case 2 : if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read()) && esl_seteq<1,1,1>(ap_sig_ioackin_gmem_ARREADY.read(), ap_const_logic_1))) { ap_NS_fsm = ap_ST_fsm_state3; } else { ap_NS_fsm = ap_ST_fsm_state2; } break; case 4 : ap_NS_fsm = ap_ST_fsm_state4; break; case 8 : ap_NS_fsm = ap_ST_fsm_state5; break; case 16 : ap_NS_fsm = ap_ST_fsm_state6; break; case 32 : ap_NS_fsm = ap_ST_fsm_state7; break; case 64 : ap_NS_fsm = ap_ST_fsm_state8; break; case 128 : ap_NS_fsm = ap_ST_fsm_pp0_stage0; break; case 256 : if ((!(esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter2.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_enable_reg_pp0_iter1.read(), ap_const_logic_0)) && !(esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_1, exitcond_fu_345_p2.read()) && esl_seteq<1,1,1>(ap_enable_reg_pp0_iter1.read(), ap_const_logic_0)))) { ap_NS_fsm = ap_ST_fsm_pp0_stage0; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter2.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_enable_reg_pp0_iter1.read(), ap_const_logic_0)) || (esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_1, exitcond_fu_345_p2.read()) && esl_seteq<1,1,1>(ap_enable_reg_pp0_iter1.read(), ap_const_logic_0)))) { ap_NS_fsm = ap_ST_fsm_state12; } else { ap_NS_fsm = ap_ST_fsm_pp0_stage0; } break; case 512 : if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state12.read()) && esl_seteq<1,1,1>(ap_const_lv1_1, tmp_fu_373_p2.read()))) { ap_NS_fsm = ap_ST_fsm_state23; } else { ap_NS_fsm = ap_ST_fsm_state13; } break; case 1024 : if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state13.read()) && esl_seteq<1,1,1>(ap_sig_ioackin_gmem_ARREADY.read(), ap_const_logic_1))) { ap_NS_fsm = ap_ST_fsm_state14; } else { ap_NS_fsm = ap_ST_fsm_state13; } break; case 2048 : ap_NS_fsm = ap_ST_fsm_state15; break; case 4096 : ap_NS_fsm = ap_ST_fsm_state16; break; case 8192 : ap_NS_fsm = ap_ST_fsm_state17; break; case 16384 : ap_NS_fsm = ap_ST_fsm_state18; break; case 32768 : ap_NS_fsm = ap_ST_fsm_state19; break; case 65536 : ap_NS_fsm = ap_ST_fsm_pp1_stage0; break; case 131072 : if ((!(esl_seteq<1,1,1>(ap_block_pp1_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter2.read()) && esl_seteq<1,1,1>(ap_enable_reg_pp1_iter1.read(), ap_const_logic_0)) && !(esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp1_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_1, exitcond1_fu_405_p2.read()) && esl_seteq<1,1,1>(ap_enable_reg_pp1_iter1.read(), ap_const_logic_0)))) { ap_NS_fsm = ap_ST_fsm_pp1_stage0; } else if (((esl_seteq<1,1,1>(ap_block_pp1_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter2.read()) && esl_seteq<1,1,1>(ap_enable_reg_pp1_iter1.read(), ap_const_logic_0)) || (esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp1_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_1, exitcond1_fu_405_p2.read()) && esl_seteq<1,1,1>(ap_enable_reg_pp1_iter1.read(), ap_const_logic_0)))) { ap_NS_fsm = ap_ST_fsm_state23; } else { ap_NS_fsm = ap_ST_fsm_pp1_stage0; } break; case 262144 : ap_NS_fsm = ap_ST_fsm_pp2_stage0; break; case 524288 : if ((esl_seteq<1,1,1>(ap_block_pp2_stage0_subdone.read(), ap_const_boolean_0) && !(esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_1, tmp_2_fu_421_p2.read()) && esl_seteq<1,1,1>(ap_enable_reg_pp2_iter1.read(), ap_const_logic_0)))) { ap_NS_fsm = ap_ST_fsm_pp2_stage1; } else if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_1, tmp_2_fu_421_p2.read()) && esl_seteq<1,1,1>(ap_enable_reg_pp2_iter1.read(), ap_const_logic_0))) { ap_NS_fsm = ap_ST_fsm_state28; } else { ap_NS_fsm = ap_ST_fsm_pp2_stage0; } break; case 1048576 : if ((esl_seteq<1,1,1>(ap_block_pp2_stage1_subdone.read(), ap_const_boolean_0) && !(esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage1.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter1.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage1_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_enable_reg_pp2_iter0.read(), ap_const_logic_0)))) { ap_NS_fsm = ap_ST_fsm_pp2_stage0; } else if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage1.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter1.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage1_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_enable_reg_pp2_iter0.read(), ap_const_logic_0))) { ap_NS_fsm = ap_ST_fsm_state28; } else { ap_NS_fsm = ap_ST_fsm_pp2_stage1; } break; case 2097152 : ap_NS_fsm = ap_ST_fsm_state29; break; case 4194304 : ap_NS_fsm = ap_ST_fsm_state30; break; case 8388608 : if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state30.read()) && esl_seteq<1,1,1>(x_data_0_vld_out.read(), ap_const_logic_1))) { ap_NS_fsm = ap_ST_fsm_state31; } else { ap_NS_fsm = ap_ST_fsm_state30; } break; case 16777216 : if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state31.read()) && esl_seteq<1,1,1>(y_data_1_ack_in.read(), ap_const_logic_1))) { ap_NS_fsm = ap_ST_fsm_state32; } else { ap_NS_fsm = ap_ST_fsm_state31; } break; case 33554432 : if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state32.read()) && esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_state.read()[0]) && esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_state.read()[0]) && esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_state.read()[0]) && !(esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_ack_in.read()) || esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_ack_in.read()) || esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_ack_in.read())))) { ap_NS_fsm = ap_ST_fsm_state1; } else { ap_NS_fsm = ap_ST_fsm_state32; } break; default : ap_NS_fsm = (sc_lv<26>) ("XXXXXXXXXXXXXXXXXXXXXXXXXX"); break; } } void x_order_fir::thread_hdltv_gen() { const char* dump_tv = std::getenv("AP_WRITE_TV"); if (!(dump_tv && string(dump_tv) == "on")) return; wait(); mHdltvinHandle << "[ " << endl; mHdltvoutHandle << "[ " << endl; int ap_cycleNo = 0; while (1) { wait(); const char* mComma = ap_cycleNo == 0 ? " " : ", " ; mHdltvinHandle << mComma << "{" << " \"ap_rst_n\" : \"" << ap_rst_n.read() << "\" "; mHdltvoutHandle << mComma << "{" << " \"m_axi_gmem_AWVALID\" : \"" << m_axi_gmem_AWVALID.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_AWREADY\" : \"" << m_axi_gmem_AWREADY.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_AWADDR\" : \"" << m_axi_gmem_AWADDR.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_AWID\" : \"" << m_axi_gmem_AWID.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_AWLEN\" : \"" << m_axi_gmem_AWLEN.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_AWSIZE\" : \"" << m_axi_gmem_AWSIZE.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_AWBURST\" : \"" << m_axi_gmem_AWBURST.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_AWLOCK\" : \"" << m_axi_gmem_AWLOCK.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_AWCACHE\" : \"" << m_axi_gmem_AWCACHE.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_AWPROT\" : \"" << m_axi_gmem_AWPROT.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_AWQOS\" : \"" << m_axi_gmem_AWQOS.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_AWREGION\" : \"" << m_axi_gmem_AWREGION.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_AWUSER\" : \"" << m_axi_gmem_AWUSER.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_WVALID\" : \"" << m_axi_gmem_WVALID.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_WREADY\" : \"" << m_axi_gmem_WREADY.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_WDATA\" : \"" << m_axi_gmem_WDATA.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_WSTRB\" : \"" << m_axi_gmem_WSTRB.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_WLAST\" : \"" << m_axi_gmem_WLAST.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_WID\" : \"" << m_axi_gmem_WID.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_WUSER\" : \"" << m_axi_gmem_WUSER.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARVALID\" : \"" << m_axi_gmem_ARVALID.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_ARREADY\" : \"" << m_axi_gmem_ARREADY.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARADDR\" : \"" << m_axi_gmem_ARADDR.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARID\" : \"" << m_axi_gmem_ARID.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARLEN\" : \"" << m_axi_gmem_ARLEN.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARSIZE\" : \"" << m_axi_gmem_ARSIZE.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARBURST\" : \"" << m_axi_gmem_ARBURST.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARLOCK\" : \"" << m_axi_gmem_ARLOCK.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARCACHE\" : \"" << m_axi_gmem_ARCACHE.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARPROT\" : \"" << m_axi_gmem_ARPROT.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARQOS\" : \"" << m_axi_gmem_ARQOS.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARREGION\" : \"" << m_axi_gmem_ARREGION.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARUSER\" : \"" << m_axi_gmem_ARUSER.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_RVALID\" : \"" << m_axi_gmem_RVALID.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_RREADY\" : \"" << m_axi_gmem_RREADY.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_RDATA\" : \"" << m_axi_gmem_RDATA.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_RLAST\" : \"" << m_axi_gmem_RLAST.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_RID\" : \"" << m_axi_gmem_RID.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_RUSER\" : \"" << m_axi_gmem_RUSER.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_RRESP\" : \"" << m_axi_gmem_RRESP.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_BVALID\" : \"" << m_axi_gmem_BVALID.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_BREADY\" : \"" << m_axi_gmem_BREADY.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_BRESP\" : \"" << m_axi_gmem_BRESP.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_BID\" : \"" << m_axi_gmem_BID.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_BUSER\" : \"" << m_axi_gmem_BUSER.read() << "\" "; mHdltvoutHandle << " , " << " \"y_TDATA\" : \"" << y_TDATA.read() << "\" "; mHdltvoutHandle << " , " << " \"y_TVALID\" : \"" << y_TVALID.read() << "\" "; mHdltvinHandle << " , " << " \"y_TREADY\" : \"" << y_TREADY.read() << "\" "; mHdltvoutHandle << " , " << " \"y_TUSER\" : \"" << y_TUSER.read() << "\" "; mHdltvoutHandle << " , " << " \"y_TLAST\" : \"" << y_TLAST.read() << "\" "; mHdltvinHandle << " , " << " \"x_TDATA\" : \"" << x_TDATA.read() << "\" "; mHdltvinHandle << " , " << " \"x_TVALID\" : \"" << x_TVALID.read() << "\" "; mHdltvoutHandle << " , " << " \"x_TREADY\" : \"" << x_TREADY.read() << "\" "; mHdltvinHandle << " , " << " \"x_TUSER\" : \"" << x_TUSER.read() << "\" "; mHdltvinHandle << " , " << " \"x_TLAST\" : \"" << x_TLAST.read() << "\" "; mHdltvinHandle << " , " << " \"s_axi_AXILiteS_AWVALID\" : \"" << s_axi_AXILiteS_AWVALID.read() << "\" "; mHdltvoutHandle << " , " << " \"s_axi_AXILiteS_AWREADY\" : \"" << s_axi_AXILiteS_AWREADY.read() << "\" "; mHdltvinHandle << " , " << " \"s_axi_AXILiteS_AWADDR\" : \"" << s_axi_AXILiteS_AWADDR.read() << "\" "; mHdltvinHandle << " , " << " \"s_axi_AXILiteS_WVALID\" : \"" << s_axi_AXILiteS_WVALID.read() << "\" "; mHdltvoutHandle << " , " << " \"s_axi_AXILiteS_WREADY\" : \"" << s_axi_AXILiteS_WREADY.read() << "\" "; mHdltvinHandle << " , " << " \"s_axi_AXILiteS_WDATA\" : \"" << s_axi_AXILiteS_WDATA.read() << "\" "; mHdltvinHandle << " , " << " \"s_axi_AXILiteS_WSTRB\" : \"" << s_axi_AXILiteS_WSTRB.read() << "\" "; mHdltvinHandle << " , " << " \"s_axi_AXILiteS_ARVALID\" : \"" << s_axi_AXILiteS_ARVALID.read() << "\" "; mHdltvoutHandle << " , " << " \"s_axi_AXILiteS_ARREADY\" : \"" << s_axi_AXILiteS_ARREADY.read() << "\" "; mHdltvinHandle << " , " << " \"s_axi_AXILiteS_ARADDR\" : \"" << s_axi_AXILiteS_ARADDR.read() << "\" "; mHdltvoutHandle << " , " << " \"s_axi_AXILiteS_RVALID\" : \"" << s_axi_AXILiteS_RVALID.read() << "\" "; mHdltvinHandle << " , " << " \"s_axi_AXILiteS_RREADY\" : \"" << s_axi_AXILiteS_RREADY.read() << "\" "; mHdltvoutHandle << " , " << " \"s_axi_AXILiteS_RDATA\" : \"" << s_axi_AXILiteS_RDATA.read() << "\" "; mHdltvoutHandle << " , " << " \"s_axi_AXILiteS_RRESP\" : \"" << s_axi_AXILiteS_RRESP.read() << "\" "; mHdltvoutHandle << " , " << " \"s_axi_AXILiteS_BVALID\" : \"" << s_axi_AXILiteS_BVALID.read() << "\" "; mHdltvinHandle << " , " << " \"s_axi_AXILiteS_BREADY\" : \"" << s_axi_AXILiteS_BREADY.read() << "\" "; mHdltvoutHandle << " , " << " \"s_axi_AXILiteS_BRESP\" : \"" << s_axi_AXILiteS_BRESP.read() << "\" "; mHdltvoutHandle << " , " << " \"interrupt\" : \"" << interrupt.read() << "\" "; mHdltvinHandle << "}" << std::endl; mHdltvoutHandle << "}" << std::endl; ap_cycleNo++; } } }
46.94216
519
0.69364
xupsh
090fd6e6ba328840af358250e489abbf6db83d71
817
cpp
C++
4.27/PlayFabPlugin/PlayFab/Source/PlayFabCommon/Private/PlayFabCommonSettings.cpp
parnic-sks/UnrealMarketplacePlugin
87a9d392de53d2031a3ceafbc79ab86d86ca3a33
[ "Apache-2.0" ]
null
null
null
4.27/PlayFabPlugin/PlayFab/Source/PlayFabCommon/Private/PlayFabCommonSettings.cpp
parnic-sks/UnrealMarketplacePlugin
87a9d392de53d2031a3ceafbc79ab86d86ca3a33
[ "Apache-2.0" ]
null
null
null
4.27/PlayFabPlugin/PlayFab/Source/PlayFabCommon/Private/PlayFabCommonSettings.cpp
parnic-sks/UnrealMarketplacePlugin
87a9d392de53d2031a3ceafbc79ab86d86ca3a33
[ "Apache-2.0" ]
null
null
null
////////////////////////////////////////////////////// // Copyright (C) Microsoft. 2018. All rights reserved. ////////////////////////////////////////////////////// #include "PlayFabCommonSettings.h" namespace PlayFabCommon { const FString PlayFabCommonSettings::sdkVersion = "1.70.211209"; const FString PlayFabCommonSettings::buildIdentifier = "jbuild_unrealmarketplaceplugin_sdk-unrealslave-6_0"; const FString PlayFabCommonSettings::versionString = "UE4MKPL-1.70.211209"; FString PlayFabCommonSettings::clientSessionTicket; FString PlayFabCommonSettings::entityToken; FString PlayFabCommonSettings::connectionString; FString PlayFabCommonSettings::photonRealtimeAppId; FString PlayFabCommonSettings::photonTurnbasedAppId; FString PlayFabCommonSettings::photonChatAppId; }
37.136364
112
0.69645
parnic-sks
09102ed991acec6383ecdecda5e7412b631308c3
38,522
hxx
C++
include/opengm/functions/constraint_functions/label_order_function.hxx
jasjuang/opengm
3c098e91244c98dbd3aafdc5e3a54dad67b7dfd9
[ "MIT" ]
318
2015-01-07T15:22:02.000Z
2022-01-22T10:10:29.000Z
include/opengm/functions/constraint_functions/label_order_function.hxx
jasjuang/opengm
3c098e91244c98dbd3aafdc5e3a54dad67b7dfd9
[ "MIT" ]
89
2015-03-24T14:33:01.000Z
2020-07-10T13:59:13.000Z
include/opengm/functions/constraint_functions/label_order_function.hxx
jasjuang/opengm
3c098e91244c98dbd3aafdc5e3a54dad67b7dfd9
[ "MIT" ]
119
2015-01-13T08:35:03.000Z
2022-03-01T01:49:08.000Z
#ifndef OPENGM_LABEL_ORDER_FUNCTION_HXX_ #define OPENGM_LABEL_ORDER_FUNCTION_HXX_ #include <algorithm> #include <vector> #include <cmath> #include <opengm/opengm.hxx> #include <opengm/functions/function_registration.hxx> #include <opengm/utilities/subsequence_iterator.hxx> #include <opengm/functions/constraint_functions/linear_constraint_function_base.hxx> #include <opengm/datastructures/linear_constraint.hxx> namespace opengm { /********************* * class definition * *********************/ template<class VALUE_TYPE, class INDEX_TYPE = size_t, class LABEL_TYPE = size_t> class LabelOrderFunction : public LinearConstraintFunctionBase<LabelOrderFunction<VALUE_TYPE,INDEX_TYPE, LABEL_TYPE> > { public: // public function properties static const bool useSingleConstraint_ = true; static const bool useMultipleConstraints_ = false; // typedefs typedef LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE> LinearConstraintFunctionType; typedef LinearConstraintFunctionBase<LinearConstraintFunctionType> LinearConstraintFunctionBaseType; typedef LinearConstraintFunctionTraits<LinearConstraintFunctionType> LinearConstraintFunctionTraitsType; typedef typename LinearConstraintFunctionTraitsType::ValueType ValueType; typedef typename LinearConstraintFunctionTraitsType::IndexType IndexType; typedef typename LinearConstraintFunctionTraitsType::LabelType LabelType; typedef std::vector<ValueType> LabelOrderType; typedef typename LinearConstraintFunctionTraitsType::LinearConstraintType LinearConstraintType; typedef typename LinearConstraintFunctionTraitsType::LinearConstraintsContainerType LinearConstraintsContainerType; typedef typename LinearConstraintFunctionTraitsType::LinearConstraintsIteratorType LinearConstraintsIteratorType; typedef typename LinearConstraintFunctionTraitsType::IndicatorVariablesContainerType IndicatorVariablesContainerType; typedef typename LinearConstraintFunctionTraitsType::IndicatorVariablesIteratorType IndicatorVariablesIteratorType; typedef typename LinearConstraintFunctionTraitsType::VariableLabelPairsIteratorType VariableLabelPairsIteratorType; typedef typename LinearConstraintFunctionTraitsType::ViolatedLinearConstraintsIteratorType ViolatedLinearConstraintsIteratorType; typedef typename LinearConstraintFunctionTraitsType::ViolatedLinearConstraintsWeightsContainerType ViolatedLinearConstraintsWeightsContainerType; typedef typename LinearConstraintFunctionTraitsType::ViolatedLinearConstraintsWeightsIteratorType ViolatedLinearConstraintsWeightsIteratorType; // constructors LabelOrderFunction(); LabelOrderFunction(const LabelType numLabelsVar1, const LabelType numLabelsVar2, const LabelOrderType& labelOrder, const ValueType returnValid = 0.0, const ValueType returnInvalid = 1.0); template <class ITERATOR_TYPE> LabelOrderFunction(const LabelType numLabelsVar1, const LabelType numLabelsVar2, ITERATOR_TYPE labelOrderBegin, const ValueType returnValid = 0.0, const ValueType returnInvalid = 1.0); ~LabelOrderFunction(); // function access template<class Iterator> ValueType operator()(Iterator statesBegin) const; // function evaluation size_t shape(const size_t i) const; // number of labels of the indicated input variable size_t dimension() const; // number of input variables size_t size() const; // number of parameters // specializations ValueType min() const; ValueType max() const; MinMaxFunctor<ValueType> minMax() const; protected: // storage static const size_t dimension_ = 2; LabelType numLabelsVar1_; LabelType numLabelsVar2_; size_t size_; LabelOrderType labelOrder_; ValueType returnValid_; ValueType returnInvalid_; LinearConstraintsContainerType constraints_; mutable std::vector<size_t> violatedConstraintsIds_; mutable ViolatedLinearConstraintsWeightsContainerType violatedConstraintsWeights_; IndicatorVariablesContainerType indicatorVariableList_; // implementations for LinearConstraintFunctionBase LinearConstraintsIteratorType linearConstraintsBegin_impl() const; LinearConstraintsIteratorType linearConstraintsEnd_impl() const; IndicatorVariablesIteratorType indicatorVariablesOrderBegin_impl() const; IndicatorVariablesIteratorType indicatorVariablesOrderEnd_impl() const; template <class LABEL_ITERATOR> void challenge_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const; template <class LABEL_ITERATOR> void challengeRelaxed_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const; // sanity check bool checkLabelOrder() const; // helper functions void fillIndicatorVariableList(); void createConstraints(); // friends friend class FunctionSerialization<LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE> >; friend class opengm::LinearConstraintFunctionBase<LabelOrderFunction<VALUE_TYPE,INDEX_TYPE, LABEL_TYPE> >; }; template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> struct LinearConstraintFunctionTraits<LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE> > { // typedefs typedef VALUE_TYPE ValueType; typedef INDEX_TYPE IndexType; typedef LABEL_TYPE LabelType; typedef LinearConstraint<ValueType, IndexType, LabelType> LinearConstraintType; typedef std::vector<LinearConstraintType> LinearConstraintsContainerType; typedef typename LinearConstraintsContainerType::const_iterator LinearConstraintsIteratorType; typedef typename LinearConstraintType::IndicatorVariablesContainerType IndicatorVariablesContainerType; typedef typename LinearConstraintType::IndicatorVariablesIteratorType IndicatorVariablesIteratorType; typedef typename LinearConstraintType::VariableLabelPairsIteratorType VariableLabelPairsIteratorType; typedef SubsequenceIterator<LinearConstraintsIteratorType, typename std::vector<size_t>::const_iterator> ViolatedLinearConstraintsIteratorType; typedef std::vector<double> ViolatedLinearConstraintsWeightsContainerType; typedef typename ViolatedLinearConstraintsWeightsContainerType::const_iterator ViolatedLinearConstraintsWeightsIteratorType; }; /// \cond HIDDEN_SYMBOLS /// FunctionRegistration template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> struct FunctionRegistration<LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE> > { enum ID { // TODO set final Id Id = opengm::FUNCTION_TYPE_ID_OFFSET - 2 }; }; /// FunctionSerialization template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> class FunctionSerialization<LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE> > { public: typedef typename LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::ValueType ValueType; static size_t indexSequenceSize(const LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>&); static size_t valueSequenceSize(const LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>&); template<class INDEX_OUTPUT_ITERATOR, class VALUE_OUTPUT_ITERATOR> static void serialize(const LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>&, INDEX_OUTPUT_ITERATOR, VALUE_OUTPUT_ITERATOR); template<class INDEX_INPUT_ITERATOR, class VALUE_INPUT_ITERATOR> static void deserialize( INDEX_INPUT_ITERATOR, VALUE_INPUT_ITERATOR, LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>&); }; /// \endcond /*********************** * class documentation * ***********************/ /*! \file label_order_function.hxx * \brief Provides implementation of a label order function. */ /*! \class LabelOrderFunction * \brief A linear constraint function class ensuring the correct label order * for two variables. * * This class implements a linear constraint function which ensures the correct * label order for two variables. Each label is associated with a weight and * the function checks the condition \f$w(l_1) \leq w(l_2)\f$ where * \f$w(l_1)\f$ is the weight of the label of the first variable and * \f$w(l_2)\f$ is the weight of the label of the second variable. * * \tparam VALUE_TYPE Value type. * \tparam INDEX_TYPE Index type. * \tparam LABEL_TYPE Label type. * * \ingroup functions */ /*! \var LabelOrderFunction::useSingleConstraint_ * \brief Describe the label order constraint in one single linear constraint. * * The label order constraint is described by the following linear constraint: * \f[ * \sum_i c_i \cdot v^0_i - \sum_j c_j \cdot v^1_j \quad \leq \quad 0. * \f] * Where \f$c_i\f$ is the weight for label i, \f$v^0_i\f$ is the indicator * variable of variable 0 which is 1 if variable 0 is set to label i and 0 * otherwise and \f$v^1_j\f$ is the indicator variable of variable 1. * * \note LabelOrderFunction::useSingleConstraint_ can be used in combination * with LabelOrderFunction::useMultipleConstraints_ in this case both * descriptions of the label order constraint are considered. At least * one of both variables has to be set to true. */ /*! \var LabelOrderFunction::useMultipleConstraints_ * \brief Describe the label order constraint in multiple linear constraints. * * The label order constraint is described by the following set of linear * constraints: * \f[ * c_i \cdot v^0_i - \sum_j c_j \cdot v^1_j \quad \leq \quad 0 \qquad \forall i \in \{0, ..., n - 1\}. * \f] * Where \f$c_i\f$ is the weight for label i, \f$v^0_i\f$ is the indicator * variable of variable 0 which is 1 if variable 0 is set to label i and 0 * otherwise, \f$v^1_j\f$ is the indicator variable of variable 1 and n is the * number of labels of variable 0. * * \note LabelOrderFunction::useMultipleConstraints_ can be used in combination * with LabelOrderFunction::useSingleConstraint_ in this case both * descriptions of the label order constraint are considered. At least * one of both variables has to be set to true. */ /*! \typedef LabelOrderFunction::LinearConstraintFunctionType * \brief Typedef of the LabelOrderFunction class with appropriate * template parameter. */ /*! \typedef LabelOrderFunction::LinearConstraintFunctionBaseType * \brief Typedef of the LinearConstraintFunctionBase class with appropriate * template parameter. */ /*! \typedef LabelOrderFunction::LinearConstraintFunctionTraitsType * \brief Typedef of the LinearConstraintFunctionTraits class with appropriate * template parameter. */ /*! \typedef LabelOrderFunction::ValueType * \brief Typedef of the VALUE_TYPE template parameter type from the class * LabelOrderFunction. */ /*! \typedef LabelOrderFunction::IndexType * \brief Typedef of the INDEX_TYPE template parameter type from the class * LabelOrderFunction. */ /*! \typedef LabelOrderFunction::LabelType * \brief Typedef of the LABEL_TYPE template parameter type from the class * LabelOrderFunction. */ /*! \typedef LabelOrderFunction::LabelOrderType * \brief Type to store the weights of the label order. */ /*! \typedef LabelOrderFunction::LinearConstraintType * \brief Typedef of the LinearConstraint class which is used to represent * linear constraints. */ /*! \typedef LabelOrderFunction::LinearConstraintsContainerType * \brief Defines the linear constraints container type which is used to store * multiple linear constraints. */ /*! \typedef LabelOrderFunction::LinearConstraintsIteratorType * \brief Defines the linear constraints container iterator type which is used * to iterate over the set of linear constraints. */ /*! \typedef LabelOrderFunction::IndicatorVariablesContainerType * \brief Defines the indicator variables container type which is used to store * the indicator variables used by the linear constraint function. */ /*! \typedef LabelOrderFunction::IndicatorVariablesIteratorType * \brief Defines the indicator variables container iterator type which is used * to iterate over the indicator variables used by the linear constraint * function. */ /*! \typedef LabelOrderFunction::VariableLabelPairsIteratorType * \brief Defines the variable label pairs iterator type which is used * to iterate over the variable label pairs of an indicator variable. */ /*! \typedef LabelOrderFunction::ViolatedLinearConstraintsIteratorType * \brief Defines the violated linear constraints iterator type which is used * to iterate over the set of violated linear constraints. */ /*! \typedef LabelOrderFunction::ViolatedLinearConstraintsWeightsContainerType * \brief Defines the violated linear constraints weights container type which * is used to store the weights of the violated linear constraints. */ /*! \typedef LabelOrderFunction::ViolatedLinearConstraintsWeightsIteratorType * \brief Defines the violated linear constraints weights iterator type which * is used to iterate over the weights of the violated linear * constraints. */ /*! \fn LabelOrderFunction::LabelOrderFunction() * \brief LabelOrderFunction constructor. * * This constructor will create an empty LabelOrderFunction. */ /*! \fn LabelOrderFunction::LabelOrderFunction(const LabelType numLabelsVar1, const LabelType numLabelsVar2, const LabelOrderType& labelOrder, const ValueType returnValid = 0.0, const ValueType returnInvalid = 1.0) * \brief LabelOrderFunction constructor. * * This constructor will create a LabelOrderFunction. * * \param[in] numLabelsVar1 Number of labels for the first variable. * \param[in] numLabelsVar2 Number of labels for the second variable. * \param[in] labelOrder Weights for the label order. * \param[in] returnValid The value which will be returned by the function * evaluation if no constraint is violated. * \param[in] returnInvalid The value which will be returned by the function * evaluation if at least one constraint is violated. */ /*! \fn LabelOrderFunction::LabelOrderFunction(const LabelType numLabelsVar1, const LabelType numLabelsVar2, ITERATOR_TYPE labelOrderBegin, const ValueType returnValid = 0.0, const ValueType returnInvalid = 1.0) * \brief LabelOrderFunction constructor. * * This constructor will create a LabelOrderFunction. * * \tparam ITERATOR_TYPE Iterator to iterate over the weights of the label * order. * * \param[in] numLabelsVar1 Number of labels for the first variable. * \param[in] numLabelsVar2 Number of labels for the second variable. * \param[in] labelOrderBegin Iterator pointing to the begin of the weights for * the label order. * \param[in] labelOrderBegin Iterator pointing to the end of the weights for * the label order. * \param[in] returnValid The value which will be returned by the function * evaluation if no constraint is violated. * \param[in] returnInvalid The value which will be returned by the function * evaluation if at least one constraint is violated. */ /*! \fn LabelOrderFunction::~LabelOrderFunction() * \brief LabelOrderFunction destructor. */ /*! \fn LabelOrderFunction::ValueType LabelOrderFunction::operator()(Iterator statesBegin) const * \brief Function evaluation. * * \param[in] statesBegin Iterator pointing to the begin of a sequence of * labels for the variables of the function. * * \return LabelOrderFunction::returnValid_ if no constraint is violated * by the labeling. LabelOrderFunction::returnInvalid_ if at * least one constraint is violated by the labeling. */ /*! \fn size_t LabelOrderFunction::shape(const size_t i) const * \brief Number of labels of the indicated input variable. * * \param[in] i Index of the variable. * * \return Returns the number of labels of the i-th variable. */ /*! \fn size_t LabelOrderFunction::dimension() const * \brief Number of input variables. * * \return Returns the number of variables. */ /*! \fn size_t LabelOrderFunction::size() const * \brief Number of parameters. * * \return Returns the number of parameters. */ /*! \fn LabelOrderFunction::ValueType LabelOrderFunction::min() const * \brief Minimum value of the label order function. * * \return Returns the minimum value of LabelOrderFunction::returnValid_ * and LabelOrderFunction::returnInvalid_. */ /*! \fn LabelOrderFunction::ValueType LabelOrderFunction::max() const * \brief Maximum value of the label order function. * * \return Returns the maximum value of LabelOrderFunction::returnValid_ * and LabelOrderFunction::returnInvalid_. */ /*! \fn MinMaxFunctor LabelOrderFunction::minMax() const * \brief Get minimum and maximum at the same time. * * \return Returns a functor containing the minimum and the maximum value of * the label order function. */ /*! \var LabelOrderFunction::dimension_ * \brief The dimension of the label order function. */ /*! \var LabelOrderFunction::numLabelsVar1_ * \brief The number of labels of the first variable. */ /*! \var LabelOrderFunction::numLabelsVar2_ * \brief The number of labels of the second variable. */ /*! \var LabelOrderFunction::size_ * \brief Stores the size of the label order function. */ /*! \var LabelOrderFunction::labelOrder_ * \brief The weights defining the label order. */ /*! \var LabelOrderFunction::returnValid_ * \brief Stores the return value of LabelOrderFunction::operator() if no * constraint is violated. */ /*! \var LabelOrderFunction::returnInvalid_ * \brief Stores the return value of LabelOrderFunction::operator() if at * least one constraint is violated. */ /*! \var LabelOrderFunction::constraints_ * \brief Stores the linear constraints of the label order function. */ /*! \var LabelOrderFunction::violatedConstraintsIds_ * \brief Stores the indices of the violated constraints which are detected by * LabelOrderFunction::challenge and * LabelOrderFunction::challengeRelaxed. */ /*! \var LabelOrderFunction::violatedConstraintsWeights_ * \brief Stores the weights of the violated constraints which are detected by * LabelOrderFunction::challenge and * LabelOrderFunction::challengeRelaxed. */ /*! \var LabelOrderFunction::indicatorVariableList_ * \brief A list of all indicator variables present in the label order * function. */ /*! \fn LabelOrderFunction::LinearConstraintsIteratorType LabelOrderFunction::linearConstraintsBegin_impl() const * \brief Implementation of * LinearConstraintFunctionBase::linearConstraintsBegin. */ /*! \fn LabelOrderFunction::LinearConstraintsIteratorType LabelOrderFunction::linearConstraintsEnd_impl() const * \brief Implementation of LinearConstraintFunctionBase::linearConstraintsEnd. */ /*! \fn LabelOrderFunction::IndicatorVariablesIteratorType LabelOrderFunction::indicatorVariablesOrderBegin_impl() const * \brief Implementation of * LinearConstraintFunctionBase::indicatorVariablesOrderBegin. */ /*! \fn LabelOrderFunction::IndicatorVariablesIteratorType LabelOrderFunction::indicatorVariablesOrderEnd_impl() const * \brief Implementation of * LinearConstraintFunctionBase::indicatorVariablesOrderEnd. */ /*! \fn void LabelOrderFunction::challenge_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const * \brief Implementation of LinearConstraintFunctionBase::challenge. */ /*! \fn void LabelOrderFunction::challengeRelaxed_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const * \brief Implementation of LinearConstraintFunctionBase::challengeRelaxed. */ /*! \fn bool LabelOrderFunction::checkLabelOrder() const * \brief Check label order weights. Only used for assertion in debug mode. * * \return Returns true if the number of weights is large enough to define a * weight for each label of both variables. False otherwise. */ /*! \fn bool LabelOrderFunction::fillIndicatorVariableList() * \brief Helper function to fill LabelOrderFunction::indicatorVariableList_ * with all indicator variables used by the label order function. */ /*! \fn bool LabelOrderFunction::createConstraints() * \brief Helper function to create all linear constraints which are implied by * the label order function. */ /****************** * implementation * ******************/ template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::LabelOrderFunction() : numLabelsVar1_(), numLabelsVar2_(), size_(), labelOrder_(), returnValid_(), returnInvalid_(), constraints_(), violatedConstraintsIds_(), violatedConstraintsWeights_(), indicatorVariableList_() { if(!(useSingleConstraint_ || useMultipleConstraints_)) { throw opengm::RuntimeError("Unsupported configuration for label order function. At least one of LabelOrderFunction::useSingleConstraint_ and LabelOrderFunction::useMultipleConstraints_ has to be set to true."); } } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::LabelOrderFunction(const LabelType numLabelsVar1, const LabelType numLabelsVar2, const LabelOrderType& labelOrder, const ValueType returnValid, const ValueType returnInvalid) : numLabelsVar1_(numLabelsVar1), numLabelsVar2_(numLabelsVar2), size_(numLabelsVar1_ * numLabelsVar2_), labelOrder_(labelOrder), returnValid_(returnValid), returnInvalid_(returnInvalid), constraints_((useSingleConstraint_ ? 1 : 0) + (useMultipleConstraints_ ? numLabelsVar1_ : 0)), violatedConstraintsIds_((useSingleConstraint_ ? 1 : 0) + (useMultipleConstraints_ ? numLabelsVar1_ : 0)), violatedConstraintsWeights_((useSingleConstraint_ ? 1 : 0) + (useMultipleConstraints_ ? numLabelsVar1_ : 0)), indicatorVariableList_(numLabelsVar1_ + numLabelsVar2_) { OPENGM_ASSERT(checkLabelOrder()); if(!(useSingleConstraint_ || useMultipleConstraints_)) { throw opengm::RuntimeError("Unsupported configuration for label order function. At least one of LabelOrderFunction::useSingleConstraint_ and LabelOrderFunction::useMultipleConstraints_ has to be set to true."); } // fill indicator variable list fillIndicatorVariableList(); // create linear constraints createConstraints(); } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> template <class ITERATOR_TYPE> inline LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::LabelOrderFunction(const LabelType numLabelsVar1, const LabelType numLabelsVar2, ITERATOR_TYPE labelOrderBegin, const ValueType returnValid, const ValueType returnInvalid) : numLabelsVar1_(numLabelsVar1), numLabelsVar2_(numLabelsVar2), size_(numLabelsVar1_ * numLabelsVar2_), labelOrder_(labelOrderBegin, labelOrderBegin + std::max(numLabelsVar1_, numLabelsVar2_)), returnValid_(returnValid), returnInvalid_(returnInvalid), constraints_((useSingleConstraint_ ? 1 : 0) + (useMultipleConstraints_ ? numLabelsVar1_ : 0)), violatedConstraintsIds_((useSingleConstraint_ ? 1 : 0) + (useMultipleConstraints_ ? numLabelsVar1_ : 0)), violatedConstraintsWeights_((useSingleConstraint_ ? 1 : 0) + (useMultipleConstraints_ ? numLabelsVar1_ : 0)), indicatorVariableList_(numLabelsVar1_ + numLabelsVar2_) { OPENGM_ASSERT(checkLabelOrder()); if(!(useSingleConstraint_ || useMultipleConstraints_)) { throw opengm::RuntimeError("Unsupported configuration for label order function. At least one of LabelOrderFunction::useSingleConstraint_ and LabelOrderFunction::useMultipleConstraints_ has to be set to true."); } // fill indicator variable list fillIndicatorVariableList(); // create linear constraints createConstraints(); } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::~LabelOrderFunction() { } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> template<class Iterator> inline typename LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::ValueType LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::operator()(Iterator statesBegin) const { if(labelOrder_[statesBegin[0]] <= labelOrder_[statesBegin[1]]) { return returnValid_; } else { return returnInvalid_; } } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline size_t LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::shape(const size_t i) const { OPENGM_ASSERT(i < dimension_); return (i==0 ? numLabelsVar1_ : numLabelsVar2_); } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline size_t LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::dimension() const { return dimension_; } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline size_t LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::size() const { return size_; } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline typename LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::ValueType LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::min() const { return returnValid_ < returnInvalid_ ? returnValid_ : returnInvalid_; } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline typename LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::ValueType LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::max() const { return returnValid_ > returnInvalid_ ? returnValid_ : returnInvalid_; } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline MinMaxFunctor<typename LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::ValueType> LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::minMax() const { if(returnValid_ < returnInvalid_) { return MinMaxFunctor<VALUE_TYPE>(returnValid_, returnInvalid_); } else { return MinMaxFunctor<VALUE_TYPE>(returnInvalid_, returnValid_); } } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline typename LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::LinearConstraintsIteratorType LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::linearConstraintsBegin_impl() const { return constraints_.begin(); } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline typename LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::LinearConstraintsIteratorType LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::linearConstraintsEnd_impl() const { return constraints_.end(); } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline typename LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::IndicatorVariablesIteratorType LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::indicatorVariablesOrderBegin_impl() const { return indicatorVariableList_.begin(); } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline typename LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::IndicatorVariablesIteratorType LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::indicatorVariablesOrderEnd_impl() const { return indicatorVariableList_.end(); } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> template <class LABEL_ITERATOR> inline void LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::challenge_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance) const { const ValueType weight = labelOrder_[labelingBegin[0]] - labelOrder_[labelingBegin[1]]; if(weight <= tolerance) { violatedConstraintsBegin = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), 0); violatedConstraintsEnd = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), 0); violatedConstraintsWeightsBegin = violatedConstraintsWeights_.begin(); return; } else { if(useSingleConstraint_) { violatedConstraintsIds_[0] = 0; violatedConstraintsWeights_[0] = weight; } if(useMultipleConstraints_) { violatedConstraintsIds_[(useSingleConstraint_ ? 1 : 0)] = labelingBegin[0] + (useSingleConstraint_ ? 1 : 0); violatedConstraintsWeights_[(useSingleConstraint_ ? 1 : 0)] = weight; } violatedConstraintsBegin = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), 0); violatedConstraintsEnd = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), (useSingleConstraint_ ? 1 : 0) + (useMultipleConstraints_ ? 1 : 0)); violatedConstraintsWeightsBegin = violatedConstraintsWeights_.begin(); return; } } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> template <class LABEL_ITERATOR> inline void LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::challengeRelaxed_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance) const { size_t numViolatedConstraints = 0; double weightVar2 = 0.0; for(IndexType i = 0; i < numLabelsVar2_; ++i) { weightVar2 -= labelOrder_[i] * labelingBegin[numLabelsVar1_ + i]; } double totalWeight = weightVar2; for(IndexType i = 0; i < numLabelsVar1_; ++i) { double currentWeight = (labelOrder_[i] * labelingBegin[i]); // - (); if(useSingleConstraint_) { totalWeight += currentWeight; } if(useMultipleConstraints_) { currentWeight += weightVar2; if(currentWeight > tolerance) { violatedConstraintsIds_[numViolatedConstraints] = i + (useSingleConstraint_ ? 1 : 0); violatedConstraintsWeights_[numViolatedConstraints] = currentWeight; ++numViolatedConstraints; } } } if(useSingleConstraint_) { if(totalWeight > tolerance) { violatedConstraintsIds_[numViolatedConstraints] = 0; violatedConstraintsWeights_[numViolatedConstraints] = totalWeight; ++numViolatedConstraints; } } violatedConstraintsBegin = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), 0); violatedConstraintsEnd = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), numViolatedConstraints); violatedConstraintsWeightsBegin = violatedConstraintsWeights_.begin(); } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline bool LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::checkLabelOrder() const { if(labelOrder_.size() < std::max(numLabelsVar1_, numLabelsVar2_)) { return false; } else { return true; } } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline void LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::fillIndicatorVariableList() { for(size_t i = 0; i < numLabelsVar1_; ++i) { indicatorVariableList_[i] = typename LinearConstraintType::IndicatorVariableType(IndexType(0), LabelType(i)); } for(size_t i = 0; i < numLabelsVar2_; ++i) { indicatorVariableList_[numLabelsVar1_ + i] = typename LinearConstraintType::IndicatorVariableType(IndexType(1), LabelType(i)); } } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline void LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::createConstraints() { if(useSingleConstraint_) { constraints_[0].setBound(0.0); constraints_[0].setConstraintOperator(LinearConstraintType::LinearConstraintOperatorType::LessEqual); for(size_t i = 0; i < numLabelsVar1_; ++i) { constraints_[0].add(typename LinearConstraintType::IndicatorVariableType(IndexType(0), LabelType(i)), labelOrder_[i]); } for(size_t i = 0; i < numLabelsVar2_; ++i) { constraints_[0].add(typename LinearConstraintType::IndicatorVariableType(IndexType(1), LabelType(i)), -labelOrder_[i]); } } if(useMultipleConstraints_) { for(size_t i = 0; i < numLabelsVar1_; ++i) { constraints_[i + (useSingleConstraint_ ? 1 : 0)].add(typename LinearConstraintType::IndicatorVariableType(IndexType(0), LabelType(i)), labelOrder_[i]); constraints_[i + (useSingleConstraint_ ? 1 : 0)].setBound(0.0); constraints_[i + (useSingleConstraint_ ? 1 : 0)].setConstraintOperator(LinearConstraintType::LinearConstraintOperatorType::LessEqual); for(size_t j = 0; j < numLabelsVar2_; ++j) { constraints_[i + (useSingleConstraint_ ? 1 : 0)].add(typename LinearConstraintType::IndicatorVariableType(IndexType(1), LabelType(j)), -labelOrder_[j]); } } } } /// \cond HIDDEN_SYMBOLS template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline size_t FunctionSerialization<LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE> >::indexSequenceSize(const LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>& src) { const size_t shapeSize = 2; // numLabelsVar1 and numLabelsVar2 const size_t labelOrderSize = 1; const size_t totalIndexSize = shapeSize + labelOrderSize; return totalIndexSize; } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline size_t FunctionSerialization<LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE> >::valueSequenceSize(const LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>& src) { const size_t labelOrderSize = src.labelOrder_.size(); const size_t returnSize = 2; //returnValid and returnInvalid const size_t totalValueSize = labelOrderSize + returnSize; return totalValueSize; } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> template<class INDEX_OUTPUT_ITERATOR, class VALUE_OUTPUT_ITERATOR> inline void FunctionSerialization<LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE> >::serialize(const LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>& src, INDEX_OUTPUT_ITERATOR indexOutIterator, VALUE_OUTPUT_ITERATOR valueOutIterator) { // index output // shape *indexOutIterator = src.numLabelsVar1_; ++indexOutIterator; *indexOutIterator = src.numLabelsVar2_; ++indexOutIterator; // label order size *indexOutIterator = src.labelOrder_.size(); // value output // label order for(size_t i = 0; i < src.labelOrder_.size(); ++i) { *valueOutIterator = src.labelOrder_[i]; ++valueOutIterator; } // return values *valueOutIterator = src.returnValid_; ++valueOutIterator; *valueOutIterator = src.returnInvalid_; } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> template<class INDEX_INPUT_ITERATOR, class VALUE_INPUT_ITERATOR> inline void FunctionSerialization<LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE> >::deserialize( INDEX_INPUT_ITERATOR indexInIterator, VALUE_INPUT_ITERATOR valueInIterator, LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>& dst) { // index input // shape const size_t numLabelsVar1 = *indexInIterator; ++indexInIterator; const size_t numLabelsVar2 = *indexInIterator; ++indexInIterator; // label order size const size_t labelOrderSize = *indexInIterator; // value input typename LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::LabelOrderType labelOrder(valueInIterator, valueInIterator + labelOrderSize); valueInIterator += labelOrderSize; // valid value VALUE_TYPE returnValid = *valueInIterator; ++valueInIterator; // invalid value VALUE_TYPE returnInvalid = *valueInIterator; dst = LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>(numLabelsVar1, numLabelsVar2, labelOrder, returnValid, returnInvalid); } /// \endcond } // namespace opengm #endif /* OPENGM_LABEL_ORDER_FUNCTION_HXX_ */
48.885787
361
0.741005
jasjuang
091037d464c88f3b2609bbc9a494b4f1ac29dd5d
4,219
cpp
C++
src/RayTracerLib/shapes/Box.cpp
CantTouchDis/ElTrazadoDeRayos
8975f76bcf990b94364e595b3b9f0b4128f6c56e
[ "MIT", "BSL-1.0", "MIT-0", "BSD-3-Clause" ]
null
null
null
src/RayTracerLib/shapes/Box.cpp
CantTouchDis/ElTrazadoDeRayos
8975f76bcf990b94364e595b3b9f0b4128f6c56e
[ "MIT", "BSL-1.0", "MIT-0", "BSD-3-Clause" ]
null
null
null
src/RayTracerLib/shapes/Box.cpp
CantTouchDis/ElTrazadoDeRayos
8975f76bcf990b94364e595b3b9f0b4128f6c56e
[ "MIT", "BSL-1.0", "MIT-0", "BSD-3-Clause" ]
1
2021-05-05T08:37:05.000Z
2021-05-05T08:37:05.000Z
/* The MIT License (MIT) Copyright (c) 2014 CantTouchDis <bauschp@informatik.uni-freiburg.de> Copyright (c) 2014 brio1009 <christoph1009@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. */ #include "./Box.h" #include <glm/glm.hpp> #include <algorithm> #include <cstdio> #include <limits> #include <utility> #include <vector> #include "./Constants.h" #include "../Solver.h" #include "./Ray.h" using std::vector; const char* Box::name = "Box"; // _____________________________________________________________________________ Box::Box(REAL x, REAL y, REAL z) : _rX(x), _rY(y), _rZ(z) { } // _____________________________________________________________________________ vector<REAL> Box::intersect(const Ray& ray) const { // Bring vector to unit space. Ray transRay = _inverseTransform * ray; // This is the slab method. const glm::vec4& rayDir = transRay.direction(); glm::vec4 invRayDir; invRayDir.x = (!solve::isZero(rayDir.x)) ? (1.0f / rayDir.x) : std::numeric_limits<float>::max(); invRayDir.y = (!solve::isZero(rayDir.y)) ? (1.0f / rayDir.y) : std::numeric_limits<float>::max(); invRayDir.z = (!solve::isZero(rayDir.z)) ? (1.0f / rayDir.z) : std::numeric_limits<float>::max(); invRayDir.w = 0.0f; glm::vec4 t1 = (getMinPosition() - transRay.origin()) * invRayDir; glm::vec4 t2 = (getMaxPosition() - transRay.origin()) * invRayDir; glm::vec4 tMin = glm::min(t1, t2); glm::vec4 tMax = glm::max(t1, t2); vector<REAL> hits(2); hits[0] = std::max(tMin.x, std::max(tMin.y, tMin.z)); hits[1] = std::min(tMax.x, std::min(tMax.y, tMax.z)); if (hits[1] >= hits[0]) return hits; // Else. return vector<REAL>(); } // _____________________________________________________________________________ glm::vec4 Box::getNormalAt(const glm::vec4& p) const { glm::vec4 pInObjectCoord = _inverseTransform * p; // We just have six cases (three real ones + the inverse). // Just check where we are the closest. glm::vec3 extent(_rX, _rY, _rZ); glm::vec3 dis = 0.5f * extent - glm::abs(glm::vec3(pInObjectCoord)); glm::vec4 out; if (dis.x < dis.y && dis.x < dis.z) { // Normal in x direction. if (pInObjectCoord.x <= 0) { out = glm::vec4(-1, 0, 0, 0); } else { out = glm::vec4(1, 0, 0, 0); } } else if (dis.y < dis.x && dis.y < dis.z) { // Normal in y direction. if (pInObjectCoord.y <= 0) { out = glm::vec4(0, -1, 0, 0); } else { out = glm::vec4(0, 1, 0, 0); } } else { // Normal in z direction. if (pInObjectCoord.z <= 0) { out = glm::vec4(0, 0, -1, 0); } else { out = glm::vec4(0, 0, 1, 0); } } return glm::normalize(_transformation * out); } // _____________________________________________________________________________ glm::vec4 Box::getMinPosition() const { // We just calculate the position. return glm::vec4(-0.5 * _rX, -0.5 * _rY, -0.5 * _rZ, 1.0); } // _____________________________________________________________________________ glm::vec4 Box::getMaxPosition() const { // We just calculate the position. return glm::vec4(0.5 * _rX, 0.5 * _rY, 0.5 * _rZ, 1.0); }
33.220472
80
0.670301
CantTouchDis
09175a1772e49e91cbe95ac21f6acd5fc93d53db
6,153
hpp
C++
src/math/multiprecision.hpp
yDMhaven/pinocchio
fabed17d5ad0dc1c8d251c64cfa656a0215469a5
[ "BSD-2-Clause-FreeBSD" ]
1
2020-04-07T07:23:34.000Z
2020-04-07T07:23:34.000Z
src/math/multiprecision.hpp
yDMhaven/pinocchio
fabed17d5ad0dc1c8d251c64cfa656a0215469a5
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/math/multiprecision.hpp
yDMhaven/pinocchio
fabed17d5ad0dc1c8d251c64cfa656a0215469a5
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
// // Copyright (c) 2020 INRIA // #ifndef __pinocchio_math_mutliprecision_hpp__ #define __pinocchio_math_mutliprecision_hpp__ #include "pinocchio/math/fwd.hpp" #include <boost/multiprecision/number.hpp> #include <Eigen/Dense> namespace Eigen { namespace internal { template <class Backend, boost::multiprecision::expression_template_option ExpressionTemplates, typename Scalar> struct cast_impl<boost::multiprecision::number<Backend, ExpressionTemplates>,Scalar> { #if EIGEN_VERSION_AT_LEAST(3,2,90) EIGEN_DEVICE_FUNC #endif static inline Scalar run(const boost::multiprecision::number<Backend, ExpressionTemplates> & x) { return x.template convert_to<Scalar>(); } }; } } //namespace Eigen #ifndef BOOST_MP_EIGEN_HPP // Code adapted from <boost/multiprecision/eigen.hpp> // Copyright 2018 John Maddock. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) namespace Eigen { template <class Backend, boost::multiprecision::expression_template_option ExpressionTemplates> struct NumTraits<boost::multiprecision::number<Backend, ExpressionTemplates> > { typedef boost::multiprecision::number<Backend, ExpressionTemplates> self_type; #if BOOST_VERSION / 100 % 1000 >= 68 typedef typename boost::multiprecision::scalar_result_from_possible_complex<self_type>::type Real; #else typedef self_type Real; #endif typedef self_type NonInteger; // Not correct but we can't do much better?? typedef double Literal; typedef self_type Nested; enum { #if BOOST_VERSION / 100 % 1000 >= 68 IsComplex = boost::multiprecision::number_category<self_type>::value == boost::multiprecision::number_kind_complex, #else IsComplex = 0, #endif IsInteger = boost::multiprecision::number_category<self_type>::value == boost::multiprecision::number_kind_integer, ReadCost = 1, AddCost = 4, MulCost = 8, IsSigned = std::numeric_limits<self_type>::is_specialized ? std::numeric_limits<self_type>::is_signed : true, RequireInitialization = 1 }; static Real epsilon() { return std::numeric_limits<Real>::epsilon(); } static Real dummy_precision() { return 1000 * epsilon(); } static Real highest() { return (std::numeric_limits<Real>::max)(); } static Real lowest() { return (std::numeric_limits<Real>::min)(); } static int digits10_imp(const boost::mpl::true_&) { return std::numeric_limits<Real>::digits10; } template <bool B> static int digits10_imp(const boost::mpl::bool_<B>&) { return Real::default_precision(); } static int digits10() { return digits10_imp(boost::mpl::bool_ < std::numeric_limits<Real>::digits10 && (std::numeric_limits<Real>::digits10 != INT_MAX) ? true : false > ()); } }; template <class tag, class Arg1, class Arg2, class Arg3, class Arg4> struct NumTraits<boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4> > : public NumTraits<typename boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type> { }; namespace internal { template <class Backend, boost::multiprecision::expression_template_option ExpressionTemplates, class tag, class Arg1, class Arg2, class Arg3, class Arg4> struct scalar_product_traits<boost::multiprecision::number<Backend, ExpressionTemplates>, boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4> > { // BOOST_STATIC_ASSERT(boost::is_convertible<typename boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type, boost::multiprecision::number<Backend, ExpressionTemplates> >::value, "Interoperability with this arithmetic type is not supported."); typedef boost::multiprecision::number<Backend, ExpressionTemplates> ReturnType; }; template <class tag, class Arg1, class Arg2, class Arg3, class Arg4, class Backend, boost::multiprecision::expression_template_option ExpressionTemplates> struct scalar_product_traits<boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>, boost::multiprecision::number<Backend, ExpressionTemplates> > { // BOOST_STATIC_ASSERT(boost::is_convertible<typename boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type, boost::multiprecision::number<Backend, ExpressionTemplates> >::value, "Interoperability with this arithmetic type is not supported."); typedef boost::multiprecision::number<Backend, ExpressionTemplates> ReturnType; }; template <typename Scalar> struct conj_retval; template <typename Scalar, bool IsComplex> struct conj_impl; template <class tag, class Arg1, class Arg2, class Arg3, class Arg4> struct conj_retval<boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4> > { typedef typename boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type type; }; template <class tag, class Arg1, class Arg2, class Arg3, class Arg4> struct conj_impl<boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>, true> { #if EIGEN_VERSION_AT_LEAST(3,2,90) EIGEN_DEVICE_FUNC #endif static inline typename boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type run(const typename boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>& x) { return conj(x); } }; } // namespace internal } // namespace Eigen #endif // ifndef BOOST_MP_EIGEN_HPP #endif // ifndef __pinocchio_math_mutliprecision_hpp__
41.295302
278
0.671705
yDMhaven
091bdd16b600da8268d9fca5284b072e5e926705
1,803
hpp
C++
include/variadic/detail/numerate.hpp
AnatoliyProjects/variadic
f34a973e527218e3ba0f8146ccbf478d351f6cb2
[ "BSL-1.0" ]
null
null
null
include/variadic/detail/numerate.hpp
AnatoliyProjects/variadic
f34a973e527218e3ba0f8146ccbf478d351f6cb2
[ "BSL-1.0" ]
null
null
null
include/variadic/detail/numerate.hpp
AnatoliyProjects/variadic
f34a973e527218e3ba0f8146ccbf478d351f6cb2
[ "BSL-1.0" ]
2
2020-05-31T11:50:35.000Z
2020-06-07T18:38:12.000Z
// Copyright 2020 Anatoliy Petrov // (apetrov.projects@gmail.com) // // Distributed under the Boost Software License, Version 1.0. // // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt #ifndef VARIADIC_DETAIL_NUMERATE_HPP #define VARIADIC_DETAIL_NUMERATE_HPP /* variadic */ #include <variadic/token.hpp> //token getters /* boost */ #include <boost/preprocessor/seq/to_list.hpp> #include <boost/preprocessor/list/for_each.hpp> #include <boost/preprocessor/control/if.hpp> #include <boost/preprocessor/facilities/expand.hpp> #include <boost/preprocessor/facilities/expand.hpp> #include <boost/preprocessor/cat.hpp> // Conversion to the list is necessary to bypass the restriction on the depth // of nesting BOOST_PP_FOR loop (especially in case where VDC_EXPAND calls // directly from VDC_HANDLER) #define VDC_DETAIL_NUMERATE(expr, pos) \ BOOST_PP_LIST_FOR_EACH( \ VDC_DETAIL_NUMERATOR, \ pos, \ BOOST_PP_SEQ_TO_LIST(expr) \ ) #define VDC_DETAIL_NUMERATOR(unspec, pos, token) \ BOOST_PP_IF( \ VDC_DETAIL_GET_FLAG(token), \ VDC_DETAIL_TOKEN_NUMERATOR(token, pos), \ VDC_DETAIL_TOKEN_FN_NUMERATOR(token, pos) \ ) #define VDC_DETAIL_PAIR(a, b) a, b #define VDC_DETAIL_TOKEN_NUMERATOR(token, pos) \ BOOST_PP_IF( \ VDC_DETAIL_IS_NUMBERED(token), \ BOOST_PP_CAT( \ VDC_DETAIL_GET_STR(token), \ VDC_DETAIL_GET_POS(token, pos) \ ), \ VDC_DETAIL_GET_STR(token) \ ) #define VDC_DETAIL_TOKEN_FN_NUMERATOR(token, pos) \ BOOST_PP_IF( \ VDC_DETAIL_IS_NUMBERED(token), \ VDC_DETAIL_GET_FN(token)( VDC_DETAIL_GET_POS(token, pos) ), \ VDC_DETAIL_GET_FN(token)() \ ) #endif /* VARIADIC_DETAIL_NUMERATE_HPP */
29.557377
77
0.707709
AnatoliyProjects
091f18e0ba1f8dbb57b3151dcacdd3982b303e3b
11,739
cpp
C++
util/test/demos/d3d11/d3d11_amd_shader_extensions.cpp
orsonbraines/renderdoc
ed9ac9f7bf594f79f834ce8fa0b9717b69d13b0e
[ "MIT" ]
1
2022-02-17T21:18:24.000Z
2022-02-17T21:18:24.000Z
util/test/demos/d3d11/d3d11_amd_shader_extensions.cpp
orsonbraines/renderdoc
ed9ac9f7bf594f79f834ce8fa0b9717b69d13b0e
[ "MIT" ]
null
null
null
util/test/demos/d3d11/d3d11_amd_shader_extensions.cpp
orsonbraines/renderdoc
ed9ac9f7bf594f79f834ce8fa0b9717b69d13b0e
[ "MIT" ]
null
null
null
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2019-2022 Baldur Karlsson * * 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 "d3d11_test.h" #include "3rdparty/ags/ags_shader_intrinsics_dx11.hlsl.h" #include "3rdparty/ags/amd_ags.h" RD_TEST(D3D11_AMD_Shader_Extensions, D3D11GraphicsTest) { static constexpr const char *Description = "Tests using AMD shader extensions on D3D11."; AGS_INITIALIZE dyn_agsInitialize = NULL; AGS_DEINITIALIZE dyn_agsDeInitialize = NULL; AGS_DRIVEREXTENSIONSDX11_CREATEDEVICE dyn_agsDriverExtensionsDX11_CreateDevice = NULL; AGS_DRIVEREXTENSIONSDX11_DESTROYDEVICE dyn_agsDriverExtensionsDX11_DestroyDevice = NULL; AGSContext *ags = NULL; std::string BaryCentricPixel = R"EOSHADER( float4 main() : SV_Target0 { float2 bary = AmdDxExtShaderIntrinsics_IjBarycentricCoords( AmdDxExtShaderIntrinsicsBarycentric_LinearCenter ); float3 bary3 = float3(bary.x, bary.y, 1.0 - (bary.x + bary.y)); if(bary3.x > bary3.y && bary3.x > bary3.z) return float4(1.0f, 0.0f, 0.0f, 1.0f); else if(bary3.y > bary3.x && bary3.y > bary3.z) return float4(0.0f, 1.0f, 0.0f, 1.0f); else return float4(0.0f, 0.0f, 1.0f, 1.0f); } )EOSHADER"; std::string MaxCompute = R"EOSHADER( RWByteAddressBuffer inUAV : register(u0); RWByteAddressBuffer outUAV : register(u1); [numthreads(256, 1, 1)] void main(uint3 threadID : SV_DispatchThreadID) { // read input from source uint2 input; input.x = inUAV.Load(threadID.x * 8); input.y = inUAV.Load(threadID.x * 8 + 4); AmdDxExtShaderIntrinsics_AtomicMaxU64(outUAV, 0, input); } )EOSHADER"; void Prepare(int argc, char **argv) { D3D11GraphicsTest::Prepare(argc, argv); if(!Avail.empty()) return; std::string agsname = sizeof(void *) == 8 ? "amd_ags_x64.dll" : "amd_ags_x86.dll"; HMODULE agsLib = LoadLibraryA(agsname.c_str()); // try in local plugins folder if(!agsLib) { agsLib = LoadLibraryA( ("../../" + std::string(sizeof(void *) == 8 ? "plugins-win64/" : "plugins/win32/") + "amd/ags/" + agsname) .c_str()); } if(!agsLib) { // try in plugins folder next to renderdoc.dll HMODULE rdocmod = GetModuleHandleA("renderdoc.dll"); char path[MAX_PATH + 1] = {}; if(rdocmod) { GetModuleFileNameA(rdocmod, path, MAX_PATH); std::string tmp = path; tmp.resize(tmp.size() - (sizeof("/renderdoc.dll") - 1)); agsLib = LoadLibraryA((tmp + "/plugins/amd/ags/" + agsname).c_str()); } } if(!agsLib) { Avail = "Couldn't load AGS dll"; return; } dyn_agsInitialize = (AGS_INITIALIZE)GetProcAddress(agsLib, "agsInitialize"); dyn_agsDeInitialize = (AGS_DEINITIALIZE)GetProcAddress(agsLib, "agsDeInitialize"); dyn_agsDriverExtensionsDX11_CreateDevice = (AGS_DRIVEREXTENSIONSDX11_CREATEDEVICE)GetProcAddress( agsLib, "agsDriverExtensionsDX11_CreateDevice"); dyn_agsDriverExtensionsDX11_DestroyDevice = (AGS_DRIVEREXTENSIONSDX11_DESTROYDEVICE)GetProcAddress( agsLib, "agsDriverExtensionsDX11_DestroyDevice"); if(!dyn_agsInitialize || !dyn_agsDeInitialize || !dyn_agsDriverExtensionsDX11_CreateDevice || !dyn_agsDriverExtensionsDX11_DestroyDevice) { Avail = "AGS didn't have all necessary entry points - too old?"; return; } AGSReturnCode agsret = dyn_agsInitialize( AGS_MAKE_VERSION(AMD_AGS_VERSION_MAJOR, AMD_AGS_VERSION_MINOR, AMD_AGS_VERSION_PATCH), NULL, &ags, NULL); if(agsret != AGS_SUCCESS || ags == NULL) { Avail = "AGS couldn't initialise"; return; } ID3D11Device *ags_devHandle = NULL; ID3D11DeviceContext *ags_ctxHandle = NULL; CreateExtendedDevice(&ags_devHandle, &ags_ctxHandle); // once we've checked that we can create an extension device on an adapter, we can release it // and return ready to run if(ags_devHandle) { Avail = ""; unsigned int dummy = 0; dyn_agsDriverExtensionsDX11_DestroyDevice(ags, ags_devHandle, &dummy, ags_ctxHandle, &dummy); return; } Avail = "AGS couldn't create device on any selected adapter."; } void CreateExtendedDevice(ID3D11Device * *ags_devHandle, ID3D11DeviceContext * *ags_ctxHandle) { std::vector<IDXGIAdapterPtr> adapters = GetAdapters(); for(IDXGIAdapterPtr a : adapters) { AGSDX11DeviceCreationParams devCreate = {}; AGSDX11ExtensionParams extCreate = {}; AGSDX11ReturnedParams ret = {}; devCreate.pAdapter = a.GetInterfacePtr(); devCreate.DriverType = D3D_DRIVER_TYPE_UNKNOWN; devCreate.Flags = createFlags | (debugDevice ? D3D11_CREATE_DEVICE_DEBUG : 0); devCreate.pFeatureLevels = &feature_level; devCreate.FeatureLevels = 1; devCreate.SDKVersion = D3D11_SDK_VERSION; extCreate.uavSlot = 7; extCreate.crossfireMode = AGS_CROSSFIRE_MODE_DISABLE; extCreate.pAppName = L"RenderDoc demos"; extCreate.pEngineName = L"RenderDoc demos"; AGSReturnCode agsret = dyn_agsDriverExtensionsDX11_CreateDevice(ags, &devCreate, &extCreate, &ret); if(agsret == AGS_SUCCESS && ret.pDevice) { // don't accept devices that don't support the intrinsics we want if(!ret.extensionsSupported.intrinsics16 || !ret.extensionsSupported.intrinsics19) { unsigned int dummy = 0; dyn_agsDriverExtensionsDX11_DestroyDevice(ags, ret.pDevice, &dummy, ret.pImmediateContext, &dummy); } else { *ags_devHandle = ret.pDevice; *ags_ctxHandle = ret.pImmediateContext; return; } } } } int main() { // initialise, create window, create device, etc if(!Init()) return 3; // release the old device and swapchain dev = NULL; ctx = NULL; dev1 = NULL; dev2 = NULL; dev3 = NULL; dev4 = NULL; dev5 = NULL; ctx1 = NULL; ctx2 = NULL; ctx3 = NULL; ctx4 = NULL; annot = NULL; swapBlitVS = NULL; swapBlitPS = NULL; // and swapchain & related swap = NULL; bbTex = NULL; bbRTV = NULL; // we don't use these directly, just copy them into the real device so we know that ags is the // one to destroy the last reference to the device ID3D11Device *ags_devHandle = NULL; ID3D11DeviceContext *ags_ctxHandle = NULL; CreateExtendedDevice(&ags_devHandle, &ags_ctxHandle); dev = ags_devHandle; ctx = ags_ctxHandle; annot = ctx; // create the swapchain on the new AGS-extended device DXGI_SWAP_CHAIN_DESC swapDesc = MakeSwapchainDesc(mainWindow); HRESULT hr = fact->CreateSwapChain(dev, &swapDesc, &swap); if(FAILED(hr)) { TEST_ERROR("Couldn't create swapchain"); return 4; } hr = swap->GetBuffer(0, __uuidof(ID3D11Texture2D), (void **)&bbTex); if(FAILED(hr)) { TEST_ERROR("Couldn't get swapchain backbuffer"); return 4; } hr = dev->CreateRenderTargetView(bbTex, NULL, &bbRTV); if(FAILED(hr)) { TEST_ERROR("Couldn't create swapchain RTV"); return 4; } std::string ags_header = ags_shader_intrinsics_dx11_hlsl(); ID3DBlobPtr vsblob = Compile(D3DDefaultVertex, "main", "vs_4_0"); // can't skip optimising and still have the extensions work, sadly ID3DBlobPtr psblob = Compile(ags_header + BaryCentricPixel, "main", "ps_5_0", false); ID3DBlobPtr csblob = Compile(ags_header + MaxCompute, "main", "cs_5_0", false); CreateDefaultInputLayout(vsblob); ID3D11VertexShaderPtr vs = CreateVS(vsblob); ID3D11PixelShaderPtr ps = CreatePS(psblob); ID3D11ComputeShaderPtr cs = CreateCS(csblob); SetDebugName(cs, "cs"); ID3D11BufferPtr vb = MakeBuffer().Vertex().Data(DefaultTri); // make a simple texture so that the structured data includes texture initial states ID3D11Texture2DPtr fltTex = MakeTexture(DXGI_FORMAT_R32G32B32A32_FLOAT, 4, 4).RTV(); ID3D11RenderTargetViewPtr fltRT = MakeRTV(fltTex); const int numInputValues = 16384; std::vector<uint64_t> values; values.resize(numInputValues); uint64_t cpuMax = 0; for(uint64_t &v : values) { v = 0; for(uint32_t byte = 0; byte < 8; byte++) { uint64_t b = (rand() & 0xff0) >> 4; v |= b << (byte * 8); } cpuMax = std::max(v, cpuMax); } ID3D11BufferPtr inBuf = MakeBuffer() .UAV() .ByteAddressed() .Data(values.data()) .Size(UINT(sizeof(uint64_t) * values.size())); ID3D11BufferPtr outBuf = MakeBuffer().UAV().ByteAddressed().Size(32); SetDebugName(outBuf, "outBuf"); ID3D11UnorderedAccessViewPtr inUAV = MakeUAV(inBuf).Format(DXGI_FORMAT_R32_TYPELESS); ID3D11UnorderedAccessViewPtr outUAV = MakeUAV(outBuf).Format(DXGI_FORMAT_R32_TYPELESS); while(Running()) { ctx->ClearState(); uint32_t zero[4] = {}; ctx->ClearUnorderedAccessViewUint(outUAV, zero); ClearRenderTargetView(bbRTV, {0.2f, 0.2f, 0.2f, 1.0f}); ClearRenderTargetView(fltRT, {0.2f, 0.2f, 0.2f, 1.0f}); IASetVertexBuffer(vb, sizeof(DefaultA2V), 0); ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); ctx->IASetInputLayout(defaultLayout); ctx->VSSetShader(vs, NULL, 0); ctx->PSSetShader(ps, NULL, 0); RSSetViewport({0.0f, 0.0f, (float)screenWidth, (float)screenHeight, 0.0f, 1.0f}); ctx->OMSetRenderTargets(1, &bbRTV.GetInterfacePtr(), NULL); ctx->Draw(3, 0); ctx->CSSetShader(cs, NULL, 0); ctx->CSSetUnorderedAccessViews(0, 1, &inUAV.GetInterfacePtr(), NULL); ctx->CSSetUnorderedAccessViews(1, 1, &outUAV.GetInterfacePtr(), NULL); ctx->Dispatch(numInputValues / 256, 1, 1); ctx->Flush(); std::vector<byte> output = GetBufferData(outBuf, 0, 8); uint64_t gpuMax = 0; memcpy(&gpuMax, output.data(), sizeof(uint64_t)); setMarker("cpuMax: " + std::to_string(cpuMax)); setMarker("gpuMax: " + std::to_string(gpuMax)); Present(); } dev = NULL; ctx = NULL; annot = NULL; unsigned int dummy = 0; dyn_agsDriverExtensionsDX11_DestroyDevice(ags, ags_devHandle, &dummy, ags_ctxHandle, &dummy); dyn_agsDeInitialize(ags); return 0; } }; REGISTER_TEST();
30.973615
113
0.653037
orsonbraines
091f4406216dd8f9ec0b6f5bd1801b12107496b4
316
cpp
C++
skia/src/core/SkQuadTreePicture.cpp
bonescreater/bones
618ced87a9a2061b0a7879be32b2fea263880f1b
[ "MIT" ]
16
2015-09-02T17:47:53.000Z
2022-03-01T19:12:53.000Z
src/core/SkQuadTreePicture.cpp
rgraebert/skia
33a4b46e9f24be6268855478b5c895f883fb4ac5
[ "BSD-3-Clause" ]
null
null
null
src/core/SkQuadTreePicture.cpp
rgraebert/skia
33a4b46e9f24be6268855478b5c895f883fb4ac5
[ "BSD-3-Clause" ]
6
2015-11-11T13:22:59.000Z
2022-03-01T19:13:02.000Z
/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkQuadTreePicture.h" #include "SkQuadTree.h" SkBBoxHierarchy* SkQuadTreePicture::createBBoxHierarchy() const { return SkNEW_ARGS(SkQuadTree, (fBounds)); }
21.066667
73
0.731013
bonescreater
0926ecc53d84b320e1f4c0f74bdb29549382911e
16,609
cc
C++
project2/solution/solution2.cc
nbdhhzh/CompilerProject-2020Spring
a41a09d4116a3715414f2ffba0f832cf34692736
[ "MIT" ]
null
null
null
project2/solution/solution2.cc
nbdhhzh/CompilerProject-2020Spring
a41a09d4116a3715414f2ffba0f832cf34692736
[ "MIT" ]
null
null
null
project2/solution/solution2.cc
nbdhhzh/CompilerProject-2020Spring
a41a09d4116a3715414f2ffba0f832cf34692736
[ "MIT" ]
null
null
null
// this is a silly solution // just to show you how different // components of this framework work // please bring your wise to write // a 'real' solution :) #include <iostream> #include <fstream> #include <string> #include <vector> #include <sstream> #include <map> #include "json/json.h" #include "IR.h" #include "IRMutator.h" #include "IRVisitor.h" #include "IRPrinter.h" #include "type.h" using namespace Boost::Internal; using namespace std; class mydom{ public: string name; int l, r; }; class myvar{ public: string name; vector<size_t>shape; int use; }nowvar, LHSvar; map<string, bool> usedom, LHSusedom; vector<Expr>domlist, LHSdomlist, *gradvarlist; map<string, myvar> myvarlist; map<string, mydom> mydomlist; vector<Stmt>mycode; vector<string>grad_to; Type data_type; int cntgrad; int nowgrad; string gradname; Type index_type = Type::int_scalar(32); int tempcnt = 0; Expr *now_grad_to; Expr *res_LHS; void build_Clist(const string &str, vector<size_t> *&ret); template <class stnTP> stnTP strToNum(const string& str) { istringstream iss(str); stnTP num; iss >> num; return num; } int findfirst(const string &str, char ch){ int n = str.length(); for(int i = 0; i < n; i++) if(str[i] == ch)return i; return -1; } int findlast(const string &str, char ch){ int n = str.length(); for(int i = n - 1; i >= 0; i--) if(str[i] == ch)return i; return -1; } int fix_expr_size(const string &str, int l, int r){ //cout << "fix_expr "<< str << " " << l << " " << r << endl; int n = str.length(), cnt = 0, i; bool quo = true; for(i = n - 1; i >= 0; i--){ if(str[i] == ')')cnt++; if(cnt == 0){ quo = false; if(str[i] == '+' || str[i] == '-')break; } if(str[i] == '(')cnt--; } if(quo) return fix_expr_size(str.substr(1, n - 2), l, r); if(i >= 0){ int sum, ssum; sum = fix_expr_size(str.substr(i + 1), l, r); //cout << sum << endl; if(str[i] == '-')sum = -sum; ssum = fix_expr_size(str.substr(0, i), l - sum, r - sum); if(ssum != 0 && str[i] == '+') fix_expr_size(str.substr(i + 1), l - ssum, r - ssum); return ssum + sum; } for(i = n - 1; i >= 0; i--){ if(str[i] == ')')cnt++; if(cnt == 0) if(str[i] == '*' || str[i] == '/' || str[i] == '%')break; if(str[i] == '(')cnt--; } if(i >= 0){ int sum, ssum; sum = fix_expr_size(str.substr(i + 1), l, r); if(str[i] == '*')ssum = fix_expr_size(str.substr(0, i), l / max((int)1, sum), (r - 1) / max((int)1, sum) + 1); else if(str[i] == '/')ssum = fix_expr_size(str.substr(0, i - 1), l * sum, r * sum); else ssum = fix_expr_size(str.substr(0, i), -1000000000, 1000000000); if(str[i] == '*')return ssum * sum; else if(str[i] == '/') return ssum / max((int)1, sum); else return ssum % max((int)1, sum); } if(str[n - 1] >= '0' && str[n - 1] <= '9')return strToNum<int>(str); if(mydomlist.find(str) == mydomlist.end()){ mydom a({str, l, r}); mydomlist[str] = a; } mydomlist[str].l = max(mydomlist[str].l, l); mydomlist[str].r = min(mydomlist[str].r, r); return 0; } void fix_list_size(const string &str, vector<size_t> *&_size){ string st = str; for(auto i : *_size){ int t = findfirst(st, ','); fix_expr_size(st.substr(0, t), 0, (int)i); st = st.substr(t + 1); } } void fix_size(const string &str){ string st = str; for(int t = findlast(st, ']'); t >= 0; t = findlast(st, ']')){ st = st.substr(0, t); int s = findlast(st, '['); int r = findlast(st, '<'); vector<size_t> *res_Clist; build_Clist(st.substr(r + 1, s - r - 2), res_Clist); fix_list_size(st.substr(s + 1, t - s - 1), res_Clist); st = st.substr(0, r); } } void deluse(const string &str){ string st = str; for(int t = findlast(st, ']'); t >= 0; t = findlast(st, ']')){ st = st.substr(0, t); int r = findlast(st, '<'); int s = r - 1; while((st[s] >= 'A' && st[s] <='Z') || (st[s] >= 'a' && st[s] <= 'z'))s--; string name = st.substr(s + 1, r - s - 1); myvarlist[name].use--; } } void build_IdExpr(const string &str, Expr *&ret, Expr *&varret){ //cout << "build_IdExpr " << str << endl; int n = str.length(), cnt = 0, i; bool quo = true; for(i = n - 1; i >= 0; i--){ if(str[i] == ')')cnt++; if(cnt == 0){ quo = false; if(str[i] == '+' || str[i] == '-')break; } if(str[i] == '(')cnt--; } if(quo){ Expr *res_IdExpr, *res_varExpr; build_IdExpr(str.substr(1, n - 2), res_IdExpr, res_varExpr); ret = new Expr(Unary::make(data_type, UnaryOpType::Not, *res_IdExpr)); varret = new Expr(Unary::make(data_type, UnaryOpType::Not, *res_varExpr)); return; } if(i >= 0){ Expr *LIdExpr, *RIdExpr, *LvarExpr, *RvarExpr; build_IdExpr(str.substr(0, i), LIdExpr, LvarExpr); build_IdExpr(str.substr(i + 1), RIdExpr, RvarExpr); if(str[i] == '+') ret = new Expr(Binary::make(data_type, BinaryOpType::Add, *LIdExpr, *RIdExpr)), varret = new Expr(Binary::make(data_type, BinaryOpType::Add, *LvarExpr, *RvarExpr)); else ret = new Expr(Binary::make(data_type, BinaryOpType::Sub, *LIdExpr, *RIdExpr)), varret = new Expr(Binary::make(data_type, BinaryOpType::Sub, *LvarExpr, *RvarExpr)); return; } for(i = n - 1; i >= 0; i--){ if(str[i] == ')')cnt++; if(cnt == 0) if(str[i] == '*' || str[i] == '/' || str[i] == '%')break; if(str[i] == '(')cnt--; } if(i >= 0){ Expr *LIdExpr, *RIdExpr, *LvarExpr, *RvarExpr; build_IdExpr(str.substr(0, i - (str[i - 1] == '/')), LIdExpr, LvarExpr); build_IdExpr(str.substr(i + 1), RIdExpr, RvarExpr); if(str[i] == '*') ret = new Expr(Binary::make(data_type, BinaryOpType::Mul, *LIdExpr, *RIdExpr)), varret = new Expr(Binary::make(data_type, BinaryOpType::Mul, *LvarExpr, *RvarExpr)); else if(str[i] == '/') ret = new Expr(Binary::make(data_type, BinaryOpType::Div, *LIdExpr, *RIdExpr)), varret = new Expr(Binary::make(data_type, BinaryOpType::Div, *LvarExpr, *RvarExpr)); else ret = new Expr(Binary::make(data_type, BinaryOpType::Mod, *LIdExpr, *RIdExpr)), varret = new Expr(Binary::make(data_type, BinaryOpType::Mod, *LvarExpr, *RvarExpr)); return; } if(str[n - 1] >= '0' && str[n - 1] <= '9'){ ret = new Expr(strToNum<int>(str)); varret = new Expr(strToNum<int>(str)); return; } Expr thisdom = Dom::make(index_type, max(0, mydomlist[str].l), max(0, mydomlist[str].r)); ret = new Expr(Index::make(index_type, str, thisdom, IndexType::Spatial)); varret = new Expr(Var::make(index_type, str, {}, {})); if(!usedom[str]){ usedom[str] = 1; domlist.push_back(*ret); } return; } void build_Clist(const string &str, vector<size_t> *&ret){ //cout << "build_Clist " << str << endl; int t = findlast(str, ','); if(t < 0) ret = new vector<size_t>({strToNum<size_t>(str)}); else{ build_Clist(str.substr(0, t), ret); ret->push_back(strToNum<size_t>(str.substr(t + 1))); } } void build_Alist(const string &str, vector<Expr> *&ret, vector<Expr> *&varret){ //cout << "build_Alist " << str << endl; int t = findlast(str, ','); if(t < 0){ Expr *res_IdExpr, *res_varExpr; build_IdExpr(str, res_IdExpr, res_varExpr); ret = new vector<Expr>({*res_IdExpr}); varret = new vector<Expr>({*res_varExpr}); }else{ build_Alist(str.substr(0, t), ret, varret); Expr *res_IdExpr, *res_varExpr; build_IdExpr(str.substr(t + 1), res_IdExpr, res_varExpr); ret->push_back(*res_IdExpr); varret->push_back(*res_varExpr); } //cout << "build_Alist_finish " << str << endl; } void build_SRef(const string &str, Expr *&ret){ //cout << "build_SRef " << str << endl; int r = findfirst(str, '<'); string name = str.substr(0, r); nowvar.name = name; nowvar.shape.clear(); if(myvarlist.find(name) == myvarlist.end()) myvarlist[name] = nowvar; ret = new Expr(Var::make(data_type, name, {}, {})); } void build_TRef(const string &str, Expr *&ret, bool d = false){ // int n = str.length(); int s = findfirst(str, '['); int r = findfirst(str, '<'); string name = str.substr(0, r); bool e = false; if(!d){ for(int i = 0; i < grad_to.size(); i++) if(name == grad_to[i]){ cntgrad++; if(cntgrad == nowgrad)e = true; } } if(d || e)name = "d" + name; //cout << "build_TRef " << name << endl; vector<size_t> *res_Clist; vector<Expr> *res_Alist; vector<Expr> *res_varlist; build_Clist(str.substr(r + 1, s - r - 2), res_Clist); build_Alist(str.substr(s + 1, n - s - 2), res_Alist, res_varlist); nowvar.name = name; nowvar.shape = *res_Clist; if(myvarlist.find(name) == myvarlist.end()) myvarlist[name] = nowvar; myvarlist[name].use++; ret = new Expr(Var::make(data_type, name, *res_Alist, *res_Clist)); if(e){ gradname = name; gradvarlist = res_varlist; ret = new Expr(1); } } void build_LHS(const string &str, Expr *&ret){ //cout << "build_LHS " << str << endl; usedom.clear(); domlist.clear(); build_TRef(str, ret, true); LHSvar = nowvar; LHSvar.name = "d" + LHSvar.name; LHSdomlist.clear(); for(auto i : domlist) LHSdomlist.push_back(i); LHSusedom.clear(); for(auto i : usedom) LHSusedom[i.first] = 1; } void build_RHS(const string &str, Expr *&ret){ //cout << "build_RHS " << str << endl; int n = str.length(), cnt = 0, i; bool quo = true; for(i = n - 1; i >= 0; i--){ if(str[i] == ')' || str[i] == ']')cnt++; if(cnt == 0){ quo = false; if(str[i] == '+' || str[i] == '-')break; } if(str[i] == '(' || str[i] == '[')cnt--; } if(quo){ Expr *res_IdExpr; build_RHS(str.substr(1, n - 2), res_IdExpr); ret = new Expr(Unary::make(data_type, UnaryOpType::Not, *res_IdExpr)); return; } if(i >= 0){ Expr *res_LRHS, *res_RRHS; int tr = 0; if(cntgrad >= nowgrad)tr = 1; build_RHS(str.substr(0, i), res_LRHS); if(cntgrad >= nowgrad && (!tr))tr = 2; build_RHS(str.substr(i + 1), res_RRHS); if(cntgrad >= nowgrad && (!tr))tr = 3; if(tr == 2){ deluse(str.substr(i + 1)); ret = res_LRHS; } else if(tr == 3){ ret = res_RRHS; deluse(str.substr(0, i)); } else{ if(str[i] == '+') ret = new Expr(Binary::make(data_type, BinaryOpType::Add, *res_LRHS, *res_RRHS)); else ret = new Expr(Binary::make(data_type, BinaryOpType::Sub, *res_LRHS, *res_RRHS)); } return; } for(i = n - 1; i >= 0; i--){ if(str[i] == ')' || str[i] == ']')cnt++; if(cnt == 0)if(str[i] == '*' || str[i] == '/' || str[i] == '%')break; if(str[i] == '(' || str[i] == '[')cnt--; } if(i >= 0){ Expr *res_LRHS, *res_RRHS; build_RHS(str.substr(0, i - (str[i - 1] == '/')), res_LRHS); build_RHS(str.substr(i + 1), res_RRHS); if(str[i] == '*') ret = new Expr(Binary::make(data_type, BinaryOpType::Mul, *res_LRHS, *res_RRHS)); else if(str[i] == '/') ret = new Expr(Binary::make(data_type, BinaryOpType::Div, *res_LRHS, *res_RRHS)); else ret = new Expr(Binary::make(data_type, BinaryOpType::Mod, *res_LRHS, *res_RRHS)); return; } if(str[n - 1] == ']'){ build_TRef(str, ret); return; } if(str[n - 1] == '>'){ build_SRef(str, ret); return; } if(data_type == Type::float_scalar(32)) ret = new Expr(strToNum<float>(str)); else ret = new Expr(strToNum<int>(str)); return; } void build_RHS_list(const string &str, vector<Stmt> *&ret){ //cout << "build_RHS_list " << str << endl; ret = new vector<Stmt>({}); for(nowgrad = 1;; nowgrad++){ usedom.clear(); for(auto i : LHSusedom) usedom[i.first] = 1; domlist.clear(); cntgrad = 0; Expr *res_RHS; build_RHS(str, res_RHS); //IRPrinter printer; vector<Expr>tempdomlist; string s = "a"; //cout << graddomlist->size() << endl; for(int i = 0; i < gradvarlist->size(); i++){ for(s[0]++; mydomlist.find(s) != mydomlist.end(); s[0]++); Expr thisdom = Dom::make(index_type, gradvarlist->at(i), Binary::make(data_type, BinaryOpType::Add, gradvarlist->at(i), 1)); //Expr thisdom = Dom::make(index_type, 0, 10); tempdomlist.push_back(Index::make(index_type, s, thisdom, IndexType::Spatial)); } now_grad_to = new Expr(Var::make(data_type, gradname, tempdomlist, myvarlist[gradname].shape)); Stmt tem = LoopNest::make(tempdomlist, {Move::make(*now_grad_to, Binary::make(data_type, BinaryOpType::Add, *now_grad_to, Binary::make(data_type, BinaryOpType::Mul, *res_LHS, *res_RHS)), MoveType::MemToMem)}); /*Stmt tem = Move::make(*now_grad_to, Binary::make(data_type, BinaryOpType::Add, *now_grad_to, Binary::make(data_type, BinaryOpType::Mul, *res_LHS, *res_RHS)), MoveType::MemToMem);*/ if(domlist.size()) ret->push_back(LoopNest::make(domlist, {tem})); else{ ret->push_back(tem); } //cout << nowgrad << " " << cntgrad << endl; if(cntgrad == nowgrad)break; } return; } void build_S(const string &str){ int n = str.length(); //cout << "build_S " << str << endl; mydomlist.clear(); fix_size(str); /*for(auto i : mydomlist) cout << i.second.name << " " << i.second.l << " " << i.second.r << endl;*/ int t = findfirst(str, '='); build_LHS(str.substr(0, t), res_LHS); vector<Stmt> *res_RHS; build_RHS_list(str.substr(t + 1, n - t - 2), res_RHS); mycode.push_back(LoopNest::make(LHSdomlist, *res_RHS)); } void build_P(const string &str){ //cout << "build_P " << str << endl; int n = str.length(), t = findfirst(str, ';'); if(t == n - 1) build_S(str); else{ build_S(str.substr(0, t + 1)); build_P(str.substr(t + 1)); } } bool Input(int cnt, string &name, vector<string>&ins, vector<string>&outs, string &data_type, string &kernel, vector<string> &grad_to){ string st; if(cnt == 0)st = "./cases/example.json"; else st = "./cases/case" + to_string(cnt) + ".json"; ifstream ifile(st, std::ios::in); if(!ifile.good())return false; Json::Reader reader; Json::Value root; if (reader.parse(ifile, root)) { name = root["name"].asString(); data_type = root["data_type"].asString(); kernel = root["kernel"].asString(); Json::Value object = root["ins"]; for (int i = 0; i < object.size(); i++) ins.push_back(object[i].asString()); object = root["outs"]; for (int i = 0; i < object.size(); i++) outs.push_back(object[i].asString()); object = root["grad_to"]; for (int i = 0; i < object.size(); i++) grad_to.push_back(object[i].asString()); } else return false; ifile.close(); return true; } int main() { for(int i = 1; i <= 10; i++){ string name, type, kernel; vector<string> ins, outs; grad_to.clear(); if(!Input(i, name, ins, outs, type, kernel, grad_to)){ cout<< "case" + to_string(i) + " missed!" << endl; continue; } //cout << name <<endl; //cout << kernel <<endl; if(type[0] == 'f')data_type = Type::float_scalar(32); else data_type = Type::int_scalar(32); int n = kernel.length(); string st = ""; for(int i = 0; i < n; i++) if(kernel[i] != ' ')st += kernel[i]; usedom.clear(); LHSusedom.clear(); domlist.clear(); LHSdomlist.clear(); myvarlist.clear(); mydomlist.clear(); mycode.clear(); //grad_to.clear(); tempcnt = 0; build_P(st); for(auto t : grad_to){ vector<Expr> domli; string str = "i"; for(auto s : myvarlist["d" + t].shape){ Expr thisdom = Dom::make(index_type, 0, (int)s); domli.push_back(Index::make(index_type, str, thisdom, IndexType::Spatial)); str[0] = str[0] + 1; } mycode.insert(mycode.begin(), LoopNest::make(domli, {Move::make(Var::make(data_type, "d" + t, domli, myvarlist["d" + t].shape), 0, MoveType::MemToMem)})); } vector<Expr>input; vector<Expr>output; for(auto i : ins)if(myvarlist.find(i) != myvarlist.end() && myvarlist[i].use) input.push_back(Var::make(data_type, i, {}, myvarlist[i].shape)); for(auto i : outs) output.push_back(Var::make(data_type, "d" + i, {}, myvarlist["d" + i].shape)); for(auto i : grad_to) output.push_back(Var::make(data_type, "d" + i, {}, myvarlist["d" + i].shape)); Group _kernel = Kernel::make(name, input, output, mycode, KernelType::CPU); IRPrinter printer; string code = printer.print(_kernel); //cout << code; if(i > 0){ ofstream ofile("./kernels/grad_case" + to_string(i) + ".cc", std::ios::out); ofile << code; ofile.close(); }else{ ofstream ofile("./kernels/kernel_example.cc", std::ios::out); ofile << code; ofile.close(); } //cout<< code; cout<< "case" + to_string(i) + " finished!" <<endl; } return 0; }
31.396975
158
0.582756
nbdhhzh
092734362d089f28b986ea8a7a86fa36e070fdf2
11,087
cpp
C++
src/modules/processes/contrib/nvolkov/SplitCFA/MergeCFAInstance.cpp
fmeschia/pixinsight-class-library
11b956e27d6eee3e119a7b1c337d090d7a03f436
[ "JasPer-2.0", "libtiff" ]
null
null
null
src/modules/processes/contrib/nvolkov/SplitCFA/MergeCFAInstance.cpp
fmeschia/pixinsight-class-library
11b956e27d6eee3e119a7b1c337d090d7a03f436
[ "JasPer-2.0", "libtiff" ]
null
null
null
src/modules/processes/contrib/nvolkov/SplitCFA/MergeCFAInstance.cpp
fmeschia/pixinsight-class-library
11b956e27d6eee3e119a7b1c337d090d7a03f436
[ "JasPer-2.0", "libtiff" ]
null
null
null
// ____ ______ __ // / __ \ / ____// / // / /_/ // / / / // / ____// /___ / /___ PixInsight Class Library // /_/ \____//_____/ PCL 2.4.9 // ---------------------------------------------------------------------------- // Standard SplitCFA Process Module Version 1.0.6 // ---------------------------------------------------------------------------- // MergeCFAInstance.cpp - Released 2021-04-09T19:41:49Z // ---------------------------------------------------------------------------- // This file is part of the standard SplitCFA PixInsight module. // // Copyright (c) 2013-2020 Nikolay Volkov // Copyright (c) 2003-2020 Pleiades Astrophoto S.L. // // Redistribution and use in both source and binary forms, with or without // modification, is permitted provided that the following conditions are met: // // 1. All redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. All 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 names "PixInsight" and "Pleiades Astrophoto", nor the names // of their contributors, may be used to endorse or promote products derived // from this software without specific prior written permission. For written // permission, please contact info@pixinsight.com. // // 4. All products derived from this software, in any form whatsoever, must // reproduce the following acknowledgment in the end-user documentation // and/or other materials provided with the product: // // "This product is based on software from the PixInsight project, developed // by Pleiades Astrophoto and its contributors (https://pixinsight.com/)." // // Alternatively, if that is where third-party acknowledgments normally // appear, this acknowledgment must be reproduced in the product itself. // // THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO AND ITS 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 PLEIADES ASTROPHOTO OR ITS // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS // INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE, // DATA OR PROFITS) 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 "MergeCFAInstance.h" #include "MergeCFAParameters.h" #include <pcl/AutoPointer.h> #include <pcl/AutoViewLock.h> #include <pcl/Console.h> #include <pcl/StandardStatus.h> #include <pcl/View.h> namespace pcl { // ---------------------------------------------------------------------------- MergeCFAInstance::MergeCFAInstance( const MetaProcess* m ) : ProcessImplementation( m ) { } // ---------------------------------------------------------------------------- MergeCFAInstance::MergeCFAInstance( const MergeCFAInstance& x ) : ProcessImplementation( x ) { Assign( x ); } // ---------------------------------------------------------------------------- void MergeCFAInstance::Assign( const ProcessImplementation& p ) { const MergeCFAInstance* x = dynamic_cast<const MergeCFAInstance*>( &p ); if ( x != nullptr ) { p_viewId = x->p_viewId; o_outputViewId = x->o_outputViewId; } } // ---------------------------------------------------------------------------- bool MergeCFAInstance::CanExecuteOn( const View&, pcl::String& whyNot ) const { whyNot = "MergeCFA can only be executed in the global context."; return false; } // ---------------------------------------------------------------------------- bool MergeCFAInstance::CanExecuteGlobal( String& whyNot ) const { return true; } // ---------------------------------------------------------------------------- View MergeCFAInstance::GetView( int n ) { const String id = p_viewId[n]; if ( id.IsEmpty() ) throw Error( "MergeCFA: Source image #" + String( n ) + " not set." ); ImageWindow w = ImageWindow::WindowById( id ); if ( w.IsNull() ) throw Error( "MergeCFA: Source image not found: " + id ); ImageVariant image = w.MainView().Image(); if ( n == 0 ) { m_width = image.Width(); m_height = image.Height(); m_isColor = image.IsColor(); m_isFloatSample = image.IsFloatSample(); m_bitsPerSample = image.BitsPerSample(); m_numberOfChannels = image.NumberOfChannels(); } else { const String str = "MergeCFA: Incompatible source image "; if ( image.Width() != m_width || image.Height() != m_height || image.NumberOfChannels() != m_numberOfChannels ) throw Error( str + "geometry: " + id ); if ( image.BitsPerSample() != m_bitsPerSample || image.IsFloatSample() != m_isFloatSample ) throw Error( str + "sample type : " + id ); if ( image.IsColor() != m_isColor ) throw Error( str + "color space: " + id ); } return w.MainView(); } // ---------------------------------------------------------------------------- template <class P> static void MergeCFAImage( GenericImage<P>& outputImage, const GenericImage<P>& inputImage0, const GenericImage<P>& inputImage1, const GenericImage<P>& inputImage2, const GenericImage<P>& inputImage3 ) { for ( int c = 0; c < outputImage.NumberOfChannels(); ++c ) for ( int sY = 0, tY = 0; tY < outputImage.Height(); tY += 2, ++sY ) { for ( int sX = 0, tX = 0; tX < outputImage.Width(); tX += 2, ++sX ) { outputImage( tX, tY, c ) = inputImage0( sX, sY, c ); outputImage( tX, tY + 1, c ) = inputImage1( sX, sY, c ); outputImage( tX + 1, tY, c ) = inputImage2( sX, sY, c ); outputImage( tX + 1, tY + 1, c ) = inputImage3( sX, sY, c ); } outputImage.Status() += outputImage.Width() / 2; } } // ---------------------------------------------------------------------------- bool MergeCFAInstance::ExecuteGlobal() { o_outputViewId.Clear(); Array<View> sourceView; for ( int i = 0; i < 4; ++i ) sourceView << GetView( i ); ImageWindow outputWindow( m_width * 2, m_height * 2, m_numberOfChannels, m_bitsPerSample, m_isFloatSample, m_isColor, true ); if ( outputWindow.IsNull() ) throw Error( "MergeCFA: Unable to create target image." ); View outputView = outputWindow.MainView(); try { volatile AutoViewLock outputLock( outputView ); Array<AutoPointer<AutoViewWriteLock>> sourceViewLock; sourceViewLock << new AutoViewWriteLock( sourceView[0] ); for ( int i = 1; i < 4; ++i ) if ( sourceView[i].CanWrite() ) // allow the same view selected for several input channels sourceViewLock << new AutoViewWriteLock( sourceView[i] ); ImageVariant outputImage = outputView.Image(); Array<ImageVariant> inputImage; for ( int i = 0; i < 4; ++i ) inputImage << sourceView[i].Image(); StandardStatus status; outputImage.SetStatusCallback( &status ); outputImage.Status().Initialize( "Merging CFA components", outputImage.NumberOfSamples() / 4 ); Console().EnableAbort(); #define MERGE_CFA_IMAGE( I ) \ MergeCFAImage( static_cast<I&>( *outputImage ), \ static_cast<const I&>( *inputImage[0] ), \ static_cast<const I&>( *inputImage[1] ), \ static_cast<const I&>( *inputImage[2] ), \ static_cast<const I&>( *inputImage[3] ) ) if ( outputImage.IsFloatSample() ) switch ( outputImage.BitsPerSample() ) { case 32: MERGE_CFA_IMAGE( Image ); break; case 64: MERGE_CFA_IMAGE( DImage ); break; } else switch ( outputImage.BitsPerSample() ) { case 8: MERGE_CFA_IMAGE( UInt8Image ); break; case 16: MERGE_CFA_IMAGE( UInt16Image ); break; case 32: MERGE_CFA_IMAGE( UInt32Image ); break; } #undef MERGE_CFA_IMAGE Console().DisableAbort(); o_outputViewId = outputView.Id(); outputWindow.Show(); return true; } catch ( ... ) { outputWindow.Close(); throw; } } // ---------------------------------------------------------------------------- void* MergeCFAInstance::LockParameter( const MetaParameter* p, size_type /*tableRow*/ ) { if ( p == TheMergeCFASourceImage0Parameter ) return p_viewId[0].Begin(); if ( p == TheMergeCFASourceImage1Parameter ) return p_viewId[1].Begin(); if ( p == TheMergeCFASourceImage2Parameter ) return p_viewId[2].Begin(); if ( p == TheMergeCFASourceImage3Parameter ) return p_viewId[3].Begin(); if ( p == TheMergeCFAOutputViewIdParameter ) return o_outputViewId.Begin(); return nullptr; } // ---------------------------------------------------------------------------- bool MergeCFAInstance::AllocateParameter( size_type length, const MetaParameter* p, size_type /*tableRow*/ ) { StringList::iterator s; if ( p == TheMergeCFASourceImage0Parameter ) s = p_viewId.At( 0 ); else if ( p == TheMergeCFASourceImage1Parameter ) s = p_viewId.At( 1 ); else if ( p == TheMergeCFASourceImage2Parameter ) s = p_viewId.At( 2 ); else if ( p == TheMergeCFASourceImage3Parameter ) s = p_viewId.At( 3 ); else if ( p == TheMergeCFAOutputViewIdParameter ) s = &o_outputViewId; else return false; s->Clear(); if ( length > 0 ) s->SetLength( length ); return true; } // ---------------------------------------------------------------------------- size_type MergeCFAInstance::ParameterLength( const MetaParameter* p, size_type /*tableRow*/ ) const { if ( p == TheMergeCFASourceImage0Parameter ) return p_viewId[0].Length(); if ( p == TheMergeCFASourceImage1Parameter ) return p_viewId[1].Length(); if ( p == TheMergeCFASourceImage2Parameter ) return p_viewId[2].Length(); if ( p == TheMergeCFASourceImage3Parameter ) return p_viewId[3].Length(); if ( p == TheMergeCFAOutputViewIdParameter ) return o_outputViewId.Length(); return 0; } // ---------------------------------------------------------------------------- } // namespace pcl // ---------------------------------------------------------------------------- // EOF MergeCFAInstance.cpp - Released 2021-04-09T19:41:49Z
35.308917
128
0.56697
fmeschia
092cc8fb137d57a9aa8a1af54cbe1913ebfef4c7
772
cpp
C++
CodeForces-Contest/1433/D.cpp
Tech-Intellegent/CodeForces-Solution
2f291a38b80b8ff2a2595b2e526716468ff26bf8
[ "MIT" ]
1
2022-01-23T07:18:07.000Z
2022-01-23T07:18:07.000Z
CodeForces-Contest/1433/D.cpp
Tech-Intellegent/CodeForces-Solution
2f291a38b80b8ff2a2595b2e526716468ff26bf8
[ "MIT" ]
null
null
null
CodeForces-Contest/1433/D.cpp
Tech-Intellegent/CodeForces-Solution
2f291a38b80b8ff2a2595b2e526716468ff26bf8
[ "MIT" ]
1
2022-02-05T11:53:04.000Z
2022-02-05T11:53:04.000Z
#include<bits/stdc++.h> using namespace std; int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; vector<pair<int, int>> a; for (int i = 1; i <= n; i++) { int k; cin >> k; a.push_back({k, i}); } sort(a.begin(), a.end()); if (a[0].first == a[n - 1].first) { cout << "NO\n"; } else { cout << "YES\n"; for (int i = 0; i < n - 1; i++) { if (a[i].first != a[n - 1].first) { cout << a[i].second << ' ' << a[n - 1].second << '\n'; } } for (int i = n - 2; i >= 0; i--) { if (a[i].first == a[n - 1].first) { cout << a[i].second << ' ' << a[0].second << '\n'; } } } } return 0; }
22.705882
64
0.392487
Tech-Intellegent
092d511caf89f0dfdfe395abed1f9bfbe9c430a1
9,954
cpp
C++
src/Entities/Entity.cpp
Mac1512/engge
50c203c09b57c0fbbcdf6284c60886c8db471e07
[ "MIT" ]
null
null
null
src/Entities/Entity.cpp
Mac1512/engge
50c203c09b57c0fbbcdf6284c60886c8db471e07
[ "MIT" ]
null
null
null
src/Entities/Entity.cpp
Mac1512/engge
50c203c09b57c0fbbcdf6284c60886c8db471e07
[ "MIT" ]
null
null
null
#include <memory> #include <optional> #include <utility> #include "Entities/Entity.hpp" #include "Scripting/ScriptEngine.hpp" #include "Audio/SoundTrigger.hpp" #include "Engine/Camera.hpp" #include "Engine/Trigger.hpp" #include "Actor/_TalkingState.hpp" namespace ng { struct Entity::Impl { Engine &_engine; std::map<int, Trigger *> _triggers; std::vector<std::unique_ptr<SoundTrigger>> _soundTriggers; std::optional<sf::Vector2f> _usePos; std::optional<UseDirection> _useDir; sf::Vector2f _offset; bool _isLit{true}; bool _isVisible{true}; bool _isTouchable{true}; sf::Vector2i _renderOffset; Motor _offsetTo, _scaleTo, _rotateTo, _moveTo, _alphaTo; sf::Color _color{sf::Color::White}; bool _objectBumperCycle{true}; sf::Color _talkColor; sf::Vector2i _talkOffset; _TalkingState _talkingState; std::string _key; Impl() : _engine(ng::Locator<ng::Engine>::get()) { _talkingState.setEngine(&_engine); } static std::optional<int> getDefaultVerb(const Entity *pEntity) { if(!pEntity) return std::nullopt; const char *dialog = nullptr; if (ScriptEngine::rawGet(pEntity, "dialog", dialog)) return std::make_optional(VerbConstants::VERB_TALKTO); int value = 0; if(ScriptEngine::rawGet(pEntity, "defaultVerb", value)) return std::make_optional(value); return std::nullopt; } }; Entity::Entity() : pImpl(std::make_unique<Entity::Impl>()) { } Entity::~Entity() = default; void Entity::objectBumperCycle(bool enabled) { pImpl->_objectBumperCycle = enabled; } bool Entity::objectBumperCycle() const { return pImpl->_objectBumperCycle; } void Entity::update(const sf::Time &elapsed) { pImpl->_talkingState.update(elapsed); update(pImpl->_offsetTo, elapsed); update(pImpl->_scaleTo, elapsed); update(pImpl->_rotateTo, elapsed); update(pImpl->_moveTo, elapsed); update(pImpl->_alphaTo, elapsed); } void Entity::update(Motor &motor, const sf::Time &elapsed) { if (motor.isEnabled) { (*motor.function)(elapsed); if (motor.isEnabled && motor.function->isElapsed()) { motor.isEnabled = false; } } } void Entity::setLit(bool isLit) { pImpl->_isLit = isLit; } bool Entity::isLit() const { return pImpl->_isLit; } void Entity::setVisible(bool isVisible) { pImpl->_isVisible = isVisible; } bool Entity::isVisible() const { return pImpl->_isVisible; } void Entity::setUsePosition(std::optional<sf::Vector2f> pos) { pImpl->_usePos = pos; } void Entity::setUseDirection(std::optional<UseDirection> direction) { pImpl->_useDir = direction; } std::optional<UseDirection> Entity::getUseDirection() const { return pImpl->_useDir; } void Entity::setPosition(const sf::Vector2f &pos) { _transform.setPosition(pos); pImpl->_moveTo.isEnabled = false; } sf::Vector2f Entity::getPosition() const { return _transform.getPosition(); } sf::Vector2f Entity::getRealPosition() const { return getPosition() + pImpl->_offset; } void Entity::setOffset(const sf::Vector2f &offset) { pImpl->_offset = offset; pImpl->_offsetTo.isEnabled = false; } sf::Vector2f Entity::getOffset() const { return pImpl->_offset; } void Entity::setRotation(float angle) { _transform.setRotation(angle); } float Entity::getRotation() const { // SFML give rotation in degree between [0, 360] float angle = _transform.getRotation(); // convert it to [-180, 180] if (angle > 180) angle -= 360; return angle; } void Entity::setColor(const sf::Color &color) { pImpl->_color = color; pImpl->_alphaTo.isEnabled = false; } const sf::Color &Entity::getColor() const { return pImpl->_color; } void Entity::setScale(float s) { _transform.setScale(s, s); pImpl->_scaleTo.isEnabled = false; } float Entity::getScale() const { return _transform.getScale().x; } sf::Transformable Entity::getTransform() const { auto transform = _transform; transform.move(pImpl->_offset.x, pImpl->_offset.y); return transform; } std::optional<sf::Vector2f> Entity::getUsePosition() const { return pImpl->_usePos; } void Entity::setTrigger(int triggerNumber, Trigger *pTrigger) { pImpl->_triggers[triggerNumber] = pTrigger; } void Entity::removeTrigger(int triggerNumber) { pImpl->_triggers.erase(triggerNumber); } void Entity::trig(int triggerNumber) { auto it = pImpl->_triggers.find(triggerNumber); if (it != pImpl->_triggers.end()) { it->second->trig(); } } void Entity::trigSound(const std::string &) { } void Entity::drawForeground(sf::RenderTarget &target, sf::RenderStates s) const { if (!pImpl->_talkingState.isTalking()) return; target.draw(pImpl->_talkingState, s); } SoundTrigger *Entity::createSoundTrigger(Engine &engine, const std::vector<SoundDefinition *> &sounds) { auto trigger = std::make_unique<SoundTrigger>(engine, sounds, this->getId()); SoundTrigger *pTrigger = trigger.get(); pImpl->_soundTriggers.push_back(std::move(trigger)); return pTrigger; } void Entity::setKey(const std::string &key) { pImpl->_key = key; } const std::string &Entity::getKey() const { return pImpl->_key; } uint32_t Entity::getFlags() const { int flags = 0; ScriptEngine::rawGet(this, "flags", flags); return (uint32_t) flags; } void Entity::setTouchable(bool isTouchable) { pImpl->_isTouchable = isTouchable; } bool Entity::isTouchable() const { if (!isVisible()) return false; return pImpl->_isTouchable; } void Entity::setRenderOffset(const sf::Vector2i &offset) { pImpl->_renderOffset = offset; } sf::Vector2i Entity::getRenderOffset() const { return pImpl->_renderOffset; } void Entity::alphaTo(float destination, sf::Time time, InterpolationMethod method) { auto getAlpha = [this] { return static_cast<float>(getColor().a) / 255.f; }; auto setAlpha = [this](const float &a) { pImpl->_color.a = static_cast<sf::Uint8>(a * 255.f); }; auto alphaTo = std::make_unique<ChangeProperty<float>>(getAlpha, setAlpha, destination, time, method); pImpl->_alphaTo.function = std::move(alphaTo); pImpl->_alphaTo.isEnabled = true; } void Entity::offsetTo(sf::Vector2f destination, sf::Time time, InterpolationMethod method) { auto get = [this] { return pImpl->_offset; }; auto set = [this](const sf::Vector2f &value) { pImpl->_offset = value; }; auto offsetTo = std::make_unique<ChangeProperty<sf::Vector2f>>(get, set, destination, time, method); pImpl->_offsetTo.function = std::move(offsetTo); pImpl->_offsetTo.isEnabled = true; } void Entity::moveTo(sf::Vector2f destination, sf::Time time, InterpolationMethod method) { auto get = [this] { return getPosition(); }; auto set = [this](const sf::Vector2f &value) { _transform.setPosition(value); }; auto moveTo = std::make_unique<ChangeProperty<sf::Vector2f>>(get, set, destination, time, method); pImpl->_moveTo.function = std::move(moveTo); pImpl->_moveTo.isEnabled = true; } void Entity::rotateTo(float destination, sf::Time time, InterpolationMethod method) { auto get = [this] { return getRotation(); }; auto set = [this](const float &value) { _transform.setRotation(value); }; auto rotateTo = std::make_unique<ChangeProperty<float>>(get, set, destination, time, method); pImpl->_rotateTo.function = std::move(rotateTo); pImpl->_rotateTo.isEnabled = true; } void Entity::scaleTo(float destination, sf::Time time, InterpolationMethod method) { auto get = [this] { return _transform.getScale().x; }; auto set = [this](const float &s) { _transform.setScale(s, s); }; auto scalteTo = std::make_unique<ChangeProperty<float>>(get, set, destination, time, method); pImpl->_scaleTo.function = std::move(scalteTo); pImpl->_scaleTo.isEnabled = true; } void Entity::setName(const std::string &name) { ScriptEngine::set(getTable(), "name", name.c_str()); } std::string Entity::getName() const { const char *name = nullptr; ScriptEngine::get(getTable(), "name", name); if (!name) return std::string(); return name; } void Entity::stopObjectMotors() { pImpl->_offsetTo.isEnabled = false; pImpl->_scaleTo.isEnabled = false; pImpl->_rotateTo.isEnabled = false; pImpl->_moveTo.isEnabled = false; pImpl->_alphaTo.isEnabled = false; } void Entity::setTalkColor(sf::Color color) { pImpl->_talkColor = color; } sf::Color Entity::getTalkColor() const { return pImpl->_talkColor; } void Entity::setTalkOffset(const sf::Vector2i &offset) { pImpl->_talkOffset = offset; } sf::Vector2i Entity::getTalkOffset() const { return pImpl->_talkOffset; } void Entity::say(const std::string &text, bool mumble) { pImpl->_talkingState.loadLip(text, this, mumble); sf::Vector2f pos; auto screenSize = pImpl->_engine.getRoom()->getScreenSize(); if (getRoom() == pImpl->_engine.getRoom()) { auto at = pImpl->_engine.getCamera().getAt(); pos = getRealPosition(); pos = {pos.x - at.x + pImpl->_talkOffset.x, screenSize.y - pos.y - at.y - pImpl->_talkOffset.y}; } else { // TODO: the position in this case is wrong, don't know what to do yet pos = (sf::Vector2f) pImpl->_talkOffset; pos = {pos.x, screenSize.y + pos.y}; } pos = toDefaultView((sf::Vector2i) pos, pImpl->_engine.getRoom()->getScreenSize()); pImpl->_talkingState.setPosition(pos); } void Entity::stopTalking() { pImpl->_talkingState.stop(); } bool Entity::isTalking() const { return pImpl->_talkingState.isTalking(); } int Entity::getDefaultVerb(int defaultVerbId) const { auto result = pImpl->getDefaultVerb(this); if(result.has_value()) return result.value(); result = pImpl->getDefaultVerb(getActor(this)); return result.value_or(defaultVerbId); } Actor *Entity::getActor(const Entity *pEntity) { // if an actor has the same name then get its flags auto &actors = Locator<Engine>::get().getActors(); auto itActor = std::find_if(actors.begin(), actors.end(), [pEntity](auto &pActor) -> bool { return pActor->getName() == pEntity->getName(); }); if (itActor != actors.end()) { return itActor->get(); } return nullptr; } } // namespace ng
29.713433
104
0.703335
Mac1512
092ddcb732ca5a2361c9dd48e6a35c5f50853686
350
hpp
C++
PolyDock/PolyDock/src/pd/ecs/cmp/tabbedWindow/Closing.hpp
PolyEngineTeam/PolyDock
27a105b2cc80db4286e03a2a1e5bee64438d37c8
[ "MIT" ]
3
2020-05-16T16:33:51.000Z
2021-08-05T18:48:13.000Z
PolyDock/PolyDock/src/pd/ecs/cmp/tabbedWindow/Closing.hpp
Qt-Widgets/PolyDock
f32def214753ca0f6bab9968bc2bb5e451cb6e4f
[ "MIT" ]
30
2020-03-25T17:22:51.000Z
2020-08-17T00:33:04.000Z
PolyDock/PolyDock/src/pd/ecs/cmp/tabbedWindow/Closing.hpp
Qt-Widgets/PolyDock
f32def214753ca0f6bab9968bc2bb5e451cb6e4f
[ "MIT" ]
5
2020-03-26T17:12:34.000Z
2021-03-05T08:08:39.000Z
#pragma once namespace pd::ecs::cmp::tabbedWindow { // --------------------------------------------------------------------------------------------------------- class CloseRequest { public: }; // --------------------------------------------------------------------------------------------------------- class RemoveRequest { public: }; }
20.588235
109
0.245714
PolyEngineTeam
09341207e208e5874f8eb2ea1c598eb265e9033e
864
cpp
C++
307. Range Sum Query - Mutable/main.cpp
Competitive-Programmers-Community/LeetCode
841fdee805b1a626e9f1cd0e12398d25054638af
[ "MIT" ]
2
2019-10-05T09:48:20.000Z
2019-10-05T15:40:01.000Z
307. Range Sum Query - Mutable/main.cpp
Competitive-Programmers-Community/LeetCode
841fdee805b1a626e9f1cd0e12398d25054638af
[ "MIT" ]
null
null
null
307. Range Sum Query - Mutable/main.cpp
Competitive-Programmers-Community/LeetCode
841fdee805b1a626e9f1cd0e12398d25054638af
[ "MIT" ]
3
2020-09-27T05:48:30.000Z
2021-08-13T10:07:08.000Z
class NumArray { private: const int N = 1e5; int n; vector<int> t = vector<int>(2*N); public: void build(){ for(int i=n-1;i>0;i--) t[i] = t[i<<1] +t[i<<1 | 1]; } NumArray(vector<int> nums) { n=nums.size(); for(int i=0; i<n; i++) t[n+i]=nums[i]; build(); } void update(int p, int value) { for(t[p += n] = value; p>1; p>>=1) t[p>>1] = t[p] +t[p^1]; } int sumRange(int l, int r) { r+=1; int res=0; for(l += n, r += n; l<r; l >>= 1, r >>= 1){ if(l&1) res += t[l++]; if(r&1) res += t[--r]; } return res; } }; /** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * obj.update(i,val); * int param_2 = obj.sumRange(i,j); */
20.571429
66
0.431713
Competitive-Programmers-Community
09397e65e69a15cd883f4dbf77802cee6d966d6a
1,372
cpp
C++
ROS/dextrobot_ws/src/dextrobot_controller/src/arduino/base_controller/src/Imu.cpp
AntoBrandi/Dextro-Bot
533f873485b1c8d816c6ed368b63c03e476102b9
[ "MIT", "Unlicense" ]
3
2021-07-02T15:40:32.000Z
2022-01-09T15:09:51.000Z
ROS/dextrobot_ws/src/dextrobot_controller/src/arduino/simplified_controller/src/Imu.cpp
AntoBrandi/DextroBot
533f873485b1c8d816c6ed368b63c03e476102b9
[ "MIT", "Unlicense" ]
null
null
null
ROS/dextrobot_ws/src/dextrobot_controller/src/arduino/simplified_controller/src/Imu.cpp
AntoBrandi/DextroBot
533f873485b1c8d816c6ed368b63c03e476102b9
[ "MIT", "Unlicense" ]
1
2021-05-22T09:14:18.000Z
2021-05-22T09:14:18.000Z
#include <Imu.h> Imu::Imu(/* args */) { } Imu::~Imu() { } // convert RPY degrees angles to Radians float Imu::toRadians(float degree){ return degree*PI/180; } // reads the value coming from the IMU sensor and update the class parameters void Imu::sense(){ Vector normAccel = mpu.readNormalizeAccel(); Vector normGyro = mpu.readNormalizeGyro(); // Calculate Pitch & Roll pitch = -(atan2(normAccel.XAxis, sqrt(normAccel.YAxis*normAccel.YAxis + normAccel.ZAxis*normAccel.ZAxis))*180.0)/M_PI; roll = (atan2(normAccel.YAxis, normAccel.ZAxis)*180.0)/M_PI; //Ignore the gyro if our angular velocity does not meet our threshold if (normGyro.ZAxis > 1 || normGyro.ZAxis < -1) { normGyro.ZAxis /= 100; yaw += normGyro.ZAxis; } //Keep our angle between 0-359 degrees if (yaw < 0) yaw += 360; else if (yaw > 359) yaw -= 360; AcX = normAccel.XAxis; AcY = normAccel.YAxis; AcZ = normAccel.ZAxis; } // Get the data coming from the IMU sensor and arrange those in a ROS string message String Imu::composeStringMessage(){ String data = String(AcX) + "," + String(AcY) + "," + String(AcZ) + "," + String(toRadians(roll)) + ","+ String(toRadians(pitch)) + "," + String(toRadians(yaw)); return data; }
27.44
165
0.605685
AntoBrandi
093b3fca4883fb98169ba8001ff1444991746728
3,097
cpp
C++
lib/libcpp/Mesh/boundarymeshinfo.cpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
null
null
null
lib/libcpp/Mesh/boundarymeshinfo.cpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
1
2019-01-31T10:59:11.000Z
2019-01-31T10:59:11.000Z
lib/libcpp/Mesh/boundarymeshinfo.cpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
null
null
null
#include "Mesh/boundarymeshinfo.hpp" #include <cassert> #include <mpi.h> using namespace mesh; /*--------------------------------------------------------------------------*/ BoundaryMeshInfo::~BoundaryMeshInfo() {} BoundaryMeshInfo::BoundaryMeshInfo(): GeometryObject(){} BoundaryMeshInfo::BoundaryMeshInfo( const BoundaryMeshInfo& boundarymeshinfo): GeometryObject(boundarymeshinfo) { _nodes_to_parent = boundarymeshinfo._nodes_to_parent; _cells_to_parent = boundarymeshinfo._cells_to_parent; } BoundaryMeshInfo& BoundaryMeshInfo::operator=( const BoundaryMeshInfo& boundarymeshinfo) { assert(0); GeometryObject::operator=(boundarymeshinfo); return *this; } std::string BoundaryMeshInfo::getClassName() const { return "BoundaryMeshInfo"; } std::unique_ptr<GeometryObject> BoundaryMeshInfo::clone() const { return std::unique_ptr<mesh::GeometryObject>(new BoundaryMeshInfo(*this)); } /*--------------------------------------------------------------------------*/ const alat::armaivec& BoundaryMeshInfo::getNodesToParent() const {return _nodes_to_parent;} alat::armaivec& BoundaryMeshInfo::getNodesToParent() {return _nodes_to_parent;} const alat::armaimat& BoundaryMeshInfo::getCellsToParent() const {return _cells_to_parent;} alat::armaimat& BoundaryMeshInfo::getCellsToParent() {return _cells_to_parent;} /*--------------------------------------------------------------------------*/ alat::armaivec BoundaryMeshInfo::getSizes() const { alat::armaivec sizes(3); sizes[0] = _nodes_to_parent.size(); sizes[1] = _cells_to_parent.n_rows; sizes[2] = _cells_to_parent.n_cols; return sizes; } void BoundaryMeshInfo::setSizes(alat::armaivec::const_iterator sizes) { _nodes_to_parent.set_size(sizes[0]); _cells_to_parent.set_size(sizes[1], sizes[2]); } void BoundaryMeshInfo::send(int neighbor, int tag) const { MPI_Request request; MPI_Isend(_nodes_to_parent.begin(), _nodes_to_parent.size(), MPI_INT, neighbor, tag, MPI_COMM_WORLD, &request); MPI_Isend(_cells_to_parent.begin(), _cells_to_parent.size(), MPI_INT, neighbor, tag, MPI_COMM_WORLD, &request); } void BoundaryMeshInfo::recv(int neighbor, int tag) { MPI_Status status; MPI_Request request; MPI_Irecv(_nodes_to_parent.begin(), _nodes_to_parent.size(), MPI_INT, neighbor, tag, MPI_COMM_WORLD, &request); MPI_Wait(&request, &status); MPI_Irecv(_cells_to_parent.begin(), _cells_to_parent.size(), MPI_INT, neighbor, tag, MPI_COMM_WORLD, &request); MPI_Wait(&request, &status); } /*--------------------------------------------------------------------------*/ void BoundaryMeshInfo::loadH5(const arma::hdf5_name& spec) { _nodes_to_parent.load(arma::hdf5_name(spec.filename, spec.dsname+"/nodes_to_parent", spec.opts)); _cells_to_parent.load(arma::hdf5_name(spec.filename, spec.dsname+"/cells_to_parent", spec.opts)); } void BoundaryMeshInfo::saveH5(const arma::hdf5_name& spec) const { _nodes_to_parent.save(arma::hdf5_name(spec.filename, spec.dsname+"/nodes_to_parent", spec.opts)); _cells_to_parent.save(arma::hdf5_name(spec.filename, spec.dsname+"/cells_to_parent", spec.opts)); }
40.220779
113
0.699387
beckerrh
093f08509d481524d8ae4aa5c308632a3ebf7aef
356
cpp
C++
solutions/525.contiguous-array.324108882.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
78
2020-10-22T11:31:53.000Z
2022-02-22T13:27:49.000Z
solutions/525.contiguous-array.324108882.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
null
null
null
solutions/525.contiguous-array.324108882.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
26
2020-10-23T15:10:44.000Z
2021-11-07T16:13:50.000Z
class Solution { public: int findMaxLength(vector<int> &nums) { int n = nums.size(); unordered_map<int, int> dp; int c = 0; int ans = 0; dp[0] = -1; for (int i = 0; i < n; i++) { c += nums[i] ? 1 : -1; if (dp.count(c)) ans = max(ans, i - dp[c]); else dp[c] = i; } return ans; } };
14.833333
40
0.438202
satu0king
0948608a7b29eaae18fdb49ef752352d112ed26c
12,232
cpp
C++
framework/private/test/bundle_archive_test.cpp
rwalraven343/celix
353ac0d2e0f819f8f59d4cdf8ea1dfd701201d74
[ "Apache-2.0" ]
1
2019-03-17T06:06:19.000Z
2019-03-17T06:06:19.000Z
framework/private/test/bundle_archive_test.cpp
rwalraven343/celix
353ac0d2e0f819f8f59d4cdf8ea1dfd701201d74
[ "Apache-2.0" ]
13
2019-02-21T21:27:44.000Z
2019-02-28T22:47:13.000Z
framework/private/test/bundle_archive_test.cpp
rwalraven343/celix
353ac0d2e0f819f8f59d4cdf8ea1dfd701201d74
[ "Apache-2.0" ]
null
null
null
/** *Licensed to the Apache Software Foundation (ASF) under one *or more contributor license agreements. See the NOTICE file *distributed with this work for additional information *regarding copyright ownership. The ASF licenses this file *to you under the Apache License, Version 2.0 (the *"License"); you may not use this file except in compliance *with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * *Unless required by applicable law or agreed to in writing, *software distributed under the License is distributed on an *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the *specific language governing permissions and limitations *under the License. */ /* * bundle_archive_test.cpp * * \date Feb 11, 2013 * \author <a href="mailto:dev@celix.apache.org">Apache Celix Project Team</a> * \copyright Apache License, Version 2.0 */ #include <stdlib.h> #include <stdio.h> #include <sys/stat.h> #include <dirent.h> #include <unistd.h> #include <string.h> #include "CppUTest/TestHarness.h" #include "CppUTest/TestHarness_c.h" #include "CppUTest/CommandLineTestRunner.h" #include "CppUTestExt/MockSupport.h" extern "C" { #include "bundle_archive.h" framework_logger_pt logger = (framework_logger_pt) 0x42; } int main(int argc, char** argv) { return RUN_ALL_TESTS(argc, argv); } //----------------------TESTGROUP DEFINES---------------------- TEST_GROUP(bundle_archive) { bundle_archive_pt bundle_archive; char * bundle_path; //uses the default build shell bundle char * alternate_bundle_path;//alternative bundle, if shell bundle not found char cache_path[512]; //a local cache folder void setup(void) { char cwd[512]; bundle_archive = NULL; bundle_path = (char*) "../shell/shell.zip"; //uses the default build shell bundle alternate_bundle_path = (char*) "../log_service/log_service.zip"; //alternative bundle, if shell bundle not found snprintf(cache_path, sizeof(cache_path), "%s/.cache", getcwd(cwd, sizeof(cwd))); //a local cache folder struct stat file_stat; if (stat(bundle_path, &file_stat) < 0) { if (stat(alternate_bundle_path, &file_stat) < 0) { FAIL("failed to find needed test bundle"); } else { bundle_path = alternate_bundle_path; } } } void teardown() { mock().checkExpectations(); mock().clear(); } }; //----------------------TEST DEFINES---------------------- //WARNING: if one test fails, it does not clean up properly, //causing most if not all of the subsequent tests to also fail TEST(bundle_archive, create) { mock().expectOneCall("framework_logCode").withParameter("code", CELIX_ILLEGAL_ARGUMENT); bundle_archive = (bundle_archive_pt) 0x42; LONGS_EQUAL(CELIX_ILLEGAL_ARGUMENT, bundleArchive_create(cache_path, 5, bundle_path, NULL, &bundle_archive)); bundle_archive = NULL; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 5, bundle_path, NULL, &bundle_archive)); CHECK(bundle_archive != NULL); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); } TEST(bundle_archive, createSystemBundleArchive) { mock().expectOneCall("framework_logCode").withParameter("code", CELIX_ILLEGAL_ARGUMENT); bundle_archive = (bundle_archive_pt) 0x42; LONGS_EQUAL(CELIX_ILLEGAL_ARGUMENT, bundleArchive_createSystemBundleArchive(&bundle_archive )); bundle_archive = NULL; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_createSystemBundleArchive(&bundle_archive)); CHECK(bundle_archive != NULL); //LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); } TEST(bundle_archive, recreate) { char * get_root; char * get_location; bundle_archive_pt recr_archive = NULL; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 5, bundle_path, NULL, &bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_recreate(cache_path, &recr_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getArchiveRoot(recr_archive, &get_root)); STRCMP_EQUAL(cache_path, get_root); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getLocation(recr_archive, &get_location)); STRCMP_EQUAL(bundle_path, get_location); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(recr_archive)); } TEST(bundle_archive, getId) { long get_id; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, -42, bundle_path, NULL, &bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getId(bundle_archive, &get_id)); LONGS_EQUAL(-42, get_id); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); bundle_archive = NULL; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 666, bundle_path, NULL, &bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getId(bundle_archive, &get_id)); LONGS_EQUAL(666, get_id); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); } TEST(bundle_archive, getLocation) { char * get_loc; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 1, bundle_path, NULL, &bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getLocation(bundle_archive, &get_loc)); STRCMP_EQUAL(bundle_path, get_loc); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); } TEST(bundle_archive, getArchiveRoot) { char * get_root; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 1, bundle_path, NULL, &bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getArchiveRoot(bundle_archive, &get_root)); STRCMP_EQUAL(cache_path, get_root); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); } TEST(bundle_archive, getCurrentRevisionNumber) { long get_rev_num; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 1, bundle_path, NULL, &bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getCurrentRevisionNumber(bundle_archive, &get_rev_num)); LONGS_EQUAL(0, get_rev_num); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_revise(bundle_archive, bundle_path, NULL)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getCurrentRevisionNumber(bundle_archive, &get_rev_num)); LONGS_EQUAL(1, get_rev_num); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_revise(bundle_archive, bundle_path, NULL)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getCurrentRevisionNumber(bundle_archive, &get_rev_num)); LONGS_EQUAL(2, get_rev_num); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); } TEST(bundle_archive, getCurrentRevision) { long get_rev_num; bundle_revision_pt get_rev; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 1, bundle_path, NULL, &bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getCurrentRevision(bundle_archive, &get_rev)); bundleRevision_getNumber(get_rev, &get_rev_num); LONGS_EQUAL(0, get_rev_num); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_revise(bundle_archive, bundle_path, NULL)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getCurrentRevision(bundle_archive, &get_rev)); bundleRevision_getNumber(get_rev, &get_rev_num); LONGS_EQUAL(1, get_rev_num); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); } TEST(bundle_archive, getRevision) { long get_rev_num; bundle_revision_pt get_rev; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 1, bundle_path, NULL, &bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_revise(bundle_archive, bundle_path, NULL)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_revise(bundle_archive, bundle_path, NULL)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getRevision(bundle_archive, 0, &get_rev)); bundleRevision_getNumber(get_rev, &get_rev_num); LONGS_EQUAL(0, get_rev_num); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getRevision(bundle_archive, 2, &get_rev)); bundleRevision_getNumber(get_rev, &get_rev_num); LONGS_EQUAL(2, get_rev_num); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getRevision(bundle_archive, 1, &get_rev)); bundleRevision_getNumber(get_rev, &get_rev_num); LONGS_EQUAL(1, get_rev_num); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); } TEST(bundle_archive, set_getPersistentState) { bundle_state_e get; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 1, bundle_path, NULL, &bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_setPersistentState(bundle_archive, OSGI_FRAMEWORK_BUNDLE_UNKNOWN)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getPersistentState(bundle_archive, &get)); LONGS_EQUAL(OSGI_FRAMEWORK_BUNDLE_INSTALLED, get); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_setPersistentState(bundle_archive, OSGI_FRAMEWORK_BUNDLE_ACTIVE)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getPersistentState(bundle_archive, &get)); LONGS_EQUAL(OSGI_FRAMEWORK_BUNDLE_ACTIVE, get); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_setPersistentState(bundle_archive, OSGI_FRAMEWORK_BUNDLE_STARTING)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getPersistentState(bundle_archive, &get)); LONGS_EQUAL(OSGI_FRAMEWORK_BUNDLE_STARTING, get); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_setPersistentState(bundle_archive, OSGI_FRAMEWORK_BUNDLE_UNINSTALLED)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getPersistentState(bundle_archive, &get)); LONGS_EQUAL(OSGI_FRAMEWORK_BUNDLE_UNINSTALLED, get); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); } TEST(bundle_archive, set_getRefreshCount) { long get_refresh_num; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 1, bundle_path, NULL, &bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getRefreshCount(bundle_archive, &get_refresh_num)); LONGS_EQUAL(0, get_refresh_num); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_setRefreshCount(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getRefreshCount(bundle_archive, &get_refresh_num)); LONGS_EQUAL(0, get_refresh_num); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); } TEST(bundle_archive, get_setLastModified) { time_t set_time; time_t get_time; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 1, bundle_path, NULL, &bundle_archive)); time(&set_time); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_setLastModified(bundle_archive, set_time)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getLastModified(bundle_archive, &get_time)); CHECK(set_time == get_time); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); } //CANT seem to find a way to test this static function /*TEST(bundle_archive, readLastModified) { mock().expectOneCall("framework_logCode"); time_t set_time; time_t get_time; bundle_archive_pt recr_archive = NULL; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 1, bundle_path, NULL, &bundle_archive)); time(&set_time); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_setLastModified(bundle_archive, set_time)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_recreate(cache_path, &recr_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getLastModified(recr_archive, &get_time)); LONGS_EQUAL(set_time, get_time); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); //LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); }*/ TEST(bundle_archive, rollbackRevise) { bool get; bundleArchive_rollbackRevise(NULL, &get); LONGS_EQUAL(true, get); }
39.079872
115
0.805347
rwalraven343
094b05ca1bfdaef50c964e7dda8ac06f8ed3a7db
396
cpp
C++
test/what_print.cpp
xdanielsb/OperatingSystems
23bf014fae9644d4512b2337739e52adcd1087d6
[ "MIT" ]
null
null
null
test/what_print.cpp
xdanielsb/OperatingSystems
23bf014fae9644d4512b2337739e52adcd1087d6
[ "MIT" ]
null
null
null
test/what_print.cpp
xdanielsb/OperatingSystems
23bf014fae9644d4512b2337739e52adcd1087d6
[ "MIT" ]
null
null
null
#include <sys/types.h> #include <sys/wait.h> // wait #include <stdio.h> #include <unistd.h> //fork int value = 5; int main(){ pid_t pid; pid = fork(); if (pid == 0) { /* child process */ value += 15; return 0; } else if (pid > 0) { /* parent process */ wait(NULL); printf("PARENT: value = %d\n",value); /* LINE A */ return 0; } }
19.8
58
0.494949
xdanielsb
094d3141328f988eef54456acd4d36168c361e9a
8,596
cpp
C++
lualib-src/fixmath/bounce/Dynamics/Contacts/b3ContactSolver.cpp
ChestnutGames/chestnut
720cf88779f480191ae16fb1ba4da4597e5797d9
[ "MIT" ]
null
null
null
lualib-src/fixmath/bounce/Dynamics/Contacts/b3ContactSolver.cpp
ChestnutGames/chestnut
720cf88779f480191ae16fb1ba4da4597e5797d9
[ "MIT" ]
null
null
null
lualib-src/fixmath/bounce/Dynamics/Contacts/b3ContactSolver.cpp
ChestnutGames/chestnut
720cf88779f480191ae16fb1ba4da4597e5797d9
[ "MIT" ]
1
2019-11-07T16:06:03.000Z
2019-11-07T16:06:03.000Z
/* * Copyright (c) 2015-2015 Irlan Robson http://www.irlans.wordpress.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include "b3ContactSolver.h" #include "b3Contact.h" #include "..\..\Collision\Shapes\b3Shape.h" #include "..\..\Dynamics\b3Body.h" #include "..\..\Common\Memory\b3StackAllocator.h" #include "..\..\Common\b3Time.h" b3ContactSolver::b3ContactSolver(const b3ContactSolverDef* def) { m_allocator = def->allocator; m_contacts = def->contacts; m_count = def->count; m_invDt = def->dt > B3_ZERO ? B3_ONE / def->dt : B3_ZERO; m_positions = def->positions; m_velocities = def->velocities; m_velocityConstraints = (b3ContactVelocityConstraint*)m_allocator->Allocate(m_count * sizeof(b3ContactVelocityConstraint)); for (u32 i = 0; i < m_count; ++i) { b3Contact* c = m_contacts[i]; b3ContactVelocityConstraint* vc = m_velocityConstraints + i; b3Body* bodyA = c->m_shapeA->GetBody(); b3Body* bodyB = c->m_shapeB->GetBody(); u32 pointCount = c->m_manifold.pointCount; b3Assert(pointCount > 0); vc->normal = c->m_manifold.normal; vc->invMassA = bodyA->m_invMass; vc->invMassB = bodyB->m_invMass; vc->invIA = bodyA->m_invWorldInertia; vc->invIB = bodyB->m_invWorldInertia; vc->friction = c->m_friction; vc->restitution = c->m_restitution; vc->indexA = bodyA->m_islandID; vc->indexB = bodyB->m_islandID; vc->pointCount = pointCount; for (u32 j = 0; j < pointCount; ++j) { b3ContactPoint* cp = c->m_manifold.points + j; b3VelocityConstraintPoint* vcp = vc->points + j; // Setup warm start. vcp->normalImpulse = cp->normalImpulse; vcp->tangentImpulse[0] = cp->tangentImpulse[0]; vcp->tangentImpulse[1] = cp->tangentImpulse[1]; vcp->tangents[0] = cp->tangents[0]; vcp->tangents[1] = cp->tangents[1]; } } } b3ContactSolver::~b3ContactSolver() { m_allocator->Free(m_velocityConstraints); } void b3ContactSolver::InitializeVelocityConstraints() { for (u32 i = 0; i < m_count; ++i) { b3Contact* c = m_contacts[i]; b3ContactVelocityConstraint* vc = m_velocityConstraints + i; r32 mA = vc->invMassA; r32 mB = vc->invMassB; b3Mat33 iA = vc->invIA; b3Mat33 iB = vc->invIB; u32 indexA = vc->indexA; u32 indexB = vc->indexB; u32 pointCount = c->m_manifold.pointCount; b3Vec3 vA = m_velocities[indexA].v; b3Vec3 wA = m_velocities[indexA].w; b3Vec3 xA = m_positions[indexA].x; b3Quaternion qA = m_positions[indexA].q; b3Vec3 vB = m_velocities[indexB].v; b3Vec3 wB = m_velocities[indexB].w; b3Vec3 xB = m_positions[indexB].x; b3Quaternion qB = m_positions[indexB].q; for (u32 j = 0; j < pointCount; ++j) { b3ContactPoint* cp = c->m_manifold.points + j; b3VelocityConstraintPoint* vcp = vc->points + j; vcp->rA = cp->position - xA; vcp->rB = cp->position - xB; // Compute tangent mass. b3Vec3 rt1A = b3Cross(vcp->rA, vcp->tangents[0]); b3Vec3 rt1B = b3Cross(vcp->rB, vcp->tangents[0]); b3Vec3 rt2A = b3Cross(vcp->rA, vcp->tangents[1]); b3Vec3 rt2B = b3Cross(vcp->rB, vcp->tangents[1]); r32 kTangent1 = mA + mB + b3Dot(rt1A, iA * rt1A) + b3Dot(rt1B, iB * rt1B); r32 kTangent2 = mA + mB + b3Dot(rt2A, iA * rt2A) + b3Dot(rt2B, iB * rt2B); vcp->tangentMass[0] = B3_ONE / kTangent1; vcp->tangentMass[1] = B3_ONE / kTangent2; // Compute normal mass. b3Vec3 rnA = b3Cross(vcp->rA, vc->normal); b3Vec3 rnB = b3Cross(vcp->rB, vc->normal); r32 kNormal = mA + mB + b3Dot(rnA, iA * rnA) + b3Dot(rnB, iB * rnB); vcp->normalMass = B3_ONE / kNormal; r32 C = b3Min(B3_ZERO, c->m_manifold.distances[j] + B3_LINEAR_SLOP); vcp->velocityBias = -m_invDt * B3_BAUMGARTE * C; // Add restitution in the velocity constraint. r32 vn = b3Dot(vB + b3Cross(wB, vcp->rB) - vA - b3Cross(wA, vcp->rA), vc->normal); if (vn < -B3_ONE) { vcp->velocityBias += -(c->m_restitution) * vn; } } } } void b3ContactSolver::WarmStart() { // Warm start. for (u32 i = 0; i < m_count; ++i) { b3ContactVelocityConstraint* vc = m_velocityConstraints + i; b3Vec3 normal = vc->normal; r32 mA = vc->invMassA; r32 mB = vc->invMassB; b3Mat33 iA = vc->invIA; b3Mat33 iB = vc->invIB; u32 indexA = vc->indexA; u32 indexB = vc->indexB; u32 pointCount = vc->pointCount; b3Vec3 vA = m_velocities[indexA].v; b3Vec3 wA = m_velocities[indexA].w; b3Vec3 vB = m_velocities[indexB].v; b3Vec3 wB = m_velocities[indexB].w; for (u32 j = 0; j < pointCount; ++j) { // Project old solutions into the new transposed Jacobians. b3VelocityConstraintPoint* vcp = vc->points + j; r32 lastNormalLambda = vcp->normalImpulse; r32 lastTangentLambda1 = vcp->tangentImpulse[0]; r32 lastTangentLambda2 = vcp->tangentImpulse[1]; b3Vec3 normalImpulse = lastNormalLambda * normal; b3Vec3 tangentImpulse1 = lastTangentLambda1 * vcp->tangents[0]; b3Vec3 tangentImpulse2 = lastTangentLambda2 * vcp->tangents[1]; b3Vec3 impulse = normalImpulse + tangentImpulse1 + tangentImpulse2; vA -= mA * impulse; wA -= iA * b3Cross(vcp->rA, impulse); vB += mB * impulse; wB += iB * b3Cross(vcp->rB, impulse); } m_velocities[indexA].v = vA; m_velocities[indexA].w = wA; m_velocities[indexB].v = vB; m_velocities[indexB].w = wB; } } void b3ContactSolver::SolveVelocityConstraints() { for (u32 i = 0; i < m_count; ++i) { b3ContactVelocityConstraint* vc = m_velocityConstraints + i; b3Vec3 normal = vc->normal; r32 mA = vc->invMassA; r32 mB = vc->invMassB; b3Mat33 iA = vc->invIA; b3Mat33 iB = vc->invIB; u32 indexA = vc->indexA; u32 indexB = vc->indexB; u32 pointCount = vc->pointCount; b3Vec3 vA = m_velocities[indexA].v; b3Vec3 wA = m_velocities[indexA].w; b3Vec3 vB = m_velocities[indexB].v; b3Vec3 wB = m_velocities[indexB].w; for (u32 j = 0; j < pointCount; ++j) { b3VelocityConstraintPoint* vcp = vc->points + j; { // Compute J * u. b3Vec3 dv = vB + b3Cross(wB, vcp->rB) - vA - b3Cross(wA, vcp->rA); r32 dCdt = b3Dot(dv, normal); // Compute new lambda values. r32 lambda = vcp->normalMass * (-dCdt + vcp->velocityBias); r32 newLambda = b3Max(vcp->normalImpulse + lambda, B3_ZERO); r32 deltaLambda = newLambda - vcp->normalImpulse; vcp->normalImpulse = newLambda; b3Vec3 deltaImpulse = deltaLambda * normal; vA -= mA * deltaImpulse; wA -= iA * b3Cross(vcp->rA, deltaImpulse); vB += mB * deltaImpulse; wB += iB * b3Cross(vcp->rB, deltaImpulse); } for (u32 k = 0; k < 2; ++k) { // Compute tangential impulse. r32 hi = vc->friction * vcp->normalImpulse; r32 lo = -hi; // Compute J * u. b3Vec3 dv = vB + b3Cross(wB, vcp->rB) - vA - b3Cross(wA, vcp->rA); r32 dCdt = b3Dot(dv, vcp->tangents[k]); // Compute new lambda values. r32 lambda = vcp->tangentMass[k] * -dCdt; r32 newLambda = b3Clamp(vcp->tangentImpulse[k] + lambda, lo, hi); r32 deltaLambda = newLambda - vcp->tangentImpulse[k]; vcp->tangentImpulse[k] = newLambda; b3Vec3 deltaImpulse = deltaLambda * vcp->tangents[k]; vA -= mA * deltaImpulse; wA -= iA * b3Cross(vcp->rA, deltaImpulse); vB += mB * deltaImpulse; wB += iB * b3Cross(vcp->rB, deltaImpulse); } } m_velocities[indexA].v = vA; m_velocities[indexA].w = wA; m_velocities[indexB].v = vB; m_velocities[indexB].w = wB; } } void b3ContactSolver::StoreImpulses() { for (u32 i = 0; i < m_count; ++i) { b3Contact* c = m_contacts[i]; b3ContactVelocityConstraint* vc = m_velocityConstraints + i; for (u32 j = 0; j < vc->pointCount; ++j) { b3VelocityConstraintPoint* vcp = vc->points + j; b3ContactPoint* cp = c->m_manifold.points + j; cp->normalImpulse = vcp->normalImpulse; cp->tangentImpulse[0] = vcp->tangentImpulse[0]; cp->tangentImpulse[1] = vcp->tangentImpulse[1]; } } }
31.487179
124
0.668334
ChestnutGames
0959eded48ad3f2cf9e3c83095eff3cf19ee341f
4,582
cxx
C++
src/ozw/zwNode.cxx
whpenner/upm
3168c61d8613da62ecc7598517a1decf533d5fe7
[ "MIT" ]
null
null
null
src/ozw/zwNode.cxx
whpenner/upm
3168c61d8613da62ecc7598517a1decf533d5fe7
[ "MIT" ]
null
null
null
src/ozw/zwNode.cxx
whpenner/upm
3168c61d8613da62ecc7598517a1decf533d5fe7
[ "MIT" ]
null
null
null
/* * Author: Jon Trulson <jtrulson@ics.com> * Copyright (c) 2015-2016 Intel Corporation. * * 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 <stdint.h> #include <string> #include <cinttypes> #include "zwNode.hpp" #include "Node.h" using namespace upm; using namespace std; using namespace OpenZWave; zwNode::zwNode(uint32_t homeId, uint8_t nodeId) { m_homeId = homeId; m_nodeId = nodeId; m_vindex = 0; m_list.clear(); m_values.clear(); m_autoUpdate = false; } zwNode::~zwNode() { } uint8_t zwNode::nodeId() { return m_nodeId; } uint32_t zwNode::homeId() { return m_homeId; } void zwNode::addValueID(ValueID vid) { m_list.push_back(vid); if (m_autoUpdate) updateVIDMap(); } void zwNode::removeValueID(ValueID vid) { m_list.remove(vid); if (m_autoUpdate) updateVIDMap(); } void zwNode::updateVIDMap() { m_values.clear(); m_vindex = 0; m_list.sort(); for (auto it = m_list.cbegin(); it != m_list.cend(); ++it) { // We need to use insert since ValueID's default ctor is private m_values.insert(std::pair<int, ValueID>(m_vindex++, *it)); } } bool zwNode::indexToValueID(int index, ValueID *vid) { valueMap_t::iterator it; it = m_values.find(index); if (it == m_values.end()) { // not found, return false return false; } else *vid = (*it).second; return true; } void zwNode::dumpNode(bool all) { for (auto it = m_values.cbegin(); it != m_values.cend(); ++it) { int vindex = it->first; ValueID vid = it->second; string label = Manager::Get()->GetValueLabel(vid); string valueAsStr; Manager::Get()->GetValueAsString(vid, &valueAsStr); string valueUnits = Manager::Get()->GetValueUnits(vid); ValueID::ValueType vType = vid.GetType(); string vTypeStr; string perms; if (Manager::Get()->IsValueWriteOnly(vid)) perms = "WO"; else if (Manager::Get()->IsValueReadOnly(vid)) perms = "RO"; else perms = "RW"; switch (vType) { case ValueID::ValueType_Bool: vTypeStr = "bool"; break; case ValueID::ValueType_Byte: vTypeStr = "byte"; break; case ValueID::ValueType_Decimal: vTypeStr = "float"; break; case ValueID::ValueType_Int: vTypeStr = "int32"; break; case ValueID::ValueType_List: vTypeStr = "list"; break; case ValueID::ValueType_Schedule: vTypeStr = "schedule"; break; case ValueID::ValueType_Short: vTypeStr = "int16"; break; case ValueID::ValueType_String: vTypeStr = "string"; break; case ValueID::ValueType_Button: vTypeStr = "button"; break; case ValueID::ValueType_Raw: vTypeStr = "raw"; break; default: vTypeStr = "undefined"; break; } // by default we only want user values, unless 'all' is true if (all || (vid.GetGenre() == ValueID::ValueGenre_User)) { fprintf(stderr, "\t Index: %d, Type: %s, Label: %s, Value: %s %s (%s)\n", vindex, vTypeStr.c_str(), label.c_str(), valueAsStr.c_str(), valueUnits.c_str(), perms.c_str()); fprintf(stderr, "\t\t VID: %016" PRIx64 "\n", vid.GetId()); } } }
23.141414
83
0.606285
whpenner
0959f0c4e1b8fd7238398cf8b691ed44e495d065
2,953
hpp
C++
include/System/Xml/Schema/RangePositionInfo.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Xml/Schema/RangePositionInfo.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Xml/Schema/RangePositionInfo.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" // Including type: System.Decimal #include "System/Decimal.hpp" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Xml::Schema namespace System::Xml::Schema { // Forward declaring type: BitSet class BitSet; } // Completed forward declares // Type namespace: System.Xml.Schema namespace System::Xml::Schema { // Forward declaring type: RangePositionInfo struct RangePositionInfo; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::System::Xml::Schema::RangePositionInfo, "System.Xml.Schema", "RangePositionInfo"); // Type namespace: System.Xml.Schema namespace System::Xml::Schema { // Size: 0x10 #pragma pack(push, 1) // WARNING Layout: Sequential may not be correctly taken into account! // Autogenerated type: System.Xml.Schema.RangePositionInfo // [TokenAttribute] Offset: FFFFFFFF struct RangePositionInfo/*, public ::System::ValueType*/ { public: public: // public System.Xml.Schema.BitSet curpos // Size: 0x8 // Offset: 0x0 ::System::Xml::Schema::BitSet* curpos; // Field size check static_assert(sizeof(::System::Xml::Schema::BitSet*) == 0x8); // public System.Decimal[] rangeCounters // Size: 0x8 // Offset: 0x8 ::ArrayW<::System::Decimal> rangeCounters; // Field size check static_assert(sizeof(::ArrayW<::System::Decimal>) == 0x8); public: // Creating value type constructor for type: RangePositionInfo constexpr RangePositionInfo(::System::Xml::Schema::BitSet* curpos_ = {}, ::ArrayW<::System::Decimal> rangeCounters_ = ::ArrayW<::System::Decimal>(static_cast<void*>(nullptr))) noexcept : curpos{curpos_}, rangeCounters{rangeCounters_} {} // Creating interface conversion operator: operator ::System::ValueType operator ::System::ValueType() noexcept { return *reinterpret_cast<::System::ValueType*>(this); } // Get instance field reference: public System.Xml.Schema.BitSet curpos [[deprecated("Use field access instead!")]] ::System::Xml::Schema::BitSet*& dyn_curpos(); // Get instance field reference: public System.Decimal[] rangeCounters [[deprecated("Use field access instead!")]] ::ArrayW<::System::Decimal>& dyn_rangeCounters(); }; // System.Xml.Schema.RangePositionInfo #pragma pack(pop) static check_size<sizeof(RangePositionInfo), 8 + sizeof(::ArrayW<::System::Decimal>)> __System_Xml_Schema_RangePositionInfoSizeCheck; static_assert(sizeof(RangePositionInfo) == 0x10); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
44.074627
240
0.709448
v0idp
095a7b30837fe2e296d01cf71c341c322ad91b94
4,679
cpp
C++
cpp/example_code/dynamodb/query_items.cpp
brmur/aws-doc-sdk-examples
9158f493ee2c016f0b4a2260e8f43acc7b0b49e6
[ "Apache-2.0" ]
null
null
null
cpp/example_code/dynamodb/query_items.cpp
brmur/aws-doc-sdk-examples
9158f493ee2c016f0b4a2260e8f43acc7b0b49e6
[ "Apache-2.0" ]
1
2020-03-18T17:00:15.000Z
2020-03-18T17:04:05.000Z
cpp/example_code/dynamodb/query_items.cpp
brmur/aws-doc-sdk-examples
9158f493ee2c016f0b4a2260e8f43acc7b0b49e6
[ "Apache-2.0" ]
null
null
null
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX - License - Identifier: Apache - 2.0 /* Purpose: query_items.cpp demonstrates how to perfrom Query operation and retrieve items from an Amazon DynamoDB table. */ //snippet-start:[dynamodb.cpp.query_items.inc] #include <aws/core/Aws.h> #include <aws/core/utils/Outcome.h> #include <aws/dynamodb/DynamoDBClient.h> #include <aws/dynamodb/model/AttributeDefinition.h> #include <aws/dynamodb/model/QueryRequest.h> #include <iostream> //snippet-end:[dynamodb.cpp.query_items.inc] /** * Perform query on a DynamoDB Table and retrieve item(s). * * Takes the name of the table and partition key attribute name and value to query. * * The partition key attribute is searched with the specified value. By default, all fields and values * contained in the item are returned. If an optional projection expression is * specified on the command line, only the specified fields and values are * returned. * */ int main(int argc, char** argv) { const std::string USAGE = "\n" \ "Usage:\n" " query_items <table> <partitionKeyAttributeName>=<partitionKeyValue> [projection_expression]\n\n" "Where:\n" " table - the table to get an item from.\n" " partitionKeyAttributeName - Partition Key attribute of the table.\n" " partitionKeyValue - Partition Key value to query.\n\n" "You can add an optional projection expression (a quote-delimited,\n" "comma-separated list of attributes to retrieve) to limit the\n" "fields returned from the table.\n\n" "Example:\n" " query_items HelloTable Name=Namaste\n" " query_items Players FirstName=Mike\n" " query_items SiteColors Background=white \"default, bold\"\n"; if (argc < 3) { std::cout << USAGE; return 1; } Aws::SDKOptions options; Aws::InitAPI(options); { const Aws::String table(argv[1]); const Aws::String partitionKeyNameAndValue(argv[2]); Aws::String partitionKeyAttributeName(""); Aws::String partitionKeyAttributeValue(""); // Split and get partitionKeyAttributeName and partitionKeyAttributeValue const Aws::Vector<Aws::String>& flds = Aws::Utils::StringUtils::Split(partitionKeyNameAndValue, '='); if (flds.size() == 2) { partitionKeyAttributeName = flds[0]; partitionKeyAttributeValue = flds[1]; } else { std::cout << "Invalid argument: " << partitionKeyNameAndValue << std::endl << USAGE; return 1; } const Aws::String projection(argc > 3 ? argv[3] : ""); // snippet-start:[dynamodb.cpp.query_items.code] Aws::Client::ClientConfiguration clientConfig; Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfig); Aws::DynamoDB::Model::QueryRequest req; req.SetTableName(table); // Set query key condition expression req.SetKeyConditionExpression(partitionKeyAttributeName + "= :valueToMatch"); // Set Expression AttributeValues Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> attributeValues; attributeValues.emplace(":valueToMatch", partitionKeyAttributeValue); req.SetExpressionAttributeValues(attributeValues); // Perform Query operation const Aws::DynamoDB::Model::QueryOutcome& result = dynamoClient.Query(req); if (result.IsSuccess()) { // Reference the retrieved items const Aws::Vector<Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue>>& items = result.GetResult().GetItems(); if(items.size() > 0) { std::cout << "Number of items retrieved from Query: " << items.size() << std::endl; //Iterate each item and print for(const auto &item: items) { std::cout << "******************************************************" << std::endl; // Output each retrieved field and its value for (const auto& i : item) std::cout << i.first << ": " << i.second.GetS() << std::endl; } } else { std::cout << "No item found in table: " << table << std::endl; } } else { std::cout << "Failed to Query items: " << result.GetError().GetMessage(); } // snippet-end:[dynamodb.cpp.query_items.code] } Aws::ShutdownAPI(options); return 0; }
36.554688
130
0.60312
brmur
095a954b9b931effd33d133383a2ae1d34574731
4,391
cpp
C++
test/datetime/main.cpp
HanixNicolas/app-mesh
8ee77a6adb1091b3a0afcbc34d271b4b9508840e
[ "MIT" ]
90
2020-06-06T12:11:33.000Z
2022-01-04T11:30:24.000Z
test/datetime/main.cpp
HanixNicolas/app-mesh
8ee77a6adb1091b3a0afcbc34d271b4b9508840e
[ "MIT" ]
80
2020-05-19T14:33:34.000Z
2022-03-25T08:00:54.000Z
test/datetime/main.cpp
HanixNicolas/app-mesh
8ee77a6adb1091b3a0afcbc34d271b4b9508840e
[ "MIT" ]
14
2020-07-16T11:35:47.000Z
2022-01-04T03:10:44.000Z
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "../../src/common/DateTime.h" #include "../../src/common/Utility.h" #include "../catch.hpp" #include <ace/Init_ACE.h> #include <ace/OS.h> #include <chrono> #include <fstream> #include <iostream> #include <log4cpp/Appender.hh> #include <log4cpp/Category.hh> #include <log4cpp/FileAppender.hh> #include <log4cpp/OstreamAppender.hh> #include <log4cpp/PatternLayout.hh> #include <log4cpp/Priority.hh> #include <log4cpp/RollingFileAppender.hh> #include <set> #include <string> #include <thread> #include <time.h> void init() { static bool initialized = false; if (!initialized) { initialized = true; ACE::init(); using namespace log4cpp; auto logDir = Utility::stringFormat("%s", Utility::getSelfDir().c_str()); auto consoleLayout = new PatternLayout(); consoleLayout->setConversionPattern("%d [%t] %p %c: %m%n"); auto consoleAppender = new OstreamAppender("console", &std::cout); consoleAppender->setLayout(consoleLayout); auto rollingFileAppender = new RollingFileAppender( "rollingFileAppender", logDir.append("/unittest.log"), 20 * 1024 * 1024, 5, true, 00664); auto pLayout = new PatternLayout(); pLayout->setConversionPattern("%d [%t] %p %c: %m%n"); rollingFileAppender->setLayout(pLayout); Category &root = Category::getRoot(); root.addAppender(rollingFileAppender); root.addAppender(consoleAppender); // Log level Utility::setLogLevel("DEBUG"); LOG_INF << "Logging process ID:" << getpid(); } } TEST_CASE("DateTime Class Test", "[DateTime]") { init(); // covert now to seconds auto now = std::chrono::system_clock::now(); std::string timeStr = "2020-10-08T14:14:00+08"; LOG_DBG << timeStr << " is " << DateTime::formatISO8601Time(DateTime::parseISO8601DateTime(timeStr, "")); auto localTime = std::chrono::system_clock::from_time_t(std::chrono::system_clock::to_time_t(now)); LOG_DBG << "now: " << DateTime::formatISO8601Time(localTime); REQUIRE(localTime == DateTime::parseISO8601DateTime(DateTime::formatISO8601Time(localTime), "")); // parseISO8601DateTime try { DateTime::parseISO8601DateTime("123"); } catch (...) { REQUIRE(true); } REQUIRE(DateTime::parseISO8601DateTime("") == std::chrono::system_clock::from_time_t(0)); auto iso8601 = "2020-10-07T21:19:00+08"; auto iso8601TimePoint = DateTime::parseISO8601DateTime(iso8601, ""); REQUIRE(iso8601TimePoint == DateTime::parseISO8601DateTime("2020-10-07T21:19:00+8", "")); REQUIRE_FALSE(DateTime::parseISO8601DateTime("2020-10-07T21:19:00", "") == DateTime::parseISO8601DateTime("2020-10-07T21:19:00+07", "")); // formatRFC3339Time auto rfc3339 = "2020-10-07T13:19:00Z"; LOG_DBG << DateTime::formatRFC3339Time(iso8601TimePoint); REQUIRE(DateTime::formatRFC3339Time(iso8601TimePoint) == rfc3339); // getLocalZoneUTCOffset LOG_DBG << DateTime::getLocalZoneUTCOffset(); REQUIRE(boost::posix_time::to_simple_string(DateTime::parseDayTimeUtcDuration("20:33:00", "+08")) == "12:33:00"); // time in different zone REQUIRE(DateTime::parseISO8601DateTime("2020-10-07T21:19:00+07", "") == DateTime::parseISO8601DateTime("2020-10-07T22:19:00+08", "")); } TEST_CASE("Boost Date Time Test", "[Boost]") { init(); LOG_DBG << "get_std_zone_abbrev: " << machine_time_zone::get_std_zone_abbrev(); LOG_DBG << "get_utc_offset: " << machine_time_zone::get_utc_offset(); REQUIRE(boost::posix_time::to_simple_string(boost::posix_time::duration_from_string("-08:00")) == "-08:00:00"); REQUIRE(boost::posix_time::to_simple_string(boost::posix_time::duration_from_string("08:00")) == "08:00:00"); REQUIRE(boost::posix_time::to_simple_string(boost::posix_time::duration_from_string("+20:01:00")) == "20:01:00"); REQUIRE(boost::posix_time::to_simple_string(boost::posix_time::duration_from_string("-20:01")) == "-20:01:00"); REQUIRE(boost::posix_time::to_simple_string(boost::posix_time::duration_from_string("8")) == "08:00:00"); REQUIRE(boost::posix_time::to_simple_string(boost::posix_time::duration_from_string("+8")) == "08:00:00"); }
38.858407
141
0.669551
HanixNicolas
095a9f4ba64148dadce2bc756c03e8ab9972ae13
2,168
cpp
C++
for c++/data/sfatima/usetsm.cpp
aerolalit/Auto-Testing-Python-Programs
dd49ab266c9f0fd8e34278f68f8af017711942e3
[ "MIT" ]
4
2019-10-03T21:16:51.000Z
2019-10-04T01:28:08.000Z
for c++/data/sfatima/usetsm.cpp
aerolalit/Auto-Testing
dd49ab266c9f0fd8e34278f68f8af017711942e3
[ "MIT" ]
null
null
null
for c++/data/sfatima/usetsm.cpp
aerolalit/Auto-Testing
dd49ab266c9f0fd8e34278f68f8af017711942e3
[ "MIT" ]
null
null
null
/* CH08-320143 a4_p3.cpp Syeda Alizae Fatima s.fatima@jacobs-university.de */ #include <iostream> #include <cstdlib> #include <set> #include <algorithm> using namespace std; int main(){ int n; set <int> A; multiset <int> B; multiset <int> uni; set <int> intersection; set <int> difference; set <int> symmetric; set<int>::iterator si; multiset<int>::iterator mi; cin >> n; while(1) { if(n<0) break; A.insert(n); B.insert(n); cin >> n; } cout << endl << "A: "; for(si = A.begin(); si != A.end(); si++) cout << *si << " "; cout << endl << endl; cout << "B: "; for(mi = B.begin(); mi != B.end(); mi++) cout << *mi << " "; cout << endl; A.erase(5); B.erase(5); cout << endl << "A: "; for(si = A.begin(); si != A.end(); si++) cout << *si << " "; cout << endl << endl; cout << "B: "; for(mi = B.begin(); mi != B.end(); mi++) cout << *mi << " "; cout << endl; A.insert(14); A.insert(198); set_union(A.begin(),A.end(),B.begin(),B.end(),inserter(uni,uni.begin())); cout << endl << "Union:"; for(mi = uni.begin(); mi != uni.end(); mi++) cout << *mi << " "; cout << endl; set_intersection(A.begin(),A.end(),B.begin(),B.end(),inserter(intersection,intersection.begin())); cout << endl << "Intersection:"; for(si = intersection.begin(); si != intersection.end(); si++) cout << *si << " "; cout << endl; set_difference(A.begin(),A.end(),B.begin(),B.end(),inserter(difference,difference.begin())); cout << endl << "Difference:"; for(si = difference.begin(); si != difference.end(); si++) cout << *si << " "; cout << endl; set_symmetric_difference(A.begin(),A.end(),B.begin(),B.end(),inserter(symmetric,symmetric.begin())); cout << endl << "Symmetric difference:"; for(si = symmetric.begin(); si != symmetric.end(); si++) cout << *si << " "; cout << endl; return 0; }
22.821053
105
0.480627
aerolalit
095f1354b8a02f6f329d7736e4bb603f5ed9f2b4
710
cpp
C++
p14889.cpp
sjnov11/Baekjoon-Online-Judge
a95df8a62e181d86a97d0e8969d139a3dae2be74
[ "MIT" ]
null
null
null
p14889.cpp
sjnov11/Baekjoon-Online-Judge
a95df8a62e181d86a97d0e8969d139a3dae2be74
[ "MIT" ]
null
null
null
p14889.cpp
sjnov11/Baekjoon-Online-Judge
a95df8a62e181d86a97d0e8969d139a3dae2be74
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> #include <algorithm> using namespace std; int N; int S[21][21]; int A[21]; int answer = 99999999; void go(int idx, int cnt) { if (cnt == N / 2) { int A_score = 0; int B_score = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (A[i] == 1 && A[j] == 1) A_score += S[i][j]; if (A[i] == 0 && A[j] == 0) B_score += S[i][j]; } } answer = min(answer, abs(A_score - B_score)); return; } if (idx == N) return; go(idx + 1, cnt); A[idx] = 1; go(idx + 1, cnt + 1); A[idx] = 0; } int main() { cin >> N; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cin >> S[i][j]; } } go(0, 0); cout << answer << endl; }
16.904762
51
0.473239
sjnov11
095feab036982b34e11aea96d4377a8f1939e700
967
cpp
C++
bzoj/2464.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
3
2017-09-17T09:12:50.000Z
2018-04-06T01:18:17.000Z
bzoj/2464.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
bzoj/2464.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
#include <bits/stdc++.h> #define ll long long using namespace std; int n, m, mp[502][502], a[4]={0,1,0,-1}, sx, sy, ex, ey, ans[505][505]; char c[505]; struct node{ int x, y, time; }; queue<node> q; void dfs(){ node s; while(!q.empty()){ s = q.front();q.pop(); if(ans[s.x][s.y] <= s.time) continue; ans[s.x][s.y] = s.time; for(int i = 0; i < 4; i++){ if(s.x+a[i]>n||s.x+a[i]<1||s.y+a[3-i]>m||s.y+a[3-i]<1)continue; if(mp[s.x][s.y] == mp[s.x+a[i]][s.y+a[3-i]]) q.push((node){s.x+a[i], s.y+a[3-i], s.time}); else q.push((node){s.x+a[i], s.y+a[3-i], s.time+1}); } } printf("%d\n", ans[ex][ey]); } int main(){ while(~scanf("%d%d", &n, &m) && n && m){ memset(mp, 0, sizeof mp); memset(ans, 127/3, sizeof ans); for(int i = 1; i <= n; i++){ scanf("%s", c); for(int j = 0; j < m; j++) mp[i][j+1] = (c[j] == '@'); } scanf("%d%d%d%d", &sx, &sy, &ex, &ey); ex++,ey++; q.push((node){sx+1, sy+1, 0}); dfs(); } return 0; }
23.02381
71
0.4788
swwind
8231328deb968f632cee6436163ddb145cf4a364
1,093
cpp
C++
libvast/test/index/enumeration_index.cpp
lava/vast
0bc9e3c12eb31ec50dd0270626d55e84b2255899
[ "BSD-3-Clause" ]
1
2021-05-14T02:03:17.000Z
2021-05-14T02:03:17.000Z
libvast/test/index/enumeration_index.cpp
5l1v3r1/vast
a2cb4be879a13cef855da2c1d73083204aed4dff
[ "BSD-3-Clause" ]
null
null
null
libvast/test/index/enumeration_index.cpp
5l1v3r1/vast
a2cb4be879a13cef855da2c1d73083204aed4dff
[ "BSD-3-Clause" ]
null
null
null
// _ _____ __________ // | | / / _ | / __/_ __/ Visibility // | |/ / __ |_\ \ / / Across // |___/_/ |_/___/ /_/ Space and Time // // SPDX-FileCopyrightText: (c) 2020 The VAST Contributors // SPDX-License-Identifier: BSD-3-Clause #define SUITE value_index #include "vast/index/enumeration_index.hpp" #include "vast/concept/printable/to_string.hpp" #include "vast/concept/printable/vast/bitmap.hpp" #include "vast/test/test.hpp" #include <caf/test/dsl.hpp> using namespace vast; using namespace std::string_literals; TEST(enumeration) { auto e = enumeration_type{{"foo", "bar"}}; auto idx = enumeration_index(e); REQUIRE(idx.append(enumeration{0})); REQUIRE(idx.append(enumeration{0})); REQUIRE(idx.append(enumeration{1})); REQUIRE(idx.append(enumeration{0})); auto foo = idx.lookup(relational_operator::equal, make_data_view(enumeration{0})); CHECK_EQUAL(to_string(foo), "1101"); auto bar = idx.lookup(relational_operator::not_equal, make_data_view(enumeration{0})); CHECK_EQUAL(to_string(bar), "0010"); }
30.361111
77
0.673376
lava
82375faee2505d17fdd5800bfc7c7b69f49302b5
2,309
cpp
C++
src/HRI.cpp
qqzz0xx/bgfx-with-imgui-example-cmake
18add8dedd11fbfe0f644f0693adfb21f5cc4606
[ "BSD-2-Clause" ]
null
null
null
src/HRI.cpp
qqzz0xx/bgfx-with-imgui-example-cmake
18add8dedd11fbfe0f644f0693adfb21f5cc4606
[ "BSD-2-Clause" ]
null
null
null
src/HRI.cpp
qqzz0xx/bgfx-with-imgui-example-cmake
18add8dedd11fbfe0f644f0693adfb21f5cc4606
[ "BSD-2-Clause" ]
null
null
null
#include "HRI.h" #include "bgfx/bgfx.h" #include "bx/math.h" #include <array> #include <vector> #include <memory_resource> using mat4 = std::array<float, 16>; struct HRIContext; static mat4 makeMat4(); struct HRIContext { std::vector<mat4> modelMatrixs; std::vector<mat4> viewMatrixs; std::vector<mat4> projectMatrixs; HRIContext() { modelMatrixs.push_back(makeMat4()); viewMatrixs.push_back(makeMat4()); projectMatrixs.push_back(makeMat4()); } }; static HRIContext s_ctx; static mat4 makeMat4() { mat4 res = { 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 }; return res; } void HRI::push_viewTarget(uint16_t viewId) { } void HRI::pop_viewTarget() { } void HRI::push_matrix() { s_ctx.modelMatrixs.push_back(makeMat4()); } void HRI::pop_matrix() { s_ctx.modelMatrixs.pop_back(); } void HRI::setMatrix(float m[16]) { auto& cur = s_ctx.modelMatrixs.back(); memcpy(cur.data(), m, 16 * sizeof(float)); } void HRI::push_viewMatrix() { s_ctx.viewMatrixs.push_back(makeMat4()); } void HRI::pop_viewMatrix() { s_ctx.viewMatrixs.pop_back(); } void HRI::push_projectMatrix() { s_ctx.projectMatrixs.push_back(makeMat4()); } void HRI::pop_projectMatrix() { s_ctx.projectMatrixs.pop_back(); } void HRI::ortho(float _left, float _right, float _bottom, float _top, float _near, float _far, float _offset) { auto& cur = s_ctx.projectMatrixs.back(); auto caps = bgfx::getCaps(); bx::mtxOrtho(cur.data(), _left, _right, _bottom, _top, _near, _far, _offset, caps->homogeneousDepth); } void HRI::perspective(float _fovy, float _aspect, float _near, float _far) { auto& cur = s_ctx.projectMatrixs.back(); auto caps = bgfx::getCaps(); bx::mtxProj(cur.data(), _fovy, _aspect, _near, _far, caps->homogeneousDepth); } void HRI::push_MVP() { push_matrix(); push_viewMatrix(); push_projectMatrix(); } void HRI::updateMVP(uint16_t viewId) { const auto& curModel = s_ctx.modelMatrixs.back(); const auto& curView = s_ctx.viewMatrixs.back(); const auto& curProj = s_ctx.projectMatrixs.back(); bgfx::setTransform(curModel.data()); bgfx::setViewTransform(viewId, curView.data(), curProj.data()); } void HRI::pop_MVP() { pop_matrix(); pop_viewMatrix(); pop_projectMatrix(); } void HRI::draw_rect(float x, float y, int w, int h) { }
18.181102
109
0.689476
qqzz0xx
8241cba0d258a27076a85a09fb31795eaae60bd6
3,995
hpp
C++
tlx/thread_barrier_spin.hpp
mullovc/tlx
e7c17b5981cbd7912b689fa0ad993e18424e26fe
[ "BSL-1.0" ]
284
2017-02-26T08:49:15.000Z
2022-03-30T21:55:37.000Z
tlx/thread_barrier_spin.hpp
xiao2mo/tlx
b311126e670753897c1defceeaa75c83d2d9531a
[ "BSL-1.0" ]
24
2017-09-05T21:02:41.000Z
2022-03-07T10:09:59.000Z
tlx/thread_barrier_spin.hpp
xiao2mo/tlx
b311126e670753897c1defceeaa75c83d2d9531a
[ "BSL-1.0" ]
62
2017-02-23T12:29:27.000Z
2022-03-31T07:45:59.000Z
/******************************************************************************* * tlx/thread_barrier_spin.hpp * * Part of tlx - http://panthema.net/tlx * * Copyright (C) 2015-2019 Timo Bingmann <tb@panthema.net> * * All rights reserved. Published under the Boost Software License, Version 1.0 ******************************************************************************/ #ifndef TLX_THREAD_BARRIER_SPIN_HEADER #define TLX_THREAD_BARRIER_SPIN_HEADER #include <tlx/meta/no_operation.hpp> #include <atomic> #include <thread> namespace tlx { /*! * Implements a thread barrier using atomics and a spin lock that can be used to * synchronize threads. * * This ThreadBarrier implementation was a lot faster in tests than * ThreadBarrierMutex, but ThreadSanitizer shows data races (probably due to the * generation counter). */ class ThreadBarrierSpin { public: /*! * Creates a new barrier that waits for n threads. */ explicit ThreadBarrierSpin(size_t thread_count) : thread_count_(thread_count - 1) { } /*! * Waits for n threads to arrive. When they have arrive, execute lambda on * the one thread, which arrived last. After lambda, step the generation * counter. * * This method blocks and returns as soon as n threads are waiting inside * the method. */ template <typename Lambda = NoOperation<void> > void wait(Lambda lambda = Lambda()) { // get synchronization generation step counter. size_t this_step = step_.load(std::memory_order_acquire); if (waiting_.fetch_add(1, std::memory_order_acq_rel) == thread_count_) { // we are the last thread to wait() -> reset and increment step. waiting_.store(0, std::memory_order_release); // step other generation counters. lambda(); // the following statement releases all threads from busy waiting. step_.fetch_add(1, std::memory_order_acq_rel); } else { // spin lock awaiting the last thread to increment the step counter. while (step_.load(std::memory_order_acquire) == this_step) { // busy spinning loop } } } /*! * Waits for n threads to arrive, yield thread while spinning. When they * have arrive, execute lambda on the one thread, which arrived last. After * lambda, step the generation counter. * * This method blocks and returns as soon as n threads are waiting inside * the method. */ template <typename Lambda = NoOperation<void> > void wait_yield(Lambda lambda = Lambda()) { // get synchronization generation step counter. size_t this_step = step_.load(std::memory_order_acquire); if (waiting_.fetch_add(1, std::memory_order_acq_rel) == thread_count_) { // we are the last thread to wait() -> reset and increment step. waiting_.store(0, std::memory_order_release); // step other generation counters. lambda(); // the following statement releases all threads from busy waiting. step_.fetch_add(1, std::memory_order_acq_rel); } else { // spin lock awaiting the last thread to increment the step counter. while (step_.load(std::memory_order_acquire) == this_step) { std::this_thread::yield(); } } } //! Return generation step counter size_t step() const { return step_.load(std::memory_order_acquire); } protected: //! number of threads, minus one due to comparison needed in loop const size_t thread_count_; //! number of threads in spin lock std::atomic<size_t> waiting_ { 0 }; //! barrier synchronization generation std::atomic<size_t> step_ { 0 }; }; } // namespace tlx #endif // !TLX_THREAD_BARRIER_SPIN_HEADER /******************************************************************************/
34.145299
80
0.609262
mullovc
82450868873c8ef8d2b6bbbe2e481dc5b7857c12
1,530
hxx
C++
include/jsservice.hxx
ostosh/jsbinder
fa75fe5ff31501ca1513a8a77e851c437978e26d
[ "BSD-3-Clause" ]
7
2015-04-29T20:38:59.000Z
2021-06-02T11:47:37.000Z
include/jsservice.hxx
ostosh/jsbinder
fa75fe5ff31501ca1513a8a77e851c437978e26d
[ "BSD-3-Clause" ]
null
null
null
include/jsservice.hxx
ostosh/jsbinder
fa75fe5ff31501ca1513a8a77e851c437978e26d
[ "BSD-3-Clause" ]
2
2016-02-02T07:13:45.000Z
2020-10-18T21:39:15.000Z
/* * Copyright (C) 2015,2017 Opersys inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _JSSERVICE_HXX #define _JSSERVICE_HXX #include <nan.h> #include <binder/Parcel.h> using namespace android; class JsService : public Nan::ObjectWrap { public: static NAN_MODULE_INIT(Init); void setService(sp<IBinder> sv) { assert(sv != 0); this->sv = sv; } private: friend class JsServiceManager; static Nan::Persistent<v8::Function> & constructor() { static Nan::Persistent<v8::Function> jsServiceConstructor; return jsServiceConstructor; } static NAN_METHOD(New); static NAN_METHOD(Ping); static NAN_METHOD(Transact); static NAN_METHOD(GetInterface); static NAN_METHOD(Dump); // The memory that is reserved for dumpMem calls on the service. const int dumpAreaSize = 4096000; void *dumpArea; int dumpFd; sp<IBinder> sv; explicit JsService(); ~JsService(); }; #endif // _JSSERVICE_HXX
25.5
75
0.690196
ostosh
824afca41ba01026ae5a840d80d20113822a46ed
300
cpp
C++
deep_ptr_test.cpp
jbcoe/deep_ptr
ba76ed1d64dc47edd23020441c165a579734c638
[ "MIT" ]
2
2021-03-19T17:42:04.000Z
2021-03-19T18:10:42.000Z
deep_ptr_test.cpp
jbcoe/deep_ptr
ba76ed1d64dc47edd23020441c165a579734c638
[ "MIT" ]
19
2016-01-10T23:01:30.000Z
2020-03-05T10:54:06.000Z
deep_ptr_test.cpp
jbcoe/deep_ptr
ba76ed1d64dc47edd23020441c165a579734c638
[ "MIT" ]
2
2020-02-28T23:42:41.000Z
2021-03-19T17:42:05.000Z
#define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> #include "deep_ptr.h" using namespace jbcoe; TEST_CASE("Ensure that deep_ptr default construction produces a default initialised deep_ptr", "[deep_ptr.constructor]") { deep_ptr<int> instance; REQUIRE(instance.operator->() == nullptr); }
27.272727
120
0.76
jbcoe
82502b5efb095f696d705a99b0e69570d2a5f736
5,604
cpp
C++
src/main/cpp/Commands/AutoSlalom.cpp
1828Boxerbots/AllRobotsInOneCode
95814c320517ff3cc53cade380c25bca4a3b1914
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/Commands/AutoSlalom.cpp
1828Boxerbots/AllRobotsInOneCode
95814c320517ff3cc53cade380c25bca4a3b1914
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/Commands/AutoSlalom.cpp
1828Boxerbots/AllRobotsInOneCode
95814c320517ff3cc53cade380c25bca4a3b1914
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #include "Commands/AutoSlalom.h" AutoSlalom::AutoSlalom(DriveTrainSubsystemBase *pDrive) { // Use Requires() here to declare subsystem dependencies // eg. Requires(Robot::chassis.get()); m_pDrive = pDrive; AddRequirements(pDrive); //bruh } // Called just before this Command runs the first time void AutoSlalom::Initialize() { timer.Start(); m_pDrive->SetLookingColorV(OldCameraVision::GREEN_CONE_A); } // Called repeatedly when this Command is scheduled to run void AutoSlalom::Execute() { if (m_pDrive != nullptr) { /* SwitchColor(DriveTrainSubsystemBase::BROWN); loop1(); loop2(); loop3(); SwitchColor(DriveTrainSubsystemBase::BLUE); loop4(); loop5(); loop6(); */ /* if (m_loopsUpdate != 0) { m_state++; m_loopsUpdate = 0; //m_result = 0; } */ //Color 1 is Green //Color 2 is Red Util::Log("Auto2021 State", m_state); m_result = m_pDrive->WhereToTurn(m_center, 25); switch (m_state) { case 0: loop0(); break; /* case 1: m_pDrive->SetLookingColorV(OldCameraVision::GREEN_CONE_N); loop1(); break; case 2: loop2(); break; case 3: loop3(); break; case 4: loop4(); break; case 5: m_pDrive->SetLookingColorV(OldCameraVision::PURPLE_BOTTLE_N); loop5(); break; case 6: loop6(); break; */ default: m_pDrive->Stop(); break; } } } bool AutoSlalom::IsFinished() { if (m_IsFinished) { Util::Log("Auto2021 Finished", "IsFinished = true"); m_pDrive->Stop(); } else { Util::Log("Auto2021 Finished", "IsFinished = false"); } return m_IsFinished; } void AutoSlalom::loop0() { //Forward, left, forward, right m_pDrive->TimedArcade(0.6, -0.2, 1.15); m_pDrive->TimedArcade(0.6, 0.2, 1.17); //Move the 10 feet or so m_pDrive->ForwardInInch(107, 0, 0.8); //Loop around the cone m_pDrive->TimedArcade(0.6, 0.2, 1.20); m_pDrive->TimedArcade(0.6, -0.24, 3.8); //Go back the 10 feet ///m_pDrive->TurnInDegreesGyro(90, 0); m_pDrive->TimedArcade(0.6, 0.2, 1.3); m_pDrive->ForwardInInch(95, 0, 0.8); //Go back around the initial cone ///m_pDrive->ForwardInInch(45, 0, 0.3); ///m_pDrive->TurnInDegreesGyro(-90, 0.4); ///m_pDrive->ForwardInInch(45, 0, 0.3); ///m_pDrive->TurnInDegreesGyro(90, 0.4); m_pDrive->TimedArcade(0.6, 0.2, 1.3); m_pDrive->TimedArcade(0.6, -0.24, 1.0); m_pDrive->ForwardInInch(10,0,0.5); //Move forward a little bit //No state check because this function is shared by other cases //m_pDrive->ForwardInSeconds(0.25, 0.5); //m_state = 1; m_IsFinished = true; } void AutoSlalom::loop1() { //Rotate until Color1 on right side m_center = 0.50; if (m_state != 1) //Return if state is not 1 { return; } double direction; if (m_result < -2.0 || m_result < 0.0) //If I can't see the cone or it is on the left side of the center { Util::Log("Auto2021 S1 State", "Turning Left"); direction = -0.2; } else if (m_result > 0.0) //If the cone is on the right side of the center { Util::Log("Auto2021 S1 State", "Turning Right"); direction = 0.2; } else //If cone is in the center { direction = 0.0; m_state = 2; //Increment state } //m_pDrive->MoveTank(direction, -direction); m_pDrive->MoveArcade(0, direction); //Move } void AutoSlalom::loop2() { //Move forward until I can't see color1 m_center = 0.0; //Center is in the center double speed = 0.0; if (m_state != 2) //Return if state is not 2 { return; } if (m_result > -3) //If I see the cone { if (m_result > 0) //If cone is on the right { speed = -0.2; } else if (m_result < 0) //If cone is on the left { speed = 0.2; } } else //If I don't see the cone { m_state = 3; //Increment state } m_pDrive->MoveArcade(0.2, speed); //Move } void AutoSlalom::loop3() { //Move forward a little bit //No state check because this function is shared by other cases m_pDrive->ForwardInInch(49, 0, 0.2); m_state = 4; } void AutoSlalom::loop4() { //Rotate Right until color1 is on the right side m_center = 0.50; if (m_state != 4) { return; } double direction; if (m_result < -2.0 || m_result < 0.0) { direction = -0.2; } else { direction = 0.0; m_state = 5; } m_pDrive->MoveArcade(0, direction); } void AutoSlalom::loop5() { //Rotate until Color2 on left side m_center = -0.75; //left side if (m_state != 5) { return; } double direction; if(m_result < -2.0 || m_result < 0.0) { direction = -0.2; } else if (m_result > 0.0) { direction = 0.2; } else { direction = 0.0; m_state = 6; } m_pDrive->MoveArcade(0, direction); } void AutoSlalom::loop6() { //Move forward until I can't see color2 m_center = 0.0; //Center is in the center double speed = 0.0; if (m_state != 6) //Return if state is not 2 { return; } if (m_result > -3) //If I see the cone { if (m_result > 0) //If cone is on the right { speed = -0.2; } else if (m_result < 0) //If cone is on the left { speed = 0.2; } } else //If I don't see the cone { m_state = 3; //Increment state } m_pDrive->MoveArcade(0.2, speed); //Move }
19.257732
106
0.601713
1828Boxerbots