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
4ed0a1f4e9dd31aaec7a62cabe118e9ad8ec65c4
741
cpp
C++
solid/utility/test/test_event_size.cpp
vipalade/solidframe
cff130652127ca9607019b4db508bc67f8bbecff
[ "BSL-1.0" ]
26
2015-08-25T16:07:58.000Z
2019-07-05T15:21:22.000Z
solid/utility/test/test_event_size.cpp
vipalade/solidframe
cff130652127ca9607019b4db508bc67f8bbecff
[ "BSL-1.0" ]
5
2016-10-15T22:55:15.000Z
2017-09-19T12:41:10.000Z
solid/utility/test/test_event_size.cpp
vipalade/solidframe
cff130652127ca9607019b4db508bc67f8bbecff
[ "BSL-1.0" ]
5
2016-09-15T10:34:52.000Z
2018-10-30T11:46:46.000Z
#include "solid/utility/event.hpp" #include "solid/utility/function.hpp" #include <functional> using namespace std; using namespace solid; int test_event_size(int argc, char* argv[]) { cout << "sizeof(Event) = " << sizeof(Event) << endl; cout << "sizeof(Event::any) = " << sizeof(Event::AnyT) << endl; cout << "Event::any::smallCapacity = " << Event::AnyT::smallCapacity() << endl; cout << "sizeof(Function<void()>) = " << sizeof(Function<void()>) << endl; cout << "sizeof(std::function<void()>) = " << sizeof(std::function<void()>) << endl; static_assert(Event::AnyT::smallCapacity() >= sizeof(Function<void()>)); static_assert(Event::AnyT::smallCapacity() >= sizeof(std::function<void()>)); return 0; }
35.285714
88
0.635628
[ "solid" ]
4de849a04e4a24db664f148cb90039e4cba890c4
2,813
cc
C++
tensorflow/lite/micro/benchmarks/keyword_benchmark.cc
paultanger/tensorflow
fb8382b4638de18388083cdd5e8d9c5c20bb7816
[ "Apache-2.0" ]
2
2020-10-28T20:24:19.000Z
2021-02-08T21:24:15.000Z
tensorflow/lite/micro/benchmarks/keyword_benchmark.cc
paultanger/tensorflow
fb8382b4638de18388083cdd5e8d9c5c20bb7816
[ "Apache-2.0" ]
null
null
null
tensorflow/lite/micro/benchmarks/keyword_benchmark.cc
paultanger/tensorflow
fb8382b4638de18388083cdd5e8d9c5c20bb7816
[ "Apache-2.0" ]
1
2021-01-04T20:55:01.000Z
2021-01-04T20:55:01.000Z
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <cstdint> #include <cstdlib> #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/micro/benchmarks/keyword_scrambled_model_data.h" #include "tensorflow/lite/micro/benchmarks/micro_benchmark.h" #include "tensorflow/lite/micro/micro_error_reporter.h" #include "tensorflow/lite/micro/micro_interpreter.h" #include "tensorflow/lite/micro/micro_mutable_op_resolver.h" /* * Keyword Spotting Benchmark for performance optimizations. The model used in * this benchmark only serves as a reference. The values assigned to the model * weights and parameters are not representative of the original model. */ namespace { // Create an area of memory to use for input, output, and intermediate arrays. // Align arena to 16 bytes to avoid alignment warnings on certain platforms. constexpr int tensor_arena_size = 21 * 1024; alignas(16) uint8_t tensor_arena[tensor_arena_size + sizeof(MicroBenchmarkRunner<int16_t>)]; // A random number generator seed to generate input values. constexpr int kRandomSeed = 42; MicroBenchmarkRunner<int16_t>* benchmark_runner = nullptr; // Initialize benchmark runner instance explicitly to avoid global init order // issues on Sparkfun. Use new since static variables within a method // are automatically surrounded by locking, which breaks bluepill and stm32f4. void CreateBenchmarkRunner() { benchmark_runner = new (tensor_arena) MicroBenchmarkRunner<int16_t>( g_keyword_scrambled_model_data, &tensor_arena[sizeof(MicroBenchmarkRunner<int16_t>)], tensor_arena_size); } // Initializes keyword runner and sets random inputs. void InitializeKeywordRunner() { CreateBenchmarkRunner(); benchmark_runner->SetRandomInput(kRandomSeed); } // This method assumes InitializeKeywordRunner has already been run. void KeywordRunNIerations(int iterations) { for (int i = 0; i < iterations; i++) { benchmark_runner->RunSingleIteration(); } } } // namespace TF_LITE_MICRO_BENCHMARKS_BEGIN TF_LITE_MICRO_BENCHMARK(InitializeKeywordRunner()); TF_LITE_MICRO_BENCHMARK(KeywordRunNIerations(1)); TF_LITE_MICRO_BENCHMARK(KeywordRunNIerations(10)); TF_LITE_MICRO_BENCHMARKS_END
36.532468
80
0.77284
[ "model" ]
4deb251e2460ca1ae1d085ea8d59f09ed3f905dc
260
hpp
C++
proton/file.hpp
fikret0/proton
fbba4898e2a0c0bfc014b24085602565c95e9284
[ "MIT" ]
8
2021-04-18T17:04:22.000Z
2021-08-21T17:33:13.000Z
proton/file.hpp
fikret0/proton
fbba4898e2a0c0bfc014b24085602565c95e9284
[ "MIT" ]
null
null
null
proton/file.hpp
fikret0/proton
fbba4898e2a0c0bfc014b24085602565c95e9284
[ "MIT" ]
1
2021-04-19T06:22:49.000Z
2021-04-19T06:22:49.000Z
#pragma once #include <iostream> #include <string> #include <vector> namespace proton { class file { public: std::vector<std::string> ReadAllLines(std::string path); bool WriteAllText(std::string path, std::string text); }; }
16.25
64
0.638462
[ "vector" ]
4deea5953f337d28b3c55b842dd41b18c0c7f840
404
cpp
C++
src/configactionhandler.cpp
nickwynja/newsboat
e6105033129a3dd853bde8fd11a1e2a9fd574f38
[ "MIT" ]
2,086
2017-09-17T18:02:29.000Z
2022-03-31T21:15:13.000Z
src/configactionhandler.cpp
nickwynja/newsboat
e6105033129a3dd853bde8fd11a1e2a9fd574f38
[ "MIT" ]
1,966
2017-09-17T18:07:36.000Z
2022-03-31T20:09:44.000Z
src/configactionhandler.cpp
majacQ/newsboat
7f1dc6459f3911f33d6a391e636642ff7b18e1fa
[ "MIT" ]
263
2017-09-22T19:49:54.000Z
2022-03-22T09:48:48.000Z
#include "configactionhandler.h" #include "utils.h" namespace newsboat { void ConfigActionHandler::handle_action(const std::string& action, const std::string& params) { const std::vector<std::string> tokens = utils::tokenize_quoted(params); handle_action(action, tokens); } void ConfigActionHandler::handle_action(const std::string&, const std::vector<std::string>&) { } } // namespace newsboat
20.2
72
0.75
[ "vector" ]
4df1402d406795963b6b87140b5ee9ab0d5913e7
13,859
cc
C++
crawl-ref/source/syscalls.cc
robertxgray/crawl
a495bdf9d0bc3b54edaf46380901ba1342e5a3d5
[ "CC0-1.0" ]
2
2021-05-26T14:08:47.000Z
2022-03-17T21:24:06.000Z
crawl-ref/source/syscalls.cc
robertxgray/crawl
a495bdf9d0bc3b54edaf46380901ba1342e5a3d5
[ "CC0-1.0" ]
null
null
null
crawl-ref/source/syscalls.cc
robertxgray/crawl
a495bdf9d0bc3b54edaf46380901ba1342e5a3d5
[ "CC0-1.0" ]
null
null
null
/** * @file * @brief Wrappers for sys/libc calls, mostly for charset purposes. **/ #include "AppHdr.h" #include "syscalls.h" #ifdef TARGET_OS_WINDOWS # ifdef TARGET_COMPILER_VC # include <direct.h> # endif # define WIN32_LEAN_AND_MEAN # include <windows.h> # include <wincrypt.h> # include <io.h> #else # include <dirent.h> # include <unistd.h> # include <fcntl.h> # include <sys/types.h> # include <sys/stat.h> #endif #include "files.h" #include "random.h" #include "unicode.h" #ifdef __ANDROID__ #define HAVE_STAT #include <errno.h> #include <android/asset_manager.h> #include <android/asset_manager_jni.h> #include <jni.h> extern "C" { extern JNIEnv *Android_JNI_GetEnv(); // sigh } AAssetManager *_android_asset_manager = nullptr; // XXX // Used to save the game on SDLActivity.onPause extern "C" JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_nativeSaveGame( JNIEnv* env, jclass thiz) { save_game(false); } bool jni_keyboard_control(bool toggle) { JNIEnv *env = Android_JNI_GetEnv(); jclass sdlClass = env->FindClass("org/libsdl/app/SDLActivity"); if (!sdlClass) return false; jmethodID mid = env->GetStaticMethodID(sdlClass, "jniKeyboardControl", "(Z)Z"); jboolean shown = env->CallStaticBooleanMethod(sdlClass, mid, toggle); return shown; } #endif bool lock_file(int fd, bool write, bool wait) { #ifdef TARGET_OS_WINDOWS OVERLAPPED pos; pos.hEvent = 0; pos.Offset = 0; pos.OffsetHigh = 0; return !!LockFileEx((HANDLE)_get_osfhandle(fd), (write ? LOCKFILE_EXCLUSIVE_LOCK : 0) | (wait ? 0 : LOCKFILE_FAIL_IMMEDIATELY), 0, -1, -1, &pos); #else struct flock fl; fl.l_type = write ? F_WRLCK : F_RDLCK; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; return !fcntl(fd, wait ? F_SETLKW : F_SETLK, &fl); #endif } bool unlock_file(int fd) { #ifdef TARGET_OS_WINDOWS return !!UnlockFile((HANDLE)_get_osfhandle(fd), 0, 0, -1, -1); #else struct flock fl; fl.l_type = F_UNLCK; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; return !fcntl(fd, F_SETLK, &fl); #endif } bool read_urandom(char *buf, int len) { #ifdef TARGET_OS_WINDOWS HCRYPTPROV hProvider = 0; if (!CryptAcquireContextW(&hProvider, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { return false; } if (!CryptGenRandom(hProvider, len, (BYTE*)buf)) { CryptReleaseContext(hProvider, 0); return false; } CryptReleaseContext(hProvider, 0); return true; #else /* Try opening from various system provided (hopefully) CSPRNGs */ FILE* seed_f = fopen("/dev/urandom", "rb"); if (!seed_f) seed_f = fopen("/dev/random", "rb"); if (!seed_f) seed_f = fopen("/dev/srandom", "rb"); if (!seed_f) seed_f = fopen("/dev/arandom", "rb"); if (seed_f) { int res = fread(buf, 1, len, seed_f); fclose(seed_f); return res == len; } return false; #endif } #ifdef TARGET_OS_WINDOWS # ifndef UNIX // should check the presence of alarm() instead static void CALLBACK _abortion(PVOID /*dummy*/, BOOLEAN /*timedout*/) { TerminateProcess(GetCurrentProcess(), 0); } void alarm(unsigned int seconds) { HANDLE dummy; CreateTimerQueueTimer(&dummy, 0, _abortion, 0, seconds * 1000, 0, 0); } # endif # ifndef CRAWL_HAVE_FDATASYNC // implementation by Richard W.M. Jones // He claims this is the equivalent to fsync(), reading the MSDN doesn't seem // to show that vital metadata is indeed flushed, others report that at least // non-vital isn't. int fdatasync(int fd) { HANDLE h = (HANDLE)_get_osfhandle(fd); if (h == INVALID_HANDLE_VALUE) { errno = EBADF; return -1; } if (!FlushFileBuffers(h)) { /* Translate some Windows errors into rough approximations of Unix * errors. MSDN is useless as usual - in this case it doesn't * document the full range of errors. */ switch (GetLastError()) { /* eg. Trying to fsync a tty. */ case ERROR_INVALID_HANDLE: errno = EINVAL; break; default: errno = EIO; } return -1; } return 0; } # endif # ifndef CRAWL_HAVE_MKSTEMP int mkstemp(char *dummy) { HANDLE fh; for (int tries = 0; tries < 100; tries++) { wchar_t filename[MAX_PATH]; int len = GetTempPathW(MAX_PATH - 8, filename); ASSERT(len); for (int i = 0; i < 6; i++) filename[len + i] = 'a' + random2(26); filename[len + 6] = 0; fh = CreateFileW(filename, GENERIC_READ | GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_FLAG_DELETE_ON_CLOSE | FILE_ATTRIBUTE_TEMPORARY, nullptr); if (fh != INVALID_HANDLE_VALUE) return _open_osfhandle((intptr_t)fh, 0); } die("can't create temporary file in %%TMPDIR%%"); } # endif #else // non-Windows # ifndef CRAWL_HAVE_FDATASYNC // At least MacOS X 10.6 has it (as required by Posix) but present only // as a symbol in the libraries without a proper header. int fdatasync(int fd) { # ifdef F_FULLFSYNC // On MacOS X, fsync() doesn't even try to actually do what it was asked. // Sane systems might have this problem only on disks that do write caching // but ignore flush requests. fsync() should never return before the disk // claims the flush completed, but this is not the case on OS X. // // Except, this is the case for internal drives only. For "external" ones, // F_FULLFSYNC is said to fail (at least on some versions of OS X), while // fsync() actually works. Thus, we need to try both. return fcntl(fd, F_FULLFSYNC, 0) && fsync(fd); # else return fsync(fd); # endif } # endif #endif // The old school way of doing short delays via low level I/O sync. // Good for systems like old versions of Solaris that don't have usleep. #ifdef NEED_USLEEP # ifdef TARGET_OS_WINDOWS void usleep(unsigned long time) { ASSERT(time > 0); ASSERT(!(time % 1000)); Sleep(time/1000); } # else #include <sys/time.h> #include <sys/types.h> #include <sys/unistd.h> void usleep(unsigned long time) { struct timeval timer; timer.tv_sec = (time / 1000000L); timer.tv_usec = (time % 1000000L); select(0, nullptr, nullptr, nullptr, &timer); } # endif #endif #ifdef __ANDROID__ AAssetManager *_android_get_asset_manager() { JNIEnv *env = Android_JNI_GetEnv(); jclass sdlClass = env->FindClass("org/libsdl/app/SDLActivity"); if (!sdlClass) return nullptr; jmethodID mid = env->GetStaticMethodID(sdlClass, "getContext", "()Landroid/content/Context;"); jobject context = env->CallStaticObjectMethod(sdlClass, mid); if (!context) return nullptr; mid = env->GetMethodID(env->GetObjectClass(context), "getAssets", "()Landroid/content/res/AssetManager;"); jobject assets = env->CallObjectMethod(context, mid); if (!assets) return nullptr; return AAssetManager_fromJava(env, assets); } #endif bool file_exists(const string &name) { #ifdef TARGET_OS_WINDOWS DWORD lAttr = GetFileAttributesW(OUTW(name)); return lAttr != INVALID_FILE_ATTRIBUTES && !(lAttr & FILE_ATTRIBUTE_DIRECTORY); #else #ifdef __ANDROID__ if (name.find(ANDROID_ASSETS) == 0) { if (!_android_asset_manager) _android_asset_manager = _android_get_asset_manager(); ASSERT(_android_asset_manager); AAsset* asset = AAssetManager_open(_android_asset_manager, name.substr(strlen(ANDROID_ASSETS) + 1) .c_str(), AASSET_MODE_UNKNOWN); if (asset) { AAsset_close(asset); return true; } return false; } #endif struct stat st; const int err = ::stat(OUTS(name), &st); return !err && S_ISREG(st.st_mode); #endif } #ifdef __ANDROID__ /** * Remove an ANDROID_ASSETS prefix and strip any trailing slashes * from a directory name. */ static string _android_strip_dir_slash(const string &in) { string out = in.substr(strlen(ANDROID_ASSETS) + 1); if (out.back() == '/') out = out.substr(0, out.length() - 1); return out; } #endif // Low-tech existence check. bool dir_exists(const string &dir) { #ifdef TARGET_OS_WINDOWS DWORD lAttr = GetFileAttributesW(OUTW(dir)); return lAttr != INVALID_FILE_ATTRIBUTES && (lAttr & FILE_ATTRIBUTE_DIRECTORY); #else #ifdef __ANDROID__ if (dir.find(ANDROID_ASSETS) == 0) { if (!_android_asset_manager) _android_asset_manager = _android_get_asset_manager(); ASSERT(_android_asset_manager); AAssetDir* adir = AAssetManager_openDir(_android_asset_manager, _android_strip_dir_slash(dir) .c_str()); if (adir) { AAssetDir_close(adir); return true; } return false; } #endif #ifdef HAVE_STAT struct stat st; const int err = ::stat(OUTS(dir), &st); return !err && S_ISDIR(st.st_mode); #else DIR *d = opendir(OUTS(dir)); const bool exists = !!d; if (d) closedir(d); return exists; #endif #endif } static inline bool _is_good_filename(const string &s) { return s != "." && s != ".."; } // Returns the names of all files in the given directory. Note that the // filenames returned are relative to the directory. vector<string> get_dir_files(const string &dirname) { vector<string> files; #ifdef TARGET_OS_WINDOWS WIN32_FIND_DATAW lData; string dir = dirname; if (!dir.empty() && dir[dir.length() - 1] != FILE_SEPARATOR) dir += FILE_SEPARATOR; dir += "*"; HANDLE hFind = FindFirstFileW(OUTW(dir), &lData); if (hFind != INVALID_HANDLE_VALUE) { do { if (_is_good_filename(utf16_to_8(lData.cFileName))) files.push_back(utf16_to_8(lData.cFileName)); } while (FindNextFileW(hFind, &lData)); FindClose(hFind); } #else #ifdef __ANDROID__ if (dirname.find(ANDROID_ASSETS) == 0) { if (!_android_asset_manager) _android_asset_manager = _android_get_asset_manager(); ASSERT(_android_asset_manager); AAssetDir* adir = AAssetManager_openDir(_android_asset_manager, _android_strip_dir_slash(dirname).c_str()); if (!adir) return files; const char *file; while ((file = AAssetDir_getNextFileName(adir)) != nullptr) files.emplace_back(file); AAssetDir_close(adir); return files; } #endif DIR *dir = opendir(OUTS(dirname)); if (!dir) return files; while (dirent *entry = readdir(dir)) { string name = mb_to_utf8(entry->d_name); if (_is_good_filename(name)) files.push_back(name); } closedir(dir); #endif return files; } int rename_u(const char *oldpath, const char *newpath) { #ifdef TARGET_OS_WINDOWS return !MoveFileExW(OUTW(oldpath), OUTW(newpath), MOVEFILE_REPLACE_EXISTING); #else return rename(OUTS(oldpath), OUTS(newpath)); #endif } int unlink_u(const char *pathname) { #ifdef TARGET_OS_WINDOWS return _wunlink(OUTW(pathname)); #else return unlink(OUTS(pathname)); #endif } #ifdef __ANDROID__ /** * This implementation of handling Android fopens to Android assets * appears to originate from here: * http://www.50ply.com/blog/2013/01/19/ * loading-compressed-android-assets-with-file-pointer/ */ static int _android_read(void* cookie, char* buf, int size) { return AAsset_read((AAsset*)cookie, buf, size); } static int _android_write(void* cookie, const char* buf, int size) { return EACCES; // can't provide write access to the apk } static fpos_t _android_seek(void* cookie, fpos_t offset, int whence) { return AAsset_seek((AAsset*)cookie, offset, whence); } static int _android_close(void* cookie) { AAsset_close((AAsset*)cookie); return 0; } #endif FILE *fopen_u(const char *path, const char *mode) { #ifdef TARGET_OS_WINDOWS // Why it wants the mode string as double-byte is beyond me. return _wfopen(OUTW(path), OUTW(mode)); #else #ifdef __ANDROID__ if (strstr(path, ANDROID_ASSETS) == path) { if (!mode || mode[0] == 'w') return nullptr; if (!_android_asset_manager) _android_asset_manager = _android_get_asset_manager(); ASSERT(_android_asset_manager); AAsset* asset = AAssetManager_open(_android_asset_manager, path + strlen(ANDROID_ASSETS) + 1, AASSET_MODE_RANDOM); if (!asset) return nullptr; return funopen(asset, _android_read, _android_write, _android_seek, _android_close); } #endif return fopen(OUTS(path), mode); #endif } int mkdir_u(const char *pathname, mode_t mode) { #ifdef TARGET_OS_WINDOWS UNUSED(mode); return _wmkdir(OUTW(pathname)); #else return mkdir(OUTS(pathname), mode); #endif } int open_u(const char *pathname, int flags, mode_t mode) { #ifdef TARGET_OS_WINDOWS return _wopen(OUTW(pathname), flags, mode); #else return open(OUTS(pathname), flags, mode); #endif }
24.792487
79
0.620608
[ "vector" ]
4dfc23903fcfadc634c3e2f52519682c773c1718
3,009
cpp
C++
code/graphics_program_wrapper_main.cpp
aod6060/fps_game
b1d55d02ec124dc22ce877b814b6ff8452915213
[ "MIT" ]
1
2021-06-22T07:05:51.000Z
2021-06-22T07:05:51.000Z
code/graphics_program_wrapper_main.cpp
aod6060/fps_game
b1d55d02ec124dc22ce877b814b6ff8452915213
[ "MIT" ]
14
2018-08-29T09:32:17.000Z
2018-09-15T10:52:22.000Z
code/graphics_program_wrapper_main.cpp
aod6060/fps_game
b1d55d02ec124dc22ce877b814b6ff8452915213
[ "MIT" ]
null
null
null
#include "sys.h" void ProgramWrapperMain::init() { // Shaders vertex.create(GL_VERTEX_SHADER, "data/shaders/main.vert"); fragment.create(GL_FRAGMENT_SHADER, "data/shaders/main.frag"); // Program program.addShader(&vertex); program.addShader(&fragment); program.create(); program.bind(); // Attributes program.getAttr()->set("vertices", 0); program.getAttr()->set("texCoords", 1); program.getAttr()->set("normals", 2); program.getAttr()->bind(); program.getAttr()->enable("vertices"); program.getAttr()->enable("texCoords"); program.getAttr()->enable("normals"); program.getAttr()->unbind(); program.getAttr()->disable("vertices"); program.getAttr()->disable("texCoords"); program.getAttr()->disable("normals"); // Uniforms program.getUniforms()->create("proj"); program.getUniforms()->create("view"); program.getUniforms()->create("model"); program.getUniforms()->create("tex0"); program.getUniforms()->set1i("tex0", 0); program.unbind(); } void ProgramWrapperMain::bind() { program.bind(); } void ProgramWrapperMain::unbind() { program.unbind(); } void ProgramWrapperMain::release() { program.release(); fragment.release(); vertex.release(); } Program* ProgramWrapperMain::getProgram() { return &this->program; } void ProgramWrapperMain::bindAttribute() { program.getAttr()->bind(); } void ProgramWrapperMain::unbindAttribute() { program.getAttr()->unbind(); } void ProgramWrapperMain::verticesPointer() { program.getAttr()->pointer("vertices", 3, GL_FLOAT); } void ProgramWrapperMain::texCoordsPointer() { program.getAttr()->pointer("texCoords", 2, GL_FLOAT); } void ProgramWrapperMain::normalsPointer() { program.getAttr()->pointer("normals", 3, GL_FLOAT); } void ProgramWrapperMain::drawArrays(GLenum type, uint32_t count) { glDrawArrays(type, 0, count); } void ProgramWrapperMain::drawElements(GLenum type, uint32_t count) { glDrawElements(type, count, GL_UNSIGNED_INT, 0); } void ProgramWrapperMain::setProjection(const glm::mat4& m) { program.getUniforms()->setMat4("proj", m); } void ProgramWrapperMain::setView(const glm::mat4& m) { program.getUniforms()->setMat4("view", m); } void ProgramWrapperMain::setModel(const glm::mat4& m) { program.getUniforms()->setMat4("model", m); } void ProgramWrapperMain::bindTex0(Texture2D& tex) { tex.bind(GL_TEXTURE0); } void ProgramWrapperMain::unbindTex0(Texture2D& tex) { tex.unbind(GL_TEXTURE0); } void ProgramWrapperMain::drawMesh(Mesh& mesh, Texture2D& texture) { this->bindTex0(texture); this->bindAttribute(); mesh.getVertexBuffer()->bind(); this->verticesPointer(); mesh.getVertexBuffer()->unbind(); mesh.getTexCoordBuffer()->bind(); this->texCoordsPointer(); mesh.getTexCoordBuffer()->unbind(); mesh.getNormalBuffer()->bind(); this->normalsPointer(); mesh.getNormalBuffer()->unbind(); mesh.getIndexBuffer()->bind(); this->drawElements(GL_TRIANGLES, mesh.getIndexBuffer()->size()); mesh.getIndexBuffer()->unbind(); this->unbindAttribute(); this->unbindTex0(texture); }
21.190141
66
0.71984
[ "mesh", "model" ]
4dfd07085fb2241ba290231ff35e161847b8172f
4,673
cpp
C++
core/test/math/base_converter_tests.cpp
RomanWlm/lib-ledger-core
8c068fccb074c516096abb818a4e20786e02318b
[ "MIT" ]
92
2016-11-13T01:28:34.000Z
2022-03-25T01:11:37.000Z
core/test/math/base_converter_tests.cpp
RomanWlm/lib-ledger-core
8c068fccb074c516096abb818a4e20786e02318b
[ "MIT" ]
242
2016-11-28T11:13:09.000Z
2022-03-04T13:02:53.000Z
core/test/math/base_converter_tests.cpp
RomanWlm/lib-ledger-core
8c068fccb074c516096abb818a4e20786e02318b
[ "MIT" ]
91
2017-06-20T10:35:28.000Z
2022-03-09T14:15:40.000Z
/* * * base_converter_tests.cpp * ledger-core * * Created by Pierre Pollastri on 05/03/2019. * * The MIT License (MIT) * * Copyright (c) 2019 Ledger * * 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 <gtest/gtest.h> #include <math/BaseConverter.hpp> #include <utils/hex.h> #include <iostream> using namespace ledger::core; static std::vector<std::string> data { "FF11223344556677889900AABBCCFF00", "0011223344556677889900AABBCCFF00", "FF", "00000000", "", "666F6F", "666F6F62", "666F6F6261", "666F6F626172" }; static std::vector<std::string> expected_base32rfc_no_padding_encoding = { "74ISEM2EKVTHPCEZACVLXTH7AA", "AAISEM2EKVTHPCEZACVLXTH7AA", "74", "AAAAAAA", "", "MZXW6", "MZXW6YQ", "MZXW6YTB", "MZXW6YTBOI" }; static std::vector<std::string> expected_base32rfc_encoding = { "74ISEM2EKVTHPCEZACVLXTH7AA======", "AAISEM2EKVTHPCEZACVLXTH7AA======", "74======", "AAAAAAA=", "", "MZXW6===", "MZXW6YQ=", "MZXW6YTB", "MZXW6YTBOI======" }; static std::vector<std::string> expected_base64_encoding = { "/xEiM0RVZneImQCqu8z/AA==", "ABEiM0RVZneImQCqu8z/AA==", "/w==", "AAAAAA==", "", "Zm9v", "Zm9vYg==", "Zm9vYmE=", "Zm9vYmFy" }; TEST(BaseConverterTests, EncodeInBase32NoPadding) { auto index = 0; for (auto& d : data) { auto bytes = hex::toByteArray(d); auto base32Rfc = BaseConverter::encode(bytes, BaseConverter::BASE32_RFC4648_NO_PADDING); std::cout << "Base32: " << base32Rfc << std::endl; EXPECT_EQ(base32Rfc, expected_base32rfc_no_padding_encoding[index++]); } } TEST(BaseConverterTests, EncodeInBase32) { auto index = 0; for (auto& d : data) { auto bytes = hex::toByteArray(d); auto base32Rfc = BaseConverter::encode(bytes, BaseConverter::BASE32_RFC4648); std::cout << "Base32: " << base32Rfc << std::endl; EXPECT_EQ(base32Rfc, expected_base32rfc_encoding[index++]); } } TEST(BaseConverterTests, DecodeWithBase32NoPadding) { auto index = 0; for (auto& encoded : expected_base32rfc_no_padding_encoding) { std::vector<uint8_t> decoded; BaseConverter::decode(encoded, BaseConverter::BASE32_RFC4648_NO_PADDING, decoded); auto hexDecoded = hex::toString(decoded, true); std::cout << "Decoded: " << hexDecoded << std::endl; EXPECT_EQ(hexDecoded, data[index++]); } } TEST(BaseConverterTests, DecodeWithBase32) { auto index = 0; for (auto& encoded : expected_base32rfc_encoding) { std::vector<uint8_t> decoded; BaseConverter::decode(encoded, BaseConverter::BASE32_RFC4648, decoded); auto hexDecoded = hex::toString(decoded, true); std::cout << "Decoded: " << hexDecoded << std::endl; EXPECT_EQ(hexDecoded, data[index++]); } } TEST(BaseConverterTests, EncodeInBase64) { auto index = 0; for (auto& d : data) { auto bytes = hex::toByteArray(d); auto base64Rfc = BaseConverter::encode(bytes, BaseConverter::BASE64_RFC4648); std::cout << "Base64: " << base64Rfc << std::endl; EXPECT_EQ(base64Rfc, expected_base64_encoding[index++]); } } TEST(BaseConverterTests, DecodeWithBase64) { auto index = 0; for (auto& encoded : expected_base64_encoding) { std::vector<uint8_t> decoded; BaseConverter::decode(encoded, BaseConverter::BASE64_RFC4648, decoded); auto hexDecoded = hex::toString(decoded, true); std::cout << "Decoded: " << hexDecoded << std::endl; EXPECT_EQ(hexDecoded, data[index++]); } }
31.362416
96
0.666595
[ "vector" ]
1501f3dccc04487c702d64ae1e9cb4cf9eac518c
3,843
cc
C++
RecoLocalTracker/SiPixelRecHits/plugins/PixelCPEGenericESProducer.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
RecoLocalTracker/SiPixelRecHits/plugins/PixelCPEGenericESProducer.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
RecoLocalTracker/SiPixelRecHits/plugins/PixelCPEGenericESProducer.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
#include "RecoLocalTracker/SiPixelRecHits/interface/PixelCPEGenericESProducer.h" #include "RecoLocalTracker/SiPixelRecHits/interface/PixelCPEGeneric.h" #include "MagneticField/Engine/interface/MagneticField.h" #include "MagneticField/Records/interface/IdealMagneticFieldRecord.h" #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h" #include "Geometry/Records/interface/TrackerDigiGeometryRecord.h" #include "Geometry/Records/interface/TrackerTopologyRcd.h" #include "DataFormats/TrackerCommon/interface/TrackerTopology.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/ModuleFactory.h" #include "FWCore/Framework/interface/ESProducer.h" // new record #include "CondFormats/DataRecord/interface/SiPixelGenErrorDBObjectRcd.h" #include <string> #include <memory> using namespace edm; PixelCPEGenericESProducer::PixelCPEGenericESProducer(const edm::ParameterSet & p) { std::string myname = p.getParameter<std::string>("ComponentName"); // Use LA-width from DB. If both (upper and this) are false LA-width is calcuated from LA-offset useLAWidthFromDB_ = p.existsAs<bool>("useLAWidthFromDB")? p.getParameter<bool>("useLAWidthFromDB"):false; // Use Alignment LA-offset useLAAlignmentOffsets_ = p.existsAs<bool>("useLAAlignmentOffsets")? p.getParameter<bool>("useLAAlignmentOffsets"):false; magname_ = p.existsAs<edm::ESInputTag>("MagneticFieldRecord")? p.getParameter<edm::ESInputTag>("MagneticFieldRecord"):edm::ESInputTag(""); UseErrorsFromTemplates_ = p.getParameter<bool>("UseErrorsFromTemplates"); pset_ = p; setWhatProduced(this,myname); //std::cout<<" ESProducer "<<myname<<" "<<useLAWidthFromDB_<<" "<<useLAAlignmentOffsets_<<" " // <<UseErrorsFromTemplates_<<std::endl; //dk } PixelCPEGenericESProducer::~PixelCPEGenericESProducer() {} std::shared_ptr<PixelClusterParameterEstimator> PixelCPEGenericESProducer::produce(const TkPixelCPERecord & iRecord){ ESHandle<MagneticField> magfield; iRecord.getRecord<IdealMagneticFieldRecord>().get( magname_, magfield ); edm::ESHandle<TrackerGeometry> pDD; iRecord.getRecord<TrackerDigiGeometryRecord>().get( pDD ); edm::ESHandle<TrackerTopology> hTT; iRecord.getRecord<TrackerDigiGeometryRecord>().getRecord<TrackerTopologyRcd>().get(hTT); // Lorant angle for offsets ESHandle<SiPixelLorentzAngle> lorentzAngle; if(useLAAlignmentOffsets_) // LA offsets from alignment iRecord.getRecord<SiPixelLorentzAngleRcd>().get("fromAlignment",lorentzAngle ); else // standard LA, from calibration, label="" iRecord.getRecord<SiPixelLorentzAngleRcd>().get(lorentzAngle ); // add the new la width object ESHandle<SiPixelLorentzAngle> lorentzAngleWidth; const SiPixelLorentzAngle * lorentzAngleWidthProduct = 0; if(useLAWidthFromDB_) { // use the width LA iRecord.getRecord<SiPixelLorentzAngleRcd>().get("forWidth",lorentzAngleWidth ); lorentzAngleWidthProduct = lorentzAngleWidth.product(); } else { lorentzAngleWidthProduct = NULL;} // do not use it //std::cout<<" la width "<<lorentzAngleWidthProduct<<std::endl; //dk const SiPixelGenErrorDBObject * genErrorDBObjectProduct = 0; // Errors take only from new GenError ESHandle<SiPixelGenErrorDBObject> genErrorDBObject; if(UseErrorsFromTemplates_) { // do only when generrors are needed iRecord.getRecord<SiPixelGenErrorDBObjectRcd>().get(genErrorDBObject); genErrorDBObjectProduct = genErrorDBObject.product(); //} else { //std::cout<<" pass an empty GenError pointer"<<std::endl; } cpe_ = std::make_shared<PixelCPEGeneric>( pset_,magfield.product(),*pDD.product(), *hTT.product(),lorentzAngle.product(), genErrorDBObjectProduct,lorentzAngleWidthProduct); return cpe_; }
40.452632
98
0.76867
[ "geometry", "object" ]
150b76ba8ad4fffa2217f599e541fff6800e5425
1,606
cpp
C++
113-path-sum-ii/path-sum-ii.cpp
TJUSsr/leetcodesolution
8244de2d76c9e8e5b9d98dd1e8efed4d680d44ee
[ "MIT" ]
null
null
null
113-path-sum-ii/path-sum-ii.cpp
TJUSsr/leetcodesolution
8244de2d76c9e8e5b9d98dd1e8efed4d680d44ee
[ "MIT" ]
2
2021-03-31T19:10:41.000Z
2021-12-13T19:58:15.000Z
113-path-sum-ii/path-sum-ii.cpp
TJUSsr/leetcodesolution
8244de2d76c9e8e5b9d98dd1e8efed4d680d44ee
[ "MIT" ]
null
null
null
// Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. // // Note: A leaf is a node with no children. // // Example: // // Given the below binary tree and sum = 22, // // // 5 // / \ // 4 8 // / / \ // 11 13 4 // / \ / \ // 7 2 5 1 // // // Return: // // // [ // [5,4,11,2], // [5,8,4,5] // ] // // /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ static const auto _=[](){ std::ios::sync_with_stdio(false); cin.tie(nullptr); return nullptr; }(); class Solution { public: vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<int> tempres; vector<vector<int>> res; if(root==nullptr) return res; DFS(root,sum,0,tempres,res); return res; } private: void DFS(TreeNode* root, int sum, int tempressum, vector<int> &tempres, vector<vector<int>> &res){ tempres.push_back(root->val); tempressum+=root->val; if(root->left==nullptr&&root->right==nullptr){ if(sum==tempressum) res.push_back(tempres); } else{ if(root->left){ DFS(root->left,sum,tempressum,tempres,res); } if(root->right){ DFS(root->right,sum,tempressum,tempres,res); } } tempressum-=root->val; tempres.pop_back(); return; } };
21.413333
105
0.504981
[ "vector" ]
15144caad74d7bebf1f2961a804bffdace97ddbd
19,483
cxx
C++
main/sd/source/ui/sidebar/DocumentHelper.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sd/source/ui/sidebar/DocumentHelper.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sd/source/ui/sidebar/DocumentHelper.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #include "precompiled_sd.hxx" #include "DocumentHelper.hxx" #include "drawdoc.hxx" #include "DrawDocShell.hxx" #include "sdpage.hxx" #include "glob.hxx" #include "unmovss.hxx" #include "strings.hrc" #include "sdresid.hxx" #include "undoback.hxx" #include <com/sun/star/drawing/XDrawPagesSupplier.hpp> #include <com/sun/star/drawing/XDrawPages.hpp> #include <com/sun/star/frame/XComponentLoader.hpp> #include <com/sun/star/container/XIndexAccess.hpp> #include "stlpool.hxx" #include <svx/xfillit0.hxx> #include <tools/diagnose_ex.h> using namespace ::com::sun::star; namespace sd { namespace sidebar { SdPage* DocumentHelper::CopyMasterPageToLocalDocument ( SdDrawDocument& rTargetDocument, SdPage* pMasterPage) { SdPage* pNewMasterPage = NULL; do { if (pMasterPage == NULL) break; // Check the presence of the source document. SdDrawDocument* pSourceDocument = static_cast<SdDrawDocument*>( pMasterPage->GetModel()); if (pSourceDocument == NULL) break; // When the given master page already belongs to the target document // then there is nothing more to do. if (pSourceDocument == &rTargetDocument) { pNewMasterPage = pMasterPage; break; } // Test if the master pages of both the slide and its notes page are // present. This is not the case when we are called during the // creation of the slide master page because then the notes master // page is not there. sal_uInt16 nSourceMasterPageCount = pSourceDocument->GetMasterPageCount(); if (nSourceMasterPageCount%2 == 0) // There should be 1 handout page + n slide masters + n notes // masters = 2*n+1. An even value indicates that a new slide // master but not yet the notes master has been inserted. break; sal_uInt16 nIndex = pMasterPage->GetPageNum(); if (nSourceMasterPageCount <= nIndex+1) break; // Get the slide master page. if (pMasterPage != static_cast<SdPage*>( pSourceDocument->GetMasterPage(nIndex))) break; // Get the notes master page. SdPage* pNotesMasterPage = static_cast<SdPage*>( pSourceDocument->GetMasterPage(nIndex+1)); if (pNotesMasterPage == NULL) break; // Check if a master page with the same name as that of the given // master page already exists. bool bPageExists (false); sal_uInt16 nMasterPageCount(rTargetDocument.GetMasterSdPageCount(PK_STANDARD)); for (sal_uInt16 nMaster=0; nMaster<nMasterPageCount; nMaster++) { SdPage* pCandidate = static_cast<SdPage*>( rTargetDocument.GetMasterSdPage (nMaster, PK_STANDARD)); if (pMasterPage!=NULL && pCandidate->GetName().CompareTo(pMasterPage->GetName())==0) { bPageExists = true; pNewMasterPage = pCandidate; break; } } if (bPageExists) break; // Create a new slide (and its notes page.) uno::Reference<drawing::XDrawPagesSupplier> xSlideSupplier ( rTargetDocument.getUnoModel(), uno::UNO_QUERY); if ( ! xSlideSupplier.is()) break; uno::Reference<drawing::XDrawPages> xSlides ( xSlideSupplier->getDrawPages(), uno::UNO_QUERY); if ( ! xSlides.is()) break; xSlides->insertNewByIndex (xSlides->getCount()); // Set a layout. SdPage* pSlide = rTargetDocument.GetSdPage( rTargetDocument.GetSdPageCount(PK_STANDARD)-1, PK_STANDARD); if (pSlide == NULL) break; pSlide->SetAutoLayout(AUTOLAYOUT_TITLE, sal_True); // Create a copy of the master page and the associated notes // master page and insert them into our document. pNewMasterPage = AddMasterPage(rTargetDocument, pMasterPage); if (pNewMasterPage==NULL) break; SdPage* pNewNotesMasterPage = AddMasterPage(rTargetDocument, pNotesMasterPage); if (pNewNotesMasterPage==NULL) break; // Make the connection from the new slide to the master page // (and do the same for the notes page.) rTargetDocument.SetMasterPage ( rTargetDocument.GetSdPageCount(PK_STANDARD)-1, pNewMasterPage->GetName(), &rTargetDocument, sal_False, // Connect the new master page with the new slide but // do not modify other (master) pages. sal_True); } while (false); // We are not interested in any automatisms for our modified internal // document. rTargetDocument.SetChanged (sal_False); return pNewMasterPage; } SdPage* DocumentHelper::GetSlideForMasterPage (SdPage* pMasterPage) { SdPage* pCandidate = NULL; SdDrawDocument* pDocument = NULL; if (pMasterPage != NULL) pDocument = dynamic_cast<SdDrawDocument*>(pMasterPage->GetModel()); // Iterate over all pages and check if it references the given master // page. if (pDocument!=NULL && pDocument->GetSdPageCount(PK_STANDARD) > 0) { // In most cases a new slide has just been inserted so start with // the last page. sal_uInt16 nPageIndex (pDocument->GetSdPageCount(PK_STANDARD)-1); bool bFound (false); while ( ! bFound) { pCandidate = pDocument->GetSdPage( nPageIndex, PK_STANDARD); if (pCandidate != NULL) { if (static_cast<SdPage*>(&pCandidate->TRG_GetMasterPage()) == pMasterPage) { bFound = true; break; } } if (nPageIndex == 0) break; else nPageIndex --; } // If no page was found that refernced the given master page reset // the pointer that is returned. if ( ! bFound) pCandidate = NULL; } return pCandidate; } SdPage* DocumentHelper::AddMasterPage ( SdDrawDocument& rTargetDocument, SdPage* pMasterPage) { SdPage* pClonedMasterPage = NULL; if (pMasterPage!=NULL) { try { // Duplicate the master page. pClonedMasterPage = static_cast<SdPage*>(pMasterPage->Clone()); // Copy the necessary styles. SdDrawDocument* pSourceDocument = static_cast<SdDrawDocument*>(pMasterPage->GetModel()); if (pSourceDocument != NULL) ProvideStyles (*pSourceDocument, rTargetDocument, pClonedMasterPage); // Copy the precious flag. pClonedMasterPage->SetPrecious(pMasterPage->IsPrecious()); // Now that the styles are available we can insert the cloned // master page. rTargetDocument.InsertMasterPage (pClonedMasterPage); } catch (uno::Exception& rException) { pClonedMasterPage = NULL; DBG_UNHANDLED_EXCEPTION(); } catch (::std::exception rException) { pClonedMasterPage = NULL; OSL_TRACE ("caught general exception"); } catch (...) { pClonedMasterPage = NULL; OSL_TRACE ("caught general exception"); } } return pClonedMasterPage; } void DocumentHelper::ProvideStyles ( SdDrawDocument& rSourceDocument, SdDrawDocument& rTargetDocument, SdPage* pPage) { // Get the layout name of the given page. String sLayoutName (pPage->GetLayoutName()); sLayoutName.Erase (sLayoutName.SearchAscii (SD_LT_SEPARATOR)); // Copy the style sheet from source to target document. SdStyleSheetPool* pSourceStyleSheetPool = static_cast<SdStyleSheetPool*>(rSourceDocument.GetStyleSheetPool()); SdStyleSheetPool* pTargetStyleSheetPool = static_cast<SdStyleSheetPool*>(rTargetDocument.GetStyleSheetPool()); SdStyleSheetVector aCreatedStyles; pTargetStyleSheetPool->CopyLayoutSheets ( sLayoutName, *pSourceStyleSheetPool, aCreatedStyles); // Add an undo action for the copied style sheets. if( !aCreatedStyles.empty() ) { ::svl::IUndoManager* pUndoManager = rTargetDocument.GetDocSh()->GetUndoManager(); if (pUndoManager != NULL) { SdMoveStyleSheetsUndoAction* pMovStyles = new SdMoveStyleSheetsUndoAction ( &rTargetDocument, aCreatedStyles, sal_True); pUndoManager->AddUndoAction (pMovStyles); } } } void DocumentHelper::AssignMasterPageToPageList ( SdDrawDocument& rTargetDocument, SdPage* pMasterPage, const ::boost::shared_ptr<std::vector<SdPage*> >& rpPageList) { do { if (pMasterPage == NULL && pMasterPage->IsMasterPage()) break; // Make the layout name by stripping ouf the layout postfix from the // layout name of the given master page. String sFullLayoutName (pMasterPage->GetLayoutName()); String sBaseLayoutName (sFullLayoutName); sBaseLayoutName.Erase (sBaseLayoutName.SearchAscii (SD_LT_SEPARATOR)); if (rpPageList->empty()) break; // Create a second list that contains only the valid pointers to // pages for which an assignment is necessary. ::std::vector<SdPage*>::const_iterator iPage; ::std::vector<SdPage*> aCleanedList; for (iPage=rpPageList->begin(); iPage!=rpPageList->end(); ++iPage) { OSL_ASSERT(*iPage!=NULL && (*iPage)->GetModel() == &rTargetDocument); if (*iPage != NULL && (*iPage)->GetLayoutName().CompareTo(sFullLayoutName)!=0) { aCleanedList.push_back(*iPage); } } if (aCleanedList.empty() ) break; ::svl::IUndoManager* pUndoMgr = rTargetDocument.GetDocSh()->GetUndoManager(); if( pUndoMgr ) pUndoMgr->EnterListAction(String(SdResId(STR_UNDO_SET_PRESLAYOUT)), String()); SdPage* pMasterPageInDocument = ProvideMasterPage(rTargetDocument,pMasterPage,rpPageList); if (pMasterPageInDocument == NULL) break; // Assign the master pages to the given list of pages. for (iPage=aCleanedList.begin(); iPage!=aCleanedList.end(); ++iPage) { AssignMasterPageToPage ( pMasterPageInDocument, sBaseLayoutName, *iPage); } if( pUndoMgr ) pUndoMgr->LeaveListAction(); } while (false); } SdPage* DocumentHelper::AddMasterPage ( SdDrawDocument& rTargetDocument, SdPage* pMasterPage, sal_uInt16 nInsertionIndex) { SdPage* pClonedMasterPage = NULL; if (pMasterPage!=NULL) { // Duplicate the master page. pClonedMasterPage = static_cast<SdPage*>(pMasterPage->Clone()); // Copy the precious flag. pClonedMasterPage->SetPrecious(pMasterPage->IsPrecious()); // Copy the necessary styles. SdDrawDocument* pSourceDocument = static_cast<SdDrawDocument*>(pMasterPage->GetModel()); if (pSourceDocument != NULL) { ProvideStyles (*pSourceDocument, rTargetDocument, pClonedMasterPage); // Now that the styles are available we can insert the cloned // master page. rTargetDocument.InsertMasterPage (pClonedMasterPage, nInsertionIndex); // Adapt the size of the new master page to that of the pages in // the document. Size aNewSize (rTargetDocument.GetSdPage(0, pMasterPage->GetPageKind())->GetSize()); Rectangle aBorders ( pClonedMasterPage->GetLftBorder(), pClonedMasterPage->GetUppBorder(), pClonedMasterPage->GetRgtBorder(), pClonedMasterPage->GetLwrBorder()); pClonedMasterPage->ScaleObjects(aNewSize, aBorders, sal_True); pClonedMasterPage->SetSize(aNewSize); pClonedMasterPage->CreateTitleAndLayout(sal_True); } } return pClonedMasterPage; } /** In here we have to handle three cases: 1. pPage is a normal slide. We can use SetMasterPage to assign the master pages to it. 2. pPage is a master page that is used by at least one slide. We can assign the master page to these slides. 3. pPage is a master page that is currently not used by any slide. We can delete that page and add copies of the given master pages instead. For points 2 and 3 where one master page A is assigned to another B we have to keep in mind that the master page that page A has already been inserted into the target document. */ void DocumentHelper::AssignMasterPageToPage ( SdPage* pMasterPage, const String& rsBaseLayoutName, SdPage* pPage) { // Leave early when the parameters are invalid. if (pPage == NULL || pMasterPage == NULL) return; SdDrawDocument* pDocument = dynamic_cast<SdDrawDocument*>(pPage->GetModel()); if (pDocument == NULL) return; if ( ! pPage->IsMasterPage()) { // 1. Remove the background object (so that that, if it exists, does // not override the new master page) and assign the master page to // the regular slide. pDocument->GetDocSh()->GetUndoManager()->AddUndoAction( new SdBackgroundObjUndoAction( *pDocument, *pPage, pPage->getSdrPageProperties().GetItemSet()), sal_True); pPage->getSdrPageProperties().PutItem(XFillStyleItem(XFILL_NONE)); pDocument->SetMasterPage ( (pPage->GetPageNum()-1)/2, rsBaseLayoutName, pDocument, sal_False, sal_False); } else { // Find first slide that uses the master page. SdPage* pSlide = NULL; sal_uInt16 nPageCount = pDocument->GetSdPageCount(PK_STANDARD); for (sal_uInt16 nPage=0; nPage<nPageCount&&pSlide==NULL; nPage++) { SdrPage* pCandidate = pDocument->GetSdPage(nPage,PK_STANDARD); if (pCandidate != NULL && pCandidate->TRG_HasMasterPage() && &(pCandidate->TRG_GetMasterPage()) == pPage) { pSlide = static_cast<SdPage*>(pCandidate); } } if (pSlide != NULL) { // 2. Assign the given master pages to the first slide that was // found above that uses the master page. pDocument->SetMasterPage ( (pSlide->GetPageNum()-1)/2, rsBaseLayoutName, pDocument, sal_False, sal_False); } else { // 3. Replace the master page A by a copy of the given master // page B. pDocument->RemoveUnnecessaryMasterPages ( pPage, sal_False); } } } SdPage* DocumentHelper::ProvideMasterPage ( SdDrawDocument& rTargetDocument, SdPage* pMasterPage, const ::boost::shared_ptr<std::vector<SdPage*> >& rpPageList) { // Make sure that both the master page and its notes master exist // in the source document. If one is missing then return without // making any changes. if (pMasterPage == NULL) { // The caller should make sure that the master page is valid. OSL_ASSERT(pMasterPage != NULL); return NULL; } SdDrawDocument* pSourceDocument = static_cast<SdDrawDocument*>(pMasterPage->GetModel()); if (pSourceDocument == NULL) return NULL; SdPage* pNotesMasterPage = static_cast<SdPage*>( pSourceDocument->GetMasterPage(pMasterPage->GetPageNum()+1)); if (pNotesMasterPage == NULL) { // The model is not in a valid state. Maybe a new master page // is being (not finished yet) created? Return without making // any changes. return NULL; } SdPage* pMasterPageInDocument = NULL; // Search for a master page with the same name as the given one in // the target document. const XubString sMasterPageLayoutName (pMasterPage->GetLayoutName()); for (sal_uInt16 nIndex=0,nCount=rTargetDocument.GetMasterPageCount(); nIndex<nCount; ++nIndex) { SdPage* pCandidate = static_cast<SdPage*>(rTargetDocument.GetMasterPage(nIndex)); if (pCandidate!=NULL && sMasterPageLayoutName==pCandidate->GetLayoutName()) { // The requested master page does already exist in the // target document, return it. return pCandidate; } } // The given master page does not already belong to the target // document so we have to create copies and insert them into the // targer document. // Determine the position where the new master pages are inserted. // By default they are inserted at the end. When we assign to a // master page then insert after the last of the (selected) pages. sal_uInt16 nInsertionIndex = rTargetDocument.GetMasterPageCount(); if (rpPageList->front()->IsMasterPage()) { nInsertionIndex = rpPageList->back()->GetPageNum(); } // Clone the master page. if (pMasterPage->GetModel() != &rTargetDocument) { pMasterPageInDocument = AddMasterPage (rTargetDocument, pMasterPage, nInsertionIndex); if( rTargetDocument.IsUndoEnabled() ) rTargetDocument.AddUndo( rTargetDocument.GetSdrUndoFactory().CreateUndoNewPage(*pMasterPageInDocument)); } else pMasterPageInDocument = pMasterPage; // Clone the notes master. if (pNotesMasterPage->GetModel() != &rTargetDocument) { SdPage* pClonedNotesMasterPage = AddMasterPage (rTargetDocument, pNotesMasterPage, nInsertionIndex+1); if( rTargetDocument.IsUndoEnabled() ) rTargetDocument.AddUndo( rTargetDocument.GetSdrUndoFactory().CreateUndoNewPage(*pClonedNotesMasterPage)); } return pMasterPageInDocument; } } } // end of namespace sd::sidebar
33.649396
98
0.61623
[ "object", "vector", "model" ]
15163589714ba461f737b72b550569d80d0e91cf
4,830
cc
C++
c++/test/TestSargsApplier.cc
hinxx/orc
22cb5388c958261df8f1c3d6de82d36afb78f140
[ "Apache-2.0" ]
545
2015-05-11T18:22:53.000Z
2022-03-28T03:47:49.000Z
c++/test/TestSargsApplier.cc
hinxx/orc
22cb5388c958261df8f1c3d6de82d36afb78f140
[ "Apache-2.0" ]
704
2015-07-06T22:07:34.000Z
2022-03-31T02:53:22.000Z
c++/test/TestSargsApplier.cc
coderex2522/orc
7d2838b4b38111bc1bfa00592d84a8b36286b9f2
[ "Apache-2.0" ]
441
2015-05-14T23:00:45.000Z
2022-03-30T06:09:20.000Z
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "sargs/SargsApplier.hh" #include "wrap/gtest-wrapper.h" namespace orc { TEST(TestSargsApplier, findColumnTest) { auto type = std::unique_ptr<Type>(Type::buildTypeFromString( "struct<a:int,c:string,e:struct<f:bigint,g:double>>")); EXPECT_EQ(1, SargsApplier::findColumn(*type, "a")); EXPECT_EQ(2, SargsApplier::findColumn(*type, "c")); EXPECT_EQ(3, SargsApplier::findColumn(*type, "e")); EXPECT_EQ(4, SargsApplier::findColumn(*type, "f")); EXPECT_EQ(5, SargsApplier::findColumn(*type, "g")); EXPECT_EQ(std::numeric_limits<uint64_t>::max(), SargsApplier::findColumn(*type, "b")); } TEST(TestSargsApplier, findArrayColumnTest) { auto type = std::unique_ptr<Type>(Type::buildTypeFromString( "struct<a:int,c:string,e:array<struct<f:bigint,g:double>>>")); EXPECT_EQ(1, SargsApplier::findColumn(*type, "a")); EXPECT_EQ(2, SargsApplier::findColumn(*type, "c")); EXPECT_EQ(3, SargsApplier::findColumn(*type, "e")); EXPECT_EQ(5, SargsApplier::findColumn(*type, "f")); EXPECT_EQ(6, SargsApplier::findColumn(*type, "g")); EXPECT_EQ(std::numeric_limits<uint64_t>::max(), SargsApplier::findColumn(*type, "b")); } TEST(TestSargsApplier, findMapColumnTest) { auto type = std::unique_ptr<Type>(Type::buildTypeFromString( "struct<a:int,c:string,e:map<int,struct<f:bigint,g:double>>>")); EXPECT_EQ(1, SargsApplier::findColumn(*type, "a")); EXPECT_EQ(2, SargsApplier::findColumn(*type, "c")); EXPECT_EQ(3, SargsApplier::findColumn(*type, "e")); EXPECT_EQ(6, SargsApplier::findColumn(*type, "f")); EXPECT_EQ(7, SargsApplier::findColumn(*type, "g")); EXPECT_EQ(std::numeric_limits<uint64_t>::max(), SargsApplier::findColumn(*type, "b")); } static proto::ColumnStatistics createIntStats( int64_t min, int64_t max, bool hasNull = false) { proto::ColumnStatistics statistics; statistics.set_hasnull(hasNull); auto intStats = statistics.mutable_intstatistics(); intStats->set_minimum(min); intStats->set_maximum(max); return statistics; } TEST(TestSargsApplier, testPickRowGroups) { auto type = std::unique_ptr<Type>( Type::buildTypeFromString("struct<x:int,y:int>")); auto sarg = SearchArgumentFactory::newBuilder() ->startAnd() .equals( "x", PredicateDataType::LONG, Literal(static_cast<int64_t>(100))) .equals( "y", PredicateDataType::LONG, Literal(static_cast<int64_t>(10))) .end() .build(); // prepare row group column statistics std::unordered_map<uint64_t, proto::RowIndex> rowIndexes; // col 1 proto::RowIndex rowIndex1; *rowIndex1.mutable_entry()->Add()->mutable_statistics() = createIntStats(0L, 10L); *rowIndex1.mutable_entry()->Add()->mutable_statistics() = createIntStats(100L, 200L); *rowIndex1.mutable_entry()->Add()->mutable_statistics() = createIntStats(300L, 500L); *rowIndex1.mutable_entry()->Add()->mutable_statistics() = createIntStats(100L, 100L); rowIndexes[1] = rowIndex1; // col 2 proto::RowIndex rowIndex2; *rowIndex2.mutable_entry()->Add()->mutable_statistics() = createIntStats(0L, 9L); *rowIndex2.mutable_entry()->Add()->mutable_statistics() = createIntStats(11L, 20L); *rowIndex2.mutable_entry()->Add()->mutable_statistics() = createIntStats(10L, 10L); *rowIndex2.mutable_entry()->Add()->mutable_statistics() = createIntStats(0L, 100LL); rowIndexes[2] = rowIndex2; // evaluate row group index SargsApplier applier(*type, sarg.get(), 1000, WriterVersion_ORC_135); EXPECT_TRUE(applier.pickRowGroups(4000, rowIndexes, {})); std::vector<bool> rowgroups = applier.getRowGroups(); EXPECT_EQ(4, rowgroups.size()); EXPECT_EQ(false, rowgroups[0]); EXPECT_EQ(false, rowgroups[1]); EXPECT_EQ(false, rowgroups[2]); EXPECT_EQ(true, rowgroups[3]); } } // namespace orc
38.951613
75
0.676812
[ "vector" ]
15180ef61a4b40115e7c6a22fa61676ebafebe46
4,382
hpp
C++
contrib/base64.hpp
nondejus/sha1_gpu_nearcollisionattacks
26642b9e88b6ba331a2d917136d79970c14ae491
[ "MIT" ]
26
2017-12-22T19:02:21.000Z
2021-04-24T04:51:07.000Z
contrib/base64.hpp
nondejus/sha1_gpu_nearcollisionattacks
26642b9e88b6ba331a2d917136d79970c14ae491
[ "MIT" ]
1
2019-12-01T09:49:06.000Z
2019-12-01T09:49:06.000Z
contrib/base64.hpp
nondejus/sha1_gpu_nearcollisionattacks
26642b9e88b6ba331a2d917136d79970c14ae491
[ "MIT" ]
7
2018-01-16T08:36:41.000Z
2020-08-31T10:35:50.000Z
/*********************************************************************************\ * * * https://github.com/cr-marcstevens/snippets/tree/master/cxxheaderonly * * * * base64.hpp - A header only C++ base64 encoder/decoder library * * Copyright (c) 2017 Marc Stevens * * * * MIT License * * * * 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 BASE64_HPP #define BASE64_HPP #include <string> #include <vector> static inline std::string base64_encode(const std::string& in); static inline std::string base64_decode(const std::string& in); namespace detail { // template class so that instantiations in different compilation units are merged template<int dummy> struct base64_helper { static const char* chars; static std::vector<int> LUT; static std::string base64_encode(const std::string& in) { std::string out; out.reserve( ((in.size()+2)/3)*4 ); int val=0, bits=-6; for (std::size_t i = 0; i < in.size(); ++i) { val = (val<<8) + (int)((unsigned char)(in[i])); for (bits += 8; bits >= 0; bits -= 6) { out.push_back( chars[ (val>>bits)&0x3F ] ); } } if (bits > - 6) { val <<= 8; bits += 8; out.push_back( chars[ (val>>bits)&0x3F ] ); } while (out.size()%4) { out.push_back('='); } return out; } static std::string base64_decode(const std::string& in) { std::string out; out.reserve((in.size()/4)*3); if (LUT.empty()) { LUT.resize(256,-1); for (int i = 0; i < 64; ++i) { LUT[(int)( (unsigned char)(chars[i]) )] = i; } } int val=0, bits=-8; for (std::size_t i = 0; i < in.size(); ++i) { int c = LUT[(int)( (unsigned char)(in[i]) )]; if (c == -1) { break; } val = (val << 6) + c; bits += 6; if (bits >= 0) { out.push_back( (char)( (val>>bits)&0xFF ) ); bits -= 8; } } return out; } }; template<int dummy> const char* base64_helper<dummy>::chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; template<int dummy> std::vector<int> base64_helper<dummy>::LUT; } static inline std::string base64_encode(const std::string& in) { return detail::base64_helper<0>::base64_encode(in); } static inline std::string base64_decode(const std::string& in) { return detail::base64_helper<0>::base64_decode(in); } #endif // BASE64_HPP
33.19697
110
0.493382
[ "vector" ]
151a070003b734a0a55f5588efacab0a144ce3a1
9,231
hpp
C++
include/GlobalNamespace/ColorTransitionSO.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/ColorTransitionSO.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/ColorTransitionSO.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: BaseTransitionSO #include "GlobalNamespace/BaseTransitionSO.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: ColorSO class ColorSO; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Color struct Color; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Size: 0x50 #pragma pack(push, 1) // Autogenerated type: ColorTransitionSO // [TokenAttribute] Offset: FFFFFFFF class ColorTransitionSO : public GlobalNamespace::BaseTransitionSO { public: // private ColorSO _normalColor // Size: 0x8 // Offset: 0x20 GlobalNamespace::ColorSO* normalColor; // Field size check static_assert(sizeof(GlobalNamespace::ColorSO*) == 0x8); // private ColorSO _highlightedColor // Size: 0x8 // Offset: 0x28 GlobalNamespace::ColorSO* highlightedColor; // Field size check static_assert(sizeof(GlobalNamespace::ColorSO*) == 0x8); // private ColorSO _pressedColor // Size: 0x8 // Offset: 0x30 GlobalNamespace::ColorSO* pressedColor; // Field size check static_assert(sizeof(GlobalNamespace::ColorSO*) == 0x8); // private ColorSO _disabledColor // Size: 0x8 // Offset: 0x38 GlobalNamespace::ColorSO* disabledColor; // Field size check static_assert(sizeof(GlobalNamespace::ColorSO*) == 0x8); // private ColorSO _selectedColor // Size: 0x8 // Offset: 0x40 GlobalNamespace::ColorSO* selectedColor; // Field size check static_assert(sizeof(GlobalNamespace::ColorSO*) == 0x8); // private ColorSO _selectedAndHighlightedColor // Size: 0x8 // Offset: 0x48 GlobalNamespace::ColorSO* selectedAndHighlightedColor; // Field size check static_assert(sizeof(GlobalNamespace::ColorSO*) == 0x8); // Creating value type constructor for type: ColorTransitionSO ColorTransitionSO(GlobalNamespace::ColorSO* normalColor_ = {}, GlobalNamespace::ColorSO* highlightedColor_ = {}, GlobalNamespace::ColorSO* pressedColor_ = {}, GlobalNamespace::ColorSO* disabledColor_ = {}, GlobalNamespace::ColorSO* selectedColor_ = {}, GlobalNamespace::ColorSO* selectedAndHighlightedColor_ = {}) noexcept : normalColor{normalColor_}, highlightedColor{highlightedColor_}, pressedColor{pressedColor_}, disabledColor{disabledColor_}, selectedColor{selectedColor_}, selectedAndHighlightedColor{selectedAndHighlightedColor_} {} // Get instance field reference: private ColorSO _normalColor GlobalNamespace::ColorSO*& dyn__normalColor(); // Get instance field reference: private ColorSO _highlightedColor GlobalNamespace::ColorSO*& dyn__highlightedColor(); // Get instance field reference: private ColorSO _pressedColor GlobalNamespace::ColorSO*& dyn__pressedColor(); // Get instance field reference: private ColorSO _disabledColor GlobalNamespace::ColorSO*& dyn__disabledColor(); // Get instance field reference: private ColorSO _selectedColor GlobalNamespace::ColorSO*& dyn__selectedColor(); // Get instance field reference: private ColorSO _selectedAndHighlightedColor GlobalNamespace::ColorSO*& dyn__selectedAndHighlightedColor(); // public UnityEngine.Color get_normalColor() // Offset: 0x10E0BE4 UnityEngine::Color get_normalColor(); // public UnityEngine.Color get_highlightedColor() // Offset: 0x10E0E48 UnityEngine::Color get_highlightedColor(); // public UnityEngine.Color get_pressedColor() // Offset: 0x10E0E8C UnityEngine::Color get_pressedColor(); // public UnityEngine.Color get_disabledColor() // Offset: 0x10E0ED0 UnityEngine::Color get_disabledColor(); // public UnityEngine.Color get_selectedColor() // Offset: 0x10E0F14 UnityEngine::Color get_selectedColor(); // public UnityEngine.Color get_selectedAndHighlightedColor() // Offset: 0x10E0F58 UnityEngine::Color get_selectedAndHighlightedColor(); // public System.Void .ctor() // Offset: 0x10E4C74 // Implemented from: BaseTransitionSO // Base method: System.Void BaseTransitionSO::.ctor() // Base method: System.Void PersistentScriptableObject::.ctor() // Base method: System.Void ScriptableObject::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ColorTransitionSO* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::ColorTransitionSO::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<ColorTransitionSO*, creationType>())); } }; // ColorTransitionSO #pragma pack(pop) static check_size<sizeof(ColorTransitionSO), 72 + sizeof(GlobalNamespace::ColorSO*)> __GlobalNamespace_ColorTransitionSOSizeCheck; static_assert(sizeof(ColorTransitionSO) == 0x50); } DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::ColorTransitionSO*, "", "ColorTransitionSO"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::ColorTransitionSO::get_normalColor // Il2CppName: get_normalColor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Color (GlobalNamespace::ColorTransitionSO::*)()>(&GlobalNamespace::ColorTransitionSO::get_normalColor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorTransitionSO*), "get_normalColor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::ColorTransitionSO::get_highlightedColor // Il2CppName: get_highlightedColor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Color (GlobalNamespace::ColorTransitionSO::*)()>(&GlobalNamespace::ColorTransitionSO::get_highlightedColor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorTransitionSO*), "get_highlightedColor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::ColorTransitionSO::get_pressedColor // Il2CppName: get_pressedColor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Color (GlobalNamespace::ColorTransitionSO::*)()>(&GlobalNamespace::ColorTransitionSO::get_pressedColor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorTransitionSO*), "get_pressedColor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::ColorTransitionSO::get_disabledColor // Il2CppName: get_disabledColor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Color (GlobalNamespace::ColorTransitionSO::*)()>(&GlobalNamespace::ColorTransitionSO::get_disabledColor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorTransitionSO*), "get_disabledColor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::ColorTransitionSO::get_selectedColor // Il2CppName: get_selectedColor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Color (GlobalNamespace::ColorTransitionSO::*)()>(&GlobalNamespace::ColorTransitionSO::get_selectedColor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorTransitionSO*), "get_selectedColor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::ColorTransitionSO::get_selectedAndHighlightedColor // Il2CppName: get_selectedAndHighlightedColor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Color (GlobalNamespace::ColorTransitionSO::*)()>(&GlobalNamespace::ColorTransitionSO::get_selectedAndHighlightedColor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorTransitionSO*), "get_selectedAndHighlightedColor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::ColorTransitionSO::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
52.748571
544
0.756364
[ "object", "vector" ]
151cd327ccb20929e55bf2687ee9ee1fc12407cf
10,893
cpp
C++
Vector/Vector.cpp
Artintrex/Utility-Vector
8e0e02c2552edfb01cb70dcb47e8c7d60fdda42c
[ "MIT" ]
null
null
null
Vector/Vector.cpp
Artintrex/Utility-Vector
8e0e02c2552edfb01cb70dcb47e8c7d60fdda42c
[ "MIT" ]
null
null
null
Vector/Vector.cpp
Artintrex/Utility-Vector
8e0e02c2552edfb01cb70dcb47e8c7d60fdda42c
[ "MIT" ]
null
null
null
// This is an independent project of an individual developer. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com //Author: Egemen Gungor #include "Vector.h" #include <limits> #include <cmath> float clamp(float x, float min, float max); const Vector4 Vector4::one = Vector4(1, 1, 1, 1); const Vector4 Vector4::zero = Vector4(0, 0, 0, 0); const Vector4 Vector4::negativeInfinity = Vector4(-std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity()); const Vector4 Vector4::positiveInfinity = Vector4(std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity()); const Vector3 Vector3::forward = Vector3(0, 0, 1); const Vector3 Vector3::back = Vector3(0, 0, -1); const Vector3 Vector3::left = Vector3(-1, 0, 0); const Vector3 Vector3::right = Vector3(1, 0, 0); const Vector3 Vector3::up = Vector3(0, 1, 0); const Vector3 Vector3::down = Vector3(0, -1, 0); const Vector3 Vector3::one = Vector3(1, 1, 1); const Vector3 Vector3::zero = Vector3(0, 0, 0); const Vector3 Vector3::negativeInfinity = Vector3(-std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity()); const Vector3 Vector3::positiveInfinity = Vector3(std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity()); const Vector2 Vector2::left = Vector2(-1, 0); const Vector2 Vector2::right = Vector2(1, 0); const Vector2 Vector2::up = Vector2(0, 1); const Vector2 Vector2::down = Vector2(0, -1); const Vector2 Vector2::one = Vector2(1, 1); const Vector2 Vector2::zero = Vector2(0, 0); const Vector2 Vector2::negativeInfinity = Vector2(-std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity()); const Vector2 Vector2::positiveInfinity = Vector2(std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity()); //Vector4 bool Vector4::operator == (Vector4 const& p) const { return static_cast<double>((*this - p).SqrMagnitude()) < DBL_EPSILON; } bool Vector4::operator !=(Vector4 const& p) const { return static_cast<double>((*this - p).SqrMagnitude()) >= DBL_EPSILON; } float Vector4::SqrMagnitude() const { return static_cast<float>(static_cast<double>(x) * x + static_cast<double>(y) * y + static_cast<double>(z) * z + static_cast<double>(w) * w); } float Vector4::Magnitude() const { return sqrt(SqrMagnitude()); } Vector4 Vector4::Normalize() const { const float len = Magnitude(); return Vector4(x / len, y / len, z / len, w / len); } float Vector4::Dot(const Vector4& lhs, const Vector4& rhs) { return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z + lhs.w * rhs.w; } float Vector4::Distance(const Vector4& from, const Vector4& to) { return (from - to).Magnitude(); } Vector4 Vector4::Lerp(const Vector4& from, const Vector4& to, float t) { if (t > 1) t = 1; else if (t < 0) t = 0; return to * t + from * (1 - t); } Vector4 Vector4::LerpNoClamp(const Vector4& from, const Vector4& to, float t) { return to * t + from * (1 - t); } Vector4 Vector4::Project(const Vector4& vector, const Vector4& normal) { return normal * (Dot(vector, normal) / normal.SqrMagnitude()); } //Vector3 bool Vector3::operator==(Vector3 const& p) const { return static_cast<double>((*this - p).SqrMagnitude()) < DBL_EPSILON; } bool Vector3::operator!=(Vector3 const& p) const { return static_cast<double>((*this - p).SqrMagnitude()) >= DBL_EPSILON; } float Vector3::SqrMagnitude() const { return static_cast<float>(static_cast<double>(x) * x + static_cast<double>(y) * y + static_cast<double>(z) * z); } float Vector3::Magnitude() const { return sqrt(SqrMagnitude()); } float Vector3::Dot(const Vector3& lhs, const Vector3& rhs) { return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z; } Vector3 Vector3::Cross(const Vector3& lhs, const Vector3& rhs) { return Vector3(lhs.y * rhs.z - lhs.z * rhs.y, lhs.z * rhs.x - lhs.x * rhs.z, lhs.x * rhs.y - lhs.y * rhs.x); } float Vector3::Angle(const Vector3& from, const Vector3& to) { return acos(clamp(Dot(from.Normalize(), to.Normalize()), -1.0f, 1.0f)) * 57.29578f; } float Vector3::Distance(const Vector3& from, const Vector3& to) { return (from - to).Magnitude(); } Vector3 Vector3::Lerp(const Vector3& from, const Vector3& to, float delta) { delta = clamp(delta, 0, 1); return to * delta + from * (1 - delta); } Vector3 Vector3::LerpNoClamp(const Vector3& from, const Vector3& to, const float delta) { return to * delta + from * (1 - delta); } Vector3 Vector3::MoveTowards(const Vector3& from, const Vector3& to, const float delta) { const Vector3 direction = to - from; const float magnitude = direction.Magnitude(); if (magnitude <= delta || delta < FLT_EPSILON) { return to; } return from + (direction / magnitude) * delta; } Vector3 Vector3::Project(const Vector3& vector, const Vector3& normal) { const float magnitude = normal.SqrMagnitude(); if (magnitude < FLT_EPSILON) return zero; const float dp = Dot(vector, normal) / magnitude; return Vector3(normal.x * dp, normal.y * dp, normal.z * dp); } Vector3 Vector3::ProjectOnPlane(const Vector3& vector, const Vector3& planeNormal) { const float magnitude = planeNormal.SqrMagnitude(); if (magnitude < FLT_EPSILON) return vector; const float dp = Dot(vector, planeNormal); return Vector3(vector.x - planeNormal.x * dp / magnitude, vector.y - planeNormal.y * dp / magnitude, vector.z - planeNormal.z * dp / magnitude); } Vector3 Vector3::Reflect(const Vector3& vector, const Vector3& normal) { const float dp = -2 * Dot(normal, vector); return Vector3(dp * normal.x + vector.x, dp * normal.y + vector.y, dp * normal.z + vector.z); } float Vector3::TriangleArea(const Vector3& a, const Vector3& b, const Vector3& c) { return abs(Cross((a - c), (b - c)).Magnitude() / 2); } bool Vector3::PointTriangleIntersection(const Vector3& point, const Vector3& a, const Vector3& b, const Vector3& c) { const float area = TriangleArea(a, b, c); const float area1 = TriangleArea(point, b, c); const float area2 = TriangleArea(a, point, c); const float area3 = TriangleArea(a, b, point); return fabs(area - (area1 + area2 + area3)) < FLT_EPSILON; } bool Vector3::LinePlaneIntersection(Vector3& intersection, const Vector3& direction, const Vector3& origin, const Vector3& normal, const Vector3& plane) { const float d = Dot(normal, direction); //Check if they are parallel if (fabs(d) < FLT_EPSILON) return false; const float x = (Dot(normal, plane - origin)) / d; //Check if the plane is behind the line if (x < 0) return false; intersection = origin + direction * x; return true; } bool Vector3::LineTriangleIntersection(Vector3& intersection, const Vector3& direction, const Vector3& origin, const Vector3& a, const Vector3& b, const Vector3& c) { const Vector3 edge1 = b - a; const Vector3 edge2 = c - a; const Vector3 normal = Cross(direction, edge2); float d = Dot(edge1, normal); if (fabs(d) < FLT_EPSILON) return false; d = (1.0f / d); const Vector3 s = origin - a; const float u = d * Dot(s, normal); if (u < 0.0 || u > 1.0) return false; const Vector3 q = Cross(s, edge1); const float v = d * Dot(direction, q); if (v < 0.0 || static_cast<double>(u) + v > 1.0) return false; const float t = d * Dot(edge2, q); if (t > FLT_EPSILON) { intersection = origin + direction * t; return true; } return false; } Vector3 Vector3::Normalize() const { const float len = Magnitude(); return Vector3(x / len, y / len, z / len); } //Vector2 bool Vector2::operator==(Vector2 const& p) const { return static_cast<double>((*this - p).SqrMagnitude())< DBL_EPSILON; } bool Vector2::operator!=(Vector2 const& p) const { return static_cast<double>((*this - p).SqrMagnitude()) >= DBL_EPSILON; } float Vector2::SqrMagnitude() const { return static_cast<float>(static_cast<double>(x) * x + static_cast<double>(y) * y); } float Vector2::Magnitude() const { return sqrt(SqrMagnitude()); } Vector2 Vector2::Normalize() const { const float len = Magnitude(); return Vector2(x / len, y / len); } float Vector2::Angle(const Vector2& from, const Vector2& to) { return acos(clamp(Dot(from.Normalize(), to.Normalize()), -1.0f, 1.0f)) * 57.29578f; } float Vector2::Distance(const Vector2& from, const Vector2& to) { return (from - to).Magnitude(); } float Vector2::Dot(const Vector2& lhs, const Vector2& rhs) { return lhs.x * rhs.x + lhs.y * rhs.y; } Vector2 Vector2::Lerp(const Vector2& from, const Vector2& to, float delta) { delta = clamp(delta, 0, 1); return to * delta + from * (1 - delta); } Vector2 Vector2::LerpNoClamp(const Vector2& from, const Vector2& to, float delta) { return to * delta + from * (1 - delta); } Vector2 Vector2::MoveTowards(const Vector2& from, const Vector2& to, float delta) { const Vector2 direction = to - from; const float magnitude = direction.Magnitude(); if (magnitude <= delta || delta < FLT_EPSILON) { return to; } return from + (direction / magnitude) * delta; } Vector2 Vector2::Reflect(const Vector2& vector, const Vector2& normal) { const float dp = -2 * Dot(normal, vector); return Vector2(dp * normal.x + vector.x, dp * normal.y + vector.y); } Vector2 Vector2::Perpendicular(const Vector2& vector) { return Vector2(-vector.y, vector.x); } float Vector2::TriangleArea(const Vector2& a, const Vector2& b, const Vector2& c) { return static_cast<float>(abs((static_cast<double>(a.x) * (static_cast<double>(b.y) - c.y) + static_cast<double>(b.x) * (static_cast<double>(c.y) - a.y) + static_cast<double>(c.x) * (static_cast<double>(a.y) - b.y)) / 2.0)); } bool Vector2::PointTriangleIntersection(const Vector2& point, const Vector2& a, const Vector2& b, const Vector2& c) { const float area = TriangleArea(a, b, c); const float area1 = TriangleArea(point, b, c); const float area2 = TriangleArea(a, point, c); const float area3 = TriangleArea(a, b, point); return fabs(area - (area1 + area2 + area3)) < FLT_EPSILON; } //String operations std::string Vector2::ToString(int precision) const { char buffer[89]; snprintf(buffer, 89, "%.*f, %.*f", precision, x, precision, y); return std::string(buffer); } std::string Vector3::ToString(int precision) const { char buffer[134]; snprintf(buffer, 134, "%.*f, %.*f, %.*f", precision, x, precision, y, precision, z); return std::string(buffer); } std::string Vector4::ToString(int precision) const { char buffer[179]; snprintf(buffer, 179, "%.*f, %.*f, %.*f, %.*f", precision, x, precision, y, precision, z, precision, w); return std::string(buffer); } float clamp(float x, float min, float max) { if (x < min) x = min; else if (x > max) x = max; return x; }
28.665789
214
0.688516
[ "vector" ]
151ef437e9c5196ec62768b8e58920d8d3916ee9
3,216
cpp
C++
ngraph/test/type_prop/gather.cpp
Byoungmin-Cho/openvino
902a89b582d9c43ad2fe854092fd69c3aaf1db81
[ "Apache-2.0" ]
null
null
null
ngraph/test/type_prop/gather.cpp
Byoungmin-Cho/openvino
902a89b582d9c43ad2fe854092fd69c3aaf1db81
[ "Apache-2.0" ]
28
2021-09-24T09:29:02.000Z
2022-03-28T13:20:46.000Z
ngraph/test/type_prop/gather.cpp
jayabs2020/openvino
67a82a040faaf66f109035acf7de6e4b7568bc08
[ "Apache-2.0" ]
1
2020-08-30T11:48:03.000Z
2020-08-30T11:48:03.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "gtest/gtest.h" #include "ngraph/ngraph.hpp" #include "util/type_prop.hpp" NGRAPH_SUPPRESS_DEPRECATED_START using namespace std; using namespace ngraph; TEST(type_prop, gather_axis_0) { Shape params_shape{3, 2}; Shape indices_shape{2, 2}; Shape out_shape{2, 2, 2}; auto P = make_shared<op::Parameter>(element::f32, params_shape); auto I = make_shared<op::Parameter>(element::i32, indices_shape); auto A = op::Constant::create(element::i64, Shape{}, {0}); auto G = make_shared<op::v1::Gather>(P, I, A); ASSERT_EQ(G->get_element_type(), element::f32); ASSERT_EQ(G->get_shape(), out_shape); ASSERT_EQ(G->get_axis(), 0); } TEST(type_prop, gather_axis_1) { Shape params_shape{3, 3}; Shape indices_shape{1, 2}; Shape out_shape{3, 1, 2}; auto P = make_shared<op::Parameter>(element::f32, params_shape); auto I = make_shared<op::Parameter>(element::i32, indices_shape); auto A = op::Constant::create(element::i64, Shape{}, {1}); auto G = make_shared<op::v1::Gather>(P, I, A); ASSERT_EQ(G->get_element_type(), element::f32); ASSERT_EQ(G->get_shape(), out_shape); ASSERT_EQ(G->get_axis(), 1); } TEST(type_prop, gather_v1_incorrect_axis_shape) { auto params = make_shared<op::Parameter>(element::f32, Shape{5, 6}); auto indices = make_shared<op::Parameter>(element::i64, Shape{4}); auto axis = make_shared<op::Parameter>(element::i64, Shape{2}); try { auto G = make_shared<op::v1::Gather>(params, indices, axis); // Should have thrown, so fail if it didn't FAIL() << "Incorrect axis input shape"; } catch (const NodeValidationFailure& error) { EXPECT_HAS_SUBSTRING(error.what(), std::string("Axes input must be scalar or have 1 element (shape:")); } catch (...) { FAIL() << "Deduced type check failed for unexpected reason"; } } TEST(type_prop, gather_v1_axis_out_of_input_rank) { auto params = make_shared<op::Parameter>(element::f32, Shape{5, 6}); auto indices = make_shared<op::Parameter>(element::i64, Shape{4}); auto axis = make_shared<op::Constant>(element::i64, Shape{1}, vector<int64_t>{2}); try { auto G = make_shared<op::v1::Gather>(params, indices, axis); // Should have thrown, so fail if it didn't FAIL() << "Incorrect element of axis input"; } catch (const NodeValidationFailure& error) { EXPECT_HAS_SUBSTRING(error.what(), std::string("The axis must => 0 and <= input_rank (axis:")); } catch (...) { FAIL() << "Deduced type check failed for unexpected reason"; } } TEST(type_prop, gather_v1_negative_axis) { auto params = make_shared<op::Parameter>(element::f32, Shape{5, 6, 7}); auto indices = make_shared<op::Parameter>(element::i64, Shape{4}); int64_t axis = -2; auto axis_node = make_shared<op::Constant>(element::i64, Shape{1}, vector<int64_t>{axis}); auto gather_v1 = make_shared<op::v1::Gather>(params, indices, axis_node); ASSERT_EQ(gather_v1->get_axis(), 1); }
33.852632
97
0.643657
[ "shape", "vector" ]
1520f3b7f6795829b55ca2ee24dfe5b8a7af12d2
1,024
cpp
C++
plugins/gui/src/gui_utils/geometry.cpp
e7p/hal
2a88a8abefe5e2f79a74ec646e5fb3d8e6eb7cc8
[ "MIT" ]
407
2019-04-26T10:45:52.000Z
2022-03-31T15:52:30.000Z
plugins/gui/src/gui_utils/geometry.cpp
e7p/hal
2a88a8abefe5e2f79a74ec646e5fb3d8e6eb7cc8
[ "MIT" ]
219
2019-04-29T16:42:01.000Z
2022-03-11T22:57:41.000Z
plugins/gui/src/gui_utils/geometry.cpp
e7p/hal
2a88a8abefe5e2f79a74ec646e5fb3d8e6eb7cc8
[ "MIT" ]
53
2019-05-02T21:23:35.000Z
2022-03-11T19:46:05.000Z
#include "gui/gui_utils/geometry.h" #include <QApplication> #include <QDesktopWidget> #include <QWidget> namespace hal { namespace gui_utility { void ensureOnScreen(QWidget* w) { auto boundingRect = QApplication::desktop()->availableGeometry(w); auto requiredRect = w->geometry(); // Try fitting vertically, prioritizing top on screen if (boundingRect.top() > requiredRect.top()) requiredRect.moveTop(boundingRect.top()); else if (boundingRect.bottom() < requiredRect.bottom()) requiredRect.moveBottom(boundingRect.bottom()); // Try fitting horizontally, prioritizing left on screen if (boundingRect.left() > requiredRect.left()) requiredRect.moveLeft(boundingRect.left()); else if (boundingRect.right() < requiredRect.right()) requiredRect.moveRight(boundingRect.right()); w->move(requiredRect.topLeft()); } } }
34.133333
78
0.612305
[ "geometry" ]
15221a62fee6b5a47baf9f826c620025f166681b
3,326
cxx
C++
handoff_response/src/aeff_phi_dep/aeff_phi_dep.cxx
fermi-lat/irfs
cebe27fc6a974ac4448f15d7944b21e419c585e9
[ "BSD-3-Clause" ]
null
null
null
handoff_response/src/aeff_phi_dep/aeff_phi_dep.cxx
fermi-lat/irfs
cebe27fc6a974ac4448f15d7944b21e419c585e9
[ "BSD-3-Clause" ]
4
2020-02-21T20:16:38.000Z
2022-03-22T17:39:03.000Z
handoff_response/src/aeff_phi_dep/aeff_phi_dep.cxx
fermi-lat/irfs
cebe27fc6a974ac4448f15d7944b21e419c585e9
[ "BSD-3-Clause" ]
1
2020-07-07T18:30:05.000Z
2020-07-07T18:30:05.000Z
#include <iostream> #include <sstream> #include <vector> #include "TCanvas.h" #include "TFile.h" #include "TF1.h" #include "TH1F.h" #include "TH2F.h" #include "TMath.h" #include "TTree.h" #include "TVirtualPad.h" int main() { TFile root_file("goodEvent.root"); TTree * merit = (TTree*)(root_file.Get("MeritTuple")); size_t astepno(6); double amin(0.2), amax(1.0), astep((amax - amin)/astepno); size_t lestepno(12); double lemin(1.25), lemax(5.75), lestep((lemax - lemin)/lestepno); TF1 fitf("fitf", "1 + [0]*x^[1]", 0, 0.9); fitf.SetParameter(0, 1.2); fitf.SetParameter(1, 2); TH2F par1map("par1map", "par1map", lestepno, lemin, lemax, astepno, amin, amax); TH2F par2map("par2map", "par2map", lestepno, lemin, lemax, astepno, amin, amax); TCanvas canvas("canvas", "aeff", 600, 800); canvas.Divide(3, 4); std::string psfile("foo.ps"); for (size_t ai(0); ai < astepno; ai++) { double as0(ai*astep + amin); double as1(as0 + astep); for (size_t lei(0); lei < lestepno; lei++) { size_t i(ai*lestepno + lei + 1); size_t ipad(lei + 1); canvas.cd(ipad); double les0(lei*lestep + lemin); double les1(les0 + lestep); std::ostringstream cuts; cuts << "log10(McEnergy)>" << les0 << " && log10(McEnergy)<" << les1 << " && McZDir>" << -as1 << " && McZDir<" << -as0; std::cout << cuts.str() << std::endl; std::string my_var; if (i == 1) { my_var = "abs(abs(atan(McYDir/McXDir))*2./pi-0.5)*2>>htemp(10,0,1)"; } else { my_var = "abs(abs(atan(McYDir/McXDir))*2./pi-0.5)*2"; } merit->Draw(my_var.c_str(), cuts.str().c_str()); long nevents(merit->GetSelectedRows()); if (nevents > 10) { TVirtualPad * pad(canvas.GetPad(ipad)); TH1F * hist = (TH1F*)(pad->GetPrimitive("htemp")); double lowval = (hist->GetBinContent(1)+hist->GetBinContent(2) + hist->GetBinContent(3)+hist->GetBinContent(4))/4.; if (lowval > 0) { for (size_t jb(1); jb < 11; jb++) { hist->SetBinContent(jb, hist->GetBinContent(jb)/lowval); } } hist->Draw(); fitf.SetParameter(1, 2); fitf.SetParameter(2, 1); hist->Fit(&fitf); double psq(fitf.GetParameter(0)); double psx(fitf.GetParameter(1)); par1map.Fill(les0 + lestep/2, as0 + astep/2, psq); par2map.Fill(les0 + lestep/2, as0 + astep/2, psx); } } if (ai == 0) { canvas.Print((psfile + "(").c_str()); } else { canvas.Print(psfile.c_str()); } } TCanvas minicvas1("minicvas1", "PAR1", 500, 350); par1map.Draw("COLZ"); par1map.SetXTitle("log10(McEnergy)"); par1map.SetXTitle("McZDir"); minicvas1.Print(psfile.c_str()); TCanvas minicvas2("minicvas2", "PAR2", 500, 350); par2map.Draw("COLZ"); par2map.SetXTitle("log10(McEnergy)"); par2map.SetXTitle("McZDir"); minicvas2.Print((psfile + ")").c_str()); TFile file("phi_params.root", "recreate"); par1map.Write(); par2map.Write(); }
31.980769
80
0.532471
[ "vector" ]
1527b45ded98b76dd9b8d32a4cee5d0199863b00
1,465
cpp
C++
Engine/Source/Game.cpp
FloatyMonkey/FmEngine
f187f00c2d25ae662218de72b69ea57a93de6d41
[ "MIT" ]
15
2019-12-01T10:17:17.000Z
2022-01-30T00:37:43.000Z
Engine/Source/Game.cpp
FloatyMonkey/FmEngine
f187f00c2d25ae662218de72b69ea57a93de6d41
[ "MIT" ]
null
null
null
Engine/Source/Game.cpp
FloatyMonkey/FmEngine
f187f00c2d25ae662218de72b69ea57a93de6d41
[ "MIT" ]
2
2020-01-18T21:32:22.000Z
2021-06-28T07:51:46.000Z
// Copyright (c) 2020 Lauro Oyen, FmEngine contributors. All rights reserved. // Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. #include "World/World.h" #include "Components/Components.h" #include "Physics/Rigidbody.h" #include "Audio/AudioSource.h" #include "Audio/AudioClip.h" #include "Graphics/Mesh.h" namespace FM::Game { Mesh meshA; Mesh meshB; AudioClip clipA; AudioClip clipB; void Setup(World& world) { meshA.Load("Resource/Monkey.fme"); meshB.Load("Resource/Cube.fme"); clipA.Load("Resource/HappyBackground01.wav"); clipB.Load("Resource/HappyBackground02.wav"); { Entity e = world.Create(); world.Assign<Transform>(e); world.Assign<StaticMesh>(e).mesh = &meshA; } { Entity e = world.Create(); Transform& tr = world.Assign<Transform>(e); Rigidbody& rb = world.Assign<Rigidbody>(e); world.Assign<StaticMesh>(e).mesh = &meshB; tr.translation.y = 1.0f; tr.scale = 0.5f; rb.inverseMass = 1.0f / 5.0f; rb.linearVelocity.y = 10.0f; } { Entity e = world.Create(); AudioSource& source = world.Assign<AudioSource>(e); source.clip = &clipA; source.repeat = true; source.volume = -3; source.Play(); } { Entity e = world.Create(); AudioSource& source = world.Assign<AudioSource>(e); source.clip = &clipB; source.repeat = true; source.volume = -3; source.Play(); } } void Update(World& world) { } }
19.797297
99
0.662116
[ "mesh", "transform" ]
15289dce77c1725682e2f2e9a9f8b941ea9c607b
32,241
cpp
C++
src/EmailWorker.cpp
r4sas/pboted
b1db56579f3876d2abfd3157ca0fe0045c8a60a4
[ "BSD-3-Clause" ]
null
null
null
src/EmailWorker.cpp
r4sas/pboted
b1db56579f3876d2abfd3157ca0fe0045c8a60a4
[ "BSD-3-Clause" ]
null
null
null
src/EmailWorker.cpp
r4sas/pboted
b1db56579f3876d2abfd3157ca0fe0045c8a60a4
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (c) 2019-2021 polistern */ #include <openssl/sha.h> #include <iterator> #include <utility> #include <vector> #include <ctime> #include "BoteContext.h" #include "DHTworker.h" #include "EmailWorker.h" namespace pbote { namespace kademlia { EmailWorker email_worker; EmailWorker::EmailWorker() : started_(false), m_send_email_thread_(nullptr), m_worker_thread_(nullptr) {} EmailWorker::~EmailWorker() { stop(); } void EmailWorker::start() { if (!started_) { started_ = true; email_identities = context.getEmailIdentities(); if (email_identities.empty()) { LogPrint(eLogError, "EmailWorker: have no identities for start"); } else { LogPrint(eLogInfo, "EmailWorker: have ", email_identities.size(), " identities"); startCheckEmailTasks(); startSendEmailTask(); } m_worker_thread_ = new std::thread([this] { run(); }); } } void EmailWorker::stop() { LogPrint(eLogWarning, "EmailWorker: stopping"); if (started_) { started_ = false; stopCheckEmailTasks(); stopSendEmailTask(); if (m_worker_thread_) { m_worker_thread_->join(); delete m_worker_thread_; m_worker_thread_ = nullptr; } } LogPrint(eLogWarning, "EmailWorker: stopped"); } void EmailWorker::startCheckEmailTasks() { if (started_) { for (const auto &email_identity: email_identities) { // ToDo: move to object? LogPrint(eLogInfo, "EmailWorker: start startCheckEmailTasks for identity ", email_identity->publicName); auto new_thread = std::make_shared<std::thread>([this, email_identity] { checkEmailTask(email_identity); }); m_check_email_threads_.push_back(new_thread); } } } bool EmailWorker::stopCheckEmailTasks() { LogPrint(eLogInfo, "EmailWorker: stop checkEmailTask"); for (const auto& thread: m_check_email_threads_) { thread->join(); } LogPrint(eLogInfo, "EmailWorker: checkEmailTask stopped"); return true; } void EmailWorker::startSendEmailTask() { if (started_) { LogPrint(eLogInfo, "EmailWorker: start sendEmailTask"); m_send_email_thread_ = new std::thread([this] { sendEmailTask(); }); } } bool EmailWorker::stopSendEmailTask() { LogPrint(eLogInfo, "EmailWorker: stop sendEmailTask"); if (m_send_email_thread_ && !started_) { m_send_email_thread_->join(); delete m_send_email_thread_; m_send_email_thread_ = nullptr; } LogPrint(eLogInfo, "EmailWorker: sendEmailTask stopped"); return true; } std::vector<std::shared_ptr<pbote::Email>> EmailWorker::check_inbox() { LogPrint(eLogDebug, "EmailWorker: check_inbox: start"); // outbox - plain text packet // ToDo: encrypt all local stored emails std::string outboxPath = pbote::fs::DataDirPath("inbox"); std::vector<std::string> mails_path; auto result = pbote::fs::ReadDir(outboxPath, mails_path); std::vector<std::shared_ptr<pbote::Email>> emails; if (result) { for (const auto &mail_path: mails_path) { // read mime packet std::ifstream file(mail_path, std::ios::binary); std::vector<uint8_t> bytes((std::istreambuf_iterator<char>(file)), (std::istreambuf_iterator<char>())); file.close(); pbote::Email mailPacket; mailPacket.fromMIME(bytes); if (mailPacket.length() > 0) { LogPrint(eLogDebug, "EmailWorker: check_inbox: file loaded: ", mail_path); } else { LogPrint(eLogWarning, "EmailWorker: check_inbox: can't read file: ", mail_path); continue; } // ToDo: check signature and set header field mailPacket.fillPacket(); mailPacket.filename(mail_path); if (!mailPacket.empty()) { emails.push_back(std::make_shared<pbote::Email>(mailPacket)); } } } LogPrint(eLogDebug, "EmailWorker: check_inbox: found ", emails.size(), " email(s)."); return emails; } std::vector<uint8_t> EmailWorker::decryptData(const std::shared_ptr<pbote::EmailIdentityFull>& identity, uint8_t *enc, size_t elen) { std::vector<uint8_t> data = identity->identity.Decrypt(enc, elen); return data; } std::vector<uint8_t> EmailWorker::encryptData(const std::shared_ptr<pbote::EmailIdentityFull>& identity, uint8_t *data, size_t dlen, const pbote::EmailIdentityPublic &recipient) { std::vector<uint8_t> enc_data = identity->identity.Encrypt(data, dlen, recipient.GetEncryptionPublicKey()); return enc_data; } void EmailWorker::run() { while (started_) { // ToDo: run checkEmailTask for new loaded identities auto new_identities = context.getEmailIdentities(); if (!new_identities.empty()) { email_identities = new_identities; LogPrint(eLogInfo, "EmailWorker: update identities, now: ", email_identities.size()); } else { LogPrint(eLogWarning, "EmailWorker: have no identities for start"); } if (m_check_email_threads_.empty() && started_ && !new_identities.empty()) { LogPrint(eLogDebug, "EmailWorker: checkEmailTask not run, try to start"); startCheckEmailTasks(); } if (!m_send_email_thread_ && started_ && !new_identities.empty()) { LogPrint(eLogDebug, "EmailWorker: sendEmailTask not run, try to start"); startSendEmailTask(); } std::this_thread::sleep_for(std::chrono::seconds(60)); } } void EmailWorker::checkEmailTask(const std::shared_ptr<pbote::EmailIdentityFull> &email_identity) { while (started_) { auto index_packets = retrieveIndex(email_identity); auto local_index_packet = DHT_worker.getIndex(email_identity->identity.GetPublic()->GetIdentHash()); if (!local_index_packet.empty()) { LogPrint(eLogDebug, "EmailWorker: checkEmailTask: ", email_identity->publicName, ": got ", local_index_packet.size(), " local index packet(s) for identity"); /// from_net is true, because we save it as is pbote::IndexPacket parsed_local_index_packet; bool parsed = parsed_local_index_packet.fromBuffer(local_index_packet, true); if (parsed && parsed_local_index_packet.data.size() == parsed_local_index_packet.nump) { index_packets.push_back(parsed_local_index_packet); } } else { LogPrint(eLogDebug, "EmailWorker: checkEmailTask: ", email_identity->publicName, ": can't find local index packets for identity"); } LogPrint(eLogDebug, "EmailWorker: checkEmailTask: ", email_identity->publicName, ": index count: ", index_packets.size()); auto enc_mail_packets = retrieveEmailPacket(index_packets); LogPrint(eLogDebug, "EmailWorker: checkEmailTask: ", email_identity->publicName, ": mail count: ", enc_mail_packets.size()); if (!enc_mail_packets.empty()) { auto emails = processEmail(email_identity, enc_mail_packets); LogPrint(eLogInfo, "EmailWorker: checkEmailTask: ", email_identity->publicName, ": email(s) processed: ", emails.size()); // ToDo: check mail signature for (auto mail: emails) { mail.save("inbox"); pbote::EmailDeleteRequestPacket delete_email_packet; auto email_packet = mail.getDecrypted(); memcpy(delete_email_packet.DA, email_packet.DA, 32); auto enc_email_packet = mail.getEncrypted(); memcpy(delete_email_packet.key, enc_email_packet.key, 32); i2p::data::Tag<32> email_dht_key(enc_email_packet.key); i2p::data::Tag<32> email_del_auth(email_packet.DA); // We need to remove all received email packets // ToDo: check status of responses DHT_worker.deleteEmail(email_dht_key, DataE, delete_email_packet); // Delete index packets // ToDo: add multipart email support DHT_worker.deleteIndexEntry(email_identity->identity.GetPublic()->GetIdentHash(), email_dht_key, email_del_auth); } } else { LogPrint(eLogDebug, "EmailWorker: checkEmailTask: ", email_identity->publicName, ": have no emails for process"); } // ToDo: check sent emails status // if nodes sent empty response - mark as deleted (delivered) LogPrint(eLogInfo, "EmailWorker: checkEmailTask: ", email_identity->publicName, ": Round complete"); // ToDo: read interval parameter from config std::this_thread::sleep_for(std::chrono::seconds(CHECK_EMAIL_INTERVAL)); } } void EmailWorker::incompleteEmailTask() { // ToDo: need to implement for multipart mail packets } void EmailWorker::sendEmailTask() { while (started_) { // compress packet with LZMA/ZLIB // ToDo: don't forget, for tests sent uncompressed //for (auto packet : emailPackets) // lzmaCompress(packet.data, packet.data); // ToDo: slice big packet after compress std::vector<std::string> nodes; auto outbox = checkOutbox(); if (!outbox.empty()) { // Create Encrypted Email Packet for (const auto &email: outbox) { // ToDo: move to function pbote::EmailEncryptedPacket enc_packet; auto packet = email->getDecrypted(); // Get hash of Delete Auth LogPrint(eLogDebug, "EmailWorker: sendEmailTask: Get hash of Delete Auth"); SHA256(packet.DA, 32, enc_packet.delete_hash); i2p::data::Tag<32> del_hash(enc_packet.delete_hash); LogPrint(eLogDebug, "EmailWorker: sendEmailTask: del_hash: ", del_hash.ToBase64()); email->setField("X-I2PBote-Delete-Auth-Hash", del_hash.ToBase64()); // Create recipient pbote::EmailIdentityPublic recipient_identity; std::string to_address = email->getToAddresses(); LogPrint(eLogDebug, "EmailWorker: sendEmailTask: to_address: ", to_address); // Add zeros to beginning std::string cryptoPubKey = "A" + to_address.substr(0, 43); std::string signingPubKey = "A" + to_address.substr(43, 43); to_address = cryptoPubKey + signingPubKey; if (recipient_identity.FromBase64(to_address) == 0) { LogPrint(eLogWarning, "EmailWorker: sendEmailTask: Can't create identity from \"TO\" header, skip mail"); email->skip(true); continue; } LogPrint(eLogDebug, "EmailWorker: sendEmailTask: email: recipient hash: ", recipient_identity.GetIdentHash().ToBase64()); // Get FROM identity auto from_name = email->field("From"); auto identity_name = from_name.substr(0, from_name.find(' ')); auto identity = pbote::context.identityByName(identity_name); // ToDo: sign email if (!identity) { if (!email_identities.empty()) { LogPrint(eLogWarning, "EmailWorker: sendEmailTask: Can't find identity with name: ", identity_name, ", we can use any other for encrypt data."); identity = email_identities[0]; } else { LogPrint(eLogError, "EmailWorker: sendEmailTask: Have no identities, stopping send task"); stopSendEmailTask(); } } // Encrypt data LogPrint(eLogDebug, "EmailWorker: sendEmailTask: Encrypt data"); LogPrint(eLogDebug, "EmailWorker: sendEmailTask: packet.data.size: ", packet.data.size()); auto packet_bytes = packet.toByte(); enc_packet.edata = encryptData(identity, packet_bytes.data(), packet_bytes.size(), recipient_identity); enc_packet.length = enc_packet.edata.size(); LogPrint(eLogDebug, "EmailWorker: sendEmailTask: enc_packet.edata.size(): ", enc_packet.edata.size()); // ToDo: for now only supported ECDH-256 / ECDSA-256 enc_packet.alg = 2; enc_packet.stored_time = 0; // Get hash of data + length for DHT key LogPrint(eLogDebug, "EmailWorker: sendEmailTask: Get hash of data + length for DHT key"); uint8_t data_for_hash[2 + enc_packet.edata.size()]; uint8_t v_length[2] = {static_cast<uint8_t>(enc_packet.length >> 8), static_cast<uint8_t>(enc_packet.length & 0xff)}; memcpy(data_for_hash, &v_length, 2); memcpy(data_for_hash + 2, enc_packet.edata.data(), enc_packet.edata.size()); SHA256(data_for_hash, 2 + enc_packet.edata.size(), enc_packet.key); i2p::data::Tag<32> dht_key(enc_packet.key); LogPrint(eLogDebug, "EmailWorker: sendEmailTask: dht_key : ", dht_key.ToBase64()); email->setField("X-I2PBote-DHT-Key", dht_key.ToBase64()); LogPrint(eLogDebug, "EmailWorker: sendEmailTask: enc_packet.length : ", enc_packet.length); // hton for hash because recipient will check hash before ntoh uint32_t test_time; uint8_t v_time[4] = {static_cast<uint8_t>(enc_packet.stored_time >> 24), static_cast<uint8_t>(enc_packet.stored_time >> 16), static_cast<uint8_t>(enc_packet.stored_time >> 8), static_cast<uint8_t>(enc_packet.stored_time & 0xffff)}; std::memcpy(&test_time, v_time, 4); uint16_t test_len; memcpy(&test_len, &v_length, 2); email->setEncrypted(enc_packet); } // Store Encrypted Email Packet for (const auto &email: outbox) { // ToDo: move to function if (email->skip()) { continue; } LogPrint(eLogDebug, "EmailWorker: sendEmailTask: Create Store Request packet"); pbote::StoreRequestPacket store_packet; // For now, it's not checking from Java-Bote side store_packet.hashcash = email->getHashCash(); store_packet.hc_length = store_packet.hashcash.size(); LogPrint(eLogDebug, "EmailWorker: sendEmailTask: store_packet.hc_length: ", store_packet.hc_length); store_packet.length = email->getEncrypted().toByte().size(); store_packet.data = email->getEncrypted().toByte(); LogPrint(eLogDebug, "EmailWorker: sendEmailTask: store_packet.length: ", store_packet.length); // Send Store Request with Encrypted Email Packet to nodes LogPrint(eLogDebug, "EmailWorker: sendEmailTask: Send Store Request with Encrypted Email Packet to nodes"); // ToDo: check response status nodes = DHT_worker.store(i2p::data::Tag<32>(email->getEncrypted().key), email->getEncrypted().type, store_packet); DHT_worker.safe(email->getEncrypted().toByte()); LogPrint(eLogDebug, "EmailWorker: sendEmailTask: Email send to ", nodes.size(), " node(s)"); } // Create and store Index Packet for (const auto &email: outbox) { // ToDo: move to function if (email->skip()) { continue; } pbote::IndexPacket new_index_packet; // Create recipient // ToDo: re-use from previous step pbote::EmailIdentityPublic recipient_identity; std::string to_address = email->getToAddresses(); LogPrint(eLogDebug, "EmailWorker: sendEmailTask: to_address: ", to_address); // Add zeros to beginning std::string cryptoPubKey = "A" + to_address.substr(0, 43); std::string signingPubKey = "A" + to_address.substr(43, 43); to_address = cryptoPubKey + signingPubKey; if (recipient_identity.FromBase64(to_address) == 0) { LogPrint(eLogWarning, "EmailWorker: sendEmailTask: Can't create identity from \"TO\" header, skip mail"); email->skip(true); continue; } LogPrint(eLogDebug, "EmailWorker: sendEmailTask: index recipient hash: ", recipient_identity.GetIdentHash().ToBase64()); memcpy(new_index_packet.hash, recipient_identity.GetIdentHash().data(), 32); // ToDo: for test, need to rewrite new_index_packet.nump = 1; //for (const auto &email : encryptedEmailPackets) { pbote::IndexPacket::Entry entry{}; memcpy(entry.key, email->getEncrypted().key, 32); memcpy(entry.dv, email->getEncrypted().delete_hash, 32); auto unix_timestamp = std::chrono::seconds(std::time(nullptr)); auto value = std::chrono::duration_cast<std::chrono::seconds>(unix_timestamp); entry.time = value.count(); new_index_packet.data.push_back(entry); //} pbote::StoreRequestPacket store_index_packet; // For now it's not checking from Java-Bote side store_index_packet.hashcash = email->getHashCash(); store_index_packet.hc_length = store_index_packet.hashcash.size(); LogPrint(eLogDebug, "EmailWorker: sendEmailTask: store_index_packet.hc_length: ", store_index_packet.hc_length); auto index_packet = new_index_packet.toByte(); store_index_packet.length = index_packet.size(); store_index_packet.data = index_packet; // send Store Request with Index Packet to nodes // ToDo: check response status nodes = DHT_worker.store(recipient_identity.GetIdentHash(), new_index_packet.type, store_index_packet); DHT_worker.safe(new_index_packet.toByte()); LogPrint(eLogDebug, "EmailWorker: sendEmailTask: Index send to ", nodes.size(), " node(s)"); } for (const auto &email: outbox) { // ToDo: move to function if (email->skip()) { continue; } email->setField("X-I2PBote-Deleted", "false"); // Write new metadata before move file to sent email->save(""); email->move("sent"); } } // ToDo: read interval parameter from config LogPrint(eLogInfo, "EmailWorker: sendEmailTask: Round complete"); std::this_thread::sleep_for(std::chrono::seconds(SEND_EMAIL_INTERVAL)); } } std::vector<pbote::IndexPacket> EmailWorker::retrieveIndex(const std::shared_ptr<pbote::EmailIdentityFull> &identity) { auto identity_hash = identity->identity.GetPublic()->GetIdentHash(); LogPrint(eLogDebug, "EmailWorker: retrieveIndex: Try to find index for: ", identity_hash.ToBase64()); // Use findAll rather than findOne because some peers might have an incomplete set of // Email Packet keys, and because we want to send IndexPacketDeleteRequests to all of them. auto results = DHT_worker.findAll(identity_hash, DataI); if (results.empty()) { LogPrint(eLogWarning, "EmailWorker: retrieveIndex: can't find index for: ", identity_hash.ToBase64()); return {}; } std::map<i2p::data::Tag<32>, pbote::IndexPacket> index_packets; // retrieve index packets for (const auto &response: results) { if (response->type != type::CommN) { // ToDo: looks like in case if we got request to ourself, for now we just skip it LogPrint(eLogWarning, "EmailWorker: retrieveIndex: got non-response packet in batch, type: ", response->type, ", ver: ", unsigned(response->ver)); continue; } LogPrint(eLogDebug, "EmailWorker: retrieveIndex: got response from: ", response->from); size_t offset = 0; uint8_t status; uint16_t dataLen; std::memcpy(&status, response->payload.data(), 1); offset += 1; std::memcpy(&dataLen, response->payload.data() + offset, 2); offset += 2; dataLen = ntohs(dataLen); if (status != StatusCode::OK) { LogPrint(eLogWarning, "EmailWorker: retrieveIndex: response status: ", statusToString(status)); continue; } if (dataLen < 4) { LogPrint(eLogWarning, "EmailWorker: retrieveIndex: packet without payload, skip parsing"); continue; } std::vector<uint8_t> v_data(response->payload.begin() + offset, response->payload.begin() + offset + dataLen); if (DHT_worker.safe(v_data)) LogPrint(eLogDebug, "EmailWorker: retrieveIndex: save index packet locally"); pbote::IndexPacket index_packet; bool parsed = index_packet.fromBuffer(v_data, true); if (parsed && !index_packet.data.empty()) { i2p::data::Tag<32> hash(index_packet.hash); index_packets.insert(std::pair<i2p::data::Tag<32>, pbote::IndexPacket>(hash, index_packet)); } else LogPrint(eLogWarning, "EmailWorker: retrieveIndex: index packet without entries"); } LogPrint(eLogDebug, "EmailWorker: retrieveIndex: ", index_packets.size(), " index packets parsed"); std::vector<pbote::IndexPacket> res; res.reserve(index_packets.size()); for (const auto &packet: index_packets) res.push_back(packet.second); // save index packets for interrupt case // ToDo: check if we have packet locally and sent delete request now return res; } std::vector<pbote::EmailEncryptedPacket> EmailWorker::retrieveEmailPacket(const std::vector<pbote::IndexPacket> &index_packets) { // retrieve mail packets std::vector<std::shared_ptr<pbote::CommunicationPacket>> responses; std::vector<pbote::EmailEncryptedPacket> local_email_packets; for (const auto &index: index_packets) { for (auto entry: index.data) { i2p::data::Tag<32> hash(entry.key); auto local_email_packet = DHT_worker.getEmail(hash); if (!local_email_packet.empty()) { LogPrint(eLogDebug, "EmailWorker: retrieveEmailPacket: got local encrypted email for key:", hash.ToBase64()); pbote::EmailEncryptedPacket parsed_local_email_packet; bool parsed = parsed_local_email_packet.fromBuffer(local_email_packet.data(), local_email_packet.size(), true); if (parsed && !parsed_local_email_packet.edata.empty()) { local_email_packets.push_back(parsed_local_email_packet); } } else { LogPrint(eLogDebug, "EmailWorker: retrieveEmailPacket: can't find local encrypted email for key:", hash.ToBase64()); } auto temp_results = DHT_worker.findAll(hash, DataE); responses.insert(responses.end(), temp_results.begin(), temp_results.end()); } } LogPrint(eLogDebug, "EmailWorker: retrieveEmailPacket: ", responses.size(), " response packets received"); std::map<i2p::data::Tag<32>, pbote::EmailEncryptedPacket> mail_packets; for (const auto &response: responses) { if (response->type != type::CommN) { // ToDo: looks like in case if we got request to ourself, for now we just skip it LogPrint(eLogWarning, "EmailWorker: retrieveIndex: got non-response packet in batch, type: ", response->type, ", ver: ", unsigned(response->ver)); continue; } size_t offset = 0; uint8_t status; uint16_t dataLen; std::memcpy(&status, response->payload.data(), 1); offset += 1; std::memcpy(&dataLen, response->payload.data() + offset, 2); offset += 2; dataLen = ntohs(dataLen); if (status != StatusCode::OK) { LogPrint(eLogWarning, "EmailWorker: retrieveEmailPacket: response status: ", statusToString(status)); continue; } if (dataLen == 0) { LogPrint(eLogWarning, "EmailWorker: retrieveEmailPacket: packet without payload, skip parsing"); continue; } LogPrint(eLogDebug, "EmailWorker: retrieveEmailPacket: got email packet, payload size: ", dataLen); uint8_t data[dataLen]; std::memcpy(&data, response->payload.data() + offset, dataLen); std::vector<uint8_t> v_data(response->payload.begin() + offset, response->payload.begin() + offset + dataLen); if (DHT_worker.safe(v_data)) LogPrint(eLogDebug, "EmailWorker: retrieveEmailPacket: save encrypted email packet locally"); pbote::EmailEncryptedPacket parsed_packet; bool parsed = parsed_packet.fromBuffer(data, dataLen, true); if (parsed && !parsed_packet.edata.empty()) { i2p::data::Tag<32> hash(parsed_packet.key); mail_packets.insert(std::pair<i2p::data::Tag<32>, pbote::EmailEncryptedPacket>(hash, parsed_packet)); } else LogPrint(eLogWarning, "EmailWorker: retrieveEmailPacket: mail packet without entries"); } LogPrint(eLogDebug, "EmailWorker: retrieveEmailPacket: parsed mail packets: ", mail_packets.size()); for (auto local_packet: local_email_packets) { i2p::data::Tag<32> hash(local_packet.key); mail_packets.insert(std::pair<i2p::data::Tag<32>, pbote::EmailEncryptedPacket>(hash, local_packet)); } LogPrint(eLogDebug, "EmailWorker: retrieveEmailPacket: mail packets: ", mail_packets.size()); std::vector<pbote::EmailEncryptedPacket> res; res.reserve(mail_packets.size()); for (const auto &packet: mail_packets) res.push_back(packet.second); // save encrypted email packets for interrupt case // ToDo: check if we have packet locally and sent delete request now return res; } std::vector<pbote::EmailUnencryptedPacket> EmailWorker::loadLocalIncompletePacket() { // ToDo: just for tests, need to implement // ToDo: move to ? /*std::string indexPacketPath = pbote::fs::DataDirPath("incomplete"); std::vector<std::string> packets_path; std::vector<pbote::EmailUnencryptedPacket> indexPackets; auto result = pbote::fs::ReadDir(indexPacketPath, packets_path); if (result) { for (const auto &packet_path : packets_path) { std::ifstream file(packet_path, std::ios::binary); std::vector<uint8_t> bytes((std::istreambuf_iterator<char>(file)), (std::istreambuf_iterator<char>())); file.close(); auto indexPacket = parseEmailUnencryptedPkt(bytes.data(), bytes.size(), false); if (!indexPacket.data.empty()) indexPackets.push_back(indexPacket); } LogPrint(eLogDebug, "Email: loadLocalIndex: loaded index files: ", indexPackets.size()); return indexPackets; } LogPrint(eLogWarning, "Email: loadLocalIndex: have no index files");*/ return {}; } std::vector<std::shared_ptr<pbote::Email>> EmailWorker::checkOutbox() { LogPrint(eLogDebug, "EmailWorker: checkOutbox: start"); // outbox - plain text packet // ToDo: encrypt all local stored emails std::string outboxPath = pbote::fs::DataDirPath("outbox"); std::vector<std::string> mails_path; auto result = pbote::fs::ReadDir(outboxPath, mails_path); std::vector<std::shared_ptr<pbote::Email>> emails; if (result) { for (const auto &mail_path: mails_path) { // read mime packet std::ifstream file(mail_path, std::ios::binary); std::vector<uint8_t> bytes((std::istreambuf_iterator<char>(file)), (std::istreambuf_iterator<char>())); file.close(); pbote::Email mailPacket; mailPacket.fromMIME(bytes); if (mailPacket.length() > 0) { LogPrint(eLogDebug, "EmailWorker: checkOutbox: file loaded: ", mail_path); } else { LogPrint(eLogWarning, "EmailWorker: checkOutbox: can't read file: ", mail_path); continue; } mailPacket.filename(mail_path); // ToDo: need to simplify /// Check if if FROM and TO fields have valid public names, else /// Check if <name@domain> in AddressBook for replacement /// if not found - log warning and skip /// if replaced - save modified email to file to keep changes std::string from_address = mailPacket.field("From"); std::string to_address = mailPacket.field("To"); if (from_address.empty() || to_address.empty()) { LogPrint(eLogWarning, "EmailWorker: checkOutbox: FROM or TO field are empty"); continue; } bool changed = false; std::string et_char("@"), less_char("<"); size_t from_less_pos = from_address.find(less_char); if (from_less_pos != std::string::npos) { LogPrint(eLogDebug, "EmailWorker: checkOutbox: try to replace FROM: ", from_address); std::string old_from_address = from_address; std::string pub_name = from_address.substr(0, from_less_pos - 1); from_address.erase(0, from_less_pos + 1); size_t from_et_pos = from_address.find(et_char); std::string alias_name = from_address.substr(0, from_et_pos); auto pub_from_identity = context.identityByName(pub_name); auto alias_from_identity = context.identityByName(alias_name); if (!pub_from_identity && !alias_from_identity) { LogPrint(eLogWarning, "EmailWorker: checkOutbox: can't find address for name:", pub_name, ", alias: ", alias_name); continue; } std::string new_from; if (pub_from_identity) { std::string pub_str = pub_from_identity->full_key.substr(0, 86); new_from.append( pub_from_identity->publicName + " <" + pub_str + ">"); } else if (alias_from_identity) { std::string alias_str = alias_from_identity->full_key.substr(0, 86); new_from.append( alias_from_identity->publicName + " <" + alias_str + ">"); } else { LogPrint(eLogError, "EmailWorker: checkOutbox: unknown error, name:", pub_name, ", alias: ", alias_name); continue; } LogPrint(eLogDebug, "EmailWorker: checkOutbox: FROM replaced, old: ", old_from_address, ", new: ", new_from); mailPacket.setField("From", new_from); changed = true; } // Now replace TO size_t to_less_pos = to_address.find(less_char); if (to_less_pos != std::string::npos) { LogPrint(eLogDebug, "EmailWorker: checkOutbox: try to replace TO: ", to_address); std::string old_to_address = to_address; std::string pub_name = to_address.substr(0, to_less_pos - 1); to_address.erase(0, to_less_pos + 1); size_t to_et_pos = to_address.find(et_char); std::string alias_name = to_address.substr(0, to_et_pos); auto pub_to_address = context.address_for_name(pub_name); auto alias_to_address = context.address_for_alias(alias_name); if (pub_to_address.empty() && alias_to_address.empty()) { LogPrint(eLogWarning, "EmailWorker: checkOutbox: can't find address for ", to_address); continue; } std::string new_to; if (!pub_to_address.empty()) { new_to.append(pub_name + " <" +pub_to_address + ">"); } else if (!alias_to_address.empty()) { new_to.append(alias_name + " <" + pub_to_address + ">"); } else { LogPrint(eLogError, "EmailWorker: checkOutbox: unknown error, name:", pub_name, ", alias: ", alias_name); continue; } LogPrint(eLogDebug, "EmailWorker: checkOutbox: TO replaced, old: ", old_to_address, ", new: ", new_to); mailPacket.setField("To", new_to); changed = true; } if (changed) mailPacket.save(""); mailPacket.fillPacket(); // ToDo: compress mailPacket.compress(pbote::Email::CompressionAlgorithm::UNCOMPRESSED); if (!mailPacket.empty()) { emails.push_back(std::make_shared<pbote::Email>(mailPacket)); } } } LogPrint(eLogDebug, "EmailWorker: checkOutbox: found ", emails.size(), " email(s) for send."); return emails; } std::vector<pbote::Email> EmailWorker::processEmail(const std::shared_ptr<pbote::EmailIdentityFull>& identity, const std::vector<pbote::EmailEncryptedPacket> &mail_packets) { // ToDo: move to incompleteEmailTask? LogPrint(eLogDebug, "EmailWorker: processEmail: emails for process: ", mail_packets.size()); std::vector<pbote::Email> emails; for (auto enc_mail: mail_packets) { std::vector<uint8_t> unencrypted_email_data; if (!enc_mail.edata.empty()) unencrypted_email_data = decryptData(identity, enc_mail.edata.data(), enc_mail.edata.size()); if (!unencrypted_email_data.empty()) { pbote::Email temp_mail(unencrypted_email_data, true); if (!temp_mail.verify(enc_mail.delete_hash)) { i2p::data::Tag<32> cur_hash(enc_mail.delete_hash); LogPrint(eLogError, "EmailWorker: processEmail: email ", cur_hash.ToBase32(), " is unequal"); continue; } temp_mail.setEncrypted(enc_mail); if (!temp_mail.empty()) { emails.push_back(temp_mail); } } } LogPrint(eLogDebug, "EmailWorker: processEmail: processed emails: ", emails.size()); return emails; } } // namespace kademlia } // namespace pbote
38.98549
129
0.658075
[ "object", "vector" ]
1529631d5ec1e7bac8055be0f75c1a437e3d9d7f
5,819
cc
C++
src/relay/transforms/combine_parallel_batch_matmul.cc
jiangzoi/incubator-tvm
144c6f45f7217b9df2f5605e06f0903e470ac11c
[ "Apache-2.0" ]
4
2019-05-08T04:46:07.000Z
2019-11-11T19:43:04.000Z
src/relay/transforms/combine_parallel_batch_matmul.cc
jiangzoi/incubator-tvm
144c6f45f7217b9df2f5605e06f0903e470ac11c
[ "Apache-2.0" ]
1
2020-07-29T07:29:17.000Z
2020-07-29T07:29:17.000Z
src/relay/transforms/combine_parallel_batch_matmul.cc
jiangzoi/incubator-tvm
144c6f45f7217b9df2f5605e06f0903e470ac11c
[ "Apache-2.0" ]
2
2019-08-08T01:48:03.000Z
2019-09-27T06:49:16.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * * \file combine_parallel_batch_matmul.cc * \brief Combine parallel batch matmuls into a single one. * * This pass replaces batch_matmul that share the same lhs node with a * single batch matmul.Elemwise and broadcast ops following batch_matmul are also * combined if possible. * * This prevents launching multiple kernels in networks with multiple * convolution branches, such as Inception block. */ #include <tvm/relay/analysis.h> #include <tvm/relay/attrs/nn.h> #include <tvm/relay/attrs/transform.h> #include <tvm/relay/expr_functor.h> #include <tvm/relay/op_attr_types.h> #include <tvm/relay/transform.h> #include <unordered_map> #include <unordered_set> #include "./combine_parallel_op.h" #include "./expr_subst.h" #include "pattern_util.h" namespace tvm { namespace relay { class ParallelBatchMatmulCombiner : public ParallelOpCombiner { public: explicit ParallelBatchMatmulCombiner(uint64_t min_num_branches) : ParallelOpCombiner("nn.batch_matmul", min_num_branches) {} protected: bool IsSupportedOp(const CallNode* n) { return true; } bool CanOpsBeCombined(const CallNode* a, const CallNode* b) { StructuralEqual eq; const auto* rhs_a = a->args[1]->type_as<TensorTypeNode>(); const auto* rhs_b = b->args[1]->type_as<TensorTypeNode>(); const auto* restype_a = a->type_as<TensorTypeNode>(); const auto* restype_b = b->type_as<TensorTypeNode>(); // shape[2] is the contraction axis and automatically consistent // if it were valid batch_matmul ops auto res = eq(rhs_a->dtype, rhs_b->dtype) && eq(restype_a->dtype, restype_b->dtype) && (rhs_a->shape.size() == 3) && (rhs_b->shape.size() == 3) && eq(rhs_a->shape[0], rhs_b->shape[0]); return res; } Call MakeCombinedOp(const Group& branches) { const Op& batch_matmul = Op::Get("nn.batch_matmul"); Expr data = branches[0][0]->args[0]; Array<Expr> weights; for (const auto& branch : branches) { auto batch_matmul = branch[0]; weights.push_back(batch_matmul->args[1]); } Expr new_weight = MakeConcatenate(Tuple(weights), 1); return Call(batch_matmul, {data, new_weight}, {}, {}); } bool IsArgCompatible(const CallNode* a, const CallNode* b, size_t index) { return true; } Call MakeCombinedCallFromFollowingOps(const Expr& data, const Group& branches, size_t depth, size_t parent_index) { Array<Expr> new_args; const CallNode* call = branches[0][depth]; for (size_t i = 0; i < call->args.size(); i++) { if (i == parent_index) { new_args.push_back(data); continue; } Array<Expr> tuple; for (const auto& branch : branches) { tuple.push_back(branch[depth]->args[i]); } auto concat = MakeConcatenate(Tuple(tuple), -1); new_args.push_back(std::move(concat)); } return Call(call->op, new_args, call->attrs, {}); } void UpdateGroupOutput(const Expr& data, const Group& branches, size_t depth, ExprSubstMap* subst_map) { int64_t index = 0; for (const auto& branch : branches) { const CallNode* batch_matmul = branch[0]; auto feature_dim = batch_matmul->args[1]->type_as<TensorTypeNode>()->shape[1]; auto fpp = tir::as_const_int(feature_dim); int64_t features = *fpp; std::vector<int64_t> begin; std::vector<int64_t> end; for (size_t i = 0; i < 2; i++) { begin.push_back(0); end.push_back(-1); } begin.push_back(index); index += features; end.push_back(features); std::vector<int64_t> strides(begin.size(), 1); std::vector<int64_t> ndarray_shape = {static_cast<int64_t>(begin.size())}; Constant begin_const = MakeConstantTensor(DataType::Int(64), ndarray_shape, begin); Constant end_const = MakeConstantTensor(DataType::Int(64), ndarray_shape, end); Constant strides_const = MakeConstantTensor(DataType::Int(64), ndarray_shape, strides); auto slice = MakeStridedSlice(data, begin_const, end_const, strides_const, "size"); subst_map->insert({GetRef<Expr>(branch[depth]), slice}); } } }; /*! \brief Combine parallel batch_matmul if number of branches >= min_num_branches */ Expr CombineParallelBatchMatmul(const Expr& expr, uint64_t min_num_branches) { return ParallelBatchMatmulCombiner(min_num_branches).Combine(expr); } namespace transform { Pass CombineParallelBatchMatmul(uint64_t min_num_branches) { runtime::TypedPackedFunc<Function(Function, IRModule, PassContext)> pass_func = [=](Function f, IRModule m, PassContext pc) { return Downcast<Function>(CombineParallelBatchMatmul(f, min_num_branches)); }; return CreateFunctionPass(pass_func, 4, "CombineParallelBatchMatmul", {"InferType"}); } TVM_REGISTER_GLOBAL("relay._transform.CombineParallelBatchMatmul") .set_body_typed(CombineParallelBatchMatmul); } // namespace transform } // namespace relay } // namespace tvm
36.142857
94
0.692043
[ "shape", "vector", "transform" ]
152def18d4394da868677423502e7e62644aab76
6,388
cpp
C++
test/example1.cpp
tevaughan/units
75e5cfa76a44225983ca55f2a54e0869ff7b3715
[ "BSD-3-Clause" ]
null
null
null
test/example1.cpp
tevaughan/units
75e5cfa76a44225983ca55f2a54e0869ff7b3715
[ "BSD-3-Clause" ]
4
2019-04-17T21:36:00.000Z
2019-04-30T22:06:31.000Z
test/example1.cpp
tevaughan/units
75e5cfa76a44225983ca55f2a54e0869ff7b3715
[ "BSD-3-Clause" ]
null
null
null
/// @copyright 2019 Thomas E. Vaughan; all rights reserved. /// @license BSD three-clause; see LICENSE. #include <array> // for array #include <eigen3/Eigen/Geometry> // for AngleAxis, Matrix, etc. #include <iostream> // for cout, etc. #include <type_traits> // for remove_const #include <utility> // for index_sequence #include <vnix/units.hpp> using std::array; using std::cerr; using std::cout; using std::endl; using std::index_sequence; using std::make_index_sequence; using std::ostream; namespace vnix { namespace mv { /// Convert element i of array a from type OT to type T. template <typename T, typename OT, size_t N> constexpr T cnv_el(array<OT, N> const &a, size_t i) { return a[i]; } /// Convert array of elements of type OT to array of elements of type T. template <typename T, typename OT, size_t... i> constexpr auto _cnv(array<OT, sizeof...(i)> const &a, index_sequence<i...>) { return array<T, sizeof...(i)>{{cnv_el<T>(a, i)...}}; } /// Convert array of elements of type OT to array of elements of type T. template <typename T, typename OT, size_t N> constexpr auto cnv_ar(array<OT, N> const &a) { return _cnv<T>(a, make_index_sequence<N>{}); } /// Reference to column or row in matrix. template <typename T, size_t S, size_t N> class mref { T *beg_; ///< Pointer to first element. public: constexpr mref(T *b) : beg_(b) {} ///< Initialize aggregate. constexpr static size_t size() { return N; } ///< Number of elements. constexpr T * begin() { return beg_; } ///< First element. /// Pointer to element that is S elements past last element identified by /// mref. constexpr T *end() { return beg_ + S * N; } /// Assign from list. constexpr mref &operator=(std::initializer_list<T> list) { auto i = list.begin(); auto j = begin(); auto ie = list.end(); auto je = end(); while (i != ie && j != je) { *j++ = *i; i += S; } return *this; } /// Distance in memory between successive elements. constexpr static size_t stride() { return S; } /// Access element at offset off. constexpr T &operator()(size_t off) const { return beg_[S * off]; } }; /// Dot-product of two mrefs. template <typename T1, typename T2, size_t S1, size_t S2, size_t N> constexpr auto dot(mref<T1, S1, N> const &mr1, mref<T2, S2, N> const &mr2) { auto sum = 0 * mr1(0) * mr2(0); for (size_t i = 0; i < N; ++i) { sum += mr1(i) * mr2(i); } return sum; } /// Model of a matrix of quantities. template <typename T, size_t NR, size_t NC> struct mat { array<T, NR * NC> a; ///< Array in which quantities are stored. /// Allow access to every other type of matrix. template <typename OT, size_t ONR, size_t ONC> friend struct mat; mat() {} /// Initialize from list. template <typename... X> constexpr mat(X... xs) : a({T(xs)...}) {} /// Copy from same-size matrix of other element-type OT. template <typename OT> constexpr mat(mat<OT, NR, NC> const &m) : a(cnv_ar<T>(m.a)) {} /// Reference to immutable column. constexpr auto col(size_t off) const { return mref<T const, NC, NR>(a.data() + off); } /// Reference to mutable column. constexpr auto col(size_t off) { using RT = typename std::remove_const<T>::type; return mref<RT, NC, NR>(a.data() + off); } /// Reference to immutable row. constexpr auto row(size_t off) const { return mref<T const, 1, NC>(a.data() + NC * off); } /// Reference to mutable row. constexpr auto row(size_t off) { using RT = typename std::remove_const<T>::type; return mref<RT, 1, NC>(a.data() + NC * off); } }; /// Model of column of quantities. template <typename T, size_t NR> using col = mat<T, NR, 1>; /// Model of row of quantities. template <typename T, size_t NC> using row = mat<T, 1, NC>; /// Multiply two matrices. template <typename T1, typename T2, size_t NR1, size_t NC2, size_t N> constexpr auto operator*(mat<T1, NR1, N> const &m1, mat<T2, N, NC2> const &m2) { using TT = decltype(dot(m1.row(0), m2.col(0))); using TP = typename std::remove_const<TT>::type; mat<TP, NR1, NC2> pr; // product for (size_t i = 0; i < NR1; ++i) { auto const m1_rowi = m1.row(i); auto pr_rowi = pr.row(i); for (size_t j = 0; j < NC2; ++j) { pr_rowi(j) = dot(m1_rowi, m2.col(j)); } } return pr; } /// Multiply matrix on left by scalar. template <typename T1, typename T2, size_t NR2, size_t NC2> constexpr auto operator*(T1 const &s1, mat<T2, NR2, NC2> const &m2) { mat<decltype(s1 * m2.row(0)(0)), NR2, NC2> pr; // product for (size_t i = 0; i < NR2; ++i) { auto const m2_rowi = m2.row(i); auto pr_rowi = pr.row(i); for (size_t j = 0; j < NC2; ++j) { pr_rowi(j) = s1 * m2_rowi(j); } } return pr; } /// Print matrix. template <typename T, size_t NR, size_t NC> ostream &operator<<(ostream &os, mat<T, NR, NC> const &m) { for (size_t i = 0; i < NR; ++i) { auto const rowi = m.row(i); os << endl; for (size_t j = 0; j < NC; ++j) { os << rowi(j) << " "; } } return os; } } // namespace mv } // namespace vnix int main() { try { using namespace vnix::mv; mat<float, 3, 3> m1; m1.row(0) = {1, 2, 3}; m1.row(1) = {4, 5, 6}; m1.row(2) = {7, 8, 9}; col<double, 3> v({0.3, 0.2, 0.1}); auto f = vnix::units::newtons(m1); auto d = vnix::units::kilometers(v); cout << (f * d) << endl; } catch (char const *e) { cerr << e << endl; } cout << endl; try { using namespace vnix::mv; using namespace vnix::units::flt; force foo; mat<force, 3, 3> f2; f2.row(0) = {1.0_N, 2.0_N, 3.0_N}; f2.row(1) = {4.0_N, 5.0_N, 6.0_N}; f2.row(2) = {7.0_N, 8.0_N, 9.0_N}; col<length, 3> d2({0.3_km, 0.2_km, 0.1_km}); cout << (f2 * d2) << endl; } catch (char const *e) { cerr << e << endl; } cout << endl; try { using namespace Eigen; using namespace vnix::units; using namespace vnix::units::flt; AngleAxisf r(M_PI / 6, Vector3f(0, 0, 1)); auto f = newtons(Vector3f(1, 0, 0)); auto d = meters(Vector3f(0, 1, 0)); auto v = d / (2.5_s); flt::time t = 3.0_s; cout << (r.toRotationMatrix() * f).cross(d + v * t) << endl; } catch (char const *e) { cerr << e << endl; } return 0; }
29.711628
78
0.592674
[ "geometry", "model" ]
1532754620db3ca030e05211ed4818539e010727
1,927
cpp
C++
Source/UncoExample/Private/ExampleBase01.cpp
laycnc/UncoExample
a58d0f9811cc17b4638e0e7e3255fce3fafdddf3
[ "MIT" ]
null
null
null
Source/UncoExample/Private/ExampleBase01.cpp
laycnc/UncoExample
a58d0f9811cc17b4638e0e7e3255fce3fafdddf3
[ "MIT" ]
null
null
null
Source/UncoExample/Private/ExampleBase01.cpp
laycnc/UncoExample
a58d0f9811cc17b4638e0e7e3255fce3fafdddf3
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "ExampleBase01.h" #include "Components/StaticMeshComponent.h" #include "Engine/StaticMesh.h" #include "Kismet/KismetSystemLibrary.h" #include "UncoAsyncSystemLibrary.h" // Sets default values AExampleBase01::AExampleBase01() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; StaticMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("StaticMeshComponent0")); StaticMeshComponent->SetCollisionProfileName( UCollisionProfile::BlockAll_ProfileName); StaticMeshComponent->Mobility = EComponentMobility::Movable; StaticMeshComponent->SetGenerateOverlapEvents(false); StaticMeshComponent->bUseDefaultCollision = true; RootComponent = StaticMeshComponent; } // Called when the game starts or when spawned void AExampleBase01::BeginPlay() { Super::BeginPlay(); // 非同期での初期化を行う AsyncBeginPlay(); } // Called every frame void AExampleBase01::Tick(float DeltaTime) { Super::Tick(DeltaTime); } // 非同期初期化 unco::FObjectTask AExampleBase01::AsyncBeginPlay() { UKismetSystemLibrary::PrintString( this, FString::Printf(TEXT("AsyncDelay:%f"), DelayBeginTime)); // 一定時間待機する co_await unco::AsyncDelay(this, DelayBeginTime); UKismetSystemLibrary::PrintString(this, FString::Printf(TEXT("AsyncDelay Finish"))); UKismetSystemLibrary::PrintString( this, FString::Printf(TEXT("AsyncLoadAsset:%s"), *LoadMeshPath.ToString())); // メッシュの非同期ロードを行う UStaticMesh* Mesh = co_await unco::AsyncLoadAsset(this, LoadMeshPath); if ( !IsValid(Mesh) ) { UKismetSystemLibrary::PrintString(this, TEXT("Load Failed")); co_return; } // ログを出す UKismetSystemLibrary::PrintString(this, TEXT("Load Success")); // 読み込んだメッシュを設定する StaticMeshComponent->SetStaticMesh(Mesh); }
27.528571
114
0.755579
[ "mesh" ]
15396fe90b5c1f352aaaf9ede76d022921098da9
38,852
cpp
C++
net/config/upgrade/netupgrd/infmap.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
net/config/upgrade/netupgrd/infmap.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
net/config/upgrade/netupgrd/infmap.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// ---------------------------------------------------------------------- // // Microsoft Windows NT // Copyright (C) Microsoft Corporation, 1997. // // File: I N F M A P . C P P // // Contents: Functions that work on netmap.inf file. // // Notes: // // Author: kumarp 22-December-97 // // ---------------------------------------------------------------------- #include "pch.h" #pragma hdrstop #include "infmap.h" #include "kkcwinf.h" #include "kkutils.h" #include "ncreg.h" #include "ncsetup.h" #include "netupgrd.h" #include "nustrs.h" #include "nuutils.h" #include "oemupg.h" extern const WCHAR c_szNetUpgradeDll[]; // ----------------------------------------------------------------- // Structure of netmap.inf file // // We use netmap.inf file to map pre-NT5 InfID of a netcard to its // NT5 InfID (PnPID). // // This file has a number of top-level sections. // Each top-level section holds entries for mapping netcards of a particular // bus type. the format of each line is // // <pre-NT5 InfID>=<NT5 InfID> // OR // <pre-NT5 InfID>=<mapping-method-#>,<section-name> // // the former is a 1-1 mapping while the latter offers a way to map a single // preNT5 InfID to multiple InfIDs // // Mapping method 0 // ---------------- // This method is used when a single pre-NT5 InfID represents more than one // net card which means that a single pre-NT5 InfID is mapped onto many // NT5 PnPIDs. The only way to differentiate between the different types of // net cards is to inspect a single value under the parameters key. // // In this mapping method, two keys are required to be specified for // each net card. // - ValueName: this specifies the value to be inspected under the Parameters key // - ValueType: this specifies the type of ValueName // // there can be any number of additional keys in this section. // each such line is of the form // <NT5 InfID>=<some value of type ValueType> // // we first find out the value of ValueName // then we enumerate each key in this section to see if the value matches the // value of any of the keys. // if we find a match, then the name of the found key represents <NT5 InfID> // // e.g. // 5 flavors of the ELNK3MCA card are represented by the same InfID in NT4 // the only way to distinguish between them is to inspect the McaPosId value // for this card we have the mapping section defined as follows: // // [McaAdapters] // ELNK3MCA = 0,ELNK3MCA ; 0 --> mapping method 0 // ... other mca card entries ... // // [ELNK3MCA] // ValueName= McaPosId // ValueType= 4 ; REG_DWORD // mca_627c = 0x0000627c ; if value of McaPosId is 0x627c then PnPID == mca_627c // mca_627d = 0x0000627d // mca_61db = 0x000061db // mca_62f6 = 0x000062f6 // mca_62f7 = 0x000062f7 // // Note: a special keyword "ValueNotPresent" can be used to make a mapping // for the case when a value is not present. // List of sections that can appear in the netmap.inf // const WCHAR c_szIsaAdapters[] = L"IsaAdapters"; const WCHAR c_szEisaAdapters[] = L"EisaAdapters"; const WCHAR c_szPciAdapters[] = L"PciAdapters"; const WCHAR c_szMcaAdapters[] = L"McaAdapters"; const WCHAR c_szPcmciaAdapters[] = L"PcmciaAdapters"; const WCHAR c_szOemNetAdapters[] = L"OemNetAdapters"; const WCHAR c_szAsyncAdapters[] = L"AsyncAdapters"; const WCHAR c_szOemAsyncAdapters[] = L"OemAsyncAdapters"; static PCWSTR g_aszInfMapNetCardSections[] = { c_szIsaAdapters, c_szEisaAdapters, c_szPciAdapters, c_szMcaAdapters, c_szPcmciaAdapters, c_szOemNetAdapters, c_szAsyncAdapters, c_szOemAsyncAdapters }; const BYTE g_cNumNetCardSections = celems(g_aszInfMapNetCardSections); const WCHAR c_szNetProtocols[] = L"NetProtocols"; const WCHAR c_szOemNetProtocols[] = L"OemNetProtocols"; const WCHAR c_szNetServices[] = L"NetServices"; const WCHAR c_szOemNetServices[] = L"OemNetServices"; const WCHAR c_szNetClients[] = L"NetClients"; const WCHAR c_szOemNetClients[] = L"OemNetClients"; const WCHAR c_szOemUpgradeSupport[] = L"OemUpgradeSupport"; // value in netmap.inf indicating the absence of a value in the registry // const WCHAR c_szValueNotPresent[] = L"ValueNotPresent"; // ---------------------------------------------------------------------- // prototypes // HRESULT HrMapPreNT5InfIdToNT5InfIdInSection(IN HINF hinf, IN HKEY hkeyAdapterParams, IN PCWSTR pszSectionName, IN PCWSTR pszPreNT5InfId, OUT tstring* pstrNT5InfId, OUT BOOL* pfOemComponent); HRESULT HrMapPreNT5InfIdToNT5InfIdUsingMethod0(IN HKEY hkeyAdapterParams, IN HINF hInf, IN PCWSTR pszAdapterSection, OUT tstring* pstrNT5InfId); HRESULT HrSetupFindKeyWithStringValue(IN HINF hInf, IN PCWSTR pszSection, IN PCWSTR pszValue, OUT tstring* pstrKey); // ---------------------------------------------------------------------- #pragma BEGIN_CONST_SECTION const WCHAR c_szNetMapInf[] = L"netmap.inf"; const WCHAR c_szKeyValueName[] = L"ValueName"; const WCHAR c_szKeyValueType[] = L"ValueType"; const WCHAR c_szInfId_MS_ATMUNI[] = L"MS_ATMUNI"; const WCHAR c_szInfId_MS_ATMARPS[] = L"MS_ATMARPS"; #pragma END_CONST_SECTION //+--------------------------------------------------------------------------- // // Function: HrMapPreNT5NetCardInfIdInInf // // Purpose: Maps using hinf, pre-NT5 InfID of a net card to its NT5 equivalent // // Arguments: // hinf [in] handle of netmap.inf file // hkeyAdapterParams [in] handle to Parameters key under the netcard driver key // pszPreNT5InfId [in] pre-NT5 InfID // pstrNT5InfId [out] NT5 InfID // pstrAdapterType [out] section in which the map was found // pfOemComponent [out] set to TRUE if it is an OEM card // // Returns: S_OK if found, S_FALSE if not, // otherwise HRESULT_FROM_WIN32 error code. // // Author: kumarp 24-July-97 // // Notes: // HRESULT HrMapPreNT5NetCardInfIdInInf(IN HINF hinf, IN HKEY hkeyAdapterParams, IN PCWSTR pszPreNT5InfId, OUT tstring* pstrNT5InfId, OUT tstring* pstrAdapterType, OUT BOOL* pfOemComponent) { DefineFunctionName("HrMapPreNT5InfIdToNT5InfId"); Assert(hinf); Assert(hkeyAdapterParams); AssertValidReadPtr(pszPreNT5InfId); AssertValidWritePtr(pstrNT5InfId); AssertValidWritePtr(pfOemComponent); HRESULT hr=S_FALSE; PCWSTR pszSectionName; for (int iSection=0; iSection < g_cNumNetCardSections; iSection++) { pszSectionName = g_aszInfMapNetCardSections[iSection]; hr = HrMapPreNT5InfIdToNT5InfIdInSection(hinf, hkeyAdapterParams, pszSectionName, pszPreNT5InfId, pstrNT5InfId, pfOemComponent); if (hr == S_OK) { if (pstrAdapterType) { *pstrAdapterType = pszSectionName; } if (!lstrcmpiW(pszSectionName, c_szOemNetAdapters) || !lstrcmpiW(pszSectionName, c_szAsyncAdapters) || !lstrcmpiW(pszSectionName, c_szOemAsyncAdapters)) { *pfOemComponent = TRUE; } else { *pfOemComponent = FALSE; } break; } } TraceErrorOptional(__FUNCNAME__, hr, (hr == S_FALSE)); return hr; } //+--------------------------------------------------------------------------- // // Function: HrMapPreNT5NetCardInfIdToNT5InfId // // Purpose: Maps pre-NT5 InfID of a net card to its NT5 equivalent // // Arguments: // hkeyAdapterParams [in] handle to Parameters key under the netcard driver key // pszPreNT5InfId [in] pre-NT5 InfID // pstrNT5InfId [out] NT5 InfID // pstrAdapterType [out] section in which the map was found // pfOemComponent [out] set to TRUE if it is an OEM card // ppnmi [out] CNetMapInfo object representing the map found // // Returns: S_OK if found, S_FALSE if not, // otherwise HRESULT_FROM_WIN32 error code. // // Author: kumarp 24-July-97 // // Notes: // HRESULT HrMapPreNT5NetCardInfIdToNT5InfId(IN HKEY hkeyAdapterParams, IN PCWSTR pszPreNT5InfId, OUT tstring* pstrNT5InfId, OUT tstring* pstrAdapterType, OUT BOOL* pfOemComponent, OUT CNetMapInfo** ppnmi) { DefineFunctionName("HrMapPreNT5NetCardInfIdToNT5InfId"); Assert(hkeyAdapterParams); AssertValidReadPtr(pszPreNT5InfId); AssertValidWritePtr(pstrNT5InfId); AssertValidWritePtr(pstrAdapterType); AssertValidWritePtr(pfOemComponent); AssertValidReadPtr(g_pnmaNetMap); HRESULT hr=E_FAIL; TraceTag(ttidNetUpgrade, "finding mapping for %S...", pszPreNT5InfId); if (g_pnmaNetMap) { CNetMapInfo* pnmi; size_t cNumNetMapEntries = g_pnmaNetMap->size(); for (size_t i = 0; i < cNumNetMapEntries; i++) { pnmi = (CNetMapInfo*) (*g_pnmaNetMap)[i]; hr = HrMapPreNT5NetCardInfIdInInf(pnmi->m_hinfNetMap, hkeyAdapterParams, pszPreNT5InfId, pstrNT5InfId, pstrAdapterType, pfOemComponent); if (S_OK == hr) { if (ppnmi) { *ppnmi = pnmi; } TraceTag(ttidNetUpgrade, "%s: %S --> %S (type: %S)", __FUNCNAME__, pszPreNT5InfId, pstrNT5InfId->c_str(), pstrAdapterType->c_str()); break; } } } TraceErrorOptional(__FUNCNAME__, hr, (hr == S_FALSE)); return hr; } //+--------------------------------------------------------------------------- // // Function: HrMapPreNT5InfIdToNT5InfIdInSection // // Purpose: Searches in szSectionName section to // map pre-NT5 InfID of a net card to its NT5 equivalent // // Arguments: // hinf [in] handle of netmap.inf file // hkeyAdapterParams [in] handle to Parameters key under the netcard driver key // pszSectionName [in] name of section to search // pszPreNT5InfId [in] pre-NT5 InfID // pstrNT5InfId [out] NT5 InfID // pfOemComponent [out] set to TRUE if it is an OEM card // // Returns: S_OK if found, S_FALSE if not, // otherwise HRESULT_FROM_WIN32 error code. // // Author: kumarp 24-July-97 // // Notes: // HRESULT HrMapPreNT5InfIdToNT5InfIdInSection(IN HINF hinf, IN HKEY hkeyAdapterParams, IN PCWSTR pszSectionName, IN PCWSTR pszPreNT5InfId, OUT tstring* pstrNT5InfId, OUT BOOL* pfOemComponent) { DefineFunctionName("HrMapPreNT5InfIdToNT5InfIdInSection"); Assert(hinf); AssertValidReadPtr(pszSectionName); AssertValidReadPtr(pszPreNT5InfId); AssertValidWritePtr(pstrNT5InfId); HRESULT hr=S_FALSE; INFCONTEXT ic; hr = HrSetupFindFirstLine(hinf, pszSectionName, pszPreNT5InfId, &ic); if (SUCCEEDED(hr)) { DWORD dwMappingMethod=-1; // key found, get value // we do not use the common function HrSetupGetIntField because it causes // tons of TraceError messages for 1-1 mapping where the first value // is not an integer if (::SetupGetIntField(&ic, 1, (int*) &dwMappingMethod)) { // value begins with a number --> this is a special case mapping // if (dwMappingMethod == 0) { // use mapping method 0 Assert(hkeyAdapterParams); tstring strAdapterSection; hr = HrSetupGetStringField(ic, 2, &strAdapterSection); if (S_OK == hr) { hr = HrMapPreNT5InfIdToNT5InfIdUsingMethod0(hkeyAdapterParams, hinf, strAdapterSection.c_str(), pstrNT5InfId); } } else { // currently we support only mapping-method 0 // hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); } } else { // the first field was not an integer which means // this is a straight forward (1 to 1) mapping // hr = HrSetupGetStringField(ic, 1, pstrNT5InfId); } } if (HRESULT_FROM_SETUPAPI(ERROR_LINE_NOT_FOUND) == hr) { hr = S_FALSE; } TraceErrorOptional(__FUNCNAME__, hr, (hr == S_FALSE)); return hr; } //+--------------------------------------------------------------------------- // // Function: HrMapPreNT5InfIdToNT5InfIdUsingMethod0 // // Purpose: map pre-NT5 InfID of a net card to its NT5 equivalent // using mapping method 0 // // Arguments: // hkeyAdapterParams [in] handle to Parameters key under the netcard driver key // hInf [in] handle of netmap.inf // pszSectionName [in] name of section to search // pstrNT5InfId [out] NT5 InfID // // Returns: S_OK if found, S_FALSE if not, otherwise HRESULT_FROM_WIN32 error code. // // Author: kumarp 24-July-97 // // Notes: // // Mapping method 0 // ---------------- // This method is used when a single pre-NT5 InfID represents more than one // net card which means that a single pre-NT5 InfID is mapped onto many // NT5 PnPIDs. The only way to differentiate between the different types of // net cards is to inspect a single value under the parameters key. // // In this mapping method, two keys are required to be specified for // each net card. // - ValueName: this specifies the value to be inspected under the Parameters key // - ValueType: this specifies the type of ValueName // // there can be any number of additional keys in this section. // each such line is of the form // <NT5 InfID>=<some value of type ValueType> // // we first find out the value of ValueName // then we enumerate each key in this section to see if the value matches the // value of any of the keys. // if we find a match, then the name of the found key represents <NT5 InfID> // // e.g. // 5 flavors of the ELNK3MCA card are represented by the same InfID in NT4 // the only way to distinguish between them is to inspect the McaPosId value // for this card we have the mapping section defined as follows: // // [McaAdapters] // ELNK3MCA = 0,ELNK3MCA ; 0 --> mapping method 0 // ... other mca card entries ... // // [ELNK3MCA] // ValueName= McaPosId // ValueType= 4 ; REG_DWORD // mca_627c = 0x0000627c ; if value of McaPosId is 0x627c then PnPID == mca_627c // mca_627d = 0x0000627d // mca_61db = 0x000061db // mca_62f6 = 0x000062f6 // mca_62f7 = 0x000062f7 // // Note: a special keyword "ValueNotPresent" can be used to make a mapping // for the case when a value is not present. // HRESULT HrMapPreNT5InfIdToNT5InfIdUsingMethod0(IN HKEY hkeyAdapterParams, IN HINF hInf, IN PCWSTR pszAdapterSection, OUT tstring* pstrNT5InfId) { DefineFunctionName("HrMapPreNT5InfIdToNT5InfIdUsingMethod0"); Assert(hkeyAdapterParams); Assert(hInf); AssertValidReadPtr(pszAdapterSection); AssertValidWritePtr(pstrNT5InfId); HRESULT hr=S_FALSE; INFCONTEXT ic; tstring strValueName; // get ValueName hr = HrSetupGetFirstString(hInf, pszAdapterSection, c_szKeyValueName, &strValueName); if (SUCCEEDED(hr)) { DWORD dwRegValue=0; DWORD dwInfValue=0; DWORD dwValueType; tstring strRegValue; tstring strInfValue; tstring strValue; // get ValueType hr = HrSetupGetFirstDword(hInf, pszAdapterSection, c_szKeyValueType, &dwValueType); if (SUCCEEDED(hr)) { switch (dwValueType) { case REG_DWORD: // find the value in under adapter driver parameters key // hr = HrRegQueryDword(hkeyAdapterParams, strValueName.c_str(), &dwRegValue); if (SUCCEEDED(hr)) { // goto the ValueType line hr = HrSetupFindFirstLine(hInf, pszAdapterSection, c_szKeyValueType, &ic); if (S_OK == hr) { // move the context from the ValueType line to // the next line, where values begin hr = HrSetupFindNextLine(ic, &ic); } while (S_OK == hr) { // now enumerate over all keys in this section and // try to locate the key with dwRegValue in the infmap hr = HrSetupGetIntField(ic, 1, (int*) &dwInfValue); if ((S_OK == hr) && (dwRegValue == dwInfValue)) { // value matches, now find the key name hr = HrSetupGetStringField(ic, 0, pstrNT5InfId); if (S_OK == hr) { // the key name (NT5 infid) // is returned in pstrNT5InfId break; } } hr = HrSetupFindNextLine(ic, &ic); } } else if (HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) == hr) { hr = HrSetupFindKeyWithStringValue(hInf, pszAdapterSection, c_szValueNotPresent, pstrNT5InfId); } break; case REG_SZ: // find the value in under adapter driver parameters key // hr = HrRegQueryString(hkeyAdapterParams, strValueName.c_str(), &strRegValue); if (SUCCEEDED(hr)) { // goto the ValueType line hr = HrSetupFindFirstLine(hInf, pszAdapterSection, c_szKeyValueType, &ic); if (S_OK == hr) { // move the context from the ValueType line to // the next line, where values begin hr = HrSetupFindNextLine(ic, &ic); } while (S_OK == hr) { // now enumerate over all keys in this section and // try to locate the key with dwRegValue in the infmap hr = HrSetupGetStringField(ic, 1, &strInfValue); if ((S_OK == hr) && !lstrcmpiW(strRegValue.c_str(), strInfValue.c_str())) { // value matches, now find the key name hr = HrSetupGetStringField(ic, 0, pstrNT5InfId); if (S_OK == hr) { // the key name (NT5 infid) // is returned in pstrNT5InfId break; } } hr = HrSetupFindNextLine(ic, &ic); } } else if (HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) == hr) { hr = HrSetupFindKeyWithStringValue(hInf, pszAdapterSection, c_szValueNotPresent, pstrNT5InfId); } break; default: hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); // currently we support only REG_DWORD and REG_SZ type values TraceTag(ttidError, "%s: ValueType %d is not supported", __FUNCNAME__, dwValueType); break; } } } TraceError(__FUNCNAME__, hr); return hr; } // ---------------------------------------------------------------------- // // Function: HrMapPreNT5NetComponentInfIDUsingInfHelper // // Purpose: // // Arguments: // hinf [in] handle of netmap.inf file // pszOldInfID [in] pre NT5 InfID // pszMSSection [in] section having MS components // pszOemSection [in] section having OEM components // pstrNT5InfId [out] mapped NT5 InfID // pfOemComponent [out] set to TRUE for OEM component // // Returns: S_OK on success, // S_FALSE if a mapping is not found // otherwise an error code // // Author: kumarp 17-December-97 // // Notes: // HRESULT HrMapPreNT5NetComponentInfIDUsingInfHelper(IN HINF hinf, IN PCWSTR pszOldInfID, IN PCWSTR pszMSSection, IN PCWSTR pszOemSection, OUT tstring* pstrNT5InfId, OUT BOOL* pfOemComponent) { DefineFunctionName("HrMapPreNT5NetComponentInfIDUsingInfHelper"); Assert(hinf); AssertValidReadPtr(pszOldInfID); AssertValidReadPtr(pszMSSection); AssertValidReadPtr(pszOemSection); AssertValidWritePtr(pstrNT5InfId); AssertValidWritePtr(pfOemComponent); HRESULT hr=S_FALSE; INFCONTEXT ic; hr = HrSetupFindFirstLine(hinf, pszMSSection, pszOldInfID, &ic); if (S_OK == hr) { *pfOemComponent = FALSE; } else { hr = HrSetupFindFirstLine(hinf, pszOemSection, pszOldInfID, &ic); if (S_OK == hr) { *pfOemComponent = TRUE; } } if (S_OK == hr) { hr = HrSetupGetStringField(ic, 1, pstrNT5InfId); if (S_OK == hr) { if (*pfOemComponent) { tstring strOemDll; tstring strOemInf; HRESULT hrT; hrT = HrGetOemUpgradeInfoInInf(hinf, pstrNT5InfId->c_str(), &strOemDll, &strOemInf); if ((S_OK == hrT) && !lstrcmpiW(strOemDll.c_str(), c_szNotSupported)) { TraceTag(ttidNetUpgrade, "%s: %S --> %S",__FUNCNAME__, pszOldInfID, c_szNotSupported); hr = S_FALSE; } } } } else if (HRESULT_FROM_SETUPAPI(ERROR_LINE_NOT_FOUND) == hr) { hr = S_FALSE; } TraceErrorOptional(__FUNCNAME__, hr, (hr == S_FALSE)); return hr; } // ---------------------------------------------------------------------- // // Function: HrMapPreNT5NetComponentInfIDInInf // // Purpose: Search the specified netmap.inf file for mapping // the specified pre-NT5 InfID of a s/w component to its NT5 value // // Arguments: // hinf [in] handle of netmap.inf file // pszOldInfID [in] pre-NT5 InfID // pstrNT5InfId [out] mapped ID // pfOemComponent [out] set to TRUE for OEM component // // Returns: S_OK on success, // S_FALSE if a mapping is not found // otherwise an error code // // Author: kumarp 17-December-97 // // Notes: // HRESULT HrMapPreNT5NetComponentInfIDInInf(IN HINF hinf, IN PCWSTR pszOldInfID, OUT tstring* pstrNT5InfId, OUT ENetComponentType* pnct, OUT BOOL* pfOemComponent) { DefineFunctionName("HrMapPreNT5NetComponentInfIDUsingInf"); Assert(hinf); AssertValidReadPtr(pszOldInfID); AssertValidWritePtr(pstrNT5InfId); AssertValidWritePtr(pfOemComponent); HRESULT hr=S_FALSE; ENetComponentType nct = NCT_Unknown; hr = HrMapPreNT5NetComponentInfIDUsingInfHelper(hinf, pszOldInfID, c_szNetProtocols, c_szOemNetProtocols, pstrNT5InfId, pfOemComponent); if (S_OK == hr) { nct = NCT_Protocol; } else { hr = HrMapPreNT5NetComponentInfIDUsingInfHelper(hinf, pszOldInfID, c_szNetServices, c_szOemNetServices, pstrNT5InfId, pfOemComponent); if (S_OK == hr) { nct = NCT_Service; } else { hr = HrMapPreNT5NetComponentInfIDUsingInfHelper(hinf, pszOldInfID, c_szNetClients, c_szOemNetClients, pstrNT5InfId, pfOemComponent); if (S_OK == hr) { nct = NCT_Client; } } } if ((S_OK == hr) && pnct) { *pnct = nct; } TraceErrorOptional(__FUNCNAME__, hr, (hr == S_FALSE)); return hr; } // ---------------------------------------------------------------------- // // Function: HrMapPreNT5NetComponentInfIDToNT5InfID // // Purpose: maps pre-NT5 InfID of a service or protocol to its NT5 equivalent // // Arguments: // pszPreNT5InfId [in] pre-NT5 InfID // pstrNT5InfId [out] mapped ID // pfOemComponent [out] set to TRUE for OEM component // pdwNetMapIndex [out] the index in netmap array for which map was found // // Returns: S_OK on success, // S_FALSE if a mapping is not found // otherwise an error code // // Author: kumarp 17-December-97 // // Notes: // HRESULT HrMapPreNT5NetComponentInfIDToNT5InfID(IN PCWSTR pszPreNT5InfId, OUT tstring* pstrNT5InfId, OUT BOOL* pfOemComponent, OUT ENetComponentType* pnct, OUT CNetMapInfo** ppnmi) { DefineFunctionName("HrMapPreNT5NetComponentInfIDToNT5InfID"); AssertValidReadPtr(pszPreNT5InfId); AssertValidWritePtr(pstrNT5InfId); AssertValidReadPtr(g_pnmaNetMap); HRESULT hr=E_FAIL; TraceTag(ttidNetUpgrade, "finding mapping for %S...", pszPreNT5InfId); if (g_pnmaNetMap) { CNetMapInfo* pnmi; size_t cNumNetMapEntries = g_pnmaNetMap->size(); for (size_t i = 0; i < cNumNetMapEntries; i++) { pnmi = (CNetMapInfo*) (*g_pnmaNetMap)[i]; hr = HrMapPreNT5NetComponentInfIDInInf(pnmi->m_hinfNetMap, pszPreNT5InfId, pstrNT5InfId, pnct, pfOemComponent); if (SUCCEEDED(hr)) { if (ppnmi) { *ppnmi = pnmi; } if (S_OK == hr) { TraceTag(ttidNetUpgrade, "%s: %S --> %S", __FUNCNAME__, pszPreNT5InfId, pstrNT5InfId->c_str()); break; } } } } TraceErrorOptional(__FUNCNAME__, hr, (hr == S_FALSE)); return hr; } // ---------------------------------------------------------------------- // // Function: HrGetSoftwareProductKey // // Purpose: Get handle to registry key for a software product of a provider // // Arguments: // pszProvider [in] name of provider // pszProduct [in] name of product // phkey [out] pointer to handle of regkey // // Returns: S_OK on success, otherwise an error code // // Author: kumarp 17-December-97 // // Notes: // HRESULT HrGetSoftwareProductKey(IN PCWSTR pszProvider, IN PCWSTR pszProduct, OUT HKEY* phkey) { DefineFunctionName("HrGetSoftwareProductKey"); AssertValidReadPtr(pszProvider); AssertValidReadPtr(pszProduct); AssertValidWritePtr(phkey); HRESULT hr=S_OK; tstring strProduct; strProduct = c_szRegKeySoftware; AppendToPath(&strProduct, pszProvider); AppendToPath(&strProduct, pszProduct); AppendToPath(&strProduct, c_szRegKeyCurrentVersion); hr = HrRegOpenKeyEx(HKEY_LOCAL_MACHINE, strProduct.c_str(), KEY_READ, phkey); TraceErrorOptional(__FUNCNAME__, hr, (hr == S_FALSE)); return hr; } // ---------------------------------------------------------------------- // // Function: HrMapPreNT5NetComponentServiceNameToNT5InfId // // Purpose: Map pre-NT5 InfID of a service to its NT5 value // // Arguments: // pszServiceName [in] name of service // pstrNT5InfId [out] mapped ID // // Returns: S_OK on success, // S_FALSE if a mapping is not found // otherwise an error code // // Author: kumarp 17-December-97 // // Notes: // HRESULT HrMapPreNT5NetComponentServiceNameToNT5InfId(IN PCWSTR pszServiceName, OUT tstring* pstrNT5InfId) { DefineFunctionName("HrMapPreNT5NetComponentServiceNameToNT5InfId"); AssertValidReadPtr(pszServiceName); AssertValidWritePtr(pstrNT5InfId); tstring strPreNT5InfId; HKEY hkey; HRESULT hr=S_OK; hr = HrGetSoftwareProductKey(c_szRegKeyMicrosoft, pszServiceName, &hkey); if (S_OK == hr) { hr = HrGetPreNT5InfIdAndDesc(hkey, &strPreNT5InfId, NULL, NULL); if (S_OK == hr) { BOOL fIsOemComponent; hr = HrMapPreNT5NetComponentInfIDToNT5InfID(strPreNT5InfId.c_str(), pstrNT5InfId, &fIsOemComponent, NULL, NULL); #ifdef ENABLETRACE if (FAILED(hr)) { TraceTag(ttidNetUpgrade, "%s: could not map %S to NT5 InfID", __FUNCNAME__, pszServiceName); } #endif } RegCloseKey(hkey); } TraceErrorOptional(__FUNCNAME__, hr, (hr == S_FALSE)); return hr; } // ---------------------------------------------------------------------- // // Function: HrGetOemUpgradeInfoInInf // // Purpose: Find out which OEM DLL to load for a component // // Arguments: // hinf [in] handle of netmap.inf file // pszNT5InfId [in] NT5 InfID of a component // pstrUpgradeDllName [out] name of the upgrade DLL found // pstrInf [out] INF file for this component // // Returns: S_OK on success, otherwise an error code // // Author: kumarp 17-December-97 // // Notes: // HRESULT HrGetOemUpgradeInfoInInf(IN HINF hinf, IN PCWSTR pszNT5InfId, OUT tstring* pstrUpgradeDllName, OUT tstring* pstrInf) { DefineFunctionName("HrGetOemUpgradeInfoInInf"); Assert(hinf); AssertValidReadPtr(pszNT5InfId); AssertValidWritePtr(pstrUpgradeDllName); AssertValidWritePtr(pstrInf); HRESULT hr=S_FALSE; INFCONTEXT ic; pstrUpgradeDllName->erase(); pstrInf->erase(); // each line in this section is of the format // <NT5-InfId>=<oem-upgrade-dll-name>[,<inf-file-name>] hr = HrSetupFindFirstLine(hinf, c_szOemUpgradeSupport, pszNT5InfId, &ic); if (S_OK == hr) { hr = HrSetupGetStringField(ic, 1, pstrUpgradeDllName); if (S_OK == hr) { // the value OemInfFile is optional, so we dont // complain if we cannot find it. if (HRESULT_FROM_SETUPAPI(ERROR_INVALID_PARAMETER) == HrSetupGetStringField(ic, 2, pstrInf)) { TraceTag(ttidNetUpgrade, "%s: OemInf is not specified for %S", __FUNCNAME__, pszNT5InfId); } } } TraceTag(ttidNetUpgrade, "%s: OemDll: %S, OemInf: %S", __FUNCNAME__, pstrUpgradeDllName->c_str(), pstrInf->c_str()); TraceErrorOptional(__FUNCNAME__, hr, (hr == S_FALSE)); return hr; } // ---------------------------------------------------------------------- // // Function: HrGetOemUpgradeDllInfo // // Purpose: Find out which OEM DLL to load for a component // // Arguments: // pszNT5InfId [in] InfID of OEM component // pstrUpgradeDllName [out] name of OEM DLL found // // Returns: S_OK on success, otherwise an error code // // Author: kumarp 17-December-97 // // Notes: // HRESULT HrGetOemUpgradeInfo(IN PCWSTR pszNT5InfId, OUT tstring* pstrUpgradeDllName, OUT tstring* pstrInf) { DefineFunctionName("HrGetOemUpgradeInfo"); AssertValidReadPtr(pszNT5InfId); AssertValidWritePtr(pstrUpgradeDllName); Assert(g_pnmaNetMap); HRESULT hr=E_FAIL; TraceTag(ttidNetUpgrade, "finding upgrade dll info for %S...", pszNT5InfId); if (g_pnmaNetMap) { CNetMapInfo* pnmi; size_t cNumNetMapEntries = g_pnmaNetMap->size(); for (size_t i = 0; i < cNumNetMapEntries; i++) { pnmi = (CNetMapInfo*) (*g_pnmaNetMap)[i]; hr = HrGetOemUpgradeInfoInInf(pnmi->m_hinfNetMap, pszNT5InfId, pstrUpgradeDllName, pstrInf); if (S_OK == hr) { TraceTag(ttidNetUpgrade, "%s: %S --> Dll: %S, Inf: %S", __FUNCNAME__, pszNT5InfId, pstrUpgradeDllName->c_str(), pstrInf->c_str()); break; } } } TraceErrorOptional(__FUNCNAME__, hr, (hr == S_FALSE)); return hr; } // ---------------------------------------------------------------------- // // Function: HrSetupFindKeyWithStringValue // // Purpose: Find the key in a section that has the specified value // // Arguments: // hInf [in] handle of netmap.inf file // szSection [in] name of section // szValue [in] value to find // pstrKey [out] name of the key found // // Returns: S_OK on success, otherwise an error code // // Author: kumarp 17-December-97 // // Notes: // HRESULT HrSetupFindKeyWithStringValue(IN HINF hInf, IN PCWSTR szSection, IN PCWSTR szValue, OUT tstring* pstrKey) { DefineFunctionName("HrSetupFindKeyWithStringValue"); HRESULT hr=S_OK; INFCONTEXT ic; tstring strValue; hr = HrSetupFindFirstLine(hInf, szSection, NULL, &ic); while (S_OK == hr) { // now enumerate over all keys in this section and // try to locate the key with value szValue hr = HrSetupGetStringField(ic, 1, &strValue); if ((S_OK == hr) && !lstrcmpiW(strValue.c_str(), szValue)) { // value matches, now find the key name hr = HrSetupGetStringField(ic, 0, pstrKey); break; } hr = HrSetupFindNextLine(ic, &ic); } if (HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS) == hr) { hr = S_FALSE; } TraceError(__FUNCNAME__, hr); return hr; }
34.351901
88
0.507181
[ "object" ]
1539af132d7b851f216243cf79a9ac02ac4ce41d
562
cpp
C++
practice/binarySearch/binarySearch.cpp
atpk/CP
0eee3af02bb0466c85aeb8dd86cf3620567a354c
[ "MIT" ]
null
null
null
practice/binarySearch/binarySearch.cpp
atpk/CP
0eee3af02bb0466c85aeb8dd86cf3620567a354c
[ "MIT" ]
null
null
null
practice/binarySearch/binarySearch.cpp
atpk/CP
0eee3af02bb0466c85aeb8dd86cf3620567a354c
[ "MIT" ]
null
null
null
class Solution { public: int binarySearch(vector<int>& nums, int start, int end, int key){ if(start>end) return -1; int mid = start + (end-start)/2; if(key==nums[mid]) return mid; if(key<nums[mid]){ return binarySearch(nums, start, mid-1, key); } else{ return binarySearch(nums, mid+1, end, key); } } int search(vector<int>& nums, int target) { return binarySearch(nums, 0, nums.size()-1, target); } };
24.434783
69
0.491103
[ "vector" ]
154311a601ac79f567ea8eb62007d116153bad0e
7,378
cpp
C++
src/pke/unittest/UnitTestSerialize.cpp
marcelmon/PALISADE_capstone
2cfd1626b26576f8fe93bb3a424f934ef700c5b2
[ "BSD-2-Clause" ]
null
null
null
src/pke/unittest/UnitTestSerialize.cpp
marcelmon/PALISADE_capstone
2cfd1626b26576f8fe93bb3a424f934ef700c5b2
[ "BSD-2-Clause" ]
null
null
null
src/pke/unittest/UnitTestSerialize.cpp
marcelmon/PALISADE_capstone
2cfd1626b26576f8fe93bb3a424f934ef700c5b2
[ "BSD-2-Clause" ]
null
null
null
/* * @file * @author TPOC: palisade@njit.edu * * @copyright Copyright (c) 2017, New Jersey Institute of Technology (NJIT) * 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 "include/gtest/gtest.h" #include <iostream> #include "palisade.h" #include "cryptocontext.h" #include "math/nbtheory.h" #include "utils/utilities.h" #include "utils/parmfactory.h" #include "utils/serializablehelper.h" using namespace std; using namespace lbcrypto; class UnitTestPkeSerialize : public ::testing::Test { protected: virtual void SetUp() { } virtual void TearDown() { // Code here will be called immediately after each test // (right before the destructor). } }; static shared_ptr<CryptoContext<Poly>> GenerateTestCryptoContext(const string& parmsetName) { BigInteger modulusP(256); shared_ptr<CryptoContext<Poly>> cc = CryptoContextHelper::getNewContext(parmsetName); shared_ptr<EncodingParams> encodingParams(new EncodingParams(modulusP,PackedIntPlaintextEncoding::GetAutomorphismGenerator(modulusP),8)); cc->GetCryptoParameters()->SetEncodingParams(encodingParams); cc->Enable(ENCRYPTION); cc->Enable(SHE); return cc; } static shared_ptr<CryptoContext<DCRTPoly>> GenerateTestDCRTCryptoContext(const string& parmsetName, usint nTower, usint pbits) { shared_ptr<CryptoContext<DCRTPoly>> cc = CryptoContextHelper::getNewDCRTContext(parmsetName, nTower, pbits); cc->Enable(ENCRYPTION); cc->Enable(SHE); return cc; } template<typename T> void UnitTestContext(shared_ptr<CryptoContext<T>> cc) { LPKeyPair<T> kp = cc->KeyGen(); try { cc->EvalMultKeyGen(kp.secretKey); } catch(...) {} try { cc->EvalSumKeyGen(kp.secretKey, kp.publicKey); } catch(...) {} Serialized ser; ser.SetObject(); ASSERT_TRUE( cc->Serialize(&ser) ) << "Serialization failed"; shared_ptr<CryptoContext<T>> newcc = CryptoContextFactory<T>::DeserializeAndCreateContext(ser); ASSERT_TRUE( newcc ) << "Deserialization failed"; EXPECT_EQ( cc->GetEncryptionAlgorithm()->GetEnabled(), (usint)(ENCRYPTION|SHE) ) << "Enabled features mismatch after ser/deser"; EXPECT_EQ( *cc->GetCryptoParameters(), *newcc->GetCryptoParameters() ) << "Mismatch after ser/deser"; Serialized serK; ASSERT_TRUE( kp.publicKey->Serialize(&serK) ) << "Key serialization failed"; shared_ptr<LPPublicKey<T>> newPub = cc->deserializePublicKey(serK); ASSERT_TRUE( newPub ) << "Key deserialize failed"; EXPECT_EQ( *kp.publicKey, *newPub ) << "Key mismatch"; shared_ptr<CryptoContext<T>> newccFromkey = CryptoContextFactory<T>::DeserializeAndCreateContext(serK); ASSERT_TRUE( newccFromkey ) << "Deserialization from key failed"; shared_ptr<LPPublicKey<T>> finalPub = newccFromkey->deserializePublicKey(serK); ASSERT_TRUE( finalPub ) << "Key deserialize in new ctx failed"; EXPECT_EQ( *newPub, *finalPub ) << "Key mismatch from new ctx"; } TEST(UTPKESer, LTV_Poly_Serial) { shared_ptr<CryptoContext<Poly>> cc = GenerateTestCryptoContext("LTV5"); UnitTestContext<Poly>(cc); } TEST(UTPKESer, LTV_DCRTPoly_Serial) { shared_ptr<CryptoContext<DCRTPoly>> cc = GenerateTestDCRTCryptoContext("LTV5", 3, 20); UnitTestContext<DCRTPoly>(cc); } TEST(UTPKESer, StSt_Poly_Serial) { shared_ptr<CryptoContext<Poly>> cc = GenerateTestCryptoContext("StSt6"); UnitTestContext<Poly>(cc); } TEST(UTPKESer, StSt_DCRTPoly_Serial) { shared_ptr<CryptoContext<DCRTPoly>> cc = GenerateTestDCRTCryptoContext("StSt6", 3, 20); UnitTestContext<DCRTPoly>(cc); } TEST(UTPKESer, BV_Poly_Serial) { shared_ptr<CryptoContext<Poly>> cc = GenerateTestCryptoContext("BV2"); UnitTestContext<Poly>(cc); } TEST(UTPKESer, BV_DCRTPoly_Serial) { shared_ptr<CryptoContext<DCRTPoly>> cc = GenerateTestDCRTCryptoContext("BV2", 3, 20); UnitTestContext<DCRTPoly>(cc); } TEST(UTPKESer, Null_Poly_Serial) { shared_ptr<CryptoContext<Poly>> cc = GenerateTestCryptoContext("Null"); UnitTestContext<Poly>(cc); } TEST(UTPKESer, Null_DCRTPoly_Serial) { shared_ptr<CryptoContext<DCRTPoly>> cc = GenerateTestDCRTCryptoContext("Null", 3, 20); UnitTestContext<DCRTPoly>(cc); } TEST(UTPKESer, FV_Poly_Serial) { shared_ptr<CryptoContext<Poly>> cc = GenerateTestCryptoContext("FV2"); UnitTestContext<Poly>(cc); } //TEST(UTPKESer, FV_DCRTPoly_Serial) { // shared_ptr<CryptoContext<DCRTPoly>> cc = GenerateTestDCRTCryptoContext("FV2", 3, 20); // UnitTestContext<DCRTPoly>(cc); //} // REMAINDER OF THE TESTS USE LTV AS A REPRESENTITIVE CONTEXT TEST(UTPKESer, LTV_keys_and_ciphertext) { bool dbg_flag = false; shared_ptr<CryptoContext<Poly>> cc = GenerateTestCryptoContext("LTV5"); LPKeyPair<Poly> kp = cc->KeyGen(); LPKeyPair<Poly> kpnew; DEBUG("step 1"); { Serialized ser; ser.SetObject(); DEBUG("step 1.1"); ASSERT_TRUE( kp.publicKey->Serialize(&ser) ) << "Public Key serialization failed"; DEBUG("step 1.2"); ASSERT_TRUE( (kpnew.publicKey = cc->deserializePublicKey(ser)) ) << "Public key deserialization failed"; DEBUG("step 1.3"); EXPECT_EQ( *kp.publicKey, *kpnew.publicKey ) << "Public key mismatch after ser/deser"; } DEBUG("step 2"); { Serialized ser; ser.SetObject(); ASSERT_TRUE( kp.secretKey->Serialize(&ser) ) << "Secret Key serialization failed"; ASSERT_TRUE( (kpnew.secretKey = cc->deserializeSecretKey(ser)) ) << "Secret key deserialization failed"; EXPECT_EQ( *kp.secretKey, *kpnew.secretKey ) << "Secret key mismatch after ser/deser"; } DEBUG("step 3"); BytePlaintextEncoding plaintextShort("This is just a little test"); vector<shared_ptr<Ciphertext<Poly>>> ciphertext = cc->Encrypt(kp.publicKey, plaintextShort, true); Serialized ser; ser.SetObject(); ASSERT_TRUE( ciphertext[0]->Serialize(&ser) ) << "Ciphertext serialize failed"; DEBUG("step 4"); shared_ptr<Ciphertext<Poly>> newC; ASSERT_TRUE( (newC = cc->deserializeCiphertext(ser)) ) << "Ciphertext deserialization failed"; EXPECT_EQ( *ciphertext[0], *newC ) << "Ciphertext mismatch"; DEBUG("step 5"); ciphertext[0] = newC; BytePlaintextEncoding plaintextShortNew; cc->Decrypt(kp.secretKey, ciphertext, &plaintextShortNew, true); EXPECT_EQ(plaintextShortNew, plaintextShort) << "Decrypted deserialize failed"; }
35.815534
138
0.751694
[ "vector" ]
15468de8ee019219d07466945f1367613ecd869a
1,825
cpp
C++
VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/Hilo C++ sample (Windows 8)/C++/Hilo/CropImageView.xaml.cpp
alonmm/VCSamples
6aff0b4902f5027164d593540fcaa6601a0407c3
[ "MIT" ]
300
2019-05-09T05:32:33.000Z
2022-03-31T20:23:24.000Z
VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/Hilo C++ sample (Windows 8)/C++/Hilo/CropImageView.xaml.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
9
2016-09-19T18:44:26.000Z
2018-10-26T10:20:05.000Z
VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/Hilo C++ sample (Windows 8)/C++/Hilo/CropImageView.xaml.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
633
2019-05-08T07:34:12.000Z
2022-03-30T04:38:28.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 #include "pch.h" #include "CropImageView.xaml.h" #include "CropImageViewModel.h" using namespace Hilo; using namespace Platform; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Input; // See http://go.microsoft.com/fwlink/?LinkId=267278 for info on how Hilo creates pages and navigates to pages. CropImageView::CropImageView() { InitializeComponent(); m_cropImageViewModel = static_cast<CropImageViewModel^>(DataContext); m_sizeChangedAttached = false; } void CropImageView::OnSizeChanged(Object^ sender, SizeChangedEventArgs^ e) { m_cropImageViewModel->CalculateInitialCropOverlayPosition( Photo->TransformToVisual(CropImageGrid), Photo->RenderSize.Width, Photo->RenderSize.Height); if (!m_sizeChangedAttached) { SizeChanged += ref new SizeChangedEventHandler(this, &CropImageView::OnSizeChanged); m_sizeChangedAttached = true; } } void CropImageView::OnThumbDragDelta(Object^ sender, DragDeltaEventArgs^ e) { if (!m_cropImageViewModel->InProgress) { m_cropImageViewModel->UpdateCropOverlayPostion(safe_cast<Thumb^>(sender), e->VerticalChange, e->HorizontalChange, CropOverlay->MinWidth, CropOverlay->MinHeight); } } void CropImageView::OnCropRectangleTapped(Object^ sender, TappedRoutedEventArgs^ e) { if (!m_cropImageViewModel->InProgress) { m_cropImageViewModel->CropImageAsync(Photo->ActualWidth); } }
32.017544
111
0.736986
[ "object" ]
154858d1de49988a25dbc5b5f8da87dd84066f13
5,257
cpp
C++
lib/Input/src/gamepads.cpp
jfcameron/WebAssembly-C-Cpp-Reference
b0d276565097920e700776fbf621f24ef82972cd
[ "MIT" ]
1
2018-06-05T07:54:52.000Z
2018-06-05T07:54:52.000Z
lib/Input/src/gamepads.cpp
jfcameron/WebAssembly-C-Cpp-Reference
b0d276565097920e700776fbf621f24ef82972cd
[ "MIT" ]
8
2018-08-11T05:13:57.000Z
2018-11-15T00:14:42.000Z
lib/Input/src/gamepads.cpp
jfcameron/WebAssembly-C-Cpp-Reference
b0d276565097920e700776fbf621f24ef82972cd
[ "MIT" ]
null
null
null
// © 2018 Joseph Cameron - All Rights Reserved #include <gdk/exception.h> #include <gdk/gamepads.h> #include <gdk/input_protected.h> #include <gdk/glfw_wrapper.h> #include <GLFW/glfw3.h> #ifdef JFC_TARGET_PLATFORM_Emscripten #include <emscripten.h> #endif #include <cassert> #include <cstdio> #include <cstring> #include <iostream> #include <map> #include <vector> static constexpr char TAG[] = "Gamepad"; namespace gdk { /// \brief a gamepad attached to the system. /// /// \detailed /// /// \note this class cannot be directly accessed by the user; it is an implementation detail of the gamepads.h api class Gamepad final { friend void gdk::input::hidden::gamepads::initialize(); Gamepad(const int aJoystickIndex); public: std::string m_Name; std::vector<const unsigned char *> m_Buttons; std::vector<const float *> m_Axes; void update(); }; void Gamepad::update() { //check if my pointers in glfw context are null and my behaviour is now evil and undefined } Gamepad::Gamepad(const int aJoystickIndex) : m_Name([&]() { const char *name = glfwGetJoystickName(aJoystickIndex); if (!name) throw gdk::Exception(TAG, "Gamepad handler failed to create a gdk::Gamepad using index: ", aJoystickIndex, " is there a gamepad connected at that index?"); return name; }()) , m_Buttons([&]() { int button_count; const unsigned char *buttons = glfwGetJoystickButtons(aJoystickIndex, &button_count); if (!buttons) throw gdk::Exception(TAG, "Gamepad handler failed to create a gdk::Gamepad using index: ", aJoystickIndex, " is there a gamepad connected at that index?"); return (std::vector<const unsigned char *>) {buttons, buttons + button_count}; }()) , m_Axes([&]() { int axes_count; const float *axes = glfwGetJoystickAxes(aJoystickIndex, &axes_count); if (!axes) throw gdk::Exception(TAG, "Gamepad handler failed to create a gdk::Gamepad using index: ", aJoystickIndex, " is there a gamepad connected at that index?"); return (std::vector<const float *>) {axes, axes + axes_count}; }()) {} } namespace { // std::map<std::string, gdk::Gamepad> gamepadMap; //for o1 retrieval? std::vector<gdk::Gamepad> gamepadList; } namespace gdk::input::hidden::gamepads { void initialize() { glfwSetJoystickCallback( [](int joy, int event) { if (event == GLFW_CONNECTED) { std::cout << "Joystick connected: " << joy << glfwGetJoystickName(joy) << std::endl; gamepadList.push_back(gdk::Gamepad(joy)); } else if (event == GLFW_DISCONNECTED) { std::cout << "Joystick disconnected: " << joy << std::endl; gamepadList.erase(gamepadList.begin() + joy); } }); } void update() { for (const auto &gamepad : gamepadList) { std::cout << "Name: " << gamepad.m_Name << [&]() { std::string output; int i = 0; for (const auto &button : gamepad.m_Buttons) output += static_cast<int>(*button); return output; }() << std::endl; } } /*int joystick_count = 0; for (int j = GLFW_JOYSTICK_1; j < GLFW_JOYSTICK_16; ++j) { int joy = GLFW_JOYSTICK_1 + j; if (!glfwJoystickPresent(joy)) continue; joystick_count++; static struct { int axes_count; float axes[16]; int button_count; unsigned char buttons[16]; } last_gamepad_state[16] = {0}; const char *name = glfwGetJoystickName(joy); int axes_count = 0; const float *axes = glfwGetJoystickAxes(joy, &axes_count); int button_count = 0; const unsigned char *buttons = glfwGetJoystickButtons(joy, &button_count); last_gamepad_state[joy].axes_count = axes_count; for (int i = 0; i < axes_count; ++i) { if (last_gamepad_state[joy].axes[i] != axes[i]) { printf("(%d %s) axis %d = %f\n", joy, name, i, axes[i]); } last_gamepad_state[joy].axes[i] = axes[i]; } last_gamepad_state[joy].button_count = button_count; for (int i = 0; i < button_count; ++i) { if (last_gamepad_state[joy].buttons[i] != buttons[i]) { printf("(%d %s) button %d = %d\n", joy, name, i, buttons[i]); } last_gamepad_state[joy].buttons[i] = buttons[i]; } }*/ // } }
29.205556
177
0.517976
[ "vector" ]
15530ef3805337b0e5b483635cff904d3b77ba4d
1,639
cpp
C++
CodeForces/Complete/700-799/733D-KostyaTheSculptor-OLD.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
CodeForces/Complete/700-799/733D-KostyaTheSculptor-OLD.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
CodeForces/Complete/700-799/733D-KostyaTheSculptor-OLD.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
#include <cstdio> #include <vector> #include <algorithm> typedef long long ll; struct marble{ll a, b, c, r;}; bool mcompare(marble x, marble y){ if(x.a < y.a){return true;} else if(x.a == y.a && x.b < y.b){return true;} else if(x.a == y.a && x.b == y.b && x.c < y.c){return true;} else if(x.a == y.a && x.b == y.b && x.c == y.c && x.r <= y.r){return true;} return false; } int main(){ long n; scanf("%ld", &n); std::vector<marble> a; std::pair<ll, ll> ans; ll mx(0); for(long p = 1; p <= n; p++){ std::vector<ll> v(3); scanf("%lld %lld %lld", &v[0], &v[1], &v[2]); sort(v.begin(), v.end()); if(v[0] > mx){ans = std::make_pair(p, -1); mx = v[0];} marble m1; m1.a = v[0]; m1.b = v[1]; m1.c = v[2]; m1.r = p; a.push_back(m1); marble m2; m2.a = v[0]; m2.b = v[2]; m2.c = v[1]; m2.r = p; a.push_back(m2); marble m3; m3.a = v[1]; m3.b = v[2]; m3.c = v[0]; m3.r = p; a.push_back(m3); } sort(a.begin(), a.end(), mcompare); for(long p = 1; p < a.size(); p++){ marble x = a[p - 1]; marble y = a[p]; if((x.a != y.a) || (x.b != y.b)){continue;} if(x.r == y.r){continue;} //printf("a:%lld b:%lld c:%lld r:%lld with ", x.a, x.b, x.c, x.r); //printf("a:%lld b:%lld c:%lld r:%lld \n", y.a, y.b, y.c, y.r); ll cc = x.c + y.c; ll mn(cc); mn = (mn < x.a) ? mn : x.a; mn = (mn < x.b) ? mn : x.b; if(mn > mx){mx = cc; ans = std::make_pair(x.r, y.r);} } if(ans.second == -1){printf("1\n%lld\n", ans.first);} else{printf("2\n%lld %lld\n", ans.first, ans.second);} return 0; }
33.44898
84
0.466138
[ "vector" ]
155479cd0b22aa65e5f3541c7a3f6462db243a52
35,028
cc
C++
src/llv8.cc
Glassig/llnode
ec016041c4c95ec1d7e391bc377627bfd95d8bc9
[ "MIT" ]
null
null
null
src/llv8.cc
Glassig/llnode
ec016041c4c95ec1d7e391bc377627bfd95d8bc9
[ "MIT" ]
null
null
null
src/llv8.cc
Glassig/llnode
ec016041c4c95ec1d7e391bc377627bfd95d8bc9
[ "MIT" ]
null
null
null
#include <assert.h> #include <algorithm> #include <cinttypes> #include <cstdarg> #include <iomanip> #include <sstream> #include <string> #include "deps/rang/include/rang.hpp" #include "llv8-inl.h" #include "llv8.h" #include "src/settings.h" namespace llnode { namespace v8 { using lldb::addr_t; using lldb::SBError; using lldb::SBTarget; static std::string kConstantPrefix = "v8dbg_"; void LLV8::Load(SBTarget target) { // Reload process anyway process_ = target.GetProcess(); // No need to reload if (target_ == target) return; target_ = target; common.Assign(target); smi.Assign(target, &common); heap_obj.Assign(target, &common); map.Assign(target, &common); js_object.Assign(target, &common); heap_number.Assign(target, &common); js_array.Assign(target, &common); js_function.Assign(target, &common); shared_info.Assign(target, &common); uncompiled_data.Assign(target, &common); code.Assign(target, &common); scope_info.Assign(target, &common); context.Assign(target, &common); script.Assign(target, &common); string.Assign(target, &common); one_byte_string.Assign(target, &common); two_byte_string.Assign(target, &common); cons_string.Assign(target, &common); sliced_string.Assign(target, &common); thin_string.Assign(target, &common); fixed_array_base.Assign(target, &common); fixed_array.Assign(target, &common); fixed_typed_array_base.Assign(target, &common); oddball.Assign(target, &common); js_array_buffer.Assign(target, &common); js_array_buffer_view.Assign(target, &common); js_regexp.Assign(target, &common); js_date.Assign(target, &common); descriptor_array.Assign(target, &common); name_dictionary.Assign(target, &common); frame.Assign(target, &common); symbol.Assign(target, &common); types.Assign(target, &common); } int64_t LLV8::LoadPtr(int64_t addr, Error& err) { SBError sberr; int64_t value = process_.ReadPointerFromMemory(static_cast<addr_t>(addr), sberr); if (sberr.Fail()) { // TODO(joyeecheung): use Error::Failure() to report information when // there is less noise from here. err = Error(true, "Failed to load pointer from v8 memory"); return -1; } err = Error::Ok(); return value; } template <class T> CheckedType<T> LLV8::LoadUnsigned(int64_t addr, uint32_t byte_size) { SBError sberr; int64_t value = process_.ReadUnsignedFromMemory(static_cast<addr_t>(addr), byte_size, sberr); if (sberr.Fail()) { PRINT_DEBUG("Failed to load unsigned from v8 memory. Reason: %s", sberr.GetCString()); return CheckedType<T>(); } return CheckedType<T>(value); } int64_t LLV8::LoadUnsigned(int64_t addr, uint32_t byte_size, Error& err) { SBError sberr; int64_t value = process_.ReadUnsignedFromMemory(static_cast<addr_t>(addr), byte_size, sberr); if (sberr.Fail()) { // TODO(joyeecheung): use Error::Failure() to report information when // there is less noise from here. err = Error(true, "Failed to load unsigned from v8 memory"); return -1; } err = Error::Ok(); return value; } double LLV8::LoadDouble(int64_t addr, Error& err) { SBError sberr; int64_t value = process_.ReadUnsignedFromMemory(static_cast<addr_t>(addr), sizeof(double), sberr); if (sberr.Fail()) { err = Error::Failure( "Failed to load double from v8 memory, " "addr=0x%016" PRIx64, addr); return -1.0; } err = Error::Ok(); // dereferencing type-punned pointer will break strict-aliasing rules // return *reinterpret_cast<double*>(&value); double dvalue; std::memcpy(&dvalue, &value, sizeof(double)); return dvalue; } std::string LLV8::LoadBytes(int64_t addr, int64_t length, Error& err) { uint8_t* buf = new uint8_t[length + 1]; SBError sberr; process_.ReadMemory(addr, buf, static_cast<size_t>(length), sberr); if (sberr.Fail()) { err = Error::Failure( "Failed to load v8 backing store memory, " "addr=0x%016" PRIx64 ", length=%" PRId64, addr, length); delete[] buf; return std::string(); } std::string res; char tmp[10]; for (int i = 0; i < length; ++i) { snprintf(tmp, sizeof(tmp), "%s%02x", (i == 0 ? "" : ", "), buf[i]); res += tmp; } delete[] buf; return res; } std::string LLV8::LoadString(int64_t addr, int64_t length, Error& err) { if (length < 0) { err = Error::Failure("Failed to load V8 one byte string - Invalid length"); return std::string(); } char* buf = new char[length + 1]; SBError sberr; process_.ReadMemory(static_cast<addr_t>(addr), buf, static_cast<size_t>(length), sberr); if (sberr.Fail()) { err = Error::Failure( "Failed to load v8 one byte string memory, " "addr=0x%016" PRIx64 ", length=%" PRId64, addr, length); delete[] buf; return std::string(); } buf[length] = '\0'; std::string res = buf; delete[] buf; err = Error::Ok(); return res; } std::string LLV8::LoadTwoByteString(int64_t addr, int64_t length, Error& err) { if (length < 0) { err = Error::Failure("Failed to load V8 two byte string - Invalid length"); return std::string(); } char* buf = new char[length * 2 + 1]; SBError sberr; process_.ReadMemory(static_cast<addr_t>(addr), buf, static_cast<size_t>(length * 2), sberr); if (sberr.Fail()) { err = Error::Failure( "Failed to load V8 two byte string memory, " "addr=0x%016" PRIx64 ", length=%" PRId64, addr, length); delete[] buf; return std::string(); } for (int64_t i = 0; i < length; i++) buf[i] = buf[i * 2]; buf[length] = '\0'; std::string res = buf; delete[] buf; err = Error::Ok(); return res; } uint8_t* LLV8::LoadChunk(int64_t addr, int64_t length, Error& err) { uint8_t* buf = new uint8_t[length]; SBError sberr; process_.ReadMemory(static_cast<addr_t>(addr), buf, static_cast<size_t>(length), sberr); if (sberr.Fail()) { err = Error::Failure( "Failed to load V8 chunk memory, " "addr=0x%016" PRIx64 ", length=%" PRId64, addr, length); delete[] buf; return nullptr; } err = Error::Ok(); return buf; } // reset_line - make line_start absolute vs start of function // otherwise relative to last end // returns line cursor uint32_t JSFrame::GetSourceForDisplay(bool reset_line, uint32_t line_start, uint32_t line_limit, std::string lines[], uint32_t& lines_found, Error& err) { v8::JSFunction fn = GetFunction(err); if (err.Fail()) { return line_start; } v8::SharedFunctionInfo info = fn.Info(err); if (err.Fail()) { return line_start; } v8::Script script = info.GetScript(err); if (err.Fail()) { return line_start; } // Check if this is being run multiple times against the same frame // if not, reset last line if (reset_line) { uint32_t pos = info.StartPosition(err); if (err.Fail()) { return line_start; } int64_t tmp_line; int64_t tmp_col; script.GetLineColumnFromPos(pos, tmp_line, tmp_col, err); if (err.Fail()) { return line_start; } line_start += tmp_line; } script.GetLines(line_start, lines, line_limit, lines_found, err); if (err.Fail()) { const char* msg = err.GetMessage(); if (msg == nullptr) { err = Error::Failure("Failed to get Function Source"); } return line_start; } return line_start + lines_found; } // On 64 bits systems, V8 stores SMIs (small ints) in the top 32 bits of // a 64 bits word. Frame markers used to obey this convention but as of // V8 5.8, they are stored as 32 bits SMIs with the top half set to zero. // Shift the raw value up to make it a normal SMI again. Smi JSFrame::FromFrameMarker(Value value) const { if (v8()->smi()->kShiftSize == 31 && Smi(value).Check() && value.raw() < 1LL << 31) { value = Value(v8(), value.raw() << 31); } return Smi(value); } bool JSFrame::MightBeV8Frame(lldb::SBFrame& frame) { // TODO(mmarchini): There might be a better way to check for V8 builtins // embedded in the binary. auto c_function_name = frame.GetFunctionName(); std::string function_name(c_function_name != nullptr ? c_function_name : ""); return !frame.GetSymbol().IsValid() || function_name.find("Builtins_") == 0; } std::string JSFunction::GetDebugLine(std::string args, Error& err) { SharedFunctionInfo info = Info(err); if (err.Fail()) return std::string(); std::string res = info.ProperName(err); if (err.Fail()) return std::string(); if (!args.empty()) res += "(" + args + ")"; res += " at "; std::string shared; res += info.GetPostfix(err); if (err.Fail()) return std::string(); return res; } std::string JSFunction::GetSource(Error& err) { v8::SharedFunctionInfo info = Info(err); if (err.Fail()) { return std::string(); } v8::Script script = info.GetScript(err); if (err.Fail()) { return std::string(); } // There is no `Script` for functions created in C++ (and possibly others) int64_t type = script.GetType(err); if (err.Fail()) { return std::string(); } if (type != v8()->types()->kScriptType) { return std::string(); } HeapObject source = script.Source(err); if (err.Fail()) return std::string(); int64_t source_type = source.GetType(err); if (err.Fail()) return std::string(); // No source if (source_type > v8()->types()->kFirstNonstringType) { err = Error::Failure("No source, source_type=%" PRId64, source_type); return std::string(); } String str(source); std::string source_str = str.ToString(err); int64_t start_pos = info.StartPosition(err); if (err.Fail()) { return std::string(); } int64_t end_pos = info.EndPosition(err); if (err.Fail()) { return std::string(); } int64_t source_len = source_str.length(); if (end_pos > source_len) { end_pos = source_len; } int64_t len = end_pos - start_pos; std::string res = source_str.substr(start_pos, len); return res; } std::string SharedFunctionInfo::ProperName(Error& err) { String name = Name(err); if (err.Fail()) return std::string(); std::string res = name.ToString(err); if (err.Fail() || res.empty()) { Value inferred = GetInferredName(err); if (err.Fail() || inferred.raw() == -1) return std::string(); // Function may not have inferred name if (!inferred.IsHoleOrUndefined(err) && !err.Fail()) res = inferred.ToString(err); if (err.Fail()) return std::string(); } if (res.empty()) res = "(anonymous)"; return res; } std::string SharedFunctionInfo::GetPostfix(Error& err) { Script script = GetScript(err); if (err.Fail() || script.raw() == -1) return std::string(); // There is no `Script` for functions created in C++ (and possibly others) int64_t type = script.GetType(err); if (err.Fail() || type != v8()->types()->kScriptType) return std::string("(no script)"); String name = script.Name(err); if (err.Fail()) return std::string(); int64_t start_pos = StartPosition(err); if (err.Fail()) return std::string(); std::string res = name.ToString(err); if (res.empty()) res = "(no script)"; int64_t line = 0; int64_t column = 0; script.GetLineColumnFromPos(start_pos, line, column, err); if (err.Fail()) return std::string(); // NOTE: lines start from 1 in most of editors char tmp[128]; snprintf(tmp, sizeof(tmp), ":%d:%d", static_cast<int>(line + 1), static_cast<int>(column)); return res + tmp; } std::string SharedFunctionInfo::ToString(Error& err) { std::string res = ProperName(err); if (err.Fail()) return std::string(); return res + " at " + GetPostfix(err); } // return end_char+1, which may be less than line_limit if source // ends before end_inclusive void Script::GetLines(uint64_t start_line, std::string lines[], uint64_t line_limit, uint32_t& lines_found, Error& err) { lines_found = 0; HeapObject source = Source(err); if (err.Fail()) return; int64_t type = source.GetType(err); if (err.Fail()) return; // No source if (type > v8()->types()->kFirstNonstringType) { err = Error::Failure("No source, source_type=%" PRId64, type); return; } String str(source); std::string source_str = str.ToString(err); uint64_t limit = source_str.length(); uint64_t length = 0; uint64_t line_i = 0; uint64_t i = 0; for (; i < limit && lines_found < line_limit; i++) { // \r\n should ski adding a line and column on \r if (source_str[i] == '\r' && i < limit - 1 && source_str[i + 1] == '\n') { i++; } if (source_str[i] == '\n' || source_str[i] == '\r') { if (line_i >= start_line) { lines[lines_found] = std::string(source_str, i - length, length); lines_found++; } line_i++; length = 0; } else { length++; } } if (line_i >= start_line && length != 0 && lines_found < line_limit) { lines[lines_found] = std::string(source_str, limit - length, length); lines_found++; } } void Script::GetLineColumnFromPos(int64_t pos, int64_t& line, int64_t& column, Error& err) { line = 0; column = 0; HeapObject source = Source(err); if (err.Fail()) return; int64_t type = source.GetType(err); if (err.Fail()) return; // No source if (type > v8()->types()->kFirstNonstringType) { err = Error(true, "No source"); return; } String str(source); std::string source_str = str.ToString(err); int64_t limit = source_str.length(); if (limit > pos) limit = pos; for (int64_t i = 0; i < limit; i++, column++) { // \r\n should ski adding a line and column on \r if (source_str[i] == '\r' && i < limit - 1 && source_str[i + 1] == '\n') { i++; } if (source_str[i] == '\n' || source_str[i] == '\r') { column = 0; line++; } } } bool Value::IsHoleOrUndefined(Error& err) { HeapObject obj(this); if (!obj.Check()) return false; int64_t type = obj.GetType(err); if (err.Fail()) return false; if (type != v8()->types()->kOddballType) return false; Oddball odd(this); return odd.IsHoleOrUndefined(err); } // TODO(indutny): deduplicate this? bool Value::IsHole(Error& err) { HeapObject obj(this); if (!obj.Check()) return false; int64_t type = obj.GetType(err); if (err.Fail()) return false; if (type != v8()->types()->kOddballType) return false; Oddball odd(this); return odd.IsHole(err); } std::string Value::GetTypeName(Error& err) { Smi smi(this); if (smi.Check()) return "(Smi)"; HeapObject obj(this); if (!obj.Check()) { err = Error::Failure("Not object and not smi"); return std::string(); } return obj.GetTypeName(err); } std::string Value::ToString(Error& err) { Smi smi(this); if (smi.Check()) return smi.ToString(err); HeapObject obj(this); if (!obj.Check()) { err = Error::Failure("Not object and not smi"); return std::string(); } return obj.ToString(err); } std::string HeapObject::ToString(Error& err) { int64_t type = GetType(err); if (err.Fail()) return std::string(); if (type == v8()->types()->kHeapNumberType) { HeapNumber n(this); return n.ToString(false, err); } if (type < v8()->types()->kFirstNonstringType) { String str(this); return str.ToString(err); } if (type == v8()->types()->kSymbolType) { Symbol symbol(this); return symbol.ToString(err); } return "<non-string>"; } std::string Smi::ToString(Error& err) { char buf[128]; snprintf(buf, sizeof(buf), "%d", static_cast<int>(GetValue())); err = Error::Ok(); return buf; } /* Utility function to generate short type names for objects. */ std::string HeapObject::GetTypeName(Error& err) { int64_t type = GetType(err); if (type == v8()->types()->kGlobalObjectType) return "(Global)"; if (type == v8()->types()->kGlobalProxyType) return "(Global proxy)"; if (type == v8()->types()->kCodeType) return "(Code)"; if (type == v8()->types()->kMapType) { return "(Map)"; } if (type >= v8()->types()->kFirstContextType && type <= v8()->types()->kLastContextType) { return "Context"; } if (JSObject::IsObjectType(v8(), type)) { v8::HeapObject map_obj = GetMap(err); if (err.Fail()) { return std::string(); } v8::Map map(map_obj); v8::HeapObject constructor_obj = map.Constructor(err); if (err.Fail()) { return std::string(); } int64_t constructor_type = constructor_obj.GetType(err); if (err.Fail()) { return std::string(); } if (constructor_type != v8()->types()->kJSFunctionType) { return "(Object)"; } v8::JSFunction constructor(constructor_obj); return constructor.Name(err); } if (type == v8()->types()->kHeapNumberType) { return "(HeapNumber)"; } if (type == v8()->types()->kJSArrayType) { return "(Array)"; } if (type == v8()->types()->kOddballType) { return "(Oddball)"; } if (type == v8()->types()->kJSFunctionType) { return "(Function)"; } if (type == v8()->types()->kJSRegExpType) { return "(RegExp)"; } if (type < v8()->types()->kFirstNonstringType) { return "(String)"; } if (type == v8()->types()->kFixedArrayType) { return "(FixedArray)"; } if (type == v8()->types()->kJSArrayBufferType) { return "(ArrayBuffer)"; } if (type == v8()->types()->kJSTypedArrayType) { return "(ArrayBufferView)"; } if (type == v8()->types()->kJSDateType) { return "(Date)"; } std::string unknown("unknown: "); return unknown + std::to_string(type); } std::string HeapNumber::ToString(bool whole, Error& err) { char buf[128]; const char* fmt = whole ? "%f" : "%.2f"; snprintf(buf, sizeof(buf), fmt, GetValue(err)); err = Error::Ok(); return buf; } std::string JSDate::ToString(Error& err) { v8::Value val(GetValue(err)); // Check if it is SMI // e.g: date = new Date(1) v8::Smi smi(val); if (smi.Check()) { std::string s = smi.ToString(err); if (err.Fail()) return ""; return s; } // Check if it is HeapNumber // e.g: date = new Date() v8::HeapNumber hn(val); if (hn.Check()) { std::string s = hn.ToString(true, err); if (err.Fail()) return ""; return s; } PRINT_DEBUG("JSDate is not a Smi neither a HeapNumber"); return ""; } std::string Symbol::ToString(Error& err) { if (!String::IsString(v8(), Name(err), err)) { return "Symbol()"; } HeapObject name = Name(err); return "Symbol('" + String(name).ToString(err) + "')"; } std::string String::ToString(Error& err) { CheckedType<int64_t> repr = Representation(err); RETURN_IF_INVALID(repr, std::string()); int64_t encoding = Encoding(err); if (err.Fail()) return std::string(); if (*repr == v8()->string()->kSeqStringTag) { if (encoding == v8()->string()->kOneByteStringTag) { OneByteString one(this); return one.ToString(err); } else if (encoding == v8()->string()->kTwoByteStringTag) { TwoByteString two(this); return two.ToString(err); } err = Error::Failure("Unsupported seq string encoding %" PRId64, encoding); return std::string(); } if (*repr == v8()->string()->kConsStringTag) { ConsString cons(this); return cons.ToString(err); } if (*repr == v8()->string()->kSlicedStringTag) { SlicedString sliced(this); return sliced.ToString(err); } // TODO(indutny): add support for external strings if (*repr == v8()->string()->kExternalStringTag) { return std::string("(external)"); } if (*repr == v8()->string()->kThinStringTag) { ThinString thin(this); return thin.ToString(err); } err = Error::Failure("Unsupported string representation %" PRId64, *repr); return std::string(); } // Context locals iterator implementations Context::Locals::Locals(Context* context, Error& err) { context_ = context; HeapObject scope_obj = context_->GetScopeInfo(err); if (err.Fail()) return; scope_info_ = ScopeInfo(scope_obj); Smi local_count_smi = scope_info_.ContextLocalCount(err); if (err.Fail()) return; local_count_ = local_count_smi.GetValue(); } Context::Locals::Iterator Context::Locals::begin() { return Iterator(0, this); } Context::Locals::Iterator Context::Locals::end() { return Iterator(local_count_, this); } const Context::Locals::Iterator Context::Locals::Iterator::operator++(int) { current_++; return Iterator(current_, this->outer_); } bool Context::Locals::Iterator::operator!=(Context::Locals::Iterator that) { return current_ != that.current_ || outer_->context_ != that.outer_->context_; } v8::Value Context::Locals::Iterator::operator*() { Error err; return outer_->context_->ContextSlot(current_, err); } String Context::Locals::Iterator::LocalName(Error& err) { return outer_->scope_info_.ContextLocalName(current_, err); } Value Context::Locals::Iterator::GetValue(Error& err) { return outer_->context_->ContextSlot(current_, err); } HeapObject Map::Constructor(Error& err) { Map current = this; do { HeapObject obj = current.MaybeConstructor(err); if (err.Fail()) return current; int64_t type = obj.GetType(err); if (err.Fail()) return current; current = obj; if (type != v8()->types()->kMapType) break; } while (true); return current; } /* Returns the set of keys on an object - similar to Object.keys(obj) in * Javascript. That includes array indices but not special fields like * "length" on an array. */ void JSObject::Keys(std::vector<std::string>& keys, Error& err) { keys.clear(); // First handle array indices. ElementKeys(keys, err); HeapObject map_obj = GetMap(err); Map map(map_obj); bool is_dict = map.IsDictionary(err); if (err.Fail()) return; if (is_dict) { DictionaryKeys(keys, err); } else { DescriptorKeys(keys, map, err); } return; } std::vector<std::pair<Value, Value>> JSObject::Entries(Error& err) { HeapObject map_obj = GetMap(err); Map map(map_obj); bool is_dict = map.IsDictionary(err); if (err.Fail()) return {}; if (is_dict) { return DictionaryEntries(err); } else { return DescriptorEntries(map, err); } } std::vector<std::pair<Value, Value>> JSObject::DictionaryEntries(Error& err) { HeapObject dictionary_obj = Properties(err); if (err.Fail()) return {}; NameDictionary dictionary(dictionary_obj); int64_t length = dictionary.Length(err); if (err.Fail()) return {}; std::vector<std::pair<Value, Value>> entries; for (int64_t i = 0; i < length; i++) { Value key = dictionary.GetKey(i, err); if (err.Fail()) return entries; // Skip holes bool is_hole = key.IsHoleOrUndefined(err); if (err.Fail()) return entries; if (is_hole) continue; Value value = dictionary.GetValue(i, err); entries.push_back(std::pair<Value, Value>(key, value)); } return entries; } std::vector<std::pair<Value, Value>> JSObject::DescriptorEntries(Map map, Error& err) { HeapObject descriptors_obj = map.InstanceDescriptors(err); if (err.Fail()) return {}; DescriptorArray descriptors(descriptors_obj); int64_t own_descriptors_count = map.NumberOfOwnDescriptors(err); if (err.Fail()) return {}; int64_t in_object_count = map.InObjectProperties(err); if (err.Fail()) return {}; int64_t instance_size = map.InstanceSize(err); if (err.Fail()) return {}; HeapObject extra_properties_obj = Properties(err); if (err.Fail()) return {}; FixedArray extra_properties(extra_properties_obj); std::vector<std::pair<Value, Value>> entries; for (int64_t i = 0; i < own_descriptors_count; i++) { Smi details = descriptors.GetDetails(i, err); if (err.Fail()) continue; Value key = descriptors.GetKey(i, err); if (err.Fail()) continue; if (descriptors.IsConstFieldDetails(details) || descriptors.IsDescriptorDetails(details)) { Value value; value = descriptors.GetValue(i, err); if (err.Fail()) continue; entries.push_back(std::pair<Value, Value>(key, value)); continue; } // Skip non-fields for now, Object.keys(obj) does // not seem to return these (for example the "length" // field on an array). if (!descriptors.IsFieldDetails(details)) continue; if (descriptors.IsDoubleField(details)) continue; int64_t index = descriptors.FieldIndex(details) - in_object_count; Value value; if (index < 0) { value = GetInObjectValue<Value>(instance_size, index, err); } else { value = extra_properties.Get<Value>(index, err); } entries.push_back(std::pair<Value, Value>(key, value)); } return entries; } void JSObject::ElementKeys(std::vector<std::string>& keys, Error& err) { HeapObject elements_obj = Elements(err); if (err.Fail()) return; FixedArray elements(elements_obj); Smi length_smi = elements.Length(err); if (err.Fail()) return; int64_t length = length_smi.GetValue(); for (int i = 0; i < length; ++i) { // Add keys for anything that isn't a hole. Value value = elements.Get<Value>(i, err); if (err.Fail()) continue; ; bool is_hole = value.IsHole(err); if (err.Fail()) continue; if (!is_hole) { keys.push_back(std::to_string(i)); } } } void JSObject::DictionaryKeys(std::vector<std::string>& keys, Error& err) { HeapObject dictionary_obj = Properties(err); if (err.Fail()) return; NameDictionary dictionary(dictionary_obj); int64_t length = dictionary.Length(err); if (err.Fail()) return; for (int64_t i = 0; i < length; i++) { Value key = dictionary.GetKey(i, err); if (err.Fail()) return; // Skip holes bool is_hole = key.IsHoleOrUndefined(err); if (err.Fail()) return; if (is_hole) continue; std::string key_name = key.ToString(err); if (err.Fail()) { // TODO - should I continue onto the next key here instead. return; } keys.push_back(key_name); } } void JSObject::DescriptorKeys(std::vector<std::string>& keys, Map map, Error& err) { HeapObject descriptors_obj = map.InstanceDescriptors(err); if (err.Fail()) return; DescriptorArray descriptors(descriptors_obj); int64_t own_descriptors_count = map.NumberOfOwnDescriptors(err); if (err.Fail()) return; for (int64_t i = 0; i < own_descriptors_count; i++) { Smi details = descriptors.GetDetails(i, err); if (err.Fail()) return; Value key = descriptors.GetKey(i, err); if (err.Fail()) return; // Skip non-fields for now, Object.keys(obj) does // not seem to return these (for example the "length" // field on an array). if (!descriptors.IsFieldDetails(details)) { continue; } std::string key_name = key.ToString(err); if (err.Fail()) { // TODO - should I continue onto the next key here instead. return; } keys.push_back(key_name); } } /* Return the v8 value for a property stored using the given key. * (Caller should have some idea of what type of object will be stored * in that key, they will get a v8::Value back that they can cast.) */ Value JSObject::GetProperty(std::string key_name, Error& err) { HeapObject map_obj = GetMap(err); if (err.Fail()) Value(); Map map(map_obj); bool is_dict = map.IsDictionary(err); if (err.Fail()) return Value(); if (is_dict) { return GetDictionaryProperty(key_name, err); } else { return GetDescriptorProperty(key_name, map, err); } if (err.Fail()) return Value(); // Nothing's gone wrong, we just didn't find the key. return Value(); } Value JSObject::GetDictionaryProperty(std::string key_name, Error& err) { HeapObject dictionary_obj = Properties(err); if (err.Fail()) return Value(); NameDictionary dictionary(dictionary_obj); int64_t length = dictionary.Length(err); if (err.Fail()) return Value(); for (int64_t i = 0; i < length; i++) { Value key = dictionary.GetKey(i, err); if (err.Fail()) return Value(); // Skip holes bool is_hole = key.IsHoleOrUndefined(err); if (err.Fail()) return Value(); if (is_hole) continue; if (key.ToString(err) == key_name) { Value value = dictionary.GetValue(i, err); if (err.Fail()) return Value(); return value; } } return Value(); } Value JSObject::GetDescriptorProperty(std::string key_name, Map map, Error& err) { HeapObject descriptors_obj = map.InstanceDescriptors(err); if (err.Fail()) return Value(); DescriptorArray descriptors(descriptors_obj); int64_t own_descriptors_count = map.NumberOfOwnDescriptors(err); if (err.Fail()) return Value(); int64_t in_object_count = map.InObjectProperties(err); if (err.Fail()) return Value(); int64_t instance_size = map.InstanceSize(err); if (err.Fail()) return Value(); HeapObject extra_properties_obj = Properties(err); if (err.Fail()) return Value(); FixedArray extra_properties(extra_properties_obj); for (int64_t i = 0; i < own_descriptors_count; i++) { Smi details = descriptors.GetDetails(i, err); if (err.Fail()) return Value(); Value key = descriptors.GetKey(i, err); if (err.Fail()) return Value(); if (key.ToString(err) != key_name) { continue; } // Found the right key, get the value. if (err.Fail()) return Value(); if (descriptors.IsConstFieldDetails(details) || descriptors.IsDescriptorDetails(details)) { Value value; value = descriptors.GetValue(i, err); if (err.Fail()) return Value(); continue; } // Skip non-fields for now if (!descriptors.IsFieldDetails(details)) { // This path would return the length field for an array, // however Object.keys(arr) doesn't return length as a // field so neither do we. continue; } int64_t index = descriptors.FieldIndex(details) - in_object_count; if (descriptors.IsDoubleField(details)) { double value; if (index < 0) { value = GetInObjectValue<double>(instance_size, index, err); } else { value = extra_properties.Get<double>(index, err); } if (err.Fail()) return Value(); } else { Value value; if (index < 0) { value = GetInObjectValue<Value>(instance_size, index, err); } else { value = extra_properties.Get<Value>(index, err); } if (err.Fail()) { return Value(); } else { return value; }; } if (err.Fail()) return Value(); } return Value(); } /* An array is also an object so this method is on JSObject * not JSArray. */ int64_t JSObject::GetArrayLength(Error& err) { HeapObject elements_obj = Elements(err); if (err.Fail()) return 0; FixedArray elements(elements_obj); Smi length_smi = elements.Length(err); if (err.Fail()) return 0; int64_t length = length_smi.GetValue(); return length; } /* An array is also an object so this method is on JSObject * not JSArray. * Note that you the user should know what the expect the array to contain * and should check they haven't been returned a hole. */ v8::Value JSObject::GetArrayElement(int64_t pos, Error& err) { if (pos < 0) { // TODO - Set err.Fail()? return Value(); } HeapObject elements_obj = Elements(err); if (err.Fail()) return Value(); FixedArray elements(elements_obj); Smi length_smi = elements.Length(err); if (err.Fail()) return Value(); int64_t length = length_smi.GetValue(); if (pos >= length) { return Value(); } Value value = elements.Get<v8::Value>(pos, err); if (err.Fail()) return Value(); return value; } bool JSError::HasStackTrace(Error& err) { StackTrace stack_trace = GetStackTrace(err); return stack_trace.GetFrameCount() > -1; } JSArray JSError::GetFrameArray(Error& err) { v8::Value maybe_stack = GetProperty(stack_trace_property(), err); if (err.Fail() || maybe_stack.raw() == -1) { PRINT_DEBUG("Couldn't find a symbol property in the Error object."); return JSArray(); } int64_t type = v8::HeapObject(maybe_stack).GetType(err); if (err.Fail()) { PRINT_DEBUG("Symbol property references an invalid object."); return JSArray(); } // NOTE (mmarchini): The stack is stored as a JSArray if (type != v8()->types()->kJSArrayType) { PRINT_DEBUG("Symbol property doesn't have the right type."); return JSArray(); } v8::JSArray arr(maybe_stack); return arr; } StackTrace::Iterator StackTrace::begin() { Error err; return StackTrace::Iterator(this, err); } StackTrace::Iterator StackTrace::end() { Error err; return StackTrace::Iterator(this, GetFrameCount(), err); } StackTrace::StackTrace(JSArray frame_array, Error& err) : frame_array_(frame_array) { if (!frame_array.Check()) { PRINT_DEBUG("JS Array is not a valid object"); len_ = -1; multiplier_ = -1; return; } v8::Value maybe_stack_len = frame_array.GetArrayElement(0, err); if (err.Fail()) { PRINT_DEBUG("Couldn't get the first element from the stack array"); return; } len_ = v8::Smi(maybe_stack_len).GetValue(); multiplier_ = 5; // On Node.js v8.x, the first array element is the stack size, and each // stack frame use 5 elements. if ((len_ * multiplier_ + 1) != frame_array_.GetArrayLength(err)) { // On Node.js v6.x, the first array element is zero, and each stack frame // use 4 element. multiplier_ = 4; if ((len_ != 0) || ((frame_array_.GetArrayLength(err) - 1) % multiplier_ != 0)) { PRINT_DEBUG( "JSArray doesn't look like a Stack Frames array. stack_len: %d " "array_len: %ld", len_, frame_array_.GetArrayLength(err)); len_ = -1; multiplier_ = -1; return; } len_ = (frame_array_.GetArrayLength(err) - 1) / multiplier_; } } StackTrace JSError::GetStackTrace(Error& err) { return StackTrace(GetFrameArray(err), err); } StackFrame StackTrace::GetFrame(uint32_t index, Error& err) { return StackFrame(this, index); } StackFrame::StackFrame(StackTrace* stack_trace, int index) : stack_trace_(stack_trace), index_(index) {} JSFunction StackFrame::GetFunction(Error& err) { JSArray frame_array = stack_trace_->frame_array_; v8::Value maybe_fn = frame_array.GetArrayElement(frame_array_index(), err); if (err.Fail()) return JSFunction(); return JSFunction(maybe_fn); } int StackFrame::frame_array_index() { int multiplier = stack_trace_->multiplier_; const int js_function_pos = 1; const int begin_offset = 1; return begin_offset + js_function_pos + (index_ * multiplier); } } // namespace v8 } // namespace llnode
25.661538
80
0.636805
[ "object", "vector" ]
1554af0b07ad3323fadf17de9387e2ecc79ca8c1
2,244
cpp
C++
Classes/Pipes.cpp
shivmsit/FlappyBird-cocos2dx
82c5199c47bde5b751fe6742aa9f1c1e25d48f8b
[ "Apache-2.0" ]
2
2020-11-17T14:49:41.000Z
2021-09-29T16:28:29.000Z
Classes/Pipes.cpp
shivmsit/FlappyBird-cocos2dx
82c5199c47bde5b751fe6742aa9f1c1e25d48f8b
[ "Apache-2.0" ]
null
null
null
Classes/Pipes.cpp
shivmsit/FlappyBird-cocos2dx
82c5199c47bde5b751fe6742aa9f1c1e25d48f8b
[ "Apache-2.0" ]
1
2021-08-20T14:52:01.000Z
2021-08-20T14:52:01.000Z
#include "Pipes.h" #include "Settings.h" #include "PhysicsHelper.h" Pipes* Pipes::create() { Pipes* pipes = new (std::nothrow) Pipes(); if (pipes && pipes->init()) { pipes->autorelease(); return pipes; } CC_SAFE_DELETE(pipes); return nullptr; } bool Pipes::init() { if (!Node::init()) return false; auto visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); _top = Sprite::createWithSpriteFrameName("pipe_green_top.png"); auto shape = PhysicsShapeBox::create(_top->getContentSize()); _top->setPhysicsBody(createBody(shape, false, false, PIPE_BIT, BIRD_BIT, BIRD_BIT)); _top->setPosition(Vec2(0, _top->getContentSize().height/2.0f + PIPE_VERTICAL_GAP/2.0f)); _bottom = Sprite::createWithSpriteFrameName("pipe_green_bottom.png"); shape = PhysicsShapeBox::create(_bottom->getContentSize()); _bottom->setPhysicsBody(createBody(shape, false, false, PIPE_BIT, BIRD_BIT, BIRD_BIT)); _bottom->setPosition(Vec2(0, -_bottom->getContentSize().height/2.0f - PIPE_VERTICAL_GAP/2.0f)); // add these sprite as a child to this layer addChild(_top, 0); addChild(_bottom, 0); //Add physics body to detect if bird has crossed the pipe and add score auto node = Node::create(); auto edgeSegment = PhysicsShapeEdgeSegment::create(Vec2(0, PIPE_VERTICAL_GAP/2.0f), Vec2(0, -PIPE_VERTICAL_GAP/2.0f)); _coin = createBody(edgeSegment, false, false, COIN_BIT, BIRD_BIT, BIRD_BIT); node->setPhysicsBody(_coin); addChild(node); return true; } /* * Set whether physics for coin colleciton is enabled, this is neccesory to * disable it once a coin is collected otherwise same coin can be collected * multiple time due to physics bounces. */ void Pipes::setCoinPhysicsEnabled(bool enable) { _coin->setEnabled(enable); } void Pipes::setPhysicsEnabled(bool enable) { _top->getPhysicsBody()->setEnabled(enable); _bottom->getPhysicsBody()->setEnabled(enable); _coin->setEnabled(enable); } void Pipes::setTag(int tag) { _top->getPhysicsBody()->setTag(tag); _bottom->getPhysicsBody()->setTag(tag); } Pipes::Pipes() { } Pipes::~Pipes() { }
27.703704
122
0.691176
[ "shape" ]
155723c9e7550fd5fe4d3f6f92c56fca96f25bb8
1,042
cpp
C++
leetcode/0228_Summary_Ranges/result.cpp
theck17/notes
f32f0f4b8f821b1ed38d173ef0913efddd094b91
[ "MIT" ]
null
null
null
leetcode/0228_Summary_Ranges/result.cpp
theck17/notes
f32f0f4b8f821b1ed38d173ef0913efddd094b91
[ "MIT" ]
null
null
null
leetcode/0228_Summary_Ranges/result.cpp
theck17/notes
f32f0f4b8f821b1ed38d173ef0913efddd094b91
[ "MIT" ]
null
null
null
/** * Copyright (C) 2021 All rights reserved. * * FileName :result.cpp * Author :C.K * Email :theck17@163.com * DateTime :2021-06-21 19:07:40 * Description : */ #include <algorithm> //STL 通用算法 #include <streambuf> //底层输入/输出支持 #include <string> //字符串类 #include <vector> //STL 动态数组容器 #include <valarray> //对包含值的数组的操作 #include <ctime> //定义关于时间的函数 using namespace std; class Solution { public: vector<string> summaryRanges(vector<int>& nums) { const int size_n = nums.size(); vector<string> res; if ( 0 == size_n) return res; for (int i = 0; i < size_n;) { int start = i, end = i; while (end + 1 < size_n && nums[end+1] == nums[end] + 1) end++; if (end > start) res.push_back(to_string(nums[start]) + "->" + to_string(nums[end])); else res.push_back(to_string(nums[start])); i = end+1; } return res; } }; int main(){ return 0; }
27.421053
97
0.525912
[ "vector" ]
155e9243293bd0490eb72bbed45dd90c5a4d711e
1,756
cpp
C++
source/toneMapper/photographicGlobalToneMapper.cpp
xh5a5n6k6/High-Dynamic-Range-Imaging
a2bbb85f39d1e1a524ab8f4b0022ca9a7e3de188
[ "MIT" ]
5
2019-04-04T15:14:13.000Z
2020-03-25T15:13:31.000Z
source/toneMapper/photographicGlobalToneMapper.cpp
xh5a5n6k6/High-Dynamic-Range-Imaging
a2bbb85f39d1e1a524ab8f4b0022ca9a7e3de188
[ "MIT" ]
null
null
null
source/toneMapper/photographicGlobalToneMapper.cpp
xh5a5n6k6/High-Dynamic-Range-Imaging
a2bbb85f39d1e1a524ab8f4b0022ca9a7e3de188
[ "MIT" ]
2
2020-05-30T07:47:51.000Z
2020-09-19T11:28:32.000Z
#include "toneMapper/photographicGlobalToneMapper.h" #include <cmath> #include <iostream> namespace shdr { PhotographicGlobalToneMapper::PhotographicGlobalToneMapper() : PhotographicGlobalToneMapper(0.7f, 0.000001f) { } PhotographicGlobalToneMapper::PhotographicGlobalToneMapper(const float alpha, const float delta) : _alpha(alpha), _delta(delta) { } void PhotographicGlobalToneMapper::map(const cv::Mat& hdri, cv::Mat* const out_ldri) const { std::cout << "# Begin to implement tone mapping using photographic global method" << std::endl; cv::Mat ldri = hdri.clone(); cv::Mat lw; cv::Mat logLw; cv::Mat lm; cv::Mat ld; cv::cvtColor(hdri, lw, cv::COLOR_BGR2GRAY); cv::log(lw + _delta, logLw); const float meanLogLw = static_cast<float>(cv::mean(logLw)[0]); const float meanLw = std::exp(meanLogLw); const float invMeanLw = 1.0f / meanLw; lm = _alpha * invMeanLw * lw; double min; double max; cv::minMaxLoc(lm, &min, &max); const float lWhite = static_cast<float>(max); const float invLWhite2 = 1.0f / (lWhite * lWhite); const cv::Mat up = 1.0f + lm * invLWhite2; const cv::Mat down = 1.0f + lm; cv::divide(up, down, ld); ld = ld.mul(lm); /* calculate each channel */ std::vector<cv::Mat> vecMat; cv::split(ldri, vecMat); for (int c = 0; c < 3; ++c) { cv::divide(vecMat[c], lw, vecMat[c]); vecMat[c] = vecMat[c].mul(ld); } cv::merge(vecMat, ldri); ldri *= 255.0f; ldri.convertTo(ldri, CV_8UC3); *out_ldri = ldri; std::cout << "# Finish implementing tone mapping" << std::endl; } } // namespace shdr
25.823529
98
0.604784
[ "vector" ]
15630ee892067c844903328635aa95d43f27380c
386
cpp
C++
SORTING/Easy/Intersection of Two Arrays/Code.cpp
HassanRahim26/LEETCODE
c0ec81b037ff7b2d6e6030ac9835c21ed825100f
[ "MIT" ]
3
2021-08-31T11:02:28.000Z
2022-01-17T08:07:00.000Z
SORTING/Easy/Intersection of Two Arrays/Code.cpp
HassanRahim26/LEETCODE
c0ec81b037ff7b2d6e6030ac9835c21ed825100f
[ "MIT" ]
null
null
null
SORTING/Easy/Intersection of Two Arrays/Code.cpp
HassanRahim26/LEETCODE
c0ec81b037ff7b2d6e6030ac9835c21ed825100f
[ "MIT" ]
null
null
null
/* PROBLEM LINK:- https://leetcode.com/problems/intersection-of-two-arrays/ */ class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { set<int> s(nums1.begin(), nums1.end()); vector<int> ans; for(int x : nums2) { if(s.erase(x)) ans.push_back(x); } return ans; } };
21.444444
72
0.533679
[ "vector" ]
d07eecb772d0e7a32afd3d0508fb1d031b4b81fa
591
cc
C++
cpp/Codeforces/1-50/41A_Translation.cc
phongvcao/CP_Contests_Solutions
2e76e73ee7e53c798f63e1870be47653c75180a9
[ "MIT" ]
null
null
null
cpp/Codeforces/1-50/41A_Translation.cc
phongvcao/CP_Contests_Solutions
2e76e73ee7e53c798f63e1870be47653c75180a9
[ "MIT" ]
null
null
null
cpp/Codeforces/1-50/41A_Translation.cc
phongvcao/CP_Contests_Solutions
2e76e73ee7e53c798f63e1870be47653c75180a9
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <sstream> #include <vector> int main(int argc, char **argv) { std::string line1 = ""; std::string line2 = ""; if (std::getline(std::cin, line1)) { } if (std::getline(std::cin, line2)) { } bool isCorrect = true; for (unsigned int i = 0; i != line1.length(); ++i) { if (line1[i] != line2[line1.length() - 1 - i]) { isCorrect = false; break; } } if (isCorrect) { std::cout << "YES"; } else { std::cout << "NO"; } return 0; }
15.972973
56
0.478849
[ "vector" ]
d081dbea40b12a22963b8688788840c04921decb
3,919
hpp
C++
include/dish2/services_threadlocal/DiversityMaintenanceService.hpp
mmore500/dishtiny
9fcb52c4e56c74a4e17f7d577143ed40c158c92e
[ "MIT" ]
29
2019-02-04T02:39:52.000Z
2022-01-28T10:06:26.000Z
include/dish2/services_threadlocal/DiversityMaintenanceService.hpp
mmore500/dishtiny
9fcb52c4e56c74a4e17f7d577143ed40c158c92e
[ "MIT" ]
95
2020-02-22T19:48:14.000Z
2021-09-14T19:17:53.000Z
include/dish2/services_threadlocal/DiversityMaintenanceService.hpp
mmore500/dishtiny
9fcb52c4e56c74a4e17f7d577143ed40c158c92e
[ "MIT" ]
6
2019-11-19T10:13:09.000Z
2021-03-25T17:35:32.000Z
#pragma once #ifndef DISH2_SERVICES_THREADLOCAL_DIVERSITYMAINTENANCESERVICE_HPP_INCLUDE #define DISH2_SERVICES_THREADLOCAL_DIVERSITYMAINTENANCESERVICE_HPP_INCLUDE #include <algorithm> #include <cmath> #include "../../../third-party/conduit/include/uitsl/math/shift_mod.hpp" #include "../../../third-party/conduit/include/uitsl/polyfill/identity.hpp" #include "../cell/cardinal_iterators/ResourceStockpileWrapper.hpp" #include "../config/cfg.hpp" #include "../debug/LogScope.hpp" #include "../enum/CauseOfDeath.hpp" #include "../introspection/count_live_cells.hpp" #include "../introspection/get_root_id_counts.hpp" #include "../world/iterators/LiveCellIterator.hpp" #include "../world/iterators/RootIDValWrapper.hpp" namespace dish2 { /** * Prevents any one originally-generated ancestor from sweeping the population, * preserving deep phylogenetic diversity. * * Counts cells that descend from each originally-generated ancestor. If more * than `DIVERSITY_MAINTENANCE_PREVALENCE` of cells descend from a single * originally-generated ancestor, decay their resource stockpiles. The * magnitude of this effect increases with excess prevalence. */ struct DiversityMaintenanceService { static bool ShouldRun( const size_t update ) { const size_t freq = dish2::cfg.DIVERSITY_MAINTENANCE_SERVICE_FREQUENCY(); return freq > 0 && uitsl::shift_mod( update, freq ) == 0 && dish2::cfg.GENESIS() != "innoculate" && dish2::cfg.GENESIS() != "monoculture" ; } template<typename ThreadWorld> static void DoService( ThreadWorld& thread_world, const size_t ) { using spec_t = typename ThreadWorld::spec_t; const dish2::LogScope guard{ "diversity maintentance service", "TODO", 3 }; auto& population = thread_world.population; const auto root_id_counts = dish2::get_root_id_counts( thread_world ); const size_t threshold_count = ( dish2::cfg.DIVERSITY_MAINTENANCE_PREVALENCE() * static_cast<double>( dish2::count_live_cells( thread_world ) ) ); const auto begin = dish2::LiveCellIterator<spec_t>::make_begin(population); const auto end = dish2::LiveCellIterator<spec_t>::make_end(population); uitsl::for_each( begin, end, dish2::RootIDValWrapper{ begin }, [&root_id_counts, threshold_count]( auto& cell, const size_t root_id ){ const size_t count = root_id_counts.at( root_id ); if ( threshold_count && count > threshold_count ) { const size_t excess = count - threshold_count; const double excess_frac = excess / static_cast<double>( threshold_count ); emp_assert( excess_frac >= 0, excess_frac ); emp_assert( std::isfinite(excess_frac), excess_frac ); const double decay = std::max( 1.0 - excess_frac, 0.0 ); emp_assert( std::isfinite(decay), decay ); // update stockpiles to reflect decay std::transform( cell.template begin<dish2::ResourceStockpileWrapper<spec_t>>(), cell.template end<dish2::ResourceStockpileWrapper<spec_t>>(), cell.template begin<dish2::ResourceStockpileWrapper<spec_t>>(), [decay](const auto cur) { return cur * decay; } ); emp_assert( std::none_of( cell.template begin<dish2::ResourceStockpileWrapper<spec_t>>(), cell.template end<dish2::ResourceStockpileWrapper<spec_t>>(), []( const auto val ){ return std::isnan( val ); } ), decay ); emp_assert( std::none_of( cell.template begin<dish2::ResourceStockpileWrapper<spec_t>>(), cell.template end<dish2::ResourceStockpileWrapper<spec_t>>(), []( const auto val ){ return std::isinf( val ); } ), decay ); } } ); } }; } // namespace dish2 #endif // #ifndef DISH2_SERVICES_THREADLOCAL_DIVERSITYMAINTENANCESERVICE_HPP_INCLUDE
35.306306
84
0.685634
[ "transform" ]
d085da8b15538f97afb3621f9ef42700f04b1bb5
5,655
cpp
C++
src/hsp3/strnote.cpp
m4saka/OpenHSP
391f0a2100e701138d0610a5b94492d6f57ad1f2
[ "BSD-3-Clause" ]
127
2018-02-24T20:41:15.000Z
2022-03-22T05:57:56.000Z
src/hsp3/strnote.cpp
m4saka/OpenHSP
391f0a2100e701138d0610a5b94492d6f57ad1f2
[ "BSD-3-Clause" ]
21
2018-09-11T15:04:22.000Z
2022-02-03T09:30:16.000Z
src/hsp3/strnote.cpp
m4saka/OpenHSP
391f0a2100e701138d0610a5b94492d6f57ad1f2
[ "BSD-3-Clause" ]
21
2019-03-28T07:49:44.000Z
2021-12-25T02:49:07.000Z
/*----------------------------------------------------------------*/ // notepad object related routines // (CR/LFだけでなくLFにも対応した版) /*----------------------------------------------------------------*/ #include <string.h> #include "hsp3config.h" #include "strnote.h" #include "supio.h" #if defined(HSPLINUX) || defined(HSPMAC) || defined(HSPIOS) || defined(HSPNDK) || defined(HSPEMSCRIPTEN) // LFを改行として扱う #define MATCH_LF #define CRSTR "\n" #else // CR/LFを改行として扱う #define CRSTR "\r\n" #endif //------------------------------------------------------------- // Interfaces //------------------------------------------------------------- CStrNote::CStrNote() { base = NULL; nulltmp[0] = 0; } CStrNote::~CStrNote() { } void CStrNote::Select( char *str ) { base = str; } int CStrNote::GetSize( void ) { return (int)strlen( base ); } //------------------------------------------------------------- // Routines //------------------------------------------------------------- int CStrNote::nnget( char *nbase, int line ) { // 指定した行の先頭ポインタを求める // nn = 先頭ポインタ // lastcr : CR/LFで終了している // line : line number(-1=最終行) // result:0=ok/1=no line // int a,i; char a1; a=0; lastcr=0; nn=nbase; if (line<0) { i=(int)strlen(nbase);if (i==0) return 0; nn+=i;a1=*(nn-1); if ((a1==10)||(a1==13)) lastcr++; return 0; } if (line) { while(1) { a1=*nn;if (a1==0) return 1; nn++; #ifdef MATCH_LF if (a1==10) { a++;if (a==line) break; } #endif if (a1==13) { if (*nn==10) nn++; a++;if (a==line) break; } } } lastcr++; return 0; } int CStrNote::GetLine( char *nres, int line ) { // Get specified line from note // result:0=ok/1=no line // char a1; char *pp; pp=nres; if ( nnget( base,line ) ) return 1; if (*nn==0) return 1; while(1) { a1=*nn++; if ((a1==0)||(a1==13)) break; #ifdef MATCH_LF if (a1==10) break; #endif *pp++=a1; } *pp=0; return 0; } int CStrNote::GetLine( char *nres, int line, int max ) { // Get specified line from note // result:0=ok/1=no line // char a1; char *pp; int cnt; pp=nres; cnt = 0; if ( nnget( base,line ) ) return 1; if (*nn==0) return 1; while(1) { if ( cnt>=max ) break; a1=*nn++; if ((a1==0)||(a1==13)) break; #ifdef MATCH_LF if (a1==10) break; #endif *pp++=a1; cnt++; } *pp=0; return 0; } char *CStrNote::GetLineDirect( int line ) { // Get specified line from note // char a1; if ( nnget( base,line ) ) nn = nulltmp; lastnn = nn; while(1) { a1=*lastnn; if ((a1==0)||(a1==13)) break; #ifdef MATCH_LF if (a1==10) break; #endif lastnn++; } lastcode = a1; *lastnn = 0; return nn; } void CStrNote::ResumeLineDirect( void ) { // Resume last GetLineDirect function // *lastnn = lastcode; } int CStrNote::GetMaxLine( void ) { // Get total lines // int a,b; char a1; a=1;b=0; nn=base; while(1) { a1=*nn++;if (a1==0) break; #ifdef MATCH_LF if ((a1==13)||(a1==10)) { if (a1==13&&*nn==10) nn++; #else if (a1==13) { if (*nn==10) nn++; #endif a++;b=0; } else b++; } if (b==0) a--; return a; } int CStrNote::PutLine( char *nstr2, int line, int ovr ) { // Pet specified line to note // result:0=ok/1=no line // int a = 0,ln,la,lw; char a1; char *pp; char *p1; char *p2; char *nstr; if ( nnget( base,line ) ) return 1; if (lastcr==0) { if ( nn != base ) { strcat( base, CRSTR );nn+=2; } } nstr = nstr2; if ( nstr == NULL ) { nstr=""; } pp=nstr; if ( nstr2 != NULL ) strcat(nstr, CRSTR ); ln=(int)strlen(nstr); // base new str + cr/lf la=(int)strlen(base); lw=la-(int)(nn-base)+1; // if (ovr) { // when overwrite mode p1=nn;a=0; while(1) { a1=*p1++;if (a1==0) break; a++; #ifdef MATCH_LF if ((a1==13)||(a1==10)) { if (a1==13&&*p1==10) { p1++;a++; } #else if (a1==13) { if (*p1==10) { p1++;a++; } #endif break; } } ln=ln-a; lw=lw-a;if (lw<1) lw=1; } // if (ln>=0) { p1=base+la+ln; p2=base+la; for(a=0;a<lw;a++) { *p1--=*p2--; } } else { p1=nn+a+ln;p2=nn+a; for(a=0;a<lw;a++) { *p1++=*p2++; } } // while(1) { a1=*pp++;if (a1==0) break; *nn++=a1; } return 0; } int CStrNote::FindLine( char *nstr, int mode ) { // Search string from note // nstr:search string // mode:STRNOTE_FIND_* // result:line number(-1:no match) // char a1; int curline, len, res; nn=base; curline = 0; len = 0; baseline = nn; // 行の先頭ポインタ while(1) { a1=*nn;if (a1==0) break; #ifdef MATCH_LF if (a1==10) { if ( len ) { lastcode = a1; *nn = 0; res = FindLineSub( nstr, mode ); *nn = lastcode; if ( res ) return curline; } nn++; curline++;len=0; baseline = nn; continue; } #endif if (a1==13) { if ( len ) { lastcode = a1; *nn = 0; res = FindLineSub( nstr, mode ); *nn = lastcode; if ( res ) return curline; } nn++; curline++;len=0; if (*nn==10) nn++; // LFをスキップ baseline = nn; continue; } nn++; len++; } // 最終行に文字列があればサーチ if ( len ) { if ( FindLineSub( nstr, mode ) ) return curline; } return -1; } int CStrNote::FindLineSub( char *nstr, int mode ) { // 全体サーチ用文字列比較 // mode : STRNOTE_FIND_MATCH = 完全一致 // STRNOTE_FIND_FIRST = 前方一致 // STRNOTE_FIND_INSTR = 部分一致 // switch( mode ) { case STRNOTE_FIND_MATCH: // 完全一致 if ( strcmp( baseline, nstr ) == 0 ) return 1; break; case STRNOTE_FIND_FIRST: // 前方一致 { char *p = strstr2( baseline, nstr ); if ( p != NULL ) { if ( p == baseline ) return 1; } break; } case STRNOTE_FIND_INSTR: // 部分一致 if ( strstr2( baseline, nstr ) != NULL ) return 1; break; default: break; } return 0; }
16.343931
104
0.51176
[ "object" ]
d096bf98c3e047dc05b6da1c68d47a0a698f4096
3,595
cpp
C++
packages/monte_carlo/collision/core/test/tstNuclearScatteringDistribution.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
10
2019-11-14T19:58:30.000Z
2021-04-04T17:44:09.000Z
packages/monte_carlo/collision/core/test/tstNuclearScatteringDistribution.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
43
2020-03-03T19:59:20.000Z
2021-09-08T03:36:08.000Z
packages/monte_carlo/collision/core/test/tstNuclearScatteringDistribution.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
6
2020-02-12T17:37:07.000Z
2020-09-08T18:59:51.000Z
//---------------------------------------------------------------------------// //! //! \file tstNuclearScatteringDistribution.cpp //! \author Alex Robinson //! \brief Nuclear scattering distribution unit tests //! //---------------------------------------------------------------------------// // Std Lib Includes #include <iostream> // FRENSIE Includes #include "MonteCarlo_NuclearScatteringDistribution.hpp" #include "MonteCarlo_NeutronState.hpp" #include "Utility_RandomNumberGenerator.hpp" #include "Utility_UnitTestHarnessWithMain.hpp" //---------------------------------------------------------------------------// // Testing Structs //---------------------------------------------------------------------------// class TestScatteringDistribution : public MonteCarlo::NuclearScatteringDistribution<MonteCarlo::NeutronState,MonteCarlo::NeutronState> { public: TestScatteringDistribution( const double atomic_weight_ratio ) : MonteCarlo::NuclearScatteringDistribution<MonteCarlo::NeutronState,MonteCarlo::NeutronState>( atomic_weight_ratio ) { /* ... */ } ~TestScatteringDistribution() { /* ... */ } void scatterParticle( const MonteCarlo::NeutronState& incoming_neutron, MonteCarlo::NeutronState& outgoing_neutron, const double temperature ) const { /* ... */ } // Allow public access to the protected member functions using MonteCarlo::NuclearScatteringDistribution<MonteCarlo::NeutronState,MonteCarlo::NeutronState>::getAtomicWeightRatio; using MonteCarlo::NuclearScatteringDistribution<MonteCarlo::NeutronState,MonteCarlo::NeutronState>::sampleAzimuthalAngle; }; //---------------------------------------------------------------------------// // Tests. //---------------------------------------------------------------------------// // Check that the atomic weight ratio can be returned FRENSIE_UNIT_TEST( NuclearScatteringDistribution, getAtomicWeightRatio ) { TestScatteringDistribution scattering_distribution( 2.0 ); FRENSIE_CHECK_EQUAL( scattering_distribution.getAtomicWeightRatio(), 2.0 ); } //---------------------------------------------------------------------------// // Check that the azimuthal angle can be sampled FRENSIE_UNIT_TEST( NuclearScatteringDistribution, sampleAzimuthalAngle ) { std::vector<double> fake_stream( 3 ); fake_stream[0] = 0.0; fake_stream[1] = 0.5; fake_stream[2] = 1.0 - 1e-15; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); TestScatteringDistribution scattering_distribution( 2.0 ); double azimuthal_angle = scattering_distribution.sampleAzimuthalAngle(); FRENSIE_CHECK_EQUAL( azimuthal_angle, 0.0 ); azimuthal_angle = scattering_distribution.sampleAzimuthalAngle(); FRENSIE_CHECK_EQUAL( azimuthal_angle, Utility::PhysicalConstants::pi ); azimuthal_angle = scattering_distribution.sampleAzimuthalAngle(); FRENSIE_CHECK_FLOATING_EQUALITY( azimuthal_angle, 2*Utility::PhysicalConstants::pi, 1e-15 ); } //---------------------------------------------------------------------------// // Custom Setup //---------------------------------------------------------------------------// FRENSIE_CUSTOM_UNIT_TEST_SETUP_BEGIN(); FRENSIE_CUSTOM_UNIT_TEST_INIT() { // Initialize the random number generator Utility::RandomNumberGenerator::createStreams(); } FRENSIE_CUSTOM_UNIT_TEST_SETUP_END(); //---------------------------------------------------------------------------// // tstNuclearScatteringDistribution.cpp //---------------------------------------------------------------------------//
37.447917
134
0.584423
[ "vector" ]
d096c43a239eb201f8e2b33e27b584030b7db154
584
cpp
C++
Practice code/Linked list/Queue/stock span problem/code.cpp
MythicalStack/Data-structure-CS201
83411ef3b29971df86ba27fc409003a9e492d99e
[ "Apache-2.0" ]
1
2021-08-10T11:45:10.000Z
2021-08-10T11:45:10.000Z
Practice code/Linked list/Queue/stock span problem/code.cpp
jkbells/Data-structure-CS201
83411ef3b29971df86ba27fc409003a9e492d99e
[ "Apache-2.0" ]
null
null
null
Practice code/Linked list/Queue/stock span problem/code.cpp
jkbells/Data-structure-CS201
83411ef3b29971df86ba27fc409003a9e492d99e
[ "Apache-2.0" ]
null
null
null
#include<bits/stdc++.h> #include<stack> using namespace std; vector<int> stockspan(vector<int> prices){ vector<int> ans; stack<pair<int,int>> s; for (auto price:prices){ int days = 1; while(!s.empty() and s.top().first <= price){ days += s.top().second; s.pop(); } s.push{(prices,days)}; ans.push_back(days); } return ans; } int main() { vector<int> a = {100,80,60,70,60,75,85}; vector<int> res = stockspan(a); for (auto i : res) cout << i << " "; cout << "\n"; return 0; }
20.137931
53
0.513699
[ "vector" ]
d09b07a153a40308848e2257eacf0bbc34bf82cb
13,264
cpp
C++
cfw/src/v20190904/model/SecurityGroupRule.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
cfw/src/v20190904/model/SecurityGroupRule.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
cfw/src/v20190904/model/SecurityGroupRule.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/cfw/v20190904/model/SecurityGroupRule.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Cfw::V20190904::Model; using namespace std; SecurityGroupRule::SecurityGroupRule() : m_sourceContentHasBeenSet(false), m_sourceTypeHasBeenSet(false), m_destContentHasBeenSet(false), m_destTypeHasBeenSet(false), m_ruleActionHasBeenSet(false), m_descriptionHasBeenSet(false), m_orderIndexHasBeenSet(false), m_protocolHasBeenSet(false), m_portHasBeenSet(false), m_serviceTemplateIdHasBeenSet(false), m_idHasBeenSet(false), m_enableHasBeenSet(false) { } CoreInternalOutcome SecurityGroupRule::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("SourceContent") && !value["SourceContent"].IsNull()) { if (!value["SourceContent"].IsString()) { return CoreInternalOutcome(Core::Error("response `SecurityGroupRule.SourceContent` IsString=false incorrectly").SetRequestId(requestId)); } m_sourceContent = string(value["SourceContent"].GetString()); m_sourceContentHasBeenSet = true; } if (value.HasMember("SourceType") && !value["SourceType"].IsNull()) { if (!value["SourceType"].IsString()) { return CoreInternalOutcome(Core::Error("response `SecurityGroupRule.SourceType` IsString=false incorrectly").SetRequestId(requestId)); } m_sourceType = string(value["SourceType"].GetString()); m_sourceTypeHasBeenSet = true; } if (value.HasMember("DestContent") && !value["DestContent"].IsNull()) { if (!value["DestContent"].IsString()) { return CoreInternalOutcome(Core::Error("response `SecurityGroupRule.DestContent` IsString=false incorrectly").SetRequestId(requestId)); } m_destContent = string(value["DestContent"].GetString()); m_destContentHasBeenSet = true; } if (value.HasMember("DestType") && !value["DestType"].IsNull()) { if (!value["DestType"].IsString()) { return CoreInternalOutcome(Core::Error("response `SecurityGroupRule.DestType` IsString=false incorrectly").SetRequestId(requestId)); } m_destType = string(value["DestType"].GetString()); m_destTypeHasBeenSet = true; } if (value.HasMember("RuleAction") && !value["RuleAction"].IsNull()) { if (!value["RuleAction"].IsString()) { return CoreInternalOutcome(Core::Error("response `SecurityGroupRule.RuleAction` IsString=false incorrectly").SetRequestId(requestId)); } m_ruleAction = string(value["RuleAction"].GetString()); m_ruleActionHasBeenSet = true; } if (value.HasMember("Description") && !value["Description"].IsNull()) { if (!value["Description"].IsString()) { return CoreInternalOutcome(Core::Error("response `SecurityGroupRule.Description` IsString=false incorrectly").SetRequestId(requestId)); } m_description = string(value["Description"].GetString()); m_descriptionHasBeenSet = true; } if (value.HasMember("OrderIndex") && !value["OrderIndex"].IsNull()) { if (!value["OrderIndex"].IsString()) { return CoreInternalOutcome(Core::Error("response `SecurityGroupRule.OrderIndex` IsString=false incorrectly").SetRequestId(requestId)); } m_orderIndex = string(value["OrderIndex"].GetString()); m_orderIndexHasBeenSet = true; } if (value.HasMember("Protocol") && !value["Protocol"].IsNull()) { if (!value["Protocol"].IsString()) { return CoreInternalOutcome(Core::Error("response `SecurityGroupRule.Protocol` IsString=false incorrectly").SetRequestId(requestId)); } m_protocol = string(value["Protocol"].GetString()); m_protocolHasBeenSet = true; } if (value.HasMember("Port") && !value["Port"].IsNull()) { if (!value["Port"].IsString()) { return CoreInternalOutcome(Core::Error("response `SecurityGroupRule.Port` IsString=false incorrectly").SetRequestId(requestId)); } m_port = string(value["Port"].GetString()); m_portHasBeenSet = true; } if (value.HasMember("ServiceTemplateId") && !value["ServiceTemplateId"].IsNull()) { if (!value["ServiceTemplateId"].IsString()) { return CoreInternalOutcome(Core::Error("response `SecurityGroupRule.ServiceTemplateId` IsString=false incorrectly").SetRequestId(requestId)); } m_serviceTemplateId = string(value["ServiceTemplateId"].GetString()); m_serviceTemplateIdHasBeenSet = true; } if (value.HasMember("Id") && !value["Id"].IsNull()) { if (!value["Id"].IsString()) { return CoreInternalOutcome(Core::Error("response `SecurityGroupRule.Id` IsString=false incorrectly").SetRequestId(requestId)); } m_id = string(value["Id"].GetString()); m_idHasBeenSet = true; } if (value.HasMember("Enable") && !value["Enable"].IsNull()) { if (!value["Enable"].IsString()) { return CoreInternalOutcome(Core::Error("response `SecurityGroupRule.Enable` IsString=false incorrectly").SetRequestId(requestId)); } m_enable = string(value["Enable"].GetString()); m_enableHasBeenSet = true; } return CoreInternalOutcome(true); } void SecurityGroupRule::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_sourceContentHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "SourceContent"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_sourceContent.c_str(), allocator).Move(), allocator); } if (m_sourceTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "SourceType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_sourceType.c_str(), allocator).Move(), allocator); } if (m_destContentHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DestContent"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_destContent.c_str(), allocator).Move(), allocator); } if (m_destTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DestType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_destType.c_str(), allocator).Move(), allocator); } if (m_ruleActionHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RuleAction"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_ruleAction.c_str(), allocator).Move(), allocator); } if (m_descriptionHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Description"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_description.c_str(), allocator).Move(), allocator); } if (m_orderIndexHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "OrderIndex"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_orderIndex.c_str(), allocator).Move(), allocator); } if (m_protocolHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Protocol"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_protocol.c_str(), allocator).Move(), allocator); } if (m_portHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Port"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_port.c_str(), allocator).Move(), allocator); } if (m_serviceTemplateIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ServiceTemplateId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_serviceTemplateId.c_str(), allocator).Move(), allocator); } if (m_idHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Id"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_id.c_str(), allocator).Move(), allocator); } if (m_enableHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Enable"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_enable.c_str(), allocator).Move(), allocator); } } string SecurityGroupRule::GetSourceContent() const { return m_sourceContent; } void SecurityGroupRule::SetSourceContent(const string& _sourceContent) { m_sourceContent = _sourceContent; m_sourceContentHasBeenSet = true; } bool SecurityGroupRule::SourceContentHasBeenSet() const { return m_sourceContentHasBeenSet; } string SecurityGroupRule::GetSourceType() const { return m_sourceType; } void SecurityGroupRule::SetSourceType(const string& _sourceType) { m_sourceType = _sourceType; m_sourceTypeHasBeenSet = true; } bool SecurityGroupRule::SourceTypeHasBeenSet() const { return m_sourceTypeHasBeenSet; } string SecurityGroupRule::GetDestContent() const { return m_destContent; } void SecurityGroupRule::SetDestContent(const string& _destContent) { m_destContent = _destContent; m_destContentHasBeenSet = true; } bool SecurityGroupRule::DestContentHasBeenSet() const { return m_destContentHasBeenSet; } string SecurityGroupRule::GetDestType() const { return m_destType; } void SecurityGroupRule::SetDestType(const string& _destType) { m_destType = _destType; m_destTypeHasBeenSet = true; } bool SecurityGroupRule::DestTypeHasBeenSet() const { return m_destTypeHasBeenSet; } string SecurityGroupRule::GetRuleAction() const { return m_ruleAction; } void SecurityGroupRule::SetRuleAction(const string& _ruleAction) { m_ruleAction = _ruleAction; m_ruleActionHasBeenSet = true; } bool SecurityGroupRule::RuleActionHasBeenSet() const { return m_ruleActionHasBeenSet; } string SecurityGroupRule::GetDescription() const { return m_description; } void SecurityGroupRule::SetDescription(const string& _description) { m_description = _description; m_descriptionHasBeenSet = true; } bool SecurityGroupRule::DescriptionHasBeenSet() const { return m_descriptionHasBeenSet; } string SecurityGroupRule::GetOrderIndex() const { return m_orderIndex; } void SecurityGroupRule::SetOrderIndex(const string& _orderIndex) { m_orderIndex = _orderIndex; m_orderIndexHasBeenSet = true; } bool SecurityGroupRule::OrderIndexHasBeenSet() const { return m_orderIndexHasBeenSet; } string SecurityGroupRule::GetProtocol() const { return m_protocol; } void SecurityGroupRule::SetProtocol(const string& _protocol) { m_protocol = _protocol; m_protocolHasBeenSet = true; } bool SecurityGroupRule::ProtocolHasBeenSet() const { return m_protocolHasBeenSet; } string SecurityGroupRule::GetPort() const { return m_port; } void SecurityGroupRule::SetPort(const string& _port) { m_port = _port; m_portHasBeenSet = true; } bool SecurityGroupRule::PortHasBeenSet() const { return m_portHasBeenSet; } string SecurityGroupRule::GetServiceTemplateId() const { return m_serviceTemplateId; } void SecurityGroupRule::SetServiceTemplateId(const string& _serviceTemplateId) { m_serviceTemplateId = _serviceTemplateId; m_serviceTemplateIdHasBeenSet = true; } bool SecurityGroupRule::ServiceTemplateIdHasBeenSet() const { return m_serviceTemplateIdHasBeenSet; } string SecurityGroupRule::GetId() const { return m_id; } void SecurityGroupRule::SetId(const string& _id) { m_id = _id; m_idHasBeenSet = true; } bool SecurityGroupRule::IdHasBeenSet() const { return m_idHasBeenSet; } string SecurityGroupRule::GetEnable() const { return m_enable; } void SecurityGroupRule::SetEnable(const string& _enable) { m_enable = _enable; m_enableHasBeenSet = true; } bool SecurityGroupRule::EnableHasBeenSet() const { return m_enableHasBeenSet; }
28.709957
153
0.685012
[ "model" ]
d09d43b78c3a0ac90ba25cea19828fdd0a14a8ea
3,271
cpp
C++
image_landmark_track_source.cpp
tussedrotten/sensor-fusion-example
fa1c21e0c5dd8387bc67773a1343f1bf1e0f676a
[ "BSD-3-Clause" ]
1
2021-04-23T10:00:02.000Z
2021-04-23T10:00:02.000Z
image_landmark_track_source.cpp
tussedrotten/sensor-fusion-example
fa1c21e0c5dd8387bc67773a1343f1bf1e0f676a
[ "BSD-3-Clause" ]
null
null
null
image_landmark_track_source.cpp
tussedrotten/sensor-fusion-example
fa1c21e0c5dd8387bc67773a1343f1bf1e0f676a
[ "BSD-3-Clause" ]
1
2021-10-04T12:40:47.000Z
2021-10-04T12:40:47.000Z
#include "image_landmark_track_source.h" #include "opencv2/core/eigen.hpp" #include "opencv2/calib3d.hpp" #include <fstream> Eigen::Matrix3d Intrinsics::toCalibrationMatrix() const { Eigen::Matrix3d calib_mat; calib_mat << fu, 0., cu, 0., fv, cv, 0., 0., 1.; return calib_mat; } cv::Matx33d Intrinsics::toCvCalibrationMatrix() const { cv::Matx33d calib_matrix( fu, 0.0, cu, 0.0, fv, cv, 0.0, 0.0, 1.0 ); return calib_matrix; } Intrinsics::Vector5d Intrinsics::toDistortionCoefficientVector() const { Vector5d dist_coeffs; dist_coeffs << k1, k2, 0., 0., k3; return dist_coeffs; } cv::Mat Intrinsics::toCvDistortionCoefficientVector() const { auto dist_coeffs = toDistortionCoefficientVector(); cv::Mat dist_coeffs_cv; cv::eigen2cv(dist_coeffs, dist_coeffs_cv); return dist_coeffs_cv; } std::istream& operator>>(std::istream& is, Intrinsics& intrinsics) { is >> intrinsics.fu >> intrinsics.fv >> intrinsics.cu >> intrinsics.cv >> intrinsics.k1 >> intrinsics.k2 >> intrinsics.k3; return is; } std::istream& operator>>(std::istream& is, Track& track) { is >> track.id; is >> track.pixel.x(); is >> track.pixel.y(); is >> track.sigmas.x(); is >> track.sigmas.y(); return is; } std::istream& operator>>(std::istream& is, InitialPose& init_pose) { is >> init_pose.pos.latitude; is >> init_pose.pos.longitude; is >> init_pose.pos.altitude; is >> init_pose.att.x_rot; is >> init_pose.att.y_rot; is >> init_pose.att.z_rot; return is; } std::istream& operator>>(std::istream& is, TrackingFrame& frame) { is >> frame.time; size_t num_tracks{}; is >> num_tracks; is >> frame.init; if (!is) { return is; } for (size_t i = 0; i < num_tracks; ++i) { Track track; is >> track; frame.tracks.emplace_back(track); } return is; } ImageLandmarkTrackSource::ImageLandmarkTrackSource(const std::string& filename) { std::ifstream is(filename); is >> calibration_; const auto dist_coeffs = calibration_.toCvDistortionCoefficientVector(); const auto calib_matrix = calibration_.toCvCalibrationMatrix(); TrackingFrame frame; while (is >> frame) { for (auto& track : frame.tracks) { std::vector<cv::Point2d> distorted{{track.pixel.x(), track.pixel.y()}}; std::vector<cv::Point2d> undistorted(1); cv::undistortPoints(distorted, undistorted, calib_matrix, dist_coeffs, cv::Mat{}, calib_matrix); track.pixel.x() = undistorted[0].x; track.pixel.y() = undistorted[0].y; } data_.emplace_back(frame); frame = TrackingFrame{}; } } bool ImageLandmarkTrackSource::hasNext() const { return !data_.empty(); } const Intrinsics& ImageLandmarkTrackSource::calibration() const { return calibration_; } double ImageLandmarkTrackSource::nextTime() const { if (data_.empty()) { return std::numeric_limits<double>::infinity(); } return data_.front().time; } const TrackingFrame& ImageLandmarkTrackSource::next() const { if (data_.empty()) { throw std::out_of_range("Data is hasNext"); } return data_.front(); } void ImageLandmarkTrackSource::pop() { if (data_.empty()) { throw std::out_of_range("Data is hasNext"); } data_.pop_front(); }
20.067485
102
0.665851
[ "vector" ]
d0a0f520f0d3c291ff67f91b181fdee609998c99
24,431
cpp
C++
src/cas_20200407.cpp
alibabacloud-sdk-cpp/cas-20200407
57156fd5933b1c1bd1ba45c7ed8558fd360c186d
[ "Apache-2.0" ]
null
null
null
src/cas_20200407.cpp
alibabacloud-sdk-cpp/cas-20200407
57156fd5933b1c1bd1ba45c7ed8558fd360c186d
[ "Apache-2.0" ]
null
null
null
src/cas_20200407.cpp
alibabacloud-sdk-cpp/cas-20200407
57156fd5933b1c1bd1ba45c7ed8558fd360c186d
[ "Apache-2.0" ]
null
null
null
// This file is auto-generated, don't edit it. Thanks. #include <alibabacloud/cas_20200407.hpp> #include <alibabacloud/endpoint_util.hpp> #include <alibabacloud/open_api.hpp> #include <alibabacloud/open_api_util.hpp> #include <boost/any.hpp> #include <boost/throw_exception.hpp> #include <darabonba/core.hpp> #include <darabonba/util.hpp> #include <iostream> #include <map> #include <vector> using namespace std; using namespace Alibabacloud_Cas20200407; Alibabacloud_Cas20200407::Client::Client(const shared_ptr<Alibabacloud_OpenApi::Config>& config) : Alibabacloud_OpenApi::Client(config) { _endpointRule = make_shared<string>("regional"); _endpointMap = make_shared<map<string, string>>(map<string, string>({ {"cn-hangzhou", "cas.aliyuncs.com"}, {"ap-northeast-2-pop", "cas.aliyuncs.com"}, {"ap-southeast-1", "cas.aliyuncs.com"}, {"ap-southeast-3", "cas.aliyuncs.com"}, {"ap-southeast-5", "cas.aliyuncs.com"}, {"cn-beijing", "cas.aliyuncs.com"}, {"cn-beijing-finance-1", "cas.aliyuncs.com"}, {"cn-beijing-finance-pop", "cas.aliyuncs.com"}, {"cn-beijing-gov-1", "cas.aliyuncs.com"}, {"cn-beijing-nu16-b01", "cas.aliyuncs.com"}, {"cn-chengdu", "cas.aliyuncs.com"}, {"cn-edge-1", "cas.aliyuncs.com"}, {"cn-fujian", "cas.aliyuncs.com"}, {"cn-haidian-cm12-c01", "cas.aliyuncs.com"}, {"cn-hangzhou-bj-b01", "cas.aliyuncs.com"}, {"cn-hangzhou-finance", "cas.aliyuncs.com"}, {"cn-hangzhou-internal-prod-1", "cas.aliyuncs.com"}, {"cn-hangzhou-internal-test-1", "cas.aliyuncs.com"}, {"cn-hangzhou-internal-test-2", "cas.aliyuncs.com"}, {"cn-hangzhou-internal-test-3", "cas.aliyuncs.com"}, {"cn-hangzhou-test-306", "cas.aliyuncs.com"}, {"cn-hongkong", "cas.aliyuncs.com"}, {"cn-hongkong-finance-pop", "cas.aliyuncs.com"}, {"cn-huhehaote", "cas.aliyuncs.com"}, {"cn-north-2-gov-1", "cas.aliyuncs.com"}, {"cn-qingdao", "cas.aliyuncs.com"}, {"cn-qingdao-nebula", "cas.aliyuncs.com"}, {"cn-shanghai", "cas.aliyuncs.com"}, {"cn-shanghai-et15-b01", "cas.aliyuncs.com"}, {"cn-shanghai-et2-b01", "cas.aliyuncs.com"}, {"cn-shanghai-finance-1", "cas.aliyuncs.com"}, {"cn-shanghai-inner", "cas.aliyuncs.com"}, {"cn-shanghai-internal-test-1", "cas.aliyuncs.com"}, {"cn-shenzhen", "cas.aliyuncs.com"}, {"cn-shenzhen-finance-1", "cas.aliyuncs.com"}, {"cn-shenzhen-inner", "cas.aliyuncs.com"}, {"cn-shenzhen-st4-d01", "cas.aliyuncs.com"}, {"cn-shenzhen-su18-b01", "cas.aliyuncs.com"}, {"cn-wuhan", "cas.aliyuncs.com"}, {"cn-yushanfang", "cas.aliyuncs.com"}, {"cn-zhangbei-na61-b01", "cas.aliyuncs.com"}, {"cn-zhangjiakou", "cas.aliyuncs.com"}, {"cn-zhangjiakou-na62-a01", "cas.aliyuncs.com"}, {"cn-zhengzhou-nebula-1", "cas.aliyuncs.com"}, {"eu-west-1", "cas.aliyuncs.com"}, {"eu-west-1-oxs", "cas.aliyuncs.com"}, {"rus-west-1-pop", "cas.aliyuncs.com"}, {"us-east-1", "cas.aliyuncs.com"}, {"us-west-1", "cas.aliyuncs.com"} }) ); checkConfig(config); _endpoint = make_shared<string>(getEndpoint(make_shared<string>("cas"), _regionId, _endpointRule, _network, _suffix, _endpointMap, _endpoint)); }; string Alibabacloud_Cas20200407::Client::getEndpoint(shared_ptr<string> productId, shared_ptr<string> regionId, shared_ptr<string> endpointRule, shared_ptr<string> network, shared_ptr<string> suffix, shared_ptr<map<string, string>> endpointMap, shared_ptr<string> endpoint) { if (!Darabonba_Util::Client::empty(endpoint)) { return *endpoint; } if (!Darabonba_Util::Client::isUnset<map<string, string>>(endpointMap) && !Darabonba_Util::Client::empty(make_shared<string>((*endpointMap)[regionId]))) { return (*endpointMap)[regionId]; } return Alibabacloud_EndpointUtil::Client::getEndpointRules(productId, regionId, endpointRule, network, suffix); } CancelCertificateForPackageRequestResponse Alibabacloud_Cas20200407::Client::cancelCertificateForPackageRequestWithOptions(shared_ptr<CancelCertificateForPackageRequestRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { Darabonba_Util::Client::validateModel(request); shared_ptr<map<string, boost::any>> query = make_shared<map<string, boost::any>>(map<string, boost::any>()); if (!Darabonba_Util::Client::isUnset<long>(request->orderId)) { query->insert(pair<string, long>("OrderId", *request->orderId)); } shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({ {"query", boost::any(Alibabacloud_OpenApiUtil::Client::query(query))} })); shared_ptr<Alibabacloud_OpenApi::Params> params = make_shared<Alibabacloud_OpenApi::Params>(map<string, boost::any>({ {"action", boost::any(string("CancelCertificateForPackageRequest"))}, {"version", boost::any(string("2020-04-07"))}, {"protocol", boost::any(string("HTTPS"))}, {"pathname", boost::any(string("/"))}, {"method", boost::any(string("POST"))}, {"authType", boost::any(string("AK"))}, {"style", boost::any(string("RPC"))}, {"reqBodyType", boost::any(string("formData"))}, {"bodyType", boost::any(string("json"))} })); return CancelCertificateForPackageRequestResponse(callApi(params, req, runtime)); } CancelCertificateForPackageRequestResponse Alibabacloud_Cas20200407::Client::cancelCertificateForPackageRequest(shared_ptr<CancelCertificateForPackageRequestRequest> request) { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return cancelCertificateForPackageRequestWithOptions(request, runtime); } CancelOrderRequestResponse Alibabacloud_Cas20200407::Client::cancelOrderRequestWithOptions(shared_ptr<CancelOrderRequestRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { Darabonba_Util::Client::validateModel(request); shared_ptr<map<string, boost::any>> query = make_shared<map<string, boost::any>>(map<string, boost::any>()); if (!Darabonba_Util::Client::isUnset<long>(request->orderId)) { query->insert(pair<string, long>("OrderId", *request->orderId)); } shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({ {"query", boost::any(Alibabacloud_OpenApiUtil::Client::query(query))} })); shared_ptr<Alibabacloud_OpenApi::Params> params = make_shared<Alibabacloud_OpenApi::Params>(map<string, boost::any>({ {"action", boost::any(string("CancelOrderRequest"))}, {"version", boost::any(string("2020-04-07"))}, {"protocol", boost::any(string("HTTPS"))}, {"pathname", boost::any(string("/"))}, {"method", boost::any(string("POST"))}, {"authType", boost::any(string("AK"))}, {"style", boost::any(string("RPC"))}, {"reqBodyType", boost::any(string("formData"))}, {"bodyType", boost::any(string("json"))} })); return CancelOrderRequestResponse(callApi(params, req, runtime)); } CancelOrderRequestResponse Alibabacloud_Cas20200407::Client::cancelOrderRequest(shared_ptr<CancelOrderRequestRequest> request) { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return cancelOrderRequestWithOptions(request, runtime); } CreateCertificateForPackageRequestResponse Alibabacloud_Cas20200407::Client::createCertificateForPackageRequestWithOptions(shared_ptr<CreateCertificateForPackageRequestRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { Darabonba_Util::Client::validateModel(request); shared_ptr<map<string, boost::any>> query = make_shared<map<string, boost::any>>(map<string, boost::any>()); if (!Darabonba_Util::Client::isUnset<string>(request->companyName)) { query->insert(pair<string, string>("CompanyName", *request->companyName)); } if (!Darabonba_Util::Client::isUnset<string>(request->csr)) { query->insert(pair<string, string>("Csr", *request->csr)); } if (!Darabonba_Util::Client::isUnset<string>(request->domain)) { query->insert(pair<string, string>("Domain", *request->domain)); } if (!Darabonba_Util::Client::isUnset<string>(request->email)) { query->insert(pair<string, string>("Email", *request->email)); } if (!Darabonba_Util::Client::isUnset<string>(request->phone)) { query->insert(pair<string, string>("Phone", *request->phone)); } if (!Darabonba_Util::Client::isUnset<string>(request->productCode)) { query->insert(pair<string, string>("ProductCode", *request->productCode)); } if (!Darabonba_Util::Client::isUnset<string>(request->username)) { query->insert(pair<string, string>("Username", *request->username)); } if (!Darabonba_Util::Client::isUnset<string>(request->validateType)) { query->insert(pair<string, string>("ValidateType", *request->validateType)); } shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({ {"query", boost::any(Alibabacloud_OpenApiUtil::Client::query(query))} })); shared_ptr<Alibabacloud_OpenApi::Params> params = make_shared<Alibabacloud_OpenApi::Params>(map<string, boost::any>({ {"action", boost::any(string("CreateCertificateForPackageRequest"))}, {"version", boost::any(string("2020-04-07"))}, {"protocol", boost::any(string("HTTPS"))}, {"pathname", boost::any(string("/"))}, {"method", boost::any(string("POST"))}, {"authType", boost::any(string("AK"))}, {"style", boost::any(string("RPC"))}, {"reqBodyType", boost::any(string("formData"))}, {"bodyType", boost::any(string("json"))} })); return CreateCertificateForPackageRequestResponse(callApi(params, req, runtime)); } CreateCertificateForPackageRequestResponse Alibabacloud_Cas20200407::Client::createCertificateForPackageRequest(shared_ptr<CreateCertificateForPackageRequestRequest> request) { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return createCertificateForPackageRequestWithOptions(request, runtime); } CreateCertificateRequestResponse Alibabacloud_Cas20200407::Client::createCertificateRequestWithOptions(shared_ptr<CreateCertificateRequestRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { Darabonba_Util::Client::validateModel(request); shared_ptr<map<string, boost::any>> query = make_shared<map<string, boost::any>>(map<string, boost::any>()); if (!Darabonba_Util::Client::isUnset<string>(request->domain)) { query->insert(pair<string, string>("Domain", *request->domain)); } if (!Darabonba_Util::Client::isUnset<string>(request->email)) { query->insert(pair<string, string>("Email", *request->email)); } if (!Darabonba_Util::Client::isUnset<string>(request->phone)) { query->insert(pair<string, string>("Phone", *request->phone)); } if (!Darabonba_Util::Client::isUnset<string>(request->productCode)) { query->insert(pair<string, string>("ProductCode", *request->productCode)); } if (!Darabonba_Util::Client::isUnset<string>(request->username)) { query->insert(pair<string, string>("Username", *request->username)); } if (!Darabonba_Util::Client::isUnset<string>(request->validateType)) { query->insert(pair<string, string>("ValidateType", *request->validateType)); } shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({ {"query", boost::any(Alibabacloud_OpenApiUtil::Client::query(query))} })); shared_ptr<Alibabacloud_OpenApi::Params> params = make_shared<Alibabacloud_OpenApi::Params>(map<string, boost::any>({ {"action", boost::any(string("CreateCertificateRequest"))}, {"version", boost::any(string("2020-04-07"))}, {"protocol", boost::any(string("HTTPS"))}, {"pathname", boost::any(string("/"))}, {"method", boost::any(string("POST"))}, {"authType", boost::any(string("AK"))}, {"style", boost::any(string("RPC"))}, {"reqBodyType", boost::any(string("formData"))}, {"bodyType", boost::any(string("json"))} })); return CreateCertificateRequestResponse(callApi(params, req, runtime)); } CreateCertificateRequestResponse Alibabacloud_Cas20200407::Client::createCertificateRequest(shared_ptr<CreateCertificateRequestRequest> request) { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return createCertificateRequestWithOptions(request, runtime); } CreateCertificateWithCsrRequestResponse Alibabacloud_Cas20200407::Client::createCertificateWithCsrRequestWithOptions(shared_ptr<CreateCertificateWithCsrRequestRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { Darabonba_Util::Client::validateModel(request); shared_ptr<map<string, boost::any>> query = make_shared<map<string, boost::any>>(map<string, boost::any>()); if (!Darabonba_Util::Client::isUnset<string>(request->csr)) { query->insert(pair<string, string>("Csr", *request->csr)); } if (!Darabonba_Util::Client::isUnset<string>(request->email)) { query->insert(pair<string, string>("Email", *request->email)); } if (!Darabonba_Util::Client::isUnset<string>(request->phone)) { query->insert(pair<string, string>("Phone", *request->phone)); } if (!Darabonba_Util::Client::isUnset<string>(request->productCode)) { query->insert(pair<string, string>("ProductCode", *request->productCode)); } if (!Darabonba_Util::Client::isUnset<string>(request->username)) { query->insert(pair<string, string>("Username", *request->username)); } if (!Darabonba_Util::Client::isUnset<string>(request->validateType)) { query->insert(pair<string, string>("ValidateType", *request->validateType)); } shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({ {"query", boost::any(Alibabacloud_OpenApiUtil::Client::query(query))} })); shared_ptr<Alibabacloud_OpenApi::Params> params = make_shared<Alibabacloud_OpenApi::Params>(map<string, boost::any>({ {"action", boost::any(string("CreateCertificateWithCsrRequest"))}, {"version", boost::any(string("2020-04-07"))}, {"protocol", boost::any(string("HTTPS"))}, {"pathname", boost::any(string("/"))}, {"method", boost::any(string("POST"))}, {"authType", boost::any(string("AK"))}, {"style", boost::any(string("RPC"))}, {"reqBodyType", boost::any(string("formData"))}, {"bodyType", boost::any(string("json"))} })); return CreateCertificateWithCsrRequestResponse(callApi(params, req, runtime)); } CreateCertificateWithCsrRequestResponse Alibabacloud_Cas20200407::Client::createCertificateWithCsrRequest(shared_ptr<CreateCertificateWithCsrRequestRequest> request) { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return createCertificateWithCsrRequestWithOptions(request, runtime); } DeleteCertificateRequestResponse Alibabacloud_Cas20200407::Client::deleteCertificateRequestWithOptions(shared_ptr<DeleteCertificateRequestRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { Darabonba_Util::Client::validateModel(request); shared_ptr<map<string, boost::any>> query = make_shared<map<string, boost::any>>(map<string, boost::any>()); if (!Darabonba_Util::Client::isUnset<long>(request->orderId)) { query->insert(pair<string, long>("OrderId", *request->orderId)); } shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({ {"query", boost::any(Alibabacloud_OpenApiUtil::Client::query(query))} })); shared_ptr<Alibabacloud_OpenApi::Params> params = make_shared<Alibabacloud_OpenApi::Params>(map<string, boost::any>({ {"action", boost::any(string("DeleteCertificateRequest"))}, {"version", boost::any(string("2020-04-07"))}, {"protocol", boost::any(string("HTTPS"))}, {"pathname", boost::any(string("/"))}, {"method", boost::any(string("POST"))}, {"authType", boost::any(string("AK"))}, {"style", boost::any(string("RPC"))}, {"reqBodyType", boost::any(string("formData"))}, {"bodyType", boost::any(string("json"))} })); return DeleteCertificateRequestResponse(callApi(params, req, runtime)); } DeleteCertificateRequestResponse Alibabacloud_Cas20200407::Client::deleteCertificateRequest(shared_ptr<DeleteCertificateRequestRequest> request) { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return deleteCertificateRequestWithOptions(request, runtime); } DescribeCertificateStateResponse Alibabacloud_Cas20200407::Client::describeCertificateStateWithOptions(shared_ptr<DescribeCertificateStateRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { Darabonba_Util::Client::validateModel(request); shared_ptr<map<string, boost::any>> query = make_shared<map<string, boost::any>>(map<string, boost::any>()); if (!Darabonba_Util::Client::isUnset<long>(request->orderId)) { query->insert(pair<string, long>("OrderId", *request->orderId)); } shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({ {"query", boost::any(Alibabacloud_OpenApiUtil::Client::query(query))} })); shared_ptr<Alibabacloud_OpenApi::Params> params = make_shared<Alibabacloud_OpenApi::Params>(map<string, boost::any>({ {"action", boost::any(string("DescribeCertificateState"))}, {"version", boost::any(string("2020-04-07"))}, {"protocol", boost::any(string("HTTPS"))}, {"pathname", boost::any(string("/"))}, {"method", boost::any(string("POST"))}, {"authType", boost::any(string("AK"))}, {"style", boost::any(string("RPC"))}, {"reqBodyType", boost::any(string("formData"))}, {"bodyType", boost::any(string("json"))} })); return DescribeCertificateStateResponse(callApi(params, req, runtime)); } DescribeCertificateStateResponse Alibabacloud_Cas20200407::Client::describeCertificateState(shared_ptr<DescribeCertificateStateRequest> request) { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return describeCertificateStateWithOptions(request, runtime); } DescribePackageStateResponse Alibabacloud_Cas20200407::Client::describePackageStateWithOptions(shared_ptr<DescribePackageStateRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { Darabonba_Util::Client::validateModel(request); shared_ptr<map<string, boost::any>> query = make_shared<map<string, boost::any>>(map<string, boost::any>()); if (!Darabonba_Util::Client::isUnset<string>(request->productCode)) { query->insert(pair<string, string>("ProductCode", *request->productCode)); } shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({ {"query", boost::any(Alibabacloud_OpenApiUtil::Client::query(query))} })); shared_ptr<Alibabacloud_OpenApi::Params> params = make_shared<Alibabacloud_OpenApi::Params>(map<string, boost::any>({ {"action", boost::any(string("DescribePackageState"))}, {"version", boost::any(string("2020-04-07"))}, {"protocol", boost::any(string("HTTPS"))}, {"pathname", boost::any(string("/"))}, {"method", boost::any(string("POST"))}, {"authType", boost::any(string("AK"))}, {"style", boost::any(string("RPC"))}, {"reqBodyType", boost::any(string("formData"))}, {"bodyType", boost::any(string("json"))} })); return DescribePackageStateResponse(callApi(params, req, runtime)); } DescribePackageStateResponse Alibabacloud_Cas20200407::Client::describePackageState(shared_ptr<DescribePackageStateRequest> request) { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return describePackageStateWithOptions(request, runtime); } ListUserCertificateOrderResponse Alibabacloud_Cas20200407::Client::listUserCertificateOrderWithOptions(shared_ptr<ListUserCertificateOrderRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { Darabonba_Util::Client::validateModel(request); shared_ptr<map<string, boost::any>> query = make_shared<map<string, boost::any>>(map<string, boost::any>()); if (!Darabonba_Util::Client::isUnset<long>(request->currentPage)) { query->insert(pair<string, long>("CurrentPage", *request->currentPage)); } if (!Darabonba_Util::Client::isUnset<string>(request->keyword)) { query->insert(pair<string, string>("Keyword", *request->keyword)); } if (!Darabonba_Util::Client::isUnset<string>(request->orderType)) { query->insert(pair<string, string>("OrderType", *request->orderType)); } if (!Darabonba_Util::Client::isUnset<long>(request->showSize)) { query->insert(pair<string, long>("ShowSize", *request->showSize)); } if (!Darabonba_Util::Client::isUnset<string>(request->status)) { query->insert(pair<string, string>("Status", *request->status)); } shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({ {"query", boost::any(Alibabacloud_OpenApiUtil::Client::query(query))} })); shared_ptr<Alibabacloud_OpenApi::Params> params = make_shared<Alibabacloud_OpenApi::Params>(map<string, boost::any>({ {"action", boost::any(string("ListUserCertificateOrder"))}, {"version", boost::any(string("2020-04-07"))}, {"protocol", boost::any(string("HTTPS"))}, {"pathname", boost::any(string("/"))}, {"method", boost::any(string("POST"))}, {"authType", boost::any(string("AK"))}, {"style", boost::any(string("RPC"))}, {"reqBodyType", boost::any(string("formData"))}, {"bodyType", boost::any(string("json"))} })); return ListUserCertificateOrderResponse(callApi(params, req, runtime)); } ListUserCertificateOrderResponse Alibabacloud_Cas20200407::Client::listUserCertificateOrder(shared_ptr<ListUserCertificateOrderRequest> request) { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return listUserCertificateOrderWithOptions(request, runtime); } RenewCertificateOrderForPackageRequestResponse Alibabacloud_Cas20200407::Client::renewCertificateOrderForPackageRequestWithOptions(shared_ptr<RenewCertificateOrderForPackageRequestRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { Darabonba_Util::Client::validateModel(request); shared_ptr<map<string, boost::any>> query = make_shared<map<string, boost::any>>(map<string, boost::any>()); if (!Darabonba_Util::Client::isUnset<string>(request->csr)) { query->insert(pair<string, string>("Csr", *request->csr)); } if (!Darabonba_Util::Client::isUnset<long>(request->orderId)) { query->insert(pair<string, long>("OrderId", *request->orderId)); } shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({ {"query", boost::any(Alibabacloud_OpenApiUtil::Client::query(query))} })); shared_ptr<Alibabacloud_OpenApi::Params> params = make_shared<Alibabacloud_OpenApi::Params>(map<string, boost::any>({ {"action", boost::any(string("RenewCertificateOrderForPackageRequest"))}, {"version", boost::any(string("2020-04-07"))}, {"protocol", boost::any(string("HTTPS"))}, {"pathname", boost::any(string("/"))}, {"method", boost::any(string("POST"))}, {"authType", boost::any(string("AK"))}, {"style", boost::any(string("RPC"))}, {"reqBodyType", boost::any(string("formData"))}, {"bodyType", boost::any(string("json"))} })); return RenewCertificateOrderForPackageRequestResponse(callApi(params, req, runtime)); } RenewCertificateOrderForPackageRequestResponse Alibabacloud_Cas20200407::Client::renewCertificateOrderForPackageRequest(shared_ptr<RenewCertificateOrderForPackageRequestRequest> request) { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return renewCertificateOrderForPackageRequestWithOptions(request, runtime); }
55.651481
251
0.716467
[ "vector" ]
d0a641ff7e3baa157da98ebb0fcd84832f50cae6
1,400
cpp
C++
C++ Solutions/Other/Binary_Search/Find_an_Element_in_Bitonic_Array.cpp
LearnEarn-Fun/Competitive-Programming-Solutions
2c353bea49413e3f0f14b8980baf982881ad2c65
[ "MIT" ]
1
2021-02-06T04:24:05.000Z
2021-02-06T04:24:05.000Z
C++ Solutions/Other/Binary_Search/Find_an_Element_in_Bitonic_Array.cpp
hridaya423/Competitive-Programming-Solutions
2c353bea49413e3f0f14b8980baf982881ad2c65
[ "MIT" ]
null
null
null
C++ Solutions/Other/Binary_Search/Find_an_Element_in_Bitonic_Array.cpp
hridaya423/Competitive-Programming-Solutions
2c353bea49413e3f0f14b8980baf982881ad2c65
[ "MIT" ]
1
2021-11-13T18:46:55.000Z
2021-11-13T18:46:55.000Z
#include<bits/stdc++.h> using namespace std; #define ll long long #define endl "\n" #define MOD 1e9+7 #define deb(x) cout << #x << "=" << x << endl int PeakElement(vector<int> &value) { int n=value.size(), start=0, end=n-1, mid; while(start<=end) { mid=start+((end-start)/2); if(n==1 || value[0]>value[1]) return 0; else if(value[n-1]>value[n-2]) return n-1; if(value[mid]>value[mid-1] && value[mid]>value[mid+1]) return mid; if(value[mid]<value[mid-1]) end=mid-1; else if(value[mid]<value[mid+1]) start=mid+1; } return -1; } bool BinarySearch(vector<int> &value,int start, int end, int number) { int mid=start+((end-start)/2); int n; while(start<=end) { cout<<"."; if(value[mid]==number) return true; if(number > value[mid]) start=mid+1; else if(number < value[mid]) end=mid-1; mid=(end+start)/2; } return false; } void solve() { vector<int> value={1, 3, 8, 12, 4, 2}; int key=1; int peak=PeakElement(value); if(value[peak]==key) { cout<<"Yes"<<endl; return; } bool left=BinarySearch(value, 0, peak-1, key), right=BinarySearch(value, peak+1, value.size()-1, key); if(left || right) cout<<"Yes"<<endl; else cout<<"No"<<endl; return; } int main() { int t=1; // cin>>t; while(t--) { solve(); } return 0; }
17.283951
104
0.553571
[ "vector" ]
d0b099bfe335d2634f34168cab770cbe88fa38e9
5,038
cpp
C++
Miracle/src/Miracle/Graphics/Implementations/Vulkan/PhysicalDeviceSelector.cpp
McFlyboy/Miracle
03a41bb8e24ecf2dfc18b5e3aee964640ec9a593
[ "MIT" ]
null
null
null
Miracle/src/Miracle/Graphics/Implementations/Vulkan/PhysicalDeviceSelector.cpp
McFlyboy/Miracle
03a41bb8e24ecf2dfc18b5e3aee964640ec9a593
[ "MIT" ]
3
2021-12-10T23:19:29.000Z
2022-03-27T05:04:14.000Z
Miracle/src/Miracle/Graphics/Implementations/Vulkan/PhysicalDeviceSelector.cpp
McFlyboy/Miracle
03a41bb8e24ecf2dfc18b5e3aee964640ec9a593
[ "MIT" ]
null
null
null
#include "PhysicalDeviceSelector.hpp" #include <cstring> #include <optional> #include <fmt/format.h> #include <Miracle/MiracleError.hpp> #include <Miracle/components/Miracle/Diagnostics/Logger.hpp> using namespace Miracle::Diagnostics; namespace Miracle::Graphics::Implementations::Vulkan { std::variant<MiracleError, std::reference_wrapper<vk::raii::PhysicalDevice>> PhysicalDeviceSelector::selectPhysicalDevice( std::vector<vk::raii::PhysicalDevice>& physicalDevices, const vk::raii::SurfaceKHR& supportedSurface ) { auto supportedPhysicalDevices = std::vector<std::reference_wrapper<vk::raii::PhysicalDevice>>(); for (auto& physicalDevice : physicalDevices) { if (queryDeviceSupport(physicalDevice, supportedSurface).meetsAllRequirements()) { supportedPhysicalDevices.push_back(physicalDevice); } } if (supportedPhysicalDevices.empty()) { Logger::error("No Vulkan devices supported!"); return MiracleError::VulkanGraphicsEngineNoPhysicalDevicesSupportedError; } std::optional<std::reference_wrapper<vk::raii::PhysicalDevice>> discreteGpu = std::nullopt; for (auto& supportedPhysicalDevice : supportedPhysicalDevices) { if ( supportedPhysicalDevice.get().getProperties().deviceType == vk::PhysicalDeviceType::eDiscreteGpu ) { discreteGpu = supportedPhysicalDevice; break; } } auto selectedPhysicalDevice = discreteGpu.value_or(supportedPhysicalDevices.front()); Logger::info( fmt::format( "Found Vulkan supported device: {}", selectedPhysicalDevice.get().getProperties().deviceName.data() ) ); return selectedPhysicalDevice; } DeviceSupportDetails PhysicalDeviceSelector::queryDeviceSupport( const vk::raii::PhysicalDevice& physicalDevice, const vk::raii::SurfaceKHR& supportedSurface ) { return DeviceSupportDetails{ .queueFamilyIndices = queryQueueFamilyIndices(physicalDevice, supportedSurface), .extensionsSupported = queryExtensionsSupported(physicalDevice), .memoryProperties = physicalDevice.getMemoryProperties(), .swapchainSupportDetails = querySwapchainSupportDetails(physicalDevice, supportedSurface) }; } QueueFamilyIndices PhysicalDeviceSelector::queryQueueFamilyIndices( const vk::raii::PhysicalDevice& physicalDevice, const vk::raii::SurfaceKHR& supportedSurface ) { auto queueFamilyIndices = QueueFamilyIndices(); auto queueFamilyPropertiesList = physicalDevice.getQueueFamilyProperties(); for (size_t i = 0; i < queueFamilyPropertiesList.size(); i++) { auto& queueFamilyProperties = queueFamilyPropertiesList[i]; if ( !queueFamilyIndices.graphicsFamilyIndex.has_value() && ( queueFamilyProperties.queueFlags & vk::QueueFlagBits::eGraphics ) ) { queueFamilyIndices.graphicsFamilyIndex = static_cast<uint32_t>(i); } if (!queueFamilyIndices.presentFamilyIndex.has_value()) { try { auto isSurfaceSupported = physicalDevice.getSurfaceSupportKHR(i, *supportedSurface); if (isSurfaceSupported) { queueFamilyIndices.presentFamilyIndex = static_cast<uint32_t>(i); } } catch (const std::exception&) {} } if (queueFamilyIndices.hasAll()) { break; } } return queueFamilyIndices; } ExtensionsSupported PhysicalDeviceSelector::queryExtensionsSupported( const vk::raii::PhysicalDevice& physicalDevice ) { auto extensionsSupported = ExtensionsSupported(); auto extensionPropertiesList = physicalDevice.enumerateDeviceExtensionProperties(); for (auto& extensionProperties : extensionPropertiesList) { if (std::strcmp(extensionProperties.extensionName.data(), VK_KHR_SWAPCHAIN_EXTENSION_NAME) == 0) { extensionsSupported.khrSwapchainExtensionSupported = true; } } return extensionsSupported; } SwapchainSupportDetails PhysicalDeviceSelector::querySwapchainSupportDetails( const vk::raii::PhysicalDevice& physicalDevice, const vk::raii::SurfaceKHR& supportedSurface ) { return SwapchainSupportDetails{ .capabilities = physicalDevice.getSurfaceCapabilitiesKHR(*supportedSurface), .formats = physicalDevice.getSurfaceFormatsKHR(*supportedSurface), .presentModesSupported = queryPresentModesSupported(physicalDevice, supportedSurface) }; } PresentModesSupported PhysicalDeviceSelector::queryPresentModesSupported( const vk::raii::PhysicalDevice& physicalDevice, const vk::raii::SurfaceKHR& supportedSurface ) { auto presentModesSupported = PresentModesSupported(); auto presentModes = physicalDevice.getSurfacePresentModesKHR(*supportedSurface); for (auto& presentMode : presentModes) { switch (presentMode) { case vk::PresentModeKHR::eImmediate: presentModesSupported.immediateModeSupported = true; break; case vk::PresentModeKHR::eFifo: presentModesSupported.fifoModeSupported = true; break; case vk::PresentModeKHR::eMailbox: presentModesSupported.mailboxModeSupported = true; break; } if (presentModesSupported.supportsAll()) { break; } } return presentModesSupported; } }
31.098765
123
0.762207
[ "vector" ]
d0b714858719f07a1b0fc8a693e43c700c8144a7
11,864
cpp
C++
src/Core/EulerOps/GlueVert.cpp
lsimic/AobaAPI
5bb17a1055cd1621eebeb91844c2f8b4a3572cb8
[ "MIT" ]
9
2021-05-16T19:49:09.000Z
2021-12-02T17:42:30.000Z
src/Core/EulerOps/GlueVert.cpp
lsimic/AobaAPI
5bb17a1055cd1621eebeb91844c2f8b4a3572cb8
[ "MIT" ]
null
null
null
src/Core/EulerOps/GlueVert.cpp
lsimic/AobaAPI
5bb17a1055cd1621eebeb91844c2f8b4a3572cb8
[ "MIT" ]
null
null
null
#include "AobaAPI/Core/EulerOps.hpp" #include "AobaAPI/Core/Mesh.hpp" #include <algorithm> namespace Aoba { namespace Core { void deleteMergeableFaces(Edge* v1e1, Edge* v1e2, Edge* v2e1, Edge* v2e2) { // check if v1e1, v1e2 share a face std::vector<Face*> facesv1 = std::vector<Face*>(); for(Face* fe1 : v1e1->Faces()) { for(Face* fe2 : v1e2->Faces()) { if(fe1 == fe2) { facesv1.push_back(fe1); } } } if(facesv1.size() < 1) { return; } // check if v2e1, v2e2 share a face std::vector<Face*> facesv2 = std::vector<Face*>(); for(Face* fe1 : v2e1->Faces()) { for(Face* fe2 : v2e2->Faces()) { if(fe1 == fe2) { facesv2.push_back(fe1); } } } if(facesv2.size() < 1) { return; } // both edges around v1 and both edges around v2 have a common face // for each face in facesv1, check if there are faces in facesf2 which match the rest of it's loop std::vector<Face*> facesToKill = std::vector<Face*>(); for(Face* fv1 : facesv1) { std::vector<Edge*> fv1Edges = fv1->Edges(); for(Face* fv2 : facesv2) { bool notFound = false; for(Edge* fv2Edge : fv2->Edges()) { if(fv2Edge != v2e1 && fv2Edge != v2e2) { // ignoring edges aroud v2, v1 // checking edges here. if the faces are same, edges will be same, but opposite orientation if(std::find(fv1Edges.begin(), fv1Edges.end(), fv2Edge) == fv1Edges.end()) { // edge from face fv2 was not found in face fv1 notFound = true; break; } } } if(!notFound) { // found all edges of fv2 in fv1 // mark fv2 for deletion facesToKill.push_back(fv2); } } } for(Face* f : facesToKill) { KillFace(f); } } // this code is... interesting // several parts are rather costly, and some checks could be separated, at the cost of safety void GlueVert(Vert* v1, Vert* v2) { std::vector<Edge*> v1Edges = v1->Edges(); std::vector<Edge*> v2Edges = v2->Edges(); // check if there is an edge between v1, v2 Edge* common = nullptr; for(Edge* e : v1Edges) { if(e->Other(v1) == v2) { common = e; break; } } // TODO: in order to handle the case where v1 and v2 belong to the same face // but do not share an edge // call manifoldMakeEdge, to split the face // if the remaining faces are triangles, they will get dissolved. // not the ideal solution, but works if(common == nullptr) { // check if v1 and v2 are used by the same face... Face* found = nullptr; std::vector<Face*> v1Faces = v1->Faces(); std::vector<Face*> v2Faces = v2->Faces(); for(Face* f1 : v1Faces) { if(std::find(v2Faces.begin(), v2Faces.end(), f1) != v2Faces.end()) { // edge from face fv2 was not found in face fv1 found = f1; break; } } if(found != nullptr) { // v1 and v2 are used in the same face // split the face using manifoldMakeEdge Edge* newe = new Edge(); Face* newf = new Face(); ManifoldMakeEdge(v1, v2, found, newe, newf); common = newe; } } // find edge pairs and their appropriate vertices. // edge pairs are pairs of edges(e1, e2), where e1 is from v1->Edges() and v2 is from v2->Edges() // such that e1->Other(v1) == ev->Other(v2) std::vector<Edge*> v1PairEdges = std::vector<Edge*>(); std::vector<Edge*> v2PairEdges = std::vector<Edge*>(); std::vector<Edge*> v2OtherEdges = std::vector<Edge*>(); for(Edge* v2Edge : v2Edges) { bool found = false; for(Edge* v1Edge : v1Edges) { if(v1Edge->Other(v1) == v2Edge->Other(v2)) { v1PairEdges.push_back(v1Edge); v2PairEdges.push_back(v2Edge); found = true; break; } } if(!found) { // edge of v2 does not share vertices with any edges of v1 if(v2Edge != common) { v2OtherEdges.push_back(v2Edge); } } } // find suspicious face pairs // suspicious face pairs are pairs of faces(f1 from v1->faces(), f2 from v2->faces()), // such that edges from two edge pairs(v1, v2) are utilized in the face loop // if first pair is named (e11, e21) and second pair (e21, e22), // f1 contains e11, e12, and f2 contains e21, e22 // mergeable faces are suspicious face pairs, which use the same edges inside their loops, // except the edges currently being merged. // if mergeable faces are found, delete faces from face pairs which utilize v2 if(v1PairEdges.size() > 1) { for(int i = 0; i < v1PairEdges.size() - 1; ++i) { for(int j = i + 1; j < v1PairEdges.size(); ++j) { deleteMergeableFaces(v1PairEdges.at(i), v1PairEdges.at(j), v2PairEdges.at(i), v2PairEdges.at(j)); } } } if(common != nullptr) { // check if common edge has faces // TODO: this can likely be optimized for(Face* face : common->Faces()) { if(face->Loops().size() <= 3) { // faces with loops < 3 should not exist, but check anyways // if face has 3 loops, this means that it's a triangle // therefore, it's edges are already inside pairEdges lists. // kill the face. KillFace(face); } else { // face has 4 or more loops, therefore, it will remain // find the loop which uses this edge and remove it from face list via fNext, fPrev std::vector<Loop*> loops = common->Loops(); for(Loop* loop : loops) { if(loop->f == face) { // remove loop from face list of loops loop->fNext->fPrev = loop->fPrev; loop->fPrev->fNext = loop->fNext; if(face->l == loop) { face->l = loop->fNext; } // remove loop from edge list of loops if(loop->eNext == loop && loop->ePrev == loop) { // this is the last loop of this edge common->l = nullptr; } else { common->l = loop->eNext; loop->ePrev->eNext = loop->eNext; loop->eNext->ePrev = loop->ePrev; } delete loop; break; } } } } // at this point, nothing should reference the common edge, kill it. // this will remove it from v1, v2 lists. KillEdge(common); } // for edges without a pair which will not be merged, // remove all v2 references from edges and loops and replace them with references to v1 // add the edge to list of edges around v1 for(Edge* edge : v2OtherEdges) { if(edge->v1 == v2) { edge->v1 = v1; if(v1->e == nullptr) { v1->e = edge; edge->v1Next = edge; edge->v1Prev = edge; } else { // v1 already has some edges Edge* current = v1->e; Edge* prev = current->Prev(v1); // v1->e = edge; edge->v1Prev = prev; edge->v1Next = current; // must check wether v1 is v1 or v2 in current and previous edge if(current->v1 == v1) { current->v1Prev = edge; } else { current->v2Prev = edge; } if(prev->v1 == v1) { prev->v1Next = edge; } else { prev->v2Next = edge; } } } else { edge->v2 = v1; if(v1->e == nullptr) { v1->e = edge; edge->v2Next = edge; edge->v2Prev = edge; } else { // v1 already has some edges Edge* current = v1->e; Edge* prev = current->Prev(v1); // v1->e = edge; edge->v2Prev = prev; edge->v2Next = current; // must check wether v1 is v1 or v2 in current and previous edge if(current->v1 == v1) { current->v1Prev = edge; } else { current->v2Prev = edge; } if(prev->v1 == v1) { prev->v1Next = edge; } else { prev->v2Next = edge; } } } for(Loop* loop : edge->Loops()) { if(loop->v == v2) { loop->v = v1; } } } // for edges with pairs // replace all references to e2 edges with e1 edges // delete e2 edges for(std::size_t i = 0; i < v2PairEdges.size(); ++i) { Edge* edge = v2PairEdges.at(i); Edge* pairEdge = v1PairEdges.at(i); for(Loop* loop : edge->Loops()) { loop->e = pairEdge; if(loop->v == v2) { loop->v = v1; } // add loop to list of loops around e if(pairEdge->l == nullptr) { pairEdge->l = loop; loop->eNext = loop; loop->ePrev = loop; } else { // edge already has some adjecent loops Loop* currentLoop = pairEdge->l; Loop* prevLoop = currentLoop->ePrev; pairEdge->l = loop; loop->ePrev = prevLoop; loop->eNext = currentLoop; currentLoop->ePrev = loop; prevLoop->eNext = loop; } } // remove edge from list of edges around pair vert. // other edge will always have at least one edge connected // otherwise it wouldn't be in this list Edge* prev; Edge* next; Vert* other = edge->Other(v2); if(edge->v2 == other) { // use v2next, v2prev prev = edge->v2Prev; next = edge->v2Next; } else { // use v1next, v1prev prev = edge->v1Prev; next = edge->v1Next; } if(next->v1 == other) { next->v1Prev = prev; } else { next->v2Prev = prev; } if(prev->v1 == other) { prev->v1Next = next; } else { prev->v2Next = next; } // remove edge from mesh list of edges if(edge->mNext == edge && edge->mPrev == edge) { edge->m->edges = nullptr; } else { edge->mPrev->mNext = edge->mNext; edge->mNext->mPrev = edge->mPrev; if(edge->m->edges == edge) { edge->m->edges = edge->mNext; } } delete edge; } // remove v2 from mesh list of verts // not checking if v2 is last, because v1 must remain v2->mPrev->mNext = v2->mNext; v2->mNext->mPrev = v2->mPrev; if(v2->m->verts == v2) { v2->m->verts = v2->mNext; } delete v2; return; } } // namespace Core } // namespace Aoba
34.190202
113
0.472353
[ "mesh", "vector" ]
d0b9d41f41e0cbd9e9ca83e31f90d7965f16864e
32,232
cc
C++
examples/pxScene2d/external/libnode-v10.15.3/deps/v8/src/x64/code-stubs-x64.cc
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
examples/pxScene2d/external/libnode-v10.15.3/deps/v8/src/x64/code-stubs-x64.cc
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
1,432
2017-06-21T04:08:48.000Z
2020-08-25T16:21:15.000Z
examples/pxScene2d/external/libnode-v10.15.3/deps/v8/src/x64/code-stubs-x64.cc
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2013 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #if V8_TARGET_ARCH_X64 #include "src/api-arguments.h" #include "src/bootstrapper.h" #include "src/code-stubs.h" #include "src/counters.h" #include "src/double.h" #include "src/frame-constants.h" #include "src/frames.h" #include "src/heap/heap-inl.h" #include "src/ic/ic.h" #include "src/ic/stub-cache.h" #include "src/isolate.h" #include "src/objects-inl.h" #include "src/objects/api-callbacks.h" #include "src/objects/regexp-match-info.h" #include "src/regexp/jsregexp.h" #include "src/regexp/regexp-macro-assembler.h" #include "src/runtime/runtime.h" namespace v8 { namespace internal { #define __ ACCESS_MASM(masm) void ArrayNArgumentsConstructorStub::Generate(MacroAssembler* masm) { __ popq(rcx); __ movq(MemOperand(rsp, rax, times_8, 0), rdi); __ pushq(rdi); __ pushq(rbx); __ pushq(rcx); __ addq(rax, Immediate(3)); __ TailCallRuntime(Runtime::kNewArray); } void CodeStub::GenerateStubsAheadOfTime(Isolate* isolate) { // It is important that the store buffer overflow stubs are generated first. CommonArrayConstructorStub::GenerateStubsAheadOfTime(isolate); StoreFastElementStub::GenerateAheadOfTime(isolate); } void JSEntryStub::Generate(MacroAssembler* masm) { Label invoke, handler_entry, exit; Label not_outermost_js, not_outermost_js_2; ProfileEntryHookStub::MaybeCallEntryHook(masm); { // NOLINT. Scope block confuses linter. NoRootArrayScope uninitialized_root_register(masm); // Set up frame. __ pushq(rbp); __ movp(rbp, rsp); // Push the stack frame type. __ Push(Immediate(StackFrame::TypeToMarker(type()))); // context slot ExternalReference context_address = ExternalReference::Create(IsolateAddressId::kContextAddress, isolate()); __ Load(kScratchRegister, context_address); __ Push(kScratchRegister); // context // Save callee-saved registers (X64/X32/Win64 calling conventions). __ pushq(r12); __ pushq(r13); __ pushq(r14); __ pushq(r15); #ifdef _WIN64 __ pushq(rdi); // Only callee save in Win64 ABI, argument in AMD64 ABI. __ pushq(rsi); // Only callee save in Win64 ABI, argument in AMD64 ABI. #endif __ pushq(rbx); #ifdef _WIN64 // On Win64 XMM6-XMM15 are callee-save __ subp(rsp, Immediate(EntryFrameConstants::kXMMRegistersBlockSize)); __ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 0), xmm6); __ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 1), xmm7); __ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 2), xmm8); __ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 3), xmm9); __ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 4), xmm10); __ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 5), xmm11); __ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 6), xmm12); __ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 7), xmm13); __ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 8), xmm14); __ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 9), xmm15); #endif // Set up the roots and smi constant registers. // Needs to be done before any further smi loads. __ InitializeRootRegister(); } // Save copies of the top frame descriptor on the stack. ExternalReference c_entry_fp = ExternalReference::Create(IsolateAddressId::kCEntryFPAddress, isolate()); { Operand c_entry_fp_operand = masm->ExternalOperand(c_entry_fp); __ Push(c_entry_fp_operand); } // If this is the outermost JS call, set js_entry_sp value. ExternalReference js_entry_sp = ExternalReference::Create(IsolateAddressId::kJSEntrySPAddress, isolate()); __ Load(rax, js_entry_sp); __ testp(rax, rax); __ j(not_zero, &not_outermost_js); __ Push(Immediate(StackFrame::OUTERMOST_JSENTRY_FRAME)); __ movp(rax, rbp); __ Store(js_entry_sp, rax); Label cont; __ jmp(&cont); __ bind(&not_outermost_js); __ Push(Immediate(StackFrame::INNER_JSENTRY_FRAME)); __ bind(&cont); // Jump to a faked try block that does the invoke, with a faked catch // block that sets the pending exception. __ jmp(&invoke); __ bind(&handler_entry); handler_offset_ = handler_entry.pos(); // Caught exception: Store result (exception) in the pending exception // field in the JSEnv and return a failure sentinel. ExternalReference pending_exception = ExternalReference::Create( IsolateAddressId::kPendingExceptionAddress, isolate()); __ Store(pending_exception, rax); __ LoadRoot(rax, Heap::kExceptionRootIndex); __ jmp(&exit); // Invoke: Link this frame into the handler chain. __ bind(&invoke); __ PushStackHandler(); // Invoke the function by calling through JS entry trampoline builtin and // pop the faked function when we return. We load the address from an // external reference instead of inlining the call target address directly // in the code, because the builtin stubs may not have been generated yet // at the time this code is generated. __ Call(EntryTrampoline(), RelocInfo::CODE_TARGET); // Unlink this frame from the handler chain. __ PopStackHandler(); __ bind(&exit); // Check if the current stack frame is marked as the outermost JS frame. __ Pop(rbx); __ cmpp(rbx, Immediate(StackFrame::OUTERMOST_JSENTRY_FRAME)); __ j(not_equal, &not_outermost_js_2); __ Move(kScratchRegister, js_entry_sp); __ movp(Operand(kScratchRegister, 0), Immediate(0)); __ bind(&not_outermost_js_2); // Restore the top frame descriptor from the stack. { Operand c_entry_fp_operand = masm->ExternalOperand(c_entry_fp); __ Pop(c_entry_fp_operand); } // Restore callee-saved registers (X64 conventions). #ifdef _WIN64 // On Win64 XMM6-XMM15 are callee-save __ movdqu(xmm6, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 0)); __ movdqu(xmm7, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 1)); __ movdqu(xmm8, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 2)); __ movdqu(xmm9, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 3)); __ movdqu(xmm10, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 4)); __ movdqu(xmm11, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 5)); __ movdqu(xmm12, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 6)); __ movdqu(xmm13, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 7)); __ movdqu(xmm14, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 8)); __ movdqu(xmm15, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 9)); __ addp(rsp, Immediate(EntryFrameConstants::kXMMRegistersBlockSize)); #endif __ popq(rbx); #ifdef _WIN64 // Callee save on in Win64 ABI, arguments/volatile in AMD64 ABI. __ popq(rsi); __ popq(rdi); #endif __ popq(r15); __ popq(r14); __ popq(r13); __ popq(r12); __ addp(rsp, Immediate(2 * kPointerSize)); // remove markers // Restore frame pointer and return. __ popq(rbp); __ ret(0); } void ProfileEntryHookStub::MaybeCallEntryHook(MacroAssembler* masm) { if (masm->isolate()->function_entry_hook() != nullptr) { ProfileEntryHookStub stub(masm->isolate()); masm->CallStub(&stub); } } void ProfileEntryHookStub::MaybeCallEntryHookDelayed(TurboAssembler* tasm, Zone* zone) { if (tasm->isolate()->function_entry_hook() != nullptr) { tasm->CallStubDelayed(new (zone) ProfileEntryHookStub(nullptr)); } } void ProfileEntryHookStub::Generate(MacroAssembler* masm) { // This stub can be called from essentially anywhere, so it needs to save // all volatile and callee-save registers. const size_t kNumSavedRegisters = 2; __ pushq(arg_reg_1); __ pushq(arg_reg_2); // Calculate the original stack pointer and store it in the second arg. __ leap(arg_reg_2, Operand(rsp, kNumSavedRegisters * kRegisterSize + kPCOnStackSize)); // Calculate the function address to the first arg. __ movp(arg_reg_1, Operand(rsp, kNumSavedRegisters * kRegisterSize)); __ subp(arg_reg_1, Immediate(Assembler::kShortCallInstructionLength)); // Save the remainder of the volatile registers. masm->PushCallerSaved(kSaveFPRegs, arg_reg_1, arg_reg_2); // Call the entry hook function. __ Move(rax, FUNCTION_ADDR(isolate()->function_entry_hook()), RelocInfo::NONE); AllowExternalCallThatCantCauseGC scope(masm); const int kArgumentCount = 2; __ PrepareCallCFunction(kArgumentCount); __ CallCFunction(rax, kArgumentCount); // Restore volatile regs. masm->PopCallerSaved(kSaveFPRegs, arg_reg_1, arg_reg_2); __ popq(arg_reg_2); __ popq(arg_reg_1); __ Ret(); } template<class T> static void CreateArrayDispatch(MacroAssembler* masm, AllocationSiteOverrideMode mode) { if (mode == DISABLE_ALLOCATION_SITES) { T stub(masm->isolate(), GetInitialFastElementsKind(), mode); __ TailCallStub(&stub); } else if (mode == DONT_OVERRIDE) { int last_index = GetSequenceIndexFromFastElementsKind(TERMINAL_FAST_ELEMENTS_KIND); for (int i = 0; i <= last_index; ++i) { Label next; ElementsKind kind = GetFastElementsKindFromSequenceIndex(i); __ cmpl(rdx, Immediate(kind)); __ j(not_equal, &next); T stub(masm->isolate(), kind); __ TailCallStub(&stub); __ bind(&next); } // If we reached this point there is a problem. __ Abort(AbortReason::kUnexpectedElementsKindInArrayConstructor); } else { UNREACHABLE(); } } static void CreateArrayDispatchOneArgument(MacroAssembler* masm, AllocationSiteOverrideMode mode) { // rbx - allocation site (if mode != DISABLE_ALLOCATION_SITES) // rdx - kind (if mode != DISABLE_ALLOCATION_SITES) // rax - number of arguments // rdi - constructor? // rsp[0] - return address // rsp[8] - last argument STATIC_ASSERT(PACKED_SMI_ELEMENTS == 0); STATIC_ASSERT(HOLEY_SMI_ELEMENTS == 1); STATIC_ASSERT(PACKED_ELEMENTS == 2); STATIC_ASSERT(HOLEY_ELEMENTS == 3); STATIC_ASSERT(PACKED_DOUBLE_ELEMENTS == 4); STATIC_ASSERT(HOLEY_DOUBLE_ELEMENTS == 5); if (mode == DISABLE_ALLOCATION_SITES) { ElementsKind initial = GetInitialFastElementsKind(); ElementsKind holey_initial = GetHoleyElementsKind(initial); ArraySingleArgumentConstructorStub stub_holey(masm->isolate(), holey_initial, DISABLE_ALLOCATION_SITES); __ TailCallStub(&stub_holey); } else if (mode == DONT_OVERRIDE) { // is the low bit set? If so, we are holey and that is good. Label normal_sequence; __ testb(rdx, Immediate(1)); __ j(not_zero, &normal_sequence); // We are going to create a holey array, but our kind is non-holey. // Fix kind and retry (only if we have an allocation site in the slot). __ incl(rdx); if (FLAG_debug_code) { Handle<Map> allocation_site_map = masm->isolate()->factory()->allocation_site_map(); __ Cmp(FieldOperand(rbx, 0), allocation_site_map); __ Assert(equal, AbortReason::kExpectedAllocationSite); } // Save the resulting elements kind in type info. We can't just store r3 // in the AllocationSite::transition_info field because elements kind is // restricted to a portion of the field...upper bits need to be left alone. STATIC_ASSERT(AllocationSite::ElementsKindBits::kShift == 0); __ SmiAddConstant( FieldOperand(rbx, AllocationSite::kTransitionInfoOrBoilerplateOffset), Smi::FromInt(kFastElementsKindPackedToHoley)); __ bind(&normal_sequence); int last_index = GetSequenceIndexFromFastElementsKind(TERMINAL_FAST_ELEMENTS_KIND); for (int i = 0; i <= last_index; ++i) { Label next; ElementsKind kind = GetFastElementsKindFromSequenceIndex(i); __ cmpl(rdx, Immediate(kind)); __ j(not_equal, &next); ArraySingleArgumentConstructorStub stub(masm->isolate(), kind); __ TailCallStub(&stub); __ bind(&next); } // If we reached this point there is a problem. __ Abort(AbortReason::kUnexpectedElementsKindInArrayConstructor); } else { UNREACHABLE(); } } template<class T> static void ArrayConstructorStubAheadOfTimeHelper(Isolate* isolate) { int to_index = GetSequenceIndexFromFastElementsKind(TERMINAL_FAST_ELEMENTS_KIND); for (int i = 0; i <= to_index; ++i) { ElementsKind kind = GetFastElementsKindFromSequenceIndex(i); T stub(isolate, kind); stub.GetCode(); if (AllocationSite::ShouldTrack(kind)) { T stub1(isolate, kind, DISABLE_ALLOCATION_SITES); stub1.GetCode(); } } } void CommonArrayConstructorStub::GenerateStubsAheadOfTime(Isolate* isolate) { ArrayConstructorStubAheadOfTimeHelper<ArrayNoArgumentConstructorStub>( isolate); ArrayConstructorStubAheadOfTimeHelper<ArraySingleArgumentConstructorStub>( isolate); ArrayNArgumentsConstructorStub stub(isolate); stub.GetCode(); ElementsKind kinds[2] = {PACKED_ELEMENTS, HOLEY_ELEMENTS}; for (int i = 0; i < 2; i++) { // For internal arrays we only need a few things InternalArrayNoArgumentConstructorStub stubh1(isolate, kinds[i]); stubh1.GetCode(); InternalArraySingleArgumentConstructorStub stubh2(isolate, kinds[i]); stubh2.GetCode(); } } void ArrayConstructorStub::GenerateDispatchToArrayStub( MacroAssembler* masm, AllocationSiteOverrideMode mode) { Label not_zero_case, not_one_case; __ testp(rax, rax); __ j(not_zero, &not_zero_case); CreateArrayDispatch<ArrayNoArgumentConstructorStub>(masm, mode); __ bind(&not_zero_case); __ cmpl(rax, Immediate(1)); __ j(greater, &not_one_case); CreateArrayDispatchOneArgument(masm, mode); __ bind(&not_one_case); ArrayNArgumentsConstructorStub stub(masm->isolate()); __ TailCallStub(&stub); } void ArrayConstructorStub::Generate(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- rax : argc // -- rbx : AllocationSite or undefined // -- rdi : constructor // -- rdx : new target // -- rsp[0] : return address // -- rsp[8] : last argument // ----------------------------------- if (FLAG_debug_code) { // The array construct code is only set for the global and natives // builtin Array functions which always have maps. // Initial map for the builtin Array function should be a map. __ movp(rcx, FieldOperand(rdi, JSFunction::kPrototypeOrInitialMapOffset)); // Will both indicate a nullptr and a Smi. STATIC_ASSERT(kSmiTag == 0); Condition not_smi = NegateCondition(masm->CheckSmi(rcx)); __ Check(not_smi, AbortReason::kUnexpectedInitialMapForArrayFunction); __ CmpObjectType(rcx, MAP_TYPE, rcx); __ Check(equal, AbortReason::kUnexpectedInitialMapForArrayFunction); // We should either have undefined in rbx or a valid AllocationSite __ AssertUndefinedOrAllocationSite(rbx); } // Enter the context of the Array function. __ movp(rsi, FieldOperand(rdi, JSFunction::kContextOffset)); Label subclassing; __ cmpp(rdi, rdx); __ j(not_equal, &subclassing); Label no_info; // If the feedback vector is the undefined value call an array constructor // that doesn't use AllocationSites. __ CompareRoot(rbx, Heap::kUndefinedValueRootIndex); __ j(equal, &no_info); // Only look at the lower 16 bits of the transition info. __ movp(rdx, FieldOperand( rbx, AllocationSite::kTransitionInfoOrBoilerplateOffset)); __ SmiToInteger32(rdx, rdx); STATIC_ASSERT(AllocationSite::ElementsKindBits::kShift == 0); __ andp(rdx, Immediate(AllocationSite::ElementsKindBits::kMask)); GenerateDispatchToArrayStub(masm, DONT_OVERRIDE); __ bind(&no_info); GenerateDispatchToArrayStub(masm, DISABLE_ALLOCATION_SITES); // Subclassing __ bind(&subclassing); StackArgumentsAccessor args(rsp, rax); __ movp(args.GetReceiverOperand(), rdi); __ addp(rax, Immediate(3)); __ PopReturnAddressTo(rcx); __ Push(rdx); __ Push(rbx); __ PushReturnAddressFrom(rcx); __ JumpToExternalReference(ExternalReference::Create(Runtime::kNewArray)); } void InternalArrayConstructorStub::GenerateCase( MacroAssembler* masm, ElementsKind kind) { Label not_zero_case, not_one_case; Label normal_sequence; __ testp(rax, rax); __ j(not_zero, &not_zero_case); InternalArrayNoArgumentConstructorStub stub0(isolate(), kind); __ TailCallStub(&stub0); __ bind(&not_zero_case); __ cmpl(rax, Immediate(1)); __ j(greater, &not_one_case); if (IsFastPackedElementsKind(kind)) { // We might need to create a holey array // look at the first argument StackArgumentsAccessor args(rsp, 1, ARGUMENTS_DONT_CONTAIN_RECEIVER); __ movp(rcx, args.GetArgumentOperand(0)); __ testp(rcx, rcx); __ j(zero, &normal_sequence); InternalArraySingleArgumentConstructorStub stub1_holey(isolate(), GetHoleyElementsKind(kind)); __ TailCallStub(&stub1_holey); } __ bind(&normal_sequence); InternalArraySingleArgumentConstructorStub stub1(isolate(), kind); __ TailCallStub(&stub1); __ bind(&not_one_case); ArrayNArgumentsConstructorStub stubN(isolate()); __ TailCallStub(&stubN); } void InternalArrayConstructorStub::Generate(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- rax : argc // -- rdi : constructor // -- rsp[0] : return address // -- rsp[8] : last argument // ----------------------------------- if (FLAG_debug_code) { // The array construct code is only set for the global and natives // builtin Array functions which always have maps. // Initial map for the builtin Array function should be a map. __ movp(rcx, FieldOperand(rdi, JSFunction::kPrototypeOrInitialMapOffset)); // Will both indicate a nullptr and a Smi. STATIC_ASSERT(kSmiTag == 0); Condition not_smi = NegateCondition(masm->CheckSmi(rcx)); __ Check(not_smi, AbortReason::kUnexpectedInitialMapForArrayFunction); __ CmpObjectType(rcx, MAP_TYPE, rcx); __ Check(equal, AbortReason::kUnexpectedInitialMapForArrayFunction); } // Figure out the right elements kind __ movp(rcx, FieldOperand(rdi, JSFunction::kPrototypeOrInitialMapOffset)); // Load the map's "bit field 2" into |result|. We only need the first byte, // but the following masking takes care of that anyway. __ movzxbp(rcx, FieldOperand(rcx, Map::kBitField2Offset)); // Retrieve elements_kind from bit field 2. __ DecodeField<Map::ElementsKindBits>(rcx); if (FLAG_debug_code) { Label done; __ cmpl(rcx, Immediate(PACKED_ELEMENTS)); __ j(equal, &done); __ cmpl(rcx, Immediate(HOLEY_ELEMENTS)); __ Assert( equal, AbortReason::kInvalidElementsKindForInternalArrayOrInternalPackedArray); __ bind(&done); } Label fast_elements_case; __ cmpl(rcx, Immediate(PACKED_ELEMENTS)); __ j(equal, &fast_elements_case); GenerateCase(masm, HOLEY_ELEMENTS); __ bind(&fast_elements_case); GenerateCase(masm, PACKED_ELEMENTS); } static int Offset(ExternalReference ref0, ExternalReference ref1) { int64_t offset = (ref0.address() - ref1.address()); // Check that fits into int. DCHECK(static_cast<int>(offset) == offset); return static_cast<int>(offset); } // Prepares stack to put arguments (aligns and so on). WIN64 calling convention // requires to put the pointer to the return value slot into rcx (rcx must be // preserverd until CallApiFunctionAndReturn). Clobbers rax. Allocates // arg_stack_space * kPointerSize inside the exit frame (not GCed) accessible // via StackSpaceOperand. static void PrepareCallApiFunction(MacroAssembler* masm, int arg_stack_space) { __ EnterApiExitFrame(arg_stack_space); } // Calls an API function. Allocates HandleScope, extracts returned value // from handle and propagates exceptions. Clobbers r14, r15, rbx and // caller-save registers. Restores context. On return removes // stack_space * kPointerSize (GCed). static void CallApiFunctionAndReturn(MacroAssembler* masm, Register function_address, ExternalReference thunk_ref, Register thunk_last_arg, int stack_space, Operand* stack_space_operand, Operand return_value_operand) { Label prologue; Label promote_scheduled_exception; Label delete_allocated_handles; Label leave_exit_frame; Label write_back; Isolate* isolate = masm->isolate(); Factory* factory = isolate->factory(); ExternalReference next_address = ExternalReference::handle_scope_next_address(isolate); const int kNextOffset = 0; const int kLimitOffset = Offset( ExternalReference::handle_scope_limit_address(isolate), next_address); const int kLevelOffset = Offset( ExternalReference::handle_scope_level_address(isolate), next_address); ExternalReference scheduled_exception_address = ExternalReference::scheduled_exception_address(isolate); DCHECK(rdx == function_address || r8 == function_address); // Allocate HandleScope in callee-save registers. Register prev_next_address_reg = r14; Register prev_limit_reg = rbx; Register base_reg = r15; __ Move(base_reg, next_address); __ movp(prev_next_address_reg, Operand(base_reg, kNextOffset)); __ movp(prev_limit_reg, Operand(base_reg, kLimitOffset)); __ addl(Operand(base_reg, kLevelOffset), Immediate(1)); if (FLAG_log_timer_events) { FrameScope frame(masm, StackFrame::MANUAL); __ PushSafepointRegisters(); __ PrepareCallCFunction(1); __ LoadAddress(arg_reg_1, ExternalReference::isolate_address(isolate)); __ CallCFunction(ExternalReference::log_enter_external_function(), 1); __ PopSafepointRegisters(); } Label profiler_disabled; Label end_profiler_check; __ Move(rax, ExternalReference::is_profiling_address(isolate)); __ cmpb(Operand(rax, 0), Immediate(0)); __ j(zero, &profiler_disabled); // Third parameter is the address of the actual getter function. __ Move(thunk_last_arg, function_address); __ Move(rax, thunk_ref); __ jmp(&end_profiler_check); __ bind(&profiler_disabled); // Call the api function! __ Move(rax, function_address); __ bind(&end_profiler_check); // Call the api function! __ call(rax); if (FLAG_log_timer_events) { FrameScope frame(masm, StackFrame::MANUAL); __ PushSafepointRegisters(); __ PrepareCallCFunction(1); __ LoadAddress(arg_reg_1, ExternalReference::isolate_address(isolate)); __ CallCFunction(ExternalReference::log_leave_external_function(), 1); __ PopSafepointRegisters(); } // Load the value from ReturnValue __ movp(rax, return_value_operand); __ bind(&prologue); // No more valid handles (the result handle was the last one). Restore // previous handle scope. __ subl(Operand(base_reg, kLevelOffset), Immediate(1)); __ movp(Operand(base_reg, kNextOffset), prev_next_address_reg); __ cmpp(prev_limit_reg, Operand(base_reg, kLimitOffset)); __ j(not_equal, &delete_allocated_handles); // Leave the API exit frame. __ bind(&leave_exit_frame); if (stack_space_operand != nullptr) { __ movp(rbx, *stack_space_operand); } __ LeaveApiExitFrame(); // Check if the function scheduled an exception. __ Move(rdi, scheduled_exception_address); __ Cmp(Operand(rdi, 0), factory->the_hole_value()); __ j(not_equal, &promote_scheduled_exception); #if DEBUG // Check if the function returned a valid JavaScript value. Label ok; Register return_value = rax; Register map = rcx; __ JumpIfSmi(return_value, &ok, Label::kNear); __ movp(map, FieldOperand(return_value, HeapObject::kMapOffset)); __ CmpInstanceType(map, LAST_NAME_TYPE); __ j(below_equal, &ok, Label::kNear); __ CmpInstanceType(map, FIRST_JS_RECEIVER_TYPE); __ j(above_equal, &ok, Label::kNear); __ CompareRoot(map, Heap::kHeapNumberMapRootIndex); __ j(equal, &ok, Label::kNear); __ CompareRoot(return_value, Heap::kUndefinedValueRootIndex); __ j(equal, &ok, Label::kNear); __ CompareRoot(return_value, Heap::kTrueValueRootIndex); __ j(equal, &ok, Label::kNear); __ CompareRoot(return_value, Heap::kFalseValueRootIndex); __ j(equal, &ok, Label::kNear); __ CompareRoot(return_value, Heap::kNullValueRootIndex); __ j(equal, &ok, Label::kNear); __ Abort(AbortReason::kAPICallReturnedInvalidObject); __ bind(&ok); #endif if (stack_space_operand != nullptr) { DCHECK_EQ(stack_space, 0); __ PopReturnAddressTo(rcx); __ addq(rsp, rbx); __ jmp(rcx); } else { __ ret(stack_space * kPointerSize); } // Re-throw by promoting a scheduled exception. __ bind(&promote_scheduled_exception); __ TailCallRuntime(Runtime::kPromoteScheduledException); // HandleScope limit has changed. Delete allocated extensions. __ bind(&delete_allocated_handles); __ movp(Operand(base_reg, kLimitOffset), prev_limit_reg); __ movp(prev_limit_reg, rax); __ LoadAddress(arg_reg_1, ExternalReference::isolate_address(isolate)); __ LoadAddress(rax, ExternalReference::delete_handle_scope_extensions()); __ call(rax); __ movp(rax, prev_limit_reg); __ jmp(&leave_exit_frame); } void CallApiCallbackStub::Generate(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- rbx : call_data // -- rcx : holder // -- rdx : api_function_address // -- rsi : context // -- rax : number of arguments if argc is a register // -- rsp[0] : return address // -- rsp[8] : last argument // -- ... // -- rsp[argc * 8] : first argument // -- rsp[(argc + 1) * 8] : receiver // ----------------------------------- Register call_data = rbx; Register holder = rcx; Register api_function_address = rdx; Register return_address = r8; typedef FunctionCallbackArguments FCA; STATIC_ASSERT(FCA::kArgsLength == 6); STATIC_ASSERT(FCA::kNewTargetIndex == 5); STATIC_ASSERT(FCA::kDataIndex == 4); STATIC_ASSERT(FCA::kReturnValueOffset == 3); STATIC_ASSERT(FCA::kReturnValueDefaultValueIndex == 2); STATIC_ASSERT(FCA::kIsolateIndex == 1); STATIC_ASSERT(FCA::kHolderIndex == 0); __ PopReturnAddressTo(return_address); // new target __ PushRoot(Heap::kUndefinedValueRootIndex); // call data __ Push(call_data); // return value __ PushRoot(Heap::kUndefinedValueRootIndex); // return value default __ PushRoot(Heap::kUndefinedValueRootIndex); // isolate Register scratch = call_data; __ Move(scratch, ExternalReference::isolate_address(masm->isolate())); __ Push(scratch); // holder __ Push(holder); int argc = this->argc(); __ movp(scratch, rsp); // Push return address back on stack. __ PushReturnAddressFrom(return_address); // Allocate the v8::Arguments structure in the arguments' space since // it's not controlled by GC. const int kApiStackSpace = 3; PrepareCallApiFunction(masm, kApiStackSpace); // FunctionCallbackInfo::implicit_args_. __ movp(StackSpaceOperand(0), scratch); __ addp(scratch, Immediate((argc + FCA::kArgsLength - 1) * kPointerSize)); // FunctionCallbackInfo::values_. __ movp(StackSpaceOperand(1), scratch); // FunctionCallbackInfo::length_. __ Set(StackSpaceOperand(2), argc); #if defined(__MINGW64__) || defined(_WIN64) Register arguments_arg = rcx; Register callback_arg = rdx; #else Register arguments_arg = rdi; Register callback_arg = rsi; #endif // It's okay if api_function_address == callback_arg // but not arguments_arg DCHECK(api_function_address != arguments_arg); // v8::InvocationCallback's argument. __ leap(arguments_arg, StackSpaceOperand(0)); ExternalReference thunk_ref = ExternalReference::invoke_function_callback(); // Accessor for FunctionCallbackInfo and first js arg. StackArgumentsAccessor args_from_rbp(rbp, FCA::kArgsLength + 1, ARGUMENTS_DONT_CONTAIN_RECEIVER); Operand return_value_operand = args_from_rbp.GetArgumentOperand( FCA::kArgsLength - FCA::kReturnValueOffset); const int stack_space = argc + FCA::kArgsLength + 1; Operand* stack_space_operand = nullptr; CallApiFunctionAndReturn(masm, api_function_address, thunk_ref, callback_arg, stack_space, stack_space_operand, return_value_operand); } void CallApiGetterStub::Generate(MacroAssembler* masm) { #if defined(__MINGW64__) || defined(_WIN64) Register getter_arg = r8; Register accessor_info_arg = rdx; Register name_arg = rcx; #else Register getter_arg = rdx; Register accessor_info_arg = rsi; Register name_arg = rdi; #endif Register api_function_address = r8; Register receiver = ApiGetterDescriptor::ReceiverRegister(); Register holder = ApiGetterDescriptor::HolderRegister(); Register callback = ApiGetterDescriptor::CallbackRegister(); Register scratch = rax; DCHECK(!AreAliased(receiver, holder, callback, scratch)); // Build v8::PropertyCallbackInfo::args_ array on the stack and push property // name below the exit frame to make GC aware of them. STATIC_ASSERT(PropertyCallbackArguments::kShouldThrowOnErrorIndex == 0); STATIC_ASSERT(PropertyCallbackArguments::kHolderIndex == 1); STATIC_ASSERT(PropertyCallbackArguments::kIsolateIndex == 2); STATIC_ASSERT(PropertyCallbackArguments::kReturnValueDefaultValueIndex == 3); STATIC_ASSERT(PropertyCallbackArguments::kReturnValueOffset == 4); STATIC_ASSERT(PropertyCallbackArguments::kDataIndex == 5); STATIC_ASSERT(PropertyCallbackArguments::kThisIndex == 6); STATIC_ASSERT(PropertyCallbackArguments::kArgsLength == 7); // Insert additional parameters into the stack frame above return address. __ PopReturnAddressTo(scratch); __ Push(receiver); __ Push(FieldOperand(callback, AccessorInfo::kDataOffset)); __ LoadRoot(kScratchRegister, Heap::kUndefinedValueRootIndex); __ Push(kScratchRegister); // return value __ Push(kScratchRegister); // return value default __ PushAddress(ExternalReference::isolate_address(isolate())); __ Push(holder); __ Push(Smi::kZero); // should_throw_on_error -> false __ Push(FieldOperand(callback, AccessorInfo::kNameOffset)); __ PushReturnAddressFrom(scratch); // v8::PropertyCallbackInfo::args_ array and name handle. const int kStackUnwindSpace = PropertyCallbackArguments::kArgsLength + 1; // Allocate v8::PropertyCallbackInfo in non-GCed stack space. const int kArgStackSpace = 1; // Load address of v8::PropertyAccessorInfo::args_ array. __ leap(scratch, Operand(rsp, 2 * kPointerSize)); PrepareCallApiFunction(masm, kArgStackSpace); // Create v8::PropertyCallbackInfo object on the stack and initialize // it's args_ field. Operand info_object = StackSpaceOperand(0); __ movp(info_object, scratch); __ leap(name_arg, Operand(scratch, -kPointerSize)); // The context register (rsi) has been saved in PrepareCallApiFunction and // could be used to pass arguments. __ leap(accessor_info_arg, info_object); ExternalReference thunk_ref = ExternalReference::invoke_accessor_getter_callback(); // It's okay if api_function_address == getter_arg // but not accessor_info_arg or name_arg DCHECK(api_function_address != accessor_info_arg); DCHECK(api_function_address != name_arg); __ movp(scratch, FieldOperand(callback, AccessorInfo::kJsGetterOffset)); __ movp(api_function_address, FieldOperand(scratch, Foreign::kForeignAddressOffset)); // +3 is to skip prolog, return address and name handle. Operand return_value_operand( rbp, (PropertyCallbackArguments::kReturnValueOffset + 3) * kPointerSize); CallApiFunctionAndReturn(masm, api_function_address, thunk_ref, getter_arg, kStackUnwindSpace, nullptr, return_value_operand); } #undef __ } // namespace internal } // namespace v8 #endif // V8_TARGET_ARCH_X64
35.85317
80
0.716183
[ "object", "vector" ]
d0c2466be038c3091f651fca89e378eb811111f8
1,058
cc
C++
arc090_a.cc
mnrn/xxx-coder
2db331c57f15fbd36fbb61a5526afc07af010727
[ "MIT" ]
null
null
null
arc090_a.cc
mnrn/xxx-coder
2db331c57f15fbd36fbb61a5526afc07af010727
[ "MIT" ]
null
null
null
arc090_a.cc
mnrn/xxx-coder
2db331c57f15fbd36fbb61a5526afc07af010727
[ "MIT" ]
null
null
null
// #define _GLIBCXX_DEBUG #include <bits/stdc++.h> #define FOR(i, a, b) for (int i = (a); i < int(b); ++i) #define RFOR(i, a, b) for (int i = (b)-1; i >= int(a); --i) #define REP(i, n) FOR(i, 0, n) #define REP1(i, n) FOR(i, 1, int(n) + 1) #define RREP(i, n) RFOR(i, 0, n) #define RREP1(i, n) RFOR(i, 1, int(n) + 1) #define ALL(c) begin(c), end(c) int _ = ( #ifndef LOCAL std::cin.tie(nullptr), std::ios::sync_with_stdio(false), #endif std::cout.precision(10), std::cout.setf(std::ios::fixed)); using ll = long long; using ull = unsigned long long; using ld = long double; template <typename T> using vec = std::vector<T>; using namespace std; int main() { ll N; cin >> N; vec<ll> L(N), R(N); ll l, accl = 0; REP(i, N) { cin >> l; accl += l; L[i] = accl; } ll accr = 0; vec<ll> tmp(N); REP(i, N) cin >> tmp[i]; reverse(ALL(tmp)); REP(i, N) { accr += tmp[i]; R[i] = accr; } reverse(ALL(R)); ll answer = 0; REP(i, N) { answer = max(answer, L[i] + R[i]); } cout << answer << endl; return 0; }
20.745098
62
0.546314
[ "vector" ]
d0c3b2c8f4409fe1e0099dfb09f900411463eceb
27,595
cpp
C++
src/Connection_uLimeSDR/Connection_uLimeSDR.cpp
bastille-attic/LimeSuite
761805c75b1ae1e0ec9b8c6c182ebd058a088ab8
[ "Apache-2.0" ]
null
null
null
src/Connection_uLimeSDR/Connection_uLimeSDR.cpp
bastille-attic/LimeSuite
761805c75b1ae1e0ec9b8c6c182ebd058a088ab8
[ "Apache-2.0" ]
null
null
null
src/Connection_uLimeSDR/Connection_uLimeSDR.cpp
bastille-attic/LimeSuite
761805c75b1ae1e0ec9b8c6c182ebd058a088ab8
[ "Apache-2.0" ]
null
null
null
/** @file Connection_uLimeSDR.cpp @author Lime Microsystems @brief Implementation of STREAM board connection. */ #include "Connection_uLimeSDR.h" #include "ErrorReporting.h" #include <cstring> #include <iostream> #include <thread> #include <chrono> using namespace std; using namespace lime; #define USB_TIMEOUT 1000 Connection_uLimeSDR::Connection_uLimeSDR(void *arg) { mStreamWrEndPtAddr = 0x03; mStreamRdEndPtAddr = 0x83; isConnected = false; txSize = 0; rxSize = 0; #ifndef __unix__ mFTHandle = NULL; #else dev_handle = 0; devs = 0; mUsbCounter = 0; ctx = (libusb_context *)arg; #endif } /** @brief Initializes port type and object necessary to communicate to usb device. */ Connection_uLimeSDR::Connection_uLimeSDR(void *arg, const unsigned index, const int vid, const int pid) { mStreamWrEndPtAddr = 0x03; mStreamRdEndPtAddr = 0x83; isConnected = false; txSize = 0; rxSize = 0; #ifndef __unix__ mFTHandle = NULL; #else dev_handle = 0; devs = 0; mUsbCounter = 0; ctx = (libusb_context *)arg; #endif if(this->Open(index, vid, pid) != 0) std::cerr << GetLastErrorMessage() << std::endl; } /** @brief Closes connection to chip and deallocates used memory. */ Connection_uLimeSDR::~Connection_uLimeSDR() { mStreamService.reset(); Close(); } #ifdef __unix__ int Connection_uLimeSDR::FT_FlushPipe(unsigned char ep) { int actual = 0; unsigned char wbuffer[20]={0}; mUsbCounter++; wbuffer[0] = (mUsbCounter)&0xFF; wbuffer[1] = (mUsbCounter>>8)&0xFF; wbuffer[2] = (mUsbCounter>>16)&0xFF; wbuffer[3] = (mUsbCounter>>24)&0xFF; wbuffer[4] = ep; libusb_bulk_transfer(dev_handle, 0x01, wbuffer, 20, &actual, USB_TIMEOUT); if (actual != 20) return -1; mUsbCounter++; wbuffer[0] = (mUsbCounter)&0xFF; wbuffer[1] = (mUsbCounter>>8)&0xFF; wbuffer[2] = (mUsbCounter>>16)&0xFF; wbuffer[3] = (mUsbCounter>>24)&0xFF; wbuffer[4] = ep; wbuffer[5] = 0x03; libusb_bulk_transfer(dev_handle, 0x01, wbuffer, 20, &actual, USB_TIMEOUT); if (actual != 20) return -1; return 0; } int Connection_uLimeSDR::FT_SetStreamPipe(unsigned char ep, size_t size) { int actual = 0; unsigned char wbuffer[20]={0}; mUsbCounter++; wbuffer[0] = (mUsbCounter)&0xFF; wbuffer[1] = (mUsbCounter>>8)&0xFF; wbuffer[2] = (mUsbCounter>>16)&0xFF; wbuffer[3] = (mUsbCounter>>24)&0xFF; wbuffer[4] = ep; libusb_bulk_transfer(dev_handle, 0x01, wbuffer, 20, &actual, USB_TIMEOUT); if (actual != 20) return -1; mUsbCounter++; wbuffer[0] = (mUsbCounter)&0xFF; wbuffer[1] = (mUsbCounter>>8)&0xFF; wbuffer[2] = (mUsbCounter>>16)&0xFF; wbuffer[3] = (mUsbCounter>>24)&0xFF; wbuffer[5] = 0x02; wbuffer[8] = (size)&0xFF; wbuffer[9] = (size>>8)&0xFF; wbuffer[10] = (size>>16)&0xFF; wbuffer[11] = (size>>24)&0xFF; libusb_bulk_transfer(dev_handle, 0x01, wbuffer, 20, &actual, USB_TIMEOUT); if (actual != 20) return -1; return 0; } #endif /** @brief Tries to open connected USB device and find communication endpoints. @return Returns 0-Success, other-EndPoints not found or device didn't connect. */ int Connection_uLimeSDR::Open(const unsigned index, const int vid, const int pid) { #ifndef __unix__ DWORD devCount; FT_STATUS ftStatus = FT_OK; DWORD dwNumDevices = 0; // // Open a device // ftStatus = FT_Create(0, FT_OPEN_BY_INDEX, &mFTHandle); if (FT_FAILED(ftStatus)) { ReportError(ENODEV, "Failed to list USB Devices"); return -1; } FT_AbortPipe(mFTHandle, mStreamRdEndPtAddr); FT_AbortPipe(mFTHandle, 0x82); FT_AbortPipe(mFTHandle, 0x02); FT_AbortPipe(mFTHandle, mStreamWrEndPtAddr); FT_SetStreamPipe(mFTHandle, FALSE, FALSE, 0x82, 64); FT_SetStreamPipe(mFTHandle, FALSE, FALSE, 0x02, 64); isConnected = true; return 0; #else dev_handle = libusb_open_device_with_vid_pid(ctx, vid, pid); if(dev_handle == nullptr) return ReportError("libusb_open failed"); libusb_reset_device(dev_handle); if(libusb_kernel_driver_active(dev_handle, 1) == 1) //find out if kernel driver is attached { printf("Kernel Driver Active\n"); if(libusb_detach_kernel_driver(dev_handle, 1) == 0) //detach it printf("Kernel Driver Detached!\n"); } int r = libusb_claim_interface(dev_handle, 1); //claim interface 0 (the first) of device if(r < 0) { printf("Cannot Claim Interface\n"); return ReportError("Cannot claim interface - %s", libusb_strerror(libusb_error(r))); } r = libusb_claim_interface(dev_handle, 1); //claim interface 0 (the first) of device if(r < 0) { printf("Cannot Claim Interface\n"); return ReportError("Cannot claim interface - %s", libusb_strerror(libusb_error(r))); } printf("Claimed Interface\n"); FT_SetStreamPipe(0x82,64); FT_SetStreamPipe(0x02,64); isConnected = true; return 0; #endif } /** @brief Closes communication to device. */ void Connection_uLimeSDR::Close() { #ifndef __unix__ FT_Close(mFTHandle); #else if(dev_handle != 0) { FT_FlushPipe(mStreamRdEndPtAddr); FT_FlushPipe(0x82); libusb_release_interface(dev_handle, 1); libusb_close(dev_handle); dev_handle = 0; } #endif isConnected = false; } /** @brief Returns connection status @return 1-connection open, 0-connection closed. */ bool Connection_uLimeSDR::IsOpen() { return isConnected; } /** @brief Sends given data buffer to chip through USB port. @param buffer data buffer, must not be longer than 64 bytes. @param length given buffer size. @param timeout_ms timeout limit for operation in milliseconds @return number of bytes sent. */ int Connection_uLimeSDR::Write(const unsigned char *buffer, const int length, int timeout_ms) { std::lock_guard<std::mutex> lock(mExtraUsbMutex); long len = 0; if(IsOpen() == false) return 0; unsigned char* wbuffer = new unsigned char[length]; memcpy(wbuffer, buffer, length); #ifndef __unix__ // // Write to channel 1 ep 0x02 // ULONG ulBytesWrite = 0; FT_STATUS ftStatus = FT_OK; OVERLAPPED vOverlapped = { 0 }; memset(&vOverlapped, 0, sizeof(OVERLAPPED)); vOverlapped.hEvent = CreateEvent(NULL, false, false, NULL); ftStatus = FT_WritePipe(mFTHandle, 0x02, (unsigned char*)buffer, length, &ulBytesWrite, &vOverlapped); if (ftStatus != FT_IO_PENDING) { CloseHandle(vOverlapped.hEvent); return -1; } DWORD dwRet = WaitForSingleObject(vOverlapped.hEvent, USB_TIMEOUT); if (dwRet == WAIT_OBJECT_0 || dwRet == WAIT_TIMEOUT) { if (GetOverlappedResult(mFTHandle, &vOverlapped, &ulBytesWrite, FALSE)==FALSE) { ulBytesWrite = -1; } } else { ulBytesWrite = -1; } CloseHandle(vOverlapped.hEvent); return ulBytesWrite; #else int actual = 0; libusb_bulk_transfer(dev_handle, 0x02, wbuffer, length, &actual, USB_TIMEOUT); len = actual; #endif delete wbuffer; return len; } /** @brief Reads data coming from the chip through USB port. @param buffer pointer to array where received data will be copied, array must be big enough to fit received data. @param length number of bytes to read from chip. @param timeout_ms timeout limit for operation in milliseconds @return number of bytes received. */ int Connection_uLimeSDR::Read(unsigned char *buffer, const int length, int timeout_ms) { std::lock_guard<std::mutex> lock(mExtraUsbMutex); long len = length; if(IsOpen() == false) return 0; #ifndef __unix__ // // Read from channel 1 ep 0x82 // ULONG ulBytesRead = 0; FT_STATUS ftStatus = FT_OK; OVERLAPPED vOverlapped = { 0 }; memset(&vOverlapped, 0, sizeof(OVERLAPPED)); vOverlapped.hEvent = CreateEvent(NULL, false, false, NULL); ftStatus = FT_ReadPipe(mFTHandle, 0x82, buffer, length, &ulBytesRead, &vOverlapped); if (ftStatus != FT_IO_PENDING) { CloseHandle(vOverlapped.hEvent); return -1;; } DWORD dwRet = WaitForSingleObject(vOverlapped.hEvent, USB_TIMEOUT); if (dwRet == WAIT_OBJECT_0 || dwRet == WAIT_TIMEOUT) { if (GetOverlappedResult(mFTHandle, &vOverlapped, &ulBytesRead, FALSE)==FALSE) { ulBytesRead = -1; } } else { ulBytesRead = -1; } CloseHandle(vOverlapped.hEvent); return ulBytesRead; #else int actual = 0; libusb_bulk_transfer(dev_handle, 0x82, buffer, len, &actual, USB_TIMEOUT); len = actual; #endif return len; } #ifdef __unix__ /** @brief Function for handling libusb callbacks */ static void callback_libusbtransfer(libusb_transfer *trans) { Connection_uLimeSDR::USBTransferContext *context = reinterpret_cast<Connection_uLimeSDR::USBTransferContext*>(trans->user_data); switch(trans->status) { case LIBUSB_TRANSFER_CANCELLED: //printf("Transfer %i canceled\n", context->id); context->bytesXfered = trans->actual_length; context->done.store(true); //context->used = false; //context->reset(); break; case LIBUSB_TRANSFER_COMPLETED: //if(trans->actual_length == context->bytesExpected) { context->bytesXfered = trans->actual_length; context->done.store(true); } break; case LIBUSB_TRANSFER_ERROR: printf("TRANSFER ERRRO\n"); context->bytesXfered = trans->actual_length; context->done.store(true); //context->used = false; break; case LIBUSB_TRANSFER_TIMED_OUT: //printf("transfer timed out %i\n", context->id); context->bytesXfered = trans->actual_length; context->done.store(true); //context->used = false; break; case LIBUSB_TRANSFER_OVERFLOW: printf("transfer overflow\n"); break; case LIBUSB_TRANSFER_STALL: printf("transfer stalled\n"); break; case LIBUSB_TRANSFER_NO_DEVICE: printf("transfer no device\n"); break; } context->transferLock.unlock(); context->cv.notify_one(); } #endif /** @brief Starts asynchronous data reading from board @param *buffer buffer where to store received data @param length number of bytes to read @return handle of transfer context */ int Connection_uLimeSDR::BeginDataReading(char *buffer, long length) { int i = 0; bool contextFound = false; //find not used context for(i = 0; i<USB_MAX_CONTEXTS; i++) { if(!contexts[i].used) { contextFound = true; break; } } if(!contextFound) { printf("No contexts left for reading data\n"); return -1; } contexts[i].used = true; #ifndef __unix__ if (length != rxSize) { rxSize = length; FT_SetStreamPipe(mFTHandle, FALSE, FALSE, mStreamRdEndPtAddr, rxSize); } memset(&contexts[i].inOvLap, 0, sizeof(OVERLAPPED)); contexts[i].inOvLap.hEvent = CreateEvent(NULL, false, false, NULL); ULONG ulActual; if (FT_ReadPipe(mFTHandle, mStreamRdEndPtAddr, (unsigned char*)buffer, length, &ulActual, &contexts[i].inOvLap)!= FT_IO_PENDING) { return -1; } #else if (length != rxSize) { rxSize = length; FT_SetStreamPipe(mStreamRdEndPtAddr,rxSize); } unsigned int Timeout = 500; libusb_transfer *tr = contexts[i].transfer; libusb_fill_bulk_transfer(tr, dev_handle, mStreamRdEndPtAddr, (unsigned char*)buffer, length, callback_libusbtransfer, &contexts[i], Timeout); contexts[i].done = false; contexts[i].bytesXfered = 0; contexts[i].bytesExpected = length; int status = libusb_submit_transfer(tr); if(status != 0) { printf("ERROR BEGIN DATA READING %s\n", libusb_error_name(status)); contexts[i].used = false; return -1; } else contexts[i].transferLock.lock(); #endif return i; } /** @brief Waits for asynchronous data reception @param contextHandle handle of which context data to wait @param timeout_ms number of miliseconds to wait @return 1-data received, 0-data not received */ int Connection_uLimeSDR::WaitForReading(int contextHandle, unsigned int timeout_ms) { if(contextHandle >= 0 && contexts[contextHandle].used == true) { int status = 0; #ifndef __unix__ contexts[contextHandle].inOvLap.InternalHigh = 0; DWORD dwRet = WaitForSingleObject(contexts[contextHandle].inOvLap.hEvent, USB_TIMEOUT); if (dwRet == WAIT_OBJECT_0 || dwRet == WAIT_TIMEOUT) return 1; #else auto t1 = chrono::high_resolution_clock::now(); auto t2 = chrono::high_resolution_clock::now(); std::unique_lock<std::mutex> lck(contexts[contextHandle].transferLock); while(contexts[contextHandle].done.load() == false && std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count() < timeout_ms) { //blocking not to waste CPU contexts[contextHandle].cv.wait(lck); t2 = chrono::high_resolution_clock::now(); } return contexts[contextHandle].done.load() == true; #endif } return 0; } /** @brief Finishes asynchronous data reading from board @param buffer array where to store received data @param length number of bytes to read, function changes this value to number of bytes actually received @param contextHandle handle of which context to finish @return false failure, true number of bytes received */ int Connection_uLimeSDR::FinishDataReading(char *buffer, long &length, int contextHandle) { if(contextHandle >= 0 && contexts[contextHandle].used == true) { #ifndef __unix__ ULONG ulActualBytesTransferred; if (GetOverlappedResult(mFTHandle, &contexts[contextHandle].inOvLap, &ulActualBytesTransferred, FALSE) == FALSE) { return -1; } length = ulActualBytesTransferred; contexts[contextHandle].used = false; return length; #else length = contexts[contextHandle].bytesXfered; contexts[contextHandle].used = false; contexts[contextHandle].reset(); return length; #endif } else return 0; } int Connection_uLimeSDR::ReadDataBlocking(char *buffer, long &length, int timeout_ms) { #ifndef __unix__ return 0; #else return 0; #endif } /** @brief Aborts reading operations */ void Connection_uLimeSDR::AbortReading() { #ifndef __unix__ FT_AbortPipe(mFTHandle, mStreamRdEndPtAddr); for (int i = 0; i < USB_MAX_CONTEXTS; ++i) { if (contexts[i].used == true) { CloseHandle(contexts[i].inOvLap.hEvent); contexts[i].used = false; } } rxSize = 0; #else for(int i = 0; i<USB_MAX_CONTEXTS; ++i) { if(contexts[i].used) libusb_cancel_transfer(contexts[i].transfer); } FT_FlushPipe(mStreamRdEndPtAddr); rxSize = 0; #endif } /** @brief Starts asynchronous data Sending to board @param *buffer buffer to send @param length number of bytes to send @return handle of transfer context */ int Connection_uLimeSDR::BeginDataSending(const char *buffer, long length) { int i = 0; //find not used context bool contextFound = false; for(i = 0; i<USB_MAX_CONTEXTS; i++) { if(!contextsToSend[i].used) { contextFound = true; break; } } if(!contextFound) return -1; contextsToSend[i].used = true; #ifndef __unix__ FT_STATUS ftStatus = FT_OK; ULONG ulActualBytesSend; if (length != txSize) { txSize = length; FT_SetStreamPipe(mFTHandle, FALSE, FALSE, mStreamWrEndPtAddr, txSize); } memset(&contextsToSend[i].inOvLap, 0, sizeof(OVERLAPPED)); contextsToSend[i].inOvLap.hEvent = CreateEvent(NULL, false, false, NULL); ftStatus = FT_WritePipe(mFTHandle, mStreamWrEndPtAddr, (unsigned char*)buffer, length, &ulActualBytesSend, &contextsToSend[i].inOvLap); if (ftStatus != FT_IO_PENDING) { return -1; } #else if (length != txSize) { txSize = length; FT_SetStreamPipe(mStreamWrEndPtAddr,txSize); } unsigned int Timeout = 500; libusb_transfer *tr = contextsToSend[i].transfer; libusb_fill_bulk_transfer(tr, dev_handle, mStreamWrEndPtAddr, (unsigned char*)buffer, length, callback_libusbtransfer, &contextsToSend[i], Timeout); contextsToSend[i].done = false; contextsToSend[i].bytesXfered = 0; contextsToSend[i].bytesExpected = length; int status = libusb_submit_transfer(tr); if(status != 0) { printf("ERROR BEGIN DATA SENDING %s\n", libusb_error_name(status)); contextsToSend[i].used = false; return -1; } else contextsToSend[i].transferLock.lock(); #endif return i; } /** @brief Waits for asynchronous data sending @param contextHandle handle of which context data to wait @param timeout_ms number of miliseconds to wait @return 1-data received, 0-data not received */ int Connection_uLimeSDR::WaitForSending(int contextHandle, unsigned int timeout_ms) { if(contextsToSend[contextHandle].used == true) { #ifndef __unix__ contextsToSend[contextHandle].inOvLap.InternalHigh = 0; DWORD dwRet = WaitForSingleObject(contextsToSend[contextHandle].inOvLap.hEvent, USB_TIMEOUT); if (dwRet == WAIT_OBJECT_0 || dwRet == WAIT_TIMEOUT) return 1; #else auto t1 = chrono::high_resolution_clock::now(); auto t2 = chrono::high_resolution_clock::now(); std::unique_lock<std::mutex> lck(contextsToSend[contextHandle].transferLock); while(contextsToSend[contextHandle].done.load() == false && std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count() < timeout_ms) { //blocking not to waste CPU contextsToSend[contextHandle].cv.wait(lck); t2 = chrono::high_resolution_clock::now(); } return contextsToSend[contextHandle].done == true; #endif } return 0; } /** @brief Finishes asynchronous data sending to board @param buffer array where to store received data @param length number of bytes to read, function changes this value to number of bytes acctually received @param contextHandle handle of which context to finish @return false failure, true number of bytes sent */ int Connection_uLimeSDR::FinishDataSending(const char *buffer, long &length, int contextHandle) { if(contextsToSend[contextHandle].used == true) { #ifndef __unix__ ULONG ulActualBytesTransferred ; if (GetOverlappedResult(mFTHandle, &contextsToSend[contextHandle].inOvLap, &ulActualBytesTransferred, FALSE)==FALSE) { return -1; } length = ulActualBytesTransferred; CloseHandle(contextsToSend[contextHandle].inOvLap.hEvent); contextsToSend[contextHandle].used = false; return length; #else length = contextsToSend[contextHandle].bytesXfered; contextsToSend[contextHandle].used = false; contextsToSend[contextHandle].reset(); return length; #endif } else return 0; } /** @brief Aborts sending operations */ void Connection_uLimeSDR::AbortSending() { #ifndef __unix__ FT_AbortPipe(mFTHandle, mStreamWrEndPtAddr); for (int i = 0; i < USB_MAX_CONTEXTS; ++i) { if (contextsToSend[i].used == true) { CloseHandle(contextsToSend[i].inOvLap.hEvent); contextsToSend[i].used = false; } } txSize = 0; #else for(int i = 0; i<USB_MAX_CONTEXTS; ++i) { if(contextsToSend[i].used) libusb_cancel_transfer(contextsToSend[i].transfer); } FT_FlushPipe(mStreamWrEndPtAddr); txSize = 0; #endif } /** @brief Configures Stream board FPGA clocks to Limelight interface @param tx Rx/Tx selection @param InterfaceClk_Hz Limelight interface frequency @param phaseShift_deg IQ phase shift in degrees @return 0-success, other-failure */ int Connection_uLimeSDR::ConfigureFPGA_PLL(unsigned int pllIndex, const double interfaceClk_Hz, const double phaseShift_deg) { eLMS_DEV boardType = GetDeviceInfo().deviceName == GetDeviceName(LMS_DEV_QSPARK) ? LMS_DEV_QSPARK : LMS_DEV_UNKNOWN; const uint16_t busyAddr = 0x0021; if(IsOpen() == false) return ReportError(ENODEV, "Connection_uLimeSDR: configure FPGA PLL, device not connected"); uint16_t drct_clk_ctrl_0005 = 0; ReadRegister(0x0005, drct_clk_ctrl_0005); if(interfaceClk_Hz < 5e6) { //enable direct clocking WriteRegister(0x0005, drct_clk_ctrl_0005 | (1 << pllIndex)); uint16_t drct_clk_ctrl_0006; ReadRegister(0x0006, drct_clk_ctrl_0006); drct_clk_ctrl_0006 = drct_clk_ctrl_0006 & ~0x3FF; const int cnt_ind = 1 << 5; const int clk_ind = pllIndex; drct_clk_ctrl_0006 = drct_clk_ctrl_0006 | cnt_ind | clk_ind; WriteRegister(0x0006, drct_clk_ctrl_0006); const uint16_t phase_reg_sel_addr = 0x0004; float inputClock_Hz = interfaceClk_Hz; const float oversampleClock_Hz = 100e6; const int registerChainSize = 128; const float phaseShift_deg = 90; const float oversampleClock_ns = 1e9 / oversampleClock_Hz; const float phaseStep_deg = 360 * oversampleClock_ns*(1e-9) / (1 / inputClock_Hz); uint16_t phase_reg_select = (phaseShift_deg / phaseStep_deg) + 0.5; const float actualPhaseShift_deg = 360 * inputClock_Hz / (1 / (phase_reg_select * oversampleClock_ns*1e-9)); #ifndef NDEBUG printf("reg value : %i\n", phase_reg_select); printf("input clock: %f\n", inputClock_Hz); printf("phase : %.2f/%.2f\n", phaseShift_deg, actualPhaseShift_deg); #endif if(WriteRegister(phase_reg_sel_addr, phase_reg_select) != 0) return ReportError(EIO, "Connection_uLimeSDR: configure FPGA PLL, failed to write registers"); const uint16_t LOAD_PH_REG = 1 << 10; WriteRegister(0x0006, drct_clk_ctrl_0006 | LOAD_PH_REG); WriteRegister(0x0006, drct_clk_ctrl_0006); return 0; } //if interface frequency >= 5MHz, configure PLLs WriteRegister(0x0005, drct_clk_ctrl_0005 & ~(1 << pllIndex)); //select FPGA index pllIndex = pllIndex & 0x1F; uint16_t reg23val = 0; if(ReadRegister(0x0003, reg23val) != 0) return ReportError(ENODEV, "Connection_uLimeSDR: configure FPGA PLL, failed to read register"); const uint16_t PLLCFG_START = 0x1; const uint16_t PHCFG_START = 0x2; const uint16_t PLLRST_START = 0x4; const uint16_t PHCFG_UPDN = 1 << 13; reg23val &= 0x1F << 3; //clear PLL index reg23val &= ~PLLCFG_START; //clear PLLCFG_START reg23val &= ~PHCFG_START; //clear PHCFG reg23val &= ~PLLRST_START; //clear PLL reset reg23val &= ~PHCFG_UPDN; //clear PHCFG_UpDn reg23val |= pllIndex << 3; uint16_t statusReg; bool done = false; uint8_t errorCode = 0; vector<uint32_t> addrs; vector<uint32_t> values; addrs.push_back(0x0023); values.push_back(reg23val); //PLL_IND addrs.push_back(0x0023); values.push_back(reg23val | PLLRST_START); //PLLRST_START WriteRegisters(addrs.data(), values.data(), values.size()); if(boardType == LMS_DEV_QSPARK) do //wait for reset to activate { ReadRegister(busyAddr, statusReg); done = statusReg & 0x1; errorCode = (statusReg >> 7) & 0xFF; } while(!done && errorCode == 0); if(errorCode != 0) return ReportError(EBUSY, "Connection_uLimeSDR: error resetting PLL"); addrs.clear(); values.clear(); addrs.push_back(0x0023); values.push_back(reg23val & ~PLLRST_START); //configure FPGA PLLs const float vcoLimits_MHz[2] = { 600, 1300 }; int M, C; const short bufSize = 64; float fOut_MHz = interfaceClk_Hz / 1e6; float coef = 0.8*vcoLimits_MHz[1] / fOut_MHz; M = C = (int)coef; int chigh = (((int)coef) / 2) + ((int)(coef) % 2); int clow = ((int)coef) / 2; addrs.clear(); values.clear(); if(interfaceClk_Hz*M / 1e6 > vcoLimits_MHz[0] && interfaceClk_Hz*M / 1e6 < vcoLimits_MHz[1]) { //bypass N addrs.push_back(0x0026); values.push_back(0x0001 | (M % 2 ? 0x8 : 0)); addrs.push_back(0x0027); values.push_back(0x5550 | (C % 2 ? 0xA : 0)); //bypass c7-c1 addrs.push_back(0x0028); values.push_back(0x5555); //bypass c15-c8 addrs.push_back(0x002A); values.push_back(0x0101); //N_high_cnt, N_low_cnt addrs.push_back(0x002B); values.push_back(chigh << 8 | clow); //M_high_cnt, M_low_cnt for(int i = 0; i <= 1; ++i) { addrs.push_back(0x002E + i); values.push_back(chigh << 8 | clow); // ci_high_cnt, ci_low_cnt } float Fstep_us = 1 / (8 * fOut_MHz*C); float Fstep_deg = (360 * Fstep_us) / (1 / fOut_MHz); short nSteps = phaseShift_deg / Fstep_deg; addrs.push_back(0x0024); values.push_back(nSteps); addrs.push_back(0x0023); int cnt_ind = 0x3 & 0x1F; reg23val = reg23val | PHCFG_UPDN | (cnt_ind << 8); values.push_back(reg23val); //PHCFG_UpDn, CNT_IND addrs.push_back(0x0023); values.push_back(reg23val | PLLCFG_START); //PLLCFG_START if(WriteRegisters(addrs.data(), values.data(), values.size()) != 0) ReportError(EIO, "Connection_uLimeSDR: configure FPGA PLL, failed to write registers"); if(boardType == LMS_DEV_QSPARK) do //wait for config to activate { ReadRegister(busyAddr, statusReg); done = statusReg & 0x1; errorCode = (statusReg >> 7) & 0xFF; } while(!done && errorCode == 0); if(errorCode != 0) return ReportError(EBUSY, "Connection_uLimeSDR: error configuring PLLCFG"); addrs.clear(); values.clear(); addrs.push_back(0x0023); values.push_back(reg23val & ~PLLCFG_START); //PLLCFG_START addrs.push_back(0x0023); values.push_back(reg23val | PHCFG_START); //PHCFG_START if(WriteRegisters(addrs.data(), values.data(), values.size()) != 0) ReportError(EIO, "Connection_uLimeSDR: configure FPGA PLL, failed to write registers"); if(boardType == LMS_DEV_QSPARK) do { ReadRegister(busyAddr, statusReg); done = statusReg & 0x1; errorCode = (statusReg >> 7) & 0xFF; } while(!done && errorCode == 0); if(errorCode != 0) return ReportError(EBUSY, "Connection_uLimeSDR: error configuring PHCFG"); addrs.clear(); values.clear(); addrs.push_back(0x0023); values.push_back(reg23val & ~PHCFG_START); //PHCFG_START if(WriteRegisters(addrs.data(), values.data(), values.size()) != 0) ReportError(EIO, "Connection_uLimeSDR: configure FPGA PLL, failed to write registers"); return 0; } return ReportError(ERANGE, "Connection_uLimeSDR: configure FPGA PLL, desired frequency out of range"); }
31.718391
153
0.649864
[ "object", "vector" ]
d0cad70ece35a56d5bd7d48be2da034946c71fb3
799
cpp
C++
box2constantvolumejoint.cpp
FrankMamuda/qml-box2d
7fcf844b00f635ad68842f0e0473390c4095ad10
[ "Zlib" ]
null
null
null
box2constantvolumejoint.cpp
FrankMamuda/qml-box2d
7fcf844b00f635ad68842f0e0473390c4095ad10
[ "Zlib" ]
null
null
null
box2constantvolumejoint.cpp
FrankMamuda/qml-box2d
7fcf844b00f635ad68842f0e0473390c4095ad10
[ "Zlib" ]
null
null
null
/* * includes */ #include "box2constantvolumejoint.h" /** * @brief Box2DConstantVolumeJoint::Box2DConstantVolumeJoint * @param parent */ Box2DConstantVolumeJoint::Box2DConstantVolumeJoint( QObject *parent ) : Box2DJoint( ConstantVolumeJoint, parent ) {} /** * @brief Box2DConstantVolumeJoint::createJoint * @return */ b2Joint *Box2DConstantVolumeJoint::createJoint() { b2ConstantVolumeJointDef jointDef; std::vector<b2Body*> b2Bodies; for ( const QVariant &v : this->bodies()) b2Bodies.push_back( v.value<Box2DBody*>()->body()); initializeJointDef( jointDef ); jointDef.Initialize( b2Bodies ); jointDef.dampingRatio = this->dampingRatio(); jointDef.frequencyHz = this->frequencyHz(); return this->world()->world().CreateJoint( &jointDef ); }
25.774194
69
0.708385
[ "vector" ]
d0cbc7ec6986ff44450cea2748a40f57fab79c36
1,424
cpp
C++
cpp/src/exercise/e0100/e0054.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
cpp/src/exercise/e0100/e0054.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
cpp/src/exercise/e0100/e0054.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
#include "extern.h" class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { if (matrix.empty() || matrix[0].empty()) return {}; int row_num = matrix.size(), col_num = matrix[0].size(); vector<int> result; result.reserve(row_num * col_num); vector<vector<bool>> parsed(row_num, vector<bool>(col_num, false)); vector<int> row_id{ 0, 1, 0, -1 }; vector<int> col_id{ 1, 0, -1, 0 }; int pattern = 0; int r = 0, c = 0; for (int count = 0; count < row_num * col_num; ++count) { result.push_back(matrix[r][c]); parsed[r][c] = true; int rt = r + row_id[pattern], ct = c + col_id[pattern]; if (rt >= row_num || rt < 0 || ct >= col_num || ct < 0 || parsed[rt][ct]) pattern = (pattern + 1) % 4; r += row_id[pattern]; c += col_id[pattern]; } return result; } }; TEST(e0100, e0054) { vector<vector<int>> m = str_to_mat<int>("[\ [1, 2, 3], \ [4, 5, 6], \ [7, 8, 9] \ ]"); vector<int> ans = str_to_vec<int>("[1,2,3,6,9,8,7,4,5]"); ASSERT_THAT(Solution().spiralOrder(m), ans); m = str_to_mat<int>("[\ [1, 2, 3, 4], \ [5, 6, 7, 8], \ [9, 10, 11, 12] \ ]"); ans = str_to_vec<int>("[1,2,3,4,8,12,11,10,9,5,6,7]"); ASSERT_THAT(Solution().spiralOrder(m), ans); }
33.904762
85
0.494382
[ "vector" ]
d0d1407e7a4072716210444e544607382beeb7d5
54,978
cpp
C++
unittests/emitc_mhlo.cpp
OliverScherf/mlir-emitc
af6a34bee5563bf71a218a93139da0e25cd9b2a5
[ "Apache-2.0" ]
39
2020-06-25T10:21:36.000Z
2022-03-27T21:01:42.000Z
unittests/emitc_mhlo.cpp
OliverScherf/mlir-emitc
af6a34bee5563bf71a218a93139da0e25cd9b2a5
[ "Apache-2.0" ]
63
2020-09-22T23:19:01.000Z
2022-03-30T14:19:57.000Z
unittests/emitc_mhlo.cpp
OliverScherf/mlir-emitc
af6a34bee5563bf71a218a93139da0e25cd9b2a5
[ "Apache-2.0" ]
9
2020-09-17T04:16:00.000Z
2022-01-20T10:40:09.000Z
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "gmock/gmock.h" #include "emitc/emitc_mhlo.h" #include "emitc/emitc_types.h" namespace { using namespace emitc; using ::testing::DoubleEq; using ::testing::Eq; using ::testing::FloatEq; using ::testing::FloatNear; using ::testing::Pointwise; const float EPSILON = 5e-4; // Unary elementwise ops TEST(mhlo, abs) { EXPECT_EQ(1, mhlo::abs(-1)); Tensor0D<int> t0{-1}; Tensor1D<float, 2> t1{-1.0f, -2.0f}; Tensor2D<long, 2, 2> t2{-2, -1, 0, 2}; Tensor3D<int32_t, 2, 1, 2> t3{-2, -1, 0, 2}; Tensor4D<int, 2, 2, 1, 2> t4{-2, -1, 0, 0, 3, -3, -2, 1}; EXPECT_THAT(mhlo::abs(t0), Pointwise(Eq(), {1})); EXPECT_THAT(mhlo::abs(t1), Pointwise(Eq(), {1.0f, 2.0f})); EXPECT_THAT(mhlo::abs(t2), Pointwise(Eq(), {2, 1, 0, 2})); EXPECT_THAT(mhlo::abs(t3), Pointwise(Eq(), {2, 1, 0, 2})); EXPECT_THAT(mhlo::abs(t4), Pointwise(Eq(), {2, 1, 0, 0, 3, 3, 2, 1})); // TODO:: Test complex to real. } TEST(mhlo, ceil) { EXPECT_EQ(1.0, mhlo::ceil(0.7)); Tensor0D<float> t0{0.7f}; Tensor1D<float, 2> t1{1.6f, 2.0f}; Tensor2D<double, 2, 2> t2{2.1, 1.6, 0.0, 2.0}; Tensor3D<double, 2, 1, 2> t3{2.1, 1.6, 0.0, 2.0}; Tensor4D<double, 1, 2, 1, 2> t4{2.1, 1.6, 0.0, 2.0}; EXPECT_THAT(mhlo::ceil(t0), Pointwise(Eq(), {1.0f})); EXPECT_THAT(mhlo::ceil(t1), Pointwise(Eq(), {2.0f, 2.0f})); EXPECT_THAT(mhlo::ceil(t2), Pointwise(Eq(), {3.0, 2.0, 0.0, 2.0})); EXPECT_THAT(mhlo::ceil(t3), Pointwise(Eq(), {3.0, 2.0, 0.0, 2.0})); EXPECT_THAT(mhlo::ceil(t4), Pointwise(Eq(), {3.0, 2.0, 0.0, 2.0})); } TEST(mhlo, convert) { uint32_t a = 1; uint64_t b = 1; EXPECT_EQ(b, mhlo::convert<uint64_t>(a)); Tensor0D<uint32_t> t0{1}; auto lambda_0d = [&t0]() -> Tensor0D<size_t> { return mhlo::convert<Tensor0D<size_t>>(t0); }; EXPECT_THAT(lambda_0d(), Pointwise(Eq(), {1})); Tensor1D<uint16_t, 2> t1{1, 2}; auto lambda_1d = [&t1]() -> Tensor1D<size_t, 2> { return mhlo::convert<Tensor1D<size_t, 2>>(t1); }; EXPECT_THAT(lambda_1d(), Pointwise(Eq(), {1, 2})); Tensor2D<float, 2, 2> t2{1.0f, 2.0f, 4.0f, 8.0f}; auto lambda_2d = [&t2]() -> Tensor2D<double, 2, 2> { return mhlo::convert<Tensor2D<double, 2, 2>>(t2); }; EXPECT_THAT(lambda_2d(), Pointwise(DoubleEq(), {1.0, 2.0, 4.0, 8.0})); Tensor3D<float, 2, 1, 2> t3{1.0f, 2.0f, 4.0f, 8.0f}; auto lambda_3d = [&t3]() -> Tensor3D<double, 2, 1, 2> { return mhlo::convert<Tensor3D<double, 2, 1, 2>>(t3); }; EXPECT_THAT(lambda_3d(), Pointwise(DoubleEq(), {1.0, 2.0, 4.0, 8.0})); Tensor4D<double, 2, 1, 2, 2> t4{1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0}; auto lambda_4d = [&t4]() -> Tensor4D<float, 2, 1, 2, 2> { return mhlo::convert<Tensor4D<float, 2, 1, 2, 2>>(t4); }; EXPECT_THAT(lambda_4d(), Pointwise(FloatEq(), {1.0f, 2.0f, 4.0f, 8.0f, 16.0f, 32.0f, 64.0f, 128.0f})); } TEST(mhlo, cos) { EXPECT_NEAR(1.0f, mhlo::cos(0.0f), EPSILON); Tensor0D<float> t0{M_PIf32}; Tensor1D<float, 2> t1{M_PI_2f32, -M_PI_2f32}; Tensor2D<double, 2, 2> t2{2 * M_PIf32, 0.0f, -0.5f, 0.5f}; EXPECT_THAT(mhlo::cos(t0), Pointwise(FloatNear(EPSILON), {-1.0f})); EXPECT_THAT(mhlo::cos(t1), Pointwise(FloatNear(EPSILON), {0.0f, 0.0f})); EXPECT_THAT(mhlo::cos(t2), Pointwise(FloatNear(EPSILON), {1.0f, 1.0f, 0.8775826f, 0.8775826f})); } TEST(mhlo, exponential) { EXPECT_NEAR(M_Ef32, mhlo::exponential(1.0f), EPSILON); Tensor0D<float> t0{0.0f}; Tensor1D<float, 2> t1{M_LN2f32, M_LN10f32}; Tensor2D<double, 2, 2> t2{1.0f, 2.0f, 3.0f, 4.0f}; EXPECT_THAT(mhlo::exponential(t0), Pointwise(FloatNear(EPSILON), {1.0f})); EXPECT_THAT(mhlo::exponential(t1), Pointwise(FloatNear(EPSILON), {2.0f, 10.0f})); EXPECT_THAT(mhlo::exponential(t2), Pointwise(FloatNear(EPSILON), {2.718281f, 7.389056f, 20.085536f, 54.598150f})); } TEST(mhlo, exponential_minus_one) { EXPECT_NEAR(M_Ef32 - 1, mhlo::exponential_minus_one(1.0f), EPSILON); Tensor0D<float> t0{0.0f}; Tensor1D<float, 2> t1{M_LN2f32, M_LN10f32}; Tensor2D<double, 2, 2> t2{1.0f, 2.0f, 3.0f, 4.0f}; EXPECT_THAT(mhlo::exponential_minus_one(t0), Pointwise(FloatNear(EPSILON), {0.0f})); EXPECT_THAT(mhlo::exponential_minus_one(t1), Pointwise(FloatNear(EPSILON), {1.0f, 9.0f})); EXPECT_THAT(mhlo::exponential_minus_one(t2), Pointwise(FloatNear(EPSILON), {1.718281f, 6.389056f, 19.085536f, 53.598150f})); } TEST(mhlo, floor) { EXPECT_EQ(0.0, mhlo::floor(0.7)); Tensor0D<float> t0{0.7f}; Tensor1D<float, 2> t1{1.6f, 2.0f}; Tensor2D<double, 2, 2> t2{2.1, 1.6, 0.0, 2.0}; EXPECT_THAT(mhlo::floor(t0), Pointwise(Eq(), {0.0f})); EXPECT_THAT(mhlo::floor(t1), Pointwise(Eq(), {1.0f, 2.0f})); EXPECT_THAT(mhlo::floor(t2), Pointwise(Eq(), {2.0, 1.0, 0.0, 2.0})); } TEST(mhlo, is_finite) { EXPECT_EQ(true, mhlo::is_finite(0.0f)); Tensor0D<float> t0{M_PIf32}; Tensor1D<float, 2> t1{M_PI_2f32, INFINITY}; Tensor2D<double, 2, 2> t2{INFINITY, -INFINITY, NAN, -0.0f}; EXPECT_THAT(mhlo::is_finite(t0), Pointwise(Eq(), {true})); EXPECT_THAT(mhlo::is_finite(t1), Pointwise(Eq(), {true, false})); EXPECT_THAT(mhlo::is_finite(t2), Pointwise(Eq(), {false, false, false, true})); } TEST(mhlo, log) { EXPECT_NEAR(0.0f, mhlo::log(1.0f), EPSILON); Tensor0D<float> t0{M_Ef32}; Tensor1D<float, 2> t1{M_Ef32 * M_Ef32, M_Ef32 * M_Ef32 * M_Ef32}; Tensor2D<double, 2, 2> t2{1.0f, 2.0f, 3.0f, 4.0f}; EXPECT_THAT(mhlo::log(t0), Pointwise(FloatNear(EPSILON), {1.0f})); EXPECT_THAT(mhlo::log(t1), Pointwise(FloatNear(EPSILON), {2.0f, 3.0f})); // clang-format off EXPECT_THAT(mhlo::log(t2), Pointwise(FloatNear(EPSILON), {0.0f, 0.693147f, 1.098612f, 1.386294f})); // clang-format on } TEST(mhlo, log_plus_one) { EXPECT_NEAR(0.693147f, mhlo::log_plus_one(1.0f), EPSILON); Tensor0D<float> t0{M_Ef32 - 1}; Tensor1D<float, 2> t1{M_Ef32 * M_Ef32, M_Ef32 * M_Ef32 * M_Ef32}; Tensor2D<double, 2, 2> t2{0.0f, 1.0f, 2.0f, 3.0f}; EXPECT_THAT(mhlo::log_plus_one(t0), Pointwise(FloatNear(EPSILON), {1.0f})); EXPECT_THAT(mhlo::log_plus_one(t1), Pointwise(FloatNear(EPSILON), {2.126928f, 3.048587f})); // clang-format off EXPECT_THAT(mhlo::log_plus_one(t2), Pointwise(FloatNear(EPSILON), {0.0f, 0.693147f, 1.098612f, 1.386294f})); // clang-format on } TEST(mhlo, negate) { EXPECT_EQ(1, mhlo::negate(-1)); Tensor0D<int> s0{-3}; auto lambda_0d = [&s0]() -> Tensor0D<int> { return mhlo::negate<Tensor0D<int>>(s0); }; EXPECT_THAT(lambda_0d(), Pointwise(Eq(), {3})); Tensor1D<float, 2> s1{-1.3f, 2.4f}; auto lambda_1d = [&s1]() -> Tensor1D<float, 2> { return mhlo::negate<Tensor1D<float, 2>>(s1); }; EXPECT_THAT(lambda_1d(), Pointwise(FloatEq(), {1.3f, -2.4f})); Tensor2D<long, 2, 2> s2{3, 1, -4, 0}; auto lambda_2d = [&s2]() -> Tensor2D<long, 2, 2> { return mhlo::negate<Tensor2D<long, 2, 2>>(s2); }; EXPECT_THAT(lambda_2d(), Pointwise(Eq(), {-3, -1, 4, 0})); } TEST(mhlo, round) { EXPECT_EQ(1.0, mhlo::round(0.7)); EXPECT_EQ(0.0, mhlo::round(0.4)); Tensor0D<float> t0{0.7f}; Tensor1D<float, 3> t1{1.4f, 1.6f, 2.0f}; Tensor2D<double, 2, 2> t2{2.1, 1.6, 0.0, 2.0}; Tensor3D<float, 2, 1, 2> t3{2.1, 1.6, 0.0, 2.0}; Tensor4D<double, 2, 2, 1, 1> t4{2.1, 1.6, 0.0, 2.0}; EXPECT_THAT(mhlo::round(t0), Pointwise(Eq(), {1.0f})); EXPECT_THAT(mhlo::round(t1), Pointwise(Eq(), {1.0f, 2.0f, 2.0f})); EXPECT_THAT(mhlo::round(t2), Pointwise(Eq(), {2.0, 2.0, 0.0, 2.0})); EXPECT_THAT(mhlo::round(t3), Pointwise(Eq(), {2.0f, 2.0f, 0.0f, 2.0f})); EXPECT_THAT(mhlo::round(t4), Pointwise(Eq(), {2.0, 2.0, 0.0, 2.0})); } TEST(mhlo, sin) { EXPECT_NEAR(0.0f, mhlo::sin(0.0f), EPSILON); Tensor0D<float> t0{M_PIf32}; Tensor1D<float, 2> t1{M_PI_2f32, -M_PI_2f32}; Tensor2D<double, 2, 2> t2{2 * M_PIf32, 0.0f, -0.5f, 0.5f}; Tensor3D<double, 1, 2, 2> t3{2 * M_PIf32, 0.0f, -0.5f, 0.5f}; Tensor4D<double, 2, 1, 2, 1> t4{2 * M_PIf32, 0.0f, -0.5f, 0.5f}; EXPECT_THAT(mhlo::sin(t0), Pointwise(FloatNear(EPSILON), {0.0f})); EXPECT_THAT(mhlo::sin(t1), Pointwise(FloatNear(EPSILON), {1.0f, -1.0f})); EXPECT_THAT(mhlo::sin(t2), Pointwise(FloatNear(EPSILON), {0.0f, 0.0f, -0.479426f, 0.479426f})); EXPECT_THAT(mhlo::sin(t3), Pointwise(FloatNear(EPSILON), {0.0f, 0.0f, -0.479426f, 0.479426f})); EXPECT_THAT(mhlo::sin(t4), Pointwise(FloatNear(EPSILON), {0.0f, 0.0f, -0.479426f, 0.479426f})); } TEST(mhlo, sqrt) { EXPECT_NEAR(3.0f, mhlo::sqrt(9.0f), EPSILON); Tensor0D<float> t0{4.0f}; Tensor1D<float, 2> t1{0.0f, 81.0f}; Tensor2D<double, 2, 2> t2{2.0, 3.0, 10.0, 1.0}; Tensor3D<double, 2, 1, 2> t3{2.0, 3.0, 10.0, 1.0}; Tensor4D<double, 2, 2, 1, 2> t4{2.0, 3.0, 10.0, 1.0, 18.0, 9.0, 5.0, 25.0}; EXPECT_THAT(mhlo::sqrt(t0), Pointwise(FloatNear(EPSILON), {2.0f})); EXPECT_THAT(mhlo::sqrt(t1), Pointwise(FloatNear(EPSILON), {0.0f, 9.0f})); EXPECT_THAT( mhlo::sqrt(t2), Pointwise(FloatNear(EPSILON), {1.414213f, 1.732050f, 3.162277f, 1.0f})); EXPECT_THAT( mhlo::sqrt(t3), Pointwise(FloatNear(EPSILON), {1.414213f, 1.732050f, 3.162277f, 1.0f})); EXPECT_THAT(mhlo::sqrt(t4), Pointwise(FloatNear(EPSILON), {1.414213f, 1.732050f, 3.162277f, 1.0f, 4.242640f, 3.0f, 2.236067f, 5.0f})); } TEST(mhlo, tanh) { EXPECT_NEAR(0.0f, mhlo::tanh(0.0f), EPSILON); Tensor0D<float> t0{0.0f}; Tensor1D<float, 2> t1{0.0f, 1.0f}; Tensor2D<double, 2, 2> t2{0.0, 1.0, -1.0, 0.0}; Tensor3D<float, 1, 2, 2> t3{0.0f, 1.0f, -1.0f, 0.0f}; Tensor4D<double, 3, 1, 1, 2> t4{0.0, 1.0, -1.0, 0.0f, M_PIf64, -M_2_PIf64}; EXPECT_THAT(mhlo::tanh(t0), Pointwise(FloatNear(EPSILON), {0.0f})); EXPECT_THAT(mhlo::tanh(t1), Pointwise(FloatNear(EPSILON), {0.0f, 0.761594f})); EXPECT_THAT(mhlo::tanh(t2), Pointwise(FloatNear(EPSILON), {0.0f, 0.761594f, -0.761594f, 0.0f})); EXPECT_THAT(mhlo::tanh(t3), Pointwise(FloatNear(EPSILON), {0.0f, 0.761594f, -0.761594f, 0.0f})); EXPECT_THAT(mhlo::tanh(t4), Pointwise(FloatNear(EPSILON), {0.0f, 0.761594f, -0.761594f, 0.0f, 0.996272f, -0.562593f})); } // Binary elementwise ops TEST(mhlo, add) { EXPECT_EQ(2, mhlo::add(-1, 3)); Tensor0D<int> s0{-3}; Tensor0D<int> t0{8}; auto lambda_0d = [&s0, &t0]() -> Tensor0D<int> { return mhlo::add<Tensor0D<int>>(s0, t0); }; EXPECT_THAT(lambda_0d(), Pointwise(Eq(), {5})); Tensor1D<float, 2> s1{-1.3f, 2.4f}; Tensor1D<float, 2> t1{0.2f, -3.7f}; auto lambda_1d = [&s1, &t1]() -> Tensor1D<float, 2> { return mhlo::add<Tensor1D<float, 2>>(s1, t1); }; EXPECT_THAT(lambda_1d(), Pointwise(FloatEq(), {-1.1f, -1.3f})); Tensor2D<long, 2, 2> s2{3, 1, 4, 9}; Tensor2D<long, 2, 2> t2{-2, 8, 6, -10}; auto lambda_2d = [&s2, &t2]() -> Tensor2D<long, 2, 2> { return mhlo::add<Tensor2D<long, 2, 2>>(s2, t2); }; EXPECT_THAT(lambda_2d(), Pointwise(Eq(), {1, 9, 10, -1})); Tensor3D<int16_t, 2, 1, 2> s3{3, 1, 4, 9}; Tensor3D<int16_t, 2, 1, 2> t3{-2, 8, 6, -10}; auto lambda_3d = [&s3, &t3]() -> Tensor3D<int16_t, 2, 1, 2> { return mhlo::add<Tensor3D<int16_t, 2, 1, 2>>(s3, t3); }; EXPECT_THAT(lambda_3d(), Pointwise(Eq(), {1, 9, 10, -1})); Tensor4D<int8_t, 2, 1, 2, 2> s4{3, 1, 4, 9, 10, 11, 0, 1}; Tensor4D<int8_t, 2, 1, 2, 2> t4{-2, 8, 6, -10, -10, 11, 1, 1}; auto lambda_4d = [&s4, &t4]() -> Tensor4D<int8_t, 2, 1, 2, 2> { return mhlo::add<Tensor4D<int8_t, 2, 1, 2, 2>>(s4, t4); }; EXPECT_THAT(lambda_4d(), Pointwise(Eq(), {1, 9, 10, -1, 0, 22, 1, 2})); } TEST(mhlo, atan2) { EXPECT_NEAR(0.321751f, mhlo::atan2(1.0f, 3.0f), EPSILON); Tensor0D<float> s0{1.0f}; Tensor0D<float> t0{3.0f}; auto lambda_0d = [&s0, &t0]() -> Tensor0D<float> { return mhlo::atan2<Tensor0D<float>>(s0, t0); }; EXPECT_THAT(lambda_0d(), Pointwise(FloatNear(EPSILON), {0.321751f})); Tensor1D<float, 2> s1{1.0f, 0.5f}; Tensor1D<float, 2> t1{3.0f, -0.5f}; auto lambda_1d = [&s1, &t1]() -> Tensor1D<float, 2> { return mhlo::atan2<Tensor1D<float, 2>>(s1, t1); }; EXPECT_THAT(lambda_1d(), Pointwise(FloatNear(EPSILON), {0.321751f, 2.35619f})); Tensor2D<double, 2, 2> s2{1.0, 0.5, -0.5, 0.5}; Tensor2D<double, 2, 2> t2{3.0, -0.5, 0.5, 0.5}; auto lambda_2d = [&s2, &t2]() -> Tensor2D<double, 2, 2> { return mhlo::atan2<Tensor2D<double, 2, 2>>(s2, t2); }; EXPECT_THAT(lambda_2d(), Pointwise(FloatNear(EPSILON), {0.321751, 2.35619, -0.785398, 0.785398})); Tensor3D<double, 1, 2, 2> s3{1.0, 0.5, -0.5, 0.5}; Tensor3D<double, 1, 2, 2> t3{3.0, -0.5, 0.5, 0.5}; auto lambda_3d = [&s3, &t3]() -> Tensor3D<double, 1, 2, 2> { return mhlo::atan2<Tensor3D<double, 1, 2, 2>>(s3, t3); }; EXPECT_THAT(lambda_3d(), Pointwise(FloatNear(EPSILON), {0.321751, 2.35619, -0.785398, 0.785398})); Tensor4D<float, 1, 3, 1, 2> s4{1.0f, 0.5f, -0.5f, 0.5f, M_PIf32, 0.0f}; Tensor4D<float, 1, 3, 1, 2> t4{3.0f, -0.5f, 0.5f, 0.5f, 0.0f, -M_PIf32}; auto lambda_4d = [&s4, &t4]() -> Tensor4D<float, 1, 3, 1, 2> { return mhlo::atan2<Tensor4D<float, 1, 3, 1, 2>>(s4, t4); }; EXPECT_THAT(lambda_4d(), Pointwise(FloatNear(EPSILON), {0.321751f, 2.35619f, -0.785398f, 0.785398f, 1.570796f, M_PIf32})); } TEST(mhlo, div) { EXPECT_EQ(-3, mhlo::div(-3, 1)); EXPECT_EQ(-6.75, mhlo::div(27.0, -4.0)); EXPECT_EQ(-6, mhlo::div<int>(27.0, -4.0)); Tensor0D<int> s0{27}; Tensor0D<int> t0{-4}; auto lambda_0d = [&s0, &t0]() -> Tensor0D<int> { return mhlo::div<Tensor0D<int>>(s0, t0); }; EXPECT_THAT(lambda_0d(), Pointwise(Eq(), {-6})); Tensor1D<float, 2> s1{-1.3f, 2.4f}; Tensor1D<float, 2> t1{0.2f, -3.7f}; auto lambda_1d = [&s1, &t1]() -> Tensor1D<float, 2> { return mhlo::div<Tensor1D<float, 2>>(s1, t1); }; EXPECT_THAT(lambda_1d(), Pointwise(FloatNear(EPSILON), {-6.5f, -0.6486f})); Tensor2D<long, 2, 2> s2{3, 14, -31, -51}; Tensor2D<long, 2, 2> t2{-2, 2, 6, 7}; auto lambda_2d = [&s2, &t2]() -> Tensor2D<long, 2, 2> { return mhlo::div<Tensor2D<long, 2, 2>>(s2, t2); }; EXPECT_THAT(lambda_2d(), Pointwise(Eq(), {-1, 7, -5, -7})); Tensor3D<int8_t, 2, 2, 1> s3{3, 14, -31, -51}; Tensor3D<int8_t, 2, 2, 1> t3{-2, 2, 6, 7}; auto lambda_3d = [&s3, &t3]() -> Tensor3D<int8_t, 2, 2, 1> { return mhlo::div<Tensor3D<int8_t, 2, 2, 1>>(s3, t3); }; EXPECT_THAT(lambda_3d(), Pointwise(Eq(), {-1, 7, -5, -7})); Tensor4D<int16_t, 2, 1, 3, 1> s4{3, 14, -31, -51, 16, -2}; Tensor4D<int16_t, 2, 1, 3, 1> t4{-2, 2, 6, 7, 8, -2}; auto lambda_4d = [&s4, &t4]() -> Tensor4D<int16_t, 2, 1, 3, 1> { return mhlo::div<Tensor4D<int16_t, 2, 1, 3, 1>>(s4, t4); }; EXPECT_THAT(lambda_4d(), Pointwise(Eq(), {-1, 7, -5, -7, 2, 1})); } TEST(mhlo, max) { EXPECT_EQ(3, mhlo::max(-1, 3)); Tensor0D<int> s0{-3}; Tensor0D<int> t0{8}; auto lambda_0d = [&s0, &t0]() -> Tensor0D<int> { return mhlo::max<Tensor0D<int>>(s0, t0); }; EXPECT_THAT(lambda_0d(), Pointwise(Eq(), {8})); Tensor1D<float, 2> s1{-1.3f, 2.4f}; Tensor1D<float, 2> t1{0.2f, -3.7f}; auto lambda_1d = [&s1, &t1]() -> Tensor1D<float, 2> { return mhlo::max<Tensor1D<float, 2>>(s1, t1); }; EXPECT_THAT(lambda_1d(), Pointwise(FloatEq(), {0.2f, 2.4f})); Tensor2D<long, 2, 2> s2{3, 1, 4, 9}; Tensor2D<long, 2, 2> t2{-2, 8, 6, -10}; auto lambda_2d = [&s2, &t2]() -> Tensor2D<long, 2, 2> { return mhlo::max<Tensor2D<long, 2, 2>>(s2, t2); }; EXPECT_THAT(lambda_2d(), Pointwise(Eq(), {3, 8, 6, 9})); } TEST(mhlo, min) { EXPECT_EQ(-1, mhlo::min(-1, 3)); Tensor0D<int> s0{-3}; Tensor0D<int> t0{8}; auto lambda_0d = [&s0, &t0]() -> Tensor0D<int> { return mhlo::min<Tensor0D<int>>(s0, t0); }; EXPECT_THAT(lambda_0d(), Pointwise(Eq(), {-3})); Tensor1D<float, 2> s1{-1.3f, 2.4f}; Tensor1D<float, 2> t1{0.2f, -3.7f}; auto lambda_1d = [&s1, &t1]() -> Tensor1D<float, 2> { return mhlo::min<Tensor1D<float, 2>>(s1, t1); }; EXPECT_THAT(lambda_1d(), Pointwise(FloatEq(), {-1.3f, -3.7f})); Tensor2D<long, 2, 2> s2{3, 1, 4, 9}; Tensor2D<long, 2, 2> t2{-2, 8, 6, -10}; auto lambda_2d = [&s2, &t2]() -> Tensor2D<long, 2, 2> { return mhlo::min<Tensor2D<long, 2, 2>>(s2, t2); }; EXPECT_THAT(lambda_2d(), Pointwise(Eq(), {-2, 1, 4, -10})); } TEST(mhlo, mul) { EXPECT_EQ(-3, mhlo::mul(-1, 3)); Tensor0D<int> s0{-3}; Tensor0D<int> t0{8}; auto lambda_0d = [&s0, &t0]() -> Tensor0D<int> { return mhlo::mul<Tensor0D<int>>(s0, t0); }; EXPECT_THAT(lambda_0d(), Pointwise(Eq(), {-24})); Tensor1D<float, 2> s1{-1.3f, 2.4f}; Tensor1D<float, 2> t1{0.2f, -3.7f}; auto lambda_1d = [&s1, &t1]() -> Tensor1D<float, 2> { return mhlo::mul<Tensor1D<float, 2>>(s1, t1); }; EXPECT_THAT(lambda_1d(), Pointwise(FloatEq(), {-0.26f, -8.88f})); Tensor2D<long, 2, 2> s2{3, 1, 4, 9}; Tensor2D<long, 2, 2> t2{-2, 8, 6, -10}; auto lambda_2d = [&s2, &t2]() -> Tensor2D<long, 2, 2> { return mhlo::mul<Tensor2D<long, 2, 2>>(s2, t2); }; EXPECT_THAT(lambda_2d(), Pointwise(Eq(), {-6, 8, 24, -90})); } TEST(mhlo, pow) { EXPECT_EQ(9, mhlo::pow(3, 2)); Tensor0D<int> s0{2}; Tensor0D<int> t0{4}; auto lambda_0d = [&s0, &t0]() -> Tensor0D<int> { return mhlo::pow<Tensor0D<int>>(s0, t0); }; EXPECT_THAT(lambda_0d(), Pointwise(Eq(), {16})); Tensor1D<float, 2> s1{4.0f, 2.0f}; Tensor1D<float, 2> t1{0.5f, -2.0f}; auto lambda_1d = [&s1, &t1]() -> Tensor1D<float, 2> { return mhlo::pow<Tensor1D<float, 2>>(s1, t1); }; EXPECT_THAT(lambda_1d(), Pointwise(FloatNear(EPSILON), {2.0f, 0.25f})); Tensor2D<long, 2, 2> s2{3, 1, 4, 2}; Tensor2D<long, 2, 2> t2{0, -1, 3, -2}; auto lambda_2d = [&s2, &t2]() -> Tensor2D<long, 2, 2> { return mhlo::pow<Tensor2D<long, 2, 2>>(s2, t2); }; EXPECT_THAT(lambda_2d(), Pointwise(Eq(), {1, 1, 64, 0})); } TEST(mhlo, shift_left) { EXPECT_EQ(16u, mhlo::shift_left(2u, 3u)); Tensor0D<uint> s0{2}; Tensor0D<uint> t0{8}; auto lambda_0d = [&s0, &t0]() -> Tensor0D<uint> { return mhlo::shift_left<Tensor0D<uint>>(s0, t0); }; EXPECT_THAT(lambda_0d(), Pointwise(Eq(), {512})); Tensor1D<uint8_t, 2> s1{3, 0}; Tensor1D<uint8_t, 2> t1{2, 3}; auto lambda_1d = [&s1, &t1]() -> Tensor1D<uint8_t, 2> { return mhlo::shift_left<Tensor1D<uint8_t, 2>>(s1, t1); }; EXPECT_THAT(lambda_1d(), Pointwise(Eq(), {12, 0})); Tensor2D<uint64_t, 2, 2> s2{0, 2, 5, 10}; Tensor2D<uint64_t, 2, 2> t2{0, 1, 3, 4}; auto lambda_2d = [&s2, &t2]() -> Tensor2D<uint64_t, 2, 2> { return mhlo::shift_left<Tensor2D<uint64_t, 2, 2>>(s2, t2); }; EXPECT_THAT(lambda_2d(), Pointwise(Eq(), {0, 4, 40, 160})); } TEST(mhlo, shift_right_logical) { EXPECT_EQ(2u, mhlo::shift_right_logical(4u, 1u)); Tensor0D<uint> s0{6}; Tensor0D<uint> t0{2}; auto lambda_0d = [&s0, &t0]() -> Tensor0D<uint> { return mhlo::shift_right_logical<Tensor0D<uint>>(s0, t0); }; EXPECT_THAT(lambda_0d(), Pointwise(Eq(), {1})); Tensor1D<uint8_t, 2> s1{17, 32}; Tensor1D<uint8_t, 2> t1{1, 3}; auto lambda_1d = [&s1, &t1]() -> Tensor1D<uint8_t, 2> { return mhlo::shift_right_logical<Tensor1D<uint8_t, 2>>(s1, t1); }; EXPECT_THAT(lambda_1d(), Pointwise(Eq(), {8, 4})); Tensor2D<uint64_t, 2, 2> s2{0, 2, 25, 10}; Tensor2D<uint64_t, 2, 2> t2{0, 1, 3, 2}; auto lambda_2d = [&s2, &t2]() -> Tensor2D<uint64_t, 2, 2> { return mhlo::shift_right_logical<Tensor2D<uint64_t, 2, 2>>(s2, t2); }; EXPECT_THAT(lambda_2d(), Pointwise(Eq(), {0, 1, 3, 2})); } TEST(mhlo, sub) { EXPECT_EQ(-4, mhlo::sub(-1, 3)); Tensor0D<int> s0{-3}; Tensor0D<int> t0{8}; auto lambda_0d = [&s0, &t0]() -> Tensor0D<int> { return mhlo::sub<Tensor0D<int>>(s0, t0); }; EXPECT_THAT(lambda_0d(), Pointwise(Eq(), {-11})); Tensor1D<float, 2> s1{-1.3f, 2.4f}; Tensor1D<float, 2> t1{0.2f, -3.7f}; auto lambda_1d = [&s1, &t1]() -> Tensor1D<float, 2> { return mhlo::sub<Tensor1D<float, 2>>(s1, t1); }; EXPECT_THAT(lambda_1d(), Pointwise(FloatEq(), {-1.5f, 6.1f})); Tensor2D<long, 2, 2> s2{3, 1, 4, 9}; Tensor2D<long, 2, 2> t2{-2, 8, 6, -10}; auto lambda_2d = [&s2, &t2]() -> Tensor2D<long, 2, 2> { return mhlo::sub<Tensor2D<long, 2, 2>>(s2, t2); }; EXPECT_THAT(lambda_2d(), Pointwise(Eq(), {5, -7, -2, 19})); } // Binary logical elementwise ops TEST(mhlo, or) { EXPECT_EQ(1, mhlo::logical_or(2, 3)); Tensor0D<int> s0{2}; Tensor0D<int> t0{8}; auto lambda_0d = [&s0, &t0]() -> Tensor0D<int> { return mhlo::logical_or<Tensor0D<int>>(s0, t0); }; EXPECT_THAT(lambda_0d(), Pointwise(Eq(), {1})); Tensor1D<int8_t, 2> s1{-1, 0}; Tensor1D<int8_t, 2> t1{0, 0}; auto lambda_1d = [&s1, &t1]() -> Tensor1D<int8_t, 2> { return mhlo::logical_or<Tensor1D<int8_t, 2>>(s1, t1); }; EXPECT_THAT(lambda_1d(), Pointwise(Eq(), {1, 0})); Tensor2D<long, 2, 2> s2{0, 2, 0, -1}; Tensor2D<long, 2, 2> t2{0, 0, -2, -2}; auto lambda_2d = [&s2, &t2]() -> Tensor2D<long, 2, 2> { return mhlo::logical_or<Tensor2D<long, 2, 2>>(s2, t2); }; EXPECT_THAT(lambda_2d(), Pointwise(Eq(), {0, 1, 1, 1})); } TEST(mhlo, xor) { EXPECT_EQ(1, mhlo::logical_xor(2, 3)); Tensor0D<int> s0{2}; Tensor0D<int> t0{8}; auto lambda_0d = [&s0, &t0]() -> Tensor0D<int> { return mhlo::logical_xor<Tensor0D<int>>(s0, t0); }; EXPECT_THAT(lambda_0d(), Pointwise(Eq(), {1})); Tensor1D<int8_t, 2> s1{-1, 0}; Tensor1D<int8_t, 2> t1{0, 0}; auto lambda_1d = [&s1, &t1]() -> Tensor1D<int8_t, 2> { return mhlo::logical_xor<Tensor1D<int8_t, 2>>(s1, t1); }; EXPECT_THAT(lambda_1d(), Pointwise(Eq(), {1, 0})); Tensor2D<long, 2, 2> s2{0, 2, 0, -1}; Tensor2D<long, 2, 2> t2{0, 0, -2, -2}; auto lambda_2d = [&s2, &t2]() -> Tensor2D<long, 2, 2> { return mhlo::logical_xor<Tensor2D<long, 2, 2>>(s2, t2); }; EXPECT_THAT(lambda_2d(), Pointwise(Eq(), {0, 1, 1, 1})); } // Tuple ops TEST(mhlo, compare) { auto lambda = []() { return mhlo::compare<int, std::less>(-1, 3); }; EXPECT_EQ(true, lambda()); Tensor0D<int> s0{-3}; Tensor0D<int> t0{-8}; auto lambda_0d = [&s0, &t0]() { return mhlo::compare<Tensor0D<int>, std::less_equal>(s0, t0); }; EXPECT_THAT(lambda_0d(), Pointwise(Eq(), {false})); Tensor1D<float, 2> s1{-1.3f, 2.4f}; Tensor1D<float, 2> t1{0.2f, 2.4f}; auto lambda_1d = [&s1, &t1]() { return mhlo::compare<Tensor1D<float, 2>, std::equal_to>(s1, t1); }; EXPECT_THAT(lambda_1d(), Pointwise(Eq(), {false, true})); Tensor2D<long, 2, 2> s2{3, 1, 4, 9}; Tensor2D<long, 2, 2> t2{-2, 1, 6, -10}; auto lambda_2d = [&s2, &t2]() { return mhlo::compare<Tensor2D<long, 2, 2>, std::greater_equal>(s2, t2); }; EXPECT_THAT(lambda_2d(), Pointwise(Eq(), {true, true, false, true})); Tensor3D<long, 2, 1, 2> s3{3, 1, 4, 9}; Tensor3D<long, 2, 1, 2> t3{-2, 1, 6, -10}; auto lambda_3d = [&s3, &t3]() { return mhlo::compare<Tensor3D<long, 2, 1, 2>, std::greater_equal>(s3, t3); }; EXPECT_THAT(lambda_3d(), Pointwise(Eq(), {true, true, false, true})); Tensor4D<int, 2, 1, 2, 2> s4{3, 1, 4, 9, 10, 12, -4, 8}; Tensor4D<int, 2, 1, 2, 2> t4{-2, 1, 6, -10, 9, 13, 4, 10}; auto lambda_4d = [&s4, &t4]() { return mhlo::compare<Tensor4D<int, 2, 1, 2, 2>, std::greater_equal>(s4, t4); }; EXPECT_THAT(lambda_4d(), Pointwise(Eq(), {true, true, false, true, true, false, false, false})); } // Slice ops TEST(mhlo, slice) { // Slice Tensor1D Tensor1D<float, 5> s1{0.0f, 1.0f, 2.0f, 3.0f, 4.0f}; auto t1 = mhlo::slice<Tensor1D<float, 2>, Tensor1D<float, 5>>(s1, {2}, {4}, {1}); EXPECT_THAT(t1, Pointwise(FloatEq(), {2.0f, 3.0f})); auto t1_strided = mhlo::slice<Tensor1D<float, 2>, Tensor1D<float, 5>>(s1, {1}, {4}, {2}); EXPECT_THAT(t1_strided, Pointwise(FloatEq(), {1.0f, 3.0f})); // Slice Tensor2D Tensor2D<float, 4, 3> s2{0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f}; auto t2 = mhlo::slice<Tensor2D<float, 2, 2>, Tensor2D<float, 4, 3>>( s2, {2, 1}, {4, 3}, {1, 1}); EXPECT_THAT(t2, Pointwise(FloatEq(), {7.0f, 8.0f, 10.0f, 11.0f})); auto t2_strided = mhlo::slice<Tensor2D<float, 2, 2>, Tensor2D<float, 4, 3>>( s2, {1, 0}, {4, 3}, {2, 2}); EXPECT_THAT(t2_strided, Pointwise(FloatEq(), {3.0f, 5.0f, 9.0f, 11.0f})); // Slice Tensor3D Tensor3D<float, 4, 3, 2> s3{0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f, 16.0f, 17.0f, 18.0f, 19.0f, 20.0f, 21.0f, 22.0f, 23.0f}; auto t3 = mhlo::slice<Tensor3D<float, 2, 2, 2>, Tensor3D<float, 4, 3, 2>>( s3, {2, 1, 0}, {4, 3, 2}, {1, 1, 1}); EXPECT_THAT(t3, Pointwise(FloatEq(), {14.0f, 15.0f, 16.0f, 17.0f, 20.0f, 21.0f, 22.0f, 23.0f})); auto t3_strided = mhlo::slice<Tensor3D<float, 2, 2, 1>, Tensor3D<float, 4, 3, 2>>( s3, {0, 1, 0}, {4, 3, 2}, {2, 1, 2}); EXPECT_THAT(t3_strided, Pointwise(FloatEq(), {2.0f, 4.0f, 14.0f, 16.0f})); auto t3_strided2 = mhlo::slice<Tensor3D<float, 1, 2, 1>, Tensor3D<float, 4, 3, 2>>( s3, {0, 1, 0}, {2, 3, 2}, {2, 1, 2}); EXPECT_THAT(t3_strided2, Pointwise(FloatEq(), {2.0f, 4.0f})); // Slice Tensor4D Tensor4D<float, 4, 3, 1, 2> s4{0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f, 16.0f, 17.0f, 18.0f, 19.0f, 20.0f, 21.0f, 22.0f, 23.0f}; auto t4 = mhlo::slice<Tensor4D<float, 2, 2, 1, 2>, Tensor4D<float, 4, 3, 1, 2>>( s4, {2, 1, 0, 0}, {4, 3, 1, 2}, {1, 1, 1, 1}); EXPECT_THAT(t4, Pointwise(FloatEq(), {14.0f, 15.0f, 16.0f, 17.0f, 20.0f, 21.0f, 22.0f, 23.0f})); auto t4_2 = mhlo::slice<Tensor4D<float, 4, 3, 1, 2>, Tensor4D<float, 4, 3, 1, 2>>( s4, {0, 0, 0, 0}, {4, 3, 1, 2}, {1, 1, 1, 1}); EXPECT_THAT(t4_2, Pointwise(FloatEq(), s4)); auto t4_strided = mhlo::slice<Tensor4D<float, 3, 2, 1, 1>, Tensor4D<float, 4, 3, 1, 2>>( s4, {1, 0, 0, 0}, {4, 3, 1, 2}, {1, 2, 1, 2}); EXPECT_THAT(t4_strided, Pointwise(FloatEq(), {6.0f, 10.0f, 12.0f, 16.0f, 18.0f, 22.0f})); auto t4_strided_2 = mhlo::slice<Tensor4D<float, 2, 1, 1, 1>, Tensor4D<float, 4, 3, 1, 2>>( s4, {0, 2, 0, 0}, {4, 3, 1, 1}, {2, 1, 1, 1}); EXPECT_THAT(t4_strided_2, Pointwise(FloatEq(), {4.0f, 16.0f})); } TEST(mhlo, dynamic_slice) { Tensor1D<float, 5> s1{0.0f, 1.0f, 2.0f, 3.0f, 4.0f}; auto t1 = mhlo::dynamic_slice<Tensor1D<float, 2>, Tensor1D<float, 5>>(s1, {2}, {2}); EXPECT_THAT(t1, Pointwise(FloatEq(), {2.0f, 3.0f})); Tensor2D<float, 4, 3> s2{0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f}; auto t2 = mhlo::dynamic_slice<Tensor2D<float, 2, 2>, Tensor2D<float, 4, 3>>( s2, {2}, {1}, {2, 2}); EXPECT_THAT(t2, Pointwise(FloatEq(), {7.0f, 8.0f, 10.0f, 11.0f})); } TEST(mhlo, dynamic_update_slice) { Tensor1D<float, 5> s1{0.0f, 1.0f, 2.0f, 3.0f, 4.0f}; Tensor1D<float, 2> u1{5.0f, 6.0f}; auto t1 = mhlo::dynamic_update_slice<Tensor1D<float, 2>, Tensor1D<float, 5>>( s1, u1, {2}); EXPECT_THAT(t1, Pointwise(FloatEq(), {0.0f, 1.0f, 5.0f, 6.0f, 4.0f})); Tensor2D<float, 4, 3> s2{0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f}; Tensor2D<float, 3, 2> u2{12.0f, 13.0f, 14.0f, 15.0f, 16.0f, 17.0f}; auto t2 = mhlo::dynamic_update_slice<Tensor2D<float, 3, 2>, Tensor2D<float, 4, 3>>( s2, u2, {1}, {1}); EXPECT_THAT(t2, Pointwise(FloatEq(), {0.0f, 1.0f, 2.0f, 3.0f, 12.0f, 13.0f, 6.0f, 14.0f, 15.0f, 9.0f, 16.0f, 17.0f})); } // Other ops TEST(mhlo, batch_norm_inference) { Tensor<float, 4, 2> input{0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f}; Tensor<float, 4, 2> expected_result{-3.0f, 2.0f, 1.0f, 6.0f, 5.0f, 10.0f, 9.0f, 14.0f}; Tensor<float, 4, 2> result = mhlo::batch_norm_inference<Tensor<float, 4, 2>, Tensor<float, 2>>( input, {1.0f, 2.0f}, {1.0f, 2.0f}, {2.0f, 1.0f}, {0.249f, 0.999f}, 0.001f, 1); EXPECT_THAT(result, Pointwise(FloatNear(EPSILON), expected_result)); } TEST(mhlo, bitcast_convert) { uint8_t a = 128; int8_t b = -128; EXPECT_EQ(b, mhlo::bitcast_convert<int8_t>(a)); Tensor0D<int16_t> t0{-1}; auto lambda_0d = [&t0]() { return mhlo::bitcast_convert<Tensor0D<uint16_t>>(t0); }; EXPECT_THAT(lambda_0d(), Pointwise(Eq(), {65535})); Tensor1D<uint16_t, 2> t1{1, 2}; auto lambda_1d = [&t1]() { return mhlo::bitcast_convert<Tensor1D<int16_t, 2>>(t1); }; EXPECT_THAT(lambda_1d(), Pointwise(Eq(), {1, 2})); Tensor2D<int8_t, 2, 2> t2{0, -4, 3, -12}; auto lambda_2d = [&t2]() { return mhlo::bitcast_convert<Tensor2D<uint8_t, 2, 2>>(t2); }; EXPECT_THAT(lambda_2d(), Pointwise(DoubleEq(), {0, 252, 3, 244})); Tensor3D<int8_t, 2, 1, 2> t3{0, -4, 3, -12}; auto lambda_3d = [&t3]() { return mhlo::bitcast_convert<Tensor3D<uint8_t, 2, 1, 2>>(t3); }; EXPECT_THAT(lambda_3d(), Pointwise(DoubleEq(), {0, 252, 3, 244})); Tensor4D<int8_t, 2, 1, 2, 2> t4{0, -4, 3, -12, -11, 0, 2, -4}; auto lambda_4d = [&t4]() { return mhlo::bitcast_convert<Tensor4D<uint8_t, 2, 1, 2, 2>>(t4); }; EXPECT_THAT(lambda_4d(), Pointwise(DoubleEq(), {0, 252, 3, 244, 245, 0, 2, 252})); } TEST(mhlo, broadcast_in_dim) { Tensor0D<int> t0{1}; Tensor1D<int64_t, 0> b0; { // 0D -> 1D using Dest = Tensor1D<int, 4>; Dest expected_result{1, 1, 1, 1}; Dest result = mhlo::broadcast_in_dim<Dest>(t0, b0); EXPECT_THAT(result, Pointwise(Eq(), expected_result)); } { // 0D -> 2D using Dest = Tensor2D<int, 2, 3>; Dest expected_result{1, 1, 1, 1, 1, 1}; Dest result = mhlo::broadcast_in_dim<Dest>(t0, b0); EXPECT_THAT(result, Pointwise(Eq(), expected_result)); } Tensor<int, 2> t1{1, 2}; { // 1D -> 2D using Dest = Tensor<int, 3, 2>; Dest expected_result{1, 2, 1, 2, 1, 2}; Dest result = mhlo::broadcast_in_dim<Dest>(t1, {1}); EXPECT_THAT(result, Pointwise(Eq(), expected_result)); } { // 1D -> 2D using Dest = Tensor<int, 2, 3>; Dest expected_result{1, 1, 1, 2, 2, 2}; Dest result = mhlo::broadcast_in_dim<Dest>(t1, {0}); EXPECT_THAT(result, Pointwise(Eq(), expected_result)); } Tensor<int, 2, 3> t2{1, 2, 3, 4, 5, 6}; { // 2D transpose using Dest = Tensor<int, 3, 2>; Dest expected_result{1, 4, 2, 5, 3, 6}; Dest result = mhlo::broadcast_in_dim<Dest>(t2, {1, 0}); EXPECT_THAT(result, Pointwise(Eq(), expected_result)); } Tensor2D<float, 1, 3> t3{1.1, 1.2, 1.3}; { // 2D -> 3D using Dest = Tensor3D<float, 1, 2, 3>; Tensor1D<int64_t, 2> broadcast_dim{1, 2}; Dest result = mhlo::broadcast_in_dim<Dest>(t3, broadcast_dim); Dest expected_result{1.1, 1.2, 1.3, 1.1, 1.2, 1.3}; EXPECT_THAT(result, Pointwise(Eq(), expected_result)); } { // 2D -> 3D + transpose using Dest = Tensor3D<float, 1, 3, 2>; Tensor1D<int64_t, 2> broadcast_dim{2, 1}; Dest result = mhlo::broadcast_in_dim<Dest>(t3, broadcast_dim); Dest expected_result{1.1, 1.1, 1.2, 1.2, 1.3, 1.3}; EXPECT_THAT(result, Pointwise(Eq(), expected_result)); } { // 2D -> 4D using Dest = Tensor4D<float, 1, 2, 2, 3>; Tensor1D<int64_t, 2> broadcast_dim{2, 3}; Dest result = mhlo::broadcast_in_dim<Dest>(t3, broadcast_dim); Dest expected_result{1.1, 1.2, 1.3, 1.1, 1.2, 1.3, 1.1, 1.2, 1.3, 1.1, 1.2, 1.3}; EXPECT_THAT(result, Pointwise(Eq(), expected_result)); } Tensor3D<float, 2, 2, 3> t4{1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6}; { // 3D -> 4D using Dest = Tensor4D<float, 2, 2, 2, 3>; Tensor1D<int64_t, 3> broadcast_dim{1, 2, 3}; Dest result = mhlo::broadcast_in_dim<Dest>(t4, broadcast_dim); Dest expected_result{1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6}; EXPECT_THAT(result, Pointwise(Eq(), expected_result)); } } TEST(mhlo, clamp) { Tensor<float, 2, 1> operand{-1.0f, 1.0f}; Tensor<float, 2, 1> min{0.0f, 0.0f}; Tensor<float, 2, 1> max{3.0f, 0.0f}; Tensor<float, 2, 1> expected_result{0.0, 0.0f}; Tensor<float, 2, 1> result = mhlo::clamp(min, operand, max); EXPECT_THAT(result, Pointwise(FloatEq(), expected_result)); // broadcasting Tensor<int32_t, 4, 2, 1> operand_b{0, 1, 2, 3, 4, 5, 6, 7}; Tensor<int32_t> min_b{2}; Tensor<int32_t> max_b{5}; Tensor<int32_t, 4, 2, 1> expected_result_b{2, 2, 2, 3, 4, 5, 5, 5}; Tensor<int32_t, 4, 2, 1> result_b = mhlo::clamp(min_b, operand_b, max_b); EXPECT_THAT(result_b, Pointwise(Eq(), expected_result_b)); } TEST(mhlo, concatenate) { Tensor1D<int, 1> t1{1}; Tensor1D<int, 2> t2{2, 3}; Tensor1D<int, 3> t3{4, 5, 6}; auto lambda_1d_1 = [&t1]() -> Tensor1D<int, 1> { return mhlo::concatenate<0, Tensor1D<int, 1>, Tensor1D<int, 1>>(t1); }; EXPECT_THAT(lambda_1d_1(), Pointwise(Eq(), {1})); auto lambda_1d_2 = [&t1, &t2]() -> Tensor1D<int, 3> { return mhlo::concatenate<0, Tensor1D<int, 3>, Tensor1D<int, 1>, Tensor1D<int, 2>>(t1, t2); }; EXPECT_THAT(lambda_1d_2(), Pointwise(Eq(), {1, 2, 3})); auto lambda_1d_3 = [&t1, &t2, &t3]() -> Tensor1D<int, 6> { return mhlo::concatenate<0, Tensor1D<int, 6>, Tensor1D<int, 1>, Tensor1D<int, 2>, Tensor1D<int, 3>>(t1, t2, t3); }; EXPECT_THAT(lambda_1d_3(), Pointwise(Eq(), {1, 2, 3, 4, 5, 6})); Tensor2D<float, 1, 2> t4{1.0f, 2.0f}; Tensor2D<float, 2, 2> t5{3.0f, 4.0f, 5.0f, 6.0f}; Tensor2D<float, 3, 2> t6{7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f}; auto lambda_2d_2_row = [&t4, &t5]() -> Tensor2D<float, 3, 2> { return mhlo::concatenate<0, Tensor2D<float, 3, 2>, Tensor2D<float, 1, 2>, Tensor2D<float, 2, 2>>(t4, t5); }; EXPECT_THAT(lambda_2d_2_row(), Pointwise(FloatEq(), {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f})); auto lambda_2d_2_col = [&t4, &t5]() -> Tensor2D<float, 2, 3> { Tensor2D<float, 2, 1> t4_reshape = mhlo::reshape<Tensor2D<float, 2, 1>>(t4); return mhlo::concatenate<1, Tensor2D<float, 2, 3>, Tensor2D<float, 2, 1>, Tensor2D<float, 2, 2>>(t4_reshape, t5); }; EXPECT_THAT(lambda_2d_2_col(), Pointwise(FloatEq(), {1.0f, 3.0f, 4.0f, 2.0f, 5.0f, 6.0f})); auto lambda_2d_3_row = [&t4, &t5, &t6]() -> Tensor2D<float, 6, 2> { return mhlo::concatenate<0, Tensor2D<float, 6, 2>, Tensor2D<float, 1, 2>, Tensor2D<float, 2, 2>, Tensor2D<float, 3, 2>>( t4, t5, t6); }; EXPECT_THAT(lambda_2d_3_row(), Pointwise(FloatEq(), {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f})); auto lambda_2d_3_col = [&t4, &t5, &t6]() -> Tensor2D<float, 2, 6> { Tensor2D<float, 2, 1> t4_reshape = mhlo::reshape<Tensor2D<float, 2, 1>>(t4); Tensor2D<float, 2, 3> t6_reshape = mhlo::reshape<Tensor2D<float, 2, 3>>(t6); return mhlo::concatenate<1, Tensor2D<float, 2, 6>, Tensor2D<float, 2, 1>, Tensor2D<float, 2, 2>, Tensor2D<float, 2, 3>>( t4_reshape, t5, t6_reshape); }; EXPECT_THAT(lambda_2d_3_col(), Pointwise(FloatEq(), {1.0f, 3.0f, 4.0f, 7.0f, 8.0f, 9.0f, 2.0f, 5.0f, 6.0f, 10.0f, 11.0f, 12.0f})); Tensor3D<float, 2, 2, 2> t7{1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f}; Tensor3D<float, 2, 2, 2> t8{9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f, 16.0f}; Tensor3D<float, 2, 2, 1> t9{9.0f, 10.0f, 11.0f, 12.0f}; auto lambda_3d_422 = [&t7, &t8]() -> Tensor3D<float, 4, 2, 2> { return mhlo::concatenate<0, Tensor3D<float, 4, 2, 2>, Tensor3D<float, 2, 2, 2>, Tensor3D<float, 2, 2, 2>>(t7, t8); }; EXPECT_THAT(lambda_3d_422(), Pointwise(FloatEq(), {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f, 16.0f})); auto lambda_3d_242 = [&t7, &t8]() -> Tensor3D<float, 2, 4, 2> { return mhlo::concatenate<1, Tensor3D<float, 2, 4, 2>, Tensor3D<float, 2, 2, 2>, Tensor3D<float, 2, 2, 2>>(t7, t8); }; EXPECT_THAT(lambda_3d_242(), Pointwise(FloatEq(), {1.0f, 2.0f, 3.0f, 4.0f, 9.0f, 10.0f, 11.0f, 12.0f, 5.0f, 6.0f, 7.0f, 8.0f, 13.0f, 14.0f, 15.0f, 16.0f})); auto lambda_3d_223 = [&t7, &t9]() -> Tensor3D<float, 2, 2, 3> { return mhlo::concatenate<2, Tensor3D<float, 2, 2, 3>, Tensor3D<float, 2, 2, 2>, Tensor3D<float, 2, 2, 1>>(t7, t9); }; EXPECT_THAT(lambda_3d_223(), Pointwise(FloatEq(), {1.0f, 2.0f, 9.0f, 3.0f, 4.0f, 10.0f, 5.0f, 6.0f, 11.0f, 7.0f, 8.0f, 12.0f})); Tensor4D<float, 2, 2, 2, 2> t10{1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f, 16.0f}; Tensor4D<float, 2, 2, 2, 2> t11{17.0f, 18.0f, 19.0f, 20.0f, 21.0f, 22.0f, 23.0f, 24.0f, 25.0f, 26.0f, 27.0f, 28.0f, 29.0f, 30.0f, 31.0f, 32.0f}; Tensor4D<float, 2, 2, 1, 2> t12{33.0f, 34.0f, 35.0f, 36.0f, 37.0f, 38.0f, 39.0f, 40.0f}; auto lambda_4d_4222 = [&t10, &t11]() -> Tensor4D<float, 4, 2, 2, 2> { return mhlo::concatenate<0, Tensor4D<float, 4, 2, 2, 2>, Tensor4D<float, 2, 2, 2, 2>, Tensor4D<float, 2, 2, 2, 2>>(t10, t11); }; EXPECT_THAT( lambda_4d_4222(), Pointwise(FloatEq(), {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f, 16.0f, 17.0f, 18.0f, 19.0f, 20.0f, 21.0f, 22.0f, 23.0f, 24.0f, 25.0f, 26.0f, 27.0f, 28.0f, 29.0f, 30.0f, 31.0f, 32.0f})); auto lambda_4d_2422 = [&t10, &t11]() -> Tensor4D<float, 2, 4, 2, 2> { return mhlo::concatenate<1, Tensor4D<float, 2, 4, 2, 2>, Tensor4D<float, 2, 2, 2, 2>, Tensor4D<float, 2, 2, 2, 2>>(t10, t11); }; EXPECT_THAT( lambda_4d_2422(), Pointwise(FloatEq(), {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 17.0f, 18.0f, 19.0f, 20.0f, 21.0f, 22.0f, 23.0f, 24.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f, 16.0f, 25.0f, 26.0f, 27.0f, 28.0f, 29.0f, 30.0f, 31.0f, 32.0f})); auto lambda_4d_2242 = [&t10, &t11]() -> Tensor4D<float, 2, 2, 4, 2> { return mhlo::concatenate<2, Tensor4D<float, 2, 2, 4, 2>, Tensor4D<float, 2, 2, 2, 2>, Tensor4D<float, 2, 2, 2, 2>>(t10, t11); }; EXPECT_THAT( lambda_4d_2242(), Pointwise(FloatEq(), {1.0f, 2.0f, 3.0f, 4.0f, 17.0f, 18.0f, 19.0f, 20.0f, 5.0f, 6.0f, 7.0f, 8.0f, 21.0f, 22.0f, 23.0f, 24.0f, 9.0f, 10.0f, 11.0f, 12.0f, 25.0f, 26.0f, 27.0f, 28.0f, 13.0f, 14.0f, 15.0f, 16.0f, 29.0f, 30.0f, 31.0f, 32.0f})); auto lambda_4d_2224 = [&t10, &t11]() -> Tensor4D<float, 2, 2, 2, 4> { return mhlo::concatenate<3, Tensor4D<float, 2, 2, 2, 4>, Tensor4D<float, 2, 2, 2, 2>, Tensor4D<float, 2, 2, 2, 2>>(t10, t11); }; EXPECT_THAT( lambda_4d_2224(), Pointwise(FloatEq(), {1.0f, 2.0f, 17.0f, 18.0f, 3.0f, 4.0f, 19.0f, 20.0f, 5.0f, 6.0f, 21.0f, 22.0f, 7.0f, 8.0f, 23.0f, 24.0f, 9.0f, 10.0f, 25.0f, 26.0f, 11.0f, 12.0f, 27.0f, 28.0f, 13.0f, 14.0f, 29.0f, 30.0f, 15.0f, 16.0f, 31.0f, 32.0f})); auto lambda_4d_2232 = [&t10, &t12]() -> Tensor4D<float, 2, 2, 3, 2> { return mhlo::concatenate<2, Tensor4D<float, 2, 2, 3, 2>, Tensor4D<float, 2, 2, 2, 2>, Tensor4D<float, 2, 2, 1, 2>>(t10, t12); }; EXPECT_THAT(lambda_4d_2232(), Pointwise(FloatEq(), {1.0f, 2.0f, 3.0f, 4.0f, 33.0f, 34.0f, 5.0f, 6.0f, 7.0f, 8.0f, 35.0f, 36.0f, 9.0f, 10.0f, 11.0f, 12.0f, 37.0f, 38.0f, 13.0f, 14.0f, 15.0f, 16.0f, 39.0f, 40.0f})); } TEST(mhlo, convolution) { int64_t batch_group_count = 1; int64_t input_batch_dimension = 0; int64_t input_feature_dimension = 3; Tensor1D<int64_t, 2> input_spatial_dimensions{1, 2}; int64_t kernel_input_feature_dimension = 2; int64_t kernel_output_feature_dimension = 3; Tensor1D<int64_t, 2> kernel_spatial_dimensions{0, 1}; int64_t output_batch_dimension = 0; int64_t output_feature_dimension = 3; Tensor1D<int64_t, 2> output_spatial_dimensions{1, 2}; int64_t feature_group_count = 1; Tensor1D<int64_t, 2> rhs_dilation{1, 1}; Tensor1D<int64_t, 2> lhs_dilation{1, 1}; { /// Adapted from /// https://github.com/google/iree/blob/efd78a0b47a46457a644f43d98617d3e279b2a79/iree/test/e2e/xla_ops/convolution.mlir#L33 using InputType = Tensor4D<float, 1, 4, 5, 2>; // N H W C using WeightType = Tensor4D<float, 3, 2, 2, 1>; // KH KW CIN COUT using ResultType = Tensor4D<float, 1, 4, 5, 1>; // N H W C InputType input{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40}; WeightType weights{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; ResultType expected_result{600, 736, 872, 1008, 476, 1310, 1466, 1622, 1778, 805, 2090, 2246, 2402, 2558, 1135, 1080, 1152, 1224, 1296, 524}; Tensor2D<int64_t, 2, 2> padding{1, 1, 0, 1}; // {pt, pb, pl, pr} Tensor1D<int64_t, 2> window_strides{1, 1}; ResultType result = mhlo::convolution<ResultType, InputType, WeightType>( input, weights, batch_group_count, input_batch_dimension, input_feature_dimension, input_spatial_dimensions, kernel_input_feature_dimension, kernel_output_feature_dimension, kernel_spatial_dimensions, output_batch_dimension, output_feature_dimension, output_spatial_dimensions, feature_group_count, padding, lhs_dilation, rhs_dilation, window_strides); EXPECT_THAT(result, Pointwise(FloatNear(EPSILON), expected_result)); } { // Strided convolution using InputType = Tensor4D<float, 1, 4, 4, 1>; // N H W C using WeightType = Tensor4D<float, 2, 2, 1, 1>; // KH KW CIN COUT using ResultType = Tensor4D<float, 1, 2, 2, 1>; // N H W C // clang-format off InputType input{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; WeightType weights{1, 2, 3, 4}; ResultType expected_result{44, 64, 124, 144}; // clang-format on Tensor2D<int64_t, 2, 2> padding{0, 0, 0, 0}; // {pt, pb, pl, pr} Tensor1D<int64_t, 2> window_strides{2, 2}; ResultType result = mhlo::convolution<ResultType, InputType, WeightType>( input, weights, batch_group_count, input_batch_dimension, input_feature_dimension, input_spatial_dimensions, kernel_input_feature_dimension, kernel_output_feature_dimension, kernel_spatial_dimensions, output_batch_dimension, output_feature_dimension, output_spatial_dimensions, feature_group_count, padding, lhs_dilation, rhs_dilation, window_strides); EXPECT_THAT(result, Pointwise(FloatNear(EPSILON), expected_result)); } } TEST(mhlo, convolution_depthwise) { using InputType = Tensor4D<float, 1, 4, 5, 2>; using WeightType = Tensor4D<float, 2, 2, 1, 2>; using ResultType = Tensor4D<float, 1, 3, 4, 2>; InputType input{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40}; WeightType weights{1, 2, 3, 4, 5, 6, 7, 8}; ResultType expected_result{156, 204, 188, 244, 220, 284, 252, 324, 316, 404, 348, 444, 380, 484, 412, 524, 476, 604, 508, 644, 540, 684, 572, 724}; int64_t batch_group_count = 1; int64_t input_batch_dimension = 0; int64_t input_feature_dimension = 3; Tensor1D<int64_t, 2> input_spatial_dimensions{1, 2}; int64_t kernel_input_feature_dimension = 2; int64_t kernel_output_feature_dimension = 3; Tensor1D<int64_t, 2> kernel_spatial_dimensions{0, 1}; int64_t output_batch_dimension = 0; int64_t output_feature_dimension = 3; Tensor1D<int64_t, 2> output_spatial_dimensions{1, 2}; int64_t feature_group_count = 2; Tensor2D<int64_t, 2, 2> padding{0, 0, 0, 0}; Tensor1D<int64_t, 2> rhs_dilation{1, 1}; Tensor1D<int64_t, 2> lhs_dilation{1, 1}; Tensor1D<int64_t, 2> window_strides{1, 1}; ResultType result = mhlo::convolution<ResultType, InputType, WeightType>( input, weights, batch_group_count, input_batch_dimension, input_feature_dimension, input_spatial_dimensions, kernel_input_feature_dimension, kernel_output_feature_dimension, kernel_spatial_dimensions, output_batch_dimension, output_feature_dimension, output_spatial_dimensions, feature_group_count, padding, lhs_dilation, rhs_dilation, window_strides); EXPECT_THAT(result, Pointwise(FloatNear(EPSILON), expected_result)); } TEST(mhlo, DISABLED_convolution_grouped) { // TODO implement test } TEST(mhlo, DISABLED_convolution_dilated) { // TODO implement test } TEST(mhlo, dot) { Tensor2D<int, 2, 2> a2{1, 0, 0, 1}; Tensor2D<int, 2, 2> b2{4, 1, 2, 2}; auto lambda_2d = [&a2, &b2]() -> Tensor2D<int, 2, 2> { return mhlo::dot<Tensor2D<int, 2, 2>>(a2, b2); }; EXPECT_THAT(lambda_2d(), Pointwise(Eq(), {4, 1, 2, 2})); } TEST(mhlo, reshape) { Tensor0D<int> s0{-3}; auto t0 = mhlo::reshape<Tensor1D<int, 1>>(s0); auto t0_1 = mhlo::reshape<Tensor2D<int, 1, 1>>(s0); EXPECT_THAT(t0, Pointwise(Eq(), {-3})); EXPECT_THAT(t0_1, Pointwise(Eq(), {-3})); Tensor1D<float, 2> s1{-1.3f, 2.4f}; auto t1 = mhlo::reshape<Tensor2D<float, 1, 2>>(s1); EXPECT_THAT(t1, Pointwise(FloatEq(), {-1.3f, 2.4f})); Tensor2D<long, 2, 2> s2{3, 1, 4, 9}; auto t2 = mhlo::reshape<Tensor1D<long, 4>>(s2); EXPECT_THAT(t2, Pointwise(Eq(), {3, 1, 4, 9})); } TEST(mhlo, pad) { Tensor<int32_t, 2, 3> operand{1, 2, 3, 4, 5, 6}; Tensor<int32_t> value{0}; Tensor<int32_t, 3, 6> expected_result0{0, 1, 2, 3, 0, 0, 0, 4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0}; Tensor<int32_t, 3, 6> result0 = mhlo::pad<Tensor<int32_t, 3, 6>>(operand, value, {0, 1}, {1, 2}, {0, 0}); EXPECT_THAT(result0, Pointwise(Eq(), expected_result0)); Tensor<int32_t, 3, 5> expected_result1{1, 0, 2, 0, 3, 0, 0, 0, 0, 0, 4, 0, 5, 0, 6}; Tensor<int32_t, 3, 5> result1 = mhlo::pad<Tensor<int32_t, 3, 5>>(operand, value, {0, 0}, {0, 0}, {1, 1}); EXPECT_THAT(result1, Pointwise(Eq(), expected_result1)); Tensor<int32_t, 4, 8> expected_result2{0, 1, 0, 2, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 5, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Tensor<int32_t, 4, 8> result2 = mhlo::pad<Tensor<int32_t, 4, 8>>(operand, value, {0, 1}, {1, 2}, {1, 1}); EXPECT_THAT(result2, Pointwise(Eq(), expected_result2)); } Tensor<int32_t> reduce_computation(Tensor<int32_t> a, Tensor<int32_t> b) { Tensor<int32_t> v0 = mhlo::add(a, b); return v0; } TEST(mhlo, reduce) { Tensor<int32_t, 2, 3> t0{1, 2, 3, 4, 5, 6}; Tensor<int32_t, 4, 2, 3> t1{1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6}; Tensor<int32_t, 3> expected_result0_0{5, 7, 9}; Tensor<int32_t, 2> expected_result0_1{6, 15}; Tensor<int32_t> expected_result0_01{21}; Tensor<int32_t, 2, 3> expected_result1_0{4, 8, 12, 16, 20, 24}; Tensor<int32_t, 4, 3> expected_result1_1{5, 7, 9, 5, 7, 9, 5, 7, 9, 5, 7, 9}; Tensor<int32_t, 4, 2> expected_result1_2{6, 15, 6, 15, 6, 15, 6, 15}; Tensor<int32_t, 3> expected_result1_01{20, 28, 36}; Tensor<int32_t, 2> expected_result1_02{24, 60}; Tensor<int32_t, 4> expected_result1_12{21, 21, 21, 21}; Tensor<int32_t> expected_result1_012{84}; Tensor<int32_t> initValue; Tensor<int32_t, 3> result0_0 = mhlo::reduce<Tensor<int32_t, 3>, 1>( t0, initValue, {0}, reduce_computation); Tensor<int32_t, 2> result0_1 = mhlo::reduce<Tensor<int32_t, 2>, 1>( t0, initValue, {1}, reduce_computation); Tensor<int32_t> result0_01 = mhlo::reduce<Tensor<int32_t>, 2>( t0, initValue, {0, 1}, reduce_computation); Tensor<int32_t, 2, 3> result1_0 = mhlo::reduce<Tensor<int32_t, 2, 3>, 1>( t1, initValue, {0}, reduce_computation); Tensor<int32_t, 4, 3> result1_1 = mhlo::reduce<Tensor<int32_t, 4, 3>, 1>( t1, initValue, {1}, reduce_computation); Tensor<int32_t, 4, 2> result1_2 = mhlo::reduce<Tensor<int32_t, 4, 2>, 1>( t1, initValue, {2}, reduce_computation); Tensor<int32_t, 3> result1_01 = mhlo::reduce<Tensor<int32_t, 3>, 2>( t1, initValue, {0, 1}, reduce_computation); Tensor<int32_t, 2> result1_02 = mhlo::reduce<Tensor<int32_t, 2>, 2>( t1, initValue, {0, 2}, reduce_computation); Tensor<int32_t, 4> result1_12 = mhlo::reduce<Tensor<int32_t, 4>, 2>( t1, initValue, {1, 2}, reduce_computation); Tensor<int32_t> result1_012 = mhlo::reduce<Tensor<int32_t>, 3>( t1, initValue, {0, 1, 2}, reduce_computation); EXPECT_THAT(result0_0, Pointwise(Eq(), expected_result0_0)); EXPECT_THAT(result0_1, Pointwise(Eq(), expected_result0_1)); EXPECT_THAT(result0_01, Pointwise(Eq(), expected_result0_01)); EXPECT_THAT(result1_0, Pointwise(Eq(), expected_result1_0)); EXPECT_THAT(result1_1, Pointwise(Eq(), expected_result1_1)); EXPECT_THAT(result1_2, Pointwise(Eq(), expected_result1_2)); EXPECT_THAT(result1_01, Pointwise(Eq(), expected_result1_01)); EXPECT_THAT(result1_02, Pointwise(Eq(), expected_result1_02)); EXPECT_THAT(result1_12, Pointwise(Eq(), expected_result1_12)); EXPECT_THAT(result1_012, Pointwise(Eq(), expected_result1_012)); } TEST(mhlo, reduce_window) { Tensor<int32_t> c0{std::numeric_limits<int32_t>::min()}; Tensor<int32_t, 4, 8> t0{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32}; auto max = [](Tensor<int32_t> a, Tensor<int32_t> b) { return mhlo::max(a, b); }; Tensor<int32_t, 2, 4> expected_result0{10, 12, 14, 16, 26, 28, 30, 32}; Tensor<int32_t, 2, 4> result0 = mhlo::reduce_window<Tensor<int32_t, 2, 4>>( t0, c0, {2, 2}, {2, 2}, {1, 1}, {1, 1}, {0, 0, 0, 0}, max); EXPECT_THAT(result0, Pointwise(Eq(), expected_result0)); Tensor<int32_t, 3, 7> expected_result1{10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22, 23, 24, 26, 27, 28, 29, 30, 31, 32}; Tensor<int32_t, 3, 7> result1 = mhlo::reduce_window<Tensor<int32_t, 3, 7>>( t0, c0, {2, 2}, {1, 1}, {1, 1}, {1, 1}, {0, 0, 0, 0}, max); EXPECT_THAT(result1, Pointwise(Eq(), expected_result1)); auto min = [](Tensor<float> a, Tensor<float> b) { return mhlo::min(a, b); }; Tensor<float> c1{std::numeric_limits<float>::max()}; Tensor<float, 5> t1{10000.0f, 1000.0f, 100.0f, 10.0f, 1.0f}; Tensor<float, 2> expected_result2{100.0f, 1.0f}; Tensor<float, 2> result2 = mhlo::reduce_window<Tensor<float, 2>>( t1, c1, {3}, {2}, {1}, {1}, {0, 0}, min); EXPECT_THAT(result2, Pointwise(Eq(), expected_result2)); Tensor<float, 3> expected_result3{1000.0f, 10.0f, 1.0f}; Tensor<float, 3> result3 = mhlo::reduce_window<Tensor<float, 3>>( t1, c1, {3}, {2}, {1}, {1}, {1, 1}, min); EXPECT_THAT(result3, Pointwise(Eq(), expected_result3)); } TEST(mhlo, select) { EXPECT_EQ(-1, mhlo::select(true, -1, 3)); EXPECT_EQ(3, mhlo::select(false, -1, 3)); Tensor0D<int> s0{-3}; Tensor0D<int> t0{8}; Tensor0D<bool> p0{true}; auto lambda_0d = [&p0, &s0, &t0]() -> Tensor0D<int> { return mhlo::select<Tensor0D<int>>(p0, s0, t0); }; EXPECT_THAT(lambda_0d(), Pointwise(Eq(), {-3})); Tensor1D<float, 2> s1{-1.3f, 2.4f}; Tensor1D<float, 2> t1{0.2f, -3.7f}; Tensor1D<bool, 2> p1{true, false}; auto lambda_1d = [&p1, &s1, &t1]() -> Tensor1D<float, 2> { return mhlo::select<Tensor1D<float, 2>>(p1, s1, t1); }; EXPECT_THAT(lambda_1d(), Pointwise(FloatEq(), {-1.3f, -3.7f})); Tensor2D<long, 2, 2> s2{3, 1, 4, 9}; Tensor2D<long, 2, 2> t2{-2, 8, 6, -10}; Tensor2D<bool, 2, 2> p2{false, true, true, false}; auto lambda_2d = [&p2, &s2, &t2]() -> Tensor2D<long, 2, 2> { return mhlo::select<Tensor2D<long, 2, 2>>(p2, s2, t2); }; EXPECT_THAT(lambda_2d(), Pointwise(Eq(), {-2, 1, 4, -10})); } } // namespace
35.401159
127
0.569028
[ "3d" ]
d0e41c55d83025696b941488e14a3e06bbc91706
6,936
cpp
C++
vehicle/OVMS.V3/components/dbc/src/dbc_app.cpp
mmezog/Open-Vehicle-Monitoring-System-3
ed7e6288708e6f24f3e1148d6320f1c5e7023346
[ "MIT" ]
1
2018-10-21T14:32:14.000Z
2018-10-21T14:32:14.000Z
vehicle/OVMS.V3/components/dbc/src/dbc_app.cpp
mmezog/Open-Vehicle-Monitoring-System-3
ed7e6288708e6f24f3e1148d6320f1c5e7023346
[ "MIT" ]
null
null
null
vehicle/OVMS.V3/components/dbc/src/dbc_app.cpp
mmezog/Open-Vehicle-Monitoring-System-3
ed7e6288708e6f24f3e1148d6320f1c5e7023346
[ "MIT" ]
null
null
null
/* ; Project: Open Vehicle Monitor System ; Date: 14th March 2017 ; ; Changes: ; 1.0 Initial release ; ; (C) 2011 Michael Stegen / Stegen Electronics ; (C) 2011-2017 Mark Webb-Johnson ; (C) 2011 Sonny Chen @ EPRO/DX ; ; 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 "ovms_log.h" static const char *TAG = "dbc-app"; #include <algorithm> #include <list> #include <vector> #include "dbc.h" #include "dbc_app.h" #include "ovms_config.h" dbc MyDBC __attribute__ ((init_priority (4510))); void dbc_list(int verbosity, OvmsWriter* writer, OvmsCommand* cmd, int argc, const char* const* argv) { OvmsMutexLock ldbc(&MyDBC.m_mutex); dbcLoadedFiles_t::iterator it=MyDBC.m_dbclist.begin(); while (it!=MyDBC.m_dbclist.end()) { writer->printf("%s: ",it->first.c_str()); //dbcfile* dbcf = it->second; //dbcf->ShowStatusLine(writer); writer->puts(""); ++it; } } void dbc_load(int verbosity, OvmsWriter* writer, OvmsCommand* cmd, int argc, const char* const* argv) { if (MyDBC.LoadFile(argv[0],argv[1])) { writer->printf("Loaded DBC %s ok\n",argv[0]); } else { writer->printf("Error: Failed to load DBC %s from %s\n",argv[0],argv[1]); } } void dbc_unload(int verbosity, OvmsWriter* writer, OvmsCommand* cmd, int argc, const char* const* argv) { if (MyDBC.Unload(argv[0])) { writer->printf("Unloaded DBC %s ok\n",argv[0]); } else { writer->printf("Error: Failed to unload DBC %s\n",argv[0]); } } void dbc_show(int verbosity, OvmsWriter* writer, OvmsCommand* cmd, int argc, const char* const* argv) { dbcfile* dbc = MyDBC.Find(argv[0]); if (dbc == NULL) { writer->printf("Cannot find DBD file: %s",argv[0]); return; } writer->printf("DBC: %s (version %s)\n",argv[0],dbc->m_version.c_str()); if (!dbc->m_path.empty()) writer->printf("Source: %s\n",dbc->m_path.c_str()); for (std::string c : dbc->m_comments.m_entrymap) writer->puts(c.c_str()); writer->puts(""); if (argc==1) { writer->printf("Nodes:"); for (dbcNode* n : dbc->m_nodes.m_entrymap) { writer->printf(" %s",n->m_name.c_str()); } writer->puts(""); writer->printf("Messages:\n"); dbcMessageEntry_t::iterator it=dbc->m_messages.m_entrymap.begin(); while (it!=dbc->m_messages.m_entrymap.end()) { writer->printf(" 0x%x (%d): %s\n", it->first, it->first, it->second->m_name.c_str()); ++it; } } else if (argc==2) { dbcMessage* m = dbc->m_messages.FindMessage(atoi(argv[1])); if (m==NULL) { writer->printf("Error: No message id #%s\n",argv[1]); return; } writer->printf("Message: 0x%x (%d): %s (%d byte(s) from %s)\n", m->m_id, m->m_id, m->m_name.c_str(), m->m_size, m->m_transmitter_node.c_str()); for (std::string c : m->m_comments) writer->puts(c.c_str()); for (dbcSignal* s : m->m_signals) { writer->printf(" %s %d|%d@%d%c (%g,%g) [%g|%g]\n", s->m_name.c_str(), s->m_start_bit, s->m_signal_size, s->m_byte_order, s->m_value_type, s->m_factor, s->m_offset, s->m_minimum, s->m_maximum); } } else if (argc==3) { dbcMessage* m = dbc->m_messages.FindMessage(atoi(argv[1])); if (m==NULL) { writer->printf("Error: No message id #%s\n",argv[1]); return; } dbcSignal* s = m->FindSignal(argv[2]); if (s==NULL) { writer->printf("Error: No signal %s on message id #%s\n",argv[2],argv[1]); return; } writer->printf("Message: 0x%x (%d): %s (%d byte(s) from %s)\n", m->m_id, m->m_id, m->m_name.c_str(), m->m_size, m->m_transmitter_node.c_str()); for (std::string c : m->m_comments) writer->puts(c.c_str()); writer->printf("Signal: %s %d|%d@%d%c (%g,%g) [%g|%g]\n", s->m_name.c_str(), s->m_start_bit, s->m_signal_size, s->m_byte_order, s->m_value_type, s->m_factor, s->m_offset, s->m_minimum, s->m_maximum); for (std::string c : s->m_comments) writer->puts(c.c_str()); writer->printf("Receivers:"); for (std::string r : s->m_receivers) { writer->printf(" %s",r.c_str()); } writer->puts(""); writer->printf("Values (%s):\n",s->m_values.m_name.c_str()); dbcValueTableEntry_t::iterator it=s->m_values.m_entrymap.begin(); while (it!=s->m_values.m_entrymap.end()) { writer->printf(" %d: %s\n", it->first, it->second.c_str()); ++it; } writer->puts("\n"); for (std::string c : s->m_comments) { writer->puts(c.c_str()); } } } dbc::dbc() { ESP_LOGI(TAG, "Initialising DBC (4510)"); OvmsCommand* cmd_dbc = MyCommandApp.RegisterCommand("dbc","DBC framework",NULL, "", 0, 0, true); cmd_dbc->RegisterCommand("list", "List DBC status", dbc_list, "", 0, 0, true); cmd_dbc->RegisterCommand("load", "Load DBC file", dbc_load, "<name> <path>", 2, 2, true); cmd_dbc->RegisterCommand("unload", "Unload DBC file", dbc_unload, "<name>", 1, 1, true); cmd_dbc->RegisterCommand("show", "Show DBC file", dbc_show, "<name>", 1, 3, true); } dbc::~dbc() { } bool dbc::LoadFile(const char* name, const char* path) { OvmsMutexLock ldbc(&m_mutex); dbcfile* ndbc = new dbcfile(); if (!ndbc->LoadFile(path)) { // delete ndbc; // return false; } auto k = m_dbclist.find(name); if (k == m_dbclist.end()) { // Create a new entry... m_dbclist[name] = ndbc; } else { // Replace it inline... delete k->second; m_dbclist[name] = ndbc; } return true; } bool dbc::Unload(const char* name) { OvmsMutexLock ldbc(&m_mutex); return false; } dbcfile* dbc::Find(const char* name) { OvmsMutexLock ldbc(&m_mutex); auto k = m_dbclist.find(name); if (k == m_dbclist.end()) return NULL; else return k->second; }
29.142857
103
0.612313
[ "vector" ]
d0e8e393e128ef2405b96319483ae42a9cdfc4a2
443
cpp
C++
Cplus/PowerfulIntegers.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
1
2018-01-22T12:06:28.000Z
2018-01-22T12:06:28.000Z
Cplus/PowerfulIntegers.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
Cplus/PowerfulIntegers.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
#include <algorithm> #include <unordered_set> #include <vector> using namespace std; class Solution { public: vector<int> powerfulIntegers(int x, int y, int bound) { unordered_set<int> res; for (int i = 1; i <= bound; i *= x) { for (int j = 1; j <= bound; j *= y) { if (i + j <= bound) res.insert(i + j); if (y == 1) break; } if (x == 1) break; } return vector<int>(res.begin(), res.end()); } };
17.038462
54
0.55079
[ "vector" ]
d0ec7dae3763167c38aa78f1af90a3cfd3881c05
6,757
cpp
C++
gamelift/src/gamelift.cpp
samuel-strangequest/defold-gamelift
32db4d1cab1539712f30d24fdde1d809532f74f8
[ "MIT" ]
null
null
null
gamelift/src/gamelift.cpp
samuel-strangequest/defold-gamelift
32db4d1cab1539712f30d24fdde1d809532f74f8
[ "MIT" ]
null
null
null
gamelift/src/gamelift.cpp
samuel-strangequest/defold-gamelift
32db4d1cab1539712f30d24fdde1d809532f74f8
[ "MIT" ]
null
null
null
// Extension lib defines #define LIB_NAME "Gamelift" #define MODULE_NAME "gamelift" #define DLIB_LOG_DOMAIN "Gamelift" #define GAMELIFT_USE_STD 1 #include <dmsdk/sdk.h> #include <aws/gamelift/server/GameLiftServerAPI.h> #include "gamelift.h" #include "luautils.h" #include <stdlib.h> #include <string.h> void GameLift_OnStartGameSession(Aws::GameLift::Server::Model::GameSession myGameSession) { dmLogInfo("GameLift_OnStartGameSession"); lua_State* L = g_GameLift.m_OnStartGameSessionListener.m_L; int top = lua_gettop(L); lua_pushlistener(L, g_GameLift.m_OnStartGameSessionListener); lua_createtable(L, 0, 7); lua_pushtablestringstring(L, "name", myGameSession.GetName().c_str()); lua_pushtablestringstring(L, "game_session_id", myGameSession.GetGameSessionId().c_str()); lua_pushtablestringnumber(L, "maximum_player_session_count", myGameSession.GetMaximumPlayerSessionCount()); lua_pushtablestringstring(L, "ip_address", myGameSession.GetIpAddress().c_str()); lua_pushtablestringnumber(L, "port", myGameSession.GetPort()); lua_pushtablestringstring(L, "fleet_id", myGameSession.GetFleetId().c_str()); size_t size = myGameSession.GetGameProperties().size(); lua_createtable(L, 0, size); for(int i=0; i < size; i++) { const Aws::GameLift::Server::Model::GameProperty property = myGameSession.GetGameProperties().at(i); lua_pushtablestringstring(L, property.GetKey().c_str(), property.GetValue().c_str()); } lua_setfield(L, -2, "game_properties"); int ret = lua_pcall(L, 2, 0, 0); if (ret != 0) { dmLogError("Error while invoking start game session callback: %s", lua_tostring(L, -1)); lua_pop(L, 1); // pop error message } assert(top == lua_gettop(L)); } void GameLift_OnProcessTerminate() { dmLogInfo("GameLift_OnProcessTerminate"); lua_State* L = g_GameLift.m_OnProcessTerminateListener.m_L; int top = lua_gettop(L); lua_pushlistener(L, g_GameLift.m_OnProcessTerminateListener); int ret = lua_pcall(L, 1, 0, 0); if (ret != 0) { dmLogError("Error while invoking process terminate callback: %s", lua_tostring(L, -1)); lua_pop(L, 1); // pop error message } assert(top == lua_gettop(L)); } bool GameLift_OnHealthCheck() { dmLogInfo("GameLift_OnHealthCheck"); lua_State* L = g_GameLift.m_OnHealthCheckListener.m_L; int top = lua_gettop(L); lua_pushlistener(L, g_GameLift.m_OnHealthCheckListener); int health = 0; int ret = lua_pcall(L, 1, 1, 0); if (ret != 0) { dmLogError("Error while invoking health check callback: %s", lua_tostring(L, -1)); lua_pop(L, 1); // pop error message } else { health = lua_toboolean(L, 1); } lua_pop(L, 1); // pop health check boolean assert(top == lua_gettop(L)); return health; } static int InitGamelift(lua_State* L) { dmLogInfo("InitGameLift"); int top = lua_gettop(L); g_GameLift.m_Port = luaL_checknumber(L, 1); luaL_checklistener(L, 2, g_GameLift.m_OnStartGameSessionListener); luaL_checklistener(L, 3, g_GameLift.m_OnProcessTerminateListener); luaL_checklistener(L, 4, g_GameLift.m_OnHealthCheckListener); dmLogInfo("InitGameLift %d", g_GameLift.m_Port); auto initOutcome = Aws::GameLift::Server::InitSDK(); if (!initOutcome.IsSuccess()) { dmLogError("Unable to initialize GameLift SDK %s", initOutcome.GetError().GetErrorMessage().c_str()); lua_pushboolean(L, 0); lua_pushstring(L, initOutcome.GetError().GetErrorMessage().c_str()); assert(top + 2 == lua_gettop(L)); return false; } auto processReadyParameter = Aws::GameLift::Server::ProcessParameters( std::bind(&GameLift_OnStartGameSession, std::placeholders::_1), std::bind(&GameLift_OnProcessTerminate), std::bind(&GameLift_OnHealthCheck), g_GameLift.m_Port, Aws::GameLift::Server::LogParameters() ); auto readyOutcome = Aws::GameLift::Server::ProcessReady(processReadyParameter); if (!readyOutcome.IsSuccess()) { dmLogError("Unable to initialize GameLift SDK %s", readyOutcome.GetError().GetErrorMessage().c_str()); lua_pushboolean(L, 0); lua_pushstring(L, initOutcome.GetError().GetErrorMessage().c_str()); assert(top + 2 == lua_gettop(L)); return false; } lua_pushboolean(L, 1); dmLogInfo("InitGameLift - end"); assert(top + 1 == lua_gettop(L)); return 0; } static int ActivateGameSession(lua_State* L) { int top = lua_gettop(L); Aws::GameLift::Server::ActivateGameSession(); assert(top == lua_gettop(L)); return 0; } static int TerminateGameSession(lua_State* L) { int top = lua_gettop(L); Aws::GameLift::Server::TerminateGameSession(); assert(top == lua_gettop(L)); return 0; } static int ProcessEnding(lua_State* L) { int top = lua_gettop(L); Aws::GameLift::Server::ProcessEnding(); assert(top == lua_gettop(L)); return 0; } static int RemovePlayerSession(lua_State* L) { int top = lua_gettop(L); const char* playerSessionId = luaL_checkstring(L, 1); Aws::GameLift::Server::RemovePlayerSession(playerSessionId); assert(top == lua_gettop(L)); return 0; } static int AcceptPlayerSession(lua_State* L) { int top = lua_gettop(L); const char* playerSessionId = luaL_checkstring(L, 1); auto outcome = Aws::GameLift::Server::AcceptPlayerSession(playerSessionId); if (!outcome.IsSuccess()) { lua_pushboolean(L, 0); lua_pushstring(L, outcome.GetError().GetErrorMessage().c_str()); assert(top + 2 == lua_gettop(L)); return 2; } lua_pushboolean(L, 1); assert(top + 1 == lua_gettop(L)); return 1; } // Functions exposed to Lua static const luaL_reg Module_methods[] = { {"init", InitGamelift}, {"activate_game_session", ActivateGameSession}, {"terminate_game_session", TerminateGameSession}, {"process_ending", ProcessEnding}, {"remove_player_session", RemovePlayerSession}, {"accept_player_session", AcceptPlayerSession}, {0, 0} }; static void LuaInit(lua_State* L) { int top = lua_gettop(L); // Register lua names luaL_register(L, MODULE_NAME, Module_methods); lua_pop(L, 1); assert(top == lua_gettop(L)); } dmExtension::Result AppInitializeGameliftExtension(dmExtension::AppParams* params) { return dmExtension::RESULT_OK; } dmExtension::Result InitializeGameliftExtension(dmExtension::Params* params) { // Init Lua LuaInit(params->m_L); printf("Registered %s Extension\n", MODULE_NAME); return dmExtension::RESULT_OK; } dmExtension::Result AppFinalizeGameliftExtension(dmExtension::AppParams* params) { return dmExtension::RESULT_OK; } dmExtension::Result FinalizeGameliftExtension(dmExtension::Params* params) { return dmExtension::RESULT_OK; } // Defold SDK uses a macro for setting up extension entry points: // // DM_DECLARE_EXTENSION(symbol, name, app_init, app_final, init, update, on_event, final) DM_DECLARE_EXTENSION(Gamelift, LIB_NAME, AppInitializeGameliftExtension, AppFinalizeGameliftExtension, InitializeGameliftExtension, 0, 0, FinalizeGameliftExtension)
31.282407
164
0.745153
[ "model" ]
d0f10fa6c194f62bdde5c130fd9acd0cb8600460
4,364
cpp
C++
src/FastRoute/src/SteinerTree.cpp
ax3ghazy/OpenROAD
2d41acd184d2fb5c551fbdb1f74bbe73a782de6f
[ "BSD-3-Clause-Clear" ]
null
null
null
src/FastRoute/src/SteinerTree.cpp
ax3ghazy/OpenROAD
2d41acd184d2fb5c551fbdb1f74bbe73a782de6f
[ "BSD-3-Clause-Clear" ]
null
null
null
src/FastRoute/src/SteinerTree.cpp
ax3ghazy/OpenROAD
2d41acd184d2fb5c551fbdb1f74bbe73a782de6f
[ "BSD-3-Clause-Clear" ]
null
null
null
///////////////////////////////////////////////////////////////////////////// // // BSD 3-Clause License // // Copyright (c) 2019, University of California, San Diego. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "SteinerTree.h" #include <vector> namespace FastRoute { void SteinerTree::printSegments() { for (Segment seg : _segments) { Node node1 = seg.getFirstNode(); Node node2 = seg.getLastNode(); std::cout << "(" << nodeTypeString(node1.getType()) << " " << node1.getPosition().getX() << ", " << node1.getPosition().getY() << ", " << node1.getLayer() << "); (" << nodeTypeString(node2.getType()) << " " << node2.getPosition().getX() << ", " << node2.getPosition().getY() << ", " << node2.getLayer() << ")\n"; } } void SteinerTree::addNode(Node node) { if (!nodeExists(node)) { _nodes.push_back(node); } else if (node.getType() == NodeType::SOURCE) { for (Node& n : _nodes) { if (n == node) { n.setType(NodeType::SOURCE); } } } } void SteinerTree::addSegment(Segment segment) { for (Segment seg : _segments) { if ((seg.getFirstNode() == segment.getFirstNode() && seg.getLastNode() == segment.getLastNode()) || (seg.getFirstNode() == segment.getLastNode() && seg.getLastNode() == segment.getFirstNode())) { return; } } _segments.push_back(segment); } bool SteinerTree::nodeExists(Node node) { for (Node n : _nodes) { if (n == node) { return true; } } return false; } bool SteinerTree::getNodeIfExists(Node node, Node& requestedNode) { for (Node n : _nodes) { if (n == node) { requestedNode = n; return true; } } return false; } std::vector<Segment> SteinerTree::getNodeSegments(Node node) { std::vector<Segment> nodeSegments; for (Segment seg : _segments) { if (seg.getFirstNode() == node || seg.getLastNode() == node) { nodeSegments.push_back(seg); } } return nodeSegments; } Node SteinerTree::getSource() { Node source; bool found = false; for (Node node : _nodes) { if (node.getType() == NodeType::SOURCE) { source = node; found = true; } } if (!found) { std::cout << "[ERROR] Source not found\n"; std::exit(0); } return source; } std::vector<Node> SteinerTree::getSinks() { std::vector<Node> sinks; for (Node node : _nodes) { if (node.getType() == NodeType::SINK) { sinks.push_back(node); } } return sinks; } Segment SteinerTree::getSegmentByIndex(int index) { Segment idxSeg; for (Segment seg : _segments) { if (seg.getIndex() == index) { idxSeg = seg; break; } } return idxSeg; } } // namespace FastRoute
26.609756
80
0.622365
[ "vector" ]
d0f4e5f4d3670409518983a9e1e4304c1a36f0ef
25,183
cpp
C++
ColliderBit/src/ColliderBit_Higgs.cpp
GambitBSM/gambit_2.0
a4742ac94a0352585a3b9dcb9b222048a5959b91
[ "Unlicense" ]
1
2021-09-17T22:53:26.000Z
2021-09-17T22:53:26.000Z
ColliderBit/src/ColliderBit_Higgs.cpp
GambitBSM/gambit_2.0
a4742ac94a0352585a3b9dcb9b222048a5959b91
[ "Unlicense" ]
3
2021-07-22T11:23:48.000Z
2021-08-22T17:24:41.000Z
ColliderBit/src/ColliderBit_Higgs.cpp
GambitBSM/gambit_2.0
a4742ac94a0352585a3b9dcb9b222048a5959b91
[ "Unlicense" ]
1
2021-08-14T10:31:41.000Z
2021-08-14T10:31:41.000Z
// GAMBIT: Global and Modular BSM Inference Tool // ********************************************* /// \file /// /// Functions of ColliderBit that deal exclusively with Higgs physics /// some functions were originally in CollderBit.cpp /// /// ********************************************* /// /// Authors (add name and date if you modify): /// /// \author Chris Rogan /// (crogan@cern.ch) /// \date 2014 Aug /// \date 2015 May /// /// \author Pat Scott /// (p.scott@imperial.ac.uk) /// \date 2015 Jul /// \date 2016 Sep /// /// \author James McKay /// (j.mckay14@imperial.ac.uk) /// \date 2016 Sep /// /// \author Sanjay Bloor /// (sanjay.bloor12@imperial.ac.uk) /// \date 2020 Mar /// /// \author Tomas Gonzalo /// (tomas.gonzalo@monash.edu) /// \date 2020 Mar /// /// ********************************************* #include <cmath> #include <string> #include <iostream> #include <fstream> #include <memory> #include <numeric> #include <sstream> #include <vector> #include "gambit/Elements/gambit_module_headers.hpp" #include "gambit/Utils/util_types.hpp" #include "gambit/ColliderBit/ColliderBit_rollcall.hpp" //#define COLLIDERBIT_DEBUG namespace Gambit { namespace ColliderBit { /// Helper function to set HiggsBounds/Signals parameters cross-section ratios from a GAMBIT HiggsCouplingsTable void set_CS(hb_ModelParameters &result, const HiggsCouplingsTable& couplings, int n_neutral_higgses) { for(int i = 0; i < n_neutral_higgses; i++) { result.CS_bg_hjb_ratio[i] = couplings.C_bb2[i]; result.CS_bb_hj_ratio[i] = couplings.C_bb2[i]; result.CS_lep_bbhj_ratio[i] = couplings.C_bb2[i]; result.CS_lep_tautauhj_ratio[i] = couplings.C_tautau2[i]; result.CS_lep_hjZ_ratio[i] = couplings.C_ZZ2[i]; result.CS_gg_hjZ_ratio[i] = 0.; result.CS_dd_hjZ_ratio[i] = couplings.C_ZZ2[i]; result.CS_uu_hjZ_ratio[i] = couplings.C_ZZ2[i]; result.CS_ss_hjZ_ratio[i] = couplings.C_ZZ2[i]; result.CS_cc_hjZ_ratio[i] = couplings.C_ZZ2[i]; result.CS_bb_hjZ_ratio[i] = couplings.C_ZZ2[i]; result.CS_ud_hjWp_ratio[i] = couplings.C_WW2[i]; result.CS_cs_hjWp_ratio[i] = couplings.C_WW2[i]; result.CS_ud_hjWm_ratio[i] = couplings.C_WW2[i]; result.CS_cs_hjWm_ratio[i] = couplings.C_WW2[i]; result.CS_tev_vbf_ratio[i] = couplings.C_WW2[i]; result.CS_lhc7_vbf_ratio[i] = couplings.C_WW2[i]; result.CS_lhc8_vbf_ratio[i] = couplings.C_WW2[i]; result.CS_gg_hj_ratio[i] = couplings.C_gg2[i]; result.CS_tev_tthj_ratio[i] = couplings.C_tt2[i]; result.CS_lhc7_tthj_ratio[i] = couplings.C_tt2[i]; result.CS_lhc8_tthj_ratio[i] = couplings.C_tt2[i]; for(int j = 0; j < n_neutral_higgses; j++) { result.CS_lep_hjhi_ratio[i][j] = couplings.C_hiZ2[i][j]; } } // LEP H+ H- x-section ratio result.CS_lep_HpjHmi_ratio[0] = 1.; } /// Helper function for populating a HiggsBounds/Signals ModelParameters object for SM-like Higgs. void set_SMLikeHiggs_ModelParameters(const SubSpectrum& spec, const HiggsCouplingsTable& couplings, hb_ModelParameters &result) { // Retrieve the decays const DecayTable::Entry& decays = couplings.get_neutral_decays(0); // Set the CP of the lone higgs result.CP[0] = couplings.CP[0]; // Set h mass and uncertainty result.Mh[0] = spec.get(Par::Pole_Mass,25,0); bool has_high_err = spec.has(Par::Pole_Mass_1srd_high, 25, 0); bool has_low_err = spec.has(Par::Pole_Mass_1srd_low, 25, 0); if (has_high_err and has_low_err) { double upper = spec.get(Par::Pole_Mass_1srd_high, 25, 0); double lower = spec.get(Par::Pole_Mass_1srd_low, 25, 0); result.deltaMh[0] = result.Mh[0] * std::max(upper,lower); } else { result.deltaMh[0] = 0.; } // Set the total h width result.hGammaTot[0] = decays.width_in_GeV; // Set the branching fractions result.BR_hjss[0] = decays.BF("s", "sbar"); result.BR_hjcc[0] = decays.BF("c", "cbar"); result.BR_hjbb[0] = decays.BF("b", "bbar"); result.BR_hjmumu[0] = decays.BF("mu+", "mu-"); result.BR_hjtautau[0] = decays.BF("tau+", "tau-"); result.BR_hjWW[0] = decays.BF("W+", "W-"); result.BR_hjZZ[0] = decays.BF("Z0", "Z0"); result.BR_hjZga[0] = decays.BF("gamma", "Z0"); result.BR_hjgaga[0] = decays.BF("gamma", "gamma"); result.BR_hjgg[0] = decays.BF("g", "g"); // Add the invisibles result.BR_hjinvisible[0] = 0.; for (std::vector<std::pair<str,str>>::const_iterator it = couplings.invisibles.begin(); it != couplings.invisibles.end(); ++it) { result.BR_hjinvisible[0] += decays.BF(it->first, it->second); } // Retrieve cross-section ratios from the HiggsCouplingsTable set_CS(result, couplings, 1); // Zero all heavy neutral higgs masses, widths and effective couplings for(int i = 1; i < 3; i++) { result.Mh[i] = 0.; result.deltaMh[i] = 0.; result.hGammaTot[i] = 0.; result.CP[i] = 0.; result.BR_hjss[i] = 0.; result.BR_hjcc[i] = 0.; result.BR_hjbb[i] = 0.; result.BR_hjmumu[i] = 0.; result.BR_hjtautau[i] = 0.; result.BR_hjWW[i] = 0.; result.BR_hjZZ[i] = 0.; result.BR_hjZga[i] = 0.; result.BR_hjgaga[i] = 0.; result.BR_hjgg[i] = 0.; result.BR_hjinvisible[i] = 0.; result.CS_lep_hjZ_ratio[i] = 0.; result.CS_lep_bbhj_ratio[i] = 0.; result.CS_lep_tautauhj_ratio[i] = 0.; result.CS_gg_hj_ratio[i] = 0.; result.CS_bb_hj_ratio[i] = 0.; result.CS_bg_hjb_ratio[i] = 0.; result.CS_ud_hjWp_ratio[i] = 0.; result.CS_cs_hjWp_ratio[i] = 0.; result.CS_ud_hjWm_ratio[i] = 0.; result.CS_cs_hjWm_ratio[i] = 0.; result.CS_gg_hjZ_ratio[i] = 0.; result.CS_dd_hjZ_ratio[i] = 0.; result.CS_uu_hjZ_ratio[i] = 0.; result.CS_ss_hjZ_ratio[i] = 0.; result.CS_cc_hjZ_ratio[i] = 0.; result.CS_bb_hjZ_ratio[i] = 0.; result.CS_tev_vbf_ratio[i] = 0.; result.CS_tev_tthj_ratio[i] = 0.; result.CS_lhc7_vbf_ratio[i] = 0.; result.CS_lhc7_tthj_ratio[i] = 0.; result.CS_lhc8_vbf_ratio[i] = 0.; result.CS_lhc8_tthj_ratio[i] = 0.; for(int j = 0; j < 3; j++) result.BR_hjhihi[i][j] = 0.; for(int j = 0; j < 3; j++) result.CS_lep_hjhi_ratio[i][j] = 0.; } // Zero all H+ masses, widths and effective couplings result.MHplus[0] = 0.; result.deltaMHplus[0] = 0.; result.HpGammaTot[0] = 0.; result.BR_tWpb = 0.; result.BR_tHpjb[0] = 0.; result.BR_Hpjcs[0] = 0.; result.BR_Hpjcb[0] = 0.; result.BR_Hptaunu[0] = 0.; result.CS_lep_HpjHmi_ratio[0] = 0.; } /// SM-like (SM + possible invisibles) Higgs model parameters for HiggsBounds/Signals void SMLikeHiggs_ModelParameters(hb_ModelParameters &result) { using namespace Pipes::SMLikeHiggs_ModelParameters; dep_bucket<Spectrum>* spectrum_dependency = nullptr; if (ModelInUse("ScalarSingletDM_Z2") or ModelInUse("ScalarSingletDM_Z2_running")) spectrum_dependency = &Dep::ScalarSingletDM_Z2_spectrum; else if (ModelInUse("ScalarSingletDM_Z3") or ModelInUse("ScalarSingletDM_Z3_running")) spectrum_dependency = &Dep::ScalarSingletDM_Z3_spectrum; else if (ModelInUse("StandardModel_Higgs") or ModelInUse("StandardModel_Higgs_running")) spectrum_dependency = &Dep::SM_spectrum; else ColliderBit_error().raise(LOCAL_INFO, "No valid model for SMLikeHiggs_ModelParameters."); const SubSpectrum& spec = (*spectrum_dependency)->get_HE(); set_SMLikeHiggs_ModelParameters(spec, *Dep::Higgs_Couplings, result); } /// MSSM-like (MSSM + NMSSM + ...) Higgs model parameters for HiggsBounds/Signals void MSSMLikeHiggs_ModelParameters(hb_ModelParameters &result) { using namespace Pipes::MSSMLikeHiggs_ModelParameters; // Set up neutral Higgses int n_neutral_higgses = Dep::Higgs_Couplings->get_n_neutral_higgs(); // Set the CP of the Higgs states. for (int i = 0; i < n_neutral_higgses; i++) result.CP[i] = Dep::Higgs_Couplings->CP[i]; // Retrieve higgs partial widths const std::vector<const DecayTable::Entry*>& h0_widths = Dep::Higgs_Couplings->get_neutral_decays_array(); const DecayTable::Entry& H_plus_widths = Dep::Higgs_Couplings->get_charged_decays(0); const DecayTable::Entry& t_widths = Dep::Higgs_Couplings->get_t_decays(); // Pick the correct spectrum and specify the Higgses dep_bucket<Spectrum>* spectrum_dependency; std::vector<str> Higgses; if (ModelInUse("MSSM63atMGUT") or ModelInUse("MSSM63atQ")) { spectrum_dependency = &Dep::MSSM_spectrum; Higgses = initVector<str>("h0_1", "h0_2", "A0"); } else ColliderBit_error().raise(LOCAL_INFO, "No valid model for MSSMLikeHiggs_ModelParameters."); const SubSpectrum& spec = (*spectrum_dependency)->get_HE(); static const std::vector<str> sHneut(Higgses); // Neutral higgs masses and errors for(int i = 0; i < n_neutral_higgses; i++) { result.Mh[i] = spec.get(Par::Pole_Mass,sHneut[i]); double upper = spec.get(Par::Pole_Mass_1srd_high,sHneut[i]); double lower = spec.get(Par::Pole_Mass_1srd_low,sHneut[i]); result.deltaMh[i] = result.Mh[i] * std::max(upper,lower); } // Loop over all neutral Higgses, setting their branching fractions and total widths. for(int i = 0; i < n_neutral_higgses; i++) { result.hGammaTot[i] = h0_widths[i]->width_in_GeV; result.BR_hjss[i] = h0_widths[i]->BF("s", "sbar"); result.BR_hjcc[i] = h0_widths[i]->BF("c", "cbar"); result.BR_hjbb[i] = h0_widths[i]->BF("b", "bbar"); result.BR_hjmumu[i] = h0_widths[i]->BF("mu+", "mu-"); result.BR_hjtautau[i] = h0_widths[i]->BF("tau+", "tau-"); result.BR_hjWW[i] = h0_widths[i]->has_channel("W+", "W-") ? h0_widths[i]->BF("W+", "W-") : 0.0; result.BR_hjZZ[i] = h0_widths[i]->has_channel("Z0", "Z0") ? h0_widths[i]->BF("Z0", "Z0") : 0.0; result.BR_hjZga[i] = h0_widths[i]->has_channel("gamma", "Z0") ? h0_widths[i]->BF("gamma", "Z0") : 0.0; result.BR_hjgaga[i] = h0_widths[i]->BF("gamma", "gamma"); result.BR_hjgg[i] = h0_widths[i]->BF("g", "g"); // Do decays to invisibles result.BR_hjinvisible[i] = 0.; for (std::vector<std::pair<str,str>>::const_iterator it = Dep::Higgs_Couplings->invisibles.begin(); it != Dep::Higgs_Couplings->invisibles.end(); ++it) { result.BR_hjinvisible[i] += h0_widths[i]->BF(it->first, it->second); } // Do decays to other neutral higgses for (int j = 0; j < n_neutral_higgses; j++) { if (2.*result.Mh[j] < result.Mh[i] and h0_widths[i]->has_channel(sHneut[j],sHneut[j])) { result.BR_hjhihi[i][j] = h0_widths[i]->BF(sHneut[j],sHneut[j]); } else { result.BR_hjhihi[i][j] = 0.; } } } // Charged higgs masses and errors result.MHplus[0] = spec.get(Par::Pole_Mass,"H+"); double upper = spec.get(Par::Pole_Mass_1srd_high,"H+"); double lower = spec.get(Par::Pole_Mass_1srd_low,"H+"); result.deltaMHplus[0] = result.MHplus[0] * std::max(upper,lower); // Set charged Higgs branching fractions and total width. result.HpGammaTot[0] = H_plus_widths.width_in_GeV; result.BR_Hpjcs[0] = H_plus_widths.BF("c", "sbar"); result.BR_Hpjcb[0] = H_plus_widths.BF("c", "bbar"); result.BR_Hptaunu[0] = H_plus_widths.BF("tau+", "nu_tau"); // Set top branching fractions result.BR_tWpb = t_widths.BF("W+", "b"); result.BR_tHpjb[0] = t_widths.has_channel("H+", "b") ? t_widths.BF("H+", "b") : 0.0; // Retrieve cross-section ratios from the HiggsCouplingsTable set_CS(result, *Dep::Higgs_Couplings, n_neutral_higgses); } /// Get a LEP chisq from HiggsBounds void calc_HB_LEP_LogLike(double &result) { using namespace Pipes::calc_HB_LEP_LogLike; hb_ModelParameters ModelParam = *Dep::HB_ModelParameters; Farray<double, 1,3, 1,3> CS_lep_hjhi_ratio; Farray<double, 1,3, 1,3> BR_hjhihi; // Transpose to get around Fortran matrix types for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) { CS_lep_hjhi_ratio(i+1,j+1) = ModelParam.CS_lep_hjhi_ratio[i][j]; BR_hjhihi(i+1,j+1) = ModelParam.BR_hjhihi[i][j]; } for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) { ModelParam.CS_lep_hjhi_ratio[j][i] = CS_lep_hjhi_ratio(i+1,j+1); ModelParam.BR_hjhihi[j][i] = BR_hjhihi(i+1,j+1); } BEreq::HiggsBounds_neutral_input_part(&ModelParam.Mh[0], &ModelParam.hGammaTot[0], &ModelParam.CP[0], &ModelParam.CS_lep_hjZ_ratio[0], &ModelParam.CS_lep_bbhj_ratio[0], &ModelParam.CS_lep_tautauhj_ratio[0], &ModelParam.CS_lep_hjhi_ratio[0][0], &ModelParam.CS_gg_hj_ratio[0], &ModelParam.CS_bb_hj_ratio[0], &ModelParam.CS_bg_hjb_ratio[0], &ModelParam.CS_ud_hjWp_ratio[0], &ModelParam.CS_cs_hjWp_ratio[0], &ModelParam.CS_ud_hjWm_ratio[0], &ModelParam.CS_cs_hjWm_ratio[0], &ModelParam.CS_gg_hjZ_ratio[0], &ModelParam.CS_dd_hjZ_ratio[0], &ModelParam.CS_uu_hjZ_ratio[0], &ModelParam.CS_ss_hjZ_ratio[0], &ModelParam.CS_cc_hjZ_ratio[0], &ModelParam.CS_bb_hjZ_ratio[0], &ModelParam.CS_tev_vbf_ratio[0], &ModelParam.CS_tev_tthj_ratio[0], &ModelParam.CS_lhc7_vbf_ratio[0], &ModelParam.CS_lhc7_tthj_ratio[0], &ModelParam.CS_lhc8_vbf_ratio[0], &ModelParam.CS_lhc8_tthj_ratio[0], &ModelParam.BR_hjss[0], &ModelParam.BR_hjcc[0], &ModelParam.BR_hjbb[0], &ModelParam.BR_hjmumu[0], &ModelParam.BR_hjtautau[0], &ModelParam.BR_hjWW[0], &ModelParam.BR_hjZZ[0], &ModelParam.BR_hjZga[0], &ModelParam.BR_hjgaga[0], &ModelParam.BR_hjgg[0], &ModelParam.BR_hjinvisible[0], &ModelParam.BR_hjhihi[0][0]); // Transpose it back for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) { CS_lep_hjhi_ratio(i+1,j+1) = ModelParam.CS_lep_hjhi_ratio[i][j]; BR_hjhihi(i+1,j+1) = ModelParam.BR_hjhihi[i][j]; } for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) { ModelParam.CS_lep_hjhi_ratio[j][i] = CS_lep_hjhi_ratio(i+1,j+1); ModelParam.BR_hjhihi[j][i] = BR_hjhihi(i+1,j+1); } BEreq::HiggsBounds_charged_input(&ModelParam.MHplus[0], &ModelParam.HpGammaTot[0], &ModelParam.CS_lep_HpjHmi_ratio[0], &ModelParam.BR_tWpb, &ModelParam.BR_tHpjb[0], &ModelParam.BR_Hpjcs[0], &ModelParam.BR_Hpjcb[0], &ModelParam.BR_Hptaunu[0]); BEreq::HiggsBounds_set_mass_uncertainties(&ModelParam.deltaMh[0],&ModelParam.deltaMHplus[0]); // run Higgs bounds 'classic' double obsratio; int HBresult, chan, ncombined; BEreq::run_HiggsBounds_classic(HBresult,chan,obsratio,ncombined); // extract the LEP chisq double chisq_withouttheory,chisq_withtheory; int chan2; double theor_unc = 1.5; // theory uncertainty BEreq::HB_calc_stats(theor_unc,chisq_withouttheory,chisq_withtheory,chan2); // Catch HiggsBound's error value, chisq = -999 if( fabs(chisq_withouttheory - (-999.)) < 1e-6) { ColliderBit_warning().raise(LOCAL_INFO, "Got chisq=-999 from HB_calc_stats in HiggsBounds, indicating a cross-section outside tabulated range. Will use chisq=0."); chisq_withouttheory = 0.0; } result = -0.5*chisq_withouttheory; } /// Get an LHC chisq from HiggsSignals void calc_HS_LHC_LogLike(double &result) { using namespace Pipes::calc_HS_LHC_LogLike; hb_ModelParameters ModelParam = *Dep::HB_ModelParameters; Farray<double, 1,3, 1,3> CS_lep_hjhi_ratio; Farray<double, 1,3, 1,3> BR_hjhihi; // Transpose to get around Fortran matrix types for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) { CS_lep_hjhi_ratio(i+1,j+1) = ModelParam.CS_lep_hjhi_ratio[i][j]; BR_hjhihi(i+1,j+1) = ModelParam.BR_hjhihi[i][j]; } for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) { ModelParam.CS_lep_hjhi_ratio[j][i] = CS_lep_hjhi_ratio(i+1,j+1); ModelParam.BR_hjhihi[j][i] = BR_hjhihi(i+1,j+1); } BEreq::HiggsBounds_neutral_input_part_HS(&ModelParam.Mh[0], &ModelParam.hGammaTot[0], &ModelParam.CP[0], &ModelParam.CS_lep_hjZ_ratio[0], &ModelParam.CS_lep_bbhj_ratio[0], &ModelParam.CS_lep_tautauhj_ratio[0], &ModelParam.CS_lep_hjhi_ratio[0][0], &ModelParam.CS_gg_hj_ratio[0], &ModelParam.CS_bb_hj_ratio[0], &ModelParam.CS_bg_hjb_ratio[0], &ModelParam.CS_ud_hjWp_ratio[0], &ModelParam.CS_cs_hjWp_ratio[0], &ModelParam.CS_ud_hjWm_ratio[0], &ModelParam.CS_cs_hjWm_ratio[0], &ModelParam.CS_gg_hjZ_ratio[0], &ModelParam.CS_dd_hjZ_ratio[0], &ModelParam.CS_uu_hjZ_ratio[0], &ModelParam.CS_ss_hjZ_ratio[0], &ModelParam.CS_cc_hjZ_ratio[0], &ModelParam.CS_bb_hjZ_ratio[0], &ModelParam.CS_tev_vbf_ratio[0], &ModelParam.CS_tev_tthj_ratio[0], &ModelParam.CS_lhc7_vbf_ratio[0], &ModelParam.CS_lhc7_tthj_ratio[0], &ModelParam.CS_lhc8_vbf_ratio[0], &ModelParam.CS_lhc8_tthj_ratio[0], &ModelParam.BR_hjss[0], &ModelParam.BR_hjcc[0], &ModelParam.BR_hjbb[0], &ModelParam.BR_hjmumu[0], &ModelParam.BR_hjtautau[0], &ModelParam.BR_hjWW[0], &ModelParam.BR_hjZZ[0], &ModelParam.BR_hjZga[0], &ModelParam.BR_hjgaga[0], &ModelParam.BR_hjgg[0], &ModelParam.BR_hjinvisible[0], &ModelParam.BR_hjhihi[0][0]); // Transpose it back for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) { CS_lep_hjhi_ratio(i+1,j+1) = ModelParam.CS_lep_hjhi_ratio[i][j]; BR_hjhihi(i+1,j+1) = ModelParam.BR_hjhihi[i][j]; } for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) { ModelParam.CS_lep_hjhi_ratio[j][i] = CS_lep_hjhi_ratio(i+1,j+1); ModelParam.BR_hjhihi[j][i] = BR_hjhihi(i+1,j+1); } BEreq::HiggsBounds_charged_input_HS(&ModelParam.MHplus[0], &ModelParam.HpGammaTot[0], &ModelParam.CS_lep_HpjHmi_ratio[0], &ModelParam.BR_tWpb, &ModelParam.BR_tHpjb[0], &ModelParam.BR_Hpjcs[0], &ModelParam.BR_Hpjcb[0], &ModelParam.BR_Hptaunu[0]); BEreq::HiggsSignals_neutral_input_MassUncertainty(&ModelParam.deltaMh[0]); // add uncertainties to cross-sections and branching ratios // double dCS[5] = {0.,0.,0.,0.,0.}; // double dBR[5] = {0.,0.,0.,0.,0.}; // BEreq::setup_rate_uncertainties(dCS,dBR); // run HiggsSignals int mode = 1; // 1- peak-centered chi2 method (recommended) double csqmu, csqmh, csqtot, Pvalue; int nobs; BEreq::run_HiggsSignals(mode, csqmu, csqmh, csqtot, nobs, Pvalue); result = -0.5*csqtot; #ifdef COLLIDERBIT_DEBUG std::ofstream f; f.open ("HB_ModelParameters_contents.dat"); f<<"LHC log-likleihood"; for (int i = 0; i < 3; i++) f<< " higgs index" << " "<<i<<":CP"<< " "<<i<<":Mh"<< " "<<i<<":hGammaTot"<< " "<<i<<":CS_lep_hjZ_ratio"<< " "<<i<<":CS_tev_vbf_ratio"<< " "<<i<<":CS_lep_bbhj_ratio"<< " "<<i<<":CS_lep_tautauhj_ratio"<< " "<<i<<":CS_gg_hj_ratio"<< " "<<i<<":CS_tev_tthj_ratio"<< " "<<i<<":CS_lhc7_tthj_ratio"<< " "<<i<<":CS_lhc8_tthj_ratio"<< " "<<i<<":CS_lep_hjhi_ratio[0]"<< " "<<i<<":CS_lep_hjhi_ratio[1]"<< " "<<i<<":CS_lep_hjhi_ratio[2]"<< " "<<i<<":BR_ss"<< " "<<i<<":BR_cc"<< " "<<i<<":BR_bb"<< " "<<i<<":BR_mumu"<< " "<<i<<":BR_tautau"<< " "<<i<<":BR_WW"<< " "<<i<<":BR_ZZ"<< " "<<i<<":BR_Zga"<< " "<<i<<":BR_gamgam"<< " "<<i<<":BR_gg"<< " "<<i<<":BR_invisible"<< " "<<i<<":BR_hihi[0]"<< " "<<i<<":BR_hihi[1]"<< " "<<i<<":BR_hihi[2]"; f<< " higgs index" << " "<<4<<"MHplus"<< " "<<4<<":HpGammaTot"<< " "<<4<<":CS_lep_HpjHmi_ratio"<< " "<<4<<":BR_H+->cs"<< " "<<4<<":BR_H+->cb"<< " "<<4<<":BR_H+->taunu"<< " "<<4<<":BR_t->W+b"<< " "<<4<<":BR_t->H+b"; f << endl << std::setw(18) << result; const int w = 24; for (int i = 0; i < 3; i++) { f << std::setw(w) << i << std::setw(w) << ModelParam.CP[i] << std::setw(w) << ModelParam.Mh[i] << std::setw(w) << ModelParam.hGammaTot[i] << std::setw(w) << ModelParam.CS_lep_hjZ_ratio[i] << std::setw(w) << ModelParam.CS_tev_vbf_ratio[i] << std::setw(w) << ModelParam.CS_lep_bbhj_ratio[i] << std::setw(w) << ModelParam.CS_lep_tautauhj_ratio[i] << std::setw(w) << ModelParam.CS_gg_hj_ratio[i] << std::setw(w) << ModelParam.CS_tev_tthj_ratio[i] << std::setw(w) << ModelParam.CS_lhc7_tthj_ratio[i] << std::setw(w) << ModelParam.CS_lhc8_tthj_ratio[i]; for (int j = 0; j < 3; j++) f << std::setw(w) << ModelParam.CS_lep_hjhi_ratio[i][j]; f << std::setw(w) << ModelParam.BR_hjss[i] << std::setw(w) << ModelParam.BR_hjcc[i] << std::setw(w) << ModelParam.BR_hjbb[i] << std::setw(w) << ModelParam.BR_hjmumu[i] << std::setw(w) << ModelParam.BR_hjtautau[i] << std::setw(w) << ModelParam.BR_hjWW[i] << std::setw(w) << ModelParam.BR_hjZZ[i] << std::setw(w) << ModelParam.BR_hjZga[i] << std::setw(w) << ModelParam.BR_hjgaga[i] << std::setw(w) << ModelParam.BR_hjgg[i] << std::setw(w) << ModelParam.BR_hjinvisible[i]; for (int j = 0; j < 3; j++) f << std::setw(w) << ModelParam.BR_hjhihi[i][j]; } f << std::setw(w) << 4 << std::setw(w) << ModelParam.MHplus[0] << std::setw(w) << ModelParam.HpGammaTot[0] << std::setw(w) << ModelParam.CS_lep_HpjHmi_ratio[0] << std::setw(w) << ModelParam.BR_Hpjcs[0] << std::setw(w) << ModelParam.BR_Hpjcb[0] << std::setw(w) << ModelParam.BR_Hptaunu[0] << std::setw(w) << ModelParam.BR_tWpb << std::setw(w) << ModelParam.BR_tHpjb[0]; f.close(); #endif } /// Higgs production cross-sections from FeynHiggs. void FH_HiggsProd(fh_HiggsProd &result) { using namespace Pipes::FH_HiggsProd; Farray<fh_real, 1,52> prodxs; fh_HiggsProd HiggsProd; int error; fh_real sqrts; // Tevatron sqrts = 2.; error = 1; BEreq::FHHiggsProd(error, sqrts, prodxs); if (error != 0) { std::ostringstream err; err << "BEreq::FHHiggsProd raised error flag for Tevatron: " << error << "."; invalid_point().raise(err.str()); } for(int i = 0; i < 52; i++) HiggsProd.prodxs_Tev[i] = prodxs(i+1); // LHC7 sqrts = 7.; error = 1; BEreq::FHHiggsProd(error, sqrts, prodxs); if (error != 0) { std::ostringstream err; err << "BEreq::FHHiggsProd raised error flag for LHC7: " << error << "."; invalid_point().raise(err.str()); } for(int i = 0; i < 52; i++) HiggsProd.prodxs_LHC7[i] = prodxs(i+1); // LHC8 sqrts = 8.; error = 1; BEreq::FHHiggsProd(error, sqrts, prodxs); if (error != 0) { std::ostringstream err; err << "BEreq::FHHiggsProd raised error flag for LHC8: " << error << "."; invalid_point().raise(err.str()); } for(int i = 0; i < 52; i++) HiggsProd.prodxs_LHC8[i] = prodxs(i+1); // The ttbar production cross-sections for the (BSM,SM) model can be found at (prodxs_X[h+27], prodxs_X[h+30]), // where h is the higgs index (0 = h0_1, 1 = h0_2, 2 = A0) and X is one of Tev, LHC7 or LHC8. result = HiggsProd; } } }
41.283607
171
0.580868
[ "object", "vector", "model" ]
d0fc7e0d4d0544d7e899426732feafa5bb01d978
6,020
cpp
C++
main/inet/Xprt.cpp
semmerson/hycast
683f10a6a8b47501ecf4f2e619e7b64c039f4f1c
[ "Apache-2.0" ]
null
null
null
main/inet/Xprt.cpp
semmerson/hycast
683f10a6a8b47501ecf4f2e619e7b64c039f4f1c
[ "Apache-2.0" ]
12
2017-03-29T21:39:38.000Z
2017-12-07T18:09:09.000Z
main/inet/Xprt.cpp
semmerson/hycast
683f10a6a8b47501ecf4f2e619e7b64c039f4f1c
[ "Apache-2.0" ]
2
2018-06-29T16:57:13.000Z
2020-09-28T20:03:29.000Z
/** * This file defines a socket-based transport mechanism that is independent of * the socket's underlying protocol (TCP, UDP, etc.). * * @file: Xprt.cpp * @author: Steven R. Emmerson <emmerson@ucar.edu> * * Copyright 2021 University Corporation for Atmospheric Research * * 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 <error.h> #include <Socket.h> #include <Xprt.h> namespace hycast { class Xprt::Impl { using PduId = Xprt::PduId; Socket sock; Dispatch dispatch; public: Impl(Socket& sock) : sock(sock) , dispatch() {} Impl(Socket& sock, Dispatch& dispatch) : sock(sock) , dispatch(dispatch) {} virtual ~Impl() {}; SockAddr getRmtAddr() const { return sock.getRmtAddr(); } std::string to_string() const { return sock.to_string(); } /** * Sends a PDU ID as a PDU to the remote counterpart. * * @param[in] pduId PDU ID * @param[in] xprt Transport * @retval `true` Success * @retval `false` Connection lost */ bool send(const PduId pduId, Xprt& xprt) { return xprt.write(pduId) && sock.flush(); } /** * Sends a boolean as a PDU to the remote counterpart. * * @param[in] pduId PDU ID * @param[in] value Boolean to be sent * @param[in] xprt Transport * @retval `true` Success * @retval `false` Connection lost */ bool send(const PduId pduId, const bool value, Xprt& xprt) { return xprt.write(pduId) && sock.write(value) && sock.flush(); } /** * Sends an object as a PDU to the remote counterpart. * * @param[in] pduId PDU ID * @param[in] obj Object to be sent * @param[in] xprt Transport * @retval `true` Success * @retval `false` Connection lost */ bool send(PduId pduId, const XprtAble& obj, Xprt& xprt) { return xprt.write(pduId) && obj.write(xprt) && sock.flush(); } bool recv(Xprt xprt, Dispatch& dispatch) { PduId id; sock.clear(); return read(id) && dispatch(id, xprt); } bool write(const void* value, size_t nbytes) { return sock.write(value, nbytes); } bool write(const bool value) { return sock.write(value); } bool write(const uint8_t value) { return sock.write(value); } bool write(const uint16_t value) { return sock.write(value); } bool write(const uint32_t value) { LOG_NOTE("Writing uint32_t"); return sock.write(value); } bool write(const uint64_t value) { return sock.write(value); } bool write(const std::string& value) { return sock.write(value); } bool read(void* value, size_t nbytes) { return sock.read(value, nbytes); } bool read(bool& value) { return sock.read(value); } bool read(uint8_t& value) { return sock.read(value); } bool read(uint16_t& value) { return sock.read(value); } bool read(uint32_t& value) { LOG_NOTE("Reading uint32_t"); return sock.read(value); } bool read(uint64_t& value) { return sock.read(value); } bool read(std::string& value) { return sock.read(value); } void shutdown() { sock.shutdown(SHUT_RD); } }; /******************************************************************************/ Xprt::Xprt(Socket& sock) : pImpl(new Impl(sock)) {} SockAddr Xprt::getRmtAddr() const { return pImpl->getRmtAddr(); } std::string Xprt::to_string() const { return pImpl ? pImpl->to_string() : "<unset>"; } bool Xprt::send(const PduId pduId) { return pImpl->send(pduId, *this); } bool Xprt::send(const PduId pduId, const bool value) { return pImpl->send(pduId, value, *this); } bool Xprt::send(const PduId pduId, const XprtAble& obj) { return pImpl->send(pduId, obj, *this); } bool Xprt::recv(Dispatch& dispatch) { return pImpl->recv(*this, dispatch); } bool Xprt::write(const void* value, size_t nbytes) { return pImpl->write(value, nbytes); } bool Xprt::write(const bool value) { return pImpl->write(value); } bool Xprt::write(const uint8_t value) { return pImpl->write(value); } bool Xprt::write(const uint16_t value) { return pImpl->write(value); } bool Xprt::write(const uint32_t value) { return pImpl->write(value); } bool Xprt::write(const uint64_t value) { return pImpl->write(value); } bool Xprt::write(const std::string& value) { return pImpl->write(value); } bool Xprt::read(void* value, size_t nbytes) { return pImpl->read(value, nbytes); } bool Xprt::read(bool& value) { return pImpl->read(value); } bool Xprt::read(uint8_t& value) { return pImpl->read(value); } bool Xprt::read(uint16_t& value) { return pImpl->read(value); } bool Xprt::read(uint32_t& value) { return pImpl->read(value); } bool Xprt::read(uint64_t& value) { return pImpl->read(value); } bool Xprt::read(std::string& value) { return pImpl->read(value); } void Xprt::shutdown() { return pImpl->shutdown(); } } // namespace
25.083333
80
0.575748
[ "object" ]
cb9b916fadab59fca2a51b5ae5e3bb2b19007ddc
2,672
cpp
C++
AAEngine/src/Sound/SoundListener.cpp
archsolar/AncientArcher
529271c40b2fd2fd51aaa92526cb67248c78ed09
[ "MIT" ]
null
null
null
AAEngine/src/Sound/SoundListener.cpp
archsolar/AncientArcher
529271c40b2fd2fd51aaa92526cb67248c78ed09
[ "MIT" ]
null
null
null
AAEngine/src/Sound/SoundListener.cpp
archsolar/AncientArcher
529271c40b2fd2fd51aaa92526cb67248c78ed09
[ "MIT" ]
null
null
null
#include "../Sound/SoundDevice.h" #include "../Sound/SoundListener.h" namespace AA { SoundListener* SoundListener::Get() { // make sure sound device is initialized SoundDevice::Init(); SoundListener* snd_listener = new SoundListener(); return snd_listener; } void SoundListener::SetMasterGain(const float& gain) { // consider gain clamps float newVol = gain; if (newVol < 0.f) { newVol = 0.f; } else if (newVol > 5.f) { // now thats flippin loud, lets cap it newVol = 5.f; } alListenerf(AL_GAIN, newVol); if (alGetError() != AL_NO_ERROR) { throw("error setting gain"); } } void SoundListener::SetPosition(const glm::vec3& pos) { SetLocation(pos); } void SoundListener::SetLocation(const glm::vec3& pos) { alListener3f(AL_POSITION, pos.x, pos.y, pos.z); if (alGetError() != AL_NO_ERROR) { throw("error setting listener location"); } } void SoundListener::SetPosition(const float& x, const float& y, const float& z) { SetLocation(x, y, z); } void SoundListener::SetLocation(const float& x, const float& y, const float& z) { alListener3f(AL_POSITION, x, y, z); if (alGetError() != AL_NO_ERROR) { throw("error setting listener location"); } } void SoundListener::SetOrientation(const glm::vec3& at, const glm::vec3& up) { std::vector<float> ori; ori.push_back(at.x); ori.push_back(at.y); ori.push_back(at.z); ori.push_back(up.x); ori.push_back(up.y); ori.push_back(up.z); alListenerfv(AL_ORIENTATION, ori.data()); if (alGetError() != AL_NO_ERROR) { throw("error setting gain"); } } void SoundListener::SetOrientation(const float& atx, const float& aty, const float& atz, const float& upx, const float& upy, const float& upz) { float ori[6] = { atx, aty, atz, upx, upy, upz }; alListenerfv(AL_ORIENTATION, &ori[0]); if (alGetError() != AL_NO_ERROR) { throw("error setting gain"); } } /// <summary> /// AL_INVERSE_DISTANCE, AL_INVERSE_DISTANCE_CLAMPED, AL_LINEAR_DISTANCE, /// AL_LINEAR_DISTANCE_CLAMPED, AL_EXPONENT_DISTANCE, /// AL_EXPONENT_DISTANCE_CLAMPED, or AL_NONE. /// </summary> /// <param name="type">option</param> void SoundListener::SetDistanceModel(ALint type) { switch (type) { case AL_INVERSE_DISTANCE: case AL_INVERSE_DISTANCE_CLAMPED: case AL_LINEAR_DISTANCE: case AL_LINEAR_DISTANCE_CLAMPED: case AL_EXPONENT_DISTANCE: case AL_EXPONENT_DISTANCE_CLAMPED: case AL_NONE: break; default: throw("invalid distance model"); } alDistanceModel(type); if (alGetError() != AL_NO_ERROR) { throw("error setting listener distance model"); } } SoundListener::SoundListener() {} } // end namespace AA
21.901639
142
0.687874
[ "vector", "model" ]
cb9de3f7440ea9854f9dde7af116b7cc729134ff
531
hpp
C++
include/dsp.hpp
bander9289/StratifyAPI
9b45091aa71a4e5718047438ea4044c1fdc814a3
[ "MIT" ]
2
2016-05-21T03:09:19.000Z
2016-08-27T03:40:51.000Z
include/dsp.hpp
bander9289/StratifyAPI
9b45091aa71a4e5718047438ea4044c1fdc814a3
[ "MIT" ]
75
2017-10-08T22:21:19.000Z
2020-03-30T21:13:20.000Z
include/dsp.hpp
StratifyLabs/StratifyLib
975a5c25a84296fd0dec64fe4dc579cf7027abe6
[ "MIT" ]
5
2018-03-27T16:44:09.000Z
2020-07-08T16:45:55.000Z
/*! \file */ // Copyright 2011-2020 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md for rights. #ifndef SAPI_DSP_HPP_ #define SAPI_DSP_HPP_ /*! \brief Digital Signal Processing * \details The Digital Signal Processing (dsp) namespace * includes signal processing algorithms including * wrappers and data management tools for using the * ARM CMSIS DSP library. * * */ namespace dsp {} #include "dsp/SignalData.hpp" #include "dsp/Transform.hpp" #include "dsp/Filter.hpp" using namespace dsp; #endif // SAPI_DSP_HPP_
23.086957
100
0.745763
[ "transform" ]
cba0a54f3fa060dd4b2cf7cdf5c2af9b9d8e49fc
2,114
cpp
C++
src/tools.cpp
hanshu86/ExtendedKalmanFilter
fb65f57a27319eb9928005b8d4d791ebc95033af
[ "MIT" ]
null
null
null
src/tools.cpp
hanshu86/ExtendedKalmanFilter
fb65f57a27319eb9928005b8d4d791ebc95033af
[ "MIT" ]
null
null
null
src/tools.cpp
hanshu86/ExtendedKalmanFilter
fb65f57a27319eb9928005b8d4d791ebc95033af
[ "MIT" ]
null
null
null
#include "tools.h" #include <iostream> using Eigen::VectorXd; using Eigen::MatrixXd; using std::vector; using std::cout; using std::endl; Tools::Tools() {} Tools::~Tools() {} /** * Implementation based in Quiz */ VectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations, const vector<VectorXd> &ground_truth) { VectorXd rmse(4); rmse << 0,0,0,0; // check the validity of the following inputs: // * the estimation vector size should not be zero // * the estimation vector size should equal ground truth vector size if ((estimations.size() != ground_truth.size()) || (estimations.size() == 0) ) { cout << "CalculateRMSE[ERR]: Invalid estimation or ground_truth data" << endl; goto done; } for (unsigned int i = 0; i < estimations.size(); ++i) { VectorXd difference = estimations[i] - ground_truth[i]; // coefficient-wise multiplication difference = difference.array() * difference.array(); rmse += difference; } // calculate the mean rmse = rmse/estimations.size(); // cout << "RMSE:" << rmse << endl; // calculate the squared root rmse = rmse.array().sqrt(); done: return rmse; } /** * Implementation based in Quiz */ MatrixXd Tools::CalculateJacobian(const VectorXd& x_state) { MatrixXd Hj(3,4); Hj << 0,0,0,0, 0,0,0,0, 0,0,0,0; // recover state parameters float px = x_state(0); float py = x_state(1); float vx = x_state(2); float vy = x_state(3); float sqrt_px_py = sqrt(px*px + py*py); float sq_px_py = (px*px + py*py); float cube_sqrt_px_py = pow(sqrt_px_py, 3); // check division by zero if( (sqrt_px_py == 0) || (sq_px_py == 0) || (cube_sqrt_px_py == 0)) { cout<<"CalculateJacobian[ERR]: Divide by Zero" << endl; goto done; } // compute the Jacobian matrix Hj(0,0) = px/sqrt_px_py; Hj(0,1) = py/sqrt_px_py; Hj(0,2) = 0; Hj(0,3) = 0; Hj(1,0) = -py/sq_px_py; Hj(1,1) = px/sq_px_py; Hj(1,2) = 0; Hj(1,3) = 0; Hj(2,0) = (py*(vx*py - vy*px))/cube_sqrt_px_py; Hj(2,1) = (px*(vy*px - vx*py))/cube_sqrt_px_py; Hj(2,2) = px/sqrt_px_py; Hj(2,3) = py/sqrt_px_py; done: return Hj; }
22.020833
80
0.635762
[ "vector" ]
cbae6fe1dffa52fb72ddd8e50865f0f24801e999
8,045
cc
C++
media/audio/cras/cras_output_unittest.cc
GnorTech/chromium
e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2018-03-10T13:08:49.000Z
2018-03-10T13:08:49.000Z
media/audio/cras/cras_output_unittest.cc
GnorTech/chromium
e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
media/audio/cras/cras_output_unittest.cc
GnorTech/chromium
e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:19:31.000Z
2020-11-04T07:19:31.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include "base/threading/thread.h" #include "media/audio/cras/audio_manager_cras.h" #include "media/audio/cras/cras_output.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using testing::_; using testing::DoAll; using testing::Return; using testing::SetArgumentPointee; using testing::StrictMock; namespace media { class MockAudioSourceCallback : public AudioOutputStream::AudioSourceCallback { public: MOCK_METHOD2(OnMoreData, int(AudioBus* audio_bus, AudioBuffersState buffers_state)); MOCK_METHOD3(OnMoreIOData, int(AudioBus* source, AudioBus* dest, AudioBuffersState buffers_state)); MOCK_METHOD2(OnError, void(AudioOutputStream* stream, int code)); }; class MockAudioManagerCras : public AudioManagerCras { public: MOCK_METHOD0(Init, void()); MOCK_METHOD0(HasAudioOutputDevices, bool()); MOCK_METHOD0(HasAudioInputDevices, bool()); MOCK_METHOD1(MakeLinearOutputStream, AudioOutputStream*( const AudioParameters& params)); MOCK_METHOD1(MakeLowLatencyOutputStream, AudioOutputStream*( const AudioParameters& params)); MOCK_METHOD2(MakeLinearOutputStream, AudioInputStream*( const AudioParameters& params, const std::string& device_id)); MOCK_METHOD2(MakeLowLatencyInputStream, AudioInputStream*( const AudioParameters& params, const std::string& device_id)); // We need to override this function in order to skip the checking the number // of active output streams. It is because the number of active streams // is managed inside MakeAudioOutputStream, and we don't use // MakeAudioOutputStream to create the stream in the tests. virtual void ReleaseOutputStream(AudioOutputStream* stream) OVERRIDE { DCHECK(stream); delete stream; } // We don't mock this method since all tests will do the same thing // and use the current message loop. virtual scoped_refptr<base::MessageLoopProxy> GetMessageLoop() OVERRIDE { return MessageLoop::current()->message_loop_proxy(); } }; class CrasOutputStreamTest : public testing::Test { protected: CrasOutputStreamTest() { mock_manager_.reset(new StrictMock<MockAudioManagerCras>()); } virtual ~CrasOutputStreamTest() { } CrasOutputStream* CreateStream(ChannelLayout layout) { return CreateStream(layout, kTestFramesPerPacket); } CrasOutputStream* CreateStream(ChannelLayout layout, int32 samples_per_packet) { AudioParameters params(kTestFormat, layout, kTestSampleRate, kTestBitsPerSample, samples_per_packet); return new CrasOutputStream(params, mock_manager_.get()); } MockAudioManagerCras& mock_manager() { return *(mock_manager_.get()); } static const ChannelLayout kTestChannelLayout; static const int kTestSampleRate; static const int kTestBitsPerSample; static const int kTestBytesPerFrame; static const AudioParameters::Format kTestFormat; static const uint32 kTestFramesPerPacket; static const uint32 kTestPacketSize; static struct cras_audio_format* const kFakeAudioFormat; static struct cras_stream_params* const kFakeStreamParams; static struct cras_client* const kFakeClient; scoped_ptr<StrictMock<MockAudioManagerCras> > mock_manager_; private: DISALLOW_COPY_AND_ASSIGN(CrasOutputStreamTest); }; const ChannelLayout CrasOutputStreamTest::kTestChannelLayout = CHANNEL_LAYOUT_STEREO; const int CrasOutputStreamTest::kTestSampleRate = AudioParameters::kAudioCDSampleRate; const int CrasOutputStreamTest::kTestBitsPerSample = 16; const int CrasOutputStreamTest::kTestBytesPerFrame = CrasOutputStreamTest::kTestBitsPerSample / 8 * ChannelLayoutToChannelCount(CrasOutputStreamTest::kTestChannelLayout); const AudioParameters::Format CrasOutputStreamTest::kTestFormat = AudioParameters::AUDIO_PCM_LINEAR; const uint32 CrasOutputStreamTest::kTestFramesPerPacket = 1000; const uint32 CrasOutputStreamTest::kTestPacketSize = CrasOutputStreamTest::kTestFramesPerPacket * CrasOutputStreamTest::kTestBytesPerFrame; struct cras_audio_format* const CrasOutputStreamTest::kFakeAudioFormat = reinterpret_cast<struct cras_audio_format*>(1); struct cras_stream_params* const CrasOutputStreamTest::kFakeStreamParams = reinterpret_cast<struct cras_stream_params*>(1); struct cras_client* const CrasOutputStreamTest::kFakeClient = reinterpret_cast<struct cras_client*>(1); TEST_F(CrasOutputStreamTest, ConstructedState) { // Should support mono. CrasOutputStream* test_stream = CreateStream(CHANNEL_LAYOUT_MONO); EXPECT_EQ(CrasOutputStream::kCreated, test_stream->state()); test_stream->Close(); // Should support stereo. test_stream = CreateStream(CHANNEL_LAYOUT_SURROUND); EXPECT_EQ(CrasOutputStream::kCreated, test_stream->state()); test_stream->Close(); // Bad bits per sample. AudioParameters bad_bps_params(kTestFormat, kTestChannelLayout, kTestSampleRate, kTestBitsPerSample - 1, kTestFramesPerPacket); test_stream = new CrasOutputStream(bad_bps_params, mock_manager_.get()); EXPECT_EQ(CrasOutputStream::kInError, test_stream->state()); test_stream->Close(); // Bad format. AudioParameters bad_format_params(AudioParameters::AUDIO_LAST_FORMAT, kTestChannelLayout, kTestSampleRate, kTestBitsPerSample, kTestFramesPerPacket); test_stream = new CrasOutputStream(bad_format_params, mock_manager_.get()); EXPECT_EQ(CrasOutputStream::kInError, test_stream->state()); test_stream->Close(); // Bad sample rate. AudioParameters bad_rate_params(kTestFormat, kTestChannelLayout, 0, kTestBitsPerSample, kTestFramesPerPacket); test_stream = new CrasOutputStream(bad_rate_params, mock_manager_.get()); EXPECT_EQ(CrasOutputStream::kInError, test_stream->state()); test_stream->Close(); } TEST_F(CrasOutputStreamTest, OpenClose) { CrasOutputStream* test_stream = CreateStream(CHANNEL_LAYOUT_MONO); // Open the stream. ASSERT_TRUE(test_stream->Open()); EXPECT_EQ(CrasOutputStream::kIsOpened, test_stream->state()); // Close the stream. test_stream->Close(); } TEST_F(CrasOutputStreamTest, StartFailBeforeOpen) { CrasOutputStream* test_stream = CreateStream(CHANNEL_LAYOUT_MONO); MockAudioSourceCallback mock_callback; test_stream->Start(&mock_callback); EXPECT_EQ(CrasOutputStream::kInError, test_stream->state()); } TEST_F(CrasOutputStreamTest, StartStop) { CrasOutputStream* test_stream = CreateStream(CHANNEL_LAYOUT_MONO); MockAudioSourceCallback mock_callback; // Open the stream. ASSERT_TRUE(test_stream->Open()); EXPECT_EQ(CrasOutputStream::kIsOpened, test_stream->state()); // Start. test_stream->Start(&mock_callback); EXPECT_EQ(CrasOutputStream::kIsPlaying, test_stream->state()); // Stop. test_stream->Stop(); EXPECT_EQ(CrasOutputStream::kIsStopped, test_stream->state()); // Close the stream. test_stream->Close(); } TEST_F(CrasOutputStreamTest, RenderFrames) { CrasOutputStream* test_stream = CreateStream(CHANNEL_LAYOUT_MONO); MockAudioSourceCallback mock_callback; // Open the stream. ASSERT_TRUE(test_stream->Open()); EXPECT_EQ(CrasOutputStream::kIsOpened, test_stream->state()); // Render Callback. EXPECT_CALL(mock_callback, OnMoreData(_, _)) .WillRepeatedly(Return(kTestFramesPerPacket)); // Start. test_stream->Start(&mock_callback); EXPECT_EQ(CrasOutputStream::kIsPlaying, test_stream->state()); // Stop. test_stream->Stop(); EXPECT_EQ(CrasOutputStream::kIsStopped, test_stream->state()); // Close the stream. test_stream->Close(); } } // namespace media
36.238739
79
0.748291
[ "render" ]
cbb244f3ba26d7481aae859a586c585ca4c483f8
1,365
hpp
C++
src/frontend/DLX/include/DLX/Core/compiler.hpp
maurizioabba/rose
7597292cf14da292bdb9a4ef573001b6c5b9b6c0
[ "BSD-3-Clause" ]
1
2019-04-22T09:09:05.000Z
2019-04-22T09:09:05.000Z
src/frontend/DLX/include/DLX/Core/compiler.hpp
maurizioabba/rose
7597292cf14da292bdb9a4ef573001b6c5b9b6c0
[ "BSD-3-Clause" ]
null
null
null
src/frontend/DLX/include/DLX/Core/compiler.hpp
maurizioabba/rose
7597292cf14da292bdb9a4ef573001b6c5b9b6c0
[ "BSD-3-Clause" ]
null
null
null
/*! * * \file DLX/Core/compiler.hpp * * \author Tristan Vanderbruggen * */ #ifndef __DLX_CORE_COMPILER_HPP__ #define __DLX_CORE_COMPILER_HPP__ #include "DLX/Core/directives.hpp" /*! * \addtogroup grp_rose * @{ */ class SgNode; class SgSymbol; typedef SgNode * ast_fragment_t; /** @} */ namespace DLX { namespace Compiler { /*! * \addtogroup grp_dlx_core_compiler * @{ */ template <class language_tpl, class compiler_modules_t> class Compiler { public: typedef language_tpl language_t; typedef Directives::directive_t<language_t> directive_t; typedef std::vector<directive_t *> directives_ptr_set_t; compiler_modules_t & compiler_modules; public: Compiler(compiler_modules_t & compiler_modules_) : compiler_modules(compiler_modules_) {} /*! * \brief It applies the transformation associated with the directives. * \param directives the set of all the directive found * \param graph_entry the set of directives without predecessor (or parent) * \param graph_final the set of directives without successor (or children) * return true if the compilation is successful */ bool compile(const directives_ptr_set_t & directives, const directives_ptr_set_t & graph_entry, const directives_ptr_set_t & graph_final); }; /** @} */ } } #endif /* __DLX_COMPILER_CORE_HPP__ */
20.073529
142
0.718681
[ "vector" ]
cbb7b53bff2e97d115758f780ff3b67a35d3ddca
10,923
cc
C++
android/art/openjdkjvmti/ti_search.cc
Solotov/deoptfuscator
8a54119e81517bcef73d2d6dfefba910ae2446e7
[ "MIT" ]
206
2020-04-13T03:19:33.000Z
2022-03-27T13:52:25.000Z
android/art/openjdkjvmti/ti_search.cc
Solotov/deoptfuscator
8a54119e81517bcef73d2d6dfefba910ae2446e7
[ "MIT" ]
9
2020-06-07T12:51:09.000Z
2022-03-28T23:55:09.000Z
android/art/openjdkjvmti/ti_search.cc
Solotov/deoptfuscator
8a54119e81517bcef73d2d6dfefba910ae2446e7
[ "MIT" ]
42
2020-04-13T03:37:58.000Z
2022-03-23T15:08:12.000Z
/* Copyright (C) 2017 The Android Open Source Project * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This file implements interfaces from the file jvmti.h. This implementation * is licensed under the same terms as the file jvmti.h. The * copyright and license information for the file jvmti.h follows. * * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #include "ti_search.h" #include "jni.h" #include "art_field-inl.h" #include "art_jvmti.h" #include "base/enums.h" #include "base/macros.h" #include "class_linker.h" #include "dex/art_dex_file_loader.h" #include "dex/dex_file.h" #include "dex/dex_file_loader.h" #include "jni_internal.h" #include "mirror/class-inl.h" #include "mirror/object.h" #include "mirror/string.h" #include "nativehelper/scoped_local_ref.h" #include "obj_ptr-inl.h" #include "runtime.h" #include "runtime_callbacks.h" #include "scoped_thread_state_change-inl.h" #include "thread-current-inl.h" #include "thread_list.h" #include "ti_phase.h" #include "well_known_classes.h" namespace openjdkjvmti { static std::vector<std::string> gSystemOnloadSegments; static art::ObjPtr<art::mirror::Object> GetSystemProperties(art::Thread* self, art::ClassLinker* class_linker) REQUIRES_SHARED(art::Locks::mutator_lock_) { art::ObjPtr<art::mirror::Class> system_class = class_linker->LookupClass(self, "Ljava/lang/System;", nullptr); DCHECK(system_class != nullptr); DCHECK(system_class->IsInitialized()); art::ArtField* props_field = system_class->FindDeclaredStaticField("props", "Ljava/util/Properties;"); DCHECK(props_field != nullptr); art::ObjPtr<art::mirror::Object> props_obj = props_field->GetObject(system_class); DCHECK(props_obj != nullptr); return props_obj; } static void Update() REQUIRES_SHARED(art::Locks::mutator_lock_) { if (gSystemOnloadSegments.empty()) { return; } // In the on-load phase we have to modify java.class.path to influence the system classloader. // As this is an unmodifiable system property, we have to access the "defaults" field. art::ClassLinker* class_linker = art::Runtime::Current()->GetClassLinker(); DCHECK(class_linker != nullptr); art::Thread* self = art::Thread::Current(); // Prepare: collect classes, fields and methods. art::ObjPtr<art::mirror::Class> properties_class = class_linker->LookupClass(self, "Ljava/util/Properties;", nullptr); DCHECK(properties_class != nullptr); ScopedLocalRef<jobject> defaults_jobj(self->GetJniEnv(), nullptr); { art::ObjPtr<art::mirror::Object> props_obj = GetSystemProperties(self, class_linker); art::ArtField* defaults_field = properties_class->FindDeclaredInstanceField("defaults", "Ljava/util/Properties;"); DCHECK(defaults_field != nullptr); art::ObjPtr<art::mirror::Object> defaults_obj = defaults_field->GetObject(props_obj); DCHECK(defaults_obj != nullptr); defaults_jobj.reset(self->GetJniEnv()->AddLocalReference<jobject>(defaults_obj)); } art::ArtMethod* get_property = properties_class->FindClassMethod( "getProperty", "(Ljava/lang/String;)Ljava/lang/String;", art::kRuntimePointerSize); DCHECK(get_property != nullptr); DCHECK(!get_property->IsDirect()); DCHECK(get_property->GetDeclaringClass() == properties_class); art::ArtMethod* set_property = properties_class->FindClassMethod( "setProperty", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;", art::kRuntimePointerSize); DCHECK(set_property != nullptr); DCHECK(!set_property->IsDirect()); DCHECK(set_property->GetDeclaringClass() == properties_class); // This is an allocation. Do this late to avoid the need for handles. ScopedLocalRef<jobject> cp_jobj(self->GetJniEnv(), nullptr); { art::ObjPtr<art::mirror::Object> cp_key = art::mirror::String::AllocFromModifiedUtf8(self, "java.class.path"); if (cp_key == nullptr) { self->AssertPendingOOMException(); self->ClearException(); return; } cp_jobj.reset(self->GetJniEnv()->AddLocalReference<jobject>(cp_key)); } // OK, now get the current value. std::string str_value; { ScopedLocalRef<jobject> old_value(self->GetJniEnv(), self->GetJniEnv()->CallObjectMethod( defaults_jobj.get(), art::jni::EncodeArtMethod(get_property), cp_jobj.get())); DCHECK(old_value.get() != nullptr); str_value = self->DecodeJObject(old_value.get())->AsString()->ToModifiedUtf8(); self->GetJniEnv()->DeleteLocalRef(old_value.release()); } // Update the value by appending the new segments. for (const std::string& segment : gSystemOnloadSegments) { if (!str_value.empty()) { str_value += ":"; } str_value += segment; } gSystemOnloadSegments.clear(); // Create the new value object. ScopedLocalRef<jobject> new_val_jobj(self->GetJniEnv(), nullptr); { art::ObjPtr<art::mirror::Object> new_value = art::mirror::String::AllocFromModifiedUtf8(self, str_value.c_str()); if (new_value == nullptr) { self->AssertPendingOOMException(); self->ClearException(); return; } new_val_jobj.reset(self->GetJniEnv()->AddLocalReference<jobject>(new_value)); } // Write to the defaults. ScopedLocalRef<jobject> res_obj(self->GetJniEnv(), self->GetJniEnv()->CallObjectMethod(defaults_jobj.get(), art::jni::EncodeArtMethod(set_property), cp_jobj.get(), new_val_jobj.get())); if (self->IsExceptionPending()) { self->ClearException(); return; } } struct SearchCallback : public art::RuntimePhaseCallback { void NextRuntimePhase(RuntimePhase phase) OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) { if (phase == RuntimePhase::kStart) { // It's time to update the system properties. Update(); } } }; static SearchCallback gSearchCallback; void SearchUtil::Register() { art::Runtime* runtime = art::Runtime::Current(); art::ScopedThreadStateChange stsc(art::Thread::Current(), art::ThreadState::kWaitingForDebuggerToAttach); art::ScopedSuspendAll ssa("Add search callback"); runtime->GetRuntimeCallbacks()->AddRuntimePhaseCallback(&gSearchCallback); } void SearchUtil::Unregister() { art::ScopedThreadStateChange stsc(art::Thread::Current(), art::ThreadState::kWaitingForDebuggerToAttach); art::ScopedSuspendAll ssa("Remove search callback"); art::Runtime* runtime = art::Runtime::Current(); runtime->GetRuntimeCallbacks()->RemoveRuntimePhaseCallback(&gSearchCallback); } jvmtiError SearchUtil::AddToBootstrapClassLoaderSearch(jvmtiEnv* env ATTRIBUTE_UNUSED, const char* segment) { art::Runtime* current = art::Runtime::Current(); if (current == nullptr) { return ERR(WRONG_PHASE); } if (current->GetClassLinker() == nullptr) { return ERR(WRONG_PHASE); } if (segment == nullptr) { return ERR(NULL_POINTER); } std::string error_msg; std::vector<std::unique_ptr<const art::DexFile>> dex_files; const art::ArtDexFileLoader dex_file_loader; if (!dex_file_loader.Open( segment, segment, /* verify */ true, /* verify_checksum */ true, &error_msg, &dex_files)) { LOG(WARNING) << "Could not open " << segment << " for boot classpath extension: " << error_msg; return ERR(ILLEGAL_ARGUMENT); } art::ScopedObjectAccess soa(art::Thread::Current()); for (std::unique_ptr<const art::DexFile>& dex_file : dex_files) { current->GetClassLinker()->AppendToBootClassPath(art::Thread::Current(), *dex_file.release()); } return ERR(NONE); } jvmtiError SearchUtil::AddToSystemClassLoaderSearch(jvmtiEnv* jvmti_env ATTRIBUTE_UNUSED, const char* segment) { if (segment == nullptr) { return ERR(NULL_POINTER); } jvmtiPhase phase = PhaseUtil::GetPhaseUnchecked(); if (phase == jvmtiPhase::JVMTI_PHASE_ONLOAD) { // We could try and see whether it is a valid path. We could also try to allocate Java // objects to avoid later OOME. gSystemOnloadSegments.push_back(segment); return ERR(NONE); } else if (phase != jvmtiPhase::JVMTI_PHASE_LIVE) { return ERR(WRONG_PHASE); } jobject sys_class_loader = art::Runtime::Current()->GetSystemClassLoader(); if (sys_class_loader == nullptr) { // This is unexpected. return ERR(INTERNAL); } // We'll use BaseDexClassLoader.addDexPath, as it takes care of array resizing etc. As a downside, // exceptions are swallowed. art::Thread* self = art::Thread::Current(); JNIEnv* env = self->GetJniEnv(); if (!env->IsInstanceOf(sys_class_loader, art::WellKnownClasses::dalvik_system_BaseDexClassLoader)) { return ERR(INTERNAL); } jmethodID add_dex_path_id = env->GetMethodID( art::WellKnownClasses::dalvik_system_BaseDexClassLoader, "addDexPath", "(Ljava/lang/String;)V"); if (add_dex_path_id == nullptr) { return ERR(INTERNAL); } ScopedLocalRef<jstring> dex_path(env, env->NewStringUTF(segment)); if (dex_path.get() == nullptr) { return ERR(INTERNAL); } env->CallVoidMethod(sys_class_loader, add_dex_path_id, dex_path.get()); if (env->ExceptionCheck()) { env->ExceptionClear(); return ERR(ILLEGAL_ARGUMENT); } return ERR(NONE); } } // namespace openjdkjvmti
36.289037
100
0.678843
[ "object", "vector" ]
cbb7d6ec85149b267933cc56de0cbb19726c1c2a
522
cpp
C++
Olympiad Programs/Contest/Way Too Long Words 71A.cpp
mirtaba/ACMICPC-INOI_Archive
ea06e4e40e984f0807410e4f9b5f7042580da2e3
[ "MIT" ]
1
2020-12-08T11:21:34.000Z
2020-12-08T11:21:34.000Z
Olympiad Programs/Contest/Way Too Long Words 71A.cpp
mirtaba/ACMICPC-INOI_Archive
ea06e4e40e984f0807410e4f9b5f7042580da2e3
[ "MIT" ]
null
null
null
Olympiad Programs/Contest/Way Too Long Words 71A.cpp
mirtaba/ACMICPC-INOI_Archive
ea06e4e40e984f0807410e4f9b5f7042580da2e3
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <string> #include <cctype> #include <stack> #include <queue> #include <list> #include <vector> #include <map> #include <sstream> #include <cmath> #include <bitset> #include <utility> #include <set> #include <numeric> using namespace std; int n; int main() { cin >> n; while(n--) { string s; cin >> s; if(s.length()<=10) cout << s << endl; else { cout<<s[0]<<s.length()-2<<s[s.length()-1]<<endl; } } }
13.736842
51
0.611111
[ "vector" ]
cbb820e4b6d911f28d813510df2fe8ab52ec0c85
10,195
cpp
C++
src/metaspades/src/projects/corrector/dataset_processor.cpp
STRIDES-Codes/Exploring-the-Microbiome-
bd29c8c74d8f40a58b63db28815acb4081f20d6b
[ "MIT" ]
null
null
null
src/metaspades/src/projects/corrector/dataset_processor.cpp
STRIDES-Codes/Exploring-the-Microbiome-
bd29c8c74d8f40a58b63db28815acb4081f20d6b
[ "MIT" ]
null
null
null
src/metaspades/src/projects/corrector/dataset_processor.cpp
STRIDES-Codes/Exploring-the-Microbiome-
bd29c8c74d8f40a58b63db28815acb4081f20d6b
[ "MIT" ]
2
2021-06-05T07:40:20.000Z
2021-06-05T08:02:58.000Z
//*************************************************************************** //* Copyright (c) 2015 Saint Petersburg State University //* Copyright (c) 2011-2014 Saint Petersburg Academic University //* All Rights Reserved //* See file LICENSE for details. //*************************************************************************** #include "dataset_processor.hpp" #include "variants_table.hpp" #include "contig_processor.hpp" #include "config_struct.hpp" #include "io/reads/file_reader.hpp" #include "utils/filesystem/path_helper.hpp" #include "io/reads/osequencestream.hpp" #include "utils/parallel/openmp_wrapper.h" #include <boost/algorithm/string.hpp> #include <iostream> #include <unistd.h> using namespace std; namespace corrector { std::string DatasetProcessor::GetLibDir(const size_t lib_count) { if (lib_dirs_.find(lib_count) != lib_dirs_.end()) return lib_dirs_[lib_count]; std::string res = fs::make_temp_dir(corr_cfg::get().work_dir, "lib" + to_string(lib_count)); lib_dirs_[lib_count] = res; return res; } void DatasetProcessor::SplitGenome(const string &genome_splitted_dir) { io::FileReadStream frs(genome_file_); size_t cur_id = 0; while (!frs.eof()) { io::SingleRead cur_read; frs >> cur_read; string contig_name = cur_read.name(); string contig_seq = cur_read.GetSequenceString(); if (all_contigs_.find(contig_name) != all_contigs_.end()) { WARN("Duplicated contig names! Multiple contigs with name" << contig_name); } string full_path = fs::append_path(genome_splitted_dir, contig_name + ".fasta"); string out_full_path = fs::append_path(genome_splitted_dir, contig_name + ".ref.fasta"); string sam_filename = fs::append_path(genome_splitted_dir, contig_name + ".pair.sam"); all_contigs_[contig_name] = {full_path, out_full_path, contig_seq.length(), sam_files_type(), sam_filename, cur_id}; cur_id ++; buffered_reads_[contig_name].clear(); io::OFastaReadStream oss(full_path); oss << io::SingleRead(contig_name, contig_seq); DEBUG("full_path " + full_path) } } //contigs - set of aligned contig names void DatasetProcessor::GetAlignedContigs(const string &read, set<string> &contigs) const { vector<string> arr; boost::split(arr, read, boost::is_any_of("\t")); if (arr.size() > 5) { if (arr[2] != "*" && stoi(arr[4]) > 0) { // here can be multuple aligned parsing if neeeded; contigs.insert(arr[2]); } } } void DatasetProcessor::SplitLibrary(const string &all_reads_filename, const size_t lib_count, bool is_paired = false) { int reads_cnt = is_paired ? 2 : 1; ifstream fs(all_reads_filename); while (!fs.eof()) { set<string> contigs; std::vector<std::string> reads(reads_cnt); getline(fs, reads[0]); if (reads[0][0] == '@') continue; if (is_paired) { getline(fs, reads[1]); } for (int i = 0; i < reads_cnt; ++i) { GetAlignedContigs(reads[i], contigs); } for (auto &contig : contigs) { CHECK_FATAL_ERROR(all_contigs_.find(contig) != all_contigs_.end(), "wrong contig name in SAM file header: " + contig); for (int i = 0; i < reads_cnt; ++i) { BufferedOutputRead(reads[i], contig, lib_count); } } } FlushAll(lib_count); } void DatasetProcessor::FlushAll(const size_t lib_count) { for (const auto &ac : all_contigs_) { if (buffered_reads_[ac.first].size() > 0) { ofstream stream(ac.second.sam_filenames[lib_count].first.c_str(), std::ios_base::app | std::ios_base::out); for (const string &read : buffered_reads_[ac.first]) { stream << read; stream << '\n'; } buffered_reads_[ac.first].clear(); } } } void DatasetProcessor::BufferedOutputRead(const string &read, const string &contig_name, const size_t lib_count) { buffered_reads_[contig_name].push_back(read); buffered_count_++; if (buffered_count_ % kBuffSize == 0) { if (buffered_count_ % (10 * kBuffSize) == 0) INFO("processed " << buffered_count_ << "reads, flushing"); FlushAll(lib_count); } } int DatasetProcessor::RunBwaIndex() { string bwa_string = fs::screen_whitespaces(fs::screen_whitespaces(corr_cfg::get().bwa)); string genome_screened = fs::screen_whitespaces(genome_file_); string index_line = bwa_string + " index " + genome_screened; INFO("Running bwa index ...: " << index_line); int run_res = system(index_line.c_str()); if (run_res != 0) { INFO("bwa failed, skipping sublib"); } return run_res; } std::string DatasetProcessor::RunBwaMem(const std::vector<std::string> &reads, const size_t lib, const std::string &params = "") { string cur_dir = GetLibDir(lib); string tmp_sam_filename = fs::append_path(cur_dir, "tmp.sam"); string bwa_string = fs::screen_whitespaces(fs::screen_whitespaces(corr_cfg::get().bwa)); string genome_screened = fs::screen_whitespaces(genome_file_); int run_res = 0; std::string reads_line = ""; for (auto& filename : reads) { reads_line += fs::screen_whitespaces(filename) + " "; } string nthreads_str = to_string(nthreads_); string last_line = bwa_string + " mem -v 1 -t " + nthreads_str + " " + params + " " + genome_screened + " " + reads_line + " > " + fs::screen_whitespaces(tmp_sam_filename) ; INFO("Running bwa mem ...:" << last_line); run_res = system(last_line.c_str()); if (run_res != 0) { INFO("bwa failed, skipping sublib"); return ""; } return tmp_sam_filename; } void DatasetProcessor::PrepareContigDirs(const size_t lib_count) { string out_dir = GetLibDir(lib_count); for (auto &ac : all_contigs_) { auto contig_name = ac.first; string out_name = fs::append_path(out_dir, contig_name + ".sam"); ac.second.sam_filenames.push_back(make_pair(out_name, unsplitted_sam_files_[lib_count].second)); BufferedOutputRead("@SQ\tSN:" + contig_name + "\tLN:" + to_string(all_contigs_[contig_name].contig_length), contig_name, lib_count); } FlushAll(lib_count); } void DatasetProcessor::ProcessDataset() { size_t lib_num = 0; INFO("Splitting assembly..."); INFO("Assembly file: " + genome_file_); SplitGenome(work_dir_); if (RunBwaIndex() != 0) { FATAL_ERROR("Failed to build bwa index for " << genome_file_); } auto handle_one_lib = [this, &lib_num](const std::vector<std::string>& reads, const std::string& type, const auto& lib_type){ std::string reads_files_str = ""; for (const auto& filename : reads) { reads_files_str += filename + " "; } INFO("Processing " + type + " sublib of number " << lib_num); INFO(reads_files_str); std::string param = ""; if (type == "interlaced") { param = "-p"; } string samf = RunBwaMem(reads, lib_num, param); if (samf != "") { INFO("Adding samfile " << samf); unsplitted_sam_files_.push_back(make_pair(samf, lib_type)); PrepareContigDirs(lib_num); SplitLibrary(samf, lib_num,lib_type != io::LibraryType::SingleReads); lib_num++; } else { FATAL_ERROR("Failed to align " + type + " reads " << reads_files_str); } }; for (size_t i = 0; i < corr_cfg::get().dataset.lib_count(); ++i) { const auto& dataset = corr_cfg::get().dataset[i]; auto lib_type = dataset.type(); if (lib_type == io::LibraryType::PairedEnd || lib_type == io::LibraryType::HQMatePairs || lib_type == io::LibraryType::SingleReads) { for (auto iter = dataset.paired_begin(); iter != dataset.paired_end(); iter++) { handle_one_lib({iter->first, iter->second}, "paired", lib_type); } for (auto iter = dataset.interlaced_begin(); iter != dataset.interlaced_end(); iter++) { handle_one_lib({*iter}, "interlaced", lib_type); } for (auto iter = dataset.single_begin(); iter != dataset.single_end(); iter++) { handle_one_lib({*iter}, "single", lib_type); } } } INFO("Processing contigs"); vector<pair<size_t, string> > ordered_contigs; for (const auto &ac : all_contigs_) { ordered_contigs.push_back(make_pair(ac.second.contig_length, ac.first)); } size_t cont_num = ordered_contigs.size(); sort(ordered_contigs.begin(), ordered_contigs.end(), std::greater<pair<size_t, string> >()); auto all_contigs_ptr = &all_contigs_; # pragma omp parallel for shared(all_contigs_ptr, ordered_contigs) num_threads(nthreads_) schedule(dynamic,1) for (size_t i = 0; i < cont_num; i++) { bool long_enough = (*all_contigs_ptr)[ordered_contigs[i].second].contig_length > kMinContigLengthForInfo; ContigProcessor pc((*all_contigs_ptr)[ordered_contigs[i].second].sam_filenames, (*all_contigs_ptr)[ordered_contigs[i].second].input_contig_filename); size_t changes = pc.ProcessMultipleSamFiles(); if (long_enough) { #pragma omp critical { INFO("Contig " << ordered_contigs[i].second << " processed with " << changes << " changes in thread " << omp_get_thread_num()); } } } INFO("Gluing processed contigs"); GlueSplittedContigs(output_contig_file_); } void DatasetProcessor::GlueSplittedContigs(string &out_contigs_filename) { ofstream of_c(out_contigs_filename, std::ios_base::binary); vector<string> ordered_names; ordered_names.resize(all_contigs_.size()); for (const auto &ac : all_contigs_) { ordered_names[ac.second.id] = ac.first; } for (size_t i = 0; i < ordered_names.size(); i++) { ifstream a_f(all_contigs_[ordered_names[i]].output_contig_filename, std::ios_base::binary); of_c << a_f.rdbuf(); } } } ;
38.327068
157
0.622658
[ "vector" ]
cbb900cc15d47d164ef4c15c5f13545932504f37
16,692
cpp
C++
source/polyvec/geometry/path.cpp
ShnitzelKiller/polyfit
51ddc6365a794db1678459140658211cb78f65b1
[ "MIT" ]
27
2020-08-17T17:25:59.000Z
2022-03-01T05:49:12.000Z
source/polyvec/geometry/path.cpp
ShnitzelKiller/polyfit
51ddc6365a794db1678459140658211cb78f65b1
[ "MIT" ]
4
2020-08-26T13:54:59.000Z
2020-09-21T07:19:22.000Z
source/polyvec/geometry/path.cpp
ShnitzelKiller/polyfit
51ddc6365a794db1678459140658211cb78f65b1
[ "MIT" ]
5
2020-08-26T23:26:48.000Z
2021-01-04T09:06:07.000Z
// Header #include <polyvec/geometry/path.hpp> // polyvec #include <polyvec/api.hpp> #include <polyvec/core/constants.hpp> #include <polyvec/misc.hpp> #include <polyvec/geometry/line.hpp> #include <polyvec/debug.hpp> #include <polyvec/utils/matrix.hpp> #include <polyvec/utils/directions.hpp> #include <polyvec/geometry/winding_number.hpp> #include <polyvec/core/log.hpp> #include <polyvec/geometry/raster.hpp> #include <polyvec/geometry/angle.hpp> #include <polyvec/geometry/line.hpp> #include <polyvec/geometry/winding_number.hpp> #include <polyvec/polygon-tracer/error-metrics.hpp> // c++ stl #include <algorithm> #include <limits> // #include <Eigen/Geometry> using namespace Eigen; using namespace polyvec; using namespace std; NAMESPACE_BEGIN(polyfit) NAMESPACE_BEGIN(PathUtils) void order_clockwise(mat2x& P) { bool ccw; WindingNumber::compute_orientation(P, ccw); PF_LOGF("orientation %s", ccw ? "counter-clockwise" : "clockwise"); if (ccw) { Reverse(P); } } bool DegenerateClassifierAxisAligned1Px::should_skip_edge (const vec2& p0, const vec2& p1) { const vec2 dabs = (p1 - p0).cwiseAbs(); return dabs.maxCoeff() < 1. + PF_EPS && dabs.minCoeff() < PF_EPS; //return dabs.minCoeff() < PF_EPS; } bool DegenerateClassifier2Px::should_skip_edge(const vec2& p0, const vec2& p1) { const vec2 dabs = (p1 - p0).cwiseAbs(); return dabs.maxCoeff() < 2. + PF_EPS; } template <typename TDegenerateClassifier> int find_next_non_degenerate_corner( const Eigen::Matrix2Xd& P, const int vertex, // Current vertex const int vertex_next, // Next expected vertex const bool circular ) { if (!circular && vertex_next == P.cols() - 1) { return vertex; } const int direction = CircularDist(P, vertex, vertex_next) < CircularDist(P, vertex_next, vertex) ? +1 : -1; const vec2 p0 = P.col(vertex); const vec2 p1 = P.col(vertex_next); const vec2 p2 = CircularAt(P, vertex_next + direction); // If this actually happens, the conditionals below should be made into a for loop statement maybe? const bool is_next_degenerate = TDegenerateClassifier::should_skip_edge(p0, p1); const bool is_next_flat = AngleUtils::spanned_shortest(p0, p1, p2) > PV_FLAT_ANGLE_MIN; if (is_next_degenerate || is_next_flat) { return Circular(P, vertex_next + direction); } else { return vertex_next; } } //explicit instantiations template int find_next_non_degenerate_corner<DegenerateClassifierAxisAligned1Px>(const Eigen::Matrix2Xd& P, const int vertex, const int vertex_next, const bool circular); template int find_next_non_degenerate_corner<DegenerateClassifier2Px>(const Eigen::Matrix2Xd& P, const int vertex, const int vertex_next, const bool circular); void compute_hull_with_overlaps(const Eigen::Matrix2Xd& points, Eigen::Matrix2Xd& boundary, const int direction) { std::vector<int> convexities; PathUtils::compute_convexities(points, convexities); boundary.resize(Eigen::NoChange, 0); for (Index i = 0; i < (Index)convexities.size(); ++i) { if (convexities[i] == 0) { continue; } const Vector2d p = points.col(i); const Vector2d p_next = CircularAt(points, i + 1); const Vector2d p_prev = CircularAt(points, i - 1); const Vector2d cp = (p - p_next) * .5 + (p - p_prev) * .5; MatrixUtils::append(boundary, p + cp * convexities[i] * direction); } } double bounding_box_diagonal(const Eigen::Matrix2Xd& points) { Vector2d min(INFINITY, INFINITY), max(-INFINITY, -INFINITY); for (Index i = 0; i < points.cols(); ++i) { min = min.cwiseMin(points.col(i)); max = max.cwiseMax(points.col(i)); } return (max - min).norm(); } void compute_convexities(const Eigen::Matrix2Xd& points, std::vector<int>& convexities) { convexities.resize(points.cols(), 0); bool is_ccw; WindingNumber::compute_orientation(points, is_ccw); const int orientation = is_ccw ? -1 : +1; for (Index i = 0; i < points.cols(); ++i) { int j = (i + 1) % (int)points.cols(); int k = (i - 1 + (int)points.cols()) % (int)points.cols(); Vector2d tangent_i = (points.col(j) - points.col(i)).normalized(); Vector2d tangent_k = (points.col(i) - points.col(k)).normalized(); Vector2d normal_k = orientation * Vector2d(-tangent_k[1], tangent_k[0]); double dconvexity = -tangent_i.dot(normal_k); int iconvexity; if (abs(dconvexity) < 1e-5) { iconvexity = 0; } else if (dconvexity > 0) { iconvexity = 1; } else { iconvexity = -1; } convexities[i] = iconvexity; } } // Starting from a corner, it counts the number of flat vertices before reaching another corner int count_flat_vertices_before_transition(const std::vector<int>& convexities, const Eigen::Index from, const Eigen::Index direction) { assert_break(convexities[from] != 0); assert_break(direction == +1 || direction == -1); int distance = 0; while (++distance < convexities.size()) { const int next_index = (from + (distance * direction) + (int)convexities.size() * 2) % (int)convexities.size(); if (convexities[next_index] != 0) { break; } } return distance; } int count_transitions_between_vertices(const std::vector<int>& convexities, const Eigen::Index src, const Eigen::Index dst) { int vertex = Circular(convexities, src + 1); int transitions = 0; while (vertex != dst) { transitions += convexities[vertex] != 0 ? 1 : 0; vertex = Circular(convexities, vertex + 1); } return transitions; } bool is_edge_inflected(const Eigen::Vector2d& v0, const Eigen::Vector2d& v1, const Eigen::Vector2d& v2, const Eigen::Vector2d& v3) { const Vector2d vfrom2d = v1 - v0; const Vector2d vto2d = v3 - v2; const Vector2d sep2d = v2 - v1; const Vector3d vfrom(vfrom2d.x(), vfrom2d.y(), 0.); const Vector3d vto(vto2d.x(), vto2d.y(), 0.); const Vector3d sep(sep2d.x(), sep2d.y(), 0.); const Vector3d cross_from = sep.cross(vfrom); const Vector3d cross_to = sep.cross(vto); int sfrom = misc::sign(cross_from.z()); int sto = misc::sign(cross_to.z()); return sfrom * sto == 0 ? false : sfrom == sto; } Vertex end_of_convex_region(const std::vector<int>& C, const Vertex v0, const int d, bool circular) { PF_ASSERT(v0 >= 0 && v0 < (Vertex)C.size()); if (!circular && v0 == C.size() - 1) { return v0; } int c_last = C[v0]; Vertex v = Circular(C, v0 + d); while (true) { if (!circular && v == C.size() - 1) { return v; } if (C[v] != 0) { if (c_last == C[v]) { break; } c_last = C[v]; } v = Circular(C, v + d); } return v; } bool contains_closed(const int size, Vertex v0, Vertex v1, Vertex v, bool circular) { Vertex d01 = circular ? CircularDist(size, v0, v1) : (v1 - v0); Vertex d1 = circular ? CircularDist(size, v, v1) : (v1 - v); return d1 <= d01; } bool contains_closed(const mat2x& P, Vertex v0, Vertex v1, Vertex v, bool circular) { return contains_closed(P.cols(), v0, v1, v, circular); } bool contains_open(const mat2x& P, Vertex v0, Vertex v1, Vertex v, bool circular) { Vertex d01 = circular ? CircularDist(P, v0, v1) : (v1 - v0); Vertex d1 = circular ? CircularDist(P, v, v1) : (v1 - v); return d1 > 0 && d1 < d01; } bool has_equal_distance(const mat2x& P, Vertex v0, Vertex v, Vertex v1, bool circular) { if (!circular && (v < v0 || v > v1)) { return false; } return CircularDist(P, v0, v) == CircularDist(P, v, v1); } Eigen::Index next_transition_vertex(const std::vector<int>& convexities, const Eigen::Index from, const int direction, const bool circular) { Index vertex = Circular(convexities, from + direction); while (convexities[vertex] == 0) { vertex = Circular(convexities, vertex + direction); } return vertex; } Vertex distance_to_next_corner (const std::vector<int>& convexities, const Eigen::Index from, const int direction) { return direction > 0 ? CircularDist(convexities, from, next_transition_vertex(convexities, from, direction)) : CircularDist(convexities, next_transition_vertex(convexities, from, direction), from); } bool are_axis_aligned(const Eigen::Vector2d& p0, const Eigen::Vector2d& p1) { return abs((p0.x() - p1.x())) < constants::Eps || abs((p0.y() - p1.y())) < constants::Eps; } double shortest_angle_spanned(const vec2& p0, const vec2& p1, const vec2& p2) { return acos((p0 - p1).normalized().dot((p2 - p1).normalized())); } // todo: is a cross product really needed? bool are_consecutive_angles_opposite(const vec2& p0, const vec2& p1, const vec2& p2, const vec2& p3) { vec3 v01 = vec3::Zero(), v23 = vec3::Zero(), v12 = vec3::Zero(); v01.segment(0, 2) = p1 - p0; v23.segment(0, 2) = p3 - p2; v12.segment(0, 2) = p2 - p1; const int sign_xprev = misc::sign(v12.cross(v01).z()); const int sign_xnext = misc::sign(v12.cross(v23).z()); return sign_xprev * sign_xnext == 0 ? false : sign_xprev == sign_xnext; } /* OLD VERSION USING WYKOBY primitives vec2 distance_bounds_from_points(const mat2x& points, const mat2& p, vec2i vp) { Vertex voxel_src = vp(0); Vertex voxel_dst = vp(1); vec2 from = p.col(0); vec2 to = p.col(1); // This happens when the raster region has 1-pixel wide diagonals if (voxel_src != voxel_dst && GeomRaster::are_overlapping(from, to)) { return vec2(FLT_MAX, FLT_MAX); } const double WEAK_THR = .5; // This is perfectly valid. The reason is that generated nodes store the respective voxel // with the `-` sign in front. voxel_src = abs(voxel_src); voxel_dst = abs(voxel_dst); // // Finding how voxel midpoints to check for accuracy geom::segment edge_segment(from, to); const double edge_segment_len = edge_segment.length() + constants::Eps; ::polyvec::index n_voxels = points.cols(); ::polyvec::index num_nodes = -1; if (voxel_dst < voxel_src) { num_nodes = voxel_dst + n_voxels - voxel_src; } else { num_nodes = voxel_dst - voxel_src; } // // Keeping track of the maximum violation double max_in_accuracy_violation = -1.; double max_out_accuracy_violation = -1.; for (int i = 0; i < num_nodes; ++i) { ::polyvec::index v = (voxel_src + i) % n_voxels; ::polyvec::index next_v = (v + 1) % n_voxels; // only considering pixel points, not raster points, // todo: this shouldn't really be here if ((points.col(v) - points.col(next_v)).norm() < 1. - PF_EPS) { next_v = (v + 2) % n_voxels; PF_ASSERT((points.col(v) - points.col(next_v)).norm() >= 1. - PF_EPS); ++i; } Vector2d cur = points.col(v); Vector2d next = points.col(next_v); Vector2d midpoint = 0.5 * (cur + next); Vector2d normal = next - cur; normal = polyvec::util::normal_dir(normal).normalized(); // WEAK ACCURACY (<0.5) - FIRST TEST // We first check along the midpoint normal double d = std::numeric_limits<double>::quiet_NaN(); const vec2 n_abs = normal.cwiseAbs(); if (geom::ray_intersect(midpoint, normal, edge_segment, d)) { //PF_ASSERT(abs(d - d2) < 1e-4 ||abs(d + d2) < 1e-4); if (std::abs(d) >= WEAK_THR) { d = std::numeric_limits<double>::quiet_NaN(); } } if (std::isnan(d)) { // STRONG ACCURACY (>=0.5 to 0.5+slack) - SECOND TEST // Accuracy is checked as distance from the offset midpoint and its projection on the segment real2 off_midpoint_out = midpoint + 0.5 * normal; real2 off_midpoint_in = midpoint - 0.5 * normal; double dist_out = -1; double dist_in = -1; real2 out_proj = geom::project(off_midpoint_out, edge_segment); real2 in_proj = geom::project(off_midpoint_in, edge_segment); // Is the point on the line ? if (!geom::point_on_line(edge_segment, out_proj) && !geom::point_on_line(edge_segment, in_proj)) { //printf("edge (%f %f) (%f %f)\n", edge_segment.src(0), edge_segment.src(1), edge_segment.dst(0), edge_segment.dst(1)); //printf("out proj %f %f\n", out_proj(0), out_proj(1)); //printf("in proj %f %f\n", in_proj(0), in_proj(1)); return vec2(FLT_MAX, FLT_MAX); } real2 d_out = (out_proj - off_midpoint_out).cwiseAbs(); real2 d_in = (in_proj - off_midpoint_in).cwiseAbs(); dist_out = ::std::max(d_out.x(), d_out.y()); dist_in = ::std::max(d_in.x(), d_in.y()); assert_break(dist_out >= 0.); assert_break(dist_in >= 0.); if (dist_out < dist_in) { d = abs(.5 + dist_out); } else { d = -abs(.5 + dist_in); } } if (d > 0) { max_out_accuracy_violation = max(max_out_accuracy_violation, abs(d)); } else { max_in_accuracy_violation = max(max_in_accuracy_violation, abs(d)); } } double accuracy_in = 0.; double accuracy_out = 0.; if (max_out_accuracy_violation > 0) { accuracy_out = max_out_accuracy_violation; } if (max_in_accuracy_violation > 0) { accuracy_in = max_in_accuracy_violation; } return vec2(std::min(accuracy_in, accuracy_out), std::max(accuracy_in, accuracy_out)); } bool edge_is_within_relaxed_distance_bounds(const mat2x& P, const int vsrc, const int vdst) { mat2 e; e.col(0) = P.col(vsrc); e.col(1) = P.col(vdst); const vec2 d_error = PathUtils::distance_bounds_from_points(P, e, {vsrc, vdst}); return ErrorMetrics::accuracy_within_bounds_relaxed(d_error.minCoeff(), d_error.maxCoeff()); } */ // returns true if exp is the first vertex encountered traversing the polygon P from i in direction d bool points_in_same_partition(const mat2x& P, Vertex i, Vertex exp, Vertex fail, int d) { Vertex v = i + d; while (v != fail && v != i) { if (v == exp) { return true; } v = Circular(P, v + d); } return false; } Vertex opposite(const Eigen::Index& size, const Eigen::Index& v, const Eigen::Index& vsym) { if (CircularDist(size, vsym, v) < CircularDist(size, v, vsym )) { return Circular(size, vsym - 1); } else { return Circular(size, vsym + 1); } } void order(const mat2x& P, std::vector<Vertex>& V, Vertex vstart, bool circular) { // todo: test PF_ASSERT(circular); std::vector<Vertex> Vord; Vertex prev = vstart; while (Vord.size() < V.size()) { Vertex dmin = numeric_limits<Vertex>::max(); Vord.emplace_back(-1); // finding the next closest vertex in the path for (int i = 0; i < V.size(); ++i) { const Vertex d = CircularDist(P, vstart, V[i]); const bool exists = find(Vord.begin(), Vord.end(), V[i]) != Vord.end(); if (!exists && d < dmin) { dmin = d; Vord.back() = V[i]; } } PF_ASSERT(Vord.back() != -1); } V = std::move(Vord); } double angle_at_corner( const mat2x& B, const vecXi& P, const int v, const bool circular ) { if (!circular && (v == 0 || v == P.size() - 1)) { return 0.; } return AngleUtils::spanned_shortest( B.col(CircularAt(P, v - 1)), B.col(CircularAt(P, v)), B.col(CircularAt(P, v + 1)) ); } int count_degenerate_edges_exclusive( const mat2x& P, // raster boundary const mat2xi& E, // exceptions const bool circular ) { Vertex off = circular ? 0 : 1; (void)off; int count = 0; for (int i = 0; i < P.cols(); ++i) { if (!circular && (i == 0 || i >= P.cols() - 1)) { continue; } // testing if any of the two edges is contained in the intervals to exclude bool exclude = false; for (int j = 0; j < E.cols(); ++j) { if (PathUtils::contains_open(P, E(0, j), E(1, j), i, circular)) { exclude = true; break; } } if (exclude) { continue; } // testing inflection + length 1 const vec2 p0p = CircularAt(P, i - 1); const vec2 p0 = P.col(i); const vec2 p1 = CircularAt(P, i + 1); const vec2 p1n = CircularAt(P, i + 2); const bool is_short_aa = PathUtils::are_axis_aligned(p0, p1) && (p1 - p0).norm() < 1. + 1e-4; const bool is_inflection = AngleUtils::have_opposite_convexity(p0p, p0, p1, p1n); if (is_short_aa && is_inflection) { ++count; } } return count; } Eigen::Index find_closest_corner_before_strict( const mat2x& B, // list of points const vecXi& P, // polygon vertices const Eigen::Index q // corner limit (index to B) ) { Index min_d = numeric_limits<Index>::max(); Index min_v = -1; for (Index i = 0; i < P.size(); ++i) { const Index d = CircularDist(B, P(i), q); if (d > 0 && d < min_d) { min_d = d; min_v = i; } } return min_v; } // Given a list of points and a list of vertices with the same orientation, it finds the first // vertex of P which lies after the queried point, excluding the point itself. Eigen::Index find_closest_corner_after_strict( const mat2x& B, // list of points const vecXi& P, // polygon vertices const Eigen::Index q // corner limit (index to B) ) { Index min_d = numeric_limits<Index>::max(); Index min_v = -1; for (Index i = 0; i < P.size(); ++i) { const Index d = CircularDist(B, q, P(i)); if (d > 0 && d < min_d) { min_d = d; min_v = i; } } return min_v; } NAMESPACE_END(PathUtils) NAMESPACE_END(polyvec)
28.77931
170
0.663671
[ "geometry", "vector" ]
cbbb1fa35ae79f50c213f84c8b5bb7ab96ce1b62
4,248
cpp
C++
Level Ancestor Query (LA-problem)/Ladders & Jump pointers:<O(nlog(n),1)>.cpp
yokeshrana/Fast_Algorithms_in_Data_Structures
2346fee16c6c3ffceac7cb79b1f449b4d8dc9df2
[ "MIT" ]
4
2021-01-15T16:30:48.000Z
2021-08-12T03:17:00.000Z
Level Ancestor Query (LA-problem)/Ladders & Jump pointers:<O(nlog(n),1)>.cpp
andy489/Fast_Algorithms_in_Data_Structures
0f28a75030df3367902f0aa859a34096ea2b2582
[ "MIT" ]
null
null
null
Level Ancestor Query (LA-problem)/Ladders & Jump pointers:<O(nlog(n),1)>.cpp
andy489/Fast_Algorithms_in_Data_Structures
0f28a75030df3367902f0aa859a34096ea2b2582
[ "MIT" ]
2
2021-02-24T14:50:08.000Z
2021-02-28T17:39:41.000Z
// github.com/andy489 #include <iostream> #include <vector> #include <list> using namespace std; #define ios ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr) #define pb push_back int n, leaves; vector<list<int>> adj, AL; // adjacency list, All Leaves vector<int> par, dep, SL, mark, indexP, flog; // parent, depth, Sorted leaves, max/long-Path index, floor log vector<vector<int>> P, L, jump; // P = max/long-paths, L = ladders vector<int> traversal; // shortest path from root to current node void pre() { flog.resize(n); for (int i = 2; i <= n; ++i) flog[i] = flog[i / 2] + 1; } void init() { // read tree from file cin>>n; adj.resize(n+1); int m,c; for(int i = 1;i<=n;++i){ cin>>m; while(m--){ cin>>c; adj[i].pb(c); adj[c].pb(i); } } par.resize(n + 1), dep.resize(n + 1, -1); AL.resize(n), mark.resize(n + 1), indexP.resize(n + 1); traversal.reserve(n); // making traversal vector efficient for a stack (no resizing) jump.resize(n + 1); pre(); } void fillJumps(int u) { if (u == 1) return; int l = (int) traversal.size() - 1; jump[u].resize(flog[l] + 1); int k = 0, j = 1; while (j <= l) { jump[u][k++] = traversal[l - j]; j = (j << 1); } } void dfs(int u = 1, int p = 0) { par[u] = p; // parent function fill dep[u] = dep[p] + 1; // depth function fill traversal.pb(u); // traversal path fill if (adj[u].size() == 1) AL[dep[u]].pb(u), leaves++, fillJumps(u);; // All Leaves array of lists for (const int &child:adj[u]) { if (child == p) continue; dfs(child, u); traversal.pop_back(); } } void counting() { SL.resize(leaves); // Sorted Leaves (decreasing) int k = 0; for (int d = n - 1; d >= 0; --d) { while (!AL[d].empty()) { auto it = --AL[d].end(); int l = *it; AL[d].erase(it), SL[k++] = l; } } } void maxPathsDecomposition() { for (int l = 0; l <= leaves - 1; ++l) { vector<int> currMaxPath; currMaxPath.reserve(20); int v = SL[l]; while (v && !mark[v]) { currMaxPath.pb(v); indexP[v] = l; mark[v] = true; v = par[v]; } P.pb(currMaxPath); // P = Max Paths Decomposition } } void ladders() { L.resize(leaves); // we start from the second path, the first contains the root L[0] = P[0]; for (int i = 1; i < leaves; ++i) { int SIZE = (int)P[i].size(); L[i].reserve(2 * SIZE + 1); L[i].resize(SIZE); int j = 0; for (; j < SIZE; ++j) { L[i][j] = P[i][j]; } int v = par[P[i].back()]; L[i].pb(v); while (SIZE-- && par[v]) { v = par[v]; L[i].pb(v); } } } int LAQ_leaf(int l, int d) { int k = flog[d]; int u = jump[l][flog[d]]; // jump to a vertex with height at least 2^k int ind = indexP[u]; // index of long-path with at least 2^k nodes int height = dep[L[ind][0]] - dep[u]; // height of node u in ladder int searched = height + d - (1 << k); // we are sure that it is in that ladder return L[ind][searched]; } int LAQ_const(int v, int d) { if (d == 0) return v; if (d > dep[v]) return -1; if (d == 1) return par[v]; int i = indexP[v]; // index to long-path, where v is int l = L[indexP[v]][0]; // leaf node (first node) in ladder/long-path int height = dep[l] - dep[v]; // height of node v in ladder if (height + d < L[i].size()) return L[i][height + d]; // return the searched ancestor if in the ladder return LAQ_leaf(l, height + d); // query a leaf (1 jump and 1 ladder) } void solve() { int q, v, d; cout << "Enter number of queries of the form \"v d\": "; cin >> q; cout<<"Enter query \"v d\":\n"; while (q--) { cin >> v >> d; int ans = LAQ_const(v, d); ans == -1 ? cout << "no such ancestor\n" : cout << ans << '\n'; } } int main() { ios; freopen("input.txt", "r", stdin); init(); dfs(); counting(); maxPathsDecomposition(); ladders(); solve(); return 0; }
27.057325
109
0.508239
[ "vector" ]
cbc1620c23324238dff215f82196efe201250896
2,728
cc
C++
roofnet/sr/txcountmetric.cc
kohler/click-packages
cec70da7cf460548ef08f1ddad6924db29d5c0c5
[ "MIT" ]
13
2015-02-26T23:12:09.000Z
2021-04-18T04:37:12.000Z
roofnet/sr/txcountmetric.cc
kohoumas/click-packages
6bb5c4ba286e5dbc74efd1708921d530425691f6
[ "MIT" ]
null
null
null
roofnet/sr/txcountmetric.cc
kohoumas/click-packages
6bb5c4ba286e5dbc74efd1708921d530425691f6
[ "MIT" ]
7
2015-08-25T09:29:41.000Z
2021-04-18T04:37:13.000Z
/* * txcountmetric.{cc,hh} -- estimated transmission count (`TXCount') metric * * Copyright (c) 2003 Massachusetts Institute of Technology * * 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, subject to the conditions * listed in the Click LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Click LICENSE file; the license in that file is * legally binding. */ #include <click/config.h> #include <click/confparse.hh> #include <click/error.hh> #include <click/straccum.hh> #include "txcountmetric.hh" #include "ettstat.hh" #include <elements/wifi/linktable.hh> CLICK_DECLS #define max(a, b) ((a) > (b) ? (a) : (b)) #define min(a, b) ((a) < (b) ? (a) : (b)) TXCountMetric::TXCountMetric() : LinkMetric(), _link_table(0) { } TXCountMetric::~TXCountMetric() { } void * TXCountMetric::cast(const char *n) { if (strcmp(n, "TXCountMetric") == 0) return (TXCountMetric *) this; else if (strcmp(n, "LinkMetric") == 0) return (LinkMetric *) this; else return 0; } int TXCountMetric::configure(Vector<String> &conf, ErrorHandler *errh) { int res = cp_va_kparse(conf, this, errh, "LT", 0, cpElement, &_link_table, cpEnd); if (res < 0) return res; if (_link_table == 0) { click_chatter("%{element}: no LTelement specified", this); } if (_link_table && _link_table->cast("LinkTable") == 0) { return errh->error("LinkTable element is not a LinkTable"); } return 0; } void TXCountMetric::update_link(IPAddress from, IPAddress to, Vector<RateSize>, Vector<int> fwd, Vector<int> rev, uint32_t seq) { int metric = 9999; if (fwd.size() && rev.size() && fwd[0] && rev[0]) { metric = 100 * 100 * 100 / (fwd[0] * rev[0]); } /* update linktable */ if (metric && _link_table && !_link_table->update_link(from, to, seq, 0, metric)) { click_chatter("%{element} couldn't update link %s > %d > %s\n", this, from.unparse().c_str(), metric, to.unparse().c_str()); } if (metric && _link_table && !_link_table->update_link(to, from, seq, 0, metric)){ click_chatter("%{element} couldn't update link %s < %d < %s\n", this, from.unparse().c_str(), metric, to.unparse().c_str()); } } EXPORT_ELEMENT(TXCountMetric) ELEMENT_REQUIRES(bitrate) CLICK_ENDDECLS
25.735849
77
0.653226
[ "vector" ]
cbc446a19418fdfe1f2e62f47e3a6a59d5b19e56
17,367
cxx
C++
main/basic/source/sbx/sbxvar.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/basic/source/sbx/sbxvar.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/basic/source/sbx/sbxvar.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_basic.hxx" #include <tools/stream.hxx> #include "svl/brdcst.hxx" #include <basic/sbx.hxx> #include <basic/sbxbase.hxx> #include "sbxres.hxx" #include "sbxconv.hxx" #include <math.h> #include <ctype.h> #include "com/sun/star/uno/XInterface.hpp" using namespace com::sun::star::uno; ///////////////////////////// SbxVariable ////////////////////////////// TYPEINIT1(SbxVariable,SbxValue) TYPEINIT1(SbxHint,SfxSimpleHint) extern sal_uInt32 nVarCreator; // in SBXBASE.CXX, fuer LoadData() #ifdef DBG_UTIL static sal_uIntPtr nVar = 0; #endif ///////////////////////////// SbxVariableImpl //////////////////////////// class SbxVariableImpl { friend class SbxVariable; String m_aDeclareClassName; Reference< XInterface > m_xComListener; StarBASIC* m_pComListenerParentBasic; SbxVariableImpl( void ) : m_pComListenerParentBasic( NULL ) {} SbxVariableImpl( const SbxVariableImpl& r ) : m_aDeclareClassName( r.m_aDeclareClassName ) , m_xComListener( r.m_xComListener ) , m_pComListenerParentBasic( r.m_pComListenerParentBasic ) { } }; ///////////////////////////// Konstruktoren ////////////////////////////// SbxVariable::SbxVariable() : SbxValue() { mpSbxVariableImpl = NULL; pCst = NULL; pParent = NULL; nUserData = 0; nHash = 0; #ifdef DBG_UTIL DbgOutf( "SbxVariable::Ctor %lx=%ld", (void*)this, ++nVar ); GetSbxData_Impl()->aVars.Insert( this, LIST_APPEND ); #endif } void registerComListenerVariableForBasic( SbxVariable* pVar, StarBASIC* pBasic ); SbxVariable::SbxVariable( const SbxVariable& r ) : SvRefBase( r ), SbxValue( r ), mpPar( r.mpPar ), pInfo( r.pInfo ) { mpSbxVariableImpl = NULL; if( r.mpSbxVariableImpl != NULL ) { mpSbxVariableImpl = new SbxVariableImpl( *r.mpSbxVariableImpl ); if( mpSbxVariableImpl->m_xComListener.is() ) registerComListenerVariableForBasic( this, mpSbxVariableImpl->m_pComListenerParentBasic ); } pCst = NULL; if( r.CanRead() ) { pParent = r.pParent; nUserData = r.nUserData; maName = r.maName; nHash = r.nHash; } else { pParent = NULL; nUserData = 0; nHash = 0; } #ifdef DBG_UTIL static sal_Char const aCellsStr[] = "Cells"; if ( maName.EqualsAscii( aCellsStr ) ) maName.AssignAscii( aCellsStr, sizeof( aCellsStr )-1 ); DbgOutf( "SbxVariable::Ctor %lx=%ld", (void*)this, ++nVar ); GetSbxData_Impl()->aVars.Insert( this, LIST_APPEND ); #endif } SbxVariable::SbxVariable( SbxDataType t, void* p ) : SbxValue( t, p ) { mpSbxVariableImpl = NULL; pCst = NULL; pParent = NULL; nUserData = 0; nHash = 0; #ifdef DBG_UTIL DbgOutf( "SbxVariable::Ctor %lx=%ld", (void*)this, ++nVar ); GetSbxData_Impl()->aVars.Insert( this, LIST_APPEND ); #endif } void removeDimAsNewRecoverItem( SbxVariable* pVar ); SbxVariable::~SbxVariable() { #ifdef DBG_UTIL ByteString aBStr( (const UniString&)maName, RTL_TEXTENCODING_ASCII_US ); DbgOutf( "SbxVariable::Dtor %lx (%s)", (void*)this, aBStr.GetBuffer() ); static sal_Char const aCellsStr[] = "Cells"; if ( maName.EqualsAscii( aCellsStr ) ) maName.AssignAscii( aCellsStr, sizeof( aCellsStr )-1 ); GetSbxData_Impl()->aVars.Remove( this ); #endif if( IsSet( SBX_DIM_AS_NEW )) removeDimAsNewRecoverItem( this ); delete mpSbxVariableImpl; delete pCst; } ////////////////////////////// Broadcasting ////////////////////////////// SfxBroadcaster& SbxVariable::GetBroadcaster() { if( !pCst ) pCst = new SfxBroadcaster; return *pCst; } // Eines Tages kann man vielleicht den Parameter 0 schleifen, // dann entfaellt die Kopiererei... void SbxVariable::Broadcast( sal_uIntPtr nHintId ) { if( pCst && !IsSet( SBX_NO_BROADCAST ) && StaticIsEnabledBroadcasting() ) { // Da die Methode von aussen aufrufbar ist, hier noch einmal // die Berechtigung testen if( nHintId & SBX_HINT_DATAWANTED ) if( !CanRead() ) return; if( nHintId & SBX_HINT_DATACHANGED ) if( !CanWrite() ) return; // Weitere Broadcasts verhindern SfxBroadcaster* pSave = pCst; pCst = NULL; sal_uInt16 nSaveFlags = GetFlags(); SetFlag( SBX_READWRITE ); if( mpPar.Is() ) // this, als Element 0 eintragen, aber den Parent nicht umsetzen! mpPar->GetRef( 0 ) = this; pSave->Broadcast( SbxHint( nHintId, this ) ); delete pCst; // wer weiss schon, auf welche Gedanken mancher kommt? pCst = pSave; SetFlags( nSaveFlags ); } } SbxInfo* SbxVariable::GetInfo() { if( !pInfo ) { Broadcast( SBX_HINT_INFOWANTED ); if( pInfo.Is() ) SetModified( sal_True ); } return pInfo; } void SbxVariable::SetInfo( SbxInfo* p ) { pInfo = p; } void SbxVariable::SetParameters( SbxArray* p ) { mpPar = p; } /////////////////////////// Name der Variablen /////////////////////////// void SbxVariable::SetName( const XubString& rName ) { maName = rName; nHash = MakeHashCode( rName ); } const XubString& SbxVariable::GetName( SbxNameType t ) const { static char cSuffixes[] = " %&!#@ $"; if( t == SbxNAME_NONE ) return maName; // Parameter-Infos anfordern (nicht fuer Objekte) ((SbxVariable*)this)->GetInfo(); // Nix anfuegen, wenn einfache Property (keine leeren Klammern) if( !pInfo || ( !pInfo->aParams.Count() && GetClass() == SbxCLASS_PROPERTY ) ) return maName; xub_Unicode cType = ' '; XubString aTmp( maName ); // Kurzer Typ? Dann holen, evtl. ist dieser 0. SbxDataType et = GetType(); if( t == SbxNAME_SHORT_TYPES ) { if( et <= SbxSTRING ) cType = cSuffixes[ et ]; if( cType != ' ' ) aTmp += cType; } aTmp += '('; for( sal_uInt16 i = 0; i < pInfo->aParams.Count(); i++ ) { const SbxParamInfo* q = pInfo->aParams.GetObject( i ); int nt = q->eType & 0x0FFF; if( i ) aTmp += ','; if( q->nFlags & SBX_OPTIONAL ) aTmp += String( SbxRes( STRING_OPTIONAL ) ); if( q->eType & SbxBYREF ) aTmp += String( SbxRes( STRING_BYREF ) ); aTmp += q->aName; cType = ' '; // Kurzer Typ? Dann holen, evtl. ist dieser 0. if( t == SbxNAME_SHORT_TYPES ) { if( nt <= SbxSTRING ) cType = cSuffixes[ nt ]; } if( cType != ' ' ) { aTmp += cType; if( q->eType & SbxARRAY ) aTmp.AppendAscii( "()" ); } else { if( q->eType & SbxARRAY ) aTmp.AppendAscii( "()" ); // langer Typ? if( t != SbxNAME_SHORT ) { aTmp += String( SbxRes( STRING_AS ) ); if( nt < 32 ) aTmp += String( SbxRes( sal::static_int_cast< sal_uInt16 >( STRING_TYPES + nt ) ) ); else aTmp += String( SbxRes( STRING_ANY ) ); } } } aTmp += ')'; // Langer Typ? Dann holen if( t == SbxNAME_LONG_TYPES && et != SbxEMPTY ) { aTmp += String( SbxRes( STRING_AS ) ); if( et < 32 ) aTmp += String( SbxRes( sal::static_int_cast< sal_uInt16 >( STRING_TYPES + et ) ) ); else aTmp += String( SbxRes( STRING_ANY ) ); } ((SbxVariable*) this)->aToolString = aTmp; return aToolString; } // Einen simplen Hashcode erzeugen: Es werden die ersten 6 Zeichen gewertet. sal_uInt16 SbxVariable::MakeHashCode( const XubString& rName ) { sal_uInt16 n = 0; sal_uInt16 nLen = rName.Len(); if( nLen > 6 ) nLen = 6; const xub_Unicode* p = rName.GetBuffer(); while( nLen-- ) { sal_uInt8 c = (sal_uInt8)*p; p++; // Falls wir ein Schweinezeichen haben, abbrechen!! if( c >= 0x80 ) return 0; n = sal::static_int_cast< sal_uInt16 >( ( n << 3 ) + toupper( c ) ); } return n; } ////////////////////////////// Operatoren //////////////////////////////// SbxVariable& SbxVariable::operator=( const SbxVariable& r ) { SbxValue::operator=( r ); delete mpSbxVariableImpl; if( r.mpSbxVariableImpl != NULL ) { mpSbxVariableImpl = new SbxVariableImpl( *r.mpSbxVariableImpl ); if( mpSbxVariableImpl->m_xComListener.is() ) registerComListenerVariableForBasic( this, mpSbxVariableImpl->m_pComListenerParentBasic ); } else mpSbxVariableImpl = NULL; return *this; } //////////////////////////////// Konversion //////////////////////////////// SbxDataType SbxVariable::GetType() const { if( aData.eType == SbxOBJECT ) return aData.pObj ? aData.pObj->GetType() : SbxOBJECT; else if( aData.eType == SbxVARIANT ) return aData.pObj ? aData.pObj->GetType() : SbxVARIANT; else return aData.eType; } SbxClassType SbxVariable::GetClass() const { return SbxCLASS_VARIABLE; } void SbxVariable::SetModified( sal_Bool b ) { if( IsSet( SBX_NO_MODIFY ) ) return; SbxBase::SetModified( b ); if( pParent && pParent != this ) //??? HotFix: Rekursion raus MM pParent->SetModified( b ); } void SbxVariable::SetParent( SbxObject* p ) { #ifdef DBG_UTIL // wird der Parent eines SbxObjects gesetzt? if ( p && ISA(SbxObject) ) { // dann mu\s dieses auch Child vom neuen Parent sein sal_Bool bFound = sal_False; SbxArray *pChilds = p->GetObjects(); if ( pChilds ) { for ( sal_uInt16 nIdx = 0; !bFound && nIdx < pChilds->Count(); ++nIdx ) bFound = ( this == pChilds->Get(nIdx) ); } if ( !bFound ) { String aMsg = String::CreateFromAscii( "dangling: [" ); aMsg += GetName(); aMsg.AppendAscii( "].SetParent([" ); aMsg += p->GetName(); aMsg.AppendAscii( "])" ); ByteString aBStr( (const UniString&)aMsg, RTL_TEXTENCODING_ASCII_US ); DbgOut( aBStr.GetBuffer(), DBG_OUT_WARNING, __FILE__, __LINE__); } } #endif pParent = p; } SbxVariableImpl* SbxVariable::getImpl( void ) { if( mpSbxVariableImpl == NULL ) mpSbxVariableImpl = new SbxVariableImpl(); return mpSbxVariableImpl; } const String& SbxVariable::GetDeclareClassName( void ) { SbxVariableImpl* pImpl = getImpl(); return pImpl->m_aDeclareClassName; } void SbxVariable::SetDeclareClassName( const String& rDeclareClassName ) { SbxVariableImpl* pImpl = getImpl(); pImpl->m_aDeclareClassName = rDeclareClassName; } void SbxVariable::SetComListener( ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > xComListener, StarBASIC* pParentBasic ) { SbxVariableImpl* pImpl = getImpl(); pImpl->m_xComListener = xComListener; pImpl->m_pComListenerParentBasic = pParentBasic; registerComListenerVariableForBasic( this, pParentBasic ); } void SbxVariable::ClearComListener( void ) { SbxVariableImpl* pImpl = getImpl(); pImpl->m_xComListener.clear(); } ////////////////////////////// Laden/Speichern ///////////////////////////// sal_Bool SbxVariable::LoadData( SvStream& rStrm, sal_uInt16 nVer ) { sal_uInt16 nType; sal_uInt8 cMark; rStrm >> cMark; if( cMark == 0xFF ) { if( !SbxValue::LoadData( rStrm, nVer ) ) return sal_False; rStrm.ReadByteString( maName, RTL_TEXTENCODING_ASCII_US ); sal_uInt32 nTemp; rStrm >> nTemp; nUserData = nTemp; } else { rStrm.SeekRel( -1L ); rStrm >> nType; rStrm.ReadByteString( maName, RTL_TEXTENCODING_ASCII_US ); sal_uInt32 nTemp; rStrm >> nTemp; nUserData = nTemp; // Korrektur: Alte Methoden haben statt SbxNULL jetzt SbxEMPTY if( nType == SbxNULL && GetClass() == SbxCLASS_METHOD ) nType = SbxEMPTY; SbxValues aTmp; String aTmpString; ::rtl::OUString aVal; aTmp.eType = aData.eType = (SbxDataType) nType; aTmp.pOUString = &aVal; switch( nType ) { case SbxBOOL: case SbxERROR: case SbxINTEGER: rStrm >> aTmp.nInteger; break; case SbxLONG: rStrm >> aTmp.nLong; break; case SbxSINGLE: { // Floats als ASCII rStrm.ReadByteString( aTmpString, RTL_TEXTENCODING_ASCII_US ); double d; SbxDataType t; if( ImpScan( aTmpString, d, t, NULL ) != SbxERR_OK || t == SbxDOUBLE ) { aTmp.nSingle = 0; return sal_False; } aTmp.nSingle = (float) d; break; } case SbxDATE: case SbxDOUBLE: { // Floats als ASCII rStrm.ReadByteString( aTmpString, RTL_TEXTENCODING_ASCII_US ); SbxDataType t; if( ImpScan( aTmpString, aTmp.nDouble, t, NULL ) != SbxERR_OK ) { aTmp.nDouble = 0; return sal_False; } break; } case SbxSTRING: rStrm.ReadByteString( aTmpString, RTL_TEXTENCODING_ASCII_US ); aVal = aTmpString; break; case SbxEMPTY: case SbxNULL: break; default: aData.eType = SbxNULL; DBG_ASSERT( sal_False, "Unsupported data type loaded" ); return sal_False; } // Wert putten if( nType != SbxNULL && nType != SbxEMPTY && !Put( aTmp ) ) return sal_False; } rStrm >> cMark; // cMark ist auch eine Versionsnummer! // 1: initial version // 2: mit nUserData if( cMark ) { if( cMark > 2 ) return sal_False; pInfo = new SbxInfo; pInfo->LoadData( rStrm, (sal_uInt16) cMark ); } // Privatdaten nur laden, wenn es eine SbxVariable ist if( GetClass() == SbxCLASS_VARIABLE && !LoadPrivateData( rStrm, nVer ) ) return sal_False; ((SbxVariable*) this)->Broadcast( SBX_HINT_DATACHANGED ); nHash = MakeHashCode( maName ); SetModified( sal_True ); return sal_True; } sal_Bool SbxVariable::StoreData( SvStream& rStrm ) const { rStrm << (sal_uInt8) 0xFF; // Marker sal_Bool bValStore; if( this->IsA( TYPE(SbxMethod) ) ) { // #50200 Verhindern, dass Objekte, die zur Laufzeit als Return-Wert // in der Methode als Value gespeichert sind, mit gespeichert werden SbxVariable* pThis = (SbxVariable*)this; sal_uInt16 nSaveFlags = GetFlags(); pThis->SetFlag( SBX_WRITE ); pThis->SbxValue::Clear(); pThis->SetFlags( nSaveFlags ); // Damit die Methode in keinem Fall ausgefuehrt wird! // CAST, um const zu umgehen! pThis->SetFlag( SBX_NO_BROADCAST ); bValStore = SbxValue::StoreData( rStrm ); pThis->ResetFlag( SBX_NO_BROADCAST ); } else bValStore = SbxValue::StoreData( rStrm ); if( !bValStore ) return sal_False; // if( !SbxValue::StoreData( rStrm ) ) // return sal_False; rStrm.WriteByteString( maName, RTL_TEXTENCODING_ASCII_US ); rStrm << (sal_uInt32)nUserData; if( pInfo.Is() ) { rStrm << (sal_uInt8) 2; // Version 2: mit UserData! pInfo->StoreData( rStrm ); } else rStrm << (sal_uInt8) 0; // Privatdaten nur speichern, wenn es eine SbxVariable ist if( GetClass() == SbxCLASS_VARIABLE ) return StorePrivateData( rStrm ); else return sal_True; } ////////////////////////////// SbxInfo /////////////////////////////////// SbxInfo::SbxInfo() : aHelpFile(), nHelpId( 0 ), aParams() {} SbxInfo::SbxInfo( const String& r, sal_uInt32 n ) : aHelpFile( r ), nHelpId( n ), aParams() {} ////////////////////////////// SbxAlias ////////////////////////////////// SbxAlias::SbxAlias( const XubString& rName, SbxVariable* p ) : SbxVariable(), xAlias( p ) { SetName( rName ); SetFlags( p->GetFlags() ); SetFlag( SBX_DONTSTORE ); aData.eType = p->GetType(); StartListening( p->GetBroadcaster() ); } SbxAlias::SbxAlias( const SbxAlias& r ) : SvRefBase( r ), SbxVariable( r ), SfxListener( r ), xAlias( r.xAlias ) {} SbxAlias& SbxAlias::operator=( const SbxAlias& r ) { xAlias = r.xAlias; return *this; } SbxAlias::~SbxAlias() { if( xAlias.Is() ) EndListening( xAlias->GetBroadcaster() ); } void SbxAlias::Broadcast( sal_uIntPtr nHt ) { if( xAlias.Is() && StaticIsEnabledBroadcasting() ) { xAlias->SetParameters( GetParameters() ); if( nHt == SBX_HINT_DATAWANTED ) SbxVariable::operator=( *xAlias ); else if( nHt == SBX_HINT_DATACHANGED || nHt == SBX_HINT_CONVERTED ) *xAlias = *this; else if( nHt == SBX_HINT_INFOWANTED ) { xAlias->Broadcast( nHt ); pInfo = xAlias->GetInfo(); } } } void SbxAlias::SFX_NOTIFY( SfxBroadcaster&, const TypeId&, const SfxHint& rHint, const TypeId& ) { const SbxHint* p = PTR_CAST(SbxHint,&rHint); if( p && p->GetId() == SBX_HINT_DYING ) { xAlias.Clear(); // Alias loeschen? if( pParent ) pParent->Remove( this ); } } void SbxVariable::Dump( SvStream& rStrm, sal_Bool bFill ) { ByteString aBNameStr( (const UniString&)GetName( SbxNAME_SHORT_TYPES ), RTL_TEXTENCODING_ASCII_US ); rStrm << "Variable( " << ByteString::CreateFromInt64( (sal_uIntPtr) this ).GetBuffer() << "==" << aBNameStr.GetBuffer(); ByteString aBParentNameStr( (const UniString&)GetParent()->GetName(), RTL_TEXTENCODING_ASCII_US ); if ( GetParent() ) rStrm << " in parent '" << aBParentNameStr.GetBuffer() << "'"; else rStrm << " no parent"; rStrm << " ) "; // bei Object-Vars auch das Object ausgeben if ( GetValues_Impl().eType == SbxOBJECT && GetValues_Impl().pObj && GetValues_Impl().pObj != this && GetValues_Impl().pObj != GetParent() ) { rStrm << " contains "; ((SbxObject*) GetValues_Impl().pObj)->Dump( rStrm, bFill ); } else rStrm << endl; }
25.998503
117
0.646801
[ "object" ]
cbc58ec91b83deb5f284c4dca0c7a378438c0faa
16,801
hh
C++
src/fkvb/fdb_helper.hh
IBM/fkvb
f04b647e1f78dec7e73a7172ea234460e5c720e0
[ "Apache-2.0" ]
2
2021-09-30T13:44:14.000Z
2022-02-02T12:59:50.000Z
src/fkvb/fdb_helper.hh
IBM/fkvb
f04b647e1f78dec7e73a7172ea234460e5c720e0
[ "Apache-2.0" ]
null
null
null
src/fkvb/fdb_helper.hh
IBM/fkvb
f04b647e1f78dec7e73a7172ea234460e5c720e0
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2021 International Business Machines * All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Authors: Diego Didona (ddi@zurich.ibm.com), * */ #ifndef FDB_HELPER_HH #define FDB_HELPER_HH #include "defs.hh" #include <ticks.hh> static const int MAX_KEY_SIZE = 2048; extern thread_local char tx_sid[20]; //We use the params also for return value struct op_result { int rc; fdb_error_t err; uint64_t grv_time, commit_time; op_result(int r, fdb_error_t e) : rc(r), err(e), grv_time(0), commit_time(0) {} op_result(int r, fdb_error_t e, uint64_t grv, uint64_t com) : rc(r), err(e), grv_time(grv), commit_time(com) {} op_result(int r, fdb_error_t e, uint64_t grv) : rc(r), err(e), grv_time(grv), commit_time(0) {} }; struct op_params { }; struct op_params_get : public op_params { char *key; size_t key_size; char *buf; size_t buf_size; size_t size_read; size_t val_read; op_params_get(char *_key, size_t _key_size, char *_buf, size_t _buf_size) : key(_key), key_size(_key_size), buf(_buf), buf_size(_buf_size) {} }; struct op_params_clearall : public op_params { op_params_clearall() {} }; struct op_params_num_keys : public op_params { //https://stackoverflow.com/questions/20944784/why-is-conversion-from-string-constant-to-char-valid-in-c-but-invalid-in-c char const init_key = '\0';//"0"; char const end_key = '\xFF'; static const size_t offset = 1 << 10; //MUST be power of two size_t num_keys = 0; char last_key[MAX_KEY_SIZE]; int last_size; op_params_num_keys() { //We need a power-of-two offset b/c we halve it to find the size of the db if ((!offset) || (offset & (offset - 1))) { FATAL("Offset not power of 2: %zu", offset); } memcpy(last_key, &init_key, sizeof(init_key)); last_size = sizeof(init_key); } }; struct op_params_generic : public op_params { int num_op; bool *rw; char *keys; size_t *key_sizes; char **put_values; size_t *put_value_sizes; char *get_buffer; size_t get_buffer_size; size_t *read_values; std::vector<char *> read_values_ptr; FDBFuture **futures; op_params_generic(int _num_op, bool *_rw, char *_keys, size_t *_key_sizes, char **_put_values, size_t *_put_value_sizes, char *_get_buffer, size_t _get_buffer_size, size_t *_read_values, std::vector<char *> &_read_values_ptr, FDBFuture **_futures) : num_op(_num_op), rw(_rw), keys(_keys), key_sizes(_key_sizes), put_values(_put_values), put_value_sizes(_put_value_sizes), get_buffer(_get_buffer), get_buffer_size(_get_buffer_size), read_values(_read_values), read_values_ptr(_read_values_ptr), futures(_futures) {} }; struct op_params_put : public op_params { const char *key; size_t key_size; const char *value; size_t value_size; op_params_put(const char *_key, size_t _key_size, const char *_buf, size_t _buf_size) : key(_key), key_size(_key_size), value(_buf), value_size(_buf_size) {}; }; struct op_params_put_bulk : public op_params { const char *keys; size_t *key_sizes; const char *values; size_t *value_sizes; size_t num_ops; op_params_put_bulk(const char *_keys, size_t *_key_sizes, const char *_buf, size_t *_buf_size, size_t num) : keys(_keys), key_sizes(_key_sizes), values(_buf), value_sizes(_buf_size), num_ops(num) {}; }; enum fdb_ops { GRV = 0, COMMIT = 1, GENERIC=2, GET=3, PUT,DELETE=4, CLEAR_ALL=5, GET_NUM_KEYS=6, PUT_BULK=7 }; struct fdb_op_g { virtual op_result run(FDBTransaction *tr) = 0; virtual const char *str() = 0; virtual const fdb_ops op() = 0; virtual const bool is_ro()=0; }; template<typename param_type> struct fdb_op : public fdb_op_g { param_type *params; u64 cache_grv; fdb_op(param_type *p) : params(p),cache_grv(0) {}; fdb_op(param_type *p,u64 cachegrv) : params(p), cache_grv(cachegrv){}; virtual op_result run(FDBTransaction *tr) = 0; virtual const char *str() = 0; virtual const fdb_ops op() = 0; virtual const bool is_ro()=0; }; #define SNAPSHOT_READ 1 #define SERIALIZABLE_READ 0 struct fdb_op_clearall : public fdb_op<op_params_clearall> { fdb_op_clearall(op_params_clearall *p) : fdb_op<op_params_clearall>(p) {} op_result run(FDBTransaction *tr) { fdb_transaction_clear_range(tr, (uint8_t *) "", 0, (uint8_t *) "\xff", 1); return op_result(0, 0); } const char *str() { return "clear_all"; } const fdb_ops op() { return CLEAR_ALL; } const bool is_ro(){return false;} }; /* * Note for self. RYWTransactions are the one used. ThreadSafeTransactions are the wrapper */ struct fdb_op_generic : public fdb_op<op_params_generic> { fdb_op_generic(op_params_generic *p) : fdb_op<op_params_generic>(p) {} const char *str() { return "generic_op"; } const fdb_ops op() { return GENERIC; } const bool is_ro(){ if( params->num_op ==0) return true; int i; for(i=0;i<params->num_op;i++){ if(params->rw[i]) return false; } return true; } op_result run(FDBTransaction *tr) { int done = 0; int put_index = 0; int rc = 0; char *value_ptr = params->put_values[0], *key_ptr = params->keys; while (done < params->num_op) { if (params->rw[done]) { TRACE_FORMAT("%d PUTTING key %.*s on address(%p) with size %zu and value %.*s", done, (int) params->key_sizes[done], key_ptr, value_ptr, params->put_value_sizes[put_index], (int) params->put_value_sizes[put_index], value_ptr); fdb_transaction_set(tr, (uint8_t *) key_ptr, params->key_sizes[done], (uint8_t *) value_ptr, params->put_value_sizes[put_index]); put_index++; value_ptr = params->put_values[put_index];//params->put_value_sizes[put_index]; } else { TRACE_FORMAT("%s %d GETTING key %.*s", tx_sid, done, (int) params->key_sizes[done], key_ptr); params->futures[done] = fdb_transaction_get(tr, (uint8_t *) key_ptr, params->key_sizes[done], SERIALIZABLE_READ); } key_ptr += params->key_sizes[done]; done++; } done = 0; key_ptr = params->keys; while (done < params->num_op) { if (!params->rw[done]) { TRACE_FORMAT("%d GET CHECK", done); FDBFuture *f = params->futures[done]; fdb_error_t e = fdb_future_block_until_ready(f); if (e) { fdb_future_destroy(f); return op_result(0, e); } fdb_bool_t present; uint8_t const *outValue; int outValueLength; e = fdb_future_get_value(f, &present, &outValue, &outValueLength); fdb_future_destroy(f); if (e) { return op_result(0, e); } else { if (!present) { PRINT_FORMAT("WARNING: Value not found for key %.*s", (int) params->key_sizes[done], key_ptr); rc = 2; } else { TRACE_FORMAT("Read %s length %d", outValue, outValueLength); } } //ALL good, now we have to copy results to user supplied buffers // FIXME @ddi: copy to usr buffer TRACE_FORMAT("%.*s => %.*s", (int) params->key_sizes[done], key_ptr, outValueLength, (char *) outValue); } key_ptr += params->key_sizes[done]; done++; } return op_result(rc, 0); } }; /* Solution inspired from the discussion at https://forums.foundationdb.org/t/getting-the-number-of-key-value-pairs/189/4 Check also https://apple.github.io/foundationdb/developer-guide.html#key-selectors We use the get_key(k,offset) to get the single key at k+offset. We call the function from the start of the keyspace ('') until we get to the end of the range (special key ' ) and we sum the number of scanned keys in the meanwhile Note that an iteration of this algorithm may fail (e.g., a tx with many get_key can last way more than 5 sec). What we do is: we save the last key we tried to get and the number of keys read so far, and we restart a new transaction from that point Note that the restarting is transparent because it is done by the "run" function that we implement in the FDBKVstore (the errors returned in case a tx fail in this case are not critical, so the tx is retried transparently to this code) */ struct fdb_op_num_keys : public fdb_op<op_params_num_keys> { //#define RETRY_GETCOUNT fdb_op_num_keys(op_params_num_keys *p) : fdb_op<op_params_num_keys>(p) {} const char *str() { return "get_num_keys"; } const fdb_ops op() { return GET_NUM_KEYS; } op_result run(FDBTransaction *tr) { FDBFuture *f, *f_old = nullptr; uint8_t *last = (uint8_t * ) & params->last_key[0];// & params->init_key; uint8_t *out_value; int last_size = params->last_size; size_t it = 0; TRACE_FORMAT("GET_KEYS INIT: last %.*s of size %d", last_size, (char *) last, last_size); size_t off = params->offset; while (1) { TRACE_FORMAT("ITERATION %zu start %.*s Offset %zu", it, last_size, last, off); f = fdb_transaction_get_key(tr, (const uint8_t *) last, last_size, true, off, SNAPSHOT_READ); fdb_error_t e = fdb_future_block_until_ready(f); if (e) { TRACE_FORMAT("ERROR IN TX GETTING FUTURE"); //Remember to copy this before destroying the future, which holds the content of the variables memcpy(params->last_key, last, last_size); params->last_size = last_size; TRACE_FORMAT("NEXT last is going to be %.*s", (int) last_size, params->last_key); fdb_future_destroy(f); if (f_old != nullptr)fdb_future_destroy(f_old); return op_result(0, e); } int outValueLength; e = fdb_future_get_key(f, (const uint8_t **) &out_value, &outValueLength); if (e) { TRACE_FORMAT("ERROR IN FUTURE GETTING KEY"); //Remember to copy this before destroying the future, which holds the content of the variables memcpy(params->last_key, last, last_size); params->last_size = last_size; TRACE_FORMAT("NEXT last is going to be %.*s", (int) last_size, params->last_key); fdb_future_destroy(f); if (f_old != nullptr)fdb_future_destroy(f_old); return op_result(0, e); } if ((int) *out_value == 255) {//This is the end key apparently. //We have reached the end. There are two cases //1. We are out of range because our offset was too large. Then we halve the offset and continue //2. We have really reached the end. This condition is true if offset is 1. Then we return if (off == 1) { TRACE_FORMAT("End of scan at iteration %zu with %zu keys", it, params->num_keys); fdb_future_destroy(f); if (f_old != nullptr)fdb_future_destroy(f_old); return op_result(0, 0); } else { TRACE_FORMAT("Reached end of store. Halving offset"); off = off >> 1; //We keep the last and last_size at the current value } } else { TRACE_FORMAT("Out key %.*s of size %d", outValueLength, (char *) out_value, outValueLength); if (outValueLength == 1) { PRINT_FORMAT("actually a char %c %d", *out_value, (int) *out_value); } last = out_value; last_size = outValueLength; params->num_keys += off; TRACE_FORMAT("Keys now %zu", params->num_keys); } f_old = f; ++it; //We need to be able to reference last and last_size, which belong to the future of the just-past invocation //So we do not destroy it until we advance to a new base key } } const bool is_ro(){return true;} }; struct fdb_op_get : public fdb_op<op_params_get> { fdb_op_get(op_params_get *p) : fdb_op<op_params_get>(p) {}; const char *str() { return "get_op"; } const fdb_ops op() { return GET; } op_result run(FDBTransaction *tr) { int rc = 0; FDBFuture *f = fdb_transaction_get(tr, (uint8_t *) params->key, params->key_size, SERIALIZABLE_READ); fdb_error_t e = fdb_future_block_until_ready(f); if (e) { fdb_future_destroy(f); return op_result(0, e); } fdb_bool_t present; uint8_t const *outValue; int outValueLength; e = fdb_future_get_value(f, &present, &outValue, &outValueLength); fdb_future_destroy(f); if (e) { return op_result(0, e); } if (!present) { PRINT_FORMAT("WARNING: Value not found for key %.*s", (int) params->key_size, params->key); rc = 2; } else { //ALL good, now we have to copy results to user supplied buffers TRACE_FORMAT("Get key %s value %s size %d", params->key, outValue, outValueLength); params->val_read = outValueLength; params->size_read = (size_t) outValueLength > params->buf_size ? params->buf_size : outValueLength; memcpy(params->buf, outValue, params->size_read); } return op_result(rc, 0); } const bool is_ro(){return true;} }; struct fdb_op_put : public fdb_op<op_params_put> { fdb_op_put(op_params_put *p) : fdb_op<op_params_put>(p) {}; //fdb_op_put(op_params_put p) : fdb_op(p) {} const char *str() { return "put_op"; } const fdb_ops op() { return PUT; } op_result run(FDBTransaction *tr) { TRACE_FORMAT("PUTTING key %.*s %.*s size %zu", (int) params->key_size, params->key, (int) params->value_size, params->value, params->value_size); fdb_transaction_set(tr, (uint8_t * ) & params->key[0], params->key_size, (uint8_t *) params->value, params->value_size); return op_result(0, 0); } const bool is_ro(){return false;} }; struct fdb_op_put_bulk : public fdb_op<op_params_put_bulk> { fdb_op_put_bulk(op_params_put_bulk *p) : fdb_op<op_params_put_bulk>( p) {}; //fdb_op_put(op_params_put p) : fdb_op(p) {} const char *str() { return "put_op_bulk"; } const fdb_ops op() { return PUT_BULK; } const bool is_ro(){return false;} op_result run(FDBTransaction *tr) { u32 i; char *k = (char *) params->keys, *v = (char *) params->values; for (i = 0; i < params->num_ops; i++) { TRACE_FORMAT("PUTTING key %.*s %.*s size %zu", (int) params->key_size, params->key, (int) params->value_size, params->value, params->value_size); /* * Setting flags. Done every time bc apparently doing set resets the flags * https://forums.foundationdb.org/t/best-practices-for-bulk-load/422/6 */ fdb_error_t err = fdb_transaction_set_option(tr, FDB_TR_OPTION_NEXT_WRITE_NO_WRITE_CONFLICT_RANGE, nullptr, 0); if (err) { FATAL("%s", fdb_get_error(err)); } err = fdb_transaction_set_option(tr, FDB_TR_OPTION_READ_YOUR_WRITES_DISABLE, nullptr, 0); if (err) { FATAL("%s", fdb_get_error(err)); } fdb_transaction_set(tr, (uint8_t *) k, params->key_sizes[i], (uint8_t *) v, params->value_sizes[i]); k += params->key_sizes[i]; v += params->value_sizes[i]; } return op_result(0, 0); } }; #endif //FDB_HELPER_HH
35.296218
125
0.583001
[ "vector" ]
cbc96e719e0af4b855b1e17b3b5137b1f1f37462
13,913
cpp
C++
eval/src/vespa/eval/eval/node_types.cpp
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
null
null
null
eval/src/vespa/eval/eval/node_types.cpp
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
1
2021-03-31T22:24:20.000Z
2021-03-31T22:24:20.000Z
eval/src/vespa/eval/eval/node_types.cpp
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
1
2020-09-03T11:39:52.000Z
2020-09-03T11:39:52.000Z
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "check_type.h" #include "node_traverser.h" #include "node_types.h" #include <vespa/vespalib/util/stringfmt.h> #include <vespa/vespalib/util/classname.h> using vespalib::make_string_short::fmt; namespace vespalib::eval { namespace nodes { namespace { class State { private: const std::vector<ValueType> &_params; std::map<const Node *, ValueType> &_type_map; std::vector<vespalib::string> &_errors; public: State(const std::vector<ValueType> &params, std::map<const Node *, ValueType> &type_map, std::vector<vespalib::string> &errors) : _params(params), _type_map(type_map), _errors(errors) {} const ValueType &param_type(size_t idx) { assert(idx < _params.size()); return _params[idx]; } void bind(const ValueType &type, const Node &node) { auto pos = _type_map.find(&node); assert(pos == _type_map.end()); _type_map.emplace(&node, type); } const ValueType &type(const Node &node) { auto pos = _type_map.find(&node); assert(pos != _type_map.end()); return pos->second; } void add_error(const vespalib::string &msg) { _errors.push_back(msg); } }; struct TypeResolver : public NodeVisitor, public NodeTraverser { State state; TypeResolver(const std::vector<ValueType> &params_in, std::map<const Node *, ValueType> &type_map_out, std::vector<vespalib::string> &errors_out); ~TypeResolver(); const ValueType &param_type(size_t idx) { return state.param_type(idx); } void fail(const Node &node, const vespalib::string &msg, bool child_types = true) { auto str = fmt("%s: %s", vespalib::getClassName(node).c_str(), msg.c_str()); if (child_types) { str += ", child types: ["; for (size_t i = 0; i < node.num_children(); ++i) { if (i > 0) { str += ", "; } str += state.type(node.get_child(i)).to_spec(); } str += "]"; } state.add_error(str); state.bind(ValueType::error_type(), node); } void bind(const ValueType &type, const Node &node, bool check_error = true) { if (check_error && type.is_error()) { fail(node, "type resolving failed"); } else { state.bind(type, node); } } const ValueType &type(const Node &node) { return state.type(node); } void import_errors(const NodeTypes &types) { for (const auto &err: types.errors()) { state.add_error(fmt("[lambda]: %s", err.c_str())); } } void import_types(const NodeTypes &types) { types.each([&](const Node &node, const ValueType &type) { state.bind(type, node); }); } //------------------------------------------------------------------------- bool check_error(const Node &node) { for (size_t i = 0; i < node.num_children(); ++i) { if (type(node.get_child(i)).is_error()) { bind(ValueType::error_type(), node, false); return true; } } return false; } void resolve_op1(const Node &node) { bind(type(node.get_child(0)), node); } void resolve_op2(const Node &node) { bind(ValueType::join(type(node.get_child(0)), type(node.get_child(1))), node); } //------------------------------------------------------------------------- void visit(const Number &node) override { bind(ValueType::double_type(), node); } void visit(const Symbol &node) override { bind(param_type(node.id()), node, false); } void visit(const String &node) override { bind(ValueType::double_type(), node); } void visit(const In &node) override { resolve_op1(node); } void visit(const Neg &node) override { resolve_op1(node); } void visit(const Not &node) override { resolve_op1(node); } void visit(const If &node) override { bind(ValueType::either(type(node.true_expr()), type(node.false_expr())), node); } void visit(const Error &node) override { bind(ValueType::error_type(), node, false); } void visit(const TensorMap &node) override { resolve_op1(node); } void visit(const TensorJoin &node) override { resolve_op2(node); } void visit(const TensorMerge &node) override { bind(ValueType::merge(type(node.get_child(0)), type(node.get_child(1))), node); } void visit(const TensorReduce &node) override { auto my_type = type(node.get_child(0)).reduce(node.dimensions()); if (my_type.is_error()) { auto str = fmt("aggr: %s, dimensions: [", AggrNames::name_of(node.aggr())->c_str()); size_t i = 0; for (const auto &dimension: node.dimensions()) { if (i++ > 0) { str += ","; } str += dimension; } str += "]"; fail(node, str); } else { bind(my_type, node); } } void visit(const TensorRename &node) override { auto my_type = type(node.get_child(0)).rename(node.from(), node.to()); if (my_type.is_error()) { auto str = fmt("%s -> %s", TensorRename::flatten(node.from()).c_str(), TensorRename::flatten(node.to()).c_str()); fail(node, str); } else { bind(my_type, node); } } void visit(const TensorConcat &node) override { bind(ValueType::concat(type(node.get_child(0)), type(node.get_child(1)), node.dimension()), node); } void visit(const TensorCreate &node) override { for (size_t i = 0; i < node.num_children(); ++i) { if (!type(node.get_child(i)).is_double()) { return fail(node, fmt("non-double child at index %zu", i), false); } } bind(node.type(), node); } void visit(const TensorLambda &node) override { std::vector<ValueType> arg_types; for (const auto &dim: node.type().dimensions()) { (void) dim; arg_types.push_back(ValueType::double_type()); } for (size_t binding: node.bindings()) { arg_types.push_back(param_type(binding)); } NodeTypes lambda_types(node.lambda(), arg_types); const ValueType &lambda_type = lambda_types.get_type(node.lambda().root()); if (!lambda_type.is_double()) { import_errors(lambda_types); return fail(node, fmt("lambda function has non-double result type: %s", lambda_type.to_spec().c_str()), false); } import_types(lambda_types); bind(node.type(), node); } void visit(const TensorPeek &node) override { const ValueType &param_type = type(node.param()); std::vector<vespalib::string> dimensions; for (const auto &dim: node.dim_list()) { dimensions.push_back(dim.first); if (dim.second.is_expr()) { if (!type(*dim.second.expr).is_double()) { return fail(node, fmt("non-double label expression for dimension %s", dim.first.c_str())); } } else { size_t dim_idx = param_type.dimension_index(dim.first); if (dim_idx == ValueType::Dimension::npos) { return fail(node, fmt("dimension not in param: %s", dim.first.c_str())); } const auto &param_dim = param_type.dimensions()[dim_idx]; if (param_dim.is_indexed()) { if (!is_number(dim.second.label)) { return fail(node, fmt("non-numeric label for dimension %s: '%s'", dim.first.c_str(), dim.second.label.c_str())); } if (as_number(dim.second.label) >= param_dim.size) { return fail(node, fmt("out-of-bounds label for dimension %s: %s", dim.first.c_str(), dim.second.label.c_str())); } } } } bind(param_type.reduce(dimensions), node); } void visit(const Add &node) override { resolve_op2(node); } void visit(const Sub &node) override { resolve_op2(node); } void visit(const Mul &node) override { resolve_op2(node); } void visit(const Div &node) override { resolve_op2(node); } void visit(const Mod &node) override { resolve_op2(node); } void visit(const Pow &node) override { resolve_op2(node); } void visit(const Equal &node) override { resolve_op2(node); } void visit(const NotEqual &node) override { resolve_op2(node); } void visit(const Approx &node) override { resolve_op2(node); } void visit(const Less &node) override { resolve_op2(node); } void visit(const LessEqual &node) override { resolve_op2(node); } void visit(const Greater &node) override { resolve_op2(node); } void visit(const GreaterEqual &node) override { resolve_op2(node); } void visit(const And &node) override { resolve_op2(node); } void visit(const Or &node) override { resolve_op2(node); } void visit(const Cos &node) override { resolve_op1(node); } void visit(const Sin &node) override { resolve_op1(node); } void visit(const Tan &node) override { resolve_op1(node); } void visit(const Cosh &node) override { resolve_op1(node); } void visit(const Sinh &node) override { resolve_op1(node); } void visit(const Tanh &node) override { resolve_op1(node); } void visit(const Acos &node) override { resolve_op1(node); } void visit(const Asin &node) override { resolve_op1(node); } void visit(const Atan &node) override { resolve_op1(node); } void visit(const Exp &node) override { resolve_op1(node); } void visit(const Log10 &node) override { resolve_op1(node); } void visit(const Log &node) override { resolve_op1(node); } void visit(const Sqrt &node) override { resolve_op1(node); } void visit(const Ceil &node) override { resolve_op1(node); } void visit(const Fabs &node) override { resolve_op1(node); } void visit(const Floor &node) override { resolve_op1(node); } void visit(const Atan2 &node) override { resolve_op2(node); } void visit(const Ldexp &node) override { resolve_op2(node); } void visit(const Pow2 &node) override { resolve_op2(node); } void visit(const Fmod &node) override { resolve_op2(node); } void visit(const Min &node) override { resolve_op2(node); } void visit(const Max &node) override { resolve_op2(node); } void visit(const IsNan &node) override { resolve_op1(node); } void visit(const Relu &node) override { resolve_op1(node); } void visit(const Sigmoid &node) override { resolve_op1(node); } void visit(const Elu &node) override { resolve_op1(node); } void visit(const Erf &node) override { resolve_op1(node); } //------------------------------------------------------------------------- bool open(const Node &) override { return true; } void close(const Node &node) override { if (!check_error(node)) { node.accept(*this); } } }; TypeResolver::TypeResolver(const std::vector<ValueType> &params_in, std::map<const Node *, ValueType> &type_map_out, std::vector<vespalib::string> &errors_out) : state(params_in, type_map_out, errors_out) { } TypeResolver::~TypeResolver() {} struct TypeExporter : public NodeTraverser { const std::map<const Node *, ValueType> &parent_type_map; std::map<const Node *, ValueType> &exported_type_map; size_t missing_cnt; TypeExporter(const std::map<const Node *, ValueType> &parent_type_map_in, std::map<const Node *, ValueType> &exported_type_map_out) : parent_type_map(parent_type_map_in), exported_type_map(exported_type_map_out), missing_cnt(0) {} bool open(const Node &) override { return true; } void close(const Node &node) override { auto pos = parent_type_map.find(&node); if (pos != parent_type_map.end()) { exported_type_map.emplace(&node, pos->second); } else { ++missing_cnt; } } }; } // namespace vespalib::eval::nodes::<unnamed> } // namespace vespalib::eval::nodes NodeTypes::NodeTypes() : _not_found(ValueType::error_type()), _type_map() { } NodeTypes::NodeTypes(const Function &function, const std::vector<ValueType> &input_types) : _not_found(ValueType::error_type()), _type_map() { assert(input_types.size() == function.num_params()); nodes::TypeResolver resolver(input_types, _type_map, _errors); function.root().traverse(resolver); } NodeTypes::~NodeTypes() = default; NodeTypes NodeTypes::export_types(const nodes::Node &root) const { NodeTypes exported_types; nodes::TypeExporter exporter(_type_map, exported_types._type_map); root.traverse(exporter); if (exporter.missing_cnt > 0) { exported_types._errors.push_back(fmt("[export]: %zu nodes had missing types", exporter.missing_cnt)); } return exported_types; } const ValueType & NodeTypes::get_type(const nodes::Node &node) const { auto pos = _type_map.find(&node); if (pos == _type_map.end()) { return _not_found; } return pos->second; } }
38.222527
118
0.578955
[ "vector" ]
cbd0bdab35e4331c1b718ea2c6d9870457f1088c
3,367
cpp
C++
tests/vec.cpp
amaiorano/noc
f239b6c3a1ef09ba9d35c0ddc8a5b5cae215b425
[ "MIT" ]
250
2015-06-12T09:14:11.000Z
2022-03-25T08:44:06.000Z
tests/vec.cpp
amaiorano/noc
f239b6c3a1ef09ba9d35c0ddc8a5b5cae215b425
[ "MIT" ]
9
2015-06-12T13:19:27.000Z
2020-12-02T06:48:57.000Z
tests/vec.cpp
amaiorano/noc
f239b6c3a1ef09ba9d35c0ddc8a5b5cae215b425
[ "MIT" ]
25
2015-06-12T10:13:56.000Z
2021-03-27T00:35:57.000Z
/* noc_vec.h test code. * * Copyright (c) 2015 Guillaume Chereau <guillaume@noctua-software.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 "noc_vec.h" #include <stdio.h> #include <assert.h> int main() { vec2_t a2, b2, c2; vec3_t a3, b3, c3; vec4_t a4; float n; a2 = vec2(1, 2); b2 = vec2(3, 4); a3 = vec3(1, 2, 3); b3 = vec3(4, 5, 6); // Create a vector. a4 = vec4_zero; a4 = vec4(1, 2, 3, 4); // Access members. a4.x = 0; a4.xy = vec2(1, 2); a4.xyz = vec3(1, 2, 3); printf("%g, %g, %g, %g\n", VEC4_SPLIT(a4)); // Add vectors. a4 = vec4_add(vec4(1, 2, 3, 4), vec4(10, 20, 30, 40)); // in place add. vec4_iadd(&a4, vec4(100, 100, 100, 100)); // Other operations. vec4_iaddk(&a4, vec4(4, 6, 8, 10), 0.5); vec4_imul(&a4, 10); // Cross product. c3 = vec3_cross(a3, b3); printf("(%g, %g, %g) x (%g, %g, %g) = (%g, %g, %g)\n", VEC3_SPLIT(a3), VEC3_SPLIT(b3), VEC3_SPLIT(c3)); // Norm. n = vec3_norm(a3); printf("norm(%g, %g, %g) = %g\n", VEC3_SPLIT(a3), n); // Dot product. n = vec3_dot(a3, b3); printf("(%g, %g, %g) . (%g, %g, %g) = %g\n", VEC3_SPLIT(a3), VEC3_SPLIT(b3), n); // lerp. c3 = vec3_lerp(a3, b3, 0.1); printf("lerp((%g, %g, %g), (%g, %g, %g), 0.1) = (%g, %g, %g)\n", VEC3_SPLIT(a3), VEC3_SPLIT(b3), VEC3_SPLIT(c3)); // 2d rotation. c2 = vec2_rot(a2, M_PI / 8); printf("rot((%g, %g), pi/8) = (%g, %g)\n", VEC2_SPLIT(a2), VEC2_SPLIT(c2)); // 90 deg rotations. c2 = vec2_perp(a2); printf("perp(%g, %g) = (%g, %g)\n", VEC2_SPLIT(a2), VEC2_SPLIT(c2)); // Matrix. mat4_t mat4 = mat4_translate(mat4_identity, 1, 0, 0); mat4_itranslate(&mat4, 10, 10, 10); mat4_iscale(&mat4, 1, 1, 2); a4 = mat4_mul_vec(mat4, a4); printf("%g, %g, %g, %g\n", a4.x, a4.y, a4.z, a4.w); // Quaternion. quat_t quat = quat_from_axis(M_PI / 4, 0, 0, 1); c3 = quat_mul_vec3(quat, a3); // c++ operators. c3 = a3 + b3 * 2; c3 += a3; c3 = -a3; n = a3 * b3; assert(n == vec3_dot(a3, b3)); assert(a3 == a3); n = a2 ^ b2; assert(n == vec2_cross(a2, b2)); c3 = a3 ^ b3; assert(c3 == vec3_cross(a3, b3)); a4 = a4 * mat4; a4 = a4 * quat; }
31.46729
79
0.5842
[ "vector" ]
cbd2b6e2f54fcfe13ffca467ed3cd958c41f1699
4,861
cpp
C++
core-tests/src/reactor/base.cpp
Hetystars/swoole-src
1693fc6d87159dd1447808a0a14a1ec3ef5f2d93
[ "Apache-2.0" ]
11
2020-04-22T06:01:37.000Z
2020-12-07T08:25:08.000Z
core-tests/src/reactor/base.cpp
wangchangkui/swoole-src
ada01b5af50456c64c3a364f4313506b5e04a9f9
[ "Apache-2.0" ]
null
null
null
core-tests/src/reactor/base.cpp
wangchangkui/swoole-src
ada01b5af50456c64c3a364f4313506b5e04a9f9
[ "Apache-2.0" ]
null
null
null
#include "tests.h" #include "swoole/swoole_api.h" TEST(reactor, swReactor_create) { swReactor reactor; int ret = swReactor_create(&reactor, SW_REACTOR_MAXEVENTS); ASSERT_EQ(ret, SW_OK); ASSERT_NE(reactor.object, nullptr); ASSERT_EQ(reactor.max_event_num, SW_REACTOR_MAXEVENTS); ASSERT_NE(reactor.add, nullptr); ASSERT_NE(reactor.set, nullptr); ASSERT_NE(reactor.del, nullptr); ASSERT_NE(reactor.wait, nullptr); ASSERT_NE(reactor.free, nullptr); ASSERT_EQ(reactor.running, 1); ASSERT_NE(reactor.onFinish, nullptr); ASSERT_NE(reactor.onTimeout, nullptr); ASSERT_NE(reactor.is_empty, nullptr); ASSERT_EQ(reactor.can_exit, nullptr); // set in PHP_METHOD(swoole_coroutine_scheduler, set) ASSERT_NE(reactor.write, nullptr); ASSERT_NE(reactor.close, nullptr); ASSERT_NE(reactor.defer, nullptr); ASSERT_EQ(reactor.defer_tasks, nullptr); ASSERT_NE(reactor.default_write_handler, nullptr); /** * coroutine socket reactor */ ASSERT_NE(reactor.read_handler[swReactor_fdtype(SW_FD_CORO_SOCKET | SW_EVENT_READ)], nullptr); ASSERT_NE(reactor.write_handler[swReactor_fdtype(SW_FD_CORO_SOCKET | SW_EVENT_WRITE)], nullptr); ASSERT_NE(reactor.error_handler[swReactor_fdtype(SW_FD_CORO_SOCKET | SW_EVENT_ERROR)], nullptr); /** * system reactor */ ASSERT_NE(reactor.read_handler[swReactor_fdtype(SW_FD_CORO_POLL | SW_EVENT_READ)], nullptr); ASSERT_NE(reactor.write_handler[swReactor_fdtype(SW_FD_CORO_POLL | SW_EVENT_WRITE)], nullptr); ASSERT_NE(reactor.error_handler[swReactor_fdtype(SW_FD_CORO_POLL | SW_EVENT_ERROR)], nullptr); ASSERT_NE(reactor.read_handler[swReactor_fdtype(SW_FD_CORO_EVENT | SW_EVENT_READ)], nullptr); ASSERT_NE(reactor.write_handler[swReactor_fdtype(SW_FD_CORO_EVENT | SW_EVENT_WRITE)], nullptr); ASSERT_NE(reactor.error_handler[swReactor_fdtype(SW_FD_CORO_EVENT | SW_EVENT_ERROR)], nullptr); ASSERT_NE(reactor.read_handler[swReactor_fdtype(SW_FD_AIO | SW_EVENT_READ)], nullptr); } TEST(reactor, swReactor_set_handler) { swReactor reactor; swReactor_set_handler(&reactor, SW_EVENT_READ, (swReactor_handler) 0x1); ASSERT_EQ(reactor.read_handler[swReactor_fdtype(SW_EVENT_READ)], (swReactor_handler) 0x1); swReactor_set_handler(&reactor, SW_EVENT_WRITE, (swReactor_handler) 0x2); ASSERT_EQ(reactor.write_handler[swReactor_fdtype(SW_EVENT_WRITE)], (swReactor_handler) 0x2); swReactor_set_handler(&reactor, SW_EVENT_ERROR, (swReactor_handler) 0x3); ASSERT_EQ(reactor.error_handler[swReactor_fdtype(SW_EVENT_ERROR)], (swReactor_handler) 0x3); } TEST(reactor, swReactor_close) { swReactor reactor; swSocket *socket = swSocket_new(10, SW_FD_SESSION); socket->in_buffer = swBuffer_new(SW_BUFFER_MIN_SIZE); socket->out_buffer = swBuffer_new(SW_SEND_BUFFER_SIZE); swReactor_close(&reactor, socket); ASSERT_EQ(socket->in_buffer, nullptr); ASSERT_EQ(socket->out_buffer, nullptr); } TEST(reactor, swReactor_wait) { int ret; swPipe p; ret = swoole_event_init(); ASSERT_EQ(ret, SW_OK); ASSERT_NE(SwooleTG.reactor, nullptr); ret = swPipeUnsock_create(&p, 1, SOCK_DGRAM); ASSERT_EQ(ret, SW_OK); swoole_event_set_handler(SW_FD_PIPE | SW_EVENT_READ, [](swReactor *reactor, swEvent *ev) -> int { char buffer[16]; ssize_t n = read(ev->fd, buffer, sizeof(buffer)); EXPECT_EQ(sizeof("hello world"), n); EXPECT_STREQ("hello world", buffer); reactor->del(reactor, ev->socket); reactor->wait_exit = 1; return SW_OK; }); ret = swoole_event_add(p.worker_socket, SW_EVENT_READ); ASSERT_EQ(ret, SW_OK); ret = p.write(&p, (void *) SW_STRS("hello world")); ASSERT_EQ(ret, sizeof("hello world")); ret = swoole_event_wait(); ASSERT_EQ(ret, SW_OK); ASSERT_EQ(SwooleTG.reactor, nullptr); } TEST(reactor, swReactor_write) { int ret; swPipe p; ret = swoole_event_init(); ASSERT_EQ(ret, SW_OK); ASSERT_NE(SwooleTG.reactor, nullptr); ret = swPipeUnsock_create(&p, 1, SOCK_DGRAM); ASSERT_EQ(ret, SW_OK); swoole_event_set_handler(SW_FD_PIPE | SW_EVENT_READ, [](swReactor *reactor, swEvent *ev) -> int { char buffer[16]; ssize_t n = read(ev->fd, buffer, sizeof(buffer)); EXPECT_EQ(sizeof("hello world"), n); EXPECT_STREQ("hello world", buffer); reactor->del(reactor, ev->socket); reactor->wait_exit = 1; return SW_OK; }); ret = swoole_event_add(p.worker_socket, SW_EVENT_READ); ASSERT_EQ(ret, SW_OK); ret = swoole_event_write(p.master_socket, (void *) SW_STRS("hello world")); ASSERT_EQ(ret, sizeof("hello world")); ret = swoole_event_wait(); ASSERT_EQ(ret, SW_OK); ASSERT_EQ(SwooleTG.reactor, nullptr); }
32.192053
100
0.711993
[ "object" ]
cbd475a33bbd5410cdae0128310301d36cc0ff93
3,074
cpp
C++
Source/Engine/Gameplay/Systems/SEditorCamera.cpp
muit/FecoEngine
b2f8729c0bf0893b770434645c2a0fa8e7717cb7
[ "Apache-2.0" ]
3
2019-03-01T19:34:26.000Z
2021-03-31T09:25:16.000Z
Source/Engine/Gameplay/Systems/SEditorCamera.cpp
muit/FecoEngine
b2f8729c0bf0893b770434645c2a0fa8e7717cb7
[ "Apache-2.0" ]
null
null
null
Source/Engine/Gameplay/Systems/SEditorCamera.cpp
muit/FecoEngine
b2f8729c0bf0893b770434645c2a0fa8e7717cb7
[ "Apache-2.0" ]
1
2019-01-21T21:45:13.000Z
2019-01-21T21:45:13.000Z
// Copyright 2015-2019 Piperift - All rights reserved #include "SEditorCamera.h" #include "Core/Log.h" #include "Gameplay/Components/CTransform.h" #include "Gameplay/Components/CEditorCamera.h" #include "Core/Engine.h" void SEditorCamera::Construct() { Super::Construct(); input = GEngine->GetInput(); input->CreateTriggerAction({ "ViewportMoveMode" }, { { EKey::MouseRight, EKeyModifier::None }, }) .Bind(this, &SEditorCamera::ViewportMoveMode); input->CreateAxisAction({ "MoveForward" }, { { EKey::W, EKeyModifier::None, 1.f }, { EKey::S, EKeyModifier::None, -1.f } }, {}) .Bind(this, &SEditorCamera::MoveForward); input->CreateAxisAction({ "MoveRight" }, { { EKey::A, EKeyModifier::None, -1.f }, { EKey::D, EKeyModifier::None, 1.f } }, {}) .Bind(this, &SEditorCamera::MoveRight); input->CreateAxisAction({ "TurnUp" }, {}, { { EAxis::MouseY, EKeyModifier::None, 1.f } }) .Bind(this, &SEditorCamera::TurnUp); input->CreateAxisAction({ "TurnRight" }, {}, { { EAxis::MouseX, EKeyModifier::None, -1.f } }) .Bind(this, &SEditorCamera::TurnRight); // If there's no camera, create one auto view = ECS()->View<CEditorCamera>(); if (view.empty()) { camera = ECS()->CreateEntity({ "EditorCamera" }); auto& t = ECS()->Assign<CTransform>(camera).transform; t.location = { 0, -10, 0 }; t.SetRotation({ 0.f, 0.f, 0.f }); ECS()->Assign<CEditorCamera>(camera); } } void SEditorCamera::Tick(float deltaTime) { // Only tick on editor if (!GetWorld()->IsEditor()) { bRotatingMode = false; return; } const v3 finalRotateDelta = rotationDelta * deltaTime; const v3 finalMoveDelta = movementDelta * deltaTime; ECS()->View<CTransform, CEditorCamera>() .each([finalRotateDelta, finalMoveDelta](const auto e, CTransform& t, CEditorCamera& c) { // Rotate Camera Rotator rotation = t.transform.GetRotation(); rotation += finalRotateDelta * c.rotateSpeed; // Limit vertical rotation rotation.x = Math::ClampAngle(rotation.x, 270.01f, 89.99f); t.transform.SetRotation(rotation); // Rotate movement towards angle t.transform.location += t.transform.TransformVector( finalMoveDelta * v3{ c.sideSpeed, c.forwardSpeed, 0.f } ); }); rotationDelta = v3::Zero(); movementDelta = v3::Zero(); } void SEditorCamera::BeforeDestroy() { ECS()->DestroyEntity(camera); Super::BeforeDestroy(); } void SEditorCamera::ViewportMoveMode(EKeyPressState state) { switch (state) { case EKeyPressState::Press: bRotatingMode = true; SDL_SetRelativeMouseMode(SDL_TRUE); break; case EKeyPressState::Release: bRotatingMode = false; SDL_SetRelativeMouseMode(SDL_FALSE); break; } } void SEditorCamera::MoveForward(float delta) { if (GetWorld()->IsEditor()) { movementDelta.y += delta; } } void SEditorCamera::MoveRight(float delta) { if (GetWorld()->IsEditor()) { movementDelta.x += delta; } } void SEditorCamera::TurnUp(float delta) { if (bRotatingMode) { rotationDelta.x += delta; } } void SEditorCamera::TurnRight(float delta) { if (bRotatingMode) { rotationDelta.z += delta; } }
21.647887
88
0.6838
[ "transform" ]
cbddb11782415f30b965052efc21ee5f1645f9c5
12,994
cpp
C++
Krakoa/Source/Graphics/2D/Renderer2D.cpp
KingKiller100/Krakatoa-Engine
ff07f7328d428c04e06b561b6afd315eea39865c
[ "Apache-2.0" ]
1
2020-04-05T13:37:48.000Z
2020-04-05T13:37:48.000Z
Krakoa/Source/Graphics/2D/Renderer2D.cpp
KingKiller100/Krakoa-Engine
0f2a5a5109e256a384abe8dc21eacaa45c1de610
[ "Apache-2.0" ]
null
null
null
Krakoa/Source/Graphics/2D/Renderer2D.cpp
KingKiller100/Krakoa-Engine
0f2a5a5109e256a384abe8dc21eacaa45c1de610
[ "Apache-2.0" ]
null
null
null
#include "Precompile.hpp" #include "Renderer2D.hpp" #include "Textures/iTexture2D.hpp" #include "Textures/SubTexture2d.hpp" #include "Primitives2D/VertexData.hpp" #include "Primitives2D/GeometryData.hpp" #include "Primitives2D/Primitives2D.hpp" #include "../RenderCommand.hpp" #include "../ShaderLibrary.hpp" #include "../Resources/iShader.hpp" #include "../Resources/iVertexArray.hpp" #include "../../Debug/Instrumentor.hpp" #include "../../Camera/iCamera.hpp" #include "../../Camera/OrthographicCamera.hpp" #include <Maths/Quaternions/QuaternionsMathsHelper.hpp> #include <Maths/Matrices/MatrixMathsHelper.hpp> #include <array> using namespace krakoa::scene::ecs::components; namespace krakoa::gfx { namespace { constexpr kmaths::Quaternionf q_ = kmaths::IdentityQuaternion<float>(Theta::DEGREES); } _2D::PrimitivesData* pData = nullptr; const Statistics& Renderer2D::GetStats() { return stats; } void Renderer2D::Initialize(ShaderLibrary& shaderLibrary) { KRK_PROFILE_FUNCTION(); pData = new _2D::PrimitivesData(); constexpr auto sizeOfVertexData = sizeof(VertexData); // Triangle creation code { auto& triangle = pData->triangle; triangle.pVertexArray.reset(iVertexArray::Create()); auto& vertexArray = *triangle.pVertexArray; // Vertex buffer { auto* triangleVB = iVertexBuffer::Create(batch::limits::triangle::maxVertices * sizeOfVertexData); triangleVB->SetLayout({ { ShaderDataType::FLOAT3, "a_Position" }, { ShaderDataType::FLOAT4, "a_Colour" }, { ShaderDataType::FLOAT2, "a_TexCoord" }, { ShaderDataType::FLOAT, "a_TexIndex" }, { ShaderDataType::FLOAT, "a_TilingFactor" }, }); vertexArray.AddVertexBuffer(triangleVB); } triangle.pVertexBufferBase = new VertexData[batch::limits::triangle::maxVertices]; // Index buffer { constexpr auto maxIndices = batch::limits::triangle::maxIndices; constexpr auto verticesPerTriangle = batch::limits::triangle::vertices; const std::unique_ptr<uint32_t[]> triangleIndices(new uint32_t[maxIndices]); uint32_t offset = 0; for (size_t i = 0; i < maxIndices; i += batch::limits::triangle::indices) { triangleIndices[i + 0] = offset + 0; triangleIndices[i + 1] = offset + 1; triangleIndices[i + 2] = offset + 2; offset += verticesPerTriangle; } triangle.pVertexArray->SetIndexBuffer(iIndexBuffer::Create( triangleIndices.get(), maxIndices) ); } } // Quad creation code { auto& quad = pData->quad; pData->quad.pVertexArray.reset(iVertexArray::Create()); auto& vertexArray = *pData->quad.pVertexArray; // Vertex buffer { iVertexBuffer* quadVB = iVertexBuffer::Create(batch::limits::quad::maxVertices * sizeOfVertexData); quadVB->SetLayout({ { ShaderDataType::FLOAT3, "a_Position" }, { ShaderDataType::FLOAT4, "a_Colour" }, { ShaderDataType::FLOAT2, "a_TexCoord" }, { ShaderDataType::FLOAT, "a_TexIndex" }, { ShaderDataType::FLOAT, "a_TilingFactor" }, }); vertexArray.AddVertexBuffer(quadVB); } quad.pVertexBufferBase = new VertexData[batch::limits::quad::maxVertices]; // Index buffer { constexpr auto maxIndices = batch::limits::quad::maxIndices; constexpr auto verticesPerQuad = batch::limits::quad::vertices; const std::unique_ptr<uint32_t[]> quadIndices(new uint32_t[batch::limits::quad::maxIndices]); uint32_t offset = 0; for (size_t i = 0; i < maxIndices; i += batch::limits::quad::indices) { quadIndices[i + 0] = offset + 0; quadIndices[i + 1] = offset + 1; quadIndices[i + 2] = offset + 2; quadIndices[i + 3] = offset + 2; quadIndices[i + 4] = offset + 3; quadIndices[i + 5] = offset + 0; offset += verticesPerQuad; } quad.pVertexArray->SetIndexBuffer(iIndexBuffer::Create( quadIndices.get(), maxIndices) ); } } // Create white texture { constexpr uint32_t whiteTexture = 0xffffffff; auto* const pWhiteTexture = iTexture2D::Create(1u, 1u); pWhiteTexture->SetData(&whiteTexture, sizeof(whiteTexture)); pData->textures.slots.front() = std::shared_ptr<iTexture2D>(pWhiteTexture); // index 0 = white texture } // Creating and setting texture sampler { int32_t samplers[batch::limits::texture::maxSlots]; for (auto i = 0; i < batch::limits::texture::maxSlots; ++i) { samplers[i] = i; } const auto mainShader = shaderLibrary.Load("MainShader", "MainShader"); if (!mainShader.expired()) { auto main_shader_s_ptr = mainShader.lock(); main_shader_s_ptr->Bind(); main_shader_s_ptr->SetIntArray("u_Textures", samplers, batch::limits::texture::maxSlots); } pData->pMainShader = mainShader; } } void Renderer2D::ShutDown() { if (!pData) return; delete pData; pData = nullptr; } void Renderer2D::BeginScene(const iCamera& camera, const kmaths::TransformMatrix<float>& transformMat) { KRK_PROFILE_FUNCTION(); const auto viewMat = transformMat.Inverse(); const auto viewProjMat = camera.GetProjectionMatrix() * viewMat ; if (!pData->pMainShader.expired()) { auto mainShader = pData->pMainShader.lock(); mainShader->Bind(); mainShader->SetMat4x4("u_VpMat", viewProjMat); } RestartBatch(); #if KRK_ENABLE_STATISTICS stats.Reset(); #endif } void Renderer2D::BeginScene(const OrthographicCamera& camera) { KRK_PROFILE_FUNCTION(); if (!pData->pMainShader.expired()) { auto mainShader = pData->pMainShader.lock(); mainShader->Bind(); mainShader->SetMat4x4("u_VpMat", camera.GetViewProjectionMatrix()); } RestartBatch(); #if KRK_ENABLE_STATISTICS stats.Reset(); #endif } void Renderer2D::EndScene() { KRK_PROFILE_FUNCTION(); auto& quad = pData->quad; auto& triangle = pData->triangle; quad.PrepareForRendering(); triangle.PrepareForRendering(); pData->textures.BindTextures(); const auto totalIndices = pData->quad.indexCount + pData->triangle.indexCount; if (totalIndices >= batch::limits::maxIndices) { FlushAll(); } else { if (quad.pVertexBuffer != quad.pVertexBufferBase) FlushQuads(); if (triangle.pVertexBuffer != triangle.pVertexBufferBase) FlushTriangles(); } } void Renderer2D::RestartBatch() noexcept { pData->quad.Reset(); pData->triangle.Reset(); pData->textures.Reset(1); } void Renderer2D::FlushAll() { pData->textures.BindTextures(); FlushQuads(); FlushTriangles(); } void Renderer2D::FlushQuads() { pData->quad.pVertexArray->Bind(); RenderCommand::DrawIndexed(*pData->quad.pVertexArray, pData->quad.indexCount); #if KRK_ENABLE_STATISTICS stats.quadDrawCallsCount++; #endif } void Renderer2D::FlushTriangles() { pData->triangle.pVertexArray->Bind(); RenderCommand::DrawIndexed(*pData->triangle.pVertexArray, pData->triangle.indexCount); #if KRK_ENABLE_STATISTICS stats.triangleDrawCallsCount++; #endif } void Renderer2D::DrawTriangle(const Appearance2DComponent& appearance, const TransformComponent& transform) { DrawTriangle(appearance.GetSubTexture(), transform.GetPosition(), transform.GetScale(), transform.GetRotation().z, appearance.GetColour(), appearance.GetTilingFactor()); } void Renderer2D::DrawQuad(const Appearance2DComponent& appearance, const TransformComponent& transform) { DrawQuad(appearance.GetSubTexture(), transform.GetPosition(), transform.GetScale(), transform.GetRotation().z, appearance.GetColour(), appearance.GetTilingFactor()); } void Renderer2D::DrawTriangle(const SubTexture2D& subTexture, const kmaths::Vector2f& position, const kmaths::Vector2f& scale, const float radians, const Colour tintColour, const float tilingFactor) { DrawTriangle(subTexture, kmaths::Vector3f(position), scale, radians, tintColour, tilingFactor); } void Renderer2D::DrawTriangle(const SubTexture2D& subTexture, const kmaths::Vector3f& position, const kmaths::Vector2f& scale, const float radians, const Colour tintColour, const float tilingFactor) { KRK_PROFILE_FUNCTION(); FlushIfLimitsMet(); float texIndex = 0.f; const kmaths::Vector2f* texCoords; if (!subTexture.GetTexture()) { static constexpr kmaths::Vector2f defaultCoords[] = { {0.f, 0.f}, {1.f, 0.f}, {0.5f, 1.f} }; texCoords = defaultCoords; } else { texIndex = UpdateTextureList(subTexture.GetTexture()); texCoords = subTexture.GetTexCoord(); } AddNewTriangle(position, scale, radians, tintColour, texIndex, texCoords, tilingFactor); } void Renderer2D::DrawQuad(const SubTexture2D& subTexture, const kmaths::Vector2f& position, const kmaths::Vector2f& scale, const float radians, const Colour tintColour, const float tilingFactor) { DrawQuad(subTexture, kmaths::Vector3f(position), scale, radians, tintColour, tilingFactor); } void Renderer2D::DrawQuad(const SubTexture2D& subTexture, const kmaths::Vector3f& position, const kmaths::Vector2f& scale, const float radians, const Colour tintColour, const float tilingFactor) { KRK_PROFILE_FUNCTION(); FlushIfLimitsMet(); float texIndex = 0.f; const kmaths::Vector2f* texCoords; if (!subTexture.GetTexture()) { static constexpr kmaths::Vector2f defaultCoords[] = { {0.f, 0.f}, {1.f, 0.f}, {1.f, 1.f}, {0.f, 1.f} }; texCoords = defaultCoords; } else { texIndex = UpdateTextureList(subTexture.GetTexture()); texCoords = subTexture.GetTexCoord(); } AddNewQuad(position, scale, radians, tintColour, texIndex, texCoords, tilingFactor); } void Renderer2D::FlushIfLimitsMet() noexcept { const auto totalIndices = pData->quad.indexCount + pData->triangle.indexCount; if (pData->textures.slotIdx == batch::limits::texture::maxSlots) { EndScene(); RestartBatch(); } if (totalIndices >= batch::limits::maxIndices) { EndScene(); RestartBatch(); } if (pData->quad.indexCount >= batch::limits::quad::maxIndices) { EndScene(); RestartBatch(); } if (pData->triangle.indexCount >= batch::limits::triangle::maxIndices) { EndScene(); RestartBatch(); } } float Renderer2D::UpdateTextureList(const std::shared_ptr<iTexture2D>& texture) noexcept { if (texture == nullptr) return 0.f; float texIdx = 0.f; auto& textures = pData->textures; for (size_t i = 1u; i < textures.slotIdx; ++i) { if (*textures.slots[i] == *texture) { texIdx = CAST(float, i); break; } } if (texIdx == 0) { const auto lastIdx = textures.slotIdx; texIdx = CAST(float, lastIdx); textures.slots[lastIdx] = texture; textures.slotIdx++; } return texIdx; } void Renderer2D::AddNewTriangle(const kmaths::Vector3f& position, const kmaths::Vector2f& scale, const float radians, const Colour colour, const float texIndex, const kmaths::Vector2f*& texCoords, const float tilingFactor) { static constexpr auto loops = kmaths::SizeOfCArray(TriangleData::vertices); auto& triangle = pData->triangle; auto& bufferPtr = triangle.pVertexBuffer; const kmaths::Vector3f scale3D(scale.x, scale.y, 1.f); kmaths::Quaternionf qpq_; if (radians != 0) { const kmaths::Quaternionf qp(radians, 1, 1, 1); qpq_ = qp * q_; } for (auto i = 0; i < loops; ++bufferPtr, ++i) { kmaths::Vector4f worldPosition; if (radians == 0) { worldPosition = (position + (triangle.vertices[i] * scale3D)); } else { const auto scaledVertex = (triangle.vertices[i] * scale3D); worldPosition = position + (qpq_ * scaledVertex); } bufferPtr->position = worldPosition; bufferPtr->colour = colour.GetRGBA(); bufferPtr->texCoord = texCoords[i]; bufferPtr->texIdx = texIndex; bufferPtr->tilingFactor = tilingFactor; } triangle.IncrementIndexCount(); #if KRK_ENABLE_STATISTICS stats.triangleCount++; #endif } void Renderer2D::AddNewQuad(const kmaths::Vector3f& position, const kmaths::Vector2f& scale, const float radians, const Colour colour, float texIndex, const kmaths::Vector2f*& texCoords, const float tilingFactor) { static constexpr auto loops = kmaths::SizeOfCArray(QuadData::vertices); auto& quad = pData->quad; auto& bufferPtr = quad.pVertexBuffer; const kmaths::Vector3f scale3D(scale.x, scale.y, 1.f); kmaths::Quaternionf qpq_; if (radians != 0) { const kmaths::Quaternionf qp(radians, 0, 0, 1); qpq_ = qp * q_; } for (auto i = 0; i < loops; ++bufferPtr, ++i) { kmaths::Vector4f worldPosition; if (radians == 0) { worldPosition = (position + (quad.vertices[i] * scale3D)); } else { const auto scaledVertex = (quad.vertices[i] * scale3D); worldPosition = position + (qpq_ * scaledVertex); } bufferPtr->position = worldPosition; bufferPtr->colour = colour.GetRGBA(); bufferPtr->texCoord = texCoords[i]; bufferPtr->texIdx = texIndex; bufferPtr->tilingFactor = tilingFactor; } quad.IncrementIndexCount(); #if KRK_ENABLE_STATISTICS stats.quadCount++; #endif } }
25.133462
127
0.691781
[ "transform" ]
cbec38f5a7b6f5ec32db18c127c2ea2793a4c001
2,379
cpp
C++
Delete Nodes And Return Forest.cpp
dishanilahiri/LeetCode-Premium
1882606edac81586edea264d94b215acdac4f8b6
[ "MIT" ]
null
null
null
Delete Nodes And Return Forest.cpp
dishanilahiri/LeetCode-Premium
1882606edac81586edea264d94b215acdac4f8b6
[ "MIT" ]
null
null
null
Delete Nodes And Return Forest.cpp
dishanilahiri/LeetCode-Premium
1882606edac81586edea264d94b215acdac4f8b6
[ "MIT" ]
1
2021-06-06T09:46:13.000Z
2021-06-06T09:46:13.000Z
Question-> Given the root of a binary tree, each node in the tree has a distinct value. After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest. You may return the result in any order. Example 1: Input: root = [1,2,3,4,5,6,7], to_delete = [3,5] Output: [[1,2,null,4],[6],[7]] Example 2: Input: root = [1,2,4,null,3], to_delete = [3] Output: [[1,2,4]] Constraints: The number of nodes in the given tree is at most 1000. Each node has a distinct value between 1 and 1000. to_delete.length <= 1000 to_delete contains distinct values between 1 and 1000. Code: /** * 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 { public: TreeNode* delNodesUtil(TreeNode* &root,unordered_set<int> &sets,vector<TreeNode*> &ans) { if(!root) return NULL; if(sets.find(root->val)!=sets.end()) { sets.erase(root->val); TreeNode* l=delNodesUtil(root->left,sets,ans); TreeNode* r=delNodesUtil(root->right,sets,ans); if(l) ans.push_back(l); if(r) ans.push_back(r); return NULL; } else { root->left=delNodesUtil(root->left,sets,ans); root->right=delNodesUtil(root->right,sets,ans); return root; } } vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) { vector<TreeNode*> ans; unordered_set<int> sets(to_delete.begin(),to_delete.end()); if(sets.find(root->val)==sets.end()) ans.push_back(root); //Has to be pushed in the beginning itself if it is valid delNodesUtil(root,sets,ans); //root has to be passed by reference for the sake of the case where root is already pushed into ans but it's children might get rejected in final tree. return ans; } };
30.5
239
0.580916
[ "vector" ]
cbefbc87dd63a37e3f82121c925cd008de15a6ef
703
cpp
C++
leetcode/494_Target-Sum/TargetSum3.cpp
chasingegg/Online_Judge
8a3f4b5b207cbeda921c743a527a25bf9c7b6248
[ "MIT" ]
1
2017-10-13T10:34:46.000Z
2017-10-13T10:34:46.000Z
leetcode/494_Target-Sum/TargetSum3.cpp
chasingegg/Online_Judge
8a3f4b5b207cbeda921c743a527a25bf9c7b6248
[ "MIT" ]
null
null
null
leetcode/494_Target-Sum/TargetSum3.cpp
chasingegg/Online_Judge
8a3f4b5b207cbeda921c743a527a25bf9c7b6248
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include <cmath> #include <algorithm> using namespace std; class Solution { public: int findTargetSumWays(vector<int>& nums, int S) { if (S < 0) { S = (-1)*S; } int sum = 0; for (auto& num : nums) { sum += num; } if (sum < S) return 0; if ((S + sum) % 2 != 0) return 0; int target = (S + sum) / 2; // 接下来就是寻找和为target的组合 vector<int> dp(target+1, 0); dp[0] = 1; for (auto num : nums) { for (int i = target; i >= num; --i) { dp[i] += dp[i-num]; } } return dp[target]; } };
23.433333
58
0.446657
[ "vector" ]
cbf411ae5f3011089752d2c9d213c9de3d6d1cad
9,521
cpp
C++
source/tests/llassetgen-tests/Packing.cpp
bwasty/openll-asset-generator
ee7b146b1d8493f0744a85aa019e4dc43ff3da29
[ "MIT" ]
6
2018-07-30T09:41:50.000Z
2020-07-03T18:47:29.000Z
source/tests/llassetgen-tests/Packing.cpp
bwasty/openll-asset-generator
ee7b146b1d8493f0744a85aa019e4dc43ff3da29
[ "MIT" ]
42
2017-11-06T12:44:14.000Z
2018-06-21T14:37:39.000Z
source/tests/llassetgen-tests/Packing.cpp
hpicgs/openll-asset-generator
39d5a03e492dbdfc839eccb3502e5599bf73d29c
[ "MIT" ]
1
2018-10-19T23:19:25.000Z
2018-10-19T23:19:25.000Z
#include <gmock/gmock.h> #include <numeric> #include <llassetgen/llassetgen.h> using llassetgen::Packing; using Vec = llassetgen::Vec2<llassetgen::PackingSizeType>; using Rect = llassetgen::Rect<llassetgen::PackingSizeType>; /** * Base class for all packing test fixtures. * * Defines several test methods that should be run for all packing methods. */ class PackingTest : public testing::Test { protected: virtual Packing run(const std::vector<Vec>& rectSizes, bool allowRotations, Vec atlasSize) = 0; virtual Packing run(const std::vector<Vec>& rectSizes, bool allowRotations) = 0; static bool rotatedSizesEquals(Vec size1, Vec size2) { return size1 == size2 || size1 == Vec{size2.y, size2.x}; } static bool doNotOverlap(const Rect& rect1, const Rect& rect2) { return !rect1.overlaps(rect2); } /** * Expect a fixed size packing to succeed and validate the result. */ Packing expectSuccessfulValidPacking(const std::vector<Vec>& rectSizes, Vec atlasSize, bool allowRotations); /** * Expects a variable size packing to return a valid result. */ Packing expectValidPacking(const std::vector<Vec>& rectSizes, bool allowRotations) { Packing packing = run(rectSizes, allowRotations); validatePacking(packing, rectSizes, allowRotations); return packing; } /** * Validate a packing given the input parameters. */ void validatePacking(const Packing& packing, const std::vector<Vec>& rectSizes, bool allowRotations); void expectPackingFailure(const std::vector<Vec>& rectSizes, bool allowRotations, Vec atlasSize) { std::vector<Rect> emptyVec{}; EXPECT_EQ(emptyVec, run(rectSizes, allowRotations, atlasSize).rects); } void testRejectTooWide() { expectPackingFailure({{2, 1}}, false, {1, 1}); expectPackingFailure({{2, 1}}, true, {1, 1}); } void testRejectTooHigh() { expectPackingFailure({{1, 2}}, false, {1, 1}); expectPackingFailure({{1, 2}}, true, {1, 1}); } void testRotateOnly() { expectPackingFailure({{2, 1}, {1, 2}}, false, {2, 2}); expectSuccessfulValidPacking({{2, 1}, {1, 2}}, {2, 2}, true); } void testAcceptAtlasSized() { expectSuccessfulValidPacking({{1, 1}}, {1, 1}, false); expectSuccessfulValidPacking({{1, 1}}, {1, 1}, true); } void testAcceptMultipleTiny() { expectSuccessfulValidPacking({{1, 2}, {3, 4}, {5, 6}, {7, 8}}, {256, 256}, false); expectSuccessfulValidPacking({{1, 2}, {3, 4}, {5, 6}, {7, 8}}, {256, 256}, true); } void testVariableSizePacking() { expectValidPacking({{1, 2}, {3, 4}, {5, 6}}, false); expectValidPacking({{1, 2}, {3, 4}, {5, 6}}, true); } void testNonSquareSizePrediction() { auto expectValidNonSquarePacking = [this](const std::vector<Vec>& rectSizes, bool allowRotations) { Packing p = expectValidPacking(rectSizes, allowRotations); EXPECT_NE(p.atlasSize.x, p.atlasSize.y); }; // Should not result in a square packing with any packing method. expectValidNonSquarePacking({{1, 1024}}, false); expectValidNonSquarePacking({{1, 1024}}, true); expectValidNonSquarePacking({{1024, 1}}, false); expectValidNonSquarePacking({{1024, 1}}, true); } void testTooSmallSizePrediction() { // These have a combined area of 28 < 4*8, but can't be packed into a // 4x8 atlas. Testing both direction forces both directions of growth // in packing methods that support it. std::vector<Vec> rectSizes{{8, 2}, {8, 1}, {1, 4}}; std::vector<Vec> rectSizesRotated{{2, 8}, {1, 8}, {4, 1}}; expectValidPacking(rectSizes, false); expectValidPacking(rectSizes, true); expectValidPacking(rectSizesRotated, false); expectValidPacking(rectSizesRotated, true); } }; Packing PackingTest::expectSuccessfulValidPacking(const std::vector<Vec>& rectSizes, Vec atlasSize, bool allowRotations) { Packing packing = run(rectSizes, allowRotations, atlasSize); EXPECT_EQ(atlasSize, packing.atlasSize); validatePacking(packing, rectSizes, allowRotations); return packing; } void PackingTest::validatePacking(const Packing& packing, const std::vector<Vec>& rectSizes, bool allowRotations) { EXPECT_EQ(rectSizes.size(), packing.rects.size()); for (size_t i = 0; i < packing.rects.size(); i++) { auto rect = packing.rects[i]; if (allowRotations) { EXPECT_PRED2(rotatedSizesEquals, rectSizes[i], rect.size); } else { EXPECT_EQ(rectSizes[i], rect.size); } EXPECT_LE(0, rect.position.x); EXPECT_LE(0, rect.position.y); EXPECT_GE(packing.atlasSize.x, rect.position.x + rect.size.x); EXPECT_GE(packing.atlasSize.y, rect.position.y + rect.size.y); for (size_t j = i + 1; j < packing.rects.size(); j++) { EXPECT_PRED2(doNotOverlap, rect, packing.rects[j]); } } } class ShelfNextFitPackingTest : public PackingTest { Packing run(const std::vector<Vec>& rectSizes, bool allowRotations, Vec atlasSize) override { return llassetgen::shelfPackAtlas(rectSizes.begin(), rectSizes.end(), atlasSize, allowRotations); } Packing run(const std::vector<Vec>& rectSizes, bool allowRotations) override { return llassetgen::shelfPackAtlas(rectSizes.begin(), rectSizes.end(), allowRotations); } }; class MaxRectsPackingTest : public PackingTest { protected: Packing run(const std::vector<Vec>& rectSizes, bool allowRotations, Vec atlasSize) override { return llassetgen::maxRectsPackAtlas(rectSizes.begin(), rectSizes.end(), atlasSize, allowRotations); } Packing run(const std::vector<Vec>& rectSizes, bool allowRotations) override { return llassetgen::maxRectsPackAtlas(rectSizes.begin(), rectSizes.end(), allowRotations); } public: void testNoFreeRect() { // No free rect available when packing the second rect. expectPackingFailure({{1, 1}, {1, 1}}, false, {1, 1}); expectPackingFailure({{1, 1}, {1, 1}}, false, {1, 1}); // Uses internal packer because chosen atlas size always has enough // area for all rectangles. for (bool allowRotations : {false, true}) { llassetgen::internal::MaxRectsPacker packer{{1, 1}, allowRotations, true}; Rect r1{{0, 0}, {1, 1}}; Rect r2{{0, 0}, {1, 1}}; EXPECT_TRUE(packer.pack(r1)); EXPECT_TRUE(packer.pack(r2)); EXPECT_TRUE(packer.atlasSize().x > 1 || packer.atlasSize().y > 1); } } void testFreeRectPruning() { // Test case forces the following to happen: // - Rectangle placed top-left, creating two free rectangles which // overlap in the bottom-right // - Fill the non-overlapping part of one rectangle, causing the // remainder to be pruned. Chosen due to best short-side fit. // - Fill the other rectangle completely. Chosen because only it can // fit the rectangle // - Last rectangle is the size of the pruned rectangle, and should // fail to pack // // To avoid reordering of the rectangles, this test uses the internal // packing class directly. auto test = [](const std::vector<Vec>& rectSizes, const Vec& nonFitting) { llassetgen::internal::MaxRectsPacker packer{{8, 8}, false, false}; for (Vec size : rectSizes) { Rect r{{0, 0}, size}; EXPECT_TRUE(packer.pack(r)); } Rect r{{0, 0}, nonFitting}; EXPECT_FALSE(packer.pack(r)); }; // Test both orientations test({{4, 3}, {4, 3}, {8, 5}}, {4, 5}); test({{3, 4}, {3, 4}, {5, 8}}, {5, 4}); } }; #define ADD_TESTS_FOR_FIXTURE(Fixture) \ TEST_F(Fixture, TestRejectTooWide) { testRejectTooWide(); } \ TEST_F(Fixture, TestRejectTooHigh) { testRejectTooHigh(); } \ TEST_F(Fixture, TestRotateOnly) { testRotateOnly(); } \ TEST_F(Fixture, TestAcceptAtlasSized) { testAcceptAtlasSized(); } \ TEST_F(Fixture, TestAcceptMultipleTiny) { testAcceptMultipleTiny(); } \ TEST_F(Fixture, TestVariableSizePacking) { testVariableSizePacking(); } \ TEST_F(Fixture, TestNonSquareSizePrediction) { testNonSquareSizePrediction(); } \ TEST_F(Fixture, TestTooSmallSizePrediction) { testTooSmallSizePrediction(); } ADD_TESTS_FOR_FIXTURE(ShelfNextFitPackingTest) ADD_TESTS_FOR_FIXTURE(MaxRectsPackingTest) #undef ADD_TESTS_FOR_FIXTURE TEST_F(MaxRectsPackingTest, TestNoFreeRect) { testNoFreeRect(); } TEST_F(MaxRectsPackingTest, TestFreeRectPruning) { testFreeRectPruning(); } TEST(PackingInternalsTest, TestCeilLog2) { for (int i = 0; i < 64; i++) { std::uint64_t twoToTheI = static_cast<std::uint64_t>(1) << i; EXPECT_EQ(i, llassetgen::internal::ceilLog2(twoToTheI)); EXPECT_EQ(i + 1, llassetgen::internal::ceilLog2(twoToTheI + 1)); if (twoToTheI > 2) { EXPECT_EQ(i, llassetgen::internal::ceilLog2(twoToTheI - 1)); } } EXPECT_EQ(64, llassetgen::internal::ceilLog2(std::numeric_limits<std::uint64_t>::max())); }
40.862661
117
0.631656
[ "vector" ]
cbf4e3666ef8c002f27bd086b0062805f16146f4
37,844
cpp
C++
sa_main.cpp
TheHolyJoker/Comparing-Filters
2c65a4bb2b788b5f0ecbaea33962e26c0c0b0301
[ "Apache-2.0" ]
7
2021-01-04T12:26:45.000Z
2022-02-07T18:41:04.000Z
sa_main.cpp
TheHolyJoker/Comparing_Filters
2e8ac44163847a09beaa72e4f399291907a96891
[ "Apache-2.0" ]
1
2021-03-15T03:21:30.000Z
2021-09-08T15:06:22.000Z
sa_main.cpp
TheHolyJoker/Comparing-Filters
2c65a4bb2b788b5f0ecbaea33962e26c0c0b0301
[ "Apache-2.0" ]
1
2021-07-06T08:38:42.000Z
2021-07-06T08:38:42.000Z
#include "dict_approximation_tests.hpp" void symmetric_difference_for_multiple_filters(size_t n, float PD_load, float CF_load) { using itemType = uint64_t; // using Table_ts_CF = ts_cuckoofilter::ts_CuckooFilter<uint64_t, BITS_PER_ELEMENT_MACRO, cuckoofilter::SingleTable>; using Table_ts_CF12_32 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 32>; using Table_ts_CF12_16 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 16>; using Table_ts_CF12_8 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 8>; using Table_ts_CF12_4 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 4>; using Table_DictApx512 = DictApx512<itemType>; using Table_TS_SIMD = TS_SimdBlockFilter<>; const size_t max_filter_capacity = (n);// load is .94 const float work_load = 0.95; const size_t max_number_of_elements_in_the_filter = (size_t) ceil(max_filter_capacity * work_load); const size_t lookup_reps = (n << 1); const size_t num_of_blocks_it_takes_to_fill_the_filter = 8; vector<itemType> vec_add, vec_find; vector<vector<itemType> *> elements{&vec_add, &vec_find}; init_vectors<itemType>(max_filter_capacity, work_load, lookup_reps, 2, &elements); constexpr size_t reps = 4; vector<size_t> vec_arr[reps * 2]; size_t vec_index = 0; vector<vector<size_t> *> temp_vec = {&vec_arr[vec_index++], &vec_arr[vec_index++]}; constexpr float starting_load = 0.65; constexpr float inc = 0.05; for (size_t i = 0; i < reps; i++) { float temp_load = starting_load + i * inc; compute_prob_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, temp_load, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); temp_vec.at(0) = &vec_arr[vec_index++]; temp_vec.at(1) = &vec_arr[vec_index++]; } compute_prob_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, PD_load, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); temp_vec.at(0) = &vec_arr[vec_index++]; temp_vec.at(1) = &vec_arr[vec_index++]; // auto line = std::string(40, '-'); // std::cout << line << std::endl; // compute_prob_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, PD_load, // lookup_reps, // num_of_blocks_it_takes_to_fill_the_filter); // bench_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, 0.9, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // std::cout << line << std::endl; } void error_rates_test() { // std::cout << "In pre_main:" << std::endl; using itemType = uint64_t; using Table_ts_CF = ts_cuckoofilter::ts_CuckooFilter<uint64_t, BITS_PER_ELEMENT_MACRO, cuckoofilter::SingleTable>; using Table_ts_CF12 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable>; using Table_DictApx512 = DictApx512<itemType>; constexpr size_t max_filter_capacity = (1 << 18);// load is .94 constexpr float work_load = 0.95; const size_t max_number_of_elements_in_the_filter = (size_t) ceil(max_filter_capacity * work_load); constexpr size_t lookup_reps = (1 << 19); constexpr size_t num_of_blocks_it_takes_to_fill_the_filter = 8; vector<itemType> vec_add, vec_find; vector<vector<itemType> *> elements{&vec_add, &vec_find}; init_vectors<itemType>(max_filter_capacity, work_load, lookup_reps, 2, &elements); auto line = std::string(40, '*'); std::cout << line << std::endl; compute_prob_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, 0.8, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // bench_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, 0.9, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; compute_prob_symmetric_difference_wrapper<Table_ts_CF12, itemType>(&elements, max_filter_capacity, 0.95, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; } void testing_error_rate_of_bff(size_t n) { using itemType = uint64_t; using Table_DictApx512 = DictApx512<itemType>; using Table_TS_SIMD = TS_SimdBlockFilter<>; const size_t max_filter_capacity = (n);// load is .94 const float work_load = 0.95; const size_t max_number_of_elements_in_the_filter = (size_t) ceil(max_filter_capacity * work_load); const size_t lookup_reps = (n << 1); const size_t num_of_blocks_it_takes_to_fill_the_filter = 8; vector<itemType> vec_add, vec_find; vector<vector<itemType> *> elements{&vec_add, &vec_find}; init_vectors<itemType>(max_filter_capacity, work_load, lookup_reps, 2, &elements); auto line = std::string(120, '='); // compute_prob_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, 0.7, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // std::cout << line << std::endl; // sleep(300); compute_prob_symmetric_difference_wrapper<Table_TS_SIMD, itemType>(&elements, max_filter_capacity, 0.75, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; // compute_prob_symmetric_difference_wrapper<Table_TS_SIMD, itemType>(&elements, max_filter_capacity, 0.5, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // std::cout << line << std::endl; // compute_prob_symmetric_difference_wrapper<Table_TS_SIMD, itemType>(&elements, max_filter_capacity, 0.25, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // std::cout << line << std::endl; // compute_prob_symmetric_difference_wrapper<Table_TS_SIMD, itemType>(&elements, max_filter_capacity, 0.1, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // std::cout << line << std::endl; return; } void error_rates_test_param(size_t n, float PD_load, float CF_load) { using itemType = uint64_t; // using Table_ts_CF = ts_cuckoofilter::ts_CuckooFilter<uint64_t, BITS_PER_ELEMENT_MACRO, cuckoofilter::SingleTable>; using Table_ts_CF12_32 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 32>; using Table_ts_CF12_16 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 16>; using Table_ts_CF12_8 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 8>; using Table_ts_CF12_4 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 4>; using Table_DictApx512 = DictApx512<itemType>; using Table_TS_SIMD = TS_SimdBlockFilter<>; const size_t max_filter_capacity = (n);// load is .94 const float work_load = 0.95; const size_t max_number_of_elements_in_the_filter = (size_t) ceil(max_filter_capacity * work_load); const size_t lookup_reps = (n << 1); const size_t num_of_blocks_it_takes_to_fill_the_filter = 8; vector<itemType> vec_add, vec_find; vector<vector<itemType> *> elements{&vec_add, &vec_find}; init_vectors<itemType>(max_filter_capacity, work_load, lookup_reps, 2, &elements); auto line = std::string(120, '='); // std::cout << line << std::endl; // compute_prob_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, PD_load, // lookup_reps, // num_of_blocks_it_takes_to_fill_the_filter); // bench_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, 0.9, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; // bench_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, PD_load, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // compute_prob_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, PD_load, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); compute_prob_symmetric_difference_wrapper<Table_TS_SIMD, itemType>(&elements, max_filter_capacity, 0.75, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; compute_prob_symmetric_difference_wrapper<Table_TS_SIMD, itemType>(&elements, max_filter_capacity, 0.5, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; compute_prob_symmetric_difference_wrapper<Table_TS_SIMD, itemType>(&elements, max_filter_capacity, 0.25, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; compute_prob_symmetric_difference_wrapper<Table_TS_SIMD, itemType>(&elements, max_filter_capacity, 0.1, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; return; // compute_prob_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, PD_load, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // compute_prob_symmetric_difference_wrapper<Table_ts_CF12_32, itemType>(&elements, max_filter_capacity, CF_load, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // compute_prob_symmetric_difference_wrapper<Table_ts_CF12_16, itemType>(&elements, max_filter_capacity, CF_load, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // compute_prob_symmetric_difference_wrapper<Table_ts_CF12_8, itemType>(&elements, max_filter_capacity, CF_load, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // compute_prob_symmetric_difference_wrapper<Table_ts_CF12_4, itemType>(&elements, max_filter_capacity, CF_load, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // std::cout << line << std::endl; bench_symmetric_difference_wrapper<Table_ts_CF12_4, itemType>(&elements, max_filter_capacity, 0.7, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; } void compute_how_many_evictions(size_t n, float load) { using itemType = uint64_t; // using Table_ts_CF = ts_cuckoofilter::ts_CuckooFilter<uint64_t, BITS_PER_ELEMENT_MACRO, cuckoofilter::SingleTable>; using Table_ts_CF12_32 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 32>; using Table_ts_CF12_16 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 16>; using Table_ts_CF12_8 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 8>; using Table_ts_CF12_4 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 4>; using Table_DictApx512 = DictApx512<itemType>; const size_t max_filter_capacity = (n);// load is .94 const float work_load = 0.95; const size_t max_number_of_elements_in_the_filter = (size_t) ceil(max_filter_capacity * work_load); const size_t lookup_reps = (n << 1); const size_t num_of_blocks_it_takes_to_fill_the_filter = 8; vector<itemType> vec_add, vec_find; vector<vector<itemType> *> elements{&vec_add, &vec_find}; init_vectors<itemType>(max_filter_capacity, work_load, lookup_reps, 2, &elements); auto line = std::string(40, '-'); auto big_sep = "\n\n" + std::string(40, '$') + "\n\n"; for (size_t i = 80; i < 95; i++) { double load = 1.0 * i / 100; std::cout << "load: " << load << std::endl; compute_prob_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, load, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; compute_prob_symmetric_difference_wrapper<Table_ts_CF12_32, itemType>(&elements, max_filter_capacity, load, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; compute_prob_symmetric_difference_wrapper<Table_ts_CF12_16, itemType>(&elements, max_filter_capacity, load, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; compute_prob_symmetric_difference_wrapper<Table_ts_CF12_8, itemType>(&elements, max_filter_capacity, load, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; compute_prob_symmetric_difference_wrapper<Table_ts_CF12_4, itemType>(&elements, max_filter_capacity, load, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; std::cout << big_sep << std::endl; } } void compute_how_many_evictions_only_pd(size_t n) { using itemType = uint64_t; using Table_DictApx512 = DictApx512<itemType>; const size_t max_filter_capacity = (n);// load is .94 const float work_load = 0.95; const size_t max_number_of_elements_in_the_filter = (size_t) ceil(max_filter_capacity * work_load); const size_t lookup_reps = (n << 1); const size_t num_of_blocks_it_takes_to_fill_the_filter = 8; vector<itemType> vec_add, vec_find; vector<vector<itemType> *> elements{&vec_add, &vec_find}; init_vectors<itemType>(max_filter_capacity, work_load, lookup_reps, 2, &elements); auto line = std::string(40, '-'); for (size_t i = 68; i < 82; i++) { double load = 1.0 * i / 100; std::cout << "load: " << load << std::endl; compute_prob_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, load, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; } } void pre_main() { std::cout << "In pre_main:" << std::endl; using itemType = uint64_t; using Table_ts_CF = ts_cuckoofilter::ts_CuckooFilter<uint64_t, BITS_PER_ELEMENT_MACRO, cuckoofilter::SingleTable>; using Table_ts_CF12 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable>; using Table_DictApx512 = DictApx512<itemType>; constexpr size_t max_filter_capacity = (1 << 18);// load is .94 constexpr float work_load = 0.95; const size_t max_number_of_elements_in_the_filter = (size_t) ceil(max_filter_capacity * work_load); constexpr size_t lookup_reps = (1 << 19); constexpr size_t num_of_blocks_it_takes_to_fill_the_filter = 8; vector<itemType> vec_add, vec_find; vector<vector<itemType> *> elements{&vec_add, &vec_find}; init_vectors<itemType>(max_filter_capacity, work_load, lookup_reps, 2, &elements); auto line = std::string(40, '*'); std::cout << line << std::endl; compute_prob_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, 0.9, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); bench_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, 0.9, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; compute_prob_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, 0.8, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); bench_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, 0.8, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; compute_prob_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, 0.7, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); bench_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, 0.7, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; compute_prob_symmetric_difference_wrapper<Table_ts_CF12, itemType>(&elements, max_filter_capacity, 0.8, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); bench_symmetric_difference_wrapper<Table_ts_CF12, itemType>(&elements, max_filter_capacity, 0.8, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; compute_prob_symmetric_difference_wrapper<Table_ts_CF, itemType>(&elements, max_filter_capacity, 0.8, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); bench_symmetric_difference_wrapper<Table_ts_CF, itemType>(&elements, max_filter_capacity, 0.8, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; compute_prob_symmetric_difference_wrapper<Table_ts_CF, itemType>(&elements, max_filter_capacity, 0.95, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); bench_symmetric_difference_wrapper<Table_ts_CF, itemType>(&elements, max_filter_capacity, 0.95, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; std::cout << line << std::endl; std::cout << line << std::endl; std::cout << line << std::endl; std::cout << line << std::endl; std::cout << line << std::endl; } void helper_for_printing_fp_rates() { using itemType = uint64_t; using Table_ts_CF = ts_cuckoofilter::ts_CuckooFilter<uint64_t, BITS_PER_ELEMENT_MACRO, cuckoofilter::SingleTable>; using Table_ts_CF12 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable>; using Table_DictApx512 = DictApx512<itemType>; using Table_Dict256_Ver7 = Dict256_Ver7<itemType>; constexpr size_t max_filter_capacity = (1 << 22); constexpr float work_load = 0.95; const size_t max_number_of_elements_in_the_filter = (size_t) ceil(max_filter_capacity * work_load); constexpr size_t lookup_reps = (1 << 23); constexpr size_t num_of_blocks_it_takes_to_fill_the_filter = 8; vector<itemType> vec_add, vec_find; vector<vector<itemType> *> elements{&vec_add, &vec_find}; init_vectors<itemType>(max_filter_capacity, work_load, lookup_reps, 3, &elements); auto line = std::string(40, '*'); // std::cout << line << std::endl; // std::cout << line << std::endl; // bench_symmetric_difference_wrapper<Table_Dict256_Ver7, itemType>(&elements, max_filter_capacity, 0.8, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // std::cout << line << std::endl; // std::cout << line << std::endl; auto big_sep = "\n\n" + std::string(40, '$') + "\n\n"; for (size_t i = 0; i < 4; i++) { compute_prob_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, 0.8, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; compute_prob_symmetric_difference_wrapper<Table_ts_CF, itemType>(&elements, max_filter_capacity, 0.94, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; std::cout << big_sep << std::endl; } return; compute_prob_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, 0.8, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; bench_symmetric_difference_wrapper<Table_ts_CF, itemType>(&elements, max_filter_capacity, 0.95, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; bench_symmetric_difference_wrapper<Table_ts_CF, itemType>(&elements, max_filter_capacity, 0.95, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; bench_symmetric_difference_wrapper<Table_ts_CF, itemType>(&elements, max_filter_capacity, 0.95, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; return; // bench_symmetric_difference_wrapper<Table_ts_CF, itemType>(&elements, max_filter_capacity, 0.8, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; // compute_prob_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, 0.8, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); bench_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, 0.8, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // bench_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, 0.8, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; bench_symmetric_difference_wrapper<Table_ts_CF, itemType>(&elements, max_filter_capacity, 0.95, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); compute_prob_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, 0.9, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; compute_prob_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, 0.7, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; // compute_prob_symmetric_difference_wrapper<Table_ts_CF, itemType>(&elements, max_filter_capacity, work_load, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // return 0; } void plot_error_graphs() { using itemType = uint64_t; auto sep_line = "|" + std::string(129, '-') + "|"; using Table_ts_CF12_32 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 32>; using Table_ts_CF12_16 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 16>; using Table_ts_CF12_8 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 8>; using Table_ts_CF12_4 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 4>; using Table_DictApx512 = DictApx512<itemType>; constexpr size_t max_filter_capacity = (1 << 24);// load is .94 constexpr float work_load = 0.95; const size_t max_number_of_elements_in_the_filter = (size_t) ceil(max_filter_capacity * work_load); constexpr size_t lookup_reps = (max_filter_capacity << 1); constexpr size_t num_of_blocks_it_takes_to_fill_the_filter = 32; vector<itemType> vec_add, vec_find; vector<vector<itemType> *> elements{&vec_add, &vec_find}; std::cout << std::string(80, '~') << std::endl; std::cout << "max_filter_capacity: " << max_filter_capacity << std::endl; std::cout << "work_load: " << work_load << std::endl; std::cout << "max_number_of_elements_in_the_filter: " << max_number_of_elements_in_the_filter << std::endl; std::cout << "lookup_reps: " << lookup_reps << std::endl; std::cout << "num_of_blocks_it_takes_to_fill_a_filter: " << num_of_blocks_it_takes_to_fill_the_filter << std::endl; std::cout << std::string(80, '~') << std::endl; std::cout << std::endl; init_vectors<itemType>(max_filter_capacity, work_load, lookup_reps, 2, &elements); for (size_t i = 70; i < 91; i += 10) { float load = 1.0 * i / 100; // std::cout << "load: " << load << std::endl; compute_prob_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, load, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << std::endl; } for (size_t i = 70; i < 91; i += 10) { float load = 1.0 * i / 100; compute_prob_symmetric_difference_wrapper<Table_ts_CF12_4, itemType>(&elements, max_filter_capacity, load, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << std::endl; } for (size_t i = 70; i < 91; i += 10) { float load = 1.0 * i / 100; compute_prob_symmetric_difference_wrapper<Table_ts_CF12_8, itemType>(&elements, max_filter_capacity, load, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << std::endl; } for (size_t i = 70; i < 91; i += 10) { float load = 1.0 * i / 100; compute_prob_symmetric_difference_wrapper<Table_ts_CF12_16, itemType>(&elements, max_filter_capacity, load, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << std::endl; } } void plot_thorughput_graphs() { using itemType = uint64_t; auto sep_line = "|" + std::string(129, '-') + "|"; using Table_ts_CF12_32 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 32>; using Table_ts_CF12_16 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 16>; using Table_ts_CF12_8 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 8>; using Table_ts_CF12_4 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 4>; using Table_DictApx512 = DictApx512<itemType>; constexpr size_t max_filter_capacity = (1 << 24);// load is .94 constexpr float work_load = 0.95; const size_t max_number_of_elements_in_the_filter = (size_t) ceil(max_filter_capacity * work_load); constexpr size_t lookup_reps = (max_filter_capacity << 2); constexpr size_t num_of_blocks_it_takes_to_fill_the_filter = 32; vector<itemType> vec_add, vec_find; vector<vector<itemType> *> elements{&vec_add, &vec_find}; std::cout << std::string(80, '~') << std::endl; std::cout << "max_filter_capacity: " << max_filter_capacity << std::endl; std::cout << "work_load: " << work_load << std::endl; std::cout << "max_number_of_elements_in_the_filter: " << max_number_of_elements_in_the_filter << std::endl; std::cout << "lookup_reps: " << lookup_reps << std::endl; std::cout << "num_of_blocks_it_takes_to_fill_a_filter: " << num_of_blocks_it_takes_to_fill_the_filter << std::endl; std::cout << std::string(80, '~') << std::endl; std::cout << std::endl; init_vectors<itemType>(max_filter_capacity, work_load, lookup_reps, 3, &elements); bench_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, .7, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << std::endl; bench_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, .85, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << std::endl; bench_symmetric_difference_wrapper<Table_ts_CF12_4, itemType>(&elements, max_filter_capacity, 0.7, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << std::endl; bench_symmetric_difference_wrapper<Table_ts_CF12_4, itemType>(&elements, max_filter_capacity, 0.85, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << std::endl; std::cout << sep_line << std::endl; std::cout << sep_line << std::endl; return; } int old_main(int argc, char **argv) { using itemType = uint64_t; auto sep_line = "|" + std::string(129, '-') + "|"; // #ifndef NDEBUG // assert(pd512::select64(4, 0) == 2); // error_rates_test(); // return 0; // auto temp = (DEBUG); // #ifndef NDEBUG // std::cout << "here!" << std::endl; // error_rates_test(); // #else // assert(0); // #endif // #ifdef VALIDATE // pre_main(); // #endif // auto big_sep = "\n\n" + std::string(40, '$') + "\n\n"; // std::cout << big_sep << std::endl; // helper_for_printing_fp_rates(); // std::cout << big_sep << std::endl; // error_rates_test(); // error_rates_test_param(1ull << 16, 0.7, 0.7); // std::cout << std::string(80, '$') << std::endl; // error_rates_test_param(1ull << 17, 0.7, 0.7); // std::cout << std::string(80, '$') << std::endl; // error_rates_test_param(1ull << 18, 0.7, 0.7); // std::cout << std::string(80, '$') << std::endl; // error_rates_test_param(1ull << 21, 0.7, 0.7); // std::cout << std::string(80, '$') << std::endl; // return 0; // error_rates_test_param(20, 0.25); // error_rates_test_param(20, 0.5); // error_rates_test_param(20, 0.75); // return 0; using Table_ts_CF12_32 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 32>; using Table_ts_CF12_16 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 16>; using Table_ts_CF12_8 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 8>; using Table_ts_CF12_4 = ts_cuckoofilter::ts_CuckooFilter<uint64_t, 12, cuckoofilter::SingleTable, cuckoofilter::TwoIndependentMultiplyShift, 4>; using Table_DictApx512 = DictApx512<itemType>; using Table_TS_SIMD = TS_SimdBlockFilter<>; // constexpr size_t max_filter_capacity = 15435038UL; // load is .92 // constexpr size_t max_filter_capacity = 15770583UL;// load is .94 constexpr size_t max_filter_capacity = (1 << 26);// load is .94 constexpr float work_load = 0.95; const size_t max_number_of_elements_in_the_filter = (size_t) ceil(max_filter_capacity * work_load); // constexpr size_t max_filter_capacity = 15435038UL >> 3;// load is .92 // const size_t max_filter_capacity = 62411242; // constexpr size_t lookup_reps = 124822484; constexpr size_t lookup_reps = (max_filter_capacity << 1); // constexpr size_t lookup_reps = (max_filter_capacity << 1); // constexpr size_t bench_precision = 16; constexpr size_t num_of_blocks_it_takes_to_fill_the_filter = 32; vector<itemType> vec_add, vec_find; vector<vector<itemType> *> elements{&vec_add, &vec_find}; std::cout << std::string(80, '~') << std::endl; std::cout << "max_filter_capacity: " << max_filter_capacity << std::endl; std::cout << "work_load: " << work_load << std::endl; std::cout << "max_number_of_elements_in_the_filter: " << max_number_of_elements_in_the_filter << std::endl; std::cout << "lookup_reps: " << lookup_reps << std::endl; std::cout << "num_of_blocks_it_takes_to_fill_a_filter: " << num_of_blocks_it_takes_to_fill_the_filter << std::endl; std::cout << std::string(80, '~') << std::endl; std::cout << std::endl; init_vectors<itemType>(max_filter_capacity, work_load, lookup_reps, 3, &elements); auto line = std::string(40, '-'); // bench_symmetric_difference_wrapper<Table_ts_CF12_4, itemType>(&elements, max_filter_capacity, 0.7, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // std::cout << line << std::endl; bench_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, .7, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; // bench_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, .75, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // std::cout << line << std::endl; // bench_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, .8, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // std::cout << line << std::endl; bench_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, .85, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; // bench_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, .9, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // std::cout << line << std::endl; // bench_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, .95, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // std::cout << line << std::endl; // bench_symmetric_difference_wrapper<Table_ts_CF12_32, itemType>(&elements, max_filter_capacity, 0.80, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // std::cout << line << std::endl; // bench_symmetric_difference_wrapper<Table_ts_CF12_16, itemType>(&elements, max_filter_capacity, 0.8, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // // bench_symmetric_difference_wrapper<Table_ts_CF12_16, itemType>(&elements, max_filter_capacity, 0.90, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // // std::cout << line << std::endl; // bench_symmetric_difference_wrapper<Table_ts_CF12_8, itemType>(&elements, max_filter_capacity, 0.8, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // std::cout << line << std::endl; // std::cout << sep_line << std::endl; // return 0; bench_symmetric_difference_wrapper<Table_ts_CF12_4, itemType>(&elements, max_filter_capacity, 0.7, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; // bench_symmetric_difference_wrapper<Table_ts_CF12_4, itemType>(&elements, max_filter_capacity, 0.75, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // std::cout << line << std::endl; // bench_symmetric_difference_wrapper<Table_ts_CF12_4, itemType>(&elements, max_filter_capacity, 0.8, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // std::cout << line << std::endl; bench_symmetric_difference_wrapper<Table_ts_CF12_4, itemType>(&elements, max_filter_capacity, 0.85, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << line << std::endl; // bench_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, 0.8, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // std::cout << line << std::endl; // bench_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, 0.85, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // std::cout << line << std::endl; // bench_symmetric_difference_wrapper<Table_DictApx512, itemType>(&elements, max_filter_capacity, 0.9, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); // std::cout << line << std::endl; // bench_symmetric_difference_wrapper<Table_ts_CF, itemType>(&elements, max_filter_capacity, 0.95, lookup_reps, num_of_blocks_it_takes_to_fill_the_filter); std::cout << sep_line << std::endl; std::cout << sep_line << std::endl; return 0; } int main(int argc, char **argv) { old_main(argc, argv); // plot_error_graphs(); // plot_thorughput_graphs(); // testing_error_rate_of_bff(1<<22); return 0; }
60.5504
177
0.689066
[ "vector" ]
cbf799ca3c08720107ff1c7872c0b70044b5d6da
509
hpp
C++
app/tgit/src/History.hpp
Templar-von-Midgard/tgit
d3d1f5148d7570d17672b02ae571ba3589d48713
[ "MIT" ]
3
2019-02-20T11:58:54.000Z
2021-05-09T00:12:52.000Z
app/tgit/src/History.hpp
Templar-von-Midgard/tgit
d3d1f5148d7570d17672b02ae571ba3589d48713
[ "MIT" ]
7
2019-02-12T21:15:29.000Z
2019-03-05T23:41:45.000Z
app/tgit/src/History.hpp
Templar-von-Midgard/tgit
d3d1f5148d7570d17672b02ae571ba3589d48713
[ "MIT" ]
3
2019-02-20T11:59:34.000Z
2019-04-16T10:31:46.000Z
#ifndef HISTORY_HPP #define HISTORY_HPP #include <vector> #include <gitpp/ObjectId.hpp> #include "GraphRow.hpp" namespace gitpp { class Repository; class Commit; } // namespace gitpp class History { public: explicit History(const gitpp::Repository& repository); int size() const; gitpp::Commit commit(int row) const; GraphRow graph(int row) const; private: const gitpp::Repository& Repository; std::vector<gitpp::ObjectId> Commits; std::vector<GraphRow> Graph; }; #endif // HISTORY_HPP
16.419355
56
0.732809
[ "vector" ]
cbf7b86ac6237f962a81cb2408c0cba5e05826e2
1,659
cpp
C++
AS-environment.cpp
ede1998/asteroids
d4a8f5e069f55c00fa1dcf6b3c849bce00fcaf0c
[ "MIT" ]
null
null
null
AS-environment.cpp
ede1998/asteroids
d4a8f5e069f55c00fa1dcf6b3c849bce00fcaf0c
[ "MIT" ]
null
null
null
AS-environment.cpp
ede1998/asteroids
d4a8f5e069f55c00fa1dcf6b3c849bce00fcaf0c
[ "MIT" ]
null
null
null
/* * * file: AS-environment.cpp * * author: Erik Hennig * * date: 29.12.2016 * * abstract: controls environment of asteroids game */ #include "AS-environment.h" #include <algorithm> #include <iostream> extern uint32_t NOW; Environment::Environment(Spaceship& s) : _last_generation ( 0 ), _spaceship ( s ) { for (int i = 0; i < 1; ++i) { _asteroids.push_back(Asteroid::generate(5)); } } Environment::~Environment() { } void Environment::render() { std::for_each(std::begin(_asteroids), std::end(_asteroids), [](const Asteroid& a){ a.render(); }); } int Environment::detectCollision(Spaceship s) { const auto& ship = s.getShape(); std::for_each(_asteroids.begin(), _asteroids.end(), [ship] (const Asteroid& a) { if (a.getShape().checkCollision(ship)) { std::cout << "asteroid:" << a._positionx << " " << a._positiony; std::cout << " collision" << std::endl; } }); return -1; } void Environment::detectCollision(Bullet b) { } void Environment::process(double tp) { std::for_each(std::begin(_asteroids), std::end(_asteroids), [tp](Asteroid& a) { a.process(tp); }); if (_last_generation + GENERATION_COOLDOWN < NOW) { _asteroids.push_back(Asteroid::generate(5)); _last_generation = NOW; } detectCollision(_spaceship); } void Environment::generate() { } void Environment::splitAsteroid() { } void Environment::checkHealth() { } int Environment::calcmass() { return -1; }
18.433333
75
0.571429
[ "render" ]
020898caa08255660a237a9ae525adf9133baf27
1,189
cpp
C++
src/1000/1948.cpp17.cpp
upple/BOJ
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
[ "MIT" ]
8
2018-04-12T15:54:09.000Z
2020-06-05T07:41:15.000Z
src/1000/1948.cpp17.cpp
upple/BOJ
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
[ "MIT" ]
null
null
null
src/1000/1948.cpp17.cpp
upple/BOJ
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; const int INF=-1; struct edge{int v, c;}; int n, m; vector<edge> adj[100001], rvs[100001]; int in[100001], dist[100001]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin>>n>>m; while(m--) { int a, b, c; cin>>a>>b>>c; adj[a].push_back({b, c}); rvs[b].push_back({a, c}); in[b]++; } int s, t; int cnt=0; cin>>s>>t; queue<int> Q; Q.push(s); memset(dist, INF, sizeof(dist)); dist[s]=0; while(Q.size()) { int cur=Q.front(); Q.pop(); for(auto &[next, cost] : adj[cur]) { dist[next]=max(dist[next], dist[cur]+cost); if(--in[next]==0) { Q.push(next); } } } Q.push(t); in[t]=1; while(Q.size()) { int cur=Q.front(); Q.pop(); for(auto &[next, cost] : rvs[cur]) { if(dist[cur]-cost==dist[next]) { if(in[next]==0) Q.push(next); in[next]=1; cnt++; } } } cout<<dist[t]<<'\n'<<cnt; }
18.292308
55
0.406224
[ "vector" ]
020c05b708288e73a18ad99b131fceef7787f93e
2,009
cpp
C++
0321_cs_test/02.cpp
zhangdan0602/DailyAlgorithm
2969ed143b16c5c655d39ff3a86ee5f0cabb704a
[ "Apache-2.0" ]
null
null
null
0321_cs_test/02.cpp
zhangdan0602/DailyAlgorithm
2969ed143b16c5c655d39ff3a86ee5f0cabb704a
[ "Apache-2.0" ]
null
null
null
0321_cs_test/02.cpp
zhangdan0602/DailyAlgorithm
2969ed143b16c5c655d39ff3a86ee5f0cabb704a
[ "Apache-2.0" ]
null
null
null
// // Created by ZD-Mac on 2021/3/21. // /* * Friend 时间限制: 1.0 秒 空间限制: 512 MiB 题目描述 F 学校有 𝑛 个学生,编号为 1,2,…,𝑛。这些学生之间存在 𝑚 对好友关系。 每对好友关系形如:𝑢𝑗 号学生与 𝑣𝑗 号学生互为好友(1≤𝑗≤𝑚)。 好友关系是双向的,这意味着 𝑢𝑗 号学生是 𝑣𝑗 号学生的好友,同时 𝑣𝑗 号学生也是 𝑢𝑗 号学生的好友。 F 学校要将 𝑛 个学生均匀(等概率)随机地分为若干小组,每组 3 个学生。 保证 𝑛 是 3 的倍数,即能够恰好分完。在分组完毕后,每个组内的好友关系也会有不同的情况。 现在,对于每个学生 𝑖,他希望计算他所在小组的 3 个学生当中以下每个事件发生的概率: 3 个学生两两均不为好友; 3 个学生中,除自己外的 2 个学生互为好友,不存在其他好友关系; 3 个学生中,自己与另外某个学生互为好友,不存在其他好友关系; 3 个学生中,恰好有 2 对好友关系,且有 2 个好友的那个人是自己 (即:自己与另外 2 个学生分别互为好友,但他们两个不为好友); 3 个学生中,恰好有 2 对好友关系,但有 2 个好友的那个人不是自己 (即:存在某个学生 A 与自己和另外一个学生 B(分别)互为好友,但自己与 B 不为好友); 3 个学生中两两互为好友。 请帮助每个学生计算吧! 输入格式 从标准输入读入数据。 第一行输入两个正整数 𝑛,𝑚,以空格隔开。 接下来 𝑚 行,每行输入两个正整数 𝑢𝑗,𝑣𝑗,以空格隔开,表示 𝑢𝑗 与 𝑣𝑗 号学生互为好友。 输出格式 输出到标准输出。 输出 𝑛 行,每行 6 个最简分数,以空格隔开,表示每个学生每种情况的发生概率。 输出最简分数的形式为:先输出分子,再输出斜线 /,最后输出分母。你应当输出最简分数,例如不应当输出 3/6,而应输出 1/2。 特殊地,如果所求的某个概率为 0,应当输出 0/1;概率为 1 则输出 1/1。 样例1输入 3 2 1 2 1 3 样例1输出 0/1 0/1 0/1 1/1 0/1 0/1 0/1 0/1 0/1 0/1 1/1 0/1 0/1 0/1 0/1 0/1 1/1 0/1 样例1解释 一共只有 3 个学生,分组实际上仅有 1 种方案,不存在随机性。 3 个学生之间存在 2 对好友关系,在 1 号学生看来是第 4 种情况,在 2 号和 3 号学生看来是第 5 种情况。 样例2输入 6 6 1 2 2 3 3 1 1 4 1 5 1 6 样例2输出 0/1 0/1 0/1 9/10 0/1 1/10 3/10 0/1 3/10 0/1 3/10 1/10 3/10 0/1 3/10 0/1 3/10 1/10 1/2 1/10 0/1 0/1 2/5 0/1 1/2 1/10 0/1 0/1 2/5 0/1 1/2 1/10 0/1 0/1 2/5 0/1 子任务 对于所有的数据,3≤𝑛≤30000 且 𝑛 是 3 的倍数,0≤𝑚≤300000。 (14 分)子任务 1:𝑛≤3,𝑚≤3; (12 分)子任务 2:𝑛≤30,𝑚≤300; (12 分)子任务 3:𝑛≤300,𝑚≤3000; (34 分)子任务 4:𝑛≤3000,𝑚≤30000; (28 分)子任务 5:𝑛≤30000,𝑚≤300000。 语言及编译选项信息 # 名称 编译器 额外参数 代码长度限制(B) 0 g++ with std17 g++ -O2 -std=c++17 -DONLINE_JUDGE 65536 1 g++ g++ -O2 -DONLINE_JUDGE 65536 2 gcc with std17 gcc -O2 -std=c17 -DONLINE_JUDGE 65536 3 gcc gcc -O2 -DONLINE_JUDGE 65536 4 java javac 65536 5 python python 65536 6 python3 python3 65536 */ #include <iostream> #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <time.h> #include <algorithm> #include <iostream> #include <set> #include <map> #include <queue> #include <stack> #include <vector> #include <string> using namespace std;
18.431193
63
0.692384
[ "vector" ]
020f06cf958845003b09d960194f0bb3f24199e9
4,033
cpp
C++
src/dmp_discrete/CanonicalSystemDiscrete.cpp
gsutanto/dmp
4f4492cf4295d9c3fe0ba9ce2fb726bf37be40df
[ "MIT" ]
null
null
null
src/dmp_discrete/CanonicalSystemDiscrete.cpp
gsutanto/dmp
4f4492cf4295d9c3fe0ba9ce2fb726bf37be40df
[ "MIT" ]
null
null
null
src/dmp_discrete/CanonicalSystemDiscrete.cpp
gsutanto/dmp
4f4492cf4295d9c3fe0ba9ce2fb726bf37be40df
[ "MIT" ]
null
null
null
#include "dmp/dmp_discrete/CanonicalSystemDiscrete.h" namespace dmp { CanonicalSystemDiscrete::CanonicalSystemDiscrete() : CanonicalSystem(), order(2), alpha(25.0), beta(25.0 / 4.0), x(0), xd(0), xdd(0), v(0), vd(0) {} CanonicalSystemDiscrete::CanonicalSystemDiscrete( TauSystem* tau_system, RealTimeAssertor* real_time_assertor, uint cs_order, std::vector<CanonicalCoupling*>* canonical_couplers) : CanonicalSystem(tau_system, real_time_assertor, canonical_couplers) { order = cs_order; if (order == 2) { alpha = 25.0; beta = alpha / 4.0; } else { order = 1; alpha = 25.0 / 3.0; beta = 0.0; } x = 1.0; xd = 0.0; xdd = 0.0; v = 0.0; vd = 0.0; } CanonicalSystemDiscrete::CanonicalSystemDiscrete( TauSystem* tau_system, uint cs_order, double cs_alpha, RealTimeAssertor* real_time_assertor, std::vector<CanonicalCoupling*>* canonical_couplers) : CanonicalSystem(tau_system, real_time_assertor, canonical_couplers) { order = cs_order; alpha = cs_alpha; if (order == 2) { beta = alpha / 4.0; } else { order = 1; beta = 0.0; } x = 1.0; xd = 0.0; xdd = 0.0; v = 0.0; vd = 0.0; } CanonicalSystemDiscrete::CanonicalSystemDiscrete( TauSystem* tau_system, uint cs_order, double cs_alpha, double cs_beta, RealTimeAssertor* real_time_assertor, std::vector<CanonicalCoupling*>* canonical_couplers) : CanonicalSystem(tau_system, real_time_assertor, canonical_couplers) { order = cs_order; alpha = cs_alpha; beta = cs_beta; x = 1.0; xd = 0.0; xdd = 0.0; v = 0.0; vd = 0.0; } bool CanonicalSystemDiscrete::isValid() { if (rt_assert(CanonicalSystem::isValid()) == false) { return false; } if (rt_assert((rt_assert(order >= 1)) && (rt_assert(order <= 2))) == false) { return false; } if (rt_assert(alpha > 0.0) == false) { return false; } if (rt_assert(beta >= 0.0) == false) { return false; } return true; } bool CanonicalSystemDiscrete::start() { if (rt_assert(CanonicalSystemDiscrete::isValid()) == false) { return false; } x = 1.0; xd = 0.0; xdd = 0.0; v = 0.0; vd = 0.0; is_started = true; return true; } uint CanonicalSystemDiscrete::getOrder() { return order; } double CanonicalSystemDiscrete::getAlpha() { return alpha; } double CanonicalSystemDiscrete::getBeta() { return beta; } double CanonicalSystemDiscrete::getX() { return x; } double CanonicalSystemDiscrete::getXd() { return xd; } double CanonicalSystemDiscrete::getXdd() { return xdd; } double CanonicalSystemDiscrete::getCanonicalPosition() { return x; } double CanonicalSystemDiscrete::getCanonicalMultiplier() { if (order == 1) { return (x); } else if (order == 2) { return (v); } else { return 0.0; } } Vector3 CanonicalSystemDiscrete::getCanonicalState() { Vector3 canonical_state; canonical_state << x, xd, xdd; return (canonical_state); } bool CanonicalSystemDiscrete::updateCanonicalState(double dt) { if (rt_assert(is_started == true) == false) { return false; } if (rt_assert(CanonicalSystemDiscrete::isValid()) == false) { return false; } // input checking if (rt_assert(dt > 0.0) == false) // dt does NOT make sense { return false; } double tau; if (rt_assert(tau_sys->getTauRelative(tau)) == false) { return false; } double C_c = 0.0; if (rt_assert(CanonicalSystem::getCouplingTerm(C_c)) == false) { return false; } if (order == 2) { xdd = vd / tau; vd = ((alpha * ((beta * (0 - x)) - v)) + C_c) / tau; xd = v / tau; } else { // if (order == 1) xdd = vd / tau; vd = 0.0; // vd is irrelevant for 1st order canonical system, no need for // computation xd = ((alpha * (0 - x)) + C_c) / tau; } x = x + (xd * dt); v = v + (vd * dt); if (rt_assert(x >= 0.0) == false) { return false; } return true; } CanonicalSystemDiscrete::~CanonicalSystemDiscrete() {} } // namespace dmp
22.530726
79
0.6303
[ "vector" ]
021195b4badbd50ba1dc7effc346370f35091b25
2,992
cpp
C++
src/ar_render_node.cpp
Tuebel/scigl_render_ros
6afa6b6981a7fb6b51f3a719a8143600e7bd39e7
[ "MIT" ]
null
null
null
src/ar_render_node.cpp
Tuebel/scigl_render_ros
6afa6b6981a7fb6b51f3a719a8143600e7bd39e7
[ "MIT" ]
null
null
null
src/ar_render_node.cpp
Tuebel/scigl_render_ros
6afa6b6981a7fb6b51f3a719a8143600e7bd39e7
[ "MIT" ]
null
null
null
#include <scigl_render_ros/ar_render_node.hpp> #include <scigl_render_ros/camera_init.hpp> namespace scigl_render_ros { const std::string CAMERA_TOPIC = "camera/color/image_raw"; ArRenderNode::ArRenderNode() : tf_listener(tf_buffer), img_transport(node_handle) { ros::NodeHandle private_nh("~"); // frames private_nh.param<std::string>("world_frame_id", world_frame_id, "world"); private_nh.param<std::string>("object_frame_id", object_frame_id, "object"); private_nh.param<std::string>("light_frame_id", light_frame_id, "light"); // publisher for the augmented reality image ar_publisher = img_transport.advertiseCamera("/ar_camera/color/image_raw", 1); // model to render private_nh.param<std::string>("model_path", model_path, "/model/beckenkamm.3ds"); } void ArRenderNode::run() { namespace ph = std::placeholders; ROS_INFO("waiting for camera info"); auto camera_info = CameraInit::wait_for_info(CAMERA_TOPIC, node_handle); ar_render = std::unique_ptr<ArRender>(new ArRender( model_path, camera_info)); ROS_INFO("initalized OpenGL renderer"); // subscribe the images and publish the modified ones image_transport::CameraSubscriber ar_subscriber = img_transport.subscribeCamera(CAMERA_TOPIC, 1, &ArRenderNode::camera_callback, this); // block to keep ar_render in scope ros::spin(); } void ArRenderNode::camera_callback(const sensor_msgs::ImageConstPtr &image, const sensor_msgs::CameraInfoConstPtr &info) { try { auto camera_pose = tf_buffer.lookupTransform(world_frame_id, info->header.frame_id, ros::Time(0), ros::Duration(1)); auto object_pose = tf_buffer.lookupTransform(world_frame_id, object_frame_id, ros::Time(0), ros::Duration(1)); auto light_pose = tf_buffer.lookupTransform(world_frame_id, light_frame_id, ros::Time(0), ros::Duration(1)); // publish rendered image if (ar_publisher.getNumSubscribers() > 0) { ar_publisher.publish(ar_render->render(camera_pose, object_pose, light_pose, image), info); } } catch (tf2::TransformException &ex) { ROS_WARN("%s", ex.what()); // avoid black screen if (ar_publisher.getNumSubscribers() > 0) { ar_publisher.publish(image, info); } } } } // namespace scigl_render_ros int main(int argc, char **argv) { // init ros ros::init(argc, argv, "ar_render_node"); ros::NodeHandle nh; scigl_render_ros::ArRenderNode render_node; // will block/spin render_node.run(); return EXIT_SUCCESS; }
36.048193
83
0.606283
[ "render", "object", "model" ]
021b5ae1bbb3408f54647d3d71048c13b079a9c2
2,228
hpp
C++
module-db/Tables/CountryCodesTable.hpp
bitigchi/MuditaOS
425d23e454e09fd6ae274b00f8d19c57a577aa94
[ "BSL-1.0" ]
369
2021-11-10T09:20:29.000Z
2022-03-30T06:36:58.000Z
module-db/Tables/CountryCodesTable.hpp
bitigchi/MuditaOS
425d23e454e09fd6ae274b00f8d19c57a577aa94
[ "BSL-1.0" ]
149
2021-11-10T08:38:35.000Z
2022-03-31T23:01:52.000Z
module-db/Tables/CountryCodesTable.hpp
bitigchi/MuditaOS
425d23e454e09fd6ae274b00f8d19c57a577aa94
[ "BSL-1.0" ]
41
2021-11-10T08:30:37.000Z
2022-03-29T08:12:46.000Z
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #pragma once #include "Common/Common.hpp" #include "Database/Database.hpp" #include "Record.hpp" #include "Table.hpp" #include "utf8/UTF8.hpp" #include <string> struct CodesTableRow : public Record { uint32_t mcc; uint32_t mnc; std::string iso; std::string country; uint32_t country_code; std::string network; }; enum CodesTableFields { }; class CountryCodesTable : public Table<CodesTableRow, CodesTableFields> { public: CountryCodesTable(Database *db); virtual ~CountryCodesTable(); bool create() override final; uint32_t count() override final; bool add(CodesTableRow entry) override final { return (true); } bool removeById(uint32_t id) override final { return (true); } bool update(CodesTableRow entry) override final { return (true); } CodesTableRow getById(uint32_t id) override final { return CodesTableRow(); } std::vector<CodesTableRow> getLimitOffset(uint32_t offset, uint32_t limit) override final { return std::vector<CodesTableRow>(); } std::vector<CodesTableRow> getLimitOffsetByField(uint32_t offset, uint32_t limit, CodesTableFields field, const char *str) override final { return std::vector<CodesTableRow>(); } uint32_t countByFieldId(const char *field, uint32_t id) override final { return count(); } CodesTableRow GetByMCC(uint32_t mcc); private: const char *createTableQuery = "CREATE TABLE IF NOT EXISTS codes(" "_id INTEGER PRIMARY KEY," "mcc INTEGER," "mnc INTEGER," "iso TEXT NOT NULL," "country TEXT NOT NULL," "country_code INTEGER," "network TEXT NOT NULL);"; };
29.315789
93
0.560592
[ "vector" ]
02215d39c53aeaa1d1065573ba6bf82e5da55870
2,078
cpp
C++
src/limitless/models/plane.cpp
hotstreams/graphicsengine
47736452f1f4d977f60354900ee4a81dca47ca0d
[ "MIT" ]
null
null
null
src/limitless/models/plane.cpp
hotstreams/graphicsengine
47736452f1f4d977f60354900ee4a81dca47ca0d
[ "MIT" ]
null
null
null
src/limitless/models/plane.cpp
hotstreams/graphicsengine
47736452f1f4d977f60354900ee4a81dca47ca0d
[ "MIT" ]
null
null
null
#include <limitless/models/plane.hpp> using namespace Limitless; #include <limitless/util/tangent_space.hpp> #include <limitless/models/mesh.hpp> #include <limitless/core/indexed_stream.hpp> Plane::Plane() : ElementaryModel("plane") { /* Plane size (1, 0, 1) centered at (0, 0, 0) */ std::vector<VertexNormalTangent> vertices = { { {0.5f, 0.0f, -0.5f}, { 0.0f, 1.0f, 0.0f }, glm::vec3{0.0f}, {1.0f, 1.0f} }, { {0.5f, 0.0f, 0.5f}, { 0.0f, 1.0f, 0.0f }, glm::vec3{0.0f}, {1.0f, 0.0f} }, { {-0.5f, 0.0f, 0.5f}, { 0.0f, 1.0f, 0.0f }, glm::vec3{0.0f}, {0.0f, 0.0f} }, { {-0.5f, 0.0f, -0.5f}, { 0.0f, 1.0f, 0.0f }, glm::vec3{0.0f}, {0.0f, 1.0f} } }; std::vector<GLuint> indices = { 0, 1, 3, 1, 2, 3 }; calculateTangentSpaceTriangle(vertices, indices); meshes.emplace_back( std::make_unique<Mesh>( std::make_unique<IndexedVertexStream<VertexNormalTangent>>(std::move(vertices), std::move(indices), VertexStreamUsage::Static, VertexStreamDraw::Triangles), "plane_mesh") ); calculateBoundingBox(); } PlaneQuad::PlaneQuad() : ElementaryModel("planequad") { /* Plane size (1, 0, 1) centered at (0, 0, 0) */ std::vector<VertexNormalTangent> vertices = { { {-0.5f, 0.0f, -0.5f}, { 0.0f, 1.0f, 0.0f }, glm::vec3{0.0f}, {0.0f, 1.0f} }, { {0.5f, 0.0f, -0.5f}, { 0.0f, 1.0f, 0.0f }, glm::vec3{0.0f}, {1.0f, 1.0f} }, { {-0.5f, 0.0f, 0.5f}, { 0.0f, 1.0f, 0.0f }, glm::vec3{0.0f}, {0.0f, 0.0f} }, { {0.5f, 0.0f, 0.5f}, { 0.0f, 1.0f, 0.0f }, glm::vec3{0.0f}, {1.0f, 0.0f} }, }; std::vector<GLuint> indices = { 0, 1, 3, 1, 2, 3 }; calculateTangentSpaceTriangle(vertices, indices); meshes.emplace_back( std::make_unique<Mesh>( std::make_unique<VertexStream<VertexNormalTangent>>(std::move(vertices), VertexStreamUsage::Static, VertexStreamDraw::Patches), "planequad_mesh") ); calculateBoundingBox(); }
36.45614
168
0.546679
[ "mesh", "vector" ]
022e7a566e34d4536ece418e2635ae907f56e342
1,448
hpp
C++
src/synth/voice.hpp
faemiyah/faemiyah-demoscene_2016-08_80k-intro_ghosts_of_mars
69a79a8cb68591c834989e89be530a1a94fb02c2
[ "BSD-3-Clause" ]
null
null
null
src/synth/voice.hpp
faemiyah/faemiyah-demoscene_2016-08_80k-intro_ghosts_of_mars
69a79a8cb68591c834989e89be530a1a94fb02c2
[ "BSD-3-Clause" ]
null
null
null
src/synth/voice.hpp
faemiyah/faemiyah-demoscene_2016-08_80k-intro_ghosts_of_mars
69a79a8cb68591c834989e89be530a1a94fb02c2
[ "BSD-3-Clause" ]
null
null
null
#ifndef _VOICE_H_ #define _VOICE_H_ #include "types.hpp" #include "instrument.hpp" #include "controller.hpp" #include "globalconfig.hpp" #include <cstdint> class Voice { static const unsigned int OVERSAMPLE_FACTOR = 4; Vector<uint32_t> osc_ctr; // Current voice params. Initialized from instrument on note on, // modified by envelopes. Vector<sample_t> params; Vector<sample_t> osc_pitches; int32_t osc_increments[GlobalConfig::max_oscs_per_voice]; sample_t oscillator(); sample_t filter(sample_t in); void run_modulation(const Vector<Controller> &rt_controls); int mod_ctr = 0; int fade_ctr = 0; // if > 0, we're doing a quick fade at note cut for this many samples public: int instrument = -1; int note = -1; int octave = -1; bool pressed = false; bool sustained = false; Vector<Instrument::OscShape> osc_shapes; // Filter state for this voice sample_t flt_p1 = 0.0; sample_t flt_p2 = 0.0; // Filter parameters, updated once per modulation update cycle. sample_t flt_modulated_cutoff = 0.0; sample_t flt_fb_amount = 0.0; sample_t out[2]; Voice(); void set_on(int _instrument, int _note, int _octave, const Instrument &instrument_ref); void set_off(); void set_param(size_t param_idx, sample_t value); void run(const Vector<Controller> &rt_controls, sample_t *out, const size_t frame_count); }; #endif // _VOICE_H_
26.814815
93
0.699586
[ "vector" ]
0230fc13f3c6d0e0bdad949cc473ab218e0a540e
47,364
cpp
C++
src/Tensor.cpp
j9263178/Cytnx
cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b
[ "Apache-2.0" ]
11
2020-04-14T15:45:42.000Z
2022-03-31T14:37:03.000Z
src/Tensor.cpp
j9263178/Cytnx
cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b
[ "Apache-2.0" ]
38
2019-08-02T15:15:51.000Z
2022-03-04T19:07:02.000Z
src/Tensor.cpp
j9263178/Cytnx
cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b
[ "Apache-2.0" ]
7
2019-07-17T07:50:55.000Z
2021-07-03T06:44:52.000Z
#include <typeinfo> #include "Tensor.hpp" #include "utils/utils_internal_interface.hpp" #include "linalg.hpp" #include "utils/is.hpp" using namespace std; namespace cytnx{ //---------------------------------------------- //Tproxy Tensor Tensor::Tproxy::operator+=(const Tensor::Tproxy &rc){ Tensor self; self._impl = _insimpl->get(_accs); //self += Tensor(rc); cytnx::linalg::iAdd(self,Tensor(rc)); _insimpl->set(_accs,self._impl); self._impl = this->_insimpl; return self; } Tensor Tensor::Tproxy::operator-=(const Tensor::Tproxy &rc){ Tensor self; self._impl = _insimpl->get(_accs); //self += Tensor(rc); cytnx::linalg::iSub(self,Tensor(rc)); _insimpl->set(_accs,self._impl); self._impl = this->_insimpl; return self; } Tensor Tensor::Tproxy::operator/=(const Tensor::Tproxy &rc){ Tensor self; self._impl = _insimpl->get(_accs); //self += Tensor(rc); cytnx::linalg::iDiv(self,Tensor(rc)); _insimpl->set(_accs,self._impl); self._impl = this->_insimpl; return self; } Tensor Tensor::Tproxy::operator*=(const Tensor::Tproxy &rc){ Tensor self; self._impl = _insimpl->get(_accs); //self += Tensor(rc); cytnx::linalg::iMul(self,Tensor(rc)); _insimpl->set(_accs,self._impl); self._impl = this->_insimpl; return self; } //ADD Tensor Tensor::Tproxy::operator+(const cytnx_complex128 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Add(rc); } Tensor Tensor::Tproxy::operator+(const cytnx_complex64 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Add(rc); } Tensor Tensor::Tproxy::operator+(const cytnx_double &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Add(rc); } Tensor Tensor::Tproxy::operator+(const cytnx_float &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Add(rc); } Tensor Tensor::Tproxy::operator+(const cytnx_uint64 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Add(rc); } Tensor Tensor::Tproxy::operator+(const cytnx_int64 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Add(rc); } Tensor Tensor::Tproxy::operator+(const cytnx_uint32 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Add(rc); } Tensor Tensor::Tproxy::operator+(const cytnx_int32 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Add(rc); } Tensor Tensor::Tproxy::operator+(const cytnx_uint16 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Add(rc); } Tensor Tensor::Tproxy::operator+(const cytnx_int16 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Add(rc); } Tensor Tensor::Tproxy::operator+(const cytnx_bool &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Add(rc); } Tensor Tensor::Tproxy::operator+(const Tproxy &rc) const{ Tensor out; out._impl = _insimpl->get(_accs); return cytnx::linalg::Add(out,Tensor(rc)); } //SUB: Tensor Tensor::Tproxy::operator-(const cytnx_complex128 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Sub(rc); } Tensor Tensor::Tproxy::operator-(const cytnx_complex64 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Sub(rc); } Tensor Tensor::Tproxy::operator-(const cytnx_double &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Sub(rc); } Tensor Tensor::Tproxy::operator-(const cytnx_float &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Sub(rc); } Tensor Tensor::Tproxy::operator-(const cytnx_uint64 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Sub(rc); } Tensor Tensor::Tproxy::operator-(const cytnx_int64 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Sub(rc); } Tensor Tensor::Tproxy::operator-(const cytnx_uint32 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Sub(rc); } Tensor Tensor::Tproxy::operator-(const cytnx_int32 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Sub(rc); } Tensor Tensor::Tproxy::operator-(const cytnx_uint16 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Sub(rc); } Tensor Tensor::Tproxy::operator-(const cytnx_int16 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Sub(rc); } Tensor Tensor::Tproxy::operator-(const cytnx_bool &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Sub(rc); } Tensor Tensor::Tproxy::operator-(const Tproxy &rc) const{ Tensor out; out._impl = _insimpl->get(_accs); return cytnx::linalg::Sub(out,Tensor(rc)); } Tensor Tensor::Tproxy::operator-() const{ Tensor out; out._impl = _insimpl->get(_accs); return out.Mul(-1); } // MUL Tensor Tensor::Tproxy::operator*(const cytnx_complex128 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Mul(rc); } Tensor Tensor::Tproxy::operator*(const cytnx_complex64 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Mul(rc); } Tensor Tensor::Tproxy::operator*(const cytnx_double &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Mul(rc); } Tensor Tensor::Tproxy::operator*(const cytnx_float &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Mul(rc); } Tensor Tensor::Tproxy::operator*(const cytnx_uint64 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Mul(rc); } Tensor Tensor::Tproxy::operator*(const cytnx_int64 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Mul(rc); } Tensor Tensor::Tproxy::operator*(const cytnx_uint32 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Mul(rc); } Tensor Tensor::Tproxy::operator*(const cytnx_int32 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Mul(rc); } Tensor Tensor::Tproxy::operator*(const cytnx_uint16 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Mul(rc); } Tensor Tensor::Tproxy::operator*(const cytnx_int16 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Mul(rc); } Tensor Tensor::Tproxy::operator*(const cytnx_bool &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Mul(rc); } Tensor Tensor::Tproxy::operator*(const Tproxy &rc) const{ Tensor out; out._impl = _insimpl->get(_accs); return cytnx::linalg::Mul(out,Tensor(rc)); } //DIV Tensor Tensor::Tproxy::operator/(const cytnx_complex128 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Div(rc); } Tensor Tensor::Tproxy::operator/(const cytnx_complex64 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Div(rc); } Tensor Tensor::Tproxy::operator/(const cytnx_double &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Div(rc); } Tensor Tensor::Tproxy::operator/(const cytnx_float &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Div(rc); } Tensor Tensor::Tproxy::operator/(const cytnx_uint64 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Div(rc); } Tensor Tensor::Tproxy::operator/(const cytnx_int64 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Div(rc); } Tensor Tensor::Tproxy::operator/(const cytnx_uint32 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Div(rc); } Tensor Tensor::Tproxy::operator/(const cytnx_int32 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Div(rc); } Tensor Tensor::Tproxy::operator/(const cytnx_uint16 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Div(rc); } Tensor Tensor::Tproxy::operator/(const cytnx_int16 &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Div(rc); } Tensor Tensor::Tproxy::operator/(const cytnx_bool &rc) const{//{return this->_operatorADD(rc);}; Tensor out; out._impl = _insimpl->get(_accs); return out.Div(rc); } Tensor Tensor::Tproxy::operator/(const Tproxy &rc) const{ Tensor out; out._impl = _insimpl->get(_accs); return cytnx::linalg::Div(out,Tensor(rc)); } //----------------------------------------------- void Tensor_impl::Init(const std::vector<cytnx_uint64> &shape, const unsigned int &dtype, int device){ //check: cytnx_error_msg(dtype>=N_Type,"%s","[ERROR] invalid argument: dtype"); cytnx_error_msg(shape.size()==0,"%s","[ERROR] invalid argument: shape. Must at least have one element."); cytnx_uint64 Nelem= 1; for(int i=0;i<shape.size();i++){ cytnx_error_msg(shape[i]==0,"%s","[ERROR] shape cannot have 0 dimension in any rank."); Nelem *= shape[i]; } //this->_storage = __SII.USIInit[dtype](); this->_storage.Init(Nelem,dtype,device); this->_shape = shape; this->_mapper = vec_range(shape.size()); this->_invmapper = this->_mapper; this->_contiguous = true; //cout << shape << endl; } void Tensor_impl::Init(const Storage &in){ cytnx_error_msg(in.dtype()==Type.Void,"[ERROR] cannot init Tensor using un-initialized Storage%s","\n"); this->_storage = in; this->_shape.clear(); this->_shape.push_back(in.size()); this->_mapper.clear(); this->_mapper.push_back(0); this->_invmapper = this->_mapper; this->_contiguous=true; } boost::intrusive_ptr<Tensor_impl> Tensor_impl::permute(const std::vector<cytnx_uint64> &rnks){ //check:: if(rnks.size()!=this->_shape.size()){ cytnx_error_msg(true,"%s","reshape a tensor with a specify shape that does not match with the shape of the incident tensor."); } if(vec_unique(rnks).size()!=rnks.size()){ cytnx_error_msg(true,"%s","tensor permute with duplicated index.\n"); } std::vector<cytnx_uint64> new_fwdmap(this->_shape.size()); std::vector<cytnx_uint64> new_shape(this->_shape.size()); std::vector<cytnx_uint64> new_idxmap(this->_shape.size()); //for(int i=0;i<this->_shape.size();i++) // std::cout << this->_mapper[i] << " " << this->_invmapper[i] << std::endl; for(cytnx_uint32 i=0;i<rnks.size();i++){ if(rnks[i] >= rnks.size()){ cytnx_error_msg(1,"%s","reshape a tensor with invalid rank index."); } //std::cout << this->_mapper[rnks[i]] << " " << i << std::endl; new_idxmap[this->_mapper[rnks[i]]] = i; new_fwdmap[i] = this->_mapper[rnks[i]]; new_shape[i] = this->_shape[rnks[i]]; } boost::intrusive_ptr<Tensor_impl> out(new Tensor_impl()); out->_invmapper = new_idxmap; out->_shape = new_shape; out->_mapper = new_fwdmap; ///checking if permute back to contiguous: bool iconti=true; for(cytnx_uint32 i=0;i<rnks.size();i++){ if(new_fwdmap[i]!=new_idxmap[i]){iconti = false; break;} if(new_fwdmap[i] != i){iconti=false; break;} } out->_contiguous= iconti; //ref storage out->_storage = this->_storage; return out; } void Tensor_impl::permute_(const std::vector<cytnx_uint64> &rnks){ //check:: if(rnks.size()!=this->_shape.size()){ cytnx_error_msg(true,"%s","reshape a tensor with a specify shape that does not match with the shape of the incident tensor."); } if(vec_unique(rnks).size()!=rnks.size()){ cytnx_error_msg(true,"%s","tensor permute with duplicated index.\n"); } std::vector<cytnx_uint64> new_fwdmap(this->_shape.size()); std::vector<cytnx_uint64> new_shape(this->_shape.size()); std::vector<cytnx_uint64> new_idxmap(this->_shape.size()); //for(int i=0;i<this->_shape.size();i++) // std::cout << this->_mapper[i] << " " << this->_invmapper[i] << std::endl; for(cytnx_uint32 i=0;i<rnks.size();i++){ if(rnks[i] >= rnks.size()){ cytnx_error_msg(1,"%s","reshape a tensor with invalid rank index."); } //std::cout << this->_mapper[rnks[i]] << " " << i << std::endl; new_idxmap[this->_mapper[rnks[i]]] = i; new_fwdmap[i] = this->_mapper[rnks[i]]; new_shape[i] = this->_shape[rnks[i]]; } this->_invmapper = new_idxmap; this->_shape = new_shape; this->_mapper = new_fwdmap; ///checking if permute back to contiguous: bool iconti=true; for(cytnx_uint32 i=0;i<rnks.size();i++){ if(new_fwdmap[i]!=new_idxmap[i]){iconti = false; break;} if(new_fwdmap[i] != i){iconti=false; break;} } this->_contiguous= iconti; } //shadow new: // boost::intrusive_ptr<Tensor_impl> Tensor_impl::get(const std::vector<cytnx::Accessor> &accessors){ cytnx_error_msg(accessors.size() > this->_shape.size(), "%s", "The input indexes rank is out of range! (>Tensor's rank)."); std::vector<cytnx::Accessor> acc = accessors; for(int i=0;i<this->_shape.size()-accessors.size();i++){ acc.push_back(Accessor::all()); } /* cout << "acc type bef" << endl; for(int i=0;i<acc.size();i++){ cout << acc[i].type() << " "; } */ acc = vec_map(acc,this->_invmapper); //contiguous. /* cout << "acc type aft" << endl; for(int i=0;i<acc.size();i++){ cout << acc[i].type() << " "; } */ //[1] curr_shape: auto curr_shape = vec_map(this->_shape,this->_invmapper); //cout << "curr_shape" << endl; //cout << curr_shape << endl; //[2] from back to front, check until last all: cytnx_uint64 Nunit = 1; int tmpidx = 0; while(tmpidx<curr_shape.size()){ if(acc.back().type()==Accessor::All){ Nunit*=curr_shape[curr_shape.size()-1-tmpidx]; tmpidx++; acc.pop_back(); }else{ break; } } //cout << "tmpidx" << tmpidx << endl; //cout << "Nunit" << Nunit << endl; //cout << acc.size() << endl; //acc-> locators std::vector<cytnx_uint64> get_shape(acc.size()); std::vector<std::vector<cytnx_uint64> > locators(acc.size()); for(cytnx_uint32 i=0;i<acc.size();i++){ cytnx_error_msg(acc[i].type() == Accessor::Qns,"[ERROR] Tensor cannot accept accessor with qnum list.%s","\n"); acc[i].get_len_pos(curr_shape[i],get_shape[i],locators[i]); } //cout << "get_shape" << endl; //cout << get_shape << endl; //create Tensor: for(cytnx_uint64 i=0;i<tmpidx;i++){ get_shape.push_back(curr_shape[acc.size()+i]); } boost::intrusive_ptr<Tensor_impl> out( new Tensor_impl()); out->Init(get_shape,this->dtype(),this->device()); //cout << get_shape << endl; if(locators.size()==0){ locators.resize(1); locators[0].push_back(0); } //call storage this->storage()._impl->GetElem_byShape_v2(out->storage()._impl,curr_shape,locators,Nunit); //permute back: std::vector<cytnx_int64> new_mapper(this->_mapper.begin(),this->_mapper.end()); std::vector<cytnx_int64> new_shape; std::vector<cytnx_int32> remove_id; for(unsigned int i=0;i<out->_shape.size();i++){ if(out->shape()[i]==1) remove_id.push_back(this->_mapper[this->_invmapper[i]]); else new_shape.push_back(out->shape()[i]); } //cout << "mapper" << endl; //cout << new_mapper << endl; //cout << "inv_mapper" << endl; //cout << this->_invmapper << endl; //cout << "remove_id" << endl; //cout << remove_id << endl; //cout << "out shape raw" << endl; //cout << out->shape() << endl; //cout << "perm" << endl; //cout << perm << endl; //cout << new_shape << endl; if(new_shape.size()){ //exclude the case where only single element exists! out->reshape_(new_shape); // remove size-1 axis std::vector<cytnx_uint64> perm; for(unsigned int i=0;i<new_mapper.size();i++){ perm.push_back(new_mapper[i]); for(unsigned int j=0;j<remove_id.size();j++){ if(new_mapper[i]>remove_id[j]) perm.back()-=1; else if(new_mapper[i]==remove_id[j]){ perm.pop_back(); break; } } } out->permute_(perm); }else{ out->reshape_({1}); // if it is only one element. } return out; } boost::intrusive_ptr<Tensor_impl> Tensor_impl::get_deprecated(const std::vector<cytnx::Accessor> &accessors){ cytnx_error_msg(accessors.size() > this->_shape.size(), "%s", "The input indexes rank is out of range! (>Tensor's rank)."); std::vector<cytnx::Accessor> acc = accessors; for(int i=0;i<this->_shape.size()-accessors.size();i++){ acc.push_back(Accessor::all()); } vector<cytnx_uint64> get_shape(acc.size()); //vector<cytnx_uint64> new_shape; std::vector<std::vector<cytnx_uint64> > locators(this->_shape.size()); for(cytnx_uint32 i=0;i<acc.size();i++){ acc[i].get_len_pos(this->_shape[i],get_shape[i],locators[i]); //std::cout << this->_shape[i] << " " << get_shape[i] << "|"; //for(int j=0;j<locators[i].size();j++) std::cout << locators[i][j] << " "; //std::cout << std::endl; } boost::intrusive_ptr<Tensor_impl> out( new Tensor_impl()); out->Init(get_shape,this->dtype(),this->device()); this->storage()._impl->GetElem_byShape(out->storage()._impl,this->shape(),this->_mapper,get_shape,locators); vector<cytnx_int64> new_shape; for(cytnx_uint32 i=0;i<acc.size();i++) if(get_shape[i]!=1) new_shape.push_back(get_shape[i]); if(new_shape.size()==0) out->reshape_({1}); else out->reshape_(new_shape); return out; } void Tensor_impl::set(const std::vector<cytnx::Accessor> &accessors, const boost::intrusive_ptr<Tensor_impl> &rhs){ //cout << "calling set" << endl; cytnx_error_msg(accessors.size() > this->_shape.size(), "%s", "The input indexes rank is out of range! (>Tensor's rank)."); vector<cytnx::Accessor> acc = accessors; for(int i=0;i<this->_shape.size()-accessors.size();i++){ acc.push_back(Accessor::all()); } //vector<cytnx_uint64> get_shape(acc.size()); acc = vec_map(acc,this->_invmapper); //contiguous. //[1] curr_shape: auto curr_shape = vec_map(this->_shape,this->_invmapper); //[2] from back to front, check until last all: cytnx_uint64 Nunit = 1; int tmpidx = 0; while(tmpidx<curr_shape.size()){ if(acc.back().type()==Accessor::All){ Nunit*=curr_shape[curr_shape.size()-1-tmpidx]; tmpidx++; acc.pop_back(); }else{ break; } } std::vector<cytnx_uint64> get_shape(acc.size()); std::vector<std::vector<cytnx_uint64> > locators(acc.size()); for(cytnx_uint32 i=0;i<acc.size();i++){ cytnx_error_msg(acc[i].type() == Accessor::Qns,"[ERROR] Tensor cannot accept accessor with qnum list.%s","\n"); acc[i].get_len_pos(curr_shape[i],get_shape[i],locators[i]); } /// checking if its scalar assign! if(rhs->storage().size()==1){ this->storage()._impl->SetElem_byShape_v2(rhs->storage()._impl,curr_shape,locators,Nunit,true); //std::cout << "Scalar" << endl; }else{ for(cytnx_uint64 i=0;i<tmpidx;i++){ get_shape.push_back(curr_shape[acc.size()+i]); } //std::cout << get_shape << endl; //permute input to currect pos std::vector<cytnx_int64> new_mapper(this->_mapper.begin(),this->_mapper.end()); std::vector<cytnx_uint64> new_shape; std::vector<cytnx_int32> remove_id; for(unsigned int i=0;i<get_shape.size();i++){ if(acc[i].type()==Accessor::Singl) remove_id.push_back(this->_mapper[this->_invmapper[i]]); else new_shape.push_back(get_shape[i]); } if(new_shape.size()==0) new_shape.push_back(1); // use current size to infer rhs permutation. std::vector<cytnx_uint64> perm; for(unsigned int i=0;i<new_mapper.size();i++){ perm.push_back(new_mapper[i]); for(unsigned int j=0;j<remove_id.size();j++){ if(new_mapper[i]>remove_id[j]) perm.back()-=1; else if(new_mapper[i]==remove_id[j]){ perm.pop_back(); break; } } } std::vector<cytnx_uint64> iperm(perm.size()); for(unsigned int i=0;i<iperm.size();i++) iperm[perm[i]] = i; //std::cout << new_shape << endl; boost::intrusive_ptr<Tensor_impl> tmp; //std::cout << iperm << std::endl; tmp = rhs->permute(iperm)->contiguous(); cytnx_error_msg(new_shape != tmp->shape(), "[ERROR][Tensor.set_elems]%s","inconsistent shape"); this->storage()._impl->SetElem_byShape_v2(tmp->storage()._impl,curr_shape,locators,Nunit,false); } } template<class T> void Tensor_impl::set(const std::vector<cytnx::Accessor> &accessors, const T &rc){ cytnx_error_msg(accessors.size() > this->_shape.size(), "%s", "The input indexes rank is out of range! (>Tensor's rank)."); std::vector<cytnx::Accessor> acc = accessors; for(int i=0;i<this->_shape.size()-accessors.size();i++){ acc.push_back(Accessor::all()); } acc = vec_map(acc,this->_invmapper); //contiguous. //[1] curr_shape: auto curr_shape = vec_map(this->_shape,this->_invmapper); //[2] from back to front, check until last all: cytnx_uint64 Nunit = 1; int tmpidx = 0; while(tmpidx<curr_shape.size()){ if(acc.back().type()==Accessor::All){ Nunit*=curr_shape[curr_shape.size()-1-tmpidx]; tmpidx++; acc.pop_back(); }else{ break; } } //cout << "tmpidx" << tmpidx << endl; //cout << "Nunit" << Nunit << endl; //cout << acc.size() << endl; //acc-> locators std::vector<cytnx_uint64> get_shape(acc.size()); std::vector<std::vector<cytnx_uint64> > locators(acc.size()); for(cytnx_uint32 i=0;i<acc.size();i++){ cytnx_error_msg(acc[i].type() == Accessor::Qns,"[ERROR] Tensor cannot accept accessor with qnum list.%s","\n"); acc[i].get_len_pos(curr_shape[i],get_shape[i],locators[i]); } //cout << "get_shape" << endl; //cout << get_shape << endl; //call storage Scalar c = rc; Storage tmp(1,c.dtype(),this->device()); tmp.set_item(0,rc); this->storage()._impl->SetElem_byShape_v2(tmp._impl,curr_shape,locators,Nunit,true); } template void Tensor_impl::set<cytnx_complex128>(const std::vector<cytnx::Accessor> &, const cytnx_complex128&); template void Tensor_impl::set<cytnx_complex64>(const std::vector<cytnx::Accessor> &, const cytnx_complex64&); template void Tensor_impl::set<cytnx_double>(const std::vector<cytnx::Accessor> &, const cytnx_double&); template void Tensor_impl::set<cytnx_float>(const std::vector<cytnx::Accessor> &, const cytnx_float&); template void Tensor_impl::set<cytnx_int64>(const std::vector<cytnx::Accessor> &, const cytnx_int64&); template void Tensor_impl::set<cytnx_uint64>(const std::vector<cytnx::Accessor> &, const cytnx_uint64&); template void Tensor_impl::set<cytnx_int32>(const std::vector<cytnx::Accessor> &, const cytnx_int32&); template void Tensor_impl::set<cytnx_uint32>(const std::vector<cytnx::Accessor> &, const cytnx_uint32&); template void Tensor_impl::set<cytnx_int16>(const std::vector<cytnx::Accessor> &, const cytnx_int16&); template void Tensor_impl::set<cytnx_uint16>(const std::vector<cytnx::Accessor> &, const cytnx_uint16&); template void Tensor_impl::set<cytnx_bool>(const std::vector<cytnx::Accessor> &, const cytnx_bool&); template void Tensor_impl::set<Scalar>(const std::vector<cytnx::Accessor> &, const Scalar&); void Tensor_impl::set(const std::vector<cytnx::Accessor> &accessors, const Scalar::Sproxy&rc){ this->set(accessors,Scalar(rc)); } std::ostream& operator<<(std::ostream& os,const Tensor &in){ if(in.is_contiguous()) in._impl->storage()._impl->PrintElem_byShape(os,in.shape()); else in._impl->storage()._impl->PrintElem_byShape(os,in.shape(),in._impl->invmapper()); return os; } std::ostream& operator<<(std::ostream& os,const Tensor::Tproxy &in){ os << Tensor(in) << std::endl; return os; } //=================================================================== //wrapper void Tensor::Tofile(const std::string &fname) const{ if(!this->is_contiguous()){ auto A = this->contiguous(); A.storage().Tofile(fname); }else{ this->_impl->_storage.Tofile(fname); } } void Tensor::Tofile(const char* fname) const{ if(!this->is_contiguous()){ auto A = this->contiguous(); A.storage().Tofile(fname); }else{ this->_impl->_storage.Tofile(fname); } } void Tensor::Tofile(fstream &f) const{ if(!this->is_contiguous()){ auto A = this->contiguous(); A.storage().Tofile(f); }else{ this->_impl->_storage.Tofile(f); } } void Tensor::Save(const std::string &fname) const{ fstream f; f.open((fname+".cytn"),ios::out|ios::trunc|ios::binary); if(!f.is_open()){ cytnx_error_msg(true,"[ERROR] invalid file path for save.%s","\n"); } this->_Save(f); f.close(); } void Tensor::Save(const char* fname) const{ fstream f; string ffname = string(fname) + ".cytn"; f.open(ffname,ios::out|ios::trunc|ios::binary); if(!f.is_open()){ cytnx_error_msg(true,"[ERROR] invalid file path for save.%s","\n"); } this->_Save(f); f.close(); } void Tensor::_Save(fstream &f) const{ //header //check: cytnx_error_msg(!f.is_open(),"[ERROR] invalid fstream!.%s","\n"); unsigned int IDDs = 888; f.write((char*)&IDDs,sizeof(unsigned int)); cytnx_uint64 shp = this->shape().size(); cytnx_uint64 Conti = this->is_contiguous(); f.write((char*)&shp,sizeof(cytnx_uint64)); f.write((char*)&Conti,sizeof(cytnx_uint64)); f.write((char*)&this->_impl->_shape[0],sizeof(cytnx_uint64)*shp); f.write((char*)&this->_impl->_mapper[0],sizeof(cytnx_uint64)*shp); f.write((char*)&this->_impl->_invmapper[0],sizeof(cytnx_uint64)*shp); //pass to storage for save: this->_impl->_storage._Save(f); } Tensor Tensor::Fromfile(const std::string &fname, const unsigned int &dtype,const cytnx_int64 &count){ return Tensor::from_storage(Storage::Fromfile(fname,dtype,count)); } Tensor Tensor::Fromfile(const char* fname, const unsigned int &dtype,const cytnx_int64 &count){ return Tensor::from_storage(Storage::Fromfile(fname,dtype,count)); } Tensor Tensor::Load(const std::string &fname){ Tensor out; fstream f; f.open(fname,ios::in|ios::binary); if(!f.is_open()){ cytnx_error_msg(true,"[ERROR] invalid file path for load.%s","\n"); } out._Load(f); f.close(); return out; } Tensor Tensor::Load(const char* fname){ Tensor out; fstream f; f.open(fname,ios::in|ios::binary); if(!f.is_open()){ cytnx_error_msg(true,"[ERROR] invalid file path for load.%s","\n"); } out._Load(f); f.close(); return out; } void Tensor::_Load(fstream &f){ //header //check: cytnx_error_msg(!f.is_open(),"[ERROR] invalid fstream!.%s","\n"); unsigned int tmpIDDs; f.read((char*)&tmpIDDs,sizeof(unsigned int)); cytnx_error_msg(tmpIDDs!=888,"[ERROR] the object is not a cytnx tensor!%s","\n"); cytnx_uint64 shp ; cytnx_uint64 Conti; f.read((char*)&shp,sizeof(cytnx_uint64)); f.read((char*)&Conti,sizeof(cytnx_uint64)); this->_impl->_contiguous = Conti; this->_impl->_shape.resize(shp); this->_impl->_mapper.resize(shp); this->_impl->_invmapper.resize(shp); f.read((char*)&this->_impl->_shape[0],sizeof(cytnx_uint64)*shp); f.read((char*)&this->_impl->_mapper[0],sizeof(cytnx_uint64)*shp); f.read((char*)&this->_impl->_invmapper[0],sizeof(cytnx_uint64)*shp); //pass to storage for save: this->_impl->_storage._Load(f); } Tensor Tensor::real(){ Tensor out; out._impl = this->_impl->_clone_meta_only(); out._impl->_storage = this->_impl->_storage.real(); return out; }; Tensor Tensor::imag(){ Tensor out; out._impl = this->_impl->_clone_meta_only(); out._impl->_storage = this->_impl->_storage.imag(); return out; } // += template<> Tensor& Tensor::operator+=<Tensor>(const Tensor &rc){ cytnx::linalg::iAdd(*this,rc); return *this; } template<> Tensor& Tensor::operator+=<Tensor::Tproxy>(const Tensor::Tproxy &rc){ cytnx::linalg::iAdd(*this,Tensor(rc)); return *this; } template<> Tensor& Tensor::operator+=<cytnx_complex128>(const cytnx_complex128 &rc){ this->_impl->storage() = cytnx::linalg::Add(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator+=<cytnx_complex64>(const cytnx_complex64 &rc){ this->_impl->storage() = cytnx::linalg::Add(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator+=<cytnx_double>(const cytnx_double &rc){ this->_impl->storage() = cytnx::linalg::Add(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator+=<cytnx_float>(const cytnx_float &rc){ this->_impl->storage() = cytnx::linalg::Add(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator+=<cytnx_int64>(const cytnx_int64 &rc){ this->_impl->storage() = cytnx::linalg::Add(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator+=<cytnx_uint64>(const cytnx_uint64 &rc){ this->_impl->storage() = cytnx::linalg::Add(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator+=<cytnx_int32>(const cytnx_int32 &rc){ this->_impl->storage() = cytnx::linalg::Add(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator+=<cytnx_uint32>(const cytnx_uint32 &rc){ this->_impl->storage() = cytnx::linalg::Add(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator+=<cytnx_int16>(const cytnx_int16 &rc){ this->_impl->storage() = cytnx::linalg::Add(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator+=<cytnx_uint16>(const cytnx_uint16 &rc){ this->_impl->storage() = cytnx::linalg::Add(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator+=<cytnx_bool>(const cytnx_bool &rc){ this->_impl->storage() = cytnx::linalg::Add(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator+=<Scalar>(const Scalar &rc){ this->_impl->storage() = cytnx::linalg::Add(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator+=<Scalar::Sproxy>(const Scalar::Sproxy &rc){ return this->operator+=(Scalar(rc)); } // -= template<> Tensor& Tensor::operator-=<Tensor>(const Tensor &rc){ cytnx::linalg::iSub(*this,rc); return *this; } template<> Tensor& Tensor::operator-=<Tensor::Tproxy>(const Tensor::Tproxy &rc){ cytnx::linalg::iSub(*this,Tensor(rc)); return *this; } template<> Tensor& Tensor::operator-=<cytnx_complex128>(const cytnx_complex128 &rc){ this->_impl->storage() = cytnx::linalg::Sub(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator-=<cytnx_complex64>(const cytnx_complex64 &rc){ this->_impl->storage() = cytnx::linalg::Sub(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator-=<cytnx_double>(const cytnx_double &rc){ this->_impl->storage() = cytnx::linalg::Sub(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator-=<cytnx_float>(const cytnx_float &rc){ this->_impl->storage() = cytnx::linalg::Sub(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator-=<cytnx_int64>(const cytnx_int64 &rc){ this->_impl->storage() = cytnx::linalg::Sub(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator-=<cytnx_uint64>(const cytnx_uint64 &rc){ this->_impl->storage() = cytnx::linalg::Sub(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator-=<cytnx_int32>(const cytnx_int32 &rc){ this->_impl->storage() = cytnx::linalg::Sub(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator-=<cytnx_uint32>(const cytnx_uint32 &rc){ this->_impl->storage() = cytnx::linalg::Sub(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator-=<cytnx_int16>(const cytnx_int16 &rc){ this->_impl->storage() = cytnx::linalg::Sub(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator-=<cytnx_uint16>(const cytnx_uint16 &rc){ this->_impl->storage() = cytnx::linalg::Sub(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator-=<cytnx_bool>(const cytnx_bool &rc){ this->_impl->storage() = cytnx::linalg::Sub(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator-=<Scalar>(const Scalar &rc){ this->_impl->storage() = cytnx::linalg::Sub(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator-=<Scalar::Sproxy>(const Scalar::Sproxy &rc){ return this->operator-=(Scalar(rc)); } // *= template<> Tensor& Tensor::operator*=<Tensor>(const Tensor &rc){ cytnx::linalg::iMul(*this,rc); return *this; } template<> Tensor& Tensor::operator*=<Tensor::Tproxy>(const Tensor::Tproxy &rc){ cytnx::linalg::iMul(*this,Tensor(rc)); return *this; } template<> Tensor& Tensor::operator*=<cytnx_complex128>(const cytnx_complex128 &rc){ this->_impl->storage() = cytnx::linalg::Mul(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator*=<cytnx_complex64>(const cytnx_complex64 &rc){ this->_impl->storage() = cytnx::linalg::Mul(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator*=<cytnx_double>(const cytnx_double &rc){ this->_impl->storage() = cytnx::linalg::Mul(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator*=<cytnx_float>(const cytnx_float &rc){ this->_impl->storage() = cytnx::linalg::Mul(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator*=<cytnx_int64>(const cytnx_int64 &rc){ this->_impl->storage() = cytnx::linalg::Mul(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator*=<cytnx_uint64>(const cytnx_uint64 &rc){ this->_impl->storage() = cytnx::linalg::Mul(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator*=<cytnx_int32>(const cytnx_int32 &rc){ this->_impl->storage() = cytnx::linalg::Mul(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator*=<cytnx_uint32>(const cytnx_uint32 &rc){ this->_impl->storage() = cytnx::linalg::Mul(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator*=<cytnx_int16>(const cytnx_int16 &rc){ this->_impl->storage() = cytnx::linalg::Mul(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator*=<cytnx_uint16>(const cytnx_uint16 &rc){ this->_impl->storage() = cytnx::linalg::Mul(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator*=<cytnx_bool>(const cytnx_bool &rc){ this->_impl->storage() = cytnx::linalg::Mul(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator*=<Scalar>(const Scalar &rc){ this->_impl->storage() = cytnx::linalg::Mul(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator*=<Scalar::Sproxy>(const Scalar::Sproxy &rc){ return this->operator*=(Scalar(rc)); } // /= template<> Tensor& Tensor::operator/=<Tensor>(const Tensor &rc){ cytnx::linalg::iDiv(*this,rc); return *this; } template<> Tensor& Tensor::operator/=<Tensor::Tproxy>(const Tensor::Tproxy &rc){ cytnx::linalg::iDiv(*this,Tensor(rc)); return *this; } template<> Tensor& Tensor::operator/=<cytnx_complex128>(const cytnx_complex128 &rc){ this->_impl->storage() = cytnx::linalg::Div(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator/=<cytnx_complex64>(const cytnx_complex64 &rc){ this->_impl->storage() = cytnx::linalg::Div(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator/=<cytnx_double>(const cytnx_double &rc){ this->_impl->storage() = cytnx::linalg::Div(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator/=<cytnx_float>(const cytnx_float &rc){ this->_impl->storage() = cytnx::linalg::Div(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator/=<cytnx_int64>(const cytnx_int64 &rc){ this->_impl->storage() = cytnx::linalg::Div(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator/=<cytnx_uint64>(const cytnx_uint64 &rc){ this->_impl->storage() = cytnx::linalg::Div(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator/=<cytnx_int32>(const cytnx_int32 &rc){ //std::cout << "entry /= int32" << std::endl; this->_impl->storage() = cytnx::linalg::Div(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator/=<cytnx_uint32>(const cytnx_uint32 &rc){ this->_impl->storage() = cytnx::linalg::Div(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator/=<cytnx_int16>(const cytnx_int16 &rc){ this->_impl->storage() = cytnx::linalg::Div(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator/=<cytnx_uint16>(const cytnx_uint16 &rc){ this->_impl->storage() = cytnx::linalg::Div(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator/=<cytnx_bool>(const cytnx_bool &rc){ this->_impl->storage() = cytnx::linalg::Div(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator/=<Scalar>(const Scalar &rc){ this->_impl->storage() = cytnx::linalg::Div(*this,rc)._impl->storage(); return *this; } template<> Tensor& Tensor::operator/=<Scalar::Sproxy>(const Scalar::Sproxy &rc){ return this->operator/=(Scalar(rc)); } std::vector<Tensor> Tensor::Svd(const bool&is_U, const bool&is_vT) const{ return linalg::Svd(*this, is_U, is_vT); } std::vector<Tensor> Tensor::Eigh(const bool &is_V,const bool &row_v) const{ return linalg::Eigh(*this, is_V,row_v); } Tensor& Tensor::InvM_(){ linalg::InvM_(*this); return *this; } Tensor Tensor::InvM() const{ return linalg::InvM(*this); } Tensor& Tensor::Inv_(const double &clip){ linalg::Inv_(*this,clip); return *this; } Tensor Tensor::Inv(const double &clip) const{ return linalg::Inv(*this,clip); } Tensor& Tensor::Conj_(){ linalg::Conj_(*this); return *this; } Tensor Tensor::Conj() const{ return linalg::Conj(*this); } Tensor& Tensor::Exp_(){ linalg::Exp_(*this); return *this; } Tensor Tensor::Exp() const{ return linalg::Exp(*this); } Tensor Tensor::Norm() const{ return linalg::Norm(*this); } Tensor Tensor::Pow(const cytnx_double &p) const{ return linalg::Pow(*this,p); } Tensor& Tensor::Pow_(const cytnx_double &p){ linalg::Pow_(*this,p); return *this; } Tensor& Tensor::Abs_(){ linalg::Abs_(*this); return *this; } Tensor Tensor::Abs() const{ return linalg::Abs(*this); } Tensor Tensor::Max() const{ return linalg::Max(*this); } Tensor Tensor::Min() const{ return linalg::Min(*this); } Tensor Tensor::Trace(const cytnx_uint64 &a, const cytnx_uint64 &b) const{ Tensor out = linalg::Trace(*this,a,b); return out; } bool Tensor::same_data(const Tensor &rhs)const{ return is(this->_impl->storage(),rhs.storage()); } //=========================== //Tensor am Tproxy Tensor operator+(const Tensor &lhs, const Tensor::Tproxy &rhs){ return cytnx::linalg::Add(lhs,Tensor(rhs)); } Tensor operator-(const Tensor &lhs, const Tensor::Tproxy &rhs){ return cytnx::linalg::Sub(lhs,Tensor(rhs)); } Tensor operator*(const Tensor &lhs, const Tensor::Tproxy &rhs){ return cytnx::linalg::Mul(lhs,Tensor(rhs)); } Tensor operator/(const Tensor &lhs, const Tensor::Tproxy &rhs){ return cytnx::linalg::Div(lhs,Tensor(rhs)); } //=========================== //Tensor am Sproxy Tensor operator+(const Tensor &lhs, const Scalar::Sproxy &rhs){ return cytnx::linalg::Add(lhs,Scalar(rhs)); } Tensor operator-(const Tensor &lhs, const Scalar::Sproxy &rhs){ return cytnx::linalg::Sub(lhs,Scalar(rhs)); } Tensor operator*(const Tensor &lhs, const Scalar::Sproxy &rhs){ return cytnx::linalg::Mul(lhs,Scalar(rhs)); } Tensor operator/(const Tensor &lhs, const Scalar::Sproxy &rhs){ return cytnx::linalg::Div(lhs,Scalar(rhs)); } }//namespace cytnx
37.441897
138
0.575331
[ "object", "shape", "vector" ]
023f10faf21e6535bf67b68b829fe9a466737539
4,810
cpp
C++
src/Tools/ArcTool.cpp
HerrNamenlos123/TechnicalSketcher
90c5af44dcaa6060dc202fddb38ea9d869bea194
[ "MIT" ]
null
null
null
src/Tools/ArcTool.cpp
HerrNamenlos123/TechnicalSketcher
90c5af44dcaa6060dc202fddb38ea9d869bea194
[ "MIT" ]
null
null
null
src/Tools/ArcTool.cpp
HerrNamenlos123/TechnicalSketcher
90c5af44dcaa6060dc202fddb38ea9d869bea194
[ "MIT" ]
null
null
null
#include "pch.h" #include "Tools/ArcTool.h" #include "Navigator.h" static float mag(const glm::vec2& v) { return sqrt(pow(v.x, 2) + pow(v.y, 2)); } // // double angle(const glm::vec2& v); // // Angle from X-Axis to vector, range 0 to 360 counterclockwise // // Y // | P // | / // | / // | / \. // | / a | // |------------------X // static float angle(const glm::vec2& v) { if (mag(v) > 0) { if (v.y >= 0) { return glm::degrees(acos(v.x / mag(v))); } else if (v.y <= 0) { return 360 - glm::degrees(acos(v.x / mag(v))); } } return 0; } void ArcTool::OnToolChanged() { Navigator::GetInstance()->previewPointShown = true; Navigator::GetInstance()->previewPointPosition = Navigator::GetInstance()->mouseSnapped; } void ArcTool::OnSpaceClicked(const glm::vec2& position, const glm::vec2& snapped, bool left, bool right, bool wheel) { if (left) { if (!arcStarted) { // Start the arc previewArc.SetCenter(snapped); previewArc.SetRadius(0); previewCircle.SetCenter(snapped); previewArc.SetRadius(0); previewCircle.SetThickness(1); previewCircle.SetColor({ 0, 0, 0, 255 }); Navigator::GetInstance()->previewPointShown = true; arcStarted = true; arcSecondStage = false; } else { // Continue the arc if (!arcSecondStage) { arcSecondStage = true; previewArc.SetRadius(glm::distance(snapped, previewArc.GetCenter())); glm::vec2 toMouse = Navigator::GetInstance()->mouseSnapped - previewArc.GetCenter(); toMouse.y *= -1; previewArc.SetStartAngle(angle(toMouse)); } else { // Finish the arc Navigator::GetInstance()->AddArc(previewArc); CancelShape(); } } } else { CancelShape(); } } void ArcTool::OnShapeClicked(const glm::vec2& position, const glm::vec2& snapped, bool left, bool right, bool wheel, ShapeID shape) { } void ArcTool::OnMouseHovered(const glm::vec2& position, const glm::vec2& snapped, float dx, float dy) { if (arcStarted) { if (!arcSecondStage) { // First stage previewCircle.SetRadius(glm::distance(snapped, previewArc.GetCenter())); } else { // Second stage glm::vec2 toMouse = Navigator::GetInstance()->mouseSnapped - previewArc.GetCenter(); toMouse.y *= -1; previewArc.SetEndAngle(angle(toMouse)); } } Navigator::GetInstance()->previewPointPosition = Navigator::GetInstance()->mouseSnapped; } void ArcTool::OnMouseDragged(const glm::vec2& position, const glm::vec2& snapped, float dx, float dy) { } void ArcTool::OnMouseReleased(const glm::vec2& position, bool left, bool right, bool wheel) { } void ArcTool::OnLayerSelected(LayerID layer) { } void ArcTool::CancelShape() { Navigator::GetInstance()->previewPointPosition = Navigator::GetInstance()->mouseSnapped; Navigator::GetInstance()->previewPointShown = true; arcStarted = false; arcSecondStage = false; } void ArcTool::SelectAll() { } void ArcTool::CopyClipboard() { } void ArcTool::CutClipboard() { } void ArcTool::PasteClipboard() { } bool ArcTool::StepToolBack() { if (arcStarted) { CancelShape(); return true; } return false; } bool ArcTool::IsPropertiesWindowShown() { if (!arcStarted) { return true; } return false; } void ArcTool::ShowPropertiesWindow() { if (!arcStarted) { previewArc.ShowPropertiesWindow(); } } void ArcTool::RenderPreview() { if (arcStarted) { if (!arcSecondStage) { // Draw the radius circle // Make circle 1 pixel thick previewCircle.SetThickness(Navigator::GetInstance()->ConvertScreenToWorkspaceDistance(1)); previewCircle.RenderPreview(); // Draw an arrow to indicate the arc direction glm::vec2 pos = Navigator::GetInstance()->ConvertWorkspaceToScreenCoords(previewCircle.GetCenter()); glm::vec2 toMouse = Navigator::GetInstance()->mouseSnapped - previewArc.GetCenter(); float start = angle({ toMouse.x, -toMouse.y }); glm::vec2 mouse = Navigator::GetInstance()->ConvertWorkspaceToScreenCoords(Navigator::GetInstance()->mouseSnapped); float rad = glm::distance(pos, mouse) + 20; float arcLength = 25; float end = start + glm::degrees(arcLength) / rad; ApplicationRenderer::DrawArcScreenspace(pos, rad, start, end, 4, { 0, 0, 0, 255 }); glm::vec2 endPoint = pos + glm::vec2(cos(glm::radians(end)), -sin(glm::radians(end))) * rad; float ang2 = start + glm::degrees(arcLength) / rad * 0.7; glm::vec2 p1 = pos + glm::vec2(cos(glm::radians(ang2)), -sin(glm::radians(ang2))) * (rad - 5); glm::vec2 p2 = pos + glm::vec2(cos(glm::radians(ang2)), -sin(glm::radians(ang2))) * (rad + 5); ApplicationRenderer::DrawLineScreenspace(endPoint, p1, 4, { 0, 0, 0, 255 }); ApplicationRenderer::DrawLineScreenspace(endPoint, p2, 4, { 0, 0, 0, 255 }); } else { // Draw the actual arc previewArc.RenderPreview(); } } }
26.284153
133
0.663825
[ "shape", "vector" ]
02420c8743bb29f34a32dec70477a348d239e934
2,534
hpp
C++
include/codegen/include/UnityEngine/Playables/PlayableBinding_CreateOutputMethod.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/UnityEngine/Playables/PlayableBinding_CreateOutputMethod.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/UnityEngine/Playables/PlayableBinding_CreateOutputMethod.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:32 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.MulticastDelegate #include "System/MulticastDelegate.hpp" // Including type: UnityEngine.Playables.PlayableBinding #include "UnityEngine/Playables/PlayableBinding.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Skipping declaration: IntPtr because it is already included! // Forward declaring type: IAsyncResult class IAsyncResult; // Forward declaring type: AsyncCallback class AsyncCallback; } // Forward declaring namespace: UnityEngine::Playables namespace UnityEngine::Playables { // Forward declaring type: PlayableOutput struct PlayableOutput; // Forward declaring type: PlayableGraph struct PlayableGraph; } // Completed forward declares // Type namespace: UnityEngine.Playables namespace UnityEngine::Playables { // Autogenerated type: UnityEngine.Playables.PlayableBinding/CreateOutputMethod class PlayableBinding::CreateOutputMethod : public System::MulticastDelegate { public: // public System.Void .ctor(System.Object object, System.IntPtr method) // Offset: 0x1401054 static PlayableBinding::CreateOutputMethod* New_ctor(::Il2CppObject* object, System::IntPtr method); // public UnityEngine.Playables.PlayableOutput Invoke(UnityEngine.Playables.PlayableGraph graph, System.String name) // Offset: 0x1400C34 UnityEngine::Playables::PlayableOutput Invoke(UnityEngine::Playables::PlayableGraph graph, ::Il2CppString* name); // public System.IAsyncResult BeginInvoke(UnityEngine.Playables.PlayableGraph graph, System.String name, System.AsyncCallback callback, System.Object object) // Offset: 0x1401068 System::IAsyncResult* BeginInvoke(UnityEngine::Playables::PlayableGraph graph, ::Il2CppString* name, System::AsyncCallback* callback, ::Il2CppObject* object); // public UnityEngine.Playables.PlayableOutput EndInvoke(System.IAsyncResult result) // Offset: 0x1401100 UnityEngine::Playables::PlayableOutput EndInvoke(System::IAsyncResult* result); }; // UnityEngine.Playables.PlayableBinding/CreateOutputMethod } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::Playables::PlayableBinding::CreateOutputMethod*, "UnityEngine.Playables", "PlayableBinding/CreateOutputMethod"); #pragma pack(pop)
48.730769
162
0.766377
[ "object" ]
02430356d95d5a8981234bd1dc31d2f479ed9b68
9,736
hpp
C++
install/halodi_msgs/include/halodi_msgs/msg/whole_body_state__struct.hpp
AHGOverbeek/halodi-messages
4286676cb85cc4d5b2684523c1482afc9eef6ec9
[ "Apache-2.0" ]
null
null
null
install/halodi_msgs/include/halodi_msgs/msg/whole_body_state__struct.hpp
AHGOverbeek/halodi-messages
4286676cb85cc4d5b2684523c1482afc9eef6ec9
[ "Apache-2.0" ]
3
2020-11-05T14:53:41.000Z
2021-04-27T13:40:47.000Z
install/halodi_msgs/include/halodi_msgs/msg/whole_body_state__struct.hpp
AHGOverbeek/halodi-messages
4286676cb85cc4d5b2684523c1482afc9eef6ec9
[ "Apache-2.0" ]
1
2021-10-05T14:08:08.000Z
2021-10-05T14:08:08.000Z
// generated from rosidl_generator_cpp/resource/idl__struct.hpp.em // with input from halodi_msgs:msg/WholeBodyState.idl // generated code does not contain a copyright notice #ifndef HALODI_MSGS__MSG__WHOLE_BODY_STATE__STRUCT_HPP_ #define HALODI_MSGS__MSG__WHOLE_BODY_STATE__STRUCT_HPP_ #include <rosidl_generator_cpp/bounded_vector.hpp> #include <rosidl_generator_cpp/message_initialization.hpp> #include <algorithm> #include <array> #include <memory> #include <string> #include <vector> // Include directives for member types // Member 'header' #include "std_msgs/msg/header__struct.hpp" // Member 'current_balance_mode' #include "halodi_msgs/msg/balance_mode__struct.hpp" // Member 'pose' #include "geometry_msgs/msg/pose__struct.hpp" // Member 'angular_velocity' // Member 'linear_velocity' #include "geometry_msgs/msg/vector3__struct.hpp" // Member 'imu_measurements' #include "halodi_msgs/msg/imu_measurement__struct.hpp" // Member 'joint_states' #include "halodi_msgs/msg/joint_measurement__struct.hpp" // Member 'taskspace_feedback' #include "halodi_msgs/msg/task_space_feedback__struct.hpp" #ifndef _WIN32 # define DEPRECATED__halodi_msgs__msg__WholeBodyState __attribute__((deprecated)) #else # define DEPRECATED__halodi_msgs__msg__WholeBodyState __declspec(deprecated) #endif namespace halodi_msgs { namespace msg { // message struct template<class ContainerAllocator> struct WholeBodyState_ { using Type = WholeBodyState_<ContainerAllocator>; explicit WholeBodyState_(rosidl_generator_cpp::MessageInitialization _init = rosidl_generator_cpp::MessageInitialization::ALL) : header(_init), current_balance_mode(_init), pose(_init), angular_velocity(_init), linear_velocity(_init) { if (rosidl_generator_cpp::MessageInitialization::ALL == _init || rosidl_generator_cpp::MessageInitialization::ZERO == _init) { this->last_received_sequence_id = 0l; this->controller_state = ""; this->robot_status = 0; } } explicit WholeBodyState_(const ContainerAllocator & _alloc, rosidl_generator_cpp::MessageInitialization _init = rosidl_generator_cpp::MessageInitialization::ALL) : header(_alloc, _init), controller_state(_alloc), current_balance_mode(_alloc, _init), pose(_alloc, _init), angular_velocity(_alloc, _init), linear_velocity(_alloc, _init) { if (rosidl_generator_cpp::MessageInitialization::ALL == _init || rosidl_generator_cpp::MessageInitialization::ZERO == _init) { this->last_received_sequence_id = 0l; this->controller_state = ""; this->robot_status = 0; } } // field types and members using _header_type = std_msgs::msg::Header_<ContainerAllocator>; _header_type header; using _last_received_sequence_id_type = int32_t; _last_received_sequence_id_type last_received_sequence_id; using _controller_state_type = std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other>; _controller_state_type controller_state; using _current_balance_mode_type = halodi_msgs::msg::BalanceMode_<ContainerAllocator>; _current_balance_mode_type current_balance_mode; using _robot_status_type = unsigned char; _robot_status_type robot_status; using _pose_type = geometry_msgs::msg::Pose_<ContainerAllocator>; _pose_type pose; using _angular_velocity_type = geometry_msgs::msg::Vector3_<ContainerAllocator>; _angular_velocity_type angular_velocity; using _linear_velocity_type = geometry_msgs::msg::Vector3_<ContainerAllocator>; _linear_velocity_type linear_velocity; using _imu_measurements_type = rosidl_generator_cpp::BoundedVector<halodi_msgs::msg::ImuMeasurement_<ContainerAllocator>, 2, typename ContainerAllocator::template rebind<halodi_msgs::msg::ImuMeasurement_<ContainerAllocator>>::other>; _imu_measurements_type imu_measurements; using _joint_states_type = rosidl_generator_cpp::BoundedVector<halodi_msgs::msg::JointMeasurement_<ContainerAllocator>, 25, typename ContainerAllocator::template rebind<halodi_msgs::msg::JointMeasurement_<ContainerAllocator>>::other>; _joint_states_type joint_states; using _taskspace_feedback_type = rosidl_generator_cpp::BoundedVector<halodi_msgs::msg::TaskSpaceFeedback_<ContainerAllocator>, 5, typename ContainerAllocator::template rebind<halodi_msgs::msg::TaskSpaceFeedback_<ContainerAllocator>>::other>; _taskspace_feedback_type taskspace_feedback; // setters for named parameter idiom Type & set__header( const std_msgs::msg::Header_<ContainerAllocator> & _arg) { this->header = _arg; return *this; } Type & set__last_received_sequence_id( const int32_t & _arg) { this->last_received_sequence_id = _arg; return *this; } Type & set__controller_state( const std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other> & _arg) { this->controller_state = _arg; return *this; } Type & set__current_balance_mode( const halodi_msgs::msg::BalanceMode_<ContainerAllocator> & _arg) { this->current_balance_mode = _arg; return *this; } Type & set__robot_status( const unsigned char & _arg) { this->robot_status = _arg; return *this; } Type & set__pose( const geometry_msgs::msg::Pose_<ContainerAllocator> & _arg) { this->pose = _arg; return *this; } Type & set__angular_velocity( const geometry_msgs::msg::Vector3_<ContainerAllocator> & _arg) { this->angular_velocity = _arg; return *this; } Type & set__linear_velocity( const geometry_msgs::msg::Vector3_<ContainerAllocator> & _arg) { this->linear_velocity = _arg; return *this; } Type & set__imu_measurements( const rosidl_generator_cpp::BoundedVector<halodi_msgs::msg::ImuMeasurement_<ContainerAllocator>, 2, typename ContainerAllocator::template rebind<halodi_msgs::msg::ImuMeasurement_<ContainerAllocator>>::other> & _arg) { this->imu_measurements = _arg; return *this; } Type & set__joint_states( const rosidl_generator_cpp::BoundedVector<halodi_msgs::msg::JointMeasurement_<ContainerAllocator>, 25, typename ContainerAllocator::template rebind<halodi_msgs::msg::JointMeasurement_<ContainerAllocator>>::other> & _arg) { this->joint_states = _arg; return *this; } Type & set__taskspace_feedback( const rosidl_generator_cpp::BoundedVector<halodi_msgs::msg::TaskSpaceFeedback_<ContainerAllocator>, 5, typename ContainerAllocator::template rebind<halodi_msgs::msg::TaskSpaceFeedback_<ContainerAllocator>>::other> & _arg) { this->taskspace_feedback = _arg; return *this; } // constant declarations // pointer types using RawPtr = halodi_msgs::msg::WholeBodyState_<ContainerAllocator> *; using ConstRawPtr = const halodi_msgs::msg::WholeBodyState_<ContainerAllocator> *; using SharedPtr = std::shared_ptr<halodi_msgs::msg::WholeBodyState_<ContainerAllocator>>; using ConstSharedPtr = std::shared_ptr<halodi_msgs::msg::WholeBodyState_<ContainerAllocator> const>; template<typename Deleter = std::default_delete< halodi_msgs::msg::WholeBodyState_<ContainerAllocator>>> using UniquePtrWithDeleter = std::unique_ptr<halodi_msgs::msg::WholeBodyState_<ContainerAllocator>, Deleter>; using UniquePtr = UniquePtrWithDeleter<>; template<typename Deleter = std::default_delete< halodi_msgs::msg::WholeBodyState_<ContainerAllocator>>> using ConstUniquePtrWithDeleter = std::unique_ptr<halodi_msgs::msg::WholeBodyState_<ContainerAllocator> const, Deleter>; using ConstUniquePtr = ConstUniquePtrWithDeleter<>; using WeakPtr = std::weak_ptr<halodi_msgs::msg::WholeBodyState_<ContainerAllocator>>; using ConstWeakPtr = std::weak_ptr<halodi_msgs::msg::WholeBodyState_<ContainerAllocator> const>; // pointer types similar to ROS 1, use SharedPtr / ConstSharedPtr instead // NOTE: Can't use 'using' here because GNU C++ can't parse attributes properly typedef DEPRECATED__halodi_msgs__msg__WholeBodyState std::shared_ptr<halodi_msgs::msg::WholeBodyState_<ContainerAllocator>> Ptr; typedef DEPRECATED__halodi_msgs__msg__WholeBodyState std::shared_ptr<halodi_msgs::msg::WholeBodyState_<ContainerAllocator> const> ConstPtr; // comparison operators bool operator==(const WholeBodyState_ & other) const { if (this->header != other.header) { return false; } if (this->last_received_sequence_id != other.last_received_sequence_id) { return false; } if (this->controller_state != other.controller_state) { return false; } if (this->current_balance_mode != other.current_balance_mode) { return false; } if (this->robot_status != other.robot_status) { return false; } if (this->pose != other.pose) { return false; } if (this->angular_velocity != other.angular_velocity) { return false; } if (this->linear_velocity != other.linear_velocity) { return false; } if (this->imu_measurements != other.imu_measurements) { return false; } if (this->joint_states != other.joint_states) { return false; } if (this->taskspace_feedback != other.taskspace_feedback) { return false; } return true; } bool operator!=(const WholeBodyState_ & other) const { return !this->operator==(other); } }; // struct WholeBodyState_ // alias to use template instance with default allocator using WholeBodyState = halodi_msgs::msg::WholeBodyState_<std::allocator<void>>; // constant definitions } // namespace msg } // namespace halodi_msgs #endif // HALODI_MSGS__MSG__WHOLE_BODY_STATE__STRUCT_HPP_
34.524823
225
0.752876
[ "vector" ]
0243cc91d60336eeec2e78f55be73968579cf7a0
3,100
cc
C++
bubblesmp/generators/halton-sequence-generator.cc
adnanademovic/bubbles-motion-planning
0532e557913053f57e859f7b5aa7b8d4467fac09
[ "BSD-2-Clause" ]
null
null
null
bubblesmp/generators/halton-sequence-generator.cc
adnanademovic/bubbles-motion-planning
0532e557913053f57e859f7b5aa7b8d4467fac09
[ "BSD-2-Clause" ]
null
null
null
bubblesmp/generators/halton-sequence-generator.cc
adnanademovic/bubbles-motion-planning
0532e557913053f57e859f7b5aa7b8d4467fac09
[ "BSD-2-Clause" ]
null
null
null
// // Copyright (c) 2015, Adnan Ademovic // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 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 "bubblesmp/generators/halton-sequence-generator.h" #include <chrono> namespace com { namespace ademovic { namespace bubblesmp { namespace generators { // TODO: add validity checks for keys. HaltonSequenceGenerator::HaltonSequenceGenerator( const std::vector<std::pair<double, double> >& limits, const std::vector<unsigned>& keys, unsigned skips) : dimensions_(limits.size()), current_(dimensions_, std::vector<unsigned>(1, 1)), keys_(keys) { for (unsigned i = 0; i < dimensions_; ++i) { starts_.push_back(limits[i].first); steps_.emplace_back(1, (limits[i].second - limits[i].first) / keys[i]); } // TODO: generate the state instead of doing the incremental calculation. for (unsigned i = 0; i < skips; ++i) NextPoint(); } HaltonSequenceGenerator::HaltonSequenceGenerator( const std::vector<std::pair<double, double> >& limits, const std::vector<unsigned>& keys) : HaltonSequenceGenerator( limits, keys, std::chrono::system_clock::now().time_since_epoch().count() & 0xFFFF) {} std::vector<double> HaltonSequenceGenerator::NextPoint() { std::vector<double> point = starts_; for (unsigned i = 0; i < dimensions_; ++i) { unsigned depth = current_[i].size(); for (unsigned j = 0; j < depth; ++j) { point[i] += steps_[i][j] * current_[i][j]; } unsigned current_depth = 0; while (++current_[i][current_depth] >= keys_[i]) { current_[i][current_depth++] = 0; if (current_depth >= depth) { steps_[i].push_back(steps_[i].back() / keys_[i]); current_[i].push_back(0); } } } return point; } } // namespace generators } // namespace bubblesmp } // namespace ademovic } // namespace com
38.271605
81
0.705161
[ "vector" ]
024be64405a04e6dabb5f98fcf2113d40840d28e
9,766
cpp
C++
src_example/oauth2-google/main.cpp
bradosia/BookFiler-Module-HTTP-Curl
7a4b81badb32391a9f640babd676cdf81d6e1f39
[ "MIT" ]
null
null
null
src_example/oauth2-google/main.cpp
bradosia/BookFiler-Module-HTTP-Curl
7a4b81badb32391a9f640babd676cdf81d6e1f39
[ "MIT" ]
null
null
null
src_example/oauth2-google/main.cpp
bradosia/BookFiler-Module-HTTP-Curl
7a4b81badb32391a9f640babd676cdf81d6e1f39
[ "MIT" ]
null
null
null
/* * @name BookFiler Module - HTTP w/ Curl * @author Branden Lee * @version 1.00 * @license MIT * @brief HTTP module for BookFiler™ applications. */ // C++ #include <sstream> #include <thread> // Bookfiler Modules #include <BookFilerModuleHttpLoader.hpp> std::mutex globalMutex; std::string authCode, userId, accessToken, refreshToken; std::string routeAll(bookfiler::HTTP::request req, bookfiler::HTTP::response res); int allModulesLoaded(); std::string testName = "Oauth2 Example"; std::shared_ptr<bookfiler::HTTP::ModuleInterface> httpModule; std::shared_ptr<bookfiler::HTTP::Server> httpServer; int main() { std::cout << testName << " BEGIN" << std::endl; bookfiler::HTTP::loadModule("modules", std::bind(&allModulesLoaded), httpModule); std::cout << testName << " END" << std::endl; return 0; } int allModulesLoaded() { int rc = 0; // SSL Certificate manager std::shared_ptr<bookfiler::certificate::Manager> certificateManager = httpModule->newCertificateManager(); std::shared_ptr<bookfiler::certificate::Certificate> certRootPtr, certServerPtr; // certificateManager->newCertRootLocalhost(certRootPtr, nullptr); certificateManager->loadCertificate(certRootPtr); if (certRootPtr) { std::cout << "root Certificate Info: " << certRootPtr->getInfo() << std::endl; // certificateManager->saveCertificate(certRootPtr,"root"); // certificateManager->addCertificate(certRootPtr); // certificateManager->newCertServerLocalhost(certServerPtr, nullptr); if (certServerPtr) { std::cout << "Server Certificate Info: " << certServerPtr->getInfo() << std::endl; certificateManager->createX509Store(); } } // start server std::shared_ptr<bookfiler::HTTP::Server> httpServer = httpModule->newServer({}); httpServer->useCertificate(certRootPtr); httpServer->run(); httpServer->route({{"method", "GET"}, {"path", "/"}, {"handler", std::bind(&routeAll, std::placeholders::_1, std::placeholders::_2)}}); // authorization url std::shared_ptr<bookfiler::HTTP::Url> authUrl = httpModule->newUrl({{"host", "accounts.google.com"}, {"path", "/o/oauth2/v2/auth"}, {"scheme", "https"}}); authUrl->setQuery( {{"client_id", "854776203850-r64s69l8jmh71ugiio16impqfcp80j1m.apps." "googleusercontent.com"}, {"scope", "https://mail.google.com/"}, {"response_type", "code"}, {"redirect_uri", "https://localhost:8081"}, {"test", "/*&op=4$@"}}); std::cout << "allModulesLoaded::authUrl->getURL() = " << authUrl->url() << "\n\n"; // open google oauth2 window std::string windowOpenCommand = "explorer \""; windowOpenCommand.append(authUrl->url()).append("\""); system(windowOpenCommand.c_str()); std::cout << "\n===MAIN THREAD===\nPlease login to your google account in " "the new window."; httpModule->wait("auth"); /* { std::unique_lock<std::mutex> mutexLock(globalMutex); authCondition.wait(mutexLock, [] { return authFlag; }); }*/ std::cout << "\n===MAIN THREAD===\nAuthorization Code: " << authCode << "\n"; /* Start an HTTP post request to get the access token */ std::shared_ptr<bookfiler::HTTP::Client> httpClient = httpModule->newClient({ {"host", "oauth2.googleapis.com"}, {"path", "/token"}, {"scheme", "https"}, {"method", "POST"}, }); std::cout << "allModulesLoaded httpClient->url() = " << httpClient->url() << "\n\n"; // token url httpClient->setQuery( {{"client_id", "854776203850-r64s69l8jmh71ugiio16impqfcp80j1m.apps." "googleusercontent.com"}, {"client_secret", "18e_rRNMBIJOJ0jWUthY7RKp"}, {"grant_type", "authorization_code"}, {"redirect_uri", "https://localhost:8081"}, {"code", authCode}}); httpClient->setHeader({{"Content-Length", "0"}}); std::cout << "\n=== THREAD " << std::this_thread::get_id() << " ===\n" << testName << " allModulesLoaded httpClient->url():\n" << httpClient->url() << std::endl; rc = httpClient->end(); if (rc < 0) { std::cout << "\n=== THREAD " << std::this_thread::get_id() << " ===\n" << testName << " allModulesLoaded ERROR:\n" << "Could not access webpage by HTTP" << std::endl; return -1; } std::optional<std::shared_ptr<rapidjson::Document>> jsonDocOpt = httpClient->getResponseJson(); if (!jsonDocOpt) { std::cout << "\n=== THREAD " << std::this_thread::get_id() << " ===\n" << testName << " allModulesLoaded ERROR:\n" << "Response is not JSON" << std::endl; return 0; } // get the JSON Document std::shared_ptr<rapidjson::Document> &jsonDoc = *jsonDocOpt; // Pretty write the JSON rapidjson::StringBuffer buffer; rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer); jsonDoc->Accept(writer); std::cout << "\n=== THREAD " << std::this_thread::get_id() << " ===\n" << testName << " allModulesLoaded jsonDoc PrettyWriter:\n" << buffer.GetString() << std::endl; /* parse the response */ if (!jsonDoc->IsObject()) { std::cout << "\n=== THREAD " << std::this_thread::get_id() << " ===\n" << testName << " allModulesLoaded ERROR:\n" << "JSON document not an object." << std::endl; return -1; } char memberName01[] = "access_token"; if (jsonDoc->HasMember(memberName01) && (*jsonDoc)[memberName01].IsString()) { accessToken = (*jsonDoc)[memberName01].GetString(); } char memberName02[] = "refresh_token"; if (jsonDoc->HasMember(memberName02) && (*jsonDoc)[memberName02].IsString()) { refreshToken = (*jsonDoc)[memberName02].GetString(); } /* Get the user's ID */ std::cout << "\n===MAIN THREAD===\nPlease enter your google user ID " "into the form on the new window."; httpModule->wait("userId"); std::cout << "\n===MAIN THREAD===\nUser ID: " << userId << "\n"; std::cout << "\n===MAIN THREAD===\nApplication waiting until shut down."; httpModule->wait("exit"); std::cout << "\n===MAIN THREAD===\nApplication Shutting Done\n"; return 0; } std::string routeAll(bookfiler::HTTP::request req, bookfiler::HTTP::response res) { std::string bodyStr = "<h1>Google OAUTH2 Example</h1>"; auto codeQuery = req->getQuery("code"); auto userIdQuery = req->getQuery("userId"); auto messagesPageQuery = req->getQuery("messagesPage"); if (userIdQuery) { userId = userIdQuery.value(); httpModule->notify("userId"); bodyStr.append("<br>userId=") .append(userId) .append("<form action=\"/\" method=\"GET\"><label for=\"resultNum" "\">Results:</label><br><input " "type=\"text\" id=\"resultNum" "\" name=\"resultNum\" value=\"20\"><br><input type=\"hidden\" " "name=\"messagesPage\" value=\"1\"><input type=\"hidden\" " "name=\"userId\" value=\"") .append(userId) .append("\"><input type=\"submit" "\" value=\"Submit\"></form>"); if (messagesPageQuery) { std::string resultsNum = "20"; auto resultNumQuery = req->getQuery("resultNum"); if (resultNumQuery) { resultsNum = resultNumQuery.value(); } /* Let's test a call to the Google API! */ int rc; std::string baseUrl = ""; baseUrl.append("https://gmail.googleapis.com/gmail/v1/users/") .append(userId) .append("/messages"); std::shared_ptr<bookfiler::HTTP::Client> httpClient = httpModule->newClient(); httpClient->setURL(baseUrl); httpClient->setQuery({{"maxResults", resultsNum}}); httpClient->setHeader( {{"Authorization", std::string("Bearer ").append(accessToken)}, {"Accept", "application/json"}}); httpClient->setMethod("GET"); rc = httpClient->end(); if (rc < 0) { bodyStr.append("Could not access webpage by HTTP\n"); std::cout << "Could not access webpage by HTTP\n"; return bodyStr; } std::optional<std::shared_ptr<rapidjson::Document>> jsonDocOpt = httpClient->getResponseJson(); if (!jsonDocOpt) { bodyStr.append("JSON response not valid"); std::cout << "JSON response not valid\n"; return bodyStr; } std::shared_ptr<rapidjson::Document> &jsonDoc = *jsonDocOpt; rapidjson::StringBuffer buffer; rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer); jsonDoc->Accept(writer); std::thread::id threadId = std::this_thread::get_id(); std::stringstream ss; ss << threadId; bodyStr.append("<br>THREAD ") .append(ss.str()) .append("<br><br>allModulesLoaded jsonDoc PrettyWriter:<br><pre>") .append(buffer.GetString()) .append("</pre>"); return bodyStr; } } else if (codeQuery) { authCode = codeQuery.value(); httpModule->notify("auth"); bodyStr.append("<br>code=") .append(authCode) .append("<form action=\"/\" method=\"GET\"><label for=\"userId" "\">Google User ID (Email address):</label><br><input " "type=\"text\" id=\"userId" "\" name=\"userId\" value=\"\"><br><input type=\"submit" "\" value=\"Submit\"></form>"); } else { bodyStr.append("<br>Error: Code not received"); } bodyStr.append("<br>path: ").append(req->path()); return bodyStr; }
35.129496
80
0.589392
[ "object" ]
0251834136c76b38fa4a63c5c38333b7bad13496
39,030
cpp
C++
frameworks/bridge/declarative_frontend/engine/jsi/jsi_declarative_engine.cpp
openharmony-gitee-mirror/ace_ace_engine
78013960cdce81348d1910e466a3292605442a5e
[ "Apache-2.0" ]
null
null
null
frameworks/bridge/declarative_frontend/engine/jsi/jsi_declarative_engine.cpp
openharmony-gitee-mirror/ace_ace_engine
78013960cdce81348d1910e466a3292605442a5e
[ "Apache-2.0" ]
null
null
null
frameworks/bridge/declarative_frontend/engine/jsi/jsi_declarative_engine.cpp
openharmony-gitee-mirror/ace_ace_engine
78013960cdce81348d1910e466a3292605442a5e
[ "Apache-2.0" ]
1
2021-09-13T11:17:50.000Z
2021-09-13T11:17:50.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "frameworks/bridge/declarative_frontend/engine/jsi/jsi_declarative_engine.h" #include <unistd.h> #include "worker_init.h" #include "base/i18n/localization.h" #include "base/log/ace_trace.h" #include "base/log/event_report.h" #include "core/common/ace_application_info.h" #include "core/common/container.h" #include "frameworks/bridge/declarative_frontend/engine/jsi/ark/ark_js_runtime.h" #include "frameworks/bridge/declarative_frontend/engine/jsi/jsi_declarative_utils.h" #include "frameworks/bridge/declarative_frontend/engine/jsi/modules/jsi_module_manager.h" #include "frameworks/bridge/declarative_frontend/engine/jsi/modules/jsi_timer_module.h" #include "frameworks/bridge/declarative_frontend/jsview/js_view_register.h" #include "frameworks/bridge/js_frontend/engine/common/js_api_perf.h" #include "frameworks/bridge/js_frontend/engine/common/runtime_constants.h" extern const char _binary_stateMgmt_abc_start[]; extern const char _binary_stateMgmt_abc_end[]; extern const char _binary_jsEnumStyle_abc_start[]; extern const char _binary_jsEnumStyle_abc_end[]; namespace OHOS::Ace::Framework { namespace { #ifdef APP_USE_ARM const std::string ARK_DEBUGGER_LIB_PATH = "/system/lib/libark_debugger.z.so"; #else const std::string ARK_DEBUGGER_LIB_PATH = "/system/lib64/libark_debugger.z.so"; #endif std::string ParseLogContent(const std::vector<std::string>& params) { std::string ret; if (params.empty()) { return ret; } std::string formatStr = params[0]; int32_t size = params.size(); int32_t len = formatStr.size(); int32_t pos = 0; int32_t count = 1; for (; pos < len; ++pos) { if (count >= size) { break; } if (formatStr[pos] == '%') { if (pos + 1 >= len) { break; } switch (formatStr[pos + 1]) { case 's': case 'j': case 'd': case 'O': case 'o': case 'i': case 'f': case 'c': ret += params[count++]; ++pos; break; case '%': ret += formatStr[pos]; ++pos; break; default: ret += formatStr[pos]; break; } } else { ret += formatStr[pos]; } } if (pos < len) { ret += formatStr.substr(pos, len - pos); } return ret; } std::string GetLogContent( const shared_ptr<JsRuntime>& runtime, const std::vector<shared_ptr<JsValue>>& argv, int32_t argc) { if (argc == 1) { return argv[0]->ToString(runtime); } std::vector<std::string> params; for (int32_t i = 0; i < argc; ++i) { params.emplace_back(argv[i]->ToString(runtime)); } return ParseLogContent(params); } shared_ptr<JsValue> AppLogPrint( const shared_ptr<JsRuntime>& runtime, JsLogLevel level, const std::vector<shared_ptr<JsValue>>& argv, int32_t argc) { // Should have at least 1 parameters. if (argc == 0) { LOGE("the arg is error"); return runtime->NewUndefined(); } std::string content = GetLogContent(runtime, argv, argc); switch (level) { case JsLogLevel::DEBUG: APP_LOGD("app Log: %{public}s", content.c_str()); break; case JsLogLevel::INFO: APP_LOGI("app Log: %{public}s", content.c_str()); break; case JsLogLevel::WARNING: APP_LOGW("app Log: %{public}s", content.c_str()); break; case JsLogLevel::ERROR: APP_LOGE("app Log: %{public}s", content.c_str()); break; } return runtime->NewUndefined(); } // native implementation for js function: console.debug() shared_ptr<JsValue> AppDebugLogPrint(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj, const std::vector<shared_ptr<JsValue>>& argv, int32_t argc) { return AppLogPrint(runtime, JsLogLevel::DEBUG, argv, argc); } // native implementation for js function: console.info() shared_ptr<JsValue> AppInfoLogPrint(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj, const std::vector<shared_ptr<JsValue>>& argv, int32_t argc) { return AppLogPrint(runtime, JsLogLevel::INFO, argv, argc); } // native implementation for js function: console.warn() shared_ptr<JsValue> AppWarnLogPrint(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj, const std::vector<shared_ptr<JsValue>>& argv, int32_t argc) { return AppLogPrint(runtime, JsLogLevel::WARNING, argv, argc); } // native implementation for js function: console.error() shared_ptr<JsValue> AppErrorLogPrint(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj, const std::vector<shared_ptr<JsValue>>& argv, int32_t argc) { return AppLogPrint(runtime, JsLogLevel::ERROR, argv, argc); } shared_ptr<JsValue> JsLogPrint( const shared_ptr<JsRuntime>& runtime, JsLogLevel level, const std::vector<shared_ptr<JsValue>>& argv, int32_t argc) { // Should have 1 parameters. if (argc == 0) { LOGE("the arg is error"); return runtime->NewUndefined(); } std::string content = GetLogContent(runtime, argv, argc); switch (level) { case JsLogLevel::DEBUG: LOGD("ace Log: %{public}s", content.c_str()); break; case JsLogLevel::INFO: LOGI("ace Log: %{public}s", content.c_str()); break; case JsLogLevel::WARNING: LOGW("ace Log: %{public}s", content.c_str()); break; case JsLogLevel::ERROR: LOGE("ace Log: %{public}s", content.c_str()); break; } shared_ptr<JsValue> ret = runtime->NewUndefined(); return ret; } int PrintLog(int id, int level, const char* tag, const char* fmt, const char* message) { switch (JsLogLevel(level - 3)) { case JsLogLevel::INFO: LOGI("%{public}s::%{public}s", tag, message); break; case JsLogLevel::WARNING: LOGW("%{public}s::%{public}s", tag, message); break; case JsLogLevel::ERROR: LOGE("%{public}s::%{public}s", tag, message); break; case JsLogLevel::DEBUG: LOGD("%{public}s::%{public}s", tag, message); break; default: LOGF("%{public}s::%{public}s", tag, message); break; } return 0; } // native implementation for js function: aceConsole.debug() shared_ptr<JsValue> JsDebugLogPrint(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj, const std::vector<shared_ptr<JsValue>>& argv, int32_t argc) { return JsLogPrint(runtime, JsLogLevel::DEBUG, std::move(argv), argc); } // native implementation for js function: aceConsole.info() shared_ptr<JsValue> JsInfoLogPrint(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj, const std::vector<shared_ptr<JsValue>>& argv, int32_t argc) { return JsLogPrint(runtime, JsLogLevel::INFO, std::move(argv), argc); } // native implementation for js function: aceConsole.warn() shared_ptr<JsValue> JsWarnLogPrint(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj, const std::vector<shared_ptr<JsValue>>& argv, int32_t argc) { return JsLogPrint(runtime, JsLogLevel::WARNING, std::move(argv), argc); } // native implementation for js function: aceConsole.error() shared_ptr<JsValue> JsErrorLogPrint(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj, const std::vector<shared_ptr<JsValue>>& argv, int32_t argc) { return JsLogPrint(runtime, JsLogLevel::ERROR, std::move(argv), argc); } // native implementation for js function: perfutil.print() shared_ptr<JsValue> JsPerfPrint(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj, const std::vector<shared_ptr<JsValue>>& argv, int32_t argc) { std::string ret = JsApiPerf::GetInstance().PrintToLogs(); return runtime->NewString(ret); } // native implementation for js function: perfutil.sleep() shared_ptr<JsValue> JsPerfSleep(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj, const std::vector<shared_ptr<JsValue>>& argv, int32_t argc) { int32_t valInt = argv[0]->ToInt32(runtime); usleep(valInt); return runtime->NewNull(); } // native implementation for js function: perfutil.begin() shared_ptr<JsValue> JsPerfBegin(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj, const std::vector<shared_ptr<JsValue>>& argv, int32_t argc) { int64_t currentTime = GetMicroTickCount(); JsApiPerf::GetInstance().InsertJsBeginLog(argv[0]->ToString(runtime), currentTime); return runtime->NewNull(); } // native implementation for js function: perfutil.end() shared_ptr<JsValue> JsPerfEnd(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj, const std::vector<shared_ptr<JsValue>>& argv, int32_t argc) { int64_t currentTime = GetMicroTickCount(); JsApiPerf::GetInstance().InsertJsEndLog(argv[0]->ToString(runtime), currentTime); return runtime->NewNull(); } shared_ptr<JsValue> RequireNativeModule(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj, const std::vector<shared_ptr<JsValue>>& argv, int32_t argc) { std::string moduleName = argv[0]->ToString(runtime); // has already init module object shared_ptr<JsValue> global = runtime->GetGlobal(); shared_ptr<JsValue> moduleObject = global->GetProperty(runtime, moduleName); if (moduleObject != nullptr && moduleObject->IsObject(runtime)) { LOGE("has already init moduleObject %{private}s", moduleName.c_str()); return moduleObject; } // init module object first time shared_ptr<JsValue> newObject = runtime->NewObject(); if (ModuleManager::GetInstance()->InitModule(runtime, newObject, moduleName)) { global->SetProperty(runtime, moduleName, newObject); return newObject; } return runtime->NewNull(); } } // namespace // ----------------------- // Start JsiDeclarativeEngineInstance // ----------------------- std::map<std::string, std::string> JsiDeclarativeEngineInstance::mediaResourceFileMap_; std::unique_ptr<JsonValue> JsiDeclarativeEngineInstance::currentConfigResourceData_; thread_local shared_ptr<JsRuntime> JsiDeclarativeEngineInstance::runtime_; JsiDeclarativeEngineInstance::~JsiDeclarativeEngineInstance() { CHECK_RUN_ON(JS); LOG_DESTROY(); DestroyAllRootViewHandle(); if (runtime_) { runtime_->RegisterUncaughtExceptionHandler(nullptr); // reset runtime in utils JsiDeclarativeUtils::SetRuntime(nullptr, runtime_); runtime_->Reset(); } runtime_.reset(); runtime_ = nullptr; } bool JsiDeclarativeEngineInstance::InitJsEnv(bool debuggerMode, const std::unordered_map<std::string, void*>& extraNativeObject) { CHECK_RUN_ON(JS); ACE_SCOPED_TRACE("JsiDeclarativeEngineInstance::InitJsEnv"); LOGI("JsiDeclarativeEngineInstance InitJsEnv"); runtime_.reset(new ArkJSRuntime()); if (runtime_ == nullptr) { LOGE("Js Engine cannot allocate JSI JSRuntime"); EventReport::SendJsException(JsExcepType::JS_ENGINE_INIT_ERR); return false; } runtime_->SetLogPrint(PrintLog); std::string libraryPath = ""; if (debuggerMode) { libraryPath = ARK_DEBUGGER_LIB_PATH; } if (!runtime_->Initialize(libraryPath)) { LOGE("Js Engine initialize runtime failed"); return false; } // set new runtime JsiDeclarativeUtils::SetRuntime(runtime_); runtime_->SetEmbedderData(this); runtime_->RegisterUncaughtExceptionHandler(JsiDeclarativeUtils::ReportJsErrorEvent); #if !defined(WINDOWS_PLATFORM) and !defined(MAC_PLATFORM) for (const auto& [key, value] : extraNativeObject) { shared_ptr<JsValue> nativeValue = runtime_->NewNativePointer(value); runtime_->GetGlobal()->SetProperty(runtime_, key, nativeValue); } #endif InitGlobalObjectTemplate(); InitConsoleModule(); InitAceModule(); InitPerfUtilModule(); InitJsExportsUtilObject(); InitJsNativeModuleObject(); InitGroupJsBridge(); // load resourceConfig currentConfigResourceData_ = JsonUtil::CreateArray(true); frontendDelegate_->LoadResourceConfiguration(mediaResourceFileMap_, currentConfigResourceData_); return true; } bool JsiDeclarativeEngineInstance::FireJsEvent(const std::string& eventStr) { return true; } void JsiDeclarativeEngineInstance::InitAceModule() { bool stateMgmtResult = runtime_->EvaluateJsCode( (uint8_t *)_binary_stateMgmt_abc_start, _binary_stateMgmt_abc_end - _binary_stateMgmt_abc_start); if (!stateMgmtResult) { JsiDeclarativeUtils::SetCurrentState(JsErrorType::LOAD_JS_BUNDLE_ERROR, instanceId_); LOGE("EvaluateJsCode stateMgmt failed"); } bool jsEnumStyleResult = runtime_->EvaluateJsCode( (uint8_t *)_binary_jsEnumStyle_abc_start, _binary_jsEnumStyle_abc_end - _binary_jsEnumStyle_abc_start); if (!jsEnumStyleResult) { JsiDeclarativeUtils::SetCurrentState(JsErrorType::LOAD_JS_BUNDLE_ERROR, instanceId_); LOGE("EvaluateJsCode jsEnumStyle failed"); } } void JsiDeclarativeEngineInstance::InitConsoleModule() { ACE_SCOPED_TRACE("JsiDeclarativeEngineInstance::InitConsoleModule"); LOGD("JsiDeclarativeEngineInstance InitConsoleModule"); shared_ptr<JsValue> global = runtime_->GetGlobal(); // app log method shared_ptr<JsValue> consoleObj = runtime_->NewObject(); consoleObj->SetProperty(runtime_, "log", runtime_->NewFunction(AppDebugLogPrint)); consoleObj->SetProperty(runtime_, "debug", runtime_->NewFunction(AppDebugLogPrint)); consoleObj->SetProperty(runtime_, "info", runtime_->NewFunction(AppInfoLogPrint)); consoleObj->SetProperty(runtime_, "warn", runtime_->NewFunction(AppWarnLogPrint)); consoleObj->SetProperty(runtime_, "error", runtime_->NewFunction(AppErrorLogPrint)); global->SetProperty(runtime_, "console", consoleObj); // js framework log method shared_ptr<JsValue> aceConsoleObj = runtime_->NewObject(); aceConsoleObj->SetProperty(runtime_, "log", runtime_->NewFunction(JsDebugLogPrint)); aceConsoleObj->SetProperty(runtime_, "debug", runtime_->NewFunction(JsDebugLogPrint)); aceConsoleObj->SetProperty(runtime_, "info", runtime_->NewFunction(JsInfoLogPrint)); aceConsoleObj->SetProperty(runtime_, "warn", runtime_->NewFunction(JsWarnLogPrint)); aceConsoleObj->SetProperty(runtime_, "error", runtime_->NewFunction(JsErrorLogPrint)); global->SetProperty(runtime_, "aceConsole", aceConsoleObj); } std::string GetLogContent(NativeEngine* nativeEngine, NativeCallbackInfo* info) { std::string content; for (size_t i = 0; i < info->argc; ++i) { if (info->argv[i]->TypeOf() != NATIVE_STRING) { LOGE("argv is not NativeString"); continue; } auto nativeString = reinterpret_cast<NativeString*>(info->argv[i]->GetInterface(NativeString::INTERFACE_ID)); size_t bufferSize = nativeString->GetLength(); size_t strLength = 0; char* buffer = new char[bufferSize + 1] { 0 }; nativeString->GetCString(buffer, bufferSize + 1, &strLength); content.append(buffer); delete[] buffer; } return content; } NativeValue* AppLogPrint(NativeEngine* nativeEngine, NativeCallbackInfo* info, JsLogLevel level) { // Should have at least 1 parameters. if (info->argc == 0) { LOGE("the arg is error"); return nativeEngine->CreateUndefined(); } std::string content = GetLogContent(nativeEngine, info); switch (level) { case JsLogLevel::DEBUG: APP_LOGD("app Log: %{public}s", content.c_str()); break; case JsLogLevel::INFO: APP_LOGI("app Log: %{public}s", content.c_str()); break; case JsLogLevel::WARNING: APP_LOGW("app Log: %{public}s", content.c_str()); break; case JsLogLevel::ERROR: APP_LOGE("app Log: %{public}s", content.c_str()); break; } return nativeEngine->CreateUndefined(); } NativeValue* AppDebugLogPrint(NativeEngine* nativeEngine, NativeCallbackInfo* info) { return AppLogPrint(nativeEngine, info, JsLogLevel::DEBUG); } NativeValue* AppInfoLogPrint(NativeEngine* nativeEngine, NativeCallbackInfo* info) { return AppLogPrint(nativeEngine, info, JsLogLevel::INFO); } NativeValue* AppWarnLogPrint(NativeEngine* nativeEngine, NativeCallbackInfo* info) { return AppLogPrint(nativeEngine, info, JsLogLevel::WARNING); } NativeValue* AppErrorLogPrint(NativeEngine* nativeEngine, NativeCallbackInfo* info) { return AppLogPrint(nativeEngine, info, JsLogLevel::ERROR); } void JsiDeclarativeEngineInstance::InitConsoleModule(ArkNativeEngine* engine) { ACE_SCOPED_TRACE("JsiDeclarativeEngineInstance::RegisterConsoleModule"); LOGD("JsiDeclarativeEngineInstance RegisterConsoleModule to nativeEngine"); NativeValue* global = engine->GetGlobal(); if (global->TypeOf() != NATIVE_OBJECT) { LOGE("global is not NativeObject"); return; } auto nativeGlobal = reinterpret_cast<NativeObject*>(global->GetInterface(NativeObject::INTERFACE_ID)); // app log method NativeValue* console = engine->CreateObject(); auto consoleObj = reinterpret_cast<NativeObject*>(console->GetInterface(NativeObject::INTERFACE_ID)); consoleObj->SetProperty("log", engine->CreateFunction("log", strlen("log"), AppDebugLogPrint, nullptr)); consoleObj->SetProperty("debug", engine->CreateFunction("debug", strlen("debug"), AppDebugLogPrint, nullptr)); consoleObj->SetProperty("info", engine->CreateFunction("info", strlen("info"), AppInfoLogPrint, nullptr)); consoleObj->SetProperty("warn", engine->CreateFunction("warn", strlen("warn"), AppWarnLogPrint, nullptr)); consoleObj->SetProperty("error", engine->CreateFunction("error", strlen("error"), AppErrorLogPrint, nullptr)); nativeGlobal->SetProperty("console", console); } void JsiDeclarativeEngineInstance::InitPerfUtilModule() { ACE_SCOPED_TRACE("JsiDeclarativeEngineInstance::InitPerfUtilModule"); LOGD("JsiDeclarativeEngineInstance InitPerfUtilModule"); shared_ptr<JsValue> perfObj = runtime_->NewObject(); perfObj->SetProperty(runtime_, "printlog", runtime_->NewFunction(JsPerfPrint)); perfObj->SetProperty(runtime_, "sleep", runtime_->NewFunction(JsPerfSleep)); perfObj->SetProperty(runtime_, "begin", runtime_->NewFunction(JsPerfBegin)); perfObj->SetProperty(runtime_, "end", runtime_->NewFunction(JsPerfEnd)); shared_ptr<JsValue> global = runtime_->GetGlobal(); global->SetProperty(runtime_, "perfutil", perfObj); } void JsiDeclarativeEngineInstance::InitJsExportsUtilObject() { shared_ptr<JsValue> exportsUtilObj = runtime_->NewObject(); shared_ptr<JsValue> global = runtime_->GetGlobal(); global->SetProperty(runtime_, "exports", exportsUtilObj); } void JsiDeclarativeEngineInstance::InitJsNativeModuleObject() { shared_ptr<JsValue> global = runtime_->GetGlobal(); global->SetProperty(runtime_, "requireNativeModule", runtime_->NewFunction(RequireNativeModule)); JsiTimerModule::GetInstance()->InitTimerModule(runtime_, global); } void JsiDeclarativeEngineInstance::InitGlobalObjectTemplate() { auto runtime = std::static_pointer_cast<ArkJSRuntime>(runtime_); JsRegisterViews(JSNApi::GetGlobalObject(runtime->GetEcmaVm())); } void JsiDeclarativeEngineInstance::InitGroupJsBridge() { } thread_local std::unordered_map<int32_t, panda::Global<panda::ObjectRef>> JsiDeclarativeEngineInstance::rootViewMap_; void JsiDeclarativeEngineInstance::RootViewHandle(const shared_ptr<JsRuntime>& runtime, panda::Local<panda::ObjectRef> value) { LOGD("RootViewHandle"); if (runtime == nullptr) { LOGE("jsRuntime is nullptr"); return; } RefPtr<JsAcePage> page = JsiDeclarativeEngineInstance::GetStagingPage(runtime); if (page != nullptr) { auto arkRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime_); if (!arkRuntime) { LOGE("ark engine is null"); return; } rootViewMap_.emplace(page->GetPageId(), panda::Global<panda::ObjectRef>(arkRuntime->GetEcmaVm(), value)); } } void JsiDeclarativeEngineInstance::DestroyRootViewHandle(int32_t pageId) { CHECK_RUN_ON(JS); if (rootViewMap_.count(pageId) != 0) { auto arkRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime_); if (!arkRuntime) { LOGE("ark engine is null"); return; } panda::Local<panda::ObjectRef> rootView = rootViewMap_[pageId].ToLocal(arkRuntime->GetEcmaVm()); JSView* jsView = static_cast<JSView*>(rootView->GetNativePointerField(0)); jsView->Destroy(nullptr); rootViewMap_.erase(pageId); } } void JsiDeclarativeEngineInstance::DestroyAllRootViewHandle() { CHECK_RUN_ON(JS); if (rootViewMap_.size() > 0) { LOGI("DestroyAllRootViewHandle release left %{private}zu views ", rootViewMap_.size()); } auto arkRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime_); if (!arkRuntime) { LOGE("ark engine is null"); return; } for (const auto& pair : rootViewMap_) { panda::Local<panda::ObjectRef> rootView = pair.second.ToLocal(arkRuntime->GetEcmaVm()); JSView* jsView = static_cast<JSView*>(rootView->GetNativePointerField(0)); jsView->Destroy(nullptr); } rootViewMap_.clear(); } std::unique_ptr<JsonValue> JsiDeclarativeEngineInstance::GetI18nStringResource( const std::string& targetStringKey, const std::string& targetStringValue) { auto resourceI18nFileNum = currentConfigResourceData_->GetArraySize(); for (int i = 0; i < resourceI18nFileNum; i++) { auto priorResource = currentConfigResourceData_->GetArrayItem(i); if ((priorResource->Contains(targetStringKey))) { auto valuePair = priorResource->GetValue(targetStringKey); if (valuePair->Contains(targetStringValue)) { return valuePair->GetValue(targetStringValue); } } } return JsonUtil::Create(true); } std::string JsiDeclarativeEngineInstance::GetMediaResource(const std::string& targetFileName) { auto iter = mediaResourceFileMap_.find(targetFileName); if (iter != mediaResourceFileMap_.end()) { return iter->second; } return std::string(); } RefPtr<JsAcePage> JsiDeclarativeEngineInstance::GetRunningPage(const shared_ptr<JsRuntime>& runtime) { LOGD("GetRunningPage"); if (runtime == nullptr) { LOGE("jsRuntime is nullptr"); return nullptr; } auto engineInstance = static_cast<JsiDeclarativeEngineInstance*>(runtime->GetEmbedderData()); if (engineInstance == nullptr) { LOGE("engineInstance is nullptr"); return nullptr; } return engineInstance->GetRunningPage(); } RefPtr<JsAcePage> JsiDeclarativeEngineInstance::GetStagingPage(const shared_ptr<JsRuntime>& runtime) { LOGD("GetStagingPage"); if (runtime == nullptr) { LOGE("jsRuntime is nullptr"); return nullptr; } auto engineInstance = static_cast<JsiDeclarativeEngineInstance*>(runtime->GetEmbedderData()); if (engineInstance == nullptr) { LOGE("engineInstance is nullptr"); return nullptr; } return engineInstance->GetStagingPage(); } void JsiDeclarativeEngineInstance::PostJsTask(const shared_ptr<JsRuntime>& runtime, std::function<void()>&& task) { LOGD("PostJsTask"); if (runtime == nullptr) { LOGE("jsRuntime is nullptr"); return; } auto engineInstance = static_cast<JsiDeclarativeEngineInstance*>(runtime->GetEmbedderData()); if (engineInstance == nullptr) { LOGE("engineInstance is nullptr"); return; } engineInstance->GetDelegate()->PostJsTask(std::move(task)); } void JsiDeclarativeEngineInstance::TriggerPageUpdate(const shared_ptr<JsRuntime>& runtime) { LOGD("TriggerPageUpdate"); if (runtime == nullptr) { LOGE("jsRuntime is nullptr"); return; } auto engineInstance = static_cast<JsiDeclarativeEngineInstance*>(runtime->GetEmbedderData()); if (engineInstance == nullptr) { LOGE("engineInstance is nullptr"); return; } engineInstance->GetDelegate()->TriggerPageUpdate(engineInstance->GetRunningPage()->GetPageId()); } RefPtr<PipelineContext> JsiDeclarativeEngineInstance::GetPipelineContext(const shared_ptr<JsRuntime>& runtime) { LOGD("GetPipelineContext"); if (runtime == nullptr) { LOGE("jsRuntime is nullptr"); return nullptr; } auto engineInstance = static_cast<JsiDeclarativeEngineInstance*>(runtime->GetEmbedderData()); if (engineInstance == nullptr) { LOGE("engineInstance is nullptr"); return nullptr; } return engineInstance->GetDelegate()->GetPipelineContext(); } void JsiDeclarativeEngineInstance::FlushCommandBuffer(void* context, const std::string& command) { return; } // ----------------------- // Start JsiDeclarativeEngine // ----------------------- JsiDeclarativeEngine::~JsiDeclarativeEngine() { CHECK_RUN_ON(JS); LOG_DESTROY(); engineInstance_->GetDelegate()->RemoveTaskObserver(); if (nativeEngine_ != nullptr) { nativeEngine_->CancelCheckUVLoop(); delete nativeEngine_; } } bool JsiDeclarativeEngine::Initialize(const RefPtr<FrontendDelegate>& delegate) { CHECK_RUN_ON(JS); ACE_SCOPED_TRACE("JsiDeclarativeEngine::Initialize"); LOGI("JsiDeclarativeEngine Initialize"); ACE_DCHECK(delegate); engineInstance_ = AceType::MakeRefPtr<JsiDeclarativeEngineInstance>(delegate, instanceId_); bool result = engineInstance_->InitJsEnv(IsDebugVersion() && NeedDebugBreakPoint(), GetExtraNativeObject()); if (!result) { LOGE("JsiDeclarativeEngine Initialize, init js env failed"); return false; } auto runtime = engineInstance_->GetJsRuntime(); auto vm = std::static_pointer_cast<ArkJSRuntime>(runtime)->GetEcmaVm(); if (vm == nullptr) { LOGE("JsiDeclarativeEngine Initialize, vm is null"); return false; } nativeEngine_ = new ArkNativeEngine(const_cast<EcmaVM*>(vm), static_cast<void*>(this)); SetPostTask(nativeEngine_); nativeEngine_->CheckUVLoop(); RegisterWorker(); return result; } void JsiDeclarativeEngine::SetPostTask(NativeEngine* nativeEngine) { LOGI("SetPostTask"); auto weakDelegate = AceType::WeakClaim(AceType::RawPtr(engineInstance_->GetDelegate())); auto&& postTask = [weakDelegate, nativeEngine = nativeEngine_](bool needSync) { auto delegate = weakDelegate.Upgrade(); if (delegate == nullptr) { LOGE("delegate is nullptr"); return; } delegate->PostJsTask([nativeEngine, needSync]() { if (nativeEngine == nullptr) { return; } nativeEngine->Loop(LOOP_NOWAIT, needSync); }); }; nativeEngine_->SetPostTask(postTask); } void JsiDeclarativeEngine::RegisterInitWorkerFunc() { auto weakInstance = AceType::WeakClaim(AceType::RawPtr(engineInstance_)); auto&& initWorkerFunc = [weakInstance](NativeEngine* nativeEngine) { LOGI("WorkerCore RegisterInitWorkerFunc called"); if (nativeEngine == nullptr) { LOGE("nativeEngine is nullptr"); return; } auto arkNativeEngine = static_cast<ArkNativeEngine*>(nativeEngine); if (arkNativeEngine == nullptr) { LOGE("arkNativeEngine is nullptr"); return; } auto instance = weakInstance.Upgrade(); if (instance == nullptr) { LOGE("instance is nullptr"); return; } instance->InitConsoleModule(arkNativeEngine); std::vector<uint8_t> buffer((uint8_t *)_binary_jsEnumStyle_abc_start, (uint8_t *)_binary_jsEnumStyle_abc_end); auto stateMgmtResult = arkNativeEngine->RunBufferScript(buffer); if (stateMgmtResult == nullptr) { LOGE("init worker error"); } }; OHOS::CCRuntime::Worker::WorkerCore::RegisterInitWorkerFunc(initWorkerFunc); } void JsiDeclarativeEngine::RegisterAssetFunc() { auto weakDelegate = AceType::WeakClaim(AceType::RawPtr(engineInstance_->GetDelegate())); auto&& assetFunc = [weakDelegate](const std::string& uri, std::vector<uint8_t>& content) { LOGI("WorkerCore RegisterAssetFunc called"); auto delegate = weakDelegate.Upgrade(); if (delegate == nullptr) { LOGE("delegate is nullptr"); return; } size_t index = uri.find_last_of("."); if (index == std::string::npos) { LOGE("invalid uri"); } else { delegate->GetResourceData(uri.substr(0, index) + ".abc", content); } }; OHOS::CCRuntime::Worker::WorkerCore::RegisterAssetFunc(assetFunc); } void JsiDeclarativeEngine::RegisterWorker() { RegisterInitWorkerFunc(); RegisterAssetFunc(); } void JsiDeclarativeEngine::LoadJs(const std::string& url, const RefPtr<JsAcePage>& page, bool isMainPage) { ACE_SCOPED_TRACE("JsiDeclarativeEngine::LoadJs"); LOGD("JsiDeclarativeEngine LoadJs"); ACE_DCHECK(engineInstance_); engineInstance_->SetStagingPage(page); if (isMainPage) { ACE_DCHECK(!engineInstance_->GetRunningPage()); engineInstance_->SetRunningPage(page); } auto runtime = engineInstance_->GetJsRuntime(); auto delegate = engineInstance_->GetDelegate(); JsiDeclarativeUtils::SetCurrentState(JsErrorType::LOAD_JS_BUNDLE_ERROR, instanceId_, page->GetUrl(), page); // get source map std::string jsSourceMap; if (delegate->GetAssetContent(url + ".map", jsSourceMap)) { page->SetPageMap(jsSourceMap); } else { LOGW("js source map load failed!"); } // get js bundle content shared_ptr<JsValue> jsCode = runtime->NewUndefined(); shared_ptr<JsValue> jsAppCode = runtime->NewUndefined(); const char js_ext[] = ".js"; const char bin_ext[] = ".abc"; auto pos = url.rfind(js_ext); if (pos != std::string::npos && pos == url.length() - (sizeof(js_ext) - 1)) { std::string urlName = url.substr(0, pos) + bin_ext; std::string assetBasePath = delegate->GetAssetPath(urlName); std::string assetPath = assetBasePath.append(urlName); LOGI("assetPath is: %{private}s", assetPath.c_str()); if (isMainPage) { std::string appMap; if (delegate->GetAssetContent("app.js.map", appMap)) { page->SetAppMap(appMap); } else { LOGW("app map load failed!"); } std::string appBasePath = delegate->GetAssetPath("app.abc"); std::string appPath = appBasePath.append("app.abc"); LOGI("appPath is: %{private}s", appPath.c_str()); if (!runtime->ExecuteJsBin(appPath)) { LOGE("ExecuteJsBin \"app.js\" failed."); return; } CallAppFunc("onCreate"); } if (!runtime->ExecuteJsBin(assetPath)) { LOGE("ExecuteJsBin %{private}s failed.", urlName.c_str()); return; } } } void JsiDeclarativeEngine::UpdateRunningPage(const RefPtr<JsAcePage>& page) { LOGD("JsiDeclarativeEngine UpdateRunningPage"); ACE_DCHECK(engineInstance_); engineInstance_->SetRunningPage(page); } void JsiDeclarativeEngine::UpdateStagingPage(const RefPtr<JsAcePage>& page) { LOGD("JsiDeclarativeEngine UpdateStagingPage"); ACE_DCHECK(engineInstance_); engineInstance_->SetStagingPage(page); } void JsiDeclarativeEngine::ResetStagingPage() { LOGD("JsiDeclarativeEngine ResetStagingPage"); ACE_DCHECK(engineInstance_); auto runningPage = engineInstance_->GetRunningPage(); engineInstance_->ResetStagingPage(runningPage); } void JsiDeclarativeEngine::SetJsMessageDispatcher(const RefPtr<JsMessageDispatcher>& dispatcher) { LOGD("JsiDeclarativeEngine SetJsMessageDispatcher"); ACE_DCHECK(engineInstance_); engineInstance_->SetJsMessageDispatcher(dispatcher); } void JsiDeclarativeEngine::FireAsyncEvent(const std::string& eventId, const std::string& param) { LOGD("JsiDeclarativeEngine FireAsyncEvent"); std::string callBuf = std::string("[{\"args\": [\"") .append(eventId) .append("\",") .append(param) .append("], \"method\":\"fireEvent\"}]"); LOGD("FireASyncEvent string: %{private}s", callBuf.c_str()); ACE_DCHECK(engineInstance_); if (!engineInstance_->FireJsEvent(callBuf.c_str())) { LOGE("Js Engine FireSyncEvent FAILED!"); } } void JsiDeclarativeEngine::FireSyncEvent(const std::string& eventId, const std::string& param) { LOGD("JsiDeclarativeEngine FireSyncEvent"); std::string callBuf = std::string("[{\"args\": [\"") .append(eventId) .append("\",") .append(param) .append("], \"method\":\"fireEventSync\"}]"); LOGD("FireSyncEvent string: %{private}s", callBuf.c_str()); ACE_DCHECK(engineInstance_); if (!engineInstance_->FireJsEvent(callBuf.c_str())) { LOGE("Js Engine FireSyncEvent FAILED!"); } } void JsiDeclarativeEngine::TimerCallback(const std::string& callbackId, const std::string& delay, bool isInterval) { TimerCallJs(callbackId); auto runtime = JsiDeclarativeEngineInstance::GetJsRuntime(); auto instance = static_cast<JsiDeclarativeEngineInstance*>(runtime->GetEmbedderData()); if (instance == nullptr) { LOGE("get jsi engine instance failed"); return; } auto delegate = instance->GetDelegate(); if (!delegate) { LOGE("get frontend delegate failed"); return; } if (isInterval) { delegate->WaitTimer(callbackId, delay, isInterval, false); } else { JsiTimerModule::GetInstance()->RemoveCallBack(std::stoi(callbackId)); delegate->ClearTimer(callbackId); } } void JsiDeclarativeEngine::TimerCallJs(const std::string& callbackId) const { shared_ptr<JsValue> func; std::vector<shared_ptr<JsValue>> params; if (!JsiTimerModule::GetInstance()->GetCallBack(std::stoi(callbackId), func, params)) { LOGE("get callback failed"); return; } auto runtime = JsiDeclarativeEngineInstance::GetJsRuntime(); func->Call(runtime, runtime->GetGlobal(), params, params.size()); } void JsiDeclarativeEngine::DestroyPageInstance(int32_t pageId) { LOGI("JsiDeclarativeEngine DestroyPageInstance"); ACE_DCHECK(engineInstance_); engineInstance_->DestroyRootViewHandle(pageId); } void JsiDeclarativeEngine::DestroyApplication(const std::string& packageName) { LOGI("JsiDeclarativeEngine DestroyApplication, packageName %{public}s", packageName.c_str()); shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime(); JsiDeclarativeUtils::SetCurrentState(JsErrorType::DESTROY_APP_ERROR, instanceId_, "", engineInstance_->GetStagingPage()); CallAppFunc("onDestroy"); } void JsiDeclarativeEngine::UpdateApplicationState(const std::string& packageName, Frontend::State state) { LOGD("JsiDeclarativeEngine UpdateApplicationState, packageName %{public}s", packageName.c_str()); if (state == Frontend::State::ON_SHOW) { CallAppFunc("onShow"); } else if (state == Frontend::State::ON_HIDE) { CallAppFunc("onHide"); } else { LOGW("unsupport state"); } } void JsiDeclarativeEngine::OnWindowDisplayModeChanged(bool isShownInMultiWindow, const std::string& data) { LOGI("JsiDeclarativeEngine OnWindowDisplayModeChanged"); shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime(); const std::vector<shared_ptr<JsValue>>& argv = { runtime->NewBoolean(isShownInMultiWindow), runtime->NewString(data) }; CallAppFunc("onWindowDisplayModeChanged", argv); } void JsiDeclarativeEngine::CallAppFunc(const std::string& appFuncName) { const std::vector<shared_ptr<JsValue>>& argv = { }; CallAppFunc(appFuncName, argv); } void JsiDeclarativeEngine::CallAppFunc(const std::string& appFuncName, const std::vector<shared_ptr<JsValue>>& argv) { LOGD("JsiDeclarativeEngine CallAppFunc"); shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime(); ACE_DCHECK(runtime); shared_ptr<JsValue> global = runtime->GetGlobal(); shared_ptr<JsValue> exportsObject = global->GetProperty(runtime, "exports"); if (!exportsObject->IsObject(runtime)) { LOGE("property \"exports\" is not a object"); return; } shared_ptr<JsValue> defaultObject = exportsObject->GetProperty(runtime, "default"); if (!defaultObject->IsObject(runtime)) { LOGE("property \"default\" is not a object"); return; } shared_ptr<JsValue> func = defaultObject->GetProperty(runtime, appFuncName); if (!func || !func->IsFunction(runtime)) { LOGE("%{public}s not found or is not a function!", appFuncName.c_str()); return; } func->Call(runtime, global, argv, argv.size()); } void JsiDeclarativeEngine::MediaQueryCallback(const std::string& callbackId, const std::string& args) { JsEngine::MediaQueryCallback(callbackId, args); } void JsiDeclarativeEngine::RequestAnimationCallback(const std::string& callbackId, uint64_t timeStamp) { } void JsiDeclarativeEngine::JsCallback(const std::string& callbackId, const std::string& args) { } void JsiDeclarativeEngine::RunGarbageCollection() { if (engineInstance_ && engineInstance_->GetJsRuntime()) { engineInstance_->GetJsRuntime()->RunGC(); } } RefPtr<GroupJsBridge> JsiDeclarativeEngine::GetGroupJsBridge() { return nullptr; } } // namespace OHOS::Ace::Framework
35.807339
119
0.67917
[ "object", "vector" ]
0256a5fc27cd8a07babc4596830d2b343a02dec1
7,164
cpp
C++
pong/main.cpp
pixelsquare/pong-opengl
af8f59ce2a33d286265f49b697495a3e4db54e3b
[ "MIT" ]
null
null
null
pong/main.cpp
pixelsquare/pong-opengl
af8f59ce2a33d286265f49b697495a3e4db54e3b
[ "MIT" ]
null
null
null
pong/main.cpp
pixelsquare/pong-opengl
af8f59ce2a33d286265f49b697495a3e4db54e3b
[ "MIT" ]
null
null
null
#include "header.h" #define __HEADER_H__ #include <stdio.h> #include <conio.h> void main(int argc, char **argv) { GLUTmain(argc, argv); srand(time(NULL)); } void Scene() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(LookX, LookY, LookZ, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); /* Keyboard Rotate & Object Position */ glTranslatef(MoveX, MoveY, 0.0f); glRotatef(AngleY, 0.0, 1.0, 0.0); glRotatef(AngleX, 1.0, 0.0, 0.0); /* Objects on Screen */ Lighting(); grid(); bg(); box(); ball(); paddle1(); paddle2(); //******************************************* Color Changer*****// if(ball_x > boxR) { R = 1.0f; G = 0.0f; B = 0.0f; ball_x = 100.0f; } if(ball_x < boxL) { R = 0.0f; G = 0.0f; B = 1.0f; ball_x = -100.0f; } //************************************************// glutSwapBuffers(); } void bg() { glPushMatrix(); glTranslatef(0.0, 0.0, -0.4); glBegin(GL_QUADS); glNormal3f(1.0, 0.0, 0.0); glColor3f(0.2, 1.0, 0.5); glVertex3f(25.0, 25.0, 0.0); glVertex3f(25.0, -25.0, 0.0); glVertex3f(-25.0, -25.0, 0.0); glVertex3f(-25.0, 25.0, 00); glEnd(); } void grid() { for(int i = 0; i < 25; i++) { //x-axis (center) glPushMatrix(); glTranslatef(0.0f, i, -0.5f); glBegin(GL_LINES); glVertex3f(-25.0f, 0.0f, 0.0f); glVertex3f(25.0f, 0.0f,0.0f); glEnd(); glPopMatrix(); //y-axis (center) glPushMatrix(); glTranslatef(i, 0.0f, -0.5f); glBegin(GL_LINES); glVertex3f(0.0f, 25.0f, 0.0f); glVertex3f(0.0f, -25.0f,0.0f); glEnd(); glPopMatrix(); } for(int i = 0; i > -25; i--) { //x-axis (center) glPushMatrix(); glTranslatef(0.0f, i, -0.5f); glBegin(GL_LINES); glVertex3f(-25.0f, 0.0f, 0.0f); glVertex3f(25.0f, 0.0f,0.0f); glEnd(); glPopMatrix(); //y-axis (center) glPushMatrix(); glTranslatef(i, 0.0f, -0.5f); glBegin(GL_LINES); glVertex3f(0.0f, -25.0f, 0.0f); glVertex3f(0.0f, 25.0f,0.0f); glEnd(); glPopMatrix(); } } void box() { glPushMatrix(); glColor3f(R, G, B); /* Ball Edges */ glPushMatrix(); // BOTTOM - LEFT BOX glScalef(0.8, 1.0, 1.0); glTranslatef(-6.0, -6.0, 0.1); glutSolidCube(1.0); glPopMatrix(); glPushMatrix(); // BOTTOM - RIGHT BOX glScalef(0.8, 1.0, 1.0); glTranslatef(6.0, -6.0, 0.1); glutSolidCube(1.0); glPopMatrix(); glPushMatrix(); // TOP - LEFT BOX glScalef(0.8, 1.0, 1.0); glTranslatef(-6.0, 6.0, 0.1); glutSolidCube(1.0); glPopMatrix(); glPushMatrix(); // TOP - RIGHT BOX glScalef(0.8, 1.0, 1.0); glTranslatef(6.0, 6.0, 0.1); glutSolidCube(1.0); glPopMatrix(); for(int a = 0; a < 12; a++) { a += 1.0; glPushMatrix(); // RIGHT Side glScalef(0.8, 1.0, 0.5); glTranslatef(0.0, -5.0, -0.3); glTranslatef(6.0, a, 0.0); glutSolidCube(1.0); glPopMatrix(); glPushMatrix(); // RIGHT Side glScalef(0.8, 1.0, 0.8); glTranslatef(0.0, -6.0, 0.0); glTranslatef(6.0, a, 0.0); glutSolidCube(1.0); glPopMatrix(); glPushMatrix(); // LEFT Side glScalef(0.8, 1.0, 0.5); glTranslatef(0.0, -5.0, -0.3); glTranslatef(-6.0, a, 0.0); glutSolidCube(1.0); glPopMatrix(); glPushMatrix(); // LEFT Side glScalef(0.8, 1.0, 0.8); glTranslatef(0.0, -6.0, 0.0); glTranslatef(-6.0, a, 0.0); glutSolidCube(1.0); glPopMatrix(); glPushMatrix(); // TOP Side glScalef(0.8, 1.0, 0.5); glTranslatef(-5.0, 0.0, -0.3); glTranslatef(a, 6.0, 0.0); glutSolidCube(1.0); glPopMatrix(); glPushMatrix(); // TOP Side glScalef(0.8, 1.0, 0.8); glTranslatef(-6.0, 0.0, 0.0); glTranslatef(a, 6.0, 0.0); glutSolidCube(1.0); glPopMatrix(); glPushMatrix(); // BOTTOM Side glScalef(0.8, 1.0, 0.5); glTranslatef(-5.0, 0.0, -0.3); glTranslatef(a, -6.0, 0.0); glutSolidCube(1.0); glPopMatrix(); glPushMatrix(); // BOTTOM Side glScalef(0.8, 1.0, 0.8); glTranslatef(-6.0, 0.0, 0.0); glTranslatef(a, -6.0, 0.0); glutSolidCube(1.0); glPopMatrix(); } glPopMatrix(); } void ball() { //************************************************// if((blrx >= p1ulx && bulx <= p1lrx) && (blry <= p1uly && buly >= p1lry)) { Tx = true; Srate = ((rand() % 50) / 1000.0) + 0.05; } if((blrx >= p2ulx && bulx <= p2lrx) && (blry <= p2uly && buly >= p2lry)) { Tx = false; Srate = ((rand() % 50) / 1000.0) + 0.07; } //******************************************* TEST (X-axis) *****// if (Tx) { ball_x -= Srate; blrx -= Srate; bulx -= Srate; } else { ball_x += Srate; blrx += Srate; bulx += Srate; } //************************************************// if(buly >= boxT && bulx <= boxT) { Ty = true; Srate = ((rand() % 50) / 1000.0) + 0.08; } if(blrx >= boxB && blry <= boxB) { Ty = false; Srate = ((rand() % 50) / 1000.0) + 0.04; } //******************************************* TEST (Y-axis)*****// if (Ty) { ball_y -= Srate; blry -= Srate; buly -= Srate; } else { ball_y += Srate; blry += Srate; buly += Srate; } //************************************************// angle += 1.0; glPushMatrix(); glColor3f(1.0f, 1.0f, 1.0f); glTranslatef(ball_x, ball_y, z); glRotatef(angle, 1.0f, 1.0f, 1.0f); glutWireSphere(0.3, slices, stacks); glPopMatrix(); } void paddle1() { if(Tai1) { if(blrx >= p1 && bulx >= p1) { Tai = false; //Srate = ((rand() % 100) / 1000.0) + 0.02; } if(blry <= p1 && buly <= p1) { Tai = true; //Srate = ((rand() % 100) / 1000.0) + 0.02; } if (Tai) { if(p1lry >= -5.2) { p1 -= Srate; p1uly -= Srate; p1lry -= Srate; } } else { if(p1lry <= 5.2) { p1 += Srate; p1uly += Srate; p1lry += Srate; } } } glPushMatrix(); glTranslatef(4.0, p1, 0.0); glColor3f(1.0f, 1.0f, 1.0f); glPushMatrix(); glRotatef(90.0, -45.0, 0.0, 0.0); glScalef(pwidth, pheight, 0.5); glutSolidCone(0.4, 2.5, slices, stacks); glPopMatrix(); glPushMatrix(); glRotatef(90.0, 45.0, 0.0, 0.0); glScalef(0.3, 0.3, 0.5); glutSolidCone(0.4, 2.5, slices, stacks); glPopMatrix(); glPushMatrix(); glutSolidSphere(0.15, slices, stacks); glPopMatrix(); glPopMatrix(); } void paddle2() { if(Tai2) { if(blrx >= p2 && bulx >= p2) { Tai = false; //Srate = ((rand() % 100) / 1000.0) + 0.02; } if(blry <= p2 && buly <= p2) { Tai = true; //Srate = ((rand() % 100) / 1000.0) + 0.02; } if (Tai) { if(p2lry >= -5.2) { p2 -= Srate; p2uly -= Srate; p2lry -= Srate; } } else { if(p2lry <= 5.2) { p2 += Srate; p2uly += Srate; p2lry += Srate; } } } glPushMatrix(); glTranslatef(-4.0, p2, 0.0); glColor3f(1.0f, 1.0f, 1.0f); glPushMatrix(); glRotatef(90.0, -45.0, 0.0, 0.0); glScalef(pwidth, pheight, 0.5); glutSolidCone(0.4, 2.5, slices, stacks); glPopMatrix(); glPushMatrix(); glRotatef(90.0, 45.0, 0.0, 0.0); glScalef(0.3, 0.3, 0.5); glutSolidCone(0.4, 2.5, slices, stacks); glPopMatrix(); glPushMatrix(); glutSolidSphere(0.15, slices, stacks); glPopMatrix(); glPopMatrix(); }
18.65625
73
0.519403
[ "object" ]
0257a3384f5696f1b5511d437a73febce04948f9
4,934
cpp
C++
src/Meta/math/atlas2.cpp
MadManRises/Madgine
c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f
[ "MIT" ]
5
2018-05-16T14:09:34.000Z
2019-10-24T19:01:15.000Z
src/Meta/math/atlas2.cpp
MadManRises/Madgine
c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f
[ "MIT" ]
71
2017-06-20T06:41:42.000Z
2021-01-11T11:18:53.000Z
src/Meta/math/atlas2.cpp
MadManRises/Madgine
c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f
[ "MIT" ]
2
2018-05-16T13:57:25.000Z
2018-05-16T13:57:51.000Z
#include "../metalib.h" #include "atlas2.h" #include "common.h" namespace Engine { static std::tuple<float, int, bool> getScore(Atlas2::Bin &bin, const Vector2i &binSize, const Vector2i &size, bool allowFlip) { float score = 0; int cornerIndex; bool flipped; for (int index = 0; index < bin.mCorners.size(); ++index) { const Vector2i &pos = bin.mCorners[index]; int rightEnd = index > 0 ? bin.mCorners[index - 1].x : binSize.x; int bottomEnd = (index < bin.mCorners.size() - 1) ? bin.mCorners[index + 1].y : binSize.y; Vector2i cornerBounds { rightEnd - pos.x, bottomEnd - pos.y }; if (pos.x + size.x <= binSize.x && pos.y + size.y <= binSize.y) { float score_x = float(cornerBounds.x) / size.x; if (score_x > 1.0f) score_x = 1.0f; float score_y = float(cornerBounds.y) / size.y; if (score_y > 1.0f) score_y = 1.0f; if (score_x * score_y > score) { score = score_x * score_y; cornerIndex = index; flipped = false; } } if (allowFlip) { if (pos.x + size.y <= binSize.x && pos.y + size.x <= binSize.y) { float score_x = float(cornerBounds.x) / size.y; if (score_x > 1.0f) score_x = 1.0f; float score_y = float(cornerBounds.y) / size.x; if (score_y > 1.0f) score_y = 1.0f; if (score_x * score_y > score) { score = score_x * score_y; cornerIndex = index; flipped = true; } } } } return { score, cornerIndex, flipped }; } static Atlas2::Entry insertIntoBin(Atlas2::Bin &bin, const Vector2i &_size, int cornerIndex, bool flipped) { Vector2i size = _size; if (flipped) size = { size.y, size.x }; Atlas2::Entry entry; entry.mArea.mTopLeft = bin.mCorners[cornerIndex] + bin.mOrigin; entry.mArea.mSize = size; entry.mFlipped = flipped; //Update x Vector2i newCornerX = bin.mCorners[cornerIndex] + Vector2i { size.x, 0 }; while (cornerIndex > 0 && newCornerX.x >= bin.mCorners[cornerIndex - 1].x) { newCornerX.y = bin.mCorners[cornerIndex - 1].y; bin.mCorners.erase(bin.mCorners.begin() + (cornerIndex - 1)); --cornerIndex; } bin.mCorners.insert(bin.mCorners.begin() + cornerIndex, newCornerX); ++cornerIndex; //Update y Vector2i newCornerY = bin.mCorners[cornerIndex] + Vector2i { 0, size.y }; while (cornerIndex < bin.mCorners.size() - 1 && newCornerY.y >= bin.mCorners[cornerIndex + 1].y) { newCornerY.x = bin.mCorners[cornerIndex + 1].x; bin.mCorners.erase(bin.mCorners.begin() + (cornerIndex + 1)); } bin.mCorners[cornerIndex] = newCornerY; return entry; } void Atlas2::addBin(const Vector2i &origin) { mBins.emplace_back(Bin { origin }).mCorners.emplace_back(Vector2i { 0, 0 }); } Atlas2::Entry Atlas2::insert(const Vector2i &size, const std::function<void()> &expand, bool allowFlip) { assert(size.x <= mBinSize.x && size.y <= mBinSize.y); float score = 0; Bin *targetBin; int cornerIndex; bool flipped; for (Bin &bin : mBins) { auto [newScore, newCornerIndex, newFlipped] = getScore(bin, mBinSize, size, allowFlip); if (newScore > score) { score = newScore; cornerIndex = newCornerIndex; targetBin = &bin; flipped = newFlipped; } } if (score == 0) { size_t store = mBins.size(); expand(); if (mBins.size() > store) { return insert(size, expand, allowFlip); } } if (score > 0) return insertIntoBin(*targetBin, size, cornerIndex, flipped); else return Entry(); } std::vector<Atlas2::Entry> Atlas2::insert(const std::vector<Vector2i> &sizes, const std::function<void()> &expand, bool allowFlip) { std::vector<std::pair<Vector2i, int>> items; int index = 0; std::transform(sizes.begin(), sizes.end(), std::back_inserter(items), [&](const Vector2i &v) { return std::make_pair(v, index++); }); std::sort(items.begin(), items.end(), [](const std::pair<Vector2i, int> &first, const std::pair<Vector2i, int> &second) { if (first.first.x * first.first.y > second.first.x * second.first.y) return true; if (first.first.x * first.first.y < second.first.x * second.first.y) return false; return min(first.first.x, first.first.y) > min(second.first.x, second.first.y); }); std::vector<Entry> result; result.resize(items.size()); for (const std::pair<Vector2i, int> &p : items) { result[p.second] = insert(p.first, expand, allowFlip); } return result; } }
31.628205
130
0.569315
[ "vector", "transform" ]
0268c153ed931270e76b15157e769a9f2e049363
14,599
cpp
C++
example/full_sample/full_sample.cpp
icerlion/FlyRedis
3cac60c67b0c117da55b5fc404fd6d9cd939e8b1
[ "Apache-2.0" ]
19
2019-05-24T07:26:19.000Z
2022-03-25T13:14:45.000Z
example/full_sample/full_sample.cpp
icerlion/FlyRedis
3cac60c67b0c117da55b5fc404fd6d9cd939e8b1
[ "Apache-2.0" ]
7
2020-05-27T09:12:59.000Z
2021-12-18T17:32:29.000Z
example/full_sample/full_sample.cpp
icerlion/FlyRedis
3cac60c67b0c117da55b5fc404fd6d9cd939e8b1
[ "Apache-2.0" ]
4
2020-06-09T09:56:18.000Z
2020-10-28T09:07:35.000Z
#include "FlyRedis/FlyRedis.h" #include "boost/thread.hpp" void Logger(const char* pszLevel, const char* pszMsg) { int nCurTime = (int)time(nullptr); printf("%d - %s - %s\n", nCurTime, pszLevel, pszMsg); } void LoggerDebug(const char* pszMsg) { Logger("Debug", pszMsg); } void LoggerNotice(const char* pszMsg) { Logger("Notice", pszMsg); } void LoggerError(const char* pszMsg) { Logger("Error", pszMsg); } void LoggerWarning(const char* pszMsg) { Logger("Warning", pszMsg); } void LoggerCommand(const char* pszMsg) { Logger("Command", pszMsg); } bool InitFlyRedisClient(CFlyRedisClient& hFlyRedisClient, const std::string& strRedisAddr, const std::string& strPassword, bool bUseTLSFlag) { hFlyRedisClient.SetRedisConfig(strRedisAddr, strPassword); hFlyRedisClient.SetRedisReadWriteType(FlyRedisReadWriteType::ReadWriteOnMaster); hFlyRedisClient.SetReadTimeoutSeconds(60); #ifdef FLY_REDIS_ENABLE_TLS if (bUseTLSFlag && !hFlyRedisClient.SetTLSContext("./tls/redis.crt", "./tls/redis.key", "./tls/ca.crt", "")) { return false; } #else if (bUseTLSFlag) { LoggerError("TLS Not Enable, Please Define Macro FLY_REDIS_ENABLE_TLS When Compile"); return false; } #endif // FLY_REDIS_ENABLE_TLS //hFlyRedisClient.SetRedisClusterDetectType(FlyRedisClusterDetectType::DisableCluster); if (!hFlyRedisClient.Open()) { return false; } return true; } void ThreadTestCommon(std::string strRedisAddr, std::string strPassword, bool bUseTLSFlag) { CFlyRedisClient hFlyRedisClient; if (!InitFlyRedisClient(hFlyRedisClient, strRedisAddr, strPassword, bUseTLSFlag)) { return; } hFlyRedisClient.HELLO(3); hFlyRedisClient.HELLO_AUTH_SETNAME(2, "default", "123456", "FlyRedis"); hFlyRedisClient.HELLO_AUTH_SETNAME(3, "default", "123456", "FlyRedis"); ////////////////////////////////////////////////////////////////////////// FlyRedisResponse stRedisResponse; double fResult = 0.0f; int nResult = 0; ////////////////////////////////////////////////////////////////////////// hFlyRedisClient.SET("{mkey}:1", "val1"); hFlyRedisClient.SET("{mkey}:2", "val2"); std::vector<std::string> vecMKey; vecMKey.push_back("{mkey}:1"); vecMKey.push_back("{mkey}:2"); hFlyRedisClient.MGET(vecMKey, stRedisResponse.vecRedisResponse); // You are free to run every redis cmd. time_t nBeginTime = time(nullptr); ////////////////////////////////////////////////////////////////////////// std::string strKey = "floatkey"; hFlyRedisClient.SET(strKey, std::to_string(1.5f)); hFlyRedisClient.INCRBYFLOAT(strKey, 0.1f, fResult); ////////////////////////////////////////////////////////////////////////// for (int i = 0; i < 1000; ++i) { if (i % 100 == 0) { LoggerNotice(std::to_string(i).c_str()); } strKey = "key_" + std::to_string(i); if (!hFlyRedisClient.SET(strKey, "value")) { LoggerError("SET FAILED"); continue; } if (!hFlyRedisClient.GET(strKey, stRedisResponse.strRedisResponse)) { LoggerError("GET FAILED"); continue; } if (!hFlyRedisClient.DEL(strKey, nResult)) { LoggerError("DEL FAILED"); continue; } strKey = "hashkey_" + std::to_string(i); for (int j = 0; j < 5; ++j) { std::string strHashField = "field_" + std::to_string(j); if (!hFlyRedisClient.HSET(strKey, strHashField, "value", nResult)) { LoggerError("HSET FAILED"); continue; } if (!hFlyRedisClient.HGET(strKey, strHashField, stRedisResponse.strRedisResponse)) { LoggerError("HGET FAILED"); continue; } if (!hFlyRedisClient.HGETALL(strKey, stRedisResponse.mapRedisResponse)) { LoggerError("HGET FAILED"); continue; } } strKey = "setkey_" + std::to_string(i); for (int j = 0; j < 5; ++j) { std::string strValue = "sval_" + std::to_string(j); if (!hFlyRedisClient.SADD(strKey, strValue, nResult)) { LoggerError("SADD FAILED"); continue; } if (!hFlyRedisClient.SMEMBERS(strKey, stRedisResponse.setRedisResponse)) { LoggerError("SMEMBERS FAILED"); continue; } } } time_t nElapsedTime = time(nullptr) - nBeginTime; LoggerNotice(("TimeCost: " + std::to_string(nElapsedTime)).c_str()); } void ThreadTestPubSub(const std::string& strRedisAddr, const std::string& strPassword, bool bUseTLSFlag) { CFlyRedisClient hFlyRedisClient; if (!InitFlyRedisClient(hFlyRedisClient, strRedisAddr, strPassword, bUseTLSFlag)) { return; } int nResult = 0; std::vector<std::string> vecRedisNodeList = hFlyRedisClient.FetchRedisNodeList(); for (auto& strNode : vecRedisNodeList) { hFlyRedisClient.ChoseCurRedisNode(strNode); hFlyRedisClient.PUBSUB_NUMPAT(nResult); hFlyRedisClient.PUBSUB_NUMSUB("", nResult); hFlyRedisClient.PUBSUB_NUMSUB("ch1", nResult); std::map<std::string, int> mapKVP; std::vector<std::string> vecChannel; vecChannel.emplace_back("ch1"); vecChannel.push_back("ch2"); vecChannel.push_back("ch3"); hFlyRedisClient.PUBSUB_NUMSUB(vecChannel, mapKVP); std::vector<std::string> vecResult; hFlyRedisClient.PUBSUB_CHANNELS("", vecResult); vecResult.clear(); hFlyRedisClient.PUBSUB_CHANNELS("ch1", vecResult); vecResult.clear(); hFlyRedisClient.PUBSUB_CHANNELS("ch*", vecResult); } for (int i = 0; i < 10; ++i) { std::string strMsg = "msg-" + std::to_string(time(nullptr)) + "-" + std::to_string(i); for (int j = 0; j < 10; ++j) { std::string strChannel = "ch" + std::to_string(j); hFlyRedisClient.PUBLISH(strChannel, strMsg, nResult); for (auto& strNode : vecRedisNodeList) { hFlyRedisClient.ChoseCurRedisNode(strNode); hFlyRedisClient.PUBSUB_NUMPAT(nResult); } } } for (int i = 1; i < 2; ++i) { std::string strChannel1 = "ch" + std::to_string(i); std::string strChannel2 = "ch" + std::to_string(i * 2); std::vector<std::string> vecChannel; vecChannel.push_back(strChannel1); vecChannel.push_back(strChannel2); for (auto& strNode : vecRedisNodeList) { hFlyRedisClient.ChoseCurRedisNode(strNode); std::vector<FlyRedisSubscribeResponse> vecResult; hFlyRedisClient.SUBSCRIBE(vecChannel, vecResult); time_t nCurTime = time(nullptr); time_t nBeginTime = nCurTime; while (nCurTime - nBeginTime < 5) { nCurTime = time(nullptr); std::vector<FlyRedisSubscribeResponse> vecSubscribeRst; hFlyRedisClient.PollSubscribeMsg(vecSubscribeRst, 100); for (auto& stRst : vecSubscribeRst) { printf("%zu - %s - %s - %s\n", nCurTime, stRst.strCmd.c_str(), stRst.strChannel.c_str(), stRst.strMsg.c_str()); if (0 == stRst.strMsg.compare("un1")) { std::vector<std::string> vecUnSubResult; hFlyRedisClient.UNSUBSCRIBE(strChannel1, vecUnSubResult); } else if (0 == stRst.strMsg.compare("un2")) { std::vector<std::string> vecUnSubResult; hFlyRedisClient.UNSUBSCRIBE(strChannel2, vecUnSubResult); } else if (0 == stRst.strMsg.compare("un")) { std::vector<std::string> vecUnSubResult; hFlyRedisClient.UNSUBSCRIBE("", vecUnSubResult); } } if (nCurTime % 30 == 0) { std::string strPingResponse; hFlyRedisClient.PING(std::to_string(nCurTime), strPingResponse); printf("PING %zu - %s\n", nCurTime, strPingResponse.c_str()); boost::this_thread::sleep_for(boost::chrono::seconds(1)); } } } } return; } void ThreadPublish(const std::string& strRedisAddr, const std::string& strPassword, bool bUseTLSFlag) { CFlyRedisClient hFlyRedisClient; if (!InitFlyRedisClient(hFlyRedisClient, strRedisAddr, strPassword, bUseTLSFlag)) { return; } int nResult = 0; time_t nBeginTime = time(nullptr); while (time(nullptr) - nBeginTime < 10) { std::string strChannel = "ch1"; std::string strMsg = "ch1-msg-" + std::to_string(time(nullptr)) + "-" + std::to_string(rand()); hFlyRedisClient.PUBLISH(strChannel, strMsg, nResult); strChannel = "ch2"; strMsg = "ch2-msg-" + std::to_string(time(nullptr)) + "-" + std::to_string(rand()); hFlyRedisClient.PUBLISH(strChannel, strMsg, nResult); boost::this_thread::sleep_for(boost::chrono::milliseconds(100)); } } void ThreadSubscribe(const std::string& strRedisAddr, const std::string& strPassword, bool bUseTLSFlag) { CFlyRedisClient hFlyRedisClient; if (!InitFlyRedisClient(hFlyRedisClient, strRedisAddr, strPassword, bUseTLSFlag)) { return; } FlyRedisSubscribeResponse stFlyRedisSubscribeResponse; std::vector<FlyRedisSubscribeResponse> vecFlyRedisSubscribeResponse; ////////////////////////////////////////////////////////////////////////// hFlyRedisClient.SUBSCRIBE("ch1", stFlyRedisSubscribeResponse); //std::vector<std::string> vecChannel; //vecChannel.push_back("ch1"); //vecChannel.push_back("ch2"); //hFlyRedisClient.SUBSCRIBE(vecChannel, vecFlyRedisSubscribeResponse); ////////////////////////////////////////////////////////////////////////// time_t nBeginTime = time(nullptr); while (time(nullptr) - nBeginTime < 10) { std::vector<FlyRedisSubscribeResponse> vecSubscribeRst; hFlyRedisClient.PollSubscribeMsg(vecSubscribeRst, 10); for (auto& stResponse : vecSubscribeRst) { printf("%zu,Subscribe,%s,%s,%s\n", time(nullptr), stResponse.strCmd.c_str(), stResponse.strChannel.c_str(), stResponse.strMsg.c_str()); } } } void ThreadPSubscribe(const std::string& strRedisAddr, const std::string& strPassword, bool bUseTLSFlag) { CFlyRedisClient hFlyRedisClient; if (!InitFlyRedisClient(hFlyRedisClient, strRedisAddr, strPassword, bUseTLSFlag)) { return; } FlyRedisSubscribeResponse stFlyRedisSubscribeResponse; std::vector<FlyRedisSubscribeResponse> vecFlyRedisSubscribeResponse; ////////////////////////////////////////////////////////////////////////// //hFlyRedisClient.PSUBSCRIBE("ch*", stFlyRedisSubscribeResponse); std::vector<std::string> vecChannel; vecChannel.push_back("c*"); vecChannel.push_back("ch*"); hFlyRedisClient.PSUBSCRIBE(vecChannel, vecFlyRedisSubscribeResponse); ////////////////////////////////////////////////////////////////////////// time_t nBeginTime = time(nullptr); while (time(nullptr) - nBeginTime < 10) { std::vector<FlyRedisPMessageResponse> vecSubscribeRst; hFlyRedisClient.PollPSubscribeMsg(vecSubscribeRst, 10); for (FlyRedisPMessageResponse& stResponse : vecSubscribeRst) { printf("%zu,PSubscribe,%s,%s,%s,%s\n", time(nullptr), stResponse.strCmd.c_str(), stResponse.strPattern.c_str(), stResponse.strChannel.c_str(), stResponse.strMsg.c_str()); } } } int main(int argc, char* argv[]) { // ./sample 192.168.1.10:1000 123456 tls 1 // Start Redis server enable tls // redis-server --tls-port 2000 --port 1000 --tls-cert-file ./tests/tls/redis.crt --tls-key-file ./tests/tls/redis.key --tls-ca-cert-file ./tests/tls/ca.crt --bind 192.168.1.10 --requirepass 123455 if (argc != 5) { // Param: 127.0.0.1:8000 123456 tls 1 printf("sample redis_ip:redis_port redis_password enable_tls thread_count\n"); return -1; } std::string strRedisAddr = argv[1]; std::string strPassword = argv[2]; bool bUseTLSFlag = (0 == strcmp("tls", argv[3])); int nThreadCount = atoi(argv[4]); // Config FlyRedis, but it's not not necessary CFlyRedis::SetLoggerHandler(FlyRedisLogLevel::Debug, LoggerDebug); CFlyRedis::SetLoggerHandler(FlyRedisLogLevel::Notice, LoggerNotice); CFlyRedis::SetLoggerHandler(FlyRedisLogLevel::Error, LoggerError); CFlyRedis::SetLoggerHandler(FlyRedisLogLevel::Warning, LoggerWarning); CFlyRedis::SetLoggerHandler(FlyRedisLogLevel::Command, LoggerCommand); ////////////////////////////////////////////////////////////////////////// boost::thread_group tgPubSub; tgPubSub.create_thread(boost::bind(ThreadPublish, strRedisAddr, strPassword, bUseTLSFlag)); tgPubSub.create_thread(boost::bind(ThreadSubscribe, strRedisAddr, strPassword, bUseTLSFlag)); tgPubSub.create_thread(boost::bind(ThreadPSubscribe, strRedisAddr, strPassword, bUseTLSFlag)); tgPubSub.join_all(); ////////////////////////////////////////////////////////////////////////// ThreadTestPubSub(strRedisAddr, strPassword, bUseTLSFlag); ThreadTestCommon(strRedisAddr, strPassword, bUseTLSFlag); ////////////////////////////////////////////////////////////////////////// boost::thread_group tgTestFun; for (int i = 0; i < nThreadCount; ++i) { tgTestFun.create_thread(boost::bind(ThreadTestCommon, strRedisAddr, strPassword, bUseTLSFlag)); tgTestFun.create_thread(boost::bind(ThreadTestPubSub, strRedisAddr, strPassword, bUseTLSFlag)); } tgTestFun.join_all(); LoggerNotice("Done Test"); return 0; }
40.893557
202
0.573258
[ "vector" ]
02693ed1facdfce11f098527204cfcbb24fd7aec
42,999
cpp
C++
DialogTools/VarGroupingEditorDlg.cpp
chenyoujie/GeoDa
87504344512bd0da2ccadfb160ecd1e918a52f06
[ "BSL-1.0" ]
null
null
null
DialogTools/VarGroupingEditorDlg.cpp
chenyoujie/GeoDa
87504344512bd0da2ccadfb160ecd1e918a52f06
[ "BSL-1.0" ]
null
null
null
DialogTools/VarGroupingEditorDlg.cpp
chenyoujie/GeoDa
87504344512bd0da2ccadfb160ecd1e918a52f06
[ "BSL-1.0" ]
null
null
null
/** * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved * * This file is part of GeoDa. * * GeoDa is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GeoDa is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <set> #include <boost/foreach.hpp> #include <boost/uuid/uuid.hpp> #include <wx/wx.h> #include <wx/xrc/xmlres.h> #include <wx/msgdlg.h> #include <wx/sizer.h> #include <wx/filedlg.h> #include <wx/button.h> #include "../FramesManager.h" #include "../DbfFile.h" #include "../DataViewer/DbfTable.h" #include "../DataViewer/OGRTable.h" #include "../DataViewer/DataViewerAddColDlg.h" #include "../DataViewer/TableInterface.h" #include "../DataViewer/TableState.h" #include "../DataViewer/TimeState.h" #include "../DialogTools/ExportDataDlg.h" #include "../VarCalc/WeightsManInterface.h" #include "../ShapeOperations/GalWeight.h" #include "../GeneralWxUtils.h" #include "../GeoDa.h" #include "../logger.h" #include "../Project.h" #include "../GdaConst.h" #include "VarGroupingEditorDlg.h" #include "TimeEditorDlg.h" #include "../GdaException.h" BEGIN_EVENT_TABLE( VarGroupingEditorDlg, wxDialog ) EVT_CLOSE( VarGroupingEditorDlg::OnClose ) EVT_BUTTON( XRCID("ID_SAVE_SPACETIME_TABLE"), VarGroupingEditorDlg::OnSaveSpaceTimeTableClick ) EVT_BUTTON( XRCID("ID_CREATE_GRP_BUTTON"), VarGroupingEditorDlg::OnCreateGrpClick ) EVT_BUTTON( XRCID("ID_UNGROUP_BUTTON"), VarGroupingEditorDlg::OnUngroupClick ) EVT_BUTTON( XRCID("ID_MOVE_UP_BUTTON"), VarGroupingEditorDlg::OnMoveUpClick ) EVT_BUTTON( XRCID("ID_MOVE_DOWN_BUTTON"), VarGroupingEditorDlg::OnMoveDownClick ) EVT_BUTTON( XRCID("ID_SORT_BUTTON"), VarGroupingEditorDlg::OnSortClick ) EVT_BUTTON( XRCID("ID_PLACEHOLDER_BUTTON"), VarGroupingEditorDlg::OnPlaceholderClick ) EVT_BUTTON( XRCID("ID_ADD_TO_LIST_BUTTON"), VarGroupingEditorDlg::OnAddToListClick ) EVT_BUTTON( XRCID("ID_REMOVE_FR_LIST_BUTTON"), VarGroupingEditorDlg::OnRemoveFrListClick ) EVT_LIST_ITEM_ACTIVATED( XRCID("ID_UNGROUPED_LIST"), VarGroupingEditorDlg::OnUngroupedListItemActivate ) EVT_LIST_ITEM_SELECTED( XRCID("ID_UNGROUPED_LIST"), VarGroupingEditorDlg::OnUngroupedListSelection ) EVT_LIST_ITEM_DESELECTED( XRCID("ID_UNGROUPED_LIST"), VarGroupingEditorDlg::OnUngroupedListSelection ) EVT_LIST_ITEM_ACTIVATED( XRCID("ID_INCLUDE_LIST"), VarGroupingEditorDlg::OnIncludeListItemActivate ) EVT_LIST_ITEM_SELECTED( XRCID("ID_INCLUDE_LIST"), VarGroupingEditorDlg::OnIncludeListSelection ) EVT_LIST_ITEM_DESELECTED( XRCID("ID_INCLUDE_LIST"), VarGroupingEditorDlg::OnIncludeListSelection ) EVT_LIST_BEGIN_LABEL_EDIT(XRCID("ID_INCLUDE_LIST"), VarGroupingEditorDlg::OnIncludeListEdit) EVT_LIST_END_LABEL_EDIT(XRCID("ID_INCLUDE_LIST"), VarGroupingEditorDlg::OnIncludeListEditEnd) EVT_LIST_COL_CLICK(XRCID("ID_INCLUDE_LIST"), VarGroupingEditorDlg::OnIncludeListColClick) EVT_LISTBOX( XRCID("ID_GROUPED_LIST"), VarGroupingEditorDlg::OnGroupedListSelection ) EVT_TEXT( XRCID("ID_NEW_GROUP_NAME_TXT_CTRL"), VarGroupingEditorDlg::OnNewGroupNameChange ) EVT_BUTTON( XRCID("ID_UNGROUPED_VARS_HELP"), VarGroupingEditorDlg::OnUngroupedVarsHelp ) EVT_BUTTON( XRCID("ID_NEW_GROUP_HELP"), VarGroupingEditorDlg::OnNewGroupHelp ) EVT_BUTTON( XRCID("ID_CUR_GROUPED_HELP"), VarGroupingEditorDlg::OnCurGroupedHelp ) EVT_BUTTON( XRCID("ID_SAVE_SPACETIME_HELP"), VarGroupingEditorDlg::OnSaveSTHelp ) EVT_BUTTON( XRCID("ID_TIME_LOAD_FROM_GDA"), VarGroupingEditorDlg::OnLoadFromGda ) END_EVENT_TABLE() using namespace std; VarGroupingEditorDlg::VarGroupingEditorDlg(Project* project_p, wxWindow* parent, const wxString& title, const wxPoint& pos, const wxSize& size, long style) : project(project_p), table_int(project_p->GetTableInt()), frames_manager(project_p->GetFramesManager()), table_state(project_p->GetTableState()), highlight_state(project_p->GetHighlightState()), wmi(project_p->GetWManInt()), common_empty(true), all_init(false), pos_ungrouped_list(0),is_editing(false) { wxLogMessage("Open VarGroupingEditorDlg."); CreateControls(); SetPosition(pos); SetTitle(title); Centre(); frames_manager->registerObserver(this); table_state->registerObserver(this); all_init = true; } VarGroupingEditorDlg::~VarGroupingEditorDlg() { frames_manager->removeObserver(this); table_state->removeObserver(this); } void VarGroupingEditorDlg::CreateControls() { wxXmlResource::Get()->LoadDialog(this, GetParent(), "ID_VAR_GROUPING_EDITOR"); new_group_name_txt_ctrl = wxDynamicCast(FindWindow(XRCID("ID_NEW_GROUP_NAME_TXT_CTRL")), wxTextCtrl); new_field_type_stat_txt = wxDynamicCast(FindWindow(XRCID("ID_NEW_FIELD_TYPE_STAT_TXT")), wxStaticText); move_up_button = wxDynamicCast(FindWindow(XRCID("ID_MOVE_UP_BUTTON")), wxButton); move_down_button = wxDynamicCast(FindWindow(XRCID("ID_MOVE_DOWN_BUTTON")), wxButton); sort_button = wxDynamicCast(FindWindow(XRCID("ID_SORT_BUTTON")), wxButton); placeholder_button = wxDynamicCast(FindWindow(XRCID("ID_PLACEHOLDER_BUTTON")), wxButton); include_list = wxDynamicCast(FindWindow(XRCID("ID_INCLUDE_LIST")), wxListCtrl); include_list->AppendColumn("Time"); include_list->SetColumnWidth(0, 50); include_list->AppendColumn("Name"); include_list->SetColumnWidth(1, 120); include_list_stat_txt = wxDynamicCast(FindWindow(XRCID("ID_INCLUDE_LIST_STAT_TXT")), wxStaticText); add_to_list_button = wxDynamicCast(FindWindow(XRCID("ID_ADD_TO_LIST_BUTTON")), wxButton); remove_fr_list_button = wxDynamicCast(FindWindow(XRCID("ID_REMOVE_FR_LIST_BUTTON")), wxButton); group_button = wxDynamicCast(FindWindow(XRCID("ID_CREATE_GRP_BUTTON")), wxButton); ungroup_button = wxDynamicCast(FindWindow(XRCID("ID_UNGROUP_BUTTON")), wxButton); ungrouped_list = wxDynamicCast(FindWindow(XRCID("ID_UNGROUPED_LIST")), wxListCtrl); ungrouped_list->AppendColumn("Name"); ungrouped_list->SetColumnWidth(0, 120); ungrouped_list->AppendColumn("Type"); ungrouped_list->SetColumnWidth(1, 50); grouped_list = wxDynamicCast(FindWindow(XRCID("ID_GROUPED_LIST")), wxListBox); save_spacetime_button =wxDynamicCast(FindWindow(XRCID("ID_SAVE_SPACETIME_TABLE")), wxButton); ResetAllButtons(); UpdateCommonType(); all_init = true; InitAll(); UpdateButtons(); ungrouped_list->Bind(wxEVT_LEFT_DOWN, &VarGroupingEditorDlg::OnUngroupedListLeftDown, this); include_list->Bind(wxEVT_LEFT_DCLICK, &VarGroupingEditorDlg::OnIncludeListDblClicked, this); include_list->Bind(wxEVT_RIGHT_UP, &VarGroupingEditorDlg::OnIncludeListRightUp, this); include_list->Bind(wxEVT_RIGHT_DOWN, &VarGroupingEditorDlg::OnIncludeListRightDown, this); } /** This should completely reset all info based on data from TableInterface. This is called when dialog is first constructed, and can be called again when changes TableState::update is called. */ void VarGroupingEditorDlg::InitAll() { new_group_name_txt_ctrl->SetValue(wxEmptyString); std::set<wxString> empty_set; InitUngroupedList(empty_set); include_list->DeleteAllItems(); int table_ts = table_int->GetTimeSteps(); if (table_ts > 1) { for (int t=0; t<table_ts; ++t) { include_list->InsertItem(t, table_int->GetTimeString(t)); include_list->SetItem(t, 1, wxEmptyString); } } UpdateTimeStepsTxt(); InitGroupedList(); } void VarGroupingEditorDlg::InitUngroupedList(std::set<wxString>& excl_nms) { ungrouped_list->DeleteAllItems(); std::vector<int> col_id_map; table_int->FillColIdMap(col_id_map); int ug_cnt = 0; for (int i=0, cid_sz=col_id_map.size(); i<cid_sz; ++i) { int col = col_id_map[i]; if (table_int->IsColTimeVariant(col) || excl_nms.find(table_int->GetColName(col)) != excl_nms.end()) { continue; } GdaConst::FieldType type = table_int->GetColType(col); wxString type_str; if (type == GdaConst::double_type || type == GdaConst::long64_type) { type_str << "num"; } else if (type == GdaConst::string_type) { type_str << "str"; } else if (type == GdaConst::date_type) { type_str << "date"; } else if (type == GdaConst::time_type) { type_str << "time"; } else if (type == GdaConst::datetime_type) { type_str << "datetime"; } ungrouped_list->InsertItem(ug_cnt, wxEmptyString); ungrouped_list->SetItem(ug_cnt, 0, table_int->GetColName(col)); ungrouped_list->SetItem(ug_cnt, 1, type_str); ++ug_cnt; } if (pos_ungrouped_list > 0) { if (pos_ungrouped_list >= ug_cnt) { pos_ungrouped_list = ug_cnt -1; } ungrouped_list->EnsureVisible(pos_ungrouped_list); ungrouped_list->SetItemState(pos_ungrouped_list, wxLIST_STATE_FOCUSED|wxLIST_STATE_SELECTED, wxLIST_STATE_FOCUSED|wxLIST_STATE_SELECTED); } } void VarGroupingEditorDlg::OnUngroupedListLeftDown(wxMouseEvent& ev) { ev.Skip(); } void VarGroupingEditorDlg::InitGroupedList() { grouped_list->Clear(); std::vector<int> col_id_map; table_int->FillColIdMap(col_id_map); for (int i=0, ug_cnt=0, cid_sz=col_id_map.size(); i<cid_sz; ++i) { int col = col_id_map[i]; if (table_int->IsColTimeVariant(col)) { grouped_list->Append(table_int->GetColName(col)); continue; } } } void VarGroupingEditorDlg::OnClose(wxCloseEvent& event) { wxLogMessage("In VarGroupingEditorDlg::OnClose"); // Note: it seems that if we don't explictly capture the close event // and call Destory, then the destructor is not called. Destroy(); } void VarGroupingEditorDlg::OnSaveSpaceTimeTableClick( wxCommandEvent& event ) { wxLogMessage("In VarGroupingEditorDlg::OnSaveSpaceTimeTableClick"); std::vector<wxString> tm_strs; table_int->GetTimeStrings(tm_strs); int n_obs = table_int->GetNumberRows(); int n_ts = tm_strs.size(); int n = n_ts * n_obs; std::vector<wxString> time_stack; std::vector<wxInt64> select_stack; std::vector<wxInt64> id_stack; std::vector<wxInt64> new_ids; std::vector<bool> undefs; // should be ignored bool has_highligh = false; const std::vector<bool>& hs(highlight_state->GetHighlight()); int idx = 1; for (int t=0; t<n_ts; t++) { for (int j=0; j<n_obs; j++) { if (hs[j]) { select_stack.push_back(1); has_highligh = true; } else { select_stack.push_back(0); } time_stack.push_back(tm_strs[t]); id_stack.push_back(j); new_ids.push_back(idx); undefs.push_back(false); idx += 1; } } // create in-memory table OGRTable* mem_table_int = new OGRTable(n); OGRColumn* id_col = new OGRColumnInteger("STID", 18, 0, n); id_col->UpdateData(new_ids, undefs); mem_table_int->AddOGRColumn(id_col); if (!id_stack.empty()) { bool using_default_id = true; if (wmi) { boost::uuids::uuid default_wid = wmi->GetDefault(); if (!default_wid.is_nil()) { GalWeight* gw = wmi->GetGal(default_wid); std::vector<wxString> id_vec; int c_id = table_int->FindColId(gw->id_field); if (c_id > 0) { table_int->GetColData(c_id, 1, id_vec); std::vector<wxString> new_id_vec; for (int ii=0; ii<n; ii++) { new_id_vec.push_back(id_vec[id_stack[ii]]); } OGRColumn* id_col = new OGRColumnString(gw->id_field, 50, 0, n); id_col->UpdateData(new_id_vec, undefs); mem_table_int->AddOGRColumn(id_col); using_default_id = false; } } } } if (!select_stack.empty() && has_highligh) { OGRColumn* select_col = new OGRColumnInteger("SELECT", 18, 0, n); select_col->UpdateData(select_stack, undefs); mem_table_int->AddOGRColumn(select_col); } if (!time_stack.empty()) { OGRColumn* time_col = new OGRColumnString("TIME", 50, 0, n); time_col->UpdateData(time_stack, undefs); mem_table_int->AddOGRColumn(time_col); // add time dummies for (int t=0; t<n_ts; t++) { wxString time_dummy_name = "T_" + tm_strs[t]; OGRColumn* time_dummy_col = new OGRColumnInteger(time_dummy_name, 18, 0, n); std::vector<wxInt64> time_dummy_vals; for (int tt=0; tt<n_ts; tt++) { for (int j=0; j<n_obs; j++) { if ( tt == t) { time_dummy_vals.push_back(1); } else { time_dummy_vals.push_back(0); } } } time_dummy_col->UpdateData(time_dummy_vals, undefs); mem_table_int->AddOGRColumn(time_dummy_col); } } int n_col = table_int->GetNumberCols(); for (int i=0; i<n_col; i++) { if (table_int->IsColTimeVariant(i)) { wxString col_name(table_int->GetColName(i)); GdaConst::FieldType ft = table_int->GetColType(i); if (ft == GdaConst::long64_type) { std::vector<wxInt64> stack_dat; stack_dat.reserve(n); for (int t=0; t<n_ts; t++) { std::vector<wxInt64> dat; table_int->GetColData(i, t, dat); stack_dat.insert(stack_dat.end(), dat.begin(), dat.end()); } OGRColumn* var_col = new OGRColumnInteger(col_name, 18, 0, n); var_col->UpdateData(stack_dat, undefs); mem_table_int->AddOGRColumn(var_col); } else if (ft == GdaConst::double_type) { int n_decimal = -1; std::vector<double> stack_dat; stack_dat.reserve(n); for (int t=0; t<n_ts; t++) { std::vector<double> dat; table_int->GetColData(i, t, dat); stack_dat.insert(stack_dat.end(), dat.begin(), dat.end()); int deci = table_int->GetColDecimals(i, t); if (deci > n_decimal) n_decimal = deci; } OGRColumn* var_col = new OGRColumnDouble(col_name, 18, n_decimal, n); var_col->UpdateData(stack_dat, undefs); mem_table_int->AddOGRColumn(var_col); } } } // export ExportDataDlg dlg(this, (TableInterface*)mem_table_int); if (dlg.ShowModal() == wxID_OK) { wxString ds_name = dlg.GetDatasourceName(); wxFileName wx_fn(ds_name); // save weights if (wmi) { boost::uuids::uuid default_wid = wmi->GetDefault(); if (!default_wid.is_nil()) { GeoDaWeight* w = wmi->GetWeights(default_wid); if (w->weight_type == GeoDaWeight::gal_type) { wx_fn.SetExt("gal"); } else if (w->weight_type == GeoDaWeight::gwt_type) { wx_fn.SetExt("gwt"); } wxString ofn(wx_fn.GetFullPath()); w->SaveSpaceTimeWeights(ofn, wmi, table_int); } } } // clean memory delete mem_table_int; } void VarGroupingEditorDlg::OnCreateGrpClick( wxCommandEvent& event ) { wxLogMessage("In VarGroupingEditorDlg::OnCreateGrpClick"); if (!all_init) return; // check that new field name is valid wxString grp_nm = new_group_name_txt_ctrl->GetValue(); grp_nm.Trim(true); grp_nm.Trim(false); if (!table_int->IsValidGroupName(grp_nm) || table_int->DoesNameExist(grp_nm, false)) { wxString m; m << "Variable name \"" << grp_nm << "\" is either a duplicate\n"; m << "or is invalid. Please enter an alternative,\n"; m << "non-duplicate variable name."; wxMessageDialog dlg (this, m, "Error", wxOK | wxICON_ERROR ); dlg.ShowModal(); return; } int tot_items = include_list->GetItemCount(); std::vector<int> cols(tot_items); for (int t=0; t<tot_items; t++) { wxString nm = include_list->GetItemText(t, 1); if (nm == GdaConst::placeholder_str) { cols[t] = -1; } else { cols[t] = table_int->FindColId(nm); } } if (table_int->GetTimeSteps() == 1) { if (table_int->GetTimeSteps() == 1 && tot_items > 1) { if (table_state->GetNumDisallowTimelineChanges() > 0) { wxString msg = table_state->GetDisallowTimelineChangesMsg(); wxMessageDialog dlg (this, msg, "Warning", wxOK | wxICON_INFORMATION); dlg.ShowModal(); return; } } // This is a special case since we are increasing // the number of table time steps. for (int t=1; t<tot_items; ++t) { wxString s; s << "time " << t; table_int->InsertTimeStep(t, s); } } table_int->GroupCols(cols, grp_nm, cols[0]); InitAll(); UpdateButtons(); GdaFrame::GetGdaFrame()->UpdateToolbarAndMenus(); event.Skip(); } void VarGroupingEditorDlg::OnUngroupClick( wxCommandEvent& event ) { wxLogMessage("In VarGroupingEditorDlg::OnUngroupClick"); wxString grp_nm = grouped_list->GetStringSelection(); if (grp_nm == "") return; int col = table_int->FindColId(grp_nm); if (col < 0) return; int tms = table_int->GetColTimeSteps(col); set<wxString> col_nms_set; vector<wxString> col_nms(tms); for (int t=0; t<tms; ++t) { wxString nm = table_int->GetColName(col, t); if (nm.IsEmpty()) nm = GdaConst::placeholder_str; col_nms[t] = nm; col_nms_set.insert(nm); } GdaConst::FieldType type = table_int->GetColType(col); table_int->UngroupCol(col); InitAll(); new_group_name_txt_ctrl->SetValue(grp_nm); if (type == GdaConst::double_type || type == GdaConst::long64_type) { common_type = "num"; } else if (type == GdaConst::date_type) { common_type = "date"; } else if (type == GdaConst::time_type) { common_type = "time"; } else if (type == GdaConst::datetime_type) { common_type = "datetime"; } else { common_type = "string"; } common_empty = false; UpdateCommonType(); include_list->DeleteAllItems(); for (int t=0; t<tms; ++t) { include_list->InsertItem(t, wxEmptyString); include_list->SetItem(t, 1, col_nms[t]); include_list->SetItem(t, 0, table_int->GetTimeString(t)); } InitUngroupedList(col_nms_set); UpdateTimeStepsTxt(); UpdateButtons(); event.Skip(); } /** Shift selected items, including selection highlighting, backwards in time. */ void VarGroupingEditorDlg::OnMoveUpClick( wxCommandEvent& event ) { wxLogMessage("In VarGroupingEditorDlg::OnMoveUpClick"); if (!all_init) return; int item_cnt = include_list->GetItemCount(); int sel_count = include_list->GetSelectedItemCount(); if (sel_count == 0) return; list<int> sel_pos = GetListSel(include_list); if (sel_pos.front() == 0) return; set<int> sel_pos_set; BOOST_FOREACH(int i, sel_pos) sel_pos_set.insert(i); list<int> unsel_pos; for (int i=0; i<item_cnt; ++i) { if (sel_pos_set.find(i) == sel_pos_set.end()) { unsel_pos.push_back(i); } } vector<wxString> orig(item_cnt); for (int i=0; i<item_cnt; i++) orig[i] = include_list->GetItemText(i, 1); UnselectAll(include_list); set<int> new_pos_set; BOOST_FOREACH(int i, sel_pos) { include_list->SetItem(i-1, 1, orig[i]); SelectItem(include_list, i-1); new_pos_set.insert(i-1); } int free_pos = 0; BOOST_FOREACH(int i, unsel_pos) { while (new_pos_set.find(free_pos) != new_pos_set.end()) ++free_pos; include_list->SetItem(free_pos, 1, orig[i]); ++free_pos; } UpdateButtons(); } /** Shift selected items, including selection highlighting, forwards in time */ void VarGroupingEditorDlg::OnMoveDownClick( wxCommandEvent& event ) { wxLogMessage("In VarGroupingEditorDlg::OnMoveDownClick"); if (!all_init) return; int item_cnt = include_list->GetItemCount(); int sel_count = include_list->GetSelectedItemCount(); if (sel_count == 0) return; list<int> sel_pos = GetListSel(include_list); if (sel_pos.back() == item_cnt-1) return; set<int> sel_pos_set; BOOST_FOREACH(int i, sel_pos) sel_pos_set.insert(i); list<int> unsel_pos; for (int i=0; i<item_cnt; ++i) { if (sel_pos_set.find(i) == sel_pos_set.end()) { unsel_pos.push_back(i); } } vector<wxString> orig(item_cnt); for (int i=0; i<item_cnt; i++) orig[i] = include_list->GetItemText(i, 1); UnselectAll(include_list); set<int> new_pos_set; BOOST_FOREACH(int i, sel_pos) { include_list->SetItem(i+1, 1, orig[i]); SelectItem(include_list, i+1); new_pos_set.insert(i+1); } int free_pos = 0; BOOST_FOREACH(int i, unsel_pos) { while (new_pos_set.find(free_pos) != new_pos_set.end()) ++free_pos; include_list->SetItem(free_pos, 1, orig[i]); ++free_pos; } UpdateButtons(); } void VarGroupingEditorDlg::sortColumn(int col, bool asc) { if (!all_init) return; list<wxString> all_str = GetListAllStrs(include_list, col); list<int> nm_locs; vector<wxString> sorted_nms; set<wxString> sel_nms; int loc=0; BOOST_FOREACH(const wxString& s, all_str) { if (!s.IsEmpty() && s != GdaConst::placeholder_str) { nm_locs.push_back(loc); sorted_nms.push_back(s); if (IsItemSel(include_list, loc)) { UnselectItem(include_list, loc); sel_nms.insert(s); } } ++loc; } asc = sort_asc; sort_asc = !sort_asc; if (asc) sort(sorted_nms.begin(), sorted_nms.end()); else sort(sorted_nms.begin(), sorted_nms.end(), greater<wxString>()); list<int>::iterator pos = nm_locs.begin(); BOOST_FOREACH(const wxString& s, sorted_nms) { include_list->SetItem(*pos, col, s); if (sel_nms.find(s) != sel_nms.end()) SelectItem(include_list, *pos); ++pos; } UpdateButtons(); } /** Sort items in place ignoring blanks and placeholders. Highlighting moves with items. */ void VarGroupingEditorDlg::OnSortClick( wxCommandEvent& event ) { wxLogMessage("In VarGroupingEditorDlg::OnSortClick"); if (!all_init) return; list<wxString> all_str = GetListAllStrs(include_list, 1); list<int> nm_locs; vector<wxString> sorted_nms; set<wxString> sel_nms; int loc=0; BOOST_FOREACH(const wxString& s, all_str) { if (!s.IsEmpty() && s != GdaConst::placeholder_str) { nm_locs.push_back(loc); sorted_nms.push_back(s); if (IsItemSel(include_list, loc)) { UnselectItem(include_list, loc); sel_nms.insert(s); } } ++loc; } sort(sorted_nms.begin(), sorted_nms.end()); list<int>::iterator pos = nm_locs.begin(); BOOST_FOREACH(const wxString& s, sorted_nms) { include_list->SetItem(*pos, 1, s); if (sel_nms.find(s) != sel_nms.end()) SelectItem(include_list, *pos); ++pos; } UpdateButtons(); } // NOTE: this "placeholder" button is changed to "Edit" button void VarGroupingEditorDlg::OnPlaceholderClick( wxCommandEvent& event ) { wxPoint pt = GetPosition(); std::list<FramesManagerObserver*> observers(frames_manager->getCopyObservers()); std::list<FramesManagerObserver*>::iterator it; for (it=observers.begin(); it != observers.end(); ++it) { if (TimeEditorDlg* w = dynamic_cast<TimeEditorDlg*>(*it)) { w->Show(true); w->Maximize(false); w->Raise(); w->SetPosition(wxPoint(pt.x + 50, pt.y + 30)); return; } } TimeEditorDlg* dlg = new TimeEditorDlg(0,frames_manager, table_state, table_int); dlg->Show(true); dlg->SetPosition(wxPoint(pt.x + 50, pt.y + 30)); } void VarGroupingEditorDlg::OnUngroupedListItemActivate( wxListEvent& event ) { wxCommandEvent ce; OnAddToListClick(ce); } void VarGroupingEditorDlg::OnAddToListClick( wxCommandEvent& event ) { wxLogMessage("In VarGroupingEditorDlg::OnAddToListClick"); if (!all_init) return; int sel_cnt = ungrouped_list->GetSelectedItemCount(); if (sel_cnt == 0) return; list<wxString> typs = GetListSelStrs(ungrouped_list, 1); set<wxString> pool; BOOST_FOREACH(const wxString& s, typs) pool.insert(s); if (pool.size() != 1) return; if (!common_empty && common_type != typs.front()) return; int cur_tm_steps = table_int->GetTimeSteps(); if (cur_tm_steps > 1) { int empty_spots = cur_tm_steps - GetIncListNonPlaceholderCnt(); //if (sel_cnt > empty_spots) return; } // At this point, we know for sure operation is legal common_empty = false; common_type = typs.front(); UpdateCommonType(); // attempt to add after last selected item, but if that won't // fit, then add into empty spots from the beginning. If // placeholders must be overwritten, then do so as well. bool overwrite_plhdr = false; int room_with_plhdr = -1; if (cur_tm_steps > 1) { room_with_plhdr = cur_tm_steps - GetIncListNameCnt(); if (room_with_plhdr < sel_cnt) overwrite_plhdr = true; } list<int> inc_list_sel = GetListSel(include_list); int last_inc_list_sel = 0; if (inc_list_sel.size() > 0) last_inc_list_sel = inc_list_sel.back(); bool fill_from_top = false; if (cur_tm_steps == 1) { fill_from_top = true; overwrite_plhdr = true; } else if (cur_tm_steps - last_inc_list_sel < sel_cnt) { fill_from_top = true; } // add time periods as needed int item_cnt = include_list->GetItemCount(); int room = item_cnt - GetIncListNonPlaceholderCnt(); if (sel_cnt > room) { int diff = sel_cnt - room; for (int i=0; i<diff; ++i) { wxString t; if (item_cnt+i == 0) { t = table_int->GetTimeString(0); if (t.IsEmpty()) t = "time 0"; } else { t = GenerateTimeLabel(); table_int->InsertTimeStep(item_cnt+i, t); } include_list->InsertItem(item_cnt+i, t); include_list->SetItem(item_cnt+i, 1, wxEmptyString); } } list<wxString> ung_sel_strs = GetListSelStrs(ungrouped_list, 0); int insert_pos = 0; if (!fill_from_top) insert_pos = last_inc_list_sel; BOOST_FOREACH(const wxString& s, ung_sel_strs) { while (!((overwrite_plhdr && (include_list->GetItemText(insert_pos, 1) == GdaConst::placeholder_str)) || include_list->GetItemText(insert_pos, 1).IsEmpty())) { ++insert_pos; } include_list->SetItem(insert_pos, 1, s); ++insert_pos; } // Remove added items from ungrouped_list set<wxString> add_nms; BOOST_FOREACH(const wxString& s, ung_sel_strs) add_nms.insert(s); list<wxString> inc_nms; inc_nms = GetListAllStrs(include_list, 1); BOOST_FOREACH(const wxString& s, inc_nms) add_nms.insert(s); InitUngroupedList(add_nms); int inc_list_cnt = GetIncListNameCnt(); UpdateTimeStepsTxt(); if (new_group_name_txt_ctrl->GetValue().IsEmpty() && inc_list_cnt > 1) { vector<wxString> names(inc_list_cnt); for (int i=0; i<inc_list_cnt; ++i) { names[i] = include_list->GetItemText(i, 1); } wxString grp_nm = table_int->SuggestGroupName(names); new_group_name_txt_ctrl->SetValue(grp_nm); } UpdateButtons(); } void VarGroupingEditorDlg::OnIncludePopupClick(wxCommandEvent &evt) { wxLogMessage("In VarGroupingEditorDlg::OnIncludePopupClick"); int menu_id = evt.GetId(); if (menu_id == XRCID("INCLUDE_ADD_TIME")) { includeListAddNewTime(); } else if (menu_id == XRCID("INCLUDE_DELETE_TIME")) { includeListDeleteTime(); } evt.Skip(); } void VarGroupingEditorDlg::OnIncludeListItemActivate( wxListEvent& event ) { wxLogMessage("In VarGroupingEditorDlg::OnIncludeListItemActivate"); //wxCommandEvent ce; //OnPlaceholderClick(ce); wxListItem item = event.GetItem(); include_list->EditLabel(item.GetId()); } wxString VarGroupingEditorDlg::GetNewAppendTimeLabel() { wxString s = GenerateTimeLabel(); return s; } wxString VarGroupingEditorDlg::GenerateTimeLabel() { wxString s; for (int i=0; i<10000; i++) { s = "time "; s << i; if (include_list->FindItem(-1, s) == wxNOT_FOUND) return s; } return s; } void VarGroupingEditorDlg::includeListAddNewTime() { int time_step = include_list->GetItemCount(); wxString lbl = GetNewAppendTimeLabel(); // sync TableState table_int->InsertTimeStep(time_step, lbl); include_list->InsertItem(time_step, lbl); include_list->SetItem(time_step, 1, wxEmptyString); UpdateTimeStepsTxt(); } void VarGroupingEditorDlg::includeListDeleteTime() { std::list<int> sels = GetListSel(include_list); sels.sort(); sels.reverse(); if (!sels.empty()) { BOOST_FOREACH(int i, sels) { include_list->DeleteItem(i); if (table_int->GetTimeSteps()>1) table_int->RemoveTimeStep(i); } } list<wxString> inc_strs = GetListAllStrs(include_list, 1); set<wxString> excl; BOOST_FOREACH(const wxString& s, inc_strs) if (s!="") excl.insert(s); InitUngroupedList(excl); UpdateTimeStepsTxt(); } void VarGroupingEditorDlg::OnIncludeListDblClicked( wxMouseEvent& event) { list<int> inc_sel_pos = GetListSel(include_list); BOOST_FOREACH(int i, inc_sel_pos) { include_list->EditLabel(i); break; } } void VarGroupingEditorDlg::OnIncludeListRightDown( wxMouseEvent& event) { } void VarGroupingEditorDlg::OnIncludeListRightUp( wxMouseEvent& event) { wxLogMessage("In VarGroupingEditorDlg::OnIncludeListRightUp"); if (!is_editing) { wxMenu mnu; int id1 = XRCID("INCLUDE_ADD_TIME"); mnu.Append(id1, _("Add Time")); mnu.Append(XRCID("INCLUDE_DELETE_TIME"), _("Remove Time")); mnu.Connect(wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(VarGroupingEditorDlg::OnIncludePopupClick), NULL, this); if (GetListSel(include_list).size() == 0) { mnu.Enable(XRCID("INCLUDE_DELETE_TIME"), false); } PopupMenu(&mnu); } event.Skip(); } void VarGroupingEditorDlg::OnRemoveFrListClick( wxCommandEvent& event ) { wxLogMessage("In VarGroupingEditorDlg::OnRemoveFrListClick"); if (!all_init) return; list<int> inc_sel_pos = GetListSel(include_list); BOOST_FOREACH(int i, inc_sel_pos) { include_list->SetItem(i, 1, ""); include_list->SetItemState(i, 1, wxLIST_STATE_SELECTED); } if (table_int->GetTimeSteps() == 1) { // remove any unused time periods at the end int inc_cnt = include_list->GetItemCount(); bool done = false; for (int i=inc_cnt-1; i>=0 && !done; --i) { if (!include_list->GetItemText(i, 1).IsEmpty()) { done = true; } else { include_list->DeleteItem(i); } } } list<wxString> inc_strs = GetListAllStrs(include_list, 1); set<wxString> excl; BOOST_FOREACH(const wxString& s, inc_strs) if (s!="") excl.insert(s); InitUngroupedList(excl); UpdateTimeStepsTxt(); if (GetIncListNonPlaceholderCnt() == 0) { common_empty = true; UpdateCommonType(); } UpdateButtons(); } void VarGroupingEditorDlg::OnUngroupedListSelection( wxListEvent& event ) { wxLogMessage("In VarGroupingEditorDlg::OnUngroupedListSelection"); if (!all_init) return; long item = -1; item = ungrouped_list->GetNextItem(item, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED); pos_ungrouped_list = item > -1 ? item : 0; UpdateButtons(); } void VarGroupingEditorDlg::OnIncludeListSelection( wxListEvent& event ) { wxLogMessage("In VarGroupingEditorDlg::OnIncludeListSelection"); if (!all_init) return; UpdateButtons(); } void VarGroupingEditorDlg::OnIncludeListColClick( wxListEvent& event ) { wxLogMessage("In VarGroupingEditorDlg::OnIncludeListColClick"); long col = event.GetColumn(); if (col > -1) sortColumn(col); } void VarGroupingEditorDlg::OnIncludeListEdit( wxListEvent& event ) { wxLogMessage("In VarGroupingEditorDlg::OnIncludeListEdit"); wxListItem item = event.GetItem(); wxString val = item.GetText(); is_editing = true; } void VarGroupingEditorDlg::OnIncludeListEditEnd( wxListEvent& event ) { wxLogMessage("In VarGroupingEditorDlg::OnIncludeListEditEnd"); is_editing = false; if (event.IsEditCancelled()) return; int id = event.GetItem().GetId(); wxString item_new = event.GetLabel(); item_new.Trim(true); item_new.Trim(false); // ensure that new time label is unique and not empty bool is_dup = false; for (int t=0, tms=table_int->GetTimeSteps(); t<tms && !is_dup; ++t) { if (t != id && table_int->GetTimeString(t) == item_new) is_dup = true; } bool is_disallow = table_state->GetNumDisallowTimelineChanges() > 0; if (item_new.IsEmpty() || is_dup || is_disallow) { if (is_disallow && !(item_new.IsEmpty() || is_dup)) { wxString msg = table_state->GetDisallowTimelineChangesMsg(); wxMessageDialog dlg(this, msg, "Warning", wxOK | wxICON_INFORMATION); dlg.ShowModal(); } event.Veto(); return; } // item_new is valid, proceed with rename table_int->RenameTimeStep(id, item_new); } void VarGroupingEditorDlg::OnGroupedListSelection( wxCommandEvent& event ) { wxLogMessage("In VarGroupingEditorDlg::OnGroupedListSelection"); if (!all_init) return; UpdateButtons(); } void VarGroupingEditorDlg::OnNewGroupNameChange( wxCommandEvent& event ) { wxLogMessage("In VarGroupingEditorDlg::OnNewGroupNameChange"); if (!all_init) return; UpdateGroupButton(); } void VarGroupingEditorDlg::UpdateGroupButton() { group_button->Enable(!new_group_name_txt_ctrl->GetValue().IsEmpty() && (GetIncListNameCnt() == table_int->GetTimeSteps() || table_int->GetTimeSteps() == 1) ); } void VarGroupingEditorDlg::UpdateAddToListButton() { // Enable add to list button when following conditions are met: // 1) Non-empty selection //int sel_cnt = ungrouped_list->GetSelectedItemCount(); int sel_cnt = GetListSel(ungrouped_list).size(); if (sel_cnt == 0) { add_to_list_button->Enable(false); return; } // 2) Currently selected items are type compatible with each other std::list<wxString> typs = GetListSelStrs(ungrouped_list, 1); std::set<wxString> pool; BOOST_FOREACH(const wxString& s, typs) pool.insert(s); if (pool.size() != 1) { add_to_list_button->Enable(false); return; } // 3) Currently selected items are type compatible with items in // include list currently if (!common_empty && common_type != typs.front()) { add_to_list_button->Enable(false); return; } // 4) Number of selected items is <= number of empty or placeholder items // but current number of time steps is > 1 /* int cur_tm_steps = table_int->GetTimeSteps(); if (cur_tm_steps > 1) { int empty_spots = cur_tm_steps - GetIncListNonPlaceholderCnt(); if (sel_cnt > empty_spots) { add_to_list_button->Enable(false); return; } } */ add_to_list_button->Enable(true); } void VarGroupingEditorDlg::UpdateButtons() { using namespace std; list<wxString> sel_strs = GetListSelStrs(include_list, 1); int non_empty_cnt = 0; BOOST_FOREACH(const wxString& s, sel_strs) if (s != "") ++non_empty_cnt; list<int> sel_pos = GetListSel(include_list); int sel_first = -1; int sel_last = -1; if (sel_pos.size() > 0) { sel_first = sel_pos.front(); sel_last = sel_pos.back(); } int cnt = GetIncListNameCnt(); int inc_item_cnt = include_list->GetItemCount(); int inc_sel_cnt = include_list->GetSelectedItemCount(); move_up_button->Enable(inc_sel_cnt > 0 && sel_first != 0); move_down_button->Enable(inc_sel_cnt > 0 && sel_last != inc_item_cnt-1); sort_button->Enable(cnt > 1); //placeholder_button->Enable((table_int->GetTimeSteps() == 1 && // inc_item_cnt > 0) || // (sel_strs.size()-non_empty_cnt > 0)); placeholder_button->Enable(true); placeholder_button->Hide(); sort_button->Hide(); UpdateAddToListButton(); remove_fr_list_button->Enable(non_empty_cnt > 0); ungroup_button->Enable(grouped_list->GetSelection() != wxNOT_FOUND); save_spacetime_button->Enable(grouped_list->GetCount() > 0); UpdateGroupButton(); } void VarGroupingEditorDlg::ResetAllButtons() { group_button->Disable(); ungroup_button->Disable(); move_up_button->Disable(); move_down_button->Disable(); sort_button->Disable(); placeholder_button->Disable(); add_to_list_button->Disable(); remove_fr_list_button->Disable(); save_spacetime_button->Disable(); } void VarGroupingEditorDlg::UpdateCommonType() { if (common_empty) { new_field_type_stat_txt->SetLabelText(""); } else if (common_type == "str") { new_field_type_stat_txt->SetLabelText("string"); } else if (common_type == "date") { new_field_type_stat_txt->SetLabelText("date"); } else if (common_type == "time") { new_field_type_stat_txt->SetLabelText("time"); } else if (common_type == "datetime") { new_field_type_stat_txt->SetLabelText("datetime"); } else if (common_type == "num") { new_field_type_stat_txt->SetLabelText("numeric"); } } void VarGroupingEditorDlg::UpdateTimeStepsTxt() { wxString s; int cur_tm_steps = table_int->GetTimeSteps(); if (cur_tm_steps > 1) { s << GetIncListNameCnt() << " of " << cur_tm_steps; } else { s << GetIncListNameCnt(); } s << " variables to include"; include_list_stat_txt->SetLabelText(s); //wxSizer* szr = include_list_stat_txt->GetContainingSizer(); //if (szr) szr->Layout(); //Fit(); Refresh(); } void VarGroupingEditorDlg::OnUngroupedVarsHelp( wxCommandEvent& event ) { wxString msg; msg << _("List of existing ungrouped variables. To group variables by time, move them to the list on the right.\n\nFor example, to group Pop80 and Pop90, select them on the left and move them to the right."); wxMessageDialog dlg (this, msg, "Help", wxOK | wxICON_INFORMATION ); dlg.ShowModal(); } void VarGroupingEditorDlg::OnNewGroupHelp( wxCommandEvent& event ) { wxString msg; msg << _("Add a name for your group of variables. \n\nYou can edit the time period labels for easier interpretation of results."); wxMessageDialog dlg (this, msg, "Help", wxOK | wxICON_INFORMATION ); dlg.ShowModal(); } void VarGroupingEditorDlg::OnSaveSTHelp( wxCommandEvent& event ) { wxString msg; msg << _("Once you have grouped variables, you can save a new space-time table and weights: To add a spatial ID to your space-time table and create space-time weights, you need to have an active weights file (Tools-Weights Manager)."); wxMessageDialog dlg (this, msg, "Help", wxOK | wxICON_INFORMATION ); dlg.ShowModal(); } void VarGroupingEditorDlg::OnCurGroupedHelp( wxCommandEvent& event ) { wxString msg; msg << _("This is the list of existing grouped variables. As new groups are created, they will appear on this list. You can open an existing .gda file and edit it here."); wxMessageDialog dlg (this, msg, "Help", wxOK | wxICON_INFORMATION ); dlg.ShowModal(); } void VarGroupingEditorDlg::OnLoadFromGda( wxCommandEvent& event ) { wxString wildcard = "GeoDa Project (*.gda)|*.gda"; wxFileDialog dlg(this, _("GeoDa Project File to Open"), "", "", wildcard); if (dlg.ShowModal() != wxID_OK) return; wxString full_proj_path = dlg.GetPath(); try { ProjectConfiguration* project_conf = new ProjectConfiguration(full_proj_path); project->UpdateProjectConf(project_conf); } catch( GdaException& ex) { wxMessageDialog dlg (this, ex.what(), "Error", wxOK | wxICON_ERROR ); dlg.ShowModal(); } } void VarGroupingEditorDlg::update(FramesManager* o) { } void VarGroupingEditorDlg::update(TableState* o) { TableState::EventType ev_type = o->GetEventType(); if (ev_type == TableState::refresh || ev_type == TableState::col_rename) { common_empty = true; InitAll(); ResetAllButtons(); UpdateCommonType(); } } std::list<int> VarGroupingEditorDlg::GetListSel(wxListCtrl* lc) { std::list<int> l; if (!lc) return l; long item = -1; for ( ;; ) { item = lc->GetNextItem(item, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED); if ( item == -1 ) break; l.push_back(item); } return l; } std::list<wxString> VarGroupingEditorDlg::GetListSelStrs(wxListCtrl* lc, int col) { std::list<wxString> l; if (!lc) return l; long item = -1; for ( ;; ) { item = lc->GetNextItem(item, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED); if ( item == -1 ) break; l.push_back(lc->GetItemText(item, col)); } return l; } std::list<wxString> VarGroupingEditorDlg::GetListAllStrs(wxListCtrl* lc, int col) { std::list<wxString> l; if (!lc) return l; long item = -1; for ( ;; ) { item = lc->GetNextItem(item, wxLIST_NEXT_ALL, wxLIST_STATE_DONTCARE); if ( item == -1 ) break; l.push_back(lc->GetItemText(item, col)); } return l; } void VarGroupingEditorDlg::UnselectAll(wxListCtrl* lc) { if (!lc) return; int cnt = lc->GetItemCount(); for (int i=0; i<cnt; ++i) { lc->SetItemState(i, 0, wxLIST_STATE_SELECTED); } } void VarGroupingEditorDlg::SelectItem(wxListCtrl* lc, int i) { if (!lc || i<0 || i>=lc->GetItemCount()) return; lc->SetItemState(i, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED); } void VarGroupingEditorDlg::UnselectItem(wxListCtrl* lc, int i) { if (!lc || i<0 || i>=lc->GetItemCount()) return; lc->SetItemState(i, 0, wxLIST_STATE_SELECTED); } bool VarGroupingEditorDlg::IsItemSel(wxListCtrl* lc, int i) { if (!lc || i<0 || i>=lc->GetItemCount()) return false; return lc->GetItemState(i, wxLIST_STATE_SELECTED) != 0; } int VarGroupingEditorDlg::GetIncListNameCnt() { if (!all_init || !include_list) return 0; int nm_cnt = 0; for (int i=0, il_sz=include_list->GetItemCount(); i<il_sz; ++i) { if (!include_list->GetItemText(i, 1).IsEmpty()) ++nm_cnt; } return nm_cnt; } int VarGroupingEditorDlg::GetIncListNonPlaceholderCnt() { if (!all_init || !include_list) return 0; int nm_cnt = 0; for (int i=0, il_sz=include_list->GetItemCount(); i<il_sz; ++i) { if (!include_list->GetItemText(i, 1).IsEmpty() && include_list->GetItemText(i, 1) != GdaConst::placeholder_str ) { ++nm_cnt; } } return nm_cnt; }
30.867911
236
0.670318
[ "vector" ]
026de3c8a098904b4f9d74ae042ad90210ede168
37,125
cpp
C++
Tram.Engine/VulkanRenderer.cpp
eduardojonssen/Tram
82eb517ed63b72dde4395fd766e524e280147c6b
[ "MIT" ]
null
null
null
Tram.Engine/VulkanRenderer.cpp
eduardojonssen/Tram
82eb517ed63b72dde4395fd766e524e280147c6b
[ "MIT" ]
null
null
null
Tram.Engine/VulkanRenderer.cpp
eduardojonssen/Tram
82eb517ed63b72dde4395fd766e524e280147c6b
[ "MIT" ]
null
null
null
#include "VulkanRenderer.h" #include <iostream> #include <exception> #include <string> #include <set> #include <array> #include "FileStream.h" #include "glm/glm.hpp" struct Vertex { glm::vec2 pos; glm::vec3 color; static VkVertexInputBindingDescription GetBindingDescription() { VkVertexInputBindingDescription bindingDescription{}; bindingDescription.binding = 0; bindingDescription.stride = sizeof(Vertex); bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; return bindingDescription; } static std::array<VkVertexInputAttributeDescription, 2> GetAttributeDescriptions() { std::array<VkVertexInputAttributeDescription, 2> attributeDescriptions{}; attributeDescriptions[0].binding = 0; attributeDescriptions[0].location = 0; attributeDescriptions[0].format = VK_FORMAT_R32G32_SFLOAT; attributeDescriptions[0].offset = offsetof(Vertex, pos); attributeDescriptions[1].binding = 0; attributeDescriptions[1].location = 1; attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT; attributeDescriptions[1].offset = offsetof(Vertex, color); return attributeDescriptions; } }; const std::vector<Vertex> vertices = { {{-0.5f, -0.5f}, {1.0f, 0.0f, 0.0f}}, {{0.5f, -0.5f}, {0.0f, 1.0f, 0.0f}}, {{0.5f, 0.5f}, {0.0f, 0.0f, 1.0f}}, {{-0.5f, 0.5f}, {1.0f, 1.0f, 1.0f}} }; const std::vector<uint16_t> indices = { 0, 1, 2, 2, 3, 0 }; const int MAX_FRAMES_IN_FLIGHT = 2; VulkanRenderer::VulkanRenderer() { } void VulkanRenderer::Init(GLFWwindow* window) { this->window = window; this->CreateInstance(); if (enableValidationLayers == true) { this->debugger = new DebugMessenger; this->debugger->SetupDebugMessenger(instance, enableValidationLayers); } this->CreateSurface(); this->PickPhysicalDevice(); this->CreateLogicalDevice(); this->CreateSwapChain(); this->CreateImageViews(); this->CreateRenderPass(); this->CreateGraphicsPipeline(); this->CrateFramebuffers(); this->CreateCommandPool(); this->CreateVertexBuffer(); this->CreateIndexBuffer(); this->CreateCommandBuffers(); this->CreateSyncObjects(); } void VulkanRenderer::Draw() { vkWaitForFences(this->device, 1, &this->inFlightFences[this->currentFrame], VK_TRUE, UINT64_MAX); uint32_t imageIndex; VkResult result = vkAcquireNextImageKHR(this->device, this->swapChain, UINT64_MAX, this->imageAvailableSemaphores[this->currentFrame], VK_NULL_HANDLE, &imageIndex); if (result == VK_ERROR_OUT_OF_DATE_KHR) { this->RecreateSwapChain(); return; } else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) { throw std::runtime_error("Failed to acquire swap chain image."); } if (this->imagesInFlight[imageIndex] != VK_NULL_HANDLE) { vkWaitForFences(this->device, 1, &this->imagesInFlight[imageIndex], VK_TRUE, UINT64_MAX); } this->imagesInFlight[imageIndex] = this->inFlightFences[this->currentFrame]; VkSubmitInfo submitInfo{}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; VkSemaphore waitSemaphores[] = { this->imageAvailableSemaphores[this->currentFrame] }; VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT }; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = waitSemaphores; submitInfo.pWaitDstStageMask = waitStages; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffers[imageIndex]; VkSemaphore signalSemaphores[] = { this->renderFinishedSemaphores[this->currentFrame] }; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = signalSemaphores; vkResetFences(this->device, 1, &this->inFlightFences[this->currentFrame]); if (vkQueueSubmit(this->graphicsQueue, 1, &submitInfo, this->inFlightFences[this->currentFrame]) != VK_SUCCESS) { throw std::runtime_error("Failed to submit draw command buffer."); } VkPresentInfoKHR presentInfo{}; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; presentInfo.waitSemaphoreCount = 1; presentInfo.pWaitSemaphores = signalSemaphores; VkSwapchainKHR swapChains[] = { this->swapChain }; presentInfo.swapchainCount = 1; presentInfo.pSwapchains = swapChains; presentInfo.pImageIndices = &imageIndex; presentInfo.pResults = nullptr; result = vkQueuePresentKHR(presentQueue, &presentInfo); if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || framebufferResized) { framebufferResized = false; this->RecreateSwapChain(); } else if (result != VK_SUCCESS) { throw std::runtime_error("Failed to present swap chain image."); } this->currentFrame = (this->currentFrame + 1) % MAX_FRAMES_IN_FLIGHT; } void VulkanRenderer::Destroy() { this->CleanupSwapChain(); vkDestroyBuffer(this->device, this->indexBuffer, nullptr); vkFreeMemory(this->device, this->indexBufferMemory, nullptr); vkDestroyBuffer(this->device, this->vertexBuffer, nullptr); vkFreeMemory(this->device, this->vertexBufferMemory, nullptr); for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { vkDestroySemaphore(this->device, this->renderFinishedSemaphores[i], nullptr); vkDestroySemaphore(this->device, this->imageAvailableSemaphores[i], nullptr); vkDestroyFence(this->device, this->inFlightFences[i], nullptr); } vkDestroyCommandPool(this->device, this->commandPool, nullptr); vkDestroyDevice(this->device, nullptr); if (this->debugger != nullptr) { this->debugger->Destroy(); delete this->debugger; } vkDestroySurfaceKHR(instance, surface, nullptr); vkDestroyInstance(instance, NULL); } void VulkanRenderer::CleanupSwapChain() { vkDeviceWaitIdle(this->device); for (auto framebuffer : this->swapChainFramebuffers) { vkDestroyFramebuffer(this->device, framebuffer, nullptr); } vkFreeCommandBuffers(this->device, this->commandPool, static_cast<uint32_t>(this->commandBuffers.size()), this->commandBuffers.data()); vkDestroyPipeline(this->device, this->graphicsPipeline, nullptr); vkDestroyPipelineLayout(this->device, this->pipelineLayout, nullptr); vkDestroyRenderPass(device, renderPass, nullptr); for (auto imageView : this->swapChainImageViews) { vkDestroyImageView(this->device, imageView, nullptr); } vkDestroySwapchainKHR(this->device, this->swapChain, nullptr); } void VulkanRenderer::RecreateSwapChain() { int width = 0, height = 0; glfwGetFramebufferSize(this->window, &width, &height); while (width == 0 || height == 0) { glfwGetFramebufferSize(this->window, &width, &height); glfwWaitEvents(); } this->CleanupSwapChain(); this->CreateSwapChain(); this->CreateImageViews(); this->CreateRenderPass(); this->CreateGraphicsPipeline(); this->CrateFramebuffers(); this->CreateCommandBuffers(); } void VulkanRenderer::CreateSyncObjects() { this->imageAvailableSemaphores.resize(MAX_FRAMES_IN_FLIGHT); this->renderFinishedSemaphores.resize(MAX_FRAMES_IN_FLIGHT); this->inFlightFences.resize(MAX_FRAMES_IN_FLIGHT); this->imagesInFlight.resize(this->swapChainImages.size(), VK_NULL_HANDLE); VkSemaphoreCreateInfo semaphoreInfo{}; semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; VkFenceCreateInfo fenceInfo{}; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { if (vkCreateSemaphore(this->device, &semaphoreInfo, nullptr, &this->imageAvailableSemaphores[i]) != VK_SUCCESS || vkCreateSemaphore(this->device, &semaphoreInfo, nullptr, &this->renderFinishedSemaphores[i]) != VK_SUCCESS || vkCreateFence(this->device, &fenceInfo, nullptr, &this->inFlightFences[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create synchronization objects."); } } } void VulkanRenderer::CreateCommandBuffers() { this->commandBuffers.resize(this->swapChainFramebuffers.size()); VkCommandBufferAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.commandPool = this->commandPool; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandBufferCount = (uint32_t)this->commandBuffers.size(); if (vkAllocateCommandBuffers(this->device, &allocInfo, this->commandBuffers.data()) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate command buffers."); } for (size_t i = 0; i < this->commandBuffers.size(); i++) { VkCommandBufferBeginInfo beginInfo{}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = 0; beginInfo.pInheritanceInfo = nullptr; if (vkBeginCommandBuffer(this->commandBuffers[i], &beginInfo) != VK_SUCCESS) { throw std::runtime_error("Failed to begin recording command buffer."); } VkRenderPassBeginInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassInfo.renderPass = this->renderPass; renderPassInfo.framebuffer = this->swapChainFramebuffers[i]; renderPassInfo.renderArea.offset = { 0, 0 }; renderPassInfo.renderArea.extent = this->swapChainExtent; VkClearValue clearColor = {0.0f, 0.0f, 0.0f, 1.0f}; renderPassInfo.clearValueCount = 1; renderPassInfo.pClearValues = &clearColor; vkCmdBeginRenderPass(this->commandBuffers[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindPipeline(this->commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, this->graphicsPipeline); VkBuffer vertexBuffers[] = { this->vertexBuffer }; VkDeviceSize offsets[] = { 0 }; vkCmdBindVertexBuffers(this->commandBuffers[i], 0, 1, vertexBuffers, offsets); vkCmdBindIndexBuffer(this->commandBuffers[i], this->indexBuffer, 0, VK_INDEX_TYPE_UINT16); vkCmdDrawIndexed(this->commandBuffers[i], static_cast<uint32_t>(indices.size()), 1, 0, 0, 0); vkCmdEndRenderPass(this->commandBuffers[i]); if (vkEndCommandBuffer(this->commandBuffers[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to record command buffer."); } } } void VulkanRenderer::CreateVertexBuffer() { VkDeviceSize bufferSize = sizeof(vertices[0]) * vertices.size(); VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; this->CreateBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); void* data; vkMapMemory(this->device, stagingBufferMemory, 0, bufferSize, 0, &data); memcpy(data, vertices.data(), (size_t)bufferSize); vkUnmapMemory(this->device, stagingBufferMemory); this->CreateBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, this->vertexBuffer, this->vertexBufferMemory); this->CopyBuffer(stagingBuffer, this->vertexBuffer, bufferSize); vkDestroyBuffer(this->device, stagingBuffer, nullptr); vkFreeMemory(this->device, stagingBufferMemory, nullptr); } void VulkanRenderer::CreateBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory) { VkBufferCreateInfo bufferInfo{}; bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferInfo.size = size; bufferInfo.usage = usage; bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; if (vkCreateBuffer(this->device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS) { throw std::runtime_error("Failed to create vertex buffer."); } VkMemoryRequirements memRequirements; vkGetBufferMemoryRequirements(this->device, buffer, &memRequirements); VkMemoryAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = memRequirements.size; allocInfo.memoryTypeIndex = this->FindMemoryType(memRequirements.memoryTypeBits, properties); if (vkAllocateMemory(this->device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate vertex buffer memory."); } vkBindBufferMemory(this->device, buffer, bufferMemory, 0); } void VulkanRenderer::CopyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size) { VkCommandBufferAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandPool = this->commandPool; allocInfo.commandBufferCount = 1; VkCommandBuffer commandBuffer; vkAllocateCommandBuffers(this->device, &allocInfo, &commandBuffer); VkCommandBufferBeginInfo beginInfo{}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; vkBeginCommandBuffer(commandBuffer, &beginInfo); VkBufferCopy copyRegion{}; copyRegion.srcOffset = 0; copyRegion.dstOffset = 0; copyRegion.size = size; vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, &copyRegion); vkEndCommandBuffer(commandBuffer); VkSubmitInfo submitInfo{}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; vkQueueSubmit(this->graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE); vkQueueWaitIdle(this->graphicsQueue); vkFreeCommandBuffers(this->device, this->commandPool, 1, &commandBuffer); } void VulkanRenderer::CreateIndexBuffer() { VkDeviceSize bufferSize = sizeof(indices[0]) * indices.size(); VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; this->CreateBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); void* data; vkMapMemory(this->device, stagingBufferMemory, 0, bufferSize, 0, &data); memcpy(data, indices.data(), (size_t)bufferSize); vkUnmapMemory(this->device, stagingBufferMemory); this->CreateBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, this->indexBuffer, this->indexBufferMemory); this->CopyBuffer(stagingBuffer, this->indexBuffer, bufferSize); vkDestroyBuffer(this->device, stagingBuffer, nullptr); vkFreeMemory(this->device, stagingBufferMemory, nullptr); } uint32_t VulkanRenderer::FindMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties) { VkPhysicalDeviceMemoryProperties memProperties; vkGetPhysicalDeviceMemoryProperties(this->physicalDevice, &memProperties); for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) { if (typeFilter & (1 << i) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties) { return i; } } throw std::runtime_error("Failed to find suitable memory type."); } void VulkanRenderer::CreateCommandPool() { QueueFamilyIndices queueFamilyIndices = this->FindQueueFamilies(this->physicalDevice); VkCommandPoolCreateInfo poolInfo{}; poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value(); poolInfo.flags = 0; if (vkCreateCommandPool(this->device, &poolInfo, nullptr, &this->commandPool) != VK_SUCCESS) { throw std::runtime_error("Failed to create command pool."); } } void VulkanRenderer::CrateFramebuffers() { this->swapChainFramebuffers.resize(this->swapChainImageViews.size()); for (size_t i = 0; i < this->swapChainImageViews.size(); i++) { VkImageView attachments[] = { this->swapChainImageViews[i] }; VkFramebufferCreateInfo framebufferInfo{}; framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferInfo.renderPass = renderPass; framebufferInfo.attachmentCount = 1; framebufferInfo.pAttachments = attachments; framebufferInfo.width = this->swapChainExtent.width; framebufferInfo.height = this->swapChainExtent.height; framebufferInfo.layers = 1; if (vkCreateFramebuffer(this->device, &framebufferInfo, nullptr, &swapChainFramebuffers[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create framebuffer."); } } } void VulkanRenderer::CreateRenderPass() { VkAttachmentDescription colorAttachment{}; colorAttachment.format = this->swapChainImageFormat; colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT; colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; VkAttachmentReference colorAttachmentRef{}; colorAttachmentRef.attachment = 0; colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkSubpassDescription subpass{}; subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass.colorAttachmentCount = 1; subpass.pColorAttachments = &colorAttachmentRef; VkSubpassDependency dependency{}; dependency.srcSubpass = VK_SUBPASS_EXTERNAL; dependency.dstSubpass = 0; dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.srcAccessMask = 0; dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; VkRenderPassCreateInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; renderPassInfo.attachmentCount = 1; renderPassInfo.pAttachments = &colorAttachment; renderPassInfo.subpassCount = 1; renderPassInfo.pSubpasses = &subpass; renderPassInfo.dependencyCount = 1; renderPassInfo.pDependencies = &dependency; if (vkCreateRenderPass(this->device, &renderPassInfo, nullptr, &this->renderPass) != VK_SUCCESS) { throw std::runtime_error("Failed to create render pass."); } } void VulkanRenderer::CreateGraphicsPipeline() { auto vertShaderCode = ReadFile("shaders/vert.spv"); auto fragShaderCode = ReadFile("shaders/frag.spv"); VkShaderModule vertShaderModule = this->CreateShaderModule(vertShaderCode); VkShaderModule fragShaderModule = this->CreateShaderModule(fragShaderCode); VkPipelineShaderStageCreateInfo vertShaderStageInfo{}; vertShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT; vertShaderStageInfo.module = vertShaderModule; vertShaderStageInfo.pName = "main"; VkPipelineShaderStageCreateInfo fragShaderStageInfo{}; fragShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT; fragShaderStageInfo.module = fragShaderModule; fragShaderStageInfo.pName = "main"; VkPipelineShaderStageCreateInfo shaderStages[] = { vertShaderStageInfo, fragShaderStageInfo }; VkPipelineVertexInputStateCreateInfo vertexInputInfo{}; vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; auto bindingDescription = Vertex::GetBindingDescription(); auto attributeDescriptions = Vertex::GetAttributeDescriptions(); vertexInputInfo.vertexBindingDescriptionCount = 1; vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size()); vertexInputInfo.pVertexBindingDescriptions = &bindingDescription; vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data(); VkPipelineInputAssemblyStateCreateInfo inputAssembly{}; inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; inputAssembly.primitiveRestartEnable = VK_FALSE; VkViewport viewport{}; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = (float)this->swapChainExtent.width; viewport.height = (float)this->swapChainExtent.height; viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor{}; scissor.offset = { 0,0 }; scissor.extent = swapChainExtent; VkPipelineViewportStateCreateInfo viewportState{}; viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewportState.viewportCount = 1; viewportState.pViewports = &viewport; viewportState.scissorCount = 1; viewportState.pScissors = &scissor; VkPipelineRasterizationStateCreateInfo rasterizer{}; rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rasterizer.depthClampEnable = VK_FALSE; rasterizer.rasterizerDiscardEnable = VK_FALSE; rasterizer.polygonMode = VK_POLYGON_MODE_FILL; rasterizer.lineWidth = 1.0f; rasterizer.cullMode = VK_CULL_MODE_BACK_BIT; rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE; rasterizer.depthBiasEnable = VK_FALSE; rasterizer.depthBiasConstantFactor = 0.0f; rasterizer.depthBiasClamp = 0.0f; rasterizer.depthBiasSlopeFactor = 0.0f; VkPipelineMultisampleStateCreateInfo multisampling{}; multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multisampling.sampleShadingEnable = VK_FALSE; multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; multisampling.minSampleShading = 1.0f; multisampling.pSampleMask = nullptr; multisampling.alphaToCoverageEnable = VK_FALSE; multisampling.alphaToOneEnable = VK_FALSE; VkPipelineColorBlendAttachmentState colorBlendAttachment{}; colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; colorBlendAttachment.blendEnable = VK_FALSE; colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; VkPipelineColorBlendStateCreateInfo colorBlending{}; colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; colorBlending.logicOpEnable = VK_FALSE; colorBlending.logicOp = VK_LOGIC_OP_COPY; colorBlending.attachmentCount = 1; colorBlending.pAttachments = &colorBlendAttachment; colorBlending.blendConstants[0] = 0.0f; colorBlending.blendConstants[1] = 0.0f; colorBlending.blendConstants[2] = 0.0f; colorBlending.blendConstants[3] = 0.0f; VkDynamicState dynamicStates[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_LINE_WIDTH }; VkPipelineDynamicStateCreateInfo dynamicState{}; dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; dynamicState.dynamicStateCount = 2; dynamicState.pDynamicStates = dynamicStates; VkPipelineLayoutCreateInfo pipelineLayoutInfo{}; pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipelineLayoutInfo.setLayoutCount = 0; pipelineLayoutInfo.pSetLayouts = nullptr; pipelineLayoutInfo.pushConstantRangeCount = 0; pipelineLayoutInfo.pPushConstantRanges = nullptr; if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &this->pipelineLayout) != VK_SUCCESS) { throw std::runtime_error("Failed to create pipeline layout."); } VkGraphicsPipelineCreateInfo pipelineInfo{}; pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipelineInfo.stageCount = 2; pipelineInfo.pStages = shaderStages; pipelineInfo.pVertexInputState = &vertexInputInfo; pipelineInfo.pInputAssemblyState = &inputAssembly; pipelineInfo.pViewportState = &viewportState; pipelineInfo.pRasterizationState = &rasterizer; pipelineInfo.pMultisampleState = &multisampling; pipelineInfo.pDepthStencilState = nullptr; pipelineInfo.pColorBlendState = &colorBlending; pipelineInfo.pDynamicState = nullptr; pipelineInfo.layout = pipelineLayout; pipelineInfo.renderPass = renderPass; pipelineInfo.subpass = 0; pipelineInfo.basePipelineHandle = VK_NULL_HANDLE; pipelineInfo.basePipelineIndex = -1; if (vkCreateGraphicsPipelines(this->device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &graphicsPipeline) != VK_SUCCESS) { throw std::runtime_error("Failed to create graphics pipeline."); } vkDestroyShaderModule(device, fragShaderModule, nullptr); vkDestroyShaderModule(device, vertShaderModule, nullptr); } VkShaderModule VulkanRenderer::CreateShaderModule(const std::vector<char>& code) { VkShaderModuleCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; createInfo.codeSize = code.size(); createInfo.pCode = reinterpret_cast<const uint32_t*>(code.data()); VkShaderModule shaderModule; if (vkCreateShaderModule(device, &createInfo, nullptr, &shaderModule) != VK_SUCCESS) { throw std::runtime_error("Failed to create shader module."); } return shaderModule; } void VulkanRenderer::CreateImageViews() { this->swapChainImageViews.resize(swapChainImages.size()); for (size_t i = 0; i < swapChainImages.size(); i++) { VkImageViewCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; createInfo.image = swapChainImages[i]; createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; createInfo.format = swapChainImageFormat; createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; createInfo.subresourceRange.baseMipLevel = 0; createInfo.subresourceRange.levelCount = 1; createInfo.subresourceRange.baseArrayLayer = 0; createInfo.subresourceRange.layerCount = 1; if (vkCreateImageView(device, &createInfo, nullptr, &this->swapChainImageViews[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create image views."); } } } void VulkanRenderer::CreateSwapChain() { SwapChainSupportDetails swapChainSupport = this->QuerySwapChainSupport(this->physicalDevice); VkSurfaceFormatKHR surfaceFormat = this->ChooseSwapSurfaceFormat(swapChainSupport.formats); VkPresentModeKHR presentMode = this->ChooseSwapPresentMode(swapChainSupport.presentModes); VkExtent2D extent = this->ChooseSwapExtent(swapChainSupport.capabilities); uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1; if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) { imageCount = swapChainSupport.capabilities.maxImageCount; } VkSwapchainCreateInfoKHR createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; createInfo.surface = surface; createInfo.minImageCount = imageCount; createInfo.imageFormat = surfaceFormat.format; createInfo.imageColorSpace = surfaceFormat.colorSpace; createInfo.imageExtent = extent; createInfo.imageArrayLayers = 1; createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; QueueFamilyIndices indices = this->FindQueueFamilies(this->physicalDevice); uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() }; if (indices.graphicsFamily != indices.presentFamily) { createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; createInfo.queueFamilyIndexCount = 2; createInfo.pQueueFamilyIndices = queueFamilyIndices; } else { createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; createInfo.queueFamilyIndexCount = 0; createInfo.pQueueFamilyIndices = nullptr; } createInfo.preTransform = swapChainSupport.capabilities.currentTransform; createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; createInfo.presentMode = presentMode; createInfo.clipped = VK_TRUE; createInfo.oldSwapchain = VK_NULL_HANDLE; if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &this->swapChain) != VK_SUCCESS) { throw std::runtime_error("Failed to create swapchain."); } this->swapChainImageFormat = surfaceFormat.format; this->swapChainExtent = extent; vkGetSwapchainImagesKHR(this->device, this->swapChain, &imageCount, nullptr); this->swapChainImages.resize(imageCount); vkGetSwapchainImagesKHR(this->device, this->swapChain, &imageCount, this->swapChainImages.data()); } VkSurfaceFormatKHR VulkanRenderer::ChooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats) { for (const auto& availableFormat : availableFormats) { if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { return availableFormat; } } return availableFormats[0]; } VkPresentModeKHR VulkanRenderer::ChooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes) { for (const auto& availablePresentMode : availablePresentModes) { if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) { return availablePresentMode; } } return VK_PRESENT_MODE_FIFO_KHR; } VkExtent2D VulkanRenderer::ChooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities) { if (capabilities.currentExtent.width != UINT32_MAX) { return capabilities.currentExtent; } else { int width, height; glfwGetFramebufferSize(this->window, &width, &height); VkExtent2D actualExtent = { static_cast<uint32_t>(width), static_cast<uint32_t>(height) }; actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width)); actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height)); return actualExtent; } } void VulkanRenderer::CreateLogicalDevice() { QueueFamilyIndices indices = this->FindQueueFamilies(this->physicalDevice); std::vector<VkDeviceQueueCreateInfo> queueCreateInfos; std::set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value() }; float queuePriority = 1.0f; for (uint32_t queueFamily : uniqueQueueFamilies) { VkDeviceQueueCreateInfo queueCreateInfo{}; queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueCreateInfo.queueFamilyIndex = indices.graphicsFamily.value(); queueCreateInfo.queueCount = 1; queueCreateInfo.pQueuePriorities = &queuePriority; queueCreateInfos.push_back(queueCreateInfo); } VkPhysicalDeviceFeatures deviceFeatures{ }; VkDeviceCreateInfo createInfo{ }; createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size()); createInfo.pQueueCreateInfos = queueCreateInfos.data(); createInfo.pEnabledFeatures = &deviceFeatures; createInfo.enabledExtensionCount = static_cast<uint32_t>(this->deviceExtensions.size()); createInfo.ppEnabledExtensionNames = this->deviceExtensions.data(); if (enableValidationLayers) { createInfo.enabledLayerCount = static_cast<uint32_t>(this->validationLayers.size()); createInfo.ppEnabledLayerNames = this->validationLayers.data(); } else { createInfo.enabledLayerCount = 0; } if (vkCreateDevice(this->physicalDevice, &createInfo, nullptr, &this->device) != VK_SUCCESS) { throw std::runtime_error("Failed to create logical device."); } vkGetDeviceQueue(this->device, indices.graphicsFamily.value(), 0, &this->graphicsQueue); vkGetDeviceQueue(this->device, indices.presentFamily.value(), 0, &this->presentQueue); } void VulkanRenderer::PickPhysicalDevice() { uint32_t deviceCount = 0; vkEnumeratePhysicalDevices(this->instance, &deviceCount, nullptr); if (deviceCount == 0) { throw std::runtime_error("No GPUs with Vulkan support available."); } std::vector<VkPhysicalDevice> devices(deviceCount); vkEnumeratePhysicalDevices(this->instance, &deviceCount, devices.data()); for (const auto& device : devices) { if (this->IsDeviceSuitable(device)) { this->physicalDevice = device; break; } } if (this->physicalDevice == VK_NULL_HANDLE) { throw std::runtime_error("Failed to find a suitable GPU."); } } bool VulkanRenderer::IsDeviceSuitable(VkPhysicalDevice device) { QueueFamilyIndices indices = this->FindQueueFamilies(device); bool extensionsSupported = this->CheckDeviceExtensionSupport(device); bool swapChainAdequate = false; if (extensionsSupported) { SwapChainSupportDetails swapChainSupport = this->QuerySwapChainSupport(device); swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty(); } return indices.isComplete() && extensionsSupported && swapChainAdequate; } QueueFamilyIndices VulkanRenderer::FindQueueFamilies(VkPhysicalDevice device) { QueueFamilyIndices indices; uint32_t queueFamilyCount = 0; vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr); std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data()); int i = 0; for (const auto& queueFamily : queueFamilies) { if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) { indices.graphicsFamily = i; } VkBool32 presentSupport = false; vkGetPhysicalDeviceSurfaceSupportKHR(device, i, this->surface, &presentSupport); if (presentSupport == VK_TRUE) { indices.presentFamily = i; } if (indices.isComplete()) { break; } i++; } return indices; } bool VulkanRenderer::CheckDeviceExtensionSupport(VkPhysicalDevice device) { uint32_t extensionCount; vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr); std::vector<VkExtensionProperties> availableExtensions(extensionCount); vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data()); std::set<std::string> requiredExtensions(this->deviceExtensions.begin(), this->deviceExtensions.end()); for (const auto& extension : availableExtensions) { requiredExtensions.erase(extension.extensionName); } return requiredExtensions.empty(); } SwapChainSupportDetails VulkanRenderer::QuerySwapChainSupport(VkPhysicalDevice device) { SwapChainSupportDetails details; vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, this->surface, &details.capabilities); uint32_t formatCount; vkGetPhysicalDeviceSurfaceFormatsKHR(device, this->surface, &formatCount, nullptr); if (formatCount != 0) { details.formats.resize(formatCount); vkGetPhysicalDeviceSurfaceFormatsKHR(device, this->surface, &formatCount, details.formats.data()); } uint32_t presentModeCount; vkGetPhysicalDeviceSurfacePresentModesKHR(device, this->surface, &presentModeCount, nullptr); if (presentModeCount != 0) { details.presentModes.resize(presentModeCount); vkGetPhysicalDeviceSurfacePresentModesKHR(device, this->surface, &presentModeCount, details.presentModes.data()); } return details; } void VulkanRenderer::CreateSurface() { if (glfwCreateWindowSurface(this->instance, this->window, nullptr, &this->surface) != VK_SUCCESS) { throw std::runtime_error("Failed to create window surface."); } } void VulkanRenderer::CreateInstance() { if (enableValidationLayers == true && this->CheckValidationLayerSupport() == false) { throw std::runtime_error("Requested validation layers not available."); } VkApplicationInfo appInfo = { }; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pApplicationName = "Tram"; appInfo.pEngineName = "Vulkan engine"; appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.apiVersion = VK_API_VERSION_1_2; VkInstanceCreateInfo createInfo = { }; createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; createInfo.pApplicationInfo = &appInfo; std::vector<const char*> extensions = this->GetRequiredExtensions(); createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size()); createInfo.ppEnabledExtensionNames = extensions.data(); VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo; if (enableValidationLayers == true) { createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size()); createInfo.ppEnabledLayerNames = validationLayers.data(); debugger->PopulateDebugMessengerCreateInfo(debugCreateInfo); createInfo.pNext = (VkDebugUtilsMessengerCreateInfoEXT*)&debugCreateInfo; } else { createInfo.enabledLayerCount = 0; createInfo.pNext = nullptr; } if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) { throw std::runtime_error("Failed to create instance."); } } bool VulkanRenderer::CheckValidationLayerSupport() { uint32_t layerCount = 0; vkEnumerateInstanceLayerProperties(&layerCount, nullptr); std::vector<VkLayerProperties> availableLayers(layerCount); vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data()); for (const char* layerName : validationLayers) { bool layerFound = false; for (const auto& layerProperties : availableLayers) { if (strcmp(layerName, layerProperties.layerName) == 0) { layerFound = true; break; } } if (layerFound == false) { std::cout << "Layer: " << layerName << " not found.\n" << std::endl; return false; } } return true; } std::vector<const char*> VulkanRenderer::GetRequiredExtensions() { uint32_t glfwExtensionCount = 0; const char** glfwExtensions; glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); std::vector<const char*> extensions(glfwExtensions, glfwExtensions + glfwExtensionCount); if (enableValidationLayers) { extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); } return extensions; } void VulkanRenderer::FramebufferResizeCallback(GLFWwindow* window, int width, int height) { auto renderer = reinterpret_cast<VulkanRenderer*>(glfwGetWindowUserPointer(window)); renderer->framebufferResized = true; }
37.199399
165
0.795609
[ "render", "vector" ]
026edaa2748cb3ea35c5302d003cb09a6d6ec9ef
2,576
cpp
C++
Segment Trees/12086.cpp
enricava/Competitive-Programming
ea39f5c74acc2202f3933f693f6d7f03f5435391
[ "MIT" ]
null
null
null
Segment Trees/12086.cpp
enricava/Competitive-Programming
ea39f5c74acc2202f3933f693f6d7f03f5435391
[ "MIT" ]
null
null
null
Segment Trees/12086.cpp
enricava/Competitive-Programming
ea39f5c74acc2202f3933f693f6d7f03f5435391
[ "MIT" ]
null
null
null
#include <iostream> #include <iomanip> #include <fstream> #include <algorithm> #include <vector> #include <utility> #include <queue> #include <sstream> using namespace std; int caso = 0; int v[200000]; class SegmentTree { vector<int> st; int tam; // Numero de hojas que manejamos public: // Tamano maximo que podremos guardar // (numero de hojas). // Antes de las consultas, se necesita rellenar // con los datos iniciales usando build(). SegmentTree(int maxN) { st.assign(4 * maxN + 10,0); } int query(int a, int b) { return query(1, 0, tam - 1, a, b); } int query(int vertex, int L, int R, int i, int j) { if (i > R || j < L) { return 0; } if (L >= i && R <= j) // Segmento completamente dentro de la consulta return st[vertex]; int mitad = (L + R) / 2; return query(2 * vertex, L, mitad, i, j) + query(2 * vertex + 1, mitad + 1, R, i, j); } void update(int pos, int newVal) { update(1, 0, tam - 1, pos, newVal); } void update(int vertex, int l, int r, int pos, int newVal) { if ((pos < l) || (r < pos)) return; if (l == r) { st[vertex] = newVal; return; } int m = (l + r) / 2; if ((l <= pos) && (pos <= m)) update(2 * vertex, l, m, pos, newVal); else update(2 * vertex + 1, m + 1, r, pos, newVal); st[vertex] = st[2 * vertex] + st[2 * vertex + 1]; } void build(int* values, int n) { tam = n; build(values, 1, 0, n - 1); } void build(int* values, int p, int l, int r) { if (l == r) { st[p] = values[l]; return; } int m = (l + r) / 2; build(values, 2 * p, l, m); build(values, 2 * p + 1, m + 1, r); st[p] = st[2 * p] + st[2 * p + 1]; } }; bool resuelveCaso() { caso++; int n; cin >> n; if (n == 0) return false; cout << "Case " << caso << ":\n"; SegmentTree s(n); for (int i = 0; i < n; ++i) { cin >> v[i]; } s.build(v, n); string action; int a, b; cin >> action; while (action != "END") { cin >> a >> b; //cout << action << ' ' << a << ' ' << b << '\n'; if (action == "S") { s.update(a-1, b); } else cout << s.query(a - 1, b - 1) << '\n'; cin >> action; } cout << '\n'; return true; } int main() { #ifndef DOMJUDGE std::ifstream in("datos.txt"); std::ofstream out("salida.txt"); auto cinbuf = std::cin.rdbuf(in.rdbuf()); auto coutbuf = std::cout.rdbuf(out.rdbuf()); #endif while (resuelveCaso()); #ifndef DOMJUDGE std::cin.rdbuf(cinbuf); std::cout.rdbuf(coutbuf); system("PAUSE"); #endif return 0; }
21.114754
53
0.526009
[ "vector" ]