blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
sequencelengths
1
1
author_id
stringlengths
0
158
22326c7a3fa7530436b917940068931117a26c8f
e485761b6b5caac519feacf600742d19e349f89e
/include/core/model.h
5500024ad99faa8b1ecc3fc4e41ca5a0d4b7e71b
[]
no_license
szotaksoma/cpp-neural-net
2d40db3b98749721e471f66617c9074caf61aa85
030b4a5aad4560ca3ab9f24d3733a89bb06e05cd
refs/heads/master
2020-12-09T12:22:28.504598
2020-02-06T15:56:46
2020-02-06T15:56:46
233,302,622
2
0
null
null
null
null
UTF-8
C++
false
false
1,287
h
#ifndef _MODEL #define _MODEL #include "core/layers.h" #include "util/namable.h" #include <string> #include <vector> namespace NeuralNet { class Model : public Namable { public: Model(std::string name = "Unnamed model"); ~Model(); bool is_compiled(); bool is_disposed(); // Print model description to console void describe(); // Add a new layer to the model void add_layer(Layer*); // Get number of layers for model unsigned int layer_count(); // Get model layer by index Layer* get_layer(unsigned int index); // Get model layer by name Layer* get_layer(std::string name); // Get input (first) layer of the model Layer* get_input(); // Get output (last) layer of the model Layer* get_output(); // Compile current model structure void compile(); // Feed data forward through the model void feed_forward(std::vector<double> iv); // Evaluate model output over a single input point std::vector<double> evaluate(std::vector<double>); // Free resources used by model void dispose(); std::vector<Layer*> layers; unsigned long n_params; unsigned long n_trainable_params; unsigned long allocated_memory; private: bool _compiled = false; bool _disposed = false; }; } #endif // !_MODEL
86fa4b98a86f4eba85552b9473a03fe8d679e2aa
9dbdd167c279665172c68735d36325769e552e4b
/Source/External/EASTL/test/source/TestString.inl
509c7aaf98ee71026fb6b93827db686b8bffcd87
[ "MIT", "BSD-3-Clause", "BSD-2-Clause" ]
permissive
michal-z/eneida-software
d814838e4570f5144c2198a2df5e67392b1633ef
740f27cf1f7b7b29e3294f6a3be8eee6b937f979
refs/heads/master
2021-04-06T19:43:54.328465
2018-06-15T22:16:07
2018-06-15T22:16:07
125,278,279
2
0
null
null
null
null
UTF-8
C++
false
false
54,440
inl
///////////////////////////////////////////////////////////////////////////// // Copyright (c) Electronic Arts Inc. All rights reserved. ///////////////////////////////////////////////////////////////////////////// // todo: // Test Encoding // Test StringHash // Test exceptions #if EASTL_OPENSOURCE #define EASTL_SNPRINTF_TESTS_ENABLED 0 #else #define EASTL_SNPRINTF_TESTS_ENABLED 1 #endif template<typename StringType> int TEST_STRING_NAME() { int nErrorCount = 0; struct Failocator { Failocator() = default; Failocator(const char*) {} void* allocate(size_t n) { EA_FAIL(); return nullptr; } void deallocate(void* p, size_t) { EA_FAIL(); } }; #if defined(EA_PLATFORM_ANDROID) || defined(EA_PLATFORM_APPLE) EA_DISABLE_CLANG_WARNING(-Winherited-variadic-ctor) // warning: inheriting constructor does not inherit ellipsis #endif struct SSOStringType : public StringType { using StringType::StringType; using StringType::IsSSO; }; // Use custom string type that always fails to allocate memory to highlight when SSO is not functioning correctly. struct SSOFailocatorString : public eastl::basic_string<typename StringType::value_type, Failocator> { using eastl::basic_string<typename StringType::value_type, Failocator>::basic_string; using eastl::basic_string<typename StringType::value_type, Failocator>::IsSSO; }; #if defined(EA_PLATFORM_ANDROID) || defined(EA_PLATFORM_APPLE) EA_RESTORE_CLANG_WARNING() #endif // SSO (short string optimization) tests { { SSOFailocatorString str; VERIFY(str.validate()); VERIFY(str.empty()); VERIFY(str.IsSSO()); } if(EA_PLATFORM_WORD_SIZE == 8) { // test SSO size on 64 bit platforms if(sizeof(typename StringType::value_type) == 1) { // we can fit 23 characters on 64bit system with 1 byte chars const auto* pLiteral = LITERAL("aaaaaaaaaaaaaaaaaaaaaaa"); SSOFailocatorString str(pLiteral); VERIFY(EA::StdC::Strlen(pLiteral) == 23); VERIFY(str == pLiteral); VERIFY(str.validate()); VERIFY(str.IsSSO()); } if(sizeof(typename StringType::value_type) == 2) { // we can fit 11 characters on 64 bit system with 2 byte chars const auto* pLiteral = LITERAL("aaaaaaaaaaa"); SSOFailocatorString str(pLiteral); VERIFY(EA::StdC::Strlen(pLiteral) == 11); VERIFY(str == pLiteral); VERIFY(str.validate()); VERIFY(str.IsSSO()); } if(sizeof(typename StringType::value_type) == 4) { // we can fit 5 characters on 64 bit system with 4 byte chars const auto* pLiteral = LITERAL("aaaaa"); SSOFailocatorString str(pLiteral); VERIFY(EA::StdC::Strlen(pLiteral) == 5); VERIFY(str == pLiteral); VERIFY(str.validate()); VERIFY(str.IsSSO()); } } if(EA_PLATFORM_WORD_SIZE == 4) { // test SSO size on 32 bit platforms if(sizeof(typename StringType::value_type) == 1) { // we can fit 11 characters on 32bit system with 1 byte chars const auto* pLiteral = LITERAL("aaaaaaaaaaa"); SSOFailocatorString str(pLiteral); VERIFY(EA::StdC::Strlen(pLiteral) == 11); VERIFY(str == pLiteral); VERIFY(str.validate()); VERIFY(str.IsSSO()); } if(sizeof(typename StringType::value_type) == 2) { // we can fit 5 characters on 32 bit system with 2 byte chars const auto* pLiteral = LITERAL("aaaaa"); SSOFailocatorString str(pLiteral); VERIFY(EA::StdC::Strlen(pLiteral) == 5); VERIFY(str == pLiteral); VERIFY(str.validate()); VERIFY(str.IsSSO()); } if(sizeof(typename StringType::value_type) == 4) { // we can fit 2 characters on 32 bit system with 4 byte chars const auto* pLiteral = LITERAL("aa"); SSOFailocatorString str(pLiteral); VERIFY(EA::StdC::Strlen(pLiteral) == 2); VERIFY(str == pLiteral); VERIFY(str.validate()); VERIFY(str.IsSSO()); } } } // basic_string(); { StringType str; VERIFY(str.empty()); VERIFY(str.length() == 0); VERIFY(str.validate()); } // explicit basic_string(const allocator_type& allocator); { typename StringType::allocator_type alloc; StringType str(alloc); VERIFY(str.validate()); } // basic_string(const value_type* p, size_type n, const allocator_type& allocator = EASTL_BASIC_STRING_DEFAULT_ALLOCATOR); { { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz"), 26); VERIFY(str[5] == LITERAL('f')); VERIFY(!str.empty()); VERIFY(str.length() == 26); VERIFY(str.validate()); } { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); VERIFY(str[5] == LITERAL('f')); VERIFY(!str.empty()); VERIFY(str.length() == 26); VERIFY(str.validate()); } } // basic_string(const this_type& x, size_type position, size_type n = npos); { StringType str1(LITERAL("abcdefghijklmnopqrstuvwxyz")); StringType str2(str1, 3, 3); VERIFY(str2 == LITERAL("def")); VERIFY(str2.size() == 3); VERIFY(str2.length() == 3); VERIFY(str2.capacity() >= 3); // SSO buffer size StringType str3(str1, 25, 3); VERIFY(str3 == LITERAL("z")); VERIFY(str3.size() == 1); VERIFY(str3.length() == 1); VERIFY(str3.capacity() >= 1); // SSO buffer size VERIFY(str1.validate()); VERIFY(str2.validate()); VERIFY(str3.validate()); } // EASTL_STRING_EXPLICIT basic_string(const value_type* p, const allocator_type& allocator = EASTL_BASIC_STRING_DEFAULT_ALLOCATOR); { auto* pLiteral = LITERAL("abcdefghijklmnopqrstuvwxyz"); StringType str(pLiteral); VERIFY(str == pLiteral); } // basic_string(size_type n, value_type c, const allocator_type& allocator = EASTL_BASIC_STRING_DEFAULT_ALLOCATOR); { StringType str(32, LITERAL('a')); VERIFY(!str.empty()); VERIFY(str.size() == 32); VERIFY(str.length() == 32); VERIFY(str == LITERAL("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")); VERIFY(str.validate()); } // basic_string(const this_type& x); { StringType str1(LITERAL("abcdefghijklmnopqrstuvwxyz")); StringType str2(str1); VERIFY(str1 == str2); VERIFY(str1.size() == str2.size()); VERIFY(str1.empty() == str2.empty()); VERIFY(str1.length() == str2.length()); VERIFY(EA::StdC::Memcmp(str1.data(), str2.data(), str1.size()) == 0); VERIFY(str1.validate()); VERIFY(str2.validate()); } // basic_string(const value_type* pBegin, const value_type* pEnd, const allocator_type& allocator = EASTL_BASIC_STRING_DEFAULT_ALLOCATOR); { StringType str1(LITERAL("abcdefghijklmnopqrstuvwxyz")); auto* pStart = str1.data() + 5; auto* pEnd = str1.data() + 20; StringType str(pStart, pEnd); VERIFY(str == LITERAL("fghijklmnopqrst")); VERIFY(!str.empty()); VERIFY(str.size() == 15); } // basic_string(CtorDoNotInitialize, size_type n, const allocator_type& allocator = EASTL_BASIC_STRING_DEFAULT_ALLOCATOR); { StringType str(typename StringType::CtorDoNotInitialize(), 42); VERIFY(str.size() == 0); VERIFY(str.length() == 0); VERIFY(str.capacity() == 42); } // basic_string(CtorSprintf, const value_type* pFormat, ...); { #if EASTL_SNPRINTF_TESTS_ENABLED { StringType str(typename StringType::CtorSprintf(), LITERAL("Hello, %d"), 42); VERIFY(str == LITERAL("Hello, 42")); VERIFY(str.validate()); } { StringType str(typename StringType::CtorSprintf(), LITERAL("Hello, %d %d %d %d %d %d %d %d %d"), 42, 42, 42, 42, 42, 42, 42, 42, 42); VERIFY(str == LITERAL("Hello, 42 42 42 42 42 42 42 42 42")); VERIFY(str.validate()); } #endif } // basic_string(std::initializer_list<value_type> init, const allocator_type& allocator = EASTL_BASIC_STRING_DEFAULT_ALLOCATOR); { #if !defined(EA_COMPILER_NO_INITIALIZER_LISTS) StringType str({'a','b','c','d','e','f'}); VERIFY(str == LITERAL("abcdef")); VERIFY(!str.empty()); VERIFY(str.length() == 6); VERIFY(str.size() == 6); VERIFY(str.validate()); #endif } // basic_string(this_type&& x); // basic_string(this_type&& x, const allocator_type& allocator); { #if EASTL_MOVE_SEMANTICS_ENABLED { // test heap string StringType str1(LITERAL("abcdefghijklmnopqrstuvwxyz")); StringType str2(eastl::move(str1)); VERIFY(str1 != LITERAL("abcdefghijklmnopqrstuvwxyz")); VERIFY(str2 == LITERAL("abcdefghijklmnopqrstuvwxyz")); VERIFY(str1.empty()); VERIFY(!str2.empty()); VERIFY(str1.length() == 0); VERIFY(str2.length() == 26); VERIFY(str1.size() == 0); VERIFY(str2.size() == 26); VERIFY(str1.validate()); VERIFY(str2.validate()); } { // test sso string StringType str1(LITERAL("a")); StringType str2(eastl::move(str1)); VERIFY(str1 != LITERAL("a")); VERIFY(str2 == LITERAL("a")); VERIFY(str1.empty()); VERIFY(!str2.empty()); VERIFY(str1.length() == 0); VERIFY(str2.length() == 1); VERIFY(str1.size() == 0); VERIFY(str2.size() == 1); VERIFY(str1.validate()); VERIFY(str2.validate()); } #endif } // template <typename OtherCharType> // basic_string(CtorConvert, const OtherCharType* p, const allocator_type& allocator = EASTL_BASIC_STRING_DEFAULT_ALLOCATOR); { { #if defined(EA_CHAR8) StringType str(typename StringType::CtorConvert(), EA_CHAR8("123456789")); VERIFY(str == LITERAL("123456789")); VERIFY(str.validate()); #endif } { #if defined(EA_CHAR16) StringType str(typename StringType::CtorConvert(), EA_CHAR16("123456789")); VERIFY(str == LITERAL("123456789")); VERIFY(str.validate()); #endif } { #if defined(EA_CHAR32) StringType str(typename StringType::CtorConvert(), EA_CHAR32("123456789")); VERIFY(str == LITERAL("123456789")); VERIFY(str.validate()); #endif } { // #if defined(EA_WCHAR) // StringType str(typename StringType::CtorConvert(), EA_WCHAR("123456789")); // VERIFY(str == LITERAL("123456789")); // VERIFY(str.validate()); // #endif } } // template <typename OtherCharType> // basic_string(CtorConvert, const OtherCharType* p, size_type n, const allocator_type& allocator = EASTL_BASIC_STRING_DEFAULT_ALLOCATOR); { { #if defined(EA_CHAR8) StringType str(typename StringType::CtorConvert(), EA_CHAR8("123456789"), 4); VERIFY(str == LITERAL("1234")); VERIFY(str.validate()); #endif } { #if defined(EA_CHAR16) StringType str(typename StringType::CtorConvert(), EA_CHAR16("123456789"), 4); VERIFY(str == LITERAL("1234")); VERIFY(str.validate()); #endif } { #if defined(EA_CHAR32) StringType str(typename StringType::CtorConvert(), EA_CHAR32("123456789"), 4); VERIFY(str == LITERAL("1234")); VERIFY(str.validate()); #endif } { // #if defined(EA_WCHAR) // StringType str(typename StringType::CtorConvert(), EA_WCHAR("123456789"), 4); // VERIFY(str == LITERAL("1234")); // VERIFY(str.validate()); // #endif } } // template <typename OtherStringType> // basic_string(CtorConvert, const OtherStringType& x); { { #if defined(EA_CHAR8) StringType str(typename StringType::CtorConvert(), eastl::basic_string<char8_t, typename StringType::allocator_type>(EA_CHAR8("123456789"))); VERIFY(str == LITERAL("123456789")); VERIFY(str.validate()); #endif } { #if defined(EA_CHAR16) StringType str(typename StringType::CtorConvert(), eastl::basic_string<char16_t, typename StringType::allocator_type>(EA_CHAR16("123456789"))); VERIFY(str == LITERAL("123456789")); VERIFY(str.validate()); #endif } { #if defined(EA_CHAR32) StringType str(typename StringType::CtorConvert(), eastl::basic_string<char32_t, typename StringType::allocator_type>(EA_CHAR32("123456789"))); VERIFY(str == LITERAL("123456789")); VERIFY(str.validate()); #endif } { // #if defined(EA_WCHAR) // StringType str(typename StringType::CtorConvert(), eastl::basic_string<wchar_t, StringType::allocator_type>(EA_WCHAR("123456789"))); // VERIFY(str == LITERAL("123456789")); // VERIFY(str.validate()); // #endif } } // const allocator_type& get_allocator() const EA_NOEXCEPT; // allocator_type& get_allocator() EA_NOEXCEPT; // void set_allocator(const allocator_type& allocator); { } // this_type& operator=(const this_type& x); { StringType str1(LITERAL("abcdefghijklmnopqrstuvwxyz")); StringType str1_copy(LITERAL("")); VERIFY(str1_copy.empty()); str1_copy = str1; VERIFY(str1 == str1_copy); VERIFY(!str1_copy.empty()); VERIFY(str1.validate()); VERIFY(str1_copy.validate()); } // this_type& operator=(const value_type* p); { StringType str; str = LITERAL("abcdefghijklmnopqrstuvwxyz"); VERIFY(str[5] == LITERAL('f')); VERIFY(str == LITERAL("abcdefghijklmnopqrstuvwxyz")); VERIFY(!str.empty()); VERIFY(str.length() == 26); VERIFY(str.validate()); } // this_type& operator=(value_type c); { StringType str; str = LITERAL('a'); VERIFY(str == LITERAL("a")); VERIFY(!str.empty()); VERIFY(str.length() == 1); VERIFY(str.size() == 1); VERIFY(str.validate()); } // this_type& operator=(std::initializer_list<value_type> ilist); { #if !defined(EA_COMPILER_NO_INITIALIZER_LISTS) StringType str = {'a','b','c','d','e','f'}; VERIFY(str == LITERAL("abcdef")); VERIFY(!str.empty()); VERIFY(str.length() == 6); VERIFY(str.size() == 6); VERIFY(str.validate()); #endif } // this_type& operator=(this_type&& x); { #if EASTL_MOVE_SEMANTICS_ENABLED { StringType str1(LITERAL("abcdefghijklmnopqrstuvwxyz")); StringType str2 = eastl::move(str1); VERIFY(str1 != LITERAL("abcdefghijklmnopqrstuvwxyz")); VERIFY(str2 == LITERAL("abcdefghijklmnopqrstuvwxyz")); VERIFY(str1.empty()); VERIFY(!str2.empty()); VERIFY(str1.length() == 0); VERIFY(str2.length() == 26); VERIFY(str1.size() == 0); VERIFY(str2.size() == 26); VERIFY(str1.validate()); VERIFY(str2.validate()); } { StringType str1(LITERAL("a")); StringType str2 = eastl::move(str1); VERIFY(str1 != LITERAL("a")); VERIFY(str2 == LITERAL("a")); VERIFY(str1.empty()); VERIFY(!str2.empty()); VERIFY(str1.length() == 0); VERIFY(str2.length() == 1); VERIFY(str1.size() == 0); VERIFY(str2.size() == 1); VERIFY(str1.validate()); VERIFY(str2.validate()); } #endif } // this_type& operator=(value_type* p); // // template <typename OtherCharType> // this_type& operator=(const OtherCharType* p); // // template <typename OtherStringType> // this_type& operator=(const OtherStringType& x); { #if EASTL_OPERATOR_EQUALS_OTHER_ENABLED { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str = LITERAL("123456789"); VERIFY(str == LITERAL("123456789"); VERIFY(str.validate()); } { { #if defined(EA_CHAR8) StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str = EA_CHAR8("123456789"); VERIFY(str == LITERAL("123456789")); VERIFY(str.validate()); #endif } { #if defined(EA_CHAR16) StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str = EA_CHAR16("123456789"); VERIFY(str == LITERAL("123456789")); VERIFY(str.validate()); #endif } { #if defined(EA_CHAR32) StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str = EA_CHAR32("123456789"); VERIFY(str == LITERAL("123456789")); VERIFY(str.validate()); #endif } { #if defined(EA_WCHAR) StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str = EA_WCHAR("123456789"); VERIFY(str == LITERAL("123456789")); VERIFY(str.validate()); #endif } } { { #if defined(EA_CHAR8) StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str = eastl::basic_string<char8_t>(EA_CHAR8("123456789")); VERIFY(str == LITERAL("123456789")); VERIFY(str.validate()); #endif } { #if defined(EA_CHAR16) StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str = eastl::basic_string<char16_t>(EA_CHAR16("123456789")); VERIFY(str == LITERAL("123456789")); VERIFY(str.validate()); #endif } { #if defined(EA_CHAR32) StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str = eastl::basic_string<char32_t>(EA_CHAR32("123456789")); VERIFY(str == LITERAL("123456789")); VERIFY(str.validate()); #endif } { #if defined(EA_WCHAR) StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str = eastl::basic_string<wchar_t>(EA_WCHAR("123456789")); VERIFY(str == LITERAL("123456789")); VERIFY(str.validate()); #endif } } #endif } // void swap(this_type& x); { StringType str1(LITERAL("abcdefghijklmnopqrstuvwxyz")); StringType str2; str1.swap(str2); VERIFY(str1 != LITERAL("abcdefghijklmnopqrstuvwxyz")); VERIFY(str2 == LITERAL("abcdefghijklmnopqrstuvwxyz")); VERIFY(str1.empty()); VERIFY(!str2.empty()); VERIFY(str1.length() == 0); VERIFY(str2.length() == 26); VERIFY(str1.size() == 0); VERIFY(str2.size() == 26); VERIFY(str1.validate()); VERIFY(str2.validate()); } // this_type& assign(const this_type& x); { StringType str1(LITERAL("abcdefghijklmnopqrstuvwxyz")); StringType str2; str2.assign(str1); VERIFY(str1 == LITERAL("abcdefghijklmnopqrstuvwxyz")); VERIFY(str2 == LITERAL("abcdefghijklmnopqrstuvwxyz")); VERIFY(!str1.empty()); VERIFY(!str2.empty()); VERIFY(str1.length() == 26); VERIFY(str2.length() == 26); VERIFY(str1.size() == 26); VERIFY(str2.size() == 26); VERIFY(str1.validate()); VERIFY(str2.validate()); } // this_type& assign(const this_type& x, size_type position, size_type n); { StringType str1(LITERAL("abcdefghijklmnopqrstuvwxyz")); StringType str2(LITERAL("123456789")); str1.assign(str2, 3, 3); VERIFY(str1 == LITERAL("456")); VERIFY(str1.validate()); VERIFY(str2.validate()); } // this_type& assign(const value_type* p, size_type n); { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str.assign(LITERAL("123456789"), 5); VERIFY(str == LITERAL("12345")); VERIFY(str.validate()); } // this_type& assign(const value_type* p); { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str.assign(LITERAL("123")); VERIFY(str == LITERAL("123")); VERIFY(str.validate()); } // this_type& assign(size_type n, value_type c); { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str.assign(32, LITERAL('c')); VERIFY(str == LITERAL("cccccccccccccccccccccccccccccccc")); VERIFY(str.validate()); } // this_type& assign(const value_type* pBegin, const value_type* pEnd); { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); auto* pLiteral = LITERAL("0123456789"); auto* pBegin = pLiteral + 4; auto* pEnd = pLiteral + 7; str.assign(pBegin, pEnd); VERIFY(str == LITERAL("456")); VERIFY(str.validate()); } // this_type& assign(this_type&& x); { #if EASTL_MOVE_SEMANTICS_ENABLED StringType str1(LITERAL("abcdefghijklmnopqrstuvwxyz")); StringType str2; str1.assign(eastl::move(str2)); VERIFY(str1 != LITERAL("abcdefghijklmnopqrstuvwxyz")); VERIFY(str2 == LITERAL("abcdefghijklmnopqrstuvwxyz")); VERIFY(str1.empty()); VERIFY(!str2.empty()); VERIFY(str1.length() == 0); VERIFY(str2.length() == 26); VERIFY(str1.size() == 0); VERIFY(str2.size() == 26); VERIFY(str1.validate()); VERIFY(str2.validate()); #endif } // this_type& assign(std::initializer_list<value_type>); { #if !defined(EA_COMPILER_NO_INITIALIZER_LISTS) StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str.assign({'1','2','3'}); VERIFY(str == LITERAL("123")); VERIFY(str.validate()); #endif } // template <typename OtherCharType> // this_type& assign_convert(const OtherCharType* p); { { #if defined(EA_CHAR8) StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str.assign_convert(EA_CHAR8("123456789")); VERIFY(str == LITERAL("123456789")); VERIFY(str.validate()); #endif } { #if defined(EA_CHAR16) StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str.assign_convert(EA_CHAR16("123456789")); VERIFY(str == LITERAL("123456789")); VERIFY(str.validate()); #endif } { #if defined(EA_CHAR32) StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str.assign_convert(EA_CHAR32("123456789")); VERIFY(str == LITERAL("123456789")); VERIFY(str.validate()); #endif } { // #if defined(EA_WCHAR) // StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); // str.assign_convert(EA_WCHAR("123456789")); // VERIFY(str == LITERAL("123456789")); // VERIFY(str.validate()); // #endif } } // template <typename OtherCharType> // this_type& assign_convert(const OtherCharType* p, size_type n); { { #if defined(EA_CHAR8) StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str.assign_convert(EA_CHAR8("123456789"), 3); VERIFY(str == LITERAL("123")); VERIFY(str.validate()); #endif } { #if defined(EA_CHAR16) StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str.assign_convert(EA_CHAR16("123456789"), 3); VERIFY(str == LITERAL("123")); VERIFY(str.validate()); #endif } { #if defined(EA_CHAR32) StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str.assign_convert(EA_CHAR32("123456789"), 3); VERIFY(str == LITERAL("123")); VERIFY(str.validate()); #endif } { // #if defined(EA_WCHAR) // StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); // str.assign_convert(EA_WCHAR("123456789"), 3); // VERIFY(str == LITERAL("123")); // VERIFY(str.validate()); // #endif } } // template <typename OtherStringType> // this_type& assign_convert(const OtherStringType& x); { { #if defined(EA_CHAR8) StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); eastl::basic_string<char8_t> str2(EA_CHAR8("123456789")); str.assign_convert(str2); VERIFY(str == LITERAL("123456789")); VERIFY(str.validate()); #endif } { #if defined(EA_CHAR16) StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); eastl::basic_string<char16_t> str2(EA_CHAR16("123456789")); str.assign_convert(str2); VERIFY(str == LITERAL("123456789")); VERIFY(str.validate()); #endif } { #if defined(EA_CHAR32) StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); eastl::basic_string<char32_t> str2(EA_CHAR32("123456789")); str.assign_convert(str2); VERIFY(str == LITERAL("123456789")); VERIFY(str.validate()); #endif } { // #if defined(EA_WCHAR) // StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); // eastl::basic_string<wchar_t> str2(EA_WCHAR("123456789")); // str.assign_convert(str2); // VERIFY(str == LITERAL("123456789")); // VERIFY(str.validate()); // #endif } } // iterator begin() EA_NOEXCEPT; // const_iterator begin() const EA_NOEXCEPT; // const_iterator cbegin() const EA_NOEXCEPT; { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); auto iBegin = str.begin(); VERIFY(*iBegin++ == LITERAL('a')); VERIFY(*iBegin++ == LITERAL('b')); VERIFY(*iBegin++ == LITERAL('c')); VERIFY(*iBegin++ == LITERAL('d')); VERIFY(*iBegin++ == LITERAL('e')); VERIFY(*iBegin++ == LITERAL('f')); VERIFY(*(str.begin() + 25) == LITERAL('z')); } // iterator end() EA_NOEXCEPT; // const_iterator end() const EA_NOEXCEPT; // const_iterator cend() const EA_NOEXCEPT; { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); auto iEnd = str.end()-1; VERIFY(*iEnd-- == LITERAL('z')); VERIFY(*iEnd-- == LITERAL('y')); VERIFY(*iEnd-- == LITERAL('x')); VERIFY(*iEnd-- == LITERAL('w')); VERIFY(*iEnd-- == LITERAL('v')); VERIFY(*iEnd-- == LITERAL('u')); VERIFY(*(str.end() - 26) == LITERAL('a')); } // reverse_iterator rbegin() EA_NOEXCEPT; // const_reverse_iterator rbegin() const EA_NOEXCEPT; // const_reverse_iterator crbegin() const EA_NOEXCEPT; { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); auto iRBegin = str.rbegin(); VERIFY(*iRBegin++ == LITERAL('z')); VERIFY(*iRBegin++ == LITERAL('y')); VERIFY(*iRBegin++ == LITERAL('x')); VERIFY(*iRBegin++ == LITERAL('w')); VERIFY(*iRBegin++ == LITERAL('v')); VERIFY(*iRBegin++ == LITERAL('u')); VERIFY(*(str.rbegin() + 25) == LITERAL('a')); } // reverse_iterator rend() EA_NOEXCEPT; // const_reverse_iterator rend() const EA_NOEXCEPT; // const_reverse_iterator crend() const EA_NOEXCEPT; { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); auto iREnd = str.rend() - 1; VERIFY(*iREnd-- == LITERAL('a')); VERIFY(*iREnd-- == LITERAL('b')); VERIFY(*iREnd-- == LITERAL('c')); VERIFY(*iREnd-- == LITERAL('d')); VERIFY(*iREnd-- == LITERAL('e')); VERIFY(*iREnd-- == LITERAL('f')); VERIFY(*(str.rend() - 26) == LITERAL('z')); } // bool empty() const EA_NOEXCEPT; // size_type size() const EA_NOEXCEPT; // size_type length() const EA_NOEXCEPT; // size_type capacity() const EA_NOEXCEPT; // void resize(size_type n, value_type c); // void resize(size_type n); // void set_capacity(size_type n = npos); { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); VERIFY(!str.empty()); VERIFY(str.size() == 26); VERIFY(str.length() == 26); VERIFY(str.capacity() >= 26); str.assign(LITERAL("")); VERIFY(str.empty()); VERIFY(str.size() == 0); VERIFY(str.length() == 0); VERIFY(str.capacity() >= 26); // should not free existing capacity str.resize(0); VERIFY(str.empty()); VERIFY(str.size() == 0); VERIFY(str.length() == 0); VERIFY(str.capacity() >= 26); // should not free existing capacity str.set_capacity(0); // VERIFY(str.capacity() == 0); // frees existing capacity, but has a minimun of SSO capacity str.resize(32, LITERAL('c')); VERIFY(!str.empty()); VERIFY(str.size() == 32); VERIFY(str.length() == 32); VERIFY(str.capacity() >= 32); VERIFY(str == LITERAL("cccccccccccccccccccccccccccccccc")); } // void shrink_to_fit { SSOStringType str(LITERAL("a")); str.reserve(100); VERIFY(str.capacity() == 100); str.shrink_to_fit(); // string should shrink to SSO VERIFY(str.IsSSO()); str = LITERAL("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); // 32 characters str.reserve(100); VERIFY(str.capacity() == 100); str.shrink_to_fit(); // string should shrink but still be heap VERIFY(str.capacity() == 32); VERIFY(!str.IsSSO()); } // void set_capacity(n) { const auto *pLiteral32 = LITERAL("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); const auto *pLiteral31 = LITERAL("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); const auto *pLiteral1 = LITERAL("a"); const auto *pLiteral2 = LITERAL("aa"); SSOStringType str = pLiteral32; // set_capacity(0) - deallocate and reset to SSO; { // heap -> sso VERIFY(!str.IsSSO()); str.set_capacity(0); VERIFY(str.IsSSO()); VERIFY(str == LITERAL("")); } { // sso -> sso str = pLiteral1; VERIFY(str.IsSSO()); str.set_capacity(0); VERIFY(str.IsSSO()); VERIFY(str == LITERAL("")); } // set_capacity(npos) - set capacity equal to current size - should realloc { // heap -> heap str = pLiteral32; str.reserve(100); VERIFY(!str.IsSSO()); VERIFY(str.capacity() == 100); str.set_capacity(StringType::npos); VERIFY(!str.IsSSO()); VERIFY(str.capacity() == 32); VERIFY(str == pLiteral32); } { // heap -> sso str = pLiteral1; str.reserve(100); VERIFY(!str.IsSSO()); VERIFY(str.capacity() == 100); str.set_capacity(StringType::npos); VERIFY(str.IsSSO()); VERIFY(str == pLiteral1); } { // sso -> sso str = pLiteral1; VERIFY(str.IsSSO()); str.set_capacity(StringType::npos); VERIFY(str.IsSSO()); VERIFY(str == pLiteral1); } // set_capacity(n > capacity) - set capacity greater than out current capacity { // heap -> heap str = pLiteral32; VERIFY(!str.IsSSO()); auto nSavedCap = str.capacity(); str.set_capacity(nSavedCap + 1); VERIFY(!str.IsSSO()); VERIFY(str == pLiteral32); VERIFY(str.capacity() > nSavedCap); } { // sso -> heap str.set_capacity(0); // reset to sso str = pLiteral1; VERIFY(str.IsSSO()); auto nSavedCap = str.capacity(); str.set_capacity(nSavedCap + 1); VERIFY(!str.IsSSO()); VERIFY(str == pLiteral1); VERIFY(str.capacity() > nSavedCap); } { // sso -> sso str.set_capacity(0); // reset to sso str = pLiteral1; VERIFY(str.IsSSO()); auto nSavedCap = str.capacity(); str.set_capacity(str.size() + 1); VERIFY(str.IsSSO()); VERIFY(str == pLiteral1); VERIFY(str.capacity() == nSavedCap); } // set_capacity(n < size) - set capacity less than current size, str should truncate { // sso -> sso str = pLiteral2; VERIFY(str.IsSSO()); str.set_capacity(1); VERIFY(str.IsSSO()); VERIFY(str == pLiteral1); } { // heap -> sso str = pLiteral32; VERIFY(!str.IsSSO()); str.set_capacity(1); VERIFY(str.IsSSO()); VERIFY(str == pLiteral1); } { // heap -> heap str = pLiteral32; VERIFY(!str.IsSSO()); str.set_capacity(31); VERIFY(!str.IsSSO()); VERIFY(str == pLiteral31); } } // void reserve(size_type = 0); { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); VERIFY(!str.empty()); VERIFY(str.size() == 26); VERIFY(str.length() == 26); VERIFY(str.capacity() >= 26); // verifies that we allocate memory str.reserve(64); VERIFY(!str.empty()); VERIFY(str.size() == 26); VERIFY(str.length() == 26); VERIFY(str.capacity() >= 64); // verifies that we do not free memory str.reserve(32); VERIFY(!str.empty()); VERIFY(str.size() == 26); VERIFY(str.length() == 26); VERIFY(str.capacity() >= 64); } // void force_size(size_type n); { // force_size does not write terminating null, meant to set size when using external // string writing mnethods like strcpy or sprintf StringType str(LITERAL("aaa")); VERIFY(str.size() == 3); str.force_size(0); VERIFY(str.size() == 0); str.reserve(4); // 32 bit platform with char32_t can only hold 2 characters str.force_size(4); VERIFY(str.size() == 4); str[4] = '0'; str = LITERAL("aaa"); VERIFY(str.size() == 3); } // const value_type* data() const EA_NOEXCEPT; // const value_type* c_str() const EA_NOEXCEPT; { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); auto* pData = str.data(); auto* pCStr = str.c_str(); VERIFY(pData != nullptr); VERIFY(pCStr != nullptr); VERIFY(pData == pCStr); VERIFY(EA::StdC::Memcmp(pData, pCStr, str.size()) == 0); } // reference operator[](size_type n); // const_reference operator[](size_type n) const; { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); VERIFY(str[0] == LITERAL('a')); VERIFY(str[14] == LITERAL('o')); VERIFY(str[25] == LITERAL('z')); } // reference at(size_type n); // const_reference at(size_type n) const; { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); VERIFY(str.at(0) == LITERAL('a')); VERIFY(str.at(14) == LITERAL('o')); VERIFY(str.at(25) == LITERAL('z')); } // reference front(); // const_reference front() const; { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); VERIFY(str.front() == LITERAL('a')); } // reference back(); // const_reference back() const; { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); VERIFY(str.back() == LITERAL('z')); } // this_type& operator+=(const this_type& x); // this_type& operator+=(const value_type* p); // this_type& operator+=(value_type c); { StringType str1(LITERAL("abcdefghijklmnopqrstuvwxyz")); StringType str2(LITERAL("123")); str1 += str2; str1 += LITERAL("456"); str1 += LITERAL('7'); VERIFY(str1 == LITERAL("abcdefghijklmnopqrstuvwxyz1234567")); } // this_type& append(const this_type& x); // this_type& append(const this_type& x, size_type position, size_type n); // this_type& append(const value_type* p, size_type n); // this_type& append(const value_type* p); // this_type& append(size_type n, value_type c); // this_type& append(const value_type* pBegin, const value_type* pEnd); { const StringType src(LITERAL("abcdefghijklmnopqrstuvwxyz")); StringType str; str.append(StringType(LITERAL("abcd"))); // "abcd" str.append(src, 4, 4); // "abcdefgh" str.append(src.data() + 8, 4); // "abcdefghijkl" str.append(LITERAL("mnop")); // "abcdefghijklmnop" str.append(1, LITERAL('q')); // "abcdefghijklmnopq" str.append(src.data() + 17, src.data() + 26); // "abcdefghijklmnopqrstuvwxyz" VERIFY(str == src); } // this_type& append_sprintf_va_list(const value_type* pFormat, va_list arguments); // this_type& append_sprintf(const value_type* pFormat, ...); { #if EASTL_SNPRINTF_TESTS_ENABLED StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str.append_sprintf(LITERAL("Hello, %d"), 42); VERIFY(str == LITERAL("abcdefghijklmnopqrstuvwxyzHello, 42")); VERIFY(str.validate()); #endif } // template <typename OtherCharType> // this_type& append_convert(const OtherCharType* p); { { #if defined(EA_CHAR8) StringType str; str.append_convert(EA_CHAR8("123456789")); VERIFY(str == LITERAL("123456789")); VERIFY(str.validate()); #endif } { #if defined(EA_CHAR16) StringType str; str.append_convert(EA_CHAR16("123456789")); VERIFY(str == LITERAL("123456789")); VERIFY(str.validate()); #endif } { #if defined(EA_CHAR32) StringType str; str.append_convert(EA_CHAR32("123456789")); VERIFY(str == LITERAL("123456789")); VERIFY(str.validate()); #endif } { // #if defined(EA_WCHAR) // StringType str; // str.append_convert(EA_WCHAR("123456789")); // VERIFY(str == LITERAL("123456789")); // VERIFY(str.validate()); // #endif } } // template <typename OtherCharType> // this_type& append_convert(const OtherCharType* p, size_type n); { { #if defined(EA_CHAR8) StringType str; str.append_convert(EA_CHAR8("123456789"), 5); VERIFY(str == LITERAL("12345")); VERIFY(str.validate()); #endif } { #if defined(EA_CHAR16) StringType str; str.append_convert(EA_CHAR16("123456789"), 5); VERIFY(str == LITERAL("12345")); VERIFY(str.validate()); #endif } { #if defined(EA_CHAR32) StringType str; str.append_convert(EA_CHAR32("123456789"), 5); VERIFY(str == LITERAL("12345")); VERIFY(str.validate()); #endif } // { // #if defined(EA_WCHAR) // StringType str; // str.append_convert(EA_WCHAR("123456789"), 5); // VERIFY(str == LITERAL("12345")); // VERIFY(str.validate()); // #endif // } } // template <typename OtherStringType> // this_type& append_convert(const OtherStringType& x); { { #if defined(EA_CHAR8) StringType str; str.append_convert(EA_CHAR8("123456789"), 5); VERIFY(str == LITERAL("12345")); VERIFY(str.validate()); #endif } { #if defined(EA_CHAR16) StringType str; str.append_convert(EA_CHAR16("123456789"), 5); VERIFY(str == LITERAL("12345")); VERIFY(str.validate()); #endif } { #if defined(EA_CHAR32) StringType str; str.append_convert(EA_CHAR32("123456789"), 5); VERIFY(str == LITERAL("12345")); VERIFY(str.validate()); #endif } // { // #if defined(EA_WCHAR) // StringType str; // str.append_convert(EA_WCHAR("123456789"), 5); // VERIFY(str == LITERAL("12345")); // VERIFY(str.validate()); // #endif // } } // void push_back(value_type c); { StringType str; const StringType src(LITERAL("abcdefghijklmnopqrstuvwxyz")); eastl::for_each(eastl::begin(src), eastl::end(src), [&str](const typename StringType::value_type& c) { str.push_back(c); }); VERIFY(str == src); VERIFY(str.validate()); } // void pop_back(); { StringType str(LITERAL("123456789")); VERIFY(str == LITERAL("123456789")); str.pop_back(); VERIFY(str == LITERAL("12345678")); str.pop_back(); VERIFY(str == LITERAL("1234567")); str.pop_back(); VERIFY(str == LITERAL("123456")); str.pop_back(); VERIFY(str == LITERAL("12345")); str.pop_back(); VERIFY(str == LITERAL("1234")); str.pop_back(); VERIFY(str == LITERAL("123")); str.pop_back(); VERIFY(str == LITERAL("12")); str.pop_back(); VERIFY(str == LITERAL("1")); str.pop_back(); VERIFY(str == LITERAL("")); VERIFY(str.validate()); } // this_type& insert(size_type position, const this_type& x); // this_type& insert(size_type position, const this_type& x, size_type beg, size_type n); // this_type& insert(size_type position, const value_type* p, size_type n); // this_type& insert(size_type position, const value_type* p); // this_type& insert(size_type position, size_type n, value_type c); // iterator insert(const_iterator p, value_type c); // iterator insert(const_iterator p, size_type n, value_type c); // iterator insert(const_iterator p, const value_type* pBegin, const value_type* pEnd); { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str.insert((typename StringType::size_type)0, (typename StringType::size_type)1, LITERAL('1')); // todo: elminiate the cast to disambiguate VERIFY(str == LITERAL("1abcdefghijklmnopqrstuvwxyz")); str.insert(2, LITERAL("234")); VERIFY(str == LITERAL("1a234bcdefghijklmnopqrstuvwxyz")); str.insert(15, StringType(LITERAL("567"))); VERIFY(str == LITERAL("1a234bcdefghijk567lmnopqrstuvwxyz")); str.insert(30, StringType(LITERAL(" is an example of a substring")), 1, 14); VERIFY(str == LITERAL("1a234bcdefghijk567lmnopqrstuvwis an example xyz")); { StringType strSSO; auto nSSOCap = strSSO.capacity(); StringType strCheck; strCheck.append(nSSOCap, LITERAL('a')); strSSO.append(nSSOCap - 1, LITERAL('a')); strSSO.insert(strSSO.size() - 1, LITERAL("a")); VERIFY(strSSO.validate()); VERIFY(strSSO == strCheck); } { StringType strSSO; auto nSSOCap = strSSO.capacity(); // 32 bit platform with char32_t can only hold 2 characters in SSO if (nSSOCap - 2 > 0) { StringType strCheck; strCheck.append(nSSOCap, LITERAL('a')); strSSO.append(nSSOCap - 2, LITERAL('a')); strSSO.insert(strSSO.size() - 1, LITERAL("aa")); VERIFY(strSSO.validate()); VERIFY(strSSO == strCheck); } } } // iterator insert(const_iterator p, std::initializer_list<value_type>); { #if !defined(EA_COMPILER_NO_INITIALIZER_LISTS) StringType str; str.insert(str.begin(), {'a','b','c'}); str.insert(str.end(), {'d','e','f'}); str.insert(str.begin() + 3, {'1','2','3'}); VERIFY(str == LITERAL("abc123def")); VERIFY(str.validate()); #endif } // insert(const_iterator p, value_type c) { StringType str = LITERAL("aaa"); auto it = str.insert(str.end(), 'b'); VERIFY(*it == LITERAL('b')); VERIFY(str == LITERAL("aaab")); it = str.insert(str.begin(), 'c'); VERIFY(*it == LITERAL('c')); VERIFY(str == LITERAL("caaab")); it = str.insert(str.begin() + 2, 'd'); VERIFY(*it == LITERAL('d')); VERIFY(str == LITERAL("cadaab")); } // this_type& erase(size_type position = 0, size_type n = npos); // iterator erase(const_iterator p); // iterator erase(const_iterator pBegin, const_iterator pEnd); // reverse_iterator erase(reverse_iterator position); // reverse_iterator erase(reverse_iterator first, reverse_iterator last); { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str.erase(0,5); VERIFY(str == LITERAL("fghijklmnopqrstuvwxyz")); str.erase(5,10); VERIFY(str == LITERAL("fghijuvwxyz")); str.erase(str.find(LITERAL('v'))); VERIFY(str == LITERAL("fghiju")); str.erase(str.find(LITERAL('g')), str.find(LITERAL('i'))); VERIFY(str == LITERAL("fju")); typename StringType::const_iterator it = str.begin() + 1; // 'j' str.erase(it); VERIFY(str == LITERAL("fu")); } // void clear() EA_NOEXCEPT; { StringType str(LITERAL("123456789")); VERIFY(str == LITERAL("123456789")); str.clear(); VERIFY(str == LITERAL("")); VERIFY(str.empty()); VERIFY(str.validate()); } // pointer detach() EA_NOEXCEPT; { { // Heap auto* pLiteral = LITERAL("abcdefghijklmnopqrstuvwxyz"); StringType str(pLiteral); const auto sz = str.size() + 1; // +1 for null-terminator auto* pDetach = str.detach(); VERIFY(pDetach != nullptr); VERIFY(EA::StdC::Strcmp(pDetach, pLiteral) == 0); VERIFY(pDetach != pLiteral); VERIFY(str.empty()); VERIFY(str.size() == 0); str.get_allocator().deallocate(pDetach, sz); } { // SSO auto* pLiteral = LITERAL("a"); StringType str(pLiteral); const auto sz = str.size() + 1; // +1 for null-terminator auto* pDetach = str.detach(); VERIFY(pDetach != nullptr); VERIFY(EA::StdC::Strcmp(pDetach, pLiteral) == 0); VERIFY(pDetach != pLiteral); VERIFY(str.empty()); VERIFY(str.size() == 0); str.get_allocator().deallocate(pDetach, sz); } { // SSO, empty string auto* pLiteral = LITERAL(""); StringType str(pLiteral); const auto sz = str.size() + 1; // +1 for null-terminator auto* pDetach = str.detach(); VERIFY(pDetach != nullptr); VERIFY(EA::StdC::Strcmp(pDetach, pLiteral) == 0); VERIFY(pDetach != pLiteral); VERIFY(str.empty()); VERIFY(str.size() == 0); str.get_allocator().deallocate(pDetach, sz); } { // SSO, empty string via default ctor StringType str; const auto sz = str.size() + 1; // +1 for null-terminator auto* pDetach = str.detach(); VERIFY(pDetach != nullptr); VERIFY(pDetach[0] == 0); VERIFY(str.empty()); VERIFY(str.size() == 0); str.get_allocator().deallocate(pDetach, sz); } } // this_type& replace(size_type position, size_type n, const this_type& x); // this_type& replace(size_type pos1, size_type n1, const this_type& x, size_type pos2, size_type n2); // this_type& replace(size_type position, size_type n1, const value_type* p, size_type n2); // this_type& replace(size_type position, size_type n1, const value_type* p); // this_type& replace(size_type position, size_type n1, size_type n2, value_type c); // this_type& replace(const_iterator first, const_iterator last, const this_type& x); // this_type& replace(const_iterator first, const_iterator last, const value_type* p, size_type n); // this_type& replace(const_iterator first, const_iterator last, const value_type* p); // this_type& replace(const_iterator first, const_iterator last, size_type n, value_type c); // this_type& replace(const_iterator first, const_iterator last, const value_type* pBegin, const value_type* pEnd); { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str.replace(5, 10, StringType(LITERAL("123"))); VERIFY(str == LITERAL("abcde123pqrstuvwxyz")); str.replace(13, 1, StringType(LITERAL("0123456789")), 4, 6 ); VERIFY(str == LITERAL("abcde123pqrst456789vwxyz")); str.replace(24, 1, LITERAL("0123456789")); VERIFY(str == LITERAL("abcde123pqrst456789vwxyz0123456789")); str.replace(16, 4, 4, LITERAL('@')); VERIFY(str == LITERAL("abcde123pqrst456@@@@wxyz0123456789")); } // size_type copy(value_type* p, size_type n, size_type position = 0) const; { typename StringType::value_type buf[64]; StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str.copy(buf, 10, 10); VERIFY(EA::StdC::Memcmp(buf, LITERAL("klmnopqrst"), 10) == 0); } // size_type find(const this_type& x, size_type position = 0) const EA_NOEXCEPT; // size_type find(const value_type* p, size_type position = 0) const; // size_type find(const value_type* p, size_type position, size_type n) const; // size_type find(value_type c, size_type position = 0) const EA_NOEXCEPT; { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); VERIFY(str.find(StringType(LITERAL("d"))) != StringType::npos); VERIFY(str.find(StringType(LITERAL("tuv"))) != StringType::npos); VERIFY(str.find(StringType(LITERAL("123r"))) == StringType::npos); VERIFY(str.find(LITERAL("d")) != StringType::npos); VERIFY(str.find(LITERAL("tuv")) != StringType::npos); VERIFY(str.find(LITERAL("123r")) == StringType::npos); VERIFY(str.find(LITERAL("d"), 0) != StringType::npos); VERIFY(str.find(LITERAL("tuv"), 2) != StringType::npos); VERIFY(str.find(LITERAL("123r"), 2) == StringType::npos); VERIFY(str.find(LITERAL('d'), 0) != StringType::npos); VERIFY(str.find(LITERAL('t'), 2) != StringType::npos); VERIFY(str.find(LITERAL('1'), 2) == StringType::npos); } // size_type rfind(const this_type& x, size_type position = npos) const EA_NOEXCEPT; // size_type rfind(const value_type* p, size_type position = npos) const; // size_type rfind(const value_type* p, size_type position, size_type n) const; // size_type rfind(value_type c, size_type position = npos) const EA_NOEXCEPT; { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); VERIFY(str.rfind(StringType(LITERAL("d"))) != StringType::npos); VERIFY(str.rfind(StringType(LITERAL("tuv"))) != StringType::npos); VERIFY(str.rfind(StringType(LITERAL("123r"))) == StringType::npos); VERIFY(str.rfind(LITERAL("d")) != StringType::npos); VERIFY(str.rfind(LITERAL("tuv")) != StringType::npos); VERIFY(str.rfind(LITERAL("123r")) == StringType::npos); VERIFY(str.rfind(LITERAL("d"), 20) != StringType::npos); VERIFY(str.rfind(LITERAL("tuv"), 20) != StringType::npos); VERIFY(str.rfind(LITERAL("123r"), 20) == StringType::npos); VERIFY(str.rfind(LITERAL('d'), 20) != StringType::npos); VERIFY(str.rfind(LITERAL('t'), 20) != StringType::npos); VERIFY(str.rfind(LITERAL('1'), 20) == StringType::npos); } // size_type find_first_of(const this_type& x, size_type position = 0) const EA_NOEXCEPT; // size_type find_first_of(const value_type* p, size_type position = 0) const; // size_type find_first_of(const value_type* p, size_type position, size_type n) const; // size_type find_first_of(value_type c, size_type position = 0) const EA_NOEXCEPT; { StringType str(LITERAL("aaaaabbbbbcccdddddeeeeefffggh")); VERIFY(str.find_first_of(StringType(LITERAL("aaa"))) == 0); VERIFY(str.find_first_of(LITERAL("aab")) == 0); VERIFY(str.find_first_of(LITERAL("baab")) == 0); VERIFY(str.find_first_of(LITERAL("ceg")) == 10); VERIFY(str.find_first_of(LITERAL("eeef"), 1, 2) == 18); VERIFY(str.find_first_of(LITERAL("eeef"), 1, 4) == 18); VERIFY(str.find_first_of(LITERAL('g')) == 26); VERIFY(str.find_first_of(LITERAL('$')) == StringType::npos); } // size_type find_last_of(const this_type& x, size_type position = npos) const EA_NOEXCEPT; // size_type find_last_of(const value_type* p, size_type position = npos) const; // size_type find_last_of(const value_type* p, size_type position, size_type n) const; // size_type find_last_of(value_type c, size_type position = npos) const EA_NOEXCEPT; { StringType str(LITERAL("aaaaabbbbbcccdddddeeeeefffggh")); VERIFY(str.find_last_of(StringType(LITERAL("aaa"))) == 4); VERIFY(str.find_last_of(LITERAL("aab")) == 9); VERIFY(str.find_last_of(LITERAL("baab")) == 9); VERIFY(str.find_last_of(LITERAL("ceg")) == 27); // VERIFY(str.find_last_of(LITERAL("eeef"), 1, 2) == StringType::npos); // todo: FIX ME // VERIFY(str.find_last_of(LITERAL("eeef"), 1, 4) == StringType::npos); // todo: FIX ME VERIFY(str.find_last_of(LITERAL('g')) == 27); VERIFY(str.find_last_of(LITERAL('$')) == StringType::npos); } // size_type find_first_not_of(const this_type& x, size_type position = 0) const EA_NOEXCEPT; // size_type find_first_not_of(const value_type* p, size_type position = 0) const; // size_type find_first_not_of(const value_type* p, size_type position, size_type n) const; // size_type find_first_not_of(value_type c, size_type position = 0) const EA_NOEXCEPT; { StringType str(LITERAL("aaaaabbbbbcccdddddeeeeefffggh")); VERIFY(str.find_first_not_of(StringType(LITERAL("abcdfg"))) == 18); VERIFY(str.find_first_not_of(LITERAL("abcdfg")) == 18); // VERIFY(str.find_first_not_of(LITERAL("abcdfg"), 2, 2) == 0); // todo: FIX ME // VERIFY(str.find_first_not_of(LITERAL("abcdfg"), 0, 2) == 10); // todo: FIX ME VERIFY(str.find_first_not_of(LITERAL('a')) == 5); } // size_type find_last_not_of(const this_type& x, size_type position = npos) const EA_NOEXCEPT; // size_type find_last_not_of(const value_type* p, size_type position = npos) const; // size_type find_last_not_of(const value_type* p, size_type position, size_type n) const; // size_type find_last_not_of(value_type c, size_type position = npos) const EA_NOEXCEPT; { StringType str(LITERAL("aaaaabbbbbcccdddddeeeeefffggh")); VERIFY(str.find_last_not_of(StringType(LITERAL("a"))) == 28); VERIFY(str.find_last_not_of(StringType(LITERAL("abcdfg"))) == 28); VERIFY(str.find_last_not_of(StringType(LITERAL("abcdfgh"))) == 22); VERIFY(str.find_last_not_of(LITERAL("abcdfgh")) == 22); // VERIFY(str.find_last_not_of(LITERAL("abcdfg"), 2, 2) == 0); // todo: FIX ME // VERIFY(str.find_last_not_of(LITERAL("abcdfg"), 0, 2) == 10); // todo: FIX ME VERIFY(str.find_last_not_of(LITERAL('a')) == 28); } // this_type substr(size_type position = 0, size_type n = npos) const; { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); auto substring = str.substr(0, 6); VERIFY(substring == LITERAL("abcdef")); substring = str.substr(0, 0); VERIFY(substring == LITERAL("")); substring = str.substr(16, 0); VERIFY(substring == LITERAL("")); substring = str.substr(16, 42); VERIFY(substring == LITERAL("qrstuvwxyz")); } // int compare(const this_type& x) const EA_NOEXCEPT; // int compare(size_type pos1, size_type n1, const this_type& x) const; // int compare(size_type pos1, size_type n1, const this_type& x, size_type pos2, size_type n2) const; // int compare(const value_type* p) const; // int compare(size_type pos1, size_type n1, const value_type* p) const; // int compare(size_type pos1, size_type n1, const value_type* p, size_type n2) const; // static int compare(const value_type* pBegin1, const value_type* pEnd1, const value_type* pBegin2, const value_type* pEnd2); { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); VERIFY(str.compare(StringType(LITERAL("abcdefghijklmnopqrstuvwxyz"))) == 0); VERIFY(str.compare(StringType(LITERAL("ABCDEFGHIJKLMNOPQRSTUVWXYZ"))) != 0); VERIFY(str.compare(StringType(LITERAL("abcdefghijklmnopqrstuvwxyz123"))) != 0); VERIFY(str.compare(LITERAL("abcdefghijklmnopqrstuvwxyz")) == 0); VERIFY(str.compare(LITERAL("abcdefghijklmnopqrstuvwxyz123")) != 0); VERIFY(str.compare(LITERAL("ABCDEFGHIJKLMNOPQRSTUVWXYZ123")) != 0); } // int comparei(const this_type& x) const EA_NOEXCEPT; // int comparei(const value_type* p) const; // static int comparei(const value_type* pBegin1, const value_type* pEnd1, const value_type* pBegin2, const value_type* pEnd2); { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); VERIFY(str.comparei(StringType(LITERAL("abcdefghijklmnopqrstuvwxyz"))) == 0); VERIFY(str.comparei(StringType(LITERAL("ABCDEFGHIJKLMNOPQRSTUVWXYZ"))) == 0); VERIFY(str.comparei(StringType(LITERAL("abcdefghijklmnopqrstuvwxyz123"))) != 0); VERIFY(str.comparei(LITERAL("abcdefghijklmnopqrstuvwxyz")) == 0); VERIFY(str.comparei(LITERAL("ABCDEFGHIJKLMNOPQRSTUVWXYZ")) == 0); VERIFY(str.comparei(LITERAL("abcdefghijklmnopqrstuvwxyz123")) != 0); } // void make_lower(); { { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str.make_lower(); VERIFY(str == LITERAL("abcdefghijklmnopqrstuvwxyz")); } { StringType str(LITERAL("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); str.make_lower(); VERIFY(str == LITERAL("abcdefghijklmnopqrstuvwxyz")); } { StringType str(LITERAL("123456789~!@#$%^&*()_+")); str.make_lower(); VERIFY(str == LITERAL("123456789~!@#$%^&*()_+")); } } // void make_upper(); { { StringType str(LITERAL("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); str.make_upper(); VERIFY(str == LITERAL("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); } { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); str.make_upper(); VERIFY(str == LITERAL("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); } { StringType str(LITERAL("123456789~!@#$%^&*()_+")); str.make_upper(); VERIFY(str == LITERAL("123456789~!@#$%^&*()_+")); } } // void ltrim(); // void rtrim(); // void trim(); { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); { StringType rstr(LITERAL("abcdefghijklmnopqrstuvwxyz \t \t\t\t ")); rstr.ltrim(); VERIFY(str != rstr); } { StringType lstr(LITERAL(" \t abcdefghijklmnopqrstuvwxyz")); lstr.ltrim(); VERIFY(str == lstr); } { StringType rstr(LITERAL("abcdefghijklmnopqrstuvwxyz \t\t\t ")); rstr.rtrim(); VERIFY(str == rstr); } { StringType lstr(LITERAL(" \t abcdefghijklmnopqrstuvwxyz")); lstr.rtrim(); VERIFY(str != lstr); } { StringType lrstr(LITERAL(" \t abcdefghijklmnopqrstuvwxyz \t ")); lrstr.trim(); VERIFY(str == lrstr); } { auto* pLiteral = LITERAL("abcdefghijklmn opqrstuvwxyz"); StringType mstr(pLiteral); mstr.trim(); VERIFY(mstr == pLiteral); } } // this_type left(size_type n) const; // this_type right(size_type n) const; { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); auto lstr = str.left(6); VERIFY(lstr == LITERAL("abcdef")); auto rstr = str.right(8); VERIFY(rstr == LITERAL("stuvwxyz")); } // this_type& sprintf_va_list(const value_type* pFormat, va_list arguments); // this_type& sprintf(const value_type* pFormat, ...); { #if EASTL_SNPRINTF_TESTS_ENABLED StringType str(LITERAL("")); str.sprintf(LITERAL("Hello, %d"), 42); VERIFY(str == LITERAL("Hello, 42")); #endif } // void force_size(size_type n); { StringType str(LITERAL("")); str.reserve(10); auto p = const_cast<typename StringType::value_type*>(str.data()); p[0] = 'a'; p[1] = 'a'; p[2] = 'a'; p[3] = '\0'; str.force_size(3); VERIFY(str.size() == 3); VERIFY(str.validate()); VERIFY(!str.empty()); } // test basic_string implicit conversion to basic_string_view // eastl::string implicitly converts to eastl::string_view. { StringType str(LITERAL("abcdefghijklmnopqrstuvwxyz")); [&](basic_string_view<typename StringType::value_type> sv) // simulate api that requires eastl::string_view. { VERIFY(sv.compare(LITERAL("abcdefghijklmnopqrstuvwxyz")) == 0); }(str); } return nErrorCount; } // Required to prevent manual undef of macros when 'TestString.inl' preprocessed at the top of the unit test cpp file. #undef TEST_STRING_NAME #undef LITERAL
dc2ba2c62890c211cef93c7d9a1d5dc617e8cab0
9c0987e2a040902a82ed04d5e788a074a2161d2f
/cpp/platform/impl/windows/generated/winrt/impl/Windows.Devices.PointOfService.1.h
98c360e32a9ebf5d354d9be58efa552d6b8360cc
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
l1kw1d/nearby-connections
ff9119338a6bd3e5c61bc2c93d8d28b96e5ebae5
ea231c7138d3dea8cd4cd75692137e078cbdd73d
refs/heads/master
2023-06-15T04:15:54.683855
2021-07-12T23:05:16
2021-07-12T23:06:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
82,793
h
// 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 // // https://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. // WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.210505.3 #ifndef WINRT_Windows_Devices_PointOfService_1_H #define WINRT_Windows_Devices_PointOfService_1_H #include "winrt/impl/Windows.Devices.PointOfService.0.h" WINRT_EXPORT namespace winrt::Windows::Devices::PointOfService { struct __declspec(empty_bases) IBarcodeScanner : winrt::Windows::Foundation::IInspectable, impl::consume_t<IBarcodeScanner> { IBarcodeScanner(std::nullptr_t = nullptr) noexcept {} IBarcodeScanner(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IBarcodeScanner(IBarcodeScanner const&) noexcept = default; IBarcodeScanner(IBarcodeScanner&&) noexcept = default; IBarcodeScanner& operator=(IBarcodeScanner const&) & noexcept = default; IBarcodeScanner& operator=(IBarcodeScanner&&) & noexcept = default; }; struct __declspec(empty_bases) IBarcodeScanner2 : winrt::Windows::Foundation::IInspectable, impl::consume_t<IBarcodeScanner2> { IBarcodeScanner2(std::nullptr_t = nullptr) noexcept {} IBarcodeScanner2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IBarcodeScanner2(IBarcodeScanner2 const&) noexcept = default; IBarcodeScanner2(IBarcodeScanner2&&) noexcept = default; IBarcodeScanner2& operator=(IBarcodeScanner2 const&) & noexcept = default; IBarcodeScanner2& operator=(IBarcodeScanner2&&) & noexcept = default; }; struct __declspec(empty_bases) IBarcodeScannerCapabilities : winrt::Windows::Foundation::IInspectable, impl::consume_t<IBarcodeScannerCapabilities> { IBarcodeScannerCapabilities(std::nullptr_t = nullptr) noexcept {} IBarcodeScannerCapabilities(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IBarcodeScannerCapabilities(IBarcodeScannerCapabilities const&) noexcept = default; IBarcodeScannerCapabilities(IBarcodeScannerCapabilities&&) noexcept = default; IBarcodeScannerCapabilities& operator=(IBarcodeScannerCapabilities const&) & noexcept = default; IBarcodeScannerCapabilities& operator=(IBarcodeScannerCapabilities&&) & noexcept = default; }; struct __declspec(empty_bases) IBarcodeScannerCapabilities1 : winrt::Windows::Foundation::IInspectable, impl::consume_t<IBarcodeScannerCapabilities1> { IBarcodeScannerCapabilities1(std::nullptr_t = nullptr) noexcept {} IBarcodeScannerCapabilities1(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IBarcodeScannerCapabilities1(IBarcodeScannerCapabilities1 const&) noexcept = default; IBarcodeScannerCapabilities1(IBarcodeScannerCapabilities1&&) noexcept = default; IBarcodeScannerCapabilities1& operator=(IBarcodeScannerCapabilities1 const&) & noexcept = default; IBarcodeScannerCapabilities1& operator=(IBarcodeScannerCapabilities1&&) & noexcept = default; }; struct __declspec(empty_bases) IBarcodeScannerCapabilities2 : winrt::Windows::Foundation::IInspectable, impl::consume_t<IBarcodeScannerCapabilities2> { IBarcodeScannerCapabilities2(std::nullptr_t = nullptr) noexcept {} IBarcodeScannerCapabilities2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IBarcodeScannerCapabilities2(IBarcodeScannerCapabilities2 const&) noexcept = default; IBarcodeScannerCapabilities2(IBarcodeScannerCapabilities2&&) noexcept = default; IBarcodeScannerCapabilities2& operator=(IBarcodeScannerCapabilities2 const&) & noexcept = default; IBarcodeScannerCapabilities2& operator=(IBarcodeScannerCapabilities2&&) & noexcept = default; }; struct __declspec(empty_bases) IBarcodeScannerDataReceivedEventArgs : winrt::Windows::Foundation::IInspectable, impl::consume_t<IBarcodeScannerDataReceivedEventArgs> { IBarcodeScannerDataReceivedEventArgs(std::nullptr_t = nullptr) noexcept {} IBarcodeScannerDataReceivedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IBarcodeScannerDataReceivedEventArgs(IBarcodeScannerDataReceivedEventArgs const&) noexcept = default; IBarcodeScannerDataReceivedEventArgs(IBarcodeScannerDataReceivedEventArgs&&) noexcept = default; IBarcodeScannerDataReceivedEventArgs& operator=(IBarcodeScannerDataReceivedEventArgs const&) & noexcept = default; IBarcodeScannerDataReceivedEventArgs& operator=(IBarcodeScannerDataReceivedEventArgs&&) & noexcept = default; }; struct __declspec(empty_bases) IBarcodeScannerErrorOccurredEventArgs : winrt::Windows::Foundation::IInspectable, impl::consume_t<IBarcodeScannerErrorOccurredEventArgs> { IBarcodeScannerErrorOccurredEventArgs(std::nullptr_t = nullptr) noexcept {} IBarcodeScannerErrorOccurredEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IBarcodeScannerErrorOccurredEventArgs(IBarcodeScannerErrorOccurredEventArgs const&) noexcept = default; IBarcodeScannerErrorOccurredEventArgs(IBarcodeScannerErrorOccurredEventArgs&&) noexcept = default; IBarcodeScannerErrorOccurredEventArgs& operator=(IBarcodeScannerErrorOccurredEventArgs const&) & noexcept = default; IBarcodeScannerErrorOccurredEventArgs& operator=(IBarcodeScannerErrorOccurredEventArgs&&) & noexcept = default; }; struct __declspec(empty_bases) IBarcodeScannerImagePreviewReceivedEventArgs : winrt::Windows::Foundation::IInspectable, impl::consume_t<IBarcodeScannerImagePreviewReceivedEventArgs> { IBarcodeScannerImagePreviewReceivedEventArgs(std::nullptr_t = nullptr) noexcept {} IBarcodeScannerImagePreviewReceivedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IBarcodeScannerImagePreviewReceivedEventArgs(IBarcodeScannerImagePreviewReceivedEventArgs const&) noexcept = default; IBarcodeScannerImagePreviewReceivedEventArgs(IBarcodeScannerImagePreviewReceivedEventArgs&&) noexcept = default; IBarcodeScannerImagePreviewReceivedEventArgs& operator=(IBarcodeScannerImagePreviewReceivedEventArgs const&) & noexcept = default; IBarcodeScannerImagePreviewReceivedEventArgs& operator=(IBarcodeScannerImagePreviewReceivedEventArgs&&) & noexcept = default; }; struct __declspec(empty_bases) IBarcodeScannerReport : winrt::Windows::Foundation::IInspectable, impl::consume_t<IBarcodeScannerReport> { IBarcodeScannerReport(std::nullptr_t = nullptr) noexcept {} IBarcodeScannerReport(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IBarcodeScannerReport(IBarcodeScannerReport const&) noexcept = default; IBarcodeScannerReport(IBarcodeScannerReport&&) noexcept = default; IBarcodeScannerReport& operator=(IBarcodeScannerReport const&) & noexcept = default; IBarcodeScannerReport& operator=(IBarcodeScannerReport&&) & noexcept = default; }; struct __declspec(empty_bases) IBarcodeScannerReportFactory : winrt::Windows::Foundation::IInspectable, impl::consume_t<IBarcodeScannerReportFactory> { IBarcodeScannerReportFactory(std::nullptr_t = nullptr) noexcept {} IBarcodeScannerReportFactory(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IBarcodeScannerReportFactory(IBarcodeScannerReportFactory const&) noexcept = default; IBarcodeScannerReportFactory(IBarcodeScannerReportFactory&&) noexcept = default; IBarcodeScannerReportFactory& operator=(IBarcodeScannerReportFactory const&) & noexcept = default; IBarcodeScannerReportFactory& operator=(IBarcodeScannerReportFactory&&) & noexcept = default; }; struct __declspec(empty_bases) IBarcodeScannerStatics : winrt::Windows::Foundation::IInspectable, impl::consume_t<IBarcodeScannerStatics> { IBarcodeScannerStatics(std::nullptr_t = nullptr) noexcept {} IBarcodeScannerStatics(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IBarcodeScannerStatics(IBarcodeScannerStatics const&) noexcept = default; IBarcodeScannerStatics(IBarcodeScannerStatics&&) noexcept = default; IBarcodeScannerStatics& operator=(IBarcodeScannerStatics const&) & noexcept = default; IBarcodeScannerStatics& operator=(IBarcodeScannerStatics&&) & noexcept = default; }; struct __declspec(empty_bases) IBarcodeScannerStatics2 : winrt::Windows::Foundation::IInspectable, impl::consume_t<IBarcodeScannerStatics2> { IBarcodeScannerStatics2(std::nullptr_t = nullptr) noexcept {} IBarcodeScannerStatics2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IBarcodeScannerStatics2(IBarcodeScannerStatics2 const&) noexcept = default; IBarcodeScannerStatics2(IBarcodeScannerStatics2&&) noexcept = default; IBarcodeScannerStatics2& operator=(IBarcodeScannerStatics2 const&) & noexcept = default; IBarcodeScannerStatics2& operator=(IBarcodeScannerStatics2&&) & noexcept = default; }; struct __declspec(empty_bases) IBarcodeScannerStatusUpdatedEventArgs : winrt::Windows::Foundation::IInspectable, impl::consume_t<IBarcodeScannerStatusUpdatedEventArgs> { IBarcodeScannerStatusUpdatedEventArgs(std::nullptr_t = nullptr) noexcept {} IBarcodeScannerStatusUpdatedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IBarcodeScannerStatusUpdatedEventArgs(IBarcodeScannerStatusUpdatedEventArgs const&) noexcept = default; IBarcodeScannerStatusUpdatedEventArgs(IBarcodeScannerStatusUpdatedEventArgs&&) noexcept = default; IBarcodeScannerStatusUpdatedEventArgs& operator=(IBarcodeScannerStatusUpdatedEventArgs const&) & noexcept = default; IBarcodeScannerStatusUpdatedEventArgs& operator=(IBarcodeScannerStatusUpdatedEventArgs&&) & noexcept = default; }; struct __declspec(empty_bases) IBarcodeSymbologiesStatics : winrt::Windows::Foundation::IInspectable, impl::consume_t<IBarcodeSymbologiesStatics> { IBarcodeSymbologiesStatics(std::nullptr_t = nullptr) noexcept {} IBarcodeSymbologiesStatics(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IBarcodeSymbologiesStatics(IBarcodeSymbologiesStatics const&) noexcept = default; IBarcodeSymbologiesStatics(IBarcodeSymbologiesStatics&&) noexcept = default; IBarcodeSymbologiesStatics& operator=(IBarcodeSymbologiesStatics const&) & noexcept = default; IBarcodeSymbologiesStatics& operator=(IBarcodeSymbologiesStatics&&) & noexcept = default; }; struct __declspec(empty_bases) IBarcodeSymbologiesStatics2 : winrt::Windows::Foundation::IInspectable, impl::consume_t<IBarcodeSymbologiesStatics2> { IBarcodeSymbologiesStatics2(std::nullptr_t = nullptr) noexcept {} IBarcodeSymbologiesStatics2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IBarcodeSymbologiesStatics2(IBarcodeSymbologiesStatics2 const&) noexcept = default; IBarcodeSymbologiesStatics2(IBarcodeSymbologiesStatics2&&) noexcept = default; IBarcodeSymbologiesStatics2& operator=(IBarcodeSymbologiesStatics2 const&) & noexcept = default; IBarcodeSymbologiesStatics2& operator=(IBarcodeSymbologiesStatics2&&) & noexcept = default; }; struct __declspec(empty_bases) IBarcodeSymbologyAttributes : winrt::Windows::Foundation::IInspectable, impl::consume_t<IBarcodeSymbologyAttributes> { IBarcodeSymbologyAttributes(std::nullptr_t = nullptr) noexcept {} IBarcodeSymbologyAttributes(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IBarcodeSymbologyAttributes(IBarcodeSymbologyAttributes const&) noexcept = default; IBarcodeSymbologyAttributes(IBarcodeSymbologyAttributes&&) noexcept = default; IBarcodeSymbologyAttributes& operator=(IBarcodeSymbologyAttributes const&) & noexcept = default; IBarcodeSymbologyAttributes& operator=(IBarcodeSymbologyAttributes&&) & noexcept = default; }; struct __declspec(empty_bases) ICashDrawer : winrt::Windows::Foundation::IInspectable, impl::consume_t<ICashDrawer> { ICashDrawer(std::nullptr_t = nullptr) noexcept {} ICashDrawer(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ICashDrawer(ICashDrawer const&) noexcept = default; ICashDrawer(ICashDrawer&&) noexcept = default; ICashDrawer& operator=(ICashDrawer const&) & noexcept = default; ICashDrawer& operator=(ICashDrawer&&) & noexcept = default; }; struct __declspec(empty_bases) ICashDrawerCapabilities : winrt::Windows::Foundation::IInspectable, impl::consume_t<ICashDrawerCapabilities> { ICashDrawerCapabilities(std::nullptr_t = nullptr) noexcept {} ICashDrawerCapabilities(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ICashDrawerCapabilities(ICashDrawerCapabilities const&) noexcept = default; ICashDrawerCapabilities(ICashDrawerCapabilities&&) noexcept = default; ICashDrawerCapabilities& operator=(ICashDrawerCapabilities const&) & noexcept = default; ICashDrawerCapabilities& operator=(ICashDrawerCapabilities&&) & noexcept = default; }; struct __declspec(empty_bases) ICashDrawerCloseAlarm : winrt::Windows::Foundation::IInspectable, impl::consume_t<ICashDrawerCloseAlarm> { ICashDrawerCloseAlarm(std::nullptr_t = nullptr) noexcept {} ICashDrawerCloseAlarm(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ICashDrawerCloseAlarm(ICashDrawerCloseAlarm const&) noexcept = default; ICashDrawerCloseAlarm(ICashDrawerCloseAlarm&&) noexcept = default; ICashDrawerCloseAlarm& operator=(ICashDrawerCloseAlarm const&) & noexcept = default; ICashDrawerCloseAlarm& operator=(ICashDrawerCloseAlarm&&) & noexcept = default; }; struct __declspec(empty_bases) ICashDrawerEventSource : winrt::Windows::Foundation::IInspectable, impl::consume_t<ICashDrawerEventSource> { ICashDrawerEventSource(std::nullptr_t = nullptr) noexcept {} ICashDrawerEventSource(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ICashDrawerEventSource(ICashDrawerEventSource const&) noexcept = default; ICashDrawerEventSource(ICashDrawerEventSource&&) noexcept = default; ICashDrawerEventSource& operator=(ICashDrawerEventSource const&) & noexcept = default; ICashDrawerEventSource& operator=(ICashDrawerEventSource&&) & noexcept = default; }; struct __declspec(empty_bases) ICashDrawerEventSourceEventArgs : winrt::Windows::Foundation::IInspectable, impl::consume_t<ICashDrawerEventSourceEventArgs> { ICashDrawerEventSourceEventArgs(std::nullptr_t = nullptr) noexcept {} ICashDrawerEventSourceEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ICashDrawerEventSourceEventArgs(ICashDrawerEventSourceEventArgs const&) noexcept = default; ICashDrawerEventSourceEventArgs(ICashDrawerEventSourceEventArgs&&) noexcept = default; ICashDrawerEventSourceEventArgs& operator=(ICashDrawerEventSourceEventArgs const&) & noexcept = default; ICashDrawerEventSourceEventArgs& operator=(ICashDrawerEventSourceEventArgs&&) & noexcept = default; }; struct __declspec(empty_bases) ICashDrawerStatics : winrt::Windows::Foundation::IInspectable, impl::consume_t<ICashDrawerStatics> { ICashDrawerStatics(std::nullptr_t = nullptr) noexcept {} ICashDrawerStatics(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ICashDrawerStatics(ICashDrawerStatics const&) noexcept = default; ICashDrawerStatics(ICashDrawerStatics&&) noexcept = default; ICashDrawerStatics& operator=(ICashDrawerStatics const&) & noexcept = default; ICashDrawerStatics& operator=(ICashDrawerStatics&&) & noexcept = default; }; struct __declspec(empty_bases) ICashDrawerStatics2 : winrt::Windows::Foundation::IInspectable, impl::consume_t<ICashDrawerStatics2> { ICashDrawerStatics2(std::nullptr_t = nullptr) noexcept {} ICashDrawerStatics2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ICashDrawerStatics2(ICashDrawerStatics2 const&) noexcept = default; ICashDrawerStatics2(ICashDrawerStatics2&&) noexcept = default; ICashDrawerStatics2& operator=(ICashDrawerStatics2 const&) & noexcept = default; ICashDrawerStatics2& operator=(ICashDrawerStatics2&&) & noexcept = default; }; struct __declspec(empty_bases) ICashDrawerStatus : winrt::Windows::Foundation::IInspectable, impl::consume_t<ICashDrawerStatus> { ICashDrawerStatus(std::nullptr_t = nullptr) noexcept {} ICashDrawerStatus(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ICashDrawerStatus(ICashDrawerStatus const&) noexcept = default; ICashDrawerStatus(ICashDrawerStatus&&) noexcept = default; ICashDrawerStatus& operator=(ICashDrawerStatus const&) & noexcept = default; ICashDrawerStatus& operator=(ICashDrawerStatus&&) & noexcept = default; }; struct __declspec(empty_bases) ICashDrawerStatusUpdatedEventArgs : winrt::Windows::Foundation::IInspectable, impl::consume_t<ICashDrawerStatusUpdatedEventArgs> { ICashDrawerStatusUpdatedEventArgs(std::nullptr_t = nullptr) noexcept {} ICashDrawerStatusUpdatedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ICashDrawerStatusUpdatedEventArgs(ICashDrawerStatusUpdatedEventArgs const&) noexcept = default; ICashDrawerStatusUpdatedEventArgs(ICashDrawerStatusUpdatedEventArgs&&) noexcept = default; ICashDrawerStatusUpdatedEventArgs& operator=(ICashDrawerStatusUpdatedEventArgs const&) & noexcept = default; ICashDrawerStatusUpdatedEventArgs& operator=(ICashDrawerStatusUpdatedEventArgs&&) & noexcept = default; }; struct __declspec(empty_bases) IClaimedBarcodeScanner : winrt::Windows::Foundation::IInspectable, impl::consume_t<IClaimedBarcodeScanner> { IClaimedBarcodeScanner(std::nullptr_t = nullptr) noexcept {} IClaimedBarcodeScanner(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IClaimedBarcodeScanner(IClaimedBarcodeScanner const&) noexcept = default; IClaimedBarcodeScanner(IClaimedBarcodeScanner&&) noexcept = default; IClaimedBarcodeScanner& operator=(IClaimedBarcodeScanner const&) & noexcept = default; IClaimedBarcodeScanner& operator=(IClaimedBarcodeScanner&&) & noexcept = default; }; struct __declspec(empty_bases) IClaimedBarcodeScanner1 : winrt::Windows::Foundation::IInspectable, impl::consume_t<IClaimedBarcodeScanner1> { IClaimedBarcodeScanner1(std::nullptr_t = nullptr) noexcept {} IClaimedBarcodeScanner1(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IClaimedBarcodeScanner1(IClaimedBarcodeScanner1 const&) noexcept = default; IClaimedBarcodeScanner1(IClaimedBarcodeScanner1&&) noexcept = default; IClaimedBarcodeScanner1& operator=(IClaimedBarcodeScanner1 const&) & noexcept = default; IClaimedBarcodeScanner1& operator=(IClaimedBarcodeScanner1&&) & noexcept = default; }; struct __declspec(empty_bases) IClaimedBarcodeScanner2 : winrt::Windows::Foundation::IInspectable, impl::consume_t<IClaimedBarcodeScanner2> { IClaimedBarcodeScanner2(std::nullptr_t = nullptr) noexcept {} IClaimedBarcodeScanner2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IClaimedBarcodeScanner2(IClaimedBarcodeScanner2 const&) noexcept = default; IClaimedBarcodeScanner2(IClaimedBarcodeScanner2&&) noexcept = default; IClaimedBarcodeScanner2& operator=(IClaimedBarcodeScanner2 const&) & noexcept = default; IClaimedBarcodeScanner2& operator=(IClaimedBarcodeScanner2&&) & noexcept = default; }; struct __declspec(empty_bases) IClaimedBarcodeScanner3 : winrt::Windows::Foundation::IInspectable, impl::consume_t<IClaimedBarcodeScanner3> { IClaimedBarcodeScanner3(std::nullptr_t = nullptr) noexcept {} IClaimedBarcodeScanner3(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IClaimedBarcodeScanner3(IClaimedBarcodeScanner3 const&) noexcept = default; IClaimedBarcodeScanner3(IClaimedBarcodeScanner3&&) noexcept = default; IClaimedBarcodeScanner3& operator=(IClaimedBarcodeScanner3 const&) & noexcept = default; IClaimedBarcodeScanner3& operator=(IClaimedBarcodeScanner3&&) & noexcept = default; }; struct __declspec(empty_bases) IClaimedBarcodeScanner4 : winrt::Windows::Foundation::IInspectable, impl::consume_t<IClaimedBarcodeScanner4> { IClaimedBarcodeScanner4(std::nullptr_t = nullptr) noexcept {} IClaimedBarcodeScanner4(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IClaimedBarcodeScanner4(IClaimedBarcodeScanner4 const&) noexcept = default; IClaimedBarcodeScanner4(IClaimedBarcodeScanner4&&) noexcept = default; IClaimedBarcodeScanner4& operator=(IClaimedBarcodeScanner4 const&) & noexcept = default; IClaimedBarcodeScanner4& operator=(IClaimedBarcodeScanner4&&) & noexcept = default; }; struct __declspec(empty_bases) IClaimedBarcodeScannerClosedEventArgs : winrt::Windows::Foundation::IInspectable, impl::consume_t<IClaimedBarcodeScannerClosedEventArgs> { IClaimedBarcodeScannerClosedEventArgs(std::nullptr_t = nullptr) noexcept {} IClaimedBarcodeScannerClosedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IClaimedBarcodeScannerClosedEventArgs(IClaimedBarcodeScannerClosedEventArgs const&) noexcept = default; IClaimedBarcodeScannerClosedEventArgs(IClaimedBarcodeScannerClosedEventArgs&&) noexcept = default; IClaimedBarcodeScannerClosedEventArgs& operator=(IClaimedBarcodeScannerClosedEventArgs const&) & noexcept = default; IClaimedBarcodeScannerClosedEventArgs& operator=(IClaimedBarcodeScannerClosedEventArgs&&) & noexcept = default; }; struct __declspec(empty_bases) IClaimedCashDrawer : winrt::Windows::Foundation::IInspectable, impl::consume_t<IClaimedCashDrawer> { IClaimedCashDrawer(std::nullptr_t = nullptr) noexcept {} IClaimedCashDrawer(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IClaimedCashDrawer(IClaimedCashDrawer const&) noexcept = default; IClaimedCashDrawer(IClaimedCashDrawer&&) noexcept = default; IClaimedCashDrawer& operator=(IClaimedCashDrawer const&) & noexcept = default; IClaimedCashDrawer& operator=(IClaimedCashDrawer&&) & noexcept = default; }; struct __declspec(empty_bases) IClaimedCashDrawer2 : winrt::Windows::Foundation::IInspectable, impl::consume_t<IClaimedCashDrawer2> { IClaimedCashDrawer2(std::nullptr_t = nullptr) noexcept {} IClaimedCashDrawer2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IClaimedCashDrawer2(IClaimedCashDrawer2 const&) noexcept = default; IClaimedCashDrawer2(IClaimedCashDrawer2&&) noexcept = default; IClaimedCashDrawer2& operator=(IClaimedCashDrawer2 const&) & noexcept = default; IClaimedCashDrawer2& operator=(IClaimedCashDrawer2&&) & noexcept = default; }; struct __declspec(empty_bases) IClaimedCashDrawerClosedEventArgs : winrt::Windows::Foundation::IInspectable, impl::consume_t<IClaimedCashDrawerClosedEventArgs> { IClaimedCashDrawerClosedEventArgs(std::nullptr_t = nullptr) noexcept {} IClaimedCashDrawerClosedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IClaimedCashDrawerClosedEventArgs(IClaimedCashDrawerClosedEventArgs const&) noexcept = default; IClaimedCashDrawerClosedEventArgs(IClaimedCashDrawerClosedEventArgs&&) noexcept = default; IClaimedCashDrawerClosedEventArgs& operator=(IClaimedCashDrawerClosedEventArgs const&) & noexcept = default; IClaimedCashDrawerClosedEventArgs& operator=(IClaimedCashDrawerClosedEventArgs&&) & noexcept = default; }; struct __declspec(empty_bases) IClaimedJournalPrinter : winrt::Windows::Foundation::IInspectable, impl::consume_t<IClaimedJournalPrinter> { IClaimedJournalPrinter(std::nullptr_t = nullptr) noexcept {} IClaimedJournalPrinter(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IClaimedJournalPrinter(IClaimedJournalPrinter const&) noexcept = default; IClaimedJournalPrinter(IClaimedJournalPrinter&&) noexcept = default; IClaimedJournalPrinter& operator=(IClaimedJournalPrinter const&) & noexcept = default; IClaimedJournalPrinter& operator=(IClaimedJournalPrinter&&) & noexcept = default; }; struct __declspec(empty_bases) IClaimedLineDisplay : winrt::Windows::Foundation::IInspectable, impl::consume_t<IClaimedLineDisplay> { IClaimedLineDisplay(std::nullptr_t = nullptr) noexcept {} IClaimedLineDisplay(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IClaimedLineDisplay(IClaimedLineDisplay const&) noexcept = default; IClaimedLineDisplay(IClaimedLineDisplay&&) noexcept = default; IClaimedLineDisplay& operator=(IClaimedLineDisplay const&) & noexcept = default; IClaimedLineDisplay& operator=(IClaimedLineDisplay&&) & noexcept = default; }; struct __declspec(empty_bases) IClaimedLineDisplay2 : winrt::Windows::Foundation::IInspectable, impl::consume_t<IClaimedLineDisplay2> { IClaimedLineDisplay2(std::nullptr_t = nullptr) noexcept {} IClaimedLineDisplay2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IClaimedLineDisplay2(IClaimedLineDisplay2 const&) noexcept = default; IClaimedLineDisplay2(IClaimedLineDisplay2&&) noexcept = default; IClaimedLineDisplay2& operator=(IClaimedLineDisplay2 const&) & noexcept = default; IClaimedLineDisplay2& operator=(IClaimedLineDisplay2&&) & noexcept = default; }; struct __declspec(empty_bases) IClaimedLineDisplay3 : winrt::Windows::Foundation::IInspectable, impl::consume_t<IClaimedLineDisplay3> { IClaimedLineDisplay3(std::nullptr_t = nullptr) noexcept {} IClaimedLineDisplay3(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IClaimedLineDisplay3(IClaimedLineDisplay3 const&) noexcept = default; IClaimedLineDisplay3(IClaimedLineDisplay3&&) noexcept = default; IClaimedLineDisplay3& operator=(IClaimedLineDisplay3 const&) & noexcept = default; IClaimedLineDisplay3& operator=(IClaimedLineDisplay3&&) & noexcept = default; }; struct __declspec(empty_bases) IClaimedLineDisplayClosedEventArgs : winrt::Windows::Foundation::IInspectable, impl::consume_t<IClaimedLineDisplayClosedEventArgs> { IClaimedLineDisplayClosedEventArgs(std::nullptr_t = nullptr) noexcept {} IClaimedLineDisplayClosedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IClaimedLineDisplayClosedEventArgs(IClaimedLineDisplayClosedEventArgs const&) noexcept = default; IClaimedLineDisplayClosedEventArgs(IClaimedLineDisplayClosedEventArgs&&) noexcept = default; IClaimedLineDisplayClosedEventArgs& operator=(IClaimedLineDisplayClosedEventArgs const&) & noexcept = default; IClaimedLineDisplayClosedEventArgs& operator=(IClaimedLineDisplayClosedEventArgs&&) & noexcept = default; }; struct __declspec(empty_bases) IClaimedLineDisplayStatics : winrt::Windows::Foundation::IInspectable, impl::consume_t<IClaimedLineDisplayStatics> { IClaimedLineDisplayStatics(std::nullptr_t = nullptr) noexcept {} IClaimedLineDisplayStatics(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IClaimedLineDisplayStatics(IClaimedLineDisplayStatics const&) noexcept = default; IClaimedLineDisplayStatics(IClaimedLineDisplayStatics&&) noexcept = default; IClaimedLineDisplayStatics& operator=(IClaimedLineDisplayStatics const&) & noexcept = default; IClaimedLineDisplayStatics& operator=(IClaimedLineDisplayStatics&&) & noexcept = default; }; struct __declspec(empty_bases) IClaimedMagneticStripeReader : winrt::Windows::Foundation::IInspectable, impl::consume_t<IClaimedMagneticStripeReader> { IClaimedMagneticStripeReader(std::nullptr_t = nullptr) noexcept {} IClaimedMagneticStripeReader(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IClaimedMagneticStripeReader(IClaimedMagneticStripeReader const&) noexcept = default; IClaimedMagneticStripeReader(IClaimedMagneticStripeReader&&) noexcept = default; IClaimedMagneticStripeReader& operator=(IClaimedMagneticStripeReader const&) & noexcept = default; IClaimedMagneticStripeReader& operator=(IClaimedMagneticStripeReader&&) & noexcept = default; }; struct __declspec(empty_bases) IClaimedMagneticStripeReader2 : winrt::Windows::Foundation::IInspectable, impl::consume_t<IClaimedMagneticStripeReader2> { IClaimedMagneticStripeReader2(std::nullptr_t = nullptr) noexcept {} IClaimedMagneticStripeReader2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IClaimedMagneticStripeReader2(IClaimedMagneticStripeReader2 const&) noexcept = default; IClaimedMagneticStripeReader2(IClaimedMagneticStripeReader2&&) noexcept = default; IClaimedMagneticStripeReader2& operator=(IClaimedMagneticStripeReader2 const&) & noexcept = default; IClaimedMagneticStripeReader2& operator=(IClaimedMagneticStripeReader2&&) & noexcept = default; }; struct __declspec(empty_bases) IClaimedMagneticStripeReaderClosedEventArgs : winrt::Windows::Foundation::IInspectable, impl::consume_t<IClaimedMagneticStripeReaderClosedEventArgs> { IClaimedMagneticStripeReaderClosedEventArgs(std::nullptr_t = nullptr) noexcept {} IClaimedMagneticStripeReaderClosedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IClaimedMagneticStripeReaderClosedEventArgs(IClaimedMagneticStripeReaderClosedEventArgs const&) noexcept = default; IClaimedMagneticStripeReaderClosedEventArgs(IClaimedMagneticStripeReaderClosedEventArgs&&) noexcept = default; IClaimedMagneticStripeReaderClosedEventArgs& operator=(IClaimedMagneticStripeReaderClosedEventArgs const&) & noexcept = default; IClaimedMagneticStripeReaderClosedEventArgs& operator=(IClaimedMagneticStripeReaderClosedEventArgs&&) & noexcept = default; }; struct __declspec(empty_bases) IClaimedPosPrinter : winrt::Windows::Foundation::IInspectable, impl::consume_t<IClaimedPosPrinter> { IClaimedPosPrinter(std::nullptr_t = nullptr) noexcept {} IClaimedPosPrinter(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IClaimedPosPrinter(IClaimedPosPrinter const&) noexcept = default; IClaimedPosPrinter(IClaimedPosPrinter&&) noexcept = default; IClaimedPosPrinter& operator=(IClaimedPosPrinter const&) & noexcept = default; IClaimedPosPrinter& operator=(IClaimedPosPrinter&&) & noexcept = default; }; struct __declspec(empty_bases) IClaimedPosPrinter2 : winrt::Windows::Foundation::IInspectable, impl::consume_t<IClaimedPosPrinter2> { IClaimedPosPrinter2(std::nullptr_t = nullptr) noexcept {} IClaimedPosPrinter2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IClaimedPosPrinter2(IClaimedPosPrinter2 const&) noexcept = default; IClaimedPosPrinter2(IClaimedPosPrinter2&&) noexcept = default; IClaimedPosPrinter2& operator=(IClaimedPosPrinter2 const&) & noexcept = default; IClaimedPosPrinter2& operator=(IClaimedPosPrinter2&&) & noexcept = default; }; struct __declspec(empty_bases) IClaimedPosPrinterClosedEventArgs : winrt::Windows::Foundation::IInspectable, impl::consume_t<IClaimedPosPrinterClosedEventArgs> { IClaimedPosPrinterClosedEventArgs(std::nullptr_t = nullptr) noexcept {} IClaimedPosPrinterClosedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IClaimedPosPrinterClosedEventArgs(IClaimedPosPrinterClosedEventArgs const&) noexcept = default; IClaimedPosPrinterClosedEventArgs(IClaimedPosPrinterClosedEventArgs&&) noexcept = default; IClaimedPosPrinterClosedEventArgs& operator=(IClaimedPosPrinterClosedEventArgs const&) & noexcept = default; IClaimedPosPrinterClosedEventArgs& operator=(IClaimedPosPrinterClosedEventArgs&&) & noexcept = default; }; struct __declspec(empty_bases) IClaimedReceiptPrinter : winrt::Windows::Foundation::IInspectable, impl::consume_t<IClaimedReceiptPrinter> { IClaimedReceiptPrinter(std::nullptr_t = nullptr) noexcept {} IClaimedReceiptPrinter(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IClaimedReceiptPrinter(IClaimedReceiptPrinter const&) noexcept = default; IClaimedReceiptPrinter(IClaimedReceiptPrinter&&) noexcept = default; IClaimedReceiptPrinter& operator=(IClaimedReceiptPrinter const&) & noexcept = default; IClaimedReceiptPrinter& operator=(IClaimedReceiptPrinter&&) & noexcept = default; }; struct __declspec(empty_bases) IClaimedSlipPrinter : winrt::Windows::Foundation::IInspectable, impl::consume_t<IClaimedSlipPrinter> { IClaimedSlipPrinter(std::nullptr_t = nullptr) noexcept {} IClaimedSlipPrinter(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IClaimedSlipPrinter(IClaimedSlipPrinter const&) noexcept = default; IClaimedSlipPrinter(IClaimedSlipPrinter&&) noexcept = default; IClaimedSlipPrinter& operator=(IClaimedSlipPrinter const&) & noexcept = default; IClaimedSlipPrinter& operator=(IClaimedSlipPrinter&&) & noexcept = default; }; struct __declspec(empty_bases) ICommonClaimedPosPrinterStation : winrt::Windows::Foundation::IInspectable, impl::consume_t<ICommonClaimedPosPrinterStation> { ICommonClaimedPosPrinterStation(std::nullptr_t = nullptr) noexcept {} ICommonClaimedPosPrinterStation(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ICommonClaimedPosPrinterStation(ICommonClaimedPosPrinterStation const&) noexcept = default; ICommonClaimedPosPrinterStation(ICommonClaimedPosPrinterStation&&) noexcept = default; ICommonClaimedPosPrinterStation& operator=(ICommonClaimedPosPrinterStation const&) & noexcept = default; ICommonClaimedPosPrinterStation& operator=(ICommonClaimedPosPrinterStation&&) & noexcept = default; }; struct __declspec(empty_bases) ICommonPosPrintStationCapabilities : winrt::Windows::Foundation::IInspectable, impl::consume_t<ICommonPosPrintStationCapabilities> { ICommonPosPrintStationCapabilities(std::nullptr_t = nullptr) noexcept {} ICommonPosPrintStationCapabilities(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ICommonPosPrintStationCapabilities(ICommonPosPrintStationCapabilities const&) noexcept = default; ICommonPosPrintStationCapabilities(ICommonPosPrintStationCapabilities&&) noexcept = default; ICommonPosPrintStationCapabilities& operator=(ICommonPosPrintStationCapabilities const&) & noexcept = default; ICommonPosPrintStationCapabilities& operator=(ICommonPosPrintStationCapabilities&&) & noexcept = default; }; struct __declspec(empty_bases) ICommonReceiptSlipCapabilities : winrt::Windows::Foundation::IInspectable, impl::consume_t<ICommonReceiptSlipCapabilities>, impl::require<winrt::Windows::Devices::PointOfService::ICommonReceiptSlipCapabilities, winrt::Windows::Devices::PointOfService::ICommonPosPrintStationCapabilities> { ICommonReceiptSlipCapabilities(std::nullptr_t = nullptr) noexcept {} ICommonReceiptSlipCapabilities(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ICommonReceiptSlipCapabilities(ICommonReceiptSlipCapabilities const&) noexcept = default; ICommonReceiptSlipCapabilities(ICommonReceiptSlipCapabilities&&) noexcept = default; ICommonReceiptSlipCapabilities& operator=(ICommonReceiptSlipCapabilities const&) & noexcept = default; ICommonReceiptSlipCapabilities& operator=(ICommonReceiptSlipCapabilities&&) & noexcept = default; }; struct __declspec(empty_bases) IJournalPrintJob : winrt::Windows::Foundation::IInspectable, impl::consume_t<IJournalPrintJob> { IJournalPrintJob(std::nullptr_t = nullptr) noexcept {} IJournalPrintJob(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IJournalPrintJob(IJournalPrintJob const&) noexcept = default; IJournalPrintJob(IJournalPrintJob&&) noexcept = default; IJournalPrintJob& operator=(IJournalPrintJob const&) & noexcept = default; IJournalPrintJob& operator=(IJournalPrintJob&&) & noexcept = default; }; struct __declspec(empty_bases) IJournalPrinterCapabilities : winrt::Windows::Foundation::IInspectable, impl::consume_t<IJournalPrinterCapabilities> { IJournalPrinterCapabilities(std::nullptr_t = nullptr) noexcept {} IJournalPrinterCapabilities(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IJournalPrinterCapabilities(IJournalPrinterCapabilities const&) noexcept = default; IJournalPrinterCapabilities(IJournalPrinterCapabilities&&) noexcept = default; IJournalPrinterCapabilities& operator=(IJournalPrinterCapabilities const&) & noexcept = default; IJournalPrinterCapabilities& operator=(IJournalPrinterCapabilities&&) & noexcept = default; }; struct __declspec(empty_bases) IJournalPrinterCapabilities2 : winrt::Windows::Foundation::IInspectable, impl::consume_t<IJournalPrinterCapabilities2> { IJournalPrinterCapabilities2(std::nullptr_t = nullptr) noexcept {} IJournalPrinterCapabilities2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IJournalPrinterCapabilities2(IJournalPrinterCapabilities2 const&) noexcept = default; IJournalPrinterCapabilities2(IJournalPrinterCapabilities2&&) noexcept = default; IJournalPrinterCapabilities2& operator=(IJournalPrinterCapabilities2 const&) & noexcept = default; IJournalPrinterCapabilities2& operator=(IJournalPrinterCapabilities2&&) & noexcept = default; }; struct __declspec(empty_bases) ILineDisplay : winrt::Windows::Foundation::IInspectable, impl::consume_t<ILineDisplay> { ILineDisplay(std::nullptr_t = nullptr) noexcept {} ILineDisplay(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ILineDisplay(ILineDisplay const&) noexcept = default; ILineDisplay(ILineDisplay&&) noexcept = default; ILineDisplay& operator=(ILineDisplay const&) & noexcept = default; ILineDisplay& operator=(ILineDisplay&&) & noexcept = default; }; struct __declspec(empty_bases) ILineDisplay2 : winrt::Windows::Foundation::IInspectable, impl::consume_t<ILineDisplay2> { ILineDisplay2(std::nullptr_t = nullptr) noexcept {} ILineDisplay2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ILineDisplay2(ILineDisplay2 const&) noexcept = default; ILineDisplay2(ILineDisplay2&&) noexcept = default; ILineDisplay2& operator=(ILineDisplay2 const&) & noexcept = default; ILineDisplay2& operator=(ILineDisplay2&&) & noexcept = default; }; struct __declspec(empty_bases) ILineDisplayAttributes : winrt::Windows::Foundation::IInspectable, impl::consume_t<ILineDisplayAttributes> { ILineDisplayAttributes(std::nullptr_t = nullptr) noexcept {} ILineDisplayAttributes(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ILineDisplayAttributes(ILineDisplayAttributes const&) noexcept = default; ILineDisplayAttributes(ILineDisplayAttributes&&) noexcept = default; ILineDisplayAttributes& operator=(ILineDisplayAttributes const&) & noexcept = default; ILineDisplayAttributes& operator=(ILineDisplayAttributes&&) & noexcept = default; }; struct __declspec(empty_bases) ILineDisplayCapabilities : winrt::Windows::Foundation::IInspectable, impl::consume_t<ILineDisplayCapabilities> { ILineDisplayCapabilities(std::nullptr_t = nullptr) noexcept {} ILineDisplayCapabilities(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ILineDisplayCapabilities(ILineDisplayCapabilities const&) noexcept = default; ILineDisplayCapabilities(ILineDisplayCapabilities&&) noexcept = default; ILineDisplayCapabilities& operator=(ILineDisplayCapabilities const&) & noexcept = default; ILineDisplayCapabilities& operator=(ILineDisplayCapabilities&&) & noexcept = default; }; struct __declspec(empty_bases) ILineDisplayCursor : winrt::Windows::Foundation::IInspectable, impl::consume_t<ILineDisplayCursor> { ILineDisplayCursor(std::nullptr_t = nullptr) noexcept {} ILineDisplayCursor(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ILineDisplayCursor(ILineDisplayCursor const&) noexcept = default; ILineDisplayCursor(ILineDisplayCursor&&) noexcept = default; ILineDisplayCursor& operator=(ILineDisplayCursor const&) & noexcept = default; ILineDisplayCursor& operator=(ILineDisplayCursor&&) & noexcept = default; }; struct __declspec(empty_bases) ILineDisplayCursorAttributes : winrt::Windows::Foundation::IInspectable, impl::consume_t<ILineDisplayCursorAttributes> { ILineDisplayCursorAttributes(std::nullptr_t = nullptr) noexcept {} ILineDisplayCursorAttributes(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ILineDisplayCursorAttributes(ILineDisplayCursorAttributes const&) noexcept = default; ILineDisplayCursorAttributes(ILineDisplayCursorAttributes&&) noexcept = default; ILineDisplayCursorAttributes& operator=(ILineDisplayCursorAttributes const&) & noexcept = default; ILineDisplayCursorAttributes& operator=(ILineDisplayCursorAttributes&&) & noexcept = default; }; struct __declspec(empty_bases) ILineDisplayCustomGlyphs : winrt::Windows::Foundation::IInspectable, impl::consume_t<ILineDisplayCustomGlyphs> { ILineDisplayCustomGlyphs(std::nullptr_t = nullptr) noexcept {} ILineDisplayCustomGlyphs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ILineDisplayCustomGlyphs(ILineDisplayCustomGlyphs const&) noexcept = default; ILineDisplayCustomGlyphs(ILineDisplayCustomGlyphs&&) noexcept = default; ILineDisplayCustomGlyphs& operator=(ILineDisplayCustomGlyphs const&) & noexcept = default; ILineDisplayCustomGlyphs& operator=(ILineDisplayCustomGlyphs&&) & noexcept = default; }; struct __declspec(empty_bases) ILineDisplayMarquee : winrt::Windows::Foundation::IInspectable, impl::consume_t<ILineDisplayMarquee> { ILineDisplayMarquee(std::nullptr_t = nullptr) noexcept {} ILineDisplayMarquee(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ILineDisplayMarquee(ILineDisplayMarquee const&) noexcept = default; ILineDisplayMarquee(ILineDisplayMarquee&&) noexcept = default; ILineDisplayMarquee& operator=(ILineDisplayMarquee const&) & noexcept = default; ILineDisplayMarquee& operator=(ILineDisplayMarquee&&) & noexcept = default; }; struct __declspec(empty_bases) ILineDisplayStatics : winrt::Windows::Foundation::IInspectable, impl::consume_t<ILineDisplayStatics> { ILineDisplayStatics(std::nullptr_t = nullptr) noexcept {} ILineDisplayStatics(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ILineDisplayStatics(ILineDisplayStatics const&) noexcept = default; ILineDisplayStatics(ILineDisplayStatics&&) noexcept = default; ILineDisplayStatics& operator=(ILineDisplayStatics const&) & noexcept = default; ILineDisplayStatics& operator=(ILineDisplayStatics&&) & noexcept = default; }; struct __declspec(empty_bases) ILineDisplayStatics2 : winrt::Windows::Foundation::IInspectable, impl::consume_t<ILineDisplayStatics2> { ILineDisplayStatics2(std::nullptr_t = nullptr) noexcept {} ILineDisplayStatics2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ILineDisplayStatics2(ILineDisplayStatics2 const&) noexcept = default; ILineDisplayStatics2(ILineDisplayStatics2&&) noexcept = default; ILineDisplayStatics2& operator=(ILineDisplayStatics2 const&) & noexcept = default; ILineDisplayStatics2& operator=(ILineDisplayStatics2&&) & noexcept = default; }; struct __declspec(empty_bases) ILineDisplayStatisticsCategorySelector : winrt::Windows::Foundation::IInspectable, impl::consume_t<ILineDisplayStatisticsCategorySelector> { ILineDisplayStatisticsCategorySelector(std::nullptr_t = nullptr) noexcept {} ILineDisplayStatisticsCategorySelector(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ILineDisplayStatisticsCategorySelector(ILineDisplayStatisticsCategorySelector const&) noexcept = default; ILineDisplayStatisticsCategorySelector(ILineDisplayStatisticsCategorySelector&&) noexcept = default; ILineDisplayStatisticsCategorySelector& operator=(ILineDisplayStatisticsCategorySelector const&) & noexcept = default; ILineDisplayStatisticsCategorySelector& operator=(ILineDisplayStatisticsCategorySelector&&) & noexcept = default; }; struct __declspec(empty_bases) ILineDisplayStatusUpdatedEventArgs : winrt::Windows::Foundation::IInspectable, impl::consume_t<ILineDisplayStatusUpdatedEventArgs> { ILineDisplayStatusUpdatedEventArgs(std::nullptr_t = nullptr) noexcept {} ILineDisplayStatusUpdatedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ILineDisplayStatusUpdatedEventArgs(ILineDisplayStatusUpdatedEventArgs const&) noexcept = default; ILineDisplayStatusUpdatedEventArgs(ILineDisplayStatusUpdatedEventArgs&&) noexcept = default; ILineDisplayStatusUpdatedEventArgs& operator=(ILineDisplayStatusUpdatedEventArgs const&) & noexcept = default; ILineDisplayStatusUpdatedEventArgs& operator=(ILineDisplayStatusUpdatedEventArgs&&) & noexcept = default; }; struct __declspec(empty_bases) ILineDisplayStoredBitmap : winrt::Windows::Foundation::IInspectable, impl::consume_t<ILineDisplayStoredBitmap> { ILineDisplayStoredBitmap(std::nullptr_t = nullptr) noexcept {} ILineDisplayStoredBitmap(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ILineDisplayStoredBitmap(ILineDisplayStoredBitmap const&) noexcept = default; ILineDisplayStoredBitmap(ILineDisplayStoredBitmap&&) noexcept = default; ILineDisplayStoredBitmap& operator=(ILineDisplayStoredBitmap const&) & noexcept = default; ILineDisplayStoredBitmap& operator=(ILineDisplayStoredBitmap&&) & noexcept = default; }; struct __declspec(empty_bases) ILineDisplayWindow : winrt::Windows::Foundation::IInspectable, impl::consume_t<ILineDisplayWindow> { ILineDisplayWindow(std::nullptr_t = nullptr) noexcept {} ILineDisplayWindow(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ILineDisplayWindow(ILineDisplayWindow const&) noexcept = default; ILineDisplayWindow(ILineDisplayWindow&&) noexcept = default; ILineDisplayWindow& operator=(ILineDisplayWindow const&) & noexcept = default; ILineDisplayWindow& operator=(ILineDisplayWindow&&) & noexcept = default; }; struct __declspec(empty_bases) ILineDisplayWindow2 : winrt::Windows::Foundation::IInspectable, impl::consume_t<ILineDisplayWindow2> { ILineDisplayWindow2(std::nullptr_t = nullptr) noexcept {} ILineDisplayWindow2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ILineDisplayWindow2(ILineDisplayWindow2 const&) noexcept = default; ILineDisplayWindow2(ILineDisplayWindow2&&) noexcept = default; ILineDisplayWindow2& operator=(ILineDisplayWindow2 const&) & noexcept = default; ILineDisplayWindow2& operator=(ILineDisplayWindow2&&) & noexcept = default; }; struct __declspec(empty_bases) IMagneticStripeReader : winrt::Windows::Foundation::IInspectable, impl::consume_t<IMagneticStripeReader> { IMagneticStripeReader(std::nullptr_t = nullptr) noexcept {} IMagneticStripeReader(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IMagneticStripeReader(IMagneticStripeReader const&) noexcept = default; IMagneticStripeReader(IMagneticStripeReader&&) noexcept = default; IMagneticStripeReader& operator=(IMagneticStripeReader const&) & noexcept = default; IMagneticStripeReader& operator=(IMagneticStripeReader&&) & noexcept = default; }; struct __declspec(empty_bases) IMagneticStripeReaderAamvaCardDataReceivedEventArgs : winrt::Windows::Foundation::IInspectable, impl::consume_t<IMagneticStripeReaderAamvaCardDataReceivedEventArgs> { IMagneticStripeReaderAamvaCardDataReceivedEventArgs(std::nullptr_t = nullptr) noexcept {} IMagneticStripeReaderAamvaCardDataReceivedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IMagneticStripeReaderAamvaCardDataReceivedEventArgs(IMagneticStripeReaderAamvaCardDataReceivedEventArgs const&) noexcept = default; IMagneticStripeReaderAamvaCardDataReceivedEventArgs(IMagneticStripeReaderAamvaCardDataReceivedEventArgs&&) noexcept = default; IMagneticStripeReaderAamvaCardDataReceivedEventArgs& operator=(IMagneticStripeReaderAamvaCardDataReceivedEventArgs const&) & noexcept = default; IMagneticStripeReaderAamvaCardDataReceivedEventArgs& operator=(IMagneticStripeReaderAamvaCardDataReceivedEventArgs&&) & noexcept = default; }; struct __declspec(empty_bases) IMagneticStripeReaderBankCardDataReceivedEventArgs : winrt::Windows::Foundation::IInspectable, impl::consume_t<IMagneticStripeReaderBankCardDataReceivedEventArgs> { IMagneticStripeReaderBankCardDataReceivedEventArgs(std::nullptr_t = nullptr) noexcept {} IMagneticStripeReaderBankCardDataReceivedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IMagneticStripeReaderBankCardDataReceivedEventArgs(IMagneticStripeReaderBankCardDataReceivedEventArgs const&) noexcept = default; IMagneticStripeReaderBankCardDataReceivedEventArgs(IMagneticStripeReaderBankCardDataReceivedEventArgs&&) noexcept = default; IMagneticStripeReaderBankCardDataReceivedEventArgs& operator=(IMagneticStripeReaderBankCardDataReceivedEventArgs const&) & noexcept = default; IMagneticStripeReaderBankCardDataReceivedEventArgs& operator=(IMagneticStripeReaderBankCardDataReceivedEventArgs&&) & noexcept = default; }; struct __declspec(empty_bases) IMagneticStripeReaderCapabilities : winrt::Windows::Foundation::IInspectable, impl::consume_t<IMagneticStripeReaderCapabilities> { IMagneticStripeReaderCapabilities(std::nullptr_t = nullptr) noexcept {} IMagneticStripeReaderCapabilities(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IMagneticStripeReaderCapabilities(IMagneticStripeReaderCapabilities const&) noexcept = default; IMagneticStripeReaderCapabilities(IMagneticStripeReaderCapabilities&&) noexcept = default; IMagneticStripeReaderCapabilities& operator=(IMagneticStripeReaderCapabilities const&) & noexcept = default; IMagneticStripeReaderCapabilities& operator=(IMagneticStripeReaderCapabilities&&) & noexcept = default; }; struct __declspec(empty_bases) IMagneticStripeReaderCardTypesStatics : winrt::Windows::Foundation::IInspectable, impl::consume_t<IMagneticStripeReaderCardTypesStatics> { IMagneticStripeReaderCardTypesStatics(std::nullptr_t = nullptr) noexcept {} IMagneticStripeReaderCardTypesStatics(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IMagneticStripeReaderCardTypesStatics(IMagneticStripeReaderCardTypesStatics const&) noexcept = default; IMagneticStripeReaderCardTypesStatics(IMagneticStripeReaderCardTypesStatics&&) noexcept = default; IMagneticStripeReaderCardTypesStatics& operator=(IMagneticStripeReaderCardTypesStatics const&) & noexcept = default; IMagneticStripeReaderCardTypesStatics& operator=(IMagneticStripeReaderCardTypesStatics&&) & noexcept = default; }; struct __declspec(empty_bases) IMagneticStripeReaderEncryptionAlgorithmsStatics : winrt::Windows::Foundation::IInspectable, impl::consume_t<IMagneticStripeReaderEncryptionAlgorithmsStatics> { IMagneticStripeReaderEncryptionAlgorithmsStatics(std::nullptr_t = nullptr) noexcept {} IMagneticStripeReaderEncryptionAlgorithmsStatics(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IMagneticStripeReaderEncryptionAlgorithmsStatics(IMagneticStripeReaderEncryptionAlgorithmsStatics const&) noexcept = default; IMagneticStripeReaderEncryptionAlgorithmsStatics(IMagneticStripeReaderEncryptionAlgorithmsStatics&&) noexcept = default; IMagneticStripeReaderEncryptionAlgorithmsStatics& operator=(IMagneticStripeReaderEncryptionAlgorithmsStatics const&) & noexcept = default; IMagneticStripeReaderEncryptionAlgorithmsStatics& operator=(IMagneticStripeReaderEncryptionAlgorithmsStatics&&) & noexcept = default; }; struct __declspec(empty_bases) IMagneticStripeReaderErrorOccurredEventArgs : winrt::Windows::Foundation::IInspectable, impl::consume_t<IMagneticStripeReaderErrorOccurredEventArgs> { IMagneticStripeReaderErrorOccurredEventArgs(std::nullptr_t = nullptr) noexcept {} IMagneticStripeReaderErrorOccurredEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IMagneticStripeReaderErrorOccurredEventArgs(IMagneticStripeReaderErrorOccurredEventArgs const&) noexcept = default; IMagneticStripeReaderErrorOccurredEventArgs(IMagneticStripeReaderErrorOccurredEventArgs&&) noexcept = default; IMagneticStripeReaderErrorOccurredEventArgs& operator=(IMagneticStripeReaderErrorOccurredEventArgs const&) & noexcept = default; IMagneticStripeReaderErrorOccurredEventArgs& operator=(IMagneticStripeReaderErrorOccurredEventArgs&&) & noexcept = default; }; struct __declspec(empty_bases) IMagneticStripeReaderReport : winrt::Windows::Foundation::IInspectable, impl::consume_t<IMagneticStripeReaderReport> { IMagneticStripeReaderReport(std::nullptr_t = nullptr) noexcept {} IMagneticStripeReaderReport(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IMagneticStripeReaderReport(IMagneticStripeReaderReport const&) noexcept = default; IMagneticStripeReaderReport(IMagneticStripeReaderReport&&) noexcept = default; IMagneticStripeReaderReport& operator=(IMagneticStripeReaderReport const&) & noexcept = default; IMagneticStripeReaderReport& operator=(IMagneticStripeReaderReport&&) & noexcept = default; }; struct __declspec(empty_bases) IMagneticStripeReaderStatics : winrt::Windows::Foundation::IInspectable, impl::consume_t<IMagneticStripeReaderStatics> { IMagneticStripeReaderStatics(std::nullptr_t = nullptr) noexcept {} IMagneticStripeReaderStatics(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IMagneticStripeReaderStatics(IMagneticStripeReaderStatics const&) noexcept = default; IMagneticStripeReaderStatics(IMagneticStripeReaderStatics&&) noexcept = default; IMagneticStripeReaderStatics& operator=(IMagneticStripeReaderStatics const&) & noexcept = default; IMagneticStripeReaderStatics& operator=(IMagneticStripeReaderStatics&&) & noexcept = default; }; struct __declspec(empty_bases) IMagneticStripeReaderStatics2 : winrt::Windows::Foundation::IInspectable, impl::consume_t<IMagneticStripeReaderStatics2> { IMagneticStripeReaderStatics2(std::nullptr_t = nullptr) noexcept {} IMagneticStripeReaderStatics2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IMagneticStripeReaderStatics2(IMagneticStripeReaderStatics2 const&) noexcept = default; IMagneticStripeReaderStatics2(IMagneticStripeReaderStatics2&&) noexcept = default; IMagneticStripeReaderStatics2& operator=(IMagneticStripeReaderStatics2 const&) & noexcept = default; IMagneticStripeReaderStatics2& operator=(IMagneticStripeReaderStatics2&&) & noexcept = default; }; struct __declspec(empty_bases) IMagneticStripeReaderStatusUpdatedEventArgs : winrt::Windows::Foundation::IInspectable, impl::consume_t<IMagneticStripeReaderStatusUpdatedEventArgs> { IMagneticStripeReaderStatusUpdatedEventArgs(std::nullptr_t = nullptr) noexcept {} IMagneticStripeReaderStatusUpdatedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IMagneticStripeReaderStatusUpdatedEventArgs(IMagneticStripeReaderStatusUpdatedEventArgs const&) noexcept = default; IMagneticStripeReaderStatusUpdatedEventArgs(IMagneticStripeReaderStatusUpdatedEventArgs&&) noexcept = default; IMagneticStripeReaderStatusUpdatedEventArgs& operator=(IMagneticStripeReaderStatusUpdatedEventArgs const&) & noexcept = default; IMagneticStripeReaderStatusUpdatedEventArgs& operator=(IMagneticStripeReaderStatusUpdatedEventArgs&&) & noexcept = default; }; struct __declspec(empty_bases) IMagneticStripeReaderTrackData : winrt::Windows::Foundation::IInspectable, impl::consume_t<IMagneticStripeReaderTrackData> { IMagneticStripeReaderTrackData(std::nullptr_t = nullptr) noexcept {} IMagneticStripeReaderTrackData(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IMagneticStripeReaderTrackData(IMagneticStripeReaderTrackData const&) noexcept = default; IMagneticStripeReaderTrackData(IMagneticStripeReaderTrackData&&) noexcept = default; IMagneticStripeReaderTrackData& operator=(IMagneticStripeReaderTrackData const&) & noexcept = default; IMagneticStripeReaderTrackData& operator=(IMagneticStripeReaderTrackData&&) & noexcept = default; }; struct __declspec(empty_bases) IMagneticStripeReaderVendorSpecificCardDataReceivedEventArgs : winrt::Windows::Foundation::IInspectable, impl::consume_t<IMagneticStripeReaderVendorSpecificCardDataReceivedEventArgs> { IMagneticStripeReaderVendorSpecificCardDataReceivedEventArgs(std::nullptr_t = nullptr) noexcept {} IMagneticStripeReaderVendorSpecificCardDataReceivedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IMagneticStripeReaderVendorSpecificCardDataReceivedEventArgs(IMagneticStripeReaderVendorSpecificCardDataReceivedEventArgs const&) noexcept = default; IMagneticStripeReaderVendorSpecificCardDataReceivedEventArgs(IMagneticStripeReaderVendorSpecificCardDataReceivedEventArgs&&) noexcept = default; IMagneticStripeReaderVendorSpecificCardDataReceivedEventArgs& operator=(IMagneticStripeReaderVendorSpecificCardDataReceivedEventArgs const&) & noexcept = default; IMagneticStripeReaderVendorSpecificCardDataReceivedEventArgs& operator=(IMagneticStripeReaderVendorSpecificCardDataReceivedEventArgs&&) & noexcept = default; }; struct __declspec(empty_bases) IPosPrinter : winrt::Windows::Foundation::IInspectable, impl::consume_t<IPosPrinter> { IPosPrinter(std::nullptr_t = nullptr) noexcept {} IPosPrinter(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IPosPrinter(IPosPrinter const&) noexcept = default; IPosPrinter(IPosPrinter&&) noexcept = default; IPosPrinter& operator=(IPosPrinter const&) & noexcept = default; IPosPrinter& operator=(IPosPrinter&&) & noexcept = default; }; struct __declspec(empty_bases) IPosPrinter2 : winrt::Windows::Foundation::IInspectable, impl::consume_t<IPosPrinter2> { IPosPrinter2(std::nullptr_t = nullptr) noexcept {} IPosPrinter2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IPosPrinter2(IPosPrinter2 const&) noexcept = default; IPosPrinter2(IPosPrinter2&&) noexcept = default; IPosPrinter2& operator=(IPosPrinter2 const&) & noexcept = default; IPosPrinter2& operator=(IPosPrinter2&&) & noexcept = default; }; struct __declspec(empty_bases) IPosPrinterCapabilities : winrt::Windows::Foundation::IInspectable, impl::consume_t<IPosPrinterCapabilities> { IPosPrinterCapabilities(std::nullptr_t = nullptr) noexcept {} IPosPrinterCapabilities(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IPosPrinterCapabilities(IPosPrinterCapabilities const&) noexcept = default; IPosPrinterCapabilities(IPosPrinterCapabilities&&) noexcept = default; IPosPrinterCapabilities& operator=(IPosPrinterCapabilities const&) & noexcept = default; IPosPrinterCapabilities& operator=(IPosPrinterCapabilities&&) & noexcept = default; }; struct __declspec(empty_bases) IPosPrinterCharacterSetIdsStatics : winrt::Windows::Foundation::IInspectable, impl::consume_t<IPosPrinterCharacterSetIdsStatics> { IPosPrinterCharacterSetIdsStatics(std::nullptr_t = nullptr) noexcept {} IPosPrinterCharacterSetIdsStatics(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IPosPrinterCharacterSetIdsStatics(IPosPrinterCharacterSetIdsStatics const&) noexcept = default; IPosPrinterCharacterSetIdsStatics(IPosPrinterCharacterSetIdsStatics&&) noexcept = default; IPosPrinterCharacterSetIdsStatics& operator=(IPosPrinterCharacterSetIdsStatics const&) & noexcept = default; IPosPrinterCharacterSetIdsStatics& operator=(IPosPrinterCharacterSetIdsStatics&&) & noexcept = default; }; struct __declspec(empty_bases) IPosPrinterFontProperty : winrt::Windows::Foundation::IInspectable, impl::consume_t<IPosPrinterFontProperty> { IPosPrinterFontProperty(std::nullptr_t = nullptr) noexcept {} IPosPrinterFontProperty(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IPosPrinterFontProperty(IPosPrinterFontProperty const&) noexcept = default; IPosPrinterFontProperty(IPosPrinterFontProperty&&) noexcept = default; IPosPrinterFontProperty& operator=(IPosPrinterFontProperty const&) & noexcept = default; IPosPrinterFontProperty& operator=(IPosPrinterFontProperty&&) & noexcept = default; }; struct __declspec(empty_bases) IPosPrinterJob : winrt::Windows::Foundation::IInspectable, impl::consume_t<IPosPrinterJob> { IPosPrinterJob(std::nullptr_t = nullptr) noexcept {} IPosPrinterJob(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IPosPrinterJob(IPosPrinterJob const&) noexcept = default; IPosPrinterJob(IPosPrinterJob&&) noexcept = default; IPosPrinterJob& operator=(IPosPrinterJob const&) & noexcept = default; IPosPrinterJob& operator=(IPosPrinterJob&&) & noexcept = default; }; struct __declspec(empty_bases) IPosPrinterPrintOptions : winrt::Windows::Foundation::IInspectable, impl::consume_t<IPosPrinterPrintOptions> { IPosPrinterPrintOptions(std::nullptr_t = nullptr) noexcept {} IPosPrinterPrintOptions(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IPosPrinterPrintOptions(IPosPrinterPrintOptions const&) noexcept = default; IPosPrinterPrintOptions(IPosPrinterPrintOptions&&) noexcept = default; IPosPrinterPrintOptions& operator=(IPosPrinterPrintOptions const&) & noexcept = default; IPosPrinterPrintOptions& operator=(IPosPrinterPrintOptions&&) & noexcept = default; }; struct __declspec(empty_bases) IPosPrinterReleaseDeviceRequestedEventArgs : winrt::Windows::Foundation::IInspectable, impl::consume_t<IPosPrinterReleaseDeviceRequestedEventArgs> { IPosPrinterReleaseDeviceRequestedEventArgs(std::nullptr_t = nullptr) noexcept {} IPosPrinterReleaseDeviceRequestedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IPosPrinterReleaseDeviceRequestedEventArgs(IPosPrinterReleaseDeviceRequestedEventArgs const&) noexcept = default; IPosPrinterReleaseDeviceRequestedEventArgs(IPosPrinterReleaseDeviceRequestedEventArgs&&) noexcept = default; IPosPrinterReleaseDeviceRequestedEventArgs& operator=(IPosPrinterReleaseDeviceRequestedEventArgs const&) & noexcept = default; IPosPrinterReleaseDeviceRequestedEventArgs& operator=(IPosPrinterReleaseDeviceRequestedEventArgs&&) & noexcept = default; }; struct __declspec(empty_bases) IPosPrinterStatics : winrt::Windows::Foundation::IInspectable, impl::consume_t<IPosPrinterStatics> { IPosPrinterStatics(std::nullptr_t = nullptr) noexcept {} IPosPrinterStatics(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IPosPrinterStatics(IPosPrinterStatics const&) noexcept = default; IPosPrinterStatics(IPosPrinterStatics&&) noexcept = default; IPosPrinterStatics& operator=(IPosPrinterStatics const&) & noexcept = default; IPosPrinterStatics& operator=(IPosPrinterStatics&&) & noexcept = default; }; struct __declspec(empty_bases) IPosPrinterStatics2 : winrt::Windows::Foundation::IInspectable, impl::consume_t<IPosPrinterStatics2> { IPosPrinterStatics2(std::nullptr_t = nullptr) noexcept {} IPosPrinterStatics2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IPosPrinterStatics2(IPosPrinterStatics2 const&) noexcept = default; IPosPrinterStatics2(IPosPrinterStatics2&&) noexcept = default; IPosPrinterStatics2& operator=(IPosPrinterStatics2 const&) & noexcept = default; IPosPrinterStatics2& operator=(IPosPrinterStatics2&&) & noexcept = default; }; struct __declspec(empty_bases) IPosPrinterStatus : winrt::Windows::Foundation::IInspectable, impl::consume_t<IPosPrinterStatus> { IPosPrinterStatus(std::nullptr_t = nullptr) noexcept {} IPosPrinterStatus(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IPosPrinterStatus(IPosPrinterStatus const&) noexcept = default; IPosPrinterStatus(IPosPrinterStatus&&) noexcept = default; IPosPrinterStatus& operator=(IPosPrinterStatus const&) & noexcept = default; IPosPrinterStatus& operator=(IPosPrinterStatus&&) & noexcept = default; }; struct __declspec(empty_bases) IPosPrinterStatusUpdatedEventArgs : winrt::Windows::Foundation::IInspectable, impl::consume_t<IPosPrinterStatusUpdatedEventArgs> { IPosPrinterStatusUpdatedEventArgs(std::nullptr_t = nullptr) noexcept {} IPosPrinterStatusUpdatedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IPosPrinterStatusUpdatedEventArgs(IPosPrinterStatusUpdatedEventArgs const&) noexcept = default; IPosPrinterStatusUpdatedEventArgs(IPosPrinterStatusUpdatedEventArgs&&) noexcept = default; IPosPrinterStatusUpdatedEventArgs& operator=(IPosPrinterStatusUpdatedEventArgs const&) & noexcept = default; IPosPrinterStatusUpdatedEventArgs& operator=(IPosPrinterStatusUpdatedEventArgs&&) & noexcept = default; }; struct __declspec(empty_bases) IReceiptOrSlipJob : winrt::Windows::Foundation::IInspectable, impl::consume_t<IReceiptOrSlipJob>, impl::require<winrt::Windows::Devices::PointOfService::IReceiptOrSlipJob, winrt::Windows::Devices::PointOfService::IPosPrinterJob> { IReceiptOrSlipJob(std::nullptr_t = nullptr) noexcept {} IReceiptOrSlipJob(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IReceiptOrSlipJob(IReceiptOrSlipJob const&) noexcept = default; IReceiptOrSlipJob(IReceiptOrSlipJob&&) noexcept = default; IReceiptOrSlipJob& operator=(IReceiptOrSlipJob const&) & noexcept = default; IReceiptOrSlipJob& operator=(IReceiptOrSlipJob&&) & noexcept = default; }; struct __declspec(empty_bases) IReceiptPrintJob : winrt::Windows::Foundation::IInspectable, impl::consume_t<IReceiptPrintJob> { IReceiptPrintJob(std::nullptr_t = nullptr) noexcept {} IReceiptPrintJob(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IReceiptPrintJob(IReceiptPrintJob const&) noexcept = default; IReceiptPrintJob(IReceiptPrintJob&&) noexcept = default; IReceiptPrintJob& operator=(IReceiptPrintJob const&) & noexcept = default; IReceiptPrintJob& operator=(IReceiptPrintJob&&) & noexcept = default; }; struct __declspec(empty_bases) IReceiptPrintJob2 : winrt::Windows::Foundation::IInspectable, impl::consume_t<IReceiptPrintJob2> { IReceiptPrintJob2(std::nullptr_t = nullptr) noexcept {} IReceiptPrintJob2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IReceiptPrintJob2(IReceiptPrintJob2 const&) noexcept = default; IReceiptPrintJob2(IReceiptPrintJob2&&) noexcept = default; IReceiptPrintJob2& operator=(IReceiptPrintJob2 const&) & noexcept = default; IReceiptPrintJob2& operator=(IReceiptPrintJob2&&) & noexcept = default; }; struct __declspec(empty_bases) IReceiptPrinterCapabilities : winrt::Windows::Foundation::IInspectable, impl::consume_t<IReceiptPrinterCapabilities> { IReceiptPrinterCapabilities(std::nullptr_t = nullptr) noexcept {} IReceiptPrinterCapabilities(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IReceiptPrinterCapabilities(IReceiptPrinterCapabilities const&) noexcept = default; IReceiptPrinterCapabilities(IReceiptPrinterCapabilities&&) noexcept = default; IReceiptPrinterCapabilities& operator=(IReceiptPrinterCapabilities const&) & noexcept = default; IReceiptPrinterCapabilities& operator=(IReceiptPrinterCapabilities&&) & noexcept = default; }; struct __declspec(empty_bases) IReceiptPrinterCapabilities2 : winrt::Windows::Foundation::IInspectable, impl::consume_t<IReceiptPrinterCapabilities2> { IReceiptPrinterCapabilities2(std::nullptr_t = nullptr) noexcept {} IReceiptPrinterCapabilities2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IReceiptPrinterCapabilities2(IReceiptPrinterCapabilities2 const&) noexcept = default; IReceiptPrinterCapabilities2(IReceiptPrinterCapabilities2&&) noexcept = default; IReceiptPrinterCapabilities2& operator=(IReceiptPrinterCapabilities2 const&) & noexcept = default; IReceiptPrinterCapabilities2& operator=(IReceiptPrinterCapabilities2&&) & noexcept = default; }; struct __declspec(empty_bases) ISlipPrintJob : winrt::Windows::Foundation::IInspectable, impl::consume_t<ISlipPrintJob> { ISlipPrintJob(std::nullptr_t = nullptr) noexcept {} ISlipPrintJob(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ISlipPrintJob(ISlipPrintJob const&) noexcept = default; ISlipPrintJob(ISlipPrintJob&&) noexcept = default; ISlipPrintJob& operator=(ISlipPrintJob const&) & noexcept = default; ISlipPrintJob& operator=(ISlipPrintJob&&) & noexcept = default; }; struct __declspec(empty_bases) ISlipPrinterCapabilities : winrt::Windows::Foundation::IInspectable, impl::consume_t<ISlipPrinterCapabilities> { ISlipPrinterCapabilities(std::nullptr_t = nullptr) noexcept {} ISlipPrinterCapabilities(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ISlipPrinterCapabilities(ISlipPrinterCapabilities const&) noexcept = default; ISlipPrinterCapabilities(ISlipPrinterCapabilities&&) noexcept = default; ISlipPrinterCapabilities& operator=(ISlipPrinterCapabilities const&) & noexcept = default; ISlipPrinterCapabilities& operator=(ISlipPrinterCapabilities&&) & noexcept = default; }; struct __declspec(empty_bases) ISlipPrinterCapabilities2 : winrt::Windows::Foundation::IInspectable, impl::consume_t<ISlipPrinterCapabilities2> { ISlipPrinterCapabilities2(std::nullptr_t = nullptr) noexcept {} ISlipPrinterCapabilities2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} ISlipPrinterCapabilities2(ISlipPrinterCapabilities2 const&) noexcept = default; ISlipPrinterCapabilities2(ISlipPrinterCapabilities2&&) noexcept = default; ISlipPrinterCapabilities2& operator=(ISlipPrinterCapabilities2 const&) & noexcept = default; ISlipPrinterCapabilities2& operator=(ISlipPrinterCapabilities2&&) & noexcept = default; }; struct __declspec(empty_bases) IUnifiedPosErrorData : winrt::Windows::Foundation::IInspectable, impl::consume_t<IUnifiedPosErrorData> { IUnifiedPosErrorData(std::nullptr_t = nullptr) noexcept {} IUnifiedPosErrorData(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IUnifiedPosErrorData(IUnifiedPosErrorData const&) noexcept = default; IUnifiedPosErrorData(IUnifiedPosErrorData&&) noexcept = default; IUnifiedPosErrorData& operator=(IUnifiedPosErrorData const&) & noexcept = default; IUnifiedPosErrorData& operator=(IUnifiedPosErrorData&&) & noexcept = default; }; struct __declspec(empty_bases) IUnifiedPosErrorDataFactory : winrt::Windows::Foundation::IInspectable, impl::consume_t<IUnifiedPosErrorDataFactory> { IUnifiedPosErrorDataFactory(std::nullptr_t = nullptr) noexcept {} IUnifiedPosErrorDataFactory(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IUnifiedPosErrorDataFactory(IUnifiedPosErrorDataFactory const&) noexcept = default; IUnifiedPosErrorDataFactory(IUnifiedPosErrorDataFactory&&) noexcept = default; IUnifiedPosErrorDataFactory& operator=(IUnifiedPosErrorDataFactory const&) & noexcept = default; IUnifiedPosErrorDataFactory& operator=(IUnifiedPosErrorDataFactory&&) & noexcept = default; }; } #endif
78d9c120b937e304bd3c4a8e91c54782030a5e2a
c18d6aa35ec220ee5f25755c009deeb9f0165260
/CWStarter/include/GameObjects/Objects/Physics/Door.h
4472fe1fcad82046cc9dd262820d679f49a9fc51
[]
no_license
DanBullin/ProjectDB
07d6cf67f606853b15674f453444997e3765c992
664f09dabeac1e84dab8d5f6f60eb45d849492ae
refs/heads/master
2023-04-27T23:17:11.039424
2021-05-17T09:04:53
2021-05-17T09:04:53
368,121,127
0
0
null
null
null
null
UTF-8
C++
false
false
603
h
#ifndef DOOR_H #define DOOR_H #pragma once #include "GameObjects/PhysicsObject.h" /*! \file Door.h * \brief Header file for Door * * Implementation for a Door */ /*! \class Door \brief A Door */ /*! A Door Class */ class Door : public PhysicsObject { private: bool m_updatedTexture; //!< Has the door texture been updated, used to stop updating once it has public: Door(b2World* world, const sf::Vector2f& position); //!< Constructor bool contains(const sf::Vector2f pos) override; //!< Does this object contain the point passed void update(Game* game) override; //!< Update the object }; #endif
13c8101e0af0287f47badf079571c3b371ede6a1
e85417e15441ab98a2b216d4fd2175c0881a3558
/usb/UcmTcpciCxClientSample/Alert.cpp
b63692db5c6fa780e018827ec551caac2731f631
[ "MS-PL" ]
permissive
fossabot/Windows-driver-samples
2700655759c45586ae5e7eabde7e781c394fb298
6d21d1397816ec80d4997645ecda172cbf1b55a6
refs/heads/master
2021-05-01T14:31:12.436927
2018-02-11T04:59:06
2018-02-11T04:59:06
121,086,531
0
0
null
2018-02-11T04:59:05
2018-02-11T04:59:05
null
UTF-8
C++
false
false
9,885
cpp
/*++ Module Name: Alert.c Abstract: This file contains functions that handle alerts from the port controller hardware. Environment: Kernel-mode Driver Framework --*/ #include "Driver.h" #include "alert.tmh" #ifdef ALLOC_PRAGMA #pragma alloc_text (PAGE, OnInterruptPassiveIsr) #endif BOOLEAN OnInterruptPassiveIsr( _In_ WDFINTERRUPT PortControllerInterrupt, _In_ ULONG MessageID ) /*++ Routine Description: Per the TCPCI spec, the port controller hardware will drive the Alert pin high when a hardware event occurs. This routine services such a hardware interrupt at PASSIVE_LEVEL. The routine determines if an interrupt is an alert from the port controller hardware; if so, it completes processing of the alert. Arguments: Interrupt: A handle to a framework interrupt object. MessageID: If the device is using message-signaled interrupts (MSIs), this parameter is the message number that identifies the device's hardware interrupt message. Otherwise, this value is 0. Return Value: TRUE if the function services the hardware interrupt. Otherwise, this function must return FALSE. --*/ { TRACE_FUNC_ENTRY(TRACE_ALERT); UNREFERENCED_PARAMETER(MessageID); PAGED_CODE(); NTSTATUS status; PDEVICE_CONTEXT deviceContext; ALERT_REGISTER alertRegister; BOOLEAN interruptRecognized = FALSE; int numAlertsProcessed = 0; deviceContext = DeviceGetContext(WdfInterruptGetDevice(PortControllerInterrupt)); // Process the alerts as long as there are bits set in the alert register. // Set a maximum number of alerts to process in this loop. If the hardware is messed up and we're unable // to quiesce the interrupt by writing to the alert register, then we don't want to be stuck in an // infinite loop. while (numAlertsProcessed <= MAX_ALERTS_TO_PROCESS) { status = I2CReadSynchronously(deviceContext, I2CRequestSourceAlertIsr, ALERT, &alertRegister, sizeof(alertRegister)); if (!NT_SUCCESS(status)) { goto Exit; } // If there are no bits set in the alert register, we should not service this interrupt. if (alertRegister.AsUInt16 == 0) { goto Exit; } // Since there are bits set in the alert register, we can safely assume that the // interrupt is ours to process. interruptRecognized = TRUE; ProcessAndSendAlerts(&alertRegister, deviceContext); ++numAlertsProcessed; } Exit: TRACE_FUNC_EXIT(TRACE_ALERT); return interruptRecognized; } void ProcessAndSendAlerts( _In_ PALERT_REGISTER AlertRegister, _In_ PDEVICE_CONTEXT DeviceContext ) /*++ Routine Description: Processes the set of hardware alerts that were reported and notifies UcmTcpciCx of the alerts along with the contents of relevant registers. Arguments: AlertRegister: Pointer to alert register contents. DeviceContext: Device's context space. --*/ { TRACE_FUNC_ENTRY(TRACE_ALERT); PAGED_CODE(); NTSTATUS status; size_t numAlerts = 0; UCMTCPCI_PORT_CONTROLLER_ALERT_DATA alertData; UCMTCPCI_PORT_CONTROLLER_CC_STATUS ccStatus; UCMTCPCI_PORT_CONTROLLER_POWER_STATUS powerStatus; UCMTCPCI_PORT_CONTROLLER_FAULT_STATUS faultStatus; UCMTCPCI_PORT_CONTROLLER_RECEIVE_BUFFER receiveBuffer; // UcmTcpciCx expects the information on all of the alerts firing presently. UCMTCPCI_PORT_CONTROLLER_ALERT_DATA hardwareAlerts[MAX_ALERTS]; status = STATUS_SUCCESS; if (AlertRegister->CCStatus == 1) { UCMTCPCI_PORT_CONTROLLER_ALERT_DATA_INIT(&alertData); alertData.AlertType = UcmTcpciPortControllerAlertCCStatus; // We must read the CC status register and send the contents to // UcmTcpciCx along with the CC status alert. status = I2CReadSynchronously(DeviceContext, I2CRequestSourceAlertIsr, CC_STATUS, &ccStatus, sizeof(ccStatus)); if (!NT_SUCCESS(status)) { goto Exit; } alertData.CCStatus = ccStatus; hardwareAlerts[numAlerts] = alertData; ++numAlerts; } if (AlertRegister->PowerStatus == 1) { UCMTCPCI_PORT_CONTROLLER_ALERT_DATA_INIT(&alertData); alertData.AlertType = UcmTcpciPortControllerAlertPowerStatus; // We must read the power status register and send the contents to // UcmTcpciCx along with the power status alert. status = I2CReadSynchronously(DeviceContext, I2CRequestSourceAlertIsr, POWER_STATUS, &powerStatus, sizeof(powerStatus)); if (!NT_SUCCESS(status)) { goto Exit; } alertData.PowerStatus = powerStatus; hardwareAlerts[numAlerts] = alertData; ++numAlerts; } if (AlertRegister->Fault == 1) { UCMTCPCI_PORT_CONTROLLER_ALERT_DATA_INIT(&alertData); alertData.AlertType = UcmTcpciPortControllerAlertFault; // We must read the fault status register and send the contents to // UcmTcpciCx along with the fault alert. status = I2CReadSynchronously(DeviceContext, I2CRequestSourceAlertIsr, FAULT_STATUS, &faultStatus, sizeof(faultStatus)); if (!NT_SUCCESS(status)) { goto Exit; } alertData.FaultStatus = faultStatus; hardwareAlerts[numAlerts] = alertData; ++numAlerts; // Clear FAULT_STATUS Register. // Mask reserved bit 7 in TCPCI Rev 1.0 Ver 1.0 only, see spec section 4.4.6.3 faultStatus.AsUInt8 &= 0x7F; status = I2CWriteSynchronously(DeviceContext, I2CRequestSourceAlertIsr, FAULT_STATUS, &faultStatus, sizeof(faultStatus)); if (!NT_SUCCESS(status)) { goto Exit; } } if (AlertRegister->ReceiveSOPMessageStatus == 1) { UCMTCPCI_PORT_CONTROLLER_ALERT_DATA_INIT(&alertData); alertData.AlertType = UcmTcpciPortControllerAlertReceiveSOPMessageStatus; // We must read the receive buffer register and send the contents to // UcmTcpciCx along with the receive SOP alert. status = I2CReadSynchronously(DeviceContext, I2CRequestSourceAlertIsr, RECEIVE_BUFFER, &receiveBuffer, sizeof(receiveBuffer)); if (!NT_SUCCESS(status)) { goto Exit; } alertData.ReceiveBuffer = &receiveBuffer; hardwareAlerts[numAlerts] = alertData; ++numAlerts; } // The remainder of the alert types do not require us to provide any extra // information to UcmTcpciCx. if (AlertRegister->ReceivedHardReset == 1) { UCMTCPCI_PORT_CONTROLLER_ALERT_DATA_INIT(&alertData); alertData.AlertType = UcmTcpciPortControllerAlertReceivedHardReset; hardwareAlerts[numAlerts] = alertData; ++numAlerts; } if (AlertRegister->RxBufferOverflow == 1) { UCMTCPCI_PORT_CONTROLLER_ALERT_DATA_INIT(&alertData); alertData.AlertType = UcmTcpciPortControllerAlertRxBufferOverflow; hardwareAlerts[numAlerts] = alertData; ++numAlerts; } if (AlertRegister->TransmitSOPMessageDiscarded == 1) { UCMTCPCI_PORT_CONTROLLER_ALERT_DATA_INIT(&alertData); alertData.AlertType = UcmTcpciPortControllerAlertTransmitSOPMessageDiscarded; hardwareAlerts[numAlerts] = alertData; ++numAlerts; } if (AlertRegister->TransmitSOPMessageFailed == 1) { UCMTCPCI_PORT_CONTROLLER_ALERT_DATA_INIT(&alertData); alertData.AlertType = UcmTcpciPortControllerAlertTransmitSOPMessageFailed; hardwareAlerts[numAlerts] = alertData; ++numAlerts; } if (AlertRegister->TransmitSOPMessageSuccessful == 1) { UCMTCPCI_PORT_CONTROLLER_ALERT_DATA_INIT(&alertData); alertData.AlertType = UcmTcpciPortControllerAlertTransmitSOPMessageSuccessful; hardwareAlerts[numAlerts] = alertData; ++numAlerts; } if (AlertRegister->VbusSinkDisconnectDetected == 1) { UCMTCPCI_PORT_CONTROLLER_ALERT_DATA_INIT(&alertData); alertData.AlertType = UcmTcpciPortControllerAlertVbusSinkDisconnectDetected; hardwareAlerts[numAlerts] = alertData; ++numAlerts; } if (AlertRegister->VbusVoltageAlarmHi == 1) { UCMTCPCI_PORT_CONTROLLER_ALERT_DATA_INIT(&alertData); alertData.AlertType = UcmTcpciPortControllerAlertVbusVoltageAlarmHi; hardwareAlerts[numAlerts] = alertData; ++numAlerts; } if (AlertRegister->VbusVoltageAlarmLo == 1) { UCMTCPCI_PORT_CONTROLLER_ALERT_DATA_INIT(&alertData); alertData.AlertType = UcmTcpciPortControllerAlertVbusVoltageAlarmLo; hardwareAlerts[numAlerts] = alertData; ++numAlerts; } // Only write back non-reserved bits see spec section 4.4.2 // TCPCI Rev 1.0 Ver 1.0: 0x0FFF // TCPCI Rev 1.0 Ver 1.1: 0x8FFF AlertRegister->AsUInt16 &= 0x0FFF; // Quiesce the interrupt by writing back the alert register. // Per TCPCI spec 4.4.2, the alert is cleared by writing a 1 back to the bit position it is to clear. status = I2CWriteSynchronously(DeviceContext, I2CRequestSourceAlertIsr, ALERT, AlertRegister, sizeof(*AlertRegister)); if (!NT_SUCCESS(status)) { goto Exit; } Exit: if (NT_SUCCESS(status)) { // Send the list of hardware alerts to UcmTcpciCx. UcmTcpciPortControllerAlert(DeviceContext->PortController, hardwareAlerts, numAlerts); } TRACE_FUNC_EXIT(TRACE_ALERT); }
d239001a25bcacc035e04bbb8e5cdbc100ebfc3f
460c7a645508c2569ca4e78fb4f11120e7dd9c6d
/Submission Challenge/AtCoder/146C.cpp
2c46f7a602965ddec208dda54155d104f2000be2
[]
no_license
EddyHu71/Fundamental-Repository
6d883e79df991169513717aab1f06e09eef8e685
fc7f9b6b484ca9708ba6001af7f29635480839c0
refs/heads/master
2021-06-24T08:50:00.825321
2021-04-07T07:33:01
2021-04-07T07:33:01
218,901,078
0
0
null
null
null
null
UTF-8
C++
false
false
542
cpp
#include "bits/stdc++.h" #define hhh printf("hhh\n") #define see(x) (cerr<<(#x)<<'='<<(x)<<endl) using namespace std; typedef long long ll; typedef pair<int,int> pr; inline int read() {int x=0,f=1;char c=getchar();while(c!='-'&&(c<'0'||c>'9'))c=getchar();if(c=='-')f=-1,c=getchar();while(c>='0'&&c<='9')x=x*10+c-'0',c=getchar();return f*x;} const int maxn = 3e5+7; const int inf = 0x3f3f3f3f; const int mod = 1e9+7; ll gcd(ll a, ll b) { return !b?a:gcd(b,a%b); } int main() { ll a, b; cin>>a>>b; cout<<a*b/gcd(a,b)<<endl; }
e3e615684a9291b713ca76ecbfda7919b48ea446
8e9b71e4aa7eda13524c5a8b0ff4b1bb89885e5d
/MuonAnalysis/MuonAssociators/plugins/L1MuonMatcher.cc
9a84ae7b5572e1e1f670ff2884dc5871a50ba745
[]
no_license
lecriste/CMSSW_forZ4430
d3ae8099af7c7addec221101bbcf7997a4e69626
eac636b2302f63b76b49e386a7c6fd9baae62b2e
refs/heads/master
2020-03-13T07:49:20.709410
2018-04-27T16:36:05
2018-04-27T16:36:05
131,032,214
0
0
null
null
null
null
UTF-8
C++
false
false
7,539
cc
// // $Id: L1MuonMatcher.cc,v 1.3 2010/07/12 20:56:11 gpetrucc Exp $ // /** \class pat::L1MuonMatcher L1MuonMatcher.h "MuonAnalysis/MuonAssociators/interface/L1MuonMatcher.h" \brief Matcher of reconstructed objects to L1 Muons \author Giovanni Petrucciani \version $Id: L1MuonMatcher.cc,v 1.3 2010/07/12 20:56:11 gpetrucc Exp $ */ #include "FWCore/Framework/interface/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Utilities/interface/InputTag.h" #include "DataFormats/Math/interface/deltaR.h" #include "DataFormats/Math/interface/deltaPhi.h" #include "DataFormats/Common/interface/Association.h" #include "DataFormats/Common/interface/ValueMap.h" #include "DataFormats/Common/interface/Ptr.h" #include "DataFormats/Common/interface/View.h" #include "MuonAnalysis/MuonAssociators/interface/L1MuonMatcherAlgo.h" #include "DataFormats/PatCandidates/interface/TriggerObjectStandAlone.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" namespace pat { class L1MuonMatcher : public edm::EDProducer { public: explicit L1MuonMatcher(const edm::ParameterSet & iConfig); virtual ~L1MuonMatcher() { } virtual void produce(edm::Event & iEvent, const edm::EventSetup & iSetup); virtual void beginRun(edm::Run & iRun, const edm::EventSetup & iSetup); private: typedef pat::TriggerObjectStandAlone PATPrimitive; typedef pat::TriggerObjectStandAloneCollection PATPrimitiveCollection; typedef pat::TriggerObjectStandAloneMatch PATTriggerAssociation; L1MuonMatcherAlgo matcher_; /// Labels for input collections edm::InputTag reco_, l1_; /// Labels to set as filter names in the output std::string labelL1_, labelProp_; /// Write out additional info as ValueMaps bool writeExtraInfo_; /// Store extra information in a ValueMap template<typename Hand, typename T> void storeExtraInfo(edm::Event &iEvent, const Hand & handle, const std::vector<T> & values, const std::string & label) const ; }; } // namespace pat::L1MuonMatcher::L1MuonMatcher(const edm::ParameterSet & iConfig) : matcher_(iConfig), reco_(iConfig.getParameter<edm::InputTag>("src")), l1_(iConfig.getParameter<edm::InputTag>("matched")), labelL1_(iConfig.getParameter<std::string>( "setL1Label")), labelProp_(iConfig.getParameter<std::string>("setPropLabel")), writeExtraInfo_(iConfig.getParameter<bool>("writeExtraInfo")) { produces<PATPrimitiveCollection>("l1muons"); // l1 in PAT format produces<PATPrimitiveCollection>("propagatedReco"); // reco to muon station 2 produces<PATTriggerAssociation>("propagatedReco"); // asso reco to propagated reco produces<PATTriggerAssociation>(); // asso reco to l1 if (writeExtraInfo_) { produces<edm::ValueMap<float> >("deltaR"); produces<edm::ValueMap<float> >("deltaPhi"); produces<edm::ValueMap<int> >("quality"); produces<edm::ValueMap<int> >("bx"); produces<edm::ValueMap<int> >("isolated"); produces<edm::ValueMap<reco::CandidatePtr> >(); produces<edm::ValueMap<reco::CandidatePtr> >("l1ToReco"); } } void pat::L1MuonMatcher::produce(edm::Event & iEvent, const edm::EventSetup & iSetup) { using namespace edm; using namespace std; Handle<View<reco::Candidate> > reco; Handle<vector<l1extra::L1MuonParticle> > l1s; iEvent.getByLabel(reco_, reco); iEvent.getByLabel(l1_, l1s); auto_ptr<PATPrimitiveCollection> propOut(new PATPrimitiveCollection()); auto_ptr<PATPrimitiveCollection> l1Out(new PATPrimitiveCollection()); std::vector<edm::Ptr<reco::Candidate> > l1rawMatches(reco->size()); vector<int> isSelected(l1s->size(), -1); std::vector<edm::Ptr<reco::Candidate> > whichRecoMatch(l1s->size()); vector<int> propMatches(reco->size(), -1); vector<int> fullMatches(reco->size(), -1); vector<float> deltaRs(reco->size(), 999), deltaPhis(reco->size(), 999); vector<int> quality(reco->size(), 0), bx(reco->size(), -999), isolated(reco->size(), -999); for (int i = 0, n = reco->size(); i < n; ++i) { TrajectoryStateOnSurface propagated; const reco::Candidate &mu = (*reco)[i]; int match = matcher_.match(mu, *l1s, deltaRs[i], deltaPhis[i], propagated); if (propagated.isValid()) { GlobalPoint pos = propagated.globalPosition(); propMatches[i] = propOut->size(); propOut->push_back(PATPrimitive(math::PtEtaPhiMLorentzVector(mu.pt(), pos.eta(), pos.phi(), mu.mass()))); propOut->back().addFilterLabel(labelProp_); propOut->back().setCharge(mu.charge()); } if (match != -1) { const l1extra::L1MuonParticle & l1 = (*l1s)[match]; whichRecoMatch[match] = reco->ptrAt(i); if (isSelected[match] == -1) { // copy to output if needed isSelected[match] = l1Out->size(); l1Out->push_back(PATPrimitive(l1.polarP4())); l1Out->back().addFilterLabel(labelL1_); l1Out->back().setCharge(l1.charge()); } fullMatches[i] = isSelected[match]; // index in the output collection const L1MuGMTCand & gmt = l1.gmtMuonCand(); quality[i] = gmt.quality(); bx[i] = gmt.bx(); isolated[i] = gmt.isol(); l1rawMatches[i] = edm::Ptr<reco::Candidate>(l1s, size_t(match)); } } OrphanHandle<PATPrimitiveCollection> l1Done = iEvent.put(l1Out, "l1muons"); OrphanHandle<PATPrimitiveCollection> propDone = iEvent.put(propOut, "propagatedReco"); auto_ptr<PATTriggerAssociation> propAss(new PATTriggerAssociation(propDone)); PATTriggerAssociation::Filler propFiller(*propAss); propFiller.insert(reco, propMatches.begin(), propMatches.end()); propFiller.fill(); iEvent.put(propAss, "propagatedReco"); auto_ptr<PATTriggerAssociation> fullAss(new PATTriggerAssociation( l1Done)); PATTriggerAssociation::Filler fullFiller(*fullAss); fullFiller.insert(reco, fullMatches.begin(), fullMatches.end()); fullFiller.fill(); iEvent.put(fullAss); if (writeExtraInfo_) { storeExtraInfo(iEvent, reco, deltaRs, "deltaR"); storeExtraInfo(iEvent, reco, deltaPhis, "deltaPhi"); storeExtraInfo(iEvent, reco, bx, "bx"); storeExtraInfo(iEvent, reco, isolated, "isolated"); storeExtraInfo(iEvent, reco, quality, "quality"); storeExtraInfo(iEvent, reco, l1rawMatches, ""); storeExtraInfo(iEvent, l1s, whichRecoMatch, "l1ToReco"); } } template<typename Hand, typename T> void pat::L1MuonMatcher::storeExtraInfo(edm::Event &iEvent, const Hand & handle, const std::vector<T> & values, const std::string & label) const { using namespace edm; using namespace std; auto_ptr<ValueMap<T> > valMap(new ValueMap<T>()); typename edm::ValueMap<T>::Filler filler(*valMap); filler.insert(handle, values.begin(), values.end()); filler.fill(); iEvent.put(valMap, label); } void pat::L1MuonMatcher::beginRun(edm::Run & iRun, const edm::EventSetup & iSetup) { matcher_.init(iSetup); } #include "FWCore/Framework/interface/MakerMacros.h" using namespace pat; DEFINE_FWK_MODULE(L1MuonMatcher);
42c25ba51a8836362875642fb9b02f84408e02bd
b4d8262d1bc518f3766fa954c4c14e726cefb3db
/leetcode/editor/cn/[剑指 Offer 15]二进制中1的个数.cpp
6943374ee1dae4139365b2ccb23532624a2cd632
[]
no_license
YimiYimi/LeetCode1
562c1d35870a9e477b3b2a651e91bad3bec5609c
cb8fa0e49ef30d5c8287fa6a56fa551415b621ad
refs/heads/master
2023-06-23T13:37:23.237053
2021-07-18T12:02:23
2021-07-18T12:02:23
359,390,991
0
0
null
null
null
null
UTF-8
C++
false
false
1,518
cpp
//请实现一个函数,输入一个整数(以二进制串形式),输出该数二进制表示中 1 的个数。例如,把 9 表示成二进制是 1001,有 2 位是 1。因此,如果输入 //9,则该函数输出 2。 // // // // 示例 1: // // //输入:00000000000000000000000000001011 //输出:3 //解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。 // // // 示例 2: // // //输入:00000000000000000000000010000000 //输出:1 //解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。 // // // 示例 3: // // //输入:11111111111111111111111111111101 //输出:31 //解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。 // // // // 提示: // // // 输入必须是长度为 32 的 二进制串 。 // // // // // 注意:本题与主站 191 题相同:https://leetcode-cn.com/problems/number-of-1-bits/ // Related Topics 位运算 // 👍 117 👎 0 //leetcode submit region begin(Prohibit modification and deletion) //class Solution { //public: // int hammingWeight(uint32_t n) { // bitset<32> myBit(n); // return myBit.count(); // } //}; class Solution { public: int hammingWeight(uint32_t n) { int re = 0; while(n){ re += n&1; n >>= 1; //位运算:右移一位 } return re; } }; //leetcode submit region end(Prohibit modification and deletion)
8343de39be30fa3ced784fab6ff1839b0afc886d
a1a8b69b2a24fd86e4d260c8c5d4a039b7c06286
/build/iOS/Release/include/Fuse.NameValuePair.h
bf827abcac0ddce236555240546d93c77cc8d7f7
[]
no_license
epireve/hikr-tute
df0af11d1cfbdf6e874372b019d30ab0541c09b7
545501fba7044b4cc927baea2edec0674769e22c
refs/heads/master
2021-09-02T13:54:05.359975
2018-01-03T01:21:31
2018-01-03T01:21:31
115,536,756
0
0
null
null
null
null
UTF-8
C++
false
false
1,366
h
// This file was generated based on /usr/local/share/uno/Packages/Fuse.Common/1.4.2/NameValuePair.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.IObject.h> #include <Uno.Object.h> namespace g{namespace Fuse{struct NameValuePair;}} namespace g{ namespace Fuse{ // public sealed class NameValuePair :17 // { struct NameValuePair_type : uType { ::g::Fuse::IObject interface0; }; NameValuePair_type* NameValuePair_typeof(); void NameValuePair__FuseIObjectContainsKey_fn(NameValuePair* __this, uString* key, bool* __retval); void NameValuePair__FuseIObjectget_Item_fn(NameValuePair* __this, uString* key, uObject** __retval); void NameValuePair__FuseIObjectget_Keys_fn(NameValuePair* __this, uArray** __retval); void NameValuePair__get_Name_fn(NameValuePair* __this, uString** __retval); void NameValuePair__set_Name_fn(NameValuePair* __this, uString* value); void NameValuePair__ToString_fn(NameValuePair* __this, uString** __retval); void NameValuePair__get_Value_fn(NameValuePair* __this, uObject** __retval); void NameValuePair__set_Value_fn(NameValuePair* __this, uObject* value); struct NameValuePair : uObject { uStrong<uString*> _Name; uStrong<uObject*> _Value; uString* Name(); void Name(uString* value); uObject* Value(); void Value(uObject* value); }; // } }} // ::g::Fuse
4a948d0e2a0244fd05349b17fde8554cca0a12fa
2ed5a802568ba81d9f32ad14be3e0f691735cf27
/streaming/network/HttpHandler.hpp
8de4b76337222497b95326aea4b5bf5f578fa803
[ "Apache-2.0" ]
permissive
avenezia/SoccerStreaming
a69628e49edc4f7e8dc9292a2836b7e060f95ef6
e4d9e8670b3558be8b48e68d6a7ac49d3b42cd6f
refs/heads/master
2021-01-10T19:55:00.534782
2014-06-15T15:27:48
2014-06-15T15:27:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
883
hpp
#ifndef HTTP_HANDLER_HPP #define HTTP_HANDLER_HPP #include <string> #include <vector> namespace network { class HttpResponse; class HttpHandler { public: HttpHandler() {}; explicit HttpHandler(const std::string& hostnameUrl) {}; virtual ~HttpHandler() {}; virtual HttpResponse getRequest(const std::string& requestUri, const std::vector<std::pair<std::string, std::string>>& headerList, bool withAbsolutePath = false) = 0; virtual HttpResponse getRequest(const std::string& requestUri, const std::pair<std::string, std::string>& singleHeader, bool withAbsolutePath = false) = 0; virtual HttpResponse getRequest(const std::string& requestUri, bool withAbsolutePath = false) = 0; }; } #endif
b00d494cb7c73154cc33daabb97ef9a5940b4f6e
7d2db382e8c7da7b9775de9aa349b71e00b29d29
/source/libraries/libxmp/exempi-2.1.1/samples/source/XMPScanner.cpp
87a7cb176ff6a9253a9f5341ba167d1fb5b3e0df
[ "FSFUL", "BSD-3-Clause" ]
permissive
sergray/Uforia
5f00a2bfcc6151ea9bc41625bf3ebc1d3a098268
a55480ad8c9ef4fef27b6a6bcab18112173b0402
refs/heads/master
2020-04-29T03:30:34.505742
2017-01-08T17:13:33
2017-01-08T17:13:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
50,732
cpp
// ================================================================================================= // Copyright 2002-2007 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms // of the Adobe license agreement accompanying it. // // Adobe patent application tracking #P435, entitled 'Unique markers to simplify embedding data of // one format in a file with a different format', inventors: Sean Parent, Greg Gilley. // ================================================================================================= #if WIN32 #pragma warning ( disable : 4127 ) // conditional expression is constant #pragma warning ( disable : 4510 ) // default constructor could not be generated #pragma warning ( disable : 4610 ) // user defined constructor required #pragma warning ( disable : 4786 ) // debugger can't handle long symbol names #endif #include "XMPScanner.hpp" #include <cassert> #include <string> #include <cstdlib> #include <cstring> #if DEBUG #include <iostream> #include <iomanip> #include <fstream> #endif #ifndef UseStringPushBack // VC++ 6.x does not provide push_back for strings! #define UseStringPushBack 0 #endif using namespace std; // *** Consider Boyer-Moore style search for "<?xpacket begin=". It isn't an obvious win, the // *** additional code might be slower than scanning every character. Especially if we will // *** read every cache line anyway. // ================================================================================================= // ================================================================================================= // class PacketMachine // =================== // // This is the packet recognizer state machine. The top of the machine is FindNextPacket, this // calls the specific state components and handles transitions. The states are described by an // array of RecognizerInfo records, indexed by the RecognizerKind enumeration. Each RecognizerInfo // record has a function that does that state's work, the success and failure transition states, // and a string literal that is passed to the state function. The literal lets a common MatchChar // or MatchString function be used in several places. // // The state functions are responsible for consuming input to recognize their particular state. // This includes intervening nulls for 16 and 32 bit character forms. For the simplicity, things // are treated as essentially little endian and the nulls are not actually checked. The opening // '<' is found with a byte-by-byte search, then the number of bytes per character is determined // by counting the following nulls. From then on, consuming a character means incrementing the // buffer pointer by the number of bytes per character. Thus the buffer pointer only points to // the "real" bytes. This also means that the pointer can go off the end of the buffer by a // variable amount. The amount of overrun is saved so that the pointer can be positioned at the // right byte to start the next buffer. // // The state functions return a TriState value, eTriYes means the pattern was found, eTriNo means // the pattern was definitely not found, eTriMaybe means that the end of the buffer was reached // while working through the pattern. // // When eTriYes is returned, the fBufferPtr data member is left pointing to the "real" byte // following the last actual byte. Which might not be addressable memory! This also means that // a state function can be entered with nothing available in the buffer. When eTriNo is returned, // the fBufferPtr data member is left pointing to the byte that caused the failure. The state // machine starts over from the failure byte. // // The state functions must preserve their internal micro-state before returning eTriMaybe, and // resume processing when called with the next buffer. The fPosition data member is used to denote // how many actual characters have been consumed. The fNullCount data member is used to denote how // many nulls are left before the next actual character. // ================================================================================================= // PacketMachine // ============= XMPScanner::PacketMachine::PacketMachine ( XMP_Int64 bufferOffset, const void * bufferOrigin, XMP_Int64 bufferLength ) : // Public members fPacketStart ( 0 ), fPacketLength ( 0 ), fBytesAttr ( -1 ), fCharForm ( eChar8Bit ), fAccess ( ' ' ), fBogusPacket ( false ), // Private members fBufferOffset ( bufferOffset ), fBufferOrigin ( (const char *) bufferOrigin ), fBufferPtr ( fBufferOrigin ), fBufferLimit ( fBufferOrigin + bufferLength ), fRecognizer ( eLeadInRecognizer ), fPosition ( 0 ), fBytesPerChar ( 1 ), fBufferOverrun ( 0 ), fQuoteChar ( ' ' ) { /* REVIEW NOTES : Should the buffer stuff be in a class? */ assert ( bufferOrigin != NULL ); assert ( bufferLength != 0 ); } // PacketMachine // ================================================================================================= // ~PacketMachine // ============== XMPScanner::PacketMachine::~PacketMachine () { // An empty placeholder. } // ~PacketMachine // ================================================================================================= // AssociateBuffer // =============== void XMPScanner::PacketMachine::AssociateBuffer ( XMP_Int64 bufferOffset, const void * bufferOrigin, XMP_Int64 bufferLength ) { fBufferOffset = bufferOffset; fBufferOrigin = (const char *) bufferOrigin; fBufferPtr = fBufferOrigin + fBufferOverrun; fBufferLimit = fBufferOrigin + bufferLength; } // AssociateBuffer // ================================================================================================= // ResetMachine // ============ void XMPScanner::PacketMachine::ResetMachine () { fRecognizer = eLeadInRecognizer; fPosition = 0; fBufferOverrun = 0; fCharForm = eChar8Bit; fBytesPerChar = 1; fAccess = ' '; fBytesAttr = -1; fBogusPacket = false; fAttrName.erase ( fAttrName.begin(), fAttrName.end() ); fAttrValue.erase ( fAttrValue.begin(), fAttrValue.end() ); fEncodingAttr.erase ( fEncodingAttr.begin(), fEncodingAttr.end() ); } // ResetMachine // ================================================================================================= // FindLessThan // ============ XMPScanner::PacketMachine::TriState XMPScanner::PacketMachine::FindLessThan ( PacketMachine * ths, const char * which ) { if ( *which == 'H' ) { // -------------------------------------------------------------------------------- // We're looking for the '<' of the header. If we fail there is no packet in this // part of the input, so return eTriNo. ths->fCharForm = eChar8Bit; // We might have just failed from a bogus 16 or 32 bit case. ths->fBytesPerChar = 1; while ( ths->fBufferPtr < ths->fBufferLimit ) { // Don't skip nulls for the header's '<'! if ( *ths->fBufferPtr == '<' ) break; ths->fBufferPtr++; } if ( ths->fBufferPtr >= ths->fBufferLimit ) return eTriNo; ths->fBufferPtr++; return eTriYes; } else { // -------------------------------------------------------------------------------- // We're looking for the '<' of the trailer. We're already inside the packet body, // looking for the trailer. So here if we fail we must return eTriMaybe so that we // keep looking for the trailer in the next buffer. const int bytesPerChar = ths->fBytesPerChar; while ( ths->fBufferPtr < ths->fBufferLimit ) { if ( *ths->fBufferPtr == '<' ) break; ths->fBufferPtr += bytesPerChar; } if ( ths->fBufferPtr >= ths->fBufferLimit ) return eTriMaybe; ths->fBufferPtr += bytesPerChar; return eTriYes; } } // FindLessThan // ================================================================================================= // MatchString // =========== XMPScanner::PacketMachine::TriState XMPScanner::PacketMachine::MatchString ( PacketMachine * ths, const char * literal ) { const int bytesPerChar = ths->fBytesPerChar; const char * litPtr = literal + ths->fPosition; const int charsToGo = strlen ( literal ) - ths->fPosition; int charsDone = 0; while ( (charsDone < charsToGo) && (ths->fBufferPtr < ths->fBufferLimit) ) { if ( *litPtr != *ths->fBufferPtr ) return eTriNo; charsDone++; litPtr++; ths->fBufferPtr += bytesPerChar; } if ( charsDone == charsToGo ) return eTriYes; ths->fPosition += charsDone; return eTriMaybe; } // MatchString // ================================================================================================= // MatchChar // ========= XMPScanner::PacketMachine::TriState XMPScanner::PacketMachine::MatchChar ( PacketMachine * ths, const char * literal ) { const int bytesPerChar = ths->fBytesPerChar; if ( ths->fBufferPtr >= ths->fBufferLimit ) return eTriMaybe; const char currChar = *ths->fBufferPtr; if ( currChar != *literal ) return eTriNo; ths->fBufferPtr += bytesPerChar; return eTriYes; } // MatchChar // ================================================================================================= // MatchOpenQuote // ============== XMPScanner::PacketMachine::TriState XMPScanner::PacketMachine::MatchOpenQuote ( PacketMachine * ths, const char * /* unused */ ) { const int bytesPerChar = ths->fBytesPerChar; if ( ths->fBufferPtr >= ths->fBufferLimit ) return eTriMaybe; const char currChar = *ths->fBufferPtr; if ( (currChar != '\'') && (currChar != '"') ) return eTriNo; ths->fQuoteChar = currChar; ths->fBufferPtr += bytesPerChar; return eTriYes; } // MatchOpenQuote // ================================================================================================= // MatchCloseQuote // =============== XMPScanner::PacketMachine::TriState XMPScanner::PacketMachine::MatchCloseQuote ( PacketMachine * ths, const char * /* unused */ ) { return MatchChar ( ths, &ths->fQuoteChar ); } // MatchCloseQuote // ================================================================================================= // CaptureAttrName // =============== XMPScanner::PacketMachine::TriState XMPScanner::PacketMachine::CaptureAttrName ( PacketMachine * ths, const char * /* unused */ ) { const int bytesPerChar = ths->fBytesPerChar; char currChar; if ( ths->fPosition == 0 ) { // Get the first character in the name. if ( ths->fBufferPtr >= ths->fBufferLimit ) return eTriMaybe; currChar = *ths->fBufferPtr; if ( ths->fAttrName.size() == 0 ) { if ( ! ( ( ('a' <= currChar) && (currChar <= 'z') ) || ( ('A' <= currChar) && (currChar <= 'Z') ) || (currChar == '_') || (currChar == ':') ) ) { return eTriNo; } } ths->fAttrName.erase ( ths->fAttrName.begin(), ths->fAttrName.end() ); #if UseStringPushBack ths->fAttrName.push_back ( currChar ); #else ths->fAttrName.insert ( ths->fAttrName.end(), currChar ); #endif ths->fBufferPtr += bytesPerChar; } while ( ths->fBufferPtr < ths->fBufferLimit ) { // Get the remainder of the name. currChar = *ths->fBufferPtr; if ( ! ( ( ('a' <= currChar) && (currChar <= 'z') ) || ( ('A' <= currChar) && (currChar <= 'Z') ) || ( ('0' <= currChar) && (currChar <= '9') ) || (currChar == '-') || (currChar == '.') || (currChar == '_') || (currChar == ':') ) ) { break; } #if UseStringPushBack ths->fAttrName.push_back ( currChar ); #else ths->fAttrName.insert ( ths->fAttrName.end(), currChar ); #endif ths->fBufferPtr += bytesPerChar; } if ( ths->fBufferPtr < ths->fBufferLimit ) return eTriYes; ths->fPosition = ths->fAttrName.size(); // The name might span into the next buffer. return eTriMaybe; } // CaptureAttrName // ================================================================================================= // CaptureAttrValue // ================ // // Recognize the equal sign and the quoted string value, capture the value along the way. XMPScanner::PacketMachine::TriState XMPScanner::PacketMachine::CaptureAttrValue ( PacketMachine * ths, const char * /* unused */ ) { const int bytesPerChar = ths->fBytesPerChar; char currChar = 0; TriState result = eTriMaybe; if ( ths->fBufferPtr >= ths->fBufferLimit ) return eTriMaybe; switch ( ths->fPosition ) { case 0 : // The name should haved ended at the '=', nulls already skipped. if ( ths->fBufferPtr >= ths->fBufferLimit ) return eTriMaybe; if ( *ths->fBufferPtr != '=' ) return eTriNo; ths->fBufferPtr += bytesPerChar; ths->fPosition = 1; // fall through OK because MatchOpenQuote will check the buffer limit and nulls ... case 1 : // Look for the open quote. result = MatchOpenQuote ( ths, NULL ); if ( result != eTriYes ) return result; ths->fPosition = 2; // fall through OK because the buffer limit and nulls are checked below ... default : // Look for the close quote, capturing the value along the way. assert ( ths->fPosition == 2 ); const char quoteChar = ths->fQuoteChar; while ( ths->fBufferPtr < ths->fBufferLimit ) { currChar = *ths->fBufferPtr; if ( currChar == quoteChar ) break; #if UseStringPushBack ths->fAttrValue.push_back ( currChar ); #else ths->fAttrValue.insert ( ths->fAttrValue.end(), currChar ); #endif ths->fBufferPtr += bytesPerChar; } if ( ths->fBufferPtr >= ths->fBufferLimit ) return eTriMaybe; assert ( currChar == quoteChar ); ths->fBufferPtr += bytesPerChar; // Advance past the closing quote. return eTriYes; } } // CaptureAttrValue // ================================================================================================= // RecordStart // =========== // // Note that this routine looks at bytes, not logical characters. It has to figure out how many // bytes per character there are so that the other recognizers can skip intervening nulls. XMPScanner::PacketMachine::TriState XMPScanner::PacketMachine::RecordStart ( PacketMachine * ths, const char * /* unused */ ) { while ( true ) { if ( ths->fBufferPtr >= ths->fBufferLimit ) return eTriMaybe; const char currByte = *ths->fBufferPtr; switch ( ths->fPosition ) { case 0 : // Record the length. assert ( ths->fCharForm == eChar8Bit ); assert ( ths->fBytesPerChar == 1 ); ths->fPacketStart = ths->fBufferOffset + ((ths->fBufferPtr - 1) - ths->fBufferOrigin); ths->fPacketLength = 0; ths->fPosition = 1; // ! OK to fall through here, we didn't consume a byte in this step. case 1 : // Look for the first null byte. if ( currByte != 0 ) return eTriYes; // No nulls found. ths->fCharForm = eChar16BitBig; // Assume 16 bit big endian for now. ths->fBytesPerChar = 2; ths->fBufferPtr++; ths->fPosition = 2; break; // ! Don't fall through, have to check for the end of the buffer between each byte. case 2 : // One null was found, look for a second. if ( currByte != 0 ) return eTriYes; // Just one null found. ths->fBufferPtr++; ths->fPosition = 3; break; case 3 : // Two nulls were found, look for a third. if ( currByte != 0 ) return eTriNo; // Just two nulls is not valid. ths->fCharForm = eChar32BitBig; // Assume 32 bit big endian for now. ths->fBytesPerChar = 4; ths->fBufferPtr++; return eTriYes; break; } } } // RecordStart // ================================================================================================= // RecognizeBOM // ============ // // Recognizing the byte order marker is a surprisingly messy thing to do. It can't be done by the // normal string matcher, there are no intervening nulls. There are 4 transitions after the opening // quote, the closing quote or one of the three encodings. For the actual BOM there are then 1 or 2 // following bytes that depend on which of the encodings we're in. Not to mention that the buffer // might end at any point. // // The intervening null count done earlier determined 8, 16, or 32 bits per character, but not the // big or little endian nature for the 16/32 bit cases. The BOM must be present for the 16 and 32 // bit cases in order to determine the endian mode. There are six possible byte sequences for the // quoted BOM string, ignoring the differences for quoting with ''' versus '"'. // // Keep in mind that for the 16 and 32 bit cases there will be nulls for the quote. In the table // below the symbol <quote> means just the one byte containing the ''' or '"'. The nulls for the // quote character are explicitly shown. // // <quote> <quote> - 1: No BOM, this must be an 8 bit case. // <quote> \xEF \xBB \xBF <quote> - 1.12-13: The 8 bit form. // // <quote> \xFE \xFF \x00 <quote> - 1.22-23: The 16 bit, big endian form // <quote> \x00 \xFF \xFE <quote> - 1.32-33: The 16 bit, little endian form. // // <quote> \x00 \x00 \xFE \xFF \x00 \x00 \x00 <quote> - 1.32.43-45.56-57: The 32 bit, big endian form. // <quote> \x00 \x00 \x00 \xFF \xFE \x00 \x00 <quote> - 1.32.43.54-57: The 32 bit, little endian form. enum { eBOM_8_1 = 0xEF, eBOM_8_2 = 0xBB, eBOM_8_3 = 0xBF, eBOM_Big_1 = 0xFE, eBOM_Big_2 = 0xFF, eBOM_Little_1 = eBOM_Big_2, eBOM_Little_2 = eBOM_Big_1 }; XMPScanner::PacketMachine::TriState XMPScanner::PacketMachine::RecognizeBOM ( PacketMachine * ths, const char * /* unused */ ) { const int bytesPerChar = ths->fBytesPerChar; while ( true ) { // Handle one character at a time, the micro-state (fPosition) changes for each. if ( ths->fBufferPtr >= ths->fBufferLimit ) return eTriMaybe; const unsigned char currChar = *ths->fBufferPtr; // ! The BOM bytes look like integers bigger than 127. switch ( ths->fPosition ) { case 0 : // Look for the opening quote. if ( (currChar != '\'') && (currChar != '"') ) return eTriNo; ths->fQuoteChar = currChar; ths->fBufferPtr++; ths->fPosition = 1; break; // ! Don't fall through, have to check for the end of the buffer between each byte. case 1 : // Look at the byte immediately following the opening quote. if ( currChar == ths->fQuoteChar ) { // Closing quote, no BOM character, must be 8 bit. if ( ths->fCharForm != eChar8Bit ) return eTriNo; ths->fBufferPtr += bytesPerChar; // Skip the nulls after the closing quote. return eTriYes; } else if ( currChar == eBOM_8_1 ) { // Start of the 8 bit form. if ( ths->fCharForm != eChar8Bit ) return eTriNo; ths->fBufferPtr++; ths->fPosition = 12; } else if ( currChar == eBOM_Big_1 ) { // Start of the 16 bit big endian form. if ( ths->fCharForm != eChar16BitBig ) return eTriNo; ths->fBufferPtr++; ths->fPosition = 22; } else if ( currChar == 0 ) { // Start of the 16 bit little endian or either 32 bit form. if ( ths->fCharForm == eChar8Bit ) return eTriNo; ths->fBufferPtr++; ths->fPosition = 32; } else { return eTriNo; } break; case 12 : // Look for the second byte of the 8 bit form. if ( currChar != eBOM_8_2 ) return eTriNo; ths->fPosition = 13; ths->fBufferPtr++; break; case 13 : // Look for the third byte of the 8 bit form. if ( currChar != eBOM_8_3 ) return eTriNo; ths->fPosition = 99; ths->fBufferPtr++; break; case 22 : // Look for the second byte of the 16 bit big endian form. if ( currChar != eBOM_Big_2 ) return eTriNo; ths->fPosition = 23; ths->fBufferPtr++; break; case 23 : // Look for the null before the closing quote of the 16 bit big endian form. if ( currChar != 0 ) return eTriNo; ths->fBufferPtr++; ths->fPosition = 99; break; case 32 : // Look at the second byte of the 16 bit little endian or either 32 bit form. if ( currChar == eBOM_Little_1 ) { ths->fPosition = 33; } else if ( currChar == 0 ) { ths->fPosition = 43; } else { return eTriNo; } ths->fBufferPtr++; break; case 33 : // Look for the third byte of the 16 bit little endian form. if ( ths->fCharForm != eChar16BitBig ) return eTriNo; // Null count before assumed big endian. if ( currChar != eBOM_Little_2 ) return eTriNo; ths->fCharForm = eChar16BitLittle; ths->fPosition = 99; ths->fBufferPtr++; break; case 43 : // Look at the third byte of either 32 bit form. if ( ths->fCharForm != eChar32BitBig ) return eTriNo; // Null count before assumed big endian. if ( currChar == eBOM_Big_1 ) { ths->fPosition = 44; } else if ( currChar == 0 ) { ths->fPosition = 54; } else { return eTriNo; } ths->fBufferPtr++; break; case 44 : // Look for the fourth byte of the 32 bit big endian form. if ( currChar != eBOM_Big_2 ) return eTriNo; ths->fPosition = 45; ths->fBufferPtr++; break; case 45 : // Look for the first null before the closing quote of the 32 bit big endian form. if ( currChar != 0 ) return eTriNo; ths->fPosition = 56; ths->fBufferPtr++; break; case 54 : // Look for the fourth byte of the 32 bit little endian form. ths->fCharForm = eChar32BitLittle; if ( currChar != eBOM_Little_1 ) return eTriNo; ths->fPosition = 55; ths->fBufferPtr++; break; case 55 : // Look for the fifth byte of the 32 bit little endian form. if ( currChar != eBOM_Little_2 ) return eTriNo; ths->fPosition = 56; ths->fBufferPtr++; break; case 56 : // Look for the next to last null before the closing quote of the 32 bit forms. if ( currChar != 0 ) return eTriNo; ths->fPosition = 57; ths->fBufferPtr++; break; case 57 : // Look for the last null before the closing quote of the 32 bit forms. if ( currChar != 0 ) return eTriNo; ths->fPosition = 99; ths->fBufferPtr++; break; default : // Look for the closing quote. assert ( ths->fPosition == 99 ); if ( currChar != ths->fQuoteChar ) return eTriNo; ths->fBufferPtr += bytesPerChar; // Skip the nulls after the closing quote. return eTriYes; break; } } } // RecognizeBOM // ================================================================================================= // RecordHeadAttr // ============== XMPScanner::PacketMachine::TriState XMPScanner::PacketMachine::RecordHeadAttr ( PacketMachine * ths, const char * /* unused */ ) { if ( ths->fAttrName == "encoding" ) { assert ( ths->fEncodingAttr.empty() ); ths->fEncodingAttr = ths->fAttrValue; } else if ( ths->fAttrName == "bytes" ) { long value = 0; int count = ths->fAttrValue.size(); int i; assert ( ths->fBytesAttr == -1 ); if ( count > 0 ) { // Allow bytes='' to be the same as no bytes attribute. for ( i = 0; i < count; i++ ) { const char currChar = ths->fAttrValue[i]; if ( ('0' <= currChar) && (currChar <= '9') ) { value = (value * 10) + (currChar - '0'); } else { ths->fBogusPacket = true; value = -1; break; } } ths->fBytesAttr = value; if ( CharFormIs16Bit ( ths->fCharForm ) ) { if ( (ths->fBytesAttr & 1) != 0 ) ths->fBogusPacket = true; } else if ( CharFormIs32Bit ( ths->fCharForm ) ) { if ( (ths->fBytesAttr & 3) != 0 ) ths->fBogusPacket = true; } } } ths->fAttrName.erase ( ths->fAttrName.begin(), ths->fAttrName.end() ); ths->fAttrValue.erase ( ths->fAttrValue.begin(), ths->fAttrValue.end() ); return eTriYes; } // RecordHeadAttr // ================================================================================================= // CaptureAccess // ============= XMPScanner::PacketMachine::TriState XMPScanner::PacketMachine::CaptureAccess ( PacketMachine * ths, const char * /* unused */ ) { const int bytesPerChar = ths->fBytesPerChar; while ( true ) { if ( ths->fBufferPtr >= ths->fBufferLimit ) return eTriMaybe; const char currChar = *ths->fBufferPtr; switch ( ths->fPosition ) { case 0 : // Look for the opening quote. if ( (currChar != '\'') && (currChar != '"') ) return eTriNo; ths->fQuoteChar = currChar; ths->fBufferPtr += bytesPerChar; ths->fPosition = 1; break; // ! Don't fall through, have to check for the end of the buffer between each byte. case 1 : // Look for the 'r' or 'w'. if ( (currChar != 'r') && (currChar != 'w') ) return eTriNo; ths->fAccess = currChar; ths->fBufferPtr += bytesPerChar; ths->fPosition = 2; break; default : // Look for the closing quote. assert ( ths->fPosition == 2 ); if ( currChar != ths->fQuoteChar ) return eTriNo; ths->fBufferPtr += bytesPerChar; return eTriYes; break; } } } // CaptureAccess // ================================================================================================= // RecordTailAttr // ============== XMPScanner::PacketMachine::TriState XMPScanner::PacketMachine::RecordTailAttr ( PacketMachine * ths, const char * /* unused */ ) { // There are no known "general" attributes for the packet trailer. ths->fAttrName.erase ( ths->fAttrName.begin(), ths->fAttrName.end() ); ths->fAttrValue.erase ( ths->fAttrValue.begin(), ths->fAttrValue.end() ); return eTriYes; } // RecordTailAttr // ================================================================================================= // CheckPacketEnd // ============== // // Check for trailing padding and record the packet length. We have trailing padding if the bytes // attribute is present and has a value greater than the current length. XMPScanner::PacketMachine::TriState XMPScanner::PacketMachine::CheckPacketEnd ( PacketMachine * ths, const char * /* unused */ ) { const int bytesPerChar = ths->fBytesPerChar; if ( ths->fPosition == 0 ) { // First call, decide if there is trailing padding. const XMP_Int64 currLen64 = (ths->fBufferOffset + (ths->fBufferPtr - ths->fBufferOrigin)) - ths->fPacketStart; if ( currLen64 > 0x7FFFFFFF ) throw std::runtime_error ( "Packet length exceeds 2GB-1" ); const XMP_Int32 currLength = (XMP_Int32)currLen64; if ( (ths->fBytesAttr != -1) && (ths->fBytesAttr != currLength) ) { if ( ths->fBytesAttr < currLength ) { ths->fBogusPacket = true; // The bytes attribute value is too small. } else { ths->fPosition = ths->fBytesAttr - currLength; if ( (ths->fPosition % ths->fBytesPerChar) != 0 ) { ths->fBogusPacket = true; // The padding is not a multiple of the character size. ths->fPosition = (ths->fPosition / ths->fBytesPerChar) * ths->fBytesPerChar; } } } } while ( ths->fPosition > 0 ) { if ( ths->fBufferPtr >= ths->fBufferLimit ) return eTriMaybe; const char currChar = *ths->fBufferPtr; if ( (currChar != ' ') && (currChar != '\t') && (currChar != '\n') && (currChar != '\r') ) { ths->fBogusPacket = true; // The padding is not whitespace. break; // Stop the packet here. } ths->fPosition -= bytesPerChar; ths->fBufferPtr += bytesPerChar; } const XMP_Int64 currLen64 = (ths->fBufferOffset + (ths->fBufferPtr - ths->fBufferOrigin)) - ths->fPacketStart; if ( currLen64 > 0x7FFFFFFF ) throw std::runtime_error ( "Packet length exceeds 2GB-1" ); ths->fPacketLength = (XMP_Int32)currLen64; return eTriYes; } // CheckPacketEnd // ================================================================================================= // CheckFinalNulls // =============== // // Do some special case processing for little endian characters. We have to make sure the presumed // nulls after the last character actually exist, i.e. that the stream does not end too soon. Note // that the prior character scanning has moved the buffer pointer to the address following the last // byte of the last character. I.e. we're already past the presumed nulls, so we can't check their // content. All we can do is verify that the stream does not end too soon. // // Doing this check is simple yet subtle. If we're still in the current buffer then the trailing // bytes obviously exist. If we're exactly at the end of the buffer then the bytes also exist. // The only question is when we're actually past this buffer, partly into the next buffer. This is // when "ths->fBufferPtr > ths->fBufferLimit" on entry. For that case we have to wait until we've // actually seen enough extra bytes of input. // // Since the normal buffer processing is already adjusting for this partial character overrun, all // that needs to be done here is wait until "ths->fBufferPtr <= ths->fBufferLimit" on entry. In // other words, if we're presently too far, ths->fBufferPtr will be adjusted by the amount of the // overflow the next time XMPScanner::Scan is called. This might still be too far, so just keep // waiting for enough data to pass by. // // Note that there is a corresponding special case for big endian characters, we must decrement the // starting offset by the number of leading nulls. But we don't do that here, we leave it to the // outer code. This is because the leading nulls might have been at the exact end of a previous // buffer, in which case we have to also decrement the length of that raw data snip. XMPScanner::PacketMachine::TriState XMPScanner::PacketMachine::CheckFinalNulls ( PacketMachine * ths, const char * /* unused */ ) { if ( (ths->fCharForm != eChar8Bit) && CharFormIsLittleEndian ( ths->fCharForm ) ) { if ( ths->fBufferPtr > ths->fBufferLimit ) return eTriMaybe; } return eTriYes; } // CheckFinalNulls // ================================================================================================= // SetNextRecognizer // ================= void XMPScanner::PacketMachine::SetNextRecognizer ( RecognizerKind nextRecognizer ) { fRecognizer = nextRecognizer; fPosition = 0; } // SetNextRecognizer // ================================================================================================= // FindNextPacket // ============== // *** When we start validating intervening nulls for 2 and 4 bytes characters, throw an exception // *** for errors. Don't return eTriNo, that might skip at an optional point. XMPScanner::PacketMachine::TriState XMPScanner::PacketMachine::FindNextPacket () { TriState status; #define kPacketHead "?xpacket begin=" #define kPacketID "W5M0MpCehiHzreSzNTczkc9d" #define kPacketTail "?xpacket end=" static const RecognizerInfo recognizerTable [eRecognizerCount] = { // ! Would be safer to assign these explicitly. // proc successNext failureNext literal { NULL, eFailureRecognizer, eFailureRecognizer, NULL}, // eFailureRecognizer { NULL, eSuccessRecognizer, eSuccessRecognizer, NULL}, // eSuccessRecognizer { FindLessThan, eHeadStartRecorder, eFailureRecognizer, "H" }, // eLeadInRecognizer { RecordStart, eHeadStartRecognizer, eLeadInRecognizer, NULL }, // eHeadStartRecorder { MatchString, eBOMRecognizer, eLeadInRecognizer, kPacketHead }, // eHeadStartRecognizer { RecognizeBOM, eIDTagRecognizer, eLeadInRecognizer, NULL }, // eBOMRecognizer { MatchString, eIDOpenRecognizer, eLeadInRecognizer, " id=" }, // eIDTagRecognizer { MatchOpenQuote, eIDValueRecognizer, eLeadInRecognizer, NULL }, // eIDOpenRecognizer { MatchString, eIDCloseRecognizer, eLeadInRecognizer, kPacketID }, // eIDValueRecognizer { MatchCloseQuote, eAttrSpaceRecognizer_1, eLeadInRecognizer, NULL }, // eIDCloseRecognizer { MatchChar, eAttrNameRecognizer_1, eHeadEndRecognizer, " " }, // eAttrSpaceRecognizer_1 { CaptureAttrName, eAttrValueRecognizer_1, eLeadInRecognizer, NULL }, // eAttrNameRecognizer_1 { CaptureAttrValue, eAttrValueRecorder_1, eLeadInRecognizer, NULL }, // eAttrValueRecognizer_1 { RecordHeadAttr, eAttrSpaceRecognizer_1, eLeadInRecognizer, NULL }, // eAttrValueRecorder_1 { MatchString, eBodyRecognizer, eLeadInRecognizer, "?>" }, // eHeadEndRecognizer { FindLessThan, eTailStartRecognizer, eBodyRecognizer, "T"}, // eBodyRecognizer { MatchString, eAccessValueRecognizer, eBodyRecognizer, kPacketTail }, // eTailStartRecognizer { CaptureAccess, eAttrSpaceRecognizer_2, eBodyRecognizer, NULL }, // eAccessValueRecognizer { MatchChar, eAttrNameRecognizer_2, eTailEndRecognizer, " " }, // eAttrSpaceRecognizer_2 { CaptureAttrName, eAttrValueRecognizer_2, eBodyRecognizer, NULL }, // eAttrNameRecognizer_2 { CaptureAttrValue, eAttrValueRecorder_2, eBodyRecognizer, NULL }, // eAttrValueRecognizer_2 { RecordTailAttr, eAttrSpaceRecognizer_2, eBodyRecognizer, NULL }, // eAttrValueRecorder_2 { MatchString, ePacketEndRecognizer, eBodyRecognizer, "?>" }, // eTailEndRecognizer { CheckPacketEnd, eCloseOutRecognizer, eBodyRecognizer, "" }, // ePacketEndRecognizer { CheckFinalNulls, eSuccessRecognizer, eBodyRecognizer, "" } // eCloseOutRecognizer }; while ( true ) { switch ( fRecognizer ) { case eFailureRecognizer : return eTriNo; case eSuccessRecognizer : return eTriYes; default : // ------------------------------------------------------------------- // For everything else, the normal cases, use the state machine table. const RecognizerInfo * thisState = &recognizerTable [fRecognizer]; status = thisState->proc ( this, thisState->literal ); switch ( status ) { case eTriNo : SetNextRecognizer ( thisState->failureNext ); continue; case eTriYes : SetNextRecognizer ( thisState->successNext ); continue; case eTriMaybe : fBufferOverrun = (unsigned char)(fBufferPtr - fBufferLimit); return eTriMaybe; // Keep this recognizer intact, to be resumed later. } } // switch ( fRecognizer ) { ... } // while ( true ) { ... } // FindNextPacket // ================================================================================================= // ================================================================================================= // class InternalSnip // ================== // ================================================================================================= // InternalSnip // ============ XMPScanner::InternalSnip::InternalSnip ( XMP_Int64 offset, XMP_Int64 length ) { fInfo.fOffset = offset; fInfo.fLength = length; } // InternalSnip // ================================================================================================= // InternalSnip // ============ XMPScanner::InternalSnip::InternalSnip ( const InternalSnip & rhs ) : fInfo ( rhs.fInfo ), fMachine ( NULL ) { assert ( rhs.fMachine.get() == NULL ); // Don't copy a snip with a machine. assert ( (rhs.fInfo.fEncodingAttr == 0) || (*rhs.fInfo.fEncodingAttr == 0) ); // Don't copy a snip with an encoding. } // InternalSnip // ================================================================================================= // ~InternalSnip // ============= XMPScanner::InternalSnip::~InternalSnip () { } // ~InternalSnip // ================================================================================================= // ================================================================================================= // class XMPScanner // ================ // ================================================================================================= // DumpSnipList // ============ #if DEBUG static const char * snipStateName [6] = { "not-seen", "pending", "raw-data", "good-packet", "partial", "bad-packet" }; void XMPScanner::DumpSnipList ( const char * title ) { InternalSnipIterator currPos = fInternalSnips.begin(); InternalSnipIterator endPos = fInternalSnips.end(); cout << endl << title << " snip list: " << fInternalSnips.size() << endl; for ( ; currPos != endPos; ++currPos ) { SnipInfo * currSnip = &currPos->fInfo; cout << '\t' << currSnip << ' ' << snipStateName[currSnip->fState] << ' ' << currSnip->fOffset << ".." << (currSnip->fOffset + currSnip->fLength - 1) << ' ' << currSnip->fLength << ' ' << endl; } } // DumpSnipList #endif // ================================================================================================= // PrevSnip and NextSnip // ===================== XMPScanner::InternalSnipIterator XMPScanner::PrevSnip ( InternalSnipIterator snipPos ) { InternalSnipIterator prev = snipPos; return --prev; } // PrevSnip XMPScanner::InternalSnipIterator XMPScanner::NextSnip ( InternalSnipIterator snipPos ) { InternalSnipIterator next = snipPos; return ++next; } // NextSnip // ================================================================================================= // XMPScanner // ========== // // Initialize the scanner object with one "not seen" snip covering the whole stream. XMPScanner::XMPScanner ( XMP_Int64 streamLength ) : fStreamLength ( streamLength ) { InternalSnip rootSnip ( 0, streamLength ); if ( streamLength > 0 ) fInternalSnips.push_front ( rootSnip ); // Be nice for empty files. // DumpSnipList ( "New XMPScanner" ); } // XMPScanner // ================================================================================================= // ~XMPScanner // =========== XMPScanner::~XMPScanner() { } // ~XMPScanner // ================================================================================================= // GetSnipCount // ============ long XMPScanner::GetSnipCount () { return fInternalSnips.size(); } // GetSnipCount // ================================================================================================= // StreamAllScanned // ================ bool XMPScanner::StreamAllScanned () { InternalSnipIterator currPos = fInternalSnips.begin(); InternalSnipIterator endPos = fInternalSnips.end(); for ( ; currPos != endPos; ++currPos ) { if ( currPos->fInfo.fState == eNotSeenSnip ) return false; } return true; } // StreamAllScanned // ================================================================================================= // SplitInternalSnip // ================= // // Split the given snip into up to 3 pieces. The new pieces are inserted before and after this one // in the snip list. The relOffset is the first byte to be kept, it is relative to this snip. If // the preceeding or following snips have the same state as this one, just shift the boundaries. // I.e. move the contents from one snip to the other, don't create a new snip. // *** To be thread safe we ought to lock the entire list during manipulation. Let data scanning // *** happen in parallel, serialize all mucking with the list. void XMPScanner::SplitInternalSnip ( InternalSnipIterator snipPos, XMP_Int64 relOffset, XMP_Int64 newLength ) { assert ( (relOffset + newLength) > relOffset ); // Check for overflow. assert ( (relOffset + newLength) <= snipPos->fInfo.fLength ); // ----------------------------------- // First deal with the low offset end. if ( relOffset > 0 ) { InternalSnipIterator prevPos; if ( snipPos != fInternalSnips.begin() ) prevPos = PrevSnip ( snipPos ); if ( (snipPos != fInternalSnips.begin()) && (snipPos->fInfo.fState == prevPos->fInfo.fState) ) { prevPos->fInfo.fLength += relOffset; // Adjust the preceeding snip. } else { InternalSnip headExcess ( snipPos->fInfo.fOffset, relOffset ); headExcess.fInfo.fState = snipPos->fInfo.fState; headExcess.fInfo.fOutOfOrder = snipPos->fInfo.fOutOfOrder; fInternalSnips.insert ( snipPos, headExcess ); // Insert the head piece before the middle piece. } snipPos->fInfo.fOffset += relOffset; // Adjust the remainder of this snip. snipPos->fInfo.fLength -= relOffset; } // ---------------------------------- // Now deal with the high offset end. if ( newLength < snipPos->fInfo.fLength ) { InternalSnipIterator nextPos = NextSnip ( snipPos ); const XMP_Int64 tailLength = snipPos->fInfo.fLength - newLength; if ( (nextPos != fInternalSnips.end()) && (snipPos->fInfo.fState == nextPos->fInfo.fState) ) { nextPos->fInfo.fOffset -= tailLength; // Adjust the following snip. nextPos->fInfo.fLength += tailLength; } else { InternalSnip tailExcess ( (snipPos->fInfo.fOffset + newLength), tailLength ); tailExcess.fInfo.fState = snipPos->fInfo.fState; tailExcess.fInfo.fOutOfOrder = snipPos->fInfo.fOutOfOrder; fInternalSnips.insert ( nextPos, tailExcess ); // Insert the tail piece after the middle piece. } snipPos->fInfo.fLength = newLength; } } // SplitInternalSnip // ================================================================================================= // MergeInternalSnips // ================== XMPScanner::InternalSnipIterator XMPScanner::MergeInternalSnips ( InternalSnipIterator firstPos, InternalSnipIterator secondPos ) { firstPos->fInfo.fLength += secondPos->fInfo.fLength; fInternalSnips.erase ( secondPos ); return firstPos; } // MergeInternalSnips // ================================================================================================= // Scan // ==== void XMPScanner::Scan ( const void * bufferOrigin, XMP_Int64 bufferOffset, XMP_Int64 bufferLength ) { XMP_Int64 relOffset; #if 0 cout << "Scan: @ " << bufferOrigin << ", " << bufferOffset << ", " << bufferLength << endl; #endif if ( bufferLength == 0 ) return; // ---------------------------------------------------------------- // These comparisons are carefully done to avoid overflow problems. if ( (bufferOffset >= fStreamLength) || (bufferLength > (fStreamLength - bufferOffset)) || (bufferOrigin == 0) ) { throw ScanError ( "Bad origin, offset, or length" ); } // ---------------------------------------------------------------------------------------------- // This buffer must be within a not-seen snip. Find it and split it. The first snip whose whose // end is beyond the buffer must be the enclosing one. // *** It would be friendly for rescans for out of order problems to accept any buffer postion. const XMP_Int64 endOffset = bufferOffset + bufferLength - 1; InternalSnipIterator snipPos = fInternalSnips.begin(); while ( endOffset > (snipPos->fInfo.fOffset + snipPos->fInfo.fLength - 1) ) ++ snipPos; if ( snipPos->fInfo.fState != eNotSeenSnip ) throw ScanError ( "Already seen" ); relOffset = bufferOffset - snipPos->fInfo.fOffset; if ( (relOffset + bufferLength) > snipPos->fInfo.fLength ) throw ScanError ( "Not within existing snip" ); SplitInternalSnip ( snipPos, relOffset, bufferLength ); // *** If sequential & prev is partial, just tack on, // -------------------------------------------------------- // Merge this snip with the preceeding snip if appropriate. // *** When out of order I/O is supported we have to do something about buffers who's predecessor is not seen. if ( snipPos->fInfo.fOffset > 0 ) { InternalSnipIterator prevPos = PrevSnip ( snipPos ); if ( prevPos->fInfo.fState == ePartialPacketSnip ) snipPos = MergeInternalSnips ( prevPos, snipPos ); } // ---------------------------------- // Look for packets within this snip. snipPos->fInfo.fState = ePendingSnip; PacketMachine* thisMachine = snipPos->fMachine.get(); // DumpSnipList ( "Before scan" ); if ( thisMachine != 0 ) { thisMachine->AssociateBuffer ( bufferOffset, bufferOrigin, bufferLength ); } else { // *** snipPos->fMachine.reset ( new PacketMachine ( bufferOffset, bufferOrigin, bufferLength ) ); VC++ lacks reset #if 0 snipPos->fMachine = auto_ptr<PacketMachine> ( new PacketMachine ( bufferOffset, bufferOrigin, bufferLength ) ); #else { // Some versions of gcc complain about the assignment operator above. This avoids the gcc bug. PacketMachine * pm = new PacketMachine ( bufferOffset, bufferOrigin, bufferLength ); auto_ptr<PacketMachine> ap ( pm ); snipPos->fMachine = ap; } #endif thisMachine = snipPos->fMachine.get(); } bool bufferDone = false; while ( ! bufferDone ) { PacketMachine::TriState foundPacket = thisMachine->FindNextPacket(); if ( foundPacket == PacketMachine::eTriNo ) { // ----------------------------------------------------------------------- // No packet, mark the snip as raw data and get rid of the packet machine. // We're done with this buffer. snipPos->fInfo.fState = eRawInputSnip; #if 0 snipPos->fMachine = auto_ptr<PacketMachine>(); // *** snipPos->fMachine.reset(); VC++ lacks reset #else { // Some versions of gcc complain about the assignment operator above. This avoids the gcc bug. auto_ptr<PacketMachine> ap ( 0 ); snipPos->fMachine = ap; } #endif bufferDone = true; } else { // --------------------------------------------------------------------------------------------- // Either a full or partial packet. First trim any excess off of the front as a raw input snip. // If this is a partial packet mark the snip and keep the packet machine to be resumed later. // We're done with this buffer, the partial packet by definition extends to the end. If this is // a complete packet first extract the additional information from the packet machine. If there // is leftover data split the snip and transfer the packet machine to the new trailing snip. if ( thisMachine->fPacketStart > snipPos->fInfo.fOffset ) { // There is data at the front of the current snip that must be trimmed. SnipState savedState = snipPos->fInfo.fState; snipPos->fInfo.fState = eRawInputSnip; // ! So it gets propagated to the trimmed front part. relOffset = thisMachine->fPacketStart - snipPos->fInfo.fOffset; SplitInternalSnip ( snipPos, relOffset, (snipPos->fInfo.fLength - relOffset) ); snipPos->fInfo.fState = savedState; } if ( foundPacket == PacketMachine::eTriMaybe ) { // We have only found a partial packet. snipPos->fInfo.fState = ePartialPacketSnip; bufferDone = true; } else { // We have found a complete packet. Extract all the info for it and split any trailing data. InternalSnipIterator packetSnip = snipPos; SnipState packetState = eValidPacketSnip; if ( thisMachine->fBogusPacket ) packetState = eBadPacketSnip; packetSnip->fInfo.fAccess = thisMachine->fAccess; packetSnip->fInfo.fCharForm = thisMachine->fCharForm; packetSnip->fInfo.fBytesAttr = thisMachine->fBytesAttr; packetSnip->fInfo.fEncodingAttr = thisMachine->fEncodingAttr.c_str(); thisMachine->fEncodingAttr.erase ( thisMachine->fEncodingAttr.begin(), thisMachine->fEncodingAttr.end() ); if ( (thisMachine->fCharForm != eChar8Bit) && CharFormIsBigEndian ( thisMachine->fCharForm ) ) { // ------------------------------------------------------------------------------ // Handle a special case for big endian characters. The packet machine works as // though things were little endian. The packet starting offset points to the // byte containing the opening '<', and the length includes presumed nulls that // follow the last "real" byte. If the characters are big endian we now have to // decrement the starting offset of the packet, and also decrement the length of // the previous snip. // // Note that we can't do this before the head trimming above in general. The // nulls might have been exactly at the end of a buffer and already in the // previous snip. We are doing this before trimming the tail from the raw snip // containing the packet. We adjust the raw snip's size because it ends with // the input buffer. We don't adjust the packet's size, it is already correct. // // The raw snip (the one before the packet) might entirely disappear. A simple // example of this is when the packet is at the start of the file. assert ( packetSnip != fInternalSnips.begin() ); // Leading nulls were trimmed! if ( packetSnip != fInternalSnips.begin() ) { // ... but let's program defensibly. InternalSnipIterator prevSnip = PrevSnip ( packetSnip ); const unsigned int nullsToAdd = ( CharFormIs16Bit ( thisMachine->fCharForm ) ? 1 : 3 ); assert ( nullsToAdd <= prevSnip->fInfo.fLength ); prevSnip->fInfo.fLength -= nullsToAdd; if ( prevSnip->fInfo.fLength == 0 ) (void) fInternalSnips.erase ( prevSnip ); packetSnip->fInfo.fOffset -= nullsToAdd; packetSnip->fInfo.fLength += nullsToAdd; thisMachine->fPacketStart -= nullsToAdd; } } if ( thisMachine->fPacketLength == snipPos->fInfo.fLength ) { // This packet ends exactly at the end of the current snip. #if 0 snipPos->fMachine = auto_ptr<PacketMachine>(); // *** snipPos->fMachine.reset(); VC++ lacks reset #else { // Some versions of gcc complain about the assignment operator above. This avoids the gcc bug. auto_ptr<PacketMachine> ap ( 0 ); snipPos->fMachine = ap; } #endif bufferDone = true; } else { // There is trailing data to split from the just found packet. SplitInternalSnip ( snipPos, 0, thisMachine->fPacketLength ); InternalSnipIterator tailPos = NextSnip ( snipPos ); tailPos->fMachine = snipPos->fMachine; // auto_ptr assignment - taking ownership thisMachine->ResetMachine (); snipPos = tailPos; } packetSnip->fInfo.fState = packetState; // Do this last to avoid messing up the tail split. // DumpSnipList ( "Found a packet" ); } } } // -------------------------------------------------------- // Merge this snip with the preceeding snip if appropriate. // *** When out of order I/O is supported we have to check the following snip too. if ( (snipPos->fInfo.fOffset > 0) && (snipPos->fInfo.fState == eRawInputSnip) ) { InternalSnipIterator prevPos = PrevSnip ( snipPos ); if ( prevPos->fInfo.fState == eRawInputSnip ) snipPos = MergeInternalSnips ( prevPos, snipPos ); } // DumpSnipList ( "After scan" ); } // Scan // ================================================================================================= // Report // ====== void XMPScanner::Report ( SnipInfoVector& snips ) { const int count = fInternalSnips.size(); InternalSnipIterator snipPos = fInternalSnips.begin(); int s; // DumpSnipList ( "Report" ); snips.erase ( snips.begin(), snips.end() ); // ! Should use snips.clear, but VC++ doesn't have it. snips.reserve ( count ); for ( s = 0; s < count; s += 1 ) { snips.push_back ( SnipInfo ( snipPos->fInfo.fState, snipPos->fInfo.fOffset, snipPos->fInfo.fLength ) ); snips[s] = snipPos->fInfo; // Pick up all of the fields. ++ snipPos; } } // Report
d012d915b14cfd602d11ef4338671821a5e8930f
e07e3f41c9774c9684c4700a9772712bf6ac3533
/app/Temp/StagingArea/Data/il2cppOutput/AssemblyU2DCSharp_UnityTest_ColliderComparer_Compa3910007866.h
c14efd578ef82130a0608da36e047afaf419b26d
[]
no_license
gdesmarais-gsn/inprocess-mobile-skill-client
0171a0d4aaed13dbbc9cca248aec646ec5020025
2499d8ab5149a306001995064852353c33208fc3
refs/heads/master
2020-12-03T09:22:52.530033
2017-06-27T22:08:38
2017-06-27T22:08:38
95,603,544
0
0
null
null
null
null
UTF-8
C++
false
false
996
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_Enum2459695545.h" #include "AssemblyU2DCSharp_UnityTest_ColliderComparer_Compa3910007866.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityTest.ColliderComparer/CompareType struct CompareType_t3910007866 { public: // System.Int32 UnityTest.ColliderComparer/CompareType::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(CompareType_t3910007866, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
fa37ee0e9c9ce669372c74a3ad933e5155bc2b61
5ce034563e2cdef0a53a893390cff71509f49a2b
/hmwk/Assignment_5/Gaddis_9thEdition_Chapter7_Problem1_LargestSmallest/main.cpp
f027fc010993a325ea9411baa32acb112d114685
[]
no_license
aohara19/Ohara-Allison-CSC5-40652
283f61b913f32f8c4b6704b31da6e706c7e7fe96
663783f794695bd3f569e3251fe68efef74fd046
refs/heads/master
2021-09-06T17:39:30.554912
2018-02-09T05:52:30
2018-02-09T05:52:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
916
cpp
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.cpp * Author: Allison Ohara * Gaddis 9th Edition Chapter 7 Problem 1 "Largest/Smallest Array Values" * Created on January 27, 2018, 4:22 PM */ #include <iostream> using namespace std; /* * */ int main(int argc, char** argv) { int numbers[10]; int highest, lowest; for(short i = 0; i<10; i++){ cout<<"Enter a number\n"; cin>>numbers[i]; } highest = lowest = numbers[0]; for (short i = 0; i<10;i++){ if(numbers[i]>highest) highest = numbers[i]; else if(numbers[i]<lowest) lowest=numbers[i]; } cout<<"The largest value inputted is "<<highest; cout<<" and the smallest value is "<<lowest<<endl; return 0; }
bb434fcd3c9afb657302e3ad51e17cebb6dcbd1f
63ecf4424740570db7c3df9cd32f8f09632915b9
/perspective_texture_mapping/rasterizer.h
2d686ec8d288ebe533682e143804ed36f460b1a1
[]
no_license
Vicfred/Computer-Graphics-Explained
186abc754c675be9e92ecbc9f08189127ccd35a9
d97abbe8ca4a9f4ca4def72e01a991997ac3ac58
refs/heads/master
2020-08-02T04:31:25.368802
2017-07-05T22:02:09
2017-07-05T22:02:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,098
h
/* Copyright (c) 2013, Mads Andreas Elvheim 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 organization nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. */ #ifndef RASTERIZER_H_GUARD #define RASTERIZER_H_GUARD #include <linealg.h> void DrawTriangle( std::vector<Vector4f>& vertexData, std::vector<Vector4f>& textureData, unsigned int* buffer, unsigned int width, unsigned int height ); void TriangleSplit( std::vector<Vector4f>& vertexData, std::vector<Vector4f>& textureData ); #endif
2423ad8184a25b19079e3a51e9e518cda47466f2
960312e5355da7bef69d9900840f519379a82bc4
/net/tools/quic/quic_scion_multipath_server_bin.cc
7797b0a80d31b6317728051fc773dfbd4d5a292d
[ "BSD-3-Clause" ]
permissive
cyrill-k/chromium
b141f8149db8c3c90b344a9a600a67eb4435018c
4b854ed486b5e7d73d4fc730ff57e495a5a70705
refs/heads/master
2023-03-10T09:04:41.510407
2019-04-24T10:38:44
2019-04-24T10:38:44
124,514,113
0
0
null
2018-08-22T07:15:12
2018-03-09T08:50:48
null
UTF-8
C++
false
false
8,236
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // A binary wrapper for QuicServer. It listens forever on --port // (default 6121) until it's killed or ctrl-cd to death. #include <iostream> #include "base/at_exit.h" #include "base/command_line.h" #include "base/logging.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "net/quic/chromium/crypto/proof_source_chromium.h" #include "net/quic/core/quic_packets.h" #include "net/quic/platform/api/quic_socket_address.h" #include "net/tools/quic/quic_http_response_cache.h" #include "net/tools/quic/quic_multipath_server.h" #include "net/quic/core/quic_multipath_configuration.h" #include "net/quic/platform/api/quic_flags.h" #include "net/quic/core/congestion_control/multipath_send_algorithm_interface.h" #include "net/quic/core/congestion_control/olia_send_algorithm.h" #include "net/quic/core/quic_bandwidth.h" #include "net/quic/core/quic_connection_manager.h" #include "net/quic/core/quic_connection.h" #include "net/quic/core/quic_connection_manager_logger.h" using net::QuicMultipathConfiguration; using net::MultipathSendAlgorithmInterface; using net::OliaSendAlgorithm; using net::QuicBandwidth; using net::QuicConnectionManager; using net::QuicConnection; using net::QuicConnectionManagerLogger; // The port the quic server will listen on. int32_t FLAGS_port = 6121; std::unique_ptr<net::ProofSource> CreateProofSource( const base::FilePath& cert_path, const base::FilePath& key_path) { std::unique_ptr<net::ProofSourceChromium> proof_source( new net::ProofSourceChromium()); CHECK(proof_source->Initialize(cert_path, key_path, base::FilePath())); return std::move(proof_source); } int main(int argc, char* argv[]) { base::AtExitManager exit_manager; base::MessageLoopForIO message_loop; base::CommandLine::Init(argc, argv); base::CommandLine* line = base::CommandLine::ForCurrentProcess(); logging::LoggingSettings settings; settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG; CHECK(logging::InitLogging(settings)); if (line->HasSwitch("h") || line->HasSwitch("help")) { const char* help_str = "Usage: quic_server [options]\n" "\n" "Options:\n" "-h, --help show this help message and exit\n" "--port=<port> specify the port to listen on\n" "--quic_response_cache_dir directory containing response data\n" " to load\n" "--certificate_file=<file> path to the certificate chain\n" "--key_file=<file> path to the pkcs8 private key\n" "--ack Ack handling method: simple, roundrobin or smallestrtt\n" "--pkt Packet scheduling method: roundrobin or smallestrtt\n" "--disable-pacing Disables pacing\n" "--logging-type simple, extensive, full\n"; std::cout << help_str; exit(0); } net::QuicHttpResponseCache response_cache; if (line->HasSwitch("quic_response_cache_dir")) { response_cache.InitializeFromDirectory( line->GetSwitchValueASCII("quic_response_cache_dir")); } if (line->HasSwitch("port")) { if (!base::StringToInt(line->GetSwitchValueASCII("port"), &FLAGS_port)) { LOG(ERROR) << "--port must be an integer\n"; return 1; } } bool disablePacing = false; if (line->HasSwitch("disable-pacing")) { disablePacing = true; } if (!line->HasSwitch("certificate_file")) { LOG(ERROR) << "missing --certificate_file"; return 1; } if (!line->HasSwitch("key_file")) { LOG(ERROR) << "missing --key_file"; return 1; } net::QuicIpAddress address = net::QuicIpAddress::Any6(); if (line->HasSwitch("host")) { address.FromString(line->GetSwitchValueASCII("host")); LOG(INFO) << "using host: " << address.ToString(); } QuicMultipathConfiguration::AckSending ackHandlingMethod = QuicMultipathConfiguration::DEFAULT_ACK_HANDLING; if (line->HasSwitch("ack")) { if (line->GetSwitchValueASCII("ack") == "simple") { ackHandlingMethod = QuicMultipathConfiguration::AckSending::SIMPLE; } else if (line->GetSwitchValueASCII("ack") == "roundrobin") { ackHandlingMethod = QuicMultipathConfiguration::AckSending::ROUNDROBIN; } else if (line->GetSwitchValueASCII("ack") == "smallestrtt") { ackHandlingMethod = QuicMultipathConfiguration::AckSending::SEND_ON_SMALLEST_RTT; } else { LOG(ERROR) << "Invalid ACK method: " << line->GetSwitchValueASCII("ack"); } } QuicMultipathConfiguration::PacketScheduling packetSchedulingMethod = QuicMultipathConfiguration::DEFAULT_PACKET_SCHEDULING; if (line->HasSwitch("pkt")) { if (line->GetSwitchValueASCII("pkt") == "roundrobin") { packetSchedulingMethod = QuicMultipathConfiguration::PacketScheduling::ROUNDROBIN; } else if (line->GetSwitchValueASCII("pkt") == "smallestrtt") { packetSchedulingMethod = QuicMultipathConfiguration::PacketScheduling::SMALLEST_RTT_FIRST; } else { LOG(ERROR) << "Invalid scheduling method: " << line->GetSwitchValueASCII("pkt"); } } QuicMultipathConfiguration mpConf = QuicMultipathConfiguration::CreateServerConfiguration( packetSchedulingMethod, ackHandlingMethod, !disablePacing); net::QuicConfig config; if(line->HasSwitch("disable-prr")) { MultipathSendAlgorithmInterface::noPrr = true; std::cerr << "disable-prr" << std::endl; } if(line->HasSwitch("enable-rate-based-sending")) { MultipathSendAlgorithmInterface::rateBasedSending = true; std::cerr << "enable-rate-based-sending" << std::endl; } if(line->HasSwitch("enable-slow-start-large-reduction")) { MultipathSendAlgorithmInterface::slowStartLargeReduction = true; std::cerr << "enable-slow-start-large-reduction" << std::endl; } if(line->HasSwitch("path-update-frequency")) { int path_frequency; if (!base::StringToInt(line->GetSwitchValueASCII("path-update-frequency"), &path_frequency)) { std::cerr << "--determine-path-frequency must be an integer\n"; return 1; } OliaSendAlgorithm::pathUpdateFrequency = path_frequency; std::cerr << "path-update-frequency=" << path_frequency << std::endl; } if(line->HasSwitch("logging-type")) { if(line->GetSwitchValueASCII("logging-type") == "simple") { QuicConnection::LOG_STATS = true; std::cerr << "enable logging simple connection stats" << std::endl; } else if(line->GetSwitchValueASCII("logging-type") == "extensive") { QuicConnectionManagerLogger::ENABLED = true; std::cerr << "enable extensive logging" << std::endl; } else if(line->GetSwitchValueASCII("logging-type") == "full") { std::cerr << "enable logging simple connection stats" << std::endl; std::cerr << "enable extensive logging" << std::endl; QuicConnection::LOG_STATS = true; QuicConnectionManagerLogger::ENABLED = true; } } /*QuicBandwidth maxBandwidth = QuicBandwidth::Zero(); if(line->HasSwitch("max-bandwidth")) { int b; if (!base::StringToInt(line->GetSwitchValueASCII("max-bandwidth"), &b)) { std::cerr << "--max-bandwidth must be an integer\n"; return 1; } maxBandwidth = QuicBandwidth::FromKBitsPerSecond(b); QuicConnectionManager::MAX_BANDWIDTH = maxBandwidth; std::cerr << "max-bandwidth=" << maxBandwidth.ToKBitsPerSecond() << "Kbps" << std::endl; }*/ net::QuicMultipathServer server( CreateProofSource(line->GetSwitchValuePath("certificate_file"), line->GetSwitchValuePath("key_file")), config, net::QuicCryptoServerConfig::ConfigOptions(), net::AllSupportedVersions(), &response_cache, mpConf); int rc = server.CreateUDPSocketAndListen( net::QuicSocketAddress(address, FLAGS_port)); //int rc = server.CreateUDPSocketAndListen( // net::QuicSocketAddress(net::QuicIpAddress::Any6(), FLAGS_port)); if (rc < 0) { return 1; } while (1) { server.WaitForEvents(); } }
b3a1f1dc1cfbaeed2e9760141b4d5bc3b194f96c
350b9cd0c7c563340f3463c60f959fc19f80d29b
/openglstudyv2/src/main/version/sencev7.cpp
25e30b85901ff29a493c5297a4e7ec1983e675af
[]
no_license
TangGSen/OpenglStudyV1
e288e057b807db8287850253b3c0806507c53c25
0eca79b4d6516b49be86bbcec98217818634bed3
refs/heads/master
2021-05-16T11:19:24.998788
2017-10-25T12:42:30
2017-10-25T12:42:30
104,992,357
0
0
null
null
null
null
UTF-8
C++
false
false
2,194
cpp
// // Created by Administrator on 2017/10/11. // #include "drawAnyS.h" #include "scence.h" #include "sen_test.h" glm::mat4 mViewMatrix; glm::mat4 mProjectionMatrix; glm::mat4 mModelMatrix; //使用封装好的来画三角形 VertexBuffer *vertexBuffer; SShader *mShader; void init() { // testCMap(); vertexBuffer = new VertexBuffer; vertexBuffer->setSize(3); vertexBuffer->setPosition(0, -0.2f, -0.2f, -0.6f); vertexBuffer->setPosition(1, 0.2f, -0.2f, -0.6f); vertexBuffer->setPosition(2, 0.0f, 0.2f, -0.6f); vertexBuffer->setNarmal(0, 0.0f, 1.0f, 0.0f); vertexBuffer->setNarmal(1, 0.0f, 1.0f, 0.0f); vertexBuffer->setNarmal(2 , 0.0f, 1.0f, 0.0f); vertexBuffer->setColor(0, 0.7f, 0.7f, 0.7f, 1.0f); vertexBuffer->setColor(1 , 0.7f, 0.7f, 0.7f, 1.0f); vertexBuffer->setColor(2 , 0.7f, 0.7f, 0.7f, 1.0f); vertexBuffer->setTexcoord(0,0.0f,0.0f); vertexBuffer->setTexcoord(1,1.0f,0.0f); vertexBuffer->setTexcoord(2,0.0f,1.0f); mShader = new SShader; mShader->init("Res/ground.vs", "Res/ground.fs"); mShader->setTexture("U_Texture","Res/testv2.bmp"); mShader->setTexture("U_Texture2","Res/test.bmp"); } void setViewPortSize(float width, float height) { /** * 1.视角 * 2.宽高比 * 3.最近看到的距离 * 4.最远看到的距离 */ mProjectionMatrix= glm::perspective(60.0f,width/height,0.1f,1000.0f); //其他两个没设置就是单位矩阵 } //绘制 使用ElementBuffer 来指定顶点顺序来绘制 void draw() { float time = getTime(); glEnable(GL_DEPTH_TEST);//启动深度测试 glClearColor(0.6f,0.0f,0.6f,1.0f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); ////这里要注意,必须先设置vbo ,后shader 才能获取attribute,否则出错 vertexBuffer->bind(); mShader->bind(glm::value_ptr(mModelMatrix), glm::value_ptr(mViewMatrix), glm::value_ptr(mProjectionMatrix)); glDrawArrays(GL_TRIANGLES, 0, 3); vertexBuffer->unBind(); //良好习惯,当绘制完毕后,将程序置为0 号程序 glUseProgram(0); float timeEnd = getTime(); LOGE("draw usetime %f",timeEnd-time); }
ba2f78fc773eff9ee26c9fa5438f7c729c9d68b5
a46d23b1c03be1edf8127db532170580ae919b22
/libmedia/unit_test/SdpCreate.cxx
cfac00c952e379867bfb261c4c52179776e8feb4
[ "BSD-2-Clause" ]
permissive
greearb/vocal-ct
0e2935aa43d6bddf1506ad904d0cf61484724438
8c99a61930cc7c4887515ade518ad01022011a4e
refs/heads/master
2023-08-19T05:26:24.583272
2023-08-12T00:08:06
2023-08-12T00:08:06
87,567,277
5
0
null
null
null
null
UTF-8
C++
false
false
3,077
cxx
/* ==================================================================== * The Vovida Software License, Version 1.0 * * Copyright (c) 2000 Vovida Networks, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "VOCAL", "Vovida Open Communication Application Library", * and "Vovida Open Communication Application Library (VOCAL)" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 4. Products derived from this software may not be called "VOCAL", nor * may "VOCAL" appear in their name, without prior written * permission of Vovida Networks, Inc. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND * NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL VOVIDA * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES * IN EXCESS OF $1,000, NOR FOR ANY 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. * * ==================================================================== * * This software consists of voluntary contributions made by Vovida * Networks, Inc. and many individuals on behalf of Vovida Networks, * Inc. For more information on Vovida Networks, Inc., please see * <http://www.vovida.org/>. * */ static const char* const SdpCreate_cxx_Version = "$Id: SdpCreate.cxx,v 1.1 2004/05/01 04:15:16 greear Exp $"; #include "MediaController.hxx" #include "Verify.hxx" #include "Sdp2Session.hxx" using namespace Vocal; using namespace Vocal::SDP; using namespace Vocal::UA; void test() { { // test a simple SipUrl MediaController::instance(10000, 10005); SdpSession sdpSession = MediaController::instance().createSession(); NetworkAddress na; test_verify(sdpSession.getConnection()->getUnicast() == Data(na.getIpName().c_str())); cerr << "SDP Created:" << sdpSession.encode().logData() << endl; } } int main() { test(); return test_return_code(1); }
[ "greear" ]
greear
934f0048f8e5890ce7e3603c0714d10965a6f3ff
04b1803adb6653ecb7cb827c4f4aa616afacf629
/third_party/android_crazy_linker/src/src/crazy_linker_proc_maps_unittest.cpp
ec5ede4aefc5247a974b352d32200f1081eb22ce
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-3-Clause", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
7,229
cpp
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "crazy_linker_proc_maps.h" #include <gtest/gtest.h> #include <limits.h> #include "crazy_linker_system_mock.h" namespace crazy { namespace { const char kProcMaps0[] = "4000b000-4000c000 r--p 00000000 00:00 0\n" "4005c000-40081000 r-xp 00000000 b3:01 141 /system/bin/mksh\n" "40082000-40083000 r--p 00025000 b3:01 141 /system/bin/mksh\n" "40083000-40084000 rw-p 00026000 b3:01 141 /system/bin/mksh\n" "40084000-40088000 rw-p 00000000 00:00 0\n" "40088000-40090000 r--s 00000000 00:0b 1704 /dev/__properties__\n" "400eb000-400ec000 r--p 00000000 00:00 0\n" "40141000-40150000 r-xp 00000000 b3:01 126 /system/bin/linker\n" "40150000-40151000 r--p 0000e000 b3:01 126 /system/bin/linker\n" "40151000-40152000 rw-p 0000f000 b3:01 126 /system/bin/linker\n" "40152000-40153000 rw-p 00000000 00:00 0\n" "40231000-40277000 r-xp 00001000 b3:01 638 /system/lib/libc.so\n" "40277000-40279000 r--p 00046000 b3:01 638 /system/lib/libc.so\n" "40279000-4027b000 rw-p 00048000 b3:01 638 /system/lib/libc.so\n" "4027b000-40289000 rw-p 00000000 00:00 0\n" "41e6b000-41e72000 rw-p 00000000 00:00 0 [heap]\n" "be91b000-be93c000 rw-p 00000000 00:00 0 [stack]\n" "ffff0000-ffff1000 r-xp 00000000 00:00 0 [vectors]\n"; class ScopedTestEnv { public: ScopedTestEnv() : sys_() { sys_.AddRegularFile("/proc/self/maps", kProcMaps0, sizeof(kProcMaps0) - 1); } ~ScopedTestEnv() {} private: SystemMock sys_; }; } // namespace TEST(ProcMaps, FindElfBinaryForAddress) { ScopedTestEnv env; char path[512]; uintptr_t load_address; EXPECT_TRUE(FindElfBinaryForAddress( reinterpret_cast<void*>(0x400694c2), &load_address, path, sizeof(path))); EXPECT_EQ(0x4005c000, load_address); EXPECT_STREQ("/system/bin/mksh", path); } TEST(ProcMaps, FindElfBinaryForAddressWithBadAddress) { ScopedTestEnv env; char path[512]; uintptr_t load_address; EXPECT_FALSE(FindElfBinaryForAddress( reinterpret_cast<void*>(0x50000000), &load_address, path, sizeof(path))); } TEST(ProcMaps, FindLoadAddressForFile) { ScopedTestEnv env; static const struct { bool success; uintptr_t address; uintptr_t offset; const char* name; } kData[] = {{true, 0x4005c000, 0, "mksh"}, {true, 0x40141000, 0, "/system/bin/linker"}, {false, 0, 0, "[heap]"}, {false, 0, 0, "bin/mksh"}, {true, 0x4005c000, 0, "/system/bin/mksh"}, {true, 0x40231000, 0x1000000, "libc.so"}, }; for (auto const& data : kData) { uintptr_t address, offset; bool success = FindLoadAddressForFile(data.name, &address, &offset); EXPECT_EQ(data.success, success) << "Checking " << data.name; if (success) { EXPECT_EQ(data.address, address) << "Checking " << data.name; EXPECT_EQ(data.offset, offset) << "Checking " << data.name; } } } TEST(ProcMaps, Entries) { ScopedTestEnv env; // "4000b000-4000c000 r--p 00000000 00:00 0\n" // "4005c000-40081000 r-xp 00000000 b3:01 141 /system/bin/mksh\n" // "40082000-40083000 r--p 00025000 b3:01 141 /system/bin/mksh\n" // "40083000-40084000 rw-p 00026000 b3:01 141 /system/bin/mksh\n" // "40084000-40088000 rw-p 00000000 00:00 0\n" // "40088000-40090000 r--s 00000000 00:0b 1704 // /dev/__properties__\n" // "400eb000-400ec000 r--p 00000000 00:00 0\n" // "40141000-40150000 r-xp 00000000 b3:01 126 /system/bin/linker\n" // "40150000-40151000 r--p 0000e000 b3:01 126 /system/bin/linker\n" // "40151000-40152000 rw-p 0000f000 b3:01 126 /system/bin/linker\n" // "40152000-40153000 rw-p 00000000 00:00 0\n" // "40231000-40277000 r-xp 00001000 b3:01 638 // /system/lib/libc.so\n" // "40277000-40279000 r--p 00046000 b3:01 638 // /system/lib/libc.so\n" // "40279000-4027b000 rw-p 00048000 b3:01 638 // /system/lib/libc.so\n" // "4027b000-40289000 rw-p 00000000 00:00 0\n" // "41e6b000-41e72000 rw-p 00000000 00:00 0 [heap]\n" // "be91b000-be93c000 rw-p 00000000 00:00 0 [stack]\n" // "ffff0000-ffff1000 r-xp 00000000 00:00 0 [vectors]\n" static const struct { size_t vma_start; size_t vma_end; int prot_flags; size_t load_offset; const char* path; } kData[] = { {0x4000b000, 0x4000c000, PROT_READ, 0, NULL}, {0x4005c000, 0x40081000, PROT_READ | PROT_EXEC, 0, "/system/bin/mksh"}, {0x40082000, 0x40083000, PROT_READ, 0x25000 * PAGE_SIZE, "/system/bin/mksh"}, {0x40083000, 0x40084000, PROT_READ | PROT_WRITE, 0x26000 * PAGE_SIZE, "/system/bin/mksh"}, {0x40084000, 0x40088000, PROT_READ | PROT_WRITE, 0, NULL}, {0x40088000, 0x40090000, PROT_READ, 0, "/dev/__properties__"}, {0x400eb000, 0x400ec000, PROT_READ, 0, NULL}, {0x40141000, 0x40150000, PROT_READ | PROT_EXEC, 0, "/system/bin/linker"}, {0x40150000, 0x40151000, PROT_READ, 0xe000 * PAGE_SIZE, "/system/bin/linker"}, {0x40151000, 0x40152000, PROT_READ | PROT_WRITE, 0xf000 * PAGE_SIZE, "/system/bin/linker"}, {0x40152000, 0x40153000, PROT_READ | PROT_WRITE, 0, NULL}, {0x40231000, 0x40277000, PROT_READ | PROT_EXEC, 0x1000 * PAGE_SIZE, "/system/lib/libc.so"}, {0x40277000, 0x40279000, PROT_READ, 0x46000 * PAGE_SIZE, "/system/lib/libc.so"}, {0x40279000, 0x4027b000, PROT_READ | PROT_WRITE, 0x48000 * PAGE_SIZE, "/system/lib/libc.so"}, {0x4027b000, 0x40289000, PROT_READ | PROT_WRITE, 0, NULL}, {0x41e6b000, 0x41e72000, PROT_READ | PROT_WRITE, 0, "[heap]"}, {0xbe91b000, 0xbe93c000, PROT_READ | PROT_WRITE, 0, "[stack]"}, {0xffff0000, 0xffff1000, PROT_READ | PROT_EXEC, 0, "[vectors]"}, }; ProcMaps self_maps; ProcMaps::Entry entry; const Vector<ProcMaps::Entry>& entries = self_maps.entries(); size_t count = 0; for (const auto& data : kData) { std::string text = "Checking entry #"; text += std::to_string(++count); text += " "; text += std::to_string(data.vma_start); text += "-"; text += std::to_string(data.vma_end); EXPECT_LT(count - 1U, entries.GetCount()) << text; const ProcMaps::Entry& entry = entries[count - 1]; EXPECT_EQ(data.vma_start, entry.vma_start) << text; EXPECT_EQ(data.vma_end, entry.vma_end) << text; EXPECT_EQ(data.prot_flags, entry.prot_flags) << text; EXPECT_EQ(data.load_offset, entry.load_offset) << text; if (!data.path) { EXPECT_FALSE(entry.path) << text; } else { EXPECT_EQ(std::string(data.path), std::string(entry.path, entry.path_len)) << text; } } EXPECT_EQ(count, entries.GetCount()); } } // namespace crazy
8babc19dc688cebdd8c4b03aa9aa17540b8240f3
8b3f9e359cadff65d8574da9b44a1408ebcade86
/third_party/IXWebSocket/ixwebsocket/IXWebSocketHandshake.cpp
8193892f444819de02d1ca264b5b0bf1dde6ed99
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
opcon/nakama-cpp
42f2e1b837620bee15792695d71d31c1a1950f4e
ba965046c27b52303bf4519f9dee046d6499bac5
refs/heads/master
2020-05-15T15:08:37.546370
2019-04-15T15:41:01
2019-04-15T15:41:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,205
cpp
/* * IXWebSocketHandshake.h * Author: Benjamin Sergeant * Copyright (c) 2019 Machine Zone, Inc. All rights reserved. */ #include "IXWebSocketHandshake.h" #include "IXSocketConnect.h" #include "IXUrlParser.h" #include "libwshandshake.hpp" #include <iostream> #include <sstream> #include <regex> #include <random> #include <algorithm> namespace ix { WebSocketHandshake::WebSocketHandshake(std::atomic<bool>& requestInitCancellation, std::shared_ptr<Socket> socket, WebSocketPerMessageDeflate& perMessageDeflate, WebSocketPerMessageDeflateOptions& perMessageDeflateOptions, std::atomic<bool>& enablePerMessageDeflate) : _requestInitCancellation(requestInitCancellation), _socket(socket), _perMessageDeflate(perMessageDeflate), _perMessageDeflateOptions(perMessageDeflateOptions), _enablePerMessageDeflate(enablePerMessageDeflate) { } std::string WebSocketHandshake::trim(const std::string& str) { std::string out(str); out.erase(std::remove(out.begin(), out.end(), ' '), out.end()); out.erase(std::remove(out.begin(), out.end(), '\r'), out.end()); out.erase(std::remove(out.begin(), out.end(), '\n'), out.end()); return out; } bool WebSocketHandshake::insensitiveStringCompare(const std::string& a, const std::string& b) { return std::equal(a.begin(), a.end(), b.begin(), b.end(), [](char a, char b) { return tolower(a) == tolower(b); }); } std::tuple<std::string, std::string, std::string> WebSocketHandshake::parseRequestLine(const std::string& line) { // Request-Line = Method SP Request-URI SP HTTP-Version CRLF std::string token; std::stringstream tokenStream(line); std::vector<std::string> tokens; // Split by ' ' while (std::getline(tokenStream, token, ' ')) { tokens.push_back(token); } std::string method; if (tokens.size() >= 1) { method = trim(tokens[0]); } std::string requestUri; if (tokens.size() >= 2) { requestUri = trim(tokens[1]); } std::string httpVersion; if (tokens.size() >= 3) { httpVersion = trim(tokens[2]); } return std::make_tuple(method, requestUri, httpVersion); } std::string WebSocketHandshake::genRandomString(const int len) { std::string alphanum = "0123456789" "ABCDEFGH" "abcdefgh"; std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<int> dist(0, (int) alphanum.size() - 1); std::string s; s.resize(len); for (int i = 0; i < len; ++i) { int x = dist(e1); s[i] = alphanum[x]; } return s; } WebSocketInitResult WebSocketHandshake::sendErrorResponse(int code, const std::string& reason) { std::stringstream ss; ss << "HTTP/1.1 "; ss << code; ss << "\r\n"; ss << reason; ss << "\r\n"; // Socket write can only be cancelled through a timeout here, not manually. static std::atomic<bool> requestInitCancellation(false); auto isCancellationRequested = makeCancellationRequestWithTimeout(1, requestInitCancellation); if (!_socket->writeBytes(ss.str(), isCancellationRequested)) { return WebSocketInitResult(false, 500, "Timed out while sending error response"); } return WebSocketInitResult(false, code, reason); } WebSocketInitResult WebSocketHandshake::clientHandshake(const std::string& url, const std::string& host, const std::string& path, int port, int timeoutSecs) { _requestInitCancellation = false; auto isCancellationRequested = makeCancellationRequestWithTimeout(timeoutSecs, _requestInitCancellation); std::string errMsg; bool success = _socket->connect(host, port, errMsg, isCancellationRequested); if (!success) { std::stringstream ss; ss << "Unable to connect to " << host << " on port " << port << ", error: " << errMsg; return WebSocketInitResult(false, 0, ss.str()); } // // Generate a random 24 bytes string which looks like it is base64 encoded // y3JJHMbDL1EzLkh9GBhXDw== // 0cb3Vd9HkbpVVumoS3Noka== // // See https://stackoverflow.com/questions/18265128/what-is-sec-websocket-key-for // std::string secWebSocketKey = genRandomString(22); secWebSocketKey += "=="; std::stringstream ss; ss << "GET " << path << " HTTP/1.1\r\n"; ss << "Host: "<< host << ":" << port << "\r\n"; ss << "Upgrade: websocket\r\n"; ss << "Connection: Upgrade\r\n"; ss << "Sec-WebSocket-Version: 13\r\n"; ss << "Sec-WebSocket-Key: " << secWebSocketKey << "\r\n"; if (_enablePerMessageDeflate) { ss << _perMessageDeflateOptions.generateHeader(); } ss << "\r\n"; if (!_socket->writeBytes(ss.str(), isCancellationRequested)) { return WebSocketInitResult(false, 0, std::string("Failed sending GET request to ") + url); } // Read HTTP status line auto lineResult = _socket->readLine(isCancellationRequested); auto lineValid = lineResult.first; auto line = lineResult.second; if (!lineValid) { return WebSocketInitResult(false, 0, std::string("Failed reading HTTP status line from ") + url); } // Validate status int status; // HTTP/1.0 is too old. if (sscanf(line.c_str(), "HTTP/1.0 %d", &status) == 1) { std::stringstream ss; ss << "Server version is HTTP/1.0. Rejecting connection to " << host << ", status: " << status << ", HTTP Status line: " << line; return WebSocketInitResult(false, status, ss.str()); } // We want an 101 HTTP status if (sscanf(line.c_str(), "HTTP/1.1 %d", &status) != 1 || status != 101) { std::stringstream ss; ss << "Got bad status connecting to " << host << ", status: " << status << ", HTTP Status line: " << line; return WebSocketInitResult(false, status, ss.str()); } auto result = parseHttpHeaders(_socket, isCancellationRequested); auto headersValid = result.first; auto headers = result.second; if (!headersValid) { return WebSocketInitResult(false, status, "Error parsing HTTP headers"); } // Check the presence of the connection field if (headers.find("connection") == headers.end()) { std::string errorMsg("Missing connection value"); return WebSocketInitResult(false, status, errorMsg); } // Check the value of the connection field // Some websocket servers (Go/Gorilla?) send lowercase values for the // connection header, so do a case insensitive comparison if (!insensitiveStringCompare(headers["connection"], "Upgrade")) { std::stringstream ss; ss << "Invalid connection value: " << headers["connection"]; return WebSocketInitResult(false, status, ss.str()); } char output[29] = {}; WebSocketHandshakeKeyGen::generate(secWebSocketKey.c_str(), output); if (std::string(output) != headers["sec-websocket-accept"]) { std::string errorMsg("Invalid Sec-WebSocket-Accept value"); return WebSocketInitResult(false, status, errorMsg); } if (_enablePerMessageDeflate) { // Parse the server response. Does it support deflate ? std::string header = headers["sec-websocket-extensions"]; WebSocketPerMessageDeflateOptions webSocketPerMessageDeflateOptions(header); // If the server does not support that extension, disable it. if (!webSocketPerMessageDeflateOptions.enabled()) { _enablePerMessageDeflate = false; } // Otherwise try to initialize the deflate engine (zlib) else if (!_perMessageDeflate.init(webSocketPerMessageDeflateOptions)) { return WebSocketInitResult( false, 0,"Failed to initialize per message deflate engine"); } } return WebSocketInitResult(true, status, "", headers, path); } WebSocketInitResult WebSocketHandshake::serverHandshake(int fd, int timeoutSecs) { _requestInitCancellation = false; // Set the socket to non blocking mode + other tweaks SocketConnect::configure(fd); auto isCancellationRequested = makeCancellationRequestWithTimeout(timeoutSecs, _requestInitCancellation); std::string remote = std::string("remote fd ") + std::to_string(fd); // Read first line auto lineResult = _socket->readLine(isCancellationRequested); auto lineValid = lineResult.first; auto line = lineResult.second; if (!lineValid) { return sendErrorResponse(400, "Error reading HTTP request line"); } // Validate request line (GET /foo HTTP/1.1\r\n) auto requestLine = parseRequestLine(line); auto method = std::get<0>(requestLine); auto uri = std::get<1>(requestLine); auto httpVersion = std::get<2>(requestLine); if (method != "GET") { return sendErrorResponse(400, "Invalid HTTP method, need GET, got " + method); } if (httpVersion != "HTTP/1.1") { return sendErrorResponse(400, "Invalid HTTP version, need HTTP/1.1, got: " + httpVersion); } // Retrieve and validate HTTP headers auto result = parseHttpHeaders(_socket, isCancellationRequested); auto headersValid = result.first; auto headers = result.second; if (!headersValid) { return sendErrorResponse(400, "Error parsing HTTP headers"); } if (headers.find("sec-websocket-key") == headers.end()) { return sendErrorResponse(400, "Missing Sec-WebSocket-Key value"); } if (headers["upgrade"] != "websocket") { return sendErrorResponse(400, "Invalid or missing Upgrade header"); } if (headers.find("sec-websocket-version") == headers.end()) { return sendErrorResponse(400, "Missing Sec-WebSocket-Version value"); } { std::stringstream ss; ss << headers["sec-websocket-version"]; int version; ss >> version; if (version != 13) { return sendErrorResponse(400, "Invalid Sec-WebSocket-Version, " "need 13, got" + ss.str()); } } char output[29] = {}; WebSocketHandshakeKeyGen::generate(headers["sec-websocket-key"].c_str(), output); std::stringstream ss; ss << "HTTP/1.1 101\r\n"; ss << "Sec-WebSocket-Accept: " << std::string(output) << "\r\n"; ss << "Upgrade: websocket\r\n"; ss << "Connection: Upgrade\r\n"; // Parse the client headers. Does it support deflate ? std::string header = headers["sec-websocket-extensions"]; WebSocketPerMessageDeflateOptions webSocketPerMessageDeflateOptions(header); // If the client has requested that extension, enable it. if (webSocketPerMessageDeflateOptions.enabled()) { _enablePerMessageDeflate = true; if (!_perMessageDeflate.init(webSocketPerMessageDeflateOptions)) { return WebSocketInitResult( false, 0,"Failed to initialize per message deflate engine"); } ss << webSocketPerMessageDeflateOptions.generateHeader(); } ss << "\r\n"; if (!_socket->writeBytes(ss.str(), isCancellationRequested)) { return WebSocketInitResult(false, 0, std::string("Failed sending response to ") + remote); } return WebSocketInitResult(true, 200, "", headers, uri); } }
304c338500525ac22b3fe6b67d2dd7ff6d8ab409
23b8e5d97e136302a89efc113cf43476c8240b5b
/NewTugasGPU/Tvector.h
b4b261b7a3db4a8ee851438178c32067e5913f4d
[]
no_license
jackiejohn/gpunehesrc
e0cdf1aa4dbb51d5881def84412ff1ebbfcb5598
b79643876f120a88e93f28fc28d0a5875b60eea8
refs/heads/master
2021-05-28T21:28:46.280527
2017-03-02T14:26:26
2017-03-02T14:26:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,599
h
#ifndef tvector_h #define tvector_h #include <iostream> #include <math.h> #include "mathex.h" using std::ostream; using std::istream; class TRay; class TVector { public: enum TStatus { INVALID, DEFAULT, UNIT }; private: double _x, _y, _z; TStatus _Status; // Constructors TVector(double x, double y, double z, TStatus s) : _x(x), _y(y), _z(z), _Status(s) {} // Input and output ostream &write(ostream &out) const; istream &read(istream &in); public: // Constructors TVector() : _x(0.0), _y(0.0), _z(0.0), _Status(INVALID) {} TVector(double x, double y, double z) : _x(x), _y(y), _z(z), _Status(DEFAULT) {} // Mid point between two lines TVector(const TRay &line1, const TRay &line2); // Selectors double X() const { return _x; } double Y() const { return _y; } double Z() const { return _z; } int isUnit() const { return _Status == UNIT; } int isDefault() const { return _Status == DEFAULT; } int isValid() const { return _Status != INVALID; } // Change the status of a vector TVector &unit(); static TVector &unit(const TVector &v, TVector &result) { result = v; return result.unit(); } static TVector unit(const TVector &v) { return TVector(v).unit(); } TVector &Default(); static TVector Default(const TVector &v, TVector &result) { result = v; return result.Default(); } static TVector Default(const TVector &v) { return TVector(v).Default(); } // Magnitude double mag() const { return (isValid() ? (isUnit() ? 1.0 : sqrt(sqr(X()) + sqr(Y()) + sqr(Z()))) : 0.0); } double magSqr() const { return (isValid() ? (isUnit() ? 1.0 : sqr(X()) + sqr(Y()) + sqr(Z())) : 0.0); } // Dot or scalar product double dot(const TVector &v) const { return ((isValid() && v.isValid()) ? (X()*v.X() + Y()*v.Y() + Z()*v.Z()) : 0.0); } static double dot(const TVector &v1, const TVector &v2) { return v1.dot(v2); } // Distance between two vectors double dist(const TVector &v) const { return (*this - v).mag(); } double distSqr(const TVector &v) const { return (*this - v).magSqr(); } // Optimised arithmetic methods static TVector &add(const TVector &v1, const TVector &v2, TVector &result); static TVector &subtract(const TVector &v1, const TVector &v2, TVector &result); static TVector &cross(const TVector &v1, const TVector &v2, TVector &result); static TVector &invert(const TVector &v1, TVector &result); static TVector &multiply(const TVector &v1, const double &scale, TVector &result); // Vector arithmetic, addition, subtraction and vector product TVector operator-() const { return invert(*this, TVector()); } TVector &operator+=(const TVector &v) { return add(*this, v, *this); } TVector &operator-=(const TVector &v) { return subtract(*this, v, *this); } TVector &operator*=(const TVector &v) { TVector tv(*this); return cross(tv, v, *this); } TVector &operator*=(const double &scale) { return multiply(*this, scale, *this); } TVector operator+(const TVector &v) const { TVector tv; return add(*this, v, tv); } TVector operator-(const TVector &v) const { TVector tv; return subtract(*this, v, tv); } TVector operator*(const TVector &v) const { TVector tv; return cross(*this, v, tv); } TVector operator*(const double &scale) const { TVector tv; return multiply(*this, scale, tv); } // Streaming friend ostream &operator<<(ostream &out, const TVector &o) { return o.write(out); } friend istream &operator >> (istream &in, TVector &o) { return o.read(in); } }; #endif
e2b8590c556424146f47d4d7ae4ec0b710e008d7
2a2c909ca11664fbfe3bbac77b60d9ff68c6f3d4
/C_C++_Projects/BAPS Contest/delta/weirdsquare.cpp
a6fd49c11f22f65f49291923eb85985e40fbf07a
[ "MIT" ]
permissive
sunjerry019/RandomCodes
d8049ca188d7f0daeee4a9b43d119ab026a9027c
4402604aaeee63bb1ce6fa962c496b438bb17e50
refs/heads/master
2021-01-12T14:32:02.077792
2019-05-19T15:42:48
2019-05-19T15:42:48
70,065,532
0
0
null
null
null
null
UTF-8
C++
false
false
774
cpp
#include <iostream> using namespace std; int arr[2000][2000]; int main() { int inp, cur = 1, seqlen = 1; bool down = false; cin >> inp; for (int a=1;a<=inp;++a) { if (down) { for (int b=1;b<=seqlen;++b) { arr[b-1][a-b] = cur++; } } else { for (int b=1;b<=seqlen;++b) { arr[a-b][b-1] = cur++; } } down = !down; seqlen++; } seqlen = inp - 1; for (int a=1;a<inp;++a) { if (down) { for (int b=1;b<=seqlen;++b) { arr[a+b-1][inp-b] = cur++; } } else { for (int b=1;b<=seqlen;++b) { arr[inp-b][b+a-1] = cur++; } } down = !down; seqlen--; } for (int a=0;a<inp;++a) { for (int b=0;b<inp;++b) { if (b) cout << " "; cout << arr[a][b]; } cout << "\n"; } }
5e9791b316a049fa133dbd4b1044d9e988c84f73
b45b9cd2f6bb6a37f7d596ce6130e79467ec9c4e
/src/cv_utils.cpp
284921d3749d58dc2b467f6b1d9a9df94f54e7e2
[ "Apache-2.0" ]
permissive
dcully-ironox/simple_fiducial_mapping
3d31da52579c94233ca80359ad62b618407a8657
ff940b184349bff3d66e8da33b2c31fee5ce0db7
refs/heads/master
2023-03-16T02:45:24.686613
2019-08-11T18:01:32
2019-08-11T18:04:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,827
cpp
#include <simple_fiducial_mapping/cv_utils.h> #include "tag36h11.h" #include "tag36h10.h" #include "tag25h9.h" #include "tag25h7.h" #include "tag16h5.h" namespace simple_fiducial_mapping { void draw2DFeatureLocation(const cv::Point2d& image_point, cv::Mat& image) { cv::circle(image, image_point, 5, CV_RGB(0, 0, 255)); } void drawObservation(size_t fiducial_id, const Eigen::Vector3d fiducial_position, const image_geometry::PinholeCameraModel& camera_model, cv::Mat& image) { // Project the 3d observation point into the image. cv::Point3d cv_point(fiducial_position.x(), fiducial_position.y(), fiducial_position.z()); cv::Point2d image_point = camera_model.project3dToPixel(cv_point); cv::circle(image, image_point, 10, CV_RGB(255, 0, 0)); cv::Point2d text_origin = image_point; text_origin.x += 10; // Write the fiducial ID next to it on the image. char fiducial_label[4]; snprintf(fiducial_label, 4, "%zu", fiducial_id); cv::putText(image, fiducial_label, text_origin, cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cvScalar(200, 200, 250), 1, CV_AA); } void drawObservationsInImage(const std::map<size_t, Eigen::Vector3d>& observations, const image_geometry::PinholeCameraModel& camera_model, cv::Mat& image) { for (const auto& observation_pair : observations) { drawObservation(observation_pair.first, observation_pair.second, camera_model, image); } } void drawFiducialPositionsInImage(const Eigen::Isometry3d& camera_pose, const image_geometry::PinholeCameraModel& camera_model, const std::map<size_t, Eigen::Vector3d>& fiducial_positions, cv::Mat& image) { Eigen::Isometry3d camera_H_map = camera_pose.inverse(); for (const auto& fiducial_pair : fiducial_positions) { Eigen::Vector3d tag_in_map_frame = fiducial_pair.second; Eigen::Vector3d tag_in_camera_frame = camera_H_map * tag_in_map_frame; cv::Point2d image_point = camera_model.project3dToPixel( cv::Point3d(tag_in_camera_frame.x(), tag_in_camera_frame.y(), tag_in_camera_frame.z())); draw2DFeatureLocation(image_point, image); } } void drawTagDetectionsInImage(const std::vector<TagDetection>& tag_detections, cv::Mat& image) { for (const auto& tag_detection : tag_detections) draw2DFeatureLocation(tag_detection.center, image); } std::vector<TagDetection> findTagsInImage(const cv::Mat& image) { cv::Mat grayscale_image; cv::cvtColor(image, grayscale_image, CV_BGR2GRAY); image_u8_t raw_image = {.width = grayscale_image.cols, .height = grayscale_image.rows, .stride = grayscale_image.cols, .buf = grayscale_image.data }; apriltag_family_t* tag_family = tag36h11_create(); apriltag_detector_t* tag_detector = apriltag_detector_create(); apriltag_detector_add_family(tag_detector, tag_family); tag_detector->refine_decode = 1; tag_detector->refine_edges = 1; tag_detector->quad_decimate = 1.0; tag_detector->qtp.max_nmaxima = 10; tag_detector->qtp.min_cluster_pixels = 5; tag_detector->qtp.max_line_fit_mse = 10.0; tag_detector->qtp.critical_rad = 10 * M_PI / 180; tag_detector->qtp.deglitch = 0; tag_detector->qtp.min_white_black_diff = 5; zarray_t* tag_detections = apriltag_detector_detect(tag_detector, &raw_image); std::vector<TagDetection> detections_vector; for (int detection_i = 0; detection_i < zarray_size(tag_detections); detection_i++) { apriltag_detection_t* tag_detection; zarray_get(tag_detections, detection_i, &tag_detection); detections_vector.push_back( TagDetection{.tag_id = tag_detection->id, .center = cv::Point2d(tag_detection->c[0], tag_detection->c[1]) }); } return detections_vector; } };
18287a669de95129a229709b06a69fa65ceb0fe6
8e567498a9224d7c6bf71cfe66ec5360e056ec02
/mars/boost/iostreams/imbue.hpp
2859e65d49d9dd38e8d2274b4b38a3e725102693
[ "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "OpenSSL", "BSD-3-Clause", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows", "BSL-1.0", "Apache-2.0", "BSD-2-Clause" ]
permissive
Tencent/mars
db31afeeb5c0325bfceede594038381bce3c1635
6c7028fffe01e2b49a66c221b1ac2f548649053f
refs/heads/master
2023-08-31T07:29:50.430084
2023-08-09T07:24:42
2023-08-09T07:24:42
76,222,419
18,118
3,828
NOASSERTION
2023-09-12T07:37:07
2016-12-12T04:39:54
C++
UTF-8
C++
false
false
2,384
hpp
// (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com) // (C) Copyright 2003-2007 Jonathan Turkanis // 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.) // See http://www.boost.org/libs/iostreams for documentation. #ifndef BOOST_IOSTREAMS_IMBUE_HPP_INCLUDED #define BOOST_IOSTREAMS_IMBUE_HPP_INCLUDED #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif #include <boost/config.hpp> // DEDUCED_TYPENAME, MSVC. #include <boost/detail/workaround.hpp> #include <boost/iostreams/detail/dispatch.hpp> #include <boost/iostreams/detail/streambuf.hpp> #include <boost/iostreams/detail/wrap_unwrap.hpp> #include <boost/iostreams/operations_fwd.hpp> #include <boost/mpl/if.hpp> // Must come last. #include <boost/iostreams/detail/config/disable_warnings.hpp> namespace mars_boost {} namespace boost = mars_boost; namespace mars_boost { namespace iostreams { namespace detail { // Implementation templates for simulated tag dispatch. template<typename T> struct imbue_impl; } // End namespace detail. template<typename T, typename Locale> void imbue(T& t, const Locale& loc) { detail::imbue_impl<T>::imbue(detail::unwrap(t), loc); } namespace detail { //------------------Definition of imbue_impl----------------------------------// template<typename T> struct imbue_impl : mpl::if_< is_custom<T>, operations<T>, imbue_impl< BOOST_DEDUCED_TYPENAME dispatch< T, streambuf_tag, localizable_tag, any_tag >::type > >::type { }; template<> struct imbue_impl<any_tag> { template<typename T, typename Locale> static void imbue(T&, const Locale&) { } }; template<> struct imbue_impl<streambuf_tag> { template<typename T, typename Locale> static void imbue(T& t, const Locale& loc) { t.pubimbue(loc); } }; template<> struct imbue_impl<localizable_tag> { template<typename T, typename Locale> static void imbue(T& t, const Locale& loc) { t.imbue(loc); } }; } // End namespace detail. } } // End namespaces iostreams, boost. #include <boost/iostreams/detail/config/enable_warnings.hpp> #endif // #ifndef BOOST_IOSTREAMS_IMBUE_HPP_INCLUDED
c9bedc3e737eac2c9576862004a4e3983df538d7
c00a2490947ad10582b5d675f070ccb62b70901d
/extensions/api/guest_view/vivaldi_web_view_constants.h
e4f801a99ce73deb88591130fc3e6817d0c4e046
[ "BSD-3-Clause" ]
permissive
teotikalki/vivaldi-source
543d0ab336fb5784eaae1904457598f95f426186
22a46f2c969f6a0b7ca239a05575d1ea2738768c
refs/heads/master
2021-01-23T01:17:34.305328
2016-04-29T20:28:18
2016-04-29T20:28:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
894
h
// Copyright (c) 2016 Vivaldi Technologies AS. All rights reserved #ifndef EXTENSIONS_GUEST_VIEW_VIVALDI_WEB_VIEW_CONSTANTS_H #define EXTENSIONS_GUEST_VIEW_VIVALDI_WEB_VIEW_CONSTANTS_H namespace webview { extern const char kEventRequestPageInfo[]; extern const char kEventSSLStateChanged[]; extern const char kEventTargetURLChanged[]; extern const char kEventCreateSearch[]; extern const char kEventMediaStateChanged[]; extern const char kEventPasteAndGo[]; extern const char kEventWebContentsDiscarded[]; extern const char kAttributeExtensionHost[]; extern const char kEventOnFullscreen[]; extern const char kNewSearchName[]; extern const char kNewSearchUrl[]; extern const char kClipBoardText[]; extern const char kLoadedBytes[]; extern const char kLoadedElements[]; extern const char kTotalElements[]; } //namespace webview #endif // EXTENSIONS_GUEST_VIEW_VIVALDI_WEB_VIEW_CONSTANTS_H
d13e9c2f560b9b6596874c68774bc17d3e39540f
ba5850d8c165f758ac716521edb001bf5728fd2a
/4.cpp
b51bf385c52bae343c7903513a49fa4a677abaa4
[]
no_license
Neha-Mangukiya/OOPs_Concept_Programs
a9475a28ed73d1c88d9e62d180127338126f5028
9c85d23a5e16cb0060136b082f674232e23ebd9c
refs/heads/master
2023-08-11T19:38:47.256285
2021-09-29T08:33:15
2021-09-29T08:33:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,049
cpp
//Write a program of Addition of two Matrix using Class. #include<iostream> using namespace std; class addmatrix { int a[2][2],b[2][2],c[2][2],i,j; public: void getdata() { cout << "enter the array element of a[2][2]:"; for(i=0;i<2;i++) { for(j=0;j<2;j++) { cin >> a[i][j]; } } cout << "enter the array element of b[2][2]:"; for(i=0;i<2;i++) { for(j=0;j<2;j++) { cin >> b[i][j]; } } for(i=0;i<2;i++) { for(j=0;j<2;j++) { c[i][j] = a[i][j] + b[i][j]; } } } void setdata() { cout << "first matrix :"<<endl; for(i=0;i<2;i++) { for(j=0;j<2;j++) { cout << "\t " << a[i][j]; } cout << endl; } cout << "second matrix :" << endl; for(i=0;i<2;i++) { for(j=0;j<2;j++) { cout << "\t " << b[i][j]; } cout << endl; } cout << "addition of matrix"; cout << endl; for(i=0;i<2;i++) { for(j=0;j<2;j++) { cout << "\t" <<c[i][j] ; } cout<<endl; } } }; int main() { addmatrix m; m.getdata(); m.setdata(); }
2164a79c37f29c09cffb2d0fcfd7376c28ab315e
bb7cf43fbc96ea7dd5e5a7699a61993004c3fefe
/mindspore/ccsrc/kernel/gpu/nn/rmsprop_gpu_kernel.cc
85aabe5756570e75e22af1e4b53892d0d9be13a1
[ "Apache-2.0", "BSD-3-Clause-Open-MPI", "MPL-2.0-no-copyleft-exception", "LGPL-2.1-only", "BSD-3-Clause", "MPL-2.0", "MPL-1.0", "Libpng", "AGPL-3.0-only", "MPL-1.1", "LicenseRef-scancode-proprietary-license", "MIT", "IJG", "LicenseRef-scancode-unknown-license-reference", "Unlicense", "Zlib", "GPL-2.0-only", "BSL-1.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
doc22940/mindspore
db1185c4ad3ab6456e2011a57c475b07abaf925d
21bcdcd8adb97b9171b2822a7ed2c4c138c99607
refs/heads/master
2023-02-24T18:41:11.117709
2020-05-13T09:43:04
2020-05-13T09:43:04
263,610,727
1
0
Apache-2.0
2021-01-28T06:06:39
2020-05-13T11:31:15
null
UTF-8
C++
false
false
2,099
cc
/** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "kernel/gpu/nn/rmsprop_gpu_kernel.h" namespace mindspore { namespace kernel { MS_REG_GPU_KERNEL_ONE(ApplyRMSProp, KernelAttr() .AddInputAttr(kNumberTypeFloat32) .AddInputAttr(kNumberTypeFloat32) .AddInputAttr(kNumberTypeFloat32) .AddInputAttr(kNumberTypeFloat32) .AddInputAttr(kNumberTypeFloat32) .AddInputAttr(kNumberTypeFloat32) .AddInputAttr(kNumberTypeFloat32) .AddInputAttr(kNumberTypeFloat32) .AddOutputAttr(kNumberTypeFloat32), RMSPropGpuKernel, float) MS_REG_GPU_KERNEL_ONE(ApplyCenteredRMSProp, KernelAttr() .AddInputAttr(kNumberTypeFloat32) .AddInputAttr(kNumberTypeFloat32) .AddInputAttr(kNumberTypeFloat32) .AddInputAttr(kNumberTypeFloat32) .AddInputAttr(kNumberTypeFloat32) .AddInputAttr(kNumberTypeFloat32) .AddInputAttr(kNumberTypeFloat32) .AddInputAttr(kNumberTypeFloat32) .AddInputAttr(kNumberTypeFloat32) .AddOutputAttr(kNumberTypeFloat32), RMSPropGpuKernel, float) } // namespace kernel } // namespace mindspore
2011e3ec48da1a38240b0c7bddc20590d91ec9d4
fe164360a17a2afee0dc5ad3ed08d214e7bd74a8
/Platform/Windows/HelloEngine_opengl.cpp
8ce88ec0ad7a1d8547d7d17589f8b9883c931a47
[]
no_license
AcmenLu/AcmenEngine
9fd94338974b6300465f0d40f70d65c55c6e32a9
437b55dea0edd6ea89ac6fc236f21e067dbf97aa
refs/heads/master
2020-06-19T09:29:55.526623
2019-08-29T01:09:28
2019-08-29T01:09:28
196,661,645
0
0
null
null
null
null
UTF-8
C++
false
false
31,433
cpp
#include <windows.h> #include <windowsx.h> #include <tchar.h> #include <GL/gl.h> #include <fstream> #include "math.h" using namespace std; ///////////// // DEFINES // ///////////// #define WGL_DRAW_TO_WINDOW_ARB 0x2001 #define WGL_ACCELERATION_ARB 0x2003 #define WGL_SWAP_METHOD_ARB 0x2007 #define WGL_SUPPORT_OPENGL_ARB 0x2010 #define WGL_DOUBLE_BUFFER_ARB 0x2011 #define WGL_PIXEL_TYPE_ARB 0x2013 #define WGL_COLOR_BITS_ARB 0x2014 #define WGL_DEPTH_BITS_ARB 0x2022 #define WGL_STENCIL_BITS_ARB 0x2023 #define WGL_FULL_ACCELERATION_ARB 0x2027 #define WGL_SWAP_EXCHANGE_ARB 0x2028 #define WGL_TYPE_RGBA_ARB 0x202B #define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091 #define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092 #define GL_ARRAY_BUFFER 0x8892 #define GL_STATIC_DRAW 0x88E4 #define GL_FRAGMENT_SHADER 0x8B30 #define GL_VERTEX_SHADER 0x8B31 #define GL_COMPILE_STATUS 0x8B81 #define GL_LINK_STATUS 0x8B82 #define GL_INFO_LOG_LENGTH 0x8B84 #define GL_TEXTURE0 0x84C0 #define GL_BGRA 0x80E1 #define GL_ELEMENT_ARRAY_BUFFER 0x8893 ////////////// // TYPEDEFS // ////////////// typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats); typedef HGLRC (WINAPI * PFNWGLCREATECONTEXTATTRIBSARBPROC) (HDC hDC, HGLRC hShareContext, const int *attribList); typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval); typedef void (APIENTRY * PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader); typedef void (APIENTRY * PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer); typedef void (APIENTRY * PFNGLBINDVERTEXARRAYPROC) (GLuint array); typedef void (APIENTRY * PFNGLBUFFERDATAPROC) (GLenum target, ptrdiff_t size, const GLvoid *data, GLenum usage); typedef void (APIENTRY * PFNGLCOMPILESHADERPROC) (GLuint shader); typedef GLuint(APIENTRY * PFNGLCREATEPROGRAMPROC) (void); typedef GLuint(APIENTRY * PFNGLCREATESHADERPROC) (GLenum type); typedef void (APIENTRY * PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers); typedef void (APIENTRY * PFNGLDELETEPROGRAMPROC) (GLuint program); typedef void (APIENTRY * PFNGLDELETESHADERPROC) (GLuint shader); typedef void (APIENTRY * PFNGLDELETEVERTEXARRAYSPROC) (GLsizei n, const GLuint *arrays); typedef void (APIENTRY * PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader); typedef void (APIENTRY * PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index); typedef void (APIENTRY * PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers); typedef void (APIENTRY * PFNGLGENVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays); typedef GLint(APIENTRY * PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const char *name); typedef void (APIENTRY * PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, char *infoLog); typedef void (APIENTRY * PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params); typedef void (APIENTRY * PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, char *infoLog); typedef void (APIENTRY * PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params); typedef void (APIENTRY * PFNGLLINKPROGRAMPROC) (GLuint program); typedef void (APIENTRY * PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const char* *string, const GLint *length); typedef void (APIENTRY * PFNGLUSEPROGRAMPROC) (GLuint program); typedef void (APIENTRY * PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer); typedef void (APIENTRY * PFNGLBINDATTRIBLOCATIONPROC) (GLuint program, GLuint index, const char *name); typedef GLint(APIENTRY * PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const char *name); typedef void (APIENTRY * PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (APIENTRY * PFNGLACTIVETEXTUREPROC) (GLenum texture); typedef void (APIENTRY * PFNGLUNIFORM1IPROC) (GLint location, GLint v0); typedef void (APIENTRY * PFNGLGENERATEMIPMAPPROC) (GLenum target); typedef void (APIENTRY * PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index); typedef void (APIENTRY * PFNGLUNIFORM3FVPROC) (GLint location, GLsizei count, const GLfloat *value); typedef void (APIENTRY * PFNGLUNIFORM4FVPROC) (GLint location, GLsizei count, const GLfloat *value); PFNGLATTACHSHADERPROC glAttachShader; PFNGLBINDBUFFERPROC glBindBuffer; PFNGLBINDVERTEXARRAYPROC glBindVertexArray; PFNGLBUFFERDATAPROC glBufferData; PFNGLCOMPILESHADERPROC glCompileShader; PFNGLCREATEPROGRAMPROC glCreateProgram; PFNGLCREATESHADERPROC glCreateShader; PFNGLDELETEBUFFERSPROC glDeleteBuffers; PFNGLDELETEPROGRAMPROC glDeleteProgram; PFNGLDELETESHADERPROC glDeleteShader; PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays; PFNGLDETACHSHADERPROC glDetachShader; PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray; PFNGLGENBUFFERSPROC glGenBuffers; PFNGLGENVERTEXARRAYSPROC glGenVertexArrays; PFNGLGETATTRIBLOCATIONPROC glGetAttribLocation; PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog; PFNGLGETPROGRAMIVPROC glGetProgramiv; PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog; PFNGLGETSHADERIVPROC glGetShaderiv; PFNGLLINKPROGRAMPROC glLinkProgram; PFNGLSHADERSOURCEPROC glShaderSource; PFNGLUSEPROGRAMPROC glUseProgram; PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer; PFNGLBINDATTRIBLOCATIONPROC glBindAttribLocation; PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation; PFNGLUNIFORMMATRIX4FVPROC glUniformMatrix4fv; PFNGLACTIVETEXTUREPROC glActiveTexture; PFNGLUNIFORM1IPROC glUniform1i; PFNGLGENERATEMIPMAPPROC glGenerateMipmap; PFNGLDISABLEVERTEXATTRIBARRAYPROC glDisableVertexAttribArray; PFNGLUNIFORM3FVPROC glUniform3fv; PFNGLUNIFORM4FVPROC glUniform4fv; PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB; PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB; PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT; typedef struct VertexType { VectorType position; VectorType color; } VertexType; HDC g_deviceContext = 0; HGLRC g_renderingContext = 0; char g_videoCardDescription[128]; const bool VSYNC_ENABLE = true; const float SCREEN_DEPTH = 1000.0f; const float SCREEN_NEAR = 0.1f; int g_vertexCount, g_indexCount; unsigned int g_vertexArrayID, g_vertexBufferId, g_indexBufferId; unsigned int g_vertexShader; unsigned int g_fragmenShader; unsigned int g_shaderProgram; const char VS_SHADER_SOURCE_FILE[] = "color.vs"; const char PS_SHADER_SOURCE_FILE[] = "color.ps"; float g_positionX = 0, g_positionY = 0, g_positionZ = -10; float g_rotationX = 0, g_rotationY = 0, g_rotationZ = 0; float g_worldMatrix[16]; float g_viewMatrix[16]; float g_projectionMatrix[16]; bool InitializeOpenGL(HWND hWnd, int screenWidth, int screenHeight, float screenDepth, float screenNear, bool vsync) { int attributeListInt[19]; int pixelFormat[1]; unsigned int formatCount; int result; PIXELFORMATDESCRIPTOR pixelFormatDescriptor; int attributeList[5]; float fieldOfView, screenAspect; char *vendorString, * rendererString; g_deviceContext = GetDC(hWnd); if(!g_deviceContext) { return false; } // Support for OpenGL rendering. attributeListInt[0] = WGL_SUPPORT_OPENGL_ARB; attributeListInt[1] = TRUE; // Support for rendering to a window. attributeListInt[2] = WGL_DRAW_TO_WINDOW_ARB; attributeListInt[3] = TRUE; // Support for hardware acceleration. attributeListInt[4] = WGL_ACCELERATION_ARB; attributeListInt[5] = WGL_FULL_ACCELERATION_ARB; // Support for 24bit color. attributeListInt[6] = WGL_COLOR_BITS_ARB; attributeListInt[7] = 24; // Support for 24 bit depth buffer. attributeListInt[8] = WGL_DEPTH_BITS_ARB; attributeListInt[9] = 24; // Support for double buffer. attributeListInt[10] = WGL_DOUBLE_BUFFER_ARB; attributeListInt[11] = TRUE; // Support for swapping front and back buffer. attributeListInt[12] = WGL_SWAP_METHOD_ARB; attributeListInt[13] = WGL_SWAP_EXCHANGE_ARB; // Support for the RGBA pixel type. attributeListInt[14] = WGL_PIXEL_TYPE_ARB; attributeListInt[15] = WGL_TYPE_RGBA_ARB; // Support for a 8 bit stencil buffer. attributeListInt[16] = WGL_STENCIL_BITS_ARB; attributeListInt[17] = 8; // Null terminate the attribute list. attributeListInt[18] = 0; // Query for a pixel format that fits the attributes we want. result = wglChoosePixelFormatARB(g_deviceContext, attributeListInt, NULL, 1, pixelFormat, &formatCount); if(result != 1) { return false; } // If the video card/display can handle our desired pixel format then we set it as the current one. result = SetPixelFormat(g_deviceContext, pixelFormat[0], &pixelFormatDescriptor); if(result != 1) { return false; } // Set the 4.0 version of OpenGL in the attribute list. attributeList[0] = WGL_CONTEXT_MAJOR_VERSION_ARB; attributeList[1] = 4; attributeList[2] = WGL_CONTEXT_MINOR_VERSION_ARB; attributeList[3] = 0; // Null terminate the attribute list. attributeList[4] = 0; g_renderingContext = wglCreateContextAttribsARB(g_deviceContext, 0, attributeList); if(g_renderingContext == NULL) { return false; } result = wglMakeCurrent(g_deviceContext, g_renderingContext); if(result != 1) { return false; } glClearDepth(1.0f); glEnable(GL_DEPTH_TEST); glFrontFace(GL_CW); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); // Initialize the world/model matrix to the identity matrix. BuildIdentityMatrix(g_worldMatrix); fieldOfView = PI / 4.0f; screenAspect = (float)screenWidth / (float)screenHeight; BuildPerspectiveFovLHMatrix(g_projectionMatrix, fieldOfView, screenAspect, screenNear, screenDepth); vendorString = (char*)glGetString(GL_VENDOR); rendererString = (char*)glGetString(GL_RENDERER); strcpy_s(g_videoCardDescription, vendorString); strcat_s(g_videoCardDescription, " - "); strcat_s(g_videoCardDescription, rendererString); if(vsync) { result = wglSwapIntervalEXT(1); } else { result = wglSwapIntervalEXT(0); } if(result != 1) { return false; } return true; } bool LoadExtensionList() { // Load the OpenGL extensions that this application will be using. wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"); if(!wglChoosePixelFormatARB) { return false; } wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); if(!wglCreateContextAttribsARB) { return false; } wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT"); if(!wglSwapIntervalEXT) { return false; } glAttachShader = (PFNGLATTACHSHADERPROC)wglGetProcAddress("glAttachShader"); if(!glAttachShader) { return false; } glBindBuffer = (PFNGLBINDBUFFERPROC)wglGetProcAddress("glBindBuffer"); if(!glBindBuffer) { return false; } glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)wglGetProcAddress("glBindVertexArray"); if(!glBindVertexArray) { return false; } glBufferData = (PFNGLBUFFERDATAPROC)wglGetProcAddress("glBufferData"); if(!glBufferData) { return false; } glCompileShader = (PFNGLCOMPILESHADERPROC)wglGetProcAddress("glCompileShader"); if(!glCompileShader) { return false; } glCreateProgram = (PFNGLCREATEPROGRAMPROC)wglGetProcAddress("glCreateProgram"); if(!glCreateProgram) { return false; } glCreateShader = (PFNGLCREATESHADERPROC)wglGetProcAddress("glCreateShader"); if(!glCreateShader) { return false; } glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)wglGetProcAddress("glDeleteBuffers"); if(!glDeleteBuffers) { return false; } glDeleteProgram = (PFNGLDELETEPROGRAMPROC)wglGetProcAddress("glDeleteProgram"); if(!glDeleteProgram) { return false; } glDeleteShader = (PFNGLDELETESHADERPROC)wglGetProcAddress("glDeleteShader"); if(!glDeleteShader) { return false; } glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC)wglGetProcAddress("glDeleteVertexArrays"); if(!glDeleteVertexArrays) { return false; } glDetachShader = (PFNGLDETACHSHADERPROC)wglGetProcAddress("glDetachShader"); if(!glDetachShader) { return false; } glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)wglGetProcAddress("glEnableVertexAttribArray"); if(!glEnableVertexAttribArray) { return false; } glGenBuffers = (PFNGLGENBUFFERSPROC)wglGetProcAddress("glGenBuffers"); if(!glGenBuffers) { return false; } glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)wglGetProcAddress("glGenVertexArrays"); if(!glGenVertexArrays) { return false; } glGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC)wglGetProcAddress("glGetAttribLocation"); if(!glGetAttribLocation) { return false; } glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)wglGetProcAddress("glGetProgramInfoLog"); if(!glGetProgramInfoLog) { return false; } glGetProgramiv = (PFNGLGETPROGRAMIVPROC)wglGetProcAddress("glGetProgramiv"); if(!glGetProgramiv) { return false; } glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)wglGetProcAddress("glGetShaderInfoLog"); if(!glGetShaderInfoLog) { return false; } glGetShaderiv = (PFNGLGETSHADERIVPROC)wglGetProcAddress("glGetShaderiv"); if(!glGetShaderiv) { return false; } glLinkProgram = (PFNGLLINKPROGRAMPROC)wglGetProcAddress("glLinkProgram"); if(!glLinkProgram) { return false; } glShaderSource = (PFNGLSHADERSOURCEPROC)wglGetProcAddress("glShaderSource"); if(!glShaderSource) { return false; } glUseProgram = (PFNGLUSEPROGRAMPROC)wglGetProcAddress("glUseProgram"); if(!glUseProgram) { return false; } glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)wglGetProcAddress("glVertexAttribPointer"); if(!glVertexAttribPointer) { return false; } glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)wglGetProcAddress("glBindAttribLocation"); if(!glBindAttribLocation) { return false; } glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)wglGetProcAddress("glGetUniformLocation"); if(!glGetUniformLocation) { return false; } glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)wglGetProcAddress("glUniformMatrix4fv"); if(!glUniformMatrix4fv) { return false; } glActiveTexture = (PFNGLACTIVETEXTUREPROC)wglGetProcAddress("glActiveTexture"); if(!glActiveTexture) { return false; } glUniform1i = (PFNGLUNIFORM1IPROC)wglGetProcAddress("glUniform1i"); if(!glUniform1i) { return false; } glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)wglGetProcAddress("glGenerateMipmap"); if(!glGenerateMipmap) { return false; } glDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC)wglGetProcAddress("glDisableVertexAttribArray"); if(!glDisableVertexAttribArray) { return false; } glUniform3fv = (PFNGLUNIFORM3FVPROC)wglGetProcAddress("glUniform3fv"); if(!glUniform3fv) { return false; } glUniform4fv = (PFNGLUNIFORM4FVPROC)wglGetProcAddress("glUniform4fv"); if(!glUniform4fv) { return false; } return true; } void FinalizeOpenGL(HWND hwnd) { // Release the rendering context. if(g_renderingContext) { wglMakeCurrent(NULL, NULL); wglDeleteContext(g_renderingContext); g_renderingContext = 0; } // Release the device context. if(g_deviceContext) { ReleaseDC(hwnd, g_deviceContext); g_deviceContext = 0; } } void GetVideoCardInfo(char* cardName) { strcpy_s(cardName, 128, g_videoCardDescription); return; } bool InitializeExtensions(HWND hwnd) { HDC deviceContex; PIXELFORMATDESCRIPTOR pixelFormat; int error; HGLRC renderContex; bool result; deviceContex = GetDC(hwnd); if(!deviceContex) { return false; } error = SetPixelFormat(deviceContex, 1, &pixelFormat); if(error != 1) { return false; } renderContex = wglCreateContext(deviceContex); if(!renderContex) { return false; } error = wglMakeCurrent(deviceContex, renderContex); if(error != 1) { return false; } result = LoadExtensionList(); if(!result) { return false; } wglMakeCurrent(NULL, NULL); wglDeleteContext(renderContex); renderContex = NULL; ReleaseDC(hwnd, deviceContex); deviceContex = 0; return true; } void OutputShaderErrorMessage(HWND hwnd, unsigned int shaderId, const char* shaderFilename) { int logSize, i; char* infoLog; ofstream fout; wchar_t newString[128]; unsigned int error; size_t convertedChars; // Get the size of the string containing the information log for the failed shader compilation message. glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &logSize); // Increment the size by one to handle also the null terminator. logSize++; // Create a char buffer to hold the info log. infoLog = new char[logSize]; if(!infoLog) { return; } // Now retrieve the info log. glGetShaderInfoLog(shaderId, logSize, NULL, infoLog); // Open a file to write the error message to. fout.open("shader-error.txt"); // Write out the error message. for(i=0; i<logSize; i++) { fout << infoLog[i]; } // Close the file. fout.close(); // Convert the shader filename to a wide character string. error = mbstowcs_s(&convertedChars, newString, 128, shaderFilename, 128); if(error != 0) { return; } // Pop a message up on the screen to notify the user to check the text file for compile errors. MessageBoxW(hwnd, L"Error compiling shader. Check shader-error.txt for message.", newString, MB_OK); return; } void OutputLinkerErrorMessage(HWND hwnd, unsigned int programId) { int logSize, i; char* infoLog; ofstream fout; // Get the size of the string containing the information log for the failed shader compilation message. glGetProgramiv(programId, GL_INFO_LOG_LENGTH, &logSize); // Increment the size by one to handle also the null terminator. logSize++; // Create a char buffer to hold the info log. infoLog = new char[logSize]; if(!infoLog) { return; } // Now retrieve the info log. glGetProgramInfoLog(programId, logSize, NULL, infoLog); // Open a file to write the error message to. fout.open("linker-error.txt"); // Write out the error message. for(i=0; i<logSize; i++) { fout << infoLog[i]; } // Close the file. fout.close(); // Pop a message up on the screen to notify the user to check the text file for linker errors. MessageBox(hwnd, _T("Error compiling linker. Check linker-error.txt for message."), _T("Linker Error"), MB_OK); } char* LoadShaderSourceFile(const char* filename) { ifstream fin; int fileSize; char input; char* buffer; // Open the shader source file. fin.open(filename); // If it could not open the file then exit. if(fin.fail()) { return 0; } // Initialize the size of the file. fileSize = 0; // Read the first element of the file. fin.get(input); // Count the number of elements in the text file. while(!fin.eof()) { fileSize++; fin.get(input); } // Close the file for now. fin.close(); // Initialize the buffer to read the shader source file into. buffer = new char[fileSize+1]; if(!buffer) { return 0; } // Open the shader source file again. fin.open(filename); // Read the shader text file into the buffer as a block. fin.read(buffer, fileSize); // Close the file. fin.close(); // Null terminate the buffer. buffer[fileSize] = '\0'; return buffer; } bool InitializeShader(HWND hwnd, const char* vsFilename, const char* fsFilename) { const char* vertexShaderBuffer; const char* fragmentShaderBuffer; int status; // Load the vertex shader source file into a text buffer. vertexShaderBuffer = LoadShaderSourceFile(vsFilename); if(!vertexShaderBuffer) { return false; } // Load the fragment shader source file into a text buffer. fragmentShaderBuffer = LoadShaderSourceFile(fsFilename); if(!fragmentShaderBuffer) { return false; } // Create a vertex and fragment shader object. g_vertexShader = glCreateShader(GL_VERTEX_SHADER); g_fragmenShader = glCreateShader(GL_FRAGMENT_SHADER); // Copy the shader source code strings into the vertex and fragment shader objects. glShaderSource(g_vertexShader, 1, &vertexShaderBuffer, NULL); glShaderSource(g_fragmenShader, 1, &fragmentShaderBuffer, NULL); // Release the vertex and fragment shader buffers. delete [] vertexShaderBuffer; vertexShaderBuffer = 0; delete [] fragmentShaderBuffer; fragmentShaderBuffer = 0; // Compile the shaders. glCompileShader(g_vertexShader); glCompileShader(g_fragmenShader); // Check to see if the vertex shader compiled successfully. glGetShaderiv(g_vertexShader, GL_COMPILE_STATUS, &status); if(status != 1) { // If it did not compile then write the syntax error message out to a text file for review. OutputShaderErrorMessage(hwnd, g_vertexShader, vsFilename); return false; } // Check to see if the fragment shader compiled successfully. glGetShaderiv(g_fragmenShader, GL_COMPILE_STATUS, &status); if(status != 1) { // If it did not compile then write the syntax error message out to a text file for review. OutputShaderErrorMessage(hwnd, g_fragmenShader, fsFilename); return false; } // Create a shader program object. g_shaderProgram = glCreateProgram(); // Attach the vertex and fragment shader to the program object. glAttachShader(g_shaderProgram, g_vertexShader); glAttachShader(g_shaderProgram, g_fragmenShader); // Bind the shader input variables. glBindAttribLocation(g_shaderProgram, 0, "inputPosition"); glBindAttribLocation(g_shaderProgram, 1, "inputColor"); // Link the shader program. glLinkProgram(g_shaderProgram); // Check the status of the link. glGetProgramiv(g_shaderProgram, GL_LINK_STATUS, &status); if(status != 1) { // If it did not link then write the syntax error message out to a text file for review. OutputLinkerErrorMessage(hwnd, g_shaderProgram); return false; } return true; } void ShutdownShader() { // Detach the vertex and fragment shaders from the program. glDetachShader(g_shaderProgram, g_vertexShader); glDetachShader(g_shaderProgram, g_fragmenShader); // Delete the vertex and fragment shaders. glDeleteShader(g_vertexShader); glDeleteShader(g_fragmenShader); // Delete the shader program. glDeleteProgram(g_shaderProgram); } bool SetShaderParameters(float* worldMatrix, float* viewMatrix, float* projectionMatrix) { unsigned int location; // Set the world matrix in the vertex shader. location = glGetUniformLocation(g_shaderProgram, "worldMatrix"); if(location == -1) { return false; } glUniformMatrix4fv(location, 1, false, worldMatrix); // Set the view matrix in the vertex shader. location = glGetUniformLocation(g_shaderProgram, "viewMatrix"); if(location == -1) { return false; } glUniformMatrix4fv(location, 1, false, viewMatrix); // Set the projection matrix in the vertex shader. location = glGetUniformLocation(g_shaderProgram, "projectionMatrix"); if(location == -1) { return false; } glUniformMatrix4fv(location, 1, false, projectionMatrix); return true; } bool InitializeBuffers() { VertexType vertices[] = { {{ 1.0f, 1.0f, 1.0f }, { 1.0f, 0.0f, 0.0f }}, {{ 1.0f, 1.0f, -1.0f }, { 0.0f, 1.0f, 0.0f }}, {{ -1.0f, 1.0f, -1.0f }, { 0.0f, 0.0f, 1.0f }}, {{ -1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 0.0f }}, {{ 1.0f, -1.0f, 1.0f }, { 1.0f, 0.0f, 1.0f }}, {{ 1.0f, -1.0f, -1.0f }, { 0.0f, 1.0f, 1.0f }}, {{ -1.0f, -1.0f, -1.0f }, { 0.5f, 1.0f, 0.5f }}, {{ -1.0f, -1.0f, 1.0f }, { 1.0f, 0.5f, 1.0f }}, }; uint16_t indices[] = { 1, 2, 3, 3, 2, 6, 6, 7, 3, 3, 0, 1, 0, 3, 7, 7, 6, 4, 4, 6, 5, 0, 7, 4, 1, 0, 4, 1, 4, 5, 2, 1, 5, 2, 5, 6 }; // Set the number of vertices in the vertex array. g_vertexCount = sizeof(vertices) / sizeof(VertexType); // Set the number of indices in the index array. g_indexCount = sizeof(indices) / sizeof(uint16_t); // Allocate an OpenGL vertex array object. glGenVertexArrays(1, &g_vertexArrayID); // Bind the vertex array object to store all the buffers and vertex attributes we create here. glBindVertexArray(g_vertexArrayID); // Generate an ID for the vertex buffer. glGenBuffers(1, &g_vertexBufferId); // Bind the vertex buffer and load the vertex (position and color) data into the vertex buffer. glBindBuffer(GL_ARRAY_BUFFER, g_vertexBufferId); glBufferData(GL_ARRAY_BUFFER, g_vertexCount * sizeof(VertexType), vertices, GL_STATIC_DRAW); // Enable the two vertex array attributes. glEnableVertexAttribArray(0); // Vertex position. glEnableVertexAttribArray(1); // Vertex color. // Specify the location and format of the position portion of the vertex buffer. glBindBuffer(GL_ARRAY_BUFFER, g_vertexBufferId); glVertexAttribPointer(0, 3, GL_FLOAT, false, sizeof(VertexType), 0); // Specify the location and format of the color portion of the vertex buffer. glBindBuffer(GL_ARRAY_BUFFER, g_vertexBufferId); glVertexAttribPointer(1, 3, GL_FLOAT, false, sizeof(VertexType), (char*)NULL + (3 * sizeof(float))); // Generate an ID for the index buffer. glGenBuffers(1, &g_indexBufferId); // Bind the index buffer and load the index data into it. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indexBufferId); glBufferData(GL_ELEMENT_ARRAY_BUFFER, g_indexCount* sizeof(uint16_t), indices, GL_STATIC_DRAW); return true; } void ShutdownBuffers() { // Disable the two vertex array attributes. glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); // Release the vertex buffer. glBindBuffer(GL_ARRAY_BUFFER, 0); glDeleteBuffers(1, &g_vertexBufferId); // Release the index buffer. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glDeleteBuffers(1, &g_indexBufferId); // Release the vertex array object. glBindVertexArray(0); glDeleteVertexArrays(1, &g_vertexArrayID); return; } void RenderBuffers() { // Bind the vertex array object that stored all the information about the vertex and index buffers. glBindVertexArray(g_vertexArrayID); // Render the vertex buffer using the index buffer. glDrawElements(GL_TRIANGLES, g_indexCount, GL_UNSIGNED_SHORT, 0); return; } void CalculateCameraPosition() { VectorType up, position, lookAt; float yaw, pitch, roll; float rotationMatrix[9]; // Setup the vector that points upwards. up.x = 0.0f; up.y = 1.0f; up.z = 0.0f; // Setup the position of the camera in the world. position.x = g_positionX; position.y = g_positionY; position.z = g_positionZ; // Setup where the camera is looking by default. lookAt.x = 0.0f; lookAt.y = 0.0f; lookAt.z = 1.0f; // Set the yaw (Y axis), pitch (X axis), and roll (Z axis) rotations in radians. pitch = g_rotationX * 0.0174532925f; yaw = g_rotationY * 0.0174532925f; roll = g_rotationZ * 0.0174532925f; // Create the rotation matrix from the yaw, pitch, and roll values. MatrixRotationYawPitchRoll(rotationMatrix, yaw, pitch, roll); // Transform the lookAt and up vector by the rotation matrix so the view is correctly rotated at the origin. TransformCoord(lookAt, rotationMatrix); TransformCoord(up, rotationMatrix); // Translate the rotated camera position to the location of the viewer. lookAt.x = position.x + lookAt.x; lookAt.y = position.y + lookAt.y; lookAt.z = position.z + lookAt.z; // Finally create the view matrix from the three updated vectors. BuildViewMatrix(position, lookAt, up, g_viewMatrix); } void Draw() { static float rotateAngle = 0.0f; // Set the color to clear the screen to. glClearColor(0.2f, 0.3f, 0.4f, 1.0f); // Clear the screen and depth buffer. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Update world matrix to rotate the model rotateAngle += PI / 120; float rotationMatrixY[16]; float rotationMatrixZ[16]; MatrixRotationY(rotationMatrixY, rotateAngle); MatrixRotationZ(rotationMatrixZ, rotateAngle); MatrixMultiply(g_worldMatrix, rotationMatrixZ, rotationMatrixY); // Generate the view matrix based on the camera's position. CalculateCameraPosition(); // Set the color shader as the current shader program and set the matrices that it will use for rendering. glUseProgram(g_shaderProgram); SetShaderParameters(g_worldMatrix, g_viewMatrix, g_projectionMatrix); // Render the model using the color shader. RenderBuffers(); // Present the back buffer to the screen since rendering is complete. SwapBuffers(g_deviceContext); } LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { HWND hwnd; WNDCLASSEX wc; ZeroMemory(&wc, sizeof(WNDCLASSEX)); wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = DefWindowProc; wc.hInstance = hInstance; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)COLOR_WINDOW; wc.lpszClassName = _T("AcmenEngine"); RegisterClassEx(&wc); hwnd = CreateWindowEx(0, _T("AcmenEngine"), // name of the window class _T("Hello Engine"), // title of the window WS_OVERLAPPEDWINDOW, // window style 0, // x-position of the window 0, // y-position of the window 640, // width of the window 480, // height of the window NULL, // we have no parent window, NULL NULL, // we aren't using menus, NULL hInstance, // application handle NULL); // used with multiple windows, NULL ShowWindow(hwnd, SW_HIDE); InitializeExtensions(hwnd); DestroyWindow(hwnd); hwnd = NULL; // clear out the window class for use ZeroMemory(&wc, sizeof(WNDCLASSEX)); // fill in the struct with the needed information wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = WindowProc; wc.hInstance = hInstance; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)COLOR_WINDOW; wc.lpszClassName = _T("Hello, Engine!"); // register the window class RegisterClassEx(&wc); // create the window and use the result as the handle hwnd = CreateWindowEx(WS_EX_APPWINDOW, _T("Hello, Engine!"), // name of the window class _T("Hello, Engine!"), // title of the window WS_OVERLAPPEDWINDOW, // window style 300, // x-position of the window 300, // y-position of the window 960, // width of the window 540, // height of the window NULL, // we have no parent window, NULL NULL, // we aren't using menus, NULL hInstance, // application handle NULL); // used with multiple windows, NULL InitializeOpenGL(hwnd, 960, 540, SCREEN_DEPTH, SCREEN_NEAR, true); // display the window on the screen ShowWindow(hwnd, nCmdShow); SetForegroundWindow(hwnd); InitializeShader(hwnd, VS_SHADER_SOURCE_FILE, PS_SHADER_SOURCE_FILE); InitializeBuffers(); MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } ShutdownBuffers(); ShutdownShader(); FinalizeOpenGL(hwnd); return msg.wParam; } LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch(message) { case WM_CREATE: { } case WM_PAINT: { Draw(); return 0; } case WM_DESTROY: { PostQuitMessage(0); return 0; } } return DefWindowProc(hWnd, message, wParam, lParam); }
9598daba45502743cdb10d6de502de3925ad6790
f719e253095d24a95f837be39d8d10914c18aa40
/Balero/Private/BaleroPlayerController.cpp
e0579c0e0db2034ada75fa7da9f14351c1fb273e
[]
no_license
balazon/Balero
10ff78ffe7758d2c045a71be0abaa5e89b529087
908a9682dbcfd80778269aacc18f6f735f634883
refs/heads/master
2021-01-02T23:08:20.424684
2014-11-18T21:59:04
2014-11-18T21:59:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,557
cpp
// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved. #include "Balero.h" #include "BaleroPlayerController.h" #include "AI/Navigation/NavigationSystem.h" #include "AI/Navigation/NavigationPath.h" #include "math.h" #include "BaleroCharacter.h" #include "GameFramework/HUD.h" #include "AIControllerBase.h" #include "BalaLib.h" #include "Formation.h" #include "UnitGroup.h" #define SELECTION_INITSIZE 10 ABaleroPlayerController::ABaleroPlayerController(const class FPostConstructInitializeProperties& PCIP) : Super(PCIP) { bShowMouseCursor = true; DefaultMouseCursor = EMouseCursor::Crosshairs; SelectedUnits.Init(SELECTION_INITSIZE); SelectedUnits.Empty(SELECTION_INITSIZE); Delta = 0.f; } void ABaleroPlayerController::PlayerTick(float DeltaTime) { Super::PlayerTick(DeltaTime); // keep updating the destination every tick while desired if (bMoveToMouseCursor) { MoveToMouseCursor(); } Delta = DeltaTime; } void ABaleroPlayerController::SetupInputComponent() { // set up gameplay key bindings Super::SetupInputComponent(); InputComponent->BindAction("SetDestination", IE_Pressed, this, &ABaleroPlayerController::OnSetDestinationPressed); InputComponent->BindAction("SetDestination", IE_Released, this, &ABaleroPlayerController::OnSetDestinationReleased); // support touch devices //InputComponent->BindTouch(EInputEvent::IE_Pressed, this, &ABallertsPlayerController::TouchPressed); //InputComponent->BindTouch(EInputEvent::IE_Repeat, this, &ABallertsPlayerController::MoveToTouchLocation); InputComponent->BindAction("Click", IE_Pressed, this, &ABaleroPlayerController::OnClickPressed); InputComponent->BindAction("Click", IE_Released, this, &ABaleroPlayerController::OnClickReleased); InputComponent->BindAction("IncreaseSelection", IE_Pressed, this, &ABaleroPlayerController::OnIncreaseSelectionPressed); InputComponent->BindAction("IncreaseSelection", IE_Released, this, &ABaleroPlayerController::OnIncreaseSelectionReleased); InputComponent->BindAction("Zoom", IE_Pressed, this, &ABaleroPlayerController::OnZoomStart); InputComponent->BindAction("Zoom", IE_Released, this, &ABaleroPlayerController::OnZoomProcessing); //InputComponent->BindAction("MoveForward", IE_Pressed, this, &ABallertsPlayerController::OnPanVerticalStart); //InputComponent->BindAction("MoveRight", IE_Pressed, this, &ABallertsPlayerController::OnPanHorizontalStart); InputComponent->BindAxis("MoveRight", this, &ABaleroPlayerController::OnPanVerticalStart); InputComponent->BindAxis("MoveForward", this, &ABaleroPlayerController::OnPanHorizontalStart); InputComponent->BindAction("RightClick", IE_Pressed, this, &ABaleroPlayerController::OnRightClickPressed); InputComponent->BindAction("Test", IE_Pressed, this, &ABaleroPlayerController::OnTestButtonPressed); } void ABaleroPlayerController::BeginPlay() { Super::BeginPlay(); AHUD* Hud = GetHUD(); bEnableClickEvents = true; bShowMouseCursor = true; Hud->EnableInput(this); UUnitGroup::SetWorld(GetWorld()); } void ABaleroPlayerController::MoveToMouseCursor() { // Trace to see what is under the mouse cursor FHitResult Hit; GetHitResultUnderCursor(ECC_Visibility, false, Hit); if (Hit.bBlockingHit) { // We hit something, move there SetNewMoveDestination(Hit.ImpactPoint); } } void ABaleroPlayerController::TouchPressed(const ETouchIndex::Type FingerIndex, const FVector Location) { } void ABaleroPlayerController::MoveToTouchLocation(const ETouchIndex::Type FingerIndex, const FVector Location) { FVector2D ScreenSpaceLocation(Location); // Trace to see what is under the touch location FHitResult HitResult; GetHitResultAtScreenPosition(ScreenSpaceLocation, CurrentClickTraceChannel, true, HitResult); if (HitResult.bBlockingHit) { // We hit something, move there SetNewMoveDestination(HitResult.ImpactPoint); } } void ABaleroPlayerController::MoveToActor(AActor* TargetActor) { for (ABaleroCharacter* MyChar : SelectedUnits) { if (MyChar) { AAIControllerBase* controller = Cast<AAIControllerBase>(MyChar->GetController()); controller->SetTargetActor(TargetActor); } } } void ABaleroPlayerController::SetNewMoveDestination(const FVector DestLocation) { UUnitGroup::Move(FVector2D(DestLocation.X, DestLocation.Y), SelectedUnits); } void ABaleroPlayerController::MoveToFormation() { UUnitGroup::MoveToFormation(SelectedUnits, EShapeEnum::SE_ONE_TRIANGLE); } void ABaleroPlayerController::OnSetDestinationPressed() { // set flag to keep updating destination until released //bMoveToMouseCursor = true; } void ABaleroPlayerController::OnSetDestinationReleased() { // clear flag to indicate we should stop updating the destination //bMoveToMouseCursor = false; } void ABaleroPlayerController::DeselectAll() { UE_LOG(LogTemp, Warning, TEXT("DESELECT ALL")); for (ABaleroCharacter* Unit : SelectedUnits) { if (Unit) { Unit->SelectedEffect->SetVisibility(false); } } SelectedUnits.Init(SELECTION_INITSIZE); SelectedUnits.Empty(SELECTION_INITSIZE); } void ABaleroPlayerController::OnClickPressed() { UE_LOG(LogTemp, Warning, TEXT("clickpressed")); FHitResult Hit; GetHitResultUnderCursor(ECC_Visibility, false, Hit); FVector2D MouseLocation; GetMousePosition(MouseLocation.X, MouseLocation.Y); int32 ViewportX; int32 ViewportY; GetViewportSize(ViewportX, ViewportY); if (MouseLocation.X > ViewportX * .9f) { return; } if (Hit.bBlockingHit) { UE_LOG(LogTemp, Warning, TEXT("clickedsomething")); APawn* pawn = Cast<APawn>(Hit.GetActor()); if (pawn != NULL) { UE_LOG(LogTemp, Warning, TEXT("clicked pawn")); ABaleroCharacter* Unit = Cast<ABaleroCharacter>(pawn); if (Unit != NULL) { //deselect the clicked unit if (SelectedUnits.Contains(Unit)) { RemoveUnitFromSelection(Unit); } //add unit to selection else { AddUnitToSelection(Unit); } } } else { //give move command to move UE_LOG(LogTemp, Warning, TEXT("MOVE COMMAND_A")); for (ABaleroCharacter* Unit : SelectedUnits) { AAIControllerBase* AIControl = Cast<AAIControllerBase>(Unit->GetController()); FVector loc = Unit->GetActorLocation(); UE_LOG(LogTemp, Warning, TEXT("Unit ai: %s , pos: %.1f %.1f %.1f"), *(AActor::GetDebugName(AIControl)), loc.X, loc.Y, loc.Z); } MoveToMouseCursor(); } } else { UE_LOG(LogTemp, Warning, TEXT("MOVE COMMAND_B")); MoveToMouseCursor(); } } void ABaleroPlayerController::OnClickReleased() { } void ABaleroPlayerController::OnIncreaseSelectionPressed() { UE_LOG(LogTemp, Warning, TEXT("shiftclickpressed")); FHitResult Hit; GetHitResultUnderCursor(ECC_Visibility, false, Hit); if (Hit.bBlockingHit) { APawn* pawn = Cast<APawn>(Hit.Actor.Get()); if (pawn != NULL) { ABaleroCharacter* Unit = Cast<ABaleroCharacter>(pawn); if (Unit != NULL) { SelectedUnits.Add(Unit); Unit->SelectedEffect->SetVisibility(true); } } } } void ABaleroPlayerController::OnIncreaseSelectionReleased() { } void ABaleroPlayerController::OnZoomStart() { } void ABaleroPlayerController::OnZoomProcessing() { } void ABaleroPlayerController::OnPanVerticalStart(float value) { //UE_LOG(LogTemp, Warning, TEXT("RIGHT -- LEFT")); GetPawn()->AddMovementInput(FVector(0, 10.f, 0), value); if (true) { GetPawn()->AddActorLocalOffset(FVector(0, 500.f * value * Delta, 0)); //UE_LOG(LogTemp, Warning, TEXT("RIGHT -- LEFT")); } //SetActorLocation() } void ABaleroPlayerController::OnPanVerticalProcessing(float value) { } void ABaleroPlayerController::OnPanHorizontalStart(float value) { GetPawn()->AddMovementInput(FVector(10.f, 0, 0), value); //FMath::Abs(value) > .1f if (true) { GetPawn()->AddActorLocalOffset(FVector(500.f * value * Delta, 0, 0)); //UE_LOG(LogTemp, Warning, TEXT("RIGHT -- LEFT")); } } void ABaleroPlayerController::OnPanHorizontalProcessing(float value) { } void ABaleroPlayerController::OnRightClickPressed() { UE_LOG(LogTemp, Warning, TEXT("rightclick")); FHitResult Hit; GetHitResultUnderCursor(ECC_Visibility, false, Hit); FVector2D MouseLocation; GetMousePosition(MouseLocation.X, MouseLocation.Y); int32 ViewportX; int32 ViewportY; GetViewportSize(ViewportX, ViewportY); if (MouseLocation.X > ViewportX * .9f) { return; } if (Hit.bBlockingHit) { UE_LOG(LogTemp, Warning, TEXT("rightclickedsomething")); APawn* pawn = Cast<APawn>(Hit.GetActor()); if (pawn != NULL) { UE_LOG(LogTemp, Warning, TEXT("clicked pawn")); ABaleroCharacter* Unit = Cast<ABaleroCharacter>(pawn); if (Unit != NULL) { MoveToActor(Unit); } } else { MoveToMouseCursor(); } } } void ABaleroPlayerController::AddUnitToSelection(ABaleroCharacter* Unit) { SelectedUnits.Add(Unit); Unit->SelectedEffect->SetVisibility(true); } void ABaleroPlayerController::RemoveUnitFromSelection(ABaleroCharacter* Unit) { SelectedUnits.Remove(Unit); Unit->SelectedEffect->SetVisibility(false); } void ABaleroPlayerController::OnTestButtonPressed() { //TArray<float> Weights; // //Weights.Init(10000); //for (int i = 0; i < 10000; i++) Weights[i] = FMath::FRandRange(1.f, 10.f); //TArray<int32> res; //UBalaLib::Assignment(Weights, 100, res); ////assignment has a while(true), but if the algorithm was implemented well, it shouldnt be a problem //UE_LOG(LogTemp, Warning, TEXT("Assignment OK")); if (SelectedUnits.Num() > 0) { AAIControllerBase* Controller = Cast<AAIControllerBase>(SelectedUnits[0]->GetController()); Controller->MyTestFunc(); } }
a6de054ff1b3761280158e13dd85334ca6364e45
27f6fe82e87031bd6943d2db61203cf320a82eeb
/beScene/source/beEffectQueueSetup.cpp
18b8c6d13b07da35eaf622b85fb2226f5ab73875
[ "BSL-1.0", "MIT" ]
permissive
shadercoder/breeze-2
834283163f2be22a8d571cc08f36ebba4b7ed8ca
1692b97f455c4bc856ec2f0eb8c0b86e708a398a
refs/heads/master
2020-06-04T04:57:56.330850
2013-03-12T22:34:58
2013-03-12T22:34:58
35,313,683
0
0
null
null
null
null
UTF-8
C++
false
false
1,852
cpp
/****************************************************/ /* breeze Engine Scene Module (c) Tobias Zirr 2011 */ /****************************************************/ #include "beSceneInternal/stdafx.h" #include "beScene/beEffectQueueSetup.h" #include "beScene/beAbstractRenderableEffectDriver.h" #include "beScene/beRenderContext.h" #include "beScene/beRenderingLimits.h" #include <beGraphics/Any/beStateManager.h> namespace beScene { // Constructor. EffectQueueSetup::EffectQueueSetup(AbstractRenderableEffectDriver *pEffectDriver) : m_pEffectDriver(pEffectDriver) { } // Destructor. EffectQueueSetup::~EffectQueueSetup() { } // Called before drawing of a specific render queue begins. void EffectQueueSetup::SetupRendering(uint4 stageID, uint4 queueID, const Perspective &perspective, const RenderContext &context) const { beGraphics::Any::StateManager &stateManager = ToImpl( context.StateManager() ); stateManager.Revert(); struct NoDraw : lean::vcallable_base<AbstractRenderableEffectDriver::DrawJobSignature, NoDraw> { void operator ()(uint4 passIdx, beGraphics::StateManager &stateManager, const beGraphics::DeviceContext &context) { } } noDraw; AbstractRenderableEffectDriver::PassRange passes = m_pEffectDriver->GetPasses(); for (uint4 passID = 0; passID < Size(passes); ++passID) { const QueuedPass *pass = &passes.Begin[passID]; uint4 passStageID = pass->GetStageID(); uint4 passQueueID = pass->GetQueueID(); bool bStageMatch = passStageID == stageID || passStageID == InvalidPipelineStage; bool bQueueMatch = passQueueID == queueID || passQueueID == InvalidRenderQueue; if (bStageMatch && bQueueMatch) m_pEffectDriver->Render(pass, nullptr, perspective, noDraw, stateManager, context.Context()); } stateManager.RecordOverridden(); } } // namespace
[ "[email protected]@344fd88e-b756-27f1-9498-cf4cd09e0567" ]
[email protected]@344fd88e-b756-27f1-9498-cf4cd09e0567
80671d754649ef05e54aad31304e15c6d1f8a4c0
c250d07c0f8a304ed74425592aa7950d75d7fdab
/src/play.cpp
aa3c515ac8d9d18f588d1ea8de9bb8767bad4a20
[ "MIT" ]
permissive
aosterthun/rgbd-calib-py
50cb90aa314c522996676b3e005425b7bf392d22
2890a5e571a05c0d7ebb841a6f7346893fa812c8
refs/heads/master
2021-01-11T20:06:41.962170
2018-04-24T10:31:12
2018-04-24T10:31:12
79,460,958
0
0
null
2017-01-19T14:25:15
2017-01-19T14:25:15
null
UTF-8
C++
false
false
11,728
cpp
#include "play.hpp" Play::Play(RGBDRIClient &client, std::string const& filename, std::string const& stream_endpoint): client{client}, filename{filename}, loop{false}, number_rgbd_sensors{4}, compressed{true}, stream_endpoint{stream_endpoint}, ctx{}, skt{}, req_inited{false}, m_logger{spdlog::get("console")}, is_running{false}, backchannel_endpoint{} { ctx = std::make_shared<zmq::context_t>(4); m_logger->debug("Stream endpoint {0:s}", this->stream_endpoint); if(this->stream_endpoint != "self"){ auto endpoint = split(this->stream_endpoint,':'); m_logger->debug(endpoint[1]); auto port = std::stoi(endpoint[1]); auto new_port = port + 1; this->backchannel_endpoint = endpoint[0] + ":" + std::to_string(new_port); m_logger->debug(this->backchannel_endpoint); } }; Play::Play(RGBDRIClient &client, std::string const& filename, std::string const& stream_endpoint, std::string const& backchannel_endpoint): client{client}, filename{filename}, loop{false}, number_rgbd_sensors{4}, compressed{true}, stream_endpoint{stream_endpoint}, ctx{}, skt{}, req_inited{false}, m_logger{spdlog::get("console")}, is_running{false}, backchannel_endpoint{backchannel_endpoint} { ctx = std::make_shared<zmq::context_t>(4); m_logger->debug("Stream endpoint {0:s}", stream_endpoint); if(stream_endpoint != "self"){ auto endpoint = split(stream_endpoint,':'); m_logger->debug(endpoint[1]); auto port = std::stoi(endpoint[1]); auto new_port = port + 1; this->backchannel_endpoint = endpoint[0] + ":" + std::to_string(new_port); m_logger->debug(backchannel_endpoint); } }; Play::Play(std::string const& filename, std::string const& stream_endpoint): client{}, filename{filename}, loop{false}, number_rgbd_sensors{4}, compressed{true}, stream_endpoint{stream_endpoint}, ctx{}, skt{}, req_inited{false}, m_logger{spdlog::get("console")}, is_running{false}, backchannel_endpoint{} { ctx = std::make_shared<zmq::context_t>(4); m_logger->debug(stream_endpoint); if(stream_endpoint != "self"){ auto endpoint = split(stream_endpoint,':'); m_logger->debug(endpoint[1]); auto port = std::stoi(endpoint[1]); auto new_port = port + 1; backchannel_endpoint = endpoint[0] + ":" + std::to_string(new_port); m_logger->debug(backchannel_endpoint); } }; Play::Play(std::string const& filename, bool loop, int number_rgbd_sensors, int max_fps, bool compressed, int start_frame, int end_frame, std::string const& stream_endpoint): client{}, filename{filename}, loop{loop}, number_rgbd_sensors{number_rgbd_sensors}, max_fps{max_fps}, compressed{compressed}, start_frame{start_frame}, end_frame{end_frame}, stream_endpoint{stream_endpoint}, ctx{}, skt{}, req_inited{false}, m_logger{spdlog::get("console")}, is_running{false}, backchannel_endpoint{}{ ctx = std::make_shared<zmq::context_t>(4); m_logger->debug(stream_endpoint); if(stream_endpoint != "self"){ auto endpoint = split(stream_endpoint,':'); m_logger->debug(endpoint[1]); auto port = std::stoi(endpoint[1]); auto new_port = port + 1; backchannel_endpoint = endpoint[0] + ":" + std::to_string(new_port); m_logger->debug(backchannel_endpoint); } }; Play::Play(std::string const& filename, bool loop, int number_rgbd_sensors, int max_fps, bool compressed, int start_frame, int end_frame, std::string const& backchannel_endpoint, std::string const& stream_endpoint): client{}, filename{filename}, loop{loop}, number_rgbd_sensors{number_rgbd_sensors}, max_fps{max_fps}, compressed{compressed}, start_frame{start_frame}, end_frame{end_frame}, stream_endpoint{stream_endpoint}, ctx{}, skt{}, req_inited{false}, m_logger{spdlog::get("console")}, is_running{false}, backchannel_endpoint{backchannel_endpoint}{ ctx = std::make_shared<zmq::context_t>(4); }; Play::~Play(){ m_logger->debug("destructor {0:s}", filename); m_logger->debug("destructor {0:b}", is_running); if(is_running){ stop(); } } void Play::init_req(){ if(!req_inited){ skt = std::make_shared<zmq::socket_t>(*ctx.get(), ZMQ_REQ); req_inited = true; } } void Play::init_rep(){ m_logger->debug("[START] void Play::init_rep()"); skt = std::make_shared<zmq::socket_t>(*ctx.get(), ZMQ_REP); m_logger->debug("backchannel_endpoint:{0:s}", backchannel_endpoint); skt->bind("tcp://" + backchannel_endpoint); while(is_running){ m_logger->debug("backchannel_endpoint:{0:s}", backchannel_endpoint); zmq::message_t message; auto request = srecv(*skt.get()); if(request[0] == "STOP"){ m_logger->debug("STOP"); ssend(*skt.get(), "STOPED"); is_running = false; } if(request[0] == "PAUSE"){ m_logger->debug("PAUSE"); ssend(*skt.get(), "PAUSED"); is_paused = true; } if(request[0] == "RESUME"){ m_logger->debug("RESUME"); ssend(*skt.get(), "RESUMED"); is_paused = false; } } m_logger->debug("backchannel_endpoint:{0:s}", backchannel_endpoint); skt->unbind("tcp://" + backchannel_endpoint); m_logger->debug("[END] void Play::init_rep()"); } void Play::execute(){ m_logger->debug("[START] void Play::execute()"); is_running = true; auto rep_thread = std::thread(&Play::init_rep,this); rep_thread.detach(); const unsigned colorsize = compressed ? 691200 : 1280 * 1080 * 3; const unsigned depthsize = 512 * 424 * sizeof(float); const unsigned framesize = (colorsize + depthsize) * number_rgbd_sensors; double frametime = 0; double last_frame_time = 0; FileBuffer* fb = nullptr; size_t framecounter = 0; size_t num_frames = 0; zmq::socket_t socket(*ctx.get(), ZMQ_PUB); uint32_t hwm = 1; socket.setsockopt(ZMQ_SNDHWM,&hwm, sizeof(hwm)); std::string endpoint("tcp://" + stream_endpoint); socket.bind(endpoint.c_str()); if(fb != nullptr){ fb->close(); delete fb; fb = nullptr; } fb = new FileBuffer(filename.c_str()); if(!fb->open("r", 0)){ m_logger->critical("error opening {0:s} exiting...",filename); exit(0); } fb->setLooping(loop); framecounter = 0; num_frames = fb->getFileSizeBytes()/framesize; while (is_running) { if(!is_paused){ zmq::message_t zmqm(framesize); fb->read((unsigned char*) zmqm.data(), framesize); memcpy((char*) &frametime, (const char*) zmqm.data(), sizeof(double)); const double elapsed_frame_time = frametime - last_frame_time; last_frame_time = frametime; const unsigned sleep_time = std::min(100u, std::max(0u, (unsigned)((elapsed_frame_time) * 1000u))); if(framecounter > 1){ std::this_thread::sleep_for(std::chrono::milliseconds(sleep_time)); } socket.send(zmqm); ++framecounter; if(framecounter >= num_frames){ if(loop){ m_logger->debug("loop: restart stream"); framecounter = 0; } else{ m_logger->debug("stop play since end reached"); is_running = false; } } } } m_logger->debug("[END] void Play::execute()"); }; void Play::start(){ //Wrap command as GenericMessage auto msg = GenericMessage(); msg.type = 0; //TODO: think about type handling m_logger->debug("start"); msg.payload = to_string(); m_logger->debug(msg.payload); //Send command to server client.send(msg.to_string()); m_logger->debug("Send request"); auto reply = client.recv(); m_logger->debug("Received reply"); auto reply_msg = GenericMessage::from_string(reply.back()); switch (reply_msg.type) { case 15:{ m_logger->debug(reply_msg.payload); Play::from_string(*this, reply_msg.payload); // stream_endpoint = cmd.stream_endpoint; // backchannel_endpoint = cmd.backchannel_endpoint; // is_running = cmd.is_running; // is_paused = cmd.is_paused; // m_logger->debug("Play on endpoint: {0:s}", cmd.stream_endpoint); break; } case 1:{ m_logger->warn("Received non valid command"); break; } } }; bool Play::is_playing(){ init_req(); skt->connect("tcp://" + backchannel_endpoint); m_logger->debug(backchannel_endpoint); ssend(*skt.get(),"IS_RUNNING"); auto rep = srecv(*skt.get()); skt->disconnect("tcp://" + backchannel_endpoint); return to_bool(rep.front()); }; void Play::play_as_loop(){ loop = true; start(); loop = false; }; void Play::stop(){ init_req(); m_logger->debug("[START] void Play::stop()"); skt->connect("tcp://" + backchannel_endpoint); m_logger->debug("Connected"); ssend(*skt.get(),"STOP"); m_logger->debug("Send"); srecv(*skt.get()); m_logger->debug("Recv"); skt->disconnect("tcp://" + backchannel_endpoint); m_logger->debug("[END] void Play::stop()"); }; void Play::pause(){ init_req(); m_logger->debug("[START] void Play::pause()"); skt->connect("tcp://" + backchannel_endpoint); ssend(*skt.get(),"PAUSE"); srecv(*skt.get()); skt->disconnect("tcp://" + backchannel_endpoint); m_logger->debug("[END] void Play::pause()"); }; void Play::resume(){ init_req(); m_logger->debug("[START] void Play::resume()"); skt->connect("tcp://" + backchannel_endpoint); ssend(*skt.get(),"RESUME"); srecv(*skt.get()); skt->disconnect("tcp://" + backchannel_endpoint); m_logger->debug("[END] void Play::resume()"); }; std::string Play::to_string(){ std::string output; output += filename + "$"; output += std::to_string(loop) + "$"; output += std::to_string(number_rgbd_sensors) + "$"; output += std::to_string(max_fps) + "$"; output += std::to_string(compressed) + "$"; output += std::to_string(start_frame) + "$"; output += std::to_string(end_frame) + "$"; output += std::to_string(is_running) + "$"; output += std::to_string(is_paused) + "$"; output += backchannel_endpoint + "$"; output += stream_endpoint + "$"; return output; }; Play Play::from_string(std::string const& play_string){ std::cout << "from string start" << std::endl; std::cout << play_string << std::endl; auto parts = split(play_string, '$'); auto cmd = Play( parts[0] + "ich bin fake", to_bool(parts[1]), std::stoi(parts[2]), std::stoi(parts[3]), to_bool(parts[4]), std::stoi(parts[5]), std::stoi(parts[6]), parts[9], parts[10] ); cmd.is_running = to_bool(parts[7]); cmd.is_paused = to_bool(parts[8]); std::cout << "from string end" << std::endl; return cmd; }; void Play::from_string(Play &play,std::string const& play_string){ std::cout << "from string start" << std::endl; std::cout << play_string << std::endl; auto parts = split(play_string, '$'); play.filename = parts[0]; play.loop = to_bool(parts[1]); play.number_rgbd_sensors = std::stoi(parts[2]); play.max_fps = std::stoi(parts[3]); play.compressed = to_bool(parts[4]); play.start_frame = std::stoi(parts[5]); play.end_frame = std::stoi(parts[6]); play.is_running = to_bool(parts[7]); play.is_paused = to_bool(parts[8]); play.backchannel_endpoint = parts[9]; play.stream_endpoint = parts[10]; std::cout << "from string end" << std::endl; };
339e89ec8f99136e3f4ee74c2369865f5d71ace6
831a3f43a4e99b8e765ac89bcf089b698f6de334
/fs/src/node_iterator.h
18fb27f00f8c8e8f317e20aa0d00de4490cbd7ba
[]
no_license
t105598072/FileSystemSimulated
de56bdbbed1a7031ec6702bcd01d81be1469bced
23e5403ae916d3a277497362ba372e8e09548d76
refs/heads/master
2020-05-20T03:22:56.581452
2019-05-07T09:20:59
2019-05-07T09:20:59
185,356,745
0
0
null
null
null
null
UTF-8
C++
false
false
256
h
#ifndef NODE_ITERATOR_H #define NODE_ITERATOR_H class Node; class NodeIterator { public: virtual void first() = 0; virtual Node* currentItem() = 0; virtual void next() = 0; virtual bool isDone() = 0; virtual ~NodeIterator() { } }; #endif
603a04e1db66b5fb103661d472b35026dd0a91c0
c0df06c4057d2705d5602f5347daab327324ab04
/01_ADT.cpp
63036b08ec45e8c4a663ca3c4ced9459732d7d2f
[]
no_license
Rehancoder14/Data-structure-and-algorithm
4c8d34040e7d867ec42c2d8cf8cb571f1c440fa8
261a6e8ecbc3824213f108a5fe04dd1bc1a1f246
refs/heads/main
2023-08-19T22:22:59.683281
2021-10-25T07:19:09
2021-10-25T07:19:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
796
cpp
#include <iostream> using namespace std; #define n 10 class stack{ int *arr; int top; public: stack(){ arr = new int[n]; top = -1; } void push(int x){ if (top==n-1) { cout<<"Stack overflow"<<endl; } top++; arr[top]= x; } void pop(){ top--; } int Top(){ if (top==-1) { cout<<"no elements of Pop"<<endl; } return arr[top]; } bool empty(){ return top==-1; } void display(){ cout<<*arr<<" "; } }; int main() { stack st; st.push(10); st.push(20); st.push(40); st.push(30); st.pop(); cout<<st.Top()<<endl; cout<<st.empty()<<endl; return 0 ; }
c74cb4c8907234315bfd8beb42a95d9a70ff6749
547372791dc4ed86c8dcd5a538759ae49513c866
/src/sw/redis++/redis.cpp
8f529427eccae3e90aa20beb30ea8feab7cc9a52
[ "Apache-2.0" ]
permissive
jiangwch/redis-plus-plus
05418e67e1b117c003f1f665ed41d856d3b2930c
6ffdf4d01fac52f40010513634c552074376a243
refs/heads/master
2020-05-15T10:22:58.889362
2019-04-19T03:32:35
2019-04-19T03:32:35
182,191,549
0
0
null
2019-04-19T02:55:17
2019-04-19T02:55:16
null
UTF-8
C++
false
false
21,455
cpp
/************************************************************************** Copyright (c) 2017 sewenew 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 "redis.h" #include <hiredis/hiredis.h> #include "command.h" #include "errors.h" #include "queued_redis.h" namespace sw { namespace redis { Redis::Redis(const std::string &uri) : Redis(ConnectionOptions(uri)) {} Redis::Redis(const ConnectionSPtr &connection) : _connection(connection) { assert(_connection); } Pipeline Redis::pipeline() { auto opts = _pool.connection_options(); return Pipeline(std::make_shared<Connection>(opts)); } Transaction Redis::transaction(bool piped) { auto opts = _pool.connection_options(); return Transaction(std::make_shared<Connection>(opts), piped); } Subscriber Redis::subscriber() { auto opts = _pool.connection_options(); return Subscriber(Connection(opts)); } // CONNECTION commands. void Redis::auth(const StringView &password) { auto reply = command(cmd::auth, password); reply::parse<void>(*reply); } std::string Redis::echo(const StringView &msg) { auto reply = command(cmd::echo, msg); return reply::parse<std::string>(*reply); } std::string Redis::ping() { auto reply = command<void (*)(Connection &)>(cmd::ping); return reply::to_status(*reply); } std::string Redis::ping(const StringView &msg) { auto reply = command<void (*)(Connection &, const StringView &)>(cmd::ping, msg); return reply::parse<std::string>(*reply); } void Redis::swapdb(long long idx1, long long idx2) { auto reply = command(cmd::swapdb, idx1, idx2); reply::parse<void>(*reply); } // SERVER commands. void Redis::bgrewriteaof() { auto reply = command(cmd::bgrewriteaof); reply::parse<void>(*reply); } void Redis::bgsave() { auto reply = command(cmd::bgsave); reply::parse<void>(*reply); } long long Redis::dbsize() { auto reply = command(cmd::dbsize); return reply::parse<long long>(*reply); } void Redis::flushall(bool async) { auto reply = command(cmd::flushall, async); reply::parse<void>(*reply); } void Redis::flushdb(bool async) { auto reply = command(cmd::flushdb, async); reply::parse<void>(*reply); } std::string Redis::info() { auto reply = command<void (*)(Connection &)>(cmd::info); return reply::parse<std::string>(*reply); } std::string Redis::info(const StringView &section) { auto reply = command<void (*)(Connection &, const StringView &)>(cmd::info, section); return reply::parse<std::string>(*reply); } long long Redis::lastsave() { auto reply = command(cmd::lastsave); return reply::parse<long long>(*reply); } void Redis::save() { auto reply = command(cmd::save); reply::parse<void>(*reply); } // KEY commands. long long Redis::del(const StringView &key) { auto reply = command(cmd::del, key); return reply::parse<long long>(*reply); } OptionalString Redis::dump(const StringView &key) { auto reply = command(cmd::dump, key); return reply::parse<OptionalString>(*reply); } long long Redis::exists(const StringView &key) { auto reply = command(cmd::exists, key); return reply::parse<long long>(*reply); } bool Redis::expire(const StringView &key, long long timeout) { auto reply = command(cmd::expire, key, timeout); return reply::parse<bool>(*reply); } bool Redis::expireat(const StringView &key, long long timestamp) { auto reply = command(cmd::expireat, key, timestamp); return reply::parse<bool>(*reply); } bool Redis::move(const StringView &key, long long db) { auto reply = command(cmd::move, key, db); return reply::parse<bool>(*reply); } bool Redis::persist(const StringView &key) { auto reply = command(cmd::persist, key); return reply::parse<bool>(*reply); } bool Redis::pexpire(const StringView &key, long long timeout) { auto reply = command(cmd::pexpire, key, timeout); return reply::parse<bool>(*reply); } bool Redis::pexpireat(const StringView &key, long long timestamp) { auto reply = command(cmd::pexpireat, key, timestamp); return reply::parse<bool>(*reply); } long long Redis::pttl(const StringView &key) { auto reply = command(cmd::pttl, key); return reply::parse<long long>(*reply); } OptionalString Redis::randomkey() { auto reply = command(cmd::randomkey); return reply::parse<OptionalString>(*reply); } void Redis::rename(const StringView &key, const StringView &newkey) { auto reply = command(cmd::rename, key, newkey); reply::parse<void>(*reply); } bool Redis::renamenx(const StringView &key, const StringView &newkey) { auto reply = command(cmd::renamenx, key, newkey); return reply::parse<bool>(*reply); } void Redis::restore(const StringView &key, const StringView &val, long long ttl, bool replace) { auto reply = command(cmd::restore, key, val, ttl, replace); reply::parse<void>(*reply); } long long Redis::touch(const StringView &key) { auto reply = command(cmd::touch, key); return reply::parse<long long>(*reply); } long long Redis::ttl(const StringView &key) { auto reply = command(cmd::ttl, key); return reply::parse<long long>(*reply); } std::string Redis::type(const StringView &key) { auto reply = command(cmd::type, key); return reply::parse<std::string>(*reply); } long long Redis::unlink(const StringView &key) { auto reply = command(cmd::unlink, key); return reply::parse<long long>(*reply); } long long Redis::wait(long long numslaves, long long timeout) { auto reply = command(cmd::wait, numslaves, timeout); return reply::parse<long long>(*reply); } // STRING commands. long long Redis::append(const StringView &key, const StringView &val) { auto reply = command(cmd::append, key, val); return reply::parse<long long>(*reply); } long long Redis::bitcount(const StringView &key, long long start, long long end) { auto reply = command(cmd::bitcount, key, start, end); return reply::parse<long long>(*reply); } long long Redis::bitpos(const StringView &key, long long bit, long long start, long long end) { auto reply = command(cmd::bitpos, key, bit, start, end); return reply::parse<long long>(*reply); } long long Redis::decr(const StringView &key) { auto reply = command(cmd::decr, key); return reply::parse<long long>(*reply); } long long Redis::decrby(const StringView &key, long long decrement) { auto reply = command(cmd::decrby, key, decrement); return reply::parse<long long>(*reply); } OptionalString Redis::get(const StringView &key) { auto reply = command(cmd::get, key); return reply::parse<OptionalString>(*reply); } long long Redis::getbit(const StringView &key, long long offset) { auto reply = command(cmd::getbit, key, offset); return reply::parse<long long>(*reply); } std::string Redis::getrange(const StringView &key, long long start, long long end) { auto reply = command(cmd::getrange, key, start, end); return reply::parse<std::string>(*reply); } OptionalString Redis::getset(const StringView &key, const StringView &val) { auto reply = command(cmd::getset, key, val); return reply::parse<OptionalString>(*reply); } long long Redis::incr(const StringView &key) { auto reply = command(cmd::incr, key); return reply::parse<long long>(*reply); } long long Redis::incrby(const StringView &key, long long increment) { auto reply = command(cmd::incrby, key, increment); return reply::parse<long long>(*reply); } double Redis::incrbyfloat(const StringView &key, double increment) { auto reply = command(cmd::incrbyfloat, key, increment); return reply::parse<double>(*reply); } void Redis::psetex(const StringView &key, long long ttl, const StringView &val) { auto reply = command(cmd::psetex, key, ttl, val); reply::parse<void>(*reply); } bool Redis::set(const StringView &key, const StringView &val, const std::chrono::milliseconds &ttl, UpdateType type) { auto reply = command(cmd::set, key, val, ttl.count(), type); reply::rewrite_set_reply(*reply); return reply::parse<bool>(*reply); } void Redis::setex(const StringView &key, long long ttl, const StringView &val) { auto reply = command(cmd::setex, key, ttl, val); reply::parse<void>(*reply); } bool Redis::setnx(const StringView &key, const StringView &val) { auto reply = command(cmd::setnx, key, val); return reply::parse<bool>(*reply); } long long Redis::setrange(const StringView &key, long long offset, const StringView &val) { auto reply = command(cmd::setrange, key, offset, val); return reply::parse<long long>(*reply); } long long Redis::strlen(const StringView &key) { auto reply = command(cmd::strlen, key); return reply::parse<long long>(*reply); } // LIST commands. OptionalString Redis::brpoplpush(const StringView &source, const StringView &destination, long long timeout) { auto reply = command(cmd::brpoplpush, source, destination, timeout); return reply::parse<OptionalString>(*reply); } OptionalString Redis::lindex(const StringView &key, long long index) { auto reply = command(cmd::lindex, key, index); return reply::parse<OptionalString>(*reply); } long long Redis::linsert(const StringView &key, InsertPosition position, const StringView &pivot, const StringView &val) { auto reply = command(cmd::linsert, key, position, pivot, val); return reply::parse<long long>(*reply); } long long Redis::llen(const StringView &key) { auto reply = command(cmd::llen, key); return reply::parse<long long>(*reply); } OptionalString Redis::lpop(const StringView &key) { auto reply = command(cmd::lpop, key); return reply::parse<OptionalString>(*reply); } long long Redis::lpush(const StringView &key, const StringView &val) { auto reply = command(cmd::lpush, key, val); return reply::parse<long long>(*reply); } long long Redis::lpushx(const StringView &key, const StringView &val) { auto reply = command(cmd::lpushx, key, val); return reply::parse<long long>(*reply); } long long Redis::lrem(const StringView &key, long long count, const StringView &val) { auto reply = command(cmd::lrem, key, count, val); return reply::parse<long long>(*reply); } void Redis::lset(const StringView &key, long long index, const StringView &val) { auto reply = command(cmd::lset, key, index, val); reply::parse<void>(*reply); } void Redis::ltrim(const StringView &key, long long start, long long stop) { auto reply = command(cmd::ltrim, key, start, stop); reply::parse<void>(*reply); } OptionalString Redis::rpop(const StringView &key) { auto reply = command(cmd::rpop, key); return reply::parse<OptionalString>(*reply); } OptionalString Redis::rpoplpush(const StringView &source, const StringView &destination) { auto reply = command(cmd::rpoplpush, source, destination); return reply::parse<OptionalString>(*reply); } long long Redis::rpush(const StringView &key, const StringView &val) { auto reply = command(cmd::rpush, key, val); return reply::parse<long long>(*reply); } long long Redis::rpushx(const StringView &key, const StringView &val) { auto reply = command(cmd::rpushx, key, val); return reply::parse<long long>(*reply); } long long Redis::hdel(const StringView &key, const StringView &field) { auto reply = command(cmd::hdel, key, field); return reply::parse<long long>(*reply); } bool Redis::hexists(const StringView &key, const StringView &field) { auto reply = command(cmd::hexists, key, field); return reply::parse<bool>(*reply); } OptionalString Redis::hget(const StringView &key, const StringView &field) { auto reply = command(cmd::hget, key, field); return reply::parse<OptionalString>(*reply); } long long Redis::hincrby(const StringView &key, const StringView &field, long long increment) { auto reply = command(cmd::hincrby, key, field, increment); return reply::parse<long long>(*reply); } double Redis::hincrbyfloat(const StringView &key, const StringView &field, double increment) { auto reply = command(cmd::hincrbyfloat, key, field, increment); return reply::parse<double>(*reply); } long long Redis::hlen(const StringView &key) { auto reply = command(cmd::hlen, key); return reply::parse<long long>(*reply); } bool Redis::hset(const StringView &key, const StringView &field, const StringView &val) { auto reply = command(cmd::hset, key, field, val); return reply::parse<bool>(*reply); } bool Redis::hset(const StringView &key, const std::pair<StringView, StringView> &item) { return hset(key, item.first, item.second); } bool Redis::hsetnx(const StringView &key, const StringView &field, const StringView &val) { auto reply = command(cmd::hsetnx, key, field, val); return reply::parse<bool>(*reply); } bool Redis::hsetnx(const StringView &key, const std::pair<StringView, StringView> &item) { return hsetnx(key, item.first, item.second); } long long Redis::hstrlen(const StringView &key, const StringView &field) { auto reply = command(cmd::hstrlen, key, field); return reply::parse<long long>(*reply); } // SET commands. long long Redis::sadd(const StringView &key, const StringView &member) { auto reply = command(cmd::sadd, key, member); return reply::parse<long long>(*reply); } long long Redis::scard(const StringView &key) { auto reply = command(cmd::scard, key); return reply::parse<long long>(*reply); } bool Redis::sismember(const StringView &key, const StringView &member) { auto reply = command(cmd::sismember, key, member); return reply::parse<bool>(*reply); } bool Redis::smove(const StringView &source, const StringView &destination, const StringView &member) { auto reply = command(cmd::smove, source, destination, member); return reply::parse<bool>(*reply); } OptionalString Redis::spop(const StringView &key) { auto reply = command(cmd::spop, key); return reply::parse<OptionalString>(*reply); } OptionalString Redis::srandmember(const StringView &key) { auto reply = command(cmd::srandmember, key); return reply::parse<OptionalString>(*reply); } long long Redis::srem(const StringView &key, const StringView &member) { auto reply = command(cmd::srem, key, member); return reply::parse<long long>(*reply); } // SORTED SET commands. auto Redis::bzpopmax(const StringView &key, long long timeout) -> Optional<std::tuple<std::string, std::string, double>> { auto reply = command(cmd::bzpopmax, key, timeout); return reply::parse<Optional<std::tuple<std::string, std::string, double>>>(*reply); } auto Redis::bzpopmin(const StringView &key, long long timeout) -> Optional<std::tuple<std::string, std::string, double>> { auto reply = command(cmd::bzpopmin, key, timeout); return reply::parse<Optional<std::tuple<std::string, std::string, double>>>(*reply); } long long Redis::zadd(const StringView &key, const StringView &member, double score, UpdateType type, bool changed) { auto reply = command(cmd::zadd, key, member, score, type, changed); return reply::parse<long long>(*reply); } long long Redis::zcard(const StringView &key) { auto reply = command(cmd::zcard, key); return reply::parse<long long>(*reply); } double Redis::zincrby(const StringView &key, double increment, const StringView &member) { auto reply = command(cmd::zincrby, key, increment, member); return reply::parse<double>(*reply); } Optional<std::pair<std::string, double>> Redis::zpopmax(const StringView &key) { auto reply = command(cmd::zpopmax, key, 1); return reply::parse<Optional<std::pair<std::string, double>>>(*reply); } Optional<std::pair<std::string, double>> Redis::zpopmin(const StringView &key) { auto reply = command(cmd::zpopmin, key, 1); return reply::parse<Optional<std::pair<std::string, double>>>(*reply); } OptionalLongLong Redis::zrank(const StringView &key, const StringView &member) { auto reply = command(cmd::zrank, key, member); return reply::parse<OptionalLongLong>(*reply); } long long Redis::zrem(const StringView &key, const StringView &member) { auto reply = command(cmd::zrem, key, member); return reply::parse<long long>(*reply); } long long Redis::zremrangebyrank(const StringView &key, long long start, long long stop) { auto reply = command(cmd::zremrangebyrank, key, start, stop); return reply::parse<long long>(*reply); } OptionalLongLong Redis::zrevrank(const StringView &key, const StringView &member) { auto reply = command(cmd::zrevrank, key, member); return reply::parse<OptionalLongLong>(*reply); } OptionalDouble Redis::zscore(const StringView &key, const StringView &member) { auto reply = command(cmd::zscore, key, member); return reply::parse<OptionalDouble>(*reply); } // HYPERLOGLOG commands. bool Redis::pfadd(const StringView &key, const StringView &element) { auto reply = command(cmd::pfadd, key, element); return reply::parse<bool>(*reply); } long long Redis::pfcount(const StringView &key) { auto reply = command(cmd::pfcount, key); return reply::parse<long long>(*reply); } // GEO commands. long long Redis::geoadd(const StringView &key, const std::tuple<StringView, double, double> &member) { auto reply = command(cmd::geoadd, key, member); return reply::parse<long long>(*reply); } OptionalDouble Redis::geodist(const StringView &key, const StringView &member1, const StringView &member2, GeoUnit unit) { auto reply = command(cmd::geodist, key, member1, member2, unit); return reply::parse<OptionalDouble>(*reply); } OptionalLongLong Redis::georadius(const StringView &key, const std::pair<double, double> &loc, double radius, GeoUnit unit, const StringView &destination, bool store_dist, long long count) { auto reply = command(cmd::georadius_store, key, loc, radius, unit, destination, store_dist, count); reply::rewrite_georadius_reply(*reply); return reply::parse<OptionalLongLong>(*reply); } OptionalLongLong Redis::georadiusbymember(const StringView &key, const StringView &member, double radius, GeoUnit unit, const StringView &destination, bool store_dist, long long count) { auto reply = command(cmd::georadiusbymember_store, key, member, radius, unit, destination, store_dist, count); reply::rewrite_georadius_reply(*reply); return reply::parse<OptionalLongLong>(*reply); } // SCRIPTING commands. void Redis::script_flush() { auto reply = command(cmd::script_flush); reply::parse<void>(*reply); } void Redis::script_kill() { auto reply = command(cmd::script_kill); reply::parse<void>(*reply); } std::string Redis::script_load(const StringView &script) { auto reply = command(cmd::script_load, script); return reply::parse<std::string>(*reply); } // PUBSUB commands. long long Redis::publish(const StringView &channel, const StringView &message) { auto reply = command(cmd::publish, channel, message); return reply::parse<long long>(*reply); } // Transaction commands. void Redis::watch(const StringView &key) { auto reply = command(cmd::watch, key); reply::parse<void>(*reply); } } }
75bbf1d5f11b3b88e6f54f7e11e8eee26a0ccc52
fec2ee4e113fe948c9fd82a645ec196d05e187d2
/ros/melodic/x64/include/pcl_ros/VoxelGridConfig.h
1f9e85bca964db4e2cd11a06e90b2a3845f97e1e
[]
no_license
gptshubham595/ROS-WINDOWS-FILES
9c76690b087ebe2662df190b4b486af1af935e8b
1d421802c296b5ee83453057ec76567047acc07a
refs/heads/master
2020-07-01T23:11:57.317818
2019-09-18T20:23:36
2019-09-18T20:23:36
201,327,393
0
0
null
null
null
null
UTF-8
C++
false
false
29,732
h
//#line 2 "D:/opt/ros/melodic/x64/share/dynamic_reconfigure/cmake/..\\templates\\ConfigType.h.template" // ********************************************************* // // File autogenerated for the pcl_ros package // by the dynamic_reconfigure package. // Please do not edit. // // ********************************************************/ #ifndef __pcl_ros__VOXELGRIDCONFIG_H__ #define __pcl_ros__VOXELGRIDCONFIG_H__ #if __cplusplus >= 201103L #define DYNAMIC_RECONFIGURE_FINAL final #else #define DYNAMIC_RECONFIGURE_FINAL #endif #include <dynamic_reconfigure/config_tools.h> #include <limits> #include <ros/node_handle.h> #include <dynamic_reconfigure/ConfigDescription.h> #include <dynamic_reconfigure/ParamDescription.h> #include <dynamic_reconfigure/Group.h> #include <dynamic_reconfigure/config_init_mutex.h> #include <boost/any.hpp> namespace pcl_ros { class VoxelGridConfigStatics; class VoxelGridConfig { public: class AbstractParamDescription : public dynamic_reconfigure::ParamDescription { public: AbstractParamDescription(std::string n, std::string t, uint32_t l, std::string d, std::string e) { name = n; type = t; level = l; description = d; edit_method = e; } virtual void clamp(VoxelGridConfig &config, const VoxelGridConfig &max, const VoxelGridConfig &min) const = 0; virtual void calcLevel(uint32_t &level, const VoxelGridConfig &config1, const VoxelGridConfig &config2) const = 0; virtual void fromServer(const ros::NodeHandle &nh, VoxelGridConfig &config) const = 0; virtual void toServer(const ros::NodeHandle &nh, const VoxelGridConfig &config) const = 0; virtual bool fromMessage(const dynamic_reconfigure::Config &msg, VoxelGridConfig &config) const = 0; virtual void toMessage(dynamic_reconfigure::Config &msg, const VoxelGridConfig &config) const = 0; virtual void getValue(const VoxelGridConfig &config, boost::any &val) const = 0; }; typedef boost::shared_ptr<AbstractParamDescription> AbstractParamDescriptionPtr; typedef boost::shared_ptr<const AbstractParamDescription> AbstractParamDescriptionConstPtr; // Final keyword added to class because it has virtual methods and inherits // from a class with a non-virtual destructor. template <class T> class ParamDescription DYNAMIC_RECONFIGURE_FINAL : public AbstractParamDescription { public: ParamDescription(std::string a_name, std::string a_type, uint32_t a_level, std::string a_description, std::string a_edit_method, T VoxelGridConfig::* a_f) : AbstractParamDescription(a_name, a_type, a_level, a_description, a_edit_method), field(a_f) {} T VoxelGridConfig::* field; virtual void clamp(VoxelGridConfig &config, const VoxelGridConfig &max, const VoxelGridConfig &min) const { if (config.*field > max.*field) config.*field = max.*field; if (config.*field < min.*field) config.*field = min.*field; } virtual void calcLevel(uint32_t &comb_level, const VoxelGridConfig &config1, const VoxelGridConfig &config2) const { if (config1.*field != config2.*field) comb_level |= level; } virtual void fromServer(const ros::NodeHandle &nh, VoxelGridConfig &config) const { nh.getParam(name, config.*field); } virtual void toServer(const ros::NodeHandle &nh, const VoxelGridConfig &config) const { nh.setParam(name, config.*field); } virtual bool fromMessage(const dynamic_reconfigure::Config &msg, VoxelGridConfig &config) const { return dynamic_reconfigure::ConfigTools::getParameter(msg, name, config.*field); } virtual void toMessage(dynamic_reconfigure::Config &msg, const VoxelGridConfig &config) const { dynamic_reconfigure::ConfigTools::appendParameter(msg, name, config.*field); } virtual void getValue(const VoxelGridConfig &config, boost::any &val) const { val = config.*field; } }; class AbstractGroupDescription : public dynamic_reconfigure::Group { public: AbstractGroupDescription(std::string n, std::string t, int p, int i, bool s) { name = n; type = t; parent = p; state = s; id = i; } std::vector<AbstractParamDescriptionConstPtr> abstract_parameters; bool state; virtual void toMessage(dynamic_reconfigure::Config &msg, const boost::any &config) const = 0; virtual bool fromMessage(const dynamic_reconfigure::Config &msg, boost::any &config) const =0; virtual void updateParams(boost::any &cfg, VoxelGridConfig &top) const= 0; virtual void setInitialState(boost::any &cfg) const = 0; void convertParams() { for(std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = abstract_parameters.begin(); i != abstract_parameters.end(); ++i) { parameters.push_back(dynamic_reconfigure::ParamDescription(**i)); } } }; typedef boost::shared_ptr<AbstractGroupDescription> AbstractGroupDescriptionPtr; typedef boost::shared_ptr<const AbstractGroupDescription> AbstractGroupDescriptionConstPtr; // Final keyword added to class because it has virtual methods and inherits // from a class with a non-virtual destructor. template<class T, class PT> class GroupDescription DYNAMIC_RECONFIGURE_FINAL : public AbstractGroupDescription { public: GroupDescription(std::string a_name, std::string a_type, int a_parent, int a_id, bool a_s, T PT::* a_f) : AbstractGroupDescription(a_name, a_type, a_parent, a_id, a_s), field(a_f) { } GroupDescription(const GroupDescription<T, PT>& g): AbstractGroupDescription(g.name, g.type, g.parent, g.id, g.state), field(g.field), groups(g.groups) { parameters = g.parameters; abstract_parameters = g.abstract_parameters; } virtual bool fromMessage(const dynamic_reconfigure::Config &msg, boost::any &cfg) const { PT* config = boost::any_cast<PT*>(cfg); if(!dynamic_reconfigure::ConfigTools::getGroupState(msg, name, (*config).*field)) return false; for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i) { boost::any n = &((*config).*field); if(!(*i)->fromMessage(msg, n)) return false; } return true; } virtual void setInitialState(boost::any &cfg) const { PT* config = boost::any_cast<PT*>(cfg); T* group = &((*config).*field); group->state = state; for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i) { boost::any n = boost::any(&((*config).*field)); (*i)->setInitialState(n); } } virtual void updateParams(boost::any &cfg, VoxelGridConfig &top) const { PT* config = boost::any_cast<PT*>(cfg); T* f = &((*config).*field); f->setParams(top, abstract_parameters); for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i) { boost::any n = &((*config).*field); (*i)->updateParams(n, top); } } virtual void toMessage(dynamic_reconfigure::Config &msg, const boost::any &cfg) const { const PT config = boost::any_cast<PT>(cfg); dynamic_reconfigure::ConfigTools::appendGroup<T>(msg, name, id, parent, config.*field); for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i) { (*i)->toMessage(msg, config.*field); } } T PT::* field; std::vector<VoxelGridConfig::AbstractGroupDescriptionConstPtr> groups; }; class DEFAULT { public: DEFAULT() { state = true; name = "Default"; } void setParams(VoxelGridConfig &config, const std::vector<AbstractParamDescriptionConstPtr> params) { for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator _i = params.begin(); _i != params.end(); ++_i) { boost::any val; (*_i)->getValue(config, val); if("leaf_size"==(*_i)->name){leaf_size = boost::any_cast<double>(val);} if("filter_field_name"==(*_i)->name){filter_field_name = boost::any_cast<std::string>(val);} if("filter_limit_min"==(*_i)->name){filter_limit_min = boost::any_cast<double>(val);} if("filter_limit_max"==(*_i)->name){filter_limit_max = boost::any_cast<double>(val);} if("filter_limit_negative"==(*_i)->name){filter_limit_negative = boost::any_cast<bool>(val);} if("keep_organized"==(*_i)->name){keep_organized = boost::any_cast<bool>(val);} if("input_frame"==(*_i)->name){input_frame = boost::any_cast<std::string>(val);} if("output_frame"==(*_i)->name){output_frame = boost::any_cast<std::string>(val);} } } double leaf_size; std::string filter_field_name; double filter_limit_min; double filter_limit_max; bool filter_limit_negative; bool keep_organized; std::string input_frame; std::string output_frame; bool state; std::string name; }groups; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" double leaf_size; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" std::string filter_field_name; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" double filter_limit_min; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" double filter_limit_max; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" bool filter_limit_negative; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" bool keep_organized; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" std::string input_frame; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" std::string output_frame; //#line 228 "D:/opt/ros/melodic/x64/share/dynamic_reconfigure/cmake/..\\templates\\ConfigType.h.template" bool __fromMessage__(dynamic_reconfigure::Config &msg) { const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__(); const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__ = __getGroupDescriptions__(); int count = 0; for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i) if ((*i)->fromMessage(msg, *this)) count++; for (std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); i ++) { if ((*i)->id == 0) { boost::any n = boost::any(this); (*i)->updateParams(n, *this); (*i)->fromMessage(msg, n); } } if (count != dynamic_reconfigure::ConfigTools::size(msg)) { ROS_ERROR("VoxelGridConfig::__fromMessage__ called with an unexpected parameter."); ROS_ERROR("Booleans:"); for (unsigned int i = 0; i < msg.bools.size(); i++) ROS_ERROR(" %s", msg.bools[i].name.c_str()); ROS_ERROR("Integers:"); for (unsigned int i = 0; i < msg.ints.size(); i++) ROS_ERROR(" %s", msg.ints[i].name.c_str()); ROS_ERROR("Doubles:"); for (unsigned int i = 0; i < msg.doubles.size(); i++) ROS_ERROR(" %s", msg.doubles[i].name.c_str()); ROS_ERROR("Strings:"); for (unsigned int i = 0; i < msg.strs.size(); i++) ROS_ERROR(" %s", msg.strs[i].name.c_str()); // @todo Check that there are no duplicates. Make this error more // explicit. return false; } return true; } // This version of __toMessage__ is used during initialization of // statics when __getParamDescriptions__ can't be called yet. void __toMessage__(dynamic_reconfigure::Config &msg, const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__, const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__) const { dynamic_reconfigure::ConfigTools::clear(msg); for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i) (*i)->toMessage(msg, *this); for (std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); ++i) { if((*i)->id == 0) { (*i)->toMessage(msg, *this); } } } void __toMessage__(dynamic_reconfigure::Config &msg) const { const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__(); const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__ = __getGroupDescriptions__(); __toMessage__(msg, __param_descriptions__, __group_descriptions__); } void __toServer__(const ros::NodeHandle &nh) const { const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__(); for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i) (*i)->toServer(nh, *this); } void __fromServer__(const ros::NodeHandle &nh) { static bool setup=false; const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__(); for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i) (*i)->fromServer(nh, *this); const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__ = __getGroupDescriptions__(); for (std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); i++){ if (!setup && (*i)->id == 0) { setup = true; boost::any n = boost::any(this); (*i)->setInitialState(n); } } } void __clamp__() { const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__(); const VoxelGridConfig &__max__ = __getMax__(); const VoxelGridConfig &__min__ = __getMin__(); for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i) (*i)->clamp(*this, __max__, __min__); } uint32_t __level__(const VoxelGridConfig &config) const { const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__(); uint32_t level = 0; for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i) (*i)->calcLevel(level, config, *this); return level; } static const dynamic_reconfigure::ConfigDescription &__getDescriptionMessage__(); static const VoxelGridConfig &__getDefault__(); static const VoxelGridConfig &__getMax__(); static const VoxelGridConfig &__getMin__(); static const std::vector<AbstractParamDescriptionConstPtr> &__getParamDescriptions__(); static const std::vector<AbstractGroupDescriptionConstPtr> &__getGroupDescriptions__(); private: static const VoxelGridConfigStatics *__get_statics__(); }; template <> // Max and min are ignored for strings. inline void VoxelGridConfig::ParamDescription<std::string>::clamp(VoxelGridConfig &config, const VoxelGridConfig &max, const VoxelGridConfig &min) const { (void) config; (void) min; (void) max; return; } class VoxelGridConfigStatics { friend class VoxelGridConfig; VoxelGridConfigStatics() { VoxelGridConfig::GroupDescription<VoxelGridConfig::DEFAULT, VoxelGridConfig> Default("Default", "", 0, 0, true, &VoxelGridConfig::groups); //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __min__.leaf_size = 0.0; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __max__.leaf_size = 1.0; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __default__.leaf_size = 0.01; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" Default.abstract_parameters.push_back(VoxelGridConfig::AbstractParamDescriptionConstPtr(new VoxelGridConfig::ParamDescription<double>("leaf_size", "double", 0, "The size of a leaf (on x,y,z) used for downsampling.", "", &VoxelGridConfig::leaf_size))); //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __param_descriptions__.push_back(VoxelGridConfig::AbstractParamDescriptionConstPtr(new VoxelGridConfig::ParamDescription<double>("leaf_size", "double", 0, "The size of a leaf (on x,y,z) used for downsampling.", "", &VoxelGridConfig::leaf_size))); //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __min__.filter_field_name = ""; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __max__.filter_field_name = ""; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __default__.filter_field_name = "z"; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" Default.abstract_parameters.push_back(VoxelGridConfig::AbstractParamDescriptionConstPtr(new VoxelGridConfig::ParamDescription<std::string>("filter_field_name", "str", 0, "The field name used for filtering", "", &VoxelGridConfig::filter_field_name))); //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __param_descriptions__.push_back(VoxelGridConfig::AbstractParamDescriptionConstPtr(new VoxelGridConfig::ParamDescription<std::string>("filter_field_name", "str", 0, "The field name used for filtering", "", &VoxelGridConfig::filter_field_name))); //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __min__.filter_limit_min = -100000.0; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __max__.filter_limit_min = 100000.0; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __default__.filter_limit_min = 0.0; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" Default.abstract_parameters.push_back(VoxelGridConfig::AbstractParamDescriptionConstPtr(new VoxelGridConfig::ParamDescription<double>("filter_limit_min", "double", 0, "The minimum allowed field value a point will be considered from", "", &VoxelGridConfig::filter_limit_min))); //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __param_descriptions__.push_back(VoxelGridConfig::AbstractParamDescriptionConstPtr(new VoxelGridConfig::ParamDescription<double>("filter_limit_min", "double", 0, "The minimum allowed field value a point will be considered from", "", &VoxelGridConfig::filter_limit_min))); //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __min__.filter_limit_max = -100000.0; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __max__.filter_limit_max = 100000.0; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __default__.filter_limit_max = 1.0; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" Default.abstract_parameters.push_back(VoxelGridConfig::AbstractParamDescriptionConstPtr(new VoxelGridConfig::ParamDescription<double>("filter_limit_max", "double", 0, "The maximum allowed field value a point will be considered from", "", &VoxelGridConfig::filter_limit_max))); //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __param_descriptions__.push_back(VoxelGridConfig::AbstractParamDescriptionConstPtr(new VoxelGridConfig::ParamDescription<double>("filter_limit_max", "double", 0, "The maximum allowed field value a point will be considered from", "", &VoxelGridConfig::filter_limit_max))); //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __min__.filter_limit_negative = 0; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __max__.filter_limit_negative = 1; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __default__.filter_limit_negative = 0; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" Default.abstract_parameters.push_back(VoxelGridConfig::AbstractParamDescriptionConstPtr(new VoxelGridConfig::ParamDescription<bool>("filter_limit_negative", "bool", 0, "Set to true if we want to return the data outside [filter_limit_min; filter_limit_max].", "", &VoxelGridConfig::filter_limit_negative))); //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __param_descriptions__.push_back(VoxelGridConfig::AbstractParamDescriptionConstPtr(new VoxelGridConfig::ParamDescription<bool>("filter_limit_negative", "bool", 0, "Set to true if we want to return the data outside [filter_limit_min; filter_limit_max].", "", &VoxelGridConfig::filter_limit_negative))); //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __min__.keep_organized = 0; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __max__.keep_organized = 1; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __default__.keep_organized = 0; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" Default.abstract_parameters.push_back(VoxelGridConfig::AbstractParamDescriptionConstPtr(new VoxelGridConfig::ParamDescription<bool>("keep_organized", "bool", 0, "Set whether the filtered points should be kept and set to NaN, or removed from the PointCloud, thus potentially breaking its organized structure.", "", &VoxelGridConfig::keep_organized))); //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __param_descriptions__.push_back(VoxelGridConfig::AbstractParamDescriptionConstPtr(new VoxelGridConfig::ParamDescription<bool>("keep_organized", "bool", 0, "Set whether the filtered points should be kept and set to NaN, or removed from the PointCloud, thus potentially breaking its organized structure.", "", &VoxelGridConfig::keep_organized))); //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __min__.input_frame = ""; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __max__.input_frame = ""; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __default__.input_frame = ""; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" Default.abstract_parameters.push_back(VoxelGridConfig::AbstractParamDescriptionConstPtr(new VoxelGridConfig::ParamDescription<std::string>("input_frame", "str", 0, "The input TF frame the data should be transformed into before processing, if input.header.frame_id is different.", "", &VoxelGridConfig::input_frame))); //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __param_descriptions__.push_back(VoxelGridConfig::AbstractParamDescriptionConstPtr(new VoxelGridConfig::ParamDescription<std::string>("input_frame", "str", 0, "The input TF frame the data should be transformed into before processing, if input.header.frame_id is different.", "", &VoxelGridConfig::input_frame))); //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __min__.output_frame = ""; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __max__.output_frame = ""; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __default__.output_frame = ""; //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" Default.abstract_parameters.push_back(VoxelGridConfig::AbstractParamDescriptionConstPtr(new VoxelGridConfig::ParamDescription<std::string>("output_frame", "str", 0, "The output TF frame the data should be transformed into after processing, if input.header.frame_id is different.", "", &VoxelGridConfig::output_frame))); //#line 291 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __param_descriptions__.push_back(VoxelGridConfig::AbstractParamDescriptionConstPtr(new VoxelGridConfig::ParamDescription<std::string>("output_frame", "str", 0, "The output TF frame the data should be transformed into after processing, if input.header.frame_id is different.", "", &VoxelGridConfig::output_frame))); //#line 246 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" Default.convertParams(); //#line 246 "C:\opt\ros\melodic\x64\lib\site-packages\dynamic_reconfigure\parameter_generator_catkin.py" __group_descriptions__.push_back(VoxelGridConfig::AbstractGroupDescriptionConstPtr(new VoxelGridConfig::GroupDescription<VoxelGridConfig::DEFAULT, VoxelGridConfig>(Default))); //#line 366 "D:/opt/ros/melodic/x64/share/dynamic_reconfigure/cmake/..\\templates\\ConfigType.h.template" for (std::vector<VoxelGridConfig::AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); ++i) { __description_message__.groups.push_back(**i); } __max__.__toMessage__(__description_message__.max, __param_descriptions__, __group_descriptions__); __min__.__toMessage__(__description_message__.min, __param_descriptions__, __group_descriptions__); __default__.__toMessage__(__description_message__.dflt, __param_descriptions__, __group_descriptions__); } std::vector<VoxelGridConfig::AbstractParamDescriptionConstPtr> __param_descriptions__; std::vector<VoxelGridConfig::AbstractGroupDescriptionConstPtr> __group_descriptions__; VoxelGridConfig __max__; VoxelGridConfig __min__; VoxelGridConfig __default__; dynamic_reconfigure::ConfigDescription __description_message__; static const VoxelGridConfigStatics *get_instance() { // Split this off in a separate function because I know that // instance will get initialized the first time get_instance is // called, and I am guaranteeing that get_instance gets called at // most once. static VoxelGridConfigStatics instance; return &instance; } }; inline const dynamic_reconfigure::ConfigDescription &VoxelGridConfig::__getDescriptionMessage__() { return __get_statics__()->__description_message__; } inline const VoxelGridConfig &VoxelGridConfig::__getDefault__() { return __get_statics__()->__default__; } inline const VoxelGridConfig &VoxelGridConfig::__getMax__() { return __get_statics__()->__max__; } inline const VoxelGridConfig &VoxelGridConfig::__getMin__() { return __get_statics__()->__min__; } inline const std::vector<VoxelGridConfig::AbstractParamDescriptionConstPtr> &VoxelGridConfig::__getParamDescriptions__() { return __get_statics__()->__param_descriptions__; } inline const std::vector<VoxelGridConfig::AbstractGroupDescriptionConstPtr> &VoxelGridConfig::__getGroupDescriptions__() { return __get_statics__()->__group_descriptions__; } inline const VoxelGridConfigStatics *VoxelGridConfig::__get_statics__() { const static VoxelGridConfigStatics *statics; if (statics) // Common case return statics; boost::mutex::scoped_lock lock(dynamic_reconfigure::__init_mutex__); if (statics) // In case we lost a race. return statics; statics = VoxelGridConfigStatics::get_instance(); return statics; } } #undef DYNAMIC_RECONFIGURE_FINAL #endif // __VOXELGRIDRECONFIGURATOR_H__
feb2ea4a82a000a0bb43632b9698545185d3e0af
8463eb4cddf926397551da0ce879729cfdf5013d
/main.cpp
f38cedfeae0fbcd7fa0b1e91249556c7811ba812
[ "MIT" ]
permissive
macstepien/2DRacing
a50039f4fc8ce2a1878af9a8f4b1539dc460054c
249fd5fa3533f578557bca318b4577fca406f826
refs/heads/master
2021-10-16T18:54:12.058592
2019-02-12T17:41:42
2019-02-12T17:41:42
null
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
437
cpp
/* Author: Maciej Stępień Copyright(c) 2012-2013 Maciej Stępień Version: pre-beta */ #include <SFML/Graphics.hpp> #include <cmath> #include <cstdio> #include <fstream> #include "gra.h" sf::Event event; sf::RenderWindow window(sf::VideoMode(640, 480, 32), "2DRacing", sf::Style::Close); const sf::Input& wejscie = window.GetInput(); Gra gra1(window); int main() { gra1.Main(wejscie, event, window); return 0; }
168475256c4011f29f917a036a7fcd618a90ec5d
5ef7887a7aefbbf536047c59052f99d9039590e3
/src/components/application_manager/src/commands/command_notification_impl.cc
c99f2d90862d5b6d3f0f01c181ce1f248f9b4345
[]
no_license
smartdevice475/sdl_core_v4.0_winceport
8b2ce9118635bf33700f71c5a87ceed668db1b7f
1cdc30551eb58b0e1e3b4de8c0a0c66f975cf534
refs/heads/master
2021-01-24T20:52:42.830355
2016-11-29T06:22:16
2016-11-29T06:22:16
73,656,016
1
2
null
2016-11-14T01:37:46
2016-11-14T01:37:46
null
UTF-8
C++
false
false
2,648
cc
/* Copyright (c) 2013, Ford Motor Company 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 Ford Motor Company nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "application_manager/commands/command_notification_impl.h" #include "application_manager/application_manager_impl.h" #include "application_manager/message_helper.h" namespace application_manager { namespace commands { CommandNotificationImpl::CommandNotificationImpl( const MessageSharedPtr& message) : CommandImpl(message) { } CommandNotificationImpl::~CommandNotificationImpl() { } bool CommandNotificationImpl::Init() { return true; } bool CommandNotificationImpl::CleanUp() { return true; } void CommandNotificationImpl::Run() { } void CommandNotificationImpl::SendNotification() { (*message_)[strings::params][strings::protocol_type] = mobile_protocol_type_; (*message_)[strings::params][strings::protocol_version] = protocol_version_; (*message_)[strings::params][strings::message_type] = static_cast<int32_t>(application_manager::MessageType::kNotification); LOG4CXX_INFO(logger_, "SendNotification"); MessageHelper::PrintSmartObject(*message_); ApplicationManagerImpl::instance()->SendMessageToMobile(message_); } } // namespace commands } // namespace application_manager
68b8054435499f4cd1303be019ea2a022dbc6b39
b2fb1c10bba0a97bbde769c199caa3e259d5a1ab
/window.hxx
c9f8390b7626179e5500787896e749b3d7f2e491
[]
no_license
jjzhang166/vclinclude
300fccdac1a9df882a8ff0839d0a93981b9512ec
b92eff23de03206d3d636d6f5bc9d57ca0684b5d
refs/heads/master
2021-12-05T13:43:43.321965
2015-07-01T14:09:08
2015-07-01T14:09:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
64,613
hxx
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_VCL_WINDOW_HXX #define INCLUDED_VCL_WINDOW_HXX #include <tools/solar.h> #include <vcl/dllapi.h> #include <vcl/outdev.hxx> #include <tools/resid.hxx> #include <vcl/pointr.hxx> #include <tools/wintypes.hxx> #include <rsc/rsc-vcl-shared-types.hxx> #include <vcl/apptypes.hxx> #include <vcl/inputctx.hxx> #include <vcl/vclevent.hxx> // Only for compatibility - because many people outside haven't included event.hxx #include <vcl/event.hxx> #include <vcl/region.hxx> #include <vcl/salnativewidgets.hxx> #include <rtl/ustring.hxx> #include <cppuhelper/weakref.hxx> #include <com/sun/star/uno/Reference.hxx> #include <boost/shared_ptr.hpp> class VirtualDevice; struct ImplDelData; struct ImplSVEvent; struct ImplWinData; struct ImplFrameData; struct ImplCalcToTopData; struct SystemEnvData; struct SystemParentData; class ImplBorderWindow; class Timer; class Cursor; class DockingManager; class ScrollBar; class Bitmap; class FixedText; class Image; class MouseEvent; class KeyEvent; class CommandEvent; class TrackingEvent; class HelpEvent; class DataChangedEvent; class NotifyEvent; class SystemWindow; class SalFrame; class MenuFloatingWindow; class VCLXWindow; namespace com { namespace sun { namespace star { namespace accessibility { class XAccessible; }}}} namespace com { namespace sun { namespace star { namespace beans { struct PropertyValue; }}}} namespace com { namespace sun { namespace star { namespace rendering { class XCanvas; class XSpriteCanvas; }}}} namespace com { namespace sun { namespace star { namespace awt { class XWindowPeer; class XWindow; } namespace uno { class Any; class XInterface; } namespace datatransfer { namespace clipboard { class XClipboard; } namespace dnd { class XDragGestureRecognizer; class XDragSource; class XDropTarget; } } } } } namespace vcl { struct ControlLayoutData; } namespace svt { class PopupWindowControllerImpl; } // - WindowTypes - // Type fuer GetWindow() #define WINDOW_PARENT ((sal_uInt16)0) #define WINDOW_FIRSTCHILD ((sal_uInt16)1) #define WINDOW_LASTCHILD ((sal_uInt16)2) #define WINDOW_PREV ((sal_uInt16)3) #define WINDOW_NEXT ((sal_uInt16)4) #define WINDOW_FIRSTOVERLAP ((sal_uInt16)5) #define WINDOW_LASTOVERLAP ((sal_uInt16)6) #define WINDOW_OVERLAP ((sal_uInt16)7) #define WINDOW_PARENTOVERLAP ((sal_uInt16)8) #define WINDOW_CLIENT ((sal_uInt16)9) #define WINDOW_REALPARENT ((sal_uInt16)10) #define WINDOW_FRAME ((sal_uInt16)11) #define WINDOW_BORDER ((sal_uInt16)12) #define WINDOW_FIRSTTOPWINDOWCHILD ((sal_uInt16)13) #define WINDOW_LASTTOPWINDOWCHILD ((sal_uInt16)14) #define WINDOW_PREVTOPWINDOWSIBLING ((sal_uInt16)15) #define WINDOW_NEXTTOPWINDOWSIBLING ((sal_uInt16)16) // Flags for setPosSizePixel() #define WINDOW_POSSIZE_X ((sal_uInt16)0x0001) #define WINDOW_POSSIZE_Y ((sal_uInt16)0x0002) #define WINDOW_POSSIZE_WIDTH ((sal_uInt16)0x0004) #define WINDOW_POSSIZE_HEIGHT ((sal_uInt16)0x0008) #define WINDOW_POSSIZE_POS (WINDOW_POSSIZE_X | WINDOW_POSSIZE_Y) #define WINDOW_POSSIZE_SIZE (WINDOW_POSSIZE_WIDTH | WINDOW_POSSIZE_HEIGHT) #define WINDOW_POSSIZE_POSSIZE (WINDOW_POSSIZE_POS | WINDOW_POSSIZE_SIZE) #define WINDOW_POSSIZE_ALL (WINDOW_POSSIZE_POSSIZE) #define WINDOW_POSSIZE_DROPDOWN ((sal_uInt16)0x0010) // Flags for Show() #define SHOW_NOPARENTUPDATE ((sal_uInt16)0x0001) #define SHOW_NOFOCUSCHANGE ((sal_uInt16)0x0002) #define SHOW_NOACTIVATE ((sal_uInt16)0x0004) #define SHOW_FOREGROUNDTASK ((sal_uInt16)0x0008) // Flags for SetZOrder() #define WINDOW_ZORDER_BEFOR ((sal_uInt16)0x0001) #define WINDOW_ZORDER_BEHIND ((sal_uInt16)0x0002) #define WINDOW_ZORDER_FIRST ((sal_uInt16)0x0004) #define WINDOW_ZORDER_LAST ((sal_uInt16)0x0008) // Activate-Flags #define ACTIVATE_MODE_GRABFOCUS ((sal_uInt16)0x0001) // ToTop-Flags #define TOTOP_RESTOREWHENMIN ((sal_uInt16)0x0001) #define TOTOP_FOREGROUNDTASK ((sal_uInt16)0x0002) #define TOTOP_NOGRABFOCUS ((sal_uInt16)0x0004) #define TOTOP_GRABFOCUSONLY ((sal_uInt16)0x0008) // Flags for Invalidate #define INVALIDATE_CHILDREN ((sal_uInt16)0x0001) #define INVALIDATE_NOCHILDREN ((sal_uInt16)0x0002) #define INVALIDATE_NOERASE ((sal_uInt16)0x0004) #define INVALIDATE_UPDATE ((sal_uInt16)0x0008) #define INVALIDATE_TRANSPARENT ((sal_uInt16)0x0010) #define INVALIDATE_NOTRANSPARENT ((sal_uInt16)0x0020) #define INVALIDATE_NOCLIPCHILDREN ((sal_uInt16)0x4000) // Temporaer fuer Kompatibilitaet #define INVALIDATE_BACKGROUND INVALIDATE_TRANSPARENT // Flags for Validate #define VALIDATE_CHILDREN ((sal_uInt16)0x0001) #define VALIDATE_NOCHILDREN ((sal_uInt16)0x0002) // Flags for Scroll #define SCROLL_CLIP ((sal_uInt16)0x0001) #define SCROLL_CHILDREN ((sal_uInt16)0x0002) #define SCROLL_NOCHILDREN ((sal_uInt16)0x0004) #define SCROLL_NOERASE ((sal_uInt16)0x0008) #define SCROLL_NOINVALIDATE ((sal_uInt16)0x0010) #define SCROLL_NOWINDOWINVALIDATE ((sal_uInt16)0x0020) #define SCROLL_USECLIPREGION ((sal_uInt16)0x0040) #define SCROLL_UPDATE ((sal_uInt16)0x0080) // Flags for ParentClipMode #define PARENTCLIPMODE_CLIP ((sal_uInt16)0x0001) #define PARENTCLIPMODE_NOCLIP ((sal_uInt16)0x0002) // Flags for Invert() #define INVERT_HIGHLIGHT ((sal_uInt16)0x0001) #define INVERT_50 ((sal_uInt16)0x0002) // Flags for ShowTracking() #define SHOWTRACK_SMALL ((sal_uInt16)0x0001) #define SHOWTRACK_BIG ((sal_uInt16)0x0002) #define SHOWTRACK_SPLIT ((sal_uInt16)0x0003) #define SHOWTRACK_OBJECT ((sal_uInt16)0x0004) #define SHOWTRACK_WINDOW ((sal_uInt16)0x1000) #define SHOWTRACK_CLIP ((sal_uInt16)0x2000) #define SHOWTRACK_STYLE ((sal_uInt16)0x000F) // Flags for StartTracking() #define STARTTRACK_KEYINPUT ((sal_uInt16)0x0001) #define STARTTRACK_KEYMOD ((sal_uInt16)0x0002) #define STARTTRACK_NOKEYCANCEL ((sal_uInt16)0x0004) #define STARTTRACK_SCROLLREPEAT ((sal_uInt16)0x0008) #define STARTTRACK_BUTTONREPEAT ((sal_uInt16)0x0010) #define STARTTRACK_MOUSEBUTTONDOWN ((sal_uInt16)0x0020) #define STARTTRACK_FOCUSCANCEL ((sal_uInt16)0x0040) // Flags for StartAutoScroll() #define AUTOSCROLL_VERT ((sal_uInt16)0x0001) #define AUTOSCROLL_HORZ ((sal_uInt16)0x0002) // Flags for StateChanged() typedef sal_uInt16 StateChangedType; #define STATE_CHANGE_INITSHOW ((StateChangedType)1) #define STATE_CHANGE_VISIBLE ((StateChangedType)2) #define STATE_CHANGE_UPDATEMODE ((StateChangedType)3) #define STATE_CHANGE_ENABLE ((StateChangedType)4) #define STATE_CHANGE_TEXT ((StateChangedType)5) #define STATE_CHANGE_IMAGE ((StateChangedType)6) #define STATE_CHANGE_DATA ((StateChangedType)7) #define STATE_CHANGE_STATE ((StateChangedType)8) #define STATE_CHANGE_STYLE ((StateChangedType)9) #define STATE_CHANGE_ZOOM ((StateChangedType)10) #define STATE_CHANGE_BORDER ((StateChangedType)11) #define STATE_CHANGE_TRANSPARENT ((StateChangedType)12) #define STATE_CHANGE_CONTROLFONT ((StateChangedType)13) #define STATE_CHANGE_CONTROLFOREGROUND ((StateChangedType)14) #define STATE_CHANGE_CONTROLBACKGROUND ((StateChangedType)15) #define STATE_CHANGE_READONLY ((StateChangedType)16) #define STATE_CHANGE_EXTENDEDSTYLE ((StateChangedType)17) #define STATE_CHANGE_MIRRORING ((StateChangedType)18) #define STATE_CHANGE_CONTROL_FOCUS ((StateChangedType)20) #define STATE_CHANGE_USER ((StateChangedType)10000) // GetFocusFlags #define GETFOCUS_TAB ((sal_uInt16)0x0001) #define GETFOCUS_CURSOR ((sal_uInt16)0x0002) #define GETFOCUS_MNEMONIC ((sal_uInt16)0x0004) #define GETFOCUS_F6 ((sal_uInt16)0x0008) #define GETFOCUS_FORWARD ((sal_uInt16)0x0010) #define GETFOCUS_BACKWARD ((sal_uInt16)0x0020) #define GETFOCUS_AROUND ((sal_uInt16)0x0040) #define GETFOCUS_UNIQUEMNEMONIC ((sal_uInt16)0x0100) #define GETFOCUS_INIT ((sal_uInt16)0x0200) #define GETFOCUS_FLOATWIN_POPUPMODEEND_CANCEL ((sal_uInt16)0x0400) // Draw-Flags fuer Draw() #define WINDOW_DRAW_MONO ((sal_uLong)0x00000001) #define WINDOW_DRAW_NOBORDER ((sal_uLong)0x00000002) #define WINDOW_DRAW_NOCONTROLS ((sal_uLong)0x00000004) #define WINDOW_DRAW_NODISABLE ((sal_uLong)0x00000008) #define WINDOW_DRAW_NOMNEMONIC ((sal_uLong)0x00000010) #define WINDOW_DRAW_NOSELECTION ((sal_uLong)0x00000020) #define WINDOW_DRAW_NOFOCUS ((sal_uLong)0x00000040) #define WINDOW_DRAW_NOBACKGROUND ((sal_uLong)0x00000080) #define WINDOW_DRAW_ROLLOVER ((sal_uLong)0x00000100) // DialogControl-Flags #define WINDOW_DLGCTRL_RETURN ((sal_uInt16)0x0001) #define WINDOW_DLGCTRL_WANTFOCUS ((sal_uInt16)0x0002) #define WINDOW_DLGCTRL_MOD1TAB ((sal_uInt16)0x0004) #define WINDOW_DLGCTRL_FLOATWIN_POPUPMODEEND_CANCEL ((sal_uInt16)0x0008) // GetWindowClipRegionPixel-Flags #define WINDOW_GETCLIPREGION_NULL ((sal_uInt16)0x0001) #define WINDOW_GETCLIPREGION_NOCHILDREN ((sal_uInt16)0x0002) // EndExtTextInput-Flags #define EXTTEXTINPUT_END_COMPLETE ((sal_uInt16)0x0001) #define EXTTEXTINPUT_END_CANCEL ((sal_uInt16)0x0002) #define IMPL_MINSIZE_BUTTON_WIDTH 70 #define IMPL_MINSIZE_BUTTON_HEIGHT 22 #define IMPL_EXTRA_BUTTON_WIDTH 18 #define IMPL_EXTRA_BUTTON_HEIGHT 10 #define IMPL_SEP_BUTTON_X 5 #define IMPL_SEP_BUTTON_Y 5 #define IMPL_MINSIZE_MSGBOX_WIDTH 150 #define IMPL_MINSIZE_MSGBOX_HEIGHT 80 #define IMPL_DIALOG_OFFSET 5 #define IMPL_DIALOG_BAR_OFFSET 3 #define IMPL_MSGBOX_OFFSET_EXTRA_X 0 #define IMPL_MSGBOX_OFFSET_EXTRA_Y 2 #define IMPL_SEP_MSGBOX_IMAGE 8 #define DLGWINDOW_PREV 0 #define DLGWINDOW_NEXT 1 #define DLGWINDOW_FIRST 2 // - Window - #ifdef DBG_UTIL const char* ImplDbgCheckWindow( const void* pObj ); #endif class Dialog; class WindowImpl; class PaintHelper; class VclBuilder; class VclSizeGroup; struct WindowResHeader { sal_uLong nObjMask; OString aHelpId; sal_uLong nRSStyle; }; class VCL_DLLPUBLIC Window : public OutputDevice, public Resource { friend class Cursor; friend class OutputDevice; friend class Application; friend class SystemWindow; friend class WorkWindow; friend class Dialog; friend class MessBox; friend class DockingWindow; friend class FloatingWindow; friend class GroupBox; friend class PushButton; friend class RadioButton; friend class SystemChildWindow; friend class ImplBorderWindow; friend class VclBuilder; friend class PaintHelper; // TODO: improve missing functionality // only required because of SetFloatingMode() friend class ImplDockingWindowWrapper; friend class ImplPopupFloatWin; friend class MenuFloatingWindow; friend class svt::PopupWindowControllerImpl; private: // NOTE: to remove many dependencies of other modules // to this central file, all members are now hidden // in the WindowImpl class and all inline functions // were removed. // (WindowImpl is a pImpl pattern) // Please do *not* add new members or inline functions to class Window, // but use class WindowImpl instead WindowImpl* mpWindowImpl; // This is a first attempt to start to remove the dependency of Window on // OutputDevice OutputDevice* mpOutputDevice; #ifdef DBG_UTIL friend const char* ImplDbgCheckWindow( const void* pObj ); #endif friend Window* ImplFindWindow( const SalFrame* pFrame, Point& rSalFramePos ); public: DECL_DLLPRIVATE_LINK( ImplHandlePaintHdl, void* ); DECL_DLLPRIVATE_LINK( ImplGenerateMouseMoveHdl, void* ); DECL_DLLPRIVATE_LINK( ImplTrackTimerHdl, Timer* ); DECL_DLLPRIVATE_LINK( ImplAsyncFocusHdl, void* ); DECL_DLLPRIVATE_LINK( ImplHandleResizeTimerHdl, void* ); DECL_DLLPRIVATE_LINK( ImplHideOwnerDrawWindowsHdl, void* ); SAL_DLLPRIVATE static void ImplInitAppFontData( Window* pWindow ); SAL_DLLPRIVATE Window* ImplGetFrameWindow() const; SalFrame* ImplGetFrame() const; SAL_DLLPRIVATE ImplFrameData* ImplGetFrameData(); SAL_DLLPRIVATE Window* ImplGetWindow(); SAL_DLLPRIVATE ImplWinData* ImplGetWinData() const; SAL_DLLPRIVATE Window* ImplGetClientWindow() const; SAL_DLLPRIVATE Window* ImplGetDlgWindow( sal_uInt16 n, sal_uInt16 nType, sal_uInt16 nStart = 0, sal_uInt16 nEnd = 0xFFFF, sal_uInt16* pIndex = NULL ); SAL_DLLPRIVATE Window* ImplGetParent() const; SAL_DLLPRIVATE Window* ImplFindWindow( const Point& rFramePos ); SAL_DLLPRIVATE void ImplInvalidateFrameRegion( const Region* pRegion, sal_uInt16 nFlags ); SAL_DLLPRIVATE void ImplInvalidateOverlapFrameRegion( const Region& rRegion ); SAL_DLLPRIVATE bool ImplSetClipFlag( bool bSysObjOnlySmaller = false ); SAL_DLLPRIVATE bool ImplIsWindowOrChild( const Window* pWindow, bool bSystemWindow = false ) const; SAL_DLLPRIVATE bool ImplIsChild( const Window* pWindow, bool bSystemWindow = false ) const; SAL_DLLPRIVATE bool ImplIsFloatingWindow() const; SAL_DLLPRIVATE bool ImplIsPushButton() const; SAL_DLLPRIVATE bool ImplIsSplitter() const; SAL_DLLPRIVATE bool ImplIsDockingWindow() const; SAL_DLLPRIVATE bool ImplIsOverlapWindow() const; SAL_DLLPRIVATE void ImplIsInTaskPaneList( bool mbIsInTaskList ); SAL_DLLPRIVATE WindowImpl* ImplGetWindowImpl() const { return mpWindowImpl; } SAL_DLLPRIVATE Point ImplFrameToOutput( const Point& rPos ); SAL_DLLPRIVATE void ImplGrabFocus( sal_uInt16 nFlags ); SAL_DLLPRIVATE void ImplGrabFocusToDocument( sal_uInt16 nFlags ); SAL_DLLPRIVATE void ImplInvertFocus( const Rectangle& rRect ); SAL_DLLPRIVATE PointerStyle ImplGetMousePointer() const; SAL_DLLPRIVATE void ImplCallMouseMove( sal_uInt16 nMouseCode, bool bModChanged = false ); SAL_DLLPRIVATE void ImplGenerateMouseMove(); SAL_DLLPRIVATE void ImplNotifyKeyMouseCommandEventListeners( NotifyEvent& rNEvt ); SAL_DLLPRIVATE void ImplNotifyIconifiedState( bool bIconified ); SAL_DLLPRIVATE void ImplUpdateAll( bool bOverlapWindows = true ); SAL_DLLPRIVATE void ImplDeleteOverlapBackground(); SAL_DLLPRIVATE void ImplControlFocus( sal_uInt16 nFlags = 0 ); SAL_DLLPRIVATE void ImplMirrorFramePos( Point &pt ) const; SAL_DLLPRIVATE void ImplPosSizeWindow( long nX, long nY, long nWidth, long nHeight, sal_uInt16 nFlags ); SAL_DLLPRIVATE void ImplAddDel( ImplDelData* pDel ); SAL_DLLPRIVATE void ImplRemoveDel( ImplDelData* pDel ); SAL_DLLPRIVATE void ImplCallResize(); SAL_DLLPRIVATE void ImplCallMove(); SAL_DLLPRIVATE void ImplIncModalCount(); SAL_DLLPRIVATE void ImplDecModalCount(); SAL_DLLPRIVATE static void ImplCalcSymbolRect( Rectangle& rRect ); protected: SAL_DLLPRIVATE void ImplInit( Window* pParent, WinBits nStyle, SystemParentData* pSystemParentData ); SAL_DLLPRIVATE Point ImplOutputToFrame( const Point& rPos ); SAL_DLLPRIVATE void ImplInvalidateParentFrameRegion( Region& rRegion ); SAL_DLLPRIVATE void ImplValidateFrameRegion( const Region* rRegion, sal_uInt16 nFlags ); SAL_DLLPRIVATE void ImplValidate( const Region* rRegion, sal_uInt16 nFlags ); SAL_DLLPRIVATE void ImplMoveInvalidateRegion( const Rectangle& rRect, long nHorzScroll, long nVertScroll, bool bChildren ); SAL_DLLPRIVATE void ImplMoveAllInvalidateRegions( const Rectangle& rRect, long nHorzScroll, long nVertScroll, bool bChildren ); SAL_DLLPRIVATE Window* ImplGetBorderWindow() const; SAL_DLLPRIVATE void ImplInvalidate( const Region* rRegion, sal_uInt16 nFlags ); SAL_DLLPRIVATE sal_uInt16 ImplHitTest( const Point& rFramePos ); SAL_DLLPRIVATE void ImplSetMouseTransparent( bool bTransparent ); SAL_DLLPRIVATE void ImplScroll( const Rectangle& rRect, long nHorzScroll, long nVertScroll, sal_uInt16 nFlags ); SAL_DLLPRIVATE void ImplSaveOverlapBackground(); SAL_DLLPRIVATE bool ImplRestoreOverlapBackground( Region& rInvRegion ); SAL_DLLPRIVATE void ImplInvalidateAllOverlapBackgrounds(); SAL_DLLPRIVATE bool ImplSetClipFlagChildren( bool bSysObjOnlySmaller = false ); SAL_DLLPRIVATE bool ImplSetClipFlagOverlapWindows( bool bSysObjOnlySmaller = false ); SAL_DLLPRIVATE WinBits ImplInitRes( const ResId& rResId ); SAL_DLLPRIVATE WindowResHeader ImplLoadResHeader( const ResId& rResId ); SAL_DLLPRIVATE void ImplLoadRes( const ResId& rResId ); SAL_DLLPRIVATE void PushPaintHelper(PaintHelper *pHelper); SAL_DLLPRIVATE void PopPaintHelper(PaintHelper *pHelper); private: SAL_DLLPRIVATE void ImplInitWindowData( WindowType nType ); SAL_DLLPRIVATE void ImplSetFrameParent( const Window* pParent ); SAL_DLLPRIVATE void ImplInsertWindow( Window* pParent ); SAL_DLLPRIVATE void ImplRemoveWindow( bool bRemoveFrameData ); SAL_DLLPRIVATE SalGraphics* ImplGetFrameGraphics() const; SAL_DLLPRIVATE void ImplCallFocusChangeActivate( Window* pNewOverlapWindow, Window* pOldOverlapWindow ); SAL_DLLPRIVATE Window* ImplGetFirstOverlapWindow(); SAL_DLLPRIVATE const Window* ImplGetFirstOverlapWindow() const; SAL_DLLPRIVATE bool ImplIsRealParentPath( const Window* pWindow ) const; SAL_DLLPRIVATE int ImplTestMousePointerSet(); SAL_DLLPRIVATE void ImplResetReallyVisible(); SAL_DLLPRIVATE void ImplSetReallyVisible(); SAL_DLLPRIVATE void ImplCallInitShow(); SAL_DLLPRIVATE void ImplInitResolutionSettings(); SAL_DLLPRIVATE void ImplPointToLogic( Font& rFont ) const; SAL_DLLPRIVATE void ImplLogicToPoint( Font& rFont ) const; SAL_DLLPRIVATE bool ImplSysObjClip( const Region* pOldRegion ); SAL_DLLPRIVATE void ImplUpdateSysObjChildrenClip(); SAL_DLLPRIVATE void ImplUpdateSysObjOverlapsClip(); SAL_DLLPRIVATE void ImplUpdateSysObjClip(); SAL_DLLPRIVATE void ImplIntersectWindowClipRegion( Region& rRegion ); SAL_DLLPRIVATE void ImplIntersectWindowRegion( Region& rRegion ); SAL_DLLPRIVATE void ImplExcludeWindowRegion( Region& rRegion ); SAL_DLLPRIVATE void ImplExcludeOverlapWindows( Region& rRegion ); SAL_DLLPRIVATE void ImplExcludeOverlapWindows2( Region& rRegion ); SAL_DLLPRIVATE void ImplClipBoundaries( Region& rRegion, bool bThis, bool bOverlaps ); SAL_DLLPRIVATE bool ImplClipChildren( Region& rRegion ); SAL_DLLPRIVATE void ImplClipAllChildren( Region& rRegion ); SAL_DLLPRIVATE void ImplClipSiblings( Region& rRegion ); SAL_DLLPRIVATE void ImplInitWinClipRegion(); SAL_DLLPRIVATE void ImplInitWinChildClipRegion(); SAL_DLLPRIVATE Region* ImplGetWinChildClipRegion(); SAL_DLLPRIVATE void ImplIntersectAndUnionOverlapWindows( const Region& rInterRegion, Region& rRegion ); SAL_DLLPRIVATE void ImplIntersectAndUnionOverlapWindows2( const Region& rInterRegion, Region& rRegion ); SAL_DLLPRIVATE void ImplCalcOverlapRegionOverlaps( const Region& rInterRegion, Region& rRegion ); SAL_DLLPRIVATE void ImplCalcOverlapRegion( const Rectangle& rSourceRect, Region& rRegion, bool bChildren, bool bParent, bool bSiblings ); SAL_DLLPRIVATE void ImplCallPaint( const Region* pRegion, sal_uInt16 nPaintFlags ); SAL_DLLPRIVATE void ImplCallOverlapPaint(); SAL_DLLPRIVATE void ImplPostPaint(); SAL_DLLPRIVATE void ImplUpdateWindowPtr( Window* pWindow ); SAL_DLLPRIVATE void ImplUpdateWindowPtr(); SAL_DLLPRIVATE void ImplUpdateOverlapWindowPtr( bool bNewFrame ); SAL_DLLPRIVATE bool ImplUpdatePos(); SAL_DLLPRIVATE void ImplUpdateSysObjPos(); /** check whether a font is suitable for UI The font to be tested will be checked whether it could display a localized test string. If this is not the case, then the font is deemed unsuitable as UI font. @param rFont the font to be tested @returns True if the font can be used as UI font False if the font is unsuitable as UI font */ SAL_DLLPRIVATE bool ImplCheckUIFont( const Font& rFont ); SAL_DLLPRIVATE void ImplUpdateGlobalSettings( AllSettings& rSettings, bool bCallHdl = true ); SAL_DLLPRIVATE void ImplAlignChildren(); SAL_DLLPRIVATE void ImplToBottomChild(); SAL_DLLPRIVATE void ImplCalcToTop( ImplCalcToTopData* pPrevData ); SAL_DLLPRIVATE void ImplToTop( sal_uInt16 nFlags ); SAL_DLLPRIVATE void ImplStartToTop( sal_uInt16 nFlags ); SAL_DLLPRIVATE void ImplFocusToTop( sal_uInt16 nFlags, bool bReallyVisible ); SAL_DLLPRIVATE void ImplShowAllOverlaps(); SAL_DLLPRIVATE void ImplHideAllOverlaps(); SAL_DLLPRIVATE bool ImplDlgCtrl( const KeyEvent& rKEvt, bool bKeyInput ); SAL_DLLPRIVATE bool ImplHasDlgCtrl(); SAL_DLLPRIVATE void ImplDlgCtrlNextWindow(); SAL_DLLPRIVATE void ImplDlgCtrlFocusChanged( Window* pWindow, bool bGetFocus ); SAL_DLLPRIVATE Window* ImplFindDlgCtrlWindow( Window* pWindow ); SAL_DLLPRIVATE long ImplLogicUnitToPixelX( long nX, MapUnit eUnit ); SAL_DLLPRIVATE long ImplLogicUnitToPixelY( long nY, MapUnit eUnit ); SAL_DLLPRIVATE bool ImplIsWindowInFront( const Window* pTestWindow ) const; SAL_DLLPRIVATE static void ImplNewInputContext(); SAL_DLLPRIVATE void ImplCallActivateListeners(Window*); SAL_DLLPRIVATE void ImplCallDeactivateListeners(Window*); SAL_DLLPRIVATE void ImplHandleScroll( ScrollBar* pHScrl, long nX, ScrollBar* pVScrl, long nY ); SAL_DLLPRIVATE Rectangle ImplOutputToUnmirroredAbsoluteScreenPixel( const Rectangle& rRect ) const; SAL_DLLPRIVATE long ImplGetUnmirroredOutOffX(); // retrieves the list of owner draw decorated windows for this window hiearchy SAL_DLLPRIVATE ::std::vector<Window *>& ImplGetOwnerDrawList(); SAL_DLLPRIVATE Window* ImplGetTopmostFrameWindow(); SAL_DLLPRIVATE Rectangle ImplGetWindowExtentsRelative( Window *pRelativeWindow, bool bClientOnly ) const; SAL_DLLPRIVATE bool ImplStopDnd(); SAL_DLLPRIVATE void ImplStartDnd(); SAL_DLLPRIVATE void ImplPaintToDevice( OutputDevice* pTargetOutDev, const Point& rPos ); SAL_DLLPRIVATE ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XCanvas > ImplGetCanvas( const Size& rFullscreenSize, bool bFullscreen, bool bSpriteCanvas ) const; public: virtual Region GetActiveClipRegion() const SAL_OVERRIDE; private: // Default construction is forbidden and not implemented. SAL_DLLPRIVATE Window(); // Copy assignment is forbidden and not implemented. SAL_DLLPRIVATE Window (const Window &); SAL_DLLPRIVATE Window & operator= (const Window &); protected: // Single argument ctors shall be explicit. explicit Window( WindowType nType ); void SetCompoundControl( bool bCompound ); void ImplCallEventListeners( sal_uLong nEvent, void* pData = NULL ); void CallEventListeners( sal_uLong nEvent, void* pData = NULL ); void FireVclEvent( VclSimpleEvent* pEvent ); virtual bool AcquireGraphics() const SAL_OVERRIDE; virtual void ReleaseGraphics( bool bRelease = true ) SAL_OVERRIDE; virtual void InitClipRegion() SAL_OVERRIDE; // FIXME: this is a hack to workaround missing layout functionality SAL_DLLPRIVATE void ImplAdjustNWFSizes(); virtual void CopyDeviceArea( SalTwoRect& aPosAry, sal_uInt32 nFlags) SAL_OVERRIDE; virtual void ClipToPaintRegion( Rectangle& rDstRect ) SAL_OVERRIDE; virtual bool UsePolyPolygonForComplexGradient() SAL_OVERRIDE; virtual void DrawGradientWallpaper( long nX, long nY, long nWidth, long nHeight, const Wallpaper& rWallpaper ) SAL_OVERRIDE; public: bool HasMirroredGraphics() const SAL_OVERRIDE; public: // Single argument ctors shall be explicit. explicit Window( Window* pParent, WinBits nStyle = 0 ); Window( Window* pParent, const ResId& rResId ); virtual ~Window(); OutputDevice const* GetOutDev() const { return mpOutputDevice; }; OutputDevice* GetOutDev() { return mpOutputDevice; }; virtual void EnableRTL ( bool bEnable = true ) SAL_OVERRIDE; virtual void MouseMove( const MouseEvent& rMEvt ); virtual void MouseButtonDown( const MouseEvent& rMEvt ); virtual void MouseButtonUp( const MouseEvent& rMEvt ); virtual void KeyInput( const KeyEvent& rKEvt ); virtual void KeyUp( const KeyEvent& rKEvt ); virtual void PrePaint(); virtual void Paint( const Rectangle& rRect ); virtual void Erase() SAL_OVERRIDE; virtual void Erase( const Rectangle& rRect ) SAL_OVERRIDE { OutputDevice::Erase( rRect ); } virtual void PostPaint(); virtual void Draw( OutputDevice* pDev, const Point& rPos, const Size& rSize, sal_uLong nFlags ); virtual void Move(); virtual void Resize(); virtual void Activate(); virtual void Deactivate(); virtual void GetFocus(); virtual void LoseFocus(); virtual void RequestHelp( const HelpEvent& rHEvt ); virtual void Command( const CommandEvent& rCEvt ); virtual void Tracking( const TrackingEvent& rTEvt ); virtual void StateChanged( StateChangedType nStateChange ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); virtual bool PreNotify( NotifyEvent& rNEvt ); virtual bool Notify( NotifyEvent& rNEvt ); virtual Window* GetPreferredKeyInputWindow(); /*virtual*/ void AddEventListener( const Link& rEventListener ); /*virtual*/ void RemoveEventListener( const Link& rEventListener ); /*virtual*/ void AddChildEventListener( const Link& rEventListener ); /*virtual*/ void RemoveChildEventListener( const Link& rEventListener ); ImplSVEvent * PostUserEvent( const Link& rLink, void* pCaller = NULL ); void RemoveUserEvent( ImplSVEvent * nUserEvent ); void IncrementLockCount(); void DecrementLockCount(); bool IsLocked( bool bChildren = false ) const; // returns the input language used for the last key stroke // may be LANGUAGE_DONTKNOW if not supported by the OS LanguageType GetInputLanguage() const; void SetStyle( WinBits nStyle ); WinBits GetStyle() const; WinBits GetPrevStyle() const; void SetExtendedStyle( WinBits nExtendedStyle ); WinBits GetExtendedStyle() const; void SetType( WindowType nType ); WindowType GetType() const; bool IsSystemWindow() const; bool IsDialog() const; bool IsMenuFloatingWindow() const; bool IsToolbarFloatingWindow() const; bool IsTopWindow() const; SystemWindow* GetSystemWindow() const; void EnableAllResize( bool bEnable = true ); void SetBorderStyle( sal_uInt16 nBorderStyle ); sal_uInt16 GetBorderStyle() const; void GetBorder( sal_Int32& rLeftBorder, sal_Int32& rTopBorder, sal_Int32& rRightBorder, sal_Int32& rBottomBorder ) const; Size CalcWindowSize( const Size& rOutSz ) const; Size CalcOutputSize( const Size& rWinSz ) const; long CalcTitleWidth() const; void EnableClipSiblings( bool bClipSiblings = true ); void EnableChildTransparentMode( bool bEnable = true ); bool IsChildTransparentModeEnabled() const; void SetMouseTransparent( bool bTransparent ); bool IsMouseTransparent() const; void SetPaintTransparent( bool bTransparent ); bool IsPaintTransparent() const; void SetDialogControlStart( bool bStart ); bool IsDialogControlStart() const; void SetDialogControlFlags( sal_uInt16 nFlags ); sal_uInt16 GetDialogControlFlags() const; struct PointerState { sal_uLong mnState; // the button state Point maPos; // mouse position in output coordinates }; PointerState GetPointerState(); bool IsMouseOver(); sal_uLong GetCurrentModButtons(); void SetInputContext( const InputContext& rInputContext ); const InputContext& GetInputContext() const; void EndExtTextInput( sal_uInt16 nFlags ); void SetCursorRect( const Rectangle* pRect = NULL, long nExtTextInputWidth = 0 ); const Rectangle* GetCursorRect() const; long GetCursorExtTextInputWidth() const; void SetCompositionCharRect( const Rectangle* pRect, long nCompositionLength, bool bVertical = false ); using OutputDevice::SetSettings; virtual void SetSettings( const AllSettings& rSettings ) SAL_OVERRIDE; virtual void SetSettings( const AllSettings& rSettings, bool bChild ); void UpdateSettings( const AllSettings& rSettings, bool bChild = false ); void NotifyAllChildren( DataChangedEvent& rDCEvt ); void SetPointFont( const Font& rFont ); Font GetPointFont() const; void SetZoomedPointFont( const Font& rFont ); long GetDrawPixel( OutputDevice* pDev, long nPixels ) const; Font GetDrawPixelFont( OutputDevice* pDev ) const; void SetControlFont(); void SetControlFont( const Font& rFont ); Font GetControlFont() const; bool IsControlFont() const; void SetControlForeground(); void SetControlForeground( const Color& rColor ); Color GetControlForeground() const; bool IsControlForeground() const; void SetControlBackground(); void SetControlBackground( const Color& rColor ); Color GetControlBackground() const; bool IsControlBackground() const; void SetParentClipMode( sal_uInt16 nMode = 0 ); sal_uInt16 GetParentClipMode() const; void SetWindowRegionPixel(); void SetWindowRegionPixel( const Region& rRegion ); const Region& GetWindowRegionPixel() const; bool IsWindowRegionPixel() const; Region GetWindowClipRegionPixel( sal_uInt16 nFlags = 0 ) const; Region GetPaintRegion() const; bool IsInPaint() const; // while IsInPaint returns true ExpandPaintClipRegion adds the // submitted region to the paint clip region so you can // paint additional parts of your window if necessary void ExpandPaintClipRegion( const Region& rRegion ); void SetParent( Window* pNewParent ); Window* GetParent() const; // return the dialog we are contained in or NULL if un-contained Dialog* GetParentDialog() const; void Show( bool bVisible = true, sal_uInt16 nFlags = 0 ); void Hide() { Show( false ); } bool IsVisible() const; bool IsReallyVisible() const; bool IsReallyShown() const; bool IsInInitShow() const; void Enable( bool bEnable = true, bool bChild = true ); void Disable( bool bChild = true ) { Enable( false, bChild ); } bool IsEnabled() const; void EnableInput( bool bEnable = true, bool bChild = true ); void EnableInput( bool bEnable, bool bChild, bool bSysWin, const Window* pExcludeWindow = NULL ); bool IsInputEnabled() const; /** Override <code>EnableInput</code>. This can be necessary due to other people using EnableInput for whole window hierarchies. <code>AlwaysEnableInput</code> and <code>AlwaysDisableInput</code> are mutually exclusive; the last setter wins. @param bAlways sets always enabled flag @param bChild if true children are recursively set to AlwaysEnableInput */ void AlwaysEnableInput( bool bAlways, bool bChild = true ); /** returns the current AlwaysEnableInput state @return true if window is in AlwaysEnableInput state */ bool IsAlwaysEnableInput() const; /** Override <code>EnableInput</code>, counterpart to AlwaysEnableInput. Windows with AlwaysDisableInput will not get key events even if enabled and input enabled.This can be necessary due to other people using EnableInput for whole window hierarchies. <code>AlwaysEnableInput</code> and <code>AlwaysDisableInput</code> are mutually exclusive; the last setter wins. @param bAlways sets always disable flag @param bChild if true children are recursively set to AlwaysDisableInput */ void AlwaysDisableInput( bool bAlways, bool bChild = true ); /** usually event handlers (see AddEventListener and AddChildEventListener) are not called on disabled, modal or input disabled windows. There are however rare cases in which one wants a Window or rather one of its Control subclasses to not evaluate events but still react to those events externally. In these rare cases call SetCallHandlersOnInputDisabled( true ) to have your handler called anyway. Currently only mouse events get this special treatment. Use this sparingly, chances are if you want to use it you're working around the real problem. @param bCall Enable/Disable calling event handlers for this disabled, modal or input disabled window. This call is implicity done recursively for possible child windows. */ void SetCallHandlersOnInputDisabled( bool bCall ); /** get state of SetCallHandlersOnInputDisabled @returns whether handlers are called regardless of input enabled state */ bool IsCallHandlersOnInputDisabled() const; /** A window is in modal mode if one of its children or subchildren is a running modal window (a modal dialog) @returns sal_True if a child or subchild is a running modal window */ bool IsInModalMode() const; /** * Necessary for calc ref input handling from modal dialogs */ bool IsInModalNonRefMode() const; void SetActivateMode( sal_uInt16 nMode ); sal_uInt16 GetActivateMode() const; void ToTop( sal_uInt16 nFlags = 0 ); void SetZOrder( Window* pRefWindow, sal_uInt16 nFlags ); void EnableAlwaysOnTop( bool bEnable = true ); bool IsAlwaysOnTopEnabled() const; virtual void setPosSizePixel( long nX, long nY, long nWidth, long nHeight, sal_uInt16 nFlags = WINDOW_POSSIZE_ALL ); virtual void SetPosPixel( const Point& rNewPos ); virtual Point GetPosPixel() const; virtual void SetSizePixel( const Size& rNewSize ); virtual Size GetSizePixel() const; virtual void SetPosSizePixel( const Point& rNewPos, const Size& rNewSize ); virtual void SetOutputSizePixel( const Size& rNewSize ); bool IsDefaultPos() const; bool IsDefaultSize() const; // those conversion routines might deliver different results during UI mirroring Point OutputToScreenPixel( const Point& rPos ) const; Point ScreenToOutputPixel( const Point& rPos ) const; // the normalized screen methods work independent from UI mirroring Point OutputToNormalizedScreenPixel( const Point& rPos ) const; Point NormalizedScreenToOutputPixel( const Point& rPos ) const; Point OutputToAbsoluteScreenPixel( const Point& rPos ) const; Point AbsoluteScreenToOutputPixel( const Point& rPos ) const; Rectangle GetDesktopRectPixel() const; // window extents including border and decoratrion Rectangle GetWindowExtentsRelative( Window *pRelativeWindow ) const; // window extents of the client window, coordinates to be used in SetPosPixel Rectangle GetClientWindowExtentsRelative( Window *pRelativeWindow ) const; virtual bool IsScrollable() const; virtual void Scroll( long nHorzScroll, long nVertScroll, sal_uInt16 nFlags = 0 ); virtual void Scroll( long nHorzScroll, long nVertScroll, const Rectangle& rRect, sal_uInt16 nFlags = 0 ); virtual void Invalidate( sal_uInt16 nFlags = 0 ); virtual void Invalidate( const Rectangle& rRect, sal_uInt16 nFlags = 0 ); virtual void Invalidate( const Region& rRegion, sal_uInt16 nFlags = 0 ); void Validate( sal_uInt16 nFlags = 0 ); bool HasPaintEvent() const; void Update(); void Flush(); void Sync(); // toggles new docking support, enabled via toolkit void EnableDocking( bool bEnable = true ); // retrieves the single dockingmanager instance static DockingManager* GetDockingManager(); void EnablePaint( bool bEnable ); bool IsPaintEnabled() const; void SetUpdateMode( bool bUpdate ); bool IsUpdateMode() const; void SetParentUpdateMode( bool bUpdate ); void GrabFocus(); bool HasFocus() const; bool HasChildPathFocus( bool bSystemWindow = false ) const; bool IsActive() const; bool HasActiveChildFrame(); sal_uInt16 GetGetFocusFlags() const; void GrabFocusToDocument(); /** * Set this when you need to act as if the window has focus even if it * doesn't. This is necessary for implementing tab stops inside floating * windows, but floating windows don't get focus from the system. */ void SetFakeFocus( bool bFocus ); bool IsCompoundControl() const; static sal_uIntPtr SaveFocus(); static bool EndSaveFocus( sal_uIntPtr nSaveId, bool bRestore = true ); void CaptureMouse(); void ReleaseMouse(); bool IsMouseCaptured() const; void SetPointer( const Pointer& rPointer ); const Pointer& GetPointer() const; void EnableChildPointerOverwrite( bool bOverwrite ); void SetPointerPosPixel( const Point& rPos ); Point GetPointerPosPixel(); Point GetLastPointerPosPixel(); void ShowPointer( bool bVisible ); void EnterWait(); void LeaveWait(); bool IsWait() const; void SetCursor( Cursor* pCursor ); Cursor* GetCursor() const; void SetZoom( const Fraction& rZoom ); const Fraction& GetZoom() const; bool IsZoom() const; long CalcZoom( long n ) const; virtual void SetText( const OUString& rStr ); virtual OUString GetText() const; // return the actual text displayed // this may have e.g. accelerators removed or portions // replaced by ellipses virtual OUString GetDisplayText() const; // gets the visible background color. for transparent windows // this may be the parent's background color; for controls // this may be a child's background color (e.g. ListBox) virtual const Wallpaper& GetDisplayBackground() const; void SetHelpText( const OUString& rHelpText ); const OUString& GetHelpText() const; void SetQuickHelpText( const OUString& rHelpText ); const OUString& GetQuickHelpText() const; void SetHelpId( const OString& ); const OString& GetHelpId() const; void SetUniqueId( const OString& ); const OString& GetUniqueId() const; Window* FindWindow( const Point& rPos ) const; sal_uInt16 GetChildCount() const; Window* GetChild( sal_uInt16 nChild ) const; Window* GetWindow( sal_uInt16 nType ) const; bool IsChild( const Window* pWindow, bool bSystemWindow = false ) const; bool IsWindowOrChild( const Window* pWindow, bool bSystemWindow = false ) const; void SetData( void* pNewData ); void* GetData() const; void ShowFocus( const Rectangle& rRect ); void HideFocus(); void Invert( const Rectangle& rRect, sal_uInt16 nFlags = 0 ); void Invert( const Polygon& rPoly, sal_uInt16 nFlags = 0 ); // transparent background for selected or checked items in toolboxes etc. void DrawSelectionBackground( const Rectangle& rRect, sal_uInt16 highlight, bool bChecked, bool bDrawBorder, bool bDrawExtBorderOnly ); // the same, but fills a passed Color with a text color complementing the selection background void DrawSelectionBackground( const Rectangle& rRect, sal_uInt16 highlight, bool bChecked, bool bDrawBorder, bool bDrawExtBorderOnly, Color* pSelectionTextColor ); // support rounded edges in the selection rect void DrawSelectionBackground( const Rectangle& rRect, sal_uInt16 highlight, bool bChecked, bool bDrawBorder, bool bDrawExtBorderOnly, long nCornerRadius, Color* pSelectionTextColor, Color* pPaintColor ); void ShowTracking( const Rectangle& rRect, sal_uInt16 nFlags = SHOWTRACK_SMALL ); void HideTracking(); void InvertTracking( const Rectangle& rRect, sal_uInt16 nFlags = SHOWTRACK_SMALL ); void InvertTracking( const Polygon& rPoly, sal_uInt16 nFlags = 0 ); void StartTracking( sal_uInt16 nFlags = 0 ); void EndTracking( sal_uInt16 nFlags = 0 ); bool IsTracking() const; void StartAutoScroll( sal_uInt16 nFlags ); void EndAutoScroll(); bool HandleScrollCommand( const CommandEvent& rCmd, ScrollBar* pHScrl = NULL, ScrollBar* pVScrl = NULL ); void SaveBackground( const Point& rPos, const Size& rSize, const Point& rDestOff, VirtualDevice& rSaveDevice ); const SystemEnvData* GetSystemData() const; ::com::sun::star::uno::Any GetSystemDataAny() const; // API to set/query the component interfaces virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > GetComponentInterface( sal_Bool bCreate = sal_True ); virtual void SetComponentInterface( ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > xIFace ); /** @name Accessibility */ ///@{ public: ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > GetAccessible( bool bCreate = true ); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible(); void SetAccessible( ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > ); Window* GetAccessibleParentWindow() const; sal_uInt16 GetAccessibleChildWindowCount(); Window* GetAccessibleChildWindow( sal_uInt16 n ); void SetAccessibleRole( sal_uInt16 nRole ); sal_uInt16 GetAccessibleRole() const; void SetAccessibleName( const OUString& rName ); OUString GetAccessibleName() const; void SetAccessibleDescription( const OUString& rDescr ); OUString GetAccessibleDescription() const; void SetAccessibleRelationLabeledBy( Window* pLabeledBy ); Window* GetAccessibleRelationLabeledBy() const; void SetAccessibleRelationLabelFor( Window* pLabelFor ); Window* GetAccessibleRelationLabelFor() const; void SetAccessibleRelationMemberOf( Window* pMemberOf ); Window* GetAccessibleRelationMemberOf() const; // to avoid sending accessibility events in cases like closing dialogs // by default checks complete parent path bool IsAccessibilityEventsSuppressed( bool bTraverseParentPath = true ); void SetAccessibilityEventsSuppressed(bool bSuppressed); // Deprecated - can use SetAccessibleRelationLabelFor/By nowadys virtual Window* GetParentLabelFor( const Window* pLabel ) const; virtual Window* GetParentLabeledBy( const Window* pLabeled ) const; KeyEvent GetActivationKey() const; protected: // These eventually are supposed to go when everything is converted to .ui SAL_DLLPRIVATE Window* getLegacyNonLayoutAccessibleRelationMemberOf() const; SAL_DLLPRIVATE Window* getLegacyNonLayoutAccessibleRelationLabeledBy() const; SAL_DLLPRIVATE Window* getLegacyNonLayoutAccessibleRelationLabelFor() const; // Let Label override the code part of GetAccessibleRelationLabelFor virtual Window* getAccessibleRelationLabelFor() const; virtual sal_uInt16 getDefaultAccessibleRole() const; virtual OUString getDefaultAccessibleName() const; private: SAL_DLLPRIVATE bool ImplIsAccessibleCandidate() const; SAL_DLLPRIVATE bool ImplIsAccessibleNativeFrame() const; SAL_DLLPRIVATE sal_uInt16 ImplGetAccessibleCandidateChildWindowCount( sal_uInt16 nFirstWindowType ) const; SAL_DLLPRIVATE Window* ImplGetAccessibleCandidateChild( sal_uInt16 nChild, sal_uInt16& rChildCount, sal_uInt16 nFirstWindowType, bool bTopLevel = true ) const; SAL_DLLPRIVATE bool ImplRegisterAccessibleNativeFrame(); SAL_DLLPRIVATE void ImplRevokeAccessibleNativeFrame(); ///@} public: /// request XCanvas render interface for this window ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XCanvas > GetCanvas() const; /// request XSpriteCanvas render interface for this window ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XSpriteCanvas > GetSpriteCanvas() const; /* records all DrawText operations within the passed rectangle; * a synchronous paint is sent to achieve this */ void RecordLayoutData( vcl::ControlLayoutData* pLayout, const Rectangle& rRect ); // set and retrieve for Toolkit VCLXWindow* GetWindowPeer() const; void SetWindowPeer( ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > xPeer, VCLXWindow* pVCLXWindow ); // remember if it was generated by Toolkit bool IsCreatedWithToolkit() const; void SetCreatedWithToolkit( bool b ); // Drag and Drop interfaces virtual ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::dnd::XDropTarget > GetDropTarget(); virtual ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::dnd::XDragSource > GetDragSource(); virtual ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::dnd::XDragGestureRecognizer > GetDragGestureRecognizer(); // Clipboard/Selection interfaces virtual ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboard > GetClipboard(); virtual ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboard > GetPrimarySelection(); /* * Advisory Sizing - what is a good size for this widget * * Retrieves the preferred size of a widget ignoring * "width-request" and "height-request" properties. * * Implement this in sub-classes to tell layout * the preferred widget size. */ virtual Size GetOptimalSize() const; /* * Widgets call this to inform their owner container that the widget wants * to renegotiate its size. Should be called when a widget has a new size * request. e.g. a FixedText Control gets a new label. * * akin to gtk_widget_queue_resize */ virtual void queue_resize(); /* * Sets the "width-request" property * * Override for width request of the widget, or -1 if natural request * should be used. * * @see get_preferred_size, set_width_request */ void set_height_request(sal_Int32 nHeightRequest); sal_Int32 get_height_request() const; /* * Sets the "height-request" property * * Override for height request of the widget, or -1 if natural request * should be used. * * @see get_preferred_size, set_height_request */ void set_width_request(sal_Int32 nWidthRequest); sal_Int32 get_width_request() const; /* * Retrieves the preferred size of a widget taking * into account the "width-request" and "height-request" properties. * * Overrides the result of GetOptimalSize to honor the * width-request and height-request properties. * * @see GetOptimalSize * * akin to gtk_widget_get_preferred_size */ Size get_preferred_size() const; /* * How to horizontally align this widget */ VclAlign get_halign() const; void set_halign(VclAlign eAlign); /* * How to vertically align this widget */ VclAlign get_valign() const; void set_valign(VclAlign eAlign); /* * Whether the widget would like to use any available extra horizontal * space. */ bool get_hexpand() const; void set_hexpand(bool bExpand); /* * Whether the widget would like to use any available extra vertical * space. */ bool get_vexpand() const; void set_vexpand(bool bExpand); /* * Whether the widget would like to use any available extra space. */ bool get_expand() const; void set_expand(bool bExpand); /* * Whether the widget should receive extra space when the parent grows */ bool get_fill() const; void set_fill(bool bFill); void set_border_width(sal_Int32 nBorderWidth); sal_Int32 get_border_width() const; void set_margin_left(sal_Int32 nWidth); sal_Int32 get_margin_left() const; void set_margin_right(sal_Int32 nWidth); sal_Int32 get_margin_right() const; void set_margin_top(sal_Int32 nWidth); sal_Int32 get_margin_top() const; void set_margin_bottom(sal_Int32 nWidth); sal_Int32 get_margin_bottom() const; /* * How the widget is packed with reference to the start or end of the parent */ VclPackType get_pack_type() const; void set_pack_type(VclPackType ePackType); /* * The extra space to put between the widget and its neighbors */ sal_Int32 get_padding() const; void set_padding(sal_Int32 nPadding); /* * The number of columns that the widget spans */ sal_Int32 get_grid_width() const; void set_grid_width(sal_Int32 nCols); /* * The column number to attach the left side of the widget to */ sal_Int32 get_grid_left_attach() const; void set_grid_left_attach(sal_Int32 nAttach); /* * The number of row that the widget spans */ sal_Int32 get_grid_height() const; void set_grid_height(sal_Int32 nRows); /* * The row number to attach the top side of the widget to */ sal_Int32 get_grid_top_attach() const; void set_grid_top_attach(sal_Int32 nAttach); /* * If true this child appears in a secondary layout group of children * e.g. help buttons in a buttonbox */ bool get_secondary() const; void set_secondary(bool bSecondary); /* * If true this child is exempted from homogenous sizing * e.g. special button in a buttonbox */ bool get_non_homogeneous() const; void set_non_homogeneous(bool bNonHomogeneous); /* * Sets a widget property * * @return false if property is unknown */ virtual bool set_property(const OString &rKey, const OString &rValue); /* * Sets a font attribute * * @return false if attribute is unknown */ bool set_font_attribute(const OString &rKey, const OString &rValue); /* * Adds this widget to the xGroup VclSizeGroup * */ void add_to_size_group(boost::shared_ptr< VclSizeGroup > xGroup); void remove_from_all_size_groups(); /* * add/remove mnemonic label */ void add_mnemonic_label(FixedText *pLabel); void remove_mnemonic_label(FixedText *pLabel); std::vector<FixedText*> list_mnemonic_labels() const; /* * Move this widget to be the nNewPosition'd child of its parent */ void reorderWithinParent(sal_uInt16 nNewPosition); // Native Widget Rendering functions // form controls must never use native widgets, this can be toggled here void EnableNativeWidget( bool bEnable = true ); bool IsNativeWidgetEnabled() const; // a helper method for a Control's Draw method void PaintToDevice( OutputDevice* pDevice, const Point& rPos, const Size& rSize ); /* mark Window for deletion in top of event queue */ void doLazyDelete(); // Keyboard access functions /** Query the states of keyboard indicators - Caps Lock, Num Lock and Scroll Lock. Use the following mask to retrieve the state of each indicator: INDICATOR_CAPS_LOCK INDICATOR_NUM_LOCK INDICATOR_SCROLL_LOCK */ sal_uInt16 GetIndicatorState() const; void SimulateKeyPress( sal_uInt16 nKeyCode ) const; virtual OUString GetSurroundingText() const; virtual Selection GetSurroundingTextSelection() const; }; #endif // INCLUDED_VCL_WINDOW_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
2ba6eb2457b5bda133fe282a6bc692507f5963ce
f642cd236a54344c792281f9e6caba618bcb4e36
/coherence examples/cpp/contacts/LoaderExample.hpp
da173f9e3049e6d3e33660fe9f936eda262e7269
[]
no_license
gitrepo7777/sourcecodebackup
6c7ef3c15e647b83564ab257c6853fc035821260
6b26bbd7c2b0073b44a620004ed5a59058c1e26c
refs/heads/master
2021-01-01T19:28:31.603969
2014-06-08T00:30:27
2014-06-08T00:30:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,032
hpp
/* * LoaderExample.hpp * * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. * * Oracle is a registered trademarks of Oracle Corporation and/or its * affiliates. * * This software is the confidential and proprietary information of Oracle * Corporation. You shall not disclose such confidential and proprietary * information and shall use it only in accordance with the terms of the * license agreement you entered into with Oracle. * * This notice may not be removed or altered. */ #ifndef COH_EXAMPLES_LOADERXAMPLE_HPP #define COH_EXAMPLES_LOADERXAMPLE_HPP #include <iostream> #include "coherence/lang.ns" #include "coherence/net/NamedCache.hpp" COH_OPEN_NAMESPACE2(coherence,examples) using namespace coherence::lang; using coherence::net::NamedCache; /** * LoaderExample loads contacts into the cache from a file or stream. * <p/> * Demonstrates the most effective way of inserting data into a cache using the * Map.putAll() method. This will allow for minimizing the number of network * round trips between the application and the cache. * * @author ch 2009-04-06 */ class LoaderExample { // ----- Constructors ---------------------------------------------------- public: virtual ~LoaderExample() {} // ----- public methods -------------------------------------------------- public: /** * Load contacts from the input stream and insert them into the cache. * * @param in stream containing contacts * @param hCache target cache */ virtual void load(std::istream& in, NamedCache::Handle hCache) const; /** * Read a single contact from the supplied stream. * * @param in the stream from which to read a contact * * @return the contact or null upon reaching end of stream */ virtual Managed<Contact>::View readContact(std::istream& in) const; }; COH_CLOSE_NAMESPACE2 #endif //COH_EXAMPLES_LOADERXAMPLE_HPP
bd62167c160707bc5d610d91ef2983e4b40e9732
7099faa88c485595fd5037507b41045d0c8d94a5
/iids/movingterrainproperty.cpp
179ec82315681b078fdff5c6b36ea5c88472962e
[ "LicenseRef-scancode-public-domain" ]
permissive
whoopdedo/lg
8dc17f3e7cd62118801c9c6d80af0127a31b8f56
0c29f1f46f16dd16f9e436840ce5baa3d65ee357
refs/heads/master
2022-11-05T14:31:34.545712
2022-10-10T23:27:48
2022-10-10T23:27:48
1,752,480
1
7
null
2014-12-12T01:29:54
2011-05-15T21:09:45
C++
UTF-8
C++
false
false
148
cpp
#include <initguid.h> DEFINE_GUID(IID_IMovingTerrainProperty, 0x2f00012e, 0x7bae, 0x12fd, 0x83, 0x48, 0x00, 0xaa, 0x00, 0xa8, 0x2b, 0x51);
e188252719f1667e4925f307e3a9f1bd51fd49af
d053e0e8687f122d120bcd0fa1f9076deb35afa5
/Olymp/hackerrank/101_hack_36/maximum-cost-queries.cpp
670d0e263c36bc131184d39aec2244a3de4875ad
[]
no_license
shaihitdin/CP
e8911bc543932866d6fc83eb1d48d9cf79918c61
dc90082f3ebedaccbfb0818cc68539c887f86553
refs/heads/master
2021-01-11T17:10:20.356635
2017-10-05T08:53:56
2017-10-05T08:53:56
79,729,913
1
0
null
null
null
null
UTF-8
C++
false
false
2,072
cpp
#include <bits/stdc++.h> using namespace std; struct edge { int from; int to; int w; }; struct node { int v; int d; int comp; }; int const N = 333333; vector<edge> edges[N]; vector<node> sv[N]; int sz[N], banned[N]; multiset<int> best[N]; int painted[N]; #define mp make_pair void dfs(int v, int p) { sz[v] = 1; for (edge & e : edges[v]) { if (e.to == p || banned[e.to]) continue; dfs(e.to, v); sz[v] += sz[e.to]; } } void dfs2(int v, int p, int centroid, int d, int colorito) { sv[v].push_back({centroid, d, colorito}); for (edge & e : edges[v]) { if (e.to == p || banned[e.to]) continue; dfs2(e.to, v, centroid, max (d, e.w), (colorito == -1) ? e.to : colorito); } } void go(int v) { dfs(v, -1); int all = sz[v]; { int pv = -1; while (true) { bool changed = false; for (edge & e : edges[v]) { if (e.to == pv || banned[e.to]) continue; if (sz[e.to] * 2 > all) { pv = v; v = e.to; changed = true; break; } } if (!changed) break; } } dfs2(v, -1, v, 0, -1); banned[v] = true; for (edge & e : edges[v]) { if (!banned[e.to]) go(e.to); } } int const INF = 1 << 29; multiset <pair <int, int> > c[N]; map <int, int> cc; int main() { freopen("treeeg.in", "r", stdin); freopen("treeeg.out", "w", stdout); int n; scanf("%d", &n); for (int i = 0; i + 1 < n; i++) { int v, u, l; scanf("%d%d%d", &v, &u, &l); --v; --u; edges[v].push_back({v, u, l}); edges[u].push_back({u, v, l}); } go(0); int q; scanf("%d", &q); for (int i = 0; i < n; ++i) { for (auto ee : sv[i]) { c[ee.v].insert (mp (ee.d, ee.comp)); } } for (int i = 0; i < n; ++i) { int cnt = 0; for (auto v : c[i]) { ans += cnt - cc[v.second]++; ++cnt; } } cout << ans; }
3ab688123d9d8c3661ce354758f27229716cc216
a9e60be005d468781dc7ed2280a57286af009dc2
/main.cpp
3bb614e42cd2653f22b70b19df3124412a6fdb12
[]
no_license
ZhiqiJiang/openMP
e07eb3c359b63b4047cfb13189e171d0cfccf806
3c0ee1a16b0aae84efe20becd4a3f69b2d8e9135
refs/heads/main
2023-08-05T13:31:42.760667
2021-01-22T08:56:49
2021-01-22T08:56:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,337
cpp
#include <iostream> #include<opencv2/opencv.hpp> #include <omp.h> using namespace std; using namespace cv; bool processInput(std::vector<cv::Mat> imgs) { const int inputC = 3; const int inputH = 1080; const int inputW = 1920; // Fill data buffer float* hostDataBuffer = new float[imgs.size()*3*1920*1080]; // Host memory for input buffer for (int i = 0, volImg = inputC * inputH * inputW; i < imgs.size(); ++i) { for (int c = 0; c < inputC; ++c) { for (unsigned j = 0, volChl = inputH * inputW; j < volChl; ++j) { hostDataBuffer[i * volImg + c * volChl + j] = float(imgs[i].data[j * inputC + 2 - c])/255.; } } } return true; } int main() { int size = 16; double sum=0; Mat img=imread("/home/jiangzhiqi/1.jpg"); std::vector<cv::Mat> imgs; imgs.push_back(img); imgs.push_back(img); for(int j=0;j<1000;j++) { double time11=omp_get_wtime()*1000; #pragma omp parallel for num_threads(2) schedule(static, 8) for (int i = 0; i < size; ++i) { processInput(imgs); } double time22=omp_get_wtime()*1000; sum=sum+time22-time11; cout<<time22-time11<<"ms"<<endl; } cout<<"average="<<sum/1000<<endl; return 0; }
9963d928f18ffe88d559246bdb3330dfd76e320a
466e44131645fb20ee96a6a95ad0819a361346a9
/leetcodecpp/slidingWinMax.cpp
0ac7904620457fb570e36302260a1f365950c84e
[]
no_license
navyhu/all
2bdcb676a453200ed81e21c92374d302010858b2
02fa80d6edcca5e90fb1e9085a6a6b9299bb0ab8
refs/heads/master
2021-01-01T15:45:09.944583
2015-07-30T00:18:26
2015-07-30T00:18:26
38,821,647
0
0
null
null
null
null
UTF-8
C++
false
false
999
cpp
#include <vector> #include <deque> using namespace std; class Solution { public: vector<int> maxSlideingWindow(vector<int>& nums, int k) { if (nums.empty() || k <= 1) return nums; vector<int> result; // used to record the first element of the window vector<int>::iterator winFirst = nums.begin(); // deque to record elements, // bigger values are stored in begin( from start), // smaller values are stored in the rbegin(from end), // so the 'begin' one is the biggest one of the window, // we should erase deque<int> myDeque; int beginCnt = 1; int rbeginCnt = 0; // push back the 1st element myDeque.push_back(*nums.begin()); for (vector<int>::iterator it = nums.begin() + 1; it != nums.end(); it++) { deque<int> begin = myDeque.begin(); deque<int> rbegin = myDeque.rbegin; if (*it >= begin) myDeque.push_front(*it); else myDeque.push_back(*it); if (count >= k) { } } } };
6629053d25e995d777e63ef2132fca2fce8d15dd
57b0d12b0b1baa7c419ebbf28fdfb43729cc032e
/test/bool/allocator/move_assign.cc
ad90e5dc8bad8a3d0c9155dc7511a1a7ed76ba91
[]
no_license
PierreTSE/DynamicBitset
63b3455961ac156501e247a6fe4b40ab03744fac
b349f2303a69863c206757a3f06310f1d072149c
refs/heads/master
2020-05-17T16:57:18.251030
2019-05-02T20:47:06
2019-05-02T20:47:06
183,834,372
0
0
null
null
null
null
UTF-8
C++
false
false
2,132
cc
// Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // { dg-do run { target c++11 } } #include "../../../DynamicBitset.hpp" #include <catch.hpp> #include "testsuite_allocator.h" using T = bool; using __gnu_test::propagating_allocator; TEST_CASE("01") { typedef propagating_allocator<T, false> alloc_type; typedef std::vector<T, alloc_type> test_type; test_type v1(alloc_type(1)); v1.push_back(T()); test_type v2(alloc_type(2)); v2.push_back(T()); v2 = std::move(v1); REQUIRE(1 == v1.get_allocator().get_personality()); REQUIRE(2 == v2.get_allocator().get_personality()); } TEST_CASE("02") { typedef propagating_allocator<T, true> alloc_type; typedef std::vector<T, alloc_type> test_type; test_type v1(alloc_type(1)); v1.push_back(T()); auto it = v1.begin(); test_type v2(alloc_type(2)); v2.push_back(T()); v2 = std::move(v1); REQUIRE( it == v2.begin() ); REQUIRE(0 == v1.get_allocator().get_personality()); REQUIRE(1 == v2.get_allocator().get_personality()); } TEST_CASE("03") { typedef propagating_allocator<T, false> alloc_type; typedef std::vector<T, alloc_type> test_type; test_type v1(alloc_type(1)); v1.push_back(T()); auto it = v1.begin(); test_type v2(alloc_type(1)); v2.push_back(T()); v2 = std::move(v1); REQUIRE( it == v2.begin() ); REQUIRE(1 == v1.get_allocator().get_personality()); REQUIRE(1 == v2.get_allocator().get_personality()); }
59cfa65ad7e22174e2678c7796e7bae336c7df14
12201d8eadb08d60bd2ad6421f34b1f745ec5622
/planner/FD/src/search/ext/boost/config/compiler/pgi.hpp
add5a4d7f46642882255979a69f6c9d9b3a58592
[ "MIT" ]
permissive
karthikv792/PlanningAssistance
63b323edb7db943c33aaa6d08f9c9aeffed1a361
5693c844e9067591ea1414ee9586bcd2dfff6f51
refs/heads/current-dev
2020-09-01T22:48:21.289927
2019-09-23T22:21:16
2019-09-23T22:21:16
219,077,956
0
0
MIT
2019-11-08T00:27:42
2019-11-01T23:35:01
null
UTF-8
C++
false
false
2,197
hpp
// (C) Copyright Noel Belcourt 2007. // Use, modification and distribution are subject to 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) // See http://www.boost.org for most recent version. // PGI C++ compiler setup: #define BOOST_COMPILER_VERSION __PGIC__##__PGIC_MINOR__ #define BOOST_COMPILER "PGI compiler version " BOOST_STRINGIZE(_COMPILER_VERSION) // // Threading support: // Turn this on unconditionally here, it will get turned off again later // if no threading API is detected. // // PGI 10.x doesn't seem to define __PGIC__ // versions earlier than 10.x do define __PGIC__ #if __PGIC__ >= 10 // options requested by configure --enable-test #define BOOST_HAS_PTHREADS #define BOOST_HAS_NRVO #define BOOST_HAS_LONG_LONG // options --enable-test wants undefined #undef BOOST_NO_STDC_NAMESPACE #undef BOOST_NO_EXCEPTION_STD_NAMESPACE #undef BOOST_DEDUCED_TYPENAME #elif __PGIC__ >= 7 #define BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL #define BOOST_NO_TWO_PHASE_NAME_LOOKUP #define BOOST_NO_SWPRINTF #define BOOST_NO_AUTO_MULTIDECLARATIONS #define BOOST_NO_AUTO_DECLARATIONS #else # error "Pgi compiler not configured - please reconfigure" #endif // // C++0x features // // See boost\config\suffix.hpp for BOOST_NO_LONG_LONG // #define BOOST_NO_CHAR16_T #define BOOST_NO_CHAR32_T #define BOOST_NO_CONCEPTS #define BOOST_NO_CONSTEXPR #define BOOST_NO_DECLTYPE #define BOOST_NO_DEFAULTED_FUNCTIONS #define BOOST_NO_DELETED_FUNCTIONS #define BOOST_NO_EXPLICIT_CONVERSION_OPERATORS #define BOOST_NO_EXTERN_TEMPLATE #define BOOST_NO_FUNCTION_TEMPLATE_DEFAULT_ARGS #define BOOST_NO_INITIALIZER_LISTS #define BOOST_NO_LAMBDAS #define BOOST_NO_NULLPTR #define BOOST_NO_RAW_LITERALS #define BOOST_NO_RVALUE_REFERENCES #define BOOST_NO_SCOPED_ENUMS #define BOOST_NO_SFINAE_EXPR #define BOOST_NO_STATIC_ASSERT #define BOOST_NO_TEMPLATE_ALIASES #define BOOST_NO_UNICODE_LITERALS #define BOOST_NO_VARIADIC_TEMPLATES #define BOOST_NO_VARIADIC_MACROS // // version check: // probably nothing to do here?
[ "yochan@yochan1.wq05meqkrcaetfjrraeacfwdxc.dx.internal.cloudapp.net" ]
yochan@yochan1.wq05meqkrcaetfjrraeacfwdxc.dx.internal.cloudapp.net
e14595f7c0c57096c50e9feae7f1a4ce2b1e7219
0f00ef0c1371ee04aa5c792c03c1fd860e9f2ff6
/cmake/foonathan.net/include/my_library/header-a.hpp
3a9c7fc48b6e9b160cde73990c927334bc190e56
[]
no_license
glkhobragade/Git_Commands
b207de76e651be186d846f0018d53922097384bb
25318b3fc4ab04e663001f07784b1db72d857261
refs/heads/master
2020-12-30T17:00:06.474651
2020-08-08T09:49:17
2020-08-08T09:49:17
91,051,759
3
1
null
2017-05-12T06:34:00
2017-05-12T04:34:57
C
UTF-8
C++
false
false
28
hpp
int a = 10; int sqr(int n);
a634f3e81543921b55250e0992e5bce6ba93b9fb
c26631487f8e5c10b80d4f96710fed4309cdd354
/Dependence/PythonQt/generated_cpp/com_trolltech_qt_core/com_trolltech_qt_core0.h
663527a3cb9ff3d9f978001ead3cadeb746a0a4a
[]
no_license
ccdump/PebbleEngine
975fe39f80dc0a5b73257f528d459510fb69b23b
a7360989a204093dcbe4e70afa0d5a157284f296
refs/heads/master
2021-01-19T21:48:19.379256
2013-05-29T12:03:00
2013-05-29T12:03:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
80,770
h
#include <PythonQt.h> #include <QDateTime> #include <QDir> #include <QObject> #include <QSize> #include <QStringList> #include <QUrl> #include <QVariant> #include <qabstractanimation.h> #include <qabstractitemmodel.h> #include <qabstractstate.h> #include <qabstracttransition.h> #include <qanimationgroup.h> #include <qbasictimer.h> #include <qbuffer.h> #include <qbytearray.h> #include <qbytearraymatcher.h> #include <qcoreapplication.h> #include <qcoreevent.h> #include <qcryptographichash.h> #include <qdatastream.h> #include <qdatetime.h> #include <qdir.h> #include <qdiriterator.h> #include <qeasingcurve.h> #include <qeventloop.h> #include <qeventtransition.h> #include <qfactoryinterface.h> #include <qfile.h> #include <qfileinfo.h> #include <qfilesystemwatcher.h> #include <qfinalstate.h> #include <qhistorystate.h> #include <qiodevice.h> #include <qlibraryinfo.h> #include <qlist.h> #include <qmimedata.h> #include <qobject.h> #include <qsize.h> #include <qstate.h> #include <qstatemachine.h> #include <qstringlist.h> #include <qtranslator.h> #include <qurl.h> class PythonQtShell_QAbstractAnimation : public QAbstractAnimation { public: PythonQtShell_QAbstractAnimation(QObject* parent = 0):QAbstractAnimation(parent),_wrapper(NULL) {}; virtual void childEvent(QChildEvent* arg__1); virtual void customEvent(QEvent* arg__1); virtual int duration() const; virtual bool event(QEvent* event); virtual bool eventFilter(QObject* arg__1, QEvent* arg__2); virtual void timerEvent(QTimerEvent* arg__1); virtual void updateCurrentTime(int currentTime); virtual void updateDirection(QAbstractAnimation::Direction direction); virtual void updateState(QAbstractAnimation::State newState, QAbstractAnimation::State oldState); PythonQtInstanceWrapper* _wrapper; }; class PythonQtPublicPromoter_QAbstractAnimation : public QAbstractAnimation { public: inline bool promoted_event(QEvent* event) { return QAbstractAnimation::event(event); } inline void promoted_updateDirection(QAbstractAnimation::Direction direction) { QAbstractAnimation::updateDirection(direction); } inline void promoted_updateState(QAbstractAnimation::State newState, QAbstractAnimation::State oldState) { QAbstractAnimation::updateState(newState, oldState); } }; class PythonQtWrapper_QAbstractAnimation : public QObject { Q_OBJECT public: Q_ENUMS(DeletionPolicy ) enum DeletionPolicy{ KeepWhenStopped = QAbstractAnimation::KeepWhenStopped, DeleteWhenStopped = QAbstractAnimation::DeleteWhenStopped}; public slots: QAbstractAnimation* new_QAbstractAnimation(QObject* parent = 0); void delete_QAbstractAnimation(QAbstractAnimation* obj) { delete obj; } int currentLoop(QAbstractAnimation* theWrappedObject) const; int currentLoopTime(QAbstractAnimation* theWrappedObject) const; int currentTime(QAbstractAnimation* theWrappedObject) const; QAbstractAnimation::Direction direction(QAbstractAnimation* theWrappedObject) const; bool event(QAbstractAnimation* theWrappedObject, QEvent* event); QAnimationGroup* group(QAbstractAnimation* theWrappedObject) const; int loopCount(QAbstractAnimation* theWrappedObject) const; void setDirection(QAbstractAnimation* theWrappedObject, QAbstractAnimation::Direction direction); void setLoopCount(QAbstractAnimation* theWrappedObject, int loopCount); QAbstractAnimation::State state(QAbstractAnimation* theWrappedObject) const; int totalDuration(QAbstractAnimation* theWrappedObject) const; void updateDirection(QAbstractAnimation* theWrappedObject, QAbstractAnimation::Direction direction); void updateState(QAbstractAnimation* theWrappedObject, QAbstractAnimation::State newState, QAbstractAnimation::State oldState); }; class PythonQtShell_QAbstractItemModel : public QAbstractItemModel { public: PythonQtShell_QAbstractItemModel(QObject* parent = 0):QAbstractItemModel(parent),_wrapper(NULL) {}; virtual QModelIndex buddy(const QModelIndex& index) const; virtual bool canFetchMore(const QModelIndex& parent) const; virtual void childEvent(QChildEvent* arg__1); virtual int columnCount(const QModelIndex& parent = QModelIndex()) const; virtual void customEvent(QEvent* arg__1); virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; virtual bool dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent); virtual bool event(QEvent* arg__1); virtual bool eventFilter(QObject* arg__1, QEvent* arg__2); virtual void fetchMore(const QModelIndex& parent); virtual Qt::ItemFlags flags(const QModelIndex& index) const; virtual bool hasChildren(const QModelIndex& parent = QModelIndex()) const; virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; virtual QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const; virtual bool insertColumns(int column, int count, const QModelIndex& parent = QModelIndex()); virtual bool insertRows(int row, int count, const QModelIndex& parent = QModelIndex()); virtual QMap<int , QVariant > itemData(const QModelIndex& index) const; virtual QList<QModelIndex > match(const QModelIndex& start, int role, const QVariant& value, int hits = 1, Qt::MatchFlags flags = Qt::MatchFlags(Qt::MatchStartsWith|Qt::MatchWrap)) const; virtual QMimeData* mimeData(const QList<QModelIndex >& indexes) const; virtual QStringList mimeTypes() const; virtual QModelIndex parent(const QModelIndex& child) const; virtual bool removeColumns(int column, int count, const QModelIndex& parent = QModelIndex()); virtual bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex()); virtual void revert(); virtual int rowCount(const QModelIndex& parent = QModelIndex()) const; virtual bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole); virtual bool setHeaderData(int section, Qt::Orientation orientation, const QVariant& value, int role = Qt::EditRole); virtual bool setItemData(const QModelIndex& index, const QMap<int , QVariant >& roles); virtual void sort(int column, Qt::SortOrder order = Qt::AscendingOrder); virtual QSize span(const QModelIndex& index) const; virtual bool submit(); virtual Qt::DropActions supportedDropActions() const; virtual void timerEvent(QTimerEvent* arg__1); PythonQtInstanceWrapper* _wrapper; }; class PythonQtPublicPromoter_QAbstractItemModel : public QAbstractItemModel { public: inline QModelIndex promoted_buddy(const QModelIndex& index) const { return QAbstractItemModel::buddy(index); } inline bool promoted_canFetchMore(const QModelIndex& parent) const { return QAbstractItemModel::canFetchMore(parent); } inline bool promoted_dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent) { return QAbstractItemModel::dropMimeData(data, action, row, column, parent); } inline void promoted_fetchMore(const QModelIndex& parent) { QAbstractItemModel::fetchMore(parent); } inline Qt::ItemFlags promoted_flags(const QModelIndex& index) const { return QAbstractItemModel::flags(index); } inline bool promoted_hasChildren(const QModelIndex& parent = QModelIndex()) const { return QAbstractItemModel::hasChildren(parent); } inline QVariant promoted_headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const { return QAbstractItemModel::headerData(section, orientation, role); } inline bool promoted_insertColumns(int column, int count, const QModelIndex& parent = QModelIndex()) { return QAbstractItemModel::insertColumns(column, count, parent); } inline bool promoted_insertRows(int row, int count, const QModelIndex& parent = QModelIndex()) { return QAbstractItemModel::insertRows(row, count, parent); } inline QMap<int , QVariant > promoted_itemData(const QModelIndex& index) const { return QAbstractItemModel::itemData(index); } inline QList<QModelIndex > promoted_match(const QModelIndex& start, int role, const QVariant& value, int hits = 1, Qt::MatchFlags flags = Qt::MatchFlags(Qt::MatchStartsWith|Qt::MatchWrap)) const { return QAbstractItemModel::match(start, role, value, hits, flags); } inline QMimeData* promoted_mimeData(const QList<QModelIndex >& indexes) const { return QAbstractItemModel::mimeData(indexes); } inline QStringList promoted_mimeTypes() const { return QAbstractItemModel::mimeTypes(); } inline bool promoted_removeColumns(int column, int count, const QModelIndex& parent = QModelIndex()) { return QAbstractItemModel::removeColumns(column, count, parent); } inline bool promoted_removeRows(int row, int count, const QModelIndex& parent = QModelIndex()) { return QAbstractItemModel::removeRows(row, count, parent); } inline void promoted_revert() { QAbstractItemModel::revert(); } inline bool promoted_setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) { return QAbstractItemModel::setData(index, value, role); } inline bool promoted_setHeaderData(int section, Qt::Orientation orientation, const QVariant& value, int role = Qt::EditRole) { return QAbstractItemModel::setHeaderData(section, orientation, value, role); } inline bool promoted_setItemData(const QModelIndex& index, const QMap<int , QVariant >& roles) { return QAbstractItemModel::setItemData(index, roles); } inline void promoted_sort(int column, Qt::SortOrder order = Qt::AscendingOrder) { QAbstractItemModel::sort(column, order); } inline QSize promoted_span(const QModelIndex& index) const { return QAbstractItemModel::span(index); } inline bool promoted_submit() { return QAbstractItemModel::submit(); } inline Qt::DropActions promoted_supportedDropActions() const { return QAbstractItemModel::supportedDropActions(); } }; class PythonQtWrapper_QAbstractItemModel : public QObject { Q_OBJECT public: public slots: QAbstractItemModel* new_QAbstractItemModel(QObject* parent = 0); void delete_QAbstractItemModel(QAbstractItemModel* obj) { delete obj; } QModelIndex buddy(QAbstractItemModel* theWrappedObject, const QModelIndex& index) const; bool canFetchMore(QAbstractItemModel* theWrappedObject, const QModelIndex& parent) const; bool dropMimeData(QAbstractItemModel* theWrappedObject, const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent); void fetchMore(QAbstractItemModel* theWrappedObject, const QModelIndex& parent); Qt::ItemFlags flags(QAbstractItemModel* theWrappedObject, const QModelIndex& index) const; bool hasChildren(QAbstractItemModel* theWrappedObject, const QModelIndex& parent = QModelIndex()) const; bool hasIndex(QAbstractItemModel* theWrappedObject, int row, int column, const QModelIndex& parent = QModelIndex()) const; QVariant headerData(QAbstractItemModel* theWrappedObject, int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; bool insertColumn(QAbstractItemModel* theWrappedObject, int column, const QModelIndex& parent = QModelIndex()); bool insertColumns(QAbstractItemModel* theWrappedObject, int column, int count, const QModelIndex& parent = QModelIndex()); bool insertRow(QAbstractItemModel* theWrappedObject, int row, const QModelIndex& parent = QModelIndex()); bool insertRows(QAbstractItemModel* theWrappedObject, int row, int count, const QModelIndex& parent = QModelIndex()); QMap<int , QVariant > itemData(QAbstractItemModel* theWrappedObject, const QModelIndex& index) const; QList<QModelIndex > match(QAbstractItemModel* theWrappedObject, const QModelIndex& start, int role, const QVariant& value, int hits = 1, Qt::MatchFlags flags = Qt::MatchFlags(Qt::MatchStartsWith|Qt::MatchWrap)) const; QMimeData* mimeData(QAbstractItemModel* theWrappedObject, const QList<QModelIndex >& indexes) const; QStringList mimeTypes(QAbstractItemModel* theWrappedObject) const; QObject* parent(QAbstractItemModel* theWrappedObject) const; bool removeColumn(QAbstractItemModel* theWrappedObject, int column, const QModelIndex& parent = QModelIndex()); bool removeColumns(QAbstractItemModel* theWrappedObject, int column, int count, const QModelIndex& parent = QModelIndex()); bool removeRow(QAbstractItemModel* theWrappedObject, int row, const QModelIndex& parent = QModelIndex()); bool removeRows(QAbstractItemModel* theWrappedObject, int row, int count, const QModelIndex& parent = QModelIndex()); const QHash<int , QByteArray >* roleNames(QAbstractItemModel* theWrappedObject) const; bool setData(QAbstractItemModel* theWrappedObject, const QModelIndex& index, const QVariant& value, int role = Qt::EditRole); bool setHeaderData(QAbstractItemModel* theWrappedObject, int section, Qt::Orientation orientation, const QVariant& value, int role = Qt::EditRole); bool setItemData(QAbstractItemModel* theWrappedObject, const QModelIndex& index, const QMap<int , QVariant >& roles); void setSupportedDragActions(QAbstractItemModel* theWrappedObject, Qt::DropActions arg__1); QModelIndex sibling(QAbstractItemModel* theWrappedObject, int row, int column, const QModelIndex& idx) const; void sort(QAbstractItemModel* theWrappedObject, int column, Qt::SortOrder order = Qt::AscendingOrder); QSize span(QAbstractItemModel* theWrappedObject, const QModelIndex& index) const; Qt::DropActions supportedDragActions(QAbstractItemModel* theWrappedObject) const; Qt::DropActions supportedDropActions(QAbstractItemModel* theWrappedObject) const; }; class PythonQtShell_QAbstractListModel : public QAbstractListModel { public: PythonQtShell_QAbstractListModel(QObject* parent = 0):QAbstractListModel(parent),_wrapper(NULL) {}; virtual QModelIndex buddy(const QModelIndex& index) const; virtual bool canFetchMore(const QModelIndex& parent) const; virtual void childEvent(QChildEvent* arg__1); virtual void customEvent(QEvent* arg__1); virtual QVariant data(const QModelIndex& index, int role) const; virtual bool dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent); virtual bool event(QEvent* arg__1); virtual bool eventFilter(QObject* arg__1, QEvent* arg__2); virtual void fetchMore(const QModelIndex& parent); virtual Qt::ItemFlags flags(const QModelIndex& index) const; virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const; virtual QModelIndex index(int row, int column = 0, const QModelIndex& parent = QModelIndex()) const; virtual bool insertColumns(int column, int count, const QModelIndex& parent); virtual bool insertRows(int row, int count, const QModelIndex& parent); virtual QMap<int , QVariant > itemData(const QModelIndex& index) const; virtual QList<QModelIndex > match(const QModelIndex& start, int role, const QVariant& value, int hits, Qt::MatchFlags flags) const; virtual QMimeData* mimeData(const QList<QModelIndex >& indexes) const; virtual QStringList mimeTypes() const; virtual bool removeColumns(int column, int count, const QModelIndex& parent); virtual bool removeRows(int row, int count, const QModelIndex& parent); virtual void revert(); virtual int rowCount(const QModelIndex& parent) const; virtual bool setData(const QModelIndex& index, const QVariant& value, int role); virtual bool setHeaderData(int section, Qt::Orientation orientation, const QVariant& value, int role); virtual bool setItemData(const QModelIndex& index, const QMap<int , QVariant >& roles); virtual void sort(int column, Qt::SortOrder order); virtual QSize span(const QModelIndex& index) const; virtual bool submit(); virtual Qt::DropActions supportedDropActions() const; virtual void timerEvent(QTimerEvent* arg__1); PythonQtInstanceWrapper* _wrapper; }; class PythonQtPublicPromoter_QAbstractListModel : public QAbstractListModel { public: inline bool promoted_dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent) { return QAbstractListModel::dropMimeData(data, action, row, column, parent); } inline QModelIndex promoted_index(int row, int column = 0, const QModelIndex& parent = QModelIndex()) const { return QAbstractListModel::index(row, column, parent); } }; class PythonQtWrapper_QAbstractListModel : public QObject { Q_OBJECT public: public slots: QAbstractListModel* new_QAbstractListModel(QObject* parent = 0); void delete_QAbstractListModel(QAbstractListModel* obj) { delete obj; } bool dropMimeData(QAbstractListModel* theWrappedObject, const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent); QModelIndex index(QAbstractListModel* theWrappedObject, int row, int column = 0, const QModelIndex& parent = QModelIndex()) const; }; class PythonQtShell_QAbstractState : public QAbstractState { public: PythonQtShell_QAbstractState(QState* parent = 0):QAbstractState(parent),_wrapper(NULL) {}; virtual void childEvent(QChildEvent* arg__1); virtual void customEvent(QEvent* arg__1); virtual bool event(QEvent* e); virtual bool eventFilter(QObject* arg__1, QEvent* arg__2); virtual void onEntry(QEvent* event); virtual void onExit(QEvent* event); virtual void timerEvent(QTimerEvent* arg__1); PythonQtInstanceWrapper* _wrapper; }; class PythonQtPublicPromoter_QAbstractState : public QAbstractState { public: inline bool promoted_event(QEvent* e) { return QAbstractState::event(e); } }; class PythonQtWrapper_QAbstractState : public QObject { Q_OBJECT public: public slots: void delete_QAbstractState(QAbstractState* obj) { delete obj; } bool event(QAbstractState* theWrappedObject, QEvent* e); QStateMachine* machine(QAbstractState* theWrappedObject) const; QState* parentState(QAbstractState* theWrappedObject) const; }; class PythonQtShell_QAbstractTransition : public QAbstractTransition { public: PythonQtShell_QAbstractTransition(QState* sourceState = 0):QAbstractTransition(sourceState),_wrapper(NULL) {}; virtual void childEvent(QChildEvent* arg__1); virtual void customEvent(QEvent* arg__1); virtual bool event(QEvent* e); virtual bool eventFilter(QObject* arg__1, QEvent* arg__2); virtual bool eventTest(QEvent* event); virtual void onTransition(QEvent* event); virtual void timerEvent(QTimerEvent* arg__1); PythonQtInstanceWrapper* _wrapper; }; class PythonQtPublicPromoter_QAbstractTransition : public QAbstractTransition { public: inline bool promoted_event(QEvent* e) { return QAbstractTransition::event(e); } }; class PythonQtWrapper_QAbstractTransition : public QObject { Q_OBJECT public: public slots: QAbstractTransition* new_QAbstractTransition(QState* sourceState = 0); void delete_QAbstractTransition(QAbstractTransition* obj) { delete obj; } void addAnimation(QAbstractTransition* theWrappedObject, QAbstractAnimation* animation); QList<QAbstractAnimation* > animations(QAbstractTransition* theWrappedObject) const; bool event(QAbstractTransition* theWrappedObject, QEvent* e); QStateMachine* machine(QAbstractTransition* theWrappedObject) const; void removeAnimation(QAbstractTransition* theWrappedObject, QAbstractAnimation* animation); void setTargetState(QAbstractTransition* theWrappedObject, QAbstractState* target); void setTargetStates(QAbstractTransition* theWrappedObject, const QList<QAbstractState* >& targets); QState* sourceState(QAbstractTransition* theWrappedObject) const; QAbstractState* targetState(QAbstractTransition* theWrappedObject) const; QList<QAbstractState* > targetStates(QAbstractTransition* theWrappedObject) const; }; class PythonQtShell_QAnimationGroup : public QAnimationGroup { public: PythonQtShell_QAnimationGroup(QObject* parent = 0):QAnimationGroup(parent),_wrapper(NULL) {}; virtual void childEvent(QChildEvent* arg__1); virtual void customEvent(QEvent* arg__1); virtual int duration() const; virtual bool event(QEvent* event); virtual bool eventFilter(QObject* arg__1, QEvent* arg__2); virtual void timerEvent(QTimerEvent* arg__1); virtual void updateCurrentTime(int currentTime); virtual void updateDirection(QAbstractAnimation::Direction direction); virtual void updateState(QAbstractAnimation::State newState, QAbstractAnimation::State oldState); PythonQtInstanceWrapper* _wrapper; }; class PythonQtPublicPromoter_QAnimationGroup : public QAnimationGroup { public: inline bool promoted_event(QEvent* event) { return QAnimationGroup::event(event); } }; class PythonQtWrapper_QAnimationGroup : public QObject { Q_OBJECT public: public slots: QAnimationGroup* new_QAnimationGroup(QObject* parent = 0); void delete_QAnimationGroup(QAnimationGroup* obj) { delete obj; } void addAnimation(QAnimationGroup* theWrappedObject, QAbstractAnimation* animation); QAbstractAnimation* animationAt(QAnimationGroup* theWrappedObject, int index) const; int animationCount(QAnimationGroup* theWrappedObject) const; void clear(QAnimationGroup* theWrappedObject); bool event(QAnimationGroup* theWrappedObject, QEvent* event); int indexOfAnimation(QAnimationGroup* theWrappedObject, QAbstractAnimation* animation) const; void insertAnimation(QAnimationGroup* theWrappedObject, int index, QAbstractAnimation* animation); void removeAnimation(QAnimationGroup* theWrappedObject, QAbstractAnimation* animation); QAbstractAnimation* takeAnimation(QAnimationGroup* theWrappedObject, int index); }; class PythonQtWrapper_QBasicTimer : public QObject { Q_OBJECT public: public slots: QBasicTimer* new_QBasicTimer(); QBasicTimer* new_QBasicTimer(const QBasicTimer& other) { QBasicTimer* a = new QBasicTimer(); *((QBasicTimer*)a) = other; return a; } void delete_QBasicTimer(QBasicTimer* obj) { delete obj; } bool isActive(QBasicTimer* theWrappedObject) const; void start(QBasicTimer* theWrappedObject, int msec, QObject* obj); void stop(QBasicTimer* theWrappedObject); int timerId(QBasicTimer* theWrappedObject) const; }; class PythonQtShell_QBuffer : public QBuffer { public: PythonQtShell_QBuffer(QByteArray* buf, QObject* parent = 0):QBuffer(buf, parent),_wrapper(NULL) {}; PythonQtShell_QBuffer(QObject* parent = 0):QBuffer(parent),_wrapper(NULL) {}; virtual bool atEnd() const; virtual qint64 bytesAvailable() const; virtual qint64 bytesToWrite() const; virtual bool canReadLine() const; virtual void childEvent(QChildEvent* arg__1); virtual void close(); virtual void customEvent(QEvent* arg__1); virtual bool event(QEvent* arg__1); virtual bool eventFilter(QObject* arg__1, QEvent* arg__2); virtual bool isSequential() const; virtual bool open(QIODevice::OpenMode openMode); virtual qint64 pos() const; virtual qint64 readData(char* data, qint64 maxlen); virtual qint64 readLineData(char* data, qint64 maxlen); virtual bool reset(); virtual bool seek(qint64 off); virtual qint64 size() const; virtual void timerEvent(QTimerEvent* arg__1); virtual bool waitForBytesWritten(int msecs); virtual bool waitForReadyRead(int msecs); virtual qint64 writeData(const char* data, qint64 len); PythonQtInstanceWrapper* _wrapper; }; class PythonQtPublicPromoter_QBuffer : public QBuffer { public: inline bool promoted_atEnd() const { return QBuffer::atEnd(); } inline bool promoted_canReadLine() const { return QBuffer::canReadLine(); } inline void promoted_close() { QBuffer::close(); } inline bool promoted_open(QIODevice::OpenMode openMode) { return QBuffer::open(openMode); } inline qint64 promoted_pos() const { return QBuffer::pos(); } inline qint64 promoted_readData(char* data, qint64 maxlen) { return QBuffer::readData(data, maxlen); } inline bool promoted_seek(qint64 off) { return QBuffer::seek(off); } inline qint64 promoted_size() const { return QBuffer::size(); } inline qint64 promoted_writeData(const char* data, qint64 len) { return QBuffer::writeData(data, len); } }; class PythonQtWrapper_QBuffer : public QObject { Q_OBJECT public: public slots: QBuffer* new_QBuffer(QByteArray* buf, QObject* parent = 0); QBuffer* new_QBuffer(QObject* parent = 0); void delete_QBuffer(QBuffer* obj) { delete obj; } bool atEnd(QBuffer* theWrappedObject) const; bool canReadLine(QBuffer* theWrappedObject) const; void close(QBuffer* theWrappedObject); bool open(QBuffer* theWrappedObject, QIODevice::OpenMode openMode); qint64 pos(QBuffer* theWrappedObject) const; qint64 readData(QBuffer* theWrappedObject, char* data, qint64 maxlen); bool seek(QBuffer* theWrappedObject, qint64 off); void setBuffer(QBuffer* theWrappedObject, QByteArray* a); void setData(QBuffer* theWrappedObject, const QByteArray& data); qint64 size(QBuffer* theWrappedObject) const; qint64 writeData(QBuffer* theWrappedObject, const char* data, qint64 len); }; class PythonQtWrapper_QByteArrayMatcher : public QObject { Q_OBJECT public: public slots: QByteArrayMatcher* new_QByteArrayMatcher(); QByteArrayMatcher* new_QByteArrayMatcher(const QByteArray& pattern); QByteArrayMatcher* new_QByteArrayMatcher(const QByteArrayMatcher& other); QByteArrayMatcher* new_QByteArrayMatcher(const char* pattern, int length); void delete_QByteArrayMatcher(QByteArrayMatcher* obj) { delete obj; } int indexIn(QByteArrayMatcher* theWrappedObject, const QByteArray& ba, int from = 0) const; int indexIn(QByteArrayMatcher* theWrappedObject, const char* str, int len, int from = 0) const; QByteArray pattern(QByteArrayMatcher* theWrappedObject) const; void setPattern(QByteArrayMatcher* theWrappedObject, const QByteArray& pattern); }; class PythonQtShell_QChildEvent : public QChildEvent { public: PythonQtShell_QChildEvent(QEvent::Type type, QObject* child):QChildEvent(type, child),_wrapper(NULL) {}; PythonQtInstanceWrapper* _wrapper; }; class PythonQtWrapper_QChildEvent : public QObject { Q_OBJECT public: public slots: QChildEvent* new_QChildEvent(QEvent::Type type, QObject* child); void delete_QChildEvent(QChildEvent* obj) { delete obj; } bool added(QChildEvent* theWrappedObject) const; QObject* child(QChildEvent* theWrappedObject) const; bool polished(QChildEvent* theWrappedObject) const; bool removed(QChildEvent* theWrappedObject) const; }; class PythonQtShell_QCoreApplication : public QCoreApplication { public: PythonQtShell_QCoreApplication(int& argc, char** argv):QCoreApplication(argc, argv),_wrapper(NULL) {}; virtual void childEvent(QChildEvent* arg__1); virtual void customEvent(QEvent* arg__1); virtual bool event(QEvent* arg__1); virtual bool eventFilter(QObject* arg__1, QEvent* arg__2); virtual bool notify(QObject* arg__1, QEvent* arg__2); virtual void timerEvent(QTimerEvent* arg__1); PythonQtInstanceWrapper* _wrapper; }; class PythonQtPublicPromoter_QCoreApplication : public QCoreApplication { public: inline bool promoted_event(QEvent* arg__1) { return QCoreApplication::event(arg__1); } inline bool promoted_notify(QObject* arg__1, QEvent* arg__2) { return QCoreApplication::notify(arg__1, arg__2); } }; class PythonQtWrapper_QCoreApplication : public QObject { Q_OBJECT public: Q_ENUMS(Encoding ) enum Encoding{ CodecForTr = QCoreApplication::CodecForTr, UnicodeUTF8 = QCoreApplication::UnicodeUTF8, DefaultCodec = QCoreApplication::DefaultCodec}; public slots: QCoreApplication* new_QCoreApplication(int& argc, char** argv); void delete_QCoreApplication(QCoreApplication* obj) { delete obj; } void static_QCoreApplication_addLibraryPath(const QString& arg__1); QString static_QCoreApplication_applicationDirPath(); QString static_QCoreApplication_applicationFilePath(); QString static_QCoreApplication_applicationName(); qint64 static_QCoreApplication_applicationPid(); QString static_QCoreApplication_applicationVersion(); bool static_QCoreApplication_closingDown(); bool event(QCoreApplication* theWrappedObject, QEvent* arg__1); int static_QCoreApplication_exec(); void static_QCoreApplication_exit(int retcode = 0); void static_QCoreApplication_flush(); bool static_QCoreApplication_hasPendingEvents(); void static_QCoreApplication_installTranslator(QTranslator* messageFile); QCoreApplication* static_QCoreApplication_instance(); QStringList static_QCoreApplication_libraryPaths(); bool notify(QCoreApplication* theWrappedObject, QObject* arg__1, QEvent* arg__2); QString static_QCoreApplication_organizationDomain(); QString static_QCoreApplication_organizationName(); void static_QCoreApplication_postEvent(QObject* receiver, QEvent* event); void static_QCoreApplication_postEvent(QObject* receiver, QEvent* event, int priority); void static_QCoreApplication_processEvents(QEventLoop::ProcessEventsFlags flags = QEventLoop::AllEvents); void static_QCoreApplication_processEvents(QEventLoop::ProcessEventsFlags flags, int maxtime); void static_QCoreApplication_removeLibraryPath(const QString& arg__1); void static_QCoreApplication_removePostedEvents(QObject* receiver); void static_QCoreApplication_removePostedEvents(QObject* receiver, int eventType); void static_QCoreApplication_removeTranslator(QTranslator* messageFile); bool static_QCoreApplication_sendEvent(QObject* receiver, QEvent* event); void static_QCoreApplication_sendPostedEvents(); void static_QCoreApplication_sendPostedEvents(QObject* receiver, int event_type); void static_QCoreApplication_setApplicationName(const QString& application); void static_QCoreApplication_setApplicationVersion(const QString& version); void static_QCoreApplication_setAttribute(Qt::ApplicationAttribute attribute, bool on = true); void static_QCoreApplication_setLibraryPaths(const QStringList& arg__1); void static_QCoreApplication_setOrganizationDomain(const QString& orgDomain); void static_QCoreApplication_setOrganizationName(const QString& orgName); bool static_QCoreApplication_startingUp(); bool static_QCoreApplication_testAttribute(Qt::ApplicationAttribute attribute); QString static_QCoreApplication_translate(const char* context, const char* key, const char* disambiguation = 0, QCoreApplication::Encoding encoding = QCoreApplication::CodecForTr); QString static_QCoreApplication_translate(const char* context, const char* key, const char* disambiguation, QCoreApplication::Encoding encoding, int n); }; class PythonQtWrapper_QCryptographicHash : public QObject { Q_OBJECT public: Q_ENUMS(Algorithm ) enum Algorithm{ Md4 = QCryptographicHash::Md4, Md5 = QCryptographicHash::Md5, Sha1 = QCryptographicHash::Sha1}; public slots: QCryptographicHash* new_QCryptographicHash(QCryptographicHash::Algorithm method); void delete_QCryptographicHash(QCryptographicHash* obj) { delete obj; } void addData(QCryptographicHash* theWrappedObject, const QByteArray& data); QByteArray static_QCryptographicHash_hash(const QByteArray& data, QCryptographicHash::Algorithm method); void reset(QCryptographicHash* theWrappedObject); QByteArray result(QCryptographicHash* theWrappedObject) const; }; class PythonQtShell_QDataStream : public QDataStream { public: PythonQtShell_QDataStream():QDataStream(),_wrapper(NULL) {}; PythonQtShell_QDataStream(QByteArray* arg__1, QIODevice::OpenMode flags):QDataStream(arg__1, flags),_wrapper(NULL) {}; PythonQtShell_QDataStream(QIODevice* arg__1):QDataStream(arg__1),_wrapper(NULL) {}; PythonQtShell_QDataStream(const QByteArray& arg__1):QDataStream(arg__1),_wrapper(NULL) {}; PythonQtInstanceWrapper* _wrapper; }; class PythonQtWrapper_QDataStream : public QObject { Q_OBJECT public: Q_ENUMS(FloatingPointPrecision Version Status ) enum FloatingPointPrecision{ SinglePrecision = QDataStream::SinglePrecision, DoublePrecision = QDataStream::DoublePrecision}; enum Version{ Qt_1_0 = QDataStream::Qt_1_0, Qt_2_0 = QDataStream::Qt_2_0, Qt_2_1 = QDataStream::Qt_2_1, Qt_3_0 = QDataStream::Qt_3_0, Qt_3_1 = QDataStream::Qt_3_1, Qt_3_3 = QDataStream::Qt_3_3, Qt_4_0 = QDataStream::Qt_4_0, Qt_4_1 = QDataStream::Qt_4_1, Qt_4_2 = QDataStream::Qt_4_2, Qt_4_3 = QDataStream::Qt_4_3, Qt_4_4 = QDataStream::Qt_4_4, Qt_4_5 = QDataStream::Qt_4_5, Qt_4_6 = QDataStream::Qt_4_6, Qt_4_7 = QDataStream::Qt_4_7, Qt_4_8 = QDataStream::Qt_4_8}; enum Status{ Ok = QDataStream::Ok, ReadPastEnd = QDataStream::ReadPastEnd, ReadCorruptData = QDataStream::ReadCorruptData, WriteFailed = QDataStream::WriteFailed}; public slots: QDataStream* new_QDataStream(); QDataStream* new_QDataStream(QByteArray* arg__1, QIODevice::OpenMode flags); QDataStream* new_QDataStream(QIODevice* arg__1); QDataStream* new_QDataStream(const QByteArray& arg__1); void delete_QDataStream(QDataStream* obj) { delete obj; } bool atEnd(QDataStream* theWrappedObject) const; QIODevice* device(QDataStream* theWrappedObject) const; QDataStream::FloatingPointPrecision floatingPointPrecision(QDataStream* theWrappedObject) const; QDataStream* writeBoolean(QDataStream* theWrappedObject, bool i); QDataStream* writeDouble(QDataStream* theWrappedObject, double f); QDataStream* writeFloat(QDataStream* theWrappedObject, float f); QDataStream* writeInt(QDataStream* theWrappedObject, int i); QDataStream* writeLongLong(QDataStream* theWrappedObject, qint64 i); QDataStream* writeShort(QDataStream* theWrappedObject, short i); QDataStream* readBoolean(QDataStream* theWrappedObject, bool& i); QDataStream* readDouble(QDataStream* theWrappedObject, double& f); QDataStream* readFloat(QDataStream* theWrappedObject, float& f); QDataStream* readInt(QDataStream* theWrappedObject, int& i); QDataStream* readLongLong(QDataStream* theWrappedObject, qint64& i); QDataStream* readShort(QDataStream* theWrappedObject, short& i); QDataStream* readUShort(QDataStream* theWrappedObject, unsigned short& i); void resetStatus(QDataStream* theWrappedObject); void setDevice(QDataStream* theWrappedObject, QIODevice* arg__1); void setFloatingPointPrecision(QDataStream* theWrappedObject, QDataStream::FloatingPointPrecision precision); void setStatus(QDataStream* theWrappedObject, QDataStream::Status status); void setVersion(QDataStream* theWrappedObject, int arg__1); int skipRawData(QDataStream* theWrappedObject, int len); QDataStream::Status status(QDataStream* theWrappedObject) const; void unsetDevice(QDataStream* theWrappedObject); int version(QDataStream* theWrappedObject) const; }; class PythonQtWrapper_QDir : public QObject { Q_OBJECT public: Q_ENUMS(Filter SortFlag ) Q_FLAGS(Filters SortFlags ) enum Filter{ Dirs = QDir::Dirs, Files = QDir::Files, Drives = QDir::Drives, NoSymLinks = QDir::NoSymLinks, AllEntries = QDir::AllEntries, TypeMask = QDir::TypeMask, Readable = QDir::Readable, Writable = QDir::Writable, Executable = QDir::Executable, PermissionMask = QDir::PermissionMask, Modified = QDir::Modified, Hidden = QDir::Hidden, System = QDir::System, AccessMask = QDir::AccessMask, AllDirs = QDir::AllDirs, CaseSensitive = QDir::CaseSensitive, NoDotAndDotDot = QDir::NoDotAndDotDot, NoDot = QDir::NoDot, NoDotDot = QDir::NoDotDot, NoFilter = QDir::NoFilter}; enum SortFlag{ Name = QDir::Name, Time = QDir::Time, Size = QDir::Size, Unsorted = QDir::Unsorted, SortByMask = QDir::SortByMask, DirsFirst = QDir::DirsFirst, Reversed = QDir::Reversed, IgnoreCase = QDir::IgnoreCase, DirsLast = QDir::DirsLast, LocaleAware = QDir::LocaleAware, Type = QDir::Type, NoSort = QDir::NoSort}; Q_DECLARE_FLAGS(Filters, Filter) Q_DECLARE_FLAGS(SortFlags, SortFlag) public slots: QDir* new_QDir(const QDir& arg__1); QDir* new_QDir(const QString& path = QString()); QDir* new_QDir(const QString& path, const QString& nameFilter, QDir::SortFlags sort = QDir::SortFlags(Name | IgnoreCase), QDir::Filters filter = QDir::AllEntries); void delete_QDir(QDir* obj) { delete obj; } QString absoluteFilePath(QDir* theWrappedObject, const QString& fileName) const; QString absolutePath(QDir* theWrappedObject) const; void static_QDir_addSearchPath(const QString& prefix, const QString& path); QString canonicalPath(QDir* theWrappedObject) const; bool cd(QDir* theWrappedObject, const QString& dirName); bool cdUp(QDir* theWrappedObject); QString static_QDir_cleanPath(const QString& path); QString static_QDir_convertSeparators(const QString& pathName); uint count(QDir* theWrappedObject) const; QDir static_QDir_current(); QString static_QDir_currentPath(); QString dirName(QDir* theWrappedObject) const; QList<QFileInfo > static_QDir_drives(); QList<QFileInfo > entryInfoList(QDir* theWrappedObject, QDir::Filters filters = QDir::NoFilter, QDir::SortFlags sort = QDir::NoSort) const; QList<QFileInfo > entryInfoList(QDir* theWrappedObject, const QStringList& nameFilters, QDir::Filters filters = QDir::NoFilter, QDir::SortFlags sort = QDir::NoSort) const; QStringList entryList(QDir* theWrappedObject, QDir::Filters filters = QDir::NoFilter, QDir::SortFlags sort = QDir::NoSort) const; QStringList entryList(QDir* theWrappedObject, const QStringList& nameFilters, QDir::Filters filters = QDir::NoFilter, QDir::SortFlags sort = QDir::NoSort) const; bool exists(QDir* theWrappedObject) const; bool exists(QDir* theWrappedObject, const QString& name) const; QString filePath(QDir* theWrappedObject, const QString& fileName) const; QDir::Filters filter(QDir* theWrappedObject) const; QString static_QDir_fromNativeSeparators(const QString& pathName); QDir static_QDir_home(); QString static_QDir_homePath(); bool isAbsolute(QDir* theWrappedObject) const; bool static_QDir_isAbsolutePath(const QString& path); bool isReadable(QDir* theWrappedObject) const; bool isRelative(QDir* theWrappedObject) const; bool static_QDir_isRelativePath(const QString& path); bool isRoot(QDir* theWrappedObject) const; bool makeAbsolute(QDir* theWrappedObject); bool static_QDir_match(const QString& filter, const QString& fileName); bool static_QDir_match(const QStringList& filters, const QString& fileName); bool mkdir(QDir* theWrappedObject, const QString& dirName) const; bool mkpath(QDir* theWrappedObject, const QString& dirPath) const; QStringList nameFilters(QDir* theWrappedObject) const; QStringList static_QDir_nameFiltersFromString(const QString& nameFilter); bool __ne__(QDir* theWrappedObject, const QDir& dir) const; bool __eq__(QDir* theWrappedObject, const QDir& dir) const; QString operator_subscript(QDir* theWrappedObject, int arg__1) const; QString path(QDir* theWrappedObject) const; void refresh(QDir* theWrappedObject) const; QString relativeFilePath(QDir* theWrappedObject, const QString& fileName) const; bool remove(QDir* theWrappedObject, const QString& fileName); bool rename(QDir* theWrappedObject, const QString& oldName, const QString& newName); bool rmdir(QDir* theWrappedObject, const QString& dirName) const; bool rmpath(QDir* theWrappedObject, const QString& dirPath) const; QDir static_QDir_root(); QString static_QDir_rootPath(); QStringList static_QDir_searchPaths(const QString& prefix); QChar static_QDir_separator(); bool static_QDir_setCurrent(const QString& path); void setFilter(QDir* theWrappedObject, QDir::Filters filter); void setNameFilters(QDir* theWrappedObject, const QStringList& nameFilters); void setPath(QDir* theWrappedObject, const QString& path); void static_QDir_setSearchPaths(const QString& prefix, const QStringList& searchPaths); void setSorting(QDir* theWrappedObject, QDir::SortFlags sort); QDir::SortFlags sorting(QDir* theWrappedObject) const; QDir static_QDir_temp(); QString static_QDir_tempPath(); QString static_QDir_toNativeSeparators(const QString& pathName); QString py_toString(QDir*); }; class PythonQtShell_QDirIterator : public QDirIterator { public: PythonQtShell_QDirIterator(const QDir& dir, QDirIterator::IteratorFlags flags = QDirIterator::NoIteratorFlags):QDirIterator(dir, flags),_wrapper(NULL) {}; PythonQtShell_QDirIterator(const QString& path, QDir::Filters filter, QDirIterator::IteratorFlags flags = QDirIterator::NoIteratorFlags):QDirIterator(path, filter, flags),_wrapper(NULL) {}; PythonQtShell_QDirIterator(const QString& path, QDirIterator::IteratorFlags flags = QDirIterator::NoIteratorFlags):QDirIterator(path, flags),_wrapper(NULL) {}; PythonQtShell_QDirIterator(const QString& path, const QStringList& nameFilters, QDir::Filters filters = QDir::NoFilter, QDirIterator::IteratorFlags flags = QDirIterator::NoIteratorFlags):QDirIterator(path, nameFilters, filters, flags),_wrapper(NULL) {}; PythonQtInstanceWrapper* _wrapper; }; class PythonQtWrapper_QDirIterator : public QObject { Q_OBJECT public: Q_ENUMS(IteratorFlag ) Q_FLAGS(IteratorFlags ) enum IteratorFlag{ NoIteratorFlags = QDirIterator::NoIteratorFlags, FollowSymlinks = QDirIterator::FollowSymlinks, Subdirectories = QDirIterator::Subdirectories}; Q_DECLARE_FLAGS(IteratorFlags, IteratorFlag) public slots: QDirIterator* new_QDirIterator(const QDir& dir, QDirIterator::IteratorFlags flags = QDirIterator::NoIteratorFlags); QDirIterator* new_QDirIterator(const QString& path, QDir::Filters filter, QDirIterator::IteratorFlags flags = QDirIterator::NoIteratorFlags); QDirIterator* new_QDirIterator(const QString& path, QDirIterator::IteratorFlags flags = QDirIterator::NoIteratorFlags); QDirIterator* new_QDirIterator(const QString& path, const QStringList& nameFilters, QDir::Filters filters = QDir::NoFilter, QDirIterator::IteratorFlags flags = QDirIterator::NoIteratorFlags); void delete_QDirIterator(QDirIterator* obj) { delete obj; } QFileInfo fileInfo(QDirIterator* theWrappedObject) const; QString fileName(QDirIterator* theWrappedObject) const; QString filePath(QDirIterator* theWrappedObject) const; bool hasNext(QDirIterator* theWrappedObject) const; QString next(QDirIterator* theWrappedObject); QString path(QDirIterator* theWrappedObject) const; }; class PythonQtWrapper_QDynamicPropertyChangeEvent : public QObject { Q_OBJECT public: public slots: QDynamicPropertyChangeEvent* new_QDynamicPropertyChangeEvent(const QByteArray& name); void delete_QDynamicPropertyChangeEvent(QDynamicPropertyChangeEvent* obj) { delete obj; } QByteArray propertyName(QDynamicPropertyChangeEvent* theWrappedObject) const; }; class PythonQtWrapper_QEasingCurve : public QObject { Q_OBJECT public: Q_ENUMS(Type ) enum Type{ Linear = QEasingCurve::Linear, InQuad = QEasingCurve::InQuad, OutQuad = QEasingCurve::OutQuad, InOutQuad = QEasingCurve::InOutQuad, OutInQuad = QEasingCurve::OutInQuad, InCubic = QEasingCurve::InCubic, OutCubic = QEasingCurve::OutCubic, InOutCubic = QEasingCurve::InOutCubic, OutInCubic = QEasingCurve::OutInCubic, InQuart = QEasingCurve::InQuart, OutQuart = QEasingCurve::OutQuart, InOutQuart = QEasingCurve::InOutQuart, OutInQuart = QEasingCurve::OutInQuart, InQuint = QEasingCurve::InQuint, OutQuint = QEasingCurve::OutQuint, InOutQuint = QEasingCurve::InOutQuint, OutInQuint = QEasingCurve::OutInQuint, InSine = QEasingCurve::InSine, OutSine = QEasingCurve::OutSine, InOutSine = QEasingCurve::InOutSine, OutInSine = QEasingCurve::OutInSine, InExpo = QEasingCurve::InExpo, OutExpo = QEasingCurve::OutExpo, InOutExpo = QEasingCurve::InOutExpo, OutInExpo = QEasingCurve::OutInExpo, InCirc = QEasingCurve::InCirc, OutCirc = QEasingCurve::OutCirc, InOutCirc = QEasingCurve::InOutCirc, OutInCirc = QEasingCurve::OutInCirc, InElastic = QEasingCurve::InElastic, OutElastic = QEasingCurve::OutElastic, InOutElastic = QEasingCurve::InOutElastic, OutInElastic = QEasingCurve::OutInElastic, InBack = QEasingCurve::InBack, OutBack = QEasingCurve::OutBack, InOutBack = QEasingCurve::InOutBack, OutInBack = QEasingCurve::OutInBack, InBounce = QEasingCurve::InBounce, OutBounce = QEasingCurve::OutBounce, InOutBounce = QEasingCurve::InOutBounce, OutInBounce = QEasingCurve::OutInBounce, InCurve = QEasingCurve::InCurve, OutCurve = QEasingCurve::OutCurve, SineCurve = QEasingCurve::SineCurve, CosineCurve = QEasingCurve::CosineCurve, Custom = QEasingCurve::Custom, NCurveTypes = QEasingCurve::NCurveTypes}; public slots: QEasingCurve* new_QEasingCurve(QEasingCurve::Type type = QEasingCurve::Linear); QEasingCurve* new_QEasingCurve(const QEasingCurve& other); void delete_QEasingCurve(QEasingCurve* obj) { delete obj; } qreal amplitude(QEasingCurve* theWrappedObject) const; bool __ne__(QEasingCurve* theWrappedObject, const QEasingCurve& other) const; void writeTo(QEasingCurve* theWrappedObject, QDataStream& arg__1); QEasingCurve* operator_assign(QEasingCurve* theWrappedObject, const QEasingCurve& other); bool __eq__(QEasingCurve* theWrappedObject, const QEasingCurve& other) const; void readFrom(QEasingCurve* theWrappedObject, QDataStream& arg__1); qreal overshoot(QEasingCurve* theWrappedObject) const; qreal period(QEasingCurve* theWrappedObject) const; void setAmplitude(QEasingCurve* theWrappedObject, qreal amplitude); void setOvershoot(QEasingCurve* theWrappedObject, qreal overshoot); void setPeriod(QEasingCurve* theWrappedObject, qreal period); void setType(QEasingCurve* theWrappedObject, QEasingCurve::Type type); QEasingCurve::Type type(QEasingCurve* theWrappedObject) const; qreal valueForProgress(QEasingCurve* theWrappedObject, qreal progress) const; QString py_toString(QEasingCurve*); }; class PythonQtShell_QEvent : public QEvent { public: PythonQtShell_QEvent(QEvent::Type type):QEvent(type),_wrapper(NULL) {}; PythonQtInstanceWrapper* _wrapper; }; class PythonQtWrapper_QEvent : public QObject { Q_OBJECT public: Q_ENUMS(Type ) enum Type{ None = QEvent::None, Timer = QEvent::Timer, MouseButtonPress = QEvent::MouseButtonPress, MouseButtonRelease = QEvent::MouseButtonRelease, MouseButtonDblClick = QEvent::MouseButtonDblClick, MouseMove = QEvent::MouseMove, KeyPress = QEvent::KeyPress, KeyRelease = QEvent::KeyRelease, FocusIn = QEvent::FocusIn, FocusOut = QEvent::FocusOut, Enter = QEvent::Enter, Leave = QEvent::Leave, Paint = QEvent::Paint, Move = QEvent::Move, Resize = QEvent::Resize, Create = QEvent::Create, Destroy = QEvent::Destroy, Show = QEvent::Show, Hide = QEvent::Hide, Close = QEvent::Close, Quit = QEvent::Quit, ParentChange = QEvent::ParentChange, ParentAboutToChange = QEvent::ParentAboutToChange, ThreadChange = QEvent::ThreadChange, WindowActivate = QEvent::WindowActivate, WindowDeactivate = QEvent::WindowDeactivate, ShowToParent = QEvent::ShowToParent, HideToParent = QEvent::HideToParent, Wheel = QEvent::Wheel, WindowTitleChange = QEvent::WindowTitleChange, WindowIconChange = QEvent::WindowIconChange, ApplicationWindowIconChange = QEvent::ApplicationWindowIconChange, ApplicationFontChange = QEvent::ApplicationFontChange, ApplicationLayoutDirectionChange = QEvent::ApplicationLayoutDirectionChange, ApplicationPaletteChange = QEvent::ApplicationPaletteChange, PaletteChange = QEvent::PaletteChange, Clipboard = QEvent::Clipboard, Speech = QEvent::Speech, MetaCall = QEvent::MetaCall, SockAct = QEvent::SockAct, WinEventAct = QEvent::WinEventAct, DeferredDelete = QEvent::DeferredDelete, DragEnter = QEvent::DragEnter, DragMove = QEvent::DragMove, DragLeave = QEvent::DragLeave, Drop = QEvent::Drop, DragResponse = QEvent::DragResponse, ChildAdded = QEvent::ChildAdded, ChildPolished = QEvent::ChildPolished, ChildRemoved = QEvent::ChildRemoved, ShowWindowRequest = QEvent::ShowWindowRequest, PolishRequest = QEvent::PolishRequest, Polish = QEvent::Polish, LayoutRequest = QEvent::LayoutRequest, UpdateRequest = QEvent::UpdateRequest, UpdateLater = QEvent::UpdateLater, EmbeddingControl = QEvent::EmbeddingControl, ActivateControl = QEvent::ActivateControl, DeactivateControl = QEvent::DeactivateControl, ContextMenu = QEvent::ContextMenu, InputMethod = QEvent::InputMethod, AccessibilityPrepare = QEvent::AccessibilityPrepare, TabletMove = QEvent::TabletMove, LocaleChange = QEvent::LocaleChange, LanguageChange = QEvent::LanguageChange, LayoutDirectionChange = QEvent::LayoutDirectionChange, Style = QEvent::Style, TabletPress = QEvent::TabletPress, TabletRelease = QEvent::TabletRelease, OkRequest = QEvent::OkRequest, HelpRequest = QEvent::HelpRequest, IconDrag = QEvent::IconDrag, FontChange = QEvent::FontChange, EnabledChange = QEvent::EnabledChange, ActivationChange = QEvent::ActivationChange, StyleChange = QEvent::StyleChange, IconTextChange = QEvent::IconTextChange, ModifiedChange = QEvent::ModifiedChange, MouseTrackingChange = QEvent::MouseTrackingChange, WindowBlocked = QEvent::WindowBlocked, WindowUnblocked = QEvent::WindowUnblocked, WindowStateChange = QEvent::WindowStateChange, ToolTip = QEvent::ToolTip, WhatsThis = QEvent::WhatsThis, StatusTip = QEvent::StatusTip, ActionChanged = QEvent::ActionChanged, ActionAdded = QEvent::ActionAdded, ActionRemoved = QEvent::ActionRemoved, FileOpen = QEvent::FileOpen, Shortcut = QEvent::Shortcut, ShortcutOverride = QEvent::ShortcutOverride, WhatsThisClicked = QEvent::WhatsThisClicked, ToolBarChange = QEvent::ToolBarChange, ApplicationActivate = QEvent::ApplicationActivate, ApplicationActivated = QEvent::ApplicationActivated, ApplicationDeactivate = QEvent::ApplicationDeactivate, ApplicationDeactivated = QEvent::ApplicationDeactivated, QueryWhatsThis = QEvent::QueryWhatsThis, EnterWhatsThisMode = QEvent::EnterWhatsThisMode, LeaveWhatsThisMode = QEvent::LeaveWhatsThisMode, ZOrderChange = QEvent::ZOrderChange, HoverEnter = QEvent::HoverEnter, HoverLeave = QEvent::HoverLeave, HoverMove = QEvent::HoverMove, AccessibilityHelp = QEvent::AccessibilityHelp, AccessibilityDescription = QEvent::AccessibilityDescription, AcceptDropsChange = QEvent::AcceptDropsChange, MenubarUpdated = QEvent::MenubarUpdated, ZeroTimerEvent = QEvent::ZeroTimerEvent, GraphicsSceneMouseMove = QEvent::GraphicsSceneMouseMove, GraphicsSceneMousePress = QEvent::GraphicsSceneMousePress, GraphicsSceneMouseRelease = QEvent::GraphicsSceneMouseRelease, GraphicsSceneMouseDoubleClick = QEvent::GraphicsSceneMouseDoubleClick, GraphicsSceneContextMenu = QEvent::GraphicsSceneContextMenu, GraphicsSceneHoverEnter = QEvent::GraphicsSceneHoverEnter, GraphicsSceneHoverMove = QEvent::GraphicsSceneHoverMove, GraphicsSceneHoverLeave = QEvent::GraphicsSceneHoverLeave, GraphicsSceneHelp = QEvent::GraphicsSceneHelp, GraphicsSceneDragEnter = QEvent::GraphicsSceneDragEnter, GraphicsSceneDragMove = QEvent::GraphicsSceneDragMove, GraphicsSceneDragLeave = QEvent::GraphicsSceneDragLeave, GraphicsSceneDrop = QEvent::GraphicsSceneDrop, GraphicsSceneWheel = QEvent::GraphicsSceneWheel, KeyboardLayoutChange = QEvent::KeyboardLayoutChange, DynamicPropertyChange = QEvent::DynamicPropertyChange, TabletEnterProximity = QEvent::TabletEnterProximity, TabletLeaveProximity = QEvent::TabletLeaveProximity, NonClientAreaMouseMove = QEvent::NonClientAreaMouseMove, NonClientAreaMouseButtonPress = QEvent::NonClientAreaMouseButtonPress, NonClientAreaMouseButtonRelease = QEvent::NonClientAreaMouseButtonRelease, NonClientAreaMouseButtonDblClick = QEvent::NonClientAreaMouseButtonDblClick, MacSizeChange = QEvent::MacSizeChange, ContentsRectChange = QEvent::ContentsRectChange, MacGLWindowChange = QEvent::MacGLWindowChange, FutureCallOut = QEvent::FutureCallOut, GraphicsSceneResize = QEvent::GraphicsSceneResize, GraphicsSceneMove = QEvent::GraphicsSceneMove, CursorChange = QEvent::CursorChange, ToolTipChange = QEvent::ToolTipChange, NetworkReplyUpdated = QEvent::NetworkReplyUpdated, GrabMouse = QEvent::GrabMouse, UngrabMouse = QEvent::UngrabMouse, GrabKeyboard = QEvent::GrabKeyboard, UngrabKeyboard = QEvent::UngrabKeyboard, MacGLClearDrawable = QEvent::MacGLClearDrawable, StateMachineSignal = QEvent::StateMachineSignal, StateMachineWrapped = QEvent::StateMachineWrapped, TouchBegin = QEvent::TouchBegin, TouchUpdate = QEvent::TouchUpdate, TouchEnd = QEvent::TouchEnd, NativeGesture = QEvent::NativeGesture, RequestSoftwareInputPanel = QEvent::RequestSoftwareInputPanel, CloseSoftwareInputPanel = QEvent::CloseSoftwareInputPanel, UpdateSoftKeys = QEvent::UpdateSoftKeys, WinIdChange = QEvent::WinIdChange, Gesture = QEvent::Gesture, GestureOverride = QEvent::GestureOverride, User = QEvent::User, MaxUser = QEvent::MaxUser}; public slots: QEvent* new_QEvent(QEvent::Type type); void delete_QEvent(QEvent* obj) { delete obj; } void accept(QEvent* theWrappedObject); void ignore(QEvent* theWrappedObject); bool isAccepted(QEvent* theWrappedObject) const; int static_QEvent_registerEventType(int hint = -1); void setAccepted(QEvent* theWrappedObject, bool accepted); bool spontaneous(QEvent* theWrappedObject) const; QEvent::Type type(QEvent* theWrappedObject) const; QString py_toString(QEvent*); }; class PythonQtShell_QEventLoop : public QEventLoop { public: PythonQtShell_QEventLoop(QObject* parent = 0):QEventLoop(parent),_wrapper(NULL) {}; virtual void childEvent(QChildEvent* arg__1); virtual void customEvent(QEvent* arg__1); virtual bool event(QEvent* arg__1); virtual bool eventFilter(QObject* arg__1, QEvent* arg__2); virtual void timerEvent(QTimerEvent* arg__1); PythonQtInstanceWrapper* _wrapper; }; class PythonQtWrapper_QEventLoop : public QObject { Q_OBJECT public: Q_ENUMS(ProcessEventsFlag ) Q_FLAGS(ProcessEventsFlags ) enum ProcessEventsFlag{ AllEvents = QEventLoop::AllEvents, ExcludeUserInputEvents = QEventLoop::ExcludeUserInputEvents, ExcludeSocketNotifiers = QEventLoop::ExcludeSocketNotifiers, WaitForMoreEvents = QEventLoop::WaitForMoreEvents, X11ExcludeTimers = QEventLoop::X11ExcludeTimers, DeferredDeletion = QEventLoop::DeferredDeletion, EventLoopExec = QEventLoop::EventLoopExec, DialogExec = QEventLoop::DialogExec}; Q_DECLARE_FLAGS(ProcessEventsFlags, ProcessEventsFlag) public slots: QEventLoop* new_QEventLoop(QObject* parent = 0); void delete_QEventLoop(QEventLoop* obj) { delete obj; } int exec(QEventLoop* theWrappedObject, QEventLoop::ProcessEventsFlags flags = QEventLoop::AllEvents); void exit(QEventLoop* theWrappedObject, int returnCode = 0); bool isRunning(QEventLoop* theWrappedObject) const; bool processEvents(QEventLoop* theWrappedObject, QEventLoop::ProcessEventsFlags flags = QEventLoop::AllEvents); void processEvents(QEventLoop* theWrappedObject, QEventLoop::ProcessEventsFlags flags, int maximumTime); void wakeUp(QEventLoop* theWrappedObject); }; class PythonQtShell_QEventTransition : public QEventTransition { public: PythonQtShell_QEventTransition(QObject* object, QEvent::Type type, QState* sourceState = 0):QEventTransition(object, type, sourceState),_wrapper(NULL) {}; PythonQtShell_QEventTransition(QState* sourceState = 0):QEventTransition(sourceState),_wrapper(NULL) {}; virtual void childEvent(QChildEvent* arg__1); virtual void customEvent(QEvent* arg__1); virtual bool event(QEvent* e); virtual bool eventFilter(QObject* arg__1, QEvent* arg__2); virtual bool eventTest(QEvent* event); virtual void onTransition(QEvent* event); virtual void timerEvent(QTimerEvent* arg__1); PythonQtInstanceWrapper* _wrapper; }; class PythonQtPublicPromoter_QEventTransition : public QEventTransition { public: inline bool promoted_event(QEvent* e) { return QEventTransition::event(e); } inline bool promoted_eventTest(QEvent* event) { return QEventTransition::eventTest(event); } inline void promoted_onTransition(QEvent* event) { QEventTransition::onTransition(event); } }; class PythonQtWrapper_QEventTransition : public QObject { Q_OBJECT public: public slots: QEventTransition* new_QEventTransition(QObject* object, QEvent::Type type, QState* sourceState = 0); QEventTransition* new_QEventTransition(QState* sourceState = 0); void delete_QEventTransition(QEventTransition* obj) { delete obj; } bool event(QEventTransition* theWrappedObject, QEvent* e); QObject* eventSource(QEventTransition* theWrappedObject) const; bool eventTest(QEventTransition* theWrappedObject, QEvent* event); QEvent::Type eventType(QEventTransition* theWrappedObject) const; void onTransition(QEventTransition* theWrappedObject, QEvent* event); void setEventSource(QEventTransition* theWrappedObject, QObject* object); void setEventType(QEventTransition* theWrappedObject, QEvent::Type type); }; class PythonQtShell_QFactoryInterface : public QFactoryInterface { public: PythonQtShell_QFactoryInterface():QFactoryInterface(),_wrapper(NULL) {}; virtual QStringList keys() const; PythonQtInstanceWrapper* _wrapper; }; class PythonQtWrapper_QFactoryInterface : public QObject { Q_OBJECT public: public slots: QFactoryInterface* new_QFactoryInterface(); void delete_QFactoryInterface(QFactoryInterface* obj) { delete obj; } }; class PythonQtShell_QFile : public QFile { public: PythonQtShell_QFile():QFile(),_wrapper(NULL) {}; PythonQtShell_QFile(QObject* parent):QFile(parent),_wrapper(NULL) {}; PythonQtShell_QFile(const QString& name):QFile(name),_wrapper(NULL) {}; PythonQtShell_QFile(const QString& name, QObject* parent):QFile(name, parent),_wrapper(NULL) {}; virtual bool atEnd() const; virtual qint64 bytesAvailable() const; virtual qint64 bytesToWrite() const; virtual bool canReadLine() const; virtual void childEvent(QChildEvent* arg__1); virtual void close(); virtual void customEvent(QEvent* arg__1); virtual bool event(QEvent* arg__1); virtual bool eventFilter(QObject* arg__1, QEvent* arg__2); virtual QAbstractFileEngine* fileEngine() const; virtual bool isSequential() const; virtual bool open(QIODevice::OpenMode flags); virtual qint64 pos() const; virtual qint64 readData(char* data, qint64 maxlen); virtual qint64 readLineData(char* data, qint64 maxlen); virtual bool reset(); virtual bool seek(qint64 offset); virtual qint64 size() const; virtual void timerEvent(QTimerEvent* arg__1); virtual bool waitForBytesWritten(int msecs); virtual bool waitForReadyRead(int msecs); virtual qint64 writeData(const char* data, qint64 len); PythonQtInstanceWrapper* _wrapper; }; class PythonQtPublicPromoter_QFile : public QFile { public: inline bool promoted_atEnd() const { return QFile::atEnd(); } inline void promoted_close() { QFile::close(); } inline QAbstractFileEngine* promoted_fileEngine() const { return QFile::fileEngine(); } inline bool promoted_isSequential() const { return QFile::isSequential(); } inline bool promoted_open(QIODevice::OpenMode flags) { return QFile::open(flags); } inline qint64 promoted_pos() const { return QFile::pos(); } inline qint64 promoted_readData(char* data, qint64 maxlen) { return QFile::readData(data, maxlen); } inline qint64 promoted_readLineData(char* data, qint64 maxlen) { return QFile::readLineData(data, maxlen); } inline bool promoted_seek(qint64 offset) { return QFile::seek(offset); } inline qint64 promoted_size() const { return QFile::size(); } inline qint64 promoted_writeData(const char* data, qint64 len) { return QFile::writeData(data, len); } }; class PythonQtWrapper_QFile : public QObject { Q_OBJECT public: Q_ENUMS(FileError MemoryMapFlags Permission ) Q_FLAGS(Permissions ) enum FileError{ NoError = QFile::NoError, ReadError = QFile::ReadError, WriteError = QFile::WriteError, FatalError = QFile::FatalError, ResourceError = QFile::ResourceError, OpenError = QFile::OpenError, AbortError = QFile::AbortError, TimeOutError = QFile::TimeOutError, UnspecifiedError = QFile::UnspecifiedError, RemoveError = QFile::RemoveError, RenameError = QFile::RenameError, PositionError = QFile::PositionError, ResizeError = QFile::ResizeError, PermissionsError = QFile::PermissionsError, CopyError = QFile::CopyError}; enum MemoryMapFlags{ NoOptions = QFile::NoOptions}; enum Permission{ ReadOwner = QFile::ReadOwner, WriteOwner = QFile::WriteOwner, ExeOwner = QFile::ExeOwner, ReadUser = QFile::ReadUser, WriteUser = QFile::WriteUser, ExeUser = QFile::ExeUser, ReadGroup = QFile::ReadGroup, WriteGroup = QFile::WriteGroup, ExeGroup = QFile::ExeGroup, ReadOther = QFile::ReadOther, WriteOther = QFile::WriteOther, ExeOther = QFile::ExeOther}; Q_DECLARE_FLAGS(Permissions, Permission) public slots: QFile* new_QFile(); QFile* new_QFile(QObject* parent); QFile* new_QFile(const QString& name); QFile* new_QFile(const QString& name, QObject* parent); void delete_QFile(QFile* obj) { delete obj; } bool atEnd(QFile* theWrappedObject) const; void close(QFile* theWrappedObject); bool static_QFile_copy(const QString& fileName, const QString& newName); bool copy(QFile* theWrappedObject, const QString& newName); QString static_QFile_decodeName(const QByteArray& localFileName); QByteArray static_QFile_encodeName(const QString& fileName); QFile::FileError error(QFile* theWrappedObject) const; bool exists(QFile* theWrappedObject) const; bool static_QFile_exists(const QString& fileName); QAbstractFileEngine* fileEngine(QFile* theWrappedObject) const; QString fileName(QFile* theWrappedObject) const; bool flush(QFile* theWrappedObject); int handle(QFile* theWrappedObject) const; bool isSequential(QFile* theWrappedObject) const; bool link(QFile* theWrappedObject, const QString& newName); bool static_QFile_link(const QString& oldname, const QString& newName); bool open(QFile* theWrappedObject, QIODevice::OpenMode flags); QFile::Permissions permissions(QFile* theWrappedObject) const; QFile::Permissions static_QFile_permissions(const QString& filename); qint64 pos(QFile* theWrappedObject) const; qint64 readData(QFile* theWrappedObject, char* data, qint64 maxlen); qint64 readLineData(QFile* theWrappedObject, char* data, qint64 maxlen); bool remove(QFile* theWrappedObject); bool static_QFile_remove(const QString& fileName); bool rename(QFile* theWrappedObject, const QString& newName); bool static_QFile_rename(const QString& oldName, const QString& newName); bool static_QFile_resize(const QString& filename, qint64 sz); bool resize(QFile* theWrappedObject, qint64 sz); bool seek(QFile* theWrappedObject, qint64 offset); void setFileName(QFile* theWrappedObject, const QString& name); bool setPermissions(QFile* theWrappedObject, QFile::Permissions permissionSpec); bool static_QFile_setPermissions(const QString& filename, QFile::Permissions permissionSpec); qint64 size(QFile* theWrappedObject) const; QString symLinkTarget(QFile* theWrappedObject) const; QString static_QFile_symLinkTarget(const QString& fileName); void unsetError(QFile* theWrappedObject); qint64 writeData(QFile* theWrappedObject, const char* data, qint64 len); }; class PythonQtWrapper_QFileInfo : public QObject { Q_OBJECT public: public slots: QFileInfo* new_QFileInfo(); QFileInfo* new_QFileInfo(const QDir& dir, const QString& file); QFileInfo* new_QFileInfo(const QFile& file); QFileInfo* new_QFileInfo(const QFileInfo& fileinfo); QFileInfo* new_QFileInfo(const QString& file); void delete_QFileInfo(QFileInfo* obj) { delete obj; } QDir absoluteDir(QFileInfo* theWrappedObject) const; QString absoluteFilePath(QFileInfo* theWrappedObject) const; QString absolutePath(QFileInfo* theWrappedObject) const; QString baseName(QFileInfo* theWrappedObject) const; QString bundleName(QFileInfo* theWrappedObject) const; bool caching(QFileInfo* theWrappedObject) const; QString canonicalFilePath(QFileInfo* theWrappedObject) const; QString canonicalPath(QFileInfo* theWrappedObject) const; QString completeBaseName(QFileInfo* theWrappedObject) const; QString completeSuffix(QFileInfo* theWrappedObject) const; QDateTime created(QFileInfo* theWrappedObject) const; QDir dir(QFileInfo* theWrappedObject) const; bool exists(QFileInfo* theWrappedObject) const; QString fileName(QFileInfo* theWrappedObject) const; QString filePath(QFileInfo* theWrappedObject) const; QString group(QFileInfo* theWrappedObject) const; uint groupId(QFileInfo* theWrappedObject) const; bool isAbsolute(QFileInfo* theWrappedObject) const; bool isBundle(QFileInfo* theWrappedObject) const; bool isDir(QFileInfo* theWrappedObject) const; bool isExecutable(QFileInfo* theWrappedObject) const; bool isFile(QFileInfo* theWrappedObject) const; bool isHidden(QFileInfo* theWrappedObject) const; bool isReadable(QFileInfo* theWrappedObject) const; bool isRelative(QFileInfo* theWrappedObject) const; bool isRoot(QFileInfo* theWrappedObject) const; bool isSymLink(QFileInfo* theWrappedObject) const; bool isWritable(QFileInfo* theWrappedObject) const; QDateTime lastModified(QFileInfo* theWrappedObject) const; QDateTime lastRead(QFileInfo* theWrappedObject) const; bool makeAbsolute(QFileInfo* theWrappedObject); bool __ne__(QFileInfo* theWrappedObject, const QFileInfo& fileinfo); bool __eq__(QFileInfo* theWrappedObject, const QFileInfo& fileinfo); QString owner(QFileInfo* theWrappedObject) const; uint ownerId(QFileInfo* theWrappedObject) const; QString path(QFileInfo* theWrappedObject) const; bool permission(QFileInfo* theWrappedObject, QFile::Permissions permissions) const; QFile::Permissions permissions(QFileInfo* theWrappedObject) const; void refresh(QFileInfo* theWrappedObject); void setCaching(QFileInfo* theWrappedObject, bool on); void setFile(QFileInfo* theWrappedObject, const QDir& dir, const QString& file); void setFile(QFileInfo* theWrappedObject, const QFile& file); void setFile(QFileInfo* theWrappedObject, const QString& file); qint64 size(QFileInfo* theWrappedObject) const; QString suffix(QFileInfo* theWrappedObject) const; QString symLinkTarget(QFileInfo* theWrappedObject) const; }; class PythonQtShell_QFileSystemWatcher : public QFileSystemWatcher { public: PythonQtShell_QFileSystemWatcher(QObject* parent = 0):QFileSystemWatcher(parent),_wrapper(NULL) {}; PythonQtShell_QFileSystemWatcher(const QStringList& paths, QObject* parent = 0):QFileSystemWatcher(paths, parent),_wrapper(NULL) {}; virtual void childEvent(QChildEvent* arg__1); virtual void customEvent(QEvent* arg__1); virtual bool event(QEvent* arg__1); virtual bool eventFilter(QObject* arg__1, QEvent* arg__2); virtual void timerEvent(QTimerEvent* arg__1); PythonQtInstanceWrapper* _wrapper; }; class PythonQtWrapper_QFileSystemWatcher : public QObject { Q_OBJECT public: public slots: QFileSystemWatcher* new_QFileSystemWatcher(QObject* parent = 0); QFileSystemWatcher* new_QFileSystemWatcher(const QStringList& paths, QObject* parent = 0); void delete_QFileSystemWatcher(QFileSystemWatcher* obj) { delete obj; } void addPath(QFileSystemWatcher* theWrappedObject, const QString& file); void addPaths(QFileSystemWatcher* theWrappedObject, const QStringList& files); QStringList directories(QFileSystemWatcher* theWrappedObject) const; QStringList files(QFileSystemWatcher* theWrappedObject) const; void removePath(QFileSystemWatcher* theWrappedObject, const QString& file); void removePaths(QFileSystemWatcher* theWrappedObject, const QStringList& files); }; class PythonQtShell_QFinalState : public QFinalState { public: PythonQtShell_QFinalState(QState* parent = 0):QFinalState(parent),_wrapper(NULL) {}; virtual void childEvent(QChildEvent* arg__1); virtual void customEvent(QEvent* arg__1); virtual bool event(QEvent* e); virtual bool eventFilter(QObject* arg__1, QEvent* arg__2); virtual void onEntry(QEvent* event); virtual void onExit(QEvent* event); virtual void timerEvent(QTimerEvent* arg__1); PythonQtInstanceWrapper* _wrapper; }; class PythonQtPublicPromoter_QFinalState : public QFinalState { public: inline bool promoted_event(QEvent* e) { return QFinalState::event(e); } inline void promoted_onEntry(QEvent* event) { QFinalState::onEntry(event); } inline void promoted_onExit(QEvent* event) { QFinalState::onExit(event); } }; class PythonQtWrapper_QFinalState : public QObject { Q_OBJECT public: public slots: QFinalState* new_QFinalState(QState* parent = 0); void delete_QFinalState(QFinalState* obj) { delete obj; } bool event(QFinalState* theWrappedObject, QEvent* e); void onEntry(QFinalState* theWrappedObject, QEvent* event); void onExit(QFinalState* theWrappedObject, QEvent* event); }; class PythonQtShell_QHistoryState : public QHistoryState { public: PythonQtShell_QHistoryState(QHistoryState::HistoryType type, QState* parent = 0):QHistoryState(type, parent),_wrapper(NULL) {}; PythonQtShell_QHistoryState(QState* parent = 0):QHistoryState(parent),_wrapper(NULL) {}; virtual void childEvent(QChildEvent* arg__1); virtual void customEvent(QEvent* arg__1); virtual bool event(QEvent* e); virtual bool eventFilter(QObject* arg__1, QEvent* arg__2); virtual void onEntry(QEvent* event); virtual void onExit(QEvent* event); virtual void timerEvent(QTimerEvent* arg__1); PythonQtInstanceWrapper* _wrapper; }; class PythonQtPublicPromoter_QHistoryState : public QHistoryState { public: inline bool promoted_event(QEvent* e) { return QHistoryState::event(e); } inline void promoted_onEntry(QEvent* event) { QHistoryState::onEntry(event); } inline void promoted_onExit(QEvent* event) { QHistoryState::onExit(event); } }; class PythonQtWrapper_QHistoryState : public QObject { Q_OBJECT public: public slots: QHistoryState* new_QHistoryState(QHistoryState::HistoryType type, QState* parent = 0); QHistoryState* new_QHistoryState(QState* parent = 0); void delete_QHistoryState(QHistoryState* obj) { delete obj; } QAbstractState* defaultState(QHistoryState* theWrappedObject) const; bool event(QHistoryState* theWrappedObject, QEvent* e); QHistoryState::HistoryType historyType(QHistoryState* theWrappedObject) const; void onEntry(QHistoryState* theWrappedObject, QEvent* event); void onExit(QHistoryState* theWrappedObject, QEvent* event); void setDefaultState(QHistoryState* theWrappedObject, QAbstractState* state); void setHistoryType(QHistoryState* theWrappedObject, QHistoryState::HistoryType type); }; class PythonQtShell_QIODevice : public QIODevice { public: PythonQtShell_QIODevice():QIODevice(),_wrapper(NULL) {}; PythonQtShell_QIODevice(QObject* parent):QIODevice(parent),_wrapper(NULL) {}; virtual bool atEnd() const; virtual qint64 bytesAvailable() const; virtual qint64 bytesToWrite() const; virtual bool canReadLine() const; virtual void childEvent(QChildEvent* arg__1); virtual void close(); virtual void customEvent(QEvent* arg__1); virtual bool event(QEvent* arg__1); virtual bool eventFilter(QObject* arg__1, QEvent* arg__2); virtual bool isSequential() const; virtual bool open(QIODevice::OpenMode mode); virtual qint64 pos() const; virtual qint64 readData(char* data, qint64 maxlen); virtual qint64 readLineData(char* data, qint64 maxlen); virtual bool reset(); virtual bool seek(qint64 pos); virtual qint64 size() const; virtual void timerEvent(QTimerEvent* arg__1); virtual bool waitForBytesWritten(int msecs); virtual bool waitForReadyRead(int msecs); virtual qint64 writeData(const char* data, qint64 len); PythonQtInstanceWrapper* _wrapper; }; class PythonQtPublicPromoter_QIODevice : public QIODevice { public: inline bool promoted_atEnd() const { return QIODevice::atEnd(); } inline qint64 promoted_bytesAvailable() const { return QIODevice::bytesAvailable(); } inline qint64 promoted_bytesToWrite() const { return QIODevice::bytesToWrite(); } inline bool promoted_canReadLine() const { return QIODevice::canReadLine(); } inline void promoted_close() { QIODevice::close(); } inline bool promoted_isSequential() const { return QIODevice::isSequential(); } inline bool promoted_open(QIODevice::OpenMode mode) { return QIODevice::open(mode); } inline qint64 promoted_pos() const { return QIODevice::pos(); } inline qint64 promoted_readLineData(char* data, qint64 maxlen) { return QIODevice::readLineData(data, maxlen); } inline bool promoted_reset() { return QIODevice::reset(); } inline bool promoted_seek(qint64 pos) { return QIODevice::seek(pos); } inline qint64 promoted_size() const { return QIODevice::size(); } inline bool promoted_waitForBytesWritten(int msecs) { return QIODevice::waitForBytesWritten(msecs); } inline bool promoted_waitForReadyRead(int msecs) { return QIODevice::waitForReadyRead(msecs); } }; class PythonQtWrapper_QIODevice : public QObject { Q_OBJECT public: Q_ENUMS(OpenModeFlag ) Q_FLAGS(OpenMode ) enum OpenModeFlag{ NotOpen = QIODevice::NotOpen, ReadOnly = QIODevice::ReadOnly, WriteOnly = QIODevice::WriteOnly, ReadWrite = QIODevice::ReadWrite, Append = QIODevice::Append, Truncate = QIODevice::Truncate, Text = QIODevice::Text, Unbuffered = QIODevice::Unbuffered}; Q_DECLARE_FLAGS(OpenMode, OpenModeFlag) public slots: QIODevice* new_QIODevice(); QIODevice* new_QIODevice(QObject* parent); void delete_QIODevice(QIODevice* obj) { delete obj; } bool atEnd(QIODevice* theWrappedObject) const; qint64 bytesAvailable(QIODevice* theWrappedObject) const; qint64 bytesToWrite(QIODevice* theWrappedObject) const; bool canReadLine(QIODevice* theWrappedObject) const; void close(QIODevice* theWrappedObject); QString errorString(QIODevice* theWrappedObject) const; bool getChar(QIODevice* theWrappedObject, char* c); bool isOpen(QIODevice* theWrappedObject) const; bool isReadable(QIODevice* theWrappedObject) const; bool isSequential(QIODevice* theWrappedObject) const; bool isTextModeEnabled(QIODevice* theWrappedObject) const; bool isWritable(QIODevice* theWrappedObject) const; bool open(QIODevice* theWrappedObject, QIODevice::OpenMode mode); QIODevice::OpenMode openMode(QIODevice* theWrappedObject) const; QByteArray peek(QIODevice* theWrappedObject, qint64 maxlen); qint64 pos(QIODevice* theWrappedObject) const; bool putChar(QIODevice* theWrappedObject, char c); QByteArray read(QIODevice* theWrappedObject, qint64 maxlen); QByteArray readAll(QIODevice* theWrappedObject); QByteArray readLine(QIODevice* theWrappedObject, qint64 maxlen = 0); qint64 readLineData(QIODevice* theWrappedObject, char* data, qint64 maxlen); bool reset(QIODevice* theWrappedObject); bool seek(QIODevice* theWrappedObject, qint64 pos); void setTextModeEnabled(QIODevice* theWrappedObject, bool enabled); qint64 size(QIODevice* theWrappedObject) const; void ungetChar(QIODevice* theWrappedObject, char c); bool waitForBytesWritten(QIODevice* theWrappedObject, int msecs); bool waitForReadyRead(QIODevice* theWrappedObject, int msecs); qint64 write(QIODevice* theWrappedObject, const QByteArray& data); qint64 write(QIODevice* theWrappedObject, const char* data); }; class PythonQtWrapper_QLibraryInfo : public QObject { Q_OBJECT public: Q_ENUMS(LibraryLocation ) enum LibraryLocation{ PrefixPath = QLibraryInfo::PrefixPath, DocumentationPath = QLibraryInfo::DocumentationPath, HeadersPath = QLibraryInfo::HeadersPath, LibrariesPath = QLibraryInfo::LibrariesPath, BinariesPath = QLibraryInfo::BinariesPath, PluginsPath = QLibraryInfo::PluginsPath, DataPath = QLibraryInfo::DataPath, TranslationsPath = QLibraryInfo::TranslationsPath, SettingsPath = QLibraryInfo::SettingsPath, DemosPath = QLibraryInfo::DemosPath, ExamplesPath = QLibraryInfo::ExamplesPath, ImportsPath = QLibraryInfo::ImportsPath}; public slots: void delete_QLibraryInfo(QLibraryInfo* obj) { delete obj; } QDate static_QLibraryInfo_buildDate(); QString static_QLibraryInfo_buildKey(); QString static_QLibraryInfo_licensedProducts(); QString static_QLibraryInfo_licensee(); QString static_QLibraryInfo_location(QLibraryInfo::LibraryLocation arg__1); }; class PythonQtShell_QMimeData : public QMimeData { public: PythonQtShell_QMimeData():QMimeData(),_wrapper(NULL) {}; virtual void childEvent(QChildEvent* arg__1); virtual void customEvent(QEvent* arg__1); virtual bool event(QEvent* arg__1); virtual bool eventFilter(QObject* arg__1, QEvent* arg__2); virtual QStringList formats() const; virtual bool hasFormat(const QString& mimetype) const; virtual QVariant retrieveData(const QString& mimetype, QVariant::Type preferredType) const; virtual void timerEvent(QTimerEvent* arg__1); PythonQtInstanceWrapper* _wrapper; }; class PythonQtPublicPromoter_QMimeData : public QMimeData { public: inline QStringList promoted_formats() const { return QMimeData::formats(); } inline bool promoted_hasFormat(const QString& mimetype) const { return QMimeData::hasFormat(mimetype); } inline QVariant promoted_retrieveData(const QString& mimetype, QVariant::Type preferredType) const { return QMimeData::retrieveData(mimetype, preferredType); } }; class PythonQtWrapper_QMimeData : public QObject { Q_OBJECT public: public slots: QMimeData* new_QMimeData(); void delete_QMimeData(QMimeData* obj) { delete obj; } void clear(QMimeData* theWrappedObject); QVariant colorData(QMimeData* theWrappedObject) const; QByteArray data(QMimeData* theWrappedObject, const QString& mimetype) const; QStringList formats(QMimeData* theWrappedObject) const; bool hasColor(QMimeData* theWrappedObject) const; bool hasFormat(QMimeData* theWrappedObject, const QString& mimetype) const; bool hasHtml(QMimeData* theWrappedObject) const; bool hasImage(QMimeData* theWrappedObject) const; bool hasText(QMimeData* theWrappedObject) const; bool hasUrls(QMimeData* theWrappedObject) const; QString html(QMimeData* theWrappedObject) const; QVariant imageData(QMimeData* theWrappedObject) const; void removeFormat(QMimeData* theWrappedObject, const QString& mimetype); QVariant retrieveData(QMimeData* theWrappedObject, const QString& mimetype, QVariant::Type preferredType) const; void setColorData(QMimeData* theWrappedObject, const QVariant& color); void setData(QMimeData* theWrappedObject, const QString& mimetype, const QByteArray& data); void setHtml(QMimeData* theWrappedObject, const QString& html); void setImageData(QMimeData* theWrappedObject, const QVariant& image); void setText(QMimeData* theWrappedObject, const QString& text); void setUrls(QMimeData* theWrappedObject, const QList<QUrl >& urls); QString text(QMimeData* theWrappedObject) const; QList<QUrl > urls(QMimeData* theWrappedObject) const; }; class PythonQtWrapper_QModelIndex : public QObject { Q_OBJECT public: public slots: QModelIndex* new_QModelIndex(); QModelIndex* new_QModelIndex(const QModelIndex& other); void delete_QModelIndex(QModelIndex* obj) { delete obj; } QModelIndex child(QModelIndex* theWrappedObject, int row, int column) const; int column(QModelIndex* theWrappedObject) const; QVariant data(QModelIndex* theWrappedObject, int role = Qt::DisplayRole) const; Qt::ItemFlags flags(QModelIndex* theWrappedObject) const; qint64 internalId(QModelIndex* theWrappedObject) const; void* internalPointer(QModelIndex* theWrappedObject) const; bool isValid(QModelIndex* theWrappedObject) const; const QAbstractItemModel* model(QModelIndex* theWrappedObject) const; bool __ne__(QModelIndex* theWrappedObject, const QModelIndex& other) const; bool __lt__(QModelIndex* theWrappedObject, const QModelIndex& other) const; bool __eq__(QModelIndex* theWrappedObject, const QModelIndex& other) const; QModelIndex parent(QModelIndex* theWrappedObject) const; int row(QModelIndex* theWrappedObject) const; QModelIndex sibling(QModelIndex* theWrappedObject, int row, int column) const; QString py_toString(QModelIndex*); };
2629b784c8af460d08cc71729e0a1b1eaef8cf41
546d00dd96099d7ad669373f5771b9b200938f6e
/Sources/Sword3PaySys/S3RELAYSERVER/S3PDBSocketServer.h
42080d8c02fb7c1971498f575cac0ed541812d72
[]
no_license
lubing521/mmo-resourse
74f6bcbd78aba61de0e8a681c4c6850f564e08d8
94fc594acba9bba9a9c3d0a5ecbca7a6363b42a5
refs/heads/master
2021-01-22T01:43:29.825927
2015-03-17T02:24:16
2015-03-17T02:24:16
36,480,084
2
1
null
2015-05-29T03:16:18
2015-05-29T03:16:18
null
UTF-8
C++
false
false
1,431
h
//-----------------------------------------// // // // File : S3PDBSocketServer.h // // Author : Yang Xiaodong // // Modified : 8/26/2002 // // // //-----------------------------------------// #ifndef _S3PDBSOCKETSERVER_H_ #define _S3PDBSOCKETSERVER_H_ #include "KStdAfx.h" #include "S3PDBSocketPool.h" typedef struct tag_DBSOCKETSERVERPARAM { SOCKET serverSocket; int* piRunSignal; S3PDBSocketPool* pSocketPool; }_DBSOCKETSERVERPARAM, *_LPDBSOCKETSERVERPARAM; class S3PDBSocketServer { public: static SOCKET CreateSocket( int iPort ); static BOOL SendUDP( SOCKET s, DWORD dwTargetIP, int iTargetPort, IBYTE buf[def_UDPSIZE], DWORD dwSize ); public: S3PDBSocketServer( SOCKET s, S3PDBSocketPool* pPool = NULL ); S3PDBSocketServer( int iPort, S3PDBSocketPool* pPool = NULL ); virtual ~S3PDBSocketServer(); virtual HANDLE Start(); virtual BOOL Stop(); protected: static DWORD WINAPI StartServer( LPVOID lpParam ); virtual void CreateEnablePoolEvent(); virtual BOOL ReleaseSocket(); virtual BOOL CreateSocket(); int* m_piRunSignal; int m_iPort; SOCKET m_Socket; HANDLE m_hServer; DWORD m_dwServerThreadId; S3PDBSocketPool* m_pSocketPool; _DBSOCKETSERVERPARAM m_ServerParam; HANDLE m_hEnablePool; }; #endif // _S3PDBSOCKETSERVER_H_
[ "[email protected]@6f215214-8c51-1d4b-a490-e1557286002c" ]
[email protected]@6f215214-8c51-1d4b-a490-e1557286002c
8e528916cb8845448fc7ca1c3e31bde02cd1eb28
065e58016a4506e4a5b429a2b77a6f432930a362
/include/shinobu/frontend/opengl/TextureArray.hpp
7c9c9a68a23137b999ef2f25cf488df2a707f819
[]
no_license
UnsafePointer/shinobu
380ba84b1dfe122da3f6042da2261bcec5f07abe
5088e95c3dcd7b0f3e9b226dc768811a6b2ddc4f
refs/heads/master
2023-01-07T06:31:50.271267
2020-09-23T14:00:40
2020-09-23T14:00:40
265,358,408
3
0
null
2020-09-23T14:00:41
2020-05-19T20:28:27
C++
UTF-8
C++
false
false
627
hpp
#pragma once #include <vector> #include <tuple> #include <glad/glad.h> namespace Shinobu { namespace Frontend { namespace OpenGL { class TextureArray { std::vector<GLuint> textures; unsigned int capacity; GLsizei width; GLsizei height; public: TextureArray(unsigned int capacity, GLsizei width, GLsizei height); ~TextureArray(); GLuint getTextureAtIndex(unsigned int index); std::pair<GLsizei,GLsizei> getDimensions() const; }; }; }; };
c4fb12174bd31627e755b7c28b3249bf35363683
df515cfd75d557f6889c7feb7048cad56f51f7b8
/(TAP)/Uri/1792 Ataque/solucao.cpp
f4e9801e80a7bf8889543c71e7fcca64dc357835
[]
no_license
elsioantunes/cloud9
680d31e0ef892893823d0949112667be091f088d
c0e11d7594e1726d06b65107b6944eb191a50d51
refs/heads/master
2020-05-27T18:44:33.355231
2019-05-29T23:03:23
2019-05-29T23:03:23
188,745,952
0
0
null
null
null
null
UTF-8
C++
false
false
1,342
cpp
#include <stdio.h> #include <string.h> #include <vector> #include <queue> using namespace std; const int MAXN = 10000; int n, m, s; vector<int> adj[MAXN]; typedef struct Node { int id, friends, enemies, incoming; bool operator()(Node a, Node b) { if(a.enemies == b.enemies) { return a.friends < b.friends; } else { return a.enemies > b.enemies; } } } Node; Node node[MAXN]; int main() { priority_queue<Node, vector<Node>, Node> pq; while(scanf("%d %d %d", &n, &m, &s) != EOF and n) { for(int i=0; i<n; i++) { adj[i].clear(); node[i].incoming = 0; node[i].id = i; } for(int i=0; i<n; i++) { scanf("%d", &node[i].enemies); } for(int i=0; i<n; i++) { scanf("%d", &node[i].friends); } for(int i=0; i<m; i++) { int a, b; scanf("%d %d", &a, &b); a--; b--; adj[a].push_back(b); node[b].incoming++; } while(!pq.empty()) pq.pop(); for(int i=0; i<n; i++) if(!node[i].incoming) { pq.push(node[i]); } int count = n; while(!pq.empty()) { Node u = pq.top(); pq.pop(); if(u.enemies >= s) { break; } count--; s += u.friends; for(int i=0; i<(int)adj[u.id].size(); i++) { if(--node[ adj[u.id][i] ].incoming == 0) { pq.push(node[ adj[u.id][i] ]); } } } printf("%s\n", count ? "impossivel" : "possivel"); } }
a30465b26383d6cb03d4bcc363c0afc480960506
f7ec60de12f1b6c2ae37061b2e67362a340222e6
/Step1.Gait_Library/gen/opt/Ce3_vec4_five_link_walker.hh
b12cb2a4ed453177929d39fce79d267161f9e5a2
[]
no_license
yangcyself/TA_GaitDesign
c01d8d60ac4227add58df3ce6cad837b824c09c5
45b2afaaceec8b46dd9c8a4d52f7136f81b99f77
refs/heads/master
2020-09-20T19:41:43.542067
2020-02-15T03:26:47
2020-02-15T03:26:47
224,573,966
1
0
null
2019-11-28T05:06:52
2019-11-28T05:06:52
null
UTF-8
C++
false
false
989
hh
/* * Automatically Generated from Mathematica. * Tue 17 Sep 2019 23:17:06 GMT-04:00 */ #ifndef CE3_VEC4_FIVE_LINK_WALKER_HH #define CE3_VEC4_FIVE_LINK_WALKER_HH #ifdef MATLAB_MEX_FILE // No need for external definitions #else // MATLAB_MEX_FILE #include "math2mat.hpp" #include "mdefs.hpp" namespace Times[step, Pattern[Rabbit, Blank[]]] { void Ce3_vec4_five_link_walker_raw(double *p_output1, const double *var1,const double *var2); inline void Ce3_vec4_five_link_walker(Eigen::MatrixXd &p_output1, const Eigen::VectorXd &var1,const Eigen::VectorXd &var2) { // Check // - Inputs assert_size_matrix(var1, 7, 1); assert_size_matrix(var2, 7, 1); // - Outputs assert_size_matrix(p_output1, 7, 1); // set zero the matrix p_output1.setZero(); // Call Subroutine with raw data Ce3_vec4_five_link_walker_raw(p_output1.data(), var1.data(),var2.data()); } } #endif // MATLAB_MEX_FILE #endif // CE3_VEC4_FIVE_LINK_WALKER_HH
946a375121b9eea4a11bc6e4664961cf7a6d5362
78bc09b155f05398ef60dc142545db7ce41e0339
/C-Programming-Udemy-master/Code/Tutorial 025 - Do While Loop/Mac/C Plus Plus Tutorial/C Plus Plus Tutorial/main.cpp
cd60704bb0852e6d3de124e4e8a934afde209b1d
[ "Unlicense", "MIT" ]
permissive
PacktPublishing/C-Development-Tutorial-Series---The-Complete-Coding-Guide
4b17e4aa1eefe6474e3bc30b30f8013ed0109812
7b2d3708a052d9ebda3872603f6bef3dc6003560
refs/heads/master
2021-06-27T21:43:52.966333
2021-01-19T07:59:16
2021-01-19T07:59:16
185,386,658
1
0
null
null
null
null
UTF-8
C++
false
false
349
cpp
// // main.cpp // C Plus Plus Tutorial // // Created by Sonar Systems on 14/06/2014. // Copyright (c) 2014 Sonar Systems. All rights reserved. // #include <iostream> int main(int argc, const char * argv[]) { int i = 3; do { std::cout << i << std::endl; i++; } while (i < 5); return 0; }
82cbd268fe624d88d1c8f48fa86b9d79fb881e36
ac964eaaa7e8510fb6e051c8a19a6560c257db86
/tensorflow/compiler/mlir/tf2xla/transforms/xla_legalize_tf.cc
81f2498527a70b05665f47babcb1e1cb2f9cf9a6
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
wonjeon/tensorflow
7a4b1724146322d4581b6f59c2a1eeed5d200f6b
c223f92e906b71623f838a44ee82e5248a97e84a
refs/heads/master
2023-06-25T13:12:33.141764
2023-06-07T18:17:01
2023-06-07T18:21:58
80,862,594
0
0
null
2017-02-03T19:34:28
2017-02-03T19:34:28
null
UTF-8
C++
false
false
41,036
cc
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <algorithm> #include <cstdint> #include <map> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Debug.h" #include "llvm/Support/FormatVariadic.h" #include "mlir/Dialect/Arith/IR/Arith.h" // from @llvm-project #include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project #include "mlir/Dialect/Quant/QuantOps.h" // from @llvm-project #include "mlir/Dialect/Shape/IR/Shape.h" // from @llvm-project #include "mlir/Dialect/SparseTensor/IR/SparseTensor.h" // from @llvm-project #include "mlir/Dialect/Tensor/IR/Tensor.h" // from @llvm-project #include "mlir/IR/Attributes.h" // from @llvm-project #include "mlir/IR/BuiltinAttributeInterfaces.h" // from @llvm-project #include "mlir/IR/BuiltinAttributes.h" // from @llvm-project #include "mlir/IR/BuiltinTypeInterfaces.h" // from @llvm-project #include "mlir/IR/BuiltinTypes.h" // from @llvm-project #include "mlir/IR/MLIRContext.h" // from @llvm-project #include "mlir/IR/PatternMatch.h" // from @llvm-project #include "mlir/IR/TypeUtilities.h" // from @llvm-project #include "mlir/Pass/Pass.h" // from @llvm-project #include "mlir/Support/LLVM.h" // from @llvm-project #include "mlir/Support/LogicalResult.h" // from @llvm-project #include "mlir/Transforms/DialectConversion.h" // from @llvm-project #include "stablehlo/dialect/ChloOps.h" // from @stablehlo #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_types.h" #include "tensorflow/compiler/mlir/tensorflow/transforms/lower_tf.h" #include "tensorflow/compiler/mlir/tensorflow/utils/mangling_util.h" #include "tensorflow/compiler/mlir/tf2xla/transforms/passes.h" #include "tensorflow/compiler/mlir/tf2xla/transforms/utils.h" #include "tensorflow/compiler/mlir/tf2xla/transforms/xla_legalize_targets.h" #include "tensorflow/compiler/xla/mlir_hlo/mhlo/IR/hlo_ops.h" #include "tensorflow/compiler/xla/mlir_hlo/mhlo/transforms/rewriters.h" #include "tensorflow/compiler/xla/translate/hlo_to_mhlo/attribute_importer.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #include "tensorflow/core/framework/numeric_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/lib/monitoring/counter.h" #include "tensorflow/core/util/quantization/uniform_quant_ops_attr.pb.h" #include "tensorflow/core/util/quantization/uniform_quant_ops_params.h" namespace mlir { namespace mhlo { namespace { #define GEN_PASS_DEF_LEGALIZETF #include "tensorflow/compiler/mlir/tf2xla/transforms/xla_legalize_tf_passes.h.inc" auto *mlir_failed_legalization_count = tensorflow::monitoring::Counter<2>::New( "/tensorflow/core/tf2xla/v0/mlir_failed_xla_legalize_tf_pass_count", "Counts the failure of legalization of ops", "op_name", "legality"); class LegalizeTF : public impl::LegalizeTFBase<LegalizeTF> { public: explicit LegalizeTF(bool allow_partial_conversion, bool legalize_chlo, std::optional<StringRef> tf2xla_fallback_device_type, bool prefer_tf2xla) { legalize_chlo_ = legalize_chlo; prefer_tf2xla_ = prefer_tf2xla; use_tf2xla_fallback_ = tf2xla_fallback_device_type.has_value(); if (tf2xla_fallback_device_type.has_value()) { device_type_ = tf2xla_fallback_device_type.value().str(); } } /// Performs the lowering to XLA dialect. void runOnOperation() override; }; #define GEN_PASS_DEF_LEGALIZETFMODULEPASS #include "tensorflow/compiler/mlir/tf2xla/transforms/xla_legalize_tf_passes.h.inc" FailureOr<IntegerType> GetStorageType(Operation *op, Type original_output_element_type, PatternRewriter &rewriter) { if (original_output_element_type.isa<TF::Qint8Type>()) { return rewriter.getIntegerType(8); } else if (original_output_element_type.isa<TF::Qint32Type>()) { return rewriter.getIntegerType(32); } else { return rewriter.notifyMatchFailure( op, "Quantized type must be qint8 or qint32."); } } TensorType GetSameShapeTensorType(TensorType tensor_type, Type element_type) { if (auto ranked_tensor_ty = tensor_type.dyn_cast_or_null<RankedTensorType>()) { return RankedTensorType::get(ranked_tensor_ty.getShape(), element_type); } if (auto unranked_tensor_ty = tensor_type.dyn_cast_or_null<UnrankedTensorType>()) { return UnrankedTensorType::get(element_type); } llvm_unreachable("unhandled type"); } template <typename UniformQuantizedOp> FailureOr<TensorType> GetUniformQuantizedType( UniformQuantizedOp op, Type original_type, TypedValue<TensorType> scales_value, TypedValue<TensorType> zero_points_value, FloatType expressed_type, int64_t storage_type_min, int64_t storage_type_max, int64_t quantized_dimension, PatternRewriter &rewriter) { // Check whether the scales operand has constant op. DenseFPElementsAttr scales; if (!matchPattern(scales_value, m_Constant(&scales))) { return rewriter.notifyMatchFailure(op, "scales must be constant"); } // Check whether the zero_points operand has constant op. DenseIntElementsAttr zero_points; if (!matchPattern(zero_points_value, m_Constant(&zero_points))) { return rewriter.notifyMatchFailure(op, "zero_points must be constant"); } auto storage_type_or = GetStorageType(op, getElementTypeOrSelf(original_type), rewriter); if (failed(storage_type_or)) { return failure(); } const unsigned flags = quant::QuantizationFlags::Signed; Type elem_ty; if (quantized_dimension == -1) { elem_ty = quant::UniformQuantizedType::get( flags, *storage_type_or, expressed_type, scales.getValues<float>()[0], zero_points.getValues<int32_t>()[0], storage_type_min, storage_type_max); } else { SmallVector<double> scales_vec; SmallVector<int64_t> zero_points_vec; for (auto elem : scales.getValues<float>()) scales_vec.push_back(elem); for (auto elem : zero_points.getValues<int32_t>()) zero_points_vec.push_back(elem); elem_ty = quant::UniformQuantizedPerAxisType::get( flags, *storage_type_or, expressed_type, scales_vec, zero_points_vec, quantized_dimension, storage_type_min, storage_type_max); } return GetSameShapeTensorType(original_type.cast<TensorType>(), elem_ty); } template <typename TFQuantizedType, typename UniformQuantizedOp> FailureOr<mhlo::ConstantOp> CreateConstantOp(UniformQuantizedOp op, Value original_operand, TensorType new_operand_type, PatternRewriter &rewriter) { // Check whether the rhs operand has constant op. TF::TensorProtoAttr tensor_proto_attr; if (!matchPattern(original_operand, m_Constant(&tensor_proto_attr))) { return rewriter.notifyMatchFailure(op, "operand must be constant."); } llvm::StringRef mangled_tensor = tensor_proto_attr.getValue(); absl::string_view tensor_view(mangled_tensor.data(), mangled_tensor.size()); // TODO(hinsu): Instead of getting the weight from TensorProto, use MLIR // constant attribute to avoid depending on the Tensor proto. tensorflow::TensorProto tensor_proto; tensorflow::Status status = tensorflow::mangling_util::DemangleTensor(tensor_view, &tensor_proto); if (!status.ok()) { return rewriter.notifyMatchFailure(op, status.message()); } tensorflow::Tensor t; if (!t.FromProto(tensor_proto)) { return op.emitError("Failed to convert tensor proto to Tensor."); } auto arr = t.flat<TFQuantizedType>(); auto dense_attr = mlir::DenseElementsAttr::get( GetSameShapeTensorType( new_operand_type, rewriter.getIntegerType(8 * sizeof(TFQuantizedType))), llvm::ArrayRef(arr.data(), arr.size())); return rewriter.create<mhlo::ConstantOp>(op.getLoc(), new_operand_type, dense_attr); } xla::ConvolutionDimensionNumbers ConvertConvolutionDimensionNumbers( const tensorflow::UniformQuantizedConvolutionDimensionNumbersAttr &dnums_input) { xla::ConvolutionDimensionNumbers dnums; dnums.set_input_batch_dimension(dnums_input.input_batch_dimension()); dnums.set_input_feature_dimension(dnums_input.input_feature_dimension()); for (auto value : dnums_input.input_spatial_dimensions()) { dnums.add_input_spatial_dimensions(value); } dnums.set_kernel_input_feature_dimension( dnums_input.kernel_input_feature_dimension()); dnums.set_kernel_output_feature_dimension( dnums_input.kernel_output_feature_dimension()); for (auto value : dnums_input.kernel_spatial_dimensions()) { dnums.add_kernel_spatial_dimensions(value); } dnums.set_output_batch_dimension(dnums_input.output_batch_dimension()); dnums.set_output_feature_dimension(dnums_input.output_feature_dimension()); for (auto value : dnums_input.output_spatial_dimensions()) { dnums.add_output_spatial_dimensions(value); } return dnums; } DenseIntElementsAttr ConvertToDenseElementsAttr(ArrayAttr array_attr, PatternRewriter &rewriter) { SmallVector<int64_t> array; array.reserve(array_attr.size()); for (auto elem : array_attr.getAsRange<IntegerAttr>()) { array.push_back(elem.getInt()); } return DenseIntElementsAttr::get( RankedTensorType::get({static_cast<int64_t>(array_attr.size())}, rewriter.getIntegerType(64)), array); } template <typename UniformQuantizedConvolutionOp> FailureOr<ElementsAttr> ConvertPaddingAttr( UniformQuantizedConvolutionOp op, const xla::ConvolutionDimensionNumbers &dnums, PatternRewriter &rewriter) { StringAttr conv_padding = op.getPaddingAttr(); SmallVector<int64_t> padding_nums; ShapedType lhs_shape = op.getLhs().getType().template cast<ShapedType>(); ShapedType rhs_shape = op.getRhs().getType().template cast<ShapedType>(); // Handle only static shape cases. // TODO(b/260284866): Handle dynamic shape cases. if (!lhs_shape.hasStaticShape()) { return op.emitError("lhs must have static shape."); } if (!rhs_shape.hasStaticShape()) { return op.emitError("rhs must have static shape."); } const int64_t padding_nums_size = 2 * (rhs_shape.getRank() - 2); padding_nums.reserve(padding_nums_size); if (conv_padding.strref().equals("EXPLICIT")) { for (auto padding_elem : op.getExplicitPaddingAttr().template getAsRange<IntegerAttr>()) { padding_nums.push_back(padding_elem.getInt()); } } else if (conv_padding.strref().equals("VALID")) { padding_nums.resize(padding_nums_size, 0); } else { padding_nums.resize(padding_nums_size); for (int i = 0; i < dnums.input_spatial_dimensions_size(); ++i) { const int64_t stride = op.getWindowStridesAttr()[i].template cast<IntegerAttr>().getInt(); const int64_t lhs_size_dilated = tensorflow::UniformQuantizedConvolutionParams::DilatedSize( lhs_shape.getDimSize(dnums.input_spatial_dimensions(i)), op.getLhsDilationAttr()[i].template cast<IntegerAttr>().getInt()); const int64_t rhs_size_dilated = tensorflow::UniformQuantizedConvolutionParams::DilatedSize( rhs_shape.getDimSize(dnums.kernel_spatial_dimensions(i)), op.getRhsDilationAttr()[i].template cast<IntegerAttr>().getInt()); const int64_t output_size = (lhs_size_dilated + stride - 1) / stride; const int64_t total_padding = std::max( (output_size - 1) * stride + rhs_size_dilated - lhs_size_dilated, static_cast<int64_t>(0)); const int64_t padding_end = total_padding / 2; const int64_t padding_begin = total_padding - padding_end; padding_nums[2 * i] = padding_begin; padding_nums[2 * i + 1] = padding_end; } } ElementsAttr padding_attr = DenseIntElementsAttr::get( RankedTensorType::get({static_cast<int32_t>(padding_nums.size() / 2), 2}, rewriter.getIntegerType(64)), padding_nums); return padding_attr; } template <typename UniformQuantizedConvolutionOp> FailureOr<SmallVector<NamedAttribute>> ConvertToMhloConvolutionOpAttrs( UniformQuantizedConvolutionOp op, PatternRewriter &rewriter) { // TODO(b/261005147): Update the lowering logic after migration to mhlo // ConvolutionDimensionNumbers. tensorflow::UniformQuantizedConvolutionDimensionNumbersAttr dnums_input; if (!dnums_input.ParseFromString(std::string(op.getDimensionNumbers()))) { return op->emitError("Parse dimension_numbers failed."); } xla::ConvolutionDimensionNumbers dnums = ConvertConvolutionDimensionNumbers(dnums_input); SmallVector<NamedAttribute> converted_attrs; for (auto attr : op->getAttrs()) { if (attr.getName() == op.getFeatureGroupCountAttrName() || attr.getName() == op.getBatchGroupCountAttrName()) { converted_attrs.push_back(attr); } else if (attr.getName() == op.getDimensionNumbersAttrName()) { attr.setValue(xla::ConvertConvDimensionNumbers(dnums, &rewriter)); converted_attrs.push_back(attr); } else if (attr.getName() == op.getPaddingAttrName()) { auto value_or = ConvertPaddingAttr(op, dnums, rewriter); if (failed(value_or)) { return failure(); } attr.setValue(*value_or); converted_attrs.push_back(attr); } else if (attr.getName() == op.getWindowStridesAttrName() || attr.getName() == op.getLhsDilationAttrName() || attr.getName() == op.getRhsDilationAttrName()) { attr.setValue(ConvertToDenseElementsAttr( attr.getValue().template cast<ArrayAttr>(), rewriter)); converted_attrs.push_back(attr); } } return converted_attrs; } // TODO(hinsu): Move this pattern to legalize_tf after resolving the dependency // on the tensor proto. class ConvertUniformQuantizedDotHybridOp : public OpRewritePattern<TF::UniformQuantizedDotHybridOp> { public: using OpRewritePattern::OpRewritePattern; LogicalResult matchAndRewrite(TF::UniformQuantizedDotHybridOp op, PatternRewriter &rewriter) const override { // Uniform Quantized type for the rhs. int64_t rhs_quantized_dimension = op.getRhsQuantizationAxis(); // Currently for dot, PTQ supports per-tensor quantization. if (rhs_quantized_dimension != -1) { return rewriter.notifyMatchFailure( op, "Legalization supports only rhs_quantization_axis -1."); } auto rhs_type = GetUniformQuantizedType( op, op.getRhs().getType(), op.getRhsScales(), op.getRhsZeroPoints(), /*expressed_type=*/rewriter.getF32Type(), op.getRhsQuantizationMinVal(), op.getRhsQuantizationMaxVal(), rhs_quantized_dimension, rewriter); if (failed(rhs_type)) { return failure(); } auto rhs = CreateConstantOp<tensorflow::qint8>(op, op.getRhs(), *rhs_type, rewriter); if (failed(rhs)) { return failure(); } rewriter.replaceOpWithNewOp<mhlo::DotOp>(op, op.getType(), op.getLhs(), *rhs, /*precision_config=*/nullptr); return success(); } }; class ConvertUniformQuantizedConvolutionHybridOp : public OpRewritePattern<TF::UniformQuantizedConvolutionHybridOp> { public: using OpRewritePattern::OpRewritePattern; LogicalResult matchAndRewrite(TF::UniformQuantizedConvolutionHybridOp op, PatternRewriter &rewriter) const override { // Uniform Quantized type for the rhs. auto rhs_type = GetUniformQuantizedType( op, op.getRhs().getType(), op.getRhsScales(), op.getRhsZeroPoints(), /*expressed_type=*/rewriter.getF32Type(), op.getRhsQuantizationMinVal(), op.getRhsQuantizationMaxVal(), op.getRhsQuantizationAxis(), rewriter); if (failed(rhs_type)) { return failure(); } auto rhs = CreateConstantOp<tensorflow::qint8>(op, op.getRhs(), *rhs_type, rewriter); if (failed(rhs)) { return failure(); } auto converted_attrs_or = ConvertToMhloConvolutionOpAttrs(op, rewriter); if (failed(converted_attrs_or)) { return failure(); } SmallVector<Value, 2> operands{op.getLhs(), *rhs}; rewriter.replaceOpWithNewOp<mhlo::ConvolutionOp>(op, op.getType(), operands, *converted_attrs_or); return success(); } }; class ConvertUniformQuantizeOp : public OpRewritePattern<TF::UniformQuantizeOp> { public: using OpRewritePattern::OpRewritePattern; LogicalResult matchAndRewrite(TF::UniformQuantizeOp op, PatternRewriter &rewriter) const override { auto output_type = GetUniformQuantizedType( op, op.getOutput().getType(), op.getScales(), op.getZeroPoints(), /*expressed_type=*/rewriter.getF32Type(), op.getQuantizationMinVal(), op.getQuantizationMaxVal(), op.getQuantizationAxis(), rewriter); if (failed(output_type)) { return failure(); } rewriter.replaceOpWithNewOp<mhlo::UniformQuantizeOp>(op, *output_type, op.getInput()); return success(); } }; // UniformDequantizeOp takes TF quantized types as input which would have been // converted to the mhlo quantized types. Use OpConversionPattern in order to // retrieve the operand type *after* conversion, using OpAdaptor operand // accessor. // Same for other Uniform Quant Ops that take TF quantized types as input. class ConvertUniformDequantizeOp : public OpConversionPattern<TF::UniformDequantizeOp> { public: using OpConversionPattern::OpConversionPattern; LogicalResult matchAndRewrite( TF::UniformDequantizeOp op, TF::UniformDequantizeOpAdaptor adaptor, ConversionPatternRewriter &rewriter) const override { Value input = adaptor.getInput(); rewriter.replaceOpWithNewOp<mhlo::UniformDequantizeOp>( op, op.getOutput().getType(), input); return success(); } }; class ConvertUniformRequantizeOp : public OpConversionPattern<TF::UniformRequantizeOp> { public: using OpConversionPattern::OpConversionPattern; LogicalResult matchAndRewrite( TF::UniformRequantizeOp op, TF::UniformRequantizeOpAdaptor adaptor, ConversionPatternRewriter &rewriter) const override { Value input = adaptor.getInput(); auto output_type = GetUniformQuantizedType( op, op.getOutput().getType(), op.getOutputScales(), op.getOutputZeroPoints(), /*expressed_type=*/rewriter.getF32Type(), op.getOutputQuantizationMinVal(), op.getOutputQuantizationMaxVal(), op.getOutputQuantizationAxis(), rewriter); if (failed(output_type)) { return failure(); } rewriter.replaceOpWithNewOp<mhlo::UniformQuantizeOp>(op, *output_type, input); return success(); } }; class ConvertUniformQuantizedDotOp : public OpConversionPattern<TF::UniformQuantizedDotOp> { public: using OpConversionPattern::OpConversionPattern; LogicalResult matchAndRewrite( TF::UniformQuantizedDotOp op, TF::UniformQuantizedDotOpAdaptor adaptor, ConversionPatternRewriter &rewriter) const override { Value lhs = adaptor.getLhs(); // Uniform Quantized type for the rhs. int64_t rhs_quantized_dimension = op.getRhsQuantizationAxis(); // Currently for dot, PTQ supports per-tensor quantization. if (rhs_quantized_dimension != -1) { return rewriter.notifyMatchFailure( op, "Legalization supports only rhs_quantization_axis -1."); } auto rhs_type = GetUniformQuantizedType( op, adaptor.getRhs().getType(), op.getRhsScales(), op.getRhsZeroPoints(), /*expressed_type=*/rewriter.getF32Type(), op.getRhsQuantizationMinVal(), op.getRhsQuantizationMaxVal(), rhs_quantized_dimension, rewriter); if (failed(rhs_type)) { return failure(); } auto rhs_or = CreateConstantOp<tensorflow::qint8>(op, op.getRhs(), *rhs_type, rewriter); if (failed(rhs_or)) { return failure(); } auto output_type = GetUniformQuantizedType( op, op.getOutput().getType(), op.getOutputScales(), op.getOutputZeroPoints(), /*expressed_type=*/rewriter.getF32Type(), op.getOutputQuantizationMinVal(), op.getOutputQuantizationMaxVal(), op.getOutputQuantizationAxis(), rewriter); if (failed(output_type)) { return failure(); } rewriter.replaceOpWithNewOp<mhlo::DotOp>(op, *output_type, lhs, *rhs_or, /*precision_config=*/nullptr); return success(); } }; class ConvertUniformQuantizedConvolutionOp : public OpConversionPattern<TF::UniformQuantizedConvolutionOp> { public: using OpConversionPattern::OpConversionPattern; LogicalResult matchAndRewrite( TF::UniformQuantizedConvolutionOp op, TF::UniformQuantizedConvolutionOpAdaptor adaptor, ConversionPatternRewriter &rewriter) const override { Value lhs = adaptor.getLhs(); auto rhs_type = GetUniformQuantizedType( op, adaptor.getRhs().getType(), op.getRhsScales(), op.getRhsZeroPoints(), /*expressed_type=*/rewriter.getF32Type(), op.getRhsQuantizationMinVal(), op.getRhsQuantizationMaxVal(), op.getRhsQuantizationAxis(), rewriter); if (failed(rhs_type)) { return failure(); } auto rhs_or = CreateConstantOp<tensorflow::qint8>(op, op.getRhs(), *rhs_type, rewriter); if (failed(rhs_or)) { return failure(); } auto output_type = GetUniformQuantizedType( op, op.getOutput().getType(), op.getOutputScales(), op.getOutputZeroPoints(), /*expressed_type=*/rewriter.getF32Type(), op.getOutputQuantizationMinVal(), op.getOutputQuantizationMaxVal(), op.getOutputQuantizationAxis(), rewriter); if (failed(output_type)) { return failure(); } auto converted_attrs_or = ConvertToMhloConvolutionOpAttrs(op, rewriter); if (failed(converted_attrs_or)) { return failure(); } SmallVector<Value, 2> operands{lhs, *rhs_or}; rewriter.replaceOpWithNewOp<mhlo::ConvolutionOp>(op, *output_type, operands, *converted_attrs_or); return success(); } }; class ConvertUniformQuantizedAddOp : public OpConversionPattern<TF::UniformQuantizedAddOp> { public: using OpConversionPattern::OpConversionPattern; LogicalResult matchAndRewrite( TF::UniformQuantizedAddOp op, TF::UniformQuantizedAddOpAdaptor adaptor, ConversionPatternRewriter &rewriter) const override { Value lhs = adaptor.getLhs(); auto lhs_type = lhs.getType().cast<ShapedType>(); if (!lhs_type.hasRank()) { return rewriter.notifyMatchFailure( op, "Legalization supports cases where only lhs rank known."); } // rhs (bias) is always 1D that broadcasts to the last dim of lhs. auto broadcast_dims = GetI64ElementsAttr({lhs_type.getRank() - 1}, &rewriter); auto rhs_type = GetUniformQuantizedType( op, adaptor.getRhs().getType(), op.getRhsScales(), op.getRhsZeroPoints(), /*expressed_type=*/rewriter.getF32Type(), op.getRhsQuantizationMinVal(), op.getRhsQuantizationMaxVal(), op.getRhsQuantizationAxis(), rewriter); if (failed(rhs_type)) { return failure(); } auto rhs_or = CreateConstantOp<tensorflow::qint32>(op, op.getRhs(), *rhs_type, rewriter); if (failed(rhs_or)) { return failure(); } auto output_type = GetUniformQuantizedType( op, op.getOutput().getType(), op.getOutputScales(), op.getOutputZeroPoints(), /*expressed_type=*/rewriter.getF32Type(), op.getOutputQuantizationMinVal(), op.getOutputQuantizationMaxVal(), op.getOutputQuantizationAxis(), rewriter); if (failed(output_type)) { return failure(); } // lhs, rhs, output scales and zero_points are guaranteed (by the TF // quantizer) to be identical, respectively. rewriter.replaceOpWithNewOp<chlo::BroadcastAddOp>(op, *output_type, lhs, *rhs_or, broadcast_dims); return success(); } }; class ConvertUniformQuantizedClipByValueOp : public OpConversionPattern<TF::UniformQuantizedClipByValueOp> { public: using OpConversionPattern::OpConversionPattern; LogicalResult matchAndRewrite( TF::UniformQuantizedClipByValueOp op, TF::UniformQuantizedClipByValueOpAdaptor adaptor, ConversionPatternRewriter &rewriter) const override { Value operand = adaptor.getOperand(); const int64_t quantization_axis = op.getQuantizationAxis(); llvm::SmallVector<int64_t> broadcast_dims_values = {}; if (quantization_axis >= 0) { broadcast_dims_values.push_back(quantization_axis); } auto broadcast_dims = GetI64ElementsAttr(broadcast_dims_values, &rewriter); auto min_max_type = GetUniformQuantizedType( op, adaptor.getMin().getType(), op.getScales(), op.getZeroPoints(), /*expressed_type=*/rewriter.getF32Type(), op.getQuantizationMinVal(), op.getQuantizationMaxVal(), op.getQuantizationAxis(), rewriter); if (failed(min_max_type)) { return failure(); } auto min_or = CreateConstantOp<tensorflow::qint32>(op, op.getMin(), *min_max_type, rewriter); if (failed(min_or)) { return failure(); } auto max_or = CreateConstantOp<tensorflow::qint32>(op, op.getMax(), *min_max_type, rewriter); if (failed(max_or)) { return failure(); } auto output_type = GetUniformQuantizedType( op, op.getOutput().getType(), op.getScales(), op.getZeroPoints(), /*expressed_type=*/rewriter.getF32Type(), op.getQuantizationMinVal(), op.getQuantizationMaxVal(), op.getQuantizationAxis(), rewriter); if (failed(output_type)) { return failure(); } Value res_min_clipped = rewriter.create<chlo::BroadcastMaxOp>( op->getLoc(), *output_type, operand, *min_or, broadcast_dims); rewriter.replaceOpWithNewOp<chlo::BroadcastMinOp>( op, *output_type, res_min_clipped, *max_or, broadcast_dims); return success(); } }; // Emits debug information which includes the number of ops of each type which // failed to legalize. void EmitLegalizationErrors(Operation *op, const DenseSet<Operation *> &nonlegalized_ops) { // Track the legalization failures by mapping op name to information about // that failure: the number of unlegalized occurrences of the op, and one // example operation that failed. std::map<StringRef, std::pair<int, Operation *>> op_name_to_error_info; DenseSet<Operation *> error_ops; for (Operation *nonlegalized_op : nonlegalized_ops) { // Increment count of this legalization failure. StringRef op_name = nonlegalized_op->getName().getStringRef(); // If this emplace is successful, it's the first time we've encountered // this op type. Initialize count to 0 so that after increment, it is 1. auto insertion_result = op_name_to_error_info.emplace( op_name, std::make_pair(0, nonlegalized_op)); ++insertion_result.first->second.first; } std::vector<std::string> error_messages; error_messages.reserve(op_name_to_error_info.size()); for (const auto &op_info : op_name_to_error_info) { error_messages.push_back( llvm::formatv("{0} (count: {1})", op_info.first, op_info.second.first)); } Location loc = op->getLoc(); emitError(loc) << "The following operations cannot be legalized: " << llvm::join(error_messages, "; ") << ". These legalization failure(s) may be due to missing TF " "to HLO lowerings and/or unsupported attributes, etc."; // Emit more information about the missing ops. This error message // contains useful details beyond the op name (input and output shapes, // attributes, etc.). if (!VLOG_IS_ON(1) && nonlegalized_ops.size() != 1) { emitError(loc) << "Emitting more detail about one op that failed to legalize..."; } else if (VLOG_IS_ON(1)) { emitError(loc) << "Emitting more detail about one of each type of op " "that failed to legalize..."; } for (const auto &op_info : op_name_to_error_info) { op_info.second.second->emitOpError() << "is not legalizable"; if (!VLOG_IS_ON(1)) break; } } /// Returns ops that should use MLIR legalization only in the case of /// prefer_tf2xla. All other ops not in this list should use XlaOpKernel /// legalization only or not be legalized by the new bridge. // LINT.IfChange const llvm::DenseSet<mlir::TypeID> &MlirPreferredOps() { // The static variable is a pointer in order to avoid destruction upon thread // termination. // clang-format off static const llvm::DenseSet<mlir::TypeID>* ops = new llvm::DenseSet<mlir::TypeID>{ // Ops that should always use the MLIR legalization. TypeID::get<TF::FusedBatchNormV3Op>(), TypeID::get<TF::FusedBatchNormGradV3Op>(), TypeID::get<TF::XlaReduceScatterOp>(), TypeID::get<TF::ModOp>(), // Ops that are legalized in the old bridge using MlirXlaOpKernel TypeID::get<TF::AbsOp>(), TypeID::get<TF::AtanOp>(), TypeID::get<TF::AvgPool3DOp>(), TypeID::get<TF::BiasAddGradOp>(), TypeID::get<TF::CeilOp>(), TypeID::get<TF::CheckNumericsOp>(), TypeID::get<TF::CosOp>(), TypeID::get<TF::TanOp>(), TypeID::get<TF::DiagPartOp>(), TypeID::get<TF::EinsumOp>(), TypeID::get<TF::ExpOp>(), TypeID::get<TF::Expm1Op>(), TypeID::get<TF::FakeQuantWithMinMaxArgsOp>(), TypeID::get<TF::FloorOp>(), TypeID::get<TF::IFFTOp>(), TypeID::get<TF::ImagOp>(), TypeID::get<TF::IsFiniteOp>(), TypeID::get<TF::IsInfOp>(), TypeID::get<TF::IsNanOp>(), TypeID::get<TF::LgammaOp>(), TypeID::get<TF::Log1pOp>(), TypeID::get<TF::LogSoftmaxOp>(), TypeID::get<TF::MatrixBandPartOp>(), TypeID::get<TF::MaxPool3DGradOp>(), TypeID::get<TF::PreventGradientOp>(), TypeID::get<TF::RandomShuffleOp>(), TypeID::get<TF::RealOp>(), TypeID::get<TF::ReciprocalOp>(), TypeID::get<TF::ReluOp>(), TypeID::get<TF::Relu6Op>(), TypeID::get<TF::ReluGradOp>(), TypeID::get<TF::RsqrtOp>(), TypeID::get<TF::SelectOp>(), TypeID::get<TF::SigmoidOp>(), TypeID::get<TF::SignOp>(), TypeID::get<TF::SoftmaxOp>(), TypeID::get<TF::SqrtOp>(), TypeID::get<TF::TanhOp>(), TypeID::get<TF::XlaConvV2Op>(), TypeID::get<TF::XlaDotOp>(), TypeID::get<TF::XlaDotV2Op>(), TypeID::get<TF::XlaDynamicSliceOp>(), TypeID::get<TF::XlaEinsumOp>(), TypeID::get<TF::XlaReduceWindowOp>(), TypeID::get<TF::XlaReplicaIdOp>(), TypeID::get<TF::XlaRngBitGeneratorOp>(), TypeID::get<TF::XlaSelectAndScatterOp>(), TypeID::get<TF::XlaSortOp>(), TypeID::get<TF::XlaVariadicReduceV2Op>(), TypeID::get<TF::XlaVariadicSortOp>(), // Ops that have no XlaOpKernel. TypeID::get<TF::RiscAddOp>(), TypeID::get<TF::RiscDotOp>(), // Const op has a simple legalization and it is much more efficient to lower // within MLIR. TypeID::get<TF::ConstOp>(), // AssertOp with string types are not supported by the fallback. TypeID::get<TF::AssertOp>(), // TF2XLA fallback pattern doesn't support these op as MLIR hlo builder // doesn't override the necessary builder methods. These ops have simple // lowering pattern so this should be safe. TypeID::get<TF::CrossReplicaSumOp>(), TypeID::get<TF::InfeedDequeueTupleOp>(), TypeID::get<TF::OutfeedEnqueueTupleOp>(), TypeID::get<TF::XlaShardingOp>(), // These ops have undetermined bugs, may not be legalizable with XlaOpKernel // legalization in TF2XLA fallback. By legalization with MLIR, we can fix // the bug. b/195583695 describes the motivation of this change. // See b/216355804 how to reproduce the bug regarding tf.RandomUniform Op // See b/216353817 how to reproduce the bug regarding tf.StridedSlice Op // See b/245615401 how to reproduce the bug regarding tf.SliceOp TypeID::get<TF::RandomUniformOp>(), TypeID::get<TF::StridedSliceOp>(), TypeID::get<TF::SliceOp>(), // Conditional ops TypeID::get<TF::IfRegionOp>(), TypeID::get<TF::WhileRegionOp>(), TypeID::get<TF::CaseRegionOp>(), TypeID::get<TF::YieldOp>(), }; // clang-format on return *ops; } // LINT.ThenChange(:PopulateLegalizeTfPatterns) // Patterns whose root op is in the set `include_ops` are moved from the set // `from` to the returned set. This is used to partition patterns by op so they // can be cleanly migrated from the old bridge to the MLIR bridge. RewritePatternSet PatternsIncludeOps( RewritePatternSet &from, const llvm::DenseSet<mlir::TypeID> &include_ops) { RewritePatternSet to(from.getContext()); // Filter NativePatterns. for (auto &pattern : from.getNativePatterns()) { std::optional<OperationName> pat_op_name = pattern->getRootKind(); // If the pattern does not have a specific operation, always include it, // If the pattern is in include_ops then include it. bool include = !pat_op_name || include_ops.count(pat_op_name->getRegisteredInfo()->getTypeID()); if (include) to.add(std::move(pattern)); } // Don't filter PDLPatterns. to.add(std::move(from.getPDLPatterns())); return to; } std::string OperationLegalityString(Operation *op, const ConversionTarget &target) { auto op_name = op->getName(); auto action = target.getOpAction(op_name); if (!action.has_value()) { return "Unknown"; } switch (action.value_or(ConversionTarget::LegalizationAction::Legal)) { case ConversionTarget::LegalizationAction::Legal: return "Legal"; case ConversionTarget::LegalizationAction::Dynamic: return "Dynamic"; case ConversionTarget::LegalizationAction::Illegal: return "Illegal"; default: return "Invalid"; } } void IncrementFailedLegalizationCount(Operation *op, const ConversionTarget &target) { auto op_name = op->getName(); auto name_string = op_name.getStringRef().str(); auto op_legality = OperationLegalityString(op, target); mlir_failed_legalization_count->GetCell(name_string, op_legality) ->IncrementBy(1); } mlir::LogicalResult ApplyPatterns(Operation *op, RewritePatternSet &patterns, bool legalize_chlo) { ConversionTarget target = GetDefaultLegalConversionTargets(*op->getContext(), legalize_chlo); DenseSet<Operation *> unconverted_ops; auto result = applyPartialConversion(op, target, std::move(patterns), &unconverted_ops); if (failed(result)) { IncrementFailedLegalizationCount(op, target); } for (const auto &unconverted_op : unconverted_ops) { IncrementFailedLegalizationCount(unconverted_op, target); } return result; } /// When `tf2xla_fallback_device_type` is not `None`, also uses legalization /// patterns from TF2XLA fallback for provided device type (see /// legalize_tf_with_tf2xla.cc for details). By default, TF2XLA fallback is /// not used. LogicalResult legalizeTF(Operation *op, bool legalize_chlo, std::optional<StringRef> tf2xla_fallback_device_type, bool prefer_tf2xla, bool use_tf2xla_hlo_importer) { MLIRContext *context = op->getContext(); RewritePatternSet legalize_lower_patterns(context); // Note that the `OperationConverter` orders patterns lexicographically by: // 1) Ascending legalization depth (i.e., minimum number of patterns // necessary // to arrive at conversion target). This requires relevant patterns to // specify the list of ops generated by it which most of patterns // implemented in C++ don't do so this comparison doesn't work in those // cases. // 2) Descending pattern benefit. // 3) Op specific patterns over patterns with MatchAnyOpTypeTag. // 4) Order of patterns in `RewritePatternSet`. // Add TF->HLO legalization patterns. PopulateLegalizeTfPatterns(context, &legalize_lower_patterns); PopulateLegalizeTfQuantizationPatterns(context, &legalize_lower_patterns); // Add TF->TF lowering patterns. TF::PopulateTFLoweringBeforeHLOPatterns(context, &legalize_lower_patterns); if (tf2xla_fallback_device_type && prefer_tf2xla) { VLOG(1) << "TF to XLA legalization patterns are partitioned by op into " "either native MLIR legalization, or TF2XLA fallback " "legalzation, with a preference toward TF2XLA."; } else if (tf2xla_fallback_device_type) { VLOG(1) << "TF to XLA legalization patterns include all native patterns " "and TF2XLA fallback patterns."; } else { VLOG(1) << "TF to XLA legalization patterns are native patterns only."; } // Set patterns to legalize_lower_patters, where in the prefer_tf2xla case // only patterns whose ops are in the set MlirPreferredOps are kept. RewritePatternSet patterns = (tf2xla_fallback_device_type && prefer_tf2xla) ? PatternsIncludeOps(legalize_lower_patterns, MlirPreferredOps()) : std::move(legalize_lower_patterns); Tf2XlaTypeConverter converter; if (tf2xla_fallback_device_type) { // Add TF->HLO legalization patterns via TF2XLA fallback. PopulateLegalizeTfWithTf2XlaPatterns( tf2xla_fallback_device_type.value(), patterns, context, converter, prefer_tf2xla, use_tf2xla_hlo_importer); } // Populate with CHLO->HLO lowerings to account for TF ops legalized to // CHLO first. if (legalize_chlo) { chlo::populateDecomposeChloPatterns(context, &patterns); chlo::populateChloBroadcastingPatterns(context, &patterns); } // ConstantLike op is convenient to create splat constants, but is // canonicalized to plain HLO constant if statically shaped. Add the // canonicalization pattern to pattern list to enable multi-hop lowering. chlo::ConstantLikeOp::getCanonicalizationPatterns(patterns, context); return ApplyPatterns(op, patterns, legalize_chlo); } // Performs the lowering to XLA dialect. void LegalizeTF::runOnOperation() { std::optional<StringRef> tf2xla_fallback_device_type = std::nullopt; if (use_tf2xla_fallback_) { tf2xla_fallback_device_type = device_type_; } if (failed(legalizeTF(getOperation(), legalize_chlo_, tf2xla_fallback_device_type, prefer_tf2xla_, use_tf2xla_hlo_importer_))) { signalPassFailure(); } } } // end namespace void PopulateLegalizeTfQuantizationPatterns(MLIRContext *context, RewritePatternSet *patterns) { patterns ->add<ConvertUniformQuantizedDotHybridOp, ConvertUniformQuantizedConvolutionHybridOp, ConvertUniformQuantizeOp, ConvertUniformRequantizeOp, ConvertUniformDequantizeOp, ConvertUniformQuantizedDotOp, ConvertUniformQuantizedConvolutionOp, ConvertUniformQuantizedAddOp, ConvertUniformQuantizedClipByValueOp>(context); } std::unique_ptr<OperationPass<ModuleOp>> createLegalizeTFPass( bool allow_partial_conversion, bool legalize_chlo, std::optional<StringRef> tf2xla_fallback_device_type, bool prefer_tf2xla) { return std::make_unique<LegalizeTF>(allow_partial_conversion, legalize_chlo, tf2xla_fallback_device_type, prefer_tf2xla); } } // end namespace mhlo } // end namespace mlir
e2aae21033025331948481cd3e81a19424ee032c
ef31dbdca65af3c7e96235c316db4138a31ad128
/header/OutputReApp.hpp
357ec2160cd9110f8522a805685b4e16c00970c5
[]
no_license
adel037/RShell
bd4858bc9d12497f3eee6e45c5ba3b87b2ccd7af
22e6fe1b166a84903f271011f83cc21dabddeeb8
refs/heads/master
2022-12-31T18:56:02.051079
2020-10-24T23:42:22
2020-10-24T23:42:22
306,987,982
0
0
null
null
null
null
UTF-8
C++
false
false
409
hpp
#ifndef __OUTPUTREAPP_HPP__ #define __OUTPUTREAPP_HPP__ #include "Base.hpp" using namespace std; class OutputReApp : public Base { public: OutputReApp(Base* userLeft, Base* userRight); void execute(); private: void initializeFileDesc(int &savestdout, int &file_desc); void restore_CloseFile(int &savestdout, int &file_desc); char* getFileName() { }; }; #endif
a06cdeceefed627dc706961f8eeabcb4a9be4430
8727d1a506114c2bbab2f74db9bdaf68b5a6c83e
/6/6-6/grade.h
3f0b7f6ed6dfda3b72ea841247af4a9afe152f20
[]
no_license
BaiXious/Accelerated-cpp
5c5525eb9678ad98475208f82ea63b1606e31a86
26ad13fe83aa36c8d3ca1caf89b04e90f441d7d7
refs/heads/master
2022-01-13T08:11:14.337940
2018-08-28T04:06:10
2018-08-28T04:06:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,342
h
#ifndef _GRADE_H_ #define _GRADE_H_ #include <algorithm> #include <vector> #include <string> #include "student_info.h" bool fgrade(const student_info& ); double median(/*const*/ std::vector<double>/*&*/ ); double grade(const student_info& ); double grade(double, double, const std::vector<double>& ); double grade(double, double, double ); bool did_all_hw(const student_info& ); double grade_aux(const student_info& ); //double median_analysis(const std::vector<student_info>& ); /*void write_analysis(std::ostream&, const std::string&, double analysis(const std::vector<student_info>&), const std::vector<student_info>& did, const std::vector<student_info>& did_not); */ void write_analysis(std::ostream&, const std::string&, double analysis_function(const student_info&), const std::vector<student_info>& did, const std::vector<student_info>& didnt); double average(const std::vector<double>& ); double average_grade(const student_info& ); //double average_analysis(const std::vector<student_info>& ); double optimistic_median(const student_info& ); //double optimistic_median_analysis(const std::vector<student_info>& ); double analysis(const std::vector<student_info>& , double function(const student_info& )); #endif
bb7e3effb9dccbdd50ba92d8c66bfc338198a8bb
4211011a7ef3bfacd490a576da3955636c650c54
/gCCD/gCCDComponent/include/STRModelsHeaders/STRBase.h
e07c13cc3b61b2c45f49df8124a2769c5ba0542c
[]
no_license
andreltr/goos-acs
136760de02499014b974c38fa2f6afb7693a630f
cae97907b735b22f3f448cc86813d51a38b1927b
refs/heads/master
2018-01-08T14:41:33.040253
2010-11-08T23:08:00
2010-11-08T23:08:00
49,103,361
0
0
null
null
null
null
UTF-8
C++
false
false
1,032
h
#ifndef STRBASE_H_ #define STRBASE_H_ #ifndef __cplusplus #error This is a C++ include file and cannot be used from plain C #endif #include <iostream> #include "ComponentProperties.h" #include "Observer.h" /** * Abstract base class for the Strategy Pattern */ class STRBase: public Observer { protected: std::string* filesQueue; float currentTemp; ComponentProperties* componentProperties; public: STRBase() { filesQueue = 0; componentProperties = 0; } virtual ~STRBase() { if (filesQueue != 0) { delete[] filesQueue; } } virtual void on() = 0; virtual void off() = 0; virtual void resetCamera() = 0; virtual std::string* startExposure() = 0; virtual void stopExposure() = 0; virtual void startCooler() = 0; virtual void stopCooler() = 0; // float getCurrentCCDTemperatue() { return currentTemp; } virtual void update()=0; void setComponentProperties(Observable* observable) { componentProperties = (ComponentProperties*) observable; setObservable(componentProperties); } }; #endif
[ "miguel.ortiz.cortes@d55a11f0-c6b6-1512-6fd8-a0a8490a29df" ]
miguel.ortiz.cortes@d55a11f0-c6b6-1512-6fd8-a0a8490a29df
5a257ec17ed6d6c5e6bc4389fe1266f39bd987e0
791ef6dc8a32bd68423866cce2d30d71ae45ca55
/test/test_lest_cpp03.cpp
08b976f5673d8396ac44f54e947976d94c60d081
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
0xc0170/lest
a0cc69241a4569ab29bb01b96bc63f5b1688965d
3ab5bca4bf62bf075d6d837c270c388c1e67fa65
refs/heads/master
2021-01-15T17:14:10.559149
2015-07-23T08:21:00
2015-07-23T08:21:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
28,476
cpp
// Copyright 2013, 2014 by Martin Moene // // 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 "lest_cpp03.hpp" #include <string> #ifdef lest_COMPILER_IS_MSVC6 namespace std { using ::size_t; } #endif lest::test_specification no_using_namespace_lest; lest_CASE( no_using_namespace_lest, "Namespace lest is specified correctly in lest_cpp03.hpp [compile-only]" ) { EXPECT( true ); EXPECT_NOT( false ); EXPECT_NO_THROW( true ); EXPECT_THROWS( true ); EXPECT_THROWS_AS( true, std::exception ); } #define CASE( name ) lest_CASE( specification, name ) using namespace lest; test_specification specification; CASE( "Function to suppress warning \"expression has no effect\" acts as identity function" ) { EXPECT( false == is_true( false ) ); EXPECT( true == is_true( true ) ); } CASE( "Function with_message() returns correct string" ) { std::string with = "with message \"" ; std::string msg = "Let writing tests become irresistibly easy and attractive."; EXPECT( ( with + msg + "\"" ) == with_message( msg ) ); } CASE( "Function of_type() returns correct string" ) { std::string msg = "this_type"; EXPECT( ( "of type " + msg ) == of_type( msg ) ); } CASE( "Function pluralise() adds 's' except for 1 item" ) { std::string word = "hammer"; EXPECT( word == pluralise( 1, word ) ); int range[] = {0,2,3,4,5,6,7,8,9,10,11,12}; for ( int * pos = range; pos != range + lest_DIMENSION_OF(range); ++pos ) EXPECT( ( word + "s" ) == pluralise( *pos, word ) ); } CASE( "Location constructs properly" ) { char const * file = __FILE__; int line = __LINE__; location where( file, line ); EXPECT( file == where.file ); EXPECT( line == where.line ); } CASE( "Comment constructs properly" ) { std::string info = __FILE__; comment note = info; EXPECT( info == note.info ); } CASE( "Comment converted to bool indicates absence or presence of comment" ) { EXPECT( false == bool( comment( "") ) ); EXPECT( true == bool( comment("x") ) ); } CASE( "Failure exception type constructs and prints properly" ) { std::string name = "test-name"; failure msg( location("filename.cpp", 765), "expression", "decomposition" ); std::ostringstream os; report( os, msg, name ); #ifndef __GNUG__ EXPECT( os.str() == "filename.cpp(765): failed: test-name: expression for decomposition\n" ); #else EXPECT( os.str() == "filename.cpp:765: failed: test-name: expression for decomposition\n" ); #endif } CASE( "Expected exception type constructs and prints properly" ) { std::string name = "test-name"; expected msg( location("filename.cpp", 765), "expression" ); std::ostringstream os; report( os, msg, name ); #ifndef __GNUG__ EXPECT( os.str() == "filename.cpp(765): failed: didn't get exception: test-name: expression\n" ); #else EXPECT( os.str() == "filename.cpp:765: failed: didn't get exception: test-name: expression\n" ); #endif } CASE( "Unexpected exception type constructs and prints properly" ) { std::string name = "test-name"; lest::unexpected msg( location("filename.cpp", 765), "expression", "exception-type" ); std::ostringstream os; report( os, msg, name ); #ifndef __GNUG__ EXPECT( os.str() == "filename.cpp(765): failed: got unexpected exception exception-type: test-name: expression\n" ); #else EXPECT( os.str() == "filename.cpp:765: failed: got unexpected exception exception-type: test-name: expression\n" ); #endif } CASE( "Expect generates no message exception for a succeeding test" ) { struct f { static void pass(env & $) { EXPECT(true); } }; test pass( "P", f::pass ); try { pass.behaviour( $ ); } catch(...) { throw failure(location(__FILE__,__LINE__), "unexpected error generated", "true"); } } CASE( "Expect generates a message exception for a failing test" ) { struct f { static void fail(env & $) { EXPECT(false); } }; test fail( "F", f::fail ); for (;;) { try { fail.behaviour( $ ); } catch ( message & ) { break; } throw failure(location(__FILE__,__LINE__), "no error generated", "false"); } } CASE( "Expect succeeds for success (true) and failure (false)" ) { struct f { static void pass(env & $) { EXPECT(true);} static void fail(env & $) { EXPECT(false);} }; test pass[] = { test( "P", f::pass ) }; test fail[] = { test( "F", f::fail ) }; std::ostringstream os; EXPECT( 0 == run( pass, os ) ); EXPECT( 1 == run( fail, os ) ); } CASE( "Expect succeeds for integer comparation" ) { EXPECT( 7 == 7 ); EXPECT( 7 != 8 ); EXPECT( 7 >= 6 ); EXPECT( 7 <= 8 ); EXPECT( 7 > 6 ); EXPECT( 7 < 8 ); EXPECT_NOT( 7 == 8 ); EXPECT_NOT( 7 != 7 ); EXPECT_NOT( 7 <= 6 ); EXPECT_NOT( 7 >= 8 ); EXPECT_NOT( 7 < 6 ); EXPECT_NOT( 7 > 8 ); } CASE( "Expect succeeds for mixed integer, real comparation" ) { EXPECT( 7.0 == 7 ); EXPECT( 7.0 != 8 ); EXPECT( 7 == 7.0 ); EXPECT( 7 != 8.0 ); EXPECT_NOT( 7.0 == 8 ); EXPECT_NOT( 7 != 7.0 ); } CASE( "Expect succeeds for string comparation" ) { std::string a("a"); std::string b("b"); EXPECT( a == a ); EXPECT( a != b ); EXPECT( b >= a ); EXPECT( a <= b ); EXPECT( b > a ); EXPECT( a < b ); EXPECT_NOT( a == b ); EXPECT_NOT( a != a ); EXPECT_NOT( b <= a ); EXPECT_NOT( a >= b ); EXPECT_NOT( b < a ); EXPECT_NOT( a > b ); } CASE( "Expect expression RHS can use * / % + -" ) { EXPECT( 7 == 1 * 7 ); EXPECT( 7 == 7 / 1 ); EXPECT( 0 == 7 % 1 ); EXPECT( 7 == 1 + 6 ); EXPECT( 7 == 8 - 1 ); } CASE( "Expect expression LHS can use * / % + -" ) { EXPECT( 1 * 7 == 7 ); EXPECT( 7 / 1 == 7 ); EXPECT( 7 % 1 == 0 ); EXPECT( 1 + 6 == 7 ); EXPECT( 8 - 1 == 7 ); } CASE( "Function run() returns the right failure count" ) { struct f { static void pass(env & $) { EXPECT( 1==1 ); } static void fail(env & $) { EXPECT( 0==1 ); }}; test pass [] = { test( "P" , f::pass ) }; test fail_1[] = { test( "F1", f::fail ) }; test fail_3[] = { test( "F1", f::fail ), test( "F2", f::fail ), test( "F3", f::fail ),}; std::ostringstream os; EXPECT( 0 == run( pass , os ) ); EXPECT( 1 == run( fail_1, os ) ); EXPECT( 3 == run( fail_3, os ) ); } std::string std_hello_world = "hello-world"; CASE( "Expect reports an unexpected standard exception" ) { struct f { static void fail(env & $) { EXPECT( (throw std::runtime_error(std_hello_world), true) ); }}; test fail[] = { test( "F", f::fail ) }; std::ostringstream os; EXPECT( 1 == run( fail, os ) ); EXPECT( std::string::npos != os.str().find(std_hello_world) ); } CASE( "Expect reports an unexpected non-standard exception" ) { struct f { static void fail(env & $) { EXPECT( (throw 77, true) ); }}; test fail[] = { test( "F", f::fail ) }; std::ostringstream os; EXPECT( 1 == run( fail, os ) ); } CASE( "Expect_no_throw succeeds without an exception" ) { struct f { static void pass(env & $) { EXPECT_NO_THROW( true ); }}; test pass[] = { test( "P", f::pass ) }; std::ostringstream os; EXPECT( 0 == run( pass, os ) ); } CASE( "Expect_no_throw reports a standard exception" ) { struct f { static void fail(env & $) { EXPECT_NO_THROW( throw std::runtime_error(std_hello_world) ); }}; test fail[] = { test( "F", f::fail ) }; std::ostringstream os; EXPECT( 1 == run( fail, os ) ); EXPECT( std::string::npos != os.str().find(std_hello_world) ); } CASE( "Expect_no_throw reports a non-standard exception" ) { struct f { static void fail(env & $) { EXPECT_NO_THROW( (throw 77, true) ); }}; test fail[] = { test( "F", f::fail ) }; std::ostringstream os; EXPECT( 1 == run( fail, os ) ); } CASE( "Expect_throws reports a missing exception" ) { struct f { static void fail(env & $) { EXPECT_THROWS( true ); }}; test fail[] = { test( "F", f::fail ) }; std::ostringstream os; EXPECT( 1 == run( fail, os ) ); } CASE( "Expect_throws succeeds with a standard exception" ) { struct f { static void pass(env & $) { EXPECT_THROWS( throw std::runtime_error(std_hello_world) ); }}; test pass[] = { test( "P", f::pass ) }; std::ostringstream os; EXPECT( 0 == run( pass, os ) ); } CASE( "Expect_throws succeeds with a non-standard exception" ) { struct f { static void pass(env & $) { EXPECT_THROWS( throw 77 ); }}; test pass[] = { test( "P", f::pass ) }; std::ostringstream os; EXPECT( 0 == run( pass, os ) ); } CASE( "Expect_throws_as reports a missing exception" ) { struct f { static void fail(env & $) { EXPECT_THROWS_AS( true, std::runtime_error ); }}; test fail[] = { test( "F", f::fail ) }; std::ostringstream os; EXPECT( 1 == run( fail, os ) ); } CASE( "Expect_throws_as reports getting a different exception" ) { struct f { static void fail(env & $) { EXPECT_THROWS_AS( throw std::bad_alloc(), std::runtime_error ); }}; test fail[] = { test( "F", f::fail ) }; std::ostringstream os; EXPECT( 1 == run( fail, os ) ); } CASE( "Expect_throws_as succeeds with a specific standard exception" ) { struct f { static void pass(env & $) { EXPECT_THROWS_AS( throw std::bad_alloc(), std::bad_alloc ); }}; test pass[] = { test( "P", f::pass ) }; std::ostringstream os; EXPECT( 0 == run( pass, os ) ); } CASE( "Expect_throws_as succeeds with a specific non-standard exception" ) { struct f { static void pass(env & $) { EXPECT_THROWS_AS( throw 77, int ); }}; test pass[] = { test( "P", f::pass ) }; std::ostringstream os; EXPECT( 0 == run( pass, os ) ); } CASE( "Setup creates a fresh fixture for each section" ) { SETUP("Context") { int i = 7; SECTION("S1") { i = 42; } SECTION("S2") { EXPECT( i == 7 ); } } } CASE( "Setup runs as many times as there are sections" ) { int i = 0; SETUP("Context") { ++i; SECTION("S1") { } SECTION("S2") { } } EXPECT( i == 2 ); } #if __cplusplus >= 201103L CASE( "Decomposition formats nullptr as string" ) { struct f { static void pass(env & $) { EXPECT( nullptr == nullptr ); } static void fail(env & $) { EXPECT( (void*)1 == nullptr ); }}; test pass[] = { test( "P", f::pass ) }; test fail[] = { test( "F", f::fail ) }; std::ostringstream os; EXPECT( 0 == run( pass, os ) ); EXPECT( 1 == run( fail, os ) ); EXPECT( std::string::npos != os.str().find( "(void*)1 == nullptr for 0x1 == nullptr" ) ); } #endif CASE( "Decomposition formats boolean as strings true and false" ) { struct f { static void pass(env & $) { EXPECT( true == true ); } static void fail(env & $) { EXPECT( true == false ); }}; test pass[] = { test( "P", f::pass ) }; test fail[] = { test( "F", f::fail ) }; std::ostringstream os; EXPECT( 0 == run( pass, os ) ); EXPECT( 1 == run( fail, os ) ); EXPECT( std::string::npos != os.str().find( "true == false for true == false" ) ); } CASE( "Decomposition formats character with single quotes" ) { struct f { static void pass(env & $) { EXPECT( 'a' < 'b' ); } static void fail(env & $) { EXPECT( 'b' < 'a' ); }}; test pass[] = { test( "P", f::pass ) }; test fail[] = { test( "F", f::fail ) }; std::ostringstream os; EXPECT( 0 == run( pass, os ) ); EXPECT( 1 == run( fail, os ) ); EXPECT( std::string::npos != os.str().find( "'b' < 'a' for 'b' < 'a'" ) ); } std::string std_hello( "hello" ); std::string std_world( "world" ); char const * hello = "hello"; char const * world = "world"; CASE( "Decomposition formats std::string with double quotes" ) { struct f { static void pass(env & $) { EXPECT( std_hello < "world" ); } static void fail(env & $) { EXPECT( std_world < "hello" ); }}; test pass[] = { test( "P", f::pass ) }; test fail[] = { test( "F", f::fail ) }; std::ostringstream os; EXPECT( 0 == run( pass, os ) ); EXPECT( 1 == run( fail, os ) ); // lifted from assertion for VC6: std::size_t pos = os.str().find( "std_world < \"hello\" for \"world\" < \"hello\"" ); EXPECT( std::string::npos != pos ); } CASE( "Decomposition formats C string with double quotes" ) { struct f { static void pass(env & $) { EXPECT( hello < std_world ); } static void fail(env & $) { EXPECT( world < std_hello ); }}; test pass[] = { test( "P", f::pass ) }; test fail[] = { test( "F", f::fail ) }; std::ostringstream os; EXPECT( 0 == run( pass, os ) ); EXPECT( 1 == run( fail, os ) ); // lifted from assertion for VC6: std::size_t pos = os.str().find( "world < std_hello for \"world\" < \"hello\"" ); EXPECT( std::string::npos != pos ); } CASE( "Decomposition formats a pair with elements between curly braces" ) { EXPECT( "{ 42, 3.14 }" == lest::to_string( std::make_pair( 42, 3.14 ) ) ); } #ifdef lest_CPP11_OR_GREATER CASE( "Decomposition formats a tuple with elements between curly braces" ) { typedef std::tuple<> type; EXPECT( "{ }" == lest::to_string( type{} ) ); EXPECT( "{ 'a', 42, 3.14, \"hello world\" }" == lest::to_string( std::make_tuple( 'a', 42, 3.14, "hello world" ) ) ); } #endif CASE( "Has single expression evaluation" ) { struct f { static void pass(env & $) { int n = 0; EXPECT( 1 == ++n ); } static void fail(env & $) { int n = 0; EXPECT( 2 == ++n ); }}; test pass[] = { test( "P", f::pass ) }; test fail[] = { test( "F", f::fail ) }; std::ostringstream os; EXPECT( 0 == run( pass, os ) ); EXPECT( 1 == run( fail, os ) ); EXPECT( std::string::npos != os.str().find( "for 2 == 1" ) ); } CASE( "Approximate compares properly [approx][basic]" ) { EXPECT( 1.23 == approx( 1.23 ) ); EXPECT( 1.23 != approx( 1.24 ) ); } CASE( "Approximate using epsilon compares properly [approx][epsilon]" ) { EXPECT( 1.23 != approx( 1.231 ) ); EXPECT( 1.23 == approx( 1.231 ).epsilon( 0.1 ) ); } CASE( "Approximate using custom epsilon compares properly [approx][custom]" ) { approx custom = approx::custom().epsilon( 0.1 ); EXPECT( approx( 1.231 ) != 1.23 ); EXPECT( custom( 1.231 ) == 1.23 ); } CASE( "Approximate to Pi compares properly [approx][pi]" ) { struct f { static double divide( double a, double b ) { return a / b; }}; EXPECT( f::divide( 22, 7 ) == approx( 3.141 ).epsilon( 0.001 ) ); EXPECT( f::divide( 22, 7 ) != approx( 3.141 ).epsilon( 0.0001 ) ); } CASE( "Skips tests tagged [hide]" ) { EXPECT( false ); } CASE( "Skips tests tagged [.]" ) { EXPECT( false ); } CASE( "Skips tests with tags that start with [.followed by anything]" ) { EXPECT( false ); } #if lest_FEATURE_REGEX_SEARCH CASE( "Test specifications select tests [commandline]" ) { struct f { static void fail(env & $) { EXPECT( false ); }}; test fail[] = { test( "Hello world [tag1]" , f::fail ), test( "Good morning [tag1]", f::fail ), test( "Good noon [tag2]" , f::fail ), test( "Good bye tags" , f::fail )}; std::ostringstream os; char const * args1[] = { "world" }; char const * args2[] = { "1\\]" }; char const * args3[] = { "\\[.*\\]" }; EXPECT( 1 == run( fail, make_texts( args1 ), os ) ); EXPECT( 2 == run( fail, make_texts( args2 ), os ) ); EXPECT( 3 == run( fail, make_texts( args3 ), os ) ); } CASE( "Test specifications omit tests [commandline]" ) { struct f { static void fail(env & $) { EXPECT( false ); }}; test fail[] = { test( "Hello world [tag1]" , f::fail ), test( "Good morning [tag1]", f::fail ), test( "Good noon [tag2]" , f::fail ), test( "Good bye tags" , f::fail )}; std::ostringstream os; char const * args1[] = { "!world" }; char const * args2[] = { "!1\\]" }; char const * args3[] = { "!\\[.*\\]" }; EXPECT( 3 == run( fail, make_texts( args1 ), os ) ); EXPECT( 2 == run( fail, make_texts( args2 ), os ) ); EXPECT( 1 == run( fail, make_texts( args3 ), os ) ); } CASE( "Test specification series select tests [commandline]" ) { struct f { static void fail(env & $) { EXPECT( false ); }}; test fail[] = { test( "a [x1]" , f::fail ), test( "b [x1]" , f::fail ), test( "c [x2]" , f::fail ), test( "d [hide]", f::fail ), test( "e [.]" , f::fail )}; std::ostringstream os; char const * args1[] = { "!\\[x" }; char const * args2[] = { "!\\[x1" }; char const * args3[] = { "!\\[x" , "\\[x2" }; char const * args4[] = { "\\[\\.\\]", "!\\[x" }; char const * args5[] = { "@" , "!\\[x" }; char const * args6[] = { "*" , "!\\[x" }; char const * args7[] = { "^.*$" , "!\\[x" }; EXPECT( 0 == run( fail, make_texts( args1 ), os ) ); EXPECT( 1 == run( fail, make_texts( args2 ), os ) ); EXPECT( 1 == run( fail, make_texts( args3 ), os ) ); EXPECT( 1 == run( fail, make_texts( args4 ), os ) ); EXPECT( 2 == run( fail, make_texts( args5 ), os ) ); EXPECT( 2 == run( fail, make_texts( args6 ), os ) ); EXPECT( 2 == run( fail, make_texts( args7 ), os ) ); } #else // regex_search: CASE( "Test specifications select tests [commandline]" ) { struct f { static void fail(env & $) { EXPECT( false ); }}; test fail[] = { test( "Hello world [tag1]" , f::fail ), test( "Good morning [tag1]", f::fail ), test( "Good noon [tag2]" , f::fail ), test( "Good bye tags" , f::fail )}; std::ostringstream os; char const * args1[] = { "Hello" }; char const * args2[] = { "[tag1]" }; char const * args3[] = { "[tag2]" }; char const * args5[] = { "@" }; char const * args6[] = { "*" }; char const * args7[] = { "AAA*BBB" }; EXPECT( 1 == run( fail, make_texts( args1 ), os ) ); EXPECT( 2 == run( fail, make_texts( args2 ), os ) ); EXPECT( 1 == run( fail, make_texts( args3 ), os ) ); EXPECT( 4 == run( fail, texts( ), os ) ); EXPECT( 4 == run( fail, make_texts( args5 ), os ) ); EXPECT( 4 == run( fail, make_texts( args6 ), os ) ); EXPECT( 0 == run( fail, make_texts( args7 ), os ) ); } CASE( "Test specifications omit tests [commandline]" ) { struct f { static void fail(env & $) { EXPECT( false ); }}; test fail[] = { test( "Hello world [tag1]" , f::fail ), test( "Good morning [tag1]", f::fail ), test( "Good bye [tag2]" , f::fail )}; std::ostringstream os; char const * args1[] = { "![tag1]" }; char const * args2[] = { "![tag2]" }; EXPECT( 1 == run( fail, make_texts( args1 ), os ) ); EXPECT( 2 == run( fail, make_texts( args2 ), os ) ); } CASE( "Test specification series select tests [commandline]" ) { struct f { static void fail(env & $) { EXPECT( false ); }}; test fail[] = { test( "a [x1]" , f::fail ), test( "b [x1]" , f::fail ), test( "c [x2]" , f::fail ), test( "d [hide]", f::fail ), test( "e [.]" , f::fail )}; std::ostringstream os; char const * args1[] = { "![x" }; char const * args2[] = { "![x1" }; char const * args3[] = { "![x" , "[x2" }; char const * args4[] = { "[.]" , "![x" }; char const * args5[] = { "@" , "![x" }; char const * args6[] = { "*" , "![x" }; EXPECT( 0 == run( fail, make_texts( args1 ), os ) ); EXPECT( 1 == run( fail, make_texts( args2 ), os ) ); EXPECT( 1 == run( fail, make_texts( args3 ), os ) ); EXPECT( 1 == run( fail, make_texts( args4 ), os ) ); EXPECT( 2 == run( fail, make_texts( args5 ), os ) ); EXPECT( 2 == run( fail, make_texts( args6 ), os ) ); } #endif CASE( "Unrecognised option recognised as such [commandline]" ) { struct f { static void fail(env &) { ; }}; test fail[] = { test( "", f::fail ) }; std::ostringstream os; char const * args[] = { "--nonexisting-option" }; EXPECT( 1 == run( fail, make_texts( args ), os ) ); } CASE( "Option -h,--help shows help message [commandline]" ) { struct f { static void pass(env &) { ; }}; test pass[] = { test( "", f::pass ) }; std::ostringstream os; char const * args1[] = { "-h" }; char const * args2[] = { "--help" }; EXPECT( 0 == run( pass, make_texts( args1 ), os ) ); EXPECT( 0 == run( pass, make_texts( args2 ), os ) ); } CASE( "Option -a,--abort aborts selected tests [commandline]" ) { struct f { static void fail(env & $) { EXPECT( false ); }}; test fail[] = { test( "", f::fail ), test( "", f::fail ) }; std::ostringstream os; char const * args1[] = { "-a" }; char const * args2[] = { "--abort" }; EXPECT( 2 == run( fail, texts( ), os ) ); EXPECT( 1 == run( fail, make_texts( args1 ), os ) ); EXPECT( 1 == run( fail, make_texts( args2 ), os ) ); } CASE( "Option -c,--count counts selected tests [commandline]" ) { struct f { static void abc(env &) { ; } static void xyz(env &) { ; }}; test pass[] = { test( "a b c", f::abc ), test( "x y z", f::xyz ) }; { std::ostringstream os; char const * args1[] = { "-c" }; char const * args2[] = { "--count" }; EXPECT( 0 == run( pass, make_texts( args1 ), os ) ); EXPECT( 0 == run( pass, make_texts( args2 ), os ) ); EXPECT( std::string::npos != os.str().find( "2 " ) ); }{ std::ostringstream os; char const * args[] = { "-c", "y" }; EXPECT( 0 == run( pass, make_texts( args ), os ) ); EXPECT( std::string::npos != os.str().find( "1 " ) ); } } CASE( "Option -g,--list-tags lists tags of selected tests [commandline]" ) { struct f { static void abc(env &) { ; } static void xyz(env &) { ; }}; test pass[] = { test( "a [b][c]" , f::abc ), test( "[x] y [z]", f::xyz ) }; { std::ostringstream os; char const * args1[] = { "-g" }; char const * args2[] = { "--list-tags" }; EXPECT( 0 == run( pass, make_texts( args1 ), os ) ); EXPECT( 0 == run( pass, make_texts( args2 ), os ) ); EXPECT( std::string::npos != os.str().find( "[b]" ) ); EXPECT( std::string::npos != os.str().find( "[c]" ) ); EXPECT( std::string::npos != os.str().find( "[x]" ) ); EXPECT( std::string::npos != os.str().find( "[z]" ) ); }{ std::ostringstream os; char const * args1[] = { "-g", "[x]" }; EXPECT( 0 == run( pass, make_texts( args1 ), os ) ); EXPECT( std::string::npos == os.str().find( "[b]" ) ); EXPECT( std::string::npos == os.str().find( "[c]" ) ); EXPECT( std::string::npos != os.str().find( "[x]" ) ); EXPECT( std::string::npos != os.str().find( "[z]" ) ); } } CASE( "Option -l,--list-tests lists selected tests [commandline]" ) { struct f { static void abc(env &) { ; } static void xyz(env &) { ; }}; test pass[] = { test( "a b c", f::abc ), test( "x y z", f::xyz ) }; { std::ostringstream os; char const * args1[] = { "-l" }; char const * args2[] = { "--list-tests" }; EXPECT( 0 == run( pass, make_texts( args1 ), os ) ); EXPECT( 0 == run( pass, make_texts( args2 ), os ) ); EXPECT( std::string::npos != os.str().find( "a b c" ) ); EXPECT( std::string::npos != os.str().find( "x y z" ) ); }{ std::ostringstream os; char const * args[] = { "-l", "b" }; EXPECT( 0 == run( pass, make_texts( args ), os ) ); EXPECT( std::string::npos != os.str().find( "b" ) ); EXPECT( std::string::npos == os.str().find( "y" ) ); } } CASE( "Option -p,--pass also reports passing selected tests [commandline]" ) { struct f { static void pass(env & $) { EXPECT( true ); }}; test pass[] = { test( "a b c", f::pass ) }; { std::ostringstream os; char const * args[] = { "-p" }; EXPECT( 0 == run( pass, make_texts( args ), os ) ); EXPECT( std::string::npos != os.str().find( "a b c" ) ); EXPECT( std::string::npos != os.str().find( "passed" ) ); }{ std::ostringstream os; char const * args[] = { "--pass" }; EXPECT( 0 == run( pass, make_texts( args ), os ) ); EXPECT( std::string::npos != os.str().find( "a b c" ) ); EXPECT( std::string::npos != os.str().find( "passed" ) ); } } CASE( "Option -t,--time reports execution time of selected tests [commandline]" ) { struct f { static void pass(env & $) { EXPECT( true ); }}; test pass[] = { test( "a b c", f::pass ) }; { std::ostringstream os; char const * args[] = { "-t" }; EXPECT( 0 == run( pass, make_texts( args ), os ) ); EXPECT( std::string::npos != os.str().find( "a b c" ) ); EXPECT( std::string::npos != os.str().find( "ms:" ) ); EXPECT( std::string::npos != os.str().find( "Elapsed" ) ); }{ std::ostringstream os; char const * args[] = { "--time" }; EXPECT( 0 == run( pass, make_texts( args ), os ) ); EXPECT( std::string::npos != os.str().find( "a b c" ) ); EXPECT( std::string::npos != os.str().find( "ms:" ) ); EXPECT( std::string::npos != os.str().find( "Elapsed" ) ); } } CASE( "Option --repeat=N is recognised [commandline]" ) { std::ostringstream os; char const * args[] = { "--repeat=42" }; EXPECT( 0 == run( tests(), make_texts( args ), os ) ); } CASE( "Option --repeat=3 repeats 3x [commandline]" ) { struct f { static void fail(env & $) { EXPECT( false ); }}; test fail[] = { test( "", f::fail ) }; std::ostringstream os; char const * args[] = { "--repeat=3" }; EXPECT( 3 == run( fail, make_texts( args ), os ) ); } CASE( "Option --repeat=-1 (indefinite) is recognised [commandline]" ) { struct f { static void fail(env & $) { EXPECT( false ); }}; test fail[] = { test( "", f::fail ) }; std::ostringstream os; char const * args[] = { "--abort", "--repeat=-1" }; // currently no-tests are also repeated indefinitely hence the aborting a failing test: EXPECT( 1 == run( fail, make_texts( args ), os ) ); EXPECT( std::string::npos == os.str().find( "Error" ) ); } CASE( "Option --repeat={negative-number} is recognised as invalid [commandline]" ) { struct f { static void fail(env & $) { EXPECT( false ); }}; test fail[] = { test( "", f::fail ) }; std::ostringstream os; char const * args[] = { "--repeat=-3" }; EXPECT( 1 == run( fail, make_texts( args ), os ) ); EXPECT( std::string::npos != os.str().find( "Error" ) ); } CASE( "Option --version is recognised [commandline]" ) { std::ostringstream os; char const * args[] = { "--version" }; EXPECT( 0 == run( tests(), make_texts( args ), os ) ); } CASE( "Option -- ends option section [commandline]" ) { struct f { static void pass(env & $) { EXPECT( true ); }}; test pass[] = { test( "a-b", f::pass ) }; std::ostringstream os; char const * args1[] = { "-l", "--", "-" }; char const * args2[] = { "-c", "--", "-" }; EXPECT( 0 == run( pass, make_texts( args1 ), os ) ); EXPECT( 0 == run( pass, make_texts( args2 ), os ) ); EXPECT( std::string::npos != os.str().find( "a-b" ) ); EXPECT( std::string::npos != os.str().find( "1 " ) ); } int main( int argc, char * argv[] ) { return lest::run( specification, argc, argv ); } // cl -nologo -W3 -EHsc -I.. test_lest_cpp03.cpp && test_lest_cpp03 // cl -nologo -Wall -EHsc -I.. test_lest_cpp03.cpp && test_lest_cpp03 // g++ -Wall -Wextra -std=c++11 -I.. -o test_lest_cpp03.exe test_lest_cpp03.cpp && test_lest_cpp03 // g++ -Wall -Wextra -std=c++03 -I.. -o test_lest_cpp03.exe test_lest_cpp03.cpp && test_lest_cpp03
51370c3bf36c34fa6ea43a5a01f345da8a366aa4
2be0ed4aca1b3c3261fff481c99a2dc1519a51c0
/src/Control.h
d783e5510d81a73e5ceb1e20f9dee0fcf3f05ede
[]
no_license
JonathanPHumphreys/Group_Project_Bubble
372908884a7590df9b6645ce05906f219f4149ab
a4b7d7d78a9730ed6787f771f32066e381098363
refs/heads/master
2021-01-22T18:33:43.622452
2017-05-21T20:11:03
2017-05-21T20:11:03
85,091,701
0
0
null
null
null
null
UTF-8
C++
false
false
806
h
#pragma once #include "constants.h" class Control { public: Control(); Control(SDL_Texture* font_input); ~Control(); SDL_Texture* font; SDL_Texture* scoreTexture; SDL_Texture* numbersTexture; SDL_Rect scoreRect = { 5,5, 30, 30 }; SDL_Rect numberRect0 = { 95, 5, 21, 36 }; SDL_Rect numberRect1 = { 120, 5, 21, 36 };//+20 SDL_Color white = { 225,255,255,255 }; SDL_Color black = { 0,0,0,255 }; SDL_Color red = { 225,0,0,255 }; SDL_Color blue = { 0,255,0,255 }; SDL_Color green = { 0,0,255,255 }; char * numbers[30] = { "1","2","3","4","5","6","7","8","9","10", "11","12","13","14","15","16","17","18","19","20", "21","22","23","24","25","26","27","28","29","30"}; char * score[10] = { "0" , "1" , "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9" }; int score0 = 0; int score1 = 0; };
282e4eeff134ec70e6ab897e8866857dc10af55f
f636fcfcc7042b7234daec03bd0497a94a620cf2
/src/compiler/js-create-lowering.h
ac04542d662ecb23f3694a6b62e8ee65d97d0cc0
[ "BSD-3-Clause", "SunPro", "bzip2-1.0.6" ]
permissive
yingjianchen/v8
7106f74d96cbb9f20c5b0a68171373e6a4eaf7dc
c59c9c46b589deb2a41ba07cf87275921b8b2885
refs/heads/master
2020-04-01T09:17:20.611552
2018-10-15T05:20:38
2018-10-15T06:00:03
153,068,701
1
0
null
2018-10-15T07:12:51
2018-10-15T07:12:50
null
UTF-8
C++
false
false
5,585
h
// Copyright 2016 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_COMPILER_JS_CREATE_LOWERING_H_ #define V8_COMPILER_JS_CREATE_LOWERING_H_ #include "src/base/compiler-specific.h" #include "src/compiler/graph-reducer.h" #include "src/globals.h" namespace v8 { namespace internal { // Forward declarations. class AllocationSiteUsageContext; class Factory; class JSRegExp; namespace compiler { // Forward declarations. class CommonOperatorBuilder; class CompilationDependencies; class JSGraph; class JSOperatorBuilder; class MachineOperatorBuilder; class SimplifiedOperatorBuilder; class SlackTrackingPrediction; // Lowers JSCreate-level operators to fast (inline) allocations. class V8_EXPORT_PRIVATE JSCreateLowering final : public NON_EXPORTED_BASE(AdvancedReducer) { public: JSCreateLowering(Editor* editor, CompilationDependencies* dependencies, JSGraph* jsgraph, JSHeapBroker* js_heap_broker, Zone* zone) : AdvancedReducer(editor), dependencies_(dependencies), jsgraph_(jsgraph), js_heap_broker_(js_heap_broker), zone_(zone) {} ~JSCreateLowering() final = default; const char* reducer_name() const override { return "JSCreateLowering"; } Reduction Reduce(Node* node) final; private: Reduction ReduceJSCreate(Node* node); Reduction ReduceJSCreateArguments(Node* node); Reduction ReduceJSCreateArray(Node* node); Reduction ReduceJSCreateArrayIterator(Node* node); Reduction ReduceJSCreateAsyncFunctionObject(Node* node); Reduction ReduceJSCreateCollectionIterator(Node* node); Reduction ReduceJSCreateBoundFunction(Node* node); Reduction ReduceJSCreateClosure(Node* node); Reduction ReduceJSCreateIterResultObject(Node* node); Reduction ReduceJSCreateStringIterator(Node* node); Reduction ReduceJSCreateKeyValueArray(Node* node); Reduction ReduceJSCreatePromise(Node* node); Reduction ReduceJSCreateLiteralArrayOrObject(Node* node); Reduction ReduceJSCreateEmptyLiteralObject(Node* node); Reduction ReduceJSCreateEmptyLiteralArray(Node* node); Reduction ReduceJSCreateLiteralRegExp(Node* node); Reduction ReduceJSCreateFunctionContext(Node* node); Reduction ReduceJSCreateWithContext(Node* node); Reduction ReduceJSCreateCatchContext(Node* node); Reduction ReduceJSCreateBlockContext(Node* node); Reduction ReduceJSCreateGeneratorObject(Node* node); Reduction ReduceNewArray( Node* node, Node* length, MapRef initial_map, ElementsKind elements_kind, PretenureFlag pretenure, const SlackTrackingPrediction& slack_tracking_prediction); Reduction ReduceNewArray( Node* node, Node* length, int capacity, MapRef initial_map, ElementsKind elements_kind, PretenureFlag pretenure, const SlackTrackingPrediction& slack_tracking_prediction); Reduction ReduceNewArray( Node* node, std::vector<Node*> values, MapRef initial_map, ElementsKind elements_kind, PretenureFlag pretenure, const SlackTrackingPrediction& slack_tracking_prediction); Reduction ReduceJSCreateObject(Node* node); Node* AllocateArguments(Node* effect, Node* control, Node* frame_state); Node* AllocateRestArguments(Node* effect, Node* control, Node* frame_state, int start_index); Node* AllocateAliasedArguments(Node* effect, Node* control, Node* frame_state, Node* context, const SharedFunctionInfoRef& shared, bool* has_aliased_arguments); Node* AllocateAliasedArguments(Node* effect, Node* control, Node* context, Node* arguments_frame, Node* arguments_length, const SharedFunctionInfoRef& shared, bool* has_aliased_arguments); Node* AllocateElements(Node* effect, Node* control, ElementsKind elements_kind, int capacity, PretenureFlag pretenure); Node* AllocateElements(Node* effect, Node* control, ElementsKind elements_kind, Node* capacity_and_length); Node* AllocateElements(Node* effect, Node* control, ElementsKind elements_kind, std::vector<Node*> const& values, PretenureFlag pretenure); Node* AllocateFastLiteral(Node* effect, Node* control, JSObjectRef boilerplate, PretenureFlag pretenure); Node* AllocateFastLiteralElements(Node* effect, Node* control, JSObjectRef boilerplate, PretenureFlag pretenure); Node* AllocateLiteralRegExp(Node* effect, Node* control, JSRegExpRef boilerplate); Factory* factory() const; Graph* graph() const; JSGraph* jsgraph() const { return jsgraph_; } Isolate* isolate() const; NativeContextRef native_context() const; CommonOperatorBuilder* common() const; SimplifiedOperatorBuilder* simplified() const; CompilationDependencies* dependencies() const { return dependencies_; } JSHeapBroker* js_heap_broker() const { return js_heap_broker_; } Zone* zone() const { return zone_; } CompilationDependencies* const dependencies_; JSGraph* const jsgraph_; JSHeapBroker* const js_heap_broker_; Zone* const zone_; }; } // namespace compiler } // namespace internal } // namespace v8 #endif // V8_COMPILER_JS_CREATE_LOWERING_H_
e877d8d064995b65e5f0e1ed30a51bee12c6101d
6267c3e316ddd8a5bcd5b02be79dfb106d860573
/src/FitnessAnalyzer.cpp
14876ab54dd4cc28778d1e068e10794a65a7358d
[ "MIT" ]
permissive
ngetahun/Clusterer
2e608c65fd124645df51e5e29c1aebe9d99ebffd
8e3994af02977a79d2f1f36a23aebac5c2485be2
refs/heads/master
2020-05-25T08:17:25.512327
2015-10-03T16:50:52
2015-10-03T16:50:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
609
cpp
/** * @file FitnessAnalyzer.hpp * @brief FitnessAnalyzer implementation. */ // standard headers #include <stdint.h> // external headers // internal headers #include "../include/FitnessAnalyzer.hpp" namespace clusterer { namespace backend { double FitnessAnalyzer::analyze(const ClusterEncoding* clusteringSolution, const AbstractGraph* graph) { auto mqValue = this->mqAnalyzer.analyze(clusteringSolution, graph); auto performanceValue = this->performanceAnalyzer.analyze(clusteringSolution, graph); return (1 + mqValue) / 2 + performanceValue; } FitnessAnalyzer::~FitnessAnalyzer() { } } }
5c389a5d89dde3499d0850077cfd33ac5bb6aaeb
5de42c4e14a7ddbc284a742c66cb01b230ba43ce
/codeforces/1303/G.cpp
2fb886c519bec354731c6090302b3cd840edc890
[]
no_license
NhatMinh0208/CP-Archive
42d6cc9b1d2d6b8c85e637b8a88a6852a398cc23
f95784d53708003e7ba74cbe4f2c7a888d29eac4
refs/heads/master
2023-05-09T15:50:34.344385
2021-05-04T14:25:00
2021-05-19T16:10:11
323,779,542
0
0
null
null
null
null
UTF-8
C++
false
false
4,907
cpp
/* A Submission by $%U%$ at time: $%Y%$-$%M%$-$%D%$ $%h%$:$%m%$:$%s%$ */ #include <bits/stdc++.h> using namespace std; #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; #define rep(i,n) for(int64_t i=0;i < (int64_t)(n);i++) #pragma comment(linker, "/stack:200000000") #pragma GCC optimize("O3,unroll-loops") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") #define FILE_IN "graph.inp" #define FILE_OUT "graph.out" #define ofile freopen(FILE_IN,"r",stdin);freopen(FILE_OUT,"w",stdout) #define fio ios::sync_with_stdio(0);cin.tie(0);cout.tie(0) #define nfio cin.tie(0);cout.tie(0) #define max(x,y) (((x)>(y))?(x):(y)) #define min(x,y) (((x)<(y))?(x):(y)) #define ord(a,b,c) ((a>=b)and(b>=c)) #define MOD (ll(1000000007)) #define MAX 300001 #define mag 320 #define p1 first #define p2 second.first #define p3 second.second #define fi first #define se second #define pow2(x) (ll(1)<<x) #define pii pair<int,int> #define piii pair<int,pii> #define For(i,__,___) for(int i=__;i<=___;i++) #define Rep(i,__,___) for(int i=__;i>=___;i--) #define ordered_set tree<long long,null_type,less<long long>,rb_tree_tag,tree_order_statistics_node_update> #define endl "\n" #define bi BigInt #define pi 3.1415926535897 typedef long long ll; //------------xúc xích normie tám muoi tám phan tram não----------// const int N = 2e5; int n; vector<int>g[N]; int v[N]; const ll is_query = 1ll << 62; struct line{ ll k, b; mutable function<const line *()> succ; bool operator<(const line & a) const { if (a.b != is_query) return k < a.k; auto y = succ(); if (!y) return 0; return a.k * k + b < a.k * y->k + y->b; } }; struct HullDynamic:public multiset<line> { bool bad(iterator y) { auto z = next(y); if (y == begin()) { if (z == end()) return 0; return z->k >= y->k && z->b >= y->b; } auto x = prev(y); if (z == end()) { return x->k == y->k && x->b == y->b; } return (x->b - z->b) * (y->k - x->k) <= (x->b - y->b) * (z ->k - x->k); } void insert_line(ll k, ll b) { auto y = insert({k, b}); y -> succ = [=]() {return next(y) == end()? 0: &*next(y);}; if (bad(y)) { erase(y); return; } while (next(y) != end() && bad(next(y))) erase(next(y)); while (y != begin() && bad(prev(y))) erase(prev(y)); } ll eval(ll x) { auto y = *lower_bound((line){x, is_query}); return y.k * x + y.b; } }H; vector<int>d, d2; bool bz[N]; int sz[N], mxsz[N]; int len[N]; ll res = 0; ll w[N], all[N]; int root(int x) { function<void(int, int)>dfs = [&](int x, int fa){ sz[x] = 1; mxsz[x] = 0; d.push_back(x); for (auto u:g[x]) if (u != fa && !bz[u]) dfs(u, x), sz[x] += sz[u], mxsz[x] = max(mxsz[x], sz[u]); }; d.clear(); dfs(x, 0); for (auto u:d) if (max(mxsz[u], (int)d.size() - sz[u]) < max(mxsz[x], (int)d.size() - sz[x])) x = u; return x; } void divide(int x) { x = root(x); function<void(int, int)> dfs = [&] (int x, int fa) { d2.push_back(x); for (auto u:g[x]) if (u != fa && !bz[u]) { len[u] = len[x] + 1; w[u] = w[x] + (all[u] = all[x] + v[u]); dfs(u, x); } }; function<void(int, int)> dfs1 = [&] (int x, int fa) { for (auto u:g[x]) if (u != fa && !bz[u]) { len[u] = len[x] + 1; w[u] = w[x] + 1ll * len[u] * v[u]; all[u] = all[x] + v[u]; dfs1(u, x); } }; function<void(int)> work = [&] (int x) { H.clear(); for (auto u:g[x]) if (!bz[u]) { d2.clear(); len[u] = 2, all[u] = v[u] + v[x]; w[u] = all[u] + v[x]; dfs(u, x); for (auto v:d2) { if (!H.empty()) res = max(res, H.eval(len[v]) + w[v]); res = max(res, w[v]); } len[u] = 1, w[u] = all[u] = v[u]; dfs1(u, x); ll tmp = v[x]; for (auto v:d2) { H.insert_line(all[v], w[v]); res = max(res, w[v] + all[v] + tmp); } } }; work(x); reverse(g[x].begin(), g[x].end()); work(x); bz[x] = 1; for (auto u:g[x]) if (!bz[u]) divide(u); } int main() { fio; cin>>n; for (int i = 1; i < n; i ++) { int x, y; cin>>x>>y; g[x].push_back(y); g[y].push_back(x); } for (int i= 1; i <= n; i ++) cin>>v[i]; divide(1); cout<<res; }
384db1b9fbd9229c31396160b06e78f7ace85c93
d6dc96d8afc5bc16582bba83b1cb734938ce859e
/C++/Student Register Migration Tool/Course.h
98da05e775fcbc16fc1290106bd8a9e930499c49
[ "MIT" ]
permissive
VasilisPat/UniversityProjects
b3d54e079b2893da0516d8cec1ca36dc7cf79390
72fc8ca026bb31c24c8f63215e4a0964f750ffc2
refs/heads/main
2023-06-26T19:31:57.019597
2023-06-08T17:58:08
2023-06-08T17:58:08
306,084,254
0
0
null
null
null
null
UTF-8
C++
false
false
780
h
#pragma once #include <iostream> using namespace std; class Course{ private: char* newCode=nullptr; char* newName=nullptr; char* oldCode=nullptr; char* oldName=nullptr; public: //Constructors and Deconstructor Declaration Course(); Course(char*, char*, char*, char*); Course(const Course&); ~Course(); //Class Methods Declaration friend ostream& operator<<(ostream&, Course&); //Setters Declaration void setNewCode(char*); void setNewName(char*); void setOldCode(char*); void setOldName(char*); //Getters Declaration char* getNewCode(); char* getNewName(); char* getOldCode(); char* getOldName(); };
a3ad4c33c21d8f57f4c492a9d4dbc16209408e0f
ab25adae8bb69f9a4705cf71dca13dc26ae39429
/client/Classes/AppDelegate.h
945e1c6892ec689cbb1d0bf05226cf9ca7dd4618
[]
no_license
yangyong3108/project-001
db12600aa1bfaccbdf9d83514e269b09e6fd496d
6f1dfa135a120bd3330d36b2f4ecad1bd9b4e816
refs/heads/master
2021-01-10T21:58:14.892479
2015-08-28T15:33:04
2015-08-28T15:33:04
40,808,142
0
0
null
null
null
null
UTF-8
C++
false
false
1,064
h
#ifndef _APP_DELEGATE_H_ #define _APP_DELEGATE_H_ #include "cocos2d.h" class NetMessageManager; /** @brief The cocos2d Application. The reason for implement as private inheritance is to hide some interface call by Director. */ class AppDelegate : private cocos2d::Application { public: AppDelegate(); virtual ~AppDelegate(); virtual void initGLContextAttrs(); /** @brief Implement Director and Scene init code here. @return true Initialize success, app continue. @return false Initialize failed, app terminate. */ virtual bool applicationDidFinishLaunching(); /** @brief The function be called when the application enter background @param the pointer of the application */ virtual void applicationDidEnterBackground(); /** @brief The function be called when the application enter foreground @param the pointer of the application */ virtual void applicationWillEnterForeground(); private: NetMessageManager* m_pNetMessageManager; }; #endif // _APP_DELEGATE_H_
8e5641450ed6279e2e3303d2d23f888a2e5b199c
4119ea6909154ac505d2a5cfbdb043b0e22afc01
/10. Floyd Warshall/3 [uva] 10171 - Meeting Prof. Miguel (Solution 2).cpp
5dc5bbe7cf70dbf191f699b65af218a78079855a
[]
no_license
mojtabafazeli/competitive-programming
ec1ac188f3e9fad9be3f3ee2b63233dca26a7aca
0d134d140daf9bde6ee713f746a532aeda68a687
refs/heads/master
2022-11-23T13:01:09.834233
2019-07-13T10:02:39
2019-07-13T10:02:39
298,296,962
1
0
null
2020-09-24T14:02:42
2020-09-24T14:02:41
null
UTF-8
C++
false
false
2,703
cpp
// Problem: 10171 - Meeting Prof. Miguel... // Link: https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=1112 // Author: Mai Thanh Hiep // Complexity: O(MAX^3), MAX = 26 => O(26^3) #include <iostream> #include <vector> #include <limits.h> #include <queue> #define MAX 'Z'-'A'+1 #define INF INT_MAX using namespace std; bool floydWarshall(int (*dist)[MAX], int V) { for (int k = 0; k < V; k++) { for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (dist[i][k] != INF && dist[k][j] != INF && dist[i][j] > dist[i][k] + dist[k][j]) { dist[i][j] = dist[i][k] + dist[k][j]; } } } } // check negative cycle for (int i = 0; i < V; i++) { if (dist[i][i] < 0) return true; } return false; } int main() { int n; char age, direction, city1, city2; int energy; char src, dst; int distY[MAX][MAX]; int distM[MAX][MAX]; while (true) { cin >> n; if (n == 0) break; for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) { if (i == j) { distM[i][j] = distY[i][j] = 0; } else { distM[i][j] = distY[i][j] = INF; } } } while (n--) { cin >> age >> direction >> city1 >> city2 >> energy; city1 -= 'A', city2 -= 'A'; if (age == 'Y') { distY[city1][city2] = min(distY[city1][city2], energy); if (direction == 'B') { distY[city2][city1] = min(distY[city2][city1], energy); } } else { distM[city1][city2] = min(distM[city1][city2], energy); if (direction == 'B') { distM[city2][city1] = min(distM[city2][city1], energy); } } } cin >> src >> dst; src -= 'A', dst -= 'A'; floydWarshall(distY, MAX); // O(MAX^3) = O(26^3) floydWarshall(distM, MAX); // O(MAX^3) = O(26^3) int minDist = INF; for (int i = 0; i < MAX; i++) { // O(MAX) if (distY[src][i] != INF && distM[dst][i] != INF && minDist > distY[src][i] + distM[dst][i]) { minDist = distY[src][i] + distM[dst][i]; } } if (minDist != INF) { cout << minDist; for (int i = 0; i < MAX; i++) { if (distY[src][i] != INF && distM[dst][i] != INF && minDist == distY[src][i] + distM[dst][i]) { cout << " " << char(i + 'A'); } } cout << endl; } else { cout << "You will never meet." << endl; } } return 0; }
ce990e2700a85a7b55d86752ea5d3d411d85b948
f7591bda8f45d00348b23fca01823fc51201835f
/swap.cpp
6696b2a7248724f5e23502ecc6b4513272dce674
[]
no_license
ImjustWritingCode/Gaussian_Elimination
0148c5dac71827b30c89962b1567e1c9e3f91634
c7f50f6f45098d92c3c01f28dd990bfee0deb5c0
refs/heads/master
2021-01-19T21:13:32.793360
2017-05-16T09:45:39
2017-05-16T09:45:39
88,018,904
0
1
null
2017-04-13T03:58:47
2017-04-12T06:45:05
C++
UTF-8
C++
false
false
537
cpp
#include<iostream> using namespace std; int main(void) { int mat[4][3]={0}; int i,j,k; cout<<"Please insert your matrix? "; for(i=0;i<3;i++) { for(j=0;j<4;j++) cin>>mat[j][i]; } for(i=2;i>0;i--) { for(j=0;j<i;j++) { if(mat[0][j]>mat[0][j+1]) { for(k=0;k<4;k++) swap(mat[k][j],mat[k][j+1]); } } } for(i=0;i<3;i++) { for(j=0;j<4;j++) cout<<mat[j][i]<<'\t'; cout<<endl; } return 0; }
92f0829ab376a62ca4b984c60dddf01a9a923801
bd1db27d708b1dbc6dffe63231294168396c7fdf
/CppPractice/SplitTest/Split.h
cd5f1a8dc2fda9c405c837e1b0b2648bb5a4aa16
[]
no_license
abigpotostew/CppPractice
da8202292b4c6460536cae4e889090c7a8403b83
31c8b908e5439a5e2ea68ddfe695f8098d49f1a2
refs/heads/master
2016-09-02T20:57:55.620860
2013-12-18T00:49:08
2013-12-18T00:49:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
466
h
// // Split.h // InterviewPractice // // Created by Stewart Bracken on 12/5/13. // Copyright (c) 2013 Stewart Bracken. All rights reserved. // #ifndef InterviewPractice_Split_h #define InterviewPractice_Split_h #include <vector> #include <string> using namespace std; //only supports single delim character at this point vector<string> split(const string& toSplit, const char& delim); vector<string> split2(const string& toSplit, const char& delim); #endif
440819fbae6157771bdea66a729a4cb9b55bd845
4c8c13eb891b514037d3adb1be7f28af53144e85
/mjolnir/input/read_observer.cpp
c216b0e0b7105d5cf2a6ee91b23857eafb9f920e
[ "MIT" ]
permissive
Mjolnir-MD/Mjolnir
f07b501cf60d6d1ca7cdeafc400749423dcde142
20dbdea5529c24a49b71e8876ac1651efc512445
refs/heads/master
2023-02-03T22:59:33.972243
2022-04-12T10:23:04
2022-04-12T10:23:04
74,558,351
14
9
MIT
2023-01-27T04:46:54
2016-11-23T08:53:31
C++
UTF-8
C++
false
false
1,720
cpp
#include <mjolnir/input/read_observer.hpp> #ifndef MJOLNIR_SEPARATE_BUILD #error "MJOLNIR_SEPARATE_BUILD flag is required" #endif namespace mjolnir { template void add_observer<SimulatorTraits<double, UnlimitedBoundary> >(ObserverContainer<SimulatorTraits<double, UnlimitedBoundary> >& observers, const toml::value& format, const std::string& file_prefix); template void add_observer<SimulatorTraits<float, UnlimitedBoundary> >(ObserverContainer<SimulatorTraits<float, UnlimitedBoundary> >& observers, const toml::value& format, const std::string& file_prefix); template void add_observer<SimulatorTraits<double, CuboidalPeriodicBoundary>>(ObserverContainer<SimulatorTraits<double, CuboidalPeriodicBoundary>>& observers, const toml::value& format, const std::string& file_prefix); template void add_observer<SimulatorTraits<float, CuboidalPeriodicBoundary>>(ObserverContainer<SimulatorTraits<float, CuboidalPeriodicBoundary>>& observers, const toml::value& format, const std::string& file_prefix); template ObserverContainer<SimulatorTraits<double, UnlimitedBoundary> > read_observer<SimulatorTraits<double, UnlimitedBoundary> >(const toml::value& root); template ObserverContainer<SimulatorTraits<float, UnlimitedBoundary> > read_observer<SimulatorTraits<float, UnlimitedBoundary> >(const toml::value& root); template ObserverContainer<SimulatorTraits<double, CuboidalPeriodicBoundary>> read_observer<SimulatorTraits<double, CuboidalPeriodicBoundary>>(const toml::value& root); template ObserverContainer<SimulatorTraits<float, CuboidalPeriodicBoundary>> read_observer<SimulatorTraits<float, CuboidalPeriodicBoundary>>(const toml::value& root); } // mjolnir
ef8a7b555d62e90aa0f94069c3a8236d4ffa0289
866558f94b9b0d841e8ef68715273a8671511a84
/tests/test_data/str_gb2312.inc
8ad41685851920b6efd33840071200bc45b4905e
[ "MIT" ]
permissive
ximenpo/simple-cpp
66a1de295fafaf911051889fbf21fc3f368eb9ac
0779674dbea5cd8f4081140cad90edeaa31da7c8
refs/heads/master
2021-01-19T01:02:12.640957
2016-11-15T06:30:28
2016-11-15T06:30:28
32,370,140
2
0
null
null
null
null
MacCentralEurope
C++
false
false
62
inc
std::string str = "XiMenPo «SimpleĶń“Ű“Ž√ݰ£";
f336b29caf9ebdd77773eea1b27d70aae1f0ed51
a9063108a677217c489bf45c8b2734981f8138a4
/XLUnityiOSDemo/unityiOSDemo/Classes/Native/Il2CppMetadataRegistration.cpp
1c0e2159a38d29655922f53848ca1c7b7b586d07
[]
no_license
kongfanwu/iOSMergeUnity3D
afe5ad13ff4317c6169106ea6784283d256d0fec
dd353107caa059a5054573c877466e1aed062ab7
refs/heads/master
2021-01-02T09:16:47.323708
2018-06-01T09:34:44
2018-06-01T09:34:44
99,179,503
1
0
null
null
null
null
UTF-8
C++
false
false
1,099
cpp
#include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <cstring> #include <string.h> #include <stdio.h> #include <cmath> #include <limits> #include <assert.h> #include "class-internals.h" #include "codegen/il2cpp-codegen.h" extern Il2CppGenericClass* const s_Il2CppGenericTypes[]; extern const Il2CppGenericInst* const g_Il2CppGenericInstTable[]; extern const Il2CppGenericMethodFunctionsDefinitions s_Il2CppGenericMethodFunctions[]; extern const Il2CppType* const g_Il2CppTypeTable[]; extern const Il2CppMethodSpec g_Il2CppMethodSpecTable[]; extern const int32_t* g_FieldOffsetTable[]; extern const Il2CppTypeDefinitionSizes* g_Il2CppTypeDefinitionSizesTable[]; extern void** const g_MetadataUsages[]; extern const Il2CppMetadataRegistration g_MetadataRegistration = { 1968, s_Il2CppGenericTypes, 532, g_Il2CppGenericInstTable, 4503, s_Il2CppGenericMethodFunctions, 7385, g_Il2CppTypeTable, 4801, g_Il2CppMethodSpecTable, 1700, g_FieldOffsetTable, 1700, g_Il2CppTypeDefinitionSizesTable, 6523, g_MetadataUsages, };
2c33fada7a3d334f39e929826f1c3ceb96198d4d
297d4a178916bbed73f8b19f7e106bb223b8ea8b
/q5122113, Ben Shoesmith Spice My Sponza/SpinceMySponzaICA/SpiceMySponza/source/MyController.cpp
7415218ab1efac470c0805145b1164f4c22dc260
[]
no_license
benshoesmith/C-2nd-Year-Graphics-Programming
fcf8869f6a00dc82d921cfadf7a26b7dfd597153
0e9fe41070d33898a57ce6fa62d424cca6334f47
refs/heads/master
2020-05-04T08:49:25.395677
2019-04-02T10:29:31
2019-04-02T10:29:31
179,054,583
0
0
null
null
null
null
UTF-8
C++
false
false
5,364
cpp
#include "MyController.hpp" #include "MyView.hpp" #include <sponza/sponza.hpp> #include <tygra/Window.hpp> #include <glm/glm.hpp> #include <iostream> MyController::MyController() { scene_ = new sponza::Context(); view_ = new MyView(); view_->setScene(scene_); } MyController::~MyController() { delete view_; delete scene_; } void MyController::windowControlWillStart(tygra::Window * window) { window->setView(view_); window->setTitle("3D Graphics Programming :: SpiceMySponza"); } void MyController::windowControlDidStop(tygra::Window * window) { window->setView(nullptr); } void MyController::windowControlViewWillRender(tygra::Window * window) { scene_->update(); if (camera_turn_mode_) { scene_->getCamera().setRotationalVelocity(sponza::Vector2(0, 0)); } } void MyController::windowControlMouseMoved(tygra::Window * window, int x, int y) { static int prev_x = x; static int prev_y = y; if (camera_turn_mode_) { int dx = x - prev_x; int dy = y - prev_y; const float mouse_speed = 0.6f; scene_->getCamera().setRotationalVelocity( sponza::Vector2(-dx * mouse_speed, -dy * mouse_speed)); } prev_x = x; prev_y = y; } void MyController::windowControlMouseButtonChanged(tygra::Window * window, int button_index, bool down) { if (button_index == tygra::kWindowMouseButtonLeft) { camera_turn_mode_ = down; } } void MyController::windowControlMouseWheelMoved(tygra::Window * window, int position) { } void MyController::windowControlKeyboardChanged(tygra::Window * window, int key_index, bool down) { switch (key_index) { case tygra::kWindowKeyLeft: case 'A': camera_move_speed_[0] = down ? 1.f : 0.f; break; case tygra::kWindowKeyRight: case 'D': camera_move_speed_[1] = down ? 1.f : 0.f; break; case tygra::kWindowKeyUp: case 'W': camera_move_speed_[2] = down ? 1.f : 0.f; break; case tygra::kWindowKeyDown: case 'S': camera_move_speed_[3] = down ? 1.f : 0.f; break; } updateCameraTranslation(); if (!down) return; switch (key_index) { // TODO: put usual keypress responses here } } void MyController::windowControlGamepadAxisMoved(tygra::Window * window, int gamepad_index, int axis_index, float pos) { const float deadzone = 0.2f; const float rotate_speed = 3.f; switch (axis_index) { case tygra::kWindowGamepadAxisLeftThumbX: if (pos < -deadzone) { camera_move_speed_[0] = -pos; camera_move_speed_[1] = 0.f; } else if (pos > deadzone) { camera_move_speed_[0] = 0.f; camera_move_speed_[1] = pos; } else { camera_move_speed_[0] = 0.f; camera_move_speed_[1] = 0.f; } break; case tygra::kWindowGamepadAxisLeftThumbY: if (pos < -deadzone) { camera_move_speed_[3] = -pos; camera_move_speed_[2] = 0.f; } else if (pos > deadzone) { camera_move_speed_[3] = 0.f; camera_move_speed_[2] = pos; } else { camera_move_speed_[3] = 0.f; camera_move_speed_[2] = 0.f; } break; case tygra::kWindowGamepadAxisRightThumbX: if (pos < -deadzone || pos > deadzone) { camera_rotate_speed_[0] = -pos; } else { camera_rotate_speed_[0] = 0.f; } scene_->getCamera().setRotationalVelocity( sponza::Vector2(camera_rotate_speed_[0] * rotate_speed, camera_rotate_speed_[1] * rotate_speed)); break; case tygra::kWindowGamepadAxisRightThumbY: if (pos < -deadzone || pos > deadzone) { camera_rotate_speed_[1] = pos; } else { camera_rotate_speed_[1] = 0.f; } scene_->getCamera().setRotationalVelocity( sponza::Vector2(camera_rotate_speed_[0] * rotate_speed, camera_rotate_speed_[1] * rotate_speed)); break; } updateCameraTranslation(); } void MyController::windowControlGamepadButtonChanged(tygra::Window * window, int gamepad_index, int button_index, bool down) { } void MyController::updateCameraTranslation() { const float key_speed = 100.f; const float sideward_speed = -key_speed * camera_move_speed_[0] + key_speed * camera_move_speed_[1]; const float forward_speed = key_speed * camera_move_speed_[2] - key_speed * camera_move_speed_[3]; scene_->getCamera().setLinearVelocity( sponza::Vector3(sideward_speed, 0, forward_speed)); }
419afea81ffcdb5fa3f1dd09905ced9cb7e0507b
2fd0fae47b85ce8661edaf2ea4fab2377a69eaf8
/archiv/queue.h
16975eb5f6892d24f6615393cf1ebc5c6afdd793
[]
no_license
Seakuh/OOP
1277bb32a7bb5db09a2e6992ac27fa63efc9e6b0
aa9fe6e88b92126223a4b0c713bbf34d883e93ea
refs/heads/master
2020-12-13T04:06:35.957386
2020-01-16T11:49:19
2020-01-16T11:49:19
234,308,392
0
0
null
null
null
null
UTF-8
C++
false
false
413
h
#ifndef queue #define queue_h class queue { public: int arr[50]; int size = 0; int *head = &arr[0]; //Der Kopf zeigt auf das Array an der 0. Stelle int *tail = &arr[0]; //Das ende ist am Anfang auch 0. Stelle da arr leer ist int length = 0; int tIndex = 0; int hIndex = 0; void put(int v); int get(); bool isEmpty(); int getanStelle(int); int getSize(); }; #endif
97b3713cd50713bc5e9074d364765ad38e4c93c4
6f1d14bf99574e0d2be6b91f6e27151f5a7f960d
/include/input/InputTransport.h
a7ef60fc227d455091e335de9aa718bdfddd0950
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
jianglu/framework_native
60cd76c9bb910b7a254869efaed1a7bbc18e3820
5612e28118e7158e664beed7e970d60e56e20c2a
refs/heads/master
2021-01-11T07:11:54.739596
2016-10-31T18:07:13
2016-10-31T18:07:13
72,464,372
3
1
null
null
null
null
UTF-8
C++
false
false
16,409
h
/* * Copyright (C) 2014 MediaTek Inc. * Modification based on code covered by the mentioned copyright * and/or permission notice(s). */ /* * Copyright (C) 2010 The Android Open Source Project * * 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 _LIBINPUT_INPUT_TRANSPORT_H #define _LIBINPUT_INPUT_TRANSPORT_H /** * Native input transport. * * The InputChannel provides a mechanism for exchanging InputMessage structures across processes. * * The InputPublisher and InputConsumer each handle one end-point of an input channel. * The InputPublisher is used by the input dispatcher to send events to the application. * The InputConsumer is used by the application to receive events from the input dispatcher. */ #include <input/Input.h> #include <utils/Errors.h> #include <utils/Timers.h> #include <utils/RefBase.h> #include <utils/String8.h> #include <utils/Vector.h> #include <utils/BitSet.h> namespace android { /* * Intermediate representation used to send input events and related signals. * * Note that this structure is used for IPCs so its layout must be identical * on 64 and 32 bit processes. This is tested in StructLayout_test.cpp. */ struct InputMessage { enum { TYPE_KEY = 1, TYPE_MOTION = 2, TYPE_FINISHED = 3, }; struct Header { uint32_t type; // We don't need this field in order to align the body below but we // leave it here because InputMessage::size() and other functions // compute the size of this structure as sizeof(Header) + sizeof(Body). uint32_t padding; } header; // Body *must* be 8 byte aligned. union Body { struct Key { uint32_t seq; nsecs_t eventTime __attribute__((aligned(8))); int32_t deviceId; int32_t source; int32_t action; int32_t flags; int32_t keyCode; int32_t scanCode; int32_t metaState; int32_t repeatCount; nsecs_t downTime __attribute__((aligned(8))); inline size_t size() const { return sizeof(Key); } } key; struct Motion { uint32_t seq; nsecs_t eventTime __attribute__((aligned(8))); int32_t deviceId; int32_t source; int32_t action; int32_t flags; int32_t metaState; int32_t buttonState; int32_t edgeFlags; nsecs_t downTime __attribute__((aligned(8))); float xOffset; float yOffset; float xPrecision; float yPrecision; uint32_t pointerCount; // Note that PointerCoords requires 8 byte alignment. struct Pointer{ PointerProperties properties; PointerCoords coords; } pointers[MAX_POINTERS]; int32_t getActionId() const { uint32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; return pointers[index].properties.id; } inline size_t size() const { return sizeof(Motion) - sizeof(Pointer) * MAX_POINTERS + sizeof(Pointer) * pointerCount; } } motion; struct Finished { uint32_t seq; bool handled; inline size_t size() const { return sizeof(Finished); } } finished; } __attribute__((aligned(8))) body; bool isValid(size_t actualSize) const; size_t size() const; }; /* * An input channel consists of a local unix domain socket used to send and receive * input messages across processes. Each channel has a descriptive name for debugging purposes. * * Each endpoint has its own InputChannel object that specifies its file descriptor. * * The input channel is closed when all references to it are released. */ class InputChannel : public RefBase { protected: virtual ~InputChannel(); public: InputChannel(const String8& name, int fd); /* Creates a pair of input channels. * * Returns OK on success. */ static status_t openInputChannelPair(const String8& name, sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel); inline String8 getName() const { return mName; } inline int getFd() const { return mFd; } /* Sends a message to the other endpoint. * * If the channel is full then the message is guaranteed not to have been sent at all. * Try again after the consumer has sent a finished signal indicating that it has * consumed some of the pending messages from the channel. * * Returns OK on success. * Returns WOULD_BLOCK if the channel is full. * Returns DEAD_OBJECT if the channel's peer has been closed. * Other errors probably indicate that the channel is broken. */ status_t sendMessage(const InputMessage* msg); /* Receives a message sent by the other endpoint. * * If there is no message present, try again after poll() indicates that the fd * is readable. * * Returns OK on success. * Returns WOULD_BLOCK if there is no message present. * Returns DEAD_OBJECT if the channel's peer has been closed. * Other errors probably indicate that the channel is broken. */ status_t receiveMessage(InputMessage* msg); /* Returns a new object that has a duplicate of this channel's fd. */ sp<InputChannel> dup() const; /// M: Switch log by command static void switchInputLog(bool enable); private: String8 mName; int mFd; }; /* * Publishes input events to an input channel. */ class InputPublisher { public: /* Creates a publisher associated with an input channel. */ explicit InputPublisher(const sp<InputChannel>& channel); /* Destroys the publisher and releases its input channel. */ ~InputPublisher(); /* Gets the underlying input channel. */ inline sp<InputChannel> getChannel() { return mChannel; } /* Publishes a key event to the input channel. * * Returns OK on success. * Returns WOULD_BLOCK if the channel is full. * Returns DEAD_OBJECT if the channel's peer has been closed. * Returns BAD_VALUE if seq is 0. * Other errors probably indicate that the channel is broken. */ status_t publishKeyEvent( uint32_t seq, int32_t deviceId, int32_t source, int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState, int32_t repeatCount, nsecs_t downTime, nsecs_t eventTime); /* Publishes a motion event to the input channel. * * Returns OK on success. * Returns WOULD_BLOCK if the channel is full. * Returns DEAD_OBJECT if the channel's peer has been closed. * Returns BAD_VALUE if seq is 0 or if pointerCount is less than 1 or greater than MAX_POINTERS. * Other errors probably indicate that the channel is broken. */ status_t publishMotionEvent( uint32_t seq, int32_t deviceId, int32_t source, int32_t action, int32_t flags, int32_t edgeFlags, int32_t metaState, int32_t buttonState, float xOffset, float yOffset, float xPrecision, float yPrecision, nsecs_t downTime, nsecs_t eventTime, uint32_t pointerCount, const PointerProperties* pointerProperties, const PointerCoords* pointerCoords); /* Receives the finished signal from the consumer in reply to the original dispatch signal. * If a signal was received, returns the message sequence number, * and whether the consumer handled the message. * * The returned sequence number is never 0 unless the operation failed. * * Returns OK on success. * Returns WOULD_BLOCK if there is no signal present. * Returns DEAD_OBJECT if the channel's peer has been closed. * Other errors probably indicate that the channel is broken. */ status_t receiveFinishedSignal(uint32_t* outSeq, bool* outHandled); private: sp<InputChannel> mChannel; }; /* * Consumes input events from an input channel. */ class InputConsumer { public: /* Creates a consumer associated with an input channel. */ explicit InputConsumer(const sp<InputChannel>& channel); /* Destroys the consumer and releases its input channel. */ ~InputConsumer(); /* Gets the underlying input channel. */ inline sp<InputChannel> getChannel() { return mChannel; } /* Consumes an input event from the input channel and copies its contents into * an InputEvent object created using the specified factory. * * Tries to combine a series of move events into larger batches whenever possible. * * If consumeBatches is false, then defers consuming pending batched events if it * is possible for additional samples to be added to them later. Call hasPendingBatch() * to determine whether a pending batch is available to be consumed. * * If consumeBatches is true, then events are still batched but they are consumed * immediately as soon as the input channel is exhausted. * * The frameTime parameter specifies the time when the current display frame started * rendering in the CLOCK_MONOTONIC time base, or -1 if unknown. * * The returned sequence number is never 0 unless the operation failed. * * Returns OK on success. * Returns WOULD_BLOCK if there is no event present. * Returns DEAD_OBJECT if the channel's peer has been closed. * Returns NO_MEMORY if the event could not be created. * Other errors probably indicate that the channel is broken. */ status_t consume(InputEventFactoryInterface* factory, bool consumeBatches, nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent); /* Sends a finished signal to the publisher to inform it that the message * with the specified sequence number has finished being process and whether * the message was handled by the consumer. * * Returns OK on success. * Returns BAD_VALUE if seq is 0. * Other errors probably indicate that the channel is broken. */ status_t sendFinishedSignal(uint32_t seq, bool handled); /* Returns true if there is a deferred event waiting. * * Should be called after calling consume() to determine whether the consumer * has a deferred event to be processed. Deferred events are somewhat special in * that they have already been removed from the input channel. If the input channel * becomes empty, the client may need to do extra work to ensure that it processes * the deferred event despite the fact that the input channel's file descriptor * is not readable. * * One option is simply to call consume() in a loop until it returns WOULD_BLOCK. * This guarantees that all deferred events will be processed. * * Alternately, the caller can call hasDeferredEvent() to determine whether there is * a deferred event waiting and then ensure that its event loop wakes up at least * one more time to consume the deferred event. */ bool hasDeferredEvent() const; /* Returns true if there is a pending batch. * * Should be called after calling consume() with consumeBatches == false to determine * whether consume() should be called again later on with consumeBatches == true. */ bool hasPendingBatch() const; private: // True if touch resampling is enabled. const bool mResampleTouch; // The input channel. sp<InputChannel> mChannel; // The current input message. InputMessage mMsg; // True if mMsg contains a valid input message that was deferred from the previous // call to consume and that still needs to be handled. bool mMsgDeferred; // Batched motion events per device and source. struct Batch { Vector<InputMessage> samples; }; Vector<Batch> mBatches; // Touch state per device and source, only for sources of class pointer. struct History { nsecs_t eventTime; BitSet32 idBits; int32_t idToIndex[MAX_POINTER_ID + 1]; PointerCoords pointers[MAX_POINTERS]; void initializeFrom(const InputMessage* msg) { eventTime = msg->body.motion.eventTime; idBits.clear(); for (uint32_t i = 0; i < msg->body.motion.pointerCount; i++) { uint32_t id = msg->body.motion.pointers[i].properties.id; idBits.markBit(id); idToIndex[id] = i; pointers[i].copyFrom(msg->body.motion.pointers[i].coords); } } const PointerCoords& getPointerById(uint32_t id) const { return pointers[idToIndex[id]]; } }; struct TouchState { int32_t deviceId; int32_t source; size_t historyCurrent; size_t historySize; History history[2]; History lastResample; void initialize(int32_t deviceId, int32_t source) { this->deviceId = deviceId; this->source = source; historyCurrent = 0; historySize = 0; lastResample.eventTime = 0; lastResample.idBits.clear(); } void addHistory(const InputMessage* msg) { historyCurrent ^= 1; if (historySize < 2) { historySize += 1; } history[historyCurrent].initializeFrom(msg); } const History* getHistory(size_t index) const { return &history[(historyCurrent + index) & 1]; } }; Vector<TouchState> mTouchStates; // Chain of batched sequence numbers. When multiple input messages are combined into // a batch, we append a record here that associates the last sequence number in the // batch with the previous one. When the finished signal is sent, we traverse the // chain to individually finish all input messages that were part of the batch. struct SeqChain { uint32_t seq; // sequence number of batched input message uint32_t chain; // sequence number of previous batched input message }; Vector<SeqChain> mSeqChains; status_t consumeBatch(InputEventFactoryInterface* factory, nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent); status_t consumeSamples(InputEventFactoryInterface* factory, Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent); void updateTouchState(InputMessage* msg); void rewriteMessage(const TouchState& state, InputMessage* msg); void resampleTouchState(nsecs_t frameTime, MotionEvent* event, const InputMessage *next); ssize_t findBatch(int32_t deviceId, int32_t source) const; ssize_t findTouchState(int32_t deviceId, int32_t source) const; status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled); static void initializeKeyEvent(KeyEvent* event, const InputMessage* msg); static void initializeMotionEvent(MotionEvent* event, const InputMessage* msg); static void addSample(MotionEvent* event, const InputMessage* msg); static bool canAddSample(const Batch& batch, const InputMessage* msg); static ssize_t findSampleNoLaterThan(const Batch& batch, nsecs_t time); static bool shouldResampleTool(int32_t toolType); static bool isTouchResamplingEnabled(); }; } // namespace android #endif // _LIBINPUT_INPUT_TRANSPORT_H
760fb996ccb789267be468dd7075b6bfa561494c
01fc45fd6c210ffed08b3e9a3666a1573fd46512
/Dijkstra.cpp
5ee7f90731a7f7565dbc6d5f4c7ea1b064c5e6b4
[]
no_license
vinaygudarad/APS
7fe91c51171818f6fb3f6edfd5fcfe8af84e9efb
532d0dd4abfd78d30eefcedea52de5b4dfa2c4f2
refs/heads/master
2023-05-23T22:55:51.240782
2021-06-27T18:02:34
2021-06-27T18:02:34
372,820,117
0
0
null
null
null
null
UTF-8
C++
false
false
2,124
cpp
/* 1.........2 . . 1 . . .4 . 1 7. . . . . . 4........3 2 */ #include<bits/stdc++.h> using namespace std; template<typename T> class Graph{ unordered_map<T,list<pair<T,int> > > m; public: void addedge(T u, T v, int dist, bool bidir = true){ m[u].push_back(make_pair(v,dist)); if(bidir){ m[v].push_back(make_pair(v,dist)); } } void print(){ for(auto j : m){ cout << j.first << "->"; for(auto l : j.second){ cout << "(" << l.first << " " << l.second << ")"; } cout << endl; } } void dijsktrassp(T src){ unordered_map<T, int > dist; for(auto j : m){ dist[j.first] = INT_MAX; } set<pair<int,T> > s; dist[src] = 0; s.insert(make_pair(0,src)); while(!s.empty()){ auto p = *(s.begin()); T node = p.second; int nodeDist = p.first; s.erase(s.begin()); for(auto childpair : m[node]){ if(nodeDist + childpair.second < dist[childpair.first]){ T dest = childpair.first; auto f = s.find(make_pair(dist[dest],dest)); if(f != s.end()){ s.erase(f); } dist[dest] = nodeDist + childpair.second; s.insert(make_pair(dist[dest], dest)); } } } for(auto d : dist){ cout << d.first << " is located at distance of " << d.second << endl; } } }; int main(){ Graph<int>g; /* g.addedge(1,2,1); g.addedge(1,3,4); g.addedge(2,3,1); g.addedge(3,4,2); g.addedge(1,4,7); //g.printadj(); g.dijsktrassp(1); */ g.addedge(0,1,2); g.addedge(1,2,4); g.addedge(0,2,8); g.dijsktrassp(0); return 0; }
655ad74b56294e8c1da5cd3954a626f650cbae44
5f5bb4fe58ca6c9758e5ecd4f1acd7f3af7a41a4
/codeforces/edu/ITMO Academy: pilot course/Binary Search/step 5/a.cpp
a5fc370385d4f0382d92f760c885f3918b7d48b4
[ "MIT" ]
permissive
tysm/cpsols
61a93de55dbeb2d92d92c80681d6615521d3d0ba
262212646203e516d1706edf962290de93762611
refs/heads/master
2023-03-10T01:04:39.409948
2021-02-23T21:49:55
2021-02-23T21:49:55
202,269,911
4
0
null
null
null
null
UTF-8
C++
false
false
705
cpp
#include <cpplib/stdinc.hpp> int calc(vii &arr, int x){ int res = 0; for(ii &i:arr){ if(x > i.ss) res += i.ss-i.ff+1; else if(x >= i.ff) res += x-i.ff; } return res; } int32_t main(){ desync(); int n, k; cin >> n >> k; vii arr(n); for(ii &i:arr) cin >> i.ff >> i.ss; int lo = -INF, hi = INF; while(lo <= hi){ int mid = lo + (hi-lo)/2; int resx = calc(arr, mid), resxp1 = calc(arr, mid+1); if(resx <= k and resxp1 > k){ cout << mid << endl; break; } if(resx > k) hi = mid-1; else lo = mid+1; } return 0; }
552d7385839aac0e811e47b12981d8f33b267212
963b9d9a926941e87b69400398a43e20cc3f1dc4
/day03 ( Arrays 3 )/majorityElement.cpp
a2a78681d251cd0d1b194a0374c264873a29c884
[]
no_license
argon17/SDESheet
162bf4b22b279d74ea6371ee5576dfdfb71a30ed
265e1882d3512b09561cc407db8878b766ec87eb
refs/heads/master
2023-08-14T20:26:45.579637
2021-09-21T06:40:14
2021-09-21T06:40:14
374,260,281
5
1
null
null
null
null
UTF-8
C++
false
false
320
cpp
#include <bits/stdc++.h> #include <iostream> using namespace std; class Solution { public: int majorityElement(vector<int>& nums) { int cnt = 0, e = 0; for(int num : nums){ if(cnt == 0) e = num; if(e == num) ++cnt; else --cnt; } return e; } };
8fb0c12925b2724c03fc2f6505d714394b92437d
e64baba567510928c0d0922231b3219302c92f83
/qq/testwrite.cpp
6f3f93ece6145ab9bd1cc32910e9c4689023010c
[ "BSD-3-Clause" ]
permissive
nonego/ldb
21a5aa1fccc11b486d0da1b716238f5bd0d91b63
448e71c76bba66a9c93ca3d2899af4e0d95948fc
refs/heads/master
2021-01-01T19:07:06.173288
2014-05-19T03:32:36
2014-05-19T03:32:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
761
cpp
#include <leveldb/db.h> #include <string> #include <iostream> using namespace std; using namespace leveldb; int main( int argc, char* argv[]) { DB* db; Options options; options.create_if_missing = true; if( argc < 2 ) return 0; char delim; if( argc == 3 ) delim = argv[2][0]; else delim = '\t'; leveldb::Status status = leveldb::DB::Open(options, argv[1], &db); string line; int n=0; while( getline(cin, line)) { size_t i=line.find(delim); if( i == string::npos ) continue; db->Put(leveldb::WriteOptions(), line.substr(0, i), line.substr(i+1)); ++n; if( ( n & 0xFFFF ) == 0 ) cout << n << endl; } return 0; }
6314b8d4b4a5b03e5dd71b6cedffa6bb6e9a99c1
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_repos_function_804_httpd-2.4.6.cpp
cb6fb30be51292c211cf6e41e8b3fc3e622c5417
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
377
cpp
const char *ssl_cmd_SSLPKCS7CertificateFile(cmd_parms *cmd, void *dcfg, const char *arg) { SSLSrvConfigRec *sc = mySrvConfig(cmd->server); const char *err; if ((err = ssl_cmd_check_file(cmd, &arg))) { return err; } sc->server->pkcs7 = arg; return NULL; }
b2699e6f94a320e4c29ab1b230989b83d964e3c2
24baacc8b399eb0a5b73ab6c0e8e3bc16b2d5c07
/C_Data_Structure/src/Hashing/Hashing.cpp
59639a0d7a0f825d2f06602c4a4bb3ebb8c7c1b0
[]
no_license
jhseoeo/C_Algoritm_DataStructure
0049e38483d79201428d92d2970214d362b92e71
6b1b24593a8ba41dc56aa2c4edae2e3d41d442f6
refs/heads/master
2023-07-13T05:52:10.376159
2021-08-19T13:04:52
2021-08-19T13:04:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
317
cpp
#include "Hashing.h" void Hashing_Main() { int n; system(CLEAR); printf("Select the type of hashing\n"); printf("1. Chain Hashing\n"); printf("2. Closed Hashing\n"); printf(">>> "); scanf("%d", &n); switch (n) { case 1: ChainHashMain(); break; case 2: ClosedHashMain(); break; default: break; } }
f5c6f5dcc29d0d6296694565f1a1277948fe4d5c
bd5ca643253046ba841fe3d38731d60db9716352
/geeksy/medium/dp_medium_geeksforgeeks_page3_dp.cpp
c10c09db430e80beb8a3a6b4bd8f85c83f599995
[]
no_license
vivekgopalshetty/code
eabb32d2a8cc464eda399dd20f152ce9eb418913
8472fb15b87f027d088f4cecf538967a0c311717
refs/heads/master
2022-11-16T21:28:31.944287
2020-07-14T11:47:53
2020-07-14T11:47:53
279,570,731
0
0
null
null
null
null
UTF-8
C++
false
false
14,680
cpp
//https://www.geeksforgeeks.org/medium/dynamic-programming/3/ //dynamic-programming #include <bits/stdc++.h> using namespace std; #define MAX 50 //not done //https://www.geeksforgeeks.org/maximum-sum-path-in-a-matrix-from-top-to-bottom-and-back/ // int max_sum_twice(int arr[][MAX],int n,int m) // { // int cost[n][m]; // cost[0][0]=arr[0][0]; // for(int i=1;i<n;i++) // { // cost[i][0]=cost[i-1][0]+arr[i][0]; // } // for(int j=1;j<m;j++) // { // cost[0][j]=cost[0][j-1]+arr[0][j]; // } // for(int i=1;i<n;i++) // { // for(int j=1;j<m;j++) // { // cost[i][j]=arr[i][j]+max(cost[i-1][j-1], // max(cost[i][j-1],cost[i-1][j])); // } // } // int vis[n][m]={0}; // for(int i=1;i<n;i++) // { // for(int j=1;j<m;j++) // { // int maxi=0; // int maxj=0; // if(cost[i-1][j]>cost[i][j-1] && cost[i-1][j]>cost[i-1][j-1]) // { // maxi=i-1; // maxj=j; // } // else if(cost[i-1][j-1]>cost[i][j-1] && cost[i-1][j-1]>cost[i-1][j]) // { // maxi=i-1; // maxj=j-1; // } // else if(cost[i][j-1]>cost[i-1][j-1] && cost[i][j-1]>cost[i-1][j]) // { // maxi=i; // maxj=j-1; // } // vis[maxi][maxj]=1; // cout << arr[maxi][maxj] << endl; // } // } // for(int i=1;i<n;i++) // { // for(int j=1;j<m;j++) // { // cout << vis[i][j] << " "; // } // cout << endl; // } // return cost[n-1][m-1]; // } void bellman_ford(int graph[][3],int v,int e,int src) { int dist[v]; for(int i=0;i<v;i++) { dist[i]=INT_MAX; } dist[src]=0; for(int i=0;i<v-1;i++) { for(int j=0;j<e;j++) { if(dist[graph[j][0]]+graph[j][2]< dist[graph[j][1]]) { dist[graph[j][1]]=dist[graph[j][0]]+graph[j][2]; } } } for (int i = 0; i < e; i++) { int x = graph[i][0]; int y = graph[i][1]; int weight = graph[i][2]; if (dist[x] != INT_MAX && dist[x] + weight < dist[y]) cout << "Graph contains negative" " weight cycle" << endl; } cout << "Vertex Distance from Source" << endl; for (int i = 0; i < v; i++) cout << i << "\t\t" << dist[i] << endl; } int dp_mincub[1000]; int min_cubes_req(int k) { if(dp_mincub[k]!=0) { return dp_mincub[k]; } if (k < 8) return k; int res = k; for (int i = 1; i <= k; i++) { if ((i * i * i) > k) return res; res = min(res,min_cubes_req(k - (i * i * i)) + 1); } return dp_mincub[res]=res; } void print_answer(string s,int l,int h) { for(int i=l;i<=h;i++) { cout << s[i] ; } cout << endl; } void longest_pallindrome(string s) { int maxlen=1; int n=s.length(); int start=0; bool dp[n][n]; memset(dp,0,sizeof(dp)); for(int i=0;i<n;i++) { dp[i][i]=true; } for(int i=0;i<n-1;i++) { if(s[i]==s[i+1]) { maxlen=2; dp[i][i+1]=true; start=i; } } for(int k=3;k<=n;++k) { for(int i=0;i<n-k+1;++i) { // starting index i and length k int j=i+k-1; if(dp[i+1][j-1] && s[i]==s[j]) { dp[i][j]=true; if(k>maxlen) { start=i; maxlen=k; } } } } print_answer(s,start,start+maxlen-1); cout << maxlen; } void longest_pallindrome_v2(string str) { int maxlen=1; int n=str.length(); int start=0; int low,high; for(int i=1;i<n;i++) { low=i-1; high=i; while(low>=0 && high<n && str[low]==str[high]) { if(high-low+1>maxlen) { start=low; maxlen=high-low+1; } --low; ++high; } low = i - 1; high = i + 1; while (low >= 0 && high < n && str[low] == str[high]) { if (high - low + 1 > maxlen) { start = low; maxlen = high - low + 1; } --low; ++high; } } print_answer(str,start,start+maxlen-1); cout << maxlen; } int binary_string_with_3cons1s(int n) { int dp[n+2][3]; dp[2][0]=2; dp[2][1]=1; dp[2][2]=1; for(int i=3;i<=n+1;i++) { dp[i][0]=dp[i-1][0]+dp[i-1][1]+dp[i-1][2]; dp[i][1]=dp[i-1][0]; dp[i][2]=dp[i-1][1]; } return pow(2,n)-dp[n+1][0]; } int max_sum_subarray_alteringsigns(int a[],int n) { int dp[n+1][3]; memset(dp,0,sizeof(dp)); int arr[n+1]; int ans=0; for(int i=1;i<=n;i++) { arr[i]=a[i-1]; } for(int i=1;i<=n;i++) { dp[i][0]=max(arr[i],dp[i-1][0]+arr[i]); dp[i][1]=max(0,dp[i-1][0])-arr[i]; if(i>=2) { dp[i][1]=max(dp[i][1],dp[i-1][1]+arr[i]); } if(i>=2) { dp[i][2]=dp[i-1][1]-arr[i]; } if(i>=3) { dp[i][2]=max(dp[i][2],dp[i-1][2]+arr[i]); } ans = max(ans, dp[i][0]); ans = max(ans, dp[i][1]); ans = max(ans, dp[i][2]); } return ans; } int subsequence_not_less_thank(int arr[],int k,int n) { int dp[n+1]; dp[0]=1; for(int i=1;i<k;i++) { dp[i]=max(dp[i-1],arr[i]); } for(int i=k;i<n;i++) { dp[i]=max(dp[i-(1+k)]+arr[i],arr[i]); } return *max_element(dp,dp+n); } int max_number_of_composite(int n) { int maxn=16; int dp[maxn]={-1}; dp[0]=0; for(int i=0;i<maxn;i++) { for(int j:{4,6,9}) { if(i>=j && dp[i-j]!=-1) { dp[i]=max(dp[i],dp[i-j]+1); } } } if(n<16) { return dp[n]; } else { int t=(n-maxn)/4+1; return t+dp[n-4*t]; } return -1; } bool comp(int a,int i,vector<vector<int> > v) { int temp=a; int k; while(temp>0) { k=temp%10; temp=temp/10; if(v[i][k]==1) { return true; } } return false; } int ways_to_score_r(int r,int b,int w,int arr[],int dp[MAX][MAX][MAX]) { if(w<=0 && r>0) { return 0; } if(r<0) { return 0; } if(b<=0 && r!=0) { return 0; } if(r==0 && b==0) { return 1; } if(dp[r][b][w]!=-1) { return dp[r][b][w]; } int ways=0; for(int i=0;i<7;i++) { if(arr[i]==-1) { ways+=ways_to_score_r(r,b-1,w-1,arr,dp); } else { ways+=ways_to_score_r(r-arr[i],b-1,w,arr,dp); } } return dp[r][b][w]=ways; } int min_cost_path_jumps_lessthank(int arr[],int n,int k) { int dp[n+1]; dp[0]=0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < i + k + 1; j++) { dp[j] = min(dp[j], dp[i] + abs(arr[i] - arr[j])); } } return dp[n-1]; } //make changes int max_sum_3arrays_nocons(int arr1[],int arr2[],int arr3[],int n) { int dp[n+1][3]; dp[0][0]=arr1[0]; dp[0][1]=arr2[0]; dp[0][2]=arr3[0]; for(int i=1;i<n;i++) { dp[i][0]=max(arr2[i]+dp[i-1][0],arr3[i]+dp[i-1][0]); dp[i][1]=max(arr1[i]+dp[i-1][1],arr3[i]+dp[i-1][1]); dp[i][2]=max(arr1[i]+dp[i-1][2],arr2[i]+dp[i-1][2]); } return max(dp[n-1][0],max(dp[n-1][1],dp[n-1][2])); } int min_steps_delete_elems(int start,int end,string s,int dp[][MAX]) { if(start>end) { return 0; } if(start==end) { return 1; } if(dp[start][end]!=-1) { return dp[start][end]; } int res=1+min_steps_delete_elems(start+1,end,s,dp); for(int i=start+1;i<=end;i++) { if(s[start]==s[i]) { res=min(res,min_steps_delete_elems(start,i-1,s,dp)+ min_steps_delete_elems(i+1,end,s,dp)); } } return dp[start][end]=res; } //wrong int min_prod_dist_lessk(int arr[],int n,int k) { int dp[n+1]; dp[0]=INT_MAX; for(int i=0;i<=k;i++) { for(int j=i+1;j<i+k+1;j++) { dp[i]=min(dp[i],dp[i]*arr[j]); } } return dp[n-1]; } int dfs(vector<vector<int> > adj,int i,int v,int e) { stack<int> s; s.push(i); int cnt=0; int vis[v]={0}; while(!s.empty()) { int k=s.top(); s.pop(); if(vis[k]!=1) { cnt++; } for(int i=0;i<adj[k].size();i++) { if(vis[adj[k][i]]!=1) { s.push(adj[k][i]); } } } return cnt; } int longest_path_DAG(int graph[][MAX],int v,int e) { vector<vector<int> > adj; for(int i=0;i<e;i++) { adj[graph[i][0]].push_back(graph[i][1]); } int maxi=0; for(int i=0;i<v;i++) { maxi=max(maxi,dfs(adj,i,v,e)); } return maxi; } int findSubarraySum(int ind, int flips, int n, int a[], int k,int dp[][MAX]) { if (flips > k) return -1e9; if (ind == n) return 0; if (dp[ind][flips] != -1) return dp[ind][flips]; int ans = 0; ans = max(0, a[ind] + findSubarraySum(ind + 1, flips, n, a, k,dp)); ans = max(ans, -a[ind] + findSubarraySum(ind + 1, flips + 1, n, a, k,dp)); return dp[ind][flips] = ans; } int findMaxSubarraySum(int a[], int n, int k) { //int dp[n][k+1]; int dp[n][MAX]; memset(dp, -1, sizeof(dp)); int ans = -1e9; for (int i = 0; i < n; i++) ans = max(ans, findSubarraySum(i, 0, n, a, k,dp)); return ans; } int dp_knap[MAX][MAX][MAX]; int maxWeight(int* arr, int n, int w1_r, int w2_r, int i) { if (i == n) return 0; if (dp_knap[i][w1_r][w2_r] != -1) return dp_knap[i][w1_r][w2_r]; int fill_w1 = 0, fill_w2 = 0, fill_none = 0; if (w1_r >= arr[i]) fill_w1 = arr[i] + maxWeight(arr, n, w1_r - arr[i], w2_r, i + 1); if (w2_r >= arr[i]) fill_w2 = arr[i] + maxWeight(arr, n, w1_r, w2_r - arr[i], i + 1); fill_none = maxWeight(arr, n, w1_r, w2_r, i + 1); dp_knap[i][w1_r][w2_r] = max(fill_none, max(fill_w1, fill_w2)); return dp_knap[i][w1_r][w2_r]; } int removing_subsequence(string s,int arr[],int n) { long long valofc=0,valofo=0,valofd=0,valofe=0; for(int i=0;i<n;i++) { //remove c if(s[i]=='c') { valofc+=arr[i]; } //remove co else if(s[i]=='o') { valofo=min(valofc,valofo+arr[i]); } //remove cod else if(s[i]=='d') { valofd=min(valofo,valofd+arr[i]); } //remove code else if(s[i]=='e') { valofe=min(valofd,valofe+arr[i]); } } return valofe; } int longest_subsequence_common_digits(int arr[],int n) { vector<vector<int>> dp(n , vector<int> (10,0) ); for(int i=0;i<n;i++) { int temp=arr[i]; int k; while(temp>0) { k=temp%10; temp=temp/10; dp[i][k]=1; } } int ans[n+1]; ans[0]=1; for(int i=1;i<n;i++) { ans[i]=1; for(int j=0;j<i;j++) { if(comp(arr[i],j,dp) && ans[i]<ans[j]+1) { ans[i]=ans[j]+1; } } } return *max_element(ans,ans+n); } int main() { // int arr[][MAX]={{1, 0, 3, -1}, // {3, 5, 1, -2}, // {-2, 0, 1, 1}, // {2, 1, -1, 1}}; // int n=4;int m=4; // cout << max_sum_twice(arr,n,m); // int v = 5; // int e = 8; // int graph[][3] = { { 0, 1, -1 }, { 0, 2, 4 }, // { 1, 2, 3 }, { 1, 3, 2 }, // { 1, 4, 2 }, { 3, 2, 5 }, // { 3, 1, 1 }, { 4, 3, -3 } }; // bellman_ford(graph, v, e, 1); // string s="forgeeksskeegfor"; // longest_pallindrome(s); // string s="forgeeksskeegfor"; // longest_pallindrome_v2(s); //cout << binary_string_with_3cons1s(10); // int arr[] = { -5, 3, 2, 7, -8, 3, 7, -9, 10, 12, -6 }; // int n = sizeof(arr) / sizeof(arr[0]); // cout << max_sum_subarray_alteringsigns(arr, n); // int arr[] = { 6, 7, 1, 3, 8, 2, 4 }; // int n = sizeof(arr) / sizeof(arr[0]); // int k = 2; // cout << subsequence_not_less_thank(arr, k, n); // cout << max_number_of_composite(12); // int arr[]={12, 23, 45, 43, 36, 97}; // int n = sizeof(arr) / sizeof(arr[0]); // cout << longest_subsequence_common_digits(arr,n); // int R = 40, B = 10, W = 4; // int arr[]={-1,0,1,2,4,3,6}; // int dp[MAX][MAX][MAX]; // memset(dp, -1, sizeof dp); // cout << ways_to_score_r(40,10,4,arr,dp); // int a[] = { 6, 8, 2, 7, 4, 2, 7 }; // int b[] = { 7, 8, 5, 8, 6, 3, 5 }; // int c[] = { 8, 3, 2, 6, 8, 4, 1 }; // int n = sizeof(a) / sizeof(a[0]); // cout << max_sum_3arrays_nocons(a,b,c,n); // int arr[]={ 83, 26, 37, 35, 33, 35, 56 }; // int k=3; // int n = sizeof(arr) / sizeof(arr[0]); // cout << min_cost_path_jumps_lessthank(arr,n,k); // string s = "abcddcba"; // int n = s.length(); // int dp[MAX][MAX]; // memset(dp,-1,sizeof(dp)); // cout << min_steps_delete_elems(0,n-1,s,dp); // string str = "geekcodergeeks"; // int arr[] = { 1, 2, 1, 3, 4, 2, 6, 4, 6, 2, 3, 3, 3, 2 }; // int n = sizeof(arr) / sizeof(arr[0]); // cout << removing_subsequence(str, arr, n); return 0; }
7f625bd03c8d036396b29962c80a5154305426d2
439b02e8df3482052f5fe09661156566ef17df8f
/include/requests/detail/timed_handler.hpp
6cf990862f99dd2542b7cf75e9e52872e61731be
[ "BSL-1.0" ]
permissive
cbodley/requests
a88406e10526b90447df7bb44d3d457787362b8c
74fa7821da4789573da05629357fda618e760b20
refs/heads/master
2020-04-04T15:46:17.341127
2018-11-04T04:59:40
2018-11-04T04:59:40
156,051,622
1
0
null
null
null
null
UTF-8
C++
false
false
2,051
hpp
#pragma once #include <boost/asio/associated_allocator.hpp> #include <boost/asio/associated_executor.hpp> namespace requests::detail { // a handler wrapper that cancels a timer on completion template <typename Handler, typename Timer> struct timed_handler { Handler handler; Timer& timer; timed_handler(Handler&& h, Timer& t) : handler(std::move(h)), timer(t) {} template <typename Canceler> timed_handler(Canceler& canceler, Timer& timer, typename Timer::time_point expires_at, Handler&& handler) : handler(std::move(handler)), timer(timer) { timer.expires_at(expires_at); timer.async_wait([&canceler] (boost::system::error_code ec) { if (ec != boost::asio::error::operation_aborted) canceler.cancel(); }); } template <typename Canceler> timed_handler(Canceler& canceler, Timer& timer, typename Timer::duration expires_after, Handler&& handler) : handler(std::move(handler)), timer(timer) { timer.expires_after(expires_after); timer.async_wait([&canceler] (boost::system::error_code ec) { if (ec != boost::asio::error::operation_aborted) canceler.cancel(); }); } template <typename ...Args> void operator()(Args&& ...args) { timer.cancel(); handler(std::forward<Args>(args)...); } using allocator_type = boost::asio::associated_allocator_t<Handler>; allocator_type get_allocator() const noexcept { return boost::asio::get_associated_allocator(handler); } }; } // namespace requests::detail namespace boost::asio { // associated_executor trait for requests::detail::basic_timed_handler template <typename Handler, typename Timer, typename Executor> struct associated_executor<requests::detail::timed_handler<Handler, Timer>, Executor> { using type = associated_executor_t<Handler, Executor>; static type get(const requests::detail::timed_handler<Handler, Timer>& h, const Executor& ex = Executor()) noexcept { return get_associated_executor(h.handler, ex); } }; } // namespace boost::asio
836c2e1a2a042c3738ebf428fc487247abbde2ce
80d97bc5ff8a43da99893a57f03002e68081d780
/scintilla/lexlib/DefaultLexer.h
b7c5d894deded7cb50b110ae422e71bd24329c92
[ "LicenseRef-scancode-scintilla", "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ProgerXP/Notepad2e
38798db10e0fe0a5602a463a5681bd653afe3bb6
c703f11bc278457286b3ca1565047a3b09ccdf8d
refs/heads/master
2023-09-05T23:32:07.576076
2023-07-27T11:03:30
2023-07-27T11:03:49
10,840,481
376
50
NOASSERTION
2022-08-22T14:06:36
2013-06-21T10:28:18
C++
UTF-8
C++
false
false
2,387
h
// Scintilla source code edit control /** @file DefaultLexer.h ** A lexer base class with default empty implementations of methods. ** For lexers that do not support all features so do not need real implementations. ** Does have real implementation for style metadata. **/ // Copyright 2017 by Neil Hodgson <[email protected]> // The License.txt file describes the conditions under which this software may be distributed. #ifndef DEFAULTLEXER_H #define DEFAULTLEXER_H namespace Scintilla { // A simple lexer with no state class DefaultLexer : public ILexerWithMetaData { const LexicalClass *lexClasses; size_t nClasses; public: DefaultLexer(const LexicalClass *lexClasses_ = nullptr, size_t nClasses_ = 0); virtual ~DefaultLexer(); void SCI_METHOD Release() override; int SCI_METHOD Version() const override; const char * SCI_METHOD PropertyNames() override; int SCI_METHOD PropertyType(const char *name) override; const char * SCI_METHOD DescribeProperty(const char *name) override; Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override; const char * SCI_METHOD DescribeWordListSets() override; Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override; void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument *pAccess) override = 0; void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument *pAccess) override; void * SCI_METHOD PrivateCall(int operation, void *pointer) override; int SCI_METHOD LineEndTypesSupported() override; int SCI_METHOD AllocateSubStyles(int styleBase, int numberStyles) override; int SCI_METHOD SubStylesStart(int styleBase) override; int SCI_METHOD SubStylesLength(int styleBase) override; int SCI_METHOD StyleFromSubStyle(int subStyle) override; int SCI_METHOD PrimaryStyleFromStyle(int style) override; void SCI_METHOD FreeSubStyles() override; void SCI_METHOD SetIdentifiers(int style, const char *identifiers) override; int SCI_METHOD DistanceToSecondaryStyles() override; const char * SCI_METHOD GetSubStyleBases() override; int SCI_METHOD NamedStyles() override; const char * SCI_METHOD NameOfStyle(int style) override; const char * SCI_METHOD TagsOfStyle(int style) override; const char * SCI_METHOD DescriptionOfStyle(int style) override; }; } #endif
0e85693114a4e46384a6f56444b6b0ae2680aeab
8e756b03d03bb8404e2b6fa3d7e54f6c031fa2db
/source/Spec.h
4a18e0b463d13587a41d43da7c4abba763aab534
[]
no_license
kimdopal/Job-Consulting
32311ed316681e21339ff5243b564f124b25acda
6a55a51ffc49ddc9acc95f586916660bc19abbe3
refs/heads/master
2022-04-01T01:21:17.379015
2020-01-14T11:02:44
2020-01-14T11:02:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,443
h
#ifndef SPEC_H #define SPEC_H #include <string> using namespace std; class Spec { public: Spec(); // class constructor ~Spec() {} // class destructor // getter string getUniversity() { return mUniversity; } string getMajor() { return mMajor; } float getGpa() { return mGpa; } int getToeic() { return mToeic; } int getOpic() { return mOpic; } int getToeicSpeaking() { return mToeicSpeaking; } int getCertCount() { return mCertCount; } int getLangStudy() { return mLangStudy; } int getIntern() { return mIntern; } // setter void setUniversity(string inUniversity) { mUniversity = inUniversity; } void setMajor(string inMajor) { mMajor = inMajor; } void setGpa(float inGpa) { mGpa = inGpa; } void setToeic(int inToeic) { mToeic = inToeic; } void setOpic(int inOpic) { mOpic = inOpic; } void setToeicSpeaking(int inToeicSpeaking) { mToeicSpeaking = inToeicSpeaking; } void setCertCount(int inCertCount) { mCertCount = inCertCount; } void setLangStudy(int inLangStudy) { mLangStudy = inLangStudy; } void setIntern(int inIntern) { mIntern = inIntern; } protected: string mUniversity; // 출신 대학 string mMajor; // 전공 float mGpa; // 학점 int mToeic; // 토익 (없는 경우 0) int mOpic; // 오픽 (없는 경우 0) int mToeicSpeaking; // 토스 (없는 경우 0) int mCertCount; // 자격증 개수 int mLangStudy; // 어학연수 횟수 int mIntern; // 인턴 횟수 }; #endif // !SPEC_H
6bfc0daeaf0e77902670b567121e0a5ce326fc74
2ba94892764a44d9c07f0f549f79f9f9dc272151
/Engine/Source/Runtime/OpenGLDrv/Public/OpenGLES31.h
12abd7fecee0ba80b3d66729d724f1b75c9e1df2
[ "BSD-2-Clause", "LicenseRef-scancode-proprietary-license" ]
permissive
PopCap/GameIdea
934769eeb91f9637f5bf205d88b13ff1fc9ae8fd
201e1df50b2bc99afc079ce326aa0a44b178a391
refs/heads/master
2021-01-25T00:11:38.709772
2018-09-11T03:38:56
2018-09-11T03:38:56
37,818,708
0
0
BSD-2-Clause
2018-09-11T03:39:05
2015-06-21T17:36:44
null
UTF-8
C++
false
false
36,580
h
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. /*============================================================================= OpenGL3.h: Public OpenGL 3.2 definitions for non-common functionality =============================================================================*/ #pragma once #define OPENGL_ES31 1 #include "OpenGL.h" #ifdef GL_AMD_debug_output #undef GL_AMD_debug_output #endif /** Unreal tokens that maps to different OpenGL tokens by platform. */ #undef UGL_ANY_SAMPLES_PASSED #define UGL_ANY_SAMPLES_PASSED GL_ANY_SAMPLES_PASSED_EXT #undef UGL_CLAMP_TO_BORDER #define UGL_CLAMP_TO_BORDER FOpenGL::ClampToBorederMode() #undef UGL_TIME_ELAPSED #define UGL_TIME_ELAPSED GL_TIME_ELAPSED_EXT #define USE_OPENGL_NAME_CACHE 1 #define OPENGL_NAME_CACHE_SIZE 1024 struct FOpenGLES31 : public FOpenGLBase { static FORCEINLINE bool SupportsVertexArrayObjects() { return bSupportsVertexArrayObjects || !bES2Fallback; } static FORCEINLINE bool SupportsMapBuffer() { return bSupportsMapBuffer || !bES2Fallback; } static FORCEINLINE bool SupportsDepthTexture() { return bSupportsDepthTexture || !bES2Fallback; } static FORCEINLINE bool SupportsDrawBuffers() { return !bES2Fallback; } static FORCEINLINE bool SupportsPixelBuffers() { return !bES2Fallback; } static FORCEINLINE bool SupportsUniformBuffers() { return !bES2Fallback; } static FORCEINLINE bool SupportsStructuredBuffers() { return false; } static FORCEINLINE bool SupportsOcclusionQueries() { return bSupportsOcclusionQueries; } static FORCEINLINE bool SupportsExactOcclusionQueries() { return false; } static FORCEINLINE bool SupportsTimestampQueries() { return !bES2Fallback && bSupportsNvTimerQuery; } static bool SupportsDisjointTimeQueries(); static FORCEINLINE bool SupportsBlitFramebuffer() { return bSupportsNVFrameBufferBlit || !bES2Fallback; } static FORCEINLINE bool SupportsDepthStencilRead() { return !bES2Fallback; } static FORCEINLINE bool SupportsFloatReadSurface() { return !bES2Fallback; } static FORCEINLINE bool SupportsMultipleRenderTargets() { return !bES2Fallback; } static FORCEINLINE bool SupportsMultisampledTextures() { return !bES2Fallback; } static FORCEINLINE bool SupportsFences() { return !bES2Fallback; } static FORCEINLINE bool SupportsPolygonMode() { return false; } static FORCEINLINE bool SupportsSamplerObjects() { return !bES2Fallback; } static FORCEINLINE bool SupportsTexture3D() { return !bES2Fallback; } static FORCEINLINE bool SupportsTextureLODBias() { return false; } static FORCEINLINE bool SupportsTextureCompare() { return !bES2Fallback; } static FORCEINLINE bool SupportsTextureBaseLevel() { return !bES2Fallback; } static FORCEINLINE bool SupportsTextureMaxLevel() { return !bES2Fallback; } static FORCEINLINE bool SupportsInstancing() { return !bES2Fallback; } static FORCEINLINE bool SupportsVertexAttribInteger() { return true; } static FORCEINLINE bool SupportsVertexAttribShort() { return true; } static FORCEINLINE bool SupportsVertexAttribByte() { return true; } static FORCEINLINE bool SupportsVertexAttribDouble() { return true; } static FORCEINLINE bool SupportsDrawIndexOffset() { return !bES2Fallback; } static FORCEINLINE bool SupportsResourceView() { return !bES2Fallback; } static FORCEINLINE bool SupportsCopyBuffer() { return !bES2Fallback; } static FORCEINLINE bool SupportsDiscardFrameBuffer() { return bSupportsDiscardFrameBuffer; } static FORCEINLINE bool SupportsIndexedExtensions() { return !bES2Fallback; } static FORCEINLINE bool SupportsVertexHalfFloat() { return bSupportsVertexHalfFloat || !bES2Fallback; } static FORCEINLINE bool SupportsTextureFloat() { return bSupportsTextureFloat || !bES2Fallback; } static FORCEINLINE bool SupportsTextureHalfFloat() { return bSupportsTextureHalfFloat || !bES2Fallback; } static FORCEINLINE bool SupportsColorBufferHalfFloat() { return bSupportsColorBufferHalfFloat || !bES2Fallback; } static FORCEINLINE bool SupportsRG16UI() { return bSupportsNvImageFormats && !bES2Fallback; } static FORCEINLINE bool SupportsR11G11B10F() { return bSupportsNvImageFormats && !bES2Fallback; } static FORCEINLINE bool SupportsShaderFramebufferFetch() { return bSupportsShaderFramebufferFetch; } static FORCEINLINE bool SupportsShaderDepthStencilFetch() { return bSupportsShaderDepthStencilFetch; } static FORCEINLINE bool SupportsMultisampledRenderToTexture() { return bSupportsMultisampledRenderToTexture; } static FORCEINLINE bool SupportsVertexArrayBGRA() { return false; } static FORCEINLINE bool SupportsBGRA8888() { return bSupportsBGRA8888; } static FORCEINLINE bool SupportsSRGB() { return bSupportsSGRB || !bES2Fallback; } static FORCEINLINE bool SupportsRGBA8() { return bSupportsRGBA8; } static FORCEINLINE bool SupportsDXT() { return bSupportsDXT; } static FORCEINLINE bool SupportsPVRTC() { return bSupportsPVRTC; } static FORCEINLINE bool SupportsATITC() { return bSupportsATITC; } static FORCEINLINE bool SupportsETC1() { return bSupportsETC1; } static FORCEINLINE bool SupportsETC2() { return bSupportsETC2; } static FORCEINLINE bool SupportsCombinedDepthStencilAttachment() { return !bES2Fallback;; } static FORCEINLINE bool SupportsPackedDepthStencil() { return bSupportsPackedDepthStencil || !bES2Fallback; } static FORCEINLINE bool SupportsTextureCubeLodEXT() { return bES2Fallback ? bSupportsTextureCubeLodEXT : false; } static FORCEINLINE bool SupportsShaderTextureLod() { return bES2Fallback ? bSupportsShaderTextureLod : true; } static FORCEINLINE bool SupportsShaderTextureCubeLod() { return bES2Fallback ? bSupportsShaderTextureCubeLod : true; } static FORCEINLINE bool SupportsCopyTextureLevels() { return bSupportsCopyTextureLevels; } static FORCEINLINE GLenum GetDepthFormat() { return GL_DEPTH_COMPONENT16; } static FORCEINLINE GLenum GetShadowDepthFormat() { return GL_DEPTH_COMPONENT16; } static FORCEINLINE bool RequiresDontEmitPrecisionForTextureSamplers() { return bRequiresDontEmitPrecisionForTextureSamplers; } static FORCEINLINE bool RequiresTextureCubeLodEXTToTextureCubeLodDefine() { return bRequiresTextureCubeLodEXTToTextureCubeLodDefine; } static FORCEINLINE bool SupportsStandardDerivativesExtension() { return true; } static FORCEINLINE bool RequiresGLFragCoordVaryingLimitHack() { return bRequiresGLFragCoordVaryingLimitHack; } static FORCEINLINE GLenum GetVertexHalfFloatFormat() { return bES2Fallback ? GL_HALF_FLOAT_OES : GL_HALF_FLOAT; } static FORCEINLINE bool RequiresTexture2DPrecisionHack() { return bRequiresTexture2DPrecisionHack; } // On iOS both glMapBufferOES() and glBufferSubData() for immediate vertex and index data // is the slow path (they both hit GPU sync and data cache flush in driver according to profiling in driver symbols). // Turning this to false reverts back to not using vertex and index buffers // for glDrawArrays() and glDrawElements() on dynamic data. static FORCEINLINE bool SupportsFastBufferData() { return !bES2Fallback; } // ES 2 will not work with non-power of two textures with non-clamp mode static FORCEINLINE bool HasSamplerRestrictions() { return bES2Fallback; } static FORCEINLINE bool UseES30ShadingLanguage() { return GetMajorVersion() == 3; } static FORCEINLINE bool IsDebugContent() { return bDebugContext; } static FORCEINLINE bool SupportsSeamlessCubeMap() { return !bES2Fallback; } static FORCEINLINE bool SupportsVolumeTextureRendering() { return bSupportsVolumeTextureRendering; } static FORCEINLINE bool SupportsGenerateMipmap() { return true; } static FORCEINLINE bool SupportsTextureSwizzle() { return !bES2Fallback; } //from FOpenGL4 static FORCEINLINE bool SupportsSeparateAlphaBlend() { return bSupportsSeparateAlphaBlend; } static FORCEINLINE bool SupportsTessellation() { return bSupportsTessellation; } static FORCEINLINE bool SupportsComputeShaders() { return !bES2Fallback; } static FORCEINLINE bool SupportsDrawIndirect() { return !bES2Fallback; } static FORCEINLINE bool SupportsVertexAttribBinding() { return !bES2Fallback; } static FORCEINLINE bool SupportsTextureView() { return bSupportsTextureView; } // Whether GLES 3.1 + extension pack is supported static bool SupportsAdvancedFeatures(); static FORCEINLINE GLenum ClampToBorederMode() { return bES2Fallback ? GL_CLAMP_TO_EDGE : GL_CLAMP_TO_BORDER_EXT;} // Optional static FORCEINLINE void QueryTimestampCounter(GLuint QueryID) { //glQueryCounter(QueryID, GL_TIMESTAMP); } static FORCEINLINE void BeginQuery(GLenum QueryType, GLuint QueryId) { glBeginQuery( QueryType, QueryId ); } static FORCEINLINE void EndQuery(GLenum QueryType) { glEndQuery( QueryType ); } static FORCEINLINE void GetQueryObject(GLuint QueryId, EQueryMode QueryMode, GLuint64* OutResult) { GLenum QueryName = (QueryMode == QM_Result) ? GL_QUERY_RESULT : GL_QUERY_RESULT_AVAILABLE; GLuint Result = 0; glGetQueryObjectuiv(QueryId, QueryName, &Result); *OutResult = Result; } /* static FORCEINLINE void ReadBuffer(GLenum Mode) { glReadBuffer( Mode ); } static FORCEINLINE void DrawBuffer(GLenum Mode) { glDrawBuffers( 1, &Mode ); } static FORCEINLINE void DeleteSync(UGLsync Sync) { glDeleteSync( Sync ); } static FORCEINLINE UGLsync FenceSync(GLenum Condition, GLbitfield Flags) { return glFenceSync( Condition, Flags ); } static FORCEINLINE bool IsSync(UGLsync Sync) { return (glIsSync( Sync ) == GL_TRUE) ? true : false; } static FORCEINLINE EFenceResult ClientWaitSync(UGLsync Sync, GLbitfield Flags, GLuint64 Timeout) { GLenum Result = glClientWaitSync( Sync, Flags, Timeout ); switch (Result) { case GL_ALREADY_SIGNALED: return FR_AlreadySignaled; case GL_TIMEOUT_EXPIRED: return FR_TimeoutExpired; case GL_CONDITION_SATISFIED: return FR_ConditionSatisfied; } return FR_WaitFailed; } */ static FORCEINLINE void GenSamplers(GLsizei Count, GLuint* Samplers) { glGenSamplers(Count, Samplers); } static FORCEINLINE void DeleteSamplers(GLsizei Count, GLuint* Samplers) { glDeleteSamplers(Count, Samplers); } static FORCEINLINE void SetSamplerParameter(GLuint Sampler, GLenum Parameter, GLint Value) { glSamplerParameteri(Sampler, Parameter, Value); } static FORCEINLINE void BindSampler(GLuint Unit, GLuint Sampler) { glBindSampler(Unit, Sampler); } static FORCEINLINE void PolygonMode(GLenum Face, GLenum Mode) { // Not in ES //glPolygonMode(Face, Mode); } static FORCEINLINE void VertexAttribDivisor(GLuint Index, GLuint Divisor) { if (!bES2Fallback) { glVertexAttribDivisor(Index, Divisor); } } // Required static FORCEINLINE void* MapBufferRange(GLenum Type, uint32 InOffset, uint32 InSize, EResourceLockMode LockMode) { void *Result = nullptr; if (!bES2Fallback) { GLenum Access; switch ( LockMode ) { case RLM_ReadOnly: Access = GL_MAP_READ_BIT; break; case RLM_WriteOnly: Access = (GL_MAP_INVALIDATE_BUFFER_BIT | GL_MAP_WRITE_BIT ); // Temp workaround for synchrnoization when a UBO is discarded while being referenced Access |= GL_MAP_UNSYNCHRONIZED_BIT; break; case RLM_WriteOnlyUnsynchronized: Access = (GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT); break; case RLM_WriteOnlyPersistent: Access = (GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT); break; case RLM_ReadWrite: default: Access = (GL_MAP_READ_BIT | GL_MAP_WRITE_BIT); } Result = glMapBufferRange(Type, InOffset, InSize, Access); } else { #if OPENGL_ES2_BRING_UP // Non-written areas retain prior values. // Lack of unsynchronized in glMapBufferOES() is a perf bug which needs to be fixed later. checkf(LockMode == RLM_WriteOnly || LockMode == RLM_WriteOnlyUnsynchronized, TEXT("OpenGL ES 2.0 only supports write-only buffer locks")); #else checkf(LockMode == RLM_WriteOnly, TEXT("OpenGL ES 2.0 only supports write-only buffer locks")); #endif check(Type == GL_ARRAY_BUFFER || Type == GL_ELEMENT_ARRAY_BUFFER); uint8* Data = (uint8*) glMapBufferOES(Type, GL_WRITE_ONLY_OES); Result = Data ? Data + InOffset : NULL; } return Result; } static FORCEINLINE void UnmapBuffer(GLenum Type) { if (!bES2Fallback) { glUnmapBuffer(Type); } else { check(Type == GL_ARRAY_BUFFER || Type == GL_ELEMENT_ARRAY_BUFFER); glUnmapBufferOES(Type); } } static FORCEINLINE void UnmapBufferRange(GLenum Type, uint32 InOffset, uint32 InSize) { UnmapBuffer(Type); } static FORCEINLINE void GenQueries(GLsizei NumQueries, GLuint* QueryIDs) { glGenQueries(NumQueries, QueryIDs); } static FORCEINLINE void DeleteQueries(GLsizei NumQueries, const GLuint* QueryIDs ) { glDeleteQueries( NumQueries, QueryIDs ); } static FORCEINLINE void GetQueryObject(GLuint QueryId, EQueryMode QueryMode, GLuint* OutResult) { GLenum QueryName = (QueryMode == QM_Result) ? GL_QUERY_RESULT : GL_QUERY_RESULT_AVAILABLE; glGetQueryObjectuiv(QueryId, QueryName, OutResult); } static FORCEINLINE void BindBufferBase(GLenum Target, GLuint Index, GLuint Buffer) { check(!bES2Fallback); glBindBufferBase(Target, Index, Buffer); } static FORCEINLINE void BindBufferRange(GLenum Target, GLuint Index, GLuint Buffer, GLintptr Offset, GLsizeiptr Size) { check(!bES2Fallback); glBindBufferRange(Target, Index, Buffer, Offset, Size); } static FORCEINLINE GLuint GetUniformBlockIndex(GLuint Program, const GLchar* UniformBlockName) { return glGetUniformBlockIndex(Program, UniformBlockName); } static FORCEINLINE void UniformBlockBinding(GLuint Program, GLuint UniformBlockIndex, GLuint UniformBlockBinding) { glUniformBlockBinding(Program, UniformBlockIndex, UniformBlockBinding); } static FORCEINLINE void BindFragDataLocation(GLuint Program, GLuint Color, const GLchar* Name) { // Not in ES //glBindFragDataLocation(Program, Color, Name); } static FORCEINLINE void TexParameter(GLenum Target, GLenum Parameter, GLint Value) { glTexParameteri(Target, Parameter, Value); } static FORCEINLINE void FramebufferTexture(GLenum Target, GLenum Attachment, GLuint Texture, GLint Level) { glFramebufferTextureEXT(Target, Attachment, Texture, Level); } static FORCEINLINE void FramebufferTexture3D(GLenum Target, GLenum Attachment, GLenum TexTarget, GLuint Texture, GLint Level, GLint ZOffset) { // ES 3.1 uses FramebufferLAyer //glFramebufferTexture3D(Target, Attachment, TexTarget, Texture, Level, ZOffset); glFramebufferTextureLayer(Target, Attachment, Texture, Level, ZOffset); } static FORCEINLINE void FramebufferTextureLayer(GLenum Target, GLenum Attachment, GLuint Texture, GLint Level, GLint Layer) { glFramebufferTextureLayer(Target, Attachment, Texture, Level, Layer); } static FORCEINLINE void Uniform4uiv(GLint Location, GLsizei Count, const GLuint* Value) { glUniform4uiv(Location, Count, Value); } static FORCEINLINE void ProgramUniform4uiv(GLuint Program, GLint Location, GLsizei Count, const GLuint *Value) { glUniform4uiv(Location, Count, Value); } static FORCEINLINE void BlitFramebuffer(GLint SrcX0, GLint SrcY0, GLint SrcX1, GLint SrcY1, GLint DstX0, GLint DstY0, GLint DstX1, GLint DstY1, GLbitfield Mask, GLenum Filter) { glBlitFramebuffer(SrcX0, SrcY0, SrcX1, SrcY1, DstX0, DstY0, DstX1, DstY1, Mask, Filter); } static FORCEINLINE void DrawBuffers(GLsizei NumBuffers, const GLenum* Buffers) { glDrawBuffers(NumBuffers, Buffers); } static FORCEINLINE void DepthRange(GLdouble Near, GLdouble Far) { glDepthRangef(Near, Far); } static FORCEINLINE void EnableIndexed(GLenum Parameter, GLuint Index) { glEnableiEXT(Parameter, Index); } static FORCEINLINE void DisableIndexed(GLenum Parameter, GLuint Index) { glDisableiEXT(Parameter, Index); } static FORCEINLINE void ColorMaskIndexed(GLuint Index, GLboolean Red, GLboolean Green, GLboolean Blue, GLboolean Alpha) { glColorMaskiEXT(Index, Red, Green, Blue, Alpha); } static FORCEINLINE void VertexAttribPointer(GLuint Index, GLint Size, GLenum Type, GLboolean Normalized, GLsizei Stride, const GLvoid* Pointer) { glVertexAttribPointer(Index, Size, Type, Normalized, Stride, Pointer); } static FORCEINLINE void VertexAttribIPointer(GLuint Index, GLint Size, GLenum Type, GLsizei Stride, const GLvoid* Pointer) { if (bES2Fallback) { glVertexAttribPointer(Index, Size, Type, GL_FALSE, Stride, Pointer); } else { glVertexAttribIPointer(Index, Size, Type, Stride, Pointer); } } /* * * ES 3 has deprecated most conversions, need to implement conversion routines * */ template< typename Type, int Max> static void TVertexAttrib4Nv( GLuint AttributeIndex, const Type* Values) { GLfloat Params[4]; for ( int32 Idx = 0; Idx < 4; Idx++) { Params[Idx] = FMath::Max( float(Values[Idx]) / float(Max), -1.0f); } glVertexAttrib4fv( AttributeIndex, Params); } template< typename Type> static void TVertexAttrib4v( GLuint AttributeIndex, const Type* Values) { GLfloat Params[4]; for ( int32 Idx = 0; Idx < 4; Idx++) { Params[Idx] = float(Values[Idx]); } glVertexAttrib4fv( AttributeIndex, Params); } template< typename Type> static void TVertexAttrib4Iv( GLuint AttributeIndex, const Type* Values) { GLint Params[4]; for ( int32 Idx = 0; Idx < 4; Idx++) { Params[Idx] = GLint(Values[Idx]); } glVertexAttribI4iv( AttributeIndex, Params); } template< typename Type> static void TVertexAttrib4UIv( GLuint AttributeIndex, const Type* Values) { GLuint Params[4]; for ( int32 Idx = 0; Idx < 4; Idx++) { Params[Idx] = GLuint(Values[Idx]); } glVertexAttribI4uiv( AttributeIndex, Params); } static FORCEINLINE void VertexAttrib4Nsv(GLuint AttributeIndex, const GLshort* Values) { //glVertexAttrib4Nsv(AttributeIndex, Values); TVertexAttrib4Nv<GLshort, 32767>( AttributeIndex, Values); } static FORCEINLINE void VertexAttrib4sv(GLuint AttributeIndex, const GLshort* Values) { //glVertexAttrib4sv(AttributeIndex, Values); TVertexAttrib4v<GLshort>( AttributeIndex, Values); } static FORCEINLINE void VertexAttribI4sv(GLuint AttributeIndex, const GLshort* Values) { //glVertexAttribI4sv(AttributeIndex, Values); TVertexAttrib4Iv<GLshort>( AttributeIndex, Values); } static FORCEINLINE void VertexAttribI4usv(GLuint AttributeIndex, const GLushort* Values) { //glVertexAttribI4usv(AttributeIndex, Values); TVertexAttrib4UIv<GLushort>( AttributeIndex, Values); } static FORCEINLINE void VertexAttrib4Nubv(GLuint AttributeIndex, const GLubyte* Values) { //glVertexAttrib4Nubv(AttributeIndex, Values); TVertexAttrib4Nv<GLubyte, 255>( AttributeIndex, Values); } static FORCEINLINE void VertexAttrib4ubv(GLuint AttributeIndex, const GLubyte* Values) { //glVertexAttrib4ubv(AttributeIndex, Values); TVertexAttrib4v<GLubyte>( AttributeIndex, Values); } static FORCEINLINE void VertexAttribI4ubv(GLuint AttributeIndex, const GLubyte* Values) { //glVertexAttribI4ubv(AttributeIndex, Values); TVertexAttrib4UIv<GLubyte>( AttributeIndex, Values); } static FORCEINLINE void VertexAttrib4Nbv(GLuint AttributeIndex, const GLbyte* Values) { //glVertexAttrib4Nbv(AttributeIndex, Values); TVertexAttrib4Nv<GLbyte, 127>( AttributeIndex, Values); } static FORCEINLINE void VertexAttrib4bv(GLuint AttributeIndex, const GLbyte* Values) { //glVertexAttrib4bv(AttributeIndex, Values); TVertexAttrib4v<GLbyte>( AttributeIndex, Values); } static FORCEINLINE void VertexAttribI4bv(GLuint AttributeIndex, const GLbyte* Values) { //glVertexAttribI4bv(AttributeIndex, Values); TVertexAttrib4Iv<GLbyte>( AttributeIndex, Values); } static FORCEINLINE void VertexAttrib4dv(GLuint AttributeIndex, const GLdouble* Values) { //glVertexAttrib4dv(AttributeIndex, Values); TVertexAttrib4v<GLdouble>( AttributeIndex, Values); } static FORCEINLINE void VertexAttribI4iv(GLuint AttributeIndex, const GLint* Values) { glVertexAttribI4iv(AttributeIndex, Values); } static FORCEINLINE void VertexAttribI4uiv(GLuint AttributeIndex, const GLuint* Values) { glVertexAttribI4uiv(AttributeIndex, Values); } static FORCEINLINE void DrawArraysInstanced(GLenum Mode, GLint First, GLsizei Count, GLsizei InstanceCount) { glDrawArraysInstanced(Mode, First, Count, InstanceCount); } static FORCEINLINE void DrawElementsInstanced(GLenum Mode, GLsizei Count, GLenum Type, const GLvoid* Indices, GLsizei InstanceCount) { glDrawElementsInstanced(Mode, Count, Type, Indices, InstanceCount); } static FORCEINLINE void DrawRangeElements(GLenum Mode, GLuint Start, GLuint End, GLsizei Count, GLenum Type, const GLvoid* Indices) { glDrawRangeElements(Mode, Start, End, Count, Type, Indices); } static FORCEINLINE void ClearBufferfv(GLenum Buffer, GLint DrawBufferIndex, const GLfloat* Value) { glClearBufferfv(Buffer, DrawBufferIndex, Value); } static FORCEINLINE void ClearBufferfi(GLenum Buffer, GLint DrawBufferIndex, GLfloat Depth, GLint Stencil) { glClearBufferfi(Buffer, DrawBufferIndex, Depth, Stencil); } static FORCEINLINE void ClearBufferiv(GLenum Buffer, GLint DrawBufferIndex, const GLint* Value) { glClearBufferiv(Buffer, DrawBufferIndex, Value); } static FORCEINLINE void ClearDepth(GLdouble Depth) { glClearDepthf(Depth); } static FORCEINLINE void TexImage3D(GLenum Target, GLint Level, GLint InternalFormat, GLsizei Width, GLsizei Height, GLsizei Depth, GLint Border, GLenum Format, GLenum Type, const GLvoid* PixelData) { glTexImage3D(Target, Level, InternalFormat, Width, Height, Depth, Border, Format, Type, PixelData); } static FORCEINLINE void CompressedTexImage3D(GLenum Target, GLint Level, GLenum InternalFormat, GLsizei Width, GLsizei Height, GLsizei Depth, GLint Border, GLsizei ImageSize, const GLvoid* PixelData) { glCompressedTexImage3D(Target, Level, InternalFormat, Width, Height, Depth, Border, ImageSize, PixelData); } static FORCEINLINE void CompressedTexSubImage2D(GLenum Target, GLint Level, GLsizei Width, GLsizei Height, GLenum Format, GLsizei ImageSize, const GLvoid* PixelData) { glCompressedTexSubImage2D(Target, Level, 0, 0, Width, Height, Format, ImageSize, PixelData); } static FORCEINLINE void TexImage2DMultisample(GLenum Target, GLsizei Samples, GLint InternalFormat, GLsizei Width, GLsizei Height, GLboolean FixedSampleLocations) UGL_REQUIRED_VOID static FORCEINLINE void TexBuffer(GLenum Target, GLenum InternalFormat, GLuint Buffer) { glTexBufferEXT(Target, InternalFormat, Buffer); } static FORCEINLINE void TexSubImage3D(GLenum Target, GLint Level, GLint XOffset, GLint YOffset, GLint ZOffset, GLsizei Width, GLsizei Height, GLsizei Depth, GLenum Format, GLenum Type, const GLvoid* PixelData) { glTexSubImage3D(Target, Level, XOffset, YOffset, ZOffset, Width, Height, Depth, Format, Type, PixelData); } static FORCEINLINE void CopyTexSubImage3D(GLenum Target, GLint Level, GLint XOffset, GLint YOffset, GLint ZOffset, GLint X, GLint Y, GLsizei Width, GLsizei Height) { glCopyTexSubImage3D(Target, Level, XOffset, YOffset, ZOffset, X, Y, Width, Height); } //ES lacks GetTexImage of any sort static FORCEINLINE void GetCompressedTexImage(GLenum Target, GLint Level, GLvoid* OutImageData) UGL_REQUIRED_VOID static FORCEINLINE void GetTexImage(GLenum Target, GLint Level, GLenum Format, GLenum Type, GLvoid* OutPixelData) UGL_REQUIRED_VOID static FORCEINLINE void CopyBufferSubData(GLenum ReadTarget, GLenum WriteTarget, GLintptr ReadOffset, GLintptr WriteOffset, GLsizeiptr Size) { glCopyBufferSubData(ReadTarget, WriteTarget, ReadOffset, WriteOffset, Size); } static FORCEINLINE void GenBuffers( GLsizei n, GLuint *buffers) { #if USE_OPENGL_NAME_CACHE if ( n < OPENGL_NAME_CACHE_SIZE - NextBufferName) { FMemory::Memcpy( buffers, &BufferNamesCache[NextBufferName], sizeof(GLuint)*n); NextBufferName += n; } else { if ( n >= OPENGL_NAME_CACHE_SIZE) { glGenBuffers( n, buffers); } else { GLsizei Leftover = OPENGL_NAME_CACHE_SIZE - NextBufferName; FMemory::Memcpy( buffers, &BufferNamesCache[NextBufferName], sizeof(GLuint)*Leftover); glGenBuffers( OPENGL_NAME_CACHE_SIZE, BufferNamesCache); n -= Leftover; buffers += Leftover; FMemory::Memcpy( buffers, BufferNamesCache, sizeof(GLuint)*n); NextBufferName = n; } } #else glGenBuffers( n, buffers); #endif } static FORCEINLINE void GenTextures( GLsizei n, GLuint *textures) { #if USE_OPENGL_NAME_CACHE if ( n < OPENGL_NAME_CACHE_SIZE - NextTextureName) { FMemory::Memcpy( textures, &TextureNamesCache[NextTextureName], sizeof(GLuint)*n); NextTextureName += n; } else { if ( n >= OPENGL_NAME_CACHE_SIZE) { glGenTextures( n, textures); } else { GLsizei Leftover = OPENGL_NAME_CACHE_SIZE - NextTextureName; FMemory::Memcpy( textures, &TextureNamesCache[NextTextureName], sizeof(GLuint)*Leftover); glGenTextures( OPENGL_NAME_CACHE_SIZE, TextureNamesCache); n -= Leftover; textures += Leftover; FMemory::Memcpy( textures, TextureNamesCache, sizeof(GLuint)*n); NextTextureName = n; } } #else glGenTextures( n, textures); #endif } static FORCEINLINE void CompressedTexSubImage3D(GLenum Target, GLint Level, GLint XOffset, GLint YOffset, GLint ZOffset, GLsizei Width, GLsizei Height, GLsizei Depth, GLenum Format, GLsizei ImageSize, const GLvoid* PixelData) { glCompressedTexSubImage3D( Target, Level, XOffset, YOffset, ZOffset, Width, Height, Depth, Format, ImageSize, PixelData); } static FORCEINLINE void GenerateMipmap( GLenum Target ) { glGenerateMipmap( Target); } static FORCEINLINE const ANSICHAR* GetStringIndexed(GLenum Name, GLuint Index) { return (const ANSICHAR*)glGetStringi(Name, Index); } static FORCEINLINE GLuint GetMajorVersion() { return MajorVersion; } static FORCEINLINE GLuint GetMinorVersion() { return MinorVersion; } // From FOpenGL4 static FORCEINLINE void BlendFuncSeparatei(GLuint Buf, GLenum SrcRGB, GLenum DstRGB, GLenum SrcAlpha, GLenum DstAlpha) { glBlendFuncSeparateiEXT(Buf, SrcRGB, DstRGB, SrcAlpha, DstAlpha); } static FORCEINLINE void BlendEquationSeparatei(GLuint Buf, GLenum ModeRGB, GLenum ModeAlpha) { glBlendEquationSeparateiEXT(Buf, ModeRGB, ModeAlpha); } static FORCEINLINE void BlendFunci(GLuint Buf, GLenum Src, GLenum Dst) { glBlendFunciEXT(Buf, Src, Dst); } static FORCEINLINE void BlendEquationi(GLuint Buf, GLenum Mode) { glBlendEquationiEXT(Buf, Mode); } static FORCEINLINE void PatchParameteri(GLenum Pname, GLint Value) { glPatchParameteriEXT(Pname, Value); } static FORCEINLINE void BindImageTexture(GLuint Unit, GLuint Texture, GLint Level, GLboolean Layered, GLint Layer, GLenum Access, GLenum Format) { glBindImageTexture(Unit, Texture, Level, Layered, Layer, Access, Format); } static FORCEINLINE void DispatchCompute(GLuint NumGroupsX, GLuint NumGroupsY, GLuint NumGroupsZ) { glDispatchCompute(NumGroupsX, NumGroupsY, NumGroupsZ); } static FORCEINLINE void DispatchComputeIndirect(GLintptr Offset) { glDispatchComputeIndirect(Offset); } static FORCEINLINE void MemoryBarrier(GLbitfield Barriers) { glMemoryBarrier(Barriers); } static FORCEINLINE void DrawArraysIndirect (GLenum Mode, const void *Offset) { glDrawArraysIndirect( Mode, Offset); } static FORCEINLINE void DrawElementsIndirect (GLenum Mode, GLenum Type, const void *Offset) { glDrawElementsIndirect( Mode, Type, Offset); } static FORCEINLINE void BindVertexBuffer(GLuint BindingIndex, GLuint Buffer, GLintptr Offset, GLsizei Stride) { glBindVertexBuffer(BindingIndex, Buffer, Offset, Stride); } static FORCEINLINE void VertexAttribFormat(GLuint AttribIndex, GLint Size, GLenum Type, GLboolean Normalized, GLuint RelativeOffset) { glVertexAttribFormat(AttribIndex, Size, Type, Normalized, RelativeOffset); } static FORCEINLINE void VertexAttribIFormat(GLuint AttribIndex, GLint Size, GLenum Type, GLuint RelativeOffset) { glVertexAttribIFormat(AttribIndex, Size, Type, RelativeOffset); } static FORCEINLINE void VertexAttribBinding(GLuint AttribIndex, GLuint BindingIndex) { glVertexAttribBinding(AttribIndex, BindingIndex); } static FORCEINLINE void VertexBindingDivisor(GLuint BindingIndex, GLuint Divisor) { glVertexBindingDivisor(BindingIndex, Divisor); } static FORCEINLINE void TextureView(GLuint ViewName, GLenum ViewTarget, GLuint SrcName, GLenum InternalFormat, GLuint MinLevel, GLuint NumLevels, GLuint MinLayer, GLuint NumLayers) { glTextureViewEXT(ViewName, ViewTarget, SrcName, InternalFormat, MinLevel, NumLevels, MinLayer, NumLayers); } static FORCEINLINE bool TimerQueryDisjoint() { bool Disjoint = false; if (bTimerQueryCanBeDisjoint) { GLint WasDisjoint = 0; glGetIntegerv(GL_GPU_DISJOINT_EXT, &WasDisjoint); Disjoint = (WasDisjoint != 0); } return Disjoint; } static FORCEINLINE GLint GetMaxComputeTextureImageUnits() { check(MaxComputeTextureImageUnits != -1); return MaxComputeTextureImageUnits; } static FORCEINLINE GLint GetMaxComputeUniformComponents() { check(MaxComputeUniformComponents != -1); return MaxComputeUniformComponents; } static FORCEINLINE ERHIFeatureLevel::Type GetFeatureLevel() { // Should this support a commandline forced ES2? return bES2Fallback ? ERHIFeatureLevel::ES2 : ERHIFeatureLevel::SM5; } static FORCEINLINE EShaderPlatform GetShaderPlatform() { // Should this support a commandline forced ES2? return bES2Fallback ? SP_OPENGL_ES2 : SP_OPENGL_ES31_EXT; } static FORCEINLINE FString GetAdapterName() { return ANSI_TO_TCHAR((const ANSICHAR*)glGetString(GL_RENDERER)); } static FPlatformOpenGLDevice* CreateDevice() UGL_REQUIRED(NULL) static FPlatformOpenGLContext* CreateContext( FPlatformOpenGLDevice* Device, void* WindowHandle ) UGL_REQUIRED(NULL) static void ProcessQueryGLInt(); static void ProcessExtensions(const FString& ExtensionsString); static FORCEINLINE int32 GetReadHalfFloatPixelsEnum() { return GL_HALF_FLOAT; } protected: static GLsizei NextTextureName; static GLuint TextureNamesCache[OPENGL_NAME_CACHE_SIZE]; static GLsizei NextBufferName; static GLuint BufferNamesCache[OPENGL_NAME_CACHE_SIZE]; static GLint MaxComputeTextureImageUnits; static GLint MaxComputeUniformComponents; static GLint MajorVersion; static GLint MinorVersion; static GLint TimestampQueryBits; static bool bDebugContext; static bool bSupportsTessellation; static bool bSupportsTextureView; static bool bSupportsSeparateAlphaBlend; static bool bES2Fallback; /** GL_OES_vertex_array_object */ static bool bSupportsVertexArrayObjects; /** GL_OES_depth_texture */ static bool bSupportsDepthTexture; /** GL_OES_mapbuffer */ static bool bSupportsMapBuffer; /** GL_ARB_occlusion_query2, GL_EXT_occlusion_query_boolean */ static bool bSupportsOcclusionQueries; /** GL_OES_rgb8_rgba8 */ static bool bSupportsRGBA8; /** GL_APPLE_texture_format_BGRA8888 */ static bool bSupportsBGRA8888; /** GL_OES_vertex_half_float */ static bool bSupportsVertexHalfFloat; /** GL_EXT_discard_framebuffer */ static bool bSupportsDiscardFrameBuffer; /** GL_EXT_sRGB */ static bool bSupportsSGRB; /** GL_NV_texture_compression_s3tc, GL_EXT_texture_compression_s3tc */ static bool bSupportsDXT; /** GL_IMG_texture_compression_pvrtc */ static bool bSupportsPVRTC; /** GL_ATI_texture_compression_atitc, GL_AMD_compressed_ATC_texture */ static bool bSupportsATITC; /** GL_OES_compressed_ETC1_RGB8_texture */ static bool bSupportsETC1; /** OpenGL ES 3.0 profile */ static bool bSupportsETC2; /** GL_OES_texture_float */ static bool bSupportsTextureFloat; /** GL_OES_texture_half_float */ static bool bSupportsTextureHalfFloat; /** GL_EXT_color_buffer_half_float */ static bool bSupportsColorBufferHalfFloat; /** GL_NV_image_formats */ static bool bSupportsNvImageFormats; /** GL_EXT_shader_framebuffer_fetch */ static bool bSupportsShaderFramebufferFetch; /** GL_ARM_shader_framebuffer_fetch_depth_stencil */ static bool bSupportsShaderDepthStencilFetch; /** GL_EXT_MULTISAMPLED_RENDER_TO_TEXTURE */ static bool bSupportsMultisampledRenderToTexture; /** GL_FRAGMENT_SHADER, GL_LOW_FLOAT */ static int ShaderLowPrecision; /** GL_FRAGMENT_SHADER, GL_MEDIUM_FLOAT */ static int ShaderMediumPrecision; /** GL_FRAGMENT_SHADER, GL_HIGH_FLOAT */ static int ShaderHighPrecision; /** GL_NV_framebuffer_blit */ static bool bSupportsNVFrameBufferBlit; /** GL_OES_packed_depth_stencil */ static bool bSupportsPackedDepthStencil; /** textureCubeLodEXT */ static bool bSupportsTextureCubeLodEXT; /** GL_EXT_shader_texture_lod */ static bool bSupportsShaderTextureLod; /** textureCubeLod */ static bool bSupportsShaderTextureCubeLod; /** GL_APPLE_copy_texture_levels */ static bool bSupportsCopyTextureLevels; /** GL_EXT_texture_storage */ static bool bSupportsTextureStorageEXT; /** GL_EXT_disjoint_timer_query or GL_NV_timer_query*/ static bool bSupportsDisjointTimeQueries; /** Some timer query implementations are never disjoint */ static bool bTimerQueryCanBeDisjoint; /** GL_NV_timer_query for timestamp queries */ static bool bSupportsNvTimerQuery; public: /* This is a hack to remove the calls to "precision sampler" defaults which are produced by the cross compiler however don't compile on some android platforms */ static bool bRequiresDontEmitPrecisionForTextureSamplers; /* Some android platforms require textureCubeLod to be used some require textureCubeLodEXT however they either inconsistently or don't use the GL_TextureCubeLodEXT extension definition */ static bool bRequiresTextureCubeLodEXTToTextureCubeLodDefine; /* This is a hack to remove the gl_FragCoord if shader will fail to link if exceeding the max varying on android platforms */ static bool bRequiresGLFragCoordVaryingLimitHack; /* This hack fixes an issue with SGX540 compiler which can get upset with some operations that mix highp and mediump */ static bool bRequiresTexture2DPrecisionHack; }; // yes they are different between the ES2 extension and ES3.x and GL3.x core static_assert(GL_HALF_FLOAT_OES != GL_HALF_FLOAT, "GL_HALF_FLOAT_OES and GL_HALF_FLOAT should not be #defined to the same value"); #ifndef GL_FILL #define GL_FILL 0x1B02 #endif #ifndef GL_SAMPLER_1D_SHADOW #define GL_SAMPLER_1D_SHADOW 0x8B61 #endif #ifndef GL_DOUBLE #define GL_DOUBLE 0x140A #endif #ifndef GL_SAMPLER_1D #define GL_SAMPLER_1D 0x8B5D #endif #ifndef GL_RGBA16 #define GL_RGBA16 0x805B #endif #ifndef GL_RG16 #define GL_RG16 0x822C #endif #ifndef GL_SAMPLES_PASSED #define GL_SAMPLES_PASSED 0x8914 #endif #ifndef GL_POLYGON_OFFSET_LINE #define GL_POLYGON_OFFSET_LINE 0x2A02 #endif #ifndef GL_POLYGON_OFFSET_POINT #define GL_POLYGON_OFFSET_POINT 0x2A01 #endif #ifndef GL_TEXTURE_LOD_BIAS #define GL_TEXTURE_LOD_BIAS 0x8501 #endif #ifndef GL_R16 #define GL_R16 0x822A #endif #ifndef GL_POINT #define GL_POINT 0x1B00 #endif #ifndef GL_LINE #define GL_LINE 0x1B01 #endif #ifndef GL_TEXTURE_BUFFER #define GL_TEXTURE_BUFFER GL_TEXTURE_BUFFER_EXT #endif #ifndef GL_DEBUG_SOURCE_OTHER_ARB #define GL_DEBUG_SOURCE_OTHER_ARB GL_DEBUG_SOURCE_OTHER_KHR #endif #ifndef GL_DEBUG_SOURCE_API_ARB #define GL_DEBUG_SOURCE_API_ARB GL_DEBUG_SOURCE_API_KHR #endif #ifndef GL_DEBUG_TYPE_ERROR_ARB #define GL_DEBUG_TYPE_ERROR_ARB GL_DEBUG_TYPE_ERROR_KHR #endif #ifndef GL_DEBUG_TYPE_OTHER_ARB #define GL_DEBUG_TYPE_OTHER_ARB GL_DEBUG_TYPE_OTHER_KHR #endif #ifndef GL_DEBUG_TYPE_MARKER #define GL_DEBUG_TYPE_MARKER GL_DEBUG_TYPE_MARKER_KHR #endif #ifndef GL_DEBUG_TYPE_PUSH_GROUP #define GL_DEBUG_TYPE_PUSH_GROUP GL_DEBUG_TYPE_PUSH_GROUP_KHR #endif #ifndef GL_DEBUG_TYPE_POP_GROUP #define GL_DEBUG_TYPE_POP_GROUP GL_DEBUG_TYPE_POP_GROUP_KHR #endif #ifndef GL_DEBUG_SEVERITY_HIGH_ARB #define GL_DEBUG_SEVERITY_HIGH_ARB GL_DEBUG_SEVERITY_HIGH_KHR #endif #ifndef GL_DEBUG_SEVERITY_LOW_ARB #define GL_DEBUG_SEVERITY_LOW_ARB GL_DEBUG_SEVERITY_LOW_KHR #endif #ifndef GL_DEBUG_SEVERITY_NOTIFICATION #define GL_DEBUG_SEVERITY_NOTIFICATION GL_DEBUG_SEVERITY_NOTIFICATION_KHR #endif #ifndef GL_GEOMETRY_SHADER #define GL_GEOMETRY_SHADER GL_GEOMETRY_SHADER_EXT #endif #ifndef GL_FRAMEBUFFER_SRGB #define GL_FRAMEBUFFER_SRGB GL_FRAMEBUFFER_SRGB_EXT #endif
bca94b4f80bc02d8dbbf9ee297f23892d175f162
8a786f0133a4fefef0a82d2489369a461eeb3e06
/tools/UT99CampaignRoster/src/UT99CampaignRoster/Roster/RosterContainer.cpp
db88c10ecf07a3559a7bb1f6330fac3d7db28cfd
[]
no_license
orb3b/UTManager
afd6efbd91165e062f0c3966a9f0bc3a1d3a8bdb
30e2391dc8071fe00717e1722a2eaf646cb79116
refs/heads/master
2021-01-22T12:12:08.470588
2014-08-17T12:28:21
2014-08-17T12:28:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,442
cpp
#include "RosterContainer.h" RosterContainer::RosterContainer(QObject *parent) : RosterObject(parent) { } RosterContainer::~RosterContainer() { clearCollection(); } void RosterContainer::clearCollection() { clearError(); foreach (RosterObject *obj, m_memberList) { disconnect(obj, SIGNAL(destroyed(QObject*)), this, SLOT(onMemberDestroyed(QObject*))); delete obj; } m_memberList.clear(); } bool RosterContainer::addMember(RosterObject *member) { // Currently its's simple adding, no sorting clearError(); if (!member) return postError("Can't add null member to collection"); connect(member, SIGNAL(destroyed(QObject*)), SLOT(onMemberDestroyed(QObject*))); m_memberList.append(member); return true; } bool RosterContainer::removeMember(RosterObject *member) { clearError(); if (!m_memberList.contains(member)) return postError("Can't remove member which don't exist in collection"); disconnect(member, SIGNAL(destroyed(QObject*)), this, SLOT(onMemberDestroyed(QObject*))); delete member; m_memberList.removeAll(member); return true; } QList<RosterObject *> &RosterContainer::data() { return m_memberList; } const QList<RosterObject *> RosterContainer::data() const { return m_memberList; } void RosterContainer::onMemberDestroyed(QObject *obj) { m_memberList.removeAll(qobject_cast<RosterObject*>(obj)); }
76e234ebb570ef2b561d5d663fd3608244be1b7c
509eb91ac1d5afca1f28791508ec9d787694e6c1
/cyberRT-dependency/eProsima_FastRTPS-1.5.0-Linux/src/cpp/rtps/writer/RTPSWriterCollector.h
566d06b8363cff0a17908a15dd9878d4e01b5928
[ "Apache-2.0" ]
permissive
Allenhe123/cyberRT-x86
5d116dbd89911b2d54fb6cd8ad82a9e3d6e69557
1cdc0414cbf3886d9a989c5b807694e2039f8f99
refs/heads/master
2022-03-15T02:48:34.806443
2022-02-11T07:21:23
2022-02-11T07:21:23
232,505,897
16
9
null
null
null
null
UTF-8
C++
false
false
3,723
h
// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @file RTPSWriterCollector.h */ #ifndef _RTPS_WRITER_RTPSWRITERCOLLECTOR_H_ #define _RTPS_WRITER_RTPSWRITERCOLLECTOR_H_ #include <fastrtps/rtps/common/SequenceNumber.h> #include <fastrtps/rtps/common/FragmentNumber.h> #include <fastrtps/rtps/common/CacheChange.h> #include <vector> #include <cassert> namespace eprosima { namespace fastrtps { namespace rtps { template<class T> class RTPSWriterCollector { public: struct Item { Item(SequenceNumber_t seqNum, FragmentNumber_t fragNum, CacheChange_t* c) : sequenceNumber(seqNum), fragmentNumber(fragNum), cacheChange(c) { assert(seqNum == c->sequenceNumber); } //! Sequence number of the CacheChange. SequenceNumber_t sequenceNumber; /*! * Fragment number of the represented fragment. * If value is zero, it represents a whole change. */ FragmentNumber_t fragmentNumber; CacheChange_t* cacheChange; mutable std::vector<T> remoteReaders; }; struct ItemCmp { bool operator()(const Item& a, const Item& b) const { if(a.sequenceNumber < b.sequenceNumber) return true; else if(a.sequenceNumber == b.sequenceNumber) if(a.fragmentNumber < b.fragmentNumber) return true; return false; } }; typedef std::set<Item, ItemCmp> ItemSet; void add_change(CacheChange_t* change, const T& remoteReader, const FragmentNumberSet_t optionalFragmentsNotSent) { if(change->getFragmentSize() > 0) { for(auto sn = optionalFragmentsNotSent.get_begin(); sn != optionalFragmentsNotSent.get_end(); ++sn) { assert(*sn <= change->getDataFragments()->size()); auto it = mItems_.emplace(change->sequenceNumber, *sn, change); it.first->remoteReaders.push_back(remoteReader); } } else { auto it = mItems_.emplace(change->sequenceNumber, 0, change); it.first->remoteReaders.push_back(remoteReader); } } bool empty() { return mItems_.empty(); } size_t size() { return mItems_.size(); } Item pop() { auto it = mItems_.begin(); Item ret = *it; mItems_.erase(it); return ret; } void clear() { return mItems_.clear(); } ItemSet& items() { return mItems_; } private: ItemSet mItems_; }; } // namespace rtps } // namespace fastrtps } // namespace eprosima #endif // _RTPS_WRITER_RTPSWRITERCOLLECTOR_H_
f296e7d7e73ee3389d9aaea407b1da80ea2d1f45
974d2bf41fdf9e68feaac1ee696e6635097afc94
/ariac_plugins/src/assembly_lock_plugin.cpp
b0f5345f3bcb11f6c8a4ccfab9e9cedf3623dd5e
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
usnistgov/ARIAC
82c56593f30f7b031350b2cacb8a3b882b76d92a
66a0470be3d7f92201ff40ddeb5f74de14659ba1
refs/heads/ariac2023
2023-09-01T20:59:11.343777
2023-05-22T16:29:50
2023-05-22T16:29:50
236,078,087
98
68
NOASSERTION
2023-05-25T20:24:19
2020-01-24T20:28:25
C++
UTF-8
C++
false
false
8,152
cpp
/* This software was developed by employees of the National Institute of Standards and Technology (NIST), an agency of the Federal Government. Pursuant to title 17 United States Code Section 105, works of NIST employees are not subject to copyright protection in the United States and are considered to be in the public domain. Permission to freely use, copy, modify, and distribute this software and its documentation without fee is hereby granted, provided that this notice and disclaimer of warranty appears in all copies. The software is provided 'as is' without any warranty of any kind, either expressed, implied, or statutory, including, but not limited to, any warranty that the software will conform to specifications, any implied warranties of merchantability, fitness for a particular purpose, and freedom from infringement, and any warranty that the documentation will conform to the software, or any warranty that the software will be error free. In no event shall NIST be liable for any damages, including, but not limited to, direct, indirect, special or consequential damages, arising out of, resulting from, or in any way connected with this software, whether or not based upon warranty, contract, tort, or otherwise, whether or not injury was sustained by persons or property or otherwise, and whether or not loss was sustained from, or arose out of the results of, or use of, the software or services provided hereunder. Distributions of NIST software should also include copyright and licensing statements of any third-party software that are legally bundled with the code in compliance with the conditions of those licenses. */ #include <gazebo/common/common.hh> #include <gazebo/physics/Model.hh> #include <gazebo/physics/World.hh> #include <gazebo/physics/Link.hh> #include <gazebo/physics/PhysicsEngine.hh> #include <gazebo/physics/ContactManager.hh> #include <gazebo/physics/Collision.hh> #include <gazebo/transport/Subscriber.hh> #include <gazebo/transport/Publisher.hh> #include <gazebo/transport/Node.hh> #include <ignition/math.hh> #include <ariac_plugins/assembly_lock_plugin.hpp> #include <map> #include <memory> namespace ariac_plugins { /// Class to hold private data members (PIMPL pattern) class AssemblyLockPrivate { public: /// Connection to world update event. Callback is called while this is alive. gazebo::event::ConnectionPtr update_connection_; bool part_attached_; bool in_contact_; gazebo::physics::LinkPtr assembly_surface_link_; gazebo::transport::NodePtr gznode_; gazebo::transport::SubscriberPtr contact_sub_; gazebo::transport::PublisherPtr attach_pub_; gazebo::common::Timer timer_; int rate_; gazebo::physics::ModelPtr model_; gazebo::physics::JointPtr assembly_joint_; gazebo::physics::CollisionPtr model_collision_; gazebo::physics::ModelPtr model_to_attach_; std::map<std::string, gazebo::physics::CollisionPtr> collisions_; std::string assembly_part_type_; bool CheckModelContact(ConstContactsPtr &); void AttachJoint(); void PublishState(); }; AssemblyLock::AssemblyLock() : impl_(std::make_unique<AssemblyLockPrivate>()) { } AssemblyLock::~AssemblyLock() { } void AssemblyLock::Load(gazebo::physics::ModelPtr model, sdf::ElementPtr sdf) { impl_->model_ = model; gazebo::physics::WorldPtr world = impl_->model_->GetWorld(); impl_->assembly_joint_ = world->Physics()->CreateJoint("fixed", impl_->model_); impl_->assembly_joint_->SetName("assembly_fixed_joints"); // Initialize a gazebo node and subscribe to the contacts for the assembly surface impl_->gznode_ = gazebo::transport::NodePtr(new gazebo::transport::Node()); impl_->gznode_->Init(impl_->model_->GetWorld()->Name()); std::string part_type = sdf->GetElement("assembly_part_type")->Get<std::string>(); std::string link_name = part_type + "_contact"; std::string model_name = model->GetName(); impl_->assembly_surface_link_ = impl_->model_->GetLink(link_name); impl_->assembly_part_type_ = part_type; impl_->part_attached_ = false; std::string topic = "/gazebo/world/" + model_name + "/" + link_name + "/" + part_type + "_contact_sensor/contacts"; impl_->contact_sub_ = impl_->gznode_->Subscribe(topic, &AssemblyLock::OnContact, this); std::string attach_topic = "/gazebo/world/" + model_name + "/" + link_name + "/" + part_type + "_attached"; impl_->rate_ = 30; impl_->attach_pub_ = impl_->gznode_->Advertise<gazebo::msgs::Pose>(attach_topic, 100, impl_->rate_); impl_->timer_.Reset(); impl_->timer_.Start(); // Create a connection so the OnUpdate function is called at every simulation // iteration. Remove this call, the connection and the callback if not needed. impl_->update_connection_ = gazebo::event::Events::ConnectWorldUpdateBegin( std::bind(&AssemblyLock::OnUpdate, this)); } void AssemblyLock::OnUpdate() { if (!impl_->part_attached_ && impl_->in_contact_) { impl_->AttachJoint(); } auto elapsed = impl_->timer_.GetElapsed(); if (elapsed.Double() > (1. / impl_->rate_)) { impl_->PublishState(); impl_->timer_.Reset(); impl_->timer_.Start(); } } void AssemblyLock::OnContact(ConstContactsPtr &_msg) { impl_->in_contact_ = impl_->CheckModelContact(_msg); } void AssemblyLockPrivate::AttachJoint() { gzdbg << "Attaching Part" << std::endl; assembly_joint_->Load(assembly_surface_link_, model_collision_->GetLink(), ignition::math::Pose3d()); assembly_joint_->Init(); part_attached_ = true; } bool AssemblyLockPrivate::CheckModelContact(ConstContactsPtr &msg) { std::string part_in_contact; int min_contacts = 4; for (int i = 0; i < msg->contact_size(); ++i) { // Find out which contact is the plugin's link if (msg->contact(i).collision1().find("insert") != std::string::npos) { part_in_contact = msg->contact(i).collision2(); } else if (msg->contact(i).collision2().find("insert") != std::string::npos) { part_in_contact = msg->contact(i).collision1(); } else { continue; } // Ignore if part is incorrect type if (part_in_contact.find(assembly_part_type_) >= std::string::npos) { gzdbg << "incorrect part type" << std::endl; continue; } // Check number of contacts if (!msg->contact(i).position_size() > min_contacts) { gzdbg << "not enough contacts" << std::endl; continue; } model_collision_ = boost::dynamic_pointer_cast<gazebo::physics::Collision>(model_->GetWorld()->EntityByName(part_in_contact)); model_to_attach_ = model_collision_->GetModel(); return true; /* Seems to cause issues for sensor insertion //Check normals std::vector<bool> aligned; for (int j = 0; j < msg->contact(i).normal_size(); ++j){ ignition::math::Vector3d contact_normal = gazebo::msgs::ConvertIgn(msg->contact(i).normal(j)); ignition::math::Vector3d assembly_normal = assembly_surface_link_->WorldPose().Rot().RotateVector(ignition::math::Vector3d(0, 0, 1)); double alignment = assembly_normal.Dot(contact_normal); // RCLCPP_INFO_STREAM(ros_node_->get_logger(), "Alignment: " << alignment); if (std::abs(alignment) > 0.95) { aligned.push_back(true); } else{ aligned.push_back(false); } } if (std::all_of(aligned.begin(), aligned.end(), [](bool v) { return v; })){ return true; } */ } return false; } void AssemblyLockPrivate::PublishState() { auto msg = gazebo::msgs::Pose(); if (part_attached_) { msg = gazebo::msgs::Convert(model_to_attach_->RelativePose()); } else { auto blank_pose = ignition::math::Pose3d(); msg = gazebo::msgs::Convert(blank_pose); } attach_pub_->Publish(msg); } // Register this plugin with the simulator GZ_REGISTER_MODEL_PLUGIN(AssemblyLock) } // namespace ariac_plugins
e59643210aae0004b6194a7da694564659018705
a5da867210a2716fa9765ba00b7498cef4e10979
/DdyLib.wx/Ctrl/x_DataViewCtrl_1/MyDataViewVirtualListModel.cpp
7bab5a9b9345ebd4fe1b84253b43d79aef47d07b
[]
no_license
yasriady/wxProjects
65055569af4c93d9deb3521415bf02aef08899cf
26a758710712f0ed73c53b0e587d50df8ba25f78
refs/heads/master
2021-01-10T21:58:31.576665
2015-09-10T23:13:19
2015-09-10T23:13:19
41,183,038
0
0
null
null
null
null
UTF-8
C++
false
false
2,341
cpp
#include "MyDataViewVirtualListModel.h" /* * MyDataViewVirtualListModel.cpp * * Created on: Dec 30, 2014 * Author: dedy */ MyDataViewVirtualListModel::MyDataViewVirtualListModel(AppDB* db, wxString table, wxString columns, wxString where, wxString orderby) { m_db = db; m_table = table; m_columns = columns; m_where = where; m_orderby = orderby; m_row_cnt = 0; m_column_cnt = 0; } MyDataViewVirtualListModel::~MyDataViewVirtualListModel() { // TODO Auto-generated destructor stub } // --------------------------------------------------------------------------- void MyDataViewVirtualListModel::GetValueByRow(wxVariant& variant, unsigned row, unsigned col) const { //variant = wxString::Format( "Row %d Col %d", row, col ); static wxArrayString array; if (col == 0) { //array = m_db->getValueByRow2(row, m_table, m_columns, m_where, m_orderby); //const wxArrayString &arr2 = *m_db->getValueByRow3(row, m_table, m_columns, m_where, m_orderby); //array = arr2; //array = *m_db->getValueByRow3(row, m_table, m_columns, m_where, m_orderby); array = m_db->GetRecord(m_columns, m_table, m_where, m_orderby, 1, row); } wxString s; //s = m_db->getValueByRow(row, col, m_table, m_columns, m_where, m_orderby); //variant = s; s = array.Item(col); variant = s; } bool MyDataViewVirtualListModel::SetValueByRow(const wxVariant& variant, unsigned row, unsigned col) { return true; } unsigned int MyDataViewVirtualListModel::GetColumnCount() const { return m_column_cnt; } wxString MyDataViewVirtualListModel::GetColumnType(unsigned int col) const { return "string"; } // --------------------------------------------------------------------------- void MyDataViewVirtualListModel::GetData() { m_columns_arr = m_db->makeColumns(m_table, m_columns); m_row_cnt = m_db->GetRecordCount(m_table, m_where); } void MyDataViewVirtualListModel::x_UpdateData() { m_row_cnt = m_db->GetRecordCount(m_table, m_where); wxDataViewVirtualListModel::Reset(m_row_cnt); } // Refresh/reset datamodel void MyDataViewVirtualListModel::Reset() { m_row_cnt = m_db->GetRecordCount(m_table, m_where); wxDataViewVirtualListModel::Reset(m_row_cnt); } void MyDataViewVirtualListModel::Resort(wxString col_title) { m_orderby = col_title; m_db->CreateIndex(m_table, col_title); wxDataViewVirtualListModel::Resort(); }
93f641473fccb4233eb45d39177dbf5a54a0c11f
23e0cee8faabe23dc2d34a3862daffa85fb63a4f
/476-ParallelProgramming/5-MergeSort/SortingTimes.cc
48bf2a9272635093df5df451f5b53526b81d6b61
[]
no_license
smzelek/schoolwork
5225bebb3720e5f5ccde25a94ed8ecc7354ae50d
ff6e11599c829b427901b4a98f6860d1e741b28e
refs/heads/main
2022-07-10T02:27:38.144755
2017-04-19T21:23:52
2017-04-19T21:23:52
87,887,865
0
0
null
null
null
null
UTF-8
C++
false
false
6,301
cc
/************************************************************/ /* Author : Steven Zelek Course : CSCI 476 Assignment : Lab #5 Description: */ /************************************************************/ // System includes #include <iostream> #include <vector> #include <algorithm> #include <random> #include <functional> #include <thread> /************************************************************/ // Local includes #include "Timer.hpp" /************************************************************/ // Using declarations using std::cout; using std::cin; using std::endl; using std::vector; using std::iterator; /************************************************************/ // Function prototypes/global vars/typedefs typedef vector<int>::iterator iter; void getUserValues (unsigned& vectorSize, unsigned& cutoff, unsigned& maxDepth); void printSummary (double parallelTime, double serialTime, double stdTime, bool parallelOk, bool serialOk); void fillRandomVector (vector<int>& v, unsigned numElements); void printVector (const vector<int>& vec); int generateInRange (int lower, int upper); void parallelMergeSort (vector<int>& v, iter first, iter last, unsigned cutoff, unsigned depth, unsigned maxDepth); void serialMergeSort (vector<int>& v, iter first, iter last, unsigned cutoff); void serialInsertionSort (vector<int>& v, iter first, iter last); /************************************************************/ int main (int argc, char* argv[]) { unsigned vectorSize, cutoff, maxDepth; getUserValues (vectorSize, cutoff, maxDepth); //randomly generate vectorSize nums, duplicate vector twice vector<int> numsSortedByPMS; fillRandomVector (numsSortedByPMS, vectorSize); vector<int> numsSortedBySMS (numsSortedByPMS); vector<int> numsSortedBySTD (numsSortedByPMS); double parallelTime, serialTime, stdTime; //time each of the three sorts on a copy of the random array Timer<> timer; parallelMergeSort (numsSortedByPMS, numsSortedByPMS.begin (), numsSortedByPMS.end (), cutoff, 0, maxDepth); timer.stop (); parallelTime = timer.getElapsedMs (); timer.start (); serialMergeSort (numsSortedBySMS, numsSortedBySMS.begin (), numsSortedBySMS.end (), cutoff); timer.stop (); serialTime = timer.getElapsedMs (); timer.start (); std::sort (numsSortedBySTD.begin (), numsSortedBySTD.end ()); timer.stop (); stdTime = timer.getElapsedMs (); //ensure both sort results match STD sort bool parallelOk = (numsSortedBySTD == numsSortedByPMS); bool serialOk = (numsSortedBySTD == numsSortedBySMS); //output formatted timings and whether sorts are correct printSummary (parallelTime, serialTime, stdTime, parallelOk, serialOk); return EXIT_SUCCESS; } /************************************************************/ void getUserValues (unsigned& vectorSize, unsigned& cutoff, unsigned& maxDepth) { cout << "N ==> "; cin >> vectorSize; cout << "Cutoff ==> "; cin >> cutoff; cout << "Depth ==> "; cin >> maxDepth; cout << endl; } /************************************************************/ void printSummary (double parallelTime, double serialTime, double stdTime, bool parallelOk, bool serialOk) { printf ("Parallel time: %.2f ms\n", parallelTime); printf ("Serial time: %.2f ms\n", serialTime); printf ("std::sort time: %.2f ms\n", stdTime); cout << "\nParallel ok? " << (parallelOk? "true" : "false") << endl; cout << "Serial ok? " << (serialOk? "true" : "false") << endl; } /************************************************************/ void parallelMergeSort (vector<int>& v, iter first, iter last, unsigned cutoff, unsigned depth, unsigned maxDepth) { unsigned numElements = std::distance (first, last); if (numElements <= cutoff) { serialInsertionSort (v, first, last); } else if (depth < maxDepth) { iter midpoint = first + numElements / 2; std::thread t1 (parallelMergeSort, std::ref (v), first, midpoint, cutoff, depth + 1, maxDepth); std::thread t2 (parallelMergeSort, std::ref (v), midpoint, last, cutoff, depth + 1, maxDepth); t1.join (); t2.join (); //https://en.wikipedia.org/wiki/Bitonic_sorter#Example_code //TODO: add bitonic parallel merge function std::inplace_merge (first, midpoint, last); } else { iter midpoint = first + numElements / 2; serialMergeSort (v, first, midpoint, cutoff); serialMergeSort (v, midpoint, last, cutoff); std::inplace_merge (first, midpoint, last); } } /************************************************************/ void serialMergeSort (vector<int>& v, iter first, iter last, unsigned cutoff) { unsigned numElements = std::distance (first, last); if (numElements <= cutoff) { serialInsertionSort (v, first, last); } else { iter midpoint = first + numElements / 2; serialMergeSort (v, first, midpoint, cutoff); serialMergeSort (v, midpoint, last, cutoff); std::inplace_merge (first, midpoint, last); } } /************************************************************/ void serialInsertionSort (vector<int>& v, iter first, iter last) { //slide elements down by 1 after finding place to insert for (iter i = first + 1; i != last; ++i) { int valToSort = *i; iter j = i - 1; while (valToSort < *j && j != first - 1) { *(j + 1) = *j; --j; } *(j + 1) = valToSort; } } /************************************************************/ int generateInRange (int lower, int upper) { //std::random_device rd; static std::mt19937 gen {0}; return gen() % (upper + 1 - lower) + lower; } /************************************************************/ void fillRandomVector (vector<int>& v, unsigned numElements) { v.reserve (numElements); std::generate_n (std::back_inserter (v), numElements, []() { return generateInRange (0, 999); }); } /************************************************************/ void printVector (const vector<int>& vec) { const std::string separator = ", "; std::string sep = ""; cout << "{ "; for (const auto& e : vec) { cout << sep << e; sep = separator; } cout << " }" << endl; } /************************************************************/ /************************************************************/
[ "Steven Zelek" ]
Steven Zelek
0597aaf5f1945bfd91728367bf094496376250f0
14c8b0ef6bf15f29bd5787c8136e0e382d74adea
/Dependencies/AllegroC++/include/alx/Keyboard.hpp
3e25ee2eefe117f372c8134af7b2eaa8eb712f2c
[]
no_license
zerodarkzone/Cage2D
ff6d83518ffd859826c7f4ddeeb5bd66fe8d1e1e
ddb4b2b4c2bd7500bdbf420791dd483d3d3bf04d
refs/heads/master
2020-12-10T04:30:08.391378
2017-03-02T06:44:34
2017-03-02T06:44:34
83,633,973
0
0
null
null
null
null
UTF-8
C++
false
false
428
hpp
#ifndef ALX_KEYBOARD_HPP #define ALX_KEYBOARD_HPP #include <alx/EventSource.hpp> namespace alx { /** Keyboard functions. */ class Keyboard { public: /** Returns the keyboard event source. @return the keyboard event source. */ static EventSource getEventSource() { return EventSource(al_get_keyboard_event_source(), false); } }; } //namespace alx #endif //ALX_KEYBOARD_HPP
d3e6f9a10a1901e9c6e8ecda9f0ef1c0e5a895d8
c6b95358dbba65b0ba8450b8179046a41fcf4c91
/signRecognition/moveMotors/moveMotors.ino
3186f09e9f1f983c2398804716f5e619474ce2fe
[]
no_license
kmvinayaka/ML_examples
b24221c1b1e2103b1b228399ef0c3591e6f3d4e6
6a5afa3a68a3a70bc55f9941d96064fcdb8ac42c
refs/heads/master
2020-06-11T10:39:42.441157
2020-02-05T18:11:41
2020-02-05T18:11:41
193,933,972
0
2
null
2020-01-28T22:48:52
2019-06-26T15:43:09
Python
UTF-8
C++
false
false
4,604
ino
// Import the Arduino Servo library #include <Servo.h> // servo motors #define pan 5 #define tilt 6 // connect motor controller pins to Arduino digital pins // right motor #define enA 11 #define in1 12 #define in2 13 // left motor #define enB 3 #define in4 2 #define in3 7 // Create a Servo object for each servo Servo panServo, tiltServo; // Common servo setup values int minPulse = 600; // minimum servo position, us (microseconds) int maxPulse = 2400; // maximum servo position, us // User input for servo and position int startbyte; // start byte, begin reading input int servo; // which servo to pulse? int pos; // servo angle 0-180 int currentPanPosition = 95; int currentTiltPosition = 45; int leftPWM = 0; int rightPWM = 0; int time = 0; void setup() { // Attach each Servo object to a digital pin panServo.attach(pan, minPulse, maxPulse); tiltServo.attach(tilt, minPulse, maxPulse); // Define start Servo angle position panServo.write(currentPanPosition); tiltServo.write(currentTiltPosition); // set all the motor control pins to outputs pinMode(enA, OUTPUT); pinMode(enB, OUTPUT); pinMode(in1, OUTPUT); pinMode(in2, OUTPUT); pinMode(in3, OUTPUT); pinMode(in4, OUTPUT); // Open the serial connection, 9600 baud Serial.begin(9600); } void loop() { // Wait for serial input (min 3 bytes in buffer) if (Serial.available() > 2 ) { // Read the first byte startbyte = Serial.read(); switch (startbyte) { case 255: movePanTilt(); break; case 254: //map values from serial between 1-255 leftPWM = Serial.read(); leftPWM = map(leftPWM, 0, 255, -255, 255); rightPWM = Serial.read(); rightPWM = map(rightPWM, 0, 255, -255, 255); move(leftPWM, rightPWM); break; } } } void movePanTilt() { // What servo to move servo = Serial.read(); if (servo == 1) { Serial.print("Change current angle of pan servo to: "); } else { Serial.print("Change current angle of tilt servo to: "); } // For which position pos = Serial.read(); Serial.print(pos); Serial.println(" degrees"); // Assign new position to appropriate servo switch (servo) { case 1: panServo.write(pos); break; case 2: tiltServo.write(pos); break; } } void move(int leftPWM, int rightPWM) { // stop the motors if (leftPWM == -1 && rightPWM == -1) { analogWrite(enA, 0); analogWrite(enB, 0); digitalWrite(in1, LOW); digitalWrite(in2, LOW); digitalWrite(in3, LOW); digitalWrite(in4, LOW); Serial.println("Stop the motors"); Serial.print("leftPWM: "); Serial.println(leftPWM); Serial.print("rightPWM: "); Serial.println(rightPWM); } // move stright else if (rightPWM > 0 && leftPWM > 0) { analogWrite(enA, rightPWM); analogWrite(enB, leftPWM); digitalWrite(in1, LOW); digitalWrite(in2, HIGH); digitalWrite(in3, LOW); digitalWrite(in4, HIGH); Serial.println("Move stright"); Serial.print("leftPWM: "); Serial.println(leftPWM); Serial.print("rightPWM: "); Serial.println(rightPWM); } // turn left on the point else if (rightPWM > 0 && leftPWM <= -1) { analogWrite(enA, rightPWM); analogWrite(enB, abs(leftPWM)); digitalWrite(in1, LOW); digitalWrite(in2, HIGH); digitalWrite(in3, HIGH); digitalWrite(in4, LOW); Serial.println("Turn left on the point"); Serial.print("leftPWM: "); Serial.println(leftPWM); Serial.print("rightPWM: "); Serial.println(rightPWM); } // turn right on the point else if (rightPWM <= -1 && leftPWM > 0) { analogWrite(enA, abs(rightPWM)); analogWrite(enB, leftPWM); digitalWrite(in1, HIGH); digitalWrite(in2, LOW); digitalWrite(in3, LOW); digitalWrite(in4, HIGH); Serial.println("Turn right on the point"); Serial.print("leftPWM: "); Serial.println(leftPWM); Serial.print("rightPWM: "); Serial.println(rightPWM); } // go back else if (rightPWM < -1 && leftPWM < -1) { analogWrite(enA, abs(rightPWM)); analogWrite(enB, abs(leftPWM)); digitalWrite(in1, HIGH); digitalWrite(in2, LOW); digitalWrite(in3, HIGH); digitalWrite(in4, LOW); Serial.println("Go back"); Serial.print("leftPWM: "); Serial.println(leftPWM); Serial.print("rightPWM: "); Serial.println(rightPWM); } else { Serial.println("Else statement"); Serial.print("leftPWM: "); Serial.println(leftPWM); Serial.print("rightPWM: "); Serial.println(rightPWM); } }
64e4932951dc7db867a6f239673d33ca71fe8cc5
9c273d9732d7335cc75d8fee559d4c410fce7075
/C++ stld prctice/StringFind.cpp
274bb12ff410b641d6552e9f07dbd39bc75431d4
[]
no_license
Md-Sanaul-Haque-Shanto/Practice-Session
740f731ce61bc4878f5a1154cda7aa076c89b639
4e7173112ced64eabfc7bc0d5470b562f214f349
refs/heads/master
2020-03-12T11:41:32.458454
2018-06-10T18:13:44
2018-06-10T18:13:44
130,602,414
0
0
null
null
null
null
UTF-8
C++
false
false
207
cpp
#include<bits/stdc++.h> using namespace std; const int mod = 1000000007; int main(){ int t; long long a; cin>>t; for(int i=1;i<=t;i++){ cin>>a; cout<<"Case "<<i<<": "<<a%mod<<endl; } }
4a0daddc660501af4276150221efd2f451aac8d7
edc87421c947454a752592f6f2d01cfc2fe6a8d6
/src/test/arith_uint256_tests.cpp
204908798ae8ca1d1ed7e4dfdae0f2c4e5e9ebdd
[ "MIT" ]
permissive
smartinsider/cgencore
8d64acbfcaececea41cfc056ebeb79aef2f09b80
4ed6fd47303b08a241a26377e941276b4a7ea26e
refs/heads/master
2020-04-18T11:09:27.888199
2019-02-17T15:37:42
2019-02-17T15:37:42
167,490,245
1
0
null
null
null
null
UTF-8
C++
false
false
23,352
cpp
// Copyright (c) 2011-2013 The Bitcoin Core developers // Copyright (c) 2017 The PIVX developers // Copyright (c) 2017-2018 The HUZU developers // Copyright (c) 2018-2019 The ZIJA developers // Copyright (c) 2019 The CGEN developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/test/unit_test.hpp> #include <stdint.h> #include <sstream> #include <iomanip> #include <limits> #include <cmath> #include "uint256.h" #include "arith_uint256.h" #include <string> #include "version.h" BOOST_AUTO_TEST_SUITE(arith_uint256_tests) ///BOOST_FIXTURE_TEST_SUITE(arith_uint256_tests, BasicTestingSetup) /// Convert vector to arith_uint256, via uint256 blob inline arith_uint256 arith_uint256V(const std::vector<unsigned char>& vch) { return UintToArith256(uint256(vch)); } const unsigned char R1Array[] = "\x9c\x52\x4a\xdb\xcf\x56\x11\x12\x2b\x29\x12\x5e\x5d\x35\xd2\xd2" "\x22\x81\xaa\xb5\x33\xf0\x08\x32\xd5\x56\xb1\xf9\xea\xe5\x1d\x7d"; const char R1ArrayHex[] = "7D1DE5EAF9B156D53208F033B5AA8122D2d2355d5e12292b121156cfdb4a529c"; const double R1Ldouble = 0.4887374590559308955; // R1L equals roughly R1Ldouble * 2^256 const arith_uint256 R1L = arith_uint256V(std::vector<unsigned char>(R1Array,R1Array+32)); const uint64_t R1LLow64 = 0x121156cfdb4a529cULL; const unsigned char R2Array[] = "\x70\x32\x1d\x7c\x47\xa5\x6b\x40\x26\x7e\x0a\xc3\xa6\x9c\xb6\xbf" "\x13\x30\x47\xa3\x19\x2d\xda\x71\x49\x13\x72\xf0\xb4\xca\x81\xd7"; const arith_uint256 R2L = arith_uint256V(std::vector<unsigned char>(R2Array,R2Array+32)); const char R1LplusR2L[] = "549FB09FEA236A1EA3E31D4D58F1B1369288D204211CA751527CFC175767850C"; const unsigned char ZeroArray[] = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; const arith_uint256 ZeroL = arith_uint256V(std::vector<unsigned char>(ZeroArray,ZeroArray+32)); const unsigned char OneArray[] = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; const arith_uint256 OneL = arith_uint256V(std::vector<unsigned char>(OneArray,OneArray+32)); const unsigned char MaxArray[] = "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"; const arith_uint256 MaxL = arith_uint256V(std::vector<unsigned char>(MaxArray,MaxArray+32)); const arith_uint256 HalfL = (OneL << 255); std::string ArrayToString(const unsigned char A[], unsigned int width) { std::stringstream Stream; Stream << std::hex; for (unsigned int i = 0; i < width; ++i) { Stream<<std::setw(2)<<std::setfill('0')<<(unsigned int)A[width-i-1]; } return Stream.str(); } BOOST_AUTO_TEST_CASE( basics ) // constructors, equality, inequality { BOOST_CHECK(1 == 0+1); // constructor arith_uint256(vector<char>): BOOST_CHECK(R1L.ToString() == ArrayToString(R1Array,32)); BOOST_CHECK(R2L.ToString() == ArrayToString(R2Array,32)); BOOST_CHECK(ZeroL.ToString() == ArrayToString(ZeroArray,32)); BOOST_CHECK(OneL.ToString() == ArrayToString(OneArray,32)); BOOST_CHECK(MaxL.ToString() == ArrayToString(MaxArray,32)); BOOST_CHECK(OneL.ToString() != ArrayToString(ZeroArray,32)); // == and != BOOST_CHECK(R1L != R2L); BOOST_CHECK(ZeroL != OneL); BOOST_CHECK(OneL != ZeroL); BOOST_CHECK(MaxL != ZeroL); BOOST_CHECK(~MaxL == ZeroL); BOOST_CHECK( ((R1L ^ R2L) ^ R1L) == R2L); uint64_t Tmp64 = 0xc4dab720d9c7acaaULL; for (unsigned int i = 0; i < 256; ++i) { BOOST_CHECK(ZeroL != (OneL << i)); BOOST_CHECK((OneL << i) != ZeroL); BOOST_CHECK(R1L != (R1L ^ (OneL << i))); BOOST_CHECK(((arith_uint256(Tmp64) ^ (OneL << i) ) != Tmp64 )); } BOOST_CHECK(ZeroL == (OneL << 256)); // String Constructor and Copy Constructor BOOST_CHECK(arith_uint256("0x"+R1L.ToString()) == R1L); BOOST_CHECK(arith_uint256("0x"+R2L.ToString()) == R2L); BOOST_CHECK(arith_uint256("0x"+ZeroL.ToString()) == ZeroL); BOOST_CHECK(arith_uint256("0x"+OneL.ToString()) == OneL); BOOST_CHECK(arith_uint256("0x"+MaxL.ToString()) == MaxL); BOOST_CHECK(arith_uint256(R1L.ToString()) == R1L); BOOST_CHECK(arith_uint256(" 0x"+R1L.ToString()+" ") == R1L); BOOST_CHECK(arith_uint256("") == ZeroL); BOOST_CHECK(R1L == arith_uint256(R1ArrayHex)); BOOST_CHECK(arith_uint256(R1L) == R1L); BOOST_CHECK((arith_uint256(R1L^R2L)^R2L) == R1L); BOOST_CHECK(arith_uint256(ZeroL) == ZeroL); BOOST_CHECK(arith_uint256(OneL) == OneL); // uint64_t constructor BOOST_CHECK( (R1L & arith_uint256("0xffffffffffffffff")) == arith_uint256(R1LLow64)); BOOST_CHECK(ZeroL == arith_uint256(0)); BOOST_CHECK(OneL == arith_uint256(1)); BOOST_CHECK(arith_uint256("0xffffffffffffffff") == arith_uint256(0xffffffffffffffffULL)); // Assignment (from base_uint) arith_uint256 tmpL = ~ZeroL; BOOST_CHECK(tmpL == ~ZeroL); tmpL = ~OneL; BOOST_CHECK(tmpL == ~OneL); tmpL = ~R1L; BOOST_CHECK(tmpL == ~R1L); tmpL = ~R2L; BOOST_CHECK(tmpL == ~R2L); tmpL = ~MaxL; BOOST_CHECK(tmpL == ~MaxL); } void shiftArrayRight(unsigned char* to, const unsigned char* from, unsigned int arrayLength, unsigned int bitsToShift) { for (unsigned int T=0; T < arrayLength; ++T) { unsigned int F = (T+bitsToShift/8); if (F < arrayLength) to[T] = from[F] >> (bitsToShift%8); else to[T] = 0; if (F + 1 < arrayLength) to[T] |= from[(F+1)] << (8-bitsToShift%8); } } void shiftArrayLeft(unsigned char* to, const unsigned char* from, unsigned int arrayLength, unsigned int bitsToShift) { for (unsigned int T=0; T < arrayLength; ++T) { if (T >= bitsToShift/8) { unsigned int F = T-bitsToShift/8; to[T] = from[F] << (bitsToShift%8); if (T >= bitsToShift/8+1) to[T] |= from[F-1] >> (8-bitsToShift%8); } else { to[T] = 0; } } } BOOST_AUTO_TEST_CASE( shifts ) { // "<<" ">>" "<<=" ">>=" unsigned char TmpArray[32]; arith_uint256 TmpL; for (unsigned int i = 0; i < 256; ++i) { shiftArrayLeft(TmpArray, OneArray, 32, i); BOOST_CHECK(arith_uint256V(std::vector<unsigned char>(TmpArray,TmpArray+32)) == (OneL << i)); TmpL = OneL; TmpL <<= i; BOOST_CHECK(TmpL == (OneL << i)); BOOST_CHECK((HalfL >> (255-i)) == (OneL << i)); TmpL = HalfL; TmpL >>= (255-i); BOOST_CHECK(TmpL == (OneL << i)); shiftArrayLeft(TmpArray, R1Array, 32, i); BOOST_CHECK(arith_uint256V(std::vector<unsigned char>(TmpArray,TmpArray+32)) == (R1L << i)); TmpL = R1L; TmpL <<= i; BOOST_CHECK(TmpL == (R1L << i)); shiftArrayRight(TmpArray, R1Array, 32, i); BOOST_CHECK(arith_uint256V(std::vector<unsigned char>(TmpArray,TmpArray+32)) == (R1L >> i)); TmpL = R1L; TmpL >>= i; BOOST_CHECK(TmpL == (R1L >> i)); shiftArrayLeft(TmpArray, MaxArray, 32, i); BOOST_CHECK(arith_uint256V(std::vector<unsigned char>(TmpArray,TmpArray+32)) == (MaxL << i)); TmpL = MaxL; TmpL <<= i; BOOST_CHECK(TmpL == (MaxL << i)); shiftArrayRight(TmpArray, MaxArray, 32, i); BOOST_CHECK(arith_uint256V(std::vector<unsigned char>(TmpArray,TmpArray+32)) == (MaxL >> i)); TmpL = MaxL; TmpL >>= i; BOOST_CHECK(TmpL == (MaxL >> i)); } arith_uint256 c1L = arith_uint256(0x0123456789abcdefULL); arith_uint256 c2L = c1L << 128; for (unsigned int i = 0; i < 128; ++i) { BOOST_CHECK((c1L << i) == (c2L >> (128-i))); } for (unsigned int i = 128; i < 256; ++i) { BOOST_CHECK((c1L << i) == (c2L << (i-128))); } } BOOST_AUTO_TEST_CASE( unaryOperators ) // ! ~ - { BOOST_CHECK(!ZeroL); BOOST_CHECK(!(!OneL)); for (unsigned int i = 0; i < 256; ++i) BOOST_CHECK(!(!(OneL<<i))); BOOST_CHECK(!(!R1L)); BOOST_CHECK(!(!MaxL)); BOOST_CHECK(~ZeroL == MaxL); unsigned char TmpArray[32]; for (unsigned int i = 0; i < 32; ++i) { TmpArray[i] = ~R1Array[i]; } BOOST_CHECK(arith_uint256V(std::vector<unsigned char>(TmpArray,TmpArray+32)) == (~R1L)); BOOST_CHECK(-ZeroL == ZeroL); BOOST_CHECK(-R1L == (~R1L)+1); for (unsigned int i = 0; i < 256; ++i) BOOST_CHECK(-(OneL<<i) == (MaxL << i)); } // Check if doing _A_ _OP_ _B_ results in the same as applying _OP_ onto each // element of Aarray and Barray, and then converting the result into a arith_uint256. #define CHECKBITWISEOPERATOR(_A_,_B_,_OP_) \ for (unsigned int i = 0; i < 32; ++i) { TmpArray[i] = _A_##Array[i] _OP_ _B_##Array[i]; } \ BOOST_CHECK(arith_uint256V(std::vector<unsigned char>(TmpArray,TmpArray+32)) == (_A_##L _OP_ _B_##L)); #define CHECKASSIGNMENTOPERATOR(_A_,_B_,_OP_) \ TmpL = _A_##L; TmpL _OP_##= _B_##L; BOOST_CHECK(TmpL == (_A_##L _OP_ _B_##L)); BOOST_AUTO_TEST_CASE( bitwiseOperators ) { unsigned char TmpArray[32]; CHECKBITWISEOPERATOR(R1,R2,|) CHECKBITWISEOPERATOR(R1,R2,^) CHECKBITWISEOPERATOR(R1,R2,&) CHECKBITWISEOPERATOR(R1,Zero,|) CHECKBITWISEOPERATOR(R1,Zero,^) CHECKBITWISEOPERATOR(R1,Zero,&) CHECKBITWISEOPERATOR(R1,Max,|) CHECKBITWISEOPERATOR(R1,Max,^) CHECKBITWISEOPERATOR(R1,Max,&) CHECKBITWISEOPERATOR(Zero,R1,|) CHECKBITWISEOPERATOR(Zero,R1,^) CHECKBITWISEOPERATOR(Zero,R1,&) CHECKBITWISEOPERATOR(Max,R1,|) CHECKBITWISEOPERATOR(Max,R1,^) CHECKBITWISEOPERATOR(Max,R1,&) arith_uint256 TmpL; CHECKASSIGNMENTOPERATOR(R1,R2,|) CHECKASSIGNMENTOPERATOR(R1,R2,^) CHECKASSIGNMENTOPERATOR(R1,R2,&) CHECKASSIGNMENTOPERATOR(R1,Zero,|) CHECKASSIGNMENTOPERATOR(R1,Zero,^) CHECKASSIGNMENTOPERATOR(R1,Zero,&) CHECKASSIGNMENTOPERATOR(R1,Max,|) CHECKASSIGNMENTOPERATOR(R1,Max,^) CHECKASSIGNMENTOPERATOR(R1,Max,&) CHECKASSIGNMENTOPERATOR(Zero,R1,|) CHECKASSIGNMENTOPERATOR(Zero,R1,^) CHECKASSIGNMENTOPERATOR(Zero,R1,&) CHECKASSIGNMENTOPERATOR(Max,R1,|) CHECKASSIGNMENTOPERATOR(Max,R1,^) CHECKASSIGNMENTOPERATOR(Max,R1,&) uint64_t Tmp64 = 0xe1db685c9a0b47a2ULL; TmpL = R1L; TmpL |= Tmp64; BOOST_CHECK(TmpL == (R1L | arith_uint256(Tmp64))); TmpL = R1L; TmpL |= 0; BOOST_CHECK(TmpL == R1L); TmpL ^= 0; BOOST_CHECK(TmpL == R1L); TmpL ^= Tmp64; BOOST_CHECK(TmpL == (R1L ^ arith_uint256(Tmp64))); } BOOST_AUTO_TEST_CASE( comparison ) // <= >= < > { arith_uint256 TmpL; for (unsigned int i = 0; i < 256; ++i) { TmpL= OneL<< i; BOOST_CHECK( TmpL >= ZeroL && TmpL > ZeroL && ZeroL < TmpL && ZeroL <= TmpL); BOOST_CHECK( TmpL >= 0 && TmpL > 0 && 0 < TmpL && 0 <= TmpL); TmpL |= R1L; BOOST_CHECK( TmpL >= R1L ); BOOST_CHECK( (TmpL == R1L) != (TmpL > R1L)); BOOST_CHECK( (TmpL == R1L) || !( TmpL <= R1L)); BOOST_CHECK( R1L <= TmpL ); BOOST_CHECK( (R1L == TmpL) != (R1L < TmpL)); BOOST_CHECK( (TmpL == R1L) || !( R1L >= TmpL)); BOOST_CHECK(! (TmpL < R1L)); BOOST_CHECK(! (R1L > TmpL)); } } BOOST_AUTO_TEST_CASE( plusMinus ) { arith_uint256 TmpL = 0; BOOST_CHECK(R1L+R2L == arith_uint256(R1LplusR2L)); TmpL += R1L; BOOST_CHECK(TmpL == R1L); TmpL += R2L; BOOST_CHECK(TmpL == R1L + R2L); BOOST_CHECK(OneL+MaxL == ZeroL); BOOST_CHECK(MaxL+OneL == ZeroL); for (unsigned int i = 1; i < 256; ++i) { BOOST_CHECK( (MaxL >> i) + OneL == (HalfL >> (i-1)) ); BOOST_CHECK( OneL + (MaxL >> i) == (HalfL >> (i-1)) ); TmpL = (MaxL>>i); TmpL += OneL; BOOST_CHECK( TmpL == (HalfL >> (i-1)) ); TmpL = (MaxL>>i); TmpL += 1; BOOST_CHECK( TmpL == (HalfL >> (i-1)) ); TmpL = (MaxL>>i); BOOST_CHECK( TmpL++ == (MaxL>>i) ); BOOST_CHECK( TmpL == (HalfL >> (i-1))); } BOOST_CHECK(arith_uint256(0xbedc77e27940a7ULL) + 0xee8d836fce66fbULL == arith_uint256(0xbedc77e27940a7ULL + 0xee8d836fce66fbULL)); TmpL = arith_uint256(0xbedc77e27940a7ULL); TmpL += 0xee8d836fce66fbULL; BOOST_CHECK(TmpL == arith_uint256(0xbedc77e27940a7ULL+0xee8d836fce66fbULL)); TmpL -= 0xee8d836fce66fbULL; BOOST_CHECK(TmpL == 0xbedc77e27940a7ULL); TmpL = R1L; BOOST_CHECK(++TmpL == R1L+1); BOOST_CHECK(R1L -(-R2L) == R1L+R2L); BOOST_CHECK(R1L -(-OneL) == R1L+OneL); BOOST_CHECK(R1L - OneL == R1L+(-OneL)); for (unsigned int i = 1; i < 256; ++i) { BOOST_CHECK((MaxL>>i) - (-OneL) == (HalfL >> (i-1))); BOOST_CHECK((HalfL >> (i-1)) - OneL == (MaxL>>i)); TmpL = (HalfL >> (i-1)); BOOST_CHECK(TmpL-- == (HalfL >> (i-1))); BOOST_CHECK(TmpL == (MaxL >> i)); TmpL = (HalfL >> (i-1)); BOOST_CHECK(--TmpL == (MaxL >> i)); } TmpL = R1L; BOOST_CHECK(--TmpL == R1L-1); } BOOST_AUTO_TEST_CASE( multiply ) { BOOST_CHECK((R1L * R1L).ToString() == "62a38c0486f01e45879d7910a7761bf30d5237e9873f9bff3642a732c4d84f10"); BOOST_CHECK((R1L * R2L).ToString() == "de37805e9986996cfba76ff6ba51c008df851987d9dd323f0e5de07760529c40"); BOOST_CHECK((R1L * ZeroL) == ZeroL); BOOST_CHECK((R1L * OneL) == R1L); BOOST_CHECK((R1L * MaxL) == -R1L); BOOST_CHECK((R2L * R1L) == (R1L * R2L)); BOOST_CHECK((R2L * R2L).ToString() == "ac8c010096767d3cae5005dec28bb2b45a1d85ab7996ccd3e102a650f74ff100"); BOOST_CHECK((R2L * ZeroL) == ZeroL); BOOST_CHECK((R2L * OneL) == R2L); BOOST_CHECK((R2L * MaxL) == -R2L); BOOST_CHECK(MaxL * MaxL == OneL); BOOST_CHECK((R1L * 0) == 0); BOOST_CHECK((R1L * 1) == R1L); BOOST_CHECK((R1L * 3).ToString() == "7759b1c0ed14047f961ad09b20ff83687876a0181a367b813634046f91def7d4"); BOOST_CHECK((R2L * 0x87654321UL).ToString() == "23f7816e30c4ae2017257b7a0fa64d60402f5234d46e746b61c960d09a26d070"); } BOOST_AUTO_TEST_CASE( divide ) { arith_uint256 D1L("AD7133AC1977FA2B7"); arith_uint256 D2L("ECD751716"); BOOST_CHECK((R1L / D1L).ToString() == "00000000000000000b8ac01106981635d9ed112290f8895545a7654dde28fb3a"); BOOST_CHECK((R1L / D2L).ToString() == "000000000873ce8efec5b67150bad3aa8c5fcb70e947586153bf2cec7c37c57a"); BOOST_CHECK(R1L / OneL == R1L); BOOST_CHECK(R1L / MaxL == ZeroL); BOOST_CHECK(MaxL / R1L == 2); BOOST_CHECK_THROW(R1L / ZeroL, uint_error); BOOST_CHECK((R2L / D1L).ToString() == "000000000000000013e1665895a1cc981de6d93670105a6b3ec3b73141b3a3c5"); BOOST_CHECK((R2L / D2L).ToString() == "000000000e8f0abe753bb0afe2e9437ee85d280be60882cf0bd1aaf7fa3cc2c4"); BOOST_CHECK(R2L / OneL == R2L); BOOST_CHECK(R2L / MaxL == ZeroL); BOOST_CHECK(MaxL / R2L == 1); BOOST_CHECK_THROW(R2L / ZeroL, uint_error); } bool almostEqual(double d1, double d2) { return fabs(d1-d2) <= 4*fabs(d1)*std::numeric_limits<double>::epsilon(); } BOOST_AUTO_TEST_CASE( methods ) // GetHex SetHex size() GetLow64 GetSerializeSize, Serialize, Unserialize { BOOST_CHECK(R1L.GetHex() == R1L.ToString()); BOOST_CHECK(R2L.GetHex() == R2L.ToString()); BOOST_CHECK(OneL.GetHex() == OneL.ToString()); BOOST_CHECK(MaxL.GetHex() == MaxL.ToString()); arith_uint256 TmpL(R1L); BOOST_CHECK(TmpL == R1L); TmpL.SetHex(R2L.ToString()); BOOST_CHECK(TmpL == R2L); TmpL.SetHex(ZeroL.ToString()); BOOST_CHECK(TmpL == 0); TmpL.SetHex(HalfL.ToString()); BOOST_CHECK(TmpL == HalfL); TmpL.SetHex(R1L.ToString()); BOOST_CHECK(R1L.size() == 32); BOOST_CHECK(R2L.size() == 32); BOOST_CHECK(ZeroL.size() == 32); BOOST_CHECK(MaxL.size() == 32); BOOST_CHECK(R1L.GetLow64() == R1LLow64); BOOST_CHECK(HalfL.GetLow64() ==0x0000000000000000ULL); BOOST_CHECK(OneL.GetLow64() ==0x0000000000000001ULL); for (unsigned int i = 0; i < 255; ++i) { BOOST_CHECK((OneL << i).getdouble() == ldexp(1.0,i)); } BOOST_CHECK(ZeroL.getdouble() == 0.0); for (int i = 256; i > 53; --i) BOOST_CHECK(almostEqual((R1L>>(256-i)).getdouble(), ldexp(R1Ldouble,i))); uint64_t R1L64part = (R1L>>192).GetLow64(); for (int i = 53; i > 0; --i) // doubles can store all integers in {0,...,2^54-1} exactly { BOOST_CHECK((R1L>>(256-i)).getdouble() == (double)(R1L64part >> (64-i))); } } BOOST_AUTO_TEST_CASE(bignum_SetCompact) { arith_uint256 num; bool fNegative; bool fOverflow; num.SetCompact(0, &fNegative, &fOverflow); BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000000"); BOOST_CHECK_EQUAL(num.GetCompact(), 0U); BOOST_CHECK_EQUAL(fNegative, false); BOOST_CHECK_EQUAL(fOverflow, false); num.SetCompact(0x00123456, &fNegative, &fOverflow); BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000000"); BOOST_CHECK_EQUAL(num.GetCompact(), 0U); BOOST_CHECK_EQUAL(fNegative, false); BOOST_CHECK_EQUAL(fOverflow, false); num.SetCompact(0x01003456, &fNegative, &fOverflow); BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000000"); BOOST_CHECK_EQUAL(num.GetCompact(), 0U); BOOST_CHECK_EQUAL(fNegative, false); BOOST_CHECK_EQUAL(fOverflow, false); num.SetCompact(0x02000056, &fNegative, &fOverflow); BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000000"); BOOST_CHECK_EQUAL(num.GetCompact(), 0U); BOOST_CHECK_EQUAL(fNegative, false); BOOST_CHECK_EQUAL(fOverflow, false); num.SetCompact(0x03000000, &fNegative, &fOverflow); BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000000"); BOOST_CHECK_EQUAL(num.GetCompact(), 0U); BOOST_CHECK_EQUAL(fNegative, false); BOOST_CHECK_EQUAL(fOverflow, false); num.SetCompact(0x04000000, &fNegative, &fOverflow); BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000000"); BOOST_CHECK_EQUAL(num.GetCompact(), 0U); BOOST_CHECK_EQUAL(fNegative, false); BOOST_CHECK_EQUAL(fOverflow, false); num.SetCompact(0x00923456, &fNegative, &fOverflow); BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000000"); BOOST_CHECK_EQUAL(num.GetCompact(), 0U); BOOST_CHECK_EQUAL(fNegative, false); BOOST_CHECK_EQUAL(fOverflow, false); num.SetCompact(0x01803456, &fNegative, &fOverflow); BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000000"); BOOST_CHECK_EQUAL(num.GetCompact(), 0U); BOOST_CHECK_EQUAL(fNegative, false); BOOST_CHECK_EQUAL(fOverflow, false); num.SetCompact(0x02800056, &fNegative, &fOverflow); BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000000"); BOOST_CHECK_EQUAL(num.GetCompact(), 0U); BOOST_CHECK_EQUAL(fNegative, false); BOOST_CHECK_EQUAL(fOverflow, false); num.SetCompact(0x03800000, &fNegative, &fOverflow); BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000000"); BOOST_CHECK_EQUAL(num.GetCompact(), 0U); BOOST_CHECK_EQUAL(fNegative, false); BOOST_CHECK_EQUAL(fOverflow, false); num.SetCompact(0x04800000, &fNegative, &fOverflow); BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000000"); BOOST_CHECK_EQUAL(num.GetCompact(), 0U); BOOST_CHECK_EQUAL(fNegative, false); BOOST_CHECK_EQUAL(fOverflow, false); num.SetCompact(0x01123456, &fNegative, &fOverflow); BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000012"); BOOST_CHECK_EQUAL(num.GetCompact(), 0x01120000U); BOOST_CHECK_EQUAL(fNegative, false); BOOST_CHECK_EQUAL(fOverflow, false); // Make sure that we don't generate compacts with the 0x00800000 bit set num = 0x80; BOOST_CHECK_EQUAL(num.GetCompact(), 0x02008000U); num.SetCompact(0x01fedcba, &fNegative, &fOverflow); BOOST_CHECK_EQUAL(num.GetHex(), "000000000000000000000000000000000000000000000000000000000000007e"); BOOST_CHECK_EQUAL(num.GetCompact(true), 0x01fe0000U); BOOST_CHECK_EQUAL(fNegative, true); BOOST_CHECK_EQUAL(fOverflow, false); num.SetCompact(0x02123456, &fNegative, &fOverflow); BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000001234"); BOOST_CHECK_EQUAL(num.GetCompact(), 0x02123400U); BOOST_CHECK_EQUAL(fNegative, false); BOOST_CHECK_EQUAL(fOverflow, false); num.SetCompact(0x03123456, &fNegative, &fOverflow); BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000123456"); BOOST_CHECK_EQUAL(num.GetCompact(), 0x03123456U); BOOST_CHECK_EQUAL(fNegative, false); BOOST_CHECK_EQUAL(fOverflow, false); num.SetCompact(0x04123456, &fNegative, &fOverflow); BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000012345600"); BOOST_CHECK_EQUAL(num.GetCompact(), 0x04123456U); BOOST_CHECK_EQUAL(fNegative, false); BOOST_CHECK_EQUAL(fOverflow, false); num.SetCompact(0x04923456, &fNegative, &fOverflow); BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000012345600"); BOOST_CHECK_EQUAL(num.GetCompact(true), 0x04923456U); BOOST_CHECK_EQUAL(fNegative, true); BOOST_CHECK_EQUAL(fOverflow, false); num.SetCompact(0x05009234, &fNegative, &fOverflow); BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000092340000"); BOOST_CHECK_EQUAL(num.GetCompact(), 0x05009234U); BOOST_CHECK_EQUAL(fNegative, false); BOOST_CHECK_EQUAL(fOverflow, false); num.SetCompact(0x20123456, &fNegative, &fOverflow); BOOST_CHECK_EQUAL(num.GetHex(), "1234560000000000000000000000000000000000000000000000000000000000"); BOOST_CHECK_EQUAL(num.GetCompact(), 0x20123456U); BOOST_CHECK_EQUAL(fNegative, false); BOOST_CHECK_EQUAL(fOverflow, false); num.SetCompact(0xff123456, &fNegative, &fOverflow); BOOST_CHECK_EQUAL(fNegative, false); BOOST_CHECK_EQUAL(fOverflow, true); } BOOST_AUTO_TEST_CASE( getmaxcoverage ) // some more tests just to get 100% coverage { // ~R1L give a base_uint<256> BOOST_CHECK((~~R1L >> 10) == (R1L >> 10)); BOOST_CHECK((~~R1L << 10) == (R1L << 10)); BOOST_CHECK(!(~~R1L < R1L)); BOOST_CHECK(~~R1L <= R1L); BOOST_CHECK(!(~~R1L > R1L)); BOOST_CHECK(~~R1L >= R1L); BOOST_CHECK(!(R1L < ~~R1L)); BOOST_CHECK(R1L <= ~~R1L); BOOST_CHECK(!(R1L > ~~R1L)); BOOST_CHECK(R1L >= ~~R1L); BOOST_CHECK(~~R1L + R2L == R1L + ~~R2L); BOOST_CHECK(~~R1L - R2L == R1L - ~~R2L); BOOST_CHECK(~R1L != R1L); BOOST_CHECK(R1L != ~R1L); unsigned char TmpArray[32]; CHECKBITWISEOPERATOR(~R1,R2,|) CHECKBITWISEOPERATOR(~R1,R2,^) CHECKBITWISEOPERATOR(~R1,R2,&) CHECKBITWISEOPERATOR(R1,~R2,|) CHECKBITWISEOPERATOR(R1,~R2,^) CHECKBITWISEOPERATOR(R1,~R2,&) } BOOST_AUTO_TEST_SUITE_END()
f86011c0c1cd82bc6faf199a81c4a1928a4592a0
1e0613d7284d5555f6d17255a89d41205b6688b5
/universum.cpp
21960ab02ee10344af2c70ebceffdca0a35b5bbc
[]
no_license
PhilippHenne/MathesisPhysik
9cdb352673dee2a549dbb5ce1083a78daff038b9
4ec5fc3b19805ed4d9268bd245c564b7c67e2312
refs/heads/master
2016-09-14T07:09:28.665473
2016-05-19T23:59:06
2016-05-19T23:59:06
59,251,531
1
0
null
null
null
null
UTF-8
C++
false
false
2,221
cpp
#include <iostream> #include <sstream> #include <vector> #include "universum.hpp" // Bedeutung von Konstante i: // 1: Universum mit Sonne, Erde und Mond double G = 1; universe::universe(int i) { if (i == 1) { // objects.push_back(sky_object (0.,2.,4.,3.,2.,1.,1.)); // objects.push_back(sky_object (1.,1.,1.,1.,1.,1.,0.5)); // objects.push_back(sky_object (5.,5.,5.,2.,2.,2.,0.1)); sky_object* sun = new sky_object (0.,0.,0.,0.,0.,0.,1.); sky_object* earth = new sky_object (10.,0.,0.,0.,0.,0.,1.); // sky_object* moon = new sky_object(-1.657103868749121*(0.1),9.706382026425472*(0.1),-1.879812512691582*(0.0001),(-1.728100931961937*(0.01))/84600,(-3.525371122447977*(0.001))/84600,(4.909148618073602*(0.00001))/84600, 1/27068510); objects.push_back(sun); objects.push_back(earth); // objects.push_back(moon); } } universe::~universe() { } Vector3D universe::setF(unsigned int a) { Vector3D temp(0.,0.,0.); std::vector<Vector3D> forces (objects.size(), temp); for (unsigned int i = 0; i < objects.size(); i++) { if (i == a) { forces.at(a) = forces.at(a); } else { Vector3D abstand_vec (objects.at(a)->get_pos() - objects.at(i)->get_pos()); //std::cout << abstand_vec.asString() << std::endl; double abstand = objects.at(a)->get_pos().abstand(objects.at(i)->get_pos()); //std::cout << abstand << std::endl; forces.at(a) = forces.at(a) + ((abstand_vec * ((objects.at(a)->m * objects.at(i)->m)/(abstand*abstand*abstand)))* -G); } } return forces.at(a); } Vector3D universe::set_acc(unsigned int a) { return setF(a)/objects.at(a)->m; } std::string universe::asString() { std::stringstream s; for (unsigned int i = 0; i < objects.size(); i++) { s << "Objekt " << i+1 <<" Position: " << objects.at(i)->get_pos().asString() << "Geschwindigkeit: " << objects.at(i)->get_v().asString() << "Kraft: " << setF(i).asString() << "Beschleunigung: " << set_acc(i).asString() << std::endl; } return s.str(); } //(-1.630229002588497*(0.1),9.704723344534316*(0.1),-1.955367328932975*(0.0001),(-1.723383356491747*(0.01))/84600,(-2.969134550063944*(0.001))/84600,(-4.433758674928828*(0.0000001))/84600,1/332946) //3.964 * (0.00000000000001)
8cfa3b7600686026d4a121d13b55a3bd28f61852
88d452f7b5d7f97a2ec666a185d6791fa1e2da72
/RayTracingRenderer/cyCodeBase/cyVector.h
a1e74ce5aa33f0057d961f7180a1e5afeaec8c6f
[ "MIT" ]
permissive
Sumi-N/RayTracing
78a490e985c72d2f1e1888cfd75089a1b73a64bd
0a2428debac4f8573e043ad259049089cb83b35c
refs/heads/master
2022-04-27T21:51:07.136002
2020-03-29T03:36:05
2020-03-29T03:36:05
203,900,348
0
0
null
null
null
null
UTF-8
C++
false
false
37,437
h
// cyCodeBase by Cem Yuksel // [www.cemyuksel.com] //------------------------------------------------------------------------------- //! \file cyVector.h //! \author Cem Yuksel //! //! \brief 2D, 3D, 4D, and ND vector classes. //! //------------------------------------------------------------------------------- // // Copyright (c) 2016, Cem Yuksel <[email protected]> // All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // //------------------------------------------------------------------------------- #ifndef _CY_VECTOR_H_INCLUDED_ #define _CY_VECTOR_H_INCLUDED_ //------------------------------------------------------------------------------- #include "cyCore.h" //------------------------------------------------------------------------------- namespace cy { //------------------------------------------------------------------------------- // Forward declarations //! \cond HIDDEN_SYMBOLS template <typename T> class Vec2; template <typename T> class Vec3; template <typename T> class Vec4; //! \endcond //------------------------------------------------------------------------------- //! A general class for N-dimensional vectors. template <typename T, int N> class Vec { friend Vec operator + ( T v, Vec const &p ) { return p+v; } //!< Addition with a constant friend Vec operator - ( T v, Vec const &p ) { return -(p-v); } //!< Subtraction from a constant friend Vec operator * ( T v, Vec const &p ) { return p*v; } //!< Multiplication with a constant public: //!@name Components of the vector T elem[N]; //!@name Constructors Vec() CY_CLASS_FUNCTION_DEFAULT explicit Vec( T const *p ) { MemCopy(elem,p,N); } explicit Vec( T v ) { for ( int i=0; i<N; ++i ) elem[i]=v; } template <typename S> explicit Vec( Vec<S,N> const &p ) { MemConvert(elem,p.elem,N); } template <int M> explicit Vec( Vec<T,M> const &p ) { if ( N <= M ) { MemCopy(elem,p.elem,N); } else { MemCopy(elem,p.elem,M); MemClear(elem,N-M); } } template <typename S, int M> explicit Vec( Vec<S,M> const &p ) { if ( N <= M ) { MemConvert(elem,p.elem,N); } else { MemConvert(elem,p.elem,M); MemClear(elem,N-M); } } explicit Vec( Vec2<T> const &p ); explicit Vec( Vec3<T> const &p ); explicit Vec( Vec4<T> const &p ); template <typename S> explicit Vec( Vec2<S> const &p ); template <typename S> explicit Vec( Vec3<S> const &p ); template <typename S> explicit Vec( Vec4<S> const &p ); template <typename P> explicit Vec( P const &p ) { for ( int i=0; i<N; ++i ) elem[i]=(T)p[i]; } //!@name Set & Get value methods void Zero() { MemClear(elem,N); } //!< Sets the coordinates as zero void Get( T *p ) const { MemCopy(p,elem,N); } //!< Puts the coordinate values into the array void Set( T const *p ) { MemCopy(elem,p,N); } //!< Sets the coordinates using the values in the given array void Set( T v ) { for ( int i=0; i<N; ++i ) elem[i] = v; } //!< Sets all coordinates using the given value template <int M> void CopyData( T *p ) { if ( M <= N ) { MemCopy(p,elem,M); } else { MemCopy(p,elem,N); MemClear(p+N,M-N); } } template <typename S, int M> void ConvertData( S *p ) { if ( M <= N ) { MemConvert(p,elem,M); } else { MemConvert(p,elem,N); MemClear(p+N,M-N); } } //!@name General methods void Normalize () { *this /= Length(); } //!< Normalizes the vector, such that its length becomes 1. Vec GetNormalized() const { return *this / Length(); } //!< Returns a normalized copy of the vector. T LengthSquared() const { Vec p=operator*(*this); return p.Sum(); } //!< Returns the square of the length. Effectively, this is the dot product of the vector with itself. T Length () const { return cy::Sqrt(LengthSquared()); } //!< Returns the length of the vector. T Sum () const { T v=elem[0]; for ( int i=1; i<N; ++i ) v+=elem[i]; return v; } //!< Returns the sum of its components bool IsZero () const { for ( int i=0; i<N; ++i ) if ( elem[i] != T(0) ) return false; return true; } //!< Returns true if all components are exactly zero T Min () const { T m = elem[0]; for ( int i=1; i<N; ++i ) if ( m > elem[i] ) m = elem[i]; return m; } //!< Returns the minimum component of the vector. T Max () const { T m = elem[0]; for ( int i=1; i<N; ++i ) if ( m < elem[i] ) m = elem[i]; return m; } //!< Returns the maximum component of the vector. int MinID () const { T m = elem[0]; int ix=0; for ( int i=1; i<N; ++i ) if ( m > elem[i] ) { m = elem[i]; ix = i; } return ix; } //!< Returns the index of the minimum component of the vector. int MaxID () const { T m = elem[0]; int ix=0; for ( int i=1; i<N; ++i ) if ( m < elem[i] ) { m = elem[i]; ix = i; } return ix; } //!< Returns the index of the maximum component of the vector. bool IsFinite () const { for ( int i=0; i<N; ++i ) if ( ! cy::IsFinite(elem[i]) ) return false; return true; } //!< Returns true if all components are finite real numbers. bool IsUnit () const { return std::abs(LengthSquared()-T(1)) < T(0.001); } //!< Returns true if the length of the vector is close to 1. Vec Sqrt () const { Vec v; for ( int i=0; i<N; ++i ) v.elem[i] = cy::Sqrt(elem[i]); return v; } //!< Returns the square root of the vector. Vec Abs () const { Vec v; for ( int i=0; i<N; ++i ) v.elem[i] = std::abs(elem[i]); return v; } //!< Returns a vector containing the absolute values of all components. //!@name Limit methods void Clamp ( T minLimit, T maxLimit ) { ClampMin(minLimit); ClampMax(maxLimit); } //!< Ensures that all components of the vector are within the given limits. void ClampMin( T v ) { for ( int i=0; i<N; ++i ) elem[i] = (elem[i]<v) ? v : elem[i]; } //!< Ensures that all components of the vector are greater than or equal to the given limit. void ClampMax( T v ) { for ( int i=0; i<N; ++i ) elem[i] = (elem[i]>v) ? v : elem[i]; } //!< Ensures that all components of the vector are smaller than or equal to the given limit. void SetAbs () { for ( int i=0; i<N; i++ ) elem[i] = std::abs(elem[i]); } //!< Converts all negative components to positive values //!@name Unary operators Vec operator - () const { Vec r; for ( int i=0; i<N; ++i ) r.elem[i]=-elem[i]; return r; } //!@name Binary operators Vec operator + ( Vec const &p ) const { Vec r; for ( int i=0; i<N; ++i ) r.elem[i] = elem[i] + p.elem[i]; return r; } Vec operator - ( Vec const &p ) const { Vec r; for ( int i=0; i<N; ++i ) r.elem[i] = elem[i] - p.elem[i]; return r; } Vec operator * ( Vec const &p ) const { Vec r; for ( int i=0; i<N; ++i ) r.elem[i] = elem[i] * p.elem[i]; return r; } Vec operator / ( Vec const &p ) const { Vec r; for ( int i=0; i<N; ++i ) r.elem[i] = elem[i] / p.elem[i]; return r; } Vec operator + ( T const v ) const { Vec r; for ( int i=0; i<N; ++i ) r.elem[i] = elem[i] + v; return r; } Vec operator - ( T const v ) const { Vec r; for ( int i=0; i<N; ++i ) r.elem[i] = elem[i] - v; return r; } Vec operator * ( T const v ) const { Vec r; for ( int i=0; i<N; ++i ) r.elem[i] = elem[i] * v; return r; } Vec operator / ( T const v ) const { Vec r; for ( int i=0; i<N; ++i ) r.elem[i] = elem[i] / v; return r; } //!@name Assignment operators Vec const& operator += ( Vec const &p ) { for ( int i=0; i<N; ++i ) elem[i] += p.elem[i]; return *this; } Vec const& operator -= ( Vec const &p ) { for ( int i=0; i<N; ++i ) elem[i] -= p.elem[i]; return *this; } Vec const& operator *= ( Vec const &p ) { for ( int i=0; i<N; ++i ) elem[i] *= p.elem[i]; return *this; } Vec const& operator /= ( Vec const &p ) { for ( int i=0; i<N; ++i ) elem[i] /= p.elem[i]; return *this; } Vec const& operator += ( T const v ) { for ( int i=0; i<N; ++i ) elem[i] += v; return *this; } Vec const& operator -= ( T const v ) { for ( int i=0; i<N; ++i ) elem[i] -= v; return *this; } Vec const& operator *= ( T const v ) { for ( int i=0; i<N; ++i ) elem[i] *= v; return *this; } Vec const& operator /= ( T const v ) { for ( int i=0; i<N; ++i ) elem[i] /= v; return *this; } //!@name Test operators bool operator == ( Vec const& p ) const { for ( int i=0; i<N; ++i ) if ( elem[i] != p.elem[i] ) return false; return true; } bool operator != ( Vec const& p ) const { for ( int i=0; i<N; ++i ) if ( elem[i] != p.elem[i] ) return true; return false; } //!@name Access operators T& operator [] ( int i ) { return Element(i); } T operator [] ( int i ) const { return Element(i); } T& Element ( int i ) { assert(i>=0 && i<N); return elem[i]; } T const& Element ( int i ) const { assert(i>=0 && i<N); return elem[i]; } T* Elements () { return elem; } T const* Elements () const { return elem; } //!@name Dot product T Dot ( Vec const &p ) const { Vec r=operator*(p); return r.Sum(); } //!< Dot product T operator % ( Vec const &p ) const { return Dot(p); } //!< Dot product operator }; //------------------------------------------------------------------------------- //! 2D vector class template <typename T> class Vec2 { friend Vec2 operator + ( T v, Vec2 const &p ) { return p+v; } //!< Addition with a constant friend Vec2 operator - ( T v, Vec2 const &p ) { return -(p-v); } //!< Subtraction from a constant friend Vec2 operator * ( T v, Vec2 const &p ) { return p*v; } //!< Multiplication with a constant public: //!@name Components of the vector union { struct { T x, y; }; T elem[2]; //!< Array-type access to the vector elements x and y }; //!@name Constructors Vec2() CY_CLASS_FUNCTION_DEFAULT Vec2( T _x, T _y ) : x( _x), y( _y) {} explicit Vec2( T v ) : x(v ), y(v ) {} explicit Vec2( Vec3<T> const &p ); explicit Vec2( Vec4<T> const &p ); template <typename S> explicit Vec2( Vec2<S> const &p ) : x(T(p.x)), y(T(p.y)) {} template <typename S> explicit Vec2( Vec3<S> const &p ); template <typename S> explicit Vec2( Vec4<S> const &p ); template <int N > explicit Vec2( Vec<T,N> const &p ) { p.CopyData<2>(elem); } template <int N, typename S> explicit Vec2( Vec<S,N> const &p ) { p.ConvertData<T,2>(elem); } //!@name Set & Get value methods void Zero() { MemClear(elem,2); } //!< Sets the coordinates as zero. void Get( T *p ) const { ((Vec2*)p)->operator=(*this); } //!< Puts the coordinate values into the array. void Set( T const *p ) { operator=(*((Vec2*)p)); } //!< Sets the coordinates using the values in the given array. void Set( T v ) { x=v; y=v; } //!< Sets all coordinates using the given value void Set( T _x, T _y ) { x=_x; y=_y; } //!< Sets the coordinates using the given values //!@name General methods void Normalize () { *this /= Length(); } //!< Normalizes the vector, such that its length becomes 1. Vec2 GetNormalized () const { return *this / Length(); } //!< Returns a normalized copy of the vector. T LengthSquared () const { Vec2 p=operator*(*this); return p.Sum(); } //!< Returns the square of the length. Effectively, this is the dot product of the vector with itself. T Length () const { return cy::Sqrt(LengthSquared()); } //!< Returns the length of the vector. T Sum () const { return x+y; } //!< Returns the sum of its components bool IsZero () const { return x==T(0) && y==T(0); } //!< Returns true if all components are exactly zero T Min () const { return x<y ? x : y; } //!< Returns the minimum component of the vector. T Max () const { return x>y ? x : y; } //!< Returns the maximum component of the vector. int MinID () const { return x<y ? 0 : 1; } //!< Returns the index of the minimum component of the vector. int MaxID () const { return x>y ? 0 : 1; } //!< Returns the index of the maximum component of the vector. bool IsFinite () const { return cy::IsFinite(x) && cy::IsFinite(y); } //!< Returns true if all components are finite real numbers. bool IsUnit () const { return std::abs(LengthSquared()-T(1)) < T(0.001); } //!< Returns true if the length of the vector is close to 1. Vec2 Sqrt () const { return Vec2(cy::Sqrt(x),cy::Sqrt(y)); } //!< Returns the square root of the vector. Vec2 Abs () const { return Vec2(std::abs(x),std::abs(y)); } //!< Returns a vector containing the absolute values of all components. Vec2 SortDesc () const { char cxy=x<y; return Vec2(elem[cxy],elem[!cxy]); } //!< Returns a vector with components sorted in descending order. Vec2 SortAsc () const { char cxy=x>y; return Vec2(elem[cxy],elem[!cxy]); } //!< Returns a vector with components sorted in ascending order. Vec2 GetPerpendicular() const { return Vec2(-y,x); } //!< Returns a perpendicular vector (rotated by 90 degrees in counter clockwise direction). //!@name Limit methods void Clamp ( T minLimit, T maxLimit ) { ClampMin(minLimit); ClampMax(maxLimit); } //!< Ensures that all components of the vector are within the given limits. void ClampMin( T v ) { x=(x<v)?v:x; y=(y<v)?v:y; } //!< Ensures that all components of the vector are greater than or equal to the given limit. void ClampMax( T v ) { x=(x>v)?v:x; y=(y>v)?v:y; } //!< Ensures that all components of the vector are smaller than or equal to the given limit. void SetAbs () { x=std::abs(x); y=std::abs(y); } //!< Converts all negative components to positive values //!@name Unary operators Vec2 operator - () const { Vec2 r; r.x=-x; r.y=-y; return r; } //!@name Binary operators Vec2 operator + ( Vec2 const &p ) const { Vec2 r; r.x=x+p.x; r.y=y+p.y; return r; } Vec2 operator - ( Vec2 const &p ) const { Vec2 r; r.x=x-p.x; r.y=y-p.y; return r; } Vec2 operator * ( Vec2 const &p ) const { Vec2 r; r.x=x*p.x; r.y=y*p.y; return r; } Vec2 operator / ( Vec2 const &p ) const { Vec2 r; r.x=x/p.x; r.y=y/p.y; return r; } Vec2 operator + ( T const v ) const { Vec2 r; r.x=x+v; r.y=y+v; return r; } Vec2 operator - ( T const v ) const { Vec2 r; r.x=x-v; r.y=y-v; return r; } Vec2 operator * ( T const v ) const { Vec2 r; r.x=x*v; r.y=y*v; return r; } Vec2 operator / ( T const v ) const { Vec2 r; r.x=x/v; r.y=y/v; return r; } //!@name Assignment operators Vec2 const& operator += ( Vec2 const &p ) { x+=p.x; y+=p.y; return *this; } Vec2 const& operator -= ( Vec2 const &p ) { x-=p.x; y-=p.y; return *this; } Vec2 const& operator *= ( Vec2 const &p ) { x*=p.x; y*=p.y; return *this; } Vec2 const& operator /= ( Vec2 const &p ) { x/=p.x; y/=p.y; return *this; } Vec2 const& operator += ( T const v ) { x+=v; y+=v; return *this; } Vec2 const& operator -= ( T const v ) { x-=v; y-=v; return *this; } Vec2 const& operator *= ( T const v ) { x*=v; y*=v; return *this; } Vec2 const& operator /= ( T const v ) { x/=v; y/=v; return *this; } //!@name Test operators bool operator == ( Vec2 const& p ) const { return x==p.x && y==p.y; } bool operator != ( Vec2 const& p ) const { return x!=p.x && y!=p.y; } //!@name Access operators T& operator [] ( int i ) { return Element(i); } T const& operator [] ( int i ) const { return Element(i); } T& Element ( int i ) { assert(i>=0 && i<2); return elem[i]; } T const& Element ( int i ) const { assert(i>=0 && i<2); return elem[i]; } T* Elements () { return elem; } T const* Elements () const { return elem; } //!@name Cross product and dot product T Cross ( Vec2 const &p ) const { Vec2 r(-y,x); return r.Dot(p); } //!< Cross product T operator ^ ( Vec2 const &p ) const { return Cross(p); } //!< Cross product operator T Dot ( Vec2 const &p ) const { return x*p.x + y*p.y; } //!< Dot product T operator % ( Vec2 const &p ) const { return Dot(p); } //!< Dot product operator }; //------------------------------------------------------------------------------- //! 3D vector class template <typename T> class Vec3 { friend Vec3 operator + ( T v, Vec3 const &p ) { return p+v; } //!< Addition with a constant friend Vec3 operator - ( T v, Vec3 const &p ) { return -(p-v); } //!< Subtraction from a constant friend Vec3 operator * ( T v, Vec3 const &p ) { return p*v; } //!< Multiplication with a constant public: //!@name Components of the vector union { struct { T x, y, z; }; T elem[3]; //!< Array-type access to the vector elements x, y, and z }; //!@name Constructors Vec3() CY_CLASS_FUNCTION_DEFAULT Vec3( T _x, T _y, T _z ) : x( _x), y( _y), z( _z) {} explicit Vec3( T v ) : x(v ), y(v ), z(v ) {} explicit Vec3( Vec2<T> const &p, T _z=0 ) : x(p.x), y(p.y), z( _z) {} explicit Vec3( Vec4<T> const &p ); template <typename S> explicit Vec3( Vec3<S> const &p ) : x(T(p.x)), y(T(p.y)), z(T(p.z)) {} template <typename S> explicit Vec3( Vec2<S> const &p, T _z=0 ) : x(T(p.x)), y(T(p.y)), z( _z ) {} template <typename S> explicit Vec3( Vec4<S> const &p ); template <int N > explicit Vec3( Vec<T,N> const &p ) { p.CopyData<3>(elem); } template <int N, typename S> explicit Vec3( Vec<S,N> const &p ) { p.ConvertData<T,3>(elem); } //!@name Set & Get value methods void Zero() { MemClear(elem,3); } //!< Sets the coordinates as zero. void Get( T *p ) const { ((Vec3*)p)->operator=(*this); } //!< Puts the coordinate values into the array. void Set( T const *p ) { operator=(*((Vec3*)p)); } //!< Sets the coordinates using the values in the given array. void Set( T v ) { x=v; y=v; z=v; } //!< Sets all coordinates using the given value. void Set( T _x, T _y, T _z ) { x= _x; y= _y; z=_z; } //!< Sets the coordinates using the given values. void Set( Vec2<T> const &p, T _z ) { x=p.x; y=p.y; z=_z; } //!< Sets the coordinates using the given values. //!@name General methods void Normalize () { *this /= Length(); } //!< Normalizes the vector, such that its length becomes 1. Vec3 GetNormalized () const { return *this / Length(); } //!< Returns a normalized copy of the vector. T LengthSquared () const { Vec3 p=operator*(*this); return p.Sum(); } //!< Returns the square of the length. Effectively, this is the dot product of the vector with itself. T Length () const { return cy::Sqrt(LengthSquared()); } //!< Returns the length of the vector. T Sum () const { return x+y+z; } //!< Returns the sum of its components. bool IsZero () const { return x==T(0) && y==T(0) && z==T(0); } //!< Returns true if all components are exactly zero. T Min () const { return x<y ? (x<z ? x : z) : (y<z ? y : z); } //!< Returns the minimum component of the vector. T Max () const { return x>y ? (x>z ? x : z) : (y>z ? y : z); } //!< Returns the maximum component of the vector. int MinIndex () const { return x<y ? (x<z ? 0 : 2) : (y<z ? 1 : 2); } //!< Returns the index of the minimum component of the vector. int MaxIndex () const { return x>y ? (x>z ? 0 : 2) : (y>z ? 1 : 2); } //!< Returns the index of the maximum component of the vector. bool IsFinite () const { return cy::IsFinite(x) && cy::IsFinite(y) && cy::IsFinite(z); } //!< Returns true if all components are finite real numbers. bool IsUnit () const { return std::abs(LengthSquared()-T(1)) < T(0.001); } //!< Returns true if the length of the vector is close to 1. Vec3 Sqrt () const { return Vec3(cy::Sqrt(x),cy::Sqrt(y),cy::Sqrt(z)); } //!< Returns the square root of the vector. Vec3 Abs () const { return Vec3(std::abs(x),std::abs(y),std::abs(z)); } //!< Returns a vector containing the absolute values of all components. Vec3 SortDesc () const { char cxy=x<y, cxz=x<z, cyz=y<z; return Vec3( elem[(cxy|cxz)*(1+cyz)], elem[(1-(cxy^cxz))*(1+(cyz^cxz))], elem[(1-(cxy&cxz))*(2-cyz)] ); } //!< Returns a vector with components sorted in descending order. Vec3 SortAsc () const { char cxy=x>y, cxz=x>z, cyz=y>z; return Vec3( elem[(cxy|cxz)*(1+cyz)], elem[(1-(cxy^cxz))*(1+(cyz^cxz))], elem[(1-(cxy&cxz))*(2-cyz)] ); } //!< Returns a vector with components sorted in ascending order. Vec3 GetPerpendicular() const { Vec3 v0,v1; GetOrthonormals(v0,v1); return v0; } //!< Returns a perpendicular vector void GetOrthonormals ( Vec3 &v0, Vec3 &v1 ) const //!< Returns two orthogonal vectors to this vector, forming an orthonormal basis { if ( z >= y ) { T const a = T(1)/(1 + z); T const b = -x*y*a; v0.Set( 1 - x*x*a, b, -x ); v1.Set( b, 1 - y*y*a, -y ); } else { T const a = T(1)/(1 + y); T const b = -x*z*a; v0.Set( b, -z, 1 - z*z*a ); v1.Set( 1 - x*x*a, -x, b ); } } //!@name Limit methods void Clamp ( T minLimit, T maxLimit ) { ClampMin(minLimit); ClampMax(maxLimit); } //!< Ensures that all components of the vector are within the given limits. void ClampMin( T v ) { x=(x<v)?v:x; y=(y<v)?v:y; z=(z<v)?v:z; } //!< Ensures that all components of the vector are greater than or equal to the given limit. void ClampMax( T v ) { x=(x>v)?v:x; y=(y>v)?v:y; z=(z>v)?v:z; } //!< Ensures that all components of the vector are smaller than or equal to the given limit. void SetAbs () { x=std::abs(x); y=std::abs(y); z=std::abs(z); } //!< Converts all negative components to positive values //!@name Unary operators Vec3 operator - () const { Vec3 r; r.x=-x; r.y=-y; r.z=-z; return r; } //!@name Binary operators Vec3 operator + ( Vec3 const &p ) const { Vec3 r; r.x=x+p.x; r.y=y+p.y; r.z=z+p.z; return r; } Vec3 operator - ( Vec3 const &p ) const { Vec3 r; r.x=x-p.x; r.y=y-p.y; r.z=z-p.z; return r; } Vec3 operator * ( Vec3 const &p ) const { Vec3 r; r.x=x*p.x; r.y=y*p.y; r.z=z*p.z; return r; } Vec3 operator / ( Vec3 const &p ) const { Vec3 r; r.x=x/p.x; r.y=y/p.y; r.z=z/p.z; return r; } Vec3 operator + ( T const v ) const { Vec3 r; r.x=x+v; r.y=y+v; r.z=z+v; return r; } Vec3 operator - ( T const v ) const { Vec3 r; r.x=x-v; r.y=y-v; r.z=z-v; return r; } Vec3 operator * ( T const v ) const { Vec3 r; r.x=x*v; r.y=y*v; r.z=z*v; return r; } Vec3 operator / ( T const v ) const { Vec3 r; r.x=x/v; r.y=y/v; r.z=z/v; return r; } //!@name Assignment operators Vec3 const& operator += ( Vec3 const &p ) { x+=p.x; y+=p.y; z+=p.z; return *this; } Vec3 const& operator -= ( Vec3 const &p ) { x-=p.x; y-=p.y; z-=p.z; return *this; } Vec3 const& operator *= ( Vec3 const &p ) { x*=p.x; y*=p.y; z*=p.z; return *this; } Vec3 const& operator /= ( Vec3 const &p ) { x/=p.x; y/=p.y; z/=p.z; return *this; } Vec3 const& operator += ( T const v ) { x+=v; y+=v; z+=v; return *this; } Vec3 const& operator -= ( T const v ) { x-=v; y-=v; z-=v; return *this; } Vec3 const& operator *= ( T const v ) { x*=v; y*=v; z*=v; return *this; } Vec3 const& operator /= ( T const v ) { x/=v; y/=v; z/=v; return *this; } //!@name Test operators bool operator == ( Vec3 const& p ) const { return x==p.x && y==p.y && z==p.z; } bool operator != ( Vec3 const& p ) const { return x!=p.x && y!=p.y && z!=p.z; } //!@name Access operators T& operator [] ( int i ) { return Element(i); } T const& operator [] ( int i ) const { return Element(i); } T& Element ( int i ) { assert(i>=0 && i<3); return elem[i]; } T const& Element ( int i ) const { assert(i>=0 && i<3); return elem[i]; } T* Elements () { return elem; } T const* Elements () const { return elem; } //!@name Cross product and dot product Vec3 Cross ( Vec3 const &p ) const { return Vec3(y*p.z-z*p.y, z*p.x-x*p.z, x*p.y-y*p.x); } //!< Cross product Vec3 operator ^ ( Vec3 const &p ) const { return Cross(p); } //!< Cross product T Dot ( Vec3 const &p ) const { return x*p.x + y*p.y + z*p.z; } //!< Dot product T operator % ( Vec3 const &p ) const { return Dot(p); } //!< Dot product //!@name Conversion Methods Vec2<T> XY() const { return Vec2<T>(*this); } }; //------------------------------------------------------------------------------- //! 4D vector class template <typename T> class Vec4 { friend Vec4 operator + ( T v, Vec4 const &p ) { return p+v; } //!< Addition with a constant friend Vec4 operator - ( T v, Vec4 const &p ) { return -(p-v); } //!< Subtraction from a constant friend Vec4 operator * ( T v, Vec4 const &p ) { return p*v; } //!< Multiplication with a constant public: //!@name Components of the vector union { struct { T x, y, z, w; }; T elem[4]; //!< Array-type access to the vector elements x, y, z, and w }; //!@name Constructors Vec4() CY_CLASS_FUNCTION_DEFAULT Vec4( T _x, T _y, T _z, T _w ) : x( _x), y( _y), z( _z), w( _w) {} explicit Vec4( T v ) : x(v ), y(v ), z(v ), w(v ) {} explicit Vec4( Vec2<T> const &p, T _z=0, T _w=1 ) : x(p.x), y(p.y), z( _z), w( _w) {} explicit Vec4( Vec3<T> const &p, T _w=1 ) : x(p.x), y(p.y), z(p.z), w( _w) {} template <typename S> explicit Vec4( Vec2<S> const &p, T _z=0, T _w=1 ) : x(T(p.x)), y(T(p.y)), z( _z ), w( _w ) {} template <typename S> explicit Vec4( Vec3<S> const &p, T _w=1 ) : x(T(p.x)), y(T(p.y)), z(T(p.z)), w( _w ) {} template <typename S> explicit Vec4( Vec4<S> const &p ) : x(T(p.x)), y(T(p.y)), z(T(p.z)), w(T(p.w)) {} template <int N > explicit Vec4( Vec<T,N> const &p ) { p.CopyData<4>(elem); } template <int N, typename S> explicit Vec4( Vec<S,N> const &p ) { p.ConvertData<T,4>(elem); } //!@name Set & Get value methods void Zero() { MemClear(elem,4); } //!< Sets the coordinates as zero void Get( T *p ) const { ((Vec4*)p)->operator=(*this); } //!< Puts the coordinate values into the array void Set( T const *p ) { operator=(*((Vec4*)p)); } //!< Sets the coordinates using the values in the given array void Set( T v ) { x=v; y=v; z=v; w=v; } //!< Sets all coordinates using the given value void Set( T _x, T _y, T _z, T _w=1 ) { x= _x; y= _y; z= _z; w=_w; } //!< Sets the coordinates using the given values void Set( Vec2<T> const &p, T _z, T _w=1 ) { x=p.x; y=p.y; z= _z; w=_w; } //!< Sets the coordinates using the given values void Set( Vec3<T> const &p, T _w=1 ) { x=p.x; y=p.y; z=p.z; w=_w; } //!< Sets the coordinates using the given values //!@name General methods void Normalize () { *this /= Length(); } //!< Normalizes the vector, such that its length becomes 1. Vec4 GetNormalized() const { return *this / Length(); } //!< Returns a normalized copy of the vector. T LengthSquared() const { Vec4 p=operator*(*this); return p.Sum(); } //!< Returns the square of the length. Effectively, this is the dot product of the vector with itself. T Length () const { return cy::Sqrt(LengthSquared()); } //!< Returns the length of the vector. T Sum () const { return x+y+z+w; } //!< Returns the sum of its components bool IsZero () const { return x==T(0) && y==T(0) && z==T(0) && w==T(0); } //!< Returns true if all components are exactly zero T Min () const { T mxy = x<y ? x : y; T mzw = z<w ? z : w; return mxy<mzw ? mxy : mzw; } //!< Returns the minimum component of the vector. T Max () const { T mxy = x>y ? x : y; T mzw = z>w ? z : w; return mxy>mzw ? mxy : mzw; } //!< Returns the maximum component of the vector. int MinID () const { int ixy = x<y ? 0 : 1; int izw = z<w ? 2 : 3; return elem[ixy]<elem[izw] ? ixy : izw; } //!< Returns the index of the minimum component of the vector. int MaxID () const { int ixy = x>y ? 0 : 1; int izw = z>w ? 2 : 3; return elem[ixy]>elem[izw] ? ixy : izw; } //!< Returns the index of the maximum component of the vector. bool IsFinite () const { return cy::IsFinite(x) && cy::IsFinite(y) && cy::IsFinite(z) && cy::IsFinite(w); } //!< Returns true if all components are finite real numbers. bool IsUnit () const { return std::abs(LengthSquared()-T(1)) < T(0.001); } //!< Returns true if the length of the vector is close to 1. Vec4 Sqrt () const { return Vec4(cy::Sqrt(x),cy::Sqrt(y),cy::Sqrt(z),cy::Sqrt(w)); } //!< Returns the square root of the vector. Vec4 Abs () const { return Vec4(std::abs(x),std::abs(y),std::abs(z),std::abs(w)); } //!< Returns a vector containing the absolute values of all components. Vec4 SortDesc () const { Vec4 v=*this; if(v.x<v.y)Swap(v.x,v.y); if(v.z<v.w)Swap(v.z,v.w); if(v.y<v.z){ Swap(v.y,v.z); if(v.x<v.y)Swap(v.x,v.y); if(v.z<v.w)Swap(v.z,v.w); } return v; } //!< Returns a vector with components sorted in descending order. Vec4 SortAsc () const { Vec4 v=*this; if(v.x>v.y)Swap(v.x,v.y); if(v.z>v.w)Swap(v.z,v.w); if(v.y>v.z){ Swap(v.y,v.z); if(v.x>v.y)Swap(v.x,v.y); if(v.z>v.w)Swap(v.z,v.w); } return v; } //!< Returns a vector with components sorted in descending order. //!@name Limit methods void Clamp ( T minLimit, T maxLimit ) { ClampMin(minLimit); ClampMax(maxLimit); } //!< Ensures that all components of the vector are within the given limits. void ClampMin( T v ) { x=(x<v)?v:x; y=(y<v)?v:y; z=(z<v)?v:z; w=(w<v)?v:w; } //!< Ensures that all components of the vector are greater than or equal to the given limit. void ClampMax( T v ) { x=(x>v)?v:x; y=(y>v)?v:y; z=(z>v)?v:z; w=(w>v)?v:w; } //!< Ensures that all components of the vector are smaller than or equal to the given limit. void SetAbs () { x=std::abs(x); y=std::abs(y); z=std::abs(z); w=std::abs(w); } //!< Converts all negative components to positive values //!@name Unary operators Vec4 operator - () const { Vec4 r; r.x=-x; r.y=-y; r.z=-z; r.w=-w; return r; } //!@name Binary operators Vec4 operator + ( Vec4 const &p ) const { Vec4 r; r.x=x+p.x; r.y=y+p.y; r.z=z+p.z; r.w=w+p.w; return r; } Vec4 operator - ( Vec4 const &p ) const { Vec4 r; r.x=x-p.x; r.y=y-p.y; r.z=z-p.z; r.w=w-p.w; return r; } Vec4 operator * ( Vec4 const &p ) const { Vec4 r; r.x=x*p.x; r.y=y*p.y; r.z=z*p.z; r.w=w*p.w; return r; } Vec4 operator / ( Vec4 const &p ) const { Vec4 r; r.x=x/p.x; r.y=y/p.y; r.z=z/p.z; r.w=w/p.w; return r; } Vec4 operator + ( T const v ) const { Vec4 r; r.x=x+v; r.y=y+v; r.z=z+v; r.w=w+v; return r; } Vec4 operator - ( T const v ) const { Vec4 r; r.x=x-v; r.y=y-v; r.z=z-v; r.w=w-v; return r; } Vec4 operator * ( T const v ) const { Vec4 r; r.x=x*v; r.y=y*v; r.z=z*v; r.w=w*v; return r; } Vec4 operator / ( T const v ) const { Vec4 r; r.x=x/v; r.y=y/v; r.z=z/v; r.w=w/v; return r; } //!@name Assignment operators Vec4 const& operator += ( Vec4 const &p ) { x+=p.x; y+=p.y; z+=p.z; w+=p.w; return *this; } Vec4 const& operator -= ( Vec4 const &p ) { x-=p.x; y-=p.y; z-=p.z; w-=p.w; return *this; } Vec4 const& operator *= ( Vec4 const &p ) { x*=p.x; y*=p.y; z*=p.z; w*=p.w; return *this; } Vec4 const& operator /= ( Vec4 const &p ) { x/=p.x; y/=p.y; z/=p.z; w/=p.w; return *this; } Vec4 const& operator += ( T const v ) { x+=v; y+=v; z+=v; w+=v; return *this; } Vec4 const& operator -= ( T const v ) { x-=v; y-=v; z-=v; w-=v; return *this; } Vec4 const& operator *= ( T const v ) { x*=v; y*=v; z*=v; w*=v; return *this; } Vec4 const& operator /= ( T const v ) { x/=v; y/=v; z/=v; w/=v; return *this; } //!@name Test operators bool operator == ( Vec4 const& p ) const { return x==p.x && y==p.y && z==p.z && w==p.w; } bool operator != ( Vec4 const& p ) const { return x!=p.x && y!=p.y && z!=p.z && w!=p.w; } //!@name Access operators T& operator [] ( int i ) { return Element(i); } T const& operator [] ( int i ) const { return Element(i); } T& Element ( int i ) { assert(i>=0 && i<4); return elem[i]; } T const& Element ( int i ) const { assert(i>=0 && i<4); return elem[i]; } T* Elements () { return elem; } T const* Elements () const { return elem; } //!@name Dot product T Dot ( Vec4 const &p ) const { return x*p.x + y*p.y + z*p.z + w*p.w; } //!< Dot product T operator % ( Vec4 const &p ) const { return Dot(p); } //!< Dot product //!@name Conversion Methods Vec2<T> XY () const { return Vec2<T>(*this); } Vec3<T> XYZ() const { return Vec3<T>(*this); } Vec3<T> GetNonHomogeneous() const { return Vec3<T>(*this)/w; } }; //------------------------------------------------------------------------------- // Definitions of the conversion constructors template <typename T, int N> Vec<T,N>::Vec( Vec2<T> const &p ) { if ( N <= 2 ) { MemCopy (elem,&p.x,N); } else { MemCopy (elem,&p.x,2); MemClear(elem,N-2); } } template <typename T, int N> Vec<T,N>::Vec( Vec3<T> const &p ) { if ( N <= 3 ) { MemCopy (elem,&p.x,N); } else { MemCopy (elem,&p.x,3); MemClear(elem,N-3); } } template <typename T, int N> Vec<T,N>::Vec( Vec4<T> const &p ) { if ( N <= 4 ) { MemCopy (elem,&p.x,N); } else { MemCopy (elem,&p.x,4); MemClear(elem,N-4); } } template <typename T, int N> template <typename S> Vec<T,N>::Vec( Vec2<S> const &p ) { if ( N <= 2 ) { MemConvert(elem,&p.x,N); } else { MemConvert(elem,&p.x,2); MemClear(elem,N-2); } } template <typename T, int N> template <typename S> Vec<T,N>::Vec( Vec3<S> const &p ) { if ( N <= 3 ) { MemConvert(elem,&p.x,N); } else { MemConvert(elem,&p.x,3); MemClear(elem,N-3); } } template <typename T, int N> template <typename S> Vec<T,N>::Vec( Vec4<S> const &p ) { if ( N <= 4 ) { MemConvert(elem,&p.x,N); } else { MemConvert(elem,&p.x,4); MemClear(elem,N-4); } } template <typename T> Vec2<T>::Vec2( Vec3<T> const &p ) : x( p.x ), y( p.y ) {} template <typename T> Vec2<T>::Vec2( Vec4<T> const &p ) : x( p.x ), y( p.y ) {} template <typename T> Vec3<T>::Vec3( Vec4<T> const &p ) : x( p.x ), y( p.y ), z( p.z ) {} template <typename T> template <typename S> Vec2<T>::Vec2( Vec3<S> const &p ) : x(T(p.x)), y(T(p.y)) {} template <typename T> template <typename S> Vec2<T>::Vec2( Vec4<S> const &p ) : x(T(p.x)), y(T(p.y)) {} template <typename T> template <typename S> Vec3<T>::Vec3( Vec4<S> const &p ) : x(T(p.x)), y(T(p.y)), z(T(p.z)) {} //------------------------------------------------------------------------------- /// !@name Support functions template <typename T> inline Vec2<T> Normalize( Vec2<T> const &v ) { return v.GetNormalized(); } template <typename T> inline Vec3<T> Normalize( Vec3<T> const &v ) { return v.GetNormalized(); } template <typename T> inline Vec4<T> Normalize( Vec4<T> const &v ) { return v.GetNormalized(); } //------------------------------------------------------------------------------- typedef Vec2<float> Vec2f; //!< 2D vector class with float type elements typedef Vec3<float> Vec3f; //!< 3D vector class with float type elements typedef Vec4<float> Vec4f; //!< 4D vector class with float type elements typedef Vec2<double> Vec2d; //!< 2D vector class with double type elements typedef Vec3<double> Vec3d; //!< 3D vector class with double type elements typedef Vec4<double> Vec4d; //!< 4D vector class with double type elements //------------------------------------------------------------------------------- } // namespace cy //------------------------------------------------------------------------------- typedef cy::Vec2f cyVec2f; //!< 2D vector class with float type elements typedef cy::Vec3f cyVec3f; //!< 3D vector class with float type elements typedef cy::Vec4f cyVec4f; //!< 4D vector class with float type elements typedef cy::Vec2d cyVec2d; //!< 2D vector class with double type elements typedef cy::Vec3d cyVec3d; //!< 3D vector class with double type elements typedef cy::Vec4d cyVec4d; //!< 4D vector class with double type elements //------------------------------------------------------------------------------- #endif
6c96cff76f6605ee5a744e73123d19aaec3ec78d
41b444116c8431b7e4199f78b0f27f1dc61d190f
/same.cpp
3fca2adf1b3c54943d6a4c6543fad244995e4178
[ "MIT" ]
permissive
lwzhenglittle/NOIP
6caa100b1865c93837deca3283bf43e54c84462f
f256c8d706b3ac985de04a5fae77246f44ba5b23
refs/heads/master
2021-07-12T06:58:37.345212
2020-09-27T12:09:49
2020-09-27T12:09:49
207,077,580
0
0
null
null
null
null
UTF-8
C++
false
false
447
cpp
#include<cstdio> #include<cstring> #include<algorithm> #include<iostream> #include<string> #include<vector> using namespace std; vector<int> a; int main() { int n; scanf("%d",&n); for(int i=0,tmp;i<n;i++){ scanf("%d",&tmp); a.push_back(tmp); } sort(a.begin(),a.end()); for(int i=0;i<a.size();i++){ if(a[i]==a[i+1]){ printf("%d\n",a[i]); break; } } return 0; }
a772e4bac106d88d1bd596a82fffae9d2d1a5ecf
cfdaf6b064fd03ef9e3550efbe74d4f0782304c8
/VasilievAN_Programmirovanie_na_c++/chapter6_classes-and-objects-use/6.1_obj-pointer.cpp
857a62543af3c795d0a2723c826cc431eb12e701
[]
no_license
profLake/SomeOldCppProjects
9af7e90b8c63d8937827dd3a626cd37b2a74c28c
82f2331e647ef6edaf233166b746d4aa1bb52c7f
refs/heads/main
2023-07-29T12:59:02.710124
2021-09-12T19:25:31
2021-09-12T19:25:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,116
cpp
/* * ===================================================================================== * * Filename: 6.1_obj-pointer.cpp * * Description: demonstrates using class pointer * * Version: 1.0 * Created: 06/15/20 15:48:17 * Revision: none * Compiler: g++ * * Author: Artur * Organization: * * ===================================================================================== */ #include <iostream> using namespace std; class NameNum { public: string name; // string - g++ абсолютно не смущает то, что я не подключил int num; // ни <cstring>, ни <string> void show() { cout << "Name: " << name << endl; cout << "Num: " << num << endl; } }; int main() { NameNum a; NameNum b; NameNum *p; p = &a; p->name = "a"; p->num = 1; p->show(); p = &b; p->name = "b"; p->num = 2; p->show(); cout << endl; cout << "Check:" << endl; a.show(); b.show(); return 0; }
e7e691ee9388cd232c837f6afbbdddcfc2fde8a1
18488c64ea8073545133e78a884cac4d6669ccf0
/91_HangDoiHaiDau(DEQUEUE).cpp
88e63ad73be213ac844847e299099d846f3871c5
[]
no_license
manhtung001/Datastructure-Algorithm-PTIT
f6b1c3bbc2476af3989b8796696dbbb7750e91fe
c41a344d4fbfd92bf587eac14861568d2029321b
refs/heads/master
2023-06-24T07:19:33.970580
2021-07-21T13:44:54
2021-07-21T13:44:54
344,992,505
1
1
null
null
null
null
UTF-8
C++
false
false
718
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; main() { deque<ll> q; int t; cin >> t; while (t--) { string s; cin >> s; if (s == "PUSHFRONT") { ll x; cin >> x; q.push_front(x); } else if (s == "PRINTFRONT") { if (!q.empty()) cout << q.front() << endl; else cout << "NONE\n"; } else if (s == "POPFRONT") { if (!q.empty()) q.pop_front(); } else if (s == "PUSHBACK") { ll x; cin >> x; q.push_back(x); } else if (s == "PRINTBACK") { if (!q.empty()) cout << q.back() << endl; else cout << "NONE\n"; } else { if (!q.empty()) q.pop_back(); } } }
1168b234505ad954e8dc22ec2c8a8c258641784a
426aed70aa6925105f10c7fcb7b611b277bf8b84
/src/kernel/cpu/binary_bcast_reduce_max.cc
789ee76e813a69e6d8dfef20e0f3957b575ee9df
[ "Apache-2.0" ]
permissive
hengruizhang98/dgl
0ce7201ca7380482440f031cb8ced6ca0e8c8dc1
195f99362d883f8b6d131b70a7868a537e55b786
refs/heads/master
2023-06-10T22:21:45.835646
2021-04-13T12:29:43
2021-04-13T12:29:43
336,804,001
3
0
Apache-2.0
2021-02-07T14:16:20
2021-02-07T14:16:20
null
UTF-8
C++
false
false
724
cc
/*! * Copyright (c) 2019 by Contributors * \file kernel/cpu/binary_bcast_reduce_max.cc * \brief CPU kernels for braodcasting binary reduce max */ #include "./binary_reduce_impl.h" #include "./backward_binary_reduce_impl.h" namespace dgl { namespace kernel { #define REDUCER ReduceMax #define XPU kDLCPU #define IDX int32_t EVAL(GEN_NDIM, GEN_DTYPE, GEN_OP_TARGET, GEN_BCAST_DEFINE); EVAL(GEN_BACKWARD_MODE, GEN_NDIM, GEN_DTYPE, GEN_OP_TARGET, GEN_BACKWARD_BCAST_DEFINE); #undef IDX #define IDX int64_t EVAL(GEN_NDIM, GEN_DTYPE, GEN_OP_TARGET, GEN_BCAST_DEFINE); EVAL(GEN_BACKWARD_MODE, GEN_NDIM, GEN_DTYPE, GEN_OP_TARGET, GEN_BACKWARD_BCAST_DEFINE); #undef IDX } // namespace kernel } // namespace dgl
b3c9cd09782347eab3c920704744c5a85c0574ab
c776476e9d06b3779d744641e758ac3a2c15cddc
/examples/litmus/c/run-scripts/tmp_5/MP+dmb.sy+ctrl-pos-ctrl-rfi-addr.c.cbmc_out.cpp
25c5968765fed5e6c861c5a03c6db19e9006f643
[]
no_license
ashutosh0gupta/llvm_bmc
aaac7961c723ba6f7ffd77a39559e0e52432eade
0287c4fb180244e6b3c599a9902507f05c8a7234
refs/heads/master
2023-08-02T17:14:06.178723
2023-07-31T10:46:53
2023-07-31T10:46:53
143,100,825
3
4
null
2023-05-25T05:50:55
2018-08-01T03:47:00
C++
UTF-8
C++
false
false
54,008
cpp
// Global variabls: // 0:vars:4 // 4:atom_1_X0_1:1 // 5:atom_1_X7_1:1 // 6:atom_1_X9_0:1 // Local global variabls: // 0:thr0:1 // 1:thr1:1 #define ADDRSIZE 7 #define LOCALADDRSIZE 2 #define NTHREAD 3 #define NCONTEXT 5 #define ASSUME(stmt) __CPROVER_assume(stmt) #define ASSERT(stmt) __CPROVER_assert(stmt, "error") #define max(a,b) (a>b?a:b) char __get_rng(); char get_rng( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } char get_rng_th( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } int main(int argc, char **argv) { // Declare arrays for intial value version in contexts int local_mem[LOCALADDRSIZE]; // Dumping initializations local_mem[0+0] = 0; local_mem[1+0] = 0; int cstart[NTHREAD]; int creturn[NTHREAD]; // declare arrays for contexts activity int active[NCONTEXT]; int ctx_used[NCONTEXT]; // declare arrays for intial value version in contexts int meminit_[ADDRSIZE*NCONTEXT]; #define meminit(x,k) meminit_[(x)*NCONTEXT+k] int coinit_[ADDRSIZE*NCONTEXT]; #define coinit(x,k) coinit_[(x)*NCONTEXT+k] int deltainit_[ADDRSIZE*NCONTEXT]; #define deltainit(x,k) deltainit_[(x)*NCONTEXT+k] // declare arrays for running value version in contexts int mem_[ADDRSIZE*NCONTEXT]; #define mem(x,k) mem_[(x)*NCONTEXT+k] int co_[ADDRSIZE*NCONTEXT]; #define co(x,k) co_[(x)*NCONTEXT+k] int delta_[ADDRSIZE*NCONTEXT]; #define delta(x,k) delta_[(x)*NCONTEXT+k] // declare arrays for local buffer and observed writes int buff_[NTHREAD*ADDRSIZE]; #define buff(x,k) buff_[(x)*ADDRSIZE+k] int pw_[NTHREAD*ADDRSIZE]; #define pw(x,k) pw_[(x)*ADDRSIZE+k] // declare arrays for context stamps char cr_[NTHREAD*ADDRSIZE]; #define cr(x,k) cr_[(x)*ADDRSIZE+k] char iw_[NTHREAD*ADDRSIZE]; #define iw(x,k) iw_[(x)*ADDRSIZE+k] char cw_[NTHREAD*ADDRSIZE]; #define cw(x,k) cw_[(x)*ADDRSIZE+k] char cx_[NTHREAD*ADDRSIZE]; #define cx(x,k) cx_[(x)*ADDRSIZE+k] char is_[NTHREAD*ADDRSIZE]; #define is(x,k) is_[(x)*ADDRSIZE+k] char cs_[NTHREAD*ADDRSIZE]; #define cs(x,k) cs_[(x)*ADDRSIZE+k] char crmax_[NTHREAD*ADDRSIZE]; #define crmax(x,k) crmax_[(x)*ADDRSIZE+k] char sforbid_[ADDRSIZE*NCONTEXT]; #define sforbid(x,k) sforbid_[(x)*NCONTEXT+k] // declare arrays for synchronizations int cl[NTHREAD]; int cdy[NTHREAD]; int cds[NTHREAD]; int cdl[NTHREAD]; int cisb[NTHREAD]; int caddr[NTHREAD]; int cctrl[NTHREAD]; int r0= 0; char creg_r0; char creg__r0__0_; int r1= 0; char creg_r1; int r2= 0; char creg_r2; char creg__r2__0_; int r3= 0; char creg_r3; int r4= 0; char creg_r4; int r5= 0; char creg_r5; int r6= 0; char creg_r6; int r7= 0; char creg_r7; char creg__r0__1_; char creg__r3__1_; char creg__r7__0_; int r8= 0; char creg_r8; int r9= 0; char creg_r9; int r10= 0; char creg_r10; int r11= 0; char creg_r11; char creg__r11__1_; int r12= 0; char creg_r12; char creg__r12__1_; int r13= 0; char creg_r13; char creg__r13__1_; int r14= 0; char creg_r14; int r15= 0; char creg_r15; int r16= 0; char creg_r16; int r17= 0; char creg_r17; int r18= 0; char creg_r18; int r19= 0; char creg_r19; int r20= 0; char creg_r20; int r21= 0; char creg_r21; char creg__r21__1_; int r22= 0; char creg_r22; char old_cctrl= 0; char old_cr= 0; char old_cdy= 0; char old_cw= 0; char new_creg= 0; buff(0,0) = 0; pw(0,0) = 0; cr(0,0) = 0; iw(0,0) = 0; cw(0,0) = 0; cx(0,0) = 0; is(0,0) = 0; cs(0,0) = 0; crmax(0,0) = 0; buff(0,1) = 0; pw(0,1) = 0; cr(0,1) = 0; iw(0,1) = 0; cw(0,1) = 0; cx(0,1) = 0; is(0,1) = 0; cs(0,1) = 0; crmax(0,1) = 0; buff(0,2) = 0; pw(0,2) = 0; cr(0,2) = 0; iw(0,2) = 0; cw(0,2) = 0; cx(0,2) = 0; is(0,2) = 0; cs(0,2) = 0; crmax(0,2) = 0; buff(0,3) = 0; pw(0,3) = 0; cr(0,3) = 0; iw(0,3) = 0; cw(0,3) = 0; cx(0,3) = 0; is(0,3) = 0; cs(0,3) = 0; crmax(0,3) = 0; buff(0,4) = 0; pw(0,4) = 0; cr(0,4) = 0; iw(0,4) = 0; cw(0,4) = 0; cx(0,4) = 0; is(0,4) = 0; cs(0,4) = 0; crmax(0,4) = 0; buff(0,5) = 0; pw(0,5) = 0; cr(0,5) = 0; iw(0,5) = 0; cw(0,5) = 0; cx(0,5) = 0; is(0,5) = 0; cs(0,5) = 0; crmax(0,5) = 0; buff(0,6) = 0; pw(0,6) = 0; cr(0,6) = 0; iw(0,6) = 0; cw(0,6) = 0; cx(0,6) = 0; is(0,6) = 0; cs(0,6) = 0; crmax(0,6) = 0; cl[0] = 0; cdy[0] = 0; cds[0] = 0; cdl[0] = 0; cisb[0] = 0; caddr[0] = 0; cctrl[0] = 0; cstart[0] = get_rng(0,NCONTEXT-1); creturn[0] = get_rng(0,NCONTEXT-1); buff(1,0) = 0; pw(1,0) = 0; cr(1,0) = 0; iw(1,0) = 0; cw(1,0) = 0; cx(1,0) = 0; is(1,0) = 0; cs(1,0) = 0; crmax(1,0) = 0; buff(1,1) = 0; pw(1,1) = 0; cr(1,1) = 0; iw(1,1) = 0; cw(1,1) = 0; cx(1,1) = 0; is(1,1) = 0; cs(1,1) = 0; crmax(1,1) = 0; buff(1,2) = 0; pw(1,2) = 0; cr(1,2) = 0; iw(1,2) = 0; cw(1,2) = 0; cx(1,2) = 0; is(1,2) = 0; cs(1,2) = 0; crmax(1,2) = 0; buff(1,3) = 0; pw(1,3) = 0; cr(1,3) = 0; iw(1,3) = 0; cw(1,3) = 0; cx(1,3) = 0; is(1,3) = 0; cs(1,3) = 0; crmax(1,3) = 0; buff(1,4) = 0; pw(1,4) = 0; cr(1,4) = 0; iw(1,4) = 0; cw(1,4) = 0; cx(1,4) = 0; is(1,4) = 0; cs(1,4) = 0; crmax(1,4) = 0; buff(1,5) = 0; pw(1,5) = 0; cr(1,5) = 0; iw(1,5) = 0; cw(1,5) = 0; cx(1,5) = 0; is(1,5) = 0; cs(1,5) = 0; crmax(1,5) = 0; buff(1,6) = 0; pw(1,6) = 0; cr(1,6) = 0; iw(1,6) = 0; cw(1,6) = 0; cx(1,6) = 0; is(1,6) = 0; cs(1,6) = 0; crmax(1,6) = 0; cl[1] = 0; cdy[1] = 0; cds[1] = 0; cdl[1] = 0; cisb[1] = 0; caddr[1] = 0; cctrl[1] = 0; cstart[1] = get_rng(0,NCONTEXT-1); creturn[1] = get_rng(0,NCONTEXT-1); buff(2,0) = 0; pw(2,0) = 0; cr(2,0) = 0; iw(2,0) = 0; cw(2,0) = 0; cx(2,0) = 0; is(2,0) = 0; cs(2,0) = 0; crmax(2,0) = 0; buff(2,1) = 0; pw(2,1) = 0; cr(2,1) = 0; iw(2,1) = 0; cw(2,1) = 0; cx(2,1) = 0; is(2,1) = 0; cs(2,1) = 0; crmax(2,1) = 0; buff(2,2) = 0; pw(2,2) = 0; cr(2,2) = 0; iw(2,2) = 0; cw(2,2) = 0; cx(2,2) = 0; is(2,2) = 0; cs(2,2) = 0; crmax(2,2) = 0; buff(2,3) = 0; pw(2,3) = 0; cr(2,3) = 0; iw(2,3) = 0; cw(2,3) = 0; cx(2,3) = 0; is(2,3) = 0; cs(2,3) = 0; crmax(2,3) = 0; buff(2,4) = 0; pw(2,4) = 0; cr(2,4) = 0; iw(2,4) = 0; cw(2,4) = 0; cx(2,4) = 0; is(2,4) = 0; cs(2,4) = 0; crmax(2,4) = 0; buff(2,5) = 0; pw(2,5) = 0; cr(2,5) = 0; iw(2,5) = 0; cw(2,5) = 0; cx(2,5) = 0; is(2,5) = 0; cs(2,5) = 0; crmax(2,5) = 0; buff(2,6) = 0; pw(2,6) = 0; cr(2,6) = 0; iw(2,6) = 0; cw(2,6) = 0; cx(2,6) = 0; is(2,6) = 0; cs(2,6) = 0; crmax(2,6) = 0; cl[2] = 0; cdy[2] = 0; cds[2] = 0; cdl[2] = 0; cisb[2] = 0; caddr[2] = 0; cctrl[2] = 0; cstart[2] = get_rng(0,NCONTEXT-1); creturn[2] = get_rng(0,NCONTEXT-1); // Dumping initializations mem(0+0,0) = 0; mem(0+1,0) = 0; mem(0+2,0) = 0; mem(0+3,0) = 0; mem(4+0,0) = 0; mem(5+0,0) = 0; mem(6+0,0) = 0; // Dumping context matching equalities co(0,0) = 0; delta(0,0) = -1; mem(0,1) = meminit(0,1); co(0,1) = coinit(0,1); delta(0,1) = deltainit(0,1); mem(0,2) = meminit(0,2); co(0,2) = coinit(0,2); delta(0,2) = deltainit(0,2); mem(0,3) = meminit(0,3); co(0,3) = coinit(0,3); delta(0,3) = deltainit(0,3); mem(0,4) = meminit(0,4); co(0,4) = coinit(0,4); delta(0,4) = deltainit(0,4); co(1,0) = 0; delta(1,0) = -1; mem(1,1) = meminit(1,1); co(1,1) = coinit(1,1); delta(1,1) = deltainit(1,1); mem(1,2) = meminit(1,2); co(1,2) = coinit(1,2); delta(1,2) = deltainit(1,2); mem(1,3) = meminit(1,3); co(1,3) = coinit(1,3); delta(1,3) = deltainit(1,3); mem(1,4) = meminit(1,4); co(1,4) = coinit(1,4); delta(1,4) = deltainit(1,4); co(2,0) = 0; delta(2,0) = -1; mem(2,1) = meminit(2,1); co(2,1) = coinit(2,1); delta(2,1) = deltainit(2,1); mem(2,2) = meminit(2,2); co(2,2) = coinit(2,2); delta(2,2) = deltainit(2,2); mem(2,3) = meminit(2,3); co(2,3) = coinit(2,3); delta(2,3) = deltainit(2,3); mem(2,4) = meminit(2,4); co(2,4) = coinit(2,4); delta(2,4) = deltainit(2,4); co(3,0) = 0; delta(3,0) = -1; mem(3,1) = meminit(3,1); co(3,1) = coinit(3,1); delta(3,1) = deltainit(3,1); mem(3,2) = meminit(3,2); co(3,2) = coinit(3,2); delta(3,2) = deltainit(3,2); mem(3,3) = meminit(3,3); co(3,3) = coinit(3,3); delta(3,3) = deltainit(3,3); mem(3,4) = meminit(3,4); co(3,4) = coinit(3,4); delta(3,4) = deltainit(3,4); co(4,0) = 0; delta(4,0) = -1; mem(4,1) = meminit(4,1); co(4,1) = coinit(4,1); delta(4,1) = deltainit(4,1); mem(4,2) = meminit(4,2); co(4,2) = coinit(4,2); delta(4,2) = deltainit(4,2); mem(4,3) = meminit(4,3); co(4,3) = coinit(4,3); delta(4,3) = deltainit(4,3); mem(4,4) = meminit(4,4); co(4,4) = coinit(4,4); delta(4,4) = deltainit(4,4); co(5,0) = 0; delta(5,0) = -1; mem(5,1) = meminit(5,1); co(5,1) = coinit(5,1); delta(5,1) = deltainit(5,1); mem(5,2) = meminit(5,2); co(5,2) = coinit(5,2); delta(5,2) = deltainit(5,2); mem(5,3) = meminit(5,3); co(5,3) = coinit(5,3); delta(5,3) = deltainit(5,3); mem(5,4) = meminit(5,4); co(5,4) = coinit(5,4); delta(5,4) = deltainit(5,4); co(6,0) = 0; delta(6,0) = -1; mem(6,1) = meminit(6,1); co(6,1) = coinit(6,1); delta(6,1) = deltainit(6,1); mem(6,2) = meminit(6,2); co(6,2) = coinit(6,2); delta(6,2) = deltainit(6,2); mem(6,3) = meminit(6,3); co(6,3) = coinit(6,3); delta(6,3) = deltainit(6,3); mem(6,4) = meminit(6,4); co(6,4) = coinit(6,4); delta(6,4) = deltainit(6,4); // Dumping thread 1 int ret_thread_1 = 0; cdy[1] = get_rng(0,NCONTEXT-1); ASSUME(cdy[1] >= cstart[1]); T1BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !38, metadata !DIExpression()), !dbg !47 // br label %label_1, !dbg !48 goto T1BLOCK1; T1BLOCK1: // call void @llvm.dbg.label(metadata !46), !dbg !49 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 0), metadata !39, metadata !DIExpression()), !dbg !50 // call void @llvm.dbg.value(metadata i64 1, metadata !42, metadata !DIExpression()), !dbg !50 // store atomic i64 1, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !51 // ST: Guess iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l21_c3 old_cw = cw(1,0); cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l21_c3 // Check ASSUME(active[iw(1,0)] == 1); ASSUME(active[cw(1,0)] == 1); ASSUME(sforbid(0,cw(1,0))== 0); ASSUME(iw(1,0) >= 0); ASSUME(iw(1,0) >= 0); ASSUME(cw(1,0) >= iw(1,0)); ASSUME(cw(1,0) >= old_cw); ASSUME(cw(1,0) >= cr(1,0)); ASSUME(cw(1,0) >= cl[1]); ASSUME(cw(1,0) >= cisb[1]); ASSUME(cw(1,0) >= cdy[1]); ASSUME(cw(1,0) >= cdl[1]); ASSUME(cw(1,0) >= cds[1]); ASSUME(cw(1,0) >= cctrl[1]); ASSUME(cw(1,0) >= caddr[1]); // Update caddr[1] = max(caddr[1],0); buff(1,0) = 1; mem(0,cw(1,0)) = 1; co(0,cw(1,0))+=1; delta(0,cw(1,0)) = -1; ASSUME(creturn[1] >= cw(1,0)); // call void (...) @dmbsy(), !dbg !52 // dumbsy: Guess old_cdy = cdy[1]; cdy[1] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[1] >= old_cdy); ASSUME(cdy[1] >= cisb[1]); ASSUME(cdy[1] >= cdl[1]); ASSUME(cdy[1] >= cds[1]); ASSUME(cdy[1] >= cctrl[1]); ASSUME(cdy[1] >= cw(1,0+0)); ASSUME(cdy[1] >= cw(1,0+1)); ASSUME(cdy[1] >= cw(1,0+2)); ASSUME(cdy[1] >= cw(1,0+3)); ASSUME(cdy[1] >= cw(1,4+0)); ASSUME(cdy[1] >= cw(1,5+0)); ASSUME(cdy[1] >= cw(1,6+0)); ASSUME(cdy[1] >= cr(1,0+0)); ASSUME(cdy[1] >= cr(1,0+1)); ASSUME(cdy[1] >= cr(1,0+2)); ASSUME(cdy[1] >= cr(1,0+3)); ASSUME(cdy[1] >= cr(1,4+0)); ASSUME(cdy[1] >= cr(1,5+0)); ASSUME(cdy[1] >= cr(1,6+0)); ASSUME(creturn[1] >= cdy[1]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 1), metadata !43, metadata !DIExpression()), !dbg !53 // call void @llvm.dbg.value(metadata i64 1, metadata !45, metadata !DIExpression()), !dbg !53 // store atomic i64 1, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !54 // ST: Guess iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l23_c3 old_cw = cw(1,0+1*1); cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l23_c3 // Check ASSUME(active[iw(1,0+1*1)] == 1); ASSUME(active[cw(1,0+1*1)] == 1); ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(cw(1,0+1*1) >= iw(1,0+1*1)); ASSUME(cw(1,0+1*1) >= old_cw); ASSUME(cw(1,0+1*1) >= cr(1,0+1*1)); ASSUME(cw(1,0+1*1) >= cl[1]); ASSUME(cw(1,0+1*1) >= cisb[1]); ASSUME(cw(1,0+1*1) >= cdy[1]); ASSUME(cw(1,0+1*1) >= cdl[1]); ASSUME(cw(1,0+1*1) >= cds[1]); ASSUME(cw(1,0+1*1) >= cctrl[1]); ASSUME(cw(1,0+1*1) >= caddr[1]); // Update caddr[1] = max(caddr[1],0); buff(1,0+1*1) = 1; mem(0+1*1,cw(1,0+1*1)) = 1; co(0+1*1,cw(1,0+1*1))+=1; delta(0+1*1,cw(1,0+1*1)) = -1; ASSUME(creturn[1] >= cw(1,0+1*1)); // ret i8* null, !dbg !55 ret_thread_1 = (- 1); goto T1BLOCK_END; T1BLOCK_END: // Dumping thread 2 int ret_thread_2 = 0; cdy[2] = get_rng(0,NCONTEXT-1); ASSUME(cdy[2] >= cstart[2]); T2BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !58, metadata !DIExpression()), !dbg !89 // br label %label_2, !dbg !71 goto T2BLOCK1; T2BLOCK1: // call void @llvm.dbg.label(metadata !86), !dbg !91 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 1), metadata !60, metadata !DIExpression()), !dbg !92 // %0 = load atomic i64, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !74 // LD: Guess old_cr = cr(2,0+1*1); cr(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM _l29_c15 // Check ASSUME(active[cr(2,0+1*1)] == 2); ASSUME(cr(2,0+1*1) >= iw(2,0+1*1)); ASSUME(cr(2,0+1*1) >= 0); ASSUME(cr(2,0+1*1) >= cdy[2]); ASSUME(cr(2,0+1*1) >= cisb[2]); ASSUME(cr(2,0+1*1) >= cdl[2]); ASSUME(cr(2,0+1*1) >= cl[2]); // Update creg_r0 = cr(2,0+1*1); crmax(2,0+1*1) = max(crmax(2,0+1*1),cr(2,0+1*1)); caddr[2] = max(caddr[2],0); if(cr(2,0+1*1) < cw(2,0+1*1)) { r0 = buff(2,0+1*1); ASSUME((!(( (cw(2,0+1*1) < 1) && (1 < crmax(2,0+1*1)) )))||(sforbid(0+1*1,1)> 0)); ASSUME((!(( (cw(2,0+1*1) < 2) && (2 < crmax(2,0+1*1)) )))||(sforbid(0+1*1,2)> 0)); ASSUME((!(( (cw(2,0+1*1) < 3) && (3 < crmax(2,0+1*1)) )))||(sforbid(0+1*1,3)> 0)); ASSUME((!(( (cw(2,0+1*1) < 4) && (4 < crmax(2,0+1*1)) )))||(sforbid(0+1*1,4)> 0)); } else { if(pw(2,0+1*1) != co(0+1*1,cr(2,0+1*1))) { ASSUME(cr(2,0+1*1) >= old_cr); } pw(2,0+1*1) = co(0+1*1,cr(2,0+1*1)); r0 = mem(0+1*1,cr(2,0+1*1)); } ASSUME(creturn[2] >= cr(2,0+1*1)); // call void @llvm.dbg.value(metadata i64 %0, metadata !62, metadata !DIExpression()), !dbg !92 // %conv = trunc i64 %0 to i32, !dbg !75 // call void @llvm.dbg.value(metadata i32 %conv, metadata !59, metadata !DIExpression()), !dbg !89 // %tobool = icmp ne i32 %conv, 0, !dbg !76 creg__r0__0_ = max(0,creg_r0); // br i1 %tobool, label %if.then, label %if.else, !dbg !78 old_cctrl = cctrl[2]; cctrl[2] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[2] >= old_cctrl); ASSUME(cctrl[2] >= creg__r0__0_); if((r0!=0)) { goto T2BLOCK2; } else { goto T2BLOCK3; } T2BLOCK2: // br label %lbl_LC00, !dbg !79 goto T2BLOCK4; T2BLOCK3: // br label %lbl_LC00, !dbg !80 goto T2BLOCK4; T2BLOCK4: // call void @llvm.dbg.label(metadata !87), !dbg !100 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 2), metadata !64, metadata !DIExpression()), !dbg !101 // %1 = load atomic i64, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !83 // LD: Guess old_cr = cr(2,0+2*1); cr(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM _l32_c15 // Check ASSUME(active[cr(2,0+2*1)] == 2); ASSUME(cr(2,0+2*1) >= iw(2,0+2*1)); ASSUME(cr(2,0+2*1) >= 0); ASSUME(cr(2,0+2*1) >= cdy[2]); ASSUME(cr(2,0+2*1) >= cisb[2]); ASSUME(cr(2,0+2*1) >= cdl[2]); ASSUME(cr(2,0+2*1) >= cl[2]); // Update creg_r1 = cr(2,0+2*1); crmax(2,0+2*1) = max(crmax(2,0+2*1),cr(2,0+2*1)); caddr[2] = max(caddr[2],0); if(cr(2,0+2*1) < cw(2,0+2*1)) { r1 = buff(2,0+2*1); ASSUME((!(( (cw(2,0+2*1) < 1) && (1 < crmax(2,0+2*1)) )))||(sforbid(0+2*1,1)> 0)); ASSUME((!(( (cw(2,0+2*1) < 2) && (2 < crmax(2,0+2*1)) )))||(sforbid(0+2*1,2)> 0)); ASSUME((!(( (cw(2,0+2*1) < 3) && (3 < crmax(2,0+2*1)) )))||(sforbid(0+2*1,3)> 0)); ASSUME((!(( (cw(2,0+2*1) < 4) && (4 < crmax(2,0+2*1)) )))||(sforbid(0+2*1,4)> 0)); } else { if(pw(2,0+2*1) != co(0+2*1,cr(2,0+2*1))) { ASSUME(cr(2,0+2*1) >= old_cr); } pw(2,0+2*1) = co(0+2*1,cr(2,0+2*1)); r1 = mem(0+2*1,cr(2,0+2*1)); } ASSUME(creturn[2] >= cr(2,0+2*1)); // call void @llvm.dbg.value(metadata i64 %1, metadata !66, metadata !DIExpression()), !dbg !101 // %conv4 = trunc i64 %1 to i32, !dbg !84 // call void @llvm.dbg.value(metadata i32 %conv4, metadata !63, metadata !DIExpression()), !dbg !89 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 2), metadata !68, metadata !DIExpression()), !dbg !104 // %2 = load atomic i64, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !86 // LD: Guess old_cr = cr(2,0+2*1); cr(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM _l33_c15 // Check ASSUME(active[cr(2,0+2*1)] == 2); ASSUME(cr(2,0+2*1) >= iw(2,0+2*1)); ASSUME(cr(2,0+2*1) >= 0); ASSUME(cr(2,0+2*1) >= cdy[2]); ASSUME(cr(2,0+2*1) >= cisb[2]); ASSUME(cr(2,0+2*1) >= cdl[2]); ASSUME(cr(2,0+2*1) >= cl[2]); // Update creg_r2 = cr(2,0+2*1); crmax(2,0+2*1) = max(crmax(2,0+2*1),cr(2,0+2*1)); caddr[2] = max(caddr[2],0); if(cr(2,0+2*1) < cw(2,0+2*1)) { r2 = buff(2,0+2*1); ASSUME((!(( (cw(2,0+2*1) < 1) && (1 < crmax(2,0+2*1)) )))||(sforbid(0+2*1,1)> 0)); ASSUME((!(( (cw(2,0+2*1) < 2) && (2 < crmax(2,0+2*1)) )))||(sforbid(0+2*1,2)> 0)); ASSUME((!(( (cw(2,0+2*1) < 3) && (3 < crmax(2,0+2*1)) )))||(sforbid(0+2*1,3)> 0)); ASSUME((!(( (cw(2,0+2*1) < 4) && (4 < crmax(2,0+2*1)) )))||(sforbid(0+2*1,4)> 0)); } else { if(pw(2,0+2*1) != co(0+2*1,cr(2,0+2*1))) { ASSUME(cr(2,0+2*1) >= old_cr); } pw(2,0+2*1) = co(0+2*1,cr(2,0+2*1)); r2 = mem(0+2*1,cr(2,0+2*1)); } ASSUME(creturn[2] >= cr(2,0+2*1)); // call void @llvm.dbg.value(metadata i64 %2, metadata !70, metadata !DIExpression()), !dbg !104 // %conv8 = trunc i64 %2 to i32, !dbg !87 // call void @llvm.dbg.value(metadata i32 %conv8, metadata !67, metadata !DIExpression()), !dbg !89 // %tobool9 = icmp ne i32 %conv8, 0, !dbg !88 creg__r2__0_ = max(0,creg_r2); // br i1 %tobool9, label %if.then10, label %if.else11, !dbg !90 old_cctrl = cctrl[2]; cctrl[2] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[2] >= old_cctrl); ASSUME(cctrl[2] >= creg__r2__0_); if((r2!=0)) { goto T2BLOCK5; } else { goto T2BLOCK6; } T2BLOCK5: // br label %lbl_LC01, !dbg !91 goto T2BLOCK7; T2BLOCK6: // br label %lbl_LC01, !dbg !92 goto T2BLOCK7; T2BLOCK7: // call void @llvm.dbg.label(metadata !88), !dbg !112 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 3), metadata !71, metadata !DIExpression()), !dbg !113 // call void @llvm.dbg.value(metadata i64 1, metadata !73, metadata !DIExpression()), !dbg !113 // store atomic i64 1, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 3) monotonic, align 8, !dbg !95 // ST: Guess iw(2,0+3*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l36_c3 old_cw = cw(2,0+3*1); cw(2,0+3*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l36_c3 // Check ASSUME(active[iw(2,0+3*1)] == 2); ASSUME(active[cw(2,0+3*1)] == 2); ASSUME(sforbid(0+3*1,cw(2,0+3*1))== 0); ASSUME(iw(2,0+3*1) >= 0); ASSUME(iw(2,0+3*1) >= 0); ASSUME(cw(2,0+3*1) >= iw(2,0+3*1)); ASSUME(cw(2,0+3*1) >= old_cw); ASSUME(cw(2,0+3*1) >= cr(2,0+3*1)); ASSUME(cw(2,0+3*1) >= cl[2]); ASSUME(cw(2,0+3*1) >= cisb[2]); ASSUME(cw(2,0+3*1) >= cdy[2]); ASSUME(cw(2,0+3*1) >= cdl[2]); ASSUME(cw(2,0+3*1) >= cds[2]); ASSUME(cw(2,0+3*1) >= cctrl[2]); ASSUME(cw(2,0+3*1) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,0+3*1) = 1; mem(0+3*1,cw(2,0+3*1)) = 1; co(0+3*1,cw(2,0+3*1))+=1; delta(0+3*1,cw(2,0+3*1)) = -1; ASSUME(creturn[2] >= cw(2,0+3*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 3), metadata !75, metadata !DIExpression()), !dbg !115 // %3 = load atomic i64, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 3) monotonic, align 8, !dbg !97 // LD: Guess old_cr = cr(2,0+3*1); cr(2,0+3*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM _l37_c16 // Check ASSUME(active[cr(2,0+3*1)] == 2); ASSUME(cr(2,0+3*1) >= iw(2,0+3*1)); ASSUME(cr(2,0+3*1) >= 0); ASSUME(cr(2,0+3*1) >= cdy[2]); ASSUME(cr(2,0+3*1) >= cisb[2]); ASSUME(cr(2,0+3*1) >= cdl[2]); ASSUME(cr(2,0+3*1) >= cl[2]); // Update creg_r3 = cr(2,0+3*1); crmax(2,0+3*1) = max(crmax(2,0+3*1),cr(2,0+3*1)); caddr[2] = max(caddr[2],0); if(cr(2,0+3*1) < cw(2,0+3*1)) { r3 = buff(2,0+3*1); ASSUME((!(( (cw(2,0+3*1) < 1) && (1 < crmax(2,0+3*1)) )))||(sforbid(0+3*1,1)> 0)); ASSUME((!(( (cw(2,0+3*1) < 2) && (2 < crmax(2,0+3*1)) )))||(sforbid(0+3*1,2)> 0)); ASSUME((!(( (cw(2,0+3*1) < 3) && (3 < crmax(2,0+3*1)) )))||(sforbid(0+3*1,3)> 0)); ASSUME((!(( (cw(2,0+3*1) < 4) && (4 < crmax(2,0+3*1)) )))||(sforbid(0+3*1,4)> 0)); } else { if(pw(2,0+3*1) != co(0+3*1,cr(2,0+3*1))) { ASSUME(cr(2,0+3*1) >= old_cr); } pw(2,0+3*1) = co(0+3*1,cr(2,0+3*1)); r3 = mem(0+3*1,cr(2,0+3*1)); } ASSUME(creturn[2] >= cr(2,0+3*1)); // call void @llvm.dbg.value(metadata i64 %3, metadata !77, metadata !DIExpression()), !dbg !115 // %conv15 = trunc i64 %3 to i32, !dbg !98 // call void @llvm.dbg.value(metadata i32 %conv15, metadata !74, metadata !DIExpression()), !dbg !89 // %xor = xor i32 %conv15, %conv15, !dbg !99 creg_r4 = creg_r3; r4 = r3 ^ r3; // call void @llvm.dbg.value(metadata i32 %xor, metadata !78, metadata !DIExpression()), !dbg !89 // %add = add nsw i32 0, %xor, !dbg !100 creg_r5 = max(0,creg_r4); r5 = 0 + r4; // %idxprom = sext i32 %add to i64, !dbg !100 // %arrayidx = getelementptr inbounds [4 x i64], [4 x i64]* @vars, i64 0, i64 %idxprom, !dbg !100 r6 = 0+r5*1; creg_r6 = creg_r5; // call void @llvm.dbg.value(metadata i64* %arrayidx, metadata !80, metadata !DIExpression()), !dbg !120 // %4 = load atomic i64, i64* %arrayidx monotonic, align 8, !dbg !100 // LD: Guess old_cr = cr(2,r6); cr(2,r6) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM _l39_c16 // Check ASSUME(active[cr(2,r6)] == 2); ASSUME(cr(2,r6) >= iw(2,r6)); ASSUME(cr(2,r6) >= creg_r6); ASSUME(cr(2,r6) >= cdy[2]); ASSUME(cr(2,r6) >= cisb[2]); ASSUME(cr(2,r6) >= cdl[2]); ASSUME(cr(2,r6) >= cl[2]); // Update creg_r7 = cr(2,r6); crmax(2,r6) = max(crmax(2,r6),cr(2,r6)); caddr[2] = max(caddr[2],creg_r6); if(cr(2,r6) < cw(2,r6)) { r7 = buff(2,r6); ASSUME((!(( (cw(2,r6) < 1) && (1 < crmax(2,r6)) )))||(sforbid(r6,1)> 0)); ASSUME((!(( (cw(2,r6) < 2) && (2 < crmax(2,r6)) )))||(sforbid(r6,2)> 0)); ASSUME((!(( (cw(2,r6) < 3) && (3 < crmax(2,r6)) )))||(sforbid(r6,3)> 0)); ASSUME((!(( (cw(2,r6) < 4) && (4 < crmax(2,r6)) )))||(sforbid(r6,4)> 0)); } else { if(pw(2,r6) != co(r6,cr(2,r6))) { ASSUME(cr(2,r6) >= old_cr); } pw(2,r6) = co(r6,cr(2,r6)); r7 = mem(r6,cr(2,r6)); } ASSUME(creturn[2] >= cr(2,r6)); // call void @llvm.dbg.value(metadata i64 %4, metadata !82, metadata !DIExpression()), !dbg !120 // %conv19 = trunc i64 %4 to i32, !dbg !102 // call void @llvm.dbg.value(metadata i32 %conv19, metadata !79, metadata !DIExpression()), !dbg !89 // %cmp = icmp eq i32 %conv, 1, !dbg !103 creg__r0__1_ = max(0,creg_r0); // %conv20 = zext i1 %cmp to i32, !dbg !103 // call void @llvm.dbg.value(metadata i32 %conv20, metadata !83, metadata !DIExpression()), !dbg !89 // store i32 %conv20, i32* @atom_1_X0_1, align 4, !dbg !104, !tbaa !105 // ST: Guess iw(2,4) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l41_c15 old_cw = cw(2,4); cw(2,4) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l41_c15 // Check ASSUME(active[iw(2,4)] == 2); ASSUME(active[cw(2,4)] == 2); ASSUME(sforbid(4,cw(2,4))== 0); ASSUME(iw(2,4) >= creg__r0__1_); ASSUME(iw(2,4) >= 0); ASSUME(cw(2,4) >= iw(2,4)); ASSUME(cw(2,4) >= old_cw); ASSUME(cw(2,4) >= cr(2,4)); ASSUME(cw(2,4) >= cl[2]); ASSUME(cw(2,4) >= cisb[2]); ASSUME(cw(2,4) >= cdy[2]); ASSUME(cw(2,4) >= cdl[2]); ASSUME(cw(2,4) >= cds[2]); ASSUME(cw(2,4) >= cctrl[2]); ASSUME(cw(2,4) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,4) = (r0==1); mem(4,cw(2,4)) = (r0==1); co(4,cw(2,4))+=1; delta(4,cw(2,4)) = -1; ASSUME(creturn[2] >= cw(2,4)); // %cmp21 = icmp eq i32 %conv15, 1, !dbg !109 creg__r3__1_ = max(0,creg_r3); // %conv22 = zext i1 %cmp21 to i32, !dbg !109 // call void @llvm.dbg.value(metadata i32 %conv22, metadata !84, metadata !DIExpression()), !dbg !89 // store i32 %conv22, i32* @atom_1_X7_1, align 4, !dbg !110, !tbaa !105 // ST: Guess iw(2,5) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l43_c15 old_cw = cw(2,5); cw(2,5) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l43_c15 // Check ASSUME(active[iw(2,5)] == 2); ASSUME(active[cw(2,5)] == 2); ASSUME(sforbid(5,cw(2,5))== 0); ASSUME(iw(2,5) >= creg__r3__1_); ASSUME(iw(2,5) >= 0); ASSUME(cw(2,5) >= iw(2,5)); ASSUME(cw(2,5) >= old_cw); ASSUME(cw(2,5) >= cr(2,5)); ASSUME(cw(2,5) >= cl[2]); ASSUME(cw(2,5) >= cisb[2]); ASSUME(cw(2,5) >= cdy[2]); ASSUME(cw(2,5) >= cdl[2]); ASSUME(cw(2,5) >= cds[2]); ASSUME(cw(2,5) >= cctrl[2]); ASSUME(cw(2,5) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,5) = (r3==1); mem(5,cw(2,5)) = (r3==1); co(5,cw(2,5))+=1; delta(5,cw(2,5)) = -1; ASSUME(creturn[2] >= cw(2,5)); // %cmp23 = icmp eq i32 %conv19, 0, !dbg !111 creg__r7__0_ = max(0,creg_r7); // %conv24 = zext i1 %cmp23 to i32, !dbg !111 // call void @llvm.dbg.value(metadata i32 %conv24, metadata !85, metadata !DIExpression()), !dbg !89 // store i32 %conv24, i32* @atom_1_X9_0, align 4, !dbg !112, !tbaa !105 // ST: Guess iw(2,6) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l45_c15 old_cw = cw(2,6); cw(2,6) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l45_c15 // Check ASSUME(active[iw(2,6)] == 2); ASSUME(active[cw(2,6)] == 2); ASSUME(sforbid(6,cw(2,6))== 0); ASSUME(iw(2,6) >= creg__r7__0_); ASSUME(iw(2,6) >= 0); ASSUME(cw(2,6) >= iw(2,6)); ASSUME(cw(2,6) >= old_cw); ASSUME(cw(2,6) >= cr(2,6)); ASSUME(cw(2,6) >= cl[2]); ASSUME(cw(2,6) >= cisb[2]); ASSUME(cw(2,6) >= cdy[2]); ASSUME(cw(2,6) >= cdl[2]); ASSUME(cw(2,6) >= cds[2]); ASSUME(cw(2,6) >= cctrl[2]); ASSUME(cw(2,6) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,6) = (r7==0); mem(6,cw(2,6)) = (r7==0); co(6,cw(2,6))+=1; delta(6,cw(2,6)) = -1; ASSUME(creturn[2] >= cw(2,6)); // ret i8* null, !dbg !113 ret_thread_2 = (- 1); goto T2BLOCK_END; T2BLOCK_END: // Dumping thread 0 int ret_thread_0 = 0; cdy[0] = get_rng(0,NCONTEXT-1); ASSUME(cdy[0] >= cstart[0]); T0BLOCK0: // %thr0 = alloca i64, align 8 // %thr1 = alloca i64, align 8 // call void @llvm.dbg.value(metadata i32 %argc, metadata !140, metadata !DIExpression()), !dbg !182 // call void @llvm.dbg.value(metadata i8** %argv, metadata !141, metadata !DIExpression()), !dbg !182 // %0 = bitcast i64* %thr0 to i8*, !dbg !85 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !85 // call void @llvm.dbg.declare(metadata i64* %thr0, metadata !142, metadata !DIExpression()), !dbg !184 // %1 = bitcast i64* %thr1 to i8*, !dbg !87 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !87 // call void @llvm.dbg.declare(metadata i64* %thr1, metadata !146, metadata !DIExpression()), !dbg !186 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 3), metadata !147, metadata !DIExpression()), !dbg !187 // call void @llvm.dbg.value(metadata i64 0, metadata !149, metadata !DIExpression()), !dbg !187 // store atomic i64 0, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 3) monotonic, align 8, !dbg !90 // ST: Guess iw(0,0+3*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l53_c3 old_cw = cw(0,0+3*1); cw(0,0+3*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l53_c3 // Check ASSUME(active[iw(0,0+3*1)] == 0); ASSUME(active[cw(0,0+3*1)] == 0); ASSUME(sforbid(0+3*1,cw(0,0+3*1))== 0); ASSUME(iw(0,0+3*1) >= 0); ASSUME(iw(0,0+3*1) >= 0); ASSUME(cw(0,0+3*1) >= iw(0,0+3*1)); ASSUME(cw(0,0+3*1) >= old_cw); ASSUME(cw(0,0+3*1) >= cr(0,0+3*1)); ASSUME(cw(0,0+3*1) >= cl[0]); ASSUME(cw(0,0+3*1) >= cisb[0]); ASSUME(cw(0,0+3*1) >= cdy[0]); ASSUME(cw(0,0+3*1) >= cdl[0]); ASSUME(cw(0,0+3*1) >= cds[0]); ASSUME(cw(0,0+3*1) >= cctrl[0]); ASSUME(cw(0,0+3*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+3*1) = 0; mem(0+3*1,cw(0,0+3*1)) = 0; co(0+3*1,cw(0,0+3*1))+=1; delta(0+3*1,cw(0,0+3*1)) = -1; ASSUME(creturn[0] >= cw(0,0+3*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 2), metadata !150, metadata !DIExpression()), !dbg !189 // call void @llvm.dbg.value(metadata i64 0, metadata !152, metadata !DIExpression()), !dbg !189 // store atomic i64 0, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !92 // ST: Guess iw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l54_c3 old_cw = cw(0,0+2*1); cw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l54_c3 // Check ASSUME(active[iw(0,0+2*1)] == 0); ASSUME(active[cw(0,0+2*1)] == 0); ASSUME(sforbid(0+2*1,cw(0,0+2*1))== 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(cw(0,0+2*1) >= iw(0,0+2*1)); ASSUME(cw(0,0+2*1) >= old_cw); ASSUME(cw(0,0+2*1) >= cr(0,0+2*1)); ASSUME(cw(0,0+2*1) >= cl[0]); ASSUME(cw(0,0+2*1) >= cisb[0]); ASSUME(cw(0,0+2*1) >= cdy[0]); ASSUME(cw(0,0+2*1) >= cdl[0]); ASSUME(cw(0,0+2*1) >= cds[0]); ASSUME(cw(0,0+2*1) >= cctrl[0]); ASSUME(cw(0,0+2*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+2*1) = 0; mem(0+2*1,cw(0,0+2*1)) = 0; co(0+2*1,cw(0,0+2*1))+=1; delta(0+2*1,cw(0,0+2*1)) = -1; ASSUME(creturn[0] >= cw(0,0+2*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 1), metadata !153, metadata !DIExpression()), !dbg !191 // call void @llvm.dbg.value(metadata i64 0, metadata !155, metadata !DIExpression()), !dbg !191 // store atomic i64 0, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !94 // ST: Guess iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l55_c3 old_cw = cw(0,0+1*1); cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l55_c3 // Check ASSUME(active[iw(0,0+1*1)] == 0); ASSUME(active[cw(0,0+1*1)] == 0); ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(cw(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cw(0,0+1*1) >= old_cw); ASSUME(cw(0,0+1*1) >= cr(0,0+1*1)); ASSUME(cw(0,0+1*1) >= cl[0]); ASSUME(cw(0,0+1*1) >= cisb[0]); ASSUME(cw(0,0+1*1) >= cdy[0]); ASSUME(cw(0,0+1*1) >= cdl[0]); ASSUME(cw(0,0+1*1) >= cds[0]); ASSUME(cw(0,0+1*1) >= cctrl[0]); ASSUME(cw(0,0+1*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+1*1) = 0; mem(0+1*1,cw(0,0+1*1)) = 0; co(0+1*1,cw(0,0+1*1))+=1; delta(0+1*1,cw(0,0+1*1)) = -1; ASSUME(creturn[0] >= cw(0,0+1*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 0), metadata !156, metadata !DIExpression()), !dbg !193 // call void @llvm.dbg.value(metadata i64 0, metadata !158, metadata !DIExpression()), !dbg !193 // store atomic i64 0, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !96 // ST: Guess iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l56_c3 old_cw = cw(0,0); cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l56_c3 // Check ASSUME(active[iw(0,0)] == 0); ASSUME(active[cw(0,0)] == 0); ASSUME(sforbid(0,cw(0,0))== 0); ASSUME(iw(0,0) >= 0); ASSUME(iw(0,0) >= 0); ASSUME(cw(0,0) >= iw(0,0)); ASSUME(cw(0,0) >= old_cw); ASSUME(cw(0,0) >= cr(0,0)); ASSUME(cw(0,0) >= cl[0]); ASSUME(cw(0,0) >= cisb[0]); ASSUME(cw(0,0) >= cdy[0]); ASSUME(cw(0,0) >= cdl[0]); ASSUME(cw(0,0) >= cds[0]); ASSUME(cw(0,0) >= cctrl[0]); ASSUME(cw(0,0) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0) = 0; mem(0,cw(0,0)) = 0; co(0,cw(0,0))+=1; delta(0,cw(0,0)) = -1; ASSUME(creturn[0] >= cw(0,0)); // store i32 0, i32* @atom_1_X0_1, align 4, !dbg !97, !tbaa !98 // ST: Guess iw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l57_c15 old_cw = cw(0,4); cw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l57_c15 // Check ASSUME(active[iw(0,4)] == 0); ASSUME(active[cw(0,4)] == 0); ASSUME(sforbid(4,cw(0,4))== 0); ASSUME(iw(0,4) >= 0); ASSUME(iw(0,4) >= 0); ASSUME(cw(0,4) >= iw(0,4)); ASSUME(cw(0,4) >= old_cw); ASSUME(cw(0,4) >= cr(0,4)); ASSUME(cw(0,4) >= cl[0]); ASSUME(cw(0,4) >= cisb[0]); ASSUME(cw(0,4) >= cdy[0]); ASSUME(cw(0,4) >= cdl[0]); ASSUME(cw(0,4) >= cds[0]); ASSUME(cw(0,4) >= cctrl[0]); ASSUME(cw(0,4) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,4) = 0; mem(4,cw(0,4)) = 0; co(4,cw(0,4))+=1; delta(4,cw(0,4)) = -1; ASSUME(creturn[0] >= cw(0,4)); // store i32 0, i32* @atom_1_X7_1, align 4, !dbg !102, !tbaa !98 // ST: Guess iw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l58_c15 old_cw = cw(0,5); cw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l58_c15 // Check ASSUME(active[iw(0,5)] == 0); ASSUME(active[cw(0,5)] == 0); ASSUME(sforbid(5,cw(0,5))== 0); ASSUME(iw(0,5) >= 0); ASSUME(iw(0,5) >= 0); ASSUME(cw(0,5) >= iw(0,5)); ASSUME(cw(0,5) >= old_cw); ASSUME(cw(0,5) >= cr(0,5)); ASSUME(cw(0,5) >= cl[0]); ASSUME(cw(0,5) >= cisb[0]); ASSUME(cw(0,5) >= cdy[0]); ASSUME(cw(0,5) >= cdl[0]); ASSUME(cw(0,5) >= cds[0]); ASSUME(cw(0,5) >= cctrl[0]); ASSUME(cw(0,5) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,5) = 0; mem(5,cw(0,5)) = 0; co(5,cw(0,5))+=1; delta(5,cw(0,5)) = -1; ASSUME(creturn[0] >= cw(0,5)); // store i32 0, i32* @atom_1_X9_0, align 4, !dbg !103, !tbaa !98 // ST: Guess iw(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l59_c15 old_cw = cw(0,6); cw(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l59_c15 // Check ASSUME(active[iw(0,6)] == 0); ASSUME(active[cw(0,6)] == 0); ASSUME(sforbid(6,cw(0,6))== 0); ASSUME(iw(0,6) >= 0); ASSUME(iw(0,6) >= 0); ASSUME(cw(0,6) >= iw(0,6)); ASSUME(cw(0,6) >= old_cw); ASSUME(cw(0,6) >= cr(0,6)); ASSUME(cw(0,6) >= cl[0]); ASSUME(cw(0,6) >= cisb[0]); ASSUME(cw(0,6) >= cdy[0]); ASSUME(cw(0,6) >= cdl[0]); ASSUME(cw(0,6) >= cds[0]); ASSUME(cw(0,6) >= cctrl[0]); ASSUME(cw(0,6) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,6) = 0; mem(6,cw(0,6)) = 0; co(6,cw(0,6))+=1; delta(6,cw(0,6)) = -1; ASSUME(creturn[0] >= cw(0,6)); // %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !104 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,0+3)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,0+3)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[1] >= cdy[0]); // %call7 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !105 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,0+3)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,0+3)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[2] >= cdy[0]); // %2 = load i64, i64* %thr0, align 8, !dbg !106, !tbaa !107 r9 = local_mem[0]; // %call8 = call i32 @pthread_join(i64 noundef %2, i8** noundef null), !dbg !109 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,0+3)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,0+3)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[1]); // %3 = load i64, i64* %thr1, align 8, !dbg !110, !tbaa !107 r10 = local_mem[1]; // %call9 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !111 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,0+3)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,0+3)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[2]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 3), metadata !160, metadata !DIExpression()), !dbg !206 // %4 = load atomic i64, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 3) monotonic, align 8, !dbg !113 // LD: Guess old_cr = cr(0,0+3*1); cr(0,0+3*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l67_c13 // Check ASSUME(active[cr(0,0+3*1)] == 0); ASSUME(cr(0,0+3*1) >= iw(0,0+3*1)); ASSUME(cr(0,0+3*1) >= 0); ASSUME(cr(0,0+3*1) >= cdy[0]); ASSUME(cr(0,0+3*1) >= cisb[0]); ASSUME(cr(0,0+3*1) >= cdl[0]); ASSUME(cr(0,0+3*1) >= cl[0]); // Update creg_r11 = cr(0,0+3*1); crmax(0,0+3*1) = max(crmax(0,0+3*1),cr(0,0+3*1)); caddr[0] = max(caddr[0],0); if(cr(0,0+3*1) < cw(0,0+3*1)) { r11 = buff(0,0+3*1); ASSUME((!(( (cw(0,0+3*1) < 1) && (1 < crmax(0,0+3*1)) )))||(sforbid(0+3*1,1)> 0)); ASSUME((!(( (cw(0,0+3*1) < 2) && (2 < crmax(0,0+3*1)) )))||(sforbid(0+3*1,2)> 0)); ASSUME((!(( (cw(0,0+3*1) < 3) && (3 < crmax(0,0+3*1)) )))||(sforbid(0+3*1,3)> 0)); ASSUME((!(( (cw(0,0+3*1) < 4) && (4 < crmax(0,0+3*1)) )))||(sforbid(0+3*1,4)> 0)); } else { if(pw(0,0+3*1) != co(0+3*1,cr(0,0+3*1))) { ASSUME(cr(0,0+3*1) >= old_cr); } pw(0,0+3*1) = co(0+3*1,cr(0,0+3*1)); r11 = mem(0+3*1,cr(0,0+3*1)); } ASSUME(creturn[0] >= cr(0,0+3*1)); // call void @llvm.dbg.value(metadata i64 %4, metadata !162, metadata !DIExpression()), !dbg !206 // %conv = trunc i64 %4 to i32, !dbg !114 // call void @llvm.dbg.value(metadata i32 %conv, metadata !159, metadata !DIExpression()), !dbg !182 // %cmp = icmp eq i32 %conv, 1, !dbg !115 creg__r11__1_ = max(0,creg_r11); // %conv10 = zext i1 %cmp to i32, !dbg !115 // call void @llvm.dbg.value(metadata i32 %conv10, metadata !163, metadata !DIExpression()), !dbg !182 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 0), metadata !165, metadata !DIExpression()), !dbg !210 // %5 = load atomic i64, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !117 // LD: Guess old_cr = cr(0,0); cr(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l69_c13 // Check ASSUME(active[cr(0,0)] == 0); ASSUME(cr(0,0) >= iw(0,0)); ASSUME(cr(0,0) >= 0); ASSUME(cr(0,0) >= cdy[0]); ASSUME(cr(0,0) >= cisb[0]); ASSUME(cr(0,0) >= cdl[0]); ASSUME(cr(0,0) >= cl[0]); // Update creg_r12 = cr(0,0); crmax(0,0) = max(crmax(0,0),cr(0,0)); caddr[0] = max(caddr[0],0); if(cr(0,0) < cw(0,0)) { r12 = buff(0,0); ASSUME((!(( (cw(0,0) < 1) && (1 < crmax(0,0)) )))||(sforbid(0,1)> 0)); ASSUME((!(( (cw(0,0) < 2) && (2 < crmax(0,0)) )))||(sforbid(0,2)> 0)); ASSUME((!(( (cw(0,0) < 3) && (3 < crmax(0,0)) )))||(sforbid(0,3)> 0)); ASSUME((!(( (cw(0,0) < 4) && (4 < crmax(0,0)) )))||(sforbid(0,4)> 0)); } else { if(pw(0,0) != co(0,cr(0,0))) { ASSUME(cr(0,0) >= old_cr); } pw(0,0) = co(0,cr(0,0)); r12 = mem(0,cr(0,0)); } ASSUME(creturn[0] >= cr(0,0)); // call void @llvm.dbg.value(metadata i64 %5, metadata !167, metadata !DIExpression()), !dbg !210 // %conv14 = trunc i64 %5 to i32, !dbg !118 // call void @llvm.dbg.value(metadata i32 %conv14, metadata !164, metadata !DIExpression()), !dbg !182 // %cmp15 = icmp eq i32 %conv14, 1, !dbg !119 creg__r12__1_ = max(0,creg_r12); // %conv16 = zext i1 %cmp15 to i32, !dbg !119 // call void @llvm.dbg.value(metadata i32 %conv16, metadata !168, metadata !DIExpression()), !dbg !182 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 1), metadata !170, metadata !DIExpression()), !dbg !214 // %6 = load atomic i64, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !121 // LD: Guess old_cr = cr(0,0+1*1); cr(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l71_c13 // Check ASSUME(active[cr(0,0+1*1)] == 0); ASSUME(cr(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cr(0,0+1*1) >= 0); ASSUME(cr(0,0+1*1) >= cdy[0]); ASSUME(cr(0,0+1*1) >= cisb[0]); ASSUME(cr(0,0+1*1) >= cdl[0]); ASSUME(cr(0,0+1*1) >= cl[0]); // Update creg_r13 = cr(0,0+1*1); crmax(0,0+1*1) = max(crmax(0,0+1*1),cr(0,0+1*1)); caddr[0] = max(caddr[0],0); if(cr(0,0+1*1) < cw(0,0+1*1)) { r13 = buff(0,0+1*1); ASSUME((!(( (cw(0,0+1*1) < 1) && (1 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,1)> 0)); ASSUME((!(( (cw(0,0+1*1) < 2) && (2 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,2)> 0)); ASSUME((!(( (cw(0,0+1*1) < 3) && (3 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,3)> 0)); ASSUME((!(( (cw(0,0+1*1) < 4) && (4 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,4)> 0)); } else { if(pw(0,0+1*1) != co(0+1*1,cr(0,0+1*1))) { ASSUME(cr(0,0+1*1) >= old_cr); } pw(0,0+1*1) = co(0+1*1,cr(0,0+1*1)); r13 = mem(0+1*1,cr(0,0+1*1)); } ASSUME(creturn[0] >= cr(0,0+1*1)); // call void @llvm.dbg.value(metadata i64 %6, metadata !172, metadata !DIExpression()), !dbg !214 // %conv20 = trunc i64 %6 to i32, !dbg !122 // call void @llvm.dbg.value(metadata i32 %conv20, metadata !169, metadata !DIExpression()), !dbg !182 // %cmp21 = icmp eq i32 %conv20, 1, !dbg !123 creg__r13__1_ = max(0,creg_r13); // %conv22 = zext i1 %cmp21 to i32, !dbg !123 // call void @llvm.dbg.value(metadata i32 %conv22, metadata !173, metadata !DIExpression()), !dbg !182 // %7 = load i32, i32* @atom_1_X0_1, align 4, !dbg !124, !tbaa !98 // LD: Guess old_cr = cr(0,4); cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l73_c13 // Check ASSUME(active[cr(0,4)] == 0); ASSUME(cr(0,4) >= iw(0,4)); ASSUME(cr(0,4) >= 0); ASSUME(cr(0,4) >= cdy[0]); ASSUME(cr(0,4) >= cisb[0]); ASSUME(cr(0,4) >= cdl[0]); ASSUME(cr(0,4) >= cl[0]); // Update creg_r14 = cr(0,4); crmax(0,4) = max(crmax(0,4),cr(0,4)); caddr[0] = max(caddr[0],0); if(cr(0,4) < cw(0,4)) { r14 = buff(0,4); ASSUME((!(( (cw(0,4) < 1) && (1 < crmax(0,4)) )))||(sforbid(4,1)> 0)); ASSUME((!(( (cw(0,4) < 2) && (2 < crmax(0,4)) )))||(sforbid(4,2)> 0)); ASSUME((!(( (cw(0,4) < 3) && (3 < crmax(0,4)) )))||(sforbid(4,3)> 0)); ASSUME((!(( (cw(0,4) < 4) && (4 < crmax(0,4)) )))||(sforbid(4,4)> 0)); } else { if(pw(0,4) != co(4,cr(0,4))) { ASSUME(cr(0,4) >= old_cr); } pw(0,4) = co(4,cr(0,4)); r14 = mem(4,cr(0,4)); } ASSUME(creturn[0] >= cr(0,4)); // call void @llvm.dbg.value(metadata i32 %7, metadata !174, metadata !DIExpression()), !dbg !182 // %8 = load i32, i32* @atom_1_X7_1, align 4, !dbg !125, !tbaa !98 // LD: Guess old_cr = cr(0,5); cr(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l74_c13 // Check ASSUME(active[cr(0,5)] == 0); ASSUME(cr(0,5) >= iw(0,5)); ASSUME(cr(0,5) >= 0); ASSUME(cr(0,5) >= cdy[0]); ASSUME(cr(0,5) >= cisb[0]); ASSUME(cr(0,5) >= cdl[0]); ASSUME(cr(0,5) >= cl[0]); // Update creg_r15 = cr(0,5); crmax(0,5) = max(crmax(0,5),cr(0,5)); caddr[0] = max(caddr[0],0); if(cr(0,5) < cw(0,5)) { r15 = buff(0,5); ASSUME((!(( (cw(0,5) < 1) && (1 < crmax(0,5)) )))||(sforbid(5,1)> 0)); ASSUME((!(( (cw(0,5) < 2) && (2 < crmax(0,5)) )))||(sforbid(5,2)> 0)); ASSUME((!(( (cw(0,5) < 3) && (3 < crmax(0,5)) )))||(sforbid(5,3)> 0)); ASSUME((!(( (cw(0,5) < 4) && (4 < crmax(0,5)) )))||(sforbid(5,4)> 0)); } else { if(pw(0,5) != co(5,cr(0,5))) { ASSUME(cr(0,5) >= old_cr); } pw(0,5) = co(5,cr(0,5)); r15 = mem(5,cr(0,5)); } ASSUME(creturn[0] >= cr(0,5)); // call void @llvm.dbg.value(metadata i32 %8, metadata !175, metadata !DIExpression()), !dbg !182 // %9 = load i32, i32* @atom_1_X9_0, align 4, !dbg !126, !tbaa !98 // LD: Guess old_cr = cr(0,6); cr(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l75_c13 // Check ASSUME(active[cr(0,6)] == 0); ASSUME(cr(0,6) >= iw(0,6)); ASSUME(cr(0,6) >= 0); ASSUME(cr(0,6) >= cdy[0]); ASSUME(cr(0,6) >= cisb[0]); ASSUME(cr(0,6) >= cdl[0]); ASSUME(cr(0,6) >= cl[0]); // Update creg_r16 = cr(0,6); crmax(0,6) = max(crmax(0,6),cr(0,6)); caddr[0] = max(caddr[0],0); if(cr(0,6) < cw(0,6)) { r16 = buff(0,6); ASSUME((!(( (cw(0,6) < 1) && (1 < crmax(0,6)) )))||(sforbid(6,1)> 0)); ASSUME((!(( (cw(0,6) < 2) && (2 < crmax(0,6)) )))||(sforbid(6,2)> 0)); ASSUME((!(( (cw(0,6) < 3) && (3 < crmax(0,6)) )))||(sforbid(6,3)> 0)); ASSUME((!(( (cw(0,6) < 4) && (4 < crmax(0,6)) )))||(sforbid(6,4)> 0)); } else { if(pw(0,6) != co(6,cr(0,6))) { ASSUME(cr(0,6) >= old_cr); } pw(0,6) = co(6,cr(0,6)); r16 = mem(6,cr(0,6)); } ASSUME(creturn[0] >= cr(0,6)); // call void @llvm.dbg.value(metadata i32 %9, metadata !176, metadata !DIExpression()), !dbg !182 // %and = and i32 %8, %9, !dbg !127 creg_r17 = max(creg_r15,creg_r16); r17 = r15 & r16; // call void @llvm.dbg.value(metadata i32 %and, metadata !177, metadata !DIExpression()), !dbg !182 // %and23 = and i32 %7, %and, !dbg !128 creg_r18 = max(creg_r14,creg_r17); r18 = r14 & r17; // call void @llvm.dbg.value(metadata i32 %and23, metadata !178, metadata !DIExpression()), !dbg !182 // %and24 = and i32 %conv22, %and23, !dbg !129 creg_r19 = max(creg__r13__1_,creg_r18); r19 = (r13==1) & r18; // call void @llvm.dbg.value(metadata i32 %and24, metadata !179, metadata !DIExpression()), !dbg !182 // %and25 = and i32 %conv16, %and24, !dbg !130 creg_r20 = max(creg__r12__1_,creg_r19); r20 = (r12==1) & r19; // call void @llvm.dbg.value(metadata i32 %and25, metadata !180, metadata !DIExpression()), !dbg !182 // %and26 = and i32 %conv10, %and25, !dbg !131 creg_r21 = max(creg__r11__1_,creg_r20); r21 = (r11==1) & r20; // call void @llvm.dbg.value(metadata i32 %and26, metadata !181, metadata !DIExpression()), !dbg !182 // %cmp27 = icmp eq i32 %and26, 1, !dbg !132 creg__r21__1_ = max(0,creg_r21); // br i1 %cmp27, label %if.then, label %if.end, !dbg !134 old_cctrl = cctrl[0]; cctrl[0] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[0] >= old_cctrl); ASSUME(cctrl[0] >= creg__r21__1_); if((r21==1)) { goto T0BLOCK1; } else { goto T0BLOCK2; } T0BLOCK1: // call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([117 x i8], [117 x i8]* @.str.1, i64 0, i64 0), i32 noundef 81, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !135 // unreachable, !dbg !135 r22 = 1; goto T0BLOCK_END; T0BLOCK2: // %10 = bitcast i64* %thr1 to i8*, !dbg !138 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %10) #7, !dbg !138 // %11 = bitcast i64* %thr0 to i8*, !dbg !138 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %11) #7, !dbg !138 // ret i32 0, !dbg !139 ret_thread_0 = 0; goto T0BLOCK_END; T0BLOCK_END: ASSUME(meminit(0,1) == mem(0,0)); ASSUME(coinit(0,1) == co(0,0)); ASSUME(deltainit(0,1) == delta(0,0)); ASSUME(meminit(0,2) == mem(0,1)); ASSUME(coinit(0,2) == co(0,1)); ASSUME(deltainit(0,2) == delta(0,1)); ASSUME(meminit(0,3) == mem(0,2)); ASSUME(coinit(0,3) == co(0,2)); ASSUME(deltainit(0,3) == delta(0,2)); ASSUME(meminit(0,4) == mem(0,3)); ASSUME(coinit(0,4) == co(0,3)); ASSUME(deltainit(0,4) == delta(0,3)); ASSUME(meminit(1,1) == mem(1,0)); ASSUME(coinit(1,1) == co(1,0)); ASSUME(deltainit(1,1) == delta(1,0)); ASSUME(meminit(1,2) == mem(1,1)); ASSUME(coinit(1,2) == co(1,1)); ASSUME(deltainit(1,2) == delta(1,1)); ASSUME(meminit(1,3) == mem(1,2)); ASSUME(coinit(1,3) == co(1,2)); ASSUME(deltainit(1,3) == delta(1,2)); ASSUME(meminit(1,4) == mem(1,3)); ASSUME(coinit(1,4) == co(1,3)); ASSUME(deltainit(1,4) == delta(1,3)); ASSUME(meminit(2,1) == mem(2,0)); ASSUME(coinit(2,1) == co(2,0)); ASSUME(deltainit(2,1) == delta(2,0)); ASSUME(meminit(2,2) == mem(2,1)); ASSUME(coinit(2,2) == co(2,1)); ASSUME(deltainit(2,2) == delta(2,1)); ASSUME(meminit(2,3) == mem(2,2)); ASSUME(coinit(2,3) == co(2,2)); ASSUME(deltainit(2,3) == delta(2,2)); ASSUME(meminit(2,4) == mem(2,3)); ASSUME(coinit(2,4) == co(2,3)); ASSUME(deltainit(2,4) == delta(2,3)); ASSUME(meminit(3,1) == mem(3,0)); ASSUME(coinit(3,1) == co(3,0)); ASSUME(deltainit(3,1) == delta(3,0)); ASSUME(meminit(3,2) == mem(3,1)); ASSUME(coinit(3,2) == co(3,1)); ASSUME(deltainit(3,2) == delta(3,1)); ASSUME(meminit(3,3) == mem(3,2)); ASSUME(coinit(3,3) == co(3,2)); ASSUME(deltainit(3,3) == delta(3,2)); ASSUME(meminit(3,4) == mem(3,3)); ASSUME(coinit(3,4) == co(3,3)); ASSUME(deltainit(3,4) == delta(3,3)); ASSUME(meminit(4,1) == mem(4,0)); ASSUME(coinit(4,1) == co(4,0)); ASSUME(deltainit(4,1) == delta(4,0)); ASSUME(meminit(4,2) == mem(4,1)); ASSUME(coinit(4,2) == co(4,1)); ASSUME(deltainit(4,2) == delta(4,1)); ASSUME(meminit(4,3) == mem(4,2)); ASSUME(coinit(4,3) == co(4,2)); ASSUME(deltainit(4,3) == delta(4,2)); ASSUME(meminit(4,4) == mem(4,3)); ASSUME(coinit(4,4) == co(4,3)); ASSUME(deltainit(4,4) == delta(4,3)); ASSUME(meminit(5,1) == mem(5,0)); ASSUME(coinit(5,1) == co(5,0)); ASSUME(deltainit(5,1) == delta(5,0)); ASSUME(meminit(5,2) == mem(5,1)); ASSUME(coinit(5,2) == co(5,1)); ASSUME(deltainit(5,2) == delta(5,1)); ASSUME(meminit(5,3) == mem(5,2)); ASSUME(coinit(5,3) == co(5,2)); ASSUME(deltainit(5,3) == delta(5,2)); ASSUME(meminit(5,4) == mem(5,3)); ASSUME(coinit(5,4) == co(5,3)); ASSUME(deltainit(5,4) == delta(5,3)); ASSUME(meminit(6,1) == mem(6,0)); ASSUME(coinit(6,1) == co(6,0)); ASSUME(deltainit(6,1) == delta(6,0)); ASSUME(meminit(6,2) == mem(6,1)); ASSUME(coinit(6,2) == co(6,1)); ASSUME(deltainit(6,2) == delta(6,1)); ASSUME(meminit(6,3) == mem(6,2)); ASSUME(coinit(6,3) == co(6,2)); ASSUME(deltainit(6,3) == delta(6,2)); ASSUME(meminit(6,4) == mem(6,3)); ASSUME(coinit(6,4) == co(6,3)); ASSUME(deltainit(6,4) == delta(6,3)); ASSERT(r22== 0); }
a702744bfaf35cfddb8b81487f43ba03a644bca4
af69c00861536cd23422093e612691a2147ea4be
/src/rcubeobject.cpp
906da7a680f59027fec43fabeedaaaf32d875d6c
[]
no_license
2lx/rubiks_cube
00a435cf91a7255ad6f2e0d80851c289fbb7a698
548041e94e55f1d48bcb5cb55f30fcfb36f4eb7c
refs/heads/master
2022-07-03T02:19:36.007310
2017-05-07T18:25:39
2017-05-07T18:25:39
51,666,478
1
0
null
null
null
null
UTF-8
C++
false
false
10,658
cpp
#include "all.h" #include "rcubeobject.h" #include "rcubeparams.h" #include "shaderprogram.h" #include "rcubemodel.h" #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> RCubeObject::RCubeObject( ShaderProgram * shaderPr ) { m_RCModel = new RC::CubeModel(); m_VBOCubeVertices = loadGLArrayBuffer( m_aCubeVertices, sizeof( m_aCubeVertices ) ); m_VBOTexCoords = loadGLArrayBuffer( m_aTexCoords, sizeof( m_aTexCoords ) ); m_VBOTexIndex = loadGLArrayBuffer( m_aTexIndex, sizeof( m_aTexIndex ), GL_STREAM_DRAW ); m_attrCubeVertices = shaderPr->addAttribute( "cVertex" ); m_attrTexCoords = shaderPr->addAttribute( "texCoord" ); m_attrTexIndex = shaderPr->addAttribute( "texIndex" ); // get texture params const char * texFileName = "glsl/texture.png"; SDL_Surface * res_texture = IMG_Load( texFileName ); if ( res_texture == NULL ) throw std::logic_error( "RCubeObject::RCubeObject(): Error loading image " + std::string( texFileName ) ); else { m_texCount = res_texture->h / ( res_texture->w / 6 ); m_texCurScheme = 1; SDL_FreeSurface( res_texture ); // load texture m_VBOTexUnionID = loadGLTexture2D( "glsl/texture.png" ); m_UniTexUnionID = shaderPr->addUniform( "texUnion" ); } m_UniMVP = shaderPr->addUniform( "mvp" ); m_UniTexCount = shaderPr->addUniform( "texCount" ); m_UniTexCurScheme = shaderPr->addUniform( "texCurScheme" ); } RCubeObject::~RCubeObject() { glDeleteBuffers( 1, &m_VBOCubeVertices ); glDeleteBuffers( 1, &m_VBOTexCoords ); glDeleteBuffers( 1, &m_VBOTexIndex ); glDeleteTextures( 1, &m_VBOTexUnionID ); delete m_RCModel; } void RCubeObject::setTurn( const RC::TT mt ) { // calculate new turn type const glm::vec3 vec = RC::TTPar::vec( mt ); bool cw = RC::TTPar::clockwise( mt ); int lay = RC::TTPar::layer( mt ); // TODO: only for 2x2x2 and 3x3x3 cubes if ( lay < 0 ) lay = 1; const glm::vec3 vecRot = vec * m_rotateQuat; if ( glm::dot( vecRot, glm::vec3( 1.0f, 1.0f, 1.0f ) ) < 0 ) { lay = RC::CUBIE_COUNT - 1 - lay; cw = !cw; } const RC::RA ax = RC::RAPar::closestRA( vecRot ); m_turnType = RC::TTPar::equalTT( ax, lay, cw ); if ( m_turnType == RC::TT::None ) return; // calculate turn params m_turnLayer = lay; m_turnMix = 0; float angle = glm::radians( 90.0f ); m_newTurnQuat = glm::angleAxis( ( cw ) ? -angle : angle, RC::TTPar::vec( m_turnType ) ); } RC::TT RCubeObject::setTurnByCoords( const glm::vec3 & pBeg, const glm::vec3 & pEnd ) { const float cOffset = RC::CUBIE_COUNT / 2.0f; // if 1st point don't lie on the surface of the cube if ( std::abs( pBeg.x ) > cOffset + 0.1 || std::abs( pBeg.y ) > cOffset + 0.1 || std::abs( pBeg.z ) > cOffset + 0.1 ) return RC::TT::None; // get close rotation axis const glm::vec3 rvBeg = pBeg * m_rotateQuat; const glm::vec3 rvEnd = pEnd * m_rotateQuat; glm::vec3 pRes = glm::cross( rvBeg, rvEnd ); // get closest rotation axis vector const RC::RA ra = RC::RAPar::closestRA( pRes ); if ( ra == RC::RA::None ) return RC::TT::None; const glm::vec3 vAx = RC::RAPar::vec( ra ); #ifdef NDEBUG std::cout << pBeg.x << " " << pBeg.y << " " << pBeg.z << std::endl; std::cout << pEnd.x << " " << pEnd.y << " " << pEnd.z << std::endl; std::cout << rvBeg.x << " " << rvBeg.y << " " << rvBeg.z << std::endl; std::cout << rvEnd.x << " " << rvEnd.y << " " << rvEnd.z << std::endl; std::cout << pRes.x << " " << pRes.y << " " << pRes.z << std::endl; std::cout << vAx.x << " " << vAx.y << " " << vAx.z << std::endl; #endif // NDEBUG // calculate clockwise bool cw; if ( glm::dot( glm::cross( vAx, rvEnd ), rvBeg ) > 0 ) cw = true; else cw = false; // find turn layer int lay = 0; if ( ra == RC::RA::X ) lay = floor( rvBeg.x + cOffset ); else if ( ra == RC::RA::Y ) lay = floor( rvBeg.y + cOffset ); else if ( ra == RC::RA::Z ) lay = floor( rvBeg.z + cOffset ); else lay = -1; if ( lay < 0 || lay > RC::CUBIE_COUNT - 1 ) return RC::TT::None; // get turn type (absolute) RC::TT nMT = RC::TTPar::equalTT( ra, lay, cw ); if ( nMT == RC::TT::None ) return RC::TT::None; m_turnType = nMT; m_turnLayer = lay; m_turnMix = 0; float angle = glm::radians( 90.0f ); m_newTurnQuat = glm::angleAxis( ( cw ) ? -angle : angle, vAx ); // get turn type (relative) const RC::RA ra2 = RC::RAPar::closestRA( glm::cross( pBeg, pEnd ) ); bool cw2; if ( glm::dot( glm::cross( RC::RAPar::vec( ra2 ), pEnd ), pBeg ) > 0 ) cw2 = true; else cw2 = false; int lay2 = 0; if ( ra2 == RC::RA::X ) lay2 = floor( pBeg.x + cOffset ); else if ( ra2 == RC::RA::Y ) lay2 = floor( pBeg.y + cOffset ); else if ( ra2 == RC::RA::Z ) lay2 = floor( pBeg.z + cOffset ); return RC::TTPar::equalTT( ra2, lay2, cw2 ); } void RCubeObject::reset() { m_RCModel->reset(); } void RCubeObject::update() { glUniform1f( m_UniTexCount, m_texCount ); glUniform1f( m_UniTexCurScheme, m_texCurScheme ); // turn the face of cube if ( isTurning() ) { if ( m_turnMix < 1.0 ) { m_turnQuat = glm::mix( m_turnQuat, m_newTurnQuat, m_turnMix ); m_turnMix += 0.08; } else { m_RCModel->turnSide( m_turnType, m_turnLayer ); m_turnType = RC::TT::None; m_turnLayer = -1; m_turnQuat = glm::quat(); m_turnMix = -1; } } } void RCubeObject::drawObject( const glm::mat4 & pmv ) { drawCube( pmv ); const glm::mat4 mMirrorX = { -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 5.0f, 0.0f, 0.0f, 1.0f }; drawCube( pmv * mMirrorX, RC::RA::X ); const glm::mat4 mMirrorY = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -5.0f, 0.0f, 1.0f }; drawCube( pmv * mMirrorY, RC::RA::Y ); const glm::mat4 mMirrorZ = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -5.0f, 1.0f }; drawCube( pmv * mMirrorZ, RC::RA::Z ); } void RCubeObject::drawCube( const glm::mat4 & pmv, const RC::RA ra ) { const float offCenter = RC::CUBIE_COUNT / 2.0f - 0.5; // use texture glActiveTexture( GL_TEXTURE0 ); glUniform1i( m_UniTexUnionID, 0 ); glBindTexture( GL_TEXTURE_2D, m_VBOTexUnionID ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); // calculate transformation matrix const glm::mat4 rotation = glm::mat4_cast( m_rotateQuat ); const glm::mat4 moving = glm::mat4_cast( m_turnQuat ); const glm::mat4 mvpR = pmv * rotation; for ( int x = 0; x < RC::CUBIE_COUNT; ++x ) for ( int y = 0; y < RC::CUBIE_COUNT; ++y ) for ( int z = 0; z < RC::CUBIE_COUNT; ++z ) // only draw cubies in the outer layer if ( x == 0 || x == RC::CUBIE_COUNT - 1 || y == 0 || y == RC::CUBIE_COUNT - 1 || z == 0 || z == RC::CUBIE_COUNT - 1 ) { // update texture index matrix for ( int i = 0; i < 4; i++ ) { m_aTexIndex[ 4 * ( int )RC::CF::Front + i ] = m_RCModel->cubie( x, y, z ).colInd( RC::CF::Front ); m_aTexIndex[ 4 * ( int )RC::CF::Up + i ] = m_RCModel->cubie( x, y, z ).colInd( RC::CF::Up ); m_aTexIndex[ 4 * ( int )RC::CF::Back + i ] = m_RCModel->cubie( x, y, z ).colInd( RC::CF::Back ); m_aTexIndex[ 4 * ( int )RC::CF::Down + i ] = m_RCModel->cubie( x, y, z ).colInd( RC::CF::Down ); m_aTexIndex[ 4 * ( int )RC::CF::Left + i ] = m_RCModel->cubie( x, y, z ).colInd( RC::CF::Left ); m_aTexIndex[ 4 * ( int )RC::CF::Right + i ] = m_RCModel->cubie( x, y, z ).colInd( RC::CF::Right ); } m_VBOTexIndex = loadGLArrayBuffer( m_aTexIndex, sizeof( m_aTexIndex ) ); // calculate offset of cubie glm::mat4 offset = glm::translate( glm::mat4( 1.0f ), glm::vec3( x - offCenter, y - offCenter, z - offCenter ) ); // calculate model view projection matrix glm::mat4 mRes = mvpR; glm::mat4 mTest = rotation; if ( m_turnType != RC::TT::None && m_turnLayer != -1 ) { const RC::RA ax = RC::TTPar::axis( m_turnType ); if ( ( x == m_turnLayer && ax == RC::RA::X ) || ( y == m_turnLayer && ax == RC::RA::Y ) || ( z == m_turnLayer && ax == RC::RA::Z ) ) { mRes = mRes * moving; mTest = mTest * moving; } } mRes = mRes * offset; mTest = mTest * offset; glm::vec4 vTest = mTest * glm::vec4( 0.0, 0.0, 0.0, 1.0f ); if ( ra == RC::RA::X && vTest.x < 0.7 ) continue; if ( ra == RC::RA::Y && vTest.y > -0.7 ) continue; if ( ra == RC::RA::Z && vTest.z > -0.7 ) continue; glUniformMatrix4fv( m_UniMVP, 1, GL_FALSE, glm::value_ptr( mRes ) ); drawCubie( x, y, z ); } } void RCubeObject::drawCubie( const int x, const int y, const int z ) const { glEnableVertexAttribArray( m_attrTexIndex ); glBindBuffer( GL_ARRAY_BUFFER, m_VBOTexIndex ); glVertexAttribPointer( m_attrTexIndex, 1, GL_INT, GL_FALSE, 0, 0 ); glEnableVertexAttribArray( m_attrCubeVertices ); glBindBuffer( GL_ARRAY_BUFFER, m_VBOCubeVertices ); glVertexAttribPointer( m_attrCubeVertices, 3, GL_FLOAT, GL_FALSE, 0, 0 ); glEnableVertexAttribArray( m_attrTexCoords ); glBindBuffer( GL_ARRAY_BUFFER, m_VBOTexCoords ); glVertexAttribPointer( m_attrTexCoords, 2, GL_FLOAT, GL_FALSE, 0, 0 ); glDrawArrays( GL_QUADS, 0, 4 * 6 ); glDisableVertexAttribArray( m_attrTexIndex ); glDisableVertexAttribArray( m_attrCubeVertices ); glDisableVertexAttribArray( m_attrTexCoords ); }
a967b4be97da0d74ddda0f0a6a38e2d3d916c7f8
fd7d1350eefac8a9bbd952568f074284663f2794
/dds/CorbaSeq/UShortSeqTypeSupportImpl.cpp
fdb761f91782535f1e02b4f3cb3c4d4e8dd29ab0
[ "MIT" ]
permissive
binary42/OCI
4ceb7c4ed2150b4edd0496b2a06d80f623a71a53
08191bfe4899f535ff99637d019734ed044f479d
refs/heads/master
2020-06-02T08:58:51.021571
2015-09-06T03:25:05
2015-09-06T03:25:05
41,980,019
1
0
null
null
null
null
UTF-8
C++
false
false
1,560
cpp
/* Generated by ../bin/opendds_idl version 3.6 (ACE version 6.2a_p7) running on input file CorbaSeq/UShortSeq.idl*/ #include "DCPS/DdsDcps_pch.h" #include "UShortSeqTypeSupportImpl.h" #include "dds/CorbaSeq/UShortSeqTypeSupportImpl.h" /* Begin MODULE: CORBA */ /* Begin TYPEDEF: UShortSeq */ namespace OpenDDS { namespace DCPS { void gen_find_size(const CORBA::UShortSeq& seq, size_t& size, size_t& padding) { ACE_UNUSED_ARG(seq); ACE_UNUSED_ARG(size); ACE_UNUSED_ARG(padding); find_size_ulong(size, padding); if (seq.length() == 0) { return; } size += seq.length() * gen_max_marshaled_size(CORBA::UShort()); } bool operator<<(Serializer& strm, const CORBA::UShortSeq& seq) { ACE_UNUSED_ARG(strm); ACE_UNUSED_ARG(seq); const CORBA::ULong length = seq.length(); if (!(strm << length)) { return false; } if (length == 0) { return true; } return strm.write_ushort_array(seq.get_buffer(), length); } bool operator>>(Serializer& strm, CORBA::UShortSeq& seq) { ACE_UNUSED_ARG(strm); ACE_UNUSED_ARG(seq); CORBA::ULong length; if (!(strm >> length)) { return false; } seq.length(length); if (length == 0) { return true; } return strm.read_ushort_array(seq.get_buffer(), length); } } } #ifndef OPENDDS_NO_CONTENT_SUBSCRIPTION_PROFILE namespace OpenDDS { namespace DCPS { void gen_skip_over(Serializer& ser, CORBA::UShortSeq*) { ACE_UNUSED_ARG(ser); ACE_CDR::ULong length; ser >> length; ser.skip(length, 2); } } } #endif /* End TYPEDEF: UShortSeq */ /* End MODULE: CORBA */