hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
8866263f42cea726dfa486f18f253b776670aa6a
1,278
cpp
C++
daily_challenge/September_LeetCoding_Challenge_2021/minimizeDistanceToGasStation.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
1
2021-01-27T16:37:36.000Z
2021-01-27T16:37:36.000Z
daily_challenge/September_LeetCoding_Challenge_2021/minimizeDistanceToGasStation.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
null
null
null
daily_challenge/September_LeetCoding_Challenge_2021/minimizeDistanceToGasStation.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
null
null
null
/** * @author : archit * @GitHub : archit-1997 * @Email : architsingh456@gmail.com * @file : minimizeDistanceToGasStation.cpp * @created : Saturday Sep 18, 2021 02:17:22 IST */ #include <bits/stdc++.h> using namespace std; #define ll long long #define P pair<int,int> void init(){ freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); } class Solution { public: bool isPossible(vector<int> &nums,int k,double gap){ int count=0,n=nums.size(); for(int i=0;i<n-1;i++){ int val=(int)((nums[i+1]-nums[i])/gap); count+=val; } return count<=k; } double minmaxGasDist(vector<int>& stations, int k) { //we will use binary search to find the smallest possible value of distance int n=stations.size(); double l=0,r=stations[n-1]-stations[0]; //while the distance gap between the adjacent values is < 1e-6 double ans=INT_MAX; while(r-l>1e-6){ double m=l+(r-l)/2; //check if can have k stations with this gap if(isPossible(stations,k,m)){ ans=min(ans,m); r=m; } else l=m; } return ans; } };
23.666667
83
0.536776
archit-1997
88671c98ae280e3f980ab324078c10e768fd8152
304
cpp
C++
codeforces/codeforces_100_days/B/2.cpp
shivanshu-semwal/competitive-programming
b1c7fe1f9d5807fff47890267cc9936c9ff95f58
[ "MIT" ]
1
2021-09-24T03:57:42.000Z
2021-09-24T03:57:42.000Z
codeforces/codeforces_100_days/B/2.cpp
shivanshu-semwal/competitive-programming
b1c7fe1f9d5807fff47890267cc9936c9ff95f58
[ "MIT" ]
null
null
null
codeforces/codeforces_100_days/B/2.cpp
shivanshu-semwal/competitive-programming
b1c7fe1f9d5807fff47890267cc9936c9ff95f58
[ "MIT" ]
null
null
null
// https://codeforces.com/problemset/problem/734/B #include <iostream> using namespace std; int main() { long k2, k3, k5, k6; cin >> k2 >> k3 >> k5 >> k6; long min1 = std::min(k2, min(k5, k6)); long long int ans = min1 * 256 + min(k2 - min1, k3) * 32; cout << ans; return 0; }
20.266667
61
0.565789
shivanshu-semwal
886afed8d4178ac0a3781e164a789ffe6f917f2f
529
cpp
C++
clang/test/Analysis/unified-sources/source1.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,102
2015-01-04T02:28:35.000Z
2022-03-30T12:53:41.000Z
clang/test/Analysis/unified-sources/source1.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
clang/test/Analysis/unified-sources/source1.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
1,868
2015-01-03T04:27:11.000Z
2022-03-25T13:37:35.000Z
// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s // This test tests that the warning is here when it is included from // the unified sources file. The run-line in this file is there // only to suppress LIT warning for the complete lack of run-line. int foo(int x) { if (x) {} return 1 / x; // expected-warning{{}} } // Let's see if the container inlining heuristic still works. #include "container.h" int testContainerMethodInHeaderFile(ContainerInHeaderFile Cont) { return 1 / Cont.method(); // no-warning }
33.0625
68
0.725898
medismailben
886c4cd447dee614e0df4c02fbf260fdb26218e9
1,201
hpp
C++
include/caffe/util/parallel.hpp
whitenightwu/caffe-quant-TI
df1551f184d9d5e850650af0e7a68206d09cea2d
[ "MIT" ]
2
2019-06-06T13:15:46.000Z
2019-06-20T08:14:45.000Z
include/caffe/util/parallel.hpp
whitenightwu/caffe-quant-TI
df1551f184d9d5e850650af0e7a68206d09cea2d
[ "MIT" ]
null
null
null
include/caffe/util/parallel.hpp
whitenightwu/caffe-quant-TI
df1551f184d9d5e850650af0e7a68206d09cea2d
[ "MIT" ]
1
2020-03-24T02:04:59.000Z
2020-03-24T02:04:59.000Z
/** * TI C++ Reference software for Computer Vision Algorithms (TICV) * TICV is a software module developed to model computer vision * algorithms on TI's various platforms/SOCs. * * Copyright (C) 2016 Texas Instruments Incorporated - http://www.ti.com/ * ALL RIGHTS RESERVED */ /** * @file: parallel.h * @brief: Implements Parallel Thread Processing */ #pragma once #include <functional> namespace caffe { typedef std::function<void(int)> ParalelForExecutorFunc; class ParallelForFunctor: public cv::ParallelLoopBody { public: ParallelForFunctor(ParalelForExecutorFunc func) : execFunc(func) { } void operator()(const cv::Range &range) const { for (int i = range.start; i < range.end; i++) { execFunc(i); } } ParalelForExecutorFunc execFunc; }; static inline void ParallelFor(int start, int endPlus1, ParalelForExecutorFunc func, int nthreads = -1) { if (nthreads == 1) { for (int i = start; i < endPlus1; i++) { func(i); } } else { cv::Range range(start, endPlus1); ParallelForFunctor functor(func); cv::parallel_for_(range, functor, nthreads); } } }
24.510204
105
0.642798
whitenightwu
8872a557b0e6db1a52000ce44d6176f8cd4af1dd
3,055
hpp
C++
include/espadin/comments_group.hpp
mexicowilly/Espadin
f33580d2c77c5efe92c05de0816ec194e87906f0
[ "Apache-2.0" ]
null
null
null
include/espadin/comments_group.hpp
mexicowilly/Espadin
f33580d2c77c5efe92c05de0816ec194e87906f0
[ "Apache-2.0" ]
null
null
null
include/espadin/comments_group.hpp
mexicowilly/Espadin
f33580d2c77c5efe92c05de0816ec194e87906f0
[ "Apache-2.0" ]
null
null
null
#if !defined(ESPADIN_COMMENTS_GROUP_HPP_) #define ESPADIN_COMMENTS_GROUP_HPP_ #include <espadin/comment.hpp> #include <memory> namespace espadin { class ESPADIN_EXPORT comments_group { public: class create_interface { public: virtual ~create_interface() = default; virtual std::unique_ptr<comment> run() = 0; virtual create_interface& anchor(const std::string& str) = 0; virtual create_interface& quoted_file_content(const std::string& str) = 0; }; class delete_interface { public: virtual ~delete_interface() = default; virtual void run() = 0; }; class get_interface { public: virtual ~get_interface() = default; virtual std::unique_ptr<comment> run() = 0; }; class list_interface { public: class reply { public: reply(const cJSON& json); const std::optional<std::vector<comment>>& comments() const; const std::optional<std::string>& kind() const; const std::optional<std::string>& next_page_token() const; private: std::optional<std::string> kind_; std::optional<std::string> next_page_token_; std::optional<std::vector<comment>> comments_; }; virtual ~list_interface() = default; virtual list_interface& include_deleted(bool to_set) = 0; virtual list_interface& page_size(std::size_t num) = 0; virtual list_interface& page_token(const std::string& tok) = 0; virtual std::unique_ptr<reply> run() = 0; virtual list_interface& start_modified_time(const std::chrono::system_clock::time_point& when) = 0; }; class update_interface { public: virtual ~update_interface() = default; virtual std::unique_ptr<comment> run() = 0; }; virtual ~comments_group() = default; virtual std::unique_ptr<create_interface> create(const std::string& content, const std::string& fields) = 0; virtual std::unique_ptr<delete_interface> del(const std::string& comment_id) = 0; virtual std::unique_ptr<get_interface> get(const std::string& comment_id, const std::string& fields) = 0; virtual std::unique_ptr<list_interface> list(const std::string& fields) = 0; virtual std::unique_ptr<update_interface> update(const std::string& comment_id, const std::string& content, const std::string& fields) = 0; }; inline const std::optional<std::vector<comment>>& comments_group::list_interface::reply::comments() const { return comments_; } inline const std::optional<std::string>& comments_group::list_interface::reply::kind() const { return kind_; } inline const std::optional<std::string>& comments_group::list_interface::reply::next_page_token() const { return next_page_token_; } } #endif
29.375
107
0.615712
mexicowilly
8875e232fa60e8afe8603f10f69eb4d28f7cbc2d
39,264
cpp
C++
src_main/public/zip_utils.cpp
ArcadiusGFN/SourceEngine2007
51cd6d4f0f9ed901cb9b61456eb621a50ce44f55
[ "bzip2-1.0.6" ]
25
2018-02-28T15:04:42.000Z
2021-08-16T03:49:00.000Z
src_main/public/zip_utils.cpp
ArcadiusGFN/SourceEngine2007
51cd6d4f0f9ed901cb9b61456eb621a50ce44f55
[ "bzip2-1.0.6" ]
1
2019-09-20T11:06:03.000Z
2019-09-20T11:06:03.000Z
src_main/public/zip_utils.cpp
ArcadiusGFN/SourceEngine2007
51cd6d4f0f9ed901cb9b61456eb621a50ce44f55
[ "bzip2-1.0.6" ]
9
2019-07-31T11:58:20.000Z
2021-08-31T11:18:15.000Z
// Copyright © 1996-2018, Valve Corporation, All rights reserved. #include "build/include/build_config.h" #ifdef OS_WIN #include "base/include/windows/windows_light.h" #endif #include "zip_utils.h" #include "base/include/base_types.h" #include "tier0/include/platform.h" #include "tier1/byteswap.h" #include "tier1/checksum_crc.h" #include "tier1/utlbuffer.h" #include "tier1/utllinkedlist.h" #include "tier1/utlstring.h" #include "zip_uncompressed.h" // Data descriptions for uint8_t swapping - only needed // for structures that are written to file for use by the game. BEGIN_BYTESWAP_DATADESC(ZIP_EndOfCentralDirRecord) DEFINE_FIELD(signature, FIELD_INTEGER), DEFINE_FIELD(numberOfThisDisk, FIELD_SHORT), DEFINE_FIELD(numberOfTheDiskWithStartOfCentralDirectory, FIELD_SHORT), DEFINE_FIELD(nCentralDirectoryEntries_ThisDisk, FIELD_SHORT), DEFINE_FIELD(nCentralDirectoryEntries_Total, FIELD_SHORT), DEFINE_FIELD(centralDirectorySize, FIELD_INTEGER), DEFINE_FIELD(startOfCentralDirOffset, FIELD_INTEGER), DEFINE_FIELD(commentLength, FIELD_SHORT), END_BYTESWAP_DATADESC() BEGIN_BYTESWAP_DATADESC(ZIP_FileHeader) DEFINE_FIELD(signature, FIELD_INTEGER), DEFINE_FIELD(versionMadeBy, FIELD_SHORT), DEFINE_FIELD(versionNeededToExtract, FIELD_SHORT), DEFINE_FIELD(flags, FIELD_SHORT), DEFINE_FIELD(compressionMethod, FIELD_SHORT), DEFINE_FIELD(lastModifiedTime, FIELD_SHORT), DEFINE_FIELD(lastModifiedDate, FIELD_SHORT), DEFINE_FIELD(crc32, FIELD_INTEGER), DEFINE_FIELD(compressedSize, FIELD_INTEGER), DEFINE_FIELD(uncompressedSize, FIELD_INTEGER), DEFINE_FIELD(fileNameLength, FIELD_SHORT), DEFINE_FIELD(extraFieldLength, FIELD_SHORT), DEFINE_FIELD(fileCommentLength, FIELD_SHORT), DEFINE_FIELD(diskNumberStart, FIELD_SHORT), DEFINE_FIELD(internalFileAttribs, FIELD_SHORT), DEFINE_FIELD(externalFileAttribs, FIELD_INTEGER), DEFINE_FIELD(relativeOffsetOfLocalHeader, FIELD_INTEGER), END_BYTESWAP_DATADESC() #if !defined(SWDS) BEGIN_BYTESWAP_DATADESC(ZIP_LocalFileHeader) DEFINE_FIELD(signature, FIELD_INTEGER), DEFINE_FIELD(versionNeededToExtract, FIELD_SHORT), DEFINE_FIELD(flags, FIELD_SHORT), DEFINE_FIELD(compressionMethod, FIELD_SHORT), DEFINE_FIELD(lastModifiedTime, FIELD_SHORT), DEFINE_FIELD(lastModifiedDate, FIELD_SHORT), DEFINE_FIELD(crc32, FIELD_INTEGER), DEFINE_FIELD(compressedSize, FIELD_INTEGER), DEFINE_FIELD(uncompressedSize, FIELD_INTEGER), DEFINE_FIELD(fileNameLength, FIELD_SHORT), DEFINE_FIELD(extraFieldLength, FIELD_SHORT), END_BYTESWAP_DATADESC() BEGIN_BYTESWAP_DATADESC(ZIP_PreloadHeader) DEFINE_FIELD(Version, FIELD_INTEGER), DEFINE_FIELD(DirectoryEntries, FIELD_INTEGER), DEFINE_FIELD(PreloadDirectoryEntries, FIELD_INTEGER), DEFINE_FIELD(Alignment, FIELD_INTEGER), END_BYTESWAP_DATADESC() BEGIN_BYTESWAP_DATADESC(ZIP_PreloadDirectoryEntry) DEFINE_FIELD(Length, FIELD_INTEGER), DEFINE_FIELD(DataOffset, FIELD_INTEGER), END_BYTESWAP_DATADESC() // For >2 GB File Support class Win32File { public: static HANDLE CreateTempFile(CUtlString &WritePath, CUtlString &FileName) { char tmp_file_path[SOURCE_MAX_PATH]; if (WritePath.IsEmpty()) { // use a safe name in the cwd char tmp_name_with_back_slash[L_tmpnam_s]; errno_t err = tmpnam_s(tmp_name_with_back_slash); if (err != 0 || !tmp_name_with_back_slash[0]) return INVALID_HANDLE_VALUE; char *tmp_name_only = tmp_name_with_back_slash[0] == '\\' ? tmp_name_with_back_slash + 1 : tmp_name_with_back_slash; if (tmp_name_only[strlen(tmp_name_only) - 1] == '.') { tmp_name_only[strlen(tmp_name_only) - 1] = '\0'; } sprintf_s(tmp_file_path, "_%s.tmp", tmp_name_only); } else { // generate safe name at the desired prefix char unique_file_path[SOURCE_MAX_PATH]; SYSTEMTIME sysTime; GetLocalTime(&sysTime); sprintf_s(unique_file_path, "%hu_%hu_%hu_%hu_%hu.tmp", sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond, sysTime.wMilliseconds); V_ComposeFileName(WritePath.String(), unique_file_path, tmp_file_path, std::size(tmp_file_path)); } FileName = tmp_file_path; HANDLE hFile = CreateFile(tmp_file_path, GENERIC_READ | GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); return hFile; } static long long FileSeek(HANDLE hFile, long long distance, DWORD move_method) { LARGE_INTEGER li; li.QuadPart = distance; li.LowPart = SetFilePointer(hFile, li.LowPart, &li.HighPart, move_method); if (li.LowPart == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) { li.QuadPart = -1; } return li.QuadPart; } static long long FileTell(HANDLE hFile) { return FileSeek(hFile, 0, FILE_CURRENT); } static bool FileRead(HANDLE hFile, void *pBuffer, DWORD size) { DWORD bytes_read; return ReadFile(hFile, pBuffer, size, &bytes_read, nullptr) && bytes_read == size; } static bool FileWrite(HANDLE hFile, void *pBuffer, DWORD size) { DWORD bytes_written; return WriteFile(hFile, pBuffer, size, &bytes_written, nullptr) && bytes_written == size; } }; // Purpose: Interface to allow abstraction of zip file output methods, and // avoid duplication of code. Files may be written to a CUtlBuffer or a // file stream. the_interface IWriteStream { public: virtual void Put(const void *memory, usize size) = 0; virtual usize Tell() = 0; }; // Purpose: Wrapper for CUtlBuffer methods. class BufferWriteStream : public IWriteStream { public: BufferWriteStream(CUtlBuffer &buffer) : buffer_{&buffer} {} void Put(const void *memory, usize size) override { buffer_->Put(memory, size); } usize Tell() override { return buffer_->TellPut(); } private: CUtlBuffer *const buffer_; }; // Purpose: Wrapper for file I/O methods. class FileWriteStream : public IWriteStream { public: FileWriteStream(FILE *file_desc) : file_desc_{file_desc}, file_handle_{INVALID_HANDLE_VALUE} {} FileWriteStream(HANDLE file_handle) : file_desc_{nullptr}, file_handle_{file_handle} {} void Put(const void *memory, usize size) override { if (file_desc_) { fwrite(memory, size, 1, file_desc_); } else { DWORD numBytesWritten; WriteFile(file_handle_, memory, size, &numBytesWritten, nullptr); } } usize Tell() override { if (file_desc_) { return ftell(file_desc_); } return Win32File::FileTell(file_handle_); } private: FILE *const file_desc_; HANDLE const file_handle_; }; // Purpose: Container for modifiable pak file which is embedded inside the .bsp // file itself. It's used to allow one-off files to be stored local to the map // and it is hooked into the file system as an override for searching for named // files. class ZipFile { public: // Construction ZipFile(const char *pDiskCacheWritePath, bool bSortByName); ~ZipFile() { m_bUseDiskCacheForWrites = false; Reset(); } // Public API // Clear all existing data void Reset() { m_Files.RemoveAll(); if (m_hDiskCacheWriteFile != INVALID_HANDLE_VALUE) { CloseHandle(m_hDiskCacheWriteFile); DeleteFile(m_DiskCacheName.String()); m_hDiskCacheWriteFile = INVALID_HANDLE_VALUE; } if (m_bUseDiskCacheForWrites) { m_hDiskCacheWriteFile = Win32File::CreateTempFile(m_DiskCacheWritePath, m_DiskCacheName); } } // Add file to zip under relative name void AddFileToZip(const char *relativename, const char *fullpath); // Delete file from zip void RemoveFileFromZip(const char *relativename); // Add buffer to zip as a file with given name void AddBufferToZip(const char *relativename, void *data, int length, bool bTextMode); // Check if a file already exists in the zip. bool FileExistsInZip(const char *relativename); // Reads a file from a zip file bool ReadFileFromZip(const char *relativename, bool bTextMode, CUtlBuffer &buf); bool ReadFileFromZip(HANDLE hZipFile, const char *relativename, bool bTextMode, CUtlBuffer &buf); // Initialize the zip file from a buffer void ParseFromBuffer(void *buffer, int bufferlength) { // Throw away old data Reset(); // Initialize a buffer CUtlBuffer buf(0, bufferlength + 1); // +1 for 0 termination // need to swap bytes, so set the buffer opposite the machine's endian buf.ActivateByteSwapping(m_Swap.IsSwappingBytes()); buf.Put(buffer, bufferlength); buf.SeekGet(CUtlBuffer::SEEK_TAIL, 0); unsigned int fileLen = buf.TellGet(); // Start from beginning buf.SeekGet(CUtlBuffer::SEEK_HEAD, 0); unsigned int offset; ZIP_EndOfCentralDirRecord rec = {0}; bool bFoundEndOfCentralDirRecord = false; for (offset = fileLen - sizeof(ZIP_EndOfCentralDirRecord) + 1; offset >= 1; offset--) { buf.SeekGet(CUtlBuffer::SEEK_HEAD, offset - 1); buf.GetObjects(&rec); if (rec.signature == PKID(5, 6)) { bFoundEndOfCentralDirRecord = true; // Set any xzip configuration if (rec.commentLength) { char commentString[128]; usize commentLength = std::min((usize)rec.commentLength, sizeof(commentString)); buf.Get(commentString, commentLength); commentString[commentLength] = '\0'; ParseXZipCommentString(commentString); } break; } else { // wrong record rec.nCentralDirectoryEntries_Total = 0; } } Assert(bFoundEndOfCentralDirRecord); // Make sure there are some files to parse int numzipfiles = rec.nCentralDirectoryEntries_Total; if (numzipfiles <= 0) { // No files return; } buf.SeekGet(CUtlBuffer::SEEK_HEAD, rec.startOfCentralDirOffset); // Allocate space for directory TmpFileInfo_t *newfiles = new TmpFileInfo_t[numzipfiles]; Assert(newfiles); // build directory int i; for (i = 0; i < rec.nCentralDirectoryEntries_Total; i++) { ZIP_FileHeader zipFileHeader; buf.GetObjects(&zipFileHeader); Assert(zipFileHeader.signature == PKID(1, 2)); Assert(zipFileHeader.compressionMethod == 0); char tmpString[1024]; buf.Get(tmpString, zipFileHeader.fileNameLength); tmpString[zipFileHeader.fileNameLength] = '\0'; Q_strlower(tmpString); // can determine actual filepos, assuming a well formed zip newfiles[i].m_Name = tmpString; newfiles[i].filelen = zipFileHeader.compressedSize; newfiles[i].filepos = zipFileHeader.relativeOffsetOfLocalHeader + sizeof(ZIP_LocalFileHeader) + zipFileHeader.fileNameLength + zipFileHeader.extraFieldLength; int nextOffset; if (m_bCompatibleFormat) { nextOffset = zipFileHeader.extraFieldLength + zipFileHeader.fileCommentLength; } else { nextOffset = 0; } buf.SeekGet(CUtlBuffer::SEEK_CURRENT, nextOffset); } // Insert current data into rb tree for (i = 0; i < numzipfiles; i++) { CZipEntry e; e.m_Name = newfiles[i].m_Name; e.m_Length = newfiles[i].filelen; // Make sure length is reasonable if (e.m_Length > 0) { e.m_pData = malloc(e.m_Length); // Copy in data buf.SeekGet(CUtlBuffer::SEEK_HEAD, newfiles[i].filepos); buf.Get(e.m_pData, e.m_Length); } else { e.m_pData = nullptr; } // Add to tree m_Files.Insert(e); } // Through away directory delete[] newfiles; } HANDLE ParseFromDisk(const char *pFilename) { HANDLE hFile = CreateFile(pFilename, GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (!hFile) { // not found return nullptr; } unsigned int fileLen = Win32File::FileSeek(hFile, 0, FILE_END); Win32File::FileSeek(hFile, 0, FILE_BEGIN); if (fileLen < sizeof(ZIP_EndOfCentralDirRecord)) { // bad format CloseHandle(hFile); return nullptr; } // need to get the central dir unsigned int offset; ZIP_EndOfCentralDirRecord rec = {0}; for (offset = fileLen - sizeof(ZIP_EndOfCentralDirRecord) + 1; offset >= 1; offset--) { Win32File::FileSeek(hFile, offset - 1, FILE_BEGIN); Win32File::FileRead(hFile, &rec, sizeof(rec)); m_Swap.SwapFieldsToTargetEndian(&rec); if (rec.signature == PKID(5, 6)) { // Set any xzip configuration if (rec.commentLength) { char commentString[128]; usize commentLength = std::min((usize)rec.commentLength, sizeof(commentString)); Win32File::FileRead(hFile, commentString, commentLength); commentString[commentLength] = '\0'; ParseXZipCommentString(commentString); } break; } else { // wrong record rec.nCentralDirectoryEntries_Total = 0; } } // Make sure there are some files to parse int numZipFiles = rec.nCentralDirectoryEntries_Total; if (numZipFiles <= 0) { // No files CloseHandle(hFile); return nullptr; } Win32File::FileSeek(hFile, rec.startOfCentralDirOffset, FILE_BEGIN); // read entire central dir into memory CUtlBuffer zipDirBuff(0, rec.centralDirectorySize, 0); zipDirBuff.ActivateByteSwapping(m_Swap.IsSwappingBytes()); Win32File::FileRead(hFile, zipDirBuff.Base(), rec.centralDirectorySize); zipDirBuff.SeekPut(CUtlBuffer::SEEK_HEAD, rec.centralDirectorySize); // build directory for (int i = 0; i < numZipFiles; i++) { ZIP_FileHeader zipFileHeader; zipDirBuff.GetObjects(&zipFileHeader); if (zipFileHeader.signature != PKID(1, 2) || zipFileHeader.compressionMethod != 0) { // bad contents CloseHandle(hFile); return nullptr; } char fileName[1024]; zipDirBuff.Get(fileName, zipFileHeader.fileNameLength); fileName[zipFileHeader.fileNameLength] = '\0'; Q_strlower(fileName); // can determine actual filepos, assuming a well formed zip CZipEntry e; e.m_Name = fileName; e.m_Length = zipFileHeader.compressedSize; e.m_SourceDiskOffset = zipFileHeader.relativeOffsetOfLocalHeader + sizeof(ZIP_LocalFileHeader) + zipFileHeader.fileNameLength + zipFileHeader.extraFieldLength; // Add to tree m_Files.Insert(e); int nextOffset; if (m_bCompatibleFormat) { nextOffset = zipFileHeader.extraFieldLength + zipFileHeader.fileCommentLength; } else { nextOffset = 0; } zipDirBuff.SeekGet(CUtlBuffer::SEEK_CURRENT, nextOffset); } return hFile; } // Estimate the size of the zip file (including header, padding, etc.) unsigned int EstimateSize(); // Print out a directory of files in the zip. void PrintDirectory(); // Use to iterate directory, pass 0 for first element // returns nonzero element id with filled buffer, or -1 at list conclusion int GetNextFilename(int id, char *pBuffer, int bufferSize, int &fileSize); // Write the zip to a buffer void SaveToBuffer(CUtlBuffer &buffer); // Write the zip to a filestream void SaveToDisk(FILE *fout); void SaveToDisk(HANDLE hOutFile); unsigned int CalculateSize(); void ForceAlignment(bool aligned, bool bCompatibleFormat, unsigned int alignmentSize) { m_bForceAlignment = aligned; m_AlignmentSize = alignmentSize; m_bCompatibleFormat = bCompatibleFormat; if (!aligned) { m_AlignmentSize = 0; } else if (!IsPowerOfTwo(m_AlignmentSize)) { m_AlignmentSize = 0; } } unsigned int GetAlignment() { if (!m_bForceAlignment || !m_AlignmentSize) { return 0; } return m_AlignmentSize; } void SetBigEndian(bool bigEndian) { m_Swap.SetTargetBigEndian(bigEndian); } void ActivateByteSwapping(bool bActivate) { m_Swap.ActivateByteSwapping(bActivate); } private: enum { MAX_FILES_IN_ZIP = 32768, }; struct TmpFileInfo_t { CUtlSymbol m_Name; unsigned int filepos; int filelen; }; CByteswap m_Swap; unsigned int m_AlignmentSize; bool m_bForceAlignment; bool m_bCompatibleFormat; u16 CalculatePadding(unsigned int filenameLen, unsigned int pos); void SaveDirectory(IWriteStream &stream); u16 MakeXZipCommentString(char *pComment, size_t max_length); void ParseXZipCommentString(const char *pComment); // Internal entry for faster searching, etc. class CZipEntry { public: CZipEntry() { m_Name = ""; m_Length = 0; m_pData = nullptr; m_ZipOffset = 0; m_ZipCRC = 0; m_DiskCacheOffset = 0; m_SourceDiskOffset = 0; } ~CZipEntry() { heap_free(m_pData); } CZipEntry(const CZipEntry &src) { m_Name = src.m_Name; m_Length = src.m_Length; if (src.m_Length > 0 && src.m_pData) { m_pData = malloc(src.m_Length); memcpy(m_pData, src.m_pData, src.m_Length); } else { m_pData = nullptr; } m_ZipOffset = src.m_ZipOffset; m_ZipCRC = src.m_ZipCRC; m_DiskCacheOffset = src.m_DiskCacheOffset; m_SourceDiskOffset = src.m_SourceDiskOffset; } // RB tree compare function static bool ZipFileLessFunc(CZipEntry const &src1, CZipEntry const &src2) { return (src1.m_Name < src2.m_Name); } static bool ZipFileLessFunc_CaselessSort(CZipEntry const &src1, CZipEntry const &src2) { return _stricmp(src1.m_Name.String(), src2.m_Name.String()) < 0; } // Name of entry CUtlSymbol m_Name; // Lenth of data element int m_Length; // Raw data, could be 0 and data may be in disk write cache void *m_pData; // Offset in Zip ( set and valid during final write ) unsigned int m_ZipOffset; // CRC of blob ( set and valid during final write ) CRC32_t m_ZipCRC; // Location of data in disk cache unsigned int m_DiskCacheOffset; unsigned int m_SourceDiskOffset; }; // For fast name lookup and sorting CUtlRBTree<CZipEntry, int> m_Files; // Used to buffer zip data, instead of ram bool m_bUseDiskCacheForWrites; HANDLE m_hDiskCacheWriteFile; CUtlString m_DiskCacheName; CUtlString m_DiskCacheWritePath; }; ZipFile::ZipFile(const char *pDiskCacheWritePath, bool bSortByName) : m_Files{0, 32}, m_DiskCacheWritePath{pDiskCacheWritePath} { m_AlignmentSize = 0; m_bForceAlignment = false; m_bCompatibleFormat = true; m_bUseDiskCacheForWrites = (pDiskCacheWritePath != nullptr); m_hDiskCacheWriteFile = INVALID_HANDLE_VALUE; if (bSortByName) { m_Files.SetLessFunc(CZipEntry::ZipFileLessFunc_CaselessSort); } else { m_Files.SetLessFunc(CZipEntry::ZipFileLessFunc); } } static int GetLengthOfBinStringAsText(const char *pSrc, int srcSize) { const char *pSrcScan = pSrc; const char *pSrcEnd = pSrc + srcSize; int numChars = 0; for (; pSrcScan < pSrcEnd; pSrcScan++) { if (*pSrcScan == '\n') { numChars += 2; } else { numChars++; } } return numChars; } // Copies text data from a form appropriate for disk to a normal string static void ReadTextData(const char *pSrc, int nSrcSize, CUtlBuffer &buf) { buf.EnsureCapacity(nSrcSize + 1); const char *pSrcEnd = pSrc + nSrcSize; for (const char *pSrcScan = pSrc; pSrcScan < pSrcEnd; ++pSrcScan) { if (*pSrcScan == '\r') { if (pSrcScan[1] == '\n') { buf.PutChar('\n'); ++pSrcScan; continue; } } buf.PutChar(*pSrcScan); } // nullptr terminate buf.PutChar('\0'); } // Copies text data into a form appropriate for disk static void CopyTextData(char *pDst, const char *pSrc, int dstSize, int srcSize) { const char *pSrcScan = pSrc; const char *pSrcEnd = pSrc + srcSize; char *pDstScan = pDst; #ifdef _DEBUG char *pDstEnd = pDst + dstSize; #endif for (; pSrcScan < pSrcEnd; pSrcScan++) { if (*pSrcScan == '\n') { *pDstScan = '\r'; pDstScan++; *pDstScan = '\n'; pDstScan++; } else { *pDstScan = *pSrcScan; pDstScan++; } } Assert(pSrcScan == pSrcEnd); Assert(pDstScan == pDstEnd); } // Purpose: Adds a new lump, or overwrites existing one void ZipFile::AddBufferToZip(const char *relativename, void *data, int length, bool bTextMode) { // Lower case only char name[512]; strcpy_s(name, relativename); Q_strlower(name); int dstLength = length; if (bTextMode) { dstLength = GetLengthOfBinStringAsText((const char *)data, length); } // See if entry is in list already CZipEntry e; e.m_Name = name; int index = m_Files.Find(e); // If already existing, throw away old data and update data and length if (index != m_Files.InvalidIndex()) { CZipEntry *update = &m_Files[index]; heap_free(update->m_pData); if (bTextMode) { update->m_pData = malloc(dstLength); CopyTextData((char *)update->m_pData, (char *)data, dstLength, length); update->m_Length = dstLength; } else { update->m_pData = malloc(length); memcpy(update->m_pData, data, length); update->m_Length = length; } if (m_hDiskCacheWriteFile != INVALID_HANDLE_VALUE) { update->m_DiskCacheOffset = Win32File::FileTell(m_hDiskCacheWriteFile); Win32File::FileWrite(m_hDiskCacheWriteFile, update->m_pData, update->m_Length); heap_free(update->m_pData); } } else { // Create a new entry e.m_Length = dstLength; if (dstLength > 0) { if (bTextMode) { e.m_pData = malloc(dstLength); CopyTextData((char *)e.m_pData, (char *)data, dstLength, length); } else { e.m_pData = malloc(length); memcpy(e.m_pData, data, length); } if (m_hDiskCacheWriteFile != INVALID_HANDLE_VALUE) { e.m_DiskCacheOffset = Win32File::FileTell(m_hDiskCacheWriteFile); Win32File::FileWrite(m_hDiskCacheWriteFile, e.m_pData, e.m_Length); heap_free(e.m_pData); } } else { e.m_pData = nullptr; } m_Files.Insert(e); } } // Reads a file from the zip bool ZipFile::ReadFileFromZip(const char *pRelativeName, bool bTextMode, CUtlBuffer &buf) { // Lower case only char pName[512]; strcpy_s(pName, pRelativeName); Q_strlower(pName); // See if entry is in list already CZipEntry e; e.m_Name = pName; int nIndex = m_Files.Find(e); if (nIndex == m_Files.InvalidIndex()) { // not found return false; } CZipEntry *pEntry = &m_Files[nIndex]; if (bTextMode) { buf.SetBufferType(true, false); ReadTextData((char *)pEntry->m_pData, pEntry->m_Length, buf); } else { buf.SetBufferType(false, false); buf.Put(pEntry->m_pData, pEntry->m_Length); } return true; } // Reads a file from the zip bool ZipFile::ReadFileFromZip(HANDLE hZipFile, const char *pRelativeName, bool bTextMode, CUtlBuffer &buf) { // Lower case only char pName[512]; strcpy_s(pName, pRelativeName); Q_strlower(pName); // See if entry is in list already CZipEntry e; e.m_Name = pName; int nIndex = m_Files.Find(e); if (nIndex == m_Files.InvalidIndex()) { // not found return false; } CZipEntry *pEntry = &m_Files[nIndex]; void *pData = malloc(pEntry->m_Length); Win32File::FileSeek(hZipFile, pEntry->m_SourceDiskOffset, FILE_BEGIN); if (!Win32File::FileRead(hZipFile, pData, pEntry->m_Length)) { heap_free(pData); return false; } if (bTextMode) { buf.SetBufferType(true, false); ReadTextData((const char *)pData, pEntry->m_Length, buf); } else { buf.SetBufferType(false, false); buf.Put(pData, pEntry->m_Length); } heap_free(pData); return true; } // Purpose: Check if a file already exists in the zip. bool ZipFile::FileExistsInZip(const char *pRelativeName) { // Lower case only char pName[512]; strcpy_s(pName, pRelativeName); Q_strlower(pName); // See if entry is in list already CZipEntry e; e.m_Name = pName; int nIndex = m_Files.Find(e); // If it is, then it exists in the pack! return nIndex != m_Files.InvalidIndex(); } // Purpose: Adds a new file to the zip. void ZipFile::AddFileToZip(const char *relativename, const char *fullpath) { FILE *fd; if (!fopen_s(&fd, fullpath, "rb")) { // Determine length fseek(fd, 0, SEEK_END); long size = ftell(fd); fseek(fd, 0, SEEK_SET); u8 *buf = (u8 *)malloc(size + 1); if (buf) { // Read data fread(buf, size, 1, fd); } fclose(fd); if (buf) { // Now add as a buffer AddBufferToZip(relativename, buf, size, false); heap_free(buf); } } } // Purpose: Removes a file from the zip. void ZipFile::RemoveFileFromZip(const char *relativename) { CZipEntry e; e.m_Name = relativename; int index = m_Files.Find(e); if (index != m_Files.InvalidIndex()) { CZipEntry update = m_Files[index]; m_Files.Remove(update); } } // Purpose: Calculates how many bytes should be added to the extra field // to push the start of the file data to the next aligned boundary // Output: Required padding size u16 ZipFile::CalculatePadding(unsigned int filenameLen, unsigned int pos) { if (m_AlignmentSize == 0) { return 0; } unsigned int headerSize = sizeof(ZIP_LocalFileHeader) + filenameLen; return (u16)(m_AlignmentSize - ((pos + headerSize) % m_AlignmentSize)); } // Purpose: Create the XZIP identifying comment string // Output : Length u16 ZipFile::MakeXZipCommentString(char *comment, size_t max_length) { char tmp[XZIP_COMMENT_LENGTH]; memset(tmp, 0, sizeof(tmp)); sprintf_s(tmp, "XZP%c %u", m_bCompatibleFormat ? '1' : '2', m_AlignmentSize); if (comment && max_length <= XZIP_COMMENT_LENGTH) { memcpy(comment, tmp, sizeof(tmp)); } // expected fixed length return XZIP_COMMENT_LENGTH; } // Purpose: An XZIP has its configuration in the ascii comment void ZipFile::ParseXZipCommentString(const char *pCommentString) { if (!_strnicmp(pCommentString, "XZP", 3)) { m_bCompatibleFormat = true; if (pCommentString[3] == '2') { m_bCompatibleFormat = false; } // parse out the alignement configuration if (!m_bForceAlignment) { m_AlignmentSize = 0; sscanf_s(pCommentString + 4, "%u", &m_AlignmentSize); if (!IsPowerOfTwo(m_AlignmentSize)) { m_AlignmentSize = 0; } } } } // Purpose: Calculate the exact size of zip file, with headers and padding // Output : int unsigned int ZipFile::CalculateSize() { usize size = 0, dirHeaders = 0; for (int i = m_Files.FirstInorder(); i != m_Files.InvalidIndex(); i = m_Files.NextInorder(i)) { CZipEntry *e = &m_Files[i]; if (e->m_Length == 0) continue; // local file header size += sizeof(ZIP_LocalFileHeader); size += strlen(e->m_Name.String()); // every file has a directory header that duplicates the filename dirHeaders += sizeof(ZIP_FileHeader) + strlen(e->m_Name.String()); // calculate padding if (m_AlignmentSize != 0) { // round up to next boundary usize nextBoundary = (size + m_AlignmentSize) & ~((usize)m_AlignmentSize - 1); // the directory header also duplicates the padding dirHeaders += nextBoundary - size; size = nextBoundary; } // data size size += e->m_Length; } size += dirHeaders; // All processed zip files will have a comment string size += sizeof(ZIP_EndOfCentralDirRecord) + MakeXZipCommentString(nullptr, 0); return size; } // Purpose: Print a directory of files in the zip void ZipFile::PrintDirectory() { for (int i = m_Files.FirstInorder(); i != m_Files.InvalidIndex(); i = m_Files.NextInorder(i)) { CZipEntry *e = &m_Files[i]; Msg("%s\n", e->m_Name.String()); } } // Purpose: Iterate through directory int ZipFile::GetNextFilename(int id, char *pBuffer, int bufferSize, int &fileSize) { if (id == -1) { id = m_Files.FirstInorder(); } else { id = m_Files.NextInorder(id); } if (id == m_Files.InvalidIndex()) { // list is empty return -1; } CZipEntry *e = &m_Files[id]; strcpy_s(pBuffer, bufferSize, e->m_Name.String()); fileSize = e->m_Length; return id; } // Purpose: Store data out to disk void ZipFile::SaveToDisk(FILE *fout) { FileWriteStream stream(fout); SaveDirectory(stream); } void ZipFile::SaveToDisk(HANDLE hOutFile) { FileWriteStream stream(hOutFile); SaveDirectory(stream); } // Purpose: Store data out to a CUtlBuffer void ZipFile::SaveToBuffer(CUtlBuffer &buf) { BufferWriteStream stream(buf); SaveDirectory(stream); } // Purpose: Store data back out to a stream (could be CUtlBuffer or filestream) void ZipFile::SaveDirectory(IWriteStream &stream) { void *padding_buffer = nullptr; if (m_AlignmentSize) { // get a temp buffer for all padding work padding_buffer = malloc(m_AlignmentSize); memset(padding_buffer, 0x00, m_AlignmentSize); } if (m_hDiskCacheWriteFile != INVALID_HANDLE_VALUE) { FlushFileBuffers(m_hDiskCacheWriteFile); } for (int i = m_Files.FirstInorder(); i != m_Files.InvalidIndex(); i = m_Files.NextInorder(i)) { CZipEntry *e = &m_Files[i]; Assert(e); // Fix up the offset e->m_ZipOffset = stream.Tell(); if (e->m_Length > 0 && (m_hDiskCacheWriteFile != INVALID_HANDLE_VALUE)) { // get the data back from the write cache e->m_pData = malloc(e->m_Length); if (e->m_pData) { Win32File::FileSeek(m_hDiskCacheWriteFile, e->m_DiskCacheOffset, FILE_BEGIN); Win32File::FileRead(m_hDiskCacheWriteFile, e->m_pData, e->m_Length); } } if (e->m_Length > 0 && e->m_pData != nullptr) { ZIP_LocalFileHeader hdr{0}; hdr.signature = PKID(3, 4); // This is the version that the winzip that I have writes. hdr.versionNeededToExtract = 10; hdr.flags = 0; hdr.compressionMethod = 0; // NO COMPRESSION! hdr.lastModifiedTime = 0; hdr.lastModifiedDate = 0; CRC32_Init(&e->m_ZipCRC); CRC32_ProcessBuffer(&e->m_ZipCRC, e->m_pData, e->m_Length); CRC32_Final(&e->m_ZipCRC); hdr.crc32 = e->m_ZipCRC; const char *pFilename = e->m_Name.String(); hdr.compressedSize = e->m_Length; hdr.uncompressedSize = e->m_Length; Assert(strlen(pFilename) <= USHRT_MAX); hdr.fileNameLength = (u16)strlen(pFilename); hdr.extraFieldLength = CalculatePadding(hdr.fileNameLength, e->m_ZipOffset); u16 extraFieldLength = hdr.extraFieldLength; // Swap header in place m_Swap.SwapFieldsToTargetEndian(&hdr); stream.Put(&hdr, sizeof(hdr)); stream.Put(pFilename, strlen(pFilename)); stream.Put(padding_buffer, extraFieldLength); stream.Put(e->m_pData, e->m_Length); if (m_hDiskCacheWriteFile != INVALID_HANDLE_VALUE) { heap_free(e->m_pData); // temp hackery for the logic below to succeed e->m_pData = (void *)(intptr_t)-1; } } } if (m_hDiskCacheWriteFile != INVALID_HANDLE_VALUE) { Win32File::FileSeek(m_hDiskCacheWriteFile, 0, FILE_END); } usize centralDirStart = stream.Tell(); if (m_AlignmentSize) { // align the central directory starting position usize newDirStart = AlignValue(centralDirStart, m_AlignmentSize); usize padLength = newDirStart - centralDirStart; if (padLength) { stream.Put(padding_buffer, padLength); centralDirStart = newDirStart; } } u32 realNumFiles = 0; for (int i = m_Files.FirstInorder(); i != m_Files.InvalidIndex(); i = m_Files.NextInorder(i)) { CZipEntry *e = &m_Files[i]; Assert(e); if (e->m_Length > 0 && e->m_pData != nullptr) { ZIP_FileHeader hdr = {0}; hdr.signature = PKID(1, 2); hdr.versionMadeBy = 20; // This is the version that the winzip that I have writes. hdr.versionNeededToExtract = 10; // This is the version that the winzip that I have writes. hdr.flags = 0; hdr.compressionMethod = 0; hdr.lastModifiedTime = 0; hdr.lastModifiedDate = 0; hdr.crc32 = e->m_ZipCRC; hdr.compressedSize = e->m_Length; hdr.uncompressedSize = e->m_Length; Assert(strlen(e->m_Name.String()) <= USHRT_MAX); hdr.fileNameLength = (u16)strlen(e->m_Name.String()); hdr.extraFieldLength = CalculatePadding(hdr.fileNameLength, e->m_ZipOffset); hdr.fileCommentLength = 0; hdr.diskNumberStart = 0; hdr.internalFileAttribs = 0; hdr.externalFileAttribs = 0; // This is usually something, but zero is OK // as if the input came from stdin hdr.relativeOffsetOfLocalHeader = e->m_ZipOffset; u16 extraFieldLength = hdr.extraFieldLength; // Swap the header in place m_Swap.SwapFieldsToTargetEndian(&hdr); stream.Put(&hdr, sizeof(hdr)); stream.Put(e->m_Name.String(), strlen(e->m_Name.String())); if (m_bCompatibleFormat) { stream.Put(padding_buffer, extraFieldLength); } realNumFiles++; if (m_hDiskCacheWriteFile != INVALID_HANDLE_VALUE) { // clear out temp hackery e->m_pData = nullptr; } } } usize centralDirEnd = stream.Tell(); if (m_AlignmentSize) { // align the central directory starting position usize newDirEnd = AlignValue(centralDirEnd, m_AlignmentSize); usize padLength = newDirEnd - centralDirEnd; if (padLength) { stream.Put(padding_buffer, padLength); centralDirEnd = newDirEnd; } } ZIP_EndOfCentralDirRecord rec{0}; rec.signature = PKID(5, 6); rec.numberOfThisDisk = 0; rec.numberOfTheDiskWithStartOfCentralDirectory = 0; rec.nCentralDirectoryEntries_ThisDisk = realNumFiles; rec.nCentralDirectoryEntries_Total = realNumFiles; rec.centralDirectorySize = centralDirEnd - centralDirStart; rec.startOfCentralDirOffset = centralDirStart; char commentString[128]; u16 comment_size = MakeXZipCommentString(commentString, std::size(commentString)); rec.commentLength = comment_size; // Swap the header in place m_Swap.SwapFieldsToTargetEndian(&rec); stream.Put(&rec, sizeof(rec)); stream.Put(commentString, comment_size); heap_free(padding_buffer); } class CZip : public IZip { public: CZip(const char *pDiskCacheWritePath, bool bSortByName) : m_ZipFile(pDiskCacheWritePath, bSortByName) { m_ZipFile.Reset(); } virtual ~CZip() {} virtual void Reset() { m_ZipFile.Reset(); } // Add a single file to a zip - maintains the zip's previous alignment state virtual void AddFileToZip(const char *relativename, const char *fullpath) { m_ZipFile.AddFileToZip(relativename, fullpath); } // Whether a file is contained in a zip - maintains alignment virtual bool FileExistsInZip(const char *pRelativeName) { return m_ZipFile.FileExistsInZip(pRelativeName); } // Reads a file from the zip - maintains alignement virtual bool ReadFileFromZip(const char *pRelativeName, bool bTextMode, CUtlBuffer &buf) { return m_ZipFile.ReadFileFromZip(pRelativeName, bTextMode, buf); } virtual bool ReadFileFromZip(HANDLE hZipFile, const char *relativename, bool bTextMode, CUtlBuffer &buf) { return m_ZipFile.ReadFileFromZip(hZipFile, relativename, bTextMode, buf); } // Removes a single file from the zip - maintains alignment virtual void RemoveFileFromZip(const char *relativename) { m_ZipFile.RemoveFileFromZip(relativename); } // Gets next filename in zip, for walking the directory - maintains alignment virtual int GetNextFilename(int id, char *pBuffer, int bufferSize, int &fileSize) { return m_ZipFile.GetNextFilename(id, pBuffer, bufferSize, fileSize); } // Prints the zip's contents - maintains alignment virtual void PrintDirectory() { m_ZipFile.PrintDirectory(); } // Estimate the size of the Zip (including header, padding, etc.) virtual unsigned int EstimateSize() { return m_ZipFile.CalculateSize(); } // Add buffer to zip as a file with given name - uses current alignment size, // default 0 (no alignment) // Add buffer to zip as a file with given name virtual void AddBufferToZip(const char *relativename, void *data, int length, bool bTextMode) { m_ZipFile.AddBufferToZip(relativename, data, length, bTextMode); } // Writes out zip file to a buffer - uses current alignment size // (set by file's previous alignment, or a call to ForceAlignment) virtual void SaveToBuffer(CUtlBuffer &outbuf) { m_ZipFile.SaveToBuffer(outbuf); } // Writes out zip file to a filestream - uses current alignment size // (set by file's previous alignment, or a call to ForceAlignment) virtual void SaveToDisk(FILE *fout) { m_ZipFile.SaveToDisk(fout); } virtual void SaveToDisk(HANDLE hOutFile) { m_ZipFile.SaveToDisk(hOutFile); } // Reads a zip file from a buffer into memory - sets current alignment size to // the file's alignment size, unless overridden by a ForceAlignment call) virtual void ParseFromBuffer(void *buffer, int bufferlength) { m_ZipFile.Reset(); m_ZipFile.ParseFromBuffer(buffer, bufferlength); } virtual HANDLE ParseFromDisk(const char *pFilename) { m_ZipFile.Reset(); return m_ZipFile.ParseFromDisk(pFilename); } // Forces a specific alignment size for all subsequent file operations, // overriding files' previous alignment size. Return to using files' // individual alignment sizes by passing FALSE. virtual void ForceAlignment(bool aligned, bool bCompatibleFormat, unsigned int alignmentSize) { m_ZipFile.ForceAlignment(aligned, bCompatibleFormat, alignmentSize); } // Sets the endianess of the zip virtual void SetBigEndian(bool bigEndian) { m_ZipFile.SetBigEndian(bigEndian); } virtual void ActivateByteSwapping(bool bActivate) { m_ZipFile.ActivateByteSwapping(bActivate); } virtual unsigned int GetAlignment() { return m_ZipFile.GetAlignment(); } private: ZipFile m_ZipFile; }; static CUtlLinkedList<CZip *> g_ZipUtils; IZip *IZip::CreateZip(const char *pDiskCacheWritePath, bool bSortByName) { CZip *pZip = new CZip(pDiskCacheWritePath, bSortByName); g_ZipUtils.AddToTail(pZip); return pZip; } void IZip::ReleaseZip(IZip *pZip) { g_ZipUtils.FindAndRemove((CZip *)pZip); delete ((CZip *)pZip); } #endif // SWDS
30.343122
80
0.670156
ArcadiusGFN
887b0e7e8d39ff75c07236fe027d06843ce6b2f3
2,043
cpp
C++
01/solution.cpp
IAmBullsaw/AOC-2017
c320ea275403d261ebc0dbd8f46c8fb62453dc97
[ "MIT" ]
null
null
null
01/solution.cpp
IAmBullsaw/AOC-2017
c320ea275403d261ebc0dbd8f46c8fb62453dc97
[ "MIT" ]
null
null
null
01/solution.cpp
IAmBullsaw/AOC-2017
c320ea275403d261ebc0dbd8f46c8fb62453dc97
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; int solveCaptcha(string & captcha) { captcha.push_back(captcha.front()); string::const_iterator it{captcha.begin()}; int sum{0}; while(it != captcha.end()) { char letter{*it}; unsigned n{0}; do { if (letter == *(it+1+n)) { ++n; } else break; } while(n < captcha.size()); sum += static_cast<int>(letter - '0')*n; advance(it,1+n); } return sum; } int solveCaptcha2(string const& captcha) { const long unsigned half{captcha.size()/2}; int opposite{0}; char other{}; int sum{0}; long unsigned i{0}; for (char letter : captcha) { if (i < half) { opposite = half + i; } else { opposite = i - half; } other = captcha.at(opposite); if (letter == other) { sum += static_cast<int>(letter - '0'); } ++i; } return sum; } void test() { string captcha{"1122"}; int sum{solveCaptcha(captcha)}; cout << "Sum of 1122 is: " << sum << endl; captcha = "1111"; sum = solveCaptcha(captcha); cout << "Sum of 1111 is: " << sum << endl; captcha = "1234"; sum = solveCaptcha(captcha); cout << "Sum of 1234 is: " << sum << endl; captcha = "91212129"; sum = solveCaptcha(captcha); cout << "Sum of 91212129 is: " << sum << endl; } void test2() { string captcha{"1212"}; int sum{solveCaptcha2(captcha)}; cout << "Sum of " << captcha << " is: " << sum << endl; captcha = "1221"; sum = solveCaptcha2(captcha); cout << "Sum of " << captcha << " is: " << sum << endl; captcha = "123425"; sum = solveCaptcha2(captcha); cout << "Sum of " << captcha << " is: " << sum << endl; captcha = "123123"; sum = solveCaptcha2(captcha); cout << "Sum of " << captcha << " is: " << sum << endl; captcha = "12131415"; sum = solveCaptcha2(captcha); cout << "Sum of " << captcha << " is: " << sum << endl; } int main() { string captcha{""}; cin >> captcha; int sum{solveCaptcha2(captcha)}; cout << "Sum of " << captcha << " is: " << sum << endl; return 0; }
24.614458
57
0.565835
IAmBullsaw
887bc69ffdd7ebd817942f6022addd0dd752630f
5,272
cc
C++
cpp_rgb_depth_sync_example/app/src/main/jni/camera_texture_drawable.cc
jimmysoda/tango-examples-c
a6db7947c4d95337a9155a3e0519aa219c385d19
[ "Apache-2.0" ]
344
2015-01-03T10:36:33.000Z
2018-02-20T12:02:16.000Z
cpp_rgb_depth_sync_example/app/src/main/jni/camera_texture_drawable.cc
JzHuai0108/tango-examples-c
51113f2d88d61749ea396b3f5a4bebbf7912327b
[ "Apache-2.0" ]
64
2015-01-21T17:16:31.000Z
2018-01-02T19:42:07.000Z
cpp_rgb_depth_sync_example/app/src/main/jni/camera_texture_drawable.cc
JzHuai0108/tango-examples-c
51113f2d88d61749ea396b3f5a4bebbf7912327b
[ "Apache-2.0" ]
192
2015-01-03T14:36:28.000Z
2018-03-01T05:28:21.000Z
/* * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <rgb-depth-sync/camera_texture_drawable.h> namespace { const GLfloat kVertices[] = {-1.0, 1.0, 0.0, -1.0, -1.0, 0.0, 1.0, 1.0, 0.0, 1.0, -1.0, 0.0}; const GLushort kIndices[] = {0, 1, 2, 2, 1, 3}; const GLfloat kTextureCoords0[] = {0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0}; const GLfloat kTextureCoords90[] = {1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0}; const GLfloat kTextureCoords180[] = {1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0}; const GLfloat kTextureCoords270[] = {0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0}; } // namespace namespace rgb_depth_sync { CameraTextureDrawable::CameraTextureDrawable() : shader_program_(0) {} CameraTextureDrawable::~CameraTextureDrawable() {} void CameraTextureDrawable::InitializeGL() { shader_program_ = tango_gl::util::CreateProgram(rgb_depth_sync::shader::kColorCameraVert, rgb_depth_sync::shader::kColorCameraFrag); if (!shader_program_) { LOGE("Could not create shader program for CameraImageDrawable."); } glGenBuffers(2, render_buffers_); // Allocate vertices buffer. glBindBuffer(GL_ARRAY_BUFFER, render_buffers_[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 3 * 4, kVertices, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); // Allocate triangle indices buffer. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, render_buffers_[1]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLushort) * 6, kIndices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // Assign the vertices attribute data. attrib_vertices_ = glGetAttribLocation(shader_program_, "vertex"); glBindBuffer(GL_ARRAY_BUFFER, render_buffers_[0]); glEnableVertexAttribArray(attrib_vertices_); glVertexAttribPointer(attrib_vertices_, 3, GL_FLOAT, GL_FALSE, 0, nullptr); glBindBuffer(GL_ARRAY_BUFFER, 0); // Assign the texture coordinates attribute data. attrib_texture_coords_ = glGetAttribLocation(shader_program_, "textureCoords"); color_texture_handle_ = glGetUniformLocation(shader_program_, "colorTexture"); depth_texture_handle_ = glGetUniformLocation(shader_program_, "depthTexture"); blend_alpha_handle_ = glGetUniformLocation(shader_program_, "blendAlpha"); } void CameraTextureDrawable::RenderImage( TangoSupport_Rotation camera_to_display_rotation) { if (shader_program_ == 0) { InitializeGL(); } glDisable(GL_DEPTH_TEST); glUseProgram(shader_program_); glUniform1f(blend_alpha_handle_, blend_alpha_); // Note that the Tango C-API update texture will bind the texture directly to // active texture, this is currently a bug in API, and because of that, we are // not getting any handle from shader neither binding any texture here. // Once this is fix, we will need to bind the texture to the correct sampler2D // handle. glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_EXTERNAL_OES, color_texture_id_); glUniform1i(color_texture_handle_, 0); // Bind depth texture to texture unit 1. glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, depth_texture_id_); glUniform1i(depth_texture_handle_, 1); // Bind vertices buffer. glBindBuffer(GL_ARRAY_BUFFER, render_buffers_[0]); glEnableVertexAttribArray(attrib_vertices_); glVertexAttribPointer(attrib_vertices_, 3, GL_FLOAT, GL_FALSE, 0, nullptr); glBindBuffer(GL_ARRAY_BUFFER, 0); glEnableVertexAttribArray(attrib_texture_coords_); switch (camera_to_display_rotation) { case TangoSupport_Rotation::TANGO_SUPPORT_ROTATION_90: glVertexAttribPointer(attrib_texture_coords_, 2, GL_FLOAT, GL_FALSE, 0, kTextureCoords90); break; case TangoSupport_Rotation::TANGO_SUPPORT_ROTATION_180: glVertexAttribPointer(attrib_texture_coords_, 2, GL_FLOAT, GL_FALSE, 0, kTextureCoords180); break; case TangoSupport_Rotation::TANGO_SUPPORT_ROTATION_270: glVertexAttribPointer(attrib_texture_coords_, 2, GL_FLOAT, GL_FALSE, 0, kTextureCoords270); break; default: glVertexAttribPointer(attrib_texture_coords_, 2, GL_FLOAT, GL_FALSE, 0, kTextureCoords0); break; } // Bind element array buffer. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, render_buffers_[1]); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0); tango_gl::util::CheckGlError("ColorCameraDrawable glDrawElements"); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glUseProgram(0); glActiveTexture(GL_TEXTURE0); tango_gl::util::CheckGlError("CameraTextureDrawable::render"); } } // namespace rgb_depth_sync
37.928058
80
0.725152
jimmysoda
887d6855c0d662ef850a463539d0e0246c91463c
541
cpp
C++
src/command/RenderWindowCommand.cpp
tody411/SimpleMeshViewer
25aa62371bf815316244387cb1a69a27b47f80c0
[ "MIT" ]
null
null
null
src/command/RenderWindowCommand.cpp
tody411/SimpleMeshViewer
25aa62371bf815316244387cb1a69a27b47f80c0
[ "MIT" ]
null
null
null
src/command/RenderWindowCommand.cpp
tody411/SimpleMeshViewer
25aa62371bf815316244387cb1a69a27b47f80c0
[ "MIT" ]
null
null
null
/*! \file RenderWindowCommand.cpp \author Tody RenderWindowCommand definition. date 2015/12/20 */ #include "RenderWindowCommand.h" #include <QFileDialog> void RenderWindowCommand::doImp () { if ( _outputFile == "" ) { _outputFile = QFileDialog::getSaveFileName ( nullptr, "Save Screen Shot", QString(), "Image File (*.png *.bmp *.tiff)" ); } if ( _outputFile == "" ) return; _win->renderScreenShot ( _outputFile ) ; _outputFile = ""; }
20.037037
61
0.569316
tody411
887f1664c29e830bcfde11052ab662a9c323950c
5,611
cpp
C++
src/slaggy-engine/slaggy-engine/engine/Shader.cpp
SlaggyWolfie/slaggy-engine
846235c93a52a96be85c5274a1372bc09c16f144
[ "MIT" ]
1
2021-09-24T23:13:13.000Z
2021-09-24T23:13:13.000Z
src/slaggy-engine/slaggy-engine/engine/Shader.cpp
SlaggyWolfie/slaggy-engine
846235c93a52a96be85c5274a1372bc09c16f144
[ "MIT" ]
null
null
null
src/slaggy-engine/slaggy-engine/engine/Shader.cpp
SlaggyWolfie/slaggy-engine
846235c93a52a96be85c5274a1372bc09c16f144
[ "MIT" ]
2
2020-06-24T07:10:13.000Z
2022-03-08T17:19:12.000Z
#include "Shader.hpp" #include <fstream> #include <sstream> #include <iostream> #include <glm/gtc/type_ptr.hpp> namespace slaggy { std::map<Shader::ShaderType, Shader::ShaderTypeInfo> Shader::_shaderTypes = { {ShaderType::VERTEX, {"VERTEX", GL_VERTEX_SHADER}}, {ShaderType::FRAGMENT, {"FRAGMENT", GL_FRAGMENT_SHADER}}, {ShaderType::GEOMETRY, {"GEOMETRY", GL_GEOMETRY_SHADER}} }; std::map<unsigned, unsigned> Shader::_idCounter; Shader::Shader(const std::string& vertexPath, const std::string& fragmentPath) { std::string vCode, fCode; read(vertexPath, vCode); read(fragmentPath, fCode); const unsigned int vID = compile(vCode, ShaderType::VERTEX); const unsigned int fID = compile(fCode, ShaderType::FRAGMENT); id = link({ vID, fID }); incrementCounter(); } Shader::Shader(const std::string& vertexPath, const std::string& geometryPath, const std::string& fragmentPath) { std::string vCode, fCode, gCode; read(vertexPath, vCode); read(fragmentPath, fCode); read(geometryPath, gCode); const unsigned int vID = compile(vCode, ShaderType::VERTEX); const unsigned int fID = compile(fCode, ShaderType::FRAGMENT); const unsigned int gID = compile(gCode, ShaderType::GEOMETRY); id = link({ vID, fID, gID }); incrementCounter(); } Shader::Shader(const std::string& path) : Shader ( std::string(path).append(".vert"), std::string(path).append(".frag") ) { } Shader::~Shader() { decrementCounter(); } void Shader::idReassign(const Shader& other) { decrementCounter(); id = other.id; incrementCounter(); } Shader::Shader(const Shader& other) { idReassign(other); } Shader::Shader(Shader&& other) noexcept { idReassign(other); } Shader& Shader::operator=(const Shader& other) { if (this == &other) return *this; idReassign(other); return *this; } Shader& Shader::operator=(Shader&& other) noexcept { idReassign(other); return *this; } void Shader::read(const std::string& path, std::string& code) { std::ifstream file; // > ensure ifstream objects can throw exceptions file.exceptions(std::ifstream::failbit | std::ifstream::badbit); //-----OPEN & READ-----// // Try to open and read the shader files // and place them into memory // ALTERNATIVE METHOD in MGE: read line-by-line and add it to a string try { // opening the files file.open(path); // setting up streams (reading pipelines ?) std::stringstream stream; // > read file's buffer contents into the stream stream << file.rdbuf(); // close file.close(); // place into memory code = stream.str(); } catch (std::ifstream::failure& exception) { std::cout << "ERROR::SHADER::FILE_NOT_SUCCESSFULLY_FOUND_OR_READ\n" << exception.what() << std::endl; // TODO fix shader failure not stopping the rest of the process //return; } } unsigned Shader::compile(const std::string& code, const ShaderType shaderType) { const char* code_c = code.c_str(); const ShaderTypeInfo& info = _shaderTypes[shaderType]; //-----COMPILE & LINK-----// unsigned int id = 0; int success = -1; char log[512]; // Vertex Shader id = glCreateShader(info.glID); glShaderSource(id, 1, &code_c, nullptr); glCompileShader(id); // print compilation errors glGetShaderiv(id, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(id, 512, nullptr, log); std::cout << "ERROR::SHADER::" << info.name << "::COMPILATION_FAILED\n" << log << std::endl; } return id; } unsigned Shader::link(const std::vector<unsigned>& shaderIds) { int success = -1; char log[512]; const unsigned int programID = glCreateProgram(); for (unsigned id : shaderIds) glAttachShader(programID, id); glLinkProgram(programID); glGetProgramiv(programID, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(programID, 512, nullptr, log); std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << log << std::endl; } for (unsigned id : shaderIds) glDeleteShader(id); return programID; } void Shader::use() const { glUseProgram(id); } void Shader::set(const std::string& name, const bool value) const { glUniform1i(location(name), static_cast<int>(value)); } void Shader::set(const std::string& name, const int value) const { glUniform1i(location(name), value); } void Shader::set(const std::string& name, const unsigned int value) const { glUniform1ui(location(name), value); } void Shader::set(const std::string& name, const float value) const { glUniform1f(location(name), value); } void Shader::set(const std::string& name, const glm::vec2& value) const { glUniform2fv(location(name), 1, glm::value_ptr(value)); } void Shader::set(const std::string& name, const glm::vec3& value) const { glUniform3fv(location(name), 1, glm::value_ptr(value)); } void Shader::set(const std::string& name, const glm::vec4& value) const { glUniform4fv(location(name), 1, glm::value_ptr(value)); } void Shader::set(const std::string& name, const glm::mat3& value) const { glUniformMatrix3fv(location(name), 1, GL_FALSE, glm::value_ptr(value)); } void Shader::set(const std::string& name, const glm::mat4& value) const { glUniformMatrix4fv(location(name), 1, GL_FALSE, glm::value_ptr(value)); } unsigned Shader::location(const std::string& name) const { return glGetUniformLocation(id, name.c_str()); } void Shader::incrementCounter() const { _idCounter[id]++; } void Shader::decrementCounter() const { _idCounter[id]--; if (_idCounter[id] == 0) glDeleteProgram(id); } }
22.716599
112
0.679023
SlaggyWolfie
8881516f07cb80f2fe4b38071deddf5a594c62a4
5,164
cpp
C++
2018/0325_ARC093/E.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
7
2019-03-24T14:06:29.000Z
2020-09-17T21:16:36.000Z
2018/0325_ARC093/E.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
null
null
null
2018/0325_ARC093/E.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
1
2020-07-22T17:27:09.000Z
2020-07-22T17:27:09.000Z
/** * File : E.cpp * Author : Kazune Takahashi * Created : 2018-3-25 21:58:58 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; const int MAX_SIZE = 1000010; const long long MOD = 1000000007; long long inv[MAX_SIZE]; long long fact[MAX_SIZE]; long long factinv[MAX_SIZE]; const int UFSIZE = 100010; int union_find[UFSIZE]; int root(int a) { if (a == union_find[a]) return a; return (union_find[a] = root(union_find[a])); } bool issame(int a, int b) { return root(a) == root(b); } void unite(int a, int b) { union_find[root(a)] = root(b); } bool isroot(int a) { return root(a) == a; } void init() { inv[1] = 1; for (int i=2; i<MAX_SIZE; i++) { inv[i] = ((MOD - inv[MOD%i]) * (MOD/i))%MOD; } fact[0] = factinv[0] = 1; for (int i=1; i<MAX_SIZE; i++) { fact[i] = (i * fact[i-1])%MOD; factinv[i] = (inv[i] * factinv[i-1])%MOD; } for (auto i=0; i<UFSIZE; i++) { union_find[i] = i; } } long long C(int n, int k) { if (n >=0 && k >= 0 && n-k >= 0) { return ((fact[n] * factinv[k])%MOD * factinv[n-k])%MOD; } return 0; } long long power(long long x, long long n) { if (n == 0) { return 1; } else if (n%2 == 1) { return (x * power(x, n-1)) % MOD; } else { long long half = power(x, n/2); return (half * half) % MOD; } } long long gcm(long long a, long long b) { if (a < b) { return gcm(b, a); } if (b == 0) return a; return gcm(b, a%b); } typedef tuple<ll, int, int> edge; typedef tuple<ll, int> path; int N, M; ll X; vector<edge> V; vector<path> T[1010]; vector<edge> W; path parent[10][1010]; int depth[1010]; void dfs(int v, int p, ll cost, int d) { parent[0][v] = path(cost, p); depth[v] = d; for (auto x : T[v]) { if (get<1>(x) != p) { dfs(get<1>(x), v, get<0>(x), d + 1); } } } void init2() { dfs(0, -1, 0, 0); for (auto k = 0; k+1 < 10; k++) { for (auto v = 0; v < N; v++) { if (get<1>(parent[k][v]) < 0) { parent[k + 1][v] = path(0, -1); } else { ll cost = get<0>(parent[k][v]); int u = get<1>(parent[k][v]); int new_u = get<1>(parent[k][u]); ll new_cost = max(cost, get<0>(parent[k][u])); parent[k + 1][v] = path(new_cost, new_u); #if DEBUG == 1 cerr << "parent[" << k + 1 << "][" << v << "] = (" << new_cost << ", " << new_u << ")" << endl; #endif } } } } ll lca(int u, int v) { if (depth[u] > depth[v]) swap(u, v); ll ans = 0; #if DEBUG == 1 cerr << "depth[" << u << "] = " << depth[u] << ", depth[" << v << "] = " << depth[v] << endl; #endif for (auto k = 0; k < 10; k++) { if ((depth[v] - depth[u]) >> k & 1) { ans = max(ans, get<0>(parent[k][v])); v = get<1>(parent[k][v]); } } if (u == v) return ans; for (auto k = 9; k >= 0; k--) { if (get<1>(parent[k][u]) != get<1>(parent[k][v])) { ans = max(ans, get<0>(parent[k][u])); ans = max(ans, get<0>(parent[k][v])); u = get<1>(parent[k][u]); v = get<1>(parent[k][v]); } } ans = max(ans, get<0>(parent[0][v])); ans = max(ans, get<0>(parent[0][u])); return ans; } int main() { init(); cin >> N >> M; cin >> X; for (auto i = 0; i < M; i++) { int u, v; ll w; cin >> u >> v >> w; u--; v--; V.push_back(edge(w, u, v)); } sort(V.begin(), V.end()); ll Y = 0; for (auto e : V) { ll cost = get<0>(e); int u = get<1>(e); int v = get<2>(e); if (!issame(u, v)) { unite(u, v); T[u].push_back(path(cost, v)); T[v].push_back(path(cost, u)); Y += cost; } else { W.push_back(e); } } #if DEBUG == 1 cerr << "X = " << X << ", Y = " << Y << endl; #endif if (X < Y) { cout << 0 << endl; return 0; } ll ans = 0; ll K = N - 1; ll L = W.size(); if (X == Y) { ans = (((power(2, K) + MOD - 2) % MOD) * power(2, L)) % MOD; } #if DEBUG == 1 cerr << "L = " << L << ", ans = " << ans << endl; #endif init2(); ll L1 = 0; ll L2 = 0; for (auto e : W) { ll cost = get<0>(e); int u = get<1>(e); int v = get<2>(e); ll temp = cost - lca(u, v); if (temp < X - Y) L2++; else if (temp == X - Y) L1++; } #if DEBUG == 1 cerr << "L1 = " << L1 << ", L2 = " << L2 << endl; #endif ans += (2 * (power(2, L - L2) + MOD - power(2, L - L2 - L1))) % MOD; ans %= MOD; cout << ans << endl; }
19.785441
103
0.480442
kazunetakahashi
88842f01a273fce974ec20e86b3a43e9eedd4796
1,412
cpp
C++
src/problem79/Solution.cpp
MyYaYa/leetcode
d779c215516ede594267b15abdfba5a47dc879dd
[ "Apache-2.0" ]
1
2016-09-29T14:23:59.000Z
2016-09-29T14:23:59.000Z
src/problem79/Solution.cpp
MyYaYa/leetcode
d779c215516ede594267b15abdfba5a47dc879dd
[ "Apache-2.0" ]
null
null
null
src/problem79/Solution.cpp
MyYaYa/leetcode
d779c215516ede594267b15abdfba5a47dc879dd
[ "Apache-2.0" ]
null
null
null
class Solution { public: bool exist(vector<vector<char>>& board, string word) { len = word.size(); if (len == 0) { return false; } row = board.size(); if (row == 0) return false; col = board[0].size(); if (col == 0) return false; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (backtrack(board, word, 0, i, j)) return true; } } return false; } private: int len; int row; int col; bool backtrack(vector<vector<char>>& board, string& word, int w_start, int b_row, int b_col) { if (w_start == len) return true; if (b_row < 0 || b_row >= row || b_col < 0 || b_col >= col) return false; if (board[b_row][b_col] == word[w_start]) { char t = board[b_row][b_col]; board[b_row][b_col] = '\0'; if (backtrack(board, word, w_start+1, b_row+1, b_col) || \ backtrack(board, word, w_start+1, b_row-1, b_col) || \ backtrack(board, word, w_start+1, b_row, b_col+1) || \ backtrack(board, word, w_start+1, b_row, b_col-1)) { return true; } else { board[b_row][b_col] = t; } } return false; } };
31.377778
98
0.445467
MyYaYa
88858ae7961ecbe1d2a6028711cbfbdb154ef098
14,290
cpp
C++
tests/algorithms/QAOATester.cpp
Milos9304/Quacc
f9ba6076a4d55286d61684fdadf92164cfc5bff0
[ "MIT" ]
1
2021-03-02T11:14:43.000Z
2021-03-02T11:14:43.000Z
tests/algorithms/QAOATester.cpp
Milos9304/Quacc
f9ba6076a4d55286d61684fdadf92164cfc5bff0
[ "MIT" ]
null
null
null
tests/algorithms/QAOATester.cpp
Milos9304/Quacc
f9ba6076a4d55286d61684fdadf92164cfc5bff0
[ "MIT" ]
null
null
null
/******************************************************************************* * Copyright (c) 2020 UT-Battelle, LLC. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v1.0 which accompanies this * distribution. The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution *License is available at https://eclipse.org/org/documents/edl-v10.php * * Contributors: * Thien Nguyen - initial API and implementation * Milos Prokop - test evaluate_assignment *******************************************************************************/ #include <random> #include <gtest/gtest.h> //#include "../qaoa.hpp" #include "xacc.hpp" #include "Algorithm.hpp" #include "Observable.hpp" #include "xacc_service.hpp" #include "xacc_observable.hpp" using namespace xacc; /* TEST(QAOATester, checkSimple) { auto acc = xacc::getAccelerator("quest", {std::make_pair("nbQbits", 2)}); auto buffer = xacc::qalloc(2); auto optimizer = xacc::getOptimizer("nlopt"); auto qaoa = xacc::getService<Algorithm>("QAOA"); // Create deuteron Hamiltonian auto H_N_2 = xacc::quantum::getObservable( "pauli", std::string("5.907 - 2.1433 X0X1 " "- 2.1433 Y0Y1" "+ .21829 Z0 - 6.125 Z1")); EXPECT_TRUE(qaoa->initialize({std::make_pair("accelerator", acc), std::make_pair("optimizer", optimizer), std::make_pair("observable", H_N_2), std::make_pair("calc-var-assignment", true), std::make_pair("simplified-simulation", true), //Number of samples to estimate optimal variable assignment std::make_pair("nbSamples", 1024), // number of time steps (p) param std::make_pair("steps", 2)})); qaoa->execute(buffer); // The optimal value (minimal energy) must be less than -1.74886 // which is the result from VQE using a physical ansatz. // In QAOA, we don't have any physical constraints, hence, // it can find a solution that gives a lower cost function value. std::cout << "Opt-val = " << (*buffer)["opt-val"].as<double>() << "\n"; std::cout << "Opt-config = " << (*buffer)["opt-config"].as<std::string>() << "\n"; EXPECT_LT((*buffer)["opt-val"].as<double>(), -1.74); } TEST(QAOATester, checkStandardParamterizedScheme) { auto acc = xacc::getAccelerator("quest", {std::make_pair("nbQbits", 2)}); auto buffer = xacc::qalloc(2); auto optimizer = xacc::getOptimizer("nlopt"); auto qaoa = xacc::getService<Algorithm>("QAOA"); // Create deuteron Hamiltonian auto H_N_2 = xacc::quantum::getObservable( "pauli", std::string("5.907 - 2.1433 X0X1 " "- 2.1433 Y0Y1" "+ .21829 Z0 - 6.125 Z1")); EXPECT_TRUE( qaoa->initialize({std::make_pair("accelerator", acc), std::make_pair("optimizer", optimizer), std::make_pair("observable", H_N_2), std::make_pair("calc-var-assignment", true), std::make_pair("simplified-simulation", true), //Number of samples to estimate optimal variable assignment std::make_pair("nbSamples", 1024), // number of time steps (p) param std::make_pair("steps", 4), std::make_pair("parameter-scheme", "Standard")})); qaoa->execute(buffer); std::cout << "Opt-val = " << (*buffer)["opt-val"].as<double>() << "\n"; std::cout << "Opt-config = " << (*buffer)["opt-config"].as<std::string>() << "\n"; EXPECT_LT((*buffer)["opt-val"].as<double>(), -1.58); } */ TEST(QAOATester, check_evaluate_assignment) { // // Tests the QAOA::evaluate_assignment function. The parameters of QAOA are deliberately very UNperformant such that the resulting state will not be far from initial state // and hence after many shots we expect to get all possible assignments. // //xacc::setOption("quest-verbose", "true"); //xacc::setOption("quest-debug", "true"); const int num_qubits = 3; const int num_terms = 7; std::string hamiltonian[num_terms][3] = {{ "-5", "", ""}, { "2", "Z0", ""}, { "3", "Z1", ""}, { "-1", "Z2", ""}, { "-4", "Z0", "Z1"}, { "7", "Z1", "Z2"}, {"0.4", "Z0", "Z2"} }; std::string hamiltonian_str = hamiltonian[0][0] + " "; for(size_t i = 1; i < num_terms; ++i){ hamiltonian_str += "+ "; for(size_t i2 = 0; i2 < 3; i2++) hamiltonian_str += hamiltonian[i][i2] + " "; } auto acc = xacc::getAccelerator("quest", {std::make_pair("nbQbits", num_qubits)}); auto buffer = xacc::qalloc(num_qubits); auto observable = xacc::quantum::getObservable("pauli", hamiltonian_str); const int nbParams = observable -> getNonIdentitySubTerms().size() + observable->nBits();; std::vector<double> initialParams; // Init random parameters for(int i = 0; i < nbParams; ++i){ initialParams.emplace_back(0); } auto optimizer = xacc::getOptimizer("nlopt", xacc::HeterogeneousMap { std::make_pair("initial-parameters", initialParams), std::make_pair("nlopt-maxeval", 1) }); auto qaoa = xacc::getService<xacc::Algorithm>("QAOA"); qaoa->initialize({ std::make_pair("accelerator", acc), std::make_pair("optimizer", optimizer), std::make_pair("observable", observable), std::make_pair("calc-var-assignment", true), std::make_pair("simplified-simulation", true), //Number of samples to estimate optimal variable assignment std::make_pair("nbSamples", 1024), // number of time steps (p) param std::make_pair("steps", 1), std::make_pair("calc-var-assignment", true), std::make_pair("nbSamples", 1) }); qaoa->execute(buffer); std::string meas = (*buffer)["opt-config"].as<std::string>(); double expected_result = 0.; for(size_t i = 0; i < num_terms; ++i){ auto term = hamiltonian[i]; if(term[1] == ""){ //identity term expected_result += std::stod(term[0]); }else if(term[2] == ""){ //single-Z term int qbit = std::stoi(term[1].substr(1)); expected_result += (meas[qbit] == '1' ? -1 : 1) * std::stod(term[0]); }else{ //double-Z term int qbit1 = std::stoi(term[1].substr(1)); int qbit2 = std::stoi(term[2].substr(1)); expected_result += (meas[qbit1] == '1' ? -1 : 1) * (meas[qbit2] == '1' ? -1 : 1) * std::stod(term[0]); } } EXPECT_NEAR((*buffer)["opt-val"].as<double>(), expected_result, 1e-1); } // Generate random auto random_vector(const double l_range, const double r_range, const std::size_t size) { // Generate a random initial parameter set std::random_device rnd_device; std::mt19937 mersenne_engine{rnd_device()}; // Generates random integers std::uniform_real_distribution<double> dist{l_range, r_range}; auto gen = [&dist, &mersenne_engine]() { return dist(mersenne_engine); }; std::vector<double> vec(size); std::generate(vec.begin(), vec.end(), gen); return vec; } TEST(QAOATester, checkP1TriangleGraph) { //xacc::setOption("quest-verbose", "true"); //xacc::setOption("quest-debug", "true"); auto acc = xacc::getAccelerator("quest", {std::make_pair("nbQbits", 3)}); //acc->updateShotsNumber(-1); auto optimizer = xacc::getOptimizer( "nlopt", {{"maximize", true}, {"initial-parameters", random_vector(-2., 2., 2)}}); auto H = xacc::quantum::getObservable( "pauli", std::string("1.5 I - 0.5 Z0 Z1 - 0.5 Z0 Z2 - 0.5 Z1 Z2")); auto qaoa = xacc::getAlgorithm("QAOA", {{"accelerator", acc}, {"optimizer", optimizer}, {"observable", H}, {"steps", 1}, //{"calc-var-assignment", true}, {"simplified-simulation", false}, {"nbSamples", 1024}, {"parameter-scheme", "Standard"}}); auto all_betas = xacc::linspace(-xacc::constants::pi / 4., xacc::constants::pi / 4., 20); auto all_gammas = xacc::linspace(-xacc::constants::pi, xacc::constants::pi, 20); for (auto gamma : all_gammas) { for (auto beta : all_betas) { auto buffer = xacc::qalloc(3); auto cost = qaoa->execute(buffer, std::vector<double>{gamma, beta})[0]; auto d = 1; auto e = 1; auto f = 1; auto theory = 3 * (.5 + .25 * std::sin(4 * beta) * std::sin(gamma) * (std::cos(gamma) + std::cos(gamma)) - .25 * std::sin(2 * beta) * std::sin(2 * beta) * (std::pow(std::cos(gamma), d + e - 2 * f)) * (1 - std::cos(2 * gamma))); EXPECT_NEAR(cost, theory, 1e-3); } } } // Making sure that a set of Hadamards can be passed // as the "initial-state" to the QAOA algorithm and // the proper result is returned TEST(QAOATester, checkInitialStateConstruction) { auto acc = xacc::getAccelerator("quest", {std::make_pair("nbQbits", 2)}); auto buffer = xacc::qalloc(2); auto optimizer = xacc::getOptimizer("nlopt", {{"initial-parameters", random_vector(-2., 2., 8)}}); auto qaoa = xacc::getService<Algorithm>("QAOA"); // Create deuteron Hamiltonian auto H_N_2 = xacc::quantum::getObservable( "pauli", std::string("5.907 - 2.1433 X0X1 " "- 2.1433 Y0Y1" "+ .21829 Z0 - 6.125 Z1")); auto provider = getIRProvider("quantum"); auto initial_program = provider->createComposite("qaoaKernel"); for (size_t i = 0; i < buffer->size(); i++) { initial_program->addInstruction(provider->createInstruction("H", { i })); } EXPECT_TRUE( qaoa->initialize({std::make_pair("accelerator", acc), std::make_pair("optimizer", optimizer), std::make_pair("observable", H_N_2), // number of time steps (p) param std::make_pair("steps", 4), std::make_pair("initial-state", initial_program), std::make_pair("parameter-scheme", "Standard")})); qaoa->execute(buffer); std::cout << "Opt-val = " << (*buffer)["opt-val"].as<double>() << "\n"; EXPECT_LT((*buffer)["opt-val"].as<double>(), -1.5); } // Making sure that warm-starts can be initialized and run. // TODO: Check that there are the same amount of either Rx or Rz // gates as there are qubits. (Each qubit is assigned an Rx and Rz) TEST(QAOATester, checkWarmStarts) { auto acc = xacc::getAccelerator("quest", {std::make_pair("nbQbits", 3)}); auto buffer = xacc::qalloc(3); int size = buffer->size(); auto optimizer = xacc::getOptimizer("nlopt", {{"maximize",true},{"initial-parameters", random_vector(-2., 2., 2)}}); auto qaoa = xacc::getService<Algorithm>("maxcut-qaoa"); auto graph = xacc::getService<xacc::Graph>("boost-digraph"); // Triangle graph for (int i = 0; i < 3; i++) { graph->addVertex(); } graph->addEdge(0, 1); graph->addEdge(0, 2); graph->addEdge(1, 2); const bool initOk = qaoa->initialize( {std::make_pair("accelerator", acc), std::make_pair("optimizer", optimizer), std::make_pair("graph", graph), // number of time steps (p) param std::make_pair("steps", 1), // "Standard" or "Extended" std::make_pair("initialization", "warm-start"), std::make_pair("parameter-scheme", "Standard")}); qaoa->execute(buffer); std::cout << "Opt-val: " << (*buffer)["opt-val"].as<double>() << "\n"; //EXPECT_LT(nbRxgates, buffer->size()); } // Testing if a weighted graph can be constructed and passed // to the maxcut-qaoa algorithm with the correct result returned. TEST(QAOATester, checkWeightedQAOA) { auto acc = xacc::getAccelerator("quest", {std::make_pair("nbQbits", 3)}); auto buffer = xacc::qalloc(3); // xacc::set_verbose(true); int size = buffer->size(); auto optimizer = xacc::getOptimizer("nlopt", {{"maximize", true}, {"initial-parameters", random_vector(-2., 2., 2)}}); auto qaoa = xacc::getService<Algorithm>("maxcut-qaoa"); auto graph = xacc::getService<xacc::Graph>("boost-digraph"); // Triangle graph for (int i = 0; i < 3; i++) { graph->addVertex(); } graph->addEdge(0, 1, 0.15); graph->addEdge(0, 2, 0.85); const bool initOk = qaoa->initialize( {std::make_pair("accelerator", acc), std::make_pair("optimizer", optimizer), std::make_pair("graph", graph), // number of time steps (p) param std::make_pair("steps", 1), // "Standard" or "Extended" std::make_pair("parameter-scheme", "Standard")}); qaoa->execute(buffer); std::cout << "Min Val: " << (*buffer)["opt-val"].as<double>() << "\n"; } TEST(QAOATester, checkMaxCut) { auto acc = xacc::getAccelerator("quest", {std::make_pair("nbQbits", 3)}); auto buffer = xacc::qalloc(3); // xacc::set_verbose(true); auto optimizer = xacc::getOptimizer("nlopt", {{"maximize", true}, {"initial-parameters", random_vector(-2., 2., 2)}}); auto qaoa = xacc::getService<Algorithm>("maxcut-qaoa"); auto graph = xacc::getService<xacc::Graph>("boost-digraph"); // Triangle graph for (int i = 0; i < 3; i++) { graph->addVertex(); } graph->addEdge(0, 1); graph->addEdge(0, 2); graph->addEdge(1, 2); const bool initOk = qaoa->initialize( {std::make_pair("accelerator", acc), std::make_pair("optimizer", optimizer), std::make_pair("graph", graph), // number of time steps (p) param std::make_pair("steps", 1), // "Standard" or "Extended" std::make_pair("parameter-scheme", "Standard")}); qaoa->execute(buffer); std::cout << "Opt-val: " << (*buffer)["opt-val"].as<double>() << "\n"; EXPECT_NEAR((*buffer)["opt-val"].as<double>(), 2.0, 1e-3); } int main(int argc, char **argv) { xacc::Initialize(); //xacc::setOption("quest-verbose", "true"); //xacc::setOption("quest-testing", "true"); ::testing::InitGoogleTest(&argc, argv); auto ret = RUN_ALL_TESTS(); xacc::Finalize(); return ret; }
38.005319
172
0.589363
Milos9304
8888712d33dd1ac907427e6d70c7b735db6dce07
3,491
cpp
C++
sketches/signpost/samd21timerirq.cpp
xdylanm/signpost
20622b2928f1955f84882a255f6262f5392b700d
[ "MIT" ]
null
null
null
sketches/signpost/samd21timerirq.cpp
xdylanm/signpost
20622b2928f1955f84882a255f6262f5392b700d
[ "MIT" ]
null
null
null
sketches/signpost/samd21timerirq.cpp
xdylanm/signpost
20622b2928f1955f84882a255f6262f5392b700d
[ "MIT" ]
null
null
null
#include "samd21timerirq.h" hw_timer_t tcCreate(int id, uint32_t timer_period_us, bool one_shot) { // source clock is always 0 // the same source clock is muxed between TC pairs: [TCC2, TC3], [TC4, TC5] // Not sure how to support 32 bit clock with interrupt (should pair TC4+TC5 but that didn't work) hw_timer_t timer; timer.one_shot = one_shot; // clock period ticks = 1024 clocks / (SystemCoreClock clocks/sec) * (1000000 us/sec) * (1/us)) timer.period_ticks = (timer_period_us * TCX_CPU_MHZ) / TCX_PRESCALER; // currently can't support >16 bit clocks (up to 1s) if (timer.period_ticks >= (1 << 16)) { return timer; } if (id == 3) { timer.TC = TC3; timer.clkctrl_reg = (uint16_t) (GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK0 | GCLK_CLKCTRL_ID_TCC2_TC3); timer.irqn_lbl = TC3_IRQn; } else if (id == 4) { timer.TC = TC4; timer.clkctrl_reg = (uint16_t) (GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK0 | GCLK_CLKCTRL_ID_TC4_TC5); timer.irqn_lbl = TC4_IRQn; } else if (id == 5) { timer.TC = TC5; timer.clkctrl_reg = (uint16_t) (GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK0 | GCLK_CLKCTRL_ID_TC4_TC5); timer.irqn_lbl = TC5_IRQn; } else { return timer; } return timer; } bool tcConfigure(hw_timer_t& timer) { if (!timer.TC) { return false; } // select the generic clock generator used as source to the generic clock multiplexer GCLK->CLKCTRL.reg = timer.clkctrl_reg; while (GCLK->STATUS.bit.SYNCBUSY); //tcReset(timer); //reset bool const is_16bit = timer.period_ticks < (1 << 16); if (!is_16bit) { return false; } // Set Timer counter Mode to 16 bits, it will become a 16bit counter ('mode1' in the datasheet) timer.TC->COUNT16.CTRLA.reg |= TC_CTRLA_MODE_COUNT16; // Set TCx waveform generation mode to 'match frequency' timer.TC->COUNT16.CTRLA.reg |= TC_CTRLA_WAVEGEN_MFRQ; //set prescaler //the clock normally counts at the GCLK_TC frequency, but we can set it to divide that frequency to slow it down //you can use different prescaler divisons here like TC_CTRLA_PRESCALER_DIV1 to get a different range timer.TC->COUNT16.CTRLA.reg |= TC_CTRLA_PRESCALER_DIV1024 | TC_CTRLA_ENABLE; //it will divide GCLK_TC frequency by 1024 if (timer.one_shot) { timer.TC->COUNT16.CTRLBSET.reg |= TC_CTRLBSET_ONESHOT; } //set the compare-capture register. //The counter will count up to this value (it's a 16bit counter so we use uint16_t) //this is how we fine-tune the frequency, make it count to a lower or higher value timer.TC->COUNT16.CC[0].reg = (uint16_t) timer.period_ticks; while (timer.TC->COUNT16.STATUS.bit.SYNCBUSY); // Configure interrupt request NVIC_EnableIRQ(timer.irqn_lbl); // Enable the TCx interrupt request timer.TC->COUNT16.INTENSET.bit.MC0 = 1; while (timer.TC->COUNT16.STATUS.bit.SYNCBUSY); return true; } void tcStartCounter(hw_timer_t& timer) { if (!timer.TC) { return; } timer.TC->COUNT16.CTRLA.reg |= TC_CTRLA_ENABLE; //set the CTRLA register while (timer.TC->COUNT16.STATUS.bit.SYNCBUSY); } //Reset TC void tcReset(hw_timer_t& timer) { if (!timer.TC) { return; } timer.TC->COUNT16.CTRLA.reg = TC_CTRLA_SWRST; while (timer.TC->COUNT16.STATUS.bit.SYNCBUSY); while (timer.TC->COUNT16.CTRLA.bit.SWRST); } //disable TC void tcDisable(hw_timer_t& timer) { if (!timer.TC) { return; } timer.TC->COUNT16.CTRLA.reg &= ~TC_CTRLA_ENABLE; while (timer.TC->COUNT16.STATUS.bit.SYNCBUSY); }
31.169643
121
0.704383
xdylanm
888fc2cdf3f2a91c41eecd862c3158cb33cb5fa2
782
cpp
C++
src/shared/PstAll.cpp
zibneuro/cortexinsilico
d75d1410124b0d2fce83f00987950729bb45736f
[ "MIT" ]
1
2018-07-04T12:37:23.000Z
2018-07-04T12:37:23.000Z
src/shared/PstAll.cpp
zibneuro/cortexinsilico
d75d1410124b0d2fce83f00987950729bb45736f
[ "MIT" ]
null
null
null
src/shared/PstAll.cpp
zibneuro/cortexinsilico
d75d1410124b0d2fce83f00987950729bb45736f
[ "MIT" ]
3
2019-01-02T10:46:10.000Z
2022-02-08T12:56:45.000Z
#include "PstAll.h" #include <QFile> #include <QTextStream> void PstAll::load(QString filename) { QFile file(filename); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { const QString msg = QString("Error reading features file. Could not open file %1") .arg(filename); throw std::runtime_error(qPrintable(msg)); } QTextStream in(&file); in.readLine(); QString line = in.readLine(); line = in.readLine(); while (!line.isNull()) { QStringList parts = line.split(','); PstAllProps props; props.SID = parts[0].toInt(); props.exc = parts[1].toFloat(); props.inh = parts[2].toFloat(); mPstAll[props.SID] = props; line = in.readLine(); } } PstAllProps PstAll::get(int SID) { return mPstAll[SID]; }
25.225806
70
0.630435
zibneuro
889048e718aec3cb4029716789daa16ce803a323
1,071
cpp
C++
src/measurecurrent.cpp
WAAM-UFJF/Ensaio-Frequencia
7063eb764872f5039c5ce203c894402d7edaab46
[ "MIT" ]
null
null
null
src/measurecurrent.cpp
WAAM-UFJF/Ensaio-Frequencia
7063eb764872f5039c5ce203c894402d7edaab46
[ "MIT" ]
null
null
null
src/measurecurrent.cpp
WAAM-UFJF/Ensaio-Frequencia
7063eb764872f5039c5ce203c894402d7edaab46
[ "MIT" ]
null
null
null
#include <Arduino.h> #include <Adafruit_INA219.h> // Definição do sensor de corrente e tensão. Adafruit_INA219 ina219_0 (0x40); // Define o valor de amostras para a media movel static const int N = 128; static const float n = 1.0/N; static float mediaMovel[N]; static int contador=0; void inicializaINA(){ while (1){ if(ina219_0.begin()){ break; } Serial.println("Falha ao encontrar o INA219"); delay(20); } ina219_0.setCalibration_16V_400mA(); } void measureCurrent(){ float corrente = 0, correnteFiltrada = 0; contador++; corrente = ina219_0.getCurrent_mA(); mediaMovel[(contador-1)%N] = corrente; if(contador < N){ for(int i=0; i<contador+1;i++){ correnteFiltrada += mediaMovel[i]; } correnteFiltrada = correnteFiltrada/contador; } else{ for(int i=0; i<N; i++){ correnteFiltrada += mediaMovel[i]; } correnteFiltrada = correnteFiltrada*n; } Serial.print(correnteFiltrada); Serial.print(";"); }
22.787234
54
0.612512
WAAM-UFJF
88906223a4d3d9e5c88edaf0266e2134e5a36e9c
9,716
cpp
C++
Sources Age of Enigma/Scene_Island_Dive.cpp
calidrelle/Gamecodeur
4449ea1dce02b8f08e39d258d864546fcc9b2fc6
[ "CC0-1.0" ]
29
2016-05-04T08:22:46.000Z
2022-01-27T10:20:55.000Z
Sources Age of Enigma/Scene_Island_Dive.cpp
calidrelle/Gamecodeur
4449ea1dce02b8f08e39d258d864546fcc9b2fc6
[ "CC0-1.0" ]
1
2018-11-25T14:12:39.000Z
2018-11-25T14:12:39.000Z
Sources Age of Enigma/Scene_Island_Dive.cpp
calidrelle/Gamecodeur
4449ea1dce02b8f08e39d258d864546fcc9b2fc6
[ "CC0-1.0" ]
49
2016-04-29T19:43:42.000Z
2022-02-19T16:13:35.000Z
/* * SceneFondMarin.cpp * * Created by Rockford on 19/04/10. * Copyright 2010 Casual Games France. All rights reserved. * */ #include "EScene.h" #include "Scene_Island_Dive.h" #include "ESceneDirector.h" #include "SoundBank.h" #include "MyGame.h" #include <string> #include "EMiniJeuTemplate.h" #include "GlobalBank.h" SceneFondMarin::SceneFondMarin(ESceneDirector *lpSceneDirector) : EScene(lpSceneDirector) { _bDiveEnd = false; _lpAnimTempoBenitier = new KCounter; _lpAnimApnee = new KCounter; /* Load font */ EMiniJeuTemplate::Preload(); } SceneFondMarin::~SceneFondMarin() { XDELETE(_lpAnimTempoBenitier); XDELETE(_lpAnimApnee); XDELETE(_lpFont); } void SceneFondMarin::Init() { _lpFont = EFontBank::getFont("NITECLUB.TTF",200); // 1ère visite if (!TaskResolved("task_island_dive_visit")) { ResolveTask("task_island_dive_visit"); AddObjective("island","key"); AddHint("island","key","how"); } // Bénitier fermé à l'arrivée if (!TaskResolved("task_island_clamwood")) { AddTask("task_island_clamwood"); _bBenitierOpen = false; SetVisible("benitieropen", false); SetVisible("benitierclose", true); } else { _bBenitierOpen = true; SetVisible("benitieropen", true); SetVisible("woodin", true); SetVisible("benitierclose", false); if (TaskResolved("task_island_getkey")) { SetVisible("dive_pearl", true); } else { SetVisible("dive_key", true); } } SetupItem("island_shovelhead"); // Le baton au sol if (!TestGlobal("woodout")) { SetVisible("woodout", true); } else { SetVisible("woodout", false); } // StartAnimation("sharkanim"); StartAnimation("fishbanc1P2P"); // StartAnimation("wavesanim"); StartAnimation("fish1animrot"); StartAnimation("fish1animp2p"); _lpSndDive = ESoundBank::getSound("island_dive"); _lpSndDive->playSample(); // Animation ouverture / fermeture du bénitier _lpAnimTempoBenitier->startCounter(0, 1, 0, 5000, K_COUNTER_LINEAR); // 30 secondes d'apnée !! _lpAnimApnee->startCounter(30, 0, 0, 30000, K_COUNTER_LINEAR); // Musique apnée _lpSceneDirector->ChangeMusic(DIRECTOR_MUSIC_DIVE30); if (TaskResolved("task_island_getkey") && TaskResolved("island_shovelhead")) { _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("ISLAND_DIVE_MURRAY_DONE") ,"",true); } } void SceneFondMarin::Check() { EScene::Check(); #ifdef SCENE_SHORTCUT if (KInput::isPressed(K_VK_F5)) { _lpSceneDirector->GoToScene("menu"); } #endif } void SceneFondMarin::Logic() { EScene::Logic(); } void SceneFondMarin::Draw() { EScene::Draw(); // Anims // On n'avance que si aucun mini jeu n'est affiché if (_lpSceneDirector->GetCurrentMinigame() == NULL) { double fElapsed = MyGame::getGame()->getKWindow()->getFrameTime(); _lpAnimApnee->move(fElapsed); _lpAnimTempoBenitier->move(fElapsed); } // Si l'anim du bénitier est finie, on inverse l'état du bénitier et on reprend if (!TaskResolved("task_island_clamwood")) { if (_lpAnimTempoBenitier->isCompleted()) { if (_bBenitierOpen ) { _bBenitierOpen = false; SetVisible("benitieropen", false); SetVisible("dive_key", false); SetVisible("dive_pearl", false); SetVisible("benitierclose", true); StopEmitter("bubbles"); } else { _bBenitierOpen = true; SetVisible("benitieropen", true); if (TaskResolved("task_island_getkey")) { SetVisible("dive_pearl", true); } else { SetVisible("dive_key", true); } SetVisible("benitierclose", false); StartEmitter("bubbles"); } _lpAnimTempoBenitier->startCounter(0, 30, 0, 5000, K_COUNTER_LINEAR); } } // Si l'apnée est finit, on sort ! if (_lpAnimApnee->isCompleted() && _bDiveEnd == false) { _bDiveEnd = true; _lpSceneDirector->PlayDirectorSound("diveend"); _lpSceneDirector->GoToScene("island_beach"); } // Affiche le temps restant d'Apnée std::string str; str = itos(int(_lpAnimApnee->getCurrentValue())); if (int(_lpAnimApnee->getCurrentValue()) < 10) { _lpFont->drawStringCentered(str.c_str(), 750, 1024, 20); } else { std::string u = str.substr(1,1); str = str.substr(0,1); float cx = (1024-750)/2 + 750; _lpFont->drawStringFromRight(str.c_str(),cx, 20); _lpFont->drawStringFromLeft(u.c_str(),cx, 20); } } void SceneFondMarin::Close() { _lpSndDive->stopSample(); } bool SceneFondMarin::ObjectClicked(const char *szObjectName, float x, float y) { if (strcmp(szObjectName, "benitieropen") == 0 || strcmp(szObjectName, "benitierclose") == 0) { if (_bBenitierOpen) { // Referme le bénitier _lpAnimTempoBenitier->move(99999); _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("ISLAND_DIVE_MURRAY_WHY"), "", true); return true; } } if (strcmp(szObjectName, "dive_key") == 0) { // Referme le bénitier _lpAnimTempoBenitier->move(99999); // TODO:Animer 2 bouts de baton ? if (TaskResolved("task_island_clamwood")) { _lpSceneDirector->getSequencer()->PlaySound(NULL, "brokenstick"); _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("ISLAND_DIVE_MURRAY_STICKNOT"), "", true); // On annule la tâche ResetTask("task_island_clamwood"); SetVisible("woodin", false); SetVisible("woodout", true); SetGlobal("woodout","0"); // Remet l'objet au sol } else { _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("ISLAND_DIVE_MURRAY_WHY"), "", true); } return true; } if (strcmp(szObjectName, "woodout") == 0) { PickupSimple(szObjectName, "inv_island_wood"); return true; } if (strcmp(szObjectName, "island_shovelhead") == 0) { PickupMultiple(szObjectName, "inv_island_shovelhead",-1); return true; } if (strcmp(szObjectName, "woodin") == 0) { _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("ISLAND_DIVE_MURRAY_STICK"), "", true); return true; } if (strcmp(szObjectName, "dive_pearl") == 0) { _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("ISLAND_DIVE_MURRAY_PEARL"), "", true); return true; } _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("ISLAND_DIVE_MURRAY_BLOUP"), "", true); return false; } bool SceneFondMarin::ObjectOver(char *szObjectName, float x, float y) { return false; } /* Un objet de l'inventaire est utilisé sur un objet de la scène */ bool SceneFondMarin::ItemUsed(const char *szItemName, const char *szObjectName) { // Le joueur utilise la perle dans le bénitier ouvert if ( strcmp(szItemName, "inv_island_pearl") == 0 ) { if (_lpAnimApnee->getCurrentValue() > 3.0f) { if ((strcmp(szObjectName, "dive_key") == 0 || strcmp(szObjectName, "benitieropen") == 0) && TaskResolved("task_island_clamwood")) { // On peut maintenant retirer l'objet de l'inventaire _lpSceneDirector->DropItem("inv_pearl"); // On a obtenu la clé ! ESoundBank::getSound("success")->playSample(); int x, y; GetObjectPosition("dive_key", x, y, false, false); _lpSceneDirector->getSequencer()->ShowImage(NULL,"dive_key", false); _lpSceneDirector->getSequencer()->PickupItem(NULL, "inv_island_key", (float)x, (float)y, 1); _lpSceneDirector->getSequencer()->ShowImage(NULL, "dive_pearl", true); _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("ISLAND_DIVE_MURRAY_SUCCESS") ,"",true); ResolveTask("task_island_getkey"); ResolveObjective("island","key"); _lpSceneDirector->DropItem("inv_island_pearl"); return true; } else if (strcmp(szObjectName, "dive_key") == 0 && !TaskResolved("task_island_clamwood")) { // Referme le bénitier _lpAnimTempoBenitier->move(99999); // TODO:Animer 2 bouts de baton ? _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("ISLAND_DIVE_MURRAY_TOFAST"), "", true); return true; } } else { _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("ISLAND_DIVE_MURRAY_TOOLATE"), "", true); } } // Le joueur utilise le bout de bois sur l'intérieur du bénitier if ( strcmp(szItemName, "inv_island_wood") == 0 ) { if (strcmp(szObjectName, "benitieropen") == 0 || strcmp(szObjectName, "dive_key") == 0) { ESoundBank::getSound("success")->playSample(); ResolveTask("task_island_clamwood"); AddTask("task_island_getkey"); SetVisible("woodin", true); _lpSceneDirector->DropItem("inv_island_wood"); return true; } if (strcmp(szObjectName, "benitierclose") == 0) { _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("ISLAND_DIVE_MURRAY_MISSED") ,"",true); return true; } } return false; } void SceneFondMarin::MiniGameDone(const char *szGameName, bool bIsRevolved) { }
32.066007
138
0.63555
calidrelle
88918310cc9ef181dac2f71083d8c5fa8b11eedf
12,982
cxx
C++
inetcore/wininet/handles/ftp.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetcore/wininet/handles/ftp.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetcore/wininet/handles/ftp.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1994 Microsoft Corporation Module Name: ftp.cxx Abstract: Contains methods for FTP_FIND_HANDLE_OBJECT and FTP_FILE_HANDLE_OBJECT classes Contents: RMakeFtpFindObjectHandle RMakeFtpFileObjectHandle RMakeFtpErrorObjectHandle FTP_ERROR_HANDLE_OBJECT::SetErrorText FTP_ERROR_HANDLE_OBJECT::QueryHtmlDataAvailable Author: Madan Appiah (madana) 16-Nov-1994 Environment: User Mode - Win32 Revision History: Sophia Chung (sophiac) 14-Feb-1995 (added FTP and Archie class impl.) (code adopted from madana) --*/ #include <wininetp.h> // // functions // DWORD RMakeFtpFindObjectHandle( IN HINTERNET ParentHandle, IN OUT HINTERNET * ChildHandle, IN CLOSE_HANDLE_FUNC wCloseFunc, IN DWORD_PTR dwContext ) /*++ Routine Description: C-callable wrapper for creating an FTP_FIND_HANDLE_OBJECT Arguments: ParentHandle - mapped address of parent (connect) handle ChildHandle - IN: protocol-specific handle value associated with object OUT: mapped address of FTP_FIND_HANDLE_OBJECT wCloseFunc - address of protocol-specific function to be called when object is closed dwContext - app-supplied context value Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_NOT_ENOUGH_MEMORY --*/ { DWORD error; FTP_FIND_HANDLE_OBJECT * hFind; hFind = new FTP_FIND_HANDLE_OBJECT( (INTERNET_CONNECT_HANDLE_OBJECT *)ParentHandle, *ChildHandle, wCloseFunc, dwContext ); if (hFind != NULL) { error = hFind->GetStatus(); if (error == ERROR_SUCCESS) { // // inform the app of the new handle // error = InternetIndicateStatusNewHandle((LPVOID)hFind); // // ERROR_INTERNET_OPERATION_CANCELLED is the only error that we are // expecting here. If we get this error then the app has cancelled // the operation. Either way, the handle we just generated will be // already deleted // if (error != ERROR_SUCCESS) { INET_ASSERT(error == ERROR_INTERNET_OPERATION_CANCELLED); hFind = NULL; } } else { delete hFind; hFind = NULL; } } else { error = ERROR_NOT_ENOUGH_MEMORY; } *ChildHandle = (HINTERNET)hFind; return error; } DWORD RMakeFtpFileObjectHandle( IN HINTERNET ParentHandle, IN OUT HINTERNET * ChildHandle, IN CLOSE_HANDLE_FUNC wCloseFunc, IN DWORD_PTR dwContext ) /*++ Routine Description: C-callable wrapper for creating an FTP_FILE_HANDLE_OBJECT Arguments: ParentHandle - mapped address of parent (connect) handle ChildHandle - IN: protocol-specific handle value associated with object OUT: mapped address of FTP_FILE_HANDLE_OBJECT wCloseFunc - address of protocol-specific function to be called when object is closed dwContext - app-supplied context value Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_NOT_ENOUGH_MEMORY --*/ { DWORD error; FTP_FILE_HANDLE_OBJECT * hFile; DEBUG_PRINT(FTP, INFO, ("RMakeFtpFileObject(0x%x 0x%x 0x%x 0x%x)\r\n", ParentHandle, ChildHandle, wCloseFunc, dwContext)); hFile = new FTP_FILE_HANDLE_OBJECT( (INTERNET_CONNECT_HANDLE_OBJECT *)ParentHandle, *ChildHandle, wCloseFunc, dwContext ); if (hFile != NULL) { error = hFile->GetStatus(); if (error == ERROR_SUCCESS) { // // inform the app of the new handle // error = InternetIndicateStatusNewHandle((LPVOID)hFile); // // ERROR_INTERNET_OPERATION_CANCELLED is the only error that we are // expecting here. If we get this error then the app has cancelled // the operation. Either way, the handle we just generated will be // already deleted // if (error != ERROR_SUCCESS) { INET_ASSERT(error == ERROR_INTERNET_OPERATION_CANCELLED); hFile = NULL; } } else { delete hFile; hFile = NULL; } } else { error = ERROR_NOT_ENOUGH_MEMORY; } *ChildHandle = (HINTERNET)hFile; return error; } #ifdef EXTENDED_ERROR_HTML DWORD RMakeFtpErrorObjectHandle( IN HINTERNET hConnect, OUT LPHINTERNET lphError ) /*++ Routine Description: Creates an FTP_ERROR_HANDLE_OBJECT. Used to return extended error info as HTML Arguments: hConnect - pointer to INTERNET_CONNECT_HANDLE_OBJECT lphError - pointer to returned FTP_ERROR_HANDLE_OBJECT Return Value: DWORD --*/ { FTP_ERROR_HANDLE_OBJECT * hError; hError = new FTP_ERROR_HANDLE_OBJECT( (INTERNET_CONNECT_HANDLE_OBJECT *)hConnect ); DWORD error; if (hError != NULL) { error = hError->GetStatus(); if (error == ERROR_SUCCESS) { // // inform the app of the new handle // error = InternetIndicateStatusNewHandle((LPVOID)hError); // // ERROR_INTERNET_OPERATION_CANCELLED is the only error that we are // expecting here. If we get this error then the app has cancelled // the operation. Either way, the handle we just generated will be // already deleted // if (error != ERROR_SUCCESS) { INET_ASSERT(error == ERROR_INTERNET_OPERATION_CANCELLED); hError = NULL; } } else { delete hError; hError = NULL; } } else { error = ERROR_NOT_ENOUGH_MEMORY; } *lphError = (HINTERNET)hError; return error; } #endif // // FTP_FIND_HANDLE_OJBECT class implementation // FTP_FIND_HANDLE_OBJECT::FTP_FIND_HANDLE_OBJECT( INTERNET_CONNECT_HANDLE_OBJECT *Parent, HINTERNET Child, CLOSE_HANDLE_FUNC wCloseFunc, DWORD_PTR dwContext ) : INTERNET_CONNECT_HANDLE_OBJECT(Parent) { _FindHandle = Child; _wCloseFunction = wCloseFunc; _dwFtpFindBools = 0; _lpszUrl = NULL; _lpszDirEntry = NULL; _QueryBuffer = NULL; _QueryBufferLength = 0; _QueryOffset = 0; _QueryBytesAvailable = 0; _Context = dwContext; SetObjectType(TypeFtpFindHandle); } FTP_FIND_HANDLE_OBJECT::~FTP_FIND_HANDLE_OBJECT( VOID ) { // // if local internet handle, closed by local close function // if (_FindHandle != NULL) { _Status = _wCloseFunction(_FindHandle); //INET_ASSERT(_Status == ERROR_SUCCESS); } else { _Status = ERROR_SUCCESS; } // // clear out any strings we allocated // if (_lpszUrl != NULL) { DEL_STRING(_lpszUrl); } if (_lpszDirEntry != NULL) { DEL_STRING(_lpszDirEntry); } // // and the query buffer // FreeQueryBuffer(); } HANDLE FTP_FIND_HANDLE_OBJECT::GetHandle( VOID ) { return _FindHandle; } DWORD FTP_FIND_HANDLE_OBJECT::QueryHtmlDataAvailable( OUT LPDWORD lpdwNumberOfBytesAvailable ) { DWORD error; if (_QueryBuffer != NULL) { error = ERROR_SUCCESS; } else { error = AllocateQueryBuffer(); } INET_ASSERT(_QueryBytesAvailable == 0); if (error == ERROR_SUCCESS) { _QueryOffset = 0; if (ReadHtmlUrlData((HINTERNET)this, _QueryBuffer, _QueryBufferLength, lpdwNumberOfBytesAvailable )) { _QueryBytesAvailable = *lpdwNumberOfBytesAvailable; //SetAvailableDataLength(_QueryBytesAvailable); if (_QueryBytesAvailable == 0) { SetEndOfFile(); } } else { error = GetLastError(); } } return error; } // // FTP_FILE_HANDLE_OJBECT class implementation // FTP_FILE_HANDLE_OBJECT::FTP_FILE_HANDLE_OBJECT( INTERNET_CONNECT_HANDLE_OBJECT *Parent, HINTERNET Child, CLOSE_HANDLE_FUNC wCloseFunc, DWORD_PTR dwContext ) : INTERNET_CONNECT_HANDLE_OBJECT(Parent) { _FileHandle = Child; _wCloseFunction = wCloseFunc; _IsHtml = FALSE; _lpszFileName = NULL; _lpszUrl = NULL; _lpszDirEntry = NULL; _Context = dwContext; SetObjectType(TypeFtpFileHandle); } FTP_FILE_HANDLE_OBJECT::~FTP_FILE_HANDLE_OBJECT( VOID ) { // // if local internet handle, closed by local close function // if (_FileHandle != NULL) { _Status = _wCloseFunction(_FileHandle); //INET_ASSERT(_Status == ERROR_SUCCESS); } else { _Status = ERROR_INVALID_HANDLE; } // // clear out any strings we allocated // if (_lpszUrl != NULL) { DEL_STRING(_lpszUrl); } if (_lpszDirEntry != NULL) { DEL_STRING(_lpszDirEntry); } if (_lpszFileName != NULL) { DEL_STRING(_lpszFileName); } } HINTERNET FTP_FILE_HANDLE_OBJECT::GetHandle( VOID ) { return _FileHandle; } #ifdef EXTENDED_ERROR_HTML // // FTP_ERROR_HANDLE_OBJECT class implementation // FTP_ERROR_HANDLE_OBJECT::FTP_ERROR_HANDLE_OBJECT( INTERNET_CONNECT_HANDLE_OBJECT* hConnect ) : INTERNET_CONNECT_HANDLE_OBJECT(hConnect) { m_lpszErrorText = NULL; m_dwErrorTextLength = 0; m_QueryBuffer = NULL; m_QueryBufferLength = 0; m_QueryOffset = 0; m_QueryBytesAvailable = 0; m_HtmlState = HTML_STATE_START; SetObjectType(TypeFtpFileHandle); SetErrorText(); } FTP_ERROR_HANDLE_OBJECT::~FTP_ERROR_HANDLE_OBJECT( VOID ) { // // clear out any strings we allocated // if (m_lpszErrorText != NULL) { DEL_STRING(m_lpszErrorText); } // // and the query buffer // FreeQueryBuffer(); } DWORD FTP_ERROR_HANDLE_OBJECT::SetErrorText( VOID ) /*++ Routine Description: Copies last error info to this handle object Arguments: None. Return Value: DWORD Success - ERROR_SUCCESS Failure - --*/ { INET_ASSERT(m_lpszErrorText == NULL); INET_ASSERT(m_dwErrorTextLength == 0); DWORD error; DWORD category; if (!InternetGetLastResponseInfo(&category, NULL, &m_dwErrorTextLength)) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { m_lpszErrorText = (LPSTR)ALLOCATE_MEMORY( LMEM_FIXED, m_dwErrorTextLength ); if (m_lpszErrorText != NULL) { if (!InternetGetLastResponseInfo(&category, m_lpszErrorText, &m_dwErrorTextLength)) { m_lpszErrorText[0] = '\0'; m_dwErrorTextLength = 0; } error = ERROR_SUCCESS; } else { error = ERROR_NOT_ENOUGH_MEMORY; } } } return error; } DWORD FTP_ERROR_HANDLE_OBJECT::QueryHtmlDataAvailable( OUT LPDWORD lpdwNumberOfBytesAvailable ) { DWORD error; if (m_QueryBuffer != NULL) { error = ERROR_SUCCESS; } else { error = AllocateQueryBuffer(); } INET_ASSERT(m_QueryBytesAvailable == 0); if (error == ERROR_SUCCESS) { m_QueryOffset = 0; if (ReadHtmlUrlData((HINTERNET)this, m_QueryBuffer, m_QueryBufferLength, lpdwNumberOfBytesAvailable )) { m_QueryBytesAvailable = *lpdwNumberOfBytesAvailable; if (m_QueryBytesAvailable == 0) { SetEndOfFile(); } } else { error = GetLastError(); } } return error; } #endif
22.577391
83
0.561778
npocmaka
8895a634fb861c4d0f7d42812b8a21a98dce0726
1,557
hpp
C++
Game/Physics.hpp
Zakhar-V/Game32k
1b44efb539c0382500511cb0190f00ccbfbe3243
[ "MIT" ]
null
null
null
Game/Physics.hpp
Zakhar-V/Game32k
1b44efb539c0382500511cb0190f00ccbfbe3243
[ "MIT" ]
null
null
null
Game/Physics.hpp
Zakhar-V/Game32k
1b44efb539c0382500511cb0190f00ccbfbe3243
[ "MIT" ]
null
null
null
#pragma once #include "Scene.hpp" //----------------------------------------------------------------------------// // Defs //----------------------------------------------------------------------------// //----------------------------------------------------------------------------// // PhysicsBody //----------------------------------------------------------------------------// class PhysicsBody : public Object { public: }; //----------------------------------------------------------------------------// // PhysicsShape //----------------------------------------------------------------------------// enum PhysicsShapeType : uint { PST_Empty, PST_Box, PST_Sphere, PST_Capsule, PST_Cyliner, PST_Heightfield, }; class PhysicsShape : public Object { public: }; //----------------------------------------------------------------------------// // PhysicsJoint //----------------------------------------------------------------------------// class PhysicsJoint : public Object { public: }; //----------------------------------------------------------------------------// // PhysicsWorld //----------------------------------------------------------------------------// class PhysicsWorld : public NonCopyable { public: PhysicsWorld(Scene* _scene); ~PhysicsWorld(void); protected: Scene* m_scene; }; //----------------------------------------------------------------------------// // //----------------------------------------------------------------------------//
22.897059
81
0.23571
Zakhar-V
889c2d23486e34c3f670540e701c19075f50970f
5,422
cpp
C++
library/uapki/src/api/digest.cpp
DJm00n/UAPKI
7ced3adc6d2990c88cc48b273d44ec99489a0282
[ "BSD-2-Clause" ]
null
null
null
library/uapki/src/api/digest.cpp
DJm00n/UAPKI
7ced3adc6d2990c88cc48b273d44ec99489a0282
[ "BSD-2-Clause" ]
null
null
null
library/uapki/src/api/digest.cpp
DJm00n/UAPKI
7ced3adc6d2990c88cc48b273d44ec99489a0282
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2021, The UAPKI Project Authors. * * 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 "api-json-internal.h" #include "oid-utils.h" #include "parson-helper.h" #undef FILE_MARKER #define FILE_MARKER "api/digest.cpp" #define DEBUG_OUTCON(expression) #ifndef DEBUG_OUTCON #define DEBUG_OUTCON(expression) expression #endif #define FILE_BLOCK_SIZE (10 * 1024 * 1024) using namespace std; // See: byte-array-internal.h struct ByteArray_st { const uint8_t* buf; size_t len; }; static int digest_bytes (const HashAlg hashAlgo, JSON_Object* joParams, ByteArray** baHash) { int ret = RET_OK; ByteArray* ba_data = nullptr; ba_data = json_object_get_base64(joParams, "bytes"); if (!ba_data) { SET_ERROR(RET_UAPKI_INVALID_PARAMETER); } DO(::hash(hashAlgo, ba_data, baHash)); cleanup: ba_free(ba_data); return ret; } static int digest_file (const HashAlg hashAlgo, JSON_Object* joParams, ByteArray** baHash) { int ret = RET_OK; HashCtx * hash_ctx = nullptr; ByteArray *ba_data = nullptr; const char* filename = nullptr; FILE* f = nullptr; filename = json_object_get_string(joParams, "file"); if (!filename) { SET_ERROR(RET_UAPKI_INVALID_PARAMETER); } f = fopen(filename, "rb"); if (!f) { SET_ERROR(RET_UAPKI_FILE_OPEN_ERROR); } CHECK_NOT_NULL(hash_ctx = hash_alloc(hashAlgo)); CHECK_NOT_NULL(ba_data = ba_alloc_by_len(FILE_BLOCK_SIZE)); do { ba_data->len = fread(ba_get_buf(ba_data), 1, FILE_BLOCK_SIZE, f); DO(hash_update(hash_ctx, ba_data)); } while (ba_data->len == FILE_BLOCK_SIZE); if (ferror(f)) { SET_ERROR(RET_UAPKI_FILE_READ_ERROR); } DO(hash_final(hash_ctx, baHash)); cleanup: ba_free(ba_data); hash_free(hash_ctx); return ret; } static int digest_memory (const HashAlg hashAlgo, JSON_Object* joParams, ByteArray** baHash) { int ret = RET_OK; ByteArray* ba_ptr = nullptr; ByteArray ba_local = { nullptr, 0 }; double f_len = 0; ba_ptr = json_object_get_hex(joParams, "ptr"); f_len = json_object_get_number(joParams, "size"); ba_local.len = (size_t)f_len; if ((ba_get_len(ba_ptr) != sizeof(void*)) || (f_len < 0) || ((double)ba_local.len != f_len)) { SET_ERROR(RET_UAPKI_INVALID_PARAMETER); } DO(ba_swap(ba_ptr)); memcpy(&ba_local.buf, ba_get_buf(ba_ptr), ba_get_len(ba_ptr)); DEBUG_OUTCON(printf("ptr=%p\n", ba_local.buf)); if (ba_local.buf == 0) { SET_ERROR(RET_UAPKI_INVALID_PARAMETER); } DO(::hash(hashAlgo, &ba_local, baHash)); cleanup: ba_free(ba_ptr); return ret; } int uapki_digest (JSON_Object* joParams, JSON_Object* joResult) { int ret = RET_OK; ByteArray* ba_hash = nullptr; const char* s_hashalgo = nullptr; const char* s_signalgo = nullptr; HashAlg hash_algo = HashAlg::HASH_ALG_UNDEFINED; s_hashalgo = json_object_get_string(joParams, "hashAlgo"); if (!s_hashalgo) { s_signalgo = json_object_get_string(joParams, "signAlgo"); } if (!s_hashalgo && !s_signalgo) { SET_ERROR(RET_UAPKI_INVALID_PARAMETER); } hash_algo = hash_from_oid((s_hashalgo) ? s_hashalgo : s_signalgo); if (hash_algo == HashAlg::HASH_ALG_UNDEFINED) { SET_ERROR(RET_UAPKI_UNSUPPORTED_ALG); } DO_JSON(json_object_set_string(joResult, "hashAlgo", (s_hashalgo) ? s_hashalgo : hash_to_oid(hash_algo))); if (ParsonHelper::jsonObjectHasValue(joParams, "bytes", JSONString)) { DO(digest_bytes(hash_algo, joParams, &ba_hash)); } else if (ParsonHelper::jsonObjectHasValue(joParams, "file", JSONString)) { DO(digest_file(hash_algo, joParams, &ba_hash)); } else if (ParsonHelper::jsonObjectHasValue(joParams, "ptr", JSONString) && ParsonHelper::jsonObjectHasValue(joParams, "size", JSONNumber)) { DO(digest_memory(hash_algo, joParams, &ba_hash)); } else { SET_ERROR(RET_UAPKI_INVALID_PARAMETER); } DO_JSON(json_object_set_base64(joResult, "bytes", ba_hash)); cleanup: ba_free(ba_hash); return ret; }
30.460674
110
0.69716
DJm00n
88a0031164db190941245acab3b8bb995ce5c9d2
637
cpp
C++
rt/rt/cameras/perspective.cpp
DasNaCl/old-university-projects
af1c82afec4805ea672e0c353369035b394cb69d
[ "Apache-2.0" ]
null
null
null
rt/rt/cameras/perspective.cpp
DasNaCl/old-university-projects
af1c82afec4805ea672e0c353369035b394cb69d
[ "Apache-2.0" ]
null
null
null
rt/rt/cameras/perspective.cpp
DasNaCl/old-university-projects
af1c82afec4805ea672e0c353369035b394cb69d
[ "Apache-2.0" ]
null
null
null
#include <rt/cameras/perspective.h> #include <rt/ray.h> #include <cmath> #include <iostream> namespace rt { PerspectiveCamera::PerspectiveCamera(const Point& center, const Vector& forward, const Vector& up, float verticalOpeningAngle, float horizontalOpeningAngle) : center(center) , focal(forward.normalize()) , right( cross(forward, up).normalize() * std::tan(horizontalOpeningAngle / 2.f)) , sup( cross(right, forward).normalize() * std::tan(verticalOpeningAngle / 2.f)) { } Ray PerspectiveCamera::getPrimaryRay(float x, float y) const { return Ray(center, (focal + x * right + y * sup).normalize()); } }
23.592593
80
0.704867
DasNaCl
88a1ef50564b78b62b5e7e2bab2b98d5beb9b829
32
cpp
C++
code/source/Octree.cpp
MajiKau/MoosEngine
3fca25f52129a33f438d0b3477a810d1f6c83a3f
[ "MIT" ]
null
null
null
code/source/Octree.cpp
MajiKau/MoosEngine
3fca25f52129a33f438d0b3477a810d1f6c83a3f
[ "MIT" ]
null
null
null
code/source/Octree.cpp
MajiKau/MoosEngine
3fca25f52129a33f438d0b3477a810d1f6c83a3f
[ "MIT" ]
null
null
null
#include "code/headers/Octree.h"
32
32
0.78125
MajiKau
88ac57c8e8ba8ed8fe17c3605653a0daff8d98d4
4,482
cpp
C++
test/test_serialization.cpp
MikhailTerekhov/mdso
e032083bc6da6548718a5d222ec4016189ec2dc8
[ "MIT" ]
7
2020-09-11T11:27:08.000Z
2022-03-22T02:12:07.000Z
test/test_serialization.cpp
MikhailTerekhov/mdso
e032083bc6da6548718a5d222ec4016189ec2dc8
[ "MIT" ]
null
null
null
test/test_serialization.cpp
MikhailTerekhov/mdso
e032083bc6da6548718a5d222ec4016189ec2dc8
[ "MIT" ]
1
2020-09-11T19:52:59.000Z
2020-09-11T19:52:59.000Z
#include "../samples/mfov/reader/MultiFovReader.h" #include "output/TrajectoryWriter.h" #include "system/DsoSystem.h" #include "system/serialization.h" #include "util/flags.h" #include <gtest/gtest.h> using namespace fishdso; DEFINE_string(mfov_dir, "/shared/datasets/mfov", "Path to the MultiFoV dataset."); DEFINE_string(traj_original, "traj_clean.txt", "Name of the file with the original trajectory."); DEFINE_string(traj_restored, "traj_restored.txt", "Name of the file with the trajectory after the restoration."); DEFINE_int32(start, 375, "Number of the starting frame."); DEFINE_int32(count_before_interruption, 100, "Number of the frame after which the interruption happens."); DEFINE_int32(count, 200, "Total number of frames to process."); Observers createObservers(TrajectoryWriter &trajectoryWriter) { Observers observers; observers.dso.push_back(&trajectoryWriter); return observers; } class SerializationTest : public ::testing::Test { public: static constexpr double maxTransErr = 1e-2; static constexpr double maxRotErr = 0.1; SerializationTest() : outDir(fs::path("output") / curTimeBrief()) , datasetReader(new MultiFovReader(FLAGS_mfov_dir)) , cam(*datasetReader->cam) , settings(getFlaggedSettings()) , trajectoryWriterClean(outDir, "oldstyle_traj.txt", FLAGS_traj_original) , originalObservers(createObservers(trajectoryWriterClean)) , dsoOriginal(new DsoSystem(&cam, originalObservers, settings)) { fs::create_directories(outDir); } protected: fs::path outDir; std::unique_ptr<MultiFovReader> datasetReader; CameraModel cam; Settings settings; TrajectoryWriter trajectoryWriterClean; Observers originalObservers; std::unique_ptr<DsoSystem> dsoOriginal; }; double trajLength(const StdVector<SE3> &traj) { CHECK_GE(traj.size(), 2); double len = 0; for (int i = 0; i < traj.size() - 1; ++i) len += (traj[i].inverse() * traj[i + 1]).translation().norm(); return len; } TEST_F(SerializationTest, canBeInterrupted) { for (int frameInd = FLAGS_start; frameInd < FLAGS_start + FLAGS_count_before_interruption; ++frameInd) { auto frame = datasetReader->getFrame(frameInd); std::cout << "add frame #" << frameInd << std::endl; dsoOriginal->addFrame(frame, frameInd); } std::cout << "Interrupt: "; std::cout.flush(); fs::path snapshotDir = outDir / "snapshot"; dsoOriginal->saveSnapshot(snapshotDir); std::cout << "saved, "; std::cout.flush(); SnapshotLoader snapshotLoader(datasetReader.get(), &cam, snapshotDir, settings); TrajectoryWriter trajectoryWriterRestored(outDir, "oldstyle_restored.txt", FLAGS_traj_restored); Observers restoredObservers = createObservers(trajectoryWriterRestored); std::unique_ptr<DsoSystem> dsoRestored( new DsoSystem(snapshotLoader, restoredObservers, settings)); std::cout << "loaded" << std::endl; for (int frameInd = FLAGS_start + FLAGS_count_before_interruption; frameInd < FLAGS_start + FLAGS_count; ++frameInd) { auto frame = datasetReader->getFrame(frameInd); std::cout << "add frame #" << frameInd << " [1/2 .. "; std::cout.flush(); dsoOriginal->addFrame(frame, frameInd); std::cout << "2/2]" << std::endl; dsoRestored->addFrame(frame, frameInd); } dsoOriginal.reset(); dsoRestored.reset(); auto originalTraj = trajectoryWriterClean.writtenFrameToWorld(); auto restoredTraj = trajectoryWriterRestored.writtenFrameToWorld(); originalTraj.erase(originalTraj.begin(), originalTraj.begin() + originalTraj.size() - restoredTraj.size()); double len = trajLength(originalTraj); SE3 lastOrig = originalTraj.back(); SE3 lastRestored = restoredTraj.back(); SE3 diff = lastOrig * lastRestored.inverse(); double transErr = diff.translation().norm() / len; double rotErr = (180 / M_PI) * diff.so3().log().norm() / len; LOG(INFO) << "translational err = " << transErr * 100 << "%"; LOG(INFO) << "rotational err = " << rotErr << "deg / m"; EXPECT_LT(transErr, maxTransErr); EXPECT_LT(rotErr, maxRotErr); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); gflags::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); return RUN_ALL_TESTS(); }
36.145161
79
0.681169
MikhailTerekhov
88ae1d04c6346c2df3ad3805957ec45b2995839f
3,458
cpp
C++
lib/cpp/vpath.cpp
fooofei/c_cpp
83b780fd48cd3c03fd3850fb297576d5fc907955
[ "MIT" ]
null
null
null
lib/cpp/vpath.cpp
fooofei/c_cpp
83b780fd48cd3c03fd3850fb297576d5fc907955
[ "MIT" ]
null
null
null
lib/cpp/vpath.cpp
fooofei/c_cpp
83b780fd48cd3c03fd3850fb297576d5fc907955
[ "MIT" ]
null
null
null
#include "vpath.h" /* cannot use namespace base {}, will cause a link error */ #include <cstring> #include "strings_algorithm.h" #include "whereami/whereami.h" #include <string> #ifdef WIN32 #include "encoding/encoding_std.h" #include <Windows.h> int base::path_abspath(const std::string & src, std::string & dst) { std::wstring ws; std::wstring ws2; DWORD dw; wchar_t buf[2] = {}; utf8_2_wstring(src, ws); /* small to contain the path */ dw = GetFullPathNameW(ws.c_str(), 2, buf, NULL); if (dw == 0) { return -1; } ws2.resize(dw); dw = GetFullPathNameW(ws.c_str(), dw, &ws2[0], NULL); if (dw == 0) { return -1; } ws2.resize(dw); wstring_2_utf8(ws2, dst); return 0; } bool base::path_is_directory(const std::wstring & ws) { /* up Windows 10, there will not have MAX_PATH size limit. */ WIN32_FILE_ATTRIBUTE_DATA wfad; std::memset(&wfad, 0, sizeof(wfad)); if (!GetFileAttributesExW(ws.c_str(), GetFileExInfoStandard, &wfad)) { return false;// api error } return (wfad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY; } /* test a file or directory exists on Visual Studio 2017 -- <platform tool set:Visual Studio 2017 - Windows XP (v141_xp)> -- <c++ runtime library /MT> stat not work not Windows XP, but ok on Windows 7. on Windows XP, stat return EINVAL(22) even the file exists the code is: struct stat st; std::string s1; utf8_2_string(s, s1); return stat(s1.c_str(), &st) == 0; */ bool base::path_exists(const std::string & s) { std::wstring ws; utf8_2_wstring(s, ws); WIN32_FILE_ATTRIBUTE_DATA wfad; std::memset(&wfad, 0, sizeof(wfad)); // return TRUE if exists if (!GetFileAttributesExW(ws.c_str(), GetFileExInfoStandard, &wfad)) { return false;// api error } // return (wfad.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_ARCHIVE)) != 0; return true; } #else #include <limits.h> #include <stdlib.h> #include <sys/stat.h> int base::path_abspath(const std::string & src, std::string & dst) { std::string temp; temp.resize(PATH_MAX + 1); char * p = realpath(src.c_str(), &temp[0]); if (p) { dst.assign(p); return 0; } return -1; } bool base::path_is_directory(const std::string & s) { int err; struct stat st; std::memset(&st, 0, sizeof(st)); err = stat(s.c_str(), &st); if (err == 0) { return 0 != (st.st_mode & S_IFDIR); } return false; } bool base::path_exists(const std::string & s) { struct stat st; return stat(s.c_str(), &st) == 0; } #endif /* abspath the arg*/ int base::path_try_abspath_current(std::string & s) { int err; std::string temp; err = base::path_abspath_current(s, temp); if (err == 0) { s = temp; return 0; } return -1; } int base::get_current_directory(std::string & dst) { int err; std::string temp; err = get_executable_fullpath(&temp); if (err) { return err; } base::dirname(temp); if (temp.empty()) { return -1; } dst = temp; return 0; } int base::path_abspath_current(const std::string & src, std::string & dst) { // path_exists(src) maybe false if (base::startswith(src,std::string("."))) { std::string temp; if (0 != get_current_directory(temp)) { return -1; } base::path_join(temp, src); if (path_exists(temp) && 0 == path_abspath(std::string(temp), temp)) { dst = temp; return 0; } } return -1; }
18.393617
95
0.635628
fooofei
88afb7d94e6e53d06cd5b79a4479b8d188b5659e
715
cpp
C++
Jolt/Physics/Collision/CollisionGroup.cpp
All8Up/JoltPhysics
751d13891f5bd8850863ad236eaa3c340e90de9a
[ "MIT" ]
1,311
2021-08-16T07:37:05.000Z
2022-03-31T21:13:39.000Z
Jolt/Physics/Collision/CollisionGroup.cpp
All8Up/JoltPhysics
751d13891f5bd8850863ad236eaa3c340e90de9a
[ "MIT" ]
102
2021-08-28T14:41:32.000Z
2022-03-31T20:25:55.000Z
Jolt/Physics/Collision/CollisionGroup.cpp
All8Up/JoltPhysics
751d13891f5bd8850863ad236eaa3c340e90de9a
[ "MIT" ]
65
2021-08-16T07:59:04.000Z
2022-03-28T06:18:49.000Z
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe // SPDX-License-Identifier: MIT #include <Jolt.h> #include <Physics/Collision/CollisionGroup.h> #include <ObjectStream/TypeDeclarations.h> #include <Core/StreamIn.h> #include <Core/StreamOut.h> namespace JPH { JPH_IMPLEMENT_SERIALIZABLE_NON_VIRTUAL(CollisionGroup) { JPH_ADD_ATTRIBUTE(CollisionGroup, mGroupFilter) JPH_ADD_ATTRIBUTE(CollisionGroup, mGroupID) JPH_ADD_ATTRIBUTE(CollisionGroup, mSubGroupID) } void CollisionGroup::SaveBinaryState(StreamOut &inStream) const { inStream.Write(mGroupID); inStream.Write(mSubGroupID); } void CollisionGroup::RestoreBinaryState(StreamIn &inStream) { inStream.Read(mGroupID); inStream.Read(mSubGroupID); } } // JPH
22.34375
63
0.801399
All8Up
88b496e0c27305383e61cbd6071a4e8dcf07d912
2,372
cpp
C++
Hackerrank/30 Days of Code/C++/day 24.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Hackerrank/30 Days of Code/C++/day 24.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Hackerrank/30 Days of Code/C++/day 24.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
#include <cstddef> #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; class Node { public: int data; Node *next; Node(int d){ data=d; next=NULL; } }; class Solution{ public: Node* removeDuplicates(Node *head) { // As per the question, the head pointer may be null // So we check and return head if it's null if(!head) return head; // Create a new node pointer which is pointing to the // same address as head is pointing Node* curr = head; // Condition check inside while will return false only // for the last node while(curr->next != NULL) { // Checking whether the data of the present node // equals next node data in order to remove duplicates // If there are duplicates store the address of next // to next node in the current node skipping the next node // because it contains the duplicate value if(curr->data == curr->next->data) curr->next = curr->next->next; // Else just move the current pointer to next node else curr = curr->next; } return head; } Node* insert(Node *head,int data) { Node* p=new Node(data); if(head==NULL){ head=p; } else if(head->next==NULL){ head->next=p; } else{ Node *start=head; while(start->next!=NULL){ start=start->next; } start->next=p; } return head; } void display(Node *head) { Node *start=head; while(start) { cout<<start->data<<" "; start=start->next; } } }; int main() { Node* head=NULL; Solution mylist; int T,data; cin>>T; while(T-->0){ cin>>data; head=mylist.insert(head,data); } head=mylist.removeDuplicates(head); mylist.display(head); }
25.782609
70
0.462901
Next-Gen-UI
88b4bbed90633e0e94837c47bc3a79716d3bcf98
1,923
hpp
C++
lib/abcresub/abcresub/vec_wrd.hpp
osamamowafy/mockturtle
840ff314e9f5301686790a517c383240f1403588
[ "MIT" ]
98
2018-06-15T09:28:11.000Z
2022-03-31T15:42:48.000Z
lib/abcresub/abcresub/vec_wrd.hpp
osamamowafy/mockturtle
840ff314e9f5301686790a517c383240f1403588
[ "MIT" ]
257
2018-05-09T12:14:28.000Z
2022-03-30T16:12:14.000Z
lib/abcresub/abcresub/vec_wrd.hpp
osamamowafy/mockturtle
840ff314e9f5301686790a517c383240f1403588
[ "MIT" ]
75
2020-11-26T13:05:15.000Z
2021-12-24T00:28:18.000Z
/*! \file vec_wrd.hpp \brief Extracted from ABC https://github.com/berkeley-abc/abc \author Alan Mishchenko (UC Berkeley) */ #pragma once namespace abcresub { typedef struct Vec_Wrd_t_ Vec_Wrd_t; struct Vec_Wrd_t_ { int nCap; int nSize; word * pArray; }; inline Vec_Wrd_t * Vec_WrdAlloc( int nCap ) { Vec_Wrd_t * p; p = ABC_ALLOC( Vec_Wrd_t, 1 ); if ( nCap > 0 && nCap < 16 ) nCap = 16; p->nSize = 0; p->nCap = nCap; p->pArray = p->nCap? ABC_ALLOC( word, p->nCap ) : NULL; return p; } inline void Vec_WrdErase( Vec_Wrd_t * p ) { ABC_FREE( p->pArray ); p->nSize = 0; p->nCap = 0; } inline void Vec_WrdFree( Vec_Wrd_t * p ) { ABC_FREE( p->pArray ); ABC_FREE( p ); } inline word * Vec_WrdArray( Vec_Wrd_t * p ) { return p->pArray; } inline word Vec_WrdEntry( Vec_Wrd_t * p, int i ) { assert( i >= 0 && i < p->nSize ); return p->pArray[i]; } inline word * Vec_WrdEntryP( Vec_Wrd_t * p, int i ) { assert( i >= 0 && i < p->nSize ); return p->pArray + i; } inline void Vec_WrdGrow( Vec_Wrd_t * p, int nCapMin ) { if ( p->nCap >= nCapMin ) return; p->pArray = ABC_REALLOC( word, p->pArray, nCapMin ); assert( p->pArray ); p->nCap = nCapMin; } inline void Vec_WrdFill( Vec_Wrd_t * p, int nSize, word Fill ) { int i; Vec_WrdGrow( p, nSize ); for ( i = 0; i < nSize; i++ ) p->pArray[i] = Fill; p->nSize = nSize; } inline void Vec_WrdClear( Vec_Wrd_t * p ) { p->nSize = 0; } inline void Vec_WrdPush( Vec_Wrd_t * p, word Entry ) { if ( p->nSize == p->nCap ) { if ( p->nCap < 16 ) Vec_WrdGrow( p, 16 ); else Vec_WrdGrow( p, 2 * p->nCap ); } p->pArray[p->nSize++] = Entry; } inline int Vec_WrdSize( Vec_Wrd_t * p ) { return p->nSize; } } /* namespace abcresub */
18.141509
62
0.552782
osamamowafy
88b562af416f747ac467974e3d2d9f316b8cc77c
464
cpp
C++
app/bootloader/default_bd.cpp
HPezz/LekaOS
e4c16f52e2c7bd3d75c9d5aefe94eb67dbf5a694
[ "Apache-2.0" ]
2
2021-10-30T20:51:30.000Z
2022-01-12T11:18:34.000Z
app/bootloader/default_bd.cpp
HPezz/LekaOS
e4c16f52e2c7bd3d75c9d5aefe94eb67dbf5a694
[ "Apache-2.0" ]
343
2021-07-15T12:57:08.000Z
2022-03-29T10:14:06.000Z
app/bootloader/default_bd.cpp
HPezz/LekaOS
e4c16f52e2c7bd3d75c9d5aefe94eb67dbf5a694
[ "Apache-2.0" ]
3
2021-12-30T02:53:24.000Z
2022-01-11T22:08:05.000Z
// Leka - LekaOS // Copyright 2021 APF France handicap // SPDX-License-Identifier: Apache-2.0 #include "QSPIFBlockDevice.h" #include "SlicingBlockDevice.h" auto get_secondary_bd() -> mbed::BlockDevice * { // In this case, our flash is much larger than a single image so // slice it into the size of an image slot static auto _bd = QSPIFBlockDevice {}; static auto sliced_bd = mbed::SlicingBlockDevice {&_bd, 0x0, MCUBOOT_SLOT_SIZE}; return &sliced_bd; }
24.421053
81
0.734914
HPezz
88b604129332b4d2aaec50963831d7d338f8028d
11,266
cpp
C++
SofaKernel/framework/sofa/core/objectmodel/DDGNode.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
SofaKernel/framework/sofa/core/objectmodel/DDGNode.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
SofaKernel/framework/sofa/core/objectmodel/DDGNode.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include <sofa/core/objectmodel/DDGNode.h> #include <sofa/core/objectmodel/BaseData.h> #include <sofa/core/objectmodel/Base.h> #include <sofa/core/DataEngine.h> #ifdef SOFA_HAVE_BOOST_THREAD #include <boost/thread/mutex.hpp> #include <boost/thread/lock_guard.hpp> #endif //#include <sofa/helper/BackTrace.h> //#define SOFA_DDG_TRACE namespace sofa { namespace core { namespace objectmodel { struct DDGNode::UpdateState { sofa::helper::system::atomic<int> updateThreadID; sofa::helper::system::atomic<int> lastUpdateThreadID; #ifdef SOFA_HAVE_BOOST_THREAD boost::mutex updateMutex; #endif UpdateState() : updateThreadID(-1) , lastUpdateThreadID(-1) {} }; /// Constructor DDGNode::DDGNode() : inputs(initLink("inputs", "Links to inputs Data")) , outputs(initLink("outputs", "Links to outputs Data")) , updateStates(new UpdateState[SOFA_DATA_MAX_ASPECTS]) { } DDGNode::~DDGNode() { for(DDGLinkIterator it=inputs.begin(); it!=inputs.end(); ++it) (*it)->doDelOutput(this); for(DDGLinkIterator it=outputs.begin(); it!=outputs.end(); ++it) (*it)->doDelInput(this); delete[] updateStates; } template<> TClass<DDGNode,void>::TClass() { DDGNode* ptr = NULL; namespaceName = Base::namespaceName(ptr); className = Base::className(ptr); templateName = Base::templateName(ptr); shortName = Base::shortName(ptr); } void DDGNode::setDirtyValue(const core::ExecParams* params) { FlagType& dirtyValue = dirtyFlags[currentAspect(params)].dirtyValue; if (!dirtyValue.exchange_and_add(1)) { #ifdef SOFA_DDG_TRACE // TRACE LOG Base* owner = getOwner(); if (owner) owner->sout << "Data " << getName() << " is now dirty." << owner->sendl; #endif setDirtyOutputs(params); } } void DDGNode::setDirtyOutputs(const core::ExecParams* params) { FlagType& dirtyOutputs = dirtyFlags[currentAspect(params)].dirtyOutputs; if (!dirtyOutputs.exchange_and_add(1)) { for(DDGLinkIterator it=outputs.begin(params), itend=outputs.end(params); it != itend; ++it) { (*it)->setDirtyValue(params); } } } void DDGNode::doCleanDirty(const core::ExecParams* params, bool warnBadUse) { //if (!params) params = core::ExecParams::defaultInstance(); const int aspect = currentAspect(params); FlagType& dirtyValue = dirtyFlags[aspect].dirtyValue; if (!dirtyValue) // this node is not dirty, nothing to do { return; } UpdateState& state = updateStates[aspect]; int updateThreadID = state.updateThreadID; if (updateThreadID != -1) // a thread is currently updating this node, dirty flags will be updated once it finishes. { return; } if (warnBadUse) { Base* owner = getOwner(); if (owner) { owner->serr << "Data " << getName() << " deprecated cleanDirty() called. " "Instead of calling update() directly, requestUpdate() should now be called " "to manage dirty flags and provide thread safety." << getOwner()->sendl; } //sofa::helper::BackTrace::dump(); } #ifdef SOFA_HAVE_BOOST_THREAD // Here we know this thread does not own the lock (otherwise updateThreadID would not be -1 earlier), so we can take it boost::lock_guard<boost::mutex> guard(state.updateMutex); #endif dirtyValue = 0; #ifdef SOFA_DDG_TRACE Base* owner = getOwner(); if (owner) owner->sout << "Data " << getName() << " has been updated." << owner->sendl; #endif for(DDGLinkIterator it=inputs.begin(params), itend=inputs.end(params); it != itend; ++it) (*it)->dirtyFlags[aspect].dirtyOutputs = 0; } void DDGNode::cleanDirty(const core::ExecParams* params) { doCleanDirty(params, true); } void DDGNode::forceCleanDirty(const core::ExecParams* params) { doCleanDirty(params, false); } void DDGNode::requestUpdate(const core::ExecParams* params) { setDirtyValue(params); requestUpdateIfDirty(params); } void DDGNode::requestUpdateIfDirty(const core::ExecParams* params) { /*if (!params)*/ params = core::ExecParams::defaultInstance(); const int aspect = currentAspect(params); FlagType& dirtyValue = dirtyFlags[aspect].dirtyValue; UpdateState& state = updateStates[aspect]; const int currentThreadID = params->threadID(); int updateThreadID = state.updateThreadID; if (updateThreadID == currentThreadID) // recursive call to update, ignoring { //if (getOwner()) // getOwner()->serr << "Data " << getName() << " recursive update() ignored." << getOwner()->sendl; return; } if (dirtyValue == 0) { if (getOwner()) getOwner()->serr << "Data " << getName() << " requestUpdateIfDirty nothing to do." << getOwner()->sendl; return; } // Make sure all inputs are updated (before taking the lock) for(DDGLinkIterator it=inputs.begin(params), itend=inputs.end(params); it != itend; ++it) (*it)->updateIfDirty(params); if (dirtyValue == 0) { //if (getOwner()) // getOwner()->serr << "Data " << getName() << " requestUpdateIfDirty nothing to do after updating inputs." << getOwner()->sendl; return; } #ifdef SOFA_HAVE_BOOST_THREAD // Here we know this thread does not own the lock (otherwise updateThreadID would be currentThreadID earlier), so we can take it boost::lock_guard<boost::mutex> guard(state.updateMutex); #endif if (dirtyValue != 0) { // we need to call update state.updateThreadID = currentThreadID; // store the thread ID to detect recursive calls state.lastUpdateThreadID = currentThreadID; update(); // dirtyValue is updated only once update() is complete, so that other threads know that they need to wait for it dirtyValue = 0; #ifdef SOFA_DDG_TRACE Base* owner = getOwner(); if (owner) owner->sout << "Data " << getName() << " has been updated." << owner->sendl; #endif for(DDGLinkIterator it=inputs.begin(params), itend=inputs.end(params); it != itend; ++it) (*it)->dirtyFlags[aspect].dirtyOutputs = 0; state.updateThreadID = -1; } else // else nothing to do, as another thread already updated this while we were waiting to acquire the lock { #ifdef SOFA_DDG_TRACE if (getOwner()) getOwner()->serr << "Data " << getName() << " update() from multiple threads (" << state.lastUpdateThreadID << " and " << currentThreadID << ")" << getOwner()->sendl; #endif } } void DDGNode::copyAspect(int destAspect, int srcAspect) { dirtyFlags[destAspect] = dirtyFlags[srcAspect]; } void DDGNode::addInput(DDGNode* n) { doAddInput(n); n->doAddOutput(this); setDirtyValue(); } void DDGNode::delInput(DDGNode* n) { doDelInput(n); n->doDelOutput(this); } void DDGNode::addOutput(DDGNode* n) { doAddOutput(n); n->doAddInput(this); n->setDirtyValue(); } void DDGNode::delOutput(DDGNode* n) { doDelOutput(n); n->doDelInput(this); } const DDGNode::DDGLinkContainer& DDGNode::getInputs() { return inputs.getValue(); } const DDGNode::DDGLinkContainer& DDGNode::getOutputs() { return outputs.getValue(); } sofa::core::objectmodel::Base* LinkTraitsPtrCasts<DDGNode>::getBase(sofa::core::objectmodel::DDGNode* n) { if (!n) return NULL; return n->getOwner(); //sofa::core::objectmodel::BaseData* d = dynamic_cast<sofa::core::objectmodel::BaseData*>(n); //if (d) return d->getOwner(); //return dynamic_cast<sofa::core::objectmodel::Base*>(n); } sofa::core::objectmodel::BaseData* LinkTraitsPtrCasts<DDGNode>::getData(sofa::core::objectmodel::DDGNode* n) { if (!n) return NULL; return n->getData(); //return dynamic_cast<sofa::core::objectmodel::BaseData*>(n); } bool DDGNode::findDataLinkDest(DDGNode*& ptr, const std::string& path, const BaseLink* link) { std::string pathStr, dataStr(" "); // non-empty data to specify that a data name is optionnal for DDGNode (as it can be a DataEngine) if (link) { if (!link->parseString(path, &pathStr, &dataStr)) return false; } else { if (!BaseLink::ParseString(path, &pathStr, &dataStr, this->getOwner())) return false; } bool self = (pathStr.empty() || pathStr == "[]"); if (dataStr == "") // no Data -> we look for a DataEngine { if (self) { ptr = this; return true; } else { Base* owner = this->getOwner(); DataEngine* obj = NULL; if (!owner) return false; if (!owner->findLinkDest(obj, path, link)) return false; ptr = obj; return true; } } Base* owner = this->getOwner(); if (!owner) return false; if (self) { ptr = owner->findData(dataStr); return (ptr != NULL); } else { Base* obj = NULL; if (!owner->findLinkDest(obj, BaseLink::CreateString(pathStr), link)) return false; if (!obj) return false; ptr = obj->findData(dataStr); return (ptr != NULL); } return false; } void DDGNode::addLink(BaseLink* /*l*/) { // the inputs and outputs links in DDGNode is manually added // once the link vectors are constructed in Base or BaseData } } // namespace objectmodel } // namespace core } // namespace sofa
30.781421
178
0.596041
sofa-framework
88c06b07bf56737b41c15500fa2654abfe3423f4
3,623
cpp
C++
orca/gporca/libnaucrates/src/parser/CParseHandlerWindowSpecList.cpp
vitessedata/gpdb.4.3.99.x
9462aad5df1bf120a2a87456b1f9574712227da4
[ "PostgreSQL", "Apache-2.0" ]
3
2017-12-10T16:41:21.000Z
2020-07-08T12:59:12.000Z
orca/gporca/libnaucrates/src/parser/CParseHandlerWindowSpecList.cpp
vitessedata/gpdb.4.3.99.x
9462aad5df1bf120a2a87456b1f9574712227da4
[ "PostgreSQL", "Apache-2.0" ]
null
null
null
orca/gporca/libnaucrates/src/parser/CParseHandlerWindowSpecList.cpp
vitessedata/gpdb.4.3.99.x
9462aad5df1bf120a2a87456b1f9574712227da4
[ "PostgreSQL", "Apache-2.0" ]
4
2017-12-10T16:41:35.000Z
2020-11-28T12:20:30.000Z
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2012 EMC Corp. // // @filename: // CParseHandlerWindowSpecList.cpp // // @doc: // Implementation of the SAX parse handler class for parsing the list of // window specifications in the logical window operator // // @owner: // // // @test: // // //--------------------------------------------------------------------------- #include "naucrates/dxl/parser/CParseHandlerWindowSpec.h" #include "naucrates/dxl/parser/CParseHandlerWindowSpecList.h" #include "naucrates/dxl/parser/CParseHandlerManager.h" #include "naucrates/dxl/parser/CParseHandlerFactory.h" #include "naucrates/dxl/operators/CDXLOperatorFactory.h" using namespace gpdxl; XERCES_CPP_NAMESPACE_USE //--------------------------------------------------------------------------- // @function: // CParseHandlerWindowSpecList::CParseHandlerWindowSpecList // // @doc: // Ctor // //--------------------------------------------------------------------------- CParseHandlerWindowSpecList::CParseHandlerWindowSpecList ( IMemoryPool *pmp, CParseHandlerManager *pphm, CParseHandlerBase *pphRoot ) : CParseHandlerBase(pmp, pphm, pphRoot), m_pdrgpdxlws(NULL) { } //--------------------------------------------------------------------------- // @function: // CParseHandlerWindowSpecList::StartElement // // @doc: // Invoked by Xerces to process an opening tag // //--------------------------------------------------------------------------- void CParseHandlerWindowSpecList::StartElement ( const XMLCh* const xmlszUri, const XMLCh* const xmlszLocalname, const XMLCh* const xmlszQname, const Attributes& attrs ) { if (0 == XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenWindowSpecList), xmlszLocalname)) { m_pdrgpdxlws = GPOS_NEW(m_pmp) DrgPdxlws(m_pmp); } else if (0 == XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenWindowSpec), xmlszLocalname)) { // we must have seen a window specification list already GPOS_ASSERT(NULL != m_pdrgpdxlws); // start new window specification element CParseHandlerBase *pphWs = CParseHandlerFactory::Pph(m_pmp, CDXLTokens::XmlstrToken(EdxltokenWindowSpec), m_pphm, this); m_pphm->ActivateParseHandler(pphWs); // store parse handler this->Append(pphWs); pphWs->startElement(xmlszUri, xmlszLocalname, xmlszQname, attrs); } else { CWStringDynamic *pstr = CDXLUtils::PstrFromXMLCh(m_pphm->Pmm(), xmlszLocalname); GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag, pstr->Wsz()); } } //--------------------------------------------------------------------------- // @function: // CParseHandlerWindowSpecList::EndElement // // @doc: // Invoked by Xerces to process a closing tag // //--------------------------------------------------------------------------- void CParseHandlerWindowSpecList::EndElement ( const XMLCh* const, // xmlszUri, const XMLCh* const xmlszLocalname, const XMLCh* const // xmlszQname ) { if (0 != XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenWindowSpecList), xmlszLocalname)) { CWStringDynamic *pstr = CDXLUtils::PstrFromXMLCh(m_pphm->Pmm(), xmlszLocalname); GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag, pstr->Wsz()); } GPOS_ASSERT(NULL != m_pdrgpdxlws); const ULONG ulSize = this->UlLength(); // add the window specifications to the list for (ULONG ul = 0; ul < ulSize; ul++) { CParseHandlerWindowSpec *pphWs = dynamic_cast<CParseHandlerWindowSpec *>((*this)[ul]); m_pdrgpdxlws->Append(pphWs->Pdxlws()); } // deactivate handler m_pphm->DeactivateHandler(); } // EOF
28.304688
102
0.617996
vitessedata
88c0d1a67be9ae5cb7efbd991daf1c84aa3025c5
7,399
hpp
C++
stapl_release/stapl/containers/heap/seq_heap.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/stapl/containers/heap/seq_heap.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/stapl/containers/heap/seq_heap.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
/* // Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a // component of the Texas A&M University System. // // // All rights reserved. // // // The information and source code contained herein is the exclusive // // property of TEES and may not be disclosed, examined or reproduced // // in whole or in part without explicit written authorization from TEES. // */ #ifndef STAPL_CONTAINERS_HEAP_STORAGE_HPP #define STAPL_CONTAINERS_HEAP_STORAGE_HPP #include <algorithm> #include <vector> #include <iostream> #include <iterator> namespace stapl { ////////////////////////////////////////////////////////////////////// /// @brief Default container used as the internal storage of the heap /// base_container. /// @ingroup pheapDist /// @tparam T The value type of the container. /// @tparam Comp The comparator used to maintain ordering of the elements. ////////////////////////////////////////////////////////////////////// template <typename T, typename Comp> class seq_heap { public: typedef typename std::vector<T>::iterator iterator; typedef typename std::vector<T>::const_iterator const_iterator; typedef T value_type; protected: std::vector <T> m_v; Comp m_c; public: seq_heap(Comp c = Comp()) : m_c(c) { } seq_heap(const seq_heap<T,Comp>& other) : m_v(other.m_v), m_c(other.m_c) { } seq_heap(size_t size, Comp c) : m_c(c) { m_v.reserve(size); } seq_heap(std::vector <T> v, Comp c) : m_v(v), m_c(c) { this->heapify(); } ////////////////////////////////////////////////////////////////////// /// @brief Insert an element into the container. /// @param elem Element to be added. ////////////////////////////////////////////////////////////////////// void push(T const& elem) { m_v.push_back(elem); push_heap(m_v.begin(),m_v.end(), m_c); } ////////////////////////////////////////////////////////////////////// /// @brief Returns a copy of the first element according to the order /// determined by the comparator and removes it from the container. ////////////////////////////////////////////////////////////////////// T pop(void) { pop_heap(m_v.begin(),m_v.end(), m_c); T tmp = m_v.back(); m_v.pop_back(); return tmp; } ////////////////////////////////////////////////////////////////////// /// @brief Returns a copy of the first element according to the order /// determined by the comparator. ////////////////////////////////////////////////////////////////////// T top(void) { return m_v.front(); } ////////////////////////////////////////////////////////////////////// /// @brief Returns a reference of the greatest element according to the order /// determined by the comparator. ////////////////////////////////////////////////////////////////////// T& top_ref(void) { return m_v.back(); } ////////////////////////////////////////////////////////////////////// /// @brief Returns an iterator to the greatest element according /// to the order determined by the comparator. ////////////////////////////////////////////////////////////////////// iterator top_it(void) { return m_v.begin(); } ////////////////////////////////////////////////////////////////////// /// @brief Clear all elements in the container and fill it /// with elements of a view. /// @tparam The view used to populate the container. ////////////////////////////////////////////////////////////////////// template <typename V> void make(V v) { m_v.resize(v.size()); std::copy(v.begin(), v.end(), m_v.begin()); std::make_heap(m_v.begin(),m_v.end(),m_c); } ////////////////////////////////////////////////////////////////////// /// @brief Returns the index of the container where the ordering specified /// by the comparator is violated. ////////////////////////////////////////////////////////////////////// size_t is_heap_until(void) { size_t parent = 0; for (size_t child = 1; child < m_v.size(); ++child) { if (m_c(m_v.begin()[parent], m_v.begin()[child])) return child; if ((child & 1) == 0) ++parent; } return m_v.size(); } ////////////////////////////////////////////////////////////////////// /// @brief Returns if the container follows the ordering /// inferred by the comparator. ////////////////////////////////////////////////////////////////////// bool is_heap(void) { return is_heap_until() == m_v.size(); } ////////////////////////////////////////////////////////////////////// /// @brief Returns the number of elements in the container. ////////////////////////////////////////////////////////////////////// size_t size(void) const { return m_v.size(); } ////////////////////////////////////////////////////////////////////// /// @brief Return whether the container is empty /// (i.e. whether its size is 0). ////////////////////////////////////////////////////////////////////// bool empty(void) const { return m_v.empty(); } ////////////////////////////////////////////////////////////////////// /// @brief Remove all elements from the container. ////////////////////////////////////////////////////////////////////// void clear(void) { m_v.clear(); } ////////////////////////////////////////////////////////////////////// /// @brief Returns an iterator over the first element /// of the container. ////////////////////////////////////////////////////////////////////// iterator begin(void) { return m_v.begin(); } ////////////////////////////////////////////////////////////////////// /// @brief Returns an iterator over one position past the last element /// in the container. ////////////////////////////////////////////////////////////////////// iterator end(void) { return m_v.end(); } ////////////////////////////////////////////////////////////////////// /// @brief Returns a const iterator over the first element /// of the container. ////////////////////////////////////////////////////////////////////// const_iterator begin(void) const { return m_v.begin(); } ////////////////////////////////////////////////////////////////////// /// @brief Returns a const iterator over one position past the last element /// in the container. ////////////////////////////////////////////////////////////////////// const_iterator end(void) const { return m_v.end(); } ////////////////////////////////////////////////////////////////////// /// @brief Returns a copy of the first element of the container. ////////////////////////////////////////////////////////////////////// T front(void) { return m_v.front(); } void define_type(typer &t) { t.member(this->m_v); t.member(this->m_c); } private: ////////////////////////////////////////////////////////////////////// /// @brief Rearranges the container elements using the comparator /// provided in such a way that it forms a heap. ////////////////////////////////////////////////////////////////////// void heapify(void) { std::make_heap(m_v.begin(),m_v.end(),m_c); } }; }//namespace stapl #endif
30.829167
79
0.405595
parasol-ppl
88c1c46e3fb983cd08d102bef22f878a3d7a3b6f
42,925
hpp
C++
include/libopfcpp/OPF.hpp
thierrypin/LibOPFcpp
27614069e6600a1a2cab0d016018103b4eea1ee5
[ "Apache-2.0" ]
4
2019-05-06T14:44:53.000Z
2021-11-07T17:09:44.000Z
include/libopfcpp/OPF.hpp
thierrypin/LibOPFcpp
27614069e6600a1a2cab0d016018103b4eea1ee5
[ "Apache-2.0" ]
null
null
null
include/libopfcpp/OPF.hpp
thierrypin/LibOPFcpp
27614069e6600a1a2cab0d016018103b4eea1ee5
[ "Apache-2.0" ]
null
null
null
/****************************************************** * A C++ program for the OPF classification machine, * * all contained in a single header file. * * * * Author: Thierry Moreira * * * ******************************************************/ // Copyright 2019 Thierry Moreira // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef OPF_HPP #define OPF_HPP #include <functional> #include <stdexcept> #include <algorithm> #include <typeinfo> #include <sstream> #include <utility> #include <cstring> #include <string> #include <limits> #include <memory> #include <vector> #include <cmath> #include <map> #include <set> #include <omp.h> namespace opf { using uchar = unsigned char; #define INF std::numeric_limits<float>::infinity() #define NIL -1 // Generic distance function template <class T> using distance_function = std::function<T (const T*, const T*, size_t)>; /*****************************************/ /*************** Binary IO ***************/ /*****************************************/ //////////// // OPF types enum Type : unsigned char { Classifier = 1, Clustering = 2, }; ////////////////////// // Serialization Flags enum SFlags : unsigned char { Sup_SavePrototypes = 1, Unsup_Anomaly = 2, }; /////////////// // IO functions template <class T> void write_bin(std::ostream& output, const T& val) { output.write((char*) &val, sizeof(T)); } template <class T> void write_bin(std::ostream& output, const T* val, int n=1) { output.write((char*) val, sizeof(T) * n); } template <class T> T read_bin(std::istream& input) { T val; input.read((char*) &val, sizeof(T)); return val; } template <class T> void read_bin(std::istream& input, T* val, int n=1) { input.read((char*) val, sizeof(T) * n); } /*****************************************/ /************** Matrix type **************/ /*****************************************/ template <class T=float> class Mat { protected: std::shared_ptr<T> data; public: size_t rows, cols; size_t size; size_t stride; Mat(); Mat(const Mat<T>& other); Mat(size_t rows, size_t cols); Mat(size_t rows, size_t cols, T val0); Mat(std::shared_ptr<T>& data, size_t rows, size_t cols, size_t stride = 0); Mat(T* data, size_t rows, size_t cols, size_t stride=0); virtual T& at(size_t i, size_t j); const virtual T at(size_t i, size_t j) const; virtual T* row(size_t i); const virtual T* row(size_t i) const; virtual T* operator[](size_t i); const virtual T* operator[](size_t i) const; Mat<T>& operator=(const Mat<T>& other); virtual Mat<T> copy(); void release(); }; template <class T> Mat<T>::Mat() { this->rows = this->cols = this->size = this->stride = 0; } template <class T> Mat<T>::Mat(const Mat<T>& other) { this->rows = other.rows; this->cols = other.cols; this->size = other.size; this->data = other.data; this->stride = other.stride; } template <class T> Mat<T>::Mat(size_t rows, size_t cols) { this->rows = rows; this->cols = cols; this->size = rows * cols; this->stride = cols; this->data = std::shared_ptr<T>(new T[this->size], std::default_delete<T[]>()); } template <class T> Mat<T>::Mat(size_t rows, size_t cols, T val) { this->rows = rows; this->cols = cols; this->size = rows * cols; this->stride = cols; this->data = std::shared_ptr<T>(new T[this->size], std::default_delete<T[]>()); for (size_t i = 0; i < rows; i++) { T* row = this->row(i); for (size_t j = 0; j < cols; j++) row[j] = val; } } template <class T> Mat<T>::Mat(std::shared_ptr<T>& data, size_t rows, size_t cols, size_t stride) { this->rows = rows; this->cols = cols; this->size = rows * cols; this->data = data; if (stride) this->stride = stride; else this->stride = cols; } // Receives a pointer to some data, which may not be deleted. template <class T> Mat<T>::Mat(T* data, size_t rows, size_t cols, size_t stride) { this->rows = rows; this->cols = cols; this->size = rows * cols; this->data = std::shared_ptr<T>(data, [](T *p) {}); if (stride) this->stride = stride; else this->stride = cols; } template <class T> T& Mat<T>::at(size_t i, size_t j) { size_t idx = i * this->stride + j; return this->data.get()[idx]; } template <class T> const T Mat<T>::at(size_t i, size_t j) const { size_t idx = i * this->stride + j; return this->data.get()[idx]; } template <class T> T* Mat<T>::row(size_t i) { size_t idx = i * this->stride; return this->data.get() + idx; } template <class T> const T* Mat<T>::row(size_t i) const { size_t idx = i * this->stride; return this->data.get() + idx; } template <class T> T* Mat<T>::operator[](size_t i) { size_t idx = i * this->stride; return this->data.get() + idx; } template <class T> const T* Mat<T>::operator[](size_t i) const { size_t idx = i * this->stride; return this->data.get() + idx; } template <class T> Mat<T>& Mat<T>::operator=(const Mat<T>& other) { if (this != &other) { this->rows = other.rows; this->cols = other.cols; this->size = other.size; this->data = other.data; this->stride = other.stride; } return *this; } template <class T> Mat<T> Mat<T>::copy() { Mat<T> out(this->rows, this->cols); for (size_t i = 0; i < this->rows; i++) { T* row = this->row(i); T* outrow = out.row(i); for (size_t j = 0; j < this->cols; j++) outrow[j] = row[j]; } return std::move(out); } template <class T> void Mat<T>::release() { this->data.reset(); } /*****************************************/ // Default distance function template <class T> T euclidean_distance(const T* a, const T* b, size_t size) { T sum = 0; for (size_t i = 0; i < size; i++) { sum += (a[i]-b[i]) * (a[i]-b[i]); } return (T)sqrt(sum); } template <class T> T magnitude(const T* v, size_t size) { T sum = 0; for (size_t i = 0; i < size; i++) { sum += v[i] * v[i]; } return (T)sqrt(sum); } // One alternate distance function template <class T> T cosine_distance(const T* a, const T* b, size_t size) { T dividend = 0; for (size_t i = 0; i < size; i++) { dividend += a[i] * b[i]; } T divisor = magnitude<T>(a, size) * magnitude<T>(b, size); // 1 - cosine similarity return 1 - (dividend / divisor); } template <class T> Mat<T> compute_train_distances(const Mat<T> &features, distance_function<T> distance=euclidean_distance<T>) { Mat<float> distances(features.rows, features.rows); #pragma omp parallel for shared(features, distances) for (size_t i = 0; i < features.rows - 1; i++) { distances[i][i] = 0; for (size_t j = i + 1; j < features.rows; j++) { distances[i][j] = distances[j][i] = distance(features[i], features[j], features.cols); } } return distances; } /*****************************************/ /********* Distance matrix type **********/ /*****************************************/ // Instead of storing n x n elements, we only store the upper triangle, // which has (n * (n-1))/2 elements (less than half). template <class T> class DistMat: public Mat<T> { private: T diag_vals = static_cast<T>(0); int get_index(int i, int j) const; public: DistMat(){this->rows = this->cols = this->size = 0;}; DistMat(const DistMat& other); DistMat(const Mat<T>& features, distance_function<T> distance=euclidean_distance<T>); virtual T& at(size_t i, size_t j); const virtual T at(size_t i, size_t j) const; }; // The first row has n-1 cols, the second has n-2, and so on until row n has 0 cols. // This way, #define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) template <class T> inline int DistMat<T>::get_index(int i, int j) const { if (i > j) SWAP(i, j); return ((((this->rows<<1) - i - 1) * i) >> 1) + (j - i - 1); } template <class T> DistMat<T>::DistMat(const DistMat& other) { this->rows = other.rows; this->cols = other.cols; this->size = other.size; this->data = other.data; } template <class T> DistMat<T>::DistMat(const Mat<T>& features, distance_function<T> distance) { this->rows = features.rows; this->cols = features.rows; this->size = (this->rows * (this->rows - 1)) / 2; this->data = std::shared_ptr<T>(new float[this->size], std::default_delete<float[]>()); for (size_t i = 0; i < this->rows; i++) { for (size_t j = i+1; j < this->rows; j++) this->data.get()[get_index(i, j)] = distance(features[i], features[j], features.cols); } } template <class T> T& DistMat<T>::at(size_t i, size_t j) { if (i == j) return this->diag_vals = static_cast<T>(0); return this->data.get()[this->get_index(i, j)]; } template <class T> const T DistMat<T>::at(size_t i, size_t j) const { if (i == j) return 0; return this->data.get()[this->get_index(i, j)]; } /*****************************************/ /************ Data structures ************/ /*****************************************/ /** * Color codes for Prim's algorithm */ enum Color{ WHITE, // New node GRAY, // On the heap BLACK // Already seen }; /** * Plain class to store node information */ class Node { public: Node() { this->color = WHITE; this->pred = -1; this->cost = INF; this->is_prototype = false; } size_t index; // Index on the list -- makes searches easier * Color color; // Color on the heap. white: never visiter, gray: on the heap, black: removed from the heap * float cost; // Cost to reach the node int true_label; // Ground truth * int label; // Assigned label int pred; // Predecessor node * bool is_prototype; // Whether the node is a prototype * }; /** * Heap data structure to use as a priority queue * */ class Heap { private: std::vector<Node> *nodes; // A reference for the original container vector std::vector<Node*> vec; // A vector of pointers to build the heap upon static bool compare_element(const Node* lhs, const Node* rhs) { return lhs->cost >= rhs->cost; } public: // Size-constructor Heap(std::vector<Node> *nodes, const std::vector<int> &labels) { this->nodes = nodes; size_t n = nodes->size(); this->vec.reserve(n); for (size_t i = 0; i < n; i++) { (*this->nodes)[i].index = i; (*this->nodes)[i].true_label = (*this->nodes)[i].label = labels[i]; } } // Insert new element into heap void push(int item, float cost) { // Update node's cost value (*this->nodes)[item].cost = cost; // Already on the heap if ((*this->nodes)[item].color == GRAY) make_heap(this->vec.begin(), this->vec.end(), compare_element); // Remake the heap // New to the heap else if ((*this->nodes)[item].color == WHITE) { (*this->nodes)[item].color = GRAY; this->vec.push_back(&(*this->nodes)[item]); push_heap(this->vec.begin(), this->vec.end(), compare_element); // Push new item to the heap } // Note that black items can not be inserted into the heap } // Update item's cost without updating the heap void update_cost(int item, float cost) { // Update node's cost value (*this->nodes)[item].cost = cost; if ((*this->nodes)[item].color == WHITE) { (*this->nodes)[item].color = GRAY; this->vec.push_back(&(*this->nodes)[item]); } } // Update the heap. // This is used after multiple calls to update_cost in order to reduce the number of calls to make_heap. void heapify() { make_heap(this->vec.begin(), this->vec.end(), compare_element); // Remake the heap } // Remove and return the first element of the heap int pop() { // Obtain and mark the first element Node *front = this->vec.front(); front->color = BLACK; // Remove it from the heap pop_heap(this->vec.begin(), this->vec.end(), compare_element); this->vec.pop_back(); // And return it return front->index; } bool empty() { return this->vec.size() == 0; } size_t size() { return this->vec.size(); } }; /*****************************************/ /*****************************************/ /****************** OPF ******************/ /*****************************************/ /******** Supervised ********/ template <class T=float> class SupervisedOPF { private: // Model Mat<T> train_data; // Training data (original vectors or distance matrix) std::vector<Node> nodes; // Learned model // List of nodes ordered by cost. Useful for speeding up classification // Its not size_t to reduce memory usage, since ML may handle large data std::vector<unsigned int> ordered_nodes; // Options bool precomputed; distance_function<T> distance; void prim_prototype(const std::vector<int> &labels); public: SupervisedOPF(bool precomputed=false, distance_function<T> distance=euclidean_distance<T>); void fit(const Mat<T> &train_data, const std::vector<int> &labels); std::vector<int> predict(const Mat<T> &test_data); bool get_precomputed() {return this->precomputed;} // Serialization functions std::string serialize(uchar flags=0); static SupervisedOPF<T> unserialize(const std::string& contents); // Training information std::vector<std::vector<float>> get_prototypes(); }; template <class T> SupervisedOPF<T>::SupervisedOPF(bool precomputed, distance_function<T> distance) { this->precomputed = precomputed; this->distance = distance; } /** * - The first step in OPF's training procedure. Finds the prototype nodes using Prim's * Minimum Spanning Tree algorithm. * - Any node with an adjacent node of a different class is taken as a prototype. */ template <class T> void SupervisedOPF<T>::prim_prototype(const std::vector<int> &labels) { this->nodes = std::vector<Node>(this->train_data.rows); Heap h(&this->nodes, labels); // Heap as a priority queue // Arbitrary first node h.push(0, 0); while(!h.empty()) { // Gets the head of the heap and marks it black size_t s = h.pop(); // Prototype definition int pred = this->nodes[s].pred; if (pred != NIL) { // Find points in the border between two classes... if (this->nodes[s].true_label != this->nodes[pred].true_label) { // And set them as prototypes this->nodes[s].is_prototype = true; this->nodes[pred].is_prototype = true; } } // Edge selection #pragma omp parallel for default(shared) for (size_t t = 0; t < this->nodes.size(); t++) { // If nodes are different and t has not been poped out of the heap (marked black) if (s != t && this->nodes[t].color != BLACK) // TODO if s == t, t is black { // Compute weight float weight; if (this->precomputed) weight = this->train_data[s][t]; else weight = this->distance(this->train_data[s], this->train_data[t], this->train_data.cols); // Assign if smaller than current value if (weight < this->nodes[t].cost) { this->nodes[t].pred = static_cast<int>(s); // h.push(t, weight); #pragma omp critical(updateHeap) h.update_cost(t, weight); } } } h.heapify(); } } /** * Trains the model with the given data and labels. * * Inputs: * - train_data: * - original feature vectors [n_samples, n_features] -- if precomputed == false * - distance matrix [n_samples, n_samples] -- if precomputed == true * - labels: * - true label values [n_samples] */ template <class T> void SupervisedOPF<T>::fit(const Mat<T> &train_data, const std::vector<int> &labels) { if ((size_t)train_data.rows != labels.size()) throw std::invalid_argument("[OPF/fit] Error: data size does not match labels size: " + std::to_string(train_data.rows) + " x " + std::to_string(labels.size())); // Store data reference for testing this->train_data = train_data; // Initialize model this->prim_prototype(labels); // Find prototypes Heap h(&this->nodes, labels); // Heap as a priority queue // Initialization for (Node& node: this->nodes) { node.color = WHITE; // Prototypes cost 0, have no predecessor and populate the heap if (node.is_prototype) { node.pred = NIL; node.cost = 0; } else // Other nodes start with cost = INF { node.cost = INF; } // Since all nodes are connected to all the others h.push(node.index, node.cost); } // List of nodes ordered by cost // Useful for speeding up classification this->ordered_nodes.reserve(this->nodes.size()); // Consume the queue while(!h.empty()) { int s = h.pop(); this->ordered_nodes.push_back(s); // Iterate over all neighbors #pragma omp parallel for default(shared) for (int t = 0; t < (int) this->nodes.size(); t++) { if (s != t && this->nodes[s].cost < this->nodes[t].cost) // && this->nodes[t].color != BLACK ?? { // Compute weight float weight; if (precomputed) weight = this->train_data[s][t]; else weight = distance(this->train_data[s], this->train_data[t], this->train_data.cols); float cost = std::max(weight, this->nodes[s].cost); if (cost < this->nodes[t].cost) { this->nodes[t].pred = s; this->nodes[t].label = this->nodes[s].true_label; // h.push(t, cost); #pragma omp critical(updateHeap) h.update_cost(t, cost); } } } h.heapify(); } } /** * Classify a set of samples using a model trained by SupervisedOPF::fit. * * Inputs: * - test_data: * - original feature vectors [n_test_samples, n_features] -- if precomputed == false * - distance matrix [n_test_samples, n_train_samples] -- if precomputed == true * * Returns: * - predictions: * - a vector<int> of size [n_test_samples] with classification outputs. */ template <class T> std::vector<int> SupervisedOPF<T>::predict(const Mat<T> &test_data) { int n_test_samples = (int) test_data.rows; int n_train_samples = (int) this->nodes.size(); // Output predictions std::vector<int> predictions(n_test_samples); #pragma omp parallel for default(shared) for (int i = 0; i < n_test_samples; i++) { int idx = this->ordered_nodes[0]; int min_idx = 0; T min_cost = INF; T weight = 0; // 'ordered_nodes' contains sample indices ordered by cost, so if the current // best connection costs less than the next node, it is useless to keep looking. for (int j = 0; j < n_train_samples && min_cost > this->nodes[idx].cost; j++) { // Get the next node in the ordered list idx = this->ordered_nodes[j]; // Compute its distance to the query point if (precomputed) weight = test_data[i][idx]; else weight = distance(test_data[i], this->train_data[idx], this->train_data.cols); // The cost corresponds to the max between the distance and the reference cost float cost = std::max(weight, this->nodes[idx].cost); if (cost < min_cost) { min_cost = cost; min_idx = idx; } } predictions[i] = this->nodes[min_idx].label; } return predictions; } /*****************************************/ /* Persistence */ /*****************************************/ template <class T> std::string SupervisedOPF<T>::serialize(uchar flags) { if (this->precomputed) throw std::invalid_argument("Serialization for precomputed OPF not implemented yet"); // Open file std::ostringstream output(std::ios::out | std::ios::binary); int n_samples = this->train_data.rows; int n_features = this->train_data.cols; // Header write_bin<char>(output, "OPF", 3); write_bin<uchar>(output, Type::Classifier); write_bin<uchar>(output, flags); write_bin<uchar>(output, static_cast<uchar>(0)); // Reserved flags byte write_bin<int>(output, n_samples); write_bin<int>(output, n_features); // Data for (int i = 0; i < n_samples; i++) { const T* data = this->train_data.row(i); write_bin<T>(output, data, n_features); } // Nodes for (int i = 0; i < n_samples; i++) { write_bin<float>(output, this->nodes[i].cost); write_bin<int>(output, this->nodes[i].label); } // Ordered_nodes write_bin<unsigned int>(output, this->ordered_nodes.data(), n_samples); // Prototypes if (flags & SFlags::Sup_SavePrototypes) { // Find which are prototypes first, because we need the correct amount std::set<int> prots; for (int i = 0; i < n_samples; i++) { if (this->nodes[i].is_prototype) prots.insert(i); } write_bin<int>(output, prots.size()); for (auto it = prots.begin(); it != prots.end(); ++it) write_bin<int>(output, *it); } return output.str(); } template <class T> SupervisedOPF<T> SupervisedOPF<T>::unserialize(const std::string& contents) { // Header int n_samples; int n_features; char header[4]; SupervisedOPF<float> opf; // Open stream std::istringstream ifs(contents); // , std::ios::in | std::ios::binary // Check if stream is an OPF serialization read_bin<char>(ifs, header, 3); header[3] = '\0'; if (strcmp(header, "OPF")) throw std::invalid_argument("Input is not an OPF serialization"); // Get type and flags uchar type = read_bin<uchar>(ifs); uchar flags = read_bin<uchar>(ifs); read_bin<uchar>(ifs); // Reserved byte if (type != Type::Classifier) throw std::invalid_argument("Input is not a Supervised OPF serialization"); n_samples = read_bin<int>(ifs); n_features = read_bin<int>(ifs); // Data int size = n_samples * n_features; opf.train_data = Mat<T>(n_samples, n_features); T* data = opf.train_data.row(0); read_bin<T>(ifs, data, size); // Nodes opf.nodes = std::vector<Node>(n_samples); for (int i = 0; i < n_samples; i++) { opf.nodes[i].cost = read_bin<float>(ifs); opf.nodes[i].label = read_bin<int>(ifs); } // Ordered_nodes opf.ordered_nodes = std::vector<unsigned int>(n_samples); read_bin<unsigned int>(ifs, opf.ordered_nodes.data(), n_samples); if (flags & SFlags::Sup_SavePrototypes) { int prots = read_bin<int>(ifs); for (int i = 0; i < prots; i++) { int idx = read_bin<int>(ifs); opf.nodes[idx].is_prototype = true; } } return std::move(opf); } /*****************************************/ /* Data Access */ /*****************************************/ template <class T> std::vector<std::vector<float>> SupervisedOPF<T>::get_prototypes() { std::set<int> prots; for (size_t i = 0; i < this->train_data.rows; i++) { if (this->nodes[i].is_prototype) prots.insert(i); } std::vector<std::vector<float>> out(prots.size(), std::vector<float>(this->train_data.cols)); int i = 0; for (auto it = prots.begin(); it != prots.end(); ++it, ++i) { for (int j = 0; j < this->train_data.cols; j++) { out[i][j] = this->train_data[*it][j]; } } return out; } /*****************************************/ /******** Unsupervised ********/ // Index + distance to another node using Pdist = std::pair<int, float>; static bool compare_neighbor(const Pdist& lhs, const Pdist& rhs) { return lhs.second < rhs.second; } // Aux class to find the k nearest neighbors from a given node // In the future, this should be replaced by a kdtree class BestK { private: int k; std::vector<Pdist> heap; // idx, dist public: // Empty initializer BestK(int k) : k(k) {this->heap.reserve(k);} // Tries to insert another element to the heap void insert(int idx, float dist) { if (heap.size() < static_cast<unsigned int>(this->k)) { heap.push_back(Pdist(idx, dist)); push_heap(this->heap.begin(), this->heap.end(), compare_neighbor); } else { // If the new point is closer than the farthest neighbor Pdist farthest = this->heap.front(); if (dist < farthest.second) { // Remove one from the heap and add the other pop_heap(this->heap.begin(), this->heap.end(), compare_neighbor); this->heap[this->k-1] = Pdist(idx, dist); push_heap(this->heap.begin(), this->heap.end(), compare_neighbor); } } } std::vector<Pdist>& get_knn() { return heap; } }; /** * Plain class to store node information */ class NodeKNN { public: NodeKNN() { this->pred = -1; } std::set<Pdist> adj; // Node adjacency size_t index; // Index on the list -- makes searches easier int label; // Assigned label int pred; // Predecessor node float value; // Path value float rho; // probability density function }; // Unsupervised OPF classifier template <class T=float> class UnsupervisedOPF { private: // Model std::shared_ptr<const Mat<T>> train_data; // Training data (original vectors or distance matrix) distance_function<T> distance; // Distance function std::vector<NodeKNN> nodes; // Learned model std::vector<int> queue; // Priority queue implemented as a linear search in a vector int k; // The number of neighbors to build the graph int n_clusters; // Number of clusters in the model -- computed during fit // Training attributes float sigma_sq; // Sigma squared, used to compute probability distribution function float delta; // Adjustment term float denominator; // sqrt(2 * math.pi * sigma_sq) -- compute it only once // Options float thresh; bool anomaly; bool precomputed; // Queue capabilities int get_max(); // Training subroutines void build_graph(); void build_initialize(); void cluster(); public: UnsupervisedOPF(int k=5, bool anomaly=false, float thresh=.1, bool precomputed=false, distance_function<T> distance=euclidean_distance<T>); void fit(const Mat<T> &train_data); std::vector<int> fit_predict(const Mat<T> &train_data); std::vector<int> predict(const Mat<T> &test_data); void find_best_k(Mat<float>& train_data, int kmin, int kmax, int step=1, bool precompute=true); // Clustering info float quality_metric(); // Getters & Setters int get_n_clusters() {return this->n_clusters;} int get_k() {return this->k;} bool get_anomaly() {return this->anomaly;} float get_thresh() {return this->thresh;} void set_thresh(float thresh) {this->thresh = thresh;} bool get_precomputed() {return this->precomputed;} // Serialization functions std::string serialize(uchar flags=0); static UnsupervisedOPF<T> unserialize(const std::string& contents); }; template <class T> UnsupervisedOPF<T>::UnsupervisedOPF(int k, bool anomaly, float thresh, bool precomputed, distance_function<T> distance) { this->k = k; this->precomputed = precomputed; this->anomaly = anomaly; if (this->anomaly) this->n_clusters = 2; this->thresh = thresh; this->distance = distance; } // Builds the KNN graph template <class T> void UnsupervisedOPF<T>::build_graph() { this->sigma_sq = 0.; // Proportional to the length of the biggest edge for (size_t i = 0; i < this->nodes.size(); i++) { // Find the k nearest neighbors BestK bk(this->k); for (size_t j = 0; j < this->nodes.size(); j++) { if (i != j) { float dist; if (this->precomputed) dist = this->train_data->at(i, j); else dist = this->distance(this->train_data->row(i), this->train_data->row(j), this->train_data->cols); bk.insert(j, dist); } } std::vector<Pdist> knn = bk.get_knn(); for (auto it = knn.cbegin(); it != knn.cend(); ++it) { // Since the graph is undirected, make connections from both nodes this->nodes[i].adj.insert(*it); this->nodes[it->first].adj.insert(Pdist(i, it->second)); // Finding sigma if (it->second > this->sigma_sq) this->sigma_sq = it->second; } } this->sigma_sq /= 3; this->sigma_sq = 2 * (this->sigma_sq * this->sigma_sq); this->denominator = sqrt(2 * M_PI * this->sigma_sq); } // Initialize the graph nodes template <class T> void UnsupervisedOPF<T>::build_initialize() { // Compute rho std::set<Pdist>::iterator it; for (size_t i = 0; i < this->nodes.size(); i++) { int n_neighbors = this->nodes[i].adj.size(); // A node may have more than k neighbors float div = this->denominator * n_neighbors; float sum = 0; for (it = this->nodes[i].adj.cbegin(); it != this->nodes[i].adj.cend(); ++it) { float dist = it->second; sum += expf((-dist * dist) / this->sigma_sq); } this->nodes[i].rho = sum / div; } // Compute delta this->delta = INF; for (size_t i = 0; i < this->nodes.size(); i++) { for (it = this->nodes[i].adj.begin(); it != this->nodes[i].adj.end(); ++it) { float diff = abs(this->nodes[i].rho - this->nodes[it->first].rho); if (diff != 0 && this->delta > diff) this->delta = diff; } } // And, finally, initialize each node this->queue.resize(this->nodes.size()); for (size_t i = 0; i < this->nodes.size(); i++) { this->nodes[i].value = this->nodes[i].rho - this->delta; this->queue[i] = static_cast<int>(i); } } // Get the node with the biggest path value // TODO: implement it in a more efficient way? template <class T> int UnsupervisedOPF<T>::get_max() { float maxval = -INF; int maxidx = -1; int size = this->queue.size(); for (int i = 0; i < size; i++) { int idx = this->queue[i]; if (this->nodes[idx].value > maxval) { maxidx = i; maxval = this->nodes[idx].value; } } int best = this->queue[maxidx]; int tmp = this->queue[size-1]; this->queue[size-1] = this->queue[maxidx]; this->queue[maxidx] = tmp; this->queue.pop_back(); return best; } // OPF clustering template <class T> void UnsupervisedOPF<T>::cluster() { // Cluster labels int l = 0; // Priority queue while (!this->queue.empty()) { int s = this->get_max(); // Pop the highest value // If it has no predecessor, make it a prototype if (this->nodes[s].pred == -1) { this->nodes[s].label = l++; this->nodes[s].value = this->nodes[s].rho; } // Iterate and conquer over its neighbors for (auto it = this->nodes[s].adj.begin(); it != this->nodes[s].adj.end(); ++it) { int t = it->first; if (this->nodes[t].value < this->nodes[s].value) { float rho = std::min(this->nodes[s].value, this->nodes[t].rho); // std::cout << rho << " " << this->nodes[t].value << std::endl; if (rho > this->nodes[t].value) { this->nodes[t].label = this->nodes[s].label; this->nodes[t].pred = s; this->nodes[t].value = rho; } } } } this->n_clusters = l; } // Fit the model template <class T> void UnsupervisedOPF<T>::fit(const Mat<T> &train_data) { this->train_data = std::shared_ptr<const Mat<T>>(&train_data, [](const Mat<T> *p) {}); this->nodes = std::vector<NodeKNN>(this->train_data->rows); this->build_graph(); this->build_initialize(); if (!this->anomaly) this->cluster(); } // Fit and predict for all nodes template <class T> std::vector<int> UnsupervisedOPF<T>::fit_predict(const Mat<T> &train_data) { this->fit(train_data); std::vector<int> labels(this->nodes.size()); if (this->anomaly) for (size_t i = 0; i < this->nodes.size(); i++) labels[i] = (this->nodes[i].rho < this->thresh) ? 1 : 0; else for (size_t i = 0; i < this->nodes.size(); i++) labels[i] = this->nodes[i].label; return labels; } // Predict cluster pertinence template <class T> std::vector<int> UnsupervisedOPF<T>::predict(const Mat<T> &test_data) { std::vector<int> preds(test_data.rows); // For each test sample for (size_t i = 0; i < test_data.rows; i++) { // Find the k nearest neighbors BestK bk(this->k); for (size_t j = 0; j < this->nodes.size(); j++) { if (i != j) { float dist; if (this->precomputed) dist = test_data.at(i, j); else dist = this->distance(test_data[i], this->train_data->row(j), this->train_data->cols); bk.insert(j, dist); } } // Compute the testing rho std::vector<Pdist> neighbors = bk.get_knn(); int n_neighbors = neighbors.size(); float div = this->denominator * n_neighbors; float sum = 0; for (int j = 0; j < n_neighbors; j++) { float dist = neighbors[j].second; // this->distances[i][*it] sum += expf((-dist * dist) / this->sigma_sq); } float rho = sum / div; if (this->anomaly) { // And returns anomaly detection based on graph density preds[i] = (rho < this->thresh) ? 1 : 0; } else { // And find which node conquers this test sample float maxval = -INF; int maxidx = -1; for (int j = 0; j < n_neighbors; j++) { int s = neighbors[j].first; // idx, distance float val = std::min(this->nodes[s].value, rho); if (val > maxval) { maxval = val; maxidx = s; } } preds[i] = this->nodes[maxidx].label; } } return preds; } // Quality metric // From: A Robust Extension of the Mean Shift Algorithm using Optimum Path Forest // Leonardo Rocha, Alexandre Falcao, and Luis Meloni template <class T> float UnsupervisedOPF<T>::quality_metric() { if (this->anomaly) throw std::invalid_argument("Quality metric not implemented for anomaly detection yet"); std::vector<float> w(this->n_clusters, 0); std::vector<float> w_(this->n_clusters, 0); for (size_t i = 0; i < this->train_data->rows; i++) { int l = this->nodes[i].label; for (auto it = this->nodes[i].adj.begin(); it != this->nodes[i].adj.end(); ++it) { int l_ = this->nodes[it->first].label; float tmp = 0; if (it->second != 0) tmp = 1. / it->second; if (l == l_) w[l] += tmp; else w_[l] += tmp; } } float C = 0; for (int i = 0; i < this->n_clusters; i++) C += w_[i] / (w_[i] + w[i]); return C; } // Brute force method to find the best value of k template <class T> void UnsupervisedOPF<T>::find_best_k(Mat<float>& train_data, int kmin, int kmax, int step, bool precompute) { std::cout << "precompute " << precompute << std::endl; float best_quality = INF; UnsupervisedOPF<float> best_opf; DistMat<float> distances; if (precompute) distances = DistMat<float>(train_data, this->distance); for (int k = kmin; k <= kmax; k += step) { // Instanciate and train the model UnsupervisedOPF<float> opf(k, false, 0, precompute, this->distance); if (precompute) opf.fit(distances); else opf.fit(train_data); std::cout << k << ": " << opf.n_clusters << std::endl; // Compare its clustering grade float quality = opf.quality_metric(); // Normalized cut if (quality < best_quality) { best_quality = quality; best_opf = opf; } } if (best_quality == INF) { std::ostringstream ss; ss << "No search with kmin " << kmin << ", kmax " << kmax << ", and step " << step << ". The arguments might be out of order."; std::cerr << ss.str() << std::endl; throw 0; } if (this->precomputed) this->train_data = std::shared_ptr<Mat<T>>(&distances, std::default_delete<Mat<T>>()); else this->train_data = std::shared_ptr<Mat<T>>(&train_data, [](Mat<T> *p) {}); this->k = best_opf.k; this->n_clusters = best_opf.n_clusters; this->nodes = best_opf.nodes; this->denominator = best_opf.denominator; this->sigma_sq = best_opf.sigma_sq; this->delta = best_opf.delta; } /*****************************************/ /* Persistence */ /*****************************************/ template <class T> std::string UnsupervisedOPF<T>::serialize(uchar flags) { if (this->precomputed) throw std::invalid_argument("Serialization for precomputed OPF not implemented yet"); // Open file std::ostringstream output ; int n_samples = this->train_data->rows; int n_features = this->train_data->cols; // Output flags flags = 0; // For now, there are no user-defined flags if (this->anomaly) flags += SFlags::Unsup_Anomaly; // Header write_bin<char>(output, "OPF", 3); write_bin<uchar>(output, Type::Clustering); write_bin<uchar>(output, flags); write_bin<uchar>(output, static_cast<uchar>(0)); // Reserved byte write_bin<int>(output, n_samples); write_bin<int>(output, n_features); // Scalar data write_bin<int>(output, this->k); if (!this->anomaly) write_bin<int>(output, this->n_clusters); else write_bin<float>(output, this->thresh); write_bin<float>(output, this->denominator); write_bin<float>(output, this->sigma_sq); // Data for (int i = 0; i < n_samples; i++) { const T* data = this->train_data->row(i); write_bin<T>(output, data, n_features); } // Nodes for (int i = 0; i < n_samples; i++) { write_bin<float>(output, this->nodes[i].value); if (!this->anomaly) write_bin<int>(output, this->nodes[i].label); } return output.str(); } template <class T> UnsupervisedOPF<T> UnsupervisedOPF<T>::unserialize(const std::string& contents) { UnsupervisedOPF<float> opf; // Open stream std::istringstream ifs(contents); // , std::ios::in | std::ios::binary /// Header int n_samples; int n_features; char header[4]; // Check if stream is an OPF serialization read_bin<char>(ifs, header, 3); header[3] = '\0'; if (strcmp(header, "OPF")) throw std::invalid_argument("Input is not an OPF serialization"); // Get type and flags uchar type = read_bin<uchar>(ifs); uchar flags = read_bin<uchar>(ifs); // Flags byte read_bin<uchar>(ifs); // reserved byte if (flags & SFlags::Unsup_Anomaly) opf.anomaly = true; if (type != Type::Clustering) throw std::invalid_argument("Input is not an Unsupervised OPF serialization"); // Data size n_samples = read_bin<int>(ifs); n_features = read_bin<int>(ifs); // Scalar data opf.k = read_bin<int>(ifs); if (!opf.anomaly) opf.n_clusters = read_bin<int>(ifs); else { opf.thresh = read_bin<float>(ifs); opf.n_clusters = 2; } opf.denominator = read_bin<float>(ifs); opf.sigma_sq = read_bin<float>(ifs); /// Data // Temporary var to read data, since opf's train_data is const auto train_data = std::shared_ptr<Mat<T>>(new Mat<T>(n_samples, n_features), std::default_delete<Mat<T>>()); // Read data int size = n_samples * n_features; T* data = train_data->row(0); read_bin<T>(ifs, data, size); // Assign to opf opf.train_data = train_data; // Nodes opf.nodes = std::vector<NodeKNN>(n_samples); for (int i = 0; i < n_samples; i++) { opf.nodes[i].value = read_bin<float>(ifs); if (!opf.anomaly) opf.nodes[i].label = read_bin<int>(ifs); } return std::move(opf); } /*****************************************/ } #endif
27.855289
169
0.554595
thierrypin
88c3f7528073ffaf1accc9cbeb797b34aa042b57
3,505
cc
C++
mr_sequential.cc
xtommy-1/cse-labs
70e64309a77ecd57b277c51c7dac046ca60abefe
[ "Apache-2.0" ]
null
null
null
mr_sequential.cc
xtommy-1/cse-labs
70e64309a77ecd57b277c51c7dac046ca60abefe
[ "Apache-2.0" ]
null
null
null
mr_sequential.cc
xtommy-1/cse-labs
70e64309a77ecd57b277c51c7dac046ca60abefe
[ "Apache-2.0" ]
null
null
null
// // A simple sequential MapReduce for WordCount // #include <string> #include <sstream> #include <fstream> #include <iostream> #include <vector> #include <algorithm> #include <regex> using namespace std; typedef struct { string key; string val; } KeyVal; bool isLetter(char p) { return ((p >= 'a' && p <= 'z') || (p >= 'A' && p <= 'Z')); } // // The map function is called once for each file of input. The first // argument is the name of the input file, and the second is the // file's complete contents. You should ignore the input file name, // and look only at the contents argument. The return value is a slice // of key/value pairs. // vector <KeyVal> Map(const string &filename, const string &content) { // Your code goes here // Hints: split contents into an array of words. // regex reg("\\s+"); // vector <string> v(sregex_token_iterator(content.begin(), content.end(), reg, -1), sregex_token_iterator()); int len = content.length(); string str = ""; KeyVal tmp; tmp.val = "1"; vector <KeyVal> ans; ans.clear(); for (int i = 0; i < len; i++) { if (isLetter(content[i])) { str += content[i]; } else { if (str.length() > 0) { tmp.key = str; ans.push_back(tmp); } str = ""; } } return ans; } // // The reduce function is called once for each key generated by the // map tasks, with a list of all the values created for that key by // any map task. // string Reduce(const string &key, const vector <string> &values) { // Your code goes here // Hints: return the number of occurrences of the word. int len = values.size(); int res = 0; for (int i = 0; i < len; i++) { string tmp = values[i]; int tmp1 = atoi(tmp.c_str()); res += tmp1; } return to_string(res); } int main(int argc, char **argv) { if (argc < 2) { cout << "Usage: mrsequential inputfiles...\n"; exit(1); } vector <string> filename; vector <KeyVal> intermediate; // // read each input file, // pass it to Map, // accumulate the intermediate Map output. // for (int i = 1; i < argc; ++i) { string filename = argv[i]; string content; // Read the whole file into the buffer. getline(ifstream(filename), content, '\0'); vector <KeyVal> KVA = Map(filename, content); intermediate.insert(intermediate.end(), KVA.begin(), KVA.end()); } // // a big difference from real MapReduce is that all the // intermediate data is in one place, intermediate[], // rather than being partitioned into NxM buckets. // sort(intermediate.begin(), intermediate.end(), [](KeyVal const &a, KeyVal const &b) { return a.key < b.key; }); // // call Reduce on each distinct key in intermediate[], // and print the result to mr-out-0. // for (unsigned int i = 0; i < intermediate.size();) { unsigned int j = i + 1; for (; j < intermediate.size() && intermediate[j].key == intermediate[i].key;) j++; vector <string> values; for (unsigned int k = i; k < j; k++) { values.push_back(intermediate[k].val); } string output = Reduce(intermediate[i].key, values); printf("%s %s\n", intermediate[i].key.data(), output.data()); i = j; } return 0; }
25.398551
113
0.567475
xtommy-1
88c5cdc5e757ed0ae1d023cf9a5501e289a7821d
214
cpp
C++
Loops/displayDigits/displayDigits.cpp
ntjohns1/cppPractice
c9c18bec889cde56217f68996077b9d409ceef04
[ "Apache-2.0" ]
null
null
null
Loops/displayDigits/displayDigits.cpp
ntjohns1/cppPractice
c9c18bec889cde56217f68996077b9d409ceef04
[ "Apache-2.0" ]
null
null
null
Loops/displayDigits/displayDigits.cpp
ntjohns1/cppPractice
c9c18bec889cde56217f68996077b9d409ceef04
[ "Apache-2.0" ]
null
null
null
#include<iostream> using namespace std; int main() { int n, digit; cout<<"enter a number: "; cin>>n; while(n>0) { digit=n%10; n=n/10; cout<<digit<<" "; } }
12.588235
30
0.448598
ntjohns1
88c6dbab693d2a7388d9602126c089369a4a106d
20,322
cpp
C++
src/caffe/multi_node/fc_thread.cpp
AIROBOTAI/caffe-mnode
e8b03bfb04f09dce21c9b5bbf66dacecb095d3e1
[ "BSD-2-Clause" ]
null
null
null
src/caffe/multi_node/fc_thread.cpp
AIROBOTAI/caffe-mnode
e8b03bfb04f09dce21c9b5bbf66dacecb095d3e1
[ "BSD-2-Clause" ]
null
null
null
src/caffe/multi_node/fc_thread.cpp
AIROBOTAI/caffe-mnode
e8b03bfb04f09dce21c9b5bbf66dacecb095d3e1
[ "BSD-2-Clause" ]
null
null
null
#include <map> #include <string> #include <vector> #include "caffe/multi_node/fc_thread.hpp" #include "caffe/multi_node/param_helper.hpp" namespace caffe { template <typename Dtype> ParamBuf<Dtype> *FcWorker<Dtype>::pbuf_ = NULL; template <typename Dtype> boost::once_flag FcWorker<Dtype>::once_; template <typename Dtype> vector<Blob<Dtype>*> * ParamBuf<Dtype>::RefParam(void *psolver, int clock) { boost::mutex::scoped_lock rlock(ref_mutex_); psolver_to_clock_[psolver] = clock; unordered_map<int, int>::iterator clock_iter = clock_to_idx_.find(clock); int idx = -1; if (clock_iter != clock_to_idx_.end()) { // use the param associated with the clock idx = clock_iter->second; } else { // use the latest param for this clock unordered_map<void *, int>::iterator iter = pointer_to_idx_.find(platest_param_); CHECK(iter != pointer_to_idx_.end()) << "cannot find index to pointer: " << platest_param_; idx = iter->second; clock_to_idx_[clock] = idx; } psolver_to_idx_[psolver] = idx; ref_cnt_vec_[idx]++; return param_vec_[idx]; } template <typename Dtype> vector<Blob<Dtype>*> *ParamBuf<Dtype>::FindParam(void *psolver) { boost::mutex::scoped_lock lock(ref_mutex_); unordered_map<void *, int>::iterator iter = psolver_to_idx_.find(psolver); CHECK(iter != psolver_to_idx_.end()) << "cannot find index to pointer: " << psolver; int idx = iter->second; return param_vec_[idx]; } template <typename Dtype> int ParamBuf<Dtype>::DeRefParam(void *psolver) { boost::mutex::scoped_lock lock(ref_mutex_); unordered_map<void *, int>::iterator iter = psolver_to_idx_.find(psolver); CHECK(iter != psolver_to_idx_.end()) << "cannot find index to pointer: " << psolver; int idx = iter->second; psolver_to_idx_.erase(iter); ref_cnt_vec_[idx]--; CHECK_GE(ref_cnt_vec_[idx], 0) << "unexpected reference counter"; unordered_map<void *, int>::iterator clock_iter = psolver_to_clock_.find(psolver); CHECK(clock_iter != psolver_to_clock_.end()); psolver_to_clock_.erase(clock_iter); return ref_cnt_vec_[idx]; } template <typename Dtype> vector<Blob<Dtype>*> *ParamBuf<Dtype>::CreateParam( const vector<Blob<Dtype>*> &params) { vector<Blob<Dtype>*> *pblobs = new vector<Blob<Dtype>*>(); for (int i = 0; i < params.size(); i++) { Blob<Dtype>* pb = new Blob<Dtype>(); pb->ReshapeLike(*params[i]); pblobs->push_back(pb); } // insert the paramter to buffer boost::mutex::scoped_lock lock(ref_mutex_); pointer_to_idx_[pblobs] = param_vec_.size(); param_vec_.push_back(pblobs); ref_cnt_vec_.push_back(0); CHECK_EQ(ref_cnt_vec_.size(), param_vec_.size()); LOG(INFO) << "created " << ref_cnt_vec_.size() << " parameters"; return pblobs; } template <typename Dtype> void ParamBuf<Dtype>::InitParamBuf(const vector<Blob<Dtype>*> &params) { // create 4 paramters in the beginning for (int i = 0; i < 4; i++) { CreateParam(params); } } template <typename Dtype> vector<Blob<Dtype>*> *ParamBuf<Dtype>::GetParam() { return platest_param_; } template <typename Dtype> vector<Blob<Dtype>*> *ParamBuf<Dtype>::FindFreeParam() { boost::mutex::scoped_lock lock(ref_mutex_); // find a free param pointer vector<Blob<Dtype>*> *pfree = NULL; for (int i = 0; i < param_vec_.size(); i++) { if (ref_cnt_vec_[i] == 0 && param_vec_[i] != platest_param_) { pfree = param_vec_[i]; } } return pfree; } template <typename Dtype> void ParamBuf<Dtype>::ReplaceParam(vector<Blob<Dtype>*> *p) { boost::mutex::scoped_lock lock(ref_mutex_); platest_param_ = p; } template <typename Dtype> void FcThread<Dtype>::CopyInputDataFromMsg(shared_ptr<Net<Dtype> > fc_net, shared_ptr<Msg> m) { for (int i = 0; i < fc_net->num_inputs(); i++) { int blob_index = fc_net->input_blob_indices()[i]; const string& blob_name = fc_net->blob_names()[blob_index]; Blob<Dtype>* pblob = fc_net->input_blobs()[i]; ParamHelper<Dtype>::CopyBlobDataFromMsg(pblob, blob_name, m); } } template <typename Dtype> shared_ptr<Msg> FcThread<Dtype>::FcForward(shared_ptr<Msg> m) { Solver<Dtype> *pfc = (Solver<Dtype> *)NodeEnv::Instance()->PopFreeSolver(); Solver<Dtype> *proot = (Solver<Dtype> *)NodeEnv::Instance()->GetRootSolver(); MLOG(INFO) << "Begin forward for src: " << m->src() << ", ID: " << m->conv_id(); if (NULL == pfc) { const SolverParameter& solver_param = NodeEnv::Instance()->SolverParam(); pfc = (Solver<Dtype> *)this->NewSolver(proot, solver_param); } // copy param data from root solver const vector<Blob<Dtype>*>& params = pfc->net()->learnable_params(); // const vector<Blob<Dtype>*>& root_params = proot->net()->learnable_params(); const vector<Blob<Dtype>*> *ref_params = this->GetParamBuf()->RefParam(pfc, m->clock()); CHECK_EQ(params.size(), ref_params->size()); for (int i = 0; i < params.size(); i++) { // CHECK_EQ(params[i]->count(), ref_params->at(i)->count()); params[i]->ShareData(*ref_params->at(i)); } // ParamHelper<Dtype>::PrintParam(pfc->net()); shared_ptr<Net<Dtype> > fc_net = pfc->net(); CopyInputDataFromMsg(fc_net, m); fc_net->ForwardPrefilled(); shared_ptr<Msg> r(new Msg(m)); // broadcast the message r->set_dst(-1); if (NodeEnv::Instance()->num_splits() > 1) { r->set_is_partial(true); r->set_data_offset(NodeEnv::Instance()->node_position()); } ParamHelper<Dtype>::CopyOutputDataToMsg(fc_net, r); NodeEnv::Instance()->PutSolver(m->msg_id(), pfc); return r; } template <typename Dtype> void FcThread<Dtype>::CopyOutputDiffFromMsg(shared_ptr<Net<Dtype> > fc_net, shared_ptr<Msg> m) { for (int i = 0; i < fc_net->num_outputs(); i++) { int blob_index = fc_net->output_blob_indices()[i]; const string& blob_name = fc_net->blob_names()[blob_index]; Blob<Dtype>* pblob = fc_net->output_blobs()[i]; ParamHelper<Dtype>::CopyBlobDiffFromMsg(pblob, blob_name, m); } } template <typename Dtype> void FcThread<Dtype>::FcBackward(shared_ptr<Msg> m, vector<shared_ptr<Msg> > *preplies, bool copy_diff) { Solver<Dtype> *pfc = (Solver<Dtype> *)NodeEnv::Instance()->FindSolver(m->msg_id()); CHECK(pfc != NULL); MLOG(INFO) << "Begin backward for src: " << m->src() << ", ID: " << m->conv_id(); shared_ptr<Net<Dtype> > fc_net = pfc->net(); if (copy_diff) { CopyOutputDiffFromMsg(fc_net, m); } fc_net->Backward(); const vector<int>& pre_ids = NodeEnv::Instance()->prev_node_ids(); if (pre_ids.size() <= 0) { // we are the gateway node shared_ptr<Msg> r(new Msg(m)); r->set_dst(m->src()); preplies->push_back(r); } else { for (int i = 0; i < pre_ids.size(); i++) { shared_ptr<Msg> r(new Msg(m)); r->set_dst(pre_ids[i]); preplies->push_back(r); } } // copy diff to downstream nodes for (int i = 0; i < preplies->size(); i++) { shared_ptr<Msg> r = preplies->at(i); r->set_type(BACKWARD); ParamHelper<Dtype>::CopyInputDiffToMsg(fc_net, r, i, preplies->size()); } // pfc->UpdateDiff(); // notify the param thread shared_ptr<Msg> notify(new Msg(m)); notify->set_dst(ROOT_THREAD_ID); notify->AppendData(&pfc, sizeof(pfc)); preplies->push_back(notify); } template <typename Dtype> void FcThread<Dtype>::ProcessMsg(shared_ptr<Msg> m) { vector<shared_ptr<Msg> > msg_arr; if (m->type() == FORWARD) { shared_ptr<Msg> f = FcForward(m); msg_arr.push_back(f); } else if (m->type() == BACKWARD) { FcBackward(m, &msg_arr, true); } else { LOG(INFO) << "unkown type: " << m->msg_id(); } for (int i = 0; i < msg_arr.size(); i++) { this->SendMsg(msg_arr[i]); } } template <typename Dtype> void FcThread<Dtype>::Run() { #ifdef USE_MKL int n = mkl_get_max_threads(); LOG(INFO) << "max mkl threads: " << n; mkl_set_dynamic(false); #endif while (!this->must_stop()) { shared_ptr<Msg> m = this->RecvMsg(true); vector<shared_ptr<Msg> > msgs; int clock_bound = clock_ + staleness_; if (m->type() == UPDATE_CLOCK) { clock_ = m->clock(); clock_bound = clock_ + staleness_; for (int i = 0; i < msg_buf_.size(); i++) { if (msg_buf_[i]->clock() <= clock_bound) { ProcessMsg(msg_buf_[i]); } else { msgs.push_back(msg_buf_[i]); } } msg_buf_.clear(); for (int i = 0; i < msgs.size(); i++) { msg_buf_.push_back(msgs[i]); } } else if (m->type() == EXIT_TRAIN) { // exit training return; } else { if (m->clock() <= clock_bound) { ProcessMsg(m); } else { LOG(WARNING) << "Wait for param thread"; msg_buf_.push_back(m); } } } } template <typename Dtype> boost::atomic_int FcLossThread<Dtype>::iter_(0); template <typename Dtype> void FcLossThread<Dtype>::ProcessMsg(shared_ptr<Msg> m) { shared_ptr<Msg> f = this->FcForward(m); vector<shared_ptr<Msg> > replies; this->FcBackward(f, &replies, false); iter_++; for (int i = 0; i < replies.size(); i++) { this->SendMsg(replies[i]); } } #if 0 template <typename Dtype> void FcLossThread<Dtype>::Run() { #ifdef USE_MKL int n = mkl_get_max_threads(); LOG(INFO) << "max mkl threads: " << n; mkl_set_dynamic(false); #endif while (!this->must_stop()) { shared_ptr<Msg> m = this->RecvMsg(true); } } #endif template <typename Dtype> int FcParamThread<Dtype>::GetGroupIndex(void *psolver, int64_t msg_id) { int clock = this->GetParamBuf()->GetClock(psolver); CHECK_NE(clock, INVALID_CLOCK) << "invalid clock"; unordered_map<int, int>::iterator iter = clock_to_group_idx_.find(clock); if (iter != clock_to_group_idx_.end()) { return iter->second; } // find or allocate a new slot the store the group solver int i = 0; for (i = 0; i < group_solvers_.size(); i++) { if (group_solvers_[i] == NULL) { break; } } if (i >= group_solvers_.size()) { group_solvers_.push_back(psolver); grad_updates_vec_.push_back(0); msg_id_vec_.push_back(msg_id); group_loss_vec_.push_back(0); clock_vec_.push_back(clock); clock_to_group_idx_[clock] = group_solvers_.size() - 1; } else { group_solvers_[i] = psolver; grad_updates_vec_[i] = 0; msg_id_vec_[i] = msg_id; group_loss_vec_[i] = 0; clock_vec_[i] = clock; clock_to_group_idx_[clock] = i; } return i; } template <typename Dtype> void FcParamThread<Dtype>::ClearGroup(int grp_idx) { Solver<Dtype> *pgroup_solver = (Solver<Dtype> *)group_solvers_[grp_idx]; CHECK(pgroup_solver != NULL); ParamHelper<Dtype>::ScalDiff(pgroup_solver->net(), (Dtype)0.0); this->GetParamBuf()->RemoveClock(clock_vec_[grp_idx]); this->GetParamBuf()->DeRefParam(pgroup_solver); NodeEnv::Instance()->DeleteSolver(msg_id_vec_[grp_idx]); NodeEnv::Instance()->PushFreeSolver(pgroup_solver); unordered_map<int, int>::iterator iter = clock_to_group_idx_.find(clock_vec_[grp_idx]); clock_to_group_idx_.erase(iter); group_solvers_[grp_idx] = NULL; group_loss_vec_[grp_idx] = 0; grad_updates_vec_[grp_idx] = 0; msg_id_vec_[grp_idx] = INVALID_ID; clock_vec_[grp_idx] = INVALID_CLOCK; } template <typename Dtype> int FcParamThread<Dtype>::UpdateParam(shared_ptr<Msg> m) { Solver<Dtype> *psolver = (Solver<Dtype> *)NodeEnv::Instance()->FindSolver(m->msg_id()); CHECK(psolver != NULL); SGDSolver<Dtype> *proot = (SGDSolver<Dtype> *)NodeEnv::Instance()->GetRootSolver(); #if 0 map<int, int>::iterator map_iter = client_idx_map_.find(m->src()); int client_idx = -1; if (map_iter == client_idx_map_.end()) { // add new client client_idx = AddNewClient(m, psolver); } else { client_idx = map_iter->second; client_clocks_[client_idx] = m->clock(); // TODO: allow one client has many solvers CHECK(client_solvers_[client_idx] == NULL); client_solvers_[client_idx] = psolver; msg_ids_[client_idx] = m->msg_id(); } int clock_bound = MinClock() + staleness_; int num_updates = 0; // update net diff for (int i = 0; i < client_ids_.size(); i++) { if (client_clocks_[i] <= clock_bound && client_solvers_[i] != NULL) { num_updates++; ParamHelper<Dtype>::AddDiffFromNet(proot->net(), client_solvers_[i]->net()); NodeEnv::Instance()->DeleteSolver(msg_ids_[i]); NodeEnv::Instance()->PushFreeSolver(client_solvers_[i]); client_solvers_[i] = NULL; // LOG(INFO) << "update client: " << client_ids_[i]; } } if (num_updates > 0) { proot->net()->Update(); proot->net()->ClearParamDiffs(); train_iter_++; } #endif #if 0 if (sub_batches_ == 0) { ParamHelper<Dtype>::CopyDiffFromNet(proot->net(), psolver->net()); } else { ParamHelper<Dtype>::AddDiffFromNet(proot->net(), psolver->net()); } // doesn't have broadcast nodes means we are loss layer const vector<string>& bcast_addrs = NodeEnv::Instance()->bcast_addrs(); if (bcast_addrs.size() == 0) { const vector<Blob<Dtype>*>& output = psolver->net()->output_blobs(); CHECK_EQ(output.size(), 1) << "only deal with output size 1"; Blob<Dtype>* pblob = output[0]; sub_loss_ += pblob->cpu_data()[0]; } // clear diff params ParamHelper<Dtype>::ScalDiff(psolver->net(), (Dtype)0.0); this->GetParamBuf()->DeRefParam(psolver); NodeEnv::Instance()->DeleteSolver(m->msg_id()); NodeEnv::Instance()->PushFreeSolver(psolver); sub_batches_++; if (sub_batches_ < num_conv_workers_ * this->num_sub_solvers_) { return; } #endif int group_id = GetGroupIndex(psolver, m->msg_id()); Solver<Dtype> *pgroup_solver = (Solver<Dtype> *)group_solvers_[group_id]; // doesn't have broadcast nodes means we are loss layer const vector<string>& bcast_addrs = NodeEnv::Instance()->bcast_addrs(); if (bcast_addrs.size() == 0) { const vector<Blob<Dtype>*>& output = psolver->net()->output_blobs(); CHECK_EQ(output.size(), 1) << "only deal with output size 1"; Blob<Dtype>* pblob = output[0]; group_loss_vec_[group_id] += pblob->cpu_data()[0]; } grad_updates_vec_[group_id]++; // total number of gradients in the system int total_grads = grad_updates_vec_[group_id] + this->QueueSize(); int batch_size = num_conv_workers_ * this->num_sub_solvers_; if (total_grads >= batch_size) { #ifdef USE_MKL // use all the availble threads to accerate computing mkl_set_num_threads_local(total_omp_threads_); #endif } if (pgroup_solver != psolver) { ParamHelper<Dtype>::AddDiffFromNet(pgroup_solver->net(), psolver->net()); // clear diff params ParamHelper<Dtype>::ScalDiff(psolver->net(), (Dtype)0.0); this->GetParamBuf()->DeRefParam(psolver); NodeEnv::Instance()->DeleteSolver(m->msg_id()); NodeEnv::Instance()->PushFreeSolver(psolver); // LOG(INFO) << "release solver for group id: " << group_id; } else { // LOG(INFO) << "keep solver for group id: " << group_id; } if (grad_updates_vec_[group_id] < batch_size) { return 0; } // share paramters const vector<Blob<Dtype>*>& root_params = proot->net()->learnable_params(); vector<Blob<Dtype>*> *param = this->GetParamBuf()->FindFreeParam(); if (param == NULL) { param = this->GetParamBuf()->CreateParam(root_params); } CHECK_EQ(root_params.size(), param->size()); for (int i = 0; i < root_params.size(); i++) { CHECK_EQ(root_params[i]->count(), param->at(i)->count()); if (root_params[i]->cpu_data() != param->at(i)->cpu_data()) { ParamHelper<Dtype>::BlasCopy(root_params[i]->count(), root_params[i]->cpu_data(), param->at(i)->mutable_cpu_data()); root_params[i]->ShareData(*param->at(i)); } } ParamHelper<Dtype>::CopyDiffFromNet(proot->net(), pgroup_solver->net()); // scaling gradients Dtype s = (Dtype)(1.0 / (Dtype)(num_conv_workers_ * this->num_sub_solvers_)); ParamHelper<Dtype>::ScalDiff(proot->net(), s); proot->CommitGradient(); if (bcast_addrs.size() == 0) { group_loss_vec_[group_id] *= s; LOG(INFO) << "train iteration: " << train_iter_ << " loss: " << group_loss_vec_[group_id]; } ClearGroup(group_id); // switch the working param this->GetParamBuf()->ReplaceParam(param); #ifdef USE_MKL // reset mkl threads mkl_set_num_threads_local(this->omp_threads_); #endif #if 0 ParamHelper<Dtype>::PrintParam(proot->net()); ParamHelper<Dtype>::PrintDiff(proot->net()); #endif UpdateClock(); if (train_iter_ == max_iter_) { StopModelServer(); } if (test_node_id_ > 0 && (train_iter_ % TRAIN_NOTIFY_INTERVAL == 0 || train_iter_ > max_iter_) && bcast_addrs.size() == 0 ) { this->SendNotify(); } if (test_node_id_ < 0 && train_iter_ > max_iter_) { return -1; } return 0; } template <typename Dtype> void FcParamThread<Dtype>::StopModelServer() { string ms_addr(NodeEnv::model_server_addr()); int node_id = NodeEnv::Instance()->ID(); shared_ptr<SkSock> dealer(new SkSock(ZMQ_DEALER)); dealer->SetId(node_id); dealer->Connect(ms_addr); shared_ptr<Msg> m(new Msg()); m->set_type(EXIT_TRAIN); m->set_src(node_id); m->set_clock(train_iter_); int pad = 0; m->AppendData(&pad, sizeof(pad)); dealer->SendMsg(m); // notify id server shared_ptr<SkSock> req(new SkSock(ZMQ_REQ)); string id_addr(NodeEnv::id_server_addr()); req->Connect(id_addr); req->SendMsg(m); } template <typename Dtype> void FcParamThread<Dtype>::UpdateClock() { train_iter_++; shared_ptr<Msg> r(new Msg()); r->set_type(UPDATE_CLOCK); r->set_dst(WORKER_BCAST); r->set_src(NodeEnv::Instance()->ID()); r->set_clock(train_iter_); r->AppendData(&train_iter_, sizeof(train_iter_)); this->SendMsg(r); } template <typename Dtype> void FcParamThread<Dtype>::SendNotify() { shared_ptr<Msg> r(new Msg()); r->set_type(TRAIN_ITER); r->set_dst(test_node_id_); r->set_src(NodeEnv::Instance()->ID()); r->AppendData(&train_iter_, sizeof(train_iter_)); // LOG(INFO) << "sending notify"; this->SendMsg(r); } template <typename Dtype> int FcParamThread<Dtype>::SendParam(shared_ptr<Msg> m) { shared_ptr<Msg> r(new Msg()); r->set_type(PUT_PARAM); r->set_dst(m->src()); r->set_src(NodeEnv::Instance()->ID()); Solver<Dtype> *psolver = (Solver<Dtype> *)NodeEnv::Instance()->GetRootSolver(); shared_ptr<Net<Dtype> > net = psolver->net(); ParamHelper<Dtype>::CopyParamDataToMsg(net, net->layer_names(), r); // LOG(INFO) << "sending param"; this->SendMsg(r); if (train_iter_ > max_iter_) { return -1; } return 0; } template <typename Dtype> void FcParamThread<Dtype>::Run() { #ifdef USE_MKL // get the number of omp threads in each worker int fc_omp_threads = mkl_get_max_threads(); if (this->omp_threads_ > 0) { mkl_set_num_threads_local(this->omp_threads_); } int n = mkl_get_max_threads(); LOG(INFO) << "max mkl threads in param thread: " << n; this->omp_threads_ = n; total_omp_threads_ = fc_omp_threads * fc_threads_ + n; mkl_set_dynamic(false); #endif // use the root solver Caffe::set_root_solver(true); while (!this->must_stop()) { shared_ptr<Msg> m = this->RecvMsg(true); if (m->type() == GET_PARAM) { test_node_id_ = m->src(); if (SendParam(m) < 0) { this->SendExit(); return; } } else if (m->type() == EXIT_TRAIN) { // exit training this->SendExit(); return; } else { if (UpdateParam(m) < 0) { this->SendExit(); return; } } } } INSTANTIATE_CLASS(ParamBuf); INSTANTIATE_CLASS(FcWorker); INSTANTIATE_CLASS(FcThread); INSTANTIATE_CLASS(FcLossThread); INSTANTIATE_CLASS(FcParamThread); } // end namespace caffe
27.277852
80
0.635026
AIROBOTAI
88c838d2c91fe5fe7986ecd1f2f442f8990ce5c5
4,497
hh
C++
firmware/src/MightyBoard/shared/LcdBoard.hh
MalyanSystem/Malyan-M180-Sailfish
8dd1ee7178a631f0e54c10db91ab3a18b370c363
[ "AAL" ]
2
2020-08-16T00:24:59.000Z
2021-03-17T10:37:18.000Z
firmware/src/MightyBoard/shared/LcdBoard.hh
MalyanSystem/Malyan-M180-Sailfish
8dd1ee7178a631f0e54c10db91ab3a18b370c363
[ "AAL" ]
null
null
null
firmware/src/MightyBoard/shared/LcdBoard.hh
MalyanSystem/Malyan-M180-Sailfish
8dd1ee7178a631f0e54c10db91ab3a18b370c363
[ "AAL" ]
1
2015-02-01T08:47:20.000Z
2015-02-01T08:47:20.000Z
/* * Copyright 2013 by Yongzong Lin <yongzong@malyansys.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #ifndef LCD_BOARD_HH_ #define LCD_BOARD_HH_ #include "Configuration.hh" #include "Menu.hh" #define SCREEN_STACK_DEPTH 7 /// The LcdBoard module provides support for the Malyan System LCD Interface. /// \ingroup HardwareLibraries class LcdBoard { public: private: uint8_t buff_obj[8]; uint8_t buff_value[12]; uint8_t buff_ptr,buff_state; /// Stack of screens to display; the topmost one will actually /// be drawn to the screen, while the other will remain resident /// but not active. uint8_t screenStack[SCREEN_STACK_DEPTH]; int8_t screenIndex; ///< Stack index of the current screen. /// TODO: Delete this. bool building; ///< True if the bot is building uint8_t waitingMask; ///< Mask of buttons the interface is ///< waiting on. bool screen_locked; /// set to true in case of catastrophic failure (ie heater cuttoff triggered) uint16_t buttonRepetitions; /// Number of times a button has been repeated whilst held down /// used for continuous buttons and speed scaling of incrementers/decrementers bool lockoutButtonRepetitionsClear; /// Used to lockout the clearing of buttonRepetitions void ListFile(uint8_t index); public: LcdBoard(); void writeInt(uint16_t value, uint8_t digits); void writeInt32(uint32_t value, uint8_t digits); void process(); void PrintingStatus(); /// Initialze the interface board. This needs to be called once /// at system startup (or reset). void init(); /// This should be called periodically by a high-speed interrupt to /// service the button input pad. void doInterrupt(); /// This is called for a specific button and returns true if the /// button is currently depressed bool isButtonPressed(uint8_t button); /// Add a new screen to the stack. This automatically calls reset() /// and then update() on the screen, to ensure that it displays /// properly. If there are more than SCREEN_STACK_DEPTH screens already /// in the stack, than this function does nothing. /// \param[in] newScreen Screen to display. void pushScreen(uint8_t newScreen); /// Remove the current screen from the stack. If there is only one screen /// being displayed, then this function does nothing. void popScreen(); /// Return a pointer to the currently displayed screen. uint8_t getCurrentScreen() { return screenStack[screenIndex]; } micros_t getUpdateRate(); void doUpdate(); void showMonitorMode(); void setLED(uint8_t id, bool on); /// Tell the interface board that the system is waiting for a button push /// corresponding to one of the bits in the button mask. The interface board /// will not process button pushes directly until one of the buttons in the /// mask is pushed. void waitForButton(uint8_t button_mask); /// Check if the expected button push has been made. If waitForButton was /// never called, always return true. bool buttonPushed(); /// push Error Message Screen void errorMessage(uint8_t errid, bool incomplete = false); /// lock screen so that no pushes/pops can occur /// used in the case of heater failure to force restart void lock(){ screen_locked = true;} /// push screen onto the stack but don't update - this is used to create /// screen queue void pushNoUpdate(uint8_t newScreen); /// re-initialize LCD void resetLCD(); /// Returns the number of times a button has been held down /// Only applicable to continuous buttons uint16_t getButtonRepetitions(void); }; #endif
34.592308
117
0.683567
MalyanSystem
88cbb50b6aeae06e424b64a97f1ff0b684e81f2c
2,868
cpp
C++
BinaryTree.cpp
unigoetheradaw/AbstractDataTypes
5e91af09d159afe68dbb4c19de9387b2139ea5e7
[ "MIT" ]
null
null
null
BinaryTree.cpp
unigoetheradaw/AbstractDataTypes
5e91af09d159afe68dbb4c19de9387b2139ea5e7
[ "MIT" ]
null
null
null
BinaryTree.cpp
unigoetheradaw/AbstractDataTypes
5e91af09d159afe68dbb4c19de9387b2139ea5e7
[ "MIT" ]
null
null
null
// // Created by Robert on 18/09/2019. // #include <iostream> #include <stdio.h> #include <array> #include <iomanip> using namespace std; class BinaryTree { private: typedef struct Node { int data; Node *left = nullptr; Node *right = nullptr; }; Node *root; public: BinaryTree() { root = new Node; root->data = 50; root->left = nullptr; root->right = nullptr; cout << "Root at: " << &root << endl; } Node *getRoot() { return root; } static Node *generateNode(int data) { Node *temp = new Node(); temp->data = data; temp->left = nullptr; temp->right = nullptr; return temp; } void insert(Node *temp, int data) { if (temp->data > data) { if (temp->left != nullptr) { insert(temp->left, data); } else { temp->left = generateNode(data); } } else { if (temp->right != nullptr) { insert(temp->right, data); } else { temp->right = generateNode(data); } } } void inorder(Node *temp, int indent = 0) { if (temp == nullptr) { return; } inorder(temp->left, indent + 1); cout<< " " << indent << " "<< temp->data; inorder(temp->right, indent + 1); } void postorder(Node *temp, int indent = 0) { if (temp == nullptr) { return; } inorder(temp->left, indent + 1); inorder(temp->right, indent + 1); cout<< " " << indent << " "<< temp->data; } void preorder(Node *temp, int indent = 0) { if (temp == nullptr) { return; } cout<< " " << indent << " "<< temp->data; inorder(temp->left, indent + 1); inorder(temp->right, indent + 1); } int isBalanced(Node* temp, int i = 0) { if (temp == nullptr) { return 0; } else { cout << isBalanced(temp->left, i+1) << endl; cout << isBalanced(temp->left, i+1) << endl; } } int depth(Node* temp) { if (temp == nullptr) { return 0; } else { return max(depth(temp->left)+1, depth(temp->right)+1); } } }; int main() { BinaryTree a = *new BinaryTree; a.insert(a.getRoot(), 1); a.insert(a.getRoot(), 55); a.insert(a.getRoot(), 20); a.insert(a.getRoot(), 56); a.insert(a.getRoot(), 98); cout << a.depth(a.getRoot()) << endl; a.postorder(a.getRoot()); cout <<"\n"; a.preorder(a.getRoot()); cout <<"\n"; a.isBalanced(a.getRoot(), 0); return 0; }
23.9
67
0.448396
unigoetheradaw
88d5ff603da09a240e513f72962a969765012868
100
hh
C++
source/src/hardware/driver/serial/pwmcontroller.hh
Dr-MunirShah/black-sheep
e908203d9516e01f90f4ed4c796cf4143d0df0c0
[ "MIT" ]
7
2019-07-25T10:06:31.000Z
2021-02-20T06:00:51.000Z
source/src/hardware/driver/serial/pwmcontroller.hh
Dr-MunirShah/black-sheep
e908203d9516e01f90f4ed4c796cf4143d0df0c0
[ "MIT" ]
null
null
null
source/src/hardware/driver/serial/pwmcontroller.hh
Dr-MunirShah/black-sheep
e908203d9516e01f90f4ed4c796cf4143d0df0c0
[ "MIT" ]
1
2019-08-31T23:32:02.000Z
2019-08-31T23:32:02.000Z
#pragma once #include "serial.hh" class PWMController : public Serial{ using Serial::Serial; };
12.5
36
0.72
Dr-MunirShah
88d701af23d93501282275751695a0f0663ced4f
1,398
cpp
C++
src/main.cpp
Enhex/Build-Tool-Abstraction
dafeec5b541525884393508c336b9e390095c154
[ "MIT" ]
1
2019-12-29T19:31:03.000Z
2019-12-29T19:31:03.000Z
src/main.cpp
Enhex/Build-Tool-Abstraction
dafeec5b541525884393508c336b9e390095c154
[ "MIT" ]
null
null
null
src/main.cpp
Enhex/Build-Tool-Abstraction
dafeec5b541525884393508c336b9e390095c154
[ "MIT" ]
null
null
null
#include <algorithm> #include "MSBuild.h" #include "Make.h" #include "MakePkg.h" // return true if successfully found the build tool bool find_and_use_tool(fs::path const& path) { auto check_file = [](fs::path const& filepath){ // check for Visual Studio solution file if (filepath.extension() == ".sln") { fs::current_path(filepath.parent_path()); //vs_upgrade(filepath); //TODO should be optional return MSBuild(filepath); } // check for Makefile else if (filepath.filename() == "Makefile") { fs::current_path(filepath.parent_path()); Make(); return true; } // check for PKGBUILD else if (filepath.filename() == "PKGBUILD") { fs::current_path(filepath.parent_path()); MakePkg(); return true; } return false; }; if (fs::is_directory(path)) { for (auto const& entry : fs::directory_iterator(path)) { if(check_file(entry.path())) return true; } } else { if(check_file(path)) return true; } return false; } bool find_and_use_tool() { return find_and_use_tool(fs::current_path()); } int main(int argc, char* argv[]) { if (argc > 2) { std::cerr << "Too many arguments.\n"; return EXIT_FAILURE; } bool success; if (argc == 1) { success = find_and_use_tool(); } else { success = find_and_use_tool(argv[1]); } if (!success) { std::cerr << "could not find build tool file.\n"; return EXIT_FAILURE; } }
18.891892
56
0.651645
Enhex
88d8af8154336d1822535f51f2ceeb67c80fa6b2
6,281
cpp
C++
src/chatlib/client/ChatClient.cpp
heftyy/simple-qt-chat
72c35f0e37bc03197cee09a2919ea559d5222428
[ "Apache-2.0" ]
1
2019-07-17T07:01:12.000Z
2019-07-17T07:01:12.000Z
src/chatlib/client/ChatClient.cpp
heftyy/simple-qt-chat
72c35f0e37bc03197cee09a2919ea559d5222428
[ "Apache-2.0" ]
null
null
null
src/chatlib/client/ChatClient.cpp
heftyy/simple-qt-chat
72c35f0e37bc03197cee09a2919ea559d5222428
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <User.pb.h> #include <ChatMessage.pb.h> #include <NetworkMessage.pb.h> #include <communication/Message.h> #include <communication/MessageDeserializer.h> #include <chat/ChatConnection.h> #include <chat/Chatroom.h> #include <chat/Chatee.h> #include <chat/commands/CommandParser.h> #include "ChatClient.h" namespace SimpleChat { ChatClient::ChatClient() : chatroom_(new Chatroom) { } bool ChatClient::sendCommand(const std::string& command) { CommandParser commandParser(command); auto message = commandParser.chatCommand(); if(message) { auto result = sendAnyMessage(MessageBuilder::build(std::move(message))); if (!result) { std::cerr << "sending a command failed" << std::endl; return false; } return true; } return false; } void ChatClient::sendMessage(const std::string& text, const std::string& target) { auto chatMessage = std::make_unique<ChatMessage>(); chatMessage->set_text(text); if(!target.empty()) { chatMessage->set_allocated_target(chatroom_->getTarget(target).release()); } auto result = sendAnyMessage(MessageBuilder::build(std::move(chatMessage))); if (!result) std::cerr << "sending a message failed" << std::endl; } void ChatClient::updatePresence(int presence) { auto chatee = chatroom_->getChatee(clientName_); if(chatee != nullptr) { auto userChange = std::make_unique<UserChange>(); userChange->mutable_user()->CopyFrom(chatee->user()); userChange->set_presence(static_cast<UserPresence>(presence)); sendAnyMessage(MessageBuilder::build(std::move(userChange))); } } void ChatClient::receiveUntypedMessage(const MessageDeserializer& deserializer) { if (!isConnected()) { std::cerr << "chat connection is invalid" << std::endl; return; } if (!deserializer.isInitialized()) return; if (deserializer.type() == USER_JOIN_RESPONSE) { receiveMessage(deserializer.getMessage<UserJoinResponse>()); } else if (deserializer.type() == USER_LIST_RESPONSE) { receiveMessage(deserializer.getMessage<UserListResponse>()); } else if (deserializer.type() == USER_CHANGE) { receiveMessage(deserializer.getMessage<UserChange>()); } else if (deserializer.type() == CHAT_MESSAGE) { receiveMessage(deserializer.getMessage<ChatMessage>()); } else if(deserializer.type() == CHATROOM_CHANGE) { receiveMessage(deserializer.getMessage<ChatroomChange>()); } else if(deserializer.type() == GENERIC_CHAT_RESPONSE) { receiveMessage(deserializer.getMessage<GenericChatResponse>()); } } void ChatClient::receiveMessage(std::unique_ptr<UserJoinResponse> joinResponse) { std::cout << "joined successfully: " << joinResponse->DebugString().c_str() << std::endl;; if(joinResponse->success()) { requestUserList(); chatroom_->chateeJoined(joinResponse->user(), connection()); chatMotdChanged(joinResponse->motd()); } else { chatInfoReceived(joinResponse->message()); } } void ChatClient::receiveMessage(std::unique_ptr<UserListResponse> listResponse) { for(auto const& user : listResponse->users()) { chatroom_->chateeJoined(user, connection()); } refreshChateeList(); } void ChatClient::receiveMessage(std::unique_ptr<UserChange> userChange) { std::cout << "user change " << userChange->DebugString().c_str() << std::endl; // check for join first because chatee doesn't exist yet if (userChange->has_action()) { if (userChange->action() == JOINED) { chatroom_->chateeJoined(userChange->user(), connection()); chatInfoReceived(userChange->user().name() + " joined"); refreshChateeList(); return; } } auto chatee = chatroom_->getChatee(userChange->user().name()); if(chatee == nullptr) return; if(userChange->has_presence()) { chatee->user().set_presence(userChange->presence()); chatInfoReceived( userChange->user().name() + " is now " + UserPresence_Name(userChange->presence())); refreshChateeList(); } if(userChange->has_action()) { if(userChange->action() == MUTED) { chatee->mute(false); chatInfoReceived(userChange->user().name() + " has been muted"); } else if(userChange->action() == UNMUTED) { chatee->unmute(false); chatInfoReceived(userChange->user().name() + " has been unmuted"); } else if(userChange->action() == LEFT) { chatroom_->chateeLeft(userChange->user().name()); chatInfoReceived(userChange->user().name() + " left"); refreshChateeList(); } else if(userChange->action() == KICKED) { chatee->kick(false); chatInfoReceived(userChange->user().name() + " has been kicked"); refreshChateeList(); } } } void ChatClient::receiveMessage(std::unique_ptr<ChatMessage> chatMessage) { chatMessageReceived(chatMessage->text(), chatMessage->from().user_name(), chatMessage->has_target() ? chatMessage->target().user_name() : ""); } void ChatClient::receiveMessage(std::unique_ptr<ChatroomChange> chatroomChange) { if (chatroomChange->has_motd()) chatMotdChanged(chatroomChange->motd()); } void ChatClient::receiveMessage(std::unique_ptr<GenericChatResponse> response) { if(response->has_message()) { chatInfoReceived(response->message()); } } void ChatClient::join() { auto joinRequest = std::make_unique<UserJoinRequest>(); joinRequest->set_name(clientName_); sendAnyMessage(MessageBuilder::build(std::move(joinRequest))); } void ChatClient::requestUserList() { auto userListRequest = std::make_unique<UserListRequest>(); userListRequest->set_name(clientName_); sendAnyMessage(MessageBuilder::build(std::move(userListRequest))); } std::shared_ptr<Chatroom> ChatClient::chatroom() { return chatroom_; } std::string ChatClient::name() { return clientName_; } } // SimpleChat namespace
30.789216
96
0.646872
heftyy
88d8e2a584a1e2ff43810daacdcc69315a79e0bf
6,678
cpp
C++
test/TestAlgorithm.cpp
AdrianWR/ft_containers
a6b519806448853b97dff385cf72dfc0e97c8ea2
[ "MIT" ]
null
null
null
test/TestAlgorithm.cpp
AdrianWR/ft_containers
a6b519806448853b97dff385cf72dfc0e97c8ea2
[ "MIT" ]
3
2022-02-10T12:16:37.000Z
2022-03-24T03:15:01.000Z
test/TestAlgorithm.cpp
AdrianWR/ft_containers
a6b519806448853b97dff385cf72dfc0e97c8ea2
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include "algorithm.hpp" #include <algorithm> #include <deque> #include <map> #include <string> #include <vector> bool pred_int(int a, int b) { return a == b; } bool pred_str(std::string a, std::string b) { return a == b; } bool pred_map(std::pair<int, int> a, std::pair<int, int> b) { return a == b; } bool comp_int(int a, int b) { return a < b; } bool comp_str(std::string a, std::string b) { return a < b; } bool comp_map(std::pair<int, int> a, std::pair<int, int> b) { return a < b; } // Tests ft::equal TEST(TestEqual, TestEqualTrue) { std::vector<int> v1 = {1, 2, 3, 4, 5}; std::vector<int> v2 = {1, 2, 3, 4, 5}; std::vector<std::string> v3 = {"1", "2", "3", "4", "5"}; std::vector<std::string> v4 = {"1", "2", "3", "4", "5"}; std::map<int, int> m1 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; std::map<int, int> m2 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; // ASSERT_TRUE(ft::equal(v1.begin(), v1.end(), v2.begin())); EXPECT_TRUE(ft::equal(v1.begin(), v1.end(), v2.begin())); EXPECT_TRUE(ft::equal(v1.rbegin(), v1.rend(), v2.rbegin())); EXPECT_TRUE(ft::equal(v3.begin(), v3.end(), v4.begin())); EXPECT_TRUE(ft::equal(m1.begin(), m1.end(), m2.begin())); } TEST(TestEqual, TestEqualFalse) { std::vector<int> v1 = {1, 2, 3, 4, 5}; std::vector<int> v2 = {1, 2, 3, 4, 6}; std::map<int, int> m1 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; std::map<int, int> m2 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 6}}; std::deque<int> d1 = {1, 2, 3, 4, 5}; std::deque<int> d2 = {1, 2, 3, 4, 6}; EXPECT_FALSE(ft::equal(v1.begin(), v1.end(), v2.begin())); EXPECT_FALSE(ft::equal(v1.rbegin(), v1.rend(), v2.rbegin())); EXPECT_FALSE(ft::equal(m1.begin(), m1.end(), m2.begin())); EXPECT_FALSE(ft::equal(m1.rbegin(), m1.rend(), m2.rbegin())); EXPECT_FALSE(ft::equal(d1.begin(), d1.end(), d2.begin())); } TEST(TestEqual, TestEqualEmpty) { std::vector<int> v1; std::vector<int> v2; std::map<int, int> m1; std::map<int, int> m2; std::deque<int> d1; std::deque<int> d2; EXPECT_TRUE(ft::equal(v1.begin(), v1.end(), v2.begin())); EXPECT_TRUE(ft::equal(v1.rbegin(), v1.rend(), v2.rbegin())); EXPECT_TRUE(ft::equal(m1.begin(), m1.end(), m2.begin())); EXPECT_TRUE(ft::equal(m1.rbegin(), m1.rend(), m2.rbegin())); EXPECT_TRUE(ft::equal(d1.begin(), d1.end(), d2.begin())); } TEST(TestEqual, TestEqualPredicate) { std::vector<int> v1 = {1, 2, 3, 4, 5}; std::vector<int> v2 = {1, 2, 3, 4, 5}; std::vector<std::string> v3 = {"1", "2", "3", "4", "5"}; std::vector<std::string> v4 = {"1", "2", "3", "4", "5"}; std::map<int, int> m1 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; std::map<int, int> m2 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; EXPECT_TRUE(ft::equal(v1.begin(), v1.end(), v2.begin(), pred_int)); EXPECT_TRUE(ft::equal(v1.rbegin(), v1.rend(), v2.rbegin(), pred_int)); EXPECT_TRUE(ft::equal(v3.begin(), v3.end(), v4.begin(), pred_str)); EXPECT_TRUE(ft::equal(v3.rbegin(), v3.rend(), v4.rbegin(), pred_str)); EXPECT_TRUE(ft::equal(m1.begin(), m1.end(), m2.begin(), pred_map)); EXPECT_TRUE(ft::equal(m1.rbegin(), m1.rend(), m2.rbegin(), pred_map)); } TEST(TestEqual, TestEqualDifferentContainers) { int v0[] = {1, 2, 3, 4, 5}; std::vector<int> v1 = {1, 2, 3, 4, 5}; EXPECT_TRUE(ft::equal(v1.begin(), v1.end(), v0)); EXPECT_TRUE(ft::equal(v1.begin(), v1.end(), v0, pred_int)); } // Tests ft::lexicographical_compare TEST(TestLexicographicalCompare, TestLexicographicalCompareEqual) { std::vector<int> v1 = {1, 2, 3, 4, 5}; std::vector<int> v2 = {1, 2, 3, 4, 5}; std::vector<std::string> v3 = {"1", "2", "3", "4", "5"}; std::vector<std::string> v4 = {"1", "2", "3", "4", "5"}; std::map<int, int> m1 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; std::map<int, int> m2 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; EXPECT_FALSE( ft::lexicographical_compare(v1.begin(), v1.end(), v2.begin(), v2.end())); EXPECT_FALSE(ft::lexicographical_compare(v1.rbegin(), v1.rend(), v2.rbegin(), v2.rend())); EXPECT_FALSE( ft::lexicographical_compare(v3.begin(), v3.end(), v4.begin(), v4.end())); EXPECT_FALSE(ft::lexicographical_compare(v3.rbegin(), v3.rend(), v4.rbegin(), v4.rend())); EXPECT_FALSE( ft::lexicographical_compare(m1.begin(), m1.end(), m2.begin(), m2.end())); EXPECT_FALSE(ft::lexicographical_compare(m1.rbegin(), m1.rend(), m2.rbegin(), m2.rend())); } TEST(TestLexicographicalCompare, TestLexicographicalCompareLess) { std::vector<int> v1 = {1, 2, 3, 4, 5}; std::vector<int> v2 = {1, 2, 3, 4, 6}; std::map<int, int> m1 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; std::map<int, int> m2 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 6}}; std::deque<int> d1 = {1, 2, 3, 4, 5}; std::deque<int> d2 = {1, 2, 3, 4, 6}; EXPECT_TRUE( ft::lexicographical_compare(v1.begin(), v1.end(), v2.begin(), v2.end())); EXPECT_TRUE( ft::lexicographical_compare(m1.begin(), m1.end(), m2.begin(), m2.end())); EXPECT_TRUE( ft::lexicographical_compare(d1.begin(), d1.end(), d2.begin(), d2.end())); } TEST(TestLexicographicalCompare, TestLexicographicalCompareGreater) { std::vector<int> v1 = {1, 2, 3, 4, 5}; std::vector<int> v2 = {1, 2, 3, 4, 4}; std::map<int, int> m1 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; std::map<int, int> m2 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 4}}; std::deque<int> d1 = {1, 2, 3, 4, 5}; std::deque<int> d2 = {1, 2, 3, 4, 4}; EXPECT_FALSE( ft::lexicographical_compare(v1.begin(), v1.end(), v2.begin(), v2.end())); EXPECT_FALSE( ft::lexicographical_compare(m1.begin(), m1.end(), m2.begin(), m2.end())); EXPECT_FALSE( ft::lexicographical_compare(d1.begin(), d1.end(), d2.begin(), d2.end())); } TEST(TestLexicographicalCompare, TestLexicographicalCompareCompFunc) { std::vector<int> v1 = {1, 2, 3, 4, 5}; std::vector<int> v2 = {1, 2, 3, 4, 6}; std::map<int, int> m1 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; std::map<int, int> m2 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 6}}; std::vector<std::string> v3 = {"1", "2", "3", "4", "5"}; std::vector<std::string> v4 = {"1", "2", "3", "4", "6"}; EXPECT_TRUE(ft::lexicographical_compare(v1.begin(), v1.end(), v2.begin(), v2.end(), comp_int)); EXPECT_TRUE(ft::lexicographical_compare(v3.begin(), v3.end(), v4.begin(), v4.end(), comp_str)); EXPECT_TRUE(ft::lexicographical_compare(m1.begin(), m1.end(), m2.begin(), m2.end(), comp_map)); }
41.7375
79
0.549117
AdrianWR
88de24f2162a886a0a7fc0f5fe81527bf16e7306
801
cpp
C++
PATest_paractice/PAT_1005.cpp
Ginuo/DataStructure_Algorithm
3db0b328eeab9270fca14123061551de087d186c
[ "Apache-2.0" ]
null
null
null
PATest_paractice/PAT_1005.cpp
Ginuo/DataStructure_Algorithm
3db0b328eeab9270fca14123061551de087d186c
[ "Apache-2.0" ]
null
null
null
PATest_paractice/PAT_1005.cpp
Ginuo/DataStructure_Algorithm
3db0b328eeab9270fca14123061551de087d186c
[ "Apache-2.0" ]
null
null
null
#include<cstdio> #include<cstring> int main(){ char num[110]; gets(num); int len = strlen(num); int sum = 0; for(int i = 0; i < len; i++){ sum = sum + (num[i] - '0'); } int ans[100]; int index = 0; do{ ans[index++] = sum % 10; sum = sum / 10; }while(sum != 0); for(int i = index-1 ; i >= 0; i--){ switch(ans[i]){ case 0: printf("zero"); break; case 1: printf("one"); break; case 2: printf("two"); break; case 3: printf("three"); break; case 4: printf("four"); break; case 5: printf("five"); break; case 6: printf("six"); break; case 7: printf("seven"); break; case 8: printf("eight"); break; case 9: printf("nine"); break; } if(i > 0) printf(" "); } return 0; }
14.052632
36
0.486891
Ginuo
88df77e9b7aab27a0fce060078d0e5d3c0ee4812
349
cpp
C++
Problems/0026. Remove Duplicates from Sorted Array.cpp
KrKush23/LeetCode
2a87420a65347a34fba333d46e1aa6224c629b7a
[ "MIT" ]
null
null
null
Problems/0026. Remove Duplicates from Sorted Array.cpp
KrKush23/LeetCode
2a87420a65347a34fba333d46e1aa6224c629b7a
[ "MIT" ]
null
null
null
Problems/0026. Remove Duplicates from Sorted Array.cpp
KrKush23/LeetCode
2a87420a65347a34fba333d46e1aa6224c629b7a
[ "MIT" ]
null
null
null
#define pb push_back class Solution { public: int removeDuplicates(vector<int>& nums) { vector<int> v = nums; nums.clear(); if(v.empty()) return 0; nums.pb(v[0]); for(int i=1;i<(int)v.size();i++) if(v[i]!=v[i-1]) nums.pb(v[i]); return nums.size(); } };
21.8125
45
0.461318
KrKush23
88e076022188d589357a5d2575a22d454d8b15f0
1,119
hpp
C++
tsdbutil/SerializedStringTuples.hpp
naivewong/timeunion
8070492d2c6a2d68175e7d026c27b858c2aec8e6
[ "Apache-2.0" ]
null
null
null
tsdbutil/SerializedStringTuples.hpp
naivewong/timeunion
8070492d2c6a2d68175e7d026c27b858c2aec8e6
[ "Apache-2.0" ]
null
null
null
tsdbutil/SerializedStringTuples.hpp
naivewong/timeunion
8070492d2c6a2d68175e7d026c27b858c2aec8e6
[ "Apache-2.0" ]
null
null
null
#ifndef SERIALIZEDSTRINGTUPLES_H #define SERIALIZEDSTRINGTUPLES_H #include <stdint.h> #include <boost/function.hpp> #include "tsdbutil/StringTuplesInterface.hpp" namespace tsdb { namespace tsdbutil { class SerializedStringTuples : public StringTuplesInterface { public: typedef boost::function<std::string(uint64_t)> Lookup; const uint8_t *b; uint32_t tuple_size; // Currently should be 1 uint32_t size; uint32_t len_; Lookup lookup; bool clean_; SerializedStringTuples() : size(0), len_(0), clean_(false) {} SerializedStringTuples(const uint8_t *b, uint32_t tuple_size, uint32_t size, const Lookup &lookup, bool clean = false) : b(b), size(size), tuple_size(tuple_size), len_(size / (tuple_size * 4)), lookup(lookup), clean_(clean) {} ~SerializedStringTuples() { if (clean_) delete b; } uint32_t len() { return len_; } std::string at(int i) { if (i >= len_) return ""; return lookup(base::get_uint32_big_endian(b + 4 * tuple_size * i)); } }; } // namespace tsdbutil } // namespace tsdb #endif
23.3125
78
0.666667
naivewong
88e0f213a66a9ca4bda465c4039eb14e71d9b10f
11,031
cpp
C++
Generation.cpp
DiscoveryInstitute/coaly
3b9617b13887ae30423b192dcf89526d84b64d29
[ "MIT" ]
null
null
null
Generation.cpp
DiscoveryInstitute/coaly
3b9617b13887ae30423b192dcf89526d84b64d29
[ "MIT" ]
null
null
null
Generation.cpp
DiscoveryInstitute/coaly
3b9617b13887ae30423b192dcf89526d84b64d29
[ "MIT" ]
null
null
null
#include "Generation.h" #include <cmath> #include <limits> #include <numeric> #include <vector> using namespace std; const double EPSILON = numeric_limits<double>::epsilon(); /** * Given lambda, the expected number of ancestral children per member of the population, * calculate the probability of having 'ic' ancestral children on the assumption that * the parent has one or more ancestral children. This is the probability of 'ic' lineages * coalescing into one lineage. These probabilities are calculated up to 'max_coalescent' * or until they are numerically negligible. * * The 0th index of the array contains a special case: the probability of having no children. * This quantity is useful for calculating the expected ancestral parent population. */ vector<double> getCoalescenceProbabilities(double n, double p, int max_coalescent) { const double lambda = n * p; const double eml = exp(-lambda); vector<double> coal_probs; coal_probs.reserve(max_coalescent+1); coal_probs.push_back(eml); // special case: p(n=0) double coal_p = eml / (1.0 - eml); // p(n given n!=0) for (long ic=1; ic<=max_coalescent; ++ic) { coal_p *= lambda / ic; // probability that one ancestor has 'ic' ancestral children if (coal_p < EPSILON && lambda < ic) break; coal_probs.push_back(coal_p); } return coal_probs; } /* vector<double> getCoalescenceProbabilities(double n, double p, int max_coalescent) { const double lambda = n * p; vector<double> coal_probs; coal_probs.reserve(max_coalescent+1); const double p0 = pow(1.0-p, n); coal_probs.push_back(p0); // special case: p(n=0) double pre = 1.0 / (1.0 - p0); // p(n given n!=0) double logp = log(p); double logq = log(1.0-p); for (long ic=1; ic<=max_coalescent; ++ic) { double coal_p = pre*exp(lgamma(n+1) -lgamma(ic+1)-lgamma(n-ic+1) + ic*logp +(n-ic)*logq); // probability that one ancestor has 'ic' ancestral children if (coal_p < EPSILON && lambda < ic) break; coal_probs.push_back(coal_p); } return coal_probs; } */ /** * Calculate coalescence for one generation. */ void Generation::coalesceOneGeneration(double new_total_popn) { const auto& weights = this->number_of_descendants_distribution; const long sample_popn = weights.size()-1; const double n = this->ancestral_population; const double p = 1.0 / new_total_popn; vector<double> coal_probs = getCoalescenceProbabilities(n, p, sample_popn); this->total_population = new_total_popn; this->ancestral_population = new_total_popn * (1.0 - coal_probs[0]); this->coalescence_probabilities = move(coal_probs); updateSample(); } /** Determines whether or not probabilities warrant an update of the sample */ inline bool maxed(vector<double>& probs, int imax) { while (!probs.empty() && probs.back() < EPSILON) probs.pop_back(); return (probs.size() > (size_t)imax); } /** * Calculate coalescence for one generation, * but don't update whole sample unless the probabilities warrant it. */ void Generation::coalesceLiteOneGeneration(double new_total_popn, int max_coalescent){ const auto& weights = this->number_of_descendants_distribution; const long sample_popn = weights.size(); const double n = this->ancestral_population; const double p = 1.0 / new_total_popn; vector<double>& accum_probs = this->coalescence_probabilities; vector<double> coal_probs = getCoalescenceProbabilities(n, p, sample_popn); this->total_population = new_total_popn; this->ancestral_population = new_total_popn * (1.0 - coal_probs[0]); // If lots of coalescence this gen, update the sample to flush any existing probabilities. if (maxed(coal_probs, max_coalescent)) { updateSample(); // update to flush existing probabilities first accum_probs = move(coal_probs); updateSample(); // update with new probabilities return; } // If there are no accumulated probabilities (and current probabilities are not maxed), // the initial assignment is simple. if (accum_probs.empty()) { accum_probs = move(coal_probs); return; } // Compare this section with the section for coalescing the whole sample coal_probs.resize(max_coalescent+1); accum_probs.resize(max_coalescent+1); vector<double> new_accum_probs(max_coalescent+1); vector<double> uvec = accum_probs; vector<double> new_uvec(uvec.size()); for (long i=1; i<=max_coalescent; ++i) new_accum_probs[i] = coal_probs[1] * uvec[i]; for (long ic=2; ic<=max_coalescent; ++ic) { fill(new_uvec.begin(), new_uvec.end(), 0.0); for(long i=ic; i<=max_coalescent; ++i) { long pic = ic-1; for(long j=1; j<=i-pic; ++j) { new_uvec[i] += accum_probs[j] * uvec[i-j]; } if (new_uvec[i] < EPSILON && i > 0 && new_uvec[i-1] >= new_uvec[i]) break; } uvec.swap(new_uvec); for(long i=ic;i<=max_coalescent;++i) { new_accum_probs[i] += coal_probs[ic] * uvec[i]; } } this->coalescence_probabilities = move(new_accum_probs); if (maxed(accum_probs, max_coalescent)) updateSample(); } /** * Update the sample (number_of_descendants_distribution) using * the stored coalescence probabilities, * which might be just from this generation, * or may have been accumulated over several generations. */ void Generation::updateSample() { const auto& weights = this->number_of_descendants_distribution; const long sample_popn = weights.size(); vector<double>& coal_probs = this->coalescence_probabilities; while (!coal_probs.empty() && coal_probs.back()<EPSILON) coal_probs.pop_back(); const long max_ic = coal_probs.size()-1; if (max_ic < 2) return; vector<double> new_weights(sample_popn, 0.0); // uvec_n is a helper vector that can be thought of as weights^n // uvec_1[i] is just weights[i] // uvec_2[i] is sum_j weights[j] * weights[i-j] // uvec_3[i] is sum_jk weights[j] * weights[k] * weights[i-j-k] vector<double> uvec = weights; vector<double> new_uvec(uvec.size()); for(long i=1;i<sample_popn;++i) new_weights[i] += coal_probs[1] * uvec[i]; // For each number of ancestral children ic >= 2 for (long ic=2; ic<=max_ic; ++ic) { // Update uvec_ic -> uvec_(ic+1); fill(new_uvec.begin(), new_uvec.end(), 0.0); for(long i=ic; i<sample_popn; ++i) { long pic = ic-1; for(long j=1; j<=i-pic; ++j) { new_uvec[i] += weights[j] * uvec[i-j]; } if (new_uvec[i] < EPSILON && i > 0 && new_uvec[i-1] >= new_uvec[i]) break; } uvec.swap(new_uvec); // Add a contribution to the weights for(long i=ic;i<sample_popn;++i) { new_weights[i] += coal_probs[ic] * uvec[i]; } } this->number_of_descendants_distribution = move(new_weights); this->coalescence_probabilities.clear(); } /** * Add mutations at the given rate, incrementing the allele frequency spectrum using * the number_of_descendants_distribution at this generation. */ void Generation::incrementAlleleFrequencySpectrumMutations( vector<double>& afs, const double mutation_rate) const { const double prefactor = this->ancestral_population * mutation_rate; const auto& weight = this->number_of_descendants_distribution; for (size_t i=1; i<weight.size(); ++i) afs[i] += prefactor * weight[i]; } /** Combinatorial function, "N choose m" or C^n_m = n!/(m!(n-m)!) */ double n_choose_m(int ni, int mi) { double n = (double)ni; double m = (double)min(mi, ni-mi); double numerator = 1.0; for (int i=0; i<m; ++i) numerator *= (double)(n-i); double denominator = 1.0; for (int i=2; i<=m; ++i) denominator *= (double)i; return numerator / denominator; } /** * Add genetic diversity from 1,2,3,... founders, incrementing the allele frequency spectrum * using the number_of_descendants_distribution for that number of founders. */ void Generation::incrementAlleleFrequencySpectrumFoundingDiversity( vector<double>& afs, const vector<double>& founding_diversity) const { const vector<double>& weights = this->number_of_descendants_distribution; const long sample_popn = weights.size(); const long max_ic = founding_diversity.size() - 1; if (max_ic < 1) return; // First transform founding diversity into ancestral founding diversity. vector<double> ancestral_diversity(max_ic+1); double pnonzero = this->ancestral_population / this->total_population; double pzero = 1.0 - pnonzero; for (int i=1;i<=max_ic;++i) { for (int j=i;j<=max_ic;++j) { double pij = pow(pnonzero,i) * pow(pzero,j-i) * n_choose_m(j,i); ancestral_diversity[i] += pij * founding_diversity[j]; } } // Add contributions to the Allele Frequency Spectrum vector<double> uvec = weights; vector<double> new_uvec(uvec.size()); // For single founders for(long i=1;i<sample_popn;++i) afs[i] += ancestral_diversity[1] * uvec[i]; // For multiple founders for (int ic=2; ic<=max_ic; ++ic) { // Update uvec_ic -> uvec_(ic+1); fill(new_uvec.begin(), new_uvec.end(), 0.0); for(long i=ic; i<sample_popn; ++i) { long pic = ic-1; for(long j=1; j<=i-pic; ++j) { new_uvec[i] += weights[j] * uvec[i-j]; } if (new_uvec[i] < EPSILON && i > 0 && new_uvec[i-1] >= new_uvec[i]) break; } uvec.swap(new_uvec); // Add a contribution to the weights for(long i=ic;i<sample_popn;++i) { afs[i] += ancestral_diversity[ic] * uvec[i]; } } } /** Calculate AFS using the population history, mutation rate history, and any founding diversity. */ vector<double> Generation::calculateAFS(const double sample_popn, const vector<double>& popn_history, const vector<double>& mutn_history, const vector<double>& founding_diversity) { const int max_coalescent = 10; Generation generation (popn_history[0], sample_popn); vector<double> afs(sample_popn+1, 0.0); const long ngens = popn_history.size(); for (long igen = 0; igen < ngens; ++igen) { generation.coalesceLiteOneGeneration(popn_history[igen], max_coalescent); generation.incrementAlleleFrequencySpectrumMutations(afs, mutn_history[igen]); } generation.incrementAlleleFrequencySpectrumFoundingDiversity(afs, founding_diversity); return afs; }
39.823105
159
0.637567
DiscoveryInstitute
88e10f35fbebe90c460f2cc957b8d6446c2f40f4
11,947
cpp
C++
src/core/cruntimetracker.cpp
squigglepuff/XonMap
3c426c9fd66eda77c34d78dd45566062c702f6b9
[ "Apache-2.0" ]
null
null
null
src/core/cruntimetracker.cpp
squigglepuff/XonMap
3c426c9fd66eda77c34d78dd45566062c702f6b9
[ "Apache-2.0" ]
null
null
null
src/core/cruntimetracker.cpp
squigglepuff/XonMap
3c426c9fd66eda77c34d78dd45566062c702f6b9
[ "Apache-2.0" ]
null
null
null
#include "core/cruntimetracker.h" std::unique_ptr<GlobalCVariables> g_pCVars; std::unique_ptr<CRuntimeTracker> g_CrtTracker{new CRuntimeTracker}; // These are local to this module only! #if defined(Q_OS_WINDOWS) static PDH_HQUERY gCpuQuery; static PDH_HCOUNTER gCpuTotal; #endif //#if (Q_OS_WINDOWS). CRuntimeTracker::CRuntimeTracker() { // Intentionally left blank. } CRuntimeTracker::~CRuntimeTracker() { // Intentionally left blank. } Error_t CRuntimeTracker::Init() { Error_t iRtn = SUCCESS; // Attempt to reset the pointer back to a sane state. g_pCVars.reset(new GlobalCVariables); // WINDOWS ONLY! Setup the PDH and Symbol stuff. #if defined(Q_OS_WINDOWS) PdhOpenQuery(NULL, NULL, &gCpuQuery); PdhAddEnglishCounter(gCpuQuery, "\\Processor(_Total)\\% Processor Time", NULL, &gCpuTotal); SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS); SymInitialize(GetCurrentProcess(), NULL, TRUE); #endif //#if defined(Q_OS_WINDOWS). if (nullptr == g_pCVars) { iRtn = Err_Ptr_AllocFail; } else { iRtn = Update(); } return iRtn; } Error_t CRuntimeTracker::Update() { Error_t iRtn = SUCCESS; #if defined(Q_OS_WINDOWS) // Grab system memory statistics. MEMORYSTATUSEX lMemInfo; lMemInfo.dwLength = sizeof(MEMORYSTATUSEX); if (0 != GlobalMemoryStatusEx(&lMemInfo)) { DWORDLONG iFreeVirtMem = lMemInfo.ullAvailPageFile; DWORDLONG iTotalVirtMem = lMemInfo.ullTotalPageFile; DWORDLONG iUsedVirtMem = iTotalVirtMem - iFreeVirtMem; // Update the CVar. g_pCVars->mMemSysTotal = static_cast<float>(iTotalVirtMem) / 1024 / 1024; g_pCVars->mMemSysFree = static_cast<float>(iFreeVirtMem) / 1024 / 1024; g_pCVars->mMemSysUsed = static_cast<float>(iUsedVirtMem) / 1024 / 1024; // Grab the process memory statistics. PROCESS_MEMORY_COUNTERS lProcMemCnt; if (0 != GetProcessMemoryInfo(GetCurrentProcess(), &lProcMemCnt, sizeof(lProcMemCnt))) { SIZE_T iProcMemUsage = lProcMemCnt.PagefileUsage; // Update the CVar. g_pCVars->mMemProcUsed = static_cast<float>(iProcMemUsage) / 1024 / 1024; // Grab the CPU stats for the system. PDH_FMT_COUNTERVALUE lCountVal; PDH_STATUS lStatus = PdhCollectQueryData(gCpuQuery); if (ERROR_SUCCESS == lStatus) { lStatus = PdhGetFormattedCounterValue(gCpuTotal, PDH_FMT_DOUBLE, NULL, &lCountVal); if (ERROR_SUCCESS == lStatus) { // Update the CVar. g_pCVars->mCPUSysUsage = static_cast<float>(lCountVal.doubleValue); // If needed, we can setup any network statistics right here. } else if (lStatus == PDH_INVALID_ARGUMENT) { fprintf(stderr, "ERR: A parameter is not valid or is incorrectly formatted.\n"); iRtn = GetLastError(); } else if (lStatus == PDH_INVALID_DATA) { fprintf(stderr, "ERR: The specified counter does not contain valid data or a successful status code.\n"); iRtn = SUCCESS; } else if (lStatus == PDH_INVALID_HANDLE) { fprintf(stderr, "ERR: The counter handle is not valid.\n"); iRtn = GetLastError(); } else { iRtn = GetLastError(); } } else if (lStatus == PDH_INVALID_ARGUMENT) { fprintf(stderr, "ERR: A parameter is not valid or is incorrectly formatted.\n"); iRtn = GetLastError(); } else if (lStatus == PDH_INVALID_DATA) { fprintf(stderr, "ERR: The specified counter does not contain valid data or a successful status code.\n"); iRtn = SUCCESS; } else if (lStatus == PDH_INVALID_HANDLE) { fprintf(stderr, "ERR: The counter handle is not valid.\n"); iRtn = GetLastError(); } else { iRtn = GetLastError(); } } else { iRtn = GetLastError(); } } else { iRtn = GetLastError(); } #elif defined(Q_OS_LINUX) #else #endif //#if defined(Q_OS_WINDOWS) // Update the clock time. g_pCVars->mRuntime = clock(); // Done! return iRtn; } Error_t CRuntimeTracker::DumpStack() { Error_t iRtn = SUCCESS; const size_t ciMaxFrames = 63; const size_t ciMaxBuffSz = (0xFF) - 1; #if defined(Q_OS_WINDOWS) PVOID* pFrames = new PVOID[ciMaxFrames]; if (nullptr != pFrames) { memset(pFrames, 0, sizeof(PVOID)*ciMaxFrames); size_t iCapFrames = CaptureStackBackTrace(0, ciMaxFrames, pFrames, NULL); SYMBOL_INFO *pSymbol = new SYMBOL_INFO; if (nullptr != pSymbol) { pSymbol->MaxNameLen = 255; pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO); char* pData = new char[ciMaxBuffSz]; memset(pData, 0, ciMaxBuffSz); if (nullptr != pData) { std::string lDumpStr = ""; for (size_t iIdx = 1; iIdx < iCapFrames; ++iIdx) // We start at 1 since we don't want to dump this function as part of the stack. { SymFromAddr(GetCurrentProcess(), reinterpret_cast<DWORD64>(pFrames[iIdx]), 0, pSymbol); sprintf(pData, "\t%zd: [0x%llX] %s\n", (iCapFrames - iIdx - 1), pSymbol->Address, pSymbol->Name); lDumpStr.append(pData); } // Log the data! #if defined(HAS_LOGGER) #else lDumpStr.append("\n"); fprintf(stdout, lDumpStr.c_str()); #endif //#if defined(HAS_LOGGER) if (nullptr != pData) { delete[] pData; } } else { iRtn = Err_Ptr_AllocFail; } // delete pSymbol; } else { iRtn = Err_Ptr_AllocFail; } delete[] pFrames; } else { iRtn = Err_Ptr_AllocFail; } #elif defined(Q_OS_LINUX) // backtrace(&sStack.mpStack, ciMaxFrames); #elif defined(Q_OS_OSX) #endif //#if defined(Q_OS_WINDOWS). return iRtn; } Error_t CRuntimeTracker::DumpStats(bool iReset) { Error_t iRtn = SUCCESS; const size_t ciMaxBuffSz = 65535; // Allocate a temporary buffer. char* pTmpBuff = new char[ciMaxBuffSz]; memset(pTmpBuff, 0, ciMaxBuffSz); std::string lStatsLine = "Dumping Runtime Statistics...\n"; // Time running. sprintf(pTmpBuff, "Runing time (CPU clocks): %ld\n", g_pCVars->mRuntime); lStatsLine.append(pTmpBuff); memset(pTmpBuff, 0, ciMaxBuffSz); // CPU stats. sprintf(pTmpBuff, "System CPU Usage: %f\n", g_pCVars->mCPUSysUsage); lStatsLine.append(pTmpBuff); memset(pTmpBuff, 0, ciMaxBuffSz); // Memory statistics. sprintf(pTmpBuff, "System Memory Total (MiB): %f\n", g_pCVars->mMemSysTotal); lStatsLine.append(pTmpBuff); memset(pTmpBuff, 0, ciMaxBuffSz); sprintf(pTmpBuff, "System Memory Used (MiB): %f\n", g_pCVars->mMemSysUsed); lStatsLine.append(pTmpBuff); memset(pTmpBuff, 0, ciMaxBuffSz); sprintf(pTmpBuff, "System Memory Free (MiB): %f\n", g_pCVars->mMemSysFree); lStatsLine.append(pTmpBuff); memset(pTmpBuff, 0, ciMaxBuffSz); sprintf(pTmpBuff, "Process Memory Used (MiB): %f\n", g_pCVars->mMemProcUsed); lStatsLine.append(pTmpBuff); memset(pTmpBuff, 0, ciMaxBuffSz); // Network statistics. sprintf(pTmpBuff, "Network Input (KiB): %f\n", g_pCVars->mNetIn); lStatsLine.append(pTmpBuff); memset(pTmpBuff, 0, ciMaxBuffSz); sprintf(pTmpBuff, "Network Output (KiB): %f\n", g_pCVars->mNetOut); lStatsLine.append(pTmpBuff); memset(pTmpBuff, 0, ciMaxBuffSz); // Complete! Dump the data to the log. #if defined(HAS_LOGGER) #else fprintf(stdout, lStatsLine.c_str()); #endif //#if defined(HAS_LOGGER) return iRtn; } std::string CRuntimeTracker::ErrorToString(Error_t iErr) { // Clear the old error. mErrStr.clear(); switch(iErr) { // Errors. case Err_Sig_Hangup: mErrStr = "Recieved a hangup signal! (SIGHUP)\n"; case Err_Sig_Quit: mErrStr = "Recieved a quit signal! (SIGQUIT)\n"; case Err_Sig_Illegal: mErrStr = "Recieved an illegal instruction signal! (SIGILL)\n"; case Err_Sig_Abort: mErrStr = "Recieved an abort signal! (SIGABRT)\n"; case Err_Sig_FloatExcept: mErrStr = "Recieved a floating point exception signal! (SIGFPE)\n"; case Err_Sig_Kill: mErrStr = "Recieved a kill signal! (SIGKILL)\n"; case Err_Sig_Bus: mErrStr = "Recieved a bus error signal! (SIGBUS)\n"; case Err_Sig_SegFault: mErrStr = "Recieved a segmentation fault signal! (SIGSEGV)\n"; case Err_Sig_SysCall: mErrStr = "Recieved a missing system call signal! (SIGSYS)\n"; case Err_Sig_Pipe: mErrStr = "Recieved a broken pipe signal! (SIGPIPE)\n"; case Err_Sig_Alarm: mErrStr = "Recieved an alarm signal! (SIGALRM)\n"; case Err_Sig_Terminate: mErrStr = "Recieved a terminate signal! (SIGTERM)\n"; case Err_Sig_XCPU: mErrStr = "Recieved an excessive CPU signal! (SIGXCPU)\n"; case Err_Sig_FSizeLimit: mErrStr = "Recieved an excessive filesize signal! (SIGXFSZ)\n"; case Err_Sig_VirtAlarm: mErrStr = "Recieved a virtual alarm signal! (SIGVTALRM)\n"; case Err_Sig_ProfAlarm: mErrStr = "Recieved a profile alarm signal! (SIGPROF)\n"; case Err_Ptr_AllocFail: mErrStr = "Was unable to allocate space for a pointer in the system!\n"; case Err_Ptr_AccessVio: mErrStr = "Was unable to access an invalid address or dangling pointer!\n"; case Err_OS_FuncFail: mErrStr = "An internal function has failed!\n"; // Warnings. case Warn_LowMemory: mErrStr = "System is low on memory"; case Warn_LowFD: mErrStr = "System is low on file descriptors"; case Warn_LowThreads: mErrStr = "System is low on available threads"; case Warn_LowSpace: mErrStr = "System is low on HDD space"; case Warn_INetDown: mErrStr = "System doesn't have an network connection"; case Warn_INetLimit: mErrStr = "System seems to have a LAN connection, but no internet."; default: mErrStr.clear(); // This cleared AGAIN just to be sure it's empty. } if (0 >= mErrStr.size()) { // We need to query the OS for an error string! #if defined(Q_OS_WINDOWS) const size_t ciMaxBuffSz = 65535; // Allocate a temporary buffer. char* pTmpBuff = new char[ciMaxBuffSz]; memset(pTmpBuff, 0, ciMaxBuffSz); // Grab the message. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, iErr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), pTmpBuff, ciMaxBuffSz, NULL); mErrStr.append(pTmpBuff); if (nullptr != pTmpBuff) { delete[] pTmpBuff; } #elif defined(Q_OS_LINUX) #else #endif //#if defined(Q_OS_WINDOWS) } if (0 >= mErrStr.size()) { mErrStr = "An unknown error has occured!\n"; } return mErrStr; } std::string CRuntimeTracker::GetLastErrorString() { return mErrStr; }
34.232092
167
0.594291
squigglepuff
88e175c730ccc5858fc0adfa95f6921e7373124c
1,005
cpp
C++
Source/Utilities/percentage_bar.cpp
Hopson97/ASCIImonClassic
a20d0e7272c512434f767d128642a057b5b20ca5
[ "MIT" ]
1
2018-05-27T18:18:08.000Z
2018-05-27T18:18:08.000Z
Source/Utilities/percentage_bar.cpp
Hopson97/ASCIImonClassic
a20d0e7272c512434f767d128642a057b5b20ca5
[ "MIT" ]
null
null
null
Source/Utilities/percentage_bar.cpp
Hopson97/ASCIImonClassic
a20d0e7272c512434f767d128642a057b5b20ca5
[ "MIT" ]
null
null
null
#include "percentage_bar.h" #include <iostream> Percentage_Bar :: Percentage_Bar () : m_line ( BARS * 3, '-' ) { } void Percentage_Bar :: draw ( int curr, int max, Console::Foreground_Colour fullColour, Console::Foreground_Colour emptyColour ) { drawLine (); double full = (double)curr / ((double)max / (double)BARS); Console::setTextColour( fullColour ); drawFullBars ( full ); Console::setTextColour( emptyColour ); int remainder = BARS - full; drawEmptyBars(remainder); Console::resetColours(); } void Percentage_Bar :: drawFullBars ( int fullBars ) { for ( int i = 0 ; i < fullBars ; i++ ) { std::cout << "[O]"; } } void Percentage_Bar :: drawEmptyBars ( int emptyBars ) { for ( int i = 0 ; i < emptyBars ; i++ ) { std::cout << "[X]"; } Console::newLine(); drawLine (); } void Percentage_Bar :: drawLine () { Console::setTextColour ( Console::Foreground_Colour::WHITE ); std::cout << m_line << std::endl; }
22.333333
128
0.61592
Hopson97
88e1b0fc6478fec4b82d0773bd836b5a33f953f5
539
hpp
C++
kernel/frame_buffer.hpp
three-0-3/my-mikanos
e85f9e15d735babde1650c6fa87ffed210dece6d
[ "Apache-2.0" ]
null
null
null
kernel/frame_buffer.hpp
three-0-3/my-mikanos
e85f9e15d735babde1650c6fa87ffed210dece6d
[ "Apache-2.0" ]
null
null
null
kernel/frame_buffer.hpp
three-0-3/my-mikanos
e85f9e15d735babde1650c6fa87ffed210dece6d
[ "Apache-2.0" ]
null
null
null
#pragma once #include <memory> #include <vector> #include "error.hpp" #include "frame_buffer_config.hpp" #include "graphics.hpp" class FrameBuffer { public: // Initialize frame buffer by checking config Error Initialize(const FrameBufferConfig& config); FrameBufferWriter& Writer() { return *writer_; } private: FrameBufferConfig config_{}; std::vector<uint8_t> buffer_{}; // unique_ptr as this FrameBuffer owns FrameBufferWriter std::unique_ptr<FrameBufferWriter> writer_{}; }; int BitsPerPixel(PixelFormat format);
22.458333
58
0.755102
three-0-3
88e8a13a7f84538b0c31962a5996f038437f4554
3,112
cpp
C++
BroadCast_QT/group.cpp
mickelfeng/qt_learning
1f565754c36f0c09888cf4fbffa6271298d0678b
[ "Apache-2.0" ]
1
2016-01-05T07:24:32.000Z
2016-01-05T07:24:32.000Z
BroadCast_QT/group.cpp
mickelfeng/qt_learning
1f565754c36f0c09888cf4fbffa6271298d0678b
[ "Apache-2.0" ]
null
null
null
BroadCast_QT/group.cpp
mickelfeng/qt_learning
1f565754c36f0c09888cf4fbffa6271298d0678b
[ "Apache-2.0" ]
null
null
null
/* Copyright (C) 2014 by Project Tox <https://tox.im> This file is part of qTox, a Qt-based graphical interface for Tox. This program is libre software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the COPYING file for more details. */ #include "group.h" #include "widget/groupwidget.h" #include "widget/form/groupchatform.h" #include "friendlist.h" #include "friend.h" #include "widget/widget.h" #include "core.h" #include <QDebug> Group::Group(int GroupId, QString Name) : groupId(GroupId), nPeers{0}, hasPeerInfo{false} { widget = new GroupWidget(groupId, Name); chatForm = new GroupChatForm(this); connect(&peerInfoTimer, SIGNAL(timeout()), this, SLOT(queryPeerInfo())); peerInfoTimer.setInterval(500); peerInfoTimer.setSingleShot(false); //peerInfoTimer.start(); //in groupchats, we only notify on messages containing your name hasNewMessages = 0; userWasMentioned = 0; } Group::~Group() { delete chatForm; delete widget; } void Group::queryPeerInfo() { const Core* core = Widget::getInstance()->getCore(); int nPeersResult = core->getGroupNumberPeers(groupId); if (nPeersResult == -1) { qDebug() << "Group::queryPeerInfo: Can't get number of peers"; return; } nPeers = nPeersResult; widget->onUserListChanged(); chatForm->onUserListChanged(); if (nPeersResult == 0) return; bool namesOk = true; QList<QString> names = core->getGroupPeerNames(groupId); if (names.isEmpty()) { qDebug() << "Group::queryPeerInfo: Can't get names of peers"; return; } for (int i=0; i<names.size(); i++) { QString name = names[i]; if (name.isEmpty()) { name = "<Unknown>"; namesOk = false; } peers[i] = name; } nPeers = names.size(); widget->onUserListChanged(); chatForm->onUserListChanged(); if (namesOk) { qDebug() << "Group::queryPeerInfo: Successfully loaded names"; hasPeerInfo = true; peerInfoTimer.stop(); } } void Group::addPeer(int peerId, QString name) { if (peers.contains(peerId)) qWarning() << "Group::addPeer: peerId already used, overwriting anyway"; if (name.isEmpty()) peers[peerId] = "<Unknown>"; else peers[peerId] = name; nPeers++; widget->onUserListChanged(); chatForm->onUserListChanged(); } void Group::removePeer(int peerId) { peers.remove(peerId); nPeers--; widget->onUserListChanged(); chatForm->onUserListChanged(); } void Group::updatePeer(int peerId, QString name) { peers[peerId] = name; widget->onUserListChanged(); chatForm->onUserListChanged(); }
25.933333
80
0.646208
mickelfeng
88e8a43f641ef1acb02ea5a089baff74f4e0a78c
4,345
cpp
C++
tests/World.cpp
ronsaldo/abstract-physics
dbc23a57bfa369139c786071b2a6db4e84bb16fe
[ "MIT" ]
10
2016-12-11T04:54:18.000Z
2022-02-27T18:12:18.000Z
tests/World.cpp
ronsaldo/abstract-physics
dbc23a57bfa369139c786071b2a6db4e84bb16fe
[ "MIT" ]
null
null
null
tests/World.cpp
ronsaldo/abstract-physics
dbc23a57bfa369139c786071b2a6db4e84bb16fe
[ "MIT" ]
null
null
null
#include <APHY/aphy.hpp> #include <UnitTest++.h> SUITE(Engine) { class WorldFixture { public: WorldFixture() { aphy_size numEngines; aphyGetEngines(1, (aphy_engine**)&engine, &numEngines); CHECK(numEngines > 0); collisionConfiguration = engine->createDefaultCollisionConfiguration(); collisionDispatcher = engine->createDefaultCollisionDispatcher(collisionConfiguration.get()); broadphase = engine->createDefaultBroadphase(); constraintSolver = engine->createDefaultConstraintSolver(); world = engine->createDynamicsWorld(collisionDispatcher.get(), broadphase.get(), constraintSolver.get(), collisionConfiguration.get()); world->setGravity(0, -9.8, 0); } aphy_engine_ref engine; aphy_collision_configuration_ref collisionConfiguration; aphy_collision_dispatcher_ref collisionDispatcher; aphy_broadphase_ref broadphase; aphy_constraint_solver_ref constraintSolver; aphy_world_ref world; }; TEST_FIXTURE(WorldFixture, EmptyWorld) { CHECK_EQUAL(0u, world->getNumberOfCollisionObject()); CHECK_EQUAL(0u, world->getNumberOfConstraints()); } TEST_FIXTURE(WorldFixture, StepEmptyWorld) { CHECK_EQUAL(0u, world->getNumberOfCollisionObject()); CHECK_EQUAL(0u, world->getNumberOfConstraints()); world->stepSimulation(1.0, 10, 1.0/60.0); CHECK_EQUAL(0u, world->getNumberOfCollisionObject()); CHECK_EQUAL(0u, world->getNumberOfConstraints()); } TEST_FIXTURE(WorldFixture, FallingObject) { aphy_collision_shape_ref shape = engine->createBoxShape(0.5, 0.5, 0.5); aphy_motion_state_ref fallingObjectMotionState = engine->createDefaultMotionState(); aphy_collision_object_ref fallingObject = engine->createSimpleRigidBody(1.0, fallingObjectMotionState.get(), shape.get(), shape->computeLocalInertia(1.0)); world->addRigidBody(fallingObject.get()); CHECK_EQUAL(1u, world->getNumberOfCollisionObject()); CHECK_EQUAL(0u, world->getNumberOfConstraints()); auto initialPosition = fallingObjectMotionState->getTranslation(); auto delta = 1.0 / 60.0; for(int i = 0; i < 10; ++i) world->stepSimulation(delta, 2, 1.0/60.0); auto newPosition = fallingObjectMotionState->getTranslation(); CHECK(newPosition.y < initialPosition.y); } TEST_FIXTURE(WorldFixture, FallingObjectAndFloor) { // Floor aphy_collision_shape_ref floorShape = engine->createBoxShape(10.0, 0.2, 10.0); aphy_motion_state_ref floorMotionState = engine->createDefaultMotionState(); aphy_collision_object_ref floorObject = engine->createSimpleRigidBody(0.0, floorMotionState.get(), floorShape.get(), {0}); world->addRigidBody(floorObject.get()); CHECK_EQUAL(1u, world->getNumberOfCollisionObject()); CHECK_EQUAL(0u, world->getNumberOfConstraints()); // Falling object aphy_collision_shape_ref shape = engine->createBoxShape(0.5, 0.5, 0.5); aphy_motion_state_ref fallingObjectMotionState = engine->createDefaultMotionState(); fallingObjectMotionState->setTranslation({0,2,0}); aphy_collision_object_ref fallingObject = engine->createSimpleRigidBody(1.0, fallingObjectMotionState.get(), shape.get(), shape->computeLocalInertia(1.0)); world->addRigidBody(fallingObject.get()); CHECK_EQUAL(2u, world->getNumberOfCollisionObject()); CHECK_EQUAL(0u, world->getNumberOfConstraints()); auto initialPosition = fallingObjectMotionState->getTranslation(); auto initialFloorPosition = floorMotionState->getTranslation(); auto delta = 1.0 / 60.0; for(int i = 0; i < 30; ++i) world->stepSimulation(delta, 2, 1.0/60.0); auto newPosition = fallingObjectMotionState->getTranslation(); auto newFloorPosition = floorMotionState->getTranslation(); CHECK_EQUAL(initialFloorPosition.x, newFloorPosition.x); CHECK_EQUAL(initialFloorPosition.y, newFloorPosition.y); CHECK_EQUAL(initialFloorPosition.z, newFloorPosition.z); CHECK(newPosition.y < initialPosition.y); CHECK(newPosition.y > 0); } }
43.45
163
0.686997
ronsaldo
88ec5b1cda61f6c27f6a7f1ebe819eb280adc05a
636
cpp
C++
WinObj/DialogMessageLoop.cpp
ngeor/vc6
49d68aad83fec91639dbe556f44333a3a72dae6f
[ "MIT" ]
null
null
null
WinObj/DialogMessageLoop.cpp
ngeor/vc6
49d68aad83fec91639dbe556f44333a3a72dae6f
[ "MIT" ]
2
2021-10-03T10:37:59.000Z
2022-03-18T06:06:30.000Z
WinObj/DialogMessageLoop.cpp
ngeor/vc6
49d68aad83fec91639dbe556f44333a3a72dae6f
[ "MIT" ]
null
null
null
// DialogMessageLoop.cpp: implementation of the CDialogMessageLoop class. // ////////////////////////////////////////////////////////////////////// #include "StdAfx.h" #include "DialogMessageLoop.h" namespace WinObj { ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CDialogMessageLoop::CDialogMessageLoop(CDialog& dialog) : _dialog(dialog) { } CDialogMessageLoop::~CDialogMessageLoop() { } bool CDialogMessageLoop::IsMessageProcessed(LPMSG msg) { return _dialog.IsDialogMessage(msg); } } // namespace WinObj
23.555556
73
0.52044
ngeor
88ee8bc44a0180d2b8890165543ced054bbbad66
1,102
cc
C++
callback.cc
stories2/Native-Node-JS
583a2db17b0f398779378294ea21a7034ee2c815
[ "MIT" ]
null
null
null
callback.cc
stories2/Native-Node-JS
583a2db17b0f398779378294ea21a7034ee2c815
[ "MIT" ]
null
null
null
callback.cc
stories2/Native-Node-JS
583a2db17b0f398779378294ea21a7034ee2c815
[ "MIT" ]
null
null
null
#include <node.h> #include <nan.h> namespace function_arg { // using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Object; using v8::String; using v8::Value; using v8::Context; using v8::Number; using v8::Function; void CallbackFunc(const Nan::FunctionCallbackInfo<Value> &args) { Isolate *isolate = args.GetIsolate(); Local<Context> context = args.GetIsolate()->GetCurrentContext(); if(args.Length() < 1) { Nan::ThrowTypeError("Wrong number of arguments"); return; } Local<Function> cb = args[0].As<Function>(); const unsigned argc = 1; Local<Value> argv[argc] = { Nan::New("Hello World from c++").ToLocalChecked() }; Nan::MakeCallback(context->Global(), cb, argc, argv); } void init(Local<Object> exports, Local<Object> module) { // NODE_SET_METHOD(exports, "add", Add); Nan::SetMethod(module, "exports", CallbackFunc); } NODE_MODULE(NODE_GYP_MODULE_NAME, init) } // namespace demo
27.55
72
0.599819
stories2
88efae45ad5296fd391e686bde3f9b4bb9c75edf
310
cpp
C++
LeetCode/Problems/Algorithms/#1480_RunningSumOf1DArray_sol2.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#1480_RunningSumOf1DArray_sol2.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#1480_RunningSumOf1DArray_sol2.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { public: vector<int> runningSum(vector<int>& nums) { const int N = nums.size(); vector<int> prefSum(N); prefSum[0] = nums[0]; for(int i = 1; i < N; ++i){ prefSum[i] = prefSum[i - 1] + nums[i]; } return prefSum; } };
25.833333
51
0.464516
Tudor67
88f14366e84d6acc899e26bb0cd07e2ba07944c5
1,729
cpp
C++
C - C++/Painter's partition problem/Painters_Partition_Problem.cpp
ieternalleo/AlgoCode
77287392ce08fba082307adb588a1495cb42b84e
[ "MIT" ]
151
2020-10-01T07:38:26.000Z
2022-03-31T10:07:55.000Z
C - C++/Painter's partition problem/Painters_Partition_Problem.cpp
ieternalleo/AlgoCode
77287392ce08fba082307adb588a1495cb42b84e
[ "MIT" ]
285
2020-10-01T09:34:29.000Z
2021-08-02T12:13:49.000Z
C - C++/Painter's partition problem/Painters_Partition_Problem.cpp
ieternalleo/AlgoCode
77287392ce08fba082307adb588a1495cb42b84e
[ "MIT" ]
275
2020-10-01T09:43:51.000Z
2022-03-30T19:30:53.000Z
// This arena belongs to WhiteDeath99 #include<bits/stdc++.h> #define endl "\n" #define IOS ios_base::sync_with_stdio(0);cin.tie(nullptr);cout.tie(nullptr) #define rep(i,a,b) for(int i=a;i<b;i++) using namespace std; bool isPossible(long long int mid, vector<int> C, int paint) { int maxi = 0; for(int i = 0; i < C.size(); i++) { if(C[i] > maxi) { maxi = C[i]; } } if(maxi > mid) { return false; } long long int sum = 0; int count = 1; for(int i = 0; i < C.size();) { if((sum + (long long int)C[i]) > mid) { count++; sum = 0; } else { sum = sum + (long long int)C[i]; i++; } } if(count <= paint) { return true; } return false; } int main() { IOS; clock_t startTime=clock(); int A,B,N; vector<int> C; cin>>A>>B>>N; rep(i,0,N) { int ele; cin>>ele; C.push_back(ele); } long long int start = 0, end = 0; for(int i = 0; i < C.size(); i++) { end = end + C[i]; } long long int sol = INT_MAX; while(start <= end) { long long int mid = start + (end - start)/2; if(isPossible(mid, C, A)) { sol = min(sol, mid); end = mid - 1; } else { start = mid + 1; } } cout<<(int)((sol * (long long) B) % 10000003); cerr << endl <<setprecision(20)<< double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< " seconds." << endl; }//See'ya soon.
18.2
113
0.423944
ieternalleo
88f245d407e5f703cb66c9e7e6d8a2bfee10af68
594
hpp
C++
mpipe/modules/mod_equalizer.hpp
m-kus/mpipe
82e2e93200030b89d76544cee13aabedf318ea0c
[ "MIT" ]
2
2019-02-09T14:31:03.000Z
2019-05-03T05:46:15.000Z
mpipe/modules/mod_equalizer.hpp
m-kus/mpipe
82e2e93200030b89d76544cee13aabedf318ea0c
[ "MIT" ]
null
null
null
mpipe/modules/mod_equalizer.hpp
m-kus/mpipe
82e2e93200030b89d76544cee13aabedf318ea0c
[ "MIT" ]
null
null
null
#pragma once #include <core/mpipe.hpp> #include <algorithm> namespace mpipe { class ModEqualizer : public Module { public: void Mutate(State* state) override { int64_t target_qty = 0; for (auto& order : state->orders) { int64_t common_qty = order.qty / npabs(order.security->leg_factor); if (common_qty < target_qty || target_qty == 0) target_qty = common_qty; } if (target_qty > 0) { for (auto& order : state->orders) order.qty = target_qty * npabs(order.security->leg_factor); } else { state->orders.clear(); } } }; }
16.971429
71
0.624579
m-kus
88f3985112753da6c78e9ce5e64f22ce92f111f4
272
cpp
C++
RustConsumerInteropSolution/Component2/Class.cpp
raffaeler/RustConsumerInterop
ec3c803ca005cd26608230fe04ce0b4e36836cd0
[ "MIT" ]
null
null
null
RustConsumerInteropSolution/Component2/Class.cpp
raffaeler/RustConsumerInterop
ec3c803ca005cd26608230fe04ce0b4e36836cd0
[ "MIT" ]
null
null
null
RustConsumerInteropSolution/Component2/Class.cpp
raffaeler/RustConsumerInterop
ec3c803ca005cd26608230fe04ce0b4e36836cd0
[ "MIT" ]
null
null
null
#include "pch.h" #include "Class.h" #include "Class2.g.cpp" namespace winrt::Component2::implementation { int32_t Class2::MyProperty2() { return _myProperty2; } void Class2::MyProperty2(int32_t value) { _myProperty2 = value; } }
16
43
0.628676
raffaeler
88f7df8b08b019b9ba10bdf20a3bdf89d2dea2b7
357
hpp
C++
plugins/samefolder/version.hpp
TheChatty/FarManager
0a731ce0b6f9f48f10eb370240309bed48e38f11
[ "BSD-3-Clause" ]
1
2019-11-15T10:13:04.000Z
2019-11-15T10:13:04.000Z
plugins/samefolder/version.hpp
TheChatty/FarManager
0a731ce0b6f9f48f10eb370240309bed48e38f11
[ "BSD-3-Clause" ]
1
2021-01-21T13:57:07.000Z
2021-01-21T13:57:07.000Z
plugins/samefolder/version.hpp
TheChatty/FarManager
0a731ce0b6f9f48f10eb370240309bed48e38f11
[ "BSD-3-Clause" ]
null
null
null
#include "farversion.hpp" #define PLUGIN_BUILD 1 #define PLUGIN_DESC L"Same Folder Plugin for Far Manager" #define PLUGIN_NAME L"SameFolder" #define PLUGIN_FILENAME L"SameFolder.dll" #define PLUGIN_AUTHOR L"Far Group" #define PLUGIN_VERSION MAKEFARVERSION(FARMANAGERVERSION_MAJOR,FARMANAGERVERSION_MINOR,FARMANAGERVERSION_REVISION,PLUGIN_BUILD,VS_RELEASE)
39.666667
137
0.854342
TheChatty
0000307fa69e8ef7c044abee8558d48957d9292a
566
cpp
C++
POO/aulas/aula01/h03.cpp
DaniloJNS/ufs-git
5ec06c4b98ab17943280e992b53c793deb474301
[ "MIT" ]
null
null
null
POO/aulas/aula01/h03.cpp
DaniloJNS/ufs-git
5ec06c4b98ab17943280e992b53c793deb474301
[ "MIT" ]
null
null
null
POO/aulas/aula01/h03.cpp
DaniloJNS/ufs-git
5ec06c4b98ab17943280e992b53c793deb474301
[ "MIT" ]
null
null
null
#include <stdio.h> float es; int en; float ej; int corrente; float p; void novoEmprestimo(float s, int n, float j) { es = s; en = n; ej = j; corrente = 1; p = s; } float proximaParcela() { float retorno = p; corrente++; if (corrente <= en) p = p + (p * (ej / 100)); else p = 0; // não há mais parcelas return retorno; } int main() { novoEmprestimo(200, 5, 1); int i = 1; float p = proximaParcela(); while (p > 0) { printf("O valor da parcela %d eh %3.2f \n", i, p); i++; p = proximaParcela(); } return 0; }
13.804878
54
0.547703
DaniloJNS
0000dfdb0fea5abd19ee2dc1cfe3801c3a6cc439
5,240
cpp
C++
src/xray/editor/world/sources/particle_graph_node_collection.cpp
ixray-team/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
3
2021-10-30T09:36:14.000Z
2022-03-26T17:00:06.000Z
src/xray/editor/world/sources/particle_graph_node_collection.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
null
null
null
src/xray/editor/world/sources/particle_graph_node_collection.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:08.000Z
2022-03-26T17:00:08.000Z
//////////////////////////////////////////////////////////////////////////// // Created : 27.01.2010 // Author : // Copyright (C) GSC Game World - 2010 //////////////////////////////////////////////////////////////////////////// #include "pch.h" #include "particle_graph_node.h" #include "particle_graph_node_event.h" #include "particle_graph_node_action.h" #include "particle_graph_node_property.h" #include "particle_graph_node_collection.h" #include "particle_hypergraph.h" #include "particle_graph_document.h" #include "particle_links_manager.h" using namespace System; namespace xray { namespace editor { particle_graph_node_collection::particle_graph_node_collection(particle_graph_node^ owner) { m_owner = owner; m_last_property_id = 0; m_last_action_id = 0; m_last_event_id = 0; } void particle_graph_node_collection::Insert (Int32 index , particle_graph_node^ node) { R_ASSERT(m_owner->parent_hypergraph!=nullptr); node->size = m_owner->size; if(node->parent_hypergraph == nullptr){ m_owner->parent_hypergraph->links_manager->on_node_destroyed(node); safe_cast<particle_hypergraph^>(m_owner->parent_hypergraph)->append_node(node); } if (Count == 0) safe_cast<particle_links_manager^>(m_owner->parent_hypergraph->links_manager)->create_link(m_owner, node); else if (index == 0){ safe_cast<particle_links_manager^>(m_owner->parent_hypergraph->links_manager)->destroy_link(m_owner, this[0]); safe_cast<particle_links_manager^>(m_owner->parent_hypergraph->links_manager)->create_link(m_owner, node); } node->parent_node = m_owner; super::Insert(index, node); if (node->GetType() == particle_graph_node_property::typeid){ m_last_property_id = m_last_property_id + 1; } else if (node->GetType() == particle_graph_node_action::typeid){ m_last_action_id = m_last_action_id + 1; } else if (node->GetType() == particle_graph_node_event::typeid){ m_last_event_id = m_last_event_id + 1; } if (m_owner->active_node == nullptr) m_owner->active_node = node; if (m_owner == safe_cast<particle_hypergraph^>(m_owner->parent_hypergraph)->root_node) node->process_node_selection(); else{ m_owner->process_node_selection(); node->process_node_selection(); } m_owner->recalc_children_position_offsets(); m_owner->parent_hypergraph->Invalidate(true); } void particle_graph_node_collection::Add (particle_graph_node^ node) { if (node->GetType() == particle_graph_node_property::typeid){ Insert(m_last_property_id, node); } else if (node->GetType() == particle_graph_node_action::typeid){ Insert(m_last_action_id + m_last_property_id, node); } else if (node->GetType() == particle_graph_node_event::typeid){ Insert(m_last_event_id + m_last_action_id + m_last_property_id, node); } else Insert(Count, node); } void particle_graph_node_collection::Remove (particle_graph_node^ node){ if (node->properties->type == "property"){ m_last_property_id = m_last_property_id - 1; } else if (node->properties->type == "action"){ m_last_action_id = m_last_action_id - 1; } else if (node->properties->type == "event"){ m_last_event_id = m_last_event_id - 1; } node->parent_node = nullptr; if (m_owner->active_node == node) m_owner->active_node = nullptr; safe_cast<particle_links_manager^>(m_owner->parent_hypergraph->links_manager)->destroy_link(m_owner, node); m_owner->parent_hypergraph->Invalidate(true); int node_index = this->IndexOf(node); super::Remove(node); if (node_index == 0 && Count>0) safe_cast<particle_links_manager^>(m_owner->parent_hypergraph->links_manager)->create_link(m_owner, this[0]); m_owner->recalc_children_position_offsets(); m_owner->parent_hypergraph->Invalidate(false); } bool particle_graph_node_collection::MoveToIndex (particle_graph_node^ node, int index){ int min_index = 0; int max_index = Count; if(node->is_property_node()){ min_index = 0; max_index = m_last_property_id; } else if(node->is_action_node()){ min_index = m_last_property_id; max_index = m_last_property_id + m_last_action_id; } else if(node->is_event_node()){ min_index = m_last_property_id + m_last_action_id; max_index = m_last_property_id + m_last_action_id + m_last_event_id; } if (index >= max_index || index < min_index) return false; int node_index = this->IndexOf(node); super::Remove(node); if (node_index == 0){ safe_cast<particle_links_manager^>(m_owner->parent_hypergraph->links_manager)->destroy_link(m_owner, node); safe_cast<particle_links_manager^>(m_owner->parent_hypergraph->links_manager)->create_link(m_owner, this[0]); } else if (index == 0){ safe_cast<particle_links_manager^>(m_owner->parent_hypergraph->links_manager)->create_link(m_owner, node); safe_cast<particle_links_manager^>(m_owner->parent_hypergraph->links_manager)->destroy_link(m_owner, this[0]); } super::Insert(index, node); m_owner->recalc_children_position_offsets(); m_owner->parent_hypergraph->Invalidate(true); return true; } }// namespace editor }// namespace xray
31.005917
114
0.702863
ixray-team
000100773f5fee406d55f139d0c336e75509e1cc
2,362
cpp
C++
devmand/gateway/src/devmand/devices/Factory.cpp
gurrapualt/magma
13e05788fa6c40293a58b6e03cfb394bb79fa98f
[ "BSD-3-Clause" ]
2
2020-12-09T11:42:30.000Z
2021-09-26T03:28:33.000Z
devmand/gateway/src/devmand/devices/Factory.cpp
gurrapualt/magma
13e05788fa6c40293a58b6e03cfb394bb79fa98f
[ "BSD-3-Clause" ]
124
2020-08-21T06:11:21.000Z
2022-03-21T05:25:26.000Z
devmand/gateway/src/devmand/devices/Factory.cpp
yogi8091/magma
edc3b249068ad871047e898c912f3228ee9f2c88
[ "BSD-3-Clause" ]
1
2020-09-21T04:25:06.000Z
2020-09-21T04:25:06.000Z
/* Copyright 2020 The Magma Authors. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. 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 <boost/algorithm/string.hpp> #include <devmand/devices/Factory.h> #include <devmand/error/ErrorHandler.h> #include <devmand/utils/StringUtils.h> namespace devmand { namespace devices { Factory::Factory(Application& application) : app(application) {} void Factory::addPlatform( const std::string& platform, PlatformBuilder platformBuilder) { std::string platformLowerCase = platform; boost::algorithm::to_lower(platformLowerCase); if (not platformBuilders.emplace(platformLowerCase, platformBuilder).second) { LOG(ERROR) << "Failed to add platform " << platform; throw std::runtime_error("Failed to add device platform"); } } void Factory::setDefaultPlatform(PlatformBuilder defaultPlatformBuilder_) { defaultPlatformBuilder = defaultPlatformBuilder_; } std::shared_ptr<devices::Device> Factory::createDevice( const cartography::DeviceConfig& deviceConfig) { LOG(INFO) << "Loading device " << deviceConfig.id << " on platform " << deviceConfig.platform << " with ip " << deviceConfig.ip; std::string platformLowerCase = deviceConfig.platform; boost::algorithm::to_lower(platformLowerCase); PlatformBuilder builder{nullptr}; auto builderIt = platformBuilders.find(platformLowerCase); if (builderIt == platformBuilders.end()) { LOG(INFO) << "Didn't find matching platform so using default."; builder = defaultPlatformBuilder; } else { builder = builderIt->second; } std::shared_ptr<devices::Device> device{nullptr}; if (builder != nullptr) { ErrorHandler::executeWithCatch([this, &builder, &deviceConfig, &device]() { device = builder(app, deviceConfig); }); } if (device != nullptr) { return device; } else { LOG(ERROR) << "Error adding device " << deviceConfig; throw std::runtime_error("Error adding device"); } } } // namespace devices } // namespace devmand
32.356164
80
0.734124
gurrapualt
0002cc1256b81fdab140ea63ebd2246830591eb1
637
cpp
C++
src/HiContrastThemeAsCeeCode.cpp
CHRYSICS/audacity
ce1b172825cb8dcc4b7cb2bb52a4f62946f0b141
[ "CC-BY-3.0" ]
1
2021-11-01T10:32:52.000Z
2021-11-01T10:32:52.000Z
src/HiContrastThemeAsCeeCode.cpp
CHRYSICS/audacity
ce1b172825cb8dcc4b7cb2bb52a4f62946f0b141
[ "CC-BY-3.0" ]
null
null
null
src/HiContrastThemeAsCeeCode.cpp
CHRYSICS/audacity
ce1b172825cb8dcc4b7cb2bb52a4f62946f0b141
[ "CC-BY-3.0" ]
null
null
null
/*!******************************************************************** Audacity: A Digital Audio Editor @file HiContrastThemeAsCeeCode.cpp Paul Licameli split from Theme.cpp **********************************************************************/ #include <vector> #include "Theme.h" static const std::vector<unsigned char> ImageCacheAsData { // Include the generated file full of numbers #include "HiContrastThemeAsCeeCode.h" }; static ThemeBase::RegisteredTheme theme{ /* i18n-hint: greater difference between foreground and background colors */ { "high-contrast", XO("High Contrast") }, ImageCacheAsData };
26.541667
72
0.576138
CHRYSICS
322fd6e8955bb801f5a5c6578c0b83bf195344b7
16,027
cpp
C++
Shoot/src/PropertyStream.cpp
franticsoftware/starports
d723404b20383949874868c251c60cfa06120fde
[ "MIT" ]
5
2016-11-13T08:13:57.000Z
2019-03-31T10:22:38.000Z
Shoot/src/PropertyStream.cpp
franticsoftware/starports
d723404b20383949874868c251c60cfa06120fde
[ "MIT" ]
null
null
null
Shoot/src/PropertyStream.cpp
franticsoftware/starports
d723404b20383949874868c251c60cfa06120fde
[ "MIT" ]
1
2016-12-23T11:25:35.000Z
2016-12-23T11:25:35.000Z
/* Amine Rehioui Created: February 24th 2010 */ #include "Shoot.h" #include "PropertyStream.h" #include "MaterialProvider.h" #include "rapidxml.hpp" namespace shoot { //! Destructor PropertyStream::~PropertyStream() { Clear(); } //! reads/write from a property from this stream void PropertyStream::Serialize(int eType, const std::string& strName, void* pValue, const void *pParams /*= NULL*/) { SHOOT_ASSERT(eType != PT_Array, "Use SerializeArray for serializing arrays"); SHOOT_ASSERT(eType != PT_Reference, "Use SerializeReference for serializing references"); switch(m_eMode) { case SM_Read: // check if this property was marked for update if(m_strPropertyToUpdate.length() == 0 || m_strPropertyToUpdate == strName) { IProperty* pProperty = GetProperty(strName); if(pProperty) { SHOOT_ASSERT(pProperty->GetType() == eType, "PropertyType mismatch"); if(pProperty->GetType() == PT_Struct) { StructProperty* pStructProperty = static_cast<StructProperty*>(pProperty); ISerializableStruct* pStruct = static_cast<ISerializableStruct*>(pValue); pStructProperty->GetStream().SetMode(SM_Read); pStructProperty->GetStream().SetTargetObject(m_pTargetObject); pStruct->Serialize(pStructProperty->GetStream()); } else if(pProperty->GetType() == PT_Link) { if(m_pIDMap_OriginalToCopy) { Link<Object> link; pProperty->GetData(&link); if (m_pIDMap_OriginalToCopy->find(link.GetObjectID()) != m_pIDMap_OriginalToCopy->end()) static_cast<ILink*>(pValue)->SetObjectID((*m_pIDMap_OriginalToCopy)[link.GetObjectID()]); else static_cast<ILink*>(pValue)->SetObjectID(link.GetObjectID()); } else pProperty->GetData(pValue); } else { pProperty->GetData(pValue); } } } break; case SM_Write: { IProperty* pProperty = IProperty::CreateFromType(E_PropertyType(eType)); pProperty->SetName(strName); pProperty->SetParams(pParams); if(pProperty->GetType() == PT_Struct) { StructProperty* pStructProperty = static_cast<StructProperty*>(pProperty); ISerializableStruct* pStruct = static_cast<ISerializableStruct*>(pValue); pStructProperty->GetStream().SetMode(SM_Write); pStructProperty->GetStream().SetUsedForObjectCopy(m_bUsedForObjectCopy); pStruct->Serialize(pStructProperty->GetStream()); } else { pProperty->SetData(pValue); } m_aProperties.push_back(pProperty); } break; default: SHOOT_ASSERT(false, "Invalid E_SerializationMode"); } if(eType == PT_Enum) { EnumParams* _pParams = static_cast<EnumParams*>(const_cast<void*>(pParams)); sdelete(_pParams); } } //! returns the property with the specified name IProperty* PropertyStream::GetProperty(const std::string& strName) const { for (size_t i=0; i<m_aProperties.size(); ++i) { IProperty* pProperty = m_aProperties[i]; if(pProperty->GetName() == strName) return pProperty; } return 0; } //! adds a property to the stream void PropertyStream::AddProperty(IProperty* pProperty) { std::vector<IProperty*>::iterator it = std::find(m_aProperties.begin(), m_aProperties.end(), pProperty); SHOOT_ASSERT(it == m_aProperties.end(), "Trying to add a property twice"); m_aProperties.push_back(pProperty); } //! removes a propety from the stream void PropertyStream::RemoveProperty(IProperty* pProperty) { std::vector<IProperty*>::iterator it = std::find(m_aProperties.begin(), m_aProperties.end(), pProperty); SHOOT_ASSERT(it != m_aProperties.end(), "Trying to remove unexisting property"); m_aProperties.erase(it); sdelete(pProperty); } //! fills this stream from xml element void PropertyStream::ReadFromXML(rapidxml::xml_node<char>* pXMLElement, ArrayProperty* pParentArrayProperty /*= NULL*/) { auto pChild = pXMLElement->first_node(); while(pChild) { // get the property type name std::string strPropertyTypeName = pChild->name(); IProperty* pProperty = IProperty::CreateFromTypeName(strPropertyTypeName); // get the property name const char* strPropertyName = pChild->getAttribute("Name"); if(strPropertyName) { pProperty->SetName(std::string(strPropertyName)); } switch(pProperty->GetType()) { case PT_Array: ReadFromXML(pChild, static_cast<ArrayProperty*>(pProperty)); break; case PT_Reference: { ReferenceProperty* pRefProperty = static_cast<ReferenceProperty*>(pProperty); if (const char* strTemplatePath = pChild->getAttribute("TemplatePath")) { pRefProperty->SetTemplatePath(strTemplatePath); } else if (const char* strClassName = pChild->getAttribute("ClassName")) { pRefProperty->SetClassName(strClassName); pRefProperty->GetStream().ReadFromXML(pChild); } } break; case PT_Struct: { StructProperty* pStructProperty = static_cast<StructProperty*>(pProperty); pStructProperty->GetStream().ReadFromXML(pChild); } break; default: { // get the property value const char* pStrPropertyValue = pChild->getAttribute("Value"); SHOOT_ASSERT(pStrPropertyValue, "property missing Value attribute"); pProperty->SetData(std::string(pStrPropertyValue)); } } // add the property to the stream if(pParentArrayProperty) { if(pParentArrayProperty->GetSubType() == PT_Undefined) { pParentArrayProperty->SetSubType(pProperty->GetType()); } else { SHOOT_ASSERT(pParentArrayProperty->GetSubType() == pProperty->GetType(), "Can't have multiple types in an array property"); } pParentArrayProperty->GetProperties().push_back(pProperty); } else { m_aProperties.push_back(pProperty); } pChild = pChild->next_sibling(); } } // writes this stream to xml element void PropertyStream::WriteToXML(rapidxml::xml_node<char>* pXMLElement) { for (size_t i=0; i<m_aProperties.size(); ++i) { WritePropertyToXML(pXMLElement, m_aProperties[i]); } } //! reads/writes an array property from/to this stream void PropertyStream::SerializeArray(const std::string& strName, IArray* pArray, int eSubType) { SHOOT_ASSERT(eSubType != PT_Array, "Arrays of arrays not supported. Encapsulate your inner array into a struct to get around this."); switch(m_eMode) { case SM_Read: // check if this property was marked for update if(m_strPropertyToUpdate.length() == 0 || m_strPropertyToUpdate == strName) { ArrayProperty* pProperty = static_cast<ArrayProperty*>(GetProperty(strName)); if(pProperty) { // update existing elements for (size_t i = 0; i<pArray->GetSize() && i<pProperty->GetProperties().size(); ++i) { IProperty* pSubProperty = pProperty->GetProperties()[i]; SHOOT_ASSERT(pSubProperty->GetType() == eSubType, "Actual sub property type differs from expected type"); void* pElement = pArray->GetPtr(i); FillArrayElement(pElement, pSubProperty); } // attempt to add new elements for (size_t i = pArray->GetSize(); i<pProperty->GetProperties().size(); ++i) { IProperty* pSubProperty = pProperty->GetProperties()[i]; SHOOT_ASSERT(pSubProperty->GetType() == eSubType, "Actual sub property type differs from expected type"); void* pElement = pArray->Alloc(); FillArrayElement(pElement, pSubProperty); pArray->Add(pElement); } // attempt to remove elements for (size_t i = pProperty->GetProperties().size(); i<pArray->GetSize(); ++i) { pArray->Delete(i); --i; } } } break; case SM_Write: { ArrayProperty* pProperty = static_cast<ArrayProperty*>(IProperty::CreateFromType(PT_Array)); pProperty->SetName(strName); pProperty->SetSubType(E_PropertyType(eSubType)); pProperty->SetArray(pArray); for (size_t i = 0; i<pArray->GetSize(); ++i) { IProperty* pSubProperty = IProperty::CreateFromType(E_PropertyType(eSubType)); void* pElement = pArray->GetPtr(i); if(eSubType == PT_Struct) { StructProperty* pStructProperty = static_cast<StructProperty*>(pSubProperty); ISerializableStruct* pStruct = static_cast<ISerializableStruct*>(pElement); pStructProperty->GetStream().SetMode(SM_Write); pStruct->Serialize(pStructProperty->GetStream()); } else if(eSubType == PT_Reference) { IReference* pReference = static_cast<IReference*>(pElement); ReferenceProperty* pRefProperty = static_cast<ReferenceProperty*>(pSubProperty); FillPropertyFromReference(pRefProperty, pReference); } else { pSubProperty->SetData(pElement); } pProperty->GetProperties().push_back(pSubProperty); } m_aProperties.push_back(pProperty); } break; } } //! reads/writes a reference property from/to this stream void PropertyStream::SerializeReference(const std::string& strName, IReference* pReference) { switch(m_eMode) { case SM_Read: // check if this property was marked for update if(m_strPropertyToUpdate.length() == 0 || m_strPropertyToUpdate == strName) { IProperty* pProperty = GetProperty(strName); if(pProperty && pProperty->GetType() == PT_Reference) { FillReferenceFromProperty(pReference, static_cast<ReferenceProperty*>(pProperty)); } } break; case SM_Write: { ReferenceProperty* pProperty = static_cast<ReferenceProperty*>(IProperty::CreateFromType(PT_Reference)); pProperty->SetName(strName); FillPropertyFromReference(pProperty, pReference); m_aProperties.push_back(pProperty); } break; } } //! explicitly clear this stream void PropertyStream::Clear() { for (size_t i=0; i<m_aProperties.size(); ++i) { IProperty* pProperty = m_aProperties[i]; delete pProperty; } m_aProperties.clear(); } //! writes a property to XML void PropertyStream::WritePropertyToXML(rapidxml::xml_node<char>* pXMLElement, IProperty* pProperty, bool bWriteName /*= true*/) { auto pElement = pXMLElement->document()->allocate_node(rapidxml::node_element, pXMLElement->document()->allocate_string(pProperty->GetClassName().c_str())); pXMLElement->append_node(pElement); if(bWriteName) pElement->setAttribute("Name", pProperty->GetName().c_str()); switch(pProperty->GetType()) { case PT_Array: { ArrayProperty* pArrayProperty = static_cast<ArrayProperty*>(pProperty); for(size_t i=0; i<pArrayProperty->GetProperties().size(); ++i) { IProperty* pSubProperty = pArrayProperty->GetProperties()[i]; WritePropertyToXML(pElement, pSubProperty, false); // don't write the name for array sub properties } } break; case PT_Reference: { ReferenceProperty* pRefProperty = static_cast<ReferenceProperty*>(pProperty); if(pRefProperty->GetTemplatePath().empty()) { pElement->setAttribute("ClassName", pRefProperty->GetClassName().c_str()); pRefProperty->GetStream().WriteToXML(pElement); } else { pElement->setAttribute("TemplatePath", pRefProperty->GetTemplatePath().c_str()); } } break; case PT_Struct: { StructProperty* pStructProperty = static_cast<StructProperty*>(pProperty); pStructProperty->GetStream().WriteToXML(pElement); } break; default: { pElement->setAttribute("Value", pProperty->GetString().c_str()); } } } //! fills a user reference from a ReferenceProperty void PropertyStream::FillReferenceFromProperty(IReference* pReference, ReferenceProperty* pProperty) { bool bFromTemplate = !pProperty->GetTemplatePath().empty(); bool bObjectSerialized = false; if (pProperty->GetStream().GetNumProperties() == 0 && !bFromTemplate) return; Object* pObject = pProperty->GetRefInterface() ? pProperty->GetRefInterface()->Get() : NULL; if (!pObject || m_bUsedForObjectCopy) { if (bFromTemplate) { if (!pObject) { auto templatePath = pProperty->GetTemplatePath(); pObject = ObjectManager::Instance()->Find(templatePath); if (!pObject) { pObject = ObjectManager::Instance()->Load(templatePath); if (auto resource = DYNAMIC_CAST(pObject, Resource)) resource->ResourceInit(); } } } else { // hack because materials must only be created through MaterialProvider // TODO find a better way if (pReference->GetTypeID() == Material::TypeID) { if (m_bUsedForObjectCopy) { if (auto material = DYNAMIC_CAST(pObject, Material)) material->SetColor(material->GetCreationInfo().m_Color); } else { Material::CreationInfo materialInfo; pProperty->GetStream().SetMode(SM_Read); pProperty->GetStream().Serialize("CreationInfo", &materialInfo); pObject = MaterialProvider::Instance()->FindMaterial(materialInfo); if (!pObject) { pObject = MaterialProvider::Instance()->CreateMaterial(materialInfo); uint ID = pObject->GetID(); pProperty->GetStream().Serialize("ID", &ID); pObject->SetID(ID); } } bObjectSerialized = true; } else { pObject = ObjectFactory::Instance()->Create(pProperty->GetClassName()); } } } #ifdef SHOOT_EDITOR pReference->SetOwner(m_pTargetObject); if (!ObjectFactory::Instance()->IsDerived(pObject->GetClassName(), pReference->GetClassName())) { SHOOT_WARNING(false, "Invalid Reference, expecting '%s', found '%s'", pReference->GetClassName(), pObject->GetClassName()); return; } #endif pReference->SetObject(pObject); if (pProperty->GetStream().GetNumProperties() && !bObjectSerialized) { pProperty->GetStream().SetMode(SM_Read); pProperty->GetStream().SetIDMap_OriginalToCopy(m_pIDMap_OriginalToCopy); pProperty->GetStream().SetUsedForObjectCopy(m_bUsedForObjectCopy); int ID = pObject->GetID(); pObject->Serialize(pProperty->GetStream()); // If copied, use the ID from the new instance if (m_bUsedForObjectCopy) pObject->SetID(ID); } } //! fills a ReferenceProperty from a user reference void PropertyStream::FillPropertyFromReference(ReferenceProperty* pProperty, IReference* pReference) { pProperty->SetRefInterface(pReference); Object* pObject = pReference->Get(); if(pObject) { std::string strTemplatePath = pObject->GetTemplatePath(); if(!strTemplatePath.empty()) pProperty->SetTemplatePath(strTemplatePath); else pProperty->SetClassName(pObject->GetClassName()); pProperty->GetStream().SetMode(SM_Write); pProperty->GetStream().SetUsedForObjectCopy(m_bUsedForObjectCopy); pObject->Serialize(pProperty->GetStream()); } else { pProperty->SetClassName(pReference->GetClassName()); pProperty->SetTemplatePath(""); } } //! fills an array element from a property void PropertyStream::FillArrayElement(void* pElement, IProperty* pProperty) { if(pProperty->GetType() == PT_Struct) { StructProperty* pStructProperty = static_cast<StructProperty*>(pProperty); ISerializableStruct* pStruct = static_cast<ISerializableStruct*>(pElement); pStructProperty->GetStream().SetMode(SM_Read); pStruct->Serialize(pStructProperty->GetStream()); } else if(pProperty->GetType() == PT_Reference) { IReference* pReference = static_cast<IReference*>(pElement); ReferenceProperty* pRefProperty = static_cast<ReferenceProperty*>(pProperty); FillReferenceFromProperty(pReference, pRefProperty); } else { pProperty->GetData(pElement); } } //! assignment operator PropertyStream& PropertyStream::operator = (const PropertyStream& other) { Clear(); for (size_t i = 0; i<other.GetNumProperties(); ++i) { IProperty* pPropertyCopy = other.GetProperty(i)->Copy(); m_aProperties.push_back(pPropertyCopy); } return *this; } }
29.67963
158
0.683222
franticsoftware
32308f50dc46137cef962e49a5b33fa158c1f135
223
cpp
C++
src/Game/Entities/Dynamic/Inspector.cpp
emmagonz22/DinerDashGameP3
687128c1cfd58ffe8639934b67190a3e4c764642
[ "Apache-2.0" ]
null
null
null
src/Game/Entities/Dynamic/Inspector.cpp
emmagonz22/DinerDashGameP3
687128c1cfd58ffe8639934b67190a3e4c764642
[ "Apache-2.0" ]
null
null
null
src/Game/Entities/Dynamic/Inspector.cpp
emmagonz22/DinerDashGameP3
687128c1cfd58ffe8639934b67190a3e4c764642
[ "Apache-2.0" ]
null
null
null
#include "Inspector.h" Inspector::Inspector(int x, int y, int width, int height, ofImage sprite, Burger* burger) : Client(x, y,width,height, sprite, burger) { //Empty constructor in case of thing wanna que added }
37.166667
134
0.70852
emmagonz22
3236852c59ca84af00eb07bed4dfea913e944f33
26,164
cpp
C++
termsrv/license/tlserver/server/templic.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
termsrv/license/tlserver/server/templic.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
termsrv/license/tlserver/server/templic.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+-------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1996-1998 // // File: templic.cpp // // Contents: // all routine deal with temporary license // // History: // Feb 4, 98 HueiWang Created //--------------------------------------------------------------------------- #include "pch.cpp" #include "globals.h" #include "templic.h" #include "misc.h" #include "db.h" #include "clilic.h" #include "keypack.h" #include "kp.h" #include "lkpdesc.h" #define STRSAFE_NO_DEPRECATE #include "strsafe.h" #define USSTRING_TEMPORARY _TEXT("Temporary Licenses for") DWORD TLSDBGetTemporaryLicense( IN PTLSDbWorkSpace pDbWkSpace, IN PTLSDBLICENSEREQUEST pRequest, IN OUT PTLSLICENSEPACK pLicensePack ); //+------------------------------------------------------------- DWORD TLSDBIssueTemporaryLicense( IN PTLSDbWorkSpace pDbWkSpace, IN PTLSDBLICENSEREQUEST pRequest, IN FILETIME* pNotBefore, IN FILETIME* pNotAfter, IN OUT PTLSDBLICENSEDPRODUCT pLicensedProduct ) /*++ Abstract: Issue a temporary license, insert a temporary license pack if necessary Parameters: pDbWkSpace - workspace handle. pRequest - license request. Returns: Note: Seperate routine for issuing perm license just in case we decide to use our own format for temp. license ++*/ { DWORD dwStatus=ERROR_SUCCESS; ULARGE_INTEGER ulSerialNumber; DWORD dwLicenseId; LPTSTR lpRequest=NULL; LICENSEDCLIENT issuedLicense; TLSLICENSEPACK LicensePack; PMGENERATELICENSE PolModGenLicense; PPMCERTEXTENSION pPolModCertExtension=NULL; FILETIME notBefore, notAfter; // ---------------------------------------------------------- // Issue license memset(&ulSerialNumber, 0, sizeof(ulSerialNumber)); //----------------------------------------------------------------------------- // this step require reduce available license by 1 // long numLicense=1; dwStatus=TLSDBGetTemporaryLicense( pDbWkSpace, pRequest, &LicensePack ); if(dwStatus != ERROR_SUCCESS) { goto cleanup; } if((LicensePack.ucAgreementType & ~LSKEYPACK_RESERVED_TYPE) != LSKEYPACKTYPE_TEMPORARY && (LicensePack.ucKeyPackStatus & ~LSKEYPACKSTATUS_RESERVED) != LSKEYPACKSTATUS_TEMPORARY ) { SetLastError(dwStatus = TLS_E_INTERNAL); TLSASSERT(FALSE); goto cleanup; } // reset status dwStatus = ERROR_SUCCESS; dwLicenseId=TLSDBGetNextLicenseId(); ulSerialNumber.LowPart = dwLicenseId; ulSerialNumber.HighPart = LicensePack.dwKeyPackId; // // Update License Table Here // memset(&issuedLicense, 0, sizeof(LICENSEDCLIENT)); issuedLicense.dwLicenseId = dwLicenseId; issuedLicense.dwKeyPackId = LicensePack.dwKeyPackId; issuedLicense.dwKeyPackLicenseId = LicensePack.dwNextSerialNumber; issuedLicense.dwNumLicenses = 1; if(pNotBefore == NULL || pNotAfter == NULL) { issuedLicense.ftIssueDate = time(NULL); issuedLicense.ftExpireDate = issuedLicense.ftIssueDate + g_GracePeriod * 24 * 60 * 60; } else { FileTimeToLicenseDate(pNotBefore, &(issuedLicense.ftIssueDate)); FileTimeToLicenseDate(pNotAfter, &(issuedLicense.ftExpireDate)); } issuedLicense.ucLicenseStatus = LSLICENSE_STATUS_TEMPORARY; _tcscpy(issuedLicense.szMachineName, pRequest->szMachineName); _tcscpy(issuedLicense.szUserName, pRequest->szUserName); issuedLicense.dwSystemBiosChkSum = pRequest->hWid.dwPlatformID; issuedLicense.dwVideoBiosChkSum = pRequest->hWid.Data1; issuedLicense.dwFloppyBiosChkSum = pRequest->hWid.Data2; issuedLicense.dwHardDiskSize = pRequest->hWid.Data3; issuedLicense.dwRamSize = pRequest->hWid.Data4; UnixTimeToFileTime(issuedLicense.ftIssueDate, &notBefore); UnixTimeToFileTime(issuedLicense.ftExpireDate, &notAfter); // // Inform Policy Module of license generation. // PolModGenLicense.pLicenseRequest = pRequest->pPolicyLicenseRequest; PolModGenLicense.dwKeyPackType = LSKEYPACKTYPE_TEMPORARY; PolModGenLicense.dwKeyPackId = LicensePack.dwKeyPackId; PolModGenLicense.dwKeyPackLicenseId = LicensePack.dwNextSerialNumber; PolModGenLicense.ClientLicenseSerialNumber = ulSerialNumber; PolModGenLicense.ftNotBefore = notBefore; PolModGenLicense.ftNotAfter = notAfter; dwStatus = pRequest->pPolicy->PMLicenseRequest( pRequest->hClient, REQUEST_GENLICENSE, (PVOID)&PolModGenLicense, (PVOID *)&pPolModCertExtension ); if(dwStatus != ERROR_SUCCESS) { // // Error in policy module // goto cleanup; } // // Check error return from policy module // if(pPolModCertExtension != NULL) { if(pPolModCertExtension->pbData != NULL && pPolModCertExtension->cbData == 0 || pPolModCertExtension->pbData == NULL && pPolModCertExtension->cbData != 0 ) { // assuming no extension data pPolModCertExtension->cbData = 0; pPolModCertExtension->pbData = NULL; } if(CompareFileTime(&(pPolModCertExtension->ftNotBefore), &(pPolModCertExtension->ftNotAfter)) > 0) { // // invalid data return from policy module // TLSLogEvent( EVENTLOG_ERROR_TYPE, TLS_E_GENERATECLIENTELICENSE, dwStatus = TLS_E_POLICYMODULEERROR, pRequest->pPolicy->GetCompanyName(), pRequest->pPolicy->GetProductId() ); goto cleanup; } // // do not accept changes to license expiration date // if(pNotBefore != NULL && pNotAfter != NULL) { if( FileTimeToLicenseDate(&(pPolModCertExtension->ftNotBefore), &issuedLicense.ftIssueDate) == FALSE || FileTimeToLicenseDate(&(pPolModCertExtension->ftNotAfter), &issuedLicense.ftExpireDate) == FALSE ) { // // Invalid data return from policy module // TLSLogEvent( EVENTLOG_ERROR_TYPE, TLS_E_GENERATECLIENTELICENSE, dwStatus = TLS_E_POLICYMODULEERROR, pRequest->pPolicy->GetCompanyName(), pRequest->pPolicy->GetProductId() ); goto cleanup; } } notBefore = pPolModCertExtension->ftNotBefore; notAfter = pPolModCertExtension->ftNotAfter; } // // Add license into license table // dwStatus = TLSDBLicenseAdd( pDbWkSpace, &issuedLicense, 0, NULL ); // // Return licensed product // pLicensedProduct->pSubjectPublicKeyInfo = NULL; pLicensedProduct->dwQuantity = 1; pLicensedProduct->ulSerialNumber = ulSerialNumber; pLicensedProduct->dwKeyPackId = LicensePack.dwKeyPackId; pLicensedProduct->dwLicenseId = dwLicenseId; pLicensedProduct->dwKeyPackLicenseId = LicensePack.dwNextSerialNumber; pLicensedProduct->ClientHwid = pRequest->hWid; pLicensedProduct->bTemp = TRUE; pLicensedProduct->NotBefore = notBefore; pLicensedProduct->NotAfter = notAfter; pLicensedProduct->dwProductVersion = MAKELONG(LicensePack.wMinorVersion, LicensePack.wMajorVersion); _tcscpy(pLicensedProduct->szCompanyName, LicensePack.szCompanyName); _tcscpy(pLicensedProduct->szLicensedProductId, LicensePack.szProductId); _tcscpy(pLicensedProduct->szRequestProductId, pRequest->pClientLicenseRequest->pszProductId); _tcscpy(pLicensedProduct->szUserName, pRequest->szUserName); _tcscpy(pLicensedProduct->szMachineName, pRequest->szMachineName); pLicensedProduct->dwLanguageID = pRequest->dwLanguageID; pLicensedProduct->dwPlatformID = pRequest->dwPlatformID; pLicensedProduct->pbPolicyData = (pPolModCertExtension) ? pPolModCertExtension->pbData : NULL; pLicensedProduct->cbPolicyData = (pPolModCertExtension) ? pPolModCertExtension->cbData : 0; cleanup: return dwStatus; } //----------------------------------------------------------------- DWORD TLSDBAddTemporaryKeyPack( IN PTLSDbWorkSpace pDbWkSpace, IN PTLSDBLICENSEREQUEST pRequest, IN OUT LPTLSLICENSEPACK lpTmpKeyPackAdd ) /*++ Abstract: Add a temporary keypack into database. Parameter: pDbWkSpace : workspace handle. szCompanyName : szProductId : dwVersion : dwPlatformId : dwLangId : lpTmpKeyPackAdd : added keypack. Returns: ++*/ { DWORD dwStatus; TLSLICENSEPACK LicPack; TLSLICENSEPACK existingLicPack; LICPACKDESC LicPackDesc; LICPACKDESC existingLicPackDesc; BOOL bAddDefDescription=FALSE; TCHAR szDefProductDesc[LSERVER_MAX_STRING_SIZE]; int count=0; memset(&LicPack, 0, sizeof(TLSLICENSEPACK)); memset(&existingLicPack, 0, sizeof(TLSLICENSEPACK)); memset(&LicPackDesc, 0, sizeof(LICPACKDESC)); memset(szDefProductDesc, 0, sizeof(szDefProductDesc)); memset(&existingLicPackDesc, 0, sizeof(LICPACKDESC)); // // Load product description prefix // LoadResourceString( IDS_TEMPORARY_PRODUCTDESC, szDefProductDesc, sizeof(szDefProductDesc) / sizeof(szDefProductDesc[0]) ); LicPack.ucAgreementType = LSKEYPACKTYPE_TEMPORARY; StringCchCopyN( LicPack.szCompanyName, sizeof(LicPack.szCompanyName)/sizeof(LicPack.szCompanyName[0]), pRequest->pszCompanyName, min(_tcslen(pRequest->pszCompanyName), LSERVER_MAX_STRING_SIZE) ); StringCchCopyN( LicPack.szProductId, sizeof(LicPack.szCompanyName)/ sizeof(LicPack.szProductId[0]), pRequest->pszProductId, min(_tcslen(pRequest->pszProductId), LSERVER_MAX_STRING_SIZE) ); StringCchCopyN( LicPack.szInstallId, sizeof(LicPack.szInstallId)/sizeof(LicPack.szInstallId[0]), (LPTSTR)g_pszServerPid, min(_tcslen((LPTSTR)g_pszServerPid), LSERVER_MAX_STRING_SIZE) ); StringCchCopyN( LicPack.szTlsServerName, sizeof(LicPack.szTlsServerName)/sizeof(LicPack.szTlsServerName[0]), g_szComputerName, min(_tcslen(g_szComputerName), LSERVER_MAX_STRING_SIZE) ); LicPack.wMajorVersion = HIWORD(pRequest->dwProductVersion); LicPack.wMinorVersion = LOWORD(pRequest->dwProductVersion); LicPack.dwPlatformType = pRequest->dwPlatformID; LicPack.ucChannelOfPurchase = LSKEYPACKCHANNELOFPURCHASE_UNKNOWN; LicPack.dwTotalLicenseInKeyPack = INT_MAX; LoadResourceString( IDS_TEMPORARY_KEYPACKID, LicPack.szKeyPackId, sizeof(LicPack.szKeyPackId)/sizeof(LicPack.szKeyPackId[0]) ); LoadResourceString( IDS_TEMPORARY_BSERIALNUMBER, LicPack.szBeginSerialNumber, sizeof(LicPack.szBeginSerialNumber)/sizeof(LicPack.szBeginSerialNumber[0]) ); do { // // Add entry into keypack table. // dwStatus = TLSDBKeyPackAdd( pDbWkSpace, &LicPack ); *lpTmpKeyPackAdd = LicPack; LicPack.pbDomainSid = NULL; LicPack.cbDomainSid = 0; if(dwStatus == TLS_E_DUPLICATE_RECORD) { // // temporary keypack already exist // dwStatus = ERROR_SUCCESS; break; } else if(dwStatus != ERROR_SUCCESS) { // // some other error occurred // break; } // // Activate KeyPack // LicPack.ucKeyPackStatus = LSKEYPACKSTATUS_TEMPORARY; LicPack.dwActivateDate = (DWORD) time(NULL); LicPack.dwExpirationDate = INT_MAX; LicPack.dwNumberOfLicenses = 0; dwStatus=TLSDBKeyPackSetValues( pDbWkSpace, FALSE, LSKEYPACK_SET_ACTIVATEDATE | LSKEYPACK_SET_KEYPACKSTATUS | LSKEYPACK_SET_EXPIREDATE | LSKEYPACK_EXSEARCH_AVAILABLE, &LicPack ); bAddDefDescription = TRUE; // // Find existing keypack description // dwStatus = TLSDBKeyPackEnumBegin( pDbWkSpace, TRUE, LSKEYPACK_SEARCH_PRODUCTID | LSKEYPACK_SEARCH_COMPANYNAME | LSKEYPACK_SEARCH_PLATFORMTYPE, &LicPack ); if(dwStatus != ERROR_SUCCESS) break; do { dwStatus = TLSDBKeyPackEnumNext( pDbWkSpace, &existingLicPack ); if(existingLicPack.dwKeyPackId != LicPack.dwKeyPackId) { break; } } while(dwStatus == ERROR_SUCCESS); TLSDBKeyPackEnumEnd(pDbWkSpace); if(dwStatus != ERROR_SUCCESS || existingLicPack.dwKeyPackId != LicPack.dwKeyPackId) { break; } // // Copy existing keypack description into keypack description table // existingLicPackDesc.dwKeyPackId = existingLicPack.dwKeyPackId; dwStatus = TLSDBKeyPackDescEnumBegin( pDbWkSpace, TRUE, LICPACKDESCRECORD_TABLE_SEARCH_KEYPACKID, &existingLicPackDesc ); while(dwStatus == ERROR_SUCCESS) { dwStatus = TLSDBKeyPackDescEnumNext( pDbWkSpace, &existingLicPackDesc ); if(dwStatus != ERROR_SUCCESS) break; LicPackDesc.dwKeyPackId = LicPack.dwKeyPackId; LicPackDesc.dwLanguageId = existingLicPackDesc.dwLanguageId; _tcscpy(LicPackDesc.szCompanyName, existingLicPackDesc.szCompanyName); _tcscpy(LicPackDesc.szProductName, existingLicPackDesc.szProductName); // // pretty format the description // _sntprintf( LicPackDesc.szProductDesc, sizeof(LicPackDesc.szProductDesc)/sizeof(LicPackDesc.szProductDesc[0])-1, _TEXT("%s %s"), (existingLicPackDesc.dwLanguageId != GetSystemDefaultLangID()) ? USSTRING_TEMPORARY : szDefProductDesc, existingLicPackDesc.szProductDesc ); // quick and dirty fix, // // TODO - need to do a duplicate table then use the duplicate handle to // insert the record, SetValue uses enumeration to verify if record exist // which fail because we are already in enumeration // if(pDbWkSpace->m_LicPackDescTable.InsertRecord(LicPackDesc) != TRUE) { SetLastError(dwStatus = SET_JB_ERROR(pDbWkSpace->m_LicPackDescTable.GetLastJetError())); break; } //dwStatus = TLSDBKeyPackDescSetValue( // pDbWkSpace, // KEYPACKDESC_SET_ADD_ENTRY, // &keyPackDesc // ); count++; } if(count != 0) { bAddDefDescription = FALSE; } if(dwStatus == TLS_I_NO_MORE_DATA) { dwStatus = ERROR_SUCCESS; } } while(FALSE); if(bAddDefDescription) { // // ask policy module if they have description // PMKEYPACKDESCREQ kpDescReq; PPMKEYPACKDESC pKpDesc; // // Ask for English description // kpDescReq.pszProductId = pRequest->pszProductId; kpDescReq.dwLangId = MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US); kpDescReq.dwVersion = pRequest->dwProductVersion; pKpDesc = NULL; dwStatus = pRequest->pPolicy->PMLicenseRequest( pRequest->hClient, REQUEST_KEYPACKDESC, (PVOID)&kpDescReq, (PVOID *)&pKpDesc ); if(dwStatus == ERROR_SUCCESS && pKpDesc != NULL) { LicPackDesc.dwKeyPackId = LicPack.dwKeyPackId; LicPackDesc.dwLanguageId = MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US); _tcscpy(LicPackDesc.szCompanyName, pKpDesc->szCompanyName); _tcscpy(LicPackDesc.szProductName, pKpDesc->szProductName); // // pretty format the description // _sntprintf( LicPackDesc.szProductDesc, sizeof(LicPackDesc.szProductDesc)/sizeof(LicPackDesc.szProductDesc[0])-1, _TEXT("%s %s"), USSTRING_TEMPORARY, // US langid, don't use localized one pKpDesc->szProductDesc ); // // Ignore error // dwStatus = TLSDBKeyPackDescAddEntry( pDbWkSpace, &LicPackDesc ); if(dwStatus == ERROR_SUCCESS) { bAddDefDescription = FALSE; } } if(GetSystemDefaultLangID() != kpDescReq.dwLangId) { // // Get System default language id // kpDescReq.pszProductId = pRequest->pszProductId; kpDescReq.dwLangId = GetSystemDefaultLangID(); kpDescReq.dwVersion = pRequest->dwProductVersion; pKpDesc = NULL; dwStatus = pRequest->pPolicy->PMLicenseRequest( pRequest->hClient, REQUEST_KEYPACKDESC, (PVOID)&kpDescReq, (PVOID *)&pKpDesc ); if(dwStatus == ERROR_SUCCESS && pKpDesc != NULL) { LicPackDesc.dwKeyPackId = LicPack.dwKeyPackId; LicPackDesc.dwLanguageId = GetSystemDefaultLangID(); _tcscpy(LicPackDesc.szCompanyName, pKpDesc->szCompanyName); _tcscpy(LicPackDesc.szProductName, pKpDesc->szProductName); // // pretty format the description // _sntprintf( LicPackDesc.szProductDesc, sizeof(LicPackDesc.szProductDesc)/sizeof(LicPackDesc.szProductDesc[0])-1, _TEXT("%s %s"), szDefProductDesc, pKpDesc->szProductDesc ); // // Ignore error // dwStatus = TLSDBKeyPackDescAddEntry( pDbWkSpace, &LicPackDesc ); if(dwStatus == ERROR_SUCCESS) { bAddDefDescription = FALSE; } } } } if(bAddDefDescription) { // // No existing keypack description, add predefined product description // "temporary license for <product ID>" // LicPackDesc.dwKeyPackId = LicPack.dwKeyPackId; _tcscpy(LicPackDesc.szCompanyName, LicPack.szCompanyName); _tcscpy(LicPackDesc.szProductName, LicPackDesc.szProductDesc); LicPackDesc.dwLanguageId = MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US); _sntprintf(LicPackDesc.szProductDesc, sizeof(LicPackDesc.szProductDesc)/sizeof(LicPackDesc.szProductDesc[0])-1, _TEXT("%s %s"), USSTRING_TEMPORARY, pRequest->pszProductId); dwStatus = TLSDBKeyPackDescAddEntry( pDbWkSpace, &LicPackDesc ); if(GetSystemDefaultLangID() != MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US)) { LicPackDesc.dwLanguageId = GetSystemDefaultLangID(); _sntprintf(LicPackDesc.szProductDesc, sizeof(LicPackDesc.szProductDesc)/sizeof(LicPackDesc.szProductDesc[0])-1, _TEXT("%s %s"), szDefProductDesc, pRequest->pszProductId); dwStatus = TLSDBKeyPackDescAddEntry( pDbWkSpace, &LicPackDesc ); } } return dwStatus; } //++---------------------------------------------------------- DWORD TLSDBGetTemporaryLicense( IN PTLSDbWorkSpace pDbWkSpace, IN PTLSDBLICENSEREQUEST pRequest, IN OUT PTLSLICENSEPACK pLicensePack ) /*++ Abstract: Allocate a temporary license from temporary license pack. Parameter: pDbWkSpace : workspace handle. pRequest : Product to request license from. lpdwKeyPackId : return keypack ID that license is allocated from. lpdwKeyPackLicenseId : license ID for the keypack. lpdwExpirationDate : expiration date of license pack. lpucKeyPackStatus : status of keypack. lpucKeyPackType : type of keypack, always temporary. Returns: ++*/ { DWORD dwStatus=ERROR_SUCCESS; DWORD dump; TLSLICENSEPACK LicenseKeyPack; TLSDBLicenseAllocation allocated; TLSDBAllocateRequest AllocateRequest; BOOL bAcceptTemp=TRUE; LicenseKeyPack.pbDomainSid = NULL; // // Tell policy module we are about to allocate a license from temporary // license pack // dwStatus = pRequest->pPolicy->PMLicenseRequest( pRequest->hClient, REQUEST_TEMPORARY, NULL, (PVOID *)&bAcceptTemp ); // // Policy Module error // if(dwStatus != ERROR_SUCCESS) { return dwStatus; } // // Policy module does not accept temporary license // if(bAcceptTemp == FALSE) { return dwStatus = TLS_I_POLICYMODULETEMPORARYLICENSE; } AllocateRequest.ucAgreementType = LSKEYPACKTYPE_TEMPORARY; AllocateRequest.szCompanyName = (LPTSTR)pRequest->pszCompanyName; AllocateRequest.szProductId = (LPTSTR)pRequest->pszProductId; AllocateRequest.dwVersion = pRequest->dwProductVersion; AllocateRequest.dwPlatformId = pRequest->dwPlatformID; AllocateRequest.dwLangId = pRequest->dwLanguageID; AllocateRequest.dwNumLicenses = 1; AllocateRequest.dwScheme = ALLOCATE_ANY_GREATER_VERSION; memset(&allocated, 0, sizeof(allocated)); allocated.dwBufSize = 1; allocated.pdwAllocationVector = &dump; allocated.lpAllocateKeyPack = &LicenseKeyPack; dwStatus = TLSDBAddTemporaryKeyPack( pDbWkSpace, pRequest, &LicenseKeyPack ); if(dwStatus == ERROR_SUCCESS) { allocated.dwBufSize = 1; dwStatus = AllocateLicensesFromDB( pDbWkSpace, &AllocateRequest, TRUE, // fCheckAgreementType &allocated ); } if(dwStatus == ERROR_SUCCESS) { *pLicensePack = LicenseKeyPack; } else if(dwStatus == TLS_I_NO_MORE_DATA) { SetLastError(dwStatus = TLS_E_INTERNAL); } return dwStatus; }
33.457801
125
0.533137
npocmaka
323c476323b9152d26412bc6573257b7b4a7ff8a
2,284
cpp
C++
src/odil/pdu/AAbort.cpp
genisysram/odil
e6b12df698ce452f9c5d86858e896e9b6d28cdf0
[ "CECILL-B" ]
72
2016-02-04T00:41:02.000Z
2022-03-18T18:10:34.000Z
src/odil/pdu/AAbort.cpp
genisysram/odil
e6b12df698ce452f9c5d86858e896e9b6d28cdf0
[ "CECILL-B" ]
74
2016-01-11T16:04:46.000Z
2021-11-18T16:36:11.000Z
src/odil/pdu/AAbort.cpp
genisysram/odil
e6b12df698ce452f9c5d86858e896e9b6d28cdf0
[ "CECILL-B" ]
23
2016-04-27T07:14:56.000Z
2021-09-28T21:59:31.000Z
/************************************************************************* * odil - Copyright (C) Universite de Strasbourg * Distributed under the terms of the CeCILL-B license, as published by * the CEA-CNRS-INRIA. Refer to the LICENSE file or to * http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html * for details. ************************************************************************/ #include "odil/pdu/AAbort.h" #include <cstdint> #include <istream> #include "odil/Exception.h" #include "odil/pdu/Object.h" namespace odil { namespace pdu { AAbort ::AAbort(unsigned char source, unsigned char reason) { this->_item.add("PDU-type", uint8_t(0x07)); this->_item.add("Reserved-1", uint8_t(0)); this->_item.add("PDU-length", uint32_t(4)); this->_item.add("Reserved-2", uint8_t(0)); this->_item.add("Reserved-3", uint8_t(0)); this->_item.add("Source", uint8_t(0)); this->_item.add("Reason", uint8_t(0)); this->set_source(source); this->set_reason(reason); } AAbort ::AAbort(std::istream & stream) { this->_item.read(stream, "PDU-type", Item::Field::Type::unsigned_int_8); if(this->_item.as_unsigned_int_8("PDU-type") != 0x07) { throw Exception("Invalid PDU type"); } this->_item.read(stream, "Reserved-1", Item::Field::Type::unsigned_int_8); this->_item.read(stream, "PDU-length", Item::Field::Type::unsigned_int_32); this->_item.read(stream, "Reserved-2", Item::Field::Type::unsigned_int_8); this->_item.read(stream, "Reserved-3", Item::Field::Type::unsigned_int_8); this->_item.read(stream, "Source", Item::Field::Type::unsigned_int_8); this->_item.read(stream, "Reason", Item::Field::Type::unsigned_int_8); } unsigned char AAbort ::get_source() const { return this->_item.as_unsigned_int_8("Source"); } void AAbort ::set_source(unsigned char source) { if(source > 2) { throw Exception("Unknown source"); } this->_item.as_unsigned_int_8("Source") = source; } unsigned char AAbort ::get_reason() const { return this->_item.as_unsigned_int_8("Reason"); } void AAbort ::set_reason(unsigned char reason) { if(reason > 6) { throw Exception("Unknown reason"); } this->_item.as_unsigned_int_8("Reason") = reason; } } }
24.297872
79
0.627408
genisysram
323ee4bf97a753729e65cf3c8b49512152ac57e9
18,924
cpp
C++
main.cpp
jczaja/test-movidius-NCS-v2-C-API
5f461b7700ad2560dc60f9f3d72df2ba3646cdf9
[ "BSD-3-Clause" ]
null
null
null
main.cpp
jczaja/test-movidius-NCS-v2-C-API
5f461b7700ad2560dc60f9f3d72df2ba3646cdf9
[ "BSD-3-Clause" ]
null
null
null
main.cpp
jczaja/test-movidius-NCS-v2-C-API
5f461b7700ad2560dc60f9f3d72df2ba3646cdf9
[ "BSD-3-Clause" ]
null
null
null
#include <mvnc.h> #include <opencv2/opencv.hpp> #include <time.h> #include <cstring> #include <vector> #include <string> #include <fstream> #include <streambuf> #include <sstream> #include <memory> #include <x86intrin.h> #include <sys/types.h> #include <unistd.h> #include "gflags/gflags.h" DEFINE_bool(profile,false,"Print profiling(times of execution) information"); DEFINE_int32(num_reps, 1, "Number of repetitions of convolutions to be performed"); DEFINE_string(synset, "./synset_words.txt", "relative path to file describing categories"); DEFINE_string(graph, "./myGoogleNet-shave1", "relative path to graph file"); const unsigned int net_data_width = 224; const unsigned int net_data_height = 224; const unsigned int net_data_channels = 3; const cv::Scalar net_mean(0.40787054*255.0, 0.45752458*255.0, 0.48109378*255.0); struct platform_info { long num_logical_processors; long num_physical_processors_per_socket; long num_hw_threads_per_socket; unsigned int num_ht_threads; unsigned int num_total_phys_cores; unsigned long long tsc; unsigned long long max_bandwidth; }; class nn_hardware_platform { public: nn_hardware_platform() : m_num_logical_processors(0), m_num_physical_processors_per_socket(0), m_num_hw_threads_per_socket(0) ,m_num_ht_threads(1), m_num_total_phys_cores(1), m_tsc(0), m_fmaspc(0), m_max_bandwidth(0) { #ifdef __linux__ m_num_logical_processors = sysconf(_SC_NPROCESSORS_ONLN); m_num_physical_processors_per_socket = 0; std::ifstream ifs; ifs.open("/proc/cpuinfo"); // If there is no /proc/cpuinfo fallback to default scheduler if(ifs.good() == false) { m_num_physical_processors_per_socket = m_num_logical_processors; assert(0); // No cpuinfo? investigate that return; } std::string cpuinfo_content((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); std::stringstream cpuinfo_stream(cpuinfo_content); std::string cpuinfo_line; std::string cpu_name; while(std::getline(cpuinfo_stream,cpuinfo_line,'\n')){ if((m_num_physical_processors_per_socket == 0) && (cpuinfo_line.find("cpu cores") != std::string::npos)) { // convert std::string into number eg. skip colon and after it in the same line should be number of physical cores per socket std::stringstream( cpuinfo_line.substr(cpuinfo_line.find(":") + 1) ) >> m_num_physical_processors_per_socket; } if(cpuinfo_line.find("siblings") != std::string::npos) { // convert std::string into number eg. skip colon and after it in the same line should be number of HW threads per socket std::stringstream( cpuinfo_line.substr(cpuinfo_line.find(":") + 1) ) >> m_num_hw_threads_per_socket; } if(cpuinfo_line.find("model") != std::string::npos) { cpu_name = cpuinfo_line; // convert std::string into number eg. skip colon and after it in the same line should be number of HW threads per socket float ghz_tsc = 0.0f; std::stringstream( cpuinfo_line.substr(cpuinfo_line.find("@") + 1) ) >> ghz_tsc; m_tsc = static_cast<unsigned long long>(ghz_tsc*1000000000.0f); // Maximal bandwidth is Xeon 68GB/s , Brix 25.8GB/s if(cpuinfo_line.find("Xeon") != std::string::npos) { m_max_bandwidth = 68000; //68 GB/s -- XEONE5 } if(cpuinfo_line.find("i7-4770R") != std::string::npos) { m_max_bandwidth = 25800; //25.68 GB/s -- BRIX } } // determine instruction set (AVX, AVX2, AVX512) if(m_fmaspc == 0) { if (cpuinfo_line.find(" avx") != std::string::npos) { m_fmaspc = 8; // On AVX instruction set we have one FMA unit , width of registers is 256bits, so we can do 8 muls and adds on floats per cycle if (cpuinfo_line.find(" avx2") != std::string::npos) { m_fmaspc = 16; // With AVX2 instruction set we have two FMA unit , width of registers is 256bits, so we can do 16 muls and adds on floats per cycle } if (cpuinfo_line.find(" avx512") != std::string::npos) { m_fmaspc = 32; // With AVX512 instruction set we have two FMA unit , width of registers is 512bits, so we can do 32 muls and adds on floats per cycle } } } } // If no FMA ops / cycle was given/found then raise a concern if(m_fmaspc == 0) { throw std::string("No AVX instruction set found. Please use \"--fmaspc\" to specify\n"); } // There is cpuinfo, but parsing did not get quite right? Investigate it assert( m_num_physical_processors_per_socket > 0); assert( m_num_hw_threads_per_socket > 0); // Calculate how many threads can be run on single cpu core , in case of lack of hw info attributes assume 1 m_num_ht_threads = m_num_physical_processors_per_socket != 0 ? m_num_hw_threads_per_socket/ m_num_physical_processors_per_socket : 1; // calculate total number of physical cores eg. how many full Hw threads we can run in parallel m_num_total_phys_cores = m_num_hw_threads_per_socket != 0 ? m_num_logical_processors / m_num_hw_threads_per_socket * m_num_physical_processors_per_socket : 1; std::cout << "Platform:" << std::endl << " " << cpu_name << std::endl << " number of physical cores: " << m_num_total_phys_cores << std::endl; ifs.close(); #endif } // Function computing percentage of theretical efficiency of HW capabilities float compute_theoretical_efficiency(unsigned long long start_time, unsigned long long end_time, unsigned long long num_fmas) { // Num theoretical operations // Time given is there return 100.0*num_fmas/((float)(m_num_total_phys_cores*m_fmaspc))/((float)(end_time - start_time)); } void get_platform_info(platform_info& pi) { pi.num_logical_processors = m_num_logical_processors; pi.num_physical_processors_per_socket = m_num_physical_processors_per_socket; pi.num_hw_threads_per_socket = m_num_hw_threads_per_socket; pi.num_ht_threads = m_num_ht_threads; pi.num_total_phys_cores = m_num_total_phys_cores; pi.tsc = m_tsc; pi.max_bandwidth = m_max_bandwidth; } private: long m_num_logical_processors; long m_num_physical_processors_per_socket; long m_num_hw_threads_per_socket; unsigned int m_num_ht_threads; unsigned int m_num_total_phys_cores; unsigned long long m_tsc; short int m_fmaspc; unsigned long long m_max_bandwidth; }; void prepareTensor(std::unique_ptr<unsigned char[]>& input, std::string& imageName,unsigned int* inputLength) { // load an image using OpenCV cv::Mat imagefp32 = cv::imread(imageName, -1); if (imagefp32.empty()) throw std::string("Error reading image: ") + imageName; // Convert to expected format cv::Mat samplefp32; if (imagefp32.channels() == 4 && net_data_channels == 3) cv::cvtColor(imagefp32, samplefp32, cv::COLOR_BGRA2BGR); else if (imagefp32.channels() == 1 && net_data_channels == 3) cv::cvtColor(imagefp32, samplefp32, cv::COLOR_GRAY2BGR); else samplefp32 = imagefp32; // Resize input image to expected geometry cv::Size input_geometry(net_data_width, net_data_height); cv::Mat samplefp32_resized; if (samplefp32.size() != input_geometry) cv::resize(samplefp32, samplefp32_resized, input_geometry); else samplefp32_resized = samplefp32; // Convert to float32 cv::Mat samplefp32_float; samplefp32_resized.convertTo(samplefp32_float, CV_32FC3); // Mean subtract cv::Mat sample_fp32_normalized; cv::Mat mean = cv::Mat(input_geometry, CV_32FC3, net_mean); cv::subtract(samplefp32_float, mean, sample_fp32_normalized); input.reset(new unsigned char[sizeof(float)*net_data_width*net_data_height*net_data_channels]); int dst_index = 0; for(unsigned int i=0; i<net_data_channels*net_data_width*net_data_height;++i) { ((float*)input.get())[dst_index++] = ((float*)samplefp32_float.data)[i]; } *inputLength = sizeof(float)*net_data_width*net_data_height*net_data_channels; } class NCSDevice { public: NCSDevice() { # ifndef NDEBUG std::cout << "Creating NCS resources" << std::endl; # endif index = 0; // Index of device to query for ncStatus_t ret = ncDeviceCreate(index,&deviceHandle); // hardcoded max name size if (ret == NC_OK) { std::cout << "Found NCS named: " << index++ << std::endl; } // If not devices present the exit if (index == 0) { throw std::string("Error: No Intel Movidius identified in a system!\n"); } // Using first device ret = ncDeviceOpen(deviceHandle); if(ret != NC_OK) { // If we cannot open communication with device then clean up resources destroy(); throw std::string("Error: Could not open NCS device: ") + std::to_string(index-1) ; } } ~NCSDevice() { // Close communitaction with device Device # ifndef NDEBUG std::cout << "Closing communication with NCS: " << std::to_string(index-1) << std::endl; # endif ncStatus_t ret = ncDeviceClose(deviceHandle); if (ret != NC_OK) { std::cerr << "Error: Closing of device: "<< std::to_string(index-1) <<"failed!" << std::endl; } destroy(); } struct ncDeviceHandle_t* getHandle(void) { return deviceHandle; } private: void destroy(void) { # ifndef NDEBUG std::cout << "Destroying NCS resources" << std::endl; # endif ncStatus_t ret = ncDeviceDestroy(&deviceHandle); if (ret != NC_OK) { std::cerr << "Error: Freeing resources of device: "<< std::to_string(index-1) <<"failed!" << std::endl; } } private: struct ncDeviceHandle_t* deviceHandle = nullptr; int index = 0; }; class NCSFifo { public: NCSFifo(const std::string& name, ncFifoType_t fifotype) { // Create input FIFO ncStatus_t ret = ncFifoCreate("input1",fifotype, &FIFO_); if (ret != NC_OK) { throw std::string("Error: Unable to create FIFO!"); } } ~NCSFifo() { destroy(); } private: void destroy() { # ifndef NDEBUG std::cout << "Freeing FIFO!" << std::endl; # endif ncStatus_t ret = ncFifoDestroy(&FIFO_); if (ret != NC_OK) { std::cout << "Error: FIFO destroying failed!" << std::endl; } } public: struct ncFifoHandle_t* FIFO_; }; class NCSGraph { public: NCSGraph(struct ncDeviceHandle_t* deviceHandle, const std::string& graphFileName) : graphFile(nullptr), result(nullptr), input("input",NC_FIFO_HOST_WO), output("output",NC_FIFO_HOST_RO) { # ifndef NDEBUG std::cout << "Initializing graph!" << std::endl; # endif // Creation of graph resources unsigned int graphSize = 0; loadGraphFromFile(graphFile, graphFileName, &graphSize); ncStatus_t ret = ncGraphCreate(graphFileName.c_str(),&graphHandlePtr); if (ret != NC_OK) { throw std::string("Error: Graph Creation failed!"); } // Allocate graph on NCS ret = ncGraphAllocate(deviceHandle,graphHandlePtr,graphFile.get(),graphSize); if (ret != NC_OK) { destroy(); throw std::string("Error: Graph Allocation failed!"); } unsigned int optionSize = sizeof(inputDescriptor); ret = ncGraphGetOption(graphHandlePtr, NC_RO_GRAPH_INPUT_TENSOR_DESCRIPTORS, &inputDescriptor, &optionSize); if (ret != NC_OK) { destroy(); throw std::string("Error: Unable to create input FIFO!"); } ret = ncFifoAllocate(input.FIFO_, deviceHandle, &inputDescriptor, 2); if (ret != NC_OK) { destroy(); throw std::string("Error: Unable to allocate input FIFO! on NCS"); } optionSize = sizeof(outputDescriptor); ret = ncGraphGetOption(graphHandlePtr, NC_RO_GRAPH_OUTPUT_TENSOR_DESCRIPTORS, &outputDescriptor, &optionSize); if (ret != NC_OK) { destroy(); throw std::string("Error: Unable to create output FIFO!"); } ret = ncFifoAllocate(output.FIFO_, deviceHandle, &outputDescriptor, 2); if (ret != NC_OK) { destroy(); throw std::string("Error: Unable to allocate input FIFO! on NCS"); } // Get size of outputFIFO element optionSize = sizeof(unsigned int); ret = ncFifoGetOption(output.FIFO_, NC_RO_FIFO_ELEMENT_DATA_SIZE, &outputFIFOsize, &optionSize); if (ret != NC_OK) { throw std::string("Error: Getting output FIFO single element size failed!"); } // Prepare buffer for reading output result.reset(new unsigned char[outputFIFOsize]); } ~NCSGraph() { destroy(); } struct ncGraphHandle_t* getHandle(void) { return graphHandlePtr; } void printProfiling(void) { unsigned int optionSize = sizeof(unsigned int); unsigned int profilingSize = 0; ncStatus_t ret = ncGraphGetOption(graphHandlePtr, NC_RO_GRAPH_TIME_TAKEN_ARRAY_SIZE, &profilingSize, &optionSize); if (ret != NC_OK) { throw std::string("Error: Getting size of time taken array failed!!"); } // Time measures for stages are of float data type std::unique_ptr<float> profilingData(new float[profilingSize/sizeof(float)]); ret = ncGraphGetOption(graphHandlePtr, NC_RO_GRAPH_TIME_TAKEN, profilingData.get(), &profilingSize); std::cout << "Performance profiling:" << std::endl; float totalTime = 0.0f; for(unsigned int i=0; i<profilingSize/sizeof(float); ++i) { std::cout << " " << profilingData.get()[i] << " ms"<<std::endl; totalTime += profilingData.get()[i]; } std::cout << "Total compute time: " << std::to_string(totalTime) << " ms"<< std::endl; } void infer(std::vector<std::unique_ptr<unsigned char[]> >& tensors, unsigned int inputLength) { ncStatus_t ret = NC_OK; for(auto& tensor : tensors) { ret = ncFifoWriteElem(input.FIFO_,tensor.get(),&inputLength, nullptr); if (ret != NC_OK) { throw std::string("Error: Loading Tensor into input queue failed!"); } ret = ncGraphQueueInference(graphHandlePtr,&(input.FIFO_), 1, &(output.FIFO_), 1); if (ret != NC_OK) { throw std::string("Error: Queing inference failed!"); } } // Getting elements for(size_t i=0; i < tensors.size(); ++i) { ret = ncFifoReadElem(output.FIFO_, result.get(), &outputFIFOsize, nullptr); if (ret != NC_OK) { throw std::string("Error: Reading element failed !"); } printPredictions(result.get(),outputFIFOsize); } } private: void loadGraphFromFile(std::unique_ptr<char[]>& graphFile, const std::string& graphFileName, unsigned int* graphSize) { std::ifstream ifs; ifs.open(graphFileName, std::ifstream::binary); if (ifs.good() == false) { throw std::string("Error: Unable to open graph file: ") + graphFileName; } // Get size of file ifs.seekg(0, ifs.end); *graphSize = ifs.tellg(); ifs.seekg(0, ifs.beg); graphFile.reset(new char[*graphSize]); ifs.read(graphFile.get(),*graphSize); ifs.close(); } void destroy() { # ifndef NDEBUG std::cout << "Freeing graph!" << std::endl; # endif ncStatus_t ret = ncGraphDestroy(&graphHandlePtr); if (ret != NC_OK) { std::cout << "Error: Graph destroying failed!" << std::endl; } } void printPredictions(void* outputTensor,unsigned int outputLength) { unsigned int net_output_width = outputLength/sizeof(float); float* predictions = (float*)outputTensor; int top1_index= -1; float top1_result = -1.0; // find top1 results for(unsigned int i = 0; i<net_output_width;++i) { if(predictions[i] > top1_result) { top1_result = predictions[i]; top1_index = i; } } // Print top-1 result (class name , prob) std::ifstream synset_words(FLAGS_synset); std::string top1_class(std::to_string(top1_index)); if(synset_words.is_open()) { for (int i=0; i<=top1_index; ++i) { std::getline(synset_words,top1_class); } } std::cout << std::endl << "top-1: " << top1_result << " (" << top1_class << ")" << std::endl; } private: std::unique_ptr<char[]> graphFile; std::unique_ptr<unsigned char> result; struct ncGraphHandle_t* graphHandlePtr = nullptr; NCSFifo input; NCSFifo output; unsigned int outputFIFOsize = 0; struct ncTensorDescriptor_t inputDescriptor; struct ncTensorDescriptor_t outputDescriptor; }; int main(int argc, char** argv) { #ifndef GFLAGS_GFLAGS_H_ namespace gflags = google; #endif gflags::SetUsageMessage("Perform NCS classification.\n" "Usage:\n" " test_ncs [FLAGS]\n"); gflags::ParseCommandLineFlags(&argc, &argv, true); std::vector<std::string> ncs_names; nn_hardware_platform machine; platform_info pi; machine.get_platform_info(pi); int exit_code = 0; try { if(argc < 2 ) { throw std::string("ERROR: Wrong syntax. Valid syntax:\n \ test-ncs-v2 <names of images to process> [options]\n \ \n \ options: \n \ profile -- switch on printing profiling information\n \ graph -- path name to graph to be used\n \ synset -- path name to a file describing categories\n \ "); } int i = 0; std::vector<std::string> imagesFileNames(argc - 1); for(auto& vec : imagesFileNames) { vec = std::string(argv[++i]); } // Set verbose mode for a work with NCS device NCSDevice ncs; NCSGraph ncsg(ncs.getHandle(),FLAGS_graph); std::vector<std::unique_ptr<unsigned char[]> > tensors(argc-1); unsigned int inputLength; for(size_t i=0; i<tensors.size(); ++i) { prepareTensor(tensors[i], imagesFileNames[i], &inputLength); } auto t1 = __rdtsc(); for(int i=0; i< FLAGS_num_reps; ++i) { ncsg.infer(tensors,inputLength); } auto t2 = __rdtsc(); if(FLAGS_profile == true) { ncsg.printProfiling(); std::cout << "---> NCS execution including memory transfer takes " << ((t2 - t1)/(float)FLAGS_num_reps) << " RDTSC cycles time[ms]: " << (t2 -t1)*1000.0f/((float)pi.tsc*FLAGS_num_reps) << std::endl; } } catch (std::string err) { std::cout << err << std::endl; exit_code = -1; } return exit_code; }
34.722936
224
0.639717
jczaja
323fc673a2d0a679d848fda08f177a948892f9c9
931
cpp
C++
Array/Missing_Element_XOR.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
19
2018-12-02T05:59:44.000Z
2021-07-24T14:11:54.000Z
Array/Missing_Element_XOR.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
null
null
null
Array/Missing_Element_XOR.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
13
2019-04-25T16:20:00.000Z
2021-09-06T19:50:04.000Z
//Find the missing element from a list of 1..n-1 elements /*Elements are distinct and range from 1 to n.Input has a list of n-1 numbers and the missing number needs to be found*/ #include<iostream> using namespace std; //finds the missing element /*XOR all the 1..n elements and then XOR the given elements and XOR both the results since if c is the missing element then when we XOR the results then we get 0^c that is c As the common elements being getting XOR operation becomes 0* Array contains n-1 elements . But it contains distinct elements out of n elements */ int FindMissing(int arr[],int size) { int res1=0; for (int i = 0; i < size; ++i) { res1=arr[i]^res1; } int res2=0; //here n=size+1 for (int i = 1; i < size+2; ++i) { res2=res2^i; } return res1^res2; } int main() { int arr[]={1, 2, 4, 6, 3, 7, 8}; int size=sizeof(arr)/sizeof(int); cout<<"Missing element:"<<FindMissing(arr,size); return 0; }
25.861111
100
0.691729
susantabiswas
3241e5e393e06a7b6384f50fb34f6beaba275250
498
cpp
C++
Leetcode/N-Repeated Element in Size 2N Array/solution.cpp
arushmangal/Hack-CP-DSA
91f5aabc4741c1c518f35065273c7fcfced67061
[ "MIT" ]
205
2021-09-30T15:41:05.000Z
2022-03-27T18:34:56.000Z
Leetcode/N-Repeated Element in Size 2N Array/solution.cpp
arushmangal/Hack-CP-DSA
91f5aabc4741c1c518f35065273c7fcfced67061
[ "MIT" ]
566
2021-09-30T15:27:27.000Z
2021-10-16T21:21:02.000Z
Leetcode/N-Repeated Element in Size 2N Array/solution.cpp
arushmangal/Hack-CP-DSA
91f5aabc4741c1c518f35065273c7fcfced67061
[ "MIT" ]
399
2021-09-29T05:40:46.000Z
2022-03-27T18:34:58.000Z
class Solution { public: int repeatedNTimes(vector<int>& nums) { int n=nums.size(), ans=0; //defining variables sort(nums.begin(),nums.end()); // sorted vector for easily finding repeated number for (int i=0;i<n;i++){ if(nums[i]==nums[i+1]) {ans=nums[i]; break;} // breaking loop when conditon fulfilled } return ans; // returning ans } };
38.307692
101
0.471888
arushmangal
32449484973d63f27bcea3d9a61a8f2dac9832e1
3,151
cpp
C++
oopAsgn4/prob4.cpp
debargham14/Object-Oriented-Programming-Assignment
25d7c87803e957c16188cac563eb238654c5a87b
[ "MIT" ]
null
null
null
oopAsgn4/prob4.cpp
debargham14/Object-Oriented-Programming-Assignment
25d7c87803e957c16188cac563eb238654c5a87b
[ "MIT" ]
null
null
null
oopAsgn4/prob4.cpp
debargham14/Object-Oriented-Programming-Assignment
25d7c87803e957c16188cac563eb238654c5a87b
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; //designing the class array to perform the relevant operations class ARRAY { int *p; int size; public: //constrcutor to initialise the array ARRAY(int s = 0) { if (s == 0) { size = s; p = NULL; } else { size = s; p = new int[size]; for (int i = 0; i < size; i++) p[i] = 0; } } //defining the copy constructor ARRAY(const ARRAY& a) { size = a.size; if (size == 0) p = NULL; else { p = new int[size]; //creating a new array for (int i = 0; i < size; i++) p[i] = a.p[i]; } } //copy constructor to copy an array ARRAY(int *arr, int n) { size = n; if (size == 0) p = NULL; else { p = new int[size]; //creating a new array for (int i = 0; i < n; i++) p[i] = arr[i]; } } //overloading the >> to take the array as input friend void operator >> (istream &is, ARRAY& a) { for (int i = 0; i < a.size; i++) is >> a.p[i]; } //operator << overloaded to display the array friend ostream& operator << (ostream &os, ARRAY a) { for (int i = 0; i < a.size; i++) os << a.p[i] << " "; return os; } //operator overloading + to add the two array void operator = (ARRAY &b) { size = b.size; if (size == 0) { p = NULL; } else { p = new int[size]; for (int i = 0; i < b.size; i++) p[i] = b.p[i]; } } //operator overloading + to add the contents of two array friend ARRAY operator + (ARRAY &a, ARRAY &b) { ARRAY c(a.size > b.size ? a.size : b.size); if (a.size < b.size) { for (int i = 0; i < a.size; i++) c.p[i] = a.p[i] + b.p[i]; for (int i = a.size; i < b.size; i++) c.p[i] = b.p[i]; } else { for (int i = 0; i < b.size; i++) c.p[i] = a.p[i] + b.p[i]; for (int i = b.size; i < a.size; i++) c.p[i] = b.p[i]; } return c; } //operator overloading for [] so that array can be accessed as a[idx] for array being an object of the array class int& operator [] (int idx) { return p[idx]; } //overloadinf the operator * to support multiplication of an array with integers friend ARRAY operator * (ARRAY &a, int x) { ARRAY c(a.size); for (int i = 0; i < a.size; i++) c.p[i] = a.p[i] * x; return c; } friend ARRAY operator * (int x, ARRAY &a) { ARRAY c(a.size); for (int i = 0; i < a.size; i++) c.p[i] = a.p[i] * x; return c; } //destructor is used to set the memory free ~ARRAY() { delete[] p; } }; //driver code to implment the above class int main() { int n; cout << "Enter the number of elements of the array :- "; cin >> n; ARRAY a(n), b; //initialising the array using copy constructor cout << "Enter the array :- "; cin >> a; //taking input of an array cout << "Your Entered Array is :- "; cout << a << "\n"; //displaying the array b = a; //copying an array bytewise cout << "A check to the copy function :- "; cout << b << "\n"; ARRAY c = a + b; //adding the contents of two array c[0] = 1000; // check the [] operator in the ARRAY cout << "A check to the add function :- "; cout << c << "\n"; ARRAY d = 5 * c; //multiplying the content of array with constant variable cout << "A check to the multiply function :- "; cout << d << "\n"; return 0; }
24.811024
115
0.567122
debargham14
324937a3bfe24ec8894252fd46c84182623aee9d
5,295
cc
C++
src/sim/clinkedlist.cc
eniac/parallel-inet-omnet
810ed40aecac89efbd0b6a05ee10f44a09417178
[ "Xnet", "X11" ]
15
2021-08-20T08:10:01.000Z
2022-03-24T21:24:50.000Z
src/sim/clinkedlist.cc
eniac/parallel-inet-omnet
810ed40aecac89efbd0b6a05ee10f44a09417178
[ "Xnet", "X11" ]
1
2022-03-30T09:03:39.000Z
2022-03-30T09:03:39.000Z
src/sim/clinkedlist.cc
eniac/parallel-inet-omnet
810ed40aecac89efbd0b6a05ee10f44a09417178
[ "Xnet", "X11" ]
3
2021-08-20T08:10:34.000Z
2021-12-02T06:15:02.000Z
//========================================================================= // CLLIST.CC - part of // // OMNeT++/OMNEST // Discrete System Simulation in C++ // // Member functions of // cLinkedList : linked list of void* pointers // // Author: Andras Varga // //========================================================================= /*--------------------------------------------------------------* Copyright (C) 1992-2008 Andras Varga Copyright (C) 2006-2008 OpenSim Ltd. This file is distributed WITHOUT ANY WARRANTY. See the file `license' for details on this and other legal matters. *--------------------------------------------------------------*/ #include <stdio.h> // sprintf #include <string.h> // memcmp, memcpy, memset #include <sstream> #include "globals.h" #include "clinkedlist.h" #include "cexception.h" #ifdef WITH_PARSIM #include "ccommbuffer.h" #endif #ifdef _MSC_VER # pragma warning(disable:4996) // deprecation warning #endif #ifdef __GNUC__ # pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif NAMESPACE_BEGIN Register_Class(cLinkedList); cLinkedList::cLinkedList(const cLinkedList& llist) : cOwnedObject(llist) { headp = tailp = NULL; n = 0; copy(llist); } cLinkedList::cLinkedList(const char *name) : cOwnedObject(name) { headp=tailp=NULL; n=0; delfunc = NULL; dupfunc = NULL; itemsize = 0; } cLinkedList::~cLinkedList() { clear(); } std::string cLinkedList::info() const { if (n==0) return std::string("empty"); std::stringstream out; out << "length=" << n; return out.str(); } void cLinkedList::parsimPack(cCommBuffer *buffer) { throw cRuntimeError(this,"parsimPack() not supported -- don't know how to pack an item"); } void cLinkedList::parsimUnpack(cCommBuffer *buffer) { throw cRuntimeError(this,"parsimUnpack() not supported"); } void cLinkedList::config( VoidDelFunc _delfunc, VoidDupFunc _dupfunc, size_t _itemsize) { delfunc = _delfunc; dupfunc = _dupfunc; itemsize = _itemsize; } void cLinkedList::clear() { Elem *tmp; while (headp) { tmp = headp->next; if (dupfunc || itemsize>0) // we're expected to do memory mgmt { if (delfunc) delfunc(headp->item); else delete (char *)headp->item; // delete void* is no longer legal :-( } delete headp; headp=tmp; } tailp = NULL; n = 0; } void cLinkedList::copy(const cLinkedList& llist) { for (cLinkedList::Iterator iter(llist, 0); !iter.end(); iter--) { void *item; if (dupfunc) item = dupfunc(iter()); else if (itemsize>0) memcpy(item=new char[itemsize],iter(),itemsize); else item=iter(); insert( item ); } } cLinkedList& cLinkedList::operator=(const cLinkedList& llist) { if (this==&llist) return *this; clear(); cOwnedObject::operator=(llist); copy(llist); return *this; } //== STRUCTURE OF THE LIST: //== 'headp' and 'tailp' point to the ends of the list (NULL if it is empty). //== The list is double-linked, but 'headp->prev' and 'tailp->next' are NULL. cLinkedList::Elem *cLinkedList::find_llelem(void *item) const { Elem *p = headp; while( p && p->item!=item ) p = p->next; return p; } void cLinkedList::insbefore_llelem(Elem *p, void *item) { Elem *e = new Elem; e->item = item; e->prev = p->prev; e->next = p; p->prev = e; if (e->prev) e->prev->next = e; else headp = e; n++; } void cLinkedList::insafter_llelem(Elem *p, void *item) { Elem *e = new Elem; e->item = item; e->next = p->next; e->prev = p; p->next = e; if (e->next) e->next->prev = e; else tailp = e; n++; } void *cLinkedList::remove_llelem(Elem *p) { if( p->prev ) p->prev->next = p->next; else headp = p->next; if( p->next ) p->next->prev = p->prev; else tailp = p->prev; void *retitem = p->item; delete p; n--; return retitem; } void cLinkedList::insert(void *item) { Elem *p = headp; if (p) insbefore_llelem(p,item); else if (tailp) insafter_llelem(tailp,item); else { // insert as the only item Elem *e = new Elem; e->item = item; headp = tailp = e; e->prev = e->next = NULL; n++; } } void cLinkedList::insertBefore(void *where, void *item) { Elem *p = find_llelem(where); if (!p) throw cRuntimeError(this,"insertBefore(w,o): item w not in list"); insbefore_llelem(p,item); } void cLinkedList::insertAfter(void *where, void *item) { Elem *p = find_llelem(where); if (!p) throw cRuntimeError(this,"insertAfter(w,o): item w not in list"); insafter_llelem(p,item); } void *cLinkedList::remove(void *item) { if(!item) return NULL; Elem *p = find_llelem(item); if (!p) return NULL; return remove_llelem( p ); } void *cLinkedList::pop() { if (!tailp) throw cRuntimeError(this,"pop(): list empty"); return remove_llelem( tailp ); } NAMESPACE_END
21.011905
93
0.555052
eniac
324ca8e0ff33f298810188e2095817491c1da158
1,284
cpp
C++
src_tests/arm_neon/test_vset_lane.cpp
AlexYaruki/prism
ba4b20f570d03bf896ad3634e5fbf4a6bf5b02f5
[ "Apache-2.0" ]
8
2019-06-14T09:25:46.000Z
2021-11-11T10:34:28.000Z
src_tests/arm_neon/test_vset_lane.cpp
AlexYaruki/prism
ba4b20f570d03bf896ad3634e5fbf4a6bf5b02f5
[ "Apache-2.0" ]
1
2019-10-06T02:11:17.000Z
2021-11-11T11:17:16.000Z
src_tests/arm_neon/test_vset_lane.cpp
AlexYaruki/prism
ba4b20f570d03bf896ad3634e5fbf4a6bf5b02f5
[ "Apache-2.0" ]
2
2017-06-10T01:01:00.000Z
2021-07-13T00:48:30.000Z
#include <iris/iris.h> #include <cassert> using namespace iris; template<typename T> void test_vset_lane(T(*func)(typename T::elementType,T,int32_t)) { T data; for (size_t i = 0; i < T::length; i++) { data = func((typename T::elementType)i,data,i); } for (size_t i = 0; i < T::length; i++) { assert(data.template at<typename T::elementType>(i) == (typename T::elementType)i); } } int main() { test_vset_lane<int8x8_t>(vset_lane_s8); test_vset_lane<int16x4_t>(vset_lane_s16); test_vset_lane<int32x2_t>(vset_lane_s32); test_vset_lane<int64x1_t>(vset_lane_s64); test_vset_lane<uint8x8_t>(vset_lane_u8); test_vset_lane<uint16x4_t>(vset_lane_u16); test_vset_lane<uint32x2_t>(vset_lane_u32); test_vset_lane<uint64x1_t>(vset_lane_u64); test_vset_lane<float32x2_t>(vset_lane_f32); test_vset_lane<int8x16_t>(vsetq_lane_s8); test_vset_lane<int16x8_t>(vsetq_lane_s16); test_vset_lane<int32x4_t>(vsetq_lane_s32); test_vset_lane<int64x2_t>(vsetq_lane_s64); test_vset_lane<uint8x16_t>(vsetq_lane_u8); test_vset_lane<uint16x8_t>(vsetq_lane_u16); test_vset_lane<uint32x4_t>(vsetq_lane_u32); test_vset_lane<uint64x2_t>(vsetq_lane_u64); test_vset_lane<float32x4_t>(vsetq_lane_f32); }
29.181818
91
0.721963
AlexYaruki
324f495f006ff8d9558d2af4b1301fc9f4fb6fb4
2,103
hpp
C++
src/centurion/detail/array_utils.hpp
Creeperface01/centurion
e3b674c11849367a18c2d976ce94071108e1590d
[ "MIT" ]
14
2020-05-17T21:38:03.000Z
2020-11-21T00:16:25.000Z
src/centurion/detail/array_utils.hpp
Creeperface01/centurion
e3b674c11849367a18c2d976ce94071108e1590d
[ "MIT" ]
70
2020-04-26T17:08:52.000Z
2020-11-21T17:34:03.000Z
src/centurion/detail/array_utils.hpp
Creeperface01/centurion
e3b674c11849367a18c2d976ce94071108e1590d
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2019-2022 Albin Johansson * * 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 CENTURION_DETAIL_ARRAY_UTILS_HPP_ #define CENTURION_DETAIL_ARRAY_UTILS_HPP_ #include <array> // array, to_array #include <cstddef> // size_t #include "../common.hpp" #include "../features.hpp" /// \cond FALSE namespace cen::detail { template <typename T, std::size_t Size> constexpr void assign(const std::array<T, Size>& array, bounded_array_ref<T, Size> out) { std::size_t index = 0; for (auto&& value : array) { out[index] = value; ++index; } } template <typename T, std::size_t Size> [[nodiscard]] constexpr auto to_array(bounded_array_ref<const T, Size> data) -> std::array<T, Size> { #if CENTURION_HAS_FEATURE_TO_ARRAY return std::to_array(data); #else std::array<T, Size> array; // NOLINT for (std::size_t i = 0; i < Size; ++i) { array[i] = data[i]; } return array; #endif // CENTURION_HAS_FEATURE_TO_ARRAY } } // namespace cen::detail /// \endcond #endif // CENTURION_DETAIL_ARRAY_UTILS_HPP_
30.042857
87
0.724679
Creeperface01
325336bb7b753fc226e0c24b300a62e7040c8ce4
12,210
cpp
C++
Core/src/Core/GameObjectManager.cpp
Hukunaa/Condamnation
04efeb6ee62013a8399695a8294d9bd9e9f0f41d
[ "MIT" ]
null
null
null
Core/src/Core/GameObjectManager.cpp
Hukunaa/Condamnation
04efeb6ee62013a8399695a8294d9bd9e9f0f41d
[ "MIT" ]
null
null
null
Core/src/Core/GameObjectManager.cpp
Hukunaa/Condamnation
04efeb6ee62013a8399695a8294d9bd9e9f0f41d
[ "MIT" ]
null
null
null
#include <tinyxml2.h> #include <Core/GameObjectManager.h> #include <Components/LightComp.h> #include <Components/TransformComp.h> #include <Components/MaterialComp.h> #include <Components/BoxColliderComp.h> #include <Components/RigidBodyComp.h> #include <Components/ModelComp.h> #include <Rendering/Managers/InputManager.h> #include <unordered_map> #include "Components/PlayerComp.h" static int phase = 0; Core::GameObjectManager::GameObjectManager(MeshManager& p_modelManager, Rendering::Managers::CameraManager& p_camera) { LoadScene(p_modelManager, "DOOM"); Find("Player")->AddComponent<Components::PlayerComp>(p_camera.GetCamera(), 100); } void Core::GameObjectManager::Update(const float& p_deltaTime, Rendering::Managers::CameraManager& p_camera) { phase += 1; float frequency = 0.02f; if (Rendering::Managers::InputManager::GetInstance()->GetKeyDown(Rendering::Managers::InputManager::KeyCode::Mouse1)) { if(Find("Link") != nullptr ) Find("Link")->GetComponent<Components::RigidBodyComp>()->AddForce({ p_camera.GetCamera()->GetFront().x * 100, p_camera.GetCamera()->GetFront().y * 100 , p_camera.GetCamera()->GetFront().z * 100 }); if(Find("Link2") != nullptr) Find("Link2")->GetComponent<Components::RigidBodyComp>()->AddForce({ p_camera.GetCamera()->GetFront().x * 100, p_camera.GetCamera()->GetFront().y * 100 , p_camera.GetCamera()->GetFront().z * 100 }); } Find("Torch1")->GetComponent<Components::LightComp>()->GetLight()->SetColor(sin(frequency * phase), sin(frequency * phase + 2), sin(frequency * phase + 4)); Find("Torch2")->GetComponent<Components::LightComp>()->GetLight()->SetColor(sin(frequency * phase + 2), sin(frequency * phase + 4), sin(frequency * phase + 6)); Find("Torch3")->GetComponent<Components::LightComp>()->GetLight()->SetColor(sin(frequency * phase + 4), sin(frequency * phase + 6), sin(frequency * phase + 8)); Find("Torch4")->GetComponent<Components::LightComp>()->GetLight()->SetColor(sin(frequency * phase + 6), sin(frequency * phase + 8), sin(frequency * phase + 10)); if (Find("Player") != nullptr) Find("Player")->GetComponent<Components::PlayerComp>()->ProcessKeyInput(*this, p_deltaTime); m_angle += 0.005f * p_deltaTime; if (Find("BlueLight") != nullptr) { Find("BlueLight")->GetComponent<Components::TransformComp>()->GetTransform()->Rotate(glm::vec3(0, 1, 0) * p_deltaTime); Find("BlueLight")->GetComponent<Components::TransformComp>()->GetTransform()->Translate(glm::vec3(0.1, 0, 0) * p_deltaTime); Find("BlueLight")->GetComponent<Components::TransformComp>()->Update(); } if (Find("OrangeLight") != nullptr) Find("OrangeLight")->GetComponent<Components::TransformComp>()->Update(); for (auto& gameObject : m_gameObjects) { if (gameObject->GetComponent<Components::BoxColliderComp>() != nullptr) { gameObject->GetComponent<Components::BoxColliderComp>()->GetCollider()->GetPosVec() = gameObject->GetComponent<Components::TransformComp>()->GetTransform()->GetPosition(); gameObject->GetComponent<Components::BoxColliderComp>()->GetCollider()->GetMat() = gameObject->GetComponent<Components::TransformComp>()->GetTransform()->GetTransMat(); gameObject->GetComponent<Components::BoxColliderComp>()->GetCollider()->UpdateBoundingBox(); } } } int Core::GameObjectManager::SaveScene(const MeshManager& p_modelManager, const std::string& p_sceneName) { using namespace tinyxml2; std::unordered_map<std::string, int> compTypes { {"BoxColliderComp", 0}, {"LightComp", 1}, {"MaterialComp", 2}, {"ModelComp", 3}, {"TransformComp", 4}, {"RigidBodyComp", 5} }; #ifndef XMLCheckResult #define XMLCheckResult(a_eResult) if (a_eResult != XML_SUCCESS) { std::cerr << "Error while parsing XML [LOADER] Error Type: " << a_eResult << '\n'; return a_eResult; } #endif XMLDocument xmlDoc; XMLNode* root = xmlDoc.NewElement("scene"); xmlDoc.InsertFirstChild(root); XMLElement* GOList = xmlDoc.NewElement("GameObjectList"); GOList->SetAttribute("count", static_cast<unsigned int>(m_gameObjects.size())); root->InsertFirstChild(GOList); for (auto gameObject : m_gameObjects) { XMLElement* GOelement = xmlDoc.NewElement("GameObject"); GOelement->SetAttribute("name", gameObject->GetName().c_str()); if (gameObject->GetComponent<Components::ModelComp>() != nullptr) { GOelement->SetAttribute("mesh", FindInstanceIteratorInVector(gameObject->GetComponent<Components::ModelComp>()->GetModel()->GetMesh(), p_modelManager.GetMeshes())); GOelement->SetAttribute("shader", FindInstanceIteratorInVector(gameObject->GetComponent<Components::ModelComp>()->GetModel()->GetShader(), p_modelManager.GetShaders())); } GOelement->SetAttribute("tag", gameObject->GetTag().c_str()); XMLElement* ComponentList = xmlDoc.NewElement("ComponentList"); ComponentList->SetAttribute("count", gameObject->GetComponentCount()); for (const auto& component : gameObject->GetComponents()) { XMLElement* CompElement = xmlDoc.NewElement("Component"); std::string rawClassName = typeid(*component).name(); size_t offset = rawClassName.find_last_of(':'); std::string realName = rawClassName.substr(offset + 1); CompElement->SetAttribute("type", realName.c_str()); component->Serialize(CompElement, xmlDoc); ComponentList->InsertEndChild(CompElement); } GOelement->InsertFirstChild(ComponentList); GOList->InsertEndChild(GOelement); } XMLError eResult = xmlDoc.SaveFile((p_sceneName + ".xml").c_str()); XMLCheckResult(eResult); return eResult; } int Core::GameObjectManager::LoadScene(const MeshManager& p_modelManager, const std::string& p_sceneName) { using namespace tinyxml2; std::unordered_map<std::string, int> compTypes { {"BoxColliderComp", 0}, {"LightComp", 1}, {"MaterialComp", 2}, {"ModelComp", 3}, {"TransformComp", 4}, {"RigidBodyComp", 5} }; #ifndef XMLCheckResult #define XMLCheckResult(a_eResult) if (a_eResult != XML_SUCCESS) { std::cerr << "Error while parsing XML [LOADER] Error Type: " << a_eResult << '\n'; return a_eResult; } #endif XMLDocument xmlDoc; XMLError eResult = xmlDoc.LoadFile((p_sceneName + ".xml").c_str()); XMLCheckResult(eResult); XMLNode* root = xmlDoc.FirstChild(); if (root == nullptr) return XML_ERROR_FILE_READ_ERROR; XMLElement* GOList = root->FirstChildElement("GameObjectList"); if (GOList == nullptr) return XML_ERROR_PARSING_ELEMENT; XMLElement* GOelement = GOList->FirstChildElement("GameObject"); while (GOelement != nullptr) { const char* newGoName = nullptr; const char* tag = nullptr; int meshId{0}, shaderId{0}; bool empty{ true }; newGoName = GOelement->Attribute("name"); if (newGoName == nullptr) return XML_ERROR_PARSING_ATTRIBUTE; eResult = GOelement->QueryIntAttribute("mesh", &meshId); if (eResult == XML_SUCCESS) empty = false; eResult = GOelement->QueryIntAttribute("shader", &shaderId); if (eResult == XML_SUCCESS) empty = false; tag = GOelement->Attribute("tag"); std::shared_ptr<GameObject> newGo{}; if (!empty) newGo = std::make_shared<GameObject>(p_modelManager.GetMesh(meshId), p_modelManager.GetShader(shaderId), newGoName); else if (empty) newGo = std::make_shared<GameObject>(newGoName); newGo->SetTag(tag); XMLElement* ComponentList = GOelement->FirstChildElement("ComponentList"); if (GOelement == nullptr) return XML_ERROR_PARSING_ELEMENT; XMLElement* CompElement = ComponentList->FirstChildElement("Component"); while (CompElement != nullptr) { const char* attribText = nullptr; attribText = CompElement->Attribute("type"); if (attribText == nullptr) return XML_ERROR_PARSING_ATTRIBUTE; std::string newCompType{attribText}; std::unordered_map<std::string, int>::const_iterator got = compTypes.find(newCompType); // this line will be triggered by the playerComp, we are not handling it // for the moment, and we shouldn't pay much attention to it. It is not an error. if (got == compTypes.end()) std::cout << "component not found\n"; else { switch (got->second) { case 0: //boxColliderComp if (newGo->GetComponent<Components::BoxColliderComp>() == nullptr) newGo->AddComponent<Components::BoxColliderComp>(); newGo->GetComponent<Components::BoxColliderComp>()->Deserialize(CompElement); break; case 1: //LightComp if (newGo->GetComponent<Components::LightComp>() == nullptr) newGo->AddComponent<Components::LightComp>(); newGo->GetComponent<Components::LightComp>()->Deserialize(CompElement); break; case 2: //materialComp if (newGo->GetComponent<Components::MaterialComp>() == nullptr) newGo->AddComponent<Components::MaterialComp>(); newGo->GetComponent<Components::MaterialComp>()->Deserialize(CompElement); break; case 3: //modelComp if (newGo->GetComponent<Components::ModelComp>() == nullptr) newGo->AddComponent<Components::ModelComp>(); break; case 4: //TransformComp if (newGo->GetComponent<Components::TransformComp>() == nullptr) newGo->AddComponent<Components::TransformComp>(); newGo->GetComponent<Components::TransformComp>()->Deserialize(CompElement); break; case 5: //TransformComp if (newGo->GetComponent<Components::RigidBodyComp>() == nullptr) newGo->AddComponent<Components::RigidBodyComp>(this); newGo->GetComponent<Components::RigidBodyComp>()->Deserialize(CompElement); break; default: std::cerr << "ERROR : something went wrong when trying to load components on the XML loader\n Your component type is non-existent."; break; } } CompElement = CompElement->NextSiblingElement("Component"); } GOelement = GOelement->NextSiblingElement("GameObject"); m_gameObjects.push_back(newGo); } return EXIT_SUCCESS; } std::shared_ptr<Core::GameObject> Core::GameObjectManager::Find(const std::string& p_name) { for (auto& m_gameObject : m_gameObjects) { if (m_gameObject->GetName() == p_name) return m_gameObject; } std::cout << "Could not find object " << p_name << "in Game Manager\n"; return {}; } std::vector<std::shared_ptr<Core::GameObject>>& Core::GameObjectManager::GetGameObjects() noexcept { return m_gameObjects; } void Core::GameObjectManager::RemoveGameObject(std::shared_ptr<GameObject> p_gameObject) { for (int i = 0; i < m_gameObjects.size(); ++i) { if (*m_gameObjects[i] == *p_gameObject) { if (m_gameObjects[i]->GetComponent<Components::TransformComp>()->GetChild() != nullptr) { Core::GameObject& tmp = m_gameObjects[i]->GetComponent<Components::TransformComp>()->GetChild()->GetGameObject(); m_gameObjects[i]->GetComponent<Components::TransformComp>()->GetChild()->SetParent(); RemoveGameObject(std::make_shared<GameObject>(tmp)); return; } m_gameObjects.erase(m_gameObjects.begin() + i); return; } } }
40.29703
206
0.634808
Hukunaa
325a6205d1eb661c7f53405784f58e121e4906c4
93,995
cpp
C++
unittest/biunique_map_test.cpp
suomesta/ken3
edac96489d5b638dc4eff25454fcca1307ca86e9
[ "MIT" ]
null
null
null
unittest/biunique_map_test.cpp
suomesta/ken3
edac96489d5b638dc4eff25454fcca1307ca86e9
[ "MIT" ]
null
null
null
unittest/biunique_map_test.cpp
suomesta/ken3
edac96489d5b638dc4eff25454fcca1307ca86e9
[ "MIT" ]
null
null
null
/** * @file unittest/biunique_map_test.cpp * @brief Testing ken3::biunique_map using lest. * @author toda * @date 2016-11-24 * @version 0.1.0 * @remark the target is C++11 or more */ #include <iterator> #include <tuple> #include <vector> #include "ken3/biunique_map.hpp" #include "unittest/lest.hpp" namespace { // type definitions template <ken3::biunique_map_type TYPE, ken3::biunique_map_policy POLICY> using tmp_map = ken3::biunique_map<char, int, TYPE, POLICY>; using map_list = std::tuple< tmp_map<ken3::biunique_map_type::ordered_no_default, ken3::biunique_map_policy::silence>, tmp_map<ken3::biunique_map_type::ordered_front_default, ken3::biunique_map_policy::silence>, tmp_map<ken3::biunique_map_type::ordered_back_default, ken3::biunique_map_policy::silence>, tmp_map<ken3::biunique_map_type::unordered_no_default, ken3::biunique_map_policy::silence>, tmp_map<ken3::biunique_map_type::ordered_no_default, ken3::biunique_map_policy::throwing>, tmp_map<ken3::biunique_map_type::ordered_front_default, ken3::biunique_map_policy::throwing>, tmp_map<ken3::biunique_map_type::ordered_back_default, ken3::biunique_map_policy::throwing>, tmp_map<ken3::biunique_map_type::unordered_no_default, ken3::biunique_map_policy::throwing> >; ///////////////////////////////////////////////////////////////////////////// /** * @brief check std::map items are same or not. * @tparam MAP: std::map. * @param[in] lhs: left hand side. * @param[in] rhs: right hand side. * @return true: same, false: not same. */ template <typename MAP> bool same_map(const MAP& lhs, const typename MAP::map_type& rhs) { if (lhs.size() != rhs.size()) { return false; } for (auto i = lhs.cbegin(); i != lhs.cend(); ++i) { auto j = rhs.find(i->first); if (j == rhs.end()) { return false; } else if (i->second != j->second) { return false; } } return true; } ///////////////////////////////////////////////////////////////////////////// } // namespace { const lest::test specification[] = { CASE("minimum functions") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(10 == bm.f2s('A')); EXPECT(11 == bm.f2s('B')); EXPECT('A' == bm.s2f(10)); EXPECT('B' == bm.s2f(11)); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(10 == bm.f2s('A')); EXPECT(11 == bm.f2s('B')); EXPECT('A' == bm.s2f(10)); EXPECT('B' == bm.s2f(11)); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(10 == bm.f2s('A')); EXPECT(11 == bm.f2s('B')); EXPECT('A' == bm.s2f(10)); EXPECT('B' == bm.s2f(11)); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(10 == bm.f2s('A')); EXPECT(11 == bm.f2s('B')); EXPECT('A' == bm.s2f(10)); EXPECT('B' == bm.s2f(11)); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(10 == bm.f2s('A')); EXPECT(11 == bm.f2s('B')); EXPECT('A' == bm.s2f(10)); EXPECT('B' == bm.s2f(11)); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(10 == bm.f2s('A')); EXPECT(11 == bm.f2s('B')); EXPECT('A' == bm.s2f(10)); EXPECT('B' == bm.s2f(11)); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(10 == bm.f2s('A')); EXPECT(11 == bm.f2s('B')); EXPECT('A' == bm.s2f(10)); EXPECT('B' == bm.s2f(11)); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(10 == bm.f2s('A')); EXPECT(11 == bm.f2s('B')); EXPECT('A' == bm.s2f(10)); EXPECT('B' == bm.s2f(11)); } }, CASE("iterator constructor with non-duplex data") { { using my_map = std::tuple_element<0, map_list>::type; std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}}; my_map bm1(v.begin(), v.end()); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); typename my_map::map_type m{{'A', 10}, {'B', 11}}; my_map bm2(m.begin(), m.end()); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<1, map_list>::type; std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}}; my_map bm1(v.begin(), v.end()); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); typename my_map::map_type m{{'A', 10}, {'B', 11}}; my_map bm2(m.begin(), m.end()); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<2, map_list>::type; std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}}; my_map bm1(v.begin(), v.end()); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); typename my_map::map_type m{{'A', 10}, {'B', 11}}; my_map bm2(m.begin(), m.end()); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<3, map_list>::type; std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}}; my_map bm1(v.begin(), v.end()); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); typename my_map::map_type m{{'A', 10}, {'B', 11}}; my_map bm2(m.begin(), m.end()); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<4, map_list>::type; std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}}; my_map bm1(v.begin(), v.end()); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); typename my_map::map_type m{{'A', 10}, {'B', 11}}; my_map bm2(m.begin(), m.end()); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<5, map_list>::type; std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}}; my_map bm1(v.begin(), v.end()); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); typename my_map::map_type m{{'A', 10}, {'B', 11}}; my_map bm2(m.begin(), m.end()); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<6, map_list>::type; std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}}; my_map bm1(v.begin(), v.end()); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); typename my_map::map_type m{{'A', 10}, {'B', 11}}; my_map bm2(m.begin(), m.end()); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<7, map_list>::type; std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}}; my_map bm1(v.begin(), v.end()); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); typename my_map::map_type m{{'A', 10}, {'B', 11}}; my_map bm2(m.begin(), m.end()); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } }, CASE("iterator constructor with duplex data") { { using my_map = std::tuple_element<0, map_list>::type; std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}, {'A', 12}}; my_map bm1(v.begin(), v.end()); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); std::map<typename my_map::key_type, typename my_map::mapped_type> m{{'A', 10}, {'B', 11}, {'C', 10}}; // need ordered map to get stable result my_map bm2(m.begin(), m.end()); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<1, map_list>::type; std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}, {'A', 12}}; my_map bm1(v.begin(), v.end()); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); std::map<typename my_map::key_type, typename my_map::mapped_type> m{{'A', 10}, {'B', 11}, {'C', 10}}; // need ordered map to get stable result my_map bm2(m.begin(), m.end()); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<2, map_list>::type; std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}, {'A', 12}}; my_map bm1(v.begin(), v.end()); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); std::map<typename my_map::key_type, typename my_map::mapped_type> m{{'A', 10}, {'B', 11}, {'C', 10}}; // need ordered map to get stable result my_map bm2(m.begin(), m.end()); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<3, map_list>::type; std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}, {'A', 12}}; my_map bm1(v.begin(), v.end()); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); std::map<typename my_map::key_type, typename my_map::mapped_type> m{{'A', 10}, {'B', 11}, {'C', 10}}; // need ordered map to get stable result my_map bm2(m.begin(), m.end()); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<4, map_list>::type; std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}, {'A', 12}}; EXPECT_THROWS_AS((my_map(v.begin(), v.end())), std::invalid_argument); std::map<typename my_map::key_type, typename my_map::mapped_type> m{{'A', 10}, {'B', 11}, {'C', 10}}; // need ordered map to get stable result EXPECT_THROWS_AS((my_map(m.begin(), m.end())), std::invalid_argument); } { using my_map = std::tuple_element<5, map_list>::type; std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}, {'A', 12}}; EXPECT_THROWS_AS((my_map(v.begin(), v.end())), std::invalid_argument); std::map<typename my_map::key_type, typename my_map::mapped_type> m{{'A', 10}, {'B', 11}, {'C', 10}}; // need ordered map to get stable result EXPECT_THROWS_AS((my_map(m.begin(), m.end())), std::invalid_argument); } { using my_map = std::tuple_element<6, map_list>::type; std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}, {'A', 12}}; EXPECT_THROWS_AS((my_map(v.begin(), v.end())), std::invalid_argument); std::map<typename my_map::key_type, typename my_map::mapped_type> m{{'A', 10}, {'B', 11}, {'C', 10}}; // need ordered map to get stable result EXPECT_THROWS_AS((my_map(m.begin(), m.end())), std::invalid_argument); } { using my_map = std::tuple_element<7, map_list>::type; std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}, {'A', 12}}; EXPECT_THROWS_AS((my_map(v.begin(), v.end())), std::invalid_argument); std::map<typename my_map::key_type, typename my_map::mapped_type> m{{'A', 10}, {'B', 11}, {'C', 10}}; // need ordered map to get stable result EXPECT_THROWS_AS((my_map(m.begin(), m.end())), std::invalid_argument); } }, CASE("initializer_list constructor with non-duplex data") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } }, CASE("initializer_list constructor with duplex data") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}, {'A', 12}}; EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); my_map bm2{{'A', 10}, {'B', 11}, {'C', 10}}; EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}, {'A', 12}}; EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); my_map bm2{{'A', 10}, {'B', 11}, {'C', 10}}; EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}, {'A', 12}}; EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); my_map bm2{{'A', 10}, {'B', 11}, {'C', 10}}; EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}, {'A', 12}}; EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); my_map bm2{{'A', 10}, {'B', 11}, {'C', 10}}; EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<4, map_list>::type; EXPECT_THROWS_AS((my_map{{'A', 10}, {'B', 11}, {'A', 12}}), std::invalid_argument); EXPECT_THROWS_AS((my_map{{'A', 10}, {'B', 11}, {'C', 10}}), std::invalid_argument); } { using my_map = std::tuple_element<5, map_list>::type; EXPECT_THROWS_AS((my_map{{'A', 10}, {'B', 11}, {'A', 12}}), std::invalid_argument); EXPECT_THROWS_AS((my_map{{'A', 10}, {'B', 11}, {'C', 10}}), std::invalid_argument); } { using my_map = std::tuple_element<6, map_list>::type; EXPECT_THROWS_AS((my_map{{'A', 10}, {'B', 11}, {'A', 12}}), std::invalid_argument); EXPECT_THROWS_AS((my_map{{'A', 10}, {'B', 11}, {'C', 10}}), std::invalid_argument); } { using my_map = std::tuple_element<7, map_list>::type; EXPECT_THROWS_AS((my_map{{'A', 10}, {'B', 11}, {'A', 12}}), std::invalid_argument); EXPECT_THROWS_AS((my_map{{'A', 10}, {'B', 11}, {'C', 10}}), std::invalid_argument); } }, CASE("initializer_list assignment with non-duplex data") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm; bm = {{'A', 10}, {'B', 11}}; EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm; bm = {{'A', 10}, {'B', 11}}; EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm; bm = {{'A', 10}, {'B', 11}}; EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm; bm = {{'A', 10}, {'B', 11}}; EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm; bm = {{'A', 10}, {'B', 11}}; EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm; bm = {{'A', 10}, {'B', 11}}; EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm; bm = {{'A', 10}, {'B', 11}}; EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm; bm = {{'A', 10}, {'B', 11}}; EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } }, CASE("initializer_list assignment with duplex data") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm1; bm1 = {{'A', 10}, {'B', 11}, {'A', 12}}; EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); my_map bm2; bm2 = {{'A', 10}, {'B', 11}, {'C', 10}}; EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm1; bm1 = {{'A', 10}, {'B', 11}, {'A', 12}}; EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); my_map bm2; bm2 = {{'A', 10}, {'B', 11}, {'C', 10}}; EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm1; bm1 = {{'A', 10}, {'B', 11}, {'A', 12}}; EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); my_map bm2; bm2 = {{'A', 10}, {'B', 11}, {'C', 10}}; EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm1; bm1 = {{'A', 10}, {'B', 11}, {'A', 12}}; EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); my_map bm2; bm2 = {{'A', 10}, {'B', 11}, {'C', 10}}; EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm1; EXPECT_THROWS_AS((bm1 = {{'A', 10}, {'B', 11}, {'A', 12}}), std::invalid_argument); my_map bm2; EXPECT_THROWS_AS((bm2 = {{'A', 10}, {'B', 11}, {'C', 10}}), std::invalid_argument); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm1; EXPECT_THROWS_AS((bm1 = {{'A', 10}, {'B', 11}, {'A', 12}}), std::invalid_argument); my_map bm2; EXPECT_THROWS_AS((bm2 = {{'A', 10}, {'B', 11}, {'C', 10}}), std::invalid_argument); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm1; EXPECT_THROWS_AS((bm1 = {{'A', 10}, {'B', 11}, {'A', 12}}), std::invalid_argument); my_map bm2; EXPECT_THROWS_AS((bm2 = {{'A', 10}, {'B', 11}, {'C', 10}}), std::invalid_argument); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm1; EXPECT_THROWS_AS((bm1 = {{'A', 10}, {'B', 11}, {'A', 12}}), std::invalid_argument); my_map bm2; EXPECT_THROWS_AS((bm2 = {{'A', 10}, {'B', 11}, {'C', 10}}), std::invalid_argument); } }, CASE("operator==") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'A', 10}, {'B', 11}}; my_map bm3{bm1}; my_map bm4{{'A', 11}, {'B', 10}}; my_map bm5; EXPECT(bm1 == bm2); EXPECT(bm1 == bm3); EXPECT(not (bm1 == bm4)); EXPECT(not (bm1 == bm5)); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'A', 10}, {'B', 11}}; my_map bm3{bm1}; my_map bm4{{'A', 11}, {'B', 10}}; my_map bm5; EXPECT(bm1 == bm2); EXPECT(bm1 == bm3); EXPECT(not (bm1 == bm4)); EXPECT(not (bm1 == bm5)); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'A', 10}, {'B', 11}}; my_map bm3{bm1}; my_map bm4{{'A', 11}, {'B', 10}}; my_map bm5; EXPECT(bm1 == bm2); EXPECT(bm1 == bm3); EXPECT(not (bm1 == bm4)); EXPECT(not (bm1 == bm5)); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'A', 10}, {'B', 11}}; my_map bm3{bm1}; my_map bm4{{'A', 11}, {'B', 10}}; my_map bm5; EXPECT(bm1 == bm2); EXPECT(bm1 == bm3); EXPECT(not (bm1 == bm4)); EXPECT(not (bm1 == bm5)); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'A', 10}, {'B', 11}}; my_map bm3{bm1}; my_map bm4{{'A', 11}, {'B', 10}}; my_map bm5; EXPECT(bm1 == bm2); EXPECT(bm1 == bm3); EXPECT(not (bm1 == bm4)); EXPECT(not (bm1 == bm5)); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'A', 10}, {'B', 11}}; my_map bm3{bm1}; my_map bm4{{'A', 11}, {'B', 10}}; my_map bm5; EXPECT(bm1 == bm2); EXPECT(bm1 == bm3); EXPECT(not (bm1 == bm4)); EXPECT(not (bm1 == bm5)); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'A', 10}, {'B', 11}}; my_map bm3{bm1}; my_map bm4{{'A', 11}, {'B', 10}}; my_map bm5; EXPECT(bm1 == bm2); EXPECT(bm1 == bm3); EXPECT(not (bm1 == bm4)); EXPECT(not (bm1 == bm5)); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'A', 10}, {'B', 11}}; my_map bm3{bm1}; my_map bm4{{'A', 11}, {'B', 10}}; my_map bm5; EXPECT(bm1 == bm2); EXPECT(bm1 == bm3); EXPECT(not (bm1 == bm4)); EXPECT(not (bm1 == bm5)); } }, CASE("operator!=") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'A', 10}, {'B', 11}}; my_map bm3{bm1}; my_map bm4{{'A', 11}, {'B', 10}}; my_map bm5; EXPECT(not (bm1 != bm2)); EXPECT(not (bm1 != bm3)); EXPECT(bm1 != bm4); EXPECT(bm1 != bm5); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'A', 10}, {'B', 11}}; my_map bm3{bm1}; my_map bm4{{'A', 11}, {'B', 10}}; my_map bm5; EXPECT(not (bm1 != bm2)); EXPECT(not (bm1 != bm3)); EXPECT(bm1 != bm4); EXPECT(bm1 != bm5); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'A', 10}, {'B', 11}}; my_map bm3{bm1}; my_map bm4{{'A', 11}, {'B', 10}}; my_map bm5; EXPECT(not (bm1 != bm2)); EXPECT(not (bm1 != bm3)); EXPECT(bm1 != bm4); EXPECT(bm1 != bm5); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'A', 10}, {'B', 11}}; my_map bm3{bm1}; my_map bm4{{'A', 11}, {'B', 10}}; my_map bm5; EXPECT(not (bm1 != bm2)); EXPECT(not (bm1 != bm3)); EXPECT(bm1 != bm4); EXPECT(bm1 != bm5); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'A', 10}, {'B', 11}}; my_map bm3{bm1}; my_map bm4{{'A', 11}, {'B', 10}}; my_map bm5; EXPECT(not (bm1 != bm2)); EXPECT(not (bm1 != bm3)); EXPECT(bm1 != bm4); EXPECT(bm1 != bm5); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'A', 10}, {'B', 11}}; my_map bm3{bm1}; my_map bm4{{'A', 11}, {'B', 10}}; my_map bm5; EXPECT(not (bm1 != bm2)); EXPECT(not (bm1 != bm3)); EXPECT(bm1 != bm4); EXPECT(bm1 != bm5); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'A', 10}, {'B', 11}}; my_map bm3{bm1}; my_map bm4{{'A', 11}, {'B', 10}}; my_map bm5; EXPECT(not (bm1 != bm2)); EXPECT(not (bm1 != bm3)); EXPECT(bm1 != bm4); EXPECT(bm1 != bm5); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'A', 10}, {'B', 11}}; my_map bm3{bm1}; my_map bm4{{'A', 11}, {'B', 10}}; my_map bm5; EXPECT(not (bm1 != bm2)); EXPECT(not (bm1 != bm3)); EXPECT(bm1 != bm4); EXPECT(bm1 != bm5); } }, CASE("swap()") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm1, bm2; bm1.insert('A', 10); bm1.insert('B', 11); bm2.insert('C', 12); bm1.swap(bm2); EXPECT(same_map(bm1, {{'C', 12}})); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm1, bm2; bm1.insert('A', 10); bm1.insert('B', 11); bm2.insert('C', 12); bm1.swap(bm2); EXPECT(same_map(bm1, {{'C', 12}})); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm1, bm2; bm1.insert('A', 10); bm1.insert('B', 11); bm2.insert('C', 12); bm1.swap(bm2); EXPECT(same_map(bm1, {{'C', 12}})); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm1, bm2; bm1.insert('A', 10); bm1.insert('B', 11); bm2.insert('C', 12); bm1.swap(bm2); EXPECT(same_map(bm1, {{'C', 12}})); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm1, bm2; bm1.insert('A', 10); bm1.insert('B', 11); bm2.insert('C', 12); bm1.swap(bm2); EXPECT(same_map(bm1, {{'C', 12}})); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm1, bm2; bm1.insert('A', 10); bm1.insert('B', 11); bm2.insert('C', 12); bm1.swap(bm2); EXPECT(same_map(bm1, {{'C', 12}})); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm1, bm2; bm1.insert('A', 10); bm1.insert('B', 11); bm2.insert('C', 12); bm1.swap(bm2); EXPECT(same_map(bm1, {{'C', 12}})); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm1, bm2; bm1.insert('A', 10); bm1.insert('B', 11); bm2.insert('C', 12); bm1.swap(bm2); EXPECT(same_map(bm1, {{'C', 12}})); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}})); } }, CASE("size()") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm; EXPECT(0UL == bm.size()); bm.insert('A', 10); EXPECT(1UL == bm.size()); bm.insert('B', 11); EXPECT(2UL == bm.size()); bm.clear(); EXPECT(0UL == bm.size()); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm; EXPECT(0UL == bm.size()); bm.insert('A', 10); EXPECT(1UL == bm.size()); bm.insert('B', 11); EXPECT(2UL == bm.size()); bm.clear(); EXPECT(0UL == bm.size()); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm; EXPECT(0UL == bm.size()); bm.insert('A', 10); EXPECT(1UL == bm.size()); bm.insert('B', 11); EXPECT(2UL == bm.size()); bm.clear(); EXPECT(0UL == bm.size()); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm; EXPECT(0UL == bm.size()); bm.insert('A', 10); EXPECT(1UL == bm.size()); bm.insert('B', 11); EXPECT(2UL == bm.size()); bm.clear(); EXPECT(0UL == bm.size()); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm; EXPECT(0UL == bm.size()); bm.insert('A', 10); EXPECT(1UL == bm.size()); bm.insert('B', 11); EXPECT(2UL == bm.size()); bm.clear(); EXPECT(0UL == bm.size()); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm; EXPECT(0UL == bm.size()); bm.insert('A', 10); EXPECT(1UL == bm.size()); bm.insert('B', 11); EXPECT(2UL == bm.size()); bm.clear(); EXPECT(0UL == bm.size()); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm; EXPECT(0UL == bm.size()); bm.insert('A', 10); EXPECT(1UL == bm.size()); bm.insert('B', 11); EXPECT(2UL == bm.size()); bm.clear(); EXPECT(0UL == bm.size()); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm; EXPECT(0UL == bm.size()); bm.insert('A', 10); EXPECT(1UL == bm.size()); bm.insert('B', 11); EXPECT(2UL == bm.size()); bm.clear(); EXPECT(0UL == bm.size()); } }, CASE("empty()") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm; EXPECT(bm.empty()); bm.insert('A', 10); EXPECT(not bm.empty()); bm.insert('B', 11); EXPECT(not bm.empty()); bm.clear(); EXPECT(bm.empty()); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm; EXPECT(bm.empty()); bm.insert('A', 10); EXPECT(not bm.empty()); bm.insert('B', 11); EXPECT(not bm.empty()); bm.clear(); EXPECT(bm.empty()); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm; EXPECT(bm.empty()); bm.insert('A', 10); EXPECT(not bm.empty()); bm.insert('B', 11); EXPECT(not bm.empty()); bm.clear(); EXPECT(bm.empty()); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm; EXPECT(bm.empty()); bm.insert('A', 10); EXPECT(not bm.empty()); bm.insert('B', 11); EXPECT(not bm.empty()); bm.clear(); EXPECT(bm.empty()); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm; EXPECT(bm.empty()); bm.insert('A', 10); EXPECT(not bm.empty()); bm.insert('B', 11); EXPECT(not bm.empty()); bm.clear(); EXPECT(bm.empty()); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm; EXPECT(bm.empty()); bm.insert('A', 10); EXPECT(not bm.empty()); bm.insert('B', 11); EXPECT(not bm.empty()); bm.clear(); EXPECT(bm.empty()); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm; EXPECT(bm.empty()); bm.insert('A', 10); EXPECT(not bm.empty()); bm.insert('B', 11); EXPECT(not bm.empty()); bm.clear(); EXPECT(bm.empty()); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm; EXPECT(bm.empty()); bm.insert('A', 10); EXPECT(not bm.empty()); bm.insert('B', 11); EXPECT(not bm.empty()); bm.clear(); EXPECT(bm.empty()); } }, CASE("cbegin()") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); my_map::map_type m{{'A', 10}, {'B', 11}}; EXPECT(m.cbegin()->first == bm.cbegin()->first); EXPECT(m.cbegin()->second == bm.cbegin()->second); EXPECT(std::next(m.cbegin(), 1)->first == std::next(bm.cbegin(), 1)->first); EXPECT(std::next(m.cbegin(), 1)->second == std::next(bm.cbegin(), 1)->second); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); my_map::map_type m{{'A', 10}, {'B', 11}}; EXPECT(m.cbegin()->first == bm.cbegin()->first); EXPECT(m.cbegin()->second == bm.cbegin()->second); EXPECT(std::next(m.cbegin(), 1)->first == std::next(bm.cbegin(), 1)->first); EXPECT(std::next(m.cbegin(), 1)->second == std::next(bm.cbegin(), 1)->second); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); my_map::map_type m{{'A', 10}, {'B', 11}}; EXPECT(m.cbegin()->first == bm.cbegin()->first); EXPECT(m.cbegin()->second == bm.cbegin()->second); EXPECT(std::next(m.cbegin(), 1)->first == std::next(bm.cbegin(), 1)->first); EXPECT(std::next(m.cbegin(), 1)->second == std::next(bm.cbegin(), 1)->second); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); my_map::map_type m{{'A', 10}, {'B', 11}}; EXPECT(m.cbegin()->first == bm.cbegin()->first); EXPECT(m.cbegin()->second == bm.cbegin()->second); EXPECT(std::next(m.cbegin(), 1)->first == std::next(bm.cbegin(), 1)->first); EXPECT(std::next(m.cbegin(), 1)->second == std::next(bm.cbegin(), 1)->second); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); my_map::map_type m{{'A', 10}, {'B', 11}}; EXPECT(m.cbegin()->first == bm.cbegin()->first); EXPECT(m.cbegin()->second == bm.cbegin()->second); EXPECT(std::next(m.cbegin(), 1)->first == std::next(bm.cbegin(), 1)->first); EXPECT(std::next(m.cbegin(), 1)->second == std::next(bm.cbegin(), 1)->second); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); my_map::map_type m{{'A', 10}, {'B', 11}}; EXPECT(m.cbegin()->first == bm.cbegin()->first); EXPECT(m.cbegin()->second == bm.cbegin()->second); EXPECT(std::next(m.cbegin(), 1)->first == std::next(bm.cbegin(), 1)->first); EXPECT(std::next(m.cbegin(), 1)->second == std::next(bm.cbegin(), 1)->second); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); my_map::map_type m{{'A', 10}, {'B', 11}}; EXPECT(m.cbegin()->first == bm.cbegin()->first); EXPECT(m.cbegin()->second == bm.cbegin()->second); EXPECT(std::next(m.cbegin(), 1)->first == std::next(bm.cbegin(), 1)->first); EXPECT(std::next(m.cbegin(), 1)->second == std::next(bm.cbegin(), 1)->second); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); my_map::map_type m{{'A', 10}, {'B', 11}}; EXPECT(m.cbegin()->first == bm.cbegin()->first); EXPECT(m.cbegin()->second == bm.cbegin()->second); EXPECT(std::next(m.cbegin(), 1)->first == std::next(bm.cbegin(), 1)->first); EXPECT(std::next(m.cbegin(), 1)->second == std::next(bm.cbegin(), 1)->second); } }, CASE("cend()") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(std::next(bm.cbegin(), 2) == bm.cend()); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(std::next(bm.cbegin(), 2) == bm.cend()); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(std::next(bm.cbegin(), 2) == bm.cend()); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(std::next(bm.cbegin(), 2) == bm.cend()); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(std::next(bm.cbegin(), 2) == bm.cend()); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(std::next(bm.cbegin(), 2) == bm.cend()); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(std::next(bm.cbegin(), 2) == bm.cend()); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(std::next(bm.cbegin(), 2) == bm.cend()); } }, CASE("clear()") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(not bm.empty()); bm.clear(); EXPECT(bm.empty()); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(not bm.empty()); bm.clear(); EXPECT(bm.empty()); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(not bm.empty()); bm.clear(); EXPECT(bm.empty()); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(not bm.empty()); bm.clear(); EXPECT(bm.empty()); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(not bm.empty()); bm.clear(); EXPECT(bm.empty()); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(not bm.empty()); bm.clear(); EXPECT(bm.empty()); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(not bm.empty()); bm.clear(); EXPECT(bm.empty()); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm; bm.insert('A', 10); bm.insert('B', 11); EXPECT(not bm.empty()); bm.clear(); EXPECT(bm.empty()); } }, CASE("insert() with non-duplex biunique_map") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'C', 12}}; bm2.insert(bm1); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'C', 12}}; bm2.insert(bm1); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'C', 12}}; bm2.insert(bm1); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'C', 12}}; bm2.insert(bm1); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'C', 12}}; bm2.insert(bm1); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'C', 12}}; bm2.insert(bm1); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'C', 12}}; bm2.insert(bm1); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'C', 12}}; bm2.insert(bm1); EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}, {'C', 12}})); } }, CASE("insert() with duplex biunique_map") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'C', 12}, {'A', 10}}; my_map bm3{{'D', 13}, {'A', 14}}; my_map bm4{{'E', 14}, {'F', 11}}; bm1.insert(bm2); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}})); bm1.insert(bm3); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}})); bm1.insert(bm4); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}})); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'C', 12}, {'A', 10}}; my_map bm3{{'D', 13}, {'A', 14}}; my_map bm4{{'E', 14}, {'F', 11}}; bm1.insert(bm2); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}})); bm1.insert(bm3); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}})); bm1.insert(bm4); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}})); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'C', 12}, {'A', 10}}; my_map bm3{{'D', 13}, {'A', 14}}; my_map bm4{{'E', 14}, {'F', 11}}; bm1.insert(bm2); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}})); bm1.insert(bm3); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}})); bm1.insert(bm4); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}})); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'C', 12}, {'A', 10}}; my_map bm3{{'D', 13}, {'A', 14}}; my_map bm4{{'E', 14}, {'F', 11}}; bm1.insert(bm2); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}})); bm1.insert(bm3); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}})); bm1.insert(bm4); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}})); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'C', 12}, {'A', 10}}; my_map bm3{{'C', 12}, {'A', 13}}; my_map bm4{{'C', 12}, {'D', 10}}; EXPECT_THROWS_AS(bm1.insert(bm2), std::invalid_argument); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm1.insert(bm3), std::invalid_argument); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm1.insert(bm4), std::invalid_argument); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'C', 12}, {'A', 10}}; my_map bm3{{'C', 12}, {'A', 13}}; my_map bm4{{'C', 12}, {'D', 10}}; EXPECT_THROWS_AS(bm1.insert(bm2), std::invalid_argument); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm1.insert(bm3), std::invalid_argument); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm1.insert(bm4), std::invalid_argument); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'C', 12}, {'A', 10}}; my_map bm3{{'C', 12}, {'A', 13}}; my_map bm4{{'C', 12}, {'D', 10}}; EXPECT_THROWS_AS(bm1.insert(bm2), std::invalid_argument); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm1.insert(bm3), std::invalid_argument); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm1.insert(bm4), std::invalid_argument); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm1{{'A', 10}, {'B', 11}}; my_map bm2{{'C', 12}, {'A', 10}}; my_map bm3{{'C', 12}, {'A', 13}}; my_map bm4{{'C', 12}, {'D', 10}}; EXPECT_THROWS_AS(bm1.insert(bm2), std::invalid_argument); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm1.insert(bm3), std::invalid_argument); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm1.insert(bm4), std::invalid_argument); EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}})); } }, CASE("insert() with non-duplex initializer_list") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert({{'C', 12}}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert({{'C', 12}}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert({{'C', 12}}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert({{'C', 12}}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert({{'C', 12}}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert({{'C', 12}}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert({{'C', 12}}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert({{'C', 12}}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } }, CASE("insert() with duplex initializer_list") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert({{'C', 12}, {'A', 10}}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); bm.insert({{'D', 13}, {'A', 14}}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}})); bm.insert({{'E', 14}, {'F', 11}}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}})); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert({{'C', 12}, {'A', 10}}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); bm.insert({{'D', 13}, {'A', 14}}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}})); bm.insert({{'E', 14}, {'F', 11}}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}})); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert({{'C', 12}, {'A', 10}}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); bm.insert({{'D', 13}, {'A', 14}}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}})); bm.insert({{'E', 14}, {'F', 11}}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}})); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert({{'C', 12}, {'A', 10}}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); bm.insert({{'D', 13}, {'A', 14}}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}})); bm.insert({{'E', 14}, {'F', 11}}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}})); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT_THROWS_AS(bm.insert({{'A', 10}, {'C', 12}}), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm.insert({{'D', 13}, {'A', 14}}), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm.insert({{'E', 14}, {'F', 11}}), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT_THROWS_AS(bm.insert({{'A', 10}, {'C', 12}}), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm.insert({{'D', 13}, {'A', 14}}), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm.insert({{'E', 14}, {'F', 11}}), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT_THROWS_AS(bm.insert({{'A', 10}, {'C', 12}}), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm.insert({{'D', 13}, {'A', 14}}), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm.insert({{'E', 14}, {'F', 11}}), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT_THROWS_AS(bm.insert({{'A', 10}, {'C', 12}}), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm.insert({{'D', 13}, {'A', 14}}), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm.insert({{'E', 14}, {'F', 11}}), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } }, CASE("insert() with non-duplex iterator") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; const std::vector<my_map::value_type> v{{'C', 12}, {'D', 13}}; bm.insert(v.cbegin(), v.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}})); const my_map::map_type m{{'E', 14}, {'F', 15}}; bm.insert(m.cbegin(), m.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}, {'F', 15}})); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; const std::vector<my_map::value_type> v{{'C', 12}, {'D', 13}}; bm.insert(v.cbegin(), v.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}})); const my_map::map_type m{{'E', 14}, {'F', 15}}; bm.insert(m.cbegin(), m.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}, {'F', 15}})); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; const std::vector<my_map::value_type> v{{'C', 12}, {'D', 13}}; bm.insert(v.cbegin(), v.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}})); const my_map::map_type m{{'E', 14}, {'F', 15}}; bm.insert(m.cbegin(), m.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}, {'F', 15}})); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; const std::vector<my_map::value_type> v{{'C', 12}, {'D', 13}}; bm.insert(v.cbegin(), v.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}})); const my_map::map_type m{{'E', 14}, {'F', 15}}; bm.insert(m.cbegin(), m.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}, {'F', 15}})); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; const std::vector<my_map::value_type> v{{'C', 12}, {'D', 13}}; bm.insert(v.cbegin(), v.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}})); const my_map::map_type m{{'E', 14}, {'F', 15}}; bm.insert(m.cbegin(), m.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}, {'F', 15}})); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; const std::vector<my_map::value_type> v{{'C', 12}, {'D', 13}}; bm.insert(v.cbegin(), v.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}})); const my_map::map_type m{{'E', 14}, {'F', 15}}; bm.insert(m.cbegin(), m.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}, {'F', 15}})); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; const std::vector<my_map::value_type> v{{'C', 12}, {'D', 13}}; bm.insert(v.cbegin(), v.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}})); const my_map::map_type m{{'E', 14}, {'F', 15}}; bm.insert(m.cbegin(), m.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}, {'F', 15}})); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; const std::vector<my_map::value_type> v{{'C', 12}, {'D', 13}}; bm.insert(v.cbegin(), v.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}})); const my_map::map_type m{{'E', 14}, {'F', 15}}; bm.insert(m.cbegin(), m.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}, {'F', 15}})); } }, CASE("insert() with duplex iterator") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; const std::vector<my_map::value_type> v{{'C', 10}, {'D', 13}}; bm.insert(v.cbegin(), v.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'D', 13}})); const my_map::map_type m{{'E', 14}, {'F', 10}}; bm.insert(m.cbegin(), m.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'D', 13}, {'E', 14}})); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; const std::vector<my_map::value_type> v{{'C', 10}, {'D', 13}}; bm.insert(v.cbegin(), v.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'D', 13}})); const my_map::map_type m{{'E', 14}, {'F', 10}}; bm.insert(m.cbegin(), m.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'D', 13}, {'E', 14}})); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; const std::vector<my_map::value_type> v{{'C', 10}, {'D', 13}}; bm.insert(v.cbegin(), v.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'D', 13}})); const my_map::map_type m{{'E', 14}, {'F', 10}}; bm.insert(m.cbegin(), m.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'D', 13}, {'E', 14}})); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; const std::vector<my_map::value_type> v{{'C', 10}, {'D', 13}}; bm.insert(v.cbegin(), v.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'D', 13}})); const my_map::map_type m{{'E', 14}, {'F', 10}}; bm.insert(m.cbegin(), m.cend()); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'D', 13}, {'E', 14}})); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; const std::vector<my_map::value_type> v{{'C', 10}, {'D', 13}}; EXPECT_THROWS_AS(bm.insert(v.cbegin(), v.cend()), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); const my_map::map_type m{{'E', 14}, {'F', 10}}; EXPECT_THROWS_AS(bm.insert(m.cbegin(), m.cend()), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; const std::vector<my_map::value_type> v{{'C', 10}, {'D', 13}}; EXPECT_THROWS_AS(bm.insert(v.cbegin(), v.cend()), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); const my_map::map_type m{{'E', 14}, {'F', 10}}; EXPECT_THROWS_AS(bm.insert(m.cbegin(), m.cend()), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; const std::vector<my_map::value_type> v{{'C', 10}, {'D', 13}}; EXPECT_THROWS_AS(bm.insert(v.cbegin(), v.cend()), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); const my_map::map_type m{{'E', 14}, {'F', 10}}; EXPECT_THROWS_AS(bm.insert(m.cbegin(), m.cend()), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; const std::vector<my_map::value_type> v{{'C', 10}, {'D', 13}}; EXPECT_THROWS_AS(bm.insert(v.cbegin(), v.cend()), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); const my_map::map_type m{{'E', 14}, {'F', 10}}; EXPECT_THROWS_AS(bm.insert(m.cbegin(), m.cend()), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } }, CASE("insert() with non-duplex pair") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert(my_map::value_type{'C', 12}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert(my_map::value_type{'C', 12}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert(my_map::value_type{'C', 12}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert(my_map::value_type{'C', 12}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert(my_map::value_type{'C', 12}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert(my_map::value_type{'C', 12}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert(my_map::value_type{'C', 12}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert(my_map::value_type{'C', 12}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } }, CASE("insert() with duplex pair") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert(my_map::value_type{'A', 12}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); bm.insert(my_map::value_type{'C', 11}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert(my_map::value_type{'A', 12}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); bm.insert(my_map::value_type{'C', 11}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert(my_map::value_type{'A', 12}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); bm.insert(my_map::value_type{'C', 11}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert(my_map::value_type{'A', 12}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); bm.insert(my_map::value_type{'C', 11}); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT_THROWS_AS(bm.insert(my_map::value_type{'A', 12}), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm.insert(my_map::value_type{'C', 11}), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT_THROWS_AS(bm.insert(my_map::value_type{'A', 12}), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm.insert(my_map::value_type{'C', 11}), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT_THROWS_AS(bm.insert(my_map::value_type{'A', 12}), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm.insert(my_map::value_type{'C', 11}), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT_THROWS_AS(bm.insert(my_map::value_type{'A', 12}), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm.insert(my_map::value_type{'C', 11}), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } }, CASE("insert() with non-duplex f and s") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert('C', 12); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert('C', 12); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert('C', 12); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert('C', 12); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert('C', 12); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert('C', 12); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert('C', 12); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert('C', 12); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}})); } }, CASE("insert() with duplex f and s") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert('A', 12); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); bm.insert('C', 11); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert('A', 12); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); bm.insert('C', 11); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert('A', 12); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); bm.insert('C', 11); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; bm.insert('A', 12); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); bm.insert('C', 11); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT_THROWS_AS(bm.insert('A', 12), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm.insert('C', 11), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT_THROWS_AS(bm.insert('A', 12), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm.insert('C', 11), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT_THROWS_AS(bm.insert('A', 12), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm.insert('C', 11), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT_THROWS_AS(bm.insert('A', 12), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); EXPECT_THROWS_AS(bm.insert('C', 11), std::invalid_argument); EXPECT(same_map(bm, {{'A', 10}, {'B', 11}})); } }, CASE("has_f()") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_f('A')); EXPECT(bm.has_f('B')); EXPECT(not bm.has_f('C')); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_f('A')); EXPECT(bm.has_f('B')); EXPECT(not bm.has_f('C')); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_f('A')); EXPECT(bm.has_f('B')); EXPECT(not bm.has_f('C')); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_f('A')); EXPECT(bm.has_f('B')); EXPECT(not bm.has_f('C')); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_f('A')); EXPECT(bm.has_f('B')); EXPECT(not bm.has_f('C')); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_f('A')); EXPECT(bm.has_f('B')); EXPECT(not bm.has_f('C')); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_f('A')); EXPECT(bm.has_f('B')); EXPECT(not bm.has_f('C')); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_f('A')); EXPECT(bm.has_f('B')); EXPECT(not bm.has_f('C')); } }, CASE("has_s()") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_s(10)); EXPECT(bm.has_s(11)); EXPECT(not bm.has_s(12)); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_s(10)); EXPECT(bm.has_s(11)); EXPECT(not bm.has_s(12)); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_s(10)); EXPECT(bm.has_s(11)); EXPECT(not bm.has_s(12)); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_s(10)); EXPECT(bm.has_s(11)); EXPECT(not bm.has_s(12)); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_s(10)); EXPECT(bm.has_s(11)); EXPECT(not bm.has_s(12)); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_s(10)); EXPECT(bm.has_s(11)); EXPECT(not bm.has_s(12)); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_s(10)); EXPECT(bm.has_s(11)); EXPECT(not bm.has_s(12)); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_s(10)); EXPECT(bm.has_s(11)); EXPECT(not bm.has_s(12)); } }, CASE("erase_by_f()") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_f('A')); bm.erase_by_f('A'); EXPECT(not bm.has_f('A')); EXPECT(1UL == bm.size()); bm.erase_by_f('C'); EXPECT(1UL == bm.size()); EXPECT(bm.has_f('B')); bm.erase_by_f('B'); EXPECT(not bm.has_f('B')); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_f('A')); bm.erase_by_f('A'); EXPECT(not bm.has_f('A')); EXPECT(1UL == bm.size()); bm.erase_by_f('C'); EXPECT(1UL == bm.size()); EXPECT(bm.has_f('B')); bm.erase_by_f('B'); EXPECT(not bm.has_f('B')); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_f('A')); bm.erase_by_f('A'); EXPECT(not bm.has_f('A')); EXPECT(1UL == bm.size()); bm.erase_by_f('C'); EXPECT(1UL == bm.size()); EXPECT(bm.has_f('B')); bm.erase_by_f('B'); EXPECT(not bm.has_f('B')); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_f('A')); bm.erase_by_f('A'); EXPECT(not bm.has_f('A')); EXPECT(1UL == bm.size()); bm.erase_by_f('C'); EXPECT(1UL == bm.size()); EXPECT(bm.has_f('B')); bm.erase_by_f('B'); EXPECT(not bm.has_f('B')); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_f('A')); bm.erase_by_f('A'); EXPECT(not bm.has_f('A')); EXPECT(1UL == bm.size()); bm.erase_by_f('C'); EXPECT(1UL == bm.size()); EXPECT(bm.has_f('B')); bm.erase_by_f('B'); EXPECT(not bm.has_f('B')); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_f('A')); bm.erase_by_f('A'); EXPECT(not bm.has_f('A')); EXPECT(1UL == bm.size()); bm.erase_by_f('C'); EXPECT(1UL == bm.size()); EXPECT(bm.has_f('B')); bm.erase_by_f('B'); EXPECT(not bm.has_f('B')); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_f('A')); bm.erase_by_f('A'); EXPECT(not bm.has_f('A')); EXPECT(1UL == bm.size()); bm.erase_by_f('C'); EXPECT(1UL == bm.size()); EXPECT(bm.has_f('B')); bm.erase_by_f('B'); EXPECT(not bm.has_f('B')); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_f('A')); bm.erase_by_f('A'); EXPECT(not bm.has_f('A')); EXPECT(1UL == bm.size()); bm.erase_by_f('C'); EXPECT(1UL == bm.size()); EXPECT(bm.has_f('B')); bm.erase_by_f('B'); EXPECT(not bm.has_f('B')); } }, CASE("erase_by_s()") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_s(10)); bm.erase_by_s(10); EXPECT(not bm.has_s(10)); EXPECT(1UL == bm.size()); bm.erase_by_s(12); EXPECT(1UL == bm.size()); EXPECT(bm.has_s(11)); bm.erase_by_s(11); EXPECT(not bm.has_s(11)); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_s(10)); bm.erase_by_s(10); EXPECT(not bm.has_s(10)); EXPECT(1UL == bm.size()); bm.erase_by_s(12); EXPECT(1UL == bm.size()); EXPECT(bm.has_s(11)); bm.erase_by_s(11); EXPECT(not bm.has_s(11)); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_s(10)); bm.erase_by_s(10); EXPECT(not bm.has_s(10)); EXPECT(1UL == bm.size()); bm.erase_by_s(12); EXPECT(1UL == bm.size()); EXPECT(bm.has_s(11)); bm.erase_by_s(11); EXPECT(not bm.has_s(11)); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_s(10)); bm.erase_by_s(10); EXPECT(not bm.has_s(10)); EXPECT(1UL == bm.size()); bm.erase_by_s(12); EXPECT(1UL == bm.size()); EXPECT(bm.has_s(11)); bm.erase_by_s(11); EXPECT(not bm.has_s(11)); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_s(10)); bm.erase_by_s(10); EXPECT(not bm.has_s(10)); EXPECT(1UL == bm.size()); bm.erase_by_s(12); EXPECT(1UL == bm.size()); EXPECT(bm.has_s(11)); bm.erase_by_s(11); EXPECT(not bm.has_s(11)); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_s(10)); bm.erase_by_s(10); EXPECT(not bm.has_s(10)); EXPECT(1UL == bm.size()); bm.erase_by_s(12); EXPECT(1UL == bm.size()); EXPECT(bm.has_s(11)); bm.erase_by_s(11); EXPECT(not bm.has_s(11)); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_s(10)); bm.erase_by_s(10); EXPECT(not bm.has_s(10)); EXPECT(1UL == bm.size()); bm.erase_by_s(12); EXPECT(1UL == bm.size()); EXPECT(bm.has_s(11)); bm.erase_by_s(11); EXPECT(not bm.has_s(11)); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(bm.has_s(10)); bm.erase_by_s(10); EXPECT(not bm.has_s(10)); EXPECT(1UL == bm.size()); bm.erase_by_s(12); EXPECT(1UL == bm.size()); EXPECT(bm.has_s(11)); bm.erase_by_s(11); EXPECT(not bm.has_s(11)); } }, CASE("f2s()") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(10 == bm.f2s('A')); EXPECT(11 == bm.f2s('B')); EXPECT_THROWS_AS(bm.f2s('C'), std::out_of_range); bm.clear(); EXPECT_THROWS_AS(bm.f2s('A'), std::out_of_range); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(10 == bm.f2s('A')); EXPECT(11 == bm.f2s('B')); EXPECT(10 == bm.f2s('C')); bm.clear(); EXPECT_THROWS_AS(bm.f2s('A'), std::out_of_range); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(10 == bm.f2s('A')); EXPECT(11 == bm.f2s('B')); EXPECT(11 == bm.f2s('C')); bm.clear(); EXPECT_THROWS_AS(bm.f2s('A'), std::out_of_range); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(10 == bm.f2s('A')); EXPECT(11 == bm.f2s('B')); EXPECT_THROWS_AS(bm.f2s('C'), std::out_of_range); bm.clear(); EXPECT_THROWS_AS(bm.f2s('A'), std::out_of_range); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(10 == bm.f2s('A')); EXPECT(11 == bm.f2s('B')); EXPECT_THROWS_AS(bm.f2s('C'), std::out_of_range); bm.clear(); EXPECT_THROWS_AS(bm.f2s('A'), std::out_of_range); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(10 == bm.f2s('A')); EXPECT(11 == bm.f2s('B')); EXPECT(10 == bm.f2s('C')); bm.clear(); EXPECT_THROWS_AS(bm.f2s('A'), std::out_of_range); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(10 == bm.f2s('A')); EXPECT(11 == bm.f2s('B')); EXPECT(11 == bm.f2s('C')); bm.clear(); EXPECT_THROWS_AS(bm.f2s('A'), std::out_of_range); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT(10 == bm.f2s('A')); EXPECT(11 == bm.f2s('B')); EXPECT_THROWS_AS(bm.f2s('C'), std::out_of_range); bm.clear(); EXPECT_THROWS_AS(bm.f2s('A'), std::out_of_range); } }, CASE("s2f()") { { using my_map = std::tuple_element<0, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT('A' == bm.s2f(10)); EXPECT('B' == bm.s2f(11)); EXPECT_THROWS_AS(bm.s2f(12), std::out_of_range); bm.clear(); EXPECT_THROWS_AS(bm.s2f(10), std::out_of_range); } { using my_map = std::tuple_element<1, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT('A' == bm.s2f(10)); EXPECT('B' == bm.s2f(11)); EXPECT('A' == bm.s2f(12)); bm.clear(); EXPECT_THROWS_AS(bm.s2f(10), std::out_of_range); } { using my_map = std::tuple_element<2, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT('A' == bm.s2f(10)); EXPECT('B' == bm.s2f(11)); EXPECT('B' == bm.s2f(12)); bm.clear(); EXPECT_THROWS_AS(bm.s2f(10), std::out_of_range); } { using my_map = std::tuple_element<3, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT('A' == bm.s2f(10)); EXPECT('B' == bm.s2f(11)); EXPECT_THROWS_AS(bm.s2f(12), std::out_of_range); bm.clear(); EXPECT_THROWS_AS(bm.s2f(10), std::out_of_range); } { using my_map = std::tuple_element<4, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT('A' == bm.s2f(10)); EXPECT('B' == bm.s2f(11)); EXPECT_THROWS_AS(bm.s2f(12), std::out_of_range); bm.clear(); EXPECT_THROWS_AS(bm.s2f(10), std::out_of_range); } { using my_map = std::tuple_element<5, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT('A' == bm.s2f(10)); EXPECT('B' == bm.s2f(11)); EXPECT('A' == bm.s2f(12)); bm.clear(); EXPECT_THROWS_AS(bm.s2f(10), std::out_of_range); } { using my_map = std::tuple_element<6, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT('A' == bm.s2f(10)); EXPECT('B' == bm.s2f(11)); EXPECT('B' == bm.s2f(12)); bm.clear(); EXPECT_THROWS_AS(bm.s2f(10), std::out_of_range); } { using my_map = std::tuple_element<7, map_list>::type; my_map bm{{'A', 10}, {'B', 11}}; EXPECT('A' == bm.s2f(10)); EXPECT('B' == bm.s2f(11)); EXPECT_THROWS_AS(bm.s2f(12), std::out_of_range); bm.clear(); EXPECT_THROWS_AS(bm.s2f(10), std::out_of_range); } }, }; int main(int argc, char* argv[]) { return lest::run(specification, argc, argv); } /////////////////////////////////////////////////////////////////////////////
35.323187
154
0.428342
suomesta
325d42fca1b6a7218a625bb898a7d0555984b104
34,340
cpp
C++
vlib/qlang/ast.cpp
syntheticgio/fda-hive
5e645c6a5b76b5a437635631819a1c934c7fd7fc
[ "Unlicense", "MIT" ]
null
null
null
vlib/qlang/ast.cpp
syntheticgio/fda-hive
5e645c6a5b76b5a437635631819a1c934c7fd7fc
[ "Unlicense", "MIT" ]
null
null
null
vlib/qlang/ast.cpp
syntheticgio/fda-hive
5e645c6a5b76b5a437635631819a1c934c7fd7fc
[ "Unlicense", "MIT" ]
null
null
null
/* * ::718604! * * Copyright(C) November 20, 2014 U.S. Food and Drug Administration * Authors: Dr. Vahan Simonyan (1), Dr. Raja Mazumder (2), et al * Affiliation: Food and Drug Administration (1), George Washington University (2) * * All rights Reserved. * * The MIT License (MIT) * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include <slib/std/string.hpp> #include <qlang/interpreter.hpp> #include <qlang/ast.hpp> #include <assert.h> using namespace slib; using namespace slib::qlang; using namespace slib::qlang::ast; // keep in sync with qlang::ast::Node::eType static const char *NodeNames[] = { "uninitialized syntax node", "null literal", "int literal", "real literal", "string literal", "list literal", "dic literal", "variant literal", "variable name", "junction expression", "'as' typecast", "'=' operation", "'++' operation", "'--' operation", "'+' operation", "'-' operation", "'*' operation", "'/' operation", "'%' operation", "'+=' operation", "'-=' operation", "'*=' operation", "'/=' operation", "'%=' operation", "unary '+' operation", "unary '-' operation", "'[]' expression", "'[:]' operation", "'==' operation", "'!=' operation", "'>' operation", "'<=' operation", "'<' operation", "'<=' operation", "'<=>' operation", "'has' operation", "'=~' operation", "'!~' operation", "'&&' operation", "'||' operation", "'!' operation", "'?:' ternary conditional", "property access", "function call", "format call", "method call", "$ call", "'if' statement", "'for' statement", "'while' statement", "statement block", "unbreakable block", "function declaration", "'return' statement", "'break' statement", "'continue' statement", NULL }; const char* Node::getTypeName() const { return NodeNames[(int)_type]; } void Node::print(sStr &s) const { if (_loc.print(s)) s.printf(" : "); s.printf("%s @ %p\n", getTypeName(), this); } enum checkCtxModeFlags { flag_POP_SCOPE = 1, flag_IGNORE_RETURN = 1 << 1, flag_IGNORE_BREAK_CONTINUE = 1 << 2, }; // returns -1 on error, 0 on break, 1 on normal static idx checkCtxMode(Node *node, Context &ctx, idx flags=0) { switch (ctx.getMode()) { case Context::MODE_NORMAL: break; case Context::MODE_RETURN: if (flags & flag_IGNORE_RETURN) return 1; if (flags & flag_POP_SCOPE) ctx.popScope(); return 0; case Context::MODE_BREAK: case Context::MODE_CONTINUE: if (flags & flag_IGNORE_BREAK_CONTINUE) return 1; if (!ctx.isScopeInLoop()) { ctx.setError(node->getLocation(), EVAL_SYNTAX_ERROR, "cannot break/continue: no enclosing loop scope"); return -1; } if (flags & flag_POP_SCOPE) ctx.popScope(); return 0; case Context::MODE_ERROR: return -1; } return 1; } #define CHECK_RUN(node, flags) \ do { \ if (!(node)->run(ctx)) \ return false; \ idx c = checkCtxMode(node, ctx, flags); \ if (c <= 0) \ return !c; \ } while(0) #define CHECK_EVAL(node, value, flags) \ do { \ if (!(node)->eval(value, ctx)) \ return false; \ idx c = checkCtxMode(node, ctx, flags); \ if (c <= 0) \ return !c; \ } while(0) bool Node::run(Context &ctx) const { sVariant dummy; return eval(dummy, ctx); } bool Node::eval(sVariant &result, Context &ctx) const { ctx.setError(getLocation(), EVAL_NOT_IMPLEMENTED, "Cannot evaluate %s", getTypeName()); return false; } Unary::~Unary() { delete _arg; } void Unary::print(sStr &s) const { Node::print(s); s.printf("\tArgument: %s @ %p\n", _arg ? _arg->getTypeName() : NULL, _arg); if (_arg) _arg->print(s); } Binary::~Binary() { delete _lhs; delete _rhs; } void Binary::print(sStr &s) const { Node::print(s); s.printf("\tArguments: %s @ %p; %s @ %p\n", _lhs ? _lhs->getTypeName() : NULL, _lhs, _rhs ? _rhs->getTypeName() : NULL, _rhs); if (_lhs) _lhs->print(s); if (_rhs) _rhs->print(s); } Nary::~Nary() { for (idx i=0; i<_elts.dim(); i++) delete _elts[i]; } void Nary::print(sStr &s) const { Node::print(s); s.printf("\tArguments (%" DEC "):", _elts.dim()); for (idx i=0; i<_elts.dim(); i++) { s.printf(" %s @ %p;", _elts[i]->getTypeName(), _elts[i]); } s.printf("\n"); for (idx i=0; i<_elts.dim(); i++) { _elts[i]->print(s); } } void Nary::addElement(Node *node) { _elts.vadd(1, node); } bool ScalarLiteral::eval(sVariant &result, Context &ctx) const { result = _val; return true; } void ScalarLiteral::print(sStr &s) const { if (_loc.print(s)) s.printf(" : "); s.printf("%s value ", getTypeName()); _val.print(s); s.printf(" @ %p\n", this); } IntLiteral::IntLiteral(idx i, idx line, idx col): ScalarLiteral(line, col) { this->_type = node_INT_LITERAL; this->_val.setInt(i); } RealLiteral::RealLiteral(real r, idx line, idx col): ScalarLiteral(line, col) { this->_type = node_REAL_LITERAL; this->_val.setReal(r); } StringLiteral::StringLiteral(const char *s, idx line, idx col): ScalarLiteral(line, col) { this->_type = node_STRING_LITERAL; this->_val.setString(s); } bool ListLiteral::eval(sVariant &result, Context &ctx) const { result.setList(); for (idx i=0; i<this->_elts.dim(); i++) { sVariant val; CHECK_EVAL(this->_elts[i], val, 0); result.push(val); } return true; } bool DicLiteral::eval(sVariant &result, Context &ctx) const { result.setDic(); for (idx i=0; i<this->_elts.dim(); i+=2) { sVariant key, val; CHECK_EVAL(this->_elts[i], key, 0); CHECK_EVAL(this->_elts[i+1], val, 0); result.setElt(key.asString(), val); } return true; } VariantLiteral::VariantLiteral(sVariant & val, idx line, idx col): ScalarLiteral(line, col) { this->_type = node_VARIANT_LITERAL; this->_val = val; } bool BoolCast::eval(sVariant &result, Context &ctx) const { sVariant val; CHECK_EVAL(this->_arg, val, 0); result.setInt(val.asBool()); return true; } bool IntCast::eval(sVariant &result, Context &ctx) const { sVariant val; CHECK_EVAL(this->_arg, val, 0); result.setInt(val.asInt()); return true; } bool UIntCast::eval(sVariant &result, Context &ctx) const { sVariant val; CHECK_EVAL(this->_arg, val, 0); result.setUInt(val.asUInt()); return true; } bool IntlistCast::eval(sVariant &result, Context &ctx) const { sVariant val, elt; CHECK_EVAL(this->_arg, val, 0); result.setList(); // cast lists per-element // cast string scalars as comma-, semicolon-, or whitespace-separated lists // cast non-string scalars as one-element lists if (val.isList()) { for (idx i=0; i<val.dim(); i++) { val.getElt(i, elt); if (!elt.isInt()) elt.setInt(elt.asInt()); result.push(elt); } } else if (val.isString()) { result.parseIntList(val.asString()); } else if (val.isInt()) { elt = val; result.push(val); } else { elt.setInt(val.asInt()); result.push(elt); } return true; } bool ObjlistCast::eval(sVariant &result, Context &ctx) const { sVariant val, elt; CHECK_EVAL(this->_arg, val, 0); result.setList(); // cast lists per-element // cast string scalars as comma-, semicolon-, or whitespace-separated lists // cast non-string scalars as one-element lists if (val.isList()) { for (idx i=0; i<val.dim(); i++) { val.getElt(i, elt); if (!elt.isHiveId()) elt.parseHiveId(elt.asString()); result.push(elt); } } else if (val.isString()) { result.parseHiveIdList(val.asString()); } else if (val.isHiveId()) { result.push(val); } else if (val.isNumeric()) { elt.setHiveId(0, val.asUInt(), 0); result.push(elt); } else { elt.setHiveId(0, 0, 0); result.push(elt); } ctx.declareObjlist(result); return true; } bool RealCast::eval(sVariant &result, Context &ctx) const { sVariant val; CHECK_EVAL(this->_arg, val, 0); result.setReal(val.asReal()); return true; } bool StringCast::eval(sVariant &result, Context &ctx) const { sVariant val; CHECK_EVAL(this->_arg, val, 0); result.setString(val.asString()); return true; } bool ObjCast::eval(sVariant &result, Context &ctx) const { sVariant val; CHECK_EVAL(this->_arg, val, 0); if (val.isHiveId()) { result = val; } else if (val.isNumeric()) { result.setHiveId(0, val.asUInt(), 0); } else if (val.isString()) { result.parseHiveId(val.asString()); } else { result.setHiveId(0, 0, 0); } return true; } bool DateTimeCast::eval(sVariant &result, Context &ctx) const { sVariant val; CHECK_EVAL(this->_arg, val, 0); result.setDateTime(val); return true; } bool DateCast::eval(sVariant &result, Context &ctx) const { sVariant val; CHECK_EVAL(this->_arg, val, 0); result.setDate(val); return true; } bool TimeCast::eval(sVariant &result, Context &ctx) const { sVariant val; CHECK_EVAL(this->_arg, val, 0); result.setTime(val); return true; } bool Variable::eval(sVariant &result, Context &ctx) const { if (!ctx.getVarValue(_var.ptr(), result)) { ctx.setError(getLocation(), EVAL_VARIABLE_ERROR, "undefined variable '%s'", _var.ptr()); return false; } return true; } void Variable::print(sStr &s) const { if (_loc.print(s)) s.printf(" : "); s.printf("%s \"%s\" @ %p\n", getTypeName(), _var.ptr(), this); } bool Assign::assign(Node *lhs, sVariant &val, Context &ctx) const { assert(lhs); eEvalStatus code; Property *prop_node = NULL; Node *topic_node = NULL; const char *name = NULL; // We can assign to variables, properties, or list subscripts switch (lhs->getType()) { case node_VARIABLE: name = dynamic_cast<Variable*>(lhs)->getName(); if (!ctx.setVarValue(name, val)) { ctx.setError(getLocation(), EVAL_READ_ONLY_ERROR, "assignment to %s failed", name); return false; } return true; case node_PROPERTY: prop_node = dynamic_cast<Property*>(lhs); // Is the property node applied to an object? topic_node = prop_node->getTopic(); if (topic_node) { sVariant topic_val; CHECK_EVAL(topic_node, topic_val, 0); code = ctx.evalSetProperty(topic_val, prop_node->getName(), val); } else { code = ctx.evalSetProperty(prop_node->getName(), val); } if (code != EVAL_SUCCESS) { ctx.setError(getLocation(), code, "assignment to a property failed"); return false; } return true; case node_OP_SUBSCRIPT: { Subscript *sub_node = dynamic_cast<Subscript*>(lhs); Node *list_node = sub_node->getLhs(); Node *index_node = sub_node->getRhs(); sVariant list_val, index_val; CHECK_EVAL(list_node, list_val, 0); CHECK_EVAL(index_node, index_val, 0); code = ctx.evalSetSubscript(list_val, index_val, val); if (code != EVAL_SUCCESS) { ctx.setError(getLocation(), code, "assignment to an element failed"); return false; } } return true; default: // fall through break; } ctx.setError(getLocation(), EVAL_NOT_IMPLEMENTED, "cannot assign to a %s", lhs->getTypeName()); return false; } bool Assign::eval(sVariant &result, Context &ctx) const { CHECK_EVAL(_rhs, result, 0); return assign(_lhs, result, ctx); } bool Precrement::eval(sVariant &result, Context &ctx) const { CHECK_EVAL(_lhs, result, 0); eEvalStatus code = _type == node_OP_INCREMENT ? ctx.evalIncrement(result) : ctx.evalDecrement(result); if (code != EVAL_SUCCESS) { ctx.setError(getLocation(), code, "%s failed", getTypeName()); return false; } return assign(_lhs, result, ctx); } bool Postcrement::eval(sVariant &result, Context &ctx) const { CHECK_EVAL(_lhs, result, 0); sVariant crement_val = result; eEvalStatus code = _type == node_OP_INCREMENT ? ctx.evalIncrement(crement_val) : ctx.evalDecrement(crement_val); if (code != EVAL_SUCCESS) { ctx.setError(getLocation(), code, "%s failed", getTypeName()); return false; } return assign(_lhs, crement_val, ctx); } Arithmetic::Arithmetic(Node *lhs, char op, Node *rhs, idx line, idx col) : Binary(lhs, rhs, line, col) { switch(op) { case '+': _type = node_OP_PLUS; break; case '-': _type = node_OP_MINUS; break; case '*': _type = node_OP_MULTIPLY; break; case '/': _type = node_OP_DIVIDE; break; case '%': _type = node_OP_REMAINDER; break; default: assert(0); break; } } bool Arithmetic::eval(sVariant &result, Context &ctx) const { sVariant lval, rval; eEvalStatus code = EVAL_OTHER_ERROR; CHECK_EVAL(_lhs, lval, 0); CHECK_EVAL(_rhs, rval, 0); switch(this->_type) { case node_OP_PLUS: case node_OP_PLUS_INPLACE: code = ctx.evalAdd(result, lval, rval); break; case node_OP_MINUS: case node_OP_MINUS_INPLACE: code = ctx.evalSubtract(result, lval, rval); break; case node_OP_MULTIPLY: case node_OP_MULTIPLY_INPLACE: code = ctx.evalMultiply(result, lval, rval); break; case node_OP_DIVIDE: case node_OP_DIVIDE_INPLACE: code = ctx.evalDivide(result, lval, rval); break; case node_OP_REMAINDER: case node_OP_REMAINDER_INPLACE: code = ctx.evalRemainder(result, lval, rval); break; default: assert(0); break; } if (code != EVAL_SUCCESS) { ctx.setError(getLocation(), code, "%s failed", getTypeName()); return false; } return true; } ArithmeticInplace::ArithmeticInplace(Node *lhs, char op, Node *rhs, idx line, idx col): Arithmetic(lhs, op, rhs, line, col), assigner(0, 0, line, col) { switch(op) { case '+': _type = node_OP_PLUS_INPLACE; break; case '-': _type = node_OP_MINUS_INPLACE; break; case '*': _type = node_OP_MULTIPLY_INPLACE; break; case '/': _type = node_OP_DIVIDE_INPLACE; break; case '%': _type = node_OP_REMAINDER_INPLACE; break; default: assert(0); break; } } bool ArithmeticInplace::eval(sVariant &result, Context &ctx) const { return Arithmetic::eval(result, ctx) && assigner.assign(_lhs, result, ctx); } UnaryPlusMinus::UnaryPlusMinus(char op, Node *node, idx line, idx col): Unary(node, line, col) { switch(op) { case '+': _type = node_OP_U_PLUS; break; case '-': _type = node_OP_U_MINUS; break; default: assert(0); break; } } bool UnaryPlusMinus::eval(sVariant &result, Context &ctx) const { sVariant val; CHECK_EVAL(_arg, val, 0); eEvalStatus code; if (this->_type == node_OP_U_PLUS) code = ctx.evalUnaryPlus(val); else code = ctx.evalUnaryMinus(val); if (code != EVAL_SUCCESS) { ctx.setError(getLocation(), code, "%s failed", getTypeName()); return false; } result = val; return true; } bool Subscript::eval(sVariant &result, Context &ctx) const { sVariant lval, index; CHECK_EVAL(_lhs, lval, 0); CHECK_EVAL(_rhs, index, 0); eEvalStatus code = ctx.evalGetSubscript(result, lval, index); if (code != EVAL_SUCCESS) { ctx.setError(getLocation(), code, "%s failed", getTypeName()); return false; } return true; } Slice::~Slice() { delete _lhs; delete _rhs1; delete _rhs2; } bool Slice::eval(sVariant &result, Context &ctx) const { sVariant lval, index1, index2; CHECK_EVAL(_lhs, lval, 0); CHECK_EVAL(_rhs1, index1, 0); CHECK_EVAL(_rhs2, index2, 0); eEvalStatus code = ctx.evalGetSlice(result, lval, index1, index2); if (code != EVAL_SUCCESS) { ctx.setError(getLocation(), code, "%s failed", getTypeName()); return false; } return true; } void Slice::print(sStr &s) const { Node::print(s); s.printf("\tArguments: %s @ %p [ %s @ %p : %s @ %p ]\n", _lhs->getTypeName(), _lhs, _rhs1->getTypeName(), _rhs1, _rhs2->getTypeName(), _rhs2); _lhs->print(s); _rhs1->print(s); _rhs2->print(s); } Equality::Equality(Node *lhs, char op, Node *rhs, idx line, idx col): Binary(lhs, rhs, line, col) { switch(op) { case '=': _type = node_OP_EQ; break; case '!': _type = node_OP_NE; break; default: assert(0); break; } } bool Equality::eval(sVariant &result, Context &ctx) const { sVariant lval, rval; Junction *junc_node = dynamic_cast<Junction*>(_rhs); CHECK_EVAL(_lhs, lval, 0); // for equality operation, rhs can be a junction if (junc_node) { // x == a|b means "x == a || x == b" // x != a|b means "x != a && x != b" for (idx i=0; i<junc_node->dim(); i++) { CHECK_EVAL(junc_node->getElement(i), rval, 0); if (ctx.evalEquality(lval, rval)) { result.setInt(_type == node_OP_EQ); return true; } } result.setInt(_type != node_OP_EQ); } else { CHECK_EVAL(_rhs, rval, 0); bool match = ctx.evalEquality(lval, rval); result.setInt(_type == node_OP_EQ ? match : !match); } return true; } Comparison::Comparison(Node *lhs, const char *op, Node *rhs, idx line, idx col): Binary(lhs, rhs, line, col) { switch(op[0]) { case '<': _type = op[1] ? op[2] ? node_OP_CMP : node_OP_LE : node_OP_LT; break; case '>': _type = op[1] ? node_OP_GE : node_OP_GT; break; default: assert(0); break; } } bool Comparison::eval(sVariant &result, Context &ctx) const { sVariant lval, rval; CHECK_EVAL(_lhs, lval, 0); CHECK_EVAL(_rhs, rval, 0); switch (_type) { case node_OP_LT: result.setInt(ctx.evalLess(lval, rval)); break; case node_OP_LE: result.setInt(ctx.evalLessOrEqual(lval, rval)); break; case node_OP_GT: result.setInt(ctx.evalGreater(lval, rval)); break; case node_OP_GE: result.setInt(ctx.evalGreaterOrEqual(lval, rval)); break; case node_OP_CMP: if (ctx.evalEquality(lval, rval)) result.setInt(0); else result.setInt(ctx.evalLess(lval, rval) ? -1 : 1 ); break; default: assert(0); break; } return true; } bool Has::eval(sVariant &result, Context &ctx) const { sVariant lval; sVec<sVariant> rvals; idx dim = 1; CHECK_EVAL(_lhs, lval, 0); Junction *junc_node = dynamic_cast<Junction*>(_rhs); // for has operation, rhs can be a junction if (junc_node) { dim = junc_node->dim(); rvals.resize(dim); for (idx i=0; i<dim; i++) CHECK_EVAL(junc_node->getElement(i), rvals[i], 0); } else { rvals.resize(1); CHECK_EVAL(_rhs, rvals[0], 0); } eEvalStatus code = ctx.evalHas(result, lval, rvals.ptr(), dim); if (code != EVAL_SUCCESS) { ctx.setError(getLocation(), code, "%s failed", getTypeName()); return false; } return true; } Match::Match(Node *lhs, char op, regex_t *re, const char * re_string, idx line, idx col): Unary(lhs, line, col), _pmatch(sMex::fExactSize) { memcpy(&_re, re, sizeof(regex_t)); _type = (op == '=') ? node_OP_MATCH : node_OP_NMATCH; if (re_string) { idx nmatch = 0; // estimate number of substitutions for (idx i=0; re_string[i]; i++) { if (re_string[i] == '(' && (i == 0 || re_string[i-1] != '\\')) { nmatch++; } } if (nmatch) { _pmatch.resize(nmatch + 1); } } } Match::~Match() { regfree(&_re); } bool Match::eval(sVariant &result, Context &ctx) const { sVariant val; CHECK_EVAL(_arg, val, 0); eEvalStatus code = _type == node_OP_MATCH ? ctx.evalMatch(result, val, &_re, _pmatch.dim(), _pmatch.ptr()) : ctx.evalNMatch(result, val, &_re); if (code != EVAL_SUCCESS) { ctx.setError(getLocation(), code, "%s failed", getTypeName()); return false; } return true; } bool BinaryLogic::eval(sVariant &result, Context &ctx) const { sVariant lval, rval; CHECK_EVAL(_lhs, lval, 0); // short-circuit semantics: don't evaluate rhs unless needed switch(this->_type) { case node_OP_AND: if (lval.asBool()) { CHECK_EVAL(_rhs, rval, 0); result.setInt(rval.asBool()); } else result.setInt(0); break; case node_OP_OR: if (lval.asBool()) result.setInt(1); else { CHECK_EVAL(_rhs, rval, 0); result.setInt(rval.asBool()); } break; default: assert(0); break; } return true; } bool Not::eval(sVariant &result, Context &ctx) const { sVariant val; CHECK_EVAL(_arg, val, 0); result.setInt(!val.asBool()); return true; } TernaryConditional::~TernaryConditional() { delete _condition; delete _ifnode; delete _elsenode; } bool TernaryConditional::eval(sVariant &result, Context &ctx) const { sVariant val; CHECK_EVAL(_condition, val, 0); if (val.asBool()) { CHECK_EVAL(_ifnode, result, 0); } else { CHECK_EVAL(_elsenode, result, 0); } return true; } void TernaryConditional::print(sStr &s) const { Node::print(s); s.printf("\tCondition: %s @ %p; if-value: %s @ %p; else-value: %s @ %p\n", _condition->getTypeName(), _condition, _ifnode->getTypeName(), _ifnode, _elsenode->getTypeName(), _elsenode); _condition->print(s); _ifnode->print(s); _elsenode->print(s); } Property::~Property() { delete _topic; } bool Property::eval(sVariant &result, Context &ctx) const { eEvalStatus code; if (_topic) { sVariant topic_val; CHECK_EVAL(_topic, topic_val, 0); code = ctx.evalGetProperty(result, topic_val, _name.ptr()); } else { code = ctx.evalGetProperty(result, _name.ptr()); } if (code != EVAL_SUCCESS) { ctx.setError(getLocation(), code, "accessing '%s' property failed", _name.ptr()); return false; } return true; } void Property::print(sStr &s) const { Node::print(s); s.printf("\tName == \"%s\"; topic %s @ %s\n", _name.ptr(), _topic ? _topic->getTypeName() : NULL, getName()); if (_topic) _topic->print(s); } FunctionCall::~FunctionCall() { delete _verb; } bool FunctionCall::eval(sVariant &result, Context &ctx, Node *topic, const char *callableType) const { sVariant verbVal, topicVal; sVec<sVariant> argVals; argVals.resize(_elts.dim()); if (topic) CHECK_EVAL(topic, topicVal, 0); CHECK_EVAL(_verb, verbVal, 0); for (idx i=0; i<_elts.dim(); i++) CHECK_EVAL(_elts[i], argVals[i], 0); CallableWrapper *cw = dynamic_cast<CallableWrapper*>(verbVal.asData()); if (!cw) { ctx.setError(getLocation(), EVAL_TYPE_ERROR, "a %s cannot be called like a %s", verbVal.getTypeName(), callableType); return false; } return cw->call(result, ctx, topic ? &topicVal : NULL, argVals.ptr(), argVals.dim()); } bool FunctionCall::eval(sVariant &result, Context &ctx) const { return eval(result, ctx, NULL, "function"); } void FunctionCall::print(sStr &s) const { Node::print(s); s.printf("\tVerb == %s @ %p; arguments (%" DEC "): ", _verb->getTypeName(), _verb, _elts.dim()); for (idx i=0; i<_elts.dim(); i++) { s.printf(" %s @ %p;", _elts[i]->getTypeName(), _elts[i]); } s.printf("\n"); _verb->print(s); for (idx i=0; i<_elts.dim(); i++) { _elts[i]->print(s); } } MethodCall::MethodCall(Node *topic, Node *verb, idx line, idx col): FunctionCall(verb, line, col), _topic(topic) { _type = node_METHOD_CALL; // Empty topic means "this" if (!_topic) _topic = new Variable("this", line, col); } MethodCall::~MethodCall() { delete _topic; } bool MethodCall::eval(sVariant &result, Context &ctx) const { return FunctionCall::eval(result, ctx, _topic, "method"); } void MethodCall::print(sStr &s) const { Node::print(s); s.printf("\tVerb == %s @ %p; topic == %s @ %p; arguments (%" DEC "): ", _verb->getTypeName(), _verb, _topic ? _topic->getTypeName() : NULL, _topic, _elts.dim()); for (idx i=0; i<_elts.dim(); i++) { s.printf(" %s @ %p;", _elts[i]->getTypeName(), _elts[i]); } s.printf("\n"); _verb->print(s); for (idx i=0; i<_elts.dim(); i++) { _elts[i]->print(s); } } bool FormatCall::eval(sVariant &result, Context &ctx) const { return FunctionCall::eval(result, ctx, _topic, "format"); } bool Block::eval(sVariant &result, Context &ctx) const { bool ret = true; // a block introduces a new scope, evaluates its expressions // one after another, and returns the last one evaluated if (_addsScope) ctx.pushScope(); for (idx i=0; i<_elts.dim(); i++) { if (!_elts[i]->eval(result, ctx)) { ret = false; goto CLEANUP; } idx c = checkCtxMode(_elts[i], ctx, _addsScope ? flag_POP_SCOPE : 0); if (c <= 0) { ret = !c; goto CLEANUP; } } if (_addsScope) ctx.popScope(); CLEANUP: if (_isMain) { ctx.clearBreakContinue(); ctx.clearReturn(false); } return ret; } bool DollarCall::eval(sVariant &result, Context &ctx) const { bool ret = _name.ptr() ? ctx.evalGetDollarNameValue(result, _name.ptr()) : ctx.evalGetDollarNumValue(result, _num); if (!ret) { sStr e; if (_name.ptr()) e.printf("${%s}", _name.ptr()); else e.printf("$%" DEC, _num); ctx.setError(getLocation(), EVAL_VARIABLE_ERROR, "undefined expression %s", e.ptr()); return false; } return ret; } void DollarCall::print(sStr &s) const { if (_loc.print(s)) s.printf(" : "); if (_name.ptr()) s.printf("${%s} call @ %p\n", _name.ptr(), this); else s.printf("$%" DEC " call @ %p\n", _num, this); } bool DollarCall::isDollarCall(const char ** name, idx * num) const { if (_name.ptr()) { *name = _name.ptr(); *num = 0; } else { *name = 0; *num = _num; } return true; } bool UnbreakableBlock::eval(sVariant &result, Context &ctx) const { bool ret = Block::eval(result, ctx); if (ctx.getMode() == Context::MODE_RETURN) { result = ctx.getReturnValue(); ctx.clearReturn(); } ctx.clearBreakContinue(); return ret; } Lambda::Lambda(const char *arglist00, Block *block, idx line, idx col): Node(line, col) { _block = block; _block->setAddsScope(false); // make sure we don't delete local variables before returning them const char *argname; for (argname = arglist00; argname && *argname; argname = sString::next00(argname)) { _arglist.add(); _arglist[_arglist.dim()-1].printf("%s", argname); } _name.printf("function %p", this); } Lambda::~Lambda() { delete _block; } // This returns a callable value; use call() to actually call execute the lambda bool Lambda::eval(sVariant &result, Context &ctx) const { CallableWrapper callable(this, ctx.getScope()); result.setData(callable); return true; } bool Lambda::call(sVariant &result, Context &ctx, sVariant *topic, sVariant *args, idx nargs) const { // assume that context sanity has been checked by the caller... if (nargs != _arglist.dim()) { ctx.setError(getLocation(), EVAL_BAD_ARGS_NUMBER, "expected %" DEC " arguments, not %" DEC, _arglist.dim(), nargs); return false; } ctx.pushLambda(); if (topic && !ctx.addVarValue("this", *topic)) { ctx.setError(getLocation(), EVAL_READ_ONLY_ERROR, "'this' is read-only and cannot be modified"); return false; } for (idx i=0; i<nargs; i++) { if (!ctx.setVarValue(_arglist[i].ptr(), args[i])) { ctx.setError(getLocation(), EVAL_READ_ONLY_ERROR, "%s is read-only and cannot be modified", _arglist[i].ptr()); return false; } } sVariant blockResult; CHECK_EVAL(_block, blockResult, flag_POP_SCOPE|flag_IGNORE_RETURN); // did we explicitly call return? if (ctx.getMode() == Context::MODE_RETURN) { result = ctx.getReturnValue(); ctx.clearReturn(); } else result = blockResult; ctx.popScope(); return true; } void Lambda::print(sStr &s) const { Node::print(s); if (_name) s.printf("\tName == \"%s\"\n", getName()); if (_arglist.dim()) { s.printf("\tParameters (%" DEC "): ", _arglist.dim()); for (idx i=0; i<_arglist.dim(); i++) s.printf("%s%s", i ? ", " : "", _arglist[i].ptr()); s.printf("\n"); } s.printf("\tBlock : %s @ %p\n", _block->getTypeName(), _block); _block->print(s); } If::~If() { delete _condition; delete _ifBlock; delete _elseBlock; } void If::setLastElse(Node *node) { If *cur = this; while (If *next = dynamic_cast<If*>(cur->_elseBlock)) cur = next; delete cur->_elseBlock; cur->_elseBlock = node; } bool If::eval(sVariant &result, Context &ctx) const { sVariant val; ctx.pushScope(); CHECK_EVAL(_condition, val, flag_POP_SCOPE); if (val.asBool()) CHECK_EVAL(_ifBlock, result, flag_POP_SCOPE); else if (_elseBlock) CHECK_EVAL(_elseBlock, result, flag_POP_SCOPE); ctx.popScope(); return true; } void If::print(sStr &s) const { Node::print(s); s.printf("\tCondition %s @ %p; if-block %s @ %p; else-block %s @ %p\n", _condition ? _condition->getTypeName() : NULL, _condition, _ifBlock ? _ifBlock->getTypeName() : NULL, _ifBlock, _elseBlock ? _elseBlock->getTypeName() : NULL, _elseBlock); if (_condition) _condition->print(s); if (_ifBlock) _ifBlock->print(s); if (_elseBlock) _elseBlock->print(s); } For::For(Node* init, Node* condition, Node* step, Block *block, idx line, idx col): Node(line,col) { _init = init; if (dynamic_cast<Block*>(_init)) dynamic_cast<Block*>(_init)->setAddsScope(false); _condition = condition; if (dynamic_cast<Block*>(_condition)) dynamic_cast<Block*>(_condition)->setAddsScope(false); _step = step; if (dynamic_cast<Block*>(_step)) dynamic_cast<Block*>(_step)->setAddsScope(false); _block = block; this->_type = node_FOR; } For::~For() { delete _init; delete _condition; delete _step; delete _block; } bool For::eval(sVariant &result, Context &ctx) const { ctx.pushLoop(); if (_init) CHECK_RUN(_init, flag_POP_SCOPE); while(1) { sVariant val((idx)1); if (_condition) CHECK_EVAL(_condition, val, flag_POP_SCOPE); if (!val.asBool()) break; if (_block) CHECK_RUN(_block, flag_POP_SCOPE|flag_IGNORE_BREAK_CONTINUE); switch (ctx.getMode()) { case Context::MODE_BREAK: ctx.clearBreakContinue(); ctx.popScope(); return true; case Context::MODE_CONTINUE: ctx.clearBreakContinue(); break; } if (_step) CHECK_RUN(_step, flag_POP_SCOPE); } ctx.popScope(); return true; } void For::print(sStr &s) const { Node::print(s); s.printf("\tInit %s @ %p; condition %s @ %p; step %s @ %p; block %s @ %p\n", _init ? _init->getTypeName() : NULL, _init, _condition ? _condition->getTypeName() : NULL, _condition, _step ? _step->getTypeName() : NULL, _step, _block ? _block->getTypeName() : NULL, _block); if (_init) _init->print(s); if (_condition) _condition->print(s); if (_step) _step->print(s); if (_block) _block->print(s); } bool Return::eval(sVariant &result, Context &ctx) const { if (!_arg) { result.setNull(); return true; } CHECK_EVAL(_arg, result, 0); ctx.setReturn(result); return true; } bool Break::eval(sVariant &result, Context &ctx) const { sVariant val; ctx.setBreak(); return true; } bool Continue::eval(sVariant &result, Context &ctx) const { sVariant val; ctx.setContinue(); return true; }
25.26858
275
0.590419
syntheticgio
3265452c988b768445d55f2700259fcd24c36539
532
hpp
C++
core/include/olreport/tengine_cfg_data.hpp
wangshankun/Tengine_Atlas
b5485039e72b4a624c795ff95d73eb6d719c7706
[ "Apache-2.0" ]
25
2018-12-09T09:31:56.000Z
2021-08-12T10:32:19.000Z
core/include/olreport/tengine_cfg_data.hpp
wangshankun/Tengine_Atlas
b5485039e72b4a624c795ff95d73eb6d719c7706
[ "Apache-2.0" ]
1
2022-03-31T03:33:42.000Z
2022-03-31T03:33:42.000Z
core/include/olreport/tengine_cfg_data.hpp
wangshankun/Tengine_Atlas
b5485039e72b4a624c795ff95d73eb6d719c7706
[ "Apache-2.0" ]
6
2018-12-16T01:18:42.000Z
2019-09-18T07:29:56.000Z
#ifndef __TENGINE_CFG_DATA_HPP__ #define __TENGINE_CFG_DATA_HPP__ #ifndef EXTERN_CFG_REPORT_DAT #define CFG_REPORT_TIMER 7200 //seconds #define CFG_TENGINE_KEY "TENGINE_DEP_171_2019" #define CFG_TENGINE_TOKEN "TENGINE_DEP" #define CFG_APPID "tengine_others" #define CFG_APP_KEY "EzsKwQBYpAADva6k" #define CFG_API_VERSION "TENGINE_DEP_171" #define CFG_HOST "cloud.openailab.com" #define CFG_PORT 80 #define CFG_REQ_URL "/oas-cloud/application/ts/others/saveTengineInfo" #else #include "extern_cfg_report_dat.hpp" #endif #endif
23.130435
70
0.834586
wangshankun
3266afcaca7348d9bd3558479144991c005d04f1
585
cpp
C++
src/external_plugins/scintilla_editor_input_handler/input_handler_plugin.cpp
stonewell/wxglterm
27480ed01e2832e98785b517ac17037a71cefe7c
[ "MIT" ]
12
2017-11-23T16:02:41.000Z
2019-12-29T08:36:36.000Z
src/external_plugins/scintilla_editor_input_handler/input_handler_plugin.cpp
stonewell/wxglterm
27480ed01e2832e98785b517ac17037a71cefe7c
[ "MIT" ]
9
2017-12-04T15:55:51.000Z
2019-11-01T13:08:21.000Z
src/external_plugins/scintilla_editor_input_handler/input_handler_plugin.cpp
stonewell/wxglterm
27480ed01e2832e98785b517ac17037a71cefe7c
[ "MIT" ]
5
2018-09-02T07:35:13.000Z
2019-12-29T08:36:37.000Z
#include <pybind11/embed.h> #include <iostream> #include <unistd.h> #include <vector> #include <string.h> #include "key_code_map.h" #include "plugin_manager.h" #include "plugin.h" #include "term_network.h" #include "term_data_handler.h" #include "term_context.h" #include "term_window.h" #include "input.h" #include "plugin_base.h" #include "app_config_impl.h" #include "input_handler_plugin.h" extern "C" void register_plugins(PluginManagerPtr plugin_manager) { plugin_manager->RegisterPlugin(std::dynamic_pointer_cast<Plugin>(InputHandlerPtr {new DefaultInputHandler})); }
21.666667
113
0.77094
stonewell
326a561f5aa0f9ec625e95c45a2ecc229bf99da6
20,903
cpp
C++
vnpy/api/oes/vnoes/generated_files/generated_functions_9.cpp
howyu88/vnpy2
c8ae445823dc1f71abda1a79fae7d4be3dd92dd4
[ "MIT" ]
323
2015-11-21T14:45:29.000Z
2022-03-16T08:54:37.000Z
vnpy/api/oes/vnoes/generated_files/generated_functions_9.cpp
howyu88/vnpy2
c8ae445823dc1f71abda1a79fae7d4be3dd92dd4
[ "MIT" ]
9
2017-03-21T08:26:21.000Z
2021-08-23T06:41:17.000Z
vnpy/api/oes/vnoes/generated_files/generated_functions_9.cpp
howyu88/vnpy2
c8ae445823dc1f71abda1a79fae7d4be3dd92dd4
[ "MIT" ]
148
2016-09-26T03:25:39.000Z
2022-02-06T14:43:48.000Z
#include "config.h" #include <iostream> #include <string> #include <pybind11/pybind11.h> #include <pybind11/functional.h> #include <pybind11/stl.h> #include <c2py/c2py.hpp> #include "module.hpp" #include "wrappers.hpp" #include "generated_functions.h" #include "oes_api/oes_api.h" #include "mds_api/mds_api.h" void generate_class_MdsMktDataRequestReq(pybind11::object & parent) { // _MdsMktDataRequestReq pybind11::class_<_MdsMktDataRequestReq> c(parent, "_MdsMktDataRequestReq"); if constexpr (std::is_default_constructible_v<_MdsMktDataRequestReq>) c.def(pybind11::init<>()); // _MdsMktDataRequestReq::subMode c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestReq, "subMode", subMode); // _MdsMktDataRequestReq::tickType c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestReq, "tickType", tickType); // _MdsMktDataRequestReq::sseStockFlag c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestReq, "sseStockFlag", sseStockFlag); // _MdsMktDataRequestReq::sseIndexFlag c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestReq, "sseIndexFlag", sseIndexFlag); // _MdsMktDataRequestReq::sseOptionFlag c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestReq, "sseOptionFlag", sseOptionFlag); // _MdsMktDataRequestReq::szseStockFlag c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestReq, "szseStockFlag", szseStockFlag); // _MdsMktDataRequestReq::szseIndexFlag c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestReq, "szseIndexFlag", szseIndexFlag); // _MdsMktDataRequestReq::szseOptionFlag c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestReq, "szseOptionFlag", szseOptionFlag); // _MdsMktDataRequestReq::isRequireInitialMktData c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestReq, "isRequireInitialMktData", isRequireInitialMktData); // _MdsMktDataRequestReq::__channelNos c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestReq, "__channelNos", __channelNos); // _MdsMktDataRequestReq::tickExpireType c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestReq, "tickExpireType", tickExpireType); // _MdsMktDataRequestReq::__filler c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestReq, "__filler", __filler); // _MdsMktDataRequestReq::dataTypes c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestReq, "dataTypes", dataTypes); // _MdsMktDataRequestReq::beginTime c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestReq, "beginTime", beginTime); // _MdsMktDataRequestReq::subSecurityCnt c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestReq, "subSecurityCnt", subSecurityCnt); AUTOCXXPY_POST_REGISTER_CLASS(tag_vnoes, _MdsMktDataRequestReq, c); module_vnoes::objects.emplace("_MdsMktDataRequestReq", c); } void generate_class_MdsMktDataRequestReqBuf(pybind11::object & parent) { // _MdsMktDataRequestReqBuf pybind11::class_<_MdsMktDataRequestReqBuf> c(parent, "_MdsMktDataRequestReqBuf"); if constexpr (std::is_default_constructible_v<_MdsMktDataRequestReqBuf>) c.def(pybind11::init<>()); // _MdsMktDataRequestReqBuf::mktDataRequestReq c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestReqBuf, "mktDataRequestReq", mktDataRequestReq); // _MdsMktDataRequestReqBuf::entries c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestReqBuf, "entries", entries); AUTOCXXPY_POST_REGISTER_CLASS(tag_vnoes, _MdsMktDataRequestReqBuf, c); module_vnoes::objects.emplace("_MdsMktDataRequestReqBuf", c); } void generate_class_MdsMktDataRequestRsp(pybind11::object & parent) { // _MdsMktDataRequestRsp pybind11::class_<_MdsMktDataRequestRsp> c(parent, "_MdsMktDataRequestRsp"); if constexpr (std::is_default_constructible_v<_MdsMktDataRequestRsp>) c.def(pybind11::init<>()); // _MdsMktDataRequestRsp::subMode c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestRsp, "subMode", subMode); // _MdsMktDataRequestRsp::tickType c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestRsp, "tickType", tickType); // _MdsMktDataRequestRsp::isRequireInitialMktData c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestRsp, "isRequireInitialMktData", isRequireInitialMktData); // _MdsMktDataRequestRsp::__channelNos c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestRsp, "__channelNos", __channelNos); // _MdsMktDataRequestRsp::tickExpireType c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestRsp, "tickExpireType", tickExpireType); // _MdsMktDataRequestRsp::__filler c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestRsp, "__filler", __filler); // _MdsMktDataRequestRsp::dataTypes c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestRsp, "dataTypes", dataTypes); // _MdsMktDataRequestRsp::beginTime c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestRsp, "beginTime", beginTime); // _MdsMktDataRequestRsp::sseStockSubscribed c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestRsp, "sseStockSubscribed", sseStockSubscribed); // _MdsMktDataRequestRsp::sseIndexSubscribed c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestRsp, "sseIndexSubscribed", sseIndexSubscribed); // _MdsMktDataRequestRsp::sseOptionSubscribed c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestRsp, "sseOptionSubscribed", sseOptionSubscribed); // _MdsMktDataRequestRsp::szseStockSubscribed c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestRsp, "szseStockSubscribed", szseStockSubscribed); // _MdsMktDataRequestRsp::szseIndexSubscribed c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestRsp, "szseIndexSubscribed", szseIndexSubscribed); // _MdsMktDataRequestRsp::szseOptionSubscribed c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktDataRequestRsp, "szseOptionSubscribed", szseOptionSubscribed); AUTOCXXPY_POST_REGISTER_CLASS(tag_vnoes, _MdsMktDataRequestRsp, c); module_vnoes::objects.emplace("_MdsMktDataRequestRsp", c); } void generate_class_MdsTestRequestReq(pybind11::object & parent) { // _MdsTestRequestReq pybind11::class_<_MdsTestRequestReq> c(parent, "_MdsTestRequestReq"); if constexpr (std::is_default_constructible_v<_MdsTestRequestReq>) c.def(pybind11::init<>()); // _MdsTestRequestReq::testReqId c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsTestRequestReq, "testReqId", testReqId); // _MdsTestRequestReq::sendTime c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsTestRequestReq, "sendTime", sendTime); // _MdsTestRequestReq::__filler c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsTestRequestReq, "__filler", __filler); AUTOCXXPY_POST_REGISTER_CLASS(tag_vnoes, _MdsTestRequestReq, c); module_vnoes::objects.emplace("_MdsTestRequestReq", c); } void generate_class_MdsTestRequestRsp(pybind11::object & parent) { // _MdsTestRequestRsp pybind11::class_<_MdsTestRequestRsp> c(parent, "_MdsTestRequestRsp"); if constexpr (std::is_default_constructible_v<_MdsTestRequestRsp>) c.def(pybind11::init<>()); // _MdsTestRequestRsp::testReqId c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsTestRequestRsp, "testReqId", testReqId); // _MdsTestRequestRsp::origSendTime c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsTestRequestRsp, "origSendTime", origSendTime); // _MdsTestRequestRsp::__filler1 c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsTestRequestRsp, "__filler1", __filler1); // _MdsTestRequestRsp::respTime c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsTestRequestRsp, "respTime", respTime); // _MdsTestRequestRsp::__filler2 c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsTestRequestRsp, "__filler2", __filler2); // _MdsTestRequestRsp::__recvTime c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsTestRequestRsp, "__recvTime", __recvTime); // _MdsTestRequestRsp::__collectedTime c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsTestRequestRsp, "__collectedTime", __collectedTime); // _MdsTestRequestRsp::__pushingTime c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsTestRequestRsp, "__pushingTime", __pushingTime); AUTOCXXPY_POST_REGISTER_CLASS(tag_vnoes, _MdsTestRequestRsp, c); module_vnoes::objects.emplace("_MdsTestRequestRsp", c); } void generate_class_MdsChangePasswordReq(pybind11::object & parent) { // _MdsChangePasswordReq pybind11::class_<_MdsChangePasswordReq> c(parent, "_MdsChangePasswordReq"); if constexpr (std::is_default_constructible_v<_MdsChangePasswordReq>) c.def(pybind11::init<>()); // _MdsChangePasswordReq::encryptMethod c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsChangePasswordReq, "encryptMethod", encryptMethod); // _MdsChangePasswordReq::__filler c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsChangePasswordReq, "__filler", __filler); // _MdsChangePasswordReq::username c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsChangePasswordReq, "username", username); // _MdsChangePasswordReq::userInfo c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsChangePasswordReq, "userInfo", userInfo); // _MdsChangePasswordReq::oldPassword c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsChangePasswordReq, "oldPassword", oldPassword); // _MdsChangePasswordReq::newPassword c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsChangePasswordReq, "newPassword", newPassword); generate_class_decltype_MdsChangePasswordReq_userInfo_(c); AUTOCXXPY_POST_REGISTER_CLASS(tag_vnoes, _MdsChangePasswordReq, c); module_vnoes::objects.emplace("_MdsChangePasswordReq", c); } void generate_class_decltype_MdsChangePasswordReq_userInfo_(pybind11::object & parent) { // decltype(_MdsChangePasswordReq::userInfo) pybind11::class_<decltype(_MdsChangePasswordReq::userInfo)> c(parent, "decltype(userInfo)"); if constexpr (std::is_default_constructible_v<decltype(_MdsChangePasswordReq::userInfo)>) c.def(pybind11::init<>()); // decltype(_MdsChangePasswordReq::userInfo)::u64 c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, decltype(_MdsChangePasswordReq::userInfo), "u64", u64); // decltype(_MdsChangePasswordReq::userInfo)::i64 c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, decltype(_MdsChangePasswordReq::userInfo), "i64", i64); // decltype(_MdsChangePasswordReq::userInfo)::u32 c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, decltype(_MdsChangePasswordReq::userInfo), "u32", u32); // decltype(_MdsChangePasswordReq::userInfo)::i32 c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, decltype(_MdsChangePasswordReq::userInfo), "i32", i32); // decltype(_MdsChangePasswordReq::userInfo)::c8 c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, decltype(_MdsChangePasswordReq::userInfo), "c8", c8); AUTOCXXPY_POST_REGISTER_CLASS(tag_vnoes, decltype(_MdsChangePasswordReq::userInfo), c); module_vnoes::objects.emplace("decltype(_MdsChangePasswordReq::userInfo)", c); } void generate_class_MdsChangePasswordRsp(pybind11::object & parent) { // _MdsChangePasswordRsp pybind11::class_<_MdsChangePasswordRsp> c(parent, "_MdsChangePasswordRsp"); if constexpr (std::is_default_constructible_v<_MdsChangePasswordRsp>) c.def(pybind11::init<>()); // _MdsChangePasswordRsp::encryptMethod c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsChangePasswordRsp, "encryptMethod", encryptMethod); // _MdsChangePasswordRsp::__filler c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsChangePasswordRsp, "__filler", __filler); // _MdsChangePasswordRsp::username c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsChangePasswordRsp, "username", username); // _MdsChangePasswordRsp::userInfo c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsChangePasswordRsp, "userInfo", userInfo); // _MdsChangePasswordRsp::__filler2 c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsChangePasswordRsp, "__filler2", __filler2); // _MdsChangePasswordRsp::transDate c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsChangePasswordRsp, "transDate", transDate); // _MdsChangePasswordRsp::transTime c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsChangePasswordRsp, "transTime", transTime); // _MdsChangePasswordRsp::rejReason c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsChangePasswordRsp, "rejReason", rejReason); generate_class_decltype_MdsChangePasswordRsp_userInfo_(c); AUTOCXXPY_POST_REGISTER_CLASS(tag_vnoes, _MdsChangePasswordRsp, c); module_vnoes::objects.emplace("_MdsChangePasswordRsp", c); } void generate_class_decltype_MdsChangePasswordRsp_userInfo_(pybind11::object & parent) { // decltype(_MdsChangePasswordRsp::userInfo) pybind11::class_<decltype(_MdsChangePasswordRsp::userInfo)> c(parent, "decltype(userInfo)"); if constexpr (std::is_default_constructible_v<decltype(_MdsChangePasswordRsp::userInfo)>) c.def(pybind11::init<>()); // decltype(_MdsChangePasswordRsp::userInfo)::u64 c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, decltype(_MdsChangePasswordRsp::userInfo), "u64", u64); // decltype(_MdsChangePasswordRsp::userInfo)::i64 c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, decltype(_MdsChangePasswordRsp::userInfo), "i64", i64); // decltype(_MdsChangePasswordRsp::userInfo)::u32 c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, decltype(_MdsChangePasswordRsp::userInfo), "u32", u32); // decltype(_MdsChangePasswordRsp::userInfo)::i32 c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, decltype(_MdsChangePasswordRsp::userInfo), "i32", i32); // decltype(_MdsChangePasswordRsp::userInfo)::c8 c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, decltype(_MdsChangePasswordRsp::userInfo), "c8", c8); AUTOCXXPY_POST_REGISTER_CLASS(tag_vnoes, decltype(_MdsChangePasswordRsp::userInfo), c); module_vnoes::objects.emplace("decltype(_MdsChangePasswordRsp::userInfo)", c); } void generate_class_MdsMktReqMsgBody(pybind11::object & parent) { // _MdsMktReqMsgBody pybind11::class_<_MdsMktReqMsgBody> c(parent, "_MdsMktReqMsgBody"); if constexpr (std::is_default_constructible_v<_MdsMktReqMsgBody>) c.def(pybind11::init<>()); // _MdsMktReqMsgBody::wholeMktDataReqBuf c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktReqMsgBody, "wholeMktDataReqBuf", wholeMktDataReqBuf); // _MdsMktReqMsgBody::mktDataRequestReq c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktReqMsgBody, "mktDataRequestReq", mktDataRequestReq); // _MdsMktReqMsgBody::testRequestReq c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktReqMsgBody, "testRequestReq", testRequestReq); // _MdsMktReqMsgBody::qryMktDataSnapshotReq c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktReqMsgBody, "qryMktDataSnapshotReq", qryMktDataSnapshotReq); // _MdsMktReqMsgBody::qrySecurityStatusReq c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktReqMsgBody, "qrySecurityStatusReq", qrySecurityStatusReq); // _MdsMktReqMsgBody::qryTrdSessionStatusReq c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktReqMsgBody, "qryTrdSessionStatusReq", qryTrdSessionStatusReq); // _MdsMktReqMsgBody::qryStockStaticInfoReq c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktReqMsgBody, "qryStockStaticInfoReq", qryStockStaticInfoReq); // _MdsMktReqMsgBody::qrySnapshotListReq c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktReqMsgBody, "qrySnapshotListReq", qrySnapshotListReq); // _MdsMktReqMsgBody::changePasswordReq c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktReqMsgBody, "changePasswordReq", changePasswordReq); AUTOCXXPY_POST_REGISTER_CLASS(tag_vnoes, _MdsMktReqMsgBody, c); module_vnoes::objects.emplace("_MdsMktReqMsgBody", c); } void generate_class_MdsMktRspMsgBody(pybind11::object & parent) { // _MdsMktRspMsgBody pybind11::class_<_MdsMktRspMsgBody> c(parent, "_MdsMktRspMsgBody"); if constexpr (std::is_default_constructible_v<_MdsMktRspMsgBody>) c.def(pybind11::init<>()); // _MdsMktRspMsgBody::mktDataRequestRsp c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktRspMsgBody, "mktDataRequestRsp", mktDataRequestRsp); // _MdsMktRspMsgBody::testRequestRsp c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktRspMsgBody, "testRequestRsp", testRequestRsp); // _MdsMktRspMsgBody::mktDataSnapshot c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktRspMsgBody, "mktDataSnapshot", mktDataSnapshot); // _MdsMktRspMsgBody::trade c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktRspMsgBody, "trade", trade); // _MdsMktRspMsgBody::order c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktRspMsgBody, "order", order); // _MdsMktRspMsgBody::trdSessionStatus c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktRspMsgBody, "trdSessionStatus", trdSessionStatus); // _MdsMktRspMsgBody::securityStatus c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktRspMsgBody, "securityStatus", securityStatus); // _MdsMktRspMsgBody::qryStockStaticInfoRsp c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktRspMsgBody, "qryStockStaticInfoRsp", qryStockStaticInfoRsp); // _MdsMktRspMsgBody::qrySnapshotListRsp c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktRspMsgBody, "qrySnapshotListRsp", qrySnapshotListRsp); // _MdsMktRspMsgBody::changePasswordRsp c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsMktRspMsgBody, "changePasswordRsp", changePasswordRsp); AUTOCXXPY_POST_REGISTER_CLASS(tag_vnoes, _MdsMktRspMsgBody, c); module_vnoes::objects.emplace("_MdsMktRspMsgBody", c); } void generate_class_MdsUdpPktHead(pybind11::object & parent) { // _MdsUdpPktHead pybind11::class_<_MdsUdpPktHead> c(parent, "_MdsUdpPktHead"); if constexpr (std::is_default_constructible_v<_MdsUdpPktHead>) c.def(pybind11::init<>()); // _MdsUdpPktHead::msgCnt c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsUdpPktHead, "msgCnt", msgCnt); // _MdsUdpPktHead::pktSiz c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsUdpPktHead, "pktSiz", pktSiz); // _MdsUdpPktHead::pktSeq c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsUdpPktHead, "pktSeq", pktSeq); AUTOCXXPY_POST_REGISTER_CLASS(tag_vnoes, _MdsUdpPktHead, c); module_vnoes::objects.emplace("_MdsUdpPktHead", c); } void generate_class_MdsApiClientCfg(pybind11::object & parent) { // _MdsApiClientCfg pybind11::class_<_MdsApiClientCfg> c(parent, "_MdsApiClientCfg"); if constexpr (std::is_default_constructible_v<_MdsApiClientCfg>) c.def(pybind11::init<>()); // _MdsApiClientCfg::tcpChannelCfg c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsApiClientCfg, "tcpChannelCfg", tcpChannelCfg); // _MdsApiClientCfg::qryChannelCfg c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsApiClientCfg, "qryChannelCfg", qryChannelCfg); // _MdsApiClientCfg::udpL1ChannelCfg c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsApiClientCfg, "udpL1ChannelCfg", udpL1ChannelCfg); // _MdsApiClientCfg::udpL2ChannelCfg c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsApiClientCfg, "udpL2ChannelCfg", udpL2ChannelCfg); // _MdsApiClientCfg::udpTick1ChannelCfg c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsApiClientCfg, "udpTick1ChannelCfg", udpTick1ChannelCfg); // _MdsApiClientCfg::udpTradeChannelCfg c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsApiClientCfg, "udpTradeChannelCfg", udpTradeChannelCfg); // _MdsApiClientCfg::udpTick2ChannelCfg c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsApiClientCfg, "udpTick2ChannelCfg", udpTick2ChannelCfg); // _MdsApiClientCfg::udpOrderChannelCfg c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsApiClientCfg, "udpOrderChannelCfg", udpOrderChannelCfg); // _MdsApiClientCfg::subscribeInfo c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsApiClientCfg, "subscribeInfo", subscribeInfo); AUTOCXXPY_POST_REGISTER_CLASS(tag_vnoes, _MdsApiClientCfg, c); module_vnoes::objects.emplace("_MdsApiClientCfg", c); } void generate_class_MdsApiClientEnv(pybind11::object & parent) { // _MdsApiClientEnv pybind11::class_<_MdsApiClientEnv> c(parent, "_MdsApiClientEnv"); if constexpr (std::is_default_constructible_v<_MdsApiClientEnv>) c.def(pybind11::init<>()); // _MdsApiClientEnv::tcpChannel c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsApiClientEnv, "tcpChannel", tcpChannel); // _MdsApiClientEnv::qryChannel c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsApiClientEnv, "qryChannel", qryChannel); // _MdsApiClientEnv::udpL1Channel c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsApiClientEnv, "udpL1Channel", udpL1Channel); // _MdsApiClientEnv::udpL2Channel c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsApiClientEnv, "udpL2Channel", udpL2Channel); // _MdsApiClientEnv::udpTick1Channel c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsApiClientEnv, "udpTick1Channel", udpTick1Channel); // _MdsApiClientEnv::udpTradeChannel c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsApiClientEnv, "udpTradeChannel", udpTradeChannel); // _MdsApiClientEnv::udpTick2Channel c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsApiClientEnv, "udpTick2Channel", udpTick2Channel); // _MdsApiClientEnv::udpOrderChannel c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsApiClientEnv, "udpOrderChannel", udpOrderChannel); // _MdsApiClientEnv::udpChannelGroup c.AUTOCXXPY_DEF_PROPERTY(tag_vnoes, _MdsApiClientEnv, "udpChannelGroup", udpChannelGroup); AUTOCXXPY_POST_REGISTER_CLASS(tag_vnoes, _MdsApiClientEnv, c); module_vnoes::objects.emplace("_MdsApiClientEnv", c); }
58.388268
115
0.787542
howyu88
326b6347cc3bf49ac4d638cfb6ce752f624bf001
1,568
cpp
C++
mse.cpp
ArnoGranier/cppCNN
9573e01eb71a8fdbb6a62812ef02ce0641055277
[ "MIT" ]
8
2020-01-23T08:26:22.000Z
2022-02-22T22:50:17.000Z
mse.cpp
ArnoGranier/cppCNN
9573e01eb71a8fdbb6a62812ef02ce0641055277
[ "MIT" ]
1
2021-04-11T02:03:48.000Z
2021-04-11T02:05:15.000Z
mse.cpp
ArnoGranier/cppCNN
9573e01eb71a8fdbb6a62812ef02ce0641055277
[ "MIT" ]
null
null
null
#include "mse.hpp" namespace cppcnn{ double MSE::compute(const vector<double>& prediction, int8_t expected_int) const { double loss=0.0; // We receive the expected result as an int between 0 and 9 (equivalent to // a label). The expected activation of the output layer of the network // is the one-hot encoding of this int. i.e for // 0 : [1, 0, 0, 0, 0, 0, 0, 0, 0, 0] // 3 : [0, 0, 0, 1, 0, 0, 0, 0, 0, 0] // etc.. // Here we compute the one-hot encoding uint output_layer_size = prediction.size(); vector<double> expected_vector(output_layer_size, 0.0); expected_vector[expected_int] = 1.0; // Compute mean squared-error for (uint it=0;it<output_layer_size;++it){ loss += std::pow(prediction[it]-expected_vector[it], 2); } return loss; } vector<double> MSE::deriv(const vector<double>& prediction, int8_t expected_int) const { // Here we compute the one-hot encoding uint output_layer_size = prediction.size(); vector<double> expected_vector(output_layer_size, 0.0); expected_vector[expected_int] = 1.0; // Gradient of mean squared errror for vector X and Y is just // [0.5*(X_i-Y_i) for i in 1..N] // We can discard the 0.5 because it does not change proportionality transform(prediction.begin(), prediction.end(), expected_vector.begin(), expected_vector.begin(), std::minus<double>()); return expected_vector; } } // namespace
32.666667
78
0.617347
ArnoGranier
3270b3b301028853379f60a7cfd8f8b6c5a9458d
3,266
cpp
C++
Src/HideoutComponent.cpp
4anotherday/DarkMaze
e032b05641019cf5d69fd5c8bec9949f250c6c3f
[ "MIT" ]
null
null
null
Src/HideoutComponent.cpp
4anotherday/DarkMaze
e032b05641019cf5d69fd5c8bec9949f250c6c3f
[ "MIT" ]
null
null
null
Src/HideoutComponent.cpp
4anotherday/DarkMaze
e032b05641019cf5d69fd5c8bec9949f250c6c3f
[ "MIT" ]
null
null
null
#include "HideoutComponent.h" #include "HealthComponent.h" #include "ComponentIDs.h" #include "includeLUA.h" #include "Transform.h" #include "PlayerVisibilityComponent.h" #include "UserComponentsIDs.h" #include "GameObject.h" #include "RenderObjectComponent.h" #include "ColliderComponent.h" #include "Engine.h" #include "Logger.h" ADD_COMPONENT(HideoutComponent) HideoutComponent::HideoutComponent() :Component(UserComponentId::HideoutComponent), _log(nullptr), _playerTransform(nullptr), _myTransform(nullptr), _visibility(nullptr), _playerName("Player") , _render(nullptr), _alphaMaterial("Practica1/BushAlpha"), _normalMaterial("Practica1/Bush"), _distance(1) { } HideoutComponent::~HideoutComponent() { } void HideoutComponent::awake(luabridge::LuaRef& data) { if (LUAFIELDEXIST(PlayerName)) _playerName = GETLUASTRINGFIELD(PlayerName); if (LUAFIELDEXIST(AlphaMaterial)) _alphaMaterial = GETLUASTRINGFIELD(AlphaMaterial); if (LUAFIELDEXIST(NormalMaterial)) _normalMaterial = GETLUASTRINGFIELD(NormalMaterial); } void HideoutComponent::start() { _log = Logger::getInstance(); GameObject* go = Engine::getInstance()->findGameObject(_playerName); if (go != nullptr) { _visibility = static_cast<PlayerVisibilityComponent*>(go->getComponent(UserComponentId::PlayerVisibilityComponent)); if (_visibility == nullptr) throw "Player doesn't have PlayerVisibilityComponent"; _playerTransform = static_cast<Transform*>(go->getComponent(ComponentId::Transform)); if (_playerTransform == nullptr) throw "Player doesn't have Transform"; _myTransform = GETCOMPONENT(Transform, ComponentId::Transform); if (_myTransform == nullptr) throw "Hideout doesn't have Transform"; SphereColliderComponent* col = GETCOMPONENT(SphereColliderComponent, ComponentId::SphereCollider); if (col != nullptr) _distance = 2 * col->getRadius(); else if (_log != nullptr) _log->log("Hideout doesn't have SphereColliderComponent", Logger::Level::WARN); _render = GETCOMPONENT(RenderObjectComponent, ComponentId::RenderObject); if (_render == nullptr && _log != nullptr) _log->log("Hideout doesn't have RenderObjectComponent, transparencies won't work", Logger::Level::WARN); } else throw "Player GameObject not found"; } void HideoutComponent::update() { //std::cout << _myTransform->getPosition().getX() << " " << _myTransform->getPosition().getY() << _myTransform->getPosition().getZ() << '\n'; //std::cout << _playerTransform->getPosition().getX() << " " << _playerTransform->getPosition().getY() << _playerTransform->getPosition().getZ() << '\n'; if (!_visibility->getVisible()) { Vector3 pos(_myTransform->getPosition().getX(), _playerTransform->getPosition().getY(), _myTransform->getPosition().getZ()); float distance = std::abs((pos - _playerTransform->getPosition()).magnitude()); //the second check is to avoid other hideouts setting visible the player if (distance >= _distance && distance <= 1.1 * _distance) { _visibility->setVisible(true); _render->setMaterial(_normalMaterial); } } } void HideoutComponent::onTrigger(GameObject* other) { if (other->getComponent(UserComponentId::PlayerVisibilityComponent) != nullptr) { _visibility->setVisible(false); _render->setMaterial(_alphaMaterial); } }
37.54023
192
0.748928
4anotherday
327618b691aff17c7a6d8bb87feff53cb46db558
13,963
cpp
C++
AuxCore/AuxCore/LoadedModules.cpp
y11en/crystalaep
628422d210b5de4799c6c3d4fd736bee75a3deeb
[ "Unlicense" ]
30
2020-05-31T12:01:35.000Z
2021-12-08T12:50:53.000Z
AuxCore/AuxCore/LoadedModules.cpp
y11en/crystalaep
628422d210b5de4799c6c3d4fd736bee75a3deeb
[ "Unlicense" ]
null
null
null
AuxCore/AuxCore/LoadedModules.cpp
y11en/crystalaep
628422d210b5de4799c6c3d4fd736bee75a3deeb
[ "Unlicense" ]
10
2020-05-31T11:16:10.000Z
2020-08-19T03:12:33.000Z
// Copyright (c) Peter Winter-Smith [peterwintersmith@gmail.com] // important todo: // 1. push HMODULEs and CSingleLoadedModules onto a queue to be erased periodically // to avoid horrible situations when performing checks for heap/virtual mem // functions // // 2. check that this code still works on XP without the defered erase thread #include "stdafx.h" #include "AuxCore.h" #include "..\..\Shared\Utils\Utils.h" #include "LoadedModulesBase.h" #include "LoadedModules.h" CLoadedModules *CLoadedModules::m_Instance = NULL; CRITICAL_SECTION CLoadedModules::m_csCreateInst = {0}, CLoadedModules::m_csModOpLock = {0}; BOOL ModuleLoadHooks::AttachAll() { DETOUR_TRANS_BEGIN ATTACH_DETOUR_GPA(L"kernel32.dll", "LoadLibraryA", LoadLibraryA); ATTACH_DETOUR_GPA(L"kernel32.dll", "LoadLibraryW", LoadLibraryW); ATTACH_DETOUR_GPA(L"kernel32.dll", "LoadLibraryExA", LoadLibraryExA); ATTACH_DETOUR_GPA(L"kernel32.dll", "LoadLibraryExW", LoadLibraryExW); ATTACH_DETOUR_GPA(L"ntdll.dll", "LdrLoadDll", LdrLoadDll); ATTACH_DETOUR_GPA(L"kernel32.dll", "FreeLibrary", FreeLibrary); DETOUR_TRANS_COMMIT return TRUE; } BOOL ModuleLoadHooks::DetachAll() { DETOUR_TRANS_BEGIN DETACH_DETOUR(LoadLibraryA); DETACH_DETOUR(LoadLibraryW); DETACH_DETOUR(LoadLibraryExA); DETACH_DETOUR(LoadLibraryExW); DETACH_DETOUR(LdrLoadDll); DETACH_DETOUR(FreeLibrary); DETOUR_TRANS_COMMIT return TRUE; } HMODULE WINAPI ModuleLoadHooks::My_LoadLibraryA( __in char* lpFileName ) { CLoadedModules *pLoadedMods = CLoadedModules::GetInstance(); HMODULE hm = NULL; wchar_t *pwszFile = Utils::WcFromMultiByte(lpFileName); hm = Real_LoadLibraryExA(lpFileName, NULL, 0); if(hm) { pLoadedMods->AddModule(hm); } if(pwszFile) free(pwszFile); return hm; } HMODULE WINAPI ModuleLoadHooks::My_LoadLibraryW( __in LPWSTR lpFileName ) { CLoadedModules *pLoadedMods = CLoadedModules::GetInstance(); HMODULE hm = NULL; hm = Real_LoadLibraryExW(lpFileName, NULL, 0); if(hm) { pLoadedMods->AddModule(hm); } return hm; } HMODULE WINAPI ModuleLoadHooks::My_LoadLibraryExA( __in char* lpFileName, __reserved HANDLE hFile, __in DWORD dwFlags ) { CLoadedModules *pLoadedMods = CLoadedModules::GetInstance(); HMODULE hm = NULL; wchar_t *pwszFile = Utils::WcFromMultiByte(lpFileName); hm = Real_LoadLibraryExA(lpFileName, hFile, dwFlags); if(hm && !(dwFlags & LOAD_LIBRARY_AS_DATAFILE)) { pLoadedMods->AddModule(hm); } if(pwszFile) free(pwszFile); return hm; } HMODULE WINAPI ModuleLoadHooks::My_LoadLibraryExW( __in LPWSTR lpFileName, __reserved HANDLE hFile, __in DWORD dwFlags ) { CLoadedModules *pLoadedMods = CLoadedModules::GetInstance(); HMODULE hm = NULL; hm = Real_LoadLibraryExW(lpFileName, hFile, dwFlags); if(hm && !(dwFlags & LOAD_LIBRARY_AS_DATAFILE)) { pLoadedMods->AddModule(hm); } return hm; } //http://www.matcode.com/undocwin.h.txt NTSTATUS NTAPI ModuleLoadHooks::My_LdrLoadDll( __in PWCHAR PathToFile, __in ULONG Flags, __in PUNICODE_STRING ModuleFileName, __out PHANDLE ModuleHandle ) { CLoadedModules *pLoadedMods = CLoadedModules::GetInstance(); NTSTATUS ntStatus = 0xc0000135; // UNABLE_TO_LOAD_DLL std::wstring wstrModuleName((WCHAR *)ModuleFileName->Buffer, ModuleFileName->Length / sizeof(WCHAR)); WCHAR *pwszModuleName = const_cast<WCHAR *>(wstrModuleName.c_str()); if(NT_SUCCESS(ntStatus = Real_LdrLoadDll(PathToFile, Flags, ModuleFileName, ModuleHandle))) { #ifdef DEBUG_BUILD //WCHAR wszTmp[512]; //wsprintf(wszTmp, L"LdrLoadDll(HMODULE = 0x%p)\n", ModuleHandle ? *ModuleHandle : NULL); //OutputDebugString(wszTmp); #endif if(*ModuleHandle && !(Flags & LOAD_LIBRARY_AS_DATAFILE)) { pLoadedMods->AddModule((HMODULE)*ModuleHandle); } } return ntStatus; } BOOL WINAPI ModuleLoadHooks::My_FreeLibrary( __in HMODULE hModule ) { CLoadedModules *pLoadedMods = CLoadedModules::GetInstance(); BOOL bRetVal = Real_FreeLibrary(hModule); if(bRetVal) { pLoadedMods->RemoveModule(hModule); } return bRetVal; } CLoadedModules *CLoadedModules::GetInstance() { if(m_Instance == NULL) { EnterCriticalSection(&m_csCreateInst); if(m_Instance == NULL) { m_Instance = new CLoadedModules(); } LeaveCriticalSection(&m_csCreateInst); } return m_Instance; } DWORD WINAPI CLoadedModules::CleanupQueueProc(LPVOID) { CLoadedModules *pLoadedMods = CLoadedModules::GetInstance(); while(!pLoadedMods->m_bTerminate) { while(!pLoadedMods->m_listCleanupMods.empty()) { CSingleLoadedModuleBase *pSlm = pLoadedMods->m_listCleanupMods.back(); pLoadedMods->m_listCleanupMods.pop_back(); if(pSlm) delete pSlm; } Sleep(DEFER_POLL_INTERVAL_MILLIS); } SetEvent(pLoadedMods->m_hEvent); return 0; } BOOL CLoadedModules::Start() { BOOL bSuccess = FALSE; DWORD dwTID = 0; if(m_hThread) { // started already bSuccess = TRUE; goto Cleanup; } m_hThread = CreateThread(NULL, 0, CleanupQueueProc, (LPVOID)'AUXQ', 0, &dwTID); bSuccess = (m_hThread != NULL); Cleanup: return bSuccess; } void CLoadedModules::Terminate() { if(!m_hThread || !this) return; m_bTerminate = TRUE; TerminateThread(m_hThread, 0); //DWORD dwWaitStatus = WaitForSingleObject(m_hEvent, 2 * DEFER_POLL_INTERVAL_MILLIS); /* switch(dwWaitStatus) { case WAIT_OBJECT_0: case WAIT_TIMEOUT: CloseHandle(m_hThread); m_hThread = NULL; CloseHandle(m_hEvent); m_hEvent = NULL; break; default: break; } */ } std::map<HMODULE, CSingleLoadedModuleBase *>& CLoadedModules::GetLoadedModuleList() { return m_mapLoadedMods; } void CLoadedModules::AddModule(HMODULE hm) { // locking here causes deadlock (presumably something we call calls heap or // mem function which checks caller ret is valid/enums modules which locks) AddModule(hm, FALSE); } void CLoadedModules::AddModule(HMODULE hm, BOOL bLock) { WCHAR *pwszModulePath = NULL, *pwszModuleName = NULL; MODULEINFO moduleInfo = {0}; #ifdef DEBUG_BUILD CLogger *logger = NULL; #endif //if(bLock) // EnterCriticalSection(&m_csModOpLock); //if(m_mapLoadedMods.find(hm) != m_mapLoadedMods.end()) // goto Cleanup; try { #ifdef DEBUG_BUILD logger = CLogger::GetInstance("bpcore_loadedmods"); logger->Log("AddModule(HMODULE hm = 0x%x)\n", hm); #endif } catch(...) { } if(!(pwszModulePath = (WCHAR *)calloc(65600, sizeof(WCHAR)))) goto Cleanup; DWORD cchModulePath = GetModuleFileName(hm, pwszModulePath, 65600 - 1); if(!cchModulePath) { WCHAR wszTempName[32]; //do //{ // wsprintf(wszTempName, L"unnamed_dll_%u.dll", Utils::GetRandomInteger(0, 0xffffffff)); //} //while(m_mapLoadedMods.find(hm) != m_mapLoadedMods.end()); // BUG?! hm never changes => infinite loop do { wsprintf(wszTempName, L"unnamed_dll_%u.dll", Utils::GetRandomInteger(0, 0xffffffff)); } while(FindDllWithPartialName(wszTempName) != NULL); // find a unique name wcscpy(pwszModulePath, wszTempName); pwszModuleName = pwszModulePath; } else { pwszModuleName = wcsrchr(pwszModulePath, '\\'); if(!pwszModuleName) { pwszModuleName = pwszModulePath; } else { // skip '\\' pwszModuleName++; } } if(!GetModuleInformation( GetCurrentProcess(), hm, &moduleInfo, sizeof(moduleInfo) )) { // just store zero values memset(&moduleInfo, 0, sizeof(moduleInfo)); } try { #ifdef DEBUG_BUILD if(logger) logger->Log("\tSaving module info hm(0x%x) {%S, %S, 0x%p, 0x%p, 0x%p}\n", hm, pwszModuleName, pwszModulePath, moduleInfo.lpBaseOfDll, moduleInfo.SizeOfImage, moduleInfo.EntryPoint ); #endif // should never throw as modname should always be unique #ifdef DEBUG_BUILD { WCHAR wsz[256]; wsprintf(wsz, L"Registering DLL: 0x%p (0x%s)\n", moduleInfo.lpBaseOfDll, pwszModuleName); OutputDebugString(wsz); } #endif if(m_mapLoadedMods[hm] != NULL) { //m_listCleanupMods.push_back(m_mapLoadedMods[hm]); m_mapLoadedMods[hm] = NULL; } m_mapLoadedMods[hm] = new CSingleLoadedModule( pwszModuleName, pwszModulePath, moduleInfo.lpBaseOfDll, moduleInfo.SizeOfImage, moduleInfo.EntryPoint ); } catch(...) { #ifdef DEBUG_BUILD { WCHAR wsz[256]; wsprintf(wsz, L"Exception registering module hm = 0x%p\n", hm); OutputDebugString(wsz); } #endif goto Cleanup; } Cleanup: if(pwszModulePath) free(pwszModulePath); //if(bLock) // LeaveCriticalSection(&m_csModOpLock); } void CLoadedModules::RemoveModule(HMODULE hm) { #ifdef DEBUG_BUILD CLogger *logger = NULL; #endif try { #ifdef DEBUG_BUILD logger = CLogger::GetInstance("bpcore_loadedmods"); logger->Log("RemoveModule(HMODULE hm = 0x%x)\n", hm); #endif } catch(...) { } // applying the lock here leads to a deadlock condition. It shouldn't actually affect the program // realistically whether we lock during a RemoveModule or not. //EnterCriticalSection(&m_csModOpLock); try { if(m_mapLoadedMods[hm] && GetModuleHandle(m_mapLoadedMods[hm]->DllName()) != hm) { #ifdef DEBUG_BUILD if(logger) logger->Log("\tModule %S [0x%p] erased from module list\n", m_mapLoadedMods[hm]->DllName(), hm); #endif // do not erase here as when module unloads GetModuleHandle returns NULL but its DllMain can still call // functions of the DLL (which call the IsAddressInLoadedModule function, which fail) #ifdef DEBUG_BUILD { WCHAR wsz[256]; //wsprintf(wsz, L"Adding module 0x%p (0x%s) to defer erase list\n", hm, m_mapLoadedMods[hm]->DllName()); wsprintf(wsz, L"Removing module 0x%p (0x%s)\n", hm, m_mapLoadedMods[hm]->DllName()); OutputDebugString(wsz); } #endif //m_listCleanupMods.push_back(m_mapLoadedMods[hm]); m_mapLoadedMods[hm] = NULL; // clearing it out suffices to unregister it } } catch(...) { } //LeaveCriticalSection(&m_csModOpLock); } void CLoadedModules::EnumLoadedModules() { HMODULE *phmProcessModules; std::map<HMODULE, CSingleLoadedModuleBase *>::const_iterator it; DWORD cLoadedModules = 0, cbBytesNeeded = 0; //EnterCriticalSection(&m_csModOpLock); EnumProcessModules(GetCurrentProcess(), NULL, 0, &cbBytesNeeded); if(!(phmProcessModules = (HMODULE *)malloc(cbBytesNeeded))) goto Cleanup; cLoadedModules = (cbBytesNeeded / sizeof(HMODULE)); if(!EnumProcessModules(GetCurrentProcess(), phmProcessModules, cbBytesNeeded, &cbBytesNeeded)) goto Cleanup; for(it = m_mapLoadedMods.begin(); it != m_mapLoadedMods.end(); it++) { //m_listCleanupMods.push_back(m_mapLoadedMods[it->first]); m_mapLoadedMods[it->first] = NULL; } for(DWORD i=0; i<cLoadedModules; i++) { AddModule(phmProcessModules[i], FALSE); } Cleanup: //LeaveCriticalSection(&m_csModOpLock); if(phmProcessModules) free(phmProcessModules); } void CLoadedModules::StorePebPointer() { PROCESS_BASIC_INFORMATION pbi = {0}; ULONG ulReturnLength = 0; if(pfnZwQueryInformationProcess && NT_SUCCESS(pfnZwQueryInformationProcess( GetCurrentProcess(), ProcessBasicInformation, &pbi, sizeof(pbi), &ulReturnLength) )) { // this information isn't integral so don't error if ZwQIP fails m_lpvPeb = reinterpret_cast<LPVOID>(pbi.PebBaseAddress); } } BOOL CLoadedModules::IsAddressInLoadedModule(LPVOID lpvAddress) { BOOL bInMod = FALSE; std::map<HMODULE, CSingleLoadedModuleBase *>::const_iterator it; CSingleLoadedModuleBase *pSlm = NULL; //EnterCriticalSection(&m_csModOpLock); for(it = m_mapLoadedMods.begin(); it != m_mapLoadedMods.end(); it++) { if((pSlm = (*it).second) != NULL) { if(lpvAddress >= pSlm->DllBase() && lpvAddress <= ((PBYTE)pSlm->DllBase() + pSlm->DllImageSize())) { bInMod = TRUE; break; } } } //LeaveCriticalSection(&m_csModOpLock); return bInMod; } BOOL CLoadedModules::IsAddressInHModule(HMODULE hmModule, LPVOID lpvAddress) { BOOL bInMod = FALSE; CSingleLoadedModuleBase *pSlm = NULL; //EnterCriticalSection(&m_csModOpLock); try { pSlm = m_mapLoadedMods[hmModule]; if(pSlm != NULL && lpvAddress >= pSlm->DllBase() && lpvAddress <= ((PBYTE)pSlm->DllBase() + pSlm->DllImageSize())) { bInMod = TRUE; } } catch(...) { } //LeaveCriticalSection(&m_csModOpLock); return bInMod; } BOOL CLoadedModules::AttachModuleHooks() { if(!m_bRemoveHooks) ModuleLoadHooks::AttachAll(); m_bRemoveHooks = TRUE; return TRUE; } BOOL CLoadedModules::RemoveModuleHooks() { if(m_bRemoveHooks) ModuleLoadHooks::DetachAll(); m_bRemoveHooks = FALSE; return TRUE; } CSingleLoadedModuleBase *CLoadedModules::FindDllWithPartialName(LPWSTR pwszPartialName) { BOOL bInMod = FALSE; std::map<HMODULE, CSingleLoadedModuleBase *>::const_iterator it; CSingleLoadedModuleBase *pSlm = NULL; //EnterCriticalSection(&m_csModOpLock); for(it = m_mapLoadedMods.begin(); it != m_mapLoadedMods.end(); it++) { if((pSlm = (*it).second) != NULL) { if(Utils::wcsistr(const_cast<WCHAR*>(pSlm->DllName()), pwszPartialName) != NULL) { goto Cleanup; } } } pSlm = NULL; Cleanup: //LeaveCriticalSection(&m_csModOpLock); return pSlm; } //#ifdef DEBUG_BUILD void CLoadedModules::DebugOutputAllModules() { WCHAR *pwszBuffer = (WCHAR *)malloc(0x1000000); pwszBuffer[0] = '\0'; std::map<HMODULE, CSingleLoadedModuleBase *>::const_iterator it; CSingleLoadedModuleBase *pSlm = NULL; EnumLoadedModules(); for(it = m_mapLoadedMods.begin(); it != m_mapLoadedMods.end(); it++) { if((pSlm = (*it).second) != NULL) { SIZE_T cch = wcslen(pwszBuffer); if(cch >= 0x1000000 - 0x1000) DebugBreak(); wsprintf( pwszBuffer + cch, L"Module: Handle [0x%p]; Base [0x%p]; Size [0x%x]; Name [%s]\r\n", it->first, pSlm->DllBase(), pSlm->DllImageSize(), pSlm->DllName() ); } } OutputDebugString(pwszBuffer); free(pwszBuffer); pwszBuffer = NULL; } //#endif extern "C" __declspec(dllexport) CLoadedModulesBase *GetLoadedModules() { return reinterpret_cast<CLoadedModulesBase *>(CLoadedModules::GetInstance()); }
21.715397
116
0.713815
y11en
327946e7065a6100efe3614c0625ad6f721a0199
20,551
cpp
C++
graphalgorithms/AStarDelay.cpp
AaronTrip/hog2
96616b40f4173959b127011c76f3e649688e1a99
[ "MIT" ]
2
2021-06-09T13:54:15.000Z
2021-07-04T13:30:46.000Z
graphalgorithms/AStarDelay.cpp
AaronTrip/hog2
96616b40f4173959b127011c76f3e649688e1a99
[ "MIT" ]
null
null
null
graphalgorithms/AStarDelay.cpp
AaronTrip/hog2
96616b40f4173959b127011c76f3e649688e1a99
[ "MIT" ]
2
2017-04-17T11:08:57.000Z
2017-04-18T08:28:27.000Z
/* * AStarDelay.cpp * hog2 * * Created by Nathan Sturtevant on 9/27/07. * Copyright 2007 __MyCompanyName__. All rights reserved. * */ #include <sys/time.h> #include <math.h> #include <cstring> #include "AStarDelay.h" using namespace AStarDelayUtil; using namespace GraphSearchConstants; const static bool verbose = false;//true; //static unsigned long tickStart; // //static unsigned long tickGen; void AStarDelay::GetPath(GraphEnvironment *_env, Graph* _g, graphState from, graphState to, std::vector<graphState> &thePath) { if (!InitializeSearch(_env,_g,from,to,thePath)) return; struct timeval t0,t1; gettimeofday(&t0,0); while(!DoSingleSearchStep(thePath)) {} gettimeofday(&t1,0); // double usedtime = t1.tv_sec-t0.tv_sec + (t1.tv_usec-t0.tv_usec)/1000000.0; //if(thePath.size() > 0) // printf("\nNodes expanded=%ld, Nodes touched=%ld, Reopenings=%ld.\n",GetNodesExpanded(),GetNodesTouched(),GetNodesReopened()); //printf("Algorithm AStarDelay, time used=%lf sec, N/sec=%lf, solution cost=%lf, solution edges=%d.\n",usedtime, GetNodesExpanded()/usedtime,solutionCost,pathSize); } bool AStarDelay::InitializeSearch(GraphEnvironment *_env, Graph* _g, graphState from, graphState to, std::vector<graphState> &thePath) { env = _env; g = _g; nodesTouched = nodesExpanded = nodesReopened = 0; metaexpanded = 0; closedSize = 0; start = from; goal = to; closedList.clear(); openQueue.reset(); delayQueue.reset(); // fQueue.reset(); thePath.clear(); //tickNewExp = tickReExp = tickBPMX = 0; //nNewExp = nReExp = nBPMX = 0; //strcpy(algname,"AStarDelay"); if ((from == UINT32_MAX) || (to == UINT32_MAX) || (from == to)) { thePath.resize(0); return false; } // step (1) SearchNode first(env->HCost(start, goal), 0, start, start); openQueue.Add(first); F = 0; return true; } bool AStarDelay::DoSingleSearchStep(std::vector<graphState> &thePath) { static int reopenCount = 0; SearchNode topNode; graphState temp; bool found = false; // printf("Reopen count: %d. Unique nodes: %ld. Log2 = %f\n", // reopenCount, nodesExpanded-nodesReopened, log2(nodesExpanded-nodesReopened)); // printf("Delay queue: %d Open queue: %d goal? %s\n", // delayQueue.size(), openQueue.size(), // (env->GoalTest(temp = openQueue.top().currNode, goal))?"yes":"no"); // if we are about to open the goal off open, but the delay queue has // lower costs, go to the delay queue first, no matter if we're allowed to // or not if ((delayQueue.size() > 0) && (openQueue.size() > 0) && (env->GoalTest(temp = openQueue.top().currNode, goal)) && (fless(delayQueue.top().gCost, openQueue.top().fCost)/*!fgreater(delayQueue.top().fCost, openQueue.top().fCost)*/)) { do { // throw out nodes with higher cost than goal topNode = delayQueue.Remove(); } while (fgreater(topNode.fCost, openQueue.top().fCost)/*!fless(topNode.fCost, openQueue.top().fCost)*/); //reopenCount = 0; nodesReopened++; found = true; } else if ((reopenCount < fDelay(nodesExpanded-nodesReopened)) && (delayQueue.size() > 0) && (openQueue.size() > 0)) { //SearchNodeCompare cmpkey; if (fless(delayQueue.top().gCost, openQueue.top().fCost) /*!cmpkey(delayQueue.top() , openQueue.top())*/ ) { topNode = delayQueue.Remove(); reopenCount++; nodesReopened++; } else { topNode = openQueue.Remove(); reopenCount = 0; } found = true; } else if ((reopenCount < fDelay(nodesExpanded-nodesReopened)) && (delayQueue.size() > 0)) { nodesReopened++; topNode = delayQueue.Remove(); reopenCount++; found = true; } // else if (fQueue.size() > 0) // { // topNode = fQueue.Remove(); // canReopen = true; // found = true; // } else if ((openQueue.size() > 0)) { F = topNode.fCost; topNode = openQueue.Remove(); reopenCount = 0; found = true; } if (found) { return DoSingleStep(topNode, thePath); } else { thePath.resize(0); // no path found! closedList.clear(); openQueue.reset(); env = 0; return true; } return false; } /* The steps refer to the pseudo codes of the corresponding algorithms */ bool AStarDelay::DoSingleStep(SearchNode &topNode, std::vector<graphState> &thePath) { nodesExpanded += 1; //if(topNode.rxp) // nReExp++; //else // nNewExp++; if (verbose) { printf("Expanding node %ld , gcost=%lf, h=%lf, f=%lf.\n", topNode.currNode, topNode.gCost, topNode.fCost-topNode.gCost, topNode.fCost); } // unsigned long tickTmp ;//= clock(); // and if there are no lower f-costs on the other open lists... // otherwise we need to delay this node if (env->GoalTest(topNode.currNode, goal)) { //printf("Found path to goal!\n"); closedList[topNode.currNode] = topNode; // this is necessary for ExtractPathToStart() ExtractPathToStart(topNode.currNode, thePath); return true; } // step (5), computing gi is delayed neighbors.resize(0); env->GetSuccessors(topNode.currNode, neighbors); //tickGen = clock() - tickTmp; bool doBPMX = false; int ichild = 0; _BPMX: if(bpmxLevel >= 1) if(doBPMX) { ReversePropX1(topNode); // counting supplement //if(nodesExpanded%2) { // nodesExpanded += 1; // if(topNode.rxp) // nReExp++; // else // nNewExp++; //} //nodesExpanded += 1; //ichild / (double)neighbors.size(); } //tickStart = clock(); double minCost = DBL_MAX; unsigned int x; for (x = 0,ichild=1; x < neighbors.size(); x++,ichild++) { nodesTouched++; double cost; if(bpmxLevel >= 1) { cost = HandleNeighborX(neighbors[x], topNode); if(cost == 0) { //if(topNode.rxp) { // tickReExp += clock() - tickStart + tickGen; // tickGen = 0; //} //else { // tickNewExp += clock() - tickStart + tickGen; // tickGen = 0; //} doBPMX = true; goto _BPMX; } if (fless(cost, minCost)) minCost = cost; } else { HandleNeighbor(neighbors[x], topNode); } } //if(topNode.rxp) { // tickReExp += clock() - tickStart + tickGen; //} //else { // tickNewExp += clock() - tickStart + tickGen; //} // path max rule (i or ii?) // this is Mero rule (b), min rule -- allen if(bpmxLevel >= 1) if (fless(topNode.fCost-topNode.gCost, minCost)) topNode.fCost = topNode.gCost+minCost; closedList[topNode.currNode] = topNode; if(bpmxLevel >= 1) if(fifo.size() > 0) { Broadcast(1,fifo.size()); // (level, levelcount) } return false; } // for BPMX void AStarDelay::ReversePropX1(SearchNode& topNode) { //tickStart = clock(); double maxh = topNode.fCost - topNode.gCost; for(unsigned int x=0;x<neighbors.size();x++) { graphState neighbor = neighbors[x]; SearchNode neighborNode = openQueue.find(SearchNode(neighbor)); if(neighborNode.currNode == neighbor) { maxh = max(maxh, (neighborNode.fCost - neighborNode.gCost) - env->GCost(topNode.currNode,neighbor)); } else { neighborNode = delayQueue.find(SearchNode(neighbor)); if(neighborNode.currNode == neighbor) { maxh = max(maxh, (neighborNode.fCost - neighborNode.gCost) - env->GCost(topNode.currNode, neighbor)); } else { NodeLookupTable::iterator iter = closedList.find(neighbor); if(iter != closedList.end()) { neighborNode = iter->second; double oh = maxh; maxh = max(maxh, (neighborNode.fCost - neighborNode.gCost) - env->GCost(topNode.currNode,neighbor)); if(bpmxLevel > 1 && oh < maxh) { fifo.push_back(neighbor); } } else { maxh = max(maxh, env->HCost(neighbor,goal) - env->GCost(topNode.currNode,neighbor)); } } } } //nBPMX++; //tickBPMX += clock() - tickStart; metaexpanded += 1; // nodesExpanded += 1; nodesTouched += neighbors.size(); topNode.fCost = maxh + topNode.gCost; } // multi level BPMX in *closed* list /* BPMX can only center around closed nodes, but open nodes can get updated as well*/ // a recursive function void AStarDelay::Broadcast(int level, int levelcount) { // we will only enque the newly updated (neighbor) nodes; or neighbor nodes being able to update others NodeLookupTable::iterator iter; SearchNode frontNode; //tickStart = clock(); for(int i=0;i<levelcount;i++) { graphState front = fifo.front(); fifo.pop_front(); iter = closedList.find(front); if(iter == closedList.end()) { frontNode = delayQueue.find(SearchNode(front)); if(frontNode.currNode != front) continue; } else frontNode = iter->second; double frontH = frontNode.fCost - frontNode.gCost; myneighbors.clear(); env->GetSuccessors(front, myneighbors); // backward pass for (unsigned int x = 0; x < myneighbors.size(); x++) { graphState neighbor = myneighbors[x]; iter = closedList.find(neighbor); if(iter != closedList.end()) { double edgeWeight = env->GCost(front,neighbor); SearchNode neighborNode = iter->second; double neighborH = neighborNode.fCost - neighborNode.gCost; if(fgreater(neighborH - edgeWeight, frontH)) { frontH = neighborH - edgeWeight; frontNode.fCost = frontNode.gCost + frontH; fifo.push_back(neighbor); } } else { SearchNode neighborNode = openQueue.find(SearchNode(neighbor)); if(neighborNode.currNode == neighbor) { double edgeWeight = env->GCost(front,neighbor); double neighborH = neighborNode.fCost - neighborNode.gCost; if(fgreater(neighborH - edgeWeight, frontH)) { frontH = neighborH - edgeWeight; frontNode.fCost = frontNode.gCost + frontH; } } else { neighborNode = delayQueue.find(SearchNode(neighbor)); if(neighborNode.currNode == neighbor) { double edgeWeight = env->GCost(front,neighbor); double neighborH = neighborNode.fCost - neighborNode.gCost; if(fgreater(neighborH - edgeWeight, frontH)) { frontH = neighborH - edgeWeight; frontNode.fCost = frontNode.gCost + frontH; fifo.push_back(neighbor); } } } } } // store frontNode closedList[front] = frontNode; // forward pass for (unsigned int x = 0; x < myneighbors.size(); x++) { graphState neighbor = myneighbors[x]; NodeLookupTable::iterator theIter = closedList.find(neighbor); if (theIter != closedList.end()) { double edgeWeight = env->GCost(front,neighbor); SearchNode neighborNode = theIter->second; double neighborH = neighborNode.fCost - neighborNode.gCost; if(fgreater(frontH - edgeWeight, neighborH)) { neighborNode.fCost = neighborNode.gCost + frontH - edgeWeight; // store neighborNode closedList[neighbor] = neighborNode; fifo.push_back(neighbor); } } else { SearchNode neighborNode = openQueue.find(SearchNode(neighbor)); if(neighborNode.currNode == neighbor) { double edgeWeight = env->GCost(front,neighbor); double neighborH = neighborNode.fCost - neighborNode.gCost; if(fgreater(frontH - edgeWeight, neighborH)) { neighborNode.fCost = neighborNode.gCost + frontH - edgeWeight; openQueue.IncreaseKey(neighborNode); } } else { neighborNode = delayQueue.find(SearchNode(neighbor)); if(neighborNode.currNode == neighbor) { double edgeWeight = env->GCost(front,neighbor); double neighborH = neighborNode.fCost - neighborNode.gCost; if(fgreater(frontH - edgeWeight, neighborH)) { neighborNode.fCost = neighborNode.gCost + frontH - edgeWeight; delayQueue.IncreaseKey(neighborNode); fifo.push_back(neighbor); } } } } } } //nBPMX += 2; //tickBPMX += clock() - tickStart; metaexpanded += 2; // nodesExpanded += 2; nodesTouched += 2*levelcount; level++; if(level < bpmxLevel && fifo.size() > 0) Broadcast(level, fifo.size()); } double AStarDelay::HandleNeighbor(graphState neighbor, SearchNode &topNode) { if (openQueue.IsIn(SearchNode(neighbor))) // in OPEN { return UpdateOpenNode(neighbor, topNode); } else if (closedList.find(neighbor) != closedList.end()) // in CLOSED { return UpdateClosedNode(neighbor, topNode); } else if (delayQueue.IsIn(SearchNode(neighbor))) // in DELAY { return UpdateDelayedNode(neighbor, topNode); } // else if (fQueue.IsIn(SearchNode(neighbor))) // in low g-cost! // { // return UpdateLowGNode(neighbor, topNode); // } else { // not opened yet return AddNewNode(neighbor, topNode); } return 0; } double AStarDelay::HandleNeighborX(graphState neighbor, SearchNode &topNode) { SearchNode neighborNode; NodeLookupTable::iterator iter; double edge = env->GCost(topNode.currNode,neighbor); double hTop = topNode.fCost - topNode.gCost; if ((neighborNode = openQueue.find(SearchNode(neighbor))).currNode == neighbor) // in OPEN { if(fgreater(neighborNode.fCost - neighborNode.gCost - edge , hTop)) { return 0; } return UpdateOpenNode(neighbor, topNode); } else if ((iter = closedList.find(neighbor)) != closedList.end()) // in CLOSED { neighborNode = iter->second; if(fgreater(neighborNode.fCost - neighborNode.gCost - edge , hTop)) { return 0; } return UpdateClosedNode(neighbor, topNode); } else if ((neighborNode = delayQueue.find(SearchNode(neighbor))).currNode == neighbor) // in DELAY { if(fgreater(neighborNode.fCost - neighborNode.gCost - edge , hTop)) { return 0; } return UpdateDelayedNode(neighbor, topNode); } // else if (fQueue.IsIn(SearchNode(neighbor))) // in low g-cost! // { // return UpdateLowGNode(neighbor, topNode); // } else { // not opened yet if(fgreater( env->HCost(neighbor,goal) - edge , hTop)) { return 0; } return AddNewNode(neighbor, topNode); } return 0; } // return edge cost + h cost double AStarDelay::AddNewNode(graphState neighbor, SearchNode &topNode) { graphState topNodeID = topNode.currNode; double edgeCost = env->GCost(topNodeID,neighbor); double gcost = topNode.gCost + edgeCost; double h = max(env->HCost(neighbor,goal), topNode.fCost - topNode.gCost - edgeCost); double fcost = gcost + h; SearchNode n(fcost, gcost, neighbor, topNodeID); n.isGoal = (neighbor == goal); // if (fless(fcost, F)) // { // fQueue.Add(n); // nodes with cost < F // } // else { openQueue.Add(n); // } return edgeCost+n.fCost-n.gCost; } // return edge cost + h cost double AStarDelay::UpdateOpenNode(graphState neighbor, SearchNode &topNode) { // lookup node SearchNode n; n = openQueue.find(SearchNode(neighbor)); double edgeCost = env->GCost(topNode.currNode, neighbor); double oldf = n.fCost; if(bpmxLevel >= 1) n.fCost = max(n.fCost , topNode.fCost - topNode.gCost - edgeCost + n.gCost); if (fless(topNode.gCost+edgeCost, n.gCost)) { n.fCost -= n.gCost; n.gCost = topNode.gCost+edgeCost; n.fCost += n.gCost; n.prevNode = topNode.currNode; if(n.fCost < oldf) openQueue.DecreaseKey(n); else openQueue.IncreaseKey(n); } else if(n.fCost > oldf) openQueue.IncreaseKey(n); // return value for pathmax return edgeCost+n.fCost-n.gCost; } // return edge cost + h cost double AStarDelay::UpdateClosedNode(graphState neighbor, SearchNode &topNode) { // lookup node SearchNode n = closedList[neighbor]; double edgeCost = env->GCost(topNode.currNode, neighbor); // check if we should update cost if (fless(topNode.gCost+edgeCost, n.gCost)) { double hCost = n.fCost - n.gCost; n.gCost = topNode.gCost+edgeCost; // do pathmax here -- update child-h to parent-h - edge cost if(bpmxLevel >= 1) hCost = max(topNode.fCost-topNode.gCost-edgeCost, hCost); n.fCost = n.gCost + hCost; n.prevNode = topNode.currNode; // put into delay list if we can open it closedList.erase(neighbor); // delete from CLOSED //n.rxp = true; delayQueue.Add(n); // add to delay list //openQueue.Add(n); } else if(bpmxLevel >= 1) if (fgreater(topNode.fCost-topNode.gCost-edgeCost, n.fCost-n.gCost)) // pathmax { n.fCost = topNode.fCost-topNode.gCost-edgeCost; n.fCost += n.gCost; closedList[neighbor] = n; if(bpmxLevel > 1) { fifo.push_back(neighbor); } } // return value for pathmax return edgeCost+n.fCost-n.gCost; } // return edge cost + h cost double AStarDelay::UpdateDelayedNode(graphState neighbor, SearchNode &topNode) { // lookup node SearchNode n; n = delayQueue.find(SearchNode(neighbor)); double edgeCost = env->GCost(topNode.currNode, neighbor); double oldf = n.fCost; if(bpmxLevel >= 1) n.fCost = max(n.fCost , topNode.fCost - topNode.gCost - edgeCost + n.gCost); if (fless(topNode.gCost+edgeCost, n.gCost)) { n.fCost -= n.gCost; n.gCost = topNode.gCost+edgeCost; n.fCost += n.gCost; n.prevNode = topNode.currNode; //if(n.fCost < oldf) delayQueue.DecreaseKey(n); //else // delayQueue.IncreaseKey(n); } else if(n.fCost > oldf) delayQueue.IncreaseKey(n); // return value for pathmax return edgeCost+n.fCost-n.gCost; } void AStarDelay::ExtractPathToStart(graphState goalNode, std::vector<graphState> &thePath) { SearchNode n; closedSize = closedList.size(); if (closedList.find(goalNode) != closedList.end()) { n = closedList[goalNode]; } else { n = openQueue.find(SearchNode(goalNode)); } solutionCost = n.gCost; do { //solutionCost += env->GCost(n.prevNode,n.currNode); thePath.push_back(n.currNode); n = closedList[n.prevNode]; } while (n.currNode != n.prevNode); //thePath.push_back(n.currNode); pathSize = thePath.size(); } // //void AStarDelay::OpenGLDraw(int) //{ // OpenGLDraw(); //} void AStarDelay::OpenGLDraw() const { // //float r,gcost,b; // double x,y,z; // SearchNode sn; // graphState nodeID; // SearchNode topn; // char buf[100]; // // // draw nodes // node_iterator ni = g->getNodeIter(); // for(node* n = g->nodeIterNext(ni); n; n = g->nodeIterNext(ni)) // { // x = n->GetLabelF(kXCoordinate); // y = n->GetLabelF(kYCoordinate); // z = n->GetLabelF(kZCoordinate); // // nodeID = (graphState) n->GetNum(); // // // if in closed // NodeLookupTable::iterator hiter; // if ((hiter = closedList.find(nodeID)) != closedList.end()) // { // sn = hiter->second; // // memset(buf,0,100); // sprintf(buf,"C %1.0f=%1.0f+%1.0f", sn.fCost, sn.gCost, (sn.fCost - sn.gCost)); // DrawText(x,y,z+0.05,0,0,0,buf); // // glColor3f(1,0,0); // red // } // // if in open // else if (openQueue.IsIn(SearchNode(nodeID))) // { // sn = openQueue.find(SearchNode(nodeID)); // memset(buf,0,100); // sprintf(buf,"O %1.0f=%1.0f+%1.0f", sn.fCost, sn.gCost, (sn.fCost - sn.gCost)); // DrawText(x,y,z+0.05,0,0,0,buf); // // glColor3f(0,0,1); // blue // } //// else if (fQueue.IsIn(SearchNode(nodeID))) //// { //// sn = fQueue.find(SearchNode(nodeID)); //// memset(buf,0,100); //// sprintf(buf,"L %1.0f=%1.0f+%1.0f", sn.fCost, sn.gCost, (sn.fCost - sn.gCost)); //// DrawText(x,y,z+0.05,0,0,0,buf); //// //// glColor3f(1,1,0); // yellow //// } // else if (delayQueue.IsIn(SearchNode(nodeID))) // { // sn = delayQueue.find(SearchNode(nodeID)); // memset(buf,0,100); // sprintf(buf,"D %1.0f=%1.0f+%1.0f", sn.fCost, sn.gCost, (sn.fCost - sn.gCost)); // DrawText(x,y,z+0.05,0,0,0,buf); // // glColor3f(1,0,1); // purple // } // // neither in open nor closed, white // else // { // glColor3f(1,1,1); // white // } // DrawSphere(x,y,z,0.025); // // // draw the text info, in black // //DrawText(x,y,z+0.05,0,0,0,buf); // } // //// draw edges // edge_iterator ei = g->getEdgeIter(); // for(edge* e = g->edgeIterNext(ei); e; e = g->edgeIterNext(ei)) // { // DrawEdge(e->getFrom(), e->getTo(), e->GetWeight()); // } } void AStarDelay::DrawText(double x, double y, double z, float r, float gg, float b, char* str) { //glPushMatrix(); // rotate ? glPushMatrix(); glColor3f(r,gg,b); glTranslatef(x,y,z); glScalef(1.0/(20*120.0), 1.0/(20*120.0), 1); glRotatef(180, 0.0, 0.0, 1.0); glRotatef(180, 0.0, 1.0, 0.0); int i=0; while(str[i]) { glutStrokeCharacter(GLUT_STROKE_ROMAN,str[i]); i++; } glPopMatrix(); } void AStarDelay::DrawEdge(unsigned int from, unsigned int to, double weight) { double x1,y1,z1; double x2,y2,z2; char buf[100] = {0}; node* nfrom = g->GetNode(from); node* nto = g->GetNode(to); x1 = nfrom->GetLabelF(kXCoordinate); y1 = nfrom->GetLabelF(kYCoordinate); z1 = nfrom->GetLabelF(kZCoordinate); x2 = nto->GetLabelF(kXCoordinate); y2 = nto->GetLabelF(kYCoordinate); z2 = nto->GetLabelF(kZCoordinate); // draw line segment glBegin(GL_LINES); glColor3f(1,1,0); // yellow glVertex3f(x1,y1,z1); glVertex3f(x2,y2,z2); glEnd(); // draw weight info sprintf(buf,"%ld",(long)weight); DrawText((x1+x2)/2, (y1+y2)/2, (z1+z2)/2 + 0.05, 1, 0, 0, buf); // in red }
25.592777
165
0.655297
AaronTrip
3279cadbf2762fb01a492333c2210a62f038189b
350
hpp
C++
srook/config/arch/SPARC.hpp
falgon/srookCppLibraries
ebcfacafa56026f6558bcd1c584ec774cc751e57
[ "MIT" ]
1
2018-07-01T07:54:37.000Z
2018-07-01T07:54:37.000Z
srook/config/arch/SPARC.hpp
falgon/srookCppLibraries
ebcfacafa56026f6558bcd1c584ec774cc751e57
[ "MIT" ]
null
null
null
srook/config/arch/SPARC.hpp
falgon/srookCppLibraries
ebcfacafa56026f6558bcd1c584ec774cc751e57
[ "MIT" ]
null
null
null
// Copyright (C) 2011-2020 Roki. Distributed under the MIT License // Detecting to pre-defined macro of [SPARC architecture](http://en.wikipedia.org/wiki/SPARC). #ifndef INCLUDED_SROOK_CONFIG_ARCH_SPARC_HPP #define INCLUDED_SROOK_CONFIG_ARCH_SPARC_HPP #include <srook/config/arch/SPARC/core.hpp> #include <srook/config/arch/SPARC/version.hpp> #endif
43.75
94
0.808571
falgon
327d7915177103e31c46d8dc5f826a0c47939658
34,215
cpp
C++
ui/widgets/shader_node_view_widget.cpp
ppearson/ImaginePartial
9871b052f2edeb023e2845578ad69c25c5baf7d2
[ "Apache-2.0" ]
1
2018-07-10T13:36:38.000Z
2018-07-10T13:36:38.000Z
ui/widgets/shader_node_view_widget.cpp
ppearson/ImaginePartial
9871b052f2edeb023e2845578ad69c25c5baf7d2
[ "Apache-2.0" ]
null
null
null
ui/widgets/shader_node_view_widget.cpp
ppearson/ImaginePartial
9871b052f2edeb023e2845578ad69c25c5baf7d2
[ "Apache-2.0" ]
null
null
null
/* Imagine Copyright 2016 Peter Pearson. 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 "shader_node_view_widget.h" #include <QGraphicsScene> #include <QGraphicsItem> #include <QPointF> #include <QGLWidget> #include <QWheelEvent> #include <QMenu> #include <QSignalMapper> #include <cmath> #include <set> #include "shading/shader_node.h" #include "shading/shader_nodes_collection.h" #include "shader_node_view_items.h" #include "shading/shader_op.h" #include "utils/string_helpers.h" #include "parameter.h" namespace Imagine { // TODO: this is a bit overly-complex, but by design the GUI stuff is completely segmented from the backing data structures // so that the GUI part isn't always needed and operates as an additional layer on top of the data structures. // But it will be possible to reduce the amount of code here eventually. ShaderNodeViewWidget::ShaderNodeViewWidget(ShaderNodeViewWidgetHost* pHost, QWidget* pParent) : QGraphicsView(pParent), m_mouseMode(eMouseNone), m_scale(0.8f), m_selectionType(eSelectionNone), m_pSelectedItem(nullptr), m_pNodesCollection(nullptr), m_pHost(pHost), m_pInteractionConnectionItem(nullptr), m_selConnectionDragType(eSelConDragNone) { // setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers | QGL::DirectRendering))); QGLFormat format = QGLFormat::defaultFormat(); format.setDepth(false); format.setSampleBuffers(true); setViewport(new QGLWidget(format)); for (unsigned int i = 0; i < 3; i++) { m_creationMenuSignalMapper[i] = nullptr; } updateCreationMenu(); // QGraphicsScene* pScene = new QGraphicsScene(this); pScene->setSceneRect(0, 0, 1600, 1600); setScene(pScene); centerOn(400, 400); setCacheMode(CacheBackground); setViewportUpdateMode(BoundingRectViewportUpdate); setViewportUpdateMode(MinimalViewportUpdate); // setViewportUpdateMode(FullViewportUpdate); setRenderHint(QPainter::Antialiasing); // setTransformationAnchor(AnchorViewCenter); setTransformationAnchor(AnchorUnderMouse); setMouseTracking(true); setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); scale(m_scale, m_scale); setMinimumSize(400, 400); } void ShaderNodeViewWidget::updateCreationMenu() { // create list of available Ops std::vector<std::string> aOpNames; m_pHost->getListOfNodeNames(aOpNames); std::vector<std::string>::const_iterator itName = aOpNames.begin(); for (; itName != aOpNames.end(); ++itName) { const std::string& name = *itName; std::string category; std::string itemName; splitInTwo(name, category, itemName, "/"); // find the category for the menu std::map<std::string, NodeCreationMenuCategory*>::iterator itFind = m_aMenuCategories.find(category); NodeCreationMenuCategory* pMenuCat = nullptr; if (itFind == m_aMenuCategories.end()) { // we haven't got this one yet, so create a new one pMenuCat = new NodeCreationMenuCategory(); m_aMenuCategories[category] = pMenuCat; } else { pMenuCat = (*itFind).second; } QAction* pNewAction = new QAction(itemName.c_str(), this); pMenuCat->nodeItems.emplace_back(NodeCreationMenuItem(category, itemName, pNewAction)); } m_aMenuCategoriesIndexed.resize(m_aMenuCategories.size()); unsigned int index = 0; std::map<std::string, NodeCreationMenuCategory*>::iterator itCat = m_aMenuCategories.begin(); for (; itCat != m_aMenuCategories.end(); ++itCat) { NodeCreationMenuCategory* pCat = (*itCat).second; pCat->index = index; if (index < 3) { QSignalMapper* pNewSignalMapper = new QSignalMapper(this); // TODO: actually, this *could* be done with a single mapping using offset indices... if (index == 0) { QObject::connect(pNewSignalMapper, SIGNAL(mapped(int)), this, SLOT(menuNewNode0(int))); } else if (index == 1) { QObject::connect(pNewSignalMapper, SIGNAL(mapped(int)), this, SLOT(menuNewNode1(int))); } else if (index == 2) { QObject::connect(pNewSignalMapper, SIGNAL(mapped(int)), this, SLOT(menuNewNode2(int))); } m_aMenuCategoriesIndexed[index] = pCat; unsigned int menuIndex = 0; // now set up the mappings for each QAction for each menu item to the signal mapper std::vector<NodeCreationMenuItem>::iterator itNodeItem = pCat->nodeItems.begin(); for (; itNodeItem != pCat->nodeItems.end(); ++itNodeItem) { NodeCreationMenuItem& menuItem = *itNodeItem; connect(menuItem.pAction, SIGNAL(triggered()), pNewSignalMapper, SLOT(map())); pNewSignalMapper->setMapping(menuItem.pAction, menuIndex++); } m_creationMenuSignalMapper[index] = pNewSignalMapper; index++; } } } ShaderNodeViewWidget::~ShaderNodeViewWidget() { } void ShaderNodeViewWidget::createUIItemsFromNodesCollection() { if (!m_pNodesCollection) return; // clear existing items QGraphicsScene* pScene = scene(); pScene->clear(); m_pSelectedItem = nullptr; m_aConnections.clear(); m_aNodes.clear(); // for the moment, use a naive two-pass approach... std::map<unsigned int, ShaderNodeUI*> aCreatedUINodes; std::vector<ShaderNode*>& nodesArray = m_pNodesCollection->getNodes(); // create the UI nodes first std::vector<ShaderNode*>::iterator itNodes = nodesArray.begin(); for (; itNodes != nodesArray.end(); ++itNodes) { ShaderNode* pNode = *itNodes; ShaderNodeUI* pNewUINode = new ShaderNodeUI(pNode); unsigned int nodeID = pNode->getNodeID(); aCreatedUINodes[nodeID] = pNewUINode; pScene->addItem(pNewUINode); m_aNodes.emplace_back(pNewUINode); } // then go back and add connections for them itNodes = nodesArray.begin(); for (; itNodes != nodesArray.end(); ++itNodes) { ShaderNode* pNode = *itNodes; unsigned int thisNodeID = pNode->getNodeID(); std::map<unsigned int, ShaderNodeUI*>::iterator itFindMain = aCreatedUINodes.find(thisNodeID); if (itFindMain == aCreatedUINodes.end()) { // something's gone wrong continue; } ShaderNodeUI* pThisUINode = (*itFindMain).second; // connect all input connections to their source output ports... const std::vector<ShaderNode::InputShaderPort>& aInputPorts = pNode->getInputPorts(); unsigned int inputIndex = 0; std::vector<ShaderNode::InputShaderPort>::const_iterator itInputPort = aInputPorts.begin(); for (; itInputPort != aInputPorts.end(); ++itInputPort, inputIndex++) { const ShaderNode::InputShaderPort& inputPort = *itInputPort; if (inputPort.connection.nodeID == ShaderNode::kNodeConnectionNone) continue; // otherwise, connect it to the output port on the source node std::map<unsigned int, ShaderNodeUI*>::iterator itFindConnectionNode = aCreatedUINodes.find(inputPort.connection.nodeID); if (itFindConnectionNode != aCreatedUINodes.end()) { ShaderNodeUI* pOutputUINode = (*itFindConnectionNode).second; ShaderConnectionUI* pConnection = new ShaderConnectionUI(pOutputUINode, pThisUINode); pConnection->setSourceNodePortIndex(inputPort.connection.portIndex); pConnection->setDestinationNodePortIndex(inputIndex); pScene->addItem(pConnection); m_aConnections.emplace_back(pConnection); pThisUINode->setInputPortConnectionItem(inputIndex, pConnection); pOutputUINode->addOutputPortConnectionItem(inputPort.connection.portIndex, pConnection); } } } } void ShaderNodeViewWidget::wheelEvent(QWheelEvent* event) { return; float scaleAmount = powf(1.15f, event->delta()); qreal scaleFactor = transform().scale(scaleAmount, scaleAmount).mapRect(QRectF(0, 0, 1, 1)).width(); if (scaleFactor < 0.07 || scaleFactor > 5.0) return; if (m_scale * scaleFactor < 0.1f || m_scale * scaleFactor > 10.0f) return; m_scale *= scaleFactor; scale(scaleFactor, scaleFactor); } void ShaderNodeViewWidget::mousePressEvent(QMouseEvent* event) { m_lastMousePos = getEventPos(event); m_lastMouseScenePos = mapToScene(event->pos()); if (event->button() == Qt::RightButton) { showRightClickMenu(event); return; } QPointF cursorScenePos = mapToScene(event->pos().x(), event->pos().y()); bool selectedSomething = false; const bool doQuick = false; if (doQuick) { QTransform dummy; QGraphicsItem* pHitItem = scene()->itemAt(event->pos(), dummy); // if (pHitItem->) if (m_pSelectedItem) { m_pSelectedItem->setSelected(false); } if (pHitItem) { m_selectionType = eSelectionNode; pHitItem->setSelected(true); m_pSelectedItem = pHitItem; } } else { if (m_pSelectedItem) { m_pSelectedItem->setSelected(false); } // doing it this way (while inefficient as no acceleration structure is used) means we only get // the Nodes. Using scene.itemAt() returns children of QGraphicsItem object (like the text items) std::vector<ShaderNodeUI*>::iterator itNodes = m_aNodes.begin(); for (; itNodes != m_aNodes.end(); ++itNodes) { ShaderNodeUI* pTestNode = *itNodes; ShaderNodeUI::SelectionInfo selInfo; if (pTestNode->doesContain(cursorScenePos, selInfo)) { if (selInfo.selectionType == ShaderNodeUI::SelectionInfo::eSelectionNode) { m_pSelectedItem = pTestNode; m_pSelectedItem->setSelected(true); selectedSomething = true; m_selectionType = eSelectionNode; } else if (selInfo.selectionType == ShaderNodeUI::SelectionInfo::eSelectionInputPort) { selectedSomething = true; m_selectionType = eSelectionEdgeInput; // see if the selected port currently has a connection attached... if (pTestNode->getInputPortConnectionItem(selInfo.portIndex)) { // it has, so we need to modify an existing connection m_selConnectionDragType = eSelConDragExistingInput; m_pInteractionConnectionItem = pTestNode->getInputPortConnectionItem(selInfo.portIndex); m_pInteractionConnectionItem->setTempMousePos(cursorScenePos); m_pInteractionConnectionItem->setDestinationNode(nullptr); m_pInteractionConnectionItem->setDestinationNodePortIndex(-1); // set the connection on the node we're disconnecting from to nullptr pTestNode->setInputPortConnectionItem(selInfo.portIndex, nullptr); // fix up backing data structure pTestNode->getActualNode()->setInputPortConnection(selInfo.portIndex, -1, -1); ShaderNode* pSrcNode = m_pInteractionConnectionItem->getSourceNode()->getActualNode(); pSrcNode->removeOutputPortConnection(m_pInteractionConnectionItem->getSourceNodePortIndex(), pTestNode->getActualNode()->getNodeID(), selInfo.portIndex); m_pSelectedItem = m_pInteractionConnectionItem; } else { // it hasn't, so create a new temporary one... m_selConnectionDragType = eSelConDragNewInput; m_pInteractionConnectionItem = new ShaderConnectionUI(nullptr, pTestNode); m_pInteractionConnectionItem->setTempMousePos(cursorScenePos); m_pInteractionConnectionItem->setDestinationNodePortIndex(selInfo.portIndex); m_pSelectedItem = m_pInteractionConnectionItem; scene()->addItem(m_pInteractionConnectionItem); } } else if (selInfo.selectionType == ShaderNodeUI::SelectionInfo::eSelectionOutputPort) { selectedSomething = true; m_selectionType = eSelectionEdgeOutput; unsigned int existingOutputConnections = pTestNode->getOutputPortConnectionCount(selInfo.portIndex); // see if the selected port currently has a connection attached... if (existingOutputConnections > 0) { // if it has, given that we're allowed to have an output port connected to multiple different // input ports/nodes, allow creating a new one by default, or if shift is held down and only one // connection exists, drag existing connection. if (existingOutputConnections == 1 && event->modifiers() & Qt::ShiftModifier) { // so modify the existing connection m_selConnectionDragType = eSelConDragExistingOutput; m_pInteractionConnectionItem = pTestNode->getSingleOutputPortConnectionItem(selInfo.portIndex); m_pInteractionConnectionItem->setTempMousePos(cursorScenePos); m_pInteractionConnectionItem->setSourceNode(nullptr); m_pInteractionConnectionItem->setSourceNodePortIndex(-1); // set the connection on the node we're disconnecting from to nullptr pTestNode->addOutputPortConnectionItem(selInfo.portIndex, nullptr); m_pSelectedItem = m_pInteractionConnectionItem; // fix up backing data structure pTestNode->getActualNode()->removeOutputPortConnection(selInfo.portIndex, m_pInteractionConnectionItem->getDestinationNode()->getActualNode()->getNodeID(), m_pInteractionConnectionItem->getDestinationNodePortIndex()); ShaderNode* pDestNode = m_pInteractionConnectionItem->getDestinationNode()->getActualNode(); pDestNode->setInputPortConnection(m_pInteractionConnectionItem->getDestinationNodePortIndex(), -1, -1); break; } } // otherwise (no connections, or more than one), just create a new connection for dragging m_selConnectionDragType = eSelConDragNewOutput; m_pInteractionConnectionItem = new ShaderConnectionUI(pTestNode, nullptr); m_pInteractionConnectionItem->setTempMousePos(cursorScenePos); m_pInteractionConnectionItem->setSourceNodePortIndex(selInfo.portIndex); pTestNode->addOutputPortConnectionItem(selInfo.portIndex, m_pInteractionConnectionItem); m_pSelectedItem = m_pInteractionConnectionItem; scene()->addItem(m_pInteractionConnectionItem); } break; } } } if (!selectedSomething) { // if we didn't select a node, see if we selected a connection... // TODO: this isn't really that efficient, might want to have another look at using // scene()->itemAt(), although that'll involve a lot of re-jigging how things are done... // build a unique list of connections std::set<ShaderConnectionUI*> aConnections; std::vector<ShaderNodeUI*>::iterator itNodes = m_aNodes.begin(); for (; itNodes != m_aNodes.end(); ++itNodes) { ShaderNodeUI* pTestNode = *itNodes; pTestNode->getConnectionItems(aConnections); } // the final closest connection info ends up specified in here... ShaderConnectionUI::SelectionInfo connSelInfo; float closestConnectionHitDistance = 25.0f; bool haveConnection = false; std::set<ShaderConnectionUI*>::iterator itConnection = aConnections.begin(); for (; itConnection != aConnections.end(); ++itConnection) { ShaderConnectionUI* pConn = *itConnection; // ignore connections which aren't fully-connected if (pConn->getDestinationNode() == nullptr || pConn->getSourceNode() == nullptr) continue; if (pConn->didHit(cursorScenePos, connSelInfo, closestConnectionHitDistance)) { haveConnection = true; // don't break out, as we want the closest connection... } } if (haveConnection) { selectedSomething = true; m_pInteractionConnectionItem = connSelInfo.pConnection; m_pInteractionConnectionItem->setTempMousePos(cursorScenePos); m_pSelectedItem = m_pInteractionConnectionItem; // so we need to disconnect the connection at the end closest to where it was clicked... if (connSelInfo.wasSource) { m_selectionType = eSelectionEdgeOutput; // disconnect the output port side (source) m_selConnectionDragType = eSelConDragExistingOutput; ShaderNodeUI* pOldSourceNode = m_pInteractionConnectionItem->getSourceNode(); unsigned int oldSourcePortIndex = m_pInteractionConnectionItem->getSourceNodePortIndex(); m_pInteractionConnectionItem->setSourceNode(nullptr); m_pInteractionConnectionItem->setSourceNodePortIndex(-1); // set the connection on the node we're disconnecting from to nullptr pOldSourceNode->removeOutputPortConnectionItem(oldSourcePortIndex, m_pInteractionConnectionItem); // fix up backing data structure - both source and destination ShaderNode* pActualSourceNode = pOldSourceNode->getActualNode(); ShaderNode* pActualDestNode = m_pInteractionConnectionItem->getDestinationNode()->getActualNode(); unsigned int destNodePortID = m_pInteractionConnectionItem->getDestinationNodePortIndex(); pActualSourceNode->removeOutputPortConnection(oldSourcePortIndex, pActualDestNode->getNodeID(), destNodePortID); pActualDestNode->setInputPortConnection(destNodePortID, -1, -1); } else { m_selectionType = eSelectionEdgeInput; // disconnect the input port side (destination) m_selConnectionDragType = eSelConDragExistingInput; ShaderNodeUI* pOldDestinationNode = m_pInteractionConnectionItem->getDestinationNode(); unsigned int oldDestinationPortIndex = m_pInteractionConnectionItem->getSourceNodePortIndex(); m_pInteractionConnectionItem->setDestinationNode(nullptr); m_pInteractionConnectionItem->setDestinationNodePortIndex(-1); // set the connection on the node we're disconnecting from to nullptr pOldDestinationNode->setInputPortConnectionItem(oldDestinationPortIndex, nullptr); // fix up backing data structure - both source and destination ShaderNode* pActualDestNode = pOldDestinationNode->getActualNode(); ShaderNode* pActualSourceNode = m_pInteractionConnectionItem->getSourceNode()->getActualNode(); unsigned int sourceNodePortID = m_pInteractionConnectionItem->getSourceNodePortIndex(); pActualSourceNode->removeOutputPortConnection(sourceNodePortID, pActualDestNode->getNodeID(), oldDestinationPortIndex); pActualDestNode->setInputPortConnection(oldDestinationPortIndex, -1, -1); } } } if (!selectedSomething && m_pSelectedItem) { m_pSelectedItem->setSelected(false); m_selectionType = eSelectionNone; m_pSelectedItem = nullptr; } if (event->modifiers() & Qt::ALT || event->button() == Qt::MiddleButton) { m_mouseMode = eMousePan; return; } if (m_pSelectedItem) { m_mouseMode = eMouseDrag; m_pSelectedItem->setSelected(true); } } void ShaderNodeViewWidget::mouseMoveEvent(QMouseEvent* event) { QPointF sceneMousePos = mapToScene(event->pos()); QPointF cursorPosition = getEventPos(event); if (m_mouseMode == eMouseNone) { } else if (m_mouseMode == eMousePan) { // float deltaMoveX = QPointF deltaMove = mapToScene(event->pos()) - m_lastMouseScenePos; // QGraphicsView::mouseMoveEvent(event); translate(deltaMove.rx(), deltaMove.ry()); // update(); } else if (m_mouseMode == eMouseDrag && m_pSelectedItem) { QPointF deltaMove = sceneMousePos - m_lastMouseScenePos; if (m_selectionType == eSelectionNode) { // TODO: is this the most efficient way of doing things? // build up a cumulative delta during move and do it on mouse release instead? ShaderNodeUI* pNode = static_cast<ShaderNodeUI*>(m_pSelectedItem); pNode->movePos(deltaMove.x(), deltaMove.y()); } else if (m_selectionType == eSelectionEdgeInput) { if (m_selConnectionDragType == eSelConDragNewInput || m_selConnectionDragType == eSelConDragExistingInput) { ShaderConnectionUI* pConnection = static_cast<ShaderConnectionUI*>(m_pSelectedItem); QPointF temp = sceneMousePos; pConnection->publicPrepareGeometryChange(); pConnection->setTempMousePos(temp); } } else if (m_selectionType == eSelectionEdgeOutput) { if (m_selConnectionDragType == eSelConDragNewOutput || m_selConnectionDragType == eSelConDragExistingOutput) { ShaderConnectionUI* pConnection = static_cast<ShaderConnectionUI*>(m_pSelectedItem); QPointF temp = sceneMousePos; pConnection->publicPrepareGeometryChange(); pConnection->setTempMousePos(temp); } } } m_lastMousePos = getEventPos(event); m_lastMouseScenePos = sceneMousePos; QGraphicsView::mousePressEvent(event); } void ShaderNodeViewWidget::mouseReleaseEvent(QMouseEvent* event) { QPointF cursorScenePos = mapToScene(event->pos().x(), event->pos().y()); if (m_selectionType == eSelectionNone) return; bool didConnectNewConnection = false; bool didReconnectExistingConnection = false; if (m_selConnectionDragType != eSelConDragNone && m_pSelectedItem != nullptr) { // we should be currently dragging a connection from a port, so work out what port we might be being // dropped on on a source node... // work out where we dropped... std::vector<ShaderNodeUI*>::iterator itNodes = m_aNodes.begin(); for (; itNodes != m_aNodes.end(); ++itNodes) { ShaderNodeUI* pTestNode = *itNodes; if (!pTestNode->isActive()) continue; ShaderNodeUI::SelectionInfo selInfo; if (!pTestNode->doesContain(cursorScenePos, selInfo)) continue; ShaderPortVariableType existingPortType = ePortTypeAny; // check we're not trying to connect to the same node which isn't allowed... if (m_pInteractionConnectionItem) { // get hold of currently existing node, which should be the other end of the connection ShaderNodeUI* pOtherNode = m_pInteractionConnectionItem->getSourceNode(); if (!pOtherNode) { pOtherNode = m_pInteractionConnectionItem->getDestinationNode(); } if (pOtherNode == pTestNode) continue; ShaderPortVariableType thisPortType = ePortTypeAny; if (selInfo.selectionType == ShaderNodeUI::SelectionInfo::eSelectionOutputPort) { thisPortType = pTestNode->getActualNode()->getOutputPort(selInfo.portIndex).type; existingPortType = pOtherNode->getActualNode()->getInputPort(m_pInteractionConnectionItem->getDestinationNodePortIndex()).type; } else if (selInfo.selectionType == ShaderNodeUI::SelectionInfo::eSelectionInputPort) { thisPortType = pTestNode->getActualNode()->getInputPort(selInfo.portIndex).type; existingPortType = pOtherNode->getActualNode()->getOutputPort(m_pInteractionConnectionItem->getSourceNodePortIndex()).type; } bool enforceConnectionTypes = true; if (thisPortType == ePortTypeAny || existingPortType == ePortTypeAny) { enforceConnectionTypes = false; } if (enforceConnectionTypes && existingPortType != thisPortType) { continue; } } if (m_selConnectionDragType == eSelConDragNewOutput && selInfo.selectionType == ShaderNodeUI::SelectionInfo::eSelectionInputPort) { // we're currently dragging from an output port (src, right side) on the source node, and have been dropped // onto an input port on the destination (left side) // see if the selected port currently has a connection attached... if (pTestNode->getInputPortConnectionItem(selInfo.portIndex)) { // it has, so we won't do anything for the moment // TODO: if Shift is held down, swap the connection with the new one? } else { // it hasn't, so connect the current interactive one which should still be // connected at the other end... m_pInteractionConnectionItem->setDestinationNode(pTestNode); m_pInteractionConnectionItem->setDestinationNodePortIndex(selInfo.portIndex); // connect to destination pTestNode->setInputPortConnectionItem(selInfo.portIndex, m_pInteractionConnectionItem); // connect to source ShaderNodeUI* pSrcNode = m_pInteractionConnectionItem->getSourceNode(); unsigned int srcNodePortID = m_pInteractionConnectionItem->getSourceNodePortIndex(); pSrcNode->addOutputPortConnectionItem(srcNodePortID, m_pInteractionConnectionItem); didConnectNewConnection = true; // leak m_pInteractionConnectionItem for the moment... // fix up the backing data structure ShaderNode* pActualSrcNode = pSrcNode->getActualNode(); ShaderNode* pActualDstNode = pTestNode->getActualNode(); pActualSrcNode->addOutputPortConnection(srcNodePortID, pActualDstNode->getNodeID(), selInfo.portIndex); pActualDstNode->setInputPortConnection(selInfo.portIndex, pActualSrcNode->getNodeID(), srcNodePortID); } } else if (m_selConnectionDragType == eSelConDragExistingInput && selInfo.selectionType == ShaderNodeUI::SelectionInfo::eSelectionInputPort) { // we're dragging the input connection (left side of node) from an existing connection to a new one, so we're modifying // where the new destination of this connection should be m_pInteractionConnectionItem->setDestinationNode(pTestNode); m_pInteractionConnectionItem->setDestinationNodePortIndex(selInfo.portIndex); pTestNode->setInputPortConnectionItem(selInfo.portIndex, m_pInteractionConnectionItem); ShaderNodeUI* pSrcNode = m_pInteractionConnectionItem->getSourceNode(); unsigned int srcNodePortID = m_pInteractionConnectionItem->getSourceNodePortIndex(); pSrcNode->addOutputPortConnectionItem(srcNodePortID, m_pInteractionConnectionItem); // alter backing data structure ShaderNode* pActualSrcNode = pSrcNode->getActualNode(); ShaderNode* pActualDstNode = pTestNode->getActualNode(); pActualSrcNode->addOutputPortConnection(srcNodePortID, pActualDstNode->getNodeID(), selInfo.portIndex); pActualDstNode->setInputPortConnection(selInfo.portIndex, pActualSrcNode->getNodeID(), srcNodePortID); didReconnectExistingConnection = true; } else if (m_selConnectionDragType == eSelConDragNewInput && selInfo.selectionType == ShaderNodeUI::SelectionInfo::eSelectionOutputPort) { // we're currently dragging from an input port (destination, left side) on destination node, // and have been dropped onto an output port on the source (right side) // we support multiple connections on output ports m_pInteractionConnectionItem->setSourceNode(pTestNode); m_pInteractionConnectionItem->setSourceNodePortIndex(selInfo.portIndex); // connect source pTestNode->addOutputPortConnectionItem(selInfo.portIndex, m_pInteractionConnectionItem); // connect to destination ShaderNodeUI* pDstNode = m_pInteractionConnectionItem->getDestinationNode(); unsigned int dstNodePortID = m_pInteractionConnectionItem->getDestinationNodePortIndex(); pDstNode->setInputPortConnectionItem(dstNodePortID, m_pInteractionConnectionItem); didConnectNewConnection = true; // leak m_pInteractionConnectionItem for the moment... // fix up the backing data structure ShaderNode* pActualSrcNode = pTestNode->getActualNode(); ShaderNode* pActualDstNode = pDstNode->getActualNode(); pActualSrcNode->addOutputPortConnection(selInfo.portIndex, pActualDstNode->getNodeID(), dstNodePortID); pActualDstNode->setInputPortConnection(dstNodePortID, pActualSrcNode->getNodeID(), selInfo.portIndex); } else if (m_selConnectionDragType == eSelConDragExistingOutput && selInfo.selectionType == ShaderNodeUI::SelectionInfo::eSelectionOutputPort) { // we're dragging the output connection (right side of node) from an existing connection to a new one, so we're modifying // where the new source of this connection should be m_pInteractionConnectionItem->setSourceNode(pTestNode); m_pInteractionConnectionItem->setSourceNodePortIndex(selInfo.portIndex); pTestNode->addOutputPortConnectionItem(selInfo.portIndex, m_pInteractionConnectionItem); // connect to destination ShaderNodeUI* pDstNode = m_pInteractionConnectionItem->getDestinationNode(); unsigned int dstNodePortID = m_pInteractionConnectionItem->getDestinationNodePortIndex(); pDstNode->setInputPortConnectionItem(dstNodePortID, m_pInteractionConnectionItem); // fix up the backing data structure ShaderNode* pActualSrcNode = pTestNode->getActualNode(); ShaderNode* pActualDstNode = pDstNode->getActualNode(); pActualSrcNode->addOutputPortConnection(selInfo.portIndex, pActualDstNode->getNodeID(), dstNodePortID); pActualDstNode->setInputPortConnection(dstNodePortID, pActualSrcNode->getNodeID(), selInfo.portIndex); didReconnectExistingConnection = true; } break; m_selectionType = eSelectionNone; } } if (m_selectionType != eSelectionNode) { m_pSelectedItem = nullptr; m_selectionType = eSelectionNone; m_selConnectionDragType = eSelConDragNone; } m_mouseMode = eMouseNone; if (m_pInteractionConnectionItem) { m_pInteractionConnectionItem->setSelected(false); } // clean up any undropped connections... // TODO: this is pretty crap... if (didConnectNewConnection) { // m_pIneractionConnectionItem has now been made into a full connection } else if (didReconnectExistingConnection) { // an existing connection was re-connected to another node/port } else { // TODO: need to work out what to do with this // seems really bad having these allocated per-mouse down on ports... - lots of scope for // memory leaks... if (m_pInteractionConnectionItem) { // this connection is going to be discarded as it's been unconnected (dragged from a port to an empty location) // we need to change the connection state within the nodes, so they don't think they're connected any more ShaderNodeUI* pDstNode = m_pInteractionConnectionItem->getDestinationNode(); if (pDstNode) { unsigned int originalPortIndex = m_pInteractionConnectionItem->getDestinationNodePortIndex(); pDstNode->setInputPortConnectionItem(originalPortIndex, nullptr); m_pInteractionConnectionItem->setDestinationNode(nullptr); } ShaderNodeUI* pSrcNode = m_pInteractionConnectionItem->getSourceNode(); if (pSrcNode) { unsigned int originalPortIndex = m_pInteractionConnectionItem->getSourceNodePortIndex(); pSrcNode->addOutputPortConnectionItem(originalPortIndex, nullptr); m_pInteractionConnectionItem->setSourceNode(nullptr); } // just deleting the object is good enough, as QGraphicsItem's destructor calls // QGraphicsScene's removeItem() function, so we don't need to do it ourselves.. delete m_pInteractionConnectionItem; } } m_pInteractionConnectionItem = nullptr; if (didConnectNewConnection || didReconnectExistingConnection) { // trigger a re-draw, so any just dropped connections snap into place... invalidateScene(); } QGraphicsView::mouseReleaseEvent(event); } void ShaderNodeViewWidget::mouseDoubleClickEvent(QMouseEvent* event) { m_lastMousePos = getEventPos(event); m_lastMouseScenePos = mapToScene(event->pos()); QPointF cursorScenePos = mapToScene(event->pos().x(), event->pos().y()); bool selectedSomething = false; if (m_pSelectedItem) { m_pSelectedItem->setSelected(false); } ShaderNodeUI* pClickedNode = nullptr; // doing it this way (while inefficient as no acceleration structure is used) means we only get // the Nodes. Using scene.itemAt() returns children of QGraphicsItem object (like the text items) std::vector<ShaderNodeUI*>::iterator itNodes = m_aNodes.begin(); for (; itNodes != m_aNodes.end(); ++itNodes) { ShaderNodeUI* pTestNode = *itNodes; ShaderNodeUI::SelectionInfo selInfo; if (pTestNode->doesContain(cursorScenePos, selInfo)) { if (selInfo.selectionType == ShaderNodeUI::SelectionInfo::eSelectionNode) { m_pSelectedItem = pTestNode; m_pSelectedItem->setSelected(true); selectedSomething = true; m_selectionType = eSelectionNode; pClickedNode = pTestNode; } } } if (!selectedSomething && m_pSelectedItem) { m_pSelectedItem->setSelected(false); m_selectionType = eSelectionNone; m_pSelectedItem = nullptr; return; } // do stuff with the node that was double-clicked ShaderNode* pNode = pClickedNode->getActualNode(); ParametersInterface* pNodeParametersInterface = pNode->getOpParametersInterface(); ParametersInterface* pParamInterface = dynamic_cast<ParametersInterface*>(m_pSelectedItem); if (pNodeParametersInterface) { m_pHost->showParametersPanelForOp(pNodeParametersInterface); } } void ShaderNodeViewWidget::showRightClickMenu(QMouseEvent* event) { // work out what type of menu we should show std::vector<std::string> aNodeCategories; m_pHost->getAllowedCreationCategories(aNodeCategories); QMenu menu(this); QMenu* pNewNodeMenu = menu.addMenu("New node..."); std::vector<std::string>::iterator itCats = aNodeCategories.begin(); for (; itCats != aNodeCategories.end(); ++itCats) { const std::string& category = *itCats; std::map<std::string, NodeCreationMenuCategory*>::iterator itFind = m_aMenuCategories.find(category); if (itFind == m_aMenuCategories.end()) { continue; } NodeCreationMenuCategory* pMenuCat = (*itFind).second; QMenu* pCatMenu = pNewNodeMenu->addMenu(category.c_str()); std::vector<NodeCreationMenuItem>::iterator itMenu = pMenuCat->nodeItems.begin(); for (; itMenu != pMenuCat->nodeItems.end(); ++itMenu) { NodeCreationMenuItem& menuItem = *itMenu; pCatMenu->addAction(menuItem.pAction); } } menu.addSeparator(); menu.exec(event->globalPos()); } QPointF ShaderNodeViewWidget::getEventPos(QMouseEvent* event) const { #ifdef IMAGINE_QT_5 return event->localPos(); #else return event->posF(); #endif } void ShaderNodeViewWidget::createNewNodeMenu(unsigned int categoryIndex, int menuIndex) { NodeCreationMenuCategory* pCat = m_aMenuCategoriesIndexed[categoryIndex]; NodeCreationMenuItem& item = pCat->nodeItems[menuIndex]; ShaderOp* pNewOp = m_pHost->createNewShaderOp(item.category, item.name); ShaderNode* pNewNode = new ShaderNode(pNewOp); pNewNode->setName(pNewOp->getOpTypeName()); m_pNodesCollection->addNode(pNewNode); ShaderNodeUI* pNewUINode = new ShaderNodeUI(pNewNode); pNewUINode->setCustomPos(m_lastMouseScenePos.rx(), m_lastMouseScenePos.ry()); m_aNodes.emplace_back(pNewUINode); scene()->addItem(pNewUINode); } void ShaderNodeViewWidget::menuNewNode0(int index) { createNewNodeMenu(0, index); } void ShaderNodeViewWidget::menuNewNode1(int index) { createNewNodeMenu(1, index); } void ShaderNodeViewWidget::menuNewNode2(int index) { createNewNodeMenu(2, index); } } // namespace Imagine
33.218447
143
0.747596
ppearson
327fd8dbe0781f7afc1f824ea50758bf3a8adec5
68,259
cpp
C++
src/rf_cavity.cpp
PierreSchnizer/FLAME
44f42c6175be536236058452bec71c87a138710e
[ "MIT" ]
10
2016-04-04T20:14:25.000Z
2022-02-17T22:37:49.000Z
src/rf_cavity.cpp
PierreSchnizer/FLAME
44f42c6175be536236058452bec71c87a138710e
[ "MIT" ]
24
2016-04-07T19:23:31.000Z
2022-03-21T14:31:14.000Z
src/rf_cavity.cpp
PierreSchnizer/FLAME
44f42c6175be536236058452bec71c87a138710e
[ "MIT" ]
13
2016-04-13T13:26:36.000Z
2019-12-20T01:55:24.000Z
#include <fstream> #include <boost/lexical_cast.hpp> #include <boost/filesystem.hpp> #include "flame/constants.h" #include "flame/moment.h" #include "flame/moment_sup.h" #include "flame/rf_cavity.h" #include "flame/config.h" #define sqr(x) ((x)*(x)) #define cube(x) ((x)*(x)*(x)) #ifdef DEFPATH #define defpath DEFPATH #else #define defpath "." #endif std::map<std::string,boost::shared_ptr<Config> > ElementRFCavity::CavConfMap; // RF Cavity beam dynamics functions. static double ipow(double base, int exp) { double result = 1.0; while (exp) { if (exp & 1) result *= base; exp >>= 1; base *= base; } return result; } static // Evaluate the beam energy and phase in the acceleration gap. void EvalGapModel(const double dis, const double IonW0, const Particle &real, const double IonFy0, const double k, const double Lambda, const double Ecen, const double T, const double S, const double Tp, const double Sp, const double V0, double &IonW_f, double &IonFy_f); static // Calculate driven phase from synchronous phase which defined by sinusoidal fitting. double GetCavPhase(const int cavi, const Particle& ref, const double IonFys, const double multip, const std::vector<double>& P); static // Calculate driven phase from synchronous phase which defined by complex fitting (e.g. peak-base model). double GetCavPhaseComplex(const Particle& ref, const double IonFys, const double scale, const double multip, const std::vector<double>& P); void CavDataType::show(std::ostream& strm, const int k) const { strm << std::scientific << std::setprecision(5) << std::setw(13) << s[k] << std::setw(13) << Elong[k] << "\n"; } void CavDataType::show(std::ostream& strm) const { for (unsigned int k = 0; k < s.size(); k++) show(strm, k); } void CavTLMLineType::clear(void) { s.clear(); Elem.clear(); E0.clear(); T.clear(); S.clear(); Accel.clear(); } void CavTLMLineType::set(const double s, const std::string &Elem, const double E0, const double T, const double S, const double Accel) { this->s.push_back(s); this->Elem.push_back(Elem); this->E0.push_back(E0); this->T.push_back(T); this->S.push_back(S); this->Accel.push_back(Accel); } void CavTLMLineType::show(const int k) const { FLAME_LOG(FINE) << std::fixed << std::setprecision(5) << std::setw(9) << s[k] << std::setw(10) << Elem[k] << std::scientific << std::setprecision(10) << std::setw(18) << T[k] << std::setw(18) << S[k] << std::setw(18) << Accel[k] << "\n"; } void CavTLMLineType::show() const { for (unsigned int k = 0; k < s.size(); k++) show(k); } int get_column(const std::string &str) { int column; if (str == "CaviMlp_EFocus1") column = 3; else if (str == "CaviMlp_EFocus2") column = 4; else if (str == "CaviMlp_EDipole") column = 2; else if (str == "CaviMlp_EQuad") column = 5; else if (str == "CaviMlp_HMono") column = 7; else if (str == "CaviMlp_HDipole") column = 6; else if (str == "CaviMlp_HQuad") column = 8; else { throw std::runtime_error(SB()<<"get_column: undef. column: " << str); } return column; } void calTransfac(const numeric_table& fldmap, int column_no, const int gaplabel, const double IonK, const bool half, double &Ecenter, double &T, double &Tp, double &S, double &Sp, double &V0) { // Compute electric center, amplitude, and transit time factors [T, Tp, S, Sp] for RF cavity mode. int n, k; double len, dz, eml, em_mom; std::vector<double> z, EM; column_no--; // F*** fortran assert(column_no>0); n = fldmap.table.size1(); if(n<=0 || (size_t)column_no>=fldmap.table.size2()) throw std::runtime_error("field map size invalid"); z.resize(n); EM.resize(n); std::copy(fldmap.table.find1(2, 0, 0), fldmap.table.find1(2, n, 0), z.begin()); std::copy(fldmap.table.find1(2, 0, column_no), fldmap.table.find1(2, n, column_no), EM.begin()); // Used at end of function. len = z[n-1]; if (half) n = (int)round((n-1)/2e0); dz = (z[n-1]-z[0])/(n-1); // prt_data(z, EM); // Start at zero. for (k = n-1; k >= 0; k--) z[k] -= z[0]; eml = 0e0, em_mom = 0e0; for (k = 0; k < n-1; k++) { eml += (fabs(EM[k])+fabs(EM[k+1]))/2e0*dz; em_mom += (z[k]+z[k+1])/2e0*(fabs(EM[k])+fabs(EM[k+1]))/2e0*dz; } Ecenter = em_mom/eml; for (k = 0; k < n; k++) z[k] -= Ecenter; T = 0; for (k = 0; k < n-1; k++) T += (EM[k]+EM[k+1])/2e0*cos(IonK*(z[k]+z[k+1])/2e0)*dz; T /= eml; Tp = 0; for (k = 0; k < n-1; k++) Tp -= ((z[k]+z[k+1])/2e0)*(EM[k]+EM[k+1])/2e0*sin(IonK*(z[k]+z[k+1])/2e0)*dz; Tp /= eml; S = 0e0; for (k = 0; k < n-1; k++) S += (EM[k]+EM[k+1])/2e0*sin(IonK*(z[k]+z[k+1])/2e0)*(z[k+1]-z[k]); S /= eml; Sp = 0e0; for (k = 0; k < n-1; k++) { Sp += (z[k]+z[k+1])/2e0*(EM[k]+EM[k+1])/2e0*cos(IonK*(z[k]+z[k+1])/2e0)*dz; } Sp /= eml; V0 = eml/MeVtoeV/MtoMM; if (gaplabel == 2) { // Second gap. Ecenter = len - Ecenter; T = -T; Tp = -Tp; } } double PwrSeries(const double beta, const double a0, const double a1, const double a2, const double a3, const double a4, const double a5, const double a6, const double a7, const double a8, const double a9) { int k; double f; const int n = 10; const double a[] = {a0, a1, a2, a3, a4, a5, a6, a7, a8, a9}; f = a[0]; for (k = 1; k < n; k++) f += a[k]*pow(beta, k); return f; } void ElementRFCavity::TransFacts(const int cavilabel, double beta, const double CaviIonK, const int gaplabel, const double EfieldScl, double &Ecen, double &T, double &Tp, double &S, double &Sp, double &V0) const { // Evaluate Electric field center, transit factors [T, T', S, S'] and cavity field. std::ostringstream strm; // For debugging of TTF function. if (forcettfcalc) { calTransfac(CavData, 2, gaplabel, CaviIonK, true, Ecen, T, Tp, S, Sp, V0); V0 *= EfieldScl; return; } switch (cavilabel) { case 41: if (beta < 0.025 || beta > 0.08) { FLAME_LOG(DEBUG) << "*** TransFacts: CaviIonK out of Range " << cavilabel << "\n"; calTransfac(CavData, 2, gaplabel, CaviIonK, true, Ecen, T, Tp, S, Sp, V0); V0 *= EfieldScl; return; } switch (gaplabel) { case 0: // One gap evaluation. Ecen = 120.0; // [mm]. T = 0.0; Tp = 0.0; S = PwrSeries(beta, -4.109, 399.9, -1.269e4, 1.991e5, -1.569e6, 4.957e6, 0.0, 0.0, 0.0, 0.0); Sp = PwrSeries(beta, 61.98, -1.073e4, 4.841e5, 9.284e6, 8.379e7, -2.926e8, 0.0, 0.0, 0.0, 0.0); V0 = 0.98477*EfieldScl; break; case 1: // Two gap calculation, first gap. Ecen = 0.0006384*pow(beta, -1.884) + 86.69; T = PwrSeries(beta, 0.9232, -123.2, 3570, -5.476e4, 4.316e5, -1.377e6, 0.0, 0.0, 0.0, 0.0); Tp = PwrSeries(beta, 1.699, 924.7, -4.062e4, 7.528e5, -6.631e6, 2.277e7, 0.0, 0.0, 0.0, 0.0); S = 0.0; Sp = PwrSeries(beta, -1.571, 25.59, 806.6, -2.98e4, 3.385e5, -1.335e6, 0.0, 0.0, 0.0, 0.0); V0 = 0.492385*EfieldScl; break; case 2: // Two gap calculation, second gap. Ecen = -0.0006384*pow(beta, -1.884) + 33.31; T = PwrSeries(beta, -0.9232, 123.2, -3570, 5.476e4, -4.316e5, 1.377e6, 0.0, 0.0, 0.0, 0.0); Tp = PwrSeries(beta, -1.699, -924.7, 4.062e4, -7.528e5, 6.631e6, -2.277e7, 0.0, 0.0, 0.0, 0.0); S = 0.0; Sp = PwrSeries(beta, -1.571, 25.59, 806.6, -2.98e4, 3.385e5, -1.335e6, 0.0, 0.0, 0.0, 0.0); V0 = 0.492385*EfieldScl; break; default: strm << "*** GetTransitFac: undef. number of gaps " << gaplabel << "\n"; throw std::runtime_error(strm.str()); } break; case 85: if (beta < 0.05 || beta > 0.25) { FLAME_LOG(DEBUG) << "*** TransFacts: CaviIonK out of Range " << cavilabel << "\n"; calTransfac(CavData, 2, gaplabel, CaviIonK, true, Ecen, T, Tp, S, Sp, V0); V0 *= EfieldScl; return; } switch (gaplabel) { case 0: Ecen = 150.0; // [mm]. T = 0.0; Tp = 0.0; S = PwrSeries(beta, -6.811, 343.9, -6385, 6.477e4, -3.914e5, 1.407e6, -2.781e6, 2.326e6, 0.0, 0.0); Sp = PwrSeries(beta, 162.7, -1.631e4, 4.315e5, -5.344e6, 3.691e7, -1.462e8, 3.109e8, -2.755e8, 0.0, 0.0); V0 = 1.967715*EfieldScl; break; case 1: Ecen = 0.0002838*pow(beta, -2.13) + 76.5; T = 0.0009467*pow(beta, -1.855) - 1.002; Tp = PwrSeries(beta, 24.44, -334, 2468, -1.017e4, 2.195e4, -1.928e4, 0.0, 0.0, 0.0, 0.0); S = 0.0; Sp = -0.0009751*pow(beta, -1.898) + 0.001568; V0 = 0.9838574*EfieldScl; break; case 2: Ecen = -0.0002838*pow(beta, -2.13) + 73.5; T = -0.0009467*pow(beta, -1.855) + 1.002; Tp = PwrSeries(beta, -24.44, 334, -2468, 1.017e4, -2.195e4, 1.928e4, 0.0, 0.0, 0.0, 0.0); S = 0.0; Sp = -0.0009751*pow(beta, -1.898) + 0.001568; V0 = 0.9838574*EfieldScl; break; default: strm << "*** GetTransitFac: undef. number of gaps " << gaplabel << "\n"; throw std::runtime_error(strm.str()); } break; case 29: if (beta < 0.15 || beta > 0.4) { FLAME_LOG(DEBUG) << "*** TransFacts: CaviIonK out of Range " << cavilabel << "\n"; calTransfac(CavData, 2, gaplabel, CaviIonK, true, Ecen, T, Tp, S, Sp, V0); V0 *= EfieldScl; return; } switch (gaplabel) { case 0: Ecen = 150.0; // [mm]. T = 0.0; Tp = 0.0; S = PwrSeries(beta, -4.285, 58.08, -248, 486, -405.6, 76.54, 0.0, 0.0, 0.0, 0.0); Sp = PwrSeries(beta, 888, -2.043e4, 1.854e5, -9.127e5, 2.695e6, -4.791e6, 4.751e6, -2.025e6, 0.0, 0.0); V0 = 2.485036*EfieldScl; break; case 1: Ecen = 0.01163*pow(beta, -2.001) + 91.77; T = 0.02166*pow(beta, -1.618) - 1.022; Tp = PwrSeries(beta, -11.25, 534.7, -3917, 1.313e4, -2.147e4, 1.389e4, 0.0, 0.0, 0.0, 0.0); S = 0.0; Sp = PwrSeries(beta, -0.8283, -4.409, 78.77, -343.9, 645.1, -454.4, 0.0, 0.0, 0.0, 0.0); V0 = 1.242518*EfieldScl; break; case 2: Ecen =-0.01163*pow(beta, -2.001) + 58.23; T =-0.02166*pow(beta, -1.618) + 1.022; Tp = PwrSeries(beta, 11.25, -534.7, 3917, -1.313e4, 2.147e4, -1.389e4, 0.0, 0.0, 0.0, 0.0); S = 0.0; Sp = PwrSeries(beta, -0.8283, -4.409, 78.77, -343.9, 645.1, -454.4, 0.0, 0.0, 0.0, 0.0); V0 = 1.242518*EfieldScl; break; default: strm << "*** GetTransitFac: undef. number of gaps " << gaplabel << "\n"; throw std::runtime_error(strm.str()); } break; case 53: if (beta < 0.3 || beta > 0.6) { FLAME_LOG(DEBUG) << "*** TransFacts: CaviIonK out of Range " << cavilabel << "\n"; calTransfac(CavData, 2, gaplabel, CaviIonK, true, Ecen, T, Tp, S, Sp, V0); V0 *= EfieldScl; return; } switch (gaplabel) { case 0: Ecen = 250.0; // [mm]. T = 0.0; Tp = 0.0; S = PwrSeries(beta, -4.222, 26.64, -38.49, -17.73, 84.12, -52.93, 0.0, 0.0, 0.0, 0.0); Sp = PwrSeries(beta, -1261, -1.413e4, 5.702e4, -1.111e5, 1.075e5, -4.167e4, 0.0, 0.0 , 0.0, 0.0); V0 = 4.25756986*EfieldScl; break; case 1: Ecen = 0.01219*pow(beta, -2.348) + 137.8; T = 0.04856*pow(beta, -1.68) - 1.018; Tp = PwrSeries(beta, -3.612, 422.8, -1973, 4081, -4109, 1641, 0.0, 0.0, 0.0, 0.0); S = 0.0; Sp = -0.03969*pow(beta, -1.775) +0.009034; V0 = 2.12878493*EfieldScl; break; case 2: Ecen = -0.01219*pow(beta, -2.348) + 112.2; T = -0.04856*pow(beta, -1.68) + 1.018; Tp = PwrSeries(beta, 3.612, -422.8, 1973, -4081, 4109, -1641, 0.0, 0.0, 0.0, 0.0); S = 0.0; Sp = -0.03969*pow(beta, -1.775) +0.009034; V0 = 2.12878493*EfieldScl; break; default: strm << "*** GetTransitFac: undef. number of gaps " << gaplabel << "\n"; throw std::runtime_error(strm.str()); } break; default: strm << "*** GetTransitFac: undef. cavity type" << "\n"; throw std::runtime_error(strm.str()); } // Convert from [mm] to [m]. // Ecen /= MtoMM; } void ElementRFCavity::TransitFacMultipole(const int cavi, const std::string &flabel, const double CaviIonK, double &T, double &S) const { double Ecen, Tp, Sp, V0; // For debugging of TTF function. if (forcettfcalc) { calTransfac(mlptable, get_column(flabel), 0, CaviIonK, false, Ecen, T, Tp, S, Sp, V0); return; } if (((cavi == 1) && (CaviIonK < 0.025 || CaviIonK > 0.055)) || ((cavi == 2) && (CaviIonK < 0.006 || CaviIonK > 0.035)) || ((cavi == 3) && (CaviIonK < 0.01687155 || CaviIonK > 0.0449908)) || ((cavi == 4) && (CaviIonK < 0.0112477 || CaviIonK > 0.0224954))) { FLAME_LOG(DEBUG) << "*** TransitFacMultipole: CaviIonK out of Range" << "\n"; calTransfac(mlptable, get_column(flabel), 0, CaviIonK, false, Ecen, T, Tp, S, Sp, V0); return; } if (flabel == "CaviMlp_EFocus1") { switch (cavi) { case 1: T = PwrSeries(CaviIonK, 1.256386e+02, -3.108322e+04, 3.354464e+06, -2.089452e+08, 8.280687e+09, -2.165867e+11, 3.739846e+12, -4.112154e+13, 2.613462e14, -7.316972e14); S = PwrSeries(CaviIonK, 1.394183e+02, -3.299673e+04, 3.438044e+06, -2.070369e+08, 7.942886e+09, -2.013750e+11, 3.374738e+12, -3.605780e+13, 2.229446e+14, -6.079177e+14); break; case 2: T = PwrSeries(CaviIonK, -9.450041e-01, -3.641390e+01, 9.926186e+03, -1.449193e+06, 1.281752e+08, -7.150297e+09, 2.534164e+11, -5.535252e+12, 6.794778e+13, -3.586197e+14); S = PwrSeries(CaviIonK, 9.928055e-02, -5.545119e+01, 1.280168e+04, -1.636888e+06, 1.279801e+08, -6.379800e+09, 2.036575e+11, -4.029152e+12, 4.496323e+13, -2.161712e+14); break; case 3: T = PwrSeries(CaviIonK, -1.000000e+00, 2.778823e-07, 6.820327e+01, 4.235106e-03, -1.926935e+03, 1.083516e+01, 2.996807e+04, 6.108642e+03, -3.864554e+05, 6.094390e+05); S = PwrSeries(CaviIonK, -4.530303e-10, 1.625011e-07, -2.583224e-05, 2.478684e+01, -1.431967e-01, -1.545412e+03, -1.569820e+02, 3.856713e+04, -3.159828e+04, -2.700076e+05); break; case 4: T = PwrSeries(CaviIonK, -1.000000e+00, -2.406447e-07, 9.480040e+01, -7.659927e-03, -4.926996e+03, -3.504383e+01, 1.712590e+05, -1.964643e+04, -4.142976e+06, 6.085390e+06); S = PwrSeries(CaviIonK, 3.958048e-11, -2.496811e-08, 7.027794e-06, -8.662787e+01, 1.246098e-01, 9.462491e+03, 4.481784e+02, -4.552412e+05, 3.026543e+05, 8.798256e+06); break; } } else if (flabel == "CaviMlp_EFocus2") { switch (cavi) { case 1: T = PwrSeries(CaviIonK, 1.038803e+00, -9.121320e+00, 8.943931e+02, -5.619149e+04, 2.132552e+06, -5.330725e+07, 8.799404e+08, -9.246033e+09, 5.612073e+10, -1.499544e+11); S = PwrSeries(CaviIonK, 1.305154e-02, -2.585211e+00, 2.696971e+02, -1.488249e+04, 5.095765e+05, -1.154148e+07, 1.714580e+08, -1.604935e+09, 8.570757e+09, -1.983302e+10); break; case 2: T = PwrSeries(CaviIonK, 9.989307e-01, 7.299233e-01, -2.932580e+02, 3.052166e+04, -2.753614e+06, 1.570331e+08, -5.677804e+09, 1.265012e+11, -1.584238e+12, 8.533351e+12); S = PwrSeries(CaviIonK, -3.040839e-03, 2.016667e+00, -4.313590e+02, 5.855139e+04, -4.873584e+06, 2.605444e+08, -8.968899e+09, 1.923697e+11, -2.339920e+12, 1.233014e+13); break; case 3: T = PwrSeries(CaviIonK, 1.000000e+00, -4.410575e-06, -8.884752e+01, -7.927594e-02, 4.663277e+03, -2.515405e+02, -1.797134e+05, -1.904305e+05, 8.999378e+06, -2.951362e+07); S = PwrSeries(CaviIonK, 6.387813e-08, -2.300899e-05, 3.676251e-03, -1.703282e+02, 2.066461e+01, 1.704569e+04, 2.316653e+04, -1.328926e+06, 4.853676e+06, 1.132796e+06); break; case 4: T = PwrSeries(CaviIonK, 1.000000e+00, -5.025186e-06, -1.468976e+02, -2.520376e-01,2.048799e+04, -2.224267e+03, -2.532091e+06, -4.613480e+06, 3.611911e+08, -1.891951e+09); S = PwrSeries(CaviIonK, -1.801149e-08, 1.123280e-05, -3.126902e-03, 4.655245e+02, -5.431878e+01, -1.477730e+05, -1.922110e+05, 2.795761e+07, -1.290046e+08, -4.656951e+08); break; } } else if (flabel == "CaviMlp_EDipole") { switch (cavi) { case 1: T = PwrSeries(CaviIonK, -1.005885e+00, 1.526489e+00, -1.047651e+02, 1.125013e+04, -4.669147e+05, 1.255841e+07, -2.237287e+08, 2.535541e+09, -1.656906e+10, 4.758398e+10); S = PwrSeries(CaviIonK, -2.586200e-02, 5.884367e+00, -6.407538e+02, 3.888964e+04, -1.488484e+06, 3.782592e+07, -6.361033e+08, 6.817810e+09, -4.227114e+10, 1.155597e+11); break; case 2: T = PwrSeries(CaviIonK, -9.999028e-01, -6.783669e-02, 1.415756e+02, -2.950990e+03, 2.640980e+05, -1.570742e+07, 5.770450e+08, -1.303686e+10, 1.654958e+11, -9.030017e+11); S = PwrSeries(CaviIonK, 2.108581e-04, -3.700608e-01, 2.851611e+01, -3.502994e+03, 2.983061e+05, -1.522679e+07, 4.958029e+08, -1.002040e+10, 1.142835e+11, -5.617061e+11); break; default: std::ostringstream strm; strm << "*** 0.29 HWR and 0.53HWR havr no dipole term\n"; throw std::runtime_error(strm.str()); break; } } else if (flabel == "CaviMlp_EQuad") { switch (cavi) { case 1: T = PwrSeries(CaviIonK, 1.038941e+00, -9.238897e+00, 9.127945e+02, -5.779110e+04, 2.206120e+06, -5.544764e+07, 9.192347e+08, -9.691159e+09, 5.896915e+10, -1.578312e+11); S = PwrSeries(CaviIonK, 1.248096e-01, -2.923507e+01, 3.069331e+03, -1.848380e+05, 7.094882e+06, -1.801113e+08, 3.024208e+09, -3.239241e+10, 2.008767e+11, -5.496217e+11); break; case 2: T = PwrSeries(CaviIonK, 1.000003e+00, -1.015639e-03, -1.215634e+02, 1.720764e+01, 3.921401e+03, 2.674841e+05, -1.236263e+07, 3.128128e+08, -4.385795e+09, 2.594631e+10); S = PwrSeries(CaviIonK, -1.756250e-05, 2.603597e-01, -2.551122e+00, -4.840638e+01, -2.870201e+04, 1.552398e+06, -5.135200e+07, 1.075958e+09, -1.277425e+10, 6.540748e+10); break; case 3: T = PwrSeries(CaviIonK, 1.000000e+00, 6.239107e-06, -1.697479e+02, 3.444883e-02, 1.225241e+04, -1.663533e+02, -5.526645e+05, -3.593353e+05, 2.749580e+07, -9.689870e+07); S = PwrSeries(CaviIonK, 2.128708e-07, -7.985618e-05, 1.240259e-02, -3.211339e+02, 7.098731e+01, 3.474652e+04, 8.187145e+04, -3.731688e+06, 1.802053e+07, -1.819958e+07); break; case 4: T = PwrSeries(CaviIonK, 9.998746e-01, -2.431292e-05, -5.019138e+02, -1.176338e+00, 1.006054e+05, -9.908805e+03, -1.148028e+07, -1.922707e+07, 1.432258e+09, -7.054482e+09); S = PwrSeries(CaviIonK, 6.003340e-08, -1.482633e-02, 1.037590e-02, -2.235440e+03, 1.790006e+02, 6.456882e+05, 6.261020e+05, -1.055477e+08, 4.110502e+08, 2.241301e+09); break; } } else if (flabel == "CaviMlp_HMono") { switch (cavi) { case 1: T = PwrSeries(CaviIonK, 1.703336e+00, -1.671357e+02, 1.697657e+04, -9.843253e+05, 3.518178e+07, -8.043084e+08, 1.165760e+10, -1.014721e+11, 4.632851e+11, -7.604796e+11); S = PwrSeries(CaviIonK, 1.452657e+01, -3.409550e+03, 3.524921e+05, -2.106663e+07, 8.022856e+08, -2.019481e+10, 3.360597e+11, -3.565836e+12, 2.189668e+13, -5.930241e+13); break; case 2: T = PwrSeries(CaviIonK, 1.003228e+00, -1.783406e+00, 1.765330e+02, -5.326467e+04, 4.242623e+06, -2.139672e+08, 6.970488e+09, -1.411958e+11, 1.617248e+12, -8.000662e+12); S = PwrSeries(CaviIonK, -1.581533e-03, 1.277444e+00, -2.742508e+02, 3.966879e+04, -3.513478e+06, 1.962939e+08, -6.991916e+09, 1.539708e+11, -1.910236e+12, 1.021016e+13); break; case 3: T = PwrSeries(CaviIonK, 9.999990e-01, 3.477993e-04, -2.717994e+02, 4.554376e+00, 3.083481e+04, 8.441315e+03, -2.439843e+06, 1.322379e+06, 1.501750e+08, -6.822135e+08); S = PwrSeries(CaviIonK, 1.709084e-06, -6.240506e-04, 1.013278e-01, -2.649338e+02, 5.944163e+02, 4.588900e+04, 7.110518e+05, -2.226574e+07, 1.658524e+08, -3.976459e+08); break; case 4: T = PwrSeries(CaviIonK, 1.000000e+00, -4.358956e-05, -7.923870e+02, -2.472669e+00, 2.241378e+05, -2.539286e+04, -3.385480e+07, -6.375134e+07, 5.652166e+09, -3.355877e+10); S = PwrSeries(CaviIonK, 1.163146e-07, -7.302018e-05, 2.048587e-02, -3.689694e+02, 3.632907e+02, 1.757838e+05, 1.327057e+06, -9.520645e+07, 9.406709e+08, -2.139562e+09); break; } } else if (flabel == "CaviMlp_HDipole") { switch (cavi) { case 1: T = PwrSeries(CaviIonK, 6.853803e-01, 7.075414e+01, -7.117391e+03, 3.985674e+05, -1.442888e+07, 3.446369e+08, -5.420826e+09, 5.414689e+10, -3.116216e+11, 7.869717e+11); S = PwrSeries(CaviIonK, 1.021102e+00, -2.441117e+02, 2.575274e+04, -1.569273e+06, 6.090118e+07, -1.562284e+09, 2.649289e+10, -2.864139e+11, 1.791634e+12, -4.941947e+12); break; case 2: T = PwrSeries(CaviIonK, 1.014129e+00, -8.016304e+00, 1.631339e+03, -2.561826e+05, 2.115355e+07, -1.118723e+09, 3.821029e+10, -8.140248e+11, 9.839613e+12, -5.154137e+13); S = PwrSeries(CaviIonK, -4.688714e-03, 3.299051e+00, -8.101936e+02, 1.163814e+05, -1.017331e+07, 5.607330e+08, -1.967300e+10, 4.261388e+11, -5.194592e+12, 2.725370e+13); break; default: std::ostringstream strm; strm << "*** 0.29 HWR and 0.53HWR have no dipole term\n"; throw std::runtime_error(strm.str()); break; } } else if (flabel == "CaviMlp_HQuad") { switch (cavi) { case 1: T = PwrSeries(CaviIonK, -1.997432e+00, 2.439177e+02, -2.613724e+04, 1.627837e+06, -6.429625e+07, 1.676173e+09, -2.885455e+10, 3.163675e+11, -2.005326e+12, 5.600545e+12); S = PwrSeries(CaviIonK, -2.470704e+00, 5.862902e+02, -6.135071e+04, 3.711527e+06, -1.431267e+08, 3.649414e+09, -6.153570e+10, 6.617859e+11, -4.119861e+12, 1.131390e+13); break; case 2: T = PwrSeries(CaviIonK, -1.000925e+00, 5.170302e-01, 9.311761e+01, 1.591517e+04, -1.302247e+06, 6.647808e+07, -2.215417e+09, 4.603390e+10, -5.420873e+11, 2.764042e+12); S = PwrSeries(CaviIonK, 3.119419e-04, -4.540868e-01, 5.433028e+01, -7.571946e+03, 6.792565e+05, -3.728390e+07, 1.299263e+09, -2.793705e+10, 3.377097e+11, -1.755126e+12); break; case 3: T = PwrSeries(CaviIonK, -9.999997e-01, -1.049624e-04, 2.445420e+02, -1.288731e+00, -2.401575e+04, -1.972894e+03, 1.494708e+06, 2.898145e+05, -8.782506e+07, 3.566907e+08); S = PwrSeries(CaviIonK, -7.925695e-07, 2.884963e-04, -4.667266e-02, 2.950936e+02, -2.712131e+02, -4.260259e+04, -3.199682e+05, 1.103376e+07, -7.304474e+07, 1.479036e+08); break; case 4: T = PwrSeries(CaviIonK, -1.000000e+00, 4.357777e-05, 7.605879e+02, 2.285787e+00, -2.009415e+05, 2.149581e+04, 2.773856e+07, 4.886782e+07, -4.127019e+09, 2.299278e+10); S = PwrSeries(CaviIonK, -1.483304e-07, 9.278457e-05, -2.592071e-02, 1.690272e+03, -4.545599e+02, -6.192487e+05, -1.632321e+06, 1.664856e+08, -1.124066e+09, -3.121299e+08); break; } } else { std::ostringstream strm; strm << "*** TransitFacMultipole: undef. multipole type " << flabel << "\n"; throw std::runtime_error(strm.str()); } } static double GetCavPhase(const int cavi, const Particle& ref, const double IonFys, const double multip, const std::vector<double>& P) { /* If the cavity is not at full power, the method gives synchrotron * phase slightly different from the nominal value. */ double IonEk, Fyc; IonEk = (ref.IonW-ref.IonEs)/MeVtoeV; switch (cavi) { case 1: Fyc = 4.394*pow(IonEk, -0.4965) - 4.731; break; case 2: Fyc = 5.428*pow(IonEk, -0.5008) + 1.6; break; case 3: Fyc = 22.35*pow(IonEk, -0.5348) + 2.026; break; case 4: Fyc = 41.43*pow(IonEk, -0.5775) + 2.59839; break; case 5: Fyc = 5.428*pow(IonEk, -0.5008) + 1.6; break; case 0: Fyc = P[0]*pow(IonEk,P[1])- P[2]; break; default: std::ostringstream strm; strm << "*** GetCavPhase: undef. cavity type" << "\n"; throw std::runtime_error(strm.str()); } return IonFys - Fyc - ref.phis*multip; } static double GetCavPhaseComplex(const Particle& ref, const double IonFys, const double scale, const double multip, const std::vector<double>& P) { double Ek, Fyc; size_t npoly = P.size()/5; if (P.size()%5 != 0) { throw std::runtime_error(SB()<<"*** Size of fitting parameter for the synchronous phase must be 5*n."); } Ek = (ref.IonW-ref.IonEs)/MeVtoeV; Fyc = 0.0; for (size_t i=0; i<npoly; i++){ Fyc += (P[5*i]*pow(Ek,P[5*i+1]) + P[5*i+2]*log(Ek) + P[5*i+3]*exp(-Ek) + P[5*i+4]) *ipow(scale, static_cast<int>(i)); } return IonFys - Fyc - ref.phis*multip; } static void EvalGapModel(const double dis, const double IonW0, const Particle &real, const double IonFy0, const double k, const double Lambda, const double Ecen, const double T, const double S, const double Tp, const double Sp, const double V0, double &IonW_f, double &IonFy_f) { double Iongamma_f, IonBeta_f, k_f; IonW_f = IonW0 + real.IonZ*V0*T*cos(IonFy0+k*Ecen)*MeVtoeV - real.IonZ*V0*S*sin(IonFy0+k*Ecen)*MeVtoeV; Iongamma_f = IonW_f/real.IonEs; IonBeta_f = sqrt(1e0-1e0/sqr(Iongamma_f)); k_f = 2e0*M_PI/(IonBeta_f*Lambda); IonFy_f = IonFy0 + k*Ecen + k_f*(dis-Ecen) + real.IonZ*V0*k*(Tp*sin(IonFy0+k*Ecen)+Sp*cos(IonFy0+k*Ecen))/(2e0*(IonW0-real.IonEs)/MeVtoeV); } ElementRFCavity::ElementRFCavity(const Config& c) :base_t(c) { ElementRFCavity::LoadCavityFile(c); } void ElementRFCavity::LoadCavityFile(const Config& c) { fRF = c.get<double>("f"); IonFys = c.get<double>("phi")*M_PI/180e0; phi_ref = std::numeric_limits<double>::quiet_NaN(); cRm = c.get<double>("Rm", 0.0); forcettfcalc = c.get<double>("forcettfcalc", 0.0)!=0.0; MpoleLevel = get_flag(c, "MpoleLevel", 2); EmitGrowth = get_flag(c, "EmitGrowth", 0); if (MpoleLevel != 0 && MpoleLevel != 1 && MpoleLevel != 2) throw std::runtime_error(SB()<< "Undefined MpoleLevel: " << MpoleLevel); if (EmitGrowth != 0 && EmitGrowth != 1) throw std::runtime_error(SB()<< "Undefined EmitGrowth: " << EmitGrowth); CavType = c.get<std::string>("cavtype"); std::string cavfile(c.get<std::string>("Eng_Data_Dir", defpath)), fldmap(cavfile), mlpfile(cavfile); if (CavType == "0.041QWR") { cavi = 1; fldmap += "/axisData_41.txt"; cavfile += "/Multipole41/thinlenlon_41.txt"; mlpfile += "/Multipole41/CaviMlp_41.txt"; } else if (CavType == "0.085QWR") { cavi = 2; fldmap += "/axisData_85.txt"; cavfile += "/Multipole85/thinlenlon_85.txt"; mlpfile += "/Multipole85/CaviMlp_85.txt"; } else if (CavType == "0.29HWR") { cavi = 3; fldmap += "/axisData_29.txt"; cavfile += "/Multipole29/thinlenlon_29.txt"; mlpfile += "/Multipole29/CaviMlp_29.txt"; } else if (CavType == "0.53HWR") { cavi = 4; fldmap += "/axisData_53.txt"; cavfile += "/Multipole53/thinlenlon_53.txt"; mlpfile += "/Multipole53/CaviMlp_53.txt"; } else if (CavType == "Generic") { DataFile = cavfile+"/"+c.get<std::string>("datafile"); cavi = 0; } else { throw std::runtime_error(SB()<<"*** InitRFCav: undef. cavity type: " << CavType); } if (cavi != 0) { numeric_table_cache *cache = numeric_table_cache::get(); try{ numeric_table_cache::table_pointer ent = cache->fetch(fldmap); CavData = *ent; if(CavData.table.size1()==0 || CavData.table.size2()<2) throw std::runtime_error("field map needs 2+ columns"); }catch(std::exception& e){ throw std::runtime_error(SB()<<"Error parsing '"<<fldmap<<"' : "<<e.what()); } try{ numeric_table_cache::table_pointer ent = cache->fetch(mlpfile); mlptable = *ent; if(mlptable.table.size1()==0 || mlptable.table.size2()<7) throw std::runtime_error("CaviMlp needs 7+ columns"); }catch(std::exception& e){ throw std::runtime_error(SB()<<"Error parsing '"<<mlpfile<<"' : "<<e.what()); } { std::ifstream fstrm(cavfile.c_str()); std::string rawline; unsigned line=0; while(std::getline(fstrm, rawline)) { line++; size_t cpos = rawline.find_first_not_of(" \t"); if(cpos==rawline.npos || rawline[cpos]=='%') continue; // skip blank and comment lines cpos = rawline.find_last_not_of("\r\n"); if(cpos!=rawline.npos) rawline = rawline.substr(0, cpos+1); std::istringstream lstrm(rawline); RawParams params; lstrm >> params.type >> params.name >> params.length >> params.aperature; bool needE0 = params.type!="drift" && params.type!="AccGap"; if(needE0) lstrm >> params.E0; else params.E0 = 0.0; if(lstrm.fail() && !lstrm.eof()) { throw std::runtime_error(SB()<<"Error parsing line '"<<line<<"' in '"<<cavfile<<"'"); } lattice.push_back(params); } if(fstrm.fail() && !fstrm.eof()) { throw std::runtime_error(SB()<<"Error, extra chars at end of file (line "<<line<<") in '"<<cavfile<<"'"); } } } else { boost::shared_ptr<Config> conf; std::string key(SB()<<DataFile<<"|"<<boost::filesystem::last_write_time(DataFile)); if ( CavConfMap.find(key) == CavConfMap.end() ) { // not found in CavConfMap try { try { GLPSParser P; conf.reset(P.parse_file(DataFile.c_str())); }catch(std::exception& e){ std::cerr<<"Parse error: "<<e.what()<<"\n"; } }catch(std::exception& e){ std::cerr<<"Error: "<<e.what()<<"\n"; } CavConfMap.insert(std::make_pair(key, conf)); } else { // found in CavConfMap conf=CavConfMap[key]; } typedef Config::vector_t elements_t; elements_t Es(conf->get<elements_t>("elements")); for(elements_t::iterator it=Es.begin(), end=Es.end(); it!=end; ++it) { const Config& EC = *it; const std::string& etype(EC.get<std::string>("type")); const double elength(EC.get<double>("L")); // fill in the lattice RawParams params; params.type = etype; params.length = elength; std::vector<double> attrs; bool notdrift = etype!="drift"; if(notdrift) { const double eV0(EC.get<double>("V0")); params.E0 = eV0; EC.tryGet<std::vector<double> >("attr", attrs); for(int i=0; i<10; i++) { params.Tfit.push_back(attrs[i]); } for(int i=0; i<10; i++) { params.Sfit.push_back(attrs[i+10]); } } bool needSynAccTab = params.type=="AccGap"; // SynAccTab should only update once if(needSynAccTab && SynAccTab.size()==0) { for(int i=0; i<3; i++) { SynAccTab.push_back(attrs[i+20]); } } lattice.push_back(params); } std::vector<double> Ez; bool checker = conf->tryGet<std::vector<double> >("Ez", Ez); if (!checker) throw std::runtime_error(SB()<<"'Ez' is missing in RF cavity file.\n"); CavData.readvec(Ez,2); conf->tryGet<double>("Rm",cRm); // Get extra parameters for complex synchronous phase definition have_RefNrm = conf->tryGet<double>("RefNorm", RefNrm); have_SynComplex = conf->tryGet<std::vector<double> >("SyncFit", SynComplex); have_EkLim = conf->tryGet<std::vector<double> >("EnergyLimit", EkLim); have_NrLim = conf->tryGet<std::vector<double> >("NormLimit", NrLim); } } void ElementRFCavity::GetCavMatParams(const int cavi, const double beta_tab[], const double gamma_tab[], const double CaviIonK[], CavTLMLineType& lineref) const { if(lattice.empty()) throw std::runtime_error("empty RF cavity lattice"); lineref.clear(); size_t i; double s=CavData.table(0,0); for(i=0; i<lattice.size(); i++) { const RawParams& P = lattice[i]; { double E0=0.0, T=0.0, S=0.0, Accel=0.0; if ((P.type != "drift") && (P.type != "AccGap")) E0 = P.E0; s+=lattice[i].length; if (P.type == "drift") { } else if (P.type == "EFocus1") { if (s < 0e0) { // First gap. By reflection 1st Gap EFocus1 is 2nd gap EFocus2. ElementRFCavity::TransitFacMultipole(cavi, "CaviMlp_EFocus2", CaviIonK[0], T, S); // First gap *1, transverse E field the same. S = -S; } else { // Second gap. ElementRFCavity::TransitFacMultipole(cavi, "CaviMlp_EFocus1", CaviIonK[1], T, S); } } else if (P.type == "EFocus2") { if (s < 0e0) { // First gap. ElementRFCavity::TransitFacMultipole(cavi, "CaviMlp_EFocus1", CaviIonK[0], T, S); S = -S; } else { // Second gap. ElementRFCavity::TransitFacMultipole(cavi, "CaviMlp_EFocus2", CaviIonK[1], T, S); } } else if (P.type == "EDipole") { if (MpoleLevel >= 1) { if (s < 0e0) { ElementRFCavity::TransitFacMultipole(cavi, "CaviMlp_EDipole", CaviIonK[0], T, S); // First gap *1, transverse E field the same. S = -S; } else { // Second gap. ElementRFCavity::TransitFacMultipole(cavi, "CaviMlp_EDipole", CaviIonK[1], T, S); } } } else if (P.type == "EQuad") { if (MpoleLevel >= 2) { if (s < 0e0) { // First gap. ElementRFCavity::TransitFacMultipole(cavi, "CaviMlp_EQuad", CaviIonK[0], T, S); S = -S; } else { // Second Gap ElementRFCavity::TransitFacMultipole(cavi, "CaviMlp_EQuad", CaviIonK[1], T, S); } } } else if (P.type == "HMono") { if (MpoleLevel >= 2) { if (s < 0e0) { // First gap. ElementRFCavity::TransitFacMultipole(cavi, "CaviMlp_HMono", CaviIonK[0], T, S); T = -T; } else { // Second Gap ElementRFCavity::TransitFacMultipole(cavi, "CaviMlp_HMono", CaviIonK[1], T, S); } } } else if (P.type == "HDipole") { if (MpoleLevel >= 1) { if (s < 0e0) { // First gap. ElementRFCavity::TransitFacMultipole(cavi, "CaviMlp_HDipole", CaviIonK[0], T, S); T = -T; } else { // Second gap. ElementRFCavity::TransitFacMultipole(cavi, "CaviMlp_HDipole", CaviIonK[1], T, S); } } } else if (P.type == "HQuad") { if (MpoleLevel >= 2) { if (s < 0e0) { // First gap. ElementRFCavity::TransitFacMultipole(cavi, "CaviMlp_HQuad", CaviIonK[0], T, S); T = -T; } else { // Second gap. ElementRFCavity::TransitFacMultipole(cavi, "CaviMlp_HQuad", CaviIonK[1], T, S); } } } else if (P.type == "AccGap") { if (s < 0e0) { // First gap. Accel = (beta_tab[0]*gamma_tab[0])/((beta_tab[1]*gamma_tab[1])); } else { // Second gap. Accel = (beta_tab[1]*gamma_tab[1])/((beta_tab[2]*gamma_tab[2])); } } else { std::ostringstream strm; strm << "*** GetCavMatParams: undef. multipole element " << P.type << "\n"; throw std::runtime_error(strm.str()); } lineref.set(s, P.type, E0, T, S, Accel); } } if (FLAME_LOG_CHECK(DEBUG)) { std::cout << "\n"; lineref.show(); } } void ElementRFCavity::GenCavMat2(const int cavi, const double dis, const double EfieldScl, const double TTF_tab[], const double beta_tab[], const double gamma_tab[], const double Lambda, Particle &real, const double IonFys[], const double Rm, state_t::matrix_t &M, const CavTLMLineType& linetab) const { /* RF cavity model, transverse only defocusing. * 2-gap matrix model. */ int seg; double k_s[3]; double Ecens[2], Ts[2], Ss[2], V0s[2], ks[2], L1, L2, L3; double beta, gamma, kfac, V0, T, S, kfdx, kfdy, dpy, Accel, IonFy; state_t::matrix_t Idmat, Mlon_L1, Mlon_K1, Mlon_L2; state_t::matrix_t Mlon_K2, Mlon_L3, Mlon, Mtrans, Mprob; // fetch the log level once to speed our loop const bool logme = FLAME_LOG_CHECK(DEBUG); const double IonA = 1e0; using boost::numeric::ublas::prod; Idmat = boost::numeric::ublas::identity_matrix<double>(PS_Dim); k_s[0] = 2e0*M_PI/(beta_tab[0]*Lambda); k_s[1] = 2e0*M_PI/(beta_tab[1]*Lambda); k_s[2] = 2e0*M_PI/(beta_tab[2]*Lambda); // Longitudinal model: Drift-Kick-Drift, dis: total lenghth centered at 0, // Ecens[0] & Ecens[1]: Electric Center position where accel kick applies, Ecens[0] < 0 // TTFtab: 2*6 vector, Ecens, T Tp S Sp, V0; Ecens[0] = TTF_tab[0]; Ts[0] = TTF_tab[1]; Ss[0] = TTF_tab[3]; V0s[0] = TTF_tab[5]; ks[0] = 0.5*(k_s[0]+k_s[1]); L1 = dis + Ecens[0]; //try change dis/2 to dis 14/12/12 Mlon_L1 = Idmat; Mlon_K1 = Idmat; // Pay attention, original is - Mlon_L1(4, 5) = -2e0*M_PI/Lambda*(1e0/cube(beta_tab[0]*gamma_tab[0])*MeVtoeV/real.IonEs*L1); // Pay attention, original is -k1-k2 Mlon_K1(5, 4) = -real.IonZ*V0s[0]*Ts[0]*sin(IonFys[0]+ks[0]*L1)-real.IonZ*V0s[0]*Ss[0]*cos(IonFys[0]+ks[0]*L1); Ecens[1] = TTF_tab[6]; Ts[1] = TTF_tab[7]; Ss[1] = TTF_tab[9]; V0s[1] = TTF_tab[11]; ks[1] = 0.5*(k_s[1]+k_s[2]); L2 = Ecens[1] - Ecens[0]; Mlon_L2 = Idmat; Mlon_K2 = Idmat; Mlon_L2(4, 5) = -2e0*M_PI/Lambda*(1e0/cube(beta_tab[1]*gamma_tab[1])*MeVtoeV/real.IonEs*L2); //Problem is Here!! Mlon_K2(5, 4) = -real.IonZ*V0s[1]*Ts[1]*sin(IonFys[1]+ks[1]*Ecens[1])-real.IonZ*V0s[1]*Ss[1]*cos(IonFys[1]+ks[1]*Ecens[1]); L3 = dis - Ecens[1]; //try change dis/2 to dis 14/12/12 Mlon_L3 = Idmat; Mlon_L3(4, 5) = -2e0*M_PI/Lambda*(1e0/cube(beta_tab[2]*gamma_tab[2])*MeVtoeV/real.IonEs*L3); Mlon = prod(Mlon_K1, Mlon_L1); Mlon = prod(Mlon_L2, Mlon); Mlon = prod(Mlon_K2, Mlon); Mlon = prod(Mlon_L3, Mlon); // std::cout<<__FUNCTION__<<" Mlon "<<Mlon<<"\n"; // Transverse model // Drift-FD-Drift-LongiKick-Drift-FD-Drift-0-Drift-FD-Drift-LongiKick-Drift-FD-Drift seg = 0; Mtrans = Idmat; Mprob = Idmat; beta = beta_tab[0]; gamma = gamma_tab[0]; IonFy = IonFys[0]; kfac = k_s[0]; V0 = 0e0, T = 0e0, S = 0e0, kfdx = 0e0, kfdy = 0e0, dpy = 0e0; size_t n; double s=CavData.table(0,0); for(n=0; n<lattice.size(); n++) { const RawParams& P = lattice[n]; s+=lattice[n].length; if (false) printf("%9.5f %8s %8s %9.5f %9.5f %9.5f\n", s, P.type.c_str(), P.name.c_str(), P.length, P.aperature, P.E0); Mprob = Idmat; if (P.type == "drift") { IonFy = IonFy + kfac*P.length; Mprob(0, 1) = P.length; Mprob(2, 3) = P.length; Mtrans = prod(Mprob, Mtrans); } else if (P.type == "EFocus1") { V0 = linetab.E0[n]*EfieldScl; T = linetab.T[n]; S = linetab.S[n]; kfdx = real.IonZ*V0/sqr(beta)/gamma/IonA/AU*(T*cos(IonFy)-S*sin(IonFy))/Rm; kfdy = kfdx; if(logme) { FLAME_LOG(FINE)<<" X EFocus1 kfdx="<<kfdx<<"\n" <<" Y "<<linetab.E0[n]<<" "<<EfieldScl<<" "<<beta <<" "<<gamma<<" "<<IonFy<<" "<<Rm<<"\n Z "<<T<<" "<<S<<"\n"; } Mprob(1, 0) = kfdx; Mprob(3, 2) = kfdy; Mtrans = prod(Mprob, Mtrans); } else if (P.type == "EFocus2") { V0 = linetab.E0[n]*EfieldScl; T = linetab.T[n]; S = linetab.S[n]; kfdx = real.IonZ*V0/sqr(beta)/gamma/IonA/AU*(T*cos(IonFy)-S*sin(IonFy))/Rm; kfdy = kfdx; if(logme) FLAME_LOG(FINE)<<" X EFocus2 kfdx="<<kfdx<<"\n"; Mprob(1, 0) = kfdx; Mprob(3, 2) = kfdy; Mtrans = prod(Mprob, Mtrans); } else if (P.type == "EDipole") { if (MpoleLevel >= 1) { V0 = linetab.E0[n]*EfieldScl; T = linetab.T[n]; S = linetab.S[n]; dpy = real.IonZ*V0/sqr(beta)/gamma/IonA/AU*(T*cos(IonFy)-S*sin(IonFy)); if(logme) FLAME_LOG(FINE)<<" X EDipole dpy="<<dpy<<"\n"; Mprob(3, 6) = dpy; Mtrans = prod(Mprob, Mtrans); } } else if (P.type == "EQuad") { if (MpoleLevel >= 2) { V0 = linetab.E0[n]*EfieldScl; T = linetab.T[n]; S = linetab.S[n]; kfdx = real.IonZ*V0/sqr(beta)/gamma/IonA/AU*(T*cos(IonFy)-S*sin(IonFy))/Rm; kfdy = -kfdx; if(logme) FLAME_LOG(FINE)<<" X EQuad kfdx="<<kfdx<<"\n"; Mprob(1, 0) = kfdx; Mprob(3, 2) = kfdy; Mtrans = prod(Mprob, Mtrans); } } else if (P.type == "HMono") { if (MpoleLevel >= 2) { V0 = linetab.E0[n]*EfieldScl; T = linetab.T[n]; S = linetab.S[n]; kfdx = -MU0*C0*real.IonZ*V0/beta/gamma/IonA/AU*(T*cos(IonFy+M_PI/2e0)-S*sin(IonFy+M_PI/2e0))/Rm; kfdy = kfdx; if(logme) FLAME_LOG(FINE)<<" X HMono kfdx="<<kfdx<<"\n"; Mprob(1, 0) = kfdx; Mprob(3, 2) = kfdy; Mtrans = prod(Mprob, Mtrans); } } else if (P.type == "HDipole") { if (MpoleLevel >= 1) { V0 = linetab.E0[n]*EfieldScl; T = linetab.T[n]; S = linetab.S[n]; dpy = -MU0*C0*real.IonZ*V0/beta/gamma/IonA/AU*(T*cos(IonFy+M_PI/2e0)-S*sin(IonFy+M_PI/2e0)); if(logme) FLAME_LOG(FINE)<<" X HDipole dpy="<<dpy<<"\n"; Mprob(3, 6) = dpy; Mtrans = prod(Mprob, Mtrans); } } else if (P.type == "HQuad") { if (MpoleLevel >= 2) { if (s < 0e0) { // First gap. beta = (beta_tab[0]+beta_tab[1])/2e0; gamma = (gamma_tab[0]+gamma_tab[1])/2e0; } else { beta = (beta_tab[1]+beta_tab[2])/2e0; gamma = (gamma_tab[1]+gamma_tab[2])/2e0; } V0 = linetab.E0[n]*EfieldScl; T = linetab.T[n]; S = linetab.S[n]; kfdx = -MU0*C0*real.IonZ*V0/beta/gamma/IonA/AU*(T*cos(IonFy+M_PI/2e0)-S*sin(IonFy+M_PI/2e0))/Rm; kfdy = -kfdx; if(logme) FLAME_LOG(FINE)<<" X HQuad kfdx="<<kfdx<<"\n"; Mprob(1, 0) = kfdx; Mprob(3, 2) = kfdy; Mtrans = prod(Mprob, Mtrans); } } else if (P.type == "AccGap") { //IonFy = IonFy + real.IonZ*V0s[0]*kfac*(TTF_tab[2]*sin(IonFy) // + TTF_tab[4]*cos(IonFy))/2/((gamma-1)*real.IonEs/MeVtoeV); //TTF_tab[2]~Tp seg = seg + 1; beta = beta_tab[seg]; gamma = gamma_tab[seg]; kfac = 2e0*M_PI/(beta*Lambda); Accel = linetab.Accel[n]; if(logme) FLAME_LOG(FINE)<<" X AccGap Accel="<<Accel<<"\n"; Mprob(1, 1) = Accel; Mprob(3, 3) = Accel; Mtrans = prod(Mprob, Mtrans); } else { std::ostringstream strm; strm << "*** GetCavMat: undef. multipole type " << P.type << "\n"; throw std::runtime_error(strm.str()); } // FLAME_LOG(FINE) << Elem << "\n"; // PrtMat(Mprob); if(logme) FLAME_LOG(FINE)<<"Elem "<<P.name<<":"<<P.type<<"\n Mtrans "<<Mtrans<<"\nMprob "<<Mprob<<"\n"; } M = Mtrans; M(4, 4) = Mlon(4, 4); M(4, 5) = Mlon(4, 5); M(5, 4) = Mlon(5, 4); M(5, 5) = Mlon(5, 5); } void ElementRFCavity::GetCavMat(const int cavi, const int cavilabel, const double Rm, Particle &real, const double EfieldScl, const double IonFyi_s, const double IonEk_s, state_t::matrix_t &M, CavTLMLineType &linetab) const { double CaviLambda, Ecen[2], T[2], Tp[2], S[2], Sp[2], V0[2]; double dis, IonW_s[3], IonFy_s[3], gamma_s[3], beta_s[3], CaviIonK_s[3]; double CaviIonK[2]; CaviLambda = C0/fRF*MtoMM; IonW_s[0] = IonEk_s + real.IonEs; IonFy_s[0] = IonFyi_s; gamma_s[0] = IonW_s[0]/real.IonEs; beta_s[0] = sqrt(1e0-1e0/sqr(gamma_s[0])); CaviIonK_s[0] = 2e0*M_PI/(beta_s[0]*CaviLambda); size_t n = CavData.table.size1(); assert(n>0); dis = (CavData.table(n-1,0)-CavData.table(0,0))/2e0; ElementRFCavity::TransFacts(cavilabel, beta_s[0], CaviIonK_s[0], 1, EfieldScl, Ecen[0], T[0], Tp[0], S[0], Sp[0], V0[0]); EvalGapModel(dis, IonW_s[0], real, IonFy_s[0], CaviIonK_s[0], CaviLambda, Ecen[0], T[0], S[0], Tp[0], Sp[0], V0[0], IonW_s[1], IonFy_s[1]); gamma_s[1] = IonW_s[1]/real.IonEs; beta_s[1] = sqrt(1e0-1e0/sqr(gamma_s[1])); CaviIonK_s[1] = 2e0*M_PI/(beta_s[1]*CaviLambda); ElementRFCavity::TransFacts(cavilabel, beta_s[1], CaviIonK_s[1], 2, EfieldScl, Ecen[1], T[1], Tp[1], S[1], Sp[1], V0[1]); EvalGapModel(dis, IonW_s[1], real, IonFy_s[1], CaviIonK_s[1], CaviLambda, Ecen[1], T[1], S[1], Tp[1], Sp[1], V0[1], IonW_s[2], IonFy_s[2]); gamma_s[2] = IonW_s[2]/real.IonEs; beta_s[2] = sqrt(1e0-1e0/sqr(gamma_s[2])); CaviIonK_s[2] = 2e0*M_PI/(beta_s[2]*CaviLambda); Ecen[0] = Ecen[0] - dis; double TTF_tab[] = {Ecen[0], T[0], Tp[0], S[0], Sp[0], V0[0], Ecen[1], T[1], Tp[1], S[1], Sp[1], V0[1]}; CaviIonK[0] = (CaviIonK_s[0]+CaviIonK_s[1])/2e0; CaviIonK[1] = (CaviIonK_s[1]+CaviIonK_s[2])/2e0; if (false) { printf("\n GetCavMat:\n"); printf("CaviIonK: %15.10f %15.10f %15.10f\n", CaviIonK_s[0], CaviIonK_s[1], CaviIonK_s[2]); printf("CaviIonK: %15.10f %15.10f\n", CaviIonK[0], CaviIonK[1]); printf("beta: %15.10f %15.10f %15.10f\n", beta_s[0], beta_s[1], beta_s[2]); printf("gamma: %15.10f %15.10f %15.10f\n", gamma_s[0], gamma_s[1], gamma_s[2]); printf("Ecen: %15.10f %15.10f\n", Ecen[0], Ecen[1]); printf("T: %15.10f %15.10f\n", T[0], T[1]); printf("Tp: %15.10f %15.10f\n", Tp[0], Tp[1]); printf("S: %15.10f %15.10f\n", S[0], S[1]); printf("Sp: %15.10f %15.10f\n", Sp[0], Sp[1]); printf("V0: %15.10f %15.10f\n", V0[0], V0[1]); } ElementRFCavity::GetCavMatParams(cavi, beta_s, gamma_s, CaviIonK, linetab); ElementRFCavity::GenCavMat2(cavi, dis, EfieldScl, TTF_tab, beta_s, gamma_s, CaviLambda, real, IonFy_s, Rm, M, linetab); } void ElementRFCavity::GetCavMatGeneric(Particle &real, const double EfieldScl, const double IonFyi_s, const double IonEk_s, state_t::matrix_t &M, CavTLMLineType &linetab) const { const double IonA = 1e0; const bool logme = FLAME_LOG_CHECK(DEBUG); state_t::matrix_t Idmat, Mlon, Mtrans,Mprob,MprobLon; Idmat = boost::numeric::ublas::identity_matrix<double>(PS_Dim); Mtrans = Idmat; Mlon = Idmat; double IonW0 = IonEk_s + real.IonEs; double gamma0 = IonW0/real.IonEs; double beta0 = sqrt(1e0-1e0/sqr(gamma0)); double IonFy0 = IonFyi_s; double CaviLambda = C0/fRF*MtoMM; double kfac0 = 2e0*M_PI/(beta0*CaviLambda); double dis = 0.0, V0 = 0.0, T = 0.0, S = 0.0, kfdx = 0.0, kfdy = 0.0, Accel = 0.0; double dpy = 0.0; double IonW=IonW0,gamma=gamma0,beta=beta0,IonFy=IonFy0,kfac=kfac0; assert(cRm>0); for(unsigned n=0; n<lattice.size(); n++) { const RawParams& P = lattice[n]; dis+=lattice[n].length; if (false) printf("%9.5f %8s %8s %9.5f %9.5f %9.5f\n", dis, P.type.c_str(), P.name.c_str(), P.length, P.aperature, P.E0); Mprob = Idmat; MprobLon = Idmat; if (P.type == "drift") { IonFy = IonFy + kfac*P.length; Mprob(0, 1) = P.length; Mprob(2, 3) = P.length; Mtrans = prod(Mprob, Mtrans); // Pay attention, original is - MprobLon(4, 5) = -2e0*M_PI/CaviLambda*(1e0/cube(beta*gamma)*MeVtoeV/real.IonEs*P.length); Mlon = prod(MprobLon, Mlon); } else if (P.type == "EFocus") { V0 = P.E0*EfieldScl; T = calFitPow(kfac,P.Tfit); S = calFitPow(kfac,P.Sfit); kfdx = real.IonZ*V0/sqr(beta)/gamma/IonA/AU*(T*cos(IonFy)-S*sin(IonFy))/cRm; kfdy = kfdx; if(logme) { FLAME_LOG(FINE)<<" X EFocus1 kfdx="<<kfdx<<"\n" <<" Y "<<linetab.E0[n]<<" "<<EfieldScl<<" "<<beta <<" "<<gamma<<" "<<IonFy<<" "<<cRm<<"\n Z "<<T<<" "<<S<<"\n"; } Mprob(1, 0) = kfdx; Mprob(3, 2) = kfdy; Mtrans = prod(Mprob, Mtrans); } else if (P.type == "EDipole") { if (MpoleLevel >= 1) { V0 = P.E0*EfieldScl; T = calFitPow(kfac,P.Tfit); S = calFitPow(kfac,P.Sfit); dpy = real.IonZ*V0/sqr(beta)/gamma/IonA/AU*(T*cos(IonFy)-S*sin(IonFy)); if(logme) FLAME_LOG(FINE)<<" X EDipole dpy="<<dpy<<"\n"; Mprob(3, 6) = dpy; Mtrans = prod(Mprob, Mtrans); } } else if (P.type == "EQuad") { if (MpoleLevel >= 2) { V0 = P.E0*EfieldScl; T = calFitPow(kfac,P.Tfit); S = calFitPow(kfac,P.Sfit); kfdx = real.IonZ*V0/sqr(beta)/gamma/IonA/AU*(T*cos(IonFy)-S*sin(IonFy))/cRm; kfdy = -kfdx; if(logme) FLAME_LOG(FINE)<<" X EQuad kfdx="<<kfdx<<"\n"; Mprob(1, 0) = kfdx; Mprob(3, 2) = kfdy; Mtrans = prod(Mprob, Mtrans); } } else if (P.type == "HMono") { if (MpoleLevel >= 2) { V0 = P.E0*EfieldScl; T = calFitPow(kfac,P.Tfit); S = calFitPow(kfac,P.Sfit); kfdx = -MU0*C0*real.IonZ*V0/beta/gamma/IonA/AU*(T*cos(IonFy+M_PI/2e0)-S*sin(IonFy+M_PI/2e0))/cRm; kfdy = kfdx; if(logme) FLAME_LOG(FINE)<<" X HMono kfdx="<<kfdx<<"\n"; Mprob(1, 0) = kfdx; Mprob(3, 2) = kfdy; Mtrans = prod(Mprob, Mtrans); } } else if (P.type == "HDipole") { if (MpoleLevel >= 1) { V0 = P.E0*EfieldScl; T = calFitPow(kfac,P.Tfit); S = calFitPow(kfac,P.Sfit); dpy = -MU0*C0*real.IonZ*V0/beta/gamma/IonA/AU*(T*cos(IonFy+M_PI/2e0)-S*sin(IonFy+M_PI/2e0)); if(logme) FLAME_LOG(FINE)<<" X HDipole dpy="<<dpy<<"\n"; Mprob(3, 6) = dpy; Mtrans = prod(Mprob, Mtrans); } } else if (P.type == "HQuad") { if (MpoleLevel >= 2) { V0 = P.E0*EfieldScl; T = calFitPow(kfac,P.Tfit); S = calFitPow(kfac,P.Sfit); kfdx = -MU0*C0*real.IonZ*V0/beta/gamma/IonA/AU*(T*cos(IonFy+M_PI/2e0)-S*sin(IonFy+M_PI/2e0))/cRm; kfdy = -kfdx; if(logme) FLAME_LOG(FINE)<<" X HQuad kfdx="<<kfdx<<"\n"; Mprob(1, 0) = kfdx; Mprob(3, 2) = kfdy; Mtrans = prod(Mprob, Mtrans); } } else if (P.type == "AccGap") { V0 = P.E0*EfieldScl; T = calFitPow(kfac,P.Tfit); S = calFitPow(kfac,P.Sfit); IonW=IonW+real.IonZ*V0*MeVtoeV*T*cos(IonFy)-real.IonZ*V0*MeVtoeV*S*sin(IonFy); double gamma_f=IonW/real.IonEs; double beta_f=sqrt(1.0-1.0/(gamma_f*gamma_f)); kfac = 2e0*M_PI/(beta_f*CaviLambda); Accel = (beta*gamma)/((beta_f*gamma_f)); if(logme) FLAME_LOG(FINE)<<" X AccGap Accel="<<Accel<<"\n"; Mprob(1, 1) = Accel; Mprob(3, 3) = Accel; Mtrans = prod(Mprob, Mtrans); MprobLon(5, 4) = -real.IonZ*V0*T*sin(IonFy)-real.IonZ*V0*S*cos(IonFy); Mlon = prod(MprobLon, Mlon); beta=beta_f; gamma=gamma_f; } else { std::ostringstream strm; strm << "*** GetCavMat: undef. multipole type " << P.type << "\n"; throw std::runtime_error(strm.str()); } // FLAME_LOG(FINE) << Elem << "\n"; // PrtMat(Mprob); if(logme) FLAME_LOG(FINE)<<"Elem "<<P.name<<":"<<P.type<<"\n Mtrans "<<Mtrans<<"\nMprob "<<Mprob<<"\n"; } M = Mtrans; M(4, 4) = Mlon(4, 4); M(4, 5) = Mlon(4, 5); M(5, 4) = Mlon(5, 4); M(5, 5) = Mlon(5, 5); } double ElementRFCavity::calFitPow(double kfac,const std::vector<double>& Tfit) const { int order=Tfit.size(); double res=0.0; for (int ii=0; ii<order; ii++) { res=res+Tfit[ii]*ipow(kfac,order-ii-1); } return res; } void ElementRFCavity::GetCavBoost(const numeric_table &CavData, Particle &state, const double IonFy0, const double EfieldScl, double &IonFy) const { size_t n = CavData.table.size1(); assert(n>1); const bool logme = FLAME_LOG_CHECK(DEBUG); const double dis = CavData.table(n-1, 0) - CavData.table(0, 0), dz = dis/(n-1), CaviLambda = C0/fRF*MtoMM; // assumes dz is constant even though CavData contains actual z positions are available FLAME_LOG(DEBUG)<<__FUNCTION__ <<" IonFy0="<<IonFy0 <<" fRF="<<fRF <<" EfieldScl="<<EfieldScl <<" state="<<state <<"\n"; IonFy = IonFy0; // Sample rate is different for RF Cavity; due to different RF frequencies. // IonK = state.SampleIonK; double CaviIonK = 2e0*M_PI*fRF/(state.beta*C0*MtoMM); for (size_t k = 0; k < n-1; k++) { double IonFylast = IonFy; IonFy += CaviIonK*dz; state.IonW += state.IonZ*EfieldScl*(CavData.table(k,1)+CavData.table(k+1,1))/2e0 *cos((IonFylast+IonFy)/2e0)*dz/MtoMM; double IonGamma = state.IonW/state.IonEs; double IonBeta = sqrt(1e0-1e0/sqr(IonGamma)); if ((state.IonW-state.IonEs) < 0e0) { state.IonW = state.IonEs; IonBeta = 0e0; //TODO: better handling of this error? // will be divide by zero (NaN) } CaviIonK = 2e0*M_PI/(IonBeta*CaviLambda); if(logme) FLAME_LOG(DEBUG)<<" "<<k<<" CaviIonK="<<CaviIonK<<" IonW="<<state.IonW<<"\n"; } } void ElementRFCavity::PropagateLongRFCav(Particle &ref, double& phi_ref) const { double multip, EfieldScl, caviFy, IonFy_i, IonFy_o; double fsync = conf().get<double>("syncflag", 1.0); multip = fRF/ref.SampleFreq; EfieldScl = conf().get<double>("scl_fac"); // Electric field scale factor. if (cavi == 0 && have_EkLim) { if (ref.IonEk/MeVtoeV < EkLim[0] || ref.IonEk/MeVtoeV > EkLim[1]) FLAME_LOG(WARN)<< "Warning: RF cavity incident energy (" << ref.IonEk/MeVtoeV << " [MeV]) is out of range (" << EkLim[0] << " ~ " << EkLim[1] << ").\n"; } if (fsync >= 1.0) { if (cavi == 0 && have_RefNrm && have_SynComplex && fsync == 1.0) { // Get driven phase from synchronous phase based on peak position double NormScl = EfieldScl*ref.IonZ/RefNrm; if (have_NrLim) { if (NormScl < NrLim[0] || NormScl > NrLim[1]) FLAME_LOG(WARN)<< "Warning: RF cavity normalized scale (" << NormScl << ") is out of range (" << NrLim[0] << " ~ " << NrLim[1] << ").\n"; } caviFy = GetCavPhaseComplex(ref, IonFys, NormScl, multip, SynComplex); } else { // Get driven phase from synchronous phase based on sin fit model caviFy = GetCavPhase(cavi, ref, IonFys, multip, SynAccTab); } } else { caviFy = conf().get<double>("phi")*M_PI/180e0; } IonFy_i = multip*ref.phis + caviFy; phi_ref = caviFy; FLAME_LOG(DEBUG)<<"RF long phase" " caviFy="<<caviFy <<" multip="<<multip <<" phis="<<ref.phis <<" IonFy_i="<<IonFy_i <<" EfieldScl="<<EfieldScl <<"\n"; // For the reference particle, evaluate the change of: // kinetic energy, absolute phase, beta, and gamma. GetCavBoost(CavData, ref, IonFy_i, EfieldScl, IonFy_o); ref.IonEk = ref.IonW - ref.IonEs; ref.recalc(); ref.phis += (IonFy_o-IonFy_i)/multip; } void ElementRFCavity::calRFcaviEmitGrowth(const state_t::matrix_t &matIn, Particle &state, const int n, const double betaf, const double gamaf, const double aveX2i, const double cenX, const double aveY2i, const double cenY, state_t::matrix_t &matOut) { // Evaluate emittance growth. int k; double ionLamda, E0TL, DeltaPhi, kpX, fDeltaPhi, f2DeltaPhi, gPhisDeltaPhi, deltaAveXp2f, XpIncreaseFactor; double kpY, deltaAveYp2f, YpIncreaseFactor, kpZ, ionK, aveZ2i, deltaAveZp2, longiTransFactor, ZpIncreaseFactor; matOut = matIn; ionLamda = C0/fRF*MtoMM; // safe to look at last_real_out[] here as we are called (from advance() ) after it is updated const double accIonW = last_real_out[n].IonW -last_real_in[n].IonW, ave_beta = (last_real_out[n].beta +last_real_in[n].beta)/2.0, ave_gamma = (last_real_out[n].gamma+last_real_in[n].gamma)/2.0; E0TL = accIonW/cos(IonFys)/state.IonZ; // for rebuncher, because no acceleration, E0TL would be wrong when cos(ionFys) is devided. if (cos(IonFys) > -0.0001 && cos(IonFys) < 0.0001) E0TL = 0e0; DeltaPhi = sqrt(matIn(4, 4)); // ionLamda in m, kpX in 1/mm kpX = -M_PI*fabs(state.IonZ)*E0TL/state.IonEs/sqr(ave_beta*ave_gamma)/betaf/gamaf/ionLamda; fDeltaPhi = 15e0/sqr(DeltaPhi)*(3e0/sqr(DeltaPhi)*(sin(DeltaPhi)/DeltaPhi-cos(DeltaPhi))-(sin(DeltaPhi)/DeltaPhi)); f2DeltaPhi = 15e0/sqr(2e0*DeltaPhi)*(3e0/sqr(2e0*DeltaPhi) *(sin(2e0*DeltaPhi)/(2e0*DeltaPhi)-cos(2e0*DeltaPhi))-(sin(2e0*DeltaPhi)/(2e0*DeltaPhi))); gPhisDeltaPhi = 0.5e0*(1+(sqr(sin(IonFys))-sqr(cos(IonFys)))*f2DeltaPhi); deltaAveXp2f = kpX*kpX*(gPhisDeltaPhi-sqr(sin(IonFys)*fDeltaPhi))*(aveX2i+cenX*cenX); XpIncreaseFactor = 1e0; if (deltaAveXp2f+matIn(1, 1) > 0e0) XpIncreaseFactor = sqrt((deltaAveXp2f+matIn(1, 1))/matIn(1, 1)); // ionLamda in m kpY = -M_PI*fabs(state.IonZ)*E0TL/state.IonEs/sqr(ave_beta*ave_gamma)/betaf/gamaf/ionLamda; deltaAveYp2f = sqr(kpY)*(gPhisDeltaPhi-sqr(sin(IonFys)*fDeltaPhi))*(aveY2i+sqr(cenY)); YpIncreaseFactor = 1.0; if (deltaAveYp2f+matIn(3, 3)>0) { YpIncreaseFactor = sqrt((deltaAveYp2f+matIn(3, 3))/matIn(3, 3)); } kpZ = -2e0*kpX*sqr(ave_gamma); //unit: 1/mm ionK = 2e0*M_PI/(ave_beta*ionLamda); aveZ2i = sqr(DeltaPhi)/sqr(ionK); deltaAveZp2 = sqr(kpZ*DeltaPhi)*aveZ2i*(sqr(cos(IonFys))/8e0+DeltaPhi*sin(IonFys)/576e0); longiTransFactor = 1e0/(ave_gamma-1e0)/state.IonEs*MeVtoeV; ZpIncreaseFactor = 1e0; if (deltaAveZp2+matIn(5, 5)*sqr(longiTransFactor) > 0e0) ZpIncreaseFactor = sqrt((deltaAveZp2+matIn(5, 5)*sqr(longiTransFactor))/(matIn(5, 5)*sqr(longiTransFactor))); for (k = 0; k < PS_Dim; k++) { matOut(1, k) *= XpIncreaseFactor; matOut(k, 1) *= XpIncreaseFactor; matOut(3, k) *= YpIncreaseFactor; matOut(k, 3) *= YpIncreaseFactor; matOut(5, k) *= ZpIncreaseFactor; matOut(k, 5) *= ZpIncreaseFactor; } } void ElementRFCavity::InitRFCav(Particle &real, state_t::matrix_t &M, CavTLMLineType &linetab) { int cavilabel; double Rm, multip, IonFy_i, Ek_i, EfieldScl, IonFy_o; FLAME_LOG(DEBUG)<<"RF recompute start "<<real<<"\n"; if (cavi == 1) { cavilabel = 41; Rm = 17e0; } else if (cavi== 2) { cavilabel = 85; Rm = 17e0; } else if (cavi== 3) { cavilabel = 29; Rm = 20e0; } else if (cavi== 4) { cavilabel = 53; Rm = 20e0; } else if (cavi== 5) { // 5 Cell elliptical. cavilabel = 53; Rm = 20e0; } else if (cavi == 0) { // Generic2 cavilabel = 0; Rm = 0e0; //this is dummy. } else { throw std::logic_error(SB()<<"*** InitRFCav: undef. cavity type: after ctor"); } multip = fRF/real.SampleFreq; IonFy_i = multip*real.phis + phi_ref; Ek_i = real.IonEk; real.IonW = real.IonEk + real.IonEs; EfieldScl = conf().get<double>("scl_fac"); // Electric field scale factor. ElementRFCavity::GetCavBoost(CavData, real, IonFy_i, EfieldScl, IonFy_o); // updates IonW real.IonEk = real.IonW - real.IonEs; real.recalc(); real.phis += (IonFy_o-IonFy_i)/multip; FLAME_LOG(DEBUG)<<"RF recompute before "<<real <<" cavi="<<cavi <<" cavilabel="<<cavilabel <<" Rm="<<Rm <<" EfieldScl="<<EfieldScl <<" IonFy_i="<<IonFy_i <<" Ek_i="<<Ek_i <<" fRF="<<fRF <<"\n"; if (cavi> 0) { GetCavMat(cavi, cavilabel, Rm, real, EfieldScl, IonFy_i, Ek_i, M, linetab); } else { GetCavMatGeneric(real, EfieldScl, IonFy_i, Ek_i, M, linetab); } //Wrapper for fequency jump in rf cavity if (multip != 1) { for (int i=0; i < state_t::maxsize; i++){ M(i,4) *= multip; M(4,i) /= multip; } } FLAME_LOG(DEBUG)<<"RF recompute after "<<real<<"\n" <<" YY "<<M<<"\n" ; }
40.128748
143
0.509545
PierreSchnizer
327ffaac3db23bbca05af6c613dfdccd8c9925eb
8,112
cpp
C++
src/AdafruitIO_Dashboard.cpp
khoih-prog/Adafruit_IO_Arduino
f6d762f01ba249d00510d1a884c13a5829b121bf
[ "MIT" ]
181
2015-08-13T17:03:24.000Z
2022-02-20T06:44:29.000Z
src/AdafruitIO_Dashboard.cpp
khoih-prog/Adafruit_IO_Arduino
f6d762f01ba249d00510d1a884c13a5829b121bf
[ "MIT" ]
101
2016-04-10T17:40:14.000Z
2022-02-26T22:20:36.000Z
src/AdafruitIO_Dashboard.cpp
khoih-prog/Adafruit_IO_Arduino
f6d762f01ba249d00510d1a884c13a5829b121bf
[ "MIT" ]
113
2015-12-09T07:31:10.000Z
2022-03-22T01:07:18.000Z
/*! * @file AdafruitIO_Dashboard.cpp * * * Adafruit invests time and resources providing this open source code. * Please support Adafruit and open source hardware by purchasing * products from Adafruit! * * Copyright (c) 2015-2016 Adafruit Industries * Authors: Tony DiCola, Todd Treece * Licensed under the MIT license. * * All text above must be included in any redistribution. * */ #include "AdafruitIO_Dashboard.h" #include "AdafruitIO.h" /**************************************************************************/ /*! @brief Sets Adafruit IO Dashboard instance. @param *io Reference to Adafruit IO class. @param *n Valid username string. */ /**************************************************************************/ AdafruitIO_Dashboard::AdafruitIO_Dashboard(AdafruitIO *io, const char *n) { _io = io; name = n; } AdafruitIO_Dashboard::~AdafruitIO_Dashboard() {} /**************************************************************************/ /*! @brief Checks if Adafruit IO Dashboard exists. https://io.adafruit.com/api/docs/#return-dashboard @return True if successful, otherwise False. */ /**************************************************************************/ bool AdafruitIO_Dashboard::exists() { String url = "/api/v2/"; url += _io->_username; url += "/dashboards/"; url += name; _io->_http->beginRequest(); _io->_http->get(url.c_str()); _io->_http->sendHeader("X-AIO-Key", _io->_key); _io->_http->endRequest(); int status = _io->_http->responseStatusCode(); _io->_http->responseBody(); // needs to be read even if not used return status == 200; } /**************************************************************************/ /*! @brief Creates a new dashboard. https://io.adafruit.com/api/docs/#create-a-dashboard @return True if successful, otherwise False. */ /**************************************************************************/ bool AdafruitIO_Dashboard::create() { String url = "/api/v2/"; url += _io->_username; url += "/dashboards"; String body = "name="; body += name; _io->_http->beginRequest(); _io->_http->post(url.c_str()); _io->_http->sendHeader("Content-Type", "application/x-www-form-urlencoded"); _io->_http->sendHeader("Content-Length", body.length()); _io->_http->sendHeader("X-AIO-Key", _io->_key); // the following call to endRequest // should be replaced by beginBody once the // Arduino HTTP Client Library is updated // _io->_http->beginBody(); _io->_http->endRequest(); _io->_http->print(body); _io->_http->endRequest(); int status = _io->_http->responseStatusCode(); _io->_http->responseBody(); // needs to be read even if not used return status == 201; } /**************************************************************************/ /*! @brief Returns the dashboard owner. @return Adafruit IO username. */ /**************************************************************************/ const char *AdafruitIO_Dashboard::user() { return _io->_username; } AdafruitIO *AdafruitIO_Dashboard::io() { return _io; } /**************************************************************************/ /*! @brief Creates a new toggle block element on a dashboard connected to provided feed. @param *feed Reference to an Adafruit IO feed. @return Toggle block dashboard element. */ /**************************************************************************/ ToggleBlock *AdafruitIO_Dashboard::addToggleBlock(AdafruitIO_Feed *feed) { return new ToggleBlock(this, feed); } /**************************************************************************/ /*! @brief Creates a new momentary block element on a dashboard connected to provided feed. @param *feed Reference to an Adafruit IO feed. @return Momentary block dashboard element. */ /**************************************************************************/ MomentaryBlock *AdafruitIO_Dashboard::addMomentaryBlock(AdafruitIO_Feed *feed) { return new MomentaryBlock(this, feed); } /**************************************************************************/ /*! @brief Creates a new slider block element on a dashboard connected to provided feed. @param *feed Reference to an Adafruit IO feed. @return Slider block dashboard element. */ /**************************************************************************/ SliderBlock *AdafruitIO_Dashboard::addSliderBlock(AdafruitIO_Feed *feed) { return new SliderBlock(this, feed); } /**************************************************************************/ /*! @brief Creates a new gauge block element on a dashboard connected to provided feed. @param *feed Reference to an Adafruit IO feed. @return Gauge block dashboard element. */ /**************************************************************************/ GaugeBlock *AdafruitIO_Dashboard::addGaugeBlock(AdafruitIO_Feed *feed) { return new GaugeBlock(this, feed); } /**************************************************************************/ /*! @brief Creates a new momentary block element on a dashboard connected to provided feed. @param *feed Reference to an Adafruit IO feed. @return Text block dashboard element. */ /**************************************************************************/ TextBlock *AdafruitIO_Dashboard::addTextBlock(AdafruitIO_Feed *feed) { return new TextBlock(this, feed); } /**************************************************************************/ /*! @brief Creates a new chart block element on a dashboard connected to provided feed. @param *feed Reference to an Adafruit IO feed. @return Chart block dashboard element. */ /**************************************************************************/ ChartBlock *AdafruitIO_Dashboard::addChartBlock(AdafruitIO_Feed *feed) { return new ChartBlock(this, feed); } /**************************************************************************/ /*! @brief Creates a new color block element on a dashboard connected to provided feed. @param *feed Reference to an Adafruit IO feed. @return Color block dashboard element. */ /**************************************************************************/ ColorBlock *AdafruitIO_Dashboard::addColorBlock(AdafruitIO_Feed *feed) { return new ColorBlock(this, feed); } /**************************************************************************/ /*! @brief Creates a new map block element on a dashboard connected to provided feed. @param *feed Reference to an Adafruit IO feed. @return Map block dashboard element. */ /**************************************************************************/ MapBlock *AdafruitIO_Dashboard::addMapBlock(AdafruitIO_Feed *feed) { return new MapBlock(this, feed); } /**************************************************************************/ /*! @brief Creates a new stream block element on a dashboard connected to provided feed. @param *feed Reference to an Adafruit IO feed. @return Stream block dashboard element. */ /**************************************************************************/ StreamBlock *AdafruitIO_Dashboard::addStreamBlock(AdafruitIO_Feed *feed) { return new StreamBlock(this, feed); } /**************************************************************************/ /*! @brief Creates a new image block element on a dashboard connected to provided feed. @param *feed Reference to an Adafruit IO feed. @return Image block dashboard element. */ /**************************************************************************/ ImageBlock *AdafruitIO_Dashboard::addImageBlock(AdafruitIO_Feed *feed) { return new ImageBlock(this, feed); }
34.519149
80
0.489522
khoih-prog
32851497790e9fc8cb3d7034a825f68a172bf513
2,043
cpp
C++
tests/dsp_scalardelayline_tests.cpp
jontio/JSquelch
72805d6e08035daca09e6c668c63f46dc66674a2
[ "MIT" ]
2
2021-07-11T03:36:42.000Z
2022-03-26T15:04:30.000Z
tests/dsp_scalardelayline_tests.cpp
jontio/JSquelch
72805d6e08035daca09e6c668c63f46dc66674a2
[ "MIT" ]
null
null
null
tests/dsp_scalardelayline_tests.cpp
jontio/JSquelch
72805d6e08035daca09e6c668c63f46dc66674a2
[ "MIT" ]
null
null
null
#include "../src/dsp/dsp.h" #include "../src/util/RuntimeError.h" #include "../src/util/stdio_utils.h" #include "../src/util/file_utils.h" #include <QFile> #include <QDataStream> #include <iostream> //important for Qt include cpputest last as it mucks up new and causes compiling to fail #include "CppUTest/TestHarness.h" //this unit test is the big one and tests the C++ algo implimentation with //that of matlab. the output signal and snr are compared TEST_GROUP(Test_DSP_ScalarDelayLine) { const double double_tolerance=0.0000001; //cpputest does not seem to work for qt accessing io such as qfile qdebug etc //i get momory leak messages so im turning it off for this unit where i really want qfile void setup() { // MemoryLeakWarningPlugin::turnOffNewDeleteOverloads(); } void teardown() { // MemoryLeakWarningPlugin::turnOnNewDeleteOverloads(); } }; TEST(Test_DSP_ScalarDelayLine, DoubleDelay2Test) { JDsp::ScalarDelayLine<double> delayline(62); QVector<double> input(62*2); for(int k=0;k<62;k++) { input[k]=k; input[k+62]=k; delayline<<input[k]; } for(int k=0;k<62;k++) { DOUBLES_EQUAL(input[k+62],delayline<<input[k],double_tolerance); } } TEST(Test_DSP_ScalarDelayLine, DoubleZeroTest) { JDsp::ScalarDelayLine<double> delayline(0); QVector<double> input(62*2); for(int k=0;k<62;k++) { input[k]=k; input[k+62]=k; delayline.update(input[k]); } for(int k=0;k<62;k++) { delayline.update(input[k]); DOUBLES_EQUAL(input[k],delayline,double_tolerance); } } TEST(Test_DSP_ScalarDelayLine, DoubleDelayTest) { JDsp::ScalarDelayLine<double> delayline(62); QVector<double> input(62*2); for(int k=0;k<62;k++) { input[k]=k; input[k+62]=k; delayline.update(input[k]); } for(int k=0;k<62;k++) { delayline.update(input[k]); DOUBLES_EQUAL(input[k+62],delayline,double_tolerance); } }
24.321429
93
0.643661
jontio
3285d054d851d23edfbcd08c2e2dfb69ae0738f4
11,412
cc
C++
pkg/oc/varinfo.cc
ViennaNovoFlop/ViennaNovoFlop-dev
f8c4d6c06590a0d9a3890d81e9b0b4dcb7ea9e00
[ "TCL", "SWL", "MIT", "X11", "BSD-3-Clause" ]
null
null
null
pkg/oc/varinfo.cc
ViennaNovoFlop/ViennaNovoFlop-dev
f8c4d6c06590a0d9a3890d81e9b0b4dcb7ea9e00
[ "TCL", "SWL", "MIT", "X11", "BSD-3-Clause" ]
null
null
null
pkg/oc/varinfo.cc
ViennaNovoFlop/ViennaNovoFlop-dev
f8c4d6c06590a0d9a3890d81e9b0b4dcb7ea9e00
[ "TCL", "SWL", "MIT", "X11", "BSD-3-Clause" ]
null
null
null
/* FILE: varinfo.cc -*-Mode: c++-*- * * Small program to probe system characteristics. * * Last modified on: $Date: 2009-11-06 05:42:23 $ * Last modified by: $Author: donahue $ * */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <limits.h> #include <math.h> #include <float.h> #if defined(__unix) || defined(_AIX) #include <unistd.h> #endif /* __unix */ /* End includes */ /**************** #define COMPLEX #define EXTRALONG #define EXTRALONGINT #define EXTRALONGDOUBLE ****************/ #ifdef __cplusplus # if !defined(EXTRALONGDOUBLE) && !defined(__SUNPRO_CC) && !defined(__sun) /* Some(?) releases of Sun Forte compiler missing floorl support. */ /* Some(?) g++ installations on Solaris missing floorl support. */ # define EXTRALONGDOUBLE # endif #endif #ifdef EXTRALONG # ifndef EXTRALONGINT # define EXTRALONGINT # endif # ifndef EXTRALONGDOUBLE # define EXTRALONGDOUBLE # endif #endif #ifdef EXTRALONGINT # ifdef _WIN32 typedef __int64 HUGEINT; # else typedef long long HUGEINT; # endif #endif #ifdef EXTRALONGDOUBLE typedef long double HUGEFLOAT; #endif /* * If "EXTRALONG" is defined, then types "long long" and "long double" * are included. In particular, the second (long double), may be the * 10 byte IEEE 854 (3.4E-4932 to 3.4E+4932) "double-extended-precision" * format (as opposed to the 8-byte IEEE 754 "double-precision" format). * Your system might have <ieee754.h> and <ieee854.h> include files with * more information. * * Some "magic" values for the IEEE formats * * Value Internal representation * (MSB order, hexadecimal) * 4-byte: 2.015747786E+00 40 01 02 03 * 8-byte: 2.12598231449442521E+00 40 01 02 03 04 05 06 07 * 10-byte: 4.06286812764321414839E+00 40 01 82 03 04 05 06 07 08 09 * * Note that the third byte in the 10-byte format is '0x82', NOT '0x02'. * This is because in the IEEE 10-byte format, bit 63 is an explicit * "integer" or "J-bit" representing the leading bit in the mantissa. * For normal (as opposed to denormal) numbers this bit must be 1. * The J-bit is implied to be 1 in the 4- and 8-byte formats. The * leading byte is 0x40 so that the value has a small exponent; this * protects against compilers that complain about over- and under-flow * errors when selecting from among the magic values, in particular * in the FLOATCONST macro. * The PrintByteOrder routine masks off the top 4 bits, so we can * put any values we want in the top 4 bits of each byte, except * the special value 0x00 which is treated as invalid. */ /* Debugging routine */ #ifdef __cplusplus void DumpBytes(char *buf,int len) #else void DumpBytes(buf,len) char *buf; int len; #endif { int i; for(i=0;i<len;i++) printf("%02X ",(unsigned char)buf[i]); printf("\n"); } #define FillByteOrder(x,i,l) \ for(i=1,x=0x10;i<l;i++) { x<<=8; x|=(0x10+(unsigned char)i); } /* IEEE 754 floating point format "magic" strings (Hex 0x1234, 0x12345678) */ #define FLOATCONST(l) (l==4 ? (float)2.015747786 : \ (l==8 ? (float)2.12598231449442521 : \ (float)0.)) #define DOUBLECONST(l) (l==4 ? (double)2.015747786 : \ (l==8 ? (double)2.12598231449442521 : \ (double)0.)) #ifdef EXTRALONGDOUBLE #define LONGDOUBLECONST(l) (l==4 ? (HUGEFLOAT)2.015747786 : \ (l==8 ? (HUGEFLOAT)2.12598231449442521 : \ (l>8 ? (HUGEFLOAT)4.06286812764321414839L : \ (HUGEFLOAT)0.))) #endif /* EXTRALONGDOUBLE */ #ifdef __cplusplus void PrintByteOrder(char *buf,int len) #else void PrintByteOrder(buf,len) char* buf; int len; #endif { int i,ch; printf("Byte order: "); for(i=0;i<len;i++) { if(buf[i]==0) { printf("x"); } else { ch=0x0F & ((unsigned char)buf[i]); printf("%01X",ch+1); } } } double DblMachEps() { volatile double one; double eps,epsok,check; one = 1.0; eps=1.0; epsok=2.0; check=1.0+eps; while(check>one) { epsok=eps; eps/=2.0; check = 1.0 + eps; } return epsok; } #ifdef EXTRALONGDOUBLE HUGEFLOAT LongDblMachEps() { volatile HUGEFLOAT eps,epsok,check; eps=1.0; epsok=2.0; check=1.0+eps; while(check>1.0) { epsok=eps; eps/=2.0; check = 1.0 + eps; } return epsok; } #endif /* EXTRALONGDOUBLE */ void Usage() { fprintf(stderr,"Usage: varinfo [-h|--help]" " [--skip-atan2] [--skip-underflow]\n"); exit(1); } /* Declaration for dummy zero routine. Definition at bottom of file. */ double zero(); #ifdef __cplusplus int main(int argc,char** argv) #else int main(argc,argv) int argc; char **argv; #endif { short s; int i; long l; float f; double d; #ifdef EXTRALONGINT HUGEINT ll; #endif /* EXTRALONGINT */ #ifdef EXTRALONGDOUBLE HUGEFLOAT ld; #endif /* EXTRALONGDOUBLE */ #ifdef COMPLEX __complex__ int ci; __complex__ double cd; #endif /* COMPLEX */ size_t st,loop; int skip_atan2,skip_underflow; /* Check command line flags */ if(argc>3) Usage(); skip_atan2=0; skip_underflow=0; if(argc>1) { int ia; for(ia=1;ia<argc;ia++) { if(strcmp("--skip-atan2",argv[ia])==0) skip_atan2=1; else if(strcmp("--skip-underflow",argv[ia])==0) skip_underflow=1; else Usage(); } } /* Work length info */ printf("Type char is %2d bytes wide ",(int)sizeof(char)); st=sizeof(char); if(st!=1) printf("ERROR: char should be 1 byte wide!\n"); else printf("Byte order: 1\n"); printf("\n"); printf("Type short is %2d bytes wide ",(int)sizeof(short)); FillByteOrder(s,loop,sizeof(short)); PrintByteOrder((char *)&s,(int)sizeof(short)); printf("\n"); printf("Type int is %2d bytes wide ",(int)sizeof(int)); FillByteOrder(i,loop,sizeof(int)); PrintByteOrder((char *)&i,(int)sizeof(int)); printf("\n"); printf("Type long is %2d bytes wide ",(int)sizeof(long)); FillByteOrder(l,loop,sizeof(long)); PrintByteOrder((char *)&l,(int)sizeof(long)); printf("\n"); #ifdef EXTRALONGINT printf("Type HUGEINT is %2d bytes wide ",(int)sizeof(HUGEINT)); FillByteOrder(ll,loop,sizeof(HUGEINT)); PrintByteOrder((char *)&ll,(int)sizeof(HUGEINT)); printf("\n"); #endif /* EXTRALONGINT */ printf("\n"); printf("Type float is %2d bytes wide ",(int)sizeof(float)); f=FLOATCONST(sizeof(float)); PrintByteOrder((char *)&f,(int)sizeof(float)); printf("\n"); printf("Type double is %2d bytes wide ",(int)sizeof(double)); d=DOUBLECONST(sizeof(double)); PrintByteOrder((char *)&d,(int)sizeof(double)); printf("\n"); #ifdef EXTRALONGDOUBLE printf("Type HUGEFLOAT is %2d bytes wide ",(int)sizeof(HUGEFLOAT)); for(size_t ihf=0;ihf<sizeof(HUGEFLOAT);++ihf) { ((char *)&ld)[ihf]=0; } ld=LONGDOUBLECONST(sizeof(HUGEFLOAT)); PrintByteOrder((char *)&ld,(int)sizeof(HUGEFLOAT)); printf("\n"); #endif /* EXTRALONGDOUBLE */ printf("\n"); printf("Type void * is %2d bytes wide\n",(int)sizeof(void *)); #ifdef COMPLEX printf("\n"); printf("Type __complex__ int is %2d bytes wide\n", sizeof(__complex__ int)); printf("Type __complex__ double is %2d bytes wide\n", sizeof(__complex__ double)); #endif /* COMPLEX */ /* Byte order info */ printf("\n"); fflush(stdout); st=sizeof(double); if(st!=8) { fprintf(stderr,"Can't test byte order; sizeof(double)!=8\n"); } else { union { double x; unsigned char c[8]; } bytetest; double xpattern=1.234; unsigned char lsbpattern[9],msbpattern[9]; strncpy((char *)lsbpattern,"\130\071\264\310\166\276\363\077", sizeof(lsbpattern)); strncpy((char *)msbpattern,"\077\363\276\166\310\264\071\130", sizeof(msbpattern)); /* The bit pattern for 1.234 on a little endian machine (e.g., * Intel's x86 series and Digital's AXP) should be * 58 39 B4 C8 76 BE F3 3F, while on a big endian machine it is * 3F F3 BE 76 C8 B4 39 58. Examples of big endian machines * include ones using the MIPS R4000 and R8000 series chips, * for example SGI's. Note: At least some versions of the Sun * 'cc' compiler apparently don't grok '\xXX' hex notation. The * above octal constants are equivalent to the aforementioned * hex strings. */ bytetest.x=xpattern; #ifdef DEBUG printf("sizeof(lsbpattern)=%d\n",sizeof(lsbpattern)); printf("lsb pattern="); DumpBytes(lsbpattern,8); printf("msb pattern="); DumpBytes(msbpattern,8); printf(" x pattern="); DumpBytes(bytetest.c,8); #endif /* DEBUG */ /* Floating point format */ if(strncmp((char *)bytetest.c,(char *)lsbpattern,8)==0) { printf("Floating point format is IEEE in LSB (little endian) order\n"); } else if(strncmp((char *)bytetest.c,(char *)msbpattern,8)==0) { printf("Floating point format is IEEE in MSB (big endian) order\n"); } else { printf("Floating point format is either unknown" " or uses an irregular byte order\n"); } } /* Additional system-specific information (ANSI) */ printf("\nWidth of clock_t variable: %7lu bytes\n", (unsigned long)sizeof(clock_t)); #ifdef CLOCKS_PER_SEC printf( " CLOCKS_PER_SEC: %7lu\n", (unsigned long)CLOCKS_PER_SEC); #else printf( " CLOCKS_PER_SEC: <not defined>\n"); #endif #ifdef CLK_TCK printf( " CLK_TCK: %7lu\n",(unsigned long)CLK_TCK); #else printf( " CLK_TCK: <not defined>\n"); #endif printf("\nFLT_EPSILON: %.9g\n",FLT_EPSILON); printf("SQRT_FLT_EPSILON: %.9g\n",sqrt(FLT_EPSILON)); printf("DBL_EPSILON: %.17g\n",DBL_EPSILON); printf("SQRT_DBL_EPSILON: %.17g\n",sqrt(DBL_EPSILON)); printf("CUBE_ROOT_DBL_EPSILON: %.17g\n",pow(DBL_EPSILON,1./3.)); #if 0 && defined(LDBL_EPSILON) printf("LDBL_EPSILON: %.20Lg\n",LDBL_EPSILON); #endif #if 0 && defined(EXTRALONGDOUBLE) printf("\nCalculated Double Epsilon: %.17g\n",DblMachEps()); printf( "Calculated HUGEFLOAT Epsilon: %.20Lg\n",LongDblMachEps()); #else printf("\nCalculated Double Epsilon: %.17g\n",DblMachEps()); #endif /* EXTRALONGDOUBLE */ printf("\nDBL_MIN: %.17g\n",DBL_MIN); printf("DBL_MAX: %.17g\n",DBL_MAX); if(!skip_atan2) { printf("\nReturn value from atan2(0,0): %g\n",atan2(zero(),zero())); } if(!skip_underflow) { d = -999999.; errno = 0; d = exp(d); if(d!=0.0) { fprintf(stderr,"\nERROR: UNDERFLOW TEST FAILURE\n\n"); exit(1); } if(errno==0) printf("\nErrno not set on underflow\n"); else printf("\nErrno set on underflow to %d\n",errno); } #ifdef EXTRALONGDOUBLE # ifdef NO_FLOORL_CHECK printf("\nLibrary function floorl assumed bad or missing.\n"); # else /* Check for bad long double floor and ceil */ ld = -0.253L; if(floorl(ld) != -1.0L || (ld - floorl(ld)) != 1.0L - 0.253L) { printf("\nBad floorl. You should set " "program_compiler_c++_property_bad_wide2int" " to 1 in the platform oommf/config/platforms/ file.\n"); } else { printf("\nGood floorl.\n"); } # endif #endif /* EXTRALONGDOUBLE */ return 0; } /* Dummy routine that returns 0. This is a workaround for aggressive * compilers that try to resolve away constants at compile-time (or try * to and fall over with an internal compiler error...) */ double zero() { return 0.0; }
28.247525
77
0.640379
ViennaNovoFlop
3286b7e617ed6b57216c4d1e94931b07250b85b8
1,423
cpp
C++
UltraDV/Source/TKeyFrame.cpp
ModeenF/UltraDV
30474c60880de541b33687c96293766fe0dc4aef
[ "Unlicense" ]
null
null
null
UltraDV/Source/TKeyFrame.cpp
ModeenF/UltraDV
30474c60880de541b33687c96293766fe0dc4aef
[ "Unlicense" ]
null
null
null
UltraDV/Source/TKeyFrame.cpp
ModeenF/UltraDV
30474c60880de541b33687c96293766fe0dc4aef
[ "Unlicense" ]
null
null
null
//--------------------------------------------------------------------- // // File: TKeyFrame.cpp // // Author: Mike Ost // // Date: 10.23.98 // // Desc: // // TKeyFrame is owned by TCueEffect. It associates a time with a // TEffectState, as defined by the add-on effects classes. This // provides a generic interface to key frames, with the details // of effects states handled elsewhere. // //--------------------------------------------------------------------- #include "TKeyFrame.h" #include "TCueEffect.h" //--------------------------------------------------------------------- // Create and Destroy //--------------------------------------------------------------------- // // TKeyFrame::TKeyFrame() : m_time(0), m_state(0) {} TKeyFrame::~TKeyFrame() { delete m_state; } TKeyFrame::TKeyFrame(const TKeyFrame& rhs) : m_time(rhs.m_time) { if (rhs.m_state) m_state = rhs.m_state->NewCopy(); else m_state = rhs.m_state; } //--------------------------------------------------------------------- // Comparison operators //--------------------------------------------------------------------- // // bool TKeyFrame::operator<(const TKeyFrame& rhs) { if (m_time < rhs.m_time) return true; else if (m_time == rhs.m_time && m_state->LessThan(rhs.m_state)) return true; return false; } bool TKeyFrame::operator==(const TKeyFrame& rhs) { return m_time == rhs.m_time && m_state->Equals(rhs.m_state); }
21.560606
71
0.476458
ModeenF
3287eb434d6db4cc9a7763fe0426bf060c488786
4,139
cpp
C++
chess_server/RoomManager.cpp
Rexagon/chess
d13334ce89c2335b5abf65cce56d9d781bde2930
[ "Apache-2.0" ]
null
null
null
chess_server/RoomManager.cpp
Rexagon/chess
d13334ce89c2335b5abf65cce56d9d781bde2930
[ "Apache-2.0" ]
4
2017-08-18T13:14:27.000Z
2017-08-25T10:11:08.000Z
chess_server/RoomManager.cpp
Rexagon/chess
d13334ce89c2335b5abf65cce56d9d781bde2930
[ "Apache-2.0" ]
null
null
null
#include "RoomManager.h" #include "Server.h" RoomManager::RoomManager(Server* server) : m_server(server), m_room_count(0) { } RoomManager::~RoomManager() { } void RoomManager::init() { sqlite3_stmt* statement; int rc = 0; sqlite3_prepare16_v2(m_server->m_db, L"SELECT * FROM rooms", -1, &statement, 0); while ((rc = sqlite3_step(statement)) == SQLITE_ROW) { std::wstring room_name(static_cast<const wchar_t*>(sqlite3_column_text16(statement, 0))); std::wstring room_owner(static_cast<const wchar_t*>(sqlite3_column_text16(statement, 1))); std::wstring room_white_player(static_cast<const wchar_t*>(sqlite3_column_text16(statement, 2))); std::wstring room_black_player(static_cast<const wchar_t*>(sqlite3_column_text16(statement, 3))); bool room_is_private = static_cast<bool>(sqlite3_column_int(statement, 4)); bool room_is_chat_enabled = static_cast<bool>(sqlite3_column_int(statement, 5)); std::wstring room_file_path(static_cast<const wchar_t*>(sqlite3_column_text16(statement, 6))); m_server->m_rooms.push_back(std::make_unique<Room>(room_name, room_owner, room_white_player, room_black_player, room_is_private, room_is_chat_enabled, room_file_path)); m_room_count++; } } Room* RoomManager::change_room_settings(const std::wstring& old_name, const std::wstring& new_name, const std::wstring & owner, const std::wstring & white_player, const std::wstring & black_player, bool privacy, bool chat_enabled) { Room* room = nullptr; for (std::list<std::unique_ptr<Room>>::iterator it_room = m_server->m_rooms.begin(); it_room != m_server->m_rooms.end(); it_room++) { if ((*it_room)->get_name() == old_name) { room = it_room->get(); } } std::wstring query; // 0 - delete; 1 - update; 2 - create enum Action { Update, Create } action = Update; if (room != nullptr) { query = L"UPDATE rooms SET (name=?, owner=?, user_white=?, user_black=?, private=?, chat_enabled=?) WHERE (name=?)"; room->set_name(new_name); room->set_owner(owner); room->set_white_player(white_player); room->set_black_player(black_player); room->set_privacy(privacy); room->set_chat_enabled(chat_enabled); action = Action::Update; } else { query = L"INSERT INTO rooms (name, owner, user_white, user_black, private, chat_enabled, file_path) VALUES (?, ?, ?, ?, ?, ?, ?)"; std::wstring path = L"./data/rooms/" + std::to_wstring(m_room_count) + L".log"; m_server->m_rooms.push_back(std::make_unique<Room>( new_name, owner, white_player, black_player, privacy, chat_enabled, path )); room = m_server->m_rooms.back().get(); action = Action::Create; } sqlite3_stmt* statement; sqlite3_prepare16_v2(m_server->m_db, query.c_str(), -1, &statement, 0); sqlite3_bind_text16(statement, 1, new_name.c_str(), -1, 0); sqlite3_bind_text16(statement, 2, owner.c_str(), -1, 0); sqlite3_bind_text16(statement, 3, white_player.c_str(), -1, 0); sqlite3_bind_text16(statement, 4, black_player.c_str(), -1, 0); sqlite3_bind_int(statement, 5, static_cast<int>(privacy)); sqlite3_bind_int(statement, 6, static_cast<int>(chat_enabled)); if (action == Action::Update) { sqlite3_bind_text16(statement, 7, old_name.c_str(), -1, 0); } else if (action == Action::Create) { std::wstring path = L"./data/rooms/" + std::to_wstring(m_room_count) + L".log"; sqlite3_bind_text16(statement, 7, path.c_str(), -1, 0); m_room_count++; } int rc = sqlite3_step(statement); sqlite3_finalize(statement); return room; } void RoomManager::erase_room(Room * room) { for (std::list<std::unique_ptr<Room>>::iterator it_room = m_server->m_rooms.begin(); it_room != m_server->m_rooms.end(); it_room++) { if ((*it_room)->get_name() == room->get_name()) { m_server->m_rooms.erase(it_room); std::wstring query = L"DELETE FROM rooms WHERE (name=?)"; sqlite3_stmt* statement; sqlite3_prepare16_v2(m_server->m_db, query.c_str(), -1, &statement, 0); sqlite3_bind_text16(statement, 1, room->get_name().c_str(), -1, 0); int rc = sqlite3_step(statement); sqlite3_finalize(statement); break; } } } void RoomManager::erase_room(const std::wstring & name) { }
31.120301
230
0.709108
Rexagon
3289d2425a82c902390a490c3a280314b8aa1e8f
9,408
hpp
C++
WICWIU_src/Operator/ReShape.hpp
wok1909/WICWIU-OSSLab-Final-Project
ea172614c3106de3a8e203acfac8f0dd4eca7c7c
[ "Apache-2.0" ]
119
2018-05-30T01:16:36.000Z
2021-11-08T13:01:07.000Z
WICWIU_src/Operator/ReShape.hpp
wok1909/WICWIU-OSSLab-Final-Project
ea172614c3106de3a8e203acfac8f0dd4eca7c7c
[ "Apache-2.0" ]
24
2018-08-05T16:50:42.000Z
2020-10-28T00:38:48.000Z
WICWIU_src/Operator/ReShape.hpp
wok1909/WICWIU-OSSLab-Final-Project
ea172614c3106de3a8e203acfac8f0dd4eca7c7c
[ "Apache-2.0" ]
35
2018-06-29T17:10:13.000Z
2021-06-05T04:07:48.000Z
#ifndef RESHAPE_H_ #define RESHAPE_H_ value #include "../Operator.hpp" template<typename DTYPE> class ReShape : public Operator<DTYPE>{ public: /*! @brief ReShape의 생성자 @details 파라미터로 받은 pInput, pRowSize, pColSize으로 Alloc한다. @param pInput ReShape할 Operator. @param pRowSize ReShape으로 새로 만들어질 Tensor의 rowsize. @param pColSize ReShape으로 새로 만들어질 Tensor의 colsize. @paramp pName 사용자가 부여한 Operator의 이름. @ref int Alloc(Operator<DTYPE> *pInput, int pTimeSize, int pBatchSize, int pChannelSize, int pRowSize, int pColSize) */ ReShape(Operator<DTYPE> *pInput, int pRowSize, int pColSize, std::string pName, int pLoadflag = TRUE) : Operator<DTYPE>(pInput, pName, pLoadflag) { #ifdef __DEBUG__ std::cout << "ReShape::ReShape(Operator *)" << '\n'; #endif // __DEBUG__ this->Alloc(pInput, 0, 0, 0, pRowSize, pColSize); } /*! @brief ReShape의 생성자 @details 파라미터로 받은 pInput, pRowSize, pColSize으로 Alloc한다. @param pInput ReShape할 Operator. @param pChannelSize ReShape으로 새로 만들어질 Tensor의 channelsize @param pRowSize ReShape으로 새로 만들어질 Tensor의 rowsize. @param pColSize ReShape으로 새로 만들어질 Tensor의 colsize. @paramp pName 사용자가 부여한 Operator의 이름. @ref int Alloc(Operator<DTYPE> *pInput, int pTimeSize, int pBatchSize, int pChannelSize, int pRowSize, int pColSize) */ ReShape(Operator<DTYPE> *pInput, int pChannelSize, int pRowSize, int pColSize, std::string pName, int pLoadflag = TRUE) : Operator<DTYPE>(pInput, pName, pLoadflag) { #ifdef __DEBUG__ std::cout << "ReShape::ReShape(Operator *)" << '\n'; #endif // __DEBUG__ this->Alloc(pInput, 0, 0, pChannelSize, pRowSize, pColSize); } /*! @brief ReShape의 생성자 @details 파라미터로 받은 pInput, pRowSize, pColSize으로 Alloc한다. @param pInput ReShape할 Operator. @param pBatchSize ReShape으로 새로 만들어질 Tensor의 batchsize. @param pChannelSize ReShape으로 새로 만들어질 Tensor의 channelsize. @param pRowSize ReShape으로 새로 만들어질 Tensor의 rowsize. @param pColSize ReShape으로 새로 만들어질 Tensor의 colsize. @paramp pName 사용자가 부여한 Operator의 이름. @ref int Alloc(Operator<DTYPE> *pInput, int pTimeSize, int pBatchSize, int pChannelSize, int pRowSize, int pColSize) */ ReShape(Operator<DTYPE> *pInput, int pBatchSize, int pChannelSize, int pRowSize, int pColSize, std::string pName, int pLoadflag = TRUE) : Operator<DTYPE>(pInput, pName, pLoadflag) { #ifdef __DEBUG__ std::cout << "ReShape::ReShape(Operator *)" << '\n'; #endif // __DEBUG__ this->Alloc(pInput, 0, pBatchSize, pChannelSize, pRowSize, pColSize); } /*! @brief ReShape의 생성자 @details 파라미터로 받은 pInput, pRowSize, pColSize으로 Alloc한다. @param pInput ReShape할 Operator. @param pTimeSize ReShape으로 새로 만들어질 Tensor의 timesize. @param pBatchSize ReShape으로 새로 만들어질 Tensor의 batchsize. @param pChannelSize ReShape으로 새로 만들어질 Tensor의 channelsize. @param pRowSize ReShape으로 새로 만들어질 Tensor의 rowsize. @param pColSize ReShape으로 새로 만들어질 Tensor의 colsize. @paramp pName 사용자가 부여한 Operator의 이름. @ref int Alloc(Operator<DTYPE> *pInput, int pTimeSize, int pBatchSize, int pChannelSize, int pRowSize, int pColSize) */ ReShape(Operator<DTYPE> *pInput, int pTimeSize, int pBatchSize, int pChannelSize, int pRowSize, int pColSize, std::string pName, int pLoadflag = TRUE) : Operator<DTYPE>(pInput, pName, pLoadflag) { #ifdef __DEBUG__ std::cout << "ReShape::ReShape(Operator *)" << '\n'; #endif // __DEBUG__ this->Alloc(pInput, pTimeSize, pBatchSize, pChannelSize, pRowSize, pColSize); } /*! @brief ReShape의 소멸자. @details Delete 매소드를 사용한다. @ref void Delete() */ ~ReShape() { #ifdef __DEBUG__ std::cout << "ReShape::~ReShape()" << '\n'; #endif // __DEBUG__ Delete(); } /*! @brief 파라미터로 받은 값들로 Shape의 dim들을 바꾼다. @details result에 파라미터로 받은 값들로 result의 shape을 바꾸어 넣고, @details Delta도 마찬가지로 받은 Dimension 정보들로 새로운 Tensor를 생성하여 넣는다, @param pInput ReShape할 Operator. @param pTimeSize ReShape으로 새로 만들어질 Tensor의 timesize. @param pBatchSize ReShape으로 새로 만들어질 Tensor의 batchsize. @param pChannelSize ReShape으로 새로 만들어질 Tensor의 channelsize. @param pRowSize ReShape으로 새로 만들어질 Tensor의 rowsize. @param pColSize ReShape으로 새로 만들어질 Tensor의 colsize. @return 성공 시 TRUE. */ int Alloc(Operator<DTYPE> *pInput, int pTimeSize, int pBatchSize, int pChannelSize, int pRowSize, int pColSize) { #ifdef __DEBUG__ std::cout << "ReShape::Alloc(Operator *, Operator *)" << '\n'; #endif // __DEBUG__ Shape *pInputShape = pInput->GetResult()->GetShape(); if (pTimeSize == 0) pTimeSize = (*pInputShape)[0]; if (pBatchSize == 0) pBatchSize = (*pInputShape)[1]; if (pChannelSize == 0) pChannelSize = (*pInputShape)[2]; Tensor<DTYPE> *result = new Tensor<DTYPE>(pInput->GetResult()); result->ReShape(pTimeSize, pBatchSize, pChannelSize, pRowSize, pColSize); this->SetResult(result); // copy data this->SetDelta(new Tensor<DTYPE>(pTimeSize, pBatchSize, pChannelSize, pRowSize, pColSize)); return TRUE; } /*! @brief Delete 매소드. @details 별다른 기능은 없다. */ void Delete() {} /*! @brief ReShape의 ForwardPropagate 매소드 @details input값을 result(새로운 Shape을 갖는 Tensor)에 저장한다. @param pTime 연산 할 Tensor가 위치한 Time값. default는 0을 사용. @return 성공 시 TRUE. */ int ForwardPropagate(int pTime = 0) { Tensor<DTYPE> *input = this->GetInput()[0]->GetResult(); Tensor<DTYPE> *result = this->GetResult(); int timesize = result->GetTimeSize(); int batchsize = result->GetBatchSize(); int channelsize = result->GetChannelSize(); int rowsize = result->GetRowSize(); int colsize = result->GetColSize(); Shape *resultTenShape = result->GetShape(); int ti = pTime; for (int ba = 0; ba < batchsize; ba++) { for (int ch = 0; ch < channelsize; ch++) { for (int ro = 0; ro < rowsize; ro++) { for (int co = 0; co < colsize; co++) { (*result)[Index5D(resultTenShape, ti, ba, ch, ro, co)] = (*input)[Index5D(resultTenShape, ti, ba, ch, ro, co)]; } } } } return TRUE; } /*! @brief ReShape의 BackPropagate 매소드. @details input_delta에 this_delta값을 더한다. @param pTime 연산 할 Tensor가 위치한 Time값. default는 0을 사용. @return 성공 시 TRUE. */ int BackPropagate(int pTime = 0) { Tensor<DTYPE> *this_delta = this->GetDelta(); Tensor<DTYPE> *input_delta = this->GetInput()[0]->GetDelta(); int timesize = this_delta->GetTimeSize(); int batchsize = this_delta->GetBatchSize(); int channelsize = this_delta->GetChannelSize(); int rowsize = this_delta->GetRowSize(); int colsize = this_delta->GetColSize(); Shape *deltaTenShape = this_delta->GetShape(); int ti = pTime; for (int ba = 0; ba < batchsize; ba++) { for (int ch = 0; ch < channelsize; ch++) { for (int ro = 0; ro < rowsize; ro++) { for (int co = 0; co < colsize; co++) { (*input_delta)[Index5D(deltaTenShape, ti, ba, ch, ro, co)] += (*this_delta)[Index5D(deltaTenShape, ti, ba, ch, ro, co)]; } } } } return TRUE; } #ifdef __CUDNN__ /*! @brief GPU에서 동작하는 ReShape의 ForwardPropagate 메소드. @details cudnnAddTensor를 이용해 pDevInput의 값을 pDevResult에 더한다. @param pTime 연산 할 Tensor가 위치한 Time값. @return 성공 시 TRUE. */ int ForwardPropagateOnGPU(int pTime) { Tensor<DTYPE> *input = this->GetInput()[0]->GetResult(); Tensor<DTYPE> *result = this->GetResult(); DTYPE *pDevInput = input->GetGPUData(); DTYPE *pDevResult = result->GetGPUData(); cudnnTensorDescriptor_t pDesc = input->GetDescriptor(); float alpha = 1.f; float beta = 0.f; checkCUDNN(cudnnAddTensor(this->GetCudnnHandle(), &alpha, pDesc, pDevInput, &alpha, pDesc, pDevResult)); // this->ForwardPropagate(pTime); return TRUE; } /*! @brief GPU에서 동작하는 ReShape의 BackPropagateOnGPU 메소드. @details cudnnAddTensor를 이용해 pDevDelta의 값을 pDevInputDelta에 더한다. @param pTime 연산 할 Tensor가 위치한 Time값. @return 성공 시 TRUE. */ int BackPropagateOnGPU(int pTime) { Tensor<DTYPE> *this_delta = this->GetDelta(); Tensor<DTYPE> *input_delta = this->GetInput()[0]->GetDelta(); DTYPE *pDevDelta = this_delta->GetGPUData(); DTYPE *pDevInputDelta = input_delta->GetGPUData(); cudnnTensorDescriptor_t pDesc = this_delta->GetDescriptor(); float alpha = 1.f; float beta = 0.f; checkCUDNN(cudnnAddTensor(this->GetCudnnHandle(), &alpha, pDesc, pDevDelta, &alpha, pDesc, pDevInputDelta)); // this->BackPropagate(pTime); return TRUE; } #endif // __CUDNN__ }; #endif // RESHAPE_H_
36.045977
200
0.615434
wok1909
329079285f1b12fdcb96cd7dd5fe66bb7869b63c
436
cpp
C++
Dynamic Programming/Min Cost Climbing Stairs - leetcode 746.cpp
gdevanga/Competitive-programming
cb729f89b49ddf666f9db3dc7e4505a0372df740
[ "MIT" ]
2
2019-10-17T06:41:24.000Z
2021-01-31T17:12:42.000Z
Dynamic Programming/Min Cost Climbing Stairs - leetcode 746.cpp
gdevanga/Competitive-programming
cb729f89b49ddf666f9db3dc7e4505a0372df740
[ "MIT" ]
null
null
null
Dynamic Programming/Min Cost Climbing Stairs - leetcode 746.cpp
gdevanga/Competitive-programming
cb729f89b49ddf666f9db3dc7e4505a0372df740
[ "MIT" ]
1
2020-10-21T15:37:32.000Z
2020-10-21T15:37:32.000Z
/* * please find problem description @ * https://leetcode.com/problems/min-cost-climbing-stairs/ */ class Solution { public: int minCostClimbingStairs(vector<int>& cost) { int mc[cost.size()+2] = {0}; for (int i = cost.size()-1; i >= 0; --i) { mc[i] = min(cost[i]+mc[i+1], cost[i]+mc[i+2]); } // i can start on 0th index or 1st index. return min(mc[0],mc[1]); } };
27.25
59
0.529817
gdevanga
329276ffdf0b38e9ba8e91fcb9a36241b80c91c8
42,781
cpp
C++
glstate.cpp
prahal/apitrace
e9426dd61586757d23d7dddc85b3076f477e7f07
[ "MIT" ]
1
2020-06-19T12:34:44.000Z
2020-06-19T12:34:44.000Z
glstate.cpp
prahal/apitrace
e9426dd61586757d23d7dddc85b3076f477e7f07
[ "MIT" ]
null
null
null
glstate.cpp
prahal/apitrace
e9426dd61586757d23d7dddc85b3076f477e7f07
[ "MIT" ]
null
null
null
/************************************************************************** * * Copyright 2011 Jose Fonseca * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #include <string.h> #include <algorithm> #include <iostream> #include <map> #include <sstream> #include "image.hpp" #include "json.hpp" #include "glproc.hpp" #include "glsize.hpp" #include "glstate.hpp" #ifdef __APPLE__ #include <Carbon/Carbon.h> #ifdef __cplusplus extern "C" { #endif OSStatus CGSGetSurfaceBounds(CGSConnectionID, CGWindowID, CGSSurfaceID, CGRect *); #ifdef __cplusplus } #endif #endif /* __APPLE__ */ namespace glstate { static inline void resetPixelPackState(void) { glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT); glPixelStorei(GL_PACK_SWAP_BYTES, GL_FALSE); glPixelStorei(GL_PACK_LSB_FIRST, GL_FALSE); glPixelStorei(GL_PACK_ROW_LENGTH, 0); glPixelStorei(GL_PACK_IMAGE_HEIGHT, 0); glPixelStorei(GL_PACK_SKIP_ROWS, 0); glPixelStorei(GL_PACK_SKIP_PIXELS, 0); glPixelStorei(GL_PACK_SKIP_IMAGES, 0); glPixelStorei(GL_PACK_ALIGNMENT, 1); glBindBuffer(GL_PIXEL_PACK_BUFFER, 0); } static inline void restorePixelPackState(void) { glPopClientAttrib(); } // Mapping from shader type to shader source, used to accumulated the sources // of different shaders with same type. typedef std::map<std::string, std::string> ShaderMap; static void getShaderSource(ShaderMap &shaderMap, GLuint shader) { if (!shader) { return; } GLint shader_type = 0; glGetShaderiv(shader, GL_SHADER_TYPE, &shader_type); if (!shader_type) { return; } GLint source_length = 0; glGetShaderiv(shader, GL_SHADER_SOURCE_LENGTH, &source_length); if (!source_length) { return; } GLchar *source = new GLchar[source_length]; GLsizei length = 0; source[0] = 0; glGetShaderSource(shader, source_length, &length, source); shaderMap[enumToString(shader_type)] += source; delete [] source; } static void getShaderObjSource(ShaderMap &shaderMap, GLhandleARB shaderObj) { if (!shaderObj) { return; } GLint object_type = 0; glGetObjectParameterivARB(shaderObj, GL_OBJECT_TYPE_ARB, &object_type); if (object_type != GL_SHADER_OBJECT_ARB) { return; } GLint shader_type = 0; glGetObjectParameterivARB(shaderObj, GL_OBJECT_SUBTYPE_ARB, &shader_type); if (!shader_type) { return; } GLint source_length = 0; glGetObjectParameterivARB(shaderObj, GL_OBJECT_SHADER_SOURCE_LENGTH_ARB, &source_length); if (!source_length) { return; } GLcharARB *source = new GLcharARB[source_length]; GLsizei length = 0; source[0] = 0; glGetShaderSource(shaderObj, source_length, &length, source); shaderMap[enumToString(shader_type)] += source; delete [] source; } static inline void dumpProgram(JSONWriter &json, GLint program) { GLint attached_shaders = 0; glGetProgramiv(program, GL_ATTACHED_SHADERS, &attached_shaders); if (!attached_shaders) { return; } ShaderMap shaderMap; GLuint *shaders = new GLuint[attached_shaders]; GLsizei count = 0; glGetAttachedShaders(program, attached_shaders, &count, shaders); std::sort(shaders, shaders + count); for (GLsizei i = 0; i < count; ++ i) { getShaderSource(shaderMap, shaders[i]); } delete [] shaders; for (ShaderMap::const_iterator it = shaderMap.begin(); it != shaderMap.end(); ++it) { json.beginMember(it->first); json.writeString(it->second); json.endMember(); } } static inline void dumpProgramObj(JSONWriter &json, GLhandleARB programObj) { GLint attached_shaders = 0; glGetObjectParameterivARB(programObj, GL_OBJECT_ATTACHED_OBJECTS_ARB, &attached_shaders); if (!attached_shaders) { return; } ShaderMap shaderMap; GLhandleARB *shaderObjs = new GLhandleARB[attached_shaders]; GLsizei count = 0; glGetAttachedObjectsARB(programObj, attached_shaders, &count, shaderObjs); std::sort(shaderObjs, shaderObjs + count); for (GLsizei i = 0; i < count; ++ i) { getShaderObjSource(shaderMap, shaderObjs[i]); } delete [] shaderObjs; for (ShaderMap::const_iterator it = shaderMap.begin(); it != shaderMap.end(); ++it) { json.beginMember(it->first); json.writeString(it->second); json.endMember(); } } /* * When fetching the uniform name of an array we usually get name[0] * so we need to cut the trailing "[0]" in order to properly construct * array names later. Otherwise we endup with stuff like * uniformArray[0][0], * uniformArray[0][1], * instead of * uniformArray[0], * uniformArray[1]. */ static std::string resolveUniformName(const GLchar *name, GLint size) { std::string qualifiedName(name); if (size > 1) { std::string::size_type nameLength = qualifiedName.length(); static const char * const arrayStart = "[0]"; static const int arrayStartLen = 3; if (qualifiedName.rfind(arrayStart) == (nameLength - arrayStartLen)) { qualifiedName = qualifiedName.substr(0, nameLength - 3); } } return qualifiedName; } static void dumpUniform(JSONWriter &json, GLint program, GLint size, GLenum type, const GLchar *name) { GLenum elemType; GLint numElems; __gl_uniform_size(type, elemType, numElems); if (elemType == GL_NONE) { return; } GLfloat fvalues[4*4]; GLdouble dvalues[4*4]; GLint ivalues[4*4]; GLuint uivalues[4*4]; GLint i, j; std::string qualifiedName = resolveUniformName(name, size); for (i = 0; i < size; ++i) { std::stringstream ss; ss << qualifiedName; if (size > 1) { ss << '[' << i << ']'; } std::string elemName = ss.str(); json.beginMember(elemName); GLint location = glGetUniformLocation(program, elemName.c_str()); if (numElems > 1) { json.beginArray(); } switch (elemType) { case GL_FLOAT: glGetUniformfv(program, location, fvalues); for (j = 0; j < numElems; ++j) { json.writeNumber(fvalues[j]); } break; case GL_DOUBLE: glGetUniformdv(program, location, dvalues); for (j = 0; j < numElems; ++j) { json.writeNumber(dvalues[j]); } break; case GL_INT: glGetUniformiv(program, location, ivalues); for (j = 0; j < numElems; ++j) { json.writeNumber(ivalues[j]); } break; case GL_UNSIGNED_INT: glGetUniformuiv(program, location, uivalues); for (j = 0; j < numElems; ++j) { json.writeNumber(uivalues[j]); } break; case GL_BOOL: glGetUniformiv(program, location, ivalues); for (j = 0; j < numElems; ++j) { json.writeBool(ivalues[j]); } break; default: assert(0); break; } if (numElems > 1) { json.endArray(); } json.endMember(); } } static void dumpUniformARB(JSONWriter &json, GLhandleARB programObj, GLint size, GLenum type, const GLchar *name) { GLenum elemType; GLint numElems; __gl_uniform_size(type, elemType, numElems); if (elemType == GL_NONE) { return; } GLfloat fvalues[4*4]; GLint ivalues[4*4]; GLint i, j; std::string qualifiedName = resolveUniformName(name, size); for (i = 0; i < size; ++i) { std::stringstream ss; ss << qualifiedName; if (size > 1) { ss << '[' << i << ']'; } std::string elemName = ss.str(); json.beginMember(elemName); GLint location = glGetUniformLocationARB(programObj, elemName.c_str()); if (numElems > 1) { json.beginArray(); } switch (elemType) { case GL_DOUBLE: // glGetUniformdvARB does not exists case GL_FLOAT: glGetUniformfvARB(programObj, location, fvalues); for (j = 0; j < numElems; ++j) { json.writeNumber(fvalues[j]); } break; case GL_UNSIGNED_INT: // glGetUniformuivARB does not exists case GL_INT: glGetUniformivARB(programObj, location, ivalues); for (j = 0; j < numElems; ++j) { json.writeNumber(ivalues[j]); } break; case GL_BOOL: glGetUniformivARB(programObj, location, ivalues); for (j = 0; j < numElems; ++j) { json.writeBool(ivalues[j]); } break; default: assert(0); break; } if (numElems > 1) { json.endArray(); } json.endMember(); } } static inline void dumpProgramUniforms(JSONWriter &json, GLint program) { GLint active_uniforms = 0; glGetProgramiv(program, GL_ACTIVE_UNIFORMS, &active_uniforms); if (!active_uniforms) { return; } GLint active_uniform_max_length = 0; glGetProgramiv(program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &active_uniform_max_length); GLchar *name = new GLchar[active_uniform_max_length]; if (!name) { return; } for (GLint index = 0; index < active_uniforms; ++index) { GLsizei length = 0; GLint size = 0; GLenum type = GL_NONE; glGetActiveUniform(program, index, active_uniform_max_length, &length, &size, &type, name); dumpUniform(json, program, size, type, name); } delete [] name; } static inline void dumpProgramObjUniforms(JSONWriter &json, GLhandleARB programObj) { GLint active_uniforms = 0; glGetObjectParameterivARB(programObj, GL_OBJECT_ACTIVE_UNIFORMS_ARB, &active_uniforms); if (!active_uniforms) { return; } GLint active_uniform_max_length = 0; glGetObjectParameterivARB(programObj, GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB, &active_uniform_max_length); GLchar *name = new GLchar[active_uniform_max_length]; if (!name) { return; } for (GLint index = 0; index < active_uniforms; ++index) { GLsizei length = 0; GLint size = 0; GLenum type = GL_NONE; glGetActiveUniformARB(programObj, index, active_uniform_max_length, &length, &size, &type, name); dumpUniformARB(json, programObj, size, type, name); } delete [] name; } static inline void dumpArbProgram(JSONWriter &json, GLenum target) { if (!glIsEnabled(target)) { return; } GLint program_length = 0; glGetProgramivARB(target, GL_PROGRAM_LENGTH_ARB, &program_length); if (!program_length) { return; } GLchar *source = new GLchar[program_length + 1]; source[0] = 0; glGetProgramStringARB(target, GL_PROGRAM_STRING_ARB, source); source[program_length] = 0; json.beginMember(enumToString(target)); json.writeString(source); json.endMember(); delete [] source; } static inline void dumpArbProgramUniforms(JSONWriter &json, GLenum target, const char *prefix) { if (!glIsEnabled(target)) { return; } GLint program_parameters = 0; glGetProgramivARB(target, GL_PROGRAM_PARAMETERS_ARB, &program_parameters); if (!program_parameters) { return; } GLint max_program_local_parameters = 0; glGetProgramivARB(target, GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB, &max_program_local_parameters); for (GLint index = 0; index < max_program_local_parameters; ++index) { GLdouble params[4] = {0, 0, 0, 0}; glGetProgramLocalParameterdvARB(target, index, params); if (!params[0] && !params[1] && !params[2] && !params[3]) { continue; } char name[256]; snprintf(name, sizeof name, "%sprogram.local[%i]", prefix, index); json.beginMember(name); json.beginArray(); json.writeNumber(params[0]); json.writeNumber(params[1]); json.writeNumber(params[2]); json.writeNumber(params[3]); json.endArray(); json.endMember(); } GLint max_program_env_parameters = 0; glGetProgramivARB(target, GL_MAX_PROGRAM_ENV_PARAMETERS_ARB, &max_program_env_parameters); for (GLint index = 0; index < max_program_env_parameters; ++index) { GLdouble params[4] = {0, 0, 0, 0}; glGetProgramEnvParameterdvARB(target, index, params); if (!params[0] && !params[1] && !params[2] && !params[3]) { continue; } char name[256]; snprintf(name, sizeof name, "%sprogram.env[%i]", prefix, index); json.beginMember(name); json.beginArray(); json.writeNumber(params[0]); json.writeNumber(params[1]); json.writeNumber(params[2]); json.writeNumber(params[3]); json.endArray(); json.endMember(); } } static inline void dumpShadersUniforms(JSONWriter &json) { GLint program = 0; glGetIntegerv(GL_CURRENT_PROGRAM, &program); GLhandleARB programObj = glGetHandleARB(GL_PROGRAM_OBJECT_ARB); json.beginMember("shaders"); json.beginObject(); if (program) { dumpProgram(json, program); } else if (programObj) { dumpProgramObj(json, programObj); } else { dumpArbProgram(json, GL_FRAGMENT_PROGRAM_ARB); dumpArbProgram(json, GL_VERTEX_PROGRAM_ARB); } json.endObject(); json.endMember(); // shaders json.beginMember("uniforms"); json.beginObject(); if (program) { dumpProgramUniforms(json, program); } else if (programObj) { dumpProgramObjUniforms(json, programObj); } else { dumpArbProgramUniforms(json, GL_FRAGMENT_PROGRAM_ARB, "fp."); dumpArbProgramUniforms(json, GL_VERTEX_PROGRAM_ARB, "vp."); } json.endObject(); json.endMember(); // uniforms } static inline void dumpTextureImage(JSONWriter &json, GLenum target, GLint level) { GLint width, height = 1, depth = 1; GLint format; glGetTexLevelParameteriv(target, level, GL_TEXTURE_INTERNAL_FORMAT, &format); width = 0; glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width); if (target != GL_TEXTURE_1D) { height = 0; glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height); if (target == GL_TEXTURE_3D) { depth = 0; glGetTexLevelParameteriv(target, level, GL_TEXTURE_DEPTH, &depth); } } if (width <= 0 || height <= 0 || depth <= 0) { return; } else { char label[512]; GLint active_texture = GL_TEXTURE0; glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture); snprintf(label, sizeof label, "%s, %s, level = %d", enumToString(active_texture), enumToString(target), level); json.beginMember(label); json.beginObject(); // Tell the GUI this is no ordinary object, but an image json.writeStringMember("__class__", "image"); json.writeNumberMember("__width__", width); json.writeNumberMember("__height__", height); json.writeNumberMember("__depth__", depth); json.writeStringMember("__format__", enumToString(format)); // Hardcoded for now, but we could chose types more adequate to the // texture internal format json.writeStringMember("__type__", "uint8"); json.writeBoolMember("__normalized__", true); json.writeNumberMember("__channels__", 4); GLubyte *pixels = new GLubyte[depth*width*height*4]; resetPixelPackState(); glGetTexImage(target, level, GL_RGBA, GL_UNSIGNED_BYTE, pixels); restorePixelPackState(); json.beginMember("__data__"); char *pngBuffer; int pngBufferSize; image::writePixelsToBuffer(pixels, width, height, 4, true, &pngBuffer, &pngBufferSize); json.writeBase64(pngBuffer, pngBufferSize); free(pngBuffer); json.endMember(); // __data__ delete [] pixels; json.endObject(); } } static inline void dumpTexture(JSONWriter &json, GLenum target, GLenum binding) { GLint texture_binding = 0; glGetIntegerv(binding, &texture_binding); if (!glIsEnabled(target) && !texture_binding) { return; } GLint level = 0; do { GLint width = 0, height = 0; glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width); glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height); if (!width || !height) { break; } if (target == GL_TEXTURE_CUBE_MAP) { for (int face = 0; face < 6; ++face) { dumpTextureImage(json, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level); } } else { dumpTextureImage(json, target, level); } ++level; } while(true); } static inline void dumpTextures(JSONWriter &json) { json.beginMember("textures"); json.beginObject(); GLint active_texture = GL_TEXTURE0; glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture); GLint max_texture_coords = 0; glGetIntegerv(GL_MAX_TEXTURE_COORDS, &max_texture_coords); GLint max_combined_texture_image_units = 0; glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_combined_texture_image_units); GLint max_units = std::max(max_combined_texture_image_units, max_texture_coords); for (GLint unit = 0; unit < max_units; ++unit) { GLenum texture = GL_TEXTURE0 + unit; glActiveTexture(texture); dumpTexture(json, GL_TEXTURE_1D, GL_TEXTURE_BINDING_1D); dumpTexture(json, GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D); dumpTexture(json, GL_TEXTURE_3D, GL_TEXTURE_BINDING_3D); dumpTexture(json, GL_TEXTURE_RECTANGLE, GL_TEXTURE_BINDING_RECTANGLE); dumpTexture(json, GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BINDING_CUBE_MAP); } glActiveTexture(active_texture); json.endObject(); json.endMember(); // textures } static bool getDrawableBounds(GLint *width, GLint *height) { #if defined(_WIN32) HDC hDC = wglGetCurrentDC(); if (!hDC) { return false; } HWND hWnd = WindowFromDC(hDC); RECT rect; if (!GetClientRect(hWnd, &rect)) { return false; } *width = rect.right - rect.left; *height = rect.bottom - rect.top; #elif defined(__APPLE__) CGLContextObj ctx = CGLGetCurrentContext(); if (ctx == NULL) { return false; } CGSConnectionID cid; CGSWindowID wid; CGSSurfaceID sid; if (CGLGetSurface(ctx, &cid, &wid, &sid) != kCGLNoError) { return false; } CGRect rect; if (CGSGetSurfaceBounds(cid, wid, sid, &rect) != 0) { return false; } *width = rect.size.width; *height = rect.size.height; #else #if !TRACE_EGL Display *display; Drawable drawable; Window root; int x, y; unsigned int w, h, bw, depth; display = glXGetCurrentDisplay(); if (!display) { return false; } drawable = glXGetCurrentDrawable(); if (drawable == None) { return false; } if (!XGetGeometry(display, drawable, &root, &x, &y, &w, &h, &bw, &depth)) { return false; } *width = w; *height = h; #else return false; #endif #endif return true; } static const GLenum texture_bindings[][2] = { {GL_TEXTURE_1D, GL_TEXTURE_BINDING_1D}, {GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D}, {GL_TEXTURE_3D, GL_TEXTURE_BINDING_3D}, {GL_TEXTURE_RECTANGLE, GL_TEXTURE_BINDING_RECTANGLE}, {GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BINDING_CUBE_MAP} }; static bool bindTexture(GLint texture, GLenum &target, GLint &bound_texture) { for (unsigned i = 0; i < sizeof(texture_bindings)/sizeof(texture_bindings[0]); ++i) { target = texture_bindings[i][0]; GLenum binding = texture_bindings[i][1]; while (glGetError() != GL_NO_ERROR) ; glGetIntegerv(binding, &bound_texture); glBindTexture(target, texture); if (glGetError() == GL_NO_ERROR) { return true; } glBindTexture(target, bound_texture); } target = GL_NONE; return false; } static bool getTextureLevelSize(GLint texture, GLint level, GLint *width, GLint *height) { *width = 0; *height = 0; GLenum target; GLint bound_texture = 0; if (!bindTexture(texture, target, bound_texture)) { return false; } glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, width); glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, height); glBindTexture(target, bound_texture); return *width > 0 && *height > 0; } static GLenum getTextureLevelFormat(GLint texture, GLint level) { GLenum target; GLint bound_texture = 0; if (!bindTexture(texture, target, bound_texture)) { return GL_NONE; } GLint format = GL_NONE; glGetTexLevelParameteriv(target, level, GL_TEXTURE_INTERNAL_FORMAT, &format); glBindTexture(target, bound_texture); return format; } static bool getRenderbufferSize(GLint renderbuffer, GLint *width, GLint *height) { GLint bound_renderbuffer = 0; glGetIntegerv(GL_RENDERBUFFER_BINDING, &bound_renderbuffer); glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer); *width = 0; *height = 0; glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, width); glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, height); glBindRenderbuffer(GL_RENDERBUFFER, bound_renderbuffer); return *width > 0 && *height > 0; } static GLenum getRenderbufferFormat(GLint renderbuffer) { GLint bound_renderbuffer = 0; glGetIntegerv(GL_RENDERBUFFER_BINDING, &bound_renderbuffer); glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer); GLint format = GL_NONE; glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_INTERNAL_FORMAT, &format); glBindRenderbuffer(GL_RENDERBUFFER, bound_renderbuffer); return format; } static bool getFramebufferAttachmentSize(GLenum target, GLenum attachment, GLint *width, GLint *height) { GLint object_type = GL_NONE; glGetFramebufferAttachmentParameteriv(target, attachment, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type); if (object_type == GL_NONE) { return false; } GLint object_name = 0; glGetFramebufferAttachmentParameteriv(target, attachment, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &object_name); if (object_name == 0) { return false; } if (object_type == GL_RENDERBUFFER) { return getRenderbufferSize(object_name, width, height); } else if (object_type == GL_TEXTURE) { GLint texture_level = 0; glGetFramebufferAttachmentParameteriv(target, attachment, GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, &texture_level); return getTextureLevelSize(object_name, texture_level, width, height); } else { std::cerr << "warning: unexpected GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = " << object_type << "\n"; return false; } } static GLint getFramebufferAttachmentFormat(GLenum target, GLenum attachment) { GLint object_type = GL_NONE; glGetFramebufferAttachmentParameteriv(target, attachment, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type); if (object_type == GL_NONE) { return GL_NONE; } GLint object_name = 0; glGetFramebufferAttachmentParameteriv(target, attachment, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &object_name); if (object_name == 0) { return GL_NONE; } if (object_type == GL_RENDERBUFFER) { return getRenderbufferFormat(object_name); } else if (object_type == GL_TEXTURE) { GLint texture_level = 0; glGetFramebufferAttachmentParameteriv(target, attachment, GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, &texture_level); return getTextureLevelFormat(object_name, texture_level); } else { std::cerr << "warning: unexpected GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = " << object_type << "\n"; return GL_NONE; } } image::Image * getDrawBufferImage(GLenum format) { GLint channels = __gl_format_channels(format); if (channels > 4) { return NULL; } GLint draw_framebuffer = 0; glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &draw_framebuffer); GLint draw_buffer = GL_NONE; GLint width, height; if (draw_framebuffer) { glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer); if (draw_buffer == GL_NONE) { return NULL; } if (!getFramebufferAttachmentSize(GL_DRAW_FRAMEBUFFER, draw_buffer, &width, &height)) { return NULL; } } else { glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer); if (draw_buffer == GL_NONE) { return NULL; } if (!getDrawableBounds(&width, &height)) { return NULL; } } image::Image *image = new image::Image(width, height, channels, true); if (!image) { return NULL; } while (glGetError() != GL_NO_ERROR) {} GLint read_framebuffer = 0; glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer); glBindFramebuffer(GL_READ_FRAMEBUFFER, draw_framebuffer); GLint read_buffer = 0; glGetIntegerv(GL_READ_BUFFER, &read_buffer); glReadBuffer(draw_buffer); // TODO: reset imaging state too resetPixelPackState(); glReadPixels(0, 0, width, height, format, GL_UNSIGNED_BYTE, image->pixels); restorePixelPackState(); glReadBuffer(read_buffer); glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer); GLenum error = glGetError(); if (error != GL_NO_ERROR) { do { std::cerr << "warning: " << enumToString(error) << " while getting snapshot\n"; error = glGetError(); } while(error != GL_NO_ERROR); delete image; return NULL; } return image; } /** * Dump the image of the currently bound read buffer. */ static inline void dumpReadBufferImage(JSONWriter &json, GLint width, GLint height, GLenum format, GLint internalFormat = GL_NONE) { GLint channels = __gl_format_channels(format); json.beginObject(); // Tell the GUI this is no ordinary object, but an image json.writeStringMember("__class__", "image"); json.writeNumberMember("__width__", width); json.writeNumberMember("__height__", height); json.writeNumberMember("__depth__", 1); json.writeStringMember("__format__", enumToString(internalFormat)); // Hardcoded for now, but we could chose types more adequate to the // texture internal format json.writeStringMember("__type__", "uint8"); json.writeBoolMember("__normalized__", true); json.writeNumberMember("__channels__", channels); GLubyte *pixels = new GLubyte[width*height*channels]; // TODO: reset imaging state too resetPixelPackState(); glReadPixels(0, 0, width, height, format, GL_UNSIGNED_BYTE, pixels); restorePixelPackState(); json.beginMember("__data__"); char *pngBuffer; int pngBufferSize; image::writePixelsToBuffer(pixels, width, height, channels, true, &pngBuffer, &pngBufferSize); //std::cerr <<" Before = "<<(width * height * channels * sizeof *pixels) // <<", after = "<<pngBufferSize << ", ratio = " << double(width * height * channels * sizeof *pixels)/pngBufferSize; json.writeBase64(pngBuffer, pngBufferSize); free(pngBuffer); json.endMember(); // __data__ delete [] pixels; json.endObject(); } static inline GLuint downsampledFramebuffer(GLuint oldFbo, GLint drawbuffer, GLint colorRb, GLint depthRb, GLint stencilRb, GLuint *rbs, GLint *numRbs) { GLuint fbo; GLint format; GLint w, h; *numRbs = 0; glGenFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER, fbo); glBindRenderbuffer(GL_RENDERBUFFER, colorRb); glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &w); glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &h); glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_INTERNAL_FORMAT, &format); glGenRenderbuffers(1, &rbs[*numRbs]); glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]); glRenderbufferStorage(GL_RENDERBUFFER, format, w, h); glFramebufferRenderbuffer(GL_FRAMEBUFFER, drawbuffer, GL_RENDERBUFFER, rbs[*numRbs]); glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo); glDrawBuffer(drawbuffer); glReadBuffer(drawbuffer); glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_NEAREST); glBindFramebuffer(GL_FRAMEBUFFER, fbo); ++*numRbs; if (stencilRb == depthRb && stencilRb) { //combined depth and stencil buffer glBindRenderbuffer(GL_RENDERBUFFER, depthRb); glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &w); glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &h); glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_INTERNAL_FORMAT, &format); glGenRenderbuffers(1, &rbs[*numRbs]); glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]); glRenderbufferStorage(GL_RENDERBUFFER, format, w, h); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbs[*numRbs]); glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo); glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST); glBindFramebuffer(GL_FRAMEBUFFER, fbo); ++*numRbs; } else { if (depthRb) { glBindRenderbuffer(GL_RENDERBUFFER, depthRb); glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &w); glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &h); glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_INTERNAL_FORMAT, &format); glGenRenderbuffers(1, &rbs[*numRbs]); glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]); glRenderbufferStorage(GL_RENDERBUFFER, format, w, h); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rbs[*numRbs]); glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo); glDrawBuffer(GL_DEPTH_ATTACHMENT); glReadBuffer(GL_DEPTH_ATTACHMENT); glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_DEPTH_BUFFER_BIT, GL_NEAREST); ++*numRbs; } if (stencilRb) { glBindRenderbuffer(GL_RENDERBUFFER, stencilRb); glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &w); glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &h); glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_INTERNAL_FORMAT, &format); glGenRenderbuffers(1, &rbs[*numRbs]); glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]); glRenderbufferStorage(GL_RENDERBUFFER, format, w, h); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbs[*numRbs]); glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo); glDrawBuffer(GL_STENCIL_ATTACHMENT); glReadBuffer(GL_STENCIL_ATTACHMENT); glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_STENCIL_BUFFER_BIT, GL_NEAREST); ++*numRbs; } } return fbo; } /** * Dump images of current draw drawable/window. */ static void dumpDrawableImages(JSONWriter &json) { GLint width, height; if (!getDrawableBounds(&width, &height)) { return; } GLint draw_buffer = GL_NONE; glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer); glReadBuffer(draw_buffer); if (draw_buffer != GL_NONE) { GLint read_buffer = GL_NONE; glGetIntegerv(GL_READ_BUFFER, &read_buffer); GLint alpha_bits = 0; glGetIntegerv(GL_ALPHA_BITS, &alpha_bits); GLenum format = alpha_bits ? GL_RGBA : GL_RGB; json.beginMember(enumToString(draw_buffer)); dumpReadBufferImage(json, width, height, format); json.endMember(); glReadBuffer(read_buffer); } GLint depth_bits = 0; glGetIntegerv(GL_DEPTH_BITS, &depth_bits); if (depth_bits) { json.beginMember("GL_DEPTH_COMPONENT"); dumpReadBufferImage(json, width, height, GL_DEPTH_COMPONENT); json.endMember(); } GLint stencil_bits = 0; glGetIntegerv(GL_STENCIL_BITS, &stencil_bits); if (stencil_bits) { json.beginMember("GL_STENCIL_INDEX"); dumpReadBufferImage(json, width, height, GL_STENCIL_INDEX); json.endMember(); } } /** * Dump the specified framebuffer attachment. * * In the case of a color attachment, it assumes it is already bound for read. */ static void dumpFramebufferAttachment(JSONWriter &json, GLenum target, GLenum attachment, GLenum format) { GLint width = 0, height = 0; if (!getFramebufferAttachmentSize(target, attachment, &width, &height)) { return; } GLint internalFormat = getFramebufferAttachmentFormat(target, attachment); json.beginMember(enumToString(attachment)); dumpReadBufferImage(json, width, height, format, internalFormat); json.endMember(); } static void dumpFramebufferAttachments(JSONWriter &json, GLenum target) { GLint read_framebuffer = 0; glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer); GLint read_buffer = GL_NONE; glGetIntegerv(GL_READ_BUFFER, &read_buffer); GLint max_draw_buffers = 1; glGetIntegerv(GL_MAX_DRAW_BUFFERS, &max_draw_buffers); GLint max_color_attachments = 0; glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &max_color_attachments); for (GLint i = 0; i < max_draw_buffers; ++i) { GLint draw_buffer = GL_NONE; glGetIntegerv(GL_DRAW_BUFFER0 + i, &draw_buffer); if (draw_buffer != GL_NONE) { glReadBuffer(draw_buffer); GLint attachment; if (draw_buffer >= GL_COLOR_ATTACHMENT0 && draw_buffer < GL_COLOR_ATTACHMENT0 + max_color_attachments) { attachment = draw_buffer; } else { std::cerr << "warning: unexpected GL_DRAW_BUFFER" << i << " = " << draw_buffer << "\n"; attachment = GL_COLOR_ATTACHMENT0; } GLint alpha_size = 0; glGetFramebufferAttachmentParameteriv(target, attachment, GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE, &alpha_size); GLenum format = alpha_size ? GL_RGBA : GL_RGB; dumpFramebufferAttachment(json, target, attachment, format); } } glReadBuffer(read_buffer); dumpFramebufferAttachment(json, target, GL_DEPTH_ATTACHMENT, GL_DEPTH_COMPONENT); dumpFramebufferAttachment(json, target, GL_STENCIL_ATTACHMENT, GL_STENCIL_INDEX); glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer); } static void dumpFramebuffer(JSONWriter &json) { json.beginMember("framebuffer"); json.beginObject(); GLint boundDrawFbo = 0, boundReadFbo = 0; glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundDrawFbo); glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundReadFbo); if (!boundDrawFbo) { dumpDrawableImages(json); } else { GLint colorRb = 0, stencilRb = 0, depthRb = 0; GLint draw_buffer0 = GL_NONE; glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer0); bool multisample = false; GLint boundRb = 0; glGetIntegerv(GL_RENDERBUFFER_BINDING, &boundRb); GLint object_type; glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, draw_buffer0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type); if (object_type == GL_RENDERBUFFER) { glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, draw_buffer0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &colorRb); glBindRenderbuffer(GL_RENDERBUFFER, colorRb); GLint samples = 0; glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples); if (samples) { multisample = true; } } glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type); if (object_type == GL_RENDERBUFFER) { glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &depthRb); glBindRenderbuffer(GL_RENDERBUFFER, depthRb); GLint samples = 0; glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples); if (samples) { multisample = true; } } glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type); if (object_type == GL_RENDERBUFFER) { glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &stencilRb); glBindRenderbuffer(GL_RENDERBUFFER, stencilRb); GLint samples = 0; glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples); if (samples) { multisample = true; } } glBindRenderbuffer(GL_RENDERBUFFER, boundRb); GLuint rbs[3]; GLint numRbs = 0; GLuint fboCopy = 0; if (multisample) { // glReadPixels doesnt support multisampled buffers so we need // to blit the fbo to a temporary one fboCopy = downsampledFramebuffer(boundDrawFbo, draw_buffer0, colorRb, depthRb, stencilRb, rbs, &numRbs); } dumpFramebufferAttachments(json, GL_DRAW_FRAMEBUFFER); if (multisample) { glBindRenderbuffer(GL_RENDERBUFFER_BINDING, boundRb); glDeleteRenderbuffers(numRbs, rbs); glDeleteFramebuffers(1, &fboCopy); } glBindFramebuffer(GL_READ_FRAMEBUFFER, boundReadFbo); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, boundDrawFbo); } json.endObject(); json.endMember(); // framebuffer } static const GLenum bindings[] = { GL_DRAW_BUFFER, GL_READ_BUFFER, GL_PIXEL_PACK_BUFFER_BINDING, GL_PIXEL_UNPACK_BUFFER_BINDING, GL_TEXTURE_BINDING_1D, GL_TEXTURE_BINDING_2D, GL_TEXTURE_BINDING_3D, GL_TEXTURE_BINDING_RECTANGLE, GL_TEXTURE_BINDING_CUBE_MAP, GL_DRAW_FRAMEBUFFER_BINDING, GL_READ_FRAMEBUFFER_BINDING, GL_RENDERBUFFER_BINDING, GL_DRAW_BUFFER0, GL_DRAW_BUFFER1, GL_DRAW_BUFFER2, GL_DRAW_BUFFER3, GL_DRAW_BUFFER4, GL_DRAW_BUFFER5, GL_DRAW_BUFFER6, GL_DRAW_BUFFER7, }; #define NUM_BINDINGS sizeof(bindings)/sizeof(bindings[0]) void dumpCurrentContext(std::ostream &os) { JSONWriter json(os); #ifndef NDEBUG GLint old_bindings[NUM_BINDINGS]; for (unsigned i = 0; i < NUM_BINDINGS; ++i) { old_bindings[i] = 0; glGetIntegerv(bindings[i], &old_bindings[i]); } #endif dumpParameters(json); dumpShadersUniforms(json); dumpTextures(json); dumpFramebuffer(json); #ifndef NDEBUG for (unsigned i = 0; i < NUM_BINDINGS; ++i) { GLint new_binding = 0; glGetIntegerv(bindings[i], &new_binding); if (new_binding != old_bindings[i]) { std::cerr << "warning: " << enumToString(bindings[i]) << " was clobbered\n"; } } #endif } } /* namespace glstate */
29.709028
145
0.634254
prahal
3293ffac38541bdbd5aa838b8b39b45efafd8ca3
1,218
hpp
C++
Software/STM/APP/Screens/StateAccel.hpp
ProrokWielki/Wooden-Clock
96226750ab4b679764b0b254d3c3c21deb658252
[ "MIT" ]
1
2018-12-14T07:05:33.000Z
2018-12-14T07:05:33.000Z
Software/STM/APP/Screens/StateAccel.hpp
ProrokWielki/Wooden-Clock
96226750ab4b679764b0b254d3c3c21deb658252
[ "MIT" ]
null
null
null
Software/STM/APP/Screens/StateAccel.hpp
ProrokWielki/Wooden-Clock
96226750ab4b679764b0b254d3c3c21deb658252
[ "MIT" ]
null
null
null
/** * StataAccel.hpp * * Created on: 02-05-2020 * @author: Paweł Warzecha */ #ifndef APP_STATEMACHINE_STATES_STATEACCEL_HPP_ #define APP_STATEMACHINE_STATES_STATEACCEL_HPP_ #include <Canvas.hpp> #include "LSM9DS1/LSM9DS1.hpp" #include "BSP.hpp" class StateAccel: public Canvas { public: explicit StateAccel(LSM9DS1 & accel) : accel_(accel), magnet(32, 32, &empty_frame_buffer[0][0]) { } void init() override { add(&magnet); validate(); } virtual void up_date() override { static uint8_t old_x = 0; static uint8_t old_y = 0; int16_t x = accel_.get_linear_acceleration(Axis::X); int16_t y = accel_.get_linear_acceleration(Axis::Y); x = ((-x * 16) >> 14) + 16; y = ((y * 16) >> 14) + 16; x = x > 31 ? 31 : x; y = y > 31 ? 31 : y; x = x < 0 ? 0 : x; y = y < 0 ? 0 : y; empty_frame_buffer[old_y][old_x] = 0; old_x = x; old_y = y; empty_frame_buffer[y][x] = 255; validate(); } private: LSM9DS1 & accel_; uint8_t empty_frame_buffer[32][32] = {0}; Image magnet; }; #endif /* APP_STATEMACHINE_STATES_STATENORTH_HPP_ */
19.03125
99
0.569787
ProrokWielki
3298f89e4f50077b33b105f16202820fef1bbd25
2,554
cc
C++
test/limits.cc
root-project/VecCore
9375eb6005d08b2bca3b0a2b62e90dbe21694176
[ "Apache-2.0" ]
56
2017-04-12T17:57:33.000Z
2021-12-18T03:28:24.000Z
test/limits.cc
root-project/VecCore
9375eb6005d08b2bca3b0a2b62e90dbe21694176
[ "Apache-2.0" ]
19
2017-05-09T06:40:48.000Z
2021-11-01T09:54:24.000Z
test/limits.cc
root-project/VecCore
9375eb6005d08b2bca3b0a2b62e90dbe21694176
[ "Apache-2.0" ]
22
2017-04-10T13:41:15.000Z
2021-08-20T09:05:10.000Z
#include "test.h" template <class T> class NumericLimitsTest : public VectorTypeTest<T> {}; TYPED_TEST_SUITE_P(NumericLimitsTest); TYPED_TEST_P(NumericLimitsTest, Limits) { using Scalar_t = typename TestFixture::Scalar_t; using Vector_t = typename TestFixture::Vector_t; using vecCore::Get; using vecCore::NumericLimits; using vecCore::VectorSize; size_t N = VectorSize<Vector_t>(); EXPECT_TRUE(NumericLimits<Scalar_t>::Min() == Get(NumericLimits<Vector_t>::Min(), 0)); EXPECT_TRUE(NumericLimits<Scalar_t>::Max() == Get(NumericLimits<Vector_t>::Max(), 0)); EXPECT_TRUE(NumericLimits<Scalar_t>::Lowest() == Get(NumericLimits<Vector_t>::Lowest(), 0)); EXPECT_TRUE(NumericLimits<Scalar_t>::Highest() == Get(NumericLimits<Vector_t>::Highest(), 0)); EXPECT_TRUE(NumericLimits<Scalar_t>::Epsilon() == Get(NumericLimits<Vector_t>::Epsilon(), 0)); EXPECT_TRUE(NumericLimits<Scalar_t>::Infinity() == Get(NumericLimits<Vector_t>::Infinity(), 0)); EXPECT_TRUE(NumericLimits<Scalar_t>::Min() == Get(NumericLimits<Vector_t>::Min(), N - 1)); EXPECT_TRUE(NumericLimits<Scalar_t>::Max() == Get(NumericLimits<Vector_t>::Max(), N - 1)); EXPECT_TRUE(NumericLimits<Scalar_t>::Lowest() == Get(NumericLimits<Vector_t>::Lowest(), N - 1)); EXPECT_TRUE(NumericLimits<Scalar_t>::Highest() == Get(NumericLimits<Vector_t>::Highest(), N - 1)); EXPECT_TRUE(NumericLimits<Scalar_t>::Epsilon() == Get(NumericLimits<Vector_t>::Epsilon(), N - 1)); EXPECT_TRUE(NumericLimits<Scalar_t>::Infinity() == Get(NumericLimits<Vector_t>::Infinity(), N - 1)); } REGISTER_TYPED_TEST_SUITE_P(NumericLimitsTest, Limits); #define TEST_BACKEND_P(name, x) \ INSTANTIATE_TYPED_TEST_SUITE_P(name, NumericLimitsTest, \ FloatTypes<vecCore::backend::x>); #define TEST_BACKEND(x) TEST_BACKEND_P(x, x) TEST_BACKEND(Scalar); TEST_BACKEND(ScalarWrapper); #ifdef VECCORE_ENABLE_VC TEST_BACKEND(VcScalar); TEST_BACKEND(VcVector); TEST_BACKEND_P(VcSimdArray, VcSimdArray<4>); #endif #ifdef VECCORE_ENABLE_UMESIMD TEST_BACKEND(UMESimd); TEST_BACKEND_P(UMESimdArray, UMESimdArray<4>); #endif #ifdef VECCORE_ENABLE_STD_SIMD TEST_BACKEND_P(SIMDScalar, SIMDScalar); TEST_BACKEND_P(SIMDVector4, SIMDVector<4>); TEST_BACKEND_P(SIMDVector8, SIMDVector<8>); TEST_BACKEND_P(SIMDNative, SIMDNative); #endif
35.472222
80
0.676586
root-project
32993408f853be203f88de88f31cbb638cafb756
1,277
cpp
C++
Task 3/RSA.cpp
John-Ghaly88/Cryptography_Course
7045e931c77032024bbebd2305895003a8625467
[ "MIT" ]
null
null
null
Task 3/RSA.cpp
John-Ghaly88/Cryptography_Course
7045e931c77032024bbebd2305895003a8625467
[ "MIT" ]
null
null
null
Task 3/RSA.cpp
John-Ghaly88/Cryptography_Course
7045e931c77032024bbebd2305895003a8625467
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int gcd(int x, int y) { if (x == 0) return y; return gcd(y % x, x); } int EulerTotient(int x) { int r = 1; for (int i = 2; i < x; i++) if (gcd(i, x) == 1) r++; return r; } int main() { cout << "Input n | n < 65536" << endl; int n; cin >> n; cout << "Input e (The public encryption key)" << endl; int e; cin >> e; cout << "Input the cipher encrypted text" << endl; string cipher; cin >> cipher; int phi = EulerTotient(n); int k = 11; int d = (1 + (k*phi))/e; //Assuming that the RSA algorithm used for encrypting this cipher text encodes the non-numerical text //into their corresponding ASCII number and perform the operation C = P^e mod n on this ASCII value string plain = ""; for (int i = 0; i < cipher.length(); i++) { if(cipher.at(i) != ' '){ int c = (int) cipher.at(i); double p = fmod(pow(c,d), n); plain.push_back((char)p); } else plain.push_back(' '); } cout << "The value of d (The private decryption key) is = " << d << endl; cout << "The plain decrypted text is: " << plain << endl; return 0; }
22.403509
106
0.512921
John-Ghaly88
32997875f0e6406feec6fd94326385f6ae80d4c6
484
cpp
C++
VD_prep/VR_rep_K2016/main.cpp
theroyalcoder/old.HF-ICT-4-SEM-GUI
d97bec83f339807a0054449421fe061ba901ddf3
[ "MIT" ]
null
null
null
VD_prep/VR_rep_K2016/main.cpp
theroyalcoder/old.HF-ICT-4-SEM-GUI
d97bec83f339807a0054449421fe061ba901ddf3
[ "MIT" ]
null
null
null
VD_prep/VR_rep_K2016/main.cpp
theroyalcoder/old.HF-ICT-4-SEM-GUI
d97bec83f339807a0054449421fe061ba901ddf3
[ "MIT" ]
1
2018-05-03T21:46:28.000Z
2018-05-03T21:46:28.000Z
#include <iostream> using namespace std; //Klausur 2015 int crossumRec(unsigned int n, int result) { return result + (n % 10); } int crossum(unsigned int n) { int result = 0; int localN = n; while (localN > 0) { result = crossumRec(localN, result); localN /= 10; } return result; } int main() { std::cout << "Hello, World!" << std::endl; cout << crossum(123); srand(static_cast<unsigned int>(time(nullptr))); return 0; }
16.689655
52
0.586777
theroyalcoder
329b7301fa019f359ee470e9ed947bfc831d8237
15,527
cc
C++
source/common/upstream/load_balancer_impl.cc
Sodman/envoy
9cb135e059ac6af052e5a5aa6c6c279aada1850b
[ "Apache-2.0" ]
null
null
null
source/common/upstream/load_balancer_impl.cc
Sodman/envoy
9cb135e059ac6af052e5a5aa6c6c279aada1850b
[ "Apache-2.0" ]
null
null
null
source/common/upstream/load_balancer_impl.cc
Sodman/envoy
9cb135e059ac6af052e5a5aa6c6c279aada1850b
[ "Apache-2.0" ]
1
2020-12-30T17:12:11.000Z
2020-12-30T17:12:11.000Z
#include "common/upstream/load_balancer_impl.h" #include <cstdint> #include <string> #include <vector> #include "envoy/runtime/runtime.h" #include "envoy/stats/stats.h" #include "envoy/upstream/upstream.h" #include "common/common/assert.h" namespace Envoy { namespace Upstream { namespace { const HostSet* bestAvailable(const PrioritySet* priority_set) { if (priority_set == nullptr) { return nullptr; } // This is used for LoadBalancerBase priority_set_ and local_priority_set_ // which are guaranteed to have at least one host set. ASSERT(priority_set->hostSetsPerPriority().size() > 0); for (auto& host_set : priority_set->hostSetsPerPriority()) { if (!host_set->healthyHosts().empty()) { return host_set.get(); } } return priority_set->hostSetsPerPriority()[0].get(); } } // namespace static const std::string RuntimeZoneEnabled = "upstream.zone_routing.enabled"; static const std::string RuntimeMinClusterSize = "upstream.zone_routing.min_cluster_size"; static const std::string RuntimePanicThreshold = "upstream.healthy_panic_threshold"; LoadBalancerBase::LoadBalancerBase(const PrioritySet& priority_set, const PrioritySet* local_priority_set, ClusterStats& stats, Runtime::Loader& runtime, Runtime::RandomGenerator& random) : stats_(stats), runtime_(runtime), random_(random), priority_set_(priority_set), best_available_host_set_(bestAvailable(&priority_set)), local_priority_set_(local_priority_set) { ASSERT(priority_set.hostSetsPerPriority().size() > 0); resizePerPriorityState(); priority_set_.addMemberUpdateCb([this](uint32_t priority, const std::vector<HostSharedPtr>&, const std::vector<HostSharedPtr>&) -> void { // Update the host set to use for picking, based on the new state. best_available_host_set_ = bestAvailable(&priority_set_); // Make sure per_priority_state_ is as large as priority_set_.hostSetsPerPriority() resizePerPriorityState(); // If there's a local priority set, regenerate all routing based on a potential size change to // the hosts routed to. if (local_priority_set_) { regenerateLocalityRoutingStructures(priority); } }); if (local_priority_set_) { // Multiple priorities are unsupported for local priority sets. // In order to support priorities correctly, one would have to make some assumptions about // routing (all local Envoys fail over at the same time) and use all priorities when computing // the locality routing structure. ASSERT(local_priority_set_->hostSetsPerPriority().size() == 1); local_priority_set_member_update_cb_handle_ = local_priority_set_->addMemberUpdateCb( [this](uint32_t priority, const std::vector<HostSharedPtr>&, const std::vector<HostSharedPtr>&) -> void { ASSERT(priority == 0); UNREFERENCED_PARAMETER(priority); // If the set of local Envoys changes, regenerate routing based on potential changes to // the set of servers routing to priority_set_. regenerateLocalityRoutingStructures(bestAvailablePriority()); }); } } LoadBalancerBase::~LoadBalancerBase() { if (local_priority_set_member_update_cb_handle_ != nullptr) { local_priority_set_member_update_cb_handle_->remove(); } } void LoadBalancerBase::regenerateLocalityRoutingStructures(uint32_t priority) { ASSERT(local_priority_set_); stats_.lb_recalculate_zone_structures_.inc(); // We are updating based on a change for a priority level in priority_set_, or the latched // bestAvailablePriority() which is a latched priority for priority_set_. ASSERT(priority < priority_set_.hostSetsPerPriority().size()); // resizePerPriorityState should ensure these stay in sync. ASSERT(per_priority_state_.size() == priority_set_.hostSetsPerPriority().size()); // Do not perform any calculations if we cannot perform locality routing based on non runtime // params. PerPriorityState& state = *per_priority_state_[priority]; if (earlyExitNonLocalityRouting(priority)) { state.locality_routing_state_ = LocalityRoutingState::NoLocalityRouting; return; } HostSet& host_set = *priority_set_.hostSetsPerPriority()[priority]; size_t num_localities = host_set.healthyHostsPerLocality().size(); ASSERT(num_localities > 0); uint64_t local_percentage[num_localities]; calculateLocalityPercentage(localHostSet().healthyHostsPerLocality(), local_percentage); uint64_t upstream_percentage[num_localities]; calculateLocalityPercentage(host_set.healthyHostsPerLocality(), upstream_percentage); // If we have lower percent of hosts in the local cluster in the same locality, // we can push all of the requests directly to upstream cluster in the same locality. if (upstream_percentage[0] >= local_percentage[0]) { state.locality_routing_state_ = LocalityRoutingState::LocalityDirect; return; } state.locality_routing_state_ = LocalityRoutingState::LocalityResidual; // If we cannot route all requests to the same locality, calculate what percentage can be routed. // For example, if local percentage is 20% and upstream is 10% // we can route only 50% of requests directly. state.local_percent_to_route_ = upstream_percentage[0] * 10000 / local_percentage[0]; // Local locality does not have additional capacity (we have already routed what we could). // Now we need to figure out how much traffic we can route cross locality and to which exact // locality we should route. Percentage of requests routed cross locality to a specific locality // needed be proportional to the residual capacity upstream locality has. // // residual_capacity contains capacity left in a given locality, we keep accumulating residual // capacity to make search for sampled value easier. // For example, if we have the following upstream and local percentage: // local_percentage: 40000 40000 20000 // upstream_percentage: 25000 50000 25000 // Residual capacity would look like: 0 10000 5000. Now we need to sample proportionally to // bucket sizes (residual capacity). For simplicity of finding where specific // sampled value is, we accumulate values in residual capacity. This is what it will look like: // residual_capacity: 0 10000 15000 // Now to find a locality to route (bucket) we could simply iterate over residual_capacity // searching where sampled value is placed. state.residual_capacity_.resize(num_localities); // Local locality (index 0) does not have residual capacity as we have routed all we could. state.residual_capacity_[0] = 0; for (size_t i = 1; i < num_localities; ++i) { // Only route to the localities that have additional capacity. if (upstream_percentage[i] > local_percentage[i]) { state.residual_capacity_[i] = state.residual_capacity_[i - 1] + upstream_percentage[i] - local_percentage[i]; } else { // Locality with index "i" does not have residual capacity, but we keep accumulating previous // values to make search easier on the next step. state.residual_capacity_[i] = state.residual_capacity_[i - 1]; } } }; void LoadBalancerBase::resizePerPriorityState() { const uint32_t size = priority_set_.hostSetsPerPriority().size(); while (per_priority_state_.size() < size) { per_priority_state_.push_back(PerPriorityStatePtr{new PerPriorityState}); } } bool LoadBalancerBase::earlyExitNonLocalityRouting(uint32_t priority) { if (priority_set_.hostSetsPerPriority().size() < priority + 1) { return true; } HostSet& host_set = *priority_set_.hostSetsPerPriority()[priority]; if (host_set.healthyHostsPerLocality().size() < 2) { return true; } if (host_set.healthyHostsPerLocality()[0].empty()) { return true; } // Same number of localities should be for local and upstream cluster. if (host_set.healthyHostsPerLocality().size() != localHostSet().healthyHostsPerLocality().size()) { stats_.lb_zone_number_differs_.inc(); return true; } // Do not perform locality routing for small clusters. uint64_t min_cluster_size = runtime_.snapshot().getInteger(RuntimeMinClusterSize, 6U); if (host_set.healthyHosts().size() < min_cluster_size) { stats_.lb_zone_cluster_too_small_.inc(); return true; } return false; } bool LoadBalancerUtility::isGlobalPanic(const HostSet& host_set, Runtime::Loader& runtime) { uint64_t global_panic_threshold = std::min<uint64_t>(100, runtime.snapshot().getInteger(RuntimePanicThreshold, 50)); double healthy_percent = host_set.hosts().size() == 0 ? 0 : 100.0 * host_set.healthyHosts().size() / host_set.hosts().size(); // If the % of healthy hosts in the cluster is less than our panic threshold, we use all hosts. if (healthy_percent < global_panic_threshold) { return true; } return false; } void LoadBalancerBase::calculateLocalityPercentage( const std::vector<std::vector<HostSharedPtr>>& hosts_per_locality, uint64_t* ret) { uint64_t total_hosts = 0; for (const auto& locality_hosts : hosts_per_locality) { total_hosts += locality_hosts.size(); } size_t i = 0; for (const auto& locality_hosts : hosts_per_locality) { ret[i++] = total_hosts > 0 ? 10000ULL * locality_hosts.size() / total_hosts : 0; } } const std::vector<HostSharedPtr>& LoadBalancerBase::tryChooseLocalLocalityHosts() { PerPriorityState& state = *per_priority_state_[bestAvailablePriority()]; ASSERT(state.locality_routing_state_ != LocalityRoutingState::NoLocalityRouting); // At this point it's guaranteed to be at least 2 localities. size_t number_of_localities = best_available_host_set_->healthyHostsPerLocality().size(); ASSERT(number_of_localities >= 2U); // Try to push all of the requests to the same locality first. if (state.locality_routing_state_ == LocalityRoutingState::LocalityDirect) { stats_.lb_zone_routing_all_directly_.inc(); return best_available_host_set_->healthyHostsPerLocality()[0]; } ASSERT(state.locality_routing_state_ == LocalityRoutingState::LocalityResidual); // If we cannot route all requests to the same locality, we already calculated how much we can // push to the local locality, check if we can push to local locality on current iteration. if (random_.random() % 10000 < state.local_percent_to_route_) { stats_.lb_zone_routing_sampled_.inc(); return best_available_host_set_->healthyHostsPerLocality()[0]; } // At this point we must route cross locality as we cannot route to the local locality. stats_.lb_zone_routing_cross_zone_.inc(); // This is *extremely* unlikely but possible due to rounding errors when calculating // locality percentages. In this case just select random locality. if (state.residual_capacity_[number_of_localities - 1] == 0) { stats_.lb_zone_no_capacity_left_.inc(); return best_available_host_set_ ->healthyHostsPerLocality()[random_.random() % number_of_localities]; } // Random sampling to select specific locality for cross locality traffic based on the additional // capacity in localities. uint64_t threshold = random_.random() % state.residual_capacity_[number_of_localities - 1]; // This potentially can be optimized to be O(log(N)) where N is the number of localities. // Linear scan should be faster for smaller N, in most of the scenarios N will be small. int i = 0; while (threshold > state.residual_capacity_[i]) { i++; } return best_available_host_set_->healthyHostsPerLocality()[i]; } const std::vector<HostSharedPtr>& LoadBalancerBase::hostsToUse() { ASSERT(best_available_host_set_->healthyHosts().size() <= best_available_host_set_->hosts().size()); // If the best available priority has insufficient healthy hosts, return all hosts. if (LoadBalancerUtility::isGlobalPanic(*best_available_host_set_, runtime_)) { stats_.lb_healthy_panic_.inc(); return best_available_host_set_->hosts(); } // If we've latched that we can't do priority-based routing, return healthy // hosts for the best available priority. if (per_priority_state_[bestAvailablePriority()]->locality_routing_state_ == LocalityRoutingState::NoLocalityRouting) { return best_available_host_set_->healthyHosts(); } // Determine if the load balancer should do zone based routing for this pick. if (!runtime_.snapshot().featureEnabled(RuntimeZoneEnabled, 100)) { return best_available_host_set_->healthyHosts(); } if (LoadBalancerUtility::isGlobalPanic(localHostSet(), runtime_)) { stats_.lb_local_cluster_not_ok_.inc(); // If the local Envoy instances are in global panic, do not do locality // based routing. return best_available_host_set_->healthyHosts(); } return tryChooseLocalLocalityHosts(); } HostConstSharedPtr RoundRobinLoadBalancer::chooseHost(LoadBalancerContext*) { const std::vector<HostSharedPtr>& hosts_to_use = hostsToUse(); if (hosts_to_use.empty()) { return nullptr; } return hosts_to_use[rr_index_++ % hosts_to_use.size()]; } LeastRequestLoadBalancer::LeastRequestLoadBalancer(const PrioritySet& priority_set, const PrioritySet* local_priority_set, ClusterStats& stats, Runtime::Loader& runtime, Runtime::RandomGenerator& random) : LoadBalancerBase(priority_set, local_priority_set, stats, runtime, random) { priority_set.addMemberUpdateCb([this](uint32_t, const std::vector<HostSharedPtr>&, const std::vector<HostSharedPtr>& hosts_removed) -> void { if (last_host_) { for (const HostSharedPtr& host : hosts_removed) { if (host == last_host_) { hits_left_ = 0; last_host_.reset(); break; } } } }); } HostConstSharedPtr LeastRequestLoadBalancer::chooseHost(LoadBalancerContext*) { bool is_weight_imbalanced = stats_.max_host_weight_.value() != 1; bool is_weight_enabled = runtime_.snapshot().getInteger("upstream.weight_enabled", 1UL) != 0; if (is_weight_imbalanced && hits_left_ > 0 && is_weight_enabled) { --hits_left_; return last_host_; } else { // To avoid hit stale last_host_ when all hosts become weight balanced. hits_left_ = 0; last_host_.reset(); } const std::vector<HostSharedPtr>& hosts_to_use = hostsToUse(); if (hosts_to_use.empty()) { return nullptr; } // Make weighed random if we have hosts with non 1 weights. if (is_weight_imbalanced & is_weight_enabled) { last_host_ = hosts_to_use[random_.random() % hosts_to_use.size()]; hits_left_ = last_host_->weight() - 1; return last_host_; } else { HostSharedPtr host1 = hosts_to_use[random_.random() % hosts_to_use.size()]; HostSharedPtr host2 = hosts_to_use[random_.random() % hosts_to_use.size()]; if (host1->stats().rq_active_.value() < host2->stats().rq_active_.value()) { return host1; } else { return host2; } } } HostConstSharedPtr RandomLoadBalancer::chooseHost(LoadBalancerContext*) { const std::vector<HostSharedPtr>& hosts_to_use = hostsToUse(); if (hosts_to_use.empty()) { return nullptr; } return hosts_to_use[random_.random() % hosts_to_use.size()]; } } // namespace Upstream } // namespace Envoy
40.968338
99
0.724351
Sodman
329e23d63c57f0da9e779735c030b5f29642fb8f
2,802
cpp
C++
aws-cpp-sdk-route53-recovery-cluster/source/model/RoutingControl.cpp
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-route53-recovery-cluster/source/model/RoutingControl.cpp
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-route53-recovery-cluster/source/model/RoutingControl.cpp
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/route53-recovery-cluster/model/RoutingControl.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Route53RecoveryCluster { namespace Model { RoutingControl::RoutingControl() : m_controlPanelArnHasBeenSet(false), m_controlPanelNameHasBeenSet(false), m_routingControlArnHasBeenSet(false), m_routingControlNameHasBeenSet(false), m_routingControlState(RoutingControlState::NOT_SET), m_routingControlStateHasBeenSet(false) { } RoutingControl::RoutingControl(JsonView jsonValue) : m_controlPanelArnHasBeenSet(false), m_controlPanelNameHasBeenSet(false), m_routingControlArnHasBeenSet(false), m_routingControlNameHasBeenSet(false), m_routingControlState(RoutingControlState::NOT_SET), m_routingControlStateHasBeenSet(false) { *this = jsonValue; } RoutingControl& RoutingControl::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("ControlPanelArn")) { m_controlPanelArn = jsonValue.GetString("ControlPanelArn"); m_controlPanelArnHasBeenSet = true; } if(jsonValue.ValueExists("ControlPanelName")) { m_controlPanelName = jsonValue.GetString("ControlPanelName"); m_controlPanelNameHasBeenSet = true; } if(jsonValue.ValueExists("RoutingControlArn")) { m_routingControlArn = jsonValue.GetString("RoutingControlArn"); m_routingControlArnHasBeenSet = true; } if(jsonValue.ValueExists("RoutingControlName")) { m_routingControlName = jsonValue.GetString("RoutingControlName"); m_routingControlNameHasBeenSet = true; } if(jsonValue.ValueExists("RoutingControlState")) { m_routingControlState = RoutingControlStateMapper::GetRoutingControlStateForName(jsonValue.GetString("RoutingControlState")); m_routingControlStateHasBeenSet = true; } return *this; } JsonValue RoutingControl::Jsonize() const { JsonValue payload; if(m_controlPanelArnHasBeenSet) { payload.WithString("ControlPanelArn", m_controlPanelArn); } if(m_controlPanelNameHasBeenSet) { payload.WithString("ControlPanelName", m_controlPanelName); } if(m_routingControlArnHasBeenSet) { payload.WithString("RoutingControlArn", m_routingControlArn); } if(m_routingControlNameHasBeenSet) { payload.WithString("RoutingControlName", m_routingControlName); } if(m_routingControlStateHasBeenSet) { payload.WithString("RoutingControlState", RoutingControlStateMapper::GetNameForRoutingControlState(m_routingControlState)); } return payload; } } // namespace Model } // namespace Route53RecoveryCluster } // namespace Aws
23.157025
129
0.76838
Nexuscompute
329e9944c34e6b9ac913c2e359b7fbeca1276263
1,489
cpp
C++
CBP/CBP/UI/UIProfileEditorNode.cpp
clayne/CBPSSE
c2bd6470efe3e0dcb3df606fb693f5c66e66e4e5
[ "MIT" ]
3
2020-06-21T18:10:19.000Z
2021-02-05T21:33:18.000Z
CBP/CBP/UI/UIProfileEditorNode.cpp
clayne/CBPSSE
c2bd6470efe3e0dcb3df606fb693f5c66e66e4e5
[ "MIT" ]
2
2020-08-29T14:29:19.000Z
2020-09-10T18:40:52.000Z
CBP/CBP/UI/UIProfileEditorNode.cpp
clayne/CBPSSE
c2bd6470efe3e0dcb3df606fb693f5c66e66e4e5
[ "MIT" ]
4
2020-08-25T17:56:35.000Z
2021-11-25T09:39:47.000Z
#include "pch.h" #include "UIProfileEditorNode.h" #include "UI.h" #include "Common/Node.cpp" namespace CBP { using namespace UICommon; UIProfileEditorNode::UIProfileEditorNode( UIContext& a_parent, const char* a_name) : UICommon::UIProfileEditorBase<NodeProfile>(a_name), m_ctxParent(a_parent) { } ProfileManager<NodeProfile>& UIProfileEditorNode::GetProfileManager() const { return GlobalProfileManager::GetSingleton<NodeProfile>(); } void UIProfileEditorNode::DrawItem(NodeProfile& a_profile) { const auto& globalConfig = IConfig::GetGlobal(); DrawNodes(0, a_profile.Data()(globalConfig.ui.commonSettings.node.profile.selectedGender)); } void UIProfileEditorNode::UpdateNodeData( int, const stl::fixed_string&, const NodeProfile::base_type::mapped_type&, bool) { } void UIProfileEditorNode::RemoveNodeData( int a_handle, const stl::fixed_string& a_node) { } void UIProfileEditorNode::DrawOptions(NodeProfile& a_profile) { ImGui::Spacing(); DrawGenderSelector(); ImGui::Spacing(); } configGlobalCommon_t& UIProfileEditorNode::GetGlobalCommonConfig() const { return IConfig::GetGlobal().ui.commonSettings.node.profile; } UICommon::UIPopupQueue& UIProfileEditorNode::GetPopupQueue() const { return m_ctxParent.GetPopupQueue(); } }
22.560606
99
0.661518
clayne