hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
0d3fd81a70b9507d87b289272bbf67cce4957638
3,272
cpp
C++
System Programming C/MultiThreadSortProject/Utils/SplitFunctions.cpp
Bzahov98/TU-University-Tasks
9d8e86e059e36356276b8e69579735b188b72634
[ "MIT" ]
3
2018-01-31T09:33:34.000Z
2022-01-19T13:04:19.000Z
System Programming C/MultiThreadSortProject/Utils/SplitFunctions.cpp
Bzahov98/TU-University-Tasks
9d8e86e059e36356276b8e69579735b188b72634
[ "MIT" ]
1
2020-10-03T07:43:53.000Z
2020-10-03T07:43:53.000Z
System Programming C/MultiThreadSortProject/Utils/SplitFunctions.cpp
Bzahov98/TU-University-Tasks
9d8e86e059e36356276b8e69579735b188b72634
[ "MIT" ]
3
2018-11-21T03:52:15.000Z
2020-09-30T18:07:28.000Z
// // Created by bzahov on 31.05.20 г.. // #include "SplitFunctions.h" void SplitUtils::splitToTokens(const string &inputString, int *data) { string basicString = inputString.substr(0, inputString.length()); string delimiter = ","; size_t pos = 0; string token; int i = 0; while ((pos = basicString.find(delimiter)) != string::npos) { token = basicString.substr(0, pos); data[i++] = std::stoi(token); //cout <<"[" <<token<<"|" << data[i-1]<<"]"<< std::endl; // for debug basicString.erase(0, pos + delimiter.length()); } // std::cout << ">" << basicString << std::endl; // for debug try { data[i] = std::stoi(basicString); } catch (exception ignored) {} // will not add not numeric data; cerr << endl << "FILE INPUT DATA" << endl; for (int j = 0; j <= i; ++j) { cerr << data[j] << ","; }cerr<<endl; }; vector<int> SplitUtils::splitToVector(string s, string delimiter) { size_t pos_start = 0, pos_end, delim_len = delimiter.length(); string token; vector<int> result; while ((pos_end = s.find(delimiter, pos_start)) != string::npos) { token = s.substr(pos_start, pos_end - pos_start); pos_start = pos_end + delim_len; int tokenIntValue; try { // string -> integer tokenIntValue = std::stoi(token); } catch (exception e) { continue; // dont add incorrect string(not numerable value) into vector } result.push_back(tokenIntValue); } try { int tokenIntValue; // string -> integer tokenIntValue = std::stoi(s.substr(pos_start)); result.push_back(tokenIntValue); } catch (exception e) { // dont add incorrect string(not numerable value) into vector } cout << "Result" << endl; for (int numb: result) { cout << numb << ","; } //quicksort<int>(result.begin(),result.end()); /*parallel_quick_sort(result); cout << "Result after sort" << endl; for (int numb: result) { cout << numb << ","; }*/ return result; } void SplitUtils::splitToList(string s, list<int> result) { string delimiter = ","; size_t pos_start = 0, pos_end, delim_len = delimiter.length(); string token; while ((pos_end = s.find(delimiter, pos_start)) != string::npos) { token = s.substr(pos_start, pos_end - pos_start); pos_start = pos_end + delim_len; int tokenIntValue; try { // string -> integer tokenIntValue = std::stoi(token); } catch (exception e) { continue; // dont add incorrect string(not numerable value) into vector } result.push_back(tokenIntValue); } try { int tokenIntValue; // string -> integer tokenIntValue = std::stoi(s.substr(pos_start)); result.push_back(tokenIntValue); } catch (exception e) { // dont add incorrect string(not numerable value) into vector } // cout << endl<< " Split to list Result" << endl; // for (int numb: result) { // cout << numb << ",|"; // } //quicksort<int>(result.begin(),result.end()); //parallel_quick_sort(result); // return result; };
29.745455
84
0.571822
[ "vector" ]
0d46fa152ef755d7cf7d724417a6490e6866be62
3,736
cpp
C++
implementations/OpenGL/framebuffer.cpp
rsayers/abstract-gpu
48176fcb88bde7d56de662c9e49d3d0e562819e1
[ "MIT" ]
41
2016-03-25T18:14:37.000Z
2022-01-20T11:16:52.000Z
implementations/OpenGL/framebuffer.cpp
rsayers/abstract-gpu
48176fcb88bde7d56de662c9e49d3d0e562819e1
[ "MIT" ]
4
2016-05-05T22:08:01.000Z
2021-12-10T13:06:55.000Z
implementations/OpenGL/framebuffer.cpp
rsayers/abstract-gpu
48176fcb88bde7d56de662c9e49d3d0e562819e1
[ "MIT" ]
9
2016-05-23T01:51:25.000Z
2021-08-21T15:32:37.000Z
#include "texture.hpp" #include "texture_view.hpp" #include "framebuffer.hpp" #include "../Common/texture_formats_common.hpp" #include <string.h> namespace AgpuGL { inline const char *framebufferStatusToString(GLenum status) { switch(status) { #define MAP_ENUM_NAME(x) case x: return #x; MAP_ENUM_NAME(GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT) MAP_ENUM_NAME(GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT) MAP_ENUM_NAME(GL_FRAMEBUFFER_UNSUPPORTED) #undef MAP_ENUM_NAME default: return "unknown;"; } } GLFramebuffer::GLFramebuffer() { changed = true; } GLFramebuffer::~GLFramebuffer() { deviceForGL->onMainContextBlocking([&] { deviceForGL->glDeleteFramebuffers(1, &handle); }); } agpu::framebuffer_ref GLFramebuffer::create(const agpu::device_ref &device, agpu_uint width, agpu_uint height, agpu_uint colorCount, agpu::texture_view_ref* colorViews, const agpu::texture_view_ref &depthStencilView) { if (!colorViews && colorCount > 0) return agpu::framebuffer_ref(); // Create the framebuffer object. GLuint handle; deviceForGL->onMainContextBlocking([&] { deviceForGL->glGenFramebuffers(1, &handle); }); auto result = agpu::makeObject<GLFramebuffer> (); auto framebuffer = result.as<GLFramebuffer> (); framebuffer->handle = handle; framebuffer->device = device; framebuffer->width = width; framebuffer->height = height; if(depthStencilView) { auto depthStencilFormat = depthStencilView.as<GLAbstractTextureView> ()->description.format; framebuffer->hasDepth = hasDepthComponent(depthStencilFormat); framebuffer->hasStencil = hasStencilComponent(depthStencilFormat); } else { framebuffer->hasDepth = false; framebuffer->hasStencil = false; } framebuffer->colorBufferViews.resize(colorCount); framebuffer->colorBufferTextures.resize(colorCount); for(size_t i = 0; i < colorCount; ++i) { auto &view = colorViews[i]; framebuffer->colorBufferViews[i] = view; framebuffer->colorBufferTextures[i] = agpu::texture_ref(view->getTexture()); } if(depthStencilView) { framebuffer->depthStencilView = depthStencilView; framebuffer->depthStencilTexture = agpu::texture_ref(depthStencilView->getTexture()); } return result; } agpu_uint GLFramebuffer::getWidth() { return width; } agpu_uint GLFramebuffer::getHeight() { return height; } void GLFramebuffer::bind(GLenum target) { deviceForGL->glBindFramebuffer(target, handle); if(changed) updateAttachments(target); } void GLFramebuffer::updateAttachments(GLenum target) { for(size_t i = 0; i < colorBufferViews.size(); ++i) attachTo(target, colorBufferViews[i], GL_COLOR_ATTACHMENT0 + i); if(hasDepth && hasStencil) attachTo(target, depthStencilView, GL_DEPTH_STENCIL_ATTACHMENT); else if(hasDepth) attachTo(target, depthStencilView, GL_DEPTH_ATTACHMENT); else if(hasStencil) attachTo(target, depthStencilView, GL_STENCIL_ATTACHMENT); auto status = deviceForGL->glCheckFramebufferStatus(target); if(status != GL_FRAMEBUFFER_COMPLETE) { printError("Warning: %s incomplete framebuffer color: %d hasDepth: %d hasStencil: %d\n", framebufferStatusToString(status), (int)colorBufferViews.size(), hasDepth, hasStencil); } changed = false; } void GLFramebuffer::attachTo(GLenum target, const agpu::texture_view_ref &view, GLenum attachmentPoint) { if(!view) return; auto glView = view.as<GLAbstractTextureView> (); //printf("texture width: %d height: %d\n", glTexture->description.width, glTexture->description.height); //printf("view->subresource_range.base_miplevel: %d\n", view->subresource_range.base_miplevel); glView->attachToFramebuffer(target, attachmentPoint); } } // End of namespace AgpuGL
28.090226
216
0.744379
[ "object" ]
0d4aa698a91fd449dab5851e83377dc59dbae39e
17,973
cc
C++
storage/src/android/metadata_android.cc
oliwilkinsonio/firebase-cpp-sdk
1a2790030e92f77ad2aaa87000a1222d12dcabfc
[ "Apache-2.0" ]
193
2019-03-18T16:30:43.000Z
2022-03-30T17:39:32.000Z
storage/src/android/metadata_android.cc
oliwilkinsonio/firebase-cpp-sdk
1a2790030e92f77ad2aaa87000a1222d12dcabfc
[ "Apache-2.0" ]
647
2019-03-18T20:50:41.000Z
2022-03-31T18:32:33.000Z
storage/src/android/metadata_android.cc
oliwilkinsonio/firebase-cpp-sdk
1a2790030e92f77ad2aaa87000a1222d12dcabfc
[ "Apache-2.0" ]
86
2019-04-21T09:40:38.000Z
2022-03-26T20:48:37.000Z
// Copyright 2016 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "storage/src/android/metadata_android.h" #include <jni.h> #include <stdlib.h> #include "app/src/include/firebase/app.h" #include "app/src/util_android.h" #include "storage/src/android/storage_android.h" #include "storage/src/android/storage_reference_android.h" #include "storage/storage_resources.h" namespace firebase { namespace storage { namespace internal { const int64_t kMillisToSeconds = 1000L; // Java methods declared in the header file. METHOD_LOOKUP_DEFINITION(storage_metadata, PROGUARD_KEEP_CLASS "com/google/firebase/storage/StorageMetadata", STORAGE_METADATA_METHODS) METHOD_LOOKUP_DEFINITION(storage_metadata_builder, PROGUARD_KEEP_CLASS "com/google/firebase/storage/StorageMetadata$Builder", STORAGE_METADATA_BUILDER_METHODS) MetadataInternal::MetadataInternal(StorageInternal* storage, jobject obj) : storage_(storage), custom_metadata_(nullptr) { cache_.resize(kCacheStringCount, nullptr); JNIEnv* env = GetJNIEnv(); if (obj == nullptr) { obj_ = nullptr; jobject builder = env->NewObject(storage_metadata_builder::GetClass(), storage_metadata_builder::GetMethodId( storage_metadata_builder::kConstructor)); CommitBuilder(builder); } else { obj_ = env->NewGlobalRef(obj); // Cache read-only all properties that are lost when constructing a // StorageMetadata object from a Builder. md5_hash(); size_bytes(); updated_time(); creation_time(); generation(); metadata_generation(); } } MetadataInternal::MetadataInternal(StorageInternal* storage) : MetadataInternal(storage, nullptr) {} // Free any assigned string pointers from the given vector, assigning them to // nullptr. static void FreeVectorOfStringPointers(std::vector<std::string*>* vector) { for (int i = 0; i < vector->size(); i++) { if ((*vector)[i] != nullptr) { delete (*vector)[i]; (*vector)[i] = nullptr; } } } // Copy any assigned string pointers from the given source vector. static std::vector<std::string*> CopyVectorOfStringPointers( const std::vector<std::string*>& src) { std::vector<std::string*> dest; dest.resize(src.size(), nullptr); for (int i = 0; i < src.size(); i++) { if (src[i]) dest[i] = new std::string(*src[i]); } return dest; } MetadataInternal::~MetadataInternal() { if (obj_ != nullptr) { JNIEnv* env = GetJNIEnv(); env->DeleteGlobalRef(obj_); obj_ = nullptr; } // Clear cached strings. FreeVectorOfStringPointers(&cache_); if (custom_metadata_ != nullptr) { delete custom_metadata_; } } JNIEnv* MetadataInternal::GetJNIEnv() { return storage_ ? storage_->app()->GetJNIEnv() : util::GetJNIEnvFromApp(); } // Creates a new copy of the map passed in (unless the map passed in is nullptr, // in which case this function will return nullptr). static std::map<std::string, std::string>* CreateMapCopy( const std::map<std::string, std::string>* src) { std::map<std::string, std::string>* dest = nullptr; if (src != nullptr) { dest = new std::map<std::string, std::string>; #if defined(_STLPORT_VERSION) for (auto i = src->begin(); i != src->end(); ++i) { dest->insert(*i); } #else *dest = *src; #endif // defined(_STLPORT_VERSION) } return dest; } MetadataInternal::MetadataInternal(const MetadataInternal& src) : storage_(src.storage_), obj_(nullptr), custom_metadata_(nullptr) { JNIEnv* env = GetJNIEnv(); CopyJavaMetadataObject(env, src.obj_); custom_metadata_ = CreateMapCopy(src.custom_metadata_); cache_ = CopyVectorOfStringPointers(src.cache_); constants_ = src.constants_; } MetadataInternal& MetadataInternal::operator=(const MetadataInternal& src) { storage_ = src.storage_; JNIEnv* env = GetJNIEnv(); if (obj_ != nullptr) { // If there's already a Java object in the dest, delete it. env->DeleteGlobalRef(obj_); obj_ = nullptr; } CopyJavaMetadataObject(env, src.obj_); if (custom_metadata_ != nullptr) { // If there's already a custom_metadata_ in the dest, delete it. delete custom_metadata_; custom_metadata_ = nullptr; } custom_metadata_ = CreateMapCopy(src.custom_metadata_); FreeVectorOfStringPointers(&cache_); cache_ = CopyVectorOfStringPointers(src.cache_); constants_ = src.constants_; return *this; } #if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) MetadataInternal::MetadataInternal(MetadataInternal&& src) : storage_(src.storage_) { obj_ = src.obj_; custom_metadata_ = std::move(src.custom_metadata_); src.custom_metadata_ = nullptr; src.obj_ = nullptr; // Move the cache to its new owner, so the const char*'s are still valid. cache_ = src.cache_; // Clear the source cache. src.cache_.clear(); src.cache_.resize(kCacheStringCount, nullptr); constants_ = src.constants_; } MetadataInternal& MetadataInternal::operator=(MetadataInternal&& src) { obj_ = src.obj_; src.obj_ = nullptr; if (custom_metadata_ != nullptr) { delete custom_metadata_; custom_metadata_ = nullptr; } custom_metadata_ = std::move(src.custom_metadata_); src.custom_metadata_ = nullptr; // Clean up old cached data the destination has. FreeVectorOfStringPointers(&cache_); // Move the cache to its new owner, us. cache_ = src.cache_; // Clear the source's cache. src.cache_.clear(); src.cache_.resize(kCacheStringCount, nullptr); constants_ = src.constants_; return *this; } #endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) void MetadataInternal::CopyJavaMetadataObject(JNIEnv* env, jobject src_obj) { // Use StorageMetadata.Builder to create a copy of the existing object. jobject builder = env->NewObject(storage_metadata_builder::GetClass(), storage_metadata_builder::GetMethodId( storage_metadata_builder::kConstructorFromMetadata), src_obj); CommitBuilder(builder); } bool MetadataInternal::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); return storage_metadata::CacheMethodIds(env, activity) && storage_metadata_builder::CacheMethodIds(env, activity); } void MetadataInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); storage_metadata_builder::ReleaseClass(env); storage_metadata::ReleaseClass(env); util::CheckAndClearJniExceptions(env); } const char* MetadataInternal::bucket() { return GetStringProperty(storage_metadata::kGetBucket, kCacheStringBucket); } void MetadataInternal::CommitBuilder(jobject builder) { JNIEnv* env = GetJNIEnv(); jobject new_metadata = env->CallObjectMethod( builder, storage_metadata_builder::GetMethodId(storage_metadata_builder::kBuild)); env->DeleteLocalRef(builder); if (obj_ != nullptr) env->DeleteGlobalRef(obj_); obj_ = env->NewGlobalRef(new_metadata); env->DeleteLocalRef(new_metadata); } void MetadataInternal::set_cache_control(const char* cache_control) { SetStringProperty(cache_control, storage_metadata_builder::kSetCacheControl, kCacheStringCacheControl); } const char* MetadataInternal::cache_control() { return GetStringProperty(storage_metadata::kGetCacheControl, kCacheStringCacheControl); } void MetadataInternal::set_content_disposition(const char* disposition) { SetStringProperty(disposition, storage_metadata_builder::kSetContentDisposition, kCacheStringContentDisposition); } const char* MetadataInternal::content_disposition() { return GetStringProperty(storage_metadata::kGetContentDisposition, kCacheStringContentDisposition); } void MetadataInternal::set_content_encoding(const char* encoding) { SetStringProperty(encoding, storage_metadata_builder::kSetContentEncoding, kCacheStringContentEncoding); } const char* MetadataInternal::content_encoding() { return GetStringProperty(storage_metadata::kGetContentEncoding, kCacheStringContentEncoding); } void MetadataInternal::set_content_language(const char* language) { SetStringProperty(language, storage_metadata_builder::kSetContentLanguage, kCacheStringContentLanguage); } const char* MetadataInternal::content_language() { return GetStringProperty(storage_metadata::kGetContentLanguage, kCacheStringContentLanguage); } void MetadataInternal::set_content_type(const char* type) { SetStringProperty(type, storage_metadata_builder::kSetContentType, kCacheStringContentType); } const char* MetadataInternal::content_type() { return GetStringProperty(storage_metadata::kGetContentType, kCacheStringContentType); } int64_t MetadataInternal::creation_time() { return GetInt64Property(storage_metadata::kGetCreationTimeMillis, &constants_.creation_time); } std::map<std::string, std::string>* MetadataInternal::custom_metadata() { if (custom_metadata_ == nullptr) { custom_metadata_ = new std::map<std::string, std::string>(); ReadCustomMetadata(custom_metadata_); } return custom_metadata_; } void MetadataInternal::CommitCustomMetadata() { std::map<std::string, std::string> old_metadata; ReadCustomMetadata(&old_metadata); // Set all new values, and if any old values are not present in new, then // clear them. JNIEnv* env = GetJNIEnv(); jobject builder = env->NewObject(storage_metadata_builder::GetClass(), storage_metadata_builder::GetMethodId( storage_metadata_builder::kConstructorFromMetadata), obj_); if (custom_metadata_ != nullptr) { for (auto i = custom_metadata_->begin(); i != custom_metadata_->end(); ++i) { old_metadata.erase( i->first); // Erase any key we see in the new metadata. // Any left over have been erased. jobject key_string = env->NewStringUTF(i->first.c_str()); jobject value_string = env->NewStringUTF(i->second.c_str()); jobject new_builder = env->CallObjectMethod( builder, storage_metadata_builder::GetMethodId( storage_metadata_builder::kSetCustomMetadata), key_string, value_string); env->DeleteLocalRef(value_string); env->DeleteLocalRef(key_string); env->DeleteLocalRef(builder); builder = new_builder; } } // If any keys are not present in the new data, override with blank values. jobject empty_string = env->NewStringUTF(""); for (auto i = old_metadata.begin(); i != old_metadata.end(); ++i) { jobject key_string = env->NewStringUTF(i->first.c_str()); jobject new_builder = env->CallObjectMethod(builder, storage_metadata_builder::GetMethodId( storage_metadata_builder::kSetCustomMetadata), key_string, empty_string); env->DeleteLocalRef(key_string); env->DeleteLocalRef(builder); builder = new_builder; } env->DeleteLocalRef(empty_string); CommitBuilder(builder); } void MetadataInternal::ReadCustomMetadata( std::map<std::string, std::string>* output_map) { JNIEnv* env = GetJNIEnv(); jobject key_set = env->CallObjectMethod( obj_, storage_metadata::GetMethodId(storage_metadata::kGetCustomMetadataKeys)); // Iterator iter = key_set.iterator(); jobject iter = env->CallObjectMethod( key_set, firebase::util::set::GetMethodId(firebase::util::set::kIterator)); // while (iter.hasNext()) while ( env->CallBooleanMethod(iter, firebase::util::iterator::GetMethodId( firebase::util::iterator::kHasNext))) { // String key = iter.next(); jobject key_object = env->CallObjectMethod( iter, firebase::util::iterator::GetMethodId(firebase::util::iterator::kNext)); // String value = obj_.GetCustomMetadata(key); jobject value_object = env->CallObjectMethod( obj_, storage_metadata::GetMethodId(storage_metadata::kGetCustomMetadata), key_object); std::string key = util::JniStringToString(env, key_object); std::string value = util::JniStringToString(env, value_object); output_map->insert(std::pair<std::string, std::string>(key, value)); } env->DeleteLocalRef(iter); env->DeleteLocalRef(key_set); } int64_t MetadataInternal::generation() { int64_t output = 0; const char* str = GetStringProperty(storage_metadata::kGetGeneration, kCacheStringGeneration); if (str) output = strtoll(str, nullptr, 0); // NOLINT return output; } int64_t MetadataInternal::metadata_generation() { int64_t output = 0; const char* str = GetStringProperty(storage_metadata::kGetMetadataGeneration, kCacheStringMetadataGeneration); if (str) output = strtoll(str, nullptr, 0); // NOLINT return output; } const char* MetadataInternal::name() { return GetStringProperty(storage_metadata::kGetName, kCacheStringName); } const char* MetadataInternal::path() { return GetStringProperty(storage_metadata::kGetPath, kCacheStringPath); } StorageReferenceInternal* MetadataInternal::GetReference() { // If we don't have an associated Storage, we are not assigned to a reference. if (storage_ == nullptr) return nullptr; JNIEnv* env = GetJNIEnv(); jobject ref_obj = env->CallObjectMethod( obj_, storage_metadata::GetMethodId(storage_metadata::kGetReference)); if (util::CheckAndClearJniExceptions(env)) { // Failed to get the StorageReference Java object, thus the StorageReference // C++ object we are creating is invalid. return nullptr; } StorageReferenceInternal* new_ref = new StorageReferenceInternal(storage_, ref_obj); env->DeleteLocalRef(ref_obj); return new_ref; } int64_t MetadataInternal::size_bytes() { return GetInt64Property(storage_metadata::kGetSizeBytes, &constants_.size_bytes); } int64_t MetadataInternal::updated_time() { return GetInt64Property(storage_metadata::kGetUpdatedTimeMillis, &constants_.updated_time); } // Get the MD5 hash of the blob referenced by StorageReference. const char* MetadataInternal::md5_hash() { return GetStringProperty(storage_metadata::kGetMd5Hash, kCacheStringMd5Hash); } const char* MetadataInternal::GetStringProperty( storage_metadata::Method string_method, CacheString cache_string) { std::string** cached_string = &cache_[cache_string]; if (*cached_string == nullptr) { JNIEnv* env = GetJNIEnv(); jobject str = env->CallObjectMethod( obj_, storage_metadata::GetMethodId(string_method)); if (util::CheckAndClearJniExceptions(env) || !str) { if (str) env->DeleteLocalRef(str); return nullptr; } *cached_string = new std::string(util::JniStringToString(env, str)); } return (*cached_string)->c_str(); } void MetadataInternal::SetStringProperty( const char* string_value, storage_metadata_builder::Method builder_method, CacheString cache_string) { std::string** cached_string = &cache_[cache_string]; if (*cached_string != nullptr) { delete *cached_string; *cached_string = nullptr; } JNIEnv* env = GetJNIEnv(); jobject base_builder = env->NewObject(storage_metadata_builder::GetClass(), storage_metadata_builder::GetMethodId( storage_metadata_builder::kConstructorFromMetadata), obj_); if (util::CheckAndClearJniExceptions(env)) return; jobject java_string = env->NewStringUTF(string_value); jobject updated_builder = env->CallObjectMethod( base_builder, storage_metadata_builder::GetMethodId(builder_method), java_string); bool commitBuilder = !util::CheckAndClearJniExceptions(env); env->DeleteLocalRef(base_builder); env->DeleteLocalRef(java_string); if (commitBuilder) { CommitBuilder(updated_builder); } else if (updated_builder) { env->DeleteLocalRef(updated_builder); } } const char* MetadataInternal::GetUriPropertyAsString( storage_metadata::Method uri_method, CacheString cache_string) { std::string** cached_string = &cache_[cache_string]; if (*cached_string == nullptr) { JNIEnv* env = GetJNIEnv(); jobject uri = env->CallObjectMethod(obj_, storage_metadata::GetMethodId(uri_method)); if (util::CheckAndClearJniExceptions(env) || !uri) { if (uri) env->DeleteLocalRef(uri); return nullptr; } *cached_string = new std::string(util::JniUriToString(env, uri)); } return (*cached_string)->c_str(); } int64_t MetadataInternal::GetInt64Property(storage_metadata::Method long_method, int64_t* cached_value) { if (!(*cached_value)) { JNIEnv* env = GetJNIEnv(); *cached_value = static_cast<int64_t>( env->CallLongMethod(obj_, storage_metadata::GetMethodId(long_method))); util::CheckAndClearJniExceptions(env); } return *cached_value; } } // namespace internal } // namespace storage } // namespace firebase
35.449704
80
0.696322
[ "object", "vector" ]
0d4c1994d142d177ca1b65c8652d0dbbe45540e3
415
cc
C++
16-Set-and-Map/cpp/09-Leetcode-Problems-about-Map-and-Set/Solution2.cc
OpenCreate/Play-with-DSA
49de3eb3e54815d1ff6520e5933e467c1f56bdfc
[ "MIT" ]
9
2020-08-10T03:43:54.000Z
2021-11-12T06:26:32.000Z
16-Set-and-Map/cpp/09-Leetcode-Problems-about-Map-and-Set/Solution2.cc
OpenCreate/Play-with-DSA
49de3eb3e54815d1ff6520e5933e467c1f56bdfc
[ "MIT" ]
null
null
null
16-Set-and-Map/cpp/09-Leetcode-Problems-about-Map-and-Set/Solution2.cc
OpenCreate/Play-with-DSA
49de3eb3e54815d1ff6520e5933e467c1f56bdfc
[ "MIT" ]
null
null
null
// https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/ class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { map<int, int> m; for (auto e : nums1) m[e]++; vector<int> res; for (auto e : nums2) { auto it = m.find(e); if (it != m.end()) { res.push_back(e); if (--m[e] == 0) m.erase(e); } } return res; } };
23.055556
66
0.53012
[ "vector" ]
0d4f2365a6a8d9a4e9736ce352e44f5b32a613e4
16,720
cpp
C++
components/contentselector/model/contentmodel.cpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
components/contentselector/model/contentmodel.cpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
components/contentselector/model/contentmodel.cpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
#include "contentmodel.hpp" #include "esmfile.hpp" #include <stdexcept> #include <QDir> #include <QTextCodec> #include <QDebug> #include "components/esm/esmreader.hpp" ContentSelectorModel::ContentModel::ContentModel(QObject *parent) : QAbstractTableModel(parent), mMimeType ("application/omwcontent"), mMimeTypes (QStringList() << mMimeType), mColumnCount (1), mDragDropFlags (Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled), mDropActions (Qt::CopyAction | Qt::MoveAction) { setEncoding ("win1252"); uncheckAll(); } void ContentSelectorModel::ContentModel::setEncoding(const QString &encoding) { mEncoding = encoding; if (encoding == QLatin1String("win1252")) mCodec = QTextCodec::codecForName("windows-1252"); else if (encoding == QLatin1String("win1251")) mCodec = QTextCodec::codecForName("windows-1251"); else if (encoding == QLatin1String("win1250")) mCodec = QTextCodec::codecForName("windows-1250"); else return; // This should never happen; } int ContentSelectorModel::ContentModel::columnCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return mColumnCount; } int ContentSelectorModel::ContentModel::rowCount(const QModelIndex &parent) const { if(parent.isValid()) return 0; return mFiles.size(); } const ContentSelectorModel::EsmFile *ContentSelectorModel::ContentModel::item(int row) const { if (row >= 0 && row < mFiles.size()) return mFiles.at(row); return 0; } ContentSelectorModel::EsmFile *ContentSelectorModel::ContentModel::item(int row) { if (row >= 0 && row < mFiles.count()) return mFiles.at(row); return 0; } const ContentSelectorModel::EsmFile *ContentSelectorModel::ContentModel::item(const QString &name) const { EsmFile::FileProperty fp = EsmFile::FileProperty_FileName; if (name.contains ('/')) fp = EsmFile::FileProperty_FilePath; foreach (const EsmFile *file, mFiles) { if (name.compare(file->fileProperty (fp).toString(), Qt::CaseInsensitive) == 0) return file; } return 0; } QModelIndex ContentSelectorModel::ContentModel::indexFromItem(const EsmFile *item) const { //workaround: non-const pointer cast for calls from outside contentmodel/contentselector EsmFile *non_const_file_ptr = const_cast<EsmFile *>(item); if (item) return index(mFiles.indexOf(non_const_file_ptr),0); return QModelIndex(); } Qt::ItemFlags ContentSelectorModel::ContentModel::flags(const QModelIndex &index) const { if (!index.isValid()) return Qt::NoItemFlags; const EsmFile *file = item(index.row()); if (!file) return Qt::NoItemFlags; //game files can always be checked if (file->isGameFile()) return Qt::ItemIsEnabled | Qt::ItemIsSelectable; Qt::ItemFlags returnFlags; bool allDependenciesFound = true; bool gamefileChecked = false; //addon can be checked if its gamefile is and all other dependencies exist foreach (const QString &fileName, file->gameFiles()) { bool depFound = false; foreach (EsmFile *dependency, mFiles) { //compare filenames only. Multiple instances //of the filename (with different paths) is not relevant here. depFound = (dependency->fileName().compare(fileName, Qt::CaseInsensitive) == 0); if (!depFound) continue; if (!gamefileChecked) { if (isChecked (dependency->filePath())) gamefileChecked = (dependency->isGameFile()); } // force it to iterate all files in cases where the current // dependency is a game file to ensure that a later duplicate // game file is / is not checked. // (i.e., break only if it's not a gamefile or the game file has been checked previously) if (gamefileChecked || !(dependency->isGameFile())) break; } allDependenciesFound = allDependenciesFound && depFound; } if (gamefileChecked) { if (allDependenciesFound) returnFlags = returnFlags | Qt::ItemIsEnabled | Qt::ItemIsSelectable | mDragDropFlags; else returnFlags = Qt::ItemIsSelectable; } return returnFlags; } QVariant ContentSelectorModel::ContentModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (index.row() >= mFiles.size()) return QVariant(); const EsmFile *file = item(index.row()); if (!file) return QVariant(); const int column = index.column(); switch (role) { case Qt::EditRole: case Qt::DisplayRole: { if (column >=0 && column <=EsmFile::FileProperty_GameFile) return file->fileProperty(static_cast<const EsmFile::FileProperty>(column)); return QVariant(); break; } case Qt::TextAlignmentRole: { switch (column) { case 0: case 1: return Qt::AlignLeft + Qt::AlignVCenter; case 2: case 3: return Qt::AlignRight + Qt::AlignVCenter; default: return Qt::AlignLeft + Qt::AlignVCenter; } return QVariant(); break; } case Qt::ToolTipRole: { if (column != 0) return QVariant(); return file->toolTip(); break; } case Qt::CheckStateRole: { if (file->isGameFile()) return QVariant(); return mCheckStates[file->filePath()]; break; } case Qt::UserRole: { if (file->isGameFile()) return ContentType_GameFile; else if (flags(index)) return ContentType_Addon; break; } case Qt::UserRole + 1: return isChecked(file->filePath()); break; } return QVariant(); } bool ContentSelectorModel::ContentModel::setData(const QModelIndex &index, const QVariant &value, int role) { if(!index.isValid()) return false; EsmFile *file = item(index.row()); QString fileName = file->fileName(); bool success = false; switch(role) { case Qt::EditRole: { QStringList list = value.toStringList(); for (int i = 0; i < EsmFile::FileProperty_GameFile; i++) file->setFileProperty(static_cast<EsmFile::FileProperty>(i), list.at(i)); for (int i = EsmFile::FileProperty_GameFile; i < list.size(); i++) file->setFileProperty (EsmFile::FileProperty_GameFile, list.at(i)); emit dataChanged(index, index); success = true; } break; case Qt::UserRole+1: { success = (flags (index) & Qt::ItemIsEnabled); if (success) { success = setCheckState(file->filePath(), value.toBool()); emit dataChanged(index, index); } } break; case Qt::CheckStateRole: { int checkValue = value.toInt(); bool setState = false; if ((checkValue==Qt::Checked) && !isChecked(file->filePath())) { setState = true; success = true; } else if ((checkValue == Qt::Checked) && isChecked (file->filePath())) setState = true; else if (checkValue == Qt::Unchecked) setState = true; if (setState) { setCheckState(file->filePath(), success); emit dataChanged(index, index); } else return success; foreach (EsmFile *file, mFiles) { if (file->gameFiles().contains(fileName, Qt::CaseInsensitive)) { QModelIndex idx = indexFromItem(file); emit dataChanged(idx, idx); } } success = true; } break; } return success; } bool ContentSelectorModel::ContentModel::insertRows(int position, int rows, const QModelIndex &parent) { if (parent.isValid()) return false; beginInsertRows(parent, position, position+rows-1); { for (int row = 0; row < rows; ++row) mFiles.insert(position, new EsmFile); } endInsertRows(); return true; } bool ContentSelectorModel::ContentModel::removeRows(int position, int rows, const QModelIndex &parent) { if (parent.isValid()) return false; beginRemoveRows(parent, position, position+rows-1); { for (int row = 0; row < rows; ++row) delete mFiles.takeAt(position); } endRemoveRows(); return true; } Qt::DropActions ContentSelectorModel::ContentModel::supportedDropActions() const { return mDropActions; } QStringList ContentSelectorModel::ContentModel::mimeTypes() const { return mMimeTypes; } QMimeData *ContentSelectorModel::ContentModel::mimeData(const QModelIndexList &indexes) const { QByteArray encodedData; foreach (const QModelIndex &index, indexes) { if (!index.isValid()) continue; encodedData.append(item(index.row())->encodedData()); } QMimeData *mimeData = new QMimeData(); mimeData->setData(mMimeType, encodedData); return mimeData; } bool ContentSelectorModel::ContentModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) { if (action == Qt::IgnoreAction) return true; if (column > 0) return false; if (!data->hasFormat(mMimeType)) return false; int beginRow = rowCount(); if (row != -1) beginRow = row; else if (parent.isValid()) beginRow = parent.row(); QByteArray encodedData = data->data(mMimeType); QDataStream stream(&encodedData, QIODevice::ReadOnly); while (!stream.atEnd()) { QString value; QStringList values; QStringList gamefiles; for (int i = 0; i < EsmFile::FileProperty_GameFile; ++i) { stream >> value; values << value; } stream >> gamefiles; insertRows(beginRow, 1); QModelIndex idx = index(beginRow++, 0, QModelIndex()); setData(idx, QStringList() << values << gamefiles, Qt::EditRole); } return true; } void ContentSelectorModel::ContentModel::addFile(EsmFile *file) { beginInsertRows(QModelIndex(), mFiles.count(), mFiles.count()); mFiles.append(file); endInsertRows(); QModelIndex idx = index (mFiles.size() - 2, 0, QModelIndex()); emit dataChanged (idx, idx); } void ContentSelectorModel::ContentModel::addFiles(const QString &path) { QDir dir(path); QStringList filters; filters << "*.esp" << "*.esm" << "*.omwgame" << "*.omwaddon"; dir.setNameFilters(filters); QTextCodec *codec = QTextCodec::codecForName("UTF8"); // Create a decoder for non-latin characters in esx metadata QTextDecoder *decoder = codec->makeDecoder(); foreach (const QString &path, dir.entryList()) { QFileInfo info(dir.absoluteFilePath(path)); EsmFile *file = new EsmFile(path); try { ESM::ESMReader fileReader; ToUTF8::Utf8Encoder encoder = ToUTF8::calculateEncoding(mEncoding.toStdString()); fileReader.setEncoder(&encoder); fileReader.open(dir.absoluteFilePath(path).toStdString()); foreach (const ESM::Header::MasterData &item, fileReader.getGameFiles()) file->addGameFile(QString::fromStdString(item.name)); file->setAuthor (decoder->toUnicode(fileReader.getAuthor().c_str())); file->setDate (info.lastModified()); file->setFormat (fileReader.getFormat()); file->setFilePath (info.absoluteFilePath()); file->setDescription(decoder->toUnicode(fileReader.getDesc().c_str())); // Put the file in the table if (item(file->filePath()) == 0) addFile(file); } catch(std::runtime_error &e) { // An error occurred while reading the .esp qWarning() << "Error reading addon file: " << e.what(); continue; } } delete decoder; sortFiles(); } void ContentSelectorModel::ContentModel::sortFiles() { //first, sort the model such that all dependencies are ordered upstream (gamefile) first. bool movedFiles = true; int fileCount = mFiles.size(); //Dependency sort //iterate until no sorting of files occurs while (movedFiles) { movedFiles = false; //iterate each file, obtaining a reference to it's gamefiles list for (int i = 0; i < fileCount; i++) { QModelIndex idx1 = index (i, 0, QModelIndex()); const QStringList &gamefiles = mFiles.at(i)->gameFiles(); //iterate each file after the current file, verifying that none of it's //dependencies appear. for (int j = i + 1; j < fileCount; j++) { if (gamefiles.contains(mFiles.at(j)->fileName(), Qt::CaseInsensitive)) { mFiles.move(j, i); QModelIndex idx2 = index (j, 0, QModelIndex()); emit dataChanged (idx1, idx2); movedFiles = true; } } if (movedFiles) break; } } } bool ContentSelectorModel::ContentModel::isChecked(const QString& filepath) const { if (mCheckStates.contains(filepath)) return (mCheckStates[filepath] == Qt::Checked); return false; } bool ContentSelectorModel::ContentModel::isEnabled (QModelIndex index) const { return (flags(index) & Qt::ItemIsEnabled); } void ContentSelectorModel::ContentModel::setCheckStates (const QStringList &fileList, bool isChecked) { foreach (const QString &file, fileList) { setCheckState (file, isChecked); } } void ContentSelectorModel::ContentModel::refreshModel() { emit dataChanged (index(0,0), index(rowCount()-1,0)); } bool ContentSelectorModel::ContentModel::setCheckState(const QString &filepath, bool checkState) { if (filepath.isEmpty()) return false; const EsmFile *file = item(filepath); if (!file) return false; Qt::CheckState state = Qt::Unchecked; if (checkState) state = Qt::Checked; mCheckStates[filepath] = state; emit dataChanged(indexFromItem(item(filepath)), indexFromItem(item(filepath))); if (file->isGameFile()) refreshModel(); //if we're checking an item, ensure all "upstream" files (dependencies) are checked as well. if (state == Qt::Checked) { foreach (QString upstreamName, file->gameFiles()) { const EsmFile *upstreamFile = item(upstreamName); if (!upstreamFile) continue; if (!isChecked(upstreamFile->filePath())) mCheckStates[upstreamFile->filePath()] = Qt::Checked; emit dataChanged(indexFromItem(upstreamFile), indexFromItem(upstreamFile)); } } //otherwise, if we're unchecking an item (or the file is a game file) ensure all downstream files are unchecked. if (state == Qt::Unchecked) { foreach (const EsmFile *downstreamFile, mFiles) { QFileInfo fileInfo(filepath); QString filename = fileInfo.fileName(); if (downstreamFile->gameFiles().contains(filename, Qt::CaseInsensitive)) { if (mCheckStates.contains(downstreamFile->filePath())) mCheckStates[downstreamFile->filePath()] = Qt::Unchecked; emit dataChanged(indexFromItem(downstreamFile), indexFromItem(downstreamFile)); } } } return true; } ContentSelectorModel::ContentFileList ContentSelectorModel::ContentModel::checkedItems() const { ContentFileList list; // TODO: // First search for game files and next addons, // so we get more or less correct game files vs addons order. foreach (EsmFile *file, mFiles) if (isChecked(file->filePath())) list << file; return list; } void ContentSelectorModel::ContentModel::uncheckAll() { emit layoutAboutToBeChanged(); mCheckStates.clear(); emit layoutChanged(); }
26.752
147
0.599581
[ "model" ]
0d4fbda15ce7a07e09f5e3e3901e8e870d9824bd
987
cpp
C++
algorithms/Permutations/permutations.cpp
PikachuPikachuHAHA/leetcode-2
4cf8d30509f4b994b1845765807380eeffb95c73
[ "MIT" ]
93
2016-04-27T23:25:27.000Z
2021-07-13T20:32:25.000Z
algorithms/Permutations/permutations.cpp
shangan/leetcode
db05338f8057ad440cb5dd6cfe0151aafb7a8d56
[ "MIT" ]
null
null
null
algorithms/Permutations/permutations.cpp
shangan/leetcode
db05338f8057ad440cb5dd6cfe0151aafb7a8d56
[ "MIT" ]
43
2016-05-31T15:46:50.000Z
2021-04-09T04:07:39.000Z
#include <vector> #include <algorithm> #include <cstdio> #include <cstdlib> using namespace std; void print(vector<int> v) { for (auto i : v) printf("%d ", i); printf("\n"); } class Solution { public: vector<vector<int> > permute(vector<int> &num) { vector<vector<int>> ans; sort(num.begin(), num.end()); do { vector<int> v(num.begin(), num.end()); ans.push_back(v); } while(next(num)); return ans; } private: bool next(vector<int> &v) { size_t n = v.size(); int i; for (i = n - 2; i >= 0 && v[i] >= v[i + 1]; --i); if (i < 0) { reverse(v.begin(), v.end()); return false; } int j; for (j = n - 1; j > i && v[j] <= v[i]; --j); swap(v[i], v[j]); reverse(v.begin() + i + 1, v.end()); return true; } }; int main(int argc, char **argv) { Solution solution; vector<int> num = {1,2,3, 4, 5}; vector<vector<int>> ans = solution.permute(num); for (auto i : ans) print(i); return 0; }
20.142857
54
0.527862
[ "vector" ]
0d50b5158585d96ed239c741055a32474736d8ac
9,561
hpp
C++
Extensions/Editor/Editor.hpp
RachelWilSingh/ZeroCore
e9a2f82d395e5c89fb98eceac44ce60d016dbff3
[ "MIT" ]
52
2018-09-11T17:18:35.000Z
2022-03-13T15:28:21.000Z
Extensions/Editor/Editor.hpp
RachelWilSingh/ZeroCore
e9a2f82d395e5c89fb98eceac44ce60d016dbff3
[ "MIT" ]
1,409
2018-09-19T18:03:43.000Z
2021-06-09T08:33:33.000Z
Extensions/Editor/Editor.hpp
RachelWilSingh/ZeroCore
e9a2f82d395e5c89fb98eceac44ce60d016dbff3
[ "MIT" ]
26
2018-09-11T17:16:32.000Z
2021-11-22T06:21:19.000Z
/////////////////////////////////////////////////////////////////////////////// /// /// \file Editor.hpp /// Declaration of the Editor classes. /// /// Authors: Chris Peters /// Copyright 2010-2013, DigiPen Institute of Technology /// /////////////////////////////////////////////////////////////////////////////// #pragma once namespace Zero { //--------------------------------------------------------- Forward Declarations class ConsoleUi; class LoadingWindow; class ToolControl; class LibraryView; class ContentLibrary; class RuntimeEditorImpl; class PropertyView; class Level; class StressTestDialog; class ObjectView; class CommandManager; class UpdateEvent; class CommandCaptureContextEvent; class DocumentEditor; class BugReporter; class MainPropertyView; class SavingEvent; class MainWindow; class Editor; class MessageBoxEvent; class ZilchCompiledEvent; class CogCommandManager; class EventDirectoryWatcher; class FileEditEvent; class CodeTranslatorListener; class WebBrowserWidget; class CameraViewport; class EditorViewport; class FindTextDialog; //------------------------------------------------------------------------------ namespace Events { DeclareEvent(EditorChangeSpace); DeclareEvent(UnloadProject); DeclareEvent(LoadedProject); }//namespace Events //----------------------------------------------------------------- Editor Event class EditorEvent : public Event { public: ZilchDeclareType(TypeCopyMode::ReferenceType); EditorEvent(Editor* editor); Editor* mEditor; }; //----------------------------------------------------------------------- Editor DeclareEnum2(EditorMode, Mode2D, Mode3D); DeclareEnum2(PlayGameOptions, SingleInstance, MultipleInstances); /// Main editor Object. class Editor : public MultiDock { public: // Meta Initialization ZilchDeclareType(TypeCopyMode::ReferenceType); Editor(Composite* parent); ~Editor(); /// Space that is being edited Space* GetEditSpace(); /// Invoked by EditorViewport when it becomes active void SetEditSpace(Space* space); /// Sets the active space for the main EditorViewport void SetEditorViewportSpace(Space* space); /// Focus on the passed in space void SetFocus(Space* space); /// Current level being edited on the edit space Level* GetEditLevel(); /// Get starting level for game. Level* GetStartingLevel(); Widget* ShowConsole(); Widget* HideConsole(); Widget* ToggleConsole(); Widget* ShowBrowser(); Widget* ShowBrowser(StringParam url, StringParam tabName); Widget* ShowMarket(); Widget* ShowChat(); /// Selects a tool with the given name. void SelectTool(StringParam toolName); /// Sets the edit mode for the current levels editor camera controller void SetEditMode(EditorMode::Enum mode); /// Gets the edit mode for the current levels editor camera controller EditorMode::Enum GetEditMode(); void OnProjectFileModified(FileEditEvent* e); OsWindow* mOsWindow; MainWindow* mMainWindow; Widget* ShowWindow(StringParam name); Widget* HideWindow(StringParam name); Window* AddManagedWidget(Widget* widget, DockArea::Enum dockArea, bool visible = true); void CreateDockableWindow(StringParam windowName, CameraViewport* cameraViewport, Vec2Param initialSize, bool destroySpaceOnClose, DockArea::Enum dockMode = DockArea::Floating); //User Configuration object. Cog* mConfig; // Current loaded Project object. HandleOf<Cog> mProject; EventDirectoryWatcher* mProjectDirectoryWatcher; /// Get the project of current game. Cog* GetProjectCog(); /// Simple helper to get the path of the current project. Returns an empty string if no project is loaded. String GetProjectPath(); /// Current game session being edited HandleOf<GameSession> mEditGame; HandleOf<Space> mActiveSpace; HandleOf<Level> mEditLevel; HandleOf<EditorViewport> mEditorViewport; Array<EditorViewport*> mEditInGameViewports; /// Current Project Primary content library. ContentLibrary* mProjectLibrary; /// Editor Tools ToolControl* Tools; PropertyView* GetPropertyView(); MainPropertyView* mMainPropertyView; //Core Editor Widgets LibraryView* mLibrary; ConsoleUi* mConsole; LoadingWindow* mLoading; ObjectView* mObjectView; //Commands CommandManager* mCommands; CogCommandManager* mCogCommands; //Bugs BugReporter* mBugReporter; //Find FindTextDialog* mFindTextDialog; //Stress Tests StressTestDialog* mStressTestDialog; //Desync Window* mDesyncWindow; // For re-parenting on copy and paste CogId mLastCopiedParent; String mLastCopy; CogId mLastSpaceCopiedFrom; // For now, we're only storing the first copied objects // location in the hierarchy. The reason for this is I'm not exactly sure // what would be best when copying multiple objects. uint mPasteHierarchyIndex; // This should ideally be a component on the editor CodeTranslatorListener* mCodeTranslatorListener; //------------------------------------------------------------ Selection HandleOf<MetaSelection> mSelection; MetaSelection* GetSelection(); void OnSelectionFinal(SelectionChangedEvent* event); //------------------------------------------------------------ Edit // Edit a Resource Object void EditResource(Resource* resource); // Add a new resource void AddResource(); // Add a new resource type of given type void AddResourceType(BoundType* resourceType, ContentLibrary* library = nullptr, StringParam resourceName = ""); // Open a text file if it is a resource it will open as that resource virtual DocumentEditor* OpenTextFileAuto(StringParam file) = 0; // Open a string in the text editor for debugging data dumps etc virtual DocumentEditor* OpenTextString(StringParam name, StringParam text, StringParam extension = String()) = 0; // Open a text file for text editing virtual DocumentEditor* OpenTextFile(StringParam filename) = 0; // Open a document resource for text editing virtual DocumentEditor* OpenDocumentResource(DocumentResource* docResource) = 0; //Undo last change. void Undo(); //Redo last undo. void Redo(); //Save all objects. Status SaveAll(bool showNotify); bool TakeProjectScreenshot(); /// The main operation queue used by the editor. OperationQueue* GetOperationQueue() { return mQueue; } HandleOf<OperationQueue> mQueue; /// To re-initialize script objects, we need to remove all live script that /// run in editor, then re-add them after the scripts have been compiled. void OnScriptsCompiledPrePatch(ZilchCompileEvent* e); void OnScriptsCompiledPatch(ZilchCompileEvent* e); /// Removes all live zilch objects on all game sessions. It will add all /// removal operations to the mReInitializeQueue so they can all be /// re-added at a later point. void TearDownZilchStateOnGames(HashSet<ResourceLibrary*>& modifiedLibraries); /// The easiest way to re-initialize all script components is to use /// operations to remove, then undo to re-add them. OperationQueue mReInitializeQueue; /// Re-initializing the scripts will cause the space to be modified, so we /// need to store the modified state of all spaces to restore it properly. /// Otherwise, modifying a script would always mark a space as modified. HashMap<Space*, bool> mSpaceModifiedStates; //Internals void OnSaveCheck(SavingEvent* event); RuntimeEditorImpl* mRuntimeEditorImpl; /// This function is marked for removal from Zero.Editor, use Zero.Editor.Selection's functionality instead. void SelectPrimary(HandleParam object); virtual void OnEngineUpdate(UpdateEvent* event); void OnResourcesUnloaded(ResourceEvent* event); void OnMouseFileDrop(MouseFileDropEvent* event); void Update(); void ExecuteCommand(StringParam commandName); Composite* OpenSearchWindow(Widget* returnFocus, bool noBorder = false); Space* CreateNewSpace(uint flags); void OnCaptureContext(CommandCaptureContextEvent* event); typedef Array<HandleOf<GameSession> > GameArray; typedef GameArray::range GameRange; void DisplayGameSession(StringParam name, GameSession* gameSession); GameSession* PlayGame(PlayGameOptions::Enum options, bool takeFocus = true, bool startGame = true); GameSession* PlaySingleGame(); GameSession* PlayNewGame(); void ZoomOnGame(GameSession* gameSession); void EditGameSpaces(); void DestroyGames(); void PauseGame(); void ToggleGamePaused(); void SetGamePaused(bool state); void StopGame(); void StepGame(); bool AreGamesRunning(); GameRange GetGames(); void ClearInvalidGames(); void SelectGame(); void SelectSpace(); GameSession* GetEditGameSession(); GameSession* CreateDefaultGameSession(); GameSession* EditorCreateGameSession(uint flags); void SetMainPropertyViewObject(Object* object); void LoadDefaultLevel(); void ProjectLoaded(); bool RequestQuit(bool isRestart); void OnSaveQuitMessageBox(MessageBoxEvent* event); void OnSaveRestartMessageBox(MessageBoxEvent* event); GameArray mGames; bool mGamePending; bool mStopGame; Array<CogId> mSelectionGizmos; UniquePointer<EventObject> mSimpleDebuggerListener; }; namespace Z { extern Editor* gEditor; }//namespace Z }//namespace Zero
31.87
116
0.691455
[ "object" ]
0d56c1c2979b262cb5ecdf5f340d9b1cad6dfbb2
1,091
hpp
C++
include/rua/funchain.hpp
yulon/tmd
70fe8ea46fd14f77c7213c7ef4a3dd3925168fd0
[ "MIT" ]
null
null
null
include/rua/funchain.hpp
yulon/tmd
70fe8ea46fd14f77c7213c7ef4a3dd3925168fd0
[ "MIT" ]
null
null
null
include/rua/funchain.hpp
yulon/tmd
70fe8ea46fd14f77c7213c7ef4a3dd3925168fd0
[ "MIT" ]
null
null
null
#ifndef _RUA_FUNCHAIN_HPP #define _RUA_FUNCHAIN_HPP #include "util.hpp" #include <functional> #include <vector> namespace rua { template <typename Ret, typename... Args> class _funchain_base : public std::vector<std::function<Ret(Args...)>> { public: _funchain_base() = default; }; template <typename Callback, typename = void> class funchain; template <typename Ret, typename... Args> class funchain< Ret(Args...), enable_if_t<!std::is_convertible<Ret, bool>::value>> : public _funchain_base<Ret, Args...> { public: funchain() = default; void operator()(Args &&...args) const { for (auto &cb : *this) { cb(std::forward<Args>(args)...); } } }; template <typename Ret, typename... Args> class funchain<Ret(Args...), enable_if_t<std::is_convertible<Ret, bool>::value>> : public _funchain_base<Ret, Args...> { public: funchain() = default; Ret operator()(Args &&...args) const { for (auto &cb : *this) { auto &&r = cb(std::forward<Args>(args)...); if (static_cast<bool>(r)) { return std::move(r); } } return Ret(); } }; } // namespace rua #endif
19.836364
80
0.657195
[ "vector" ]
0d5e76d85c6d2460622409957264b93fbccf1d08
24,960
cpp
C++
circe/gl/texture/texture.cpp
gui-works/circe
c126a8f9521dca1eb23ac47c8f2e8081f2102f17
[ "MIT" ]
1
2021-09-17T18:12:47.000Z
2021-09-17T18:12:47.000Z
circe/gl/texture/texture.cpp
gui-works/circe
c126a8f9521dca1eb23ac47c8f2e8081f2102f17
[ "MIT" ]
null
null
null
circe/gl/texture/texture.cpp
gui-works/circe
c126a8f9521dca1eb23ac47c8f2e8081f2102f17
[ "MIT" ]
2
2021-09-17T18:13:02.000Z
2021-09-17T18:16:21.000Z
/* * Copyright (c) 2017 FilipeCN * * The MIT License (MIT) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #include <circe/gl/texture/texture.h> #include <circe/gl/utils/open_gl.h> #include <circe/gl/io/framebuffer.h> #include <circe/gl/scene/scene_model.h> #include <circe/gl/graphics/shader.h> #include <circe/scene/shapes.h> #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> namespace circe::gl { Texture unfoldCubemap(const Texture &cubemap, texture_options output_options) { bool output_is_equirectangular = circe::testMaskBit(output_options, circe::texture_options::equirectangular); Texture output; output.setTarget(GL_TEXTURE_2D); output.setInternalFormat(cubemap.internalFormat()); output.setFormat(cubemap.format()); output.setType(cubemap.type()); SceneModel quad; quad = Shapes::box({{-1, -1}, {1, 1}}, shape_options::uv); std::string vs = "#version 330 core \n" "layout (location = 0) in vec3 aPos; \n" "layout (location = 1) in vec2 aTexCoords; \n" "out vec2 uv; \n" "void main() { \n" " uv = aTexCoords; \n" " gl_Position = vec4(aPos, 1.0); \n" "}"; std::string fs; if (output_is_equirectangular) { fs = "#version 330 core \n" "uniform samplerCube cubemap; \n" "in vec2 uv; \n" "out vec4 FragColor; \n" "void main() { \n" " float phi = uv.x * 3.1415 * 2; \n" " float theta = (-uv.y + 0.5) * 3.1415; \n" " vec3 dir = vec3(cos(phi)*cos(theta),sin(theta),sin(phi)*cos(theta)); \n" " vec3 color = texture(cubemap, dir).rgb; \n" " color = color / (color + vec3(1.0)); \n" " color = pow(color, vec3(1.0/2.2)); \n" " FragColor = vec4(color, 1.0); \n" "}"; output.resize({cubemap.size().width * 2, cubemap.size().height * 1}); } else { fs = "#version 330 core \n" "uniform samplerCube cubemap; \n" "in vec2 uv; \n" "out vec4 FragColor; \n" "void main() { \n" " vec3 color = vec3(0.0,0.0,0.0); \n" " vec2 lp = vec2(mod(uv.x * 4, 1), mod(uv.y * 3, 1)); \n" " vec2 wp = vec2(uv.x * 4, uv.y * 3); \n" " if(wp.x > 1 && wp.x < 2) { \n" " if(wp.y > 2) // top (+y) \n" " color = texture(cubemap, vec3(-lp.x * 2 + 1, 1, -lp.y * 2 + 1)).rgb; \n" " else if(wp.y < 1) // bottom (-y) \n" " color = texture(cubemap, vec3(-lp.x * 2 + 1, -1, -lp.y * 2 + 1)).rgb; \n" " else // front (-z) \n" " color = texture(cubemap, vec3(-lp.x * 2 + 1,lp.y * 2 - 1, -1)).rgb; \n" " } else if(wp.y > 1 && wp.y < 2) { \n" " if(wp.x < 1) // left (+x) \n" " color = texture(cubemap, vec3(1,lp.y * 2 - 1,-lp.x * 2 + 1)).rgb; \n" " else if(wp.x < 3) // right (-x) \n" " color = texture(cubemap, vec3(-1,lp.y * 2 - 1,lp.x * 2 - 1)).rgb; \n" " else // back (+z) \n" " color = texture(cubemap, vec3(lp.x - 2 + 1,lp.y * 2 - 1, 1)).rgb; \n" " } else { FragColor = vec4(0.0); return; } \n" " color = color / (color + vec3(1.0)); \n" " color = pow(color, vec3(1.0/2.2)); \n" " FragColor = vec4(color, 1.0); \n" "}"; output.resize({cubemap.size().width * 4, cubemap.size().height * 3}); } output.bind(); Texture::View().apply(); ////////////////////////////// build shader ///////////////////////////////////////////////////////////////////////// Program program; program.attach(Shader(GL_VERTEX_SHADER, vs)); program.attach(Shader(GL_FRAGMENT_SHADER, fs)); if (!program.link()) std::cerr << "failed to compile unfold cubemap shader!\n" << program.err << std::endl; Framebuffer framebuffer; framebuffer.setRenderBufferStorageInternalFormat(GL_DEPTH_COMPONENT24); framebuffer.resize(output.size()); framebuffer.enable(); glViewport(0, 0, output.size().width, output.size().height); framebuffer.attachTexture(output); framebuffer.enable(); cubemap.bind(GL_TEXTURE0); program.use(); program.setUniform("cubemap", 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); quad.draw(); Framebuffer::disable(); return output; } Texture convertToCubemap(const Texture &input, texture_options input_options, hermes::size2 resolution) { bool input_is_hdr = circe::testMaskBit(input_options, circe::texture_options::hdr); bool input_is_equirectangular = testMaskBit(input_options, texture_options::equirectangular); std::string vs; std::string fs; Program program; if (input_is_equirectangular) { vs = "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "out vec3 localPos;\n" "uniform mat4 projection;\n" "uniform mat4 view;\n" "void main() {\n" " localPos = aPos; \n" " gl_Position = projection * view * vec4(localPos, 1.0);\n" "}"; fs = "#version 330 core\n" "out vec4 FragColor;\n" "in vec3 localPos;\n" "uniform sampler2D equirectangularMap;\n" "const vec2 invAtan = vec2(0.1591, 0.3183);\n" "vec2 SampleSphericalMap(vec3 v) {\n" " vec2 uv = vec2(atan(v.z, v.x), asin(v.y));\n" " uv *= invAtan;\n" " uv += 0.5;\n" " return uv;\n" "}\n" "void main() {\n" " vec2 uv = SampleSphericalMap(normalize(localPos));\n" " vec3 color = texture(equirectangularMap, uv).rgb;\n" " FragColor = vec4(color, 1.0);\n" "}"; program.attach(Shader(GL_VERTEX_SHADER, vs)); program.attach(Shader(GL_FRAGMENT_SHADER, fs)); if (!program.link()) std::cerr << "failed to compile equirectangular map shader!\n" << program.err << std::endl; program.use(); program.setUniform("equirectangularMap", 0); } Texture cubemap; cubemap.setTarget(GL_TEXTURE_CUBE_MAP); cubemap.setFormat(GL_RGB); if (input_is_hdr) { cubemap.setInternalFormat(GL_RGBA16F); cubemap.setType(GL_FLOAT); } cubemap.resize(resolution); cubemap.bind(); circe::gl::Texture::View parameters(GL_TEXTURE_CUBE_MAP); parameters[GL_TEXTURE_MIN_FILTER] = GL_LINEAR; parameters[GL_TEXTURE_MAG_FILTER] = GL_LINEAR; parameters[GL_TEXTURE_WRAP_S] = GL_CLAMP_TO_EDGE; parameters[GL_TEXTURE_WRAP_T] = GL_CLAMP_TO_EDGE; parameters[GL_TEXTURE_WRAP_R] = GL_CLAMP_TO_EDGE; parameters.apply(); // render cubemap faces auto projection = hermes::Transform::perspective(90, 1, 0.1, 10); hermes::Transform views[] = { hermes::Transform::lookAt({}, {1, 0, 0}, {0, -1, 0}), hermes::Transform::lookAt({}, {-1, 0, 0}, {0, -1, 0}), hermes::Transform::lookAt({}, {0, 1, 0}, {0, 0, -1}), hermes::Transform::lookAt({}, {0, -1, 0}, {0, 0, 1}), hermes::Transform::lookAt({}, {0, 0, -1}, {0, -1, 0}), hermes::Transform::lookAt({}, {0, 0, 1}, {0, -1, 0}), }; Framebuffer frambuffer; frambuffer.setRenderBufferStorageInternalFormat(GL_DEPTH_COMPONENT24); frambuffer.resize(resolution); frambuffer.enable(); glViewport(0, 0, resolution.width, resolution.height); SceneModel cube; cube = circe::Shapes::box({{-1, -1, -1}, {1, 1, 1}}); input.bind(); program.use(); program.setUniform("projection", projection); for (u32 i = 0; i < 6; ++i) { program.setUniform("view", views[i]); frambuffer.attachColorBuffer(cubemap.textureObjectId(), GL_TEXTURE_CUBE_MAP_POSITIVE_X + i); frambuffer.enable(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); cube.draw(); } Framebuffer::disable(); return cubemap; } Texture::Atlas::Atlas() = default; Texture::Atlas::~Atlas() = default; [[nodiscard]] const hermes::size2 &Texture::Atlas::size_in_texels() const { return size_in_texels_; } size_t Texture::Atlas::push(const Texture::Atlas::Region &region) { auto old_size = size_in_texels_; auto upper = region.offset + region.size; size_in_texels_.width = std::max(size_in_texels_.width, upper.width); size_in_texels_.height = std::max(size_in_texels_.height, upper.height); if (size_in_texels_ != old_size) updateUVs(); regions_.emplace_back(region); uvs_.push_back({{ static_cast<real_t>( region.offset.width) / size_in_texels_.width, static_cast<real_t>( region.offset.height) / size_in_texels_.height }, { static_cast<real_t>( upper.width) / size_in_texels_.width, static_cast<real_t>( upper.height) / size_in_texels_.height }}); return regions_.size() - 1; } void Texture::Atlas::updateUVs() { for (size_t i = 0; i < uvs_.size(); ++i) { uvs_[i].lower = {static_cast<real_t>( regions_[i].offset.width) / size_in_texels_.width, static_cast<real_t>( regions_[i].offset.height) / size_in_texels_.height}; uvs_[i].upper = {static_cast<real_t>( regions_[i].offset.width + regions_[i].size.width) / size_in_texels_.width, static_cast<real_t>( regions_[i].offset.height + regions_[i].size.height) / size_in_texels_.height}; } } const Texture::Atlas::Region &Texture::Atlas::operator[](size_t i) const { return regions_[i]; } Texture::Atlas::Region &Texture::Atlas::operator[](size_t i) { return regions_[i]; } const hermes::bbox2 &Texture::Atlas::uv(size_t i) const { return uvs_[i]; } Texture::View::View(GLuint target) : target_{target} { parameters_[GL_TEXTURE_WRAP_S] = GL_CLAMP_TO_EDGE; parameters_[GL_TEXTURE_WRAP_T] = GL_CLAMP_TO_EDGE; parameters_[GL_TEXTURE_WRAP_R] = GL_CLAMP_TO_EDGE; parameters_[GL_TEXTURE_MIN_FILTER] = GL_LINEAR; parameters_[GL_TEXTURE_MAG_FILTER] = GL_LINEAR; // parameters_[GL_TEXTURE_BASE_LEVEL] = 0; // parameters_[GL_TEXTURE_MAX_LEVEL] = 0; } Texture::View::View(circe::Color border_color, GLuint target) : Texture::View::View(target) { using_border_ = true; border_color_ = border_color; parameters_[GL_TEXTURE_WRAP_S] = GL_CLAMP_TO_BORDER; parameters_[GL_TEXTURE_WRAP_T] = GL_CLAMP_TO_BORDER; parameters_[GL_TEXTURE_WRAP_R] = GL_CLAMP_TO_BORDER; } void Texture::View::apply() const { for (auto &parameter : parameters_) glTexParameteri(target_, parameter.first, parameter.second); if (using_border_) glTexParameterfv(target_, GL_TEXTURE_BORDER_COLOR, border_color_.asArray()); } Texture Texture::fromFile(const hermes::Path &path, circe::texture_options input_options, circe::texture_options output_options) { // check input options bool input_is_hdr = circe::testMaskBit(input_options, circe::texture_options::hdr); // check output options bool output_is_cubemap = circe::testMaskBit(output_options, circe::texture_options::cubemap); // texture object Texture texture; // read file int width, height, channel_count; void *data; if (input_is_hdr) { stbi_set_flip_vertically_on_load(true); data = stbi_loadf(path.fullName().c_str(), &width, &height, &channel_count, 0); texture.attributes_.target = GL_TEXTURE_2D; texture.attributes_.internal_format = GL_RGB16F; texture.attributes_.format = (channel_count == 3) ? GL_RGB : GL_RGBA; texture.attributes_.type = GL_FLOAT; } else { data = stbi_load(path.fullName().c_str(), &width, &height, &channel_count, 0); texture.attributes_.target = GL_TEXTURE_2D; texture.attributes_.format = (channel_count == 3) ? GL_RGB : GL_RGBA; texture.attributes_.internal_format = GL_RGB; texture.attributes_.type = GL_UNSIGNED_BYTE; } if (!data) { std::cerr << "Failed to load texture from file " << path << std::endl; return Texture(); } // init texture texture.attributes_.size_in_texels = hermes::size3(width, height, 1); texture.setTexels(data); texture.bind(); circe::gl::Texture::View().apply(); texture.unbind(); stbi_image_free(data); if (output_is_cubemap) return convertToCubemap(texture, input_options, {512, 512}); return texture; } Texture Texture::fromFiles(const std::vector<hermes::Path> &face_paths) { Texture texture; // resize cube map texture.setTarget(GL_TEXTURE_CUBE_MAP); texture.setType(GL_UNSIGNED_BYTE); texture.attributes_.size_in_texels.depth = 1; // bind texture texture.bind(); // load faces int width, height, channel_count; for (size_t i = 0; i < face_paths.size(); ++i) { unsigned char *data = stbi_load(face_paths[i].fullName().c_str(), &width, &height, &channel_count, 0); if (!data) { // TODO report error std::cerr << "failed to load cubemap face texture\n"; return Texture(); } texture.attributes_.size_in_texels.width = width; texture.attributes_.size_in_texels.height = height; texture.attributes_.format = GL_RGB; texture.attributes_.internal_format = GL_RGB; texture.setTexels(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, data); CHECK_GL_ERRORS; stbi_image_free(data); } texture.unbind(); return texture; } Texture Texture::fromTexture(const Texture &texture, circe::texture_options output_options) { // check input options bool input_is_cubemap = texture.target() == GL_TEXTURE_CUBE_MAP; // check output options bool output_is_cubemap = circe::testMaskBit(output_options, circe::texture_options::cubemap); bool output_is_equirectangular = circe::testMaskBit(output_options, circe::texture_options::equirectangular); if (input_is_cubemap && !output_is_cubemap) return unfoldCubemap(texture, output_options); return Texture(); } Texture::Texture() { glGenTextures(1, &texture_object_); HERMES_ASSERT(texture_object_); } Texture::Texture(const Texture::Attributes &a, const void *data) : Texture() { attributes_ = a; setTexels(data); glBindTexture(attributes_.target, 0); } Texture::Texture(const Texture &other) : Texture() { attributes_ = other.attributes_; setTexels(nullptr); glBindTexture(attributes_.target, 0); } Texture::Texture(Texture &&other) noexcept { if (texture_object_) glDeleteTextures(1, &texture_object_); texture_object_ = other.texture_object_; attributes_ = other.attributes_; other.texture_object_ = 0; } Texture::~Texture() { glDeleteTextures(1, &texture_object_); } void Texture::set(const Texture::Attributes &a) { attributes_ = a; setTexels(nullptr); glBindTexture(attributes_.target, 0); } Texture &Texture::operator=(const Texture &other) { set(other.attributes_); return *this; } Texture &Texture::operator=(Texture &&other) noexcept { if (texture_object_) glDeleteTextures(1, &texture_object_); texture_object_ = other.texture_object_; attributes_ = other.attributes_; other.texture_object_ = 0; return *this; } void Texture::setTexels(const void *texels) const { /// bind texture glBindTexture(attributes_.target, texture_object_); if (attributes_.target == GL_TEXTURE_3D) glTexImage3D(GL_TEXTURE_3D, 0, attributes_.internal_format, attributes_.size_in_texels.width, attributes_.size_in_texels.height, attributes_.size_in_texels.depth, 0, attributes_.format, attributes_.type, texels); else if (attributes_.target == GL_TEXTURE_CUBE_MAP) for (u32 i = 0; i < 6; ++i) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, attributes_.internal_format, attributes_.size_in_texels.width, attributes_.size_in_texels.height, 0, attributes_.format, attributes_.type, texels); else glTexImage2D(GL_TEXTURE_2D, 0, attributes_.internal_format, attributes_.size_in_texels.width, attributes_.size_in_texels.height, 0, attributes_.format, attributes_.type, texels); CHECK_GL_ERRORS; glBindTexture(attributes_.target, 0); } void Texture::setTexels(GLenum target, const void *texels) const { /// bind texture glBindTexture(attributes_.target, texture_object_); glTexImage2D(target, 0, attributes_.internal_format, attributes_.size_in_texels.width, attributes_.size_in_texels.height, 0, attributes_.format, attributes_.type, texels); CHECK_GL_ERRORS; glBindTexture(attributes_.target, 0); } void Texture::generateMipmap() const { glBindTexture(attributes_.target, texture_object_); glGenerateMipmap(attributes_.target); CHECK_GL_ERRORS; glBindTexture(attributes_.target, 0); } void Texture::bind() const { glBindTexture(attributes_.target, texture_object_); } void Texture::unbind() const { glBindTexture(attributes_.target, 0); } void Texture::bind(GLenum t) const { glActiveTexture(t); glBindTexture(attributes_.target, texture_object_); } void Texture::bindImage(GLenum t) const { glActiveTexture(t); glBindImageTexture(0, texture_object_, 0, GL_FALSE, 0, GL_WRITE_ONLY, attributes_.internal_format); CHECK_GL_ERRORS; } hermes::size3 Texture::size() const { return attributes_.size_in_texels; } GLuint Texture::textureObjectId() const { return texture_object_; } GLenum Texture::target() const { return attributes_.target; } GLint Texture::internalFormat() const { return attributes_.internal_format; } GLenum Texture::format() const { return attributes_.format; } GLenum Texture::type() const { return attributes_.type; } std::ostream &operator<<(std::ostream &out, Texture &pt) { auto width = static_cast<int>(pt.attributes_.size_in_texels.width); auto height = static_cast<int>(pt.attributes_.size_in_texels.height); u8 *data = nullptr; auto bytes_per_texel = OpenGL::dataSizeInBytes(pt.attributes_.type); auto memory_size = width * height * OpenGL::dataSizeInBytes(pt.attributes_.type); data = new u8[memory_size]; memset(data, 0, memory_size); glActiveTexture(GL_TEXTURE0); std::cerr << "texture object " << pt.texture_object_ << std::endl; out << width << " x " << height << " texels of type " << OpenGL::TypeToStr(pt.attributes_.type) << " (" << bytes_per_texel << " bytes per texel)" << std::endl; out << "total memory: " << memory_size << " bytes\n"; glBindTexture(pt.attributes_.target, pt.texture_object_); glGetTexImage(pt.attributes_.target, 0, pt.attributes_.format, pt.attributes_.type, data); CHECK_GL_ERRORS; for (int j(height - 1); j >= 0; --j) { for (int i(0); i < width; ++i) { switch (pt.attributes_.type) { case GL_FLOAT:out << reinterpret_cast<f32 *>(data)[(int) (j * width + i)] << ","; break; case GL_UNSIGNED_INT:out << reinterpret_cast<u32 *>(data)[(int) (j * width + i)] << ","; break; default:out << static_cast<int>(data[(int) (j * width + i)]) << ","; } } out << std::endl; } delete[] data; return out; } std::vector<unsigned char> Texture::texels() const { auto width = static_cast<int>(attributes_.size_in_texels.width); auto height = static_cast<int>(attributes_.size_in_texels.height); size_t element_size = 1; if(attributes_.type == GL_FLOAT) element_size = 4; std::vector<unsigned char> data(element_size * 4 * width * height, 0); glActiveTexture(GL_TEXTURE0); glBindTexture(attributes_.target, texture_object_); glGetTexImage(attributes_.target, 0, attributes_.format, attributes_.type, &data[0]); CHECK_GL_ERRORS; return data; } std::vector<unsigned char> Texture::texels(hermes::index2 offset, hermes::size2 size) const { if (offset.i < 0 || offset.j < 0 || offset.i + size.width >= attributes_.size_in_texels.width || offset.j + size.height >= attributes_.size_in_texels.height) return {}; std::vector<unsigned char> data(4 * size.total()); glActiveTexture(GL_TEXTURE0); glBindTexture(attributes_.target, texture_object_); glGetTextureSubImage(attributes_.target, 0, offset.i, offset.j, 0, size.width, size.height, 1, GL_RGBA, GL_UNSIGNED_BYTE, data.size(), &data[0]); CHECK_GL_ERRORS; return data; } void Texture::resize(const hermes::size3 &new_size) { attributes_.size_in_texels = new_size; setTexels(nullptr); } void Texture::setInternalFormat(GLint internal_format) { attributes_.internal_format = internal_format; } void Texture::setFormat(GLint format) { attributes_.format = format; } void Texture::setType(GLenum type) { attributes_.type = type; } void Texture::setTarget(GLenum _target) { attributes_.target = _target; } void Texture::resize(const hermes::size2 &new_size) { attributes_.size_in_texels.width = new_size.width; attributes_.size_in_texels.height = new_size.height; attributes_.size_in_texels.depth = 1; setTexels(nullptr); } } // namespace circe
40.784314
120
0.576723
[ "render", "object", "vector", "transform" ]
0d5f3c075074dcdec011f5482333d61db42ac2f1
14,230
cc
C++
src/search_local/index_read/doc_manager.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
3
2021-08-18T09:59:42.000Z
2021-09-07T03:11:28.000Z
src/search_local/index_read/doc_manager.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
null
null
null
src/search_local/index_read/doc_manager.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
null
null
null
/* * ===================================================================================== * * Filename: doc_manager.h * * Description: doc manager class definition. * * Version: 1.0 * Created: 09/08/2018 * Revision: none * Compiler: gcc * * Author: zhulin, shzhulin3@jd.com * Company: JD.com, Inc. * * ===================================================================================== */ #include "request_context.h" #include "doc_manager.h" #include "log.h" #include "search_util.h" #include "index_tbl_op.h" #include "db_manager.h" #include "process/geo_distance_query_process.h" #include <math.h> #include <sstream> extern CIndexTableManager g_IndexInstance; DocManager::DocManager(RequestContext *c) : score_str_map() , score_int_map() , score_double_map() , valid_version_() , doc_content_map_() , component(c) { } DocManager::~DocManager(){ } bool DocManager::CheckDocByExtraFilterKey(std::string doc_id){ std::vector<ExtraFilterKey> extra_filter_vec = component->ExtraFilterOrKeys(); std::vector<ExtraFilterKey> extra_filter_and_vec = component->ExtraFilterAndKeys(); std::vector<ExtraFilterKey> extra_filter_invert_vec = component->ExtraFilterInvertKeys(); if(extra_filter_vec.size() == 0 && extra_filter_and_vec.size() == 0 && extra_filter_invert_vec.size() == 0){ return true; } else { std::vector<std::string> fields; for(int i = 0; i < (int)extra_filter_vec.size(); i++){ fields.push_back(extra_filter_vec[i].field_name); } for(int i = 0; i < (int)extra_filter_and_vec.size(); i++){ fields.push_back(extra_filter_and_vec[i].field_name); } for(int i = 0; i < (int)extra_filter_invert_vec.size(); i++){ fields.push_back(extra_filter_invert_vec[i].field_name); } Json::Value value; uint32_t doc_version = 0; if(valid_version_.find(doc_id) != valid_version_.end()){ doc_version = valid_version_[doc_id]; } if(doc_content_map_.find(doc_id) != doc_content_map_.end()){ std::string extend = doc_content_map_[doc_id]; Json::Reader r(Json::Features::strictMode()); int ret2 = r.parse(extend.c_str(), extend.c_str() + extend.length(), value); if (0 == ret2){ log_error("the err json is %s, errmsg : %s", extend.c_str(), r.getFormattedErrorMessages().c_str()); return false; } } else { bool bRet = g_IndexInstance.GetContentByField(component->Appid(), doc_id, doc_version, fields, value); if(bRet == false){ log_error("get field content error, appid[%d] doc_id[%s].", component->Appid(), doc_id.c_str()); return true; } } bool key_or_valid = false; CheckIfKeyValid(extra_filter_vec, value, true, key_or_valid); if(extra_filter_vec.size() > 0 && key_or_valid == false){ return false; } bool key_and_valid = true; CheckIfKeyValid(extra_filter_and_vec, value, false, key_and_valid); if(key_and_valid == false){ return false; } bool key_invert_valid = false; CheckIfKeyValid(extra_filter_invert_vec, value, true, key_invert_valid); if(key_invert_valid == true){ return false; } return true; } } void DocManager::CheckIfKeyValid(const std::vector<ExtraFilterKey>& extra_filter_vec, const Json::Value &value, bool flag, bool &key_valid){ for(int i = 0; i < (int)extra_filter_vec.size(); i++){ bool the_same = false; std::string field_name = extra_filter_vec[i].field_name; if(extra_filter_vec[i].field_type == FIELD_INT){ std::string query = extra_filter_vec[i].field_value; std::vector<std::string> query_vec = splitEx(query, "|"); if(query_vec.size() > 1){ for(int i = 0 ; i < (int)query_vec.size(); i++){ if(atoi(query_vec[i].c_str()) == value[field_name.c_str()].asInt()){ the_same = true; break; } } } else { the_same = (atoi(extra_filter_vec[i].field_value.c_str()) == value[field_name.c_str()].asInt()); } } else if(extra_filter_vec[i].field_type == FIELD_DOUBLE){ double d_field_value = atof(extra_filter_vec[i].field_value.c_str()); double d_extend = value[field_name.c_str()].asDouble(); the_same = (fabs(d_field_value - d_extend) < 1e-15); } else if(extra_filter_vec[i].field_type == FIELD_STRING){ std::string snapshot = value[field_name.c_str()].asString(); std::string query = extra_filter_vec[i].field_value; std::set<std::string> snapshot_set = splitStr(snapshot, "|"); std::vector<std::string> query_vec = splitEx(query, "|"); for(int i = 0 ; i < (int)query_vec.size(); i++){ if(snapshot_set.find(query_vec[i]) != snapshot_set.end()){ the_same = true; break; } } } if(the_same == flag){ key_valid = flag; break; } } } bool DocManager::GetDocContent(){ const std::vector<IndexInfo>& o_index_info_vet = ResultContext::Instance()->GetIndexInfos(); if (component->SnapshotSwitch() == 1 && o_index_info_vet.size() <= 1000) { bool need_version = false; if(component->RequiredFields().size() > 0){ need_version = true; } bool bRet = g_IndexInstance.DocValid(component->Appid(), o_index_info_vet, need_version, valid_version_, doc_content_map_); if (false == bRet) { log_error("GetDocInfo by snapshot error."); return false; } } else { for(size_t i = 0 ; i < o_index_info_vet.size(); i++){ ResultContext::Instance()->SetValidDocs(o_index_info_vet[i].doc_id); if(o_index_info_vet[i].extend != ""){ doc_content_map_.insert(std::make_pair(o_index_info_vet[i].doc_id, o_index_info_vet[i].extend)); } } } log_debug("doc_id_ver_vec size: %d", (int)o_index_info_vet.size()); return true; } bool DocManager::GetDocContent( const GeoPointContext& geo_point , std::vector<IndexInfo>& index_infos) { std::vector<IndexInfo>::iterator iter = index_infos.begin(); for( ;iter != index_infos.end(); ++iter){ if((iter->extend) != ""){ doc_content_map_.insert(make_pair(iter->doc_id, iter->extend)); } } if(doc_content_map_.empty()){ g_IndexInstance.GetDocContent(component->Appid(),index_infos , doc_content_map_); } hash_double_map docid_dis_map; bool bret = GetGisDistance(component->Appid(), geo_point, doc_content_map_, docid_dis_map); if (!bret){ return bret; } std::vector<IndexInfo> o_valid_index_infos; hash_double_map::iterator docid_dis_iter = docid_dis_map.begin(); for ( ; docid_dis_iter != docid_dis_map.end(); ++docid_dis_iter){ iter = index_infos.begin(); for( ;iter != index_infos.end(); ++iter){ if ((docid_dis_iter->first) == (iter->doc_id)){ iter->distance = docid_dis_iter->second; o_valid_index_infos.push_back(*iter); } } } index_infos.swap(o_valid_index_infos); return bret; } bool DocManager::AppendFieldsToRes(Json::Value &response, std::vector<std::string> &m_fields){ for(int i = 0; i < (int)response["result"].size(); i++){ Json::Value doc_info = response["result"][i]; std::string doc_id = doc_info["doc_id"].asString(); if(doc_content_map_.find(doc_id) != doc_content_map_.end()){ std::string extend = doc_content_map_[doc_id]; Json::Reader r(Json::Features::strictMode()); Json::Value recv_packet; int ret2 = r.parse(extend.c_str(), extend.c_str() + extend.length(), recv_packet); if (0 == ret2){ log_error("parse json error [%s], errmsg : %s", extend.c_str(), r.getFormattedErrorMessages().c_str()); return false; } Json::Value &value = response["result"][i]; for(int i = 0; i < (int)m_fields.size(); i++){ if (recv_packet.isMember(m_fields[i].c_str())) { if(recv_packet[m_fields[i].c_str()].isUInt()){ value[m_fields[i].c_str()] = recv_packet[m_fields[i].c_str()].asUInt(); } else if(recv_packet[m_fields[i].c_str()].isString()){ value[m_fields[i].c_str()] = recv_packet[m_fields[i].c_str()].asString(); } else if(recv_packet[m_fields[i].c_str()].isDouble()){ value[m_fields[i].c_str()] = recv_packet[m_fields[i].c_str()].asDouble(); } else if(recv_packet[m_fields[i].c_str()].isObject() || recv_packet[m_fields[i].c_str()].isArray()){ value[m_fields[i].c_str()] = recv_packet[m_fields[i].c_str()]; }else{ log_error("field[%s] data type error.", m_fields[i].c_str()); } } else { log_error("appid[%u] field[%s] invalid.", component->Appid(), m_fields[i].c_str()); } } } else { uint32_t doc_version = 0; if(valid_version_.find(doc_info["doc_id"].asString()) != valid_version_.end()){ doc_version = valid_version_[doc_info["doc_id"].asString()]; } bool bRet = g_IndexInstance.GetContentByField(component->Appid(), doc_info["doc_id"].asString(), doc_version, m_fields, response["result"][i]); if(bRet == false){ log_error("get field content error."); return false; } } } return true; } bool DocManager::GetScoreMap(std::string doc_id, uint32_t m_sort_type, std::string m_sort_field, FIELDTYPE &m_sort_field_type){ if(doc_content_map_.find(doc_id) != doc_content_map_.end()){ uint32_t field_type = 0; bool bRet = DBManager::Instance()->GetFieldType(component->Appid(), m_sort_field, field_type); if(false == bRet){ log_error("appid[%d] field[%s] not find.", component->Appid(), m_sort_field.c_str()); return false; } std::string extend = doc_content_map_[doc_id]; if(field_type == FIELD_INT){ int len = strlen(m_sort_field.c_str()) + strlen("\":"); size_t pos1 = extend.find(m_sort_field); size_t pos2 = extend.find_first_of(",", pos1); if(pos2 == std::string::npos){ pos2 = extend.find_first_of("}", pos1); } if(pos1 != std::string::npos && pos2 != std::string::npos){ string field_str = extend.substr(pos1+len, pos2-pos1-len); int field_int; istringstream iss(field_str); iss >> field_int; m_sort_field_type = FIELDTYPE_INT; score_int_map.insert(std::make_pair(doc_id, field_int)); } else { m_sort_field_type = FIELDTYPE_INT; score_int_map.insert(std::make_pair(doc_id, 0)); } } else { Json::Reader r(Json::Features::strictMode()); Json::Value recv_packet; int ret2 = r.parse(extend.c_str(), extend.c_str() + extend.length(), recv_packet); if (0 == ret2){ log_error("the err json is %s, errmsg : %s", extend.c_str(), r.getFormattedErrorMessages().c_str()); return false; } if(recv_packet.isMember(m_sort_field.c_str())) { if(recv_packet[m_sort_field.c_str()].isUInt()){ m_sort_field_type = FIELDTYPE_INT; score_int_map.insert(make_pair(doc_id, recv_packet[m_sort_field.c_str()].asUInt())); } else if(recv_packet[m_sort_field.c_str()].isString()){ m_sort_field_type = FIELDTYPE_STRING; score_str_map.insert(make_pair(doc_id, recv_packet[m_sort_field.c_str()].asString())); } else if(recv_packet[m_sort_field.c_str()].isDouble()){ m_sort_field_type = FIELDTYPE_DOUBLE; score_double_map.insert(make_pair(doc_id, recv_packet[m_sort_field.c_str()].asDouble())); } else { log_error("sort_field[%s] data type error.", m_sort_field.c_str()); return false; } } else { log_error("appid[%u] sort_field[%s] invalid.", component->Appid(), m_sort_field.c_str()); return false; } } } else { ScoreInfo score_info; bool bRet = g_IndexInstance.GetScoreByField(component->Appid(), doc_id, m_sort_field, m_sort_type, score_info); if(bRet == false){ log_error("get score by field error."); return false; } m_sort_field_type = score_info.type; if(score_info.type == FIELDTYPE_INT){ score_int_map.insert(make_pair(doc_id, score_info.i)); } else if(score_info.type == FIELDTYPE_STRING){ score_str_map.insert(make_pair(doc_id, score_info.str)); } else if(score_info.type == FIELDTYPE_DOUBLE){ score_double_map.insert(make_pair(doc_id, score_info.d)); } } return true; } std::map<std::string, std::string>& DocManager::ScoreStrMap(){ return score_str_map; } std::map<std::string, int>& DocManager::ScoreIntMap(){ return score_int_map; } std::map<std::string, double>& DocManager::ScoreDoubleMap(){ return score_double_map; } std::map<std::string, uint32_t>& DocManager::ValidVersion(){ return valid_version_; }
41.246377
155
0.568587
[ "vector" ]
0d621e06cd3f625ef053b418b83b76c41fbf9ec3
16,472
cpp
C++
source/decoder.cpp
astolap/WaSP
2daa1963d1f3d3fb50d3b576d470f9af0f6ce463
[ "BSD-2-Clause" ]
4
2020-03-04T10:41:26.000Z
2021-04-15T06:29:41.000Z
source/decoder.cpp
astolap/WaSP
2daa1963d1f3d3fb50d3b576d470f9af0f6ce463
[ "BSD-2-Clause" ]
2
2019-01-14T15:58:47.000Z
2021-04-18T09:09:51.000Z
source/decoder.cpp
astolap/WaSP
2daa1963d1f3d3fb50d3b576d470f9af0f6ce463
[ "BSD-2-Clause" ]
4
2018-07-20T14:36:42.000Z
2021-06-28T13:03:57.000Z
/*BSD 2-Clause License * Copyright(c) 2019, Pekka Astola * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met : * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY 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 <cstdio> #include <cstring> #include <cmath> #include "decoder.hh" #include "view.hh" #include "minconf.hh" #include "codestream.hh" #include "predictdepth.hh" #include "residualjp2.hh" #include "medianfilter.hh" #include "ppm.hh" #include "warping.hh" #include "merging.hh" #include "inpainting.hh" #include "sparsefilter.hh" #include "WaSPConf.hh" #define SAVE_PARTIAL_WARPED_VIEWS false decoder::decoder(const WaSPsetup decoder_setup) { setup = decoder_setup; input_LF = fopen(setup.input_directory.c_str(), "rb"); } decoder::~decoder() { if (LF != nullptr) { dealloc(); } fclose(input_LF); } void decoder::decode() { decode_header(); decode_views(); } void decoder::decode_header() { n_bytes_prediction += (int32_t)fread( &number_of_views, sizeof(int32_t), 1, input_LF) * sizeof(int32_t); n_bytes_prediction += (int32_t)fread( &number_of_rows, sizeof(int32_t), 1, input_LF) * sizeof(int32_t); n_bytes_prediction += (int32_t)fread( &number_of_columns, sizeof(int32_t), 1, input_LF) * sizeof(int32_t); n_bytes_prediction += (int32_t)fread( &minimum_depth, sizeof(uint16_t), 1, input_LF) * sizeof(uint16_t); uint8_t colorspace_enumerator; n_bytes_prediction += (int32_t)fread( &colorspace_enumerator, sizeof(uint8_t), 1, input_LF) * sizeof(uint8_t); if (colorspace_enumerator == 0) { colorspace_LF = "RGB"; } if (colorspace_enumerator == 1) { colorspace_LF = "YCbCr"; } n_bytes_prediction += (int32_t)fread( &maxh, sizeof(int32_t), 1, input_LF) * sizeof(uint8_t); } void decoder::forward_warp_texture_references( view *LF, view *SAI, uint16_t **warped_texture_views, uint16_t **warped_depth_views, float **DispTargs) { for (int32_t ij = 0; ij < SAI->n_references; ij++) { view *ref_view = LF + SAI->references[ij]; int32_t tmp_w, tmp_r, tmp_ncomp; aux_read16PGMPPM( ref_view->path_out_pgm, tmp_w, tmp_r, tmp_ncomp, ref_view->depth); aux_read16PGMPPM( ref_view->path_internal_colorspace_out_ppm, tmp_w, tmp_r, tmp_ncomp, ref_view->color); /* FORWARD warp color */ warpView0_to_View1( ref_view, SAI, warped_texture_views[ij], warped_depth_views[ij], DispTargs[ij]); delete[](ref_view->depth); delete[](ref_view->color); ref_view->depth = nullptr; ref_view->color = nullptr; if (SAVE_PARTIAL_WARPED_VIEWS) { char tmp_str[1024]; sprintf( tmp_str, "%s/%03d_%03d_warped_to_%03d_%03d.ppm", setup.output_directory.c_str(), (ref_view)->c, (ref_view)->r, SAI->c, SAI->r); aux_write16PGMPPM( tmp_str, SAI->nc, SAI->nr, 3, warped_texture_views[ij]); sprintf( tmp_str, "%s/%03d_%03d_warped_to_%03d_%03d.pgm", setup.output_directory.c_str(), (ref_view)->c, (ref_view)->r, SAI->c, SAI->r); aux_write16PGMPPM( tmp_str, SAI->nc, SAI->nr, 1, warped_depth_views[ij]); } } } void decoder::merge_texture_views( view *SAI, view *LF, uint16_t **warped_texture_views, float **DispTargs) { initViewW(SAI, DispTargs); if (SAI->mmode == 0) { for (int32_t icomp = 0; icomp < SAI->ncomp; icomp++) { mergeWarped_N_icomp( warped_texture_views, SAI, icomp); } /* hole filling for texture*/ for (int32_t icomp = 0; icomp < SAI->ncomp; icomp++) { uint32_t nholes = holefilling( SAI->color + icomp*SAI->nr*SAI->nc, SAI->nr, SAI->nc, (uint16_t)0, SAI->seg_vp); } } if (SAI->mmode == 1) { /* we don't use LS weights but something derived on geometric distance in view array*/ for (int32_t icomp = 0; icomp < SAI->ncomp; icomp++) { getGeomWeight_icomp( SAI, LF, icomp); } /* merge color with prediction */ for (int32_t icomp = 0; icomp < SAI->ncomp; icomp++) { mergeWarped_N_icomp( warped_texture_views, SAI, icomp); } /* hole filling for texture*/ for (int32_t icomp = 0; icomp < 3; icomp++) { uint32_t nholes = holefilling( SAI->color + icomp*SAI->nr*SAI->nc, SAI->nr, SAI->nc, (uint16_t)0, SAI->seg_vp); } } if (SAI->mmode == 2) { mergeMedian_N(warped_texture_views, DispTargs, SAI, 3); /* hole filling for texture*/ for (int32_t icomp = 0; icomp < 3; icomp++) { uint32_t nholes = holefilling( SAI->color + icomp*SAI->nr*SAI->nc, SAI->nr, SAI->nc, (uint16_t)0, SAI->seg_vp); } } delete[](SAI->seg_vp); SAI->seg_vp = nullptr; delete[](SAI->bmask); SAI->bmask = nullptr; } void decoder::predict_texture_view(view* SAI) { if (SAI->n_references > 0) { printf("Predicting texture for view %03d_%03d\n", SAI->c, SAI->r); uint16_t **warped_texture_views = nullptr; uint16_t **warped_depth_views = nullptr; float **DispTargs = nullptr; init_warping_arrays( SAI->n_references, warped_texture_views, warped_depth_views, DispTargs, SAI->nr, SAI->nc, SAI->ncomp); forward_warp_texture_references( LF, SAI, warped_texture_views, warped_depth_views, DispTargs); merge_texture_views( SAI, LF, warped_texture_views, DispTargs); clean_warping_arrays( SAI->n_references, warped_texture_views, warped_depth_views, DispTargs); if (SAI->use_global_sparse) { uint16_t *sp_filtered_image_padded = new uint16_t[(SAI->nr + 2 * SAI->NNt)*(SAI->nc + 2 * SAI->NNt)*SAI->ncomp](); for (int32_t icomp = 0; icomp < SAI->ncomp; icomp++) { dequantize_and_reorder_spfilter( SAI->sparse_filters.at(icomp)); uint16_t *padded_icomp_sai = padArrayUint16_t(SAI->color + SAI->nr*SAI->nc*icomp, SAI->nr, SAI->nc, SAI->NNt); std::vector<double> filtered_icomp = applyGlobalSparseFilter( padded_icomp_sai, SAI->nr + 2 * SAI->NNt, SAI->nc + 2 * SAI->NNt, SAI->Ms, SAI->NNt, SPARSE_BIAS_TERM, SAI->sparse_filters.at(icomp).filter_coefficients); delete[](padded_icomp_sai); for (int32_t iij = 0; iij < (SAI->nr + 2 * SAI->NNt)*(SAI->nc + 2 * SAI->NNt); iij++) { double mmax = static_cast<double>((1 << BIT_DEPTH) - 1); filtered_icomp[iij] = clip(filtered_icomp[iij], 0.0, mmax); sp_filtered_image_padded[iij + (SAI->nr + 2 * SAI->NNt)*(SAI->nc + 2 * SAI->NNt)*icomp] = static_cast<uint16_t>(floor(filtered_icomp[iij] + 0.5)); } uint16_t *cropped_icomp = cropImage(sp_filtered_image_padded + (SAI->nr + 2 * SAI->NNt)*(SAI->nc + 2 * SAI->NNt)*icomp, (SAI->nr + 2 * SAI->NNt), (SAI->nc + 2 * SAI->NNt), SAI->NNt); memcpy( SAI->color + SAI->nr*SAI->nc*icomp, cropped_icomp, sizeof(uint16_t)*SAI->nr*SAI->nc); delete[](cropped_icomp); } delete[](sp_filtered_image_padded); } } } void decoder::decode_views() { LF = new view[number_of_views](); int32_t ii = 0; /*view index*/ while (ii < number_of_views) { view *SAI = LF + ii; ii++; initView(SAI); SAI->nr = number_of_rows; SAI->nc = number_of_columns; SAI->colorspace = colorspace_LF; if (minimum_depth > 0) { SAI->min_inv_d = static_cast<int32_t>(minimum_depth); } minimal_config mconf; codestreamToViewHeader( n_bytes_prediction, SAI, input_LF, mconf); setPaths( SAI, "", setup.output_directory.c_str()); if (feof(input_LF)) { printf("File reading error. Terminating\t...\n"); exit(0); } printf("Decoding view %03d_%03d\n", SAI->c, SAI->r); SAI->color = new uint16_t[SAI->nr * SAI->nc * 3](); SAI->depth = new uint16_t[SAI->nr * SAI->nc](); /*main texture prediction here*/ predict_texture_view(SAI); /*extract residuals from codestream*/ if (SAI->has_color_residual) { printf("Decoding texture residual for view %03d_%03d\n", SAI->c, SAI->r); readResidualFromDisk( SAI->jp2_residual_path_jp2, n_bytes_residual, input_LF, JP2_dict); } if (SAI->has_depth_residual) { printf("Decoding normalized disparity residual for view %03d_%03d\n", SAI->c, SAI->r); readResidualFromDisk( SAI->jp2_residual_depth_path_jp2, n_bytes_residual, input_LF, JP2_dict); } /* apply texture residual */ if (SAI->has_color_residual) { int32_t Q = 1; int32_t offset = 0; if (SAI->level > 1) { Q = 2; const int32_t bpc = 10; offset = (1 << bpc) - 1; /* 10bit images currently */ } uint16_t *decoded_residual_image = decode_residual_JP2( SAI->path_raw_texture_residual_at_decoder_ppm, (setup.wasp_kakadu_directory + "/kdu_expand").c_str(), SAI->jp2_residual_path_jp2); aux_write16PGMPPM( SAI->path_raw_texture_residual_at_decoder_ppm, SAI->nc, SAI->nr, 3, decoded_residual_image); double *residual = dequantize_residual( decoded_residual_image, SAI->nr, SAI->nc, SAI->ncomp, 10, Q, offset); uint16_t *corrected = apply_residual( SAI->color, residual, SAI->nr, SAI->nc, SAI->ncomp, 10); /* update SAI->color to contain corrected (i.e., prediction + residual) version*/ memcpy( SAI->color, corrected, sizeof(uint16_t)*SAI->nr*SAI->nc*SAI->ncomp); delete[](residual); delete[](corrected); delete[](decoded_residual_image); } if (SAI->has_depth_residual) { delete[](SAI->depth); /* has JP2 encoded depth */ decodeKakadu( SAI->path_out_pgm, (setup.wasp_kakadu_directory + "/kdu_expand").c_str(), SAI->jp2_residual_depth_path_jp2); int32_t nr1, nc1, ncomp1; aux_read16PGMPPM( SAI->path_out_pgm, nc1, nr1, ncomp1, SAI->depth); } else { /*inverse depth prediction*/ if (SAI->level < maxh) { WaSP_predict_depth(SAI, LF); } } if (MEDFILT_DEPTH) { uint16_t *filtered_depth = medfilt2D( SAI->depth, 3, SAI->nr, SAI->nc); memcpy( SAI->depth, filtered_depth, sizeof(uint16_t) * SAI->nr * SAI->nc); delete[](filtered_depth); } /*internal colorspace version*/ aux_write16PGMPPM( SAI->path_internal_colorspace_out_ppm, SAI->nc, SAI->nr, SAI->ncomp, SAI->color); /*colorspace transformation back to input*/ write_output_ppm( SAI->color, SAI->path_out_ppm, SAI->nr, SAI->nc, SAI->ncomp, 10, SAI->colorspace); /*write inverse depth .pgm*/ if (SAI->level < maxh) { aux_write16PGMPPM( SAI->path_out_pgm, SAI->nc, SAI->nr, 1, SAI->depth); } if (SAI->color != nullptr) { delete[](SAI->color); SAI->color = nullptr; } if (SAI->depth != nullptr) { delete[](SAI->depth); SAI->depth = nullptr; } if (SAI->seg_vp != nullptr) { delete[](SAI->seg_vp); SAI->seg_vp = nullptr; } } } void decoder::dealloc() { for (int32_t ii = 0; ii < number_of_views; ii++) { view* SAI = LF + ii; if (SAI->color != nullptr) delete[](SAI->color); if (SAI->depth != nullptr) delete[](SAI->depth); if (SAI->references != nullptr) delete[](SAI->references); if (SAI->depth_references != nullptr) delete[](SAI->depth_references); if (SAI->merge_weights != nullptr) delete[](SAI->merge_weights); if (SAI->sparse_weights != nullptr) delete[](SAI->sparse_weights); if (SAI->bmask != nullptr) delete[](SAI->bmask); if (SAI->seg_vp != nullptr) delete[](SAI->seg_vp); if (SAI->sparse_mask != nullptr) delete[](SAI->sparse_mask); } delete[](LF); }
25.981073
113
0.502975
[ "vector" ]
0d69d2464023f6d851ccb440d19c51c577406152
1,420
cpp
C++
books/programming-principles-and-practice-using-c++/4d.cpp
kruschk/learning
a93cefacbd277bd00de2919e31dfbf8e619cfff2
[ "MIT" ]
1
2021-06-19T03:34:20.000Z
2021-06-19T03:34:20.000Z
books/programming-principles-and-practice-using-c++/4d.cpp
kruschk/learning
a93cefacbd277bd00de2919e31dfbf8e619cfff2
[ "MIT" ]
3
2021-05-10T21:53:08.000Z
2022-03-25T22:46:26.000Z
books/programming-principles-and-practice-using-c++/4d.cpp
kruschk/learning
a93cefacbd277bd00de2919e31dfbf8e619cfff2
[ "MIT" ]
null
null
null
#include "std_lib_facilities.h" double unit_conversion(double, string); int main(void) { vector<double> record; double number, smallest, largest; string unit = "|"; double sum = 0; cin >> number >> unit; number = unit_conversion(number, unit); smallest = largest = number; cout << number << " m, the smallest and the largest so far!\n"; sum += number; record.push_back(number); while (cin >> number >> unit) { number = unit_conversion(number, unit); if (number < smallest) { smallest = number; cout << smallest << " m, the smallest so far\n"; } else if (number > largest) { largest = number; cout << largest << " m, the largest so far\n"; } else { cout << number << " m\n"; } record.push_back(number); sum += number; } cout << "smallest:\n\t" << smallest << " m\n"; cout << "largest:\n\t" << largest << " m\n"; cout << "number of values:\n\t" << record.size() << '\n'; cout << "sum of values entered:\n\t" << sum << " m\n"; sort(record.begin(), record.end()); cout << "Entered values (in ascending order):\n"; for (double x : record) { cout << '\t' << x << " m\n"; } } // converts to m double unit_conversion(double d, string s) { if (s == "cm") { return d/100.0; } else if (s == "in") { return d*2.54/100.0; } else if (s == "ft") { return d*12.0*2.54/100.0; } else if (s == "m") { return d; } else { simple_error("Illegal unit.\n"); } }
21.846154
64
0.583099
[ "vector" ]
0d74302f87e355bde602b1ad2c5b8115d16020c5
3,401
cpp
C++
Tests/VtkHDF5Test.cpp
mpartio/MXADataModel
cfab4b41bca5c71d0ab16fb4f3ed3097093f0a57
[ "BSD-3-Clause" ]
null
null
null
Tests/VtkHDF5Test.cpp
mpartio/MXADataModel
cfab4b41bca5c71d0ab16fb4f3ed3097093f0a57
[ "BSD-3-Clause" ]
null
null
null
Tests/VtkHDF5Test.cpp
mpartio/MXADataModel
cfab4b41bca5c71d0ab16fb4f3ed3097093f0a57
[ "BSD-3-Clause" ]
1
2020-08-26T07:08:26.000Z
2020-08-26T07:08:26.000Z
/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007, 2010 Michael A. Jackson for BlueQuartz Software // All rights reserved. // BSD License: http://www.opensource.org/licenses/bsd-license.html // // This code was written under United States Air Force Contract number // FA8650-04-C-5229 // /////////////////////////////////////////////////////////////////////////////// #include <MXA/Common/MXATypeDefs.h> #include <MXA/Common/LogTime.h> #include <MXA/Core/MXADataModel.h> #include <MXA/Core/MXADataRecord.h> #include <MXA/HDF5/H5Lite.h> #include <MXA/HDF5/vtkHDF5.h> #include <Testing/DataFileGenerator.h> #include <TestDataFileLocations.h> //-- HDF5 Includes #include <hdf5.h> //-- Vtk includes #include <vtkType.h> #include <vtkSmartPointer.h> #include <vtkImageData.h> #include <vtkTIFFWriter.h> #include <vtkXMLImageDataWriter.h> // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- herr_t test() { herr_t err = -1; //First load the Data file MXADataModel::Pointer modelPtr = MXADataModel::New(); modelPtr->readModel(VTK_MXA_TEST_FILE, false); // We pass 'false' so the file will stay open hid_t fileId = modelPtr->getIODelegate()->getOpenFileId(); if (fileId < 0) { std::cout << logTime() << "Error: FileId was not valid."<< std::endl; return -1; } // We know that the data dimensions have ranges of 1->2 and 1->3, so lets get the data for the first index of each one. std::vector<int32_t> indices; indices.push_back(1); // Time step 1 indices.push_back(1); // Slice number // We also know the exact path to the Data Record, so lets use it to retrieve the Data Record from the Model MXADataRecord::Pointer record = modelPtr->getDataRecordByPath(DataGen::TableRec + "/" + DataGen::Uint8_tRec); if (NULL == record.get()) { std::cout << logTime() << "Error getting '2D Array' Data Record" << std::endl; return -1; } // Have the DataModel generate the proper internal path relative to the root level and extending to the dataset std::string datasetPath = modelPtr->generatePathToDataset(indices, record.get() ); vtkSmartPointer<vtkImageData> imgData = vtkSmartPointer<vtkImageData>::New(); err = vtkHDF5::getDataAsVTKImage(fileId, datasetPath, imgData); if (err < 0) { std::cout << logTime() << "Dataset was NULL " << std::endl; return -1; } vtkSmartPointer<vtkXMLImageDataWriter> bmpWriter = vtkSmartPointer<vtkXMLImageDataWriter>::New(); bmpWriter->SetFileName("/tmp/out.vti"); bmpWriter->SetInput(imgData); bmpWriter->Update(); return 1; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- int main(int argc, char **argv) { std::cout << logTime() << "----- Running vtkHDF5 Bridge Test ------------- " << std::endl; herr_t err = 1; // Generate a Data file to use std::string outputFile(VTK_MXA_TEST_FILE); DataFileGenerator dfg; dfg.setFilePath(outputFile); err = dfg.generate(); if (err < 0) { return EXIT_FAILURE; } test(); std::cout << logTime() << " vtkHDF5 Bridge Test Complete --------------" << std::endl; return EXIT_SUCCESS; }
31.490741
121
0.579535
[ "vector", "model" ]
0d792e486aec3d458847f057cefe9f0d539f96d4
18,664
cpp
C++
src/execution_tree/primitives/add_operation.cpp
rtohid/phylanx
c2e4e8e531c204a70b1907995b1fd467870e6d9d
[ "BSL-1.0" ]
null
null
null
src/execution_tree/primitives/add_operation.cpp
rtohid/phylanx
c2e4e8e531c204a70b1907995b1fd467870e6d9d
[ "BSL-1.0" ]
null
null
null
src/execution_tree/primitives/add_operation.cpp
rtohid/phylanx
c2e4e8e531c204a70b1907995b1fd467870e6d9d
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2017-2018 Hartmut Kaiser // // 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 <phylanx/config.hpp> #include <phylanx/execution_tree/primitives/add_operation.hpp> #include <phylanx/ir/node_data.hpp> #include <hpx/include/lcos.hpp> #include <hpx/include/naming.hpp> #include <hpx/include/util.hpp> #include <hpx/throw_exception.hpp> #include <cstddef> #include <cstdint> #include <memory> #include <numeric> #include <string> #include <utility> #include <vector> #include <blaze/Math.h> /////////////////////////////////////////////////////////////////////////////// namespace phylanx { namespace execution_tree { namespace primitives { namespace detail { struct add_simd { public: explicit add_simd(double scalar) : scalar_(scalar) { } template <typename T> BLAZE_ALWAYS_INLINE auto operator()(T const& a) const -> decltype(a + std::declval<double>()) { return a + scalar_; } template <typename T> static constexpr bool simdEnabled() { return blaze::HasSIMDAdd<T, double>::value; } template <typename T> BLAZE_ALWAYS_INLINE decltype(auto) load(T const& a) const { BLAZE_CONSTRAINT_MUST_BE_SIMD_PACK(T); return a + blaze::set(scalar_); } private: double scalar_; }; } /////////////////////////////////////////////////////////////////////////// primitive create_add_operation(hpx::id_type const& locality, std::vector<primitive_argument_type>&& operands, std::string const& name, std::string const& codename) { static std::string type("__add"); return create_primitive_component( locality, type, std::move(operands), name, codename); } match_pattern_type const add_operation::match_data = { hpx::util::make_tuple("__add", std::vector<std::string>{"_1 + __2", "__add(_1, __2)"}, &create_add_operation, &create_primitive<add_operation>) }; ////////////////////////////////////////////////////////////////////////// add_operation::add_operation( std::vector<primitive_argument_type> && operands, std::string const& name, std::string const& codename) : primitive_component_base(std::move(operands), name, codename) {} /////////////////////////////////////////////////////////////////////////// primitive_argument_type add_operation::add0d0d( arg_type&& lhs, arg_type&& rhs) const { lhs.scalar() += rhs.scalar(); return primitive_argument_type(std::move(lhs)); } primitive_argument_type add_operation::add0d0d(args_type && args) const { arg_type& lhs = args[0]; arg_type& rhs = args[1]; return primitive_argument_type{std::accumulate( args.begin() + 1, args.end(), std::move(lhs), [](arg_type& result, arg_type const& curr) -> arg_type { result.scalar() += curr.scalar(); return std::move(result); })}; } primitive_argument_type add_operation::add0d1d( arg_type&& lhs, arg_type&& rhs) const { if (rhs.is_ref()) { rhs = blaze::map(rhs.vector(), detail::add_simd(lhs.scalar())); } else { rhs.vector() = blaze::map(rhs.vector(), detail::add_simd(lhs.scalar())); } return primitive_argument_type(std::move(rhs)); } primitive_argument_type add_operation::add0d2d( arg_type&& lhs, arg_type&& rhs) const { if (rhs.is_ref()) { rhs = blaze::map(rhs.matrix(), detail::add_simd(lhs.scalar())); } else { rhs.matrix() = blaze::map( rhs.matrix(), detail::add_simd(lhs.scalar())); } return primitive_argument_type(std::move(rhs)); } primitive_argument_type add_operation::add0d( arg_type&& lhs, arg_type&& rhs) const { std::size_t rhs_dims = rhs.num_dimensions(); switch (rhs_dims) { case 0: return add0d0d(std::move(lhs), std::move(rhs)); case 1: return add0d1d(std::move(lhs), std::move(rhs)); case 2: return add0d2d(std::move(lhs), std::move(rhs)); default: HPX_THROW_EXCEPTION(hpx::bad_parameter, "add_operation::add0d", "the operands have incompatible number of dimensions"); } } primitive_argument_type add_operation::add0d(args_type && args) const { std::size_t rhs_dims = args[1].num_dimensions(); switch (rhs_dims) { case 0: return add0d0d(std::move(args)); default: HPX_THROW_EXCEPTION(hpx::bad_parameter, "add_operation::add0d", execution_tree::generate_error_message( "the operands have incompatible number of dimensions", name_, codename_)); } } /////////////////////////////////////////////////////////////////////////// primitive_argument_type add_operation::add1d0d( arg_type&& lhs, arg_type&& rhs) const { if (lhs.is_ref()) { lhs = blaze::map(lhs.vector(), detail::add_simd(rhs.scalar())); } else { lhs.vector() = blaze::map(lhs.vector(), detail::add_simd(rhs.scalar())); } return primitive_argument_type(std::move(lhs)); } primitive_argument_type add_operation::add1d1d( arg_type&& lhs, arg_type&& rhs) const { std::size_t lhs_size = lhs.dimension(0); std::size_t rhs_size = rhs.dimension(0); if (lhs_size != rhs_size) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "add_operation::add1d1d", execution_tree::generate_error_message( "the dimensions of the operands do not match", name_, codename_)); } if (lhs.is_ref()) { lhs = lhs.vector() + rhs.vector(); } else { lhs.vector() += rhs.vector(); } return primitive_argument_type(std::move(lhs)); } primitive_argument_type add_operation::add1d1d(args_type && args) const { arg_type& lhs = args[0]; arg_type& rhs = args[1]; std::size_t lhs_size = lhs.dimension(0); std::size_t rhs_size = rhs.dimension(0); if (lhs_size != rhs_size) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "add_operation::add1d1d", execution_tree::generate_error_message( "the dimensions of the operands do not match", name_, codename_)); } arg_type& first_term = *args.begin(); return primitive_argument_type(std::accumulate( args.begin() + 1, args.end(), std::move(first_term), [](arg_type& result, arg_type const& curr) -> arg_type { if (result.is_ref()) { result = result.vector() + curr.vector(); } else { result.vector() += curr.vector(); } return std::move(result); })); } primitive_argument_type add_operation::add1d2d( arg_type&& lhs, arg_type&& rhs) const { auto cv = lhs.vector(); auto cm = rhs.matrix(); if (cv.size() != cm.columns()) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "add_operation::add1d2d", execution_tree::generate_error_message( "vector size does not match number of matrix columns", name_, codename_)); } // TODO: Blaze does not support broadcasting if (rhs.is_ref()) { blaze::DynamicMatrix<double> m{cm.rows(), cm.columns()}; for (std::size_t i = 0; i != cm.rows(); ++i) { blaze::row(m, i) = blaze::row(cm, i) + blaze::trans(cv); } return primitive_argument_type{std::move(m)}; } for (std::size_t i = 0; i != cm.rows(); ++i) { blaze::row(cm, i) += blaze::trans(cv); } return primitive_argument_type{std::move(rhs)}; } primitive_argument_type add_operation::add1d( arg_type&& lhs, arg_type&& rhs) const { std::size_t rhs_dims = rhs.num_dimensions(); switch (rhs_dims) { case 0: return add1d0d(std::move(lhs), std::move(rhs)); case 1: return add1d1d(std::move(lhs), std::move(rhs)); case 2: return add1d2d(std::move(lhs), std::move(rhs)); default: HPX_THROW_EXCEPTION(hpx::bad_parameter, "add_operation::add1d", execution_tree::generate_error_message( "the operands have incompatible number of dimensions", name_, codename_)); } } primitive_argument_type add_operation::add1d(args_type && args) const { std::size_t rhs_dims = args[1].num_dimensions(); switch (rhs_dims) { case 1: return add1d1d(std::move(args)); default: HPX_THROW_EXCEPTION(hpx::bad_parameter, "add_operation::add1d", execution_tree::generate_error_message( "the operands have incompatible number of dimensions", name_, codename_)); } } /////////////////////////////////////////////////////////////////////////// primitive_argument_type add_operation::add2d0d( arg_type&& lhs, arg_type&& rhs) const { if (lhs.is_ref()) { lhs = blaze::map(lhs.matrix(), detail::add_simd(rhs.scalar())); } else { lhs.matrix() = blaze::map(lhs.matrix(), detail::add_simd(rhs.scalar())); } return primitive_argument_type(std::move(lhs)); } primitive_argument_type add_operation::add2d1d( arg_type&& lhs, arg_type&& rhs) const { auto cv = rhs.vector(); auto cm = lhs.matrix(); if (cv.size() != cm.columns()) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "add_operation::add2d1d", execution_tree::generate_error_message( "vector size does not match number of matrix columns", name_, codename_)); } // TODO: Blaze does not support broadcasting if (lhs.is_ref()) { blaze::DynamicMatrix<double> m{ cm.rows(), cm.columns() }; for (std::size_t i = 0; i != cm.rows(); ++i) { blaze::row(m, i) = blaze::row(cm, i) + blaze::trans(cv); } return primitive_argument_type{ std::move(m) }; } for (std::size_t i = 0; i != cm.rows(); ++i) { blaze::row(cm, i) += blaze::trans(cv); } return primitive_argument_type{std::move(lhs)}; } primitive_argument_type add_operation::add2d2d( arg_type&& lhs, arg_type&& rhs) const { auto lhs_size = lhs.dimensions(); auto rhs_size = rhs.dimensions(); if (lhs_size != rhs_size) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "add_operation::add2d2d", execution_tree::generate_error_message( "the dimensions of the operands do not match", name_, codename_)); } if (lhs.is_ref()) { lhs = lhs.matrix() + rhs.matrix(); } else { lhs.matrix() += rhs.matrix(); } return primitive_argument_type(std::move(lhs)); } primitive_argument_type add_operation::add2d2d(args_type && args) const { arg_type& lhs = args[0]; arg_type& rhs = args[1]; auto lhs_size = lhs.dimensions(); auto rhs_size = rhs.dimensions(); if (lhs_size != rhs_size) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "add_operation::add2d2d", execution_tree::generate_error_message( "the dimensions of the operands do not match", name_, codename_)); } arg_type& first_term = *args.begin(); return primitive_argument_type{std::accumulate( args.begin() + 1, args.end(), std::move(first_term), [](arg_type& result, arg_type const& curr) -> arg_type { if (result.is_ref()) { result = result.matrix() + curr.matrix(); } else { result.matrix() += curr.matrix(); } return std::move(result); })}; } primitive_argument_type add_operation::add2d( arg_type&& lhs, arg_type&& rhs) const { std::size_t rhs_dims = rhs.num_dimensions(); switch (rhs_dims) { case 0: return add2d0d(std::move(lhs), std::move(rhs)); case 2: return add2d2d(std::move(lhs), std::move(rhs)); case 1: return add2d1d(std::move(lhs), std::move(rhs)); default: HPX_THROW_EXCEPTION(hpx::bad_parameter, "add_operation::add2d", execution_tree::generate_error_message( "the operands have incompatible number of dimensions", name_, codename_)); } } primitive_argument_type add_operation::add2d(args_type && args) const { std::size_t rhs_dims = args[1].num_dimensions(); switch (rhs_dims) { case 2: return add2d2d(std::move(args)); default: HPX_THROW_EXCEPTION(hpx::bad_parameter, "add_operation::add2d", execution_tree::generate_error_message( "the operands have incompatible number of dimensions", name_, codename_)); } } hpx::future<primitive_argument_type> add_operation::eval( std::vector<primitive_argument_type> const& operands, std::vector<primitive_argument_type> const& args) const { if (operands.size() < 2) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "add_operation::eval", execution_tree::generate_error_message( "the add_operation primitive requires at least two " "operands", name_, codename_)); } bool arguments_valid = true; for (std::size_t i = 0; i != operands.size(); ++i) { if (!valid(operands[i])) { arguments_valid = false; } } if (!arguments_valid) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "add_operation::eval", execution_tree::generate_error_message( "the add_operation primitive requires that the " "arguments given by the operands array are valid", name_, codename_)); } auto this_ = this->shared_from_this(); if (operands.size() == 2) { // special case for 2 operands return hpx::dataflow(hpx::launch::sync, hpx::util::unwrapping( [this_](arg_type&& lhs, arg_type&& rhs) -> primitive_argument_type { std::size_t lhs_dims = lhs.num_dimensions(); switch (lhs_dims) { case 0: return this_->add0d(std::move(lhs), std::move(rhs)); case 1: return this_->add1d(std::move(lhs), std::move(rhs)); case 2: return this_->add2d(std::move(lhs), std::move(rhs)); default: HPX_THROW_EXCEPTION(hpx::bad_parameter, "add_operation::eval", execution_tree::generate_error_message( "left hand side operand has unsupported " "number of dimensions", this_->name_, this_->codename_)); } }), numeric_operand(operands[0], args, name_, codename_), numeric_operand(operands[1], args, name_, codename_)); } return hpx::dataflow(hpx::launch::sync, hpx::util::unwrapping( [this_](args_type&& args) -> primitive_argument_type { std::size_t lhs_dims = args[0].num_dimensions(); switch (lhs_dims) { case 0: return this_->add0d(std::move(args)); case 1: return this_->add1d(std::move(args)); case 2: return this_->add2d(std::move(args)); default: HPX_THROW_EXCEPTION(hpx::bad_parameter, "add_operation::eval", execution_tree::generate_error_message( "left hand side operand has unsupported " "number of dimensions", this_->name_, this_->codename_)); } }), detail::map_operands( operands, functional::numeric_operand{}, args, name_, codename_)); } // Implement '+' for all possible combinations of lhs and rhs hpx::future<primitive_argument_type> add_operation::eval( std::vector<primitive_argument_type> const& args) const { if (operands_.empty()) { return eval(args, noargs); } return eval(operands_, args); } }}}
31.633898
79
0.504126
[ "vector" ]
0d86b8439d7cd724d20c092d928a0230c0dae557
59,101
cc
C++
rambo_dict.cc
nkarast/MG5quadme
a9eb7346ff9248a3991981ef0206a696941f8a36
[ "MIT" ]
null
null
null
rambo_dict.cc
nkarast/MG5quadme
a9eb7346ff9248a3991981ef0206a696941f8a36
[ "MIT" ]
null
null
null
rambo_dict.cc
nkarast/MG5quadme
a9eb7346ff9248a3991981ef0206a696941f8a36
[ "MIT" ]
null
null
null
// // File generated by rootcint at Tue Apr 8 14:56:29 2014 // Do NOT change. Changes will be lost next time file is generated // #define R__DICTIONARY_FILENAME rambo_dict #include "RConfig.h" //rootcint 4834 #if !defined(R__ACCESS_IN_SYMBOL) //Break the privacy of classes -- Disabled for the moment #define private public #define protected public #endif // Since CINT ignores the std namespace, we need to do so in this file. namespace std {} using namespace std; #include "rambo_dict.h" #include "TCollectionProxyInfo.h" #include "TClass.h" #include "TBuffer.h" #include "TMemberInspector.h" #include "TError.h" #ifndef G__ROOT #define G__ROOT #endif #include "RtypesImp.h" #include "TIsAProxy.h" #include "TFileMergeInfo.h" // Direct notice to TROOT of the dictionary's loading. namespace { static struct DictInit { DictInit() { ROOT::RegisterModule(); } } __TheDictionaryInitializer; } // START OF SHADOWS namespace ROOT { namespace Shadow { } // of namespace Shadow } // of namespace ROOT // END OF SHADOWS namespace ROOT { void vectorlEdoublegR_ShowMembers(void *obj, TMemberInspector &R__insp); static void vectorlEdoublegR_Dictionary(); static void *new_vectorlEdoublegR(void *p = 0); static void *newArray_vectorlEdoublegR(Long_t size, void *p); static void delete_vectorlEdoublegR(void *p); static void deleteArray_vectorlEdoublegR(void *p); static void destruct_vectorlEdoublegR(void *p); // Function generating the singleton type initializer static TGenericClassInfo *GenerateInitInstanceLocal(const vector<double>*) { vector<double> *ptr = 0; static ::TVirtualIsAProxy* isa_proxy = new ::TIsAProxy(typeid(vector<double>),0); static ::ROOT::TGenericClassInfo instance("vector<double>", -2, "vector.dll", 0, typeid(vector<double>), DefineBehavior(ptr, ptr), 0, &vectorlEdoublegR_Dictionary, isa_proxy, 0, sizeof(vector<double>) ); instance.SetNew(&new_vectorlEdoublegR); instance.SetNewArray(&newArray_vectorlEdoublegR); instance.SetDelete(&delete_vectorlEdoublegR); instance.SetDeleteArray(&deleteArray_vectorlEdoublegR); instance.SetDestructor(&destruct_vectorlEdoublegR); instance.AdoptCollectionProxyInfo(TCollectionProxyInfo::Generate(TCollectionProxyInfo::Pushback< vector<double> >())); return &instance; } // Static variable to force the class initialization static ::ROOT::TGenericClassInfo *_R__UNIQUE_(Init) = GenerateInitInstanceLocal((const vector<double>*)0x0); R__UseDummy(_R__UNIQUE_(Init)); // Dictionary for non-ClassDef classes static void vectorlEdoublegR_Dictionary() { ::ROOT::GenerateInitInstanceLocal((const vector<double>*)0x0)->GetClass(); } } // end of namespace ROOT namespace ROOT { // Wrappers around operator new static void *new_vectorlEdoublegR(void *p) { return p ? ::new((::ROOT::TOperatorNewHelper*)p) vector<double> : new vector<double>; } static void *newArray_vectorlEdoublegR(Long_t nElements, void *p) { return p ? ::new((::ROOT::TOperatorNewHelper*)p) vector<double>[nElements] : new vector<double>[nElements]; } // Wrapper around operator delete static void delete_vectorlEdoublegR(void *p) { delete ((vector<double>*)p); } static void deleteArray_vectorlEdoublegR(void *p) { delete [] ((vector<double>*)p); } static void destruct_vectorlEdoublegR(void *p) { typedef vector<double> current_t; ((current_t*)p)->~current_t(); } } // end of namespace ROOT for class vector<double> namespace ROOT { void vectorlEvectorlEdoublegRsPgR_ShowMembers(void *obj, TMemberInspector &R__insp); static void vectorlEvectorlEdoublegRsPgR_Dictionary(); static void *new_vectorlEvectorlEdoublegRsPgR(void *p = 0); static void *newArray_vectorlEvectorlEdoublegRsPgR(Long_t size, void *p); static void delete_vectorlEvectorlEdoublegRsPgR(void *p); static void deleteArray_vectorlEvectorlEdoublegRsPgR(void *p); static void destruct_vectorlEvectorlEdoublegRsPgR(void *p); // Function generating the singleton type initializer static TGenericClassInfo *GenerateInitInstanceLocal(const vector<vector<double> >*) { vector<vector<double> > *ptr = 0; static ::TVirtualIsAProxy* isa_proxy = new ::TIsAProxy(typeid(vector<vector<double> >),0); static ::ROOT::TGenericClassInfo instance("vector<vector<double> >", -2, "prec_stl/vector", 49, typeid(vector<vector<double> >), DefineBehavior(ptr, ptr), 0, &vectorlEvectorlEdoublegRsPgR_Dictionary, isa_proxy, 0, sizeof(vector<vector<double> >) ); instance.SetNew(&new_vectorlEvectorlEdoublegRsPgR); instance.SetNewArray(&newArray_vectorlEvectorlEdoublegRsPgR); instance.SetDelete(&delete_vectorlEvectorlEdoublegRsPgR); instance.SetDeleteArray(&deleteArray_vectorlEvectorlEdoublegRsPgR); instance.SetDestructor(&destruct_vectorlEvectorlEdoublegRsPgR); instance.AdoptCollectionProxyInfo(TCollectionProxyInfo::Generate(TCollectionProxyInfo::Pushback< vector<vector<double> > >())); return &instance; } // Static variable to force the class initialization static ::ROOT::TGenericClassInfo *_R__UNIQUE_(Init) = GenerateInitInstanceLocal((const vector<vector<double> >*)0x0); R__UseDummy(_R__UNIQUE_(Init)); // Dictionary for non-ClassDef classes static void vectorlEvectorlEdoublegRsPgR_Dictionary() { ::ROOT::GenerateInitInstanceLocal((const vector<vector<double> >*)0x0)->GetClass(); } } // end of namespace ROOT namespace ROOT { // Wrappers around operator new static void *new_vectorlEvectorlEdoublegRsPgR(void *p) { return p ? ::new((::ROOT::TOperatorNewHelper*)p) vector<vector<double> > : new vector<vector<double> >; } static void *newArray_vectorlEvectorlEdoublegRsPgR(Long_t nElements, void *p) { return p ? ::new((::ROOT::TOperatorNewHelper*)p) vector<vector<double> >[nElements] : new vector<vector<double> >[nElements]; } // Wrapper around operator delete static void delete_vectorlEvectorlEdoublegRsPgR(void *p) { delete ((vector<vector<double> >*)p); } static void deleteArray_vectorlEvectorlEdoublegRsPgR(void *p) { delete [] ((vector<vector<double> >*)p); } static void destruct_vectorlEvectorlEdoublegRsPgR(void *p) { typedef vector<vector<double> > current_t; ((current_t*)p)->~current_t(); } } // end of namespace ROOT for class vector<vector<double> > /******************************************************** * rambo_dict.cc * CAUTION: DON'T CHANGE THIS FILE. THIS FILE IS AUTOMATICALLY GENERATED * FROM HEADER FILES LISTED IN G__setup_cpp_environmentXXX(). * CHANGE THOSE HEADER FILES AND REGENERATE THIS FILE. ********************************************************/ #ifdef G__MEMTEST #undef malloc #undef free #endif #if defined(__GNUC__) && __GNUC__ >= 4 && ((__GNUC_MINOR__ == 2 && __GNUC_PATCHLEVEL__ >= 1) || (__GNUC_MINOR__ >= 3)) #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif extern "C" void G__cpp_reset_tagtablerambo_dict(); extern "C" void G__set_cpp_environmentrambo_dict() { G__add_compiledheader("TObject.h"); G__add_compiledheader("TMemberInspector.h"); G__add_compiledheader("rambo.h"); G__cpp_reset_tagtablerambo_dict(); } #include <new> extern "C" int G__cpp_dllrevrambo_dict() { return(30051515); } /********************************************************* * Member function Interface Method *********************************************************/ /* vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > > */ static int G__rambo_dict_170_0_1(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { { const vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::reference obj = ((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->at((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type) G__int(libp->para[0])); result7->ref = (long) (&obj); result7->obj.i = (long) (&obj); } return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_2(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { { vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::const_reference obj = ((const vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->at((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type) G__int(libp->para[0])); result7->ref = (long) (&obj); result7->obj.i = (long) (&obj); } return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_3(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { { vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator* pobj; vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator xobj = ((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->begin(); pobj = new vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator(xobj); result7->obj.i = (long) ((void*) pobj); result7->ref = result7->obj.i; G__store_tempobject(*result7); } return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_4(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { { vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator* pobj; vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator xobj = ((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->end(); pobj = new vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator(xobj); result7->obj.i = (long) ((void*) pobj); result7->ref = result7->obj.i; G__store_tempobject(*result7); } return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_5(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { { vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::reverse_iterator* pobj; vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::reverse_iterator xobj = ((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->rbegin(); pobj = new vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::reverse_iterator(xobj); result7->obj.i = (long) ((void*) pobj); result7->ref = result7->obj.i; G__store_tempobject(*result7); } return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_6(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { { vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::reverse_iterator* pobj; vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::reverse_iterator xobj = ((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->rend(); pobj = new vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::reverse_iterator(xobj); result7->obj.i = (long) ((void*) pobj); result7->ref = result7->obj.i; G__store_tempobject(*result7); } return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_7(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { G__letint(result7, 107, (long) ((const vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->size()); return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_8(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { G__letint(result7, 107, (long) ((const vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->max_size()); return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_9(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { ((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->resize((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type) G__int(libp->para[0])); G__setnull(result7); return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_10(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { ((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->resize((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type) G__int(libp->para[0]), *((vector<double,allocator<double> >*) G__int(libp->para[1]))); G__setnull(result7); return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_11(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { G__letint(result7, 107, (long) ((const vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->capacity()); return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_12(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { G__letint(result7, 103, (long) ((const vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->empty()); return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_13(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { { const vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::reference obj = ((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->operator[]((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type) G__int(libp->para[0])); result7->ref = (long) (&obj); result7->obj.i = (long) (&obj); } return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_14(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { { vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::const_reference obj = ((const vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->operator[]((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type) G__int(libp->para[0])); result7->ref = (long) (&obj); result7->obj.i = (long) (&obj); } return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_15(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >* p = NULL; char* gvp = (char*) G__getgvp(); int n = G__getaryconstruct(); if (n) { if ((gvp == (char*)G__PVOID) || (gvp == 0)) { p = new vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >[n]; } else { p = new((void*) gvp) vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >[n]; } } else { if ((gvp == (char*)G__PVOID) || (gvp == 0)) { p = new vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >; } else { p = new((void*) gvp) vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >; } } result7->obj.i = (long) p; result7->ref = (long) p; G__set_tagnum(result7,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR)); return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_16(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >* p = NULL; char* gvp = (char*) G__getgvp(); switch (libp->paran) { case 2: //m: 2 if ((gvp == (char*)G__PVOID) || (gvp == 0)) { p = new vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type) G__int(libp->para[0]), *(vector<double,allocator<double> >*) libp->para[1].ref); } else { p = new((void*) gvp) vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type) G__int(libp->para[0]), *(vector<double,allocator<double> >*) libp->para[1].ref); } break; case 1: //m: 1 if ((gvp == (char*)G__PVOID) || (gvp == 0)) { p = new vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type) G__int(libp->para[0])); } else { p = new((void*) gvp) vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type) G__int(libp->para[0])); } break; } result7->obj.i = (long) p; result7->ref = (long) p; G__set_tagnum(result7,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR)); return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_17(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >* p = NULL; char* gvp = (char*) G__getgvp(); //m: 1 if ((gvp == (char*)G__PVOID) || (gvp == 0)) { p = new vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >(*(vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) libp->para[0].ref); } else { p = new((void*) gvp) vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >(*(vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) libp->para[0].ref); } result7->obj.i = (long) p; result7->ref = (long) p; G__set_tagnum(result7,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR)); return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_18(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >* p = NULL; char* gvp = (char*) G__getgvp(); //m: 2 if ((gvp == (char*)G__PVOID) || (gvp == 0)) { p = new vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >(*((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::const_iterator*) G__int(libp->para[0])), *((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::const_iterator*) G__int(libp->para[1]))); } else { p = new((void*) gvp) vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >(*((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::const_iterator*) G__int(libp->para[0])), *((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::const_iterator*) G__int(libp->para[1]))); } result7->obj.i = (long) p; result7->ref = (long) p; G__set_tagnum(result7,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR)); return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_19(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { { const vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >& obj = ((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->operator=(*(vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) libp->para[0].ref); result7->ref = (long) (&obj); result7->obj.i = (long) (&obj); } return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_20(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { ((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->reserve((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type) G__int(libp->para[0])); G__setnull(result7); return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_21(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { { const vector<double,allocator<double> >& obj = ((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->front(); result7->ref = (long) (&obj); result7->obj.i = (long) (&obj); } return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_22(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { { const vector<double,allocator<double> >& obj = ((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->back(); result7->ref = (long) (&obj); result7->obj.i = (long) (&obj); } return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_23(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { ((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->push_back(*(vector<double,allocator<double> >*) libp->para[0].ref); G__setnull(result7); return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_24(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { ((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->swap(*(vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) libp->para[0].ref); G__setnull(result7); return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_25(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { { vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator* pobj; vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator xobj = ((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->insert(*((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator*) G__int(libp->para[0])), *(vector<double,allocator<double> >*) libp->para[1].ref); pobj = new vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator(xobj); result7->obj.i = (long) ((void*) pobj); result7->ref = result7->obj.i; G__store_tempobject(*result7); } return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_26(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { ((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->insert(*((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator*) G__int(libp->para[0])), *((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::const_iterator*) G__int(libp->para[1])) , *((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::const_iterator*) G__int(libp->para[2]))); G__setnull(result7); return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_27(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { ((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->insert(*((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator*) G__int(libp->para[0])), (vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type) G__int(libp->para[1]) , *(vector<double,allocator<double> >*) libp->para[2].ref); G__setnull(result7); return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_28(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { ((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->pop_back(); G__setnull(result7); return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_29(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { ((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->erase(*((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator*) G__int(libp->para[0]))); G__setnull(result7); return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_30(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { ((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->erase(*((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator*) G__int(libp->para[0])), *((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator*) G__int(libp->para[1]))); G__setnull(result7); return(1 || funcname || hash || result7 || libp) ; } static int G__rambo_dict_170_0_31(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { ((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) G__getstructoffset())->clear(); G__setnull(result7); return(1 || funcname || hash || result7 || libp) ; } // automatic destructor typedef vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > > G__TvectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR; static int G__rambo_dict_170_0_32(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { char* gvp = (char*) G__getgvp(); long soff = G__getstructoffset(); int n = G__getaryconstruct(); // //has_a_delete: 0 //has_own_delete1arg: 0 //has_own_delete2arg: 0 // if (!soff) { return(1); } if (n) { if (gvp == (char*)G__PVOID) { delete[] (vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) soff; } else { G__setgvp((long) G__PVOID); for (int i = n - 1; i >= 0; --i) { ((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) (soff+(sizeof(vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >)*i)))->~G__TvectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR(); } G__setgvp((long)gvp); } } else { if (gvp == (char*)G__PVOID) { delete (vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) soff; } else { G__setgvp((long) G__PVOID); ((vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*) (soff))->~G__TvectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR(); G__setgvp((long)gvp); } } G__setnull(result7); return(1 || funcname || hash || result7 || libp) ; } /* Setting up global function */ static int G__rambo_dict__0_1366(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) { { vector<vector<double> >* pobj; vector<vector<double> > xobj = get_momenta((int) G__int(libp->para[0]), (double) G__double(libp->para[1]) , *((vector<double>*) G__int(libp->para[2])), (double*) G__int(libp->para[3])); pobj = new vector<vector<double> >(xobj); result7->obj.i = (long) ((void*) pobj); result7->ref = result7->obj.i; G__store_tempobject(*result7); } return(1 || funcname || hash || result7 || libp) ; } /********************************************************* * Member function Stub *********************************************************/ /* vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > > */ /********************************************************* * Global function Stub *********************************************************/ /********************************************************* * Get size of pointer to member function *********************************************************/ class G__Sizep2memfuncrambo_dict { public: G__Sizep2memfuncrambo_dict(): p(&G__Sizep2memfuncrambo_dict::sizep2memfunc) {} size_t sizep2memfunc() { return(sizeof(p)); } private: size_t (G__Sizep2memfuncrambo_dict::*p)(); }; size_t G__get_sizep2memfuncrambo_dict() { G__Sizep2memfuncrambo_dict a; G__setsizep2memfunc((int)a.sizep2memfunc()); return((size_t)a.sizep2memfunc()); } /********************************************************* * virtual base class offset calculation interface *********************************************************/ /* Setting up class inheritance */ /********************************************************* * Inheritance information setup/ *********************************************************/ extern "C" void G__cpp_setup_inheritancerambo_dict() { /* Setting up class inheritance */ } /********************************************************* * typedef information setup/ *********************************************************/ extern "C" void G__cpp_setup_typetablerambo_dict() { /* Setting up typedef entry */ G__search_typename2("vector<ROOT::TSchemaHelper>",117,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgR),0,-1); G__setnewtype(-1,NULL,0); G__search_typename2("reverse_iterator<const_iterator>",117,G__get_linked_tagnum(&G__rambo_dictLN_reverse_iteratorlEvectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgRcLcLiteratorgR),0,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgR)); G__setnewtype(-1,NULL,0); G__search_typename2("reverse_iterator<iterator>",117,G__get_linked_tagnum(&G__rambo_dictLN_reverse_iteratorlEvectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgRcLcLiteratorgR),0,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgR)); G__setnewtype(-1,NULL,0); G__search_typename2("vector<TVirtualArray*>",117,G__get_linked_tagnum(&G__rambo_dictLN_vectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgR),0,-1); G__setnewtype(-1,NULL,0); G__search_typename2("reverse_iterator<const_iterator>",117,G__get_linked_tagnum(&G__rambo_dictLN_reverse_iteratorlEvectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgRcLcLiteratorgR),0,G__get_linked_tagnum(&G__rambo_dictLN_vectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgR)); G__setnewtype(-1,NULL,0); G__search_typename2("reverse_iterator<iterator>",117,G__get_linked_tagnum(&G__rambo_dictLN_reverse_iteratorlEvectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgRcLcLiteratorgR),0,G__get_linked_tagnum(&G__rambo_dictLN_vectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgR)); G__setnewtype(-1,NULL,0); G__search_typename2("vector<vector<double> >",117,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR),0,-1); G__setnewtype(-1,NULL,0); G__search_typename2("value_type",117,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEdoublecOallocatorlEdoublegRsPgR),0,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR)); G__setnewtype(-1,NULL,0); G__search_typename2("pointer",85,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEdoublecOallocatorlEdoublegRsPgR),0,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR)); G__setnewtype(-1,NULL,0); G__search_typename2("const_pointer",85,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEdoublecOallocatorlEdoublegRsPgR),256,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR)); G__setnewtype(-1,NULL,0); G__search_typename2("reference",117,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEdoublecOallocatorlEdoublegRsPgR),1,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR)); G__setnewtype(-1,NULL,0); G__search_typename2("const_reference",117,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEdoublecOallocatorlEdoublegRsPgR),257,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR)); G__setnewtype(-1,NULL,0); G__search_typename2("size_type",107,-1,0,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR)); G__setnewtype(-1,NULL,0); G__search_typename2("difference_type",108,-1,0,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR)); G__setnewtype(-1,NULL,0); G__search_typename2("const_iterator",117,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgRcLcLiterator),256,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR)); G__setnewtype(-1,NULL,0); G__search_typename2("reverse_iterator<const_iterator>",117,G__get_linked_tagnum(&G__rambo_dictLN_reverse_iteratorlEvectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgRcLcLiteratorgR),0,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR)); G__setnewtype(-1,NULL,0); G__search_typename2("const_reverse_iterator",117,G__get_linked_tagnum(&G__rambo_dictLN_reverse_iteratorlEvectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgRcLcLiteratorgR),0,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR)); G__setnewtype(-1,NULL,0); G__search_typename2("reverse_iterator<iterator>",117,G__get_linked_tagnum(&G__rambo_dictLN_reverse_iteratorlEvectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgRcLcLiteratorgR),0,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR)); G__setnewtype(-1,NULL,0); G__search_typename2("reverse_iterator",117,G__get_linked_tagnum(&G__rambo_dictLN_reverse_iteratorlEvectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgRcLcLiteratorgR),0,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR)); G__setnewtype(-1,NULL,0); G__search_typename2("vector<vector<double,allocator<double> > >",117,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR),0,-1); G__setnewtype(-1,NULL,0); G__search_typename2("vector<std::vector<double> >",117,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR),0,-1); G__setnewtype(-1,NULL,0); G__search_typename2("vector<vector<double> >",117,G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR),0,-1); G__setnewtype(-1,NULL,0); } /********************************************************* * Data Member information setup/ *********************************************************/ /* Setting up class,struct,union tag member variable */ /* vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > > */ static void G__setup_memvarvectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR(void) { G__tag_memvar_setup(G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR)); { vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > > *p; p=(vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >*)0x1000; if (p) { } } G__tag_memvar_reset(); } extern "C" void G__cpp_setup_memvarrambo_dict() { } /*********************************************************** ************************************************************ ************************************************************ ************************************************************ ************************************************************ ************************************************************ ************************************************************ ***********************************************************/ /********************************************************* * Member function information setup for each class *********************************************************/ static void G__setup_memfuncvectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR(void) { /* vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > > */ G__tag_memfunc_setup(G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR)); G__memfunc_setup("at",213,G__rambo_dict_170_0_1, 117, G__get_linked_tagnum(&G__rambo_dictLN_vectorlEdoublecOallocatorlEdoublegRsPgR), G__defined_typename("vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::reference"), 1, 1, 1, 1, 0, "k - 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type' 0 - n", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("at",213,G__rambo_dict_170_0_2, 117, G__get_linked_tagnum(&G__rambo_dictLN_vectorlEdoublecOallocatorlEdoublegRsPgR), G__defined_typename("vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::const_reference"), 1, 1, 1, 1, 8, "k - 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type' 0 - n", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("begin",517,G__rambo_dict_170_0_3, 117, G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgRcLcLiterator), -1, 0, 0, 1, 1, 0, "", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("end",311,G__rambo_dict_170_0_4, 117, G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgRcLcLiterator), -1, 0, 0, 1, 1, 0, "", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("rbegin",631,G__rambo_dict_170_0_5, 117, G__get_linked_tagnum(&G__rambo_dictLN_reverse_iteratorlEvectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgRcLcLiteratorgR), G__defined_typename("vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::reverse_iterator"), 0, 0, 1, 1, 0, "", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("rend",425,G__rambo_dict_170_0_6, 117, G__get_linked_tagnum(&G__rambo_dictLN_reverse_iteratorlEvectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgRcLcLiteratorgR), G__defined_typename("vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::reverse_iterator"), 0, 0, 1, 1, 0, "", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("size",443,G__rambo_dict_170_0_7, 107, -1, G__defined_typename("vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type"), 0, 0, 1, 1, 8, "", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("max_size",864,G__rambo_dict_170_0_8, 107, -1, G__defined_typename("vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type"), 0, 0, 1, 1, 8, "", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("resize",658,G__rambo_dict_170_0_9, 121, -1, -1, 0, 1, 1, 1, 0, "k - 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type' 0 - sz", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("resize",658,G__rambo_dict_170_0_10, 121, -1, -1, 0, 2, 1, 1, 0, "k - 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type' 0 - sz u 'vector<double,allocator<double> >' - 0 - c", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("capacity",846,G__rambo_dict_170_0_11, 107, -1, G__defined_typename("vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type"), 0, 0, 1, 1, 8, "", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("empty",559,G__rambo_dict_170_0_12, 103, -1, -1, 0, 0, 1, 1, 8, "", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("operator[]",1060,G__rambo_dict_170_0_13, 117, G__get_linked_tagnum(&G__rambo_dictLN_vectorlEdoublecOallocatorlEdoublegRsPgR), G__defined_typename("vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::reference"), 1, 1, 1, 1, 0, "k - 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type' 0 - n", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("operator[]",1060,G__rambo_dict_170_0_14, 117, G__get_linked_tagnum(&G__rambo_dictLN_vectorlEdoublecOallocatorlEdoublegRsPgR), G__defined_typename("vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::const_reference"), 1, 1, 1, 1, 8, "k - 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type' 0 - n", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >",8392,G__rambo_dict_170_0_15, 105, G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR), -1, 0, 0, 1, 1, 0, "", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >",8392,G__rambo_dict_170_0_16, 105, G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR), -1, 0, 2, 1, 1, 0, "k - 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type' 0 - n u 'vector<double,allocator<double> >' - 11 '(vector<double,allocator<double> >)()' value", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >",8392,G__rambo_dict_170_0_17, 105, G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR), -1, 0, 1, 1, 1, 0, "u 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >' - 11 - x", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >",8392,G__rambo_dict_170_0_18, 105, G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR), -1, 0, 2, 1, 1, 0, "u 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator' 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::const_iterator' 10 - first u 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator' 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::const_iterator' 10 - last", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("operator=",937,G__rambo_dict_170_0_19, 117, G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR), -1, 1, 1, 1, 1, 0, "u 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >' - 11 - x", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("reserve",764,G__rambo_dict_170_0_20, 121, -1, -1, 0, 1, 1, 1, 0, "k - 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type' 0 - n", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("front",553,G__rambo_dict_170_0_21, 117, G__get_linked_tagnum(&G__rambo_dictLN_vectorlEdoublecOallocatorlEdoublegRsPgR), -1, 1, 0, 1, 1, 0, "", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("back",401,G__rambo_dict_170_0_22, 117, G__get_linked_tagnum(&G__rambo_dictLN_vectorlEdoublecOallocatorlEdoublegRsPgR), -1, 1, 0, 1, 1, 0, "", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("push_back",944,G__rambo_dict_170_0_23, 121, -1, -1, 0, 1, 1, 1, 0, "u 'vector<double,allocator<double> >' - 11 - x", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("swap",443,G__rambo_dict_170_0_24, 121, -1, -1, 0, 1, 1, 1, 0, "u 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >' - 1 - x", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("insert",661,G__rambo_dict_170_0_25, 117, G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgRcLcLiterator), -1, 0, 2, 1, 1, 0, "u 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator' - 0 - position u 'vector<double,allocator<double> >' - 11 - x", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("insert",661,G__rambo_dict_170_0_26, 121, -1, -1, 0, 3, 1, 1, 0, "u 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator' - 0 - position u 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator' 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::const_iterator' 10 - first " "u 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator' 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::const_iterator' 10 - last", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("insert",661,G__rambo_dict_170_0_27, 121, -1, -1, 0, 3, 1, 1, 0, "u 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator' - 0 - position k - 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::size_type' 0 - n " "u 'vector<double,allocator<double> >' - 11 - x", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("pop_back",831,G__rambo_dict_170_0_28, 121, -1, -1, 0, 0, 1, 1, 0, "", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("erase",528,G__rambo_dict_170_0_29, 121, -1, -1, 0, 1, 1, 1, 0, "u 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator' - 0 - position", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("erase",528,G__rambo_dict_170_0_30, 121, -1, -1, 0, 2, 1, 1, 0, "u 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator' - 0 - first u 'vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator' - 0 - last", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("clear",519,G__rambo_dict_170_0_31, 121, -1, -1, 0, 0, 1, 1, 0, "", (char*)NULL, (void*) NULL, 0); // automatic destructor G__memfunc_setup("~vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >", 8518, G__rambo_dict_170_0_32, (int) ('y'), -1, -1, 0, 0, 1, 1, 0, "", (char*) NULL, (void*) NULL, 0); G__tag_memfunc_reset(); } /********************************************************* * Member function information setup *********************************************************/ extern "C" void G__cpp_setup_memfuncrambo_dict() { } /********************************************************* * Global variable information setup for each class *********************************************************/ static void G__cpp_setup_global0() { /* Setting up global variables */ G__resetplocal(); } static void G__cpp_setup_global1() { G__resetglobalenv(); } extern "C" void G__cpp_setup_globalrambo_dict() { G__cpp_setup_global0(); G__cpp_setup_global1(); } /********************************************************* * Global function information setup for each class *********************************************************/ static void G__cpp_setup_func0() { G__lastifuncposition(); } static void G__cpp_setup_func1() { } static void G__cpp_setup_func2() { } static void G__cpp_setup_func3() { } static void G__cpp_setup_func4() { } static void G__cpp_setup_func5() { } static void G__cpp_setup_func6() { } static void G__cpp_setup_func7() { } static void G__cpp_setup_func8() { } static void G__cpp_setup_func9() { } static void G__cpp_setup_func10() { } static void G__cpp_setup_func11() { } static void G__cpp_setup_func12() { } static void G__cpp_setup_func13() { G__memfunc_setup("get_momenta", 1168, G__rambo_dict__0_1366, 117, G__get_linked_tagnum(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR), G__defined_typename("vector<vector<double> >"), 0, 4, 1, 1, 0, "i - - 0 - ninitial d - - 0 - energy " "u 'vector<double,allocator<double> >' 'vector<double>' 0 - masses D - - 0 - wgt", (char*) NULL , (void*) NULL, 0); G__resetifuncposition(); } extern "C" void G__cpp_setup_funcrambo_dict() { G__cpp_setup_func0(); G__cpp_setup_func1(); G__cpp_setup_func2(); G__cpp_setup_func3(); G__cpp_setup_func4(); G__cpp_setup_func5(); G__cpp_setup_func6(); G__cpp_setup_func7(); G__cpp_setup_func8(); G__cpp_setup_func9(); G__cpp_setup_func10(); G__cpp_setup_func11(); G__cpp_setup_func12(); G__cpp_setup_func13(); } /********************************************************* * Class,struct,union,enum tag information setup *********************************************************/ /* Setup class/struct taginfo */ G__linked_taginfo G__rambo_dictLN_vectorlEdoublecOallocatorlEdoublegRsPgR = { "vector<double,allocator<double> >" , 99 , -1 }; G__linked_taginfo G__rambo_dictLN_vectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgR = { "vector<ROOT::TSchemaHelper,allocator<ROOT::TSchemaHelper> >" , 99 , -1 }; G__linked_taginfo G__rambo_dictLN_reverse_iteratorlEvectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgRcLcLiteratorgR = { "reverse_iterator<vector<ROOT::TSchemaHelper,allocator<ROOT::TSchemaHelper> >::iterator>" , 99 , -1 }; G__linked_taginfo G__rambo_dictLN_vectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgR = { "vector<TVirtualArray*,allocator<TVirtualArray*> >" , 99 , -1 }; G__linked_taginfo G__rambo_dictLN_reverse_iteratorlEvectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgRcLcLiteratorgR = { "reverse_iterator<vector<TVirtualArray*,allocator<TVirtualArray*> >::iterator>" , 99 , -1 }; G__linked_taginfo G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR = { "vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >" , 99 , -1 }; G__linked_taginfo G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgRcLcLiterator = { "vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator" , 99 , -1 }; G__linked_taginfo G__rambo_dictLN_reverse_iteratorlEvectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgRcLcLiteratorgR = { "reverse_iterator<vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >::iterator>" , 99 , -1 }; /* Reset class/struct taginfo */ extern "C" void G__cpp_reset_tagtablerambo_dict() { G__rambo_dictLN_vectorlEdoublecOallocatorlEdoublegRsPgR.tagnum = -1 ; G__rambo_dictLN_vectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgR.tagnum = -1 ; G__rambo_dictLN_reverse_iteratorlEvectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgRcLcLiteratorgR.tagnum = -1 ; G__rambo_dictLN_vectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgR.tagnum = -1 ; G__rambo_dictLN_reverse_iteratorlEvectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgRcLcLiteratorgR.tagnum = -1 ; G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR.tagnum = -1 ; G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgRcLcLiterator.tagnum = -1 ; G__rambo_dictLN_reverse_iteratorlEvectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgRcLcLiteratorgR.tagnum = -1 ; } extern "C" void G__cpp_setup_tagtablerambo_dict() { /* Setting up class,struct,union tag entry */ G__get_linked_tagnum_fwd(&G__rambo_dictLN_vectorlEdoublecOallocatorlEdoublegRsPgR); G__get_linked_tagnum_fwd(&G__rambo_dictLN_vectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgR); G__get_linked_tagnum_fwd(&G__rambo_dictLN_reverse_iteratorlEvectorlEROOTcLcLTSchemaHelpercOallocatorlEROOTcLcLTSchemaHelpergRsPgRcLcLiteratorgR); G__get_linked_tagnum_fwd(&G__rambo_dictLN_vectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgR); G__get_linked_tagnum_fwd(&G__rambo_dictLN_reverse_iteratorlEvectorlETVirtualArraymUcOallocatorlETVirtualArraymUgRsPgRcLcLiteratorgR); G__tagtable_setup(G__get_linked_tagnum_fwd(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR),sizeof(vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >),-1,36608,(char*)NULL,G__setup_memvarvectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR,G__setup_memfuncvectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgR); G__get_linked_tagnum_fwd(&G__rambo_dictLN_vectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgRcLcLiterator); G__get_linked_tagnum_fwd(&G__rambo_dictLN_reverse_iteratorlEvectorlEvectorlEdoublecOallocatorlEdoublegRsPgRcOallocatorlEvectorlEdoublecOallocatorlEdoublegRsPgRsPgRsPgRcLcLiteratorgR); } extern "C" void G__cpp_setuprambo_dict(void) { G__check_setup_version(30051515,"G__cpp_setuprambo_dict()"); G__set_cpp_environmentrambo_dict(); G__cpp_setup_tagtablerambo_dict(); G__cpp_setup_inheritancerambo_dict(); G__cpp_setup_typetablerambo_dict(); G__cpp_setup_memvarrambo_dict(); G__cpp_setup_memfuncrambo_dict(); G__cpp_setup_globalrambo_dict(); G__cpp_setup_funcrambo_dict(); if(0==G__getsizep2memfunc()) G__get_sizep2memfuncrambo_dict(); return; } class G__cpp_setup_initrambo_dict { public: G__cpp_setup_initrambo_dict() { G__add_setup_func("rambo_dict",(G__incsetup)(&G__cpp_setuprambo_dict)); G__call_setup_funcs(); } ~G__cpp_setup_initrambo_dict() { G__remove_setup_func("rambo_dict"); } }; G__cpp_setup_initrambo_dict G__cpp_setup_initializerrambo_dict;
65.304972
538
0.723676
[ "vector" ]
0d992935b4488a16631a859927c6727def03342a
638
cpp
C++
October LeetCode Challenge/Day_11.cpp
mishrraG/100DaysOfCode
3358af290d4f05889917808d68b95f37bd76e698
[ "MIT" ]
13
2020-08-10T14:06:37.000Z
2020-09-24T14:21:33.000Z
October LeetCode Challenge/Day_11.cpp
mishrraG/DaysOfCP
3358af290d4f05889917808d68b95f37bd76e698
[ "MIT" ]
null
null
null
October LeetCode Challenge/Day_11.cpp
mishrraG/DaysOfCP
3358af290d4f05889917808d68b95f37bd76e698
[ "MIT" ]
1
2020-05-31T21:09:14.000Z
2020-05-31T21:09:14.000Z
class Solution { public: string removeDuplicateLetters(string s) { string res = ""; vector<bool> visited(26, false); vector<int> dict(26, 0); for (auto it : s) dict[it - 'a'] ++; for (int i = 0; i < s.length(); i++) { dict[s[i] - 'a'] --; if (visited[s[i] - 'a']) continue; while ( res.size() and res.back() > s[i] and dict[res.back() - 'a'] ) { visited[res.back() - 'a'] = false; res.pop_back(); } res += s[i]; visited[s[i] - 'a'] = true; } return res; } };
30.380952
83
0.410658
[ "vector" ]
0d9b24f0b9d99874a4586f30a82c715627b422e3
764
cpp
C++
leetcode_solutions/curated_top_100/dynamic_programming/s_55_Jump_Game_20201110.cpp
lovms/code_snippets
243d751cb2b3725e20dca1adb5b5563b64a3eed0
[ "MIT" ]
null
null
null
leetcode_solutions/curated_top_100/dynamic_programming/s_55_Jump_Game_20201110.cpp
lovms/code_snippets
243d751cb2b3725e20dca1adb5b5563b64a3eed0
[ "MIT" ]
null
null
null
leetcode_solutions/curated_top_100/dynamic_programming/s_55_Jump_Game_20201110.cpp
lovms/code_snippets
243d751cb2b3725e20dca1adb5b5563b64a3eed0
[ "MIT" ]
null
null
null
//Given an array of non-negative integers, you are initially positioned at the first index of the array. // //Each element in the array represents your maximum jump length at that position. // //Determine if you are able to reach the last index. // // // //Example 1: // //Input: nums = [2,3,1,1,4] //Output: true //Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. //Example 2: // //Input: nums = [3,2,1,0,4] //Output: false //Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. // // //Constraints: // //1 <= nums.length <= 3 * 10^4 //0 <= nums[i][j] <= 10^5 class Solution { public: bool canJump(vector<int>& nums) { } };
23.151515
145
0.659686
[ "vector" ]
0d9bc4ed14d37e64dbc00f04d32b52700cada8b3
2,880
cc
C++
Codeforces/338 Division 2/Problem C/C.cc
VastoLorde95/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
170
2017-07-25T14:47:29.000Z
2022-01-26T19:16:31.000Z
Codeforces/338 Division 2/Problem C/C.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
null
null
null
Codeforces/338 Division 2/Problem C/C.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
55
2017-07-28T06:17:33.000Z
2021-10-31T03:06:22.000Z
#include <bits/stdc++.h> #define sd(x) scanf("%d",&x) #define sd2(x,y) scanf("%d%d",&x,&y) #define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z) #define fi first #define se second #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define LET(x, a) __typeof(a) x(a) #define foreach(it, v) for(LET(it, v.begin()); it != v.end(); it++) #define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #define __ freopen("input.txt","r",stdin);freopen("output.txt","w",stdout); #define meta __FUNCTION__<<' '<<__LINE__<<' ' #define tr(x) cout<<meta<<#x<<' '<<x<<'\n'; #define tr2(x,y) cout<<meta<<#x<<' '<<x<<' '<<#y<<' '<<y<<'\n'; #define tr3(x,y,z) cout<<meta<<#x<<' '<<x<<' '<<#y<<' '<<y<<' '<<#z<<' '<<z<<'\n'; #define tr4(w,x,y,z) cout<<meta<<#w<<' '<<w<<' '<<#x<<' ' <<x<<' '<<#y<<' '<<y<<' '<<#z<<' '<<z<<'\n'; #define tr5(v,w,x,y,z) cout<<meta<<#v<<' '<<v<<' '<<#w<<' '<<w<<' '<<#x<<' '<<x<<' '<<#y<<' '<<y<<' '<<#z<<' '<<z<<'\n'; #define tr6(u,v,w,x,y,z) cout<<meta<<#u<<' '<<u<<' '<<#v<<' '<<v<<' '<<#w<<' '<<w<<' '<<#x<<' '<<x<<' '<<#y<<' '<<y<<' '<<#z<<' '<<z<<'\n'; using namespace std; template<typename S, typename T> ostream& operator<<(ostream& out, pair<S, T> const& p){out<<'('<<p.first<<", "<<p.second<<')'; return out;} template<typename T> ostream& operator<<(ostream& out, vector<T> const & v){ int l = v.size(); for(int i = 0; i < l-1; i++) out<<v[i]<<' '; if(l>0) out<<v[l-1]; return out;} void build_f(string s, int f[]){ f[0] = f[1] = 0; int l1 = s.length(); for(int i = 2; i <= l1; i++){ int j = f[i-1]; while(true){ if(s[j] == s[i-1]){ f[i] = j+1; break; // match found, next char to match is j+1 } else if(j == 0){ f[i] = 0; break; // no match found } j = f[j]; // try next prefix/suffix } } return; } pair<int,int> match(string &s, string &t, int f[]){ int l1 = s.length(), l2 = t.length(); int mx = 0; pair<int,int> ret = mp(-1,-1); for(int i = 0, j = 0; j < l2;){ if(t[j] == s[i]){ j++, i++; if(i == l1){ return mp(j-l1+1, j); } if(i > mx){ mx = i; ret = mp(j-i+1, j); } } else if(i > 0) i = f[i]; else j++; } return ret; } const int N = 2200; int f[N]; string s, r, t; vector<pair<int,int> > ans; int main(){ _ cin >> s >> t; r = s; reverse(r.begin(), r.end()); int l = t.length(), k = s.length(); for(int i = 0; i < l; i++){ string x = t.substr(i, l-i); build_f(x, f); pair<int,int> p1 = match(x,s,f); pair<int,int> p2 = match(x,r,f); if(p1.fi == -1 and p2.fi == -1){ puts("-1"); return 0; } // tr3(p1,p2,k); if(p1.se - p1.fi > p2.se - p2.fi){ ans.pb(p1); i += p1.se - p1.fi; } else{ p2.fi = k - p2.fi + 1, p2.se = k - p2.se + 1; ans.pb(p2); i += p2.fi - p2.se; } } printf("%d\n", (int) ans.size()); foreach(it, ans){ printf("%d %d\n", it->fi, it->se); } return 0; }
23.606557
139
0.478472
[ "vector" ]
3107d31f45257e6f13338e3018fd61d60d11bae6
1,588
cpp
C++
C++/wordBreakII.cpp
black-shadows/LeetCode-Solutions
b1692583f7b710943ffb19b392b8bf64845b5d7a
[ "Fair", "Unlicense" ]
1
2020-04-16T08:38:14.000Z
2020-04-16T08:38:14.000Z
wordBreakII.cpp
Jeevan-kumar-Raj/LeetCode-Solutions-Topicwise
f1111b4edd401a3fc47111993bd7250cf4dc76da
[ "MIT" ]
null
null
null
wordBreakII.cpp
Jeevan-kumar-Raj/LeetCode-Solutions-Topicwise
f1111b4edd401a3fc47111993bd7250cf4dc76da
[ "MIT" ]
1
2021-12-25T14:48:56.000Z
2021-12-25T14:48:56.000Z
// Time Complexity: O(n^2) ? // Space Complexity: O(n^2) class Solution { public: vector<string> wordBreak(string s, unordered_set<string> &dict) { vector<bool> f(s.length() + 1, false); vector<vector<bool> > valid(s.length(), vector<bool>(s.length() + 1, false)); f[0] = true; // null string for(int i = 1; i <= s.length(); ++i) { for(int j = i - 1; j >= 0; --j) { if(f[j] && dict.find(s.substr(j, i - j)) != dict.end()) { f[i] = true; valid[j][i] = true; // [j, i) is a word } } } vector<string> path; vector<string> ans; gen_path(s, valid, s.length(), path, ans); return ans; } private: // dfs void gen_path(const string &s, vector<vector<bool> > &valid, int len, vector<string> &path, vector<string> &ans) { if(len == 0) { string tmp; for(auto it = path.rbegin(); it != path.rend(); ++it) { tmp += *it + " "; } tmp.pop_back(); // remove last " " ans.push_back(tmp); } for(int i = 0; i < len; ++i) { if(valid[i][len]) { path.push_back(s.substr(i, len - i)); gen_path(s, valid, i, path, ans); path.pop_back(); } } } };
33.787234
123
0.384131
[ "vector" ]
3107f926ce600ed3b04ae63be9b3a9aac6740f30
1,583
cpp
C++
design-phone-directory/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
design-phone-directory/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
design-phone-directory/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
class PhoneDirectory { protected: vector<int> m_list; vector<bool> m_taken; int m_top; int m_maxNumbers; public: /** Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory. */ PhoneDirectory(int maxNumbers) { m_maxNumbers = maxNumbers; m_list = vector<int>(maxNumbers, 0); m_taken = vector<bool>(maxNumbers, false); m_top = m_maxNumbers - 1; for (int i = 0; i < maxNumbers; ++i) { m_list[i] = i; } } /** Provide a number which is not assigned to anyone. @return - Return an available number. Return -1 if none is available. */ int get() { if (m_top == -1) { return -1; } m_taken[m_list[m_top]] = true; return m_list[m_top--]; } /** Check if a number is available or not. */ bool check(int number) { if (number < 0 && number >= m_maxNumbers) { return false; } return !m_taken[number]; } /** Recycle or release a number. */ void release(int number) { if (number < 0 && number >= m_maxNumbers) { return; } if (m_taken[number]) { m_taken[number] = false; m_list[++m_top] = number; } } }; /** * Your PhoneDirectory object will be instantiated and called as such: * PhoneDirectory obj = new PhoneDirectory(maxNumbers); * int param_1 = obj.get(); * bool param_2 = obj.check(number); * obj.release(number); */
27.77193
93
0.556538
[ "object", "vector" ]
310aa124dfc6360ecd1bbe1136517b11d48cabdf
11,317
cpp
C++
IO/vdb/vdb.cpp
chenjiunfeng/openMaelstrom
6dc6ffe3501f056eb83d1d6306d2ac5ec754c192
[ "MIT" ]
45
2019-11-07T13:51:50.000Z
2022-02-11T01:51:14.000Z
IO/vdb/vdb.cpp
chenjiunfeng/openMaelstrom
6dc6ffe3501f056eb83d1d6306d2ac5ec754c192
[ "MIT" ]
2
2020-03-06T20:25:02.000Z
2021-02-07T21:45:39.000Z
IO/vdb/vdb.cpp
chenjiunfeng/openMaelstrom
6dc6ffe3501f056eb83d1d6306d2ac5ec754c192
[ "MIT" ]
10
2019-08-22T09:11:23.000Z
2022-02-07T07:04:55.000Z
//#define NO_OPERATORS #define BOOST_USE_WINDOWS_H #include <IO/vdb/vdb.h> #include <iostream> #include <utility/identifier.h> #include <cuda.h> #include <cuda_runtime.h> #include <fstream> #include <utility/generation.h> #include <utility/bullet/DynamicsWorld.h> void IO::vdb::emitParticleVolumes() { //emit fluid volumes for (auto fluidVolume : get<parameters::particleVolumes>()) { auto r = get<parameters::radius>(); auto volume = PI4O3 * math::power<3>(r); auto out_points = generation::generateParticles(fluidVolume.fileName.value, r, genTechnique::hex_grid); auto inserted_particles = (int32_t) out_points.size(); int32_t old_ptcls = get<parameters::num_ptcls>(); if (old_ptcls + inserted_particles > get<parameters::max_numptcls>()) { std::cerr << "Not enough memory to insert particles." << std::endl; continue; } get<parameters::num_ptcls>() += inserted_particles; #ifdef UNIFIED_MEMORY for (int32_t i = old_ptcls; i < old_ptcls + inserted_particles; ++i) { openvdb::Vec4f ptcl_position = out_points[i - old_ptcls]; get<arrays::position>()[i] = float4{ptcl_position.x(), ptcl_position.y(), ptcl_position.z(), ptcl_position.w()}; get<arrays::velocity>()[i] = float4{0.f, 0.f, 0.f, 0.f}; get<arrays::volume>()[i] = volume; } #else std::vector<float4> positions; std::vector<float4> velocities; std::vector<float> volumes; std::vector<int> particle_type; std::vector<int> particle_type_x; bool first = false; for (int32_t i = old_ptcls; i < old_ptcls + inserted_particles; ++i) { openvdb::Vec4f ptcl_position = out_points[i - old_ptcls]; positions.push_back(float4{ ptcl_position.x(), ptcl_position.y(), ptcl_position.z()+(first ? 20 : 0), ptcl_position.w() }); velocities.push_back(float4{ 0.f, 0.f, 0.f, 0.f }); volumes.push_back(volume); particle_type.push_back(FLUID_PARTICLE); // particle_type_x.push_back(FLUID_PARTICLE); particle_type_x.push_back(first ? 1 : FLUID_PARTICLE); first = false; } cudaMemcpy(arrays::position::ptr + old_ptcls, positions.data(), inserted_particles * sizeof(float4), cudaMemcpyHostToDevice); cudaMemcpy(arrays::velocity::ptr + old_ptcls, velocities.data(), inserted_particles * sizeof(float4), cudaMemcpyHostToDevice); cudaMemcpy(arrays::volume::ptr + old_ptcls, volumes.data(), inserted_particles * sizeof(float), cudaMemcpyHostToDevice); cudaMemcpy(arrays::particle_type::ptr + old_ptcls, particle_type.data(), inserted_particles * sizeof(float), cudaMemcpyHostToDevice); //cudaMemcpy(arrays::particle_type_x::ptr + old_ptcls, particle_type_x.data(), inserted_particles * sizeof(float), cudaMemcpyHostToDevice); #endif } std::vector<float> densities; std::vector<float4> rigid_velocities; std::vector<float3> rigid_avelocities; std::vector<float> rigid_volumes; std::vector<float3> rigid_origins; std::vector<float4> rigid_quaternions; std::vector<std::string> rigid_files; if (get<parameters::volumeBoundaryCounter>() == 0 && get<parameters::rigidVolumes>().size() > 0) { int rigid_nums = 1; auto wrld = DynamicsWorld::getInstance(); wrld->createWorld(); for (auto fluidVolume : get<parameters::rigidVolumes>()) { densities.push_back(fluidVolume.density.value); rigid_velocities.push_back({ 0.f, 0.f, 0.f, 0.f }); rigid_avelocities.push_back({ 0.f, 0.f, 0.f }); rigid_quaternions.push_back({ 0.f, 0.f, 0.f, 1.f }); rigid_files.push_back(fluidVolume.fileName.value); auto maxmin = wrld->addInfoBody(fluidVolume.fileName.value, fluidVolume.density.value, fluidVolume.shift.value); auto sht = fluidVolume.shift.value; rigid_origins.push_back({ (maxmin["max"].x + maxmin["min"].x) / 2 + sht.x, (maxmin["max"].y + maxmin["min"].y) / 2 + sht.y, (maxmin["max"].z + maxmin["min"].z) / 2 + sht.z }); // std::cout << "saved origin: " << (maxmin["max"].x+maxmin["min"].x)/2 << " " << // (maxmin["max"].y+maxmin["min"].y)/2 << " " << (maxmin["max"].z+maxmin["min"].z)/2 << std::endl; //TODO: combine above and below functions and make a review on the body of function below auto r = get<parameters::radius>(); auto volume = PI4O3 * math::power<3>(r); auto out_points = generation::generateParticlesRigid(fluidVolume.fileName.value, r, genTechnique::square_grid, false, maxmin); auto inserted_particles = (int32_t)out_points.size(); int32_t old_ptcls = get<parameters::num_ptcls>(); if (old_ptcls + inserted_particles > get<parameters::max_numptcls>()) { std::cerr << "Not enough memory to insert particles." << std::endl; continue; } get<parameters::num_ptcls>() += inserted_particles; #ifdef UNIFIED_MEMORY for (int32_t i = old_ptcls; i < old_ptcls + inserted_particles; ++i) { openvdb::Vec4f ptcl_position = out_points[i - old_ptcls]; get<arrays::position>()[i] = float4{ ptcl_position.x(), ptcl_position.y(), ptcl_position.z(), ptcl_position.w() }; get<arrays::velocity>()[i] = float4{ 0.f, 0.f, 0.f, 0.f }; get<arrays::volume>()[i] = volume; } #else std::vector<float4> positions; std::vector<float4> velocities; std::vector<float> volumes; std::vector<int> particle_type; std::vector<int> particle_type_x; // float4 center = {0, 0, 0, 0}; // for (int32_t i = 0; i < inserted_particles; ++i) { // openvdb::Vec4f ptcl_position = out_points[i]; // center += float4{ ptcl_position.x(), ptcl_position.y(), ptcl_position.z(), ptcl_position.w()}; // } // center = center / inserted_particles; auto shift = fluidVolume.shift.value; for (int32_t i = old_ptcls; i < old_ptcls + inserted_particles; ++i) { openvdb::Vec4f ptcl_position = out_points[i - old_ptcls]; positions.push_back(float4{ ptcl_position.x() + shift.x, ptcl_position.y() + shift.y, ptcl_position.z() + shift.z, ptcl_position.w() }); velocities.push_back(float4{ 0.f, 0.f, 0.f, 0.f }); particle_type.push_back(rigid_nums); particle_type_x.push_back(1); } for (auto& p_i : positions) { float v = 0.f; for (auto& p_j : positions) { v += kernel(p_i, p_j); } volumes.push_back(get<parameters::gamma>() / v); // volumes.push_back(volume); } cudaMemcpy(arrays::position::ptr + old_ptcls, positions.data(), inserted_particles * sizeof(float4), cudaMemcpyHostToDevice); cudaMemcpy(arrays::velocity::ptr + old_ptcls, velocities.data(), inserted_particles * sizeof(float4), cudaMemcpyHostToDevice); cudaMemcpy(arrays::volume::ptr + old_ptcls, volumes.data(), inserted_particles * sizeof(float), cudaMemcpyHostToDevice); cudaMemcpy(arrays::particle_type::ptr + old_ptcls, particle_type.data(), inserted_particles * sizeof(float), cudaMemcpyHostToDevice); //cudaMemcpy(arrays::particle_type_x::ptr + old_ptcls, particle_type_x.data(), inserted_particles * sizeof(float), cudaMemcpyHostToDevice); #endif // DynamicsWorld::getInstance()->addBody(fluidVolume.fileName.value); float total_vol = 0; for (auto i = 0; i < inserted_particles; i++) { total_vol += volumes[i]; } rigid_volumes.push_back(total_vol); int32_t index = rigid_nums - 1; wrld->addBody(total_vol, index); rigid_nums++; } if (get<parameters::rigidVolumes>().size()) { int32_t rigidCount = get<parameters::rigidVolumes>().size(); DynamicsWorld::getInstance()->createBoundingBox(); arrays::rigidOrigins::allocate(sizeof(float3) * rigidCount); cudaMemcpy(arrays::rigidOrigins::ptr, rigid_origins.data(), sizeof(float3) * rigidCount, cudaMemcpyHostToDevice); //arrays::rigidFiles::allocate(sizeof(std::string) * rigidCount); //cudaMemcpy(arrays::rigidFiles::ptr, rigid_files.data(), sizeof(std::string) * rigidCount, cudaMemcpyHostToDevice); arrays::rigidQuaternions::allocate(sizeof(float4) * rigidCount); cudaMemcpy(arrays::rigidQuaternions::ptr, rigid_quaternions.data(), sizeof(float4) * rigidCount, cudaMemcpyHostToDevice); arrays::rigidVolumes::allocate(sizeof(float) * rigidCount); cudaMemcpy(arrays::rigidVolumes::ptr, rigid_volumes.data(), sizeof(float) * rigidCount, cudaMemcpyHostToDevice); arrays::rigidDensities::allocate(sizeof(float) * rigidCount); cudaMemcpy(arrays::rigidDensities::ptr, densities.data(), sizeof(float) * rigidCount, cudaMemcpyHostToDevice); arrays::rigidLinearVelocities::allocate(sizeof(float4) * rigidCount); cudaMemcpy(arrays::rigidLinearVelocities::ptr, rigid_velocities.data(), sizeof(float4) * rigidCount, cudaMemcpyHostToDevice); arrays::rigidAVelocities::allocate(sizeof(float3) * rigidCount); cudaMemcpy(arrays::rigidAVelocities::ptr, rigid_avelocities.data(), sizeof(float3) * rigidCount, cudaMemcpyHostToDevice); } for (auto boundaryVolume : get<parameters::boundaryVolumes>()) { wrld->addBoundary(boundaryVolume.fileName.value); } } else { rigid_origins.push_back({ 0.f, 0.f, 0.f }); arrays::rigidOrigins::allocate(sizeof(float3)); cudaMemcpy(arrays::rigidOrigins::ptr, rigid_origins.data(), sizeof(float3), cudaMemcpyHostToDevice); rigid_files.push_back(""); //arrays::rigidFiles::allocate(sizeof(std::string)); //cudaMemcpy(arrays::rigidFiles::ptr, rigid_files.data(), sizeof(std::string), cudaMemcpyHostToDevice); rigid_quaternions.push_back({ 0.f, 0.f, 0.f, 0.f }); arrays::rigidQuaternions::allocate(sizeof(float4)); cudaMemcpy(arrays::rigidQuaternions::ptr, rigid_quaternions.data(), sizeof(float4), cudaMemcpyHostToDevice); rigid_volumes.push_back(0.f); arrays::rigidVolumes::allocate(sizeof(float)); cudaMemcpy(arrays::rigidVolumes::ptr, rigid_volumes.data(), sizeof(float), cudaMemcpyHostToDevice); densities.push_back(0.f); arrays::rigidDensities::allocate(sizeof(float)); cudaMemcpy(arrays::rigidDensities::ptr, densities.data(), sizeof(float), cudaMemcpyHostToDevice); rigid_velocities.push_back({ 0.0f, 0.0f, 0.0f, 0.0f }); arrays::rigidLinearVelocities::allocate(sizeof(float4)); cudaMemcpy(arrays::rigidLinearVelocities::ptr, rigid_velocities.data(), sizeof(float4), cudaMemcpyHostToDevice); rigid_avelocities.push_back({ 0.0f, 0.0f, 0.0f }); arrays::rigidAVelocities::allocate(sizeof(float3)); cudaMemcpy(arrays::rigidAVelocities::ptr, rigid_avelocities.data(), sizeof(float3), cudaMemcpyHostToDevice); } } void IO::vdb::recreateRigids() { int rigid_nums = 1; auto wrld = DynamicsWorld::getInstance(); wrld->createWorld(); for (auto fluidVolume : get<parameters::rigidVolumes>()) { // DynamicsWorld::getInstance()->addBody(fluidVolume.fileName.value); int32_t index = rigid_nums - 1; auto dens = fluidVolume.density.value; auto vol = arrays::rigidVolumes::ptr[index]; auto rfile = fluidVolume.fileName.value; wrld->addInfoBody(rfile, dens, {0, 0, 0}); wrld->addBody(vol, index); rigid_nums++; } if (get<parameters::rigidVolumes>().size()){ DynamicsWorld::getInstance()->createBoundingBox(); } else{} for (auto boundaryVolume : get<parameters::boundaryVolumes>()) { wrld->addBoundary(boundaryVolume.fileName.value); } }
43.526923
144
0.689847
[ "vector" ]
310db5d8ff0e11b19549da3fb693ac15a630bb0b
2,249
cpp
C++
kattis_done/boxes.cpp
heiseish/Competitive-Programming
e4dd4db83c38e8837914562bc84bc8c102e68e34
[ "MIT" ]
5
2019-03-17T01:33:19.000Z
2021-06-25T09:50:45.000Z
kattis_done/boxes.cpp
heiseish/Competitive-Programming
e4dd4db83c38e8837914562bc84bc8c102e68e34
[ "MIT" ]
null
null
null
kattis_done/boxes.cpp
heiseish/Competitive-Programming
e4dd4db83c38e8837914562bc84bc8c102e68e34
[ "MIT" ]
null
null
null
/** Although this mirror can show a reflection, it cannot show you the truth. */ #include <bits/stdc++.h> #define forn(i, l, r) for(int i=l;i<=r;i++) #define all(v) v.begin(),v.end() #define pb push_back #define nd second #define st first #define sz(x) (int)x.size() #define UNIQUE(v) (v).resize(unique(all(v)) - (v).begin()) #define mp make_pair #define debug(x) cout<<#x<<" --> "<<x<<endl; using namespace std; typedef long long ll; typedef long double ld; typedef vector<int> vi; typedef vector<long long> vll; typedef vector<pair<int, int> > vpi; typedef pair<int, int> pi; typedef pair<ll, ll> pll; typedef vector<pll> vpll; const int INF = 1 << 30; /** Start coding from here */ const int N = 2e5 + 3; int n; int contains[N]; vi g[N]; int roots[N]; int pre[N], post[N]; int dfs(int index) { int ans = 1; for (auto &v : g[index]) { ans += dfs(v); } return contains[index] = ans; } void preorder(int index) { static int t= 1; pre[index] = t++; for (auto &v : g[index]) preorder(v); } void postorder(int index) { static int t = 1; for (auto &v : g[index]) postorder(v); post[index] = t++; } const int maxk = 20; int l[maxk], nu[maxk]; int main() { ios_base::sync_with_stdio(false); cin.tie(0); #ifdef LOCAL_PROJECT freopen("input.txt","r",stdin); #endif cin>>n; int m; forn(i,1,n) { cin>>m; if (m==0) roots[i]++; else g[m].pb(i); } forn(i,1,n) if (roots[i]) { dfs(i); preorder(i); postorder(i); } int q; cin>>q; int k; while(q--) { cin>>k; int ans = 0; forn(i,0,k-1) { cin>>l[i]; ans += contains[l[i]]; } memset(nu, false, sizeof nu); forn(i,0,k-1) { forn(j,i+1,k-1) { if (nu[i] || nu[j]) continue; if (pre[l[i]] < pre[l[j]] && post[l[i]] > post[l[j]]) { nu[j] = true; continue; } if (pre[l[i]] > pre[l[j]] && post[l[i]] < post[l[j]]) { nu[i] = true; break; } } } forn(i,0,k-1) if(nu[i]) ans-=contains[l[i]]; cout << ans <<'\n'; } return 0; }
21.419048
81
0.501556
[ "vector" ]
310fca876f4df9bc24293f2f55b2fa744c884e5c
11,534
cpp
C++
src/Data/MapObject.cpp
jmakovicka/OsmAnd-core
d18f57bb123b6c6ad0adbed0c2f4419d0e6a6610
[ "MIT" ]
null
null
null
src/Data/MapObject.cpp
jmakovicka/OsmAnd-core
d18f57bb123b6c6ad0adbed0c2f4419d0e6a6610
[ "MIT" ]
null
null
null
src/Data/MapObject.cpp
jmakovicka/OsmAnd-core
d18f57bb123b6c6ad0adbed0c2f4419d0e6a6610
[ "MIT" ]
null
null
null
#include "MapObject.h" #include "stdlib_common.h" #include <algorithm> #include "QtExtensions.h" #include "QtCommon.h" #include "OsmAndCore.h" #include "Common.h" #include "QKeyIterator.h" #include "QKeyValueIterator.h" std::shared_ptr<const OsmAnd::MapObject::EncodingDecodingRules> OsmAnd::MapObject::defaultEncodingDecodingRules(OsmAnd::modifyAndReturn( std::shared_ptr<OsmAnd::MapObject::EncodingDecodingRules>(new OsmAnd::MapObject::EncodingDecodingRules()), static_cast< std::function<void (std::shared_ptr<OsmAnd::MapObject::EncodingDecodingRules>& instance)> >([] (std::shared_ptr<OsmAnd::MapObject::EncodingDecodingRules>& rules) -> void { rules->verifyRequiredRulesExist(); }))); OsmAnd::MapObject::MapObject() : encodingDecodingRules(defaultEncodingDecodingRules) , isArea(false) { } OsmAnd::MapObject::~MapObject() { } bool OsmAnd::MapObject::obtainSharingKey(SharingKey& outKey) const { Q_UNUSED(outKey); return false; } bool OsmAnd::MapObject::obtainSortingKey(SortingKey& outKey) const { Q_UNUSED(outKey); return false; } OsmAnd::ZoomLevel OsmAnd::MapObject::getMinZoomLevel() const { return MinZoomLevel; } OsmAnd::ZoomLevel OsmAnd::MapObject::getMaxZoomLevel() const { return MaxZoomLevel; } QString OsmAnd::MapObject::toString() const { return QString().sprintf("(@%p)", this); } bool OsmAnd::MapObject::isClosedFigure(bool checkInner /*= false*/) const { if (checkInner) { for (const auto& polygon : constOf(innerPolygonsPoints31)) { if (polygon.isEmpty()) continue; if (polygon.first() != polygon.last()) return false; } return true; } else return (points31.first() == points31.last()); } void OsmAnd::MapObject::computeBBox31() { bbox31.top() = bbox31.left() = std::numeric_limits<int32_t>::max(); bbox31.bottom() = bbox31.right() = 0; auto pPoint31 = points31.constData(); const auto pointsCount = points31.size(); for (auto pointIdx = 0; pointIdx < pointsCount; pointIdx++, pPoint31++) bbox31.enlargeToInclude(*pPoint31); } bool OsmAnd::MapObject::intersectedOrContainedBy(const AreaI& area) const { // Check if area intersects bbox31 or bbox31 contains area or area contains bbox31 // Fast check to exclude obviously false cases if (!bbox31.contains(area) && !area.contains(bbox31) && !area.intersects(bbox31)) return false; // Check if any of the object points is inside area auto pPoint31 = points31.constData(); const auto pointsCount = points31.size(); for (auto pointIdx = 0; pointIdx < pointsCount; pointIdx++, pPoint31++) { if (area.contains(*pPoint31)) return true; } return false; } bool OsmAnd::MapObject::containsType(const uint32_t typeRuleId, bool checkAdditional /*= false*/) const { return (checkAdditional ? additionalTypesRuleIds : typesRuleIds).contains(typeRuleId); } bool OsmAnd::MapObject::containsTypeSlow(const QString& tag, const QString& value, bool checkAdditional /*= false*/) const { const auto citByTag = encodingDecodingRules->encodingRuleIds.constFind(tag); if (citByTag == encodingDecodingRules->encodingRuleIds.cend()) return false; const auto citByValue = citByTag->constFind(value); if (citByValue == citByTag->cend()) return false; const auto typeRuleId = *citByValue; return (checkAdditional ? additionalTypesRuleIds : typesRuleIds).contains(typeRuleId); } bool OsmAnd::MapObject::containsTagSlow(const QString& tag, bool checkAdditional /*= false*/) const { const auto citByTag = encodingDecodingRules->encodingRuleIds.constFind(tag); if (citByTag == encodingDecodingRules->encodingRuleIds.cend()) return false; for (const auto typeRuleId : constOf(*citByTag)) { if ((checkAdditional ? additionalTypesRuleIds : typesRuleIds).contains(typeRuleId)) return true; } return false; } bool OsmAnd::MapObject::obtainTagValueByTypeRuleIndex(const uint32_t typeRuleIndex, QString& outTag, QString& outValue, bool checkAdditional /*= false*/) const { const auto& rulesIds = checkAdditional ? additionalTypesRuleIds : typesRuleIds; if (typeRuleIndex >= rulesIds.size()) return false; const auto typeRuleId = rulesIds[typeRuleIndex]; const auto citRule = encodingDecodingRules->decodingRules.constFind(typeRuleId); if (citRule == encodingDecodingRules->decodingRules.cend()) return false; const auto& rule = *citRule; outTag = rule.tag; outValue = rule.value; return true; } OsmAnd::MapObject::LayerType OsmAnd::MapObject::getLayerType() const { return LayerType::Zero; } QString OsmAnd::MapObject::getCaptionInNativeLanguage() const { const auto citName = captions.constFind(encodingDecodingRules->name_encodingRuleId); if (citName == captions.cend()) return QString::null; return *citName; } QString OsmAnd::MapObject::getCaptionInLanguage(const QString& lang) const { const auto citNameId = encodingDecodingRules->localizedName_encodingRuleIds.constFind(lang); if (citNameId == encodingDecodingRules->localizedName_encodingRuleIds.cend()) return QString::null; const auto citName = captions.constFind(*citNameId); if (citName == captions.cend()) return QString::null; return *citName; } OsmAnd::MapObject::EncodingDecodingRules::EncodingDecodingRules() : name_encodingRuleId(std::numeric_limits<uint32_t>::max()) , ref_encodingRuleId(std::numeric_limits<uint32_t>::max()) , naturalCoastline_encodingRuleId(std::numeric_limits<uint32_t>::max()) , naturalLand_encodingRuleId(std::numeric_limits<uint32_t>::max()) , naturalCoastlineBroken_encodingRuleId(std::numeric_limits<uint32_t>::max()) , naturalCoastlineLine_encodingRuleId(std::numeric_limits<uint32_t>::max()) , highway_encodingRuleId(std::numeric_limits<uint32_t>::max()) , oneway_encodingRuleId(std::numeric_limits<uint32_t>::max()) , onewayReverse_encodingRuleId(std::numeric_limits<uint32_t>::max()) , layerLowest_encodingRuleId(std::numeric_limits<uint32_t>::max()) { } OsmAnd::MapObject::EncodingDecodingRules::~EncodingDecodingRules() { } void OsmAnd::MapObject::EncodingDecodingRules::verifyRequiredRulesExist() { uint32_t lastUsedRuleId = 0u; if (!decodingRules.isEmpty()) lastUsedRuleId = *qMaxElement(keysOf(constOf(decodingRules))); createRequiredRules(lastUsedRuleId); } void OsmAnd::MapObject::EncodingDecodingRules::createRequiredRules(uint32_t& lastUsedRuleId) { if (name_encodingRuleId == std::numeric_limits<uint32_t>::max()) { addRule(lastUsedRuleId++, QLatin1String("name"), QString::null); } if (ref_encodingRuleId == std::numeric_limits<uint32_t>::max()) { addRule(lastUsedRuleId++, QLatin1String("ref"), QString::null); } if (naturalCoastline_encodingRuleId == std::numeric_limits<uint32_t>::max()) { addRule(lastUsedRuleId++, QLatin1String("natural"), QLatin1String("coastline")); } if (naturalLand_encodingRuleId == std::numeric_limits<uint32_t>::max()) { addRule(lastUsedRuleId++, QLatin1String("natural"), QLatin1String("land")); } if (naturalCoastlineBroken_encodingRuleId == std::numeric_limits<uint32_t>::max()) { addRule(lastUsedRuleId++, QLatin1String("natural"), QLatin1String("coastline_broken")); } if (naturalCoastlineLine_encodingRuleId == std::numeric_limits<uint32_t>::max()) { addRule(lastUsedRuleId++, QLatin1String("natural"), QLatin1String("coastline_line")); } if (highway_encodingRuleId == std::numeric_limits<uint32_t>::max()) { addRule(lastUsedRuleId++, QLatin1String("highway"), QLatin1String("yes")); } if (oneway_encodingRuleId == std::numeric_limits<uint32_t>::max()) { addRule(lastUsedRuleId++, QLatin1String("oneway"), QLatin1String("yes")); } if (onewayReverse_encodingRuleId == std::numeric_limits<uint32_t>::max()) { addRule(lastUsedRuleId++, QLatin1String("oneway"), QLatin1String("-1")); } if (layerLowest_encodingRuleId == std::numeric_limits<uint32_t>::max()) { addRule(lastUsedRuleId++, QLatin1String("layer"), QString::number(std::numeric_limits<int32_t>::min())); } } uint32_t OsmAnd::MapObject::EncodingDecodingRules::addRule(const uint32_t ruleId, const QString& ruleTag, const QString& ruleValue) { // Insert encoding rule auto itEncodingRule = encodingRuleIds.find(ruleTag); if (itEncodingRule == encodingRuleIds.end()) itEncodingRule = encodingRuleIds.insert(ruleTag, QHash<QString, uint32_t>()); itEncodingRule->insert(ruleValue, ruleId); // Insert decoding rule if (!decodingRules.contains(ruleId)) { DecodingRule rule; rule.tag = ruleTag; rule.value = ruleValue; decodingRules.insert(ruleId, rule); } // Capture quick-access rules if (QLatin1String("name") == ruleTag) { name_encodingRuleId = ruleId; namesRuleId.insert(ruleId); } else if (ruleTag.startsWith(QLatin1String("name:"))) { const QString languageId = ruleTag.mid(QLatin1String("name:").size()); localizedName_encodingRuleIds.insert(languageId, ruleId); localizedName_decodingRules.insert(ruleId, languageId); namesRuleId.insert(ruleId); } else if (QLatin1String("ref") == ruleTag) ref_encodingRuleId = ruleId; else if (QLatin1String("natural") == ruleTag && QLatin1String("coastline") == ruleValue) naturalCoastline_encodingRuleId = ruleId; else if (QLatin1String("natural") == ruleTag && QLatin1String("land") == ruleValue) naturalLand_encodingRuleId = ruleId; else if (QLatin1String("natural") == ruleTag && QLatin1String("coastline_broken") == ruleValue) naturalCoastlineBroken_encodingRuleId = ruleId; else if (QLatin1String("natural") == ruleTag && QLatin1String("coastline_line") == ruleValue) naturalCoastlineLine_encodingRuleId = ruleId; else if (QLatin1String("highway") == ruleTag && QLatin1String("yes") == ruleValue) highway_encodingRuleId = ruleId; else if (QLatin1String("oneway") == ruleTag && QLatin1String("yes") == ruleValue) oneway_encodingRuleId = ruleId; else if (QLatin1String("oneway") == ruleTag && QLatin1String("-1") == ruleValue) onewayReverse_encodingRuleId = ruleId; return ruleId; } OsmAnd::MapObject::EncodingDecodingRules::DecodingRule::DecodingRule() { } OsmAnd::MapObject::EncodingDecodingRules::DecodingRule::~DecodingRule() { } OsmAnd::MapObject::Comparator::Comparator() { } bool OsmAnd::MapObject::Comparator::operator()(const std::shared_ptr<const MapObject>& l, const std::shared_ptr<const MapObject>& r) const { MapObject::SortingKey lKey; const auto lHasKey = l->obtainSortingKey(lKey); MapObject::SortingKey rKey; const auto rHasKey = r->obtainSortingKey(rKey); if (lHasKey && rHasKey) { if (lKey != rKey) return (lKey < rKey); return (l < r); } if (!lHasKey && !rHasKey) return (l < r); if (lHasKey && !rHasKey) return true; if (!lHasKey && rHasKey) return false; return (l < r); }
31.6
159
0.686319
[ "object" ]
31156d5cf4998a7dbda1965a7c2dd867846178e5
1,779
cpp
C++
LeetCode/Problems/Algorithms/#971_FlipBinaryTreeToMatchPreorderTraversal_sol1_dfs_O(N)_time_O(H)_extra_space.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#971_FlipBinaryTreeToMatchPreorderTraversal_sol1_dfs_O(N)_time_O(H)_extra_space.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#971_FlipBinaryTreeToMatchPreorderTraversal_sol1_dfs_O(N)_time_O(H)_extra_space.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { private: void dfs(TreeNode* root, vector<int>& voyage, int& idx, vector<int>& flippedNodes, bool& isPossible){ if(root != NULL && isPossible){ idx += 1; if(root->val == voyage[idx]){ if(root->left != NULL){ if(root->left->val == voyage[idx + 1]){ dfs(root->left, voyage, idx, flippedNodes, isPossible); dfs(root->right, voyage, idx, flippedNodes, isPossible); }else{ flippedNodes.push_back(root->val); dfs(root->right, voyage, idx, flippedNodes, isPossible); dfs(root->left, voyage, idx, flippedNodes, isPossible); } }else{ dfs(root->right, voyage, idx, flippedNodes, isPossible); } }else{ isPossible = false; } } } public: vector<int> flipMatchVoyage(TreeNode* root, vector<int>& voyage) { int idx = -1; vector<int> flippedNodes; bool isPossible = true; dfs(root, voyage, idx, flippedNodes, isPossible); if(!isPossible){ flippedNodes.clear(); flippedNodes.push_back(-1); } return flippedNodes; } };
34.882353
106
0.482293
[ "vector" ]
3124e35877492e7116a1630b668b4af4bf8cd81c
11,503
cpp
C++
Felix/felix_cl_options_test.cpp
ultimatezen/felix
5a7ad298ca4dcd5f1def05c60ae3c84519ec54c4
[ "MIT" ]
null
null
null
Felix/felix_cl_options_test.cpp
ultimatezen/felix
5a7ad298ca4dcd5f1def05c60ae3c84519ec54c4
[ "MIT" ]
null
null
null
Felix/felix_cl_options_test.cpp
ultimatezen/felix
5a7ad298ca4dcd5f1def05c60ae3c84519ec54c4
[ "MIT" ]
null
null
null
/*! @brief Unit tests for felix_cl_options @author Ryan Ginstrom */ #include "StdAfx.h" #include "felix_cl_options.h" #include <boost/test/unit_test.hpp> #ifdef UNIT_TEST BOOST_AUTO_TEST_SUITE( test_parse_command_line ) BOOST_AUTO_TEST_CASE( simple) { LPCTSTR command_line_text = _T("foo.txt") ; std::vector<tstring> tokens ; parse_command_line(command_line_text, tokens) ; BOOST_CHECK_EQUAL(1u, tokens.size()) ; BOOST_CHECK_EQUAL(_T("foo.txt"), tokens[0]) ; } BOOST_AUTO_TEST_CASE( two) { LPCTSTR command_line_text = _T("foo.txt bar.txt") ; std::vector<tstring> tokens ; parse_command_line(command_line_text, tokens) ; BOOST_CHECK_EQUAL(2u, tokens.size()) ; BOOST_CHECK_EQUAL(_T("foo.txt"), tokens[0]) ; BOOST_CHECK_EQUAL(_T("bar.txt"), tokens[1]) ; } BOOST_AUTO_TEST_CASE( one_with_space) { LPCTSTR command_line_text = _T("\"c:\\program files\\foo.txt\"") ; std::vector<tstring> tokens ; parse_command_line(command_line_text, tokens) ; BOOST_CHECK_EQUAL(1u, tokens.size()) ; BOOST_CHECK_EQUAL(_T("c:\\program files\\foo.txt"), tokens[0]) ; } BOOST_AUTO_TEST_CASE( two_one_with_space) { LPCTSTR command_line_text = _T("foo.txt \"c:\\program files\\foo.txt\"") ; std::vector<tstring> tokens ; parse_command_line(command_line_text, tokens) ; BOOST_CHECK_EQUAL(2u, tokens.size()) ; BOOST_CHECK_EQUAL(_T("foo.txt"), tokens[0]) ; BOOST_CHECK_EQUAL(_T("c:\\program files\\foo.txt"), tokens[1]) ; } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE( test_parse_filename ) BOOST_AUTO_TEST_CASE(test_lang) { tstring token = _T("-lang") ; tstring commandline_text ; commandline_options options(commandline_text.c_str()) ; BOOST_CHECK_EQUAL(false, options.parse_filename(token)) ; BOOST_CHECK(options.m_tm_files.empty()) ; BOOST_CHECK(options.m_glossary_files.empty()) ; BOOST_CHECK(options.m_xml_files.empty()) ; BOOST_CHECK(options.m_tmx_files.empty()) ; BOOST_CHECK(options.m_trados_text_files.empty()) ; BOOST_CHECK(options.m_multiterm_files.empty()) ; BOOST_CHECK(options.m_prefs_file.empty()) ; BOOST_CHECK(! options.m_new_prefs_format) ; } BOOST_AUTO_TEST_CASE(test_logging) { tstring token = _T("-logging") ; tstring commandline_text ; commandline_options options(commandline_text.c_str()) ; BOOST_CHECK_EQUAL(false, options.parse_filename(token)) ; BOOST_CHECK(options.m_tm_files.empty()) ; BOOST_CHECK(options.m_glossary_files.empty()) ; BOOST_CHECK(options.m_xml_files.empty()) ; BOOST_CHECK(options.m_tmx_files.empty()) ; BOOST_CHECK(options.m_trados_text_files.empty()) ; BOOST_CHECK(options.m_multiterm_files.empty()) ; BOOST_CHECK(options.m_prefs_file.empty()) ; BOOST_CHECK(! options.m_new_prefs_format) ; } BOOST_AUTO_TEST_CASE(test_old_prefs) { tstring token = _T("foo.fprefs") ; tstring commandline_text ; commandline_options options(commandline_text.c_str()) ; BOOST_CHECK_EQUAL(true, options.parse_filename(token)) ; BOOST_CHECK(options.m_tm_files.empty()) ; BOOST_CHECK(options.m_glossary_files.empty()) ; BOOST_CHECK(options.m_xml_files.empty()) ; BOOST_CHECK(options.m_tmx_files.empty()) ; BOOST_CHECK(options.m_trados_text_files.empty()) ; BOOST_CHECK(options.m_multiterm_files.empty()) ; BOOST_CHECK_EQUAL(L"foo.fprefs", options.m_prefs_file) ; BOOST_CHECK(! options.m_new_prefs_format) ; } BOOST_AUTO_TEST_CASE(test_new_prefs) { tstring token = _T("foo.fprefx") ; tstring commandline_text ; commandline_options options(commandline_text.c_str()) ; BOOST_CHECK_EQUAL(true, options.parse_filename(token)) ; BOOST_CHECK(options.m_tm_files.empty()) ; BOOST_CHECK(options.m_glossary_files.empty()) ; BOOST_CHECK(options.m_xml_files.empty()) ; BOOST_CHECK(options.m_tmx_files.empty()) ; BOOST_CHECK(options.m_trados_text_files.empty()) ; BOOST_CHECK(options.m_multiterm_files.empty()) ; BOOST_CHECK_EQUAL(L"foo.fprefx", options.m_prefs_file) ; BOOST_CHECK(options.m_new_prefs_format) ; } BOOST_AUTO_TEST_SUITE_END() ////////////////////////////////////////////////////////////////////////// // commandline_options ////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_SUITE( test_commandline_options ) // language BOOST_AUTO_TEST_CASE( language_default) { LPCTSTR command_line_text = _T("foo.txt") ; commandline_options options(command_line_text) ; BOOST_CHECK_EQUAL((int)LANG_ENGLISH, (int)options.m_language) ; } BOOST_AUTO_TEST_CASE( language_english) { LPCTSTR command_line_text = _T("foo.txt") ; commandline_options options(command_line_text, LANG_ENGLISH) ; BOOST_CHECK_EQUAL((int)LANG_ENGLISH, (int)options.m_language) ; } BOOST_AUTO_TEST_CASE( language_japanese) { LPCTSTR command_line_text = _T("foo.txt") ; commandline_options options(command_line_text, LANG_JAPANESE) ; BOOST_CHECK_EQUAL((int)LANG_JAPANESE, (int)options.m_language) ; } BOOST_AUTO_TEST_CASE( parse_language_japanese) { commandline_options options(_T("")) ; BOOST_CHECK_EQUAL((int)LANG_JAPANESE, (int)options.parse_lang(_T("Japanese"))) ; } BOOST_AUTO_TEST_CASE( parse_language_ja) { commandline_options options(_T("")) ; BOOST_CHECK_EQUAL((int)LANG_JAPANESE, (int)options.parse_lang(_T("ja"))) ; } BOOST_AUTO_TEST_CASE( parse_language_jp) { commandline_options options(_T("")) ; BOOST_CHECK_EQUAL((int)LANG_JAPANESE, (int)options.parse_lang(_T("jp"))) ; } BOOST_AUTO_TEST_CASE( parse_language_english) { commandline_options options(_T("")) ; BOOST_CHECK_EQUAL((int)LANG_ENGLISH, (int)options.parse_lang(_T("English"))) ; } BOOST_AUTO_TEST_CASE( language_switch_english) { commandline_options options(_T("-lang English")) ; BOOST_CHECK_EQUAL((int)LANG_ENGLISH, (int)options.parse_lang(_T("English"))) ; } BOOST_AUTO_TEST_CASE( language_switch_japanese) { commandline_options options(_T("-lang Japanese")) ; BOOST_CHECK_EQUAL((int)LANG_JAPANESE, (int)options.m_language) ; } BOOST_AUTO_TEST_CASE( language_switch_ja) { commandline_options options(_T("-lang ja")) ; BOOST_CHECK_EQUAL((int)LANG_JAPANESE, (int)options.m_language) ; } BOOST_AUTO_TEST_CASE( language_switch_jp) { commandline_options options(_T("-lang jp")) ; BOOST_CHECK_EQUAL((int)LANG_JAPANESE, (int)options.m_language) ; } // single file BOOST_AUTO_TEST_CASE( felix_simple) { LPCTSTR command_line_text = _T("foo.ftm") ; commandline_options options(command_line_text) ; BOOST_CHECK_EQUAL(1u, options.m_tm_files.size()) ; BOOST_CHECK_EQUAL(_T("foo.ftm"), options.m_tm_files[0]) ; BOOST_CHECK_EQUAL(_T(""), options.m_prefs_file) ; } BOOST_AUTO_TEST_CASE( glossary_simple) { LPCTSTR command_line_text = _T("foo.fgloss") ; commandline_options options(command_line_text) ; BOOST_CHECK_EQUAL(1u, options.m_glossary_files.size()) ; BOOST_CHECK_EQUAL(_T("foo.fgloss"), options.m_glossary_files[0]) ; } BOOST_AUTO_TEST_CASE( tmx_simple) { LPCTSTR command_line_text = _T("foo.tmx") ; commandline_options options(command_line_text) ; BOOST_CHECK_EQUAL(1u, options.m_tmx_files.size()) ; BOOST_CHECK_EQUAL(_T("foo.tmx"), options.m_tmx_files[0]) ; } BOOST_AUTO_TEST_CASE( trados_text_simple) { LPCTSTR command_line_text = _T("foo.txt") ; commandline_options options(command_line_text) ; BOOST_CHECK_EQUAL(1u, options.m_trados_text_files.size()) ; BOOST_CHECK_EQUAL(_T("foo.txt"), options.m_trados_text_files[0]) ; } BOOST_AUTO_TEST_CASE( xml_simple) { LPCTSTR command_line_text = _T("foo.xml") ; commandline_options options(command_line_text) ; BOOST_CHECK_EQUAL(1u, options.m_xml_files.size()) ; BOOST_CHECK_EQUAL(_T("foo.xml"), options.m_xml_files[0]) ; } BOOST_AUTO_TEST_CASE( fprefs_simple) { LPCTSTR command_line_text = _T("foo.fprefs") ; commandline_options options(command_line_text) ; BOOST_CHECK_EQUAL(_T("foo.fprefs"), options.m_prefs_file) ; } // file with language switch BOOST_AUTO_TEST_CASE( felix_simple_lang_switch_none) { LPCTSTR command_line_text = _T("foo.ftm") ; commandline_options options(command_line_text, LANG_JAPANESE) ; BOOST_CHECK_EQUAL((int)LANG_JAPANESE, (int)options.m_language) ; } BOOST_AUTO_TEST_CASE( felix_simple_lang_switch_japanese) { LPCTSTR command_line_text = _T("foo.ftm -lang Japanese") ; commandline_options options(command_line_text) ; BOOST_CHECK_EQUAL((int)LANG_JAPANESE, (int)options.m_language) ; } BOOST_AUTO_TEST_CASE( felix_simple_lang_switch_ja_def_eng) { LPCTSTR command_line_text = _T("foo.ftm -lang Japanese") ; commandline_options options(command_line_text, LANG_ENGLISH) ; BOOST_CHECK_EQUAL((int)LANG_JAPANESE, (int)options.m_language) ; } BOOST_AUTO_TEST_CASE( felix_simple_lang_switch_english) { LPCTSTR command_line_text = _T("foo.ftm -lang English") ; commandline_options options(command_line_text) ; BOOST_CHECK_EQUAL((int)LANG_ENGLISH, (int)options.m_language) ; } // two files BOOST_AUTO_TEST_CASE( trados_text_two) { LPCTSTR command_line_text = _T("foo.txt bar.txt") ; commandline_options options(command_line_text) ; BOOST_CHECK_EQUAL(2u, options.m_trados_text_files.size()) ; BOOST_CHECK_EQUAL(_T("foo.txt"), options.m_trados_text_files[0]) ; BOOST_CHECK_EQUAL(_T("bar.txt"), options.m_trados_text_files[1]) ; } BOOST_AUTO_TEST_CASE( fgloss_and_ftm) { LPCTSTR command_line_text = _T("foo.fgloss bar.ftm") ; commandline_options options(command_line_text) ; BOOST_CHECK_EQUAL(1u, options.m_tm_files.size()) ; BOOST_CHECK_EQUAL(_T("bar.ftm"), options.m_tm_files[0]) ; BOOST_CHECK_EQUAL(1u, options.m_glossary_files.size()) ; BOOST_CHECK_EQUAL(_T("foo.fgloss"), options.m_glossary_files[0]) ; } // space in filename(s) BOOST_AUTO_TEST_CASE( trados_text_one_with_space) { LPCTSTR command_line_text = _T("\"c:\\program files\\foo.txt\"") ; commandline_options options(command_line_text) ; BOOST_CHECK_EQUAL(1u, options.m_trados_text_files.size()) ; BOOST_CHECK_EQUAL(_T("c:\\program files\\foo.txt"), options.m_trados_text_files[0]) ; } BOOST_AUTO_TEST_CASE( trados_text_two_one_with_space) { LPCTSTR command_line_text = _T("foo.txt \"c:\\program files\\foo.txt\"") ; commandline_options options(command_line_text) ; BOOST_CHECK_EQUAL(2u, options.m_trados_text_files.size()) ; BOOST_CHECK_EQUAL(_T("foo.txt"), options.m_trados_text_files[0]) ; BOOST_CHECK_EQUAL(_T("c:\\program files\\foo.txt"), options.m_trados_text_files[1]) ; } // logging level BOOST_AUTO_TEST_CASE(logging_all) { LPCTSTR command_line_text = _T("-logging all") ; commandline_options options(command_line_text) ; BOOST_CHECK_EQUAL(options.m_logging_level, LOGGING_DEBUG) ; } BOOST_AUTO_TEST_CASE(logging_warn) { LPCTSTR command_line_text = _T("-logging warn") ; commandline_options options(command_line_text) ; BOOST_CHECK_EQUAL(options.m_logging_level, LOGGING_WARN) ; } BOOST_AUTO_TEST_CASE(logging_error_upper) { LPCTSTR command_line_text = _T("-logging ERROR") ; commandline_options options(command_line_text) ; BOOST_CHECK_EQUAL(options.m_logging_level, LOGGING_ERROR) ; } BOOST_AUTO_TEST_SUITE_END() #endif
31.089189
88
0.724594
[ "vector" ]
312b25109160b9a707e5b01107b9344ea729078b
131,506
hpp
C++
plll/include/plll/matrix-ops2.hpp
KudrinMatvey/myfplll
99fa018201097b6c078c00721cdc409cdcd4092c
[ "MIT" ]
null
null
null
plll/include/plll/matrix-ops2.hpp
KudrinMatvey/myfplll
99fa018201097b6c078c00721cdc409cdcd4092c
[ "MIT" ]
null
null
null
plll/include/plll/matrix-ops2.hpp
KudrinMatvey/myfplll
99fa018201097b6c078c00721cdc409cdcd4092c
[ "MIT" ]
null
null
null
/* Copyright (c) 2011-2014 University of Zurich 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 PLLL_INCLUDE_GUARD__MATRIX_OPS2_HPP #define PLLL_INCLUDE_GUARD__MATRIX_OPS2_HPP /** \file \brief Operator instantiations for matrices and vectors. This header contains instantiations of the abstract templates in `matrix-ops.hpp`. They provide implementations to essentially all operations on matrices. */ namespace plll { namespace implemenation { } namespace linalg { //////////////////////////////////////////////////////////////////////////////////////////////////// //// swap //////////////////////////////////////////////////////////////////////////////////////////////////// /**@{ \name Swap functions. */ template<typename T, int R, int C, typename ST, bool MO> void swap(base_matrix<T, R, C, ST, MO> & A, base_matrix<T, R, C, ST, MO> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_INLINE { PLLL_DEBUG_OUTPUT_MESSAGE("swap(" << getAddress(A) << " " << getAddress(B) << ") [0]"); std::swap(A.d_data, B.d_data); A.implementation::template row_count_storage<R>::swap(B); A.implementation::template col_count_storage<C>::swap(B); } template<typename T, int R1, int C1, int R2, int C2, typename ST, bool MO1, bool MO2> void swap(base_matrix<T, R1, C1, ST, MO1> & A, base_matrix<T, R2, C2, ST, MO2> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_INLINE { PLLL_DEBUG_OUTPUT_MESSAGE("swap(" << getAddress(A) << " " << getAddress(B) << ") [1]"); PLLL_INTERNAL_STATIC_CHECK((R1 < 0) || (R2 < 0) || (R1 == R2), TypeAShouldNotBeConst); PLLL_INTERNAL_STATIC_CHECK((C1 < 0) || (C2 < 0) || (C1 == C2), TypeAShouldNotBeConst); if (((R1 >= 0) && (R2 < 0)) || ((R2 >= 0) && (R1 < 0))) assert(A.rows() == B.rows()); if (((C1 >= 0) && (C2 < 0)) || ((C2 >= 0) && (C1 < 0))) assert(A.cols() == B.cols()); std::swap(A.d_data, B.d_data); A.implementation::template row_count_storage<R1>::swap(B); A.implementation::template col_count_storage<C1>::swap(B); } namespace implementation { using std::swap; template<template<typename AData> class AOp, typename AData, template<typename BData> class BOp, typename BData> void do_swap(const implementation::expressions::expr<AOp, AData> & A, const implementation::expressions::expr<BOp, BData> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(A.enumerate()) && noexcept(B.enumerate()) && noexcept(helper::make_type_lvalue<typename implementation::expressions::expr<AOp, AData>::Enumerator>().has_current()) && noexcept(helper::make_type_lvalue<typename implementation::expressions::expr<AOp, AData>::Enumerator>().next()) && noexcept(helper::make_type_lvalue<typename implementation::expressions::expr<BOp, BData>::Enumerator>().next()) && noexcept(swap(helper::make_type_lvalue<typename implementation::expressions::expr<AOp, AData>::Enumerator>().current(), helper::make_type_lvalue<typename implementation::expressions::expr<BOp, BData>::Enumerator>().current()))) { PLLL_DEBUG_OUTPUT_MESSAGE("swap(" << getAddress(A) << " " << getAddress(B) << ") [2]"); PLLL_INTERNAL_STATIC_CHECK(!(implementation::MatrixInfo<implementation::expressions::expr<AOp, AData> >::is_const), TypeAShouldNotBeConst); PLLL_INTERNAL_STATIC_CHECK(!(implementation::MatrixInfo<implementation::expressions::expr<BOp, BData> >::is_const), TypeBShouldNotBeConst); PLLL_INTERNAL_STATIC_CHECK((implementation::MatrixInfo<implementation::expressions::expr<AOp, AData> >::rows < 0) || (implementation::MatrixInfo<implementation::expressions::expr<BOp, BData> >::rows < 0) || (static_cast<size_type>(implementation::MatrixInfo<implementation::expressions::expr<AOp, AData> >::rows) == static_cast<size_type>(implementation::MatrixInfo<implementation::expressions::expr<BOp, BData> >::rows)), NeedSameNumberOfRows); PLLL_INTERNAL_STATIC_CHECK((implementation::MatrixInfo<implementation::expressions::expr<AOp, AData> >::cols < 0) || (implementation::MatrixInfo<implementation::expressions::expr<BOp, BData> >::cols < 0) || (static_cast<size_type>(implementation::MatrixInfo<implementation::expressions::expr<AOp, AData> >::cols) == static_cast<size_type>(implementation::MatrixInfo<implementation::expressions::expr<BOp, BData> >::cols)), NeedSameNumberOfCols); assert(A.rows() == B.rows()); assert(A.cols() == B.cols()); typename implementation::expressions::expr<AOp, AData>::Enumerator eA = A.enumerate(); typename implementation::expressions::expr<BOp, BData>::Enumerator eB = B.enumerate(); for (; eA.has_current(); eA.next(), eB.next()) { using std::swap; swap(eA.current(), eB.current()); } } } template<template<typename AData> class AOp, typename AData, template<typename BData> class BOp, typename BData> void swap(const implementation::expressions::expr<AOp, AData> & A, const implementation::expressions::expr<BOp, BData> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::do_swap(A, B))) { implementation::do_swap(A, B); } template<template<typename AData> class AOp, typename AData, typename BT, int BRows, int BCols, typename BST, bool BMO> void swap(const implementation::expressions::expr<AOp, AData> & A, base_matrix<BT, BRows, BCols, BST, BMO> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(linalg::swap(A, implementation::expressions::make_matrix_expression(B)))) { linalg::swap(A, implementation::expressions::make_matrix_expression(B)); } template<typename AT, int ARows, int ACols, typename AST, bool AMO, template<typename BData> class BOp, typename BData> void swap(base_matrix<AT, ARows, ACols, AST, AMO> & A, const implementation::expressions::expr<BOp, BData> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(linalg::swap(implementation::expressions::make_matrix_expression(A), B))) { linalg::swap(implementation::expressions::make_matrix_expression(A), B); } template<typename T, int ARows, int ACols, typename AST, bool AMO, int BRows, int BCols, typename BST, bool BMO> void swap(base_matrix<T, ARows, ACols, AST, AMO> & A, base_matrix<T, BRows, BCols, BST, BMO> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(linalg::swap(implementation::expressions::make_matrix_expression(A), implementation::expressions::make_matrix_expression(B)))) { linalg::swap(implementation::expressions::make_matrix_expression(A), implementation::expressions::make_matrix_expression(B)); } ///@} //////////////////////////////////////////////////////////////////////////////////////////////////// //// assignment //////////////////////////////////////////////////////////////////////////////////////////////////// /**@{ \name Assignment functions. */ namespace implementation { template<template<typename SourceData> class SourceOp, typename SourceData, template<typename DestData> class DestOp, typename DestData> inline void assign_impl(const expressions::expr<DestOp, DestData> & destination, const expressions::expr<SourceOp, SourceData> & source, helper::BoolToType<false>) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(destination.enumerate()) && noexcept(source.enumerate()) && noexcept(helper::make_type_lvalue<typename expressions::expr<DestOp, DestData>::Enumerator>().has_current()) && noexcept(helper::make_type_lvalue<typename expressions::expr<DestOp, DestData>::Enumerator>().next()) && noexcept(helper::make_type_lvalue<typename expressions::expr<SourceOp, SourceData>::ConstEnumerator>().next()) && noexcept(helper::make_type_lvalue<typename expressions::expr<DestOp, DestData>::Enumerator>().current() = helper::make_type_lvalue<typename expressions::expr<SourceOp, SourceData>::ConstEnumerator>().current())) { PLLL_DEBUG_OUTPUT_MESSAGE("assign_impl(" << getAddress(destination) << " " << getAddress(source) << ") [1-1]"); typename expressions::expr<DestOp, DestData>::Enumerator eDest = destination.enumerate(); typename expressions::expr<SourceOp, SourceData>::ConstEnumerator eSrc = source.enumerate(); for (; eDest.has_current(); eDest.next(), eSrc.next()) eDest.current() = eSrc.current(); } #if __cplusplus >= 201103L template<template<typename SourceData> class SourceOp, typename SourceData, template<typename DestData> class DestOp, typename DestData> inline void assign_impl(const expressions::expr<DestOp, DestData> & destination, const expressions::expr<SourceOp, SourceData> & source, helper::BoolToType<true> move) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(destination.enumerate()) && noexcept(source.enumerate()) && noexcept(helper::make_type_lvalue<typename expressions::expr<DestOp, DestData>::Enumerator>().has_current()) && noexcept(helper::make_type_lvalue<typename expressions::expr<DestOp, DestData>::Enumerator>().next()) && noexcept(helper::make_type_lvalue<typename expressions::expr<SourceOp, SourceData>::ConstEnumerator>().next()) && (MatrixInfo<expressions::expr<SourceOp, SourceData> >::can_move_from ? noexcept(helper::make_type_lvalue<typename expressions::expr<DestOp, DestData>::Enumerator>().current() = std::move(helper::make_type_lvalue<typename expressions::expr<SourceOp, SourceData>::ConstEnumerator>().current())) : noexcept(helper::make_type_lvalue<typename expressions::expr<DestOp, DestData>::Enumerator>().current() = helper::make_type_lvalue<typename expressions::expr<SourceOp, SourceData>::ConstEnumerator>().current()))) { PLLL_DEBUG_OUTPUT_MESSAGE("assign_impl(" << getAddress(destination) << " " << getAddress(source) << ") [1-1]"); typename expressions::expr<DestOp, DestData>::Enumerator eDest = destination.enumerate(); typename expressions::expr<SourceOp, SourceData>::ConstEnumerator eSrc = source.enumerate(); for (; eDest.has_current(); eDest.next(), eSrc.next()) if (MatrixInfo<expressions::expr<SourceOp, SourceData> >::can_move_from) eDest.current() = std::move(eSrc.current()); else eDest.current() = eSrc.current(); } #else template<template<typename SourceData> class SourceOp, typename SourceData, template<typename DestData> class DestOp, typename DestData> inline void assign_impl(const expressions::expr<DestOp, DestData> & destination, const expressions::expr<SourceOp, SourceData> & source, helper::BoolToType<true> move) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(destination.enumerate()) && noexcept(source.enumerate()) && noexcept(helper::make_type_lvalue<typename expressions::expr<DestOp, DestData>::Enumerator>().has_current()) && noexcept(helper::make_type_lvalue<typename expressions::expr<DestOp, DestData>::Enumerator>().next()) && noexcept(helper::make_type_lvalue<typename expressions::expr<SourceOp, SourceData>::ConstEnumerator>().next()) && noexcept(helper::make_type_lvalue<typename expressions::expr<DestOp, DestData>::Enumerator>().current() = helper::make_type_lvalue<typename expressions::expr<SourceOp, SourceData>::ConstEnumerator>().current())) { PLLL_DEBUG_OUTPUT_MESSAGE("assign_impl(" << getAddress(destination) << " " << getAddress(source) << ") [1-1]"); typename expressions::expr<DestOp, DestData>::Enumerator eDest = destination.enumerate(); typename expressions::expr<SourceOp, SourceData>::ConstEnumerator eSrc = source.enumerate(); for (; eDest.has_current(); eDest.next(), eSrc.next()) { eDest.current() = eSrc.current(); // TODO: add "compatibility move" !!! ??? ... } } #endif template<template<typename SourceData> class SourceOp, typename SourceData, template<typename DestData> class DestOp, typename DestData> void assign_impl_resize(const expressions::expr<DestOp, DestData> & destination, const expressions::expr<SourceOp, SourceData> & source, helper::BoolToType<true> move, helper::BoolToType<true> canresize) { #if __cplusplus >= 201103L destination.move_resize(std::move(source)); #else destination.move_resize(source); #endif } template<template<typename SourceData> class SourceOp, typename SourceData, template<typename DestData> class DestOp, typename DestData> void assign_impl_resize(const expressions::expr<DestOp, DestData> & destination, const expressions::expr<SourceOp, SourceData> & source, helper::BoolToType<false> move, helper::BoolToType<true> canresize) { destination.assign_resize(source); } template<template<typename SourceData> class SourceOp, typename SourceData, template<typename DestData> class DestOp, typename DestData, bool move> void assign_impl_resize(const expressions::expr<DestOp, DestData> & destination, const expressions::expr<SourceOp, SourceData> & source, helper::BoolToType<move>, helper::BoolToType<false> canresize) { assert(!"Trying to resize a matrix object which is not resizeable!"); } template<template<typename SourceData> class SourceOp, typename SourceData, template<typename DestData> class DestOp, typename DestData, bool move> void assign_with_temporary(const expressions::expr<DestOp, DestData> & destination, const expressions::expr<SourceOp, SourceData> & source, helper::BoolToType<move> ittm, helper::BoolToType<true> with_temporary) { if (destination.test_involvement(source)) assign_impl(destination, make_matrix_temporary_expression(source), helper::BoolToType<true>()); else assign_impl(destination, source, ittm); } template<template<typename SourceData> class SourceOp, typename SourceData, template<typename DestData> class DestOp, typename DestData, bool move> void assign_with_temporary(const expressions::expr<DestOp, DestData> & destination, const expressions::expr<SourceOp, SourceData> & source, helper::BoolToType<move> ittm, helper::BoolToType<false> with_temporary) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(assign_impl(destination, source, ittm))) { assign_impl(destination, source, ittm); } } template<template<typename SourceData> class SourceOp, typename SourceData, template<typename DestData> class DestOp, typename DestData, bool move> void assign(const implementation::expressions::expr<DestOp, DestData> & destination, const implementation::expressions::expr<SourceOp, SourceData> & source, helper::BoolToType<move> ittm) { PLLL_DEBUG_OUTPUT_MESSAGE("assign(" << getAddress(destination) << " " << getAddress(source) << ") [1]"); PLLL_INTERNAL_STATIC_CHECK((!implementation::MatrixInfo<implementation::expressions::expr<DestOp, DestData> >::is_const), DestinationShouldNotBeConst); PLLL_INTERNAL_STATIC_CHECK((implementation::MatrixInfo<implementation::expressions::expr<DestOp, DestData> >::rows < 0) || (implementation::MatrixInfo<implementation::expressions::expr<SourceOp, SourceData> >::rows < 0) || (static_cast<int>(implementation::MatrixInfo<implementation::expressions::expr<DestOp, DestData> >::rows) == static_cast<int>(implementation::MatrixInfo<implementation::expressions::expr<SourceOp, SourceData> >::rows)) || ((static_cast<int>(implementation::MatrixInfo<implementation::expressions::expr<DestOp, DestData> >::rows) != static_cast<int>(implementation::MatrixInfo<implementation::expressions::expr<SourceOp, SourceData> >::rows)) && implementation::MatrixInfo<implementation::expressions::expr<DestOp, DestData> >::can_resize_rows), NeedToResizeRowsOfDestination); PLLL_INTERNAL_STATIC_CHECK((implementation::MatrixInfo<implementation::expressions::expr<DestOp, DestData> >::cols < 0) || (implementation::MatrixInfo<implementation::expressions::expr<SourceOp, SourceData> >::cols < 0) || (static_cast<int>(implementation::MatrixInfo<implementation::expressions::expr<DestOp, DestData> >::cols) == static_cast<int>(implementation::MatrixInfo<implementation::expressions::expr<SourceOp, SourceData> >::cols)) || ((static_cast<int>(implementation::MatrixInfo<implementation::expressions::expr<DestOp, DestData> >::cols) != static_cast<int>(implementation::MatrixInfo<implementation::expressions::expr<SourceOp, SourceData> >::cols)) && implementation::MatrixInfo<implementation::expressions::expr<DestOp, DestData> >::can_resize_cols), NeedToResizeColsOfDestination); assert((destination.rows() == source.rows()) || (implementation::MatrixInfo<implementation::expressions::expr<DestOp, DestData> >::can_resize_rows)); assert((destination.cols() == source.cols()) || (implementation::MatrixInfo<implementation::expressions::expr<DestOp, DestData> >::can_resize_cols)); if ((destination.rows() != source.rows()) || (destination.cols() != source.cols())) implementation::assign_impl_resize(destination, source, helper::BoolToType<move && implementation::MatrixInfo<implementation::expressions::expr<SourceOp, SourceData> >::can_move_from>(), helper::BoolToType<implementation::MatrixInfo<implementation::expressions::expr<DestOp, DestData> >::can_resize_rows || implementation::MatrixInfo<implementation::expressions::expr<DestOp, DestData> >::can_resize_cols>()); else implementation::assign_with_temporary(destination, source, ittm, helper::BoolToType<implementation::MatrixInfo<implementation::expressions::expr<SourceOp, SourceData> >::use_temporary_on_evaluate>()); } template<template<typename SourceData> class SourceOp, typename SourceData, template<typename DestData> class DestOp, typename DestData> inline void assign(const implementation::expressions::expr<DestOp, DestData> & destination, const implementation::expressions::expr<SourceOp, SourceData> & source) { assign(destination, source, helper::BoolToType<false>()); } template<typename SourceT, int SourceRows, int SourceCols, typename SourceST, bool SourceMO, template<typename DestData> class DestOp, typename DestData> inline void assign(const implementation::expressions::expr<DestOp, DestData> & destination, const base_matrix<SourceT, SourceRows, SourceCols, SourceST, SourceMO> & source) { PLLL_DEBUG_OUTPUT_MESSAGE("assign(" << getAddress(destination) << " " << getAddress(source) << ") [2]"); assign(destination, implementation::expressions::make_matrix_expression(source)); } template<template<typename SourceData> class SourceOp, typename SourceData, typename DestT, int DestRows, int DestCols, typename DestST, bool DestMO> inline void assign(base_matrix<DestT, DestRows, DestCols, DestST, DestMO> & destination, const implementation::expressions::expr<SourceOp, SourceData> & source) { PLLL_DEBUG_OUTPUT_MESSAGE("assign(" << getAddress(destination) << " " << getAddress(source) << ") [3]"); assign(implementation::expressions::make_matrix_expression(destination), source); } template<typename SourceT, int SourceRows, int SourceCols, typename SourceST, bool SourceMO, typename DestT, int DestRows, int DestCols, typename DestST, bool DestMO> inline void assign(base_matrix<DestT, DestRows, DestCols, DestST, DestMO> & destination, const base_matrix<SourceT, SourceRows, SourceCols, SourceST, SourceMO> & source) { PLLL_DEBUG_OUTPUT_MESSAGE("assign(" << getAddress(destination) << " " << getAddress(source) << ") [4]"); assign(implementation::expressions::make_matrix_expression(destination), implementation::expressions::make_matrix_expression(source)); } #if __cplusplus >= 201103L template<typename SourceT, int SourceRows, int SourceCols, typename SourceST, bool SourceMO, template<typename DestData> class DestOp, typename DestData> inline void assign(const implementation::expressions::expr<DestOp, DestData> & destination, base_matrix<SourceT, SourceRows, SourceCols, SourceST, SourceMO> && source) { PLLL_DEBUG_OUTPUT_MESSAGE("assign(" << getAddress(destination) << " " << getAddress(source) << ") [2]"); assign(destination, implementation::expressions::make_matrix_expression(source), helper::BoolToType<true>()); } template<typename SourceT, int SourceRows, int SourceCols, typename SourceST, bool SourceMO, typename DestT, int DestRows, int DestCols, typename DestST, bool DestMO> inline void assign(base_matrix<DestT, DestRows, DestCols, DestST, DestMO> & destination, base_matrix<SourceT, SourceRows, SourceCols, SourceST, SourceMO> && source) { PLLL_DEBUG_OUTPUT_MESSAGE("assign(" << getAddress(destination) << " " << getAddress(source) << ") [4]"); assign(implementation::expressions::make_matrix_expression(destination), implementation::expressions::make_matrix_expression(source), helper::BoolToType<true>()); } #endif ///@} //////////////////////////////////////////////////////////////////////////////////////////////////// //// transpose (functional) //////////////////////////////////////////////////////////////////////////////////////////////////// /**@{ \name Transpose functions. */ template<template<typename SourceData> class SourceOp, typename SourceData, template<typename DestData> class DestOp, typename DestData, bool move> inline void transpose(const implementation::expressions::expr<DestOp, DestData> & destination, const implementation::expressions::expr<SourceOp, SourceData> & source, helper::BoolToType<move> ittm) { if (implementation::expressions::expr<SourceOp, SourceData>::has_direct_access) assign(implementation::expressions::expr<implementation::expressions::transpose, implementation::expressions::expr<DestOp, DestData> >(destination), source, ittm); else assign(destination, implementation::expressions::expr<implementation::expressions::transpose, implementation::expressions::expr<SourceOp, SourceData> >(source), ittm); } template<template<typename SourceData> class SourceOp, typename SourceData, template<typename DestData> class DestOp, typename DestData> inline void transpose(const implementation::expressions::expr<DestOp, DestData> & destination, const implementation::expressions::expr<SourceOp, SourceData> & source) { transpose(destination, source, helper::BoolToType<false>()); } template<typename SourceT, int SourceRows, int SourceCols, typename SourceST, bool SourceMO, template<typename DestData> class DestOp, typename DestData> inline void transpose(const implementation::expressions::expr<DestOp, DestData> & destination, const base_matrix<SourceT, SourceRows, SourceCols, SourceST, SourceMO> & source) { PLLL_DEBUG_OUTPUT_MESSAGE("transpose(" << getAddress(destination) << " " << getAddress(source) << ") [2]"); transpose(destination, implementation::expressions::make_matrix_expression(source)); } template<template<typename SourceData> class SourceOp, typename SourceData, typename DestT, int DestRows, int DestCols, typename DestST, bool DestMO> inline void transpose(base_matrix<DestT, DestRows, DestCols, DestST, DestMO> & destination, const implementation::expressions::expr<SourceOp, SourceData> & source) { PLLL_DEBUG_OUTPUT_MESSAGE("transpose(" << getAddress(destination) << " " << getAddress(source) << ") [3]"); transpose(implementation::expressions::make_matrix_expression(destination), source); } template<typename SourceT, int SourceRows, int SourceCols, typename SourceST, bool SourceMO, typename DestT, int DestRows, int DestCols, typename DestST, bool DestMO> inline void transpose(base_matrix<DestT, DestRows, DestCols, DestST, DestMO> & destination, const base_matrix<SourceT, SourceRows, SourceCols, SourceST, SourceMO> & source) { PLLL_DEBUG_OUTPUT_MESSAGE("transpose(" << getAddress(destination) << " " << getAddress(source) << ") [4]"); transpose(implementation::expressions::make_matrix_expression(destination), implementation::expressions::make_matrix_expression(source)); } #if __cplusplus >= 201103L template<typename SourceT, int SourceRows, int SourceCols, typename SourceST, bool SourceMO, template<typename DestData> class DestOp, typename DestData> inline void transpose(const implementation::expressions::expr<DestOp, DestData> & destination, base_matrix<SourceT, SourceRows, SourceCols, SourceST, SourceMO> && source) { PLLL_DEBUG_OUTPUT_MESSAGE("transpose(" << getAddress(destination) << " " << getAddress(source) << ") [2]"); transpose(destination, implementation::expressions::make_matrix_expression(source), helper::BoolToType<true>()); } template<typename SourceT, int SourceRows, int SourceCols, typename SourceST, bool SourceMO, typename DestT, int DestRows, int DestCols, typename DestST, bool DestMO> inline void transpose(base_matrix<DestT, DestRows, DestCols, DestST, DestMO> & destination, base_matrix<SourceT, SourceRows, SourceCols, SourceST, SourceMO> && source) { PLLL_DEBUG_OUTPUT_MESSAGE("transpose(" << getAddress(destination) << " " << getAddress(source) << ") [4]"); transpose(implementation::expressions::make_matrix_expression(destination), implementation::expressions::make_matrix_expression(source), helper::BoolToType<true>()); } #endif ///@} //////////////////////////////////////////////////////////////////////////////////////////////////// //// (usual) operators //////////////////////////////////////////////////////////////////////////////////////////////////// /**@{ \name Operators. */ // Operations: base_matrix [op] other /** \brief Computes the product of `A` with `B`. \param A A matrix. \param B A matrix or scalar. \return The product of `A` and `B`. */ template<typename T, int Rows, int Cols, typename ST, typename MT> inline typename implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::Mul_ReturnType operator * (const base_matrix<T, Rows, Cols, ST, true> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::multiply(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator * (" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::multiply(A, B); } /** \brief Computes the product of `A` with `B`. \param A A scalar. \param B A matrix. \return The product of `A` and `B`. */ template<typename T, int Rows, int Cols, typename ST> inline typename implementation::BinaryMatrixOperationImpl<T, base_matrix<T, Rows, Cols, ST, true> >::Mul_ReturnType operator * (const T & A, const base_matrix<T, Rows, Cols, ST, true> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::BinaryMatrixOperationImpl<T, base_matrix<T, Rows, Cols, ST, true> >::multiply(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator * (" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::BinaryMatrixOperationImpl<T, base_matrix<T, Rows, Cols, ST, true> >::multiply(A, B); } /** \brief Computes the componentwise division of `A` with the scalar `B`. \param A A matrix. \param B A scalar. \return The componentwise division of `A` by `B`. */ template<typename T, int Rows, int Cols, typename ST, typename MT> inline typename implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::Div_ReturnType operator / (const base_matrix<T, Rows, Cols, ST, true> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::divide(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator / (" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::divide(A, B); } /** \brief Computes the componentwise modulo of `A` with the scalar `B`. \param A A matrix. \param B A scalar. \return The componentwise modulo of `A` by `B`. */ template<typename T, int Rows, int Cols, typename ST, typename MT> inline typename implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::Mod_ReturnType operator % (const base_matrix<T, Rows, Cols, ST, true> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::modulo(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator % (" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::modulo(A, B); } /** \brief Computes the componentwise multiplication of `A` with `B`. \param A A matrix. \param B A matrix. \return The componentwise multiplication of `A` and `B`. */ template<typename T, int Rows, int Cols, typename ST, typename MT> inline typename implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::CwMul_ReturnType componentwise_mul(const base_matrix<T, Rows, Cols, ST, true> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::componentwise_mul(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("componentwise_mul(" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::componentwise_mul(A, B); } /** \brief Computes the componentwise division of `A` with `B`. \param A A matrix. \param B A matrix. \return The componentwise division of `A` by `B`. */ template<typename T, int Rows, int Cols, typename ST, typename MT> inline typename implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::CwDiv_ReturnType componentwise_div(const base_matrix<T, Rows, Cols, ST, true> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::componentwise_div(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("componentwise_div(" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::componentwise_div(A, B); } /** \brief Computes the componentwise modulo of `A` with `B`. \param A A matrix. \param B A matrix. \return The componentwise modulo of `A` by `B`. */ template<typename T, int Rows, int Cols, typename ST, typename MT> inline typename implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::CwMod_ReturnType componentwise_mod(const base_matrix<T, Rows, Cols, ST, true> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::componentwise_mod(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("componentwise_mod(" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::componentwise_mod(A, B); } /** \brief Computes the sum of `A` and `B`. \param A A matrix. \param B A matrix. \return The sum of `A` and `B`. */ template<typename T, int Rows, int Cols, typename ST, typename MT> inline typename implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::Add_ReturnType operator + (const base_matrix<T, Rows, Cols, ST, true> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::add(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator + (" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::add(A, B); } /** \brief Computes the difference of `A` and `B`. \param A A matrix. \param B A matrix. \return The difference of `A` and `B`. */ template<typename T, int Rows, int Cols, typename ST, typename MT> inline typename implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::Sub_ReturnType operator - (const base_matrix<T, Rows, Cols, ST, true> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::sub(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator - (" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::BinaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::sub(A, B); } /** \brief Computes the negation of `A`. \param A A matrix. \return The componentwise negation of `A`. */ template<typename T, int Rows, int Cols, typename ST> inline typename implementation::UnaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true> >::Neg_ReturnType operator - (const base_matrix<T, Rows, Cols, ST, true> & A) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::UnaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true> >::negate(A))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator - (" << getAddress(A) << ")"); return implementation::UnaryMatrixOperationImpl<base_matrix<T, Rows, Cols, ST, true> >::negate(A); } // Operations: implementation::expressions::expr [op] other template<template<typename DataType> class Operator, typename Data, typename MT> inline typename implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::Mul_ReturnType operator * (const implementation::expressions::expr<Operator, Data> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::multiply(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator * (" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::multiply(A, B); } template<template<typename DataType> class Operator, typename Data> inline typename implementation::BinaryMatrixOperationImpl<typename implementation::MatrixInfo<implementation::expressions::expr<Operator, Data> >::Type, implementation::expressions::expr<Operator, Data> >::Mul_ReturnType operator * (const typename implementation::MatrixInfo<implementation::expressions::expr<Operator, Data> >::Type & A, const implementation::expressions::expr<Operator, Data> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::BinaryMatrixOperationImpl< typename implementation::MatrixInfo<implementation::expressions::expr<Operator, Data> >::Type, implementation::expressions::expr<Operator, Data> >::multiply(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator * (" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::BinaryMatrixOperationImpl<typename implementation::MatrixInfo<implementation::expressions::expr<Operator, Data> >::Type, implementation::expressions::expr<Operator, Data> >::multiply(A, B); } template<template<typename DataType> class Operator, typename Data, typename MT> inline typename implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::Div_ReturnType operator / (const implementation::expressions::expr<Operator, Data> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::divide(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator / (" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::divide(A, B); } template<template<typename DataType> class Operator, typename Data, typename MT> inline typename implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::Mod_ReturnType operator % (const implementation::expressions::expr<Operator, Data> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::modulo(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator % (" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::modulo(A, B); } template<template<typename DataType> class Operator, typename Data, typename MT> inline typename implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::CwMul_ReturnType componentwise_mul(const implementation::expressions::expr<Operator, Data> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::componentwise_mul(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("componentwise_mul(" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::componentwise_mul(A, B); } template<template<typename DataType> class Operator, typename Data, typename MT> inline typename implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::CwDiv_ReturnType componentwise_div(const implementation::expressions::expr<Operator, Data> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::componentwise_div(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("componentwise_div(" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::componentwise_div(A, B); } template<template<typename DataType> class Operator, typename Data, typename MT> inline typename implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::CwMod_ReturnType componentwise_mod(const implementation::expressions::expr<Operator, Data> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::componentwise_mod(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("componentwise_mod(" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::componentwise_mod(A, B); } template<template<typename DataType> class Operator, typename Data, typename MT> inline typename implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::Add_ReturnType operator + (const implementation::expressions::expr<Operator, Data> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::add(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator + (" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::add(A, B); } template<template<typename DataType> class Operator, typename Data, typename MT> inline typename implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::Mul_ReturnType operator - (const implementation::expressions::expr<Operator, Data> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::sub(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator - (" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::BinaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data>, MT>::sub(A, B); } template<template<typename DataType> class Operator, typename Data> inline typename implementation::UnaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data> >::Neg_ReturnType operator - (const implementation::expressions::expr<Operator, Data> & A) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::UnaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data> >::negate(A))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator - (" << getAddress(A) << ")"); return implementation::UnaryMatrixOperationImpl<implementation::expressions::expr<Operator, Data> >::negate(A); } ///@} //////////////////////////////////////////////////////////////////////////////////////////////////// //// functional versions of operators, i.e. something along "void op(result, opA, ...)" //////////////////////////////////////////////////////////////////////////////////////////////////// /**@{ \name Functional versions of operators. */ // Operations: base_matrix [op] other /** \brief Computes the product of `A` and `B` and stores the result in `result`. \param result The variable to store the result in. \param A The first operand. \param B The second operand. */ template<typename T, int Rows, int Cols, typename ST, typename MT1, typename MT2> void mul(base_matrix<T, Rows, Cols, ST, true> & result, const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::multiply(A, B)))) { PLLL_DEBUG_OUTPUT_MESSAGE("mul(" << getAddress(result) << " " << getAddress(A) << " " << getAddress(B) << ")"); assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::multiply(A, B)); } /** \brief Computes the componentwise division of `A` by `B` and stores the result in `result`. \param result The variable to store the result in. \param A The first operand. Must be a matrix. \param B The second operand. Must be a scalar. */ template<typename T, int Rows, int Cols, typename ST, typename MT1, typename MT2> void div(base_matrix<T, Rows, Cols, ST, true> & result, const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::divide(A, B)))) { PLLL_DEBUG_OUTPUT_MESSAGE("div(" << getAddress(result) << " " << getAddress(A) << " " << getAddress(B) << ")"); assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::divide(A, B)); } /** \brief Computes the componentwise modulo of `A` by `B` and stores the result in `result`. \param result The variable to store the result in. \param A The first operand. Must be a matrix. \param B The second operand. Must be a scalar. */ template<typename T, int Rows, int Cols, typename ST, typename MT1, typename MT2> void mod(base_matrix<T, Rows, Cols, ST, true> & result, const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::modulo(A, B)))) { PLLL_DEBUG_OUTPUT_MESSAGE("mod(" << getAddress(result) << " " << getAddress(A) << " " << getAddress(B) << ")"); assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::modulo(A, B)); } /** \brief Computes the componentwise product of `A` and `B` and stores the result in `result`. \param result The variable to store the result in. \param A The first operand. Must be a matrix. \param B The second operand. Must be a matrix. */ template<typename T, int Rows, int Cols, typename ST, typename MT1, typename MT2> void componentwise_mul(base_matrix<T, Rows, Cols, ST, true> & result, const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::componentwise_mul(A, B)))) { PLLL_DEBUG_OUTPUT_MESSAGE("componentwise_mul(" << getAddress(result) << " " << getAddress(A) << " " << getAddress(B) << ")"); assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::componentwise_mul(A, B)); } /** \brief Computes the componentwise division of `A` by `B` and stores the result in `result`. \param result The variable to store the result in. \param A The first operand. Must be a matrix. \param B The second operand. Must be a matrix. */ template<typename T, int Rows, int Cols, typename ST, typename MT1, typename MT2> void componentwise_div(base_matrix<T, Rows, Cols, ST, true> & result, const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::componentwise_div(A, B)))) { PLLL_DEBUG_OUTPUT_MESSAGE("componentwise_div(" << getAddress(result) << " " << getAddress(A) << " " << getAddress(B) << ")"); assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::componentwise_div(A, B)); } /** \brief Computes the componentwise modulo of `A` by `B` and stores the result in `result`. \param result The variable to store the result in. \param A The first operand. Must be a matrix. \param B The second operand. Must be a matrix. */ template<typename T, int Rows, int Cols, typename ST, typename MT1, typename MT2> void componentwise_mod(base_matrix<T, Rows, Cols, ST, true> & result, const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::componentwise_mod(A, B)))) { PLLL_DEBUG_OUTPUT_MESSAGE("componentwise_mod(" << getAddress(result) << " " << getAddress(A) << " " << getAddress(B) << ")"); assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::componentwise_mod(A, B)); } /** \brief Computes the sum of `A` and `B` and stores the result in `result`. \param result The variable to store the result in. \param A The first operand. Must be a matrix. \param B The second operand. Must be a matrix. */ template<typename T, int Rows, int Cols, typename ST, typename MT1, typename MT2> void add(base_matrix<T, Rows, Cols, ST, true> & result, const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::add(A, B)))) { PLLL_DEBUG_OUTPUT_MESSAGE("add(" << getAddress(result) << " " << getAddress(A) << " " << getAddress(B) << ")"); assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::add(A, B)); } /** \brief Computes the difference of `A` and `B` and stores the result in `result`. \param result The variable to store the result in. \param A The first operand. Must be a matrix. \param B The second operand. Must be a matrix. */ template<typename T, int Rows, int Cols, typename ST, typename MT1, typename MT2> void sub(base_matrix<T, Rows, Cols, ST, true> & result, const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::sub(A, B)))) { PLLL_DEBUG_OUTPUT_MESSAGE("sub(" << getAddress(result) << " " << getAddress(A) << " " << getAddress(B) << ")"); assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::sub(A, B)); } /** \brief Computes the negation of `A` and stores the result in `result`. \param result The variable to store the result in. \param A The operand. Must be a matrix. */ template<typename T, int Rows, int Cols, typename ST, typename MT> void neg(base_matrix<T, Rows, Cols, ST, true> & result, const MT & A) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(assign(result, implementation::UnaryMatrixOperationImpl<MT>::negate(A)))) { PLLL_DEBUG_OUTPUT_MESSAGE("neg(" << getAddress(result) << " " << getAddress(A) << ")"); assign(result, implementation::UnaryMatrixOperationImpl<MT>::negate(A)); } // Operations: implementation::expressions::expr [op] other template<template<typename DataType> class Operator, typename Data, typename MT1, typename MT2> void mul(const implementation::expressions::expr<Operator, Data> & result, const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::multiply(A, B)))) { PLLL_DEBUG_OUTPUT_MESSAGE("mul(" << getAddress(result) << " " << getAddress(A) << " " << getAddress(B) << ")"); assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::multiply(A, B)); } template<template<typename DataType> class Operator, typename Data, typename MT1, typename MT2> void div(const implementation::expressions::expr<Operator, Data> & result, const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::divide(A, B)))) { PLLL_DEBUG_OUTPUT_MESSAGE("div(" << getAddress(result) << " " << getAddress(A) << " " << getAddress(B) << ")"); assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::divide(A, B)); } template<template<typename DataType> class Operator, typename Data, typename MT1, typename MT2> void mod(const implementation::expressions::expr<Operator, Data> & result, const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::modulo(A, B)))) { PLLL_DEBUG_OUTPUT_MESSAGE("mod(" << getAddress(result) << " " << getAddress(A) << " " << getAddress(B) << ")"); assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::modulo(A, B)); } template<template<typename DataType> class Operator, typename Data, typename MT1, typename MT2> void componentwise_mul(const implementation::expressions::expr<Operator, Data> & result, const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::componentwise_mul(A, B)))) { PLLL_DEBUG_OUTPUT_MESSAGE("componentwise_mul(" << getAddress(result) << " " << getAddress(A) << " " << getAddress(B) << ")"); assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::componentwise_mul(A, B)); } template<template<typename DataType> class Operator, typename Data, typename MT1, typename MT2> void componentwise_div(const implementation::expressions::expr<Operator, Data> & result, const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::componentwise_div(A, B)))) { PLLL_DEBUG_OUTPUT_MESSAGE("componentwise_div(" << getAddress(result) << " " << getAddress(A) << " " << getAddress(B) << ")"); assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::componentwise_div(A, B)); } template<template<typename DataType> class Operator, typename Data, typename MT1, typename MT2> void componentwise_mod(const implementation::expressions::expr<Operator, Data> & result, const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::componentwise_mod(A, B)))) { PLLL_DEBUG_OUTPUT_MESSAGE("componentwise_mod(" << getAddress(result) << " " << getAddress(A) << " " << getAddress(B) << ")"); assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::componentwise_mod(A, B)); } template<template<typename DataType> class Operator, typename Data, typename MT1, typename MT2> void add(const implementation::expressions::expr<Operator, Data> & result, const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::add(A, B)))) { PLLL_DEBUG_OUTPUT_MESSAGE("add(" << getAddress(result) << " " << getAddress(A) << " " << getAddress(B) << ")"); assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::add(A, B)); } template<template<typename DataType> class Operator, typename Data, typename MT1, typename MT2> void sub(const implementation::expressions::expr<Operator, Data> & result, const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::sub(A, B)))) { PLLL_DEBUG_OUTPUT_MESSAGE("sub(" << getAddress(result) << " " << getAddress(A) << " " << getAddress(B) << ")"); assign(result, implementation::BinaryMatrixOperationImpl<MT1, MT2>::sub(A, B)); } template<template<typename DataType> class Operator, typename Data, typename MT> void neg(const implementation::expressions::expr<Operator, Data> & result, const MT & A) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(assign(result, implementation::UnaryMatrixOperationImpl<MT>::negate(A)))) { PLLL_DEBUG_OUTPUT_MESSAGE("neg(" << getAddress(result) << " " << getAddress(A) << ")"); assign(result, implementation::UnaryMatrixOperationImpl<MT>::negate(A)); } ///@} //////////////////////////////////////////////////////////////////////////////////////////////////// //// (usual) assignment-operation operators //////////////////////////////////////////////////////////////////////////////////////////////////// /**@{ \name Assignment-operation operators. */ // Operations: base_matrix [op]= other /** \brief Adds `B` to the current matrix. \param A The current matrix. \param B The matrix to add to the current matrix. \return A reference to the current matrix. */ template<typename T, int Rows, int Cols, typename ST, typename MT> inline base_matrix<T, Rows, Cols, ST, true> & operator += (base_matrix<T, Rows, Cols, ST, true> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::expressions::make_matrix_expression(A) += B)) { PLLL_DEBUG_OUTPUT_MESSAGE("operator += (" << getAddress(A) << " " << getAddress(B) << ")"); implementation::expressions::make_matrix_expression(A) += B; return A; } /** \brief Subtracts `B` from the current matrix. \param A The current matrix. \param B The matrix to subtract from the current matrix. \return A reference to the current matrix. */ template<typename T, int Rows, int Cols, typename ST, typename MT> inline base_matrix<T, Rows, Cols, ST, true> & operator -= (base_matrix<T, Rows, Cols, ST, true> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::expressions::make_matrix_expression(A) -= B)) { PLLL_DEBUG_OUTPUT_MESSAGE("operator -= (" << getAddress(A) << " " << getAddress(B) << ")"); implementation::expressions::make_matrix_expression(A) -= B; return A; } /** \brief Multiplies the current matrix with `B` and stores the result in the current matrix. \param A The current matrix. \param B The matrix or scalar to multiply with. \return A reference to the current matrix. */ template<typename T, int Rows, int Cols, typename ST, typename MT> inline base_matrix<T, Rows, Cols, ST, true> & operator *= (base_matrix<T, Rows, Cols, ST, true> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::expressions::make_matrix_expression(A) *= B)) { PLLL_DEBUG_OUTPUT_MESSAGE("operator *= (" << getAddress(A) << " " << getAddress(B) << ")"); implementation::expressions::make_matrix_expression(A) *= B; return A; } /** \brief Divides the current matrix by the scalar `B` and stores the result in the current matrix. \param A The current matrix. \param B The scalar to divide by. \return A reference to the current matrix. */ template<typename T, int Rows, int Cols, typename ST, typename MT> inline base_matrix<T, Rows, Cols, ST, true> & operator /= (base_matrix<T, Rows, Cols, ST, true> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::expressions::make_matrix_expression(A) /= B)) { PLLL_DEBUG_OUTPUT_MESSAGE("operator /= (" << getAddress(A) << " " << getAddress(B) << ")"); implementation::expressions::make_matrix_expression(A) /= B; return A; } /** \brief Takes the current matrix modulo the scalar `B` and stores the result in the current matrix. \param A The current matrix. \param B The scalar to mod by. \return A reference to the current matrix. */ template<typename T, int Rows, int Cols, typename ST, typename MT> inline base_matrix<T, Rows, Cols, ST, true> & operator %= (base_matrix<T, Rows, Cols, ST, true> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::expressions::make_matrix_expression(A) %= B)) { PLLL_DEBUG_OUTPUT_MESSAGE("operator %= (" << getAddress(A) << " " << getAddress(B) << ")"); implementation::expressions::make_matrix_expression(A) %= B; return A; } // Operations: expr [op]= other template<template<typename DataType> class Op, typename Data, typename MT> inline const implementation::expressions::expr<Op, Data> & operator += (const implementation::expressions::expr<Op, Data> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::AssignmentMatrixOperationImpl<implementation::expressions::expr<Op, Data>, MT>::add_assign(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator += (" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::AssignmentMatrixOperationImpl<implementation::expressions::expr<Op, Data>, MT>::add_assign(A, B); } template<template<typename DataType> class Op, typename Data, typename MT> inline const implementation::expressions::expr<Op, Data> & operator -= (const implementation::expressions::expr<Op, Data> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::AssignmentMatrixOperationImpl<implementation::expressions::expr<Op, Data>, MT>::sub_assign(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator -= (" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::AssignmentMatrixOperationImpl<implementation::expressions::expr<Op, Data>, MT>::sub_assign(A, B); } template<template<typename DataType> class Op, typename Data, typename MT> inline const implementation::expressions::expr<Op, Data> & operator *= (const implementation::expressions::expr<Op, Data> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::AssignmentMatrixOperationImpl<implementation::expressions::expr<Op, Data>, MT>::mul_assign(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator *= (" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::AssignmentMatrixOperationImpl<implementation::expressions::expr<Op, Data>, MT>::mul_assign(A, B); } template<template<typename DataType> class Op, typename Data, typename MT> inline const implementation::expressions::expr<Op, Data> & operator /= (const implementation::expressions::expr<Op, Data> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::AssignmentMatrixOperationImpl<implementation::expressions::expr<Op, Data>, MT>::div_assign(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator /= (" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::AssignmentMatrixOperationImpl<implementation::expressions::expr<Op, Data>, MT>::div_assign(A, B); } template<template<typename DataType> class Op, typename Data, typename MT> inline const implementation::expressions::expr<Op, Data> & operator %= (const implementation::expressions::expr<Op, Data> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::AssignmentMatrixOperationImpl<implementation::expressions::expr<Op, Data>, MT>::mod_assign(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator %= (" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::AssignmentMatrixOperationImpl<implementation::expressions::expr<Op, Data>, MT>::mod_assign(A, B); } ///@} //////////////////////////////////////////////////////////////////////////////////////////////////// //// other operations //////////////////////////////////////////////////////////////////////////////////////////////////// /**@{ \name Other operations. */ // sum: sums all elements in the matrix namespace implementation { template<typename MatrixType> class SumImpl { public: typedef typename MatrixInfo<MatrixType>::Type RetValue; template<typename ReturnType> inline static void sum(ReturnType & result, const MatrixType & A) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(setZero(result)) && noexcept(A.enumerate()) && noexcept(helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().has_current()) && noexcept(helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().next()) && noexcept(helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().get_current(result)) && noexcept(result += helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().current())) { PLLL_DEBUG_OUTPUT_MESSAGE("SumImpl::sum(" << getAddress(result) << " " << getAddress(A) << ")"); PLLL_INTERNAL_STATIC_CHECK(MatrixInfo<MatrixType>::is_matrix && MatrixInfo<MatrixType>::is_math_object, RequiresMathMatrix); if ((A.rows() == 0) || (A.cols() == 0)) setZero(result); else { typename MatrixType::ConstEnumerator e = A.enumerate(); e.get_current(result); for (e.next(); e.has_current(); e.next()) result += e.current(); } } inline static RetValue sum(const MatrixType & A) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(setZero(helper::make_type_lvalue<RetValue>())) && noexcept(A.enumerate()) && noexcept(RetValue()) && noexcept(helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().has_current()) && noexcept(helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().next()) && noexcept(helper::make_type_lvalue<RetValue>() = helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().current()) && noexcept(helper::make_type_lvalue<RetValue>() += helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().current())) { PLLL_DEBUG_OUTPUT_MESSAGE("SumImpl::sum(" << getAddress(A) << ")"); PLLL_INTERNAL_STATIC_CHECK(MatrixInfo<MatrixType>::is_matrix && MatrixInfo<MatrixType>::is_math_object, RequiresMathMatrix); size_type rr = A.rows(), cc = A.cols(); if ((rr == 0) || (cc == 0)) { RetValue result; setZero(result); return result; } else { typename MatrixType::ConstEnumerator e = A.enumerate(); RetValue result = e.current(); for (e.next(); e.has_current(); e.next()) result += e.current(); return result; } } }; } /** \brief Computes the sum of all entries of `A` and stores the result in `result`. \param result A scalar where to compute the result in. \param A The matrix whose entries to sum up. */ template<typename RetType, typename T, int Rows, int Cols, typename ST> void sum(RetType & result, const base_matrix<T, Rows, Cols, ST, true> & A) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::SumImpl<base_matrix<T, Rows, Cols, ST, true> >::sum(result, A))) { PLLL_DEBUG_OUTPUT_MESSAGE("sum(" << getAddress(result) << " " << getAddress(A) << ")"); implementation::SumImpl<base_matrix<T, Rows, Cols, ST, true> >::sum(result, A); } /** \brief Computes the sum of all entries of `A` and returns the result. \return A scalar whose value is the sum of all entries of `A`. \param A The matrix whose entries to sum up. */ template<typename T, int Rows, int Cols, typename ST> typename implementation::SumImpl<base_matrix<T, Rows, Cols, ST, true> >::RetValue sum(const base_matrix<T, Rows, Cols, ST, true> & A) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::SumImpl<base_matrix<T, Rows, Cols, ST, true> >::sum(A))) { PLLL_DEBUG_OUTPUT_MESSAGE("sum(" << getAddress(A) << ")"); return implementation::SumImpl<base_matrix<T, Rows, Cols, ST, true> >::sum(A); } template<typename RetType, template<typename DataType> class Operator, typename Data> void sum(RetType & result, const implementation::expressions::expr<Operator, Data> & A) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::SumImpl<implementation::expressions::expr<Operator, Data> >::sum(result, A))) { PLLL_DEBUG_OUTPUT_MESSAGE("sum(" << getAddress(result) << " " << getAddress(A) << ")"); implementation::SumImpl<implementation::expressions::expr<Operator, Data> >::sum(result, A); } template<template<typename DataType> class Operator, typename Data> typename implementation::SumImpl<implementation::expressions::expr<Operator, Data> >::RetValue sum(const implementation::expressions::expr<Operator, Data> & A) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::SumImpl<implementation::expressions::expr<Operator, Data> >::sum(A))) { PLLL_DEBUG_OUTPUT_MESSAGE("sum(" << getAddress(A) << ")"); return implementation::SumImpl<implementation::expressions::expr<Operator, Data> >::sum(A); } // dot: computes the componentwise product of two matrices and sums over the result namespace implementation { template<typename MatrixType, typename MatrixType2> class DotImpl { public: typedef typename MatrixInfo<MatrixType>::Type RetValue; template<typename ReturnType> inline static void dot(ReturnType & result, const MatrixType & A, const MatrixType2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(noexcept(setZero(result))) && noexcept(A.enumerate()) && noexcept(B.enumerate()) && noexcept(helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().has_current()) && noexcept(helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().next()) && noexcept(helper::make_type_lvalue<typename MatrixType2::ConstEnumerator>().next()) && noexcept(result = helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().current() * helper::make_type_lvalue<typename MatrixType2::ConstEnumerator>().current()) && noexcept(result += helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().current() * helper::make_type_lvalue<typename MatrixType2::ConstEnumerator>().current())) { PLLL_DEBUG_OUTPUT_MESSAGE("DotImpl::dot(" << getAddress(result) << " " << getAddress(A) << " " << getAddress(B) << ")"); PLLL_INTERNAL_STATIC_CHECK(MatrixInfo<MatrixType>::is_matrix && MatrixInfo<MatrixType>::is_math_object, RequiresMathMatrix); PLLL_INTERNAL_STATIC_CHECK(MatrixInfo<MatrixType2>::is_matrix && MatrixInfo<MatrixType2>::is_math_object, RequiresMathMatrix); PLLL_INTERNAL_STATIC_CHECK((MatrixInfo<MatrixType>::rows < 0) || (MatrixInfo<MatrixType2>::rows < 0) || (static_cast<int>(MatrixInfo<MatrixType>::rows) == static_cast<int>(MatrixInfo<MatrixType2>::rows)), FormatsDoNotMatch); PLLL_INTERNAL_STATIC_CHECK((MatrixInfo<MatrixType>::cols < 0) || (MatrixInfo<MatrixType2>::cols < 0) || (static_cast<int>(MatrixInfo<MatrixType>::cols) == static_cast<int>(MatrixInfo<MatrixType2>::cols)), FormatsDoNotMatch); size_type rr = A.rows(), cc = A.cols(); if ((rr == 0) || (cc == 0)) setZero(result); else { typename MatrixType::ConstEnumerator e = A.enumerate(); typename MatrixType2::ConstEnumerator e2 = B.enumerate(); result = e.current() * e2.current(); for (e.next(), e2.next(); e.has_current(); e.next(), e2.next()) result += e.current() * e2.current(); } } inline static RetValue dot(const MatrixType & A, const MatrixType2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(setZero(helper::make_type_lvalue<RetValue>())) && noexcept(A.enumerate()) && noexcept(B.enumerate()) && noexcept(RetValue()) && noexcept(helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().has_current()) && noexcept(helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().next()) && noexcept(helper::make_type_lvalue<typename MatrixType2::ConstEnumerator>().next()) && noexcept(helper::make_type_lvalue<RetValue>() = helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().current() * helper::make_type_lvalue<typename MatrixType2::ConstEnumerator>().current()) && noexcept(helper::make_type_lvalue<RetValue>() += helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().current() * helper::make_type_lvalue<typename MatrixType2::ConstEnumerator>().current())) { PLLL_DEBUG_OUTPUT_MESSAGE("DotImpl::dot(" << getAddress(A) << " " << getAddress(B) << ")"); PLLL_INTERNAL_STATIC_CHECK(MatrixInfo<MatrixType>::is_matrix && MatrixInfo<MatrixType>::is_math_object, RequiresMathMatrix); PLLL_INTERNAL_STATIC_CHECK(MatrixInfo<MatrixType2>::is_matrix && MatrixInfo<MatrixType2>::is_math_object, RequiresMathMatrix); PLLL_INTERNAL_STATIC_CHECK((MatrixInfo<MatrixType>::rows < 0) || (MatrixInfo<MatrixType2>::rows < 0) || (static_cast<int>(MatrixInfo<MatrixType>::rows) == static_cast<int>(MatrixInfo<MatrixType2>::rows)), FormatsDoNotMatch); PLLL_INTERNAL_STATIC_CHECK((MatrixInfo<MatrixType>::cols < 0) || (MatrixInfo<MatrixType2>::cols < 0) || (static_cast<int>(MatrixInfo<MatrixType>::cols) == static_cast<int>(MatrixInfo<MatrixType2>::cols)), FormatsDoNotMatch); size_type rr = A.rows(), cc = A.cols(); if ((rr == 0) || (cc == 0)) { RetValue result; setZero(result); return result; } else { typename MatrixType::ConstEnumerator e = A.enumerate(); typename MatrixType2::ConstEnumerator e2 = B.enumerate(); RetValue result = e.current() * e2.current(); for (e.next(), e2.next(); e.has_current(); e.next(), e2.next()) result += e.current() * e2.current(); return result; } } }; } /** \brief Computes the dot product of `A` and `B` and stores the result in `result`. What this does is componentwise multiplying `A` and `B` and then calling `sum()` of the resulting matrix. \param result A scalar where to compute the result in. \param A The first operand. \param B The second operand. */ template<typename RetType, typename T, int Rows, int Cols, typename ST, typename MT> void dot(RetType & result, const base_matrix<T, Rows, Cols, ST, true> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::DotImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::dot(result, A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("dot(" << getAddress(result) << " " << getAddress(A) << " " << getAddress(B) << ")"); implementation::DotImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::dot(result, A, B); } /** \brief Computes the dot product of `A` and `B` and returns the result. What this does is componentwise multiplying `A` and `B` and then calling `sum()` of the resulting matrix. \return A scalar whose value is the dot product of `A` and `B`. \param A The first operand. \param B The second operand. */ template<typename T, int Rows, int Cols, typename ST, typename MT> typename implementation::DotImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::RetValue dot(const base_matrix<T, Rows, Cols, ST, true> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::DotImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::dot(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("dot(" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::DotImpl<base_matrix<T, Rows, Cols, ST, true>, MT>::dot(A, B); } template<typename RetType, template<typename DataType> class Operator, typename Data, typename MT> void dot(RetType & result, const implementation::expressions::expr<Operator, Data> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::DotImpl<implementation::expressions::expr<Operator, Data>, MT>::dot(result, A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("dot(" << getAddress(result) << " " << getAddress(A) << " " << getAddress(B) << ")"); implementation::DotImpl<implementation::expressions::expr<Operator, Data>, MT>::dot(result, A, B); } template<template<typename DataType> class Operator, typename Data, typename MT> typename implementation::DotImpl<implementation::expressions::expr<Operator, Data>, MT>::RetValue dot(const implementation::expressions::expr<Operator, Data> & A, const MT & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::DotImpl<implementation::expressions::expr<Operator, Data>, MT>::dot(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("dot(" << getAddress(A) << " " << getAddress(B) << ")"); return implementation::DotImpl<implementation::expressions::expr<Operator, Data>, MT>::dot(A, B); } // normSq: computes the squared l^2 norm of the matrix, i.e. sums up the squares of all entries namespace implementation { template<typename MatrixType> class NormSqImpl { public: typedef typename MatrixInfo<MatrixType>::Type RetValue; template<typename ReturnType> inline static void normSq(ReturnType & result, const MatrixType & A) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(setZero(result)) && noexcept(A.enumerate()) && noexcept(helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().has_current()) && noexcept(helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().next()) && noexcept(result = square(helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().current())) && noexcept(result += square(helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().current()))) { PLLL_DEBUG_OUTPUT_MESSAGE("NormSqImpl::normSq(" << getAddress(result) << " " << getAddress(A) << ")"); PLLL_INTERNAL_STATIC_CHECK(MatrixInfo<MatrixType>::is_matrix && MatrixInfo<MatrixType>::is_math_object, RequiresMathMatrix); if ((0 == A.rows()) || (0 == A.cols())) setZero(result); else { typename MatrixType::ConstEnumerator e = A.enumerate(); result = square(e.current()); for (e.next(); e.has_current(); e.next()) result += square(e.current()); } } inline static RetValue normSq(const MatrixType & A) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(setZero(helper::make_type_lvalue<RetValue>())) && noexcept(A.enumerate()) && noexcept(RetValue()) && noexcept(helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().has_current()) && noexcept(helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().next()) && noexcept(RetValue(square(helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().current()))) && noexcept(helper::make_type_lvalue<RetValue>() += square(helper::make_type_lvalue<typename MatrixType::ConstEnumerator>().current()))) { PLLL_DEBUG_OUTPUT_MESSAGE("NormSqImpl::normSq(" << getAddress(A) << ")"); PLLL_INTERNAL_STATIC_CHECK(MatrixInfo<MatrixType>::is_matrix && MatrixInfo<MatrixType>::is_math_object, RequiresMathMatrix); if ((A.rows() == 0) || (A.cols() == 0)) { RetValue result; setZero(result); return result; } else { typename MatrixType::ConstEnumerator e = A.enumerate(); RetValue result = square(e.current()); for (e.next(); e.has_current(); e.next()) result += square(e.current()); return result; } } }; } /** \brief Computes the squared norm of `A`, i.e. the sum of the squares of all entries of `A`, and stores the result in `result`. \param result A scalar where to compute the result in. \param A The matrix whose square norm to compute. */ template<typename RetType, typename T, int Rows, int Cols, typename ST> void normSq(RetType & result, const base_matrix<T, Rows, Cols, ST, true> & A) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::NormSqImpl<base_matrix<T, Rows, Cols, ST, true> >::normSq(result, A))) { PLLL_DEBUG_OUTPUT_MESSAGE("normSq(" << getAddress(result) << " " << getAddress(A) << ")"); implementation::NormSqImpl<base_matrix<T, Rows, Cols, ST, true> >::normSq(result, A); } /** \brief Computes the squared norm of `A`, i.e. the sum of the squares of all entries of `A`, and returns the result. \return A scalar whose value is the squared norm of `A`. \param A The matrix whose square norm to compute. */ template<typename T, int Rows, int Cols, typename ST> typename implementation::NormSqImpl<base_matrix<T, Rows, Cols, ST, true> >::RetValue normSq(const base_matrix<T, Rows, Cols, ST, true> & A) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::NormSqImpl<base_matrix<T, Rows, Cols, ST, true> >::normSq(A))) { PLLL_DEBUG_OUTPUT_MESSAGE("normSq(" << getAddress(A) << ")"); return implementation::NormSqImpl<base_matrix<T, Rows, Cols, ST, true> >::normSq(A); } template<typename RetType, template<typename DataType> class Operator, typename Data> void normSq(RetType & result, const implementation::expressions::expr<Operator, Data> & A) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::NormSqImpl<implementation::expressions::expr<Operator, Data> >::normSq(result, A))) { PLLL_DEBUG_OUTPUT_MESSAGE("normSq(" << getAddress(result) << " " << getAddress(A) << ")"); implementation::NormSqImpl<implementation::expressions::expr<Operator, Data> >::normSq(result, A); } template<template<typename DataType> class Operator, typename Data> typename implementation::NormSqImpl<implementation::expressions::expr<Operator, Data> >::RetValue normSq(const implementation::expressions::expr<Operator, Data> & A) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::NormSqImpl<implementation::expressions::expr<Operator, Data> >::normSq(A))) { PLLL_DEBUG_OUTPUT_MESSAGE("normSq(" << getAddress(A) << ")"); return implementation::NormSqImpl<implementation::expressions::expr<Operator, Data> >::normSq(A); } // addmul() and submul() /** \brief Computes `A += B * C`. \param A The variable to add the product to. \param B The first operand of the product. \param C The second operand of the product. */ template<typename T, int Rows, int Cols, typename ST, typename T1, typename T2> void addmul(base_matrix<T, Rows, Cols, ST, true> & A, const T1 & B, const T2 & C) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(A += B * C)) { A += B * C; } /** \brief Computes `A -= B * C`. \param A The variable to subtract the product from. \param B The first operand of the product. \param C The second operand of the product. */ template<typename T, int Rows, int Cols, typename ST, typename T1, typename T2> void submul(base_matrix<T, Rows, Cols, ST, true> & A, const T1 & B, const T2 & C) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(A -= B * C)) { A -= B * C; } template<template<typename DataType> class Op, typename Data, typename T1, typename T2> void addmul(const implementation::expressions::expr<Op, Data> & A, const T1 & B, const T2 & C) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(A += B * C)) { A += B * C; } template<template<typename DataType> class Op, typename Data, typename T1, typename T2> void submul(const implementation::expressions::expr<Op, Data> & A, const T1 & B, const T2 & C) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(A -= B * C)) { A -= B * C; } ///@} //////////////////////////////////////////////////////////////////////////////////////////////////// //// comparison //////////////////////////////////////////////////////////////////////////////////////////////////// /**@{ \name Comparisons. */ namespace implementation { template<typename MT1, typename MT2> class comparison_impl { private: class compare_impl { public: typedef int IMResultType; typedef int ResultType; enum { default_value = 0 }; static inline ResultType transform(IMResultType r) PLLL_INTERNAL_NOTHROW_POSTFIX_INLINE { return r; } static inline IMResultType cmp_dimension(size_type a, size_type b) PLLL_INTERNAL_NOTHROW_POSTFIX_INLINE { if (a == b) return 0; else return a < b ? -1 : 1; } template<typename A, typename B> static inline IMResultType cmp(const A & a, const B & b) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(a == b) && noexcept(a < b)) { if (a == b) return 0; else return a < b ? -1 : 1; } }; class eq_impl { public: typedef bool IMResultType; typedef bool ResultType; enum { default_value = true }; static inline ResultType transform(IMResultType r) PLLL_INTERNAL_NOTHROW_POSTFIX_INLINE { return !r; } static inline IMResultType cmp_dimension(size_type a, size_type b) PLLL_INTERNAL_NOTHROW_POSTFIX_INLINE { return a != b; } template<typename A, typename B> static inline IMResultType cmp(const A & a, const B & b) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(a == b)) { return !(a == b); } }; class less_impl { public: typedef int IMResultType; typedef bool ResultType; enum { default_value = false }; static inline ResultType transform(IMResultType r) PLLL_INTERNAL_NOTHROW_POSTFIX_INLINE { return r < 0; } static inline IMResultType cmp_dimension(size_type a, size_type b) PLLL_INTERNAL_NOTHROW_POSTFIX_INLINE { if (a == b) return 0; else return a < b ? -1 : 1; } template<typename A, typename B> static inline IMResultType cmp(const A & a, const B & b) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(a == b) && noexcept(a < b)) { if (a == b) return 0; else return a < b ? -1 : 1; } }; class less_eq_impl { public: typedef int IMResultType; typedef bool ResultType; enum { default_value = true }; static inline ResultType transform(IMResultType r) PLLL_INTERNAL_NOTHROW_POSTFIX_INLINE { return r <= 0; } static inline IMResultType cmp_dimension(size_type a, size_type b) PLLL_INTERNAL_NOTHROW_POSTFIX_INLINE { if (a == b) return 0; else return a < b ? -1 : 1; } template<typename A, typename B> static inline IMResultType cmp(const A & a, const B & b) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(a == b) && noexcept(a < b)) { if (a == b) return 0; else return a < b ? -1 : 1; } }; class greater_impl { public: typedef int IMResultType; typedef bool ResultType; enum { default_value = false }; static inline ResultType transform(IMResultType r) PLLL_INTERNAL_NOTHROW_POSTFIX_INLINE { return r > 0; } static inline IMResultType cmp_dimension(size_type a, size_type b) PLLL_INTERNAL_NOTHROW_POSTFIX_INLINE { if (a == b) return 0; else return a < b ? -1 : 1; } template<typename A, typename B> static inline IMResultType cmp(const A & a, const B & b) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(a == b) && noexcept(a < b)) { if (a == b) return 0; else return a < b ? -1 : 1; } }; class greater_eq_impl { public: typedef int IMResultType; typedef bool ResultType; enum { default_value = true }; static inline ResultType transform(IMResultType r) PLLL_INTERNAL_NOTHROW_POSTFIX_INLINE { return r >= 0; } static inline IMResultType cmp_dimension(size_type a, size_type b) PLLL_INTERNAL_NOTHROW_POSTFIX_INLINE { if (a == b) return 0; else return a < b ? -1 : 1; } template<typename A, typename B> static inline IMResultType cmp(const A & a, const B & b) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(a == b) && noexcept(a < b)) { if (a == b) return 0; else return a < b ? -1 : 1; } }; template<typename cmp_impl> class comparator { public: static inline typename cmp_impl::ResultType cmp(const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(A.enumerate()) && noexcept(B.enumerate()) && noexcept(helper::make_type_lvalue<typename MT1::ConstEnumerator>().next()) && noexcept(helper::make_type_lvalue<typename MT2::ConstEnumerator>().next()) && noexcept(helper::make_type_lvalue<typename MT1::ConstEnumerator>().has_current()) && noexcept(cmp_impl::cmp(helper::make_type_lvalue<typename MT1::ConstEnumerator>().current(), helper::make_type_lvalue<typename MT2::ConstEnumerator>().current()))) { PLLL_DEBUG_OUTPUT_MESSAGE("comparison_impl::comparator::cmp(" << getAddress(A) << " " << getAddress(B) << ") [0]"); if (typename cmp_impl::IMResultType res = cmp_impl::cmp_dimension(A.rows(), B.rows())) return cmp_impl::transform(res); if (typename cmp_impl::IMResultType res = cmp_impl::cmp_dimension(A.cols(), B.cols())) return cmp_impl::transform(res); typename MT1::ConstEnumerator eA = A.enumerate(); typename MT2::ConstEnumerator eB = B.enumerate(); for (; eA.has_current(); eA.next(), eB.next()) if (typename cmp_impl::IMResultType res = cmp_impl::cmp(eA.current(), eB.current())) return cmp_impl::transform(res); return cmp_impl::default_value; } }; public: static inline int compare(const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(comparator<compare_impl>::cmp(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("comparison_impl::compare(" << getAddress(A) << " " << getAddress(B) << ")"); return comparator<compare_impl>::cmp(A, B); } static inline bool less(const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(comparator<less_impl>::cmp(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("comparison_impl::less(" << getAddress(A) << " " << getAddress(B) << ")"); return comparator<less_impl>::cmp(A, B); } static inline bool less_eq(const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(comparator<less_eq_impl>::cmp(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("comparison_impl::less_eq(" << getAddress(A) << " " << getAddress(B) << ")"); return comparator<less_eq_impl>::cmp(A, B); } static inline bool greater(const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(comparator<greater_impl>::cmp(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("comparison_impl::greater(" << getAddress(A) << " " << getAddress(B) << ")"); return comparator<greater_impl>::cmp(A, B); } static inline bool greater_eq(const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(comparator<greater_eq_impl>::cmp(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("comparison_impl::greater_eq(" << getAddress(A) << " " << getAddress(B) << ")"); return comparator<greater_eq_impl>::cmp(A, B); } static inline bool eq(const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(comparator<eq_impl>::cmp(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("comparison_impl::eq(" << getAddress(A) << " " << getAddress(B) << ")"); return comparator<eq_impl>::cmp(A, B); } static inline bool neq(const MT1 & A, const MT2 & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(!eq(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("comparison_impl::neq(" << getAddress(A) << " " << getAddress(B) << ")"); return !eq(A, B); } }; } template<template<typename AData> class AOp, typename AData, template<typename BData> class BOp, typename BData> inline int compare(const implementation::expressions::expr<AOp, AData> & A, const implementation::expressions::expr<BOp, BData> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::comparison_impl<implementation::expressions::expr<AOp, AData>, implementation::expressions::expr<BOp, BData> >::compare(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("compare(" << getAddress(A) << " " << getAddress(B) << ") [1]"); return implementation::comparison_impl<implementation::expressions::expr<AOp, AData>, implementation::expressions::expr<BOp, BData> >::compare(A, B); } template<template<typename AData> class AOp, typename AData, typename BT, int BRows, int BCols, typename BST, bool BMO> inline int compare(const implementation::expressions::expr<AOp, AData> & A, const base_matrix<BT, BRows, BCols, BST, BMO> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(compare(A, implementation::expressions::make_matrix_expression(B)))) { PLLL_DEBUG_OUTPUT_MESSAGE("compare(" << getAddress(A) << " " << getAddress(B) << ") [2]"); return compare(A, implementation::expressions::make_matrix_expression(B)); } template<typename AT, int ARows, int ACols, typename AST, bool AMO, template<typename BData> class BOp, typename BData> inline int compare(const base_matrix<AT, ARows, ACols, AST, AMO> & A, const implementation::expressions::expr<BOp, BData> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(compare(implementation::expressions::make_matrix_expression(A), B))) { PLLL_DEBUG_OUTPUT_MESSAGE("compare(" << getAddress(A) << " " << getAddress(B) << ") [3]"); return compare(implementation::expressions::make_matrix_expression(A), B); } /** \brief Lexicographically compares the matrices `A` and `B`. First compares rows and columns, and then all entries. The exact procedure is described in \ref matrixvector_ops_general. \param A The first operand. \param B The second operand. \return Returns a negative integer if `A < B`, zero if `A == B` and a positive integer if `A > B`. */ template<typename AT, int ARows, int ACols, typename AST, bool AMO, typename BT, int BRows, int BCols, typename BST, bool BMO> inline int compare(const base_matrix<AT, ARows, ACols, AST, AMO> & A, const base_matrix<BT, BRows, BCols, BST, BMO> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(compare(implementation::expressions::make_matrix_expression(A), implementation::expressions::make_matrix_expression(B)))) { PLLL_DEBUG_OUTPUT_MESSAGE("compare(" << getAddress(A) << " " << getAddress(B) << ") [4]"); return compare(implementation::expressions::make_matrix_expression(A), implementation::expressions::make_matrix_expression(B)); } template<template<typename AData> class AOp, typename AData, template<typename BData> class BOp, typename BData> inline bool operator == (const implementation::expressions::expr<AOp, AData> & A, const implementation::expressions::expr<BOp, BData> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::comparison_impl<implementation::expressions::expr<AOp, AData>, implementation::expressions::expr<BOp, BData> >::eq(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator == (" << getAddress(A) << " " << getAddress(B) << ") [1]"); return implementation::comparison_impl<implementation::expressions::expr<AOp, AData>, implementation::expressions::expr<BOp, BData> >::eq(A, B); } template<template<typename AData> class AOp, typename AData, typename BT, int BRows, int BCols, typename BST, bool BMO> inline bool operator == (const implementation::expressions::expr<AOp, AData> & A, const base_matrix<BT, BRows, BCols, BST, BMO> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(A == implementation::expressions::make_matrix_expression(B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator == (" << getAddress(A) << " " << getAddress(B) << ") [2]"); return A == implementation::expressions::make_matrix_expression(B); } template<typename AT, int ARows, int ACols, typename AST, bool AMO, template<typename BData> class BOp, typename BData> inline bool operator == (const base_matrix<AT, ARows, ACols, AST, AMO> & A, const implementation::expressions::expr<BOp, BData> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::expressions::make_matrix_expression(A) == B)) { PLLL_DEBUG_OUTPUT_MESSAGE("operator == (" << getAddress(A) << " " << getAddress(B) << ") [3]"); return implementation::expressions::make_matrix_expression(A) == B; } /** \brief Tests `A` and `B` for equality. \param A The first operand. \param B The second operand. \return Returns `true` if and only if `A` and `B` have the same format and the same entries. */ template<typename AT, int ARows, int ACols, typename AST, bool AMO, typename BT, int BRows, int BCols, typename BST, bool BMO> inline bool operator == (const base_matrix<AT, ARows, ACols, AST, AMO> & A, const base_matrix<BT, BRows, BCols, BST, BMO> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::expressions::make_matrix_expression(A) == implementation::expressions::make_matrix_expression(B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator == (" << getAddress(A) << " " << getAddress(B) << ") [4]"); return implementation::expressions::make_matrix_expression(A) == implementation::expressions::make_matrix_expression(B); } template<template<typename AData> class AOp, typename AData, template<typename BData> class BOp, typename BData> inline bool operator != (const implementation::expressions::expr<AOp, AData> & A, const implementation::expressions::expr<BOp, BData> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::comparison_impl<implementation::expressions::expr<AOp, AData>, implementation::expressions::expr<BOp, BData> >::neq(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator != (" << getAddress(A) << " " << getAddress(B) << ") [1]"); return implementation::comparison_impl<implementation::expressions::expr<AOp, AData>, implementation::expressions::expr<BOp, BData> >::neq(A, B); } template<template<typename AData> class AOp, typename AData, typename BT, int BRows, int BCols, typename BST, bool BMO> inline bool operator != (const implementation::expressions::expr<AOp, AData> & A, const base_matrix<BT, BRows, BCols, BST, BMO> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(A != implementation::expressions::make_matrix_expression(B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator != (" << getAddress(A) << " " << getAddress(B) << ") [2]"); return A != implementation::expressions::make_matrix_expression(B); } template<typename AT, int ARows, int ACols, typename AST, bool AMO, template<typename BData> class BOp, typename BData> inline bool operator != (const base_matrix<AT, ARows, ACols, AST, AMO> & A, const implementation::expressions::expr<BOp, BData> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::expressions::make_matrix_expression(A) != B)) { PLLL_DEBUG_OUTPUT_MESSAGE("operator != (" << getAddress(A) << " " << getAddress(B) << ") [3]"); return implementation::expressions::make_matrix_expression(A) != B; } /** \brief Tests `A` and `B` for inequality. \param A The first operand. \param B The second operand. \return Returns `false` if and only if `A` and `B` have the same format and the same entries. */ template<typename AT, int ARows, int ACols, typename AST, bool AMO, typename BT, int BRows, int BCols, typename BST, bool BMO> inline bool operator != (const base_matrix<AT, ARows, ACols, AST, AMO> & A, const base_matrix<BT, BRows, BCols, BST, BMO> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::expressions::make_matrix_expression(A) != implementation::expressions::make_matrix_expression(B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator != (" << getAddress(A) << " " << getAddress(B) << ") [4]"); return implementation::expressions::make_matrix_expression(A) != implementation::expressions::make_matrix_expression(B); } template<template<typename AData> class AOp, typename AData, template<typename BData> class BOp, typename BData> inline bool operator < (const implementation::expressions::expr<AOp, AData> & A, const implementation::expressions::expr<BOp, BData> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::comparison_impl<implementation::expressions::expr<AOp, AData>, implementation::expressions::expr<BOp, BData> >::less(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator < (" << getAddress(A) << " " << getAddress(B) << ") [1]"); return implementation::comparison_impl<implementation::expressions::expr<AOp, AData>, implementation::expressions::expr<BOp, BData> >::less(A, B); } template<template<typename AData> class AOp, typename AData, typename BT, int BRows, int BCols, typename BST, bool BMO> inline bool operator < (const implementation::expressions::expr<AOp, AData> & A, const base_matrix<BT, BRows, BCols, BST, BMO> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(A < implementation::expressions::make_matrix_expression(B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator < (" << getAddress(A) << " " << getAddress(B) << ") [2]"); return A < implementation::expressions::make_matrix_expression(B); } template<typename AT, int ARows, int ACols, typename AST, bool AMO, template<typename BData> class BOp, typename BData> inline bool operator < (const base_matrix<AT, ARows, ACols, AST, AMO> & A, const implementation::expressions::expr<BOp, BData> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::expressions::make_matrix_expression(A) < B)) { PLLL_DEBUG_OUTPUT_MESSAGE("operator < (" << getAddress(A) << " " << getAddress(B) << ") [3]"); return implementation::expressions::make_matrix_expression(A) < B; } /** \brief Tests `A` and `B` lexicographically for `A` being less than `B`. The exact procedure is described in \ref matrixvector_ops_general. \param A The first operand. \param B The second operand. \return Returns `true` if and only if \f$A < B\f$ lexicographically. */ template<typename AT, int ARows, int ACols, typename AST, bool AMO, typename BT, int BRows, int BCols, typename BST, bool BMO> inline bool operator < (const base_matrix<AT, ARows, ACols, AST, AMO> & A, const base_matrix<BT, BRows, BCols, BST, BMO> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::expressions::make_matrix_expression(A) < implementation::expressions::make_matrix_expression(B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator < (" << getAddress(A) << " " << getAddress(B) << ") [4]"); return implementation::expressions::make_matrix_expression(A) < implementation::expressions::make_matrix_expression(B); } template<template<typename AData> class AOp, typename AData, template<typename BData> class BOp, typename BData> inline bool operator <= (const implementation::expressions::expr<AOp, AData> & A, const implementation::expressions::expr<BOp, BData> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::comparison_impl<implementation::expressions::expr<AOp, AData>, implementation::expressions::expr<BOp, BData> >::less_eq(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator <= (" << getAddress(A) << " " << getAddress(B) << ") [1]"); return implementation::comparison_impl<implementation::expressions::expr<AOp, AData>, implementation::expressions::expr<BOp, BData> >::less_eq(A, B); } template<template<typename AData> class AOp, typename AData, typename BT, int BRows, int BCols, typename BST, bool BMO> inline bool operator <= (const implementation::expressions::expr<AOp, AData> & A, const base_matrix<BT, BRows, BCols, BST, BMO> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(A <= implementation::expressions::make_matrix_expression(B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator <= (" << getAddress(A) << " " << getAddress(B) << ") [2]"); return A <= implementation::expressions::make_matrix_expression(B); } template<typename AT, int ARows, int ACols, typename AST, bool AMO, template<typename BData> class BOp, typename BData> inline bool operator <= (const base_matrix<AT, ARows, ACols, AST, AMO> & A, const implementation::expressions::expr<BOp, BData> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::expressions::make_matrix_expression(A) <= B)) { PLLL_DEBUG_OUTPUT_MESSAGE("operator <= (" << getAddress(A) << " " << getAddress(B) << ") [3]"); return implementation::expressions::make_matrix_expression(A) <= B; } /** \brief Tests `A` and `B` lexicographically for `A` being less than or equal to `B`. The exact procedure is described in \ref matrixvector_ops_general. \param A The first operand. \param B The second operand. \return Returns `true` if and only if \f$A \le B\f$ lexicographically. */ template<typename AT, int ARows, int ACols, typename AST, bool AMO, typename BT, int BRows, int BCols, typename BST, bool BMO> inline bool operator <= (const base_matrix<AT, ARows, ACols, AST, AMO> & A, const base_matrix<BT, BRows, BCols, BST, BMO> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::expressions::make_matrix_expression(A) <= implementation::expressions::make_matrix_expression(B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator <= (" << getAddress(A) << " " << getAddress(B) << ") [4]"); return implementation::expressions::make_matrix_expression(A) <= implementation::expressions::make_matrix_expression(B); } template<template<typename AData> class AOp, typename AData, template<typename BData> class BOp, typename BData> inline bool operator > (const implementation::expressions::expr<AOp, AData> & A, const implementation::expressions::expr<BOp, BData> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::comparison_impl<implementation::expressions::expr<AOp, AData>, implementation::expressions::expr<BOp, BData> >::greater(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator > (" << getAddress(A) << " " << getAddress(B) << ") [1]"); return implementation::comparison_impl<implementation::expressions::expr<AOp, AData>, implementation::expressions::expr<BOp, BData> >::greater(A, B); } template<template<typename AData> class AOp, typename AData, typename BT, int BRows, int BCols, typename BST, bool BMO> inline bool operator > (const implementation::expressions::expr<AOp, AData> & A, const base_matrix<BT, BRows, BCols, BST, BMO> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(A > implementation::expressions::make_matrix_expression(B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator > (" << getAddress(A) << " " << getAddress(B) << ") [2]"); return A > implementation::expressions::make_matrix_expression(B); } template<typename AT, int ARows, int ACols, typename AST, bool AMO, template<typename BData> class BOp, typename BData> inline bool operator > (const base_matrix<AT, ARows, ACols, AST, AMO> & A, const implementation::expressions::expr<BOp, BData> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::expressions::make_matrix_expression(A) > B)) { PLLL_DEBUG_OUTPUT_MESSAGE("operator > (" << getAddress(A) << " " << getAddress(B) << ") [3]"); return implementation::expressions::make_matrix_expression(A) > B; } /** \brief Tests `A` and `B` lexicographically for `A` being greater than `B`. The exact procedure is described in \ref matrixvector_ops_general. \param A The first operand. \param B The second operand. \return Returns `true` if and only if \f$A > B\f$ lexicographically. */ template<typename AT, int ARows, int ACols, typename AST, bool AMO, typename BT, int BRows, int BCols, typename BST, bool BMO> inline bool operator > (const base_matrix<AT, ARows, ACols, AST, AMO> & A, const base_matrix<BT, BRows, BCols, BST, BMO> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::expressions::make_matrix_expression(A) > implementation::expressions::make_matrix_expression(B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator > (" << getAddress(A) << " " << getAddress(B) << ") [4]"); return implementation::expressions::make_matrix_expression(A) > implementation::expressions::make_matrix_expression(B); } template<template<typename AData> class AOp, typename AData, template<typename BData> class BOp, typename BData> inline bool operator >= (const implementation::expressions::expr<AOp, AData> & A, const implementation::expressions::expr<BOp, BData> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::comparison_impl<implementation::expressions::expr<AOp, AData>, implementation::expressions::expr<BOp, BData> >::greater_eq(A, B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator >= (" << getAddress(A) << " " << getAddress(B) << ") [1]"); return implementation::comparison_impl<implementation::expressions::expr<AOp, AData>, implementation::expressions::expr<BOp, BData> >::greater_eq(A, B); } template<template<typename AData> class AOp, typename AData, typename BT, int BRows, int BCols, typename BST, bool BMO> inline bool operator >= (const implementation::expressions::expr<AOp, AData> & A, const base_matrix<BT, BRows, BCols, BST, BMO> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(A >= implementation::expressions::make_matrix_expression(B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator >= (" << getAddress(A) << " " << getAddress(B) << ") [2]"); return A >= implementation::expressions::make_matrix_expression(B); } template<typename AT, int ARows, int ACols, typename AST, bool AMO, template<typename BData> class BOp, typename BData> inline bool operator >= (const base_matrix<AT, ARows, ACols, AST, AMO> & A, const implementation::expressions::expr<BOp, BData> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::expressions::make_matrix_expression(A) >= B)) { PLLL_DEBUG_OUTPUT_MESSAGE("operator >= (" << getAddress(A) << " " << getAddress(B) << ") [3]"); return implementation::expressions::make_matrix_expression(A) >= B; } /** \brief Tests `A` and `B` lexicographically for `A` being greater than or equal to `B`. The exact procedure is described in \ref matrixvector_ops_general. \param A The first operand. \param B The second operand. \return Returns `true` if and only if \f$A \ge B\f$ lexicographically. */ template<typename AT, int ARows, int ACols, typename AST, bool AMO, typename BT, int BRows, int BCols, typename BST, bool BMO> inline bool operator >= (const base_matrix<AT, ARows, ACols, AST, AMO> & A, const base_matrix<BT, BRows, BCols, BST, BMO> & B) PLLL_INTERNAL_NOTHROW_POSTFIX_CONDITIONAL(noexcept(implementation::expressions::make_matrix_expression(A) >= implementation::expressions::make_matrix_expression(B))) { PLLL_DEBUG_OUTPUT_MESSAGE("operator >= (" << getAddress(A) << " " << getAddress(B) << ") [4]"); return implementation::expressions::make_matrix_expression(A) >= implementation::expressions::make_matrix_expression(B); } ///@} } } #endif
65.523667
281
0.582833
[ "object", "transform" ]
312d8fe9789d9b39f6b16a43bc3302a4cbdbae70
1,663
cpp
C++
Engine/Animation.cpp
metalheadjohny/Stale_Memes
69717ff036471fa642141ac2ff9a23525b475cea
[ "MIT" ]
1
2019-09-02T08:23:40.000Z
2019-09-02T08:23:40.000Z
Engine/Animation.cpp
metalheadjohny/Stale_Memes
69717ff036471fa642141ac2ff9a23525b475cea
[ "MIT" ]
3
2021-05-09T20:19:23.000Z
2021-08-10T19:00:19.000Z
Engine/Animation.cpp
metalheadjohny/Stale_Memes
69717ff036471fa642141ac2ff9a23525b475cea
[ "MIT" ]
null
null
null
#include "pch.h" #include "Animation.h" #include "Bone.h" Animation::Animation() noexcept = default; Animation::Animation(std::string& name, double ticks, double ticksPerSecond, int nc) noexcept : _name(name), _ticks(ticks), _ticksPerSecond(ticksPerSecond) { _duration = _ticks / _ticksPerSecond; _tickDuration = _duration / _ticks; } void Animation::getTransformAtTime(const std::vector<Bone>& bones, const SMatrix& glInvT, float elapsed, std::vector<SMatrix>& vec) const { float currentTick = elapsed / _tickDuration; float t = currentTick - static_cast<uint32_t>(currentTick); for (auto i = 0; i < bones.size(); ++i) { const Bone& bone = bones[i]; SMatrix parentMatrix{}; [[likely]] if (bone._parent != Bone::INVALID_INDEX) { parentMatrix = vec[bone._parent]; } // Optimize this out! It's a temporary fix and awful. // It should be used as a preparation step where each bone is matched to an animation channel once and then has a direct lookup const AnimChannel* channel = getAnimChannel(getAnimChannelIndex(bone.name())); // If the bone has an animation channel, replace local matrix of the bone with the animated one. SMatrix animTransform = channel ? channel->getInterpolatedTransform(currentTick, t) : bone._localMatrix; vec[i] = animTransform * parentMatrix; } // Bind space to bone space, animate, apply global inverse - but only for influence bones uint32_t realIndex{ 0u }; for (auto i = 0; i < bones.size(); ++i) { if (bones[i]._isInfluenceBone) { vec[realIndex++] = bones[i]._invBindPose * vec[i] * glInvT; } } } void Animation::expand() { for (auto& channel : _channels) { } }
25.984375
137
0.705953
[ "vector" ]
3130694a2ed2c07c5b0a79d9d1e4b5f774085ee7
4,549
cxx
C++
Tracing/TraceEdit/NodeModel.cxx
tostathaina/farsight
7e9d6d15688735f34f7ca272e4e715acd11473ff
[ "Apache-2.0" ]
8
2016-07-22T11:24:19.000Z
2021-04-10T04:22:31.000Z
Tracing/TraceEdit/NodeModel.cxx
YanXuHappygela/Farsight
1711b2a1458c7e035edd21fe0019a1f7d23fcafa
[ "Apache-2.0" ]
null
null
null
Tracing/TraceEdit/NodeModel.cxx
YanXuHappygela/Farsight
1711b2a1458c7e035edd21fe0019a1f7d23fcafa
[ "Apache-2.0" ]
7
2016-07-21T07:39:17.000Z
2020-01-29T02:03:27.000Z
#include "TraceBit.h" #include "TraceLine.h" #include "NodeModel.h" NodeModel::NodeModel() { this->DataTable = vtkSmartPointer<vtkTable>::New(); this->Selection = new ObjectSelection(); this->additionalHeaders.clear(); } NodeModel::NodeModel(std::vector<TraceLine*> trace_lines) { this->DataTable = vtkSmartPointer<vtkTable>::New(); this->Selection = new ObjectSelection(); this->SetLines(trace_lines); } NodeModel::~NodeModel() { delete this->Selection; this->Selection = NULL; } void NodeModel::SetLines(std::vector<TraceLine*> trace_lines) { this->TraceLines.clear(); this->TraceLines = trace_lines; this->SyncModel(); } void NodeModel::SetupHeaders() { this->headers.clear(); this->headers.push_back("Bit ID"); this->headers.push_back("X"); this->headers.push_back("Y"); this->headers.push_back("Z"); this->headers.push_back("Radius"); this->headers.push_back("Segment ID"); this->headers.push_back("Root ID"); int size = this->additionalHeaders.size(); for (int k = 0; k < size; k++) { this->headers.push_back(QString(this->additionalHeaders[k].c_str())); } int numHeaders = (int)this->headers.size(); vtkSmartPointer<vtkVariantArray> column = vtkSmartPointer<vtkVariantArray>::New(); for(int i=0; i < numHeaders; ++i) { column = vtkSmartPointer<vtkVariantArray>::New(); column->SetName( this->headers.at(i).toStdString().c_str() ); this->DataTable->AddColumn(column); } } void NodeModel::AddNodeHeader(std::string NewFeatureHeader) { /*! * */ this->additionalHeaders.push_back(NewFeatureHeader); this->headers.push_back(QString(NewFeatureHeader.c_str())); } void NodeModel::SyncModel() { int size = this->additionalHeaders.size(); this->DataTable->Initialize(); this->Selection->clear(); this->SetupHeaders(); for (int i = 0; i < (int)this->TraceLines.size(); ++i) { TraceLine::TraceBitsType::iterator iter = this->TraceLines.at(i)->GetTraceBitIteratorBegin(); TraceLine::TraceBitsType::iterator iterend = this->TraceLines.at(i)->GetTraceBitIteratorEnd(); while(iter != iterend) { if (size == 0) { vtkSmartPointer<vtkVariantArray> DataRow = vtkSmartPointer<vtkVariantArray>::New(); DataRow = (*iter).DataRow(); DataRow->InsertNextValue(this->TraceLines.at(i)->GetId()); DataRow->InsertNextValue(this->TraceLines.at(i)->GetRootID()); this->DataTable->InsertNextRow(DataRow); } iter++; } } } void NodeModel::setDataTable(vtkSmartPointer<vtkTable> table) { this->DataTable = table; this->Selection->clear(); } vtkSmartPointer<vtkTable> NodeModel::getDataTable() { return this->DataTable; } void NodeModel::SelectByIDs(std::vector<int> IDs) { //this->Selection->clear(); std::set<long int> ID; std::vector<int>::iterator IDs_iterator; //std::cout << "IDs.size(): " << IDs.size() << std::endl; for (IDs_iterator = IDs.begin(); IDs_iterator != IDs.end(); IDs_iterator++) { ID.insert(*IDs_iterator); } Selection->select(ID); } std::vector<long int> NodeModel::GetSelectedIDs() { std::vector<long int> SelectedIDs; std::set<long> selected = this->Selection->getSelections(); std::set<long>::iterator it; for (it = selected.begin(); it != selected.end(); ++it) { SelectedIDs.push_back(*it); } return SelectedIDs; } //std::vector<TraceBit> NodeModel::GetSelectedNodes() //{ // std::vector<TraceBit> selectedNodes; // std::set<long> selected = this->Selection->getSelections(); // std::set<long>::iterator it; // for (it = selected.begin(); it != selected.end(); ++it) // { // this->NodeIDLookupIter = this->TraceBits.find((int) *it); // if (this->NodeIDLookupIter != this->TraceBits.end()) // { // selectedNodes.push_back((*this->NodeIDLookupIter)); // } // }//end for selected // // //std::vector<long int> IDList = this->GetSelectedIDs(); // // ////Search for nodes // //for ( unsigned int i = 0; i< IDList.size(); i++) // //{ // // this->NodeIDLookupIter = this->NodeIDLookupMAP.find(IDList[i]); // // if (this->NodeIDLookupIter != this->NodeIDLookupMAP.end()) // // { // // selectedNodes.push_back((*this->NodeIDLookupIter).second); // // } // //}//finished with id search // return selectedNodes; //} unsigned int NodeModel::getNodeCount() { return (unsigned int) this->TraceBits.size(); } //std::map< int ,TraceBit>::iterator NodeModel::GetNodeiterator() //{ // return this->TraceBits.begin(); //} // //std::map< int ,TraceBit>::iterator NodeModel::GetNodeiteratorEnd() //{ // return this->TraceBits.end(); //} ObjectSelection * NodeModel::GetObjectSelection() { return this->Selection; }
25.413408
96
0.681688
[ "vector" ]
31361c792e7703646f548b254204c4a6ee9c7e08
3,198
cpp
C++
src/Collision/CollisionRect.cpp
TmCrafz/ArenaSFML
a112330816b1e76564194ead9aff99e28ff9b454
[ "MIT" ]
2
2017-05-16T22:39:14.000Z
2021-03-16T13:56:55.000Z
src/Collision/CollisionRect.cpp
TmCrafz/ArenaSFML
a112330816b1e76564194ead9aff99e28ff9b454
[ "MIT" ]
null
null
null
src/Collision/CollisionRect.cpp
TmCrafz/ArenaSFML
a112330816b1e76564194ead9aff99e28ff9b454
[ "MIT" ]
1
2017-12-05T05:34:20.000Z
2017-12-05T05:34:20.000Z
#include "Collision/CollisionRect.hpp" #include "Collision/CollisionHandler.hpp" #include "Calc.hpp" CollisionRect::CollisionRect(sf::Vector2f rectSize) : m_width{ rectSize.x } , m_height{ rectSize.y } { } float CollisionRect::getWidth() const { return m_width; } float CollisionRect::getHeight() const { return m_height; } void CollisionRect::computeVertices() { const float Rotation = { getWorldRotation() }; const sf::Vector2f Position = { getWorldPosition() }; //std::cout << "Rotation: " << Rotation << std::endl; // Compute the rects vertices as AABB const sf::Vector2f EdgeA = { Position.x - m_width / 2.f, Position.y - m_height / 2.f }; const sf::Vector2f EdgeB = { Position.x + m_width / 2.f, Position.y - m_height / 2.f }; const sf::Vector2f EdgeC = { Position.x + m_width / 2.f, Position.y + m_height / 2.f }; const sf::Vector2f EdgeD = { Position.x - m_width / 2.f, Position.y + m_height / 2.f }; // Apply rects rotation to the vertices const sf::Vector2f EdgeAR = { Calc::rotatePointAround(EdgeA, Position, -Rotation) }; const sf::Vector2f EdgeBR = { Calc::rotatePointAround(EdgeB, Position, -Rotation) }; const sf::Vector2f EdgeCR = { Calc::rotatePointAround(EdgeC, Position, -Rotation) }; const sf::Vector2f EdgeDR = { Calc::rotatePointAround(EdgeD, Position, -Rotation) }; // Add the vertices to the container m_vertices.clear(); // Add vertices clockwise m_vertices.push_back(EdgeAR); m_vertices.push_back(EdgeBR); m_vertices.push_back(EdgeCR); m_vertices.push_back(EdgeDR); } std::vector<sf::Vector2f> CollisionRect::getVertices() const { return m_vertices; } void CollisionRect::draw(sf::RenderTarget &target, sf::RenderStates states) const { if (drawCollisionShapes) { sf::RectangleShape rect({ m_width, m_height }); rect.setPosition(getPosition()); rect.setFillColor(sf::Color(255, 0, 0, 160)); rect.setOrigin(m_width / 2.f, m_height / 2.f); target.draw(rect, states); } } CollisionInfo CollisionRect::isColliding(CollisionShape &collider) { return collider.isColliding(*this); } CollisionInfo CollisionRect::isColliding(CollisionCircle &collider) { return CollisionHandler::isColliding(*this, collider); } CollisionInfo CollisionRect::isColliding(CollisionRect &collider) { return CollisionHandler::isColliding(*this, collider); } // Return the point which is nearest (farthest) to the given direction sf::Vector2f CollisionRect::getFarthestPointInDirection(sf::Vector2f dir) const { int maxPos = 0; float maxScalar = Calc::getVec2Scalar<sf::Vector2f, sf::Vector2f>(dir, m_vertices[0]); // Determine which verices of the rect is the nearest // (have the highest dot product) to the given vector for (std::size_t i = 0; i != m_vertices.size(); i++) { float scalar{ Calc::getVec2Scalar<sf::Vector2f, sf::Vector2f>(dir, m_vertices[i]) }; if (scalar > maxScalar) { maxPos = i; maxScalar = scalar; } } return m_vertices[maxPos]; }
30.169811
82
0.659787
[ "vector" ]
31418a48eae0bd5169cbc831446079700aabfa6c
2,931
cpp
C++
currency_train/currency.cpp
aajay980/CurrencyRecognition
7d49cf29c6738081cd8cbcc70942939d1ea9c980
[ "IJG" ]
null
null
null
currency_train/currency.cpp
aajay980/CurrencyRecognition
7d49cf29c6738081cd8cbcc70942939d1ea9c980
[ "IJG" ]
null
null
null
currency_train/currency.cpp
aajay980/CurrencyRecognition
7d49cf29c6738081cd8cbcc70942939d1ea9c980
[ "IJG" ]
null
null
null
#include "train_BOW_IR_utils.cpp" #include "opencv2/core/types_c.h" using namespace cv; using namespace std; int main(int argc,char **argv) { /******************** extract features ********************/ Mat siftFeature; const int vocabSize = (int)strtol(argv[2], NULL, 0); const int numImagesToTrain = (int)strtol(argv[3], NULL, 0); int numImages=0; printf("\nvocabSize selected : %d", vocabSize); printf("\nMaximal number of images form each class to be used for training : %d", numImagesToTrain); printf("\nExtracting features"); siftFeature=extractSift(argv[1], numImagesToTrain); printf("\nFeatures extracted : %d", siftFeature.rows); /******************** cluster the features ********************/ printf("\nClustering start"); printf("\n"); // Mat vocabulary=kMeansCluster(siftFeature, vocabSize); Mat vocabulary=hiKMeansCluster(siftFeature,vocabSize); printf("\nClustering done : %d", vocabulary.rows); siftFeature.release(); /******************** write vocabulary to .yml and .bin file ********************/ if(writeToYML) { printf("\nWriting Vocabulary to the yml file"); writeToYMLFile(vocabulary, (char *)"vocabulary"); } printf("\nWriting Vocabulary to the binary file"); writeToBinaryFile(vocabulary, (char *)"vocabulary.bin"); /********** get BOW histogram for each image ********************/ printf("\ngetting BOW histogram for each image"); Mat allHist=getBowHist(vocabulary, argv[1], numImagesToTrain); vocabulary.release(); /******************** Weighted Histogram of allHist ********************/ printf("\ntf-idf scoring"); Mat weightedAllHist=tfIdfWeighting(allHist); numImages = weightedAllHist.rows; allHist.release(); if(writeToYML) { printf("\nWriting tf-idf weighted BOW histogram for each image to YML file"); writeToYMLFile(weightedAllHist,(char *)"weightedAllHist"); } /******************** perform inverted index ********************/ printf("\nGetting inverted index"); vector<invertedIndex> allIndex = getInvertedIndex(weightedAllHist); weightedAllHist.release(); printf("\nTotal inverted indices = %d", allIndex.size()); printf("\nWriting inverted index to binary file"); writeToBinaryFile(allIndex,(char *)"allIndex.bin"); /******************** write total num of train images and vocabSize to data file ********************/ printf("\nWrite total num of train images and vocabSize to data file"); FILE *filePointer=fopen("dataFile.txt","w"); if(filePointer==NULL) { printf("\nCouldn't open 'datafile.txt'"); return 0; } fprintf(filePointer,"%d\n%d", numImages, vocabSize); fclose(filePointer); printf("\n\n********************finish********************\n\n"); return 0; }
33.306818
107
0.591948
[ "vector" ]
314a54c1431d3029cc398e46adcdb9fe26a0361c
6,367
cpp
C++
CIM_Framework/CIMFramework/CPPClasses/Src/CIM_RemoteServiceAccessPoint.cpp
rgl/lms
cda6a25e0f39b2a18f10415560ee6a2cfc5fbbcb
[ "Apache-2.0" ]
18
2019-04-17T10:43:35.000Z
2022-03-22T22:30:39.000Z
CIM_Framework/CIMFramework/CPPClasses/Src/CIM_RemoteServiceAccessPoint.cpp
rgl/lms
cda6a25e0f39b2a18f10415560ee6a2cfc5fbbcb
[ "Apache-2.0" ]
9
2019-10-03T15:29:51.000Z
2021-12-27T14:03:33.000Z
CIM_Framework/CIMFramework/CPPClasses/Src/CIM_RemoteServiceAccessPoint.cpp
isabella232/lms
50d16f81b49aba6007388c001e8137352c5eb42e
[ "Apache-2.0" ]
8
2019-06-13T23:30:50.000Z
2021-06-25T15:51:59.000Z
//---------------------------------------------------------------------------- // // Copyright (c) Intel Corporation, 2003 - 2012 All Rights Reserved. // // File: CIM_RemoteServiceAccessPoint.cpp // // Contents: RemoteServiceAccessPoint describes access or addressing information or a combination of this information for a remote connection that is known to a local network element. This information is scoped or contained by the local network element, because this is the context in which the connection is remote. // The relevance of the remote access point and information on its use are described by subclassing RemoteServiceAccessPoint or by associating to it. // // This file was automatically generated from CIM_RemoteServiceAccessPoint.mof, version: 2.27.0 // //---------------------------------------------------------------------------- #include "CIM_RemoteServiceAccessPoint.h" namespace Intel { namespace Manageability { namespace Cim { namespace Typed { const CimFieldAttribute CIM_RemoteServiceAccessPoint::_metadata[] = { {"AccessInfo", false, false, false }, {"InfoFormat", false, false, false }, {"OtherInfoFormatDescription", false, false, false }, {"AccessContext", false, false, false }, {"OtherAccessContext", false, false, false }, }; // class fields const string CIM_RemoteServiceAccessPoint::AccessInfo() const { return GetField("AccessInfo")[0]; } void CIM_RemoteServiceAccessPoint::AccessInfo(const string &value) { SetOrAddField("AccessInfo", value); } bool CIM_RemoteServiceAccessPoint::AccessInfoExists() const { return ContainsField("AccessInfo"); } void CIM_RemoteServiceAccessPoint::RemoveAccessInfo() { RemoveField("AccessInfo"); } const unsigned short CIM_RemoteServiceAccessPoint::InfoFormat() const { unsigned short ret = 0; TypeConverter::StringToType(GetField("InfoFormat"), ret); return ret; } void CIM_RemoteServiceAccessPoint::InfoFormat(const unsigned short value) { SetOrAddField("InfoFormat", TypeConverter::TypeToString(value)); } bool CIM_RemoteServiceAccessPoint::InfoFormatExists() const { return ContainsField("InfoFormat"); } void CIM_RemoteServiceAccessPoint::RemoveInfoFormat() { RemoveField("InfoFormat"); } const string CIM_RemoteServiceAccessPoint::OtherInfoFormatDescription() const { return GetField("OtherInfoFormatDescription")[0]; } void CIM_RemoteServiceAccessPoint::OtherInfoFormatDescription(const string &value) { SetOrAddField("OtherInfoFormatDescription", value); } bool CIM_RemoteServiceAccessPoint::OtherInfoFormatDescriptionExists() const { return ContainsField("OtherInfoFormatDescription"); } void CIM_RemoteServiceAccessPoint::RemoveOtherInfoFormatDescription() { RemoveField("OtherInfoFormatDescription"); } const unsigned short CIM_RemoteServiceAccessPoint::AccessContext() const { unsigned short ret = 0; TypeConverter::StringToType(GetField("AccessContext"), ret); return ret; } void CIM_RemoteServiceAccessPoint::AccessContext(const unsigned short value) { SetOrAddField("AccessContext", TypeConverter::TypeToString(value)); } bool CIM_RemoteServiceAccessPoint::AccessContextExists() const { return ContainsField("AccessContext"); } void CIM_RemoteServiceAccessPoint::RemoveAccessContext() { RemoveField("AccessContext"); } const string CIM_RemoteServiceAccessPoint::OtherAccessContext() const { return GetField("OtherAccessContext")[0]; } void CIM_RemoteServiceAccessPoint::OtherAccessContext(const string &value) { SetOrAddField("OtherAccessContext", value); } bool CIM_RemoteServiceAccessPoint::OtherAccessContextExists() const { return ContainsField("OtherAccessContext"); } void CIM_RemoteServiceAccessPoint::RemoveOtherAccessContext() { RemoveField("OtherAccessContext"); } CimBase *CIM_RemoteServiceAccessPoint::CreateFromCimObject(const CimObject &object) { CIM_RemoteServiceAccessPoint *ret = NULL; if(object.ObjectType() != CLASS_NAME) { ret = new CimExtended<CIM_RemoteServiceAccessPoint>(object); } else { ret = new CIM_RemoteServiceAccessPoint(object); } return ret; } vector<shared_ptr<CIM_RemoteServiceAccessPoint> > CIM_RemoteServiceAccessPoint::Enumerate(ICimWsmanClient *client, const CimKeys &keys) { return CimBase::Enumerate<CIM_RemoteServiceAccessPoint>(client, keys); } void CIM_RemoteServiceAccessPoint::Delete(ICimWsmanClient *client, const CimKeys &keys) { CimBase::Delete(client, CLASS_URI, keys); } const vector<CimFieldAttribute> &CIM_RemoteServiceAccessPoint::GetMetaData() const { return _classMetaData; } const CimFieldAttribute CIM_RemoteServiceAccessPoint::RequestStateChange_INPUT::_metadata[] = { {"RequestedState", false, false }, {"TimeoutPeriod", false, false }, }; void CIM_RemoteServiceAccessPoint::RequestStateChange_INPUT::RequestedState(const unsigned short value) { SetOrAddField("RequestedState", TypeConverter::TypeToString(value)); } void CIM_RemoteServiceAccessPoint::RequestStateChange_INPUT::TimeoutPeriod(const CimDateTime &value) { SetOrAddField("TimeoutPeriod", TypeConverter::TypeToString(value)); } const VectorFieldData CIM_RemoteServiceAccessPoint::RequestStateChange_INPUT::GetAllFields() const { VectorFieldData ret; ret = sortData(_metadata, 2); return ret; } const CimReference CIM_RemoteServiceAccessPoint::RequestStateChange_OUTPUT::Job() const { CimReference ret; TypeConverter::StringToType(GetField("Job"), ret); return ret; } bool CIM_RemoteServiceAccessPoint::RequestStateChange_OUTPUT::JobExists() const { return ContainsField("Job"); } unsigned int CIM_RemoteServiceAccessPoint::RequestStateChange(const RequestStateChange_INPUT &input, RequestStateChange_OUTPUT &output) { return Invoke("RequestStateChange", input, output); } const string CIM_RemoteServiceAccessPoint::CLASS_NAME = "CIM_RemoteServiceAccessPoint"; const string CIM_RemoteServiceAccessPoint::CLASS_URI = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_RemoteServiceAccessPoint"; const string CIM_RemoteServiceAccessPoint::CLASS_NS = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_RemoteServiceAccessPoint"; const string CIM_RemoteServiceAccessPoint::CLASS_NS_PREFIX = "ARe365"; CIMFRAMEWORK_API vector <CimFieldAttribute> CIM_RemoteServiceAccessPoint::_classMetaData; } } } }
33.867021
320
0.763782
[ "object", "vector" ]
314c04b512d081ff96f272239adfe62e2601b9c5
2,613
hpp
C++
Source/Streams.hpp
sawickiap/RegEngine
613c31fd60558a75c5b8902529acfa425fc97b2a
[ "MIT" ]
11
2022-01-02T22:50:42.000Z
2022-02-15T09:10:25.000Z
Source/Streams.hpp
sawickiap/RegEngine
613c31fd60558a75c5b8902529acfa425fc97b2a
[ "MIT" ]
null
null
null
Source/Streams.hpp
sawickiap/RegEngine
613c31fd60558a75c5b8902529acfa425fc97b2a
[ "MIT" ]
null
null
null
#pragma once class BaseStream { public: // Values match WinAPI constants FILE_BEGIN, FILE_CURRENT, FILE_END. enum class MoveMethod { Begin = 0, Current = 1, End = 2 }; virtual ~BaseStream() = default; // Default implementation asserts as not supported and returns SIZE_MAX. virtual size_t GetSize(); // Default implementation asserts as not supported and returns SIZE_MAX. virtual size_t GetPosition(); // Returns new position. // Default implementation asserts as not supported and returns SIZE_MAX. virtual size_t SetPosition(ptrdiff_t distance, MoveMethod method); // Returns number of bytes read. // Default implementation asserts as not supported and returns 0. virtual size_t TryRead(void* outBytes, size_t maxBytesToRead); // If not all bytes could be written, throws error. // Default implementation asserts as not supported. virtual void Write(const void* bytes, size_t bytesToWrite); // If not all bytes could be read, throws error. void Read(void* outBytes, size_t bytesToRead); void Read(std::span<char> outBytes) { Read(outBytes.data(), outBytes.size()); } template<typename T> void ReadValue(T& outValue) { Read(&outValue, sizeof(T)); } template<typename T> T ReadValue() { T result; Read(&result, sizeof(T)); return result; } void Write(std::span<const char> bytes) { Write(bytes.data(), bytes.size()); } template<typename T> void WriteValue(const T& value) { Write(&value, sizeof(T)); } void WriteString(const str_view& str) { Write(str.data(), str.length()); } void WriteString(const wstr_view& str) { Write(str.data(), str.length() * sizeof(wchar_t)); } }; class FileStream : public BaseStream { public: enum Flags { Flag_Read = 0x1, Flag_Write = 0x2, Flag_Sequential = 0x4, }; FileStream(const wstr_view& path, uint32_t flags); size_t GetSize() override; size_t GetPosition() override; size_t SetPosition(ptrdiff_t distance, MoveMethod method) override; size_t TryRead(void* outBytes, size_t maxBytesToRead) override; void Write(const void* bytes, size_t bytesToWrite) override; using BaseStream::Write; private: unique_ptr<HANDLE, CloseHandleDeleter> m_Handle; }; std::vector<char> LoadFile(const wstr_view& path); void SaveFile(const wstr_view& path, std::span<const char> bytes);
29.693182
77
0.641791
[ "vector" ]
314c71f0e71571028f87143a7bc7eaea4c94ab65
2,061
cpp
C++
IRadiance/src/IRadiance/Raytracer/Geometry/OpenCylinder.cpp
Nickelium/IRadiance
7e7040460852a6f9f977cf466e6dcecf44618ae7
[ "MIT" ]
null
null
null
IRadiance/src/IRadiance/Raytracer/Geometry/OpenCylinder.cpp
Nickelium/IRadiance
7e7040460852a6f9f977cf466e6dcecf44618ae7
[ "MIT" ]
null
null
null
IRadiance/src/IRadiance/Raytracer/Geometry/OpenCylinder.cpp
Nickelium/IRadiance
7e7040460852a6f9f977cf466e6dcecf44618ae7
[ "MIT" ]
null
null
null
#include "pch.h" #include "OpenCylinder.h" namespace IRadiance { const float OpenCylinder::eps = 1e-3f; OpenCylinder::OpenCylinder(float _r /*= 1.0f*/, float _y0 /*= -1.0f*/, float _y1 /*= 1.0f*/) : r(_r), y0(_y0), y1(_y1) { } bool OpenCylinder::Hit(const Ray& _ray, float& _tMin, HitRecord& _sr) const { float a = _ray.d.x * _ray.d.x + _ray.d.z * _ray.d.z; float b = 2.0f * (_ray.o.x * _ray.d.x + _ray.o.z * _ray.d.z); float c = _ray.o.x * _ray.o.x + _ray.o.z * _ray.o.z - r * r; float sqrtD = b * b - 4 * a * c; if (sqrtD < 0.0f) return false; float D = sqrt(sqrtD); float denom = 2 * a; float t = (-b - D) / denom; Point3 p = _ray.o + t * _ray.d; if (t > eps && y0 <= p.y && p.y <= y1) { _tMin = t; _sr.normal = Vector{ p.x, 0.0f, p.z } / r; return true; } t = (-b + D) / denom; p = _ray.o + t * _ray.d; if (t > eps && y0 <= p.y && p.y <= y1) { _tMin = t; _sr.normal = Vector{ p.x, 0.0f, p.z } / r; return true; } return false; } bool OpenCylinder::ShadowHit(const Ray& _ray, float& _t) const { if (!m_Shadow) return false; float a = _ray.d.x * _ray.d.x + _ray.d.z * _ray.d.z; float b = 2.0f * (_ray.o.x * _ray.d.x + _ray.o.z * _ray.d.z); float c = _ray.o.x * _ray.o.x + _ray.o.z * _ray.o.z - r * r; float sqrtD = b * b - 4 * a * c; if (sqrtD < 0.0f) return false; float D = sqrt(sqrtD); float denom = 2 * a; float t = (-b - D) / denom; Point3 p = _ray.o + t * _ray.d; if (t > eps && y0 <= p.y && p.y <= y1) { _t = t; return true; } t = (-b + D) / denom; p = _ray.o + t * _ray.d; if (t > eps && y0 <= p.y && p.y <= y1) { _t = t; return true; } return false; } Point3 OpenCylinder::Sample() const { //TODO return {}; } float OpenCylinder::pdf(const HitRecord&) const { //TODO return 0.0f; } Vector OpenCylinder::Normal(const Point3& _p) const { return Vector{ _p.x, 0.0f, _p.z } / r; } }
20.818182
94
0.499757
[ "vector" ]
3160ff127d7a7cdf5baaf3a2820cc018e4c7bdd5
1,785
cpp
C++
code/BFolder.cpp
omerdagan84/neomem
7d2f782bb37f1ab0ac6580d00672e114605afab7
[ "MIT" ]
1
2022-02-10T01:41:32.000Z
2022-02-10T01:41:32.000Z
code/BFolder.cpp
omerdagan84/neomem
7d2f782bb37f1ab0ac6580d00672e114605afab7
[ "MIT" ]
null
null
null
code/BFolder.cpp
omerdagan84/neomem
7d2f782bb37f1ab0ac6580d00672e114605afab7
[ "MIT" ]
null
null
null
#include "Precompiled.h" #include "BFolder.h" #include "ConstantsDatabase.h" #include "Brooklyn.h" // 'new' handler - create a BObject BFolder::BFolder(BDoc& doc, LPCTSTR pszName, OBJID idParent, OBJID idDefaultClass, OBJID idIcon, ULONG lngFlags) : // "classFolder": this is an object of class 'folder', not something in the 'class' folder. confusing. BObject(doc, classFolder, pszName, idParent, idIcon, lngFlags) // put overrides here { if (idDefaultClass) SetPropertyLink(propDefaultClass, idDefaultClass); } // static BFolder& BFolder::New(BDoc& doc, LPCTSTR pszName, OBJID idParent, OBJID idDefaultClass, OBJID idIcon, ULONG lngFlags) { BFolder* p = new BFolder(doc, pszName, idParent, idDefaultClass, idIcon, lngFlags); ASSERT_VALID(p); return *p; } // add a column to this folder's contents view void BFolder::AddColumn(OBJID idProperty, int nWidth, int nCol) { BData* pdat = GetPropertyData(propColumnInfoArray); if (!pdat) return; BDataColumns* pdatCols = DYNAMIC_DOWNCAST(BDataColumns, pdat); if (!pdatCols) {delete pdat; return;} //, d_d will eventually throw, so won't need this pdatCols->InsertColumn(idProperty, m_pDoc, nWidth, nCol); SetPropertyData(propColumnInfoArray, pdatCols); // saves a copy of pdatcols delete pdat; // don't forget this! } // remove a column from this folder's contents view void BFolder::RemoveColumn(OBJID idProperty) { BData* pdat = GetPropertyData(propColumnInfoArray); if (!pdat) return; BDataColumns* pdatCols = DYNAMIC_DOWNCAST(BDataColumns, pdat); if (!pdatCols) return; int nCol = pdatCols->GetColumnIndex(idProperty); if (nCol==-1) return; pdatCols->RemoveColumn(nCol); SetPropertyData(propColumnInfoArray, pdatCols); delete pdat; }
30.254237
120
0.72381
[ "object" ]
316246fe77b12a4cee080b8ed85734cf867ad335
1,962
hpp
C++
includes/General.hpp
Chobischtroumpf/webserv
d538d32e1ca24c51adc1e74b6f6856f445dff1c1
[ "Unlicense" ]
null
null
null
includes/General.hpp
Chobischtroumpf/webserv
d538d32e1ca24c51adc1e74b6f6856f445dff1c1
[ "Unlicense" ]
null
null
null
includes/General.hpp
Chobischtroumpf/webserv
d538d32e1ca24c51adc1e74b6f6856f445dff1c1
[ "Unlicense" ]
null
null
null
#ifndef GENERAL_HPP # define GENERAL_HPP # include <unistd.h> # include <sys/types.h> # include <sys/stat.h> # include <fcntl.h> # include <sys/wait.h> # include <sys/time.h> # include <sys/resource.h> # include <signal.h> # include <dirent.h> # include <stdio.h> # include <errno.h> # include <sys/select.h> # include <sys/socket.h> # include <netinet/in.h> # include <arpa/inet.h> # include <cstring> # include <cstdlib> # include <ctime> # include <iostream> # include <string> # include <vector> # include <list> # include <queue> # include <stack> # include <map> # include <algorithm> # include <iterator> # include <iomanip> # include <fstream> # include <iostream> # include "Exceptions.hpp" # include "Config.hpp" # define DEBUG(MSG) std::cout << "\033[0;35m\e[1m" << MSG << "\e[0m\033[0m" << std::endl; # define BUFFER_SIZE 1000000 // Tools/utils.cpp: std::list<std::string> splitString(std::string str, std::string sep); std::string ipBytesToIpv4(struct in_addr in); std::string& rtrim(std::string& s, const char* set); std::string& ltrim(std::string& s, const char* set); std::string& trim(std::string& s, const char* set); class Config; // logger: pattern : void log_<what_you_are_logging>(); void logEnv(); void logFile(std::string file); void logServConfig(Config::server config); // checker: pattern : bool is_<what_you_are_checking>(); bool isIp(std::string ip); bool isNumber(const std::string& s); // Parsing/InitParser.cpp: void parseEnv(char **env); std::string skipComment(std::string file); size_t skipBrackets(std::string str); std::string reverseStr(std::string str); size_t skipWhitespaces(std::string str); size_t countChar(char c, std::string str); int contentType(std::string clientRequest); size_t contentLength(std::string client_request); bool isFile(const std::string& str); bool file_exists(const std::string& str); bool isDir(const std::string& str); void ctrl_c(int signal); #endif
26.16
89
0.699796
[ "vector" ]
3168a92a157420f4ff75737272ad6dbbf8381956
6,183
cc
C++
resonance_audio/utils/lockless_task_queue_test.cc
seba10000/resonance-audio
e1923fe6fe733ae4d3c8460ff883c87e2ad05d6b
[ "Apache-2.0" ]
396
2018-03-14T09:55:52.000Z
2022-03-27T14:58:38.000Z
resonance_audio/utils/lockless_task_queue_test.cc
seba10000/resonance-audio
e1923fe6fe733ae4d3c8460ff883c87e2ad05d6b
[ "Apache-2.0" ]
46
2018-04-18T17:14:29.000Z
2022-02-19T21:35:57.000Z
resonance_audio/utils/lockless_task_queue_test.cc
seba10000/resonance-audio
e1923fe6fe733ae4d3c8460ff883c87e2ad05d6b
[ "Apache-2.0" ]
96
2018-03-14T17:20:50.000Z
2022-03-03T01:12:37.000Z
/* Copyright 2018 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "utils/lockless_task_queue.h" #include <atomic> #include <condition_variable> #include <memory> #include <mutex> #include <thread> #include <vector> #include "third_party/googletest/googletest/include/gtest/gtest.h" #include "base/logging.h" namespace vraudio { namespace { // Number of task producer threads. static const size_t kNumTaskProducers = 5; // Atomic thread counter used to trigger a simultaneous execution of all // threads. static std::atomic<size_t> s_thread_count(0); // Waits until all threads are initialized. static void WaitForProducerThreads() { static std::mutex mutex; static std::condition_variable cond_var; std::unique_lock<std::mutex> lock(mutex); if (++s_thread_count < kNumTaskProducers) { cond_var.wait(lock); } else { cond_var.notify_all(); } } static void IncVectorAtIndex(std::vector<size_t>* work_vector_ptr, size_t index) { ++(*work_vector_ptr)[index]; } class TaskProducer { public: TaskProducer(LocklessTaskQueue* queue, std::vector<size_t>* work_vector_ptr, int delay_ms) : producer_thread_(new std::thread(std::bind( &TaskProducer::Produce, this, queue, work_vector_ptr, delay_ms))) { } TaskProducer(TaskProducer&& task) : producer_thread_(std::move(task.producer_thread_)) {} void Join() { if (producer_thread_->joinable()) { producer_thread_->join(); } } private: void Produce(LocklessTaskQueue* queue, std::vector<size_t>* work_vector_ptr, int delay_ms) { WaitForProducerThreads(); for (size_t i = 0; i < work_vector_ptr->size(); ++i) { queue->Post(std::bind(IncVectorAtIndex, work_vector_ptr, i)); if (delay_ms > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms)); } } } std::unique_ptr<std::thread> producer_thread_; }; } // namespace class LocklessTaskQueueTest : public ::testing::Test { protected: // Virtual methods from ::testing::Test ~LocklessTaskQueueTest() override {} void SetUp() override {} void TearDown() override {} // Helper method to initialize and run the concurrency test with multiple // task producers and a single task executor. void ConcurrentThreadsMultipleTaskProducerSingleTaskExecutorTest( int producer_delay_ms) { s_thread_count = 0; const size_t kTasksPerProducer = 50; work_vector_.resize(kNumTaskProducers); std::fill(work_vector_.begin(), work_vector_.end(), 0); LocklessTaskQueue task_queue(kNumTaskProducers * kTasksPerProducer); std::vector<TaskProducer> task_producer_tasks; for (size_t i = 0; i < kNumTaskProducers; ++i) { task_producer_tasks.emplace_back(&task_queue, &work_vector_, producer_delay_ms); } WaitForProducerThreads(); task_queue.Execute(); for (auto& producer : task_producer_tasks) { producer.Join(); } task_queue.Execute(); for (size_t worker_count : work_vector_) { EXPECT_EQ(worker_count, kNumTaskProducers); } } std::vector<size_t> work_vector_; }; TEST_F(LocklessTaskQueueTest, MaxTasks) { LocklessTaskQueue task_queue(1); work_vector_.resize(1, 0); task_queue.Execute(); task_queue.Post(std::bind(IncVectorAtIndex, &work_vector_, 0)); // Second task should be dropped since queue is initialized with size 1. task_queue.Post(std::bind(IncVectorAtIndex, &work_vector_, 0)); task_queue.Execute(); EXPECT_EQ(work_vector_[0], 1U); task_queue.Post(std::bind(IncVectorAtIndex, &work_vector_, 0)); // Second task should be dropped since queue is initialized with size 1. task_queue.Post(std::bind(IncVectorAtIndex, &work_vector_, 0)); task_queue.Execute(); EXPECT_EQ(work_vector_[0], 2U); } TEST_F(LocklessTaskQueueTest, Clear) { LocklessTaskQueue task_queue(1); work_vector_.resize(1, 0); task_queue.Post(std::bind(IncVectorAtIndex, &work_vector_, 0)); task_queue.Clear(); task_queue.Execute(); EXPECT_EQ(work_vector_[0], 0U); } TEST_F(LocklessTaskQueueTest, SynchronousTaskExecution) { const size_t kNumRounds = 5; const size_t kNumTasksPerRound = 20; LocklessTaskQueue task_queue(kNumTasksPerRound); work_vector_.resize(kNumTasksPerRound, 0); for (size_t r = 0; r < kNumRounds; ++r) { for (size_t t = 0; t < kNumTasksPerRound; ++t) { task_queue.Post(std::bind(IncVectorAtIndex, &work_vector_, t)); } task_queue.Execute(); } for (size_t t = 0; t < kNumTasksPerRound; ++t) { EXPECT_EQ(work_vector_[t], kNumRounds); } } TEST_F(LocklessTaskQueueTest, SynchronousInOrderTaskExecution) { const size_t kNumTasksPerRound = 20; LocklessTaskQueue task_queue(kNumTasksPerRound); work_vector_.resize(kNumTasksPerRound, 0); work_vector_[0] = 1; const auto accumulate_from_lower_index_task = [this](size_t index) { work_vector_[index] += work_vector_[index - 1]; }; for (size_t t = 1; t < kNumTasksPerRound; ++t) { task_queue.Post(std::bind(accumulate_from_lower_index_task, t)); } task_queue.Execute(); for (size_t t = 0; t < kNumTasksPerRound; ++t) { EXPECT_EQ(work_vector_[t], 1U); } } // Tests concurrency of multiple producers and a single executor. TEST_F(LocklessTaskQueueTest, ConcurrentThreadsMultipleFastProducersSingleExecutor) { // Test fast producers and a fast consumer. ConcurrentThreadsMultipleTaskProducerSingleTaskExecutorTest( 0 /* producer delay in ms */); ConcurrentThreadsMultipleTaskProducerSingleTaskExecutorTest( 1 /* producer delay in ms */); } } // namespace vraudio
28.625
79
0.712761
[ "vector" ]
316bdf8fcf8def23e97940559da8c4cb0be68ab3
1,656
cpp
C++
src/posix/dlfcn.cpp
KristianJerpetjon/IncludeOS
367a1dcefafd6f9618e5373c9133839f9ee2d675
[ "Apache-2.0" ]
1
2019-09-14T09:58:20.000Z
2019-09-14T09:58:20.000Z
src/posix/dlfcn.cpp
KristianJerpetjon/IncludeOS
367a1dcefafd6f9618e5373c9133839f9ee2d675
[ "Apache-2.0" ]
1
2016-06-28T13:30:26.000Z
2016-06-28T13:30:26.000Z
src/posix/dlfcn.cpp
KristianJerpetjon/IncludeOS
367a1dcefafd6f9618e5373c9133839f9ee2d675
[ "Apache-2.0" ]
1
2019-09-14T09:58:31.000Z
2019-09-14T09:58:31.000Z
// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 <dlfcn.h> #include <cstdio> void* dlopen(const char *filename, int flag) { printf("dlopen called for %s with flag %#x\n", filename, flag); return nullptr; } char* dlerror(void) { printf("dlerror\n"); return nullptr; } void* dlsym(void*, const char* symbol) { printf("dlsym on %s\n", symbol); return nullptr; } int dlclose(void*) { printf("dlclose\n"); return 0; } typedef struct { const char *dli_fname; /* Pathname of shared object that contains address */ void *dli_fbase; /* Base address at which shared object is loaded */ const char *dli_sname; /* Name of symbol whose definition overlaps addr */ void *dli_saddr; /* Exact address of symbol named in dli_sname */ } Dl_info; extern "C" int dladdr(void*, Dl_info*) { return 0; }
28.551724
79
0.65157
[ "object" ]
316cc964a33f8cf10e911bfeee42de6514228cea
1,831
hpp
C++
Gamma/Sources/GammaRenderer.hpp
harskish/gamma
e627cc9e6159141f49852493025484cea4476050
[ "MIT" ]
2
2019-12-26T00:39:36.000Z
2020-12-03T16:36:04.000Z
Gamma/Sources/GammaRenderer.hpp
harskish/gamma
e627cc9e6159141f49852493025484cea4476050
[ "MIT" ]
null
null
null
Gamma/Sources/GammaRenderer.hpp
harskish/gamma
e627cc9e6159141f49852493025484cea4476050
[ "MIT" ]
1
2021-03-15T13:26:40.000Z
2021-03-15T13:26:40.000Z
#pragma once #include <GLFW/glfw3.h> #include <memory> #include <vector> #include <imgui.h> #include "Scene.hpp" #include "Camera.hpp" #include "IBLMaps.hpp" #include "BloomPass.hpp" class GammaRenderer { public: GammaRenderer(GLFWwindow *w); ~GammaRenderer() = default; void linkScene(std::shared_ptr<Scene> scene); void linkCamera(std::shared_ptr<CameraBase> camera) { this->camera = camera; } void render(); void drawStats(bool *show); void drawSettings(bool *show); void reshape(); void setRenderScale(float s) { renderScale = s; reshape(); } // Inserted into shaders as #define static const size_t MAX_LIGHTS = 6; private: GammaRenderer(const GammaRenderer&) = delete; GammaRenderer& operator=(const GammaRenderer&) = delete; void shadowPass(); void shadingPass(); void postProcessPass(); void drawSkybox(); void createDefaultCubemap(GLProgram *prog); void setupFBO(); // Rendering statistics // Double buffered to avoid waiting for results #define NUM_STATS 3 // shadows, shading, post-processing unsigned int queryID[2][NUM_STATS]; unsigned int queryBackBuffer = 0, queryFrontBuffer = 1; void genQueryBuffers(); void swapQueryBuffers(); GLFWwindow *window; std::shared_ptr<Scene> scene; std::shared_ptr<CameraBase> camera; float renderScale = 1.0f; // scales the FB size int fbWidth, fbHeight; int windowWidth, windowHeight; bool useFXAA = true; bool useBloom = true; std::unique_ptr<BloomPass> bloomPass; int tonemapOp = 0; // 0 => Uncharted 2, 1 => Reinhard float tonemapExposure = 1.0f; // FBO for postprocessing GLuint fbo = 0; GLuint colorTex[2] = { 0, 0 }; // ping pong GLuint depthTex = 0; int colorDst = 0; // index into colorTex };
26.926471
82
0.674495
[ "render", "vector" ]
31750565f1c88ea1cf21580dc244af4bdb1d1a9c
5,242
cpp
C++
legacy_renderer.cpp
RomanFesenko/SurfaceViewer
e8f27946ae3bce125b4c6639d9315e4652f401e5
[ "MIT" ]
null
null
null
legacy_renderer.cpp
RomanFesenko/SurfaceViewer
e8f27946ae3bce125b4c6639d9315e4652f401e5
[ "MIT" ]
null
null
null
legacy_renderer.cpp
RomanFesenko/SurfaceViewer
e8f27946ae3bce125b4c6639d9315e4652f401e5
[ "MIT" ]
null
null
null
#include <iostream> #include <assert.h> #include "opengl_iface.h" #include "legacy_renderer.h" void LegacyRender(const CFunctionalMesh&mesh) { using point_t=CFunctionalMesh::point_t; auto traits=mesh.RenderingTraits(); glDisable(GL_LIGHTING);// for correct use glColor* if(traits.IsBox()) { // draw the closing box auto box=mesh.BoundedBox(); point_t min=box.first; point_t max=box.second; point_t min_proj=min;min_proj[2]=max[2]; glColor3f(1.0,1.0,1.0); { CDrawGuard dg(GL_LINE_LOOP); point_t current=min; glVertex3fv(current.data()); current[0]=max[0]; glVertex3fv(current.data()); current[1]=max[1]; glVertex3fv(current.data()); current[0]=min[0]; glVertex3fv(current.data()); } { CDrawGuard dg(GL_LINE_LOOP); point_t current=min_proj; glVertex3fv(current.data()); current[0]=max[0]; glVertex3fv(current.data()); current[1]=max[1]; glVertex3fv(current.data()); current[0]=min[0]; glVertex3fv(current.data()); } { float saved_min0=min[0]; CDrawGuard dg(GL_LINES); glVertex3fv(min.data());glVertex3fv(min_proj.data()); min[0]=min_proj[0]=max[0]; glVertex3fv(min.data());glVertex3fv(min_proj.data()); min[1]=min_proj[1]=max[1]; glVertex3fv(min.data());glVertex3fv(min_proj.data()); min[0]=min_proj[0]=saved_min0; glVertex3fv(min.data());glVertex3fv(min_proj.data()); } glCheckError(); } // Levels rendering ? // Surface auto&mater=mesh.GetMaterial(); if(traits.IsSpecularSurface()) glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,mater.shininess); // render the surface int param=traits.IsSurface(); param|=traits.IsColored()<<1; param|=traits.IsSpecularSurface()<<2; float temp[4]={0,0,0,1}; switch(param) { case 1:// pure surface, uniform grey { glColor3f(0.5,0.5,0.5); CDrawGuard dg(GL_QUADS); auto visitor=[](auto&v){glVertex3fv(v.data());}; mesh.GetGrid().quad_visit(visitor,mesh.Points()); } break; case 3:// color surface { CDrawGuard dg(GL_QUADS); auto visitor=[&](auto&v,auto&c){glColor3fv(c.data());glVertex3fv(v.data());}; mesh.GetGrid().quad_visit(visitor,mesh.Points(),mesh.Colors()); } break; case 5:// specular surface glEnable(GL_LIGHTING); temp[0]=temp[1]=temp[2]=mater.ambient; glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT,temp); temp[0]=temp[1]=temp[2]=mater.diffuse; glMaterialfv(GL_FRONT_AND_BACK,GL_DIFFUSE,temp); temp[0]=temp[1]=temp[2]=mater.specular; glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,temp); { CDrawGuard dg(GL_QUADS); auto visitor=[](auto&v,auto&n){glNormal3fv(n.data());glVertex3fv(v.data());}; mesh.GetGrid().quad_visit(visitor,mesh.Points(),mesh.Normals()); } break; case 7:// colored and specular surface glEnable(GL_LIGHTING); { CDrawGuard dg(GL_QUADS); auto visitor=[&](auto&v,auto&c,auto&n) { temp[0]=c[0];temp[1]=c[1];temp[2]=c[2]; glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT,temp); glMaterialfv(GL_FRONT_AND_BACK,GL_DIFFUSE,temp); glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,temp); glColor3fv(c.data()); glNormal3fv(n.data()); glVertex3fv(v.data()); }; mesh.GetGrid().quad_visit(visitor,mesh.Points(),mesh.Colors(),mesh.Normals()); } break; default: assert((param&1)==0); } glDisable(GL_LIGHTING); glCheckError(); // Mesh param=traits.IsMesh(); param|=traits.IsSurface()<<1; param|=traits.IsColored()<<2; switch(param) { case 1:// pure mesh, uniform white glColor3f(1,1,1); { CDrawGuard dg(GL_LINES); auto visitor=[](auto&v){glVertex3fv(v.data());}; mesh.GetGrid().edge_visit(visitor,mesh.Points()); } break; case 3:// mesh over unpainted surface case 7:// mesh over painted surface glColor3f(0,0,0); glLineWidth(2); { CDrawGuard dg(GL_LINES); auto visitor=[](auto&v){glVertex3fv(v.data());}; mesh.GetGrid().edge_visit(visitor,mesh.Points()); } glLineWidth(1); break; case 5:// colored mesh { CDrawGuard dg(GL_LINES); auto visitor=[](auto&v,auto&c){glColor3fv(c.data());glVertex3fv(v.data());}; mesh.GetGrid().edge_visit(visitor,mesh.Points(),mesh.Colors()); } break; default:assert((param&1)==0); } glCheckError(); glDisable(GL_COLOR_MATERIAL); }
23.401786
95
0.544258
[ "mesh", "render" ]
317be9ad073b87aad0e705ab734bc65c0f8c027c
4,498
cpp
C++
base/patterns/inverse/reader.cpp
zeionara/meager
a7634103cf92452a7396f100fdd7a0f7e9946315
[ "Apache-2.0" ]
null
null
null
base/patterns/inverse/reader.cpp
zeionara/meager
a7634103cf92452a7396f100fdd7a0f7e9946315
[ "Apache-2.0" ]
null
null
null
base/patterns/inverse/reader.cpp
zeionara/meager
a7634103cf92452a7396f100fdd7a0f7e9946315
[ "Apache-2.0" ]
null
null
null
#include <fstream> #include <vector> #include <unordered_set> #include "main.h" #include "../../Reader.h" using namespace std; const int nTriplesPerPattern = 2; // vector<PatternInstance> symmetricTriples; vector<PatternInstance>** inverseTriplePatternInstances = (vector<PatternInstance>**)malloc(sizeof(vector<PatternInstance>*) * (nTriplesPerPattern + 1)); void separateInverseTriples(bool verbose = false, bool drop_duplicates = true) { if (verbose) { cout << "Separating inverse triples..." << endl; } ifstream in_file(inPath + "patterns/inverse.txt"); int forwardRelation, backwardRelation; // unordered_set<int> inverseForwardRelations; // unordered_set<int> inverseBackwardRelations; unordered_map<int, int> inverseForwardRelationToBackward; unordered_map<int, int> inverseBackwardRelationToForward; while (in_file >> forwardRelation >> backwardRelation) { if (verbose) { printf("Read relations %d and %d.\n", forwardRelation, backwardRelation); } // inverseForwardRelations.insert(forwardRelation); // inverseBackwardRelations.insert(backwardRelation); inverseForwardRelationToBackward[forwardRelation] = backwardRelation; inverseBackwardRelationToForward[backwardRelation] = forwardRelation; } if (verbose) { printf("Number of inverse relations = %d.\n", (int)inverseForwardRelationToBackward.size()); } in_file.close(); if (verbose) { cout << "Inverse triples" << endl; } unordered_set<string> seenInstances; for (int i = 0; i <= nTriplesPerPattern; i++) { inverseTriplePatternInstances[i] = new vector<PatternInstance>; } auto pushPatternInstance = [drop_duplicates, &seenInstances](PatternInstance patternInstance) { if (drop_duplicates) { string direct_pattern_instance_concise_description = patternInstance.getConciseDescription(); if (seenInstances.find(direct_pattern_instance_concise_description) == seenInstances.end()) { for (int j = 0; j <= nTriplesPerPattern; j++) { if (j <= patternInstance.observedTripleIndices.size()) { inverseTriplePatternInstances[j]->push_back(patternInstance); } } seenInstances.insert(direct_pattern_instance_concise_description); } } else { for (int j = 0; j <= nTriplesPerPattern; j++) { if (j <= patternInstance.observedTripleIndices.size()) { inverseTriplePatternInstances[j]->push_back(patternInstance); } } } }; for (INT i = 0; i < trainTotal; i++) { // Reading train samples Triple triple = trainList[i]; auto forwardRelationIterator = inverseForwardRelationToBackward.find(triple.r); // unordered_map<INT, unordered_set<INT>> if (forwardRelationIterator != inverseForwardRelationToBackward.end()) { auto direct_pattern_instance = InversePatternInstance( triple, Triple(triple.t, forwardRelationIterator->second, triple.h) ); pushPatternInstance(direct_pattern_instance); } else { auto backwardRelationIterator = inverseBackwardRelationToForward.find(triple.r); // unordered_map<INT, unordered_set<INT>> if (backwardRelationIterator != inverseBackwardRelationToForward.end()) { auto inverse_pattern_instance = InversePatternInstance( Triple(triple.t, backwardRelationIterator->second, triple.h), triple, false ); pushPatternInstance(inverse_pattern_instance); } } } if (verbose) { for (int i = 0; i <= nTriplesPerPattern; i++) { cout << "Collected " << inverseTriplePatternInstances[i]->size() << " inverse pattern instances in which there are " << i << " or more observed patterns" << endl; } std::cout << std::endl; // std::cout << std::endl << std::endl; // // for (PatternInstance patternInstance: **inverseTriplePatternInstances) { // ((InversePatternInstance*)&patternInstance)->print(); // } } patternDescriptions[inversePatternName] = PatternDescription(inverse, nTriplesPerPattern, inverseTriplePatternInstances); }
38.444444
174
0.636505
[ "vector" ]
317da2cd8c1a41bec3427245671051ab0e219364
2,663
hxx
C++
cpp/src/nvgraph/include/widest_path.hxx
rgsl888prabhu/cugraph
e030a2fe22ad308fba05d6146765a3c9aa865e5b
[ "Apache-2.0" ]
16
2019-09-13T11:43:26.000Z
2022-03-02T10:11:59.000Z
cpp/src/nvgraph/include/widest_path.hxx
rgsl888prabhu/cugraph
e030a2fe22ad308fba05d6146765a3c9aa865e5b
[ "Apache-2.0" ]
5
2020-02-12T14:55:25.000Z
2021-12-06T17:55:12.000Z
cpp/src/nvgraph/include/widest_path.hxx
rgsl888prabhu/cugraph
e030a2fe22ad308fba05d6146765a3c9aa865e5b
[ "Apache-2.0" ]
6
2020-04-06T01:34:45.000Z
2021-01-21T17:13:24.000Z
/* * Copyright (c) 2019, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once namespace nvgraph { template <typename IndexType_, typename ValueType_> class WidestPath { public: typedef IndexType_ IndexType; typedef ValueType_ ValueType; private: ValuedCsrGraph <IndexType, ValueType> m_network ; Vector <ValueType> m_widest_path; Vector <ValueType> m_tmp; Vector <int> m_mask; // mask[i] = 0 if we can ignore the i th column in the csrmv IndexType m_source; ValueType m_residual; int m_iterations; bool m_is_setup; cudaStream_t m_stream; bool solve_it(); void setup(IndexType source_index, Vector<ValueType>& source_connection, Vector<ValueType>& WidestPath_result); public: // Simple constructor WidestPath(void) {}; // Simple destructor ~WidestPath(void) {}; // Create a WidestPath solver attached to a the transposed of a weighted network // *** network is the transposed/CSC*** WidestPath(const ValuedCsrGraph <IndexType, ValueType>& network, cudaStream_t stream = 0):m_network(network),m_is_setup(false), m_stream(stream) {}; /*! Find the Widest Path from the vertex source_index to every other vertices. * * \param source_index The source. * \param source_connection The connectivity of the source * - if there is a link from source_index to i, source_connection[i] = E(source_index, i) ) * - otherwise source_connection[i] = op.plus->id * - source_connection[source_index] = op.time->id The source_connection is provided as input * \param (output) m_widest_path m_widest_path[i] contains the Widest Path from the source to the vertex i. */ NVGRAPH_ERROR solve(IndexType source_index, Vector<ValueType>& source_connection, Vector<ValueType>& WidestPath_result); inline int get_iterations() const {return m_iterations;} }; } // end namespace nvgraph
42.269841
153
0.664664
[ "vector" ]
31870745797512434007fd022e242ef5c60505b5
473
cpp
C++
Dataset/Leetcode/train/88/234.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/88/234.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/88/234.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: void XXX(vector<int>& nums1, int m, vector<int>& nums2, int n) { int t = m+n-1; int i = m - 1, j = n - 1; while(i >= 0 && j >= 0){ if(nums1[i]>=nums2[j]){ nums1[t--] = nums1[i--]; }else{ nums1[t--] = nums2[j--]; } } while(j >= 0){ nums1[t--]=nums2[j--]; } return; } };
22.52381
68
0.325581
[ "vector" ]
3189a9eadcd696622e7f839ca67e265b3be2ba5b
2,131
cpp
C++
Engine/Src/BRQ/Utilities/FileSystem.cpp
saeenyoda/Burraq-Engine
885c76308358515ef4af9fcc4d6802985ae2aa18
[ "MIT" ]
null
null
null
Engine/Src/BRQ/Utilities/FileSystem.cpp
saeenyoda/Burraq-Engine
885c76308358515ef4af9fcc4d6802985ae2aa18
[ "MIT" ]
null
null
null
Engine/Src/BRQ/Utilities/FileSystem.cpp
saeenyoda/Burraq-Engine
885c76308358515ef4af9fcc4d6802985ae2aa18
[ "MIT" ]
null
null
null
#include <BRQ.h> #include "FileSystem.h" namespace BRQ { namespace Utilities { FileSystem* FileSystem::s_Instance = nullptr; void FileSystem::Init() { s_Instance = new FileSystem(); } void FileSystem::Shutdown() { if (s_Instance) { delete s_Instance; } } std::vector<BYTE> FileSystem::ReadFile(const std::string_view& filename, InputMode mode) const { std::vector<BYTE> result; FILE* handle = nullptr; std::string path = m_RootDirectory + filename.data(); errno_t error = fopen_s(&handle, path.c_str(), InputModeToString(mode)); if (error) { BRQ_CORE_WARN("Can't open file: {}", path.c_str()); return result; } fseek(handle, 0, SEEK_END); U64 size = ftell(handle); fseek(handle, 0, SEEK_SET); result.resize(size); fread(&result[0], size, sizeof(BYTE), handle); return std::move(result); } void FileSystem::WriteFile(const std::string_view& filename, InputMode mode, const std::vector<BYTE>& data) const { FILE* handle = nullptr; std::string path = m_RootDirectory + filename.data(); errno_t error = fopen_s(&handle, path.c_str(), InputModeToString(mode)); if (error) { BRQ_CORE_WARN("Can't write to file: {}", path.c_str()); return; } fwrite(&data[0], data.size(), sizeof(BYTE), handle); } const char* FileSystem::InputModeToString(InputMode mode) const { switch (mode) { case InputMode::ReadOnly: return "r"; case InputMode::ReadBinary: return "rb"; case InputMode::WriteOnly: return "w"; case InputMode::WriteBinary: return "wb"; case InputMode::Append: return "a"; case InputMode::ApendBinary: return "ab"; case InputMode::ReadAndWrite: return "r+"; case InputMode::ReadAndWriteBinary: return "rb+"; default: return "rb+"; } } } }
23.417582
119
0.557015
[ "vector" ]
318eff9ad9547c6f94ab72d81c9fa1e55b46bd2e
105,086
cpp
C++
Libraries/RobsJuceModules/jura_processors/instruments/jura_Liberty.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
34
2017-04-19T18:26:02.000Z
2022-02-15T17:47:26.000Z
Libraries/RobsJuceModules/jura_processors/instruments/jura_Liberty.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
307
2017-05-04T21:45:01.000Z
2022-02-03T00:59:01.000Z
Libraries/RobsJuceModules/jura_processors/instruments/jura_Liberty.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
4
2017-09-05T17:04:31.000Z
2021-12-15T21:24:28.000Z
using namespace romos; //================================================================================================= // class LibertyInterfaceState: LibertyInterfaceState::LibertyInterfaceState() { activePanel = STRUCTURE_PANEL; } //================================================================================================= // class LibertyAudioModule: /* LibertyAudioModule::LibertyAudioModule(CriticalSection *newPlugInLock, romos::Liberty *modularSynthToWrap) : PolyphonicInstrumentAudioModule(newPlugInLock, modularSynthToWrap) //: AudioModule(newPlugInLock) { jassert(modularSynthToWrap != NULL); // you must pass a valid rosic-object to the constructor wrappedLiberty = modularSynthToWrap; underlyingRosicInstrument = modularSynthToWrap; init(); } */ LibertyAudioModule::LibertyAudioModule(CriticalSection *newPlugInLock) : PolyphonicInstrumentAudioModule(newPlugInLock) { wrappedLiberty = new romos::Liberty; //underlyingRosicInstrument = wrappedLiberty; wrappedLibertyIsOwned = true; init(); } void LibertyAudioModule::init() { setModuleTypeName("Liberty"); macroDirectory = getPresetDirectory() + "/Macros"; } LibertyAudioModule::~LibertyAudioModule() { if(wrappedLibertyIsOwned) delete wrappedLiberty; } AudioModuleEditor* LibertyAudioModule::createEditor(int type) { return new jura::LibertyEditor(lock, this); // get rid of passing the lock } //------------------------------------------------------------------------------------------------- // persistence: void LibertyAudioModule::writeModuleTypeSpecificStateDataToXml(romos::Module *module, XmlElement* xmlState) { romos::ParameterMixIn *m = dynamic_cast<romos::ParameterMixIn*> (module); if( m != NULL ) { for(int i = 0; i < m->getNumParameters(); i++) xmlState->setAttribute(rosicToJuce(m->getParameterName(i)), rosicToJuce(m->getParameterValue(i))); } } void LibertyAudioModule::restoreModuleTypeSpecificStateDataFromXml(romos::Module *module, const XmlElement& xmlState) { romos::ParameterMixIn *m = dynamic_cast<romos::ParameterMixIn*> (module); if( m != NULL ) { if ( module->isParameterModule() ) // to be used later //if( module->getTypeIdentifierOld() == romos::ModuleTypeRegistry::PARAMETER ) { // we need special treatment of the parameter module - minValue/maxValue shlould be set // simultaneuously, because otherwise, min/max might not be recalled correctly, for example // when newMin > oldMax, the module will refuse to use the new minimum, etc. moreover, // min/max must be set up before attempting to set the default and current value: double min = xmlState.getDoubleAttribute("MinValue", 0.0); double max = xmlState.getDoubleAttribute("MaxValue", 1.0); juce::String mappingString = xmlState.getStringAttribute("MaxValue", "Linear"); int mappingIndex = romos::ParameterModule::LINEAR_MAPPING; if( mappingString == "Exponential" ) mappingIndex = romos::ParameterModule::EXPONENTIAL_MAPPING; ((romos::ParameterModule*) m)->setMinMaxAndMapping(min, max, mappingIndex); } for(int i = 0; i < m->getNumParameters(); i++) { juce::String name = rosicToJuce(m->getParameterName(i)); juce::String defaultValue = rosicToJuce(m->getParameterDefaultValue(i)); juce::String storedValue = xmlState.getStringAttribute(name, defaultValue); m->setParameter(i, juceToRosic(storedValue)); } } } XmlElement* LibertyAudioModule::getModuleStateAsXml(romos::Module *module, bool withExternalConnections) { //ScopedLock scopedLock(*plugInLock); // this function is static XmlElement *xmlState = new XmlElement(rosicToJuce(module->getTypeName())); std::map<std::string, std::string> stateMap = module->getState(); if(!stateMap.empty()) addAttributesFromMap(*xmlState, stateMap); else jassertfalse; unsigned int i; romos::ContainerModule *container = dynamic_cast<romos::ContainerModule*> (module); if( container != NULL ) { for(i=0; i<container->getNumChildModules(); i++) xmlState->addChildElement( getModuleStateAsXml(container->getChildModule(i), true) ); } else writeModuleTypeSpecificStateDataToXml(module, xmlState); // store audio connections: // input modules have invisible "ghost" connections to the source that goes into the // respective container - we don't want to store these: if( !module->isInputModule() ) { if( withExternalConnections == true ) { romos::AudioConnection ac; // connection under investigation juce::String connectionString; std::vector<romos::AudioConnection> incomingConnections = module->getIncomingAudioConnections(); for(i = 0; i < incomingConnections.size(); i++) { ac = incomingConnections[i]; connectionString += juce::String(("A_")) + juce::String(ac.getSourceModule()->getIndexWithinParentModule()) + juce::String("_") + juce::String(ac.getSourceOutputIndex()) + juce::String("_") + juce::String(ac.getTargetInputIndex()) + juce::String(", "); } // \todo add event connections to the string.. if( connectionString != juce::String() ) { connectionString = connectionString.trimCharactersAtEnd(juce::String(", ")); xmlState->setAttribute(juce::String(("IncomingConnections")), connectionString); } } } return xmlState; } void LibertyAudioModule::createAndSetupEmbeddedModulesFromXml(const XmlElement& xmlState, romos::Module *module) { if( module == nullptr ) { jassertfalse; return; } std::map<std::string, std::string> moduleState = getAttributesAsMap(xmlState); module->setState(moduleState); if( module->isContainerModule() || module->isTopLevelModule() ) { romos::ContainerModule *container = dynamic_cast<romos::ContainerModule*> (module); for(int i=0; i<xmlState.getNumChildElements(); i++) { XmlElement* childState = xmlState.getChildElement(i); rosic::rsString moduleTypeName = juceToRosic(childState->getTagName()); // get rid of that intermediate format int typeIdentifier = romos::moduleFactory.getModuleId(moduleTypeName.asStdString()); if( typeIdentifier != -1 ) { // verify that this is useless and then delete this old code: //if( module->isTopLevelModule() // && romos::ModuleTypeRegistry::isIdentifierInputOrOutput(typeIdentifier) ) //if( module->isTopLevelModule() && (module->isInputModule() || module->isOutputModule()) ) // noo - this is wrong - we are not interested in whethere the "module" is I/O but rather // the child to be added should be I/O if( module->isTopLevelModule() && (moduleTypeName == "AudioInput" || moduleTypeName == "AudioOutput") ) { // do nothing when this is the top-level module and the to-be-added child is an I/O module } else { romos::Module *newModule = container->addChildModule( moduleTypeName.asStdString(), "", 0, 0, false, false); createAndSetupEmbeddedModulesFromXml(*childState, newModule); } } } container->sortChildModuleArray(); } else restoreModuleTypeSpecificStateDataFromXml(module, xmlState); } void LibertyAudioModule::createConnectionsFromXml(const XmlElement& xmlState, romos::Module *module) { if( module == NULL ) { jassertfalse; return; } juce::String connectionString = xmlState.getStringAttribute("IncomingConnections", juce::String()); if( connectionString != juce::String() ) { connectionString = connectionString.removeCharacters(" "); juce::String remainingString = connectionString + juce::String(","); juce::String currentString; juce::String tmpString1, tmpString2; int smi, spi, tpi; // source module- and pin-index, target pin index while( remainingString != juce::String() ) { currentString = remainingString.upToFirstOccurrenceOf(",", false, false); remainingString = remainingString.fromFirstOccurrenceOf(",", false, false); tmpString1 = currentString; int connectionKind; if( tmpString1.startsWithChar('A') ) connectionKind = romos::AUDIO; else if( tmpString1.startsWithChar('E') ) connectionKind = romos::EVENT; else { jassertfalse; // unknown connection type connectionKind = romos::AUDIO; } tmpString1 = tmpString1.fromFirstOccurrenceOf("_", false, false); tmpString2 = tmpString1.upToFirstOccurrenceOf("_", false, false); smi = tmpString2.getIntValue(); tmpString1 = tmpString1.fromFirstOccurrenceOf("_", false, false); tmpString2 = tmpString1.upToFirstOccurrenceOf("_", false, false); spi = tmpString2.getIntValue(); tmpString1 = tmpString1.fromFirstOccurrenceOf("_", false, false); tmpString2 = tmpString1.upToFirstOccurrenceOf("_", false, false); tpi = tmpString2.getIntValue(); romos::ContainerModule *parentModule = module->getParentModule(); if( parentModule != NULL ) // maybe NULL when this is called from ModularBlockDiagramPanel::openContainerSaveDialog { romos::Module *sourceModule = parentModule->getChildModule(smi); if( connectionKind == romos::AUDIO ) parentModule->addAudioConnection(sourceModule, spi, module, tpi); else if( connectionKind == romos::EVENT ) { // \todo add the event connection here } } } } // recursion: romos::ContainerModule *container = dynamic_cast<romos::ContainerModule*> (module); if( container != NULL ) { for(unsigned int i=0; i<container->getNumChildModules(); i++) { XmlElement *childState = xmlState.getChildElement(i); romos::Module *childModule = container->getChildModule(i); if( childState != NULL ) createConnectionsFromXml(*childState, childModule); else romos::triggerRuntimeError("Number of embedded modules does not match number of child elements \ in LibertyAudioModule::createConnectionsFromXml"); //jassertfalse; // number of embedded modules does not match number of child elements } } } void LibertyAudioModule::setModuleStateFromXml(const XmlElement& xmlState, romos::Module *module) { createAndSetupEmbeddedModulesFromXml(xmlState, module); createConnectionsFromXml(xmlState, module); } XmlElement* LibertyAudioModule::getStateAsXml(const juce::String &stateName, bool markAsClean) { ScopedLock scopedLock(*lock); //XmlElement* xmlState = PolyphonicInstrumentAudioModule::getStateAsXml(stateName, false); XmlElement* xmlState = AudioModule::getStateAsXml(stateName, false); romos::Module *topLevelMasterVoice = wrappedLiberty->getTopLevelModule(); xmlState->addChildElement( getModuleStateAsXml(topLevelMasterVoice, true) ); return xmlState; } void LibertyAudioModule::setStateFromXml(const XmlElement& xmlState, const juce::String& stateName, bool markAsClean) { ScopedLock scopedLock(*lock); sendActionMessage("StateRecall"); // GUI should delete all pointers to the modules wrappedLiberty->reset(); romos::TopLevelModule *topLevelModule = wrappedLiberty->getTopLevelModule(); topLevelModule->deleteAllChildModules(); topLevelModule->disconnectAudioOutputModules(); XmlElement* topLevelModuleState = xmlState.getChildByName("TopLevelModule"); if( topLevelModuleState != nullptr ) setModuleStateFromXml(*topLevelModuleState, topLevelModule); restoreTopLevelInOutStates(*topLevelModuleState); //PolyphonicInstrumentAudioModule::setStateFromXml(xmlState, stateName, markAsClean); AudioModule::setStateFromXml(xmlState, stateName, markAsClean); } void LibertyAudioModule::restoreTopLevelInOutStates(const XmlElement& xmlState) { ScopedLock scopedLock(*lock); romos::ContainerModule *topLevelMasterVoice = wrappedLiberty->getTopLevelModule(); XmlElement *childElement; int numInsRestored = 0; int numOutsRestored = 0; int x, y; for(int i=0; i<xmlState.getNumChildElements(); i++) { childElement = xmlState.getChildElement(i); if( childElement->hasTagName(juce::String(("AudioInput"))) ) { x = childElement->getIntAttribute(juce::String(("X")), 2); y = childElement->getIntAttribute(juce::String(("Y")), 2+2*numInsRestored); topLevelMasterVoice->getAudioInputModule(numInsRestored)->setPositionXY( childElement->getIntAttribute(juce::String(("X")), 2), childElement->getIntAttribute(juce::String(("Y")), 2+2*numInsRestored), false); numInsRestored++; } else if( childElement->hasTagName(juce::String(("AudioOutput"))) ) { topLevelMasterVoice->getAudioOutputModule(numOutsRestored)->setPositionXY( childElement->getIntAttribute(juce::String(("X")), 2), childElement->getIntAttribute(juce::String(("Y")), 2+2*numOutsRestored), false); numOutsRestored++; } if( numInsRestored >= 2 && numOutsRestored >= 2 ) return; } } //------------------------------------------------------------------------------------------------- // event handling: void LibertyAudioModule::noteOn(int noteNumber, int velocity) { wrappedLiberty->noteOn(noteNumber, velocity); } void LibertyAudioModule::noteOff(int noteNumber) { wrappedLiberty->noteOff(noteNumber); } //================================================================================================= //================================================================================================= // class ModulePropertiesEditor: //ModulePropertiesEditor::ModulePropertiesEditor(CriticalSection *newPlugInLock, // romos::Module* newModuleToEdit) ModulePropertiesEditor::ModulePropertiesEditor(LibertyAudioModule *newLiberty, romos::Module* newModuleToEdit) { //plugInLock = newPlugInLock; // old // new: libertyModule = newLiberty; plugInLock = libertyModule->getCriticalSection();; ScopedLock scopedLock(*plugInLock); moduleToEdit = newModuleToEdit; libertyModule->addActionListener(this); setHeadlineStyle(Editor::SUB_HEADLINE); setHeadlineText(rosicToJuce(moduleToEdit->getName())); moduleTypeLabel = new RTextField(juce::String("Type:")); moduleTypeLabel->setDescription(juce::String("Type of the module")); addWidget(moduleTypeLabel, true, true); moduleTypeField = new RTextField(rosicToJuce(moduleToEdit->getTypeName())); moduleTypeField->setJustification(Justification::centredLeft); moduleTypeField->setDescription(moduleTypeLabel->getDescription()); addWidget(moduleTypeField, true, true); polyButton = new RButton(juce::String("Poly")); polyButton->setDescription(juce::String("Switch between polyphonic/monophonic mode")); polyButton->setToggleState(moduleToEdit->isPolyphonic(), false); addWidget(polyButton, true, true); } ModulePropertiesEditor::~ModulePropertiesEditor() { libertyModule->removeActionListener(this); } void ModulePropertiesEditor::rSliderValueChanged(RSlider* rSlider) { ScopedLock scopedLock(*plugInLock); widgetChanged(rSlider); } void ModulePropertiesEditor::rComboBoxChanged(RComboBox* comboBoxThatHasChanged) { ScopedLock scopedLock(*plugInLock); widgetChanged(comboBoxThatHasChanged); } void ModulePropertiesEditor::textChanged(RTextEntryField *rTextEntryFieldThatHasChanged) { ScopedLock scopedLock(*plugInLock); widgetChanged(rTextEntryFieldThatHasChanged); } void ModulePropertiesEditor::rButtonClicked(RButton *buttonThatWasClicked) { ScopedLock scopedLock(*plugInLock); widgetChanged(buttonThatWasClicked); } void ModulePropertiesEditor::widgetChanged(RWidget *widgetThatHasChanged) { ScopedLock scopedLock(*plugInLock); romos::ParameterMixIn *m = dynamic_cast<romos::ParameterMixIn*> (moduleToEdit); if( m != NULL ) { LibertyModuleWidget *lmw = dynamic_cast<LibertyModuleWidget*> (widgetThatHasChanged); if( lmw != NULL ) { rosic::rsString name = juceToRosic(lmw->getWidgetParameterName()); rosic::rsString value = juceToRosic(widgetThatHasChanged->getStateAsString()); m->setParameter(name, value); } } updateWidgetsFromModuleState(); // to update the other widgets, implements widget-interdependence } void ModulePropertiesEditor::actionListenerCallback(const String& message) { if(message == "StateRecall") moduleToEdit = nullptr; // invalidate pointer } void ModulePropertiesEditor::resized() { ScopedLock scopedLock(*plugInLock); int x, y, w, h; x = 0; //y = getHeadlineBottom()+4; y = getHeight()-20; h = 16; moduleTypeLabel->setBounds(x, y, 36, 16); x = moduleTypeLabel->getRight(); w = getWidth()-x; moduleTypeField->setBounds(x, y, w, 16); w = 32; x = getWidth() - w - 4; polyButton->setBounds(x, y, w, 16); } void ModulePropertiesEditor::updateWidgetsFromModuleState() { ScopedLock scopedLock(*plugInLock); romos::ParameterMixIn *m = dynamic_cast<romos::ParameterMixIn*> (moduleToEdit); if( m != NULL ) { for(int i = 0; i < widgets.size(); i++) { RWidget *widget = widgets[i]; // for debug LibertyModuleWidget *lmw = dynamic_cast<LibertyModuleWidget*> (widgets[i]); if( lmw != NULL ) { rosic::rsString name = juceToRosic(lmw->getWidgetParameterName()); juce::String value = rosicToJuce(m->getParameterValue(name)); widgets[i]->setStateFromString(value, false); } } } } //================================================================================================= //================================================================================================= LibertyInterfaceComponent::LibertyInterfaceComponent( LibertyInterfaceMediator *interfaceMediatorToUse) { mediator = interfaceMediatorToUse; } LibertyInterfaceMediator* LibertyInterfaceComponent::getInterfaceMediator() const { return dynamic_cast<LibertyInterfaceMediator*> (mediator); } //================================================================================================= LibertyInterfaceMediator::LibertyInterfaceMediator(CriticalSection *newPlugInLock, LibertyAudioModule* newLibertyModuleToEdit) { plugInLock = newPlugInLock; ScopedLock scopedLock(*plugInLock); modularSynthModuleToEdit = newLibertyModuleToEdit; topLevelModule = modularSynthModuleToEdit->wrappedLiberty->getTopLevelModule(); containerShownInDiagram = topLevelModule; moduleToShowEditorFor = containerShownInDiagram; } LibertyInterfaceMediator::~LibertyInterfaceMediator() { //int dummy = 0; } void LibertyInterfaceMediator::setContainerToShowInDiagram(romos::ContainerModule* containerToShow) { ScopedLock scopedLock(*plugInLock); containerShownInDiagram = containerToShow; //moduleToShowEditorFor = containerShownInDiagram; // superfluous? setModuleToShowEditorFor(containerShownInDiagram); Mediator::sendNotificationToColleagues(NULL, LibertyInterfaceComponent::CONTAINER_SHOWN_IN_DIAGRAM); // NULL is preliminary } void LibertyInterfaceMediator::setModuleToShowEditorFor(romos::Module *module) { ScopedLock scopedLock(*plugInLock); moduleToShowEditorFor = module; Mediator::sendNotificationToColleagues(NULL, LibertyInterfaceComponent::MODULE_TO_SHOW_EDITOR_FOR); // NULL is preliminary } //================================================================================================= // class ModularStructureTreeView ModularStructureTreeView::ModularStructureTreeView(LibertyInterfaceMediator *interfaceMediatorToUse) : LibertyInterfaceComponent(interfaceMediatorToUse) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); //mediator->registerColleague(this); setMediator(interfaceMediatorToUse); // will register "this" as colleague setRootNode( new RTreeViewNode(juce::String("TopLevelModule")) ); rootNode->setDeleteChildNodesOnDestruction(true); rootNode->setUserData(getInterfaceMediator()->topLevelModule); rebuildTree(); } ModularStructureTreeView::~ModularStructureTreeView() { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); //getInterfaceMediator()->deRegisterInterfaceComponent(this); // should be done in baseclass destructor delete rootNode; } //------------------------------------------------------------------------------------------------- // callbacks: void ModularStructureTreeView::mediatorHasSentNotification( MediatedColleague *originatingColleague, int messageCode) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); if( messageCode == NUM_CHILDREN || messageCode == MODULE_NAME || messageCode == CONTAINER_SHOWN_IN_DIAGRAM ) // actually, the last one is overkill - we only need to rebuild if the top-level module // changes - i.e. a patch is loaded { rebuildTree(); // \todo often, rebuilding the whole tree is overkill and it may suffice to just add or remove // a single node - we need to somehow distinguis these cases.... } if( messageCode == MODULE_TO_SHOW_EDITOR_FOR ) updateNodeHighlighting(); } void ModularStructureTreeView::nodeClicked(RTreeViewNode *nodeThatWasClicked, const MouseEvent &mouseEvent, int clickPosition) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); if( clickPosition == RTreeView::ON_TEXT ) { romos::Module *clickedNodeModule = static_cast<romos::Module*> (nodeThatWasClicked->getUserData()); if( dynamic_cast<romos::ContainerModule*> (clickedNodeModule) != NULL ) getInterfaceMediator()->setContainerToShowInDiagram( static_cast<romos::ContainerModule*> (nodeThatWasClicked->getUserData()) ); else { getInterfaceMediator()->setContainerToShowInDiagram(clickedNodeModule->getParentModule()); //if( romos::ModuleTypeRegistry::hasModuleTypeEditor(clickedNodeModule->getTypeIdentifierOld()) ) if( clickedNodeModule->hasEditor() ) getInterfaceMediator()->setModuleToShowEditorFor(clickedNodeModule); } } else if( clickPosition == RTreeView::ON_PLUSMINUS ) RTreeView::nodeClicked(nodeThatWasClicked, mouseEvent, clickPosition); // opens/closes the node } //------------------------------------------------------------------------------------------------- // others: void ModularStructureTreeView::rebuildTree() { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); rootNode->deleteChildNodesRecursively(); rootNode->setNodeText(rosicToJuce(getInterfaceMediator()->topLevelModule->getName())); for(unsigned int i=0; i<getInterfaceMediator()->topLevelModule->getNumChildModules(); i++) { // \todo add I/O modules ... or maybe not... createAndHangInSubTree(rootNode, getInterfaceMediator()->topLevelModule->getChildModule(i)); } updateScrollBarBoundsAndVisibility(); updateNodeHighlighting(); repaint(); } void ModularStructureTreeView::createAndHangInSubTree(RTreeViewNode *parentNodeToUse, romos::Module *moduleToCreateSubTreeFor) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); // check if node is container - if not do nothing and return - we don't want leaf nodes in the tree //romos::ModuleContainer *containerModule = dynamic_cast<romos::ModuleContainer*> (moduleToCreateSubTreeFor); //if( containerModule == NULL ) // return; //if( romos::ModuleTypeRegistry::hasModuleTypeEditor(moduleToCreateSubTreeFor->getTypeIdentifierOld()) ) if( moduleToCreateSubTreeFor->hasEditor() ) // maybe optionally show all modules in the tree //if(true) // preliminary //if( moduleToCreateSubTreeFor->hasTreeNode() ) { juce::String name = juce::String( moduleToCreateSubTreeFor->getName().c_str() ); RTreeViewNode *newNode = new RTreeViewNode(name); newNode->setUserData(moduleToCreateSubTreeFor); parentNodeToUse->addChildNode(newNode); // recursion to take care of the new node's child nodes: romos::ContainerModule *containerModule = dynamic_cast<romos::ContainerModule*> (moduleToCreateSubTreeFor); if( containerModule != NULL ) { for(unsigned int i=0; i<containerModule->getNumChildModules(); i++) // conatinerModule was already checked for NULL createAndHangInSubTree(newNode, containerModule->getChildModule(i)); } } } void ModularStructureTreeView::updateNodeHighlighting() { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); rootNode->setAllNodesUnticked(); //RTreeViewNode *selectedNode = rootNode->findNodeByData(getInterfaceMediator()->getContainerShownInDiagram()); RTreeViewNode *selectedNode = rootNode->findNodeByData(getInterfaceMediator()->getModuleToShowEditorFor()); jassert( selectedNode != NULL ); // one module/node should always be focused... if( selectedNode != NULL ) selectedNode->setTicked(true); repaint(); } //================================================================================================= // class ModulePropertiesEditorHolder: ModulePropertiesEditorHolder::ModulePropertiesEditorHolder( LibertyInterfaceMediator *interfaceMediatorToUse) : LibertyInterfaceComponent(interfaceMediatorToUse) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); // getInterfaceMediator() returns already valid mediator because we pass interfaceMediatorToUse to our basclass constructor setMediator(interfaceMediatorToUse); // will register "this" as colleague currentEditor = NULL; // init to NULL required because the next call first deletes the old pointer createPropertiesEditorForSelectedModule(); } ModulePropertiesEditorHolder::~ModulePropertiesEditorHolder() { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); deleteAllChildren(); } //------------------------------------------------------------------------------------------------- // callbacks: void ModulePropertiesEditorHolder::mediatorHasSentNotification( MediatedColleague *originatingColleague, int messageCode) { // \todo maybe include a switch on the messageCode later - we may not want to re-create the // editor on all kinds of messages createPropertiesEditorForSelectedModule(); } void ModulePropertiesEditorHolder::paint(Graphics &g) { // overriden with empty function to avoid painting a gradient that will be invisible anyway } void ModulePropertiesEditorHolder::resized() { currentEditor->setBounds(0, 0, getWidth(), getHeight()); } //------------------------------------------------------------------------------------------------- // others: void ModulePropertiesEditorHolder::createPropertiesEditorForSelectedModule() { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); romos::Module *moduleToShowEditorFor = getInterfaceMediator()->getModuleToShowEditorFor(); if( moduleToShowEditorFor == NULL ) moduleToShowEditorFor = getInterfaceMediator()->getContainerShownInDiagram(); // preliminary removeChildColourSchemeComponent(currentEditor, true); /* // old: // this switch statement sucks - use std::map or something - maybe when this object is created, // create a map that uses the module-id as key and the creator function (pointer) as value switch( moduleToShowEditorFor->getTypeIdentifierOld() ) { case romos::ModuleTypeRegistry::PARAMETER: currentEditor = new ParameterModuleEditor(getInterfaceMediator()->modularSynthModuleToEdit, moduleToShowEditorFor); break; case romos::ModuleTypeRegistry::CONTAINER: currentEditor = new ContainerModuleEditor(getInterfaceMediator()->modularSynthModuleToEdit, moduleToShowEditorFor); break; case romos::ModuleTypeRegistry::TOP_LEVEL_MODULE: currentEditor = new TopLevelModuleEditor(getInterfaceMediator()->modularSynthModuleToEdit, moduleToShowEditorFor); break; case romos::ModuleTypeRegistry::WHITE_NOISE: currentEditor = new WhiteNoiseModuleEditor(getInterfaceMediator()->modularSynthModuleToEdit, moduleToShowEditorFor); break; case romos::ModuleTypeRegistry::BIQUAD_DESIGNER: currentEditor = new BiquadDesignerModuleEditor(getInterfaceMediator()->modularSynthModuleToEdit, moduleToShowEditorFor); break; case romos::ModuleTypeRegistry::LADDER_FILTER: currentEditor = new LibertyLadderFilterModuleEditor(getInterfaceMediator()->modularSynthModuleToEdit, moduleToShowEditorFor); break; case romos::ModuleTypeRegistry::VOICE_KILLER: currentEditor = new VoiceKillerModuleEditor(getInterfaceMediator()->modularSynthModuleToEdit, moduleToShowEditorFor); break; default: { //jassertfalse; // for every module-type, there should be case currentEditor = new ModulePropertiesEditor(getInterfaceMediator()->modularSynthModuleToEdit, moduleToShowEditorFor); } } */ // new: // abbreviations for convenience: LibertyAudioModule* lbrtyMd = getInterfaceMediator()->modularSynthModuleToEdit; romos::Module* mdl = moduleToShowEditorFor; std::string type = mdl->getTypeName(); if( type == "Parameter") currentEditor = new ParameterModuleEditor(lbrtyMd, mdl); else if(type == "Container") currentEditor = new ContainerModuleEditor(lbrtyMd, mdl); else if(type == "TopLevelModule") currentEditor = new TopLevelModuleEditor(lbrtyMd, mdl); else if(type == "WhiteNoise") currentEditor = new WhiteNoiseModuleEditor(lbrtyMd, mdl); else if(type == "BiquadDesigner") currentEditor = new BiquadDesignerModuleEditor(lbrtyMd, mdl); else if(type == "LadderFilter") currentEditor = new LibertyLadderFilterModuleEditor(lbrtyMd, mdl); else if(type == "VoiceKiller") currentEditor = new VoiceKillerModuleEditor(lbrtyMd, mdl); //else if(type == "Formula_1_1") currentEditor = new LibertyFormulaModuleEditor(lbrtyMd, mdl); //else if(type == "Formula_N_1") currentEditor = new LibertyFormula_N_1ModuleEditor(lbrtyMd, mdl); else if(type == "Formula") currentEditor = new LibertyFormula_N_MModuleEditor(lbrtyMd, mdl); else currentEditor = new ModulePropertiesEditor(lbrtyMd, mdl); // generic // todo: optimize away all these string-comparisons // maybe make a map from type-id to creator-function currentEditor->setDescriptionField(descriptionField, true ); addChildColourSchemeComponent(currentEditor, true, true); resized(); // will set the bounds of the child } //================================================================================================= //================================================================================================= // class ModularBlockDiagramPanel: ModularBlockDiagramPanel::ModularBlockDiagramPanel(LibertyInterfaceMediator *interfaceMediatorToUse) : LibertyInterfaceComponent(interfaceMediatorToUse) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); // getInterfaceMediator() returns already valid mediator because we pass interfaceMediatorToUse // to our basclass constructor setMediator(interfaceMediatorToUse); // will register "this" as colleague availableModulesTreeView = new RTreeView(); availableModulesTreeView->setOpenOrCloseNodesOnClick(true); availableModulesTreeView->setOpaque(true); availableModulesTreeView->setAlwaysOnTop(true); availableModulesTreeView->setDrawRootNode(false); fillAvailableModulesTreeView(); availableModulesTreeView->registerTreeViewObserver(this); actOnSelectionMenu = new RPopUpMenu(this); // can we pass NULL too? actOnSelectionMenu->setDismissOnFocusLoss(false); // because it immediately seems to loose focus after opening for some reason (?) actOnSelectionMenu->registerPopUpMenuObserver(this); addWidget(actOnSelectionMenu, false, false); nameEntryField = new RTextEntryField(); nameEntryField->registerTextEntryFieldObserver(this); addWidget(nameEntryField, true, false); mouseDownX = 0; mouseDownY = 0; selectionOffsetX = 0; selectionOffsetY = 0; availableWidth = 0; availableHeight = 0; //gridStyle = DOTTED_GRID; //gridStyle = GRID_LINES; gridStyle = NO_GRID; // define metric: m = 2; // margin between text and outlines ...use later 2 here - maybe t = 2; // thickness of outlines s = 2; // stickout for the pins bigFontHeight = bigFont->getFontHeight(); normalFontHeight = normalFont->getFontHeight(); smallFontHeight = smallFont->getFontHeight(); pinDistance = smallFontHeight + m; arrowLength = 12; arrowHeadLength = 8; // todo: use colors from colorscheme wireColour = Colours::black; highlightColour = Colours::red; // maybe override ColorSchemeComponent::colorSchmeChanged and set the colors there pinHighlighter = new RectangleComponent(highlightColour, highlightColour, 0); pinHighlighter->setInterceptsMouseClicks(false, false); addChildComponent(pinHighlighter); lassoComponent = new RectangleComponent(highlightColour.withMultipliedAlpha(0.0625f), highlightColour.withMultipliedAlpha(0.25f), 2); addChildComponent(lassoComponent); } ModularBlockDiagramPanel::~ModularBlockDiagramPanel() { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); //getInterfaceMediator()->deRegisterInterfaceComponent(this); // done in baseclass delete actOnSelectionMenu; delete availableModulesTreeView; delete treeRootNode; } //----------------------------------------------------------------------------------------------------------------------------------------- // setup: void ModularBlockDiagramPanel::setAvailabeSizeForCanvas(int w, int h) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); availableWidth = w; availableHeight = h; updateCanvasBounds(0, 0, w, h); } void ModularBlockDiagramPanel::updateCanvasBounds(int x, int y, int w, int h) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); x = jmin(x, getMinXInPixels()); y = jmin(y, getMinYInPixels()); w = jmax(w, getMaxXInPixels())-x; h = jmax(h, getMaxYInPixels())-y; setBounds(x, y, w, h); } //----------------------------------------------------------------------------------------------------------------------------------------- // inquiry: int ModularBlockDiagramPanel::getMaxXInPixels() const { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); int result = 0; int tmp; romos::Module *child; for(unsigned int i=0; i<getInterfaceMediator()->getContainerShownInDiagram()->getNumChildModules(); i++) { child = getInterfaceMediator()->getContainerShownInDiagram()->getChildModule(i); tmp = inPixels(child->getPositionX()) + getRequiredWidthForModuleInPixels(child, true); if( tmp > result ) result = tmp; } return result; } int ModularBlockDiagramPanel::getMaxYInPixels() const { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); int result = 0; int tmp; romos::Module *child; for(unsigned int i=0; i<getInterfaceMediator()->getContainerShownInDiagram()->getNumChildModules(); i++) { child = getInterfaceMediator()->getContainerShownInDiagram()->getChildModule(i); tmp = inPixels(child->getPositionY()) - getOffsetY(child) + getRequiredHeightForModuleInPixels(child); // maybe use getModuleRectangle here if( tmp > result ) result = tmp; } return result; } int ModularBlockDiagramPanel::getMinXInPixels() const { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); int result = 0; romos::Module *child; for(unsigned int i=0; i<getInterfaceMediator()->getContainerShownInDiagram()->getNumChildModules(); i++) { child = getInterfaceMediator()->getContainerShownInDiagram()->getChildModule(i); if( child->getPositionX() < result ) result = child->getPositionX(); } result = inPixels(result); if( result < 0 ) result -= s; // the stickout should also be seen return result; } int ModularBlockDiagramPanel::getMinYInPixels() const { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); int result = 0; int y; romos::Module *child; for(unsigned int i=0; i<getInterfaceMediator()->getContainerShownInDiagram()->getNumChildModules(); i++) { child = getInterfaceMediator()->getContainerShownInDiagram()->getChildModule(i); y = inPixels(child->getPositionY()) - getOffsetY(child); if( y < result ) result = y; } return result; } //----------------------------------------------------------------------------------------------------------------------------------------- // callbacks: void ModularBlockDiagramPanel::mouseExit(const MouseEvent &e) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); ColourSchemeComponent::mouseExit(e); pinHighlighter->setVisible(false); } void ModularBlockDiagramPanel::mouseMove(const MouseEvent &e) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); romos::ContainerModule *container = getInterfaceMediator()->getContainerShownInDiagram(); romos::Module *module = getModuleAtPixels(e.x, e.y, true); juce::Rectangle<int> moduleRectangle = getRectangleForModuleInPixels(module, true); int kindOfPin, directionOfPin, indexOfPin; bool isOverPin = getPinPropertiesAtPixels(e.x, e.y, module, moduleRectangle, kindOfPin, directionOfPin, indexOfPin); if( isOverPin ) { pinHighlighter->setBounds( getPinBounds(kindOfPin, directionOfPin, indexOfPin, module, moduleRectangle) ); pinHighlighter->setVisible(true); } else pinHighlighter->setVisible(false); } void ModularBlockDiagramPanel::mouseDown(const MouseEvent &e) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); availableModulesTreeView->setVisible(false); actOnSelectionMenu->setVisible(false); nameEntryField->setVisible(false); romos::ContainerModule *container = getInterfaceMediator()->getContainerShownInDiagram(); mouseDownX = e.x; mouseDownY = e.y; lassoComponent->setVisible(false); lassoComponent->setBounds(e.x, e.y, 0, 0); romos::Module *module = getModuleAtPixels(e.x, e.y, true); romos::AudioConnection connection = getConnectionAtPixels(e.x, e.y); if( module == NULL && connection.isNull() ) { if( e.getNumberOfClicks() == 2 ) { romos::ContainerModule *shownContainer = getInterfaceMediator()->getContainerShownInDiagram(); romos::ContainerModule *parentContainer = shownContainer->getParentModule(); if( parentContainer != NULL ) { getInterfaceMediator()->setContainerToShowInDiagram(parentContainer); getInterfaceMediator()->setModuleToShowEditorFor(shownContainer); } } else if( e.mods.isRightButtonDown() ) openModuleInsertionMenu(getScreenX()+e.x, getScreenY()+e.y); else if( e.mods.isLeftButtonDown() ) { if( !e.mods.isShiftDown() ) { selectedModules.clear(); selectedAudioConnections.clear(); } lassoComponent->setVisible(true); repaint(); } } else { if( e.mods.isRightButtonDown() ) { openActOnSelectionMenu(getScreenX()+e.x, getScreenY()+e.y); //repaint(); return; } // check if the click was on a pin: int kindOfPin, directionOfPin, indexOfPin; bool pinClicked = getPinPropertiesAtPixels(e.x, e.y, module, getRectangleForModuleInPixels(module, true), kindOfPin, directionOfPin, indexOfPin); if( pinClicked ) { // start drawing a new connection: if( kindOfPin == romos::AUDIO ) { tmpAudioConnection.resetToNull(); if( directionOfPin == romos::OUTGOING ) { tmpAudioConnection.setSourceModule(module); tmpAudioConnection.setSourceOutputIndex(indexOfPin); } else { tmpAudioConnection.setTargetModule(module); tmpAudioConnection.setTargetInputIndex(indexOfPin); } } } bool selected; bool connectionClicked = !connection.isNull(); if( connectionClicked ) { selected = rosic::containsElement(selectedAudioConnections, connection); //selected = selectedAudioConnections.hasElement(connection); if( e.mods.isShiftDown() ) { if( selected ) rosic::removeElementByValue(selectedAudioConnections, connection); //selectedAudioConnections.removeElementByValue(connection); else rosic::appendElement(selectedAudioConnections, connection); //selectedAudioConnections.appendElement(connection); } else { if( selected ) { // keep selected (important for start dragging) } else { selectedModules.clear(); selectedAudioConnections.clear(); rosic::appendElement(selectedAudioConnections, connection); //selectedAudioConnections.appendElement(connection); } } } else { // click was not on the pin or connections, so it must have been on a module's body - change module selection: selected = isModuleSelected(module); if( e.mods.isShiftDown() ) { if( selected ) removeModuleWithConnectionsFromArray(module, selectedModules, selectedAudioConnections); else addModuleWithConnectionsToArray(module, selectedModules, selectedAudioConnections); } else if( e.getNumberOfClicks() == 2 ) { if( selectedModules.size() == 1 ) { //openModuleNameEntryField(); ...nah - maybe make this available via the PopUp - double clicks naviagte into the conatiner if( selectedModules[0]->isContainerModule() ) getInterfaceMediator()->setContainerToShowInDiagram( ((ContainerModule*)selectedModules[0]) ); } } else { if( selected ) { // keep selected (important for start dragging) } else { //if( romos::ModuleTypeRegistry::hasModuleTypeEditor(module->getTypeIdentifierOld()) ) if( module->hasEditor() ) getInterfaceMediator()->setModuleToShowEditorFor(module); // will also select it via the callback that we'll receive else selectSingleModule(module); } } } repaint(); return; } } /* void ModularBlockDiagramPanel::mouseDoubleClick(const MouseEvent &e) { // todo: navigate up and down in the container hierarchy int dummy = 0; } */ void ModularBlockDiagramPanel::mouseDrag(const MouseEvent &e) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); mouseMove(e); if( !tmpAudioConnection.isNull() ) // we are drawing a new audio connection { } else if( lassoComponent->isVisible() ) // we are opening a lasso-selector { int x = mouseDownX; int y = mouseDownY; int w = e.x-mouseDownX; int h = e.y-mouseDownY; if( w < 0 ) { w = -w; x -= w; } if( h < 0 ) { h = -h; y -= h; } lassoComponent->setBounds(x, y, w, h); modulesInLasso.clear(); audioConnectionsInLasso.clear(); std::vector<romos::Module*> tmpArray = getModulesInRectangle(lassoComponent->getBounds()); for(unsigned int i = 0; i < tmpArray.size(); i++) addModuleWithConnectionsToArray(tmpArray[i], modulesInLasso, audioConnectionsInLasso); } else // we are dragging a bunch of modules around { selectionOffsetX = snapPixelPositionToGrid(e.getDistanceFromDragStartX()); selectionOffsetY = snapPixelPositionToGrid(e.getDistanceFromDragStartY()); } repaint(); } void ModularBlockDiagramPanel::mouseUp(const MouseEvent &e) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); if( !tmpAudioConnection.isNull() ) // we were drawing a new audio connection... { romos::Module *module = getModuleAtPixels(e.x, e.y, true); if( module == NULL ) { tmpAudioConnection.resetToNull(); //...and dismiss it now repaint(); return; } // check if the mouseUp was on a pin: int kindOfPin, directionOfPin, indexOfPin; bool wasOnPin = getPinPropertiesAtPixels(e.x, e.y, module, getRectangleForModuleInPixels(module, true), kindOfPin, directionOfPin, indexOfPin); if( wasOnPin ) { if( kindOfPin == romos::AUDIO ) { if( directionOfPin == romos::INCOMING && tmpAudioConnection.getTargetModule() == NULL ) { tmpAudioConnection.setTargetModule(module); tmpAudioConnection.setTargetInputIndex(indexOfPin); getInterfaceMediator()->getContainerShownInDiagram()->addAudioConnection(&tmpAudioConnection); tmpAudioConnection.resetToNull(); repaint(); } else if( directionOfPin == romos::OUTGOING && tmpAudioConnection.getSourceModule() == NULL ) { tmpAudioConnection.setSourceModule(module); tmpAudioConnection.setSourceOutputIndex(indexOfPin); getInterfaceMediator()->getContainerShownInDiagram()->addAudioConnection(&tmpAudioConnection); tmpAudioConnection.resetToNull(); repaint(); } } } tmpAudioConnection.resetToNull(); updateAudioConnectionArray(); repaint(); return; } else if( lassoComponent->isVisible() ) // we were openenig a lasso selector { modulesInLasso = getModulesInRectangle(lassoComponent->getBounds()); for(unsigned int i = 0; i < modulesInLasso.size(); i++) addModuleWithConnectionsToArray(modulesInLasso[i], selectedModules, selectedAudioConnections); lassoComponent->setVisible(false); modulesInLasso.clear(); audioConnectionsInLasso.clear(); repaint(); } else // we were dragging a bunch of modules around { for(unsigned int i = 0; i < selectedModules.size(); i++) { selectedModules[i]->setPositionXY(selectedModules[i]->getPositionX() + inPinDistances(selectionOffsetX), selectedModules[i]->getPositionY() + inPinDistances(selectionOffsetY)); } selectionOffsetX = 0; selectionOffsetY = 0; updateCanvasBounds(0, 0, availableWidth, availableHeight); } //repaint(); } void ModularBlockDiagramPanel::paint(Graphics &g) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); //g.fillAll(Colours::lavender); // \todo obtain the background colour from the colorscheme g.fillAll(getPlotColourScheme().topLeft); // we should actually call drawBilinearGradient with the colors for the 4 corners drawGrid(g); drawDiagram(g); } void ModularBlockDiagramPanel::paintOverChildren(Graphics &g) { //ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); // do nothing - avoid outline drawing from the baseclass } /* void ModularBlockDiagramPanel::resized() { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); ColourSchemeComponent::resized(); } */ /* void ModularBlockDiagramPanel::updateDiagram() { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); repaint(); } */ void ModularBlockDiagramPanel::rPopUpMenuChanged(RPopUpMenu* menuThatHasChanged) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); if( menuThatHasChanged == actOnSelectionMenu ) { RTreeViewNode *selectedItem = actOnSelectionMenu->getSelectedItem(); if( selectedItem != NULL ) { switch( selectedItem->getNodeIdentifier() ) { case EDIT_NAME: openModuleNameEntryField(); break; case SAVE_CONTAINER: openContainerSaveDialog(); break; case EXPORT_TO_CODE: openExportToCodeDialog(); break; case SET_POLYPHONIC: setPolyphonyForSelection(true); break; case SET_MONOPHONIC: setPolyphonyForSelection(false); break; case DELETE_SELECTION: deleteSelection(); break; case CONTAINERIZE: containerizeSelection(); break; case UNCONTAINERIZE: unContainerizeSelection(); break; //case 3: minimizeNumberOfInputs(); break; default: { int dummy = 0; jassertfalse; } } } else jassertfalse; actOnSelectionMenu->dismiss(); } else jassertfalse; } void ModularBlockDiagramPanel::textChanged(RTextEntryField *rTextEntryFieldThatHasChanged) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); if( selectedModules.size() == 1 ) { char* newName = toZeroTerminatedString(nameEntryField->getText()); selectedModules[0]->setModuleName(std::string(newName)); nameEntryField->setVisible(false); grabKeyboardFocus(); // to move it away from the entry field delete newName; //getInterfaceMediator()->sendModuleChangeNotification(selectedModules[0], MODULE_NAME); notifyMediator(MODULE_NAME); //repaint(); } } void ModularBlockDiagramPanel::treeNodeClicked(RTreeView *treeView, RTreeViewNode *nodeThatWasClicked, const MouseEvent &mouseEvent, int clickPosition) { WRITE_TO_LOGFILE("ModularBlockDiagramPanel::treeNodeClicked entered\n"); ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); if( treeView == availableModulesTreeView && nodeThatWasClicked->isLeafNode() ) { availableModulesTreeView->setVisible(false); availableModulesTreeView->removeFromDesktop(); //if( nodeThatWasClicked->getNodeIdentifier() == LOAD_CONTAINER ) if( nodeThatWasClicked->getNodeText() == "Load Container..." ) openContainerLoadDialog(); else { // old: //insertModule(nodeThatWasClicked->getNodeIdentifier(), inPinDistances(mouseDownX), inPinDistances(mouseDownY)); //new: insertModule(nodeThatWasClicked->getNodeText(), inPinDistances(mouseDownX), inPinDistances(mouseDownY)); } } WRITE_TO_LOGFILE("ModularBlockDiagramPanel::treeNodeClicked finished\n"); } void ModularBlockDiagramPanel::treeNodeChanged(RTreeView *treeView, RTreeViewNode *nodeThatHasChanged) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); } void ModularBlockDiagramPanel::mediatorHasSentNotification(MediatedColleague *originatingColleague, int messageCode) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); selectedAudioConnections.clear(); selectedModules.clear(); updateAudioConnectionArray(); // maybe clear more arrays? if( messageCode == MODULE_TO_SHOW_EDITOR_FOR ) { romos::ContainerModule *containerShownInDiagram = getInterfaceMediator()->getContainerShownInDiagram(); romos::Module *moduleToShowEditorFor = getInterfaceMediator()->getModuleToShowEditorFor(); if( moduleToShowEditorFor != containerShownInDiagram ) selectSingleModule(moduleToShowEditorFor); } updateCanvasBounds(0, 0, availableWidth, availableHeight); repaint(); // \todo: put in an if( modulePropertiesThatHasChanged == focusedModule ), maybe restrict on the causes also } //----------------------------------------------------------------------------------------------------------------------------------------- // others: void ModularBlockDiagramPanel::openModuleInsertionMenu(int x, int y) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); availableModulesTreeView->setTopLeftPosition(x, y); availableModulesTreeView->addToDesktop(ComponentPeer::windowIsTemporary, 0); availableModulesTreeView->setVisible(true); } void ModularBlockDiagramPanel::openActOnSelectionMenu(int x, int y) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); actOnSelectionMenu->clear(); if( selectedModules.size() == 1 ) { actOnSelectionMenu->addItem(EDIT_NAME, ("Edit Name"), true, false); //if( selectedModules[0]->getTypeIdentifierOld() == romos::ModuleTypeRegistry::CONTAINER ) if( selectedModules[0]->getTypeName() == "Container" ) { actOnSelectionMenu->addItem(SAVE_CONTAINER, ("Save Container..."), true, false); actOnSelectionMenu->addItem(EXPORT_TO_CODE, ("Export to Code..."), true, false); } } actOnSelectionMenu->addItem(SET_POLYPHONIC, ("Set Polyphonic"), true, false); actOnSelectionMenu->addItem(SET_MONOPHONIC, ("Set Monophonic"), true, false); actOnSelectionMenu->addItem(DELETE_SELECTION, ("Delete Selection"), true, false); actOnSelectionMenu->addItem(CONTAINERIZE, ("Containerize Selection"), true, false); actOnSelectionMenu->addItem(UNCONTAINERIZE, ("Unpack Container(s)"), true, false); //actOnSelectionMenu->addItem(MINIMIZE_PINS, ("Minimize Pins"), true, false); actOnSelectionMenu->setBounds(100, 100, 150, 200); // \todo make the size adapt to the content actOnSelectionMenu->showAtMousePosition(false); } void ModularBlockDiagramPanel::openModuleNameEntryField() { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); if( selectedModules.size() == 1 ) { juce::String name = juce::String(selectedModules[0]->getName().c_str()); nameEntryField->setText(name); int x, y, w, h; getRectangleForModuleInPixels(selectedModules[0], x, y, w, h, false); //nameEntryField->setBounds(x, y, w, getModuleTitleHeightInPixels(selectedModules[0])); nameEntryField->setBounds(x, y, jmax(w, 40), 2*t+2*m+bigFontHeight); //int type = selectedModules[0]->getTypeIdentifierOld(); int typeId = selectedModules[0]->getTypeId(); std::string typeName = selectedModules[0]->getTypeName(); if( !romos::moduleFactory.isModuleNameEditable(typeId) ) return; //if( getInterfaceMediator()->getContainerShownInDiagram()->getTypeIdentifierOld() == romos::ModuleTypeRegistry::TOP_LEVEL_MODULE ) if( getInterfaceMediator()->getContainerShownInDiagram()->isTopLevelModule() ) { //if( romos::ModuleTypeRegistry::isIdentifierInputOrOutput(type) ) if( selectedModules[0]->isInputOrOutput() ) return; // disallow editing of toplevel I/O module names } //if( type == romos::ModuleTypeRegistry::CONSTANT ) if( typeName == "Constant" ) nameEntryField->setPermittedCharacters(juce::String(("0123456789.-"))); else nameEntryField->setPermittedCharacters(juce::String(("0123456789.ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"))); nameEntryField->setVisible(true); nameEntryField->grabKeyboardFocus(); } } void ModularBlockDiagramPanel::openContainerLoadDialog() { WRITE_TO_LOGFILE("ModularBlockDiagramPanel::openContainerLoadDialog entered\n"); ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); juce::File initialDirectory = getInterfaceMediator()->modularSynthModuleToEdit->macroDirectory; juce::String allowedPatterns = juce::String(("*.xml")); FileChooser chooser(juce::String(("Load Container")), initialDirectory, allowedPatterns, true); if( chooser.browseForFileToOpen() ) { juce::File fileToLoad = chooser.getResult(); getInterfaceMediator()->modularSynthModuleToEdit->macroDirectory = fileToLoad.getParentDirectory(); XmlElement *xmlState = getXmlFromFile(fileToLoad); WRITE_TO_LOGFILE("Module state was loaded\n"); if( xmlState != NULL ) { //romos::ModuleContainer *newModule = new romos::ModuleContainer(NULL); // deprecated: //romos::ModuleContainer *newModule = (ModuleContainer*) ModuleFactory::createModule(ModuleTypeRegistry::CONTAINER); // later use: romos::ContainerModule *newModule = (ContainerModule*) moduleFactory.createModule("Container"); WRITE_TO_LOGFILE("Module created\n"); LibertyAudioModule::setModuleStateFromXml(*xmlState, newModule); WRITE_TO_LOGFILE("Module state was set\n"); newModule->setPositionXY(inPinDistances(mouseDownX), inPinDistances(mouseDownY), false); WRITE_TO_LOGFILE("Module position was set\n"); getInterfaceMediator()->getContainerShownInDiagram()->addChildModule(newModule, true); //getInterfaceMediator()->sendModuleChangeNotification(getInterfaceMediator()->getContainerShownInDiagram(), NUM_CHILDREN); notifyMediator(NUM_CHILDREN); delete xmlState; } } WRITE_TO_LOGFILE("ModularBlockDiagramPanel::openContainerLoadDialog finished\n"); } void ModularBlockDiagramPanel::openContainerSaveDialog() { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); //if( selectedModules.size() == 1 && selectedModules[0]->getTypeIdentifierOld() == ModuleTypeRegistry::CONTAINER ) if( selectedModules.size() == 1 && selectedModules[0]->isContainerModule() ) { //juce::File initialDirectory = rojue::getApplicationDirectory(); // preliminary - we should have a member containerDirectory or sth juce::File initialDirectory = getInterfaceMediator()->modularSynthModuleToEdit->macroDirectory; juce::String extension = juce::String(("xml")); juce::String allowedPatterns = juce::String(("*.xml")); FileChooser chooser(juce::String(("Save Container")), initialDirectory, allowedPatterns, true); if( chooser.browseForFileToSave(true) ) { juce::File fileToSaveTo = chooser.getResult(); getInterfaceMediator()->modularSynthModuleToEdit->macroDirectory = fileToSaveTo.getParentDirectory(); if ( !fileToSaveTo.hasFileExtension(extension) ) fileToSaveTo = fileToSaveTo.withFileExtension( extension ) ; XmlElement *xmlState = LibertyAudioModule::getModuleStateAsXml(selectedModules[0], false); if( xmlState != NULL ) { saveXmlToFile(*xmlState, fileToSaveTo, true); delete xmlState; } } } } void ModularBlockDiagramPanel::openExportToCodeDialog() { jassertfalse; // to be re-activated //ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); //if( selectedModules.size() == 1 && selectedModules[0]->getTypeIdentifier() == ModuleTypeRegistry::CONTAINER ) //{ // juce::File initialDirectory = getInterfaceMediator()->modularSynthModuleToEdit->macroDirectory; // juce::String extension = juce::String(("txt")); // juce::String allowedPatterns = juce::String(("*.txt")); // FileChooser chooser(juce::String(("Export to Code")), initialDirectory, allowedPatterns, true); // if( chooser.browseForFileToSave(true) ) // { // juce::File fileToSaveTo = chooser.getResult(); // //if ( !fileToSaveTo.hasFileExtension(extension) ) // // fileToSaveTo = fileToSaveTo.withFileExtension(extension) ; // if( fileToSaveTo.existsAsFile() ) // { // fileToSaveTo.deleteFile(); // fileToSaveTo.create(); // } // juce::String codeString = rosicToJuce(ModuleBuildCodeGenerator::getCodeForModule(selectedModules[0])); // fileToSaveTo.appendText(codeString); // } //} } /* void ModularBlockDiagramPanel::openPropertiesDialog() { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); if( selectedModules.getNumElements() == 1 ) { propertiesDialog->retrievePropertiesFromModule(selectedModules[0]); propertiesDialog->setVisible(true); } } */ /* // old: void ModularBlockDiagramPanel::insertModule(int moduleIdentifer, int xInPinDistances, int yInPinDistances) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); getInterfaceMediator()->getContainerShownInDiagram()->addChildModule(moduleIdentifer, rosic::rsString(), // will fall back to a default name based on the module-type xInPinDistances, yInPinDistances, getInterfaceMediator()->getContainerShownInDiagram()->isPolyphonic() // use same polyphony as the outlying container ); //getInterfaceMediator()->sendModuleChangeNotification(getInterfaceMediator()->getContainerShownInDiagram(), NUM_CHILDREN); notifyMediator(NUM_CHILDREN); } */ // new: void ModularBlockDiagramPanel::insertModule(const juce::String& typeName, int x, int y) { LibertyInterfaceMediator* med = getInterfaceMediator(); ScopedLock scopedLock(*(med->plugInLock)); med->getContainerShownInDiagram()->addChildModule(typeName.toStdString(), "", // use a default name based on the module-type x, y, med->getContainerShownInDiagram()->isPolyphonic()); // use same polyphony as the outlying container notifyMediator(NUM_CHILDREN); } void ModularBlockDiagramPanel::selectSingleModule(romos::Module *moduleToSelect) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); selectedAudioConnections.clear(); selectedModules.clear(); addModuleWithConnectionsToArray(moduleToSelect, selectedModules, selectedAudioConnections); } void ModularBlockDiagramPanel::addModuleWithConnectionsToArray(romos::Module *moduleToAdd, std::vector<romos::Module*> &moduleArray, std::vector<romos::AudioConnection> &connectionArray) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); rosic::appendIfNotAlreadyThere(moduleArray, moduleToAdd); // wrap these 3-liners into a functions rosic::appendArrayElementsIfNotAlreadyThere(vector, vector): if( !moduleToAdd->isInputModule() ) { std::vector<AudioConnection> incomingAudioConnections = moduleToAdd->getIncomingAudioConnections(); for(unsigned int i = 0; i < incomingAudioConnections.size(); i++) rosic::appendIfNotAlreadyThere(connectionArray, incomingAudioConnections[i]); } std::vector<AudioConnection> outgoingAudioConnections = moduleToAdd->getOutgoingAudioConnections(); for(unsigned int i = 0; i < outgoingAudioConnections.size(); i++) rosic::appendIfNotAlreadyThere(connectionArray, outgoingAudioConnections[i]); } void ModularBlockDiagramPanel::removeModuleWithConnectionsFromArray(romos::Module *moduleToRemove, std::vector<romos::Module*> &moduleArray, std::vector<romos::AudioConnection> &connectionArray) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); rosic::removeElementByValue(moduleArray, moduleToRemove); romos::AudioConnection ac; unsigned int i; /* for(i = 0; i < moduleToRemove->getNumIncomingAudioConnections(); i++) { ac = moduleToRemove->getIncomingAudioConnection(i); if( !rosic::containsElement(moduleArray, ac->getSourceModule()) ) rosic::removeElementByValue(connectionArray, ac); } */ std::vector<AudioConnection> incomingAudioConnections = moduleToRemove->getIncomingAudioConnections(); for(i = 0; i < incomingAudioConnections.size(); i++) { ac = incomingAudioConnections[i]; if( !rosic::containsElement(moduleArray, ac.getSourceModule()) ) rosic::removeElementByValue(connectionArray, ac); } std::vector<AudioConnection> outgoingAudioConnections = moduleToRemove->getOutgoingAudioConnections(); for(i = 0; i < outgoingAudioConnections.size(); i++) { ac = outgoingAudioConnections[i]; if( !rosic::containsElement(moduleArray, ac.getTargetModule()) ) rosic::removeElementByValue(connectionArray, ac); } } void ModularBlockDiagramPanel::setPolyphonyForSelection(bool shouldBePolyphonic) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); getInterfaceMediator()->getContainerShownInDiagram()->setPolyphonyForModules(selectedModules, shouldBePolyphonic); notifyMediator(POLYPHONY); } void ModularBlockDiagramPanel::deleteSelection() { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); getInterfaceMediator()->getContainerShownInDiagram()->deleteAudioConnections(selectedAudioConnections); getInterfaceMediator()->getContainerShownInDiagram()->deleteModules(selectedModules); //getInterfaceMediator()->sendModuleChangeNotification(getInterfaceMediator()->getContainerShownInDiagram(), NUM_CHILDREN); getInterfaceMediator()->setModuleToShowEditorFor(getInterfaceMediator()->getContainerShownInDiagram()); notifyMediator(NUM_CHILDREN); } void ModularBlockDiagramPanel::containerizeSelection() { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); romos::ContainerModule *createdContainer = getInterfaceMediator()->getContainerShownInDiagram()->containerizeModules(selectedModules); updateAudioConnectionArray(); selectedModules.clear(); addModuleWithConnectionsToArray(createdContainer, selectedModules, selectedAudioConnections); // select the just created container //getInterfaceMediator()->sendModuleChangeNotification(getInterfaceMediator()->getContainerShownInDiagram(), NUM_CHILDREN); getInterfaceMediator()->setModuleToShowEditorFor(getInterfaceMediator()->getContainerShownInDiagram()); notifyMediator(NUM_CHILDREN); } void ModularBlockDiagramPanel::unContainerizeSelection() { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); // keep track of what's being unpacked in order to later select it: std::vector<romos::Module*> unpackedModules; for(unsigned int i = 0; i < selectedModules.size(); i++) { ContainerModule *tmpContainer = dynamic_cast<ContainerModule*> (selectedModules[i]); if( tmpContainer != NULL ) rosic::appendVector(unpackedModules, tmpContainer->getNonInOutChildModules()); //unpackedModules.appendArray( tmpContainer->getNonInOutChildModules() ); } getInterfaceMediator()->getContainerShownInDiagram()->unContainerizeModules(selectedModules); updateAudioConnectionArray(); selectedModules.clear(); getInterfaceMediator()->setModuleToShowEditorFor(getInterfaceMediator()->getContainerShownInDiagram()); notifyMediator(NUM_CHILDREN); for(unsigned int i = 0; i < unpackedModules.size(); i++) // maybe wrap this loop into a function addModuleWithConnectionsToArray(unpackedModules[i], selectedModules, selectedAudioConnections); } void ModularBlockDiagramPanel::minimizeNumberOfInputs() { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); for(unsigned int i = 0; i < selectedModules.size(); i++) { ContainerModule *tmpContainer = dynamic_cast<ContainerModule*> (selectedModules[i]); if( tmpContainer != NULL ) tmpContainer->minimizeNumberOfAudioInputs(); } //getInterfaceMediator()->sendModuleChangeNotification(getInterfaceMediator()->getContainerShownInDiagram(), NUM_CONNECTIONS); notifyMediator(NUM_CONNECTIONS); } void ModularBlockDiagramPanel::fillAvailableModulesTreeView() { // ToDo: this code should be replaced with some code that loops through the module types in the // global moduleTypeRegistry object ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); treeRootNode = new RTreeViewNode("Module", 0); treeRootNode->setDeleteChildNodesOnDestruction(true); // -> all the child-nodes that are subsequently created here via "new" (and added to the tree) will be deleted when the treeRootNode // itself is deleted // \todo write a short description for each node to appear in the infoline RTreeViewNode *tmpNode1; //, *tmpNode2; // we need one temporary node for each tree-level except the lowest ...or not? tmpNode1 = new RTreeViewNode("Load Container...", LOAD_CONTAINER); treeRootNode->addChildNode(tmpNode1); RTreeViewNode *insertModuleNode = new RTreeViewNode("Insert"); treeRootNode->addChildNode(insertModuleNode); // new - activate soon:: for(size_t i = 0; i < moduleFactory.getNumModuleTypes(); i++) { romos::ModuleTypeInfo* typeInfo = moduleFactory.getModuleTypeInfo(i); juce::String typeName = typeInfo->fullName; juce::String category = typeInfo->category; RTreeViewNode* categNode = insertModuleNode->findNodeByText(category); if(categNode == nullptr) { categNode = new RTreeViewNode(category); insertModuleNode->addChildNode(categNode); } categNode->addChildNode(new RTreeViewNode(typeName, typeInfo->id)); int dummy = 0; } // this loop should replace (almost) all the code below /* //--------------------------------------------------------------------------- // test modules: tmpNode1 = new RTreeViewNode("Test Modules"); tmpNode1->addChildNode(new RTreeViewNode("Gain", romos::ModuleTypeRegistry::TEST_GAIN)); tmpNode1->addChildNode(new RTreeViewNode("SumDiff", romos::ModuleTypeRegistry::TEST_SUM_DIFF)); tmpNode1->addChildNode(new RTreeViewNode("WrappedSumDiff", romos::ModuleTypeRegistry::TEST_WRAPPED_SUM_DIFF)); tmpNode1->addChildNode(new RTreeViewNode("SummedDiffs", romos::ModuleTypeRegistry::TEST_SUMMED_DIFFS)); tmpNode1->addChildNode(new RTreeViewNode("MovingAverage", romos::ModuleTypeRegistry::TEST_MOVING_AVERAGE)); tmpNode1->addChildNode(new RTreeViewNode("LeakyIntegrator", romos::ModuleTypeRegistry::TEST_LEAKY_INTEGRATOR)); tmpNode1->addChildNode(new RTreeViewNode("TestFilter1", romos::ModuleTypeRegistry::TEST_FILTER1)); tmpNode1->addChildNode(new RTreeViewNode("Biquad", romos::ModuleTypeRegistry::TEST_BIQUAD)); tmpNode1->addChildNode(new RTreeViewNode("AddedConstants", romos::ModuleTypeRegistry::TEST_ADDED_CONSTANTS)); tmpNode1->addChildNode(new RTreeViewNode("PinSorting", romos::ModuleTypeRegistry::TEST_PIN_SORTING)); tmpNode1->addChildNode(new RTreeViewNode("Blip", romos::ModuleTypeRegistry::TEST_BLIP)); tmpNode1->addChildNode(new RTreeViewNode("PolyBlipStereo", romos::ModuleTypeRegistry::TEST_POLY_BLIP_STEREO)); tmpNode1->addChildNode(new RTreeViewNode("NoiseFlute", romos::ModuleTypeRegistry::TEST_NOISE_FLUTE)); //tmpNode1->addChildNode(new RTreeViewNode(("Moog Filter"), romos::ModuleTypeRegistry::EXAMPLE_MOOG_FILTER)); //tmpNode1->addChildNode(new RTreeViewNode(("Containerize"), romos::ModuleTypeRegistry::TEST_CONTAINERIZE)); //tmpNode1->addChildNode(new RTreeViewNode(("UnContainerize"), romos::ModuleTypeRegistry::TEST_UNCONTAINERIZE)); //tmpNode1->addChildNode(new RTreeViewNode(("Minimize Inputs 1"), romos::ModuleTypeRegistry::TEST_MINIMIZE_INS1)); insertModuleNode->addChildNode(tmpNode1); //--------------------------------------------------------------------------- // special modules: tmpNode1 = new RTreeViewNode(("Infrastructural")); tmpNode1->addChildNode(new RTreeViewNode(("Parameter"), romos::ModuleTypeRegistry::PARAMETER)); tmpNode1->addChildNode(new RTreeViewNode(("Container"), romos::ModuleTypeRegistry::CONTAINER)); tmpNode1->addChildNode(new RTreeViewNode(("Audio Input"), romos::ModuleTypeRegistry::AUDIO_INPUT)); tmpNode1->addChildNode(new RTreeViewNode(("Audio Output"), romos::ModuleTypeRegistry::AUDIO_OUTPUT)); tmpNode1->addChildNode(new RTreeViewNode(("Voice Combiner"), romos::ModuleTypeRegistry::VOICE_COMBINER)); tmpNode1->addChildNode(new RTreeViewNode(("SampleRate"), romos::ModuleTypeRegistry::SYSTEM_SAMPLE_RATE)); //tmpNode1->addChildNode(new RTreeViewNode(("SamplePeriod"), romos::ModuleTypeRegistry::SYSTEM_SAMPLE_PERIOD)); // insert event I/O here insertModuleNode->addChildNode(tmpNode1); //--------------------------------------------------------------------------- // event modules: tmpNode1 = new RTreeViewNode(("Events")); tmpNode1->addChildNode(new RTreeViewNode(("NoteGate"), romos::ModuleTypeRegistry::NOTE_GATE)); tmpNode1->addChildNode(new RTreeViewNode(("NoteOnTrigger"), romos::ModuleTypeRegistry::NOTE_ON_TRIGGER)); tmpNode1->addChildNode(new RTreeViewNode(("NoteOffTrigger"), romos::ModuleTypeRegistry::NOTE_OFF_TRIGGER)); tmpNode1->addChildNode(new RTreeViewNode(("VoiceKiller"), romos::ModuleTypeRegistry::VOICE_KILLER)); tmpNode1->addChildNode(new RTreeViewNode(("NoteFrequency"), romos::ModuleTypeRegistry::NOTE_FREQUENCY)); tmpNode1->addChildNode(new RTreeViewNode(("NoteVelocity"), romos::ModuleTypeRegistry::NOTE_VELOCITY)); insertModuleNode->addChildNode(tmpNode1); //--------------------------------------------------------------------------- // signal generator modules: tmpNode1 = new RTreeViewNode(("Signal Generators")); tmpNode1->addChildNode(new RTreeViewNode(("Phasor"), romos::ModuleTypeRegistry::PHASOR)); tmpNode1->addChildNode(new RTreeViewNode(("WhiteNoise"), romos::ModuleTypeRegistry::WHITE_NOISE)); tmpNode1->addChildNode(new RTreeViewNode(("BandlimitedImpulseTrain"), romos::ModuleTypeRegistry::BANDLIMITED_IMPULSE_TRAIN)); tmpNode1->addChildNode(new RTreeViewNode(("BlitSaw"), romos::ModuleTypeRegistry::BLIT_SAW_OSCILLATOR)); tmpNode1->addChildNode(new RTreeViewNode(("DualBlitSaw"), romos::ModuleTypeRegistry::DUAL_BLIT_SAW_OSCILLATOR)); insertModuleNode->addChildNode(tmpNode1); //--------------------------------------------------------------------------- // modulator modules: tmpNode1 = new RTreeViewNode(("Modulators")); tmpNode1->addChildNode(new RTreeViewNode(("EnvelopeADSR"), romos::ModuleTypeRegistry::ENVELOPE_ADSR)); insertModuleNode->addChildNode(tmpNode1); //--------------------------------------------------------------------------- // arithmetic modules: tmpNode1 = new RTreeViewNode(("Arithmetic")); // unary: tmpNode2 = new RTreeViewNode(("Unary")); tmpNode2->addChildNode(new RTreeViewNode(("Constant"), romos::ModuleTypeRegistry::CONSTANT)); tmpNode2->addChildNode(new RTreeViewNode(("UnaryMinus"), romos::ModuleTypeRegistry::UNARY_MINUS)); tmpNode2->addChildNode(new RTreeViewNode(("Reciprocal"), romos::ModuleTypeRegistry::RECIPROCAL)); //tmpNode2->addChildNode(new RTreeViewNode(("Formula"), romos::ModuleTypeRegistry::UNARY_FORMULA)); tmpNode1->addChildNode(tmpNode2); // binary: tmpNode2 = new RTreeViewNode(("Binary")); tmpNode2->addChildNode(new RTreeViewNode(("Adder"), romos::ModuleTypeRegistry::ADDER)); tmpNode2->addChildNode(new RTreeViewNode(("Subtractor"), romos::ModuleTypeRegistry::SUBTRACTOR)); tmpNode2->addChildNode(new RTreeViewNode(("Multiplier"), romos::ModuleTypeRegistry::MULTIPLIER)); tmpNode2->addChildNode(new RTreeViewNode(("Divider"), romos::ModuleTypeRegistry::DIVIDER)); tmpNode2->addChildNode(new RTreeViewNode(("AdderN"), romos::ModuleTypeRegistry::ADDER_N)); //tmpNode2->addChildNode(new RTreeViewNode(("Formula"), romos::ModuleTypeRegistry::BINARY_FORMULA)); tmpNode1->addChildNode(tmpNode2); // n-ary: //tmpNode2 = new RTreeViewNode(("Multiple Ins")); //tmpNode2->addChildNode(new RTreeViewNode(("Sum"), romos::ModuleTypeRegistry::SUM)); //tmpNode2->addChildNode(new RTreeViewNode(("Product"), romos::ModuleTypeRegistry::PRODUCT)); //tmpNode2->addChildNode(new RTreeViewNode(("Formula"), romos::ModuleTypeRegistry::MULTI_IN_FORMULA)); //tmpNode1->addChildNode(tmpNode2); // n ins, m outs: //tmpNode2 = new RTreeViewNode(("Multiple Ins and Outs")); //tmpNode2->addChildNode(new RTreeViewNode(("Matrix"), romos::ModuleTypeRegistry::MATRIX)); //tmpNode2->addChildNode(new RTreeViewNode(("Formula Array"), romos::ModuleTypeRegistry::FORMULA_ARRAY)); //tmpNode1->addChildNode(tmpNode2); insertModuleNode->addChildNode(tmpNode1); //--------------------------------------------------------------------------- // functional modules: tmpNode1 = new RTreeViewNode("Functions"); tmpNode1->addChildNode(new RTreeViewNode("Clipper", romos::ModuleTypeRegistry::CLIPPER)); tmpNode1->addChildNode(new RTreeViewNode("SinCos", romos::ModuleTypeRegistry::SIN_COS)); tmpNode1->addChildNode(new RTreeViewNode("TriSaw", romos::ModuleTypeRegistry::TRISAW)); insertModuleNode->addChildNode(tmpNode1); //--------------------------------------------------------------------------- // delay modules: tmpNode1 = new RTreeViewNode(("Delays")); tmpNode1->addChildNode(new RTreeViewNode(("Unit Delay"), romos::ModuleTypeRegistry::UNIT_DELAY)); //tmpNode1->addChildNode(new RTreeViewNode(("Integer Delay"), romos::ModuleTypeRegistry::INTEGER_DELAY)); //tmpNode1->addChildNode(new RTreeViewNode(("Tapped Integer Delay"), romos::ModuleTypeRegistry::TAPPED_INTEGER_DELAY)); //tmpNode1->addChildNode(new RTreeViewNode(("Fractional Delay"), romos::ModuleTypeRegistry::FRACTIONAL_DELAY)); //tmpNode1->addChildNode(new RTreeViewNode(("Tapped Fractional Delay"), romos::ModuleTypeRegistry::TAPPED_FRACTIONAL_DELAY)); insertModuleNode->addChildNode(tmpNode1); //--------------------------------------------------------------------------- // filter modules: // \todo use another hierarch level here to distinguish several classes of filters tmpNode1 = new RTreeViewNode(("Filters")); tmpNode1->addChildNode(new RTreeViewNode(("FirstOrderLowpass"), romos::ModuleTypeRegistry::FIRST_ORDER_LOWPASS)); tmpNode1->addChildNode(new RTreeViewNode(("FirstOrderFilter"), romos::ModuleTypeRegistry::FIRST_ORDER_FILTER)); tmpNode1->addChildNode(new RTreeViewNode(("Biquad"), romos::ModuleTypeRegistry::BIQUAD)); tmpNode1->addChildNode(new RTreeViewNode(("BiquadDesigner"), romos::ModuleTypeRegistry::BIQUAD_DESIGNER)); tmpNode1->addChildNode(new RTreeViewNode(("LadderFilter"), romos::ModuleTypeRegistry::LADDER_FILTER)); insertModuleNode->addChildNode(tmpNode1); */ availableModulesTreeView->setRootNode(treeRootNode); availableModulesTreeView->setBounds(0, 0, 200, 400); } void ModularBlockDiagramPanel::updateAudioConnectionArray() { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); selectedAudioConnections.clear(); allAudioConnections.clear(); unsigned int i; romos::Module *m; for(i = 0; i < getInterfaceMediator()->getContainerShownInDiagram()->getNumChildModules(); i++) { m = getInterfaceMediator()->getContainerShownInDiagram()->getChildModule(i); rosic::appendVector(allAudioConnections, m->getIncomingAudioConnections()); //for(j = 0; j < m->getNumIncomingAudioConnections(); j++) // rosic::appendElement(allAudioConnections, m->getIncomingAudioConnection(j)); //allAudioConnections.appendElement(m->getIncomingAudioConnection(j)); } /* for(i = 0; i < getInterfaceMediator()->getContainerShownInDiagram()->getNumOutputPins(); i++) { m = getInterfaceMediator()->getContainerShownInDiagram()->getAudioOutputModule(i); for(j = 0; j < m->getNumIncomingAudioConnections(); j++) rosic::appendElement(allAudioConnections, m->getIncomingAudioConnection(j)); //allAudioConnections.appendElement(m->getIncomingAudioConnection(j)); } */ } inline void setPixel(Graphics &g, int x, int y) { // preliminary - try to find a more efficient way ...and move to GraphicsTools g.fillRect(x, y, 1, 1); } void ModularBlockDiagramPanel::drawGrid(Graphics &g) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); int numVerticalLines = inPinDistances(getWidth())+1; int numHorizontalLines = inPinDistances(getHeight())+1; //g.setColour(Colours::black); // preliminary g.setColour(getPlotColourScheme().coarseGrid); if( gridStyle == GRID_LINES ) { for(int x=1; x<numVerticalLines; x++) g.drawVerticalLine(inPixels(x), 0.f, (float) getHeight()); for(int y=1; y<numHorizontalLines; y++) g.drawHorizontalLine(inPixels(y), 0.f, (float) getWidth()); } else if( gridStyle == DOTTED_GRID ) { for(int x=1; x<numVerticalLines; x++) { for(int y=1; y<numHorizontalLines; y++) { //g.setPixel(inPixels(x), inPixels(y)); // not available in juce 5.2.0 anymore //g.fillRect(inPixels(x), inPixels(y), 1, 1); setPixel(g, inPixels(x), inPixels(y)); } } } } void ModularBlockDiagramPanel::drawDiagram(Graphics &g) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); romos::ContainerModule *mc = getInterfaceMediator()->getContainerShownInDiagram(); unsigned int i; // draw the embedded modules: int test = mc->getNumInputPins(); for(i = 0; i < mc->getNumInputPins(); i++) drawModule(g, mc->getAudioInputModule(i)); for(i = 0; i < mc->getNumChildModules(); i++) drawModule(g, mc->getChildModule(i)); for(i = 0; i < mc->getNumOutputPins(); i++) drawModule(g, mc->getAudioOutputModule(i)); // draw the connections: for(i = 0; i < mc->getNumInputPins(); i++) drawIncomingConnectionsForModule(g, mc->getAudioInputModule(i)); for(i = 0; i < mc->getNumChildModules(); i++) drawIncomingConnectionsForModule(g, mc->getChildModule(i)); for(i = 0; i < mc->getNumOutputPins(); i++) drawIncomingConnectionsForModule(g, mc->getAudioOutputModule(i)); // \todo draw event I/O modules ...maybe we can collapse these loops into one when Module provides functions like // getNumContainedModules/getContainedModule - these would inlcude all the enclosed modules (child/I/O) // draw temporary connection: if( !tmpAudioConnection.isNull() ) { Point<int> mouse = getMouseXYRelative(); int x1 = snapPixelPositionToGrid(mouseDownX); // write a function for inPixels(inPinDistances)), call it snapToGrid int y1 = snapPixelPositionToGrid(mouseDownY); int x2 = snapPixelPositionToGrid(mouse.getX()); int y2 = snapPixelPositionToGrid(mouse.getY()); g.drawLine((float) x1, (float) y1, (float) x2, (float) y2); } // draw selected connections in red (preliminary): g.setColour(highlightColour); for(i = 0; i < selectedAudioConnections.size(); i++) g.drawLine(getLineForConnection(selectedAudioConnections[i])); for(i = 0; i < audioConnectionsInLasso.size(); i++) g.drawLine(getLineForConnection(audioConnectionsInLasso[i])); } void ModularBlockDiagramPanel::drawModule(Graphics &g, romos::Module *moduleToDraw) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); if( moduleToDraw == NULL ) return; //if( moduleToDraw->getTypeIdentifier() == romos::ModuleTypeRegistry::AUDIO_OUTPUT ) // DEBUG_BREAK; int x, y, w, h; getRectangleForModuleInPixels(moduleToDraw, x, y, w, h, false); juce::Rectangle<int> moduleReactangle(x, y, w ,h); if( moduleToDraw->isPolyphonic() ) { // wrap this into a function (drawPolyphonyShadow() or something): g.setColour(plotColourScheme.getCurveColourUniform(0).withAlpha(0.375f)); int offset = 8; g.drawRect(x-offset, y+offset, w, h, t); setPixel(g, x-2, y+2); setPixel(g, x-2, y+3); setPixel(g, x-3, y+2); setPixel(g, x-3, y+3); setPixel(g, x-5, y+5); setPixel(g, x-5, y+6); setPixel(g, x-6, y+5); setPixel(g, x-6, y+6); setPixel(g, x+w-2, y+h+2); setPixel(g, x+w-2, y+h+3); setPixel(g, x+w-3, y+h+2); setPixel(g, x+w-3, y+h+3); setPixel(g, x+w-5, y+h+5); setPixel(g, x+w-5, y+h+6); setPixel(g, x+w-6, y+h+5); setPixel(g, x+w-6, y+h+6); setPixel(g, x-2+1, y+h+2-2); setPixel(g, x-2+1, y+h+3-2); setPixel(g, x-3+1, y+h+2-2); setPixel(g, x-3+1, y+h+3-2); setPixel(g, x-5+1, y+h+5-2); setPixel(g, x-5+1, y+h+6-2); setPixel(g, x-6+1, y+h+5-2); setPixel(g, x-6+1, y+h+6-2); /* // setPixel not available anymore in juce 5.2 - find replacement g.setPixel(x-2, y+2); g.setPixel(x-2, y+3); g.setPixel(x-3, y+2); g.setPixel(x-3, y+3); g.setPixel(x-5, y+5); g.setPixel(x-5, y+6); g.setPixel(x-6, y+5); g.setPixel(x-6, y+6); g.setPixel(x+w-2, y+h+2); g.setPixel(x+w-2, y+h+3); g.setPixel(x+w-3, y+h+2); g.setPixel(x+w-3, y+h+3); g.setPixel(x+w-5, y+h+5); g.setPixel(x+w-5, y+h+6); g.setPixel(x+w-6, y+h+5); g.setPixel(x+w-6, y+h+6); g.setPixel(x-2+1, y+h+2-2); g.setPixel(x-2+1, y+h+3-2); g.setPixel(x-3+1, y+h+2-2); g.setPixel(x-3+1, y+h+3-2); g.setPixel(x-5+1, y+h+5-2); g.setPixel(x-5+1, y+h+6-2); g.setPixel(x-6+1, y+h+5-2); g.setPixel(x-6+1, y+h+6-2); */ } //g.setColour(Colours::lavender); // preliminary g.setColour(getPlotColourScheme().topLeft); g.fillRect(x, y, w, h); g.setColour(plotColourScheme.getCurveColourUniform(0)); g.drawRect(x, y, w, h, t); juce::String name = juce::String( moduleToDraw->getName().c_str() ); if( moduleToDraw->hasHeader() ) { g.drawRect(x, y, w, bigFontHeight+2*m+2*t, t); // encloses the title drawBitmapFontText(g, x+t+m, y+t+m, name, bigFont, plotColourScheme.text, -1, Justification::topLeft); } else { int xArrow; int xText = x+t+s+m; if( dynamic_cast<romos::AudioInputModule*> (moduleToDraw) ) { xArrow = x+t+m; xText += arrowLength + m; g.drawArrow(Line<float>((float) xArrow, (float) (y+h/2), (float) (xArrow+arrowLength), (float) (y+h/2)), (float) (t+1), (float) (h-(2*t+2*m)), (float) arrowHeadLength); // preliminary - write our own drawing function (no-anti-aliasing) } else if( dynamic_cast<romos::AudioOutputModule*> (moduleToDraw) ) { xArrow = x+w-arrowLength-t-m; g.drawArrow(Line<float>((float) xArrow, (float) (y+h/2), (float) (xArrow+arrowLength), (float) (y+h/2)), (float) (t+1), (float) (h-(2*t+2*m)), (float) arrowHeadLength); } //drawBitmapFontText(g, xText, y+t+m-2, name, &boldFont10px, plotColourScheme.text, -1, Justification::topLeft); drawBitmapFontText(g, xText, y+t+m-1, name, bigFont, plotColourScheme.text, -1, Justification::topLeft); //drawBitmapFontText(g, xText, y+t+m-2+1, name, normalFont, plotColourScheme.text, -1, Justification::topLeft); } if( isModuleSelected(moduleToDraw) || rosic::containsElement(modulesInLasso, moduleToDraw) ) //if( isModuleSelected(moduleToDraw) || modulesInLasso.hasElement(moduleToDraw) ) { g.setColour(highlightColour); g.drawRect(x, y, w, h, 1); // \todo red frame is preliminary, find a better selection indicator } if( !dynamic_cast<romos::AudioInputModule*> (moduleToDraw) ) drawInputPins(g, moduleToDraw, moduleReactangle); if( !dynamic_cast<romos::AudioOutputModule*> (moduleToDraw) ) drawOutputPins(g, moduleToDraw, moduleReactangle); //drawIncomingConnectionsForModule(g, moduleToDraw, moduleReactangle); } void ModularBlockDiagramPanel::drawInputPins(Graphics &g, romos::Module *module, juce::Rectangle<int> moduleRectangle) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); if( module == NULL ) return; // the position where to draw the pin's text: int x = moduleRectangle.getX() + s + t + m; int y = moduleRectangle.getY() + getModuleTitleHeightInPixels(module) + m; // coordinates of the pin itself: float px = (float) (x - m - 2*s - t); float py = (float) (y + 1); float pw = (float) (t+2*s); float ph = (float) (smallFontHeight - 2); unsigned int i; for(i=0; i<module->getNumInputPins(); i++) { juce::String pinName = juce::String( module->getPinName(AUDIO, INCOMING, i).getRawString() ); if(!module->isInputPinConnected(i) && module->hasHeader()) pinName += "=" + juce::String(module->getInputPinDefaultValue(i)); drawBitmapFontText(g, x, y, pinName, smallFont, plotColourScheme.text, -1, Justification::topLeft); py = (float) (y+1); g.fillRect(px, py, pw, ph); y += (smallFontHeight+m); //y += pinDistance; } } void ModularBlockDiagramPanel::drawOutputPins(Graphics &g, romos::Module *module, juce::Rectangle<int> moduleRectangle) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); if( module == NULL ) return; int x = moduleRectangle.getX(); int y = moduleRectangle.getY(); int w = moduleRectangle.getWidth(); int h = moduleRectangle.getHeight(); y += getModuleTitleHeightInPixels(module) + m; float px = (float) (x + w - t - s); float py = (float) (y + 1); float pw = (float) (t+2*s); float ph = (float) (smallFontHeight - 2); unsigned int i; for(i = 0; i < module->getNumOutputPins(); i++) { drawBitmapFontText(g, x+w-s-t-m, y, juce::String( module->getPinName(AUDIO, OUTGOING, i).getRawString() ), smallFont, plotColourScheme.text, -1, Justification::topRight); py = (float) (y + 1); g.fillRect(px, py, pw, ph); y += (smallFontHeight+m); } // \todo perhaps we can avoid some code duplication by factoring out commonalities in drawing all the different kinds of pins } void ModularBlockDiagramPanel::drawIncomingConnectionsForModule(Graphics &g, romos::Module *module) { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); if( module == NULL ) return; if( module->isInputModule() ) // input modules do not show their connections (they are invisible to the GUI) return; juce::Rectangle<int> moduleRectangle = getRectangleForModuleInPixels(module, false); //g.setColour(Colours::red); // only for test int xs, xt, ys, yt; // center coordinates of source and target pin unsigned int i; romos::AudioConnection c; romos::Module *sourceModule; unsigned int sourcePinIndex, targetPinIndex; std::vector<romos::AudioConnection> incomingConnections = module->getIncomingAudioConnections(); for(i = 0; i < incomingConnections.size(); i++) { c = incomingConnections[i]; sourceModule = c.getSourceModule(); if( sourceModule == NULL ) // can happen for temporary connections continue; sourcePinIndex = c.getSourceOutputIndex(); targetPinIndex = c.getTargetInputIndex(); getPinCenterCoordinates(romos::AUDIO, romos::INCOMING,c.getTargetInputIndex(), module, moduleRectangle, xt, yt); juce::Rectangle<int> sourceRectangle = getRectangleForModuleInPixels(c.getSourceModule(), false); getPinCenterCoordinates(romos::AUDIO, romos::OUTGOING, c.getSourceOutputIndex(), c.getSourceModule(), sourceRectangle, xs, ys); Line<float> connectionLine((float) xs, (float) ys, (float) xt, (float) yt); if( ys == yt ) g.drawHorizontalLine(ys, (float) xs, (float) xt); else { g.drawLine(connectionLine); // \todo draw the line in 3 segments - 2 horizontals and a vertical - but the decision where to put the vertical should actually // depend on external factors such as how many other connections there are which might be obscured...mmmhhh // probably better to let the user do this by letting connections have breakpoints ...they could then also provide a method // isPointOnConnection... } if( c.hasImplicitDelay() ) { int xMid = roundToInt( 0.5*(xs+xt) ); int yMid = roundToInt( 0.5*(ys+yt) ); int w = bigFont->getTextPixelWidth(juce::String(("D")), bigFont->getDefaultKerning())+2*m+2*t; int h = bigFont->getFontHeight()+2*m+2*t; int xd = xMid - w/2; int yd = yMid - h/2; g.setColour(Colours::white); // preliminary g.fillRect(xd, yd, w, h); g.setColour(Colours::black); // preliminary g.drawRect(xd, yd, w, h, t); drawBitmapFontText(g, xd+t+m, yd+t+m, juce::String(("D")), bigFont, plotColourScheme.text, bigFont->getDefaultKerning(), Justification::topLeft); } } } void ModularBlockDiagramPanel::getRectangleForModuleInPixels(romos::Module *module, int &x, int &y, int &w, int &h, bool includingPins) const { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); if( module == NULL ) { x = y = w = h = 0; return; } x = inPixels(module->getPositionX()); y = inPixels(module->getPositionY()) - getOffsetY(module); if( isModuleSelected(module) ) { x += selectionOffsetX; y += selectionOffsetY; } w = getRequiredWidthForModuleInPixels(module, includingPins); h = getRequiredHeightForModuleInPixels(module); if( includingPins ) x -= s; // left border goes one stickout "s" leftward } juce::Rectangle<int> ModularBlockDiagramPanel::getRectangleForModuleInPixels(romos::Module *module, bool includingPins) const { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); int x, y, w, h; getRectangleForModuleInPixels(module, x, y, w, h, includingPins); return juce::Rectangle<int>(x, y, w, h); } int ModularBlockDiagramPanel::getModuleTitleHeightInPixels(romos::Module *module) const { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); if( module == NULL ) return 0; if( module->hasHeader() ) return 2*t + 2*m + bigFontHeight; else return t; } bool ModularBlockDiagramPanel::isModuleInsideRectangle(romos::Module *module, juce::Rectangle<int> rectangle, bool includingPins) const { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); juce::Rectangle<int> moduleRectangle = getRectangleForModuleInPixels(module, includingPins); return rectangle.intersects(moduleRectangle); } int ModularBlockDiagramPanel::getRequiredWidthForModuleInPixels(romos::Module *module, bool includingPins) const { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); if( module == NULL ) return 0; juce::String name = juce::String( module->getName().c_str() ); int width = bigFont->getTextPixelWidth(name, bigFont->getDefaultKerning()); if( dynamic_cast<romos::AudioInputModule*> (module) || dynamic_cast<romos::AudioOutputModule*> (module) ) width += arrowLength + m; if( includingPins == false ) width += 2*t + 2*m; else width += 2*t + 2*m + 2*s; // pins stick out one stickout "s" to left and right, so width is 2*s more if( !module->hasHeader() ) width += 2*s; return width; // \todo maybe refine the width-computation to take into account the names of the pins } int ModularBlockDiagramPanel::getRequiredHeightForModuleInPixels(romos::Module *module) const { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); if( module == NULL ) return 0; int numPins = jmax(module->getNumInputPins(), module->getNumOutputPins() ); return getModuleTitleHeightInPixels(module) + numPins*(m+smallFontHeight) + m + t; } juce::Rectangle<int> ModularBlockDiagramPanel::getPinBounds(int kindOfPin, int direction, int pinIndex, romos::Module *module, juce::Rectangle<int> moduleRectangle) const { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); if( module == NULL ) return juce::Rectangle<int>(0, 0, 0, 0); int x = moduleRectangle.getX(); if( direction == romos::OUTGOING ) x += moduleRectangle.getWidth() - (t+2*m); int y = moduleRectangle.getY(); y += getModuleTitleHeightInPixels(module) + m + 1; // + (int) floor(0.5 * hs); y += pinIndex * pinDistance; if( kindOfPin == romos::EVENT ) { if( direction == romos::INCOMING ) y += module->getNumInputPins() * pinDistance; else y += module->getNumOutputPins() * pinDistance; } int w = t+2*m; int h = smallFontHeight-2; return juce::Rectangle<int>(x, y, w, h); } void ModularBlockDiagramPanel::getPinCenterCoordinates(int kindOfPin, int direction, int pinIndex, romos::Module *module, juce::Rectangle<int> moduleRectangle, int &xPin, int &yPin) const { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); if( module == NULL ) { xPin = yPin; return; } xPin = moduleRectangle.getX(); if( direction == romos::OUTGOING ) xPin += moduleRectangle.getWidth()-1; else xPin += 1; yPin = moduleRectangle.getY(); yPin += getModuleTitleHeightInPixels(module) + m + (int) floor(0.5 * smallFontHeight); yPin += pinIndex * pinDistance; if( kindOfPin == romos::EVENT ) { if( direction == romos::INCOMING ) yPin += module->getNumInputPins() * pinDistance; else yPin += module->getNumOutputPins() * pinDistance; } } juce::Line<float> ModularBlockDiagramPanel::getLineForConnection(romos::AudioConnection connection) const { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); romos::Module *sourceModule = connection.getSourceModule(); romos::Module *targetModule = connection.getTargetModule(); int sourcePinIndex = connection.getSourceOutputIndex(); int targetPinIndex = connection.getTargetInputIndex(); juce::Rectangle<int> sourceRectangle = getRectangleForModuleInPixels(sourceModule, false); juce::Rectangle<int> targetRectangle = getRectangleForModuleInPixels(targetModule, false); if( sourceModule == NULL ) return Line<float>(0.f, 0.f, 200.f, 200.f); // if this line appears on the screen, something went wrong int xs, xt, ys, yt; getPinCenterCoordinates(romos::AUDIO, romos::OUTGOING, sourcePinIndex, sourceModule, sourceRectangle, xs, ys); getPinCenterCoordinates(romos::AUDIO, romos::INCOMING, targetPinIndex, targetModule, targetRectangle, xt, yt); return Line<float>((float) xs, (float) ys, (float) xt, (float) yt); } std::vector<romos::Module*> ModularBlockDiagramPanel::getModulesInRectangle(juce::Rectangle<int> rectangle) const { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); std::vector<romos::Module*> result; unsigned int i; romos::Module *module; /* for(i = 0; i < getInterfaceMediator()->getContainerShownInDiagram()->getNumInputs(); i++) { module = getInterfaceMediator()->getContainerShownInDiagram()->getAudioInputModule(i); if( isModuleInsideRectangle(module, rectangle, false) ) rosic::appendElement(result, module); //result.appendElement(module); } */ for(i = 0; i < getInterfaceMediator()->getContainerShownInDiagram()->getNumChildModules(); i++) { module = getInterfaceMediator()->getContainerShownInDiagram()->getChildModule(i); if( isModuleInsideRectangle(module, rectangle, false) ) rosic::appendElement(result, module); //result.appendElement(module); } /* for(i = 0; i < getInterfaceMediator()->getContainerShownInDiagram()->getNumOutputs(); i++) { module = getInterfaceMediator()->getContainerShownInDiagram()->getAudioOutputModule(i); if( isModuleInsideRectangle(module, rectangle, false) ) rosic::appendElement(result, module); //result.appendElement(module); } */ // todo we need a means to iterate over all embedded modules at once to avoid this kind of code-duplication // ->done ->commented code may be deleted ...hopefully - but check that it works before return result; } romos::Module* ModularBlockDiagramPanel::getModuleAtPixels(int x, int y, bool considerPins) const { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); // loop through the modules, return the first which is found to include the point: // todo: maybe use a local variable for getInterfaceMediator()->getContainerShownInDiagram() as abbreviation unsigned int i; for(i = 0; i < getInterfaceMediator()->getContainerShownInDiagram()->getNumInputPins(); i++) { if( getRectangleForModuleInPixels(getInterfaceMediator()->getContainerShownInDiagram()->getAudioInputModule(i), considerPins).contains(x, y) ) return getInterfaceMediator()->getContainerShownInDiagram()->getAudioInputModule(i); } for(i = 0; i < getInterfaceMediator()->getContainerShownInDiagram()->getNumChildModules(); i++) { if( getRectangleForModuleInPixels(getInterfaceMediator()->getContainerShownInDiagram()->getChildModule(i), considerPins).contains(x, y) ) return getInterfaceMediator()->getContainerShownInDiagram()->getChildModule(i); } for(i = 0; i < getInterfaceMediator()->getContainerShownInDiagram()->getNumOutputPins(); i++) { if( getRectangleForModuleInPixels(getInterfaceMediator()->getContainerShownInDiagram()->getAudioOutputModule(i), considerPins).contains(x, y) ) return getInterfaceMediator()->getContainerShownInDiagram()->getAudioOutputModule(i); } return NULL; } romos::AudioConnection ModularBlockDiagramPanel::getConnectionAtPixels(int x, int y) const { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); romos::AudioConnection ac; juce::Line<float> connectionLine; float tolerance = 2.f; for(unsigned int i = 0; i < allAudioConnections.size(); i++) { ac = allAudioConnections.at(i); connectionLine = getLineForConnection(ac); Point<float> dummy; if( connectionLine.getDistanceFromPoint(Point<float>((float) x, (float) y), dummy) < tolerance ) return ac; //if( connectionLine.getDistanceFromLine((float) x, (float) y) < tolerance ) // return ac; } return AudioConnection(); } bool ModularBlockDiagramPanel::getPinPropertiesAtPixels(int x, int y, romos::Module* module, juce::Rectangle<int> moduleRectangle, int &kindOfPin, int &directionOfPin, int &indexOfPin) const { ScopedLock scopedLock(*(getInterfaceMediator()->plugInLock)); kindOfPin = -1; directionOfPin = -1; indexOfPin = -1; if( module == NULL ) return false; unsigned int i; int tolerance = pinDistance/2; int yPin; int yFirstPin = moduleRectangle.getY() + getModuleTitleHeightInPixels(module) + m + (int) floor(0.5 * smallFontHeight); if( x >= moduleRectangle.getX() && x <= moduleRectangle.getX() + tolerance ) // x is near left border { if( dynamic_cast<romos::AudioInputModule*> (module) != NULL ) return false; yPin = yFirstPin; for(i = 0; i < module->getNumInputPins(); i++) { if( abs(y-yPin) <= tolerance ) { kindOfPin = romos::AUDIO; directionOfPin = romos::INCOMING; indexOfPin = i; return true; } yPin += pinDistance; } } if( x <= moduleRectangle.getRight() && x >= moduleRectangle.getRight() - tolerance ) // x is near right border { if( dynamic_cast<romos::AudioOutputModule*> (module) != NULL ) return false; yPin = yFirstPin; for(i=0; i<module->getNumOutputPins(); i++) { if( abs(y-yPin) <= tolerance ) { kindOfPin = romos::AUDIO; directionOfPin = romos::OUTGOING; indexOfPin = i; return true; } yPin += pinDistance; } } return false; } //========================================================================================================================================= // class LibertyEditor: //----------------------------------------------------------------------------------------------------------------------------------------- // construction/destruction: LibertyEditor::LibertyEditor(CriticalSection *newPlugInLock, LibertyAudioModule* newLibertyAudioModule) //: PolyphonicInstrumentEditor(newPlugInLock, newLibertyAudioModule) : AudioModuleEditor(newLibertyAudioModule) { ScopedLock scopedLock(*lock); setHeadlineStyle(MAIN_HEADLINE); jassert(newLibertyAudioModule != NULL ); // you must pass a valid module here modularSynthAudioModule = newLibertyAudioModule; stateWidgetSet->setLayout(StateLoadSaveWidgetSet::LABEL_AND_BUTTONS_ABOVE); interfaceMediator = new LibertyInterfaceMediator(newPlugInLock, newLibertyAudioModule); structureTreeView = new ModularStructureTreeView(interfaceMediator); structureTreeView->setOpenOrCloseNodesOnClick(true); structureTreeView->setDescription(("Patch structure represented as tree")); structureTreeView->setDescriptionField(descriptionField); addWidget(structureTreeView); moduleEditorHolder = new ModulePropertiesEditorHolder(interfaceMediator); moduleEditorHolder->setDescription(("Editor for currently selected module")); moduleEditorHolder->setDescriptionField(descriptionField, true); addChildColourSchemeComponent(moduleEditorHolder); blockDiagramPanel = new ModularBlockDiagramPanel(interfaceMediator); blockDiagramPanel->setDescription(("Block diagram representation of selected container")); blockDiagramPanel->setDescriptionField(descriptionField, true); diagramScrollContainer = new ComponentScrollContainer(blockDiagramPanel); addChildColourSchemeComponent(diagramScrollContainer); presetSectionPosition = BELOW_HEADLINE; //isTopLevelEditor = true; stateWidgetSet->setLayout(StateLoadSaveWidgetSet::LABEL_AND_BUTTONS_ABOVE); updateWidgetsAccordingToState(); setSize(600, 400); } LibertyEditor::~LibertyEditor() { // for the mediated components, we must take care to delete them before the mediator is deleted, so we do it manually here: removeChildComponent(structureTreeView); removeChildComponent(moduleEditorHolder); removeChildComponent(diagramScrollContainer); delete structureTreeView; delete moduleEditorHolder; delete diagramScrollContainer; delete interfaceMediator; } //----------------------------------------------------------------------------------------------------------------------------------------- // callbacks: /* void LibertyEditor::rButtonClicked(RButton *buttonThatWasClicked) { ScopedLock scopedLock(*plugInLock); updateWidgetsAccordingToState(); } */ void LibertyEditor::resized() { ScopedLock scopedLock(*lock); AudioModuleEditor::resized(); int x, y, w, h; x = 0; y = stateWidgetSet->getBottom() - 8; w = getWidth()/4 ; h = 240; stateWidgetSet->setBounds(0, 4, getWidth()/4, 32); structureTreeView->setBounds(x, y, w, h); x += w - RWidget::outlineThickness; w = getWidth() - x ; moduleEditorHolder->setBounds(x, y, w, h); x = 0; y = moduleEditorHolder->getBottom(); w = getWidth(); h = infoField->getY() - y; diagramScrollContainer->setBounds(x, y, w, h); blockDiagramPanel->setAvailabeSizeForCanvas(w, h); } void LibertyEditor::updateWidgetsAccordingToState() { ScopedLock scopedLock(*lock); structureTreeView->getInterfaceMediator()->setContainerToShowInDiagram(structureTreeView->getInterfaceMediator()->getTopLevelModule()); // the mediator will take care to update all panels }
38.436723
219
0.693023
[ "object", "vector" ]
319bc9a2200fd93211cf86f9f0e31601f2287a8f
307
cpp
C++
bjarnePPPUC/chp4/4.6/mean_median.cpp
Binary-bug/Cplusplus
48e33d1c572062b34ca57fe61a186ef675a9980b
[ "MIT" ]
null
null
null
bjarnePPPUC/chp4/4.6/mean_median.cpp
Binary-bug/Cplusplus
48e33d1c572062b34ca57fe61a186ef675a9980b
[ "MIT" ]
null
null
null
bjarnePPPUC/chp4/4.6/mean_median.cpp
Binary-bug/Cplusplus
48e33d1c572062b34ca57fe61a186ef675a9980b
[ "MIT" ]
null
null
null
#include "std_lib_facilities.h" int main(){ vector<double> temps; for(double temp;cin>>temp;) temps.push_back(temp); double sum=0; for(double x:temps) sum+=x; cout<<"Average temperature: "<<sum/temps.size()<<'\n'; sort(temps); cout<<"Media temperatute: "<<temps[temps.size()/2]<<'\n'; return 0; }
16.157895
57
0.664495
[ "vector" ]
31a42bec013c966b117d501d08986f92b74f0341
3,064
hh
C++
ermia/include/transaction.hh
KoseMasu/ccbench-1
ec43e67acf0674919feaea6ff252f904cd38a5bc
[ "Apache-2.0" ]
30
2019-03-20T07:23:53.000Z
2022-02-01T01:00:02.000Z
ermia/include/transaction.hh
KoseMasu/ccbench-1
ec43e67acf0674919feaea6ff252f904cd38a5bc
[ "Apache-2.0" ]
8
2019-06-06T04:24:16.000Z
2021-12-10T05:55:35.000Z
ermia/include/transaction.hh
KoseMasu/ccbench-1
ec43e67acf0674919feaea6ff252f904cd38a5bc
[ "Apache-2.0" ]
10
2019-07-21T15:24:19.000Z
2022-03-15T02:07:23.000Z
#pragma once #include <cstdint> #include <map> #include <vector> #include "../../include/config.hh" #include "../../include/procedure.hh" #include "../../include/result.hh" #include "../../include/string.hh" #include "../../include/util.hh" #include "common.hh" #include "ermia_op_element.hh" #include "garbage_collection.hh" #include "transaction_status.hh" #include "transaction_table.hh" #include "tuple.hh" #include "version.hh" using namespace std; class TxExecutor { public: char return_val_[VAL_SIZE] = {}; char write_val_[VAL_SIZE] = {}; uint8_t thid_; // thread ID uint32_t cstamp_ = 0; // Transaction end time, c(T) uint32_t pstamp_ = 0; // Predecessor high-water mark, η (T) uint32_t sstamp_ = UINT32_MAX; // Successor low-water mark, pi (T) uint32_t pre_gc_threshold_ = 0; uint32_t txid_; // TID and begin timestamp - the current log sequence number (LSN) uint64_t gcstart_, gcstop_; // counter for garbage collection vector <SetElement<Tuple>> read_set_; vector <SetElement<Tuple>> write_set_; vector <Procedure> pro_set_; Result *eres_; TransactionStatus status_ = TransactionStatus::inFlight; // Status: inFlight, committed, or aborted GarbageCollection gcobject_; TxExecutor(uint8_t thid, Result *eres) : thid_(thid), eres_(eres) { gcobject_.set_thid_(thid); read_set_.reserve(FLAGS_max_ope); write_set_.reserve(FLAGS_max_ope); pro_set_.reserve(FLAGS_max_ope); if (FLAGS_pre_reserve_tmt_element) { for (size_t i = 0; i < FLAGS_pre_reserve_tmt_element; ++i) gcobject_.reuse_TMT_element_from_gc_.emplace_back( new TransactionTable()); } if (FLAGS_pre_reserve_version) { for (size_t i = 0; i < FLAGS_pre_reserve_version; ++i) gcobject_.reuse_version_from_gc_.emplace_back(new Version()); } genStringRepeatedNumber(write_val_, VAL_SIZE, thid); } SetElement<Tuple> *searchReadSet(unsigned int key); SetElement<Tuple> *searchWriteSet(unsigned int key); void tbegin(); void ssn_tread(uint64_t key); void ssn_twrite(uint64_t key); void ssn_commit(); void ssn_parallel_commit(); void abort(); void mainte(); void verify_exclusion_or_abort(); void dispWS(); void dispRS(); void upReadersBits(Version *ver) { uint64_t expected, desired; expected = ver->readers_.load(memory_order_acquire); for (;;) { desired = expected | (1 << thid_); if (ver->readers_.compare_exchange_weak( expected, desired, memory_order_acq_rel, memory_order_acquire)) break; } } void downReadersBits(Version *ver) { uint64_t expected, desired; expected = ver->readers_.load(memory_order_acquire); for (;;) { desired = expected & ~(1 << thid_); if (ver->readers_.compare_exchange_weak( expected, desired, memory_order_acq_rel, memory_order_acquire)) break; } } static INLINE Tuple *get_tuple(Tuple *table, uint64_t key) { return &table[key]; } };
26.877193
84
0.676567
[ "vector" ]
b3b1b00b88a6a919d163e1c062f7974e66c763de
11,667
cpp
C++
Samples/Win7Samples/tabletpc/multireco/cpp/ChildWnds.cpp
windows-development/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
8
2017-04-30T17:38:27.000Z
2021-11-29T00:59:03.000Z
Samples/Win7Samples/tabletpc/multireco/cpp/ChildWnds.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
null
null
null
Samples/Win7Samples/tabletpc/multireco/cpp/ChildWnds.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
2
2020-08-11T13:21:49.000Z
2021-09-01T10:41:51.000Z
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. // // Module: // ChildWnds.cpp // // Description: // The file contains the definitions of the methods of the classes // CInkInputWnd and CRecoOutputWnd. // See the file ChildWnds.h for the definitions of the classes. //-------------------------------------------------------------------------- #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0500 #endif // Windows header file #include <windows.h> #include <richedit.h> // ATL header files: #include <atlbase.h> // defines CComModule, CComPtr, CComVariant extern CComModule _Module; #include <atlwin.h> // defines CWindowImpl // Tablet PC Automation interfaces header file #include <msinkaut.h> // The application header files #include "resource.h" // main symbols, including command ID's #include "ChildWnds.h" // contains the CInkInputWnd and CRecoOutputWnd definitions //////////////////////////////////////////////////////// // CInkInputWnd methods //////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// // // CInkInputWnd::CInkInputWnd // // Constructor. // // Parameters: // none // ///////////////////////////////////////////////////////// CInkInputWnd::CInkInputWnd() : m_cRows(0), m_cColumns(0), m_iMidline(-1) { m_ptGridLT.x = m_ptGridLT.y = 0; m_szWritingBox.cx = m_szWritingBox.cy = 0; ::SetRectEmpty(&m_rcDrawnBox); } ///////////////////////////////////////////////////////// // // CInkInputWnd::SetGuide // // Data members access method for setting the guide // drawing parameters. // // Parameters: // _InkRecoGuide& irg : see the Tablet PC Automation API // reference for the description // of the structure // // Return Values (void): // none // ///////////////////////////////////////////////////////// void CInkInputWnd::SetGuide( const _InkRecoGuide& irg ) { // Initialize the data members with values from the recognition guide structure m_ptGridLT.x = irg.rectWritingBox.left; m_ptGridLT.y = irg.rectWritingBox.top; m_szWritingBox.cx = irg.rectWritingBox.right - irg.rectWritingBox.left; m_szWritingBox.cy = irg.rectWritingBox.bottom - irg.rectWritingBox.top; m_rcDrawnBox = irg.rectDrawnBox; m_iMidline = irg.midline; m_cRows = irg.cRows; m_cColumns = irg.cColumns; // Update the window if (IsWindow()) { Invalidate(); } } ///////////////////////////////////////////////////////// // // CInkInputWnd::SetGuide // // Data members access method for setting the number // of the guide's rows and columns. // // Parameters: // int iRows : the number of rows // int iColumns : the number of columns // // Return Values (void): // none // ///////////////////////////////////////////////////////// void CInkInputWnd::SetRowsCols( int iRows, int iColumns ) { m_cRows = iRows; m_cColumns = iColumns; // Update the window if (IsWindow()) { Invalidate(); } } ///////////////////////////////////////////////////////// // // CInkInputWnd::OnPaint // // The WM_PAINT message handler. The ATL calls this member // function when Windows or an application makes a request // to repaint a portion of the CInkInputWnd object's window. // The method paints the window's background and draws // the guide if necessary. // // Parameters: // defined in the ATL's MESSAGE_HANDLER macro, // none is used here // // Return Value (LRESULT): // always 0 // ///////////////////////////////////////////////////////// LRESULT CInkInputWnd::OnPaint( UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/ ) { RECT rcClip; if (FALSE == GetUpdateRect(&rcClip)) return 0; // there's no update region, so no painting is needed PAINTSTRUCT ps; HDC hdc = BeginPaint(&ps); if (hdc == NULL) return 0; // Get the rectangle to paint. GetClipBox(hdc, &rcClip); // Paint the background. ::FillRect(hdc, &rcClip, (HBRUSH)::GetStockObject(DC_BRUSH)); // Calculate the grid rectangle. Assume that if there are any guides, // they are either boxes or horizontal lines. RECT rcGrid = {m_ptGridLT.x, m_ptGridLT.y, 0, m_ptGridLT.y + m_szWritingBox.cy * m_cRows}; if (0 == m_cColumns && 0 != m_cRows) { rcGrid.right = rcClip.right; } else { rcGrid.right = m_ptGridLT.x + m_szWritingBox.cx * m_cColumns; } // Draw the guide grid, if it's visible and not empty. RECT rcVisible; if (FALSE == ::IsRectEmpty(&rcGrid) && TRUE == ::IntersectRect(&rcVisible, &rcGrid, &rcClip)) { // Create a thin lightgray pen to draw the guides. HPEN hPen = ::CreatePen(PS_SOLID, 1, RGB(192, 192, 192)); HGDIOBJ hOldPen = ::SelectObject(hdc, hPen); if (0 == m_cColumns) { // Draw horizontal lines at the bottom side of the guide's DrawnBox int iY = rcClip.top - ((rcClip.top - m_ptGridLT.y) % m_szWritingBox.cy) + m_rcDrawnBox.bottom; for (int iRow = (rcClip.top - m_ptGridLT.y) / m_szWritingBox.cy; (iRow < m_cRows) && (iY < rcClip.bottom); iRow++, iY += m_szWritingBox.cy) { ::MoveToEx(hdc, rcClip.left, iY, NULL); ::LineTo(hdc, rcClip.right, iY); } } else { // Draw boxes int iY = rcClip.top - ((rcClip.top - m_ptGridLT.y) % m_szWritingBox.cy); for (int iRow = (rcClip.top - m_ptGridLT.y) / m_szWritingBox.cy; (iRow < m_cRows) && (iY < rcClip.bottom); iRow++, iY += m_szWritingBox.cy) { int iX = rcClip.left - ((rcClip.left - m_ptGridLT.x) % m_szWritingBox.cx); RECT rcBox = m_rcDrawnBox; ::OffsetRect(&rcBox, iX, iY); for (int iCol = (rcClip.left - m_ptGridLT.x) / m_szWritingBox.cx; (iCol < m_cColumns) && (rcBox.left < rcClip.right); iCol++) { ::Rectangle(hdc, rcBox.left, rcBox.top, rcBox.right, rcBox.bottom); ::OffsetRect(&rcBox, m_szWritingBox.cx, 0); } } } // Restore the dc and delete the pen ::SelectObject(hdc, hOldPen); ::DeleteObject(hPen); } EndPaint(&ps); return 0; } //////////////////////////////////////////////////////// // CRecoOutputWnd methods //////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// // // CRecoOutputWnd::CRecoOutputWnd // // Constructor. // // Parameters: // none // ///////////////////////////////////////////////////////// CRecoOutputWnd::CRecoOutputWnd() : m_hRichEdit(NULL), m_iSelStart(0) { } ///////////////////////////////////////////////////////// // // CRecoOutputWnd::~CRecoOutputWnd // // Destructor. // ///////////////////////////////////////////////////////// CRecoOutputWnd::~CRecoOutputWnd() { if (NULL != m_hRichEdit) { ::FreeLibrary(m_hRichEdit); } } // Helper methods ///////////////////////////////////////////////////////// // // CRecoOutputWnd::~CRecoOutputWnd // // Destructor. // ///////////////////////////////////////////////////////// HWND CRecoOutputWnd::Create( HWND hwndParent, UINT nID ) { if (NULL == m_hWnd) { m_hRichEdit = ::LoadLibraryW(L"Riched20.dll"); if (NULL != m_hRichEdit) { // Create a richedit control HWND hwndREdit = ::CreateWindowW(RICHEDIT_CLASSW, NULL, WS_VISIBLE | WS_CHILD | WS_BORDER | ES_SUNKEN | ES_MULTILINE | ES_READONLY, 0, 0, 1, 1, hwndParent, (HMENU)nID, _Module.GetModuleInstance(), NULL ); // Subclass it and attach to this CRecoOutputWnd object if (NULL != hwndREdit) { SubclassWindow(hwndREdit); } } } return m_hWnd; } ///////////////////////////////////////////////////////// // // CRecoOutputWnd::ResetResults // // Empties the output strings. // // Parameters: none // // Return Value (void): none // ///////////////////////////////////////////////////////// void CRecoOutputWnd::ResetResults() { m_iSelStart = 0; if (IsWindow()) { // Reset the text in the RichEdit control ::SendMessage(m_hWnd, WM_SETTEXT, 0, (LPARAM)L""); } } ///////////////////////////////////////////////////////// // // CRecoOutputWnd::AddString // // Adds a recognition result string to the existing text // in the RichEdit control // // Parameters: // COLORREF clr : [in] output color for the string // BSTR bstr : [in] recognition result of a stroke collection // // Return Value (void): none // ///////////////////////////////////////////////////////// void CRecoOutputWnd::AddString( COLORREF clr, BSTR bstr ) { // Set the string start position to the end of the text m_iSelStart = ::SendMessage(m_hWnd, WM_GETTEXTLENGTH, 0, 0); // If the string is not first, add a delimiting space character first if (0 != m_iSelStart) { ::SendMessageW(m_hWnd, EM_REPLACESEL, FALSE, (LPARAM)L" "); m_iSelStart++; } // Set the string format CHARFORMAT2W cf; cf.cbSize = sizeof(cf); cf.dwMask = CFM_COLOR; cf.crTextColor = clr; cf.dwEffects = 0; ::SendMessageW(m_hWnd, EM_SETSEL, m_iSelStart, -1); ::SendMessageW(m_hWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&cf); // Add the string to the text if (NULL != bstr) { ::SendMessageW(m_hWnd, EM_REPLACESEL, FALSE, (LPARAM)bstr); } } ///////////////////////////////////////////////////////// // // CRecoOutputWnd::UpdateString // // In the RichEdit control, updates the recognition result string // of the current stroke collection // // Parameters: // BSTR bstr : [in] recognition result string // // Return Value (void): none // ///////////////////////////////////////////////////////// void CRecoOutputWnd::UpdateString( BSTR bstr ) { // To update the string, select it in the RichEdit control ... ::SendMessageW(m_hWnd, EM_SETSEL, m_iSelStart, -1); // ... and replace the selected text ::SendMessageW(m_hWnd, EM_REPLACESEL, FALSE, (LPARAM)bstr); // The new text will inherit the format settings }
29.31407
107
0.490015
[ "object" ]
b3b9c640fb43d24502c9b59b2b923d5a97bccdc7
722
cpp
C++
VNOJ/Data_Structures/Prefix_Sum/nkseq.cpp
hoanghai1803/CP_Training
03495a21509fb3ab7fc64674b9a1b0c7d4327ecb
[ "MIT" ]
4
2021-08-25T10:53:32.000Z
2021-09-30T03:25:50.000Z
VNOJ/Data_Structures/Prefix_Sum/nkseq.cpp
hoanghai1803/CP_Training
03495a21509fb3ab7fc64674b9a1b0c7d4327ecb
[ "MIT" ]
null
null
null
VNOJ/Data_Structures/Prefix_Sum/nkseq.cpp
hoanghai1803/CP_Training
03495a21509fb3ab7fc64674b9a1b0c7d4327ecb
[ "MIT" ]
null
null
null
// Author: __BruteForce__ #include <bits/stdc++.h> using namespace std; int main() { cin.tie(0)->sync_with_stdio(false); int n; cin >> n; vector<int> a(n + 1, 0); for (int i = 1; i <= n; i++) { cin >> a[i]; a[i] += a[i - 1]; } vector<bool> chk1(n + 1, false); for (int i = 1, minVal = a[n]; i <= n; i++) { chk1[i] = a[i - 1] < minVal; minVal = min(minVal, a[i] + a[n]); } vector<bool> chk2(n + 1, false); for (int i = n, minVal = a[n]; i; i--) { chk2[i] = a[i - 1] < minVal; minVal = min(minVal, a[i - 1]); } int res = 0; for (int i = 1; i <= n; i++) res += chk1[i] && chk2[i]; cout << res << "\n"; }
21.878788
49
0.432133
[ "vector" ]
b3bee11891d741e6732a21d4bc0c8f50af1d2a52
6,016
cpp
C++
Src/Geometries/TriMesh/MeshConverter.cpp
dtcxzyw/Piper
af17b45848d46687ba6c9f214264759275a35a9f
[ "MIT" ]
1
2021-12-28T14:31:28.000Z
2021-12-28T14:31:28.000Z
Src/Geometries/TriMesh/MeshConverter.cpp
dtcxzyw/Piper
af17b45848d46687ba6c9f214264759275a35a9f
[ "MIT" ]
null
null
null
Src/Geometries/TriMesh/MeshConverter.cpp
dtcxzyw/Piper
af17b45848d46687ba6c9f214264759275a35a9f
[ "MIT" ]
1
2022-02-17T08:04:05.000Z
2022-02-17T08:04:05.000Z
#include <filesystem> #include <fstream> #pragma warning(push, 0) #include <assimp/Importer.hpp> #include <assimp/postprocess.h> #include <assimp/scene.h> #include <assimp/vector3.h> #include <cxxopts.hpp> #include <lz4hc.h> #pragma warning(pop) #include "../../Shared/CommandAPI.hpp" BUS_MODULE_NAME("Piper.BuiltinGeometry.TriMesh.MeshConverter"); template <typename T> void read(const std::vector<char>& stream, uint64_t& offset, T* ptr, const size_t size = 1) { const auto rsiz = sizeof(T) * size; memcpy(static_cast<void*>(ptr), stream.data() + offset, rsiz); offset += rsiz; } template <typename T> void write(std::vector<char>& stream, const T* ptr, const size_t size = 1) { const auto begin = reinterpret_cast<const char*>(ptr); stream.insert(stream.end(), begin, begin + sizeof(T) * size); } void saveLZ4(const fs::path& path, const std::vector<char>& data) { BUS_TRACE_BEG() { std::ofstream out(path, std::ios::binary); ASSERT(out, "Failed to save LZ4 binary"); const uint64_t srcSize = data.size(); out.write(reinterpret_cast<const char*>(&srcSize), sizeof(uint64_t)); std::vector<char> res(LZ4_compressBound(static_cast<int>(data.size()))); const auto dstSize = LZ4_compress_HC(data.data(), res.data(), static_cast<int>(srcSize), static_cast<int>(res.size()), LZ4HC_CLEVEL_MAX); out.write(res.data(), dstSize); } BUS_TRACE_END(); } int cast(int argc, char** argv, Bus::Reporter& reporter) { BUS_TRACE_BEG() { cxxopts::Options opt("MeshConverter", "TriMesh::MeshConverter"); opt.add_options()("i,input", "mesh file path", cxxopts::value<fs::path>())( "o,output", "output path", cxxopts::value<fs::path>()); auto res = opt.parse(argc, argv); if(!(res.count("input") && res.count("output"))) { reporter.apply(ReportLevel::Error, "Need Arguments.", BUS_DEFSRCLOC()); reporter.apply(ReportLevel::Info, opt.help(), BUS_DEFSRCLOC()); return EXIT_FAILURE; } auto in = res["input"].as<fs::path>(); auto out = res["output"].as<fs::path>(); reporter.apply(ReportLevel::Info, fs::absolute(in).string() + "->" + fs::absolute(out).string(), BUS_DEFSRCLOC()); Assimp::Importer importer; const auto scene = importer.ReadFile( in.string(), aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType | aiProcess_GenSmoothNormals | aiProcess_GenUVCoords | aiProcess_FixInfacingNormals | aiProcess_ImproveCacheLocality); if(!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE) BUS_TRACE_THROW(std::runtime_error("Failed to load the mesh.")); if(scene->mNumMeshes != 1) BUS_TRACE_THROW(std::runtime_error("Need one mesh!!!")); reporter.apply(ReportLevel::Info, "mesh loaded.", BUS_DEFSRCLOC()); const auto mesh = scene->mMeshes[0]; reporter.apply(ReportLevel::Info, std::to_string(mesh->mNumVertices) + " vertices," + std::to_string(mesh->mNumFaces) + " faces.", BUS_DEFSRCLOC()); const aiVector3D* tangents = mesh->mTangents; std::vector<char> data{ 'm', 'e', 's', 'h' }; uint32_t flag = 0; if(mesh->HasNormals()) { flag |= 1; reporter.apply(ReportLevel::Info, "Has normals.", BUS_DEFSRCLOC()); } if(mesh->HasTextureCoords(0)) { flag |= 2; reporter.apply(ReportLevel::Info, "Has texCoords.", BUS_DEFSRCLOC()); } const uint32_t vertSize = mesh->mNumVertices; write(data, &vertSize); write(data, &flag); write(data, mesh->mVertices, vertSize); Vec3 maxp(-1e20f), minp(1e20f); for(uint32_t i = 0; i < vertSize; ++i) { Vec3 cur = *reinterpret_cast<Vec3*>(mesh->mVertices + i); maxp = glm::max(maxp, cur); minp = glm::min(minp, cur); } { std::stringstream ss; ss << "Bound: [" << minp.x << "," << minp.y << "," << minp.z << "]-[" << maxp.x << "," << maxp.y << "," << maxp.z << "]" << std::endl; reporter.apply(ReportLevel::Info, ss.str(), BUS_DEFSRCLOC()); } if(mesh->HasNormals()) write(data, mesh->mNormals, vertSize); if(mesh->HasTextureCoords(0)) { std::vector<aiVector2D> texCoords(vertSize); aiVector3D* ptr = mesh->mTextureCoords[0]; for(uint32_t i = 0; i < vertSize; ++i) texCoords[i] = aiVector2D(ptr[i].x, ptr[i].y); write(data, texCoords.data(), vertSize); } { std::vector<Uint3> buf(mesh->mNumFaces); for(auto i = 0U; i < mesh->mNumFaces; ++i) buf[i] = *reinterpret_cast<Uint3*>(mesh->mFaces[i].mIndices); const uint32_t faceSize = mesh->mNumFaces; write(data, &faceSize); write(data, buf.data(), buf.size()); } importer.FreeScene(); reporter.apply(ReportLevel::Info, "Mesh encoded.", BUS_DEFSRCLOC()); saveLZ4(out, data); reporter.apply(ReportLevel::Info, "Done.", BUS_DEFSRCLOC()); return EXIT_SUCCESS; } BUS_TRACE_END(); } class MeshConverter final : public Command { public: explicit MeshConverter(Bus::ModuleInstance& instance) : Command(instance) {} int doCommand(int argc, char** argv, Bus::ModuleSystem& sys) override { return cast(argc, argv, sys.getReporter()); } }; std::shared_ptr<Bus::ModuleFunctionBase> getMesh2Raw(Bus::ModuleInstance& instance) { return std::make_shared<MeshConverter>(instance); }
40.92517
80
0.570977
[ "mesh", "vector" ]
b3ce5835ec6ee975aa0aafa924ec560d40a77c54
525
cpp
C++
leetcode.com/1665 Minimum Initial Energy to Finish Tasks/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2020-08-20T11:02:49.000Z
2020-08-20T11:02:49.000Z
leetcode.com/1665 Minimum Initial Energy to Finish Tasks/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
null
null
null
leetcode.com/1665 Minimum Initial Energy to Finish Tasks/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2022-01-01T23:23:13.000Z
2022-01-01T23:23:13.000Z
#include <algorithm> #include <iostream> #include <vector> using namespace std; class Solution { public: int minimumEffort(vector<vector<int>>& tasks) { int res = 0; for (auto& t : tasks) res += t[0]; sort(tasks.begin(), tasks.end(), [](vector<int>& a, vector<int>& b) { return a[1] - a[0] > b[1] - b[0]; }); int remain = res; for (auto& t : tasks) { if (remain < t[1]) { res += t[1] - remain; remain = t[1]; } remain -= t[0]; } return res; } };
20.192308
73
0.510476
[ "vector" ]
b3ce60f16f8c38cd5468d2e7564a6d69033db548
1,962
cpp
C++
LeetCode/ThousandOne/0638-shopping_offers.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandOne/0638-shopping_offers.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandOne/0638-shopping_offers.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
#include "leetcode.hpp" /* 638. 大礼包 在LeetCode商店中, 有许多在售的物品。 然而,也有一些大礼包,每个大礼包以优惠的价格捆绑销售一组物品。 现给定每个物品的价格,每个大礼包包含物品的清单,以及待购物品清单。 请输出确切完成待购清单的最低花费。 每个大礼包的由一个数组中的一组数据描述,最后一个数字代表大礼包的价格,其他数字分别表示内含的其他种类物品的数量。 任意大礼包可无限次购买。 示例 1: 输入: [2,5], [[3,0,5],[1,2,10]], [3,2] 输出: 14 解释: 有A和B两种物品,价格分别为¥2和¥5。 大礼包1,你可以以¥5的价格购买3A和0B。 大礼包2, 你可以以¥10的价格购买1A和2B。 你需要购买3个A和2个B, 所以你付了¥10购买了1A和2B(大礼包2),以及¥4购买2A。 示例 2: 输入: [2,3,4], [[1,1,0,4],[2,2,1,9]], [1,2,1] 输出: 11 解释: A,B,C的价格分别为¥2,¥3,¥4. 你可以用¥4购买1A和1B,也可以用¥9购买2A,2B和1C。 你需要买1A,2B和1C,所以你付了¥4买了1A和1B(大礼包1),以及¥3购买1B, ¥4购买1C。 你不可以购买超出待购清单的物品,尽管购买大礼包2更加便宜。 说明: 最多6种物品, 100种大礼包。 每种物品,你最多只需要购买6个。 你不可以购买超出待购清单的物品,即使更便宜。 */ // 抄的 class Solution { public: int noOffers(vector<int> const& price, vector<int> const& needs, int len) { int ans = 0; for (int n = 0; n < len; n++) ans += (price[n] * needs[n]); return ans; } int helper(vector<int> const& price, vector<vector<int>> const& special, vector<int>& needs, int cost) { int nsp = static_cast<int>(special.size()); int len = static_cast<int>(price.size()); for (int n = 0; n < len; n++) { if (needs[n] < 0) return INT_MAX; } int ans = cost + noOffers(price, needs, len); for (int s = 0; s < nsp; ++s) { int const* curSpc = special[s].data(); int const cur = cost + special[s].back(); if (cur > ans) continue; for (int n = 0; n < len; n++) needs[n] -= curSpc[n]; int const next = helper(price, special, needs, cur); if (next < ans) ans = next; for (int n = 0; n < len; n++) needs[n] += curSpc[n]; } return ans; } int shoppingOffers(vector<int>& price, vector<vector<int>>& special, vector<int>& needs) { int ans = helper(price, special, needs, 0); return ans; } }; int main() { vector<int> price = { 2, 3, 4 }; vector<vector<int>> special = { { 1, 1, 0, 4 }, { 2, 2, 1, 9 } }; vector<int> needs = { 1, 2, 1 }; OutExpr( Solution().shoppingOffers(price, special, needs), "%d"); }
20.226804
67
0.621305
[ "vector" ]
b3cf05c630e2fad6643fb3f8dd93d0b22fa8da53
739
cpp
C++
test/data_structures/lazy_segment_tree.max_update.test.cpp
takata-daiki/algorithms
299f7379a2acf8a3e14bc3e3de6509e821eec115
[ "MIT" ]
null
null
null
test/data_structures/lazy_segment_tree.max_update.test.cpp
takata-daiki/algorithms
299f7379a2acf8a3e14bc3e3de6509e821eec115
[ "MIT" ]
null
null
null
test/data_structures/lazy_segment_tree.max_update.test.cpp
takata-daiki/algorithms
299f7379a2acf8a3e14bc3e3de6509e821eec115
[ "MIT" ]
1
2019-12-11T06:45:30.000Z
2019-12-11T06:45:30.000Z
#define PROBLEM "https://onlinejudge.u-aizu.ac.jp/courses/library/3/DSL/all/DSL_2_F" #include "../../data_structures/lazy_segment_tree.hpp" #include "../../monoids/max.hpp" #include "../../monoids/change.hpp" #include "../../monoids/max_change_action.hpp" #include <bits/stdc++.h> using namespace std; int main() { int n, q; cin >> n >> q; vector<int> a(n, 1 << 31 | 1); LazySegmentTree<max_monoid<int>, change_monoid<int>, max_change_action<int>> seg(begin(a), end(a)); while (q--) { int com, s, t; cin >> com >> s >> t, t++; if (com) { cout << -seg.query(s, t) << endl; } else { int x; cin >> x; seg.update(s, t, -x); } } }
28.423077
103
0.537212
[ "vector" ]
b3d47f842e17f42cef246ed71b0b37e8c9f4c56c
13,447
cpp
C++
third_party/omr/gc/base/segregated/AllocationContextSegregated.cpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/gc/base/segregated/AllocationContextSegregated.cpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/gc/base/segregated/AllocationContextSegregated.cpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright (c) 1991, 2016 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this * distribution and is available at https://www.eclipse.org/legal/epl-2.0/ * or the Apache License, Version 2.0 which accompanies this distribution and * is available at https://www.apache.org/licenses/LICENSE-2.0. * * This Source Code may also be made available under the following * Secondary Licenses when the conditions for such availability set * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU * General Public License, version 2 with the GNU Classpath * Exception [1] and GNU General Public License, version 2 with the * OpenJDK Assembly Exception [2]. * * [1] https://www.gnu.org/software/classpath/license.html * [2] http://openjdk.java.net/legal/assembly-exception.html * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception *******************************************************************************/ #include "omrcfg.h" #include "omrcomp.h" #include "omrport.h" #include <string.h> #include "AtomicOperations.hpp" #include "EnvironmentBase.hpp" #include "GCExtensionsBase.hpp" #include "HeapRegionDescriptorSegregated.hpp" #include "MemoryPoolAggregatedCellList.hpp" #include "ModronAssertions.h" #include "RegionPoolSegregated.hpp" #include "SegregatedAllocationInterface.hpp" #include "SegregatedMarkingScheme.hpp" #include "SizeClasses.hpp" #include "AllocationContextSegregated.hpp" #include "HeapRegionQueue.hpp" #if defined(OMR_GC_SEGREGATED_HEAP) #define MAX_UINT ((uintptr_t) (-1)) MM_AllocationContextSegregated * MM_AllocationContextSegregated::newInstance(MM_EnvironmentBase *env, MM_GlobalAllocationManagerSegregated *gam, MM_RegionPoolSegregated *regionPool) { MM_AllocationContextSegregated *allocCtxt = (MM_AllocationContextSegregated *)env->getForge()->allocate(sizeof(MM_AllocationContextSegregated), OMR::GC::AllocationCategory::FIXED, OMR_GET_CALLSITE()); if (allocCtxt) { new(allocCtxt) MM_AllocationContextSegregated(env, gam, regionPool); if (!allocCtxt->initialize(env)) { allocCtxt->kill(env); allocCtxt = NULL; } } return allocCtxt; } bool MM_AllocationContextSegregated::initialize(MM_EnvironmentBase *env) { memset(&_perContextSmallFullRegions[0], 0, sizeof(_perContextSmallFullRegions)); if (!MM_AllocationContext::initialize(env)) { return false; } if (0 != omrthread_monitor_init_with_name(&_mutexSmallAllocations, 0, "MM_AllocationContextSegregated small allocation monitor")) { return false; } if (0 != omrthread_monitor_init_with_name(&_mutexArrayletAllocations, 0, "MM_AllocationContextSegregated arraylet allocation monitor")) { return false; } for (int32_t i = 0; i < OMR_SIZECLASSES_NUM_SMALL + 1; i++) { _smallRegions[i] = NULL; /* the small allocation lock needs to be acquired before small full region queue can be accessed, no concurrent access should be possible */ _perContextSmallFullRegions[i] = MM_RegionPoolSegregated::allocateHeapRegionQueue(env, MM_HeapRegionList::HRL_KIND_FULL, true, false, false); if (NULL == _perContextSmallFullRegions[i]) { return false; } } /* the arraylet allocation lock needs to be acquired before arraylet full region queue can be accessed, no concurrent access should be possible */ _perContextArrayletFullRegions = MM_RegionPoolSegregated::allocateHeapRegionQueue(env, MM_HeapRegionList::HRL_KIND_FULL, true, false, false); /* no locking done in the AC level for large allocation, large full page queue _is_ accessed concurrently */ _perContextLargeFullRegions = MM_RegionPoolSegregated::allocateHeapRegionQueue(env, MM_HeapRegionList::HRL_KIND_FULL, false, true, false); if ((NULL == _perContextArrayletFullRegions ) || (NULL == _perContextLargeFullRegions)) { return false; } return true; } void MM_AllocationContextSegregated::tearDown(MM_EnvironmentBase *env) { if (_mutexSmallAllocations) { omrthread_monitor_destroy(_mutexSmallAllocations); } if (_mutexArrayletAllocations) { omrthread_monitor_destroy(_mutexArrayletAllocations); } for (int32_t i = 0; i < OMR_SIZECLASSES_NUM_SMALL + 1; i++) { if (NULL != _perContextSmallFullRegions[i]) { _perContextSmallFullRegions[i]->kill(env); _perContextSmallFullRegions[i] = NULL; } } if (NULL != _perContextArrayletFullRegions) { _perContextArrayletFullRegions->kill(env); _perContextArrayletFullRegions = NULL; } if (NULL != _perContextLargeFullRegions) { _perContextLargeFullRegions->kill(env); _perContextLargeFullRegions = NULL; } MM_AllocationContext::tearDown(env); } void MM_AllocationContextSegregated::flushSmall(MM_EnvironmentBase *env, uintptr_t sizeClass) { MM_HeapRegionDescriptorSegregated *region = _smallRegions[sizeClass]; if (region != NULL) { uintptr_t cellSize = env->getExtensions()->defaultSizeClasses->getCellSize(sizeClass); flushHelper(env, region, cellSize); } _smallRegions[sizeClass] = NULL; } void MM_AllocationContextSegregated::flushArraylet(MM_EnvironmentBase *env) { if (NULL != _arrayletRegion) { flushHelper(env, _arrayletRegion, env->getOmrVM()->_arrayletLeafSize); } _arrayletRegion = NULL; } void MM_AllocationContextSegregated::flush(MM_EnvironmentBase *env) { lockContext(); /* flush the per-context small full regions to sweep regions */ for (int32_t sizeClass = OMR_SIZECLASSES_MIN_SMALL; sizeClass <= OMR_SIZECLASSES_MAX_SMALL; sizeClass++) { flushSmall(env, sizeClass); _regionPool->getSmallSweepRegions(sizeClass)->enqueue(_perContextSmallFullRegions[sizeClass]); } /* flush the per-context large full region to sweep regions */ _regionPool->getLargeSweepRegions()->enqueue(_perContextLargeFullRegions); /* flush the per-context arraylet region to sweep regions */ flushArraylet(env); _regionPool->getArrayletSweepRegions()->enqueue(_perContextArrayletFullRegions); unlockContext(); } /** * helper function to flush the cached full regions back to the region pool * so that RegionPool::showPages can gather stats on all regions in the region pool. * This can be called during an allocation failure so context lock needs to be acquired. */ void MM_AllocationContextSegregated::returnFullRegionsToRegionPool(MM_EnvironmentBase *env) { lockContext(); for (int32_t sizeClass = OMR_SIZECLASSES_MIN_SMALL; sizeClass <= OMR_SIZECLASSES_MAX_SMALL; sizeClass++) { _regionPool->getSmallFullRegions(sizeClass)->enqueue(_perContextSmallFullRegions[sizeClass]); } _regionPool->getLargeFullRegions()->enqueue(_perContextLargeFullRegions); _regionPool->getArrayletFullRegions()->enqueue(_perContextArrayletFullRegions); unlockContext(); } void MM_AllocationContextSegregated::signalSmallRegionDepleted(MM_EnvironmentBase *env, uintptr_t sizeClass) { /* No implementation */ } bool MM_AllocationContextSegregated::tryAllocateRegionFromSmallSizeClass(MM_EnvironmentBase *env, uintptr_t sizeClass) { MM_HeapRegionDescriptorSegregated *region = _regionPool->allocateRegionFromSmallSizeClass(env, sizeClass); bool result = false; if (region != NULL) { _smallRegions[sizeClass] = region; /* cache the small full region in AC */ _perContextSmallFullRegions[sizeClass]->enqueue(region); result = true; } return result; } bool MM_AllocationContextSegregated::trySweepAndAllocateRegionFromSmallSizeClass(MM_EnvironmentBase *env, uintptr_t sizeClass, uintptr_t *sweepCount, uint64_t *sweepStartTime) { bool result = false; MM_HeapRegionDescriptorSegregated *region = _regionPool->sweepAndAllocateRegionFromSmallSizeClass(env, sizeClass); if (region != NULL) { MM_AtomicOperations::storeSync(); _smallRegions[sizeClass] = region; /* Don't update bytesAllocated because unswept regions are still considered to be in use */ result = true; } return result; } bool MM_AllocationContextSegregated::tryAllocateFromRegionPool(MM_EnvironmentBase *env, uintptr_t sizeClass) { MM_HeapRegionDescriptorSegregated *region = _regionPool->allocateFromRegionPool(env, 1, sizeClass, MAX_UINT); bool result = false; if(NULL != region) { /* cache the small full region in AC */ _perContextSmallFullRegions[sizeClass]->enqueue(region); region->formatFresh(env, sizeClass, region->getLowAddress()); /* A store barrier is required here since the initialization of the new region needs to write-back before * we make it reachable via _smallRegions (_smallRegions is accessed from outside the lock which covers this write) */ MM_AtomicOperations::storeSync(); _smallRegions[sizeClass] = region; result = true; } return result; } bool MM_AllocationContextSegregated::shouldPreMarkSmallCells(MM_EnvironmentBase *env) { return true; } /* * Pre allocate a list of cells, the amount to pre-allocate is retrieved from the env's allocation interface. * @return the carved off first cell in the list */ uintptr_t * MM_AllocationContextSegregated::preAllocateSmall(MM_EnvironmentBase *env, uintptr_t sizeInBytesRequired) { MM_SizeClasses *sizeClasses = env->getExtensions()->defaultSizeClasses; uintptr_t sizeClass = sizeClasses->getSizeClassSmall(sizeInBytesRequired); uintptr_t sweepCount = 0; uint64_t sweepStartTime = 0; bool done = false; uintptr_t *result = NULL; /* BEN TODO 1429: The object allocation interface base class should define all API used by this method such that casting would be unnecessary. */ MM_SegregatedAllocationInterface* segregatedAllocationInterface = (MM_SegregatedAllocationInterface*)env->_objectAllocationInterface; uintptr_t replenishSize = segregatedAllocationInterface->getReplenishSize(env, sizeInBytesRequired); uintptr_t preAllocatedBytes = 0; while (!done) { /* If we have a region, attempt to replenish the ACL's cache */ MM_HeapRegionDescriptorSegregated *region = _smallRegions[sizeClass]; if (NULL != region) { MM_MemoryPoolAggregatedCellList *memoryPoolACL = region->getMemoryPoolACL(); uintptr_t* cellList = memoryPoolACL->preAllocateCells(env, sizeClasses->getCellSize(sizeClass), replenishSize, &preAllocatedBytes); if (NULL != cellList) { Assert_MM_true(preAllocatedBytes > 0); if (shouldPreMarkSmallCells(env)) { _markingScheme->preMarkSmallCells(env, region, cellList, preAllocatedBytes); } segregatedAllocationInterface->replenishCache(env, sizeInBytesRequired, cellList, preAllocatedBytes); result = (uintptr_t *) segregatedAllocationInterface->allocateFromCache(env, sizeInBytesRequired); done = true; } } smallAllocationLock(); /* Either we did not have a region or we failed to preAllocate from the ACL. Retry if this is no * longer true */ region = _smallRegions[sizeClass]; if ((NULL == region) || !region->getMemoryPoolACL()->hasCell()) { /* This may cause the start of a GC */ signalSmallRegionDepleted(env, sizeClass); flushSmall(env, sizeClass); /* Attempt to get a region of this size class which may already have some allocated cells */ if (!tryAllocateRegionFromSmallSizeClass(env, sizeClass)) { /* Attempt to get a region by sweeping */ if (!trySweepAndAllocateRegionFromSmallSizeClass(env, sizeClass, &sweepCount, &sweepStartTime)) { /* Attempt to get an unused region */ if (!tryAllocateFromRegionPool(env, sizeClass)) { /* Really out of regions */ done = true; } } } } smallAllocationUnlock(); } return result; } uintptr_t * MM_AllocationContextSegregated::allocateArraylet(MM_EnvironmentBase *env, omrarrayptr_t parent) { arrayletAllocationLock(); retry: uintptr_t *arraylet = (_arrayletRegion == NULL) ? NULL : _arrayletRegion->allocateArraylet(env, parent); if (arraylet != NULL) { arrayletAllocationUnlock(); OMRZeroMemory(arraylet, env->getOmrVM()->_arrayletLeafSize); return arraylet; } flushArraylet(env); MM_HeapRegionDescriptorSegregated *region = _regionPool->allocateRegionFromArrayletSizeClass(env); if (region != NULL) { /* cache the arraylet full region in AC */ _perContextArrayletFullRegions->enqueue(region); _arrayletRegion = region; goto retry; } region = _regionPool->allocateFromRegionPool(env, 1, OMR_SIZECLASSES_ARRAYLET, MAX_UINT); if (region != NULL) { /* cache the small full region in AC */ _perContextArrayletFullRegions->enqueue(region); _arrayletRegion = region; goto retry; } arrayletAllocationUnlock(); return NULL; } /* This method is moved here so that AC can see the large full page and cache it */ uintptr_t * MM_AllocationContextSegregated::allocateLarge(MM_EnvironmentBase *env, uintptr_t sizeInBytesRequired) { uintptr_t neededRegions = _regionPool->divideUpRegion(sizeInBytesRequired); MM_HeapRegionDescriptorSegregated *region = NULL; uintptr_t excess = 0; while (region == NULL && excess < MAX_UINT) { region = _regionPool->allocateFromRegionPool(env, neededRegions, OMR_SIZECLASSES_LARGE, excess); excess = (2 * excess) + 1; } uintptr_t *result = (region == NULL) ? NULL : (uintptr_t *)region->getLowAddress(); /* Flush the large page right away. */ if (region != NULL) { /* cache the large full region in AC */ _perContextLargeFullRegions->enqueue(region); /* reset ACL counts */ region->getMemoryPoolACL()->resetCounts(); } return result; } #endif /* OMR_GC_SEGREGATED_HEAP */
34.74677
201
0.761806
[ "object" ]
b3d6c1f563d25e8a1ca04b1632061b84f6e2da48
1,555
cpp
C++
Codes/Math/Fourier2.cpp
cjtoribio/Algorithms
78499613a9b018eb5e489307b14e31e5fe8227e3
[ "MIT" ]
18
2015-05-24T20:28:46.000Z
2021-01-27T02:34:43.000Z
Codes/Math/Fourier2.cpp
cjtoribio/Algorithms
78499613a9b018eb5e489307b14e31e5fe8227e3
[ "MIT" ]
null
null
null
Codes/Math/Fourier2.cpp
cjtoribio/Algorithms
78499613a9b018eb5e489307b14e31e5fe8227e3
[ "MIT" ]
4
2015-05-24T20:28:32.000Z
2021-01-30T04:04:55.000Z
namespace Fourier { #define lowbit(x) (((x) ^ (x-1)) & (x)) typedef complex<long double> Complex; void FFT(vector<Complex> &A, int s){ int n = A.size(); int p = __builtin_ctz(n); vector<Complex> a = A; for(int i = 0;i<n;++i){ int rev = 0; for(int j = 0;j<p;++j){ rev <<= 1; rev |= ((i >> j) & 1); } A[i] = a[rev]; } Complex w,wn; for(int i = 1;i<=p;++i){ int M = (1<<i), K = (M>>1); wn = Complex(cos(s*2.0*M_PI/(long double)M), sin(s*2.0*M_PI/(long double)M)); for(int j = 0;j<n;j += M){ w = Complex(1.0, 0.0); for(int l = j;l<K+j;++l){ Complex t = w; t *= A[l + K]; Complex u = A[l]; A[l] += t; u -= t; A[l + K] = u; w *= wn; } } } if(s==-1){ for(int i = 0;i<n;++i) A[i] /= (long double)n; } } vector<Complex> FFT_Multiply(vector<Complex> &P, vector<Complex> &Q){ int n = P.size()+Q.size(); while(n!=lowbit(n)) n += lowbit(n); P.resize(n,0); Q.resize(n,0); FFT(P,1); FFT(Q,1); vector<Complex> R; for(int i=0;i<n;i++) R.push_back(P[i]*Q[i]); FFT(R,-1); return R; } vector<Long> FFT_Multiply(vector<Long> &A, vector<Long> &B){ vector<Complex> AF(A.size()); for(int i = 0; i < A.size(); ++i){ AF[i] = Complex(A[i], 0); } vector<Complex> BF(B.size()); for(int i = 0; i < B.size(); ++i){ BF[i] = Complex(B[i], 0); } vector<Complex> CF = FFT_Multiply(AF,BF); vector<Long> C; for (int i = 0; i < CF.size(); ++i) { C.push_back(CF[i].real()+0.1); } return C; } }
19.935897
80
0.480386
[ "vector" ]
b3db0bb2565a760d1a8391c94bc7c3cbbc9ea4d6
1,653
cpp
C++
training/1-5-3-pprime/cpp11/main.cpp
hsun324/usaco-solutions
27f77911971513a4d2b1b820eaa09802acadfefa
[ "MIT" ]
2
2015-12-26T21:20:12.000Z
2017-12-19T00:11:45.000Z
training/1-5-3-pprime/cpp11/main.cpp
hsun324/usaco-solutions
27f77911971513a4d2b1b820eaa09802acadfefa
[ "MIT" ]
null
null
null
training/1-5-3-pprime/cpp11/main.cpp
hsun324/usaco-solutions
27f77911971513a4d2b1b820eaa09802acadfefa
[ "MIT" ]
null
null
null
/** ID: <ID HERE> LANG: C++11 TASK: pprime */ #include <iostream> #include <fstream> #include <set> #include <map> #include <cmath> #include <vector> using namespace std; bool is_prime(int num) { int max = (int) sqrt(num); for (int i = 2; i <= max; i++) if (num % i == 0) return false; return true; } void generate1(set<int> &dest) { for (int i = 1; i <= 9; i += 2) dest.insert(i); } void generate2(set<int> &dest) { } void generate3(set<int> &dest) { for (int i = 0; i <= 9; i++) for (int j = 1; j <= 9; j += 2) dest.insert(101 * j + 10 * i); } void generate5(set<int> &dest) { for (int i = 0; i <= 9; i++) for (int j = 0; j <= 9; j++) for (int k = 1; k <= 9; k += 2) dest.insert(10001 * k + 1010 * j + 100 * i); } void generate7(set<int> &dest) { for (int i = 0; i <= 9; i++) for (int j = 0; j <= 9; j++) for (int k = 0; k <= 9; k++) for (int l = 1; l <= 9; l += 2) dest.insert(1000001 * l + 100010 * k + 10100 * j + 1000 * i); } set<int> generate() { set<int> palindromes; palindromes.insert(11); // 11 is the only even-length prime palindrome generate1(palindromes); generate3(palindromes); generate5(palindromes); generate7(palindromes); return palindromes; } int main() { ifstream cin("pprime.in"); ofstream cout("pprime.out"); int min, max; cin >> min >> max; set<int> palindromes = generate(); set<int> results; auto end = palindromes.upper_bound(max); for (auto iter = palindromes.lower_bound(min); iter != end; ++iter) { if (*iter >= min && *iter <= max && is_prime(*iter)) results.insert(*iter); } for (int result : results) cout << result << endl; return 0; }
19.915663
71
0.580157
[ "vector" ]
b3e09009f84b21c258ebd725fcc904993e9b969c
1,364
cpp
C++
leetcode-algorithms/035. Search Insert Position/35.search-insert-position.cpp
cnyy7/LeetCode_EY
44e92f102b61f5e931e66081ed6636d7ecbdefd4
[ "MIT" ]
null
null
null
leetcode-algorithms/035. Search Insert Position/35.search-insert-position.cpp
cnyy7/LeetCode_EY
44e92f102b61f5e931e66081ed6636d7ecbdefd4
[ "MIT" ]
null
null
null
leetcode-algorithms/035. Search Insert Position/35.search-insert-position.cpp
cnyy7/LeetCode_EY
44e92f102b61f5e931e66081ed6636d7ecbdefd4
[ "MIT" ]
null
null
null
/* * @lc app=leetcode id=35 lang=cpp * * [35] Search Insert Position * * https://leetcode.com/problems/search-insert-position/description/ * * algorithms * Easy (40.48%) * Total Accepted: 381.4K * Total Submissions: 938.6K * Testcase Example: '[1,3,5,6]\n5' * * Given a sorted array and a target value, return the index if the target is * found. If not, return the index where it would be if it were inserted in * order. * * You may assume no duplicates in the array. * * Example 1: * * * Input: [1,3,5,6], 5 * Output: 2 * * * Example 2: * * * Input: [1,3,5,6], 2 * Output: 1 * * * Example 3: * * * Input: [1,3,5,6], 7 * Output: 4 * * * Example 4: * * * Input: [1,3,5,6], 0 * Output: 0 * * */ class Solution { public: int searchInsert(vector<int> &nums, int target) { int low = 0, high = nums.size() - 1; int mid; while (low <= high) { mid = (low + high) / 2; if (nums[mid] == target) { return mid; } else if (nums[mid] > target) { high = mid - 1; } else { low = mid + 1; } } return low; } };
18.186667
78
0.446481
[ "vector" ]
b3e69eecd02f7f37b27728c05d6a61344831caf8
2,736
cpp
C++
Samples/Win7Samples/netds/upnp/dco_dimmerservice/DeviceDll.cpp
windows-development/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
8
2017-04-30T17:38:27.000Z
2021-11-29T00:59:03.000Z
Samples/Win7Samples/netds/upnp/dco_dimmerservice/DeviceDll.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
null
null
null
Samples/Win7Samples/netds/upnp/dco_dimmerservice/DeviceDll.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
2
2020-08-11T13:21:49.000Z
2021-09-01T10:41:51.000Z
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved // // DeviceDll.cpp : Implementation of DLL Exports from DeviceDll.def #include <stdio.h> #include <atlbase.h> #include "DeviceDll.h" //object that implements the COM Server CComModule _Module; #include <atlcom.h> //has the Macro BEGIN_OBJECT_MAP etc. #include <objbase.h> #include <upnphost.h> #include "resource.h" #include "dimmerdevice.h" #include "DimmerService.h" #include "DimmerDeviceDCO.h" BEGIN_OBJECT_MAP(ObjectMap) OBJECT_ENTRY(CLSID_UPNPSampleDimmerDevice, UPNPDimmerDevice) END_OBJECT_MAP() ///////////////////////////////////////////////////////////////////////////// // DLL Entry Point ///////////////////////////////////////////////////////////////////////////// extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/) { if (dwReason == DLL_PROCESS_ATTACH) { _Module.Init(ObjectMap, hInstance); DisableThreadLibraryCalls(hInstance); } else if (dwReason == DLL_PROCESS_DETACH) _Module.Term(); return TRUE; // ok } ///////////////////////////////////////////////////////////////////////////// // Used to determine whether the DLL can be unloaded by OLE ///////////////////////////////////////////////////////////////////////////// STDAPI DllCanUnloadNow(void) { return (_Module.GetLockCount()==0) ? S_OK : S_FALSE; } ///////////////////////////////////////////////////////////////////////////// // Returns a class factory to create an object of the requested type ///////////////////////////////////////////////////////////////////////////// STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) { return _Module.GetClassObject(rclsid, riid, ppv); } ///////////////////////////////////////////////////////////////////////////// // DllRegisterServer - Adds entries to the system registry ///////////////////////////////////////////////////////////////////////////// STDAPI DllRegisterServer(void) { // registers object, typelib and all interfaces in typelib return _Module.RegisterServer(TRUE); } ///////////////////////////////////////////////////////////////////////////// // DllUnregisterServer - Removes entries from the system registry //////////////////////////////////////////////////////////////////////////// STDAPI DllUnregisterServer(void) { return _Module.UnregisterServer(FALSE); }
29.419355
80
0.504386
[ "object" ]
b3e824ae0222e0008605fa2af86e76e7535f54d3
417
cpp
C++
test/RecordingListener.cpp
jeffkilpatrick/thermocouple
fb433e46706543cce76402cfbce7c63df2790cda
[ "MIT" ]
null
null
null
test/RecordingListener.cpp
jeffkilpatrick/thermocouple
fb433e46706543cce76402cfbce7c63df2790cda
[ "MIT" ]
15
2019-06-02T21:09:40.000Z
2019-06-08T20:44:32.000Z
test/RecordingListener.cpp
jeffkilpatrick/thermocouple
fb433e46706543cce76402cfbce7c63df2790cda
[ "MIT" ]
null
null
null
// // RecordingListener.cpp // Thermocouple // // Created by Jeff Kilpatrick on 11/30/14. // Copyright (c) 2014 Jeff Kilpatrick. All rights reserved. // #include "RecordingListener.h" void RecordingListener::Notify(float celsius) { m_values.emplace_back(std::chrono::system_clock::now(), celsius); } const std::vector<RecordingListener::Value>& RecordingListener::GetValues() const { return m_values; }
19.857143
69
0.729017
[ "vector" ]
b3e86619ecfb0b4a5a817420c043ebb3889eda63
8,151
cpp
C++
ut/source/test_r_disco.cpp
TroyDL/revere
541bdc2bed9db212c1b74414b24733cf39675d08
[ "BSD-3-Clause" ]
null
null
null
ut/source/test_r_disco.cpp
TroyDL/revere
541bdc2bed9db212c1b74414b24733cf39675d08
[ "BSD-3-Clause" ]
null
null
null
ut/source/test_r_disco.cpp
TroyDL/revere
541bdc2bed9db212c1b74414b24733cf39675d08
[ "BSD-3-Clause" ]
null
null
null
#include "test_r_disco.h" #include "utils.h" #include "r_pipeline/r_gst_source.h" #include "r_pipeline/r_arg.h" #include "r_pipeline/r_stream_info.h" #include "r_fakey/r_fake_camera.h" #include "r_utils/r_string_utils.h" #include "r_utils/r_work_q.h" #include "r_utils/r_std_utils.h" #include "r_utils/r_file.h" #include "r_disco/r_agent.h" #include "r_disco/r_devices.h" #include <sys/types.h> #include <thread> #include <vector> #include <functional> #include <algorithm> #include <iterator> #include <utility> #include <tuple> #ifdef IS_WINDOWS #include <Windows.h> #include <tchar.h> #include <stdio.h> #include <strsafe.h> #pragma warning( push ) #pragma warning( disable : 4244 ) #endif #include <gst/gst.h> #ifdef IS_WINDOWS #pragma warning( pop ) #endif #ifdef IS_LINUX #include <dirent.h> #endif using namespace std; using namespace r_pipeline; using namespace r_fakey; using namespace r_utils; REGISTER_TEST_FIXTURE(test_r_disco); using namespace r_disco; void test_r_disco::setup() { gst_init(NULL, NULL); teardown(); r_fs::mkdir("top_dir"); r_fs::mkdir("top_dir" + r_fs::PATH_SLASH + "config"); r_fs::mkdir("top_dir" + r_fs::PATH_SLASH + "db"); } void test_r_disco::teardown() { auto cfg_json_path = "top_dir" + r_fs::PATH_SLASH + "config" + r_fs::PATH_SLASH + "manual_config.json"; if(r_fs::file_exists(cfg_json_path)) r_fs::remove_file(cfg_json_path); auto cfg_path = "top_dir" + r_fs::PATH_SLASH + "config"; if(r_fs::file_exists(cfg_path)) r_fs::rmdir(cfg_path); if(r_fs::file_exists("top_dir" + r_fs::PATH_SLASH + "db" + r_fs::PATH_SLASH + "cameras.db")) r_fs::remove_file("top_dir" + r_fs::PATH_SLASH + "db" + r_fs::PATH_SLASH + "cameras.db"); if(r_fs::file_exists("top_dir" + r_fs::PATH_SLASH + "db")) r_fs::rmdir("top_dir" + r_fs::PATH_SLASH + "db"); if(r_fs::file_exists("top_dir")) r_fs::rmdir("top_dir"); } void test_r_disco::test_r_disco_r_agent_start_stop() { int port = RTF_NEXT_PORT(); auto fc = _create_fc(port, "root", "1234"); auto fct = thread([&](){ fc->start(); }); r_agent agent("top_dir"); agent.start(); this_thread::sleep_for(chrono::milliseconds(5000)); agent.stop(); fc->quit(); fct.join(); } vector<pair<r_stream_config, string>> _fake_stream_configs() { vector<pair<r_stream_config, string>> configs; r_stream_config cfg; cfg.id = "93950da6-fc12-493c-a051-c22a9fec3440"; cfg.camera_name = "fake_cam1"; cfg.ipv4 = "127.0.0.1"; cfg.rtsp_url = "rtsp://url"; cfg.video_codec = "h264"; cfg.video_timebase = 90000; cfg.audio_codec = "mp4a-latm"; cfg.audio_timebase = 48000; configs.push_back(make_pair(cfg, hash_stream_config(cfg))); cfg.id = "27d0f031-da8d-41a0-9687-5fd689a78bec"; cfg.camera_name = "fake_cam2"; cfg.ipv4 = "127.0.0.1"; cfg.rtsp_url = "rtsp://url"; cfg.video_codec = "h265"; cfg.video_timebase = 90000; cfg.audio_codec = "pcmu"; cfg.audio_timebase = 8000; configs.push_back(make_pair(cfg, hash_stream_config(cfg))); cfg.id = "fae9db8f-08a5-48b7-a22d-1c19a0c05c4f"; cfg.camera_name = "fake_cam3"; cfg.ipv4 = "127.0.0.1"; cfg.rtsp_url = "rtsp://url"; cfg.video_codec = "h265"; cfg.video_codec_parameters = "foo=bar"; cfg.video_timebase = 90000; cfg.audio_codec = "mp4a-latm"; cfg.audio_codec_parameters = "foo=bar"; cfg.audio_timebase = 8000; configs.push_back(make_pair(cfg, hash_stream_config(cfg))); return configs; } void test_r_disco::test_r_disco_r_devices_basic() { r_devices devices("top_dir"); devices.start(); devices.insert_or_update_devices(_fake_stream_configs()); auto all_cameras = devices.get_all_cameras(); RTF_ASSERT(all_cameras.size() == 3); RTF_ASSERT(all_cameras[0].id == "93950da6-fc12-493c-a051-c22a9fec3440"); RTF_ASSERT(all_cameras[0].camera_name == "fake_cam1"); RTF_ASSERT(all_cameras[0].state == "discovered"); RTF_ASSERT(all_cameras[1].id == "27d0f031-da8d-41a0-9687-5fd689a78bec"); RTF_ASSERT(all_cameras[1].camera_name == "fake_cam2"); RTF_ASSERT(all_cameras[1].state == "discovered"); all_cameras[1].rtsp_username = "root"; all_cameras[1].rtsp_password = "1234"; all_cameras[1].state = "assigned"; devices.save_camera(all_cameras[1]); auto all_assigned_cameras = devices.get_assigned_cameras(); RTF_ASSERT(all_assigned_cameras.size() == 1); RTF_ASSERT(all_assigned_cameras[0].id == "27d0f031-da8d-41a0-9687-5fd689a78bec"); RTF_ASSERT(all_assigned_cameras[0].camera_name == "fake_cam2"); RTF_ASSERT(all_assigned_cameras[0].state == "assigned"); RTF_ASSERT(all_assigned_cameras[0].rtsp_username == "root"); RTF_ASSERT(all_assigned_cameras[0].rtsp_password == "1234"); devices.stop(); } void test_r_disco::test_r_disco_r_devices_modified() { // Note: this test is simulating the behavior of a camera CHANGING to rtsp_url. This is not // something an application using r_disco would do. r_devices devices("top_dir"); devices.start(); devices.insert_or_update_devices(_fake_stream_configs()); auto all_before = devices.get_all_cameras(); all_before[1].rtsp_url = "rtsp://new_url"; devices.save_camera(all_before[1]); auto modified = devices.get_modified_cameras(all_before); RTF_ASSERT(modified.size() == 1); RTF_ASSERT(modified[0].id == "27d0f031-da8d-41a0-9687-5fd689a78bec"); all_before = devices.get_all_cameras(); // now, save without modifying anything... devices.save_camera(all_before[1]); modified = devices.get_modified_cameras(all_before); RTF_ASSERT(modified.size() == 0); } void test_r_disco::test_r_disco_r_devices_assigned_cameras_added() { r_devices devices("top_dir"); devices.start(); devices.insert_or_update_devices(_fake_stream_configs()); auto all_before = devices.get_all_cameras(); vector<pair<r_stream_config, string>> configs; r_stream_config cfg; cfg.id = "9d807570-3d0e-4f87-9773-ae8d6471eab6"; cfg.ipv4 = "127.0.0.1"; cfg.rtsp_url = "rtsp://url"; cfg.video_codec = "h265"; cfg.video_timebase = 90000; cfg.audio_codec = "aac"; cfg.audio_timebase = 48000; configs.push_back(make_pair(cfg, hash_stream_config(cfg))); devices.insert_or_update_devices(configs); auto c = devices.get_camera_by_id("9d807570-3d0e-4f87-9773-ae8d6471eab6").value(); c.state = "assigned"; devices.save_camera(c); auto assigned_added = devices.get_assigned_cameras_added(all_before); RTF_ASSERT(assigned_added.size() == 1); RTF_ASSERT(assigned_added.front().id == "9d807570-3d0e-4f87-9773-ae8d6471eab6"); auto all_after = devices.get_all_cameras(); assigned_added = devices.get_assigned_cameras_added(all_after); RTF_ASSERT(assigned_added.size() == 0); } void test_r_disco::test_r_disco_r_devices_assigned_cameras_removed() { r_devices devices("top_dir"); devices.start(); devices.insert_or_update_devices(_fake_stream_configs()); auto all_before = devices.get_all_cameras(); vector<pair<r_stream_config, string>> configs; r_stream_config cfg; cfg.id = "9d807570-3d0e-4f87-9773-ae8d6471eab6"; cfg.ipv4 = "127.0.0.1"; cfg.rtsp_url = "rtsp://url"; cfg.video_codec = "h265"; cfg.video_timebase = 90000; cfg.audio_codec = "aac"; cfg.audio_timebase = 48000; configs.push_back(make_pair(cfg, hash_stream_config(cfg))); devices.insert_or_update_devices(configs); auto c = devices.get_camera_by_id("9d807570-3d0e-4f87-9773-ae8d6471eab6").value(); c.state = "assigned"; devices.save_camera(c); auto assigned_before = devices.get_assigned_cameras(); RTF_ASSERT(assigned_before.size() == 1); devices.remove_camera(c); auto removed = devices.get_assigned_cameras_removed(assigned_before); RTF_ASSERT(removed.size() == 1); RTF_ASSERT(removed.front().id == "9d807570-3d0e-4f87-9773-ae8d6471eab6"); auto assigned_after = devices.get_assigned_cameras(); RTF_ASSERT(assigned_after.size() == 0); }
28.400697
107
0.697092
[ "vector" ]
b3eeadc3b82370dfca59b5dd346e5dcc10dc4c33
3,137
hh
C++
src/lib/MeshFEM/Utilities/NameMangling.hh
pbedenbaugh/MeshFEM
742d609d4851582ffb9c5616774fc2ef489e2f88
[ "MIT" ]
19
2020-10-21T10:05:17.000Z
2022-03-20T13:41:50.000Z
src/lib/MeshFEM/Utilities/NameMangling.hh
pbedenbaugh/MeshFEM
742d609d4851582ffb9c5616774fc2ef489e2f88
[ "MIT" ]
4
2021-01-01T15:58:15.000Z
2021-09-19T03:31:09.000Z
src/lib/MeshFEM/Utilities/NameMangling.hh
pbedenbaugh/MeshFEM
742d609d4851582ffb9c5616774fc2ef489e2f88
[ "MIT" ]
4
2020-10-05T09:01:50.000Z
2022-01-11T03:02:39.000Z
//////////////////////////////////////////////////////////////////////////////// // NameMangling.hh //////////////////////////////////////////////////////////////////////////////// /*! @file // Provides mangled names needed, e.g., for generating python bindings for // template instantiations */ //////////////////////////////////////////////////////////////////////////////// #ifndef NAME_MANGLING_HH #define NAME_MANGLING_HH #include <string> #include <array> template<typename _Real> std::string floatingPointTypeSuffix() { if (std::is_same<_Real, double>::value) return ""; if (std::is_same<_Real, long double>::value) return "_long_double"; if (std::is_same<_Real, float>::value) return "_float"; throw std::runtime_error("Unrecognized floating point type"); } template<size_t _K, size_t _Degree, class _EmbeddingSpace> std::string getFEMName() { std::array<std::string, 2> degreeNames{{"Linear", "Quadratic"}}; std::array<std::string, 2> simplexNames{{"Tri", "Tet"}}; std::string dimName = std::to_string(_EmbeddingSpace::RowsAtCompileTime); return degreeNames.at(_Degree - 1) + dimName + "D" + simplexNames.at(_K - 2); } template<class _Mesh> std::string getMeshName() { using _Real = typename _Mesh::Real; return getFEMName<_Mesh::K, _Mesh::Deg, typename _Mesh::EmbeddingSpace>() + "Mesh" + floatingPointTypeSuffix<_Real>(); } template<size_t _Dimension> std::string getElasticityTensorName() { return "ElasticityTensor" + std::to_string(_Dimension) + "D"; } //////////////////////////////////////////////////////////////////////////////// // More convenient unified interface based on template spcialization. // Use forward declarations of the templates for which we specialize to avoid // increasing compilation time. //////////////////////////////////////////////////////////////////////////////// template<typename T> struct NameMangler; // FEMMesh template<size_t _K, size_t _Deg, class EmbeddingSpace, template <size_t, size_t, class> class _FEMData> class FEMMesh; template<size_t _K, size_t _Degree, class _EmbeddingSpace, template <size_t, size_t, class> class _FEMData> struct NameMangler<FEMMesh<_K, _Degree, _EmbeddingSpace, _FEMData>> { static std::string name() { return getFEMName<_K, _Degree, _EmbeddingSpace>() + "Mesh" + floatingPointTypeSuffix<typename _EmbeddingSpace::Scalar>(); } }; // ElasticityTensor template<typename _Real, size_t _Dim, bool _MajorSymmetry> class ElasticityTensor; template<typename _Real, size_t _Dim, bool _MajorSymmetry> struct NameMangler<ElasticityTensor<_Real, _Dim, _MajorSymmetry>> { static std::string name() { return getElasticityTensorName<_Dim>() + floatingPointTypeSuffix<_Real>(); } }; // SymmetricMatrix template<size_t t_N, typename Storage> class SymmetricMatrix; template<size_t t_N, typename Storage> struct NameMangler<SymmetricMatrix<t_N, Storage>> { static std::string name() { return "SymmetricMatrix" + std::to_string(t_N) + "D" + floatingPointTypeSuffix<typename Storage::Scalar>(); } }; #endif /* end of include guard: NAME_MANGLING_HH */
36.057471
129
0.636914
[ "mesh" ]
b3f49023708802134203e7b09a25893df4c01afe
804
cpp
C++
Homework/2. HW/3/Truck.cpp
Ignatoff/FMI-OOP-2018
a84c250e4b6d2df3135708a2fbe0447b9533858a
[ "MIT" ]
3
2018-03-20T18:28:53.000Z
2018-06-06T17:29:13.000Z
Homework/2. HW/3/Truck.cpp
Ignatoff/FMI-OOP-2018
a84c250e4b6d2df3135708a2fbe0447b9533858a
[ "MIT" ]
null
null
null
Homework/2. HW/3/Truck.cpp
Ignatoff/FMI-OOP-2018
a84c250e4b6d2df3135708a2fbe0447b9533858a
[ "MIT" ]
null
null
null
#include "Truck.h" #include <iostream> Truck::Truck() : Vehicle(), size(0) { } Truck::Truck(const Truck & rhs) : Vehicle(rhs), size(rhs.size) {} Truck::Truck(const char *make, const char *model, const char *color, const int &year, const int &mileage, const int& size) : Vehicle(make, model, color, year, mileage) { this->size = size; } Truck & Truck::operator=(const Truck & rhs) { Vehicle::operator=(rhs); if (this != &rhs) { size = rhs.size; } return *this; } Truck::~Truck() {} void Truck::details() const { std::cout << "Make: " << getMake() << '\n'; std::cout << "Model: " << getModel() << '\n'; std::cout << "Color: " << getColor() << '\n'; std::cout << "Year: " << getYear() << '\n'; std::cout << "Mileage: " << getMileage() << '\n'; std::cout << "Size:" << size << "\n\n"; }
22.971429
167
0.572139
[ "model" ]
b3fd00ddf595ce9b66394e30bb5ef0f3b5df66a5
12,992
cpp
C++
apps/ospTestSuite/test_fixture.cpp
tribal-tec/ospray
31ea9d16f8551c06551a11d54fe908d9d004a767
[ "Apache-2.0" ]
null
null
null
apps/ospTestSuite/test_fixture.cpp
tribal-tec/ospray
31ea9d16f8551c06551a11d54fe908d9d004a767
[ "Apache-2.0" ]
null
null
null
apps/ospTestSuite/test_fixture.cpp
tribal-tec/ospray
31ea9d16f8551c06551a11d54fe908d9d004a767
[ "Apache-2.0" ]
null
null
null
// Copyright 2017-2019 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #include "test_fixture.h" #include "ArcballCamera.h" // ospray_testing #include "ospray_testing.h" // ospcommon #include "ospcommon/utility/multidim_index_sequence.h" extern OSPRayEnvironment *ospEnv; namespace OSPRayTestScenes { // Helper functions ///////////////////////////////////////////////////////// // creates a torus // volumetric data: stores data of torus // returns created ospvolume of torus static cpp::Volume CreateTorus(const int size) { std::vector<float> volumetricData(size * size * size, 0); const float r = 30; const float R = 80; const int size_2 = size / 2; for (int x = 0; x < size; ++x) { for (int y = 0; y < size; ++y) { for (int z = 0; z < size; ++z) { const float X = x - size_2; const float Y = y - size_2; const float Z = z - size_2; const float d = (R - std::sqrt(X * X + Y * Y)); volumetricData[size * size * x + size * y + z] = r * r - d * d - Z * Z; } } } cpp::Volume torus("structured_regular"); torus.setParam("data", cpp::Data(vec3ul(size), volumetricData.data())); torus.setParam("gridOrigin", vec3f(-0.5f, -0.5f, -0.5f)); torus.setParam("gridSpacing", vec3f(1.f / size, 1.f / size, 1.f / size)); return torus; } ///////////////////////////////////////////////////////////////////////////// Base::Base() { const ::testing::TestCase *const testCase = ::testing::UnitTest::GetInstance()->current_test_case(); const ::testing::TestInfo *const testInfo = ::testing::UnitTest::GetInstance()->current_test_info(); imgSize = ospEnv->GetImgSize(); framebuffer = cpp::FrameBuffer( imgSize, frameBufferFormat, OSP_FB_COLOR | OSP_FB_ACCUM | OSP_FB_DEPTH); { std::string testCaseName = testCase->name(); std::string testInfoName = testInfo->name(); size_t pos = testCaseName.find('/'); if (pos == std::string::npos) { testName = testCaseName + "_" + testInfoName; } else { std::string instantiationName = testCaseName.substr(0, pos); std::string className = testCaseName.substr(pos + 1); testName = className + "_" + instantiationName + "_" + testInfoName; } for (char &byte : testName) if (byte == '/') byte = '_'; } rendererType = "scivis"; frames = 1; samplesPerPixel = 16; imageTool.reset(new OSPImageTools(imgSize, GetTestName(), frameBufferFormat)); } void Base::SetUp() { CreateEmptyScene(); } void Base::AddLight(cpp::Light light) { light.commit(); lightsList.push_back(light); } void Base::AddModel(cpp::GeometricModel model, affine3f xfm) { model.commit(); cpp::Group group; group.setParam("geometry", cpp::Data(model)); group.commit(); cpp::Instance instance(group); instance.setParam("xfm", xfm); AddInstance(instance); } void Base::AddModel(cpp::VolumetricModel model, affine3f xfm) { model.commit(); cpp::Group group; group.setParam("volume", cpp::Data(model)); group.commit(); cpp::Instance instance(group); instance.setParam("xfm", xfm); AddInstance(instance); } void Base::AddInstance(cpp::Instance instance) { instance.commit(); instances.push_back(instance); } void Base::PerformRenderTest() { SetLights(); if (!instances.empty()) world.setParam("instance", cpp::Data(instances)); camera.commit(); world.commit(); renderer.commit(); framebuffer.resetAccumulation(); RenderFrame(); auto *framebuffer_data = (uint32_t *)framebuffer.map(OSP_FB_COLOR); if (ospEnv->GetDumpImg()) { EXPECT_EQ(imageTool->saveTestImage(framebuffer_data), OsprayStatus::Ok); } else { EXPECT_EQ( imageTool->compareImgWithBaseline(framebuffer_data), OsprayStatus::Ok); } framebuffer.unmap(framebuffer_data); } void Base::CreateEmptyScene() { camera = cpp::Camera("perspective"); camera.setParam("aspect", imgSize.x / (float)imgSize.y); camera.setParam("position", vec3f(0.f)); camera.setParam("direction", vec3f(0.f, 0.f, 1.f)); camera.setParam("up", vec3f(0.f, 1.f, 0.f)); renderer = cpp::Renderer(rendererType); if (rendererType == "scivis") renderer.setParam("aoSamples", 0); renderer.setParam("backgroundColor", vec3f(1.0f)); renderer.setParam("pixelSamples", samplesPerPixel); world = cpp::World(); } void Base::SetLights() { if (!lightsList.empty()) world.setParam("light", cpp::Data(lightsList)); } void Base::RenderFrame() { for (int frame = 0; frame < frames; ++frame) framebuffer.renderFrame(renderer, camera, world); } SpherePrecision::SpherePrecision() { auto params = GetParam(); radius = std::get<0>(params); dist = std::get<1>(params) * radius; move_cam = std::get<2>(params); rendererType = std::get<3>(params); } void SpherePrecision::SetUp() { Base::SetUp(); float fov = 160.0f * std::min(std::tan(radius / std::abs(dist)), 1.0f); float cent = move_cam ? 0.0f : dist + radius; camera.setParam( "position", vec3f(0.f, 0.f, move_cam ? -dist - radius : 0.0f)); camera.setParam("direction", vec3f(0.f, 0.f, 1.f)); camera.setParam("up", vec3f(0.f, 1.f, 0.f)); camera.setParam("fovy", fov); renderer.setParam("pixelSamples", 16); renderer.setParam("backgroundColor", vec4f(0.2f, 0.2f, 0.4f, 1.0f)); if (rendererType == "scivis") { renderer.setParam("aoSamples", 16); renderer.setParam("aoIntensity", 1.f); } else if (rendererType == "pathtracer") { renderer.setParam("maxPathLength", 2); } cpp::Geometry sphere("sphere"); cpp::Geometry inst_sphere("sphere"); std::vector<vec3f> sph_center = {vec3f(-0.5f * radius, -0.3f * radius, cent), vec3f(0.8f * radius, -0.3f * radius, cent), vec3f(0.8f * radius, 1.5f * radius, cent), vec3f(0.0f, -10001.3f * radius, cent)}; std::vector<float> sph_radius = { radius, 0.9f * radius, 0.9f * radius, 10000.f * radius}; sphere.setParam("sphere.position", cpp::Data(sph_center)); sphere.setParam("sphere.radius", cpp::Data(sph_radius)); sphere.commit(); inst_sphere.setParam("sphere.position", cpp::Data(vec3f(0.f))); inst_sphere.setParam("sphere.radius", cpp::Data(90.f * radius)); inst_sphere.commit(); cpp::GeometricModel model1(sphere); cpp::GeometricModel model2(inst_sphere); cpp::Material sphereMaterial(rendererType, "obj"); sphereMaterial.setParam("d", 1.0f); sphereMaterial.commit(); model1.setParam("material", sphereMaterial); model2.setParam("material", sphereMaterial); affine3f xfm(vec3f(0.01, 0, 0), vec3f(0, 0.01, 0), vec3f(0, 0, 0.01), vec3f(-0.5f * radius, 1.6f * radius, cent)); AddModel(model1); AddModel(model2, xfm); cpp::Light distant("distant"); distant.setParam("intensity", 3.0f); distant.setParam("direction", vec3f(0.3f, -4.0f, 0.8f)); distant.setParam("color", vec3f(1.0f, 0.5f, 0.5f)); distant.setParam("angularDiameter", 1.0f); AddLight(distant); cpp::Light ambient = ospNewLight("ambient"); ambient.setParam("intensity", 0.1f); AddLight(ambient); } TextureVolume::TextureVolume() { rendererType = GetParam(); } void TextureVolume::SetUp() { Base::SetUp(); camera.setParam("position", vec3f(-0.7f, -1.4f, 0.f)); camera.setParam("direction", vec3f(0.5f, 1.f, 0.f)); camera.setParam("up", vec3f(0.f, 0.f, -1.f)); cpp::Volume torus = CreateTorus(256); torus.commit(); cpp::VolumetricModel volumetricModel(torus); cpp::TransferFunction transferFun("piecewiseLinear"); transferFun.setParam("valueRange", vec2f(-10000.f, 10000.f)); std::vector<vec3f> colors = { vec3f(1.0f, 0.0f, 0.0f), vec3f(0.0f, 1.0f, 0.0f)}; std::vector<float> opacities = {1.0f, 1.0f}; transferFun.setParam("color", cpp::Data(colors)); transferFun.setParam("opacity", cpp::Data(opacities)); transferFun.commit(); volumetricModel.setParam("transferFunction", transferFun); volumetricModel.commit(); cpp::Texture tex("volume"); tex.setParam("volume", volumetricModel); tex.commit(); cpp::Material sphereMaterial(rendererType, "obj"); sphereMaterial.setParam("map_kd", tex); sphereMaterial.commit(); cpp::Geometry sphere("sphere"); sphere.setParam("sphere.position", cpp::Data(vec3f(0.f))); sphere.setParam("radius", 0.51f); sphere.commit(); cpp::GeometricModel model(sphere); model.setParam("material", sphereMaterial); AddModel(model); cpp::Light ambient("ambient"); ambient.setParam("intensity", 0.5f); AddLight(ambient); } DepthCompositeVolume::DepthCompositeVolume() { auto params = GetParam(); rendererType = std::get<0>(params); bgColor = std::get<1>(params); } void DepthCompositeVolume::SetUp() { Base::SetUp(); camera.setParam("position", vec3f(0.f, 0.f, 1.f)); camera.setParam("direction", vec3f(0.f, 0.f, -1.f)); camera.setParam("up", vec3f(0.f, 1.f, 0.f)); cpp::Volume torus = CreateTorus(256); torus.commit(); cpp::VolumetricModel volumetricModel(torus); cpp::TransferFunction transferFun("piecewiseLinear"); transferFun.setParam("valueRange", vec2f(-10000.f, 10000.f)); std::vector<vec3f> colors = { vec3f(1.0f, 0.0f, 0.0f), vec3f(0.0f, 1.0f, 0.0f)}; std::vector<float> opacities = {0.05f, 1.0f}; transferFun.setParam("color", cpp::Data(colors)); transferFun.setParam("opacity", cpp::Data(opacities)); transferFun.commit(); volumetricModel.setParam("transferFunction", transferFun); volumetricModel.commit(); AddModel(volumetricModel); cpp::Texture depthTex("texture2d"); std::vector<float> texData(imgSize.product()); for (int y = 0; y < imgSize.y; y++) { for (int x = 0; x < imgSize.x; x++) { const size_t index = imgSize.x * y + x; if (x < imgSize.x / 3) { texData[index] = 999.f; } else if (x < (imgSize.x * 2) / 3) { texData[index] = 0.75f; } else { texData[index] = 0.00001f; } } } depthTex.setParam<int>("format", OSP_TEXTURE_R32F); depthTex.setParam<int>("filter", OSP_TEXTURE_FILTER_NEAREST); depthTex.setParam("data", cpp::Data(imgSize, texData.data())); depthTex.commit(); renderer.setParam("map_maxDepth", depthTex); renderer.setParam("backgroundColor", bgColor); cpp::Light ambient("ambient"); ambient.setParam("intensity", 0.5f); AddLight(ambient); } RendererMaterialList::RendererMaterialList() { rendererType = GetParam(); } void RendererMaterialList::SetUp() { Base::SetUp(); // Setup geometry // cpp::Geometry sphereGeometry("sphere"); constexpr int dimSize = 3; ospcommon::index_sequence_2D numSpheres(dimSize); std::vector<vec3f> spheres; std::vector<uint32_t> index; std::vector<cpp::Material> materials; auto makeObjMaterial = [](const std::string &rendererType, vec3f Kd, vec3f Ks) -> cpp::Material { cpp::Material mat(rendererType, "obj"); mat.setParam("kd", Kd); if (rendererType == "pathtracer") mat.setParam("ks", Ks); mat.commit(); return mat; }; for (auto i : numSpheres) { auto i_f = static_cast<vec2f>(i); spheres.emplace_back(i_f.x, i_f.y, 0.f); auto l = i_f / (dimSize - 1); materials.push_back(makeObjMaterial(rendererType, lerp(l.x, vec3f(0.1f), vec3f(0.f, 0.f, 1.f)), lerp(l.y, vec3f(0.f), vec3f(1.f)))); index.push_back(static_cast<uint32_t>(numSpheres.flatten(i))); } sphereGeometry.setParam("sphere.position", cpp::Data(spheres)); sphereGeometry.setParam("radius", 0.4f); sphereGeometry.commit(); cpp::GeometricModel model(sphereGeometry); model.setParam("material", cpp::Data(index)); AddModel(model); // Setup renderer material list // renderer.setParam("material", cpp::Data(materials)); // Create the world to get bounds for camera setup // if (!instances.empty()) world.setParam("instance", cpp::Data(instances)); instances.clear(); world.commit(); auto worldBounds = world.getBounds(); ArcballCamera arcballCamera(worldBounds, imgSize); camera.setParam("position", arcballCamera.eyePos()); camera.setParam("direction", arcballCamera.lookDir()); camera.setParam("up", arcballCamera.upDir()); // Setup lights // cpp::Light ambient("ambient"); ambient.setParam("intensity", 0.5f); AddLight(ambient); } FromOsprayTesting::FromOsprayTesting() { auto params = GetParam(); sceneName = std::get<0>(params); rendererType = std::get<1>(params); } void FromOsprayTesting::SetUp() { Base::SetUp(); instances.clear(); auto builder = ospray::testing::newBuilder(sceneName); ospray::testing::setParam(builder, "rendererType", rendererType); ospray::testing::commit(builder); world = ospray::testing::buildWorld(builder); ospray::testing::release(builder); world.commit(); auto worldBounds = world.getBounds(); ArcballCamera arcballCamera(worldBounds, imgSize); camera.setParam("position", arcballCamera.eyePos()); camera.setParam("direction", arcballCamera.lookDir()); camera.setParam("up", arcballCamera.upDir()); } } // namespace OSPRayTestScenes
25.984
80
0.657635
[ "geometry", "vector", "model" ]
b3fdc0755ff0555dcd89e8904f51fb57f7f9647b
34,224
inl
C++
DirectXErrors/DirectXErrors/data/mf.inl
Const-me/DirectXErrors
87bebfe1655ad9e09cd8203064905900e9422756
[ "MIT" ]
33
2019-01-28T03:32:17.000Z
2022-02-12T18:17:26.000Z
DirectXErrors/DirectXErrors/data/mf.inl
Const-me/DirectXErrors
87bebfe1655ad9e09cd8203064905900e9422756
[ "MIT" ]
2
2019-11-18T17:54:58.000Z
2020-07-21T18:11:21.000Z
DirectXErrors/DirectXErrors/data/mf.inl
Const-me/DirectXErrors
87bebfe1655ad9e09cd8203064905900e9422756
[ "MIT" ]
5
2019-02-16T23:00:11.000Z
2022-03-27T15:22:10.000Z
CHK_ERR( MF_E_PLATFORM_NOT_INITIALIZED, "Platform not initialized. Please call MFStartup()." ) CHK_ERR( MF_E_BUFFERTOOSMALL, "The buffer was too small to carry out the requested action." ) CHK_ERR( MF_E_INVALIDREQUEST, "The request is invalid in the current state." ) CHK_ERR( MF_E_INVALIDSTREAMNUMBER, "The stream number provided was invalid." ) CHK_ERR( MF_E_INVALIDMEDIATYPE, "The data specified for the media type is invalid, inconsistent, or not supported by this object." ) CHK_ERR( MF_E_NOTACCEPTING, "The callee is currently not accepting further input." ) CHK_ERR( MF_E_NOT_INITIALIZED, "This object needs to be initialized before the requested operation can be carried out." ) CHK_ERR( MF_E_UNSUPPORTED_REPRESENTATION, "The requested representation is not supported by this object." ) CHK_ERR( MF_E_NO_MORE_TYPES, "An object ran out of media types to suggest therefore the requested chain of streaming objects cannot be completed." ) CHK_ERR( MF_E_UNSUPPORTED_SERVICE, "The object does not support the specified service." ) CHK_ERR( MF_E_UNEXPECTED, "An unexpected error has occurred in the operation requested." ) CHK_ERR( MF_E_INVALIDNAME, "Invalid name." ) CHK_ERR( MF_E_INVALIDTYPE, "Invalid type." ) CHK_ERR( MF_E_INVALID_FILE_FORMAT, "The file does not conform to the relevant file format specification." ) CHK_ERR( MF_E_INVALIDINDEX, "Invalid index." ) CHK_ERR( MF_E_INVALID_TIMESTAMP, "An invalid timestamp was given." ) CHK_ERR( MF_E_UNSUPPORTED_SCHEME, "The scheme of the given URL is unsupported." ) CHK_ERR( MF_E_UNSUPPORTED_BYTESTREAM_TYPE, "The byte stream type of the given URL is unsupported." ) CHK_ERR( MF_E_UNSUPPORTED_TIME_FORMAT, "The given time format is unsupported." ) CHK_ERR( MF_E_NO_SAMPLE_TIMESTAMP, "The Media Sample does not have a timestamp." ) CHK_ERR( MF_E_NO_SAMPLE_DURATION, "The Media Sample does not have a duration." ) CHK_ERR( MF_E_INVALID_STREAM_DATA, "The request failed because the data in the stream is corrupt." ) CHK_ERR( MF_E_RT_UNAVAILABLE, "Real time services are not available." ) CHK_ERR( MF_E_UNSUPPORTED_RATE, "The specified rate is not supported." ) CHK_ERR( MF_E_THINNING_UNSUPPORTED, "This component does not support stream-thinning." ) CHK_ERR( MF_E_REVERSE_UNSUPPORTED, "The call failed because no reverse playback rates are available." ) CHK_ERR( MF_E_UNSUPPORTED_RATE_TRANSITION, "The requested rate transition cannot occur in the current state." ) CHK_ERR( MF_E_RATE_CHANGE_PREEMPTED, "The requested rate change has been pre-empted and will not occur." ) CHK_ERR( MF_E_NOT_FOUND, "The specified object or value does not exist." ) CHK_ERR( MF_E_NOT_AVAILABLE, "The requested value is not available." ) CHK_ERR( MF_E_NO_CLOCK, "The specified operation requires a clock and no clock is available." ) CHK_ERR( MF_E_MULTIPLE_BEGIN, "This callback has already been passed in to this event generator." ) CHK_ERR( MF_E_MULTIPLE_SUBSCRIBERS, "Some component is already listening to events on this event generator." ) CHK_ERR( MF_E_TIMER_ORPHANED, "This timer was orphaned before its callback time arrived." ) CHK_ERR( MF_E_STATE_TRANSITION_PENDING, "A state transition is already pending." ) CHK_ERR( MF_E_UNSUPPORTED_STATE_TRANSITION, "The requested state transition is unsupported." ) CHK_ERR( MF_E_UNRECOVERABLE_ERROR_OCCURRED, "An unrecoverable error has occurred." ) CHK_ERR( MF_E_SAMPLE_HAS_TOO_MANY_BUFFERS, "The provided sample has too many buffers." ) CHK_ERR( MF_E_SAMPLE_NOT_WRITABLE, "The provided sample is not writable." ) CHK_ERR( MF_E_INVALID_KEY, "The specified key is not valid." ) CHK_ERR( MF_E_BAD_STARTUP_VERSION, "You are calling MFStartup with the wrong MF_VERSION. Mismatched bits?" ) CHK_ERR( MF_E_UNSUPPORTED_CAPTION, "The caption of the given URL is unsupported." ) CHK_ERR( MF_E_INVALID_POSITION, "The operation on the current offset is not permitted." ) CHK_ERR( MF_E_ATTRIBUTENOTFOUND, "The requested attribute was not found." ) CHK_ERR( MF_E_PROPERTY_TYPE_NOT_ALLOWED, "The specified property type is not allowed in this context." ) CHK_ERR( MF_E_PROPERTY_TYPE_NOT_SUPPORTED, "The specified property type is not supported." ) CHK_ERR( MF_E_PROPERTY_EMPTY, "The specified property is empty." ) CHK_ERR( MF_E_PROPERTY_NOT_EMPTY, "The specified property is not empty." ) CHK_ERR( MF_E_PROPERTY_VECTOR_NOT_ALLOWED, "The vector property specified is not allowed in this context." ) CHK_ERR( MF_E_PROPERTY_VECTOR_REQUIRED, "A vector property is required in this context." ) CHK_ERR( MF_E_OPERATION_CANCELLED, "The operation is canceled." ) CHK_ERR( MF_E_BYTESTREAM_NOT_SEEKABLE, "The provided bytestream was expected to be seekable and it is not." ) CHK_ERR( MF_E_DISABLED_IN_SAFEMODE, "The Media Foundation platform is disabled when the system is running in Safe Mode." ) CHK_ERR( MF_E_CANNOT_PARSE_BYTESTREAM, "The Media Source could not parse the byte stream." ) CHK_ERR( MF_E_SOURCERESOLVER_MUTUALLY_EXCLUSIVE_FLAGS, "Mutually exclusive flags have been specified to source resolver. This flag combination is invalid." ) CHK_ERR( MF_E_MEDIAPROC_WRONGSTATE, "MediaProc is in the wrong state." ) CHK_ERR( MF_E_RT_THROUGHPUT_NOT_AVAILABLE, "Real time I/O service can not provide requested throughput." ) CHK_ERR( MF_E_RT_TOO_MANY_CLASSES, "The workqueue cannot be registered with more classes." ) CHK_ERR( MF_E_RT_WOULDBLOCK, "This operation cannot succeed because another thread owns this object." ) CHK_ERR( MF_E_NO_BITPUMP, "Internal. Bitpump not found." ) CHK_ERR( MF_E_RT_OUTOFMEMORY, "No more RT memory available." ) CHK_ERR( MF_E_RT_WORKQUEUE_CLASS_NOT_SPECIFIED, "An MMCSS class has not been set for this work queue." ) CHK_ERR( MF_E_INSUFFICIENT_BUFFER, "Insufficient memory for response." ) CHK_ERR( MF_E_CANNOT_CREATE_SINK, "Activate failed to create mediasink. Call OutputNode::GetUINT32(MF_TOPONODE_MAJORTYPE) for more information." ) CHK_ERR( MF_E_BYTESTREAM_UNKNOWN_LENGTH, "The length of the provided bytestream is unknown." ) CHK_ERR( MF_E_SESSION_PAUSEWHILESTOPPED, "The media session cannot pause from a stopped state." ) CHK_ERR( MF_E_FORMAT_CHANGE_NOT_SUPPORTED, "The data specified for the media type is supported, but would require a format change, which is not supported by this object." ) CHK_ERR( MF_E_INVALID_WORKQUEUE, "The operation failed because an invalid combination of workqueue ID and flags was specified." ) CHK_ERR( MF_E_DRM_UNSUPPORTED, "No DRM support is available." ) CHK_ERR( MF_E_UNAUTHORIZED, "This operation is not authorized." ) CHK_ERR( MF_E_OUT_OF_RANGE, "The value is not in the specified or valid range." ) CHK_ERR( MF_E_INVALID_CODEC_MERIT, "The registered codec merit is not valid." ) CHK_ERR( MF_E_HW_MFT_FAILED_START_STREAMING, "Hardware MFT failed to start streaming due to lack of hardware resources." ) CHK_ERR( MF_E_OPERATION_IN_PROGRESS, "The operation is already in progress." ) CHK_ERR( MF_E_HARDWARE_DRM_UNSUPPORTED, "No Hardware DRM support is available." ) CHK_ERR( MF_E_ASF_PARSINGINCOMPLETE, "Not enough data have been parsed to carry out the requested action." ) CHK_ERR( MF_E_ASF_MISSINGDATA, "There is a gap in the ASF data provided." ) CHK_ERR( MF_E_ASF_INVALIDDATA, "The data provided are not valid ASF." ) CHK_ERR( MF_E_ASF_OPAQUEPACKET, "The packet is opaque, so the requested information cannot be returned." ) CHK_ERR( MF_E_ASF_NOINDEX, "The requested operation failed since there is no appropriate ASF index." ) CHK_ERR( MF_E_ASF_OUTOFRANGE, "The value supplied is out of range for this operation." ) CHK_ERR( MF_E_ASF_INDEXNOTLOADED, "The index entry requested needs to be loaded before it can be available." ) CHK_ERR( MF_E_ASF_TOO_MANY_PAYLOADS, "The packet has reached the maximum number of payloads." ) CHK_ERR( MF_E_ASF_UNSUPPORTED_STREAM_TYPE, "Stream type is not supported." ) CHK_ERR( MF_E_ASF_DROPPED_PACKET, "One or more ASF packets were dropped." ) CHK_ERR( MF_E_NO_EVENTS_AVAILABLE, "There are no events available in the queue." ) CHK_ERR( MF_E_INVALID_STATE_TRANSITION, "A media source cannot go from the stopped state to the paused state." ) CHK_ERR( MF_E_END_OF_STREAM, "The media stream cannot process any more samples because there are no more samples in the stream." ) CHK_ERR( MF_E_SHUTDOWN, "The request is invalid because Shutdown() has been called." ) CHK_ERR( MF_E_MP3_NOTFOUND, "The MP3 object was not found." ) CHK_ERR( MF_E_MP3_OUTOFDATA, "The MP3 parser ran out of data before finding the MP3 object." ) CHK_ERR( MF_E_MP3_NOTMP3, "The file is not really a MP3 file." ) CHK_ERR( MF_E_MP3_NOTSUPPORTED, "The MP3 file is not supported." ) CHK_ERR( MF_E_NO_DURATION, "The Media stream has no duration." ) CHK_ERR( MF_E_INVALID_FORMAT, "The Media format is recognized but is invalid." ) CHK_ERR( MF_E_PROPERTY_NOT_FOUND, "The property requested was not found." ) CHK_ERR( MF_E_PROPERTY_READ_ONLY, "The property is read only." ) CHK_ERR( MF_E_PROPERTY_NOT_ALLOWED, "The specified property is not allowed in this context." ) CHK_ERR( MF_E_MEDIA_SOURCE_NOT_STARTED, "The media source is not started." ) CHK_ERR( MF_E_UNSUPPORTED_FORMAT, "The Media format is recognized but not supported." ) CHK_ERR( MF_E_MP3_BAD_CRC, "The MPEG frame has bad CRC." ) CHK_ERR( MF_E_NOT_PROTECTED, "The file is not protected." ) CHK_ERR( MF_E_MEDIA_SOURCE_WRONGSTATE, "The media source is in the wrong state." ) CHK_ERR( MF_E_MEDIA_SOURCE_NO_STREAMS_SELECTED, "No streams are selected in source presentation descriptor." ) CHK_ERR( MF_E_CANNOT_FIND_KEYFRAME_SAMPLE, "No key frame sample was found." ) CHK_ERR( MF_E_UNSUPPORTED_CHARACTERISTICS, "The characteristics of the media source are not supported." ) CHK_ERR( MF_E_NO_AUDIO_RECORDING_DEVICE, "No audio recording device was found." ) CHK_ERR( MF_E_AUDIO_RECORDING_DEVICE_IN_USE, "The requested audio recording device is currently in use." ) CHK_ERR( MF_E_AUDIO_RECORDING_DEVICE_INVALIDATED, "The audio recording device is no longer present." ) CHK_ERR( MF_E_VIDEO_RECORDING_DEVICE_INVALIDATED, "The video recording device is no longer present." ) CHK_ERR( MF_E_VIDEO_RECORDING_DEVICE_PREEMPTED, "The video recording device is preempted by another immersive application." ) CHK_ERR( MF_E_NETWORK_RESOURCE_FAILURE, "An attempt to acquire a network resource failed." ) CHK_ERR( MF_E_NET_WRITE, "Error writing to the network." ) CHK_ERR( MF_E_NET_READ, "Error reading from the network." ) CHK_ERR( MF_E_NET_REQUIRE_NETWORK, "Internal. Entry cannot complete operation without network." ) CHK_ERR( MF_E_NET_REQUIRE_ASYNC, "Internal. Async op is required." ) CHK_ERR( MF_E_NET_BWLEVEL_NOT_SUPPORTED, "Internal. Bandwidth levels are not supported." ) CHK_ERR( MF_E_NET_STREAMGROUPS_NOT_SUPPORTED, "Internal. Stream groups are not supported." ) CHK_ERR( MF_E_NET_MANUALSS_NOT_SUPPORTED, "Manual stream selection is not supported." ) CHK_ERR( MF_E_NET_INVALID_PRESENTATION_DESCRIPTOR, "Invalid presentation descriptor." ) CHK_ERR( MF_E_NET_CACHESTREAM_NOT_FOUND, "Cannot find cache stream." ) CHK_ERR( MF_E_NET_REQUIRE_INPUT, "Internal. Entry cannot complete operation without input." ) CHK_ERR( MF_E_NET_REDIRECT, "The client redirected to another server." ) CHK_ERR( MF_E_NET_REDIRECT_TO_PROXY, "The client is redirected to a proxy server." ) CHK_ERR( MF_E_NET_TOO_MANY_REDIRECTS, "The client reached maximum redirection limit." ) CHK_ERR( MF_E_NET_TIMEOUT, "The server, a computer set up to offer multimedia content to other computers, could not handle your request for multimedia content in a timely manner. Please try again later." ) CHK_ERR( MF_E_NET_CLIENT_CLOSE, "The control socket is closed by the client." ) CHK_ERR( MF_E_NET_BAD_CONTROL_DATA, "The server received invalid data from the client on the control connection." ) CHK_ERR( MF_E_NET_INCOMPATIBLE_SERVER, "The server is not a compatible streaming media server." ) CHK_ERR( MF_E_NET_UNSAFE_URL, "Url." ) CHK_ERR( MF_E_NET_CACHE_NO_DATA, "Data is not available." ) CHK_ERR( MF_E_NET_EOL, "End of line." ) CHK_ERR( MF_E_NET_BAD_REQUEST, "The request could not be understood by the server." ) CHK_ERR( MF_E_NET_INTERNAL_SERVER_ERROR, "The server encountered an unexpected condition which prevented it from fulfilling the request." ) CHK_ERR( MF_E_NET_SESSION_NOT_FOUND, "Session not found." ) CHK_ERR( MF_E_NET_NOCONNECTION, "There is no connection established with the Windows Media server. The operation failed." ) CHK_ERR( MF_E_NET_CONNECTION_FAILURE, "The network connection has failed." ) CHK_ERR( MF_E_NET_INCOMPATIBLE_PUSHSERVER, "The Server service that received the HTTP push request is not a compatible version of Windows Media Services (WMS). This error may indicate the push request was received by IIS instead of WMS. Ensure WMS is started and has the HTTP Server control protocol properly enabled and try again." ) CHK_ERR( MF_E_NET_SERVER_ACCESSDENIED, "The Windows Media server is denying access. The username and/or password might be incorrect." ) CHK_ERR( MF_E_NET_PROXY_ACCESSDENIED, "The proxy server is denying access. The username and/or password might be incorrect." ) CHK_ERR( MF_E_NET_CANNOTCONNECT, "Unable to establish a connection to the server." ) CHK_ERR( MF_E_NET_INVALID_PUSH_TEMPLATE, "The specified push template is invalid." ) CHK_ERR( MF_E_NET_INVALID_PUSH_PUBLISHING_POINT, "The specified push publishing point is invalid." ) CHK_ERR( MF_E_NET_BUSY, "The requested resource is in use." ) CHK_ERR( MF_E_NET_RESOURCE_GONE, "The Publishing Point or file on the Windows Media Server is no longer available." ) CHK_ERR( MF_E_NET_ERROR_FROM_PROXY, "The proxy experienced an error while attempting to contact the media server." ) CHK_ERR( MF_E_NET_PROXY_TIMEOUT, "The proxy did not receive a timely response while attempting to contact the media server." ) CHK_ERR( MF_E_NET_SERVER_UNAVAILABLE, "The server is currently unable to handle the request due to a temporary overloading or maintenance of the server." ) CHK_ERR( MF_E_NET_TOO_MUCH_DATA, "The encoding process was unable to keep up with the amount of supplied data." ) CHK_ERR( MF_E_NET_SESSION_INVALID, "Session not found." ) CHK_ERR( MF_E_OFFLINE_MODE, "The requested URL is not available in offline mode." ) CHK_ERR( MF_E_NET_UDP_BLOCKED, "A device in the network is blocking UDP traffic." ) CHK_ERR( MF_E_NET_UNSUPPORTED_CONFIGURATION, "The specified configuration value is not supported." ) CHK_ERR( MF_E_NET_PROTOCOL_DISABLED, "The networking protocol is disabled." ) CHK_ERR( MF_E_NET_COMPANION_DRIVER_DISCONNECT, "The companion driver asked the OS to disconnect from the receiver." ) CHK_ERR( MF_E_ALREADY_INITIALIZED, "This object has already been initialized and cannot be re-initialized at this time." ) CHK_ERR( MF_E_BANDWIDTH_OVERRUN, "The amount of data passed in exceeds the given bitrate and buffer window." ) CHK_ERR( MF_E_LATE_SAMPLE, "The sample was passed in too late to be correctly processed." ) CHK_ERR( MF_E_FLUSH_NEEDED, "The requested action cannot be carried out until the object is flushed and the queue is emptied." ) CHK_ERR( MF_E_INVALID_PROFILE, "The profile is invalid." ) CHK_ERR( MF_E_INDEX_NOT_COMMITTED, "The index that is being generated needs to be committed before the requested action can be carried out." ) CHK_ERR( MF_E_NO_INDEX, "The index that is necessary for the requested action is not found." ) CHK_ERR( MF_E_CANNOT_INDEX_IN_PLACE, "The requested index cannot be added in-place to the specified ASF content." ) CHK_ERR( MF_E_MISSING_ASF_LEAKYBUCKET, "The ASF leaky bucket parameters must be specified in order to carry out this request." ) CHK_ERR( MF_E_INVALID_ASF_STREAMID, "The stream id is invalid. The valid range for ASF stream id is from 1 to 127." ) CHK_ERR( MF_E_STREAMSINK_REMOVED, "The requested Stream Sink has been removed and cannot be used." ) CHK_ERR( MF_E_STREAMSINKS_OUT_OF_SYNC, "The various Stream Sinks in this Media Sink are too far out of sync for the requested action to take place." ) CHK_ERR( MF_E_STREAMSINKS_FIXED, "Stream Sinks cannot be added to or removed from this Media Sink because its set of streams is fixed." ) CHK_ERR( MF_E_STREAMSINK_EXISTS, "The given Stream Sink already exists." ) CHK_ERR( MF_E_SAMPLEALLOCATOR_CANCELED, "Sample allocations have been canceled." ) CHK_ERR( MF_E_SAMPLEALLOCATOR_EMPTY, "The sample allocator is currently empty, due to outstanding requests." ) CHK_ERR( MF_E_SINK_ALREADYSTOPPED, "When we try to stop a stream sink, it is already stopped." ) CHK_ERR( MF_E_ASF_FILESINK_BITRATE_UNKNOWN, "The ASF file sink could not reserve AVIO because the bitrate is unknown." ) CHK_ERR( MF_E_SINK_NO_STREAMS, "No streams are selected in sink presentation descriptor." ) CHK_ERR( MF_E_METADATA_TOO_LONG, "A metadata item was too long to write to the output container." ) CHK_ERR( MF_E_SINK_NO_SAMPLES_PROCESSED, "The operation failed because no samples were processed by the sink." ) CHK_ERR( MF_E_SINK_HEADERS_NOT_FOUND, "Sink could not create valid output file because required headers were not provided to the sink." ) CHK_ERR( MF_E_VIDEO_REN_NO_PROCAMP_HW, "There is no available procamp hardware with which to perform color correction." ) CHK_ERR( MF_E_VIDEO_REN_NO_DEINTERLACE_HW, "There is no available deinterlacing hardware with which to deinterlace the video stream." ) CHK_ERR( MF_E_VIDEO_REN_COPYPROT_FAILED, "A video stream requires copy protection to be enabled, but there was a failure in attempting to enable copy protection." ) CHK_ERR( MF_E_VIDEO_REN_SURFACE_NOT_SHARED, "A component is attempting to access a surface for sharing that is not shared." ) CHK_ERR( MF_E_VIDEO_DEVICE_LOCKED, "A component is attempting to access a shared device that is already locked by another component." ) CHK_ERR( MF_E_NEW_VIDEO_DEVICE, "The device is no longer available. The handle should be closed and a new one opened." ) CHK_ERR( MF_E_NO_VIDEO_SAMPLE_AVAILABLE, "A video sample is not currently queued on a stream that is required for mixing." ) CHK_ERR( MF_E_NO_AUDIO_PLAYBACK_DEVICE, "No audio playback device was found." ) CHK_ERR( MF_E_AUDIO_PLAYBACK_DEVICE_IN_USE, "The requested audio playback device is currently in use." ) CHK_ERR( MF_E_AUDIO_PLAYBACK_DEVICE_INVALIDATED, "The audio playback device is no longer present." ) CHK_ERR( MF_E_AUDIO_SERVICE_NOT_RUNNING, "The audio service is not running." ) CHK_ERR( MF_E_TOPO_INVALID_OPTIONAL_NODE, "The topology contains an invalid optional node. Possible reasons are incorrect number of outputs and inputs or optional node is at the beginning or end of a segment." ) CHK_ERR( MF_E_TOPO_CANNOT_FIND_DECRYPTOR, "No suitable transform was found to decrypt the content." ) CHK_ERR( MF_E_TOPO_CODEC_NOT_FOUND, "No suitable transform was found to encode or decode the content." ) CHK_ERR( MF_E_TOPO_CANNOT_CONNECT, "Unable to find a way to connect nodes." ) CHK_ERR( MF_E_TOPO_UNSUPPORTED, "Unsupported operations in topoloader." ) CHK_ERR( MF_E_TOPO_INVALID_TIME_ATTRIBUTES, "The topology or its nodes contain incorrectly set time attributes." ) CHK_ERR( MF_E_TOPO_LOOPS_IN_TOPOLOGY, "The topology contains loops, which are unsupported in media foundation topologies." ) CHK_ERR( MF_E_TOPO_MISSING_PRESENTATION_DESCRIPTOR, "A source stream node in the topology does not have a presentation descriptor." ) CHK_ERR( MF_E_TOPO_MISSING_STREAM_DESCRIPTOR, "A source stream node in the topology does not have a stream descriptor." ) CHK_ERR( MF_E_TOPO_STREAM_DESCRIPTOR_NOT_SELECTED, "A stream descriptor was set on a source stream node but it was not selected on the presentation descriptor." ) CHK_ERR( MF_E_TOPO_MISSING_SOURCE, "A source stream node in the topology does not have a source." ) CHK_ERR( MF_E_TOPO_SINK_ACTIVATES_UNSUPPORTED, "The topology loader does not support sink activates on output nodes." ) CHK_ERR( MF_E_SEQUENCER_UNKNOWN_SEGMENT_ID, "The sequencer cannot find a segment with the given ID." ) CHK_ERR( MF_E_NO_SOURCE_IN_CACHE, "Cannot find source in source cache." ) CHK_ERR( MF_E_TRANSFORM_TYPE_NOT_SET, "A valid type has not been set for this stream or a stream that it depends on." ) CHK_ERR( MF_E_TRANSFORM_STREAM_CHANGE, "A stream change has occurred. Output cannot be produced until the streams have been renegotiated." ) CHK_ERR( MF_E_TRANSFORM_INPUT_REMAINING, "The transform cannot take the requested action until all of the input data it currently holds is processed or flushed." ) CHK_ERR( MF_E_TRANSFORM_PROFILE_MISSING, "The transform requires a profile but no profile was supplied or found." ) CHK_ERR( MF_E_TRANSFORM_PROFILE_INVALID_OR_CORRUPT, "The transform requires a profile but the supplied profile was invalid or corrupt." ) CHK_ERR( MF_E_TRANSFORM_PROFILE_TRUNCATED, "The transform requires a profile but the supplied profile ended unexpectedly while parsing." ) CHK_ERR( MF_E_TRANSFORM_PROPERTY_PID_NOT_RECOGNIZED, "The property ID does not match any property supported by the transform." ) CHK_ERR( MF_E_TRANSFORM_PROPERTY_VARIANT_TYPE_WRONG, "The variant does not have the type expected for this property ID." ) CHK_ERR( MF_E_TRANSFORM_PROPERTY_NOT_WRITEABLE, "An attempt was made to set the value on a read-only property." ) CHK_ERR( MF_E_TRANSFORM_PROPERTY_ARRAY_VALUE_WRONG_NUM_DIM, "The array property value has an unexpected number of dimensions." ) CHK_ERR( MF_E_TRANSFORM_PROPERTY_VALUE_SIZE_WRONG, "The array or blob property value has an unexpected size." ) CHK_ERR( MF_E_TRANSFORM_PROPERTY_VALUE_OUT_OF_RANGE, "The property value is out of range for this transform." ) CHK_ERR( MF_E_TRANSFORM_PROPERTY_VALUE_INCOMPATIBLE, "The property value is incompatible with some other property or mediatype set on the transform." ) CHK_ERR( MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_OUTPUT_MEDIATYPE, "The requested operation is not supported for the currently set output mediatype." ) CHK_ERR( MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_INPUT_MEDIATYPE, "The requested operation is not supported for the currently set input mediatype." ) CHK_ERR( MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_MEDIATYPE_COMBINATION, "The requested operation is not supported for the currently set combination of mediatypes." ) CHK_ERR( MF_E_TRANSFORM_CONFLICTS_WITH_OTHER_CURRENTLY_ENABLED_FEATURES, "The requested feature is not supported in combination with some other currently enabled feature." ) CHK_ERR( MF_E_TRANSFORM_NEED_MORE_INPUT, "The transform cannot produce output until it gets more input samples." ) CHK_ERR( MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_SPKR_CONFIG, "The requested operation is not supported for the current speaker configuration." ) CHK_ERR( MF_E_TRANSFORM_CANNOT_CHANGE_MEDIATYPE_WHILE_PROCESSING, "The transform cannot accept mediatype changes in the middle of processing." ) CHK_ERR( MF_E_UNSUPPORTED_D3D_TYPE, "The input type is not supported for D3D device." ) CHK_ERR( MF_E_TRANSFORM_ASYNC_LOCKED, "The caller does not appear to support this transform's asynchronous capabilities." ) CHK_ERR( MF_E_TRANSFORM_CANNOT_INITIALIZE_ACM_DRIVER, "An audio compression manager driver could not be initialized by the transform." ) CHK_ERR( MF_E_TRANSFORM_STREAM_INVALID_RESOLUTION, "The input stream has invalid and illegal resolution. Output should stop on next ProcessOutput call after the invalid and illegal resolution is detected." ) CHK_ERR( MF_E_TRANSFORM_ASYNC_MFT_NOT_SUPPORTED, "The transform cannot be asynchronous in current context." ) CHK_ERR( MF_E_TRANSFORM_EXATTRIBUTE_NOT_SUPPORTED, "It is not supported in the current context to have the transform copy attributes from an input sample to an output sample." ) CHK_ERR( MF_E_LICENSE_INCORRECT_RIGHTS, "You are not allowed to open this file. Contact the content provider for further assistance." ) CHK_ERR( MF_E_LICENSE_OUTOFDATE, "The license for this media file has expired. Get a new license or contact the content provider for further assistance." ) CHK_ERR( MF_E_LICENSE_REQUIRED, "You need a license to perform the requested operation on this media file." ) CHK_ERR( MF_E_DRM_HARDWARE_INCONSISTENT, "The licenses for your media files are corrupted. Contact Microsoft product support." ) CHK_ERR( MF_E_NO_CONTENT_PROTECTION_MANAGER, "The APP needs to provide IMFContentProtectionManager callback to access the protected media file." ) CHK_ERR( MF_E_LICENSE_RESTORE_NO_RIGHTS, "Client does not have rights to restore licenses." ) CHK_ERR( MF_E_BACKUP_RESTRICTED_LICENSE, "Licenses are restricted and hence can not be backed up." ) CHK_ERR( MF_E_LICENSE_RESTORE_NEEDS_INDIVIDUALIZATION, "License restore requires machine to be individualized." ) CHK_ERR( MF_E_COMPONENT_REVOKED, "Component is revoked." ) CHK_ERR( MF_E_TRUST_DISABLED, "Trusted functionality is currently disabled on this component." ) CHK_ERR( MF_E_WMDRMOTA_NO_ACTION, "No Action is set on WMDRM Output Trust Authority." ) CHK_ERR( MF_E_WMDRMOTA_ACTION_ALREADY_SET, "Action is already set on WMDRM Output Trust Authority." ) CHK_ERR( MF_E_WMDRMOTA_DRM_HEADER_NOT_AVAILABLE, "DRM Header is not available." ) CHK_ERR( MF_E_WMDRMOTA_DRM_ENCRYPTION_SCHEME_NOT_SUPPORTED, "Current encryption scheme is not supported." ) CHK_ERR( MF_E_WMDRMOTA_ACTION_MISMATCH, "Action does not match with current configuration." ) CHK_ERR( MF_E_WMDRMOTA_INVALID_POLICY, "Invalid policy for WMDRM Output Trust Authority." ) CHK_ERR( MF_E_POLICY_UNSUPPORTED, "The policies that the Input Trust Authority requires to be enforced are unsupported by the outputs." ) CHK_ERR( MF_E_OPL_NOT_SUPPORTED, "The OPL that the license requires to be enforced are not supported by the Input Trust Authority." ) CHK_ERR( MF_E_TOPOLOGY_VERIFICATION_FAILED, "The topology could not be successfully verified." ) CHK_ERR( MF_E_SIGNATURE_VERIFICATION_FAILED, "Signature verification could not be completed successfully for this component." ) CHK_ERR( MF_E_DEBUGGING_NOT_ALLOWED, "Running this process under a debugger while using protected content is not allowed." ) CHK_ERR( MF_E_CODE_EXPIRED, "MF component has expired." ) CHK_ERR( MF_E_GRL_VERSION_TOO_LOW, "The current GRL on the machine does not meet the minimum version requirements." ) CHK_ERR( MF_E_GRL_RENEWAL_NOT_FOUND, "The current GRL on the machine does not contain any renewal entries for the specified revocation." ) CHK_ERR( MF_E_GRL_EXTENSIBLE_ENTRY_NOT_FOUND, "The current GRL on the machine does not contain any extensible entries for the specified extension GUID." ) CHK_ERR( MF_E_KERNEL_UNTRUSTED, "The kernel isn't secure for high security level content." ) CHK_ERR( MF_E_PEAUTH_UNTRUSTED, "The response from protected environment driver isn't valid." ) CHK_ERR( MF_E_NON_PE_PROCESS, "A non-PE process tried to talk to PEAuth." ) CHK_ERR( MF_E_REBOOT_REQUIRED, "We need to reboot the machine." ) CHK_ERR( MF_E_GRL_INVALID_FORMAT, "The GRL file is not correctly formed, it may have been corrupted or overwritten." ) CHK_ERR( MF_E_GRL_UNRECOGNIZED_FORMAT, "The GRL file is in a format newer than those recognized by this GRL Reader." ) CHK_ERR( MF_E_ALL_PROCESS_RESTART_REQUIRED, "The GRL was reloaded and required all processes that can run protected media to restart." ) CHK_ERR( MF_E_PROCESS_RESTART_REQUIRED, "The GRL was reloaded and the current process needs to restart." ) CHK_ERR( MF_E_USERMODE_UNTRUSTED, "The user space is untrusted for protected content play." ) CHK_ERR( MF_E_PEAUTH_SESSION_NOT_STARTED, "PEAuth communication session hasn't been started." ) CHK_ERR( MF_E_PEAUTH_PUBLICKEY_REVOKED, "PEAuth's public key is revoked." ) CHK_ERR( MF_E_GRL_ABSENT, "The GRL is absent." ) CHK_ERR( MF_E_PE_UNTRUSTED, "The Protected Environment is untrusted." ) CHK_ERR( MF_E_PEAUTH_NOT_STARTED, "The Protected Environment Authorization service (PEAUTH) has not been started." ) CHK_ERR( MF_E_INCOMPATIBLE_SAMPLE_PROTECTION, "The sample protection algorithms supported by components are not compatible." ) CHK_ERR( MF_E_PE_SESSIONS_MAXED, "No more protected environment sessions can be supported." ) CHK_ERR( MF_E_HIGH_SECURITY_LEVEL_CONTENT_NOT_ALLOWED, "WMDRM ITA does not allow protected content with high security level for this release." ) CHK_ERR( MF_E_TEST_SIGNED_COMPONENTS_NOT_ALLOWED, "WMDRM ITA cannot allow the requested action for the content as one or more components is not properly signed." ) CHK_ERR( MF_E_ITA_UNSUPPORTED_ACTION, "WMDRM ITA does not support the requested action." ) CHK_ERR( MF_E_ITA_ERROR_PARSING_SAP_PARAMETERS, "WMDRM ITA encountered an error in parsing the Secure Audio Path parameters." ) CHK_ERR( MF_E_POLICY_MGR_ACTION_OUTOFBOUNDS, "The Policy Manager action passed in is invalid." ) CHK_ERR( MF_E_BAD_OPL_STRUCTURE_FORMAT, "The structure specifying Output Protection Level is not the correct format." ) CHK_ERR( MF_E_ITA_UNRECOGNIZED_ANALOG_VIDEO_PROTECTION_GUID, "WMDRM ITA does not recognize the Explicit Analog Video Output Protection guid specified in the license." ) CHK_ERR( MF_E_NO_PMP_HOST, "IMFPMPHost object not available." ) CHK_ERR( MF_E_ITA_OPL_DATA_NOT_INITIALIZED, "WMDRM ITA could not initialize the Output Protection Level data." ) CHK_ERR( MF_E_ITA_UNRECOGNIZED_ANALOG_VIDEO_OUTPUT, "WMDRM ITA does not recognize the Analog Video Output specified by the OTA." ) CHK_ERR( MF_E_ITA_UNRECOGNIZED_DIGITAL_VIDEO_OUTPUT, "WMDRM ITA does not recognize the Digital Video Output specified by the OTA." ) CHK_ERR( MF_E_RESOLUTION_REQUIRES_PMP_CREATION_CALLBACK, "The protected stream cannot be resolved without the callback PKEY_PMP_Creation_Callback in the configuration property store." ) CHK_ERR( MF_E_INVALID_AKE_CHANNEL_PARAMETERS, "A valid hostname and port number could not be found in the DTCP parameters." ) CHK_ERR( MF_E_CONTENT_PROTECTION_SYSTEM_NOT_ENABLED, "The content protection system was not enabled by the application." ) CHK_ERR( MF_E_UNSUPPORTED_CONTENT_PROTECTION_SYSTEM, "The content protection system is not supported." ) CHK_ERR( MF_E_DRM_MIGRATION_NOT_SUPPORTED, "DRM migration is not supported for the content." ) CHK_ERR( MF_E_HDCP_AUTHENTICATION_FAILURE, "Authentication of the HDCP link failed." ) CHK_ERR( MF_E_HDCP_LINK_FAILURE, "The HDCP link failed after being established." ) CHK_ERR( MF_E_CLOCK_INVALID_CONTINUITY_KEY, "The continuity key supplied is not currently valid." ) CHK_ERR( MF_E_CLOCK_NO_TIME_SOURCE, "No Presentation Time Source has been specified." ) CHK_ERR( MF_E_CLOCK_STATE_ALREADY_SET, "The clock is already in the requested state." ) CHK_ERR( MF_E_CLOCK_NOT_SIMPLE, "The clock has too many advanced features to carry out the request." ) CHK_ERR( MF_E_NO_MORE_DROP_MODES, "The component does not support any more drop modes." ) CHK_ERR( MF_E_NO_MORE_QUALITY_LEVELS, "The component does not support any more quality levels." ) CHK_ERR( MF_E_DROPTIME_NOT_SUPPORTED, "The component does not support drop time functionality." ) CHK_ERR( MF_E_QUALITYKNOB_WAIT_LONGER, "Quality Manager needs to wait longer before bumping the Quality Level up." ) CHK_ERR( MF_E_QM_INVALIDSTATE, "Quality Manager is in an invalid state. Quality Management is off at this moment." ) CHK_ERR( MF_E_TRANSCODE_NO_CONTAINERTYPE, "No transcode output container type is specified." ) CHK_ERR( MF_E_TRANSCODE_PROFILE_NO_MATCHING_STREAMS, "The profile does not have a media type configuration for any selected source streams." ) CHK_ERR( MF_E_TRANSCODE_NO_MATCHING_ENCODER, "Cannot find an encoder MFT that accepts the user preferred output type." ) CHK_ERR( MF_E_TRANSCODE_INVALID_PROFILE, "The profile is invalid." ) CHK_ERR( MF_E_ALLOCATOR_NOT_INITIALIZED, "Memory allocator is not initialized." ) CHK_ERR( MF_E_ALLOCATOR_NOT_COMMITED, "Memory allocator is not committed yet." ) CHK_ERR( MF_E_ALLOCATOR_ALREADY_COMMITED, "Memory allocator has already been committed." ) CHK_ERR( MF_E_STREAM_ERROR, "An error occurred in media stream." ) CHK_ERR( MF_E_INVALID_STREAM_STATE, "Stream is not in a state to handle the request." ) CHK_ERR( MF_E_HW_STREAM_NOT_CONNECTED, "Hardware stream is not connected yet." ) CHK_ERR( MF_E_NO_CAPTURE_DEVICES_AVAILABLE, "No capture devices are available." ) CHK_ERR( MF_E_CAPTURE_SINK_OUTPUT_NOT_SET, "No output was set for recording." ) CHK_ERR( MF_E_CAPTURE_SINK_MIRROR_ERROR, "The current capture sink configuration does not support mirroring." ) CHK_ERR( MF_E_CAPTURE_SINK_ROTATE_ERROR, "The current capture sink configuration does not support rotation." ) CHK_ERR( MF_E_CAPTURE_ENGINE_INVALID_OP, "The op is invalid." ) CHK_ERR( MF_E_CAPTURE_ENGINE_ALL_EFFECTS_REMOVED, "The effects previously added were incompatible with the new topology which caused all effects to be removed." ) CHK_ERR( MF_E_CAPTURE_SOURCE_NO_INDEPENDENT_PHOTO_STREAM_PRESENT, "The current capture source does not have an independent photo stream." ) CHK_ERR( MF_E_CAPTURE_SOURCE_NO_VIDEO_STREAM_PRESENT, "The current capture source does not have a video stream." ) CHK_ERR( MF_E_CAPTURE_SOURCE_NO_AUDIO_STREAM_PRESENT, "The current capture source does not have an audio stream." ) CHK_ERR( MF_E_CAPTURE_SOURCE_DEVICE_EXTENDEDPROP_OP_IN_PROGRESS, "The capture source device has an asynchronous extended property operation in progress." ) CHK_ERR( MF_E_CAPTURE_PROPERTY_SET_DURING_PHOTO, "A property cannot be set because a photo or photo sequence is in progress." ) CHK_ERR( MF_E_CAPTURE_NO_SAMPLES_IN_QUEUE, "No more samples in queue." ) CHK_ERR( MF_E_HW_ACCELERATED_THUMBNAIL_NOT_SUPPORTED, "Hardware accelerated thumbnail generation is not supported for the currently selected mediatype on the mediacapture stream." ) CHK_ERR( MF_E_UNSUPPORTED_CAPTURE_DEVICE_PRESENT, "Capture device that is present on the system is not supported by Media Foundation." ) CHK_ERR( MF_E_TIMELINECONTROLLER_UNSUPPORTED_SOURCE_TYPE, "Media Source type is not supported in Media Timeline Controller scenarios." ) CHK_ERR( MF_E_TIMELINECONTROLLER_NOT_ALLOWED, "Operation is not allowed when Media Timeline Controller is attached." ) CHK_ERR( MF_E_TIMELINECONTROLLER_CANNOT_ATTACH, "Attaching Media Timeline Controller is blocked because of the current state of the object." ) CHK_ERR( MF_E_MEDIA_EXTENSION_APPSERVICE_CONNECTION_FAILED, "Connection to app service providing a media extension failed." ) CHK_ERR( MF_E_MEDIA_EXTENSION_APPSERVICE_REQUEST_FAILED, "App service providing a media extension failed to process the request." ) CHK_ERR( MF_E_MEDIA_EXTENSION_PACKAGE_INTEGRITY_CHECK_FAILED, "Package integrity check for app failed." ) CHK_ERR( MF_E_MEDIA_EXTENSION_PACKAGE_LICENSE_INVALID, "License check for app failed." )
104.66055
336
0.817438
[ "object", "vector", "transform" ]
b60021ff39e77a2fba72d96b48d2752f3778b9e6
2,333
cpp
C++
fboss/agent/hw/bcm/BcmControlPlaneQueueManager.cpp
dhtech/fboss
f8c87a0d2855acdcf92e358bc900200cfa1a31bf
[ "BSD-3-Clause" ]
1
2018-10-11T08:45:23.000Z
2018-10-11T08:45:23.000Z
fboss/agent/hw/bcm/BcmControlPlaneQueueManager.cpp
dhtech/fboss
f8c87a0d2855acdcf92e358bc900200cfa1a31bf
[ "BSD-3-Clause" ]
2
2018-10-06T18:29:44.000Z
2018-10-07T16:46:04.000Z
fboss/agent/hw/bcm/BcmControlPlaneQueueManager.cpp
dhtech/fboss
f8c87a0d2855acdcf92e358bc900200cfa1a31bf
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "fboss/agent/hw/bcm/BcmControlPlaneQueueManager.h" #include "fboss/agent/hw/bcm/BcmError.h" #include "fboss/agent/hw/bcm/BcmPlatform.h" #include "fboss/agent/hw/bcm/BcmSwitch.h" #include "fboss/agent/hw/bcm/BcmStatsConstants.h" namespace facebook { namespace fboss { const std::vector<BcmCosQueueCounterType>& BcmControlPlaneQueueManager::getQueueCounterTypes() const { static const std::vector<BcmCosQueueCounterType> types = { {cfg::StreamType::MULTICAST, BcmCosQueueStatType::DROPPED_PACKETS, BcmCosQueueCounterScope::QUEUES, "in_dropped_pkts"}, {cfg::StreamType::MULTICAST, BcmCosQueueStatType::OUT_PACKETS, BcmCosQueueCounterScope::QUEUES, "in_pkts"} }; return types; } BcmPortQueueConfig BcmControlPlaneQueueManager::getCurrentQueueSettings() const { // TODO(joseph5wu) Will implement it when we support getting multicast queue // settings return BcmPortQueueConfig({}, {}); } int BcmControlPlaneQueueManager::getNumQueues( cfg::StreamType streamType) const { // if platform doesn't support cosq, return maxCPUQueue_ if (!hw_->getPlatform()->isCosSupported()) { return maxCPUQueue_; } // cpu only have multicast if (streamType == cfg::StreamType::MULTICAST) { return cosQueueGports_.multicast.size(); } throw FbossError( "Failed to retrieve queue size because unsupported StreamType: ", cfg::_StreamType_VALUES_TO_NAMES.find(streamType)->second); } opennsl_gport_t BcmControlPlaneQueueManager::getQueueGPort( cfg::StreamType streamType, int queueIdx) const { if (!hw_->getPlatform()->isCosSupported()) { throw FbossError( "Failed to retrieve queue gport because platform doesn't support cosq"); } // cpu only have multicast if (streamType == cfg::StreamType::MULTICAST) { return cosQueueGports_.multicast.at(queueIdx); } throw FbossError( "Failed to retrieve queue gport because unsupported StreamType: ", cfg::_StreamType_VALUES_TO_NAMES.find(streamType)->second); } }} //facebook::fboss
34.820896
79
0.744535
[ "vector" ]
b601529d07a962c29db47cc54cfa65f6d6b6bea3
2,668
hh
C++
alps/include/alps/pegasus/region.hh
liujiawinds/sparkle
23099cead99603a997803af9f66e17e17161faa2
[ "Apache-2.0" ]
40
2016-03-15T20:55:01.000Z
2021-12-01T11:45:43.000Z
alps/include/alps/pegasus/region.hh
liujiawinds/sparkle
23099cead99603a997803af9f66e17e17161faa2
[ "Apache-2.0" ]
18
2016-05-19T11:10:13.000Z
2020-03-18T01:42:49.000Z
alps/include/alps/pegasus/region.hh
liujiawinds/sparkle
23099cead99603a997803af9f66e17e17161faa2
[ "Apache-2.0" ]
19
2016-06-03T16:12:25.000Z
2022-02-18T07:16:54.000Z
/* * (c) Copyright 2016 Hewlett Packard Enterprise Development LP * * 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 _ALPS_PEGASUS_REGION_BASE_HH_ #define _ALPS_PEGASUS_REGION_BASE_HH_ #include <vector> #include "alps/pegasus/interleave_group.hh" namespace alps { //forward declarations class AddressSpace; class RegionFile; typedef uint64_t RegionId; /** * \brief Persistent memory region. * * \details * A base class that represents a persistent memory region in the * logical address space (alps::AddressSpace). * * A region is instantiated by mapping (and optionally binding) a region file * (or a set of region files) to an AddressSpace object. * */ class Region { public: Region(AddressSpace* address_space, RegionFile* region_file) : region_id_(0xBEEF), address_space_(address_space), file_(region_file) { } /** * \brief Returns the region file backing this region. */ RegionFile* file() { return file_; } loff_t length() { return length_; } /** * \brief Returns a global identifier identifying the region. */ RegionId id() { return region_id_; } /** * \brief Returns the Address Space object the region is mapped to. */ AddressSpace* address_space() { return address_space_; } /** * \brief Sets interleave group hint for pages mapped in the range * [\a offset, \a offset + \a length). */ ErrorCode set_interleave_group(loff_t offset, loff_t length, const std::vector<InterleaveGroup>& vig); /** * \brief Returns assigned interleave group for pages mapped in the * range [\a offset, \a offset + \a length). */ ErrorCode interleave_group(loff_t offset, loff_t length, std::vector<InterleaveGroup>* vig); protected: RegionId region_id_; AddressSpace* address_space_; loff_t length_; ///< cached value of the backing file's length RegionFile* file_; ///< the file backing the persistent memory region }; } // namespace alps #endif // _ALPS_PEGASUS_REGION_BASE_HH_
26.156863
106
0.675787
[ "object", "vector" ]
b601edda165e3ef8ab0dac261ff985d618a7f5ee
7,983
hpp
C++
src/algebraiccontainers/algebraiccontainers_algebraicvector.hpp
meteoritenhagel/fractional-pde
a740e3d5c88ed68bb57cb15b420d2b7e2d8a52c6
[ "MIT" ]
null
null
null
src/algebraiccontainers/algebraiccontainers_algebraicvector.hpp
meteoritenhagel/fractional-pde
a740e3d5c88ed68bb57cb15b420d2b7e2d8a52c6
[ "MIT" ]
null
null
null
src/algebraiccontainers/algebraiccontainers_algebraicvector.hpp
meteoritenhagel/fractional-pde
a740e3d5c88ed68bb57cb15b420d2b7e2d8a52c6
[ "MIT" ]
null
null
null
#include <cassert> #include <cmath> #include <iomanip> #include <iostream> #include <vector> #include "containerfactory.h" template<class floating> AlgebraicVector<floating> operator* (const floating scalar, const AlgebraicVector<floating> &B) { AlgebraicVector<floating> tmp(B); tmp.scale(scalar); return tmp; } // GH //template<class floating> //AlgebraicVector<floating>&& operator* (const floating alpha, AlgebraicVector<floating> &&B) //{ //B.scale(alpha); //return B; //} // public: template<class floating> AlgebraicVector<floating>::AlgebraicVector(const ProcessingUnit<floating> processing_unit, ArrayPointerType data) : _container_factory(processing_unit), _data(data) {} template<class floating> AlgebraicVector<floating>::AlgebraicVector(AlgebraicVector<floating> const &other) : _container_factory(other._container_factory), _data(initialize_pointer_by_copying(other)) {} template<class floating> AlgebraicVector<floating>& AlgebraicVector<floating>::move_to(const ProcessingUnit<floating> processing_unit) { _container_factory = ContainerFactory<floating>(processing_unit); _data->move_to(processing_unit->get_memory_manager()); return *this; } template<class floating> AlgebraicVector<floating>& AlgebraicVector<floating>::operator=(const AlgebraicVector<floating> &other) { assert(typeid(*this->get_processing_unit()) == typeid(*other.get_processing_unit()) && "Processing Units must be identical."); assert(is_valid() && "ERROR: Object not initialized"); _container_factory = other._container_factory; access_array() = other.access_array(); return *this; } template<class floating> AlgebraicVector<floating>& AlgebraicVector<floating>::operator=(AlgebraicVector<floating> &&other) { if (is_valid()) { assert(typeid(*this->get_processing_unit()) == typeid(*other.get_processing_unit()) && "Processing Units must be identical."); access_array() = std::move(other.access_array()); other._data = nullptr; } else { _container_factory = std::move(other._container_factory); _data = std::move(other._data); } return *this; } template<class floating> floating* AlgebraicVector<floating>::data() { return access_array().data(); } template<class floating> const floating* AlgebraicVector<floating>::data() const { return access_array().data(); } template<class floating> floating& AlgebraicVector<floating>::operator[](const SizeType index) { #ifndef NDEBUG assert(typeid(*get_processing_unit()) == typeid(*std::make_shared<Cpu<floating>>()) && "Must be on Cpu"); #endif return access_array()[index]; } template<class floating> floating const & AlgebraicVector<floating>::operator[](const SizeType index) const { #ifndef NDEBUG assert(typeid(*get_processing_unit()) == typeid(*std::make_shared<Cpu<floating>>()) && "Must be on Cpu"); #endif return access_array()[index]; } template<class floating> typename AlgebraicVector<floating>::SizeType AlgebraicVector<floating>::size() const { return access_array().size(); } template<class floating> ContainerFactory<floating> AlgebraicVector<floating>::get_container_factory() const { ContainerFactory<floating> factory(get_processing_unit()); return factory; } template<class floating> ProcessingUnit<floating> AlgebraicVector<floating>::get_processing_unit() const { return _container_factory.get_processing_unit(); } template<class floating> floating AlgebraicVector<floating>::get_euclidean_norm() const { const floating sum = scalarProduct(*this, *this); return sqrt(sum); } template<class floating> floating AlgebraicVector<floating>::get_maximum_norm() const { const auto index = get_processing_unit()->ixamax(size(), data(), 1); DeviceScalar<floating> maximum(data()[index], get_processing_unit()->get_memory_manager()); maximum.move_to(std::make_shared<CpuManager>()); return maximum.value(); } template<class floating> std::string AlgebraicVector<floating>::display(std::string name) const { return access_array().display(name); } template<class floating> AlgebraicVector<floating>& AlgebraicVector<floating>::add(AlgebraicVector<floating> const &B, floating const scalar) { assert( this->size() == B.size() ); // identical dimensions? assert(typeid(*this->get_processing_unit()) == typeid(*B.get_processing_unit()) && "Processing Units must be identical."); unsigned int const N = this->size(); floating const * const b_arraystart = B.data(); floating * const c_arraystart = this->data(); unsigned int const inc = 1; get_processing_unit()->xaxpy(N, scalar, b_arraystart, inc, c_arraystart, inc); return *this; } template<class floating> AlgebraicVector<floating> AlgebraicVector<floating>::operator+(const AlgebraicVector &B) const { assert(typeid(*this->get_processing_unit()) == typeid(*B.get_processing_unit()) && "Processing Units must be identical."); auto tmp = *this; return tmp.add(B); } template<class floating> AlgebraicVector<floating>& AlgebraicVector<floating>::operator+=(const AlgebraicVector &B) { assert(typeid(*this->get_processing_unit()) == typeid(*B.get_processing_unit()) && "Processing Units must be identical."); return this->add(B); } template<class floating> AlgebraicVector<floating> AlgebraicVector<floating>::operator-(const AlgebraicVector &B) const { assert(typeid(*this->get_processing_unit()) == typeid(*B.get_processing_unit()) && "Processing Units must be identical."); auto tmp = *this; return tmp.add(B, -1.0); } template<class floating> AlgebraicVector<floating> AlgebraicVector<floating>::operator*(const AlgebraicMatrix<floating> &A) const { assert(typeid(*this->get_processing_unit()) == typeid(*A.get_processing_unit()) && "Processing Units must be identical."); auto res = *A.get_container_factory().create_array(A.get_num_cols()); floating const *const pA = A.data(); floating const *const pu = this->data(); // pointer to memory of input vector floating *const pf = res.data(); // pointer to memory of output vector floating const alpha = 1.0; floating const beta = 0.0; unsigned int const M = A.get_num_rows(); unsigned int const N = A.get_num_cols(); unsigned int const LDA = M; // since transposed get_processing_unit()->xgemv(OperationType::Transposed, M, N, alpha, pA, LDA, pu, 1, beta, pf, 1); return res; } template<class floating> void AlgebraicVector<floating>::scale(floating const scalar) { unsigned int const N = this->size(); floating* arraystart = this->data(); unsigned int const incx = 1; // spacing between elements = 1 get_processing_unit()->xscal(N, scalar, arraystart, incx); return; } // private: template<class floating> bool AlgebraicVector<floating>::is_valid() const { return (_data != nullptr); } template<class floating> typename AlgebraicVector<floating>::ArrayDataType& AlgebraicVector<floating>::access_array() { assert(is_valid() && "ERROR: Object not initialized!"); return *_data; } template<class floating> typename AlgebraicVector<floating>::ArrayDataType const & AlgebraicVector<floating>::access_array() const { assert(is_valid() && "ERROR: Object not initialized!"); return *_data; } template<class floating> typename AlgebraicVector<floating>::ArrayPointerType AlgebraicVector<floating>::initialize_pointer_by_copying(const AlgebraicVector<floating>& other) const { assert(typeid(*this->get_processing_unit()) == typeid(*other.get_processing_unit()) && "Processing Units must be identical."); auto ptr = std::make_shared<DeviceArray<floating>>(other.access_array()); return ptr; }
32.717213
156
0.705624
[ "object", "vector" ]
b60a3f1534f0db01feb458695a4394f2f095c8ae
1,872
hpp
C++
rpi_gpio.hpp
markondej/rpi_gpio
6a665e7a4eac59648e8bd87fb580c62b614fa11f
[ "BSD-3-Clause" ]
1
2022-02-01T18:17:31.000Z
2022-02-01T18:17:31.000Z
rpi_gpio.hpp
markondej/rpi_gpio
6a665e7a4eac59648e8bd87fb580c62b614fa11f
[ "BSD-3-Clause" ]
null
null
null
rpi_gpio.hpp
markondej/rpi_gpio
6a665e7a4eac59648e8bd87fb580c62b614fa11f
[ "BSD-3-Clause" ]
1
2022-02-01T11:57:39.000Z
2022-02-01T11:57:39.000Z
#pragma once #include <vector> #include <thread> #include <mutex> #include <atomic> #define GPIO_COUNT 28 #define GPIO0 0 #define GPIO1 1 #define GPIO2 2 #define GPIO3 3 #define GPIO4 4 #define GPIO5 5 #define GPIO6 6 #define GPIO7 7 #define GPIO8 8 #define GPIO9 9 #define GPIO10 10 #define GPIO11 11 #define GPIO12 12 #define GPIO13 13 #define GPIO14 14 #define GPIO15 15 #define GPIO16 16 #define GPIO17 17 #define GPIO18 18 #define GPIO19 19 #define GPIO20 20 #define GPIO21 21 #define GPIO22 22 #define GPIO23 23 #define GPIO24 24 #define GPIO25 25 #define GPIO26 26 #define GPIO27 27 namespace GPIO { struct Event { unsigned long long time; unsigned number; bool high; }; enum class Mode { In, Out }; enum class Resistor { PullUp, PullDown, Off }; class Controller { public: virtual ~Controller(); Controller(const Controller &) = delete; Controller(Controller &&) = delete; Controller &operator=(const Controller &) = delete; static Controller &GetInstance(); void SetMode(unsigned number, Mode mode); void SetResistor(unsigned number, Resistor resistor); void Set(unsigned number, bool active); bool Get(unsigned number); std::vector<Event> GetEvents(); void SetSchedule(std::vector<Event> schedule, unsigned long long scheduleInterval = 0); void Reset(); private: Controller(); static void IOEventThread(Controller *instance); std::thread *ioEventThread; std::mutex eventsAccess, scheduleAccess; unsigned long long scheduleInterval; std::atomic_bool stopped, reset; std::vector<Event> schedule; std::vector<Event> events; void *io; }; }
24.631579
99
0.63141
[ "vector" ]
b60d8b5b6e1a5e56698a932829e5b3069b2d9138
2,607
cpp
C++
LeetCode/Problems/Algorithms/#720_LongestWordInDictionary_sol1_64ms_29MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#720_LongestWordInDictionary_sol1_64ms_29MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#720_LongestWordInDictionary_sol1_64ms_29MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class TrieNode{ public: static const int ALPHABET_SIZE = 26; static const char FIRST_LETTER = 'a'; bool is_terminal_node; vector<TrieNode*> children; int max_len; int max_len_edge_id; TrieNode(bool is_terminal_node = false){ this->is_terminal_node = is_terminal_node; this->children.resize(ALPHABET_SIZE, NULL); this->max_len = 0; this->max_len_edge_id = -1; } void insert(const string& word){ TrieNode* node = this; for(char c: word){ short int edge_id = c - FIRST_LETTER; if(node->children[edge_id] == NULL){ node->children[edge_id] = new TrieNode(); } node = node->children[edge_id]; } node->is_terminal_node = true; } void dfs(TrieNode* node){ if(node != NULL){ for(short int edge_id = 0; edge_id < ALPHABET_SIZE; ++edge_id){ if(node->children[edge_id] != NULL){ dfs(node->children[edge_id]); bool consecutive_terminal_nodes = (node->is_terminal_node && node->children[edge_id]->is_terminal_node); bool better_max = (node->children[edge_id]->max_len + 1 > node->max_len || (node->children[edge_id]->max_len + 1 == node->max_len && edge_id < node->max_len_edge_id)); if(consecutive_terminal_nodes && better_max){ // update max_len (lexicographical order in case of equality) node->max_len = node->children[edge_id]->max_len + 1; node->max_len_edge_id = edge_id; } } } } } string get_longest_word(){ // compute max_len and max_len_edge_id dfs(this); // save longest_word string longest_word; TrieNode* node = this; while(node->max_len_edge_id != -1){ longest_word += char(node->max_len_edge_id + FIRST_LETTER); node = node->children[node->max_len_edge_id]; } return longest_word; } }; class Solution { public: string longestWord(vector<string>& words) { // mark root as a terminal node for convenience (for method get_longest_word()) TrieNode* trie = new TrieNode(true); for(const string& word: words){ trie->insert(word); } return trie->get_longest_word(); } };
36.208333
125
0.529344
[ "vector" ]
b6106c17cd083ebc922fb1b8f1b790441a0794a0
61,563
cc
C++
NodeModule.cc
T-amairi/IOTA
f7a212be681a002413219adca56f69bcdfbe8d17
[ "MIT" ]
3
2021-06-28T19:42:11.000Z
2021-08-11T08:23:10.000Z
NodeModule.cc
T-amairi/IOTA
f7a212be681a002413219adca56f69bcdfbe8d17
[ "MIT" ]
null
null
null
NodeModule.cc
T-amairi/IOTA
f7a212be681a002413219adca56f69bcdfbe8d17
[ "MIT" ]
1
2022-03-21T14:12:07.000Z
2022-03-21T14:12:07.000Z
#include "NodeModule.h" enum MessageType{SETTING,ISSUE,POW,UPDATE,ParasiteChainAttack,SplittingAttack,InitializationSplittingAttack,MaintainBalance}; Define_Module(NodeModule); std::vector<int> NodeModule::readCSV(bool IfExp) { auto env = cSimulation::getActiveEnvir(); auto currentRun = env->getConfigEx()->getActiveRunNumber(); std::vector<int> neib; std::fstream file; std::string path; if(IfExp) { path = "./topologies/exp_CSV/expander" + std::to_string(currentRun) + ".csv"; } else { path = "./topologies/ws_CSV/watts_strogatz" + std::to_string(currentRun) + ".csv"; } file.open(path,std::ios::in); if(!file.is_open()) throw std::runtime_error("Could not open expander CSV file"); std::string line; int count = 0; while(getline(file, line,'\n')) { if(count == getId() - 2) { std::istringstream templine(line); std::string data; bool test = false; while(std::getline(templine, data,',')) { if(test) { neib.push_back(atoi(data.c_str())); } test = true; } } count++; } file.close(); return neib; } pTr_S NodeModule::createSite(std::string ID) { pTr_S newTx = new Site; newTx->ID = ID; newTx->issuedBy = this; newTx->issuedTime = simTime(); return newTx; } pTr_S NodeModule::createGenBlock() { pTr_S GenBlock = createSite("Genesis"); GenBlock->isGenesisBlock = true; return GenBlock; } void NodeModule::DeleteTangle() { for(auto site : myTangle) { delete site; } } void NodeModule::printTangle() { std::fstream file; std::string path = "./data/tracking/TrackerTangle" + ID + ".txt"; remove(path.c_str()); file.open(path,std::ios::app); for(long unsigned int i = 0; i < myTangle.size(); i++) { file << myTangle[i]->ID << ";"; for(long unsigned int j = 0; j < myTangle[i]->approvedBy.size(); j++) { auto temp = myTangle[i]->approvedBy[j]; if(j == myTangle[i]->approvedBy.size() - 1) { file << temp->ID; } else { file << temp->ID << ","; } } file << std::endl; } file.close(); } void NodeModule::printTipsLeft() { std::fstream file; std::string path = "./data/tracking/NumberTips" + ID + ".txt"; //remove(path.c_str()); file.open(path,std::ios::app); file << myTips.size() << std::endl; file.close(); } void NodeModule::printStats() { std::fstream file; std::string path = "./data/tracking/Stats" + ID + ".txt"; //remove(path.c_str()); file.open(path,std::ios::app); file << getParentModule()->getName() << ";" << txCount << ";" << myTangle.size() << ";" << myTips.size() << ";" << myBuffer.size() << std::endl; file.close(); } void NodeModule::printChain() { std::fstream file; std::string path = "./data/tracking/Chain" + ID + ".txt"; remove(path.c_str()); file.open(path,std::ios::app); file << getId() - 2 << std::endl; for(auto DoubleSpendTx : myDoubleSpendTx) { for(auto tx : myTangle) { bool res = false; ifApp(tx,DoubleSpendTx->ID,res); if(res) { file << tx->ID << std::endl; } } } file.close(); path = "./data/tracking/LegitChain" + ID + ".txt"; remove(path.c_str()); file.open(path,std::ios::app); file << getId() - 2 << std::endl; for(auto DoubleSpendTx : myDoubleSpendTx) { for(auto tx : myTangle) { auto id = DoubleSpendTx->ID; id.erase(id.begin()); bool res = false; ifApp(tx,id,res); if(res) { file << tx->ID << std::endl; } } } file.close(); } void NodeModule::printBranchSize() { std::fstream file; std::string path = "./data/tracking/BranchSize" + ID + ".txt"; //remove(path.c_str()); file.open(path,std::ios::app); double PropRateMB = par("PropRateMB"); if(branch1.size() == 0) { file << PropRateMB << ";" << "null" << std::endl; } else if(branch1[0]== nullptr) { file << PropRateMB << ";" << "fail" << std::endl; } else { auto TxRoot = branch1[0]->S_approved[0]; int count = 0; for(auto tx : myTangle) { if(tx->issuedTime > TxRoot->issuedTime) { bool res1 = false; ifApp(tx,branch1[0]->ID,res1); bool res2 = false; ifApp(tx,branch2[0]->ID,res2); if(res1 && res2) { count++; } } } file << PropRateMB <<";" << count << ";" << branch1.size() << ";" << branch2.size() << std::endl; } file.close(); } void NodeModule::printDiffTxChain() { std::fstream file; std::string path = "./data/tracking/DiffTxChain" + ID + ".txt"; //remove(path.c_str()); file.open(path,std::ios::app); if(myDoubleSpendTx.size() == 0) { file << "null" << std::endl; } else { double prop = par("PropComputingPower"); file << prop << ";"; for(auto DoubleSpendTx : myDoubleSpendTx) { file << DoubleSpendTx->ID << ";"; int c1 = 0; int c2 = 0; for(auto tx : myTangle) { if(tx->issuedTime >= DoubleSpendTx->issuedTime && tx->ID != DoubleSpendTx->ID) { bool res = false; ifApp(tx,DoubleSpendTx->ID,res); if(res) { c1++; } else { c2++; } } } file << c1 - c2 << std::endl; } } file.close(); } void NodeModule::getDoubleDepTx(pTr_S startTx, std::string& id) { VpTr_S visited; _getdoubledeptx(startTx,visited,id); for(auto tx : visited) { tx->isVisited = false; } startTx->isVisited = false; } void NodeModule::_getdoubledeptx(pTr_S current, VpTr_S& visited, std::string& id) { if(current->isVisited) { return; } else if(current->ID[0] == '-') { id = current->ID; current->isVisited = true; visited.push_back(current); return; } else if(current->S_approved.size() == 0) { current->isVisited = true; visited.push_back(current); return; } current->isVisited = true; visited.push_back(current); for(auto tx : current->S_approved) { if(!tx->isVisited) { _getdoubledeptx(tx,visited,id); } } } void NodeModule::ifApp(pTr_S startTx, std::string id, bool& res) { VpTr_S visited; _ifapp(startTx,visited,id,res); for(auto tx : visited) { tx->isVisited = false; } startTx->isVisited = false; } void NodeModule::_ifapp(pTr_S current, VpTr_S& visited, std::string id, bool& res) { if(current->isVisited) { return; } else if(current->ID == id) { res = true; current->isVisited = true; visited.push_back(current); return; } else if(current->S_approved.size() == 0) { current->isVisited = true; visited.push_back(current); return; } current->isVisited = true; visited.push_back(current); for(auto tx : current->S_approved) { if(!tx->isVisited) { _ifapp(tx,visited,id,res); } } } void NodeModule::computeConfidence(pTr_S startTx, double conf) { VpTr_S visited; _computeconfidence(startTx,visited,conf); for(auto tx : visited) { tx->isVisited = false; } startTx->isVisited = false; } void NodeModule::_computeconfidence(pTr_S current, VpTr_S& visited, double conf) { if(!current->isVisited) { current->isVisited = true; visited.push_back(current); current->confidence += conf; for(auto tx : current->S_approved) { if(!tx->isVisited) { _computeconfidence(tx,visited,conf); } } } } void NodeModule::getAvgConf(pTr_S startTx, double& avg) { VpTr_S visited; _getavgconf(startTx,visited,avg); for(auto tx : visited) { tx->isVisited = false; } startTx->isVisited = false; } void NodeModule::_getavgconf(pTr_S current, VpTr_S& visited, double& avg) { if(!current->isVisited) { current->isVisited = true; visited.push_back(current); avg += current->confidence; for(auto tx : current->S_approved) { if(!tx->isVisited) { _getavgconf(tx,visited,avg); } } } } int NodeModule::computeWeight(pTr_S tx) { VpTr_S visited; int weight = _computeweight(tx,visited); for(auto tx : visited) { tx->isVisited = false; } tx->isVisited = false; return weight + 1; } int NodeModule::_computeweight(pTr_S current, VpTr_S& visited) { if(current->isVisited) { return 0; } else if(current->approvedBy.size() == 0) { current->isVisited = true; visited.push_back(current); return 0; } current->isVisited = true; visited.push_back(current); int weight = 0; for(auto tx : current->approvedBy) { if(!tx->isVisited) { weight += 1 + _computeweight(tx,visited); } } return weight; } pTr_S NodeModule::getWalkStart(int backTrackDist) { int iterAdvances = intuniform(0,myTips.size() - 1); auto beginIter = myTips.begin(); if(myTips.size() > 1) { std::advance(beginIter,iterAdvances); } pTr_S current = beginIter->second; int count = backTrackDist; int approvesIndex; while(!current->isGenesisBlock && count > 0) { approvesIndex = intuniform(0,current->S_approved.size() - 1); current = current->S_approved.at(approvesIndex); --count; } return current; } void NodeModule::ReconcileTips(const VpTr_S& removeTips, std::map<std::string,pTr_S>& myTips) { std::map<std::string,pTr_S>::iterator it; for(auto& tipSelected : removeTips) { for(it = myTips.begin(); it != myTips.end();) { if(tipSelected->ID == it->first) { it = myTips.erase(it); } else { ++it; } } } } pTr_S NodeModule::attach(std::string ID, simtime_t attachTime, VpTr_S& chosen) { pTr_S new_tips = createSite(ID); for(auto& tipSelected : chosen) { tipSelected->approvedBy.push_back(new_tips); if(!(tipSelected->isApproved)) { tipSelected->approvedTime = attachTime; tipSelected->isApproved = true; } } new_tips->S_approved = chosen; ReconcileTips(chosen,myTips); myTangle.push_back(new_tips); myTips.insert({new_tips->ID,new_tips}); if(ID[0] == '-') { myDoubleSpendTx.push_back(new_tips); } return new_tips; } pTr_S NodeModule::WeightedRandomWalk(pTr_S start, double alphaVal, int &walk_time) { int walkCounts = 0; pTr_S current = start; while(current->isApproved) { walkCounts++; VpTr_S currentView = current->approvedBy; if(currentView.size() == 0) { break; } if(currentView.size() == 1) { current = currentView.front(); } else { std::vector<int> sitesWeight; int start_weight = computeWeight(current); std::vector<double> p; double sum_exp = 0.0; int weight; for(int j = 0; j < static_cast<int>(currentView.size()); j++) { weight = computeWeight(currentView[j]); sum_exp = sum_exp + double(exp(double(-alphaVal*(start_weight - weight)))); sitesWeight.push_back(weight); } double prob; for(int j = 0; j < static_cast<int>(sitesWeight.size()); j++) { prob = double(exp(double(-alphaVal*(start_weight - sitesWeight[j])))); prob = prob/sum_exp; p.push_back(prob); } int nextCurrentIndex = 0; double probWalkChoice = uniform(0.0,1.0); auto p1 = p; std::rotate(p1.rbegin(), p1.rbegin() + 1, p1.rend()); p1[0] = 0.0; std::vector<double> cs; cs.resize(p.size()); std::vector<double> cs1; cs1.resize(p1.size()); std::partial_sum(p.begin(),p.end(),cs.begin()); std::partial_sum(p1.begin(),p1.end(),cs1.begin()); for(int k = 0; k < static_cast<int>(cs.size()); k++) { if(probWalkChoice > cs1[k] && probWalkChoice < cs[k]) { nextCurrentIndex = k; break; } } current = currentView[nextCurrentIndex]; } } walk_time = walkCounts; current->countSelected++; return current; } pTr_S NodeModule::RandomWalk(pTr_S start, int &walk_time) { int walkCounts = 0; pTr_S current = start; while(current->isApproved) { walkCounts++; VpTr_S currentView = current->approvedBy; if(currentView.size() == 0) { break; } if(currentView.size() == 1) { current = currentView.front(); } else { std::vector<double> p; double prob = double(1/currentView.size()); for(int j = 0; j < static_cast<int>(currentView.size()); j++) { p.push_back(prob); } int nextCurrentIndex = 0; double probWalkChoice = uniform(0.0,1.0); auto p1 = p; std::rotate(p1.rbegin(), p1.rbegin() + 1, p1.rend()); p1[0] = 0.0; std::vector<double> cs; cs.resize(p.size()); std::vector<double> cs1; cs1.resize(p1.size()); std::partial_sum(p.begin(),p.end(),cs.begin()); std::partial_sum(p1.begin(),p1.end(),cs1.begin()); for(int k = 0; k < static_cast<int>(cs.size()); k++) { if(probWalkChoice > cs1[k] && probWalkChoice < cs[k]) { nextCurrentIndex = k; break; } } current = currentView[nextCurrentIndex]; } } walk_time = walkCounts; current->countSelected++; return current; } std::tuple<bool,std::string> NodeModule::IfLegitTip(pTr_S tx) { std::string id; getDoubleDepTx(tx,id); if(id.empty()) { return std::make_tuple(true,id); } id.erase(id.begin()); bool res = false; ifApp(tx,id,res); if(res) { return std::make_tuple(false,id); } return std::make_tuple(true,id); } bool NodeModule::IfConflict(std::tuple<bool,std::string> tup1, std::tuple<bool,std::string> tup2, pTr_S tx1, pTr_S tx2) { if(!std::get<0>(tup1) || !std::get<0>(tup2)) { return true; } else if(std::get<1>(tup1).empty() && std::get<1>(tup2).empty()) { return false; } else if(!std::get<1>(tup1).empty() && !std::get<1>(tup2).empty()) { return false; } else if(std::get<1>(tup1).empty() && !std::get<1>(tup2).empty()) { bool res = false; ifApp(tx1,std::get<1>(tup2),res); if(!res) { return false; } } else if(!std::get<1>(tup1).empty() && std::get<1>(tup2).empty()) { bool res = false; ifApp(tx2,std::get<1>(tup1),res); if(!res) { return false; } } return true; } int NodeModule::getConfidence(std::string id) { int count = 0; for(auto key : myTips) { auto tip = key.second; bool res = false; ifApp(tip,id,res); if(res) { count++; } } return count; } VpTr_S NodeModule::IOTA(double alphaVal, int W, int N) { if(myTips.size() == 1) { VpTr_S tipstoApprove; tipstoApprove.push_back(myTips.begin()->second); return tipstoApprove; } std::vector<std::tuple<pTr_S,int,int>> selected_tips; int walk_time; for(int i = 0; i < N; i++) { pTr_S tip; int w = intuniform(W,2*W); pTr_S startTx = getWalkStart(w); if(alphaVal == 0.0) { tip = RandomWalk(startTx,walk_time); } else { tip = WeightedRandomWalk(startTx,alphaVal,walk_time); } bool ifFind = false; for(auto& Tip : selected_tips) { if(std::get<0>(Tip)->ID == tip->ID) { std::get<1>(Tip)++; ifFind = true; break; } } if(!ifFind) { selected_tips.push_back(std::make_tuple(tip,1,walk_time)); } } std::sort(selected_tips.begin(), selected_tips.end(), [](const std::tuple<pTr_S,int,int>& tip1, const std::tuple<pTr_S,int,int>& tip2){return std::get<1>(tip1) > std::get<1>(tip2);}); EV << "Selected tips :\n"; for(auto tup : selected_tips) { EV << std::get<0>(tup)->ID << " chosen time : " << std::get<1>(tup) << " walk time : " << std::get<2>(tup) << std::endl; } VpTr_S tipstoApprove; if(selected_tips.size() == 1) { auto tup = IfLegitTip(std::get<0>(selected_tips[0])); if(std::get<0>(tup)) { tipstoApprove.push_back(std::get<0>(selected_tips[0])); } return tipstoApprove; } std::vector<std::tuple<pTr_S,int,int>> legitTips; std::set<std::string> DoNotCheck; std::tuple<bool,std::string> tup1; std::tuple<bool,std::string> tup2; for(auto tipTup : selected_tips) { auto tip = std::get<0>(tipTup); if(legitTips.empty()) { tup1 = IfLegitTip(tip); if(std::get<0>(tup1)) { legitTips.push_back(tipTup); } else { DoNotCheck.insert(tip->ID); } } else { tup2 = IfLegitTip(tip); if(std::get<0>(tup2)) { legitTips.push_back(tipTup); break; } else { DoNotCheck.insert(tip->ID); } } } if(legitTips.size() == 1) { tipstoApprove.push_back(std::get<0>(legitTips[0])); return tipstoApprove; } if(!IfConflict(tup1,tup2,std::get<0>(legitTips[0]),std::get<0>(legitTips[1]))) { tipstoApprove.push_back(std::get<0>(legitTips[0])); tipstoApprove.push_back(std::get<0>(legitTips[1])); return tipstoApprove; } int conf1 = getConfidence(std::get<0>(legitTips[0])->ID); int conf2 = getConfidence(std::get<0>(legitTips[1])->ID); if(conf1 >= conf2) { tipstoApprove.push_back(std::get<0>(legitTips[0])); DoNotCheck.insert(std::get<0>(legitTips[1])->ID); } else { tipstoApprove.push_back(std::get<0>(legitTips[1])); DoNotCheck.insert(std::get<0>(legitTips[0])->ID); tup1 = tup2; } legitTips.clear(); for(auto tipTup : selected_tips) { auto tip = std::get<0>(tipTup); if(tip->ID != tipstoApprove[0]->ID) { auto it = DoNotCheck.find(tip->ID); if(it == DoNotCheck.end()) { tup2 = IfLegitTip(tip); if(!IfConflict(tup1,tup2,tipstoApprove[0],tip)) { tipstoApprove.push_back(tip); break; } } } } return tipstoApprove; } VpTr_S NodeModule::GIOTA(double alphaVal, int W, int N) { for(auto& tx : myTangle) { tx->confidence = 0.0; tx->countSelected = 0; } VpTr_S chosenTips = IOTA(alphaVal,W,N); if(chosenTips.size() == 1) { return chosenTips; } VpTr_S filterTips; for(auto it = myTips.begin(); it != myTips.end(); ++it) { auto tip = it->second; for(int j = 0; j < static_cast<int>(chosenTips.size()); j++) { if(!(chosenTips[j]->ID == tip->ID)) { filterTips.push_back(tip); break; } } } if(filterTips.empty()) { return chosenTips; } for(auto tip : filterTips) { if(tip->countSelected != 0) { for(auto tx : tip->S_approved) { computeConfidence(tx,double(tip->countSelected/N)); } } } std::vector<std::pair<double,pTr_S>> avgConfTips; for(auto tip : filterTips) { double avg = 0.0; for(auto tx : tip->S_approved) { getAvgConf(tx,avg); } avgConfTips.push_back(std::make_pair(avg,tip)); } std::sort(avgConfTips.begin(), avgConfTips.end(),[](const std::pair<long double,pTr_S> &a, const std::pair<long double,pTr_S> &b){return a.first < b.first;}); auto tup1 = IfLegitTip(chosenTips[0]); auto tup2 = IfLegitTip(chosenTips[1]); for(auto pair : avgConfTips) { auto tip = pair.second; if(tip->ID != chosenTips[0]->ID && tip->ID != chosenTips[1]->ID) { auto tup3 = IfLegitTip(tip); if(std::get<0>(tup3)) { if(!IfConflict(tup1,tup3,chosenTips[0],tip) && !IfConflict(tup2,tup3,chosenTips[1],tip)) { chosenTips.push_back(tip); break; } } } } return chosenTips; } VpTr_S NodeModule::EIOTA(double p1, double p2, double lowAlpha, double highAlpha, int W, int N) { auto r = uniform(0.0,1.0); if(r < p1) { return IOTA(0.0,W,N); } else if(p1 <= r && r < p2) { return IOTA(lowAlpha,W,N); } return IOTA(highAlpha,W,N); } void NodeModule::updateTangle(MsgUpdate* Msg) { pTr_S newTx = new Site; newTx->ID = Msg->ID; newTx->issuedBy = Msg->issuedBy; newTx->issuedTime = simTime(); for(auto tipSelected : Msg->S_approved) { for(auto& tx : myTangle) { if(tx->ID == tipSelected) { newTx->S_approved.push_back(tx); tx->approvedBy.push_back(newTx); if(!(tx->isApproved)) { tx->approvedTime = simTime(); tx->isApproved = true; } std::map<std::string,pTr_S>::iterator it; for(it = myTips.begin(); it != myTips.end();) { if(tx->ID == it->first) { it = myTips.erase(it); break; } else { it++; } } } } } if(newTx->ID[0] == '-') { myDoubleSpendTx.push_back(newTx); } if(par("SplittingAttack") && strcmp(par("AttackID"),ID.c_str()) == 0 && !IfIniSP) { updateBranches(newTx); } myTips.insert({newTx->ID,newTx}); myTangle.push_back(newTx); } bool NodeModule::ifAddTangle(std::vector<std::string> S_approved) { for(auto selectedTip : S_approved) { auto it = std::find_if(myTangle.begin(), myTangle.end(), [&selectedTip](const pTr_S& tx) {return tx->ID == selectedTip;}); if(it == myTangle.end()) { return false; } } return true; } bool NodeModule::IfPresent(std::string txID) { auto it = std::find_if(myTangle.begin(), myTangle.end(), [&txID](const pTr_S& tx) {return tx->ID == txID;}); if(it != myTangle.end()) { return true; } auto it2 = std::find_if(myBuffer.begin(), myBuffer.end(), [&txID](const MsgUpdate* msg) {return msg->ID == txID;}); if(it2 != myBuffer.end()) { return true; } return false; } void NodeModule::updateBuffer() { bool test; while(1) { test = false; auto it = myBuffer.begin(); while(it != myBuffer.end()) { if(ifAddTangle((*it)->S_approved)) { test = true; EV << "Updating the Buffer : " << (*it)->ID << " can be added" << std::endl; updateTangle((*it)); delete (*it); it = myBuffer.erase(it); break; } else { it++; } } if(!test) { break; } } } bool NodeModule::IfAttackStage() { int count = NodeModuleNb - 1; double AttackStage = par("AttackStage"); for(SubmoduleIterator iter(getParentModule()); !iter.end(); iter++) { cModule *submodule = *iter; if(submodule->getId() != getId()) { NodeModule* node = check_and_cast<NodeModule*>(submodule); if(node->txCount >= node->txLimit*AttackStage) { count--; } } } if(count == 0) { return true; } return false; } VpTr_S NodeModule::getParasiteChain(pTr_S RootTip, std::string TargetID, int ChainLength, int NbTipsChain) { auto RootChain = createSite("-" + TargetID); RootChain->S_approved.push_back(RootTip); RootTip->approvedBy.push_back(RootChain); RootTip->isApproved = true; RootTip->approvedTime = simTime(); VpTr_S temp; temp.push_back(RootTip); ReconcileTips(temp,myTips); temp.clear(); VpTr_S TheChain; TheChain.push_back(RootChain); myDoubleSpendTx.push_back(RootChain); for(int i = 0; i < ChainLength; i++) { if(i == 0) { auto NodeChain = createSite(ID + std::to_string(txCount)); NodeChain->S_approved.push_back(RootChain); RootChain->approvedBy.push_back(NodeChain); RootChain->approvedTime = simTime(); RootChain->isApproved = true; TheChain.push_back(NodeChain); } else { txCount++; auto NodeChain = createSite(ID + std::to_string(txCount)); NodeChain->S_approved.push_back(TheChain.back()); TheChain.back()->approvedBy.push_back(NodeChain); TheChain.back()->approvedTime = simTime(); TheChain.back()->isApproved = true; TheChain.push_back(NodeChain); } } auto BackChain = TheChain.back(); for(int i = 0; i < NbTipsChain; i++) { txCount++; auto TipChain = createSite(ID + std::to_string(txCount)); if(i == 0) { TipChain->S_approved.push_back(BackChain); BackChain->approvedBy.push_back(TipChain); BackChain->approvedTime = simTime(); BackChain->isApproved = true; TheChain.push_back(TipChain); } else { TipChain->S_approved.push_back(BackChain); BackChain->approvedBy.push_back(TipChain); TheChain.push_back(TipChain); } } return TheChain; } void NodeModule::iniSplittingAttack() { txCount++; auto tx1 = createSite(ID + std::to_string(txCount)); txCount++; auto tx2 = createSite(ID + std::to_string(txCount)); auto tip1 = branch1[0]; auto tip2 = branch2[0]; tx1->S_approved.push_back(tip1); tx2->S_approved.push_back(tip2); tip1->approvedBy.push_back(tx1); tip2->approvedBy.push_back(tx2); if(!tip1->isApproved) { tip1->isApproved = true; tip1->approvedTime = simTime(); } if(!tip2->isApproved) { tip2->isApproved = true; tip2->approvedTime = simTime(); } branch1.push_back(tx1); branch2.push_back(tx2); } void NodeModule::updateBranches(pTr_S newTx) { bool res = false; ifApp(newTx,branch1[0]->ID,res); if(res) { branch1.push_back(newTx); } else { ifApp(newTx,branch2[0]->ID,res); if(res) { branch2.push_back(newTx); } } } pTr_S NodeModule::MaintainingBalance(int whichBranch) { VpTr_S Vtips; VpTr_S toIterOver; if(whichBranch == 2) { EV << "Chosen branche to be balanced : 2\n"; toIterOver = branch2; } else { EV << "Chosen branche to be balanced : 1\n"; toIterOver = branch1; } int countTips = 0; for(auto tx : toIterOver) { if(!tx->isApproved) { countTips++; } } bool Iftip = countTips <= NodeModuleNb - 1; if(Iftip) { for(auto tx : toIterOver) { if(tx->isApproved) { Vtips.push_back(tx); } } } else { for(auto tx : toIterOver) { if(!tx->isApproved) { Vtips.push_back(tx); } } } txCount++; auto tx = createSite(ID + std::to_string(txCount)); int r = intuniform(0,Vtips.size() - 1); auto tip = Vtips[r]; Vtips.erase(Vtips.begin() + r); tx->S_approved.push_back(tip); tip->approvedBy.push_back(tx); tip->isApproved = true; tip->approvedTime = simTime(); if(!Iftip) { VpTr_S temp; temp.push_back(tip); ReconcileTips(temp,myTips); } if(!Vtips.empty()) { r = intuniform(0,Vtips.size() - 1); tip = Vtips[r]; Vtips.erase(Vtips.begin() + r); tx->S_approved.push_back(tip); tip->approvedBy.push_back(tx); tip->isApproved = true; tip->approvedTime = simTime(); if(!Iftip) { VpTr_S temp; temp.push_back(tip); ReconcileTips(temp,myTips); } } if(whichBranch == 2) { branch2.push_back(tx); } else { branch1.push_back(tx); } myTangle.push_back(tx); myTips.insert({tx->ID,tx}); return tx; } void NodeModule::IfNodesfinished() { int count = NodeModuleNb - 1; bool IfOneFinished = false; for(SubmoduleIterator iter(getParentModule()); !iter.end(); iter++) { cModule *submodule = *iter; if(submodule->getId() != getId()) { NodeModule* node = check_and_cast<NodeModule*>(submodule); if(node->txCount >= node->txLimit) { count--; IfOneFinished = true; } } } if(count == 0) { EV << "All nodes have finished the simulation, can't initiate the attack" << std::endl; IfSimFinished = true; } else if(IfOneFinished && IfIniSP) { EV << "One node have finished the simulation, can't initiate the attack" << std::endl; IfSimFinished = true; } } void NodeModule::setTxLimitNodes() { EV << "Setting new txLimit for each node:" << std::endl; for(SubmoduleIterator iter(getParentModule()); !iter.end(); iter++) { cModule *submodule = *iter; if(submodule->getId() != getId()) { NodeModule* node = check_and_cast<NodeModule*>(submodule); node->txLimit += node->txCount; EV << "Node: " << submodule->getId() << ", new txLimit: " << node->txLimit << std::endl; } } } void NodeModule::initialize() { ID = "[" + std::to_string(getId() - 2) + "]"; mean = par("mean"); powTime = par("powTime"); txLimit = getParentModule()->par("transactionLimit"); for(SubmoduleIterator iter(getParentModule()); !iter.end(); iter++) { NodeModuleNb++; } genesisBlock = createGenBlock(); myTangle.push_back(genesisBlock); myTips.insert({"Genesis",genesisBlock}); msgIssue = new cMessage("Issuing a new transaction",ISSUE); msgPoW = new cMessage("PoW time",POW); msgUpdate = new cMessage("Broadcasting a new transaction",UPDATE); MsgP = new MsgPoW; if(strcmp(getParentModule()->getName(),"Expander") == 0 || strcmp(getParentModule()->getName(),"WattsStrogatz") == 0) { EV << "Setting up connections for Watts Strogatz & Expander topologies :" << std::endl; std::vector<int> neibIdx; if(strcmp(getParentModule()->getName(),"Expander") == 0) { neibIdx = readCSV(true); } else { neibIdx = readCSV(false); } if(neibIdx.at(0) != -1) { for(int idx : neibIdx) { cModule * nodeNeib = getParentModule()->getSubmodule("Nodes",idx); if(nodeNeib == nullptr) { throw std::runtime_error("Node not found while setting connections for exp & Ws topo : check the number of nodes set in the python script and in the .ned file, they have to be identical !"); } cDelayChannel *channel1 = nullptr; cDelayChannel *channel2 = nullptr; if(getParentModule()->par("ifRandDelay")) { double minDelay = getParentModule()->par("minDelay"); double maxDelay = getParentModule()->par("maxDelay"); double delay = uniform(minDelay,maxDelay); channel1 = cDelayChannel::create("Channel"); channel2 = cDelayChannel::create("Channel"); channel1->setDelay(delay); channel2->setDelay(delay); } else { channel1 = cDelayChannel::create("Channel"); channel2 = cDelayChannel::create("Channel"); channel1->setDelay(getParentModule()->par("delay")); channel2->setDelay(getParentModule()->par("delay")); } setGateSize("NodeOut",gateSize("NodeOut") + 1); setGateSize("NodeIn",gateSize("NodeIn") + 1); nodeNeib->setGateSize("NodeIn",nodeNeib->gateSize("NodeIn") + 1); nodeNeib->setGateSize("NodeOut",nodeNeib->gateSize("NodeOut") + 1); auto gOut = gate("NodeOut",gateSize("NodeOut") - 1); auto gIn = nodeNeib->gate("NodeIn", nodeNeib->gateSize("NodeIn") - 1); gOut->connectTo(gIn,channel1); gOut = nodeNeib->gate("NodeOut", nodeNeib->gateSize("NodeOut") - 1); gIn = gate("NodeIn",gateSize("NodeIn") - 1); gOut->connectTo(gIn,channel2); EV << getId() - 2 << " <---> " << nodeNeib->getId() - 2 << std::endl; } } auto msgSetting = new cMessage("Connections are set !",SETTING); EV << "Connections are set !" << std::endl; scheduleAt(simTime(), msgSetting); } else { NeighborsNumber = gateSize("NodeOut"); if(getParentModule()->par("ifRandDelay")) { for(int i = 0; i < NeighborsNumber; i++) { cGate *g = gate("NodeOut",i); cDelayChannel *channel = check_and_cast<cDelayChannel*>(g->getChannel()); channel->setDelay(9223372.0); } auto msgSetting = new cMessage("Setting random delays",SETTING); EV << "Setting random delays !" << std::endl; scheduleAt(simTime(), msgSetting); } else { EV << "Initialization complete" << std::endl; scheduleAt(simTime() + exponential(mean), msgIssue); } } } void NodeModule::handleMessage(cMessage * msg) { if(msg->getKind() == SETTING) { delete msg; if(strcmp(getParentModule()->getName(),"Expander") == 0 || strcmp(getParentModule()->getName(),"WattsStrogatz") == 0) { NeighborsNumber = gateSize("NodeOut"); for(int i = 0; i < NeighborsNumber; i++) { cGate *g = gate("NodeOut",i); auto channel = g->getChannel(); channel->callInitialize(); } } else { cModule *mymodule = getParentModule()->getSubmodule("Nodes",getId() - 2); if(mymodule == nullptr) { throw std::runtime_error("Node not found while setting random delays"); } double minDelay = getParentModule()->par("minDelay"); double maxDelay = getParentModule()->par("maxDelay"); for(int i = 0; i < NeighborsNumber; i++) { cGate *g1 = gate("NodeOut",i); cModule *Adjmodule; double delay; double maxdbl = 9223372.0; for(SubmoduleIterator iter(getParentModule()); !iter.end(); iter++) { Adjmodule = *iter; if(g1->pathContains(Adjmodule) && Adjmodule->getId() != getId()) { break; } } cDelayChannel *channel1 = check_and_cast<cDelayChannel*>(g1->getChannel()); delay = channel1->getDelay().dbl(); for(int j = 0; j < Adjmodule->gateSize("NodeOut"); j++) { cGate *g2 = Adjmodule->gate("NodeOut",j); if(g2->pathContains(mymodule)) { cDelayChannel *channel2 = check_and_cast<cDelayChannel*>(g2->getChannel()); if(channel2->getDelay() != maxdbl && delay == maxdbl) { delay = channel2->getDelay().dbl(); channel1->setDelay(delay); } else if(channel2->getDelay() == maxdbl && delay != maxdbl) { channel2->setDelay(delay); } else { delay = uniform(minDelay,maxDelay); channel1->setDelay(delay); channel2->setDelay(delay); } break; } } } } EV << "Initialization complete" << std::endl; scheduleAt(simTime() + exponential(mean), msgIssue); } else if(msg->getKind() == ParasiteChainAttack) { delete msg; EV << "Building the parasite chain" << std::endl; VpTr_S cpyTx; bool test1 = false; bool test2 = false; for(auto tx : myTangle) { std::string id = par("AttackID"); if(tx->ID.find(id) != std::string::npos && tx->approvedBy.size() > 2) { cpyTx.push_back(tx); } } std::sort(cpyTx.begin(), cpyTx.end(), [](const pTr_S& tx1, const pTr_S& tx2){return tx1->issuedTime > tx2->issuedTime;}); pTr_S TargetTx; if(cpyTx.empty()) { EV << "Can not find a legit transaction for the chain, retrying later" << std::endl; IfAttack = false; scheduleAt(simTime() + exponential(mean), msgIssue); } else { test1 = true; TargetTx = cpyTx[0]; cpyTx.clear(); } pTr_S RootTx; std::vector<std::pair<int,pTr_S>> cpyTxLegit; if(test1) { for(auto tx : myTangle) { if(!tx->isGenesisBlock && tx->approvedBy.size() > 2) { cpyTx.push_back(tx); } } for(auto tx : cpyTx) { if(tx->issuedTime < TargetTx->issuedTime) { cpyTxLegit.push_back(std::make_pair(computeWeight(tx),tx)); } } if(!cpyTxLegit.empty()) { std::sort(cpyTxLegit.begin(), cpyTxLegit.end(), [](const std::pair<int,pTr_S>& p1, const std::pair<int,pTr_S>& p2){return p1.first > p2.first;}); RootTx = cpyTxLegit.at(0).second; test2 = true; } else { cpyTx.clear(); EV << "Can not find a legit transaction for the chain, retrying later" << std::endl; IfAttack = false; scheduleAt(simTime() + exponential(mean), msgIssue); } } if(test1 && test2) { cpyTxLegit.clear(); cpyTx.clear(); auto T_diff = TargetTx->issuedTime - RootTx->issuedTime; double meanPC = par("PropComputingPower"); meanPC = meanPC * mean.dbl(); int weightChain = int(T_diff.dbl()/meanPC); double PropChainTips = par("PropChainTips"); int ChainLength = (int) weightChain*PropChainTips; int NbTipsChain = (int) weightChain*(1 - PropChainTips); EV << "Chain weight : " << weightChain << std::endl; auto TheChain = getParasiteChain(RootTx, TargetTx->ID, ChainLength, NbTipsChain); EV << "Launching a Parasite Chain Attack !" << std::endl; for(auto tx : TheChain) { myTangle.push_back(tx); if(!tx->isApproved) { myTips.insert({tx->ID,tx}); } for(int i = 0; i < NeighborsNumber; i++) { MsgUpdate * MsgU = new MsgUpdate; MsgU->ID = tx->ID; MsgU->issuedBy = tx->issuedBy; for(auto approvedTips : tx->S_approved) { MsgU->S_approved.push_back(approvedTips->ID); } msgUpdate->setContextPointer(MsgU); send(msgUpdate->dup(),"NodeOut",i); } } TheChain.clear(); } } else if(msg->getKind() == SplittingAttack) { delete msg; EV << "Starting a splitting attack" << std::endl; if(myTips.empty()) { EV << "There are no tips for the splitting attack, retrying later" << std::endl; IfAttack = false; scheduleAt(simTime() + exponential(mean), msgIssue); } else { auto tx1 = createSite(ID + std::to_string(txCount)); auto tx2 = createSite("-" + ID + std::to_string(txCount)); branch1.push_back(tx1); branch2.push_back(tx2); double PropRateMB = par("PropRateMB"); simtime_t rateMB = mean*PropRateMB; auto msgIni = new cMessage("Initializating the first tips for both branches",InitializationSplittingAttack); scheduleAt(simTime() + 2*rateMB, msgIni); } } else if(msg->getKind() == InitializationSplittingAttack) { double SizeBrancheProp = par("SizeBrancheProp"); EV << "Preparing the two branches in offline..." << std::endl; EV << "Branches size : " << branch1.size() + branch2.size() << std::endl; EV << "The threshold to reach : " << myTips.size()*SizeBrancheProp << std::endl; IfNodesfinished(); if(branch1.size() + branch2.size() >= myTips.size()*SizeBrancheProp && !IfSimFinished) { delete msg; VpTr_S cpyTip; for(auto tip : myTips) { cpyTip.push_back(tip.second); } std::sort(cpyTip.begin(), cpyTip.end(), [](const pTr_S& tip1, const pTr_S& tip2){return tip1->issuedTime > tip2->issuedTime;}); auto RootTip = cpyTip[0]; cpyTip.clear(); auto tx1 = branch1[0]; auto tx2 = branch2[0]; tx1->S_approved.push_back(RootTip); tx2->S_approved.push_back(RootTip); RootTip->approvedBy.push_back(tx1); RootTip->approvedBy.push_back(tx2); RootTip->approvedTime = simTime(); RootTip->isApproved = true; VpTr_S temp; temp.push_back(RootTip); ReconcileTips(temp,myTips); temp.clear(); myDoubleSpendTx.push_back(tx2); EV << "Reached ! Sending the first tips for the splitting attack" << std::endl; std::vector<VpTr_S> toSend; toSend.push_back(branch1); toSend.push_back(branch2); for(auto vec : toSend) { for(auto tx : vec) { if(!tx->isApproved) { myTips.insert({tx->ID,tx}); } myTangle.push_back(tx); for(int i = 0; i < NeighborsNumber; i++) { MsgUpdate * MsgU = new MsgUpdate; MsgU->ID = tx->ID; MsgU->issuedBy = tx->issuedBy; for(auto approvedTips : tx->S_approved) { MsgU->S_approved.push_back(approvedTips->ID); } msgUpdate->setContextPointer(MsgU); send(msgUpdate->dup(),"NodeOut",i); } } } IfAttackSP = true; IfIniSP = false; toSend.clear(); setTxLimitNodes(); } else if(!IfSimFinished) { EV << "Not reached ! Issuing new tips..." << std::endl; iniSplittingAttack(); double PropRateMB = par("PropRateMB"); simtime_t rateMB = mean*PropRateMB; scheduleAt(simTime() + 2*rateMB, msg); } else { delete msg; std::vector<VpTr_S> toSend; toSend.push_back(branch1); toSend.push_back(branch2); for(auto vec : toSend) { for(auto tx : vec) { delete tx; } } toSend.clear(); branch1[0] = nullptr; } } else if(msg->getKind() == MaintainBalance) { delete msg; if(!IfSimFinished) { IfNodesfinished(); if(!IfSimFinished) { countMB--; auto tx = MaintainingBalance(whichBranch); EV << "Updated the balance of the branches" << std::endl; EV << "With transaction : " << tx->ID << std::endl; EV << "countMB : " << countMB << std::endl; for(int i = 0; i < NeighborsNumber; i++) { MsgUpdate * MsgU = new MsgUpdate; MsgU->ID = tx->ID; MsgU->issuedBy = tx->issuedBy; for(auto approvedTips : tx->S_approved) { MsgU->S_approved.push_back(approvedTips->ID); } msgUpdate->setContextPointer(MsgU); send(msgUpdate->dup(),"NodeOut",i); } if(countMB == 0 && IfScheduleMB) { EV << "Checking the balance..." << std::endl; int diff = branch1.size() - branch2.size(); IfScheduleMB = false; if(diff != 0) { EV << "The weight of the two branches is not the same : maintaining..." << std::endl; if(diff > 0) { whichBranch = 2; } else { whichBranch = 1; } countMB = std::abs(diff); IfAttackSP = false; EV << "with countMB : " << countMB << std::endl; EV << "with whichBranch : " << whichBranch << std::endl; double PropRateMB = par("PropRateMB"); simtime_t rateMB = mean*PropRateMB; int temp = txCount; for(int i = 0; i < std::abs(diff); i++) { temp++; EV << "Sending " << ID + std::to_string(temp) << " with a delay of " << (i+1)*rateMB << std::endl; auto msgMB = new cMessage("Maintaining the balance between the two branches",MaintainBalance); scheduleAt(simTime() + (i+1)*rateMB, msgMB); } } else { IfAttackSP = true; EV << "The weight of the two branches is the same" << std::endl; } } else if(countMB == 0) { IfAttackSP = true; } } } else { EV << "The other nodes have finished the simulation, can't maintain the balance" << std::endl; } } else if(msg->getKind() == ISSUE) { if(txCount < txLimit) { txCount++; printStats(); VpTr_S chosenTips; int tipsNb = 0; std::string trId; bool Ifattack = false; if(strcmp(par("AttackID"),ID.c_str()) == 0) { bool test = IfAttackStage(); if(!IfAttack && test && (par("ParasiteChainAttack") || par("SplittingAttack"))) { cMessage * msgAttack = nullptr; IfAttack = true; Ifattack = true; if(par("ParasiteChainAttack")) { msgAttack = new cMessage("Building the parasite chain",ParasiteChainAttack); } else { msgAttack = new cMessage("Starting a splitting attack",SplittingAttack); } scheduleAt(simTime(), msgAttack); } else { trId = ID + std::to_string(txCount); } } else { trId = ID + std::to_string(txCount); } if(!Ifattack) { EV << "Issuing a new transaction" << std::endl; EV << "TSA procedure for " << trId << std::endl; double WProp = par("WProp"); int W = static_cast<int>(WProp*myTangle.size()); if(strcmp(par("TSA"),"IOTA") == 0) { chosenTips = IOTA(par("alpha"),W,par("N")); tipsNb = static_cast<int>(chosenTips.size()); } if(strcmp(par("TSA"),"GIOTA") == 0) { chosenTips = GIOTA(par("alpha"),W,par("N")); tipsNb = static_cast<int>(chosenTips.size()); } if(strcmp(par("TSA"),"EIOTA") == 0) { chosenTips = EIOTA(par("p1"),par("p2"),par("lowAlpha"),par("highAlpha"),W,par("N")); tipsNb = static_cast<int>(chosenTips.size()); } if(chosenTips.empty()) { EV << "The TSA did not give legit tips to approve : attempting again." << std::endl; txCount--; scheduleAt(simTime() + exponential(mean), msgIssue); } else { EV << "Chosen Tips : "; for(auto tip : chosenTips) { EV << tip->ID << " "; } EV << std::endl; MsgP->ID = trId; MsgP->chosen = chosenTips; msgPoW->setContextPointer(MsgP); EV << "Pow time = " << tipsNb*powTime << std::endl; scheduleAt(simTime() + tipsNb*powTime, msgPoW); } } } else if(txCount >= txLimit) { EV << "Number of transactions reached : stopping issuing" << std::endl; } } else if(msg->getKind() == POW) { MsgPoW* Msg = (MsgPoW*) msg->getContextPointer(); pTr_S newTx = attach(Msg->ID,simTime(),Msg->chosen); EV << "Pow time finished for " << Msg->ID << std::endl; EV << " Sending " << newTx->ID << " to all nodes" << std::endl; for(int i = 0; i < NeighborsNumber; i++) { MsgUpdate * MsgU = new MsgUpdate; MsgU->ID = newTx->ID; MsgU->issuedBy = newTx->issuedBy; for(auto approvedTips : newTx->S_approved) { MsgU->S_approved.push_back(approvedTips->ID); } msgUpdate->setContextPointer(MsgU); send(msgUpdate->dup(),"NodeOut",i); } scheduleAt(simTime() + exponential(mean), msgIssue); } else if(msg->getKind() == UPDATE) { MsgUpdate* Msg = (MsgUpdate*) msg->getContextPointer(); if(IfPresent(Msg->ID)) { EV << Msg->ID << " is already present"<< std::endl; delete Msg; delete msg; } else { auto Sender = msg->getSenderModule(); EV << "Received a new transaction " << Msg->ID << std::endl; if(NodeModuleNb - 1 != NeighborsNumber) { EV << " Sending " << Msg->ID << " to all nodes" << std::endl; for(int i = 0; i < NeighborsNumber; i++) { cGate *g = gate("NodeOut",i); if(!g->pathContains(Sender)) { MsgUpdate * MsgU = new MsgUpdate; MsgU->ID = Msg->ID; MsgU->issuedBy = Msg->issuedBy; for(auto approvedTipsID : Msg->S_approved) { MsgU->S_approved.push_back(approvedTipsID); } msgUpdate->setContextPointer(MsgU); send(msgUpdate->dup(),"NodeOut",i); } } } if(ifAddTangle(Msg->S_approved)) { EV << "Updating the Tangle" << std::endl; updateTangle(Msg); updateBuffer(); delete Msg; if(par("SplittingAttack") && strcmp(par("AttackID"),ID.c_str()) == 0) { if(IfAttackSP && !IfSimFinished) { EV << "Received a new transaction, checking the balance..." << std::endl; int diff = branch1.size() - branch2.size(); if(diff != 0) { EV << "The weight of the two branches is not the same : maintaining..." << std::endl; if(diff > 0) { whichBranch = 2; } else { whichBranch = 1; } countMB = std::abs(diff); IfAttackSP = false; EV << "with countMB : " << countMB << std::endl; EV << "with whichBranch : " << whichBranch << std::endl; double PropRateMB = par("PropRateMB"); simtime_t rateMB = mean*PropRateMB; int temp = txCount; for(int i = 0; i < std::abs(diff); i++) { temp++; EV << "Sending " << ID + std::to_string(temp) << " with a delay of " << (i+1)*rateMB << std::endl; auto msgMB = new cMessage("Maintaining the balance between the two branches",MaintainBalance); scheduleAt(simTime() + (i+1)*rateMB, msgMB); } } else { IfAttackSP = true; EV << "The weight of the two branches is the same" << std::endl; } } else if(!IfSimFinished && !IfIniSP) { EV << "Currently maintaining the balance, buffering the request..." << std::endl; IfScheduleMB = true; } } } else { EV << "Adding to the Buffer" << std::endl; myBuffer.push_back(Msg); } delete msg; } } } void NodeModule::finish() { EV << "By NodeModule" + ID << " : Simulation ended - Deleting my local Tangle" << std::endl; if(strcmp(par("AttackID"),ID.c_str()) == 0 && par("SplittingAttack")) { EV << "Size branch 1 : " << branch1.size() << std::endl; EV << "Size branch 2 : " << branch2.size() << std::endl; printBranchSize(); } else if(strcmp(par("AttackID"),ID.c_str()) == 0 && par("ParasiteChainAttack")) { printDiffTxChain(); } if(par("ParasiteChainAttack") || par("SplittingAttack")) { //printChain(); } DeleteTangle(); delete msgIssue; delete msgPoW; delete msgUpdate; delete MsgP; }
26.376607
211
0.455809
[ "vector" ]
b611f2fd63dff72401f101d49f4937787186a8d4
1,213
hpp
C++
src/lib/view/hpp/menuVendedor.hpp
iagoizi/poo-petshop-cpp
1eb9f6858ed6f55f3c1d07024b18ef67b0533358
[ "MIT" ]
null
null
null
src/lib/view/hpp/menuVendedor.hpp
iagoizi/poo-petshop-cpp
1eb9f6858ed6f55f3c1d07024b18ef67b0533358
[ "MIT" ]
null
null
null
src/lib/view/hpp/menuVendedor.hpp
iagoizi/poo-petshop-cpp
1eb9f6858ed6f55f3c1d07024b18ef67b0533358
[ "MIT" ]
null
null
null
#ifndef MENU_VENDEDOR_HPP #define MENU_VENDEDOR_HPP #include "../../model/hpp/lib.hpp" #include "../../model/hpp/petshop.hpp" #include "../../model/hpp/usuario.hpp" #include "../../model/hpp/vendedor.hpp" #include "menu.hpp" #define CADASTRAR_CLIENTE 1 #define VENDER_PRODUTO 2 #define VENDER_SERVICO 3 using namespace std; class MenuVendedor : virtual public Menu { /*Pega o usuário logado no momento e faz um cast para que possamos acessar suas funcionalidades específicas*/ Vendedor *getVendedor(); /*Pergunta se o comprador possui cadastro e, em caso negativo, dá a opção de realizar o cadastro.*/ Cliente compradorPossuiCadastro(Vendedor *vendedor); protected: /*Faz as impressões, entradas e saídas referentes ao cadastro do cliente*/ Cliente menuCadastrarCliente(); /*Faz as impressões, entradas e saídas referentes à venda de um produto*/ void menuVenderProduto(); /*Faz as impressões, entradas e saídas referentes à venda/agendamento de um serviço*/ void menuVenderServico(); public: MenuVendedor(PetShop *petshop); ~MenuVendedor(); virtual void printMenu(); virtual void realizaOperacao(int op); }; #endif
32.783784
114
0.713932
[ "model" ]
b6251ce035c3f2efa4cccc264d310f128c3b7da5
1,081
cpp
C++
src/scenes/game/ui/sidemenu.cpp
Blackhawk-TA/32blit-rpg
eaad46e1eeab6765a6b8f6e31a2d196aeeaba6f9
[ "MIT" ]
null
null
null
src/scenes/game/ui/sidemenu.cpp
Blackhawk-TA/32blit-rpg
eaad46e1eeab6765a6b8f6e31a2d196aeeaba6f9
[ "MIT" ]
null
null
null
src/scenes/game/ui/sidemenu.cpp
Blackhawk-TA/32blit-rpg
eaad46e1eeab6765a6b8f6e31a2d196aeeaba6f9
[ "MIT" ]
null
null
null
// // Created by daniel on 21.09.21. // #include "sidemenu.hpp" #include "overlay.hpp" #include "../../../utils/saves/savegame.hpp" namespace game::sidemenu { Listbox *control; bool open_state = false; void init(uint8_t save_id) { std::vector<Listbox::Item> items = { listbox_item::create_sidemenu_item(listbox_item::INVENTORY), listbox_item::create_sidemenu_item(listbox_item::SIDEMENU_OPTIONS, save_id), listbox_item::create_sidemenu_item(listbox_item::SAVE, save_id), listbox_item::create_sidemenu_item(listbox_item::SIDEMENU_BACK), listbox_item::create_sidemenu_item(listbox_item::QUIT) }; control = new Listbox(Rect(16, 0, 4, 7), items); } void cleanup() { open_state = false; delete control; } void open() { open_state = true; } void close() { open_state = false; control->cursor_reset(); } bool is_open() { return open_state; } void draw() { control->draw(); } void cursor_up() { control->cursor_up(); } void cursor_down() { control->cursor_down(); } void cursor_press() { control->cursor_press(); } }
18.637931
79
0.689177
[ "vector" ]
b625e1d84a162f033b5676bcd37ea288dd01dfb2
360
cpp
C++
sdl/include/source/Player.cpp
numfo/tryme
596b48160cc1c2377bee05675570f62df4f37d9d
[ "MIT" ]
null
null
null
sdl/include/source/Player.cpp
numfo/tryme
596b48160cc1c2377bee05675570f62df4f37d9d
[ "MIT" ]
null
null
null
sdl/include/source/Player.cpp
numfo/tryme
596b48160cc1c2377bee05675570f62df4f37d9d
[ "MIT" ]
null
null
null
#include "../header/Player.h" Player::Player(const LoaderParams* pParams):SDLGameObject(pParams){ } void Player::draw(){ SDLGameObject::draw(); } void Player::update(){ m_currentFrame = int (((SDL_GetTicks()/100)%6)); m_acceleration.setX(.01); SDLGameObject::update(); } void Player::clean(){ cout<<"cleaning Player object"<<endl; }
20
67
0.661111
[ "object" ]
b629c84fb5474fbb8377e31708e6cad70e4f7e57
578
cpp
C++
Graph/AP.cpp
ISeaTeL/Codebook
2c137377d39085cb642294e5481bff039a074985
[ "MIT" ]
null
null
null
Graph/AP.cpp
ISeaTeL/Codebook
2c137377d39085cb642294e5481bff039a074985
[ "MIT" ]
null
null
null
Graph/AP.cpp
ISeaTeL/Codebook
2c137377d39085cb642294e5481bff039a074985
[ "MIT" ]
1
2021-01-26T05:02:48.000Z
2021-01-26T05:02:48.000Z
#define MAXN 10001 vector<int> v[MAXN]; //adjacency list bool rec[MAXN]; int clk[MAXN], low[MAXN], time, ct; //ct: the # of AP void dfs(int x, int parent){ rec[x] = 1; clk[x] = low[x] = ++time; int child = 0; bool ap = 0; for(int i = 0; i < v[x].size(); i++){ int y = v[x][i]; if(y != p){ if(!rec[y]){ child++; dfs(y, x); low[x] = low[x] < low[y] ? low[x] : low[y]; if(low[y] >= clk[x]) ap = 1; } else low[x] = low[x] < clk[y] ? low[x] : clk[y]; } } if(x == parent && child > 1 || x != parent && ap) ct++; //x-th pt is an AP }
19.931034
53
0.475779
[ "vector" ]
b62e7d2426e93087eca6ced4eddc28912c99ee68
1,835
cpp
C++
src/eight_queens.cpp
olafdietsche/algorithms
0844c19423227cfea330c0301928ffdc28aa99e0
[ "MIT" ]
null
null
null
src/eight_queens.cpp
olafdietsche/algorithms
0844c19423227cfea330c0301928ffdc28aa99e0
[ "MIT" ]
null
null
null
src/eight_queens.cpp
olafdietsche/algorithms
0844c19423227cfea330c0301928ffdc28aa99e0
[ "MIT" ]
null
null
null
#include "eight_queens.h" board::board(int size) : board_size(size), a(board_size, std::vector<bool>(board_size, false)) { } bool board::valid(int row, int col) const { return row_empty(row) && column_empty(col) && diagonals_empty(row, col); } bool board::row_empty(int row) const { for (int col = 0; col < board_size; ++col) { if (a[row][col]) return false; } return true; } bool board::column_empty(int col) const { for (int row = 0; row < board_size; ++row) { if (a[row][col]) return false; } return true; } bool board::diagonals_empty(int row, int col) const { int r, c; // check first diagonal if (row < col) { r = 0; c = col - row; } else { r = row - col; c = 0; } for (; r < board_size && c < board_size; ++r, ++c) { if (a[r][c]) return false; } // check second diagonal if (row < board_size - col) { r = 0; c = col + row; } else { r = row - (board_size - col - 1); c = board_size - 1; } for (; r < board_size && c >= 0; ++r, --c) { if (a[r][c]) return false; } return true; } void board::print(std::ostream &f) const { f << '+'; for (int col = 0; col < board_size; ++col) f << '-'; f << "+\n"; for (int row = 0; row < board_size; ++row) { f << '|'; for (int col = 0; col < board_size; ++col) f << (a[row][col] ? '*' : ' '); f << "|\n"; } f << '+'; for (int col = 0; col < board_size; ++col) f << '-'; f << "+\n"; for (int row = 0; row < board_size; ++row) { for (int col = 0; col < board_size; ++col) if (a[row][col]) f << '(' << row << ',' << col << ")\n"; } } bool eight_queens(board &b, int row) { for (int col = 0; col < b.size(); ++col) { if (b.valid(row, col)) { b.set(row, col); if (row == b.size() - 1 || eight_queens(b, row + 1)) return true; b.clear(row, col); } } return false; }
16.238938
73
0.525886
[ "vector" ]
ac072bc44399f8ed50ebca5c617af9fb5d8bc6da
890
hpp
C++
Constants/include/ParseParams.hpp
msolanik/Geliosphere
bad72f7869e8eb30fe54344ad374f2534a7f45a5
[ "BSD-3-Clause" ]
null
null
null
Constants/include/ParseParams.hpp
msolanik/Geliosphere
bad72f7869e8eb30fe54344ad374f2534a7f45a5
[ "BSD-3-Clause" ]
null
null
null
Constants/include/ParseParams.hpp
msolanik/Geliosphere
bad72f7869e8eb30fe54344ad374f2534a7f45a5
[ "BSD-3-Clause" ]
null
null
null
/** * @file ParseParams.hpp * @author Michal Solanik * @brief Parser of arguements from CLI * @version 0.1 * @date 2021-07-13 * * @copyright Copyright (c) 2021 * */ #ifndef PARSE_PARAMS_H #define PARSE_PARAMS_H #include <string> #include "ParamsCarrier.hpp" /** * @brief ParseParams is responsible for parsing arguments from CLI. * */ class ParseParams { public: /** * @brief Parse params from CLI. * * @param argc Number of arguments * @param argv Arguments * @return 1 in the case of successfully parsed arguments and * -1 in the case of failure. */ int parseParams(int argc, char **argv); /** * @brief Get the Params object * * @return ParamsCarrier* with parsed arguments */ ParamsCarrier *getParams(); private: /** * @brief Instance of ParamsCarrier for placing * parsed arguments. * */ ParamsCarrier *singleTone; }; #endif
17.45098
68
0.67191
[ "object" ]
ac19af8bcaf017a31096701c0019bc8d80fbfd17
970
cpp
C++
src/Pineapple/SurfaceColorIntegrator.cpp
ScottSWu/scwu-renderer
0136d732fdb1a6d40e46942d74f1edcbc66dc283
[ "MIT" ]
3
2016-02-23T15:41:52.000Z
2017-12-27T17:57:10.000Z
src/Pineapple/SurfaceColorIntegrator.cpp
ScottSWu/scwu-renderer
0136d732fdb1a6d40e46942d74f1edcbc66dc283
[ "MIT" ]
null
null
null
src/Pineapple/SurfaceColorIntegrator.cpp
ScottSWu/scwu-renderer
0136d732fdb1a6d40e46942d74f1edcbc66dc283
[ "MIT" ]
null
null
null
#include "Pineapple/Integrator/SurfaceColorIntegrator.hpp" #include "Pineapple/Intersection.hpp" #include "Pineapple/Scene.hpp" #include "Pineapple/Ray.hpp" SurfaceColorIntegrator::SurfaceColorIntegrator() : SurfaceIntegrator() { } SurfaceColorIntegrator::~SurfaceColorIntegrator() { } glm::vec4 SurfaceColorIntegrator::shade(const Ray & ray, Scene * scene) { Object3d * root = scene->getRoot(); std::vector<Intersection> results; root->intersect(results, ray, true); float firstValue = 0.f; int firstIndex = -1; for (int i = 0, l = results.size(); i < l; i++) { float depth = results[i].t; if (firstIndex < 0 || depth < firstValue) { firstValue = depth; firstIndex = i; } } if (firstIndex < 0) { return glm::vec4(); } else { Intersection result = results[firstIndex]; return result.surface->sampleColor(result.index, result.coord); } }
24.25
73
0.629897
[ "vector" ]
ac1baabad10fd3aedb3ded62d71746321cfa72a1
1,145
cpp
C++
leetcode.com/Weekly Contest 240/3/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2020-08-20T11:02:49.000Z
2020-08-20T11:02:49.000Z
leetcode.com/Weekly Contest 240/3/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
null
null
null
leetcode.com/Weekly Contest 240/3/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2022-01-01T23:23:13.000Z
2022-01-01T23:23:13.000Z
#include <bits/stdc++.h> using namespace std; int __fastio = []() { ios_base::sync_with_stdio(false); cout << fixed << setprecision(10); cin.tie(nullptr); return 0; } (); const int MOD = 1e9 + 7; typedef unsigned long long ull; typedef long long ll; class Solution { public: int maxSumMinProduct(vector<int>& A) { ull res = 0; int n = A.size(); vector<ull> B(n); // 单调栈 stack<pair<int,ull>> stk; for (int i = 0; i < n; ++i) { ull S = 0; while (!stk.empty() && A[i] <= stk.top().first) { S += stk.top().second; stk.pop(); } S += A[i]; B[i] = S*A[i]; stk.emplace(A[i], S); } stack<pair<int,ull>> stk2; for (int i = n - 1; i >= 0; --i) { ull S = 0; while (!stk2.empty() && A[i] <= stk2.top().first) { S += stk2.top().second; stk2.pop(); } B[i] += S*A[i]; S += A[i]; stk2.emplace(A[i], S); } return (*max_element(B.begin(), B.end()))%MOD; } };
28.625
124
0.426201
[ "vector" ]
ac1d372495a828ffdef4d3bc9adff48454e65c2e
5,222
cpp
C++
examples/rocketwar/src/game/basicState.cpp
AlexAUT/rocketWar
edea1c703755e198b1ad8909c82e5d8d56c443ef
[ "MIT" ]
null
null
null
examples/rocketwar/src/game/basicState.cpp
AlexAUT/rocketWar
edea1c703755e198b1ad8909c82e5d8d56c443ef
[ "MIT" ]
null
null
null
examples/rocketwar/src/game/basicState.cpp
AlexAUT/rocketWar
edea1c703755e198b1ad8909c82e5d8d56c443ef
[ "MIT" ]
null
null
null
#include "basicState.hpp" #include <aw/engine/engine.hpp> #include <aw/engine/resources/loaders/ofbxLoader.hpp> #include <aw/graphics/core/shaderStage.hpp> #include <aw/opengl/opengl.hpp> #include <aw/util/colors.hpp> #include <glm/gtx/string_cast.hpp> #include "logApp.hpp" BasicState::BasicState(aw::engine::Engine& engine) : State(engine.stateMachine()), WindowEventSubscriber(engine.messageBus()), mEngine(engine), mNetworkHandler{*this, "127.0.0.1", 14441} { aw::engine::OFBXLoader loader; if (!loader.load(mShipMesh, "assets/meshes/ship.fbx")) { LOG_APP_E("Could not the ship mesh"); } if (!loader.load(mLevelMesh, "assets/levels/level2.fbx")) { LOG_APP_E("Could not load the level mesh!"); } if (!loader.load(mMissleMesh, "assets/meshes/missle.fbx")) { LOG_APP_E("Could not load the missle mesh!"); } mMissleMesh.transform().scale(aw::Vec3{0.05}); aw::ShaderStage vShader(aw::ShaderStage::Type::Vertex); vShader.loadFromPath("assets/shaders/simple_vs.glsl"); aw::ShaderStage fShader(aw::ShaderStage::Type::Fragment); fShader.loadFromPath("assets/shaders/simple_fs.glsl"); mBasicShader.link(vShader, fShader); const auto clearColor = aw::Colors::BEIGE; GL_CHECK(glClearColor(clearColor.r, clearColor.g, clearColor.b, 1.0)); GL_CHECK(glEnable(GL_DEPTH_TEST)); mCamController.distance(4.f); mShipMesh.transform().scale(aw::Vec3{0.15}); mCamController.rotation({aw::pi_2(), 0.f}); mNetworkHandler.connect(); } void BasicState::onShow() {} void BasicState::update(float dt) { mNetworkHandler.update(dt); for (auto& player : mPlayers) player.ship().update(dt); if (!mPause) { for (auto& missle : mMissles) { if (missle) missle->update(dt); } } // mCamController.lookAt(mShip.transform().position()); mCamController.apply(mCamera); } void BasicState::render() { // LOG_APP(aw::log::Level::Warning, "Render nothing :/ \n"); GL_CHECK(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); mShipMesh.bind(); mBasicShader.bind(); for (auto& player : mPlayers) { aw::Transform transform; mBasicShader.set("mvp", mCamera.viewProjection() * player.ship().transform().toMatrix() * mShipMesh.transform().toMatrix()); mBasicShader.set("view", mCamera.view()); mBasicShader.set("color", aw::Colors::SKYBLUE); for (auto i = 0U; i < mShipMesh.subMeshes().size(); i++) { const auto& subMesh = mShipMesh.subMeshes()[i]; GL_CHECK(glDrawElements(GL_TRIANGLES, subMesh.indicesCount, GL_UNSIGNED_INT, reinterpret_cast<const void*>(subMesh.indicesOffset))); } } mLevelMesh.bind(); mBasicShader.bind(); mBasicShader.set("mvp", mCamera.viewProjection() * mLevelMesh.transform().toMatrix()); mBasicShader.set("view", mCamera.view()); mBasicShader.set("color", aw::Colors::FORESTGREEN); auto q = mShipMesh.transform().rotation(); for (auto i = 0U; i < mLevelMesh.subMeshes().size(); i++) { const auto& subMesh = mLevelMesh.subMeshes()[i]; GL_CHECK(glDrawElements(GL_TRIANGLES, subMesh.indicesCount, GL_UNSIGNED_INT, reinterpret_cast<const void*>(subMesh.indicesOffset))); } mMissleMesh.bind(); mBasicShader.bind(); mBasicShader.set("view", mCamera.view()); mBasicShader.set("color", aw::Colors::CRIMSON); for (auto& missle : mMissles) { if (!missle || !missle->alive()) continue; mBasicShader.set("mvp", mCamera.viewProjection() * missle->transform().toMatrix() * mMissleMesh.transform().toMatrix()); for (auto i = 0U; i < mMissleMesh.subMeshes().size(); i++) { const auto& subMesh = mMissleMesh.subMeshes()[i]; GL_CHECK(glDrawElements(GL_TRIANGLES, subMesh.indicesCount, GL_UNSIGNED_INT, reinterpret_cast<const void*>(subMesh.indicesOffset))); } } } void BasicState::receive(const aw::windowEvent::Closed& event) { mEngine.terminate(); } void BasicState::receive(const aw::windowEvent::Resized& event) { GL_CHECK(glViewport(0, 0, event.size.x, event.size.y)); mCamera.aspectRatio(static_cast<float>(event.size.x) / static_cast<float>(event.size.y)); } void BasicState::receive(const aw::windowEvent::MouseMoved& event) { if (mRightPressed) { auto rot = aw::Vec2(event.delta.y, -event.delta.x) * 0.01f; mCamController.rotation(mCamController.rotation() + rot); } } void BasicState::receive(const aw::windowEvent::MouseButtonPressed& event) { if (event.button == aw::mouse::Button::Right) mRightPressed = true; } void BasicState::receive(const aw::windowEvent::MouseButtonReleased& event) { if (event.button == aw::mouse::Button::Right) mRightPressed = false; } void BasicState::receive(const aw::windowEvent::MouseWheelScrolled& event) { if (event.wheel == aw::mouse::Wheel::Veritcal) { mCamController.distance(mCamController.distance() + event.delta); } } void BasicState::receive(const aw::windowEvent::KeyPressed& event) { if (event.key == aw::keyboard::Key::LAlt) mPause = !mPause; } void BasicState::receive(const aw::windowEvent::KeyReleased& event) {}
27.776596
93
0.673114
[ "mesh", "render", "transform" ]
ac259165fc698f4966bd595f32b85173a05cc1cb
1,198
cpp
C++
aws-cpp-sdk-opsworks/source/model/UpdateRdsDbInstanceRequest.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-opsworks/source/model/UpdateRdsDbInstanceRequest.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-opsworks/source/model/UpdateRdsDbInstanceRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/opsworks/model/UpdateRdsDbInstanceRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::OpsWorks::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpdateRdsDbInstanceRequest::UpdateRdsDbInstanceRequest() : m_rdsDbInstanceArnHasBeenSet(false), m_dbUserHasBeenSet(false), m_dbPasswordHasBeenSet(false) { } Aws::String UpdateRdsDbInstanceRequest::SerializePayload() const { JsonValue payload; if(m_rdsDbInstanceArnHasBeenSet) { payload.WithString("RdsDbInstanceArn", m_rdsDbInstanceArn); } if(m_dbUserHasBeenSet) { payload.WithString("DbUser", m_dbUser); } if(m_dbPasswordHasBeenSet) { payload.WithString("DbPassword", m_dbPassword); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection UpdateRdsDbInstanceRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "OpsWorks_20130218.UpdateRdsDbInstance")); return headers; }
20.655172
102
0.757095
[ "model" ]
ac291afa10167875f6e0606ca4f4fcb298661a19
5,678
hpp
C++
src/core/cpp/include/io/ConfigReader.hpp
railtoolkit/OpenLinTim
27eba8b6038946ce162e9f7bbc0bd23045029d51
[ "MIT" ]
null
null
null
src/core/cpp/include/io/ConfigReader.hpp
railtoolkit/OpenLinTim
27eba8b6038946ce162e9f7bbc0bd23045029d51
[ "MIT" ]
null
null
null
src/core/cpp/include/io/ConfigReader.hpp
railtoolkit/OpenLinTim
27eba8b6038946ce162e9f7bbc0bd23045029d51
[ "MIT" ]
null
null
null
/** * A reader for config files. To use, initialize a new ConfigReader and use it to call * {@link CsvReader#readCsv(std::string, java.util.function.BiConsumer)} with the config file to read. */ #ifndef CONFIGREADER_HPP #define CONFIGREADER_HPP #include "../exception/exceptions.hpp" #include "../io/CsvReader.hpp" #include "../util/config.hpp" #include "../util/SolverType.hpp" #include "../util/LogLevel.hpp" #include <string> #include <vector> #include <fstream> class ConfigReader{ private: std::string configFileName; bool onlyIfExists; Config* config; //static Logger logger = Logger.getLogger("net.lintim.io.ConfigReader"); public: /** * Initialize a new ConfigReader with the source file, that should be read, the onlyIfExists tag, i.e., whether * an io error on "include" parameters should abort the reading process, and the config to put the read values in. * @param configFileName the relative path to the config file to read * @param onlyIfExists whether an io error on "include" parameters should abort the reading process. If set to * true, io errors will be written to output but ignored * @param config the config to write the read parameters to */ ConfigReader(Config* config, std::string configFileName, bool onlyIfExists = false, std::string path = ""){ this->configFileName = path + configFileName; this->onlyIfExists = onlyIfExists; this->config = config; } std::string getConfigFileName(){ return this->configFileName; } bool getOnlyIfExists(){ return this->onlyIfExists; } Config* getConfig(){ return this->config; } //void processConfigLine(std::vector <std::string> , int ); /** * Read the file at the given filename and parse it as a config file. Will follow link to other config files, * when marked with "include" or "include_if_exists". Will throw, if any such file can not be found or read, * depending on {@code onlyIfExists}. * * @param fileName the filename of the file to read * @param onlyIfExists If true, no exception will be thrown if a referenced file cannot be found. * @throws InputFileException on any io error */ void readConfig(std::string fileName, bool onlyIfExists){ CsvReader c; c.readCsv(fileName, *this, &ConfigReader::processConfigLine); } /** * Read the file at the given filename and parse it as a config file. Will follow link to other config files, * when marked with "include" or "include_if_exists". Will throw, if any such file can not be found or read. * * @param fileName the filename of the file to read * @throws InputFileException on any io error */ void readConfig(std::string fileName){ readConfig(fileName, false); } void read(void){ CsvReader c; c.readCsv(configFileName, *this, &ConfigReader::processConfigLine); } /** * Process the contents of a config line. * @param args the content of the line * @param lineNumber the line number, used for error handling * @throws InputFormatException if the line has less than two entries * @throws UncheckedIOException on any io error while trying to read included config files */ void processConfigLine(std::vector <std::string> args, int lineNumber){ //We except at least two entries (more than two, if the value contains a ";" if(args.size() <= 1){ throw InputFormatException(configFileName, args.size(), 2); } std::string key = args[0]; std::string value = ""; for(int i = 1; i < (int) args.size() - 1; i++) value += args[i] + ";"; value += args[args.size() - 1]; // trim endline if (int(value[value.size()-1]) < 32) value = value.substr(0, value.size()-1); // trim whitespaces while (value[0] == ' ') value = value.substr(1, value.size()-1); while (value[value.size()-1] == ' ') value.resize(value.size()-1); // trim quotation marks if(value.size() >= 2 && value[0] == '"' && value[value.size() - 1] == '"'){ value = value.substr(1, value.size() - 2); } // include additional config files if(key == "include_if_exists"){ std::ifstream file((getParentDirectoryName(configFileName) + "/" + value).c_str()); if(file.good()){ readConfig(getParentDirectoryName(configFileName) + "/" + value); try{ } catch(std::exception& e){ //logger.log(Level.WARNING, "Catched IOException while reading " + Paths.get(configFileName).toAbsolutePath().getParent().toString() + File //.pathSeparator + value + ": " + e.toString()); } } } else if(key == "include"){ try{ readConfig(getParentDirectoryName(configFileName) + "/" + value); } catch(std::exception& e){ //logger.log(Level.WARNING, "Catched IOException while reading " + Paths.get(configFileName).toAbsolutePath().getParent().toString() + File // .pathSeparator + value + ": " + e.toString()); if(!onlyIfExists){ throw InputFileException(value); } } } else{ this->config->put(key, value); } } private: static std::string getParentDirectoryName(std::string filePath){ size_t found = filePath.find_last_of("/\\"); return filePath.substr(0, found); } }; #endif
38.107383
159
0.615005
[ "vector" ]
ac29cbaf37fd1cebf27394099fb2f531491ed474
2,059
hpp
C++
tket/src/Mapping/include/Mapping/RoutingMethod.hpp
CQCL/tket
3f3d7c24d9a6c9cfd85966c13dcccc8a13f92adb
[ "Apache-2.0" ]
104
2021-09-15T08:16:25.000Z
2022-03-28T21:19:00.000Z
tket/src/Mapping/include/Mapping/RoutingMethod.hpp
CQCL/tket
3f3d7c24d9a6c9cfd85966c13dcccc8a13f92adb
[ "Apache-2.0" ]
109
2021-09-16T17:14:22.000Z
2022-03-29T06:48:40.000Z
tket/src/Mapping/include/Mapping/RoutingMethod.hpp
CQCL/tket
3f3d7c24d9a6c9cfd85966c13dcccc8a13f92adb
[ "Apache-2.0" ]
8
2021-10-02T13:47:34.000Z
2022-03-17T15:36:56.000Z
// Copyright 2019-2022 Cambridge Quantum Computing // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "Mapping/MappingFrontier.hpp" #include "Utils/Json.hpp" namespace tket { class RoutingMethod { public: RoutingMethod(){}; virtual ~RoutingMethod() {} /** * routing_method modifies circuit held in mapping_frontier with gates for the * purpose of moving circuit closer to one physically permitted by given * architecture. Returns a pair with a bool returning whether any modification * was made and a new initial mapping of qubits in case permutation via swap * network is then required, or new ancilla qubits are added. This is * completed by converting boundary subcircuit in mapping frontier to a * Circuit object which is then passed to route_subcircuit_ as defined in the * constructor. * * Overloaded parameter mapping_frontier contains boundary of routed/unrouted * circuit for modifying. * Overloaded parameter architecture provides physical constraints * * @return Whether circuit is modified and Logical to Physical mapping at * boundary due to modification. * */ virtual std::pair<bool, unit_map_t> routing_method( MappingFrontier_ptr& /*mapping_frontier*/, const ArchitecturePtr& /*architecture*/) const { return {false, {}}; } virtual nlohmann::json serialize() const { nlohmann::json j; j["name"] = "RoutingMethod"; return j; } }; typedef std::shared_ptr<const RoutingMethod> RoutingMethodPtr; } // namespace tket
34.316667
80
0.735794
[ "object" ]
ac300147e4e6debd6f0a2c9860b54bc90c586f81
1,653
cpp
C++
LeetCode/ThousandTwo/1224-max_equal_freq.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandTwo/1224-max_equal_freq.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandTwo/1224-max_equal_freq.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
#include "leetcode.hpp" /* 1224. 最大相等频率 给出一个正整数数组 nums,请你帮忙从该数组中找出能满足下面要求的 最长 前缀,并返回其长度: 从前缀中 删除一个 元素后,使得所剩下的每个数字的出现次数相同。 如果删除这个元素后没有剩余元素存在,仍可认为每个数字都具有相同的出现次数(也就是 0 次)。 示例 1: 输入:nums = [2,2,1,1,5,3,3,5] 输出:7 解释:对于长度为 7 的子数组 [2,2,1,1,5,3,3],如果我们从中删去 nums[4]=5,就可以得到 [2,2,1,1,3,3],里面每个数字都出现了两次。 示例 2: 输入:nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] 输出:13 示例 3: 输入:nums = [1,1,1,2,2,2] 输出:5 示例 4: 输入:nums = [10,2,8,9,3,8,1,5,2,3,7,6] 输出:8 提示: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5 */ // https://leetcode.com/problems/maximum-equal-frequency/discuss/403743/JavaC%2B%2BPython-Only-2-Cases%3A-Delete-it-or-not // 抄的 class Solution { public: int maxEqualFreq(vector<int>& nums) { vector<int> count(100001), freq(100001); int len = static_cast<int>(nums.size()); int ans = 0, a, c, d; for (int i = 1; i <= len; ++i) { a = nums[i - 1]; ++(count[a]); c = count[a]; // 旧的出现次数减去 1 --(freq[c - 1]); // 新的出现次数加上 1 ++(freq[c]); // 要 a // 所有元素都出现了 c 次 // +1 是因为题目要求需要删除一个之后次数相等 if ((freq[c] * c) == i && (i < len)) ans = i + 1; d = i - freq[c] * c; // 不要 a // 当前数字出现了 1 次 // 前面的都是同一个数字出现 i - 1 次 if (((d == c + 1) || (d == 1)) && (freq[d] == 1)) ans = i; } return ans; } }; int main() { vector<int> a = { 2, 2, 1, 1, 5, 3, 3, 5 }, b = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5 }, c = { 1, 1, 1, 2, 2, 2 }, d = { 10, 2, 8, 9, 3, 8, 1, 5, 2, 3, 7, 6 }, e = { 1, 2, 3, 4, 5, 6, 7, 8 }; Solution s; OutExpr(s.maxEqualFreq(a), "%d"); OutExpr(s.maxEqualFreq(b), "%d"); OutExpr(s.maxEqualFreq(c), "%d"); OutExpr(s.maxEqualFreq(d), "%d"); OutExpr(s.maxEqualFreq(e), "%d"); }
19.678571
122
0.534785
[ "vector" ]
ac31adc2528365d0f39641a0d5b90401aa514de8
1,913
hpp
C++
src/jointentropyseedselector.hpp
LaoZZZZZ/bartender-1.1
ddfb2e52bdf92258dd837ab8ee34306e9fb45b81
[ "MIT" ]
22
2016-08-11T06:16:25.000Z
2022-02-22T00:06:59.000Z
src/jointentropyseedselector.hpp
LaoZZZZZ/bartender-1.1
ddfb2e52bdf92258dd837ab8ee34306e9fb45b81
[ "MIT" ]
9
2016-12-08T12:42:38.000Z
2021-12-28T20:12:15.000Z
src/jointentropyseedselector.hpp
LaoZZZZZ/bartender-1.1
ddfb2e52bdf92258dd837ab8ee34306e9fb45b81
[ "MIT" ]
8
2017-06-26T13:15:06.000Z
2021-11-12T18:39:54.000Z
// // jointentropyseedselector.hpp // barcode_project // // Created by luzhao on 4/27/16. // Copyright © 2016 luzhao. All rights reserved. // #ifndef jointentropyseedselector_hpp #define jointentropyseedselector_hpp #include "bpfrequencytracker.hpp" #include "jointentropy.hpp" #include "seedpositionpool.hpp" #include "seedselector.hpp" #include <stdio.h> #include <vector> namespace barcodeSpace { /** * Give an order of positions that will be used as seed * in the clustering process. * The method here is to use the pair-wise joint entropy. * Contuning stack positions together which have highest joint entropy * in the remaining unselected positions. */ class JointEntropySeedSelector :public SeedSelector{ public: typedef PairwiseMeasurement PairwiseEntropy; /** * barcode_length represents the barcode length * entropy_thres is used to select high diversity positions. */ JointEntropySeedSelector(int barcode_length, double entropy_thres); /** * This function is a virtual function derived from SeedSelector * This implementation will use the join entropy to order selected nucleotide positions. */ std::vector<int> getSeedsPositions(const BPFrequencyTracker& frequency_tracker); virtual ~JointEntropySeedSelector() {} private: // This function implements the simplest strategy using the joint entropy. // 1. Pick up the largest joint entropy position pair // 2. Remove this two positions from the pool. // 3. If there are still unpicked pairs go to step 1. void buildPositionFromPool(SeedPositionPool&); double _entropy_thres; std::vector<int> _seed_position; }; } // namespace barcodeSpace #endif /* jointentropyseedselector_hpp */
32.982759
96
0.681129
[ "vector" ]
ac46a847a57b53f6e463d90a3ee51726fcecb063
2,130
hpp
C++
Entity/Enemies/EnemyTank.hpp
JTuthill01/Hell-on-Treads
a89c939c3f1d0bd47d075d5b02d589637548ca31
[ "MIT" ]
null
null
null
Entity/Enemies/EnemyTank.hpp
JTuthill01/Hell-on-Treads
a89c939c3f1d0bd47d075d5b02d589637548ca31
[ "MIT" ]
null
null
null
Entity/Enemies/EnemyTank.hpp
JTuthill01/Hell-on-Treads
a89c939c3f1d0bd47d075d5b02d589637548ca31
[ "MIT" ]
null
null
null
#pragma once #include <Entity/Player/Player.hpp> #include <Entity/Entity.hpp> class EnemyTank : Entity { public: EnemyTank(); ~EnemyTank(); const int enemyDealDamage() const; void removeEnemyTankProjectile(unsigned index); void takeDamage(int damage); void render(sf::RenderTarget& target); void update(const float& deltaTime); void move(const float direction_x, const float direction_y, const float& deltaTime); void updateAnimations(const float& deltaTime); //Getters Projectile& getEnemyTankProjectile(unsigned index); inline int getHp() { return this->mHp; } inline int getEnemyType() { return this->mEnemeyType; } inline const int getEnemyTankProjectileSize() { return this->mEnemyTankProjectile.size(); } inline sf::Sprite getEnemyTankSprite() { return this->mEnemyTankSprite; } inline sf::FloatRect getGobalBounds()const { return this->mEnemyTankSprite.getGlobalBounds(); } sf::Vector2f getEnemyTankSpriteCenter(); inline sf::Vector2f getEnemyTankPosition() const { return this->mEnemyTankSprite.getPosition(); } inline void setEnemyTankColor(sf::Color color) { this->mEnemyTankSprite.setColor(color); } protected: private: int mHp; int mHpMax; int mDamage; int mDamageMax; bool mIsAlive; bool mIsAttacking; bool mIsFiring; bool mIsMuzzleOn; float mShootTimerMax; float mShootTimer; float mMuzzleTimerMax; float mMuzzleTimer; void enemyDead(const float& deltaTime); void enemyShoot(); void initVariables(); void createMovementComponent(const float max_velocity, const float acceleration, const float deceleration); void createAnimationComponent(sf::Texture& texture_sheet); void loadEnemyTanks(); void loadProjectile(); void updateAttack(const float& deltaTime); sf::Vector2f mEnemySprite; sf::Texture mEnemyTankTexture; sf::Sprite mEnemyTankSprite; sf::Vector2f mEnemyTankSpriteCenter; sf::Sound mExplosion; sf::SoundBuffer mBuffer; std::vector<sf::Texture> mProjectileTextures; std::vector<Projectile> mEnemyTankProjectile; static std::vector<sf::Texture> mEnemyProjectileTextures; };
29.178082
99
0.752113
[ "render", "vector" ]
ac5099d6ada7b8631b340008f80bd58b0490a571
1,145
cc
C++
cpptest/test4.cc
wshonline/test
2eed4c08798f7a68b139295f080a8df31c55fac4
[ "MIT" ]
null
null
null
cpptest/test4.cc
wshonline/test
2eed4c08798f7a68b139295f080a8df31c55fac4
[ "MIT" ]
null
null
null
cpptest/test4.cc
wshonline/test
2eed4c08798f7a68b139295f080a8df31c55fac4
[ "MIT" ]
null
null
null
#include <vector> using namespace std; int totalFruit(vector<int>& fruits) { // 滑动窗口 int max_len = 0; int cur_len = 0; vector<int> per_type_cnt(fruits.size(), 0); int type_cnt = 0; int i = 0; for (int j = 0; j < fruits.size(); j++) { if (per_type_cnt[fruits[j]] > 0) { per_type_cnt[fruits[j]]++; cur_len = j-i+1; max_len = max_len > cur_len ? max_len : cur_len; } else if (per_type_cnt[fruits[j]]==0 && type_cnt < 2) { per_type_cnt[fruits[j]]++; cur_len = j-i+1; max_len = max_len > cur_len ? max_len : cur_len; type_cnt++; } else if (per_type_cnt[fruits[j]]==0 && type_cnt == 2) { type_cnt++; per_type_cnt[fruits[j]]++; while (type_cnt == 3) { per_type_cnt[fruits[i]]--; if (per_type_cnt[fruits[i]] == 0) { type_cnt--; } i++; } } } return max_len; } int main() { std::vector<int> v = {0,1,1,4,3}; int num = totalFruit(v); return 0; }
27.926829
65
0.466376
[ "vector" ]
ac5ef5718892478dbcf8bd952aba7f4af66633c0
2,409
cpp
C++
Source/RawSpeed/common/TableLookUp.cpp
FSchiltz/RawParser
0f6dc895a0023298e681cc68292565f30a138419
[ "MIT" ]
11
2018-02-03T14:59:06.000Z
2020-11-23T23:39:06.000Z
Source/RawSpeed/common/TableLookUp.cpp
FSchiltz/RawParser
0f6dc895a0023298e681cc68292565f30a138419
[ "MIT" ]
null
null
null
Source/RawSpeed/common/TableLookUp.cpp
FSchiltz/RawParser
0f6dc895a0023298e681cc68292565f30a138419
[ "MIT" ]
5
2019-04-09T09:37:50.000Z
2021-09-26T20:11:54.000Z
/* RawSpeed - RAW file decoder. Copyright (C) 2009-2014 Klaus Post Copyright (C) 2017 Roman Lebedev This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "common/TableLookUp.h" #include "decoders/RawDecoderException.h" // for RawDecoderException (ptr o... #include <cassert> // for assert namespace rawspeed { const int TABLE_SIZE = 65536 * 2; // Creates n numre of tables. TableLookUp::TableLookUp(int _ntables, bool _dither) : ntables(_ntables), dither(_dither) { if (ntables < 1) { ThrowRDE("Cannot construct 0 tables"); } tables.resize(ntables * TABLE_SIZE, ushort16(0)); } void TableLookUp::setTable(int ntable, const std::vector<ushort16>& table) { assert(!table.empty()); const int nfilled = table.size(); if (ntable > ntables) { ThrowRDE("Table lookup with number greater than number of tables."); } ushort16* t = &tables[ntable * TABLE_SIZE]; if (!dither) { for (int i = 0; i < 65536; i++) { t[i] = (i < nfilled) ? table[i] : table[nfilled - 1]; } return; } for (int i = 0; i < nfilled; i++) { int center = table[i]; int lower = i > 0 ? table[i - 1] : center; int upper = i < (nfilled - 1) ? table[i + 1] : center; int delta = upper - lower; t[i * 2] = center - ((upper - lower + 2) / 4); t[i * 2 + 1] = delta; } for (int i = nfilled; i < 65536; i++) { t[i * 2] = table[nfilled - 1]; t[i * 2 + 1] = 0; } t[0] = t[1]; t[TABLE_SIZE - 1] = t[TABLE_SIZE - 2]; } ushort16* TableLookUp::getTable(int n) { if (n > ntables) { ThrowRDE("Table lookup with number greater than number of tables."); } return &tables[n * TABLE_SIZE]; } } // namespace rawspeed
30.493671
80
0.644251
[ "vector" ]
ac60c9e30c0c7be4c3036733f7ef7c7fc576abe6
10,344
cpp
C++
source/ff.dx11/source/object_cache.cpp
spadapet/ff_game_library
f1bf00f90adde66c2c2aa35b109fe61b8d2c6352
[ "MIT" ]
null
null
null
source/ff.dx11/source/object_cache.cpp
spadapet/ff_game_library
f1bf00f90adde66c2c2aa35b109fe61b8d2c6352
[ "MIT" ]
null
null
null
source/ff.dx11/source/object_cache.cpp
spadapet/ff_game_library
f1bf00f90adde66c2c2aa35b109fe61b8d2c6352
[ "MIT" ]
null
null
null
#include "pch.h" #include "operators.h" #include "object_cache.h" size_t ff::dx11::object_cache::hash_data::operator()(const std::shared_ptr<ff::data_base>& value) const { return (value && value->size()) ? ff::stable_hash_bytes(value->data(), value->size()) : 0; } bool ff::dx11::object_cache::equals_data::operator()(const std::shared_ptr<ff::data_base>& lhs, const std::shared_ptr<ff::data_base>& rhs) const { if (!lhs || !rhs) { return lhs == rhs; } return lhs->size() == rhs->size() && !std::memcmp(lhs->data(), rhs->data(), lhs->size()); } ff::dx11::object_cache::object_cache(ID3D11DeviceX* device) : device(device) {} ID3D11BlendState* ff::dx11::object_cache::get_blend_state(const D3D11_BLEND_DESC& desc) { auto i = this->blend_states.find(desc); if (i == this->blend_states.cend()) { Microsoft::WRL::ComPtr<ID3D11BlendState> state; if (FAILED(this->device->CreateBlendState(&desc, &state))) { assert(false); return nullptr; } i = this->blend_states.try_emplace(desc, state).first; } return i->second.Get(); } ID3D11DepthStencilState* ff::dx11::object_cache::get_depth_stencil_state(const D3D11_DEPTH_STENCIL_DESC& desc) { auto i = this->depth_states.find(desc); if (i == this->depth_states.cend()) { Microsoft::WRL::ComPtr<ID3D11DepthStencilState> state; if (FAILED(this->device->CreateDepthStencilState(&desc, &state))) { assert(false); return nullptr; } i = this->depth_states.try_emplace(desc, state).first; } return i->second.Get(); } ID3D11RasterizerState* ff::dx11::object_cache::get_rasterize_state(const D3D11_RASTERIZER_DESC& desc) { auto i = this->raster_states.find(desc); if (i == this->raster_states.cend()) { Microsoft::WRL::ComPtr<ID3D11RasterizerState> state; if (FAILED(this->device->CreateRasterizerState(&desc, &state))) { assert(false); return nullptr; } i = this->raster_states.try_emplace(desc, state).first; } return i->second.Get(); } ID3D11SamplerState* ff::dx11::object_cache::get_sampler_state(const D3D11_SAMPLER_DESC& desc) { auto i = this->sampler_states.find(desc); if (i == this->sampler_states.cend()) { Microsoft::WRL::ComPtr<ID3D11SamplerState> state; if (FAILED(this->device->CreateSamplerState(&desc, &state))) { assert(false); return nullptr; } i = this->sampler_states.try_emplace(desc, state).first; } return i->second.Get(); } ID3D11VertexShader* ff::dx11::object_cache::get_vertex_shader(std::string_view resource_name) { ff::auto_resource<ff::resource_file> resource = ff::global_resources::get(resource_name); std::shared_ptr<ff::saved_data_base> saved_data = resource.object() ? resource->saved_data() : nullptr; std::shared_ptr<ff::data_base> data = saved_data ? saved_data->loaded_data() : nullptr; ID3D11VertexShader* value = data ? this->get_vertex_shader(data) : nullptr; if (value) { this->resources.insert(resource.resource()); } return value; } ID3D11VertexShader* ff::dx11::object_cache::get_vertex_shader_and_input_layout(std::string_view resource_name, Microsoft::WRL::ComPtr<ID3D11InputLayout>& input_layout, const D3D11_INPUT_ELEMENT_DESC* layout, size_t count) { input_layout = this->get_input_layout(resource_name, layout, count); return this->get_vertex_shader(resource_name); } ID3D11GeometryShader* ff::dx11::object_cache::get_geometry_shader(std::string_view resource_name) { ff::auto_resource<ff::resource_file> resource = ff::global_resources::get(resource_name); std::shared_ptr<ff::saved_data_base> saved_data = resource.object() ? resource->saved_data() : nullptr; std::shared_ptr<ff::data_base> data = saved_data ? saved_data->loaded_data() : nullptr; ID3D11GeometryShader* value = data ? this->get_geometry_shader(data) : nullptr; if (value) { this->resources.insert(resource.resource()); } return value; } ID3D11GeometryShader* ff::dx11::object_cache::get_geometry_shader_stream_output(std::string_view resource_name, const D3D11_SO_DECLARATION_ENTRY* layout, size_t count, size_t vertex_stride) { ff::auto_resource<ff::resource_file> resource = ff::global_resources::get(resource_name); std::shared_ptr<ff::saved_data_base> saved_data = resource.object() ? resource->saved_data() : nullptr; std::shared_ptr<ff::data_base> data = saved_data ? saved_data->loaded_data() : nullptr; ID3D11GeometryShader* value = data ? this->get_geometry_shader_stream_output(data, layout, count, vertex_stride) : nullptr; if (value) { this->resources.insert(resource.resource()); } return value; } ID3D11PixelShader* ff::dx11::object_cache::get_pixel_shader(std::string_view resource_name) { ff::auto_resource<ff::resource_file> resource = ff::global_resources::get(resource_name); std::shared_ptr<ff::saved_data_base> saved_data = resource.object() ? resource->saved_data() : nullptr; std::shared_ptr<ff::data_base> data = saved_data ? saved_data->loaded_data() : nullptr; ID3D11PixelShader* value = data ? this->get_pixel_shader(data) : nullptr; if (value) { this->resources.insert(resource.resource()); } return value; } ID3D11InputLayout* ff::dx11::object_cache::get_input_layout(std::string_view vertex_shader_resource_name, const D3D11_INPUT_ELEMENT_DESC* layout, size_t count) { ff::auto_resource<ff::resource_file> resource = ff::global_resources::get(vertex_shader_resource_name); std::shared_ptr<ff::saved_data_base> saved_data = resource.object() ? resource->saved_data() : nullptr; std::shared_ptr<ff::data_base> data = saved_data ? saved_data->loaded_data() : nullptr; ID3D11InputLayout* value = data ? this->get_input_layout(data, layout, count) : nullptr; if (value) { this->resources.insert(resource.resource()); } return value; } ID3D11VertexShader* ff::dx11::object_cache::get_vertex_shader(const std::shared_ptr<ff::data_base>& shader_data) { ID3D11VertexShader* return_value = nullptr; Microsoft::WRL::ComPtr<ID3D11VertexShader> value; auto iter = this->shaders.find(shader_data); if (iter != this->shaders.cend()) { if (SUCCEEDED(iter->second.As(&value))) { return_value = value.Get(); } } else if (shader_data && SUCCEEDED(this->device->CreateVertexShader(shader_data->data(), shader_data->size(), nullptr, &value))) { return_value = value.Get(); this->shaders.try_emplace(shader_data, std::move(value)); } return return_value; } ID3D11VertexShader* ff::dx11::object_cache::get_vertex_shader_and_input_layout(const std::shared_ptr<ff::data_base>& shader_data, Microsoft::WRL::ComPtr<ID3D11InputLayout>& input_layout, const D3D11_INPUT_ELEMENT_DESC* layout, size_t count) { input_layout = this->get_input_layout(shader_data, layout, count); return this->get_vertex_shader(shader_data); } ID3D11GeometryShader* ff::dx11::object_cache::get_geometry_shader(const std::shared_ptr<ff::data_base>& shader_data) { ID3D11GeometryShader* return_value = nullptr; Microsoft::WRL::ComPtr<ID3D11GeometryShader> value; auto iter = this->shaders.find(shader_data); if (iter != this->shaders.cend()) { if (SUCCEEDED(iter->second.As(&value))) { return_value = value.Get(); } } else if (shader_data && SUCCEEDED(this->device->CreateGeometryShader(shader_data->data(), shader_data->size(), nullptr, &value))) { return_value = value.Get(); this->shaders.try_emplace(shader_data, std::move(value)); } return return_value; } ID3D11GeometryShader* ff::dx11::object_cache::get_geometry_shader_stream_output(const std::shared_ptr<ff::data_base>& shader_data, const D3D11_SO_DECLARATION_ENTRY* layout, size_t count, size_t vertex_stride) { ID3D11GeometryShader* return_value = nullptr; Microsoft::WRL::ComPtr<ID3D11GeometryShader> value; UINT vertex_stride_2 = static_cast<UINT>(vertex_stride); auto iter = this->shaders.find(shader_data); if (iter != this->shaders.cend()) { if (SUCCEEDED(iter->second.As(&value))) { return_value = value.Get(); } } else if (shader_data && SUCCEEDED(this->device->CreateGeometryShaderWithStreamOutput(shader_data->data(), shader_data->size(), layout, static_cast<UINT>(count), &vertex_stride_2, 1, 0, nullptr, &value))) { return_value = value.Get(); this->shaders.try_emplace(shader_data, std::move(value)); } return return_value; } ID3D11PixelShader* ff::dx11::object_cache::get_pixel_shader(const std::shared_ptr<ff::data_base>& shader_data) { ID3D11PixelShader* return_value = nullptr; Microsoft::WRL::ComPtr<ID3D11PixelShader> value; auto iter = this->shaders.find(shader_data); if (iter != this->shaders.cend()) { if (SUCCEEDED(iter->second.As(&value))) { return_value = value.Get(); } } else if (shader_data && SUCCEEDED(this->device->CreatePixelShader(shader_data->data(), shader_data->size(), nullptr, &value))) { return_value = value.Get(); this->shaders.try_emplace(shader_data, std::move(value)); } return return_value; } ID3D11InputLayout* ff::dx11::object_cache::get_input_layout(const std::shared_ptr<ff::data_base>& shader_data, const D3D11_INPUT_ELEMENT_DESC* layout, size_t count) { ID3D11InputLayout* return_value = nullptr; Microsoft::WRL::ComPtr<ID3D11InputLayout> value; size_t layout_hash = ff::stable_hash_bytes(layout, sizeof(D3D11_INPUT_ELEMENT_DESC) * count); auto iter = this->layouts.find(layout_hash); if (iter != this->layouts.cend()) { return_value = iter->second.Get(); } else if (shader_data != nullptr && SUCCEEDED(this->device->CreateInputLayout(layout, static_cast<UINT>(count), shader_data->data(), shader_data->size(), &value))) { return_value = value.Get(); this->layouts.try_emplace(layout_hash, std::move(value)); } return return_value; }
35.546392
240
0.685712
[ "object" ]
ac67c437c8ff1ff79fcdff1c2d8db61e0e83b59f
1,038
cpp
C++
tournaments/superResources/superResources.cpp
gurfinkel/codeSignal
114817947ac6311bd53a48f0f0e17c0614bf7911
[ "MIT" ]
5
2020-02-06T09:51:22.000Z
2021-03-19T00:18:44.000Z
tournaments/superResources/superResources.cpp
gurfinkel/codeSignal
114817947ac6311bd53a48f0f0e17c0614bf7911
[ "MIT" ]
null
null
null
tournaments/superResources/superResources.cpp
gurfinkel/codeSignal
114817947ac6311bd53a48f0f0e17c0614bf7911
[ "MIT" ]
3
2019-09-27T13:06:21.000Z
2021-04-20T23:13:17.000Z
typedef std::vector<std::string> elemT; typedef std::vector<elemT> listT; listT superResources(listT requests) { struct Helper { bool le(std::string const & a, std::string const & b) { return std::stoi(a) <= std::stoi(b); } }; Helper h; if (requests.size() < 2) { return requests; } listT parts[2] = { listT(requests.begin(), requests.begin() + requests.size() / 2), listT(requests.begin() + requests.size() / 2, requests.end()) }; parts[0] = superResources(parts[0]); parts[1] = superResources(parts[1]); listT result; int idx[2] = {0, 0}; int len[2] = {parts[0].size(), parts[1].size()}; std::string last = ""; while (idx[0] < len[0] || idx[1] < len[1]) { int k; if (idx[1] >= len[1] || idx[0] < len[0] && h.le(parts[0][idx[0]][0], parts[1][idx[1]][0])) { k = 0; } else { k = 1; } elemT element = parts[k][idx[k]++]; if (element[0] != last) { result.push_back(element); last = element[0]; } } return result; }
24.139535
70
0.540462
[ "vector" ]
ac696c3498db579976213405a523f55424968228
18,541
cpp
C++
games/pacman/Pacman.cpp
Sinjide/cpp_arcade
c6a9dc54ed10ea5300d7bf972c5ee2bee2e58116
[ "MIT" ]
null
null
null
games/pacman/Pacman.cpp
Sinjide/cpp_arcade
c6a9dc54ed10ea5300d7bf972c5ee2bee2e58116
[ "MIT" ]
null
null
null
games/pacman/Pacman.cpp
Sinjide/cpp_arcade
c6a9dc54ed10ea5300d7bf972c5ee2bee2e58116
[ "MIT" ]
null
null
null
// //man.cpp for pacman in /home/nicolas/arcade/cpp_arcade/libs/games // // Made by Nicolas Guillon // Login <nicolas@epitech.net> // // Started on Thu Mar 16 10:32:07 2017 Nicolas Guillon // Last update Sun Apr 9 18:43:17 2017 Jerome Dang // #include <stdlib.h> #include <ctime> #include <vector> #include <map> #include <cmath> #include "../../my.hpp" #include "Pacman.hpp" Pacman::Pacman() { } Pacman::~Pacman() { } const std::string Pacman::getName() const { return ("Pacman"); } void Pacman::checkMap(map *map) { int x; int y; int count; y = 0; count = 0; while (y < map->height) { x = 0; while (x < map->width) { if (map->map[y][x] == ITEM || map->map[y][x] == S_ITEM) count++; x++; } y++; } character player; for (std::vector<character>::iterator node = map->player.begin(); node != map->player.end(); ++node) { if ((*node).type == PLAYER) player = (*node); else if ((*node).type == CHARACTER) { if (player.x == (*node).x && player.y == (*node).y) { if (player.hasBonus == 0) map->hasLost = true; else { (*node).y = 7; (*node).x = 10; (*node).yf = 7.0; (*node).xf = 10.0; (*node).hasBonus = clock(); } } } } if (count == 0) map->hasWon = true; } void Pacman::runPlayer(character &player, map *map) { if (player.yf != (double) player.y || player.xf != (double) player.x) { if (player.yf < (double) player.y) { player.y -= 1; player.yf -= 0.5; } else if (player.yf > (double) player.y) { player.y += 1; player.yf += 0.5; } else if (player.xf < (double) player.x) { player.x -= 1; player.xf -= 0.5; } else if (player.xf > (double) player.x) { player.x += 1; player.xf += 0.5; } if (map->map[player.y][player.x] == ITEM) map->current_score.score += 10; else if (map->map[player.y][player.x] == S_ITEM) { map->current_score.score += 50; player.hasBonus = clock(); } map->map[player.y][player.x] = EMPTY; } else if (player.dir == UP && map->map[player.y - 1][player.x] != BLOCK && map->map[player.y - 1][player.x] != PLATFORM) player.yf -= 0.5; else if (player.dir == DOWN && map->map[player.y + 1][player.x] != BLOCK && map->map[player.y + 1][player.x] != PLATFORM) player.yf += 0.5; else if (player.dir == LEFT && map->map[player.y][player.x - 1] != BLOCK && map->map[player.y][player.x - 1] != PLATFORM) { player.xf -= 0.5; if (player.xf < -1.0) { player.xf = 20.0; player.x = 20; } } else if (player.dir == RIGHT && map->map[player.y][player.x + 1] != BLOCK && map->map[player.y][player.x + 1] != PLATFORM) { player.xf += 0.5; if (player.xf > 21.0) { player.xf = 0.0; player.x = 0; } } // Bonus 10secs if (player.hasBonus != 0) { clock_t actTime = clock(); double timeSecs = (actTime - player.hasBonus) / (double) CLOCKS_PER_SEC; if (timeSecs > 0.10) player.hasBonus = 0; } } void Pacman::tryTurning(character &ghost, map *map) { if (ghost.yf == (double) ghost.y && ghost.xf == (double) ghost.x) { int i = 0; std::map<int, event> dir; event lastdir; srand(time(NULL)); // Position actuelle if (ghost.dir == UP && map->map[ghost.y - 1][ghost.x] != BLOCK) dir[i++] = UP; else if (ghost.dir == DOWN && map->map[ghost.y + 1][ghost.x] != BLOCK) dir[i++] = DOWN; else if (ghost.dir == LEFT && map->map[ghost.y][ghost.x - 1] != BLOCK) dir[i++] = LEFT; else if (ghost.dir == RIGHT && map->map[ghost.y][ghost.x + 1] != BLOCK) dir[i++] = RIGHT; // Positions possibles if (ghost.dir != UP && ghost.dir != DOWN && map->map[ghost.y - 1][ghost.x] != BLOCK) dir[i++] = UP; if (ghost.dir != DOWN && ghost.dir != UP && map->map[ghost.y + 1][ghost.x] != BLOCK) dir[i++] = DOWN; if (ghost.dir != LEFT && ghost.dir != RIGHT && map->map[ghost.y][ghost.x - 1] != BLOCK) dir[i++] = LEFT; if (ghost.dir != RIGHT && ghost.dir != LEFT && map->map[ghost.y][ghost.x + 1] != BLOCK) dir[i++] = RIGHT; lastdir = ghost.dir; if (i > 0) ghost.dir = dir[(rand() % i)]; } } void Pacman::runGhost(character &ghost, map *map) { if (ghost.hasBonus != 0) { clock_t actTime = clock(); double timeSecs = (actTime - ghost.hasBonus) / (double) CLOCKS_PER_SEC; if (timeSecs > 0.05) ghost.hasBonus = 0; } else if (ghost.yf != (double) ghost.y || ghost.xf != (double) ghost.x) { if (ghost.yf < (double) ghost.y) { ghost.y -= 1; ghost.yf -= 0.5; } else if (ghost.yf > (double) ghost.y) { ghost.y += 1; ghost.yf += 0.5; } else if (ghost.xf < (double) ghost.x) { ghost.x -= 1; ghost.xf -= 0.5; } else if (ghost.xf > (double) ghost.x) { ghost.x += 1; ghost.xf += 0.5; } } else if (ghost.dir == UP && map->map[ghost.y - 1][ghost.x] != BLOCK) ghost.yf -= 0.5; else if (ghost.dir == DOWN && map->map[ghost.y + 1][ghost.x] != BLOCK) ghost.yf += 0.5; else if (ghost.dir == LEFT && map->map[ghost.y][ghost.x - 1] != BLOCK) { ghost.xf -= 0.5; if (ghost.xf < 0.0) { ghost.xf = 20.0; ghost.x = 20; } } else if (ghost.dir == RIGHT && map->map[ghost.y][ghost.x + 1] != BLOCK) { ghost.xf += 0.5; if (ghost.xf > 20.0) { ghost.xf = 0.0; ghost.x = 0; } } tryTurning(ghost, map); } void Pacman::runGame(map *map) { character player; int i; i = 0; if (map->hasWon == false && map->hasLost == false) { for (std::vector<character>::iterator node = map->player.begin(); node != map->player.end(); ++node) { if ((*node).type == PLAYER) { runPlayer((*node), map); player = (*node); } else if ((*node).type == CHARACTER) { if (map->current_score.score > i * 200) runGhost((*node), map); } i++; } clock_t actTime = clock(); double timeSeconds = (actTime - map->startTime) / (double) CLOCKS_PER_SEC; if (timeSeconds > 0.10) map->map[7][10] = PLATFORM; checkMap(map); } } void Pacman::stopGame() { } map *Pacman::createMap() { map *nmap; int i = 0; nmap = new map(); nmap->map = new map_content *[25]; while (i != 25) { nmap->map[i] = new map_content[25]; i++; } nmap->map[0][0] = EMPTY; nmap->map[0][1] = EMPTY; nmap->map[0][2] = EMPTY; nmap->map[0][3] = BLOCK; nmap->map[0][4] = BLOCK; nmap->map[0][5] = BLOCK; nmap->map[0][6] = BLOCK; nmap->map[0][7] = BLOCK; nmap->map[0][8] = BLOCK; nmap->map[0][9] = BLOCK; nmap->map[0][10] = BLOCK; nmap->map[0][11] = BLOCK; nmap->map[0][12] = BLOCK; nmap->map[0][13] = BLOCK; nmap->map[0][14] = BLOCK; nmap->map[0][15] = BLOCK; nmap->map[0][16] = BLOCK; nmap->map[0][17] = BLOCK; nmap->map[0][18] = EMPTY; nmap->map[0][19] = EMPTY; nmap->map[0][20] = EMPTY; nmap->map[1][0] = BLOCK; nmap->map[1][1] = BLOCK; nmap->map[1][2] = BLOCK; nmap->map[1][3] = BLOCK; nmap->map[1][4] = ITEM; nmap->map[1][5] = ITEM; nmap->map[1][6] = ITEM; nmap->map[1][7] = BLOCK; nmap->map[1][8] = BLOCK; nmap->map[1][9] = BLOCK; nmap->map[1][10] = BLOCK; nmap->map[1][11] = BLOCK; nmap->map[1][12] = BLOCK; nmap->map[1][13] = BLOCK; nmap->map[1][14] = ITEM; nmap->map[1][15] = ITEM; nmap->map[1][16] = ITEM; nmap->map[1][17] = BLOCK; nmap->map[1][18] = BLOCK; nmap->map[1][19] = BLOCK; nmap->map[1][20] = BLOCK; nmap->map[2][0] = BLOCK; nmap->map[2][1] = ITEM; nmap->map[2][2] = ITEM; nmap->map[2][3] = ITEM; nmap->map[2][4] = ITEM; nmap->map[2][5] = BLOCK; nmap->map[2][6] = ITEM; nmap->map[2][7] = ITEM; nmap->map[2][8] = ITEM; nmap->map[2][9] = ITEM; nmap->map[2][10] = ITEM; nmap->map[2][11] = ITEM; nmap->map[2][12] = ITEM; nmap->map[2][13] = ITEM; nmap->map[2][14] = ITEM; nmap->map[2][15] = BLOCK; nmap->map[2][16] = ITEM; nmap->map[2][17] = ITEM; nmap->map[2][18] = ITEM; nmap->map[2][19] = ITEM; nmap->map[2][20] = BLOCK; nmap->map[3][0] = BLOCK; nmap->map[3][1] = S_ITEM; nmap->map[3][2] = BLOCK; nmap->map[3][3] = BLOCK; nmap->map[3][4] = ITEM; nmap->map[3][5] = BLOCK; nmap->map[3][6] = ITEM; nmap->map[3][7] = BLOCK; nmap->map[3][8] = BLOCK; nmap->map[3][9] = BLOCK; nmap->map[3][10] = BLOCK; nmap->map[3][11] = BLOCK; nmap->map[3][12] = BLOCK; nmap->map[3][13] = BLOCK; nmap->map[3][14] = ITEM; nmap->map[3][15] = BLOCK; nmap->map[3][16] = ITEM; nmap->map[3][17] = BLOCK; nmap->map[3][18] = BLOCK; nmap->map[3][19] = S_ITEM; nmap->map[3][20] = BLOCK; nmap->map[4][0] = BLOCK; nmap->map[4][1] = ITEM; nmap->map[4][2] = ITEM; nmap->map[4][3] = ITEM; nmap->map[4][4] = ITEM; nmap->map[4][5] = BLOCK; nmap->map[4][6] = ITEM; nmap->map[4][7] = ITEM; nmap->map[4][8] = ITEM; nmap->map[4][9] = ITEM; nmap->map[4][10] = BLOCK; nmap->map[4][11] = ITEM; nmap->map[4][12] = ITEM; nmap->map[4][13] = ITEM; nmap->map[4][14] = ITEM; nmap->map[4][15] = BLOCK; nmap->map[4][16] = ITEM; nmap->map[4][17] = ITEM; nmap->map[4][18] = ITEM; nmap->map[4][19] = ITEM; nmap->map[4][20] = BLOCK; nmap->map[5][0] = BLOCK; nmap->map[5][1] = BLOCK; nmap->map[5][2] = BLOCK; nmap->map[5][3] = BLOCK; nmap->map[5][4] = ITEM; nmap->map[5][5] = BLOCK; nmap->map[5][6] = BLOCK; nmap->map[5][7] = BLOCK; nmap->map[5][8] = BLOCK; nmap->map[5][9] = ITEM; nmap->map[5][10] = BLOCK; nmap->map[5][11] = ITEM; nmap->map[5][12] = BLOCK; nmap->map[5][13] = BLOCK; nmap->map[5][14] = BLOCK; nmap->map[5][15] = BLOCK; nmap->map[5][16] = ITEM; nmap->map[5][17] = BLOCK; nmap->map[5][18] = BLOCK; nmap->map[5][19] = BLOCK; nmap->map[5][20] = BLOCK; nmap->map[6][0] = EMPTY; nmap->map[6][1] = EMPTY; nmap->map[6][2] = EMPTY; nmap->map[6][3] = BLOCK; nmap->map[6][4] = ITEM; nmap->map[6][5] = BLOCK; nmap->map[6][6] = BLOCK; nmap->map[6][7] = ITEM; nmap->map[6][8] = ITEM; nmap->map[6][9] = ITEM; nmap->map[6][10] = ITEM; nmap->map[6][11] = ITEM; nmap->map[6][12] = ITEM; nmap->map[6][13] = ITEM; nmap->map[6][14] = BLOCK; nmap->map[6][15] = BLOCK; nmap->map[6][16] = ITEM; nmap->map[6][17] = BLOCK; nmap->map[6][18] = EMPTY; nmap->map[6][19] = EMPTY; nmap->map[6][20] = EMPTY; nmap->map[7][0] = EMPTY; nmap->map[7][1] = EMPTY; nmap->map[7][2] = EMPTY; nmap->map[7][3] = BLOCK; nmap->map[7][4] = ITEM; nmap->map[7][5] = BLOCK; nmap->map[7][6] = BLOCK; nmap->map[7][7] = ITEM; nmap->map[7][8] = BLOCK; nmap->map[7][9] = BLOCK; nmap->map[7][10] = BLOCK; nmap->map[7][11] = BLOCK; nmap->map[7][12] = BLOCK; nmap->map[7][13] = ITEM; nmap->map[7][14] = BLOCK; nmap->map[7][15] = BLOCK; nmap->map[7][16] = ITEM; nmap->map[7][17] = BLOCK; nmap->map[7][18] = EMPTY; nmap->map[7][19] = EMPTY; nmap->map[7][20] = EMPTY; nmap->map[8][0] = BLOCK; nmap->map[8][1] = BLOCK; nmap->map[8][2] = BLOCK; nmap->map[8][3] = BLOCK; nmap->map[8][4] = ITEM; nmap->map[8][5] = BLOCK; nmap->map[8][6] = BLOCK; nmap->map[8][7] = ITEM; nmap->map[8][8] = BLOCK; nmap->map[8][9] = EMPTY; nmap->map[8][10] = EMPTY; nmap->map[8][11] = EMPTY; nmap->map[8][12] = BLOCK; nmap->map[8][13] = ITEM; nmap->map[8][14] = BLOCK; nmap->map[8][15] = BLOCK; nmap->map[8][16] = ITEM; nmap->map[8][17] = BLOCK; nmap->map[8][18] = BLOCK; nmap->map[8][19] = BLOCK; nmap->map[8][20] = BLOCK; nmap->map[9][0] = EMPTY; nmap->map[9][1] = EMPTY; nmap->map[9][2] = EMPTY; nmap->map[9][3] = EMPTY; nmap->map[9][4] = ITEM; nmap->map[9][5] = ITEM; nmap->map[9][6] = ITEM; nmap->map[9][7] = ITEM; nmap->map[9][8] = BLOCK; nmap->map[9][9] = EMPTY; nmap->map[9][10] = EMPTY; nmap->map[9][11] = EMPTY; nmap->map[9][12] = BLOCK; nmap->map[9][13] = ITEM; nmap->map[9][14] = ITEM; nmap->map[9][15] = ITEM; nmap->map[9][16] = ITEM; nmap->map[9][17] = EMPTY; nmap->map[9][18] = EMPTY; nmap->map[9][19] = EMPTY; nmap->map[9][20] = EMPTY; nmap->map[10][0] = BLOCK; nmap->map[10][1] = BLOCK; nmap->map[10][2] = BLOCK; nmap->map[10][3] = BLOCK; nmap->map[10][4] = ITEM; nmap->map[10][5] = BLOCK; nmap->map[10][6] = BLOCK; nmap->map[10][7] = ITEM; nmap->map[10][8] = BLOCK; nmap->map[10][9] = BLOCK; nmap->map[10][10] = BLOCK; nmap->map[10][11] = BLOCK; nmap->map[10][12] = BLOCK; nmap->map[10][13] = ITEM; nmap->map[10][14] = BLOCK; nmap->map[10][15] = BLOCK; nmap->map[10][16] = ITEM; nmap->map[10][17] = BLOCK; nmap->map[10][18] = BLOCK; nmap->map[10][19] = BLOCK; nmap->map[10][20] = BLOCK; nmap->map[11][0] = EMPTY; nmap->map[11][1] = EMPTY; nmap->map[11][2] = EMPTY; nmap->map[11][3] = BLOCK; nmap->map[11][4] = ITEM; nmap->map[11][5] = ITEM; nmap->map[11][6] = ITEM; nmap->map[11][7] = ITEM; nmap->map[11][8] = ITEM; nmap->map[11][9] = ITEM; nmap->map[11][10] = EMPTY; nmap->map[11][11] = ITEM; nmap->map[11][12] = ITEM; nmap->map[11][13] = ITEM; nmap->map[11][14] = ITEM; nmap->map[11][15] = ITEM; nmap->map[11][16] = ITEM; nmap->map[11][17] = BLOCK; nmap->map[11][18] = EMPTY; nmap->map[11][19] = EMPTY; nmap->map[11][20] = EMPTY; nmap->map[12][0] = EMPTY; nmap->map[12][1] = EMPTY; nmap->map[12][2] = EMPTY; nmap->map[12][3] = BLOCK; nmap->map[12][4] = ITEM; nmap->map[12][5] = BLOCK; nmap->map[12][6] = BLOCK; nmap->map[12][7] = BLOCK; nmap->map[12][8] = BLOCK; nmap->map[12][9] = ITEM; nmap->map[12][10] = BLOCK; nmap->map[12][11] = ITEM; nmap->map[12][12] = BLOCK; nmap->map[12][13] = BLOCK; nmap->map[12][14] = BLOCK; nmap->map[12][15] = BLOCK; nmap->map[12][16] = ITEM; nmap->map[12][17] = BLOCK; nmap->map[12][18] = EMPTY; nmap->map[12][19] = EMPTY; nmap->map[12][20] = EMPTY; nmap->map[13][0] = BLOCK; nmap->map[13][1] = BLOCK; nmap->map[13][2] = BLOCK; nmap->map[13][3] = BLOCK; nmap->map[13][4] = ITEM; nmap->map[13][5] = BLOCK; nmap->map[13][6] = ITEM; nmap->map[13][7] = ITEM; nmap->map[13][8] = ITEM; nmap->map[13][9] = ITEM; nmap->map[13][10] = BLOCK; nmap->map[13][11] = ITEM; nmap->map[13][12] = ITEM; nmap->map[13][13] = ITEM; nmap->map[13][14] = ITEM; nmap->map[13][15] = BLOCK; nmap->map[13][16] = ITEM; nmap->map[13][17] = BLOCK; nmap->map[13][18] = BLOCK; nmap->map[13][19] = BLOCK; nmap->map[13][20] = BLOCK; nmap->map[14][0] = BLOCK; nmap->map[14][1] = ITEM; nmap->map[14][2] = ITEM; nmap->map[14][3] = ITEM; nmap->map[14][4] = ITEM; nmap->map[14][5] = BLOCK; nmap->map[14][6] = ITEM; nmap->map[14][7] = BLOCK; nmap->map[14][8] = BLOCK; nmap->map[14][9] = BLOCK; nmap->map[14][10] = BLOCK; nmap->map[14][11] = BLOCK; nmap->map[14][12] = BLOCK; nmap->map[14][13] = BLOCK; nmap->map[14][14] = ITEM; nmap->map[14][15] = BLOCK; nmap->map[14][16] = ITEM; nmap->map[14][17] = ITEM; nmap->map[14][18] = ITEM; nmap->map[14][19] = ITEM; nmap->map[14][20] = BLOCK; nmap->map[15][0] = BLOCK; nmap->map[15][1] = S_ITEM; nmap->map[15][2] = BLOCK; nmap->map[15][3] = BLOCK; nmap->map[15][4] = ITEM; nmap->map[15][5] = BLOCK; nmap->map[15][6] = ITEM; nmap->map[15][7] = ITEM; nmap->map[15][8] = ITEM; nmap->map[15][9] = ITEM; nmap->map[15][10] = ITEM; nmap->map[15][11] = ITEM; nmap->map[15][12] = ITEM; nmap->map[15][13] = ITEM; nmap->map[15][14] = ITEM; nmap->map[15][15] = BLOCK; nmap->map[15][16] = ITEM; nmap->map[15][17] = BLOCK; nmap->map[15][18] = BLOCK; nmap->map[15][19] = S_ITEM; nmap->map[15][20] = BLOCK; nmap->map[16][0] = BLOCK; nmap->map[16][1] = ITEM; nmap->map[16][2] = ITEM; nmap->map[16][3] = ITEM; nmap->map[16][4] = ITEM; nmap->map[16][5] = ITEM; nmap->map[16][6] = ITEM; nmap->map[16][7] = BLOCK; nmap->map[16][8] = BLOCK; nmap->map[16][9] = BLOCK; nmap->map[16][10] = BLOCK; nmap->map[16][11] = BLOCK; nmap->map[16][12] = BLOCK; nmap->map[16][13] = BLOCK; nmap->map[16][14] = ITEM; nmap->map[16][15] = ITEM; nmap->map[16][16] = ITEM; nmap->map[16][17] = ITEM; nmap->map[16][18] = ITEM; nmap->map[16][19] = ITEM; nmap->map[16][20] = BLOCK; nmap->map[17][0] = BLOCK; nmap->map[17][1] = BLOCK; nmap->map[17][2] = BLOCK; nmap->map[17][3] = BLOCK; nmap->map[17][4] = BLOCK; nmap->map[17][5] = BLOCK; nmap->map[17][6] = BLOCK; nmap->map[17][7] = BLOCK; nmap->map[17][8] = BLOCK; nmap->map[17][9] = BLOCK; nmap->map[17][10] = BLOCK; nmap->map[17][11] = BLOCK; nmap->map[17][12] = BLOCK; nmap->map[17][13] = BLOCK; nmap->map[17][14] = BLOCK; nmap->map[17][15] = BLOCK; nmap->map[17][16] = BLOCK; nmap->map[17][17] = BLOCK; nmap->map[17][18] = BLOCK; nmap->map[17][19] = BLOCK; nmap->map[17][20] = BLOCK; character player; character ghost1; character ghost2; character ghost3; character ghost4; player.x = 10; player.y = 11; player.xf = 10.0; player.yf = 11.0; player.dir = RIGHT; player.type = PLAYER; player.hasBonus = 0; ghost1.x = 9; ghost1.y = 8; ghost1.xf = 9.0; ghost1.yf = 8.0; ghost1.dir = UP; ghost1.type = CHARACTER; ghost1.hasBonus = 0; ghost2.x = 10; ghost2.y = 8; ghost2.xf = 10.0; ghost2.yf = 8.0; ghost2.dir = UP; ghost2.type = CHARACTER; ghost2.hasBonus = 0; ghost3.x = 11; ghost3.y = 8; ghost3.xf = 11.0; ghost3.yf = 8.0; ghost3.dir = UP; ghost3.type = CHARACTER; ghost3.hasBonus = 0; ghost4.x = 10; ghost4.y = 9; ghost4.xf = 10.0; ghost4.yf = 9.0; ghost4.dir = UP; ghost4.type = CHARACTER; ghost4.hasBonus = 0; nmap->player.push_back(player); nmap->player.push_back(ghost1); nmap->player.push_back(ghost2); nmap->player.push_back(ghost3); nmap->player.push_back(ghost4); nmap->startTime = clock(); nmap->height = 18; nmap->width = 21; nmap->current_score.score = 0; nmap->hasWon = false; nmap->hasLost = false; nmap->save = false; return nmap; } void Pacman::addScore(int point, map *map) { } int Pacman::goUp(map *map) { for (std::vector<character>::iterator node = map->player.begin(); node != map->player.end(); ++node) { if ((*node).type == PLAYER && (*node).dir != UP) { (*node).dir = UP; return (0); } } return (1); } int Pacman::goDown(map *map) { for (std::vector<character>::iterator node = map->player.begin(); node != map->player.end(); ++node) { if ((*node).type == PLAYER && (*node).dir != DOWN) { (*node).dir = DOWN; return (0); } } return (1); } int Pacman::goLeft(map *map) { for (std::vector<character>::iterator node = map->player.begin(); node != map->player.end(); ++node) { if ((*node).type == PLAYER && (*node).dir != LEFT) { (*node).dir = LEFT; return (0); } } return (1); } int Pacman::goRight(map *map) { for (std::vector<character>::iterator node = map->player.begin(); node != map->player.end(); ++node) { if ((*node).type == PLAYER && (*node).dir != RIGHT) { (*node).dir = RIGHT; return (0); } } return (1); } extern "C" class Pacman *create_game() { return new Pacman(); }
40.394336
558
0.553961
[ "vector" ]
ac6c5dbcc353c16ce6f4a8f1f161e8675f816a7b
663
cpp
C++
acwing/1524.cpp
zyzisyz/OJ
55221a55515231182b6bd133edbdb55501a565fc
[ "Apache-2.0" ]
null
null
null
acwing/1524.cpp
zyzisyz/OJ
55221a55515231182b6bd133edbdb55501a565fc
[ "Apache-2.0" ]
null
null
null
acwing/1524.cpp
zyzisyz/OJ
55221a55515231182b6bd133edbdb55501a565fc
[ "Apache-2.0" ]
2
2020-01-01T13:49:08.000Z
2021-03-06T06:54:26.000Z
#include<iostream> #include<string> #include<vector> #include<algorithm> using namespace std; string str; int main(void){ getline(cin, str); int n = str.size(); string re_str = str; reverse(re_str.begin(), re_str.end()); if(str==re_str){ cout<<n<<endl; return 0; } vector<vector<int>> f(n, vector<int>(n, 0)); int res = 1; for(int i=0; i<n; i++) f[i][i] = 1; for(int i=1; i<n; i++) { if(str[i]==str[i-1]){ f[i-1][i] = 1; res = 2; } } for(int l=3; l<=n; l++){ for(int i=0; i+l-1<n; i++){ int end = i+l-1; if(str[i]==str[end] && f[i+1][end-1]==1){ f[i][end] = 1; res = max(l, res); } } } cout<<res<<endl; }
14.733333
45
0.524887
[ "vector" ]
ac732b1ee329cd7dfe19f4e3604c6ac76e3a1308
7,301
cc
C++
src/util/str_util.cc
LeeOHzzZ/ILAng
24225294ac133e5d08af5037350ede8f78610c45
[ "MIT" ]
21
2019-03-18T18:35:35.000Z
2022-01-27T06:57:47.000Z
src/util/str_util.cc
LeeOHzzZ/ILAng
24225294ac133e5d08af5037350ede8f78610c45
[ "MIT" ]
105
2019-01-19T07:09:25.000Z
2021-01-11T20:06:24.000Z
src/util/str_util.cc
LeeOHzzZ/ILAng
24225294ac133e5d08af5037350ede8f78610c45
[ "MIT" ]
7
2019-01-28T19:48:09.000Z
2020-11-05T14:42:05.000Z
/// \file /// Source for some utility functions for string formating. #include <ilang/util/str_util.h> #include <regex> #include <sstream> #include <type_traits> #include <ilang/util/log.h> #if defined(_WIN32) || defined(_WIN64) #include <locale> #endif namespace ilang { // it is of course possible to update it with arbitrary base std::string IntToStrCustomBase(uint64_t value, unsigned base, bool uppercase) { ILA_ASSERT(base > 1 && base <= 36) << "unsupported base : " << base; if (value == 0) return "0"; std::string ret; while (value != 0) { unsigned digit_val = value % base; char digit = (digit_val < 10) ? ('0' + digit_val) : ((uppercase ? 'A' : 'a') + digit_val - 10); ret = digit + ret; value /= base; } return ret; } std::string StrToUpper(const std::string& str) { std::string res = str; std::transform(res.begin(), res.end(), res.begin(), toupper); return res; } std::string StrToLower(const std::string& str) { std::string res = str; std::transform(res.begin(), res.end(), res.begin(), tolower); return res; } bool StrToBool(const std::string& str) { std::string up = StrToUpper(str); ILA_ASSERT((up == "TRUE") || (up == "FALSE")) << "Unknown boolean value " << up << "\n"; return (up == "TRUE"); } int StrToInt(const std::string& str, int base) { try { return std::stoi(str, NULL, base); } catch (const std::exception& e) { ILA_ERROR << "Converting non-numeric value " << str << " to int."; return 0; } } long long StrToLong(const std::string& str, int base) { try { return std::stoll(str, NULL, base); } catch (const std::exception& e) { ILA_ERROR << "Converting non-numeric value " << str << " to long int."; return 0; } } unsigned long long StrToULongLong(const std::string& str, int base) { try { return std::stoull(str, NULL, base); } catch (const std::exception& e) { ILA_ERROR << "Converting non-numeric value " << str << " to unsigned long long"; return 0; } } /// Trim a string from start (in place) void StrLeftTrim(std::string& s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { #if defined(_WIN32) || defined(_WIN64) return !std::isspace(ch, std::locale("en_US.UTF8")); #else return !std::isspace(static_cast<unsigned char>(ch)); #endif })); } /// Trim a string from end (in place) void StrRightTrim(std::string& s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { #if defined(_WIN32) || defined(_WIN64) return ! std::isspace(ch, std::locale("en_US.UTF8")); #else return !std::isspace(static_cast<unsigned char>(ch)); #endif }).base(), s.end()); } /// Trim a string from both ends (in place) void StrTrim(std::string &s) { StrLeftTrim(s); StrRightTrim(s); } std::vector<std::string> Split(const std::string& str, const std::string& delim) { std::vector<std::string> tokens; size_t prev = 0, pos = 0; do { pos = str.find(delim, prev); if (pos == std::string::npos) pos = str.length(); std::string token = str.substr(prev, pos - prev); if (!token.empty()) tokens.push_back(token); prev = pos + delim.length(); } while (pos < str.length() && prev < str.length()); return tokens; } std::vector<std::string> SplitSpaceTabEnter(const std::string& str) { std::vector<std::string> result; std::istringstream iss(str); for (std::string s; iss >> s;) result.push_back(s); return result; } std::string Join(const std::vector<std::string>& in, const std::string& delim) { std::string ret; std::string d = ""; for (auto&& s : in) { ret += (d + s); d = delim; } return ret; } /// Remove whitespace ' \n\t\r\f\v' std::string RemoveWhiteSpace(const std::string & in) { auto s = in; s.erase(std::remove_if(s.begin(), s.end(), ::isspace), s.end()); return s; } /// Replace all occurrance of substring a by substring b std::string ReplaceAll(const std::string& str, const std::string& a, const std::string& b) { std::string result; size_t find_len = a.size(); size_t pos, from = 0; while (std::string::npos != (pos = str.find(a, from))) { result.append(str, from, pos - from); result.append(b); from = pos + find_len; } result.append(str, from, std::string::npos); return result; } // GCC supports this after 4.9.0 // not available on Ubuntu 14.04 LTS #ifdef __GNUC__ #if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9)) std::vector<std::string> ReFindList(const std::string& s, const std::string& re) { std::vector<std::string> tokens; std::regex word_regex(re); auto words_begin = std::sregex_iterator(s.begin(), s.end(), word_regex); auto words_end = std::sregex_iterator(); for (std::sregex_iterator i = words_begin; i != words_end; ++i) { std::smatch match = *i; std::string match_str = match.str(); tokens.push_back(match_str); } return tokens; } std::vector<std::string> ReFindAndDo(const std::string& s, const std::string& re, std::function<std::string(std::string)> f) { std::vector<std::string> tokens; std::regex word_regex(re); auto words_begin = std::sregex_iterator(s.begin(), s.end(), word_regex); auto words_end = std::sregex_iterator(); for (std::sregex_iterator i = words_begin; i != words_end; ++i) { std::smatch match = *i; std::string match_str = match.str(); tokens.push_back(f(match_str)); } return tokens; } bool IsRExprUsable() { return true; } #else // not supported std::vector<std::string> ReFindList(const std::string& s, const std::string& re) { ILA_ASSERT(false) << "Not suppported: please use GCC 4.9.0 or above to " "enable this function"; return std::vector<std::string>(); } std::vector<std::string> ReFindAndDo(const std::string& s, const std::string& re, std::function<std::string(std::string)> f) { ILA_ASSERT(false) << "Not suppported: please use GCC 4.9.0 or above to " "enable this function"; return std::vector<std::string>(); } bool IsRExprUsable() { return false; } #endif #else // not defined std::vector<std::string> ReFindList(const std::string& s, const std::string& re) { ILA_ASSERT(false) << "Not suppported: please use GCC 4.9.0 or above to " "enable this function"; return std::vector<std::string>(); } std::vector<std::string> ReFindAndDo(const std::string& s, const std::string& re, std::function<std::string(std::string)> f) { ILA_ASSERT(false) << "Not suppported: please use GCC 4.9.0 or above to " "enable this function"; return std::vector<std::string>(); } bool IsRExprUsable() { return false; } #endif bool StrEndsWith(const std::string& str, const std::string& suffix) { return str.size() >= suffix.size() && 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix); } bool StrStartsWith(const std::string& str, const std::string& prefix) { return str.size() >= prefix.size() && 0 == str.compare(0, prefix.size(), prefix); } } // namespace ilang
28.189189
80
0.61019
[ "vector", "transform" ]
ac7e068b6a72726801c063de6b950ef62cd43bac
6,757
cpp
C++
legacy_firmware/firmware/steval_gps_waves_drifter/params.cpp
jerabaul29/OpenMetBuoy-v2021a
8fa4a3a9de82c8b82ecf290ccf57303cad667041
[ "MIT" ]
7
2021-12-07T18:37:21.000Z
2022-03-28T17:26:50.000Z
legacy_firmware/firmware/standard_gps_waves_thermistors_drifter/params.cpp
jerabaul29/OpenMetBuoy-v2021a
8fa4a3a9de82c8b82ecf290ccf57303cad667041
[ "MIT" ]
32
2021-12-09T08:28:20.000Z
2022-03-31T21:16:01.000Z
legacy_firmware/firmware/two_ways_gps_waves_drifter/params.cpp
jerabaul29/OpenMetBuoy-v2021a
8fa4a3a9de82c8b82ecf290ccf57303cad667041
[ "MIT" ]
null
null
null
#include "params.h" void print_params(void){ Serial.print(F("baudrate_debug_serial : ")); Serial.println(baudrate_debug_serial ); Serial.print(F("i2c_port_number: ")); Serial.println(i2c_port_number ); Serial.println(F("----- TEST_MODE -----")); Serial.print(F("DEPLOYMENT_MODE: ")); Serial.println(DEPLOYMENT_MODE); Serial.print(F("DEPLOYMENT_INFO: ")); Serial.println(DEPLOYMENT_INFO); delay(50); Serial.println(F("----- IMU_DATA_GATHERING_MODE -----")); Serial.print(F("use_dummy_imu_data: ")); Serial.println(use_dummy_imu_data); Serial.println(F("IF use_dummy_imu_data is TRUE, then use synthetic dummy signal (harmonic signal); if FALSE, then use true signal")); Serial.print(F("dummy_imu_elevation_amplitude: ")); Serial.println(dummy_imu_elevation_amplitude, 4); Serial.print(F("std dummy_imu_elevation_amplitude: ")); Serial.println(dummy_imu_elevation_amplitude / sqrt2_f, 4); Serial.print(F("SWH dummy_imu_elevation_amplitude: ")); Serial.println(4.0f * dummy_imu_elevation_amplitude / sqrt2_f, 4); Serial.print(F("dummy_imu_accel_constant_component: ")); Serial.println(dummy_imu_accel_constant_component, 4); Serial.print(F("dummy_imu_accel_amplitude: ")); Serial.println(dummy_imu_accel_amplitude, 4); Serial.print(F("std dummy_imu_accel_amplitude: ")); Serial.println(dummy_imu_accel_amplitude / sqrt2_f, 4); Serial.print(F("dummy_imu_accel_frequency: ")); Serial.println(dummy_imu_accel_frequency, 4); delay(50); Serial.println(F("----- PARAMS GNSS ----")); Serial.print(F("timeout_first_fix_seconds: ")); Serial.println(timeout_first_fix_seconds); Serial.print(F("sleep_no_initial_fix_seconds: ")); Serial.println(sleep_no_initial_fix_seconds); Serial.print(F("timeout_gnss_fix_seconds: ")); Serial.println(timeout_gnss_fix_seconds); Serial.print(F("interval_between_gnss_measurements_seconds: ")); Serial.println(interval_between_gnss_measurements_seconds); Serial.print(F("size_gps_fix_buffer: ")); Serial.println(size_gps_fix_buffer); Serial.print(F("min_nbr_of_fix_per_message: ")); Serial.println(min_nbr_of_fix_per_message); Serial.print(F("max_nbr_GPS_fixes_per_message: ")); Serial.println(max_nbr_GPS_fixes_per_message); delay(50); Serial.println(F("----- PARAMS IRIDIUM -----")); Serial.print(F("timeout_cap_charging_seconds: ")); Serial.println(timeout_cap_charging_seconds); #ifdef ISBD_DIAGNOSTICS Serial.println(F("provide ISBD diagnostics")); #else Serial.println(F("no ISBD diagnostics")); #endif delay(50); Serial.println(F("----- IMU PARAMS -----")); Serial.print(F("using magnometer: ")); Serial.println(imu_use_magnetometer); Serial.print(F("using HARD CODED Kalman output freq [Hz]: ")); Serial.println(10); Serial.print(F("blink_when_use_IMU: ")); Serial.println(blink_when_use_IMU); Serial.print(F("number_update_between_blink: ")); Serial.println(number_update_between_blink); delay(50); Serial.println(F("----- SPECTRA PARAMS -----")); Serial.print(F("use_wave_measurements [1: true; 0: false]: ")); Serial.println(use_wave_measurements); Serial.print(F("using fft transform length: ")); Serial.println(fft_length); Serial.print(F("using fft overlap nbr of points: ")); Serial.println(fft_overlap); Serial.print(F("using total number of samples: ")); Serial.println(total_number_of_samples); Serial.print(F("using number Welch segments: ")); Serial.println(number_welch_segments); Serial.print(F("welch and fft frequency resolution [Hz per bin]: ")); Serial.println(welch_frequency_resolution, 4); Serial.print(F("first transmitted bin has ind: ")); Serial.println(welch_bin_min); Serial.print(F("last transmitted bin has ind: ")); Serial.println(welch_bin_max); Serial.print(F("first transmitted bin has freq: ")); Serial.println(welch_bin_min * welch_frequency_resolution); Serial.print(F("last transmitted bin has freq: ")); Serial.println(welch_bin_max * welch_frequency_resolution); Serial.print(F("interval_between_wave_spectra_measurements: ")); Serial.println(interval_between_wave_spectra_measurements); Serial.print(F("tolerance_seconds_start_wave_measurements: ")); Serial.println(tolerance_seconds_start_wave_measurements); Serial.print(F("use windowing (only one windowing can be used at a time) | hanning ")); Serial.print(use_hanning_window); Serial.print(F(" | hamming ")); Serial.println(use_hamming_window); delay(50); Serial.println(F("----- TEMPERATURE PARAMS -----")); Serial.print(F("use_thermistor_string [1: true; 0: false]: ")); Serial.println(use_thermistor_string); Serial.print(F("interval_between_thermistors_measurements_seconds: ")); Serial.println(interval_between_thermistors_measurements_seconds); Serial.print(F("tolerance_seconds_start_thermistors_measurements: ")); Serial.println(tolerance_seconds_start_thermistors_measurements); Serial.print(F("max number of temp sensors: ")); Serial.println(number_of_thermistors); Serial.print(F("duration temp sensors acquisition [ms]: ")); Serial.println(duration_thermistor_acquisition_ms); Serial.print(F("duration imu acquisition for temp string attitutde [ms]: ")); Serial.println(duration_thermistor_imu_acquisition_ms); Serial.print(F("max_nbr_thermistor_packet: ")); Serial.println(max_nbr_thermistor_packets); Serial.print(F("min_default_nbr_thermistor_packet: ")); Serial.println(min_default_nbr_thermistor_packets); Serial.print(F("size_thermistors_packet_buffer: ")); Serial.println(size_thermistors_packets_buffer); Serial.print(F("roll_float_to_int8_factor: ")); Serial.println(roll_float_to_int8_factor); Serial.print(F("pitch_float_to_int8_factor: ")); Serial.println(pitch_float_to_int8_factor); delay(50); Serial.println(F("----- MISC PARAMS -----")); #if (PERFORM_SLEEP_BLINK == 1) Serial.println(F("perform sleep blink")); Serial.print(F("interval_between_sleep_LED_blink_seconds: ")); Serial.println(interval_between_sleep_LED_blink_seconds); Serial.print(F("duration_sleep_LED_blink_milliseconds: ")); Serial.println(duration_sleep_LED_blink_milliseconds); #else Serial.println(F("no sleep blink")); #endif delay(50); Serial.println(F("----- END PARAMS -----")); } long modifiable_interval_between_wave_spectra_measurements {interval_between_wave_spectra_measurements}; long modifiable_interval_between_gnss_measurements_seconds {interval_between_gnss_measurements_seconds}; size_t modifiable_min_nbr_of_fix_per_message {min_nbr_of_fix_per_message}; long modifiable_interval_between_thermistors_measurements_seconds {interval_between_thermistors_measurements_seconds};
69.659794
193
0.753737
[ "transform" ]
ac85789747c4710b621584862278b29abae3d679
922
cpp
C++
AAD/Aufgabe4.2/myClass.cpp
Solaflex/hf-ict
2ebed689087407019b540df07612525e8b8d6821
[ "MIT" ]
null
null
null
AAD/Aufgabe4.2/myClass.cpp
Solaflex/hf-ict
2ebed689087407019b540df07612525e8b8d6821
[ "MIT" ]
null
null
null
AAD/Aufgabe4.2/myClass.cpp
Solaflex/hf-ict
2ebed689087407019b540df07612525e8b8d6821
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <C:\git\RunProject\RunProject\myHeader.h> using namespace std; Result::Result() { cout << "Konstruktor" << endl; } Result ArrayUtil::analyseArray(vector<int> input) { Result ReturnResult; int PositiveCounter = 0, ZeroCounter = 0, NegativeCounter = 0, TotalCounter = 0; vector<int>::iterator it; for (it = input.begin(); it != input.end(); it++) { // Increase the total counter TotalCounter++; // Compare the number if (*it < 0) { NegativeCounter++; } else if (*it == 0) { ZeroCounter++; } else { PositiveCounter++; } } // Calculate the percentage. Multiply with 100 to reduce rounding issues ReturnResult.nNegative = (NegativeCounter * 100.0) / TotalCounter; ReturnResult.nZero = (ZeroCounter * 100.0) / TotalCounter; ReturnResult.nPositive = (PositiveCounter * 100.0) / TotalCounter; return ReturnResult; }
20.954545
81
0.682213
[ "vector" ]
12be8621bd6461b08ed9f047e15252f1ea6222c4
1,342
cpp
C++
algorithms/graph theory/PrimsMST.cpp
HannoFlohr/hackerrank
9644c78ce05a6b1bc5d8f542966781d53e5366e3
[ "MIT" ]
null
null
null
algorithms/graph theory/PrimsMST.cpp
HannoFlohr/hackerrank
9644c78ce05a6b1bc5d8f542966781d53e5366e3
[ "MIT" ]
null
null
null
algorithms/graph theory/PrimsMST.cpp
HannoFlohr/hackerrank
9644c78ce05a6b1bc5d8f542966781d53e5366e3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; struct Less { bool operator()(const pair<int,int> &p1, const pair<int,int> &p2) const { return p1.second > p2.second; } }; int prims(const int &n, vector<vector<int>> &edges, int start) { vector<vector<pair<int,int>>> e( n+1 ); for(int i=0; i<edges.size(); i++) { e[edges[i][0]].push_back(make_pair(edges[i][1],edges[i][2])); e[edges[i][1]].push_back(make_pair(edges[i][0],edges[i][2])); } priority_queue<pair<int,int>, vector<pair<int,int>>, Less> q; int sum = 0, j = 1; vector<int> v (n+1,0); v[start] = 1; pair<int,int> next; while(j <= n) { for(int i=0; i<e[start].size(); i++) q.push( e[start][i] ); next = q.top(); while(v[next.first]!=0 && !q.empty()) { q.pop(); next = q.top(); } if(v[next.first]==1) break; v[next.first] = 1; start = next.first; sum += next.second; q.pop(); j++; } return sum; } int main() { int n, e, start, a, b, w; cin >> n >> e; vector<vector<int>> v (e, vector<int>(3)); for(int i=0; i<e; i++) cin >> v[i][0] >> v[i][1] >> v[i][2]; cin >> start; int result = prims(n, v, start); cout << result << endl; return 0; }
23.54386
77
0.483607
[ "vector" ]
12c84cac26a1733bf8f4d24773139945b9e2e026
24,342
cpp
C++
src/vscp/common/udpsrv.cpp
nanocortex/vscp
0b1a51a35a886921179a8112c592547f84c9771a
[ "CC-BY-3.0" ]
null
null
null
src/vscp/common/udpsrv.cpp
nanocortex/vscp
0b1a51a35a886921179a8112c592547f84c9771a
[ "CC-BY-3.0" ]
null
null
null
src/vscp/common/udpsrv.cpp
nanocortex/vscp
0b1a51a35a886921179a8112c592547f84c9771a
[ "CC-BY-3.0" ]
null
null
null
// udpsrv.cpp // // This file is part of the VSCP (https://www.vscp.org) // // The MIT License (MIT) // // Copyright © 2000-2020 Ake Hedman, Grodans Paradis AB // <info@grodansparadis.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #include "udpsrv.h" #include <arpa/inet.h> #include <stdlib.h> #include <syslog.h> #include <unistd.h> #include <controlobject.h> #include <crc.h> #include <dllist.h> #include <tcpipsrv.h> #include <version.h> #include <vscp.h> #include <vscp_aes.h> #include <vscphelper.h> #include <string> /////////////////////////////////////////////////////////////////////////////// // get_ip_str // // Convert a struct sockaddr address to a string, IPv4 and IPv6: // char* get_ip_str(const struct sockaddr* sa, char* s, size_t maxlen) { switch (sa->sa_family) { case AF_INET: inet_ntop(AF_INET, &(((struct sockaddr_in*)sa)->sin_addr), s, maxlen); break; case AF_INET6: inet_ntop(AF_INET6, &(((struct sockaddr_in6*)sa)->sin6_addr), s, maxlen); break; default: strncpy(s, "Unknown AF", maxlen); return NULL; } return s; } // ----------------------------------------------------------------------------- udpRemoteClient::udpRemoteClient() { m_bQuit = false; m_bEnable = false; m_sockfd = 0; m_index = 0; // Rolling index starts at zero m_nEncryption = VSCP_ENCRYPTION_NONE; m_bSetBroadcast = false; m_pClientItem = NULL; } udpRemoteClient::~udpRemoteClient() { close(m_sockfd); } //////////////////////////////////////////////////////////////////////////////// // init // int udpRemoteClient::init(CControlObject* pobj, uint8_t nEncryption, bool bSetBroadcast) { setControlObjectPointer(pobj); m_nEncryption = nEncryption; m_bSetBroadcast = bSetBroadcast; if (-1 == (m_sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))) { return VSCP_ERROR_ERROR; } memset((char*)&m_clientAddress, 0, sizeof(m_clientAddress)); m_clientAddress.sin_family = AF_INET; m_clientAddress.sin_port = htons(m_remotePort); if (0 == inet_aton(m_remoteAddress.c_str(), &m_clientAddress.sin_addr)) { syslog(LOG_ERR, "UDP remote client: inet_aton() failed."); close(m_sockfd); return VSCP_ERROR_ERROR; } return VSCP_ERROR_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // startWorkerThread // bool udpRemoteClient::startWorkerThread(void) { if (pthread_create(&m_udpClientWorkerThread, NULL, udpClientWorkerThread, this)) { syslog(LOG_ERR, "Controlobject: Unable to start the UDP server thread."); return false; } return true; } //////////////////////////////////////////////////////////////////////////////// // sendFrames // int udpRemoteClient::sendFrame(void) { // We specify a send buffer that holds the maximum possible size unsigned char sendbuf[VSCP_MULTICAST_PACKET0_MAX]; // Send buffer uint8_t iv[16]; // Initialization vector // Check if there is an event to send if (!m_pClientItem->m_clientInputQueue.size()) { return false; } pthread_mutex_lock(&m_pClientItem->m_mutexClientInputQueue); vscpEvent* pEvent = m_pClientItem->m_clientInputQueue.front(); m_pClientItem->m_clientInputQueue.pop_front(); pthread_mutex_unlock(&m_pClientItem->m_mutexClientInputQueue); if (NULL == pEvent) return false; // Check that size is valid if (pEvent->sizeData > VSCP_LEVEL2_MAXDATA) { vscp_deleteEvent_v2(&pEvent); return false; } // Send the event to client // pthread_mutex_lock(&m_pCtrlObj->m_mutexUDPRemotes); // for ( auto it = m_pCtrlObj->m_udpremotes.crbegin(); // it != m_pCtrlObj->m_udpremotes.crend(); // ++it) { // udpRemoteClient *pRemoteUDPNode = *it; // Check if filtered out // if (!vscp_doLevel2Filter(pEvent, &pRemoteUDPNode->m_filter)) { // continue; // } // Packet type sendbuf[VSCP_MULTICAST_PACKET0_POS_PKTTYPE] = SET_VSCP_MULTICAST_TYPE(0, m_nEncryption); // Get initialization vector getRandomIV(iv, 16); uint8_t wrkbuf[VSCP_MULTICAST_PACKET0_MAX]; memset(wrkbuf, 0, sizeof(wrkbuf)); if (!vscp_writeEventToFrame(wrkbuf, sizeof(wrkbuf), SET_VSCP_MULTICAST_TYPE(0, m_nEncryption), pEvent)) { vscp_deleteEvent_v2(&pEvent); return VSCP_ERROR_OPERATION_FAILED; } // Write rolling index wrkbuf[VSCP_MULTICAST_PACKET0_POS_HEAD_LSB] &= 0xf8; wrkbuf[VSCP_MULTICAST_PACKET0_POS_HEAD_LSB] |= (0x07 & m_index); m_index++; size_t lenSend = 1 + VSCP_MULTICAST_PACKET0_HEADER_LENGTH + pEvent->sizeData + 2; if (0 == (lenSend = vscp_encryptFrame(sendbuf, wrkbuf, lenSend, m_pCtrlObj->getSystemKey(NULL), iv, m_nEncryption))) { vscp_deleteEvent_v2(&pEvent); return VSCP_ERROR_OPERATION_FAILED; } #if 0 int i; xxPrintf("IV = "); for (i = 0; i < 16; i++) { xxPrintf("%02X ", iv[i]); } xxPrintf("\n"); xxPrintf("key = "); uint8_t *pkey = m_pobj->getSystemKey(NULL); for (i = 0; i < 32; i++) { xxPrintf("%02X ", pkey[i]); } xxPrintf("\n"); #endif // Send event to client int nsent = sendto(m_sockfd, sendbuf, lenSend, 0, (struct sockaddr*)&m_remoteAddress, sizeof(m_remoteAddress)); return VSCP_ERROR_SUCCESS; } // ---------------------------------------------------------------------------- // * * * * UDPSrvObj * * * * /////////////////////////////////////////////////////////////////////////////// // CTOR // // udpSrvObj::udpSrvObj() { m_bQuit = false; // Default server information m_servaddr.sin_family = AF_INET; // IPv4 m_servaddr.sin_addr.s_addr = INADDR_ANY; m_servaddr.sin_port = htons(VSCP_DEFAULT_UDP_PORT); m_pClientItem = NULL; pthread_mutex_init(&m_mutexUDPInfo, NULL); } /////////////////////////////////////////////////////////////////////////////// // DTOR // udpSrvObj::~udpSrvObj() { pthread_mutex_destroy(&m_mutexUDPInfo); } //////////////////////////////////////////////////////////////////////////////// // receiveFrame // int udpSrvObj::receiveFrame(int sockfd, CClientItem* pClientItem) { uint8_t rcvbuf[VSCP_MULTICAST_PACKET0_MAX]; vscpEvent* pEvent; int flags = MSG_DONTWAIT; struct sockaddr from; socklen_t addrlen = sizeof(from); // Check pointers if (NULL == pClientItem) return VSCP_ERROR_PARAMETER; memset(rcvbuf, 0, sizeof(rcvbuf)); ssize_t rcvlen = recvfrom(sockfd, rcvbuf, sizeof(rcvbuf), flags, &from, &addrlen); // Null frame if (0 == rcvlen) { // Packet to short syslog(LOG_ERR, "UDP receive server: The peer has performed an orderly " "shutdown, UDP frame have invalid length = %d", (int)rcvlen); if (m_bAck) { replyNackFrame( &from, rcvbuf[VSCP_MULTICAST_PACKET0_POS_PKTTYPE], (rcvbuf[VSCP_MULTICAST_PACKET0_POS_HEAD_LSB] & 0xf8)); } return VSCP_ERROR_ERROR; } // Error if (-1 == rcvlen) { // Packet to short syslog(LOG_ERR, "UDP receive server: Error when receiving UDP frame = %d", errno); if (m_bAck) { replyNackFrame( &from, rcvbuf[VSCP_MULTICAST_PACKET0_POS_PKTTYPE], (rcvbuf[VSCP_MULTICAST_PACKET0_POS_HEAD_LSB] & 0xf8)); } return VSCP_ERROR_ERROR; } // Incoming data // Must be at least a packet-type + header and a crc if (rcvlen < (1 + VSCP_MULTICAST_PACKET0_HEADER_LENGTH + 2)) { // Packet to short syslog(LOG_ERR, "UDP receive server: UDP frame have invalid length = %d", (int)rcvlen); if (m_bAck) { replyNackFrame( &from, rcvbuf[VSCP_MULTICAST_PACKET0_POS_PKTTYPE], (rcvbuf[VSCP_MULTICAST_PACKET0_POS_HEAD_LSB] & 0xf8)); } return VSCP_ERROR_ERROR; } // If un-secure frames are not supported // frames must be encrypted if (!m_bAllowUnsecure && !GET_VSCP_MULTICAST_PACKET_ENCRYPTION( rcvbuf[VSCP_MULTICAST_PACKET0_POS_PKTTYPE])) { syslog(LOG_ERR, "UDP receive server: UDP frame must be encrypted (or" "m_bAllowUnsecure set to 'true') to be accepted."); if (m_bAck) { replyNackFrame( (struct sockaddr*)&from, rcvbuf[VSCP_MULTICAST_PACKET0_POS_PKTTYPE], (rcvbuf[VSCP_MULTICAST_PACKET0_POS_HEAD_LSB] & 0xf8)); } return VSCP_ERROR_ERROR; } if (!vscp_decryptFrame(rcvbuf, rcvbuf, rcvlen, // actually len-16 but encrypt routine handle m_pCtrlObj->getSystemKey(NULL), NULL, // Will be copied from the last 16-bytes GET_VSCP_MULTICAST_PACKET_ENCRYPTION(rcvbuf[0]))) { syslog(LOG_ERR, "UDP receive server: Decryption of UDP frame failed"); if (m_bAck) { replyNackFrame( (struct sockaddr*)&from, rcvbuf[VSCP_MULTICAST_PACKET0_POS_PKTTYPE], (rcvbuf[VSCP_MULTICAST_PACKET0_POS_HEAD_LSB] & 0xf8)); } return VSCP_ERROR_ERROR; }; if (m_bAck) { replyAckFrame((struct sockaddr*)&from, rcvbuf[VSCP_MULTICAST_PACKET0_POS_PKTTYPE], (rcvbuf[VSCP_MULTICAST_PACKET0_POS_HEAD_LSB] & 0xf8)); } // Allocate a new event if (NULL == (pEvent = new vscpEvent)) return false; pEvent->pdata = NULL; if (!vscp_getEventFromFrame(pEvent, rcvbuf, rcvlen)) { vscp_deleteEvent_v2(&pEvent); return VSCP_ERROR_ERROR; } if (vscp_doLevel2Filter(pEvent, &m_pClientItem->m_filter)) { // Set obid to ourself so we don't get events we // receive pEvent->obid = pClientItem->m_clientID; // There must be room in the receive queue if (m_pCtrlObj->m_maxItemsInClientReceiveQueue > m_pCtrlObj->m_clientOutputQueue.size()) { pthread_mutex_lock(&m_pCtrlObj->m_mutex_ClientOutputQueue); m_pCtrlObj->m_clientOutputQueue.push_back(pEvent); sem_post(&m_pCtrlObj->m_semClientOutputQueue); pthread_mutex_unlock(&m_pCtrlObj->m_mutex_ClientOutputQueue); } else { vscp_deleteEvent_v2(&pEvent); } } else { vscp_deleteEvent_v2(&pEvent); } return VSCP_ERROR_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // replyAckFrame // int udpSrvObj::replyAckFrame(struct sockaddr *to, uint8_t pkttype, uint8_t index) { unsigned char sendbuf[VSCP_MULTICAST_PACKET0_MAX]; // Send buffer vscpEventEx ex; ex.head = (index & 0xf8); ex.crc = 0; ex.obid = 0; ex.timestamp = vscp_makeTimeStamp(); ex.year = vscpdatetime::UTCNow().getYear(); ex.month = vscpdatetime::UTCNow().getMonth(); ex.day = vscpdatetime::UTCNow().getDay(); ex.hour = vscpdatetime::UTCNow().getHour(); ex.minute = vscpdatetime::UTCNow().getMinute(); ex.second = vscpdatetime::UTCNow().getSecond(); memcpy(ex.GUID, m_pClientItem->m_guid.getGUID(), 16); ex.vscp_class = VSCP_CLASS1_ERROR; ex.vscp_type = VSCP_TYPE_ERROR_SUCCESS; ex.sizeData = 3; memset(ex.data, 0, 3); // index/zone/subzone = 0 ex.data[0] = index; if (!vscp_writeEventExToFrame(sendbuf, sizeof(sendbuf), pkttype, &ex)) { return false; } // Send to remote node size_t slen = sizeof(to); if (-1 == sendto(m_sockfd, sendbuf, 1 + VSCP_MULTICAST_PACKET0_HEADER_LENGTH + 2 + ex.sizeData, 0, (struct sockaddr*)&to, slen)) { ; } return VSCP_ERROR_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // replyNackFrame // int udpSrvObj::replyNackFrame(struct sockaddr* to, uint8_t pkttype, uint8_t index) { unsigned char sendbuf[VSCP_MULTICAST_PACKET0_MAX]; // Send buffer vscpEventEx ex; ex.head = (index & 0xf8); ex.crc = 0; ex.obid = 0; ex.timestamp = vscp_makeTimeStamp(); ex.year = vscpdatetime::UTCNow().getYear(); ex.month = vscpdatetime::UTCNow().getMonth(); ex.day = vscpdatetime::UTCNow().getDay(); ex.hour = vscpdatetime::UTCNow().getHour(); ex.minute = vscpdatetime::UTCNow().getMinute(); ex.second = vscpdatetime::UTCNow().getSecond(); memcpy(ex.GUID, m_pClientItem->m_guid.getGUID(), 16); ex.vscp_class = VSCP_CLASS1_ERROR; ex.vscp_type = VSCP_TYPE_ERROR_ERROR; ex.sizeData = 3; memset(ex.data, 0, 3); // index/zone/subzone = 0 ex.data[0] = index; if (!vscp_writeEventExToFrame(sendbuf, sizeof(sendbuf), pkttype, &ex)) { return false; } // Send to remote node size_t slen = sizeof(to); if (-1 == sendto(m_sockfd, sendbuf, 1 + VSCP_MULTICAST_PACKET0_HEADER_LENGTH + 2 + ex.sizeData, 0, (struct sockaddr*)&to, slen)) { ; } return VSCP_ERROR_SUCCESS; } /////////////////////////////////////////////////////////////////////////////// // udpSrvWorkerThread // void* udpSrvWorkerThread(void* pData) { int sockfd; char rcvbuf[UDP_MAX_PACKAGE]; struct sockaddr_in servaddr, cliaddr; udpSrvObj* pObj = (udpSrvObj*)pData; if (NULL == pObj) { syslog(LOG_ERR, "UDP RX Client: No thread worker object defined."); return NULL; } if (NULL == pObj->m_pCtrlObj) { syslog(LOG_ERR, "UDP RX Client: No control object defined."); return NULL; } // Init. CRC data crcInit(); // Creating socket file descriptor if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { syslog(LOG_ERR, "UDP RX Client: Socket could not be created."); return NULL; } memset(&servaddr, 0, sizeof(servaddr)); // Bind the socket with the server address if (bind(sockfd, (const struct sockaddr*)&pObj->m_servaddr, sizeof(pObj->m_servaddr)) < 0) { syslog(LOG_ERR, "UDP RX Client: Unable to bind to server port."); close(sockfd); return NULL; } syslog( LOG_ERR, "UDP RX Client: Bind to interface. [%s]", get_ip_str((struct sockaddr*)&pObj->m_servaddr, rcvbuf, sizeof(rcvbuf))); // We need to create a client object and add this object to the list of // clients pObj->m_pClientItem = new CClientItem; if (NULL == pObj->m_pClientItem) { syslog(LOG_ERR, "[UDP RX Client] Unable to allocate memory for client - " "terminating."); close(sockfd); return NULL; } // This is now an active Client pObj->m_pClientItem->m_bOpen = true; pObj->m_pClientItem->m_type = CLIENT_ITEM_INTERFACE_TYPE_CLIENT_UDP; pObj->m_pClientItem->m_strDeviceName = "Internal UDP RX Client listener. ["; pObj->m_pClientItem->m_strDeviceName += get_ip_str((struct sockaddr*)&pObj->m_servaddr, rcvbuf, sizeof(rcvbuf)); pObj->m_pClientItem->m_strDeviceName += "]|Started at "; pObj->m_pClientItem->m_strDeviceName += vscpdatetime::Now().getISODateTime(); // If a user is defined get user item vscp_trim(pObj->m_user); if (pObj->m_user.length()) { pthread_mutex_lock(&pObj->m_pCtrlObj->m_mutex_UserList); pObj->m_pClientItem->m_pUserItem = pObj->m_pCtrlObj->m_userList.getUser(pObj->m_user); pthread_mutex_unlock(&pObj->m_pCtrlObj->m_mutex_UserList); if (NULL == pObj->m_pClientItem->m_pUserItem) { delete pObj->m_pClientItem; syslog(LOG_ERR, "[UDP RX Client] User [%s] NOT allowed to connect.", (const char*)pObj->m_user.c_str()); close(sockfd); return NULL; } } else { pObj->m_pClientItem->m_pUserItem = NULL; // No user defined } // Add the client to the Client List pthread_mutex_lock(&pObj->m_pCtrlObj->m_mutex_clientList); if (!pObj->m_pCtrlObj->addClient(pObj->m_pClientItem, CLIENT_ITEM_INTERFACE_TYPE_CLIENT_UDP)) { // Failed to add client delete pObj->m_pClientItem; pObj->m_pClientItem = NULL; pthread_mutex_lock(&pObj->m_pCtrlObj->m_mutex_clientList); syslog(LOG_ERR, "UDP server: Failed to add client. Terminating thread."); close(sockfd); return NULL; } pthread_mutex_unlock(&pObj->m_pCtrlObj->m_mutex_clientList); // Set receive filter memcpy(&pObj->m_pClientItem->m_filter, &pObj->m_filter, sizeof(vscpEventFilter)); // Set GUID for channel if (!pObj->m_guid.isNULL()) { pObj->m_pClientItem->m_guid = pObj->m_guid; } syslog(LOG_ERR, "UDP RX Client: Thread started."); struct pollfd poll_set; poll_set.events = POLLIN; poll_set.fd = sockfd; poll_set.revents = 0; int poll_ret; while (!pObj->m_bQuit) { poll_ret = poll(&poll_set, 1, 500); if (poll_ret > 0) { // OK receive the frame if (pObj->receiveFrame(sockfd, pObj->m_pClientItem)) { ; } else { ; } } // pObj->sendFrames(sockfd, pObj->m_pClientItem); } // while if (NULL != pObj->m_pClientItem) { // Add the client to the Client List pthread_mutex_lock(&pObj->m_pCtrlObj->m_mutex_clientList); pObj->m_pCtrlObj->removeClient(pObj->m_pClientItem); pthread_mutex_unlock(&pObj->m_pCtrlObj->m_mutex_clientList); } syslog(LOG_ERR, "UDP RX ClientThread: Quit."); return NULL; } /////////////////////////////////////////////////////////////////////////////// // UspClientWorkerThread // void* udpClientWorkerThread(void* pData) { char rcvbuf[UDP_MAX_PACKAGE]; // Init. CRC data crcInit(); udpRemoteClient* pObj = (udpRemoteClient*)pData; if (NULL == pObj) { syslog(LOG_ERR, "UDP TX Client: No thread worker object defined."); return NULL; } if (NULL == pObj->m_pCtrlObj) { syslog(LOG_ERR, "UDP TX Client: No control object defined."); return NULL; } // // Creating socket file descriptor // if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) { // syslog( LOG_ERR,"UDP TX Client: socket creation failed"); // exit(EXIT_FAILURE); // } // memset(&client_addr, 0, sizeof(client_addr)); // client_addr.sin_family = AF_INET; // client_addr.sin_addr.s_addr = inet_addr(pObj->m_interface.c_str()); // //servaddr.sin_addr.s_addr = INADDR_ANY; // Broadcast // client_addr.sin_port = htons(1024); // We need to create a client object and add this object to the list of // clients pObj->m_pClientItem = new CClientItem; if (NULL == pObj->m_pClientItem) { syslog(LOG_ERR, "[UDP RX Client] Unable to allocate memory for client - " "terminating."); close(pObj->m_sockfd); return NULL; } // This is now an active Client pObj->m_pClientItem->m_bOpen = true; pObj->m_pClientItem->m_type = CLIENT_ITEM_INTERFACE_TYPE_CLIENT_UDP; pObj->m_pClientItem->m_strDeviceName = ("Internal UDP RX Client listener. ["); pObj->m_pClientItem->m_strDeviceName += get_ip_str((struct sockaddr*)&pObj->m_remoteAddress, rcvbuf, sizeof(rcvbuf)); pObj->m_pClientItem->m_strDeviceName += ("]|Started at "); pObj->m_pClientItem->m_strDeviceName += vscpdatetime::Now().getISODateTime(); // If a user is defined get user item vscp_trim(pObj->m_user); if (pObj->m_user.length()) { pthread_mutex_lock(&pObj->m_pCtrlObj->m_mutex_clientList); pObj->m_pClientItem->m_pUserItem = pObj->m_pCtrlObj->m_userList.validateUser(pObj->m_user, pObj->m_password); pthread_mutex_lock(&pObj->m_pCtrlObj->m_mutex_UserList); if (NULL == pObj->m_pClientItem->m_pUserItem) { delete pObj->m_pClientItem; syslog(LOG_ERR, "[UDP RX Client] User [%s] NOT allowed to connect.", (const char*)pObj->m_user.c_str()); close(pObj->m_sockfd); return NULL; } } else { pObj->m_pClientItem->m_pUserItem = NULL; // No user defined } // Add the client to the Client List pthread_mutex_lock(&pObj->m_pCtrlObj->m_mutex_clientList); if (!pObj->m_pCtrlObj->addClient(pObj->m_pClientItem, CLIENT_ITEM_INTERFACE_TYPE_CLIENT_UDP)) { // Failed to add client delete pObj->m_pClientItem; pObj->m_pClientItem = NULL; pthread_mutex_lock(&pObj->m_pCtrlObj->m_mutex_clientList); syslog(LOG_ERR, "UDP server: Failed to add client. Terminating thread."); close(pObj->m_sockfd); return NULL; } pthread_mutex_lock(&pObj->m_pCtrlObj->m_mutex_clientList); // Set receive filter memcpy(&pObj->m_pClientItem->m_filter, &pObj->m_filter, sizeof(vscpEventFilter)); // Set GUID for channel if (!pObj->m_guid.isNULL()) { pObj->m_pClientItem->m_guid = pObj->m_guid; } syslog(LOG_ERR, "UDP RX Client: Thread started."); // Run run run... while (!pObj->m_bQuit) { // pObj->sendFrame(); } if (NULL != pObj->m_pClientItem) { // Add the client to the Client List pthread_mutex_lock(&pObj->m_pCtrlObj->m_mutex_clientList); pObj->m_pCtrlObj->removeClient(pObj->m_pClientItem); pthread_mutex_unlock(&pObj->m_pCtrlObj->m_mutex_clientList); } syslog(LOG_ERR, "UDP RX ClientThread: Quit."); return NULL; }
30.542033
81
0.569386
[ "object", "vector" ]
12d615ce42529f6aa6f4433fe00e6208a2503d96
530
cpp
C++
src/semana-9/N-Repeated-Element-in-Size-2N-Array.cpp
RicardoLopes1/desafios-prog-2021-1
1e698f0696b5636fa5608d669dd58d170f8049ea
[ "MIT" ]
null
null
null
src/semana-9/N-Repeated-Element-in-Size-2N-Array.cpp
RicardoLopes1/desafios-prog-2021-1
1e698f0696b5636fa5608d669dd58d170f8049ea
[ "MIT" ]
null
null
null
src/semana-9/N-Repeated-Element-in-Size-2N-Array.cpp
RicardoLopes1/desafios-prog-2021-1
1e698f0696b5636fa5608d669dd58d170f8049ea
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // https://leetcode.com/problems/n-repeated-element-in-size-2n-array/ // 961. N-Repeated Element in Size 2N Array class Solution { public: int repeatedNTimes(vector<int>& nums) { map <int, int> freq; int nsize = nums.size(); for(auto n : nums){ freq[n]++; } for(auto & [k,v] : freq){ if(v == nsize / 2) return k; } return 0; } }; int main(){ return 0; }
21.2
69
0.496226
[ "vector" ]
12dc2b5891daa3819a0ba20a66e664618f14c91e
669
hpp
C++
test/pch.hpp
severalgh/SimpleOpenSSL
a915c31a3e2a67e02ee3103f44f891fa5971a783
[ "MIT" ]
4
2021-01-19T00:48:02.000Z
2021-06-21T18:21:08.000Z
test/pch.hpp
severalgh/SimpleOpenSSL
a915c31a3e2a67e02ee3103f44f891fa5971a783
[ "MIT" ]
null
null
null
test/pch.hpp
severalgh/SimpleOpenSSL
a915c31a3e2a67e02ee3103f44f891fa5971a783
[ "MIT" ]
1
2020-02-17T16:03:26.000Z
2020-02-17T16:03:26.000Z
#ifndef PDY_TEST_PCH_H_ #define PDY_TEST_PCH_H_ #include <gtest/gtest.h> #include <gmock/gmock.h> // openssl #include <openssl/asn1.h> #include <openssl/ec.h> #include <openssl/evp.h> #include <openssl/err.h> #include <openssl/bio.h> #include <openssl/bn.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/pem.h> #include <openssl/cmac.h> #include <openssl/rand.h> #include <openssl/md5.h> #include <openssl/md4.h> // std #include <vector> #include <memory> #include <type_traits> #include <algorithm> #include <cstring> #include <chrono> #include <iterator> #include <sstream> // so ut #include "precalculated.h" #include "utils.h" #endif
18.081081
27
0.726457
[ "vector" ]
12de63a8a178669956354961d66447ea0b0c1d6f
18,751
cpp
C++
mysql-server/storage/ndb/test/run-test/process_management.cpp
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/storage/ndb/test/run-test/process_management.cpp
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/storage/ndb/test/run-test/process_management.cpp
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <NdbSleep.h> #include "process_management.hpp" bool ProcessManagement::startAllProcesses() { if (clusterProcessesStatus == ProcessesStatus::RUNNING) { g_logger.debug("All processes already RUNNING. No action required"); return true; } if (clusterProcessesStatus == ProcessesStatus::ERROR) { g_logger.debug("Processes in ERROR status. Stopping all processes first"); if (!stopAllProcesses()) { g_logger.warning("Failure to stop processes while in ERROR status"); return false; } } assert(clusterProcessesStatus == ProcessesStatus::STOPPED); if (!setupHostsFilesystem()) { g_logger.warning("Failed to setup hosts filesystem"); return false; } if (!startClusters()) { clusterProcessesStatus = ProcessesStatus::ERROR; g_logger.warning("Unable to start all processes: ERROR status"); g_logger.debug("Trying to stop all processes to recover from failure"); if (!stopAllProcesses()) { g_logger.warning("Failed to stop all processes during recovery"); } return false; } clusterProcessesStatus = ProcessesStatus::RUNNING; g_logger.debug("All processes RUNNING"); return true; } bool ProcessManagement::stopAllProcesses() { if (clusterProcessesStatus == ProcessesStatus::STOPPED) { g_logger.debug("All processes already STOPPED. No action required"); return true; } if (!shutdownProcesses(atrt_process::AP_ALL)) { clusterProcessesStatus = ProcessesStatus::ERROR; g_logger.debug("Unable to stop all processes: ERROR status"); return false; } clusterProcessesStatus = ProcessesStatus::STOPPED; g_logger.debug("All processes STOPPED"); return true; } bool ProcessManagement::startClientProcesses() { if (!startProcesses(ProcessManagement::P_CLIENTS)) { clusterProcessesStatus = ProcessesStatus::ERROR; g_logger.debug("Unable to start client processes: ERROR status"); return false; } return true; } bool ProcessManagement::stopClientProcesses() { if (!shutdownProcesses(P_CLIENTS)) { clusterProcessesStatus = ProcessesStatus::ERROR; g_logger.debug("Unable to stop client processes: ERROR status"); return false; } return true; } int ProcessManagement::updateProcessesStatus() { if (!updateStatus(atrt_process::AP_ALL)) { g_logger.warning("Failed to update status for all processes"); return ERR_CRITICAL; } return checkNdbOrServersFailures(); } bool ProcessManagement::startClusters() { if (!start(P_NDB | P_SERVERS)) { g_logger.critical("Failed to start server processes"); return false; } if (!setup_db(config)) { g_logger.critical("Failed to setup database"); return false; } if (!checkClusterStatus(atrt_process::AP_ALL)) { g_logger.critical("Cluster start up failed"); return false; } return true; } bool ProcessManagement::shutdownProcesses(int types) { const char *p_type = getProcessTypeName(types); g_logger.info("Stopping %s processes", p_type); if (!stopProcesses(types)) { g_logger.critical("Failed to stop %s processes", p_type); return false; } if (!waitForProcessesToStop(types)) { g_logger.critical("Failed to stop %s processes", p_type); return false; } return true; } bool ProcessManagement::start(unsigned proc_mask) { if (proc_mask & atrt_process::AP_NDB_MGMD) if (!startProcesses(atrt_process::AP_NDB_MGMD)) return false; if (proc_mask & atrt_process::AP_NDBD) { if (!connectNdbMgm()) { return false; } if (!startProcesses(atrt_process::AP_NDBD)) return false; if (!waitNdb(NDB_MGM_NODE_STATUS_NOT_STARTED)) return false; for (Uint32 i = 0; i < 3; i++) if (waitNdb(NDB_MGM_NODE_STATUS_STARTED)) goto started; return false; } started: if (!startProcesses(P_SERVERS & proc_mask)) return false; return true; } bool ProcessManagement::startProcesses(int types) { for (unsigned i = 0; i < config.m_processes.size(); i++) { atrt_process &proc = *config.m_processes[i]; if (IF_WIN(!(proc.m_type & atrt_process::AP_MYSQLD), 1) && (types & proc.m_type) != 0 && proc.m_proc.m_path != "") { if (!startProcess(proc)) { return false; } } } return true; } bool ProcessManagement::startProcess(atrt_process &proc, bool run_setup) { if (proc.m_proc.m_id != -1) { g_logger.critical("starting already started process: %u", (unsigned)proc.m_index); return false; } if (run_setup) { BaseString tmp = setup_progname; tmp.appfmt(" %s %s/ %s", proc.m_host->m_hostname.c_str(), proc.m_proc.m_cwd.c_str(), proc.m_proc.m_cwd.c_str()); g_logger.debug("system(%s)", tmp.c_str()); const int r1 = sh(tmp.c_str()); if (r1 != 0) { g_logger.critical("Failed to setup process"); return false; } } /** * For MySQL server program we need to pass the correct basedir. */ const bool mysqld = proc.m_type & atrt_process::AP_MYSQLD; if (mysqld) { BaseString basedir; /** * If MYSQL_BASE_DIR is set use that for basedir. */ ssize_t pos = proc.m_proc.m_env.indexOf("MYSQL_BASE_DIR="); if (pos > 0) { pos = proc.m_proc.m_env.indexOf(" MYSQL_BASE_DIR="); if (pos != -1) pos++; } if (pos >= 0) { pos += strlen("MYSQL_BASE_DIR="); ssize_t endpos = proc.m_proc.m_env.indexOf(' ', pos); if (endpos == -1) endpos = proc.m_proc.m_env.length(); basedir = proc.m_proc.m_env.substr(pos, endpos); } else { /** * If no MYSQL_BASE_DIR set, derive basedir from program path. * Assumming that program path is on the form * <basedir>/{bin,sql}/mysqld */ const BaseString sep("/"); Vector<BaseString> dir_parts; int num_of_parts = proc.m_proc.m_path.split(dir_parts, sep); dir_parts.erase(num_of_parts - 1); // remove trailing /mysqld dir_parts.erase(num_of_parts - 2); // remove trailing /bin num_of_parts -= 2; basedir.assign(dir_parts, sep); } if (proc.m_proc.m_args.indexOf("--basedir=") == -1) { proc.m_proc.m_args.appfmt(" --basedir=%s", basedir.c_str()); g_logger.info("appended '--basedir=%s' to mysqld process", basedir.c_str()); } } BaseString save_args(proc.m_proc.m_args); { Properties reply; if (proc.m_host->m_cpcd->define_process(proc.m_proc, reply) != 0) { BaseString msg; reply.get("errormessage", msg); g_logger.error("Unable to define process: %s", msg.c_str()); if (mysqld) { proc.m_proc.m_args = save_args; /* restore args */ } return false; } } if (mysqld) { proc.m_proc.m_args = save_args; /* restore args */ } { Properties reply; if (proc.m_host->m_cpcd->start_process(proc.m_proc.m_id, reply) != 0) { BaseString msg; reply.get("errormessage", msg); g_logger.error("Unable to start process: %s", msg.c_str()); return false; } } return true; } bool ProcessManagement::stopProcesses(int types) { int failures = 0; for (unsigned i = 0; i < config.m_processes.size(); i++) { atrt_process &proc = *config.m_processes[i]; if ((types & proc.m_type) != 0) { if (!stopProcess(proc)) { failures++; } } } return failures == 0; } bool ProcessManagement::stopProcess(atrt_process &proc) { if (proc.m_proc.m_id == -1) { return true; } if (proc.m_type == atrt_process::AP_MYSQLD) { disconnect_mysqld(proc); } { Properties reply; if (proc.m_host->m_cpcd->stop_process(proc.m_proc.m_id, reply) != 0) { Uint32 status; reply.get("status", &status); if (status != 4) { BaseString msg; reply.get("errormessage", msg); g_logger.error( "Unable to stop process id: %d host: %s cmd: %s, " "msg: %s, status: %d", proc.m_proc.m_id, proc.m_host->m_hostname.c_str(), proc.m_proc.m_path.c_str(), msg.c_str(), status); return false; } } } { Properties reply; if (proc.m_host->m_cpcd->undefine_process(proc.m_proc.m_id, reply) != 0) { BaseString msg; reply.get("errormessage", msg); g_logger.error("Unable to stop process id: %d host: %s cmd: %s, msg: %s", proc.m_proc.m_id, proc.m_host->m_hostname.c_str(), proc.m_proc.m_path.c_str(), msg.c_str()); return false; } } return true; } bool ProcessManagement::connectNdbMgm() { for (unsigned i = 0; i < config.m_processes.size(); i++) { atrt_process &proc = *config.m_processes[i]; if ((proc.m_type & atrt_process::AP_NDB_MGMD) != 0) { if (!connectNdbMgm(proc)) { return false; } } } return true; } bool ProcessManagement::connectNdbMgm(atrt_process &proc) { NdbMgmHandle handle = ndb_mgm_create_handle(); if (handle == 0) { g_logger.critical("Unable to create mgm handle"); return false; } BaseString tmp = proc.m_host->m_hostname; const char *val; proc.m_options.m_loaded.get("--PortNumber=", &val); tmp.appfmt(":%s", val); if (ndb_mgm_set_connectstring(handle, tmp.c_str())) { g_logger.critical("Unable to create parse connectstring"); return false; } if (ndb_mgm_connect(handle, 30, 1, 0) != -1) { proc.m_ndb_mgm_handle = handle; return true; } g_logger.critical("Unable to connect to ndb mgm %s", tmp.c_str()); return false; } bool ProcessManagement::waitNdb(int goal) { goal = remap(goal); size_t cnt = 0; for (unsigned i = 0; i < config.m_clusters.size(); i++) { atrt_cluster *cluster = config.m_clusters[i]; if (strcmp(cluster->m_name.c_str(), ".atrt") == 0) { /** * skip atrt mysql */ cnt++; continue; } /** * Get mgm handle for cluster */ NdbMgmHandle handle = 0; for (unsigned j = 0; j < cluster->m_processes.size(); j++) { atrt_process &proc = *cluster->m_processes[j]; if ((proc.m_type & atrt_process::AP_NDB_MGMD) != 0) { handle = proc.m_ndb_mgm_handle; break; } } if (handle == 0) { return true; } if (goal == NDB_MGM_NODE_STATUS_STARTED) { /** * 1) wait NOT_STARTED * 2) send start * 3) wait STARTED */ if (!waitNdb(NDB_MGM_NODE_STATUS_NOT_STARTED)) return false; ndb_mgm_start(handle, 0, 0); } struct ndb_mgm_cluster_state *state; time_t now = time(0); time_t end = now + 360; int min = remap(NDB_MGM_NODE_STATUS_NO_CONTACT); int min2 = goal; while (now < end) { /** * 1) retreive current state */ state = 0; do { state = ndb_mgm_get_status(handle); if (state == 0) { const int err = ndb_mgm_get_latest_error(handle); g_logger.error("Unable to poll db state: %d %s %s", ndb_mgm_get_latest_error(handle), ndb_mgm_get_latest_error_msg(handle), ndb_mgm_get_latest_error_desc(handle)); if (err == NDB_MGM_SERVER_NOT_CONNECTED && connectNdbMgm()) { g_logger.error("Reconnected..."); continue; } return false; } } while (state == 0); NdbAutoPtr<void> tmp(state); min2 = goal; for (int j = 0; j < state->no_of_nodes; j++) { if (state->node_states[j].node_type == NDB_MGM_NODE_TYPE_NDB) { const int s = remap(state->node_states[j].node_status); min2 = (min2 < s ? min2 : s); if (s < remap(NDB_MGM_NODE_STATUS_NO_CONTACT) || s > NDB_MGM_NODE_STATUS_STARTED) { g_logger.critical("Strange DB status during start: %d %d", j, min2); return false; } if (min2 < min) { g_logger.critical("wait ndb failed node: %d %d %d %d", state->node_states[j].node_id, min, min2, goal); } } } if (min2 < min) { g_logger.critical("wait ndb failed %d %d %d", min, min2, goal); return false; } if (min2 == goal) { cnt++; goto next; } min = min2; now = time(0); } g_logger.critical("wait ndb timed out %d %d %d", min, min2, goal); break; next:; } return cnt == config.m_clusters.size(); } bool ProcessManagement::checkClusterStatus(int types) { if (!updateStatus(types)) { g_logger.critical("Failed to get updated status for all processes"); return false; } if (checkNdbOrServersFailures() != 0) { return false; } return true; } int ProcessManagement::checkNdbOrServersFailures() { int failed_processes = 0; const int types = P_NDB | P_SERVERS; for (unsigned i = 0; i < config.m_processes.size(); i++) { atrt_process &proc = *config.m_processes[i]; bool skip = proc.m_atrt_stopped || IF_WIN(proc.m_type & atrt_process::AP_MYSQLD, 0); bool isRunning = proc.m_proc.m_status == "running"; if ((types & proc.m_type) != 0 && !isRunning && !skip) { g_logger.critical("%s #%d not running on %s", proc.m_name.c_str(), proc.m_index, proc.m_host->m_hostname.c_str()); failed_processes |= proc.m_type; } } if ((failed_processes & P_NDB) && (failed_processes & P_SERVERS)) { return ERR_NDB_AND_SERVERS_FAILED; } if ((failed_processes & P_NDB) != 0) { return ERR_NDB_FAILED; } if ((failed_processes & P_SERVERS) != 0) { return ERR_SERVERS_FAILED; } return 0; } bool ProcessManagement::updateStatus(int types, bool fail_on_missing) { Vector<Vector<SimpleCpcClient::Process> > m_procs; Vector<SimpleCpcClient::Process> dummy; m_procs.fill(config.m_hosts.size(), dummy); for (unsigned i = 0; i < config.m_hosts.size(); i++) { if (config.m_hosts[i]->m_hostname.length() == 0) continue; Properties p; config.m_hosts[i]->m_cpcd->list_processes(m_procs[i], p); } for (unsigned i = 0; i < config.m_processes.size(); i++) { atrt_process &proc = *config.m_processes[i]; if (proc.m_proc.m_id == -1 || (proc.m_type & types) == 0) { continue; } Vector<SimpleCpcClient::Process> &h_procs = m_procs[proc.m_host->m_index]; bool found = false; for (unsigned j = 0; j < h_procs.size() && !found; j++) { if (proc.m_proc.m_id == h_procs[j].m_id) { found = true; proc.m_proc.m_status = h_procs[j].m_status; } } if (found) continue; if (!fail_on_missing) { proc.m_proc.m_id = -1; proc.m_proc.m_status.clear(); } else { g_logger.error("update_status: not found"); g_logger.error("id: %d host: %s cmd: %s", proc.m_proc.m_id, proc.m_host->m_hostname.c_str(), proc.m_proc.m_path.c_str()); for (unsigned j = 0; j < h_procs.size(); j++) { g_logger.error("found: %d %s", h_procs[j].m_id, h_procs[j].m_path.c_str()); } return false; } } return true; } bool ProcessManagement::waitForProcessesToStop(int types, int retries, int wait_between_retries_s) { for (int attempts = 0; attempts < retries; attempts++) { bool last_attempt = attempts == (retries - 1); updateStatus(types, false); int found = 0; for (unsigned i = 0; i < config.m_processes.size(); i++) { atrt_process &proc = *config.m_processes[i]; if ((types & proc.m_type) == 0 || proc.m_proc.m_id == -1) continue; found++; if (!last_attempt) continue; // skip logging g_logger.error( "Failed to stop process id: %d host: %s status: %s cmd: %s", proc.m_proc.m_id, proc.m_host->m_hostname.c_str(), proc.m_proc.m_status.c_str(), proc.m_proc.m_path.c_str()); } if (found == 0) return true; if (!last_attempt) NdbSleep_SecSleep(wait_between_retries_s); } return false; } bool ProcessManagement::waitForProcessToStop(atrt_process &proc, int retries, int wait_between_retries_s) { for (int attempts = 0; attempts < retries; attempts++) { updateStatus(proc.m_type, false); if (proc.m_proc.m_id == -1) return true; bool last_attempt = attempts == (retries - 1); if (!last_attempt) { NdbSleep_SecSleep(wait_between_retries_s); continue; } g_logger.error("Failed to stop process id: %d host: %s status: %s cmd: %s", proc.m_proc.m_id, proc.m_host->m_hostname.c_str(), proc.m_proc.m_status.c_str(), proc.m_proc.m_path.c_str()); } return false; } bool ProcessManagement::setupHostsFilesystem() { if (!setup_directories(config, 2)) { g_logger.critical("Failed to setup directories"); return false; } if (!setup_files(config, 2, 1)) { g_logger.critical("Failed to setup files"); return false; } if (!setup_hosts(config)) { g_logger.critical("Failed to setup hosts"); return false; } return true; } int ProcessManagement::remap(int i) { if (i == NDB_MGM_NODE_STATUS_NO_CONTACT) return NDB_MGM_NODE_STATUS_UNKNOWN; if (i == NDB_MGM_NODE_STATUS_UNKNOWN) return NDB_MGM_NODE_STATUS_NO_CONTACT; return i; } const char* ProcessManagement::getProcessTypeName(int types) { switch (types) { case ProcessManagement::P_CLIENTS: return "client"; case ProcessManagement::P_NDB: return "ndb"; case ProcessManagement::P_SERVERS: return "server"; default: return "all"; } }
29.071318
80
0.628073
[ "vector" ]
12de7136aae28842e7c207b94202f179fc57dfe9
4,521
cpp
C++
tests/geometry/Plane_Inter.cpp
gaelh7/Graphics
48041204c39c3d52bbb470581683c850b000af68
[ "MIT" ]
null
null
null
tests/geometry/Plane_Inter.cpp
gaelh7/Graphics
48041204c39c3d52bbb470581683c850b000af68
[ "MIT" ]
null
null
null
tests/geometry/Plane_Inter.cpp
gaelh7/Graphics
48041204c39c3d52bbb470581683c850b000af68
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include "Graphics/geometry.hpp" struct PlaneDistTest: public ::testing::Test { gmh::Plane obj; virtual void SetUp() override { obj = gmh::Plane(glm::vec3(0, -8, 0), glm::vec3(0, 1, 0), glm::vec3(0, 0, 1)); } template<typename T> inline void checkNoInter(const T& obj2){ EXPECT_FALSE(obj2.intersect(obj)) << "Intersection: " << *obj2.intersect(obj); EXPECT_FALSE(obj.intersect(obj2)) << "Intersection: " << *obj.intersect(obj2); if(HasFailure()) std::cout << "obj: " << obj << std::endl << "obj2: " << obj2 << std::endl; } template<typename T1, typename T2> inline void checkYesInter(const T1& obj2, const T2&& inter){ ASSERT_TRUE(obj.intersect(obj2)); ASSERT_TRUE(obj2.intersect(obj)); EXPECT_TRUE(obj.intersect(obj2)->equals(*obj2.intersect(obj))) << "obj.intersect(obj2): " << *obj.intersect(obj2) << std::endl << "obj2.intersect(obj): " << *obj2.intersect(obj); EXPECT_TRUE(obj.intersect(obj2)->equals(inter)) << "Expected Intersection: " << inter << std::endl << "Actual Intersection: " << *obj.intersect(obj2); if(HasFailure()) std::cout << "obj: " << obj << std::endl << "obj2: " << obj2 << std::endl; } }; TEST_F(PlaneDistTest, PlaneDistToPlane){ gmh::Plane plan1(glm::vec3(1, 0, 0), glm::vec3(1, 1, 0), glm::vec3(1, 0, 1)); checkNoInter(plan1); plan1 = gmh::Plane(glm::vec3(-1, 0, 0), glm::vec3(1, 1, 0), glm::vec3(1, 0, 0)); checkYesInter(plan1, gmh::Line(glm::vec3(0, -2, 0), glm::vec3(0, 2, 0))); plan1 = gmh::Plane(glm::vec3(-1, -1, 0), glm::vec3(1, 1, 1), glm::vec3(1, 1, -1)); checkYesInter(plan1, gmh::Line(glm::vec3(0, 0, -2), glm::vec3(0, 0, 2))); plan1 = gmh::Plane(glm::vec3(0, 8, 9), glm::vec3(0, 21, 12), glm::vec3(0, -18, 4)); checkYesInter(plan1, gmh::Plane(glm::vec3(0, 1, 2), glm::vec3(0, 4, 4), glm::vec3(0, 5, 6))); } TEST_F(PlaneDistTest, PlaneDistToPolygon){ gmh::Polygon poly(glm::vec3(1, 2, 2), glm::vec3(1, 3, 2), glm::vec3(1, 2, 3)); checkNoInter(poly); poly = gmh::Polygon(glm::vec3(-21, 2, 2), glm::vec3(-21, 3, 2), glm::vec3(-21, 2, 3)); checkNoInter(poly); poly = gmh::Polygon(glm::vec3(0, 2, 2), glm::vec3(0, 3, 2), glm::vec3(0, 2, 3)); checkYesInter(poly, gmh::Polygon(glm::vec3(0, 2, 2), glm::vec3(0, 3, 2), glm::vec3(0, 2, 3))); poly = gmh::Polygon(glm::vec3(1, 2, 2), glm::vec3(1, 3, 2), glm::vec3(2, 2.5, 2)); checkNoInter(poly); poly = gmh::Polygon(glm::vec3(2, 2, 2), glm::vec3(2, 3, 2), glm::vec3(1, 2.5, 2)); checkNoInter(poly); poly = gmh::Polygon(glm::vec3(1, 2, 2), glm::vec3(1, 3, 2), glm::vec3(-1, 2.5, 2)); checkYesInter(poly, gmh::LinSeg(glm::vec3(0, 2.25, 2), glm::vec3(0, 2.75, 2))); poly = gmh::Polygon(glm::vec3(0, 2, 2), glm::vec3(0, 3, 2), glm::vec3(-1, 2.5, 2)); checkYesInter(poly, gmh::LinSeg(glm::vec3(0, 2, 2), glm::vec3(0, 3, 2))); poly = gmh::Polygon(glm::vec3(1, 2, 2), glm::vec3(1, 3, 2), glm::vec3(0, 2.5, 2)); checkYesInter(poly, gmh::Point({0, 2.5, 2})); } TEST_F(PlaneDistTest, PlaneDistToPolyhedron){ gmh::Polyhedron poly(glm::vec3(1, 1, 1), glm::vec3(1, -1, 1), glm::vec3(1, 1, -1), glm::vec3(1, -1, -1), glm::vec3(2, 0, 0)); checkNoInter(poly); poly = gmh::Polyhedron(glm::vec3(2, 1, 1), glm::vec3(2, -1, 1), glm::vec3(2, 1, -1), glm::vec3(2, -1, -1), glm::vec3(1, 0, 0)); checkNoInter(poly); poly = gmh::Polyhedron(glm::vec3(1, 1, 1), glm::vec3(1, -1, 1), glm::vec3(2, 1, -1), glm::vec3(2, -1, -1), glm::vec3(3, 0, 0)); checkNoInter(poly); poly = gmh::Polyhedron(glm::vec3(0, 1, 1), glm::vec3(0, -1, 1), glm::vec3(0, 1, -1), glm::vec3(0, -1, -1), glm::vec3(1, 0, 0)); checkYesInter(poly, gmh::Polygon(glm::vec3(0, 1, 1), glm::vec3(0, -1, 1), glm::vec3(0, 1, -1), glm::vec3(0, -1, -1))); poly = gmh::Polyhedron(glm::vec3(-1, 1, 1), glm::vec3(-1, -1, 1), glm::vec3(-1, 1, -1), glm::vec3(-1, -1, -1), glm::vec3(0, 0, 0)); checkYesInter(poly, gmh::Point({0, 0, 0})); poly = gmh::Polyhedron(glm::vec3(-1, 1, 1), glm::vec3(-1, -1, 1), glm::vec3(-1, 1, -1), glm::vec3(-1, -1, -1), glm::vec3(1, 0, 0)); checkYesInter(poly, gmh::Polygon(glm::vec3(0, 0.5, 0.5), glm::vec3(0, -0.5, 0.5), glm::vec3(0, 0.5, -0.5), glm::vec3(0, -0.5, -0.5))); poly = gmh::Polyhedron(glm::vec3(0, 1, 1), glm::vec3(0, -1, 1), glm::vec3(1, 1, -1), glm::vec3(1, -1, -1), glm::vec3(2, 0, 0)); checkYesInter(poly, gmh::LinSeg(glm::vec3(0, 1, 1), glm::vec3(0, -1, 1))); }
50.233333
186
0.564477
[ "geometry" ]
12e0c7791b692a611555f38fc29065a9758303be
6,332
cpp
C++
prj/TileBasedRenderer/SoftRaster/Raster.cpp
vicutrinu/pragma-studios
181fd14d072ccbb169fa786648dd942a3195d65a
[ "MIT" ]
null
null
null
prj/TileBasedRenderer/SoftRaster/Raster.cpp
vicutrinu/pragma-studios
181fd14d072ccbb169fa786648dd942a3195d65a
[ "MIT" ]
null
null
null
prj/TileBasedRenderer/SoftRaster/Raster.cpp
vicutrinu/pragma-studios
181fd14d072ccbb169fa786648dd942a3195d65a
[ "MIT" ]
null
null
null
/** * @file Raster.cpp * @author Victor Soria * * @brief Rasterization general functions */ #include "Raster.h" #include <pragma/graphics/types.h> #include <pragma/geometry/functions.h> #include <pragma/math/functions.h> #include <stdio.h> #include <memory.h> #include <assert.h> namespace pragma { namespace Raster { static unsigned sHeight; static unsigned sWidth; static unsigned char* sScreen; static const int sMaxPositions = 1024; static _Color sColor; static UV sUV; static _Point2 sPositions[sMaxPositions]; static _Color sColors[sMaxPositions]; static _Vector sNormals[sMaxPositions]; static UV sUVs[sMaxPositions]; static unsigned sNumPositions = 0; static EMode sRasterMode = eSimple; } } #include "functions.h" // Generic functions #include "internal_types.h" #include "Color.h" #include "Texture.h" #include "Position.h" #include "TextureModulate.h" #include "Gouraud.h" namespace pragma { namespace Raster { // General RasterTriangle function template<typename RASTERTYPE> inline void _RasterTriangle(int i0, int i1, int i2, typename RASTERTYPE::InterpolatorType::Interpolators& aTable) { typename RASTERTYPE::InterpolatorType::ScanlineParameters aParameters; Real lShortGradient = aTable.mTopEdge.x / aTable.mTopEdge.y; Real lLongGradient = aTable.mLongEdge.x / aTable.mLongEdge.y; unsigned lRowCount, lTotalRowCount; _Vector2 lShortStart = sPositions[i0]; Real lShortScale = AdjustEdge(lShortStart, aTable.mTopEdge, lRowCount); _Vector2 lLongStart = sPositions[i0]; Real lLongScale = AdjustEdge(lLongStart, aTable.mLongEdge, lTotalRowCount); AdjustScanlineColors<typename RASTERTYPE::InterpolatorType> (i0, i1, i2, lShortScale, lLongScale, aTable, aParameters); AdjustScanlineNormals<typename RASTERTYPE::InterpolatorType>(i0, i1, i2, lShortScale, lLongScale, aTable, aParameters); AdjustScanlineUVs<typename RASTERTYPE::InterpolatorType> (i0, i1, i2, lShortScale, lLongScale, aTable, aParameters); unsigned lY = lShortStart.y; if(sPositions[i1].x < sPositions[i2].x) { // 1 está a la izquierda RasterLines<typename RASTERTYPE::InterpolatorType,RASTERTYPE>( lShortStart.x, lLongStart.x, lY, lShortGradient, lLongGradient, lRowCount , aParameters.mIncrements, aParameters.mLeft, aParameters.mRight ); } else { RasterLines<typename RASTERTYPE::InterpolatorType,RASTERTYPE>( lLongStart.x, lShortStart.x, lY, lLongGradient, lShortGradient, lRowCount , aParameters.mIncrements, aParameters.mRight, aParameters.mLeft ); } lShortGradient = aTable.mBottomEdge.x / aTable.mBottomEdge.y; lShortStart = sPositions[i1]; lShortScale = AdjustEdge(lShortStart, aTable.mBottomEdge, lRowCount); AdjustScanlineColors<typename RASTERTYPE::InterpolatorType> (i0, i1, i2, lShortScale, aTable, aParameters); AdjustScanlineNormals<typename RASTERTYPE::InterpolatorType>(i0, i1, i2, lShortScale, aTable, aParameters); AdjustScanlineUVs<typename RASTERTYPE::InterpolatorType> (i0, i1, i2, lShortScale, aTable, aParameters); if(sPositions[i1].x < sPositions[i2].x) { // 1 está a la derecha RasterLines<typename RASTERTYPE::InterpolatorType,RASTERTYPE>( lShortStart.x, lLongStart.x, lY, lShortGradient, lLongGradient, lRowCount , aParameters.mIncrements, aParameters.mLeft, aParameters.mRight ); } else { RasterLines<typename RASTERTYPE::InterpolatorType,RASTERTYPE>( lLongStart.x, lShortStart.x, lY, lLongGradient, lShortGradient, lRowCount , aParameters.mIncrements, aParameters.mRight, aParameters.mLeft ); } } template<typename RASTERTYPE> inline void RasterTriangle(int i0, int i1, int i2) { int lTemp; if(sPositions[i0].y >= sPositions[i1].y) { lTemp = i0; i0 = i1; i1 = lTemp; } if(sPositions[i1].y >= sPositions[i2].y) { lTemp = i1; i1 = i2; i2 = lTemp; } if(sPositions[i0].y >= sPositions[i1].y) { lTemp = i0; i0 = i1; i1 = lTemp; } typename RASTERTYPE::InterpolatorType::Interpolators lTable; Real lVal = (sPositions[i1].y - sPositions[i0].y) / (sPositions[i2].y - sPositions[i0].y); // Valor magico que nos lleva a la "mitad" del triangulo lTable.mLongEdge = sPositions[i2] - sPositions[i0]; lTable.mTopEdge = sPositions[i1] - sPositions[i0]; lTable.mBottomEdge = sPositions[i2] - sPositions[i1]; lTable.mSplit = sPositions[i0] + (lTable.mLongEdge * lVal); // lTable.mSplit = (1-lVal) * sPositions[i0] + lVal * sPositions[i2]; InitColors<typename RASTERTYPE::InterpolatorType>(i0, i1, i2, lVal, lTable ); InitUVs<typename RASTERTYPE::InterpolatorType>(i0,i1,i2, lVal, lTable); InitNormals<typename RASTERTYPE::InterpolatorType>(i0, i1, i2, lVal, lTable); _RasterTriangle<RASTERTYPE>(i0, i1, i2, lTable); } void AddVertex(const _Point2& aPosition) { if(sNumPositions >= sMaxPositions) return; sPositions[sNumPositions] = aPosition; sColors[sNumPositions] = sColor; sUVs[sNumPositions] = sUV; sNumPositions++; } void VertexColor(const _Color& aColor) { sColor = aColor * Real(255); } void VertexUV(const UV& aUV) { sUV = aUV; } void SetRenderContext(unsigned char* aBuffer, int aWidth, int aHeight) { Raster::sScreen = aBuffer; Raster::sWidth = aWidth; Raster::sHeight = aHeight; } void ClearBackBuffer() { memset(Raster::sScreen, 32, Raster::sWidth * Raster::sHeight * 4); } void SetRasterMode(EMode aMode) { sRasterMode = aMode; } void Render() { switch(sRasterMode) { case eVertexColor: for(unsigned i = 0; i < sNumPositions; i+= 3) { RasterTriangle<VertexColorRaster>(i+0, i+1, i+2); } break; case eTexture: for(unsigned i = 0; i < sNumPositions; i+= 3) { RasterTriangle<TextureRaster>(i+0, i+1, i+2); } break; case eSimple: for(unsigned i = 0; i < sNumPositions; i+= 3) { RasterTriangle<SimpleRaster>(i+0, i+1, i+2); } break; case eTextureModulate: for(unsigned i = 0; i < sNumPositions; i+= 3) { RasterTriangle<TextureModulateRaster>(i+0, i+1, i+2); } break; case eGouraud: for(unsigned i = 0; i < sNumPositions; i+= 3) { RasterTriangle<GouraudRaster>(i+0, i+1, i+2); } break; } sNumPositions = 0; } } }
29.7277
149
0.699305
[ "geometry", "render" ]